@liuhlightning/jwt 0.2.1 → 0.3.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,46 @@
1
+ /**
2
+ * Error class for JWT
3
+ */
4
+ export declare abstract class JWTError extends Error {
5
+ constructor(message: string);
6
+ }
7
+ export declare class JWTErrorAlgorithmNotSupport extends JWTError {
8
+ constructor(algorithm: string);
9
+ }
10
+ export declare class JWTErrorSecretNotFound extends JWTError {
11
+ constructor();
12
+ }
13
+ export declare class JWTErrorPrivateKeyNotFound extends JWTError {
14
+ constructor();
15
+ }
16
+ export declare class JWTErrorInvalidType extends JWTError {
17
+ constructor(type: string);
18
+ }
19
+ export declare class JWTErrorInvalidIssuer extends JWTError {
20
+ constructor(issuer: string | undefined, expect: string);
21
+ }
22
+ export declare class JWTErrorInvalidSubject extends JWTError {
23
+ constructor(subject: string | undefined, expect: string);
24
+ }
25
+ export declare class JWTErrorInvalidAudience extends JWTError {
26
+ constructor(audience: string | undefined, expect: string);
27
+ }
28
+ export declare class JWTErrorExpired extends JWTError {
29
+ constructor(expiredAt: number);
30
+ }
31
+ export declare class JWTErrorNotBefore extends JWTError {
32
+ constructor(notBefore: number);
33
+ }
34
+ export declare class JWTErrorInvalidJwtId extends JWTError {
35
+ constructor(jwtId: string | undefined, expect: string);
36
+ }
37
+ export declare class JWTErrorInvalidSignature extends JWTError {
38
+ constructor();
39
+ }
40
+ export declare class JWTErrorPublicKeyNotFound extends JWTError {
41
+ constructor();
42
+ }
43
+ export declare class JWTErrorInvalidTokenLength extends JWTError {
44
+ constructor(len: number);
45
+ }
46
+ //# sourceMappingURL=error.d.ts.map
@@ -0,0 +1,91 @@
1
+ "use strict";
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;
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
+ class JWTErrorAlgorithmNotSupport extends JWTError {
14
+ constructor(algorithm) {
15
+ super(`Algorithm \`${algorithm} \` is not supported`);
16
+ }
17
+ }
18
+ exports.JWTErrorAlgorithmNotSupport = JWTErrorAlgorithmNotSupport;
19
+ class JWTErrorSecretNotFound extends JWTError {
20
+ constructor() {
21
+ super("Secrete not found");
22
+ }
23
+ }
24
+ exports.JWTErrorSecretNotFound = JWTErrorSecretNotFound;
25
+ class JWTErrorPrivateKeyNotFound extends JWTError {
26
+ constructor() {
27
+ super("Private key not found");
28
+ }
29
+ }
30
+ exports.JWTErrorPrivateKeyNotFound = JWTErrorPrivateKeyNotFound;
31
+ class JWTErrorInvalidType extends JWTError {
32
+ constructor(type) {
33
+ super(`Invalid type \`${type} \`, the \`typ\` must be \`JWT\``);
34
+ }
35
+ }
36
+ exports.JWTErrorInvalidType = JWTErrorInvalidType;
37
+ class JWTErrorInvalidIssuer extends JWTError {
38
+ constructor(issuer, expect) {
39
+ super(`Invalid issuer \`${issuer} \`, the \`iss\` must be \`${expect}\``);
40
+ }
41
+ }
42
+ exports.JWTErrorInvalidIssuer = JWTErrorInvalidIssuer;
43
+ class JWTErrorInvalidSubject extends JWTError {
44
+ constructor(subject, expect) {
45
+ super(`Invalid subject \`${subject} \`, the \`sub\` must be \`${expect}\``);
46
+ }
47
+ }
48
+ exports.JWTErrorInvalidSubject = JWTErrorInvalidSubject;
49
+ class JWTErrorInvalidAudience extends JWTError {
50
+ constructor(audience, expect) {
51
+ super(`Invalid audience \`${audience} \`, the \`aud\` must be \`${expect}\``);
52
+ }
53
+ }
54
+ exports.JWTErrorInvalidAudience = JWTErrorInvalidAudience;
55
+ class JWTErrorExpired extends JWTError {
56
+ constructor(expiredAt) {
57
+ super(`Token expired at ${new Date(expiredAt * 1000).toISOString()}`);
58
+ }
59
+ }
60
+ exports.JWTErrorExpired = JWTErrorExpired;
61
+ class JWTErrorNotBefore extends JWTError {
62
+ constructor(notBefore) {
63
+ super(`Token not before ${new Date(notBefore * 1000).toISOString()}`);
64
+ }
65
+ }
66
+ exports.JWTErrorNotBefore = JWTErrorNotBefore;
67
+ class JWTErrorInvalidJwtId extends JWTError {
68
+ constructor(jwtId, expect) {
69
+ super(`Invalid jwt id \`${jwtId} \`, the \`jti\` must be \`${expect}\``);
70
+ }
71
+ }
72
+ exports.JWTErrorInvalidJwtId = JWTErrorInvalidJwtId;
73
+ class JWTErrorInvalidSignature extends JWTError {
74
+ constructor() {
75
+ super("Invalid signature");
76
+ }
77
+ }
78
+ exports.JWTErrorInvalidSignature = JWTErrorInvalidSignature;
79
+ class JWTErrorPublicKeyNotFound extends JWTError {
80
+ constructor() {
81
+ super("Public key not found");
82
+ }
83
+ }
84
+ exports.JWTErrorPublicKeyNotFound = JWTErrorPublicKeyNotFound;
85
+ class JWTErrorInvalidTokenLength extends JWTError {
86
+ constructor(len) {
87
+ super(`Invalid token parts length \`${len}\`, the token parts length must be \`3\``);
88
+ }
89
+ }
90
+ exports.JWTErrorInvalidTokenLength = JWTErrorInvalidTokenLength;
91
+ //# sourceMappingURL=error.js.map
@@ -1,3 +1,4 @@
1
+ import { JsonWebKeyInput, KeyObject, PrivateKeyInput, PublicKeyInput } from "crypto";
1
2
  /**
2
3
  * The key used to sign and verify the token
3
4
  *
@@ -7,9 +8,13 @@
7
8
  *
8
9
  * Private key and public key are used for RS256, RS384, RS512, ES256, ES384, ES512, PS256, PS384, PS512
9
10
  */
