@liuhlightning/jwt 0.0.1 → 0.1.1

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.
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Error class for JWT
3
+ */
4
+ export declare class JWTError extends Error {
5
+ constructor(message: string);
6
+ }
7
+ //# sourceMappingURL=error.d.ts.map
package/dist/error.js ADDED
@@ -0,0 +1,13 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.JWTError = void 0;
4
+ /**
5
+ * Error class for JWT
6
+ */
7
+ class JWTError extends Error {
8
+ constructor(message) {
9
+ super(message);
10
+ }
11
+ }
12
+ exports.JWTError = JWTError;
13
+ //# sourceMappingURL=error.js.map
package/dist/index.d.ts CHANGED
@@ -32,23 +32,47 @@ export interface JWTOptions {
32
32
  */
33
33
  algorithm?: JWTAlgorithm | string;
34
34
  /**
35
- * Registered claims
35
+ * Issuer
36
+ *
37
+ * If set, the token will check if the issuer is the same
38
+ */
39
+ issuer?: string;
40
+ /**
41
+ * Subject
42
+ *
43
+ * If set, the token will check if the subject is the same
44
+ */
45
+ subject?: string;
46
+ /**
47
+ * Audience
36
48
  *
37
- * This option will mixed with the payload
49
+ * If set, the token will check if the audience is the same
38
50
  */
39
- registeredClaims?: JWTPayloadRegisteredClaims;
51
+ audience?: string;
40
52
  /**
41
- * Set the expiration time to now time + dynamicExp, in second
53
+ * Expiration time, in milliseconds
42
54
  *
43
- * This option will overwrite the exp in registered claims
55
+ * If set, the token exp will be set to the value
44
56
  */
45
- dynamicExp?: number;
57
+ expirationTime?: number;
46
58
  /**
47
- * Set the not before time to now time + dynamicNbf, in second
59
+ * Not before, in milliseconds
48
60
  *
49
- * This option will overwrite the nbf in registered claims
61
+ * If set, the token nbf will be set to the value
50
62
  */
51
- dynamicNbf?: number;
63
+ notBefore?: number;
64
+ /**
65
+ * Issued at, in milliseconds
66
+ *
67
+ * If set, the token iat will be set to the value
68
+ */
69
+ issuedAt?: number;
70
+ /**
71
+ * JWT ID
72
+ *
73
+ * If set, the token will check if the JWT ID is the same
74
+ */
75
+ jwtID?: string;
52
76
  }
