@aooth/auth 0.2.0 → 0.2.2

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 (41) hide show
  1. package/dist/atscript-db.cjs +5 -7
  2. package/dist/atscript-db.d.cts +21 -25
  3. package/dist/atscript-db.d.mts +21 -25
  4. package/dist/atscript-db.mjs +5 -7
  5. package/dist/{auth-credential-BsH0E8hG.d.mts → auth-credential-46_eOF3c.d.cts} +34 -3
  6. package/dist/{auth-credential-D1V5-2uy.d.cts → auth-credential-Co-0pqcD.d.mts} +34 -3
  7. package/dist/authz.cjs +21 -33
  8. package/dist/authz.d.cts +23 -45
  9. package/dist/authz.d.mts +23 -45
  10. package/dist/authz.mjs +21 -33
  11. package/dist/client.cjs +1 -2
  12. package/dist/client.d.cts +7 -10
  13. package/dist/client.d.mts +7 -10
  14. package/dist/client.mjs +1 -2
  15. package/dist/{clock-Bl-H3eqE.cjs → clock-BcBMqB9g.cjs} +1 -2
  16. package/dist/{clock-Bdsep_1j.mjs → clock-DzAK2bWR.mjs} +1 -2
  17. package/dist/{clock-CzAaCoZ5.d.cts → clock-hTHoZ2vA.d.cts} +0 -6
  18. package/dist/{clock-CzAaCoZ5.d.mts → clock-hTHoZ2vA.d.mts} +0 -6
  19. package/dist/{dynamic-client-store-DykM9QOT.cjs → dynamic-client-store-CC4qr_kz.cjs} +5 -8
  20. package/dist/{dynamic-client-store-CUGQiS08.d.mts → dynamic-client-store-CTt1B6Gj.d.cts} +2 -10
  21. package/dist/{dynamic-client-store-B1JwFHdP.mjs → dynamic-client-store-DrMBcFtG.mjs} +5 -8
  22. package/dist/{dynamic-client-store-D0RDGSSJ.d.cts → dynamic-client-store-mYg0nRJU.d.mts} +2 -10
  23. package/dist/index.cjs +92 -42
  24. package/dist/index.d.cts +18 -40
  25. package/dist/index.d.mts +18 -40
  26. package/dist/index.mjs +92 -42
  27. package/dist/{opaque-token-BaMOrC1A.mjs → opaque-token-BLoQKkZ3.mjs} +1 -2
  28. package/dist/{opaque-token-CaZgD2i6.cjs → opaque-token-BLuVHSVJ.cjs} +1 -2
  29. package/dist/{payload-C1cQW7p_.cjs → payload-CqQH88C6.cjs} +2 -4
  30. package/dist/{payload-DDlf38B-.mjs → payload-DizkKbzh.mjs} +2 -4
  31. package/dist/redis.cjs +8 -7
  32. package/dist/redis.d.cts +21 -11
  33. package/dist/redis.d.mts +21 -11
  34. package/dist/redis.mjs +8 -7
  35. package/dist/{store-BaFYDHxn.d.cts → store-BXxX8sUP.d.mts} +1 -3
  36. package/dist/{store-h-bLOAaS.d.mts → store-D9CcbcBp.d.cts} +1 -3
  37. package/package.json +9 -9
  38. package/src/atscript-db/auth-code.as.d.ts +1 -1
  39. package/src/atscript-db/auth-credential.as.d.ts +1 -1
  40. package/src/atscript-db/dynamic-client.as.d.ts +1 -1
  41. package/src/atscript-db/pending-authorization.as.d.ts +1 -1
package/dist/index.mjs CHANGED
@@ -1,9 +1,9 @@
1
- import { n as AuthError, t as credentialPayloadOf } from "./payload-DDlf38B-.mjs";
2
- import { t as defaultClock } from "./clock-Bdsep_1j.mjs";
3
- import { t as generateOpaqueToken } from "./opaque-token-BaMOrC1A.mjs";
1
+ import { n as AuthError, t as credentialPayloadOf } from "./payload-DizkKbzh.mjs";
2
+ import { t as defaultClock } from "./clock-DzAK2bWR.mjs";
3
+ import { t as generateOpaqueToken } from "./opaque-token-BLoQKkZ3.mjs";
4
4
  import { createCipheriv, createDecipheriv, createHash, hkdfSync, randomBytes, randomUUID, scryptSync } from "node:crypto";
5
5
  import { SignJWT, jwtVerify } from "jose";
