iterate.com / cloud

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

cloud / internal-packages / installer / test / installations.mjsmain at aacbc74

// installations.mjs — A CHAT INSTALLATION, END TO END IN NODE: the Worker (index.js, service.js),
// the installation's state machine (installation.js) with its phases acted out
// (installation-pretend.js), and the pretend Cloudflare (pretend/world.js), on a clock the test
// moves. A browser is played by hand: cookies, Origin, the consent form.
// Run: node test/installations.mjs
import assert from "node:assert/strict";
import { test } from "node:test";
import { MindConfig } from "../../../core/alchemy/src/config.ts";
import { handle as cloudflare, newWorld, worldFor } from "../pretend/world.js";
import worker from "../worker/index.js";
import { Installation, MAX_DEPLOYS, MAX_PER_OWNER } from "../worker/installation.js";
import { pretendRunner } from "../worker/installation-pretend.js";
import { handle as service } from "../worker/service.js";
import { TELEMETRY_SCOPE } from "../worker/scopes.js";

const CLOUD = "http://cloud.test";
const CF = "http://cf.test";
const SERVICE_TOKEN = "service-token-for-the-test-0123456789abcdef0123456789";
const SECOND = 1000;
const MINUTE = 60 * SECOND;
const realNow = Date.now;

/** One Cloud, one pretend Cloudflare, one clock. */
function setup({ world, site = false } = {}) {
  // the Worker reads Date.now too (a token's end): one clock for all
  const clock = { now: realNow() };
  Date.now = () => clock.now;
  const minted = [];
  const deployed = [];
  const launched = [];
  // the stack's config that each phase was given, by phase (installation.js `inputOf`)
  const configs = {};
  const stopped = [];
  world ||= newWorld({
    user: { email: "ada@example.com", first: "Ada", last: "Lovelace" },
    accounts: [{ id: "a".repeat(32), name: "Ada's account" }],
  });
  const cfFetch = async (input, init) => {
    const request = new Request(input, init);
    if (new URL(request.url).pathname === "/_pretend/deployed") deployed.push(request.url);
    return cloudflare(world, request, {
      now: clock.now,
      testControls: true,
      mint: () => {
        const token = `tok_${crypto.randomUUID().replaceAll("-", "")}_${minted.length}`;
        minted.push(token);
        return token;
      },
    });
  };
  const rows = new Map();
  const SESSIONS = {
    get: async (key) => rows.get(key) ?? null,
    put: async (key, value) => void rows.set(key, value),
    delete: async (key) => void rows.delete(key),
  };
  const objects = new Map();
  const held = { on: false };
  const failing = new Set();
  const env = {
    SESSIONS,
    SERVICE_TOKEN,
    CLIENT_ID: "pretend-client",
    CLIENT_SECRET: "fake-secret",
    CF_API: `${CF}/client/v4`,
    CF_AUTH: `${CF}/oauth2/auth`,
    CF_TOKEN: `${CF}/oauth2/token`,
    CF_REVOKE: `${CF}/oauth2/revoke`,
    CF_DASH: `${CF}/dash/`,
    CF_SERVICE: { fetch: cfFetch },
    ...(site && { CF_SITE: CF }),
  };
  /** A Durable Object of the installation: its storage outlives `evict`, its memory does not. */
  const objectOf = (name) => {
    let o = objects.get(name);
    if (!o) {
      const data = new Map();
      o = { data, alarm: null };
      objects.set(name, o);
    }
    if (!o.installation) {
      const runner = pretendRunner({
        fetch: cfFetch,
        api: env.CF_API,
        site: CF,
        now: () => clock.now,
      });
      const storage = {
        get: async (key) => structuredClone(o.data.get(key)),
        put: async (key, value) => void o.data.set(key, structuredClone(value)),
        delete: async (key) => void o.data.delete(key),
        setAlarm: async (at) => void (o.alarm = at),
        deleteAlarm: async () => void (o.alarm = null),
      };
      o.installation = new Installation({
        storage,
        env,
        fetch: cfFetch,
        now: () => clock.now,
        runner: {
          launch: (phase, input) => {
            launched.push(phase);
            const config = input.files["/work/mind.config.json"];
            if (config) configs[phase] = JSON.parse(config);
            return runner.launch(phase, input);
          },
          // `held`: the phase does not end; `failing`: these phases end with exit 1
          poll: async (phase, running) => {
            if (held.on) return { done: false, lines: [] };
            const seen = await runner.poll(phase, running);
            return seen.done && failing.has(phase) ? { ...seen, exit: "1" } : seen;
          },
          stop: async () => void stopped.push(clock.now),
        },
      });
    }
    return o;
  };
  env.DEPLOYER = {
    getByName: (name) => ({
      install: async (op, args) => structuredClone(await objectOf(name).installation[op](args)),
    }),
  };
  const fetchCloud = (request) =>
    new URL(request.url).pathname.startsWith("/service/")
      ? service(request, env)
      : worker.fetch(request, env);

  /** The service API, as the app calls it. */
  const api = async (method, path, body) => {
    const answer = await fetchCloud(
      new Request(`${CLOUD}${path}`, {
        method,
        headers: {
          authorization: `Bearer ${SERVICE_TOKEN}`,
          ...(body !== undefined && { "content-type": "application/json" }),
        },
        body: body === undefined ? undefined : JSON.stringify(body),
      }),
    );
    return { status: answer.status, body: await answer.json().catch(() => null) };
  };

  /** A browser: its cookies, per host. */
  const browser = () => {
    const jar = new Map();
    const go = async (url, { method = "GET", form, origin } = {}) => {
      const target = new URL(url, CLOUD);
      const cookies = [...jar.entries()]
        .filter(([key]) => key.startsWith(`${target.host}|`))
        .map(([key, value]) => `${key.split("|")[1]}=${value}`)
        .join("; ");
      const headers = {
        ...(cookies && { cookie: cookies }),
        ...(form && { "content-type": "application/x-www-form-urlencoded" }),
        ...(method !== "GET" && { origin: origin ?? target.origin }),
      };
      const request = new Request(target, {
        method,
        headers,
        body: form ? new URLSearchParams(form).toString() : undefined,
        redirect: "manual",
      });
      const answer = target.origin === CF ? await cfFetch(request) : await fetchCloud(request);
      for (const line of answer.headers.getSetCookie?.() || []) {
        const [pair, ...rest] = line.split(";");
        const [name, value] = pair.split("=");
        const gone = rest.some((p) => /max-age=0/i.test(p));
        if (gone) jar.delete(`${target.host}|${name.trim()}`);
        else jar.set(`${target.host}|${name.trim()}`, value);
      }
      return answer;
    };
    return { go, jar };
  };

  /** Presses Authorize on the pretend Cloudflare's consent page. `untick`: scopes left out. */
  const authorize = async (b, auth, { untick = [] } = {}) => {
    const asked = new URL(auth);
    const scope = asked.searchParams.get("scope");
    const form = new URLSearchParams({
      client_id: asked.searchParams.get("client_id"),
      redirect_uri: asked.searchParams.get("redirect_uri"),
      state: asked.searchParams.get("state"),
      scope,
      grants: "1",
    });
    for (const a of world.accounts) form.append("account", a.id);
    for (const x of scope.split(" ")) if (!untick.includes(x)) form.append("grant", x);
    const back = await cfFetch(
      new Request(`${CF}/oauth2/consent`, {
        method: "POST",
        body: form,
        headers: { "content-type": "application/x-www-form-urlencoded" },
      }),
    );
    return b.go(back.headers.get("location"));
  };

  /** Mints a link of `kind` and follows it in browser `b` to Cloudflare's consent, and back. */
  const consent = async (id, b, options) => {
    const link = await api("POST", `/service/installations/${id}/links`, { kind: "consent" });
    assert.equal(link.status, 200, JSON.stringify(link.body));
    const out = await b.go(link.body.url);
    assert.equal(out.status, 302);
    return authorize(b, out.headers.get("location"), options);
  };

  /** Moves the clock and lets the object's alarm run, as often as it is due. */
  const tick = async (id, ms, step = 2 * SECOND) => {
    const o = objectOf(`inst:${id}`);
    const until = clock.now + ms;
    while (clock.now < until) {
      clock.now = Math.min(until, clock.now + step);
      if (o.alarm !== null && o.alarm <= clock.now) {
        o.alarm = null;
        await o.installation.alarm();
      }
    }
  };
  const evict = (id) => void (objectOf(`inst:${id}`).installation = null);
  /** The installation's record as its object stores it. */
  const stored = (id) => objectOf(`inst:${id}`).data;
  const alarmOf = (id) => objectOf(`inst:${id}`).alarm;
  const status = async (id) => (await api("GET", `/service/installations/${id}`)).body;

  return {
    world,
    env,
    held,
    failing,
    clock,
    minted,
    deployed,
    launched,
    configs,
    stopped,
    api,
    browser,
    consent,
    authorize,
    tick,
    evict,
    stored,
    alarmOf,
    status,
    rows,
  };
}

