iterate.com / cloud

git clone https://git.iterate.com/repos/cloud

cloud / internal-packages / installer / worker / index.jsmain at aacbc74

// The installer's Worker: the server half of the wizard (the page is src/). A person connects
// Cloudflare, gets an account ready and a domain into it, and a deploy run (deploy-run.js) puts
// iterate on that domain, in their account.
//
// Cloudflare OAuth with no refresh token (cloudflare-access.js has the rule). The page never sees
// the token: a cookie carries a random session id, and KV holds the token until it ends or a
// deploy takes it.
//
// Bindings: SESSIONS (KV), DEPLOYER (the run), CLIENT_ID (var), CLIENT_SECRET (secret), and
// access.js's CLOUD_KEY and OPERATOR_TOKEN (secrets). wrangler.jsonc names them for each
// environment.
import { inventoryOf, keptOf, namesOf, outsideOf, refusalsOf } from "../container/takeover.mjs";
import { enrol, forget, handle, trustOf } from "./access.js";
import { claimToken, exchange, revoke, takeToken, tokenTtlOf } from "./cloudflare-access.js";
import { deploymentsOf, pagesNow, servedBy, STACK_NAME, zonesOf } from "./deployments.js";
import { iterateNameOf, workersDevNamesOf } from "./account-name.js";
import { candidatesOf } from "./domain-names.js";
import {
  cloudflareTokenGranted,
  NEEDED,
  PERMISSIONS,
  SCOPES,
  TELEMETRY_SCOPE,
  telemetryGranted,
  WIDER,
} from "./scopes.js";
import { stackCommits } from "./stack-commits.js";
import { LINK_KINDS, SIGNED_IN_KINDS } from "./installation.js";
import * as pages from "./installation-pages.js";

// Cloudflare's addresses; a test and the pretend deployment point them at a fake Cloudflare
const endpointsOf = (env) => ({
  api: env.CF_API || "https://api.cloudflare.com/client/v4",
  auth: env.CF_AUTH || "https://dash.cloudflare.com/oauth2/auth",
  token: env.CF_TOKEN,
  revoke: env.CF_REVOKE,
  dash: env.CF_DASH || "https://dash.cloudflare.com/",
});
/** How to reach Cloudflare. The pretend deployment has its pretend Cloudflare as a service binding
 *  (CF_SERVICE): one Worker can't fetch another on the same account's workers.dev by its address. */
const cfFetch = (env) =>
  env.CF_SERVICE ? (input, init) => env.CF_SERVICE.fetch(input, init) : fetch;
const SANDBOX_SCOPE = "registrar-sandbox-domains.admin"; // test mode (?test) only
const SESSION_TTL = 7 * 24 * 60 * 60; // who the person is; the token's own record ends within the hour
const CREATED_TTL = 30 * 24 * 60 * 60;
const ACCOUNT = /^[0-9a-f]{32}$/;
const DOMAIN = /^[a-z0-9-]+(\.[a-z0-9-]+)+$/;
const JSON_BODY = /^application\/json\s*(;|$)/i;

/** The answer to a write that the Cloud's own page did not send, or null for a request that may
 *  go on. A browser puts `Origin` on every request that is not a GET or a HEAD. So a write needs
 *  the Cloud's own origin there: a script on another site cannot write as the signed-in person,
 *  and neither can one on another host of the Cloud's zone, which is the same site for a cookie.
 *  A body must say that it is JSON: a form of another site can send text, and never JSON. */
function refusedWrite(request, url) {
  if (["GET", "HEAD", "OPTIONS"].includes(request.method)) return null;
  if (request.headers.get("origin") !== url.origin)
    return json({ error: "this request did not come from this page" }, 403);
  const type = request.headers.get("content-type");
  if (url.pathname.startsWith("/api/") && type !== null && !JSON_BODY.test(type))
    return json({ error: "a body must be application/json" }, 415);
  return null;
}

/** A cookie's name and its attributes after the value. On https the name starts with `__Host-`:
 *  a browser takes such a cookie from this host alone, with Secure and Path=/, so another host of
 *  the Cloud's zone cannot set one. A test on http cannot have that prefix. */
const cookieOf = (url, name) =>
  url.protocol === "https:"
    ? { name: `__Host-${name}`, attributes: "Path=/; HttpOnly; Secure" }
    : { name, attributes: "Path=/; HttpOnly" };
const cookieIn = (request, name) =>
  new RegExp(`(?:^|;\\s*)${name}=([A-Za-z0-9_-]+)`).exec(request.headers.get("cookie") || "")?.[1];

/** A domain named `iterate.<a domain>`. No stack is deployed on one: `iterate.<domain>` is the
 *  platform's host of the stack on `<domain>`, where its auth Worker publishes the stack's key
 *  (`/keys/stack.json`), and a stack on `iterate.co.uk` would serve its mind's loaded code on the
 *  host that the Cloud reads as the platform of `co.uk`. The stack's config refuses the same
 *  (core/alchemy/src/config.ts). `iterate.com` is not one: no domain follows its first label. */
const PLATFORM_HOST = /^iterate\.[^.]+\../;

export default {
  async fetch(request, env) {
    const url = new URL(request.url);
    const redirectUri = `${url.origin}/callback`;
    const ends = endpointsOf(env);
    try {
      const refused = refusedWrite(request, url);
      if (refused) return refused;
      // the page asks where Cloudflare's dashboard is (a test points it at a fake one)
      // CF_SITE is set on the pretend deployment only: the pretend Cloudflare's address, where a deployed iterate "opens"
      if (url.pathname === "/api/config") {
        const site = env.CF_SITE ? String(env.CF_SITE).replace(/\/$/, "") : null;
        return json({
          dash: ends.dash,
          permissions: PERMISSIONS,
          wider: WIDER,
          // the pages' PostHog project key (src/analytics.ts): public, and none means no reporting
          posthog: env.POSTHOG_KEY || null,
          ...(site && { pretend: { home: `${site}/`, site: `${site}/site/` } }),
        });
      }
      if (url.pathname === "/connect")
        return connect(
          url,
          request,
          env,
          redirectUri,
          ends,
          url.searchParams.get("level") === "identity" ? "identity" : "full",
          url.searchParams.has("test"),
          {
            telemetry: url.searchParams.has("telemetry"),
            cloudflare: url.searchParams.has("cloudflare"),
          },
        );
      if (url.pathname === "/callback") return callback(url, request, env, redirectUri, ends);
      // a chat installation's pages (service.js mints their links)
      const installPage = INSTALL_PAGE.exec(url.pathname);
      if (installPage)
        return installationPage(
          url,
          request,
          env,
          redirectUri,
          ends,
          installPage[1],
          installPage[2],
        );
      // SIGNING OUT IS A WRITE, so the page sends it as a POST, which `refusedWrite` lets through
      // from the Cloud's own origin alone. As a GET, any site's link or image would end the
      // person's session, and with it a run's access to their Cloudflare account.
      if (url.pathname === "/logout") {
        if (request.method !== "POST") return json({ error: "sign out with a POST" }, 405);
        const access = await endSession(env, sessionId(request, url));
        const sid = cookieOf(url, "sid");
        const answer = json({ access });
        answer.headers.set(
          "set-cookie",
          `${sid.name}=; ${sid.attributes}; Max-Age=0; SameSite=Strict`,
        );
        return answer;
      }
      // the Cloud's side of a deployment (access.js): /enrol, /enrolled, /kept, /access
      const access = await handle(request, env, {
        // a deployment that just enrolled gets what the Cloud held for it at once: cloud-clients'
        // Outbox holds it under the mind's control-plane hostname, and tries it again by itself
        // only after a wait of up to 15 minutes
        onEnrolled: (_domain, record) => env.OUTBOX?.get(env.OUTBOX.idFromName(record.mind)).wake(),
      });
      if (access) return access;
      if (url.pathname.startsWith("/api/")) {
        const id = sessionId(request, url);
        const session = id && (await loadSession(env, id));
        if (!session) return json({ error: "not connected" }, 401);
        try {
          return await api(url, request, ends.api, session, id, env);
        } catch (error) {
          if (!(error instanceof NotConnected)) throw error;
          // the access to Cloudflare is over: who the person is stays, and the page asks to connect again
          await env.SESSIONS.delete(`t:${id}`);
          return json({ error: "not connected", detail: error.message }, 401);
        }
      }
      return env.ASSETS ? env.ASSETS.fetch(request) : new Response("Not found\n", { status: 404 });
    } catch (error) {
      return json({ error: String(error?.message || error) }, 500);
    }
  },
};