6
- //#region src/stores/memory.ts
6
+ // src/stores/memory.ts
7
7
  /**
8
8
  * In-memory implementation of CredentialStore using random opaque token IDs.
9
9
  *
@@ -118,8 +118,7 @@ var CredentialStoreMemory = class {
118
118
  if (set.size === 0) this.byUser.delete(userId);
119
119
  }
120
120
  };
121
- //#endregion
122
- //#region src/stores/denylist-memory.ts
121
+ // src/stores/denylist-memory.ts
123
122
  /**
124
123
  * In-memory denylist for stateless revocation.
125
124
  *
@@ -167,15 +166,13 @@ var DenylistStoreMemory = class {
167
166
  };
168
167
  /** Smallest map size an amortized expiry sweep runs at. */
169
168
  const MIN_SWEEP_SIZE$2 = 1024;
170
- //#endregion
171
- //#region src/stores/derive-subkey.ts
169
+ // src/stores/derive-subkey.ts
172
170
  const SUBKEY_SALT = Buffer.from("aooth/credential-store/subkey-v1");
173
171
  /** HKDF-SHA256 a stable 32-byte subkey from symmetric key material + a label. */
174
172
  function hkdfSubkey(ikm, label) {
175
173
  return Buffer.from(hkdfSync("sha256", ikm, SUBKEY_SALT, Buffer.from(label, "utf8"), 32));
176
174
  }
177
- //#endregion
178
- //#region src/stores/jwt.ts
175
+ // src/stores/jwt.ts
179
176
  const HS_ALGS = /* @__PURE__ */ new Set([
180
177
  "HS256",
181
178
  "HS384",
@@ -359,8 +356,7 @@ function normalizeSecret(secret) {
359
356
  if (typeof secret === "string") return new TextEncoder().encode(secret);
360
357
  return secret;
361
358
  }
362
- //#endregion
363
- //#region src/stores/encapsulated.ts
359
+ // src/stores/encapsulated.ts
364
360
  const KEY_LEN = 32;
365
361
  const IV_LEN = 12;
366
362
  const TAG_LEN = 16;
@@ -509,11 +505,18 @@ function stripJti(payload) {
509
505
  const { jti: _jti, ...rest } = payload;
510
506
  return rest;
511
507
  }
512
- //#endregion
513
- //#region src/credential/auth-credential.ts
514
- const DEFAULT_ACCESS_TTL = 3600 * 1e3;
508
+ // src/credential/auth-credential.ts
509
+ const DEFAULT_ACCESS_TTL = 36e5;
515
510
  const DEFAULT_ROTATION_GRACE_MS = 3e4;
516
511
  /**
512
+ * Upper bound on list-then-delete passes in one revocation. Two is the norm;
513
+ * more only while refreshes keep minting off the session being revoked.
514
+ */
515
+ const MAX_REVOKE_PASSES = 8;
516
+ function revocationDidNotConverge() {
517
+ return /* @__PURE__ */ new Error(`aooth: revocation did not converge after ${MAX_REVOKE_PASSES} passes (refreshes kept minting); retry it`);
518
+ }
519
+ /**
517
520
  * Stable, non-reversible fingerprint of a token used as `credentialId` in
518
521
  * {@link AuthContext}. Hashing avoids leaking a live bearer token whenever
519
522
  * downstream consumers log or persist `ctx.credentialId`.
@@ -847,14 +850,15 @@ var AuthCredential = class {
847
850
  await opts?.guard?.(oldState);
848
851
  const rotation = oldState.metadata?.refreshRotation ?? (this.refreshConfig ? this.refreshConfig.rotation ?? "sliding" : "always");
849
852
  switch (rotation) {
850
- case "none": return await this.refreshNone(oldState, refreshToken, now);
853
+ case "none": return await this.refreshNone(oldState, refreshToken, found.key, now);
851
854
  case "always": return await this.refreshAlways(oldState, refreshToken, found.key, now);
852
855
  case "sliding": return await this.refreshSliding(oldState, refreshToken, found.key, now);
853
856
  default: throw new AuthError("INVALID_CONFIG", `Unknown rotation: ${String(rotation)}`);
854
857
  }
855
858
  }
856
- async refreshNone(oldState, refreshToken, now) {
859
+ async refreshNone(oldState, refreshToken, key, now) {
857
860
  const newAccess = await this.issueAccessFromRefresh(oldState, now);
861
+ await this.assertStillLive(key, [newAccess.token]);
858
862
  return {
859
863
  accessToken: newAccess.token,
860
864
  accessExpiresAt: newAccess.expiresAt,
@@ -956,7 +960,14 @@ var AuthCredential = class {
956
960
  async revokeAllForUser(userId) {
957
961
  this.validated?.deleteUser(userId);
958
962
  try {
959
- return await this.store.revokeAllForUser(userId);
963
+ const listForUser = this.store.listForUser?.bind(this.store);
964
+ let revoked = await this.store.revokeAllForUser(userId);
965
+ if (!listForUser) return revoked;
966
+ for (let pass = 1; (await listForUser(userId)).length > 0; pass++) {
967
+ revoked += await this.store.revokeAllForUser(userId);
968
+ if (pass >= MAX_REVOKE_PASSES) throw revocationDidNotConverge();
969
+ }
970
+ return revoked;
960
971
  } finally {
961
972
  this.validated?.deleteUser(userId);
962
973
  }
@@ -1031,14 +1042,21 @@ var AuthCredential = class {
1031
1042
  return Promise.all(sessions.map((s) => Promise.resolve(enrich(s))));
1032
1043
  }
1033
1044
  /**
1045
+ * Whether the store can enumerate a user's credentials — i.e. whether
1046
+ * {@link listSessions}, {@link revokeSession} and {@link revokeOtherSessions}
1047
+ * act at all. `false` for stateless stores (JWT, encapsulated), where those
1048
+ * are no-ops and {@link revokeAllForUser} is the only bulk revocation.
1049
+ */
1050
+ get canEnumerateSessions() {
1051
+ return this.store.listForUser !== void 0;
1052
+ }
1053
+ /**
1034
1054
  * Revoke a single session — every token in its family (access + refresh +
1035
1055
  * rotations). No-op for stores that can't enumerate. Other sessions keep
1036
1056
  * validating.
1037
1057
  */
1038
1058
  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)));
