iterate.com / cloud

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

cloud / internal-packages / installer / pretend / world.jsmain at aacbc74

// A PRETEND CLOUDFLARE, as one module: a "world" (one person's accounts, domains, tokens: plain
// JSON) and handle(world, request) → Response, which answers OAuth (consent page, token), the API
// calls the wizard makes, the dashboard pages it links to, and a control panel. Two hosts run it:
//   - test/fake-cloudflare.mjs: one world in memory, over Node http, for the end-to-end test
//   - pretend/worker.js: one world per email in a Durable Object, deployed, to try the flow by hand
// It answers the way the real Cloudflare did when we tried each call on 10 Nov 2026:
//   - an OAuth grant covers only the accounts ticked at consent; a new account needs consent again
//   - POST /accounts needs an Idempotency-Key, and a user's token
//   - /subscriptions refuses an OAuth token (403 10000); Containers answer for Workers Paid
//     (401 "... requires the Workers Paid plan"); R2 off is 403 10042
//   - a registration with no contact: 400 10000 "No registrant contact provided ..."
//   - with a contact but no payment method: 202, state "failed", error "billing_quote_failed"
// Names typed in the flow set off scenarios (SCENARIOS below lists them; the home page shows it).
import * as pages from "./pages.js";

export const hexId = () =>
  [...crypto.getRandomValues(new Uint8Array(16))]
    .map((b) => b.toString(16).padStart(2, "0"))
    .join("");
/** How long each wait of an "auto" world takes. */
const AUTO_MS = 20_000;
const cap = (s) => s.charAt(0).toUpperCase() + s.slice(1);

// ── a world ─────────────────────────────────────────────────────────────────────────────────────

const newAccount = (a) => ({
  paid: false,
  r2: false,
  card: !!a.paid,
  credit: 0,
  subdomain: null,
  ...a,
});

/** A world from its parts (the test gives them). Everything in it is JSON: it is stored as is. */
export function newWorld({ user, accounts = [], taken = [] }) {
  return {
    user: { id: "u".repeat(32), ...user },
    accounts: accounts.map((a) => newAccount({ subdomain: a.paid ? "ada-lovelace" : null, ...a })),
    codes: {}, // code -> { accounts, redirectUri, clientId, scope }
    tokens: {}, // access token -> { accounts, scope }
    takenSubdomains: ["ada", "iterate"],
    created: {}, // idempotency key -> account id
    zones: [], // { id, name, account, status, nameServers, pointed, at, hold }
    registrations: {}, // `${account}:${domain}` -> { polls, at, slow, failed }
    taken, // domain names nobody can register
    sites: {}, // domain -> { name, account, at }: where a pretend iterate is "live", from `at`
    requests: [], // the newest API calls, for the control panel
    tags: [],
  };
}

/** The world an email starts with: the part before "+" names the person, the tags after it set the state. */
export function worldFor(email, key) {
  const [local] = email.split("@");
  const [base, ...tags] = local.toLowerCase().split("+").filter(Boolean);
  const has = (t) => tags.includes(t);
  const words = (base || "you").split(/[._-]+/).filter(Boolean);
  const slug = words.join("-").replace(/[^a-z0-9-]/g, "") || "you";
  const ready = has("ready");
  const main = newAccount({
    id: hexId(),
    name: `${cap(email)}'s Account`,
    card: ready || has("card") || has("paid") || has("credit"),
    paid: ready || has("paid"),
    r2: ready || has("r2"),
    credit: ready || has("credit") ? 1000 : 0,
    subdomain: ready || has("workersdev") ? slug : null,
  });
  const world = newWorld({
    user: { id: key, email, first: cap(words[0]), last: words.slice(1).map(cap).join(" ") },
    accounts: [],
  });
  world.accounts = [main];
  world.tags = tags;
  const zone = (account, name, status, extra = {}) =>
    world.zones.push({
      id: hexId(),
      name,
      account,
      status,
      nameServers:
        status === "active"
          ? ["ada.ns.cloudflare.com", "bob.ns.cloudflare.com"]
          : ["kayleigh.ns.cloudflare.com", "nolan.ns.cloudflare.com"],
      pointed: status === "active",
      at: 0,
      ...extra,
    });
  const registered = (account, name) => {
    world.registrations[`${account}:${name}`] = { polls: 1, at: 0 };
    zone(account, name, "active");
  };
  // a chat installation that steps through each wait with nobody at the dashboard (AUTO_MS)
  if (has("auto")) registered(main.id, `${slug}-labs.com`);
  if (has("domains")) {
    registered(main.id, `${slug}-labs.com`);
    zone(main.id, `${slug}-notes.com`, "pending", { hold: true });
  }
  if (has("many")) {
    const acme = newAccount({
      id: hexId(),
      name: "Acme Inc",
      card: true,
      paid: true,
      r2: true,
      credit: 2500,
      subdomain: "acme",
    });
    const side = newAccount({ id: hexId(), name: "Side project", card: true });
    const old = newAccount({
      id: hexId(),
      name: "Old sandbox",
      card: true,
      paid: true,
      r2: true,
      subdomain: `${slug}-sandbox`,
    });
    world.accounts.push(acme, side, old);
    registered(acme.id, "acme-agents.com");
  }
  return world;
}

