cursedbelt-server 4.24.1 → 4.26.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -57,6 +57,22 @@ the Worker's `fetch` gives `Bun.password` to the auth code, backed by `argon2id`
57
57
  files as static imports that wrangler bundles from `node_modules`. No wrangler rule and no local
58
58
  `.wasm` declaration are needed. `src/server/worker-argon2/argon2.ts` has the measurements.
59
59
 
60
+ ## 🔴 A login throttle on a Worker: `cursedbelt-server/login-throttle/durable`
61
+
62
+ `createLoginThrottle()` remembers in memory, and a Worker's memory is one isolate — per colo,
63
+ several per colo, wiped by every deploy — so a Worker's sign-in keeps its ledger in the
64
+ `LoginThrottleObject` Durable Object and asks it through `createRemoteLoginThrottle(env.<BINDING>,
65
+ { ledger, fallback })`, gating with `attempt` (check and charge in one step, so a concurrent burst
66
+ cannot share one count). `src/server/auth/loginThrottleDurable.ts` has the why and the wiring.
67
+
68
+ ## 🔴 A master lock on a Worker: `attempts: createD1MasterLockAttempts(db)`
69
+
70
+ A Worker rebuilds `MasterLock` per request, so its guess throttle must be CHARGED where every
71
+ request can see it, before the argon2id verify — or a burst landing inside one verify is judged
72
+ against one stale count (task 2137). Pass `attempts: createD1MasterLockAttempts(db, { snapshot })`
73
+ (one conditional UPSERT … RETURNING on the `meta` row `master_lock:attempts`).
74
+ `src/server/master-lock/attempts.ts` has the why.
75
+
60
76
  ## Standards
61
77
 
62
78
  `docs/retention.md`, `docs/activity.md`, `docs/notifications.md`, `docs/engagement.md` — the
@@ -45,6 +45,25 @@
45
45
  * global counter keeps working after eviction, which is precisely the case where it
46
46
  * matters most.
47
47
  *
