@aooth/auth 0.1.85 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/dist/atscript-db.cjs +80 -4
  2. package/dist/atscript-db.d.cts +51 -10
  3. package/dist/atscript-db.d.mts +51 -10
  4. package/dist/atscript-db.mjs +79 -5
  5. package/dist/{auth-credential-CLAQgjCS.d.mts → auth-credential-CjCgZv7n.d.mts} +106 -9
  6. package/dist/{auth-credential-GRAK230V.d.cts → auth-credential-UV3sJ-lt.d.cts} +106 -9
  7. package/dist/authz.d.cts +2 -2
  8. package/dist/authz.d.mts +2 -2
  9. package/dist/client.cjs +25 -12
  10. package/dist/client.d.cts +59 -13
  11. package/dist/client.d.mts +59 -13
  12. package/dist/client.mjs +25 -12
  13. package/dist/{clock-CyjqzLxc.d.cts → clock-CzAaCoZ5.d.cts} +7 -0
  14. package/dist/{clock-CyjqzLxc.d.mts → clock-CzAaCoZ5.d.mts} +7 -0
  15. package/dist/{dynamic-client-store-BF4nXMK2.d.mts → dynamic-client-store-B7EnHuRp.d.cts} +2 -2
  16. package/dist/{dynamic-client-store-HLfcl2FJ.d.cts → dynamic-client-store-BifZLGkT.d.mts} +2 -2
  17. package/dist/index.cjs +351 -128
  18. package/dist/index.d.cts +26 -4
  19. package/dist/index.d.mts +26 -4
  20. package/dist/index.mjs +328 -106
  21. package/dist/{payload-HPgyPiek.cjs → payload-C1cQW7p_.cjs} +27 -0
  22. package/dist/{payload-DP5zRiXT.mjs → payload-DDlf38B-.mjs} +22 -1
  23. package/dist/redis.cjs +18 -6
  24. package/dist/redis.d.cts +19 -4
  25. package/dist/redis.d.mts +19 -4
  26. package/dist/redis.mjs +18 -6
  27. package/dist/store-BaFYDHxn.d.cts +69 -0
  28. package/dist/store-h-bLOAaS.d.mts +69 -0
  29. package/package.json +9 -9
  30. package/src/atscript-db/auth-code.as.d.ts +1 -1
  31. package/src/atscript-db/auth-credential.as.d.ts +1 -1
  32. package/src/atscript-db/dynamic-client.as.d.ts +1 -1
  33. package/src/atscript-db/pending-authorization.as.d.ts +1 -1
  34. package/dist/store-CVD1nd2j.d.mts +0 -41
  35. package/dist/store-ClQnA8yh.d.cts +0 -41
@@ -1,3 +1,24 @@
1
+ //#region src/errors.ts
2
+ const defaultMessages = {
3
+ INVALID_TOKEN: "Invalid token",
4
+ TOKEN_EXPIRED: "Token has expired",
5
+ TOKEN_REVOKED: "Token has been revoked",
6
+ REFRESH_REUSE_DETECTED: "Refresh token reuse detected",
7
+ STATELESS_OPERATION_UNSUPPORTED: "Operation is not supported by stateless credential store",
8
+ MAX_CONCURRENT_REACHED: "Maximum concurrent credentials reached for user",
9
+ INVALID_CONFIG: "Invalid auth configuration"
10
+ };
11
+ var AuthError = class extends Error {
12
+ type;
13
+ details;
14
+ name = "AuthError";
15
+ constructor(type, message, details) {
16
+ super(message ?? defaultMessages[type]);
17
+ this.type = type;
18
+ this.details = details;
19
+ }
20
+ };
21
+ //#endregion
1
22
  //#region src/credential/payload.ts
