@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.cjs CHANGED
@@ -1,10 +1,10 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_payload = require("./payload-C1cQW7p_.cjs");
3
- const require_clock = require("./clock-Bl-H3eqE.cjs");
4
- const require_opaque_token = require("./opaque-token-CaZgD2i6.cjs");
2
+ const require_payload = require("./payload-CqQH88C6.cjs");
3
+ const require_clock = require("./clock-BcBMqB9g.cjs");
4
+ const require_opaque_token = require("./opaque-token-BLuVHSVJ.cjs");
5
5
  let node_crypto = require("node:crypto");
6
6
  let jose = require("jose");
7
- //#region src/stores/memory.ts
7
+ // src/stores/memory.ts
8
8
  /**
9
9
  * In-memory implementation of CredentialStore using random opaque token IDs.
10
10
  *
@@ -119,8 +119,7 @@ var CredentialStoreMemory = class {
119
119
  if (set.size === 0) this.byUser.delete(userId);
120
120
  }
121
121
  };
122
- //#endregion
123
- //#region src/stores/denylist-memory.ts
122
+ // src/stores/denylist-memory.ts
124
123
  /**
125
124
  * In-memory denylist for stateless revocation.
126
125
  *
@@ -168,15 +167,13 @@ var DenylistStoreMemory = class {
168
167
  };
169
168
  /** Smallest map size an amortized expiry sweep runs at. */
170
169
  const MIN_SWEEP_SIZE$2 = 1024;
171
- //#endregion
172
- //#region src/stores/derive-subkey.ts
170
+ // src/stores/derive-subkey.ts
173
171
  const SUBKEY_SALT = Buffer.from("aooth/credential-store/subkey-v1");
174
172
  /** HKDF-SHA256 a stable 32-byte subkey from symmetric key material + a label. */
175
173
  function hkdfSubkey(ikm, label) {
176
174
  return Buffer.from((0, node_crypto.hkdfSync)("sha256", ikm, SUBKEY_SALT, Buffer.from(label, "utf8"), 32));
177
175
  }
178
- //#endregion
179
- //#region src/stores/jwt.ts
176
+ // src/stores/jwt.ts
180
177
  const HS_ALGS = /* @__PURE__ */ new Set([
181
178
  "HS256",
182
179
  "HS384",
@@ -360,8 +357,7 @@ function normalizeSecret(secret) {
360
357
  if (typeof secret === "string") return new TextEncoder().encode(secret);
361
358
  return secret;
362
359
  }
363
- //#endregion
364
- //#region src/stores/encapsulated.ts
360
+ // src/stores/encapsulated.ts
365
361
  const KEY_LEN = 32;
366
362
  const IV_LEN = 12;
367
363
  const TAG_LEN = 16;
@@ -510,11 +506,18 @@ function stripJti(payload) {
510
506
  const { jti: _jti, ...rest } = payload;
511
507
  return rest;
512
508
  }
513
- //#endregion
514
- //#region src/credential/auth-credential.ts
515
- const DEFAULT_ACCESS_TTL = 3600 * 1e3;
509
+ // src/credential/auth-credential.ts
510
+ const DEFAULT_ACCESS_TTL = 36e5;
516
511
  const DEFAULT_ROTATION_GRACE_MS = 3e4;
517
512
  /**
513
+ * Upper bound on list-then-delete passes in one revocation. Two is the norm;
514
+ * more only while refreshes keep minting off the session being revoked.
515
+ */
516
+ const MAX_REVOKE_PASSES = 8;
517
+ function revocationDidNotConverge() {
518
+ return /* @__PURE__ */ new Error(`aooth: revocation did not converge after ${MAX_REVOKE_PASSES} passes (refreshes kept minting); retry it`);
519
+ }
520
+ /**
518
521
  * Stable, non-reversible fingerprint of a token used as `credentialId` in
519
522
  * {@link AuthContext}. Hashing avoids leaking a live bearer token whenever
520
523
  * downstream consumers log or persist `ctx.credentialId`.
@@ -848,14 +851,15 @@ var AuthCredential = class {
848
851
  await opts?.guard?.(oldState);
849
852
  const rotation = oldState.metadata?.refreshRotation ?? (this.refreshConfig ? this.refreshConfig.rotation ?? "sliding" : "always");
850
853
  switch (rotation) {
851
- case "none": return await this.refreshNone(oldState, refreshToken, now);
854
+ case "none": return await this.refreshNone(oldState, refreshToken, found.key, now);
852
855
  case "always": return await this.refreshAlways(oldState, refreshToken, found.key, now);
853
856
  case "sliding": return await this.refreshSliding(oldState, refreshToken, found.key, now);
854
857
  default: throw new require_payload.AuthError("INVALID_CONFIG", `Unknown rotation: ${String(rotation)}`);
855
858
  }
856
859
  }
857
- async refreshNone(oldState, refreshToken, now) {
860
+ async refreshNone(oldState, refreshToken, key, now) {
858
861
  const newAccess = await this.issueAccessFromRefresh(oldState, now);
862
+ await this.assertStillLive(key, [newAccess.token]);
859
863
  return {
860
864
  accessToken: newAccess.token,
861
865
  accessExpiresAt: newAccess.expiresAt,
@@ -957,7 +961,14 @@ var AuthCredential = class {
957
961
  async revokeAllForUser(userId) {
958
962
  this.validated?.deleteUser(userId);
959
963
  try {
960
- return await this.store.revokeAllForUser(userId);
964
+ const listForUser = this.store.listForUser?.bind(this.store);
965
+ let revoked = await this.store.revokeAllForUser(userId);
966
+ if (!listForUser) return revoked;
967
+ for (let pass = 1; (await listForUser(userId)).length > 0; pass++) {
968
+ revoked += await this.store.revokeAllForUser(userId);
969
+ if (pass >= MAX_REVOKE_PASSES) throw revocationDidNotConverge();
970
+ }
971
+ return revoked;
961
972
  } finally {
962
973
  this.validated?.deleteUser(userId);
963
974
  }
@@ -1032,14 +1043,21 @@ var AuthCredential = class {
1032
1043
  return Promise.all(sessions.map((s) => Promise.resolve(enrich(s))));
1033
1044
  }
1034
1045
  /**
1046
+ * Whether the store can enumerate a user's credentials — i.e. whether
1047
+ * {@link listSessions}, {@link revokeSession} and {@link revokeOtherSessions}
1048
+ * act at all. `false` for stateless stores (JWT, encapsulated), where those
1049
+ * are no-ops and {@link revokeAllForUser} is the only bulk revocation.
1050
+ */
1051
+ get canEnumerateSessions() {
1052
+ return this.store.listForUser !== void 0;
1053
+ }
1054
+ /**
1035
1055
  * Revoke a single session — every token in its family (access + refresh +
1036
1056
  * rotations). No-op for stores that can't enumerate. Other sessions keep
1037
1057
  * validating.
1038
1058
  */
1039
1059
  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)));
