@dxkit-org/node-js-kit
Version:
Modern TypeScript utility library for Node.js - Network and JWT utilities for server-side JavaScript and TypeScript projects
1 lines • 23 kB
Source Map (JSON)
{"version":3,"sources":["../../src/jwt/index.ts"],"names":["assertNodeEnvironment","jsonwebtoken"],"mappings":";;;;;;;;;;AAiJA,eAAsB,UACpB,KAAA,EACuB;AACvB,EAAA,MAAM,EAAE,KAAA,EAAO,MAAA,EAAQ,OAAA,GAAU,IAAG,GAAI,KAAA;AAExC,EAAA,IAAI;AAEF,IAAAA,2BAAA,EAAsB;AAAA,WACf,KAAA,EAAO;AACd,IAAA,OAAO;AAAA,MACL,MAAA,EAAQ,OAAA;AAAA,MACR,KAAA,EAAO;AAAA,QACL,IAAA,EAAM,mBAAA;AAAA,QACN,OAAA,EAAS,0DAAA;AAAA,QACT,aAAA,EAAe;AAAA;AACjB,KACF;AAAA;AAGF,EAAA,OAAO,IAAI,OAAA,CAAsB,CAAC,OAAA,KAAY;AAC5C,IAAA,IAAI,CAAC,KAAA,IAAS,OAAO,KAAA,KAAU,QAAA,EAAU;AACvC,MAAA,OAAO,OAAA,CAAQ;AAAA,QACb,MAAA,EAAQ,OAAA;AAAA,QACR,KAAA,EAAO;AAAA,UACL,IAAA,EAAM,eAAA;AAAA,UACN,OAAA,EAAS;AAAA;AACX,OACD,CAAA;AAAA;AAGH,IAAA,IAAI,CAAC,MAAA,EAAQ;AACX,MAAA,OAAO,OAAA,CAAQ;AAAA,QACb,MAAA,EAAQ,OAAA;AAAA,QACR,KAAA,EAAO;AAAA,UACL,IAAA,EAAM,gBAAA;AAAA,UACN,OAAA,EAAS;AAAA;AACX,OACD,CAAA;AAAA;AAGH,IAAAC,6BAAA,CAAa,OAAO,KAAA,EAAO,MAAA,EAAQ,OAAA,EAAS,CAAC,KAAK,OAAA,KAAY;AAC5D,MAAA,IAAI,GAAA,EAAK;AACP,QAAA,OAAO,OAAA,CAAQ;AAAA,UACb,MAAA,EAAQ,OAAA;AAAA,UACR,KAAA,EAAO;A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hB,EAAA,MAAM,IAAI,KAAA,CAAM,CAAA,IAAA,EAAO,MAAA,CAAO,KAAA,CAAM,IAAI,CAAA,EAAA,EAAK,MAAA,CAAO,KAAA,CAAM,OAAO,CAAA,CAAE,CAAA;AACrE;AAyCO,IAAM,GAAA,GAAM;AAAA;AAAA;AAAA;AAAA;AAAA,EAKjB,MAAA,EAAQ,SAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMR,IAAA,EAAM,OAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMN,MAAA,EAAQ,SAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMR,SAAA,EAAW,YAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMX,eAAA,EAAiB;AACnB","file":"index.cjs","sourcesContent":["import { assertNodeEnvironment } from \"@dxkit-org/js-kit\"\r\nimport jsonwebtoken from \"jsonwebtoken\"\r\nimport {\r\n JwtPayload,\r\n VerifyOptions,\r\n SignOptions,\r\n Secret,\r\n SignCallback,\r\n} from \"jsonwebtoken\"\r\n\r\n/**\r\n * Type-safe error codes for JWT operations\r\n */\r\nexport type JwtErrorCode =\r\n | \"invalid_token\"\r\n | \"invalid_secret\"\r\n | \"invalid_payload\"\r\n | \"verification_failed\"\r\n | \"signing_failed\"\r\n | \"token_expired\"\r\n | \"decode_failed\"\r\n | \"environment_error\"\r\n\r\n/**\r\n * Error object for JWT operations\r\n */\r\nexport interface JwtError {\r\n code: JwtErrorCode\r\n message: string\r\n originalError?: Error\r\n}\r\n\r\n/**\r\n * Success result for JWT operations\r\n */\r\nexport interface JwtSuccessResult<T> {\r\n status: \"success\"\r\n data: T\r\n}\r\n\r\n/**\r\n * Error result for JWT operations\r\n */\r\nexport interface JwtErrorResult {\r\n status: \"error\"\r\n error: JwtError\r\n}\r\n\r\n/**\r\n * Result type for JWT operations\r\n */\r\nexport type JwtResult<T> = JwtSuccessResult<T> | JwtErrorResult\r\n\r\n/**\r\n * Generic payload type for JWT tokens\r\n */\r\nexport interface JwtTokenPayload extends JwtPayload {\r\n [key: string]: any\r\n}\r\n\r\n/**\r\n * Input parameters for JWT verification\r\n */\r\nexport interface JwtVerifyInput {\r\n /** The JWT token to verify */\r\n token: string\r\n /** The secret key or public key for verification */\r\n secret: Secret\r\n /** Additional verification options */\r\n options?: VerifyOptions\r\n}\r\n\r\n/**\r\n * Input parameters for JWT signing\r\n */\r\nexport interface JwtSignInput<\r\n T extends Record<string, any> = Record<string, any>\r\n> {\r\n /** The payload to sign */\r\n payload: T\r\n /** The secret key for signing */\r\n secret: Secret\r\n /** Additional signing options */\r\n options?: JwtSignOptions\r\n}\r\n\r\n/**\r\n * Options for JWT signing\r\n */\r\nexport interface JwtSignOptions extends Omit<SignOptions, \"expiresIn\"> {\r\n /** Token expiration time */\r\n expiresIn?: string | number\r\n /** Default expiration time if not specified in payload */\r\n defaultExpiresIn?: string | number\r\n}\r\n\r\n/**\r\n * Input parameters for JWT decoding\r\n */\r\nexport interface JwtDecodeInput {\r\n /** The JWT token to decode */\r\n token: string\r\n /** Decode options */\r\n options?: { complete?: boolean }\r\n}\r\n\r\n/**\r\n * Input parameters for JWT expiration check\r\n */\r\nexport interface JwtExpirationInput {\r\n /** The JWT token to check */\r\n token: string\r\n}\r\n\r\n/**\r\n * Verifies a JWT token and returns a result object.\r\n *\r\n * @template T - The expected payload type\r\n * @param input - Object containing token, secret, and verification options\r\n * @returns Promise that resolves to a result object with status and either data or error\r\n *\r\n * @example\r\n * ```typescript\r\n * // Basic usage\r\n * const result = await jwtVerify<{ userId: string }>({\r\n * token: 'your-jwt-token',\r\n * secret: 'your-secret'\r\n * });\r\n * if (result.status === 'success') {\r\n * console.log('User ID:', result.data.userId);\r\n * } else {\r\n * console.log('Error:', result.error.code, result.error.message);\r\n * }\r\n *\r\n * // With custom options\r\n * const result = await jwtVerify({\r\n * token: 'your-jwt-token',\r\n * secret: 'your-secret',\r\n * options: {\r\n * audience: 'my-app',\r\n * issuer: 'my-service'\r\n * }\r\n * });\r\n * ```\r\n */\r\nexport async function jwtVerify<T extends JwtTokenPayload = JwtTokenPayload>(\r\n input: JwtVerifyInput\r\n): Promise<JwtResult<T>> {\r\n const { token, secret, options = {} } = input\r\n\r\n try {\r\n // Check if running in Node.js environment\r\n assertNodeEnvironment()\r\n } catch (error) {\r\n return {\r\n status: \"error\",\r\n error: {\r\n code: \"environment_error\",\r\n message: \"JWT operations are only supported in Node.js environment\",\r\n originalError: error as Error,\r\n },\r\n }\r\n }\r\n\r\n return new Promise<JwtResult<T>>((resolve) => {\r\n if (!token || typeof token !== \"string\") {\r\n return resolve({\r\n status: \"error\",\r\n error: {\r\n code: \"invalid_token\",\r\n message: \"Invalid token: Token must be a non-empty string\",\r\n },\r\n })\r\n }\r\n\r\n if (!secret) {\r\n return resolve({\r\n status: \"error\",\r\n error: {\r\n code: \"invalid_secret\",\r\n message: \"Invalid secret: Secret is required for token verification\",\r\n },\r\n })\r\n }\r\n\r\n jsonwebtoken.verify(token, secret, options, (err, decoded) => {\r\n if (err) {\r\n return resolve({\r\n status: \"error\",\r\n error: {\r\n code: \"verification_failed\",\r\n message: `JWT verification failed: ${err.message}`,\r\n originalError: err,\r\n },\r\n })\r\n }\r\n\r\n // Ensure we have a valid payload object\r\n if (!decoded || typeof decoded === \"string\") {\r\n return resolve({\r\n status: \"error\",\r\n error: {\r\n code: \"invalid_payload\",\r\n message: \"Invalid payload: Expected object payload\",\r\n },\r\n })\r\n }\r\n\r\n resolve({\r\n status: \"success\",\r\n data: decoded as unknown as T,\r\n })\r\n })\r\n })\r\n}\r\n\r\n/**\r\n * Signs a payload and creates a JWT token.\r\n *\r\n * @template T - The payload type\r\n * @param input - Object containing payload, secret, and signing options\r\n * @returns Promise that resolves to a result object with status and either token or error\r\n *\r\n * @example\r\n * ```typescript\r\n * // Basic usage\r\n * const result = await jwtSign({\r\n * payload: { userId: '123' },\r\n * secret: 'your-secret'\r\n * });\r\n * if (result.status === 'success') {\r\n * console.log('Token:', result.data);\r\n * } else {\r\n * console.log('Error:', result.error.code, result.error.message);\r\n * }\r\n *\r\n * // With expiration\r\n * const result = await jwtSign({\r\n * payload: { userId: '123', role: 'admin' },\r\n * secret: 'your-secret',\r\n * options: { expiresIn: '1h' }\r\n * });\r\n *\r\n * // With default expiration\r\n * const result = await jwtSign({\r\n * payload: { userId: '123' },\r\n * secret: 'your-secret',\r\n * options: { defaultExpiresIn: '24h' }\r\n * });\r\n * ```\r\n */\r\nexport async function jwtSign<\r\n T extends Record<string, any> = Record<string, any>\r\n>(input: JwtSignInput<T>): Promise<JwtResult<string>> {\r\n const { payload, secret, options = {} } = input\r\n\r\n try {\r\n // Check if running in Node.js environment\r\n assertNodeEnvironment()\r\n } catch (error) {\r\n return {\r\n status: \"error\",\r\n error: {\r\n code: \"environment_error\",\r\n message: \"JWT operations are only supported in Node.js environment\",\r\n originalError: error as Error,\r\n },\r\n }\r\n }\r\n\r\n const { defaultExpiresIn, ...signOptions } = options\r\n\r\n return new Promise<JwtResult<string>>((resolve) => {\r\n if (!payload || typeof payload !== \"object\") {\r\n return resolve({\r\n status: \"error\",\r\n error: {\r\n code: \"invalid_payload\",\r\n message: \"Invalid payload: Payload must be an object\",\r\n },\r\n })\r\n }\r\n\r\n if (!secret) {\r\n return resolve({\r\n status: \"error\",\r\n error: {\r\n code: \"invalid_secret\",\r\n message: \"Invalid secret: Secret is required for token signing\",\r\n },\r\n })\r\n }\r\n\r\n // Apply default expiration if not already set\r\n const finalOptions = {\r\n ...signOptions,\r\n ...(defaultExpiresIn &&\r\n !signOptions.expiresIn && { expiresIn: defaultExpiresIn }),\r\n }\r\n\r\n jsonwebtoken.sign(\r\n payload,\r\n secret,\r\n finalOptions as SignOptions,\r\n (err, token) => {\r\n if (err) {\r\n return resolve({\r\n status: \"error\",\r\n error: {\r\n code: \"signing_failed\",\r\n message: `JWT signing failed: ${err.message}`,\r\n originalError: err,\r\n },\r\n })\r\n }\r\n\r\n if (!token) {\r\n return resolve({\r\n status: \"error\",\r\n error: {\r\n code: \"signing_failed\",\r\n message: \"JWT signing failed: No token generated\",\r\n },\r\n })\r\n }\r\n\r\n resolve({\r\n status: \"success\",\r\n data: token,\r\n })\r\n }\r\n )\r\n })\r\n}\r\n\r\n/**\r\n * Decodes a JWT token without verification and returns a result object.\r\n * Useful for inspecting token contents when verification is not required.\r\n *\r\n * @template T - The expected payload type\r\n * @param input - Object containing token and decode options\r\n * @returns The result object with status and either decoded token or error\r\n *\r\n * @example\r\n * ```typescript\r\n * const result = jwtDecode<{ userId: string }>({\r\n * token: 'your-jwt-token'\r\n * });\r\n * if (result.status === 'success') {\r\n * console.log('User ID:', result.data.userId);\r\n * console.log('Expires at:', new Date(result.data.exp * 1000));\r\n * } else {\r\n * console.log('Decode error:', result.error.code, result.error.message);\r\n * }\r\n *\r\n * // With complete option\r\n * const result = jwtDecode({\r\n * token: 'your-jwt-token',\r\n * options: { complete: true }\r\n * });\r\n * ```\r\n */\r\nexport function jwtDecode<T extends JwtTokenPayload = JwtTokenPayload>(\r\n input: JwtDecodeInput\r\n): JwtResult<T> {\r\n const { token, options = {} } = input\r\n\r\n try {\r\n if (!token || typeof token !== \"string\") {\r\n return {\r\n status: \"error\",\r\n error: {\r\n code: \"invalid_token\",\r\n message: \"Invalid token: Token must be a non-empty string\",\r\n },\r\n }\r\n }\r\n\r\n const decoded = jsonwebtoken.decode(token, options)\r\n\r\n if (!decoded) {\r\n return {\r\n status: \"error\",\r\n error: {\r\n code: \"decode_failed\",\r\n message: \"Failed to decode token: Invalid token format\",\r\n },\r\n }\r\n }\r\n\r\n return {\r\n status: \"success\",\r\n data: decoded as T,\r\n }\r\n } catch (error) {\r\n return {\r\n status: \"error\",\r\n error: {\r\n code: \"decode_failed\",\r\n message: `Failed to decode token: ${\r\n error instanceof Error ? error.message : \"Unknown error\"\r\n }`,\r\n originalError: error instanceof Error ? error : undefined,\r\n },\r\n }\r\n }\r\n}\r\n\r\n/**\r\n * Checks if a JWT token is expired without full verification and returns a result object.\r\n *\r\n * @param input - Object containing the token to check\r\n * @returns Result object with status and either boolean result or error\r\n *\r\n * @example\r\n * ```typescript\r\n * const result = jwtIsExpired({ token: 'your-jwt-token' });\r\n * if (result.status === 'success') {\r\n * if (result.data) {\r\n * console.log('Token is expired');\r\n * } else {\r\n * console.log('Token is still valid');\r\n * }\r\n * } else {\r\n * console.log('Error checking expiration:', result.error.code);\r\n * }\r\n * ```\r\n */\r\nexport function jwtIsExpired(input: JwtExpirationInput): JwtResult<boolean> {\r\n const { token } = input\r\n const decoded = jwtDecode({ token })\r\n\r\n if (decoded.status === \"error\") {\r\n return decoded\r\n }\r\n\r\n if (!decoded.data.exp) {\r\n return {\r\n status: \"error\",\r\n error: {\r\n code: \"invalid_payload\",\r\n message: \"Token does not contain expiration time (exp claim)\",\r\n },\r\n }\r\n }\r\n\r\n const currentTime = Math.floor(Date.now() / 1000)\r\n return {\r\n status: \"success\",\r\n data: decoded.data.exp < currentTime,\r\n }\r\n}\r\n\r\n/**\r\n * Gets the remaining time until token expiration in seconds and returns a result object.\r\n *\r\n * @param input - Object containing the token to check\r\n * @returns Result object with status and either remaining seconds or error\r\n *\r\n * @example\r\n * ```typescript\r\n * const result = jwtTimeUntilExpiry({ token: 'your-jwt-token' });\r\n * if (result.status === 'success') {\r\n * console.log(`Token expires in ${result.data} seconds`);\r\n * } else {\r\n * console.log('Error checking expiry time:', result.error.code);\r\n * }\r\n * ```\r\n */\r\nexport function jwtTimeUntilExpiry(\r\n input: JwtExpirationInput\r\n): JwtResult<number> {\r\n const { token } = input\r\n const decoded = jwtDecode({ token })\r\n\r\n if (decoded.status === \"error\") {\r\n return decoded\r\n }\r\n\r\n if (!decoded.data.exp) {\r\n return {\r\n status: \"error\",\r\n error: {\r\n code: \"invalid_payload\",\r\n message: \"Token does not contain expiration time (exp claim)\",\r\n },\r\n }\r\n }\r\n\r\n const currentTime = Math.floor(Date.now() / 1000)\r\n const timeLeft = decoded.data.exp - currentTime\r\n\r\n return {\r\n status: \"success\",\r\n data: timeLeft > 0 ? timeLeft : 0,\r\n }\r\n}\r\n\r\n/**\r\n * Type guard to check if a JWT result is successful\r\n *\r\n * @param result - The JWT result to check\r\n * @returns True if the result is successful\r\n *\r\n * @example\r\n * ```typescript\r\n * const result = await jwtVerify(token, secret);\r\n * if (isJwtSuccess(result)) {\r\n * // TypeScript knows result.data is available here\r\n * console.log('User ID:', result.data.userId);\r\n * }\r\n * ```\r\n */\r\nexport function isJwtSuccess<T>(\r\n result: JwtResult<T>\r\n): result is JwtSuccessResult<T> {\r\n return result.status === \"success\"\r\n}\r\n\r\n/**\r\n * Type guard to check if a JWT result is an error\r\n *\r\n * @param result - The JWT result to check\r\n * @returns True if the result is an error\r\n *\r\n * @example\r\n * ```typescript\r\n * const result = await jwtVerify(token, secret);\r\n * if (isJwtError(result)) {\r\n * // TypeScript knows result.error is available here\r\n * console.log('Error code:', result.error.code);\r\n * }\r\n * ```\r\n */\r\nexport function isJwtError<T>(result: JwtResult<T>): result is JwtErrorResult {\r\n return result.status === \"error\"\r\n}\r\n\r\n/**\r\n * Extracts data from a JWT result, throwing an error if the result is not successful\r\n *\r\n * @param result - The JWT result\r\n * @returns The data from the result\r\n * @throws Error if the result is not successful\r\n *\r\n * @example\r\n * ```typescript\r\n * try {\r\n * const result = await jwtVerify(token, secret);\r\n * const payload = unwrapJwtResult(result);\r\n * console.log('User ID:', payload.userId);\r\n * } catch (error) {\r\n * console.log('JWT error:', error.message);\r\n * }\r\n * ```\r\n */\r\nexport function unwrapJwtResult<T>(result: JwtResult<T>): T {\r\n if (result.status === \"success\") {\r\n return result.data\r\n }\r\n throw new Error(`JWT ${result.error.code}: ${result.error.message}`)\r\n}\r\n\r\n/**\r\n * JWT utility namespace providing a convenient API for JWT operations.\r\n * All methods take input as objects and return result objects with status 'success' or 'error'.\r\n *\r\n * @example\r\n * ```typescript\r\n * import { jwt } from 'advanced-js-kit/jwt/jwt';\r\n *\r\n * // Verify a token\r\n * const result = await jwt.verify({\r\n * token: 'your-jwt-token',\r\n * secret: 'your-secret'\r\n * });\r\n * if (result.status === 'success') {\r\n * console.log('Payload:', result.data);\r\n * } else {\r\n * console.log('Error:', result.error.code, result.error.message);\r\n * }\r\n *\r\n * // Sign a token\r\n * const signResult = await jwt.sign({\r\n * payload: { userId: '123' },\r\n * secret: 'your-secret'\r\n * });\r\n * if (signResult.status === 'success') {\r\n * console.log('Token:', signResult.data);\r\n * }\r\n *\r\n * // Decode a token\r\n * const decodeResult = jwt.decode({\r\n * token: 'your-jwt-token'\r\n * });\r\n *\r\n * // Check expiration\r\n * const expiredResult = jwt.isExpired({\r\n * token: 'your-jwt-token'\r\n * });\r\n * ```\r\n */\r\nexport const jwt = {\r\n /**\r\n * Verifies a JWT token and returns a result object.\r\n * Alias for jwtVerify function.\r\n */\r\n verify: jwtVerify,\r\n\r\n /**\r\n * Signs a payload and creates a JWT token, returns a result object.\r\n * Alias for jwtSign function.\r\n */\r\n sign: jwtSign,\r\n\r\n /**\r\n * Decodes a JWT token without verification, returns a result object.\r\n * Alias for jwtDecode function.\r\n */\r\n decode: jwtDecode,\r\n\r\n /**\r\n * Checks if a JWT token is expired, returns a result object.\r\n * Alias for jwtIsExpired function.\r\n */\r\n isExpired: jwtIsExpired,\r\n\r\n /**\r\n * Gets the remaining time until token expiration, returns a result object.\r\n * Alias for jwtTimeUntilExpiry function.\r\n */\r\n timeUntilExpiry: jwtTimeUntilExpiry,\r\n} as const\r\n"]}