cursedbelt-server 4.73.1 → 4.75.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.
@@ -16,9 +16,13 @@
16
16
  * 🔴 The door trusts nothing it is sent: every string is capped, the app's own query-key redaction
17
17
  * ({@link REDACTED_QUERY_KEY}, cursedbelt-core's, the copy `cursedbelt`'s reporter imports too) runs again
18
18
  * here, and the account is the session's, never the body's. It may be mounted outside the session
19
- * gate (a page that cannot sign in is exactly the page with a problem), so two bounds hold whoever
20
- * calls it: at most {@link ClientIssuesOptions.maxRowsPerHour} rows an hour per app, and rows older
21
- * than {@link ClientIssuesOptions.retentionMs} are purged on every write.
19
+ * gate (a page that cannot sign in is exactly the page with a problem), so three bounds hold whoever
20
+ * calls it: at most {@link ClientIssuesOptions.maxRowsPerHour} rows an hour per app, of which rows with
21
+ * no session's account (a stranger's as much as the sign-in page's) may be at most
22
+ * {@link ClientIssuesOptions.maxAnonymousRowsPerHour} — so a flood of anonymous posts cannot starve
23
+ * the signed-in reports out of the hour (forge task 5304) — and rows older than
24
+ * {@link ClientIssuesOptions.retentionMs} are purged on every write. An anonymous row's every field is
25
+ * a stranger's words: autopilot's reader fences them as such.
22
26
  *
23
27
  * 🔴 Worker-safe: nothing reachable from here at runtime imports `bun:*`.
24
28
  */
@@ -80,12 +84,22 @@ export interface ClientIssuesOptions {
80
84
  retentionMs?: number;
81
85
  /** Reports past this many in the last hour are refused (429). Default 600. */
82
86
  maxRowsPerHour?: number;
87
+ /**
88
+ * The share of {@link maxRowsPerHour} that rows with no session account may take; an anonymous
89
+ * report past it is refused (429) while signed-in reports still land. Default 100 (forge task 5304).
90
+ */
91
+ maxAnonymousRowsPerHour?: number;
83
92
  now?: () => number;
84
93
  }
85
- /** Write one row, purge the expired ones, refuse past the hourly bound. `"capped"` when refused. */
94
+ /**
95
+ * Write one row, purge the expired ones, refuse past the hourly bound — and an anonymous row (no
96
+ * `user_key`) past the anonymous share of it, so strangers can fill only their own share. `"capped"`
97
+ * when refused.
98
+ */
86
99
  export declare function recordClientIssueD1(db: D1LikeDatabase, row: ClientIssueRow, bounds: {
87
100
  retentionMs: number;
88
101
  maxRowsPerHour: number;
102
+ maxAnonymousRowsPerHour?: number;
89
103
  }): Promise<"recorded" | "capped">;
