@liuhlightning/jwt 0.4.0 → 0.5.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/dist/index.js CHANGED
@@ -17,14 +17,53 @@ Object.defineProperty(exports, "__esModule", { value: true });
17
17
  exports.JWT = void 0;
18
18
  const crypto_1 = require("crypto");
19
19
  const error_1 = require("./error");
20
- const JWT_HASH_ALGORITHM_MAP = {
21
- HS256: "sha256",
22
- HS384: "sha384",
23
- HS512: "sha512",
24
- RS256: "sha256",
25
- RS384: "sha384",
26
- RS512: "sha512",
20
+ const JWT_ALGORITHM_MAP = {
21
+ HS256: { family: "hmac", hash: "sha256" },
22
+ HS384: { family: "hmac", hash: "sha384" },
23
+ HS512: { family: "hmac", hash: "sha512" },
24
+ RS256: { family: "rsa", hash: "sha256" },
25
+ RS384: { family: "rsa", hash: "sha384" },
26
+ RS512: { family: "rsa", hash: "sha512" },
27
+ PS256: { family: "pss", hash: "sha256" },
28
+ PS384: { family: "pss", hash: "sha384" },
29
+ PS512: { family: "pss", hash: "sha512" },
30
+ ES256: {
31
+ family: "ec",
32
+ hash: "sha256",
33
+ curve: "prime256v1",
34
+ signatureLength: 64,
35
+ },
36
+ ES256K: {
37
+ family: "ec",
38
+ hash: "sha256",
39
+ curve: "secp256k1",
40
+ signatureLength: 64,
41
+ },
42
+ ES384: {
43
+ family: "ec",
44
+ hash: "sha384",
45
+ curve: "secp384r1",
46
+ signatureLength: 96,
47
+ },
48
+ ES512: {
49
+ family: "ec",
50
+ hash: "sha512",
51
+ curve: "secp521r1",
52
+ signatureLength: 132,
53
+ },
27
54
  };
55
+ const JWT_REGISTERED_CLAIMS = [
56
+ "iss",
57
+ "sub",
58
+ "aud",
59
+ "exp",
60
+ "nbf",
61
+ "iat",
62
+ "jti",
63
+ ];
64
+ const JWT_PEM_MARKER = Buffer.from("-----BEGIN");
65
+ const JWT_MIN_SECRET_BYTES = 32;
66
+ const JWT_MIN_RSA_MODULUS_BITS = 2048;
28
67
  /**
29
68
  * A class to create and verify JSON Web Tokens
30
69
  *
@@ -67,55 +106,158 @@ class JWT {
67
106
  issuer;
68
107
  subject;
69
108
  audience;
109
+ kid;
70
110
  expirationTime;
71
111
  notBefore;
72
112
  issuedAt;
73
113
  jwtID;
114
+ requireExpiration;
115
+ clockTolerance;
116
+ maxTokenAge;
74
117
  /**
75
118
  * Create a new JWT instance
76
- * @param secret The secret used to sign the token
119
+ * @param key The secret or key used to sign and verify the token
77
120
  * @param options Options for the token
78
121
  */
79
122
  constructor(key, options = {}) {
80
- if (typeof key === "string") {
81
- this.secret = (0, crypto_1.createSecretKey)(key, "utf-8");
82
- this.algorithm = options.algorithm ?? "HS256";
123
+ let secret;
124
+ let privateKey;
125
+ let publicKey;
126
+ if (typeof key === "string" ||
127
+ Buffer.isBuffer(key) ||
128
+ key instanceof crypto_1.KeyObject) {
129
+ secret = JWT.toSecretKey(key);
83
130
  }
84
- else if (key instanceof Buffer) {
85
- this.secret = (0, crypto_1.createSecretKey)(key);
86
- this.algorithm = options.algorithm ?? "HS256";
131
+ else if (typeof key === "object" && key !== null) {
132
+ const input = key;
133
+ const hasSecret = input.secret !== undefined;
134
+ const hasPrivateKey = input.privateKey !== undefined;
135
+ const hasPublicKey = input.publicKey !== undefined;
136
+ if (hasSecret && (hasPrivateKey || hasPublicKey)) {
137
+ throw new error_1.JWTErrorInvalidKey("provide either `secret` or `privateKey` / `publicKey`, not both");
138
+ }
139
+ if (hasSecret) {
140
+ secret = JWT.toSecretKey(input.secret);
141
+ }
142
+ else if (hasPrivateKey) {
143
+ privateKey = JWT.toPrivateKey(input.privateKey);
144
+ // derive the public key from the private key
145
+ let derivedPublicKey;
146
+ try {
147
+ derivedPublicKey = (0, crypto_1.createPublicKey)(privateKey);
148
+ }
149
+ catch (error) {
150
+ throw new error_1.JWTErrorInvalidKey(`invalid private key: ${JWT.errorMessage(error)}`);
151
+ }
152
+ if (hasPublicKey) {
153
+ const providedPublicKey = JWT.toPublicKey(input.publicKey);
154
+ let matches;
155
+ try {
156
+ matches = derivedPublicKey.equals(providedPublicKey);
157
+ }
158
+ catch {
159
+ matches = false;
160
+ }
161
+ if (!matches) {
162
+ throw new error_1.JWTErrorInvalidKey("the provided `publicKey` does not match `privateKey`");
163
+ }
164
+ publicKey = providedPublicKey;
165
+ }
166
+ else {
167
+ publicKey = derivedPublicKey;
168
+ }
169
+ }
170
+ else if (hasPublicKey) {
171
+ publicKey = JWT.toPublicKey(input.publicKey);
172
+ }
173
+ else {
174
+ throw new error_1.JWTErrorInvalidKey("the key must be a secret, a private key, or a public key");
175
+ }
87
176
  }
88
177
  else {
89
- const { privateKey, publicKey } = key;
90
- if (privateKey) {
91
- this.privateKey = (0, crypto_1.createPrivateKey)(privateKey);
92
- // create public key from private key
93
- this.publicKey = (0, crypto_1.createPublicKey)(this.privateKey);
178
+ throw new error_1.JWTErrorInvalidKey("the key must be a secret, a private key, or a public key");
179
+ }
180
+ const keyObject = secret ?? privateKey ?? publicKey;
181
+ if (!keyObject) {
182
+ throw new error_1.JWTErrorInvalidKey("the key must be a secret, a private key, or a public key");
183
+ }
184
+ const algorithm = options.algorithm ?? JWT.defaultAlgorithm(keyObject);
185
+ const info = JWT.algorithmInfo(algorithm);
186
+ if (info.family === "hmac") {
187
+ if (!secret) {
188
+ throw new error_1.JWTErrorInvalidKey(`algorithm \`${algorithm}\` requires a secret`);
94
189
  }
95
- else if (publicKey) {
96
- // only set public key
97
- this.publicKey = (0, crypto_1.createPublicKey)(publicKey);
190
+ JWT.assertSecretKey(secret);
191
+ }
192
+ else {
193
+ if (secret) {
194
+ throw new error_1.JWTErrorInvalidKey(`algorithm \`${algorithm}\` requires an asymmetric key`);
98
195
  }
99
- this.algorithm = options.algorithm ?? "RS256";
196
+ if (privateKey)
197
+ JWT.assertAsymmetricKey(privateKey, algorithm);
198
+ if (publicKey)
199
+ JWT.assertAsymmetricKey(publicKey, algorithm);
100
200
  }
201
+ this.secret = secret;
202
+ this.privateKey = privateKey;
203
+ this.publicKey = publicKey;
204
+ this.algorithm = algorithm;
101
205
  this.issuer = options.issuer;
102
206
  this.subject = options.subject;
103
207
  this.audience = options.audience;
208
+ this.kid = options.kid;
104
209
  this.expirationTime = options.expirationTime;
105
210
  this.notBefore = options.notBefore;
106
211
  this.issuedAt = options.issuedAt;
107
212
  this.jwtID = options.jwtID;
213
+ this.requireExpiration = JWT.resolveRequireExpiration(false, options);
214
+ this.clockTolerance = JWT.assertNonNegativeNumber(options.clockTolerance === undefined ? 0 : options.clockTolerance, "clockTolerance");
215
+ this.maxTokenAge =
216
+ options.maxTokenAge === undefined
217
+ ? undefined
218
+ : JWT.assertNonNegativeNumber(options.maxTokenAge, "maxTokenAge");
219
+ if (this.expirationTime !== undefined) {
220
+ JWT.assertNumericDate(this.expirationTime, "expirationTime");
221
+ }
222
+ if (this.notBefore !== undefined) {
223
+ JWT.assertNumericDate(this.notBefore, "notBefore");
224
+ }
225
+ if (this.issuedAt !== undefined) {
226
+ JWT.assertNumericDate(this.issuedAt, "issuedAt");
227
+ }
228
+ if (this.audience !== undefined) {
229
+ JWT.assertAudience(this.audience, "audience");
230
+ }
231
+ for (const [name, value] of [
232
+ ["issuer", this.issuer],
233
+ ["subject", this.subject],
234
+ ["jwtID", this.jwtID],
235
+ ["kid", this.kid],
236
+ ]) {
237
+ if (value !== undefined && typeof value !== "string") {
238
+ throw new error_1.JWTErrorInvalidToken(`the \`${name}\` must be a string`);
239
+ }
240
+ }
108
241
  }
109
242
  /**
110
243
  * @returns The header of the token
111
244
  */
112
- buildHeader() {
113
- return {
245
+ buildHeader(options = {}) {
246
+ const kid = options.kid ?? this.kid;
247
+ if (kid !== undefined)
248
+ JWT.assertString(kid, "kid");
249
+ const header = {
114
250
  alg: this.algorithm,
115
251
  typ: "JWT",
116
252
  };
253
+ if (kid !== undefined)
254
+ header.kid = kid;
255
+ return header;
117
256
  }
118
257
  buildPayload(input, options = {}) {
258
+ if (typeof input !== "object" || input === null || Array.isArray(input)) {
259
+ throw new error_1.JWTErrorInvalidToken("the payload must be a JSON object");
260
+ }
119
261
  const rc = {
120
262
  iss: this.issuer ?? options.issuer,
121
263
  sub: this.subject ?? options.subject,
@@ -125,20 +267,53 @@ class JWT {
125
267
  iat: this.issuedAt ?? options.issuedAt ?? this.now,
126
268
  jti: this.jwtID ?? options.jwtID,
127
269
  };
128
- return { ...rc, ...input };
270
+ const payload = { ...rc };
271
+ // `undefined` means "not provided", it must not override a registered
272
+ // claim with `undefined` (JSON.stringify would silently drop it).
273
+ for (const [name, value] of Object.entries(input)) {
274
+ if (value !== undefined)
275
+ payload[name] = value;
276
+ }
277
+ for (const claim of JWT_REGISTERED_CLAIMS) {
278
+ if (payload[claim] === undefined)
279
+ delete payload[claim];
280
+ }
281
+ this.checkSignPayload(payload, options);
282
+ return payload;
283
+ }
284
+ checkSignPayload(payload, options = {}) {
285
+ const requireExpiration = JWT.resolveRequireExpiration(this.requireExpiration, options);
286
+ if (payload.exp === undefined) {
287
+ if (requireExpiration)
288
+ throw new error_1.JWTErrorExpirationRequired();
289
+ }
290
+ else {
291
+ JWT.assertNumericDate(payload.exp, "exp");
292
+ }
293
+ if (payload.nbf !== undefined)
294
+ JWT.assertNumericDate(payload.nbf, "nbf");
295
+ if (payload.iat !== undefined)
296
+ JWT.assertNumericDate(payload.iat, "iat");
297
+ for (const claim of ["iss", "sub", "jti"]) {
298
+ if (payload[claim] !== undefined) {
299
+ JWT.assertString(payload[claim], claim);
300
+ }
301
+ }
302
+ if (payload.aud !== undefined)
303
+ JWT.assertAudience(payload.aud, "aud");
304
+ const kid = options.kid ?? this.kid;
305
+ if (kid !== undefined)
306
+ JWT.assertString(kid, "kid");
129
307
  }
130
308
  buildSignature(input, algorithm, encoding) {
131
- switch (algorithm) {
132
- case "HS256":
133
- case "HS384":
134
- case "HS512":
309
+ const info = JWT.algorithmInfo(algorithm);
310
+ switch (info.family) {
311
+ case "hmac":
135
312
  return this.buildSignatureHmac(input, algorithm, encoding);
136
- case "RS256":
137
- case "RS384":
138
- case "RS512":
139
- return this.buildSignatureSign(input, algorithm, encoding);
140
- default:
141
- throw new error_1.JWTErrorAlgorithmNotSupport(algorithm);
313
+ case "rsa":
314
+ case "pss":
315
+ case "ec":
316
+ return this.buildSignatureAsymmetric(input, algorithm, encoding);
142
317
  }
143
318
  }
144
319
  buildSignatureHmac(input, algorithm, encoding) {
@@ -148,32 +323,44 @@ class JWT {
148
323
  hmac.update(input, encoding);
149
324
  return hmac.digest("base64url");
150
325
  }
151
- buildSignatureSign(input, algorithm, encoding) {
326
+ buildSignatureAsymmetric(input, algorithm, encoding) {
152
327
  if (!this.privateKey)
153
328
  throw new error_1.JWTErrorPrivateKeyNotFound();
154
- const sign = (0, crypto_1.createSign)(JWT.hashAlgorithm(algorithm));
329
+ const info = JWT.algorithmInfo(algorithm);
330
+ const sign = (0, crypto_1.createSign)(info.hash);
155
331
  sign.update(input, encoding);
156
332
  sign.end();
157
- return sign.sign(this.privateKey, "base64url");
333
+ switch (info.family) {
334
+ case "ec":
335
+ return sign.sign({ key: this.privateKey, dsaEncoding: "ieee-p1363" }, "base64url");
336
+ case "pss":
337
+ return sign.sign({
338
+ key: this.privateKey,
339
+ padding: crypto_1.constants.RSA_PKCS1_PSS_PADDING,
340
+ saltLength: crypto_1.constants.RSA_PSS_SALTLEN_DIGEST,
341
+ }, "base64url");
342
+ default:
343
+ return sign.sign(this.privateKey, "base64url");
344
+ }
158
345
  }
159
346
  /**
160
347
  * @param input The payload of the token
161
348
  * @returns The signed token
162
349
  */
163
350
  sign(input, options = {}) {
164
- const h = JWT.encode(this.buildHeader());
351
+ const h = JWT.encode(this.buildHeader(options));
165
352
  const p = JWT.encode(this.buildPayload(input, options));
166
353
  const hp = `${h}.${p}`;
167
354
  const s = this.buildSignature(hp, this.algorithm, "utf-8");
168
355
  return `${hp}.${s}`;
169
356
  }
170
- checkHeader(input) {
357
+ checkHeader(input, options = {}) {
171
358
  // the header is not trusted, check the types before use
172
359
  const typ = input.typ;
173
- if (typ !== undefined && typ !== null && typeof typ !== "string") {
360
+ if (typ !== undefined && typeof typ !== "string") {
174
361
  throw new error_1.JWTErrorInvalidToken("the `typ` must be a string");
175
362
  }
176
- if (typ && typ !== "JWT") {
363
+ if (typ !== undefined && typ !== "JWT") {
177
364
  throw new error_1.JWTErrorInvalidType(typ);
178
365
  }
179
366
  const alg = input.alg;
@@ -184,87 +371,163 @@ class JWT {
184
371
  if (alg !== this.algorithm) {
185
372
  throw new error_1.JWTErrorInvalidAlgorithm(alg, this.algorithm);
186
373
  }
374
+ // the algorithm must be supported, even if the instance was mutated
375
+ JWT.algorithmInfo(alg);
376
+ const kid = input.kid;
377
+ if (kid !== undefined && typeof kid !== "string") {
378
+ throw new error_1.JWTErrorInvalidToken("the `kid` must be a string");
379
+ }
380
+ const expectedKid = options.kid ?? this.kid;
381
+ if (expectedKid !== undefined && kid !== expectedKid) {
382
+ throw new error_1.JWTErrorInvalidToken(`the \`kid\` must be \`${expectedKid}\``);
383
+ }
187
384
  }
188
385
  checkPayload(input, options = {}) {
386
+ const payload = input;
189
387
  // check issuer
190
388
  const iss = this.issuer ?? options.issuer;
191
- if (iss && iss !== input.iss) {
192
- throw new error_1.JWTErrorInvalidIssuer(input.iss, iss);
389
+ if (iss !== undefined &&
390
+ (typeof payload.iss !== "string" || payload.iss !== iss)) {
391
+ throw new error_1.JWTErrorInvalidIssuer(payload.iss, iss);
193
392
  }
194
393
  // check subject
195
394
  const sub = this.subject ?? options.subject;
196
- if (sub && sub !== input.sub) {
197
- throw new error_1.JWTErrorInvalidSubject(input.sub, sub);
395
+ if (sub !== undefined &&
396
+ (typeof payload.sub !== "string" || payload.sub !== sub)) {
397
+ throw new error_1.JWTErrorInvalidSubject(payload.sub, sub);
198
398
  }
199
399
  // check audience
200
400
  const aud = this.audience ?? options.audience;
201
- if (aud && aud !== input.aud) {
202
- throw new error_1.JWTErrorInvalidAudience(input.aud, aud);
401
+ if (aud !== undefined) {
402
+ const expect = Array.isArray(aud) ? aud : [aud];
403
+ let actual;
404
+ if (payload.aud === undefined) {
405
+ actual = [];
406
+ }
407
+ else if (typeof payload.aud === "string") {
408
+ actual = [payload.aud];
409
+ }
410
+ else if (Array.isArray(payload.aud) &&
411
+ payload.aud.every((item) => typeof item === "string")) {
412
+ actual = payload.aud;
413
+ }
414
+ else {
415
+ throw new error_1.JWTErrorInvalidAudience(payload.aud, aud);
416
+ }
417
+ if (!expect.some((item) => actual.includes(item))) {
418
+ throw new error_1.JWTErrorInvalidAudience(payload.aud, aud);
419
+ }
420
+ }
421
+ // check jwt id
422
+ const jti = this.jwtID ?? options.jwtID;
423
+ if (jti !== undefined &&
424
+ (typeof payload.jti !== "string" || payload.jti !== jti)) {
425
+ throw new error_1.JWTErrorInvalidJwtId(payload.jti, jti);
203
426
  }
204
- const n = JWT.ms2s(options.currentTime ?? Date.now());
205
- // a not finite current time would pass every time check
206
- if (!Number.isFinite(n)) {
427
+ const currentTime = options.currentTime === undefined ? Date.now() : options.currentTime;
428
+ if (typeof currentTime !== "number" || !Number.isFinite(currentTime)) {
207
429
  throw new TypeError("The `currentTime` must be a finite number");
208
430
  }
431
+ const now = JWT.ms2s(currentTime);
432
+ const clockTolerance = options.clockTolerance === undefined
433
+ ? this.clockTolerance
434
+ : JWT.assertNonNegativeNumber(options.clockTolerance, "clockTolerance");
435
+ const maxTokenAge = options.maxTokenAge === undefined
436
+ ? this.maxTokenAge
437
+ : options.maxTokenAge;
438
+ const maxAge = maxTokenAge === undefined
439
+ ? undefined
440
+ : JWT.assertNonNegativeNumber(maxTokenAge, "maxTokenAge");
209
441
  // check expiration time, the current time must be before `exp`
210
- const exp = input.exp;
211
- if (exp !== undefined && exp !== null) {
212
- if (typeof exp !== "number" || !Number.isFinite(exp)) {
213
- throw new error_1.JWTErrorInvalidToken("the `exp` must be a number");
214
- }
215
- if (exp <= n)
442
+ const requireExpiration = JWT.resolveRequireExpiration(this.requireExpiration, options);
443
+ if (payload.exp === undefined) {
444
+ if (requireExpiration)
445
+ throw new error_1.JWTErrorExpirationRequired();
446
+ }
447
+ else {
448
+ const exp = JWT.assertNumericDate(payload.exp, "exp");
449
+ if (exp <= now - clockTolerance)
216
450
  throw new error_1.JWTErrorExpired(exp);
217
451
  }
218
452
  // check not before
219
- const nbf = input.nbf;
220
- if (nbf !== undefined && nbf !== null) {
221
- if (typeof nbf !== "number" || !Number.isFinite(nbf)) {
222
- throw new error_1.JWTErrorInvalidToken("the `nbf` must be a number");
223
- }
224
- if (nbf > n)
453
+ if (payload.nbf !== undefined) {
454
+ const nbf = JWT.assertNumericDate(payload.nbf, "nbf");
455
+ if (nbf > now + clockTolerance)
225
456
  throw new error_1.JWTErrorNotBefore(nbf);
226
457
  }
227
- // check jwt id
228
- const jti = this.jwtID ?? options.jwtID;
229
- if (jti && jti !== input.jti) {
230
- throw new error_1.JWTErrorInvalidJwtId(input.jti, jti);
458
+ // check issued at
459
+ let issuedAt;
460
+ if (payload.iat !== undefined) {
461
+ issuedAt = JWT.assertNumericDate(payload.iat, "iat");
462
+ }
463
+ // check maximum token age
464
+ if (maxAge !== undefined) {
465
+ if (issuedAt === undefined) {
466
+ throw new error_1.JWTErrorInvalidToken("the `iat` is required when `maxTokenAge` is set");
467
+ }
468
+ if (now - issuedAt > maxAge + clockTolerance) {
469
+ throw new error_1.JWTErrorTokenTooOld(issuedAt, maxAge);
470
+ }
231
471
  }
232
472
  }
233
473
  checkSignature(signature, input, algorithm, encoding = "utf-8") {
234
- switch (this.algorithm) {
235
- case "HS256":
236
- case "HS384":
237
- case "HS512":
238
- return this.checkSignatureHmac(signature, input, algorithm, encoding);
239
- case "RS256":
240
- case "RS384":
241
- case "RS512":
242
- return this.checkSignatureVerify(signature, input, algorithm, encoding);
243
- default:
244
- throw new error_1.JWTErrorAlgorithmNotSupport(algorithm);
474
+ let sig;
475
+ try {
476
+ sig = JWT.decodeBase64Url(signature);
245
477
  }
478
+ catch {
479
+ throw new error_1.JWTErrorInvalidSignature();
480
+ }
481
+ const info = JWT.algorithmInfo(algorithm);
482
+ if (info.family === "hmac") {
483
+ return this.checkSignatureHmac(sig, input, algorithm, encoding);
484
+ }
485
+ return this.checkSignatureAsymmetric(sig, input, algorithm, encoding);
246
486
  }
247
487
  checkSignatureHmac(signature, input, algorithm, encoding = "utf-8") {
248
- const expect = Buffer.from(this.buildSignature(input, algorithm, encoding), "utf-8");
249
- const actual = Buffer.from(signature, "utf-8");
488
+ const expect = Buffer.from(this.buildSignatureHmac(input, algorithm, encoding), "base64url");
250
489
  // compare in constant time
251
- if (expect.length !== actual.length || !(0, crypto_1.timingSafeEqual)(expect, actual)) {
490
+ if (expect.length !== signature.length ||
491
+ !(0, crypto_1.timingSafeEqual)(expect, signature)) {
252
492
  throw new error_1.JWTErrorInvalidSignature();
253
493
  }
254
494
  }
255
- checkSignatureVerify(signature, input, algorithm, encoding = "utf-8") {
495
+ checkSignatureAsymmetric(signature, input, algorithm, encoding = "utf-8") {
256
496
  if (!this.publicKey) {
257
497
  throw new error_1.JWTErrorPublicKeyNotFound();
258
498
  }
259
- // the base64 url decoder is lenient, only accept the canonical encoding
260
- const sig = Buffer.from(signature, "base64url");
261
- if (sig.toString("base64url") !== signature) {
499
+ const info = JWT.algorithmInfo(algorithm);
500
+ if (info.family === "ec" &&
501
+ info.signatureLength !== undefined &&
502
+ signature.length !== info.signatureLength) {
262
503
  throw new error_1.JWTErrorInvalidSignature();
263
504
  }
264
- const verify = (0, crypto_1.createVerify)(JWT.hashAlgorithm(algorithm));
505
+ const verify = (0, crypto_1.createVerify)(info.hash);
265
506
  verify.update(input, encoding);
266
507
  verify.end();
267
- if (!verify.verify(this.publicKey, sig)) {
508
+ let valid;
509
+ try {
510
+ switch (info.family) {
511
+ case "ec":
512
+ valid = verify.verify({ key: this.publicKey, dsaEncoding: "ieee-p1363" }, signature);
513
+ break;
514
+ case "pss":
515
+ valid = verify.verify({
516
+ key: this.publicKey,
517
+ padding: crypto_1.constants.RSA_PKCS1_PSS_PADDING,
518
+ saltLength: crypto_1.constants.RSA_PSS_SALTLEN_DIGEST,
519
+ }, signature);
520
+ break;
521
+ default:
522
+ valid = verify.verify(this.publicKey, signature);
523
+ break;
524
+ }
525
+ }
526
+ catch {
527
+ // Node may throw for malformed signatures instead of returning false.
528
+ throw new error_1.JWTErrorInvalidSignature();
529
+ }
530
+ if (!valid) {
268
531
  throw new error_1.JWTErrorInvalidSignature();
269
532
  }
270
533
  }
@@ -282,9 +545,10 @@ class JWT {
282
545
  throw new error_1.JWTErrorInvalidTokenLength(parts.length);
283
546
  }
284
547
  const [header, payload, signature] = parts;
285
- // check header
548
+ // decode the header only to learn the algorithm, never trust it before
549
+ // the signature is verified
286
550
  const h = JWT.decodeObject(header, "header");
287
- this.checkHeader(h);
551
+ this.checkHeader(h, options);
288
552
  // check signature, before anything in payload is trusted
289
553
  const hp = `${header}.${payload}`;
290
554
  this.checkSignature(signature, hp, h.alg);
@@ -305,10 +569,10 @@ class JWT {
305
569
  r = JWT.decode(data);
306
570
  }
307
571
  catch {
308
- throw new error_1.JWTErrorInvalidToken(`the ${part} is not valid JSON`);
572
+ throw new error_1.JWTErrorMalformed(`the ${part} is not valid base64url or JSON`);
309
573
  }
310
574
  if (typeof r !== "object" || r === null || Array.isArray(r)) {
311
- throw new error_1.JWTErrorInvalidToken(`the ${part} must be a JSON object`);
575
+ throw new error_1.JWTErrorMalformed(`the ${part} must be a JSON object`);
312
576
  }
313
577
  return r;
314
578
  }
@@ -318,11 +582,208 @@ class JWT {
318
582
  * @returns hash algorithm
319
583
  */
320
584
  static hashAlgorithm(algorithm) {
321
- const a = JWT_HASH_ALGORITHM_MAP[algorithm];
322
- if (!a) {
585
+ return JWT.algorithmInfo(algorithm).hash;
586
+ }
587
+ static algorithmInfo(algorithm) {
588
+ if (typeof algorithm !== "string" ||
589
+ !Object.prototype.hasOwnProperty.call(JWT_ALGORITHM_MAP, algorithm)) {
590
+ throw new error_1.JWTErrorAlgorithmNotSupport(String(algorithm));
591
+ }
592
+ const info = JWT_ALGORITHM_MAP[algorithm];
593
+ if (!info) {
323
594
  throw new error_1.JWTErrorAlgorithmNotSupport(algorithm);
324
595
  }
325
- return a;
596
+ return info;
597
+ }
598
+ static defaultAlgorithm(key) {
599
+ if (key.type === "secret")
600
+ return "HS256";
601
+ switch (key.asymmetricKeyType) {
602
+ case "rsa":
603
+ return "RS256";
604
+ case "rsa-pss":
605
+ return "PS256";
606
+ case "ec": {
607
+ const curve = JWT.normalizeCurve(key.asymmetricKeyDetails?.namedCurve);
608
+ switch (curve) {
609
+ case "prime256v1":
610
+ return "ES256";
611
+ case "secp384r1":
612
+ return "ES384";
613
+ case "secp521r1":
614
+ return "ES512";
615
+ case "secp256k1":
616
+ return "ES256K";
617
+ default:
618
+ throw new error_1.JWTErrorInvalidKey(`unsupported EC curve \`${String(curve)}\``);
619
+ }
620
+ }
621
+ default:
622
+ throw new error_1.JWTErrorInvalidKey(`unsupported key type \`${String(key.asymmetricKeyType)}\``);
623
+ }
624
+ }
625
+ static normalizeCurve(curve) {
626
+ switch (curve) {
627
+ case "P-256":
628
+ case "prime256v1":
629
+ case "secp256r1":
630
+ return "prime256v1";
631
+ case "P-384":
632
+ case "secp384r1":
633
+ return "secp384r1";
634
+ case "P-521":
635
+ case "secp521r1":
636
+ return "secp521r1";
637
+ case "secp256k1":
638
+ return "secp256k1";
639
+ default:
640
+ return curve;
641
+ }
642
+ }
643
+ static toSecretKey(input) {
644
+ if (input instanceof crypto_1.KeyObject) {
645
+ if (input.type !== "secret") {
646
+ throw new error_1.JWTErrorInvalidKey("an asymmetric key must be passed as `privateKey` or `publicKey`");
647
+ }
648
+ JWT.assertSecretKey(input);
649
+ return input;
650
+ }
651
+ let buf;
652
+ if (typeof input === "string") {
653
+ buf = Buffer.from(input, "utf-8");
654
+ }
655
+ else if (Buffer.isBuffer(input)) {
656
+ buf = input;
657
+ }
658
+ else {
659
+ throw new error_1.JWTErrorInvalidKey("the secret must be a string, a Buffer, or a secret KeyObject");
660
+ }
661
+ if (buf.includes(JWT_PEM_MARKER)) {
662
+ throw new error_1.JWTErrorInvalidKey("a PEM key must be passed as `privateKey` or `publicKey`");
663
+ }
664
+ let key;
665
+ try {
666
+ key = (0, crypto_1.createSecretKey)(buf);
667
+ }
668
+ catch (error) {
669
+ throw new error_1.JWTErrorInvalidKey(`invalid secret: ${JWT.errorMessage(error)}`);
670
+ }
671
+ JWT.assertSecretKey(key);
672
+ return key;
673
+ }
674
+ static toPrivateKey(input) {
675
+ if (input instanceof crypto_1.KeyObject) {
676
+ if (input.type !== "private") {
677
+ throw new error_1.JWTErrorInvalidKey("`privateKey` must be a private key");
678
+ }
679
+ return input;
680
+ }
681
+ try {
682
+ return (0, crypto_1.createPrivateKey)(input);
683
+ }
684
+ catch (error) {
685
+ throw new error_1.JWTErrorInvalidKey(`invalid private key: ${JWT.errorMessage(error)}`);
686
+ }
687
+ }
688
+ static toPublicKey(input) {
689
+ if (input instanceof crypto_1.KeyObject) {
690
+ if (input.type === "public")
691
+ return input;
692
+ if (input.type === "private") {
693
+ try {
694
+ return (0, crypto_1.createPublicKey)(input);
695
+ }
696
+ catch (error) {
697
+ throw new error_1.JWTErrorInvalidKey(`invalid public key: ${JWT.errorMessage(error)}`);
698
+ }
699
+ }
700
+ throw new error_1.JWTErrorInvalidKey("`publicKey` must be a public or private key");
701
+ }
702
+ try {
703
+ return (0, crypto_1.createPublicKey)(input);
704
+ }
705
+ catch (error) {
706
+ throw new error_1.JWTErrorInvalidKey(`invalid public key: ${JWT.errorMessage(error)}`);
707
+ }
708
+ }
709
+ static assertSecretKey(key) {
710
+ if (key.type !== "secret") {
711
+ throw new error_1.JWTErrorInvalidKey("the secret must be a symmetric key");
712
+ }
713
+ if ((key.symmetricKeySize ?? 0) < JWT_MIN_SECRET_BYTES) {
714
+ throw new error_1.JWTErrorInvalidKey(`the secret must be at least ${JWT_MIN_SECRET_BYTES} bytes`);
715
+ }
716
+ }
717
+ static assertAsymmetricKey(key, algorithm) {
718
+ const info = JWT.algorithmInfo(algorithm);
719
+ const type = key.asymmetricKeyType;
720
+ const details = key.asymmetricKeyDetails;
721
+ if (info.family === "rsa" || info.family === "pss") {
722
+ if (type !== "rsa" && !(info.family === "pss" && type === "rsa-pss")) {
723
+ throw new error_1.JWTErrorInvalidKey(`algorithm \`${algorithm}\` requires an RSA key`);
724
+ }
725
+ const modulusLength = details?.modulusLength ?? 0;
726
+ if (modulusLength < JWT_MIN_RSA_MODULUS_BITS) {
727
+ throw new error_1.JWTErrorInvalidKey(`the RSA modulus must be at least ${JWT_MIN_RSA_MODULUS_BITS} bits`);
728
+ }
729
+ return;
730
+ }
731
+ if (info.family === "ec") {
732
+ if (type !== "ec") {
733
+ throw new error_1.JWTErrorInvalidKey(`algorithm \`${algorithm}\` requires an EC key`);
734
+ }
735
+ const curve = JWT.normalizeCurve(details?.namedCurve);
736
+ if (curve !== info.curve) {
737
+ throw new error_1.JWTErrorInvalidKey(`algorithm \`${algorithm}\` requires the \`${String(info.curve)}\` curve`);
738
+ }
739
+ return;
740
+ }
741
+ throw new error_1.JWTErrorInvalidKey(`algorithm \`${algorithm}\` requires a secret`);
742
+ }
743
+ static errorMessage(error) {
744
+ return error instanceof Error ? error.message : String(error);
745
+ }
746
+ static resolveRequireExpiration(defaultValue, options) {
747
+ if (options.requireExpiration !== undefined) {
748
+ if (typeof options.requireExpiration !== "boolean") {
749
+ throw new TypeError("The `requireExpiration` must be a boolean");
750
+ }
751
+ return options.requireExpiration;
752
+ }
753
+ if (options.allowNoExpiration !== undefined) {
754
+ if (typeof options.allowNoExpiration !== "boolean") {
755
+ throw new TypeError("The `allowNoExpiration` must be a boolean");
756
+ }
757
+ return !options.allowNoExpiration;
758
+ }
759
+ return defaultValue;
760
+ }
761
+ static assertNumericDate(value, claim) {
762
+ if (typeof value !== "number" || !Number.isFinite(value)) {
763
+ throw new error_1.JWTErrorInvalidToken(`the \`${claim}\` must be a finite number`);
764
+ }
765
+ return value;
766
+ }
767
+ static assertNonNegativeNumber(value, name) {
768
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0) {
769
+ throw new TypeError(`The \`${name}\` must be a non-negative finite number`);
770
+ }
771
+ return value;
772
+ }
773
+ static assertString(value, claim) {
774
+ if (typeof value !== "string") {
775
+ throw new error_1.JWTErrorInvalidToken(`the \`${claim}\` must be a string`);
776
+ }
777
+ return value;
778
+ }
779
+ static assertAudience(value, claim) {
780
+ if (typeof value === "string")
781
+ return value;
782
+ if (Array.isArray(value) &&
783
+ value.every((item) => typeof item === "string")) {
784
+ return value;
785
+ }
786
+ throw new error_1.JWTErrorInvalidToken(`the \`${claim}\` must be a string or an array of strings`);
326
787
  }
327
788
  /**
328
789
  * Decode base64 url data
@@ -330,7 +791,28 @@ class JWT {
330
791
  * @returns The decoded data
331
792
  */
332
793
  static decode(data, encoding = "utf-8") {
333
- return JSON.parse(Buffer.from(data, "base64url").toString(encoding));
794
+ const text = JWT.decodeBase64Url(data).toString(encoding);
795
+ try {
796
+ return JSON.parse(text);
797
+ }
798
+ catch {
799
+ throw new error_1.JWTErrorMalformed("the token is not valid JSON");
800
+ }
801
+ }
802
+ /**
803
+ * Decode a base64url segment, rejecting anything that is not the canonical
804
+ * unpadded encoding. This prevents multiple valid serializations of the same
805
+ * token from bypassing exact-string checks.
806
+ */
807
+ static decodeBase64Url(data) {
808
+ if (typeof data !== "string" || !/^[A-Za-z0-9_-]*$/.test(data)) {
809
+ throw new error_1.JWTErrorMalformed("the token is not valid base64url");
810
+ }
811
+ const decoded = Buffer.from(data, "base64url");
812
+ if (decoded.toString("base64url") !== data) {
813
+ throw new error_1.JWTErrorMalformed("the token is not canonical base64url");
814
+ }
815
+ return decoded;
334
816
  }
335
817
  /**
336
818
  * Encode data to base64 url
@@ -349,10 +831,16 @@ class JWT {
349
831
  if (typeof input !== "string") {
350
832
  throw new error_1.JWTErrorInvalidToken("the token must be a string");
351
833
  }
352
- const r = input.split(".", 3);
834
+ const r = input.split(".", 4);
353
835
  if (r.length !== 3) {
354
836
  throw new error_1.JWTErrorInvalidTokenLength(r.length);
355
837
  }
838
+ for (const part of r) {
839
+ if (part.length === 0) {
840
+ throw new error_1.JWTErrorMalformed("the token has an empty part");
841
+ }
842
+ JWT.decodeBase64Url(part);
843
+ }
356
844
  return r;
357
845
  }
358
846
  /**