53
77
  export interface JWTHeader {
54
78
  typ: string;
@@ -71,15 +95,15 @@ export interface JWTPayloadRegisteredClaims {
71
95
  */
72
96
  aud?: string;
73
97
  /**
74
- * Expiration Time
98
+ * Expiration Time, in seconds
75
99
  */
76
100
  exp?: number;
77
101
  /**
78
- * Not Before
102
+ * Not Before, in seconds
79
103
  */
80
104
  nbf?: number;
81
105
  /**
82
- * Issued At
106
+ * Issued At, in seconds
83
107
  */
84
108
  iat?: number;
85
109
  /**
@@ -93,6 +117,84 @@ export interface JWTPayloadRegisteredClaims {
93
117
  * If you want to use private claims, you should crypto it by yourself.
94
118
  */
95
119
  export type JWTPayload = JWTPayloadRegisteredClaims & Record<string, unknown>;
120
+ export interface JWTSignOptions {
121
+ /**
122
+ * Issuer
123
+ *
124
+ * If set, the token iss will be set to the value
125
+ */
126
+ issuer?: string;
127
+ /**
128
+ * Subject
129
+ *
130
+ * If set, the token sub will be set to the value
131
+ */
132
+ subject?: string;
133
+ /**
134
+ * Audience
135
+ *
136
+ * If set, the token aud will be set to the value
137
+ */
138
+ audience?: string;
139
+ /**
140
+ * Expiration time, in milliseconds
141
+ *
142
+ * If set, the token exp will be set to the value
143
+ */
144
+ expirationTime?: number;
145
+ /**
146
+ * Not before, in milliseconds
147
+ *
148
+ * If set, the token nbf will be set to the value
149
+ */
150
+ notBefore?: number;
151
+ /**
152
+ * Issued at, in milliseconds
153
+ *
154
+ * If set, the token iat will be set to the value
155
+ */
156
+ issuedAt?: number;
157
+ /**
158
+ * JWT ID
159
+ *
160
+ * If set, the token jti will be set to the value
161
+ */
162
+ jwtID?: string;
163
+ }
164
+ export interface JWTVerifyOptions {
165
+ /**
166
+ * Issuer
167
+ *
168
+ * If set, the token will check if the issuer is the same
169
+ */
170
+ issuer?: string;
171
+ /**
172
+ * Subject
173
+ *
174
+ * If set, the token will check if the subject is the same
175
+ */
176
+ subject?: string;
177
+ /**
178
+ * Audience
179
+ *
180
+ * If set, the token will check if the audience is the same
181
+ */
182
+ audience?: string;
183
+ /**
184
+ * Current time, in milliseconds
185
+ *
186
+ * If set, the token will check if the current time is less than the expiration time
187
+ *
188
+ * If not set, the current time will be set to `Date.now()`
189
+ */
190
+ currentTime?: number;
191
+ /**
192
+ * JWT ID
193
+ *
194
+ * If set, the token will check if the JWT ID is the same
195
+ */
196
+ jwtID?: string;
197
+ }
96
198
  /**
97
199
  * A class to create and verify JSON Web Tokens
98
200
  *
@@ -125,18 +227,15 @@ export declare class JWT {
125
227
  * Set in header
126
228
  */
127
229
  algorithm: JWTAlgorithm | string;
128
- /**
129
- * Registered claims
130
- */
131
- registeredClaims: JWTPayloadRegisteredClaims;
132
- /**
133
- * If the expiration time is dynamic
134
- */
135
- dynamicExp?: number;
136
- /**
137
- * If the not before time is dynamic
138
- */
139
- dynamicNbf?: number;
230
+ algorithmMap: Record<string, string>;
231
+ get realAlgorithm(): string;
232
+ issuer?: string;
233
+ subject?: string;
234
+ audience?: string;
235
+ expirationTime?: number;
236
+ notBefore?: number;
237
+ issuedAt?: number;
238
+ jwtID?: string;
140
239
  /**
141
240
  * Create a new JWT instance
142
241
  * @param secret The secret used to sign the token
@@ -151,7 +250,7 @@ export declare class JWT {
151
250
  * @param input The payload of the token
152
251
  * @returns The payload of the token
153
252
  */
154
- buildPayload(input: JWTPayload): JWTPayload;
253
+ buildPayload(input: JWTPayload, options?: JWTSignOptions): JWTPayload;
155
254
  /**
156
255
  * @param input The input to sign
157
256
  * @returns The signature of the input
@@ -161,7 +260,7 @@ export declare class JWT {
161
260
  * @param input The payload of the token
162
261
  * @returns The signed token
163
262
  */
164
- sign(input: JWTPayload): string;
263
+ sign(input: JWTPayload, options?: JWTSignOptions): string;
165
264
  /**
166
265
  * Check the header of the token
167
266
  * @param input The header of the token
@@ -171,7 +270,7 @@ export declare class JWT {
171
270
  * Check the payload of the token
172
271
  * @param input The payload of the token
173
272
  */
174
- checkPayload(input: JWTPayload): void;
273
+ checkPayload(input: JWTPayload, options?: JWTVerifyOptions): void;
175
274
  /**
176
275
  * Chec the signature of the input
177
276
  * @param algorithm The algorithm to use
@@ -184,7 +283,8 @@ export declare class JWT {
184
283
  * @param input The token to verify
185
284
  * @returns The payload of the token
186
285
  */
187
- verify<T extends JWTPayload = JWTPayload>(input: string): T;
286
+ verify<T extends JWTPayload = JWTPayload>(input: string, options?: JWTVerifyOptions): T;
188
287
  }
288
+ export * from "./error";
189
289
  export default JWT;
190
290
  //# sourceMappingURL=index.d.ts.map
package/dist/index.js CHANGED
@@ -1,10 +1,25 @@
1
1
  "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
2
16
  Object.defineProperty(exports, "__esModule", { value: true });
3
17
  exports.JWT = void 0;
4
18
  const crypto_1 = require("crypto");
5
19
  const decode_1 = require("./decode");
6
20
  const encode_1 = require("./encode");
7
- const now_1 = require("./now");
21
+ const error_1 = require("./error");
22
+ const time_1 = require("./time");
8
23
  /**
9
24
  * A class to create and verify JSON Web Tokens
10
25
  *
@@ -13,12 +28,24 @@ const now_1 = require("./now");
13
28
  * https://datatracker.ietf.org/doc/html/rfc7519
14
29
  */
15
30
  class JWT {
31
+ get realAlgorithm() {
32
+ const a = this.algorithmMap[this.algorithm];
33
+ if (!a) {
34
+ throw new error_1.JWTError(`Algorithm ${this.algorithm} is not supported`);
35
+ }
36
+ return a;
37
+ }
16
38
  /**
17
39
  * Create a new JWT instance
18
40
  * @param secret The secret used to sign the token
19
41
  * @param options Options for the token
20
42
  */
21
43
  constructor(key, options = {}) {
44
+ this.algorithmMap = {
45
+ HS256: "sha256",
46
+ HS384: "sha384",
47
+ HS512: "sha512",
48
+ };
22
49
  if (typeof key === "string") {
23
50
  this.secret = key;
24
51
  }
@@ -27,9 +54,13 @@ class JWT {
27
54
  this.privateKey = key.privateKey;
28
55
  }
29
56
  this.algorithm = options.algorithm ?? "HS256";
30
- this.registeredClaims = options.registeredClaims ?? {};
31
- this.dynamicExp = options.dynamicExp;
32
- this.dynamicNbf = options.dynamicNbf;
57
+ this.issuer = options.issuer;
58
+ this.subject = options.subject;
59
+ this.audience = options.audience;
60
+ this.expirationTime = options.expirationTime;
61
+ this.notBefore = options.notBefore;
62
+ this.issuedAt = options.issuedAt;
63
+ this.jwtID = options.jwtID;
33
64
  }
34
65
  /**
35
66
  * @returns The header of the token
@@ -44,14 +75,26 @@ class JWT {
44
75
  * @param input The payload of the token
45
76
  * @returns The payload of the token
46
77
  */
47
- buildPayload(input) {
48
- const n = (0, now_1.now)();
49
- return {
50
- ...this.registeredClaims,
51
- exp: this.dynamicExp ? n + this.dynamicExp : this.registeredClaims.exp,
52
- nbf: this.dynamicNbf ? n + this.dynamicNbf : this.registeredClaims.nbf,
53
- ...input,
78
+ buildPayload(input, options = {}) {
79
+ const rc = {
80
+ iss: this.issuer ?? options.issuer,
81
+ sub: this.subject ?? options.subject,
82
+ aud: this.audience ?? options.audience,
83
+ exp: this.expirationTime ?? options.expirationTime,
84
+ nbf: this.notBefore ?? options.notBefore,
85
+ iat: this.issuedAt ?? options.issuedAt,
86
+ jti: this.jwtID ?? options.jwtID,
54
87
  };
88
+ if (rc.exp) {
89
+ rc.exp = (0, time_1.buildTime)(rc.exp);
90
+ }
91
+ if (rc.nbf) {
92
+ rc.nbf = (0, time_1.buildTime)(rc.nbf);
93
+ }
94
+ if (rc.iat) {
95
+ rc.iat = (0, time_1.buildTime)(rc.iat);
96
+ }
97
+ return { ...rc, ...input };
55
98
  }
56
99
  /**
57
100
  * @param input The input to sign
@@ -63,23 +106,23 @@ class JWT {
63
106
  case "HS384":
64
107
  case "HS512": {
65
108
  if (!this.secret) {
66
- throw new Error("Secret is required for HS256, HS384, HS512");
109
+ throw new error_1.JWTError("Secret is required for HS256, HS384, HS512");
67
110
  }
68
- const hmac = (0, crypto_1.createHmac)(this.algorithm.replace("HS", "sha"), this.secret);
111
+ const hmac = (0, crypto_1.createHmac)(this.realAlgorithm, this.secret);
69
112
  hmac.update(input);
70
113
  return hmac.digest("base64url");
71
114
  }
72
115
  default:
73
- throw new Error(`Algorithm ${this.algorithm} is not supported`);
116
+ throw new error_1.JWTError(`Algorithm ${this.algorithm} is not supported`);
74
117
  }
75
118
  }
76
119
  /**
77
120
  * @param input The payload of the token
78
121
  * @returns The signed token
79
122
  */
80
- sign(input) {
123
+ sign(input, options = {}) {
81
124
  const h = (0, encode_1.encode)(this.buildHeader());
82
- const p = (0, encode_1.encode)(this.buildPayload(input));
125
+ const p = (0, encode_1.encode)(this.buildPayload(input, options));
83
126
  const s1 = `${h}.${p}`;
84
127
  const s = this.buildSignature(s1);
85
128
  return `${s1}.${s}`;
@@ -90,41 +133,42 @@ class JWT {
90
133
  */
91
134
  checkHeader(input) {
92
135
  if (input.typ !== "JWT") {
93
- throw new Error(`Invalid type ${input.typ}`);
136
+ throw new error_1.JWTError(`Invalid type ${input.typ}`);
94
137
  }
95
138
  }
96
139
  /**
97
140
  * Check the payload of the token
98
141
  * @param input The payload of the token
99
142
  */
100
- checkPayload(input) {
143
+ checkPayload(input, options = {}) {
101
144
  // check issuer
102
- if (this.registeredClaims.iss && this.registeredClaims.iss !== input.iss) {
103
- throw new Error(`Invalid issuer ${input.iss}`);
145
+ const iss = this.issuer ?? options.issuer;
146
+ if (iss && iss !== input.iss) {
147
+ throw new error_1.JWTError(`Invalid issuer ${input.iss}`);
104
148
  }
105
149
  // check subject
106
- if (this.registeredClaims.sub && this.registeredClaims.sub !== input.sub) {
107
- throw new Error(`Invalid subject ${input.sub}`);
150
+ const sub = this.subject ?? options.subject;
151
+ if (sub && sub !== input.sub) {
152
+ throw new error_1.JWTError(`Invalid subject ${input.sub}`);
108
153
  }
109
154
  // check audience
110
- if (this.registeredClaims.aud && this.registeredClaims.aud !== input.aud) {
111
- throw new Error(`Invalid audience ${input.aud}`);
155
+ const aud = this.audience ?? options.audience;
156
+ if (aud && aud !== input.aud) {
157
+ throw new error_1.JWTError(`Invalid audience ${input.aud}`);
112
158
  }
113
- const n = (0, now_1.now)();
159
+ const n = (0, time_1.buildTime)(options.currentTime ?? Date.now());
114
160
  // check expiration time
115
161
  if (input.exp && input.exp < n) {
116
- throw new Error(`Token expired at ${new Date(input.exp * 1000).toISOString()}`);
162
+ throw new error_1.JWTError(`Token expired at ${new Date(input.exp * 1000).toISOString()}`);
117
163
  }
118
164
  // check not before
119
165
  if (input.nbf && input.nbf > n) {
120
- throw new Error(`Token not before ${new Date(input.nbf * 1000).toISOString()}`);
121
- }
122
- if (this.registeredClaims.iat && this.registeredClaims.iat !== input.iat) {
123
- throw new Error(`Invalid issued at ${input.iat}`);
166
+ throw new error_1.JWTError(`Token not before ${new Date(input.nbf * 1000).toISOString()}`);
124
167
  }
125
168
  // check jwt id
126
- if (this.registeredClaims.jti && this.registeredClaims.jti !== input.jti) {
127
- throw new Error(`Invalid JWT ID ${input.jti}`);
169
+ const jti = this.jwtID ?? options.jwtID;
170
+ if (jti && jti !== input.jti) {
171
+ throw new error_1.JWTError(`Invalid JWT ID ${input.jti}`);
128
172
  }
129
173
  }
130
174
  /**
@@ -137,21 +181,21 @@ class JWT {
137
181
  checkSignature(signature, input, algorithm) {
138
182
  const s = this.buildSignature(input, algorithm);
139
183
  if (s !== signature) {
140
- throw new Error("Invalid signature");
184
+ throw new error_1.JWTError("Invalid signature");
141
185
  }
142
186
  }
143
187
  /**
144
188
  * @param input The token to verify
145
189
  * @returns The payload of the token
146
190
  */
147
- verify(input) {
191
+ verify(input, options = {}) {
148
192
  const [header, payload, signature] = input.split(".");
149
193
  // check header
150
194
  const h = (0, decode_1.decode)(header);
151
195
  this.checkHeader(h);
152
196
  // check payload
153
197
  const p = (0, decode_1.decode)(payload);
154
- this.checkPayload(p);
198
+ this.checkPayload(p, options);
155
199
  // check signature
156
200
  const s1 = `${header}.${payload}`;
157
201
  this.checkSignature(signature, s1, h.alg);
@@ -159,5 +203,6 @@ class JWT {
159
203
  }
160
204
  }
161
205
  exports.JWT = JWT;
206
+ __exportStar(require("./error"), exports);
162
207
  exports.default = JWT;
163
208
  //# sourceMappingURL=index.js.map
package/dist/time.d.ts ADDED
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Converts a time in milliseconds to seconds.
3
+ * @param time The time in milliseconds.
4
+ * @returns The time in seconds.
5
+ */
6
+ export declare function buildTime(time: number): number;
7
+ /**
8
+ * Returns the current Unix timestamp in seconds.
9
+ * @returns The current Unix timestamp in seconds.
10
+ */
11
+ export declare function now(): number;
12
+ //# sourceMappingURL=time.d.ts.map
package/dist/time.js ADDED
@@ -0,0 +1,20 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.buildTime = buildTime;
4
+ exports.now = now;
5
+ /**
6
+ * Converts a time in milliseconds to seconds.
7
+ * @param time The time in milliseconds.
8
+ * @returns The time in seconds.
9
+ */
10
+ function buildTime(time) {
11
+ return Math.floor(time / 1000.0);
12
+ }
13
+ /**
14
+ * Returns the current Unix timestamp in seconds.
15
+ * @returns The current Unix timestamp in seconds.
16
+ */
17
+ function now() {
18
+ return buildTime(Date.now());
19
+ }
20
+ //# sourceMappingURL=time.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@liuhlightning/jwt",
3
- "version": "0.0.1",
3
+ "version": "0.1.1",
4
4
  "description": "json web token in full typescript.",
5
5
  "keywords": [
6
6
  "jwt",
@@ -8,7 +8,10 @@
8
8
  "typescript"
9
9
  ],
10
10
  "author": "Alex",
11
- "repository": "https://github.com/ZhoufangErqiangu/jwt",
11
+ "repository": {
12
+ "type": "git",
13
+ "url": "https://github.com/ZhoufangErqiangu/jwt"
14
+ },
12
15
  "license": "MIT",
13
16
  "main": "dist/index.js",
14
17
  "types": "dist/index.d.ts",
@@ -16,6 +19,7 @@
16
19
  "dist/**/*.js",
17
20
  "dist/**/*.d.ts"
18
21
  ],
22
+ "packageManager": "yarn@1.22.19",
19
23
  "scripts": {
20
24
  "build": "tsc -p tsconfig.build.json",
21
25
  "push": "yarn version --patch && git push",
package/dist/now.d.ts DELETED
@@ -1,6 +0,0 @@
1
- /**
2
- * Returns the current Unix timestamp in seconds.
3
- * @returns The current Unix timestamp in seconds.
4
- */
5
- export declare function now(): number;
6
- //# sourceMappingURL=now.d.ts.map
package/dist/now.js DELETED
@@ -1,11 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.now = now;
4
- /**
5
- * Returns the current Unix timestamp in seconds.
6
- * @returns The current Unix timestamp in seconds.
7
- */
8
- function now() {
9
- return Math.floor(Date.now() / 1000.0);
10
- }
11
- //# sourceMappingURL=now.js.map