48
+ * 🔴 **"Per-process" is one ISOLATE on a Cloudflare Worker, and that is not a process.**
49
+ * Cloudflare runs an isolate per colo (often several), discards them without warning and
50
+ * builds a fresh one on every deploy, so a module-scope throttle there is global to one
51
+ * isolate only: a guesser reaching N isolates gets N × `globalThreshold` free failures,
52
+ * and one built per REQUEST has no memory at all (patterns' Worker until 2026-09-23). A
53
+ * Worker keeps its ledger in a Durable Object instead — `./loginThrottleDurable.ts`
54
+ * (`cursedbelt-server/login-throttle/durable`), which serves THIS algorithm from one
55
+ * named object and persists it, so every isolate and every colo meets the same counts.
56
+ *
57
+ * ── `attempt`, not `check` then `recordFailure` ─────────────────────────────
58
+ * `check` → verify → `recordFailure` has a gap exactly as long as the verify: argon2id,
59
+ * hundreds of ms. Every request that arrives inside it reads the same count, so K
60
+ * concurrent guesses are all admitted and the counter learns of them afterwards — the
61
+ * throttle limits guesses per BURST, and the burst is as wide as the attacker's
62
+ * concurrency. `attempt` closes the gap: it checks and, when admitted, charges a
63
+ * failure in the same synchronous step, so the (threshold+1)th concurrent request is
64
+ * refused. A success then clears the charge (`recordSuccess`), and a failure needs no
65
+ * second call. The Durable Object serves `attempt` as one operation for the same reason.
66
+ *
48
67
  * Pair with the coarse per-IP `createRateLimiter` (`../middleware/rateLimit`); this is
49
68
  * the strict per-identity layer.
50
69
  */
@@ -73,6 +92,26 @@ export interface LoginThrottleOptions {
73
92
  windowMs?: number;
74
93
  /** Hard cap on tracked keys, so the table cannot be a memory vector. Default 4096. */
75
94
  maxKeys?: number;
95
+ /**
96
+ * Start from a persisted {@link LoginThrottle.snapshot} rather than empty — how a Durable
97
+ * Object (`./loginThrottleDurable.ts`) survives its own eviction. An unreadable snapshot
98
+ * (wrong version, wrong shape) starts EMPTY for the keys and is ignored, never thrown on.
99
+ */
100
+ restore?: LoginThrottleSnapshot | null;
101
+ }
102
+ /** One key's (or the global counter's) ledger line — the unit {@link LoginThrottleSnapshot} holds. */
103
+ export interface LoginThrottleEntry {
104
+ failures: number;
105
+ /** When the current lockout ends; 0 when not locked. */
106
+ lockedUntil: number;
107
+ lastSeen: number;
108
+ }
109
+ /** A throttle's whole state as plain data, for a store that outlives the throttle. */
110
+ export interface LoginThrottleSnapshot {
111
+ v: 1;
112
+ global: LoginThrottleEntry;
113
+ /** Most recently seen first, `[normalizedKey, entry]`. */
114
+ entries: Array<[string, LoginThrottleEntry]>;
76
115
  }
77
116
  export type ThrottleVerdict = {
78
117
  allowed: true;
@@ -84,6 +123,13 @@ export type ThrottleVerdict = {
84
123
  export interface LoginThrottle {
85
124
  /** May this key attempt a login right now? */
86
125
  check(key: string): ThrottleVerdict;
126
+ /**
127
+ * `check`, and when allowed, charge a failure in the SAME step — so concurrent attempts
128
+ * cannot all be admitted against one count. Follow an allowed attempt with
129
+ * `recordSuccess` when the credential was right; a wrong one needs no further call.
130
+ * See the header's `attempt` section.
131
+ */
132
+ attempt(key: string): ThrottleVerdict;
87
133
  /** Record a failed attempt. Returns the verdict the NEXT attempt would get. */
88
134
  recordFailure(key: string): ThrottleVerdict;
89
135
  /** Record a success — clears this key and the global counter. */
@@ -92,7 +138,23 @@ export interface LoginThrottle {
92
138
  reset(key: string): void;
93
139
  /** Tracked-key count, for the bounded-growth test. */
94
140
  readonly size: number;
141
+ /** The state as plain data — the `limit` most recently seen keys (default all) and the global counter. */
142
+ snapshot(limit?: number): LoginThrottleSnapshot;
143
+ }
144
+ /**
145
+ * The same ledger across a round trip — `createRemoteLoginThrottle` in
146
+ * `./loginThrottleDurable.ts`. A door that awaits every call takes either shape:
147
+ * {@link LoginThrottleLike}.
148
+ */
149
+ export interface AsyncLoginThrottle {
150
+ check(key: string): Promise<ThrottleVerdict>;
151
+ attempt(key: string): Promise<ThrottleVerdict>;
152
+ recordFailure(key: string): Promise<ThrottleVerdict>;
153
+ recordSuccess(key: string): Promise<void>;
154
+ reset(key: string): Promise<void>;
95
155
  }
156
+ /** What a sign-in handler should accept: the in-process throttle or the Durable Object's. */
157
+ export type LoginThrottleLike = LoginThrottle | AsyncLoginThrottle;
96
158
  /**
97
159
  * The client address to key on — the LAST `X-Forwarded-For` entry (what our proxy
98
160
  * saw), falling back to `X-Real-IP`, the socket peer, and finally a shared constant.
@@ -45,6 +45,25 @@
45
45
  * global counter keeps working after eviction, which is precisely the case where it
46
46
  * matters most.
47
47
  *
48
+ * 🔴 **"Per-process" is one ISOLATE on a Cloudflare Worker, and that is not a process.**
49
+ * Cloudflare runs an isolate per colo (often several), discards them without warning and
50
+ * builds a fresh one on every deploy, so a module-scope throttle there is global to one
51
+ * isolate only: a guesser reaching N isolates gets N × `globalThreshold` free failures,
52
+ * and one built per REQUEST has no memory at all (patterns' Worker until 2026-09-23). A
53
+ * Worker keeps its ledger in a Durable Object instead — `./loginThrottleDurable.ts`
54
+ * (`cursedbelt-server/login-throttle/durable`), which serves THIS algorithm from one
55
+ * named object and persists it, so every isolate and every colo meets the same counts.
56
+ *
57
+ * ── `attempt`, not `check` then `recordFailure` ─────────────────────────────
58
+ * `check` → verify → `recordFailure` has a gap exactly as long as the verify: argon2id,
59
+ * hundreds of ms. Every request that arrives inside it reads the same count, so K
60
+ * concurrent guesses are all admitted and the counter learns of them afterwards — the
61
+ * throttle limits guesses per BURST, and the burst is as wide as the attacker's
62
+ * concurrency. `attempt` closes the gap: it checks and, when admitted, charges a
63
+ * failure in the same synchronous step, so the (threshold+1)th concurrent request is
64
+ * refused. A success then clears the charge (`recordSuccess`), and a failure needs no
65
+ * second call. The Durable Object serves `attempt` as one operation for the same reason.
66
+ *
48
67
  * Pair with the coarse per-IP `createRateLimiter` (`../middleware/rateLimit`); this is
49
68
  * the strict per-identity layer.
50
69
  */
@@ -98,6 +117,16 @@ export function clientKeyOfContext(req, env) {
98
117
  }
99
118
  return clientKeyOf(req, address);
100
119
  }
120
+ /** A persisted entry is trusted only as far as its three numbers are finite. */
121
+ const readEntry = (raw) => {
122
+ const e = raw;
123
+ if (!e || typeof e !== 'object')
124
+ return null;
125
+ const { failures, lockedUntil, lastSeen } = e;
126
+ if (![failures, lockedUntil, lastSeen].every((n) => typeof n === 'number' && Number.isFinite(n)))
127
+ return null;
128
+ return { failures: failures, lockedUntil: lockedUntil, lastSeen: lastSeen };
129
+ };
101
130
  /**
102
131
  * Keys are compared case- and whitespace-insensitively.
103
132
  *
@@ -119,6 +148,21 @@ export function createLoginThrottle(options = {}) {
119
148
  const maxKeys = options.maxKeys ?? 4096;
120
149
  const attempts = new Map();
121
150
  const global = { failures: 0, lockedUntil: 0, lastSeen: 0 };
151
+ const restored = options.restore;
152
+ if (restored && restored.v === 1) {
153
+ const g = readEntry(restored.global);
154
+ if (g)
155
+ Object.assign(global, g);
156
+ // Oldest first, so the Map's insertion order matches what it would have been live.
157
+ const entries = Array.isArray(restored.entries) ? [...restored.entries].reverse() : [];
158
+ for (const pair of entries) {
159
+ if (!Array.isArray(pair) || typeof pair[0] !== 'string')
160
+ continue;
161
+ const entry = readEntry(pair[1]);
162
+ if (entry)
163
+ attempts.set(normalizeKey(pair[0]), entry);
164
+ }
165
+ }
122
166
  /** Delay for the nth failure past a threshold: base·2^(n-1), capped. */
123
167
  const delayFor = (failures, limit, cap) => {
124
168
  const past = failures - limit;
@@ -162,10 +206,18 @@ export function createLoginThrottle(options = {}) {
162
206
  }
163
207
  return { allowed: true };
164
208
  };
165
- return {
209
+ const api = {
166
210
  check(key) {
167
211
  return verdict(key, now());
168
212
  },
213
+ attempt(key) {
214
+ const gate = verdict(key, now());
215
+ if (!gate.allowed)
216
+ return gate;
217
+ // Charged BEFORE the caller verifies anything — see the header's `attempt` section.
218
+ api.recordFailure(key);
219
+ return gate;
220
+ },
169
221
  recordFailure(rawKey) {
170
222
  const key = normalizeKey(rawKey);
171
223
  const nowMs = now();
@@ -200,5 +252,15 @@ export function createLoginThrottle(options = {}) {
200
252
  get size() {
201
253
  return attempts.size;
202
254
  },
255
+ snapshot(limit) {
256
+ const byRecency = [...attempts.entries()].sort((a, b) => b[1].lastSeen - a[1].lastSeen);
257
+ const kept = limit === undefined ? byRecency : byRecency.slice(0, Math.max(0, limit));
258
+ return {
259
+ v: 1,
260
+ global: { ...global },
261
+ entries: kept.map(([key, entry]) => [key, { ...entry }]),
262
+ };
263
+ },
203
264
  };
265
+ return api;
204
266
  }
@@ -0,0 +1,120 @@
1
+ /**
2
+ * The login throttle on a Cloudflare Worker: ONE Durable Object holds the ledger, every isolate
3
+ * asks it.
4
+ *
5
+ * ── Why this exists (2026-09-23, patterns task 2136) ─────────────────────────
6
+ * `createLoginThrottle` keeps its counts in memory, and its header accepts that because on the
7
+ * Mac "memory" is the one process an attacker cannot restart. On a Worker there is no such
8
+ * process. `apps/patterns`' Worker first built the throttle per REQUEST — every attempt was a
9
+ * first attempt, so the sign-in had no failed-login brake at all — and then per ISOLATE, which
10
+ * is still one ledger per colo (often several per colo), each wiped by every deploy: a guesser
11
+ * spread across N isolates gets N × the global allowance the header calls "the actual defense".
12
+ *
13
+ * A Durable Object is the exact shape of the fix: one instance addressed by name, requests to it
14
+ * serialised, so every isolate in every colo meets the same counts. It runs the SAME
15
+ * `createLoginThrottle` algorithm — nothing here re-decides a threshold or a delay — and persists
16
+ * the ledger to the object's storage after every change, so the object's own eviction (minutes
17
+ * idle, measured on patterns' live object) forgets nothing either.
18
+ *
19
+ * ── Why not D1 ──────────────────────────────────────────────────────────────
20
+ * The throttle is checked BEFORE argon2, on every attempt, and the point of checking first is
21
+ * that a refused attempt is cheap. A D1 read-modify-write per attempt is a query against the
22
+ * invocation's 1,000-query budget and, worse, not atomic across concurrent invocations: two
23
+ * guesses that snapshot the same count both write count+1. The object serialises for free.
24
+ *
25
+ * ── `attempt` is one operation, not two ─────────────────────────────────────
26
+ * `/throttle/attempt` checks and charges in one serialised step, so a burst of concurrent guesses
27
+ * is admitted only up to the threshold rather than all at once against one stale count. See
28
+ * `loginThrottle.ts`'s `attempt` section.
29
+ *
30
+ * ── When the object cannot be reached ───────────────────────────────────────
31
+ * {@link createRemoteLoginThrottle} takes a `fallback` — the isolate's own module-scope
32
+ * throttle — and MIRRORS every write into it. The object is the authority whenever it answers;
33
+ * when a call throws or answers non-2xx, the fallback decides and the error is logged. So an
34
+ * outage degrades the door to exactly the per-isolate brake it had before, never to none, and
35
+ * never to a 500 the owner cannot sign in past. Without a `fallback` the error propagates.
36
+ *
37
+ * ── Types are structural ────────────────────────────────────────────────────
38
+ * No `@cloudflare/workers-types`: an app whose `src/server` also runs under Bun cannot take Worker
39
+ * globals over its whole type graph (patterns measured five broken `randomBytes(n)` calls the one
40
+ * time it tried). The object uses the classic `fetch` interface for the same reason.
41
+ */
42
+ import { type AsyncLoginThrottle, type LoginThrottle, type LoginThrottleOptions } from './loginThrottle.js';
43
+ /** The name every isolate addresses unless told otherwise — one object, one ledger set. */
44
+ export declare const LOGIN_THROTTLE_OBJECT_NAME = "login-throttle";
45
+ /**
46
+ * Every operation the object answers, `[method, path]` — for an app's CPU-budget census, which
47
+ * must declare each path a tail can deliver. `loginThrottleDurable.spec.ts` reds if the object
48
+ * answers a path not listed here, or stops answering one that is.
49
+ */
50
+ export declare const LOGIN_THROTTLE_OPERATIONS: readonly [readonly ["POST", "/throttle/check"], readonly ["POST", "/throttle/attempt"], readonly ["POST", "/throttle/fail"], readonly ["POST", "/throttle/ok"], readonly ["POST", "/throttle/reset"]];
51
+ /**
52
+ * Keys persisted per ledger — the most recently seen. The in-memory table keeps its own
53
+ * `maxKeys` cap; this one keeps a stored value well under a Durable Object's per-value limit
54
+ * (128 KiB on the KV backend) at roughly 80 bytes a key. The global counter is always kept, and
55
+ * it is the counter a distributed guesser meets, so a key dropped here costs a courtesy layer
56
+ * only.
57
+ */
58
+ export declare const PERSISTED_KEYS = 1024;
59
+ /** The two members of `DurableObjectStorage` this reads — the KV API, on either backend. */
60
+ export interface DurableStorageLike {
61
+ get<T = unknown>(key: string): Promise<T | undefined>;
62
+ put<T>(key: string, value: T): Promise<void>;
63
+ }
64
+ /** The members of `DurableObjectState` this reads. */
65
+ export interface DurableStateLike {
66
+ storage: DurableStorageLike;
67
+ blockConcurrencyWhile?<T>(callback: () => Promise<T>): Promise<T>;
68
+ }
69
+ /** The members of a `DurableObjectNamespace` binding the client calls. */
70
+ export interface DurableNamespaceLike {
71
+ idFromName(name: string): unknown;
72
+ get(id: unknown): {
73
+ fetch(request: Request): Promise<Response>;
74
+ };
75
+ }
76
+ /**
77
+ * The Durable Object. Re-export it from the Worker's entry under the `class_name` your
78
+ * `wrangler.jsonc` binds, and add it in a migration (`new_sqlite_classes`):
79
+ *
80
+ * export { LoginThrottleObject as PatternsThrottle } from "cursedbelt-server/login-throttle/durable";
81
+ *
82
+ * One object holds any number of named LEDGERS (`owner`, `probe`, …), each an independent
83
+ * `createLoginThrottle` persisted under `ledger:<name>`.
84
+ */
85
+ export declare class LoginThrottleObject {
86
+ private readonly ledgers;
87
+ private readonly storage;
88
+ private readonly options;
89
+ /**
90
+ * `options` is for tests (a clock, a threshold); the runtime passes `(state, env)` only, and
91
+ * the throttle's own defaults are the fleet's.
92
+ */
93
+ constructor(state: DurableStateLike, _env?: unknown, options?: LoginThrottleOptions);
94
+ /**
95
+ * The ledger, loaded once per object lifetime. The PROMISE is memoised, not the result, so two
96
+ * requests arriving while the first load is in flight share it rather than each restoring its
97
+ * own copy and one of them overwriting the other's charge.
98
+ */
99
+ private ledger;
100
+ private persist;
101
+ fetch(request: Request): Promise<Response>;
102
+ }
103
+ export interface RemoteLoginThrottleOptions {
104
+ /** Which ledger in the object. Default `"default"`. A second ledger never spends the first's. */
105
+ ledger?: string;
106
+ /** Which object. Default {@link LOGIN_THROTTLE_OBJECT_NAME}. */
107
+ objectName?: string;
108
+ /**
109
+ * The isolate's own throttle, at MODULE scope — mirrored on every write and consulted only when
110
+ * the object cannot answer. See the header. Omitted → an unreachable object is an error.
111
+ */
112
+ fallback?: LoginThrottle;
113
+ /** Where an unreachable-object line goes. Default `console.error`. */
114
+ onError?: (line: string) => void;
115
+ }
116
+ /**
117
+ * The client half: an {@link AsyncLoginThrottle} whose ledger lives in the object. Cheap to build —
118
+ * build it per request over `env.<BINDING>`; the state is on the other side of the call.
119
+ */
120
+ export declare function createRemoteLoginThrottle(namespace: DurableNamespaceLike, options?: RemoteLoginThrottleOptions): AsyncLoginThrottle;
@@ -0,0 +1,231 @@
1
+ /**
2
+ * The login throttle on a Cloudflare Worker: ONE Durable Object holds the ledger, every isolate
3
+ * asks it.
4
+ *
5
+ * ── Why this exists (2026-09-23, patterns task 2136) ─────────────────────────
6
+ * `createLoginThrottle` keeps its counts in memory, and its header accepts that because on the
7
+ * Mac "memory" is the one process an attacker cannot restart. On a Worker there is no such
8
+ * process. `apps/patterns`' Worker first built the throttle per REQUEST — every attempt was a
9
+ * first attempt, so the sign-in had no failed-login brake at all — and then per ISOLATE, which
10
+ * is still one ledger per colo (often several per colo), each wiped by every deploy: a guesser
11
+ * spread across N isolates gets N × the global allowance the header calls "the actual defense".
12
+ *
13
+ * A Durable Object is the exact shape of the fix: one instance addressed by name, requests to it
14
+ * serialised, so every isolate in every colo meets the same counts. It runs the SAME
15
+ * `createLoginThrottle` algorithm — nothing here re-decides a threshold or a delay — and persists
16
+ * the ledger to the object's storage after every change, so the object's own eviction (minutes
17
+ * idle, measured on patterns' live object) forgets nothing either.
18
+ *
19
+ * ── Why not D1 ──────────────────────────────────────────────────────────────
20
+ * The throttle is checked BEFORE argon2, on every attempt, and the point of checking first is
21
+ * that a refused attempt is cheap. A D1 read-modify-write per attempt is a query against the
22
+ * invocation's 1,000-query budget and, worse, not atomic across concurrent invocations: two
23
+ * guesses that snapshot the same count both write count+1. The object serialises for free.
24
+ *
25
+ * ── `attempt` is one operation, not two ─────────────────────────────────────
26
+ * `/throttle/attempt` checks and charges in one serialised step, so a burst of concurrent guesses
27
+ * is admitted only up to the threshold rather than all at once against one stale count. See
28
+ * `loginThrottle.ts`'s `attempt` section.
29
+ *
30
+ * ── When the object cannot be reached ───────────────────────────────────────
31
+ * {@link createRemoteLoginThrottle} takes a `fallback` — the isolate's own module-scope
32
+ * throttle — and MIRRORS every write into it. The object is the authority whenever it answers;
33
+ * when a call throws or answers non-2xx, the fallback decides and the error is logged. So an
34
+ * outage degrades the door to exactly the per-isolate brake it had before, never to none, and
35
+ * never to a 500 the owner cannot sign in past. Without a `fallback` the error propagates.
36
+ *
37
+ * ── Types are structural ────────────────────────────────────────────────────
38
+ * No `@cloudflare/workers-types`: an app whose `src/server` also runs under Bun cannot take Worker
39
+ * globals over its whole type graph (patterns measured five broken `randomBytes(n)` calls the one
40
+ * time it tried). The object uses the classic `fetch` interface for the same reason.
41
+ */
42
+ import { createLoginThrottle, } from './loginThrottle.js';
43
+ /** The name every isolate addresses unless told otherwise — one object, one ledger set. */
44
+ export const LOGIN_THROTTLE_OBJECT_NAME = 'login-throttle';
45
+ /**
46
+ * Every operation the object answers, `[method, path]` — for an app's CPU-budget census, which
47
+ * must declare each path a tail can deliver. `loginThrottleDurable.spec.ts` reds if the object
48
+ * answers a path not listed here, or stops answering one that is.
49
+ */
50
+ export const LOGIN_THROTTLE_OPERATIONS = [
51
+ ['POST', '/throttle/check'],
52
+ ['POST', '/throttle/attempt'],
53
+ ['POST', '/throttle/fail'],
54
+ ['POST', '/throttle/ok'],
55
+ ['POST', '/throttle/reset'],
56
+ ];
57
+ /**
58
+ * Keys persisted per ledger — the most recently seen. The in-memory table keeps its own
59
+ * `maxKeys` cap; this one keeps a stored value well under a Durable Object's per-value limit
60
+ * (128 KiB on the KV backend) at roughly 80 bytes a key. The global counter is always kept, and
61
+ * it is the counter a distributed guesser meets, so a key dropped here costs a courtesy layer
62
+ * only.
63
+ */
64
+ export const PERSISTED_KEYS = 1024;
65
+ /** A ledger is a short slug — the object keys its storage by it. */
66
+ const LEDGER = /^[a-z0-9][a-z0-9-]{0,31}$/;
67
+ /** Longer than any address or `<email>:<ip>`; a bound so a key cannot be a storage vector. */
68
+ const MAX_KEY_CHARS = 320;
69
+ const json = (value, status = 200) => new Response(JSON.stringify(value ?? null), {
70
+ status,
71
+ headers: { 'content-type': 'application/json' },
72
+ });
73
+ /**
74
+ * The Durable Object. Re-export it from the Worker's entry under the `class_name` your
75
+ * `wrangler.jsonc` binds, and add it in a migration (`new_sqlite_classes`):
76
+ *
77
+ * export { LoginThrottleObject as PatternsThrottle } from "cursedbelt-server/login-throttle/durable";
78
+ *
79
+ * One object holds any number of named LEDGERS (`owner`, `probe`, …), each an independent
80
+ * `createLoginThrottle` persisted under `ledger:<name>`.
81
+ */
82
+ export class LoginThrottleObject {
83
+ ledgers = new Map();
84
+ storage;
85
+ options;
86
+ /**
87
+ * `options` is for tests (a clock, a threshold); the runtime passes `(state, env)` only, and
88
+ * the throttle's own defaults are the fleet's.
89
+ */
90
+ constructor(state, _env, options = {}) {
91
+ this.storage = state.storage;
92
+ this.options = options;
93
+ }
94
+ /**
95
+ * The ledger, loaded once per object lifetime. The PROMISE is memoised, not the result, so two
96
+ * requests arriving while the first load is in flight share it rather than each restoring its
97
+ * own copy and one of them overwriting the other's charge.
98
+ */
99
+ ledger(name) {
100
+ let loading = this.ledgers.get(name);
101
+ if (!loading) {
102
+ loading = this.storage
103
+ .get(`ledger:${name}`)
104
+ .then((restore) => createLoginThrottle({ ...this.options, restore: restore ?? null }));
105
+ // A failed load must not be cached as the ledger for the object's whole life.
106
+ loading.catch(() => this.ledgers.delete(name));
107
+ this.ledgers.set(name, loading);
108
+ }
109
+ return loading;
110
+ }
111
+ persist(name, throttle) {
112
+ return this.storage.put(`ledger:${name}`, throttle.snapshot(PERSISTED_KEYS));
113
+ }
114
+ async fetch(request) {
115
+ const path = new URL(request.url).pathname;
116
+ if (request.method !== 'POST')
117
+ return json({ error: `${request.method} ${path}: POST only` }, 405);
118
+ let body;
119
+ try {
120
+ body = (await request.json());
121
+ }
122
+ catch {
123
+ return json({ error: 'body must be JSON {ledger, key}' }, 400);
124
+ }
125
+ const name = body?.ledger;
126
+ const key = body?.key;
127
+ if (typeof name !== 'string' || !LEDGER.test(name))
128
+ return json({ error: 'ledger must be a short slug' }, 400);
129
+ if (typeof key !== 'string' || key.length === 0 || key.length > MAX_KEY_CHARS) {
130
+ return json({ error: `key must be 1–${MAX_KEY_CHARS} characters` }, 400);
131
+ }
132
+ const throttle = await this.ledger(name);
133
+ switch (path) {
134
+ case '/throttle/check':
135
+ return json(throttle.check(key));
136
+ case '/throttle/attempt': {
137
+ const verdict = throttle.attempt(key);
138
+ // A refused attempt changed nothing; an admitted one was charged and must be kept.
139
+ if (verdict.allowed)
140
+ await this.persist(name, throttle);
141
+ return json(verdict);
142
+ }
143
+ case '/throttle/fail': {
144
+ const verdict = throttle.recordFailure(key);
145
+ await this.persist(name, throttle);
146
+ return json(verdict);
147
+ }
148
+ case '/throttle/ok':
149
+ throttle.recordSuccess(key);
150
+ await this.persist(name, throttle);
151
+ return json({ ok: true });
152
+ case '/throttle/reset':
153
+ throttle.reset(key);
154
+ await this.persist(name, throttle);
155
+ return json({ ok: true });
156
+ default:
157
+ return json({ error: `no such throttle operation ${path}` }, 404);
158
+ }
159
+ }
160
+ }
161
+ /**
162
+ * The client half: an {@link AsyncLoginThrottle} whose ledger lives in the object. Cheap to build —
163
+ * build it per request over `env.<BINDING>`; the state is on the other side of the call.
164
+ */
165
+ export function createRemoteLoginThrottle(namespace, options = {}) {
166
+ const ledger = options.ledger ?? 'default';
167
+ if (!LEDGER.test(ledger))
168
+ throw new Error(`login throttle ledger "${ledger}" must be a short slug`);
169
+ const objectName = options.objectName ?? LOGIN_THROTTLE_OBJECT_NAME;
170
+ const fallback = options.fallback;
171
+ const onError = options.onError ?? ((line) => console.error(line));
172
+ const call = async (path, key) => {
173
+ const stub = namespace.get(namespace.idFromName(objectName));
174
+ const response = await stub.fetch(new Request(`https://login-throttle.invalid${path}`, {
175
+ method: 'POST',
176
+ headers: { 'content-type': 'application/json' },
177
+ body: JSON.stringify({ ledger, key }),
178
+ }));
179
+ if (!response.ok)
180
+ throw new Error(`${path} answered ${response.status}: ${await response.text()}`);
181
+ return (await response.json());
182
+ };
183
+ /** Ask the object; on failure, let the fallback answer (or rethrow when there is none). */
184
+ const remote = async (path, key, local) => {
185
+ try {
186
+ return await call(path, key);
187
+ }
188
+ catch (error) {
189
+ if (!local)
190
+ throw error;
191
+ onError(`[login-throttle] the "${objectName}" object did not answer ${path} (${error instanceof Error ? error.message : String(error)}) — ` +
192
+ `this isolate's own ledger decides, which is per-isolate only`);
193
+ return local();
194
+ }
195
+ };
196
+ return {
197
+ check: (key) => remote('/throttle/check', key, fallback && (() => fallback.check(key))),
198
+ async attempt(key) {
199
+ let mirrored = false;
200
+ const verdict = await remote('/throttle/attempt', key, fallback &&
201
+ (() => {
202
+ mirrored = true;
203
+ return fallback.attempt(key);
204
+ }));
205
+ // The mirror: an admitted attempt the object charged is charged here too, so an outage
206
+ // later in this isolate's life starts from what it has seen rather than from zero.
207
+ if (!mirrored && verdict.allowed)
208
+ fallback?.recordFailure(key);
209
+ return verdict;
210
+ },
211
+ async recordFailure(key) {
212
+ let mirrored = false;
213
+ const verdict = await remote('/throttle/fail', key, fallback &&
214
+ (() => {
215
+ mirrored = true;
216
+ return fallback.recordFailure(key);
217
+ }));
218
+ if (!mirrored)
219
+ fallback?.recordFailure(key);
220
+ return verdict;
221
+ },
222
+ async recordSuccess(key) {
223
+ fallback?.recordSuccess(key);
224
+ await remote('/throttle/ok', key, fallback && (() => null));
225
+ },
226
+ async reset(key) {
227
+ fallback?.reset(key);
228
+ await remote('/throttle/reset', key, fallback && (() => null));
229
+ },
230
+ };
231
+ }
@@ -0,0 +1,42 @@
1
+ import type { D1LikeDatabase } from "../d1/types.js";
2
+ /** What {@link MasterLockAttempts.charge} answers: admitted (and charged), or not (and not). */
3
+ export type MasterLockCharge = {
4
+ admitted: true;
5
+ failures: number;
6
+ } | {
7
+ admitted: false;
8
+ retryAfterMs: number;
9
+ };
10
+ export interface MasterLockAttempts {
11
+ /** What the ledger last knew, for the lock page's countdown. Never a decision. */
12
+ retryAfterMs(now: number): number;
13
+ /**
14
+ * 🔴 CHECK AND CHARGE in one step. Admitted → one failure is already charged, and
15
+ * `failures` counts it. Refused → nothing charged; `retryAfterMs` is the wait.
16
+ */
17
+ charge(now: number): MasterLockCharge | Promise<MasterLockCharge>;
18
+ /** The charged attempt was not a guess (nothing could be verified): take it back. */
19
+ refund(): void | Promise<void>;
20
+ /** A correct verifier: the run is over. */
21
+ clear(): void | Promise<void>;
22
+ }
23
+ /** The `meta`-style row a D1 ledger keeps its count in, beside the lock's record and state. */
24
+ export declare const MASTER_LOCK_ATTEMPTS_KEY = "master_lock:attempts";
25
+ /**
26
+ * `delayAfter` as a SQL `CASE` over a failure-count expression — GENERATED from the function,
27
+ * so the statement that admits a guess and the schedule the specs pin cannot disagree.
28
+ */
29
+ export declare function masterLockDelaySql(count: string): string;
30
+ /**
31
+ * The ledger over a D1 key/value table (`key TEXT PRIMARY KEY, value TEXT`) — `meta` by default,
32
+ * the table a Worker port already keeps the lock's record in, so it needs no migration.
33
+ *
34
+ * Its writes are AWAITED, never queued on a per-invocation collector: a charge that lands after
35
+ * the verify is the bug this exists to close. `snapshot` is the row as the request's own snapshot
36
+ * read it, for {@link MasterLockAttempts.retryAfterMs}; every decision reads D1 itself.
37
+ */
38
+ export declare function createD1MasterLockAttempts(db: D1LikeDatabase, options?: {
39
+ table?: string;
40
+ key?: string;
41
+ snapshot?: string | null;
42
+ }): MasterLockAttempts;