// ── OAuth ─────────────────────────────────────────────────────────────────────────────────────

/** Two levels of consent (incremental authorization): "identity" asks only who you are, enough to
 *  create a new account (POST /accounts takes a user's token with user-details.read); "full" asks for
 *  everything iterate needs, on the accounts the person selects on Cloudflare's page. */
const IDENTITY_SCOPES = ["user-details.read"];
const requestedOf = (level, test, wants) =>
  level === "identity"
    ? IDENTITY_SCOPES
    : [
        ...SCOPES,
        ...(test ? [SANDBOX_SCOPE] : []),
        ...(wants?.telemetry || wants?.cloudflare ? [TELEMETRY_SCOPE] : []),
      ];

/** What a person does on Cloudflare's page at a consent for telemetry or for a mind's Cloudflare
 *  connection. Without it Cloudflare gives no consent at all ("This application requires a permission you have unchecked"). */
const tickFor = (what) =>
  `To ${what}, turn on “Account API Tokens Write” under “Sensitive scopes” on Cloudflare's page, then press Authorize.`;

/** `wants`: what the consent is also for, `telemetry` for the stack's telemetry and `cloudflare`
 *  for the mind's Cloudflare connection. Either one asks one more scope (which links ask which:
 *  scopes.js `TELEMETRY_SCOPE`). The sign-in keeps what they asked for: the scope alone turns on
 *  neither. */
async function connect(url, request, env, redirectUri, ends, level, test, wants, extra = {}) {
  const state = randomId();
  const verifier = randomId() + randomId();
  const challenge = base64url(
    await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier)),
  );
  // `previous`: the sign-in of this browser now. The callback ends it, and the browser does not
  // send its cookie there (SameSite=Strict, and the way back starts at Cloudflare's site).
  // A chat installation's consent (`extra.installation`) is not this browser's sign-in to the
  // wizard, and ends none.
  const previous = extra.installation ? undefined : sessionId(request, url);
  await env.SESSIONS.put(
    `state:${state}`,
    JSON.stringify({ verifier, level, test, ...wants, previous, ...extra }),
    { expirationTtl: 600 },
  );
  const query = new URLSearchParams({
    response_type: "code",
    client_id: env.CLIENT_ID,
    redirect_uri: redirectUri,
    scope: requestedOf(level, test, wants).join(" "),
    state,
    code_challenge: challenge,
    code_challenge_method: "S256",
  });
  // the state also goes to this browser as a cookie: the callback takes a state from the browser
  // that started it alone, so nobody can finish their own consent in another person's browser
  const kept = stateCookie(url, state);
  return redirect(`${ends.auth}?${query}`, `${kept.name}=1; ${kept.attributes}; Max-Age=600`);
}
/** The cookie that says "this browser started the consent with this state". One for each state,
 *  so two tabs do not end each other's. SameSite=Lax: the way back from Cloudflare is a
 *  navigation from another site, and it must carry this cookie. */
const stateCookie = (url, state) => {
  const { name, attributes } = cookieOf(url, `state-${state}`);
  return { name, attributes: `${attributes}; SameSite=Lax` };
};

async function callback(url, request, env, redirectUri, ends) {
  const error = url.searchParams.get("error");
  const state = url.searchParams.get("state") || "";
  if (error) {
    const said = url.searchParams.get("error_description") || error;
    // a consent for telemetry or for a mind's Cloudflare connection that Cloudflare did not give:
    // most often the scope was not ticked
    const asked = /^[A-Za-z0-9_-]+$/.test(state)
      ? JSON.parse((await env.SESSIONS.get(`state:${state}`)) || "null")
      : null;
    const tick =
      asked?.telemetry && asked?.cloudflare
        ? tickFor("turn on telemetry and give your mind a Cloudflare connection")
        : asked?.telemetry
          ? tickFor("turn on telemetry")
          : asked?.cloudflare
            ? tickFor("give a mind a Cloudflare connection")
            : "";
    if (asked?.installation && INSTALLATION.test(asked.installation)) {
      await installationOf(env, asked.installation).install("consentRefused", { said, tick });
      return html(pages.message("Cloudflare gave no consent", tick ? `${said}. ${tick}` : said));
    }
    return redirect(`/#error=${encodeURIComponent(tick ? `${said}. ${tick}` : said)}`);
  }
  const kept = /^[A-Za-z0-9_-]+$/.test(state) ? stateCookie(url, state) : null;
  const expired = "/#error=the%20sign-in%20expired%3B%20connect%20again";
  // a state that this browser did not start is refused, and its row stays for the browser that did
  if (!kept || !cookieIn(request, kept.name)) return redirect(expired);
  const spent = `${kept.name}=; ${kept.attributes}; Max-Age=0`;
  const pending = JSON.parse((await env.SESSIONS.get(`state:${state}`)) || "null");
  if (!pending?.verifier) return redirect(expired, spent);
  await env.SESSIONS.delete(`state:${state}`);
  let access;
  try {
    access = await exchange({
      code: url.searchParams.get("code") || "",
      verifier: pending.verifier,
      redirectUri,
      clientId: env.CLIENT_ID,
      clientSecret: env.CLIENT_SECRET,
      tokenUrl: ends.token,
      revokeUrl: ends.revoke,
      fetch: cfFetch(env),
    });
  } catch (error) {
    const said = String(error?.message || error);
    if (pending.installation)
      return html(
        pages.message("Cloudflare did not connect", `${said}. Ask in the chat for a new link.`),
        502,
        spent,
      );
    return redirect(`/#error=${encodeURIComponent(said)}`, spent);
  }
  if (pending.installation) return installationConsent(url, env, ends, pending, access, spent);
  // the Worker's log: whether Cloudflare sent a refresh token, which nobody asked for
  console.log(
    JSON.stringify({
      message: access.refresh
        ? `Cloudflare's code exchange sent a refresh token. Its revoke answered ${access.refresh.revoke || "nothing"}.`
        : "Cloudflare's code exchange sent no refresh token.",
      refreshToken: !!access.refresh,
      ...(access.refresh && { revoke: access.refresh.revoke }),
    }),
  );
  await endSession(env, pending.previous); // a new consent replaces the sign-in before it
  const id = randomId();
  await env.SESSIONS.put(
    `t:${id}`,
    JSON.stringify({ token: access.token, expiresAt: access.expiresAt }),
    { expirationTtl: tokenTtlOf(access.expiresAt) },
  );
  await saveSession(env, id, {
    scope: access.scope,
    requested: requestedOf(pending.level, pending.test, pending).join(" "),
    level: pending.level,
    // what the person pressed for this consent: a deploy or an update does that, and no more
    telemetry: pending.telemetry === true,
    cloudflare: pending.cloudflare === true,
    refreshToken: access.refresh
      ? `sent, and its revoke answered ${access.refresh.revoke}`
      : "none",
    until: Date.now() + SESSION_TTL * 1000,
  });
  // SameSite=Strict: the page's own calls carry the cookie, and no request from another site does
  const sid = cookieOf(url, "sid");
  return redirect(
    `/#connected=${pending.level}`,
    `${sid.name}=${id}; ${sid.attributes}; Max-Age=${SESSION_TTL}; SameSite=Strict`,
    spent,
  );
}

