Cotton code
255 lines · 14.1 KB · TypeScriptRaw
/** * The business Worker: names the business from the request, serves its photos * from R2, and hands everything else to the business's object. * * WHICH BUSINESS. The hostname's first label (sharmila.<domain> → "sharmila"), * or in development the path prefix `/b/<slug>`. A workers.dev or localhost hostname names no business, * so the prefix is the only way there. Two businesses need no registry; when * there are twenty, a KV map of hostname to slug goes here and nothing else moves. * * THE OPEN HOST (OPEN_HOST, cottondb.com) names no object: a person's sign-in * and bearer do, through the directory (src/open.ts). */import * as accountDelete from "./account_delete.ts";import { Business, SLUG_HEADER, STREAM_PATH } from "./business.ts";import { CallRoom } from "./calling/room.ts";import { Directory, directory } from "./directory.ts";import type { Env } from "./env.ts";import { answerRefusal, bearer, isAdminToken, json, SIGN_IN_BODY_MAX, TIMING_ASK_HEADER, toldFault, toldSlow } from "./http.ts";import { slugBound, streamAtDoor } from "./media.ts";import { sendingEvents, type SendingEvent } from "./mail/events.ts";import { receive } from "./mail/receive.ts";import { PREFIX_HEADER } from "./oauth.ts";import { consume, JOB_QUEUES } from "./jobs/run.ts";import { JOB_SCHEME } from "./jobs/token.ts";import { inward, openDoor } from "./open.ts";import { normalizePhone } from "./protocol.ts";import { Published } from "./published.ts";import { watchAlarms } from "./alarm_watch.ts";import { Space } from "./space/space.ts";export { Business, CallRoom, Directory, Published, Space };const SLUG = /^[a-z][a-z0-9-]{1,40}$/;const UNNAMED_HOSTS = /(^|\.)(workers\.dev|localhost|127\.0\.0\.1)$/;/** A path a `/b/<slug>` prefix names, directly or behind a well-known segment. */const PREFIXED = /^\/(\.well-known\/[a-z-]+\/)?b\//;/** * The business a request names, the path inside it, and the path prefix that * named it ("" when the host named it), or null. An OAuth client puts a well-known * segment BEFORE the resource's own path (RFC 8414, RFC 9728), so * `/.well-known/<document>/b/<slug>/…` names the business too. */export function resolve(url: URL): { slug: string; path: string; prefix: string } | null {  const known = /^\/\.well-known\/([a-z-]+)\/b\/([^/]+)(\/.*)?$/.exec(url.pathname);  if (known) {    const slug = known[2]!;    return SLUG.test(slug) ? { slug, path: `/.well-known/${known[1]}${known[3] ?? ""}`, prefix: `/b/${slug}` } : null;  }  const prefixed = /^\/b\/([^/]+)(\/.*)?$/.exec(url.pathname);  if (prefixed) {    const slug = prefixed[1]!;    return SLUG.test(slug) ? { slug, path: prefixed[2] || "/", prefix: `/b/${slug}` } : null;  }  const host = url.hostname.toLowerCase();  if (UNNAMED_HOSTS.test(host) || !host.includes(".")) return null;  const slug = host.split(".")[0]!;  return SLUG.test(slug) ? { slug, path: url.pathname, prefix: "" } : null;}/** The body, or null past `max` bytes (refused by its length before reading, and stopped while reading). */export async function boundedBody(request: Request, max: number): Promise<ArrayBuffer | null> {  const said = Number(request.headers.get("content-length") ?? "0");  if (Number.isFinite(said) && said > max) return null;  if (!request.body) return new ArrayBuffer(0);  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);      return null;    }    parts.push(value);  }  const out = new Uint8Array(size);  let at = 0;  for (const p of parts) {    out.set(p, at);    at += p.byteLength;  }  return out.buffer;}/** * Whether a sign-in call's body could send or check a code (AUDIT A H3): a well-formed number and device for a code, a * challenge, code and device for a sign-in, the connect page's phone or code step. Anything else is refused by the * object without reaching Twilio, so it is not counted against anyone's hour. */export function reachesTwilio(path: string, body: ArrayBuffer): boolean {  const text = new TextDecoder().decode(body);  const filled = (v: unknown) => typeof v === "string" && v.trim() !== "";  if (/^\/oauth\/authorize\/?$/.test(path)) {    const form = new URLSearchParams(text);    if (form.get("step") === "phone") return normalizePhone(form.get("phone") ?? "") !== null;    return form.get("step") === "code" && filled(form.get("code")) && filled(form.get("challenge_id"));  }  let json: Record<string, unknown>;  try {    json = JSON.parse(text) as Record<string, unknown>;  } catch {    return false;  }  if (!json || typeof json !== "object") return false;  if (/^\/v1\/code\/?$/.test(path)) return typeof json.phone === "string" && normalizePhone(json.phone) !== null && filled(json.device_id);  return filled(json.challenge_id) && filled(json.code) && filled(json.device_id);}/** The calls at an object's door that send a code or prove one. */const SIGN_IN_PATHS = /^\/(v1\/code|v1\/sign-in|oauth\/authorize)\/?$/;export default {  /**   * Every answer leaves through here, and none carries the fault header out (ROUTES-AUDIT 13, 23 Nov 2026): the open   * door's own error path and any forward that skipped `toldFault` gave outside callers what threw, with its frames.   */  async fetch(outside: Request, env: Env): Promise<Response> {    const answer = await front(outside, env);    return toldFault(outside, new URL(outside.url).pathname, answer);  },  /** Mail to a person's own domain, from Cloudflare's Email Routing (src/mail/receive.ts). */  async email(message: ForwardableEmailMessage, env: Env): Promise<void> {    await receive(message, env);  },  /** JOBS OUT 4, the dead-man check: every 5 minutes each account's alarm is looked at from outside it (src/alarm_watch.ts). */  async scheduled(_controller: ScheduledController, env: Env, ctx: ExecutionContext): Promise<void> {    ctx.waitUntil(watchAlarms(env).then(() => undefined));  },  /** Cloudflare's word on mail sent from a person's own domain: bounces, complaints (src/mail/events.ts). */  async queue(batch: MessageBatch<SendingEvent | unknown>, env: Env): Promise<void> {    // The background jobs (JOBS OUT 1, src/jobs/run.ts): each reaches its account object through the front, as a phone does.    if (JOB_QUEUES.has(batch.queue)) return consume(batch, (request) => front(request, env), env.ENV_LABEL);    await sendingEvents(batch as MessageBatch<SendingEvent>, env);  },} satisfies ExportedHandler<Env, SendingEvent | unknown>;async function front(outside: Request, env: Env): Promise<Response> {  {    // Which object and which prefix are the Worker's to say, never a caller's.    const request = inward(outside);    const url = new URL(request.url);    // Deleting an account answers only where it is switched on (src/account_delete.ts `switchedOn`): off, nothing starts one.    // Off, reading /delete gets the site's page (apps/cotton-site pages.ts `deletePage`: how to ask by email), so the    // address Play asks for is never a 404; only asking (a POST, any API route) answers not available.    if (!accountDelete.switchedOn(env) && accountDelete.ANY_DELETE_PATH.test(url.pathname)) {      if (accountDelete.SITE_PAGE.test(url.pathname) && (request.method === "GET" || request.method === "HEAD") && env.SITE) return await env.SITE.fetch(request);      return accountDelete.notAvailable(url.pathname);    }    if (url.pathname === "/health") return json({ ok: true, service: "cottondb", env: env.ENV_LABEL ?? "unlabelled", agent_grant: env.AGENT_GRANT === "on", build: env.BUILD_SHA ?? null });    // On the open host a `/b/<slug>` prefix still names its object, as on workers.dev: the e2e scripts run one wrangler dev for both.    if (env.OPEN_HOST && url.hostname.toLowerCase() === env.OPEN_HOST && !PREFIXED.test(url.pathname)) return openDoor(request, env);    const named = resolve(url);    if (!named) return json({ code: "no_business", message: "name a business: <slug>.<domain> or /b/<slug>/…" }, 404);    // A job's door (JOBS OUT 2, M1): a call without a job's credential never reaches the object, nor does its body.    if (named.path.startsWith("/v1/jobs/") && !(request.headers.get("authorization") ?? "").startsWith(JOB_SCHEME)) return json({ code: "job_credential", message: "a job's call carries its credential" }, 401);    // Objects call each other on /internal/ (a forwarded MCP call); no outside request reaches it.    if (named.path.startsWith("/internal/")) return json({ code: "not_found", message: "no such route" }, 404);    if (named.path.startsWith("/v1/photos/") && (request.method === "GET" || request.method === "HEAD")) {      if (await accountDelete.marked(env, named.slug)) return json({ code: "not_found", message: "no such photo" }, 404);      return photo(env, named.slug, decodeURIComponent(named.path.slice("/v1/photos/".length)));    }    // A film's, book's or song's bytes on a slug-bound stream URL: answered here from the bucket, never in the object's    // queue (STREAM AT THE DOOR, src/media.ts streamAtDoor). An account marked for deletion streams nothing.    const stream = STREAM_PATH.exec(named.path);    if (stream && slugBound(stream[1]!)) {      if (await accountDelete.marked(env, named.slug)) return json({ code: "not_found", message: "no such media" }, 404);      try {        return await streamAtDoor(env, named.slug, stream[1]!, stream[2]!, request.method, request.headers.get("range"));      } catch (error) {        return answerRefusal(error);      }    }    // A sign-in call at an object's own door is counted as one at the open host's (ROUTES-AUDIT 7): the network's hour    // and every network's together, before any code is sent.    // The body is read first: a request whose stream waits across another call is not forwarded whole (on dev, 23 Nov    // 2026, every gated call answered 1101: "Can't read from request stream after response has been sent").    // AUDIT A H3: only a call that can reach Twilio is counted (a junk body is refused by the object and costs nothing),    // and no body over SIGN_IN_BODY_MAX is read (AUDIT A M3).    let body: ArrayBuffer | null = null;    if (request.method === "POST" && SIGN_IN_PATHS.test(named.path)) {      const read = await boundedBody(request, SIGN_IN_BODY_MAX);      if (!read) return json({ code: "too_large", message: `a sign-in call's body is at most ${SIGN_IN_BODY_MAX} bytes` }, 413);      body = read;      if (reachesTwilio(named.path, body)) {        const busy = await directory(env).signInGate(request.headers.get("cf-connecting-ip"));        if (busy) return json({ code: busy.code, message: busy.message }, busy.status);      }    }    const target = new URL(request.url);    target.pathname = named.path;    const forwarded = body === null ? new Request(target.toString(), request) : new Request(target.toString(), { method: request.method, headers: request.headers, body, redirect: request.redirect });    forwarded.headers.set(SLUG_HEADER, named.slug);    // The admin token asking for the timing split stays here (LIVE SLOW 3).    forwarded.headers.delete(TIMING_ASK_HEADER);    forwarded.headers.set(PREFIX_HEADER, named.prefix);    const id = env.BUSINESS.idFromName(await objectName(env, named.slug, request));    // The owner and the businesses are in Hyderabad. Only an object's first get honours a hint, so every get carries it.    const started = Date.now();    return toldSlow(request, named.path, started, await env.BUSINESS.get(id, { locationHint: "apac" }).fetch(forwarded), env);  }}/** * The one object every slug Cotton never made is answered by (AUDIT FIX B1, B-6): it holds no database, so it answers * as any absent object does (stranger blind), and a made-up slug makes no object of its own. Not a slug (`~`), so no * request ever names it, and no admin onboards it. */const NOBODY_OBJECT = "~nobody";/** Slugs this isolate already knows are Cotton's; a slug not known is asked again after a minute. */const known = new Map<string, number>();const UNKNOWN_FOR_MS = 60_000;/** The object name a request reaches: its slug's own when the directory knows the slug (or the admin token asks), else NOBODY_OBJECT. */async function objectName(env: Env, slug: string, request: Request): Promise<string> {  const at = known.get(slug);  if (at === Infinity) return slug;  if (isAdminToken(env, bearer(request))) {    await directory(env).knowSlug(slug);    known.set(slug, Infinity);    return slug;  }  if (at !== undefined && Date.now() - at < UNKNOWN_FOR_MS) return NOBODY_OBJECT;  const yes = await directory(env).slugKnown(slug);  known.set(slug, yes ? Infinity : Date.now());  if (known.size > 50_000) known.clear();  return yes ? slug : NOBODY_OBJECT;}/** A photo of this business, public, cached hard: keys are content addresses. */async function photo(env: Env, slug: string, key: string): Promise<Response> {  if (!key.startsWith(`${slug}/`) || key.includes("..")) return json({ code: "not_found", message: "no such photo" }, 404);  // RESTORE 2 SERVER 3 (M1): a segment beginning with "." or "_" is never a photo. Under `<slug>/` PHOTOS also holds the  // deletion marker `.deleting` (src/account_delete.ts) and, before this round, restore's own files; they are never  // served, whatever moves there later. The erasing mark `erasing/<object id>` (src/business.ts `erasingKey`) sits  // under a word a slug could be: refused by name.  if (slug === "erasing" || key.split("/").some((segment) => segment.startsWith(".") || segment.startsWith("_"))) return json({ code: "not_found", message: "no such photo" }, 404);  // A report's screenshot and log share the bucket but are never public (ROUTES-AUDIT 15): the admin reads them (`/v1/admin/feedback/file`).  if (key.startsWith(`${slug}/feedback/`)) return json({ code: "not_found", message: "no such photo" }, 404);  const object = await env.PHOTOS.get(key);  if (!object) return json({ code: "not_found", message: "no such photo" }, 404);  const headers = new Headers();  object.writeHttpMetadata(headers);  headers.set("etag", object.httpEtag);  headers.set("cache-control", "public, max-age=31536000, immutable");  return new Response(object.body, { headers });}