1059
+ await this.sweepUntilEmpty(userId, (key) => key === sessionId);
1042
1060
  }
1043
1061
  /**
1044
1062
  * Revoke every session for the user EXCEPT `keepSessionId` ("log out
@@ -1046,18 +1064,39 @@ var AuthCredential = class {
1046
1064
  * (returns 0) for stores that can't enumerate.
1047
1065
  */
1048
1066
  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));
1067
+ return (await this.sweepUntilEmpty(userId, (key) => key !== keepSessionId)).size;
1068
+ }
1069
+ /**
1070
+ * Revoke every credential of `userId` whose session key matches, repeating
1071
+ * list-then-delete until a listing finds no match; returns the distinct
1072
+ * session keys revoked. No-op on stores that can't enumerate.
1073
+ *
1074
+ * Paired with the post-mint re-check in {@link assertStillLive}, this closes
1075
+ * the race with refreshes in flight. A refresh re-reads the row it was
1076
+ * minted from AFTER persisting its new rows, and revokes them if that row is
1077
+ * gone. So a row surviving the final (empty) listing would have to be minted
1078
+ * after that listing off a parent still alive after it — a parent that, not
1079
+ * being listed, was itself minted after it, and so on down a chain that
1080
+ * must start at a row that existed before the listing: a contradiction.
1081
+ * Typically two passes (the second finds nothing); capped, failing loudly
1082
+ * rather than spinning against a refresh loop.
1083
+ */
1084
+ async sweepUntilEmpty(userId, matches) {
1085
+ const revoked = /* @__PURE__ */ new Set();
1086
+ const listForUser = this.store.listForUser?.bind(this.store);
1087
+ if (!listForUser) return revoked;
1088
+ for (let pass = 0;; pass++) {
1089
+ const revokes = [];
1090
+ for (const entry of await listForUser(userId)) {
1091
+ const key = this.sessionKeyOf(entry);
1092
+ if (!matches(key)) continue;
1093
+ revoked.add(key);
1094
+ revokes.push(this.revokeKey(entry.token));
1095
+ }
1096
+ if (revokes.length === 0) return revoked;
1097
+ await Promise.all(revokes);
1098
+ if (pass >= MAX_REVOKE_PASSES) throw revocationDidNotConverge();
1058
1099
  }
1059
- await Promise.all(revokes);
1060
- return revokedSessions.size;
1061
1100
  }