10
- export type JWTKey = string | {
11
- publicKey: string;
12
- privateKey: string;
11
+ export type JWTKey = JWTKeySecret | (JWTKeyPrivateKey & JWTKeyPublicKey);
12
+ export type JWTKeySecret = string | Buffer;
13
+ export type JWTKeyPrivateKey = {
14
+ privateKey?: PrivateKeyInput | string | Buffer | JsonWebKeyInput;
15
+ };
16
+ export type JWTKeyPublicKey = {
17
+ publicKey?: PublicKeyInput | string | Buffer | KeyObject | JsonWebKeyInput;
13
18
  };
14
19
  /**
15
20
  * The algorithm used to sign the token
@@ -34,43 +39,51 @@ export interface JWTOptions {
34
39
  /**
35
40
  * Issuer
36
41
  *
37
- * If set, the token will check if the issuer is the same
42
+ * If set, the token `iss` will be set to this value when sign.
43
+ *
44
+ * If set, the token `iss` must be same value
38
45
  */
39
46
  issuer?: string;
40
47
  /**
41
48
  * Subject
42
49
  *
43
- * If set, the token will check if the subject is the same
50
+ * If set, the token `sub` will be set to this value when sign.
51
+ *
52
+ * If set, the token `sub` must be same value
44
53
  */
45
54
  subject?: string;
46
55
  /**
47
56
  * Audience
48
57
  *
49
- * If set, the token will check if the audience is the same
58
+ * If set, the token `aud` will be set to this value when sign.
59
+ *
60
+ * If set, the token `aud` must be same value
50
61
  */
51
62
  audience?: string;
52
63
  /**
53
- * Expiration time, in milliseconds
64
+ * Expiration time, in seconds
54
65
  *
55
- * If set, the token exp will be set to the value
66
+ * If set, the token `exp` will be set to the value
56
67
  */
57
68
  expirationTime?: number;
58
69
  /**
59
- * Not before, in milliseconds
70
+ * Not before, in seconds
60
71
  *
61
- * If set, the token nbf will be set to the value
72
+ * If set, the token `nbf` will be set to the value
62
73
  */
63
74
  notBefore?: number;
64
75
  /**
65
- * Issued at, in milliseconds
76
+ * Issued at, in seconds
66
77
  *
67
- * If set, the token iat will be set to the value
78
+ * If set, the token `iat` will be set to the value
68
79
  */
69
80
  issuedAt?: number;
70
81
  /**
71
82
  * JWT ID
72
83
  *
73
- * If set, the token will check if the JWT ID is the same
84
+ * If set, the token `jti` will be set to this value when sign.
85
+ *
86
+ * If set, the token `jti` must be same value
74
87
  */
75
88
  jwtID?: string;
76
89
  }
