@aooth/auth 0.2.0 → 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.
@@ -1,5 +1,5 @@
1
1
  import { c as CredentialSuccessorRef, r as CredentialStore, s as CredentialState, t as Clock } from "./clock-CzAaCoZ5.cjs";
2
- import { c as AuthCodeStore, d as NewAuthCode, h as PendingAuthorizationStore, m as PendingAuthorization, o as NewDynamicClient, p as NewPendingAuthorization, r as DynamicClientStore, s as AuthCode, t as DynamicClient } from "./dynamic-client-store-D0RDGSSJ.cjs";
2
+ import { c as AuthCodeStore, d as NewAuthCode, h as PendingAuthorizationStore, m as PendingAuthorization, o as NewDynamicClient, p as NewPendingAuthorization, r as DynamicClientStore, s as AuthCode, t as DynamicClient } from "./dynamic-client-store-B7EnHuRp.cjs";
3
3
  //#region src/atscript-db/authz-stores.d.ts
4
4
  /**
5
5
  * atscript-db-backed durable implementations of the two short-lived
@@ -1,5 +1,5 @@
1
1
  import { c as CredentialSuccessorRef, r as CredentialStore, s as CredentialState, t as Clock } from "./clock-CzAaCoZ5.mjs";
2
- import { c as AuthCodeStore, d as NewAuthCode, h as PendingAuthorizationStore, m as PendingAuthorization, o as NewDynamicClient, p as NewPendingAuthorization, r as DynamicClientStore, s as AuthCode, t as DynamicClient } from "./dynamic-client-store-CUGQiS08.mjs";
2
+ import { c as AuthCodeStore, d as NewAuthCode, h as PendingAuthorizationStore, m as PendingAuthorization, o as NewDynamicClient, p as NewPendingAuthorization, r as DynamicClientStore, s as AuthCode, t as DynamicClient } from "./dynamic-client-store-BifZLGkT.mjs";
3
3
  //#region src/atscript-db/authz-stores.d.ts
4
4
  /**
5
5
  * atscript-db-backed durable implementations of the two short-lived
@@ -291,6 +291,13 @@ declare class AuthCredential<TPayload extends object = object> {
291
291
  enrich?: SessionEnricher;
292
292
  kind?: string | string[];
293
293
  }): Promise<SessionInfo[] | EnrichedSession[]>;
294
+ /**
295
+ * Whether the store can enumerate a user's credentials — i.e. whether
296
+ * {@link listSessions}, {@link revokeSession} and {@link revokeOtherSessions}
297
+ * act at all. `false` for stateless stores (JWT, encapsulated), where those
298
+ * are no-ops and {@link revokeAllForUser} is the only bulk revocation.
299
+ */
300
+ get canEnumerateSessions(): boolean;
294
301
  /**
295
302
  * Revoke a single session — every token in its family (access + refresh +
296
303
  * rotations). No-op for stores that can't enumerate. Other sessions keep
@@ -303,6 +310,22 @@ declare class AuthCredential<TPayload extends object = object> {
303
310
  * (returns 0) for stores that can't enumerate.
304
311
  */
305
312
  revokeOtherSessions(userId: string, keepSessionId: string): Promise<number>;
313
+ /**
314
+ * Revoke every credential of `userId` whose session key matches, repeating
315
+ * list-then-delete until a listing finds no match; returns the distinct
316
+ * session keys revoked. No-op on stores that can't enumerate.
317
+ *
318
+ * Paired with the post-mint re-check in {@link assertStillLive}, this closes
319
+ * the race with refreshes in flight. A refresh re-reads the row it was
320
+ * minted from AFTER persisting its new rows, and revokes them if that row is
321
+ * gone. So a row surviving the final (empty) listing would have to be minted
322
+ * after that listing off a parent still alive after it — a parent that, not
323
+ * being listed, was itself minted after it, and so on down a chain that
324
+ * must start at a row that existed before the listing: a contradiction.
325
+ * Typically two passes (the second finds nothing); capped, failing loudly
326
+ * rather than spinning against a refresh loop.
327
+ */
328
+ private sweepUntilEmpty;
306
329
  /**
307
330
  * Derive a stable 32-byte key from this credential's underlying store secret,
308
331
  * domain-separated by `label`. Lets adjacent subsystems (e.g. workflow-state
@@ -321,6 +344,16 @@ declare class AuthCredential<TPayload extends object = object> {
321
344
  * rotated (keeping it valid through the grace window) instead of consuming it.
322
345
  */
323
346
  private issueRotatedPair;
