@aooth/auth 0.1.85 → 0.2.1

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.
Files changed (35) hide show
  1. package/dist/atscript-db.cjs +80 -4
  2. package/dist/atscript-db.d.cts +51 -10
  3. package/dist/atscript-db.d.mts +51 -10
  4. package/dist/atscript-db.mjs +79 -5
  5. package/dist/{auth-credential-CLAQgjCS.d.mts → auth-credential-CjCgZv7n.d.mts} +106 -9
  6. package/dist/{auth-credential-GRAK230V.d.cts → auth-credential-UV3sJ-lt.d.cts} +106 -9
  7. package/dist/authz.d.cts +2 -2
  8. package/dist/authz.d.mts +2 -2
  9. package/dist/client.cjs +25 -12
  10. package/dist/client.d.cts +59 -13
  11. package/dist/client.d.mts +59 -13
  12. package/dist/client.mjs +25 -12
  13. package/dist/{clock-CyjqzLxc.d.cts → clock-CzAaCoZ5.d.cts} +7 -0
  14. package/dist/{clock-CyjqzLxc.d.mts → clock-CzAaCoZ5.d.mts} +7 -0
  15. package/dist/{dynamic-client-store-BF4nXMK2.d.mts → dynamic-client-store-B7EnHuRp.d.cts} +2 -2
  16. package/dist/{dynamic-client-store-HLfcl2FJ.d.cts → dynamic-client-store-BifZLGkT.d.mts} +2 -2
  17. package/dist/index.cjs +351 -128
  18. package/dist/index.d.cts +26 -4
  19. package/dist/index.d.mts +26 -4
  20. package/dist/index.mjs +328 -106
  21. package/dist/{payload-HPgyPiek.cjs → payload-C1cQW7p_.cjs} +27 -0
  22. package/dist/{payload-DP5zRiXT.mjs → payload-DDlf38B-.mjs} +22 -1
  23. package/dist/redis.cjs +18 -6
  24. package/dist/redis.d.cts +19 -4
  25. package/dist/redis.d.mts +19 -4
  26. package/dist/redis.mjs +18 -6
  27. package/dist/store-BaFYDHxn.d.cts +69 -0
  28. package/dist/store-h-bLOAaS.d.mts +69 -0
  29. package/package.json +9 -9
  30. package/src/atscript-db/auth-code.as.d.ts +1 -1
  31. package/src/atscript-db/auth-credential.as.d.ts +1 -1
  32. package/src/atscript-db/dynamic-client.as.d.ts +1 -1
  33. package/src/atscript-db/pending-authorization.as.d.ts +1 -1
  34. package/dist/store-CVD1nd2j.d.mts +0 -41
  35. package/dist/store-ClQnA8yh.d.cts +0 -41
package/dist/index.cjs CHANGED
@@ -1,30 +1,9 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_payload = require("./payload-C1cQW7p_.cjs");
2
3
  const require_clock = require("./clock-Bl-H3eqE.cjs");
3
- const require_payload = require("./payload-HPgyPiek.cjs");
4
4
  const require_opaque_token = require("./opaque-token-CaZgD2i6.cjs");
5
5
  let node_crypto = require("node:crypto");
6
6
  let jose = require("jose");
7
- //#region src/errors.ts
8
- const defaultMessages = {
9
- INVALID_TOKEN: "Invalid token",
10
- TOKEN_EXPIRED: "Token has expired",
11
- TOKEN_REVOKED: "Token has been revoked",
12
- REFRESH_REUSE_DETECTED: "Refresh token reuse detected",
13
- STATELESS_OPERATION_UNSUPPORTED: "Operation is not supported by stateless credential store",
14
- MAX_CONCURRENT_REACHED: "Maximum concurrent credentials reached for user",
15
- INVALID_CONFIG: "Invalid auth configuration"
16
- };
17
- var AuthError = class extends Error {
18
- type;
19
- details;
20
- name = "AuthError";
21
- constructor(type, message, details) {
22
- super(message ?? defaultMessages[type]);
23
- this.type = type;
24
- this.details = details;
25
- }
26
- };
27
- //#endregion
28
7
  //#region src/stores/memory.ts
29
8
  /**
30
9
  * In-memory implementation of CredentialStore using random opaque token IDs.
@@ -43,11 +22,14 @@ var CredentialStoreMemory = class {
43
22
  }
44
23
  async persist(state, ttl) {
45
24
  const token = (0, node_crypto.randomUUID)();
25
+ await this.persistAs(token, state, ttl);
26
+ return token;
27
+ }
28
+ async persistAs(id, state, ttl) {
46
29
  const stored = { ...state };
47
30
  if (typeof ttl === "number") stored.expiresAt = this.clock.now() + ttl;
48
- this.states.set(token, stored);
49
- this.indexAdd(stored.userId, token);
50
- return token;
31
+ this.states.set(id, stored);
32
+ this.indexAdd(stored.userId, id);
51
33
  }
52
34
  async retrieve(token) {
53
35
  const state = this.states.get(token);
@@ -239,12 +221,12 @@ var CredentialStoreJwt = class {
239
221
  this.denylist = opts.denylist;
240
222
  this.clock = opts.clock ?? require_clock.defaultClock;
241
223
  if (HS_ALGS.has(this.algorithm)) {
242
- if (opts.secret == null) throw new AuthError("INVALID_CONFIG", `Algorithm ${this.algorithm} requires a 'secret' option`);
224
+ if (opts.secret == null) throw new require_payload.AuthError("INVALID_CONFIG", `Algorithm ${this.algorithm} requires a 'secret' option`);
243
225
  const key = normalizeSecret(opts.secret);
244
226
  this.signingKey = key;
245
227
  this.verifyingKey = key;
246
228
  } else {
247
- if (opts.privateKey == null || opts.publicKey == null) throw new AuthError("INVALID_CONFIG", `Algorithm ${this.algorithm} requires both 'privateKey' and 'publicKey' options`);
229
+ if (opts.privateKey == null || opts.publicKey == null) throw new require_payload.AuthError("INVALID_CONFIG", `Algorithm ${this.algorithm} requires both 'privateKey' and 'publicKey' options`);
248
230
  this.signingKey = opts.privateKey;
249
231
  this.verifyingKey = opts.publicKey;
250
232
  }
@@ -307,10 +289,10 @@ var CredentialStoreJwt = class {
307
289
  }
308
290
  deriveSubkey(label) {
309
291
  if (this.signingKey instanceof Uint8Array) return hkdfSubkey(this.signingKey, label);
310
- throw new AuthError("INVALID_CONFIG", "deriveSubkey requires a symmetric (HS*) secret; this JWT store uses an asymmetric key — provide an explicit wfStateSecret");
292
+ throw new require_payload.AuthError("INVALID_CONFIG", "deriveSubkey requires a symmetric (HS*) secret; this JWT store uses an asymmetric key — provide an explicit wfStateSecret");
311
293
  }
312
294
  requireDenylist(op) {
313
- if (!this.denylist) throw new AuthError("STATELESS_OPERATION_UNSUPPORTED", `${op} requires a denylist on stateless JWT store`);
295
+ if (!this.denylist) throw new require_payload.AuthError("STATELESS_OPERATION_UNSUPPORTED", `${op} requires a denylist on stateless JWT store`);
314
296
  return this.denylist;
315
297
  }
316
298
  /** Convert payload `exp` (seconds) to ms; fall back to a 60s window. */