@@ -121,43 +134,43 @@ export interface JWTSignOptions {
121
134
  /**
122
135
  * Issuer
123
136
  *
124
- * If set, the token iss will be set to the value
137
+ * If set, the token `iss` will be set to this value when sign.
125
138
  */
126
139
  issuer?: string;
127
140
  /**
128
141
  * Subject
129
142
  *
130
- * If set, the token sub will be set to the value
143
+ * If set, the token `sub` will be set to this value when sign.
131
144
  */
132
145
  subject?: string;
133
146
  /**
134
147
  * Audience
135
148
  *
136
- * If set, the token aud will be set to the value
149
+ * If set, the token `aud` will be set to this value when sign.
137
150
  */
138
151
  audience?: string;
139
152
  /**
140
- * Expiration time, in milliseconds
153
+ * Expiration time, in seconds
141
154
  *
142
- * If set, the token exp will be set to the value
155
+ * If set, the token `exp` will be set to the value
143
156
  */
144
157
  expirationTime?: number;
145
158
  /**
146
- * Not before, in milliseconds
159
+ * Not before, in seconds
147
160
  *
148
- * If set, the token nbf will be set to the value
161
+ * If set, the token `nbf` will be set to the value
149
162
  */
150
163
  notBefore?: number;
151
164
  /**
152
- * Issued at, in milliseconds
165
+ * Issued at, in seconds
153
166
  *
154
- * If set, the token iat will be set to the value
167
+ * If set, the token `iat` will be set to the value
155
168
  */
156
169
  issuedAt?: number;
157
170
  /**
158
171
  * JWT ID
159
172
  *
160
- * If set, the token jti will be set to the value
173
+ * If set, the token `jti` will be set to this value when sign.
161
174
  */
162
175
  jwtID?: string;
163
176
  }
@@ -165,19 +178,19 @@ export interface JWTVerifyOptions {
165
178
  /**
166
179
  * Issuer
167
180
  *
168
- * If set, the token will check if the issuer is the same
181
+ * If set, the token `iss` must be same value
169
182
  */
170
183
  issuer?: string;
171
184
  /**
172
185
  * Subject
173
186
  *
174
- * If set, the token will check if the subject is the same
187
+ * If set, the token `sub` must be same value
175
188
  */
176
189
  subject?: string;
177
190
  /**
178
191
  * Audience
179
192
  *
180
- * If set, the token will check if the audience is the same
193
+ * If set, the token `aud` must be same value
181
194
  */
182
195
  audience?: string;
183
196
  /**
@@ -191,7 +204,7 @@ export interface JWTVerifyOptions {
191
204
  /**
192
205
  * JWT ID
193
206
  *
194
- * If set, the token will check if the JWT ID is the same
207
+ * If set, the token `jti` must be same value
195
208
  */
196
209
  jwtID?: string;
197
210
  }
