@liuhlightning/jwt 0.3.6 → 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,89 +323,211 @@ 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) {
171
- if (input.typ && input.typ !== "JWT") {
172
- throw new error_1.JWTErrorInvalidType(input.typ);
357
+ checkHeader(input, options = {}) {
358
+ // the header is not trusted, check the types before use
359
+ const typ = input.typ;
360
+ if (typ !== undefined && typeof typ !== "string") {
361
+ throw new error_1.JWTErrorInvalidToken("the `typ` must be a string");
362
+ }
363
+ if (typ !== undefined && typ !== "JWT") {
364
+ throw new error_1.JWTErrorInvalidType(typ);
365
+ }
366
+ const alg = input.alg;
367
+ if (typeof alg !== "string") {
368
+ throw new error_1.JWTErrorInvalidToken("the `alg` must be a string");
369
+ }
370
+ // the token must be signed by the algorithm of this instance
371
+ if (alg !== this.algorithm) {
372
+ throw new error_1.JWTErrorInvalidAlgorithm(alg, this.algorithm);
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}\``);
173
383
  }
174
384
  }
175
385
  checkPayload(input, options = {}) {
386
+ const payload = input;
176
387
  // check issuer
177
388
  const iss = this.issuer ?? options.issuer;
178
- if (iss && iss !== input.iss) {
179
- 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);
180
392
  }
181
393
  // check subject
182
394
  const sub = this.subject ?? options.subject;
183
- if (sub && sub !== input.sub) {
184
- 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);
185
398
  }
186
399
  // check audience
187
400
  const aud = this.audience ?? options.audience;
188
- if (aud && aud !== input.aud) {
189
- 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
+ }
190
420
  }
191
- const n = JWT.ms2s(options.currentTime ?? Date.now());
192
- // check expiration time
193
- if (typeof input.exp === "number" && input.exp < n) {
194
- throw new error_1.JWTErrorExpired(input.exp);
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);
426
+ }
427
+ const currentTime = options.currentTime === undefined ? Date.now() : options.currentTime;
428
+ if (typeof currentTime !== "number" || !Number.isFinite(currentTime)) {
429
+ throw new TypeError("The `currentTime` must be a finite number");
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");
441
+ // check expiration time, the current time must be before `exp`
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)
450
+ throw new error_1.JWTErrorExpired(exp);
195
451
  }
196
452
  // check not before
197
- if (typeof input.nbf === "number" && input.nbf > n) {
198
- throw new error_1.JWTErrorNotBefore(input.nbf);
453
+ if (payload.nbf !== undefined) {
454
+ const nbf = JWT.assertNumericDate(payload.nbf, "nbf");
455
+ if (nbf > now + clockTolerance)
456
+ throw new error_1.JWTErrorNotBefore(nbf);
199
457
  }
200
- // check jwt id
201
- const jti = this.jwtID ?? options.jwtID;
202
- if (jti && jti !== input.jti) {
203
- 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
+ }
204
471
  }
205
472
  }
