@sourceregistry/node-jwt 1.0.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/LICENSE +201 -0
- package/README.md +171 -0
- package/dist/index.cjs.js +2 -0
- package/dist/index.cjs.js.map +1 -0
- package/dist/index.d.ts +184 -0
- package/dist/index.es.js +140 -0
- package/dist/index.es.js.map +1 -0
- package/package.json +85 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
# 🔐 node-jwt
|
|
2
|
+
|
|
3
|
+
[](https://www.npmjs.com/package/@sourceregistry/node-jwt)
|
|
4
|
+
[](LICENSE)
|
|
5
|
+
[](https://github.com/SourceRegistry/node-jwt/actions)
|
|
6
|
+
[](https://codecov.io/gh/SourceRegistry/node-jwt)
|
|
7
|
+
|
|
8
|
+
A **minimal**, **secure**, and **production-ready** JWT (JSON Web Token) library for Node.js with **zero dependencies**. Supports all standard signing algorithms (HMAC, RSA, ECDSA) and full claim validation.
|
|
9
|
+
|
|
10
|
+
> ✨ **Why another JWT library?**
|
|
11
|
+
> Most JWT libraries are bloated, have security pitfalls, or lack proper TypeScript support. This library is:
|
|
12
|
+
> - **Tiny**
|
|
13
|
+
> - **Secure by default** (correct ECDSA/RSA encoding, time validation)
|
|
14
|
+
> - **TypeScript-first** with full JSDoc
|
|
15
|
+
> - **No external dependencies**
|
|
16
|
+
> - **100% test coverage**
|
|
17
|
+
|
|
18
|
+
---
|
|
19
|
+
|
|
20
|
+
## 📦 Installation
|
|
21
|
+
|
|
22
|
+
```bash
|
|
23
|
+
npm install @sourceregistry/node-jwt
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
> **Requires Node.js ≥ 16**
|
|
27
|
+
|
|
28
|
+
---
|
|
29
|
+
|
|
30
|
+
## 🚀 Quick Start
|
|
31
|
+
|
|
32
|
+
### Sign a token
|
|
33
|
+
```ts
|
|
34
|
+
import { sign } from '@sourceregistry/node-jwt';
|
|
35
|
+
|
|
36
|
+
const token = sign(
|
|
37
|
+
{ sub: '1234567890', name: 'John Doe', iat: Math.floor(Date.now() / 1000) },
|
|
38
|
+
'your-secret-key',
|
|
39
|
+
{ alg: 'HS256' }
|
|
40
|
+
);
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
### Verify a token
|
|
44
|
+
```ts
|
|
45
|
+
import { verify } from '@sourceregistry/node-jwt';
|
|
46
|
+
|
|
47
|
+
const result = verify(token, 'your-secret-key');
|
|
48
|
+
|
|
49
|
+
if (result.valid) {
|
|
50
|
+
console.log('Payload:', result.payload);
|
|
51
|
+
} else {
|
|
52
|
+
console.error('JWT Error:', result.error.code, result.error.reason);
|
|
53
|
+
}
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
### Decode (unsafe — no verification)
|
|
57
|
+
```ts
|
|
58
|
+
import { decode } from '@sourceregistry/node-jwt';
|
|
59
|
+
|
|
60
|
+
const { header, payload, signature } = decode(token);
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
---
|
|
64
|
+
|
|
65
|
+
## 🔑 Supported Algorithms
|
|
66
|
+
|
|
67
|
+
| Algorithm | Type | Secret Type |
|
|
68
|
+
|-----------|---------|---------------------------------|
|
|
69
|
+
| `HS256` | HMAC | `string \| Buffer` |
|
|
70
|
+
| `HS384` | HMAC | `string \| Buffer` |
|
|
71
|
+
| `HS512` | HMAC | `string \| Buffer` |
|
|
72
|
+
| `RS256` | RSA | Private key (signing)<br>Public key (verifying) |
|
|
73
|
+
| `RS384` | RSA | Private key (signing)<br>Public key (verifying) |
|
|
74
|
+
| `RS512` | RSA | Private key (signing)<br>Public key (verifying) |
|
|
75
|
+
| `ES256` | ECDSA | Private key (signing)<br>Public key (verifying) |
|
|
76
|
+
| `ES384` | ECDSA | Private key (signing)<br>Public key (verifying) |
|
|
77
|
+
| `ES512` | ECDSA | Private key (signing)<br>Public key (verifying) |
|
|
78
|
+
|
|
79
|
+
> 💡 **Note**: RSA/ECDSA keys must be in **PEM format** or as Node.js `KeyObject`.
|
|
80
|
+
|
|
81
|
+
---
|
|
82
|
+
|
|
83
|
+
## 🛡️ Security Features
|
|
84
|
+
|
|
85
|
+
- ✅ **Correct ECDSA signatures** (DER-encoded, not IEEE P1363)
|
|
86
|
+
- ✅ **Strict algorithm validation** (prevents algorithm confusion attacks)
|
|
87
|
+
- ✅ **Time claim validation** (`exp`, `nbf`, `iat`) with **clock skew tolerance**
|
|
88
|
+
- ✅ **Type header enforcement** (`typ: 'JWT'`)
|
|
89
|
+
- ✅ **No unsafe defaults**
|
|
90
|
+
|
|
91
|
+
---
|
|
92
|
+
|
|
93
|
+
## 📚 API Reference
|
|
94
|
+
|
|
95
|
+
### `sign(payload, secret, options?)`
|
|
96
|
+
Sign a JWT.
|
|
97
|
+
|
|
98
|
+
- `payload`: `JWTPayload` object
|
|
99
|
+
- `secret`: Key for signing (type depends on algorithm)
|
|
100
|
+
- `options`:
|
|
101
|
+
- `alg`: Algorithm (default: `'HS256'`)
|
|
102
|
+
- `kid`: Key ID
|
|
103
|
+
- `typ`: Token type (default: `'JWT'`)
|
|
104
|
+
|
|
105
|
+
Returns: `string` (JWT)
|
|
106
|
+
|
|
107
|
+
---
|
|
108
|
+
|
|
109
|
+
### `verify(token, secret, options?)`
|
|
110
|
+
Verify and validate a JWT.
|
|
111
|
+
|
|
112
|
+
- `token`: JWT string
|
|
113
|
+
- `secret`: Key for verification
|
|
114
|
+
- `options`:
|
|
115
|
+
- `ignoreExpiration`: Skip `exp` check (default: `false`)
|
|
116
|
+
- `clockSkew`: Tolerance in seconds for time validation (default: `0`)
|
|
117
|
+
|
|
118
|
+
Returns:
|
|
119
|
+
```ts
|
|
120
|
+
| { valid: true; header: JWTHeader; payload: JWTPayload; signature: string }
|
|
121
|
+
| { valid: false; error: { reason: string; code: string } }
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
**Error Codes**:
|
|
125
|
+
- `INVALID_TOKEN`: Malformed token structure
|
|
126
|
+
- `INVALID_ALGORITHM`: Unsupported algorithm
|
|
127
|
+
- `INVALID_TYPE`: Invalid `typ` header
|
|
128
|
+
- `INVALID_SIGNATURE`: Signature mismatch
|
|
129
|
+
- `TOKEN_EXPIRED`: `exp` claim exceeded
|
|
130
|
+
- `TOKEN_NOT_ACTIVE`: `nbf` claim not reached
|
|
131
|
+
- `TOKEN_FUTURE_ISSUED`: `iat` claim in future
|
|
132
|
+
|
|
133
|
+
---
|
|
134
|
+
|
|
135
|
+
### `decode(token)`
|
|
136
|
+
Decode a JWT without verification (use with caution!).
|
|
137
|
+
|
|
138
|
+
- `token`: JWT string
|
|
139
|
+
|
|
140
|
+
Returns: `{ header, payload, signature }`
|
|
141
|
+
|
|
142
|
+
Throws on malformed tokens.
|
|
143
|
+
|
|
144
|
+
---
|
|
145
|
+
|
|
146
|
+
## 🧪 Testing
|
|
147
|
+
|
|
148
|
+
This library has **100% test coverage** with Vitest:
|
|
149
|
+
|
|
150
|
+
```bash
|
|
151
|
+
npm test
|
|
152
|
+
npm run test:coverage
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
Tests include:
|
|
156
|
+
- All algorithms (HMAC, RSA, ECDSA)
|
|
157
|
+
- Time validation edge cases
|
|
158
|
+
- Malformed token handling
|
|
159
|
+
- Signature verification
|
|
160
|
+
- Custom claims
|
|
161
|
+
|
|
162
|
+
---
|
|
163
|
+
|
|
164
|
+
## 🙌 Contributing
|
|
165
|
+
|
|
166
|
+
PRs welcome! Please:
|
|
167
|
+
1. Add tests for new features
|
|
168
|
+
2. Maintain 100% coverage
|
|
169
|
+
3. Follow existing code style
|
|
170
|
+
|
|
171
|
+
Found a security issue? [Report it responsibly](mailto:a.p.a.slaa@projectsource.nl).
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const a=require("crypto"),d={encode:e=>Buffer.from(e).toString("base64url"),decode:e=>Buffer.from(e,"base64url").toString()},c={HS256:{sign:(e,r)=>a.createHmac("sha256",r).update(e).digest("base64url"),verify:(e,r,t)=>a.createHmac("sha256",r).update(e).digest("base64url")===t},HS384:{sign:(e,r)=>a.createHmac("sha384",r).update(e).digest("base64url"),verify:(e,r,t)=>a.createHmac("sha384",r).update(e).digest("base64url")===t},HS512:{sign:(e,r)=>a.createHmac("sha512",r).update(e).digest("base64url"),verify:(e,r,t)=>a.createHmac("sha512",r).update(e).digest("base64url")===t},RS256:{sign:(e,r)=>a.createSign("RSA-SHA256").update(e).end().sign(r).toString("base64url"),verify:(e,r,t)=>a.createVerify("RSA-SHA256").update(e).end().verify(r,Buffer.from(t,"base64url"))},RS384:{sign:(e,r)=>a.createSign("RSA-SHA384").update(e).end().sign(r).toString("base64url"),verify:(e,r,t)=>a.createVerify("RSA-SHA384").update(e).end().verify(r,Buffer.from(t,"base64url"))},RS512:{sign:(e,r)=>a.createSign("RSA-SHA512").update(e).end().sign(r).toString("base64url"),verify:(e,r,t)=>a.createVerify("RSA-SHA512").update(e).end().verify(r,Buffer.from(t,"base64url"))},ES256:{sign:(e,r)=>a.createSign("SHA256").update(e).end().sign(r).toString("base64url"),verify:(e,r,t)=>a.createVerify("SHA256").update(e).end().verify(r,Buffer.from(t,"base64url"))},ES384:{sign:(e,r)=>a.createSign("SHA384").update(e).end().sign(r).toString("base64url"),verify:(e,r,t)=>a.createVerify("SHA384").update(e).end().verify(r,Buffer.from(t,"base64url"))},ES512:{sign:(e,r)=>a.createSign("SHA512").update(e).end().sign(r).toString("base64url"),verify:(e,r,t)=>a.createVerify("SHA512").update(e).end().verify(r,Buffer.from(t,"base64url"))}},b=Object.keys(c),S=e=>{const r=e.split(".");if(r.length!==3)throw new Error('Invalid JWT: must contain exactly 3 parts separated by "."');const[t,s,i]=r;if(!t||!s||!i)throw new Error("Invalid JWT: empty part detected");try{const n=JSON.parse(d.decode(t)),o=JSON.parse(d.decode(s));return{header:n,payload:o,signature:i}}catch(n){throw new Error(`Invalid JWT: malformed header or payload (${n.message})`)}},y=(e,r,t={})=>{const s=t.alg??"HS256",i=t.typ??"JWT";if(!(s in c))throw new Error(`Unsupported algorithm: ${s}`);const n={alg:s,typ:i};t.kid&&(n.kid=t.kid);const o=d.encode(JSON.stringify(n)),u=d.encode(JSON.stringify(e)),f=`${o}.${u}`,p=c[s].sign(f,r);return`${o}.${u}.${p}`},v=(e,r,t={})=>{let s;try{s=S(e)}catch(A){return{valid:!1,error:{reason:A.message,code:"INVALID_TOKEN"}}}const{header:i,payload:n,signature:o}=s,u=i.alg;if(!(u in c))return{valid:!1,error:{reason:`Unsupported or unknown algorithm: ${i.alg}`,code:"INVALID_ALGORITHM"}};if(i.typ&&i.typ!=="JWT")return{valid:!1,error:{reason:`Invalid token type: expected 'JWT', got '${i.typ}'`,code:"INVALID_TYPE"}};const f=`${d.encode(JSON.stringify(i))}.${d.encode(JSON.stringify(n))}`;if(!c[u].verify(f,r,o))return{valid:!1,error:{reason:"Signature verification failed",code:"INVALID_SIGNATURE"}};const g=Math.floor(Date.now()/1e3),l=t.clockSkew??0;return!t.ignoreExpiration&&n.exp!==void 0&&g>n.exp+l?{valid:!1,error:{reason:"Token expired",code:"TOKEN_EXPIRED"}}:n.nbf!==void 0&&g+l<n.nbf?{valid:!1,error:{reason:"Token not yet valid",code:"TOKEN_NOT_ACTIVE"}}:n.iat!==void 0&&g+l<n.iat?{valid:!1,error:{reason:"Token issued in the future",code:"TOKEN_FUTURE_ISSUED"}}:{valid:!0,header:i,payload:n,signature:o}},h={sign:y,verify:v,decode:S,algorithms:c};exports.JWT=h;exports.SignatureAlgorithm=c;exports.SupportedAlgorithms=b;exports.base64Url=d;exports.decode=S;exports.sign=y;exports.verify=v;
|
|
2
|
+
//# sourceMappingURL=index.cjs.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.cjs.js","sources":["../src/index.ts"],"sourcesContent":["import {\n createHmac,\n createSign,\n createVerify,\n type BinaryLike,\n type KeyLike\n} from 'crypto';\n\n// Base64URL helpers (padding-safe)\nexport const base64Url = {\n encode: (input: string | Buffer): string =>\n Buffer.from(input).toString('base64url'),\n\n decode: (input: string): string => {\n // Node.js Buffer handles unpadded base64url since v16, but we normalize for safety\n return Buffer.from(input, 'base64url').toString();\n }\n};\n\n// Standard JWT payload claims\nexport interface JWTPayload {\n /**\n * Issuer\n */\n iss?: string;\n /**\n * Subject\n */\n sub?: string;\n /**\n * Audience\n */\n aud?: string | string[];\n /**\n * Expiration Time (as UNIX timestamp)\n */\n exp?: number;\n /**\n * Not Before (as UNIX timestamp)\n */\n nbf?: number;\n /**\n * Issued At (as UNIX timestamp)\n */\n iat?: number;\n /**\n * JWT ID\n */\n jti?: string;\n /**\n * Session ID\n */\n sid?: string;\n /**\n * Custom claims\n */\n [key: string]: unknown;\n}\n\nexport interface JWTHeader {\n alg: string; // Allow unknown algs during decode\n typ?: string;\n kid?: string;\n}\n\nexport interface JWT {\n header: JWTHeader;\n payload: JWTPayload;\n signature: string;\n}\n\n// Signature algorithms\nexport const SignatureAlgorithm = {\n // HMAC\n HS256: {\n sign: (data: BinaryLike, secret: KeyLike) =>\n createHmac('sha256', secret).update(data).digest('base64url'),\n verify: (data: BinaryLike, secret: KeyLike, signature: string) =>\n createHmac('sha256', secret).update(data).digest('base64url') === signature\n },\n HS384: {\n sign: (data: BinaryLike, secret: KeyLike) =>\n createHmac('sha384', secret).update(data).digest('base64url'),\n verify: (data: BinaryLike, secret: KeyLike, signature: string) =>\n createHmac('sha384', secret).update(data).digest('base64url') === signature\n },\n HS512: {\n sign: (data: BinaryLike, secret: KeyLike) =>\n createHmac('sha512', secret).update(data).digest('base64url'),\n verify: (data: BinaryLike, secret: KeyLike, signature: string) =>\n createHmac('sha512', secret).update(data).digest('base64url') === signature\n },\n\n // RSA (DER-encoded signatures, base64url)\n RS256: {\n sign: (data: BinaryLike, secret: KeyLike) =>\n createSign('RSA-SHA256').update(data).end().sign(secret).toString('base64url'),\n verify: (data: BinaryLike, secret: KeyLike, signature: string) =>\n createVerify('RSA-SHA256')\n .update(data)\n .end()\n .verify(secret, Buffer.from(signature, 'base64url'))\n },\n RS384: {\n sign: (data: BinaryLike, secret: KeyLike) =>\n createSign('RSA-SHA384').update(data).end().sign(secret).toString('base64url'),\n verify: (data: BinaryLike, secret: KeyLike, signature: string) =>\n createVerify('RSA-SHA384')\n .update(data)\n .end()\n .verify(secret, Buffer.from(signature, 'base64url'))\n },\n RS512: {\n sign: (data: BinaryLike, secret: KeyLike) =>\n createSign('RSA-SHA512').update(data).end().sign(secret).toString('base64url'),\n verify: (data: BinaryLike, secret: KeyLike, signature: string) =>\n createVerify('RSA-SHA512')\n .update(data)\n .end()\n .verify(secret, Buffer.from(signature, 'base64url'))\n },\n\n // ECDSA (DER-encoded by default — no dsaEncoding!)\n ES256: {\n sign: (data: BinaryLike, secret: KeyLike) =>\n createSign('SHA256').update(data).end().sign(secret).toString('base64url'),\n verify: (data: BinaryLike, secret: KeyLike, signature: string) =>\n createVerify('SHA256')\n .update(data)\n .end()\n .verify(secret, Buffer.from(signature, 'base64url'))\n },\n ES384: {\n sign: (data: BinaryLike, secret: KeyLike) =>\n createSign('SHA384').update(data).end().sign(secret).toString('base64url'),\n verify: (data: BinaryLike, secret: KeyLike, signature: string) =>\n createVerify('SHA384')\n .update(data)\n .end()\n .verify(secret, Buffer.from(signature, 'base64url'))\n },\n ES512: {\n sign: (data: BinaryLike, secret: KeyLike) =>\n createSign('SHA512').update(data).end().sign(secret).toString('base64url'),\n verify: (data: BinaryLike, secret: KeyLike, signature: string) =>\n createVerify('SHA512')\n .update(data)\n .end()\n .verify(secret, Buffer.from(signature, 'base64url'))\n }\n} as const;\n\nexport type SupportedAlgorithm = keyof typeof SignatureAlgorithm;\n\nexport const SupportedAlgorithms = Object.keys(SignatureAlgorithm) as Array<SupportedAlgorithm>;\n\n/**\n * Decode a JWT string into its parts (without verification)\n */\nexport const decode = (token: string): JWT => {\n const parts = token.split('.');\n if (parts.length !== 3) {\n throw new Error('Invalid JWT: must contain exactly 3 parts separated by \".\"');\n }\n\n const [headerPart, payloadPart, signature] = parts;\n\n if (!headerPart || !payloadPart || !signature) {\n throw new Error('Invalid JWT: empty part detected');\n }\n\n try {\n const header = JSON.parse(base64Url.decode(headerPart)) as JWTHeader;\n const payload = JSON.parse(base64Url.decode(payloadPart)) as JWTPayload;\n return { header, payload, signature };\n } catch (err) {\n throw new Error(`Invalid JWT: malformed header or payload (${(err as Error).message})`);\n }\n};\n\n/**\n * Sign a JWT\n */\nexport const sign = (\n payload: JWTPayload,\n secret: KeyLike,\n options: {\n alg?: SupportedAlgorithm;\n kid?: string;\n typ?: string;\n } = {}\n): string => {\n const alg = options.alg ?? 'HS256';\n const typ = options.typ ?? 'JWT';\n\n if (!(alg in SignatureAlgorithm)) {\n throw new Error(`Unsupported algorithm: ${alg}`);\n }\n\n const header: JWTHeader = { alg, typ };\n if (options.kid) header.kid = options.kid;\n\n const headerEncoded = base64Url.encode(JSON.stringify(header));\n const payloadEncoded = base64Url.encode(JSON.stringify(payload));\n\n const signingInput = `${headerEncoded}.${payloadEncoded}`;\n const signature = SignatureAlgorithm[alg].sign(signingInput, secret);\n\n return `${headerEncoded}.${payloadEncoded}.${signature}`;\n};\n\n/**\n * Verify and validate a JWT\n */\nexport const verify = (\n token: string,\n secret: KeyLike,\n options: {\n ignoreExpiration?: boolean;\n clockSkew?: number; // in seconds, default 0\n } = {}\n):\n | { valid: true; header: JWTHeader; payload: JWTPayload; signature: string }\n | { valid: false; error: { reason: string; code: string } } => {\n let decoded: JWT;\n try {\n decoded = decode(token);\n } catch (err) {\n return {\n valid: false,\n error: {\n reason: (err as Error).message,\n code: 'INVALID_TOKEN'\n }\n };\n }\n\n const { header, payload, signature } = decoded;\n\n // Validate algorithm\n const alg = header.alg as SupportedAlgorithm;\n if (!(alg in SignatureAlgorithm)) {\n return {\n valid: false,\n error: {\n reason: `Unsupported or unknown algorithm: ${header.alg}`,\n code: 'INVALID_ALGORITHM'\n }\n };\n }\n\n // Optional: validate 'typ' header\n if (header.typ && header.typ !== 'JWT') {\n return {\n valid: false,\n error: {\n reason: `Invalid token type: expected 'JWT', got '${header.typ}'`,\n code: 'INVALID_TYPE'\n }\n };\n }\n\n // Verify signature\n const signingInput = `${base64Url.encode(JSON.stringify(header))}.${base64Url.encode(JSON.stringify(payload))}`;\n const isValidSignature = SignatureAlgorithm[alg].verify(signingInput, secret, signature);\n\n if (!isValidSignature) {\n return {\n valid: false,\n error: {\n reason: \"Signature verification failed\",\n code: 'INVALID_SIGNATURE'\n }\n };\n }\n\n // Time validation\n const now = Math.floor(Date.now() / 1000);\n const skew = options.clockSkew ?? 0;\n\n if (!options.ignoreExpiration) {\n if (payload.exp !== undefined && now > payload.exp + skew) {\n return {\n valid: false,\n error: {\n reason: 'Token expired',\n code: 'TOKEN_EXPIRED'\n }\n };\n }\n }\n\n if (payload.nbf !== undefined && now + skew < payload.nbf) {\n return {\n valid: false,\n error: {\n reason: 'Token not yet valid',\n code: 'TOKEN_NOT_ACTIVE'\n }\n };\n }\n\n if (payload.iat !== undefined && now + skew < payload.iat) {\n return {\n valid: false,\n error: {\n reason: 'Token issued in the future',\n code: 'TOKEN_FUTURE_ISSUED'\n }\n };\n }\n\n return { valid: true, header, payload, signature };\n};\n\n// Optional: namespace export (not default)\nexport const JWT = {\n sign,\n verify,\n decode,\n algorithms: SignatureAlgorithm\n};\n"],"names":["base64Url","input","SignatureAlgorithm","data","secret","createHmac","signature","createSign","createVerify","SupportedAlgorithms","decode","token","parts","headerPart","payloadPart","header","payload","err","sign","options","alg","typ","headerEncoded","payloadEncoded","signingInput","verify","decoded","now","skew","JWT"],"mappings":"0GASaA,EAAY,CACrB,OAASC,GACL,OAAO,KAAKA,CAAK,EAAE,SAAS,WAAW,EAE3C,OAASA,GAEE,OAAO,KAAKA,EAAO,WAAW,EAAE,SAAA,CAE/C,EAuDaC,EAAqB,CAE9B,MAAO,CACH,KAAM,CAACC,EAAkBC,IACrBC,EAAAA,WAAW,SAAUD,CAAM,EAAE,OAAOD,CAAI,EAAE,OAAO,WAAW,EAChE,OAAQ,CAACA,EAAkBC,EAAiBE,IACxCD,EAAAA,WAAW,SAAUD,CAAM,EAAE,OAAOD,CAAI,EAAE,OAAO,WAAW,IAAMG,CAAA,EAE1E,MAAO,CACH,KAAM,CAACH,EAAkBC,IACrBC,EAAAA,WAAW,SAAUD,CAAM,EAAE,OAAOD,CAAI,EAAE,OAAO,WAAW,EAChE,OAAQ,CAACA,EAAkBC,EAAiBE,IACxCD,EAAAA,WAAW,SAAUD,CAAM,EAAE,OAAOD,CAAI,EAAE,OAAO,WAAW,IAAMG,CAAA,EAE1E,MAAO,CACH,KAAM,CAACH,EAAkBC,IACrBC,EAAAA,WAAW,SAAUD,CAAM,EAAE,OAAOD,CAAI,EAAE,OAAO,WAAW,EAChE,OAAQ,CAACA,EAAkBC,EAAiBE,IACxCD,EAAAA,WAAW,SAAUD,CAAM,EAAE,OAAOD,CAAI,EAAE,OAAO,WAAW,IAAMG,CAAA,EAI1E,MAAO,CACH,KAAM,CAACH,EAAkBC,IACrBG,EAAAA,WAAW,YAAY,EAAE,OAAOJ,CAAI,EAAE,MAAM,KAAKC,CAAM,EAAE,SAAS,WAAW,EACjF,OAAQ,CAACD,EAAkBC,EAAiBE,IACxCE,EAAAA,aAAa,YAAY,EACpB,OAAOL,CAAI,EACX,IAAA,EACA,OAAOC,EAAQ,OAAO,KAAKE,EAAW,WAAW,CAAC,CAAA,EAE/D,MAAO,CACH,KAAM,CAACH,EAAkBC,IAC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ACP,MAAO,CACH,OAAQ,6BACR,KAAM,qBAAA,CACV,EAID,CAAE,MAAO,GAAM,OAAAD,EAAQ,QAAAC,EAAS,UAAAV,CAAA,CAC3C,EAGauB,EAAM,CACf,KAAAX,EACA,OAAAO,EACA,OAAAf,EACA,WAAYR,CAChB"}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
import { BinaryLike, KeyLike } from 'crypto';
|
|
2
|
+
export declare const base64Url: {
|
|
3
|
+
encode: (input: string | Buffer) => string;
|
|
4
|
+
decode: (input: string) => string;
|
|
5
|
+
};
|
|
6
|
+
export interface JWTPayload {
|
|
7
|
+
/**
|
|
8
|
+
* Issuer
|
|
9
|
+
*/
|
|
10
|
+
iss?: string;
|
|
11
|
+
/**
|
|
12
|
+
* Subject
|
|
13
|
+
*/
|
|
14
|
+
sub?: string;
|
|
15
|
+
/**
|
|
16
|
+
* Audience
|
|
17
|
+
*/
|
|
18
|
+
aud?: string | string[];
|
|
19
|
+
/**
|
|
20
|
+
* Expiration Time (as UNIX timestamp)
|
|
21
|
+
*/
|
|
22
|
+
exp?: number;
|
|
23
|
+
/**
|
|
24
|
+
* Not Before (as UNIX timestamp)
|
|
25
|
+
*/
|
|
26
|
+
nbf?: number;
|
|
27
|
+
/**
|
|
28
|
+
* Issued At (as UNIX timestamp)
|
|
29
|
+
*/
|
|
30
|
+
iat?: number;
|
|
31
|
+
/**
|
|
32
|
+
* JWT ID
|
|
33
|
+
*/
|
|
34
|
+
jti?: string;
|
|
35
|
+
/**
|
|
36
|
+
* Session ID
|
|
37
|
+
*/
|
|
38
|
+
sid?: string;
|
|
39
|
+
/**
|
|
40
|
+
* Custom claims
|
|
41
|
+
*/
|
|
42
|
+
[key: string]: unknown;
|
|
43
|
+
}
|
|
44
|
+
export interface JWTHeader {
|
|
45
|
+
alg: string;
|
|
46
|
+
typ?: string;
|
|
47
|
+
kid?: string;
|
|
48
|
+
}
|
|
49
|
+
export interface JWT {
|
|
50
|
+
header: JWTHeader;
|
|
51
|
+
payload: JWTPayload;
|
|
52
|
+
signature: string;
|
|
53
|
+
}
|
|
54
|
+
export declare const SignatureAlgorithm: {
|
|
55
|
+
readonly HS256: {
|
|
56
|
+
readonly sign: (data: BinaryLike, secret: KeyLike) => string;
|
|
57
|
+
readonly verify: (data: BinaryLike, secret: KeyLike, signature: string) => boolean;
|
|
58
|
+
};
|
|
59
|
+
readonly HS384: {
|
|
60
|
+
readonly sign: (data: BinaryLike, secret: KeyLike) => string;
|
|
61
|
+
readonly verify: (data: BinaryLike, secret: KeyLike, signature: string) => boolean;
|
|
62
|
+
};
|
|
63
|
+
readonly HS512: {
|
|
64
|
+
readonly sign: (data: BinaryLike, secret: KeyLike) => string;
|
|
65
|
+
readonly verify: (data: BinaryLike, secret: KeyLike, signature: string) => boolean;
|
|
66
|
+
};
|
|
67
|
+
readonly RS256: {
|
|
68
|
+
readonly sign: (data: BinaryLike, secret: KeyLike) => string;
|
|
69
|
+
readonly verify: (data: BinaryLike, secret: KeyLike, signature: string) => boolean;
|
|
70
|
+
};
|
|
71
|
+
readonly RS384: {
|
|
72
|
+
readonly sign: (data: BinaryLike, secret: KeyLike) => string;
|
|
73
|
+
readonly verify: (data: BinaryLike, secret: KeyLike, signature: string) => boolean;
|
|
74
|
+
};
|
|
75
|
+
readonly RS512: {
|
|
76
|
+
readonly sign: (data: BinaryLike, secret: KeyLike) => string;
|
|
77
|
+
readonly verify: (data: BinaryLike, secret: KeyLike, signature: string) => boolean;
|
|
78
|
+
};
|
|
79
|
+
readonly ES256: {
|
|
80
|
+
readonly sign: (data: BinaryLike, secret: KeyLike) => string;
|
|
81
|
+
readonly verify: (data: BinaryLike, secret: KeyLike, signature: string) => boolean;
|
|
82
|
+
};
|
|
83
|
+
readonly ES384: {
|
|
84
|
+
readonly sign: (data: BinaryLike, secret: KeyLike) => string;
|
|
85
|
+
readonly verify: (data: BinaryLike, secret: KeyLike, signature: string) => boolean;
|
|
86
|
+
};
|
|
87
|
+
readonly ES512: {
|
|
88
|
+
readonly sign: (data: BinaryLike, secret: KeyLike) => string;
|
|
89
|
+
readonly verify: (data: BinaryLike, secret: KeyLike, signature: string) => boolean;
|
|
90
|
+
};
|
|
91
|
+
};
|
|
92
|
+
export type SupportedAlgorithm = keyof typeof SignatureAlgorithm;
|
|
93
|
+
export declare const SupportedAlgorithms: Array<SupportedAlgorithm>;
|
|
94
|
+
/**
|
|
95
|
+
* Decode a JWT string into its parts (without verification)
|
|
96
|
+
*/
|
|
97
|
+
export declare const decode: (token: string) => JWT;
|
|
98
|
+
/**
|
|
99
|
+
* Sign a JWT
|
|
100
|
+
*/
|
|
101
|
+
export declare const sign: (payload: JWTPayload, secret: KeyLike, options?: {
|
|
102
|
+
alg?: SupportedAlgorithm;
|
|
103
|
+
kid?: string;
|
|
104
|
+
typ?: string;
|
|
105
|
+
}) => string;
|
|
106
|
+
/**
|
|
107
|
+
* Verify and validate a JWT
|
|
108
|
+
*/
|
|
109
|
+
export declare const verify: (token: string, secret: KeyLike, options?: {
|
|
110
|
+
ignoreExpiration?: boolean;
|
|
111
|
+
clockSkew?: number;
|
|
112
|
+
}) => {
|
|
113
|
+
valid: true;
|
|
114
|
+
header: JWTHeader;
|
|
115
|
+
payload: JWTPayload;
|
|
116
|
+
signature: string;
|
|
117
|
+
} | {
|
|
118
|
+
valid: false;
|
|
119
|
+
error: {
|
|
120
|
+
reason: string;
|
|
121
|
+
code: string;
|
|
122
|
+
};
|
|
123
|
+
};
|
|
124
|
+
export declare const JWT: {
|
|
125
|
+
sign: (payload: JWTPayload, secret: KeyLike, options?: {
|
|
126
|
+
alg?: SupportedAlgorithm;
|
|
127
|
+
kid?: string;
|
|
128
|
+
typ?: string;
|
|
129
|
+
}) => string;
|
|
130
|
+
verify: (token: string, secret: KeyLike, options?: {
|
|
131
|
+
ignoreExpiration?: boolean;
|
|
132
|
+
clockSkew?: number;
|
|
133
|
+
}) => {
|
|
134
|
+
valid: true;
|
|
135
|
+
header: JWTHeader;
|
|
136
|
+
payload: JWTPayload;
|
|
137
|
+
signature: string;
|
|
138
|
+
} | {
|
|
139
|
+
valid: false;
|
|
140
|
+
error: {
|
|
141
|
+
reason: string;
|
|
142
|
+
code: string;
|
|
143
|
+
};
|
|
144
|
+
};
|
|
145
|
+
decode: (token: string) => JWT;
|
|
146
|
+
algorithms: {
|
|
147
|
+
readonly HS256: {
|
|
148
|
+
readonly sign: (data: BinaryLike, secret: KeyLike) => string;
|
|
149
|
+
readonly verify: (data: BinaryLike, secret: KeyLike, signature: string) => boolean;
|
|
150
|
+
};
|
|
151
|
+
readonly HS384: {
|
|
152
|
+
readonly sign: (data: BinaryLike, secret: KeyLike) => string;
|
|
153
|
+
readonly verify: (data: BinaryLike, secret: KeyLike, signature: string) => boolean;
|
|
154
|
+
};
|
|
155
|
+
readonly HS512: {
|
|
156
|
+
readonly sign: (data: BinaryLike, secret: KeyLike) => string;
|
|
157
|
+
readonly verify: (data: BinaryLike, secret: KeyLike, signature: string) => boolean;
|
|
158
|
+
};
|
|
159
|
+
readonly RS256: {
|
|
160
|
+
readonly sign: (data: BinaryLike, secret: KeyLike) => string;
|
|
161
|
+
readonly verify: (data: BinaryLike, secret: KeyLike, signature: string) => boolean;
|
|
162
|
+
};
|
|
163
|
+
readonly RS384: {
|
|
164
|
+
readonly sign: (data: BinaryLike, secret: KeyLike) => string;
|
|
165
|
+
readonly verify: (data: BinaryLike, secret: KeyLike, signature: string) => boolean;
|
|
166
|
+
};
|
|
167
|
+
readonly RS512: {
|
|
168
|
+
readonly sign: (data: BinaryLike, secret: KeyLike) => string;
|
|
169
|
+
readonly verify: (data: BinaryLike, secret: KeyLike, signature: string) => boolean;
|
|
170
|
+
};
|
|
171
|
+
readonly ES256: {
|
|
172
|
+
readonly sign: (data: BinaryLike, secret: KeyLike) => string;
|
|
173
|
+
readonly verify: (data: BinaryLike, secret: KeyLike, signature: string) => boolean;
|
|
174
|
+
};
|
|
175
|
+
readonly ES384: {
|
|
176
|
+
readonly sign: (data: BinaryLike, secret: KeyLike) => string;
|
|
177
|
+
readonly verify: (data: BinaryLike, secret: KeyLike, signature: string) => boolean;
|
|
178
|
+
};
|
|
179
|
+
readonly ES512: {
|
|
180
|
+
readonly sign: (data: BinaryLike, secret: KeyLike) => string;
|
|
181
|
+
readonly verify: (data: BinaryLike, secret: KeyLike, signature: string) => boolean;
|
|
182
|
+
};
|
|
183
|
+
};
|
|
184
|
+
};
|
package/dist/index.es.js
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
import { createVerify as o, createSign as d, createHmac as u } from "crypto";
|
|
2
|
+
const f = {
|
|
3
|
+
encode: (e) => Buffer.from(e).toString("base64url"),
|
|
4
|
+
decode: (e) => Buffer.from(e, "base64url").toString()
|
|
5
|
+
}, l = {
|
|
6
|
+
// HMAC
|
|
7
|
+
HS256: {
|
|
8
|
+
sign: (e, r) => u("sha256", r).update(e).digest("base64url"),
|
|
9
|
+
verify: (e, r, t) => u("sha256", r).update(e).digest("base64url") === t
|
|
10
|
+
},
|
|
11
|
+
HS384: {
|
|
12
|
+
sign: (e, r) => u("sha384", r).update(e).digest("base64url"),
|
|
13
|
+
verify: (e, r, t) => u("sha384", r).update(e).digest("base64url") === t
|
|
14
|
+
},
|
|
15
|
+
HS512: {
|
|
16
|
+
sign: (e, r) => u("sha512", r).update(e).digest("base64url"),
|
|
17
|
+
verify: (e, r, t) => u("sha512", r).update(e).digest("base64url") === t
|
|
18
|
+
},
|
|
19
|
+
// RSA (DER-encoded signatures, base64url)
|
|
20
|
+
RS256: {
|
|
21
|
+
sign: (e, r) => d("RSA-SHA256").update(e).end().sign(r).toString("base64url"),
|
|
22
|
+
verify: (e, r, t) => o("RSA-SHA256").update(e).end().verify(r, Buffer.from(t, "base64url"))
|
|
23
|
+
},
|
|
24
|
+
RS384: {
|
|
25
|
+
sign: (e, r) => d("RSA-SHA384").update(e).end().sign(r).toString("base64url"),
|
|
26
|
+
verify: (e, r, t) => o("RSA-SHA384").update(e).end().verify(r, Buffer.from(t, "base64url"))
|
|
27
|
+
},
|
|
28
|
+
RS512: {
|
|
29
|
+
sign: (e, r) => d("RSA-SHA512").update(e).end().sign(r).toString("base64url"),
|
|
30
|
+
verify: (e, r, t) => o("RSA-SHA512").update(e).end().verify(r, Buffer.from(t, "base64url"))
|
|
31
|
+
},
|
|
32
|
+
// ECDSA (DER-encoded by default — no dsaEncoding!)
|
|
33
|
+
ES256: {
|
|
34
|
+
sign: (e, r) => d("SHA256").update(e).end().sign(r).toString("base64url"),
|
|
35
|
+
verify: (e, r, t) => o("SHA256").update(e).end().verify(r, Buffer.from(t, "base64url"))
|
|
36
|
+
},
|
|
37
|
+
ES384: {
|
|
38
|
+
sign: (e, r) => d("SHA384").update(e).end().sign(r).toString("base64url"),
|
|
39
|
+
verify: (e, r, t) => o("SHA384").update(e).end().verify(r, Buffer.from(t, "base64url"))
|
|
40
|
+
},
|
|
41
|
+
ES512: {
|
|
42
|
+
sign: (e, r) => d("SHA512").update(e).end().sign(r).toString("base64url"),
|
|
43
|
+
verify: (e, r, t) => o("SHA512").update(e).end().verify(r, Buffer.from(t, "base64url"))
|
|
44
|
+
}
|
|
45
|
+
}, E = Object.keys(l), v = (e) => {
|
|
46
|
+
const r = e.split(".");
|
|
47
|
+
if (r.length !== 3)
|
|
48
|
+
throw new Error('Invalid JWT: must contain exactly 3 parts separated by "."');
|
|
49
|
+
const [t, i, n] = r;
|
|
50
|
+
if (!t || !i || !n)
|
|
51
|
+
throw new Error("Invalid JWT: empty part detected");
|
|
52
|
+
try {
|
|
53
|
+
const a = JSON.parse(f.decode(t)), s = JSON.parse(f.decode(i));
|
|
54
|
+
return { header: a, payload: s, signature: n };
|
|
55
|
+
} catch (a) {
|
|
56
|
+
throw new Error(`Invalid JWT: malformed header or payload (${a.message})`);
|
|
57
|
+
}
|
|
58
|
+
}, h = (e, r, t = {}) => {
|
|
59
|
+
const i = t.alg ?? "HS256", n = t.typ ?? "JWT";
|
|
60
|
+
if (!(i in l))
|
|
61
|
+
throw new Error(`Unsupported algorithm: ${i}`);
|
|
62
|
+
const a = { alg: i, typ: n };
|
|
63
|
+
t.kid && (a.kid = t.kid);
|
|
64
|
+
const s = f.encode(JSON.stringify(a)), g = f.encode(JSON.stringify(e)), c = `${s}.${g}`, y = l[i].sign(c, r);
|
|
65
|
+
return `${s}.${g}.${y}`;
|
|
66
|
+
}, b = (e, r, t = {}) => {
|
|
67
|
+
let i;
|
|
68
|
+
try {
|
|
69
|
+
i = v(e);
|
|
70
|
+
} catch (A) {
|
|
71
|
+
return {
|
|
72
|
+
valid: !1,
|
|
73
|
+
error: {
|
|
74
|
+
reason: A.message,
|
|
75
|
+
code: "INVALID_TOKEN"
|
|
76
|
+
}
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
const { header: n, payload: a, signature: s } = i, g = n.alg;
|
|
80
|
+
if (!(g in l))
|
|
81
|
+
return {
|
|
82
|
+
valid: !1,
|
|
83
|
+
error: {
|
|
84
|
+
reason: `Unsupported or unknown algorithm: ${n.alg}`,
|
|
85
|
+
code: "INVALID_ALGORITHM"
|
|
86
|
+
}
|
|
87
|
+
};
|
|
88
|
+
if (n.typ && n.typ !== "JWT")
|
|
89
|
+
return {
|
|
90
|
+
valid: !1,
|
|
91
|
+
error: {
|
|
92
|
+
reason: `Invalid token type: expected 'JWT', got '${n.typ}'`,
|
|
93
|
+
code: "INVALID_TYPE"
|
|
94
|
+
}
|
|
95
|
+
};
|
|
96
|
+
const c = `${f.encode(JSON.stringify(n))}.${f.encode(JSON.stringify(a))}`;
|
|
97
|
+
if (!l[g].verify(c, r, s))
|
|
98
|
+
return {
|
|
99
|
+
valid: !1,
|
|
100
|
+
error: {
|
|
101
|
+
reason: "Signature verification failed",
|
|
102
|
+
code: "INVALID_SIGNATURE"
|
|
103
|
+
}
|
|
104
|
+
};
|
|
105
|
+
const S = Math.floor(Date.now() / 1e3), p = t.clockSkew ?? 0;
|
|
106
|
+
return !t.ignoreExpiration && a.exp !== void 0 && S > a.exp + p ? {
|
|
107
|
+
valid: !1,
|
|
108
|
+
error: {
|
|
109
|
+
reason: "Token expired",
|
|
110
|
+
code: "TOKEN_EXPIRED"
|
|
111
|
+
}
|
|
112
|
+
} : a.nbf !== void 0 && S + p < a.nbf ? {
|
|
113
|
+
valid: !1,
|
|
114
|
+
error: {
|
|
115
|
+
reason: "Token not yet valid",
|
|
116
|
+
code: "TOKEN_NOT_ACTIVE"
|
|
117
|
+
}
|
|
118
|
+
} : a.iat !== void 0 && S + p < a.iat ? {
|
|
119
|
+
valid: !1,
|
|
120
|
+
error: {
|
|
121
|
+
reason: "Token issued in the future",
|
|
122
|
+
code: "TOKEN_FUTURE_ISSUED"
|
|
123
|
+
}
|
|
124
|
+
} : { valid: !0, header: n, payload: a, signature: s };
|
|
125
|
+
}, T = {
|
|
126
|
+
sign: h,
|
|
127
|
+
verify: b,
|
|
128
|
+
decode: v,
|
|
129
|
+
algorithms: l
|
|
130
|
+
};
|
|
131
|
+
export {
|
|
132
|
+
T as JWT,
|
|
133
|
+
l as SignatureAlgorithm,
|
|
134
|
+
E as SupportedAlgorithms,
|
|
135
|
+
f as base64Url,
|
|
136
|
+
v as decode,
|
|
137
|
+
h as sign,
|
|
138
|
+
b as verify
|
|
139
|
+
};
|
|
140
|
+
//# sourceMappingURL=index.es.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.es.js","sources":["../src/index.ts"],"sourcesContent":["import {\n createHmac,\n createSign,\n createVerify,\n type BinaryLike,\n type KeyLike\n} from 'crypto';\n\n// Base64URL helpers (padding-safe)\nexport const base64Url = {\n encode: (input: string | Buffer): string =>\n Buffer.from(input).toString('base64url'),\n\n decode: (input: string): string => {\n // Node.js Buffer handles unpadded base64url since v16, but we normalize for safety\n return Buffer.from(input, 'base64url').toString();\n }\n};\n\n// Standard JWT payload claims\nexport interface JWTPayload {\n /**\n * Issuer\n */\n iss?: string;\n /**\n * Subject\n */\n sub?: string;\n /**\n * Audience\n */\n aud?: string | string[];\n /**\n * Expiration Time (as UNIX timestamp)\n */\n exp?: number;\n /**\n * Not Before (as UNIX timestamp)\n */\n nbf?: number;\n /**\n * Issued At (as UNIX timestamp)\n */\n iat?: number;\n /**\n * JWT ID\n */\n jti?: string;\n /**\n * Session ID\n */\n sid?: string;\n /**\n * Custom claims\n */\n [key: string]: unknown;\n}\n\nexport interface JWTHeader {\n alg: string; // Allow unknown algs during decode\n typ?: string;\n kid?: string;\n}\n\nexport interface JWT {\n header: JWTHeader;\n payload: JWTPayload;\n signature: string;\n}\n\n// Signature algorithms\nexport const SignatureAlgorithm = {\n // HMAC\n HS256: {\n sign: (data: BinaryLike, secret: KeyLike) =>\n createHmac('sha256', secret).update(data).digest('base64url'),\n verify: (data: BinaryLike, secret: KeyLike, signature: string) =>\n createHmac('sha256', secret).update(data).digest('base64url') === signature\n },\n HS384: {\n sign: (data: BinaryLike, secret: KeyLike) =>\n createHmac('sha384', secret).update(data).digest('base64url'),\n verify: (data: BinaryLike, secret: KeyLike, signature: string) =>\n createHmac('sha384', secret).update(data).digest('base64url') === signature\n },\n HS512: {\n sign: (data: BinaryLike, secret: KeyLike) =>\n createHmac('sha512', secret).update(data).digest('base64url'),\n verify: (data: BinaryLike, secret: KeyLike, signature: string) =>\n createHmac('sha512', secret).update(data).digest('base64url') === signature\n },\n\n // RSA (DER-encoded signatures, base64url)\n RS256: {\n sign: (data: BinaryLike, secret: KeyLike) =>\n createSign('RSA-SHA256').update(data).end().sign(secret).toString('base64url'),\n verify: (data: BinaryLike, secret: KeyLike, signature: string) =>\n createVerify('RSA-SHA256')\n .update(data)\n .end()\n .verify(secret, Buffer.from(signature, 'base64url'))\n },\n RS384: {\n sign: (data: BinaryLike, secret: KeyLike) =>\n createSign('RSA-SHA384').update(data).end().sign(secret).toString('base64url'),\n verify: (data: BinaryLike, secret: KeyLike, signature: string) =>\n createVerify('RSA-SHA384')\n .update(data)\n .end()\n .verify(secret, Buffer.from(signature, 'base64url'))\n },\n RS512: {\n sign: (data: BinaryLike, secret: KeyLike) =>\n createSign('RSA-SHA512').update(data).end().sign(secret).toString('base64url'),\n verify: (data: BinaryLike, secret: KeyLike, signature: string) =>\n createVerify('RSA-SHA512')\n .update(data)\n .end()\n .verify(secret, Buffer.from(signature, 'base64url'))\n },\n\n // ECDSA (DER-encoded by default — no dsaEncoding!)\n ES256: {\n sign: (data: BinaryLike, secret: KeyLike) =>\n createSign('SHA256').update(data).end().sign(secret).toString('base64url'),\n verify: (data: BinaryLike, secret: KeyLike, signature: string) =>\n createVerify('SHA256')\n .update(data)\n .end()\n .verify(secret, Buffer.from(signature, 'base64url'))\n },\n ES384: {\n sign: (data: BinaryLike, secret: KeyLike) =>\n createSign('SHA384').update(data).end().sign(secret).toString('base64url'),\n verify: (data: BinaryLike, secret: KeyLike, signature: string) =>\n createVerify('SHA384')\n .update(data)\n .end()\n .verify(secret, Buffer.from(signature, 'base64url'))\n },\n ES512: {\n sign: (data: BinaryLike, secret: KeyLike) =>\n createSign('SHA512').update(data).end().sign(secret).toString('base64url'),\n verify: (data: BinaryLike, secret: KeyLike, signature: string) =>\n createVerify('SHA512')\n .update(data)\n .end()\n .verify(secret, Buffer.from(signature, 'base64url'))\n }\n} as const;\n\nexport type SupportedAlgorithm = keyof typeof SignatureAlgorithm;\n\nexport const SupportedAlgorithms = Object.keys(SignatureAlgorithm) as Array<SupportedAlgorithm>;\n\n/**\n * Decode a JWT string into its parts (without verification)\n */\nexport const decode = (token: string): JWT => {\n const parts = token.split('.');\n if (parts.length !== 3) {\n throw new Error('Invalid JWT: must contain exactly 3 parts separated by \".\"');\n }\n\n const [headerPart, payloadPart, signature] = parts;\n\n if (!headerPart || !payloadPart || !signature) {\n throw new Error('Invalid JWT: empty part detected');\n }\n\n try {\n const header = JSON.parse(base64Url.decode(headerPart)) as JWTHeader;\n const payload = JSON.parse(base64Url.decode(payloadPart)) as JWTPayload;\n return { header, payload, signature };\n } catch (err) {\n throw new Error(`Invalid JWT: malformed header or payload (${(err as Error).message})`);\n }\n};\n\n/**\n * Sign a JWT\n */\nexport const sign = (\n payload: JWTPayload,\n secret: KeyLike,\n options: {\n alg?: SupportedAlgorithm;\n kid?: string;\n typ?: string;\n } = {}\n): string => {\n const alg = options.alg ?? 'HS256';\n const typ = options.typ ?? 'JWT';\n\n if (!(alg in SignatureAlgorithm)) {\n throw new Error(`Unsupported algorithm: ${alg}`);\n }\n\n const header: JWTHeader = { alg, typ };\n if (options.kid) header.kid = options.kid;\n\n const headerEncoded = base64Url.encode(JSON.stringify(header));\n const payloadEncoded = base64Url.encode(JSON.stringify(payload));\n\n const signingInput = `${headerEncoded}.${payloadEncoded}`;\n const signature = SignatureAlgorithm[alg].sign(signingInput, secret);\n\n return `${headerEncoded}.${payloadEncoded}.${signature}`;\n};\n\n/**\n * Verify and validate a JWT\n */\nexport const verify = (\n token: string,\n secret: KeyLike,\n options: {\n ignoreExpiration?: boolean;\n clockSkew?: number; // in seconds, default 0\n } = {}\n):\n | { valid: true; header: JWTHeader; payload: JWTPayload; signature: string }\n | { valid: false; error: { reason: string; code: string } } => {\n let decoded: JWT;\n try {\n decoded = decode(token);\n } catch (err) {\n return {\n valid: false,\n error: {\n reason: (err as Error).message,\n code: 'INVALID_TOKEN'\n }\n };\n }\n\n const { header, payload, signature } = decoded;\n\n // Validate algorithm\n const alg = header.alg as SupportedAlgorithm;\n if (!(alg in SignatureAlgorithm)) {\n return {\n valid: false,\n error: {\n reason: `Unsupported or unknown algorithm: ${header.alg}`,\n code: 'INVALID_ALGORITHM'\n }\n };\n }\n\n // Optional: validate 'typ' header\n if (header.typ && header.typ !== 'JWT') {\n return {\n valid: false,\n error: {\n reason: `Invalid token type: expected 'JWT', got '${header.typ}'`,\n code: 'INVALID_TYPE'\n }\n };\n }\n\n // Verify signature\n const signingInput = `${base64Url.encode(JSON.stringify(header))}.${base64Url.encode(JSON.stringify(payload))}`;\n const isValidSignature = SignatureAlgorithm[alg].verify(signingInput, secret, signature);\n\n if (!isValidSignature) {\n return {\n valid: false,\n error: {\n reason: \"Signature verification failed\",\n code: 'INVALID_SIGNATURE'\n }\n };\n }\n\n // Time validation\n const now = Math.floor(Date.now() / 1000);\n const skew = options.clockSkew ?? 0;\n\n if (!options.ignoreExpiration) {\n if (payload.exp !== undefined && now > payload.exp + skew) {\n return {\n valid: false,\n error: {\n reason: 'Token expired',\n code: 'TOKEN_EXPIRED'\n }\n };\n }\n }\n\n if (payload.nbf !== undefined && now + skew < payload.nbf) {\n return {\n valid: false,\n error: {\n reason: 'Token not yet valid',\n code: 'TOKEN_NOT_ACTIVE'\n }\n };\n }\n\n if (payload.iat !== undefined && now + skew < payload.iat) {\n return {\n valid: false,\n error: {\n reason: 'Token issued in the future',\n code: 'TOKEN_FUTURE_ISSUED'\n }\n };\n }\n\n return { valid: true, header, payload, signature };\n};\n\n// Optional: namespace export (not default)\nexport const JWT = {\n sign,\n verify,\n decode,\n algorithms: SignatureAlgorithm\n};\n"],"names":["base64Url","input","SignatureAlgorithm","data","secret","createHmac","signature","createSign","createVerify","SupportedAlgorithms","decode","token","parts","headerPart","payloadPart","header","payload","err","sign","options","alg","typ","headerEncoded","payloadEncoded","signingInput","verify","decoded","now","skew","JWT"],"mappings":";AASO,MAAMA,IAAY;AAAA,EACrB,QAAQ,CAACC,MACL,OAAO,KAAKA,CAAK,EAAE,SAAS,WAAW;AAAA,EAE3C,QAAQ,CAACA,MAEE,OAAO,KAAKA,GAAO,WAAW,EAAE,SAAA;AAE/C,GAuDaC,IAAqB;AAAA;AAAA,EAE9B,OAAO;AAAA,IACH,MAAM,CAACC,GAAkBC,MACrBC,EAAW,UAAUD,CAAM,EAAE,OAAOD,CAAI,EAAE,OAAO,WAAW;AAAA,IAChE,QAAQ,CAACA,GAAkBC,GAAiBE,MACxCD,EAAW,UAAUD,CAAM,EAAE,OAAOD,CAAI,EAAE,OAAO,WAAW,MAAMG;AAAA,EAAA;AAAA,EAE1E,OAAO;AAAA,IACH,MAAM,CAACH,GAAkBC,MACrBC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f,MAAAX;AAAA,EACA,QAAAO;AAAA,EACA,QAAAf;AAAA,EACA,YAAYR;AAChB;"}
|
package/package.json
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@sourceregistry/node-jwt",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "A lightweight, zero-dependency TypeScript library for creating, verifying and decoding JSON Web Tokens (JWT).",
|
|
5
|
+
"main": "./dist/index.cjs.js",
|
|
6
|
+
"module": "./dist/index.es.js",
|
|
7
|
+
"types": "./dist/index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./dist/index.d.ts",
|
|
11
|
+
"import": "./dist/index.es.js",
|
|
12
|
+
"require": "./dist/index.cjs.js"
|
|
13
|
+
}
|
|
14
|
+
},
|
|
15
|
+
"files": [
|
|
16
|
+
"dist"
|
|
17
|
+
],
|
|
18
|
+
"scripts": {
|
|
19
|
+
"build": "tsc && vite build",
|
|
20
|
+
"test": "vitest",
|
|
21
|
+
"test:ui": "vitest --ui",
|
|
22
|
+
"test:coverage": "vitest run --coverage",
|
|
23
|
+
"lint": "tsc --noEmit"
|
|
24
|
+
},
|
|
25
|
+
"repository": {
|
|
26
|
+
"type": "git",
|
|
27
|
+
"url": "git+https://github.com/SourceRegistry/node-jwt.git"
|
|
28
|
+
},
|
|
29
|
+
"keywords": [
|
|
30
|
+
"jwt",
|
|
31
|
+
"json web token",
|
|
32
|
+
"authentication",
|
|
33
|
+
"security",
|
|
34
|
+
"typescript",
|
|
35
|
+
"zero-dependency"
|
|
36
|
+
],
|
|
37
|
+
"author": "A.P.A. Slaa (a.p.a.slaa@projectsource.nl)",
|
|
38
|
+
"license": "Apache-2.0",
|
|
39
|
+
"type": "module",
|
|
40
|
+
"bugs": {
|
|
41
|
+
"url": "https://github.com/SourceRegistry/node-jwt/issues"
|
|
42
|
+
},
|
|
43
|
+
"homepage": "https://github.com/SourceRegistry/node-jwt#readme",
|
|
44
|
+
"publishConfig": {
|
|
45
|
+
"access": "public"
|
|
46
|
+
},
|
|
47
|
+
"engines": {
|
|
48
|
+
"node": ">=16.0.0"
|
|
49
|
+
},
|
|
50
|
+
"devDependencies": {
|
|
51
|
+
"@types/node": "^24.3.0",
|
|
52
|
+
"@vitest/coverage-v8": "^3.2.4",
|
|
53
|
+
"@vitest/ui": "^3.2.4",
|
|
54
|
+
"typescript": "^5.9.3",
|
|
55
|
+
"vite": "^7.1.3",
|
|
56
|
+
"vite-plugin-dts": "^4.5.4",
|
|
57
|
+
"vitest": "^3.2.4",
|
|
58
|
+
"@semantic-release/commit-analyzer": "^13.0.1",
|
|
59
|
+
"@semantic-release/release-notes-generator": "^14.0.3",
|
|
60
|
+
"@semantic-release/changelog": "^6.0.3",
|
|
61
|
+
"@semantic-release/npm": "^12.0.2",
|
|
62
|
+
"@semantic-release/git": "^10.0.1"
|
|
63
|
+
},
|
|
64
|
+
"release": {
|
|
65
|
+
"branches": [
|
|
66
|
+
"main"
|
|
67
|
+
],
|
|
68
|
+
"plugins": [
|
|
69
|
+
"@semantic-release/commit-analyzer",
|
|
70
|
+
"@semantic-release/release-notes-generator",
|
|
71
|
+
"@semantic-release/changelog",
|
|
72
|
+
"@semantic-release/npm",
|
|
73
|
+
[
|
|
74
|
+
"@semantic-release/git",
|
|
75
|
+
{
|
|
76
|
+
"assets": [
|
|
77
|
+
"package.json",
|
|
78
|
+
"CHANGELOG.md"
|
|
79
|
+
],
|
|
80
|
+
"message": "node-jwt(release): 🚀 v${nextRelease.version}\n\n${nextRelease.notes}"
|
|
81
|
+
}
|
|
82
|
+
]
|
|
83
|
+
]
|
|
84
|
+
}
|
|
85
|
+
}
|