1060
+ await this.sweepUntilEmpty(userId, (key) => key === sessionId);
1043
1061
  }
1044
1062
  /**
1045
1063
  * Revoke every session for the user EXCEPT `keepSessionId` ("log out
@@ -1047,18 +1065,39 @@ var AuthCredential = class {
1047
1065
  * (returns 0) for stores that can't enumerate.
1048
1066
  */
1049
1067
  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));
1068
+ return (await this.sweepUntilEmpty(userId, (key) => key !== keepSessionId)).size;
1069
+ }
1070
+ /**
1071
+ * Revoke every credential of `userId` whose session key matches, repeating
1072
+ * list-then-delete until a listing finds no match; returns the distinct
1073
+ * session keys revoked. No-op on stores that can't enumerate.
1074
+ *
1075
+ * Paired with the post-mint re-check in {@link assertStillLive}, this closes
1076
+ * the race with refreshes in flight. A refresh re-reads the row it was
1077
+ * minted from AFTER persisting its new rows, and revokes them if that row is
1078
+ * gone. So a row surviving the final (empty) listing would have to be minted
1079
+ * after that listing off a parent still alive after it — a parent that, not
1080
+ * being listed, was itself minted after it, and so on down a chain that
1081
+ * must start at a row that existed before the listing: a contradiction.
1082
+ * Typically two passes (the second finds nothing); capped, failing loudly
1083
+ * rather than spinning against a refresh loop.
1084
+ */
1085
+ async sweepUntilEmpty(userId, matches) {
1086
+ const revoked = /* @__PURE__ */ new Set();
1087
+ const listForUser = this.store.listForUser?.bind(this.store);
1088
+ if (!listForUser) return revoked;
1089
+ for (let pass = 0;; pass++) {
1090
+ const revokes = [];
1091
+ for (const entry of await listForUser(userId)) {
1092
+ const key = this.sessionKeyOf(entry);
1093
+ if (!matches(key)) continue;
1094
+ revoked.add(key);
1095
+ revokes.push(this.revokeKey(entry.token));
1096
+ }
1097
+ if (revokes.length === 0) return revoked;
1098
+ await Promise.all(revokes);
1099
+ if (pass >= MAX_REVOKE_PASSES) throw revocationDidNotConverge();
1059
1100
  }
1060
- await Promise.all(revokes);
1061
- return revokedSessions.size;
1062
1101
  }
