iterate.com / cloud

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

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

// installation.js — ONE INSTALLATION THAT A CHAT DRIVES (worker/service.js): a mind's first deploy
// that starts at the person's consent and waits, by itself, for what only the person can do.
//
// The wizard's run (deploy-run.js `start`) needs everything first: Workers Paid, R2, a domain, then
// the consent. Here the order is turned round. The consent starts the run at once, and the run
// does what needs no money while it waits:
//
//   consent   the person's Cloudflare consent; the token goes to this object's memory alone
//   prep      the run's container comes up (its first start pulls the whole stack), the account is
//             checked, the account gets its workers.dev name, the stack's state store is made
//             where Cloudflare allows it, and the mind's Worker is built (container/run.sh `prep`)
//   early     the stack is deployed before its domain (run.sh `early`): no domain and no mail, and
//             `cloudflarePlan: "free"` while Workers Paid or R2 is off (core/alchemy README, "Before
//             the domain and before Workers Paid"). Skipped when all three waits are over already.
//   payment   wait: Workers Paid (Containers answer)
//   r2        wait: R2 is on
//   domain    wait: a domain is chosen, and its zone is in the account and active
//   deploy    the wizard's whole run (run.sh with no phase): check, deploy, answer, verify. After
//             `early` it is the tail: the same stack gets its domain, mail, what needs Workers Paid
//             and R2, telemetry and the mind's Cloudflare connection (run.sh `stack_updatable`)
//   finish    the token is revoked, the container goes; the Worker enrols the deployment
//
// `prep` and `early` only make the deploy shorter: the deploy does the same work again, and skips
// what is there. So a failure of one of them is a note, never the end of the installation.
//
// THE SANDBOXES: `early` says `mind.containers: false` (a Free account has no Containers). The
// deploy at the domain, on Workers Paid, names no image: sandboxes start at once on the
// Cloudflare-managed image `cloudflare/debian-trixie`, and the mind installs what it needs there
// (tasks/iterate-cloud/designs/phased-deploy.md, phase D).
//
// THE TOKEN, as in deploy-run.js: in this object's memory and in a phase's process environment
// alone. A consent lasts about an hour, and a person can take longer to add a card. When the token
// ends (or this object restarts and loses it), the installation waits for a fresh consent, which
// resumes it: the phases that are done stay done. The deploy starts only with 30 minutes of token
// left (its own limit is 20 minutes, and iterate then has 10 minutes to answer).
//
// THE FIRST OWNER'S TICKET is made when the deploy starts, so a parked installation holds none. It
// stays in memory until the owner's page takes it once (index.js `/i/<id>/owner`).
//
// No Cloudflare and no container in this module: it runs in Node for the tests. A `runner` runs the
// phases: the container (deploy-run.js) or a pretend one (installation-pretend.js).
import { workersDevNamesOf } from "./account-name.js";
import { giveUp, revoke } from "./cloudflare-access.js";
import { firstOwnerTicket } from "./first-owner.js";
import { keptLines } from "./run-log.js";
import { cloudflareTokenGranted, connectionAfter, telemetryGranted } from "./scopes.js";
import { configOf } from "./stack-config.js";

const PHASES = [
  { id: "consent", label: "Connect Cloudflare" },
  { id: "prep", label: "Get the run ready" },
  { id: "early", label: "Deploy before the domain" },
  { id: "payment", label: "Workers Paid" },
  { id: "r2", label: "R2 storage" },
  { id: "domain", label: "A domain" },
  { id: "deploy", label: "Deploy iterate" },
  { id: "finish", label: "Give up the access and enrol" },
];
/** The kinds of single-use link (service.js `links`), each a page of the Cloud's own. */
export const LINK_KINDS = ["consent", "account", "card", "workers-paid", "r2", "domain", "owner"];
/** The kinds whose page needs the person's own browser session: they spend money, pick for them,
 *  or hand over the owner's ticket. */
export const SIGNED_IN_KINDS = ["account", "domain", "owner"];

/** What service.js and index.js may ask of an installation (installation.js). */
export const INSTALL_OPS = [
  "create",
  "status",
  "choose",
  "link",
  "takeLink",
  "openSession",
  "hasSession",
  "expectedUser",
  "bindUser",
  "claimSlot",
  "releaseSlot",
  "slots",
  "noteAsker",
  "deployedElsewhere",
  "claimZone",
  "releaseZone",
  "forget",
  "forgotten",
  "consent",
  "consentRefused",
  "poke",
  "resources",
  "ownerTicket",
  "deployedZone",
  "domainSearch",
  "domainBuy",
];

const MINUTE = 60_000;
/** How much token a phase needs left when it starts: run.sh bounds each of its steps. */
const LEFT_FOR = { prep: 10 * MINUTE, early: 30 * MINUTE, deploy: 30 * MINUTE };
/** How many deploys an installation may try. A deploy that failed is tried again only after a
 *  fresh consent, which the person gives. */
export const MAX_DEPLOYS = 3;
const POLL_FIRST = 5_000;
const LINK_MS = 30 * MINUTE;
const SESSION_MS = 7 * 24 * 60 * MINUTE;

const NAME = /^[a-z][a-z0-9-]{1,30}$/;
const DOMAIN = /^[a-z0-9-]+(\.[a-z0-9-]+)+$/;
const EMAIL = /^[^@\s]+@[^@\s]+\.[^@\s]+$/;
/** Whether `email` is an address at `zone` or under it: the rule of core/auth-worker/src/config.ts
 *  for a member of the mind on `zone`. */
const atDomain = (email, zone) => {
  const host = String(email || "")
    .split("@")[1]
    ?.toLowerCase();
  return Boolean(zone && host && (host === zone || host.endsWith(`.${zone}`)));
};
/** Why `owner` cannot own the mind on `zone`, and what to change: `field`. */
const ownerAtDomain = (owner, zone, field) =>
  `${owner} is an address at ${zone}, and a mind receives the mail of its own domain: its owner signs in with an address somewhere else. Choose another ${field === "domain" ? "domain" : "owner's address"}.`;
