@celljs/jwt 4.1.0 → 4.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/README.md +16 -1
  2. package/esm/node/errors.d.ts +13 -0
  3. package/esm/node/errors.js +19 -0
  4. package/esm/node/errors.js.map +1 -1
  5. package/esm/node/index.d.ts +1 -0
  6. package/esm/node/index.js +1 -0
  7. package/esm/node/index.js.map +1 -1
  8. package/esm/node/jwt-protocol.d.ts +69 -13
  9. package/esm/node/jwt-service.js +5 -26
  10. package/esm/node/jwt-service.js.map +1 -1
  11. package/esm/node/jwt-util.d.ts +13 -0
  12. package/esm/node/jwt-util.js +304 -0
  13. package/esm/node/jwt-util.js.map +1 -0
  14. package/esm/node/module.d.ts +1 -1
  15. package/lib/node/errors.d.ts +13 -0
  16. package/lib/node/errors.d.ts.map +1 -1
  17. package/lib/node/errors.js +23 -1
  18. package/lib/node/errors.js.map +1 -1
  19. package/lib/node/index.d.ts +1 -0
  20. package/lib/node/index.d.ts.map +1 -1
  21. package/lib/node/index.js +1 -0
  22. package/lib/node/index.js.map +1 -1
  23. package/lib/node/jwt-protocol.d.ts +69 -13
  24. package/lib/node/jwt-protocol.d.ts.map +1 -1
  25. package/lib/node/jwt-service.d.ts.map +1 -1
  26. package/lib/node/jwt-service.js +5 -29
  27. package/lib/node/jwt-service.js.map +1 -1
  28. package/lib/node/jwt-util.d.ts +14 -0
  29. package/lib/node/jwt-util.d.ts.map +1 -0
  30. package/lib/node/jwt-util.js +307 -0
  31. package/lib/node/jwt-util.js.map +1 -0
  32. package/lib/node/jwt-util.spec.d.ts +2 -0
  33. package/lib/node/jwt-util.spec.d.ts.map +1 -0
  34. package/lib/node/jwt-util.spec.js +114 -0
  35. package/lib/node/jwt-util.spec.js.map +1 -0
  36. package/lib/node/module.d.ts +1 -1
  37. package/package.json +5 -4
  38. package/src/node/errors.ts +19 -0
  39. package/src/node/index.ts +1 -0
  40. package/src/node/jwt-protocol.ts +78 -13
  41. package/src/node/jwt-service.ts +4 -24
  42. package/src/node/jwt-util.spec.ts +125 -0
  43. package/src/node/jwt-util.ts +308 -0
