/** JSON in, JSON out, and the one refusal shape every route answers with. */ export class Refused extends Error { readonly status: number; readonly code: string; constructor(status: number, code: string, message: string) { super(message); this.status = status; this.code = code; } } export function refuse(status: number, code: string, message: string): never { throw new Refused(status, code, message); } export function json(value: unknown, status = 200, headers: Record = {}): Response { return new Response(JSON.stringify(value), { status, headers: { "content-type": "application/json; charset=utf-8", "cache-control": "no-store", ...headers }, }); } export function answerRefusal(error: unknown): Response { if (error instanceof Refused) return json({ code: error.code, message: error.message }, error.status); const message = error instanceof Error ? `${error.name}: ${error.message}` : String(error); console.error("cottondb: unexpected", message, error instanceof Error ? 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. */ export const 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. */ export function faultLine(error: unknown): string { const head = error instanceof Error ? `${error.name}: ${error.message}` : String(error); const frames = error instanceof Error && 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`. */ export const 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. */ async function boundedText(request: Request, max: number): Promise { 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 = new Uint8Array(size); let at = 0; for (const part of parts) { out.set(part, at); at += part.byteLength; } return new TextDecoder().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). */ export async function readJson>(request: Request, maxBytes?: number): Promise { let text: string; try { text = maxBytes === undefined ? await request.text() : await boundedText(request, maxBytes); } catch (error) { if (error instanceof Refused) 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 instanceof Refused) throw error; refuse(400, "bad_request", "the body is not JSON"); } } export function text(value: unknown, what: string): string { if (typeof value !== "string" || !value.trim()) refuse(400, "bad_request", `${what} is required`); return value.trim(); } export function optionalText(value: unknown): string | null { return typeof value === "string" && value.trim() ? value.trim() : null; } export function 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; } export function object(value: unknown, what: string): Record { if (value === null || typeof value !== "object" || Array.isArray(value)) refuse(400, "bad_request", `${what} must be an object`); return value as Record; } export function bearer(request: Request): string | null { const header = request.headers.get("authorization") ?? ""; const match = /^Bearer\s+(\S+)$/i.exec(header); return match ? match[1]! : null; } export async function sha256Hex(input: string): Promise { const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(input)); return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, "0")).join(""); } export function randomToken(bytes = 32): string { const buf = new Uint8Array(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. */ export const SLOW_ANSWER_MS = 2000; export const COLD_HEADER = "cotton-object-cold"; export const ALARM_RUNNING_HEADER = "cotton-alarm-running"; export const 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"). */ export const BEGAN_HEADER = "cotton-object-began"; export const 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. */ export const TOTAL_HEADER = "cotton-total-ms"; export const QUEUED_HEADER = "cotton-queued-ms"; export function slowLine(method: string, path: string, ms: number, answer: Response, queued: number | null = null): string | null { if (ms < SLOW_ANSWER_MS) return null; 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). */ export const 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`. */ export function 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 = new Headers(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); } return new Response(told.body, { status: told.status, statusText: told.statusText, headers }); } export function 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 = new Headers(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; return new Response(answer.body, { status: answer.status, statusText: answer.statusText, headers, ...(socket ? { webSocket: socket } : {}) } as ResponseInit); } /** * 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. */ export function isAdminToken(env: { ADMIN_TOKEN?: string }, token: string | null | undefined): boolean { const want = env.ADMIN_TOKEN; if (!want || typeof token !== "string") return false; 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; }