/** A domain named `iterate.<a domain>` is the platform's host of that domain (index.js). */
const PLATFORM_HOST = /^iterate\.[^.]+\../;

/** How many installations one owner may have at a mind (`claimSlot`). */
export const MAX_PER_OWNER = 10;
/** How many of the newest asks an installation keeps (`noteAsker`). */
const MAX_ASKED = 50;

/** The installation's id for a deployment of a calling mind: one per deployment, the same on
 *  every call. A hash, so it is a name and opens nothing. */
export async function installationIdOf(mind, deployment) {
  const digest = new Uint8Array(
    await crypto.subtle.digest(
      "SHA-256",
      new TextEncoder().encode(`iterate-cloud installation\n${mind}\n${deployment}`),
    ),
  );
  const alphabet = "abcdefghijklmnopqrstuvwxyz234567";
  let bits = 0;
  let value = 0;
  let out = "";
  for (const byte of digest) {
    value = (value << 8) | byte;
    bits += 8;
    while (bits >= 5 && out.length < 26) {
      out += alphabet[(value >>> (bits - 5)) & 31];
      bits -= 5;
    }
  }
  return `inst_${out}`;
}
export const INSTALLATION_ID = /^inst_[a-z2-7]{26}$/;

const randomText = () =>
  btoa(String.fromCharCode(...crypto.getRandomValues(new Uint8Array(24))))
    .replace(/\+/g, "-")
    .replace(/\//g, "_")
    .replace(/=+$/, "");
const sha256 = async (text) =>
  [...new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text)))]
    .map((b) => b.toString(16).padStart(2, "0"))
    .join("");

/** A refusal of an operation: `{ refused: { status, error, field? } }`. */
/** @param {number} status @param {string} error @param {string} [field] */
const refused = (status, error, field) => ({ refused: { status, error, field } });

/** Whether the installation's run is over: deployed by the Cloud, deployed elsewhere and tied to
 *  it (`deployedElsewhere`), or out of tries. Nothing more starts. */
const isOver = (s) => Boolean(s.result || s.deployedAt || s.failed);

/** The installation's record as it is first stored. */
const fresh = ({ id, mind, deployment, owner }, now) => ({
  id,
  mind,
  deployment,
  // the app's own id of its user: a note for the log, never checked against Cloudflare
  ownerUserId: owner.userId,
  // the consent must come from the Cloudflare user of this email; its id is kept at the first
  // consent, and from then on only that user may consent (`expectedUser`, `bindUser`)
  email: owner.email,
  cloudflareUserId: null,
  createdAt: now,
  // who asked through the Service entrypoint (`noteAsker`)
  asked: [],
  choices: {
    name: null,
    accountId: null,
    domain: null,
    ownerEmail: null,
    telemetry: true,
    cloudflareConnection: true,
  },
  accounts: [],
  zones: [],
  zoneId: null,
  phases: Object.fromEntries(PHASES.map(({ id: phase }) => [phase, { state: "pending" }])),
  waits: { payment: null, r2: null, domain: null },
  detail: null,
  telemetry: "unknown",
  grant: { telemetry: false, cloudflareToken: false },
  tokenEndsAt: null,
  running: null,
  current: [],
  lines: [],
  poll: { every: POLL_FIRST, next: 0 },
  attempts: { deploy: 0 },
  result: null,
  ownerLink: null,
  purchased: null,
  links: {},
  sessions: {},
  failed: false,
  updatedAt: now,
});

export class Installation {
  /** The person's Cloudflare token, in memory only. */
  #token = null;
  /** A token that a fresh consent replaced while a phase still runs with it: revoked when that
   *  phase ends, not under it. */
  #retired = null;
  /** The token the running phase was given. */
  #phaseToken = null;
  /** The first owner's ticket (first-owner.js), in memory only, until the owner's page takes it.
   *  @type {Awaited<ReturnType<typeof firstOwnerTicket>> | null} */
  #first = null;

  /** @param {{ storage: any, env: any, runner: any, fetch?: typeof fetch, now?: () => number }} parts
   *  `storage`: get, put, delete, setAlarm and deleteAlarm, as a Durable Object's. `runner`: launch(phase, input),
   *  poll(phase, running) and stop() (deploy-run.js, installation-pretend.js). */
  constructor({ storage, env, runner, fetch: fetcher = globalThis.fetch, now = Date.now }) {
    this.storage = storage;
    this.env = env;
    this.runner = runner;
    this.fetch = fetcher;
    this.now = now;
  }

  /** @returns {Promise<any>} */
  async load() {
    const s = await this.storage.get("install");
    // an installation stored before the phase `early` existed: it gets the phase, still to run
    // while its deploy is, and skipped once the deploy started or the installation is over
    if (s && !s.phases.early)
      s.phases.early =
        !isOver(s) && s.phases.deploy.state === "pending"
          ? { state: "pending" }
          : { state: "skipped" };
    return s;
  }
  async save(s) {
    s.updatedAt = this.now();
    await this.storage.put("install", s);
  }

  // ── what service.js asks ─────────────────────────────────────────────────────────────────────

  /** Makes the installation once; a second call answers the one there is and whose it is. */
  async create({ id, mind, deployment, owner }) {
    if (await this.storage.get("forgetting"))
      return refused(409, "This installation is being forgotten: ask again in a moment.");
    const s = await this.load();
    if (s) return { created: false, email: s.email };
    await this.save(fresh({ id, mind, deployment, owner }, this.now()));
    return { created: true, email: owner.email };
  }

  /** On an owner's own object (`owner:<mind>:<email>`, service.js): takes a place for the
   *  installation `id`, at most MAX_PER_OWNER. The same id takes the same place again. */
  async claimSlot({ id }) {
    const slots = (await this.storage.get("slots")) || [];
    if (slots.includes(id)) return { ok: true };
    if (slots.length >= MAX_PER_OWNER) return { ok: false, count: slots.length };
    await this.storage.put("slots", [...slots, id]);
    return { ok: true };
  }

  /** The installations that hold a place on this owner's object. */
  async slots() {
    return (await this.storage.get("slots")) || [];
  }