206
473
  checkSignature(signature, input, algorithm, encoding = "utf-8") {
207
- switch (this.algorithm) {
208
- case "HS256":
209
- case "HS384":
210
- case "HS512":
211
- return this.checkSignatureHmac(signature, input, algorithm, encoding);
212
- case "RS256":
213
- case "RS384":
214
- case "RS512":
215
- return this.checkSignatureVerify(signature, input, algorithm, encoding);
216
- default:
217
- throw new error_1.JWTErrorAlgorithmNotSupport(algorithm);
474
+ let sig;
475
+ try {
476
+ sig = JWT.decodeBase64Url(signature);
477
+ }
478
+ catch {
479
+ throw new error_1.JWTErrorInvalidSignature();
218
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);
219
486
  }
220
487
  checkSignatureHmac(signature, input, algorithm, encoding = "utf-8") {
221
- const s = this.buildSignature(input, algorithm, encoding);
222
- if (s !== signature) {
488
+ const expect = Buffer.from(this.buildSignatureHmac(input, algorithm, encoding), "base64url");
489
+ // compare in constant time
490
+ if (expect.length !== signature.length ||
491
+ !(0, crypto_1.timingSafeEqual)(expect, signature)) {
223
492
  throw new error_1.JWTErrorInvalidSignature();
224
493
  }
225
494
  }
226
- checkSignatureVerify(signature, input, algorithm, encoding = "utf-8") {
495
+ checkSignatureAsymmetric(signature, input, algorithm, encoding = "utf-8") {
227
496
  if (!this.publicKey) {
228
497
  throw new error_1.JWTErrorPublicKeyNotFound();
229
498
  }
230
- const verify = (0, crypto_1.createVerify)(JWT.hashAlgorithm(algorithm));
499
+ const info = JWT.algorithmInfo(algorithm);
500
+ if (info.family === "ec" &&
501
+ info.signatureLength !== undefined &&
502
+ signature.length !== info.signatureLength) {
503
+ throw new error_1.JWTErrorInvalidSignature();
504
+ }
505
+ const verify = (0, crypto_1.createVerify)(info.hash);
231
506
  verify.update(input, encoding);
232
507
  verify.end();
233
- if (!verify.verify(this.publicKey, signature, "base64url")) {
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) {
234
531
  throw new error_1.JWTErrorInvalidSignature();
235
532
  }
236
533
  }
@@ -239,29 +536,254 @@ class JWT {
239
536
  * @returns The payload of the token
240
537
  */
241
538
  verify(input, options = {}) {
242
- const [header, payload, signature] = JWT.parse(input);
243
- // check header
244
- const h = JWT.decode(header);
245
- this.checkHeader(h);
246
- // check payload
247
- const p = JWT.decode(payload);
248
- this.checkPayload(p, options);
249
- // check signature
539
+ if (typeof input !== "string") {
540
+ throw new error_1.JWTErrorInvalidToken("the token must be a string");
541
+ }
542
+ // the token must be exactly 3 parts, limit the split for a huge input
543
+ const parts = input.split(".", 4);
544
+ if (parts.length !== 3) {
545
+ throw new error_1.JWTErrorInvalidTokenLength(parts.length);
546
+ }
547
+ const [header, payload, signature] = parts;
548
+ // decode the header only to learn the algorithm, never trust it before
549
+ // the signature is verified
550
+ const h = JWT.decodeObject(header, "header");
551
+ this.checkHeader(h, options);
552
+ // check signature, before anything in payload is trusted
250
553
  const hp = `${header}.${payload}`;
251
554
  this.checkSignature(signature, hp, h.alg);
555
+ // check payload
556
+ const p = JWT.decodeObject(payload, "payload");
557
+ this.checkPayload(p, options);
252
558
  return p;
253
559
  }
560
+ /**
561
+ * Decode a token part, which must be a JSON object
562
+ * @param data The base64 url encoded data
563
+ * @param part The name of the part, used in error message
564
+ * @returns The decoded object
565
+ */
566
+ static decodeObject(data, part) {
567
+ let r;
568
+ try {
569
+ r = JWT.decode(data);
570
+ }
571
+ catch {
572
+ throw new error_1.JWTErrorMalformed(`the ${part} is not valid base64url or JSON`);
573
+ }
574
+ if (typeof r !== "object" || r === null || Array.isArray(r)) {
575
+ throw new error_1.JWTErrorMalformed(`the ${part} must be a JSON object`);
576
+ }
577
+ return r;
578
+ }
254
579
  /**
255
580
  * Read hash algorithm
256
581
  * @param algorithm jwt algorithm
257
582
  * @returns hash algorithm
258
583
  */
259
584
  static hashAlgorithm(algorithm) {
260
- const a = JWT_HASH_ALGORITHM_MAP[algorithm];
261
- 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) {
262
594
  throw new error_1.JWTErrorAlgorithmNotSupport(algorithm);
263
595
  }
264
- 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`);
265
787
  }
266
788
  /**
267
789
  * Decode base64 url data
@@ -269,7 +791,28 @@ class JWT {
269
791
  * @returns The decoded data
270
792
  */
271
793
  static decode(data, encoding = "utf-8") {
272
- 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;
273
816
  }
274
817
  /**
275
818
  * Encode data to base64 url
@@ -285,10 +828,19 @@ class JWT {
285
828
  * @returns The header, payload, and signature of the token
286
829
  */
287
830
  static parse(input) {
288
- const r = input.split(".", 3);
831
+ if (typeof input !== "string") {
832
+ throw new error_1.JWTErrorInvalidToken("the token must be a string");
833
+ }
834
+ const r = input.split(".", 4);
289
835
  if (r.length !== 3) {
290
836
  throw new error_1.JWTErrorInvalidTokenLength(r.length);
291
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
+ }
292
844
  return r;
293
845
  }
294
846
  /**