/** The app's deployment `deployment`, of the owner with `email` (the world's user's by default). */
const newInstallation = async (t, { deployment = "dep-1", email = t.world.user.email } = {}) => {
  const made = await t.api("POST", "/service/installations", {
    deployment,
    owner: { email, userId: "app-user-1" },
  });
  assert.equal(made.status, 200, JSON.stringify(made.body));
  return made.body.installation;
};

/** Neither a token nor a ticket nor a secret is in what the app sees. */
const assertClean = (t, value, extra = []) => {
  const text = JSON.stringify(value);
  for (const secret of [...t.minted, SERVICE_TOKEN, "fake-secret", ...extra])
    assert.equal(text.includes(secret), false, `a secret is in ${text.slice(0, 200)}…`);
};

test("an installation is one per deployment: the same on every call, of its first owner alone", async () => {
  const t = setup();
  const one = await newInstallation(t);
  assert.match(one, /^inst_[a-z2-7]{26}$/);
  // the email is trimmed and lowercased
  const again = await t.api("POST", "/service/installations", {
    deployment: "dep-1",
    owner: { email: " Ada@Example.com ", userId: "app-user-1" },
  });
  assert.deepEqual(again.body, { installation: one, deployment: "dep-1", created: false });
  const other = await t.api("POST", "/service/installations", {
    deployment: "dep-1",
    owner: { email: "bob@example.com", userId: "app-user-2" },
  });
  assert.deepEqual([other.status, other.body.field], [409, "owner"]);
  assert.notEqual(await newInstallation(t, { deployment: "dep-2" }), one);
  const s = await t.status(one);
  assert.deepEqual([s.email, s.deployment], ["ada@example.com", "dep-1"]);
});