@@ -209,26 +222,29 @@ export declare class JWT {
209
222
  * Secret is for HS256, HS384, HS512
210
223
  */
211
224
  private readonly secret?;
212
- /**
213
- * The public key used to verify the token
214
- *
215
- * Public key is for RS256, RS384, RS512, ES256, ES384, ES512, PS256, PS384, PS512
216
- */
217
- readonly publicKey?: string;
218
225
  /**
219
226
  * The private key used to sign the token
220
227
  *
221
228
  * Private key is for RS256, RS384, RS512, ES256, ES384, ES512, PS256, PS384, PS512
222
229
  */
223
230
  private readonly privateKey?;
231
+ /**
232
+ * The public key used to verify the token
233
+ *
234
+ * Public key is for RS256, RS384, RS512, ES256, ES384, ES512, PS256, PS384, PS512
235
+ */
236
+ readonly publicKey?: KeyObject;
224
237
  /**
225
238
  * The algorithm used to sign the token
226
239
  *
227
240
  * Set in header
228
241
  */
229
242
  algorithm: JWTAlgorithm | string;
230
- algorithmMap: Record<string, string>;
231
- get realAlgorithm(): string;
243
+ /**
244
+ * Returns the current Unix timestamp in seconds.
245
+ * @returns The current Unix timestamp in seconds.
246
+ */
247
+ get now(): number;
232
248
  issuer?: string;
233
249
  subject?: string;
234
250
  audience?: string;
@@ -245,45 +261,56 @@ export declare class JWT {
245
261
  /**
246
262
  * @returns The header of the token
247
263
  */
248
- buildHeader(): JWTHeader;
264
+ private buildHeader;
265
+ private buildPayload;
266
+ private buildSignature;
267
+ private buildSignatureHmac;
268
+ private buildSignatureSign;
249
269
  /**
250
270
  * @param input The payload of the token
251
- * @returns The payload of the token
271
+ * @returns The signed token
252
272
  */
253
- buildPayload(input: JWTPayload, options?: JWTSignOptions): JWTPayload;
273
+ sign(input: JWTPayload, options?: JWTSignOptions): string;
274
+ private checkHeader;
275
+ private checkPayload;
276
+ private checkSignature;
277
+ private checkSignatureHmac;
278
+ private checkSignatureVerify;
254
279
  /**
255
- * @param input The input to sign
256
- * @returns The signature of the input
280
+ * @param input The token to verify
281
+ * @returns The payload of the token
257
282
  */
258
- buildSignature(input: string, algorithm?: string): string;
283
+ verify<T extends JWTPayload = JWTPayload>(input: string, options?: JWTVerifyOptions): T;
259
284
  /**
260
- * @param input The payload of the token
261
- * @returns The signed token
285
+ * Read hash algorithm
286
+ * @param algorithm jwt algorithm
287
+ * @returns hash algorithm
262
288
  */
263
- sign(input: JWTPayload, options?: JWTSignOptions): string;
289
+ static hashAlgorithm(algorithm: JWTAlgorithm | string): string;
264
290
  /**
265
- * Check the header of the token
266
- * @param input The header of the token
291
+ * Decode base64 url data
292
+ * @param data The base64 encoded data
293
+ * @returns The decoded data
267
294
  */
268
- checkHeader(input: JWTHeader): void;
295
+ static decode<T = unknown>(data: string, encoding?: BufferEncoding): T;
269
296
  /**
270
- * Check the payload of the token
271
- * @param input The payload of the token
297
+ * Encode data to base64 url
298
+ * @param data The data to encode
299
+ * @returns The base64 encoded data
272
300
  */
273
- checkPayload(input: JWTPayload, options?: JWTVerifyOptions): void;
301
+ static encode(data: unknown, encoding?: BufferEncoding): string;
274
302
  /**
275
- * Chec the signature of the input
276
- * @param algorithm The algorithm to use
277
- * @param input The input to verify
278
- * @param signature The signature to check
279
- * @returns If the signature is correct
303
+ * Parse the token
304
+ * @param input The token to parse
305
+ * @returns The header, payload, and signature of the token
280
306
  */
281
- checkSignature(signature: string, input: string, algorithm: JWTAlgorithm | string): void;
307
+ static parse(input: string): [string, string, string];
282
308
  /**
283
- * @param input The token to verify
284
- * @returns The payload of the token
309
+ * Converts a time in milliseconds to seconds.
310
+ * @param ms The time in milliseconds.
311
+ * @returns The time in seconds.
285
312
  */
286
- verify<T extends JWTPayload = JWTPayload>(input: string, options?: JWTVerifyOptions): T;
313
+ static ms2s(ms: number): number;
287
314
  }
288
315
  export * from "./error";
289
316
  export default JWT;
@@ -0,0 +1,272 @@
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
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ exports.JWT = void 0;
18
+ const crypto_1 = require("crypto");
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",
27
+ };
28
+ /**
29
+ * A class to create and verify JSON Web Tokens
30
+ *
31
+ * https://jwt.io/
32
+ *
33
+ * https://datatracker.ietf.org/doc/html/rfc7519
34
+ */
35
+ class JWT {
36
+ /**
37
+ * Returns the current Unix timestamp in seconds.
38
+ * @returns The current Unix timestamp in seconds.
39
+ */
40
+ get now() {
41
+ return JWT.ms2s(Date.now());
42
+ }
43
+ /**
44
+ * Create a new JWT instance
45
+ * @param secret The secret used to sign the token
46
+ * @param options Options for the token
47
+ */
48
+ constructor(key, options = {}) {
49
+ if (typeof key === "string") {
50
+ this.secret = (0, crypto_1.createSecretKey)(key, "utf-8");
51
+ }
52
+ else if (key instanceof Buffer) {
53
+ this.secret = (0, crypto_1.createSecretKey)(key);
54
+ }
55
+ else {
56
+ const { privateKey, publicKey } = key;
57
+ if (privateKey) {
58
+ this.privateKey = (0, crypto_1.createPrivateKey)(privateKey);
59
+ // create public key from private key
60
+ this.publicKey = (0, crypto_1.createPublicKey)(this.privateKey);
61
+ }
62
+ else if (publicKey) {
63
+ // only set public key
64
+ this.publicKey = (0, crypto_1.createPublicKey)(publicKey);
65
+ }
66
+ }
67
+ this.algorithm = options.algorithm ?? "HS256";
68
+ this.issuer = options.issuer;
69
+ this.subject = options.subject;
70
+ this.audience = options.audience;
71
+ this.expirationTime = options.expirationTime;
72
+ this.notBefore = options.notBefore;
73
+ this.issuedAt = options.issuedAt;
74
+ this.jwtID = options.jwtID;
75
+ }
76
+ /**
77
+ * @returns The header of the token
78
+ */
79
+ buildHeader() {
80
+ return {
81
+ alg: this.algorithm,
82
+ typ: "JWT",
83
+ };
84
+ }
85
+ buildPayload(input, options = {}) {
86
+ const rc = {
87
+ iss: this.issuer ?? options.issuer,
88
+ sub: this.subject ?? options.subject,
89
+ aud: this.audience ?? options.audience,
90
+ exp: this.expirationTime ?? options.expirationTime,
91
+ nbf: this.notBefore ?? options.notBefore,
92
+ iat: this.issuedAt ?? options.issuedAt ?? this.now,
93
+ jti: this.jwtID ?? options.jwtID,
94
+ };
95
+ return { ...rc, ...input };
96
+ }
97
+ buildSignature(input, algorithm, encoding) {
98
+ switch (algorithm) {
99
+ case "HS256":
100
+ case "HS384":
101
+ case "HS512":
102
+ return this.buildSignatureHmac(input, algorithm, encoding);
103
+ case "RS256":
104
+ case "RS384":
105
+ case "RS512":
106
+ return this.buildSignatureSign(input, algorithm, encoding);
107
+ default:
108
+ throw new error_1.JWTErrorAlgorithmNotSupport(algorithm);
109
+ }
110
+ }
111
+ buildSignatureHmac(input, algorithm, encoding) {
112
+ if (!this.secret)
113
+ throw new error_1.JWTErrorSecretNotFound();
114
+ const hmac = (0, crypto_1.createHmac)(JWT.hashAlgorithm(algorithm), this.secret);
115
+ hmac.update(input, encoding);
116
+ return hmac.digest("base64url");
117
+ }
118
+ buildSignatureSign(input, algorithm, encoding) {
119
+ if (!this.privateKey)
120
+ throw new error_1.JWTErrorPrivateKeyNotFound();
121
+ const sign = (0, crypto_1.createSign)(JWT.hashAlgorithm(algorithm));
122
+ sign.update(input, encoding);
123
+ sign.end();
124
+ return sign.sign(this.privateKey, "base64url");
125
+ }
126
+ /**
127
+ * @param input The payload of the token
128
+ * @returns The signed token
129
+ */
130
+ sign(input, options = {}) {
131
+ const h = JWT.encode(this.buildHeader());
132
+ const p = JWT.encode(this.buildPayload(input, options));
133
+ const hp = `${h}.${p}`;
134
+ const s = this.buildSignature(hp, this.algorithm, "utf-8");
135
+ return `${hp}.${s}`;
136
+ }
137
+ checkHeader(input) {
138
+ if (input.typ !== "JWT")
139
+ throw new error_1.JWTErrorInvalidType(input.typ);
140
+ }
141
+ checkPayload(input, options = {}) {
142
+ // check issuer
143
+ const iss = this.issuer ?? options.issuer;
144
+ if (iss && iss !== input.iss) {
145
+ throw new error_1.JWTErrorInvalidIssuer(input.iss, iss);
146
+ }
147
+ // check subject
148
+ const sub = this.subject ?? options.subject;
149
+ if (sub && sub !== input.sub) {
150
+ throw new error_1.JWTErrorInvalidSubject(input.sub, sub);
151
+ }
152
+ // check audience
153
+ const aud = this.audience ?? options.audience;
154
+ if (aud && aud !== input.aud) {
155
+ throw new error_1.JWTErrorInvalidAudience(input.aud, aud);
156
+ }
157
+ const n = JWT.ms2s(options.currentTime ?? Date.now());
158
+ // check expiration time
159
+ if (typeof input.exp === "number" && input.exp < n) {
160
+ throw new error_1.JWTErrorExpired(input.exp);
161
+ }
162
+ // check not before
163
+ if (typeof input.nbf === "number" && input.nbf > n) {
164
+ throw new error_1.JWTErrorNotBefore(input.nbf);
165
+ }
166
+ // check jwt id
167
+ const jti = this.jwtID ?? options.jwtID;
168
+ if (jti && jti !== input.jti) {
169
+ throw new error_1.JWTErrorInvalidJwtId(input.jti, jti);
170
+ }
171
+ }
172
+ checkSignature(signature, input, algorithm, encoding = "utf-8") {
173
+ switch (this.algorithm) {
174
+ case "HS256":
175
+ case "HS384":
176
+ case "HS512":
177
+ return this.checkSignatureHmac(signature, input, algorithm, encoding);
178
+ case "RS256":
179
+ case "RS384":
180
+ case "RS512":
181
+ return this.checkSignatureVerify(signature, input, algorithm, encoding);
182
+ default:
183
+ throw new error_1.JWTErrorAlgorithmNotSupport(algorithm);
184
+ }
185
+ }
186
+ checkSignatureHmac(signature, input, algorithm, encoding = "utf-8") {
187
+ const s = this.buildSignature(input, algorithm, encoding);
188
+ if (s !== signature) {
189
+ throw new error_1.JWTErrorInvalidSignature();
190
+ }
191
+ }
192
+ checkSignatureVerify(signature, input, algorithm, encoding = "utf-8") {
193
+ if (!this.publicKey) {
194
+ throw new error_1.JWTErrorPublicKeyNotFound();
195
+ }
196
+ const verify = (0, crypto_1.createVerify)(JWT.hashAlgorithm(algorithm));
197
+ verify.update(input, encoding);
198
+ verify.end();
199
+ if (!verify.verify(this.publicKey, signature, "base64url")) {
200
+ throw new error_1.JWTErrorInvalidSignature();
201
+ }
202
+ }
203
+ /**
204
+ * @param input The token to verify
205
+ * @returns The payload of the token
206
+ */
207
+ verify(input, options = {}) {
208
+ const [header, payload, signature] = JWT.parse(input);
209
+ // check header
210
+ const h = JWT.decode(header);
211
+ this.checkHeader(h);
212
+ // check payload
213
+ const p = JWT.decode(payload);
214
+ this.checkPayload(p, options);
215
+ // check signature
216
+ const hp = `${header}.${payload}`;
217
+ this.checkSignature(signature, hp, h.alg);
218
+ return p;
219
+ }
220
+ /**
221
+ * Read hash algorithm
222
+ * @param algorithm jwt algorithm
223
+ * @returns hash algorithm
224
+ */
225
+ static hashAlgorithm(algorithm) {
226
+ const a = JWT_HASH_ALGORITHM_MAP[algorithm];
227
+ if (!a) {
228
+ throw new error_1.JWTErrorAlgorithmNotSupport(algorithm);
229
+ }
230
+ return a;
231
+ }
232
+ /**
233
+ * Decode base64 url data
234
+ * @param data The base64 encoded data
235
+ * @returns The decoded data
236
+ */
237
+ static decode(data, encoding = "utf-8") {
238
+ return JSON.parse(Buffer.from(data, "base64url").toString(encoding));
239
+ }
240
+ /**
241
+ * Encode data to base64 url
242
+ * @param data The data to encode
243
+ * @returns The base64 encoded data
244
+ */
245
+ static encode(data, encoding = "utf-8") {
246
+ return Buffer.from(JSON.stringify(data), encoding).toString("base64url");
247
+ }
248
+ /**
249
+ * Parse the token
250
+ * @param input The token to parse
251
+ * @returns The header, payload, and signature of the token
252
+ */
253
+ static parse(input) {
254
+ const r = input.split(".", 3);
255
+ if (r.length !== 3) {
256
+ throw new error_1.JWTErrorInvalidTokenLength(r.length);
257
+ }
258
+ return r;
259
+ }
260
+ /**
261
+ * Converts a time in milliseconds to seconds.
262
+ * @param ms The time in milliseconds.
263
+ * @returns The time in seconds.
264
+ */
265
+ static ms2s(ms) {
266
+ return Math.floor(ms / 1000.0);
267
+ }
268
+ }
269
+ exports.JWT = JWT;
270
+ __exportStar(require("./error"), exports);
271
+ exports.default = JWT;
272
+ //# sourceMappingURL=index.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@liuhlightning/jwt",
3
- "version": "0.2.1",
3
+ "version": "0.3.1",
4
4
  "description": "json web token in full typescript.",