// ── a chat installation (installation.js, service.js) ────────────────────────────────────────

const INSTALL_PAGE = /^\/i\/(inst_[a-z2-7]{26})\/([a-z-]+)$/;
const INSTALLATION = /^inst_[a-z2-7]{26}$/;
const installationOf = (env, id) => env.DEPLOYER.getByName(`inst:${id}`);
/** The cookie of a browser that proved, with a consent, that it is the installation's Cloudflare
 *  user. SameSite=Lax: the chat's link to a page is a navigation from another site. */
const installCookie = (url, id) => {
  const { name, attributes } = cookieOf(url, `inst-${id}`);
  return { name, attributes: `${attributes}; SameSite=Lax` };
};
/** Where a kind of link goes on Cloudflare's dashboard. */
const DASH_PAGES = {
  card: "billing/subscriptions?paymentMethod=add",
  "workers-paid": "workers/plans",
  r2: "r2/overview",
};

/** A page of a chat installation. A link the chat gives carries a single-use nonce
 *  (`?n=`): consent and the dashboard's pages go on at once. A page that spends money, picks for
 *  the person, or hands over the owner's ticket also needs the browser of the installation's own
 *  Cloudflare user: a cookie that only a consent of theirs sets. Without it, the nonce starts a
 *  sign-in that asks Cloudflare who they are, and nothing more. */
async function installationPage(url, request, env, redirectUri, ends, id, kind) {
  const installation = installationOf(env, id);
  const ask = (op, args) => installation.install(op, args);
  const status = await ask("status");
  if (!status)
    return html(pages.message("No such installation", "Ask in the chat for a new link."), 404);
  if (kind === "connected") return html(pages.connected());
  if (!LINK_KINDS.includes(kind)) return new Response("Not found\n", { status: 404 });
  const cookie = installCookie(url, id);
  const signedIn = await ask("hasSession", cookieIn(request, cookie.name) || "");
  const nonce = url.searchParams.get("n");
  if (request.method === "GET" && nonce) {
    if (!(await ask("takeLink", { nonce, kind }))) return html(pages.used(), 410);
    if (kind === "consent")
      return connect(
        url,
        request,
        env,
        redirectUri,
        ends,
        "full",
        false,
        { telemetry: status.choices.telemetry, cloudflare: status.choices.cloudflareConnection },
        { installation: id },
      );
    if (DASH_PAGES[kind]) {
      const account = status.choices.accountId;
      if (!ACCOUNT.test(account || "")) return html(pages.used(), 410);
      return redirect(`${ends.dash.replace(/\/?$/, "/")}${account}/${DASH_PAGES[kind]}`);
    }
    if (!signedIn)
      return connect(
        url,
        request,
        env,
        redirectUri,
        ends,
        "identity",
        false,
        {},
        {
          installation: id,
          next: kind,
        },
      );
    return redirect(`/i/${id}/${kind}`);
  }
  if (!SIGNED_IN_KINDS.includes(kind)) return html(pages.used(), 410);
  if (!signedIn) return html(pages.notSignedIn(), 403);
  const form =
    request.method === "POST" ? new URLSearchParams(await request.text()) : new URLSearchParams();
  if (kind === "account") {
    if (request.method === "POST") {
      const chosen = await ask("choose", { accountId: String(form.get("account") || "") });
      if (chosen.refused)
        return html(
          pages.message("That account cannot be used", chosen.refused.error),
          chosen.refused.status,
        );
      return html(pages.accounts({ done: true }));
    }
    return html(pages.accounts({ list: status.accounts, chosen: status.choices.accountId }));
  }
  if (kind === "domain") {
    if (request.method === "POST") {
      const domain = String(form.get("domain") || "").toLowerCase();
      const bought = await ask("domainBuy", {
        domain,
        confirm: String(form.get("confirm") || "")
          .trim()
          .toLowerCase(),
        contacts: pages.contactsOf(form),
      });
      if (bought.ok) return html(pages.domain({ bought: domain }));
      const found = await ask("domainSearch", domain);
      return html(
        pages.domain({ q: domain, found: found.error ? null : found, said: bought.error }),
        400,
      );
    }
    const q = String(url.searchParams.get("q") || "")
      .trim()
      .slice(0, 80);
    const found = q ? await ask("domainSearch", q) : null;
    if (found?.error)
      return html(
        pages.message(
          "The access to Cloudflare ended",
          "Ask in the chat for a fresh consent, then for a new domain link.",
        ),
        409,
      );
    return html(pages.domain({ q, found }));
  }
  // the owner's first passkey: the ticket goes from this object's memory to this browser, once
  const first = await ask("ownerTicket");
  if (!first)
    return html(
      pages.message(
        "This link was used",
        "The first passkey link works once. Sign in to your mind with a mailed code instead.",
      ),
      410,
    );
  const site = env.CF_SITE ? `${String(env.CF_SITE).replace(/\/$/, "")}/site/` : "https://";
  return redirect(`${site}iterate.${first.zone}/keys/first#${first.ticket}`);
}

/** The callback of a chat installation's consent. The token is given to the installation only
 *  when Cloudflare says that it is the installation's own user's; any other user's is revoked at
 *  once. A sign-in only to say who they are (`identity`) gives its token up at once too. */
