/** JSON in, JSON out, and the one refusal shape every route answers with. */exportclassRefusedextendsError {readonly status: number;readonly code: string; constructor(status: number, code: string, message: string) {super(message);this.status = status;this.code = code; }}exportfunction refuse(status: number, code: string, message: string): never {thrownewRefused(status, code, message);}exportfunction json(value: unknown, status = 200, headers: Record<string, string> = {}): Response {returnnewResponse(JSON.stringify(value), { status, headers: { "content-type": "application/json; charset=utf-8", "cache-control": "no-store", ...headers }, });}exportfunction answerRefusal(error: unknown): Response {if (error instanceofRefused) return json({ code: error.code, message: error.message }, error.status);const message = error instanceofError ? `${error.name}: ${error.message}` : String(error); console.error("cottondb: unexpected", message, error instanceofError ? error.stack : "");// The front Worker logs this and takes it off (`toldFault` below): an object's own log lands on the object's// tail event, and a tail of the Worker showed a bare 500 with no word of what threw (the Mac's mail, 23 Nov 2026).return json({ code: "internal_error", message: "the business did not answer" }, 500, { [FAULT_HEADER]: faultLine(error) });}/** The header an object's 500 carries to the front Worker, which logs it and never passes it on. */exportconst FAULT_HEADER = "x-cotton-fault";/** What threw, on one line a header can carry: the name, the message and the first frames, no more than 600 characters. */exportfunction faultLine(error: unknown): string {const head = error instanceofError ? `${error.name}: ${error.message}` : String(error);const frames = error instanceofError && error.stack ? error.stack.split("\n").slice(1, 4).map((f) => f.trim()).join(" ← ") : "";return`${head}${frames ? ` | ${frames}` : ""}`.replace(/[^\x20-\x7e]/g, "?").slice(0, 600);}/** * A sign-in call's body is small: a number, a code, ids (AUDIT A M3, AUDIT A2). The object door caps it * (index.ts `boundedBody`); the open door caps the same unauthenticated routes by passing this to `readJson`. */exportconst SIGN_IN_BODY_MAX = 16 * 1024;/** * The body as text, refused `413 too_large` past `max`: by the stated content-length first (so an outsized body is * turned away before a byte is read), and again while reading, since content-length can lie or be absent. */asyncfunction boundedText(request: Request, max: number): Promise<string> {const said = Number(request.headers.get("content-length") ?? "0");if (Number.isFinite(said) && said > max) refuse(413, "too_large", `the body is at most ${max} bytes`);if (!request.body) return"";const reader = request.body.getReader();const parts: Uint8Array[] = [];let size = 0;for (;;) {const { done, value } = await reader.read();if (done) break; size += value.byteLength;if (size > max) {await reader.cancel().catch(() => undefined); refuse(413, "too_large", `the body is at most ${max} bytes`); } parts.push(value); }const out = newUint8Array(size);let at = 0;for (const part of parts) { out.set(part, at); at += part.byteLength; }returnnewTextDecoder().decode(out);}/** * Read the body as a JSON object. With `maxBytes`, a body past it is refused `413 too_large` by its stated length and * again while reading, so a stranger cannot make an unauthenticated door read an arbitrarily large body (AUDIT A2). */exportasyncfunction readJson<T = Record<string, unknown>>(request: Request, maxBytes?: number): Promise<T> {let text: string;try { text = maxBytes === undefined ? await request.text() : await boundedText(request, maxBytes); } catch (error) {if (error instanceofRefused) throw error; refuse(400, "bad_request", "the body could not be read"); }if (!text.trim()) return {} as T;try {const parsed: unknown = JSON.parse(text);if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) refuse(400, "bad_request", "the body is not a JSON object");return parsed as T; } catch (error) {if (error instanceofRefused) throw error; refuse(400, "bad_request", "the body is not JSON"); }}exportfunction text(value: unknown, what: string): string {if (typeof value !== "string" || !value.trim()) refuse(400, "bad_request", `${what} is required`);return value.trim();}exportfunction optionalText(value: unknown): string | null {returntypeof value === "string" && value.trim() ? value.trim() : null;}exportfunction integer(value: unknown, what: string, fallback?: number): number {if (value === undefined || value === null) {if (fallback !== undefined) return fallback; refuse(400, "bad_request", `${what} is required`); }const n = typeof value === "number" ? value : Number(value);if (!Number.isInteger(n)) refuse(400, "bad_request", `${what} must be a whole number`);return n;}exportfunction object(value: unknown, what: string): Record<string, unknown> {if (value === null || typeof value !== "object" || Array.isArray(value)) refuse(400, "bad_request", `${what} must be an object`);return value asRecord<string, unknown>;}exportfunction bearer(request: Request): string | null {const header = request.headers.get("authorization") ?? "";const match = /^Bearer\s+(\S+)$/i.exec(header);return match ? match[1]! : null;}exportasyncfunction sha256Hex(input: string): Promise<string> {const digest = await crypto.subtle.digest("SHA-256", newTextEncoder().encode(input));return [...newUint8Array(digest)].map((b) => b.toString(16).padStart(2, "0")).join("");}exportfunction randomToken(bytes = 32): string {const buf = newUint8Array(bytes); crypto.getRandomValues(buf);let s = "";for (const b of buf) s += String.fromCharCode(b);return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");}/** An object's 500 names what threw in a header: logged by the front Worker (index.ts, and the open door in open.ts), on its own tail event, and taken off the answer. *//** * SLOW READ (coordinator, 26 Nov 2026: live answered a plain list_projects in 9.7 s once, usually 2 to 3 s). The object * cannot time its own synchronous work on Workers (the clock moves only across I/O), so the front Worker times the * forward, which crosses I/O, and says any answer slower than SLOW_ANSWER_MS with what the object told about itself: * a cold instance (its first answer since it started), an alarm under way when the request arrived (and since how many * seconds), and the bounded jobs the last alarm still had to do. Paths only, never a query, a body or a token. */exportconst SLOW_ANSWER_MS = 2000;exportconst COLD_HEADER = "cotton-object-cold";exportconst ALARM_RUNNING_HEADER = "cotton-alarm-running";exportconst ALARM_BUSY_HEADER = "cotton-alarm-busy";/** The line for an answer slower than SLOW_ANSWER_MS, or null. *//** LIVE SLOW 2: when the object began this request (its clock), and what it did just before (its route family or "alarm"). */exportconst BEGAN_HEADER = "cotton-object-began";exportconst BEFORE_HEADER = "cotton-object-before";/** Set by the front Worker on every forwarded answer: the whole time it waited, and of that how long the request waited for the object to begin it. */exportconst TOTAL_HEADER = "cotton-total-ms";exportconst QUEUED_HEADER = "cotton-queued-ms";exportfunction slowLine(method: string, path: string, ms: number, answer: Response, queued: number | null = null): string | null {if (ms < SLOW_ANSWER_MS) returnnull;const cold = answer.headers.get(COLD_HEADER) === "1";const alarm = answer.headers.get(ALARM_RUNNING_HEADER);const busy = answer.headers.get(ALARM_BUSY_HEADER);const before = answer.headers.get(BEFORE_HEADER);return`cottondb: slow answer ${ms} ms ${method} ${path} ${answer.status}: cold ${cold ? "yes" : "no"}; alarm ${alarm === null ? "not running" : `running ${alarm} s`}; alarm busy ${busy || "none"}; queued ${queued === null ? "unknown" : `${queued} ms`}; before ${before || "nothing"}`;}/** LIVE SLOW 3: the request header that asks for the split on the way out, carrying the admin token (busy-look). */exportconst TIMING_ASK_HEADER = "cotton-timing";/** * Say a slow forward (above), then the fault as `toldFault` does. The object's own timing (`cotton-object-began`, * `cotton-object-before`) is read here for the slow-answer line and never leaves this Worker (LIVE SLOW 3: anyone * holding a slug could otherwise watch when its person's phone is busy). Only a caller that sends the admin token in * `cotton-timing` (busy-look) gets the split back: `cotton-total-ms`, the whole wait here; `cotton-queued-ms`, how much * of it passed before the object began the request; and `cotton-object-before`. */exportfunction toldSlow(request: Request, path: string, started: number, answer: Response, env: { ADMIN_TOKEN?: string } = {}): Response {const total = Date.now() - started;const began = Number(answer.headers.get(BEGAN_HEADER));const queued = Number.isFinite(began) && began > 0 ? Math.max(0, began - started) : null;const before = answer.headers.get(BEFORE_HEADER);const line = slowLine(request.method, path, total, answer, queued);if (line) console.log(line);const told = toldFault(request, path, answer);// A socket's answer goes as it is (the object sets no timing on one).if ((told as unknown as { webSocket?: unknown }).webSocket) return told;const headers = newHeaders(told.headers); headers.delete(BEGAN_HEADER); headers.delete(BEFORE_HEADER);if (isAdminToken(env, request.headers.get(TIMING_ASK_HEADER))) { headers.set(TOTAL_HEADER, String(total));if (queued !== null) headers.set(QUEUED_HEADER, String(queued));if (before) headers.set(BEFORE_HEADER, before); }returnnewResponse(told.body, { status: told.status, statusText: told.statusText, headers });}exportfunction toldFault(request: Request, path: string, answer: Response): Response {const fault = answer.headers.get(FAULT_HEADER);if (fault === null) return answer; console.error(`cottondb: ${answer.status} ${request.method} ${path}: ${fault}`);const headers = newHeaders(answer.headers); headers.delete(FAULT_HEADER);// A WebSocket upgrade carries its socket on the answer (a Workers field the DOM's Response type does not name).const socket = (answer as unknown as { webSocket?: unknown }).webSocket;returnnewResponse(answer.body, { status: answer.status, statusText: answer.statusText, headers, ...(socket ? { webSocket: socket } : {}) } asResponseInit);}/** * Whether `token` is this Worker's admin token, compared in constant time (ROUTES-AUDIT 17, 23 Nov 2026): every * character is looked at whatever the first difference, and a wrong length costs the same walk. No admin token set * matches nothing. */exportfunction isAdminToken(env: { ADMIN_TOKEN?: string }, token: string | null | undefined): boolean {const want = env.ADMIN_TOKEN;if (!want || typeof token !== "string") returnfalse;let diff = token.length ^ want.length;for (let i = 0; i < want.length; i++) diff |= want.charCodeAt(i) ^ (i < token.length ? token.charCodeAt(i) : 0);return diff === 0;}