1063
1102
  /**
1064
1103
  * Derive a stable 32-byte key from this credential's underlying store secret,
@@ -1124,6 +1163,7 @@ var AuthCredential = class {
1124
1163
  });
1125
1164
  const access = await this.issueAccessFromRefresh(oldRefreshState, now);
1126
1165
  const newRefreshToken = await this.put(newRefreshState, refreshTtl);
1166
+ let liveKey = oldKey;
1127
1167
  if (rotateOld) {
1128
1168
  const rotatedState = {
1129
1169
  ...oldRefreshState,
@@ -1135,8 +1175,9 @@ var AuthCredential = class {
1135
1175
  refreshExpiresAt
1136
1176
  }, oldRefreshToken)
1137
1177
  };
1138
- await this.store.update(oldKey, rotatedState);
1178
+ liveKey = await this.store.update(oldKey, rotatedState);
1139
1179
  }
1180
+ await this.assertStillLive(liveKey, [access.token, newRefreshToken]);
1140
1181
  return {
1141
1182
  accessToken: access.token,
1142
1183
  accessExpiresAt: access.expiresAt,
@@ -1146,6 +1187,20 @@ var AuthCredential = class {
1146
1187
  };
1147
1188
  }
1148
1189
  /**
1190
+ * Post-mint half of the revocation protocol (see {@link sweepUntilEmpty}): after
1191
+ * a refresh persisted new credentials, the refresh row it was minted from
1192
+ * must still exist. If a revocation deleted it meanwhile, the new
1193
+ * credentials belong to a revoked session — revoke them and refuse.
1194
+ * Stateful stores only: a stateless refresh consumed (or keeps) a
1195
+ * self-contained token, and its revocation epoch already rejects a mint
1196
+ * stamped before the revocation.
1197
+ */
1198
+ async assertStillLive(oldKey, minted) {
1199
+ if (!this.store.listForUser || await this.store.retrieve(oldKey)) return;
1200
+ await Promise.allSettled(minted.map((token) => this.revoke(token)));
1201
+ throw new require_payload.AuthError("INVALID_TOKEN");
1202
+ }
1203
+ /**
1149
1204
  * Under `hashAtRest` the successor pair is stored encrypted with a key
1150
1205
  * derived from the old refresh token — only a holder of that token (the
1151
1206
  * grace-window re-presentation) can read the pair back.
@@ -1223,8 +1278,7 @@ var AuthCredential = class {
1223
1278
  });
1224
1279
  }
1225
1280
  };
1226
- //#endregion
1227
- //#region src/rate-limit/rules.ts
1281
+ // src/rate-limit/rules.ts
1228
1282
  const DEFAULT_RATE_LIMIT_MESSAGE = "Too many requests. Please try again in {{delta}}.";
1229
1283
  const DURATION_UNITS = {
1230
1284
  ms: 1,
@@ -1301,8 +1355,7 @@ function parseRateLimitRule(input) {
1301
1355
  function renderRateLimitMessage(template, rule, retryAfterMs) {
1302
1356
  return template.replaceAll("{{limit}}", String(rule.limit)).replaceAll("{{max}}", String(rule.limit)).replaceAll("{{window}}", formatDurationMs(rule.window)).replaceAll("{{delta}}", formatDurationMs(retryAfterMs));
1303
1357
  }
1304
- //#endregion
1305
- //#region src/rate-limit/store.ts
1358
+ // src/rate-limit/store.ts
1306
1359
  /**
1307
1360
  * In-memory `RateLimitStore` — the zero-config default (single process only).
1308
1361
  * Lazy-evicts expired counters on access, and sweeps expired counters itself
@@ -1406,8 +1459,7 @@ var RateLimitStoreMemory = class {
1406
1459
  };
1407
1460
  /** Smallest map size an amortized expiry sweep runs at. */
1408
1461
  const MIN_SWEEP_SIZE = 1024;
1409
- //#endregion
1410
- //#region src/rate-limit/rate-limiter.ts
1462
+ // src/rate-limit/rate-limiter.ts
1411
1463
  /**
1412
1464
  * Fixed-window rate limiter with window-aligned keys (RL.spec.md §4.2).
1413
1465
  *
@@ -1491,13 +1543,11 @@ var RateLimiter = class {
1491
1543
  };
1492
1544
  }
1493
1545
  };
1494
- //#endregion
1495
- //#region src/magic-link.ts
1546
+ // src/magic-link.ts
1496
1547
  /** A magic-link token is a plain {@link generateOpaqueToken} mint. */
1497
1548
  function generateMagicLinkToken() {
1498
1549
  return require_opaque_token.generateOpaqueToken();
1499
1550
  }
1500
- //#endregion
1501
1551
  exports.AuthCredential = AuthCredential;
1502
1552
  exports.AuthError = require_payload.AuthError;
1503
1553
  exports.CredentialStoreEncapsulated = CredentialStoreEncapsulated;
package/dist/index.d.cts CHANGED
@@ -1,17 +1,14 @@
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";
3
- import { n as RateLimitStoreMemory, t as RateLimitStore } from "./store-BaFYDHxn.cjs";
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-hTHoZ2vA.cjs";
2
+ import { i as RefreshCallOptions, n as AuthCredentialOptions, r as IssueOptions, t as AuthCredential } from "./auth-credential-46_eOF3c.cjs";
3
+ import { n as RateLimitStoreMemory, t as RateLimitStore } from "./store-D9CcbcBp.cjs";
4
4
  import { CryptoKey } from "jose";