async function installationConsent(url, env, ends, pending, access, spent) {
  const id = pending.installation;
  const installation = installationOf(env, id);
  const giveUp = () =>
    revoke({
      token: access.token,
      clientId: env.CLIENT_ID,
      clientSecret: env.CLIENT_SECRET,
      revokeUrl: ends.revoke,
      fetch: cfFetch(env),
    });
  if (access.refresh)
    console.log(
      JSON.stringify({
        message: "Cloudflare's code exchange sent a refresh token.",
        revoke: access.refresh.revoke,
      }),
    );
  const who = await cfFetch(env)(`${ends.api}/user`, {
    headers: { authorization: `Bearer ${access.token}` },
  })
    .then((answer) => answer.json())
    .catch(() => null);
  const expected = await installation.install("expectedUser");
  const userId = who?.result?.id;
  const email = String(who?.result?.email || "")
    .trim()
    .toLowerCase();
  // the owner's email until the first consent, then that consent's Cloudflare user alone
  const theirs =
    expected &&
    userId &&
    (expected.cloudflareUserId ? userId === expected.cloudflareUserId : email === expected.email);
  if (!theirs || !(await installation.install("bindUser", { cloudflareUserId: userId })).ok) {
    const gave = await giveUp();
    console.log(
      JSON.stringify({
        message: `A consent for an installation came from another Cloudflare user. Cloudflare ${gave.ok ? "revoked" : "did NOT revoke"} its access (${gave.status}).`,
        revoke: gave.status,
      }),
    );
    // a new consent link for the right login, when the wrong one came from a consent link
    const again =
      pending.level === "identity" ? null : await installation.install("link", "consent");
    return html(
      pages.wrongUser({
        expected: expected?.email,
        signOut: `${ends.dash.replace(/\/?$/, "/")}logout`,
        again: again?.nonce ? `/i/${id}/consent?n=${again.nonce}` : null,
      }),
      403,
      spent,
    );
  }
  // the token goes to the installation; a sign-in only to say who they are gives it up
  const answer =
    pending.level === "full"
      ? await installation.install("consent", {
          token: access.token,
          expiresAt: access.expiresAt,
          scope: access.scope,
          wants: { telemetry: pending.telemetry === true, cloudflare: pending.cloudflare === true },
          cloud: env.CLOUD_KEY ? { keys: await trustOf(env), origin: url.origin } : null,
        })
      : await giveUp();
  if (answer?.refused)
    return html(pages.message("Nothing to connect", answer.refused.error), 409, spent);
  const session = await installation.install("openSession");
  const cookie = installCookie(url, id);
  const next = SIGNED_IN_KINDS.includes(pending.next) ? pending.next : "connected";
  return redirect(
    `/i/${id}/${next}`,
    `${cookie.name}=${session.value}; ${cookie.attributes}; Max-Age=${session.maxAge}`,
    spent,
  );
}

// ── the session: `s:<id>` is who the person is, `t:<id>` is the token (cloudflare-access.js) ──

/** A call needs Cloudflare and the sign-in has no token that works: the page asks to connect again. */
class NotConnected extends Error {}

const sessionId = (request, url) => cookieIn(request, cookieOf(url, "sid").name);
/** The session with its token, if it still has one: `{ ...who, token, expiresAt }`. */
async function loadSession(env, id) {
  const [who, access] = await Promise.all([
    env.SESSIONS.get(`s:${id}`),
    env.SESSIONS.get(`t:${id}`),
  ]);
  if (!who) return null;
  const { token, expiresAt } = JSON.parse(access || "{}");
  return { ...JSON.parse(who), ...(token && Date.now() < expiresAt && { token, expiresAt }) };
}
/** Writes who the person is. The token is never written here.
 *  @param {any} env
 *  @param {string} id
 *  @param {{ token?: string, expiresAt?: number, until: number, [fact: string]: any }} session */
function saveSession(env, id, { token, expiresAt, ...who }) {
  return env.SESSIONS.put(`s:${id}`, JSON.stringify(who), {
    expirationTtl: Math.max(60, Math.ceil((who.until - Date.now()) / 1000)),
  });
}
/** Ends the sign-in `id`: its two records go, and the access to Cloudflare it still held is
 *  REVOKED AT CLOUDFLARE, not only forgotten here. Answers what became of that access: "ended"
 *  (Cloudflare revoked it), "kept" (Cloudflare did not confirm: the token ends by itself within
 *  the hour), or "none" (the sign-in held no token: it ran out, or a deploy run took it and revokes
 *  it at its own end). A token is revoked here only after `claimToken` gave it to this end: KV
 *  can still show the token of a run that works with it now. */
async function endSession(env, id) {
  if (!id) return "none";
  const key = `t:${id}`;
  const held = JSON.parse((await env.SESSIONS.get(key)) || "null");
  await Promise.all([env.SESSIONS.delete(`s:${id}`), env.SESSIONS.delete(key)]);
  if (!held?.token || !(await claimToken(env, id))) return "none";
  const answer = await revoke({
    token: held.token,
    clientId: env.CLIENT_ID,
    clientSecret: env.CLIENT_SECRET,
    revokeUrl: endpointsOf(env).revoke,
    fetch: cfFetch(env),
  });
  console.log(
    JSON.stringify({
      message: `A sign-in ended. Cloudflare ${answer.ok ? "revoked" : "did NOT revoke"} its access (${answer.status}).`,
      revoke: answer.status,
    }),
  );
  return answer.ok ? "ended" : "kept";
}

// ── the API the page calls ──────────────────────────────────────────────────────────────────────