2
23
  const ENVELOPE_KEYS = new Set(Object.keys({
3
24
  userId: true,
@@ -25,6 +46,12 @@ function credentialPayloadOf(state) {
25
46
  return out;
26
47
  }
27
48
  //#endregion
49
+ Object.defineProperty(exports, "AuthError", {
50
+ enumerable: true,
51
+ get: function() {
52
+ return AuthError;
53
+ }
54
+ });
28
55
  Object.defineProperty(exports, "credentialPayloadOf", {
29
56
  enumerable: true,
30
57
  get: function() {
@@ -1,3 +1,24 @@
1
+ //#region src/errors.ts
2
+ const defaultMessages = {
3
+ INVALID_TOKEN: "Invalid token",
4
+ TOKEN_EXPIRED: "Token has expired",
5
+ TOKEN_REVOKED: "Token has been revoked",
6
+ REFRESH_REUSE_DETECTED: "Refresh token reuse detected",
7
+ STATELESS_OPERATION_UNSUPPORTED: "Operation is not supported by stateless credential store",
8
+ MAX_CONCURRENT_REACHED: "Maximum concurrent credentials reached for user",
9
+ INVALID_CONFIG: "Invalid auth configuration"
10
+ };
11
+ var AuthError = class extends Error {
12
+ type;
13
+ details;
14
+ name = "AuthError";
15
+ constructor(type, message, details) {
16
+ super(message ?? defaultMessages[type]);
17
+ this.type = type;
18
+ this.details = details;
19
+ }
20
+ };
21
+ //#endregion
1
22
  //#region src/credential/payload.ts
2
23
  const ENVELOPE_KEYS = new Set(Object.keys({
3
24
  userId: true,
@@ -25,4 +46,4 @@ function credentialPayloadOf(state) {
25
46
  return out;
26
47
  }
27
48
  //#endregion
28
- export { credentialPayloadOf as t };
49
+ export { AuthError as n, credentialPayloadOf as t };
package/dist/redis.cjs CHANGED
@@ -29,13 +29,16 @@ var CredentialStoreRedis = class {
29
29
  }
30
30
  async persist(state, ttl) {
31
31
  const token = (0, node_crypto.randomUUID)();
32
+ await this.persistAs(token, state, ttl);
33
+ return token;
34
+ }
35
+ async persistAs(token, state, ttl) {
32
36
  const stored = { ...state };
33
37
  if (typeof ttl === "number") stored.expiresAt = Date.now() + ttl;
34
38
  const ttlMs = Math.max(0, stored.expiresAt - Date.now());
35
39
  if (ttlMs <= 0) throw new Error("CredentialStoreRedis.persist: refusing to persist an already-expired credential");
36
40
  await this.redis.set(this.tokenKey(token), JSON.stringify(stored), "PX", ttlMs);
37
41
  await this.redis.sadd(this.userKey(state.userId), token);
38
- return token;
39
42
  }
40
43
  async retrieve(token) {
41
44
  const raw = await this.redis.get(this.tokenKey(token));
@@ -58,13 +61,15 @@ var CredentialStoreRedis = class {
58
61
  const existingRaw = await this.redis.get(this.tokenKey(token));
59
62
  if (existingRaw === null) return token;
60
63
  const existing = JSON.parse(existingRaw);
61
- 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) {
62
70
  await this.redis.srem(this.userKey(existing.userId), token);
63
71
  await this.redis.sadd(this.userKey(state.userId), token);
64
72
  }
65
- const ttlMs = Math.max(0, state.expiresAt - Date.now());
66
- if (ttlMs > 0) await this.redis.set(this.tokenKey(token), JSON.stringify(state), "PX", ttlMs);
67
- else await this.revoke(token);
68
73
  return token;
69
74
  }
70
75
  async revoke(token) {
@@ -85,7 +90,7 @@ var CredentialStoreRedis = class {
85
90
  state.lastSeenAt = at;
86
91
  const ttlMs = Math.max(0, state.expiresAt - Date.now());
87
92
  if (ttlMs <= 0) return;
88
- 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");
89
94
  }
90
95
  async revokeAllForUser(userId) {
91
96
  const setKey = this.userKey(userId);
@@ -175,6 +180,13 @@ var RateLimitStoreRedis = class {
175
180
  if (count === 1) await this.redis.pexpire(k, ttlMs);
176
181
  return count;
177
182
  }
183
+ async get(key) {
184
+ const raw = await this.redis.get(this.key(key));
185
+ return raw ? Number(raw) || 0 : 0;
186
+ }
187
+ async expire(key, ttlMs) {
188
+ await this.redis.pexpire(this.key(key), ttlMs);
189
+ }
178
190
  async reset(key) {
179
191
  await this.redis.del(this.key(key));
180
192
  }
package/dist/redis.d.cts CHANGED
@@ -1,5 +1,5 @@
1
- import { i as DenylistStore, r as CredentialStore, s as CredentialState } from "./clock-CyjqzLxc.cjs";
2
- import { t as RateLimitStore } from "./store-ClQnA8yh.cjs";
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
3
  //#region src/redis/index.d.ts
4
4
  /**
5
5
  * Structural Redis client. Covers the exact set of commands used by
@@ -19,7 +19,7 @@ import { t as RateLimitStore } from "./store-ClQnA8yh.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-ClQnA8yh.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-ClQnA8yh.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>;
@@ -97,6 +109,7 @@ declare class CredentialStoreRedis<TPayload extends object = object> implements
97
109
  private tokenKey;
98
110
  private userKey;
99
111
  persist(state: CredentialState & TPayload, ttl?: number): Promise<string>;
112
+ persistAs(token: string, state: CredentialState & TPayload, ttl?: number): Promise<void>;
100
113
  retrieve(token: string): Promise<(CredentialState & TPayload) | null>;
101
114
  consume(token: string): Promise<(CredentialState & TPayload) | null>;
102
115
  update(token: string, state: CredentialState & TPayload): Promise<string>;
@@ -146,6 +159,8 @@ declare class RateLimitStoreRedis implements RateLimitStore {
146
159
  constructor(opts: RedisRateLimitStoreOptions);
147
160
  private key;
148
161
  hit(key: string, ttlMs: number): Promise<number>;
162
+ get(key: string): Promise<number>;
163
+ expire(key: string, ttlMs: number): Promise<void>;
149
164
  reset(key: string): Promise<void>;
150
165
  }
151
166
  //#endregion
package/dist/redis.d.mts CHANGED
@@ -1,5 +1,5 @@
1
- import { i as DenylistStore, r as CredentialStore, s as CredentialState } from "./clock-CyjqzLxc.mjs";
2
- import { t as RateLimitStore } from "./store-CVD1nd2j.mjs";
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
3
  //#region src/redis/index.d.ts
4
4
  /**
5
5
  * Structural Redis client. Covers the exact set of commands used by
@@ -19,7 +19,7 @@ import { t as RateLimitStore } from "./store-CVD1nd2j.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-CVD1nd2j.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-CVD1nd2j.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>;
@@ -97,6 +109,7 @@ declare class CredentialStoreRedis<TPayload extends object = object> implements
97
109
  private tokenKey;
98
110
  private userKey;
99
111
  persist(state: CredentialState & TPayload, ttl?: number): Promise<string>;
112
+ persistAs(token: string, state: CredentialState & TPayload, ttl?: number): Promise<void>;
100
113
  retrieve(token: string): Promise<(CredentialState & TPayload) | null>;
101
114
  consume(token: string): Promise<(CredentialState & TPayload) | null>;
102
115
  update(token: string, state: CredentialState & TPayload): Promise<string>;
@@ -146,6 +159,8 @@ declare class RateLimitStoreRedis implements RateLimitStore {
146
159
  constructor(opts: RedisRateLimitStoreOptions);
147
160
  private key;
148
161
  hit(key: string, ttlMs: number): Promise<number>;
162
+ get(key: string): Promise<number>;
163
+ expire(key: string, ttlMs: number): Promise<void>;
149
164
  reset(key: string): Promise<void>;
150
165
  }
151
166
  //#endregion
package/dist/redis.mjs CHANGED
@@ -28,13 +28,16 @@ var CredentialStoreRedis = class {
28
28
  }
29
29
  async persist(state, ttl) {
30
30
  const token = randomUUID();
31
+ await this.persistAs(token, state, ttl);
32
+ return token;
33
+ }
34
+ async persistAs(token, state, ttl) {
31
35
  const stored = { ...state };
32
36
  if (typeof ttl === "number") stored.expiresAt = Date.now() + ttl;
33
37
  const ttlMs = Math.max(0, stored.expiresAt - Date.now());
34
38
  if (ttlMs <= 0) throw new Error("CredentialStoreRedis.persist: refusing to persist an already-expired credential");
35
39
  await this.redis.set(this.tokenKey(token), JSON.stringify(stored), "PX", ttlMs);
36
40
  await this.redis.sadd(this.userKey(state.userId), token);
37
- return token;
38
41
  }
39
42
  async retrieve(token) {
40
43
  const raw = await this.redis.get(this.tokenKey(token));
@@ -57,13 +60,15 @@ var CredentialStoreRedis = class {
57
60
  const existingRaw = await this.redis.get(this.tokenKey(token));
58
61
  if (existingRaw === null) return token;
59
62
  const existing = JSON.parse(existingRaw);
60
- 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) {
61
69
  await this.redis.srem(this.userKey(existing.userId), token);
62
70
  await this.redis.sadd(this.userKey(state.userId), token);
63
71
  }
64
- const ttlMs = Math.max(0, state.expiresAt - Date.now());
65
- if (ttlMs > 0) await this.redis.set(this.tokenKey(token), JSON.stringify(state), "PX", ttlMs);
66
- else await this.revoke(token);
67
72
  return token;
68
73
  }
69
74
  async revoke(token) {
@@ -84,7 +89,7 @@ var CredentialStoreRedis = class {
84
89
  state.lastSeenAt = at;
85
90
  const ttlMs = Math.max(0, state.expiresAt - Date.now());
86
91
  if (ttlMs <= 0) return;
87
- 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");
88
93
  }
89
94
  async revokeAllForUser(userId) {
90
95
  const setKey = this.userKey(userId);
@@ -174,6 +179,13 @@ var RateLimitStoreRedis = class {
174
179
  if (count === 1) await this.redis.pexpire(k, ttlMs);
175
180
  return count;
176
181
  }
182
+ async get(key) {
183
+ const raw = await this.redis.get(this.key(key));
184
+ return raw ? Number(raw) || 0 : 0;
185
+ }
186
+ async expire(key, ttlMs) {
187
+ await this.redis.pexpire(this.key(key), ttlMs);
188
+ }
177
189
  async reset(key) {
178
190
  await this.redis.del(this.key(key));
179
191
  }
@@ -0,0 +1,69 @@
1
+ import { t as Clock } from "./clock-CzAaCoZ5.cjs";
2
+ //#region src/rate-limit/store.d.ts
3
+ /**
4
+ * Storage contract for the fixed-window limiter (RL.spec.md §4.3).
5
+ *
6
+ * The limiter embeds the window start in the key, so a new window is a new
7
+ * key and correctness never depends on the TTL — the TTL only garbage-collects
8
+ * dead counters.
9
+ */
10
+ interface RateLimitStore {
11
+ /**
12
+ * Atomically increment `key`, setting `ttlMs` expiry when the key is
13
+ * created; returns the new count.
14
+ */
15
+ hit(key: string, ttlMs: number): Promise<number>;
16
+ /**
17
+ * Optional: read `key`'s current count without incrementing it (`0` when
18
+ * missing or expired). Required by `RateLimiter.peek()`.
19
+ */
20
+ get?(key: string): Promise<number>;
21
+ /** Optional: reset `key`'s expiry to `ttlMs` from now (a sliding window); no-op when missing. */
22
+ expire?(key: string, ttlMs: number): Promise<void>;
23
+ /** Optional: drop a counter (tests / admin unblock). */
24
+ reset?(key: string): Promise<void>;
25
+ }
26
+ /**
27
+ * In-memory `RateLimitStore` — the zero-config default (single process only).
28
+ * Lazy-evicts expired counters on access, and sweeps expired counters itself
29
+ * as the map grows (amortized, each time it doubles); `cleanup()` sweeps the
30
+ * whole map on demand (same pattern as `DenylistStoreMemory`).
31
+ */
32
+ declare class RateLimitStoreMemory implements RateLimitStore {
33
+ private readonly entries;
34
+ private readonly clock;
35
+ private readonly maxEntries;
36
+ private readonly evictLast?;
37
+ /** Map size at which `hit` next sweeps expired counters (amortized; doubles). */
38
+ private sweepAt;
39
+ /**
40
+ * Lower bound of every entry's `expiresAt` (exact after a sweep): while
41
+ * `now` is below it nothing can have expired, so a sweep is skipped.
42
+ */
43
+ private minExpiry;
44
+ /**
45
+ * - `maxEntries` caps the live counters kept (default: unbounded). At the
46
+ * cap a new key first sweeps expired counters, then evicts the oldest one.
47
+ * - `evictLast` marks keys to keep while others can go: at the cap the
48
+ * oldest key it does NOT match is evicted first (the oldest matching one
49
+ * only when every key matches) — e.g. active lock markers that a flood of
50
+ * fresh counters must not push out.
51
+ */
52
+ constructor(opts?: {
53
+ clock?: Clock;
54
+ maxEntries?: number;
55
+ evictLast?: (key: string) => boolean;
56
+ });
57
+ hit(key: string, ttlMs: number): Promise<number>;
58
+ /** Drop the oldest key (Map keeps insertion order), sparing `evictLast` keys while it can. */
59
+ private evictOne;
60
+ get(key: string): Promise<number>;
61
+ expire(key: string, ttlMs: number): Promise<void>;
62
+ reset(key: string): Promise<void>;
63
+ /** Drop every counter — test-harness reset between cases. */
64
+ clear(): void;
65
+ cleanup(): Promise<number>;
66
+ private sweep;
67
+ }
68
+ //#endregion
69
+ export { RateLimitStoreMemory as n, RateLimitStore as t };
@@ -0,0 +1,69 @@
1
+ import { t as Clock } from "./clock-CzAaCoZ5.mjs";
2
+ //#region src/rate-limit/store.d.ts
3
+ /**
4
+ * Storage contract for the fixed-window limiter (RL.spec.md §4.3).
5
+ *
6
+ * The limiter embeds the window start in the key, so a new window is a new
7
+ * key and correctness never depends on the TTL — the TTL only garbage-collects
8
+ * dead counters.
9
+ */
10
+ interface RateLimitStore {
11
+ /**
12
+ * Atomically increment `key`, setting `ttlMs` expiry when the key is
13
+ * created; returns the new count.
14
+ */
15
+ hit(key: string, ttlMs: number): Promise<number>;
16
+ /**
17
+ * Optional: read `key`'s current count without incrementing it (`0` when
18
+ * missing or expired). Required by `RateLimiter.peek()`.
19
+ */
20
+ get?(key: string): Promise<number>;
21
+ /** Optional: reset `key`'s expiry to `ttlMs` from now (a sliding window); no-op when missing. */
22
+ expire?(key: string, ttlMs: number): Promise<void>;
23
+ /** Optional: drop a counter (tests / admin unblock). */
24
+ reset?(key: string): Promise<void>;
25
+ }
26
+ /**
27
+ * In-memory `RateLimitStore` — the zero-config default (single process only).
28
+ * Lazy-evicts expired counters on access, and sweeps expired counters itself
29
+ * as the map grows (amortized, each time it doubles); `cleanup()` sweeps the
30
+ * whole map on demand (same pattern as `DenylistStoreMemory`).
31
+ */
32
+ declare class RateLimitStoreMemory implements RateLimitStore {
33
+ private readonly entries;
34
+ private readonly clock;
35
+ private readonly maxEntries;
36
+ private readonly evictLast?;
37
+ /** Map size at which `hit` next sweeps expired counters (amortized; doubles). */
38
+ private sweepAt;
39
+ /**
40
+ * Lower bound of every entry's `expiresAt` (exact after a sweep): while
41
+ * `now` is below it nothing can have expired, so a sweep is skipped.
42
+ */
43
+ private minExpiry;
44
+ /**
45
+ * - `maxEntries` caps the live counters kept (default: unbounded). At the
46
+ * cap a new key first sweeps expired counters, then evicts the oldest one.
47
+ * - `evictLast` marks keys to keep while others can go: at the cap the
48
+ * oldest key it does NOT match is evicted first (the oldest matching one
49
+ * only when every key matches) — e.g. active lock markers that a flood of
50
+ * fresh counters must not push out.
51
+ */
52
+ constructor(opts?: {
53
+ clock?: Clock;
54
+ maxEntries?: number;
55
+ evictLast?: (key: string) => boolean;
56
+ });
57
+ hit(key: string, ttlMs: number): Promise<number>;
58
+ /** Drop the oldest key (Map keeps insertion order), sparing `evictLast` keys while it can. */
59
+ private evictOne;
60
+ get(key: string): Promise<number>;
61
+ expire(key: string, ttlMs: number): Promise<void>;
62
+ reset(key: string): Promise<void>;
63
+ /** Drop every counter — test-harness reset between cases. */
64
+ clear(): void;
65
+ cleanup(): Promise<number>;
66
+ private sweep;
67
+ }
68
+ //#endregion
69
+ 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.1.85",
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.1.85"
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**
@@ -1,41 +0,0 @@
1
- import { t as Clock } from "./clock-CyjqzLxc.mjs";
2
- //#region src/rate-limit/store.d.ts
3
- /**
4
- * Storage contract for the fixed-window limiter (RL.spec.md §4.3).
5
- *
6
- * The limiter embeds the window start in the key, so a new window is a new
7
- * key and correctness never depends on the TTL — the TTL only garbage-collects
8
- * dead counters.
9
- */
10
- interface RateLimitStore {
11
- /**
12
- * Atomically increment `key`, setting `ttlMs` expiry when the key is
13
- * created; returns the new count.
14
- */
15
- hit(key: string, ttlMs: number): Promise<number>;
16
- /** Optional: drop a counter (tests / admin unblock). */
17
- reset?(key: string): Promise<void>;
18
- }
19
- /**
20
- * In-memory `RateLimitStore` — the zero-config default (single process only).
21
- * Lazy-evicts expired counters on access, and sweeps expired counters itself
22
- * as the map grows (amortized, each time it doubles); `cleanup()` sweeps the
23
- * whole map on demand (same pattern as `DenylistStoreMemory`).
24
- */
25
- declare class RateLimitStoreMemory implements RateLimitStore {
26
- private readonly entries;
27
- private readonly clock;
28
- /** Map size at which `hit` next sweeps expired counters (amortized; doubles). */
29
- private sweepAt;
30
- constructor(opts?: {
31
- clock?: Clock;
32
- });
33
- hit(key: string, ttlMs: number): Promise<number>;
34
- reset(key: string): Promise<void>;
35
- /** Drop every counter — test-harness reset between cases. */
36
- clear(): void;
37
- cleanup(): Promise<number>;
38
- private sweep;
39
- }
40
- //#endregion
41
- export { RateLimitStoreMemory as n, RateLimitStore as t };
@@ -1,41 +0,0 @@
1
- import { t as Clock } from "./clock-CyjqzLxc.cjs";
2
- //#region src/rate-limit/store.d.ts
3
- /**
4
- * Storage contract for the fixed-window limiter (RL.spec.md §4.3).
5
- *
6
- * The limiter embeds the window start in the key, so a new window is a new
7
- * key and correctness never depends on the TTL — the TTL only garbage-collects
8
- * dead counters.
9
- */
10
- interface RateLimitStore {
11
- /**
12
- * Atomically increment `key`, setting `ttlMs` expiry when the key is
13
- * created; returns the new count.
14
- */
15
- hit(key: string, ttlMs: number): Promise<number>;
16
- /** Optional: drop a counter (tests / admin unblock). */
17
- reset?(key: string): Promise<void>;
18
- }
19
- /**
20
- * In-memory `RateLimitStore` — the zero-config default (single process only).
21
- * Lazy-evicts expired counters on access, and sweeps expired counters itself
22
- * as the map grows (amortized, each time it doubles); `cleanup()` sweeps the
23
- * whole map on demand (same pattern as `DenylistStoreMemory`).
24
- */
25
- declare class RateLimitStoreMemory implements RateLimitStore {
26
- private readonly entries;
27
- private readonly clock;
28
- /** Map size at which `hit` next sweeps expired counters (amortized; doubles). */
29
- private sweepAt;
30
- constructor(opts?: {
31
- clock?: Clock;
32
- });
33
- hit(key: string, ttlMs: number): Promise<number>;
34
- reset(key: string): Promise<void>;
35
- /** Drop every counter — test-harness reset between cases. */
36
- clear(): void;
37
- cleanup(): Promise<number>;
38
- private sweep;
39
- }
40
- //#endregion
41
- export { RateLimitStoreMemory as n, RateLimitStore as t };