347
+ /**
348
+ * Post-mint half of the revocation protocol (see {@link sweepUntilEmpty}): after
349
+ * a refresh persisted new credentials, the refresh row it was minted from
350
+ * must still exist. If a revocation deleted it meanwhile, the new
351
+ * credentials belong to a revoked session — revoke them and refuse.
352
+ * Stateful stores only: a stateless refresh consumed (or keeps) a
353
+ * self-contained token, and its revocation epoch already rejects a mint
354
+ * stamped before the revocation.
355
+ */
356
+ private assertStillLive;
324
357
  /**
325
358
  * Under `hashAtRest` the successor pair is stored encrypted with a key
326
359
  * derived from the old refresh token — only a holder of that token (the
@@ -291,6 +291,13 @@ declare class AuthCredential<TPayload extends object = object> {
291
291
  enrich?: SessionEnricher;
292
292
  kind?: string | string[];
293
293
  }): Promise<SessionInfo[] | EnrichedSession[]>;
294
+ /**
295
+ * Whether the store can enumerate a user's credentials — i.e. whether
296
+ * {@link listSessions}, {@link revokeSession} and {@link revokeOtherSessions}
297
+ * act at all. `false` for stateless stores (JWT, encapsulated), where those
298
+ * are no-ops and {@link revokeAllForUser} is the only bulk revocation.
299
+ */
300
+ get canEnumerateSessions(): boolean;
294
301
  /**
295
302
  * Revoke a single session — every token in its family (access + refresh +
296
303
  * rotations). No-op for stores that can't enumerate. Other sessions keep
@@ -303,6 +310,22 @@ declare class AuthCredential<TPayload extends object = object> {
303
310
  * (returns 0) for stores that can't enumerate.
304
311
  */
305
312
  revokeOtherSessions(userId: string, keepSessionId: string): Promise<number>;
313
+ /**
314
+ * Revoke every credential of `userId` whose session key matches, repeating
315
+ * list-then-delete until a listing finds no match; returns the distinct
316
+ * session keys revoked. No-op on stores that can't enumerate.
317
+ *
318
+ * Paired with the post-mint re-check in {@link assertStillLive}, this closes
319
+ * the race with refreshes in flight. A refresh re-reads the row it was
320
+ * minted from AFTER persisting its new rows, and revokes them if that row is
321
+ * gone. So a row surviving the final (empty) listing would have to be minted
322
+ * after that listing off a parent still alive after it — a parent that, not
323
+ * being listed, was itself minted after it, and so on down a chain that
324
+ * must start at a row that existed before the listing: a contradiction.
325
+ * Typically two passes (the second finds nothing); capped, failing loudly
326
+ * rather than spinning against a refresh loop.
327
+ */
328
+ private sweepUntilEmpty;
306
329
  /**
307
330
  * Derive a stable 32-byte key from this credential's underlying store secret,
308
331
  * domain-separated by `label`. Lets adjacent subsystems (e.g. workflow-state
@@ -321,6 +344,16 @@ declare class AuthCredential<TPayload extends object = object> {
321
344
  * rotated (keeping it valid through the grace window) instead of consuming it.
322
345
  */
323
346
  private issueRotatedPair;
