@aooth/auth 0.1.85 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs 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);
@@ -556,6 +538,34 @@ function lazyCredentialId(ctx, token) {
556
538
  }
557
539
  /** Smallest map size an amortized expiry sweep runs at. */
558
540
  const MIN_SWEEP_SIZE$1 = 1024;
541
+ /** A store key that is the SHA-256 hex of a token (`tokens.hashAtRest`). */
542
+ const HASHED_KEY = /^[0-9a-f]{64}$/i;
543
+ /** The token shape the bundled stores minted before `hashAtRest` (`randomUUID`). */
544
+ const UUID_TOKEN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
545
+ /** Prefix of a successor token encrypted at rest (`tokens.hashAtRest`). */
546
+ const SEALED_PREFIX = "enc1.";
547
+ /** AES-256-GCM key for the successor pair, derived from the presented (old) refresh token. */
548
+ function successorKey(oldRefreshToken) {
549
+ return Buffer.from(hkdfSync("sha256", oldRefreshToken, "", "aooth-refresh-successor", 32));
550
+ }
551
+ function sealToken(key, token) {
552
+ const iv = randomBytes(12);
553
+ const cipher = createCipheriv("aes-256-gcm", key, iv);
554
+ const body = Buffer.concat([cipher.update(token, "utf8"), cipher.final()]);
555
+ return `${SEALED_PREFIX}${iv.toString("base64url")}.${body.toString("base64url")}.${cipher.getAuthTag().toString("base64url")}`;
556
+ }
557
+ /** Decrypt a sealed token; a plain (legacy) value passes through; `null` on a failed decrypt. */
558
+ function openToken(key, value) {
559
+ if (!value.startsWith(SEALED_PREFIX)) return value;
560
+ const [iv, body, tag] = value.slice(5).split(".");
561
+ try {
562
+ const decipher = createDecipheriv("aes-256-gcm", key, Buffer.from(iv, "base64url"));
563
+ decipher.setAuthTag(Buffer.from(tag, "base64url"));
564
+ return Buffer.concat([decipher.update(Buffer.from(body, "base64url")), decipher.final()]).toString("utf8");
565
+ } catch {
566
+ return null;
567
+ }
568
+ }
559
569
  /**
560
570
  * The opt-in `validateCache`: token → validated state for `ttlMs`, bounded
561
571
  * (oldest dropped first). `epoch` moves on every eviction so a validation
@@ -659,8 +669,11 @@ var AuthCredential = class {
659
669
  consumedRefreshes = /* @__PURE__ */ new Map();
660
670
  /** Map size at which `consumedRefreshes` next sweeps its expired entries. */
661
671
  consumedSweepAt = MIN_SWEEP_SIZE$1;
662
- /** Opt-in validated-state cache (`validateCache`). */
672
+ /** Opt-in validated-state cache (`validateCache`), keyed by store key. */
663
673
  validated;
