UNPKG

1.93 kBTypeScriptView Raw
1/// <reference types="node" />
2import { AnyObject, ErrorData, JWTString } from '@naturalcycles/js-lib';
3import type { Algorithm, VerifyOptions, JwtHeader, SignOptions } from 'jsonwebtoken';
4import * as jsonwebtoken from 'jsonwebtoken';
5import { AnySchemaTyped } from '../validation/joi/joi.model';
6export { jsonwebtoken };
7export type { Algorithm, VerifyOptions, SignOptions, JwtHeader };
8export interface JWTServiceCfg {
9 /**
10 * Public key is required to Verify incoming tokens.
11 * Optional if you only want to Decode or Sign.
12 */
13 publicKey?: string | Buffer;
14 /**
15 * Private key is required to Sign (create) outgoing tokens.
16 * Optional if you only want to Decode or Verify.
17 */
18 privateKey?: string | Buffer;
19 /**
20 * Recommended: ES256
21 */
22 algorithm: Algorithm;
23 /**
24 * If provided - will be applied to every Sign operation.
25 */
26 signOptions?: SignOptions;
27 /**
28 * If provided - will be applied to every Sign operation.
29 */
30 verifyOptions?: VerifyOptions;
31 /**
32 * If set - errors thrown from this service will be extended
33 * with this errorData (in err.data)
34 */
35 errorData?: ErrorData;
36}
37/**
38 * Wraps popular `jsonwebtoken` library.
39 * You should create one instance of JWTService for each pair of private/public key.
40 *
41 * Generate key pair like this:
42 * openssl ecparam -name secp256k1 -genkey -noout -out key.pem
43 * openssl ec -in key.pem -pubout > key.pub.pem
44 */
45export declare class JWTService {
46 cfg: JWTServiceCfg;
47 constructor(cfg: JWTServiceCfg);
48 sign<T extends AnyObject>(payload: T, schema?: AnySchemaTyped<T>, opt?: SignOptions): JWTString;
49 verify<T extends AnyObject>(token: JWTString, schema?: AnySchemaTyped<T>, opt?: VerifyOptions): T;
50 decode<T extends AnyObject>(token: JWTString, schema?: AnySchemaTyped<T>): {
51 header: JwtHeader;
52 payload: T;
53 signature: string;
54 };
55}