// ── answers ─────────────────────────────────────────────────────────────────────────────────────

const html = (body, status = 200) =>
  new Response(body, {
    status,
    headers: { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" },
  });
const json = (value, status = 200) =>
  new Response(JSON.stringify(value), {
    status,
    headers: { "content-type": "application/json", "cache-control": "no-store" },
  });
const redirect = (location, status = 302) => new Response(null, { status, headers: { location } });
const ok = (result, status = 200) =>
  json({ success: true, errors: [], messages: [], result }, status);
const fail = (status, code, message) =>
  json({ success: false, errors: [{ code, message }], messages: [], result: null }, status);

const price = (name) =>
  /premium/.test(name)
    ? "2400.00"
    : name.endsWith(".com")
      ? "10.46"
      : name.endsWith(".dev")
        ? "12.18"
        : name.endsWith(".xyz")
          ? "12.30"
          : "11.86";
const renewal = (name) => (name.endsWith(".xyz") && !/premium/.test(name) ? "11.20" : price(name));
const zoneOut = (z) => ({
  id: z.id,
  name: z.name,
  status: z.status,
  name_servers: z.nameServers,
  account: { id: z.account },
});

/** Has the registrar been pointed at Cloudflare? Someone said so, or enough time went by. */
const pointed = (z, now, after) =>
  z.pointed || (after != null && !z.hold && !/stuck/.test(z.name) && now - (z.at || 0) >= after);
/** What a deployment leaves in an account (a.existing: what the dashboard pages list), and the
 *  domain it answers on from `at` (the pretend deployer says so at the start of its run). */
export function recordDeployment(
  world,
  { account, name, domain, at, erased, commit },
  now = Date.now(),
) {
  const a = world.accounts.find((x) => x.id === account);
  if (!a || !name || !domain) return false;
  const ex = (a.existing ||= {});
  const add = (kind, n) => {
    ex[kind] = [...new Set([...(ex[kind] || []), n])];
  };
  for (const part of ["auth", "mind", "boundary"]) add("workers", `iterate-${name}-${part}`);
  add("r2", `iterate-${name}-files`);
  // erased: "Erase and replace" ran, so what else was on the domain is gone (onZone)
  world.sites[domain] = {
    name,
    account,
    at: at ?? now,
    ...(erased || world.sites[domain]?.erased ? { erased: true } : {}),
    // the commit of iterate that its boundary Worker names in a tag, when a deploy wrote one
    ...(commit ? { commit } : {}),
  };
  return true;
}

/** What "Erase and replace" reads on a zone (container/takeover.mjs): what a deployment left
 *  there, and what a domain in use has. The domain's name sets off the awkward cases, until an
 *  erase ran on it:
 *    …used…     a website's record and a mail record
 *    …locked…   those, and a Spectrum app, which iterate cannot remove
 *    …shared…   a route to another person's Worker: iterate never erases such a domain
 *  undefined: the pretend Cloudflare has no such list. */
function onZone(world, z, list) {
  const site = world.sites[z.name];
  const n = site && `iterate-${site.name}`;
  const inUse = /used|locked/.test(z.name) && !site?.erased;
  const id = (what) => `${what}${z.id}`.slice(0, 32);
  switch (list) {
    case "dns_records":
      return [
        ...(site
          ? [
              { id: id("a"), type: "AAAA", name: z.name, content: "100::", meta: {} },
              { id: id("b"), type: "AAAA", name: `*.${z.name}`, content: "100::", meta: {} },
              {
                id: id("c"),
                type: "MX",
                name: z.name,
                content: "route1.mx.cloudflare.net",
                meta: { email_routing: true, read_only: true },
              },
            ]
          : []),
        ...(inUse
          ? [
              {
                id: id("d"),
                type: "CNAME",
                name: `www.${z.name}`,
                content: "shops.example.net",
                meta: {},
              },
              {
                id: id("e"),
                type: "TXT",
                name: z.name,
                content: "v=spf1 include:_spf.example.net ~all",
                meta: {},
              },
            ]
          : []),
      ];
    case "workers/routes":
      return [
        ...(site
          ? [
              { id: id("a"), pattern: `${z.name}/*`, script: `${n}-boundary` },
              { id: id("b"), pattern: `*.${z.name}/*`, script: `${n}-boundary` },
            ]
          : []),
        ...(/shared/.test(z.name)
          ? [{ id: id("c"), pattern: `shop.${z.name}/*`, script: "shop-of-ada" }]
          : []),
      ];
    case "email/routing":
      return { enabled: !!site, status: site ? "ready" : "unconfigured" };
    case "email/routing/rules":
      return site
        ? [
            {
              tag: id("a"),
              enabled: true,
              matchers: [{ type: "all" }],
              actions: [{ type: "worker", value: [`${n}-boundary`] }],
            },
          ]
        : [];
    case "spectrum/apps":
      return /locked/.test(z.name) && !site?.erased
        ? [{ id: id("a"), dns: { name: `ssh.${z.name}` } }]
        : [];
    case "bot_management":
      return { fight_mode: false };
    case "custom_hostnames":
    case "load_balancers":
    case "waiting_rooms":
    case "email/sending/subdomains":
    case "rulesets":
    case "pagerules":
    case "snippets":
    case "access/apps":
      return [];
  }
  return undefined;
}

/**
 * One request to the pretend Cloudflare.
 * opts: mint() → a new token (the Worker prefixes the world's key); now; testControls (/_test/*);
 *       quoteNeeds "card" | "paid" (what a registration's billing quote wants: the test says "paid");
 *       activateAfter (ms until a zone from elsewhere turns active by itself, or null: never);
 *       wizard (the wizard's address, for links back, and the only place consent sends a person
 *       to when it is set); deployed (there is a sign-in to switch); reset() → a fresh world's fields.
 */
export async function handle(world, request, opts = {}) {
  const url = new URL(request.url);
  const method = request.method;
  const now = opts.now ?? Date.now();
  const mint = opts.mint || hexId;
  const after = opts.activateAfter ?? null;
  const raw = method === "GET" || method === "HEAD" ? "" : await request.text();
  const body = () => {
    try {
      return JSON.parse(raw || "{}");
    } catch {
      return {};
    }
  };
  const form = () => new URLSearchParams(raw);
  const account = (aid) => world.accounts.find((a) => a.id === aid);
  const isTaken = (name) => world.taken.includes(name) || /taken/.test(name);
  const view = {
    world,
    wizard: opts.wizard || null,
    deployed: !!opts.deployed,
    now,
    after,
    pointed: (z) => pointed(z, now, after),
  };
  const fromWizard = (uri) => !opts.wizard || String(uri || "").startsWith(`${opts.wizard}/`);
  const stranger = () =>
    html(
      pages.missing(
        view,
        "This sign-in didn't come from the wizard",
        "The pretend Cloudflare sends people back to its own wizard only.",
      ),
      400,
    );
  const path = url.pathname;

  // ── OAuth ──
  if (path === "/oauth2/auth")
    return fromWizard(url.searchParams.get("redirect_uri"))
      ? html(pages.consent(view, url.searchParams))
      : stranger();
  if (path === "/oauth2/consent" && method === "POST") {
    const p = form();
    if (!fromWizard(p.get("redirect_uri"))) return stranger();
    const asked = (p.get("scope") || "").split(" ").filter(Boolean);
    const identityOnly = asked.every((x) => x === "user-details.read");
    if (!identityOnly && p.getAll("account").length === 0)
      return html(pages.consent(view, p, "Select at least one account."));
    // a person can untick permissions (not who they are)
    const granted = p.has("grants")
      ? asked.filter((x) => x === "user-details.read" || p.getAll("grant").includes(x))
      : asked;
    const code = mint();
    world.codes[code] = {
      accounts: p.getAll("account"),
      redirectUri: p.get("redirect_uri"),
      clientId: p.get("client_id"),
      scope: granted.join(" "),
    };
    return redirect(
      `${p.get("redirect_uri")}?${new URLSearchParams({ code, state: p.get("state") || "" })}`,
    );
  }
  if (path === "/oauth2/token" && method === "POST") {
    const f = Object.fromEntries(form());
    if (f.client_secret !== "fake-secret") return json({ error: "invalid_client" }, 401);
    const grant = world.codes[f.code];
    if (!grant || f.redirect_uri !== grant.redirectUri)
      return json({ error: "invalid_grant" }, 400);
    delete world.codes[f.code];
    const token = mint();
    world.tokens[token] = { accounts: grant.accounts, scope: grant.scope };
    return json({
      access_token: token,
      token_type: "bearer",
      expires_in: 3600,
      scope: grant.scope,
    });
  }
  // RFC 7009: the token stops working; a token nobody knows is no error
  if (path === "/oauth2/revoke" && method === "POST") {
    const f = Object.fromEntries(form());
    if (f.client_secret !== "fake-secret") return json({ error: "invalid_client" }, 401);
    delete world.tokens[f.token];
    return json({});
  }

  // ── the dashboard pages the wizard links to ──
  const dash = /^\/dash\/([0-9a-f]{32})(?:\/(.*))?$/.exec(path);
  if (dash) {
    const a = account(dash[1]);
    const page = (dash[2] || "").replace(/\/$/, "");
    if (!a)
      return html(
        pages.missing(
          view,
          "This account isn't in your pretend Cloudflare",
          "It may belong to another email's world, or you deleted it.",
        ),
        404,
      );
    for (const z of world.zones)
      if (z.status !== "active" && pointed(z, now, after)) z.status = "active";
    if (method === "POST") {
      const f = form();
      const act = f.get("do") || "";
      let saved = "1";
      if (page === "workers/plans") {
        a.paid = act !== "off";
        if (a.paid) a.card = true;
      } else if (page === "billing/subscriptions") {
        a.card = act !== "off";
        if (!a.card) a.paid = false;
      } else if (page === "ai/ai-gateway") {
        a.credit = act === "off" ? 0 : a.credit + 1000;
        if (a.credit) a.card = true;
      } else if (page === "r2/overview") a.r2 = act !== "off";
      else if (page === "workers/onboarding") {
        const name = String(f.get("name") || "")
          .toLowerCase()
          .trim();
        if (act === "off") a.subdomain = null;
        else if (!/^[a-z0-9][a-z0-9-]{0,61}[a-z0-9]$/.test(name)) saved = "bad-name";
        else if (world.takenSubdomains.includes(name) || /^taken/.test(name)) saved = "taken";
        else {
          a.subdomain = name;
          world.takenSubdomains.push(name);
        }
      } else if (page === "domains/registrations") {
        const z = world.zones.find((z) => z.id === f.get("zone") && z.account === a.id);
        if (z) {
          z.pointed = true;
          z.hold = false;
          z.status = "active";
        }
      } else if (page === "manage/configurations" && act === "delete") {
        world.accounts = world.accounts.filter((x) => x !== a);
        world.zones = world.zones.filter((z) => z.account !== a.id);
        return redirect("/?deleted=" + encodeURIComponent(a.name), 303);
      }
      return redirect(`${path}?saved=${saved}`, 303);
    }
    return html(pages.dashboard(view, a, page, url.searchParams.get("saved")));
  }

  // ── test controls ──
  if (opts.testControls && path === "/_test/expire-tokens" && method === "POST") {
    world.tokens = {}; // every access token ends, as after an hour
    return json({ ok: true });
  }
  if (opts.testControls && path === "/_test/nameservers" && method === "POST") {
    const z = world.zones.find((z) => z.name === url.searchParams.get("zone"));
    if (z) z.pointed = true;
    return json({ ok: !!z });
  }

  // ── this site's own pages: home with the control panel, and where a deployed iterate "is" ──
  if (path === "/" && method === "GET") return html(pages.home(view, url.searchParams));
  if (path === "/control" && method === "POST") {
    const f = form();
    const a = account(f.get("account"));
    const act = f.get("do");
    if (a && act === "card") {
      a.card = !a.card;
      if (!a.card) a.paid = false;
    }
    if (a && act === "paid") {
      a.paid = !a.paid;
      if (a.paid) a.card = true;
    }
    if (a && act === "r2") a.r2 = !a.r2;
    if (a && act === "credit") {
      a.credit = a.credit ? 0 : 1000;
      if (a.credit) a.card = true;
    }
    if (a && act === "workersdev")
      a.subdomain = a.subdomain
        ? null
        : (world.user.first || "you").toLowerCase().replace(/[^a-z0-9]+/g, "-") +
          "-" +
          hexId().slice(0, 4);
    if (act === "point") {
      const z = world.zones.find((z) => z.id === f.get("zone"));
      if (z) {
        z.pointed = true;
        z.hold = false;
        z.status = "active";
      }
    }
    if (act === "expire") world.tokens = {};
    if (act === "reset" && opts.reset) {
      const fresh = opts.reset();
      for (const k of Object.keys(world)) delete world[k];
      Object.assign(world, fresh);
    }
    return redirect(`/?did=${encodeURIComponent(act || "")}#world`, 303);
  }
  const site = /^\/site\/([^/]+)(\/.*)?$/.exec(path);
  if (site) {
    const host = decodeURIComponent(site[1]).toLowerCase();
    // a deployment takes its whole domain: example.com and every name under it, once its run is over
    const [domain, found] = Object.entries(world.sites).find(
      ([h, s]) => (host === h || host.endsWith(`.${h}`)) && s.at <= now,
    ) || [null, null];
    return html(pages.site(view, host, domain, found, site[2] || "/"), found ? 200 : 404);
  }

  // ── the API ──
  if (!path.startsWith("/client/v4") && path !== "/_pretend/deployed")
    return html(
      pages.missing(
        view,
        "No such page",
        "The pretend Cloudflare has only the pages the wizard links to.",
      ),
      404,
    );
  const api = path.replace(/^\/client\/v4/, "");
  const bearer = /^Bearer (\S+)$/.exec(request.headers.get("authorization") || "")?.[1];
  const grant = bearer && world.tokens[bearer];
  world.requests = [
    { at: now, method, path: api + url.search, ok: !!grant },
    ...(world.requests || []),
  ].slice(0, 40);
  if (!grant) return fail(401, 10000, "Authentication error");
  // a token sees an account only if it was ticked at consent and asked for more than who you are
  const identityOnly = grant.scope
    .split(" ")
    .filter(Boolean)
    .every((x) => x === "user-details.read");
  const reach = (aid) => !identityOnly && grant.accounts.includes(aid) && account(aid);

  // the pretend deployer says what its run will leave: Workers, a bucket, and the domain it answers on
  if (path === "/_pretend/deployed" && method === "POST") {
    const b = body();
    if (!reach(b.account)) return fail(403, 10000, "Authentication error");
    return ok({ recorded: recordDeployment(world, b, now) });
  }

  // whether a deployment's stand-in is there (the wizard's page of deployments asks: nothing
  // pretend is on the internet to ask itself)
  if (api === "/pretend/answers" && method === "GET") {
    const host = String(url.searchParams.get("host") || "").toLowerCase();
    return ok({
      answers: Object.entries(world.sites).some(
        ([domain, site]) =>
          (host === domain || host.endsWith(`.${domain}`)) &&
          site.at <= now &&
          grant.accounts.includes(site.account),
      ),
    });
  }

  if (api === "/user")
    return ok({
      id: world.user.id,
      email: world.user.email,
      first_name: world.user.first,
      last_name: world.user.last,
    });
  if (api === "/accounts" && method === "GET")
    return ok(
      world.accounts
        .filter((a) => grant.accounts.includes(a.id))
        .map(({ id, name }) => ({ id, name, type: "standard" })),
    );
  if (api === "/accounts" && method === "POST") {
    const key = request.headers.get("idempotency-key");
    if (!key) return fail(400, 1001, "Idempotency-Key header is required");
    const b = body();
    if (b.standalone !== true) return fail(400, 1002, "standalone must be true");
    if (/fail/i.test(String(b.name)))
      return fail(
        400,
        1005,
        "You have reached the limit of accounts you can create. Contact support to raise it.",
      );
    let a = account(world.created[key]);
    if (!a) {
      a = newAccount({ id: hexId(), name: b.name });
      world.accounts.push(a);
      world.created[key] = a.id;
    }
    return ok({ id: a.id, name: a.name, type: "standard" });
  }

  // one account, as a deploy run checks it first and asks again after it gave its token up
  const one = /^\/accounts\/([0-9a-f]{32})$/.exec(api);
  if (one && method === "GET") {
    const a = reach(one[1]);
    return a
      ? ok({ id: a.id, name: a.name, type: "standard" })
      : fail(403, 10000, "Authentication error");
  }
  let m = /^\/accounts\/([0-9a-f]{32})\/(.*)$/.exec(api);
  if (m) {
    const a = reach(m[1]);
    if (!a) return fail(403, 10000, "Authentication error");
    const rest = m[2];
    if (rest === "subscriptions") return fail(403, 10000, "Authentication error");
    // what a deployment left (recordDeployment): the page of a person's deployments reads it
    if (rest === "workers/scripts" && method === "GET")
      return ok(
        (a.existing?.workers || []).map((id) => {
          const site = Object.values(world.sites).find((s) => id.startsWith(`iterate-${s.name}-`));
          return {
            id,
            modified_on: new Date(site?.at || now).toISOString(),
            tags:
              site?.commit && id === `iterate-${site.name}-boundary`
                ? [`iterate-commit:${site.commit}`]
                : [],
          };
        }),
      );
    if (rest === "workers/subdomain" && method === "GET")
      return a.subdomain
        ? ok({ subdomain: a.subdomain })
        : fail(404, 10007, "This account doesn't have a workers.dev subdomain.");
    if (rest.startsWith("workers/subdomains/") && method === "GET") {
      const name = rest.slice("workers/subdomains/".length);
      return world.takenSubdomains.includes(name) || /^taken/.test(name)
        ? fail(400, 10031, `Subdomain '${name}' is unavailable`)
        : fail(400, 10032, `Subdomain '${name}' is available but not configured`);
    }
    if (rest === "workers/subdomain" && method === "PUT") {
      const name = body().subdomain;
      if (world.takenSubdomains.includes(name) || /^taken/.test(String(name)))
        return fail(409, 10031, "That subdomain is taken.");
      a.subdomain = name;
      world.takenSubdomains.push(name);
      return ok({ subdomain: name });
    }
    if (rest === "ai-gateway/billing/credit-balance")
      return ok({
        balance: a.credit,
        has_default_payment_method: !!a.card,
        ...(a.card ? { payment_method: { last4: "4242", brand: "visa" } } : {}),
        topup_config: { threshold: 0, amount: 0 },
        first_topup_success: a.credit > 0,
      });
    // "auto": Workers Paid comes on AUTO_MS after the first look for it, and R2 AUTO_MS after that
    if (world.tags?.includes("auto")) {
      if (rest === "containers/applications" && !a.paid) {
        a.autoPaidAt ??= now;
        if (now - a.autoPaidAt >= AUTO_MS) a.paid = a.card = true;
      }
      if (rest === "r2/buckets" && a.paid && !a.r2) {
        a.autoR2At ??= now;
        if (now - a.autoR2At >= AUTO_MS) a.r2 = true;
      }
    }
    if (rest === "r2/buckets")
      return a.r2
        ? ok({ buckets: (a.existing?.r2 || []).map((n) => ({ name: n })) })
        : fail(403, 10042, "Please enable R2 through the Cloudflare Dashboard.");
    if (rest === "containers/applications")
      return a.paid
        ? ok([])
        : json(
            {
              success: false,
              errors: [
                {
                  code: 1000,
                  message:
                    '{"error":"Unauthorized: You do not have access to Cloudflare Containers. Deploying containers requires the Workers Paid plan."}',
                },
              ],
            },
            401,
          );
    const r = /^(registrar|registrar-sandbox)\/(.*)$/.exec(rest);
    if (r) {
      const sandbox = r[1] === "registrar-sandbox";
      const mine = Object.keys(world.registrations).filter(
        (k) => k.startsWith(`${a.id}:`) && !world.registrations[k].failed,
      );
      const item = (name) => ({
        name,
        registrable: !isTaken(name),
        tier: /premium/.test(name) ? "premium" : "standard",
        ...(isTaken(name)
          ? { reason: "domain_unavailable" }
          : {
              pricing: {
                currency: "USD",
                registration_cost: price(name),
                renewal_cost: renewal(name),
              },
            }),
      });
      if (r[2] === "domain-check" && method === "POST")
        return ok({ domains: (body().domains || []).slice(0, 20).map(item) });
      if (r[2] === "domain-search") {
        const q = (url.searchParams.get("q") || "").toLowerCase().trim();
        const exact = /^[a-z0-9-]+(\.[a-z0-9-]+)+$/.test(q) ? q : null; // a whole domain: that one first
        const words = (exact ? q.split(".")[0] : q)
          .replace(/[^a-z0-9 ]/g, "")
          .split(/\s+/)
          .filter(Boolean);
        const stems = [words.join(""), words.join("-"), ...words].filter(Boolean);
        const names = [
          ...(exact ? [exact] : []),
          ...[...new Set(stems)].flatMap((s) => ["com", "dev", "net"].map((t) => `${s}.${t}`)),
        ];
        return ok({ domains: [...new Set(names)].slice(0, 20).map(item) });
      }
      if (r[2] === "domains" && method === "GET") {
        const held = sandbox ? [] : mine;
        return json({
          success: true,
          errors: [],
          result: held.slice(0, 1).map((k) => ({ name: k.split(":")[1] })),
          result_info: { total_count: held.length },
        });
      }
      if (r[2] === "registrations" && method === "POST") {
        const b = body();
        if (b.contacts?.registrant && !/^\+\d{1,3}\.\d{4,14}$/.test(b.contacts.registrant.phone))
          return fail(400, 10000, "Invalid phone number");
        const onFile = !sandbox && mine.length > 0;
        if (!b.contacts?.registrant && !onFile)
          return fail(
            400,
            10000,
            "No registrant contact provided and no default address book entry found for this account.",
          );
        const key = `${a.id}:${b.domain_name}`;
        if (isTaken(b.domain_name)) return fail(400, 10000, "domain_unavailable");
        if (!sandbox && !(opts.quoteNeeds === "paid" ? a.paid : a.card))
          return ok(
            {
              state: "failed",
              completed: true,
              context: { domain_name: b.domain_name },
              error: { code: "billing_quote_failed", message: "Failed to create a quote" },
            },
            202,
          );
        const failed = /fail/.test(b.domain_name);
        world.registrations[key] = {
          polls: 0,
          at: now,
          ...(/slow/.test(b.domain_name) ? { slow: true } : {}),
          ...(failed ? { failed: true } : {}),
        };
        if (!sandbox && !failed)
          world.zones.push({
            id: hexId(),
            name: b.domain_name,
            account: a.id,
            status: "active",
            nameServers: ["ada.ns.cloudflare.com", "bob.ns.cloudflare.com"],
            pointed: true,
            at: now,
          });
        return ok(
          { state: "in_progress", completed: false, context: { domain_name: b.domain_name } },
          202,
        );
      }
      const st = /^registrations\/([^/]+)\/registration-status$/.exec(r[2]);
      if (st) {
        const reg = world.registrations[`${a.id}:${st[1]}`];
        if (!reg) return fail(404, 10000, "not found");
        reg.polls++;
        if (reg.failed)
          return ok({
            state: "failed",
            completed: true,
            context: { domain_name: st[1] },
            error: {
              code: "registry_rejected",
              message: "The registry rejected the registration. You were not charged.",
            },
          });
        const done = reg.polls >= 1 && (!reg.slow || now - reg.at >= 20_000);
        return ok({
          state: done ? "succeeded" : "in_progress",
          completed: done,
          context: { domain_name: st[1] },
        });
      }
    }
    // what "Erase and replace" reads in the account (container/takeover.mjs): a deployment's
    // database and key-value store, and nothing of the rest
    if (method === "GET") {
      const stacks = Object.values(world.sites).filter((site) => site.account === a.id);
      if (rest === "d1/database")
        return ok(
          stacks.map((site) => ({
            uuid: `d1-${site.name}`,
            name: `iterate-${site.name}-auth-db`,
          })),
        );
      if (rest === "storage/kv/namespaces")
        return ok(
          stacks.map((site) => ({ id: `kv-${site.name}`, title: `iterate-${site.name}-auth-kv` })),
        );
      if (
        [
          "workers/domains",
          "workers/durable_objects/namespaces",
          "artifacts/namespaces",
          "secrets_store/stores",
          "access/apps",
          "pages/projects",
        ].includes(rest)
      )
        return ok([]);
    }
    return fail(404, 7003, `no route for ${api}`);
  }

  if (api === "/zones" && method === "GET") {
    const name = url.searchParams.get("name"),
      aid = url.searchParams.get("account.id");
    // in pages, as Cloudflare: 50 at most
    const per = Math.min(Number(url.searchParams.get("per_page")) || 20, 50),
      page = Number(url.searchParams.get("page")) || 1;
    const all = world.zones
      .filter(
        (z) =>
          (!name || z.name === name) &&
          (!aid || z.account === aid) &&
          grant.accounts.includes(z.account),
      )
      .sort((a, b) => a.name.localeCompare(b.name));
    const result = all.slice((page - 1) * per, page * per).map(zoneOut);
    // as Cloudflare: each answer says how many zones and how many pages there are
    return json({
      success: true,
      errors: [],
      messages: [],
      result,
      result_info: {
        page,
        per_page: per,
        count: result.length,
        total_count: all.length,
        total_pages: Math.ceil(all.length / per),
      },
    });
  }
  if (api === "/zones" && method === "POST") {
    const b = body();
    if (!reach(b.account?.id)) return fail(403, 10000, "Authentication error");
    if (world.zones.some((z) => z.name === b.name && z.account === b.account.id))
      return fail(400, 1061, `${b.name} already exists`);
    const z = {
      id: hexId(),
      name: b.name,
      account: b.account.id,
      status: "pending",
      nameServers: ["kayleigh.ns.cloudflare.com", "nolan.ns.cloudflare.com"],
      pointed: false,
      at: now,
    };
    world.zones.push(z);
    return ok(zoneOut(z));
  }
  m = /^\/zones\/([0-9a-f]{32})(\/activation_check)?$/.exec(api);
  if (m) {
    const z = world.zones.find((z) => z.id === m[1] && grant.accounts.includes(z.account));
    if (!z) return fail(404, 1001, "zone not found");
    if (m[2] && pointed(z, now, after)) z.status = "active";
    return ok(m[2] ? { id: z.id } : zoneOut(z));
  }
  m = /^\/zones\/([0-9a-f]{32})\/(.+)$/.exec(api);
  if (m && method === "GET") {
    const z = world.zones.find((z) => z.id === m[1] && grant.accounts.includes(z.account));
    if (!z) return fail(404, 1001, "zone not found");
    const found = onZone(world, z, m[2]);
    if (found !== undefined) return ok(found);
  }
  return fail(404, 7003, `no route for ${method} ${api}`);
}