@liuhlightning/jwt 0.0.1 → 0.1.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.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,7 @@ 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
  }
189
288
  export default JWT;
190
289
  //# sourceMappingURL=index.d.ts.map
package/dist/index.js CHANGED
@@ -4,7 +4,7 @@ exports.JWT = void 0;
4
4
  const crypto_1 = require("crypto");
5
5
  const decode_1 = require("./decode");
6
6
  const encode_1 = require("./encode");
7
- const now_1 = require("./now");
7
+ const time_1 = require("./time");
8
8
  /**
9
9
  * A class to create and verify JSON Web Tokens
10
10
  *
@@ -13,12 +13,24 @@ const now_1 = require("./now");
13
13
  * https://datatracker.ietf.org/doc/html/rfc7519
14
14
  */
15
15
  class JWT {
16
+ get realAlgorithm() {
17
+ const a = this.algorithmMap[this.algorithm];
18
+ if (!a) {
19
+ throw new Error(`Algorithm ${this.algorithm} is not supported`);
20
+ }
21
+ return a;
22
+ }
16
23
  /**
17
24
  * Create a new JWT instance
18
25
  * @param secret The secret used to sign the token
19
26
  * @param options Options for the token
20
27
  */
21
28
  constructor(key, options = {}) {
29
+ this.algorithmMap = {
30
+ HS256: "sha256",
31
+ HS384: "sha384",
32
+ HS512: "sha512",
33
+ };
22
34
  if (typeof key === "string") {
23
35
  this.secret = key;
24
36
  }
@@ -27,9 +39,13 @@ class JWT {
27
39
  this.privateKey = key.privateKey;
28
40
  }
29
41
  this.algorithm = options.algorithm ?? "HS256";
30
- this.registeredClaims = options.registeredClaims ?? {};
31
- this.dynamicExp = options.dynamicExp;
32
- this.dynamicNbf = options.dynamicNbf;
42
+ this.issuer = options.issuer;
43
+ this.subject = options.subject;
44
+ this.audience = options.audience;
45
+ this.expirationTime = options.expirationTime;
46
+ this.notBefore = options.notBefore;
47
+ this.issuedAt = options.issuedAt;
48
+ this.jwtID = options.jwtID;
33
49
  }
34
50
  /**
35
51
  * @returns The header of the token
@@ -44,14 +60,26 @@ class JWT {
44
60
  * @param input The payload of the token
45
61
  * @returns The payload of the token
46
62
  */
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,
63
+ buildPayload(input, options = {}) {
64
+ const rc = {
65
+ iss: this.issuer ?? options.issuer,
66
+ sub: this.subject ?? options.subject,
67
+ aud: this.audience ?? options.audience,
68
+ exp: this.expirationTime ?? options.expirationTime,
69
+ nbf: this.notBefore ?? options.notBefore,
70
+ iat: this.issuedAt ?? options.issuedAt,
71
+ jti: this.jwtID ?? options.jwtID,
54
72
  };
73
+ if (rc.exp) {
74
+ rc.exp = (0, time_1.buildTime)(rc.exp);
75
+ }
76
+ if (rc.nbf) {
77
+ rc.nbf = (0, time_1.buildTime)(rc.nbf);
78
+ }
79
+ if (rc.iat) {
80
+ rc.iat = (0, time_1.buildTime)(rc.iat);
81
+ }
82
+ return { ...rc, ...input };
55
83
  }
56
84
  /**
57
85
  * @param input The input to sign
@@ -65,7 +93,7 @@ class JWT {
65
93
  if (!this.secret) {
66
94
  throw new Error("Secret is required for HS256, HS384, HS512");
67
95
  }
68
- const hmac = (0, crypto_1.createHmac)(this.algorithm.replace("HS", "sha"), this.secret);
96
+ const hmac = (0, crypto_1.createHmac)(this.realAlgorithm, this.secret);
69
97
  hmac.update(input);
70
98
  return hmac.digest("base64url");
71
99
  }
@@ -77,9 +105,9 @@ class JWT {
77
105
  * @param input The payload of the token
78
106
  * @returns The signed token
79
107
  */
80
- sign(input) {
108
+ sign(input, options = {}) {
81
109
  const h = (0, encode_1.encode)(this.buildHeader());
82
- const p = (0, encode_1.encode)(this.buildPayload(input));
110
+ const p = (0, encode_1.encode)(this.buildPayload(input, options));
83
111
  const s1 = `${h}.${p}`;
84
112
  const s = this.buildSignature(s1);
85
113
  return `${s1}.${s}`;
@@ -97,20 +125,23 @@ class JWT {
97
125
  * Check the payload of the token
98
126
  * @param input The payload of the token
99
127
  */
100
- checkPayload(input) {
128
+ checkPayload(input, options = {}) {
101
129
  // check issuer
102
- if (this.registeredClaims.iss && this.registeredClaims.iss !== input.iss) {
130
+ const iss = this.issuer ?? options.issuer;
131
+ if (iss && iss !== input.iss) {
103
132
  throw new Error(`Invalid issuer ${input.iss}`);
104
133
  }
105
134
  // check subject
106
- if (this.registeredClaims.sub && this.registeredClaims.sub !== input.sub) {
135
+ const sub = this.subject ?? options.subject;
136
+ if (sub && sub !== input.sub) {
107
137
  throw new Error(`Invalid subject ${input.sub}`);
108
138
  }
109
139
  // check audience
110
- if (this.registeredClaims.aud && this.registeredClaims.aud !== input.aud) {
140
+ const aud = this.audience ?? options.audience;
141
+ if (aud && aud !== input.aud) {
111
142
  throw new Error(`Invalid audience ${input.aud}`);
112
143
  }
113
- const n = (0, now_1.now)();
144
+ const n = (0, time_1.buildTime)(options.currentTime ?? Date.now());
114
145
  // check expiration time
115
146
  if (input.exp && input.exp < n) {
116
147
  throw new Error(`Token expired at ${new Date(input.exp * 1000).toISOString()}`);
@@ -119,11 +150,9 @@ class JWT {
119
150
  if (input.nbf && input.nbf > n) {
120
151
  throw new Error(`Token not before ${new Date(input.nbf * 1000).toISOString()}`);
121
152
  }
122
- if (this.registeredClaims.iat && this.registeredClaims.iat !== input.iat) {
123
- throw new Error(`Invalid issued at ${input.iat}`);
124
- }
125
153
  // check jwt id
126
- if (this.registeredClaims.jti && this.registeredClaims.jti !== input.jti) {
154
+ const jti = this.jwtID ?? options.jwtID;
155
+ if (jti && jti !== input.jti) {
127
156
  throw new Error(`Invalid JWT ID ${input.jti}`);
128
157
  }
129
158
  }
@@ -144,14 +173,14 @@ class JWT {
144
173
  * @param input The token to verify
145
174
  * @returns The payload of the token
146
175
  */
147
- verify(input) {
176
+ verify(input, options = {}) {
148
177
  const [header, payload, signature] = input.split(".");
149
178
  // check header
150
179
  const h = (0, decode_1.decode)(header);
151
180
  this.checkHeader(h);
152
181
  // check payload
153
182
  const p = (0, decode_1.decode)(payload);
154
- this.checkPayload(p);
183
+ this.checkPayload(p, options);
155
184
  // check signature
156
185
  const s1 = `${header}.${payload}`;
157
186
  this.checkSignature(signature, s1, h.alg);
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.0",
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