test("an owner's address at the chosen domain is refused on the field that changed, before any deploy", async () => {
  const t = setup();
  const id = await newInstallation(t);
  const choose = (changes) => t.api("PATCH", `/service/installations/${id}/choices`, changes);
  // the owner is the person's own email, ada@example.com: the domain and a name under it are refused
  for (const zone of ["example.com", "Example.com"]) {
    const at = await choose({ domain: { zone } });
    assert.deepEqual([at.status, at.body.field], [400, "domain"]);
    assert.equal(
      at.body.error,
      "ada@example.com is an address at example.com, and a mind receives the mail of its own domain: its owner signs in with an address somewhere else. Choose another domain.",
    );
  }
  // a domain under the owner's, or one that only ends with the same letters, is not the owner's
  for (const zone of ["labs.example.com", "notexample.com"])
    assert.equal((await choose({ domain: { zone } })).status, 200, zone);
  // another owner at the chosen domain, or under it, is refused on the owner's field
  for (const ownerEmail of ["bob@notexample.com", "bob@mail.notexample.com"]) {
    const at = await choose({ ownerEmail });
    assert.deepEqual([at.status, at.body.field], [400, "ownerEmail"]);
  }
  // both in one change: the domain's field; the domain sent again unchanged: the owner's field
  const both = await choose({ ownerEmail: "bob@ada.dev", domain: { zone: "ada.dev" } });
  assert.deepEqual([both.status, both.body.field], [400, "domain"]);
  const same = await choose({
    domain: { zone: "notexample.com" },
    ownerEmail: "bob@notexample.com",
  });
  assert.deepEqual([same.status, same.body.field], [400, "ownerEmail"]);
  // nothing of the refused changes was kept
  const s = await t.status(id);
  assert.deepEqual(
    [s.choices.domain, s.choices.ownerEmail],
    [{ zone: "notexample.com" }, "ada@example.com"],
  );
});

test("a domain at the owner's address is not bought", async () => {
  const t = setup();
  const id = await newInstallation(t);
  await t.api("PATCH", `/service/installations/${id}/choices`, { name: "ada-labs" });
  await t.consent(id, t.browser());
  const installation = t.env.DEPLOYER.getByName(`inst:${id}`);
  const bought = await installation.install("domainBuy", {
    domain: "example.com",
    confirm: "example.com",
  });
  assert.deepEqual(bought, {
    ok: false,
    error:
      "ada@example.com is an address at example.com, and a mind receives the mail of its own domain: its owner signs in with an address somewhere else. Choose another domain.",
  });
  // the refusal came before the registrar (whose answer would be another error), and the
  // installation has no domain
  assert.equal(t.stored(id).get("install").purchased, null);
  assert.equal((await t.status(id)).choices.domain, null);
});

test("an owner has at most 10 installations; asking again for one of them still works", async () => {
  const t = setup();
  for (let i = 1; i <= MAX_PER_OWNER; i++) await newInstallation(t, { deployment: `d${i}` });
  const over = await t.api("POST", "/service/installations", {
    deployment: "d11",
    owner: { email: "ada@example.com", userId: "app-user-1" },
  });
  assert.deepEqual([over.status, over.body.field], [409, "owner"]);
  assert.equal(over.body.error, "An owner has at most 10 installations.");
  await newInstallation(t, { deployment: "d3" });
  // another owner has their own ten
  await newInstallation(t, { deployment: "d11", email: "bob@example.com" });
});