async function api(url, request, CF, session, id, env) {
  const calls = [];
  const reply = (value, status = 200) => json({ ...value, cloudflare: calls }, status);
  const send = (method, path, body, extra) =>
    cfFetch(env)(`${CF}${path}`, {
      method,
      headers: {
        authorization: `Bearer ${session.token}`,
        ...(body && { "content-type": "application/json" }),
        ...extra,
      },
      body: body ? JSON.stringify(body) : undefined,
    });
  const cf = async (method, path, body, extra = {}) => {
    if (!session.token) throw new NotConnected("the access to Cloudflare ended");
    const res = await send(method, path, body, extra);
    // Cloudflare also answers 401 for a product the plan lacks: the token is over only when /user refuses it too
    if (res.status === 401 && (path === "/user" || (await send("GET", "/user")).status === 401))
      throw new NotConnected("Cloudflare ended the access");
    const data = await res.json().catch(() => ({ success: false }));
    calls.push({
      method,
      path,
      body,
      status: res.status,
      success: !!data.success,
      errors: data.errors || [],
    });
    return { status: res.status, ...data };
  };
  const body = JSON_BODY.test(request.headers.get("content-type") || "")
    ? await request.json().catch(() => ({}))
    : {};
  const q = (name) => url.searchParams.get(name) || body[name] || "";
  const account = q("account");
  const registrar = q("mode") === "production" ? "registrar" : "registrar-sandbox";
  const needAccount = () => {
    if (!ACCOUNT.test(account)) throw new Error("choose an account first");
  };
  const needDomain = (domain) => {
    if (!DOMAIN.test(domain)) throw new Error(`${domain || "that"} is not a domain name`);
  };
  /** The account is one of the person's, as Cloudflare listed them at the sign-in: for the calls
   *  that work with no token. */
  const needOwnAccount = () => {
    needAccount();
    if (!(session.accounts || []).some((a) => a.id === account))
      throw new Error("that account is not one of yours");
  };
  /** The run of the stack on a zone, and its name. The name is made from the zone's (`nameOf`),
   *  unless the zone was seen served by a stack of another name (`servedNow`): a stack deployed
   *  from a computer has the name that its config gave it. */
  const runOf = async (zone) => {
    needOwnAccount();
    needDomain(zone);
    const kept = await env.SESSIONS.get(`stack:${account}:${zone}`);
    const name = kept && STACK_NAME.test(kept) ? kept : nameOf(zone);
    return { name, run: env.DEPLOYER.getByName(`${account}:${name}`) };
  };
  /** The name of the stack that serves a zone now, as the zone's routes say with the person's
   *  token (deployments.js `servedBy`); null when no stack serves it, or with no token. A name
   *  that is not the one made from the zone's is kept, for `runOf`: Cloudflare gives a zone's
   *  routes for that zone's own hostnames alone, so a route of `zone` names a Worker of `zone`. */
  let routesSeen = [];
  const servedNow = async (zone, zoneId) => {
    needOwnAccount();
    needDomain(zone);
    if (!session.token || !ACCOUNT.test(zoneId)) return null;
    const routes = await cf("GET", `/zones/${zoneId}/workers/routes`).catch(() => null);
    if (!routes?.success) return null;
    routesSeen = routes.result || [];
    const name = servedBy(zone, routes.result);
    if (!name) return null;
    if (name === nameOf(zone)) await env.SESSIONS.delete(`stack:${account}:${zone}`);
    else await env.SESSIONS.put(`stack:${account}:${zone}`, name);
    return name;
  };

  switch (`${request.method} ${url.pathname}`) {
    case "GET /api/me": {
      // With a token: ask Cloudflare, and keep the answer in the session. With none: the kept
      // answer, so the person still sees their deploy and their last screen.
      let errors = [];
      /** The accounts Cloudflare lists for this access now; null when it was not asked.
       *  @type {{ id: string, name: string }[] | null} */
      let listed = null;
      if (session.token) {
        const [user, accounts, zones] = await Promise.all([
          cf("GET", "/user"),
          cf("GET", "/accounts?per_page=50"),
          // how many domains this access reads: the words on the wait for "Your deployments"
          (session.level || "full") === "full" ? cf("GET", "/zones?per_page=1") : null,
        ]);
        errors = [...(user.errors || []), ...(accounts.errors || [])];
        if (user.result)
          session.user = {
            id: user.result.id,
            email: user.result.email,
            name: [user.result.first_name, user.result.last_name].filter(Boolean).join(" "),
          };
        if (accounts.success) {
          session.accounts = (accounts.result || []).map((a) => ({ id: a.id, name: a.name }));
          listed = session.accounts;
        }
        if (zones?.success) session.domains = zones.result_info?.total_count ?? null;
        await saveSession(env, id, session);
      } else if (!session.user) throw new NotConnected("the access to Cloudflare ended");
      // The account this page made for them, so that a new tab offers it instead of making
      // another. Once Cloudflare lists it for a full consent it is connected, and the record has
      // done its job: kept, it would bring that account back to every new tab of theirs for a
      // month, even when they want to make another.
      const createdKey = session.user?.id ? `created:${session.user.id}` : null;
      let created = createdKey ? JSON.parse((await env.SESSIONS.get(createdKey)) || "null") : null;
      if (
        created &&
        (session.level || "full") === "full" &&
        listed?.some((a) => a.id === created.id)
      ) {
        await env.SESSIONS.delete(createdKey);
        created = null;
      }
      const granted = new Set(
        String(session.scope || "")
          .split(/\s+/)
          .filter(Boolean),
      );
      return reply({
        connected: !!session.token,
        level: session.level || "full",
        // this access may turn a stack's telemetry on, or give its mind a Cloudflare connection:
        // the next deploy or update does
        telemetry: session.telemetry === true && telemetryGranted(session.scope),
        cloudflareToken: session.cloudflare === true && cloudflareTokenGranted(session.scope),
        // what Cloudflare granted, against what we asked and need (people can decline optional
        // permissions); a scope of WIDER that is not there stops nothing, so it is not said
        missing: granted.size
          ? String(session.requested || "")
              .split(/\s+/)
              .filter((x) => x && !granted.has(x) && (NEEDED.includes(x) || x === SANDBOX_SCOPE))
          : [],
        user: session.user
          ? {
              email: session.user.email,
              name: session.user.name,
              // the name of an account the Cloud makes for them, and its workers.dev address
              accountName: iterateNameOf(session.user.email),
            }
          : null,
        accounts: session.accounts || [],
        domains: session.domains ?? null,
        created,
        errors,
      });
    }
    case "POST /api/account": {
      const name =
        String(body.name || "")
          .trim()
          .slice(0, 60) ||
        iterateNameOf(session.user?.email) ||
        "iterate";
      // Cloudflare requires one Idempotency-Key per creation; a retry of the same attempt reuses it
      const key = /^[A-Za-z0-9_-]{8,64}$/.test(String(body.key || ""))
        ? String(body.key)
        : randomId();
      const answer = await cf(
        "POST",
        "/accounts",
        { name, standalone: true },
        { "idempotency-key": key },
      );
      const made = answer.result && { id: answer.result.id, name: answer.result.name };
      if (made) {
        session.accounts = [...(session.accounts || []), made];
        await saveSession(env, id, session);
        // remembered against the person, not the tab or the session: each consent starts a new session
        const user = await cf("GET", "/user");
        if (user.result?.id)
          await env.SESSIONS.put(`created:${user.result.id}`, JSON.stringify(made), {
            expirationTtl: CREATED_TTL,
          });
      }
      return reply(
        { account: made, errors: answer.errors || [] },
        answer.success ? 200 : answer.status,
      );
    }
    case "POST /api/account/forget": {
      // they backed out of the account this page made, or made another: a new tab doesn't offer it
      // again. The key GET /api/me reads, so this works after Cloudflare's access has ended too.
      const userId = session.user?.id;
      if (userId) await env.SESSIONS.delete(`created:${userId}`);
      return reply({ forgotten: !!userId });
    }
    case "GET /api/readiness": {
      needAccount();
      const [subs, r2, containers, credit, sub] = await Promise.all([
        cf("GET", `/accounts/${account}/subscriptions`),
        cf("GET", `/accounts/${account}/r2/buckets?per_page=1`),
        cf("GET", `/accounts/${account}/containers/applications`),
        // AI Gateway's billing answers whether a card is on file: { has_default_payment_method,
        // payment_method: { brand, last4 } } (seen 10 Nov 2026)
        cf("GET", `/accounts/${account}/ai-gateway/billing/credit-balance`),
        // a new account has no workers.dev subdomain yet: 10007 (workers-sdk deploy-helpers subdomain.ts)
        cf("GET", `/accounts/${account}/workers/subdomain`),
      ]);
      const plans = subs.success
        ? (subs.result || []).map((p) => p.rate_plan?.id).filter(Boolean)
        : null;
      // 10042 / "not enabled|entitled|subscribed" / 402: off; any other refusal: Cloudflare did not say
      const enabled = (a) => {
        if (a.success) return true;
        const text = JSON.stringify(a.errors || []);
        // Containers on a Free account: 401, "...requires the Workers Paid plan" (seen 10 Nov 2026)
        if (
          /10042/.test(text) ||
          /not (enabled|entitled|subscribed)|requires the Workers Paid plan|do not have access to Cloudflare Containers/i.test(
            text,
          ) ||
          a.status === 402
        )
          return false;
        return null;
      };
      const ready = { r2: enabled(r2), containers: enabled(containers) };
      const c = credit.success ? credit.result || {} : null;
      return reply({
        plans,
        workersPaid: plans ? plans.includes("workers_paid") : ready.containers,
        ...ready,
        paymentMethod: c ? !!c.has_default_payment_method : null,
        card: c?.payment_method
          ? { brand: c.payment_method.brand || "card", last4: c.payment_method.last4 || "" }
          : null,
        workersDev:
          sub.success && sub.result?.subdomain
            ? sub.result.subdomain
            : JSON.stringify(sub.errors || []).includes("10007")
              ? false
              : null,
      });
    }
    case "POST /api/subdomain": {
      needAccount();
      // with no name: the account's own name from their email (account-name.js), then that name
      // with a hash; each one only while Cloudflare says the one before is taken (10031)
      const auto = !body.name;
      const names = body.name
        ? [String(body.name).toLowerCase()]
        : workersDevNamesOf(session.user?.email);
      if (!names.length) throw new Error("no name for a workers.dev address");
      for (const name of names)
        if (!/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/.test(name))
          throw new Error(`${name} can't be a workers.dev name`);
      let answer;
      let taken = false;
      const tried = [];
      for (const name of names) {
        tried.push(name);
        // the availability check, as wrangler and the dashboard do it: 10031 taken, 10032 free.
        // Both come as success: false, and both are its answer, not a refusal.
        if (auto) {
          answer = await cf("GET", `/accounts/${account}/workers/subdomains/${name}`);
          const said = JSON.stringify(answer.errors || []);
          if (/1003[12]/.test(said)) calls[calls.length - 1].expected = true;
          taken = said.includes("10031");
          if (taken) continue;
        }
        answer = await cf("PUT", `/accounts/${account}/workers/subdomain`, { subdomain: name });
        // 10031: someone else has that name
        taken = JSON.stringify(answer.errors || []).includes("10031");
        if (answer.success)
          return reply({ subdomain: answer.result?.subdomain || name, taken: false, errors: [] });
        if (!taken) break;
      }
      return reply({ subdomain: null, taken, tried, errors: answer.errors || [] }, 409);
    }
    // ── "Erase and replace": what is on a domain and of an earlier iterate, for the warning a
    // person agrees to (container/takeover.mjs). It reads, and changes nothing. ──
    case "GET /api/erase": {
      const zone = q("zone").toLowerCase();
      const kept = keptOf(zone, url.hostname);
      if (kept) {
        const { name } = await runOf(zone);
        return reply({ zone, name, digest: null, items: [], unread: [], refusals: [kept] });
      }
      needOwnAccount();
      needDomain(zone);
      const zoneId = (await cf("GET", `/zones?name=${zone}&account.id=${account}`)).result?.[0]?.id;
      if (!zoneId) return reply({ error: `${zone} is not in this Cloudflare account.` }, 404);
      // the list is of the stack that serves the zone, whatever its name
      await servedNow(zone, zoneId);
      const { name } = await runOf(zone);
      const found = await inventoryOf({ cf, accountId: account, zoneId, zone, name });
      // the page shows the list, not the calls that read it
      calls.length = 0;
      return reply({
        zone,
        zoneId,
        name,
        digest: found.digest,
        items: found.items.map(({ kind, id, name, group, text, act }) => ({
          kind,
          id,
          name,
          group,
          text,
          act,
        })),
        unread: found.unread,
        refusals: refusalsOf(found),
      });
    }
    // ── the deploy run (deploy-run.js): the stack of one zone, in the person's account ──
    case "POST /api/deploy": {
      const zone = String(body.zone || "").toLowerCase();
      const zoneId = String(body.zoneId || "");
      if (!ACCOUNT.test(zoneId)) throw new Error("no zone");
      if (PLATFORM_HOST.test(zone))
        throw new Error(
          `iterate does not deploy on ${zone}: a name that starts with "iterate." is the platform's host of ${zone.slice("iterate.".length)}. Use another domain.`,
        );
      // THE ZONE'S ID IS THE NAMED ZONE'S, IN THIS ACCOUNT, as Cloudflare says with the person's
      // token: the run reads, deploys and erases by the id, and the person agreed to the name. A
      // made request with another zone's id would otherwise work on that zone under this name.
      // With no token in the session nothing is read and no run starts (below).
      if (session.token) {
        needOwnAccount();
        needDomain(zone);
        const named = await cf("GET", `/zones?name=${zone}&account.id=${account}`);
        if (!named?.success) throw new Error(`Cloudflare did not say whether ${zone} is yours`);
        if (named.result?.[0]?.id !== zoneId)
          return reply({ error: `${zone} is not a domain of this Cloudflare account` }, 400);
      }
      const served = await servedNow(zone, zoneId);
      const { name, run } = await runOf(zone);
      // "Erase and replace": the name of the list the person saw (GET /api/erase), and the
      // domain's name as they typed it. The run erases that list and no other.
      const erase = String(body.erase || "");
      if (erase) {
        if (!/^[0-9a-f]{24}$/.test(erase)) throw new Error("no list of what is erased");
        if (
          String(body.typed || "")
            .trim()
            .toLowerCase() !== zone
        )
          throw new Error(`type ${zone} to agree to the erase`);
        const kept = keptOf(zone, url.hostname);
        if (kept) throw new Error(kept);
        // a domain that serves another person's Worker is never erased: the run's erase refuses
        // the same (container/takeover.mjs), and here no run starts
        const other = routesSeen.find((route) => outsideOf(namesOf(name), route.script));
        if (other)
          throw new Error(
            `${zone} also serves the Worker ${other.script}, which is not iterate's. iterate never erases a domain that serves another Worker.`,
          );
      }
      const now = await run.status();
      if (now.status === "running") return reply({ state: now, connected: !!session.token });
      // An erase that stopped can have erased a part: a deploy over the rest would build on a
      // record of things that are gone. The person looks at the list again and erases again.
      if (!erase && now.status === "failed" && now.erase && !now.erased)
        return reply(
          { error: `The erase of ${zone} did not finish. Look at the list again, then erase.` },
          409,
        );
      // After a success it is an update: no owner and no config from here, the stack keeps its own.
      // An update that the owner asked for to get back in (they lost every passkey) also makes
      // the owner's ticket (first-owner.js). No other update makes one.
      const before = JSON.parse((await env.SESSIONS.get(`dep:${account}:${name}`)) || "null");
      // A stack that serves the zone and that this Cloud never deployed with an owner (it was
      // deployed from a computer, or by another Cloud): "Update iterate" in "Your deployments"
      // updates it from the config that the stack keeps, with its members. The Cloud knows no
      // owner of it, so it makes no ticket and gives the run no config. The wizard's Deploy step
      // names an owner: that stays a run with a config, which the run sets aside for the
      // stack's own (container/run.sh `keep_stored_config`).
      const adopted = !erase && served === name && !before?.owner && !body.email;
      // "Update anyway" names the commit that the person saw on the card (container/run.sh
      // `not_unknown_stack`). It makes the run an update whatever this Cloud's last run there
      // said (deployments.js `replaceable`).
      const anyway =
        !erase &&
        served === name &&
        /^[0-9a-f]{40}$/.test(String(body.anyway || "")) &&
        body.anyway;
      const update =
        !erase && (adopted || (!!before?.owner && (now.status === "succeeded" || !!anyway)));
      const email = adopted ? null : update ? before.owner : String(body.email || "").trim();
      const recover = update && !adopted && body.recover === true;
      if (!adopted && !/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email || ""))
        throw new Error("no owner email");
      // A run that makes the owner's ticket hands it to the person who started it, and to nobody
      // else: with no id of that person, nobody could take it, and the owner would have no way in.
      if ((!update || recover) && !session.user?.id)
        throw new NotConnected("iterate could not read who you are at Cloudflare");
      // The token leaves the session here and goes to the run alone, which revokes it at its end.
      // A session with no token read nothing above (the zone's id is unchecked): it starts no run.
      if (!session.token)
        throw new NotConnected("no access to Cloudflare: connect Cloudflare again");
      let access;
      try {
        access = await takeToken(env, id);
      } catch (error) {
        throw new NotConnected(String(error?.message || error));
      }
      const giveUp = () =>
        revoke({
          token: access.token,
          clientId: env.CLIENT_ID,
          clientSecret: env.CLIENT_SECRET,
          revokeUrl: endpointsOf(env).revoke,
          fetch: cfFetch(env),
        });
      try {
        const { began, state } = await run.start({
          accountId: account,
          zone,
          zoneId,
          name,
          ownerEmails: update ? undefined : [email],
          recoverOwner: recover ? email : undefined,
          // no trusted client: a new stack trusts no outside app to sign people in. Its own
          // hostnames are the mind's.
          // what a deployment needs to work with this Cloud: its key, and where its clients are.
          // The pretend Worker has no Cloud.
          keys: env.CLOUD_KEY ? await trustOf(env) : undefined,
          cloudOrigin: env.CLOUD_KEY ? url.origin : undefined,
          token: access.token,
          tokenExpiresAt: access.expiresAt,
          erase: erase || undefined,
          anyway: anyway || undefined,
          // the stack's own telemetry, and its mind's Cloudflare connection, each when the
          // person's consent was the one for it
          telemetry: session.telemetry === true && telemetryGranted(session.scope),
          cloudflareToken: session.cloudflare === true && cloudflareTokenGranted(session.scope),
        });
        // ANOTHER REQUEST BEGAN THIS RUN between the look above and here. It is that person's
        // run: their row stays (the first owner's ticket goes to who is named there, GET
        // /api/deploy), and this request's token, which no run took, is given up now.
        if (!began) {
          await giveUp();
          return reply({ state, connected: false });
        }
        await env.SESSIONS.put(
          `dep:${account}:${name}`,
          JSON.stringify({
            zone,
            owner: email,
            // who started this run: the first owner's ticket goes to that person alone (GET /api/deploy)
            by: session.user?.id,
            at: Date.now(),
            // what the Cloud knows of the deployment is of the one before the erase (GET /api/deploy)
            ...((erase || before?.erased) && { erased: true }),
            ...(adopted && { adopted: true }),
          }),
        );
        return reply({ state, owner: email, connected: false });
      } catch (error) {
        // a run that did not start gives the token up here: nothing else holds it
        await giveUp();
        throw error;
      }
    }
    case "GET /api/deploy": {
      const zone = q("zone").toLowerCase();
      const { name, run } = await runOf(zone);
      const row = JSON.parse((await env.SESSIONS.get(`dep:${account}:${name}`)) || "null");
      // status(true): this answer is shown to the person who started the run, so it may carry the
      // first owner's ticket. Every member of the account may watch the run, a read-only one too:
      // the ticket makes its holder the deployment's owner, so no other member gets it.
      const state = await run.status(Boolean(row?.by) && row.by === session.user?.id);
      // A run that succeeded ends in the Cloud knowing the deployment's key (access.js). The
      // deployment trusts the Cloud's key from its config, so nobody has to consent.
      // `enrolled` is false until that worked: a new address can take a moment to answer, so the
      // page asks again for a while (null: this Cloud has no key, and nothing to wait for).
      // After "Erase and replace" the deployment is a new one, with a new key: the Cloud forgets
      // the one before, once, and then gets to know this one.
      if (state.status === "succeeded" && row?.erased) {
        await forget(env, zone);
        const { erased: _, ...rest } = row;
        await env.SESSIONS.put(`dep:${account}:${name}`, JSON.stringify(rest));
      }
      /** @type {boolean | null} */
      let enrolled = null;
      if (state.status === "succeeded" && env.CLOUD_KEY)
        enrolled =
          !!(await env.SESSIONS.get(`enrolled:${zone}`)) ||
          !!(await enrol(env, url.origin, zone).catch(() => null))?.ok;
      // owner: the address that signs in to the deployment, as the person gave it at the start
      return reply({ state, enrolled, owner: row?.owner || null });
    }
    case "GET /api/kept": {
      // Every record iterate's Cloud keeps about this person and this deployment: the session's
      // (here) and the run's (its own storage). The page shows them as they are.
      const zone = q("zone").toLowerCase();
      const { name, run } = await runOf(zone);
      const KV = "Workers KV, the installer's records";
      const [created, started, enrolled, stack] = await Promise.all([
        session.user?.id && env.SESSIONS.get(`created:${session.user.id}`),
        env.SESSIONS.get(`dep:${account}:${name}`),
        env.SESSIONS.get(`enrolled:${zone}`),
        env.SESSIONS.get(`stack:${account}:${zone}`),
      ]);
      return reply({
        records: [
          {
            where: KV,
            key: "s:<your session>",
            what: `Who you are at Cloudflare: your email, your name, and the ids and names of your accounts. No token. It ends by itself at ${utc(session.until)}.`,
          },
          ...(session.token
            ? [
                {
                  where: KV,
                  key: "t:<your session>",
                  what: `Cloudflare's access token of this sign-in. Cloudflare ends it, and KV deletes it, at ${utc(session.expiresAt)}. A deploy takes it out when it starts.`,
                },
              ]
            : []),
          ...(created
            ? [
                {
                  where: KV,
                  key: "created:<your Cloudflare user id>",
                  what: "The id and the name of the account this page made for you, so that a new tab does not offer to make another. It goes once you give iterate access to that account, or when you make another.",
                },
              ]
            : []),
          ...(started
            ? [
                {
                  where: KV,
                  key: `dep:<your account>:${name}`,
                  what: "That a deploy run exists for this account and this domain, the address that signs in to it, the Cloudflare id of the person who started it, and when it started. No token.",
                },
              ]
            : []),
          ...(stack
            ? [
                {
                  where: KV,
                  key: `stack:<your account>:${zone}`,
                  what: `The name of the iterate that serves this domain in your account, ${stack}, as your domain's Workers routes said it. iterate Cloud did not choose that name.`,
                },
              ]
            : []),
          ...(enrolled
            ? [
                {
                  where: KV,
                  key: `enrolled:${zone}`,
                  what: "Your deployment's public key, so that iterate Cloud and your deployment know each other. A public key opens nothing.",
                },
              ]
            : []),
          ...(await run.kept()).records,
        ],
      });
    }
    case "POST /api/suggest": {
      needAccount();
      const names = candidatesOf(String(body.name || ""), String(body.words || ""));
      if (names.length === 0) return reply({ domains: [] });
      const checked = await cf("POST", `/accounts/${account}/${registrar}/domain-check`, {
        domains: names.slice(0, 20),
      });
      return reply({ domains: domainsOf(checked), errors: checked.errors || [] });
    }
    case "GET /api/search": {
      needAccount();
      const found = await cf(
        "GET",
        `/accounts/${account}/${registrar}/domain-search?q=${encodeURIComponent(q("q"))}`,
      );
      return reply({ domains: domainsOf(found), errors: found.errors || [] });
    }
    case "POST /api/register": {
      needAccount();
      const domain = String(body.domain || "");
      needDomain(domain);
      if (registrar === "registrar" && body.confirm !== domain)
        throw new Error("a real purchase needs the domain typed again");
      const answer = await cf("POST", `/accounts/${account}/${registrar}/registrations`, {
        domain_name: domain,
        // oxlint-disable-next-line iterate/simple-truthiness-check -- Cloudflare's registrar takes the account's own contacts when the request names none: an empty value is not the same
        ...(body.contacts && { contacts: body.contacts }),
      });
      return reply(answer, answer.status);
    }
    case "GET /api/registrar/contact": {
      // An account that already holds domains at Cloudflare has a registrant contact on file:
      // a registration without contacts uses it. A new account has none (10000 "No registrant contact").
      needAccount();
      if (registrar !== "registrar") return reply({ onFile: false, domains: 0 });
      const answer = await cf("GET", `/accounts/${account}/registrar/domains?per_page=1`);
      const domains = answer.result_info?.total_count ?? (answer.result || []).length;
      return reply({ onFile: domains > 0, domains });
    }
    case "GET /api/registration": {
      needAccount();
      needDomain(q("domain"));
      const answer = await cf(
        "GET",
        `/accounts/${account}/${registrar}/registrations/${q("domain")}/registration-status`,
      );
      return reply(answer, answer.status);
    }
    case "GET /api/pages": {
      // Which pages of a deployment answer now (deployments.js `pagesNow`), for the person's page
      // of a run that kept no record of them. Asked only of a domain that this Cloud deployed in
      // an account of the session: the run's own record says so, never the request alone.
      const zone = q("zone").toLowerCase();
      const state = await (await runOf(zone)).run.status();
      if (state.status !== "succeeded") return reply({ pages: null });
      const pages = await pagesNow(
        zone,
        // CF_SITE is set on the pretend deployment only, whose stand-ins the pretend Cloudflare
        // answers for. It asks for the session's token, which a finished run has taken: with
        // none, no stand-in is seen, and the run's own record is what the page has.
        env.CF_SITE
          ? async (host) =>
              (await cf("GET", `/pretend/answers?host=${host}`).catch(() => null))?.result
                ?.answers === true
          : undefined,
      );
      return reply({ pages });
    }
    case "GET /api/deployments": {
      // "Your deployments" (deployments.js): read now, from the person's accounts, with their token
      const timing = { accounts: [] };
      const found = await deploymentsOf({
        cf,
        nameOf,
        host: url.hostname,
        accounts: session.accounts || [],
        env,
        commits: stackCommits(),
        timing,
        // CF_SITE is set on the pretend deployment only: its deployments are stand-ins
        standIn: env.CF_SITE
          ? async (host) =>
              (await cf("GET", `/pretend/answers?host=${host}`)).result?.answers === true
          : undefined,
      });
      // where the wait of the list goes: counts and milliseconds alone, no name and no id
      console.log(JSON.stringify({ message: "deployments read", ...timing }));
      return reply(found);
    }
    case "GET /api/zones": {
      needAccount();
      // every page (Cloudflare gives 50 at most): an account can hold more domains than one page
      const { zones, errors } = await zonesOf(cf, account);
      return reply({ zones: zones.map(zoneOf), errors });
    }
    case "GET /api/zone": {
      needAccount();
      needDomain(q("name"));
      const answer = await cf("GET", `/zones?name=${q("name")}&account.id=${account}`);
      return reply({ zone: zoneOf(answer.result?.[0]), errors: answer.errors || [] });
    }
    case "POST /api/zone": {
      needAccount();
      needDomain(q("name"));
      const answer = await cf("POST", "/zones", {
        name: q("name"),
        account: { id: account },
        type: "full",
      });
      return reply(
        { zone: zoneOf(answer.result), errors: answer.errors || [] },
        answer.success ? 200 : answer.status,
      );
    }
    case "PUT /api/zone/check": {
      const id = q("id");
      if (!ACCOUNT.test(id)) throw new Error("no zone");
      await cf("PUT", `/zones/${id}/activation_check`);
      const answer = await cf("GET", `/zones/${id}`);
      return reply({ zone: zoneOf(answer.result), errors: answer.errors || [] });
    }
  }
  return reply({ error: "no such call" }, 404);
}