90
104
  /**
91
105
  * The one handler: take one posted report, answer 204 (400 malformed, 429 past the hourly bound).
@@ -89,14 +89,22 @@ const COLUMNS = [
89
89
  "facts",
90
90
  "report",
91
91
  ];
92
- /** Write one row, purge the expired ones, refuse past the hourly bound. `"capped"` when refused. */
92
+ /** The anonymous share of the hourly bound, when an app names none (forge task 5304). */
93
+ const DEFAULT_ANONYMOUS_ROWS_PER_HOUR = 100;
94
+ /**
95
+ * Write one row, purge the expired ones, refuse past the hourly bound — and an anonymous row (no
96
+ * `user_key`) past the anonymous share of it, so strangers can fill only their own share. `"capped"`
97
+ * when refused.
98
+ */
93
99
  export async function recordClientIssueD1(db, row, bounds) {
94
100
  const recent = await db
95
- .prepare("SELECT COUNT(*) AS n FROM client_issues WHERE at > ?")
101
+ .prepare("SELECT COUNT(*) AS n, COALESCE(SUM(CASE WHEN user_key = '' THEN 1 ELSE 0 END), 0) AS anonymous FROM client_issues WHERE at > ?")
96
102
  .bind(row.at - 3_600_000)
97
103
  .first();
98
104
  if ((recent?.n ?? 0) >= bounds.maxRowsPerHour)
99
105
  return "capped";
106
+ if (!row.user_key && (recent?.anonymous ?? 0) >= (bounds.maxAnonymousRowsPerHour ?? DEFAULT_ANONYMOUS_ROWS_PER_HOUR))
107
+ return "capped";
100
108
  await db.batch([
101
109
  db
102
110
  .prepare(`INSERT INTO client_issues (${COLUMNS.join(", ")}) VALUES (${COLUMNS.map(() => "?").join(", ")})`)
@@ -115,6 +123,7 @@ export function clientIssuesHandler(options) {
115
123
  const bounds = {
116
124
  retentionMs: options.retentionMs ?? 14 * 24 * 3_600_000,
117
125
  maxRowsPerHour: options.maxRowsPerHour ?? 600,
126
+ maxAnonymousRowsPerHour: options.maxAnonymousRowsPerHour ?? DEFAULT_ANONYMOUS_ROWS_PER_HOUR,
118
127
  };
119
128
  return async (c) => {
120
129
  let body;
@@ -27,6 +27,13 @@
27
27
  * here the insert itself refuses once the whole table holds `maxRows`, and the refusal THROWS
28
28
  * (→ 503 "send it again"), because a full table is the store unable to answer, not a bad payload.
29
29
  * A payload over `maxPayloadBytes` is refused as a bad one (→ 400), and its rows dropped.
30
+ *
31
+ * 🔴 ONE caller may hold at most `maxRowsPerCaller` of those rows (forge task 5306). With only the
32
+ * table-wide cap, one stranger sending "chunk 1 of 2" under fresh cids kept the table full and every
33
+ * real GET-only device's bulk write 503'd. Each row's `cid` is stored as `<caller hash>~<cid>`, the
34
+ * caller being the tunnel's `context.caller` (the edge's client address, IPv6 by /64), so a caller's
35
+ * rows are one PRIMARY KEY range to count — no schema change on the eight apps' D1s — and one caller's
36
+ * chunks can never join another's set. A caller over its share is refused like a full table (503).
30
37
  */
31
38
  import { type ChunkStoreOpts } from 'cursedbelt-core/ctgr/chunk-store';
32
39
  import type { D1LikeDatabase } from './d1/types.js';
@@ -40,6 +47,11 @@ export declare const CTGR_CHUNKS_DDL: readonly string[];
40
47
  export interface D1ChunkStoreOpts extends Pick<ChunkStoreOpts, 'maxPayloadBytes' | 'ttlMs' | 'now'> {
41
48
  /** Rows the whole table may hold before a new chunk is refused (→ 503). Default 4,000 (~10 MB). */
42
49
  maxRows?: number;
50
+ /**
51
+ * Rows ONE caller (the tunnel's `context.caller`) may hold before its next chunk is refused (→ 503).
52
+ * Default 400 — a tenth of the table, and ~700 KB of payload: far past any real bulk write.
53
+ */
54
+ maxRowsPerCaller?: number;
43
55
  }
44
56
  /**
45
57
  * A {@link CtgrChunkSink} for {@link mountCtgrTunnel} whose multi-chunk partials are rows in `db`.
@@ -27,6 +27,13 @@
27
27
  * here the insert itself refuses once the whole table holds `maxRows`, and the refusal THROWS
28
28
  * (→ 503 "send it again"), because a full table is the store unable to answer, not a bad payload.
29
29
  * A payload over `maxPayloadBytes` is refused as a bad one (→ 400), and its rows dropped.
30
+ *
31
+ * 🔴 ONE caller may hold at most `maxRowsPerCaller` of those rows (forge task 5306). With only the
32
+ * table-wide cap, one stranger sending "chunk 1 of 2" under fresh cids kept the table full and every
33
+ * real GET-only device's bulk write 503'd. Each row's `cid` is stored as `<caller hash>~<cid>`, the
34
+ * caller being the tunnel's `context.caller` (the edge's client address, IPv6 by /64), so a caller's
35
+ * rows are one PRIMARY KEY range to count — no schema change on the eight apps' D1s — and one caller's
36
+ * chunks can never join another's set. A caller over its share is refused like a full table (503).
30
37
  */
31
38
  import { ChunkStore } from 'cursedbelt-core/ctgr/chunk-store';
32
39
  import { parseChunk } from 'cursedbelt-core/ctgr';
@@ -43,6 +50,20 @@ export const CTGR_CHUNKS_DDL = [
43
50
  const DEFAULT_MAX_PAYLOAD_BYTES = 2 * 1024 * 1024;
44
51
  const DEFAULT_TTL_MS = 30_000;
45
52
  const DEFAULT_MAX_ROWS = 4_000;
53
+ const DEFAULT_MAX_ROWS_PER_CALLER = 400;
54
+ const CID = /^[A-Za-z0-9-]{1,64}$/;
55
+ /**
56
+ * The caller's namespace in `cid`: an FNV-1a hash of its address, so the table holds no address. A
57
+ * collision only makes two callers share one share.
58
+ */
59
+ function callerKey(caller) {
60
+ let h = 0x811c9dc5;
61
+ for (let i = 0; i < caller.length; i++) {
62
+ h ^= caller.charCodeAt(i);
63
+ h = Math.imul(h, 0x01000193);
64
+ }
65
+ return (h >>> 0).toString(36).padStart(7, '0');
66
+ }
46
67
  /**
47
68
  * A {@link CtgrChunkSink} for {@link mountCtgrTunnel} whose multi-chunk partials are rows in `db`.
48
69
  * Cheap to build — build it per request over the request's D1 handle.
@@ -51,11 +72,12 @@ export function createD1ChunkStore(db, options = {}) {
51
72
  const maxPayloadBytes = options.maxPayloadBytes ?? DEFAULT_MAX_PAYLOAD_BYTES;
52
73
  const ttlMs = options.ttlMs ?? DEFAULT_TTL_MS;
53
74
  const maxRows = options.maxRows ?? DEFAULT_MAX_ROWS;
75
+ const maxRowsPerCaller = options.maxRowsPerCaller ?? DEFAULT_MAX_ROWS_PER_CALLER;
54
76
  const now = options.now ?? Date.now;
55
77
  // The final decode's own caps: the size cap is this store's; its TTL never matters (one call).
56
78
  const decodeOpts = { maxPayloadBytes };
57
79
  return {
58
- async add(input) {
80
+ async add(input, context) {
59
81
  const params = input instanceof URLSearchParams ? Object.fromEntries(input) : { ...input };
60
82
  let chunk;
61
83
  try {
@@ -69,22 +91,29 @@ export function createD1ChunkStore(db, options = {}) {
69
91
  return new ChunkStore(decodeOpts).add(params);
70
92
  if (chunk.payloadLength > maxPayloadBytes)
71
93
  return new Error('ctgr: payload exceeds size cap');
94
+ // The codec's cid is a UUID. Anything past ASCII would sort outside the caller's counted range.
95
+ if (!CID.test(chunk.cid))
96
+ return new Error('ctgr: a chunk id is a short token of letters, digits and dashes');
72
97
  const at = now();
98
+ const owner = callerKey(context?.caller ?? '');
99
+ // A cid is [A-Za-z0-9-], all below `\x7f`, so `<owner>~<cid>` sorts inside [from, to): the caller's rows.
100
+ const cid = `${owner}~${chunk.cid}`;
101
+ const [from, to] = [`${owner}~`, `${owner}\x7f`];
73
102
  const [, , counted] = await db.batch([
74
103
  db.prepare(`DELETE FROM ${CTGR_CHUNKS_TABLE} WHERE at < ?`).bind(at - ttlMs),
75
104
  db
76
- .prepare(`INSERT OR IGNORE INTO ${CTGR_CHUNKS_TABLE} (cid, idx, total, bytes, params, at) SELECT ?, ?, ?, ?, ?, ? WHERE (SELECT COUNT(*) FROM ${CTGR_CHUNKS_TABLE}) < ?`)
77
- .bind(chunk.cid, chunk.index, chunk.total, chunk.bytes.length, JSON.stringify(params), at, maxRows),
105
+ .prepare(`INSERT OR IGNORE INTO ${CTGR_CHUNKS_TABLE} (cid, idx, total, bytes, params, at) SELECT ?, ?, ?, ?, ?, ? WHERE (SELECT COUNT(*) FROM ${CTGR_CHUNKS_TABLE}) < ? AND (SELECT COUNT(*) FROM ${CTGR_CHUNKS_TABLE} WHERE cid >= ? AND cid < ?) < ?`)
106
+ .bind(cid, chunk.index, chunk.total, chunk.bytes.length, JSON.stringify(params), at, maxRows, from, to, maxRowsPerCaller),
78
107
  db
79
108
  .prepare(`SELECT COUNT(*) AS n, COALESCE(SUM(bytes), 0) AS b, MAX(idx = ?) AS mine FROM ${CTGR_CHUNKS_TABLE} WHERE cid = ?`)
80
- .bind(chunk.index, chunk.cid),
109
+ .bind(chunk.index, cid),
81
110
  ]);
82
111
  const row = counted?.results[0];
83
- // Neither inserted now nor held from before: the table is at `maxRows`.
112
+ // Neither inserted now nor held from before: the table is at `maxRows`, or this caller at its share.
84
113
  if (!row?.mine)
85
- throw new Error(`ctgr: the chunk table is full (${maxRows} rows)`);
114
+ throw new Error(`ctgr: the chunk table is full (${maxRows} rows, ${maxRowsPerCaller} a caller)`);
86
115
  if (row.b > maxPayloadBytes) {
87
- await db.prepare(`DELETE FROM ${CTGR_CHUNKS_TABLE} WHERE cid = ?`).bind(chunk.cid).run();
116
+ await db.prepare(`DELETE FROM ${CTGR_CHUNKS_TABLE} WHERE cid = ?`).bind(cid).run();
88
117
  return new Error('ctgr: payload exceeds size cap');
89
118
  }
90
119
  if (row.n < chunk.total)
@@ -92,7 +121,7 @@ export function createD1ChunkStore(db, options = {}) {
92
121
  // Complete: claim the set. Only one request's DELETE can return its rows.
93
122
  const claimed = await db
94
123
  .prepare(`DELETE FROM ${CTGR_CHUNKS_TABLE} WHERE cid = ? RETURNING idx, params`)
95
- .bind(chunk.cid)
124
+ .bind(cid)
96
125
  .all();
97
126
  if (claimed.results.length < chunk.total)
98
127
  return false;
@@ -8,7 +8,15 @@ import type { Env, Hono } from 'hono';
8
8
  * a THROW means the store itself could not answer (→ 503).
9
9
  */
10
10
  export interface CtgrChunkSink {
11
- add(params: Record<string, string> | URLSearchParams): Promise<CtgrDecoded | false | Error>;
11
+ /**
12
+ * `context.caller` is who sent the chunk (`callerOfTwin` — the edge's client address, an IPv6 one by
13
+ * its /64), so a store shared by every caller can give each its own share (forge task 5306).
14
+ */
15
+ add(params: Record<string, string> | URLSearchParams,
16
+ /** `caller`: the edge's client address (`cf-connecting-ip`), an IPv6 one cut to its /64; `''` when none was sent. */
17
+ context?: {
18
+ caller?: string;
19
+ }): Promise<CtgrDecoded | false | Error>;
12
20
  }
13
21
  export interface CtgrTunnelOptions {
14
22
  /**
@@ -6,3 +6,9 @@ import type { CtgrChunkSink } from './ctgrTunnel.js';
6
6
  * unknown verb 404, an intermediate chunk 202, a bad payload 400, a store that could not answer 503).
7
7
  */
8
8
  export declare function decodeCtgrTwin(raw: Request, twinPath: string, store: CtgrChunkSink, legacy: V0ChunkStore): Promise<Request | Response>;
9
+ /**
10
+ * Who sent this twin, as one network: Cloudflare's `cf-connecting-ip` (the edge sets it and a client
11
+ * cannot), an IPv6 address cut to its /64 — one subscriber holds a whole /64, so a per-address share
12
+ * would be no share at all. `''` when the header is absent (a test, a host with no edge in front).
13
+ */
14
+ export declare function callerOfTwin(request: Request): string;
@@ -22,7 +22,7 @@ export async function decodeCtgrTwin(raw, twinPath, store, legacy) {
22
22
  return json({ error: 'not found', code: 'NOT_FOUND' }, 404);
23
23
  let result;
24
24
  try {
25
- result = params._cv === undefined ? legacy.add(params, pathMethod) : await store.add(params);
25
+ result = params._cv === undefined ? legacy.add(params, pathMethod) : await store.add(params, { caller: callerOfTwin(raw) });
26
26
  }
27
27
  catch (error) {
28
28
  console.error(`[ctgr] the chunk store could not answer: ${error instanceof Error ? error.message : String(error)}`);
@@ -34,6 +34,24 @@ export async function decodeCtgrTwin(raw, twinPath, store, legacy) {
34
34
  return json({ error: result.message, code: 'BAD_REQUEST' }, 400);
35
35
  return rebuildRequest(raw, twinPath, url, result);
36
36
  }
37
+ /**
38
+ * Who sent this twin, as one network: Cloudflare's `cf-connecting-ip` (the edge sets it and a client
39
+ * cannot), an IPv6 address cut to its /64 — one subscriber holds a whole /64, so a per-address share
40
+ * would be no share at all. `''` when the header is absent (a test, a host with no edge in front).
41
+ */
42
+ export function callerOfTwin(request) {
43
+ const ip = (request.headers.get('cf-connecting-ip') ?? '').trim().toLowerCase();
44
+ if (!ip.includes(':'))
45
+ return ip;
46
+ const [head = '', tail = ''] = ip.split('::');
47
+ const left = head ? head.split(':') : [];
48
+ const right = tail ? tail.split(':') : [];
49
+ const groups = ip.includes('::') ? [...left, ...Array(Math.max(0, 8 - left.length - right.length)).fill('0'), ...right] : left;
50
+ return `${groups
51
+ .slice(0, 4)
52
+ .map((g) => g.replace(/^0+(?=.)/, ''))
53
+ .join(':')}::/64`;
54
+ }
37
55
  /**
38
56
  * Did a browser say this twin came from somewhere else? `Sec-Fetch-Site` is set by the browser
39
57
  * and no page can forge it: only `same-origin` is the app's own `installCtgrFetch`. `none` (a
@@ -0,0 +1,95 @@
1
+ /**
2
+ * `cursedbelt-server/presence` — 🔴 an app nobody is using costs (close to) nothing (forge task 5325).
3
+ *
4
+ * The owner, 2026-11-16: *"if no one uses apps like photos, roms, flix, vault, desk, etc all day I don't
5
+ * want thousands of requests […] back and forth with no benefit."* Measured that day: the
6
+ * fleet's Worker crons fired ~6,500 times and spent ~172k CPU-ms — about a sixth of the account's Workers
7
+ * CPU, which the month was already past — and nearly all of it ran with nobody there. A five-minute cron
8
+ * is a promise to someone looking at the page; at 4 a.m. it is a promise to no one.
9
+ *
10
+ * So scheduled work keys on PRESENCE, not the clock (night is just the common case of idle):
11
+ *
12
+ * - **{@link createUseTick}** — work that used to run every few minutes runs on USE instead: a signed-in
13
+ * request kicks it under `waitUntil` when it is due, at most once per `everyMs` across every isolate
14
+ * ({@link claimTick} in D1). The Worker's own cron drops to the lowest cadence that is still correct
15
+ * with nobody there (an hourly backstop for queued work, the day's purge), and a stage tier keeps no
16
+ * cron at all: its tests in flight are the use that ticks it.
17
+ * - **{@link notePresence} / {@link lastPresence}** — for a Worker with no sign-in of its own (the media
18
+ * edge): it notes "a reader of <name> was here", throttled per isolate, and its cron asks before it
19
+ * spends anything.
20
+ * - **{@link lastHumanUse}** — for an app behind cursedauth's door: `sessions.last_seen_at` is ALREADY
21
+ * the signal. The door moves it on every signed-in request (`userIdOf`, throttled to a minute), so
22
+ * `MAX(last_seen_at)` is the tier's last human use, with no write of ours at all.
23
+ *
24
+ * Everything is created on first use (`presence_marks`, like `events_days` and the engagement tables),
25
+ * so no app's schema has to learn it. A failed claim runs nothing and warns: a lost tick is the next
26
+ * request's or the backstop cron's, never a double.
27
+ *
28
+ * `tools/check-idle-cost.ts` in the generation holds the other half: a sub-hourly cron or a stage cron
29
+ * that does not go through here is red.
30
+ *
31
+ * 🔴 Worker-safe: nothing here imports `bun:*`.
32
+ */
33
+ import type { D1LikeDatabase } from "../d1/types.js";
34
+ /** One row per name: a presence mark (`reader:<tenant>`) or a tick's last run (`tick:<name>`). */
35
+ export declare const PRESENCE_DDL: string[];
36
+ /** How often one isolate writes the same presence mark. Presence is an hours-scale question. */
37
+ export declare const PRESENCE_THROTTLE_MS: number;
38
+ /** The default "nobody is here" line: no use for this long and scheduled work stands down. */
39
+ export declare const IDLE_AFTER_MS: number;
40
+ /**
41
+ * Note that someone used `name` now. At most one D1 write per isolate per `throttleMs`, and the row only
42
+ * moves when it is older than that, so many isolates add up to a handful of writes an hour while anyone is
43
+ * there and none while no one is. Resolves `true` when it wrote; never throws (presence is advisory).
44
+ */
45
+ export declare function notePresence(db: D1LikeDatabase, name: string, options?: {
46
+ now?: () => number;
47
+ throttleMs?: number;
48
+ }): Promise<boolean>;
49
+ /** When `name` was last noted (epoch ms), or null — never noted, or no table yet. Throws on any other error. */
50
+ export declare function lastPresence(db: D1LikeDatabase, name: string): Promise<number | null>;
51
+ /**
52
+ * The tier's last human use behind cursedauth's door: `MAX(sessions.last_seen_at)`, which the door's
53
+ * `userIdOf` moves on every signed-in request. Null when nobody has a session, or the app has no
54
+ * `sessions` table. A row read per live session — a household's handful.
55
+ */
56
+ export declare function lastHumanUse(db: D1LikeDatabase): Promise<number | null>;
57
+ /** Whether a last use at `lastAt` still counts as someone being here. Null (never) is idle. Pure. */
58
+ export declare function isPresent(lastAt: number | null, now?: number, idleAfterMs?: number): boolean;
59
+ /**
60
+ * Claim tick `name` if its last run is at least `everyMs` old — one D1 statement, atomic, so of every
61
+ * isolate and cron that asks inside the window exactly one wins. `everyMs: 0` always wins: what a cron
62
+ * calls to record that it ran, so the next request does not run the same work again a minute later.
63
+ */
64
+ export declare function claimTick(db: D1LikeDatabase, name: string, everyMs: number, now?: number): Promise<boolean>;
65
+ /** When tick `name` last ran (epoch ms), or null. */
66
+ export declare const lastTick: (db: D1LikeDatabase, name: string) => Promise<number | null>;
67
+ export interface UseTickKick {
68
+ db: D1LikeDatabase;
69
+ /** The work — the same function the cron runs. Its errors are logged, never thrown at the request. */
70
+ run: () => Promise<unknown>;
71
+ /** The request's `ctx.waitUntil`: the tick never holds the answer. */
72
+ waitUntil: (promise: Promise<unknown>) => void;
73
+ now?: () => number;
74
+ }
75
+ export interface UseTick {
76
+ /** Start the tick behind this request if it is due. True when it was started (and won its claim or is asking). */
77
+ kick(input: UseTickKick): boolean;
78
+ }
79
+ /**
80
+ * Work that runs because someone is USING the app (see the header): `kick` on a signed-in request.
81
+ * The isolate remembers its last attempt, so a page's burst of requests costs one claim, and the claim
82
+ * in D1 keeps every isolate together to one run per `everyMs`.
83
+ */
84
+ export declare function createUseTick(options: {
85
+ name: string;
86
+ everyMs: number;
87
+ }): UseTick;
88
+ /**
89
+ * Whether a request is a person using the app — it carries the app's own session cookie. A stale cookie
90
+ * counts too: the price of a false yes is one tick, while a probe, a crawler, the Mac's bearer-token
91
+ * pipeline and `/healthz` carry no cookie and never tick anything.
92
+ */
93
+ export declare function carriesSession(request: Request, cookieName: string): boolean;
94
+ /** Test seam: forget what this isolate noted. */
95
+ export declare function resetPresenceMemo(): void;
@@ -0,0 +1,123 @@
1
+ /** One row per name: a presence mark (`reader:<tenant>`) or a tick's last run (`tick:<name>`). */
2
+ export const PRESENCE_DDL = ["CREATE TABLE IF NOT EXISTS presence_marks (name TEXT PRIMARY KEY, at INTEGER NOT NULL)"];
3
+ /** How often one isolate writes the same presence mark. Presence is an hours-scale question. */
4
+ export const PRESENCE_THROTTLE_MS = 5 * 60_000;
5
+ /** The default "nobody is here" line: no use for this long and scheduled work stands down. */
6
+ export const IDLE_AFTER_MS = 3 * 60 * 60_000;
7
+ const TICK_PREFIX = "tick:";
8
+ /** An upsert that only moves `at` when the row is older than `?3` — the claim and the throttled mark both. */
9
+ const UPSERT_IF_OLDER = "INSERT INTO presence_marks (name, at) VALUES (?1, ?2) ON CONFLICT(name) DO UPDATE SET at = excluded.at WHERE presence_marks.at <= ?3";
10
+ const isMissingTable = (error) => /no such table/i.test(String(error));
11
+ async function upsertIfOlder(db, name, at, olderThan) {
12
+ const run = () => db.prepare(UPSERT_IF_OLDER).bind(name, at, olderThan).run();
13
+ const result = await run().catch(async (error) => {
14
+ if (!isMissingTable(error))
15
+ throw error;
16
+ await db.batch(PRESENCE_DDL.map((ddl) => db.prepare(ddl)));
17
+ return run();
18
+ });
19
+ return (result.meta?.changes ?? 0) > 0;
20
+ }
21
+ /** What this isolate last wrote or attempted, per name — so a busy Worker asks D1 once per throttle. */
22
+ const noted = new Map();
23
+ /**
24
+ * Note that someone used `name` now. At most one D1 write per isolate per `throttleMs`, and the row only
25
+ * moves when it is older than that, so many isolates add up to a handful of writes an hour while anyone is
26
+ * there and none while no one is. Resolves `true` when it wrote; never throws (presence is advisory).
27
+ */
28
+ export async function notePresence(db, name, options = {}) {
29
+ const now = (options.now ?? Date.now)();
30
+ const throttle = options.throttleMs ?? PRESENCE_THROTTLE_MS;
31
+ const last = noted.get(name);
32
+ if (last !== undefined && now - last < throttle)
33
+ return false;
34
+ noted.set(name, now);
35
+ try {
36
+ return await upsertIfOlder(db, name, now, now - throttle);
37
+ }
38
+ catch (error) {
39
+ console.warn(`[presence] ${name} was not noted: ${String(error)}`);
40
+ return false;
41
+ }
42
+ }
43
+ /** When `name` was last noted (epoch ms), or null — never noted, or no table yet. Throws on any other error. */
44
+ export async function lastPresence(db, name) {
45
+ try {
46
+ const row = await db.prepare("SELECT at FROM presence_marks WHERE name = ?").bind(name).first();
47
+ return typeof row?.at === "number" ? row.at : null;
48
+ }
49
+ catch (error) {
50
+ if (isMissingTable(error))
51
+ return null;
52
+ throw error;
53
+ }
54
+ }
55
+ /**
56
+ * The tier's last human use behind cursedauth's door: `MAX(sessions.last_seen_at)`, which the door's
57
+ * `userIdOf` moves on every signed-in request. Null when nobody has a session, or the app has no
58
+ * `sessions` table. A row read per live session — a household's handful.
59
+ */
60
+ export async function lastHumanUse(db) {
61
+ try {
62
+ const row = await db.prepare("SELECT MAX(last_seen_at) AS at FROM sessions").first();
63
+ return typeof row?.at === "number" && row.at > 0 ? row.at : null;
64
+ }
65
+ catch (error) {
66
+ if (isMissingTable(error))
67
+ return null;
68
+ throw error;
69
+ }
70
+ }
71
+ /** Whether a last use at `lastAt` still counts as someone being here. Null (never) is idle. Pure. */
72
+ export function isPresent(lastAt, now = Date.now(), idleAfterMs = IDLE_AFTER_MS) {
73
+ return lastAt !== null && now - lastAt < idleAfterMs;
74
+ }
75
+ /**
76
+ * Claim tick `name` if its last run is at least `everyMs` old — one D1 statement, atomic, so of every
77
+ * isolate and cron that asks inside the window exactly one wins. `everyMs: 0` always wins: what a cron
78
+ * calls to record that it ran, so the next request does not run the same work again a minute later.
79
+ */
80
+ export async function claimTick(db, name, everyMs, now = Date.now()) {
81
+ return upsertIfOlder(db, TICK_PREFIX + name, now, now - everyMs);
82
+ }
83
+ /** When tick `name` last ran (epoch ms), or null. */
84
+ export const lastTick = (db, name) => lastPresence(db, TICK_PREFIX + name);
85
+ /**
86
+ * Work that runs because someone is USING the app (see the header): `kick` on a signed-in request.
87
+ * The isolate remembers its last attempt, so a page's burst of requests costs one claim, and the claim
88
+ * in D1 keeps every isolate together to one run per `everyMs`.
89
+ */
90
+ export function createUseTick(options) {
91
+ let attempted = Number.NEGATIVE_INFINITY;
92
+ return {
93
+ kick({ db, run, waitUntil, now = Date.now }) {
94
+ const at = now();
95
+ if (at - attempted < options.everyMs)
96
+ return false;
97
+ attempted = at;
98
+ waitUntil(claimTick(db, options.name, options.everyMs, at)
99
+ .then((won) => (won ? run() : undefined))
100
+ .catch((error) => console.warn(`[presence] the ${options.name} tick failed: ${String(error)}`)));
101
+ return true;
102
+ },
103
+ };
104
+ }
105
+ /**
106
+ * Whether a request is a person using the app — it carries the app's own session cookie. A stale cookie
107
+ * counts too: the price of a false yes is one tick, while a probe, a crawler, the Mac's bearer-token
108
+ * pipeline and `/healthz` carry no cookie and never tick anything.
109
+ */
110
+ export function carriesSession(request, cookieName) {
111
+ const cookie = request.headers.get("cookie");
112
+ if (!cookie)
113
+ return false;
114
+ return cookie.split(";").some((part) => {
115
+ const name = part.trim().split("=", 1)[0];
116
+ // cursedauth's account slots: `<base>` is slot 0, `<base>__<n>` the others (`slotCookieName`).
117
+ return name === cookieName || name.startsWith(`${cookieName}__`);
118
+ });
119
+ }
120
+ /** Test seam: forget what this isolate noted. */
121
+ export function resetPresenceMemo() {
122
+ noted.clear();
123
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cursedbelt-server",
3
- "version": "4.73.1",
3
+ "version": "4.75.0",
4
4
  "license": "ISC",
5
5
  "type": "module",
6
6
  "description": "The app-facing Bun/Hono server tier of the cursedbelt split — storage, sharing, activity, guard, sync. React-free; cursedbelt-core below it.",
@@ -168,6 +168,12 @@
168
168
  "source": "./src/server/events/index.ts",
169
169
  "import": "./dist/server/events/index.js"
170
170
  },
171
+ "./presence": {
172
+ "types": "./dist/server/presence/index.d.ts",
173
+ "bun": "./src/server/presence/index.ts",
174
+ "source": "./src/server/presence/index.ts",
175
+ "import": "./dist/server/presence/index.js"
176
+ },
171
177
  "./errors": {
172
178
  "types": "./dist/server/errors.d.ts",
173
179
  "bun": "./src/server/errors.ts",
@@ -441,7 +447,7 @@
441
447
  "@node-rs/argon2": "^2.0.2",
442
448
  "@types/bun": "^1.3.14",
443
449
  "@types/node": "^24",
444
- "cursedbelt": "^6.2.0",
450
+ "cursedbelt": "^6.9.1",
445
451
  "hono": "4.12.28",
446
452
  "kysely": "^0.28.17",
447
453
  "kysely-bun-sqlite": "^0.4.0",
@@ -113,6 +113,29 @@ describe('🔴 the door is bounded whoever calls it', () => {
113
113
  expect(sqlite.query('SELECT COUNT(*) AS n FROM client_issues').get()).toEqual({ n: 2 });
114
114
  });
115
115
 
116
+ test('🔴 strangers fill only their own share: past maxAnonymousRowsPerHour a signed-in report still lands (forge task 5304)', async () => {
117
+ const { sqlite, db } = fresh();
118
+ let signedIn = false;
119
+ const app = createD1ClientIssuesRecorder({ db, maxRowsPerHour: 5, maxAnonymousRowsPerHour: 2, resolveUser: () => (signedIn ? 'acct-1' : null), now: () => 5_000_000 });
120
+ expect((await post(app, report({ id: 'flood-1' }))).status).toBe(204);
121
+ expect((await post(app, report({ id: 'flood-2' }))).status).toBe(204);
122
+ expect((await post(app, report({ id: 'flood-3' }))).status).toBe(429);
123
+ signedIn = true;
124
+ expect((await post(app, report({ id: 'real-1' }))).status).toBe(204);
125
+ expect((await post(app, report({ id: 'real-2' }))).status).toBe(204);
126
+ expect((await post(app, report({ id: 'real-3' }))).status).toBe(204);
127
+ expect((await post(app, report({ id: 'real-4' }))).status).toBe(429);
128
+ expect(sqlite.query("SELECT COUNT(*) AS n FROM client_issues WHERE user_key = ''").get()).toEqual({ n: 2 });
129
+ });
130
+
131
+ test('the anonymous share defaults to 100 of the hour', async () => {
132
+ const { sqlite, db } = fresh();
133
+ const app = createD1ClientIssuesRecorder({ db, now: () => 5_000_000 });
134
+ const insert = sqlite.prepare("INSERT INTO client_issues (at, change, issue_id, area, stem, tone, outlook, title, started_at) VALUES (4999000, 'raised', 'x', 'a', 's', 'warning', '', 't', 0)");
135
+ for (let i = 0; i < 100; i++) insert.run();
136
+ expect((await post(app, report())).status).toBe(429);
137
+ });
138
+
116
139
  test('a write purges the rows older than the retention', async () => {
117
140
  const { sqlite, db } = fresh();
118
141
  let clock = 1_000;
@@ -16,9 +16,13 @@
16
16
  * 🔴 The door trusts nothing it is sent: every string is capped, the app's own query-key redaction
17
17
  * ({@link REDACTED_QUERY_KEY}, cursedbelt-core's, the copy `cursedbelt`'s reporter imports too) runs again
18
18
  * here, and the account is the session's, never the body's. It may be mounted outside the session
19
- * gate (a page that cannot sign in is exactly the page with a problem), so two bounds hold whoever
20
- * calls it: at most {@link ClientIssuesOptions.maxRowsPerHour} rows an hour per app, and rows older
21
- * than {@link ClientIssuesOptions.retentionMs} are purged on every write.
19
+ * gate (a page that cannot sign in is exactly the page with a problem), so three bounds hold whoever
20
+ * calls it: at most {@link ClientIssuesOptions.maxRowsPerHour} rows an hour per app, of which rows with
21
+ * no session's account (a stranger's as much as the sign-in page's) may be at most
22
+ * {@link ClientIssuesOptions.maxAnonymousRowsPerHour} — so a flood of anonymous posts cannot starve
23
+ * the signed-in reports out of the hour (forge task 5304) — and rows older than
24
+ * {@link ClientIssuesOptions.retentionMs} are purged on every write. An anonymous row's every field is
25
+ * a stranger's words: autopilot's reader fences them as such.
22
26
  *
23
27
  * 🔴 Worker-safe: nothing reachable from here at runtime imports `bun:*`.
24
28
  */
@@ -144,6 +148,9 @@ const COLUMNS = [
144
148
  "report",
145
149
  ] as const satisfies readonly (keyof ClientIssueRow)[];
146
150
 
151
+ /** The anonymous share of the hourly bound, when an app names none (forge task 5304). */
152
+ const DEFAULT_ANONYMOUS_ROWS_PER_HOUR = 100;
153
+
147
154
  export interface ClientIssuesOptions {
148
155
  /** The app's D1, or how to find it on the request. */
149
156
  db: D1LikeDatabase | ((c: Context) => D1LikeDatabase);
@@ -158,20 +165,30 @@ export interface ClientIssuesOptions {
158
165
  retentionMs?: number;
159
166
  /** Reports past this many in the last hour are refused (429). Default 600. */
160
167
  maxRowsPerHour?: number;
168
+ /**
169
+ * The share of {@link maxRowsPerHour} that rows with no session account may take; an anonymous
170
+ * report past it is refused (429) while signed-in reports still land. Default 100 (forge task 5304).
171
+ */
172
+ maxAnonymousRowsPerHour?: number;
161
173
  now?: () => number;
162
174
  }
163
175
 
164
- /** Write one row, purge the expired ones, refuse past the hourly bound. `"capped"` when refused. */
176
+ /**
177
+ * Write one row, purge the expired ones, refuse past the hourly bound — and an anonymous row (no
178
+ * `user_key`) past the anonymous share of it, so strangers can fill only their own share. `"capped"`
179
+ * when refused.
180
+ */
165
181
  export async function recordClientIssueD1(
166
182
  db: D1LikeDatabase,
167
183
  row: ClientIssueRow,
168
- bounds: { retentionMs: number; maxRowsPerHour: number },
184
+ bounds: { retentionMs: number; maxRowsPerHour: number; maxAnonymousRowsPerHour?: number },
169
185
  ): Promise<"recorded" | "capped"> {
170
186
  const recent = await db
171
- .prepare("SELECT COUNT(*) AS n FROM client_issues WHERE at > ?")
187
+ .prepare("SELECT COUNT(*) AS n, COALESCE(SUM(CASE WHEN user_key = '' THEN 1 ELSE 0 END), 0) AS anonymous FROM client_issues WHERE at > ?")
172
188
  .bind(row.at - 3_600_000)
173
- .first<{ n: number }>();
189
+ .first<{ n: number; anonymous: number }>();
174
190
  if ((recent?.n ?? 0) >= bounds.maxRowsPerHour) return "capped";
191
+ if (!row.user_key && (recent?.anonymous ?? 0) >= (bounds.maxAnonymousRowsPerHour ?? DEFAULT_ANONYMOUS_ROWS_PER_HOUR)) return "capped";
175
192
  await db.batch([
176
193
  db
177
194
  .prepare(`INSERT INTO client_issues (${COLUMNS.join(", ")}) VALUES (${COLUMNS.map(() => "?").join(", ")})`)
@@ -191,6 +208,7 @@ export function clientIssuesHandler(options: ClientIssuesOptions): (c: Context)
191
208
  const bounds = {
192
209
  retentionMs: options.retentionMs ?? 14 * 24 * 3_600_000,
193
210
  maxRowsPerHour: options.maxRowsPerHour ?? 600,
211
+ maxAnonymousRowsPerHour: options.maxAnonymousRowsPerHour ?? DEFAULT_ANONYMOUS_ROWS_PER_HOUR,
194
212
  };
195
213
  return async (c) => {
196
214
  let body: unknown;
@@ -128,6 +128,43 @@ describe('createD1ChunkStore — two isolates, one database', () => {
128
128
  expect(await store.add(chunks[0].params)).toBe(false);
129
129
  });
130
130
 
131
+ test('🔴 one caller flooding "chunk 1 of 2" under fresh cids cannot starve another caller (forge task 5306)', async () => {
132
+ const db = database();
133
+ const { chunks, body } = await multiChunk();
134
+ const share = chunks.length;
135
+ const store = createD1ChunkStore(db.handle(), { maxRows: share * 3, maxRowsPerCaller: share });
136
+ let refused = 0;
137
+ for (let n = 0; n < share * 4; n++) {
138
+ try {
139
+ await store.add({ ...chunks[0].params, _cid: `junk-${n}` }, { caller: '203.0.113.9' });
140
+ } catch {
141
+ refused++;
142
+ }
143
+ }
144
+ expect(refused).toBe(share * 3);
145
+ expect(db.rows()).toBe(share);
146
+ // Another caller's whole multi-chunk write still lands.
147
+ let result: unknown = false;
148
+ for (const chunk of chunks) result = await store.add(chunk.params, { caller: '198.51.100.4' });
149
+ expect(bodyOf(result)).toEqual(body);
150
+ });
151
+
152
+ test('one caller\'s chunks never join another caller\'s set of the same cid', async () => {
153
+ const db = database();
154
+ const store = createD1ChunkStore(db.handle());
155
+ const { chunks } = await multiChunk();
156
+ for (const chunk of chunks.slice(0, -1)) expect(await store.add(chunk.params, { caller: '198.51.100.4' })).toBe(false);
157
+ expect(await store.add(chunks.at(-1)!.params, { caller: '203.0.113.9' })).toBe(false);
158
+ });
159
+
160
+ test('a cid that is not a short ASCII token is refused as a bad payload, and writes nothing', async () => {
161
+ const db = database();
162
+ const store = createD1ChunkStore(db.handle());
163
+ const { chunks } = await multiChunk();
164
+ expect(await store.add({ ...chunks[0].params, _cid: '\u00ffescape' })).toBeInstanceOf(Error);
165
+ expect(db.rows()).toBe(0);
166
+ });
167
+
131
168
  test('a payload over its size cap is refused as a bad one, and its rows dropped', async () => {
132
169
  const db = database();
133
170
  const { chunks } = await multiChunk();
@@ -164,6 +201,30 @@ describe('createD1ChunkStore behind mountCtgrTunnel', () => {
164
201
  expect(seen).toEqual([body]);
165
202
  });
166
203
 
204
+ test('🔴 the tunnel names the caller by the edge\'s address, IPv6 by its /64 — a flood from one network leaves another\'s write green', async () => {
205
+ const db = database();
206
+ const seen: unknown[] = [];
207
+ const app = new Hono();
208
+ const { chunks, body } = await multiChunk();
209
+ // The table holds the flood's share plus one real write.
210
+ const share = chunks.length;
211
+ mountCtgrTunnel(app, { store: createD1ChunkStore(db.handle(), { maxRows: share * 2, maxRowsPerCaller: share }) });
212
+ app.post('/api/v1/notes', async (c) => {
213
+ seen.push(await c.req.json());
214
+ return c.json({ saved: true }, 201);
215
+ });
216
+ const statuses: number[] = [];
217
+ for (let n = 0; n < share * 2; n++) {
218
+ // Every address in ONE /64 is one caller.
219
+ const url = chunks[0].url.replace(/_cid=[^&]+/, `_cid=junk-${n}`);
220
+ const res = await app.fetch(new Request(`https://music.test${url}`, { headers: { 'cf-connecting-ip': `2001:0db8:1:2:${(n + 1).toString(16)}::1` } }));
221
+ statuses.push(res.status);
222
+ }
223
+ expect(statuses).toEqual([...Array(share).fill(202), ...Array(share).fill(503)]);
224
+ for (const chunk of chunks) await app.fetch(new Request(`https://music.test${chunk.url}`, { headers: { 'cf-connecting-ip': '2001:db8:1:3::1' } }));
225
+ expect(seen).toEqual([body]);
226
+ });
227
+
167
228
  test('a full table answers 503 CTGR_STORE_UNAVAILABLE, not 202', async () => {
168
229
  const db = database();
169
230
  const app = new Hono();
@@ -27,6 +27,13 @@
27
27
  * here the insert itself refuses once the whole table holds `maxRows`, and the refusal THROWS
28
28
  * (→ 503 "send it again"), because a full table is the store unable to answer, not a bad payload.
29
29
  * A payload over `maxPayloadBytes` is refused as a bad one (→ 400), and its rows dropped.
30
+ *
31
+ * 🔴 ONE caller may hold at most `maxRowsPerCaller` of those rows (forge task 5306). With only the
32
+ * table-wide cap, one stranger sending "chunk 1 of 2" under fresh cids kept the table full and every
33
+ * real GET-only device's bulk write 503'd. Each row's `cid` is stored as `<caller hash>~<cid>`, the
34
+ * caller being the tunnel's `context.caller` (the edge's client address, IPv6 by /64), so a caller's
35
+ * rows are one PRIMARY KEY range to count — no schema change on the eight apps' D1s — and one caller's
36
+ * chunks can never join another's set. A caller over its share is refused like a full table (503).
30
37
  */
31
38
  import { ChunkStore, type ChunkStoreOpts } from 'cursedbelt-core/ctgr/chunk-store';
32
39
  import { parseChunk, type ParsedChunk } from 'cursedbelt-core/ctgr';
@@ -48,12 +55,32 @@ export const CTGR_CHUNKS_DDL: readonly string[] = [
48
55
  export interface D1ChunkStoreOpts extends Pick<ChunkStoreOpts, 'maxPayloadBytes' | 'ttlMs' | 'now'> {
49
56
  /** Rows the whole table may hold before a new chunk is refused (→ 503). Default 4,000 (~10 MB). */
50
57
  maxRows?: number;
58
+ /**
59
+ * Rows ONE caller (the tunnel's `context.caller`) may hold before its next chunk is refused (→ 503).
60
+ * Default 400 — a tenth of the table, and ~700 KB of payload: far past any real bulk write.
61
+ */
62
+ maxRowsPerCaller?: number;
51
63
  }
52
64
 
53
65
  /** 2 MB: about 1,100 chunks — a bulk edit of thousands of ids is a few dozen. */
54
66
  const DEFAULT_MAX_PAYLOAD_BYTES = 2 * 1024 * 1024;
55
67
  const DEFAULT_TTL_MS = 30_000;
56
68
  const DEFAULT_MAX_ROWS = 4_000;
69
+ const DEFAULT_MAX_ROWS_PER_CALLER = 400;
70
+ const CID = /^[A-Za-z0-9-]{1,64}$/;
71
+
72
+ /**
73
+ * The caller's namespace in `cid`: an FNV-1a hash of its address, so the table holds no address. A
74
+ * collision only makes two callers share one share.
75
+ */
76
+ function callerKey(caller: string): string {
77
+ let h = 0x811c9dc5;
78
+ for (let i = 0; i < caller.length; i++) {
79
+ h ^= caller.charCodeAt(i);
80
+ h = Math.imul(h, 0x01000193);
81
+ }
82
+ return (h >>> 0).toString(36).padStart(7, '0');
83
+ }
57
84
 
58
85
  interface CountRow {
59
86
  n: number;
@@ -69,12 +96,13 @@ export function createD1ChunkStore(db: D1LikeDatabase, options: D1ChunkStoreOpts
69
96
  const maxPayloadBytes = options.maxPayloadBytes ?? DEFAULT_MAX_PAYLOAD_BYTES;
70
97
  const ttlMs = options.ttlMs ?? DEFAULT_TTL_MS;
71
98
  const maxRows = options.maxRows ?? DEFAULT_MAX_ROWS;
99
+ const maxRowsPerCaller = options.maxRowsPerCaller ?? DEFAULT_MAX_ROWS_PER_CALLER;
72
100
  const now = options.now ?? Date.now;
73
101
  // The final decode's own caps: the size cap is this store's; its TTL never matters (one call).
74
102
  const decodeOpts: ChunkStoreOpts = { maxPayloadBytes };
75
103
 
76
104
  return {
77
- async add(input) {
105
+ async add(input, context) {
78
106
  const params = input instanceof URLSearchParams ? Object.fromEntries(input) : { ...input };
79
107
  let chunk: ParsedChunk;
80
108
  try {
@@ -85,26 +113,32 @@ export function createD1ChunkStore(db: D1LikeDatabase, options: D1ChunkStoreOpts
85
113
  // One chunk needs no rendezvous — decode it here, in this isolate.
86
114
  if (chunk.total === 1) return new ChunkStore(decodeOpts).add(params);
87
115
  if (chunk.payloadLength > maxPayloadBytes) return new Error('ctgr: payload exceeds size cap');
116
+ // The codec's cid is a UUID. Anything past ASCII would sort outside the caller's counted range.
117
+ if (!CID.test(chunk.cid)) return new Error('ctgr: a chunk id is a short token of letters, digits and dashes');
88
118
 
89
119
  const at = now();
120
+ const owner = callerKey(context?.caller ?? '');
121
+ // A cid is [A-Za-z0-9-], all below `\x7f`, so `<owner>~<cid>` sorts inside [from, to): the caller's rows.
122
+ const cid = `${owner}~${chunk.cid}`;
123
+ const [from, to] = [`${owner}~`, `${owner}\x7f`];
90
124
  const [, , counted] = await db.batch<CountRow>([
91
125
  db.prepare(`DELETE FROM ${CTGR_CHUNKS_TABLE} WHERE at < ?`).bind(at - ttlMs),
92
126
  db
93
127
  .prepare(
94
- `INSERT OR IGNORE INTO ${CTGR_CHUNKS_TABLE} (cid, idx, total, bytes, params, at) SELECT ?, ?, ?, ?, ?, ? WHERE (SELECT COUNT(*) FROM ${CTGR_CHUNKS_TABLE}) < ?`,
128
+ `INSERT OR IGNORE INTO ${CTGR_CHUNKS_TABLE} (cid, idx, total, bytes, params, at) SELECT ?, ?, ?, ?, ?, ? WHERE (SELECT COUNT(*) FROM ${CTGR_CHUNKS_TABLE}) < ? AND (SELECT COUNT(*) FROM ${CTGR_CHUNKS_TABLE} WHERE cid >= ? AND cid < ?) < ?`,
95
129
  )
96
- .bind(chunk.cid, chunk.index, chunk.total, chunk.bytes.length, JSON.stringify(params), at, maxRows),
130
+ .bind(cid, chunk.index, chunk.total, chunk.bytes.length, JSON.stringify(params), at, maxRows, from, to, maxRowsPerCaller),
97
131
  db
98
132
  .prepare(
99
133
  `SELECT COUNT(*) AS n, COALESCE(SUM(bytes), 0) AS b, MAX(idx = ?) AS mine FROM ${CTGR_CHUNKS_TABLE} WHERE cid = ?`,
100
134
  )
101
- .bind(chunk.index, chunk.cid),
135
+ .bind(chunk.index, cid),
102
136
  ]);
103
137
  const row = counted?.results[0];
104
- // Neither inserted now nor held from before: the table is at `maxRows`.
105
- if (!row?.mine) throw new Error(`ctgr: the chunk table is full (${maxRows} rows)`);
138
+ // Neither inserted now nor held from before: the table is at `maxRows`, or this caller at its share.
139
+ if (!row?.mine) throw new Error(`ctgr: the chunk table is full (${maxRows} rows, ${maxRowsPerCaller} a caller)`);
106
140
  if (row.b > maxPayloadBytes) {
107
- await db.prepare(`DELETE FROM ${CTGR_CHUNKS_TABLE} WHERE cid = ?`).bind(chunk.cid).run();
141
+ await db.prepare(`DELETE FROM ${CTGR_CHUNKS_TABLE} WHERE cid = ?`).bind(cid).run();
108
142
  return new Error('ctgr: payload exceeds size cap');
109
143
  }
110
144
  if (row.n < chunk.total) return false;
@@ -112,7 +146,7 @@ export function createD1ChunkStore(db: D1LikeDatabase, options: D1ChunkStoreOpts
112
146
  // Complete: claim the set. Only one request's DELETE can return its rows.
113
147
  const claimed = await db
114
148
  .prepare(`DELETE FROM ${CTGR_CHUNKS_TABLE} WHERE cid = ? RETURNING idx, params`)
115
- .bind(chunk.cid)
149
+ .bind(cid)
116
150
  .all<{ idx: number; params: string }>();
117
151
  if (claimed.results.length < chunk.total) return false;
118
152
 
@@ -35,7 +35,15 @@ import { decodeCtgrTwin } from './ctgrTwin.js';
35
35
  * a THROW means the store itself could not answer (→ 503).
36
36
  */
37
37
  export interface CtgrChunkSink {
38
- add(params: Record<string, string> | URLSearchParams): Promise<CtgrDecoded | false | Error>;
38
+ /**
39
+ * `context.caller` is who sent the chunk (`callerOfTwin` — the edge's client address, an IPv6 one by
40
+ * its /64), so a store shared by every caller can give each its own share (forge task 5306).
41
+ */
42
+ add(
43
+ params: Record<string, string> | URLSearchParams,
44
+ /** `caller`: the edge's client address (`cf-connecting-ip`), an IPv6 one cut to its /64; `''` when none was sent. */
45
+ context?: { caller?: string },
46
+ ): Promise<CtgrDecoded | false | Error>;
39
47
  }
40
48
 
41
49
  export interface CtgrTunnelOptions {
@@ -41,7 +41,7 @@ export async function decodeCtgrTwin(
41
41
 
42
42
  let result: CtgrDecoded | false | Error;
43
43
  try {
44
- result = params._cv === undefined ? legacy.add(params, pathMethod) : await store.add(params);
44
+ result = params._cv === undefined ? legacy.add(params, pathMethod) : await store.add(params, { caller: callerOfTwin(raw) });
45
45
  } catch (error) {
46
46
  console.error(`[ctgr] the chunk store could not answer: ${error instanceof Error ? error.message : String(error)}`);
47
47
  return json({ error: 'ctgr: the chunk store could not answer — send it again', code: 'CTGR_STORE_UNAVAILABLE' }, 503);
@@ -51,6 +51,24 @@ export async function decodeCtgrTwin(
51
51
  return rebuildRequest(raw, twinPath, url, result);
52
52
  }
53
53
 
54
+ /**
55
+ * Who sent this twin, as one network: Cloudflare's `cf-connecting-ip` (the edge sets it and a client
56
+ * cannot), an IPv6 address cut to its /64 — one subscriber holds a whole /64, so a per-address share
57
+ * would be no share at all. `''` when the header is absent (a test, a host with no edge in front).
58
+ */
59
+ export function callerOfTwin(request: Request): string {
60
+ const ip = (request.headers.get('cf-connecting-ip') ?? '').trim().toLowerCase();
61
+ if (!ip.includes(':')) return ip;
62
+ const [head = '', tail = ''] = ip.split('::');
63
+ const left = head ? head.split(':') : [];
64
+ const right = tail ? tail.split(':') : [];
65
+ const groups = ip.includes('::') ? [...left, ...Array(Math.max(0, 8 - left.length - right.length)).fill('0'), ...right] : left;
66
+ return `${groups
67
+ .slice(0, 4)
68
+ .map((g) => g.replace(/^0+(?=.)/, ''))
69
+ .join(':')}::/64`;
70
+ }
71
+
54
72
  /**
55
73
  * Did a browser say this twin came from somewhere else? `Sec-Fetch-Site` is set by the browser
56
74
  * and no page can forge it: only `same-origin` is the app's own `installCtgrFetch`. `none` (a
@@ -0,0 +1,185 @@
1
+ /**
2
+ * `cursedbelt-server/presence` — 🔴 an app nobody is using costs (close to) nothing (forge task 5325).
3
+ *
4
+ * The owner, 2026-11-16: *"if no one uses apps like photos, roms, flix, vault, desk, etc all day I don't
5
+ * want thousands of requests […] back and forth with no benefit."* Measured that day: the
6
+ * fleet's Worker crons fired ~6,500 times and spent ~172k CPU-ms — about a sixth of the account's Workers
7
+ * CPU, which the month was already past — and nearly all of it ran with nobody there. A five-minute cron
8
+ * is a promise to someone looking at the page; at 4 a.m. it is a promise to no one.
9
+ *
10
+ * So scheduled work keys on PRESENCE, not the clock (night is just the common case of idle):
11
+ *
12
+ * - **{@link createUseTick}** — work that used to run every few minutes runs on USE instead: a signed-in
13
+ * request kicks it under `waitUntil` when it is due, at most once per `everyMs` across every isolate
14
+ * ({@link claimTick} in D1). The Worker's own cron drops to the lowest cadence that is still correct
15
+ * with nobody there (an hourly backstop for queued work, the day's purge), and a stage tier keeps no
16
+ * cron at all: its tests in flight are the use that ticks it.
17
+ * - **{@link notePresence} / {@link lastPresence}** — for a Worker with no sign-in of its own (the media
18
+ * edge): it notes "a reader of <name> was here", throttled per isolate, and its cron asks before it
19
+ * spends anything.
20
+ * - **{@link lastHumanUse}** — for an app behind cursedauth's door: `sessions.last_seen_at` is ALREADY
21
+ * the signal. The door moves it on every signed-in request (`userIdOf`, throttled to a minute), so
22
+ * `MAX(last_seen_at)` is the tier's last human use, with no write of ours at all.
23
+ *
24
+ * Everything is created on first use (`presence_marks`, like `events_days` and the engagement tables),
25
+ * so no app's schema has to learn it. A failed claim runs nothing and warns: a lost tick is the next
26
+ * request's or the backstop cron's, never a double.
27
+ *
28
+ * `tools/check-idle-cost.ts` in the generation holds the other half: a sub-hourly cron or a stage cron
29
+ * that does not go through here is red.
30
+ *
31
+ * 🔴 Worker-safe: nothing here imports `bun:*`.
32
+ */
33
+ import type { D1LikeDatabase } from "../d1/types.js";
34
+
35
+ /** One row per name: a presence mark (`reader:<tenant>`) or a tick's last run (`tick:<name>`). */
36
+ export const PRESENCE_DDL = ["CREATE TABLE IF NOT EXISTS presence_marks (name TEXT PRIMARY KEY, at INTEGER NOT NULL)"];
37
+
38
+ /** How often one isolate writes the same presence mark. Presence is an hours-scale question. */
39
+ export const PRESENCE_THROTTLE_MS = 5 * 60_000;
40
+
41
+ /** The default "nobody is here" line: no use for this long and scheduled work stands down. */
42
+ export const IDLE_AFTER_MS = 3 * 60 * 60_000;
43
+
44
+ const TICK_PREFIX = "tick:";
45
+
46
+ /** An upsert that only moves `at` when the row is older than `?3` — the claim and the throttled mark both. */
47
+ const UPSERT_IF_OLDER =
48
+ "INSERT INTO presence_marks (name, at) VALUES (?1, ?2) ON CONFLICT(name) DO UPDATE SET at = excluded.at WHERE presence_marks.at <= ?3";
49
+
50
+ const isMissingTable = (error: unknown): boolean => /no such table/i.test(String(error));
51
+
52
+ async function upsertIfOlder(db: D1LikeDatabase, name: string, at: number, olderThan: number): Promise<boolean> {
53
+ const run = () => db.prepare(UPSERT_IF_OLDER).bind(name, at, olderThan).run();
54
+ const result = await run().catch(async (error: unknown) => {
55
+ if (!isMissingTable(error)) throw error;
56
+ await db.batch(PRESENCE_DDL.map((ddl) => db.prepare(ddl)));
57
+ return run();
58
+ });
59
+ return (result.meta?.changes ?? 0) > 0;
60
+ }
61
+
62
+ /** What this isolate last wrote or attempted, per name — so a busy Worker asks D1 once per throttle. */
63
+ const noted = new Map<string, number>();
64
+
65
+ /**
66
+ * Note that someone used `name` now. At most one D1 write per isolate per `throttleMs`, and the row only
67
+ * moves when it is older than that, so many isolates add up to a handful of writes an hour while anyone is
68
+ * there and none while no one is. Resolves `true` when it wrote; never throws (presence is advisory).
69
+ */
70
+ export async function notePresence(
71
+ db: D1LikeDatabase,
72
+ name: string,
73
+ options: { now?: () => number; throttleMs?: number } = {},
74
+ ): Promise<boolean> {
75
+ const now = (options.now ?? Date.now)();
76
+ const throttle = options.throttleMs ?? PRESENCE_THROTTLE_MS;
77
+ const last = noted.get(name);
78
+ if (last !== undefined && now - last < throttle) return false;
79
+ noted.set(name, now);
80
+ try {
81
+ return await upsertIfOlder(db, name, now, now - throttle);
82
+ } catch (error) {
83
+ console.warn(`[presence] ${name} was not noted: ${String(error)}`);
84
+ return false;
85
+ }
86
+ }
87
+
88
+ /** When `name` was last noted (epoch ms), or null — never noted, or no table yet. Throws on any other error. */
89
+ export async function lastPresence(db: D1LikeDatabase, name: string): Promise<number | null> {
90
+ try {
91
+ const row = await db.prepare("SELECT at FROM presence_marks WHERE name = ?").bind(name).first<{ at: number }>();
92
+ return typeof row?.at === "number" ? row.at : null;
93
+ } catch (error) {
94
+ if (isMissingTable(error)) return null;
95
+ throw error;
96
+ }
97
+ }
98
+
99
+ /**
100
+ * The tier's last human use behind cursedauth's door: `MAX(sessions.last_seen_at)`, which the door's
101
+ * `userIdOf` moves on every signed-in request. Null when nobody has a session, or the app has no
102
+ * `sessions` table. A row read per live session — a household's handful.
103
+ */
104
+ export async function lastHumanUse(db: D1LikeDatabase): Promise<number | null> {
105
+ try {
106
+ const row = await db.prepare("SELECT MAX(last_seen_at) AS at FROM sessions").first<{ at: number | null }>();
107
+ return typeof row?.at === "number" && row.at > 0 ? row.at : null;
108
+ } catch (error) {
109
+ if (isMissingTable(error)) return null;
110
+ throw error;
111
+ }
112
+ }
113
+
114
+ /** Whether a last use at `lastAt` still counts as someone being here. Null (never) is idle. Pure. */
115
+ export function isPresent(lastAt: number | null, now: number = Date.now(), idleAfterMs: number = IDLE_AFTER_MS): boolean {
116
+ return lastAt !== null && now - lastAt < idleAfterMs;
117
+ }
118
+
119
+ /**
120
+ * Claim tick `name` if its last run is at least `everyMs` old — one D1 statement, atomic, so of every
121
+ * isolate and cron that asks inside the window exactly one wins. `everyMs: 0` always wins: what a cron
122
+ * calls to record that it ran, so the next request does not run the same work again a minute later.
123
+ */
124
+ export async function claimTick(db: D1LikeDatabase, name: string, everyMs: number, now: number = Date.now()): Promise<boolean> {
125
+ return upsertIfOlder(db, TICK_PREFIX + name, now, now - everyMs);
126
+ }
127
+
128
+ /** When tick `name` last ran (epoch ms), or null. */
129
+ export const lastTick = (db: D1LikeDatabase, name: string): Promise<number | null> => lastPresence(db, TICK_PREFIX + name);
130
+
131
+ export interface UseTickKick {
132
+ db: D1LikeDatabase;
133
+ /** The work — the same function the cron runs. Its errors are logged, never thrown at the request. */
134
+ run: () => Promise<unknown>;
135
+ /** The request's `ctx.waitUntil`: the tick never holds the answer. */
136
+ waitUntil: (promise: Promise<unknown>) => void;
137
+ now?: () => number;
138
+ }
139
+
140
+ export interface UseTick {
141
+ /** Start the tick behind this request if it is due. True when it was started (and won its claim or is asking). */
142
+ kick(input: UseTickKick): boolean;
143
+ }
144
+
145
+ /**
146
+ * Work that runs because someone is USING the app (see the header): `kick` on a signed-in request.
147
+ * The isolate remembers its last attempt, so a page's burst of requests costs one claim, and the claim
148
+ * in D1 keeps every isolate together to one run per `everyMs`.
149
+ */
150
+ export function createUseTick(options: { name: string; everyMs: number }): UseTick {
151
+ let attempted = Number.NEGATIVE_INFINITY;
152
+ return {
153
+ kick({ db, run, waitUntil, now = Date.now }) {
154
+ const at = now();
155
+ if (at - attempted < options.everyMs) return false;
156
+ attempted = at;
157
+ waitUntil(
158
+ claimTick(db, options.name, options.everyMs, at)
159
+ .then((won) => (won ? run() : undefined))
160
+ .catch((error: unknown) => console.warn(`[presence] the ${options.name} tick failed: ${String(error)}`)),
161
+ );
162
+ return true;
163
+ },
164
+ };
165
+ }
166
+
167
+ /**
168
+ * Whether a request is a person using the app — it carries the app's own session cookie. A stale cookie
169
+ * counts too: the price of a false yes is one tick, while a probe, a crawler, the Mac's bearer-token
170
+ * pipeline and `/healthz` carry no cookie and never tick anything.
171
+ */
172
+ export function carriesSession(request: Request, cookieName: string): boolean {
173
+ const cookie = request.headers.get("cookie");
174
+ if (!cookie) return false;
175
+ return cookie.split(";").some((part) => {
176
+ const name = part.trim().split("=", 1)[0];
177
+ // cursedauth's account slots: `<base>` is slot 0, `<base>__<n>` the others (`slotCookieName`).
178
+ return name === cookieName || name.startsWith(`${cookieName}__`);
179
+ });
180
+ }
181
+
182
+ /** Test seam: forget what this isolate noted. */
183
+ export function resetPresenceMemo(): void {
184
+ noted.clear();
185
+ }
@@ -0,0 +1,160 @@
1
+ import { Database } from "bun:sqlite";
2
+ import { afterEach, describe, expect, test } from "bun:test";
3
+ import { createLocalD1 } from "../d1/local.js";
4
+ import type { D1LikeDatabase } from "../d1/types.js";
5
+ import {
6
+ carriesSession,
7
+ claimTick,
8
+ createUseTick,
9
+ IDLE_AFTER_MS,
10
+ isPresent,
11
+ lastHumanUse,
12
+ lastPresence,
13
+ lastTick,
14
+ notePresence,
15
+ PRESENCE_THROTTLE_MS,
16
+ resetPresenceMemo,
17
+ } from "./index.js";
18
+
19
+ const T0 = Date.UTC(2026, 10, 17, 4, 0);
20
+ const MIN = 60_000;
21
+ const fresh = (): D1LikeDatabase => createLocalD1(new Database(":memory:"));
22
+
23
+ afterEach(() => resetPresenceMemo());
24
+
25
+ describe("notePresence / lastPresence — a throttled mark, created on first use", () => {
26
+ test("no table yet reads as never; the first note creates it", async () => {
27
+ const db = fresh();
28
+ expect(await lastPresence(db, "reader:photos")).toBeNull();
29
+ expect(await notePresence(db, "reader:photos", { now: () => T0 })).toBe(true);
30
+ expect(await lastPresence(db, "reader:photos")).toBe(T0);
31
+ });
32
+
33
+ test("one isolate writes a name at most once per throttle; another isolate inside it moves nothing", async () => {
34
+ const db = fresh();
35
+ expect(await notePresence(db, "reader:photos", { now: () => T0 })).toBe(true);
36
+ expect(await notePresence(db, "reader:photos", { now: () => T0 + MIN })).toBe(false);
37
+ resetPresenceMemo(); // another isolate, same database
38
+ expect(await notePresence(db, "reader:photos", { now: () => T0 + MIN })).toBe(false);
39
+ expect(await lastPresence(db, "reader:photos")).toBe(T0);
40
+ resetPresenceMemo();
41
+ expect(await notePresence(db, "reader:photos", { now: () => T0 + PRESENCE_THROTTLE_MS })).toBe(true);
42
+ expect(await lastPresence(db, "reader:photos")).toBe(T0 + PRESENCE_THROTTLE_MS);
43
+ });
44
+
45
+ test("a database that refuses is a warning and false, never a throw at the request", async () => {
46
+ const broken = {
47
+ prepare: () => ({ bind: () => ({ run: () => Promise.reject(new Error("D1_ERROR: overloaded")) }) }),
48
+ } as unknown as D1LikeDatabase;
49
+ expect(await notePresence(broken, "reader:photos", { now: () => T0 })).toBe(false);
50
+ });
51
+
52
+ test("lastPresence still throws on an error that is not a missing table", async () => {
53
+ const broken = {
54
+ prepare: () => ({ bind: () => ({ first: () => Promise.reject(new Error("D1_ERROR: overloaded")) }) }),
55
+ } as unknown as D1LikeDatabase;
56
+ await expect(lastPresence(broken, "reader:photos")).rejects.toThrow("overloaded");
57
+ });
58
+ });
59
+
60
+ describe("lastHumanUse — cursedauth's sessions.last_seen_at is the signal", () => {
61
+ test("no sessions table is null; an empty one is null; otherwise the newest last_seen_at", async () => {
62
+ const db = fresh();
63
+ expect(await lastHumanUse(db)).toBeNull();
64
+ await db.prepare("CREATE TABLE sessions (id TEXT PRIMARY KEY, last_seen_at INTEGER NOT NULL DEFAULT 0)").run();
65
+ expect(await lastHumanUse(db)).toBeNull();
66
+ await db.prepare("INSERT INTO sessions (id, last_seen_at) VALUES ('a', ?), ('b', ?), ('c', 0)").bind(T0 - 5 * MIN, T0).run();
67
+ expect(await lastHumanUse(db)).toBe(T0);
68
+ });
69
+
70
+ test("isPresent: never is idle; inside the line is present; at it is idle", () => {
71
+ expect(isPresent(null, T0)).toBe(false);
72
+ expect(isPresent(T0 - IDLE_AFTER_MS + 1, T0)).toBe(true);
73
+ expect(isPresent(T0 - IDLE_AFTER_MS, T0)).toBe(false);
74
+ });
75
+ });
76
+
77
+ describe("claimTick — one winner per window across every isolate", () => {
78
+ test("first claim wins, a second inside the window loses, the next window wins", async () => {
79
+ const db = fresh();
80
+ expect(await claimTick(db, "cron", 5 * MIN, T0)).toBe(true);
81
+ expect(await claimTick(db, "cron", 5 * MIN, T0 + 4 * MIN)).toBe(false);
82
+ expect(await claimTick(db, "cron", 5 * MIN, T0 + 5 * MIN)).toBe(true);
83
+ expect(await lastTick(db, "cron")).toBe(T0 + 5 * MIN);
84
+ });
85
+
86
+ test("everyMs 0 always wins — the cron's own record that it ran", async () => {
87
+ const db = fresh();
88
+ expect(await claimTick(db, "cron", 5 * MIN, T0)).toBe(true);
89
+ expect(await claimTick(db, "cron", 0, T0 + MIN)).toBe(true);
90
+ expect(await claimTick(db, "cron", 5 * MIN, T0 + 3 * MIN)).toBe(false);
91
+ });
92
+ });
93
+
94
+ describe("createUseTick — work on use, not on the clock", () => {
95
+ const kicker = (db: D1LikeDatabase, runs: number[], pending: Promise<unknown>[]) => (tick: ReturnType<typeof createUseTick>, at: number) =>
96
+ tick.kick({ db, now: () => at, waitUntil: (p) => pending.push(p), run: async () => runs.push(at) });
97
+
98
+ test("a burst of requests runs the work once; the next window runs it again", async () => {
99
+ const db = fresh();
100
+ const runs: number[] = [];
101
+ const pending: Promise<unknown>[] = [];
102
+ const tick = createUseTick({ name: "cron", everyMs: 5 * MIN });
103
+ const kick = kicker(db, runs, pending);
104
+ expect(kick(tick, T0)).toBe(true);
105
+ expect(kick(tick, T0 + 1000)).toBe(false); // the isolate's memory: no D1 at all
106
+ await Promise.all(pending);
107
+ expect(kick(tick, T0 + 5 * MIN)).toBe(true);
108
+ await Promise.all(pending);
109
+ expect(runs).toEqual([T0, T0 + 5 * MIN]);
110
+ });
111
+
112
+ test("two isolates inside one window: one runs, the other's claim loses", async () => {
113
+ const db = fresh();
114
+ const runs: number[] = [];
115
+ const pending: Promise<unknown>[] = [];
116
+ const kick = kicker(db, runs, pending);
117
+ kick(createUseTick({ name: "cron", everyMs: 5 * MIN }), T0);
118
+ await Promise.all(pending);
119
+ kick(createUseTick({ name: "cron", everyMs: 5 * MIN }), T0 + MIN);
120
+ await Promise.all(pending);
121
+ expect(runs).toEqual([T0]);
122
+ });
123
+
124
+ test("a cron that just ran (claimTick everyMs 0) holds the next request off", async () => {
125
+ const db = fresh();
126
+ const runs: number[] = [];
127
+ const pending: Promise<unknown>[] = [];
128
+ await claimTick(db, "cron", 0, T0);
129
+ kicker(db, runs, pending)(createUseTick({ name: "cron", everyMs: 5 * MIN }), T0 + MIN);
130
+ await Promise.all(pending);
131
+ expect(runs).toEqual([]);
132
+ });
133
+
134
+ test("work that throws is logged under waitUntil, never thrown at the request", async () => {
135
+ const db = fresh();
136
+ const pending: Promise<unknown>[] = [];
137
+ const tick = createUseTick({ name: "cron", everyMs: 5 * MIN });
138
+ const started = tick.kick({
139
+ db,
140
+ now: () => T0,
141
+ waitUntil: (p) => pending.push(p),
142
+ run: () => Promise.reject(new Error("queue down")),
143
+ });
144
+ expect(started).toBe(true);
145
+ await expect(Promise.all(pending)).resolves.toBeDefined();
146
+ });
147
+ });
148
+
149
+ describe("carriesSession — a person, not a probe", () => {
150
+ const req = (cookie?: string) => new Request("https://photos.example/api/albums", cookie ? { headers: { cookie } } : {});
151
+ test("the app's cookie, and its account-slot cookies, count", () => {
152
+ expect(carriesSession(req("photos_session=abc"), "photos_session")).toBe(true);
153
+ expect(carriesSession(req("theme=dark; photos_session__2=abc"), "photos_session")).toBe(true);
154
+ });
155
+ test("no cookie, another app's cookie, or a name that only starts the same do not", () => {
156
+ expect(carriesSession(req(), "photos_session")).toBe(false);
157
+ expect(carriesSession(req("family_session=abc"), "photos_session")).toBe(false);
158
+ expect(carriesSession(req("photos_sessionx=abc"), "photos_session")).toBe(false);
159
+ });
160
+ });