test("the run starts at the consent, with no domain and no payment, and goes on by itself through each wait", async () => {
  const world = worldFor("ada+auto@example.com", "f".repeat(32));
  // someone else has the first name from the owner's email: the run takes the second
  world.takenSubdomains.push("iterate-ada-example");
  const t = setup({ world, site: true });
  const id = await newInstallation(t);
  let s = await t.status(id);
  assert.equal(s.waiting, "name");
  // nothing opens before its time
  for (const kind of ["consent", "card", "domain", "owner"])
    assert.equal((await t.api("POST", `/service/installations/${id}/links`, { kind })).status, 409);
  assert.equal(
    (await t.api("PATCH", `/service/installations/${id}/choices`, { name: "ada-labs" })).status,
    200,
  );
  assert.equal((await t.status(id)).waiting, "consent");

  const b = t.browser();
  const back = await t.consent(id, b);
  assert.equal(back.status, 302);
  assert.equal(back.headers.get("location"), `/i/${id}/connected`);
  s = await t.status(id);
  // started: the prep phase runs with no domain chosen and no Workers Paid
  assert.equal(s.phases.find((p) => p.id === "prep").state, "running");
  assert.equal(s.choices.domain, null);
  assert.equal(s.waits.payment, false);
  // the person's part is said while the run gets ready
  assert.equal(s.waiting, "payment");
  assert.equal(s.telemetry, "on");
  assert.equal(s.account.id, world.accounts[0].id);
  assert.deepEqual(t.launched, ["prep"]);
  assertClean(t, s);

  await t.tick(id, 12 * SECOND);
  s = await t.status(id);
  assert.equal(s.phases.find((p) => p.id === "prep").state, "done");
  assert.ok(
    // the second name from the owner's email (ada+auto@example.com): account-name.js
    s.log.some((l) => l.startsWith("workers.dev: made iterate-ada-example-uwd2ra.workers.dev")),
    s.log.join("\n"),
  );
  // then at once the stack before its domain, on what a Free account takes
  assert.equal(s.phases.find((p) => p.id === "early").state, "running");
  assert.equal(s.waiting, "payment");
  assert.deepEqual(t.launched, ["prep", "early"]);
  const early = t.configs.early;
  assert.deepEqual(MindConfig.parse(early), early);
  assert.deepEqual(
    [early.domain, early.cloudflarePlan, early.mind, early.mail, early.telemetry],
    [undefined, "free", { containers: false }, undefined, undefined],
  );
  assert.deepEqual(early.auth.login.allow, [{ email: "ada+auto@example.com" }]);
  // that stack names the owner: from now on the owner stays
  const otherOwner = await t.api("PATCH", `/service/installations/${id}/choices`, {
    ownerEmail: "bob@example.com",
  });
  assert.deepEqual([otherOwner.status, otherOwner.body.field], [409, "ownerEmail"]);
  // the owner that the status names, sent back unchanged, is no change
  const sameOwner = await t.api("PATCH", `/service/installations/${id}/choices`, {
    ownerEmail: s.choices.ownerEmail,
  });
  assert.equal(sameOwner.status, 200, JSON.stringify(sameOwner.body));
  await t.tick(id, 10 * SECOND);
  s = await t.status(id);
  assert.equal(s.phases.find((p) => p.id === "early").state, "done");
  assert.ok(
    s.log.includes(
      "The stack iterate-ada-labs is deployed before its domain: the deploy at the domain gives it the rest.",
    ),
    s.log.join("\n"),
  );

  // Workers Paid and R2 come on in the auto world, and the run waits for the domain
  await t.tick(id, 60 * SECOND);
  s = await t.status(id);
  assert.deepEqual([s.waits.payment, s.waits.r2], [true, true]);
  assert.equal(s.waiting, "domain");
  assert.deepEqual(s.zones, ["ada-labs.com"]);

  // the domain: not in the account is refused, the one there is taken, and the deploy starts
  const wrong = await t.api("PATCH", `/service/installations/${id}/choices`, {
    domain: { zone: "elsewhere.com" },
  });
  assert.deepEqual([wrong.status, wrong.body.field], [400, "domain"]);
  const platform = await t.api("PATCH", `/service/installations/${id}/choices`, {
    domain: { zone: "iterate.ada-labs.com" },
  });
  assert.deepEqual([platform.status, platform.body.field], [400, "domain"]);
  s = (
    await t.api("PATCH", `/service/installations/${id}/choices`, {
      domain: { zone: "ada-labs.com" },
    })
  ).body;
  assert.equal(s.phases.find((p) => p.id === "deploy").state, "running");
  assert.equal(
    (
      await t.api("PATCH", `/service/installations/${id}/choices`, {
        domain: { zone: "other.com" },
      })
    ).status,
    409,
  );
  assert.equal(
    (await t.api("PATCH", `/service/installations/${id}/choices`, { name: "other" })).status,
    409,
  );

  await t.tick(id, 40 * SECOND);
  s = await t.status(id);
  assert.equal(s.phase, "done", JSON.stringify(s.phases));
  assert.deepEqual(s.result, {
    url: "https://ada-labs.com/",
    issuer: "https://iterate.ada-labs.com",
    enrolled: true,
    ownerLink: "ready",
  });
  // the access is given up, and the deployment exists once
  assert.deepEqual(Object.keys(world.tokens), []);
  assert.equal(t.deployed.length, 1);
  assert.deepEqual(t.launched, ["prep", "early", "deploy"]);
  // the tail: the same stack with its domain and mail, and sandboxes with no named image
  const tail = t.configs.deploy;
  assert.deepEqual(MindConfig.parse(tail), tail);
  assert.deepEqual(
    [tail.domain, tail.cloudflarePlan, tail.mind, tail.mail, tail.telemetry],
    ["ada-labs.com", undefined, { images: {} }, true, true],
  );
  const resources = (await t.api("GET", `/service/installations/${id}/resources`)).body.resources;
  assert.ok(
    resources.some((r) => r.id === "iterate-ada-labs-mind" && r.state === "ok"),
    JSON.stringify(resources),
  );

  // the owner's link: once, in the browser that consented, and never in what the app sees
  // `owner-link` is the app's word for `owner`
  const owner = await t.api("POST", `/service/installations/${id}/links`, { kind: "owner-link" });
  assert.match(owner.body.url, new RegExp(`/i/${id}/owner\\?n=`));
  assert.equal(owner.status, 200);
  const first = await b.go(owner.body.url);
  assert.equal(first.status, 302);
  const followed = await b.go(first.headers.get("location"));
  const location = followed.headers.get("location");
  assert.match(
    location,
    new RegExp(`^${CF}/site/iterate\\.ada-labs\\.com/keys/first#[A-Za-z0-9_-]{43}$`),
  );
  const ticket = location.split("#")[1];
  s = await t.status(id);
  assert.equal(s.result.ownerLink, "used");
  assertClean(t, s, [ticket]);
  assertClean(t, (await t.api("GET", `/service/installations/${id}/resources`)).body, [ticket]);
  assert.equal(
    (await t.api("POST", `/service/installations/${id}/links`, { kind: "owner" })).status,
    409,
  );

  // the handover: of this installation's own domain, after it is deployed
  const handed = await t.api("POST", "/service/handover", {
    deployment: "dep-1",
    summary: "A family mind.",
    domain: "evil.com",
  });
  assert.equal(handed.status, 200);
  assert.equal(handed.body.ok, true);

  // the app may tie the Cloud's own deployment too; forgetting the installation frees its zone
  const zone = s.result.url.replace(/^https:\/\/|\/$/g, "");
  assert.equal(
    (await t.api("POST", `/service/installations/${id}/deployed`, { domain: zone })).status,
    200,
  );
  const other = await newInstallation(t, { deployment: "dep-2" });
  const taken = await t.api("POST", `/service/installations/${other}/deployed`, { domain: zone });
  assert.equal(taken.status, 409);
  assert.equal((await t.api("DELETE", `/service/installations/${id}`)).status, 200);
  assert.equal(
    (await t.api("POST", `/service/installations/${other}/deployed`, { domain: zone })).status,
    200,
  );
});

