@naturalcycles/nodejs-lib
Version:
Standard library for Node.js
61 lines (60 loc) • 2.3 kB
TypeScript
import type { ErrorData } from '@naturalcycles/js-lib/error';
import type { AnyObject, JWTString } from '@naturalcycles/js-lib/types';
import type { Algorithm, JwtHeader, SignOptions, VerifyOptions } from 'jsonwebtoken';
import jsonwebtoken from 'jsonwebtoken';
import type { AjvSchema, JSchema } from '../validation/ajv/jSchema.js';
export { jsonwebtoken };
export type { Algorithm, JwtHeader, SignOptions, VerifyOptions };
export interface JWTServiceCfg {
/**
* Public key is required to Verify incoming tokens.
* Optional if you only want to Decode or Sign.
*/
publicKey?: string | Buffer;
/**
* Private key is required to Sign (create) outgoing tokens.
* Optional if you only want to Decode or Verify.
*/
privateKey?: string | Buffer;
/**
* Recommended: ES256
* Keys (private/public) should be generated using proper settings
* that fit the used Algorithm.
*/
algorithm: Algorithm;
/**
* If provided - will be applied to every Sign operation.
*/
signOptions?: SignOptions;
/**
* If provided - will be applied to every Sign operation.
*/
verifyOptions?: VerifyOptions;
/**
* If set - errors thrown from this service will be extended
* with this errorData (in err.data)
*/
errorData?: ErrorData;
}
/**
* Wraps popular `jsonwebtoken` library.
* You should create one instance of JWTService for each pair of private/public key.
*
* Generate key pair like this.
* Please note that parameters should be different for different algorithms.
* For ES256 (default algo in JWTService) key should have `prime256v1` parameter:
*
* openssl ecparam -name prime256v1 -genkey -noout -out key.pem
* openssl ec -in key.pem -pubout > key.pub.pem
*/
export declare class JWTService {
cfg: JWTServiceCfg;
constructor(cfg: JWTServiceCfg);
sign<T extends AnyObject>(payload: T, schema?: JSchema<T, any> | AjvSchema<T>, opt?: SignOptions): JWTString;
verify<T extends AnyObject>(token: JWTString, schema?: JSchema<T, any> | AjvSchema<T>, opt?: VerifyOptions, publicKey?: string): T;
decode<T extends AnyObject>(token: JWTString, schema?: JSchema<T, any> | AjvSchema<T>): {
header: JwtHeader;
payload: T;
signature: string;
};
}