@sukujs/crypto 0.0.0-stage → 0.2.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/dist/index.mjs ADDED
@@ -0,0 +1,580 @@
1
+ // src/errors.ts
2
+ /** Every failure in this package. Branch on `code`; do not show `message` to end users. */
3
+ var CryptoError = class extends Error {
4
+ constructor(code, message, options) {
5
+ super(message, options);
6
+ this.code = code;
7
+ this.name = "CryptoError";
8
+ }
9
+ };
10
+ /** A token that could not be created or must not be trusted. */
11
+ var JwtError = class extends CryptoError {
12
+ constructor(..._args) {
13
+ super(..._args);
14
+ this.name = "JwtError";
15
+ }
16
+ };
17
+
18
+ // src/duration.ts
19
+ const UNITS = {
20
+ s: 1,
21
+ m: 60,
22
+ h: 3600,
23
+ d: 86400,
24
+ w: 604800
25
+ };
26
+ function toSeconds(duration) {
27
+ if (typeof duration === "number") {
28
+ if (!Number.isFinite(duration) || duration < 0) throw new CryptoError("invalid_input", `Invalid duration: ${duration}`);
29
+ return Math.floor(duration);
30
+ }
31
+ const match = /^(\d+(?:\.\d+)?)([smhdw])$/.exec(duration);
32
+ if (!match) throw new CryptoError("invalid_input", `Invalid duration "${duration}". Use seconds or a string like "15m".`);
33
+ return Math.floor(Number(match[1]) * UNITS[match[2]]);
34
+ }
35
+
36
+ // src/encoding.ts
37
+ const encoder = new TextEncoder();
38
+ const decoder = new TextDecoder("utf-8", { fatal: true });
39
+ function toBytes(data) {
40
+ if (typeof data === "string") return encoder.encode(data);
41
+ return new Uint8Array(data);
42
+ }
43
+ function utf8(bytes) {
44
+ try {
45
+ return decoder.decode(bytes);
46
+ } catch (cause) {
47
+ throw new CryptoError("malformed", "Bytes are not valid UTF-8.", { cause });
48
+ }
49
+ }
50
+ function base64urlEncode(data) {
51
+ const bytes = toBytes(data);
52
+ let binary = "";
53
+ for (let i = 0; i < bytes.length; i += 32768) binary += String.fromCharCode(...bytes.subarray(i, i + 32768));
54
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
55
+ }
56
+ const BASE64URL = /^[A-Za-z0-9_-]*$/;
57
+ function base64urlDecode(text) {
58
+ if (!BASE64URL.test(text) || text.length % 4 === 1) throw new CryptoError("malformed", "Value is not valid base64url.");
59
+ const padded = text.replace(/-/g, "+").replace(/_/g, "/") + "===".slice((text.length + 3) % 4);
60
+ const binary = atob(padded);
61
+ const out = new Uint8Array(binary.length);
62
+ for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i);
63
+ return out;
64
+ }
65
+ function hexEncode(bytes) {
66
+ let out = "";
67
+ for (const b of bytes) out += b.toString(16).padStart(2, "0");
68
+ return out;
69
+ }
70
+ /**
71
+ * Compares two values without leaking where they differ through timing. Use it for
72
+ * secrets you compare yourself (API keys, tokens); signatures made by this package are
73
+ * already verified in constant time.
74
+ */
75
+ function timingSafeEqual(a, b) {
76
+ const x = toBytes(a);
77
+ const y = toBytes(b);
78
+ let diff = x.length ^ y.length;
79
+ const n = Math.max(x.length, y.length);
80
+ for (let i = 0; i < n; i++) diff |= (x[i] ?? 0) ^ (y[i] ?? 0);
81
+ return diff === 0;
82
+ }
83
+
84
+ // src/hash.ts
85
+ /** Raw digest bytes. Not for passwords: use `hashPassword`. */
86
+ async function digest(algorithm, data) {
87
+ return new Uint8Array(await crypto.subtle.digest(algorithm, toBytes(data)));
88
+ }
89
+ /** Hex SHA-256, e.g. for content fingerprints and cache keys. */
90
+ async function sha256(data) {
91
+ return hexEncode(await digest("SHA-256", data));
92
+ }
93
+ async function sha512(data) {
94
+ return hexEncode(await digest("SHA-512", data));
95
+ }
96
+
97
+ // src/jwt.ts
98
+ function spec(algorithm) {
99
+ const bits = algorithm.slice(2);
100
+ const hash = `SHA-${bits}`;
101
+ const size = Number(bits) / 8;
102
+ switch (algorithm.slice(0, 2)) {
103
+ case "HS": return {
104
+ import: {
105
+ name: "HMAC",
106
+ hash
107
+ },
108
+ sign: { name: "HMAC" },
109
+ size
110
+ };
111
+ case "RS": return {
112
+ import: {
113
+ name: "RSASSA-PKCS1-v1_5",
114
+ hash
115
+ },
116
+ sign: { name: "RSASSA-PKCS1-v1_5" },
117
+ size
118
+ };
119
+ case "PS": return {
120
+ import: {
121
+ name: "RSA-PSS",
122
+ hash
123
+ },
124
+ sign: {
125
+ name: "RSA-PSS",
126
+ saltLength: size
127
+ },
128
+ size
129
+ };
130
+ case "ES": return {
131
+ import: {
132
+ name: "ECDSA",
133
+ namedCurve: bits === "512" ? "P-521" : `P-${bits}`
134
+ },
135
+ sign: {
136
+ name: "ECDSA",
137
+ hash
138
+ },
139
+ size
140
+ };
141
+ default: return {
142
+ import: { name: "Ed25519" },
143
+ sign: { name: "Ed25519" },
144
+ size: 0
145
+ };
146
+ }
147
+ }
148
+ const ALGORITHMS = [
149
+ "HS256",
150
+ "HS384",
151
+ "HS512",
152
+ "RS256",
153
+ "RS384",
154
+ "RS512",
155
+ "PS256",
156
+ "PS384",
157
+ "PS512",
158
+ "ES256",
159
+ "ES384",
160
+ "ES512",
161
+ "EdDSA"
162
+ ];
163
+ function pemBody(pem, label) {
164
+ const match = new RegExp(`-----BEGIN ${label}-----([\\s\\S]+?)-----END ${label}-----`).exec(pem);
165
+ if (!match) return void 0;
166
+ const binary = atob(match[1].replace(/\s+/g, ""));
167
+ const out = new Uint8Array(binary.length);
168
+ for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i);
169
+ return out;
170
+ }
171
+ async function importKey(input, algorithm, usage) {
172
+ const params = spec(algorithm).import;
173
+ try {
174
+ if (typeof input === "string") {
175
+ const label = usage === "sign" ? "PRIVATE KEY" : "PUBLIC KEY";
176
+ const der = pemBody(input, label);
177
+ if (!der) throw new JwtError("invalid_key", `Expected a PEM "${label}" block (${usage === "sign" ? "PKCS#8" : "SPKI"}). Convert legacy "RSA PRIVATE KEY" / "EC PRIVATE KEY" files with: openssl pkcs8 -topk8 -nocrypt.`);
178
+ return await crypto.subtle.importKey(usage === "sign" ? "pkcs8" : "spki", der, params, false, [usage]);
179
+ }
180
+ if (typeof CryptoKey !== "undefined" && input instanceof CryptoKey) {
181
+ if (!input.usages.includes(usage)) throw new JwtError("invalid_key", `CryptoKey does not allow "${usage}".`);
182
+ return input;
183
+ }
184
+ return await crypto.subtle.importKey("jwk", input, params, false, [usage]);
185
+ } catch (cause) {
186
+ if (cause instanceof JwtError) throw cause;
187
+ throw new JwtError("invalid_key", `Could not import the ${usage} key for ${algorithm}.`, { cause });
188
+ }
189
+ }
190
+ function importSecret(secret, algorithm) {
191
+ const bytes = toBytes(secret);
192
+ const { size, import: params } = spec(algorithm);
193
+ if (bytes.byteLength < size) throw new JwtError("weak_key", `${algorithm} needs a secret of at least ${size} bytes; got ${bytes.byteLength}. Generate one with randomToken(${size}).`);
194
+ return crypto.subtle.importKey("raw", bytes, params, false, ["sign", "verify"]);
195
+ }
196
+ function parseJson(segment, what) {
197
+ let value;
198
+ try {
199
+ value = JSON.parse(utf8(base64urlDecode(segment)));
200
+ } catch (cause) {
201
+ throw new JwtError("malformed", `Token ${what} is not valid.`, { cause });
202
+ }
203
+ if (value === null || typeof value !== "object" || Array.isArray(value)) throw new JwtError("malformed", `Token ${what} is not an object.`);
204
+ return value;
205
+ }
206
+ function numeric(claims, name) {
207
+ const v = claims[name];
208
+ if (v === void 0) return void 0;
209
+ if (typeof v !== "number" || !Number.isFinite(v)) throw new JwtError("invalid_claim", `Claim "${name}" must be a number.`);
210
+ return v;
211
+ }
212
+ /**
213
+ * Creates a signer and verifier bound to one algorithm and one set of keys.
214
+ *
215
+ * The algorithm is fixed here and never taken from a token, which rules out `alg: none` and
216
+ * key-confusion attacks. Verification checks the signature, `exp`, `nbf`, `iat`, and the
217
+ * configured issuer and audience.
218
+ *
219
+ * ```ts
220
+ * const jwt = createJwt<{ role: string }>({ secret: env.JWT_SECRET, issuer: 'api', expiresIn: '15m' });
221
+ * const token = await jwt.sign({ sub: user.id, role: 'admin' });
222
+ * const payload = await jwt.verify(token);
223
+ * ```
224
+ */
225
+ function createJwt(options) {
226
+ const algorithm = options.algorithm ?? "HS256";
227
+ if (!ALGORITHMS.includes(algorithm)) throw new JwtError("algorithm_mismatch", `Unsupported algorithm "${algorithm}".`);
228
+ const hmac = algorithm.startsWith("HS");
229
+ const params = spec(algorithm).sign;
230
+ const tolerance = options.clockTolerance ?? 0;
231
+ const maxLength = options.maxTokenLength ?? 8192;
232
+ const now = () => Math.floor((options.now?.() ?? Date.now()) / 1e3);
233
+ const defaultExpiry = options.expiresIn === void 0 ? "1h" : options.expiresIn;
234
+ let signKey;
235
+ let verifyKeys;
236
+ const getSignKey = () => {
237
+ if (signKey) return signKey;
238
+ if (hmac) {
239
+ if (!("secret" in options) || options.secret === void 0) throw new JwtError("invalid_key", `${algorithm} needs a secret.`);
240
+ signKey = importSecret(options.secret, algorithm);
241
+ } else {
242
+ const key = options.privateKey;
243
+ if (!key) throw new JwtError("invalid_key", `Signing with ${algorithm} needs a privateKey.`);
244
+ signKey = importKey(key, algorithm, "sign");
245
+ }
246
+ return signKey;
247
+ };
248
+ const getVerifyKeys = () => {
249
+ if (verifyKeys) return verifyKeys;
250
+ if (hmac) {
251
+ const o = options;
252
+ if (o.secret === void 0) throw new JwtError("invalid_key", `${algorithm} needs a secret.`);
253
+ verifyKeys = Promise.all([o.secret, ...o.previousSecrets ?? []].map((s) => importSecret(s, algorithm)));
254
+ } else {
255
+ const o = options;
256
+ if (!o.publicKey) throw new JwtError("invalid_key", `Verifying ${algorithm} needs a publicKey.`);
257
+ verifyKeys = Promise.all([o.publicKey, ...o.previousPublicKeys ?? []].map((k) => importKey(k, algorithm, "verify")));
258
+ }
259
+ return verifyKeys;
260
+ };
261
+ async function sign(payload, signOptions = {}) {
262
+ if (payload === null || typeof payload !== "object" || Array.isArray(payload)) throw new JwtError("invalid_input", "JWT payload must be a plain object.");
263
+ const issuedAt = now();
264
+ const claims = {
265
+ ...payload,
266
+ iat: issuedAt
267
+ };
268
+ const expiry = signOptions.expiresIn === void 0 ? defaultExpiry : signOptions.expiresIn;
269
+ if (expiry !== false) claims.exp = issuedAt + toSeconds(expiry);
270
+ if (signOptions.notBefore !== void 0) claims.nbf = issuedAt + toSeconds(signOptions.notBefore);
271
+ if (options.issuer !== void 0) claims.iss = options.issuer;
272
+ if (options.audience !== void 0) claims.aud = options.audience;
273
+ if (signOptions.subject !== void 0) claims.sub = signOptions.subject;
274
+ if (signOptions.jwtId !== void 0) claims.jti = signOptions.jwtId;
275
+ const header = {
276
+ alg: algorithm,
277
+ typ: "JWT"
278
+ };
279
+ if (options.keyId !== void 0) header.kid = options.keyId;
280
+ const signingInput = `${base64urlEncode(JSON.stringify(header))}.${base64urlEncode(JSON.stringify(claims))}`;
281
+ const signature = await crypto.subtle.sign(params, await getSignKey(), toBytes(signingInput));
282
+ return `${signingInput}.${base64urlEncode(new Uint8Array(signature))}`;
283
+ }
284
+ async function verify(token) {
285
+ if (typeof token !== "string" || token.length === 0) throw new JwtError("malformed", "Token is missing.");
286
+ if (token.length > maxLength) throw new JwtError("malformed", "Token is too long.");
287
+ const parts = token.split(".");
288
+ if (parts.length !== 3) throw new JwtError("malformed", "Token must have three parts.");
289
+ const [headerPart, payloadPart, signaturePart] = parts;
290
+ const header = parseJson(headerPart, "header");
291
+ if (header.alg !== algorithm) throw new JwtError("algorithm_mismatch", `Token algorithm is not ${algorithm}.`);
292
+ if (header.crit !== void 0) throw new JwtError("malformed", "Token uses unsupported critical headers.");
293
+ if (header.typ !== void 0 && String(header.typ).toUpperCase() !== "JWT") throw new JwtError("malformed", "Token type is not JWT.");
294
+ const signature = base64urlDecode(signaturePart);
295
+ const data = toBytes(`${headerPart}.${payloadPart}`);
296
+ let valid = false;
297
+ for (const key of await getVerifyKeys()) if (await crypto.subtle.verify(params, key, signature, data)) {
298
+ valid = true;
299
+ break;
300
+ }
301
+ if (!valid) throw new JwtError("invalid_signature", "Token signature is not valid.");
302
+ const claims = parseJson(payloadPart, "payload");
303
+ const at = now();
304
+ const exp = numeric(claims, "exp");
305
+ const nbf = numeric(claims, "nbf");
306
+ const iat = numeric(claims, "iat");
307
+ if (exp === void 0) {
308
+ if (defaultExpiry !== false) throw new JwtError("invalid_claim", "Token has no expiry.");
309
+ } else if (at >= exp + tolerance) throw new JwtError("expired", "Token has expired.");
310
+ if (nbf !== void 0 && at < nbf - tolerance) throw new JwtError("not_active", "Token is not active yet.");
311
+ if (iat !== void 0 && iat > at + tolerance) throw new JwtError("invalid_claim", "Token was issued in the future.");
312
+ if (options.issuer !== void 0 && claims.iss !== options.issuer) throw new JwtError("invalid_claim", "Token issuer does not match.");
313
+ if (options.audience !== void 0) {
314
+ const expected = Array.isArray(options.audience) ? options.audience : [options.audience];
315
+ if (!(Array.isArray(claims.aud) ? claims.aud : [claims.aud]).some((a) => typeof a === "string" && expected.includes(a))) throw new JwtError("invalid_claim", "Token audience does not match.");
316
+ }
317
+ if (options.schema) {
318
+ const result = await options.schema["~standard"].validate(claims);
319
+ if (result.issues) throw new JwtError("invalid_claim", `Token payload is not valid: ${result.issues.map((i) => i.message).join("; ")}`);
320
+ return {
321
+ ...claims,
322
+ ...result.value
323
+ };
324
+ }
325
+ return claims;
326
+ }
327
+ return {
328
+ algorithm,
329
+ sign,
330
+ verify
331
+ };
332
+ }
333
+ /**
334
+ * Reads a token's header and payload **without verifying anything**. The result is
335
+ * attacker-controlled. Use only to pick a key or to log; never to make a decision.
336
+ */
337
+ function decodeJwtUnverified(token) {
338
+ const parts = typeof token === "string" ? token.split(".") : [];
339
+ if (parts.length !== 3) throw new JwtError("malformed", "Token must have three parts.");
340
+ return {
341
+ header: parseJson(parts[0], "header"),
342
+ payload: parseJson(parts[1], "payload")
343
+ };
344
+ }
345
+ /** Extracts the token from an `Authorization: Bearer <token>` header value. */
346
+ function bearerToken(header) {
347
+ if (!header) return void 0;
348
+ return /^Bearer +([A-Za-z0-9._~+/-]+=*)$/i.exec(header.trim())?.[1];
349
+ }
350
+
351
+ // src/random.ts
352
+ /** Cryptographically secure random bytes. */
353
+ function randomBytes(length) {
354
+ if (!Number.isInteger(length) || length < 0 || length > 65536) throw new CryptoError("invalid_input", "Length must be an integer between 0 and 65536.");
355
+ return crypto.getRandomValues(new Uint8Array(length));
356
+ }
357
+ /** A URL-safe random token. 32 bytes (256 bits) by default: session ids, reset tokens, API keys. */
358
+ function randomToken(bytes = 32) {
359
+ return base64urlEncode(randomBytes(bytes));
360
+ }
361
+ function randomHex(bytes = 16) {
362
+ return hexEncode(randomBytes(bytes));
363
+ }
364
+ function randomUUID() {
365
+ return crypto.randomUUID();
366
+ }
367
+ /** A uniformly distributed integer in `[min, max)`, without modulo bias. */
368
+ function randomInt(min, max) {
369
+ const range = max - min;
370
+ if (!Number.isSafeInteger(min) || !Number.isSafeInteger(max) || range <= 0 || range > 4294967295) throw new CryptoError("invalid_input", "randomInt needs integers with 0 < max - min <= 2^32 - 1.");
371
+ const limit = Math.floor(4294967296 / range) * range;
372
+ const buffer = /* @__PURE__ */ new Uint32Array(1);
373
+ for (;;) {
374
+ crypto.getRandomValues(buffer);
375
+ if (buffer[0] < limit) return min + buffer[0] % range;
376
+ }
377
+ }
378
+
379
+ // src/password.ts
380
+ /** OWASP's 2023 minimum for PBKDF2-HMAC-SHA256. */
381
+ const DEFAULT_PASSWORD_ITERATIONS = 6e5;
382
+ const MAX_ITERATIONS = 1e7;
383
+ const PREFIX = "$pbkdf2-sha256$";
384
+ async function derive(password, salt, iterations, length) {
385
+ const key = await crypto.subtle.importKey("raw", toBytes(password.normalize("NFKC")), "PBKDF2", false, ["deriveBits"]);
386
+ const bits = await crypto.subtle.deriveBits({
387
+ name: "PBKDF2",
388
+ hash: "SHA-256",
389
+ salt: toBytes(salt),
390
+ iterations
391
+ }, key, length * 8);
392
+ return new Uint8Array(bits);
393
+ }
394
+ /**
395
+ * Hashes a password for storage, with a random salt, as
396
+ * `$pbkdf2-sha256$i=<iterations>$<salt>$<hash>`.
397
+ *
398
+ * PBKDF2 is used because it is the password KDF every Web Crypto runtime provides. If you
399
+ * can take a native dependency, Argon2id is the stronger choice.
400
+ */
401
+ async function hashPassword(password, options = {}) {
402
+ const iterations = options.iterations ?? 6e5;
403
+ if (!Number.isInteger(iterations) || iterations < 1 || iterations > MAX_ITERATIONS) throw new CryptoError("invalid_input", "Invalid iteration count.");
404
+ if (typeof password !== "string" || password.length === 0) throw new CryptoError("invalid_input", "Password is empty.");
405
+ const salt = randomBytes(16);
406
+ const hash = await derive(password, salt, iterations, 32);
407
+ return `${PREFIX}i=${iterations}$${base64urlEncode(salt)}$${base64urlEncode(hash)}`;
408
+ }
409
+ function parse(stored) {
410
+ if (typeof stored !== "string" || !stored.startsWith(PREFIX)) return void 0;
411
+ const [params, salt, hash, ...rest] = stored.slice(15).split("$");
412
+ const match = /^i=(\d{1,8})$/.exec(params ?? "");
413
+ if (!match || !salt || !hash || rest.length) return void 0;
414
+ const iterations = Number(match[1]);
415
+ if (iterations < 1 || iterations > MAX_ITERATIONS) return void 0;
416
+ try {
417
+ return {
418
+ iterations,
419
+ salt: base64urlDecode(salt),
420
+ hash: base64urlDecode(hash)
421
+ };
422
+ } catch {
423
+ return;
424
+ }
425
+ }
426
+ /** `true` only if the password matches. Malformed stored values are `false`, never an error. */
427
+ async function verifyPassword(password, stored) {
428
+ const parsed = parse(stored);
429
+ if (!parsed || typeof password !== "string") return false;
430
+ const actual = await derive(password, parsed.salt, parsed.iterations, parsed.hash.length);
431
+ let diff = actual.length ^ parsed.hash.length;
432
+ for (let i = 0; i < actual.length; i++) diff |= actual[i] ^ (parsed.hash[i] ?? 0);
433
+ return diff === 0;
434
+ }
435
+ /** Whether a stored hash uses fewer iterations than you now want. Rehash after a successful login. */
436
+ function needsRehash(stored, options = {}) {
437
+ const parsed = parse(stored);
438
+ return !parsed || parsed.iterations < (options.iterations ?? 6e5);
439
+ }
440
+
441
+ // src/seal.ts
442
+ const VERSION = "v1";
443
+ /**
444
+ * Authenticated encryption (AES-256-GCM) for values the client holds but must not read or
445
+ * change: encrypted cookies, OAuth state, password-reset payloads.
446
+ */
447
+ function createSealer(secret, options = {}) {
448
+ const purpose = toBytes(options.purpose ?? "suku.seal");
449
+ const now = () => options.now?.() ?? Date.now();
450
+ const load = async (s) => {
451
+ const bytes = toBytes(s);
452
+ if (bytes.byteLength < 32) throw new CryptoError("weak_key", `Sealing secret must be at least 32 bytes; got ${bytes.byteLength}.`);
453
+ const material = await crypto.subtle.importKey("raw", bytes, "HKDF", false, ["deriveKey"]);
454
+ return crypto.subtle.deriveKey({
455
+ name: "HKDF",
456
+ hash: "SHA-256",
457
+ salt: toBytes("suku.seal.v1"),
458
+ info: purpose
459
+ }, material, {
460
+ name: "AES-GCM",
461
+ length: 256
462
+ }, false, ["encrypt", "decrypt"]);
463
+ };
464
+ let keys;
465
+ const getKeys = () => keys ??= Promise.all([secret, ...options.previousSecrets ?? []].map(load));
466
+ return {
467
+ async seal(value, sealOptions = {}) {
468
+ const envelope = { d: value };
469
+ if (sealOptions.ttl !== void 0) envelope.e = now() + toSeconds(sealOptions.ttl) * 1e3;
470
+ const json = JSON.stringify(envelope);
471
+ if (json === void 0) throw new CryptoError("invalid_input", "Value cannot be serialised to JSON.");
472
+ const iv = randomBytes(12);
473
+ const ciphertext = await crypto.subtle.encrypt({
474
+ name: "AES-GCM",
475
+ iv,
476
+ additionalData: purpose
477
+ }, (await getKeys())[0], toBytes(json));
478
+ return `${VERSION}.${base64urlEncode(iv)}.${base64urlEncode(new Uint8Array(ciphertext))}`;
479
+ },
480
+ async unseal(sealed) {
481
+ if (typeof sealed !== "string") return void 0;
482
+ const parts = sealed.split(".");
483
+ if (parts.length !== 3 || parts[0] !== VERSION) return void 0;
484
+ let iv;
485
+ let ciphertext;
486
+ try {
487
+ iv = base64urlDecode(parts[1]);
488
+ ciphertext = base64urlDecode(parts[2]);
489
+ } catch {
490
+ return;
491
+ }
492
+ if (iv.byteLength !== 12) return void 0;
493
+ for (const key of await getKeys()) try {
494
+ const plain = await crypto.subtle.decrypt({
495
+ name: "AES-GCM",
496
+ iv,
497
+ additionalData: purpose
498
+ }, key, ciphertext);
499
+ const envelope = JSON.parse(utf8(new Uint8Array(plain)));
500
+ if (envelope.e !== void 0 && now() >= envelope.e) return void 0;
501
+ return envelope.d;
502
+ } catch {}
503
+ }
504
+ };
505
+ }
506
+
507
+ // src/signer.ts
508
+ /**
509
+ * HMAC signing for values that must not be tampered with: cookies, webhook payloads,
510
+ * unsubscribe links. The value stays readable; use `createSealer` to hide it.
511
+ */
512
+ function createSigner(secret, options = {}) {
513
+ const hash = options.hash ?? "SHA-256";
514
+ const load = (s) => {
515
+ const bytes = toBytes(s);
516
+ if (bytes.byteLength < 32) throw new CryptoError("weak_key", `Signing secret must be at least 32 bytes; got ${bytes.byteLength}.`);
517
+ return crypto.subtle.importKey("raw", bytes, {
518
+ name: "HMAC",
519
+ hash
520
+ }, false, ["sign", "verify"]);
521
+ };
522
+ let keys;
523
+ const getKeys = () => keys ??= Promise.all([secret, ...options.previousSecrets ?? []].map(load));
524
+ const sign = async (data) => base64urlEncode(new Uint8Array(await crypto.subtle.sign("HMAC", (await getKeys())[0], toBytes(data))));
525
+ const verify = async (data, signature) => {
526
+ let sig;
527
+ try {
528
+ sig = base64urlDecode(signature);
529
+ } catch {
530
+ return false;
531
+ }
532
+ for (const key of await getKeys()) if (await crypto.subtle.verify("HMAC", key, sig, toBytes(data))) return true;
533
+ return false;
534
+ };
535
+ return {
536
+ sign,
537
+ verify,
538
+ pack: async (value) => `${value}.${await sign(value)}`,
539
+ unpack: async (packed) => {
540
+ const at = typeof packed === "string" ? packed.lastIndexOf(".") : -1;
541
+ if (at === -1) return void 0;
542
+ const value = packed.slice(0, at);
543
+ return await verify(value, packed.slice(at + 1)) ? value : void 0;
544
+ }
545
+ };
546
+ }
547
+
548
+ // src/index.ts
549
+ /**
550
+ * Everything in one object, for `import sukuCrypto from '@sukujs/crypto'`.
551
+ * The named exports are the same functions and tree-shake better.
552
+ */
553
+ const sukuCrypto = {
554
+ createJwt,
555
+ bearerToken,
556
+ decodeJwtUnverified,
557
+ hashPassword,
558
+ verifyPassword,
559
+ needsRehash,
560
+ createSigner,
561
+ createSealer,
562
+ randomToken,
563
+ randomBytes,
564
+ randomHex,
565
+ randomUUID,
566
+ randomInt,
567
+ sha256,
568
+ sha512,
569
+ digest,
570
+ timingSafeEqual,
571
+ base64urlEncode,
572
+ base64urlDecode,
573
+ hexEncode,
574
+ toSeconds,
575
+ CryptoError,
576
+ JwtError
577
+ };
578
+
579
+ export { CryptoError, DEFAULT_PASSWORD_ITERATIONS, JwtError, base64urlDecode, base64urlEncode, bearerToken, createJwt, createSealer, createSigner, decodeJwtUnverified, sukuCrypto as default, digest, hashPassword, hexEncode, needsRehash, randomBytes, randomHex, randomInt, randomToken, randomUUID, sha256, sha512, timingSafeEqual, toSeconds, verifyPassword };
580
+ //# sourceMappingURL=index.mjs.map