test("the token runs out while the run waits for payment; a fresh consent resumes the same installation, and nothing done is done again", async () => {
  const t = setup({ site: true });
  const id = await newInstallation(t);
  await t.api("PATCH", `/service/installations/${id}/choices`, { name: "ada-labs" });
  const b = t.browser();
  await t.consent(id, b);
  await t.tick(id, 25 * SECOND);
  let s = await t.status(id);
  const prep = s.phases.find((p) => p.id === "prep");
  const early = s.phases.find((p) => p.id === "early");
  assert.deepEqual([prep.state, early.state], ["done", "done"]);
  assert.equal(s.waiting, "payment");

  // an hour later: the token is over, the container goes, and the run waits for a fresh consent
  await t.tick(id, 61 * MINUTE, 30 * SECOND);
  s = await t.status(id);
  assert.equal(s.waiting, "fresh-consent");
  assert.equal(s.tokenEndsAt, null);
  assert.ok(t.stopped.length > 0);
  // the person paid, turned R2 on and has a domain meanwhile
  const account = t.world.accounts[0];
  Object.assign(account, { paid: true, card: true, r2: true });
  t.world.zones.push({
    id: "z".repeat(32),
    name: "ada-labs.com",
    account: account.id,
    status: "active",
    nameServers: [],
    pointed: true,
    at: 0,
  });
  await t.api("PATCH", `/service/installations/${id}/choices`, {
    domain: { zone: "ada-labs.com" },
  });

  // this object restarted meanwhile too: what is stored is enough
  t.evict(id);
  await t.consent(id, t.browser());
  s = await t.status(id);
  assert.equal(s.installation, id);
  assert.deepEqual(
    [s.phases.find((p) => p.id === "prep"), s.phases.find((p) => p.id === "early")],
    [prep, early],
  );
  assert.equal(s.phases.find((p) => p.id === "deploy").state, "running");
  await t.tick(id, 40 * SECOND);
  s = await t.status(id);
  assert.equal(s.phase, "done");
  assert.deepEqual(t.launched, ["prep", "early", "deploy"]);
  assert.equal(t.deployed.length, 1);
  assert.deepEqual(Object.keys(t.world.tokens), []);
  assertClean(t, s);
  // the owner's ticket was in memory alone
  t.evict(id);
  assert.equal((await t.status(id)).result.ownerLink, "lost");
});

test("a deploy needs 30 minutes of token: with less, the run waits for a fresh consent", async () => {
  const t = setup();
  const account = t.world.accounts[0];
  Object.assign(account, { paid: true, card: true, r2: true });
  t.world.zones.push({
    id: "z".repeat(32),
    name: "ada-labs.com",
    account: account.id,
    status: "active",
    nameServers: [],
    pointed: true,
    at: 0,
  });
  const id = await newInstallation(t);
  await t.api("PATCH", `/service/installations/${id}/choices`, { name: "ada-labs" });
  await t.consent(id, t.browser());
  await t.tick(id, 35 * MINUTE, 30 * SECOND);
  // chosen only now, with 25 minutes of token left
  await t.api("PATCH", `/service/installations/${id}/choices`, {
    domain: { zone: "ada-labs.com" },
  });
  const s = await t.status(id);
  assert.equal(s.waiting, "fresh-consent");
  assert.equal(s.phases.find((p) => p.id === "deploy").state, "pending");
  assert.match(s.detail, /30 minutes/);
  // with Workers Paid and R2 on, the stack before its domain had everything but the domain
  assert.equal(s.phases.find((p) => p.id === "early").state, "done");
  assert.equal("cloudflarePlan" in t.configs.early, false);
  assert.equal("domain" in t.configs.early, false);
  assert.deepEqual(MindConfig.parse(t.configs.early), t.configs.early);
});

test("an account that has Workers Paid, R2 and an active domain at the consent gets one deploy, as before", async () => {
  const t = setup({ site: true });
  const account = t.world.accounts[0];
  Object.assign(account, { paid: true, card: true, r2: true });
  t.world.zones.push({
    id: "z".repeat(32),
    name: "ada-labs.com",
    account: account.id,
    status: "active",
    nameServers: [],
    pointed: true,
    at: 0,
  });
  const id = await newInstallation(t);
  await t.api("PATCH", `/service/installations/${id}/choices`, {
    name: "ada-labs",
    domain: { zone: "ada-labs.com" },
  });
  await t.consent(id, t.browser());
  await t.tick(id, 12 * SECOND);
  let s = await t.status(id);
  assert.equal(s.phases.find((p) => p.id === "early").state, "skipped");
  assert.equal(s.phases.find((p) => p.id === "deploy").state, "running");
  await t.tick(id, 40 * SECOND);
  s = await t.status(id);
  assert.equal(s.phase, "done");
  assert.deepEqual(t.launched, ["prep", "deploy"]);
  assert.deepEqual(MindConfig.parse(t.configs.deploy), t.configs.deploy);
  assert.equal(t.configs.deploy.domain, "ada-labs.com");
  assert.deepEqual(t.configs.deploy.mind, { images: {} });
});