674
+ hashAtRest;
675
+ generateToken;
676
+ isLegacyToken;
664
677
  constructor(opts) {
665
678
  this.store = opts.store;
666
679
  this.method = opts.method ?? "token";
@@ -671,6 +684,10 @@ var AuthCredential = class {
671
684
  this.onLimit = opts.onLimit ?? "reject";
672
685
  this.trackLastSeen = opts.trackLastSeen ?? false;
673
686
  this.clock = opts.clock ?? defaultClock;
687
+ this.hashAtRest = opts.tokens?.hashAtRest ?? false;
688
+ this.generateToken = opts.tokens?.generate;
689
+ this.isLegacyToken = opts.tokens?.isLegacyToken ?? ((token) => UUID_TOKEN.test(token));
690
+ 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
691
  if (opts.validateCache) {
675
692
  if (!(opts.validateCache.ttlMs > 0)) throw new AuthError("INVALID_CONFIG", `validateCache.ttlMs must be > 0 (got ${opts.validateCache.ttlMs})`);
676
693
  this.validated = new ValidateCache(opts.validateCache.ttlMs, opts.validateCache.max ?? 1e4);
@@ -714,7 +731,7 @@ var AuthCredential = class {
714
731
  metadata: effectiveMetadata,
715
732
  sessionId
716
733
  });
717
- const accessToken = await this.store.persist(accessState, accessStoreTtl);
734
+ const accessToken = await this.put(accessState, accessStoreTtl);
718
735
  let refreshToken;
719
736
  let refreshExpiresAt;
720
737
  if (refreshTtl !== void 0) {
@@ -726,7 +743,7 @@ var AuthCredential = class {
726
743
  metadata: effectiveMetadata,
727
744
  sessionId
728
745
  });
729
- refreshToken = await this.store.persist(refreshState, refreshTtl);
746
+ refreshToken = await this.put(refreshState, refreshTtl);
730
747
  refreshExpiresAt = now + refreshTtl;
731
748
  }
732
749
  return {
@@ -737,47 +754,91 @@ var AuthCredential = class {
737
754
  };
738
755
  }
739
756
  async validate(accessToken) {
740
- let state = this.validated?.get(accessToken, this.clock.now());
757
+ let key = this.keyOf(accessToken);
758
+ let state = this.validated?.get(key, this.clock.now());
741
759
  let fresh = false;
742
760
  if (!state) {
743
761
  fresh = true;
744
762
  const epoch = this.validated?.epoch;
745
- state = await this.retrieveUnlessDenied(accessToken);
746
- if (!state) return null;
763
+ const found = await this.retrieveUnlessDenied(accessToken, key);
764
+ if (!found) return null;
765
+ ({key, state} = found);
747
766
  if (state.expiresAt <= this.clock.now()) return null;
748
767
  if (state.kind === "refresh") return null;
749
- if (this.validated && this.validated.epoch === epoch) this.validated.set(accessToken, state, this.clock.now());
768
+ if (this.validated && this.validated.epoch === epoch) this.validated.set(key, state, this.clock.now());
750
769
  } else if (state.expiresAt <= this.clock.now()) {
751
- this.validated.delete(accessToken);
770
+ this.validated.delete(key);
752
771
  return null;
753
772
  }
754
- if (this.trackLastSeen === "validate" && this.store.touch) await this.store.touch(accessToken, this.clock.now(), fresh ? state : void 0);
773
+ if (this.trackLastSeen === "validate" && this.store.touch) await this.store.touch(key, this.clock.now(), fresh ? state : void 0);
755
774
  const ctx = {
756
775
  ...credentialPayloadOf(state),
757
776
  userId: state.userId,
758
777
  method: this.method,
759
778
  credentialId: "",
760
- sessionId: this.sessionIdOf(state.sessionId, accessToken),
779
+ sessionId: state.sessionId ?? this.fingerprintOfKey(key),
761
780
  expiresAt: state.expiresAt
762
781
  };
763
- lazyCredentialId(ctx, accessToken);
782
+ if (key !== accessToken) ctx.credentialId = key;
783
+ else lazyCredentialId(ctx, accessToken);
764
784
  return ctx;
765
785
  }
766
786
  /**
767
787
  * The stored state of `accessToken` unless the orchestrator's denylist has
768
788
  * it — both looked up concurrently (one round trip on remote stores).
769
789
  */
770
- async retrieveUnlessDenied(accessToken) {
771
- const retrieving = this.store.retrieve(accessToken);
790
+ async retrieveUnlessDenied(accessToken, key) {
791
+ const retrieving = this.find(accessToken, key);
772
792
  if (!this.denylist) return await retrieving;
773
793
  retrieving.catch(() => {});
774
794
  if (await this.denylist.has(accessToken)) return null;
775
795
  return await retrieving;
776
796
  }
797
+ /** The store key a token's row lives under: its SHA-256 when hashing, else the token. */
798
+ keyOf(token) {
799
+ return this.hashAtRest ? fingerprint(token) : token;
800
+ }
801
+ /** `credentialId` (the token's SHA-256) of a stored row, from its store key. */
802
+ fingerprintOfKey(key) {
803
+ return this.hashAtRest && HASHED_KEY.test(key) ? key : fingerprint(key);
804
+ }
805
+ /** Persist a new credential; returns the token the client will hold. */
806
+ async put(state, ttl) {
807
+ if (!this.hashAtRest && !this.generateToken) return await this.store.persist(state, ttl);
808
+ const token = this.generateToken?.() ?? randomBytes(32).toString("base64url");
809
+ await this.store.persistAs(this.keyOf(token), state, ttl);
810
+ return token;
811
+ }
812
+ /**
813
+ * Look a token up: by its store key, and — under `hashAtRest: 'migrate'` —
814
+ * by the token itself for a row written before hashing was enabled.
815
+ */
816
+ async find(token, key = this.keyOf(token)) {
817
+ const state = await this.store.retrieve(key);
818
+ if (state) return {
819
+ key,
820
+ state
821
+ };
822
+ if (!this.mayBeLegacyKey(token)) return null;
823
+ const legacy = await this.store.retrieve(token);
824
+ return legacy ? {
825
+ key: token,
826
+ state: legacy
827
+ } : null;
828
+ }
829
+ /**
830
+ * `'migrate'`: may `token` be a row written before hashing, stored under
831
+ * the token itself? Never for a hash-shaped value — that is what a database
832
+ * read yields, and accepting it would turn a leaked row key into a session.
833
+ */
834
+ mayBeLegacyKey(token) {
835
+ return this.hashAtRest === "migrate" && !HASHED_KEY.test(token) && !/\s/.test(token) && this.isLegacyToken(token);
836
+ }
777
837
  async refresh(refreshToken, opts) {
778
838
  const now = this.clock.now();
779
- const oldState = await this.store.retrieve(refreshToken);
780
- if (!oldState) {
839
+ const found = await this.find(refreshToken);
840
+ const oldState = found?.state;
841
+ if (!found || !oldState) {
781
842
  const consumed = this.lookupConsumedRefresh(refreshToken);
782
843
  if (consumed) await this.fireRefreshReuseTheftResponse(consumed, refreshToken);
783
844
  throw new AuthError("INVALID_TOKEN");
@@ -787,8 +848,8 @@ var AuthCredential = class {
787
848
  const rotation = oldState.metadata?.refreshRotation ?? (this.refreshConfig ? this.refreshConfig.rotation ?? "sliding" : "always");
788
849
  switch (rotation) {
789
850
  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);
851
+ case "always": return await this.refreshAlways(oldState, refreshToken, found.key, now);
852
+ case "sliding": return await this.refreshSliding(oldState, refreshToken, found.key, now);
792
853
  default: throw new AuthError("INVALID_CONFIG", `Unknown rotation: ${String(rotation)}`);
793
854
  }
794
855
  }
@@ -807,8 +868,8 @@ var AuthCredential = class {
807
868
  * forward (rolling session). Grace-tolerant via the shared store-backed
808
869
  * window.
809
870
  */
810
- async refreshSliding(oldState, refreshToken, now) {
811
- return await this.rotateWithGrace(oldState, refreshToken, now, false);
871
+ async refreshSliding(oldState, refreshToken, key, now) {
872
+ return await this.rotateWithGrace(oldState, refreshToken, key, now, false);
812
873
  }
813
874
  /**
814
875
  * `always` rotation: rotate on every use but keep a FIXED session ceiling —
@@ -820,9 +881,9 @@ var AuthCredential = class {
820
881
  * kept valid (`update` re-issues), so it falls back to single-use semantics
821
882
  * with a process-local reuse signal — the only mechanism possible there.
822
883
  */
823
- async refreshAlways(oldState, refreshToken, now) {
884
+ async refreshAlways(oldState, refreshToken, key, now) {
824
885
  if (!this.store.listForUser) {
825
- await this.store.consume(refreshToken);
886
+ await this.store.consume(key);
826
887
  this.sweepConsumedRefreshes();
827
888
  this.consumedRefreshes.set(refreshToken, {
828
889
  userId: oldState.userId,
@@ -830,9 +891,9 @@ var AuthCredential = class {
830
891
  exp: oldState.expiresAt,
831
892
  ...oldState.sessionId !== void 0 && { sessionId: oldState.sessionId }
832
893
  });
833
- return await this.issueRotatedPair(oldState, refreshToken, false, now, true);
894
+ return await this.issueRotatedPair(oldState, refreshToken, key, false, now, true);
834
895
  }
835
- return await this.rotateWithGrace(oldState, refreshToken, now, true);
896
+ return await this.rotateWithGrace(oldState, refreshToken, key, now, true);
836
897
  }
837
898
  /**
838
899
  * Shared rotation-with-grace mechanism for `sliding` and `always` on stateful
@@ -849,9 +910,9 @@ var AuthCredential = class {
849
910
  * mint-time `metadata.rotationGraceMs` (when stamped) wins over the instance
850
911
  * window, and a window of `0` is strict single-use.
851
912
  */
852
- async rotateWithGrace(oldState, refreshToken, now, preserveExpiry) {
913
+ async rotateWithGrace(oldState, refreshToken, key, now, preserveExpiry) {
853
914
  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);
915
+ if (typeof oldState.rotatedAt !== "number") return await this.issueRotatedPair(oldState, refreshToken, key, true, now, preserveExpiry);
855
916
  const reuse = {
856
917
  userId: oldState.userId,
857
918
  sessionId: oldState.sessionId,
@@ -860,8 +921,8 @@ var AuthCredential = class {
860
921
  rotatedAt: oldState.rotatedAt
861
922
  };
862
923
  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);
924
+ const successor = oldState.successor === void 0 ? void 0 : this.openSuccessor(oldState.successor, refreshToken);
925
+ const successorState = successor === void 0 ? null : (await this.find(successor.refreshToken))?.state ?? null;
865
926
  if (successor === void 0 || successorState === null || typeof successorState.rotatedAt === "number") return await this.respondToRefreshReuse(reuse);
866
927
  this.refreshConfig?.onRotationGraceHit?.({
867
928
  userId: oldState.userId,
@@ -880,11 +941,16 @@ var AuthCredential = class {
880
941
  };
881
942
  }
882
943
  async revoke(token) {
883
- this.validated?.delete(token);
944
+ await this.revokeKey(this.keyOf(token));
945
+ if (this.mayBeLegacyKey(token)) await this.revokeKey(token);
946
+ }
947
+ /** Revoke the row stored under `key` (a store key, as `listForUser` returns it). */
948
+ async revokeKey(key) {
949
+ this.validated?.delete(key);
884
950
  try {
885
- await this.store.revoke(token);
951
+ await this.store.revoke(key);
886
952
  } finally {
887
- this.validated?.delete(token);
953
+ this.validated?.delete(key);
888
954
  }
889
955
  }
890
956
  async revokeAllForUser(userId) {
@@ -901,24 +967,19 @@ var AuthCredential = class {
901
967
  ...credentialPayloadOf(entry),
902
968
  userId: entry.userId,
903
969
  method: this.method,
904
- credentialId: fingerprint(entry.token),
970
+ credentialId: this.fingerprintOfKey(entry.token),
905
971
  sessionId: this.sessionKeyOf(entry),
906
972
  expiresAt: entry.expiresAt
907
973
  }));
908
974
  }
909
975
  /**
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.
976
+ * Session-grouping key for a stored credential entry (its store key
977
+ * attached): its stored `sessionId`, or the token fingerprint for legacy
978
+ * rows predating sessionId (so they surface as singleton sessions) — the
979
+ * same fallback `validate()` applies, so "this device" matching holds.
915
980
  */
916
- sessionIdOf(sessionId, token) {
917
- return sessionId ?? fingerprint(token);
918
- }
919
- /** Session-grouping key for a stored credential entry (token attached). */
920
981
  sessionKeyOf(entry) {
921
- return this.sessionIdOf(entry.sessionId, entry.token);
982
+ return entry.sessionId ?? this.fingerprintOfKey(entry.token);
922
983
  }
923
984
  /**
924
985
  * List the user's active sessions, one row per token family (access +
@@ -977,7 +1038,7 @@ var AuthCredential = class {
977
1038
  async revokeSession(userId, sessionId) {
978
1039
  if (!this.store.listForUser) return;
979
1040
  const all = await this.store.listForUser(userId);
980
- await Promise.all(all.filter((entry) => this.sessionKeyOf(entry) === sessionId).map((entry) => this.revoke(entry.token)));
1041
+ await Promise.all(all.filter((entry) => this.sessionKeyOf(entry) === sessionId).map((entry) => this.revokeKey(entry.token)));
981
1042
  }
982
1043
  /**
983
1044
  * Revoke every session for the user EXCEPT `keepSessionId` ("log out
@@ -993,7 +1054,7 @@ var AuthCredential = class {
993
1054
  const key = this.sessionKeyOf(entry);
994
1055
  if (key === keepSessionId) continue;
995
1056
  revokedSessions.add(key);
996
- revokes.push(this.revoke(entry.token));
1057
+ revokes.push(this.revokeKey(entry.token));
997
1058
  }
998
1059
  await Promise.all(revokes);
999
1060
  return revokedSessions.size;
@@ -1020,7 +1081,7 @@ var AuthCredential = class {
1020
1081
  });
1021
1082
  const sorted = accessOnly.toSorted((a, b) => a.issuedAt - b.issuedAt);
1022
1083
  const toEvict = accessOnly.length - this.maxConcurrent + 1;
1023
- for (let i = 0; i < toEvict && i < sorted.length; i++) await this.revoke(sorted[i].token);
1084
+ for (let i = 0; i < toEvict && i < sorted.length; i++) await this.revokeKey(sorted[i].token);
1024
1085
  }
1025
1086
  async issueAccessFromRefresh(refreshState, now) {
1026
1087
  const accessTtl = refreshState.metadata?.accessTtl ?? this.accessTtl;
@@ -1034,7 +1095,7 @@ var AuthCredential = class {
1034
1095
  ...this.trackLastSeen === "refresh" && { lastSeenAt: now }
1035
1096
  });
1036
1097
  return {
1037
- token: await this.store.persist(accessState, accessTtl),
1098
+ token: await this.put(accessState, accessTtl),
1038
1099
  expiresAt: now + accessTtl
1039
1100
  };
1040
1101
  }
@@ -1045,7 +1106,7 @@ var AuthCredential = class {
1045
1106
  * `now + ttl` (used by `sliding`). `rotateOld` stamps the old refresh as
1046
1107
  * rotated (keeping it valid through the grace window) instead of consuming it.
1047
1108
  */
1048
- async issueRotatedPair(oldRefreshState, oldRefreshToken, rotateOld, now, preserveExpiry = false) {
1109
+ async issueRotatedPair(oldRefreshState, oldRefreshToken, oldKey, rotateOld, now, preserveExpiry = false) {
1049
1110
  const slidingTtl = this.refreshConfig?.ttl;
1050
1111
  if (!preserveExpiry && slidingTtl === void 0) throw new AuthError("INVALID_CONFIG", "Refresh not enabled");
1051
1112
  const refreshExpiresAt = preserveExpiry ? oldRefreshState.expiresAt : now + slidingTtl;
@@ -1056,24 +1117,24 @@ var AuthCredential = class {
1056
1117
  expiresAt: refreshExpiresAt,
1057
1118
  kind: "refresh",
1058
1119
  metadata: oldRefreshState.metadata,
1059
- parentCredentialId: oldRefreshToken,
1120
+ parentCredentialId: this.hashAtRest ? fingerprint(oldRefreshToken) : oldRefreshToken,
1060
1121
  sessionId: oldRefreshState.sessionId,
1061
1122
  ...this.trackLastSeen === "refresh" && { lastSeenAt: now }
1062
1123
  });
1063
1124
  const access = await this.issueAccessFromRefresh(oldRefreshState, now);
1064
- const newRefreshToken = await this.store.persist(newRefreshState, refreshTtl);
1125
+ const newRefreshToken = await this.put(newRefreshState, refreshTtl);
1065
1126
  if (rotateOld) {
1066
1127
  const rotatedState = {
1067
1128
  ...oldRefreshState,
1068
1129
  rotatedAt: now,
1069
- successor: {
1130
+ successor: this.sealSuccessor({
1070
1131
  accessToken: access.token,
1071
1132
  accessExpiresAt: access.expiresAt,
1072
1133
  refreshToken: newRefreshToken,
1073
1134
  refreshExpiresAt
1074
- }
1135
+ }, oldRefreshToken)
1075
1136
  };
1076
- await this.store.update(oldRefreshToken, rotatedState);
1137
+ await this.store.update(oldKey, rotatedState);
1077
1138
  }
1078
1139
  return {
1079
1140
  accessToken: access.token,
@@ -1083,6 +1144,33 @@ var AuthCredential = class {
1083
1144
  userId: oldRefreshState.userId
1084
1145
  };
1085
1146
  }
1147
+ /**
1148
+ * Under `hashAtRest` the successor pair is stored encrypted with a key
1149
+ * derived from the old refresh token — only a holder of that token (the
1150
+ * grace-window re-presentation) can read the pair back.
1151
+ */
1152
+ sealSuccessor(successor, oldRefreshToken) {
1153
+ if (!this.hashAtRest) return successor;
1154
+ const key = successorKey(oldRefreshToken);
1155
+ return {
1156
+ ...successor,
1157
+ accessToken: sealToken(key, successor.accessToken),
1158
+ refreshToken: sealToken(key, successor.refreshToken)
1159
+ };
1160
+ }
1161
+ /** Inverse of {@link sealSuccessor}; `undefined` when the pair cannot be opened. */
1162
+ openSuccessor(successor, presentedToken) {
1163
+ if (!(successor.accessToken.startsWith(SEALED_PREFIX) || successor.refreshToken.startsWith(SEALED_PREFIX))) return successor;
1164
+ const key = successorKey(presentedToken);
1165
+ const accessToken = openToken(key, successor.accessToken);
1166
+ const refreshToken = openToken(key, successor.refreshToken);
1167
+ if (accessToken === null || refreshToken === null) return void 0;
1168
+ return {
1169
+ ...successor,
1170
+ accessToken,
1171
+ refreshToken
1172
+ };
1173
+ }
1086
1174
  /** Amortized sweep of expired `consumedRefreshes` entries (each size doubling). */
1087
1175
  sweepConsumedRefreshes() {
1088
1176
  if (this.consumedRefreshes.size < this.consumedSweepAt) return;
@@ -1223,44 +1311,95 @@ function renderRateLimitMessage(template, rule, retryAfterMs) {
1223
1311
  var RateLimitStoreMemory = class {
1224
1312
  entries = /* @__PURE__ */ new Map();
1225
1313
  clock;
1314
+ maxEntries;
1315
+ evictLast;
1226
1316
  /** Map size at which `hit` next sweeps expired counters (amortized; doubles). */
1227
1317
  sweepAt = MIN_SWEEP_SIZE;
1318
+ /**
1319
+ * Lower bound of every entry's `expiresAt` (exact after a sweep): while
1320
+ * `now` is below it nothing can have expired, so a sweep is skipped.
1321
+ */
1322
+ minExpiry = Infinity;
1323
+ /**
1324
+ * - `maxEntries` caps the live counters kept (default: unbounded). At the
1325
+ * cap a new key first sweeps expired counters, then evicts the oldest one.
1326
+ * - `evictLast` marks keys to keep while others can go: at the cap the
1327
+ * oldest key it does NOT match is evicted first (the oldest matching one
1328
+ * only when every key matches) — e.g. active lock markers that a flood of
1329
+ * fresh counters must not push out.
1330
+ */
1228
1331
  constructor(opts) {
1229
1332
  this.clock = opts?.clock ?? defaultClock;
1333
+ this.maxEntries = opts?.maxEntries ?? Infinity;
1334
+ this.evictLast = opts?.evictLast;
1230
1335
  }
1231
1336
  async hit(key, ttlMs) {
1232
1337
  const now = this.clock.now();
1233
1338
  const entry = this.entries.get(key);
1234
1339
  if (!entry || entry.expiresAt <= now) {
1235
- if (!entry && this.entries.size >= this.sweepAt) {
1236
- this.sweep(now);
1340
+ if (!entry && this.entries.size >= this.maxEntries) {
1341
+ if (now >= this.minExpiry) this.sweep(now);
1342
+ while (this.entries.size >= this.maxEntries) this.evictOne();
1343
+ } else if (!entry && this.entries.size >= this.sweepAt) {
1344
+ if (now >= this.minExpiry) this.sweep(now);
1237
1345
  this.sweepAt = Math.max(MIN_SWEEP_SIZE, this.entries.size * 2);
1238
1346
  }
1347
+ const expiresAt = now + ttlMs;
1348
+ if (expiresAt < this.minExpiry) this.minExpiry = expiresAt;
1349
+ this.entries.delete(key);
1239
1350
  this.entries.set(key, {
1240
1351
  count: 1,
1241
- expiresAt: now + ttlMs
1352
+ expiresAt
1242
1353
  });
1243
1354
  return 1;
1244
1355
  }
1245
1356
  entry.count += 1;
1246
1357
  return entry.count;
1247
1358
  }
1359
+ /** Drop the oldest key (Map keeps insertion order), sparing `evictLast` keys while it can. */
1360
+ evictOne() {
1361
+ let victim;
1362
+ for (const key of this.entries.keys()) {
1363
+ if (!this.evictLast?.(key)) {
1364
+ victim = key;
1365
+ break;
1366
+ }
1367
+ victim ??= key;
1368
+ }
1369
+ if (victim !== void 0) this.entries.delete(victim);
1370
+ }
1371
+ async get(key) {
1372
+ const entry = this.entries.get(key);
1373
+ return entry && entry.expiresAt > this.clock.now() ? entry.count : 0;
1374
+ }
1375
+ async expire(key, ttlMs) {
1376
+ const entry = this.entries.get(key);
1377
+ const now = this.clock.now();
1378
+ if (!entry || entry.expiresAt <= now) return;
1379
+ entry.expiresAt = now + ttlMs;
1380
+ if (entry.expiresAt < this.minExpiry) this.minExpiry = entry.expiresAt;
1381
+ this.entries.delete(key);
1382
+ this.entries.set(key, entry);
1383
+ }
1248
1384
  async reset(key) {
1249
1385
  this.entries.delete(key);
1250
1386
  }
1251
1387
  /** Drop every counter — test-harness reset between cases. */
1252
1388
  clear() {
1253
1389
  this.entries.clear();
1390
+ this.minExpiry = Infinity;
1254
1391
  }
1255
1392
  async cleanup() {
1256
1393
  return this.sweep(this.clock.now());
1257
1394
  }
1258
1395
  sweep(now) {
1259
1396
  let removed = 0;
1397
+ let min = Infinity;
1260
1398
  for (const [key, entry] of this.entries) if (entry.expiresAt <= now) {
1261
1399
  this.entries.delete(key);
1262
1400
  removed++;
1263
- }
1401
+ } else if (entry.expiresAt < min) min = entry.expiresAt;
1402
+ this.minExpiry = min;
1264
1403
  return removed;
1265
1404
  }
1266
1405
  };
@@ -1276,6 +1415,18 @@ const MIN_SWEEP_SIZE = 1024;
1276
1415
  * key and one atomic store increment decides. All rules are hit on every
1277
1416
  * check (rejected requests count too — they cannot extend a fixed window).
1278
1417
  */
1418
+ /**
1419
+ * The item that governs a combined decision: among the rejected ones (when
1420
+ * any), the one whose window frees capacity LAST — the request only becomes
1421
+ * allowed once every one passes, so a shorter hint would invite
1422
+ * guaranteed-rejected retries; otherwise the one with the least remaining
1423
+ * budget. Used across the rules of one check and across stacked policies.
1424
+ */
1425
+ function pickGoverning(items, rejected) {
1426
+ const failing = items.filter(rejected);
1427
+ if (failing.length > 0) return failing.reduce((a, b) => b.resetAt > a.resetAt ? b : a);
1428
+ return items.reduce((a, b) => b.remaining < a.remaining ? b : a);
1429
+ }
1279
1430
  var RateLimiter = class {
1280
1431
  store;
1281
1432
  clock;
@@ -1295,24 +1446,35 @@ var RateLimiter = class {
1295
1446
  * retries.
1296
1447
  */
1297
1448
  async check(scope, subject, rules, opts) {
1298
- if (rules.length === 0) throw new Error("RateLimiter.check: at least one rule is required");
1449
+ return this.evaluate(scope, subject, rules, opts, (key, rule) => this.store.hit(key, rule.window * 2));
1450
+ }
1451
+ /**
1452
+ * Read the budget `check()` would see — without spending it. `remaining`
1453
+ * is what is left in each window; `allowed` says whether a `check()` made
1454
+ * now would pass. Use it for a "N left today" status line. Requires a store
1455
+ * with `get()` (both bundled stores have it).
1456
+ */
1457
+ async peek(scope, subject, rules, opts) {
1458
+ if (!this.store.get) throw new Error("RateLimiter.peek: the rate-limit store does not implement get()");
1459
+ const get = this.store.get.bind(this.store);
1460
+ return this.evaluate(scope, subject, rules, opts, async (key) => await get(key) + 1, 1);
1461
+ }
1462
+ async evaluate(scope, subject, rules, opts, count, offset = 0) {
1463
+ if (rules.length === 0) throw new Error("RateLimiter: at least one rule is required");
1299
1464
  const parsed = rules.map((r) => parseRateLimitRule(r));
1300
1465
  const now = this.clock.now();
1301
1466
  const keyBase = `${encodeURIComponent(scope)}:${encodeURIComponent(subject)}`;
1302
- const evaluated = await Promise.all(parsed.map(async (rule, i) => {
1467
+ const governing = pickGoverning(await Promise.all(parsed.map(async (rule, i) => {
1303
1468
  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);
1469
+ const n = await count(`${keyBase}:${i}:${windowStart}`, rule);
1306
1470
  return {
1307
1471
  rule,
1308
- remaining: Math.max(0, rule.limit - count),
1472
+ remaining: Math.max(0, rule.limit - n + offset),
1309
1473
  resetAt: windowStart + rule.window,
1310
- violated: count > rule.limit
1474
+ violated: n > rule.limit
1311
1475
  };
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);
1476
+ })), (e) => e.violated);
1477
+ const rejected = governing.violated;
1316
1478
  const resetAfterMs = governing.resetAt - now;
1317
1479
  return {
1318
1480
  allowed: !rejected,
@@ -1335,4 +1497,4 @@ function generateMagicLinkToken() {
1335
1497
  return generateOpaqueToken();
1336
1498
  }
1337
1499
  //#endregion
1338
- export { AuthCredential, AuthError, CredentialStoreEncapsulated, CredentialStoreJwt, CredentialStoreMemory, DEFAULT_RATE_LIMIT_MESSAGE, DenylistStoreMemory, RateLimitStoreMemory, RateLimiter, defaultClock, formatDurationMs, generateMagicLinkToken, generateOpaqueToken, parseDurationMs, parseRateLimitRule, renderRateLimitMessage };
1500
+ export { AuthCredential, AuthError, CredentialStoreEncapsulated, CredentialStoreJwt, CredentialStoreMemory, DEFAULT_RATE_LIMIT_MESSAGE, DenylistStoreMemory, RateLimitStoreMemory, RateLimiter, defaultClock, formatDurationMs, generateMagicLinkToken, generateOpaqueToken, parseDurationMs, parseRateLimitRule, pickGoverning, renderRateLimitMessage };
@@ -1,3 +1,24 @@
1
+ //#region src/errors.ts
2
+ const defaultMessages = {
3
+ INVALID_TOKEN: "Invalid token",
4
+ TOKEN_EXPIRED: "Token has expired",
5
+ TOKEN_REVOKED: "Token has been revoked",
6
+ REFRESH_REUSE_DETECTED: "Refresh token reuse detected",
7
+ STATELESS_OPERATION_UNSUPPORTED: "Operation is not supported by stateless credential store",
8
+ MAX_CONCURRENT_REACHED: "Maximum concurrent credentials reached for user",
9
+ INVALID_CONFIG: "Invalid auth configuration"
10
+ };
11
+ var AuthError = class extends Error {
12
+ type;
13
+ details;
14
+ name = "AuthError";
15
+ constructor(type, message, details) {
16
+ super(message ?? defaultMessages[type]);
17
+ this.type = type;
18
+ this.details = details;
19
+ }
20
+ };
21
+ //#endregion
1
22
  //#region src/credential/payload.ts
2
23
  const ENVELOPE_KEYS = new Set(Object.keys({
3
24
  userId: true,
@@ -25,6 +46,12 @@ function credentialPayloadOf(state) {
25
46
  return out;
26
47
  }
27
48
  //#endregion
49
+ Object.defineProperty(exports, "AuthError", {
50
+ enumerable: true,
51
+ get: function() {
52
+ return AuthError;
53
+ }
54
+ });
28
55
  Object.defineProperty(exports, "credentialPayloadOf", {
29
56
  enumerable: true,
30
57
  get: function() {