@exortek/apikey 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,877 @@
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
+ * `true` when `value` is a plain object *or* a class instance — anything
28
+ * whose property access is safe. Rejects `null`, arrays, and every
29
+ * primitive.
30
+ *
31
+ * The Node convention `typeof x === 'object' && x !== null` accepts
32
+ * arrays, which almost never matches caller intent (an array is not a
33
+ * "config object"). This predicate additionally rules arrays out, so
34
+ * `isObject(x)` really means "I can read `x.foo` without exploding on
35
+ * a numeric index".
36
+ *
37
+ * Class instances (Node `KeyObject`, `URL`, user-defined classes) pass
38
+ * because they carry `typeof === 'object'` — the check is duck-typed,
39
+ * not prototype-restricted.
40
+ *
41
+ * @param {unknown} value
42
+ * @returns {boolean}
43
+ */
44
+ function isObject(value) {
45
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
46
+ }
47
+
48
+ /**
49
+ * `true` when `value` is a string primitive. `String` boxed objects
50
+ * (from `new String('x')`) are refused — those are a footgun almost no
51
+ * one wants, and every place in this codebase reads strings by
52
+ * primitive access.
53
+ *
54
+ * @param {unknown} value
55
+ * @returns {boolean}
56
+ */
57
+ function isString(value) {
58
+ return typeof value === 'string';
59
+ }
60
+
61
+ /**
62
+ * `true` when `value` is a function. Class constructors, arrow
63
+ * functions, and generator functions all pass — `typeof` on any
64
+ * callable is `'function'`.
65
+ *
66
+ * @param {unknown} value
67
+ * @returns {boolean}
68
+ */
69
+ function isFunction(value) {
70
+ return typeof value === 'function';
71
+ }
72
+
73
+ /**
74
+ * `true` when `value` is `undefined`.
75
+ *
76
+ * @param {unknown} value
77
+ * @returns {boolean}
78
+ */
79
+ function isUndefined(value) {
80
+ return typeof value === 'undefined';
81
+ }
82
+
83
+ /**
84
+ * Imperative single-argument guard helpers — the everyday
85
+ * `assertPositiveInt(x, 'name')` shape used at API boundaries.
86
+ * Companion to the compound schema builder in
87
+ * `@exortek/shared/validate`: **schema** for whole options objects,
88
+ * **asserts** for one-liner argument guards at the call site.
89
+ *
90
+ * The consumer surface is {@link defineGuards} (or the raw
91
+ * {@link bindAsserts} for full control). Each package binds the assert
92
+ * set to its own typed error class once (in `internal/guards.js`), so
93
+ * every argument failure throws that package's class —
94
+ * `err instanceof CryptoError` holds and users see at a glance which
95
+ * package raised the error. The bound `parse` bridges
96
+ * `@exortek/shared/validate` schemas to the same error class.
97
+ *
98
+ * **Path naming convention** (used as the `name` argument):
99
+ *
100
+ * `<publicFunction>[.options|.config][.<field>]`
101
+ *
102
+ * - `assertString(name, 'createUser.name')` — top-level arg
103
+ * - `assertPositiveInt(n, 'scrypt.options.r')` — nested option
104
+ * - `assertBytesOrString(pwd, 'pepper.wrap.password')` — method arg
105
+ *
106
+ * Keep the path short: the emitted error is `"<name> must be <desc>"`,
107
+ * so a stack-line grep already tells the caller which function fired.
108
+ * Reserve `hint` for actionable follow-ups ("pass the bytes returned by
109
+ * encryptSymmetric()"), not for restating the field.
110
+ */
111
+
112
+ /**
113
+ * @typedef {{ cause?: unknown }} WrapExtra
114
+ * Extra options forwarded to the wrap function, so `invalidArgument`
115
+ * sites that catch an underlying error can preserve the `cause` chain
116
+ * without falling back to a raw `new PackageError(...)`.
117
+ *
118
+ * @typedef {(message: string, extra?: WrapExtra) => Error} WrapFn
119
+ * Constructs (never throws) the binding package's error, e.g.
120
+ * `(m, { cause } = {}) => new CryptoError(ErrorCode.INVALID_ARGUMENT, m, { cause })`.
121
+ *
122
+ * @typedef {{ hint?: string }} AssertOptions
123
+ * `hint` is appended to the message after an em-dash — use it for
124
+ * actionable guidance ("pass the exact bytes returned by …").
125
+ *
126
+ * @typedef {{ safeParse: (input: unknown, path?: string) => { ok: true, value: unknown } | { ok: false, errors: string[] } }} ParseableSchema
127
+ */
128
+
129
+ /**
130
+ * Build the failure message. `description` completes the sentence
131
+ * `"<name> must be <description>"`; `hint` (optional) follows an
132
+ * em-dash.
133
+ *
134
+ * @param {string} name
135
+ * @param {string} description
136
+ * @param {string} [hint]
137
+ * @returns {string}
138
+ */
139
+ function message(name, description, hint) {
140
+ return `${name} must be ${description}${hint ? ` — ${hint}` : ''}`;
141
+ }
142
+
143
+ const ENCODINGS = new Set(['hex', 'base64', 'base64url']);
144
+
145
+ /**
146
+ * Bind the assert set to a package's error class. Call once per
147
+ * package (conventionally in `internal/guards.js`) and import the
148
+ * bound object everywhere:
149
+ *
150
+ * import { bindAsserts } from '@exortek/shared/asserts';
151
+ * import { CryptoError, ErrorCode } from '../errors.js';
152
+ * export const g = bindAsserts((m) => new CryptoError(ErrorCode.INVALID_ARGUMENT, m));
153
+ *
154
+ * // call sites:
155
+ * g.assertPositiveInt(options.iterations, 'options.iterations');
156
+ * const cfg = g.parse(OptionsSchema, options, 'options');
157
+ *
158
+ * @param {WrapFn} wrap
159
+ */
160
+ function bindAsserts(wrap) {
161
+ /**
162
+ * @param {string} name
163
+ * @param {string} description
164
+ * @param {AssertOptions} [opts]
165
+ * @returns {never}
166
+ */
167
+ function fail(name, description, opts) {
168
+ throw wrap(message(name, description, opts?.hint));
169
+ }
170
+
171
+ /**
172
+ * Assert that `value` is a plain object (not `null`, not an array,
173
+ * not a primitive).
174
+ * @param {unknown} value
175
+ * @param {string} name
176
+ * @param {AssertOptions} [opts]
177
+ */
178
+ function assertObject(value, name, opts) {
179
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
180
+ fail(name, 'an object', opts);
181
+ }
182
+ }
183
+
184
+ return {
185
+ /**
186
+ * Construct (not throw) the bound error with a free-form message —
187
+ * for `throw g.invalidArgument('…')` sites that don't fit the
188
+ * `X must be Y` shape (canonicalisation errors, cross-field
189
+ * constraint failures). Pass `{ cause }` when the argument-shape
190
+ * failure was triggered by an underlying throw whose chain matters
191
+ * (e.g. `JSON.stringify` on a bigint).
192
+ *
193
+ * @param {string} msg
194
+ * @param {WrapExtra} [extra]
195
+ * @returns {Error}
196
+ */
197
+ invalidArgument(msg, extra) {
198
+ return wrap(msg, extra);
199
+ },
200
+
201
+ /**
202
+ * Validate `input` against a `@exortek/shared/validate` schema;
203
+ * failures throw the bound error carrying every collected message.
204
+ * The bridge that keeps schema validation on the package's own
205
+ * error surface.
206
+ *
207
+ * @param {ParseableSchema} schema
208
+ * @param {unknown} input
209
+ * @param {string} [path='options']
210
+ * @returns {unknown} the parsed (possibly defaulted) value
211
+ */
212
+ parse(schema, input, path = 'options') {
213
+ const r = schema.safeParse(input, path);
214
+ if (!r.ok) {
215
+ throw wrap(r.errors.join('; '));
216
+ }
217
+ return r.value;
218
+ },
219
+
220
+ /**
221
+ * Assert that `value` is a non-negative safe integer (`0, 1, 2, …`).
222
+ * @param {unknown} value
223
+ * @param {string} name Argument name to include in the error message.
224
+ * @param {AssertOptions} [opts]
225
+ */
226
+ assertNonNegativeInt(value, name, opts) {
227
+ if (!Number.isSafeInteger(value) || /** @type {number} */ (value) < 0) {
228
+ fail(name, 'a non-negative safe integer', opts);
229
+ }
230
+ },
231
+
232
+ /**
233
+ * Assert that `value` is a strictly positive safe integer (`1, 2, 3, …`).
234
+ * @param {unknown} value
235
+ * @param {string} name
236
+ * @param {AssertOptions} [opts]
237
+ */
238
+ assertPositiveInt(value, name, opts) {
239
+ if (!Number.isSafeInteger(value) || /** @type {number} */ (value) <= 0) {
240
+ fail(name, 'a positive integer', opts);
241
+ }
242
+ },
243
+
244
+ /**
245
+ * Assert that `value` fits in a 48-bit unsigned integer (`0 … 2^48 − 1`).
246
+ * Used for Unix millisecond timestamps in UUID v7 / ULID.
247
+ * @param {unknown} value
248
+ * @param {string} name
249
+ * @param {AssertOptions} [opts]
250
+ */
251
+ assertUint48(value, name, opts) {
252
+ if (
253
+ !Number.isSafeInteger(value) ||
254
+ /** @type {number} */ (value) < 0 ||
255
+ /** @type {number} */ (value) > 0xffffffffffff
256
+ ) {
257
+ fail(name, 'a non-negative safe integer ≤ 2^48 − 1 (Unix ms since epoch)', opts);
258
+ }
259
+ },
260
+
261
+ /**
262
+ * Assert that `value` is a string (may be empty).
263
+ * @param {unknown} value
264
+ * @param {string} name
265
+ * @param {AssertOptions} [opts]
266
+ */
267
+ assertString(value, name, opts) {
268
+ if (typeof value !== 'string') {
269
+ fail(name, 'a string', opts);
270
+ }
271
+ },
272
+
273
+ /**
274
+ * Assert that `value` is a non-empty string.
275
+ * @param {unknown} value
276
+ * @param {string} name
277
+ * @param {AssertOptions} [opts]
278
+ */
279
+ assertNonEmptyString(value, name, opts) {
280
+ if (typeof value !== 'string' || value.length === 0) {
281
+ fail(name, 'a non-empty string', opts);
282
+ }
283
+ },
284
+
285
+ /**
286
+ * Assert that `value` is a boolean.
287
+ * @param {unknown} value
288
+ * @param {string} name
289
+ * @param {AssertOptions} [opts]
290
+ */
291
+ assertBoolean(value, name, opts) {
292
+ if (typeof value !== 'boolean') {
293
+ fail(name, 'a boolean', opts);
294
+ }
295
+ },
296
+
297
+ /**
298
+ * Assert that `value` is a function.
299
+ * @param {unknown} value
300
+ * @param {string} name
301
+ * @param {AssertOptions} [opts]
302
+ */
303
+ assertFunction(value, name, opts) {
304
+ if (typeof value !== 'function') {
305
+ fail(name, 'a function', opts);
306
+ }
307
+ },
308
+
309
+ assertObject,
310
+
311
+ /**
312
+ * Assert that `value` is either `undefined` or a plain object —
313
+ * the "optional options object" pattern.
314
+ * @param {unknown} value
315
+ * @param {string} name
316
+ * @param {AssertOptions} [opts]
317
+ */
318
+ assertOptionalObject(value, name, opts) {
319
+ if (value === undefined) {
320
+ return;
321
+ }
322
+ assertObject(value, name, opts);
323
+ },
324
+
325
+ /**
326
+ * Assert that `value` is a byte buffer (`Buffer` or `Uint8Array`) —
327
+ * strings are NOT accepted. For already-encoded material where a
328
+ * string would be ambiguous (ciphertext, signatures, raw key bytes).
329
+ * @param {unknown} value
330
+ * @param {string} name
331
+ * @param {AssertOptions} [opts]
332
+ */
333
+ assertBytes(value, name, opts) {
334
+ if (!Buffer.isBuffer(value) && !(value instanceof Uint8Array)) {
335
+ fail(name, 'a Buffer or Uint8Array', opts);
336
+ }
337
+ },
338
+
339
+ /**
340
+ * Assert that `value` is either a string or a byte buffer (`Buffer`
341
+ * or `Uint8Array`).
342
+ * @param {unknown} value
343
+ * @param {string} name
344
+ * @param {AssertOptions} [opts]
345
+ */
346
+ assertBytesOrString(value, name, opts) {
347
+ if (typeof value !== 'string' && !Buffer.isBuffer(value) && !(value instanceof Uint8Array)) {
348
+ fail(name, 'a string or Buffer', opts);
349
+ }
350
+ },
351
+
352
+ /**
353
+ * Assert that `encoding` is one of the accepted output/input
354
+ * encodings. Pass `allowBuffer: false` where a `Buffer` output makes
355
+ * no sense (verifying a string signature, decoding a token payload).
356
+ *
357
+ * @param {unknown} encoding
358
+ * @param {string} name
359
+ * @param {AssertOptions & { allowBuffer?: boolean }} [opts]
360
+ */
361
+ assertEncoding(encoding, name, opts) {
362
+ const allowBuffer = opts?.allowBuffer !== false;
363
+ const valid = (typeof encoding === 'string' && ENCODINGS.has(encoding)) || (allowBuffer && encoding === 'buffer');
364
+ if (!valid) {
365
+ const list = allowBuffer ? "'hex', 'base64', 'base64url', or 'buffer'" : "'hex', 'base64', or 'base64url'";
366
+ fail(name, list, opts);
367
+ }
368
+ },
369
+ };
370
+ }
371
+
372
+ /**
373
+ * One-line sugar over {@link bindAsserts} — the overwhelmingly common
374
+ * pattern where a package binds every argument-shape failure to its
375
+ * own error class + `INVALID_ARGUMENT` code. Emits the standard
376
+ * `new ErrorClass(code, message, { cause })` shape, so the underlying
377
+ * `BaseError` `{ cause, status, details }` options object is respected.
378
+ *
379
+ * // packages/<pkg>/src/internal/guards.js
380
+ * import { defineGuards } from '@exortek/shared/asserts';
381
+ * import { PasswordError, ErrorCode } from '../errors.js';
382
+ *
383
+ * export const { assertString, invalidArgument, parse } =
384
+ * defineGuards(PasswordError, ErrorCode.INVALID_ARGUMENT);
385
+ *
386
+ * Reach for the raw {@link bindAsserts} when you need a different
387
+ * mapping (an alt code, a decorated message) — it stays available.
388
+ *
389
+ * @param {new (code: string, message: string, options?: { cause?: unknown }) => Error} ErrorClass
390
+ * @param {string} code
391
+ */
392
+ function defineGuards(ErrorClass, code) {
393
+ return bindAsserts((message, extra) => new ErrorClass(code, message, extra));
394
+ }
395
+
396
+ /**
397
+ * Shared base error class — the single error structure behind every
398
+ * `@exortek/*` package's `errors.js`.
399
+ *
400
+ * Every package keeps its own class identity with a one-liner subclass;
401
+ * codes stay per-package frozen maps, status mapping is declared as a
402
+ * static field:
403
+ *
404
+ * import { BaseError } from '@exortek/shared/errors';
405
+ *
406
+ * export const ErrorCode = Object.freeze({
407
+ * INVALID_ARGUMENT: 'INVALID_ARGUMENT',
408
+ * INVALID_TOKEN: 'INVALID_TOKEN',
409
+ * });
410
+ *
411
+ * export class JwtError extends BaseError {
412
+ * static statuses = { INVALID_ARGUMENT: 400, INVALID_TOKEN: 401 };
413
+ * static defaultStatus = 500;
414
+ * }
415
+ *
416
+ * Instances carry a stable machine-readable `code` (branch on this,
417
+ * never on the message), an optional HTTP `status`, an optional
418
+ * `details` object, and the standard `cause` chain.
419
+ */
420
+ class BaseError extends Error {
421
+ /**
422
+ * Optional `code → HTTP status` map declared on the subclass. When
423
+ * absent the instance carries no `status` at all — for HTTP-agnostic
424
+ * packages like `@exortek/crypto`.
425
+ *
426
+ * @type {Record<string, number> | undefined}
427
+ */
428
+ static statuses = undefined;
429
+
430
+ /**
431
+ * Fallback status for codes missing from `statuses`.
432
+ *
433
+ * @type {number}
434
+ */
435
+ static defaultStatus = 500;
436
+
437
+ /**
438
+ * @param {string} code Stable machine-readable code; branch on this.
439
+ * @param {string} message Human-readable diagnostic. Free-form; may
440
+ * change across versions.
441
+ * @param {{ cause?: unknown, status?: number, details?: Record<string, unknown> }} [options]
442
+ */
443
+ constructor(code, message, options = {}) {
444
+ super(message, options.cause !== undefined ? { cause: options.cause } : undefined);
445
+ this.name = new.target.name;
446
+ /** @type {string} */
447
+ this.code = code;
448
+ const statuses = /** @type {typeof BaseError} */ (new.target).statuses;
449
+ if (options.status !== undefined) {
450
+ /** @type {number | undefined} */
451
+ this.status = options.status;
452
+ } else if (statuses !== undefined) {
453
+ // Object.hasOwn guards against inherited-property lookups for
454
+ // exotic code values ('toString', 'constructor', …).
455
+ this.status = Object.hasOwn(statuses, code)
456
+ ? statuses[code]
457
+ : /** @type {typeof BaseError} */ (new.target).defaultStatus;
458
+ }
459
+ if (options.details) {
460
+ /** @type {Record<string, unknown> | undefined} */
461
+ this.details = options.details;
462
+ }
463
+ }
464
+ }
465
+
466
+ /**
467
+ * Stable machine-readable codes for every programmer-error failure that
468
+ * `@exortek/apikey` can raise. Branch on `code`, never on the message.
469
+ * Note: expected verify failures (bad secret, expired, revoked,
470
+ * missing scope) are NOT thrown — `verifyApiKey` returns
471
+ * `{ valid: false, reason }` so a wrong or stale key is a normal auth
472
+ * outcome, not an exception. Errors below fire only when the caller
473
+ * configured something wrong or the store misbehaved.
474
+ */
475
+
476
+ const ErrorCode = Object.freeze({
477
+ INVALID_ARGUMENT: 'INVALID_ARGUMENT',
478
+ INVALID_PREFIX: 'INVALID_PREFIX',
479
+ INVALID_PEPPER: 'INVALID_PEPPER',
480
+ STORE_ERROR: 'STORE_ERROR',
481
+ });
482
+
483
+ /**
484
+ * Every recoverable failure raised by this package. Carries a stable
485
+ * `code` (from {@link ErrorCode}) and a `status` — the HTTP response
486
+ * status a middleware layer would use when translating the error.
487
+ */
488
+ class ApiKeyError extends BaseError {
489
+ static statuses = {
490
+ [ErrorCode.INVALID_ARGUMENT]: 400,
491
+ [ErrorCode.INVALID_PREFIX]: 400,
492
+ [ErrorCode.INVALID_PEPPER]: 400,
493
+ [ErrorCode.STORE_ERROR]: 500,
494
+ };
495
+ static defaultStatus = 500;
496
+ }
497
+
498
+ /**
499
+ * Argument guards bound to `ApiKeyError` — the package-wide binding of
500
+ * `@exortek/shared/asserts`. Import guards from here, never from the
501
+ * shared module directly.
502
+ */
503
+
504
+
505
+ const { invalidArgument} = defineGuards(
506
+ ApiKeyError,
507
+ ErrorCode.INVALID_ARGUMENT,
508
+ );
509
+
510
+ /**
511
+ * In-process memory store for API keys.
512
+ *
513
+ * Not cluster-safe — every worker has its own state. Use for dev,
514
+ * single-node deployments, and tests. For multi-worker production use
515
+ * {@link redisStore} or bring your own DB-backed implementation of
516
+ * `ApiKeyStore`.
517
+ *
518
+ * Backed by two Maps: one keyed by `id` (the primary lookup path),
519
+ * one keyed by `userId` holding a `Set<id>` reverse index for
520
+ * `listByUser` / `revokeAllForUser`. Both are pruned on write.
521
+ */
522
+
523
+
524
+ /**
525
+ * @returns {import('../index.js').ApiKeyStore & { _size: () => number }}
526
+ */
527
+ function memoryStore() {
528
+ /** @type {Map<string, import('../index.js').ApiKeyRecord>} */
529
+ const byId = new Map();
530
+ /** @type {Map<string, Set<string>>} */
531
+ const byUser = new Map();
532
+
533
+ function indexUser(uid, id) {
534
+ if (!isString(uid)) {
535
+ return;
536
+ }
537
+ let set = byUser.get(uid);
538
+ if (!set) {
539
+ set = new Set();
540
+ byUser.set(uid, set);
541
+ }
542
+ set.add(id);
543
+ }
544
+
545
+ function unindexUser(uid, id) {
546
+ if (!isString(uid)) {
547
+ return;
548
+ }
549
+ const set = byUser.get(uid);
550
+ if (!set) {
551
+ return;
552
+ }
553
+ set.delete(id);
554
+ if (set.size === 0) {
555
+ byUser.delete(uid);
556
+ }
557
+ }
558
+
559
+ return {
560
+ async put(record) {
561
+ if (!isObject(record) || !isString(record.id)) {
562
+ throw invalidArgument('memoryStore.put.record.id must be a string');
563
+ }
564
+ // Store a shallow copy so a caller mutating the record they
565
+ // passed in doesn't retroactively mutate what we've stored —
566
+ // matches the copy-on-read contract of getById / update.
567
+ byId.set(record.id, { ...record });
568
+ indexUser(record.userId, record.id);
569
+ },
570
+
571
+ async getById(id) {
572
+ const record = byId.get(id);
573
+ return record ? { ...record } : null;
574
+ },
575
+
576
+ async update(id, patch) {
577
+ const existing = byId.get(id);
578
+ if (!existing) {
579
+ return null;
580
+ }
581
+ const oldUserId = existing.userId;
582
+ const next = { ...existing, ...patch };
583
+ byId.set(id, next);
584
+ if (!isUndefined(patch.userId) && patch.userId !== oldUserId) {
585
+ unindexUser(oldUserId, id);
586
+ indexUser(next.userId, id);
587
+ }
588
+ return { ...next };
589
+ },
590
+
591
+ async revoke(id, reason) {
592
+ const existing = byId.get(id);
593
+ if (!existing || existing.revokedAt) {
594
+ return false;
595
+ }
596
+ existing.revokedAt = Date.now();
597
+ if (isString(reason)) {
598
+ existing.revokedReason = reason;
599
+ }
600
+ return true;
601
+ },
602
+
603
+ async revokeAllForUser(userId, reason) {
604
+ const set = byUser.get(userId);
605
+ if (!set) {
606
+ return 0;
607
+ }
608
+ const now = Date.now();
609
+ let count = 0;
610
+ for (const id of set) {
611
+ const record = byId.get(id);
612
+ if (record && !record.revokedAt) {
613
+ record.revokedAt = now;
614
+ if (isString(reason)) {
615
+ record.revokedReason = reason;
616
+ }
617
+ count += 1;
618
+ }
619
+ }
620
+ return count;
621
+ },
622
+
623
+ async listByUser(userId) {
624
+ const set = byUser.get(userId);
625
+ if (!set) {
626
+ return [];
627
+ }
628
+ const out = [];
629
+ for (const id of set) {
630
+ const record = byId.get(id);
631
+ if (record) {
632
+ out.push({ ...record });
633
+ }
634
+ }
635
+ return out;
636
+ },
637
+
638
+ _size: () => byId.size,
639
+ };
640
+ }
641
+
642
+ /**
643
+ * Duck-type guard for a Redis-compatible client. Every `@exortek/*`
644
+ * package that ships a Redis store (jwt blacklist, session store,
645
+ * security rate-limit) does the same "not null + required methods
646
+ * are functions" check up front so a missing dependency surfaces as
647
+ * a clean typed error instead of `TypeError: client.get is not a
648
+ * function` deep in a store operation.
649
+ *
650
+ * Callers pass their own `wrap` callback that throws their typed
651
+ * error class with the message — this file has no opinion on the
652
+ * error surface.
653
+ */
654
+
655
+ /**
656
+ * @param {unknown} client
657
+ * @param {readonly string[]} methods Method names that must be functions on the client.
658
+ * @param {(message: string) => never} wrap
659
+ * Called with a diagnostic message when the check fails; must throw.
660
+ * The caller's typed error class is emitted from inside this callback.
661
+ * @returns {void}
662
+ */
663
+ function assertRedisClient(client, methods, wrap) {
664
+ if (!client || typeof client !== 'object') {
665
+ wrap('client is required — pass a Redis-compatible instance (ioredis / node-redis / @upstash/redis)');
666
+ }
667
+ const c = /** @type {Record<string, unknown>} */ (client);
668
+ for (const method of methods) {
669
+ if (typeof c[method] !== 'function') {
670
+ wrap(`client is missing '${method}()' — is this a Redis-compatible client?`);
671
+ }
672
+ }
673
+ }
674
+
675
+ /**
676
+ * Redis-backed store for API keys.
677
+ *
678
+ * Layout:
679
+ *
680
+ * <keyPrefix><id> — JSON blob of the record (primary lookup)
681
+ * <keyPrefix>u:<userId> — SADD-set of the user's key ids
682
+ *
683
+ * Cluster-safe: state lives in Redis, so a key put on one worker is
684
+ * immediately visible to every other. Works with any client exposing
685
+ * `get / set / del / sadd / srem / smembers / mget` — verified against
686
+ * `ioredis`, `node-redis@4+`, and `@upstash/redis`.
687
+ *
688
+ * There is no TTL on the record — API keys are meant to be long-lived
689
+ * and their `expiresAt` field is authoritative. Revocation is a
690
+ * flip-in-place on the record itself, not a tombstone, since
691
+ * `verifyApiKey` re-reads the full record every time.
692
+ */
693
+
694
+
695
+ /**
696
+ * @typedef {object} RedisStoreOptions
697
+ * @property {string} [keyPrefix='apikey:']
698
+ */
699
+
700
+ /**
701
+ * @param {any} client
702
+ * @param {RedisStoreOptions} [options]
703
+ * @returns {import('../index.js').ApiKeyStore}
704
+ */
705
+ function redisStore(client, options = {}) {
706
+ assertRedisClient(client, ['get', 'set', 'del'], msg => {
707
+ throw invalidArgument(`redisStore.client: ${msg}`);
708
+ });
709
+ const keyPrefix = options.keyPrefix ?? 'apikey:';
710
+ const rk = id => `${keyPrefix}${id}`;
711
+ const uk = uid => `${keyPrefix}u:${uid}`;
712
+
713
+ async function readRecord(id) {
714
+ const raw = await client.get(rk(id));
715
+ if (!raw) {
716
+ return null;
717
+ }
718
+ try {
719
+ return isString(raw) ? JSON.parse(raw) : raw;
720
+ } catch {
721
+ return null;
722
+ }
723
+ }
724
+
725
+ async function writeRecord(record) {
726
+ await client.set(rk(record.id), JSON.stringify(record));
727
+ }
728
+
729
+ async function sadd(uid, id) {
730
+ if (isFunction(client.sadd)) {
731
+ return client.sadd(uk(uid), id);
732
+ }
733
+ if (isFunction(client.sAdd)) {
734
+ return client.sAdd(uk(uid), id);
735
+ }
736
+ return null;
737
+ }
738
+
739
+ async function srem(uid, id) {
740
+ if (isFunction(client.srem)) {
741
+ return client.srem(uk(uid), id);
742
+ }
743
+ if (isFunction(client.sRem)) {
744
+ return client.sRem(uk(uid), id);
745
+ }
746
+ return null;
747
+ }
748
+
749
+ async function smembers(uid) {
750
+ if (isFunction(client.smembers)) {
751
+ return client.smembers(uk(uid));
752
+ }
753
+ if (isFunction(client.sMembers)) {
754
+ return client.sMembers(uk(uid));
755
+ }
756
+ return [];
757
+ }
758
+
759
+ async function mget(keys) {
760
+ if (keys.length === 0) {
761
+ return [];
762
+ }
763
+ if (isFunction(client.mget)) {
764
+ return client.mget(...keys);
765
+ }
766
+ if (isFunction(client.mGet)) {
767
+ return client.mGet(keys);
768
+ }
769
+ return Promise.all(keys.map(k => client.get(k)));
770
+ }
771
+
772
+ return {
773
+ async put(record) {
774
+ if (!isObject(record) || !isString(record.id)) {
775
+ throw invalidArgument('redisStore.put.record.id must be a string');
776
+ }
777
+ await writeRecord(record);
778
+ if (record.userId) {
779
+ await sadd(record.userId, record.id);
780
+ }
781
+ },
782
+
783
+ async getById(id) {
784
+ return readRecord(id);
785
+ },
786
+
787
+ async update(id, patch) {
788
+ const existing = await readRecord(id);
789
+ if (!existing) {
790
+ return null;
791
+ }
792
+ const oldUserId = existing.userId;
793
+ const next = { ...existing, ...patch };
794
+ await writeRecord(next);
795
+ if (patch.userId !== undefined && patch.userId !== oldUserId) {
796
+ if (oldUserId) {
797
+ await srem(oldUserId, id);
798
+ }
799
+ if (next.userId) {
800
+ await sadd(next.userId, id);
801
+ }
802
+ }
803
+ return next;
804
+ },
805
+
806
+ async revoke(id, reason) {
807
+ const existing = await readRecord(id);
808
+ if (!existing || existing.revokedAt) {
809
+ return false;
810
+ }
811
+ existing.revokedAt = Date.now();
812
+ if (isString(reason)) {
813
+ existing.revokedReason = reason;
814
+ }
815
+ await writeRecord(existing);
816
+ return true;
817
+ },
818
+
819
+ async revokeAllForUser(userId, reason) {
820
+ const ids = await smembers(userId);
821
+ if (!ids || ids.length === 0) {
822
+ return 0;
823
+ }
824
+ const rows = await mget(ids.map(rk));
825
+ let count = 0;
826
+ const writes = [];
827
+ for (let i = 0; i < ids.length; i++) {
828
+ const raw = rows[i];
829
+ if (!raw) {
830
+ continue;
831
+ }
832
+ let record;
833
+ try {
834
+ record = isString(raw) ? JSON.parse(raw) : raw;
835
+ } catch {
836
+ continue;
837
+ }
838
+ if (record.revokedAt) {
839
+ continue;
840
+ }
841
+ record.revokedAt = Date.now();
842
+ if (isString(reason)) {
843
+ record.revokedReason = reason;
844
+ }
845
+ writes.push(writeRecord(record));
846
+ count += 1;
847
+ }
848
+ await Promise.all(writes);
849
+ return count;
850
+ },
851
+
852
+ async listByUser(userId) {
853
+ const ids = await smembers(userId);
854
+ if (!ids || ids.length === 0) {
855
+ return [];
856
+ }
857
+ const rows = await mget(ids.map(rk));
858
+ const out = [];
859
+ for (let i = 0; i < ids.length; i++) {
860
+ const raw = rows[i];
861
+ if (!raw) {
862
+ // Dead index reference — prune.
863
+ await srem(userId, ids[i]);
864
+ continue;
865
+ }
866
+ try {
867
+ out.push(isString(raw) ? JSON.parse(raw) : raw);
868
+ } catch {
869
+ // Skip corrupt row.
870
+ }
871
+ }
872
+ return out;
873
+ },
874
+ };
875
+ }
876
+
877
+ export { memoryStore, redisStore };