test("an installation stored before the phase `early` existed gets it: still to run while its deploy is, skipped after", async () => {
  const t = setup({ site: true });
  const account = t.world.accounts[0];
  Object.assign(account, { paid: true, card: true, r2: true });
  t.world.zones.push({
    id: "z".repeat(32),
    name: "ada-labs.com",
    account: account.id,
    status: "active",
    nameServers: [],
    pointed: true,
    at: 0,
  });
  const id = await newInstallation(t);
  await t.api("PATCH", `/service/installations/${id}/choices`, { name: "ada-labs" });
  const record = (s) => s.get("install");
  delete record(t.stored(id)).phases.early;
  t.evict(id);
  let s = await t.status(id);
  assert.equal(s.phases.find((p) => p.id === "early").state, "pending");
  assert.equal(s.phase, "consent");
  // one that is deployed shows nothing open
  await t.api("PATCH", `/service/installations/${id}/choices`, {
    domain: { zone: "ada-labs.com" },
  });
  await t.consent(id, t.browser());
  await t.tick(id, 60 * SECOND);
  delete record(t.stored(id)).phases.early;
  t.evict(id);
  s = await t.status(id);
  assert.equal(s.phases.find((p) => p.id === "early").state, "skipped");
  assert.equal(s.phase, "done");
});

test("a consent by a Cloudflare login of another email is refused, its token revoked, and the page names the owner's", async () => {
  const t = setup();
  const id = await newInstallation(t, { email: "grace@example.com" });
  await t.api("PATCH", `/service/installations/${id}/choices`, { name: "ada-labs" });
  const b = t.browser();
  const back = await t.consent(id, b);
  assert.equal(back.status, 403);
  const page = await back.text();
  assert.match(page, /grace@example\.com/);
  assert.match(page, new RegExp(`${CF}/dash/logout`));
  assert.deepEqual(Object.keys(t.world.tokens), []);
  const s = await t.status(id);
  assert.equal(s.waiting, "consent");
  assert.equal(s.tokenEndsAt, null);
  assert.deepEqual(t.launched, []);
  // the page's "Connect again" is a fresh consent link: as Grace, it connects
  const again = /href="(\/i\/[^"]+\/consent\?n=[^"]+)"/.exec(page)?.[1];
  assert.ok(again);
  t.world.user.email = "Grace@Example.com";
  const out = await b.go(again.replaceAll("&amp;", "&"));
  assert.equal(out.status, 302);
  const connected = await t.authorize(b, out.headers.get("location"));
  assert.equal(connected.status, 302);
  assert.equal(Object.keys(t.world.tokens).length, 1);
});

test("after the first consent, only that Cloudflare user may consent, also with the same email", async () => {
  const t = setup();
  const id = await newInstallation(t);
  await t.api("PATCH", `/service/installations/${id}/choices`, { name: "ada-labs" });
  assert.equal((await t.consent(id, t.browser())).status, 302);
  const before = Object.keys(t.world.tokens);
  t.world.user.id = "v".repeat(32);
  assert.equal((await t.consent(id, t.browser())).status, 403);
  assert.deepEqual(Object.keys(t.world.tokens), before);
});

test("a consent that Cloudflare refused says the tick, and the run can go on without telemetry", async () => {
  const t = setup();
  const id = await newInstallation(t);
  await t.api("PATCH", `/service/installations/${id}/choices`, { name: "ada-labs" });
  const b = t.browser();
  const link = await t.api("POST", `/service/installations/${id}/links`, { kind: "consent" });
  const out = await b.go(link.body.url);
  const auth = new URL(out.headers.get("location"));
  assert.ok(auth.searchParams.get("scope").split(" ").includes(TELEMETRY_SCOPE));
  const said = await b.go(
    `/callback?error=access_denied&error_description=${encodeURIComponent("This application requires a permission you have unchecked")}&state=${auth.searchParams.get("state")}`,
  );
  assert.equal(said.status, 200);
  assert.match(await said.text(), /Sensitive scopes/);
  let s = await t.status(id);
  assert.equal(s.telemetry, "refused");
  assert.match(s.detail, /Account API Tokens Write/);
  // "Go on without telemetry"
  await t.api("PATCH", `/service/installations/${id}/choices`, {
    telemetry: false,
    cloudflareConnection: false,
  });
  const again = await t.api("POST", `/service/installations/${id}/links`, { kind: "consent" });
  const next = new URL((await b.go(again.body.url)).headers.get("location"));
  assert.equal(next.searchParams.get("scope").split(" ").includes(TELEMETRY_SCOPE), false);
  await t.authorize(b, next.toString());
  s = await t.status(id);
  assert.equal(s.telemetry, "off");
});