@@ -423,7 +405,7 @@ var CredentialStoreEncapsulated = class {
423
405
  */
424
406
  epochs = /* @__PURE__ */ new Map();
425
407
  constructor(opts) {
426
- if (opts.secret == null) throw new AuthError("INVALID_CONFIG", "CredentialStoreEncapsulated requires a 'secret'");
408
+ if (opts.secret == null) throw new require_payload.AuthError("INVALID_CONFIG", "CredentialStoreEncapsulated requires a 'secret'");
427
409
  this.key = deriveKey(opts.secret);
428
410
  this.denylist = opts.denylist;
429
411
  this.clock = opts.clock ?? require_clock.defaultClock;
@@ -495,7 +477,7 @@ var CredentialStoreEncapsulated = class {
495
477
  return payload.issuedAt >= epoch;
496
478
  }
497
479
  requireDenylist(op) {
498
- if (!this.denylist) throw new AuthError("STATELESS_OPERATION_UNSUPPORTED", `${op} requires a denylist on stateless encapsulated store`);
480
+ if (!this.denylist) throw new require_payload.AuthError("STATELESS_OPERATION_UNSUPPORTED", `${op} requires a denylist on stateless encapsulated store`);
499
481
  return this.denylist;
500
482
  }
501
483
  decrypt(token) {
@@ -533,6 +515,14 @@ function stripJti(payload) {
533
515
  const DEFAULT_ACCESS_TTL = 3600 * 1e3;
534
516
  const DEFAULT_ROTATION_GRACE_MS = 3e4;
535
517
  /**
518
+ * Upper bound on list-then-delete passes in one revocation. Two is the norm;
519
+ * more only while refreshes keep minting off the session being revoked.
520
+ */
521
+ const MAX_REVOKE_PASSES = 8;
522
+ function revocationDidNotConverge() {
523
+ return /* @__PURE__ */ new Error(`aooth: revocation did not converge after ${MAX_REVOKE_PASSES} passes (refreshes kept minting); retry it`);
524
+ }
525
+ /**
536
526
  * Stable, non-reversible fingerprint of a token used as `credentialId` in
537
527
  * {@link AuthContext}. Hashing avoids leaking a live bearer token whenever
538
528
  * downstream consumers log or persist `ctx.credentialId`.
@@ -557,6 +547,34 @@ function lazyCredentialId(ctx, token) {
557
547
  }
558
548
  /** Smallest map size an amortized expiry sweep runs at. */
559
549
  const MIN_SWEEP_SIZE$1 = 1024;
550
+ /** A store key that is the SHA-256 hex of a token (`tokens.hashAtRest`). */
551
+ const HASHED_KEY = /^[0-9a-f]{64}$/i;
552
+ /** The token shape the bundled stores minted before `hashAtRest` (`randomUUID`). */
553
+ const UUID_TOKEN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
554
+ /** Prefix of a successor token encrypted at rest (`tokens.hashAtRest`). */
555
+ const SEALED_PREFIX = "enc1.";
556
+ /** AES-256-GCM key for the successor pair, derived from the presented (old) refresh token. */
557
+ function successorKey(oldRefreshToken) {
558
+ return Buffer.from((0, node_crypto.hkdfSync)("sha256", oldRefreshToken, "", "aooth-refresh-successor", 32));
559
+ }
560
+ function sealToken(key, token) {
561
+ const iv = (0, node_crypto.randomBytes)(12);
562
+ const cipher = (0, node_crypto.createCipheriv)("aes-256-gcm", key, iv);
563
+ const body = Buffer.concat([cipher.update(token, "utf8"), cipher.final()]);
564
+ return `${SEALED_PREFIX}${iv.toString("base64url")}.${body.toString("base64url")}.${cipher.getAuthTag().toString("base64url")}`;
565
+ }
566
+ /** Decrypt a sealed token; a plain (legacy) value passes through; `null` on a failed decrypt. */
567
+ function openToken(key, value) {
568
+ if (!value.startsWith(SEALED_PREFIX)) return value;
569
+ const [iv, body, tag] = value.slice(5).split(".");
570
+ try {
571
+ const decipher = (0, node_crypto.createDecipheriv)("aes-256-gcm", key, Buffer.from(iv, "base64url"));
572
+ decipher.setAuthTag(Buffer.from(tag, "base64url"));
573
+ return Buffer.concat([decipher.update(Buffer.from(body, "base64url")), decipher.final()]).toString("utf8");
574
+ } catch {
575
+ return null;
576
+ }
577
+ }
560
578
  /**
561
579
  * The opt-in `validateCache`: token → validated state for `ttlMs`, bounded
562
580
  * (oldest dropped first). `epoch` moves on every eviction so a validation
@@ -660,8 +678,11 @@ var AuthCredential = class {
660
678
  consumedRefreshes = /* @__PURE__ */ new Map();
661
679
  /** Map size at which `consumedRefreshes` next sweeps its expired entries. */
662
680
  consumedSweepAt = MIN_SWEEP_SIZE$1;
663
- /** Opt-in validated-state cache (`validateCache`). */
681
+ /** Opt-in validated-state cache (`validateCache`), keyed by store key. */
664
682
  validated;
683
+ hashAtRest;
684
+ generateToken;
685
+ isLegacyToken;
665
686
  constructor(opts) {
666
687
  this.store = opts.store;
667
688
  this.method = opts.method ?? "token";
@@ -672,14 +693,18 @@ var AuthCredential = class {
672
693
  this.onLimit = opts.onLimit ?? "reject";
673
694
  this.trackLastSeen = opts.trackLastSeen ?? false;
674
695
  this.clock = opts.clock ?? require_clock.defaultClock;
696
+ this.hashAtRest = opts.tokens?.hashAtRest ?? false;
697
+ this.generateToken = opts.tokens?.generate;
698
+ this.isLegacyToken = opts.tokens?.isLegacyToken ?? ((token) => UUID_TOKEN.test(token));
699
+ if ((this.hashAtRest || this.generateToken) && !this.store.persistAs) throw new require_payload.AuthError("INVALID_CONFIG", "tokens.hashAtRest / tokens.generate need a store that implements persistAs (memory, Redis, atscript-db)");
675
700
  if (opts.validateCache) {
676
- if (!(opts.validateCache.ttlMs > 0)) throw new AuthError("INVALID_CONFIG", `validateCache.ttlMs must be > 0 (got ${opts.validateCache.ttlMs})`);
701
+ if (!(opts.validateCache.ttlMs > 0)) throw new require_payload.AuthError("INVALID_CONFIG", `validateCache.ttlMs must be > 0 (got ${opts.validateCache.ttlMs})`);
677
702
  this.validated = new ValidateCache(opts.validateCache.ttlMs, opts.validateCache.max ?? 1e4);
678
703
  }
679
- if (this.accessTtl <= 0) throw new AuthError("INVALID_CONFIG", `accessTtl must be > 0 (got ${this.accessTtl})`);
680
- if (this.refreshConfig && this.refreshConfig.ttl <= 0) throw new AuthError("INVALID_CONFIG", `refresh.ttl must be > 0 (got ${this.refreshConfig.ttl})`);
704
+ if (this.accessTtl <= 0) throw new require_payload.AuthError("INVALID_CONFIG", `accessTtl must be > 0 (got ${this.accessTtl})`);
705
+ if (this.refreshConfig && this.refreshConfig.ttl <= 0) throw new require_payload.AuthError("INVALID_CONFIG", `refresh.ttl must be > 0 (got ${this.refreshConfig.ttl})`);
681
706
  const graceMs = this.refreshConfig?.rotationGraceMs;
682
- if (graceMs !== void 0 && graceMs < 0) throw new AuthError("INVALID_CONFIG", `refresh.rotationGraceMs must be >= 0 (got ${graceMs})`);
707
+ if (graceMs !== void 0 && graceMs < 0) throw new require_payload.AuthError("INVALID_CONFIG", `refresh.rotationGraceMs must be >= 0 (got ${graceMs})`);
683
708
  }
684
709
  async issue(userId, options) {
685
710
  if (this.maxConcurrent !== void 0 && this.store.listForUser) await this.enforceConcurrencyLimit(userId);
@@ -689,9 +714,9 @@ var AuthCredential = class {
689
714
  if (refresh === void 0) refreshTtl = this.refreshConfig?.ttl;
690
715
  else if (refresh !== false) {
691
716
  refreshTtl = refresh.ttl ?? this.refreshConfig?.ttl;
692
- if (refreshTtl === void 0) throw new AuthError("INVALID_CONFIG", "issue: per-mint refresh needs a ttl when no instance refresh config exists");
693
- if (refreshTtl <= 0) throw new AuthError("INVALID_CONFIG", `issue: refresh.ttl must be > 0 (got ${refreshTtl})`);
694
- if (refresh.graceMs !== void 0 && refresh.graceMs < 0) throw new AuthError("INVALID_CONFIG", `issue: refresh.graceMs must be >= 0 (got ${refresh.graceMs})`);
717
+ if (refreshTtl === void 0) throw new require_payload.AuthError("INVALID_CONFIG", "issue: per-mint refresh needs a ttl when no instance refresh config exists");
718
+ if (refreshTtl <= 0) throw new require_payload.AuthError("INVALID_CONFIG", `issue: refresh.ttl must be > 0 (got ${refreshTtl})`);
719
+ if (refresh.graceMs !== void 0 && refresh.graceMs < 0) throw new require_payload.AuthError("INVALID_CONFIG", `issue: refresh.graceMs must be >= 0 (got ${refresh.graceMs})`);
695
720
  }
696
721
  const perMintRefresh = refresh !== void 0 && refresh !== false;
697
722
  const stampAccessTtl = refreshTtl !== void 0 && ttl !== void 0;
@@ -702,8 +727,8 @@ var AuthCredential = class {
702
727
  ...perMintRefresh && { refreshRotation: "always" },
703
728
  ...perMintRefresh && refresh.graceMs !== void 0 && { rotationGraceMs: refresh.graceMs }
704
729
  } : metadata;
705
- if (ttl !== void 0 && expiresAt !== void 0) throw new AuthError("INVALID_CONFIG", "issue: pass either `ttl` or `expiresAt`, not both");
706
- if (ttl !== void 0 && ttl <= 0) throw new AuthError("INVALID_CONFIG", `issue: ttl must be > 0 (got ${ttl})`);
730
+ if (ttl !== void 0 && expiresAt !== void 0) throw new require_payload.AuthError("INVALID_CONFIG", "issue: pass either `ttl` or `expiresAt`, not both");
731
+ if (ttl !== void 0 && ttl <= 0) throw new require_payload.AuthError("INVALID_CONFIG", `issue: ttl must be > 0 (got ${ttl})`);
707
732
  const accessExpiresAt = expiresAt ?? now + (ttl ?? this.accessTtl);
708
733
  const accessStoreTtl = accessExpiresAt - now;
709
734
  const sessionId = providedSessionId ?? (0, node_crypto.randomUUID)();
@@ -715,7 +740,7 @@ var AuthCredential = class {
715
740
  metadata: effectiveMetadata,
716
741
  sessionId
717
742
  });
718
- const accessToken = await this.store.persist(accessState, accessStoreTtl);
743
+ const accessToken = await this.put(accessState, accessStoreTtl);
719
744
  let refreshToken;
720
745
  let refreshExpiresAt;
721
746
  if (refreshTtl !== void 0) {
@@ -727,7 +752,7 @@ var AuthCredential = class {
727
752
  metadata: effectiveMetadata,
728
753
  sessionId
729
754
  });
730
- refreshToken = await this.store.persist(refreshState, refreshTtl);
755
+ refreshToken = await this.put(refreshState, refreshTtl);
731
756
  refreshExpiresAt = now + refreshTtl;
732
757
  }
733
758
  return {
@@ -738,63 +763,108 @@ var AuthCredential = class {
738
763
  };
739
764
  }
740
765
  async validate(accessToken) {
741
- let state = this.validated?.get(accessToken, this.clock.now());
766
+ let key = this.keyOf(accessToken);
767
+ let state = this.validated?.get(key, this.clock.now());
742
768
  let fresh = false;
743
769
  if (!state) {
744
770
  fresh = true;
745
771
  const epoch = this.validated?.epoch;
746
- state = await this.retrieveUnlessDenied(accessToken);
747
- if (!state) return null;
772
+ const found = await this.retrieveUnlessDenied(accessToken, key);
773
+ if (!found) return null;
774
+ ({key, state} = found);
748
775
  if (state.expiresAt <= this.clock.now()) return null;
749
776
  if (state.kind === "refresh") return null;
750
- if (this.validated && this.validated.epoch === epoch) this.validated.set(accessToken, state, this.clock.now());
777
+ if (this.validated && this.validated.epoch === epoch) this.validated.set(key, state, this.clock.now());
751
778
  } else if (state.expiresAt <= this.clock.now()) {
752
- this.validated.delete(accessToken);
779
+ this.validated.delete(key);
753
780
  return null;
754
781
  }
755
- if (this.trackLastSeen === "validate" && this.store.touch) await this.store.touch(accessToken, this.clock.now(), fresh ? state : void 0);
782
+ if (this.trackLastSeen === "validate" && this.store.touch) await this.store.touch(key, this.clock.now(), fresh ? state : void 0);
756
783
  const ctx = {
757
784
  ...require_payload.credentialPayloadOf(state),
758
785
  userId: state.userId,
759
786
  method: this.method,
760
787
  credentialId: "",
761
- sessionId: this.sessionIdOf(state.sessionId, accessToken),
788
+ sessionId: state.sessionId ?? this.fingerprintOfKey(key),
762
789
  expiresAt: state.expiresAt
763
790
  };
764
- lazyCredentialId(ctx, accessToken);
791
+ if (key !== accessToken) ctx.credentialId = key;
792
+ else lazyCredentialId(ctx, accessToken);
765
793
  return ctx;
766
794
  }
767
795
  /**
768
796
  * The stored state of `accessToken` unless the orchestrator's denylist has
769
797
  * it — both looked up concurrently (one round trip on remote stores).
770
798
  */
771
- async retrieveUnlessDenied(accessToken) {
772
- const retrieving = this.store.retrieve(accessToken);
799
+ async retrieveUnlessDenied(accessToken, key) {
800
+ const retrieving = this.find(accessToken, key);
773
801
  if (!this.denylist) return await retrieving;
774
802
  retrieving.catch(() => {});
775
803
  if (await this.denylist.has(accessToken)) return null;
776
804
  return await retrieving;
777
805
  }
806
+ /** The store key a token's row lives under: its SHA-256 when hashing, else the token. */
807
+ keyOf(token) {
808
+ return this.hashAtRest ? fingerprint(token) : token;
809
+ }
810
+ /** `credentialId` (the token's SHA-256) of a stored row, from its store key. */
811
+ fingerprintOfKey(key) {
812
+ return this.hashAtRest && HASHED_KEY.test(key) ? key : fingerprint(key);
813
+ }
814
+ /** Persist a new credential; returns the token the client will hold. */
815
+ async put(state, ttl) {
816
+ if (!this.hashAtRest && !this.generateToken) return await this.store.persist(state, ttl);
817
+ const token = this.generateToken?.() ?? (0, node_crypto.randomBytes)(32).toString("base64url");
818
+ await this.store.persistAs(this.keyOf(token), state, ttl);
819
+ return token;
820
+ }
821
+ /**
822
+ * Look a token up: by its store key, and — under `hashAtRest: 'migrate'` —
823
+ * by the token itself for a row written before hashing was enabled.
824
+ */
825
+ async find(token, key = this.keyOf(token)) {
826
+ const state = await this.store.retrieve(key);
827
+ if (state) return {
828
+ key,
829
+ state
830
+ };
831
+ if (!this.mayBeLegacyKey(token)) return null;
832
+ const legacy = await this.store.retrieve(token);
833
+ return legacy ? {
834
+ key: token,
835
+ state: legacy
836
+ } : null;
837
+ }
838
+ /**
839
+ * `'migrate'`: may `token` be a row written before hashing, stored under
840
+ * the token itself? Never for a hash-shaped value — that is what a database
841
+ * read yields, and accepting it would turn a leaked row key into a session.
842
+ */
843
+ mayBeLegacyKey(token) {
844
+ return this.hashAtRest === "migrate" && !HASHED_KEY.test(token) && !/\s/.test(token) && this.isLegacyToken(token);
845
+ }
778
846
  async refresh(refreshToken, opts) {
779
847
  const now = this.clock.now();
780
- const oldState = await this.store.retrieve(refreshToken);
781
- if (!oldState) {
848
+ const found = await this.find(refreshToken);
849
+ const oldState = found?.state;
850
+ if (!found || !oldState) {
782
851
  const consumed = this.lookupConsumedRefresh(refreshToken);
783
852
  if (consumed) await this.fireRefreshReuseTheftResponse(consumed, refreshToken);
784
- throw new AuthError("INVALID_TOKEN");
853
+ throw new require_payload.AuthError("INVALID_TOKEN");
785
854
  }
786
- if (oldState.kind !== "refresh") throw new AuthError("INVALID_TOKEN", "Token is not a refresh credential");
855
+ if (oldState.kind !== "refresh") throw new require_payload.AuthError("INVALID_TOKEN", "Token is not a refresh credential");
787
856
  await opts?.guard?.(oldState);
788
857
  const rotation = oldState.metadata?.refreshRotation ?? (this.refreshConfig ? this.refreshConfig.rotation ?? "sliding" : "always");
789
858
  switch (rotation) {
790
- case "none": return await this.refreshNone(oldState, refreshToken, now);
791
- case "always": return await this.refreshAlways(oldState, refreshToken, now);
792
- case "sliding": return await this.refreshSliding(oldState, refreshToken, now);
793
- default: throw new AuthError("INVALID_CONFIG", `Unknown rotation: ${String(rotation)}`);
859
+ case "none": return await this.refreshNone(oldState, refreshToken, found.key, now);
860
+ case "always": return await this.refreshAlways(oldState, refreshToken, found.key, now);
861
+ case "sliding": return await this.refreshSliding(oldState, refreshToken, found.key, now);
862
+ default: throw new require_payload.AuthError("INVALID_CONFIG", `Unknown rotation: ${String(rotation)}`);
794
863
  }
795
864
  }
796
- async refreshNone(oldState, refreshToken, now) {
865
+ async refreshNone(oldState, refreshToken, key, now) {
797
866
  const newAccess = await this.issueAccessFromRefresh(oldState, now);
867
+ await this.assertStillLive(key, [newAccess.token]);
798
868
  return {
799
869
  accessToken: newAccess.token,
800
870
  accessExpiresAt: newAccess.expiresAt,
@@ -808,8 +878,8 @@ var AuthCredential = class {
808
878
  * forward (rolling session). Grace-tolerant via the shared store-backed
809
879
  * window.
810
880
  */
811
- async refreshSliding(oldState, refreshToken, now) {
812
- return await this.rotateWithGrace(oldState, refreshToken, now, false);
881
+ async refreshSliding(oldState, refreshToken, key, now) {
882
+ return await this.rotateWithGrace(oldState, refreshToken, key, now, false);
813
883
  }
814
884
  /**
815
885
  * `always` rotation: rotate on every use but keep a FIXED session ceiling —
@@ -821,9 +891,9 @@ var AuthCredential = class {
821
891
  * kept valid (`update` re-issues), so it falls back to single-use semantics
822
892
  * with a process-local reuse signal — the only mechanism possible there.
823
893
  */
824
- async refreshAlways(oldState, refreshToken, now) {
894
+ async refreshAlways(oldState, refreshToken, key, now) {
825
895
  if (!this.store.listForUser) {
826
- await this.store.consume(refreshToken);
896
+ await this.store.consume(key);
827
897
  this.sweepConsumedRefreshes();
828
898
  this.consumedRefreshes.set(refreshToken, {
829
899
  userId: oldState.userId,
@@ -831,9 +901,9 @@ var AuthCredential = class {
831
901
  exp: oldState.expiresAt,
832
902
  ...oldState.sessionId !== void 0 && { sessionId: oldState.sessionId }
833
903
  });
834
- return await this.issueRotatedPair(oldState, refreshToken, false, now, true);
904
+ return await this.issueRotatedPair(oldState, refreshToken, key, false, now, true);
835
905
  }
836
- return await this.rotateWithGrace(oldState, refreshToken, now, true);
906
+ return await this.rotateWithGrace(oldState, refreshToken, key, now, true);
837
907
  }
838
908
  /**
839
909
  * Shared rotation-with-grace mechanism for `sliding` and `always` on stateful
@@ -850,9 +920,9 @@ var AuthCredential = class {
850
920
  * mint-time `metadata.rotationGraceMs` (when stamped) wins over the instance
851
921
  * window, and a window of `0` is strict single-use.
852
922
  */
853
- async rotateWithGrace(oldState, refreshToken, now, preserveExpiry) {
923
+ async rotateWithGrace(oldState, refreshToken, key, now, preserveExpiry) {
854
924
  const graceMs = oldState.metadata?.rotationGraceMs ?? this.refreshConfig?.rotationGraceMs ?? DEFAULT_ROTATION_GRACE_MS;
855
- if (typeof oldState.rotatedAt !== "number") return await this.issueRotatedPair(oldState, refreshToken, true, now, preserveExpiry);
925
+ if (typeof oldState.rotatedAt !== "number") return await this.issueRotatedPair(oldState, refreshToken, key, true, now, preserveExpiry);
856
926
  const reuse = {
857
927
  userId: oldState.userId,
858
928
  sessionId: oldState.sessionId,
@@ -861,8 +931,8 @@ var AuthCredential = class {
861
931
  rotatedAt: oldState.rotatedAt
862
932
  };
863
933
  if (graceMs <= 0 || now - oldState.rotatedAt > graceMs) return await this.respondToRefreshReuse(reuse);
864
- const successor = oldState.successor;
865
- const successorState = successor === void 0 ? null : await this.store.retrieve(successor.refreshToken);
934
+ const successor = oldState.successor === void 0 ? void 0 : this.openSuccessor(oldState.successor, refreshToken);
935
+ const successorState = successor === void 0 ? null : (await this.find(successor.refreshToken))?.state ?? null;
866
936
  if (successor === void 0 || successorState === null || typeof successorState.rotatedAt === "number") return await this.respondToRefreshReuse(reuse);
867
937
  this.refreshConfig?.onRotationGraceHit?.({
868
938
  userId: oldState.userId,
@@ -881,17 +951,29 @@ var AuthCredential = class {
881
951
  };
882
952
  }
883
953
  async revoke(token) {
884
- this.validated?.delete(token);
954
+ await this.revokeKey(this.keyOf(token));
955
+ if (this.mayBeLegacyKey(token)) await this.revokeKey(token);
956
+ }
957
+ /** Revoke the row stored under `key` (a store key, as `listForUser` returns it). */
958
+ async revokeKey(key) {
959
+ this.validated?.delete(key);
885
960
  try {
886
- await this.store.revoke(token);
961
+ await this.store.revoke(key);
887
962
  } finally {
888
- this.validated?.delete(token);
963
+ this.validated?.delete(key);
889
964
  }
890
965
  }
891
966
  async revokeAllForUser(userId) {
892
967
  this.validated?.deleteUser(userId);
893
968
  try {
894
- return await this.store.revokeAllForUser(userId);
969
+ const listForUser = this.store.listForUser?.bind(this.store);
970
+ let revoked = await this.store.revokeAllForUser(userId);
971
+ if (!listForUser) return revoked;
972
+ for (let pass = 1; (await listForUser(userId)).length > 0; pass++) {
973
+ revoked += await this.store.revokeAllForUser(userId);
974
+ if (pass >= MAX_REVOKE_PASSES) throw revocationDidNotConverge();
975
+ }
976
+ return revoked;
895
977
  } finally {
896
978
  this.validated?.deleteUser(userId);
897
979
  }
@@ -902,24 +984,19 @@ var AuthCredential = class {
902
984
  ...require_payload.credentialPayloadOf(entry),
903
985
  userId: entry.userId,
904
986
  method: this.method,
905
- credentialId: fingerprint(entry.token),
987
+ credentialId: this.fingerprintOfKey(entry.token),
906
988
  sessionId: this.sessionKeyOf(entry),
907
989
  expiresAt: entry.expiresAt
908
990
  }));
909
991
  }
910
992
  /**
911
- * The session id for a credential: its stored `sessionId`, or the token
912
- * fingerprint for legacy rows predating sessionId (so they surface as
913
- * singleton sessions). The ONE place this fallback rule lives — shared by
914
- * `validate()`, `listForUser()`, and the session-family methods so "this
915
- * device" matching stays consistent across all of them.
993
+ * Session-grouping key for a stored credential entry (its store key
994
+ * attached): its stored `sessionId`, or the token fingerprint for legacy
995
+ * rows predating sessionId (so they surface as singleton sessions) — the
996
+ * same fallback `validate()` applies, so "this device" matching holds.
916
997
  */
917
- sessionIdOf(sessionId, token) {
918
- return sessionId ?? fingerprint(token);
919
- }
920
- /** Session-grouping key for a stored credential entry (token attached). */
921
998
  sessionKeyOf(entry) {
922
- return this.sessionIdOf(entry.sessionId, entry.token);
999
+ return entry.sessionId ?? this.fingerprintOfKey(entry.token);
923
1000
  }
924
1001
  /**
925
1002
  * List the user's active sessions, one row per token family (access +
@@ -971,14 +1048,21 @@ var AuthCredential = class {
971
1048
  return Promise.all(sessions.map((s) => Promise.resolve(enrich(s))));
972
1049
  }
973
1050
  /**
1051
+ * Whether the store can enumerate a user's credentials — i.e. whether
1052
+ * {@link listSessions}, {@link revokeSession} and {@link revokeOtherSessions}
1053
+ * act at all. `false` for stateless stores (JWT, encapsulated), where those
1054
+ * are no-ops and {@link revokeAllForUser} is the only bulk revocation.
1055
+ */
1056
+ get canEnumerateSessions() {
1057
+ return this.store.listForUser !== void 0;
1058
+ }
1059
+ /**
974
1060
  * Revoke a single session — every token in its family (access + refresh +
975
1061
  * rotations). No-op for stores that can't enumerate. Other sessions keep
976
1062
  * validating.
977
1063
  */
978
1064
  async revokeSession(userId, sessionId) {
979
- if (!this.store.listForUser) return;
980
- const all = await this.store.listForUser(userId);
981
- await Promise.all(all.filter((entry) => this.sessionKeyOf(entry) === sessionId).map((entry) => this.revoke(entry.token)));
1065
+ await this.sweepUntilEmpty(userId, (key) => key === sessionId);
982
1066
  }
983
1067
  /**
984
1068
  * Revoke every session for the user EXCEPT `keepSessionId` ("log out
@@ -986,18 +1070,39 @@ var AuthCredential = class {
986
1070
  * (returns 0) for stores that can't enumerate.
987
1071
  */
988
1072
  async revokeOtherSessions(userId, keepSessionId) {
989
- if (!this.store.listForUser) return 0;
990
- const all = await this.store.listForUser(userId);
991
- const revokedSessions = /* @__PURE__ */ new Set();
992
- const revokes = [];
993
- for (const entry of all) {
994
- const key = this.sessionKeyOf(entry);
995
- if (key === keepSessionId) continue;
996
- revokedSessions.add(key);
997
- revokes.push(this.revoke(entry.token));
1073
+ return (await this.sweepUntilEmpty(userId, (key) => key !== keepSessionId)).size;
1074
+ }
1075
+ /**
1076
+ * Revoke every credential of `userId` whose session key matches, repeating
1077
+ * list-then-delete until a listing finds no match; returns the distinct
1078
+ * session keys revoked. No-op on stores that can't enumerate.
1079
+ *
1080
+ * Paired with the post-mint re-check in {@link assertStillLive}, this closes
1081
+ * the race with refreshes in flight. A refresh re-reads the row it was
1082
+ * minted from AFTER persisting its new rows, and revokes them if that row is
1083
+ * gone. So a row surviving the final (empty) listing would have to be minted
1084
+ * after that listing off a parent still alive after it — a parent that, not
1085
+ * being listed, was itself minted after it, and so on down a chain that
1086
+ * must start at a row that existed before the listing: a contradiction.
1087
+ * Typically two passes (the second finds nothing); capped, failing loudly
1088
+ * rather than spinning against a refresh loop.
1089
+ */
1090
+ async sweepUntilEmpty(userId, matches) {
1091
+ const revoked = /* @__PURE__ */ new Set();
1092
+ const listForUser = this.store.listForUser?.bind(this.store);
1093
+ if (!listForUser) return revoked;
1094
+ for (let pass = 0;; pass++) {
1095
+ const revokes = [];
1096
+ for (const entry of await listForUser(userId)) {
1097
+ const key = this.sessionKeyOf(entry);
1098
+ if (!matches(key)) continue;
1099
+ revoked.add(key);
1100
+ revokes.push(this.revokeKey(entry.token));
1101
+ }
1102
+ if (revokes.length === 0) return revoked;
1103
+ await Promise.all(revokes);
1104
+ if (pass >= MAX_REVOKE_PASSES) throw revocationDidNotConverge();
998
1105
  }
999
- await Promise.all(revokes);
1000
- return revokedSessions.size;
1001
1106
  }
1002
1107
  /**
1003
1108
  * Derive a stable 32-byte key from this credential's underlying store secret,
@@ -1007,21 +1112,21 @@ var AuthCredential = class {
1007
1112
  * should then require an explicit secret.
1008
1113
  */
1009
1114
  deriveStateKey(label = "wf-state") {
1010
- if (!this.store.deriveSubkey) throw new AuthError("INVALID_CONFIG", "credential store has no reusable secret; provide an explicit wfStateSecret");
1115
+ if (!this.store.deriveSubkey) throw new require_payload.AuthError("INVALID_CONFIG", "credential store has no reusable secret; provide an explicit wfStateSecret");
1011
1116
  return this.store.deriveSubkey(label);
1012
1117
  }
1013
1118
  async enforceConcurrencyLimit(userId) {
1014
1119
  if (!this.store.listForUser || this.maxConcurrent === void 0) return;
1015
1120
  const accessOnly = (await this.store.listForUser(userId)).filter((entry) => entry.kind !== "refresh");
1016
1121
  if (accessOnly.length < this.maxConcurrent) return;
1017
- if (this.onLimit === "reject") throw new AuthError("MAX_CONCURRENT_REACHED", void 0, {
1122
+ if (this.onLimit === "reject") throw new require_payload.AuthError("MAX_CONCURRENT_REACHED", void 0, {
1018
1123
  userId,
1019
1124
  limit: this.maxConcurrent,
1020
1125
  active: accessOnly.length
1021
1126
  });
1022
1127
  const sorted = accessOnly.toSorted((a, b) => a.issuedAt - b.issuedAt);
1023
1128
  const toEvict = accessOnly.length - this.maxConcurrent + 1;
1024
- for (let i = 0; i < toEvict && i < sorted.length; i++) await this.revoke(sorted[i].token);
1129
+ for (let i = 0; i < toEvict && i < sorted.length; i++) await this.revokeKey(sorted[i].token);
1025
1130
  }
1026
1131
  async issueAccessFromRefresh(refreshState, now) {
1027
1132
  const accessTtl = refreshState.metadata?.accessTtl ?? this.accessTtl;
@@ -1035,7 +1140,7 @@ var AuthCredential = class {
1035
1140
  ...this.trackLastSeen === "refresh" && { lastSeenAt: now }
1036
1141
  });
1037
1142
  return {
1038
- token: await this.store.persist(accessState, accessTtl),
1143
+ token: await this.put(accessState, accessTtl),
1039
1144
  expiresAt: now + accessTtl
1040
1145
  };
1041
1146
  }
@@ -1046,9 +1151,9 @@ var AuthCredential = class {
1046
1151
  * `now + ttl` (used by `sliding`). `rotateOld` stamps the old refresh as
1047
1152
  * rotated (keeping it valid through the grace window) instead of consuming it.
1048
1153
  */
1049
- async issueRotatedPair(oldRefreshState, oldRefreshToken, rotateOld, now, preserveExpiry = false) {
1154
+ async issueRotatedPair(oldRefreshState, oldRefreshToken, oldKey, rotateOld, now, preserveExpiry = false) {
1050
1155
  const slidingTtl = this.refreshConfig?.ttl;
1051
- if (!preserveExpiry && slidingTtl === void 0) throw new AuthError("INVALID_CONFIG", "Refresh not enabled");
1156
+ if (!preserveExpiry && slidingTtl === void 0) throw new require_payload.AuthError("INVALID_CONFIG", "Refresh not enabled");
1052
1157
  const refreshExpiresAt = preserveExpiry ? oldRefreshState.expiresAt : now + slidingTtl;
1053
1158
  const refreshTtl = preserveExpiry ? Math.max(0, oldRefreshState.expiresAt - now) : slidingTtl;
1054
1159
  const newRefreshState = stateWithPayload(require_payload.credentialPayloadOf(oldRefreshState), {
@@ -1057,25 +1162,27 @@ var AuthCredential = class {
1057
1162
  expiresAt: refreshExpiresAt,
1058
1163
  kind: "refresh",
1059
1164
  metadata: oldRefreshState.metadata,
1060
- parentCredentialId: oldRefreshToken,
1165
+ parentCredentialId: this.hashAtRest ? fingerprint(oldRefreshToken) : oldRefreshToken,
1061
1166
  sessionId: oldRefreshState.sessionId,
1062
1167
  ...this.trackLastSeen === "refresh" && { lastSeenAt: now }
1063
1168
  });
1064
1169
  const access = await this.issueAccessFromRefresh(oldRefreshState, now);
1065
- const newRefreshToken = await this.store.persist(newRefreshState, refreshTtl);
1170
+ const newRefreshToken = await this.put(newRefreshState, refreshTtl);
1171
+ let liveKey = oldKey;
1066
1172
  if (rotateOld) {
1067
1173
  const rotatedState = {
1068
1174
  ...oldRefreshState,
1069
1175
  rotatedAt: now,
1070
- successor: {
1176
+ successor: this.sealSuccessor({
1071
1177
  accessToken: access.token,
1072
1178
  accessExpiresAt: access.expiresAt,
1073
1179
  refreshToken: newRefreshToken,
1074
1180
  refreshExpiresAt
1075
- }
1181
+ }, oldRefreshToken)
1076
1182
  };
1077
- await this.store.update(oldRefreshToken, rotatedState);
1183
+ liveKey = await this.store.update(oldKey, rotatedState);
1078
1184
  }
1185
+ await this.assertStillLive(liveKey, [access.token, newRefreshToken]);
1079
1186
  return {
1080
1187
  accessToken: access.token,
1081
1188
  accessExpiresAt: access.expiresAt,
@@ -1084,6 +1191,47 @@ var AuthCredential = class {
1084
1191
  userId: oldRefreshState.userId
1085
1192
  };
1086
1193
  }
1194
+ /**
1195
+ * Post-mint half of the revocation protocol (see {@link sweepUntilEmpty}): after
1196
+ * a refresh persisted new credentials, the refresh row it was minted from
1197
+ * must still exist. If a revocation deleted it meanwhile, the new
1198
+ * credentials belong to a revoked session — revoke them and refuse.
1199
+ * Stateful stores only: a stateless refresh consumed (or keeps) a
1200
+ * self-contained token, and its revocation epoch already rejects a mint
1201
+ * stamped before the revocation.
1202
+ */
1203
+ async assertStillLive(oldKey, minted) {
1204
+ if (!this.store.listForUser || await this.store.retrieve(oldKey)) return;
1205
+ await Promise.allSettled(minted.map((token) => this.revoke(token)));
1206
+ throw new require_payload.AuthError("INVALID_TOKEN");
1207
+ }
1208
+ /**
1209
+ * Under `hashAtRest` the successor pair is stored encrypted with a key
1210
+ * derived from the old refresh token — only a holder of that token (the
1211
+ * grace-window re-presentation) can read the pair back.
1212
+ */
1213
+ sealSuccessor(successor, oldRefreshToken) {
1214
+ if (!this.hashAtRest) return successor;
1215
+ const key = successorKey(oldRefreshToken);
1216
+ return {
1217
+ ...successor,
1218
+ accessToken: sealToken(key, successor.accessToken),
1219
+ refreshToken: sealToken(key, successor.refreshToken)
1220
+ };
1221
+ }
1222
+ /** Inverse of {@link sealSuccessor}; `undefined` when the pair cannot be opened. */
1223
+ openSuccessor(successor, presentedToken) {
1224
+ if (!(successor.accessToken.startsWith(SEALED_PREFIX) || successor.refreshToken.startsWith(SEALED_PREFIX))) return successor;
1225
+ const key = successorKey(presentedToken);
1226
+ const accessToken = openToken(key, successor.accessToken);
1227
+ const refreshToken = openToken(key, successor.refreshToken);
1228
+ if (accessToken === null || refreshToken === null) return void 0;
1229
+ return {
1230
+ ...successor,
1231
+ accessToken,
1232
+ refreshToken
1233
+ };
1234
+ }
1087
1235
  /** Amortized sweep of expired `consumedRefreshes` entries (each size doubling). */
1088
1236
  sweepConsumedRefreshes() {
1089
1237
  if (this.consumedRefreshes.size < this.consumedSweepAt) return;
@@ -1128,7 +1276,7 @@ var AuthCredential = class {
1128
1276
  });
1129
1277
  if ((this.refreshConfig?.reuseResponse ?? "session") === "session" && reuse.sessionId !== void 0 && this.store.listForUser) await this.revokeSession(reuse.userId, reuse.sessionId);
1130
1278
  else await this.revokeAllForUser(reuse.userId);
1131
- throw new AuthError("REFRESH_REUSE_DETECTED", void 0, {
1279
+ throw new require_payload.AuthError("REFRESH_REUSE_DETECTED", void 0, {
1132
1280
  userId: reuse.userId,
1133
1281
  ...reuse.sessionId !== void 0 && { sessionId: reuse.sessionId },
1134
1282
  ...reuse.rotatedAt !== void 0 && { rotatedAt: reuse.rotatedAt }
@@ -1224,44 +1372,95 @@ function renderRateLimitMessage(template, rule, retryAfterMs) {
1224
1372
  var RateLimitStoreMemory = class {
1225
1373
  entries = /* @__PURE__ */ new Map();
1226
1374
  clock;
1375
+ maxEntries;
1376
+ evictLast;
1227
1377
  /** Map size at which `hit` next sweeps expired counters (amortized; doubles). */
1228
1378
  sweepAt = MIN_SWEEP_SIZE;
1379
+ /**
1380
+ * Lower bound of every entry's `expiresAt` (exact after a sweep): while
1381
+ * `now` is below it nothing can have expired, so a sweep is skipped.
1382
+ */
1383
+ minExpiry = Infinity;
1384
+ /**
1385
+ * - `maxEntries` caps the live counters kept (default: unbounded). At the
1386
+ * cap a new key first sweeps expired counters, then evicts the oldest one.
1387
+ * - `evictLast` marks keys to keep while others can go: at the cap the
1388
+ * oldest key it does NOT match is evicted first (the oldest matching one
1389
+ * only when every key matches) — e.g. active lock markers that a flood of
1390
+ * fresh counters must not push out.
1391
+ */
1229
1392
  constructor(opts) {
1230
1393
  this.clock = opts?.clock ?? require_clock.defaultClock;
1394
+ this.maxEntries = opts?.maxEntries ?? Infinity;
1395
+ this.evictLast = opts?.evictLast;
1231
1396
  }
1232
1397
  async hit(key, ttlMs) {
1233
1398
  const now = this.clock.now();
1234
1399
  const entry = this.entries.get(key);
1235
1400
  if (!entry || entry.expiresAt <= now) {
1236
- if (!entry && this.entries.size >= this.sweepAt) {
1237
- this.sweep(now);
1401
+ if (!entry && this.entries.size >= this.maxEntries) {
1402
+ if (now >= this.minExpiry) this.sweep(now);
1403
+ while (this.entries.size >= this.maxEntries) this.evictOne();
1404
+ } else if (!entry && this.entries.size >= this.sweepAt) {
1405
+ if (now >= this.minExpiry) this.sweep(now);
1238
1406
  this.sweepAt = Math.max(MIN_SWEEP_SIZE, this.entries.size * 2);
1239
1407
  }
1408
+ const expiresAt = now + ttlMs;
1409
+ if (expiresAt < this.minExpiry) this.minExpiry = expiresAt;
1410
+ this.entries.delete(key);
1240
1411
  this.entries.set(key, {
1241
1412
  count: 1,
1242
- expiresAt: now + ttlMs
1413
+ expiresAt
1243
1414
  });
1244
1415
  return 1;
1245
1416
  }
1246
1417
  entry.count += 1;
1247
1418
  return entry.count;
1248
1419
  }
1420
+ /** Drop the oldest key (Map keeps insertion order), sparing `evictLast` keys while it can. */
1421
+ evictOne() {
1422
+ let victim;
1423
+ for (const key of this.entries.keys()) {
1424
+ if (!this.evictLast?.(key)) {
1425
+ victim = key;
1426
+ break;
1427
+ }
1428
+ victim ??= key;
1429
+ }
1430
+ if (victim !== void 0) this.entries.delete(victim);
1431
+ }
1432
+ async get(key) {
1433
+ const entry = this.entries.get(key);
1434
+ return entry && entry.expiresAt > this.clock.now() ? entry.count : 0;
1435
+ }
1436
+ async expire(key, ttlMs) {
1437
+ const entry = this.entries.get(key);
1438
+ const now = this.clock.now();
1439
+ if (!entry || entry.expiresAt <= now) return;
1440
+ entry.expiresAt = now + ttlMs;
1441
+ if (entry.expiresAt < this.minExpiry) this.minExpiry = entry.expiresAt;
1442
+ this.entries.delete(key);
1443
+ this.entries.set(key, entry);
1444
+ }
1249
1445
  async reset(key) {
1250
1446
  this.entries.delete(key);
1251
1447
  }
1252
1448
  /** Drop every counter — test-harness reset between cases. */
1253
1449
  clear() {
1254
1450
  this.entries.clear();
1451
+ this.minExpiry = Infinity;
1255
1452
  }
1256
1453
  async cleanup() {
1257
1454
  return this.sweep(this.clock.now());
1258
1455
  }
1259
1456
  sweep(now) {
1260
1457
  let removed = 0;
1458
+ let min = Infinity;
1261
1459
  for (const [key, entry] of this.entries) if (entry.expiresAt <= now) {
1262
1460
  this.entries.delete(key);
1263
1461
  removed++;
1264
- }
1462
+ } else if (entry.expiresAt < min) min = entry.expiresAt;
1463
+ this.minExpiry = min;
1265
1464
  return removed;
1266
1465
  }
1267
1466
  };
@@ -1277,6 +1476,18 @@ const MIN_SWEEP_SIZE = 1024;
1277
1476
  * key and one atomic store increment decides. All rules are hit on every
1278
1477
  * check (rejected requests count too — they cannot extend a fixed window).
1279
1478
  */
1479
+ /**
1480
+ * The item that governs a combined decision: among the rejected ones (when
1481
+ * any), the one whose window frees capacity LAST — the request only becomes
1482
+ * allowed once every one passes, so a shorter hint would invite
1483
+ * guaranteed-rejected retries; otherwise the one with the least remaining
1484
+ * budget. Used across the rules of one check and across stacked policies.
1485
+ */
1486
+ function pickGoverning(items, rejected) {
1487
+ const failing = items.filter(rejected);
1488
+ if (failing.length > 0) return failing.reduce((a, b) => b.resetAt > a.resetAt ? b : a);
1489
+ return items.reduce((a, b) => b.remaining < a.remaining ? b : a);
1490
+ }
1280
1491
  var RateLimiter = class {
1281
1492
  store;
1282
1493
  clock;
@@ -1296,24 +1507,35 @@ var RateLimiter = class {
1296
1507
  * retries.
1297
1508
  */
1298
1509
  async check(scope, subject, rules, opts) {
1299
- if (rules.length === 0) throw new Error("RateLimiter.check: at least one rule is required");
1510
+ return this.evaluate(scope, subject, rules, opts, (key, rule) => this.store.hit(key, rule.window * 2));
1511
+ }
1512
+ /**
1513
+ * Read the budget `check()` would see — without spending it. `remaining`
1514
+ * is what is left in each window; `allowed` says whether a `check()` made
1515
+ * now would pass. Use it for a "N left today" status line. Requires a store
1516
+ * with `get()` (both bundled stores have it).
1517
+ */
1518
+ async peek(scope, subject, rules, opts) {
1519
+ if (!this.store.get) throw new Error("RateLimiter.peek: the rate-limit store does not implement get()");
1520
+ const get = this.store.get.bind(this.store);
1521
+ return this.evaluate(scope, subject, rules, opts, async (key) => await get(key) + 1, 1);
1522
+ }
1523
+ async evaluate(scope, subject, rules, opts, count, offset = 0) {
1524
+ if (rules.length === 0) throw new Error("RateLimiter: at least one rule is required");
1300
1525
  const parsed = rules.map((r) => parseRateLimitRule(r));
1301
1526
  const now = this.clock.now();
1302
1527
  const keyBase = `${encodeURIComponent(scope)}:${encodeURIComponent(subject)}`;
1303
- const evaluated = await Promise.all(parsed.map(async (rule, i) => {
1528
+ const governing = pickGoverning(await Promise.all(parsed.map(async (rule, i) => {
1304
1529
  const windowStart = Math.floor(now / rule.window) * rule.window;
1305
- const key = `${keyBase}:${i}:${windowStart}`;
1306
- const count = await this.store.hit(key, rule.window * 2);
1530
+ const n = await count(`${keyBase}:${i}:${windowStart}`, rule);
1307
1531
  return {
1308
1532
  rule,
1309
- remaining: Math.max(0, rule.limit - count),
1533
+ remaining: Math.max(0, rule.limit - n + offset),
1310
1534
  resetAt: windowStart + rule.window,
1311
- violated: count > rule.limit
1535
+ violated: n > rule.limit
1312
1536
  };
1313
- }));
1314
- const violated = evaluated.filter((e) => e.violated);
1315
- const rejected = violated.length > 0;
1316
- const governing = rejected ? violated.reduce((a, b) => b.resetAt > a.resetAt ? b : a) : evaluated.reduce((a, b) => b.remaining < a.remaining ? b : a);
1537
+ })), (e) => e.violated);
1538
+ const rejected = governing.violated;
1317
1539
  const resetAfterMs = governing.resetAt - now;
1318
1540
  return {
1319
1541
  allowed: !rejected,
@@ -1337,7 +1559,7 @@ function generateMagicLinkToken() {
1337
1559
  }
1338
1560
  //#endregion
1339
1561
  exports.AuthCredential = AuthCredential;
1340
- exports.AuthError = AuthError;
1562
+ exports.AuthError = require_payload.AuthError;
1341
1563
  exports.CredentialStoreEncapsulated = CredentialStoreEncapsulated;
1342
1564
  exports.CredentialStoreJwt = CredentialStoreJwt;
1343
1565
  exports.CredentialStoreMemory = CredentialStoreMemory;
@@ -1351,4 +1573,5 @@ exports.generateMagicLinkToken = generateMagicLinkToken;
1351
1573
  exports.generateOpaqueToken = require_opaque_token.generateOpaqueToken;
1352
1574
  exports.parseDurationMs = parseDurationMs;
1353
1575
  exports.parseRateLimitRule = parseRateLimitRule;
1576
+ exports.pickGoverning = pickGoverning;
1354
1577
  exports.renderRateLimitMessage = renderRateLimitMessage;