5
5
  "keywords": [
6
6
  "jwt",
@@ -10,7 +10,7 @@
10
10
  "author": "Alex",
11
11
  "repository": {
12
12
  "type": "git",
13
- "url": "https://github.com/ZhoufangErqiangu/jwt"
13
+ "url": "git+https://github.com/ZhoufangErqiangu/jwt.git"
14
14
  },
15
15
  "license": "MIT",
16
16
  "main": "dist/index.js",
@@ -19,19 +19,19 @@
19
19
  "dist/**/*.js",
20
20
  "dist/**/*.d.ts"
21
21
  ],
22
- "packageManager": "yarn@1.22.19",
22
+ "packageManager": "yarn@1.22.22",
23
23
  "scripts": {
24
24
  "build": "tsc -p tsconfig.build.json",
25
25
  "push": "yarn version --patch && git push && git push --tags",
26
26
  "test": "ts-node ./tests/index.test.ts"
27
27
  },
28
28
  "devDependencies": {
29
- "@eslint/js": "^9.29.0",
30
- "@types/node": "^22.13.14",
31
- "eslint": "^9.29.0",
29
+ "@eslint/js": "^10.0.1",
30
+ "@types/node": "^25.5.0",
31
+ "eslint": "^10.1.0",
32
32
  "prettier": "^3.5.3",
33
33
  "ts-node": "^10.9.2",
34
- "typescript": "^5.8.3",
34
+ "typescript": "^6.0.2",
35
35
  "typescript-eslint": "^8.18.0"
36
36
  }