test("a link works once, and the pages that spend money or hand over need the person's own browser", async () => {
  const t = setup();
  const id = await newInstallation(t);
  await t.api("PATCH", `/service/installations/${id}/choices`, { name: "ada-labs" });
  const b = t.browser();
  await t.consent(id, b);
  const account = t.world.accounts[0].id;

  // the dashboard's pages: a redirect, once
  const card = await t.api("POST", `/service/installations/${id}/links`, { kind: "card" });
  const went = await t.browser().go(card.body.url);
  assert.equal(
    went.headers.get("location"),
    `${CF}/dash/${account}/billing/subscriptions?paymentMethod=add`,
  );
  assert.equal((await t.browser().go(card.body.url)).status, 410);

  // the domain page: a stranger's browser with the link is sent to sign in as the user first
  const link = await t.api("POST", `/service/installations/${id}/links`, { kind: "domain" });
  const stranger = t.browser();
  const asked = await stranger.go(link.body.url);
  assert.equal(asked.status, 302);
  assert.equal(
    new URL(asked.headers.get("location")).searchParams.get("scope"),
    "user-details.read",
  );
  // and without a link, or from another site, nothing
  assert.equal((await t.browser().go(`/i/${id}/domain?q=ada`)).status, 403);
  assert.equal(
    (
      await t.browser().go(`/i/${id}/domain`, {
        method: "POST",
        form: { domain: "adanew.com", confirm: "adanew.com" },
      })
    ).status,
    403,
  );
  assert.equal(
    (
      await b.go(`/i/${id}/domain`, {
        method: "POST",
        origin: "https://evil.example",
        form: { domain: "adanew.com", confirm: "adanew.com" },
      })
    ).status,
    403,
  );
  assert.equal(Object.keys(t.world.registrations).length, 0);

  // the person's own browser: a search, a buy that is not typed again is refused, then one that is
  const page = await b.go(`/i/${id}/domain?q=adanew`);
  assert.equal(page.status, 200);
  assert.match(await page.text(), /adanew\.com/);
  const contact = {
    name: "Ada Lovelace",
    email: "ada@example.com",
    phone: "+44.7700900000",
    street: "1 St James's Square",
    city: "London",
    postal: "SW1Y 4JU",
    country: "GB",
  };
  const untyped = await b.go(`/i/${id}/domain`, {
    method: "POST",
    form: { domain: "adanew.com", confirm: "", ...contact },
  });
  assert.equal(untyped.status, 400);
  assert.equal(Object.keys(t.world.registrations).length, 0);
  t.world.accounts[0].card = true;
  const bought = await b.go(`/i/${id}/domain`, {
    method: "POST",
    form: { domain: "adanew.com", confirm: "adanew.com", ...contact },
  });
  assert.equal(bought.status, 200, await bought.clone().text());
  assert.deepEqual(Object.keys(t.world.registrations), [`${account}:adanew.com`]);
  assert.deepEqual((await t.status(id)).choices.domain, { zone: "adanew.com" });
});

test("a deploy that failed is tried again after a fresh consent, a bounded number of times", async () => {
  const t = setup();
  const account = t.world.accounts[0];
  Object.assign(account, { paid: true, card: true, r2: true });
  t.world.zones.push({
    id: "z".repeat(32),
    name: "broken-flaky.com",
    account: account.id,
    status: "active",
    nameServers: [],
    pointed: true,
    at: 0,
  });
  const id = await newInstallation(t);
  await t.api("PATCH", `/service/installations/${id}/choices`, {
    name: "ada-labs",
    domain: { zone: "broken-flaky.com" },
  });
  for (let attempt = 1; attempt <= MAX_DEPLOYS; attempt++) {
    await t.consent(id, t.browser());
    await t.tick(id, 60 * SECOND);
    const s = await t.status(id);
    assert.equal(s.phases.find((p) => p.id === "deploy").state, "failed");
    assert.equal(s.attempts.deploy, attempt);
    assert.deepEqual(Object.keys(t.world.tokens), []);
    if (attempt < MAX_DEPLOYS) {
      assert.equal(s.waiting, "fresh-consent");
      assert.match(s.detail, /deploy failed/);
    } else {
      assert.equal(s.phase, "failed");
      assert.equal(s.waiting, null);
      assert.equal(
        (await t.api("POST", `/service/installations/${id}/links`, { kind: "consent" })).status,
        409,
      );
    }
  }
  assert.equal(t.launched.filter((p) => p === "deploy").length, MAX_DEPLOYS);
});

test("the handover waits for the deploy, and names the installation's own domain", async () => {
  const t = setup({ site: true });
  const id = await newInstallation(t);
  const early = await t.api("POST", "/service/handover", { installation: id, summary: "Hello." });
  assert.equal(early.status, 409);
  assert.equal(
    (await t.api("POST", "/service/handover", { installation: "inst_x", summary: "Hello." }))
      .status,
    400,
  );
});

test("a fresh consent while a phase runs leaves that phase its token until it ends", async () => {
  const t = setup();
  const id = await newInstallation(t);
  await t.api("PATCH", `/service/installations/${id}/choices`, { name: "ada-labs" });
  await t.consent(id, t.browser());
  const first = Object.keys(t.world.tokens);
  assert.equal(first.length, 1);
  assert.equal((await t.status(id)).phases.find((p) => p.id === "prep").state, "running");
  await t.consent(id, t.browser());
  // both live: the running prep still has its own
  assert.equal(Object.keys(t.world.tokens).length, 2);
  assert.ok(first[0] in t.world.tokens);
  await t.tick(id, 12 * SECOND);
  assert.equal((await t.status(id)).phases.find((p) => p.id === "prep").state, "done");
  assert.deepEqual(
    Object.keys(t.world.tokens).filter((x) => x === first[0]),
    [],
  );
  assert.equal(Object.keys(t.world.tokens).length, 1);
});

test("a third consent while a phase runs gives up the unused second token at once, and the phase's at its end", async () => {
  const t = setup();
  const id = await newInstallation(t);
  await t.api("PATCH", `/service/installations/${id}/choices`, { name: "ada-labs" });
  await t.consent(id, t.browser());
  const [first] = Object.keys(t.world.tokens);
  await t.consent(id, t.browser());
  const [second] = Object.keys(t.world.tokens).filter((x) => x !== first);
  await t.consent(id, t.browser());
  // the second was never given to a phase: it goes now; the running prep keeps the first
  assert.ok(first in t.world.tokens);
  assert.ok(!(second in t.world.tokens));
  assert.equal(Object.keys(t.world.tokens).length, 2);
  await t.tick(id, 12 * SECOND);
  assert.ok(!(first in t.world.tokens));
  assert.equal(Object.keys(t.world.tokens).length, 1);
});

