iterate.com / cloud

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

cloud / scripts / cloud-rehearsal / base-rules.tsmain at aacbc74

// base-rules.ts — THE RULES EVERY REHEARSAL STARTS WITH: the calls and the pages an install's chat
// needs, answered from the world (rules.ts). A run's own rules.mjs is tried before these, so a
// rehearsal changes one answer without touching this file. A rule added here should be one that
// every rehearsal wants; a rule for one scenario belongs in that run's rules.mjs.
//
// Three parts: Cloudflare's API under /client/v4, the dashboard's pages (a button each), and the
// deploy, which stands in for the sandbox where the real install runs Alchemy.
import { escapeHtml, type Account, type Call, type Rule, type World } from "./rules.ts";

const accountOf = (call: Call): Account | undefined =>
  call.world.accounts[call.params.account || ""];
const priceOf = (world: World, name: string) =>
  world.registrar.prices[name.split(".").at(-1) || ""] || world.registrar.prices["*"] || 9.99;
/** A domain, as the rehearsal app's deploy() and handOver() take it (mind-app/mind.ts.txt `DOMAIN`):
 *  ada-labs.com, and ada-labs.co.uk too. */
const isDomain = (name: unknown): name is string =>
  typeof name === "string" &&
  /^(?=.{4,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/.test(name);
const isTaken = (world: World, name: string) =>
  (name.split(".")[0] || "").length <= world.registrar.takenUpToLetters ||
  world.registrar.taken.includes(name) ||
  name in world.domains;
const checkOf = (world: World, name: string) => ({
  name,
  registrable: !isTaken(world, name),
  pricing: {
    currency: "USD",
    registration_cost: priceOf(world, name).toFixed(2),
    renewal_cost: priceOf(world, name).toFixed(2),
  },
});
const zonesOf = (call: Call) =>
  Object.entries(call.world.domains)
    .filter(([, domain]) => call.reached(domain.registeredAt))
    .map(([name, domain]) => ({
      id: `zone-${name.replace(/[^a-z0-9]/g, "-")}`,
      name,
      status: call.reached(domain.zoneActiveAt) ? "active" : "pending",
      account: { id: domain.account, name: call.world.accounts[domain.account]?.name },
      name_servers: ["ada.ns.cloudflare.com", "bob.ns.cloudflare.com"],
    }));
/** Buys `name` into `account` now: the registration and the zone end at instants of their own. */
function register(call: Call, account: string, name: string) {
  call.world.domains[name] = {
    account,
    boughtAt: call.instantIn(0),
    registeredAt: call.instantIn(call.world.waits.domainRegisters),
    zoneActiveAt: call.instantIn(call.world.waits.zoneActive),
  };
}
const button = (label: string, hidden = "") =>
  `<form method="post">${hidden}<p><button>${label}</button></p></form>`;
const BACK = `<p class="note">Go back to the chat: it is looking for this by itself.</p>`;
const needsCard = (call: Call) =>
  `<p>Add a payment card to this account first: <a href="${call.base}/${call.params.account}/billing">Billing</a>.</p>`;

const api: Rule[] = [
  {
    // Before the gate: iterate Cloud makes an account with the person's sign-in, before any consent.
    // A second call with the same name makes no second account.
    route: "POST /client/v4/accounts",
    answer: (call) => {
      const name = String(call.body.name || "iterate").slice(0, 100);
      const made = Object.entries(call.world.accounts).find(([, account]) => account.name === name);
      if (made) return call.ok({ id: made[0], name });
      const id = `c0de${call.now.toString(16)}`.padEnd(32, "0");
      call.world.accounts[id] = {
        name,
        createdOn: call.instantIn(0),
        billing: {
          opensAt: call.instantIn(call.world.waits.newAccountBillingOpens),
          opensSecondsAfterConsent: 0,
          card: null,
        },
        workersPaid: { boughtAt: null, showsAt: null },
        r2: { enabledAt: null },
        hasRegistrant: false,
        workersSubdomain: null,
      };
      return call.ok({ id, name });
    },
  },
  {
    route: "ANY /client/v4/*rest",
    answer: (call) => {
      if (call.world.consent.status === "approved") return undefined;
      return call.fail(401, 10000, "Authentication error");
    },
  },
  {
    route: "GET /client/v4/user",
    answer: (call) =>
      call.ok({
        id: "fake-user",
        email: call.world.person.email,
        first_name: call.world.person.firstName,
        last_name: call.world.person.lastName,
      }),
  },
  { route: "GET /client/v4/user/tokens/verify", answer: (call) => call.ok({ status: "active" }) },
  {
    route: "GET /client/v4/accounts",
    answer: (call) =>
      call.ok(
        Object.entries(call.world.accounts).map(([id, account]) => ({
          id,
          name: account.name,
          created_on: account.createdOn,
        })),
      ),
  },
  {
    route: "GET /client/v4/accounts/:account",
    answer: (call) => {
      const account = accountOf(call);
      if (!account) return undefined;
      return call.ok({
        id: call.params.account,
        name: account.name,
        created_on: account.createdOn,
      });
    },
  },
  // Two addresses for one fact: Cloudflare's billing profile, and the AI Gateway balance that
  // iterate's own guides read the card from. Both answer 200 whether or not the page takes a card.
  ...["billing/profile", "ai-gateway/billing/credit-balance"].map((path): Rule => ({
    route: `GET /client/v4/accounts/:account/${path}`,
    answer: (call) => {
      const account = accountOf(call);
      if (!account) return undefined;
      const { card } = account.billing;
      return call.ok({
        has_default_payment_method: Boolean(card),
        payment_method: card ? { brand: card.brand, last4: card.last4 } : null,
        balance: 0,
      });
    },
  })),
  {
    route: "GET /client/v4/accounts/:account/subscriptions",
    answer: (call) => {
      const account = accountOf(call);
      if (!account) return undefined;
      const paid = {
        id: "fake-subscription",
        rate_plan: { id: "workers_paid", public_name: "Workers Paid" },
        price: 5,
        currency: "USD",
        frequency: "monthly",
      };
      return call.ok(call.reached(account.workersPaid.showsAt) ? [paid] : []);
    },
  },
  {
    route: "GET /client/v4/accounts/:account/containers/applications",
    answer: (call) => {
      const account = accountOf(call);
      if (!account) return undefined;
      return call.reached(account.workersPaid.showsAt)
        ? call.ok([])
        : call.fail(403, 1000, "Containers requires the Workers Paid plan.");
    },
  },
  {
    route: "GET /client/v4/accounts/:account/r2/buckets",
    answer: (call) => {
      const account = accountOf(call);
      if (!account) return undefined;
      return account.r2.enabledAt
        ? call.ok({ buckets: [] })
        : call.fail(403, 10042, "Please enable R2 through the Cloudflare Dashboard.");
    },
  },
  {
    route: "GET /client/v4/accounts/:account/workers/subdomain",
    answer: (call) => {
      const account = accountOf(call);
      return account ? call.ok({ subdomain: account.workersSubdomain }) : undefined;
    },
  },
  {
    route: "PUT /client/v4/accounts/:account/workers/subdomain",
    answer: (call) => {
      const account = accountOf(call);
      if (!account) return undefined;
      account.workersSubdomain = String(call.body.subdomain || "iterate");
      return call.ok({ subdomain: account.workersSubdomain });
    },
  },
  {
    route: "POST /client/v4/accounts/:account/registrar/domain-check",
    answer: (call) => {
      if (!accountOf(call)) return undefined;
      const names: unknown[] = Array.isArray(call.body.domains) ? call.body.domains : [];
      return call.ok({
        domains: names
          .filter(isDomain)
          .slice(0, 20)
          .map((name) => checkOf(call.world, name)),
      });
    },
  },
  {
    route: "GET /client/v4/accounts/:account/registrar/domain-search",
    answer: (call) => {
      if (!accountOf(call)) return undefined;
      const stem = (call.query.get("q") || "").toLowerCase().replace(/[^a-z0-9]/g, "");
      const names = stem
        ? ["com", "dev", "app", "net"].flatMap((tld) => [`${stem}.${tld}`, `${stem}hq.${tld}`])
        : [];
      return call.ok({ domains: names.map((name) => checkOf(call.world, name)) });
    },
  },
  {
    route: "GET /client/v4/accounts/:account/registrar/domains",
    answer: (call) => {
      if (!accountOf(call)) return undefined;
      const owned = Object.entries(call.world.domains).filter(
        ([, domain]) => domain.account === call.params.account,
      );
      return call.ok(
        owned.map(([name]) => ({ name })),
        { result_info: { total_count: owned.length } },
      );
    },
  },
  {
    route: "POST /client/v4/accounts/:account/registrar/registrations",
    answer: (call) => {
      const account = accountOf(call);
      if (!account) return undefined;
      const name: unknown = call.body.domain_name;
      if (!isDomain(name)) return call.fail(400, 1001, "domain_name is not a domain");
      if (isTaken(call.world, name)) return call.fail(400, 1002, `${name} is not available`);
      if (!account.billing.card)
        return call.fail(400, 1003, "billing_quote_failed: this account has no payment method");
      if (!account.hasRegistrant && !call.body.contacts?.registrant)
        return call.fail(
          400,
          1004,
          "No registrant contact on file for this account: send contacts.registrant, or register the domain in the dashboard",
        );
      register(call, call.params.account || "", name);
      account.hasRegistrant = true;
      return call.ok({ domain_name: name, state: "in_progress" });
    },
  },
  {
    route: "GET /client/v4/accounts/:account/registrar/registrations/:domain/registration-status",
    answer: (call) => {
      const domain = call.world.domains[call.params.domain || ""];
      if (!domain || domain.account !== call.params.account)
        return call.fail(404, 1005, "No such registration");
      return call.ok({
        domain_name: call.params.domain,
        state: call.reached(domain.registeredAt) ? "succeeded" : "in_progress",
      });
    },
  },
  {
    route: "GET /client/v4/zones",
    answer: (call) => {
      const account = call.query.get("account.id");
      const name = call.query.get("name");
      return call.ok(
        zonesOf(call).filter(
          (zone) => (!account || zone.account.id === account) && (!name || zone.name === name),
        ),
      );
    },
  },
  {
    route: "POST /client/v4/zones",
    answer: (call) => {
      const zone = zonesOf(call).find((one) => one.name === call.body.name);
      if (!zone)
        return call.fail(400, 1049, `${String(call.body.name)} is not a registered domain`);
      return call.ok(zone);
    },
  },
  // no mind lives on a zone of the fake yet
  { route: "GET /client/v4/zones/:zone/workers/routes", answer: (call) => call.ok([]) },
];

const pages: Rule[] = [
  {
    route: "ANY /connect",
    answer: (call) => {
      const { consent, person } = call.world;
      if (call.method === "POST") {
        const approved =
          call.body.answer === "approve" && (call.body.tokens === "on" || !consent.needsTokensTick);
        consent.status = approved ? "approved" : "refused";
        consent.at = call.instantIn(0);
        // an account made minutes ago: its billing page opens at an instant counted from the consent
        for (const account of Object.values(call.world.accounts))
          if (approved && !account.billing.opensAt)
            account.billing.opensAt = call.instantIn(account.billing.opensSecondsAfterConsent);
        return {
          status: 303,
          redirect: `/connect?said=${approved ? "approved" : call.body.answer === "approve" ? "no-tick" : "refused"}`,
        };
      }
      if (consent.status === "approved")
        return call.page(
          "iterate is connected",
          `<p>iterate has access to ${escapeHtml(person.email)}'s accounts.</p>${BACK}`,
        );
      const said = call.query.get("said");
      const problem =
        said === "no-tick"
          ? `<p><b>Cloudflare refused the consent:</b> "Account API Tokens Write" was not ticked.</p>`
          : said === "refused"
            ? "<p><b>You refused the consent.</b></p>"
            : "";
      return call.page(
        "iterate wants access to your Cloudflare account",
        `${problem}<p>Signed in as ${escapeHtml(person.email)}.</p><form method="post"><p><b>Sensitive scopes</b></p><p><label><input type="checkbox" name="tokens"> Account API Tokens Write</label></p><p><button name="answer" value="approve">Approve</button> <button name="answer" value="refuse">Refuse</button></p></form>`,
      );
    },
  },
  {
    route: "ANY /:account/billing/*rest",
    answer: (call) => {
      const account = accountOf(call);
      if (!account) return undefined;
      // an instant not set yet is the consent's to set; with no wait after the consent, it is open
      const open =
        call.reached(account.billing.opensAt) ||
        (!account.billing.opensAt && account.billing.opensSecondsAfterConsent === 0);
      if (call.method === "POST") {
        if (open && !account.billing.card)
          account.billing.card = { brand: "visa", last4: "4242", addedAt: call.instantIn(0) };
        return { status: 303, redirect: `/${call.params.account}/billing?said=1` };
      }
      if (account.billing.card)
        return call.page(
          "Billing",
          `<p>Visa ending 4242 is on file for <b>${account.name}</b>.</p>${BACK}`,
        );
      if (!open)
        return call.page(
          "Billing",
          `<p><b>You do not have access to billing for this account.</b></p><p class="note">A new account takes no card for its first minutes. Try again shortly.</p>`,
        );
      return call.page(
        "Billing",
        `<p>No payment method on <b>${account.name}</b>.</p>${button("Add a card (a made-up Visa ending 4242)")}`,
      );
    },
  },
  {
    route: "ANY /:account/workers/plans",
    answer: (call) => {
      const account = accountOf(call);
      if (!account) return undefined;
      if (call.method === "POST") {
        if (account.billing.card && !account.workersPaid.boughtAt)
          account.workersPaid = {
            boughtAt: call.instantIn(0),
            showsAt: call.instantIn(call.world.waits.workersPaidShows),
          };
        return { status: 303, redirect: `/${call.params.account}/workers/plans?said=1` };
      }
      if (account.workersPaid.boughtAt)
        return call.page(
          "Workers plans",
          `<p><b>${account.name}</b> is on Workers Paid.</p>${call.reached(account.workersPaid.showsAt) ? "" : `<p class="note">It can take a few minutes to show everywhere.</p>`}${BACK}`,
        );
      return call.page(
        "Workers plans",
        account.billing.card
          ? `<p><b>${account.name}</b> is on Workers Free.</p>${button("Purchase Workers Paid, $5 a month")}`
          : needsCard(call),
      );
    },
  },
  {
    route: "ANY /:account/r2/overview",
    answer: (call) => {
      const account = accountOf(call);
      if (!account) return undefined;
      if (call.method === "POST") {
        if (account.billing.card && !account.r2.enabledAt) account.r2.enabledAt = call.instantIn(0);
        return { status: 303, redirect: `/${call.params.account}/r2/overview?said=1` };
      }
      if (account.r2.enabledAt)
        return call.page("R2", `<p>R2 is on for <b>${account.name}</b>.</p>${BACK}`);
      return call.page(
        "R2",
        account.billing.card
          ? `<p>R2 is off for <b>${account.name}</b>.</p>${button("Enable R2")}`
          : needsCard(call),
      );
    },
  },
  {
    route: "ANY /:account/domains/register",
    answer: (call) => {
      const account = accountOf(call);
      if (!account) return undefined;
      if (call.method === "POST") {
        const wanted = String(call.body.domain || "").toLowerCase();
        if (account.billing.card && isDomain(wanted) && !isTaken(call.world, wanted)) {
          register(call, call.params.account || "", wanted);
          account.hasRegistrant = true;
        }
        return {
          status: 303,
          redirect: `/${call.params.account}/domains/register?domain=${encodeURIComponent(wanted)}&said=1`,
        };
      }
      const name = (call.query.get("domain") || "").toLowerCase();
      if (!isDomain(name))
        return call.page(
          "Register a domain",
          `<form method="get"><p><input name="domain" placeholder="ada-labs.com"> <button>Look it up</button></p></form>`,
        );
      if (call.world.domains[name]?.account === call.params.account)
        return call.page(
          "Register a domain",
          `<p><b>${name}</b> is yours, in <b>${account.name}</b>.</p>${BACK}`,
        );
      if (isTaken(call.world, name))
        return call.page("Register a domain", `<p><b>${name}</b> is taken.</p>`);
      const buy = button(`Buy ${name}`, `<input type="hidden" name="domain" value="${name}">`);
      return call.page(
        "Register a domain",
        account.billing.card
          ? `<p><b>${name}</b> is free: $${priceOf(call.world, name).toFixed(2)} a year.</p>${buy}`
          : needsCard(call),
      );
    },
  },
  {
    route: "GET /",
    answer: (call) => {
      const links = Object.entries(call.world.accounts)
        .map(
          ([id, account]) =>
            `<li><b>${account.name}</b> <small>${id}</small>: <a href="${call.base}/${id}/billing">billing</a>, <a href="${call.base}/${id}/workers/plans">plans</a>, <a href="${call.base}/${id}/r2/overview">R2</a>, <a href="${call.base}/${id}/domains/register">domains</a></li>`,
        )
        .join("");
      const world = JSON.stringify(call.world, null, 2).replace(
        /[&<>]/g,
        (character) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;" })[character] || character,
      );
      return call.page(
        `${call.world.person.firstName}'s fake Cloudflare`,
        `<p>${call.world.scenario}</p><p><a href="${call.base}/connect">The consent page</a></p><ul>${links}</ul><h2>The world now</h2><pre>${world}</pre>`,
      );
    },
  },
];

/** A deploy's id: its start instant, moved on by the number of deploys before it, so that two
 *  deploys started in the same millisecond get two ids. Letters and digits alone: the id is part of
 *  the name of the deploy's log. */
const deployIdOf = (call: Pick<Call, "now" | "world">) =>
  (call.now + Object.keys(call.world.deploys).length).toString(36);

/** THE DEPLOY, in place of the sandbox: it refuses what a real deploy fails on, and ends at an
 *  instant. Its answers are plain JSON, not Cloudflare's envelope: it is not Cloudflare's. */
const deploy: Rule[] = [
  {
    route: "POST /deploy",
    answer: (call) => {
      const id = String(call.body.account || "");
      const account = call.world.accounts[id];
      const refuse = (error: string) => ({ status: 400, json: { error } });
      if (!account) return refuse("deploy: give `account`, the id of the Cloudflare account");
      const first = Object.entries(call.world.deploys).find(
        ([, one]) => one.account === id && one.kind === "first",
      );
      const wanted: unknown = call.body.domain;
      if (!wanted) {
        if (first)
          return {
            status: 200,
            json: {
              job: first[0],
              kind: "first",
              status: call.reached(first[1].endsAt) ? "done" : "running",
            },
          };
        const job = deployIdOf(call);
        call.world.deploys[job] = {
          kind: "first",
          account: id,
          domain: null,
          startedAt: call.instantIn(0),
          endsAt: call.instantIn(call.world.waits.firstDeploy),
        };
        return {
          status: 200,
          json: {
            job,
            kind: "first",
            status: "running",
            note: "It runs in the background. GET /deploy/<job> says how it goes.",
          },
        };
      }
      if (!first || !call.reached(first[1].endsAt))
        return refuse(
          "deploy failed: the first deploy has not finished, so there is no stack to attach a domain to",
        );
      // the first deploy is what a Free account takes; the deploy with the domain adds the rest
      if (!call.reached(account.workersPaid.showsAt))
        return refuse(
          "deploy failed: Cloudflare refused a Worker's upload (code 10195): this account is not on Workers Paid",
        );
      if (!account.r2.enabledAt)
        return refuse(
          "deploy failed: Cloudflare refused the bucket (code 10042): R2 is not enabled on this account",
        );
      const domain = isDomain(wanted) ? call.world.domains[wanted] : undefined;
      if (
        !isDomain(wanted) ||
        !domain ||
        domain.account !== id ||
        !call.reached(domain.zoneActiveAt)
      )
        return refuse(`deploy failed: ${String(wanted)} is not an active zone of this account yet`);
      const job = deployIdOf(call);
      call.world.deploys[job] = {
        kind: "attach",
        account: id,
        domain: wanted,
        startedAt: call.instantIn(0),
        endsAt: call.instantIn(call.world.waits.attachDeploy),
      };
      return {
        status: 200,
        json: {
          job,
          kind: "attach",
          status: "running",
          note: "It runs in the background. GET /deploy/<job> says how it goes.",
        },
      };
    },
  },
  {
    route: "GET /deploy/:job",
    answer: (call) => {
      const one = call.world.deploys[call.params.job || ""];
      if (!one) return { status: 404, json: { error: "No such deploy" } };
      const secondsLeft = Math.max(0, Math.ceil((Date.parse(one.endsAt) - call.now) / 1000));
      return {
        status: 200,
        json:
          secondsLeft === 0
            ? { job: call.params.job, kind: one.kind, status: "done", exitCode: 0 }
            : { job: call.params.job, kind: one.kind, status: "running", secondsLeft },
      };
    },
  },
  {
    // the "mind" at its domain, once a deploy has attached the domain
    route: "GET /h/:domain/*rest",
    answer: (call) => {
      const attached = Object.values(call.world.deploys).some(
        (one) =>
          one.kind === "attach" && one.domain === call.params.domain && call.reached(one.endsAt),
      );
      return attached
        ? { status: 200, text: `Homepage of mind ${call.params.domain}\n` }
        : { status: 522, text: "error code: 522\n" };
    },
  },
];

/** THE SANDBOX, in place of the Linux box where iterate Cloud's agent runs commands: the few
 *  commands the install's guide names. Any other command has no rule here, so the fake's author
 *  writes one for it (RULES.md "The sandbox"). */
const sandbox: Rule[] = [
  {
    route: "POST /sandbox",
    answer: (call) => {
      const command = String(call.body.command || "");
      const ran = (exitCode: number, stdout: string, stderr = "") => ({
        status: 200,
        json: { exitCode, stdout, stderr },
      });
      const attachedTo = (domain: string) =>
        Object.values(call.world.deploys).some(
          (one) => one.kind === "attach" && one.domain === domain && call.reached(one.endsAt),
        );
      const log = /\btail\b.*job-([a-z0-9]+)\.log/.exec(command);
      if (log) {
        const one = call.world.deploys[log[1] || ""];
        if (!one)
          return ran(
            1,
            "",
            `tail: cannot open '/root/cloud/job-${log[1]}.log' for reading: No such file or directory\n`,
          );
        const what =
          one.kind === "first" ? "the stack, before its domain" : `the domain ${one.domain}`;
        const lines = [
          `> core-alchemy@ deploy /root/core/core/alchemy`,
          `> alchemy deploy --yes --adopt`,
          ``,
          `Deploying ${what} …`,
        ];
        if (call.reached(one.endsAt))
          lines.push("Plan applied: every resource succeeded, 0 failed.", "Done.");
        else
          lines.push("  … still working (copying iterate's sandbox image takes most of the time)");
        return ran(0, `${lines.join("\n")}\n`);
      }
      const issuer =
        /https:\/\/iterate\.([a-z0-9.-]+)\/\.well-known\/oauth-authorization-server/.exec(command);
      if (issuer)
        return attachedTo(issuer[1] || "")
          ? ran(
              0,
              `${JSON.stringify({ issuer: `https://iterate.${issuer[1]}`, authorization_endpoint: `https://iterate.${issuer[1]}/oauth2/auth` })}\n`,
            )
          : ran(6, "", `curl: (6) Could not resolve host: iterate.${issuer[1]}\n`);
      const status = /%\{http_code\}.*https:\/\/([a-z0-9.-]+)\/?/.exec(command);
      if (status) return ran(0, attachedTo(status[1] || "") ? "200" : "000");
      if (/^\s*(ls|test -d)\s+\/root\/core/.test(command))
        return ran(
          0,
          /^\s*ls/.test(command) ? "README.md\nalchemy.run.ts\npackage.json\nscripts\nsrc\n" : "",
        );
      return undefined;
    },
  },
];

export const baseRules: Rule[] = [...api, ...pages, ...deploy, ...sandbox];