37
37
  }
package/dist/decode.d.ts DELETED
@@ -1,7 +0,0 @@
1
- /**
2
- * Decode base64 url data
3
- * @param data The base64 encoded data
4
- * @returns The decoded data
5
- */
6
- export declare function decode<T = unknown>(data: string): T;
7
- //# sourceMappingURL=decode.d.ts.map
package/dist/decode.js DELETED
@@ -1,12 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.decode = decode;
4
- /**
5
- * Decode base64 url data
6
- * @param data The base64 encoded data
7
- * @returns The decoded data
8
- */
9
- function decode(data) {
10
- return JSON.parse(Buffer.from(data, "base64url").toString());
11
- }
12
- //# sourceMappingURL=decode.js.map
package/dist/encode.d.ts DELETED
@@ -1,7 +0,0 @@
1
- /**
2
- * Encode data to base64 url
3
- * @param data The data to encode
4
- * @returns The base64 encoded data
5
- */
6
- export declare function encode(data: unknown): string;
7
- //# sourceMappingURL=encode.d.ts.map
package/dist/encode.js DELETED
@@ -1,12 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.encode = encode;
4
- /**
5
- * Encode data to base64 url
6
- * @param data The data to encode
7
- * @returns The base64 encoded data
8
- */
9
- function encode(data) {
10
- return Buffer.from(JSON.stringify(data)).toString("base64url");
11
- }
12
- //# sourceMappingURL=encode.js.map
package/dist/error.d.ts DELETED
@@ -1,7 +0,0 @@
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 DELETED
@@ -1,13 +0,0 @@
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.js DELETED
@@ -1,206 +0,0 @@
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
- };
16
- Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.JWT = void 0;
18
- const crypto_1 = require("crypto");
19
- const decode_1 = require("./decode");
20
- const encode_1 = require("./encode");
21
- const error_1 = require("./error");
22
- const parse_1 = require("./parse");
23
- const time_1 = require("./time");
24
- /**
25
- * A class to create and verify JSON Web Tokens
26
- *
27
- * https://jwt.io/
28
- *
29
- * https://datatracker.ietf.org/doc/html/rfc7519
30
- */
31
- class JWT {
32
- get realAlgorithm() {
33
- const a = this.algorithmMap[this.algorithm];
34
- if (!a) {
35
- throw new error_1.JWTError(`Algorithm ${this.algorithm} is not supported`);
36
- }
37
- return a;
38
- }
39
- /**
40
- * Create a new JWT instance
41
- * @param secret The secret used to sign the token
42
- * @param options Options for the token
43
- */
44
- constructor(key, options = {}) {
45
- this.algorithmMap = {
46
- HS256: "sha256",
47
- HS384: "sha384",
48
- HS512: "sha512",
49
- };
50
- if (typeof key === "string") {
51
- this.secret = key;
52
- }
53
- else {
54
- this.publicKey = key.publicKey;
55
- this.privateKey = key.privateKey;
56
- }
57
- this.algorithm = options.algorithm ?? "HS256";
58
- this.issuer = options.issuer;
59
- this.subject = options.subject;
60
- this.audience = options.audience;
61
- this.expirationTime = options.expirationTime;
62
- this.notBefore = options.notBefore;
63
- this.issuedAt = options.issuedAt;
64
- this.jwtID = options.jwtID;
65
- }
66
- /**
67
- * @returns The header of the token
68
- */
69
- buildHeader() {
70
- return {
71
- alg: this.algorithm,
72
- typ: "JWT",
73
- };
74
- }
75
- /**
76
- * @param input The payload of the token
77
- * @returns The payload of the token
78
- */
79
- buildPayload(input, options = {}) {
80
- const rc = {
81
- iss: this.issuer ?? options.issuer,
82
- sub: this.subject ?? options.subject,
83
- aud: this.audience ?? options.audience,
84
- exp: this.expirationTime ?? options.expirationTime,
85
- nbf: this.notBefore ?? options.notBefore,
86
- iat: this.issuedAt ?? options.issuedAt ?? (0, time_1.now)(),
87
- jti: this.jwtID ?? options.jwtID,
88
- };
89
- if (rc.exp)
90
- rc.exp = (0, time_1.buildTime)(rc.exp);
91
- if (rc.nbf)
92
- rc.nbf = (0, time_1.buildTime)(rc.nbf);
93
- if (rc.iat)
94
- rc.iat = (0, time_1.buildTime)(rc.iat);
95
- return { ...rc, ...input };
96
- }
97
- /**
98
- * @param input The input to sign
99
- * @returns The signature of the input
100
- */
101
- buildSignature(input, algorithm = this.algorithm) {
102
- switch (algorithm) {
103
- case "HS256":
104
- case "HS384":
105
- case "HS512": {
106
- if (!this.secret) {
107
- throw new error_1.JWTError("Secret is required for HS256, HS384, HS512");
108
- }
109
- const hmac = (0, crypto_1.createHmac)(this.realAlgorithm, this.secret);
110
- hmac.update(input);
111
- return hmac.digest("base64url");
112
- }
113
- default:
114
- throw new error_1.JWTError(`Algorithm ${this.algorithm} is not supported`);
115
- }
116
- }
117
- /**
118
- * @param input The payload of the token
119
- * @returns The signed token
120
- */
121
- sign(input, options = {}) {
122
- const h = (0, encode_1.encode)(this.buildHeader());
123
- const p = (0, encode_1.encode)(this.buildPayload(input, options));
124
- const s1 = `${h}.${p}`;
125
- const s = this.buildSignature(s1);
126
- return `${s1}.${s}`;
127
- }
128
- /**
129
- * Check the header of the token
130
- * @param input The header of the token
131
- */
132
- checkHeader(input) {
133
- if (input.typ !== "JWT") {
134
- throw new error_1.JWTError(`Invalid type ${input.typ}`);
135
- }
136
- }
137
- /**
138
- * Check the payload of the token
139
- * @param input The payload of the token
140
- */
141
- checkPayload(input, options = {}) {
142
- // check issuer
143
- const iss = this.issuer ?? options.issuer;
144
- if (iss && iss !== input.iss) {
145
- throw new error_1.JWTError(`Invalid issuer ${input.iss}`);
146
- }
147
- // check subject
148
- const sub = this.subject ?? options.subject;
149
- if (sub && sub !== input.sub) {
150
- throw new error_1.JWTError(`Invalid subject ${input.sub}`);
151
- }
152
- // check audience
153
- const aud = this.audience ?? options.audience;
154
- if (aud && aud !== input.aud) {
155
- throw new error_1.JWTError(`Invalid audience ${input.aud}`);
156
- }
157
- const n = (0, time_1.buildTime)(options.currentTime ?? Date.now());
158
- // check expiration time
159
- if (input.exp && input.exp < n) {
160
- throw new error_1.JWTError(`Token expired at ${new Date(input.exp * 1000).toISOString()}`);
161
- }
162
- // check not before
163
- if (input.nbf && input.nbf > n) {
164
- throw new error_1.JWTError(`Token not before ${new Date(input.nbf * 1000).toISOString()}`);
165
- }
166
- // check jwt id
167
- const jti = this.jwtID ?? options.jwtID;
168
- if (jti && jti !== input.jti) {
169
- throw new error_1.JWTError(`Invalid JWT ID ${input.jti}`);
170
- }
171
- }
172
- /**
173
- * Chec the signature of the input
174
- * @param algorithm The algorithm to use
175
- * @param input The input to verify
176
- * @param signature The signature to check
177
- * @returns If the signature is correct
178
- */
179
- checkSignature(signature, input, algorithm) {
180
- const s = this.buildSignature(input, algorithm);
181
- if (s !== signature) {
182
- throw new error_1.JWTError("Invalid signature");
183
- }
184
- }
185
- /**
186
- * @param input The token to verify
187
- * @returns The payload of the token
188
- */
189
- verify(input, options = {}) {
190
- const [header, payload, signature] = (0, parse_1.parse)(input);
191
- // check header
192
- const h = (0, decode_1.decode)(header);
193
- this.checkHeader(h);
194
- // check payload
195
- const p = (0, decode_1.decode)(payload);
196
- this.checkPayload(p, options);
197
- // check signature
198
- const s1 = `${header}.${payload}`;
199
- this.checkSignature(signature, s1, h.alg);
200
- return p;
201
- }
202
- }
203
- exports.JWT = JWT;
204
- __exportStar(require("./error"), exports);
205
- exports.default = JWT;
206
- //# sourceMappingURL=index.js.map
package/dist/parse.d.ts DELETED
@@ -1,7 +0,0 @@
1
- /**
2
- * Parse the token
3
- * @param input The token to parse
4
- * @returns The header, payload, and signature of the token
5
- */
6
- export declare function parse(input: string): [string, string, string];
7
- //# sourceMappingURL=parse.d.ts.map
package/dist/parse.js DELETED
@@ -1,16 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.parse = parse;
4
- const error_1 = require("./error");
5
- /**
6
- * Parse the token
7
- * @param input The token to parse
8
- * @returns The header, payload, and signature of the token
9
- */
10
- function parse(input) {
11
- const r = input.split(".", 3);
12
- if (r.length !== 3)
13
- throw new error_1.JWTError(`Token parts is not 3 ${input}`);
14
- return r;
15
- }
16
- //# sourceMappingURL=parse.js.map
package/dist/time.d.ts DELETED
@@ -1,12 +0,0 @@
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 DELETED
@@ -1,20 +0,0 @@
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