1062
1101
  /**
1063
1102
  * Derive a stable 32-byte key from this credential's underlying store secret,
@@ -1123,6 +1162,7 @@ var AuthCredential = class {
1123
1162
  });
1124
1163
  const access = await this.issueAccessFromRefresh(oldRefreshState, now);
1125
1164
  const newRefreshToken = await this.put(newRefreshState, refreshTtl);
1165
+ let liveKey = oldKey;
1126
1166
  if (rotateOld) {
1127
1167
  const rotatedState = {
1128
1168
  ...oldRefreshState,
@@ -1134,8 +1174,9 @@ var AuthCredential = class {
1134
1174
  refreshExpiresAt
1135
1175
  }, oldRefreshToken)
1136
1176
  };
1137
- await this.store.update(oldKey, rotatedState);
1177
+ liveKey = await this.store.update(oldKey, rotatedState);
1138
1178
  }
1179
+ await this.assertStillLive(liveKey, [access.token, newRefreshToken]);
1139
1180
  return {
1140
1181
  accessToken: access.token,
1141
1182
  accessExpiresAt: access.expiresAt,
@@ -1145,6 +1186,20 @@ var AuthCredential = class {
1145
1186
  };
1146
1187
  }
1147
1188
  /**
1189
+ * Post-mint half of the revocation protocol (see {@link sweepUntilEmpty}): after
1190
+ * a refresh persisted new credentials, the refresh row it was minted from
1191
+ * must still exist. If a revocation deleted it meanwhile, the new
1192
+ * credentials belong to a revoked session — revoke them and refuse.
1193
+ * Stateful stores only: a stateless refresh consumed (or keeps) a
1194
+ * self-contained token, and its revocation epoch already rejects a mint
1195
+ * stamped before the revocation.
1196
+ */
1197
+ async assertStillLive(oldKey, minted) {
1198
+ if (!this.store.listForUser || await this.store.retrieve(oldKey)) return;
1199
+ await Promise.allSettled(minted.map((token) => this.revoke(token)));
1200
+ throw new AuthError("INVALID_TOKEN");
1201
+ }
1202
+ /**
1148
1203
  * Under `hashAtRest` the successor pair is stored encrypted with a key
1149
1204
  * derived from the old refresh token — only a holder of that token (the
1150
1205
  * grace-window re-presentation) can read the pair back.
@@ -1222,8 +1277,7 @@ var AuthCredential = class {
1222
1277
  });
1223
1278
  }
1224
1279
  };
1225
- //#endregion
1226
- //#region src/rate-limit/rules.ts
1280
+ // src/rate-limit/rules.ts
1227
1281
  const DEFAULT_RATE_LIMIT_MESSAGE = "Too many requests. Please try again in {{delta}}.";
1228
1282
  const DURATION_UNITS = {
1229
1283
  ms: 1,
@@ -1300,8 +1354,7 @@ function parseRateLimitRule(input) {
1300
1354
  function renderRateLimitMessage(template, rule, retryAfterMs) {
1301
1355
  return template.replaceAll("{{limit}}", String(rule.limit)).replaceAll("{{max}}", String(rule.limit)).replaceAll("{{window}}", formatDurationMs(rule.window)).replaceAll("{{delta}}", formatDurationMs(retryAfterMs));
1302
1356
  }
1303
- //#endregion
1304
- //#region src/rate-limit/store.ts
1357
+ // src/rate-limit/store.ts
1305
1358
  /**
1306
1359
  * In-memory `RateLimitStore` — the zero-config default (single process only).
1307
1360
  * Lazy-evicts expired counters on access, and sweeps expired counters itself
@@ -1405,8 +1458,7 @@ var RateLimitStoreMemory = class {
1405
1458
  };
1406
1459
  /** Smallest map size an amortized expiry sweep runs at. */
1407
1460
  const MIN_SWEEP_SIZE = 1024;
1408
- //#endregion
1409
- //#region src/rate-limit/rate-limiter.ts
1461
+ // src/rate-limit/rate-limiter.ts
1410
1462
  /**
1411
1463
  * Fixed-window rate limiter with window-aligned keys (RL.spec.md §4.2).
1412
1464
  *
@@ -1490,11 +1542,9 @@ var RateLimiter = class {
1490
1542
  };
1491
1543
  }
1492
1544
  };
1493
- //#endregion
1494
- //#region src/magic-link.ts
1545
+ // src/magic-link.ts
1495
1546
  /** A magic-link token is a plain {@link generateOpaqueToken} mint. */
1496
1547
  function generateMagicLinkToken() {
1497
1548
  return generateOpaqueToken();
1498
1549
  }
1499
- //#endregion
1500
1550
  export { AuthCredential, AuthError, CredentialStoreEncapsulated, CredentialStoreJwt, CredentialStoreMemory, DEFAULT_RATE_LIMIT_MESSAGE, DenylistStoreMemory, RateLimitStoreMemory, RateLimiter, defaultClock, formatDurationMs, generateMagicLinkToken, generateOpaqueToken, parseDurationMs, parseRateLimitRule, pickGoverning, renderRateLimitMessage };
