@sukujs/crypto 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Suku Authors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,340 @@
1
- # Temporary Holding Version
1
+ # @sukujs/crypto
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Zero-dependency crypto helpers on the Web Crypto API. Works on Node 22+, Bun and edge
4
+ runtimes, with or without the rest of Suku.
5
+
6
+ ```ts
7
+ import sukuCrypto from '@sukujs/crypto';
8
+
9
+ const jwt = sukuCrypto.createJwt<{ role: string }>({
10
+ secret: env.JWT_SECRET,
11
+ issuer: 'api',
12
+ expiresIn: '15m',
13
+ });
14
+ const token = await jwt.sign({ role: 'admin' }, { subject: user.id });
15
+ const payload = await jwt.verify(token); // throws JwtError if not trustworthy
16
+
17
+ const stored = await sukuCrypto.hashPassword(password);
18
+ await sukuCrypto.verifyPassword(password, stored); // true or false
19
+
20
+ const signed = await sukuCrypto.createSigner(env.COOKIE_SECRET).pack('user.42'); // readable, tamper-proof
21
+ const sealed = await sukuCrypto.createSealer(env.COOKIE_SECRET).seal({ id: 42 }); // encrypted
22
+ ```
23
+
24
+ | Area | API |
25
+ | ------------------- | -------------------------------------------------------------------- |
26
+ | JWT | `createJwt`, `bearerToken`, `decodeJwtUnverified` |
27
+ | Passwords | `hashPassword`, `verifyPassword`, `needsRehash` |
28
+ | Signed values | `createSigner` (HMAC): `sign`, `verify`, `pack`, `unpack` |
29
+ | Encrypted values | `createSealer` (AES-256-GCM): `seal`, `unseal`, with optional `ttl` |
30
+ | Random | `randomToken`, `randomBytes`, `randomHex`, `randomUUID`, `randomInt` |
31
+ | Hashing and compare | `sha256`, `sha512`, `digest`, `timingSafeEqual` |
32
+
33
+ ## JWT
34
+
35
+ ### `createJwt`
36
+
37
+ Creates a signer/verifier bound to one algorithm and one set of keys. The algorithm is fixed
38
+ at creation time and never read from a token.
39
+
40
+ ```ts
41
+ import sukuCrypto from '@sukujs/crypto';
42
+
43
+ // HMAC (default HS256) — secret must be at least 32 bytes for HS256
44
+ const jwt = sukuCrypto.createJwt<{ role: string }>({
45
+ secret: env.JWT_SECRET, // or sukuCrypto.randomToken(32)
46
+ issuer: 'api',
47
+ audience: 'web',
48
+ expiresIn: '15m', // default '1h'; use false for non-expiring tokens
49
+ });
50
+
51
+ // Asymmetric — sign with privateKey, verify with publicKey
52
+ const rsa = sukuCrypto.createJwt({
53
+ algorithm: 'RS256',
54
+ privateKey: process.env.JWT_PRIVATE_PEM, // PKCS#8 PEM
55
+ publicKey: process.env.JWT_PUBLIC_PEM, // SPKI PEM
56
+ issuer: 'api',
57
+ });
58
+
59
+ // Key rotation — old keys verify, never sign
60
+ const rotated = sukuCrypto.createJwt({
61
+ secret: env.JWT_SECRET,
62
+ previousSecrets: [env.JWT_SECRET_OLD],
63
+ });
64
+ ```
65
+
66
+ ### `jwt.sign`
67
+
68
+ Signs a payload with the algorithm and secret (or private key) already set on `createJwt` —
69
+ you do not pass them again. Adds `iat`, `exp`, and the configured `iss` / `aud`.
70
+
71
+ ```ts
72
+ // algorithm + secret come from createJwt above (default HS256 + secret)
73
+ const token = await jwt.sign(
74
+ { role: 'admin' },
75
+ {
76
+ subject: user.id, // sets `sub`
77
+ expiresIn: '5m', // override default lifetime
78
+ notBefore: '30s', // rejected until then
79
+ jwtId: sukuCrypto.randomToken(16), // sets `jti`
80
+ },
81
+ );
82
+ ```
83
+
84
+ ### `jwt.verify`
85
+
86
+ Verifies signature and claims. Throws `JwtError` on failure — treat a failed token as absent.
87
+
88
+ ```ts
89
+ try {
90
+ const payload = await jwt.verify(token);
91
+ // payload.role, payload.sub, payload.exp, …
92
+ } catch (err) {
93
+ if (err instanceof JwtError) {
94
+ // expired | invalid_signature | invalid_claim | …
95
+ }
96
+ throw err;
97
+ }
98
+ ```
99
+
100
+ ### `bearerToken`
101
+
102
+ Extracts the token from an `Authorization: Bearer <token>` header value.
103
+
104
+ ```ts
105
+ import sukuCrypto from '@sukujs/crypto';
106
+
107
+ const token = sukuCrypto.bearerToken(request.headers.get('authorization'));
108
+ if (!token) return Response.json({ error: 'unauthorized' }, { status: 401 });
109
+
110
+ const payload = await jwt.verify(token);
111
+ ```
112
+
113
+ ### `decodeJwtUnverified`
114
+
115
+ Reads header and payload **without verifying anything**. Attacker-controlled — use only to
116
+ pick a key or to log; never to authorize.
117
+
118
+ ```ts
119
+ import sukuCrypto from '@sukujs/crypto';
120
+
121
+ const { header, payload } = sukuCrypto.decodeJwtUnverified(token);
122
+ console.log(header.kid, payload.sub); // do not trust these for access control
123
+ ```
124
+
125
+ ## Passwords
126
+
127
+ PBKDF2-HMAC-SHA256 with 600,000 iterations and a 16-byte random salt, stored as
128
+ `$pbkdf2-sha256$i=600000$<salt>$<hash>`. It is the password KDF every Web Crypto runtime
129
+ has. If you can take a native dependency, Argon2id is stronger.
130
+
131
+ ### `hashPassword`
132
+
133
+ ```ts
134
+ import sukuCrypto from '@sukujs/crypto';
135
+
136
+ const stored = await sukuCrypto.hashPassword(password);
137
+ // "$pbkdf2-sha256$i=600000$…"
138
+
139
+ // Raise the work factor over time
140
+ const stronger = await sukuCrypto.hashPassword(password, { iterations: 800_000 });
141
+ ```
142
+
143
+ ### `verifyPassword`
144
+
145
+ Returns `true` only on a match. Malformed stored values return `false`, never throw.
146
+
147
+ ```ts
148
+ import sukuCrypto from '@sukujs/crypto';
149
+
150
+ if (!(await sukuCrypto.verifyPassword(password, user.passwordHash))) {
151
+ return Response.json({ error: 'invalid credentials' }, { status: 401 });
152
+ }
153
+ ```
154
+
155
+ ### `needsRehash`
156
+
157
+ `true` when the stored hash uses fewer iterations than you now want. Rehash after a
158
+ successful login.
159
+
160
+ ```ts
161
+ import sukuCrypto from '@sukujs/crypto';
162
+
163
+ if (await sukuCrypto.verifyPassword(password, user.passwordHash)) {
164
+ if (sukuCrypto.needsRehash(user.passwordHash, { iterations: 800_000 })) {
165
+ user.passwordHash = await sukuCrypto.hashPassword(password, { iterations: 800_000 });
166
+ }
167
+ }
168
+ ```
169
+
170
+ ## Signed values (`createSigner`)
171
+
172
+ HMAC for values that must not be tampered with: cookies, webhook payloads, unsubscribe
173
+ links. The value stays readable; use `createSealer` to hide it. Secret must be ≥ 32 bytes.
174
+
175
+ ### `createSigner`
176
+
177
+ ```ts
178
+ import sukuCrypto from '@sukujs/crypto';
179
+
180
+ const signer = sukuCrypto.createSigner(env.COOKIE_SECRET); // ≥ 32 bytes
181
+ const rotated = sukuCrypto.createSigner(env.COOKIE_SECRET, {
182
+ previousSecrets: [env.COOKIE_SECRET_OLD],
183
+ hash: 'SHA-256', // default
184
+ });
185
+ ```
186
+
187
+ ### `signer.sign` / `signer.verify`
188
+
189
+ ```ts
190
+ const signature = await signer.sign('hello'); // base64url HMAC
191
+ const ok = await signer.verify('hello', signature); // true
192
+ const bad = await signer.verify('hellp', signature); // false
193
+ ```
194
+
195
+ ### `signer.pack` / `signer.unpack`
196
+
197
+ `value.signature` for cookies and links whose content may be read but not changed.
198
+
199
+ ```ts
200
+ const cookie = await signer.pack('user.42'); // "user.42.<sig>"
201
+ const userId = await signer.unpack(cookie); // "user.42" or undefined
202
+ ```
203
+
204
+ ## Encrypted values (`createSealer`)
205
+
206
+ Authenticated encryption (AES-256-GCM) for values the client holds but must not read or
207
+ change: encrypted cookies, OAuth state, password-reset payloads. Secret must be ≥ 32 bytes.
208
+
209
+ ### `createSealer`
210
+
211
+ ```ts
212
+ import sukuCrypto from '@sukujs/crypto';
213
+
214
+ const sealer = sukuCrypto.createSealer(env.COOKIE_SECRET, {
215
+ purpose: 'session', // binds ciphertext to a use (default 'suku.seal')
216
+ previousSecrets: [env.COOKIE_SECRET_OLD],
217
+ });
218
+
219
+ const reset = sukuCrypto.createSealer(env.COOKIE_SECRET, { purpose: 'reset' });
220
+ // a value sealed as 'session' cannot be opened with 'reset'
221
+ ```
222
+
223
+ ### `sealer.seal` / `sealer.unseal`
224
+
225
+ ```ts
226
+ const sealed = await sealer.seal({ id: 42, role: 'admin' }, { ttl: '1h' });
227
+ const session = await sealer.unseal<{ id: number; role: string }>(sealed);
228
+ // { id: 42, role: 'admin' } — or undefined if tampered, expired, or wrong key/purpose
229
+ ```
230
+
231
+ ## Random
232
+
233
+ ### `randomToken`
234
+
235
+ URL-safe random token. 32 bytes (256 bits) by default — session ids, reset tokens, API keys.
236
+
237
+ ```ts
238
+ import sukuCrypto from '@sukujs/crypto';
239
+
240
+ const sessionId = sukuCrypto.randomToken(); // 32 bytes → base64url
241
+ const apiKey = sukuCrypto.randomToken(32);
242
+ const shortId = sukuCrypto.randomToken(16);
243
+ ```
244
+
245
+ ### `randomBytes`
246
+
247
+ Cryptographically secure random bytes (`Uint8Array`).
248
+
249
+ ```ts
250
+ import sukuCrypto from '@sukujs/crypto';
251
+
252
+ const salt = sukuCrypto.randomBytes(16);
253
+ const iv = sukuCrypto.randomBytes(12);
254
+ ```
255
+
256
+ ### `randomHex`
257
+
258
+ Hex-encoded random bytes. 16 bytes by default.
259
+
260
+ ```ts
261
+ import sukuCrypto from '@sukujs/crypto';
262
+
263
+ const requestId = sukuCrypto.randomHex(); // 32 hex chars
264
+ const nonce = sukuCrypto.randomHex(8);
265
+ ```
266
+
267
+ ### `randomUUID`
268
+
269
+ ```ts
270
+ import sukuCrypto from '@sukujs/crypto';
271
+
272
+ const id = sukuCrypto.randomUUID(); // "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
273
+ ```
274
+
275
+ ### `randomInt`
276
+
277
+ Uniform integer in `[min, max)`, without modulo bias.
278
+
279
+ ```ts
280
+ import sukuCrypto from '@sukujs/crypto';
281
+
282
+ const dice = sukuCrypto.randomInt(1, 7); // 1..6
283
+ const index = sukuCrypto.randomInt(0, items.length);
284
+ ```
285
+
286
+ ## Hashing and compare
287
+
288
+ Not for passwords — use `hashPassword`.
289
+
290
+ ### `sha256` / `sha512`
291
+
292
+ Hex digests for content fingerprints and cache keys.
293
+
294
+ ```ts
295
+ import sukuCrypto from '@sukujs/crypto';
296
+
297
+ const etag = await sukuCrypto.sha256(body);
298
+ const fingerprint = await sukuCrypto.sha512(fileBytes);
299
+ ```
300
+
301
+ ### `digest`
302
+
303
+ Raw digest bytes for a chosen algorithm.
304
+
305
+ ```ts
306
+ import sukuCrypto from '@sukujs/crypto';
307
+
308
+ const bytes = await sukuCrypto.digest('SHA-256', 'hello'); // Uint8Array
309
+ const wide = await sukuCrypto.digest('SHA-512', buffer);
310
+ ```
311
+
312
+ ### `timingSafeEqual`
313
+
314
+ Constant-time compare for secrets you check yourself (API keys, tokens). Signatures from
315
+ this package are already verified in constant time.
316
+
317
+ ```ts
318
+ import sukuCrypto from '@sukujs/crypto';
319
+
320
+ if (!sukuCrypto.timingSafeEqual(providedApiKey, storedApiKey)) {
321
+ return Response.json({ error: 'unauthorized' }, { status: 401 });
322
+ }
323
+ ```
324
+
325
+ ## JWT safety defaults
326
+
327
+ - The algorithm is fixed when you call `createJwt` and is never read from a token, so
328
+ `alg: none` and RSA/HMAC key-confusion tokens are rejected.
329
+ - Tokens expire after one hour unless you set `expiresIn`; a token without `exp` is rejected
330
+ unless you opt out with `expiresIn: false`.
331
+ - HMAC secrets shorter than the hash output (32 bytes for HS256) are refused.
332
+ - `exp`, `nbf`, future `iat`, the configured `issuer` and `audience` are all checked.
333
+ - Supported: HS256/384/512, RS256/384/512, PS256/384/512, ES256/384/512, EdDSA (Ed25519).
334
+ Keys may be PEM (PKCS#8 private, SPKI public), JWK or `CryptoKey`.
335
+ - `previousSecrets` and `previousPublicKeys` allow rotation: old keys verify, never sign.
336
+
337
+ Not included: JWE (encrypted JWTs), JWKS fetching, and token revocation. Keep access tokens
338
+ short-lived and store refresh tokens server-side.
339
+
340
+ This package has not had an independent security audit.