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