const zoneOf = (z) =>
  z && { id: z.id, name: z.name, status: z.status, nameServers: z.name_servers || [] };

/** The results of a search or a check, in one shape. */
function domainsOf(answer) {
  const list = answer.result?.domains || (Array.isArray(answer.result) ? answer.result : []);
  return list.map((d) => ({
    name: d.name,
    available: d.registrable !== false && d.available !== false,
    price: d.pricing?.registration_cost || null,
    renewal: d.pricing?.renewal_cost || null,
    currency: d.pricing?.currency || "USD",
    tier: d.tier || null,
    reason: d.reason || null,
  }));
}

// ── small helpers ───────────────────────────────────────────────────────────────────────────────

const randomId = () => base64url(crypto.getRandomValues(new Uint8Array(18)));
const base64url = (buf) =>
  btoa(String.fromCharCode(...new Uint8Array(buf)))
    .replace(/\+/g, "-")
    .replace(/\//g, "_")
    .replace(/=+$/, "");
const json = (value, status = 200) =>
  new Response(JSON.stringify(value), {
    status,
    headers: { "content-type": "application/json", "cache-control": "no-store" },
  });
const html = (body, status = 200, ...cookies) => {
  const headers = new Headers({
    "content-type": "text/html; charset=utf-8",
    "cache-control": "no-store",
    "content-security-policy":
      "default-src 'none'; style-src 'unsafe-inline'; form-action 'self'; frame-ancestors 'none'",
    "referrer-policy": "no-referrer",
  });
  for (const cookie of cookies) headers.append("set-cookie", cookie);
  return new Response(body, { status, headers });
};
const redirect = (location, ...cookies) => {
  const headers = new Headers({ location });
  for (const cookie of cookies) headers.append("set-cookie", cookie);
  return new Response(null, { status: 302, headers });
};

const utc = (ms) => `${new Date(ms).toISOString().slice(0, 16).replace("T", " ")} UTC`;

/** The stack's name, from its zone: `adalovelace.xyz` gives `adalovelace-xyz`. The stack's rule is
 *  a letter first, then letters, digits and dashes, 40 characters at most. */
function nameOf(zone) {
  const name = zone.toLowerCase().replace(/[^a-z0-9]+/g, "-");
  return (/^[a-z]/.test(name) ? name : `z-${name}`).slice(0, 40).replace(/-+$/, "");
}