@dxkit-org/node-js-kit
Version:
Modern TypeScript utility library for Node.js - Network and JWT utilities for server-side JavaScript and TypeScript projects
341 lines (338 loc) • 9.98 kB
TypeScript
import { JwtPayload, Secret, VerifyOptions, SignOptions } from 'jsonwebtoken';
/**
* Type-safe error codes for JWT operations
*/
type JwtErrorCode = "invalid_token" | "invalid_secret" | "invalid_payload" | "verification_failed" | "signing_failed" | "token_expired" | "decode_failed" | "environment_error";
/**
* Error object for JWT operations
*/
interface JwtError {
code: JwtErrorCode;
message: string;
originalError?: Error;
}
/**
* Success result for JWT operations
*/
interface JwtSuccessResult<T> {
status: "success";
data: T;
}
/**
* Error result for JWT operations
*/
interface JwtErrorResult {
status: "error";
error: JwtError;
}
/**
* Result type for JWT operations
*/
type JwtResult<T> = JwtSuccessResult<T> | JwtErrorResult;
/**
* Generic payload type for JWT tokens
*/
interface JwtTokenPayload extends JwtPayload {
[key: string]: any;
}
/**
* Input parameters for JWT verification
*/
interface JwtVerifyInput {
/** The JWT token to verify */
token: string;
/** The secret key or public key for verification */
secret: Secret;
/** Additional verification options */
options?: VerifyOptions;
}
/**
* Input parameters for JWT signing
*/
interface JwtSignInput<T extends Record<string, any> = Record<string, any>> {
/** The payload to sign */
payload: T;
/** The secret key for signing */
secret: Secret;
/** Additional signing options */
options?: JwtSignOptions;
}
/**
* Options for JWT signing
*/
interface JwtSignOptions extends Omit<SignOptions, "expiresIn"> {
/** Token expiration time */
expiresIn?: string | number;
/** Default expiration time if not specified in payload */
defaultExpiresIn?: string | number;
}
/**
* Input parameters for JWT decoding
*/
interface JwtDecodeInput {
/** The JWT token to decode */
token: string;
/** Decode options */
options?: {
complete?: boolean;
};
}
/**
* Input parameters for JWT expiration check
*/
interface JwtExpirationInput {
/** The JWT token to check */
token: string;
}
/**
* Verifies a JWT token and returns a result object.
*
* @template T - The expected payload type
* @param input - Object containing token, secret, and verification options
* @returns Promise that resolves to a result object with status and either data or error
*
* @example
* ```typescript
* // Basic usage
* const result = await jwtVerify<{ userId: string }>({
* token: 'your-jwt-token',
* secret: 'your-secret'
* });
* if (result.status === 'success') {
* console.log('User ID:', result.data.userId);
* } else {
* console.log('Error:', result.error.code, result.error.message);
* }
*
* // With custom options
* const result = await jwtVerify({
* token: 'your-jwt-token',
* secret: 'your-secret',
* options: {
* audience: 'my-app',
* issuer: 'my-service'
* }
* });
* ```
*/
declare function jwtVerify<T extends JwtTokenPayload = JwtTokenPayload>(input: JwtVerifyInput): Promise<JwtResult<T>>;
/**
* Signs a payload and creates a JWT token.
*
* @template T - The payload type
* @param input - Object containing payload, secret, and signing options
* @returns Promise that resolves to a result object with status and either token or error
*
* @example
* ```typescript
* // Basic usage
* const result = await jwtSign({
* payload: { userId: '123' },
* secret: 'your-secret'
* });
* if (result.status === 'success') {
* console.log('Token:', result.data);
* } else {
* console.log('Error:', result.error.code, result.error.message);
* }
*
* // With expiration
* const result = await jwtSign({
* payload: { userId: '123', role: 'admin' },
* secret: 'your-secret',
* options: { expiresIn: '1h' }
* });
*
* // With default expiration
* const result = await jwtSign({
* payload: { userId: '123' },
* secret: 'your-secret',
* options: { defaultExpiresIn: '24h' }
* });
* ```
*/
declare function jwtSign<T extends Record<string, any> = Record<string, any>>(input: JwtSignInput<T>): Promise<JwtResult<string>>;
/**
* Decodes a JWT token without verification and returns a result object.
* Useful for inspecting token contents when verification is not required.
*
* @template T - The expected payload type
* @param input - Object containing token and decode options
* @returns The result object with status and either decoded token or error
*
* @example
* ```typescript
* const result = jwtDecode<{ userId: string }>({
* token: 'your-jwt-token'
* });
* if (result.status === 'success') {
* console.log('User ID:', result.data.userId);
* console.log('Expires at:', new Date(result.data.exp * 1000));
* } else {
* console.log('Decode error:', result.error.code, result.error.message);
* }
*
* // With complete option
* const result = jwtDecode({
* token: 'your-jwt-token',
* options: { complete: true }
* });
* ```
*/
declare function jwtDecode<T extends JwtTokenPayload = JwtTokenPayload>(input: JwtDecodeInput): JwtResult<T>;
/**
* Checks if a JWT token is expired without full verification and returns a result object.
*
* @param input - Object containing the token to check
* @returns Result object with status and either boolean result or error
*
* @example
* ```typescript
* const result = jwtIsExpired({ token: 'your-jwt-token' });
* if (result.status === 'success') {
* if (result.data) {
* console.log('Token is expired');
* } else {
* console.log('Token is still valid');
* }
* } else {
* console.log('Error checking expiration:', result.error.code);
* }
* ```
*/
declare function jwtIsExpired(input: JwtExpirationInput): JwtResult<boolean>;
/**
* Gets the remaining time until token expiration in seconds and returns a result object.
*
* @param input - Object containing the token to check
* @returns Result object with status and either remaining seconds or error
*
* @example
* ```typescript
* const result = jwtTimeUntilExpiry({ token: 'your-jwt-token' });
* if (result.status === 'success') {
* console.log(`Token expires in ${result.data} seconds`);
* } else {
* console.log('Error checking expiry time:', result.error.code);
* }
* ```
*/
declare function jwtTimeUntilExpiry(input: JwtExpirationInput): JwtResult<number>;
/**
* Type guard to check if a JWT result is successful
*
* @param result - The JWT result to check
* @returns True if the result is successful
*
* @example
* ```typescript
* const result = await jwtVerify(token, secret);
* if (isJwtSuccess(result)) {
* // TypeScript knows result.data is available here
* console.log('User ID:', result.data.userId);
* }
* ```
*/
declare function isJwtSuccess<T>(result: JwtResult<T>): result is JwtSuccessResult<T>;
/**
* Type guard to check if a JWT result is an error
*
* @param result - The JWT result to check
* @returns True if the result is an error
*
* @example
* ```typescript
* const result = await jwtVerify(token, secret);
* if (isJwtError(result)) {
* // TypeScript knows result.error is available here
* console.log('Error code:', result.error.code);
* }
* ```
*/
declare function isJwtError<T>(result: JwtResult<T>): result is JwtErrorResult;
/**
* Extracts data from a JWT result, throwing an error if the result is not successful
*
* @param result - The JWT result
* @returns The data from the result
* @throws Error if the result is not successful
*
* @example
* ```typescript
* try {
* const result = await jwtVerify(token, secret);
* const payload = unwrapJwtResult(result);
* console.log('User ID:', payload.userId);
* } catch (error) {
* console.log('JWT error:', error.message);
* }
* ```
*/
declare function unwrapJwtResult<T>(result: JwtResult<T>): T;
/**
* JWT utility namespace providing a convenient API for JWT operations.
* All methods take input as objects and return result objects with status 'success' or 'error'.
*
* @example
* ```typescript
* import { jwt } from 'advanced-js-kit/jwt/jwt';
*
* // Verify a token
* const result = await jwt.verify({
* token: 'your-jwt-token',
* secret: 'your-secret'
* });
* if (result.status === 'success') {
* console.log('Payload:', result.data);
* } else {
* console.log('Error:', result.error.code, result.error.message);
* }
*
* // Sign a token
* const signResult = await jwt.sign({
* payload: { userId: '123' },
* secret: 'your-secret'
* });
* if (signResult.status === 'success') {
* console.log('Token:', signResult.data);
* }
*
* // Decode a token
* const decodeResult = jwt.decode({
* token: 'your-jwt-token'
* });
*
* // Check expiration
* const expiredResult = jwt.isExpired({
* token: 'your-jwt-token'
* });
* ```
*/
declare const jwt: {
/**
* Verifies a JWT token and returns a result object.
* Alias for jwtVerify function.
*/
readonly verify: typeof jwtVerify;
/**
* Signs a payload and creates a JWT token, returns a result object.
* Alias for jwtSign function.
*/
readonly sign: typeof jwtSign;
/**
* Decodes a JWT token without verification, returns a result object.
* Alias for jwtDecode function.
*/
readonly decode: typeof jwtDecode;
/**
* Checks if a JWT token is expired, returns a result object.
* Alias for jwtIsExpired function.
*/
readonly isExpired: typeof jwtIsExpired;
/**
* Gets the remaining time until token expiration, returns a result object.
* Alias for jwtTimeUntilExpiry function.
*/
readonly timeUntilExpiry: typeof jwtTimeUntilExpiry;
};
export { type JwtDecodeInput, type JwtError, type JwtErrorCode, type JwtErrorResult, type JwtExpirationInput, type JwtResult, type JwtSignInput, type JwtSignOptions, type JwtSuccessResult, type JwtTokenPayload, type JwtVerifyInput, isJwtError, isJwtSuccess, jwt, jwtDecode, jwtIsExpired, jwtSign, jwtTimeUntilExpiry, jwtVerify, unwrapJwtResult };