test("the token ends while a phase runs: that phase keeps it until it ends, and then it is revoked", async () => {
  const t = setup();
  const id = await newInstallation(t);
  await t.api("PATCH", `/service/installations/${id}/choices`, { name: "ada-labs" });
  await t.consent(id, t.browser());
  const [token] = Object.keys(t.world.tokens);
  const stops = t.stopped.length;
  t.held.on = true;
  const ends = (await t.status(id)).tokenEndsAt;
  await t.tick(id, ends - t.clock.now + 30 * SECOND, 10 * SECOND);
  // over, but the running phase still holds it: neither revoked nor its container stopped
  assert.ok(token in t.world.tokens);
  assert.equal(t.stopped.length, stops);
  assert.equal((await t.status(id)).tokenEndsAt, null);
  t.held.on = false;
  await t.tick(id, 20 * SECOND);
  assert.ok(!(token in t.world.tokens));
  assert.equal((await t.status(id)).waiting, "fresh-consent");
});

test("a failed prep or deploy before the domain is a note: the status's phase is the one that is open", async () => {
  const t = setup();
  t.failing.add("prep");
  t.failing.add("early");
  const id = await newInstallation(t);
  await t.api("PATCH", `/service/installations/${id}/choices`, { name: "ada-labs" });
  await t.consent(id, t.browser());
  await t.tick(id, 25 * SECOND);
  const s = await t.status(id);
  assert.equal(s.phases.find((p) => p.id === "prep").state, "failed");
  const early = s.phases.find((p) => p.id === "early");
  assert.equal(early.state, "failed");
  assert.match(early.note, /The deploy does this work again\.$/);
  assert.equal(s.phase, "payment");
  assert.equal(s.waiting, "payment");
  // each ran once: a phase that only shortens the deploy is not tried again
  assert.deepEqual(t.launched, ["prep", "early"]);
});

test("a consent that leaves out the run's account says so until a consent covers it again", async () => {
  const t = setup({ world: worldFor("ada+auto@example.com", "f".repeat(32)), site: true });
  const id = await newInstallation(t);
  await t.api("PATCH", `/service/installations/${id}/choices`, {
    name: "ada-labs",
    domain: { zone: "ada-labs.com" },
  });
  await t.consent(id, t.browser());
  await t.tick(id, 15 * SECOND);
  assert.equal((await t.status(id)).waits.domain, true);
  const first = t.world.accounts;
  t.world.accounts = [{ ...first[0], id: "b".repeat(32), name: "Another account" }];
  await t.consent(id, t.browser());
  const launches = t.launched.length;
  await t.tick(id, 60 * SECOND);
  let s = await t.status(id);
  assert.equal(s.waiting, "fresh-consent");
  assert.match(s.detail, /did not cover/);
  // nothing is looked at or started with that token: what was seen stays, and the object
  // sleeps until the token ends
  assert.equal(t.launched.length, launches);
  assert.equal(s.waits.domain, true);
  assert.equal(t.alarmOf(id), s.tokenEndsAt + SECOND);
  t.world.accounts = first;
  await t.consent(id, t.browser());
  s = await t.status(id);
  assert.notEqual(s.waiting, "fresh-consent");
  assert.doesNotMatch(s.detail || "", /did not cover/);
});

test("an installation is forgotten only between phases: its token is revoked and nothing wakes it", async () => {
  const t = setup();
  const id = await newInstallation(t);
  await t.api("PATCH", `/service/installations/${id}/choices`, { name: "ada-labs" });
  await t.consent(id, t.browser());
  const busy = await t.api("DELETE", `/service/installations/${id}`);
  assert.equal(busy.status, 409);
  assert.match(busy.body.error, /prep phase runs/);
  await t.tick(id, 25 * SECOND);
  assert.equal(Object.keys(t.world.tokens).length, 1);
  assert.equal((await t.api("DELETE", `/service/installations/${id}`)).status, 200);
  assert.deepEqual(Object.keys(t.world.tokens), []);
  assert.equal(t.alarmOf(id), null);
  assert.equal((await t.api("GET", `/service/installations/${id}`)).status, 404);
  // the same deployment can begin again
  assert.equal(await newInstallation(t), id);
  assert.equal((await t.status(id)).phase, "consent");
});

test("a deployment made elsewhere ends the run: the token goes, nothing starts, and no consent is taken", async () => {
  const t = setup({ site: true });
  const id = await newInstallation(t);
  await t.api("PATCH", `/service/installations/${id}/choices`, { name: "ada-labs" });
  await t.consent(id, t.browser());
  // not while the Cloud runs a phase
  const busy = await t.api("POST", `/service/installations/${id}/deployed`, {
    domain: "ada-labs.com",
  });
  assert.equal(busy.status, 409);
  await t.tick(id, 25 * SECOND);
  const tied = await t.api("POST", `/service/installations/${id}/deployed`, {
    domain: "ada-labs.com",
  });
  assert.equal(tied.status, 200);
  assert.deepEqual([tied.body.phase, tied.body.waiting], ["done", null]);
  assert.deepEqual(Object.keys(t.world.tokens), []);
  assert.equal(t.alarmOf(id), null);
  const launched = t.launched.length;
  await t.tick(id, 5 * MINUTE);
  assert.equal(t.launched.length, launched);
  assert.equal(
    (await t.api("POST", `/service/installations/${id}/links`, { kind: "consent" })).status,
    409,
  );
});