advanced-js-kit
Version:
Modern TypeScript utility library with tree-shaking support - Array, String, Number, Network, Sleep, and JWT utilities for JavaScript and TypeScript projects
287 lines (283 loc) • 7.55 kB
JavaScript
import jsonwebtoken from 'jsonwebtoken';
// src/node/jwt/index.ts
// src/universal/utils/index.ts
function isNodeEnvironment() {
return typeof process !== "undefined" && process.versions != null && process.versions.node != null;
}
function isBrowserEnvironment() {
return typeof window !== "undefined" && typeof document !== "undefined";
}
function isWebWorkerEnvironment() {
return typeof globalThis.importScripts === "function" && typeof window === "undefined";
}
function getEnvironment() {
if (isNodeEnvironment()) return "node";
if (isBrowserEnvironment()) return "browser";
if (isWebWorkerEnvironment()) return "webworker";
return "unknown";
}
var EnvironmentError = class extends Error {
constructor(message, requiredEnvironment, currentEnvironment) {
super(message);
this.requiredEnvironment = requiredEnvironment;
this.currentEnvironment = currentEnvironment;
this.name = "EnvironmentError";
}
};
function assertNodeEnvironment() {
if (!isNodeEnvironment()) {
throw new EnvironmentError(
"This functionality requires Node.js environment",
"node",
getEnvironment()
);
}
}
// src/node/jwt/index.ts
async function jwtVerify(input) {
const { token, secret, options = {} } = input;
try {
assertNodeEnvironment();
} catch (error) {
return {
status: "error",
error: {
code: "environment_error",
message: "JWT operations are only supported in Node.js environment",
originalError: error
}
};
}
return new Promise((resolve) => {
if (!token || typeof token !== "string") {
return resolve({
status: "error",
error: {
code: "invalid_token",
message: "Invalid token: Token must be a non-empty string"
}
});
}
if (!secret) {
return resolve({
status: "error",
error: {
code: "invalid_secret",
message: "Invalid secret: Secret is required for token verification"
}
});
}
jsonwebtoken.verify(token, secret, options, (err, decoded) => {
if (err) {
return resolve({
status: "error",
error: {
code: "verification_failed",
message: `JWT verification failed: ${err.message}`,
originalError: err
}
});
}
if (!decoded || typeof decoded === "string") {
return resolve({
status: "error",
error: {
code: "invalid_payload",
message: "Invalid payload: Expected object payload"
}
});
}
resolve({
status: "success",
data: decoded
});
});
});
}
async function jwtSign(input) {
const { payload, secret, options = {} } = input;
try {
assertNodeEnvironment();
} catch (error) {
return {
status: "error",
error: {
code: "environment_error",
message: "JWT operations are only supported in Node.js environment",
originalError: error
}
};
}
const { defaultExpiresIn, ...signOptions } = options;
return new Promise((resolve) => {
if (!payload || typeof payload !== "object") {
return resolve({
status: "error",
error: {
code: "invalid_payload",
message: "Invalid payload: Payload must be an object"
}
});
}
if (!secret) {
return resolve({
status: "error",
error: {
code: "invalid_secret",
message: "Invalid secret: Secret is required for token signing"
}
});
}
const finalOptions = {
...signOptions,
...defaultExpiresIn && !signOptions.expiresIn && { expiresIn: defaultExpiresIn }
};
jsonwebtoken.sign(payload, secret, finalOptions, (err, token) => {
if (err) {
return resolve({
status: "error",
error: {
code: "signing_failed",
message: `JWT signing failed: ${err.message}`,
originalError: err
}
});
}
if (!token) {
return resolve({
status: "error",
error: {
code: "signing_failed",
message: "JWT signing failed: No token generated"
}
});
}
resolve({
status: "success",
data: token
});
});
});
}
function jwtDecode(input) {
const { token, options = {} } = input;
try {
if (!token || typeof token !== "string") {
return {
status: "error",
error: {
code: "invalid_token",
message: "Invalid token: Token must be a non-empty string"
}
};
}
const decoded = jsonwebtoken.decode(token, options);
if (!decoded) {
return {
status: "error",
error: {
code: "decode_failed",
message: "Failed to decode token: Invalid token format"
}
};
}
return {
status: "success",
data: decoded
};
} catch (error) {
return {
status: "error",
error: {
code: "decode_failed",
message: `Failed to decode token: ${error instanceof Error ? error.message : "Unknown error"}`,
originalError: error instanceof Error ? error : void 0
}
};
}
}
function jwtIsExpired(input) {
const { token } = input;
const decoded = jwtDecode({ token });
if (decoded.status === "error") {
return decoded;
}
if (!decoded.data.exp) {
return {
status: "error",
error: {
code: "invalid_payload",
message: "Token does not contain expiration time (exp claim)"
}
};
}
const currentTime = Math.floor(Date.now() / 1e3);
return {
status: "success",
data: decoded.data.exp < currentTime
};
}
function jwtTimeUntilExpiry(input) {
const { token } = input;
const decoded = jwtDecode({ token });
if (decoded.status === "error") {
return decoded;
}
if (!decoded.data.exp) {
return {
status: "error",
error: {
code: "invalid_payload",
message: "Token does not contain expiration time (exp claim)"
}
};
}
const currentTime = Math.floor(Date.now() / 1e3);
const timeLeft = decoded.data.exp - currentTime;
return {
status: "success",
data: timeLeft > 0 ? timeLeft : 0
};
}
function isJwtSuccess(result) {
return result.status === "success";
}
function isJwtError(result) {
return result.status === "error";
}
function unwrapJwtResult(result) {
if (result.status === "success") {
return result.data;
}
throw new Error(`JWT ${result.error.code}: ${result.error.message}`);
}
var jwt = {
/**
* Verifies a JWT token and returns a result object.
* Alias for jwtVerify function.
*/
verify: jwtVerify,
/**
* Signs a payload and creates a JWT token, returns a result object.
* Alias for jwtSign function.
*/
sign: jwtSign,
/**
* Decodes a JWT token without verification, returns a result object.
* Alias for jwtDecode function.
*/
decode: jwtDecode,
/**
* Checks if a JWT token is expired, returns a result object.
* Alias for jwtIsExpired function.
*/
isExpired: jwtIsExpired,
/**
* Gets the remaining time until token expiration, returns a result object.
* Alias for jwtTimeUntilExpiry function.
*/
timeUntilExpiry: jwtTimeUntilExpiry
};
export { isJwtError, isJwtSuccess, jwt, jwtDecode, jwtIsExpired, jwtSign, jwtTimeUntilExpiry, jwtVerify, unwrapJwtResult };
//# sourceMappingURL=index.js.map
//# sourceMappingURL=index.js.map