@liuhlightning/jwt 0.3.6 → 0.4.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 CHANGED
@@ -33,3 +33,86 @@ const token = jwt.sign({ uid: 1234, username: "alex" });
33
33
  ```typescript
34
34
  const payload = jwt.verify("input token");
35
35
  ```
36
+
37
+ `verify` throws a `JWTError` subclass (e.g. `JWTErrorInvalidSignature`, `JWTErrorExpired`) when the token is not valid.
38
+
39
+ ```typescript
40
+ import { JWTError } from "@liuhlightning/jwt";
41
+
42
+ try {
43
+ const payload = jwt.verify("input token");
44
+ } catch (err) {
45
+ if (err instanceof JWTError) {
46
+ // invalid token
47
+ }
48
+ }
49
+ ```
50
+
51
+ ## Algorithms
52
+
53
+ | Algorithm | Key |
54
+ | ----------------------- | ------------------------ |
55
+ | `HS256` `HS384` `HS512` | secret (string / Buffer) |
56
+ | `RS256` `RS384` `RS512` | RSA private / public key |
57
+
58
+ The default is `HS256` for a secret, and `RS256` for a private / public key.
59
+ The `alg` in the token header must be the same as the algorithm of the instance.
60
+
61
+ ### Use RSA key
62
+
63
+ ```typescript
64
+ // sign and verify, the public key is derived from the private key
65
+ const signer = new JWT({ privateKey: "-----BEGIN PRIVATE KEY-----..." });
66
+ const token = signer.sign({ uid: 1234 });
67
+
68
+ // verify only
69
+ const verifier = new JWT(
70
+ { publicKey: "-----BEGIN PUBLIC KEY-----..." },
71
+ { algorithm: "RS256" },
72
+ );
73
+ const payload = verifier.verify(token);
74
+ ```
75
+
76
+ A JWK is also supported.
77
+
78
+ ```typescript
79
+ const verifier = new JWT({ publicKey: { format: "jwk", key: jwk } });
80
+ ```
81
+
82
+ ## Options
83
+
84
+ ### Constructor
85
+
86
+ ```typescript
87
+ const jwt = new JWT("your jwt secret", {
88
+ algorithm: "HS512",
89
+ issuer: "my-service",
90
+ });
91
+ ```
92
+
93
+ | Option | Claim | Description |
94
+ | ---------------- | ----- | -------------------------------------------------------- |
95
+ | `algorithm` | | The algorithm used to sign and verify |
96
+ | `issuer` | `iss` | Set when sign, and must be the same when verify |
97
+ | `subject` | `sub` | Set when sign, and must be the same when verify |
98
+ | `audience` | `aud` | Set when sign, and must be the same when verify |
99
+ | `jwtID` | `jti` | Set when sign, and must be the same when verify |
100
+ | `expirationTime` | `exp` | Unix timestamp in seconds, set when sign |
101
+ | `notBefore` | `nbf` | Unix timestamp in seconds, set when sign |
102
+ | `issuedAt` | `iat` | Unix timestamp in seconds, set when sign, default is now |
103
+
104
+ `expirationTime`, `notBefore` and `issuedAt` are absolute timestamps, not durations.
105
+ To make every token expire after a period, set `exp` in the payload.
106
+
107
+ ```typescript
108
+ const token = jwt.sign({ uid: 1234, exp: jwt.now + 3600 });
109
+ ```
110
+
111
+ ### Sign and verify
112
+
113
+ `sign(payload, options)` accepts `issuer`, `subject`, `audience`, `jwtID`, `expirationTime`, `notBefore` and `issuedAt`.
114
+
115
+ `verify(token, options)` accepts `issuer`, `subject`, `audience`, `jwtID`, and `currentTime` (in milliseconds, default is `Date.now()`).
116
+ A `currentTime` that is not a finite number is a mistake of the caller, so `verify` throws a `TypeError` for it.
117
+
118
+ The options of the instance take precedence over the options of `sign` / `verify`, and the claims in the payload take precedence over both when sign.
package/dist/error.d.ts CHANGED
@@ -43,4 +43,10 @@ export declare class JWTErrorPublicKeyNotFound extends JWTError {
43
43
  export declare class JWTErrorInvalidTokenLength extends JWTError {
44
44
  constructor(len: number);
45
45
  }
46
+ export declare class JWTErrorInvalidAlgorithm extends JWTError {
47
+ constructor(algorithm: unknown, expect: string);
48
+ }
49
+ export declare class JWTErrorInvalidToken extends JWTError {
50
+ constructor(reason: string);
51
+ }
46
52
  //# sourceMappingURL=error.d.ts.map
package/dist/error.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.JWTErrorInvalidTokenLength = exports.JWTErrorPublicKeyNotFound = exports.JWTErrorInvalidSignature = exports.JWTErrorInvalidJwtId = exports.JWTErrorNotBefore = exports.JWTErrorExpired = exports.JWTErrorInvalidAudience = exports.JWTErrorInvalidSubject = exports.JWTErrorInvalidIssuer = exports.JWTErrorInvalidType = exports.JWTErrorPrivateKeyNotFound = exports.JWTErrorSecretNotFound = exports.JWTErrorAlgorithmNotSupport = exports.JWTError = void 0;
3
+ exports.JWTErrorInvalidToken = exports.JWTErrorInvalidAlgorithm = exports.JWTErrorInvalidTokenLength = exports.JWTErrorPublicKeyNotFound = exports.JWTErrorInvalidSignature = exports.JWTErrorInvalidJwtId = exports.JWTErrorNotBefore = exports.JWTErrorExpired = exports.JWTErrorInvalidAudience = exports.JWTErrorInvalidSubject = exports.JWTErrorInvalidIssuer = exports.JWTErrorInvalidType = exports.JWTErrorPrivateKeyNotFound = exports.JWTErrorSecretNotFound = exports.JWTErrorAlgorithmNotSupport = exports.JWTError = void 0;
4
4
  /**
5
5
  * Error class for JWT
6
6
  */
@@ -12,13 +12,13 @@ class JWTError extends Error {
12
12
  exports.JWTError = JWTError;
13
13
  class JWTErrorAlgorithmNotSupport extends JWTError {
14
14
  constructor(algorithm) {
15
- super(`Algorithm \`${algorithm} \` is not supported`);
15
+ super(`Algorithm \`${algorithm}\` is not supported`);
16
16
  }
17
17
  }
18
18
  exports.JWTErrorAlgorithmNotSupport = JWTErrorAlgorithmNotSupport;
19
19
  class JWTErrorSecretNotFound extends JWTError {
20
20
  constructor() {
21
- super("Secrete not found");
21
+ super("Secret not found");
22
22
  }
23
23
  }
24
24
  exports.JWTErrorSecretNotFound = JWTErrorSecretNotFound;
@@ -30,25 +30,25 @@ class JWTErrorPrivateKeyNotFound extends JWTError {
30
30
  exports.JWTErrorPrivateKeyNotFound = JWTErrorPrivateKeyNotFound;
31
31
  class JWTErrorInvalidType extends JWTError {
32
32
  constructor(type) {
33
- super(`Invalid type \`${type} \`, the \`typ\` must be \`JWT\``);
33
+ super(`Invalid type \`${type}\`, the \`typ\` must be \`JWT\``);
34
34
  }
35
35
  }
36
36
  exports.JWTErrorInvalidType = JWTErrorInvalidType;
37
37
  class JWTErrorInvalidIssuer extends JWTError {
38
38
  constructor(issuer, expect) {
39
- super(`Invalid issuer \`${issuer} \`, the \`iss\` must be \`${expect}\``);
39
+ super(`Invalid issuer \`${issuer}\`, the \`iss\` must be \`${expect}\``);
40
40
  }
41
41
  }
42
42
  exports.JWTErrorInvalidIssuer = JWTErrorInvalidIssuer;
43
43
  class JWTErrorInvalidSubject extends JWTError {
44
44
  constructor(subject, expect) {
45
- super(`Invalid subject \`${subject} \`, the \`sub\` must be \`${expect}\``);
45
+ super(`Invalid subject \`${subject}\`, the \`sub\` must be \`${expect}\``);
46
46
  }
47
47
  }
48
48
  exports.JWTErrorInvalidSubject = JWTErrorInvalidSubject;
49
49
  class JWTErrorInvalidAudience extends JWTError {
50
50
  constructor(audience, expect) {
51
- super(`Invalid audience \`${audience} \`, the \`aud\` must be \`${expect}\``);
51
+ super(`Invalid audience \`${audience}\`, the \`aud\` must be \`${expect}\``);
52
52
  }
53
53
  }
54
54
  exports.JWTErrorInvalidAudience = JWTErrorInvalidAudience;
@@ -66,7 +66,7 @@ class JWTErrorNotBefore extends JWTError {
66
66
  exports.JWTErrorNotBefore = JWTErrorNotBefore;
67
67
  class JWTErrorInvalidJwtId extends JWTError {
68
68
  constructor(jwtId, expect) {
69
- super(`Invalid jwt id \`${jwtId} \`, the \`jti\` must be \`${expect}\``);
69
+ super(`Invalid jwt id \`${jwtId}\`, the \`jti\` must be \`${expect}\``);
70
70
  }
71
71
  }
72
72
  exports.JWTErrorInvalidJwtId = JWTErrorInvalidJwtId;
@@ -88,4 +88,16 @@ class JWTErrorInvalidTokenLength extends JWTError {
88
88
  }
89
89
  }
90
90
  exports.JWTErrorInvalidTokenLength = JWTErrorInvalidTokenLength;
91
+ class JWTErrorInvalidAlgorithm extends JWTError {
92
+ constructor(algorithm, expect) {
93
+ super(`Invalid algorithm \`${algorithm}\`, the \`alg\` must be \`${expect}\``);
94
+ }
95
+ }
96
+ exports.JWTErrorInvalidAlgorithm = JWTErrorInvalidAlgorithm;
97
+ class JWTErrorInvalidToken extends JWTError {
98
+ constructor(reason) {
99
+ super(`Invalid token, ${reason}`);
100
+ }
101
+ }
102
+ exports.JWTErrorInvalidToken = JWTErrorInvalidToken;
91
103
  //# sourceMappingURL=error.js.map
package/dist/index.d.ts CHANGED
@@ -281,6 +281,13 @@ export declare class JWT {
281
281
  * @returns The payload of the token
282
282
  */
283
283
  verify<T extends JWTPayload = JWTPayload>(input: string, options?: JWTVerifyOptions): T;
284
+ /**
285
+ * Decode a token part, which must be a JSON object
286
+ * @param data The base64 url encoded data
287
+ * @param part The name of the part, used in error message
288
+ * @returns The decoded object
289
+ */
290
+ private static decodeObject;
284
291
  /**
285
292
  * Read hash algorithm
286
293
  * @param algorithm jwt algorithm
package/dist/index.js CHANGED
@@ -168,8 +168,21 @@ class JWT {
168
168
  return `${hp}.${s}`;
169
169
  }
170
170
  checkHeader(input) {
171
- if (input.typ && input.typ !== "JWT") {
172
- throw new error_1.JWTErrorInvalidType(input.typ);
171
+ // the header is not trusted, check the types before use
172
+ const typ = input.typ;
173
+ if (typ !== undefined && typ !== null && typeof typ !== "string") {
174
+ throw new error_1.JWTErrorInvalidToken("the `typ` must be a string");
175
+ }
176
+ if (typ && typ !== "JWT") {
177
+ throw new error_1.JWTErrorInvalidType(typ);
178
+ }
179
+ const alg = input.alg;
180
+ if (typeof alg !== "string") {
181
+ throw new error_1.JWTErrorInvalidToken("the `alg` must be a string");
182
+ }
183
+ // the token must be signed by the algorithm of this instance
184
+ if (alg !== this.algorithm) {
185
+ throw new error_1.JWTErrorInvalidAlgorithm(alg, this.algorithm);
173
186
  }
174
187
  }
175
188
  checkPayload(input, options = {}) {
@@ -189,13 +202,27 @@ class JWT {
189
202
  throw new error_1.JWTErrorInvalidAudience(input.aud, aud);
190
203
  }
191
204
  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);
205
+ // a not finite current time would pass every time check
206
+ if (!Number.isFinite(n)) {
207
+ throw new TypeError("The `currentTime` must be a finite number");
208
+ }
209
+ // 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)
216
+ throw new error_1.JWTErrorExpired(exp);
195
217
  }
196
218
  // check not before
197
- if (typeof input.nbf === "number" && input.nbf > n) {
198
- throw new error_1.JWTErrorNotBefore(input.nbf);
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)
225
+ throw new error_1.JWTErrorNotBefore(nbf);
199
226
  }
200
227
  // check jwt id
201
228
  const jti = this.jwtID ?? options.jwtID;
@@ -218,8 +245,10 @@ class JWT {
218
245
  }
219
246
  }
220
247
  checkSignatureHmac(signature, input, algorithm, encoding = "utf-8") {
221
- const s = this.buildSignature(input, algorithm, encoding);
222
- if (s !== signature) {
248
+ const expect = Buffer.from(this.buildSignature(input, algorithm, encoding), "utf-8");
249
+ const actual = Buffer.from(signature, "utf-8");
250
+ // compare in constant time
251
+ if (expect.length !== actual.length || !(0, crypto_1.timingSafeEqual)(expect, actual)) {
223
252
  throw new error_1.JWTErrorInvalidSignature();
224
253
  }
225
254
  }
@@ -227,10 +256,15 @@ class JWT {
227
256
  if (!this.publicKey) {
228
257
  throw new error_1.JWTErrorPublicKeyNotFound();
229
258
  }
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) {
262
+ throw new error_1.JWTErrorInvalidSignature();
263
+ }
230
264
  const verify = (0, crypto_1.createVerify)(JWT.hashAlgorithm(algorithm));
231
265
  verify.update(input, encoding);
232
266
  verify.end();
233
- if (!verify.verify(this.publicKey, signature, "base64url")) {
267
+ if (!verify.verify(this.publicKey, sig)) {
234
268
  throw new error_1.JWTErrorInvalidSignature();
235
269
  }
236
270
  }
@@ -239,18 +273,45 @@ class JWT {
239
273
  * @returns The payload of the token
240
274
  */
241
275
  verify(input, options = {}) {
242
- const [header, payload, signature] = JWT.parse(input);
276
+ if (typeof input !== "string") {
277
+ throw new error_1.JWTErrorInvalidToken("the token must be a string");
278
+ }
279
+ // the token must be exactly 3 parts, limit the split for a huge input
280
+ const parts = input.split(".", 4);
281
+ if (parts.length !== 3) {
282
+ throw new error_1.JWTErrorInvalidTokenLength(parts.length);
283
+ }
284
+ const [header, payload, signature] = parts;
243
285
  // check header
244
- const h = JWT.decode(header);
286
+ const h = JWT.decodeObject(header, "header");
245
287
  this.checkHeader(h);
246
- // check payload
247
- const p = JWT.decode(payload);
248
- this.checkPayload(p, options);
249
- // check signature
288
+ // check signature, before anything in payload is trusted
250
289
  const hp = `${header}.${payload}`;
251
290
  this.checkSignature(signature, hp, h.alg);
291
+ // check payload
292
+ const p = JWT.decodeObject(payload, "payload");
293
+ this.checkPayload(p, options);
252
294
  return p;
253
295
  }
296
+ /**
297
+ * Decode a token part, which must be a JSON object
298
+ * @param data The base64 url encoded data
299
+ * @param part The name of the part, used in error message
300
+ * @returns The decoded object
301
+ */
302
+ static decodeObject(data, part) {
303
+ let r;
304
+ try {
305
+ r = JWT.decode(data);
306
+ }
307
+ catch {
308
+ throw new error_1.JWTErrorInvalidToken(`the ${part} is not valid JSON`);
309
+ }
310
+ if (typeof r !== "object" || r === null || Array.isArray(r)) {
311
+ throw new error_1.JWTErrorInvalidToken(`the ${part} must be a JSON object`);
312
+ }
313
+ return r;
314
+ }
254
315
  /**
255
316
  * Read hash algorithm
256
317
  * @param algorithm jwt algorithm
@@ -285,6 +346,9 @@ class JWT {
285
346
  * @returns The header, payload, and signature of the token
286
347
  */
287
348
  static parse(input) {
349
+ if (typeof input !== "string") {
350
+ throw new error_1.JWTErrorInvalidToken("the token must be a string");
351
+ }
288
352
  const r = input.split(".", 3);
289
353
  if (r.length !== 3) {
290
354
  throw new error_1.JWTErrorInvalidTokenLength(r.length);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@liuhlightning/jwt",
3
- "version": "0.3.6",
3
+ "version": "0.4.0",
4
4
  "description": "json web token in full typescript.",
5
5
  "keywords": [
6
6
  "jwt",
@@ -22,6 +22,7 @@
22
22
  "packageManager": "yarn@1.22.22",
23
23
  "scripts": {
24
24
  "build": "tsc -p tsconfig.build.json",
25
+ "lint": "eslint .",
25
26
  "push": "yarn version --patch && git push && git push --tags",
26
27
  "test": "ts-node ./tests/index.test.ts"
27
28
  },
@@ -29,6 +30,7 @@
29
30
  "@eslint/js": "^10.0.1",
30
31
  "@types/node": "^25.5.0",
31
32
  "eslint": "^10.1.0",
33
+ "globals": "^17.14.0",
32
34
  "prettier": "^3.5.3",
33
35
  "ts-node": "^10.9.2",
34
36
  "typescript": "^5.9.3",