cursedbelt-server 4.24.0 → 4.25.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 +8 -0
- package/dist/server/auth/loginThrottle.d.ts +62 -0
- package/dist/server/auth/loginThrottle.js +63 -1
- package/dist/server/auth/loginThrottleDurable.d.ts +120 -0
- package/dist/server/auth/loginThrottleDurable.js +231 -0
- package/dist/server/worker-argon2/_nodeRefuses.d.ts +1 -0
- package/dist/server/worker-argon2/_nodeRefuses.js +13 -0
- package/package.json +8 -1
- package/src/leafSubpathsImportNothing.spec.ts +10 -0
- package/src/server/auth/loginThrottle.spec.ts +82 -0
- package/src/server/auth/loginThrottle.ts +108 -7
- package/src/server/auth/loginThrottleDurable.spec.ts +165 -0
- package/src/server/auth/loginThrottleDurable.ts +291 -0
- package/src/server/telemetryIsWorkerSafe.spec.ts +14 -0
- package/src/server/worker-argon2/_nodeRefuses.ts +16 -0
|
@@ -0,0 +1,291 @@
|
|
|
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 {
|
|
43
|
+
createLoginThrottle,
|
|
44
|
+
type AsyncLoginThrottle,
|
|
45
|
+
type LoginThrottle,
|
|
46
|
+
type LoginThrottleOptions,
|
|
47
|
+
type LoginThrottleSnapshot,
|
|
48
|
+
type ThrottleVerdict,
|
|
49
|
+
} from './loginThrottle.js';
|
|
50
|
+
|
|
51
|
+
/** The name every isolate addresses unless told otherwise — one object, one ledger set. */
|
|
52
|
+
export const LOGIN_THROTTLE_OBJECT_NAME = 'login-throttle';
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Every operation the object answers, `[method, path]` — for an app's CPU-budget census, which
|
|
56
|
+
* must declare each path a tail can deliver. `loginThrottleDurable.spec.ts` reds if the object
|
|
57
|
+
* answers a path not listed here, or stops answering one that is.
|
|
58
|
+
*/
|
|
59
|
+
export const LOGIN_THROTTLE_OPERATIONS = [
|
|
60
|
+
['POST', '/throttle/check'],
|
|
61
|
+
['POST', '/throttle/attempt'],
|
|
62
|
+
['POST', '/throttle/fail'],
|
|
63
|
+
['POST', '/throttle/ok'],
|
|
64
|
+
['POST', '/throttle/reset'],
|
|
65
|
+
] as const;
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Keys persisted per ledger — the most recently seen. The in-memory table keeps its own
|
|
69
|
+
* `maxKeys` cap; this one keeps a stored value well under a Durable Object's per-value limit
|
|
70
|
+
* (128 KiB on the KV backend) at roughly 80 bytes a key. The global counter is always kept, and
|
|
71
|
+
* it is the counter a distributed guesser meets, so a key dropped here costs a courtesy layer
|
|
72
|
+
* only.
|
|
73
|
+
*/
|
|
74
|
+
export const PERSISTED_KEYS = 1024;
|
|
75
|
+
|
|
76
|
+
/** A ledger is a short slug — the object keys its storage by it. */
|
|
77
|
+
const LEDGER = /^[a-z0-9][a-z0-9-]{0,31}$/;
|
|
78
|
+
/** Longer than any address or `<email>:<ip>`; a bound so a key cannot be a storage vector. */
|
|
79
|
+
const MAX_KEY_CHARS = 320;
|
|
80
|
+
|
|
81
|
+
/** The two members of `DurableObjectStorage` this reads — the KV API, on either backend. */
|
|
82
|
+
export interface DurableStorageLike {
|
|
83
|
+
get<T = unknown>(key: string): Promise<T | undefined>;
|
|
84
|
+
put<T>(key: string, value: T): Promise<void>;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** The members of `DurableObjectState` this reads. */
|
|
88
|
+
export interface DurableStateLike {
|
|
89
|
+
storage: DurableStorageLike;
|
|
90
|
+
blockConcurrencyWhile?<T>(callback: () => Promise<T>): Promise<T>;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** The members of a `DurableObjectNamespace` binding the client calls. */
|
|
94
|
+
export interface DurableNamespaceLike {
|
|
95
|
+
idFromName(name: string): unknown;
|
|
96
|
+
get(id: unknown): { fetch(request: Request): Promise<Response> };
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
const json = (value: unknown, status = 200): Response =>
|
|
100
|
+
new Response(JSON.stringify(value ?? null), {
|
|
101
|
+
status,
|
|
102
|
+
headers: { 'content-type': 'application/json' },
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* The Durable Object. Re-export it from the Worker's entry under the `class_name` your
|
|
107
|
+
* `wrangler.jsonc` binds, and add it in a migration (`new_sqlite_classes`):
|
|
108
|
+
*
|
|
109
|
+
* export { LoginThrottleObject as PatternsThrottle } from "cursedbelt-server/login-throttle/durable";
|
|
110
|
+
*
|
|
111
|
+
* One object holds any number of named LEDGERS (`owner`, `probe`, …), each an independent
|
|
112
|
+
* `createLoginThrottle` persisted under `ledger:<name>`.
|
|
113
|
+
*/
|
|
114
|
+
export class LoginThrottleObject {
|
|
115
|
+
private readonly ledgers = new Map<string, Promise<LoginThrottle>>();
|
|
116
|
+
private readonly storage: DurableStorageLike;
|
|
117
|
+
private readonly options: LoginThrottleOptions;
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* `options` is for tests (a clock, a threshold); the runtime passes `(state, env)` only, and
|
|
121
|
+
* the throttle's own defaults are the fleet's.
|
|
122
|
+
*/
|
|
123
|
+
constructor(state: DurableStateLike, _env?: unknown, options: LoginThrottleOptions = {}) {
|
|
124
|
+
this.storage = state.storage;
|
|
125
|
+
this.options = options;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* The ledger, loaded once per object lifetime. The PROMISE is memoised, not the result, so two
|
|
130
|
+
* requests arriving while the first load is in flight share it rather than each restoring its
|
|
131
|
+
* own copy and one of them overwriting the other's charge.
|
|
132
|
+
*/
|
|
133
|
+
private ledger(name: string): Promise<LoginThrottle> {
|
|
134
|
+
let loading = this.ledgers.get(name);
|
|
135
|
+
if (!loading) {
|
|
136
|
+
loading = this.storage
|
|
137
|
+
.get<LoginThrottleSnapshot>(`ledger:${name}`)
|
|
138
|
+
.then((restore) => createLoginThrottle({ ...this.options, restore: restore ?? null }));
|
|
139
|
+
// A failed load must not be cached as the ledger for the object's whole life.
|
|
140
|
+
loading.catch(() => this.ledgers.delete(name));
|
|
141
|
+
this.ledgers.set(name, loading);
|
|
142
|
+
}
|
|
143
|
+
return loading;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
private persist(name: string, throttle: LoginThrottle): Promise<void> {
|
|
147
|
+
return this.storage.put(`ledger:${name}`, throttle.snapshot(PERSISTED_KEYS));
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
async fetch(request: Request): Promise<Response> {
|
|
151
|
+
const path = new URL(request.url).pathname;
|
|
152
|
+
if (request.method !== 'POST') return json({ error: `${request.method} ${path}: POST only` }, 405);
|
|
153
|
+
let body: { ledger?: unknown; key?: unknown };
|
|
154
|
+
try {
|
|
155
|
+
body = (await request.json()) as typeof body;
|
|
156
|
+
} catch {
|
|
157
|
+
return json({ error: 'body must be JSON {ledger, key}' }, 400);
|
|
158
|
+
}
|
|
159
|
+
const name = body?.ledger;
|
|
160
|
+
const key = body?.key;
|
|
161
|
+
if (typeof name !== 'string' || !LEDGER.test(name)) return json({ error: 'ledger must be a short slug' }, 400);
|
|
162
|
+
if (typeof key !== 'string' || key.length === 0 || key.length > MAX_KEY_CHARS) {
|
|
163
|
+
return json({ error: `key must be 1–${MAX_KEY_CHARS} characters` }, 400);
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
const throttle = await this.ledger(name);
|
|
167
|
+
switch (path) {
|
|
168
|
+
case '/throttle/check':
|
|
169
|
+
return json(throttle.check(key));
|
|
170
|
+
case '/throttle/attempt': {
|
|
171
|
+
const verdict = throttle.attempt(key);
|
|
172
|
+
// A refused attempt changed nothing; an admitted one was charged and must be kept.
|
|
173
|
+
if (verdict.allowed) await this.persist(name, throttle);
|
|
174
|
+
return json(verdict);
|
|
175
|
+
}
|
|
176
|
+
case '/throttle/fail': {
|
|
177
|
+
const verdict = throttle.recordFailure(key);
|
|
178
|
+
await this.persist(name, throttle);
|
|
179
|
+
return json(verdict);
|
|
180
|
+
}
|
|
181
|
+
case '/throttle/ok':
|
|
182
|
+
throttle.recordSuccess(key);
|
|
183
|
+
await this.persist(name, throttle);
|
|
184
|
+
return json({ ok: true });
|
|
185
|
+
case '/throttle/reset':
|
|
186
|
+
throttle.reset(key);
|
|
187
|
+
await this.persist(name, throttle);
|
|
188
|
+
return json({ ok: true });
|
|
189
|
+
default:
|
|
190
|
+
return json({ error: `no such throttle operation ${path}` }, 404);
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
export interface RemoteLoginThrottleOptions {
|
|
196
|
+
/** Which ledger in the object. Default `"default"`. A second ledger never spends the first's. */
|
|
197
|
+
ledger?: string;
|
|
198
|
+
/** Which object. Default {@link LOGIN_THROTTLE_OBJECT_NAME}. */
|
|
199
|
+
objectName?: string;
|
|
200
|
+
/**
|
|
201
|
+
* The isolate's own throttle, at MODULE scope — mirrored on every write and consulted only when
|
|
202
|
+
* the object cannot answer. See the header. Omitted → an unreachable object is an error.
|
|
203
|
+
*/
|
|
204
|
+
fallback?: LoginThrottle;
|
|
205
|
+
/** Where an unreachable-object line goes. Default `console.error`. */
|
|
206
|
+
onError?: (line: string) => void;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* The client half: an {@link AsyncLoginThrottle} whose ledger lives in the object. Cheap to build —
|
|
211
|
+
* build it per request over `env.<BINDING>`; the state is on the other side of the call.
|
|
212
|
+
*/
|
|
213
|
+
export function createRemoteLoginThrottle(
|
|
214
|
+
namespace: DurableNamespaceLike,
|
|
215
|
+
options: RemoteLoginThrottleOptions = {},
|
|
216
|
+
): AsyncLoginThrottle {
|
|
217
|
+
const ledger = options.ledger ?? 'default';
|
|
218
|
+
if (!LEDGER.test(ledger)) throw new Error(`login throttle ledger "${ledger}" must be a short slug`);
|
|
219
|
+
const objectName = options.objectName ?? LOGIN_THROTTLE_OBJECT_NAME;
|
|
220
|
+
const fallback = options.fallback;
|
|
221
|
+
const onError = options.onError ?? ((line: string) => console.error(line));
|
|
222
|
+
|
|
223
|
+
const call = async <T>(path: string, key: string): Promise<T> => {
|
|
224
|
+
const stub = namespace.get(namespace.idFromName(objectName));
|
|
225
|
+
const response = await stub.fetch(
|
|
226
|
+
new Request(`https://login-throttle.invalid${path}`, {
|
|
227
|
+
method: 'POST',
|
|
228
|
+
headers: { 'content-type': 'application/json' },
|
|
229
|
+
body: JSON.stringify({ ledger, key }),
|
|
230
|
+
}),
|
|
231
|
+
);
|
|
232
|
+
if (!response.ok) throw new Error(`${path} answered ${response.status}: ${await response.text()}`);
|
|
233
|
+
return (await response.json()) as T;
|
|
234
|
+
};
|
|
235
|
+
|
|
236
|
+
/** Ask the object; on failure, let the fallback answer (or rethrow when there is none). */
|
|
237
|
+
const remote = async <T>(path: string, key: string, local: (() => T) | undefined): Promise<T> => {
|
|
238
|
+
try {
|
|
239
|
+
return await call<T>(path, key);
|
|
240
|
+
} catch (error) {
|
|
241
|
+
if (!local) throw error;
|
|
242
|
+
onError(
|
|
243
|
+
`[login-throttle] the "${objectName}" object did not answer ${path} (${error instanceof Error ? error.message : String(error)}) — ` +
|
|
244
|
+
`this isolate's own ledger decides, which is per-isolate only`,
|
|
245
|
+
);
|
|
246
|
+
return local();
|
|
247
|
+
}
|
|
248
|
+
};
|
|
249
|
+
|
|
250
|
+
return {
|
|
251
|
+
check: (key) => remote<ThrottleVerdict>('/throttle/check', key, fallback && (() => fallback.check(key))),
|
|
252
|
+
async attempt(key) {
|
|
253
|
+
let mirrored = false;
|
|
254
|
+
const verdict = await remote<ThrottleVerdict>(
|
|
255
|
+
'/throttle/attempt',
|
|
256
|
+
key,
|
|
257
|
+
fallback &&
|
|
258
|
+
(() => {
|
|
259
|
+
mirrored = true;
|
|
260
|
+
return fallback.attempt(key);
|
|
261
|
+
}),
|
|
262
|
+
);
|
|
263
|
+
// The mirror: an admitted attempt the object charged is charged here too, so an outage
|
|
264
|
+
// later in this isolate's life starts from what it has seen rather than from zero.
|
|
265
|
+
if (!mirrored && verdict.allowed) fallback?.recordFailure(key);
|
|
266
|
+
return verdict;
|
|
267
|
+
},
|
|
268
|
+
async recordFailure(key) {
|
|
269
|
+
let mirrored = false;
|
|
270
|
+
const verdict = await remote<ThrottleVerdict>(
|
|
271
|
+
'/throttle/fail',
|
|
272
|
+
key,
|
|
273
|
+
fallback &&
|
|
274
|
+
(() => {
|
|
275
|
+
mirrored = true;
|
|
276
|
+
return fallback.recordFailure(key);
|
|
277
|
+
}),
|
|
278
|
+
);
|
|
279
|
+
if (!mirrored) fallback?.recordFailure(key);
|
|
280
|
+
return verdict;
|
|
281
|
+
},
|
|
282
|
+
async recordSuccess(key) {
|
|
283
|
+
fallback?.recordSuccess(key);
|
|
284
|
+
await remote<unknown>('/throttle/ok', key, fallback && (() => null));
|
|
285
|
+
},
|
|
286
|
+
async reset(key) {
|
|
287
|
+
fallback?.reset(key);
|
|
288
|
+
await remote<unknown>('/throttle/reset', key, fallback && (() => null));
|
|
289
|
+
},
|
|
290
|
+
};
|
|
291
|
+
}
|
|
@@ -58,6 +58,20 @@ describe('🔴 cursedbelt-server/worker-argon2 — it exists to be imported by a
|
|
|
58
58
|
};
|
|
59
59
|
expect(pkg.exports['./worker-argon2']?.import).toBe('./dist/server/worker-argon2/index.js');
|
|
60
60
|
});
|
|
61
|
+
|
|
62
|
+
test('Node is refused by name — its WebAssembly ESM integration cannot load the static `.wasm` imports', async () => {
|
|
63
|
+
// 4.24.0 published with no `node` condition and failed proveInstall: node read the `.wasm`
|
|
64
|
+
// as an ES module and died on `Cannot find package 'env'`. wrangler never activates `node`
|
|
65
|
+
// (a dry-run bundle of the probe Worker carries both `.wasm` modules), so this costs a Worker nothing.
|
|
66
|
+
const pkg = JSON.parse(readFileSync(join(import.meta.dir, '..', '..', 'package.json'), 'utf8')) as {
|
|
67
|
+
exports: Record<string, Record<string, string>>;
|
|
68
|
+
};
|
|
69
|
+
const conditions = Object.keys(pkg.exports['./worker-argon2'] ?? {});
|
|
70
|
+
expect(pkg.exports['./worker-argon2']?.node).toBe('./dist/server/worker-argon2/_nodeRefuses.js');
|
|
71
|
+
expect(conditions.indexOf('node')).toBeLessThan(conditions.indexOf('import'));
|
|
72
|
+
expect(conditions.indexOf('bun')).toBeLessThan(conditions.indexOf('node'));
|
|
73
|
+
await expect(import('./worker-argon2/_nodeRefuses.ts')).rejects.toThrow('not Node');
|
|
74
|
+
});
|
|
61
75
|
});
|
|
62
76
|
|
|
63
77
|
describe('cursedbelt-server/telemetry', () => {
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
// Loaded only under Node — the `node` condition of `cursedbelt-server/worker-argon2`.
|
|
2
|
+
//
|
|
3
|
+
// This subpath's two `.wasm` files are STATIC imports, which is the one shape workerd will run
|
|
4
|
+
// (`./argon2.ts`). Node 24 reads the same import through its WebAssembly ESM integration and
|
|
5
|
+
// instantiates the module itself, resolving its imports from a package called `env` — so the
|
|
6
|
+
// real module fails under Node with `ERR_MODULE_NOT_FOUND: Cannot find package 'env'`, deep in
|
|
7
|
+
// `argon2id/dist/no-simd.wasm` (measured by tools/proveInstall.ts publishing 4.24.0, 2026-09-23).
|
|
8
|
+
// Nothing in this generation runs it on Node: a Worker gets it through wrangler (`workerd`
|
|
9
|
+
// resolves `import`), a Mac server through Bun (`bun`), and a Mac server already HAS
|
|
10
|
+
// `Bun.password`. So Node gets this sentence instead. Same shape as `../_bunOnly.ts`.
|
|
11
|
+
throw new Error(
|
|
12
|
+
"cursedbelt-server/worker-argon2 runs on workerd (through wrangler) and Bun — not Node, which cannot load its static `.wasm` imports. " +
|
|
13
|
+
"A Node server should hash with a native argon2 (`@node-rs/argon2`).",
|
|
14
|
+
);
|
|
15
|
+
|
|
16
|
+
export {};
|