@@ -0,0 +1,114 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const bun_test_1 = require("bun:test");
4
+ const chai_1 = require("chai");
5
+ const node_crypto_1 = require("node:crypto");
6
+ const jwt_util_1 = require("./jwt-util");
7
+ const errors_1 = require("./errors");
8
+ function pem(key, type) {
9
+ return key.export({ type, format: 'pem' }).toString();
10
+ }
11
+ function keyPair(type, options) {
12
+ const { publicKey, privateKey } = (0, node_crypto_1.generateKeyPairSync)(type, options);
13
+ return { publicKey: pem(publicKey, 'spki'), privateKey: pem(privateKey, 'pkcs8') };
14
+ }
15
+ const rsa = keyPair('rsa', { modulusLength: 2048 });
16
+ const ec = keyPair('ec', { namedCurve: 'prime256v1' });
17
+ function error(fn) {
18
+ try {
19
+ fn();
20
+ }
21
+ catch (e) {
22
+ return e;
23
+ }
24
+ throw new Error('did not throw');
25
+ }
26
+ (0, bun_test_1.describe)('JwtUtil', () => {
27
+ // Made by jsonwebtoken 9.0.3: tokens stay the same, byte for byte.
28
+ (0, bun_test_1.it)('signs HMAC tokens as jsonwebtoken did', () => {
29
+ (0, chai_1.expect)(jwt_util_1.JwtUtil.sign({ sub: 'u', iat: 1700000000 }, 'secret', { algorithm: 'HS256' })).to.equal('eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1IiwiaWF0IjoxNzAwMDAwMDAwfQ.XnL_w7HK3br5amJH_8ubcBdNxqsRVENLSiGZi5_2j3k');
30
+ (0, chai_1.expect)(jwt_util_1.JwtUtil.sign({ sub: 'u', iat: 1700000000, exp: 1700003600 }, 'secret', { algorithm: 'HS512', header: { kid: 'k1' } })).to.equal('eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCIsImtpZCI6ImsxIn0.eyJzdWIiOiJ1IiwiaWF0IjoxNzAwMDAwMDAwLCJleHAiOjE3MDAwMDM2MDB9.2ijjBEf4LTfiz7ILrRzd2_norxKXM7r3VJX6fAKVnJdn_0PBFugckJObZ5EX_PXNnJO9pJal2T-E5kG8qS5YkA');
31
+ });
32
+ (0, bun_test_1.it)('verifies what it signs, with every algorithm', () => {
33
+ const keys = [
34
+ ['HS256', 's', 's'], ['HS384', 's', 's'], ['HS512', 's', 's'],
35
+ ['RS256', rsa.privateKey, rsa.publicKey], ['RS512', rsa.privateKey, rsa.publicKey],
36
+ ['PS256', rsa.privateKey, rsa.publicKey], ['ES256', ec.privateKey, ec.publicKey]
37
+ ];
38
+ for (const [algorithm, privateKey, publicKey] of keys) {
39
+ const token = jwt_util_1.JwtUtil.sign({ x: 1 }, privateKey, { algorithm, expiresIn: '1h', audience: 'app', issuer: 'me', subject: 'u', keyid: 'k' });
40
+ const { header, payload } = jwt_util_1.JwtUtil.verify(token, publicKey, { audience: 'app', issuer: 'me', subject: 'u', complete: true });
41
+ (0, chai_1.expect)(header).to.deep.equal({ alg: algorithm, typ: 'JWT', kid: 'k' });
42
+ (0, chai_1.expect)(payload).to.include({ x: 1, aud: 'app', iss: 'me', sub: 'u' });
43
+ (0, chai_1.expect)(payload.exp - payload.iat).to.equal(3600);
44
+ }
45
+ });
46
+ (0, bun_test_1.it)('turns time spans into claims', () => {
47
+ const token = jwt_util_1.JwtUtil.sign({ iat: 1700000000 }, 's', { expiresIn: '2 days', notBefore: '10m' });
48
+ (0, chai_1.expect)(jwt_util_1.JwtUtil.decode(token)).to.deep.equal({ iat: 1700000000, nbf: 1700000600, exp: 1700172800 });
49
+ (0, chai_1.expect)(jwt_util_1.JwtUtil.decode(jwt_util_1.JwtUtil.sign({}, 's', { noTimestamp: true, expiresIn: 60 }))).to.not.have.property('iat');
50
+ });
51
+ (0, bun_test_1.it)('refuses expired, early, forged and mismatched tokens', () => {
52
+ (0, chai_1.expect)(error(() => jwt_util_1.JwtUtil.verify(jwt_util_1.JwtUtil.sign({ exp: 1 }, 's'), 's'))).to.be.instanceOf(errors_1.TokenExpiredError).and.have.property('message', 'jwt expired');
53
+ (0, chai_1.expect)(jwt_util_1.JwtUtil.verify(jwt_util_1.JwtUtil.sign({ exp: 1 }, 's'), 's', { ignoreExpiration: true })).to.include({ exp: 1 });
54
+ (0, chai_1.expect)(error(() => jwt_util_1.JwtUtil.verify(jwt_util_1.JwtUtil.sign({ nbf: 9999999999 }, 's'), 's'))).to.be.instanceOf(errors_1.NotBeforeError);
55
+ (0, chai_1.expect)(error(() => jwt_util_1.JwtUtil.verify(jwt_util_1.JwtUtil.sign({}, 's'), 'other')).message).to.equal('invalid signature');
56
+ (0, chai_1.expect)(error(() => jwt_util_1.JwtUtil.verify('a.b', 's')).message).to.equal('jwt malformed');
57
+ (0, chai_1.expect)(error(() => jwt_util_1.JwtUtil.verify(jwt_util_1.JwtUtil.sign({}, 's', { algorithm: 'HS512' }), 's', { algorithms: ['HS256'] })).message).to.equal('invalid algorithm');
58
+ (0, chai_1.expect)(error(() => jwt_util_1.JwtUtil.verify(jwt_util_1.JwtUtil.sign({}, 's'), rsa.publicKey)).message).to.equal('invalid algorithm');
59
+ (0, chai_1.expect)(error(() => jwt_util_1.JwtUtil.verify(jwt_util_1.JwtUtil.sign({ aud: 'x' }, 's'), 's', { audience: ['y', /z/] })).message).to.equal('jwt audience invalid. expected: y or /z/');
60
+ (0, chai_1.expect)(jwt_util_1.JwtUtil.verify(jwt_util_1.JwtUtil.sign({ aud: ['a', 'zz'] }, 's'), 's', { audience: /z/ })).to.have.property('aud');
61
+ (0, chai_1.expect)(error(() => jwt_util_1.JwtUtil.verify(jwt_util_1.JwtUtil.sign({ iat: 100 }, 's'), 's', { maxAge: '1h' })).message).to.equal('maxAge exceeded');
62
+ (0, chai_1.expect)(error(() => jwt_util_1.JwtUtil.verify(jwt_util_1.JwtUtil.sign({}, 's'), 's', { nonce: '' })).message).to.equal('nonce must be a non-empty string');
63
+ (0, chai_1.expect)(jwt_util_1.JwtUtil.verify(jwt_util_1.JwtUtil.sign({ a: 1 }, 's'), 's')).to.include({ a: 1 });
64
+ });
65
+ (0, bun_test_1.it)('accepts unsigned tokens only when "none" is listed', () => {
66
+ const none = jwt_util_1.JwtUtil.sign({ a: 1 }, undefined, { algorithm: 'none' });
67
+ (0, chai_1.expect)(none.endsWith('.')).to.equal(true);
68
+ (0, chai_1.expect)(error(() => jwt_util_1.JwtUtil.verify(none, 's')).message).to.equal('jwt signature is required');
69
+ (0, chai_1.expect)(error(() => jwt_util_1.JwtUtil.verify(none, undefined)).message).to.equal('please specify "none" in "algorithms" to verify unsigned tokens');
70
+ (0, chai_1.expect)(jwt_util_1.JwtUtil.verify(none, undefined, { algorithms: ['none'] })).to.include({ a: 1 });
71
+ });
72
+ (0, bun_test_1.it)('checks that the key fits the algorithm', () => {
73
+ (0, chai_1.expect)(error(() => jwt_util_1.JwtUtil.sign({}, 's', { algorithm: 'RS256' })).message).to.equal('secretOrPrivateKey must be an asymmetric key when using RS256');
74
+ (0, chai_1.expect)(error(() => jwt_util_1.JwtUtil.sign({}, rsa.privateKey)).message).to.equal('secretOrPrivateKey must be a symmetric key when using HS256');
75
+ (0, chai_1.expect)(error(() => jwt_util_1.JwtUtil.sign({}, ec.privateKey, { algorithm: 'ES384' })).message).to.equal('"alg" parameter "ES384" requires curve "secp384r1".');
76
+ const small = keyPair('rsa', { modulusLength: 1024 });
77
+ (0, chai_1.expect)(error(() => jwt_util_1.JwtUtil.sign({}, small.privateKey, { algorithm: 'RS256' })).message).to.equal('secretOrPrivateKey has a minimum key size of 2048 bits for RS256');
78
+ (0, chai_1.expect)(jwt_util_1.JwtUtil.sign({}, small.privateKey, { algorithm: 'RS256', allowInsecureKeySizes: true })).to.be.a('string');
79
+ });
80
+ // Failing to parse a secret as a PEM key took 0.2 ms per token with the OpenSSL 3.0 of Node.js 20.
81
+ (0, bun_test_1.it)('uses a secret without a PEM header as an HMAC key without parsing it', () => {
82
+ const crypto = require('crypto');
83
+ const { createPublicKey, createPrivateKey } = crypto;
84
+ let parsed = 0;
85
+ crypto.createPublicKey = (...args) => { parsed++; return createPublicKey(...args); };
86
+ crypto.createPrivateKey = (...args) => { parsed++; return createPrivateKey(...args); };
87
+ try {
88
+ for (const secret of ['s', Buffer.from('s')]) {
89
+ (0, chai_1.expect)(jwt_util_1.JwtUtil.verify(jwt_util_1.JwtUtil.sign({ x: 1 }, secret), secret)).to.include({ x: 1 });
90
+ }
91
+ (0, chai_1.expect)(parsed).to.equal(0);
92
+ const token = jwt_util_1.JwtUtil.sign({ x: 1 }, Buffer.from(rsa.privateKey), { algorithm: 'RS256' });
93
+ (0, chai_1.expect)(jwt_util_1.JwtUtil.verify(token, Buffer.from(rsa.publicKey))).to.include({ x: 1 });
94
+ (0, chai_1.expect)(parsed).to.equal(2);
95
+ }
96
+ finally {
97
+ Object.assign(crypto, { createPublicKey, createPrivateKey });
98
+ }
99
+ });
100
+ (0, bun_test_1.it)('keeps payloads and options apart', () => {
101
+ (0, chai_1.expect)(error(() => jwt_util_1.JwtUtil.sign({ exp: 5 }, 's', { expiresIn: 10 })).message).to.equal('Bad "options.expiresIn" option the payload already has an "exp" property.');
102
+ (0, chai_1.expect)(error(() => jwt_util_1.JwtUtil.sign('text', 's', { expiresIn: 10 })).message).to.equal('invalid expiresIn option for string payload');
103
+ (0, chai_1.expect)(jwt_util_1.JwtUtil.verify(jwt_util_1.JwtUtil.sign('text', 's'), 's')).to.equal('text');
104
+ (0, chai_1.expect)(error(() => jwt_util_1.JwtUtil.sign({}, 's', { expiresIn: 'soon' }))).to.be.instanceOf(Error);
105
+ });
106
+ (0, bun_test_1.it)('decodes without verifying', () => {
107
+ const token = jwt_util_1.JwtUtil.sign({ a: 1, iat: 1 }, 's');
108
+ (0, chai_1.expect)(jwt_util_1.JwtUtil.decode(token)).to.deep.equal({ a: 1, iat: 1 });
109
+ (0, chai_1.expect)(jwt_util_1.JwtUtil.decode(token, { complete: true })).to.deep.include({ header: { alg: 'HS256', typ: 'JWT' } });
110
+ (0, chai_1.expect)(jwt_util_1.JwtUtil.decode('nonsense')).to.equal(null);
111
+ (0, chai_1.expect)(error(() => jwt_util_1.JwtUtil.verify('a.b.c', 's'))).to.be.instanceOf(errors_1.JsonWebTokenError);
112
+ });
113
+ });
114
+ //# sourceMappingURL=jwt-util.spec.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"jwt-util.spec.js","sourceRoot":"","sources":["../../src/node/jwt-util.spec.ts"],"names":[],"mappings":";;AAAA,uCAAwC;AACxC,+BAA8B;AAC9B,6CAAkD;AAClD,yCAAqC;AACrC,qCAAgF;AAGhF,SAAS,GAAG,CAAC,GAAoF,EAAE,IAAsB;IACrH,OAAO,GAAG,CAAC,MAAM,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC,CAAC,QAAQ,EAAE,CAAC;AAC1D,CAAC;AAED,SAAS,OAAO,CAAC,IAAkB,EAAE,OAAwD;IACzF,MAAM,EAAE,SAAS,EAAE,UAAU,EAAE,GAAG,IAAA,iCAAmB,EAAC,IAAa,EAAE,OAAoC,CAAC,CAAC;IAC3G,OAAO,EAAE,SAAS,EAAE,GAAG,CAAC,SAAS,EAAE,MAAM,CAAC,EAAE,UAAU,EAAE,GAAG,CAAC,UAAU,EAAE,OAAO,CAAC,EAAE,CAAC;AACvF,CAAC;AAED,MAAM,GAAG,GAAG,OAAO,CAAC,KAAK,EAAE,EAAE,aAAa,EAAE,IAAI,EAAE,CAAC,CAAC;AACpD,MAAM,EAAE,GAAG,OAAO,CAAC,IAAI,EAAE,EAAE,UAAU,EAAE,YAAY,EAAE,CAAC,CAAC;AAEvD,SAAS,KAAK,CAAC,EAAiB;IAC5B,IAAI,CAAC;QACD,EAAE,EAAE,CAAC;IACT,CAAC;IAAC,OAAO,CAAC,EAAE,CAAC;QACT,OAAO,CAAU,CAAC;IACtB,CAAC;IACD,MAAM,IAAI,KAAK,CAAC,eAAe,CAAC,CAAC;AACrC,CAAC;AAED,IAA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AAE,QAAQ,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,MAAM,EAAE,EAAE,GAAG,EAAE,OAAO,EAAE,GAAG,EAAE,KAAK,EAAE,EAAE,CAAC,CAAC;QAC5G,IAAA,aAAM,EAAC,kBAAO,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC,CAAC,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;QAClD,IAAA,aAAM,EAAC,KAAK,CAAC,GAAG,EAAE,CAAC,kBAAO,CAAC,MAAM,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,UAAU,CAAC,0BAAiB,CAAC,CAAC;IAC1F,CAAC,CAAC,CAAC;AACP,CAAC,CAAC,CAAC"}
@@ -1,4 +1,4 @@
1
1
  import './index';