347
+ /**
348
+ * Post-mint half of the revocation protocol (see {@link sweepUntilEmpty}): after
349
+ * a refresh persisted new credentials, the refresh row it was minted from
350
+ * must still exist. If a revocation deleted it meanwhile, the new
351
+ * credentials belong to a revoked session — revoke them and refuse.
352
+ * Stateful stores only: a stateless refresh consumed (or keeps) a
353
+ * self-contained token, and its revocation epoch already rejects a mint
354
+ * stamped before the revocation.
355
+ */
356
+ private assertStillLive;
324
357
  /**
325
358
  * Under `hashAtRest` the successor pair is stored encrypted with a key
326
359
  * derived from the old refresh token — only a holder of that token (the
package/dist/authz.d.cts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { t as Clock } from "./clock-CzAaCoZ5.cjs";
2
- import { _ as PendingAuthorizationStoreMemoryOptions, a as DynamicClientStoreMemoryOptions, b as tokenPolicyToIssueOptions, c as AuthCodeStore, d as NewAuthCode, f as DEFAULT_PENDING_TTL_MS, g as PendingAuthorizationStoreMemory, h as PendingAuthorizationStore, i as DynamicClientStoreMemory, l as AuthCodeStoreMemory, m as PendingAuthorization, n as DynamicClientAuthMethod, o as NewDynamicClient, p as NewPendingAuthorization, r as DynamicClientStore, s as AuthCode, t as DynamicClient, u as AuthCodeStoreMemoryOptions, v as DEFAULT_AUTHZ_REFRESH_TTL_MS, y as TokenPolicy } from "./dynamic-client-store-D0RDGSSJ.cjs";
2
+ import { _ as PendingAuthorizationStoreMemoryOptions, a as DynamicClientStoreMemoryOptions, b as tokenPolicyToIssueOptions, c as AuthCodeStore, d as NewAuthCode, f as DEFAULT_PENDING_TTL_MS, g as PendingAuthorizationStoreMemory, h as PendingAuthorizationStore, i as DynamicClientStoreMemory, l as AuthCodeStoreMemory, m as PendingAuthorization, n as DynamicClientAuthMethod, o as NewDynamicClient, p as NewPendingAuthorization, r as DynamicClientStore, s as AuthCode, t as DynamicClient, u as AuthCodeStoreMemoryOptions, v as DEFAULT_AUTHZ_REFRESH_TTL_MS, y as TokenPolicy } from "./dynamic-client-store-B7EnHuRp.cjs";
3
3
  import { JWK } from "jose";
4
4
  //#region src/authz/authz-errors.d.ts
5
5
  /**
package/dist/authz.d.mts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { t as Clock } from "./clock-CzAaCoZ5.mjs";
2
- import { _ as PendingAuthorizationStoreMemoryOptions, a as DynamicClientStoreMemoryOptions, b as tokenPolicyToIssueOptions, c as AuthCodeStore, d as NewAuthCode, f as DEFAULT_PENDING_TTL_MS, g as PendingAuthorizationStoreMemory, h as PendingAuthorizationStore, i as DynamicClientStoreMemory, l as AuthCodeStoreMemory, m as PendingAuthorization, n as DynamicClientAuthMethod, o as NewDynamicClient, p as NewPendingAuthorization, r as DynamicClientStore, s as AuthCode, t as DynamicClient, u as AuthCodeStoreMemoryOptions, v as DEFAULT_AUTHZ_REFRESH_TTL_MS, y as TokenPolicy } from "./dynamic-client-store-CUGQiS08.mjs";
2
+ import { _ as PendingAuthorizationStoreMemoryOptions, a as DynamicClientStoreMemoryOptions, b as tokenPolicyToIssueOptions, c as AuthCodeStore, d as NewAuthCode, f as DEFAULT_PENDING_TTL_MS, g as PendingAuthorizationStoreMemory, h as PendingAuthorizationStore, i as DynamicClientStoreMemory, l as AuthCodeStoreMemory, m as PendingAuthorization, n as DynamicClientAuthMethod, o as NewDynamicClient, p as NewPendingAuthorization, r as DynamicClientStore, s as AuthCode, t as DynamicClient, u as AuthCodeStoreMemoryOptions, v as DEFAULT_AUTHZ_REFRESH_TTL_MS, y as TokenPolicy } from "./dynamic-client-store-BifZLGkT.mjs";
3
3
  import { JWK } from "jose";
4
4
  //#region src/authz/authz-errors.d.ts
5
5
  /**
@@ -1,5 +1,5 @@
1
1
  import { t as Clock } from "./clock-CzAaCoZ5.cjs";
2
- import { r as IssueOptions } from "./auth-credential-D1V5-2uy.cjs";
2
+ import { r as IssueOptions } from "./auth-credential-UV3sJ-lt.cjs";
3
3
  //#region src/authz/token-policy.d.ts
4
4
  /**
5
5
  * What the authorization server mints for a completed grant — forwarded verbatim
@@ -1,5 +1,5 @@
1
1
  import { t as Clock } from "./clock-CzAaCoZ5.mjs";
2
- import { r as IssueOptions } from "./auth-credential-BsH0E8hG.mjs";
2
+ import { r as IssueOptions } from "./auth-credential-CjCgZv7n.mjs";
3
3
  //#region src/authz/token-policy.d.ts
4
4
  /**
5
5
  * What the authorization server mints for a completed grant — forwarded verbatim
package/dist/index.cjs CHANGED
@@ -515,6 +515,14 @@ function stripJti(payload) {
515
515
  const DEFAULT_ACCESS_TTL = 3600 * 1e3;
516
516
  const DEFAULT_ROTATION_GRACE_MS = 3e4;
517
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
+ /**
518
526
  * Stable, non-reversible fingerprint of a token used as `credentialId` in
519
527
  * {@link AuthContext}. Hashing avoids leaking a live bearer token whenever
520
528
  * downstream consumers log or persist `ctx.credentialId`.
@@ -848,14 +856,15 @@ var AuthCredential = class {
848
856
  await opts?.guard?.(oldState);
849
857
  const rotation = oldState.metadata?.refreshRotation ?? (this.refreshConfig ? this.refreshConfig.rotation ?? "sliding" : "always");
850
858
  switch (rotation) {
851
- case "none": return await this.refreshNone(oldState, refreshToken, now);
859
+ case "none": return await this.refreshNone(oldState, refreshToken, found.key, now);
852
860
  case "always": return await this.refreshAlways(oldState, refreshToken, found.key, now);
853
861
  case "sliding": return await this.refreshSliding(oldState, refreshToken, found.key, now);
854
862
  default: throw new require_payload.AuthError("INVALID_CONFIG", `Unknown rotation: ${String(rotation)}`);
855
863
  }
856
864
  }
857
- async refreshNone(oldState, refreshToken, now) {
865
+ async refreshNone(oldState, refreshToken, key, now) {
858
866
  const newAccess = await this.issueAccessFromRefresh(oldState, now);
867
+ await this.assertStillLive(key, [newAccess.token]);
859
868
  return {
860
869
  accessToken: newAccess.token,
861
870
  accessExpiresAt: newAccess.expiresAt,
@@ -957,7 +966,14 @@ var AuthCredential = class {
957
966
  async revokeAllForUser(userId) {
958
967
  this.validated?.deleteUser(userId);
959
968
  try {
960
- 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;
961
977
  } finally {
962
978
  this.validated?.deleteUser(userId);
963
979
  }
@@ -1032,14 +1048,21 @@ var AuthCredential = class {
1032
1048
  return Promise.all(sessions.map((s) => Promise.resolve(enrich(s))));
1033
1049
  }
1034
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
+ /**
1035
1060
  * Revoke a single session — every token in its family (access + refresh +
1036
1061
  * rotations). No-op for stores that can't enumerate. Other sessions keep
1037
1062
  * validating.
1038
1063
  */
