Cotton code
530 lines · 33.3 KB · TypeScriptRaw
/** * The open host (OPEN_HOST, cottondb.com): one address for every person * (owner, 26 Oct 2026). Nothing in the URL names an object here: * *   POST /v1/code { phone, device_id }      the directory finds the number's *        database, or makes it, and its object issues the code; the answer *        adds `database_id` and `host` *   POST /v1/sign-in { database_id, challenge_id, code, device_id[, name][, name_after] } *        the object of `database_id` proves the code and grants a credential *        that names it (`ctd_<database_id>_…`) *   anything else with a bearer that names its database (`ctn_<id>_…`, a *        Cotton MCP token, or `ctd_<id>_…`, a device credential) goes to *        that database's object, which checks the bearer as it always has *   POST /v1/approval/ask | poll | reveal | claim  a new device approved from one *        already signed in, with no code (src/approval.ts) *   GET /v1/admin/recovery/flows, with the admin token: accounts with a one-helper setup, devices by the flow of *       the way back in they last spoke (TRUSTED RECOVERY BUILD 2), counts only. *   GET /v1/admin/deletions, with the admin token: by day, accounts set for *        deletion, kept and erased, and how many are set now (counts only) *   POST /v1/admin/directory { database_id, slug, phone }, with the admin *        token: enter a database made before the directory (the owner's) *   GET /v1/google/callback?code&state  Google's answer in the person's *        browser: the state names the database whose object gave it *   GET /v1/spotify/callback?code&state  Spotify's, the same way (src/spotify.ts) *   GET|POST /delete  the same as a page, no script (src/delete_page.ts) *   POST /v1/account/delete/web/code { phone, browser_id }  deleting an *        account without the app: the directory finds the number's object *        (never making one) and it sends a code; a number on no database is *        answered the same, and no code goes *   POST /v1/account/delete/web { phone, challenge_id, code, browser_id, *        confirm: "delete" }  the code proved and the deletion begun *        (src/account_delete.ts); both answer no sooner than ANSWER_FLOOR_MS *   a bearer naming a deleted database → 410 `account_deleted`, so a *        phone forgets its copy *   POST /v1/feedback  a shaken report, with a device credential or none: *        the sender's object vouches for the number, and the report is *        written in Cotton's own object (src/feedback.ts) *   GET /v1/stream/<token>/<database id>/films/…  a film's file for the *        player, no bearer: the key names the database, and its object *        checks the token (src/media.ts) * * OAUTH FOR MCP (owner, 6 Nov 2026): every person connects their assistant * at this one address, https://<open host>/mcp, and signs in with their number * and code in the browser (src/oauth.ts holds the flow): * *   /mcp with no bearer, or one naming no database → 401 with *        `WWW-Authenticate: Bearer resource_metadata="…"`; one naming its *        database goes to its object, which answers the same when it is no good *   GET  /.well-known/oauth-protected-resource[/mcp] and *        /.well-known/oauth-authorization-server[/mcp]  answered here *   POST /oauth/register  a client in the directory, for every person *   GET  /oauth/authorize  the phone page; its POST with the number finds or *        makes that number's database (the /v1/code limits) and that object *        issues the code; the POST with the code goes to the object the form *        names, which proves it and returns a code naming its database *   POST /oauth/token  the code or refresh token names its database *        (`ctc_<id>_…`, `ctr_<id>_…`), and that object redeems it * * * THE SITE (owner, 27 Oct 2026): cottondb.com is also the public site's * address, and Cloudflare gives a hostname to one Worker, so this door holds * it and hands the site Worker (cotton-site, bound as SITE) every request * that is not the door's own business, unchanged (`forSite`). */import { DELETE_PAGE, deletePage } from "./delete_page.ts";import { STOP_PATH, stopPage } from "./recovery_stop_page.ts";import { SLUG_HEADER, STREAM_PATH } from "./business.ts";import { ANSWER_FLOOR_MS, ASK_ID, BYTES32, DEVICE_KEY, deviceKind, deviceName } from "./approval.ts";import { requestOptions } from "./passkey.ts";import * as accountDelete from "./account_delete.ts";import { directory, type Answer, type Entry } from "./directory.ts";import type { Env } from "./env.ts";import { callRoom, roomOf } from "./calling/room.ts";import { ticketDatabase } from "./chat/chat.ts";import { answerRefusal, bearer, isAdminToken, json, readJson, refuse, SIGN_IN_BODY_MAX, text, TIMING_ASK_HEADER, toldSlow } from "./http.ts";import { CALLBACK_PATH } from "./google.ts";import { CALLBACK_PATH as SPOTIFY_CALLBACK_PATH } from "./spotify.ts";import { authorizeParams, BAD_PHONE, challenge, clientIdOf, cors, directoryClients, form, notAnswered, OAUTH_PATH, oauthDocument, oauthError, page, phonePage, PREFIX_HEADER, readAsk, register, UNREADABLE_FORM, urlsOf } from "./oauth.ts";import { normalizePhone } from "./protocol.ts";import * as feedback from "./feedback.ts";import * as plans from "./plans.ts";import * as published from "./published.ts";import * as spaces from "./space/door.ts";import { spacesOn } from "./space/switch.ts";/** A bearer that names its database: an MCP token or a device credential. */const NAMES_DATABASE = /^ct[nd]_([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})_./;/** A database id, as a key's first segment names it. */const DATABASE_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;/** An authorization code or refresh token, which names its database (src/oauth.ts). */const GRANT_NAMES_DATABASE = /^ct[cr]_([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})_./;/** A Google consent state: the database that asked, then its secret part. */const STATE_NAMES_DATABASE = /^([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.[A-Za-z0-9_-]+$/;/** Database id → its object's slug. A database never moves, so an isolate keeps what it learnt. */const objects = new Map<string, string>();/** * Whether a request on the open host is the site's. The door's own business, * decided by the path first: `/v1` and everything under it (code, sign-in, * admin/directory, google/callback and every bearer's call to its object), * `/mcp` and everything under it, `/health`, and `/internal/` (a 404 here). * Then by the header: a request carrying `Authorization` is an API client's, * whatever its path, and gets the door's answer, never a page. * * Everything else is the site's (apps/cotton-site/src/worker/index.ts * `route`): `/`, `/privacy`, `/terms`, `/beta`, `/docs` and `/docs/*`, * `/testers`, `/api/waitlist`, `/_health`, `/mac/appcast.xml`, * `/mac/download/*`, `/mac/runner/*`, a retired `/m/<handle>`, the static * assets and `/404.html`, and any path neither answers (the site's 404 page). * The OAuth documents and endpoints are the door's (`OAUTH_PATH`); every other * `/.well-known/*` is the site's. */export function forSite(pathname: string, authorization: string | null): boolean {  const door = pathname === DELETE_PAGE || pathname === "/v1" || pathname.startsWith("/v1/") || pathname === "/mcp" || pathname.startsWith("/mcp/") || pathname === "/health" || pathname.startsWith("/internal/") || OAUTH_PATH.test(pathname);  if (door) return false;  return authorization === null;}/** * The request without the headers the Worker and this door tell an object * with (which object, which prefix): whatever an outside caller sent under * them is dropped on the way in, so only the Worker's own reach an object. */export function inward(request: Request): Request {  if (!request.headers.has(SLUG_HEADER) && !request.headers.has(PREFIX_HEADER)) return request;  const headers = new Headers(request.headers);  headers.delete(SLUG_HEADER);  headers.delete(PREFIX_HEADER);  return new Request(request, { headers });}/** * The asking device's routes (`/v1/approval/*`) answer no sooner than ANSWER_FLOOR_MS after the request came, refusals * too: a number not on Cotton, one with no device open and one with a phone open answer in one timing class * (src/approval.ts). */export async function openDoor(outside: Request, env: Env): Promise<Response> {  const pathname = new URL(outside.url).pathname;  // /v1/code too (ROUTES-AUDIT 6): a new number waits for its database to be made; the floor narrows that gap.  if (!pathname.startsWith("/v1/approval/") && !pathname.startsWith(WEB_DELETE) && pathname !== DELETE_PAGE && pathname !== "/v1/code") return await openDoorNow(outside, env);  const started = Date.now();  const answer = await openDoorNow(outside, env);  const left = ANSWER_FLOOR_MS - (Date.now() - started);  await pause(left);  return answer;}function pause(ms: number): Promise<void> {  return ms > 0 ? new Promise((done) => setTimeout(done, ms)) : Promise.resolve();}async function openDoorNow(outside: Request, env: Env): Promise<Response> {  const request = inward(outside);  try {    const url = new URL(request.url);    const path = url.pathname;    // A Cotton passkey for this host works in the Cotton apps their signing certs name (src/passkey.ts).    if (request.method === "GET" && path === "/.well-known/assetlinks.json" && env.ANDROID_ASSET_LINKS) {      return new Response(env.ANDROID_ASSET_LINKS, { headers: { "content-type": "application/json", "cache-control": "public, max-age=3600" } });    }    // The iPhone's twin: the Cotton apps' `webcredentials` (team id + bundle id), so the passkey sheet takes this host.    if (request.method === "GET" && path === "/.well-known/apple-app-site-association" && env.APPLE_APP_SITE_ASSOCIATION) {      return new Response(env.APPLE_APP_SITE_ASSOCIATION, { headers: { "content-type": "application/json", "cache-control": "public, max-age=3600" } });    }    if (forSite(path, request.headers.get("authorization"))) {      if (!env.SITE) refuse(503, "no_site", "the site Worker is not bound");      return await env.SITE.fetch(request);    }    if (path.startsWith("/internal/")) refuse(404, "not_found", "no such route");    // A payment provider's webhook (src/plans.ts): 404 for every provider not bound here, which on dev and live is all.    const provider = plans.PLANS_PATH.exec(path);    if (provider) return await plans.webhook(request, env, provider[1]!);    const ip = request.headers.get("cf-connecting-ip") ?? "unknown";    if (OAUTH_PATH.test(path)) return await oauth(request, env, url, path, ip);    if (request.method === "POST" && path === "/v1/code") {      const body = await readJson(request, SIGN_IN_BODY_MAX);      const phone = normalizePhone(text(body.phone, "phone"));      if (!phone) refuse(400, "bad_phone", "use an international phone number starting with +");      text(body.device_id, "device_id");      const entry = settle(await directory(env).open(phone, ip));      return withDatabase(await forward(env, entry.slug, url, "/v1/code", body), entry, url);    }    if (request.method === "POST" && path === "/v1/sign-in") {      const body = await readJson(request, SIGN_IN_BODY_MAX);      const databaseId = text(body.database_id, "database_id");      const entry = settle(await directory(env).admit(databaseId, ip));      return withDatabase(await forward(env, entry.slug, url, "/v1/sign-in", body), entry, url);    }    // A sign-in approved from another device (src/approval.ts): the directory routes the ask and never makes a database.    if (request.method === "POST" && path === "/v1/approval/ask") {      const body = await readJson(request, SIGN_IN_BODY_MAX);      const phone = normalizePhone(text(body.phone, "phone"));      if (!phone) refuse(400, "bad_phone", "use an international phone number starting with +");      const deviceId = text(body.device_id, "device_id");      if (!DEVICE_KEY.test(deviceId)) refuse(400, "bad_device", "device_id is the device's public key, 32 bytes of base64url");      // An ask with no commit is an app from before the codes were compared on both screens.      if (typeof body.commit !== "string" || !BYTES32.test(body.commit)) refuse(400, "update_app", "update this app to be approved from another device, or send a code");      const vaultKey = body.vault_key === undefined || body.vault_key === null ? null : text(body.vault_key, "vault_key");      if (vaultKey !== null && !DEVICE_KEY.test(vaultKey)) refuse(400, "bad_vault_key", "vault_key is the device's X25519 public key, 32 bytes of base64url");      return json(settle(await directory(env).ask(phone, deviceId, deviceName(body.device_name), vaultKey, body.commit, ip, deviceKind(body.device_kind))));    }    if (request.method === "POST" && path === "/v1/approval/reveal") {      const body = await readJson(request, SIGN_IN_BODY_MAX);      const askId = text(body.ask_id, "ask_id");      if (!ASK_ID.test(askId)) refuse(404, "no_such_ask", "No such sign-in ask; ask again.");      const nonce = text(body.nonce, "nonce");      if (!BYTES32.test(nonce)) refuse(400, "bad_nonce", "nonce is 32 bytes of base64url");      return json(settle(await directory(env).reveal(askId, nonce, ip)));    }    if (request.method === "POST" && path === "/v1/approval/poll") {      const body = await readJson(request, SIGN_IN_BODY_MAX);      const askId = text(body.ask_id, "ask_id");      if (!ASK_ID.test(askId)) refuse(404, "no_such_ask", "No such sign-in ask; ask again.");      return json(settle(await directory(env).askState(askId)));    }    if (request.method === "POST" && path === "/v1/approval/claim") {      const body = await readJson(request, SIGN_IN_BODY_MAX);      const askId = text(body.ask_id, "ask_id");      if (!ASK_ID.test(askId)) refuse(404, "no_such_ask", "No such sign-in ask; ask again.");      const claimed = settle((await directory(env).claim(askId, text(body.sig, "sig"), ip)) as Answer<Record<string, unknown>>);      return json({ ...claimed, host: url.origin });    }    // A Cotton passkey signs in with no number typed (src/passkey.ts): the directory spends the challenge, the object checks the signature.    if (request.method === "POST" && path === "/v1/passkey/begin") {      const begun = settle((await directory(env).passkeyBegin(ip)) as Answer<{ challenge_id: string; challenge: string }>);      return json({ challenge_id: begun.challenge_id, request: requestOptions(begun.challenge, url.hostname) });    }    if (request.method === "POST" && path === "/v1/passkey/sign-in") {      const body = await readJson(request, SIGN_IN_BODY_MAX);      const challengeId = text(body.challenge_id, "challenge_id");      const deviceId = text(body.device_id, "device_id");      if (!DEVICE_KEY.test(deviceId)) refuse(400, "bad_device", "device_id is the device's public key, 32 bytes of base64url");      const response = body.response as Record<string, unknown> | undefined;      if (!response || typeof response !== "object") refuse(400, "bad_request", "response is the platform's answer to the passkey sheet");      const signed = settle((await directory(env).passkeySignIn(challengeId, response, url.hostname, deviceId, ip)) as Answer<Record<string, unknown>>);      return json({ ...signed, host: url.origin });    }    // Deleting an account without the app (cottondb.com/delete): the code to the number is the whole proof.    if (request.method === "POST" && (path === `${WEB_DELETE}/code` || path === WEB_DELETE)) return await webDelete(env, path, await readJson(request, SIGN_IN_BODY_MAX), ip);    // The same, as a page that works in any browser with no script (src/delete_page.ts).    if (path === DELETE_PAGE && ["GET", "HEAD", "POST"].includes(request.method)) {      return await deletePage(request, (step, body) => webDelete(env, step === "code" ? `${WEB_DELETE}/code` : WEB_DELETE, body, ip));    }    // The Stop link a recovery's SMS carries (src/recovery_stop_page.ts): the path names the database, the token is the proof.    const stopping = STOP_PATH.exec(path);    if (stopping && (request.method === "GET" || request.method === "POST")) {      const [, databaseId, token] = stopping;      return await stopPage(request, async () => {        const slug = DATABASE_ID.test(databaseId!) ? await objectOf(env, databaseId!) : null;        return slug ? await stub(env, slug).recoveryStopByLink(token!) : false;      });    }    if ((request.method === "GET" || request.method === "POST") && path === CALLBACK_PATH) return await googleCallback(env, request, url);    if ((request.method === "GET" || request.method === "POST") && path === SPOTIFY_CALLBACK_PATH) return await stateCallback(env, request, url, "Spotify was not connected");    // A film's stream URL carries no bearer: the key it names names the database (src/media.ts).    const streamed = STREAM_PATH.exec(path);    if (streamed) {      const databaseId = decodeURIComponent(streamed[2]!).split("/")[0]!;      const slug = DATABASE_ID.test(databaseId) ? await objectOf(env, databaseId) : null;      if (!slug) refuse(404, "not_found", "no such media");      const forwarded = new Request(url.toString(), request);      forwarded.headers.set(SLUG_HEADER, slug);      forwarded.headers.delete(TIMING_ASK_HEADER);      forwarded.headers.set(PREFIX_HEADER, "");      return await stub(env, slug).fetch(forwarded);    }    const token = bearer(request);    // A shared space (src/space/door.ts): who is asking settled here, what they may do by the space's own gate; its bytes    // answered from R2 by signed URL, never through a person's object. Built off (src/space/switch.ts), the door is not    // asked, and a space path is answered below exactly as any route nobody has.    const spaced = spacesOn() && await spaces.door(request, env, url, { token, objectOf: (databaseId) => objectOf(env, databaseId) });    if (spaced) return spaced;    // A shaken report, signed in or not: the door settles who sent it and hands it to Cotton's own object (src/feedback.ts).    if (request.method === "POST" && path === feedback.FEEDBACK_PATH) return await feedback.door(request, env, ip, token, (databaseId) => objectOf(env, databaseId));    // A published database: read by any signed-in device, written by its publisher alone (src/published.ts).    if (path.startsWith("/v1/published/")) {      return await published.door(request, env, path, {        token,        databaseOf: (credential) => NAMES_DATABASE.exec(credential)?.[1] ?? null,        vouch: async (databaseId, credential) => {          const slug = await objectOf(env, databaseId);          return slug ? await stub(env, slug).publishedReader(credential) : false;        },      });    }    // A call's socket carries its room's credential, not a database's: the room checks it (src/calling/room.ts).    if (request.method === "GET" && path === "/v1/calls/socket") {      const room = roomOf(token);      if (!room) refuse(401, "invalid_credential", "a call's socket needs its room's credential");      return await callRoom(env, room).fetch(request);    }    // A chat socket carries its ticket, not the device's credential: the ticket names the database whose object minted it (src/chat/chat.ts).    if (request.method === "GET" && path === "/v1/chat/socket") {      const databaseId = ticketDatabase(token);      const slug = databaseId ? await objectOf(env, databaseId) : null;      if (!slug) refuse(401, "invalid_credential", "a chat socket needs the ticket its object minted (POST /v1/chat/socket)");      const forwarded = new Request(url.toString(), request);      forwarded.headers.set(SLUG_HEADER, slug);      forwarded.headers.delete(TIMING_ASK_HEADER);      forwarded.headers.set(PREFIX_HEADER, "");      return await stub(env, slug).fetch(forwarded);    }    // The operator's daily count of accounts set for deletion, kept and erased (src/directory.ts `deletingCounts`).    // Read only (DELETE ACCOUNT 2): each account the directory holds as pending, as its own object says it stands.    if (request.method === "GET" && path === "/v1/admin/deletions/check") {      if (!isAdminToken(env, token)) refuse(403, "admin_only", "this needs the admin token");      return json(await directory(env).checkPending());    }    // The owner's count of ways back in by flow (TRUSTED RECOVERY BUILD 2, H1): when no one needs flow 1, it can go.    if (request.method === "GET" && path === "/v1/admin/recovery/flows") {      if (!isAdminToken(env, token)) refuse(403, "admin_only", "this needs the admin token");      return json(await directory(env).recoveryFlowCounts());    }    // The founder row check over every database the directory holds, a page at a time (src/vault_key_check.ts).    // Read only: counts and kinds, never a database id (KEPT FOUR 3 LOW); one database's report only by its id below.    if (request.method === "GET" && path === "/v1/admin/vault-keys/check") {      if (!isAdminToken(env, token)) refuse(403, "admin_only", "this needs the admin token");      const limit = Number(url.searchParams.get("limit") ?? "50");      if (!Number.isInteger(limit) || limit < 1 || limit > 200) refuse(400, "bad_request", "limit is 1 to 200");      const from = Number(url.searchParams.get("from") ?? "0");      if (!Number.isInteger(from) || from < 0) refuse(400, "bad_request", "from is a position, 0 or more");      return json(await directory(env).checkVaultKeys(from, limit));    }    if (request.method === "GET" && path.startsWith("/v1/admin/vault-keys/check/")) {      if (!isAdminToken(env, token)) refuse(403, "admin_only", "this needs the admin token");      const report = await directory(env).checkVaultKeysOf(decodeURIComponent(path.slice("/v1/admin/vault-keys/check/".length)));      if (!report) refuse(404, "not_found", "no database has that id");      return json(report);    }    if (request.method === "GET" && path === "/v1/admin/deletions") {      if (!isAdminToken(env, token)) refuse(403, "admin_only", "this needs the admin token");      return json(await directory(env).deletingCounts());    }    // The deletions' sweep run now (src/directory.ts `sweep`): it only asks after deletions that should have moved.    if (request.method === "POST" && path === "/v1/admin/account/sweep") {      if (!isAdminToken(env, token)) refuse(403, "admin_only", "this needs the admin token");      // On dev (and the tests) the sweep may look as if run later (`ahead_ms`), to walk a deletion it would find in an hour.      const ahead = accountDelete.mayEraseNow(env) ? Number((await readJson(request).catch(() => ({}) as Record<string, unknown>)).ahead_ms ?? 0) : 0;      return json(await directory(env).sweep(Date.now() + (Number.isFinite(ahead) && ahead > 0 ? ahead : 0)));    }    if (request.method === "POST" && path === "/v1/admin/directory") {      if (!isAdminToken(env, token)) refuse(403, "admin_only", "this needs the admin token");      const body = await readJson(request);      const phone = normalizePhone(text(body.phone, "phone"));      if (!phone) refuse(400, "bad_phone", "phone must start with +");      const entry = settle(await directory(env).enter({ databaseId: text(body.database_id, "database_id"), slug: text(body.slug, "slug"), phone }));      objects.set(entry.databaseId, entry.slug);      return json({ database_id: entry.databaseId, slug: entry.slug });    }    const named = token ? NAMES_DATABASE.exec(token) : null;    const slug = named ? await objectOf(env, named[1]!) : null;    if (!slug) {      // The person deleted this account: their phones are told so, and forget it.      if (named && (await directory(env).wasErased(named[1]!))) return json({ code: "account_deleted", message: "This account was deleted." }, 410);      const refusal = named ? json({ code: "invalid_credential", message: "sign in again" }, 401) : json({ code: "no_database", message: "sign in first: this address finds your database from your sign-in" }, 401);      // An MCP client learns from the 401 where to sign in (src/oauth.ts).      return path === "/mcp" ? challenge(refusal, request, token !== null) : refusal;    }    const target = new URL(request.url);    const forwarded = new Request(target.toString(), request);    forwarded.headers.set(SLUG_HEADER, slug);    forwarded.headers.set(PREFIX_HEADER, "");    // The apps reach their object through this door (the Mac's mail push among them): an object's 500 is logged here.    const started = Date.now();    return toldSlow(request, path, started, await stub(env, slug).fetch(forwarded), env);  } catch (error) {    return answerRefusal(error);  }}/** Where deleting without the app is asked (src/account_delete.ts). */const WEB_DELETE = "/v1/account/delete/web";/** A browser's own id for one deletion: what the code is bound to. */const BROWSER_ID = /^[A-Za-z0-9_-]{16,64}$/;type DeleteObject = {  deleteCode(phone: string, browserId: string): Promise<{ challenge_id: string; expires_in: number } | { refused: { status: number; code: string; message: string } }>;  deleteConfirm(challengeId: string, code: string, browserId: string): Promise<{ deleting: true; started_at: string; erase_at: string | null } | { refused: { status: number; code: string; message: string } }>;};/** * Deleting an account from the web. The number's object is found and never * made; a number on no database is answered as one that was sent a code, * and its code never proves, so the page never says who is on Cotton. */async function webDelete(env: Env, path: string, body: Record<string, unknown>, ip: string): Promise<Response> {  const phone = normalizePhone(text(body.phone, "phone"));  if (!phone) refuse(400, "bad_phone", "use an international phone number starting with +");  const browserId = text(body.browser_id, "browser_id");  if (!BROWSER_ID.test(browserId)) refuse(400, "bad_browser", "browser_id is 16 to 64 letters, digits, - or _");  const { slug } = settle(await directory(env).deleting(phone, ip, path.endsWith("/code")));  const object = slug ? (stub(env, slug) as unknown as DeleteObject) : null;  if (path.endsWith("/code")) {    if (!object) return json({ challenge_id: crypto.randomUUID(), expires_in: 300 });    const asked = await object.deleteCode(phone, browserId);    // Any refusal (the account already going, the object's own code limit, Twilio's) is answered as a number nobody    // holds is: a refusal only a real number could get said it was on Cotton (ROUTES-AUDIT 6). The limit is the door's.    if ("refused" in asked) return json({ challenge_id: crypto.randomUUID(), expires_in: 300 });    return json(asked);  }  if (body.confirm !== "delete") refuse(400, "not_confirmed", 'say confirm: "delete" to delete this account');  const challengeId = text(body.challenge_id, "challenge_id");  const code = text(body.code, "code");  if (!object) refuse(401, "invalid_code", "invalid or expired code");  const done = await object.deleteConfirm(challengeId, code, browserId);  if ("refused" in done) refuse(done.refused.status, done.refused.code, done.refused.message);  return json(done, 202);}/** * Google's answer arrives in the person's browser with no bearer, on the open * host or a named one: the state names the database (`<database id>.<random>`, * src/google.ts) and that object alone decides whether it gave it. */export function googleCallback(env: Env, request: Request, url: URL): Promise<Response> {  return stateCallback(env, request, url, "Google Calendar was not connected");}/** A sign-in's answer in the browser (Google's, Spotify's): the state names the database, and its object decides. */async function stateCallback(env: Env, request: Request, url: URL, notConnected: string): Promise<Response> {  // The Connect tap carries the state in its form (src/connect_confirm.ts); Google's arrival, in the query.  const body = request.method === "POST" ? await request.text() : null;  const state = body !== null ? new URLSearchParams(body).get("state") : url.searchParams.get("state");  const named = STATE_NAMES_DATABASE.exec(state ?? "");  const slug = named ? await objectOf(env, named[1]!) : null;  if (!slug) return page(notConnected, "<p>This link is not one Cotton made. Start again from Cotton.</p>", 400);  const forwarded = new Request(url.toString(), { method: request.method, headers: request.headers, body });  forwarded.headers.set(SLUG_HEADER, slug);  forwarded.headers.set(PREFIX_HEADER, "");  return stub(env, slug).fetch(forwarded);}// ── OAuth for MCP ────────────────────────────────────────────────────────/** The open host's OAuth: the documents and registration here, the rest in the object the number or the grant names. */async function oauth(request: Request, env: Env, url: URL, path: string, ip: string): Promise<Response> {  const documents = oauthDocument(request, path);  if (documents) return documents;  const method = request.method;  if (method === "POST" && path === "/oauth/register") return cors(await register(request, directoryClients(env, ip)));  if (method === "POST" && path === "/oauth/token") return token(request, env, url);  if (path === "/oauth/authorize" && (method === "GET" || method === "POST")) return authorize(request, env, url, ip);  return notAnswered(method, path);}/** * The phone page is the door's: no database is known yet. The number's step * finds or makes its database, counted as /v1/code counts it; the code's step * is counted as /v1/sign-in, and goes to the database the form names, whose * object alone holds the challenge it proves. */async function authorize(request: Request, env: Env, url: URL, ip: string): Promise<Response> {  const params = await authorizeParams(request);  if (!params) return page("Cannot connect", UNREADABLE_FORM, 400);  const urls = urlsOf(request);  const ask = await readAsk(params, directoryClients(env, ip), urls, true);  if (ask instanceof Response) return ask;  const step = request.method === "GET" ? "start" : params.get("step");  let answer: Answer<Entry>;  if (step === "phone") {    const phone = normalizePhone(params.get("phone") ?? "");    if (!phone) return phonePage(ask, urls, params, BAD_PHONE);    answer = await directory(env).open(phone, ip);  } else if (step === "code") {    answer = await directory(env).admit(params.get("database_id") ?? "", ip);  } else {    return phonePage(ask, urls, params);  }  if ("refused" in answer) return phonePage(ask, urls, params, answer.refused.message, answer.refused.status);  objects.set(answer.ok.databaseId, answer.ok.slug);  // The object's answer is the browser's: its redirect back to the assistant is passed on, never followed.  return stub(env, answer.ok.slug).fetch(`${url.origin}/oauth/authorize`, {    method: "POST",    redirect: "manual",    headers: { "content-type": "application/x-www-form-urlencoded", "cf-connecting-ip": ip, [SLUG_HEADER]: answer.ok.slug, [PREFIX_HEADER]: "" },    body: params.toString(),  });}/** A code or a refresh token names its database; that object redeems it, judging the client by the directory, and answers with its own CORS headers. */async function token(request: Request, env: Env, url: URL): Promise<Response> {  const params = await form(request);  if (!params) return cors(oauthError("invalid_request", "the body must be application/x-www-form-urlencoded"));  const grant = params.get("grant_type");  if (grant !== "authorization_code" && grant !== "refresh_token") return cors(oauthError("unsupported_grant_type", "grant_type is authorization_code or refresh_token"));  const named = GRANT_NAMES_DATABASE.exec(params.get(grant === "authorization_code" ? "code" : "refresh_token") ?? "");  const slug = named ? await objectOf(env, named[1]!) : null;  if (!slug) {    const clientId = clientIdOf(request, params);    if (!clientId || !(await directory(env).client(clientId))) return cors(oauthError("invalid_client", "unknown client", 401));    return cors(oauthError("invalid_grant", grant === "authorization_code" ? "authorization code is not valid" : "refresh token is not valid"));  }  const headers: Record<string, string> = { "content-type": "application/x-www-form-urlencoded", [SLUG_HEADER]: slug, [PREFIX_HEADER]: "" };  const basic = request.headers.get("authorization");  if (basic) headers.authorization = basic;  return stub(env, slug).fetch(`${url.origin}/oauth/token`, { method: "POST", redirect: "manual", headers, body: params.toString() });}async function objectOf(env: Env, databaseId: string): Promise<string | null> {  const held = objects.get(databaseId);  if (held) return held;  const entry = await directory(env).find(databaseId);  if (entry) objects.set(databaseId, entry.slug);  return entry?.slug ?? null;}function settle<T>(answer: Answer<T>): T {  if ("refused" in answer) refuse(answer.refused.status, answer.refused.code, answer.refused.message);  return answer.ok;}function stub(env: Env, slug: string) {  return env.BUSINESS.get(env.BUSINESS.idFromName(slug), { locationHint: "apac" });}function forward(env: Env, slug: string, url: URL, path: string, body: Record<string, unknown>): Promise<Response> {  return stub(env, slug).fetch(`${url.origin}${path}`, {    method: "POST",    headers: { "content-type": "application/json", [SLUG_HEADER]: slug, [PREFIX_HEADER]: "" },    body: JSON.stringify(body),  });}/** The object's answer with the database it came from and the address to reach it at. */async function withDatabase(res: Response, entry: Entry, url: URL): Promise<Response> {  if (!res.ok) return res;  const body = (await res.json()) as Record<string, unknown>;  return json({ ...body, database_id: entry.databaseId, host: url.origin });}