2
- declare const _default: import("inversify").interfaces.ContainerModule;
2
+ declare const _default: import("@celljs/core").ContainerModule;
3
3
  export default _default;
4
4
  //# sourceMappingURL=module.d.ts.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@celljs/jwt",
3
- "version": "4.1.0",
3
+ "version": "4.3.0",
4
4
  "description": "",
5
5
  "keywords": [
6
6
  "cell-component"
@@ -14,6 +14,9 @@
14
14
  "url": "https://github.com/cellbang/cell.git"
15
15
  },
16
16
  "license": "MIT",
17
+ "engines": {
18
+ "node": ">=18.0.0"
19
+ },
17
20
  "main": "lib/node/index.js",
18
21
  "typings": "lib/node/index.d.ts",
19
22
  "files": [
@@ -29,9 +32,7 @@
29
32
  "watch": "tsc -b -w --preserveWatchOutput"
30
33
  },
31
34
  "dependencies": {
32
- "@celljs/core": "4.1.0",
33
- "@types/jsonwebtoken": "^8.5.8",
34
- "jsonwebtoken": "^9.0.3"
35
+ "@celljs/core": "4.3.0"
35
36
  },
36
37
  "publishConfig": {
37
38
  "access": "public"
@@ -11,3 +11,22 @@ export class PrivateKeyNotFoundError extends CustomError {
11
11
  super('Private key not found');
12
12
  }
13
13
  }
