@liuhlightning/jwt 0.0.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.
package/README.md ADDED
@@ -0,0 +1,35 @@
1
+ # JWT
2
+
3
+ JSON Web Token
4
+
5
+ ## Reference
6
+
7
+ > https://jwt.io/
8
+ >
9
+ > https://datatracker.ietf.org/doc/html/rfc7519
10
+
11
+ ## How to use
12
+
13
+ ```bash
14
+ npm install --save @liuhlightning/jwt
15
+ # or
16
+ yarn add @liuhlightning/jwt
17
+ ```
18
+
19
+ ```typescript
20
+ import JWT from "@liuhlightning/jwt";
21
+
22
+ const jwt = new JWT("your jwt secret");
23
+ ```
24
+
25
+ ### Sign a token
26
+
27
+ ```typescript
28
+ const token = jwt.sign({ uid: 1234, username: "alex" });
29
+ ```
30
+
31
+ ### Verify a token and use payload
32
+
33
+ ```typescript
34
+ const payload = jwt.verify("input token");
35
+ ```
@@ -0,0 +1,7 @@
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 ADDED
@@ -0,0 +1,12 @@
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
@@ -0,0 +1,7 @@
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 ADDED
@@ -0,0 +1,12 @@
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
@@ -0,0 +1,190 @@
1
+ /**
2
+ * The key used to sign and verify the token
3
+ *
4
+ * If input a string, it will be used as the secret
5
+ *
6
+ * Secret is used for HS256, HS384, HS512
7
+ *
8
+ * Private key and public key are used for RS256, RS384, RS512, ES256, ES384, ES512, PS256, PS384, PS512
9
+ */
10
+ export type JWTKey = string | {
11
+ publicKey: string;
12
+ privateKey: string;
13
+ };
14
+ /**
15
+ * The algorithm used to sign the token
16
+ *
17
+ * HS - HMAC with SHA
18
+ *
19
+ * PS - RSA (RSASSA-PSS) with SHA
20
+ *
21
+ * RS - RSA (RSASSA-PKCS1-v1_5) with SHA
22
+ *
23
+ * ES - ECDSA with SHA
24
+ */
25
+ export type JWTAlgorithm = "HS256" | "HS384" | "HS512" | "PS256" | "PS384" | "PS512" | "RS256" | "RS384" | "RS512" | "ES256" | "ES256K" | "ES384" | "ES512" | "EdDSA";
26
+ /**
27
+ * Options for the JWT class
28
+ */
29
+ export interface JWTOptions {
30
+ /**
31
+ * The algorithm used to sign the token
32
+ */
33
+ algorithm?: JWTAlgorithm | string;
34
+ /**
35
+ * Registered claims
36
+ *
37
+ * This option will mixed with the payload
38
+ */
39
+ registeredClaims?: JWTPayloadRegisteredClaims;
40
+ /**
41
+ * Set the expiration time to now time + dynamicExp, in second
42
+ *
43
+ * This option will overwrite the exp in registered claims
44
+ */
45
+ dynamicExp?: number;
46
+ /**
47
+ * Set the not before time to now time + dynamicNbf, in second
48
+ *
49
+ * This option will overwrite the nbf in registered claims
50
+ */
51
+ dynamicNbf?: number;
52
+ }
53
+ export interface JWTHeader {
54
+ typ: string;
55
+ alg: JWTAlgorithm | string;
56
+ }
57
+ /**
58
+ * Registered claims for a JWT
59
+ */
60
+ export interface JWTPayloadRegisteredClaims {
61
+ /**
62
+ * Issuer
63
+ */
64
+ iss?: string;
65
+ /**
66
+ * Subject
67
+ */
68
+ sub?: string;
69
+ /**
70
+ * Audience
71
+ */
72
+ aud?: string;
73
+ /**
74
+ * Expiration Time
75
+ */
76
+ exp?: number;
77
+ /**
78
+ * Not Before
79
+ */
80
+ nbf?: number;
81
+ /**
82
+ * Issued At
83
+ */
84
+ iat?: number;
85
+ /**
86
+ * JWT ID
87
+ */
88
+ jti?: string;
89
+ }
90
+ /**
91
+ * The payload of a JWT
92
+ *
93
+ * If you want to use private claims, you should crypto it by yourself.
94
+ */
95
+ export type JWTPayload = JWTPayloadRegisteredClaims & Record<string, unknown>;
96
+ /**
97
+ * A class to create and verify JSON Web Tokens
98
+ *
99
+ * https://jwt.io/
100
+ *
101
+ * https://datatracker.ietf.org/doc/html/rfc7519
102
+ */
103
+ export declare class JWT {
104
+ /**
105
+ * The secret used to sign the token
106
+ *
107
+ * Secret is for HS256, HS384, HS512
108
+ */
109
+ private readonly secret?;
110
+ /**
111
+ * The public key used to verify the token
112
+ *
113
+ * Public key is for RS256, RS384, RS512, ES256, ES384, ES512, PS256, PS384, PS512
114
+ */
115
+ readonly publicKey?: string;
116
+ /**
117
+ * The private key used to sign the token
118
+ *
119
+ * Private key is for RS256, RS384, RS512, ES256, ES384, ES512, PS256, PS384, PS512
120
+ */
121
+ private readonly privateKey?;
122
+ /**
123
+ * The algorithm used to sign the token
124
+ *
125
+ * Set in header
126
+ */
127
+ 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;
140
+ /**
141
+ * Create a new JWT instance
142
+ * @param secret The secret used to sign the token
143
+ * @param options Options for the token
144
+ */
145
+ constructor(key: JWTKey, options?: JWTOptions);
146
+ /**
147
+ * @returns The header of the token
148
+ */
149
+ buildHeader(): JWTHeader;
150
+ /**
151
+ * @param input The payload of the token
152
+ * @returns The payload of the token
153
+ */
154
+ buildPayload(input: JWTPayload): JWTPayload;
155
+ /**
156
+ * @param input The input to sign
157
+ * @returns The signature of the input
158
+ */
159
+ buildSignature(input: string, algorithm?: string): string;
160
+ /**
161
+ * @param input The payload of the token
162
+ * @returns The signed token
163
+ */
164
+ sign(input: JWTPayload): string;
165
+ /**
166
+ * Check the header of the token
167
+ * @param input The header of the token
168
+ */
169
+ checkHeader(input: JWTHeader): void;
170
+ /**
171
+ * Check the payload of the token
172
+ * @param input The payload of the token
173
+ */
174
+ checkPayload(input: JWTPayload): void;
175
+ /**
176
+ * Chec the signature of the input
177
+ * @param algorithm The algorithm to use
178
+ * @param input The input to verify
179
+ * @param signature The signature to check
180
+ * @returns If the signature is correct
181
+ */
182
+ checkSignature(signature: string, input: string, algorithm: JWTAlgorithm | string): void;
183
+ /**
184
+ * @param input The token to verify
185
+ * @returns The payload of the token
186
+ */
187
+ verify<T extends JWTPayload = JWTPayload>(input: string): T;
188
+ }
189
+ export default JWT;
190
+ //# sourceMappingURL=index.d.ts.map
package/dist/index.js ADDED
@@ -0,0 +1,163 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.JWT = void 0;
4
+ const crypto_1 = require("crypto");
5
+ const decode_1 = require("./decode");
6
+ const encode_1 = require("./encode");
7
+ const now_1 = require("./now");
8
+ /**
9
+ * A class to create and verify JSON Web Tokens
10
+ *
11
+ * https://jwt.io/
12
+ *
13
+ * https://datatracker.ietf.org/doc/html/rfc7519
14
+ */
15
+ class JWT {
16
+ /**
17
+ * Create a new JWT instance
18
+ * @param secret The secret used to sign the token
19
+ * @param options Options for the token
20
+ */
21
+ constructor(key, options = {}) {
22
+ if (typeof key === "string") {
23
+ this.secret = key;
24
+ }
25
+ else {
26
+ this.publicKey = key.publicKey;
27
+ this.privateKey = key.privateKey;
28
+ }
29
+ this.algorithm = options.algorithm ?? "HS256";
30
+ this.registeredClaims = options.registeredClaims ?? {};
31
+ this.dynamicExp = options.dynamicExp;
32
+ this.dynamicNbf = options.dynamicNbf;
33
+ }
34
+ /**
35
+ * @returns The header of the token
36
+ */
37
+ buildHeader() {
38
+ return {
39
+ alg: this.algorithm,
40
+ typ: "JWT",
41
+ };
42
+ }
43
+ /**
44
+ * @param input The payload of the token
45
+ * @returns The payload of the token
46
+ */
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,
54
+ };
55
+ }
56
+ /**
57
+ * @param input The input to sign
58
+ * @returns The signature of the input
59
+ */
60
+ buildSignature(input, algorithm = this.algorithm) {
61
+ switch (algorithm) {
62
+ case "HS256":
63
+ case "HS384":
64
+ case "HS512": {
65
+ if (!this.secret) {
66
+ throw new Error("Secret is required for HS256, HS384, HS512");
67
+ }
68
+ const hmac = (0, crypto_1.createHmac)(this.algorithm.replace("HS", "sha"), this.secret);
69
+ hmac.update(input);
70
+ return hmac.digest("base64url");
71
+ }
72
+ default:
73
+ throw new Error(`Algorithm ${this.algorithm} is not supported`);
74
+ }
75
+ }
76
+ /**
77
+ * @param input The payload of the token
78
+ * @returns The signed token
79
+ */
80
+ sign(input) {
81
+ const h = (0, encode_1.encode)(this.buildHeader());
82
+ const p = (0, encode_1.encode)(this.buildPayload(input));
83
+ const s1 = `${h}.${p}`;
84
+ const s = this.buildSignature(s1);
85
+ return `${s1}.${s}`;
86
+ }
87
+ /**
88
+ * Check the header of the token
89
+ * @param input The header of the token
90
+ */
91
+ checkHeader(input) {
92
+ if (input.typ !== "JWT") {
93
+ throw new Error(`Invalid type ${input.typ}`);
94
+ }
95
+ }
96
+ /**
97
+ * Check the payload of the token
98
+ * @param input The payload of the token
99
+ */
100
+ checkPayload(input) {
101
+ // check issuer
102
+ if (this.registeredClaims.iss && this.registeredClaims.iss !== input.iss) {
103
+ throw new Error(`Invalid issuer ${input.iss}`);
104
+ }
105
+ // check subject
106
+ if (this.registeredClaims.sub && this.registeredClaims.sub !== input.sub) {
107
+ throw new Error(`Invalid subject ${input.sub}`);
108
+ }
109
+ // check audience
110
+ if (this.registeredClaims.aud && this.registeredClaims.aud !== input.aud) {
111
+ throw new Error(`Invalid audience ${input.aud}`);
112
+ }
113
+ const n = (0, now_1.now)();
114
+ // check expiration time
115
+ if (input.exp && input.exp < n) {
116
+ throw new Error(`Token expired at ${new Date(input.exp * 1000).toISOString()}`);
117
+ }
118
+ // check not before
119
+ 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}`);
124
+ }
125
+ // check jwt id
126
+ if (this.registeredClaims.jti && this.registeredClaims.jti !== input.jti) {
127
+ throw new Error(`Invalid JWT ID ${input.jti}`);
128
+ }
129
+ }
130
+ /**
131
+ * Chec the signature of the input
132
+ * @param algorithm The algorithm to use
133
+ * @param input The input to verify
134
+ * @param signature The signature to check
135
+ * @returns If the signature is correct
136
+ */
137
+ checkSignature(signature, input, algorithm) {
138
+ const s = this.buildSignature(input, algorithm);
139
+ if (s !== signature) {
140
+ throw new Error("Invalid signature");
141
+ }
142
+ }
143
+ /**
144
+ * @param input The token to verify
145
+ * @returns The payload of the token
146
+ */
147
+ verify(input) {
148
+ const [header, payload, signature] = input.split(".");
149
+ // check header
150
+ const h = (0, decode_1.decode)(header);
151
+ this.checkHeader(h);
152
+ // check payload
153
+ const p = (0, decode_1.decode)(payload);
154
+ this.checkPayload(p);
155
+ // check signature
156
+ const s1 = `${header}.${payload}`;
157
+ this.checkSignature(signature, s1, h.alg);
158
+ return p;
159
+ }
160
+ }
161
+ exports.JWT = JWT;
162
+ exports.default = JWT;
163
+ //# sourceMappingURL=index.js.map
package/dist/now.d.ts ADDED
@@ -0,0 +1,6 @@
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 ADDED
@@ -0,0 +1,11 @@
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
package/package.json ADDED
@@ -0,0 +1,33 @@
1
+ {
2
+ "name": "@liuhlightning/jwt",
3
+ "version": "0.0.1",
4
+ "description": "json web token in full typescript.",
5
+ "keywords": [
6
+ "jwt",
7
+ "json web token",
8
+ "typescript"
9
+ ],
10
+ "author": "Alex",
11
+ "repository": "https://github.com/ZhoufangErqiangu/jwt",
12
+ "license": "MIT",
13
+ "main": "dist/index.js",
14
+ "types": "dist/index.d.ts",
15
+ "files": [
16
+ "dist/**/*.js",
17
+ "dist/**/*.d.ts"
18
+ ],
19
+ "scripts": {
20
+ "build": "tsc -p tsconfig.build.json",
21
+ "push": "yarn version --patch && git push",
22
+ "test": "ts-node ./tests/index.test.ts"
23
+ },
24
+ "devDependencies": {
25
+ "@types/node": "^20.2.3",
26
+ "@typescript-eslint/eslint-plugin": "^5.59.7",
27
+ "@typescript-eslint/parser": "^5.59.7",
28
+ "eslint": "^8.41.0",
29
+ "prettier": "^2.8.8",
30
+ "ts-node": "^10.9.1",
31
+ "typescript": "^5.0.4"
32
+ }
33
+ }