sealtok 0.0.0-stage → 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/README.md +546 -2
- package/dist/index.d.mts +645 -0
- package/dist/index.d.ts +645 -0
- package/dist/index.js +80 -0
- package/dist/index.mjs +80 -0
- package/package.json +84 -4
package/README.md
CHANGED
|
@@ -1,3 +1,547 @@
|
|
|
1
|
-
|
|
1
|
+
<p align="center">
|
|
2
|
+
<img src="assets/wordmark.svg" width="220" alt="sigil">
|
|
3
|
+
</p>
|
|
2
4
|
|
|
3
|
-
|
|
5
|
+
<p align="center">
|
|
6
|
+
<b>Fast, minimal, post-quantum ready tokens for Node.js.</b><br>
|
|
7
|
+
Encrypted or signed. Zero runtime dependencies. A modern JWT alternative.
|
|
8
|
+
</p>
|
|
9
|
+
|
|
10
|
+
<p align="center">
|
|
11
|
+
<a href="https://onurege3467.github.io/webToken/">Website & live demo</a> ·
|
|
12
|
+
<a href="https://github.com/onurege3467/webToken/wiki">Wiki</a> ·
|
|
13
|
+
<a href="#api-reference">API reference</a>
|
|
14
|
+
</p>
|
|
15
|
+
|
|
16
|
+
---
|
|
17
|
+
|
|
18
|
+
```bash
|
|
19
|
+
npm install sealtok
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
The npm package is called `sealtok`; the library and its API are named sigil.
|
|
23
|
+
|
|
24
|
+
```ts
|
|
25
|
+
import { sign, verify, keys } from 'sealtok'
|
|
26
|
+
|
|
27
|
+
const key = keys.secret(process.env.SIGIL_SECRET!) // a string of at least 32 characters
|
|
28
|
+
|
|
29
|
+
const token = await sign({ userId: 42 }, key, { expiresIn: '15m' })
|
|
30
|
+
const { userId } = await verify(token, key)
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
For most apps, that is all you need.
|
|
34
|
+
|
|
35
|
+
## Contents
|
|
36
|
+
|
|
37
|
+
- [Why sigil](#why-sigil)
|
|
38
|
+
- [Choosing a key type](#choosing-a-key-type)
|
|
39
|
+
- [Keys](#keys)
|
|
40
|
+
- [Signing](#signing)
|
|
41
|
+
- [Verifying](#verifying)
|
|
42
|
+
- [Inspecting](#inspecting)
|
|
43
|
+
- [Errors](#errors)
|
|
44
|
+
- [Revocation](#revocation)
|
|
45
|
+
- [Token format](#token-format)
|
|
46
|
+
- [Security model](#security-model)
|
|
47
|
+
- [Performance](#performance)
|
|
48
|
+
- [Recipes](#recipes)
|
|
49
|
+
- [API reference](#api-reference)
|
|
50
|
+
- [Migrating](#migrating)
|
|
51
|
+
- [FAQ](#faq)
|
|
52
|
+
- [Development](#development)
|
|
53
|
+
|
|
54
|
+
## Why sigil
|
|
55
|
+
|
|
56
|
+
- **Encrypted by default.** Payloads are sealed with AES-256-GCM, not just base64-encoded. Without the key, nobody can read them.
|
|
57
|
+
- **No algorithm confusion.** The key you pass decides the algorithm. There is no `alg` field for an attacker to swap, and no `none`.
|
|
58
|
+
- **Post-quantum when you need it.** One argument switches signing to ML-DSA-65 (NIST FIPS 204, listed in NSA CNSA 2.0).
|
|
59
|
+
- **Fast.** Native `node:crypto` and a compact binary format give about 94k verifications/s for encrypted tokens on one core.
|
|
60
|
+
- **Small.** No runtime dependencies. The Redis and SQLite drivers are optional peer dependencies.
|
|
61
|
+
- **Revocation built in.** Memory, Redis and SQLite stores can revoke by token, user, session or a composite key.
|
|
62
|
+
|
|
63
|
+
## Choosing a key type
|
|
64
|
+
|
|
65
|
+
| | `keys.secret()` | `keys.pair()` | `keys.pair('pq')` |
|
|
66
|
+
|---------------------|-----------------|---------------|-------------------|
|
|
67
|
+
| Algorithm | AES-256-GCM (`v2.local`) | Ed25519 (`v1.public`) | ML-DSA-65 (`v3.public`) |
|
|
68
|
+
| Who can create tokens | anyone with the key | private-key holder | private-key holder |
|
|
69
|
+
| Who can verify | anyone with the key | anyone with the public key | anyone with the public key |
|
|
70
|
+
| Payload hidden | ✅ encrypted | ❌ readable by anyone | ❌ readable by anyone |
|
|
71
|
+
| Quantum-safe | ✅ | ❌ | ✅ |
|
|
72
|
+
| Token size (sample payload) | ~245 chars | ~295 chars | ~4.6 KB |
|
|
73
|
+
| Verify ops/s (Node 26, 1 core) | ~94k | ~27k | ~13k |
|
|
74
|
+
| Node.js | ≥ 20 | ≥ 20 | ≥ 24.7 |
|
|
75
|
+
|
|
76
|
+
How to pick:
|
|
77
|
+
|
|
78
|
+
- **One service issues and checks its own tokens** (sessions, API keys, password-reset links): use `secret`.
|
|
79
|
+
- **Other services must verify tokens but must not be able to create them** (microservices, a public API gateway): use `pair()`.
|
|
80
|
+
- **Signatures must stay unforgeable against future quantum computers** (long-lived tokens, regulated environments): use `pair('pq')`.
|
|
81
|
+
|
|
82
|
+
## Keys
|
|
83
|
+
|
|
84
|
+
Keys are frozen objects whose type is fixed when they are created. A `PublicKey` cannot be passed to `sign`. A `PrivateKey` cannot be passed to `verify`. A `SecretKey` cannot verify a signed token. These mistakes are caught by the TypeScript types and checked again at runtime.
|
|
85
|
+
|
|
86
|
+
### `keys.secret(from?)`
|
|
87
|
+
|
|
88
|
+
```ts
|
|
89
|
+
keys.secret() // random 32 bytes
|
|
90
|
+
keys.secret(process.env.SIGIL_SECRET!) // string of at least 32 characters, stretched with HKDF-SHA256
|
|
91
|
+
keys.secret(crypto.randomBytes(32)) // raw Buffer, exactly 32 bytes
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
| Input | Result |
|
|
95
|
+
|---|---|
|
|
96
|
+
| none | 32 random bytes from `crypto.randomBytes` |
|
|
97
|
+
| `string` of 32+ characters | `HKDF-SHA256(ikm = string, salt = empty, info = "sigil/v1/secret", 32 bytes)` |
|
|
98
|
+
| `string` of fewer than 32 characters | throws `TypeError` |
|
|
99
|
+
| `Buffer` of exactly 32 bytes | copied as is |
|
|
100
|
+
| `Buffer` of any other length | throws `TypeError` |
|
|
101
|
+
|
|
102
|
+
Deriving a key from the same string always gives the same key, so every instance that reads the same environment variable can verify every other instance's tokens.
|
|
103
|
+
|
|
104
|
+
### `keys.pair(kind?)`
|
|
105
|
+
|
|
106
|
+
```ts
|
|
107
|
+
const { privateKey, publicKey } = await keys.pair() // Ed25519
|
|
108
|
+
const { privateKey, publicKey } = await keys.pair('pq') // ML-DSA-65, Node ≥ 24.7
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
### `keys.publicOf(privateKey)`
|
|
112
|
+
|
|
113
|
+
Recomputes the public key from a private key. You only need to store the private key.
|
|
114
|
+
|
|
115
|
+
### `keys.export(key)` / `keys.import(string)`
|
|
116
|
+
|
|
117
|
+
```ts
|
|
118
|
+
const str = keys.export(privateKey) // "sgl_ed_sk_…"
|
|
119
|
+
const key = keys.import(str)
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
| Prefix | Key | Bytes |
|
|
123
|
+
|---|---|---|
|
|
124
|
+
| `sgl_sk_` | secret | 32 |
|
|
125
|
+
| `sgl_ed_sk_` | Ed25519 private | 32 |
|
|
126
|
+
| `sgl_ed_pk_` | Ed25519 public | 32 |
|
|
127
|
+
| `sgl_pq_sk_` | ML-DSA-65 private (seed) | 32 |
|
|
128
|
+
| `sgl_pq_pk_` | ML-DSA-65 public | 1952 |
|
|
129
|
+
|
|
130
|
+
The body after the prefix is base64url. `import` checks the prefix and the length and throws `TypeError('Unknown key format')` or `TypeError('Invalid … key length')` when they do not match. The prefix makes leaked keys easy to recognize in logs and in secret scanners.
|
|
131
|
+
|
|
132
|
+
Store exported keys in a secret manager or an environment variable. Never commit them.
|
|
133
|
+
|
|
134
|
+
## Signing
|
|
135
|
+
|
|
136
|
+
```ts
|
|
137
|
+
const token = await sign(payload, key, options?)
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
`payload` is any JSON-serializable object. It is stored in the token as `data` and returned by `verify`. `key` is a `SecretKey` or a `PrivateKey`.
|
|
141
|
+
|
|
142
|
+
| Option | Type | Default | Effect |
|
|
143
|
+
|---|---|---|---|
|
|
144
|
+
| `expiresIn` | `string \| number` | `'1h'` | Sets `exp`. A string with a unit (`'30s'`, `'15m'`, `'12h'`, `'7d'`, `'2w'`, `'1y'`) or a number of **milliseconds**. |
|
|
145
|
+
| `notBefore` | `string \| number` | none | Sets `nbf` relative to now. The token is rejected until then. |
|
|
146
|
+
| `issuer` | `string` | none | Sets `iss`. |
|
|
147
|
+
| `audience` | `string \| string[]` | none | Sets `aud`. |
|
|
148
|
+
| `subject` | `string` | none | Sets `sub`. |
|
|
149
|
+
| `jti` | `string \| () => string` | none | Sets the token ID. **Required if you want to revoke individual tokens.** |
|
|
150
|
+
| `format` | `'binary' \| 'protobuf'` | `'binary'` | How claims are encoded. `binary` is the default and slightly smaller, but limits each field (including the JSON-encoded payload) to 65,535 bytes; larger payloads make `sign` throw a `RangeError`. Use `'protobuf'` for bigger payloads. |
|
|
151
|
+
|
|
152
|
+
`iat` (issued at) is always set. Time units are case-insensitive. A number is always milliseconds: `expiresIn: 60` means 60 ms, not 60 seconds.
|
|
153
|
+
|
|
154
|
+
```ts
|
|
155
|
+
await sign({ role: 'admin' }, key, {
|
|
156
|
+
expiresIn: '15m',
|
|
157
|
+
issuer: 'auth.example.com',
|
|
158
|
+
audience: ['api', 'admin'],
|
|
159
|
+
subject: 'user-42',
|
|
160
|
+
jti: () => crypto.randomUUID(),
|
|
161
|
+
})
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
## Verifying
|
|
165
|
+
|
|
166
|
+
```ts
|
|
167
|
+
const data = await verify(token, key, options?)
|
|
168
|
+
```
|
|
169
|
+
|
|
170
|
+
`key` is a `SecretKey` or a `PublicKey`. Verification runs these steps in order and stops at the first failure:
|
|
171
|
+
|
|
172
|
+
1. **Length**: reject a token longer than `maxTokenLength` before decoding anything.
|
|
173
|
+
2. **Algorithm**: read the 3-byte header and reject the token if its algorithm does not match the key type.
|
|
174
|
+
3. **Cryptography**: decrypt and authenticate (AES-GCM, with the header as AAD), or check the signature over header and body.
|
|
175
|
+
4. **Decode** the claims. The header inside the body must match the outer header.
|
|
176
|
+
5. **Claims**: `iss`, `aud`, `exp`, `nbf`, `maxAge`.
|
|
177
|
+
6. **Revocation**, if a `revocationStore` is given.
|
|
178
|
+
|
|
179
|
+
| Option | Type | Default | Effect |
|
|
180
|
+
|---|---|---|---|
|
|
181
|
+
| `issuer` | `string \| string[]` | none | `iss` must be one of these. |
|
|
182
|
+
| `audience` | `string \| string[]` | none | At least one `aud` value must match. |
|
|
183
|
+
| `clockTolerance` | `number` (seconds) | `0` | Grace period for `exp` and `nbf` to absorb clock skew between servers. |
|
|
184
|
+
| `maxAge` | `string \| number` | none | Reject tokens whose `iat` is older than this, even if `exp` is later. |
|
|
185
|
+
| `requireExpiration` | `boolean` | `true` | Reject tokens without `exp`. Tokens from `sign` always have one. |
|
|
186
|
+
| `maxTokenLength` | `number` (chars) | `262144` | Reject longer tokens before decoding. |
|
|
187
|
+
| `complete` | `boolean` | `false` | Return `{ header, payload, signature, raw }` instead of only the data. |
|
|
188
|
+
| `revocationStore` | store | none | Check revocation after every other check passes. |
|
|
189
|
+
| `skipRevocationCheck` | `boolean` | `false` | Skip the store for this call. |
|
|
190
|
+
| `identifierConfig` | `IdentifierConfig` | store's config | Override how revocation identifiers are read for this call. |
|
|
191
|
+
| `onRevoked` | `(token) => void` | none | Called just before `TokenRevokedError` is thrown. |
|
|
192
|
+
|
|
193
|
+
```ts
|
|
194
|
+
const full = await verify(token, key, { complete: true })
|
|
195
|
+
full.header // { version: 'v2', purpose: 'local', format: 'binary' }
|
|
196
|
+
full.payload // { iss, sub, aud, exp, nbf, iat, jti, data }
|
|
197
|
+
```
|
|
198
|
+
|
|
199
|
+
Encrypted tokens sealed with the legacy `v1.local` label are also accepted by a secret key; the encryption is identical.
|
|
200
|
+
|
|
201
|
+
## Inspecting
|
|
202
|
+
|
|
203
|
+
```ts
|
|
204
|
+
const { header, payload } = inspect(token)
|
|
205
|
+
```
|
|
206
|
+
|
|
207
|
+
`inspect` reads a **signed** token's claims without checking the signature. Use it for logging, debugging, or to pick a key by `iss` before you verify. **Never base a decision on what it returns.** Anyone can create a token that `inspect` accepts.
|
|
208
|
+
|
|
209
|
+
Encrypted tokens cannot be inspected; `inspect` throws `InvalidTokenError`. A malformed token also throws `InvalidTokenError` after work that grows linearly with its size.
|
|
210
|
+
|
|
211
|
+
## Errors
|
|
212
|
+
|
|
213
|
+
Every error extends `SigilError`, which has a stable `code`.
|
|
214
|
+
|
|
215
|
+
| Class | `code` | When | Extra fields |
|
|
216
|
+
|---|---|---|---|
|
|
217
|
+
| `InvalidTokenError` | `INVALID_TOKEN` | Malformed token, wrong secret, tampered ciphertext, header mismatch, wrong `iss`/`aud`, missing `exp` | |
|
|
218
|
+
| `InvalidSignatureError` | `INVALID_SIGNATURE` | The signature does not match the public key | |
|
|
219
|
+
| `AlgorithmMismatchError` | `ALGORITHM_MISMATCH` | The token's algorithm does not belong to the key type | |
|
|
220
|
+
| `TokenExpiredError` | `TOKEN_EXPIRED` | `exp` + `clockTolerance` has passed, or `maxAge` has been exceeded | `expiredAt: Date` |
|
|
221
|
+
| `TokenNotBeforeError` | `TOKEN_NOT_BEFORE` | `nbf` − `clockTolerance` is still in the future | `notBefore: Date` |
|
|
222
|
+
| `TokenRevokedError` | `TOKEN_REVOKED` | The revocation store reports the token as revoked | `jti`, `revokedAt`, `reason` |
|
|
223
|
+
|
|
224
|
+
`keys.*`, `sign` and `verify` throw a plain `TypeError` when they are called with a key of the wrong type or with invalid input such as a short secret.
|
|
225
|
+
|
|
226
|
+
```ts
|
|
227
|
+
import { SigilError, TokenExpiredError } from 'sealtok'
|
|
228
|
+
|
|
229
|
+
try {
|
|
230
|
+
const data = await verify(token, key)
|
|
231
|
+
} catch (err) {
|
|
232
|
+
if (err instanceof TokenExpiredError) return res.status(401).json({ error: 'expired', at: err.expiredAt })
|
|
233
|
+
if (err instanceof SigilError) return res.status(401).json({ error: err.code })
|
|
234
|
+
throw err // a bug, not a bad token
|
|
235
|
+
}
|
|
236
|
+
```
|
|
237
|
+
|
|
238
|
+
To avoid giving attackers hints, reply with one generic 401 and log `err.code` on the server.
|
|
239
|
+
|
|
240
|
+
## Revocation
|
|
241
|
+
|
|
242
|
+
A token is valid until it expires. Revocation lets you reject one earlier, for example on logout, after a password change, or when a device is stolen.
|
|
243
|
+
|
|
244
|
+
```ts
|
|
245
|
+
import { MemoryStore, RevocationManager } from 'sealtok'
|
|
246
|
+
|
|
247
|
+
const store = new MemoryStore()
|
|
248
|
+
const revocation = new RevocationManager({ store })
|
|
249
|
+
|
|
250
|
+
// Issue tokens with a jti so they can be revoked one by one
|
|
251
|
+
const token = await sign({ userId: 'u1', sessionId: 's1' }, key, { jti: () => crypto.randomUUID() })
|
|
252
|
+
|
|
253
|
+
// Logout: revoke a token you have already verified
|
|
254
|
+
await revocation.revokeToken(await verify(token, key, { complete: true }), 'logout')
|
|
255
|
+
|
|
256
|
+
// Verification now fails
|
|
257
|
+
await verify(token, key, { revocationStore: store }) // throws TokenRevokedError
|
|
258
|
+
```
|
|
259
|
+
|
|
260
|
+
### What can be revoked
|
|
261
|
+
|
|
262
|
+
| Method | Revokes | Needs |
|
|
263
|
+
|---|---|---|
|
|
264
|
+
| `revokeToken(token, reason?)` | that one token | a `jti` claim |
|
|
265
|
+
| `revokeTokenFlexible(token, identifierConfig?, reason?)` | token, user, session or composite key, whichever the token yields | any identifier |
|
|
266
|
+
| `revokeUser(userId, reason?)` | every token of that user, including ones issued later | |
|
|
267
|
+
| `revokeSession(sessionId, reason?)` | every token of that session | |
|
|
268
|
+
|
|
269
|
+
Other methods: `isRevoked(jti)`, `isUserRevoked(userId)`, `isSessionRevoked(sessionId)`, `getRevokedTokensForUser(userId)`, `checkRevoked(decodedToken)`, `cleanup()`, `startAutoCleanup(ms?)`, `stopAutoCleanup()`, `disconnect()`, `getStore()`, `extractIdentifiers(payload, config?)`. `createRevocationManager(store, options?)` is a shortcut for the constructor.
|
|
270
|
+
|
|
271
|
+
> **Revoke tokens you have verified.** Passed a string, `revokeToken` and `revokeTokenFlexible` decode the token without checking its signature. If a client can send any string to your logout endpoint, it can choose which jti, user or session is revoked. Call `verify(token, key, { complete: true })` first and pass the result.
|
|
272
|
+
|
|
273
|
+
### Stores
|
|
274
|
+
|
|
275
|
+
| Store | Persistence | Shared across instances | Peer dependency |
|
|
276
|
+
|---|---|---|---|
|
|
277
|
+
| `MemoryStore` | process memory | no | none |
|
|
278
|
+
| `SQLiteStore` | a file, or `:memory:` | instances on one host | `better-sqlite3` ≥ 11 |
|
|
279
|
+
| `RedisStore` | Redis, with TTLs | yes | `ioredis` ≥ 5 |
|
|
280
|
+
|
|
281
|
+
```ts
|
|
282
|
+
new MemoryStore()
|
|
283
|
+
|
|
284
|
+
new SQLiteStore({ database: './revocations.db' }) // or { memory: true }, or { connection: existingDb }
|
|
285
|
+
|
|
286
|
+
new RedisStore({ url: 'redis://localhost:6379' }) // or { host, port, password, db }, or { client: existingIoredis }
|
|
287
|
+
```
|
|
288
|
+
|
|
289
|
+
Options shared by every store:
|
|
290
|
+
|
|
291
|
+
| Option | Default | Effect |
|
|
292
|
+
|---|---|---|
|
|
293
|
+
| `expiryGraceSeconds` | `300` | A revocation is kept this long after the token's `exp`. **Set it to at least the largest `clockTolerance` you pass to `verify`**, or a revoked token is accepted again for a short time after it expires. |
|
|
294
|
+
| `sessionRevocationTtl` | `2592000` (30 days) | How long `RedisStore.revokeSession` lasts. Make it at least your longest token lifetime. |
|
|
295
|
+
| `autoCleanupInterval` | `60000` ms | How often expired entries are pruned. `0` turns it off. |
|
|
296
|
+
| `keyPrefix` | `'webtoken:revoke:'` | Redis key prefix. |
|
|
297
|
+
| `identifierConfig` | default chain | How identifiers are read from tokens (see below). |
|
|
298
|
+
| `debug` | `false` | Log store operations to the console. |
|
|
299
|
+
|
|
300
|
+
Call `await store.disconnect()` on shutdown so SQLite and Redis connections and cleanup timers do not keep the process alive.
|
|
301
|
+
|
|
302
|
+
### Where identifiers come from
|
|
303
|
+
|
|
304
|
+
When a token is verified, the store looks for identifiers in its claims. Registered claims (`sub`, `jti`) are read first, then the `data` you signed.
|
|
305
|
+
|
|
306
|
+
- **User ID**: `userIdPath` if set, otherwise the first match in `sub`, `userId`, `uid`, `user_id`, `accountId`, `memberId`, `id`, `data.userId`, `data.uid`, `data.user_id`, `data.accountId`, `data.id`, `user?.id`, `account?.userId`. Override this list with `fallbackChain`.
|
|
307
|
+
- **Session ID**: `sessionIdPath` if set, otherwise `sessionId`, `session_id`, `sid`, `session`, `data.sessionId`, `data.sid`.
|
|
308
|
+
- **Token ID**: the `jti` claim.
|
|
309
|
+
|
|
310
|
+
```ts
|
|
311
|
+
new MemoryStore({
|
|
312
|
+
identifierConfig: {
|
|
313
|
+
userIdPath: 'user.id', // dot path into the payload
|
|
314
|
+
sessionIdPath: 'auth.session',
|
|
315
|
+
compositeKey: { fields: ['tenantId', 'userId'], separator: ':' },
|
|
316
|
+
fallbackChain: ['sub', 'data.accountId'],
|
|
317
|
+
extractIdentifiers: (payload) => ({ userId: String((payload as any).data?.uid) }), // full control
|
|
318
|
+
},
|
|
319
|
+
})
|
|
320
|
+
```
|
|
321
|
+
|
|
322
|
+
A composite key lets you revoke a combination, for example one user inside one tenant. Field values are joined with `separator` (default `':'`), so make sure the values cannot contain it.
|
|
323
|
+
|
|
324
|
+
See [`examples/revocation.mts`](examples/revocation.mts) for a runnable version.
|
|
325
|
+
|
|
326
|
+
## Token format
|
|
327
|
+
|
|
328
|
+
A token has two base64url parts joined by a dot:
|
|
329
|
+
|
|
330
|
+
```
|
|
331
|
+
encrypted: base64url(header) . base64url(iv ‖ ciphertext ‖ tag)
|
|
332
|
+
signed: base64url(header ‖ body) . base64url(signature)
|
|
333
|
+
```
|
|
334
|
+
|
|
335
|
+
The 3-byte header holds the version (`01`/`02`/`03`), the purpose (`01` local, `02` public) and the format (`01` binary, `02` protobuf). Encrypted tokens use it as AES-GCM additional authenticated data. Signed tokens include it in the signed bytes. Changing any header byte makes the token invalid.
|
|
336
|
+
|
|
337
|
+
The body is either a compact tag-length-value encoding (`binary`) or a small protobuf-style encoding (`protobuf`) of `iss`, `sub`, `aud`, `exp`, `nbf`, `iat`, `jti` and the JSON-encoded `data`. Both decoders check every length against the buffer and finish in time linear in the input.
|
|
338
|
+
|
|
339
|
+
The [wiki page on the token format](https://github.com/onurege3467/webToken/wiki/Token-Format) has the byte-level layout.
|
|
340
|
+
|
|
341
|
+
## Security model
|
|
342
|
+
|
|
343
|
+
What sigil guarantees:
|
|
344
|
+
|
|
345
|
+
- **Authenticity.** Nobody without the key can create a token that `verify` accepts or change one byte of an existing token.
|
|
346
|
+
- **Confidentiality** of encrypted tokens. Nobody without the secret can read their payload.
|
|
347
|
+
- **Algorithm binding.** The key type decides the algorithm. Algorithm-swap and `none` attacks do not apply.
|
|
348
|
+
- **No key material in tokens.** Keys never travel inside a token.
|
|
349
|
+
- **Bounded work on untrusted input.** Oversized tokens (> 256 KB by default) are rejected before decoding, and decoders never loop or recurse without bound.
|
|
350
|
+
- **Strict time claims.** Tokens without `exp` are rejected by default.
|
|
351
|
+
- **Key hygiene.** String secrets must be at least 32 characters and are stretched with HKDF-SHA256. Keys are frozen objects.
|
|
352
|
+
|
|
353
|
+
What it does not do:
|
|
354
|
+
|
|
355
|
+
- **Hide signed payloads.** Anyone holding a `v1.public` or `v3.public` token can read its claims. Use a secret key for private data.
|
|
356
|
+
- **Prevent replay** inside the validity window. Keep `expiresIn` short and use revocation where it matters.
|
|
357
|
+
- **Store keys safely for you.** Keep them in a secret manager, and rotate them by verifying with the old and new key during the switch.
|
|
358
|
+
- **Make plain `inspect()` output trustworthy.** It is unverified.
|
|
359
|
+
|
|
360
|
+
AES-256-GCM is considered quantum-resistant (Grover's algorithm only halves its effective strength). Ed25519 is not. Use `keys.pair('pq')` when signatures must be too.
|
|
361
|
+
|
|
362
|
+
The project went through a full security audit in December 2026. Every finding is fixed and has a regression test in [`tests/audit-regressions.test.ts`](tests/audit-regressions.test.ts). Report vulnerabilities privately through GitHub's security advisories for this repository.
|
|
363
|
+
|
|
364
|
+
## Performance
|
|
365
|
+
|
|
366
|
+
`npm run benchmark` on Node 26.4, one core, with a 5-field payload:
|
|
367
|
+
|
|
368
|
+
| Operation | ops/s |
|
|
369
|
+
|---|---:|
|
|
370
|
+
| `sign` secret (AES-256-GCM) | 88,626 |
|
|
371
|
+
| `verify` secret (AES-256-GCM) | 93,982 |
|
|
372
|
+
| `sign` Ed25519 | 62,035 |
|
|
373
|
+
| `verify` Ed25519 | 27,231 |
|
|
374
|
+
| `verify` Ed25519, protobuf format | 27,225 |
|
|
375
|
+
| `inspect` | 730,633 |
|
|
376
|
+
| `sign` ML-DSA-65 | 2,605 |
|
|
377
|
+
| `verify` ML-DSA-65 | 13,013 |
|
|
378
|
+
|
|
379
|
+
Every cryptographic primitive is native `node:crypto`. The cost of the token format itself is small compared with the cryptography.
|
|
380
|
+
|
|
381
|
+
## Recipes
|
|
382
|
+
|
|
383
|
+
### Express middleware
|
|
384
|
+
|
|
385
|
+
```ts
|
|
386
|
+
import { verify, keys, SigilError } from 'sealtok'
|
|
387
|
+
|
|
388
|
+
const key = keys.secret(process.env.SIGIL_SECRET!)
|
|
389
|
+
|
|
390
|
+
export async function auth(req, res, next) {
|
|
391
|
+
const token = req.headers.authorization?.replace(/^Bearer /, '')
|
|
392
|
+
if (!token) return res.sendStatus(401)
|
|
393
|
+
try {
|
|
394
|
+
req.user = await verify(token, key, { audience: 'api', clockTolerance: 5 })
|
|
395
|
+
next()
|
|
396
|
+
} catch (err) {
|
|
397
|
+
if (err instanceof SigilError) return res.sendStatus(401)
|
|
398
|
+
next(err)
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
```
|
|
402
|
+
|
|
403
|
+
### Access and refresh tokens
|
|
404
|
+
|
|
405
|
+
```ts
|
|
406
|
+
const access = await sign({ uid }, key, { expiresIn: '15m', audience: 'api' })
|
|
407
|
+
const refresh = await sign({ uid, sessionId }, key, { expiresIn: '30d', audience: 'refresh', jti: () => crypto.randomUUID() })
|
|
408
|
+
|
|
409
|
+
// Use different audiences so neither token is accepted in place of the other
|
|
410
|
+
await verify(refresh, key, { audience: 'refresh', revocationStore: store })
|
|
411
|
+
```
|
|
412
|
+
|
|
413
|
+
### Issuer and verifier on different services
|
|
414
|
+
|
|
415
|
+
```ts
|
|
416
|
+
// auth service: the only holder of the private key
|
|
417
|
+
const priv = keys.import(process.env.SIGIL_PRIVATE_KEY!)
|
|
418
|
+
const token = await sign({ uid }, priv, { issuer: 'auth' })
|
|
419
|
+
|
|
420
|
+
// any other service: holds only the public key
|
|
421
|
+
const pub = keys.import(process.env.SIGIL_PUBLIC_KEY!)
|
|
422
|
+
await verify(token, pub, { issuer: 'auth' })
|
|
423
|
+
```
|
|
424
|
+
|
|
425
|
+
### Key rotation
|
|
426
|
+
|
|
427
|
+
```ts
|
|
428
|
+
import { verify, keys, InvalidTokenError } from 'sealtok'
|
|
429
|
+
|
|
430
|
+
const current = keys.secret(process.env.SIGIL_SECRET!)
|
|
431
|
+
const previous = process.env.SIGIL_SECRET_OLD ? keys.secret(process.env.SIGIL_SECRET_OLD) : null
|
|
432
|
+
|
|
433
|
+
async function verifyAny(token: string) {
|
|
434
|
+
try { return await verify(token, current) }
|
|
435
|
+
catch (err) {
|
|
436
|
+
if (!previous || !(err instanceof InvalidTokenError)) throw err
|
|
437
|
+
return verify(token, previous)
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
```
|
|
441
|
+
|
|
442
|
+
Sign with the new key only. Remove the old key once the longest token lifetime has passed.
|
|
443
|
+
|
|
444
|
+
### Cookies
|
|
445
|
+
|
|
446
|
+
Encrypted and Ed25519 tokens fit easily in a cookie. Set `HttpOnly`, `Secure` and `SameSite`. ML-DSA tokens (~4.6 KB) can exceed the 4 KB cookie limit, so send them in the `Authorization` header.
|
|
447
|
+
|
|
448
|
+
## API reference
|
|
449
|
+
|
|
450
|
+
```ts
|
|
451
|
+
// Functions
|
|
452
|
+
sign<T>(payload: T, key: SecretKey | PrivateKey, options?: SignOptions): Promise<string>
|
|
453
|
+
verify<T>(token: string, key: SecretKey | PublicKey, options?: VerifyOptions): Promise<T>
|
|
454
|
+
verify<T>(token: string, key: SecretKey | PublicKey, options: VerifyOptions & { complete: true }): Promise<DecodedToken<T>>
|
|
455
|
+
inspect<T>(token: string): DecodedToken<T>
|
|
456
|
+
|
|
457
|
+
// Keys
|
|
458
|
+
keys.secret(from?: string | Buffer): SecretKey
|
|
459
|
+
keys.pair(kind?: 'ed25519' | 'pq'): Promise<{ privateKey: PrivateKey; publicKey: PublicKey }>
|
|
460
|
+
keys.publicOf(key: PrivateKey): PublicKey
|
|
461
|
+
keys.export(key: AnyKey): string
|
|
462
|
+
keys.import(str: string): AnyKey
|
|
463
|
+
|
|
464
|
+
// Revocation
|
|
465
|
+
new MemoryStore(config?) / new SQLiteStore(config?) / new RedisStore(config?)
|
|
466
|
+
new RevocationManager({ store, identifierConfig?, debug? })
|
|
467
|
+
createRevocationManager(store, options?)
|
|
468
|
+
|
|
469
|
+
// Errors
|
|
470
|
+
SigilError, InvalidTokenError, InvalidSignatureError, AlgorithmMismatchError,
|
|
471
|
+
TokenExpiredError, TokenNotBeforeError, TokenRevokedError
|
|
472
|
+
|
|
473
|
+
// Types
|
|
474
|
+
KeyKind, SecretKey, PrivateKey, PublicKey, SigningKey, VerifyingKey, AnyKey,
|
|
475
|
+
SignOptions, VerifyOptions, DecodedToken, TokenPayload, TokenHeader,
|
|
476
|
+
IdentifierConfig, CompositeKeyConfig, RevocationStore
|
|
477
|
+
|
|
478
|
+
// Low-level primitives
|
|
479
|
+
AES256GCM, Ed25519, MLDSA65
|
|
480
|
+
VERSION // '1.0.0'
|
|
481
|
+
```
|
|
482
|
+
|
|
483
|
+
The [wiki](https://github.com/onurege3467/webToken/wiki) documents each of these in full.
|
|
484
|
+
|
|
485
|
+
## Migrating
|
|
486
|
+
|
|
487
|
+
### From `webtoken`
|
|
488
|
+
|
|
489
|
+
`webtoken` has been withdrawn from npm and `sigil` replaces it. Reissue tokens after you switch: compatibility with tokens issued by `webtoken` is not guaranteed.
|
|
490
|
+
|
|
491
|
+
| `webtoken` | `sigil` |
|
|
492
|
+
|---|---|
|
|
493
|
+
| `createToken({ algorithm, secret, payload, expiresIn })` | `sign(payload, keys.secret(secret), { expiresIn })` |
|
|
494
|
+
| `createToken({ algorithm: 'v1.public', privateKey, … })` | `sign(payload, keys.import(…), …)` |
|
|
495
|
+
| `verifyToken(token, { secret })` | `verify(token, keys.secret(secret))` |
|
|
496
|
+
| `verifyToken(token, { publicKey })` | `verify(token, publicKey)` |
|
|
497
|
+
| `decodeToken(token)` | `inspect(token)` |
|
|
498
|
+
| `WebTokenError` | `SigilError` |
|
|
499
|
+
| `algorithms: [...]` option | removed; the key decides |
|
|
500
|
+
|
|
501
|
+
### From JWT (`jsonwebtoken`, `jose`)
|
|
502
|
+
|
|
503
|
+
| JWT | sigil |
|
|
504
|
+
|---|---|
|
|
505
|
+
| `jwt.sign(payload, secret, { expiresIn: '1h' })` (HS256) | `sign(payload, keys.secret(secret), { expiresIn: '1h' })`, which also encrypts |
|
|
506
|
+
| `jwt.sign(payload, privateKey, { algorithm: 'EdDSA' })` | `sign(payload, privateKey)` with `keys.pair()` |
|
|
507
|
+
| `jwt.verify(token, secret, { algorithms: ['HS256'] })` | `verify(token, key)`; no algorithms list needed |
|
|
508
|
+
| `jwt.decode(token)` | `inspect(token)` (signed tokens only) |
|
|
509
|
+
| `expiresIn: 3600` (seconds) | `expiresIn: '1h'`. **A number means milliseconds in sigil.** |
|
|
510
|
+
| `TokenExpiredError`, `JsonWebTokenError` | `TokenExpiredError`, `SigilError` |
|
|
511
|
+
|
|
512
|
+
Your claims move from the top level into `data`. `verify` returns `data` directly, so application code usually does not change.
|
|
513
|
+
|
|
514
|
+
## FAQ
|
|
515
|
+
|
|
516
|
+
**Is this a JWT library?** No. The format is not JWT and is not compatible with JWT tools. The design follows PASETO's idea of one algorithm per version, with a smaller binary encoding.
|
|
517
|
+
|
|
518
|
+
**Can a frontend read the token?** An encrypted token cannot be read without the secret, so a browser cannot read it. A signed token can be read by anyone, including a browser.
|
|
519
|
+
|
|
520
|
+
**Why is a number in `expiresIn` milliseconds?** For consistency with `setTimeout` and `Date`. Use strings such as `'15m'` to avoid mistakes.
|
|
521
|
+
|
|
522
|
+
**Does it work in browsers, Deno or Bun?** It targets Node.js and uses `node:crypto`. Bun and Deno's Node compatibility layer may work but are not tested.
|
|
523
|
+
|
|
524
|
+
**How large can a payload be?** With the default `binary` format, the JSON-encoded payload is limited to 65,535 bytes. With `format: 'protobuf'` the only limit is `maxTokenLength` on the verifying side (256 KB by default). Keep tokens small anyway: they travel with every request.
|
|
525
|
+
|
|
526
|
+
**Do I need `protobufjs`?** No. The protobuf format has its own small built-in codec. The peer dependency entry is left over and will be removed.
|
|
527
|
+
|
|
528
|
+
**What about Edge runtimes?** Not supported yet, because they lack `node:crypto`.
|
|
529
|
+
|
|
530
|
+
## Development
|
|
531
|
+
|
|
532
|
+
```bash
|
|
533
|
+
npm test # vitest
|
|
534
|
+
npx tsc --noEmit # type check
|
|
535
|
+
npm run benchmark # ops/s on this machine
|
|
536
|
+
npm run build # dist/ (ESM + CJS)
|
|
537
|
+
```
|
|
538
|
+
|
|
539
|
+
The repository has no CI, so run these before you merge.
|
|
540
|
+
|
|
541
|
+
## Requirements
|
|
542
|
+
|
|
543
|
+
Node.js ≥ 20 (≥ 24.7 for `keys.pair('pq')`). ESM and CommonJS are both supported.
|
|
544
|
+
|
|
545
|
+
## License
|
|
546
|
+
|
|
547
|
+
MIT
|