  /** Gives back the place of `id`: its creation lost a race to another owner (service.js). */
  async releaseSlot({ id }) {
    const slots = (await this.storage.get("slots")) || [];
    await this.storage.put(
      "slots",
      slots.filter((slot) => slot !== id),
    );
  }

  async status() {
    const s = await this.load();
    return s ? this.statusOf(s) : null;
  }

  /** Changes the person's choices. Answers the status, or `{ refused }`. */
  async choose(changes) {
    const s = await this.load();
    if (!s) return refused(404, "No such installation.");
    const started = s.phases.consent.state === "done";
    const deploying = ["running", "done"].includes(s.phases.deploy.state) || s.result;
    // the stack that `early` deploys names the owner already, and the deploy keeps that config
    // (container/run.sh `keep_stored_config`)
    const deployed = deploying || !["pending", "skipped"].includes(s.phases.early.state);
    const next = { ...s.choices };
    if ("name" in changes) {
      const name = changes.name;
      if (typeof name !== "string" || !NAME.test(name) || name.endsWith("-"))
        return refused(
          400,
          "A name is 2 to 31 lowercase letters, digits and dashes, starting with a letter.",
          "name",
        );
      if (started && name !== s.choices.name)
        return refused(409, "The name is locked: the run started with it.", "name");
      next.name = name;
    }
    if ("accountId" in changes) {
      const accountId = changes.accountId;
      if (!s.accounts.some((a) => a.id === accountId))
        return refused(400, "That account is not one the consent covered.", "accountId");
      if (s.phases.prep.state !== "pending" && s.choices.accountId !== accountId)
        return refused(409, "The account is locked: the run started in it.", "accountId");
      next.accountId = accountId;
    }
    if ("domain" in changes) {
      if (deploying && JSON.stringify(changes.domain) !== JSON.stringify(s.choices.domain))
        return refused(409, "The domain is locked: the deploy started.", "domain");
      const domain =
        changes.domain === null ? null : await this.domainOf(changes.domain, next.accountId);
      if (domain?.refused) return domain;
      next.domain = domain;
    }
    if ("ownerEmail" in changes) {
      if (typeof changes.ownerEmail !== "string" || !EMAIL.test(changes.ownerEmail))
        return refused(400, "That is not an email address.", "ownerEmail");
      // the owner is the person's own email until they choose another (`statusOf` says it)
      if (deployed && changes.ownerEmail !== (s.choices.ownerEmail || s.email))
        return refused(409, "The owner is locked: the deploy started.", "ownerEmail");
      next.ownerEmail = changes.ownerEmail;
    }
    // the stack refuses a member's address at its own domain (core/auth-worker/src/config.ts): its
    // deploy would fail at the domain, after `early` locked the owner, with a note that names no
    // cause. So that pair is refused here, on the field that changed: the domain when both did
    const owner = next.ownerEmail || s.email;
    const domainChanged = JSON.stringify(next.domain) !== JSON.stringify(s.choices.domain);
    const ownerChanged = owner !== (s.choices.ownerEmail || s.email);
    if ((domainChanged || ownerChanged) && atDomain(owner, next.domain?.zone)) {
      const field = domainChanged ? "domain" : "ownerEmail";
      return refused(400, ownerAtDomain(owner, next.domain.zone, field), field);
    }
    for (const flag of ["telemetry", "cloudflareConnection"])
      if (flag in changes) {
        if (typeof changes[flag] !== "boolean")
          return refused(400, `${flag} is true or false.`, flag);
        next[flag] = changes[flag];
      }
    s.choices = next;
    if (s.waits.domain !== null && "domain" in changes) s.waits.domain = null;
    s.poll = { every: POLL_FIRST, next: 0 };
    await this.save(s);
    await this.advance();
    return this.status();
  }

  /** Mints a single-use link of `kind`, or answers `{ refused }` when that page is not open now. */
  async link(kind) {
    const s = await this.load();
    if (!s) return refused(404, "No such installation.");
    const why = this.closedLink(s, kind);
    if (why) return refused(409, why, "kind");
    const now = this.now();
    for (const [nonce, held] of Object.entries(s.links))
      if (held.expiresAt <= now) delete s.links[nonce];
    const nonce = randomText();
    const expiresAt = now + LINK_MS;
    s.links[nonce] = { kind, expiresAt };
    await this.save(s);
    return { nonce, expiresAt };
  }