14
+
15
+ /** A token that is malformed, badly signed, or whose claims do not match the verify options. */
16
+ export class JsonWebTokenError extends CustomError {
17
+ constructor(message: string, readonly inner?: Error) {
18
+ super(message);
19
+ }
20
+ }
21
+
22
+ export class TokenExpiredError extends JsonWebTokenError {
23
+ constructor(message: string, readonly expiredAt: Date) {
24
+ super(message);
25
+ }
26
+ }
27
+
28
+ export class NotBeforeError extends JsonWebTokenError {
29
+ constructor(message: string, readonly date: Date) {
30
+ super(message);
31
+ }
32
+ }
package/src/node/index.ts CHANGED
@@ -2,3 +2,4 @@ export * from './jwt-protocol';
2
2
  export * from './jwt-service';
3
3
  export * from './errors';
4
4
  export * from './jwt-secret-service';
5
+ export * from './jwt-util';
@@ -1,27 +1,92 @@
1
- import * as jwt from 'jsonwebtoken';
1
+ import type { KeyObject } from 'crypto';
2
2
 
3
3
  export const JwtService = Symbol('JwtService');
4
4
  export const JwtSecretService = Symbol('JwtSecretService');
5
5
 
6
- export interface JwtOptions {
7
- signOptions?: jwt.SignOptions;
8
- secret?: string | Buffer;
9
- publicKey?: string | Buffer;
10
- privateKey?: jwt.Secret;
11
- verifyOptions?: jwt.VerifyOptions;
6
+ export type Algorithm =
7
+ | 'HS256' | 'HS384' | 'HS512'
8
+ | 'RS256' | 'RS384' | 'RS512'
9
+ | 'PS256' | 'PS384' | 'PS512'
10
+ | 'ES256' | 'ES384' | 'ES512'
11
+ | 'none';
12
+
13
+ /** An HMAC secret, or a PEM / KeyObject key (with its passphrase when it is encrypted). */
14
+ export type Secret = string | Buffer | KeyObject | { key: string | Buffer, passphrase: string };
15
+
16
+ export interface JwtHeader {
17
+ alg: Algorithm | string;
18
+ typ?: string;
19
+ kid?: string;
20
+ [key: string]: unknown;
12
21
  }
13
22
 
14
- export interface SignOptions extends jwt.SignOptions {}
23
+ export interface JwtPayload {
24
+ iss?: string;
25
+ sub?: string;
26
+ aud?: string | string[];
27
+ exp?: number;
28
+ nbf?: number;
29
+ iat?: number;
30
+ jti?: string;
31
+ [key: string]: any;
32
+ }
15
33
 
16
- export interface VerifyOptions extends jwt.VerifyOptions {}
34
+ export interface Jwt {
35
+ header: JwtHeader;
36
+ payload: JwtPayload | string;
37
+ signature: string;
38
+ }
17
39
 
18
- export interface DecodeOptions extends jwt.DecodeOptions {}
40
+ /** Time spans are seconds, or text such as `'2h'`, `'7 days'`, `'500ms'`. */
41
+ export interface SignOptions {
42
+ /** Default `HS256`. */
43
+ algorithm?: Algorithm;
44
+ keyid?: string;
45
+ expiresIn?: string | number;
46
+ notBefore?: string | number;
47
+ audience?: string | string[];
48
+ subject?: string;
49
+ issuer?: string;
50
+ jwtid?: string;
51
+ /** Leave out `iat`. */
52
+ noTimestamp?: boolean;
53
+ header?: Partial<JwtHeader>;
54
+ /** Allow RSA keys under 2048 bits. */
55
+ allowInsecureKeySizes?: boolean;
56
+ }
19
57
 
20
- export interface Jwt extends jwt.Jwt {}
58
+ export interface VerifyOptions {
59
+ /** Default: the algorithms of the key's kind (HS*, RS*, PS* or ES*). */
60
+ algorithms?: Algorithm[];
61
+ audience?: string | RegExp | (string | RegExp)[];
62
+ /** Return `{ header, payload, signature }` instead of the payload. */
63
+ complete?: boolean;
64
+ issuer?: string | string[];
65
+ jwtid?: string;
66
+ subject?: string;
67
+ nonce?: string;
68
+ ignoreExpiration?: boolean;
69
+ ignoreNotBefore?: boolean;
70
+ /** Seconds of clock difference allowed for `exp` and `nbf`. */
71
+ clockTolerance?: number;
72
+ /** Largest age of the token after its `iat`. */
73
+ maxAge?: string | number;
74
+ /** "Now", in seconds. */
75
+ clockTimestamp?: number;
76
+ }
21
77
 
22
- export interface JwtPayload extends jwt.JwtPayload {}
78
+ export interface DecodeOptions {
79
+ complete?: boolean;
80
+ json?: boolean;
81
+ }
23
82
 
24
- export type Secret = jwt.Secret;
83
+ export interface JwtOptions {
84
+ signOptions?: SignOptions;
85
+ secret?: string | Buffer;
86
+ publicKey?: string | Buffer;
87
+ privateKey?: Secret;
88
+ verifyOptions?: VerifyOptions;
89
+ }
25
90
 
26
91
  export interface JwtService {
27
92
  sign(payload: string | Buffer | object, options?: SignOptions, privateKey?: Secret): Promise<string>;
@@ -1,6 +1,6 @@
1
1
  import { Autowired, Component, Value } from '@celljs/core';
2
2
  import { DecodeOptions, JwtOptions, JwtPayload, JwtSecretService, JwtService, Secret, SignOptions, VerifyOptions } from './jwt-protocol';
3
- import jwt from 'jsonwebtoken';
3
+ import { JwtUtil } from './jwt-util';
4
4
 
5
5
  @Component(JwtService)
6
6
  export class JwtServiceImpl implements JwtService {
@@ -14,37 +14,17 @@ export class JwtServiceImpl implements JwtService {
14
14
  async sign(payload: string | object | Buffer, options?: SignOptions, privateKey?: Secret): Promise<string> {
15
15
  const mergedOptions = { ...this.jwtOptions?.signOptions, ...options };
16
16
  const secret = privateKey ?? await this.jwtSecretService.getPrivateKey();
17
- return new Promise<string>((resolve, reject) => {
18
- jwt.sign(payload, secret, mergedOptions, (err, token) => {
19
- if (err) {
20
- reject(err);
21
- } else {
22
- resolve(token || '');
23
- }
24
- });
25
- });
17
+ return JwtUtil.sign(payload, secret, mergedOptions);
26
18
  }
27
19
 
28
20
  async verify<T extends object = any>(token: string, options?: VerifyOptions, publicKey?: string | Buffer): Promise<T> {
29
21
  const mergedOptions = { ...this.jwtOptions?.verifyOptions, ...options };
30
22
  const secret = publicKey ?? await this.jwtSecretService.getPublicKey();
31
- return new Promise<T>((resolve, reject) => {
32
- jwt.verify(token, secret, mergedOptions, (err, decoded) => {
33
- if (err) {
34
- reject(err);
35
- } else {
36
- resolve(decoded as T);
37
- }
38
- });
39
- });
23
+ return JwtUtil.verify<T>(token, secret, mergedOptions);
40
24
  }
41
25
 
42
26
  async decode(token: string, options?: DecodeOptions): Promise<JwtPayload | string | undefined> {
43
- const decoded = jwt.decode(token, options);
44
- if (!decoded) {
45
- return undefined;
46
- }
47
- return decoded;
27
+ return JwtUtil.decode(token, options) ?? undefined;
48
28
  }
49
29
 
50
30
  }
@@ -0,0 +1,125 @@
1
+ import { describe, it } from 'bun:test';
2
+ import { expect } from 'chai';
3
+ import { generateKeyPairSync } from 'node:crypto';
4
+ import { JwtUtil } from './jwt-util';
5
+ import { JsonWebTokenError, NotBeforeError, TokenExpiredError } from './errors';
6
+ import { Algorithm } from './jwt-protocol';
7
+
8
+ function pem(key: { export(options: { type: 'spki' | 'pkcs8', format: 'pem' }): string | Buffer }, type: 'spki' | 'pkcs8'): string {
9
+ return key.export({ type, format: 'pem' }).toString();
10
+ }
11
+
12
+ function keyPair(type: 'rsa' | 'ec', options: { modulusLength?: number, namedCurve?: string }) {
13
+ const { publicKey, privateKey } = generateKeyPairSync(type as 'rsa', options as { modulusLength: number });
14
+ return { publicKey: pem(publicKey, 'spki'), privateKey: pem(privateKey, 'pkcs8') };
15
+ }
16
+
17
+ const rsa = keyPair('rsa', { modulusLength: 2048 });
18
+ const ec = keyPair('ec', { namedCurve: 'prime256v1' });
19
+
20
+ function error(fn: () => unknown): Error {
21
+ try {
22
+ fn();
23
+ } catch (e) {
24
+ return e as Error;
25
+ }
26
+ throw new Error('did not throw');
27
+ }
28
+
29
+ describe('JwtUtil', () => {
30
+ // Made by jsonwebtoken 9.0.3: tokens stay the same, byte for byte.
31
+ it('signs HMAC tokens as jsonwebtoken did', () => {
32
+ expect(JwtUtil.sign({ sub: 'u', iat: 1700000000 }, 'secret', { algorithm: 'HS256' })).to.equal(
33
+ 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1IiwiaWF0IjoxNzAwMDAwMDAwfQ.XnL_w7HK3br5amJH_8ubcBdNxqsRVENLSiGZi5_2j3k');
34
+ expect(JwtUtil.sign({ sub: 'u', iat: 1700000000, exp: 1700003600 }, 'secret', { algorithm: 'HS512', header: { kid: 'k1' } })).to.equal(
35
+ 'eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCIsImtpZCI6ImsxIn0.eyJzdWIiOiJ1IiwiaWF0IjoxNzAwMDAwMDAwLCJleHAiOjE3MDAwMDM2MDB9.2ijjBEf4LTfiz7ILrRzd2_norxKXM7r3VJX6fAKVnJdn_0PBFugckJObZ5EX_PXNnJO9pJal2T-E5kG8qS5YkA');
36
+ });
37
+
38
+ it('verifies what it signs, with every algorithm', () => {
39
+ const keys: [Algorithm, string, string][] = [
40
+ ['HS256', 's', 's'], ['HS384', 's', 's'], ['HS512', 's', 's'],
41
+ ['RS256', rsa.privateKey, rsa.publicKey], ['RS512', rsa.privateKey, rsa.publicKey],
42
+ ['PS256', rsa.privateKey, rsa.publicKey], ['ES256', ec.privateKey, ec.publicKey]
43
+ ];
44
+ for (const [algorithm, privateKey, publicKey] of keys) {
45
+ const token = JwtUtil.sign({ x: 1 }, privateKey, { algorithm, expiresIn: '1h', audience: 'app', issuer: 'me', subject: 'u', keyid: 'k' });
46
+ const { header, payload } = JwtUtil.verify<any>(token, publicKey, { audience: 'app', issuer: 'me', subject: 'u', complete: true });
47
+ expect(header).to.deep.equal({ alg: algorithm, typ: 'JWT', kid: 'k' });
48
+ expect(payload).to.include({ x: 1, aud: 'app', iss: 'me', sub: 'u' });
49
+ expect(payload.exp - payload.iat).to.equal(3600);
50
+ }
51
+ });
52
+
53
+ it('turns time spans into claims', () => {
54
+ const token = JwtUtil.sign({ iat: 1700000000 }, 's', { expiresIn: '2 days', notBefore: '10m' });
55
+ expect(JwtUtil.decode(token)).to.deep.equal({ iat: 1700000000, nbf: 1700000600, exp: 1700172800 });
56
+ expect(JwtUtil.decode(JwtUtil.sign({}, 's', { noTimestamp: true, expiresIn: 60 }))).to.not.have.property('iat');
57
+ });
58
+
59
+ it('refuses expired, early, forged and mismatched tokens', () => {
60
+ expect(error(() => JwtUtil.verify(JwtUtil.sign({ exp: 1 }, 's'), 's'))).to.be.instanceOf(TokenExpiredError).and.have.property('message', 'jwt expired');
61
+ expect(JwtUtil.verify(JwtUtil.sign({ exp: 1 }, 's'), 's', { ignoreExpiration: true })).to.include({ exp: 1 });
62
+ expect(error(() => JwtUtil.verify(JwtUtil.sign({ nbf: 9999999999 }, 's'), 's'))).to.be.instanceOf(NotBeforeError);
63
+ expect(error(() => JwtUtil.verify(JwtUtil.sign({}, 's'), 'other')).message).to.equal('invalid signature');
64
+ expect(error(() => JwtUtil.verify('a.b', 's')).message).to.equal('jwt malformed');
65
+ expect(error(() => JwtUtil.verify(JwtUtil.sign({}, 's', { algorithm: 'HS512' }), 's', { algorithms: ['HS256'] })).message).to.equal('invalid algorithm');
66
+ expect(error(() => JwtUtil.verify(JwtUtil.sign({}, 's'), rsa.publicKey)).message).to.equal('invalid algorithm');
67
+ expect(error(() => JwtUtil.verify(JwtUtil.sign({ aud: 'x' }, 's'), 's', { audience: ['y', /z/] })).message).to.equal('jwt audience invalid. expected: y or /z/');
68
+ expect(JwtUtil.verify(JwtUtil.sign({ aud: ['a', 'zz'] }, 's'), 's', { audience: /z/ })).to.have.property('aud');
69
+ expect(error(() => JwtUtil.verify(JwtUtil.sign({ iat: 100 }, 's'), 's', { maxAge: '1h' })).message).to.equal('maxAge exceeded');
70
+ expect(error(() => JwtUtil.verify(JwtUtil.sign({}, 's'), 's', { nonce: '' })).message).to.equal('nonce must be a non-empty string');
71
+ expect(JwtUtil.verify(JwtUtil.sign({ a: 1 }, 's'), 's')).to.include({ a: 1 });
72
+ });
73
+
74
+ it('accepts unsigned tokens only when "none" is listed', () => {
75
+ const none = JwtUtil.sign({ a: 1 }, undefined, { algorithm: 'none' });
76
+ expect(none.endsWith('.')).to.equal(true);
77
+ expect(error(() => JwtUtil.verify(none, 's')).message).to.equal('jwt signature is required');
78
+ expect(error(() => JwtUtil.verify(none, undefined)).message).to.equal('please specify "none" in "algorithms" to verify unsigned tokens');
79
+ expect(JwtUtil.verify(none, undefined, { algorithms: ['none'] })).to.include({ a: 1 });
80
+ });
81
+
82
+ it('checks that the key fits the algorithm', () => {
83
+ expect(error(() => JwtUtil.sign({}, 's', { algorithm: 'RS256' })).message).to.equal('secretOrPrivateKey must be an asymmetric key when using RS256');
84
+ expect(error(() => JwtUtil.sign({}, rsa.privateKey)).message).to.equal('secretOrPrivateKey must be a symmetric key when using HS256');
85
+ expect(error(() => JwtUtil.sign({}, ec.privateKey, { algorithm: 'ES384' })).message).to.equal('"alg" parameter "ES384" requires curve "secp384r1".');
86
+ const small = keyPair('rsa', { modulusLength: 1024 });
87
+ expect(error(() => JwtUtil.sign({}, small.privateKey, { algorithm: 'RS256' })).message).to.equal('secretOrPrivateKey has a minimum key size of 2048 bits for RS256');
88
+ expect(JwtUtil.sign({}, small.privateKey, { algorithm: 'RS256', allowInsecureKeySizes: true })).to.be.a('string');
89
+ });
90
+
91
+ // Failing to parse a secret as a PEM key took 0.2 ms per token with the OpenSSL 3.0 of Node.js 20.
92
+ it('uses a secret without a PEM header as an HMAC key without parsing it', () => {
93
+ const crypto = require('crypto');
94
+ const { createPublicKey, createPrivateKey } = crypto;
95
+ let parsed = 0;
96
+ crypto.createPublicKey = (...args: unknown[]) => { parsed++; return createPublicKey(...args); };
97
+ crypto.createPrivateKey = (...args: unknown[]) => { parsed++; return createPrivateKey(...args); };
98
+ try {
99
+ for (const secret of ['s', Buffer.from('s')]) {
100
+ expect(JwtUtil.verify<any>(JwtUtil.sign({ x: 1 }, secret), secret)).to.include({ x: 1 });
101
+ }
102
+ expect(parsed).to.equal(0);
103
+ const token = JwtUtil.sign({ x: 1 }, Buffer.from(rsa.privateKey), { algorithm: 'RS256' });
104
+ expect(JwtUtil.verify<any>(token, Buffer.from(rsa.publicKey))).to.include({ x: 1 });
105
+ expect(parsed).to.equal(2);
106
+ } finally {
107
+ Object.assign(crypto, { createPublicKey, createPrivateKey });
108
+ }
109
+ });
110
+
111
+ it('keeps payloads and options apart', () => {
112
+ expect(error(() => JwtUtil.sign({ exp: 5 }, 's', { expiresIn: 10 })).message).to.equal('Bad "options.expiresIn" option the payload already has an "exp" property.');
113
+ expect(error(() => JwtUtil.sign('text', 's', { expiresIn: 10 })).message).to.equal('invalid expiresIn option for string payload');
114
+ expect(JwtUtil.verify(JwtUtil.sign('text', 's'), 's')).to.equal('text');
115
+ expect(error(() => JwtUtil.sign({}, 's', { expiresIn: 'soon' }))).to.be.instanceOf(Error);
116
+ });
117
+
118
+ it('decodes without verifying', () => {
119
+ const token = JwtUtil.sign({ a: 1, iat: 1 }, 's');
120
+ expect(JwtUtil.decode(token)).to.deep.equal({ a: 1, iat: 1 });
121
+ expect(JwtUtil.decode(token, { complete: true })).to.deep.include({ header: { alg: 'HS256', typ: 'JWT' } });
122
+ expect(JwtUtil.decode('nonsense')).to.equal(null);
123
+ expect(error(() => JwtUtil.verify('a.b.c', 's'))).to.be.instanceOf(JsonWebTokenError);
124
+ });
125
+ });