@celljs/jwt 4.0.0 → 4.2.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.
- package/README.md +16 -1
- package/esm/node/errors.d.ts +13 -0
- package/esm/node/errors.js +19 -0
- package/esm/node/errors.js.map +1 -1
- package/esm/node/index.d.ts +1 -0
- package/esm/node/index.js +1 -0
- package/esm/node/index.js.map +1 -1
- package/esm/node/jwt-protocol.d.ts +69 -13
- package/esm/node/jwt-service.js +5 -26
- package/esm/node/jwt-service.js.map +1 -1
- package/esm/node/jwt-util.d.ts +13 -0
- package/esm/node/jwt-util.js +304 -0
- package/esm/node/jwt-util.js.map +1 -0
- package/esm/node/module.d.ts +1 -1
- package/lib/node/errors.d.ts +13 -0
- package/lib/node/errors.d.ts.map +1 -1
- package/lib/node/errors.js +23 -1
- package/lib/node/errors.js.map +1 -1
- package/lib/node/index.d.ts +1 -0
- package/lib/node/index.d.ts.map +1 -1
- package/lib/node/index.js +1 -0
- package/lib/node/index.js.map +1 -1
- package/lib/node/jwt-protocol.d.ts +69 -13
- package/lib/node/jwt-protocol.d.ts.map +1 -1
- package/lib/node/jwt-service.d.ts.map +1 -1
- package/lib/node/jwt-service.js +5 -29
- package/lib/node/jwt-service.js.map +1 -1
- package/lib/node/jwt-util.d.ts +14 -0
- package/lib/node/jwt-util.d.ts.map +1 -0
- package/lib/node/jwt-util.js +307 -0
- package/lib/node/jwt-util.js.map +1 -0
- package/lib/node/jwt-util.spec.d.ts +2 -0
- package/lib/node/jwt-util.spec.d.ts.map +1 -0
- package/lib/node/jwt-util.spec.js +114 -0
- package/lib/node/jwt-util.spec.js.map +1 -0
- package/lib/node/module.d.ts +1 -1
- package/package.json +5 -7
- package/src/node/errors.ts +19 -0
- package/src/node/index.ts +1 -0
- package/src/node/jwt-protocol.ts +78 -13
- package/src/node/jwt-service.ts +4 -24
- package/src/node/jwt-util.spec.ts +125 -0
- package/src/node/jwt-util.ts +308 -0
|
@@ -0,0 +1,308 @@
|
|
|
1
|
+
import { constants, createHmac, createPrivateKey, createPublicKey, createSecretKey, KeyObject, sign as cryptoSign, timingSafeEqual, verify as cryptoVerify } from 'crypto';
|
|
2
|
+
import { Algorithm, DecodeOptions, Jwt, JwtHeader, JwtPayload, Secret, SignOptions, VerifyOptions } from './jwt-protocol';
|
|
3
|
+
import { JsonWebTokenError, NotBeforeError, TokenExpiredError } from './errors';
|
|
4
|
+
|
|
5
|
+
const UNITS: Record<string, number> = {
|
|
6
|
+
ms: 0.001, msec: 0.001, msecs: 0.001, millisecond: 0.001, milliseconds: 0.001,
|
|
7
|
+
s: 1, sec: 1, secs: 1, second: 1, seconds: 1,
|
|
8
|
+
m: 60, min: 60, mins: 60, minute: 60, minutes: 60,
|
|
9
|
+
h: 3600, hr: 3600, hrs: 3600, hour: 3600, hours: 3600,
|
|
10
|
+
d: 86400, day: 86400, days: 86400,
|
|
11
|
+
w: 604800, week: 604800, weeks: 604800,
|
|
12
|
+
y: 31557600, yr: 31557600, yrs: 31557600, year: 31557600, years: 31557600
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
/** Algorithms each kind of key can verify when the options do not name them. */
|
|
16
|
+
const DEFAULT_ALGORITHMS: Record<string, Algorithm[]> = {
|
|
17
|
+
secret: ['HS256', 'HS384', 'HS512'],
|
|
18
|
+
rsa: ['RS256', 'RS384', 'RS512', 'PS256', 'PS384', 'PS512'],
|
|
19
|
+
'rsa-pss': ['RS256', 'RS384', 'RS512', 'PS256', 'PS384', 'PS512'],
|
|
20
|
+
ec: ['ES256', 'ES384', 'ES512']
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
const CURVES: Record<string, string> = { ES256: 'prime256v1', ES384: 'secp384r1', ES512: 'secp521r1' };
|
|
24
|
+
|
|
25
|
+
const CLAIMS: [keyof SignOptions, string][] = [['audience', 'aud'], ['issuer', 'iss'], ['subject', 'sub'], ['jwtid', 'jti']];
|
|
26
|
+
|
|
27
|
+
function base64url(value: string | Buffer): string {
|
|
28
|
+
return Buffer.from(value).toString('base64url');
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Seconds of a time span after `from`: `'2h'` → from + 7200; a number is seconds. */
|
|
32
|
+
function timespan(value: string | number, from: number): number {
|
|
33
|
+
if (typeof value === 'number') {
|
|
34
|
+
return Math.floor(from + value);
|
|
35
|
+
}
|
|
36
|
+
const match = /^(-?(?:\d+)?\.?\d+) *([a-z]+)?$/i.exec(value.trim());
|
|
37
|
+
const unit = match ? UNITS[(match[2] || 'ms').toLowerCase()] : undefined;
|
|
38
|
+
if (!match || unit === undefined) {
|
|
39
|
+
throw new Error(`"${value}" is not a time span such as 60, "2 days", "10h" or "7d"`);
|
|
40
|
+
}
|
|
41
|
+
return Math.floor(from + Number(match[1]) * unit);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function digest(algorithm: string): string {
|
|
45
|
+
return `sha${algorithm.slice(2)}`;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
type ErrorType = new (message: string) => Error;
|
|
49
|
+
|
|
50
|
+
function keyFor(secret: Secret, isPublic: boolean): KeyObject {
|
|
51
|
+
if (secret instanceof KeyObject) {
|
|
52
|
+
return secret;
|
|
53
|
+
}
|
|
54
|
+
// Without a PEM header the key parsers can only fail, which costs about 0.2 ms with the OpenSSL 3.0 of
|
|
55
|
+
// Node.js 20: an HMAC secret skips them.
|
|
56
|
+
if ((typeof secret === 'string' || Buffer.isBuffer(secret)) && !secret.includes('-----BEGIN')) {
|
|
57
|
+
return createSecretKey(typeof secret === 'string' ? Buffer.from(secret) : secret);
|
|
58
|
+
}
|
|
59
|
+
try {
|
|
60
|
+
return isPublic ? createPublicKey(secret as string | Buffer) : createPrivateKey(secret as string | Buffer | { key: string | Buffer, passphrase: string });
|
|
61
|
+
} catch {
|
|
62
|
+
if (typeof secret === 'object' && !Buffer.isBuffer(secret)) {
|
|
63
|
+
throw isPublic ? new JsonWebTokenError('secretOrPublicKey is not valid key material') : new Error('secretOrPrivateKey is not valid key material');
|
|
64
|
+
}
|
|
65
|
+
return createSecretKey(typeof secret === 'string' ? Buffer.from(secret) : secret);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** The checks of jsonwebtoken 9: the kind of key must fit the algorithm. */
|
|
70
|
+
function checkKey(algorithm: string, key: KeyObject, name: string, error: ErrorType, allowInsecureKeySizes?: boolean): void {
|
|
71
|
+
if (algorithm.startsWith('HS')) {
|
|
72
|
+
if (key.type !== 'secret') {
|
|
73
|
+
throw new error(`${name} must be a symmetric key when using ${algorithm}`);
|
|
74
|
+
}
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
if (key.type === 'secret') {
|
|
78
|
+
throw new error(`${name} must be an asymmetric key when using ${algorithm}`);
|
|
79
|
+
}
|
|
80
|
+
const type = key.asymmetricKeyType;
|
|
81
|
+
const expected = algorithm.startsWith('RS') ? ['rsa'] : algorithm.startsWith('PS') ? ['rsa', 'rsa-pss'] : ['ec'];
|
|
82
|
+
if (!type || !expected.includes(type)) {
|
|
83
|
+
throw new error(`"alg" parameter for "${type}" key type must be one of: ${(DEFAULT_ALGORITHMS[type ?? ''] ?? []).join(', ')}.`);
|
|
84
|
+
}
|
|
85
|
+
if (type === 'ec' && key.asymmetricKeyDetails?.namedCurve !== CURVES[algorithm]) {
|
|
86
|
+
throw new error(`"alg" parameter "${algorithm}" requires curve "${CURVES[algorithm]}".`);
|
|
87
|
+
}
|
|
88
|
+
if (type.startsWith('rsa') && !allowInsecureKeySizes && (key.asymmetricKeyDetails?.modulusLength ?? 0) < 2048) {
|
|
89
|
+
throw new error(`${name} has a minimum key size of 2048 bits for ${algorithm}`);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function signature(algorithm: string, input: string, key: KeyObject): string {
|
|
94
|
+
if (algorithm === 'none') {
|
|
95
|
+
return '';
|
|
96
|
+
}
|
|
97
|
+
if (algorithm.startsWith('HS')) {
|
|
98
|
+
return createHmac(digest(algorithm), key).update(input).digest('base64url');
|
|
99
|
+
}
|
|
100
|
+
return cryptoSign(digest(algorithm), Buffer.from(input), signingKey(algorithm, key)).toString('base64url');
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function signingKey(algorithm: string, key: KeyObject) {
|
|
104
|
+
if (algorithm.startsWith('PS')) {
|
|
105
|
+
return { key, padding: constants.RSA_PKCS1_PSS_PADDING, saltLength: constants.RSA_PSS_SALTLEN_DIGEST };
|
|
106
|
+
}
|
|
107
|
+
if (algorithm.startsWith('ES')) {
|
|
108
|
+
return { key, dsaEncoding: 'ieee-p1363' as const };
|
|
109
|
+
}
|
|
110
|
+
return key;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* JSON Web Tokens (JWS compact form) on `node:crypto`, with the options, defaults, checks and error messages
|
|
115
|
+
* of the `jsonwebtoken` package: tokens it made verify here and the other way round.
|
|
116
|
+
*/
|
|
117
|
+
export namespace JwtUtil {
|
|
118
|
+
|
|
119
|
+
export function sign(payload: string | Buffer | object, secret: Secret | undefined, options: SignOptions = {}): string {
|
|
120
|
+
const algorithm = options.algorithm ?? 'HS256';
|
|
121
|
+
const isObject = typeof payload === 'object' && !Buffer.isBuffer(payload);
|
|
122
|
+
if (payload === undefined || payload === null) {
|
|
123
|
+
throw new Error('payload is required');
|
|
124
|
+
}
|
|
125
|
+
if (!secret && algorithm !== 'none') {
|
|
126
|
+
throw new Error('secretOrPrivateKey must have a value');
|
|
127
|
+
}
|
|
128
|
+
const key = algorithm === 'none' ? undefined : keyFor(secret!, false);
|
|
129
|
+
if (key) {
|
|
130
|
+
checkKey(algorithm, key, 'secretOrPrivateKey', Error, options.allowInsecureKeySizes);
|
|
131
|
+
}
|
|
132
|
+
let body: string;
|
|
133
|
+
if (isObject) {
|
|
134
|
+
const claims: JwtPayload = { ...(payload as JwtPayload) };
|
|
135
|
+
const timestamp = claims.iat || Math.floor(Date.now() / 1000);
|
|
136
|
+
if (options.noTimestamp) {
|
|
137
|
+
delete claims.iat;
|
|
138
|
+
} else {
|
|
139
|
+
claims.iat = timestamp;
|
|
140
|
+
}
|
|
141
|
+
if (options.notBefore !== undefined) {
|
|
142
|
+
if (claims.nbf !== undefined) {
|
|
143
|
+
throw new Error('Bad "options.notBefore" option the payload already has an "nbf" property.');
|
|
144
|
+
}
|
|
145
|
+
claims.nbf = timespan(options.notBefore, timestamp);
|
|
146
|
+
}
|
|
147
|
+
if (options.expiresIn !== undefined) {
|
|
148
|
+
if (claims.exp !== undefined) {
|
|
149
|
+
throw new Error('Bad "options.expiresIn" option the payload already has an "exp" property.');
|
|
150
|
+
}
|
|
151
|
+
claims.exp = timespan(options.expiresIn, timestamp);
|
|
152
|
+
}
|
|
153
|
+
for (const [option, claim] of CLAIMS) {
|
|
154
|
+
if (options[option] !== undefined) {
|
|
155
|
+
if (claims[claim] !== undefined) {
|
|
156
|
+
throw new Error(`Bad "options.${option}" option. The payload already has an "${claim}" property.`);
|
|
157
|
+
}
|
|
158
|
+
claims[claim] = options[option];
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
body = JSON.stringify(claims);
|
|
162
|
+
} else {
|
|
163
|
+
const invalid = (['expiresIn', 'notBefore', 'noTimestamp', ...CLAIMS.map(([option]) => option)] as (keyof SignOptions)[]).find(option => options[option] !== undefined);
|
|
164
|
+
if (invalid) {
|
|
165
|
+
throw new Error(`invalid ${invalid} option for string payload`);
|
|
166
|
+
}
|
|
167
|
+
body = Buffer.isBuffer(payload) ? payload.toString('utf8') : payload as string;
|
|
168
|
+
}
|
|
169
|
+
const header: JwtHeader = JSON.parse(JSON.stringify({ alg: algorithm, typ: isObject ? 'JWT' : undefined, kid: options.keyid, ...options.header }));
|
|
170
|
+
const input = `${base64url(JSON.stringify(header))}.${base64url(body)}`;
|
|
171
|
+
return `${input}.${key ? signature(algorithm, input, key) : ''}`;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
export function decode(token: string, options: DecodeOptions & { complete: true }): Jwt | null;
|
|
175
|
+
export function decode(token: string, options?: DecodeOptions): JwtPayload | string | null;
|
|
176
|
+
export function decode(token: string, options: DecodeOptions = {}): Jwt | JwtPayload | string | null {
|
|
177
|
+
if (typeof token !== 'string') {
|
|
178
|
+
return null;
|
|
179
|
+
}
|
|
180
|
+
const parts = token.split('.');
|
|
181
|
+
if (parts.length !== 3) {
|
|
182
|
+
return null;
|
|
183
|
+
}
|
|
184
|
+
let header: JwtHeader;
|
|
185
|
+
try {
|
|
186
|
+
header = JSON.parse(Buffer.from(parts[0], 'base64url').toString('utf8'));
|
|
187
|
+
} catch {
|
|
188
|
+
return null;
|
|
189
|
+
}
|
|
190
|
+
if (!header || typeof header !== 'object') {
|
|
191
|
+
return null;
|
|
192
|
+
}
|
|
193
|
+
let payload: JwtPayload | string = Buffer.from(parts[1], 'base64url').toString('utf8');
|
|
194
|
+
try {
|
|
195
|
+
const parsed = JSON.parse(payload);
|
|
196
|
+
if (parsed !== null && typeof parsed === 'object') {
|
|
197
|
+
payload = parsed;
|
|
198
|
+
}
|
|
199
|
+
} catch {
|
|
200
|
+
if (header.typ === 'JWT' || options.json) {
|
|
201
|
+
return null;
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
return options.complete ? { header, payload, signature: parts[2] } : payload;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
export function verify<T = JwtPayload>(token: string, secret: Secret | undefined, options: VerifyOptions = {}): T {
|
|
208
|
+
if (options.nonce !== undefined && (typeof options.nonce !== 'string' || options.nonce.trim() === '')) {
|
|
209
|
+
throw new JsonWebTokenError('nonce must be a non-empty string');
|
|
210
|
+
}
|
|
211
|
+
const clockTimestamp = options.clockTimestamp ?? Math.floor(Date.now() / 1000);
|
|
212
|
+
const tolerance = options.clockTolerance ?? 0;
|
|
213
|
+
if (!token) {
|
|
214
|
+
throw new JsonWebTokenError('jwt must be provided');
|
|
215
|
+
}
|
|
216
|
+
if (typeof token !== 'string') {
|
|
217
|
+
throw new JsonWebTokenError('jwt must be a string');
|
|
218
|
+
}
|
|
219
|
+
const parts = token.split('.');
|
|
220
|
+
if (parts.length !== 3) {
|
|
221
|
+
throw new JsonWebTokenError('jwt malformed');
|
|
222
|
+
}
|
|
223
|
+
const decoded = decode(token, { complete: true });
|
|
224
|
+
if (!decoded) {
|
|
225
|
+
throw new JsonWebTokenError('invalid token');
|
|
226
|
+
}
|
|
227
|
+
const { header } = decoded;
|
|
228
|
+
const hasSignature = parts[2].trim() !== '';
|
|
229
|
+
if (!hasSignature && secret) {
|
|
230
|
+
throw new JsonWebTokenError('jwt signature is required');
|
|
231
|
+
}
|
|
232
|
+
if (hasSignature && !secret) {
|
|
233
|
+
throw new JsonWebTokenError('secret or public key must be provided');
|
|
234
|
+
}
|
|
235
|
+
const key = secret ? keyFor(secret, true) : undefined;
|
|
236
|
+
if (!hasSignature && !options.algorithms) {
|
|
237
|
+
throw new JsonWebTokenError('please specify "none" in "algorithms" to verify unsigned tokens');
|
|
238
|
+
}
|
|
239
|
+
const algorithms = options.algorithms ?? DEFAULT_ALGORITHMS[key!.type === 'secret' ? 'secret' : key!.asymmetricKeyType ?? ''] ?? [];
|
|
240
|
+
if (!algorithms.includes(header.alg as Algorithm)) {
|
|
241
|
+
throw new JsonWebTokenError('invalid algorithm');
|
|
242
|
+
}
|
|
243
|
+
if (key) {
|
|
244
|
+
checkKey(header.alg, key, 'secretOrPublicKey', JsonWebTokenError, true);
|
|
245
|
+
const input = `${parts[0]}.${parts[1]}`;
|
|
246
|
+
let valid: boolean;
|
|
247
|
+
if (header.alg.startsWith('HS')) {
|
|
248
|
+
const expected = Buffer.from(signature(header.alg, input, key));
|
|
249
|
+
const actual = Buffer.from(parts[2]);
|
|
250
|
+
valid = expected.length === actual.length && timingSafeEqual(expected, actual);
|
|
251
|
+
} else {
|
|
252
|
+
try {
|
|
253
|
+
valid = cryptoVerify(digest(header.alg), Buffer.from(input), signingKey(header.alg, key), Buffer.from(parts[2], 'base64url'));
|
|
254
|
+
} catch {
|
|
255
|
+
valid = false;
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
if (!valid) {
|
|
259
|
+
throw new JsonWebTokenError('invalid signature');
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
const payload = decoded.payload as JwtPayload;
|
|
263
|
+
if (payload.nbf !== undefined && !options.ignoreNotBefore) {
|
|
264
|
+
if (typeof payload.nbf !== 'number') {
|
|
265
|
+
throw new JsonWebTokenError('invalid nbf value');
|
|
266
|
+
}
|
|
267
|
+
if (payload.nbf > clockTimestamp + tolerance) {
|
|
268
|
+
throw new NotBeforeError('jwt not active', new Date(payload.nbf * 1000));
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
if (payload.exp !== undefined && !options.ignoreExpiration) {
|
|
272
|
+
if (typeof payload.exp !== 'number') {
|
|
273
|
+
throw new JsonWebTokenError('invalid exp value');
|
|
274
|
+
}
|
|
275
|
+
if (clockTimestamp >= payload.exp + tolerance) {
|
|
276
|
+
throw new TokenExpiredError('jwt expired', new Date(payload.exp * 1000));
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
if (options.audience) {
|
|
280
|
+
const audiences = Array.isArray(options.audience) ? options.audience : [options.audience];
|
|
281
|
+
const targets = Array.isArray(payload.aud) ? payload.aud : [payload.aud];
|
|
282
|
+
if (!targets.some(target => audiences.some(a => a instanceof RegExp ? a.test(target ?? '') : a === target))) {
|
|
283
|
+
throw new JsonWebTokenError(`jwt audience invalid. expected: ${audiences.join(' or ')}`);
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
if (options.issuer) {
|
|
287
|
+
const issuers = Array.isArray(options.issuer) ? options.issuer : [options.issuer];
|
|
288
|
+
if (!issuers.includes(payload.iss as string)) {
|
|
289
|
+
throw new JsonWebTokenError(`jwt issuer invalid. expected: ${issuers.join(',')}`);
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
for (const [option, claim] of [['subject', 'sub'], ['jwtid', 'jti'], ['nonce', 'nonce']] as const) {
|
|
293
|
+
if (options[option] && payload[claim] !== options[option]) {
|
|
294
|
+
throw new JsonWebTokenError(`jwt ${option} invalid. expected: ${options[option]}`);
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
if (options.maxAge !== undefined) {
|
|
298
|
+
if (typeof payload.iat !== 'number') {
|
|
299
|
+
throw new JsonWebTokenError('iat required when maxAge is specified');
|
|
300
|
+
}
|
|
301
|
+
const maxAgeTimestamp = timespan(options.maxAge, payload.iat);
|
|
302
|
+
if (clockTimestamp >= maxAgeTimestamp + tolerance) {
|
|
303
|
+
throw new TokenExpiredError('maxAge exceeded', new Date(maxAgeTimestamp * 1000));
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
return (options.complete ? decoded : payload) as T;
|
|
307
|
+
}
|
|
308
|
+
}
|