@@ -1,5 +1,5 @@
1
1
  import { randomBytes } from "node:crypto";
2
- //#region src/utils/opaque-token.ts
2
+ // src/utils/opaque-token.ts
3
3
  /**
4
4
  * 32 bytes of CSPRNG entropy (256 bits) encoded as base64url — 43 chars,
5
5
  * URL-safe. The single mint for every opaque bearer-style secret in the stack
@@ -9,5 +9,4 @@ import { randomBytes } from "node:crypto";
9
9
  function generateOpaqueToken() {
10
10
  return randomBytes(32).toString("base64url");
11
11
  }
12
- //#endregion
13
12
  export { generateOpaqueToken as t };
@@ -1,5 +1,5 @@
1
1
  let node_crypto = require("node:crypto");
2
- //#region src/utils/opaque-token.ts
2
+ // src/utils/opaque-token.ts
3
3
  /**
4
4
  * 32 bytes of CSPRNG entropy (256 bits) encoded as base64url — 43 chars,
5
5
  * URL-safe. The single mint for every opaque bearer-style secret in the stack
@@ -9,7 +9,6 @@ let node_crypto = require("node:crypto");
9
9
  function generateOpaqueToken() {
10
10
  return (0, node_crypto.randomBytes)(32).toString("base64url");
11
11
  }
12
- //#endregion
13
12
  Object.defineProperty(exports, "generateOpaqueToken", {
14
13
  enumerable: true,
15
14
  get: function() {
@@ -1,4 +1,4 @@
1
- //#region src/errors.ts
1
+ // src/errors.ts
2
2
  const defaultMessages = {
3
3
  INVALID_TOKEN: "Invalid token",
4
4
  TOKEN_EXPIRED: "Token has expired",
@@ -18,8 +18,7 @@ var AuthError = class extends Error {
18
18
  this.details = details;
19
19
  }
20
20
  };
21
- //#endregion
22
- //#region src/credential/payload.ts
21
+ // src/credential/payload.ts
23
22
  const ENVELOPE_KEYS = new Set(Object.keys({
24
23
  userId: true,
25
24
  issuedAt: true,
@@ -45,7 +44,6 @@ function credentialPayloadOf(state) {
45
44
  for (const [key, value] of Object.entries(state)) if (!ENVELOPE_KEYS.has(key)) out[key] = value;
46
45
  return out;
47
46
  }
48
- //#endregion
49
47
  Object.defineProperty(exports, "AuthError", {
50
48
  enumerable: true,
51
49
  get: function() {
@@ -1,4 +1,4 @@
1
- //#region src/errors.ts
1
+ // src/errors.ts
2
2
  const defaultMessages = {
3
3
  INVALID_TOKEN: "Invalid token",
4
4
  TOKEN_EXPIRED: "Token has expired",
@@ -18,8 +18,7 @@ var AuthError = class extends Error {
18
18
  this.details = details;
19
19
  }
20
20
  };
21
- //#endregion
22
- //#region src/credential/payload.ts
21
+ // src/credential/payload.ts
23
22
  const ENVELOPE_KEYS = new Set(Object.keys({
24
23
  userId: true,
25
24
  issuedAt: true,
@@ -45,5 +44,4 @@ function credentialPayloadOf(state) {
45
44
  for (const [key, value] of Object.entries(state)) if (!ENVELOPE_KEYS.has(key)) out[key] = value;
46
45
  return out;
47
46
  }
48
- //#endregion
49
47
  export { AuthError as n, credentialPayloadOf as t };
package/dist/redis.cjs CHANGED
@@ -1,6 +1,6 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  let node_crypto = require("node:crypto");
3
- //#region src/redis/index.ts
3
+ // src/redis/index.ts
4
4
  /**
5
5
  * Redis-backed `CredentialStore`. Token id is a random UUID (the same
6
6
  * scheme as `CredentialStoreMemory`) — the token is opaque to the client.
@@ -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);
@@ -189,7 +191,6 @@ var RateLimitStoreRedis = class {
189
191
  await this.redis.del(this.key(key));
190
192
  }
191
193
  };
192
- //#endregion
193
194
  exports.CredentialStoreRedis = CredentialStoreRedis;
194
195
  exports.DenylistStoreRedis = DenylistStoreRedis;
195
196
  exports.RateLimitStoreRedis = RateLimitStoreRedis;
package/dist/redis.d.cts CHANGED
@@ -1,6 +1,5 @@
1
- import { i as DenylistStore, r as CredentialStore, s as CredentialState } from "./clock-CzAaCoZ5.cjs";
2
- import { t as RateLimitStore } from "./store-BaFYDHxn.cjs";
3
- //#region src/redis/index.d.ts
1
+ import { i as DenylistStore, r as CredentialStore, s as CredentialState } from "./clock-hTHoZ2vA.cjs";
2
+ import { t as RateLimitStore } from "./store-D9CcbcBp.cjs";
4
3
  /**
5
4
  * Structural Redis client. Covers the exact set of commands used by
6
5
  * `CredentialStoreRedis`, `DenylistStoreRedis`, and `RateLimitStoreRedis` —
@@ -19,7 +18,7 @@ import { t as RateLimitStore } from "./store-BaFYDHxn.cjs";
19
18
  *
20
19
  * ```ts
21
20
  * const redisLike: RedisLike = {
22
- * set: (k, v, _px, ttlMs) => client.set(k, v, ttlMs !== undefined ? { PX: ttlMs } : {}),
21
+ * set: (k, v, _px, ttlMs, xx) => client.set(k, v, { PX: ttlMs, ...(xx && { XX: true }) }),
23
22
  * get: (k) => client.get(k),
24
23
  * del: (...k) => client.del(k),
25
24
  * exists: (k) => client.exists(k),
@@ -46,17 +45,29 @@ import { t as RateLimitStore } from "./store-BaFYDHxn.cjs";
46
45
  * overload (it collides with the `set(key, value, cb?)` overload
47
46
  * instead), which is exactly what broke structural assignment before.
48
47
  * Every adapter call site already passes all four arguments.
48
+ * 3. The conditional `set(key, value, "PX", ms, "XX")` overload is REQUIRED
49
+ * (since 0.2.1): `CredentialStoreRedis` rewrites existing credentials
50
+ * (rotation stamp, `lastSeenAt`) only if the key still exists, so a write
51
+ * racing a revocation can never re-create a deleted credential. An
52
+ * adapter must forward `XX` and resolve `null` when the key is missing.
53
+ * ioredis exposes exactly this overload.
49
54
  *
50
55
  * Return types are chosen as a supertype of what real clients resolve, so an
51
56
  * ioredis client stays assignable while the types remain useful to callers:
52
- * - `set` returns `string | null` (ioredis resolves `"OK"`)
57
+ * - `set` returns `string | null` (ioredis resolves `"OK"`, or `null` when
58
+ * an `XX` write found no key)
53
59
  * - `del` / `pexpire` / `exists` / `incr` / `sadd` / `srem` return `number`
54
60
  * - `get` returns `string | null`
55
61
  * - `smembers` returns `string[]`
56
62
  */
