@exortek/challenge 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.
@@ -0,0 +1,707 @@
1
+ /**
2
+ * Non-throwing type predicates. Companion to `asserts.js`.
3
+ *
4
+ * ### When to reach for which
5
+ *
6
+ * - Writing a **throw-guard** at a function boundary — a bad shape
7
+ * should fail with the caller's typed error class? Use
8
+ * `asserts` + `defineGuards` (`assertObject`, `assertString`, …).
9
+ * The `assert*` family bundles the check with the correctly-bound
10
+ * throw and preserves the "one error class per package" contract.
11
+ *
12
+ * - Writing a **dispatch / branch / fallback** where the wrong shape
13
+ * is meant to be handled, not thrown? Use these predicates.
14
+ * Typical shapes:
15
+ *
16
+ * if (isObject(config.store)) { ... } else { ... }
17
+ *
18
+ * const isManager = isObject(v) && isFunction(v.issue);
19
+ *
20
+ * The two APIs deliberately do not overlap in intent: `assert*` throws,
21
+ * `is*` never does. Bypassing an `assert*` with an `if (!is*(x)) throw
22
+ * new PkgError(...)` pattern skips the package's guards binding and
23
+ * duplicates work the assert family already handles — don't.
24
+ */
25
+
26
+
27
+ /**
28
+ * `true` when `value` is a function. Class constructors, arrow
29
+ * functions, and generator functions all pass — `typeof` on any
30
+ * callable is `'function'`.
31
+ *
32
+ * @param {unknown} value
33
+ * @returns {boolean}
34
+ */
35
+ function isFunction(value) {
36
+ return typeof value === 'function';
37
+ }
38
+
39
+ /**
40
+ * `true` when `value` is `undefined`.
41
+ *
42
+ * @param {unknown} value
43
+ * @returns {boolean}
44
+ */
45
+ function isUndefined(value) {
46
+ return typeof value === 'undefined';
47
+ }
48
+
49
+ /**
50
+ * `true` for a safe integer — a finite `number` inside `[MIN_SAFE_INTEGER,
51
+ * MAX_SAFE_INTEGER]` with no fractional part. Mirrors `Number.isSafeInteger`.
52
+ *
53
+ * @param {unknown} value
54
+ * @returns {boolean}
55
+ */
56
+ function isInteger(value) {
57
+ return Number.isSafeInteger(value);
58
+ }
59
+
60
+ /**
61
+ * Imperative single-argument guard helpers — the everyday
62
+ * `assertPositiveInt(x, 'name')` shape used at API boundaries.
63
+ * Companion to the compound schema builder in
64
+ * `@exortek/shared/validate`: **schema** for whole options objects,
65
+ * **asserts** for one-liner argument guards at the call site.
66
+ *
67
+ * The consumer surface is {@link defineGuards} (or the raw
68
+ * {@link bindAsserts} for full control). Each package binds the assert
69
+ * set to its own typed error class once (in `internal/guards.js`), so
70
+ * every argument failure throws that package's class —
71
+ * `err instanceof CryptoError` holds and users see at a glance which
72
+ * package raised the error. The bound `parse` bridges
73
+ * `@exortek/shared/validate` schemas to the same error class.
74
+ *
75
+ * **Path naming convention** (used as the `name` argument):
76
+ *
77
+ * `<publicFunction>[.options|.config][.<field>]`
78
+ *
79
+ * - `assertString(name, 'createUser.name')` — top-level arg
80
+ * - `assertPositiveInt(n, 'scrypt.options.r')` — nested option
81
+ * - `assertBytesOrString(pwd, 'pepper.wrap.password')` — method arg
82
+ *
83
+ * Keep the path short: the emitted error is `"<name> must be <desc>"`,
84
+ * so a stack-line grep already tells the caller which function fired.
85
+ * Reserve `hint` for actionable follow-ups ("pass the bytes returned by
86
+ * encryptSymmetric()"), not for restating the field.
87
+ */
88
+
89
+ /**
90
+ * @typedef {{ cause?: unknown }} WrapExtra
91
+ * Extra options forwarded to the wrap function, so `invalidArgument`
92
+ * sites that catch an underlying error can preserve the `cause` chain
93
+ * without falling back to a raw `new PackageError(...)`.
94
+ *
95
+ * @typedef {(message: string, extra?: WrapExtra) => Error} WrapFn
96
+ * Constructs (never throws) the binding package's error, e.g.
97
+ * `(m, { cause } = {}) => new CryptoError(ErrorCode.INVALID_ARGUMENT, m, { cause })`.
98
+ *
99
+ * @typedef {{ hint?: string }} AssertOptions
100
+ * `hint` is appended to the message after an em-dash — use it for
101
+ * actionable guidance ("pass the exact bytes returned by …").
102
+ *
103
+ * @typedef {{ safeParse: (input: unknown, path?: string) => { ok: true, value: unknown } | { ok: false, errors: string[] } }} ParseableSchema
104
+ */
105
+
106
+ /**
107
+ * Build the failure message. `description` completes the sentence
108
+ * `"<name> must be <description>"`; `hint` (optional) follows an
109
+ * em-dash.
110
+ *
111
+ * @param {string} name
112
+ * @param {string} description
113
+ * @param {string} [hint]
114
+ * @returns {string}
115
+ */
116
+ function message(name, description, hint) {
117
+ return `${name} must be ${description}${hint ? ` — ${hint}` : ''}`;
118
+ }
119
+
120
+ const ENCODINGS = new Set(['hex', 'base64', 'base64url']);
121
+
122
+ /**
123
+ * Bind the assert set to a package's error class. Call once per
124
+ * package (conventionally in `internal/guards.js`) and import the
125
+ * bound object everywhere:
126
+ *
127
+ * import { bindAsserts } from '@exortek/shared/asserts';
128
+ * import { CryptoError, ErrorCode } from '../errors.js';
129
+ * export const g = bindAsserts((m) => new CryptoError(ErrorCode.INVALID_ARGUMENT, m));
130
+ *
131
+ * // call sites:
132
+ * g.assertPositiveInt(options.iterations, 'options.iterations');
133
+ * const cfg = g.parse(OptionsSchema, options, 'options');
134
+ *
135
+ * @param {WrapFn} wrap
136
+ */
137
+ function bindAsserts(wrap) {
138
+ /**
139
+ * @param {string} name
140
+ * @param {string} description
141
+ * @param {AssertOptions} [opts]
142
+ * @returns {never}
143
+ */
144
+ function fail(name, description, opts) {
145
+ throw wrap(message(name, description, opts?.hint));
146
+ }
147
+
148
+ /**
149
+ * Assert that `value` is a plain object (not `null`, not an array,
150
+ * not a primitive).
151
+ * @param {unknown} value
152
+ * @param {string} name
153
+ * @param {AssertOptions} [opts]
154
+ */
155
+ function assertObject(value, name, opts) {
156
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
157
+ fail(name, 'an object', opts);
158
+ }
159
+ }
160
+
161
+ return {
162
+ /**
163
+ * Construct (not throw) the bound error with a free-form message —
164
+ * for `throw g.invalidArgument('…')` sites that don't fit the
165
+ * `X must be Y` shape (canonicalisation errors, cross-field
166
+ * constraint failures). Pass `{ cause }` when the argument-shape
167
+ * failure was triggered by an underlying throw whose chain matters
168
+ * (e.g. `JSON.stringify` on a bigint).
169
+ *
170
+ * @param {string} msg
171
+ * @param {WrapExtra} [extra]
172
+ * @returns {Error}
173
+ */
174
+ invalidArgument(msg, extra) {
175
+ return wrap(msg, extra);
176
+ },
177
+
178
+ /**
179
+ * Validate `input` against a `@exortek/shared/validate` schema;
180
+ * failures throw the bound error carrying every collected message.
181
+ * The bridge that keeps schema validation on the package's own
182
+ * error surface.
183
+ *
184
+ * @param {ParseableSchema} schema
185
+ * @param {unknown} input
186
+ * @param {string} [path='options']
187
+ * @returns {unknown} the parsed (possibly defaulted) value
188
+ */
189
+ parse(schema, input, path = 'options') {
190
+ const r = schema.safeParse(input, path);
191
+ if (!r.ok) {
192
+ throw wrap(r.errors.join('; '));
193
+ }
194
+ return r.value;
195
+ },
196
+
197
+ /**
198
+ * Assert that `value` is a non-negative safe integer (`0, 1, 2, …`).
199
+ * @param {unknown} value
200
+ * @param {string} name Argument name to include in the error message.
201
+ * @param {AssertOptions} [opts]
202
+ */
203
+ assertNonNegativeInt(value, name, opts) {
204
+ if (!Number.isSafeInteger(value) || /** @type {number} */ (value) < 0) {
205
+ fail(name, 'a non-negative safe integer', opts);
206
+ }
207
+ },
208
+
209
+ /**
210
+ * Assert that `value` is a strictly positive safe integer (`1, 2, 3, …`).
211
+ * @param {unknown} value
212
+ * @param {string} name
213
+ * @param {AssertOptions} [opts]
214
+ */
215
+ assertPositiveInt(value, name, opts) {
216
+ if (!Number.isSafeInteger(value) || /** @type {number} */ (value) <= 0) {
217
+ fail(name, 'a positive integer', opts);
218
+ }
219
+ },
220
+
221
+ /**
222
+ * Assert that `value` fits in a 48-bit unsigned integer (`0 … 2^48 − 1`).
223
+ * Used for Unix millisecond timestamps in UUID v7 / ULID.
224
+ * @param {unknown} value
225
+ * @param {string} name
226
+ * @param {AssertOptions} [opts]
227
+ */
228
+ assertUint48(value, name, opts) {
229
+ if (
230
+ !Number.isSafeInteger(value) ||
231
+ /** @type {number} */ (value) < 0 ||
232
+ /** @type {number} */ (value) > 0xffffffffffff
233
+ ) {
234
+ fail(name, 'a non-negative safe integer ≤ 2^48 − 1 (Unix ms since epoch)', opts);
235
+ }
236
+ },
237
+
238
+ /**
239
+ * Assert that `value` is a string (may be empty).
240
+ * @param {unknown} value
241
+ * @param {string} name
242
+ * @param {AssertOptions} [opts]
243
+ */
244
+ assertString(value, name, opts) {
245
+ if (typeof value !== 'string') {
246
+ fail(name, 'a string', opts);
247
+ }
248
+ },
249
+
250
+ /**
251
+ * Assert that `value` is a non-empty string.
252
+ * @param {unknown} value
253
+ * @param {string} name
254
+ * @param {AssertOptions} [opts]
255
+ */
256
+ assertNonEmptyString(value, name, opts) {
257
+ if (typeof value !== 'string' || value.length === 0) {
258
+ fail(name, 'a non-empty string', opts);
259
+ }
260
+ },
261
+
262
+ /**
263
+ * Assert that `value` is a boolean.
264
+ * @param {unknown} value
265
+ * @param {string} name
266
+ * @param {AssertOptions} [opts]
267
+ */
268
+ assertBoolean(value, name, opts) {
269
+ if (typeof value !== 'boolean') {
270
+ fail(name, 'a boolean', opts);
271
+ }
272
+ },
273
+
274
+ /**
275
+ * Assert that `value` is a function.
276
+ * @param {unknown} value
277
+ * @param {string} name
278
+ * @param {AssertOptions} [opts]
279
+ */
280
+ assertFunction(value, name, opts) {
281
+ if (typeof value !== 'function') {
282
+ fail(name, 'a function', opts);
283
+ }
284
+ },
285
+
286
+ assertObject,
287
+
288
+ /**
289
+ * Assert that `value` is either `undefined` or a plain object —
290
+ * the "optional options object" pattern.
291
+ * @param {unknown} value
292
+ * @param {string} name
293
+ * @param {AssertOptions} [opts]
294
+ */
295
+ assertOptionalObject(value, name, opts) {
296
+ if (value === undefined) {
297
+ return;
298
+ }
299
+ assertObject(value, name, opts);
300
+ },
301
+
302
+ /**
303
+ * Assert that `value` is a byte buffer (`Buffer` or `Uint8Array`) —
304
+ * strings are NOT accepted. For already-encoded material where a
305
+ * string would be ambiguous (ciphertext, signatures, raw key bytes).
306
+ * @param {unknown} value
307
+ * @param {string} name
308
+ * @param {AssertOptions} [opts]
309
+ */
310
+ assertBytes(value, name, opts) {
311
+ if (!Buffer.isBuffer(value) && !(value instanceof Uint8Array)) {
312
+ fail(name, 'a Buffer or Uint8Array', opts);
313
+ }
314
+ },
315
+
316
+ /**
317
+ * Assert that `value` is either a string or a byte buffer (`Buffer`
318
+ * or `Uint8Array`).
319
+ * @param {unknown} value
320
+ * @param {string} name
321
+ * @param {AssertOptions} [opts]
322
+ */
323
+ assertBytesOrString(value, name, opts) {
324
+ if (typeof value !== 'string' && !Buffer.isBuffer(value) && !(value instanceof Uint8Array)) {
325
+ fail(name, 'a string or Buffer', opts);
326
+ }
327
+ },
328
+
329
+ /**
330
+ * Assert that `encoding` is one of the accepted output/input
331
+ * encodings. Pass `allowBuffer: false` where a `Buffer` output makes
332
+ * no sense (verifying a string signature, decoding a token payload).
333
+ *
334
+ * @param {unknown} encoding
335
+ * @param {string} name
336
+ * @param {AssertOptions & { allowBuffer?: boolean }} [opts]
337
+ */
338
+ assertEncoding(encoding, name, opts) {
339
+ const allowBuffer = opts?.allowBuffer !== false;
340
+ const valid = (typeof encoding === 'string' && ENCODINGS.has(encoding)) || (allowBuffer && encoding === 'buffer');
341
+ if (!valid) {
342
+ const list = allowBuffer ? "'hex', 'base64', 'base64url', or 'buffer'" : "'hex', 'base64', or 'base64url'";
343
+ fail(name, list, opts);
344
+ }
345
+ },
346
+ };
347
+ }
348
+
349
+ /**
350
+ * One-line sugar over {@link bindAsserts} — the overwhelmingly common
351
+ * pattern where a package binds every argument-shape failure to its
352
+ * own error class + `INVALID_ARGUMENT` code. Emits the standard
353
+ * `new ErrorClass(code, message, { cause })` shape, so the underlying
354
+ * `BaseError` `{ cause, status, details }` options object is respected.
355
+ *
356
+ * // packages/<pkg>/src/internal/guards.js
357
+ * import { defineGuards } from '@exortek/shared/asserts';
358
+ * import { PasswordError, ErrorCode } from '../errors.js';
359
+ *
360
+ * export const { assertString, invalidArgument, parse } =
361
+ * defineGuards(PasswordError, ErrorCode.INVALID_ARGUMENT);
362
+ *
363
+ * Reach for the raw {@link bindAsserts} when you need a different
364
+ * mapping (an alt code, a decorated message) — it stays available.
365
+ *
366
+ * @param {new (code: string, message: string, options?: { cause?: unknown }) => Error} ErrorClass
367
+ * @param {string} code
368
+ */
369
+ function defineGuards(ErrorClass, code) {
370
+ return bindAsserts((message, extra) => new ErrorClass(code, message, extra));
371
+ }
372
+
373
+ /**
374
+ * Shared base error class — the single error structure behind every
375
+ * `@exortek/*` package's `errors.js`.
376
+ *
377
+ * Every package keeps its own class identity with a one-liner subclass;
378
+ * codes stay per-package frozen maps, status mapping is declared as a
379
+ * static field:
380
+ *
381
+ * import { BaseError } from '@exortek/shared/errors';
382
+ *
383
+ * export const ErrorCode = Object.freeze({
384
+ * INVALID_ARGUMENT: 'INVALID_ARGUMENT',
385
+ * INVALID_TOKEN: 'INVALID_TOKEN',
386
+ * });
387
+ *
388
+ * export class JwtError extends BaseError {
389
+ * static statuses = { INVALID_ARGUMENT: 400, INVALID_TOKEN: 401 };
390
+ * static defaultStatus = 500;
391
+ * }
392
+ *
393
+ * Instances carry a stable machine-readable `code` (branch on this,
394
+ * never on the message), an optional HTTP `status`, an optional
395
+ * `details` object, and the standard `cause` chain.
396
+ */
397
+ class BaseError extends Error {
398
+ /**
399
+ * Optional `code → HTTP status` map declared on the subclass. When
400
+ * absent the instance carries no `status` at all — for HTTP-agnostic
401
+ * packages like `@exortek/crypto`.
402
+ *
403
+ * @type {Record<string, number> | undefined}
404
+ */
405
+ static statuses = undefined;
406
+
407
+ /**
408
+ * Fallback status for codes missing from `statuses`.
409
+ *
410
+ * @type {number}
411
+ */
412
+ static defaultStatus = 500;
413
+
414
+ /**
415
+ * @param {string} code Stable machine-readable code; branch on this.
416
+ * @param {string} message Human-readable diagnostic. Free-form; may
417
+ * change across versions.
418
+ * @param {{ cause?: unknown, status?: number, details?: Record<string, unknown> }} [options]
419
+ */
420
+ constructor(code, message, options = {}) {
421
+ super(message, options.cause !== undefined ? { cause: options.cause } : undefined);
422
+ this.name = new.target.name;
423
+ /** @type {string} */
424
+ this.code = code;
425
+ const statuses = /** @type {typeof BaseError} */ (new.target).statuses;
426
+ if (options.status !== undefined) {
427
+ /** @type {number | undefined} */
428
+ this.status = options.status;
429
+ } else if (statuses !== undefined) {
430
+ // Object.hasOwn guards against inherited-property lookups for
431
+ // exotic code values ('toString', 'constructor', …).
432
+ this.status = Object.hasOwn(statuses, code)
433
+ ? statuses[code]
434
+ : /** @type {typeof BaseError} */ (new.target).defaultStatus;
435
+ }
436
+ if (options.details) {
437
+ /** @type {Record<string, unknown> | undefined} */
438
+ this.details = options.details;
439
+ }
440
+ }
441
+ }
442
+
443
+ /**
444
+ * Stable machine-readable codes for every programmer-error failure that
445
+ * `@exortek/challenge` can raise. Branch on `code`, never on the
446
+ * message. Note: expected verify failures (bad signature, expired,
447
+ * mismatched claim) are NOT thrown — `verifyChallenge` returns
448
+ * `{ valid: false, reason }` for those so a wrong or stale token is a
449
+ * normal auth outcome, not an exception. Errors below fire only when
450
+ * the caller configured something wrong.
451
+ */
452
+
453
+ const ErrorCode = Object.freeze({
454
+ INVALID_ARGUMENT: 'INVALID_ARGUMENT',
455
+ INVALID_SECRET: 'INVALID_SECRET',
456
+ });
457
+
458
+ /**
459
+ * Every recoverable failure raised by this package. Carries a stable
460
+ * `code` (from {@link ErrorCode}) and a `status` — the HTTP response
461
+ * status a middleware layer would use when translating the error.
462
+ */
463
+ class ChallengeError extends BaseError {
464
+ static statuses = {
465
+ [ErrorCode.INVALID_ARGUMENT]: 400,
466
+ [ErrorCode.INVALID_SECRET]: 400,
467
+ };
468
+ static defaultStatus = 500;
469
+ }
470
+
471
+ /**
472
+ * Argument guards bound to `ChallengeError` — the package-wide binding
473
+ * of `@exortek/shared/asserts`. Import guards from here, never from the
474
+ * shared module directly: every argument-shape failure must throw
475
+ * `ChallengeError` with `ErrorCode.INVALID_ARGUMENT` so callers get one
476
+ * error class for the whole package.
477
+ */
478
+
479
+
480
+ const { invalidArgument} = defineGuards(
481
+ ChallengeError,
482
+ ErrorCode.INVALID_ARGUMENT,
483
+ );
484
+
485
+ /**
486
+ * In-process memory store for challenge single-use enforcement.
487
+ *
488
+ * Not cluster-safe: every worker has its own state, so a token accepted
489
+ * on one worker could still be replayed on another. Use for dev,
490
+ * single-node deploys, sticky-session behind an LB, and tests. For
491
+ * multi-worker production, use {@link redisStore} or pass any object
492
+ * exposing `incr(key, ttlMs) → { count }` (e.g.
493
+ * `@exortek/security`'s rate-limit stores).
494
+ *
495
+ * Eviction: true LRU (least-recently-used). Every `incr` on an existing
496
+ * key re-inserts it so it becomes the newest entry;
497
+ * `map.keys().next().value` is then the least-recently-touched key and
498
+ * is dropped when `maxKeys` is exceeded. This matters for the
499
+ * replay-guard tombstone: a repeated verify attempt refreshes the
500
+ * `count > 1` entry so it stays authoritative until its TTL expires.
501
+ * FIFO would let an idle tombstone age out prematurely and a third
502
+ * replay attempt could see a fresh counter.
503
+ *
504
+ * Textbook pattern, popularised in the JS community by projects like
505
+ * `toad-cache` (MIT); no code copied, only the same ES2015
506
+ * iteration-order guarantee.
507
+ *
508
+ * Expired entries are pruned lazily on read, plus a `setInterval` sweep
509
+ * (unref'd so it never blocks process exit). The `maxKeys` cap
510
+ * protects against unbounded growth if the caller forgets to clean up.
511
+ */
512
+
513
+
514
+ /**
515
+ * @typedef {object} MemoryStoreOptions
516
+ * @property {number} [maxKeys=10000] Hard cap; oldest entry dropped when exceeded.
517
+ * @property {number} [sweepMs=60000] Interval for the background TTL sweep.
518
+ */
519
+
520
+ /**
521
+ * @param {MemoryStoreOptions} [options]
522
+ * @returns {import('./index.js').IncrStore & { _size: () => number, _stop: () => void }}
523
+ */
524
+ function memoryStore(options = {}) {
525
+ const maxKeys = options.maxKeys ?? 10_000;
526
+ const sweepMs = options.sweepMs ?? 60_000;
527
+
528
+ if (!isInteger(maxKeys) || maxKeys < 1) {
529
+ throw invalidArgument(`memoryStore.options.maxKeys must be a positive integer; got ${maxKeys}`);
530
+ }
531
+ if (!isInteger(sweepMs) || sweepMs < 1000) {
532
+ throw invalidArgument(`memoryStore.options.sweepMs must be an integer >= 1000; got ${sweepMs}`);
533
+ }
534
+
535
+ /** @type {Map<string, { count: number, expiresAt: number }>} */
536
+ const map = new Map();
537
+ let timer = null;
538
+
539
+ function peekFresh(key) {
540
+ const entry = map.get(key);
541
+ if (!entry) {
542
+ return null;
543
+ }
544
+ if (entry.expiresAt <= Date.now()) {
545
+ map.delete(key);
546
+ return null;
547
+ }
548
+ return entry;
549
+ }
550
+
551
+ function sweep() {
552
+ const t = Date.now();
553
+ for (const [key, entry] of map) {
554
+ if (entry.expiresAt <= t) {
555
+ map.delete(key);
556
+ }
557
+ }
558
+ }
559
+
560
+ function scheduleSweeper() {
561
+ if (timer) {
562
+ return;
563
+ }
564
+ timer = setInterval(sweep, sweepMs);
565
+ if (isFunction(timer.unref)) {
566
+ timer.unref();
567
+ }
568
+ }
569
+
570
+ function evictIfFull() {
571
+ if (map.size < maxKeys) {
572
+ return;
573
+ }
574
+ const oldest = map.keys().next().value;
575
+ if (!isUndefined(oldest)) {
576
+ map.delete(oldest);
577
+ }
578
+ }
579
+
580
+ return {
581
+ async incr(key, ttlMs) {
582
+ scheduleSweeper();
583
+ const existing = peekFresh(key);
584
+ if (existing) {
585
+ existing.count += 1;
586
+ // Refresh LRU position on activity — the replay-guard tombstone
587
+ // must stay warm until its TTL fires, or a third replay attempt
588
+ // could see the entry evicted and get a fresh count.
589
+ map.delete(key);
590
+ map.set(key, existing);
591
+ return { count: existing.count, expiresAt: existing.expiresAt };
592
+ }
593
+ evictIfFull();
594
+ const expiresAt = Date.now() + ttlMs;
595
+ map.set(key, { count: 1, expiresAt });
596
+ return { count: 1, expiresAt };
597
+ },
598
+
599
+ _size: () => map.size,
600
+ _stop: () => {
601
+ if (timer) {
602
+ clearInterval(timer);
603
+ timer = null;
604
+ }
605
+ },
606
+ };
607
+ }
608
+
609
+ /**
610
+ * Duck-type guard for a Redis-compatible client. Every `@exortek/*`
611
+ * package that ships a Redis store (jwt blacklist, session store,
612
+ * security rate-limit) does the same "not null + required methods
613
+ * are functions" check up front so a missing dependency surfaces as
614
+ * a clean typed error instead of `TypeError: client.get is not a
615
+ * function` deep in a store operation.
616
+ *
617
+ * Callers pass their own `wrap` callback that throws their typed
618
+ * error class with the message — this file has no opinion on the
619
+ * error surface.
620
+ */
621
+
622
+ /**
623
+ * @param {unknown} client
624
+ * @param {readonly string[]} methods Method names that must be functions on the client.
625
+ * @param {(message: string) => never} wrap
626
+ * Called with a diagnostic message when the check fails; must throw.
627
+ * The caller's typed error class is emitted from inside this callback.
628
+ * @returns {void}
629
+ */
630
+ function assertRedisClient(client, methods, wrap) {
631
+ if (!client || typeof client !== 'object') {
632
+ wrap('client is required — pass a Redis-compatible instance (ioredis / node-redis / @upstash/redis)');
633
+ }
634
+ const c = /** @type {Record<string, unknown>} */ (client);
635
+ for (const method of methods) {
636
+ if (typeof c[method] !== 'function') {
637
+ wrap(`client is missing '${method}()' — is this a Redis-compatible client?`);
638
+ }
639
+ }
640
+ }
641
+
642
+ /**
643
+ * Redis-backed store for challenge single-use enforcement.
644
+ *
645
+ * Cluster-safe: state lives in Redis, so a challenge accepted on one
646
+ * worker cannot be replayed on another. Works with any client exposing
647
+ * `eval(script, numkeys, ...args)` — verified against `ioredis`,
648
+ * `node-redis` v4+, and `@upstash/redis` (HTTP client, runs on
649
+ * Cloudflare Workers / Vercel Edge / Deno Deploy).
650
+ *
651
+ * Atomicity: `incr` runs a single Lua script that INCR's the key and
652
+ * PEXPIRE's it only when the key is fresh (count === 1). The TTL
653
+ * anchors to the first increment — exactly what single-use enforcement
654
+ * needs (the tombstone lives as long as the token could still verify,
655
+ * then rolls off).
656
+ */
657
+
658
+
659
+ const INCR_SCRIPT = `
660
+ local key = KEYS[1]
661
+ local ttl = tonumber(ARGV[1])
662
+ local count = redis.call('INCR', key)
663
+ local pttl
664
+ if count == 1 then
665
+ redis.call('PEXPIRE', key, ttl)
666
+ pttl = ttl
667
+ else
668
+ pttl = redis.call('PTTL', key)
669
+ if pttl < 0 then
670
+ redis.call('PEXPIRE', key, ttl)
671
+ pttl = ttl
672
+ end
673
+ end
674
+ return { count, pttl }
675
+ `.trim();
676
+
677
+ /**
678
+ * @typedef {object} RedisStoreOptions
679
+ * @property {string} [keyPrefix='chall:'] Prepended to every key.
680
+ */
681
+
682
+ /**
683
+ * @param {any} client
684
+ * @param {RedisStoreOptions} [options]
685
+ * @returns {import('./index.js').IncrStore}
686
+ */
687
+ function redisStore(client, options = {}) {
688
+ assertRedisClient(client, ['eval'], msg => {
689
+ throw invalidArgument(`redisStore.client: ${msg}`);
690
+ });
691
+ const keyPrefix = options.keyPrefix ?? 'chall:';
692
+ const k = key => `${keyPrefix}${key}`;
693
+
694
+ return {
695
+ async incr(key, ttlMs) {
696
+ const raw = await client.eval(INCR_SCRIPT, 1, k(key), String(Math.max(1, Math.ceil(ttlMs))));
697
+ // ioredis returns [count, pttl] as numbers; node-redis v4 does too;
698
+ // Upstash HTTP driver returns strings. Coerce defensively.
699
+ const arr = Array.isArray(raw) ? raw : [raw, ttlMs];
700
+ const count = Number(arr[0]);
701
+ const pttl = Number(arr[1]);
702
+ return { count, expiresAt: Date.now() + (Number.isFinite(pttl) && pttl > 0 ? pttl : ttlMs) };
703
+ },
704
+ };
705
+ }
706
+
707
+ export { memoryStore, redisStore };