5
- //#region src/errors.d.ts
6
5
  type AuthErrorType = "INVALID_TOKEN" | "TOKEN_EXPIRED" | "TOKEN_REVOKED" | "REFRESH_REUSE_DETECTED" | "STATELESS_OPERATION_UNSUPPORTED" | "MAX_CONCURRENT_REACHED" | "INVALID_CONFIG";
7
- declare class AuthError extends Error {
6
+ export declare class AuthError extends Error {
8
7
  readonly type: AuthErrorType;
9
8
  readonly details?: Record<string, unknown> | undefined;
10
9
  readonly name = "AuthError";
11
10
  constructor(type: AuthErrorType, message?: string, details?: Record<string, unknown> | undefined);
12
11
  }
13
- //#endregion
14
- //#region src/stores/memory.d.ts
15
12
  /**
16
13
  * In-memory implementation of CredentialStore using random opaque token IDs.
17
14
  *
@@ -20,7 +17,7 @@ declare class AuthError extends Error {
20
17
  * `listForUser` without scanning the full primary map.
21
18
  * - Both maps are kept in sync on every mutation.
22
19
  */
23
- declare class CredentialStoreMemory<TPayload extends object = object> implements CredentialStore<TPayload> {
20
+ export declare class CredentialStoreMemory<TPayload extends object = object> implements CredentialStore<TPayload> {
24
21
  private readonly states;
25
22
  private readonly byUser;
26
23
  private readonly clock;
@@ -41,8 +38,6 @@ declare class CredentialStoreMemory<TPayload extends object = object> implements
41
38
  private indexAdd;
42
39
  private indexRemove;
43
40
  }
44
- //#endregion
45
- //#region src/stores/denylist-memory.d.ts
46
41
  /**
47
42
  * In-memory denylist for stateless revocation.
48
43
  *
@@ -52,7 +47,7 @@ declare class CredentialStoreMemory<TPayload extends object = object> implements
52
47
  * doubles). `cleanup` performs a sweep on demand and returns the number of
53
48
  * entries removed.
54
49
  */
55
- declare class DenylistStoreMemory implements DenylistStore {
50
+ export declare class DenylistStoreMemory implements DenylistStore {
56
51
  private readonly entries;
57
52
  private readonly clock;
58
53
  /** Map size at which `add` next sweeps expired entries (amortized; doubles). */
@@ -65,8 +60,6 @@ declare class DenylistStoreMemory implements DenylistStore {
65
60
  cleanup(): Promise<number>;
66
61
  private sweep;
67
62
  }
68
- //#endregion
69
- //#region src/stores/jwt.d.ts
70
63
  /**
71
64
  * Supported JWT signing algorithms.
72
65
  * - HS256/HS384/HS512: symmetric (shared secret).
@@ -99,7 +92,7 @@ interface CredentialStoreJwtOptions {
99
92
  * `denylist`; without one, `revoke`/`update`/`consume` throw
100
93
  * STATELESS_OPERATION_UNSUPPORTED.
101
94
  */
102
- declare class CredentialStoreJwt<TPayload extends object = object> implements CredentialStore<TPayload> {
95
+ export declare class CredentialStoreJwt<TPayload extends object = object> implements CredentialStore<TPayload> {
103
96
  private readonly algorithm;
104
97
  private readonly signingKey;
105
98
  private readonly verifyingKey;
@@ -150,8 +143,6 @@ declare class CredentialStoreJwt<TPayload extends object = object> implements Cr
150
143
  private keyFor;
151
144
  private payloadToState;
152
145
  }
153
- //#endregion
154
- //#region src/stores/encapsulated.d.ts
155
146
  interface CredentialStoreEncapsulatedOptions {
156
147
  /**
157
148
  * Encryption key material. If a 32-byte Buffer/Uint8Array is provided it is
@@ -188,7 +179,7 @@ interface CredentialStoreEncapsulatedOptions {
188
179
  * `CredentialStoreAtscriptDb` when you need native enumeration with durable
189
180
  * cross-instance cascade semantics.
190
181
  */
191
- declare class CredentialStoreEncapsulated<TPayload extends object = object> implements CredentialStore<TPayload> {
182
+ export declare class CredentialStoreEncapsulated<TPayload extends object = object> implements CredentialStore<TPayload> {
192
183
  private readonly key;
193
184
  private readonly denylist?;
194
185
  private readonly clock;
@@ -218,8 +209,6 @@ declare class CredentialStoreEncapsulated<TPayload extends object = object> impl
218
209
  private requireDenylist;
219
210
  private decrypt;
220
211
  }
221
- //#endregion
222
- //#region src/rate-limit/rules.d.ts
223
212
  /**
224
213
  * Rate-limit rule model + the compact string grammar (RL.spec.md §4.1).
225
214
  *
@@ -250,25 +239,23 @@ type RateLimitRuleInput = string | {
250
239
  window: number | string;
251
240
  message?: string;
252
241
  };
253
- declare const DEFAULT_RATE_LIMIT_MESSAGE = "Too many requests. Please try again in {{delta}}.";
242
+ export declare const DEFAULT_RATE_LIMIT_MESSAGE = "Too many requests. Please try again in {{delta}}.";
254
243
  /** `'5m'` / `'90s'` / `'500ms'` / `'1h'` / `'2d'` → ms. Throws on anything else. */
255
- declare function parseDurationMs(input: string): number;
244
+ export declare function parseDurationMs(input: string): number;
256
245
  /**
257
246
  * Humanize a ms duration for `{{window}}` / `{{delta}}` placeholders:
258
247
  * `"5 minutes"`, `"4 minutes 32 seconds"`, `"1 hour"`. Sub-second values
259
248
  * round UP to `"1 second"` — a retry hint of "0 seconds" reads as broken.
260
249
  * At most the two largest units are shown.
261
250
  */
262
- declare function formatDurationMs(ms: number): string;
251
+ export declare function formatDurationMs(ms: number): string;
263
252
  /** Normalize any {@link RateLimitRuleInput}. Throws on invalid grammar or non-positive values. */
264
- declare function parseRateLimitRule(input: RateLimitRuleInput): RateLimitRule;
253
+ export declare function parseRateLimitRule(input: RateLimitRuleInput): RateLimitRule;
265
254
  /**
266
255
  * Render a 429 message template. Placeholders: `{{limit}}` (alias `{{max}}`),
267
256
  * `{{window}}` and `{{delta}}` — both humanized via {@link formatDurationMs}.
268
257
  */
269
- declare function renderRateLimitMessage(template: string, rule: RateLimitRule, retryAfterMs: number): string;
270
- //#endregion
271
- //#region src/rate-limit/rate-limiter.d.ts
258
+ export declare function renderRateLimitMessage(template: string, rule: RateLimitRule, retryAfterMs: number): string;
272
259
  interface RateLimiterOptions {
273
260
  /** Counter storage. Default: a fresh `RateLimitStoreMemory` (single process only). */
274
261
  store?: RateLimitStore;
@@ -311,11 +298,11 @@ interface RateLimitDecision {
311
298
  * guaranteed-rejected retries; otherwise the one with the least remaining
312
299
  * budget. Used across the rules of one check and across stacked policies.
313
300
  */
314
- declare function pickGoverning<T extends {
301
+ export declare function pickGoverning<T extends {
315
302
  resetAt: number;
316
303
  remaining: number;
317
304
  }>(items: readonly T[], rejected: (item: T) => boolean): T;
318
- declare class RateLimiter {
305
+ export declare class RateLimiter {
319
306
  private readonly store;
320
307
  private readonly clock;
321
308
  constructor(opts?: RateLimiterOptions);
@@ -344,8 +331,6 @@ declare class RateLimiter {
344
331
  }): Promise<RateLimitDecision>;
345
332
  private evaluate;
346
333
  }
347
- //#endregion
348
- //#region src/email.d.ts
349
334
  /**
350
335
  * Discriminator for auth-related email events emitted by the workflow stack.
351
336
  *
@@ -385,8 +370,6 @@ interface AuthEmailEvent {
385
370
  interface EmailSender {
386
371
  send(event: AuthEmailEvent): Promise<void>;
387
372
  }
388
- //#endregion
389
- //#region src/sms.d.ts
390
373
  /**
391
374
  * Discriminator for SMS events emitted by the auth workflow stack.
392
375
  *
@@ -422,8 +405,6 @@ interface AuthSmsEvent {
422
405
  interface SmsSender {
423
406
  send(event: AuthSmsEvent): Promise<void>;
424
407
  }
425
- //#endregion
426
- //#region src/magic-link.d.ts
427
408
  /**
428
409
  * Consumer-supplied URL builder. The consumer chooses route, query
429
410
  * convention, and base URL — aoothjs does not assume a domain or scheme.
@@ -441,15 +422,12 @@ type BuildMagicLinkUrl = (kind: AuthEmailKind, token: string, ctx?: {
441
422
  userId?: string;
442
423
  }) => string;
443
424
  /** A magic-link token is a plain {@link generateOpaqueToken} mint. */
444
- declare function generateMagicLinkToken(): string;
445
- //#endregion
446
- //#region src/utils/opaque-token.d.ts
425
+ export declare function generateMagicLinkToken(): string;
447
426
  /**
448
427
  * 32 bytes of CSPRNG entropy (256 bits) encoded as base64url — 43 chars,
449
428
  * URL-safe. The single mint for every opaque bearer-style secret in the stack
450
429
  * (magic-link tokens, dynamic-client secrets, authz browser bindings):
451
430
  * unguessable online, cheap to generate, safe to place in a URL.
452
431
  */
453
- declare function generateOpaqueToken(): string;
454
- //#endregion
455
- export { type AuthContext, AuthCredential, type AuthCredentialOptions, type AuthEmailEvent, type AuthEmailKind, AuthError, type AuthErrorType, type AuthSmsEvent, type AuthSmsKind, type BuildMagicLinkUrl, type Clock, type CredentialMetadata, type CredentialState, type CredentialStore, CredentialStoreEncapsulated, type CredentialStoreEncapsulatedOptions, CredentialStoreJwt, type CredentialStoreJwtOptions, CredentialStoreMemory, DEFAULT_RATE_LIMIT_MESSAGE, type DenylistStore, DenylistStoreMemory, type EmailSender, type EnrichedSession, type IssueOptions, type IssueResult, type JwtAlgorithm, type RateLimitDecision, type RateLimitRule, type RateLimitRuleInput, type RateLimitStore, RateLimitStoreMemory, RateLimiter, type RateLimiterOptions, type RefreshCallOptions, type RefreshConfig, type RefreshResult, type SessionEnricher, type SessionInfo, type SmsSender, defaultClock, formatDurationMs, generateMagicLinkToken, generateOpaqueToken, parseDurationMs, parseRateLimitRule, pickGoverning, renderRateLimitMessage };
432
+ export declare function generateOpaqueToken(): string;
433
+ export { type AuthContext, AuthCredential, type AuthCredentialOptions, type AuthEmailEvent, type AuthEmailKind, type AuthErrorType, type AuthSmsEvent, type AuthSmsKind, type BuildMagicLinkUrl, type Clock, type CredentialMetadata, type CredentialState, type CredentialStore, type CredentialStoreEncapsulatedOptions, type CredentialStoreJwtOptions, type DenylistStore, type EmailSender, type EnrichedSession, type IssueOptions, type IssueResult, type JwtAlgorithm, type RateLimitDecision, type RateLimitRule, type RateLimitRuleInput, type RateLimitStore, RateLimitStoreMemory, type RateLimiterOptions, type RefreshCallOptions, type RefreshConfig, type RefreshResult, type SessionEnricher, type SessionInfo, type SmsSender, defaultClock };
package/dist/index.d.mts CHANGED
@@ -1,17 +1,14 @@
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";
3
- import { n as RateLimitStoreMemory, t as RateLimitStore } from "./store-h-bLOAaS.mjs";
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-hTHoZ2vA.mjs";
2
+ import { i as RefreshCallOptions, n as AuthCredentialOptions, r as IssueOptions, t as AuthCredential } from "./auth-credential-Co-0pqcD.mjs";
3
+ import { n as RateLimitStoreMemory, t as RateLimitStore } from "./store-BXxX8sUP.mjs";
4
4
  import { CryptoKey } from "jose";
5
- //#region src/errors.d.ts
6
5
  type AuthErrorType = "INVALID_TOKEN" | "TOKEN_EXPIRED" | "TOKEN_REVOKED" | "REFRESH_REUSE_DETECTED" | "STATELESS_OPERATION_UNSUPPORTED" | "MAX_CONCURRENT_REACHED" | "INVALID_CONFIG";
7
- declare class AuthError extends Error {
6
+ export declare class AuthError extends Error {
8
7
  readonly type: AuthErrorType;
9
8
  readonly details?: Record<string, unknown> | undefined;
10
9
  readonly name = "AuthError";
11
10
  constructor(type: AuthErrorType, message?: string, details?: Record<string, unknown> | undefined);
12
11
  }
13
- //#endregion
14
- //#region src/stores/memory.d.ts
15
12
  /**
16
13
  * In-memory implementation of CredentialStore using random opaque token IDs.
17
14
  *
@@ -20,7 +17,7 @@ declare class AuthError extends Error {
20
17
  * `listForUser` without scanning the full primary map.
21
18
  * - Both maps are kept in sync on every mutation.
22
19
  */
23
- declare class CredentialStoreMemory<TPayload extends object = object> implements CredentialStore<TPayload> {
20
+ export declare class CredentialStoreMemory<TPayload extends object = object> implements CredentialStore<TPayload> {
24
21
  private readonly states;
25
22
  private readonly byUser;
26
23
  private readonly clock;
@@ -41,8 +38,6 @@ declare class CredentialStoreMemory<TPayload extends object = object> implements
41
38
  private indexAdd;
42
39
  private indexRemove;
43
40
  }
44
- //#endregion
45
- //#region src/stores/denylist-memory.d.ts
46
41
  /**
47
42
  * In-memory denylist for stateless revocation.
48
43
  *
@@ -52,7 +47,7 @@ declare class CredentialStoreMemory<TPayload extends object = object> implements
52
47
  * doubles). `cleanup` performs a sweep on demand and returns the number of
53
48
  * entries removed.
54
49
  */
55
- declare class DenylistStoreMemory implements DenylistStore {
50
+ export declare class DenylistStoreMemory implements DenylistStore {
56
51
  private readonly entries;
57
52
  private readonly clock;
58
53
  /** Map size at which `add` next sweeps expired entries (amortized; doubles). */
@@ -65,8 +60,6 @@ declare class DenylistStoreMemory implements DenylistStore {
65
60
  cleanup(): Promise<number>;
66
61
  private sweep;
67
62
  }
68
- //#endregion
69
- //#region src/stores/jwt.d.ts
70
63
  /**
71
64
  * Supported JWT signing algorithms.
72
65
  * - HS256/HS384/HS512: symmetric (shared secret).
@@ -99,7 +92,7 @@ interface CredentialStoreJwtOptions {
99
92
  * `denylist`; without one, `revoke`/`update`/`consume` throw
100
93
  * STATELESS_OPERATION_UNSUPPORTED.
101
94
  */
102
- declare class CredentialStoreJwt<TPayload extends object = object> implements CredentialStore<TPayload> {
95
+ export declare class CredentialStoreJwt<TPayload extends object = object> implements CredentialStore<TPayload> {
103
96
  private readonly algorithm;
104
97
  private readonly signingKey;
105
98
  private readonly verifyingKey;
@@ -150,8 +143,6 @@ declare class CredentialStoreJwt<TPayload extends object = object> implements Cr
150
143
  private keyFor;
151
144
  private payloadToState;
152
145
  }
153
- //#endregion
154
- //#region src/stores/encapsulated.d.ts
155
146
  interface CredentialStoreEncapsulatedOptions {
156
147
  /**
157
148
  * Encryption key material. If a 32-byte Buffer/Uint8Array is provided it is
@@ -188,7 +179,7 @@ interface CredentialStoreEncapsulatedOptions {
188
179
  * `CredentialStoreAtscriptDb` when you need native enumeration with durable
189
180
  * cross-instance cascade semantics.
190
181
  */
191
- declare class CredentialStoreEncapsulated<TPayload extends object = object> implements CredentialStore<TPayload> {
182
+ export declare class CredentialStoreEncapsulated<TPayload extends object = object> implements CredentialStore<TPayload> {
192
183
  private readonly key;
193
184
  private readonly denylist?;
194
185
  private readonly clock;
@@ -218,8 +209,6 @@ declare class CredentialStoreEncapsulated<TPayload extends object = object> impl
218
209
  private requireDenylist;
219
210
  private decrypt;
220
211
  }
221
- //#endregion
222
- //#region src/rate-limit/rules.d.ts
223
212
  /**
224
213
  * Rate-limit rule model + the compact string grammar (RL.spec.md §4.1).
225
214
  *
@@ -250,25 +239,23 @@ type RateLimitRuleInput = string | {
250
239
  window: number | string;
251
240
  message?: string;
252
241
  };
253
- declare const DEFAULT_RATE_LIMIT_MESSAGE = "Too many requests. Please try again in {{delta}}.";
242
+ export declare const DEFAULT_RATE_LIMIT_MESSAGE = "Too many requests. Please try again in {{delta}}.";
254
243
  /** `'5m'` / `'90s'` / `'500ms'` / `'1h'` / `'2d'` → ms. Throws on anything else. */
255
- declare function parseDurationMs(input: string): number;
244
+ export declare function parseDurationMs(input: string): number;
256
245
  /**
257
246
  * Humanize a ms duration for `{{window}}` / `{{delta}}` placeholders:
258
247
  * `"5 minutes"`, `"4 minutes 32 seconds"`, `"1 hour"`. Sub-second values
259
248
  * round UP to `"1 second"` — a retry hint of "0 seconds" reads as broken.
260
249
  * At most the two largest units are shown.
261
250
  */
262
- declare function formatDurationMs(ms: number): string;
251
+ export declare function formatDurationMs(ms: number): string;
263
252
  /** Normalize any {@link RateLimitRuleInput}. Throws on invalid grammar or non-positive values. */
264
- declare function parseRateLimitRule(input: RateLimitRuleInput): RateLimitRule;
253
+ export declare function parseRateLimitRule(input: RateLimitRuleInput): RateLimitRule;
265
254
  /**
266
255
  * Render a 429 message template. Placeholders: `{{limit}}` (alias `{{max}}`),
267
256
  * `{{window}}` and `{{delta}}` — both humanized via {@link formatDurationMs}.
268
257
  */
269
- declare function renderRateLimitMessage(template: string, rule: RateLimitRule, retryAfterMs: number): string;
270
- //#endregion
271
- //#region src/rate-limit/rate-limiter.d.ts
258
+ export declare function renderRateLimitMessage(template: string, rule: RateLimitRule, retryAfterMs: number): string;
272
259
  interface RateLimiterOptions {
273
260
  /** Counter storage. Default: a fresh `RateLimitStoreMemory` (single process only). */
274
261
  store?: RateLimitStore;
@@ -311,11 +298,11 @@ interface RateLimitDecision {
311
298
  * guaranteed-rejected retries; otherwise the one with the least remaining
312
299
  * budget. Used across the rules of one check and across stacked policies.
313
300
  */
314
- declare function pickGoverning<T extends {
301
+ export declare function pickGoverning<T extends {
315
302
  resetAt: number;
316
303
  remaining: number;
317
304
  }>(items: readonly T[], rejected: (item: T) => boolean): T;
318
- declare class RateLimiter {
305
+ export declare class RateLimiter {
319
306
  private readonly store;
320
307
  private readonly clock;
321
308
  constructor(opts?: RateLimiterOptions);
@@ -344,8 +331,6 @@ declare class RateLimiter {
344
331
  }): Promise<RateLimitDecision>;
345
332
  private evaluate;
346
333
  }
347
- //#endregion
348
- //#region src/email.d.ts
349
334
  /**
350
335
  * Discriminator for auth-related email events emitted by the workflow stack.
351
336
  *
@@ -385,8 +370,6 @@ interface AuthEmailEvent {
385
370
  interface EmailSender {
386
371
  send(event: AuthEmailEvent): Promise<void>;
387
372
  }
388
- //#endregion
389
- //#region src/sms.d.ts
390
373
  /**
391
374
  * Discriminator for SMS events emitted by the auth workflow stack.
392
375
  *
@@ -422,8 +405,6 @@ interface AuthSmsEvent {
422
405
  interface SmsSender {
423
406
  send(event: AuthSmsEvent): Promise<void>;
424
407
  }
425
- //#endregion
426
- //#region src/magic-link.d.ts
427
408
  /**
428
409
  * Consumer-supplied URL builder. The consumer chooses route, query
429
410
  * convention, and base URL — aoothjs does not assume a domain or scheme.
@@ -441,15 +422,12 @@ type BuildMagicLinkUrl = (kind: AuthEmailKind, token: string, ctx?: {
441
422
  userId?: string;
442
423
  }) => string;
443
424
  /** A magic-link token is a plain {@link generateOpaqueToken} mint. */
444
- declare function generateMagicLinkToken(): string;
445
- //#endregion
446
- //#region src/utils/opaque-token.d.ts
425
+ export declare function generateMagicLinkToken(): string;
447
426
  /**
448
427
  * 32 bytes of CSPRNG entropy (256 bits) encoded as base64url — 43 chars,
449
428
  * URL-safe. The single mint for every opaque bearer-style secret in the stack
450
429
  * (magic-link tokens, dynamic-client secrets, authz browser bindings):
451
430
  * unguessable online, cheap to generate, safe to place in a URL.
452
431
  */
453
- declare function generateOpaqueToken(): string;
454
- //#endregion
455
- export { type AuthContext, AuthCredential, type AuthCredentialOptions, type AuthEmailEvent, type AuthEmailKind, AuthError, type AuthErrorType, type AuthSmsEvent, type AuthSmsKind, type BuildMagicLinkUrl, type Clock, type CredentialMetadata, type CredentialState, type CredentialStore, CredentialStoreEncapsulated, type CredentialStoreEncapsulatedOptions, CredentialStoreJwt, type CredentialStoreJwtOptions, CredentialStoreMemory, DEFAULT_RATE_LIMIT_MESSAGE, type DenylistStore, DenylistStoreMemory, type EmailSender, type EnrichedSession, type IssueOptions, type IssueResult, type JwtAlgorithm, type RateLimitDecision, type RateLimitRule, type RateLimitRuleInput, type RateLimitStore, RateLimitStoreMemory, RateLimiter, type RateLimiterOptions, type RefreshCallOptions, type RefreshConfig, type RefreshResult, type SessionEnricher, type SessionInfo, type SmsSender, defaultClock, formatDurationMs, generateMagicLinkToken, generateOpaqueToken, parseDurationMs, parseRateLimitRule, pickGoverning, renderRateLimitMessage };
432
+ export declare function generateOpaqueToken(): string;
433
+ export { type AuthContext, AuthCredential, type AuthCredentialOptions, type AuthEmailEvent, type AuthEmailKind, type AuthErrorType, type AuthSmsEvent, type AuthSmsKind, type BuildMagicLinkUrl, type Clock, type CredentialMetadata, type CredentialState, type CredentialStore, type CredentialStoreEncapsulatedOptions, type CredentialStoreJwtOptions, type DenylistStore, type EmailSender, type EnrichedSession, type IssueOptions, type IssueResult, type JwtAlgorithm, type RateLimitDecision, type RateLimitRule, type RateLimitRuleInput, type RateLimitStore, RateLimitStoreMemory, type RateLimiterOptions, type RefreshCallOptions, type RefreshConfig, type RefreshResult, type SessionEnricher, type SessionInfo, type SmsSender, defaultClock };