57
- interface RedisLike {
63
+ export interface RedisLike {
58
64
  /** `SET key value PX ms` — `mode`/`ttlMs` are a required pair (see above). */
59
65
  set(key: string, value: string, mode: "PX", ttlMs: number): Promise<string | null>;
66
+ /**
67
+ * `SET key value PX ms XX` — write only if `key` exists; resolves `null`
68
+ * (and writes nothing) when it doesn't. Required since 0.2.1.
69
+ */
70
+ set(key: string, value: string, mode: "PX", ttlMs: number, condition: "XX"): Promise<string | null>;
60
71
  get(key: string): Promise<string | null>;
61
72
  del(...keys: string[]): Promise<number>;
62
73
  exists(key: string): Promise<number>;
@@ -90,7 +101,7 @@ interface RedisCredentialStoreOptions {
90
101
  * so Redis evicts it on expiry. The user-index set is NOT TTL-bounded — we
91
102
  * lazily prune dead members on `listForUser` and `revokeAllForUser`.
92
103
  */
93
- declare class CredentialStoreRedis<TPayload extends object = object> implements CredentialStore<TPayload> {
104
+ export declare class CredentialStoreRedis<TPayload extends object = object> implements CredentialStore<TPayload> {
94
105
  private readonly redis;
95
106
  private readonly prefix;
96
107
  constructor(opts: RedisCredentialStoreOptions);
@@ -118,7 +129,7 @@ interface RedisDenylistStoreOptions {
118
129
  * to `expiresAt - now`, so Redis self-evicts the entry once the underlying
119
130
  * token would have expired anyway. `cleanup` is a no-op for that reason.
120
131
  */
121
- declare class DenylistStoreRedis implements DenylistStore {
132
+ export declare class DenylistStoreRedis implements DenylistStore {
122
133
  private readonly redis;
123
134
  private readonly prefix;
124
135
  constructor(opts: RedisDenylistStoreOptions);
@@ -141,7 +152,7 @@ interface RedisRateLimitStoreOptions {
141
152
  * `incr` and `pexpire`, the TTL-less key leaks a few bytes but is never
142
153
  * counted again.
143
154
  */
144
- declare class RateLimitStoreRedis implements RateLimitStore {
155
+ export declare class RateLimitStoreRedis implements RateLimitStore {
145
156
  private readonly redis;
146
157
  private readonly prefix;
147
158
  constructor(opts: RedisRateLimitStoreOptions);
@@ -151,5 +162,4 @@ declare class RateLimitStoreRedis implements RateLimitStore {
151
162
  expire(key: string, ttlMs: number): Promise<void>;
152
163
  reset(key: string): Promise<void>;
153
164
  }
154
- //#endregion
155
- export { CredentialStoreRedis, DenylistStoreRedis, RateLimitStoreRedis, RedisLike };
165
+ export {};
package/dist/redis.d.mts CHANGED
@@ -1,6 +1,5 @@
1
- import { i as DenylistStore, r as CredentialStore, s as CredentialState } from "./clock-CzAaCoZ5.mjs";
2
- import { t as RateLimitStore } from "./store-h-bLOAaS.mjs";
3
- //#region src/redis/index.d.ts
1
+ import { i as DenylistStore, r as CredentialStore, s as CredentialState } from "./clock-hTHoZ2vA.mjs";
2
+ import { t as RateLimitStore } from "./store-BXxX8sUP.mjs";
4
3
  /**
5
4
  * Structural Redis client. Covers the exact set of commands used by
6
5
  * `CredentialStoreRedis`, `DenylistStoreRedis`, and `RateLimitStoreRedis` —
@@ -19,7 +18,7 @@ import { t as RateLimitStore } from "./store-h-bLOAaS.mjs";
19
18
  *
20
19
  * ```ts
21
20
  * const redisLike: RedisLike = {
22
- * set: (k, v, _px, ttlMs) => client.set(k, v, ttlMs !== undefined ? { PX: ttlMs } : {}),
21
+ * set: (k, v, _px, ttlMs, xx) => client.set(k, v, { PX: ttlMs, ...(xx && { XX: true }) }),
23
22
  * get: (k) => client.get(k),
24
23
  * del: (...k) => client.del(k),
25
24
  * exists: (k) => client.exists(k),
@@ -46,17 +45,29 @@ import { t as RateLimitStore } from "./store-h-bLOAaS.mjs";
46
45
  * overload (it collides with the `set(key, value, cb?)` overload
47
46
  * instead), which is exactly what broke structural assignment before.
48
47
  * Every adapter call site already passes all four arguments.
48
+ * 3. The conditional `set(key, value, "PX", ms, "XX")` overload is REQUIRED
49
+ * (since 0.2.1): `CredentialStoreRedis` rewrites existing credentials
50
+ * (rotation stamp, `lastSeenAt`) only if the key still exists, so a write
51
+ * racing a revocation can never re-create a deleted credential. An
52
+ * adapter must forward `XX` and resolve `null` when the key is missing.
53
+ * ioredis exposes exactly this overload.
49
54
  *
50
55
  * Return types are chosen as a supertype of what real clients resolve, so an
51
56
  * ioredis client stays assignable while the types remain useful to callers:
52
- * - `set` returns `string | null` (ioredis resolves `"OK"`)
57
+ * - `set` returns `string | null` (ioredis resolves `"OK"`, or `null` when
58
+ * an `XX` write found no key)
53
59
  * - `del` / `pexpire` / `exists` / `incr` / `sadd` / `srem` return `number`
54
60
  * - `get` returns `string | null`
55
61
  * - `smembers` returns `string[]`
56
62
  */
57
- interface RedisLike {
63
+ export interface RedisLike {
58
64
  /** `SET key value PX ms` — `mode`/`ttlMs` are a required pair (see above). */
59
65
  set(key: string, value: string, mode: "PX", ttlMs: number): Promise<string | null>;
66
+ /**
67
+ * `SET key value PX ms XX` — write only if `key` exists; resolves `null`
68
+ * (and writes nothing) when it doesn't. Required since 0.2.1.
69
+ */
70
+ set(key: string, value: string, mode: "PX", ttlMs: number, condition: "XX"): Promise<string | null>;
60
71
  get(key: string): Promise<string | null>;
61
72
  del(...keys: string[]): Promise<number>;
62
73
  exists(key: string): Promise<number>;
@@ -90,7 +101,7 @@ interface RedisCredentialStoreOptions {
90
101
  * so Redis evicts it on expiry. The user-index set is NOT TTL-bounded — we
91
102
  * lazily prune dead members on `listForUser` and `revokeAllForUser`.
92
103
  */
93
- declare class CredentialStoreRedis<TPayload extends object = object> implements CredentialStore<TPayload> {
104
+ export declare class CredentialStoreRedis<TPayload extends object = object> implements CredentialStore<TPayload> {
94
105
  private readonly redis;
95
106
  private readonly prefix;
96
107
  constructor(opts: RedisCredentialStoreOptions);
@@ -118,7 +129,7 @@ interface RedisDenylistStoreOptions {
118
129
  * to `expiresAt - now`, so Redis self-evicts the entry once the underlying
119
130
  * token would have expired anyway. `cleanup` is a no-op for that reason.
120
131
  */
121
- declare class DenylistStoreRedis implements DenylistStore {
132
+ export declare class DenylistStoreRedis implements DenylistStore {
122
133
  private readonly redis;
123
134
  private readonly prefix;
124
135
  constructor(opts: RedisDenylistStoreOptions);
@@ -141,7 +152,7 @@ interface RedisRateLimitStoreOptions {
141
152
  * `incr` and `pexpire`, the TTL-less key leaks a few bytes but is never
142
153
  * counted again.
143
154
  */
144
- declare class RateLimitStoreRedis implements RateLimitStore {
155
+ export declare class RateLimitStoreRedis implements RateLimitStore {
145
156
  private readonly redis;
146
157
  private readonly prefix;
147
158
  constructor(opts: RedisRateLimitStoreOptions);
@@ -151,5 +162,4 @@ declare class RateLimitStoreRedis implements RateLimitStore {
151
162
  expire(key: string, ttlMs: number): Promise<void>;
152
163
  reset(key: string): Promise<void>;
153
164
  }
154
- //#endregion
155
- export { CredentialStoreRedis, DenylistStoreRedis, RateLimitStoreRedis, RedisLike };
165
+ export {};
package/dist/redis.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  import { randomUUID } from "node:crypto";
2
- //#region src/redis/index.ts
2
+ // src/redis/index.ts
3
3
  /**
4
4
  * Redis-backed `CredentialStore`. Token id is a random UUID (the same
5
5
  * scheme as `CredentialStoreMemory`) — the token is opaque to the client.
@@ -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);
@@ -188,5 +190,4 @@ var RateLimitStoreRedis = class {
188
190
  await this.redis.del(this.key(key));
189
191
  }
190
192
  };
191
- //#endregion
192
193
  export { CredentialStoreRedis, DenylistStoreRedis, RateLimitStoreRedis };
@@ -1,5 +1,4 @@
1
- import { t as Clock } from "./clock-CzAaCoZ5.cjs";
2
- //#region src/rate-limit/store.d.ts
1
+ import { t as Clock } from "./clock-hTHoZ2vA.mjs";
3
2
  /**
4
3
  * Storage contract for the fixed-window limiter (RL.spec.md §4.3).
5
4
  *
@@ -65,5 +64,4 @@ declare class RateLimitStoreMemory implements RateLimitStore {
65
64
  cleanup(): Promise<number>;
66
65
  private sweep;
67
66
  }
68
- //#endregion
69
67
  export { RateLimitStoreMemory as n, RateLimitStore as t };
@@ -1,5 +1,4 @@
1
- import { t as Clock } from "./clock-CzAaCoZ5.mjs";
2
- //#region src/rate-limit/store.d.ts
1
+ import { t as Clock } from "./clock-hTHoZ2vA.cjs";
3
2
  /**
4
3
  * Storage contract for the fixed-window limiter (RL.spec.md §4.3).
5
4
  *
@@ -65,5 +64,4 @@ declare class RateLimitStoreMemory implements RateLimitStore {
65
64
  cleanup(): Promise<number>;
66
65
  private sweep;
67
66
  }
68
- //#endregion
69
67
  export { RateLimitStoreMemory as n, RateLimitStore as t };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aooth/auth",
3
- "version": "0.2.0",
3
+ "version": "0.2.2",
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.2"
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.3",
111
+ "@atscript/db": "^0.1.167",
112
+ "@atscript/db-sql-tools": "^0.1.167",
113
+ "@atscript/db-sqlite": "^0.1.167",
114
+ "@atscript/typescript": "^0.2.3",
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.3"
120
120
  },
121
121
  "peerDependencies": {
122
- "@atscript/db": "^0.1.164"
122
+ "@atscript/db": "^0.1.167"
123
123
  },
124
124
  "peerDependenciesMeta": {
125
125
  "@atscript/db": {