  /** The domain choice `{ zone }` as it is kept, or `{ refused }`. With a live token, the zone
   *  must be in the account. */
  async domainOf(asked, accountId) {
    const zone = String(asked?.zone || "").toLowerCase();
    if (!DOMAIN.test(zone)) return refused(400, `${zone || "That"} is not a domain.`, "domain");
    if (PLATFORM_HOST.test(zone))
      return refused(
        400,
        `iterate does not deploy on ${zone}: a name that starts with "iterate." is the platform's host of ${zone.slice("iterate.".length)}.`,
        "domain",
      );
    if (!this.#token || !accountId) return { zone };
    const named = await this.cf("GET", `/zones?name=${zone}&account.id=${accountId}`);
    if (named.success && !named.result?.[0])
      return refused(
        400,
        `${zone} is not a domain of this Cloudflare account. Buy it on the domain page, or add it to the account first.`,
        "domain",
      );
    return { zone };
  }

  /** Why a link of `kind` is not open now, or null when it is. */
  closedLink(s, kind) {
    if (!LINK_KINDS.includes(kind)) return `A link is one of: ${LINK_KINDS.join(", ")}.`;
    const done = isOver(s);
    switch (kind) {
      case "consent":
        if (done) return "The installation has ended: no consent is needed.";
        if (!s.choices.name) return "Choose the mind's name first.";
        return null;
      case "account":
        if (done || s.accounts.length < 2)
          return "There is no account to pick: the consent covered one, or none yet.";
        return null;
      case "card":
      case "workers-paid":
      case "r2":
        if (!s.choices.accountId) return "The account is not known yet: connect Cloudflare first.";
        return null;
      case "domain":
        if (!s.choices.accountId) return "The account is not known yet: connect Cloudflare first.";
        if (!this.#token) return "The access to Cloudflare ended: a fresh consent first.";
        if (s.phases.deploy.state !== "pending" && s.phases.deploy.state !== "failed")
          return "The deploy started: the domain is set.";
        return null;
      case "owner":
        if (!s.result) return "The mind is not deployed yet.";
        if (s.ownerLink !== "ready" || !this.#first)
          return "The owner's link was used, or this Cloud lost it: sign in with a mailed code.";
        return null;
    }
    return null;
  }

  /** Takes a link's nonce once: true when it was minted for `kind` and lives. */
  async takeLink({ nonce, kind }) {
    const s = await this.load();
    const held = s?.links[nonce];
    if (!held) return false;
    delete s.links[nonce];
    await this.save(s);
    return held.kind === kind && held.expiresAt > this.now();
  }

  /** A browser session of the installation's own Cloudflare user, made after a consent proved who
   *  they are (index.js). The cookie holds the value; this object keeps its hash alone. */
  async openSession() {
    const s = await this.load();
    const value = randomText();
    const now = this.now();
    for (const [hash, until] of Object.entries(s.sessions))
      if (until <= now) delete s.sessions[hash];
    s.sessions[await sha256(value)] = now + SESSION_MS;
    await this.save(s);
    return { value, maxAge: SESSION_MS / 1000 };
  }
  async hasSession(value) {
    const s = await this.load();
    if (!s || typeof value !== "string" || !value) return false;
    return (s.sessions[await sha256(value)] || 0) > this.now();
  }

  /** Notes who asked through the Service entrypoint (service.js `serviceCall`): the call, the
   *  context that called, and its principal. The newest MAX_ASKED are kept. */
  async noteAsker({ call, path, principal, onBehalfOf }) {
    const s = await this.load();
    if (!s) return;
    s.asked = [...(s.asked || []), { at: this.now(), call, path, principal, onBehalfOf }].slice(
      -MAX_ASKED,
    );
    await this.save(s);
  }

  /** Who the consent must be given by: the owner's email, and the Cloudflare user's id once a
   *  consent of theirs was taken. */
  async expectedUser() {
    const s = await this.load();
    return s ? { email: s.email, cloudflareUserId: s.cloudflareUserId } : null;
  }

  /** Keeps the Cloudflare user of the first consent that matched the owner's email: from then on
   *  only that user may consent. */
  async bindUser({ cloudflareUserId }) {
    const s = await this.load();
    if (!s) return { ok: false };
    if (s.cloudflareUserId && s.cloudflareUserId !== cloudflareUserId) return { ok: false };
    if (!s.cloudflareUserId) {
      s.cloudflareUserId = cloudflareUserId;
      await this.save(s);
    }
    return { ok: true };
  }

  /** A consent of the installation's own Cloudflare user (index.js checked who): the token comes
   *  here and nowhere else. Resumes the installation where it stands. */
  async consent({ token, expiresAt, scope, wants, cloud }) {
    const s = await this.load();
    if (!s || isOver(s)) {
      await this.giveUpToken(token);
      return refused(409, "The installation has ended: the consent was given up.");
    }
    if (this.#token && this.#token !== token) {
      // the running phase's token lives until the phase ends; any other old token goes now
      if (s.running && this.#token === this.#phaseToken) this.#retired = this.#token;
      else await this.giveUpToken(this.#token);
    }
    this.#token = token;
    const now = this.now();
    s.tokenEndsAt = expiresAt;
    // what the deployment trusts of this Cloud: its public keys and its origin (index.js `trustOf`)
    s.cloud = cloud || null;
    s.grant = {
      telemetry: wants.telemetry === true && telemetryGranted(scope),
      cloudflareToken: wants.cloudflare === true && cloudflareTokenGranted(scope),
    };
    s.telemetry = s.grant.telemetry ? "on" : "off";
    s.phases.consent = {
      state: "done",
      startedAt: s.phases.consent.startedAt ?? now,
      endedAt: now,
    };
    const accounts = await this.cf("GET", "/accounts?per_page=50");
    if (accounts.success)
      s.accounts = (accounts.result || []).map((a) => ({ id: a.id, name: a.name }));
    // the run's account must be in the consent: until a consent covers it, that is what is said
    s.accountUncovered = Boolean(
      s.choices.accountId && !s.accounts.some((a) => a.id === s.choices.accountId),
    );
    if (!s.choices.accountId && s.accounts.length === 1) s.choices.accountId = s.accounts[0].id;
    // a deploy that failed is tried again with this consent, while tries are left
    if (s.phases.deploy.state === "failed" && s.attempts.deploy < MAX_DEPLOYS)
      s.phases.deploy = { state: "pending", note: s.phases.deploy.note };
    s.poll = { every: POLL_FIRST, next: 0 };
    await this.save(s);
    await this.advance();
    return this.status();
  }

  /** Cloudflare gave no consent (most often the scope under "Sensitive scopes" was not ticked). */
  async consentRefused({ said, tick }) {
    const s = await this.load();
    if (!s) return;
    if (tick) s.telemetry = "refused";
    s.detail = tick ? `${said}. ${tick}` : said;
    await this.save(s);
  }

  async poke() {
    const s = await this.load();
    if (!s) return null;
    s.poll = { every: POLL_FIRST, next: 0 };
    await this.save(s);
    await this.advance();
    return this.status();
  }

  async alarm() {
    await this.advance();
  }

  /** What the deploy made, from its log lines. */
  async resources() {
    const s = await this.load();
    if (!s) return null;
    const lines = s.running ? [...s.lines, ...s.current] : s.lines;
    return resourcesOf(lines);
  }

  /** The first owner's ticket, once, for the owner's page: `{ ticket, zone }`. */
  async ownerTicket() {
    const s = await this.load();
    if (!s?.result || !this.#first || s.ownerLink !== "ready") return null;
    const first = this.#first;
    this.#first = null;
    s.ownerLink = "used";
    await this.save(s);
    return { ticket: first.ticket, expires: first.expires, zone: s.choices.domain.zone };
  }

  /** The zone of a deployed installation, for the Worker's enrolment and handover. */
  async deployedZone() {
    const s = await this.load();
    if (s?.result) return s.choices.domain.zone;
    return s?.deployedAt?.zone ?? null;
  }

  /** Ties `zone` to this installation for a deployment made elsewhere (service.js
   *  `installationDeployedAt`, which checked that the Cloud enrolled it). `by`: who asked. */
  async deployedElsewhere({ zone, by }) {
    const s = await this.load();
    if (!s) return refused(404, "No such installation.");
    const held = s.result ? s.choices.domain.zone : s.deployedAt?.zone;
    if (held && held !== zone)
      return refused(409, `This installation is deployed at ${held} already.`, "domain");
    if (s.running)
      return refused(409, `The ${s.running.phase} phase runs: the Cloud is deploying this one.`);
    if (!s.deployedAt && !s.result) {
      // the run ends here: the Cloud never deploys over a deployment made elsewhere
      s.deployedAt = { zone, at: this.now(), by };
      if (this.#token) await this.giveUpToken(this.#token);
      this.#token = null;
      s.tokenEndsAt = null;
      await this.runner.stop();
      await this.save(s);
      await this.storage.deleteAlarm?.();
    }
    return { ok: true, zone };
  }

  /** On a zone's own object (`zone:<domain>`, service.js): the installation that holds the zone,
   *  one at most. The same id takes it again. */
  async claimZone({ id }) {
    const holder = await this.storage.get("holder");
    if (holder && holder !== id) return { ok: false, holder };
    if (!holder) await this.storage.put("holder", id);
    return { ok: true };
  }

  /** Gives the zone up, when `id` holds it. */
  async releaseZone({ id }) {
    if ((await this.storage.get("holder")) === id) await this.storage.delete("holder");
  }

  /** Forgets the installation: its record, its token and its alarm. A phase that runs is never cut
   *  off: that is a refusal. Answers what the caller frees after: the owner and the zone. Until the
   *  caller says `forgotten`, a mark (`forgetting`) refuses a new installation of the same id, so
   *  the caller never frees a place of a new one; asked again, it answers the same. The deployment
   *  is not touched. */
  async forget() {
    const s = await this.load();
    if (!s) {
      const mark = await this.storage.get("forgetting");
      return mark ? { ok: true, ...mark } : refused(404, "No such installation.");
    }
    if (s.running)
      return refused(409, `The ${s.running.phase} phase runs: forget it after it ends.`);
    if (this.#token) await this.giveUpToken(this.#token);
    this.#token = null;
    this.#first = null;
    await this.runner.stop();
    const mark = {
      mind: s.mind,
      email: s.email,
      zone: s.deployedAt?.zone ?? (s.result ? s.choices.domain.zone : null),
    };
    await this.storage.put("forgetting", mark);
    await this.storage.delete("install");
    await this.storage.deleteAlarm?.();
    return { ok: true, ...mark };
  }

  /** The caller freed what `forget` named: the mark goes. */
  async forgotten() {
    await this.storage.delete("forgetting");
  }

  // ── the domain page (index.js `/i/<id>/domain`): the only place that spends money ──────────────

  async domainSearch(q) {
    const s = await this.load();
    if (!this.#token || !s?.choices.accountId) return { error: "no-token" };
    const found = await this.cf(
      "GET",
      `/accounts/${s.choices.accountId}/registrar/domain-search?q=${encodeURIComponent(q)}`,
    );
    const contact = await this.cf(
      "GET",
      `/accounts/${s.choices.accountId}/registrar/domains?per_page=1`,
    );
    const held = contact.result_info?.total_count ?? (contact.result || []).length;
    return {
      domains: domainsOf(found),
      contactOnFile: held > 0,
      errors: found.errors || [],
    };
  }

  /** Registers `domain` in the account, with the person's typed confirmation. */
  async domainBuy({ domain, confirm, contacts }) {
    const s = await this.load();
    if (!this.#token || !s?.choices.accountId)
      return {
        ok: false,
        error: "The access to Cloudflare ended. Ask in the chat for a fresh consent.",
      };
    if (!DOMAIN.test(domain)) return { ok: false, error: "That is not a domain." };
    if (confirm !== domain) return { ok: false, error: "Type the domain again to buy it." };
    if (PLATFORM_HOST.test(domain))
      return { ok: false, error: `iterate does not deploy on ${domain}.` };
    if (s.phases.deploy.state === "running" || s.result)
      return { ok: false, error: "The deploy started: the domain is set." };
    // before any money is spent: the same refusal as `choose`
    const owner = s.choices.ownerEmail || s.email;
    if (atDomain(owner, domain))
      return { ok: false, error: ownerAtDomain(owner, domain, "domain") };
    const answer = await this.cf(
      "POST",
      `/accounts/${s.choices.accountId}/registrar/registrations`,
      // 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
      { domain_name: domain, ...(contacts && { contacts }) },
    );
    const state = answer.result?.state;
    if (!answer.success || state === "failed")
      return {
        ok: false,
        error:
          answer.result?.error?.message ||
          (answer.errors || []).map((e) => e.message).join("; ") ||
          `Cloudflare answered ${answer.status}.`,
        needsContact: /no registrant contact|address book/i.test(
          JSON.stringify(answer.errors || []),
        ),
        needsCard: /billing_quote_failed|quote/i.test(JSON.stringify(answer.result?.error || "")),
      };
    s.purchased = { domain, at: this.now() };
    s.choices.domain = { zone: domain };
    s.waits.domain = null;
    s.poll = { every: POLL_FIRST, next: 0 };
    await this.save(s);
    await this.advance();
    return { ok: true, state: state || "in_progress" };
  }

  // ── the run ──────────────────────────────────────────────────────────────────────────────────

  /** One step of the state machine: ends a phase that ended, polls the waits that are due, starts
   *  the next phase, and sets the alarm for the next look. */
  async advance() {
    const s = await this.load();
    if (!s || isOver(s)) return;
    const now = this.now();
    if (s.running) {
      const seen = await this.runner.poll(s.running.phase, s.running);
      s.current = seen.lines;
      if (seen.done) await this.ended(s, s.running.phase, seen);
      if (s.result) return this.save(s);
    }
    // the token is over: Cloudflare ends it, and it is revoked all the same, but the running
    // phase's own only when that phase ends (`ended`); a parked container goes
    if (this.#token && (s.tokenEndsAt || 0) <= now) {
      if (s.running && this.#token === this.#phaseToken) this.#retired = this.#token;
      else await this.giveUpToken(this.#token);
      this.#token = null;
    }
    if (!this.#token && !s.running) await this.runner.stop();
    // a token that does not cover the run's account looks at nothing and starts nothing
    const works = this.#token && s.choices.accountId && !s.accountUncovered;
    if (works && !s.running) await this.look(s);
    if (works && !s.running) await this.next(s);
    s.detail = this.detailOf(s);
    await this.save(s);
    await this.schedule(s);
  }

  /** Polls the waits that are open, when their time has come. */
  async look(s) {
    const now = this.now();
    if (now < s.poll.next) return;
    const account = s.choices.accountId;
    if (s.waits.payment !== true) {
      const containers = await this.cf("GET", `/accounts/${account}/containers/applications`);
      s.waits.payment = containers.success ? true : false;
    }
    if (s.waits.r2 !== true) {
      const r2 = await this.cf("GET", `/accounts/${account}/r2/buckets?per_page=1`);
      s.waits.r2 = r2.success ? true : false;
    }
    const zones = await this.cf("GET", `/zones?account.id=${account}&per_page=50`);
    if (zones.success) s.zones = (zones.result || []).map((z) => z.name);
    s.waits.domain = false;
    s.zoneId = null;
    if (s.choices.domain) {
      const zone = s.choices.domain.zone;
      if (s.purchased?.domain === zone)
        await this.cf(
          "GET",
          `/accounts/${account}/registrar/registrations/${zone}/registration-status`,
        );
      const named = await this.cf("GET", `/zones?name=${zone}&account.id=${account}`);
      const found = named.result?.[0];
      if (found?.status === "active") {
        s.waits.domain = true;
        s.zoneId = found.id;
      }
      s.zoneState = found ? found.status : "missing";
    }
    const open = !s.waits.payment || !s.waits.r2 || !s.waits.domain;
    // a wait that just ended means the person is at it now: look again soon for the next one
    const moved = ["payment", "r2", "domain"].some(
      (id) => s.waits[id] && s.phases[id].state !== "done",
    );
    const every = moved ? POLL_FIRST : s.poll.every;
    s.poll = open
      ? { every: Math.min(every * 2, 60_000), next: now + every }
      : { every: POLL_FIRST, next: 0 };
    for (const id of ["payment", "r2", "domain"]) {
      const phase = s.phases[id];
      if (s.waits[id]) {
        if (phase.state !== "done")
          s.phases[id] = { state: "done", startedAt: phase.startedAt ?? now, endedAt: now };
      } else s.phases[id] = { state: "waiting", startedAt: phase.startedAt ?? now };
    }
  }

  /** Starts the next phase that can start now. */
  async next(s) {
    const left = (s.tokenEndsAt || 0) - this.now();
    const ready = s.waits.payment && s.waits.r2 && s.waits.domain;
    if (s.phases.prep.state === "pending") {
      if (left >= LEFT_FOR.prep) return this.start(s, "prep");
      return;
    }
    if (s.phases.early.state === "pending") {
      // with nothing left to wait for, the deploy makes the whole stack at once; with too little
      // token, `early` waits for a fresh consent, as the deploy does
      if (ready)
        s.phases.early = {
          state: "skipped",
          note: "Workers Paid, R2 and the domain were there: the deploy makes the whole stack.",
        };
      else if (left >= LEFT_FOR.early) return this.start(s, "early");
    }
    if (!ready || s.phases.deploy.state !== "pending") return;
    if (left < LEFT_FOR.deploy) return;
    return this.start(s, "deploy");
  }

  async start(s, phase) {
    const now = this.now();
    const input = await this.inputOf(s, phase);
    const extra = await this.runner.launch(phase, input);
    this.#phaseToken = this.#token;
    s.running = { phase, startedAt: now, ...extra };
    s.current = [];
    s.phases[phase] = { state: "running", startedAt: now };
    if (phase === "deploy") s.attempts.deploy++;
  }

  /** What a phase's process gets: its environment (the token in it alone) and its files. */
  async inputOf(s, phase) {
    const { name, accountId, ownerEmail } = s.choices;
    const env = {
      ITERATE_PHASE: phase === "deploy" ? "" : phase,
      ITERATE_ATTEMPT: String(s.attempts.deploy + 1),
      CLOUDFLARE_API_TOKEN: this.#token,
      CLOUDFLARE_ACCOUNT_ID: accountId,
      ITERATE_NAME: name,
      // the account's workers.dev address, when it has none (container/run.sh workers_dev_ready)
      ITERATE_WORKERS_DEV_NAMES: workersDevNamesOf(s.email).join(" "),
    };
    if (phase === "prep") return { env, files: {} };
    const owner = ownerEmail || s.email;
    if (phase === "early") {
      // the stack before its domain, the same on every plan but for `cloudflarePlan`. Telemetry
      // and the mind's Cloudflare token wait for the deploy, which sets them in the config that
      // the stack keeps (container/run.sh `stack_updatable`): telemetry needs Workers Paid and
      // R2, and whether a Free account can make the mind's token is not known
      // (tasks/iterate-cloud/designs/phased-deploy.md, "Not known yet")
      const free = !(s.waits.payment && s.waits.r2);
      const config = configOf({
        name,
        accountId,
        zone: undefined,
        ownerEmails: [owner],
        trustedClients: undefined,
        keys: s.cloud?.keys,
        cloudOrigin: s.cloud?.origin,
        telemetry: false,
        cloudflareToken: false,
        mind: { containers: false },
        cloudflarePlan: free ? "free" : undefined,
      });
      return { env, files: { "/work/mind.config.json": `${JSON.stringify(config, null, 2)}\n` } };
    }
    const zone = s.choices.domain.zone;
    this.#first = await firstOwnerTicket(owner);
    s.ownerLink = null;
    const config = configOf({
      name,
      accountId,
      zone,
      ownerEmails: [owner],
      trustedClients: undefined,
      keys: s.cloud?.keys,
      cloudOrigin: s.cloud?.origin,
      telemetry: s.grant.telemetry,
      cloudflareToken: s.grant.cloudflareToken,
      mind: { images: {} },
      cloudflarePlan: undefined,
    });
    return {
      env: {
        ...env,
        ITERATE_ZONE: zone,
        ITERATE_ZONE_ID: s.zoneId,
        ITERATE_FIRST_OWNER_TICKET: this.#first.variable,
        ITERATE_WORKERS_DEV: "1",
        ...(s.grant.telemetry && { ITERATE_TELEMETRY: "1" }),
        ...(s.grant.cloudflareToken && { ITERATE_CLOUDFLARE_TOKEN: "1" }),
      },
      files: { "/work/mind.config.json": `${JSON.stringify(config, null, 2)}\n` },
      zone,
    };
  }

  /** A phase's process ended with `exit`. */
  async ended(s, phase, { exit, lines }) {
    const now = this.now();
    if (this.#retired) {
      await this.giveUpToken(this.#retired);
      this.#retired = null;
    }
    this.#phaseToken = null;
    s.running = null;
    s.current = [];
    s.lines = keptLines([...s.lines, `== phase ${phase}`, ...lines], 400);
    const worked = exit === "0";
    const said = lines.filter((l) => /^Stopped: |^The .* failed|did not/.test(l)).at(-1);
    if (phase !== "deploy") {
      s.phases[phase] = {
        state: worked ? "done" : "failed",
        startedAt: s.phases[phase].startedAt,
        endedAt: now,
        ...(!worked && {
          note: `${said || `It ended with ${exit}.`} The deploy does this work again.`,
        }),
      };
      return;
    }
    if (!worked) {
      s.phases.deploy = {
        state: "failed",
        startedAt: s.phases.deploy.startedAt,
        endedAt: now,
        note: said || `The deploy ended with ${exit}.`,
      };
      this.#first = null;
      if (this.#token) await this.giveUpToken(this.#token);
      this.#token = null;
      s.tokenEndsAt = null;
      await this.runner.stop();
      if (s.attempts.deploy >= MAX_DEPLOYS) s.failed = true;
      return;
    }
    s.phases.deploy = { state: "done", startedAt: s.phases.deploy.startedAt, endedAt: now };
    s.phases.finish = { state: "running", startedAt: now };
    const zone = s.choices.domain.zone;
    let finishNote;
    if (this.#token) {
      const gave = await giveUp({
        token: this.#token,
        accountId: s.choices.accountId,
        clientId: this.env.CLIENT_ID,
        clientSecret: this.env.CLIENT_SECRET,
        revokeUrl: this.env.CF_REVOKE,
        api: this.env.CF_API,
        fetch: this.fetch,
      });
      this.#token = null;
      s.forgot = { revoke: gave.revoke, probe: gave.probe, works: gave.works };
      if (gave.works)
        finishNote =
          "Cloudflare still answers the run's token after the revoke. Remove “Iterate Cloud” in the Cloudflare dashboard: your profile, Access Management, Connected Applications.";
    }
    s.tokenEndsAt = null;
    await this.runner.stop();
    s.phases.finish = {
      state: finishNote ? "failed" : "done",
      startedAt: now,
      endedAt: this.now(),
      note: finishNote,
    };
    s.result = {
      url: `https://${zone}/`,
      issuer: `https://iterate.${zone}`,
      commit: lines.map((l) => /^stack ([0-9a-f]{40})$/.exec(l)?.[1]).find(Boolean) || null,
      cloudflareConnection: connectionAfter(lines, {}).connection === true,
    };
    s.ownerLink = this.#first ? "ready" : "lost";
    if (lines.some((l) => l.startsWith("No first-passkey link:"))) {
      this.#first = null;
      s.ownerLink = "lost";
    }
  }

  async schedule(s) {
    const now = this.now();
    const times = [];
    if (s.running) times.push(now + 10_000);
    // a token that leaves out the run's account polls nothing: only its end wakes the object
    else if (this.#token && s.choices.accountId && !s.accountUncovered)
      times.push(Math.max(s.poll.next, now + 1000));
    if (this.#token && s.tokenEndsAt) times.push(s.tokenEndsAt + 1000);
    if (times.length) await this.storage.setAlarm(Math.min(...times));
  }

  async giveUpToken(token) {
    await revoke({
      token,
      clientId: this.env.CLIENT_ID,
      clientSecret: this.env.CLIENT_SECRET,
      revokeUrl: this.env.CF_REVOKE,
      fetch: this.fetch,
    });
  }

  /** A call of Cloudflare's API with the token: its JSON with `status`. Never throws. */
  async cf(method, path, body) {
    if (!this.#token) return { success: false, status: 0, errors: [] };
    try {
      const answer = await this.fetch(
        `${this.env.CF_API || "https://api.cloudflare.com/client/v4"}${path}`,
        {
          method,
          headers: {
            authorization: `Bearer ${this.#token}`,
            ...(body && { "content-type": "application/json" }),
          },
          body: body ? JSON.stringify(body) : undefined,
        },
      );
      const data = await answer.json().catch(() => ({ success: false }));
      return { ...data, status: answer.status };
    } catch (error) {
      return { success: false, status: 0, errors: [{ message: String(error?.message || error) }] };
    }
  }

  // ── what the status says ─────────────────────────────────────────────────────────────────────

  waitingOf(s) {
    if (isOver(s)) return null;
    if (!s.choices.name) return "name";
    if (s.phases.consent.state !== "done") return "consent";
    // `prep` and `early` run while the person does their part: what they wait for is said
    if (s.running?.phase === "deploy") return null;
    if (!this.#token || s.accountUncovered) return "fresh-consent";
    if (!s.choices.accountId) return "account";
    for (const id of ["payment", "r2", "domain"]) if (s.waits[id] === false) return id;
    if (s.waits.payment === null) return null;
    const left = (s.tokenEndsAt || 0) - this.now();
    if (s.phases.deploy.state === "pending" && left < LEFT_FOR.deploy) return "fresh-consent";
    return null;
  }

  /** Why a fresh consent is the next thing: the account left out, a failed deploy, or the token. */
  freshConsentDetailOf(s) {
    if (s.accountUncovered && this.#token)
      return "This consent did not cover the account the run started in. Connect again, and tick that account.";
    if (s.phases.deploy.state === "failed")
      return `The deploy failed: ${s.phases.deploy.note} A fresh consent tries again (try ${s.attempts.deploy + 1} of ${MAX_DEPLOYS}).`;
    if (this.#token)
      return "The access to Cloudflare ends too soon for the deploy, which needs 30 minutes. A fresh consent goes on where the run stands.";
    return "The access to Cloudflare ended. A fresh consent goes on where the run stands: nothing done is done again.";
  }

  detailOf(s) {
    const account = s.accounts.find((a) => a.id === s.choices.accountId)?.name || "the account";
    switch (this.waitingOf(s)) {
      case "name":
        return "Choose the mind's name.";
      case "consent":
        return s.detail || "Connect Cloudflare: the run starts at the consent.";
      case "fresh-consent":
        return this.freshConsentDetailOf(s);
      case "account":
        return "The consent covered several accounts: pick the one for this mind.";
      case "payment":
        return `Workers Paid is not on in “${account}” yet. The mind runs its code with it, and its sandboxes in Containers, which need it too.`;
      case "r2":
        return `R2 is not on in “${account}” yet. iterate keeps its files there.`;
      case "domain":
        if (!s.choices.domain)
          return "Choose a domain: one in the account, or buy one on the domain page.";
        return s.zoneState === "missing"
          ? `${s.choices.domain.zone} is not in “${account}” yet.`
          : `${s.choices.domain.zone} is in the account, and not active yet (${s.zoneState}): its nameservers must point at Cloudflare.`;
    }
    if (s.failed) return `The deploy failed ${MAX_DEPLOYS} times: ${s.phases.deploy.note}`;
    return null;
  }

  statusOf(s) {
    const scrub = (line) => {
      const text = this.#token ? line.replaceAll(this.#token, "[token]") : line;
      return text.replace(/[A-Za-z0-9_-]{40,}/g, "[hidden]");
    };
    const lines = s.running ? [...s.lines, ...s.current] : s.lines;
    const phases = PHASES.map(({ id, label }) => ({ id, label, ...s.phases[id] }));
    // a failed prep or early deploy is a note: the deploy does that work again
    const open = phases.find(
      (p) =>
        p.state !== "done" &&
        p.state !== "skipped" &&
        !(p.state === "failed" && (p.id === "prep" || p.id === "early")),
    );
    return {
      installation: s.id,
      deployment: s.deployment,
      email: s.email,
      // a deployed mind is done, also when giving up the access failed (`phases` says so)
      phase: s.failed ? "failed" : s.result || s.deployedAt || !open ? "done" : open.id,
      waiting: this.waitingOf(s),
      detail: this.detailOf(s) ?? s.detail,
      phases,
      waits: { ...s.waits },
      choices: { ...s.choices, ownerEmail: s.choices.ownerEmail || s.email },
      account: s.accounts.find((a) => a.id === s.choices.accountId) || null,
      accounts: s.accounts,
      zones: s.zones,
      telemetry: s.telemetry,
      tokenEndsAt: this.#token ? s.tokenEndsAt : null,
      attempts: { deploy: s.attempts.deploy, max: MAX_DEPLOYS },
      asked: (s.asked || []).slice(-10),
      // a deployment made elsewhere that the app tied to this installation (`deployedElsewhere`)
      deployedAt: s.deployedAt ? { zone: s.deployedAt.zone, at: s.deployedAt.at } : null,
      log: lines.slice(-60).map(scrub),
      result: s.result
        ? {
            url: s.result.url,
            issuer: s.result.issuer,
            enrolled: null,
            // the ticket was in memory alone: an object that restarted has lost it
            ownerLink: s.ownerLink === "ready" && !this.#first ? "lost" : s.ownerLink,
          }
        : null,
      updatedAt: s.updatedAt,
    };
  }

  /** What `kept()` lists for an installation's object. */
  static RECORDS = {
    install:
      "A chat installation: the Cloudflare user id and email it is for, the person's choices (name, account, domain, owner email, telemetry), the state of each phase, the last 400 lines of the run's log, the hashes of its browser sessions and its single-use links while they live, and when the access to Cloudflare ends. No token and no ticket.",
  };
}

/** The resources of a deploy's log: Alchemy's `[<Id>] <verb>` and the pretend run's
 *  `+ <name>  <kind>  <verb>`. The newest verb of each wins. */
function resourcesOf(lines) {
  const found = new Map();
  for (const line of lines) {
    const alchemy = /\[([A-Za-z][A-Za-z0-9_.:-]*)\]\s+([a-z]+)/i.exec(line);
    const pretend = /^\+ (\S+)\s+(Cloudflare\.\S+)\s+(.+)$/.exec(line);
    const [id, kind, verb] = alchemy
      ? [alchemy[1], null, alchemy[2]]
      : pretend
        ? [pretend[1], pretend[2], pretend[3]]
        : [];
    if (!id) continue;
    found.set(id, { id, kind: kind || found.get(id)?.kind || null, state: stateOfVerb(verb) });
  }
  return [...found.values()];
}
const stateOfVerb = (verb) => {
  const v = verb.toLowerCase();
  if (/fail|error/.test(v)) return "failed";
  if (
    /^(created|updated|deleted|replaced|uploaded|pushed|enabled|done|ok|unchanged|noop|skipped|image pushed)/.test(
      v,
    )
  )
    return "ok";
  if (/^(plan|pending|wait)/.test(v)) return "planned";
  return "creating";
};

/** The results of a domain search, in the wizard's shape (index.js `domainsOf`). */
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",
  }));
}