1039
1064
  async revokeSession(userId, sessionId) {
1040
- if (!this.store.listForUser) return;
1041
- const all = await this.store.listForUser(userId);
1042
- await Promise.all(all.filter((entry) => this.sessionKeyOf(entry) === sessionId).map((entry) => this.revokeKey(entry.token)));
1065
+ await this.sweepUntilEmpty(userId, (key) => key === sessionId);
1043
1066
  }
1044
1067
  /**
1045
1068
  * Revoke every session for the user EXCEPT `keepSessionId` ("log out
@@ -1047,18 +1070,39 @@ var AuthCredential = class {
1047
1070
  * (returns 0) for stores that can't enumerate.
1048
1071
  */
1049
1072
  async revokeOtherSessions(userId, keepSessionId) {
1050
- if (!this.store.listForUser) return 0;
1051
- const all = await this.store.listForUser(userId);
1052
- const revokedSessions = /* @__PURE__ */ new Set();
1053
- const revokes = [];
1054
- for (const entry of all) {
1055
- const key = this.sessionKeyOf(entry);
1056
- if (key === keepSessionId) continue;
1057
- revokedSessions.add(key);
1058
- revokes.push(this.revokeKey(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();
1059
1105
  }
1060
- await Promise.all(revokes);
1061
- return revokedSessions.size;
1062
1106
  }
1063
1107
  /**
1064
1108
  * Derive a stable 32-byte key from this credential's underlying store secret,
@@ -1124,6 +1168,7 @@ var AuthCredential = class {
1124
1168
  });
1125
1169
  const access = await this.issueAccessFromRefresh(oldRefreshState, now);
1126
1170
  const newRefreshToken = await this.put(newRefreshState, refreshTtl);
1171
+ let liveKey = oldKey;
1127
1172
  if (rotateOld) {
1128
1173
  const rotatedState = {
1129
1174
  ...oldRefreshState,
@@ -1135,8 +1180,9 @@ var AuthCredential = class {
1135
1180
  refreshExpiresAt
1136
1181
  }, oldRefreshToken)
1137
1182
  };
1138
- await this.store.update(oldKey, rotatedState);
1183
+ liveKey = await this.store.update(oldKey, rotatedState);
1139
1184
  }
1185
+ await this.assertStillLive(liveKey, [access.token, newRefreshToken]);
1140
1186
  return {
1141
1187
  accessToken: access.token,
1142
1188
  accessExpiresAt: access.expiresAt,
@@ -1146,6 +1192,20 @@ var AuthCredential = class {
1146
1192
  };
1147
1193
  }
1148
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
+ /**
1149
1209
  * Under `hashAtRest` the successor pair is stored encrypted with a key
1150
1210
  * derived from the old refresh token — only a holder of that token (the
1151
1211
  * grace-window re-presentation) can read the pair back.
package/dist/index.d.cts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { a as AuthContext, d as RefreshConfig, f as RefreshResult, i as DenylistStore, l as EnrichedSession, m as SessionInfo, n as defaultClock, o as CredentialMetadata, p as SessionEnricher, r as CredentialStore, s as CredentialState, t as Clock, u as IssueResult } from "./clock-CzAaCoZ5.cjs";
2
- import { i as RefreshCallOptions, n as AuthCredentialOptions, r as IssueOptions, t as AuthCredential } from "./auth-credential-D1V5-2uy.cjs";
2
+ import { i as RefreshCallOptions, n as AuthCredentialOptions, r as IssueOptions, t as AuthCredential } from "./auth-credential-UV3sJ-lt.cjs";
3
3
  import { n as RateLimitStoreMemory, t as RateLimitStore } from "./store-BaFYDHxn.cjs";
4
4
  import { CryptoKey } from "jose";
5
5
  //#region src/errors.d.ts
package/dist/index.d.mts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { a as AuthContext, d as RefreshConfig, f as RefreshResult, i as DenylistStore, l as EnrichedSession, m as SessionInfo, n as defaultClock, o as CredentialMetadata, p as SessionEnricher, r as CredentialStore, s as CredentialState, t as Clock, u as IssueResult } from "./clock-CzAaCoZ5.mjs";
2
- import { i as RefreshCallOptions, n as AuthCredentialOptions, r as IssueOptions, t as AuthCredential } from "./auth-credential-BsH0E8hG.mjs";
2
+ import { i as RefreshCallOptions, n as AuthCredentialOptions, r as IssueOptions, t as AuthCredential } from "./auth-credential-CjCgZv7n.mjs";
3
3
  import { n as RateLimitStoreMemory, t as RateLimitStore } from "./store-h-bLOAaS.mjs";
4
4
  import { CryptoKey } from "jose";
5
5
  //#region src/errors.d.ts
package/dist/index.mjs CHANGED
@@ -514,6 +514,14 @@ function stripJti(payload) {
514
514
  const DEFAULT_ACCESS_TTL = 3600 * 1e3;
515
515
  const DEFAULT_ROTATION_GRACE_MS = 3e4;
516
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
+ /**
517
525
  * Stable, non-reversible fingerprint of a token used as `credentialId` in
518
526
  * {@link AuthContext}. Hashing avoids leaking a live bearer token whenever
519
527
  * downstream consumers log or persist `ctx.credentialId`.
@@ -847,14 +855,15 @@ var AuthCredential = class {
847
855
  await opts?.guard?.(oldState);
848
856
  const rotation = oldState.metadata?.refreshRotation ?? (this.refreshConfig ? this.refreshConfig.rotation ?? "sliding" : "always");
849
857
  switch (rotation) {
850
- case "none": return await this.refreshNone(oldState, refreshToken, now);
858
+ case "none": return await this.refreshNone(oldState, refreshToken, found.key, now);
851
859
  case "always": return await this.refreshAlways(oldState, refreshToken, found.key, now);
852
860
  case "sliding": return await this.refreshSliding(oldState, refreshToken, found.key, now);
853
861
  default: throw new AuthError("INVALID_CONFIG", `Unknown rotation: ${String(rotation)}`);
854
862
  }
855
863
  }
856
- async refreshNone(oldState, refreshToken, now) {
864
+ async refreshNone(oldState, refreshToken, key, now) {
857
865
  const newAccess = await this.issueAccessFromRefresh(oldState, now);
866
+ await this.assertStillLive(key, [newAccess.token]);
858
867
  return {
859
868
  accessToken: newAccess.token,
860
869
  accessExpiresAt: newAccess.expiresAt,
@@ -956,7 +965,14 @@ var AuthCredential = class {
956
965
  async revokeAllForUser(userId) {
957
966
  this.validated?.deleteUser(userId);
958
967
  try {
959
- 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;
960
976
  } finally {
961
977
  this.validated?.deleteUser(userId);
962
978
  }
@@ -1031,14 +1047,21 @@ var AuthCredential = class {
1031
1047
  return Promise.all(sessions.map((s) => Promise.resolve(enrich(s))));
1032
1048
  }
1033
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
+ /**
1034
1059
  * Revoke a single session — every token in its family (access + refresh +
1035
1060
  * rotations). No-op for stores that can't enumerate. Other sessions keep
1036
1061
  * validating.
1037
1062
  */
1038
1063
  async revokeSession(userId, sessionId) {
1039
- if (!this.store.listForUser) return;
1040
- const all = await this.store.listForUser(userId);
1041
- await Promise.all(all.filter((entry) => this.sessionKeyOf(entry) === sessionId).map((entry) => this.revokeKey(entry.token)));
1064
+ await this.sweepUntilEmpty(userId, (key) => key === sessionId);
1042
1065
  }
1043
1066
  /**
1044
1067
  * Revoke every session for the user EXCEPT `keepSessionId` ("log out
@@ -1046,18 +1069,39 @@ var AuthCredential = class {
1046
1069
  * (returns 0) for stores that can't enumerate.
1047
1070
  */
1048
1071
  async revokeOtherSessions(userId, keepSessionId) {
1049
- if (!this.store.listForUser) return 0;
1050
- const all = await this.store.listForUser(userId);
1051
- const revokedSessions = /* @__PURE__ */ new Set();
1052
- const revokes = [];
1053
- for (const entry of all) {
1054
- const key = this.sessionKeyOf(entry);
1055
- if (key === keepSessionId) continue;
1056
- revokedSessions.add(key);
1057
- revokes.push(this.revokeKey(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();
1058
1104
  }
1059
- await Promise.all(revokes);
1060
- return revokedSessions.size;
1061
1105
  }
1062
1106
  /**
1063
1107
  * Derive a stable 32-byte key from this credential's underlying store secret,
@@ -1123,6 +1167,7 @@ var AuthCredential = class {
1123
1167
  });
1124
1168
  const access = await this.issueAccessFromRefresh(oldRefreshState, now);
1125
1169
  const newRefreshToken = await this.put(newRefreshState, refreshTtl);
1170
+ let liveKey = oldKey;
1126
1171
  if (rotateOld) {
1127
1172
  const rotatedState = {
1128
1173
  ...oldRefreshState,
@@ -1134,8 +1179,9 @@ var AuthCredential = class {
1134
1179
  refreshExpiresAt
1135
1180
  }, oldRefreshToken)
1136
1181
  };
1137
- await this.store.update(oldKey, rotatedState);
1182
+ liveKey = await this.store.update(oldKey, rotatedState);
1138
1183
  }
1184
+ await this.assertStillLive(liveKey, [access.token, newRefreshToken]);
1139
1185
  return {
1140
1186
  accessToken: access.token,
1141
1187
  accessExpiresAt: access.expiresAt,
@@ -1145,6 +1191,20 @@ var AuthCredential = class {
1145
1191
  };
1146
1192
  }
1147
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
+ /**
1148
1208
  * Under `hashAtRest` the successor pair is stored encrypted with a key
1149
1209
  * derived from the old refresh token — only a holder of that token (the
1150
1210
  * grace-window re-presentation) can read the pair back.
package/dist/redis.cjs CHANGED
@@ -61,13 +61,15 @@ var CredentialStoreRedis = class {
61
61
  const existingRaw = await this.redis.get(this.tokenKey(token));
62
62
  if (existingRaw === null) return token;
63
63
  const existing = JSON.parse(existingRaw);
64
- if (existing.userId !== state.userId) {
64
+ const ttlMs = Math.max(0, state.expiresAt - Date.now());
65
+ if (ttlMs <= 0) {
66
+ await this.revoke(token);
67
+ return token;
68
+ }
69
+ if (await this.redis.set(this.tokenKey(token), JSON.stringify(state), "PX", ttlMs, "XX") !== null && existing.userId !== state.userId) {
65
70
  await this.redis.srem(this.userKey(existing.userId), token);
66
71
  await this.redis.sadd(this.userKey(state.userId), token);
67
72
  }
68
- const ttlMs = Math.max(0, state.expiresAt - Date.now());
69
- if (ttlMs > 0) await this.redis.set(this.tokenKey(token), JSON.stringify(state), "PX", ttlMs);
70
- else await this.revoke(token);
71
73
  return token;
72
74
  }
73
75
  async revoke(token) {
@@ -88,7 +90,7 @@ var CredentialStoreRedis = class {
88
90
  state.lastSeenAt = at;
89
91
  const ttlMs = Math.max(0, state.expiresAt - Date.now());
90
92
  if (ttlMs <= 0) return;
91
- await this.redis.set(this.tokenKey(token), JSON.stringify(state), "PX", ttlMs);
93
+ await this.redis.set(this.tokenKey(token), JSON.stringify(state), "PX", ttlMs, "XX");
92
94
  }
93
95
  async revokeAllForUser(userId) {
94
96
  const setKey = this.userKey(userId);
package/dist/redis.d.cts CHANGED
@@ -19,7 +19,7 @@ import { t as RateLimitStore } from "./store-BaFYDHxn.cjs";
19
19
  *
20
20
  * ```ts
21
21
  * const redisLike: RedisLike = {
22
- * set: (k, v, _px, ttlMs) => client.set(k, v, ttlMs !== undefined ? { PX: ttlMs } : {}),
22
+ * set: (k, v, _px, ttlMs, xx) => client.set(k, v, { PX: ttlMs, ...(xx && { XX: true }) }),
23
23
  * get: (k) => client.get(k),
24
24
  * del: (...k) => client.del(k),
25
25
  * exists: (k) => client.exists(k),
@@ -46,10 +46,17 @@ import { t as RateLimitStore } from "./store-BaFYDHxn.cjs";
46
46
  * overload (it collides with the `set(key, value, cb?)` overload
47
47
  * instead), which is exactly what broke structural assignment before.
48
48
  * Every adapter call site already passes all four arguments.
49
+ * 3. The conditional `set(key, value, "PX", ms, "XX")` overload is REQUIRED
50
+ * (since 0.2.1): `CredentialStoreRedis` rewrites existing credentials
51
+ * (rotation stamp, `lastSeenAt`) only if the key still exists, so a write
52
+ * racing a revocation can never re-create a deleted credential. An
53
+ * adapter must forward `XX` and resolve `null` when the key is missing.
54
+ * ioredis exposes exactly this overload.
49
55
  *
50
56
  * Return types are chosen as a supertype of what real clients resolve, so an
51
57
  * ioredis client stays assignable while the types remain useful to callers:
52
- * - `set` returns `string | null` (ioredis resolves `"OK"`)
58
+ * - `set` returns `string | null` (ioredis resolves `"OK"`, or `null` when
59
+ * an `XX` write found no key)
53
60
  * - `del` / `pexpire` / `exists` / `incr` / `sadd` / `srem` return `number`
54
61
  * - `get` returns `string | null`
55
62
  * - `smembers` returns `string[]`
@@ -57,6 +64,11 @@ import { t as RateLimitStore } from "./store-BaFYDHxn.cjs";
57
64
  interface RedisLike {
58
65
  /** `SET key value PX ms` — `mode`/`ttlMs` are a required pair (see above). */
59
66
  set(key: string, value: string, mode: "PX", ttlMs: number): Promise<string | null>;
67
+ /**
68
+ * `SET key value PX ms XX` — write only if `key` exists; resolves `null`
69
+ * (and writes nothing) when it doesn't. Required since 0.2.1.
70
+ */
71
+ set(key: string, value: string, mode: "PX", ttlMs: number, condition: "XX"): Promise<string | null>;
60
72
  get(key: string): Promise<string | null>;
61
73
  del(...keys: string[]): Promise<number>;
62
74
  exists(key: string): Promise<number>;
package/dist/redis.d.mts CHANGED
@@ -19,7 +19,7 @@ import { t as RateLimitStore } from "./store-h-bLOAaS.mjs";
19
19
  *
20
20
  * ```ts
21
21
  * const redisLike: RedisLike = {
22
- * set: (k, v, _px, ttlMs) => client.set(k, v, ttlMs !== undefined ? { PX: ttlMs } : {}),
22
+ * set: (k, v, _px, ttlMs, xx) => client.set(k, v, { PX: ttlMs, ...(xx && { XX: true }) }),
23
23
  * get: (k) => client.get(k),
24
24
  * del: (...k) => client.del(k),
25
25
  * exists: (k) => client.exists(k),
@@ -46,10 +46,17 @@ import { t as RateLimitStore } from "./store-h-bLOAaS.mjs";
46
46
  * overload (it collides with the `set(key, value, cb?)` overload
47
47
  * instead), which is exactly what broke structural assignment before.
48
48
  * Every adapter call site already passes all four arguments.
49
+ * 3. The conditional `set(key, value, "PX", ms, "XX")` overload is REQUIRED
50
+ * (since 0.2.1): `CredentialStoreRedis` rewrites existing credentials
51
+ * (rotation stamp, `lastSeenAt`) only if the key still exists, so a write
52
+ * racing a revocation can never re-create a deleted credential. An
53
+ * adapter must forward `XX` and resolve `null` when the key is missing.
54
+ * ioredis exposes exactly this overload.
49
55
  *
50
56
  * Return types are chosen as a supertype of what real clients resolve, so an
51
57
  * ioredis client stays assignable while the types remain useful to callers:
52
- * - `set` returns `string | null` (ioredis resolves `"OK"`)
58
+ * - `set` returns `string | null` (ioredis resolves `"OK"`, or `null` when
59
+ * an `XX` write found no key)
53
60
  * - `del` / `pexpire` / `exists` / `incr` / `sadd` / `srem` return `number`
54
61
  * - `get` returns `string | null`
55
62
  * - `smembers` returns `string[]`
@@ -57,6 +64,11 @@ import { t as RateLimitStore } from "./store-h-bLOAaS.mjs";
57
64
  interface RedisLike {
58
65
  /** `SET key value PX ms` — `mode`/`ttlMs` are a required pair (see above). */
59
66
  set(key: string, value: string, mode: "PX", ttlMs: number): Promise<string | null>;
67
+ /**
68
+ * `SET key value PX ms XX` — write only if `key` exists; resolves `null`
69
+ * (and writes nothing) when it doesn't. Required since 0.2.1.
70
+ */
71
+ set(key: string, value: string, mode: "PX", ttlMs: number, condition: "XX"): Promise<string | null>;
60
72
  get(key: string): Promise<string | null>;
61
73
  del(...keys: string[]): Promise<number>;
62
74
  exists(key: string): Promise<number>;
package/dist/redis.mjs CHANGED
@@ -60,13 +60,15 @@ var CredentialStoreRedis = class {
60
60
  const existingRaw = await this.redis.get(this.tokenKey(token));
61
61
  if (existingRaw === null) return token;
62
62
  const existing = JSON.parse(existingRaw);
63
- if (existing.userId !== state.userId) {
63
+ const ttlMs = Math.max(0, state.expiresAt - Date.now());
64
+ if (ttlMs <= 0) {
65
+ await this.revoke(token);
66
+ return token;
67
+ }
68
+ if (await this.redis.set(this.tokenKey(token), JSON.stringify(state), "PX", ttlMs, "XX") !== null && existing.userId !== state.userId) {
64
69
  await this.redis.srem(this.userKey(existing.userId), token);
65
70
  await this.redis.sadd(this.userKey(state.userId), token);
66
71
  }
67
- const ttlMs = Math.max(0, state.expiresAt - Date.now());
68
- if (ttlMs > 0) await this.redis.set(this.tokenKey(token), JSON.stringify(state), "PX", ttlMs);
69
- else await this.revoke(token);
70
72
  return token;
71
73
  }
72
74
  async revoke(token) {
@@ -87,7 +89,7 @@ var CredentialStoreRedis = class {
87
89
  state.lastSeenAt = at;
88
90
  const ttlMs = Math.max(0, state.expiresAt - Date.now());
89
91
  if (ttlMs <= 0) return;
90
- await this.redis.set(this.tokenKey(token), JSON.stringify(state), "PX", ttlMs);
92
+ await this.redis.set(this.tokenKey(token), JSON.stringify(state), "PX", ttlMs, "XX");
91
93
  }
92
94
  async revokeAllForUser(userId) {
93
95
  const setKey = this.userKey(userId);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aooth/auth",
3
- "version": "0.2.0",
3
+ "version": "0.2.1",
4
4
  "description": "Auth method layer for aoothjs (sessions, tokens, password reset, MFA primitives)",
5
5
  "keywords": [
6
6
  "aoothjs",
@@ -104,22 +104,22 @@
104
104
  },
105
105
  "dependencies": {
106
106
  "jose": "^6.2.3",
107
- "@aooth/user": "0.2.0"
107
+ "@aooth/user": "0.2.1"
108
108
  },
109
109
  "devDependencies": {
110
- "@atscript/core": "^0.1.109",
111
- "@atscript/db": "^0.1.164",
112
- "@atscript/db-sql-tools": "^0.1.164",
113
- "@atscript/db-sqlite": "^0.1.164",
114
- "@atscript/typescript": "^0.1.109",
110
+ "@atscript/core": "^0.2.1",
111
+ "@atscript/db": "^0.1.166",
112
+ "@atscript/db-sql-tools": "^0.1.166",
113
+ "@atscript/db-sqlite": "^0.1.166",
114
+ "@atscript/typescript": "^0.2.1",
115
115
  "@types/better-sqlite3": "^7.6.13",
116
116
  "@uniqu/core": "^0.1.15",
117
117
  "better-sqlite3": "^12.6.2",
118
118
  "ioredis": "^5.11.1",
119
- "unplugin-atscript": "^0.1.109"
119
+ "unplugin-atscript": "^0.2.1"
120
120
  },
121
121
  "peerDependencies": {
122
- "@atscript/db": "^0.1.164"
122
+ "@atscript/db": "^0.1.166"
123
123
  },
124
124
  "peerDependenciesMeta": {
125
125
  "@atscript/db": {
@@ -7,7 +7,7 @@
7
7
  * Do not edit this file!
8
8
  */
9
9
 
10
- import type { TAtscriptTypeObject, TAtscriptTypeComplex, TAtscriptTypeFinal, TAtscriptTypeArray, TAtscriptAnnotatedType, TMetadataMap, Validator, TValidatorOptions } from "@atscript/typescript/utils"
10
+ import type { TAtscriptTypeObject, TAtscriptTypeComplex, TAtscriptTypeFinal, TAtscriptTypeArray, TAtscriptAnnotatedType, TAtscriptField, TMetadataMap, Validator, TValidatorOptions } from "@atscript/typescript/utils"
11
11
 
12
12
  /**
13
13
  * Atscript interface **AoothAuthCode**
@@ -7,7 +7,7 @@
7
7
  * Do not edit this file!
8
8
  */
9
9
 
10
- import type { TAtscriptTypeObject, TAtscriptTypeComplex, TAtscriptTypeFinal, TAtscriptTypeArray, TAtscriptAnnotatedType, TMetadataMap, Validator, TValidatorOptions } from "@atscript/typescript/utils"
10
+ import type { TAtscriptTypeObject, TAtscriptTypeComplex, TAtscriptTypeFinal, TAtscriptTypeArray, TAtscriptAnnotatedType, TAtscriptField, TMetadataMap, Validator, TValidatorOptions } from "@atscript/typescript/utils"
11
11
 
12
12
  /**
13
13
  * Atscript type **AoothCredentialMetadataBase**
@@ -7,7 +7,7 @@
7
7
  * Do not edit this file!
8
8
  */
9
9
 
10
- import type { TAtscriptTypeObject, TAtscriptTypeComplex, TAtscriptTypeFinal, TAtscriptTypeArray, TAtscriptAnnotatedType, TMetadataMap, Validator, TValidatorOptions } from "@atscript/typescript/utils"
10
+ import type { TAtscriptTypeObject, TAtscriptTypeComplex, TAtscriptTypeFinal, TAtscriptTypeArray, TAtscriptAnnotatedType, TAtscriptField, TMetadataMap, Validator, TValidatorOptions } from "@atscript/typescript/utils"
11
11
 
12
12
  /**
13
13
  * Atscript interface **AoothDynamicClient**
@@ -7,7 +7,7 @@
7
7
  * Do not edit this file!
8
8
  */
9
9
 
10
- import type { TAtscriptTypeObject, TAtscriptTypeComplex, TAtscriptTypeFinal, TAtscriptTypeArray, TAtscriptAnnotatedType, TMetadataMap, Validator, TValidatorOptions } from "@atscript/typescript/utils"
10
+ import type { TAtscriptTypeObject, TAtscriptTypeComplex, TAtscriptTypeFinal, TAtscriptTypeArray, TAtscriptAnnotatedType, TAtscriptField, TMetadataMap, Validator, TValidatorOptions } from "@atscript/typescript/utils"
11
11
 
12
12
  /**
13
13
  * Atscript interface **AoothPendingAuthorization**