iterate.com / cloud

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

cloud / internal-packages / cloud-clients / src / worker.tsmain at aacbc74

// worker.ts — THE CLOUD'S CLIENTS (README.md): iterate's official apps at GitHub, Google and X, one
// of each for every deployment. An app exists once, so its secrets live here, in iterate's own
// account. Everything of a customer's lives in their deployment. This Worker is what stands
// between the two, and it keeps no token of anybody's.
//
//   GET  /.well-known/iterate-cloud          the Cloud's public key and each client's public facts
//   GET  /clients/<name>/begin               the one page a person confirms on, before the
//                                            provider's own: which deployment gets access
//   GET  /clients/<name>/callback            the provider's one redirect URI: the code goes on to
//                                            the deployment that began, which the person confirmed
//                                            (its vault's callback, or its sign-in with Google)
//   POST /clients/<name>/token               a deployment's code exchange or refresh: the Cloud adds
//                                            the client secret, and the tokens go back (for a
//                                            sign-in, Google's id_token and no other token)
//   POST /clients/<name>/installation-token  a GitHub App installation's token, minted with the
//                                            App's key, for a deployment that connected it
//   POST /clients/<name>/webhook             the app's one webhook URL: checked, kept, answered;
//                                            then held for each deployment until taken, signed
//                                            for it as a statement of the Cloud's mind
//   POST /clients/<name>/interactivity-webhook   Slack's second address, the same way
//   GET+POST /clients/<name>/webhook         for X: its check of the address, and its pushed
//                                            events for the bot's account (bot.ts)
//   POST /clients/<name>/webhook             for Google: Gmail's push for a mailbox, from the one
//                                            Pub/Sub subscription of the client's topic
//   POST /clients/<name>/calendar-webhook    for Google: Calendar's push on a channel that a
//                                            deployment made with the token the Cloud gave it
//   GET  /clients/<name>/bot                 an operator's link: X's consent as the bot's account
//   POST /clients/<name>/ask/reply           a deployment's answer to a message the bot relayed
//                                            (bot.ts), sent as the bot
//   POST /clients/<name>/ask/release         a deployment lets go of one account it connected
//   POST /clients/<name>/ask/mind-form       a deployment's word that it reads the mind form:
//                                            answered, and it changes nothing (`mindFormWord`)
//   POST /clients/<name>/ask/status          what the Cloud holds for the deployment; for the
//                                            Cloud's own mind, for every deployment (`status`)
//
// A DEPLOYMENT IS NAMED BY ITS CONTROL PLANE'S HOSTNAME (`iterate.ada.com`, or any hostname its
// owner chose), and that name is `mind` everywhere in this file. It asks with a signed statement
// (signed.ts) in `iterate-auth-statement` (once `iterate-statement`, still read), and its key is the one that hostname serves at
// `/keys/stack.json`. A callback address belongs to the deployment whose name is the address's
// hostname, whole (`mindOf`). No rule reads a name's labels, so two hostnames of one domain are
// two deployments. What makes any hostname safe as a name: on every hostname of a deployment but
// its control plane's, its boundary Worker answers `/keys/stack.json` itself, with 404
// (core/boundary-worker src/host-session.ts), so a mind's own code can publish no key. There is
// no register of deployments here: a deployment gets a provider account's events and tokens by
// connecting that account (`Routes`). A deployment comes to trust the Cloud's key in its stack
// config or on the installer's enrolment page (internal-packages/installer), not here.
//
// WHAT IS KEPT: which deployments connected which provider account, for as long as the person who
// connected it still administers it (`Routes`), and a webhook until its deployment takes it, a
// day at most (`Outbox`). A refresh token goes back sealed under the Cloud's key and bound to the
// deployment, so a stolen one refreshes nothing, and no table of tokens exists.
//
// AN APP THAT SERVED ANOTHER PLATFORM FIRST (os.iterate.com) has one webhook address and, for a
// GitHub App's install, one callback. When those point here, that platform keeps working: a
// callback this Cloud did not begin is sent to it, and every delivery is also sent on to it,
// unchanged (`passOn`).
import { DurableObject, waitUntil } from "cloudflare:workers";
import { publishedMindOf, type PublishedMind } from "iterate/mind-identity-log";
import { createRemoteJWKSet, jwtVerify } from "jose";
import { Bot, BOT_SCOPES, tokensOf, type Pushed } from "./bot.ts";
import { botProofOf, keptBy, keysOf, seal, unseal } from "./keys.ts";
import { askedUserId, objectOf, publicPost } from "./post-subscriptions.ts";
import { base64url, keyIdOf, statementOf, type Signed } from "./signed.ts";

export { Bot };

/** A client's public facts, by its name (`CLOUD_CLIENTS`, JSON). `kind` is how the provider
 *  speaks: how its token endpoint takes the client, what a new token reaches, how it signs a
 *  webhook. */
export type Client = {
  kind: "github" | "google" | "x" | "slack" | "cloudflare";
  clientId: string;
  authorizationEndpoint: string;
  tokenEndpoint: string;
  /** The provider's API origin: where the Cloud asks what a new token reaches. */
  api: string;
  /** The hosts a deployment's secret for this client is pinned to. */
  urls: string[];
  /** What a connect asks for when the deployment names nothing. FOR A CLOUDFLARE CLIENT IT IS ALSO
   *  THE MOST A CONNECT MAY ASK AND GET (`beyondClient`): the client reads a deployment's own
   *  Cloudflare account and deploys nothing, so a link that asks more, or a token that reaches
   *  more, connects nothing. */
  scopes?: string[];
  /** A GitHub App's id and its install page. */
  appId?: string;
  installUrl?: string;
  /** GMAIL'S PUSH, for a Google client (`gmailPushed`): the Pub/Sub topic of the client's own
   *  Google project, which a deployment names when it watches a mailbox, and what the token of
   *  that topic's one push subscription says: the audience and the service account that the
   *  subscription was made with. `issuer` and `certs` are Google's own unless a fake stands in. */
  gmailPush?: {
    topic: string;
    audience: string;
    serviceAccount: string;
    issuer?: string;
    certs?: string;
  };
  /** THE PLATFORM THIS APP SERVED BEFORE THE CLOUD, which keeps working while the app's single
   *  addresses point here: a callback the Cloud did not begin is sent to its `callback`, and a
   *  delivery on the route `webhook` or `interactivity-webhook` is also sent on, unchanged, to the
   *  address of that name. */
  passOn?: { callback?: string; webhook?: string; "interactivity-webhook"?: string };
};

export type Env = {
  /** The Cloud's P-256 private key, a JWK. What seals and what proves derive from it. */
  CLOUD_KEY: string;
  CLOUD_CLIENTS: string;
  CLOUD_CLIENT_SECRETS: string;
  ROUTES: DurableObjectNamespace<Routes>;
  OUTBOX: DurableObjectNamespace<Outbox>;
  BOT: DurableObjectNamespace<Bot>;
  /** Public X post subscriptions (post-subscriptions.ts), as JSON
   *  `{ "limit": 2, "minds": ["iterate.iterate.com"] }`: how many X accounts are watched in all,
   *  from 1 to 100, and the deployments that may ask, each by its control plane's hostname.
   *  Anyone who publishes a key can sign an ask, and every post X delivers is billed to the
   *  Cloud's X account, so the Cloud names who may spend it. Not set, or not that shape: the
   *  service is off. */
  X_POST_SUBSCRIPTIONS?: string;
  /** How many days a GitHub claim lasts with no refresh of its person's grant (`claimAgeOf`).
   *  Not set: a claim has no age limit. */
  GITHUB_CLAIM_DAYS?: string;
  /** The same for a Google claim, a mailbox's route: with no refresh of a grant that reads it. */
  GOOGLE_CLAIM_DAYS?: string;
  /** THE CLOUD'S OWN MIND (README "The Cloud signs as its own mind"): the auth Worker of that
   *  mind, which signs a statement as the mind, and the mind's name, its control plane's hostname.
   *  With both, every statement for another deployment is in the mind form alone
   *  (`statementFor`). Without them (a dev Cloud), the Cloud signs with its own key alone. */
  MIND_AUTH?: MindAuth;
  MIND_HOSTNAME?: string;
  /** The id of the Cloud's own mind, the hash of its genesis. With it, only that mind reads every
   *  deployment's status (`status`); without it, the mind that `MIND_HOSTNAME` is pinned to. */
  MIND_ID?: string;
  /** iterate's auth Worker, its `Enrolments` entrypoint (core/auth-worker rpc.ts): whether a member
   *  of iterate let a mind in, by its id (`shutOut`). Without it (a dev Cloud), every mind is
   *  served. */
  ENROLMENTS?: Enrolments;
  /** What a mind that is not enrolled meets (`shutOut`): "on" refuses it; anything else, "log" by
   *  default, serves it and logs `cloud.not-enrolled`. */
  CLOUD_ENROLMENT?: string;
};

/** The one method of the auth Worker's `Deliveries` entrypoint (core/auth-worker rpc.ts) that the
 *  Cloud calls: a statement for the mind `mind`, which names the Cloud's own mind as `from`, on
 *  `/minds/<the Cloud's mind>` + `path`. That entrypoint signs a delivery's path and no other. */
type MindAuth = {
  sign(input: {
    mind: string;
    path: string;
    type: string;
    payload?: Record<string, unknown>;
    about?: string[];
    expiresInSeconds?: number;
  }): Promise<Signed>;
};

/** How long the Cloud holds a webhook for a deployment that does not answer, and so how long its
 *  statement lasts: the longest a deployment takes one for. */
export const HELD_MS = 24 * 60 * 60_000;
/** How long a statement waits at a hostname pinned to no mind before the Cloud's own mind may
 *  clear it (`forget`): a hostname that serves a mind takes a statement in seconds. */
const UNPINNED_STALE_MS = 60 * 60_000;
/** THE CLOUD IS A BUFFER, NOT AN ARCHIVE. One queue (a deployment's outbox, an inbox's queue, an
 *  account's rows that wait aside) holds this many rows and about this many bytes at most, and no
 *  row for longer than `HELD_MS`: whichever comes first. What is over goes, the oldest first, and
 *  nobody sees it again (`Outbox.#bound`). One kind of row is bounded by age alone: a provider's
 *  word that a connection ended. */
export const QUEUE_MAX_ROWS = 1_000;
export const QUEUE_MAX_BYTES = 16 * 1024 * 1024;
/** How long the Cloud keeps a refresh's answer for a retry that shows the same token (`token`):
 *  a deployment whose answer was lost asks again at once, and then with its next day's refresh. */
const KEPT_ANSWER_MS = 2 * 24 * 60 * 60_000;
/** How long the Cloud waits for a provider's token endpoint. */
const PROVIDER_WAIT_MS = 20_000;
/** How much later than the first a second refused refresh must come to end what the person
 *  connected (`Routes.refused`). */
const REFUSAL_HOLD_MS = 60 * 60_000;
/** HOW OLD A CLAIM MAY BE, in milliseconds; 0 for no limit. A claim is made at the connect and
 *  made again at every refresh of its person's grant, which is when the Cloud reads what that
 *  person administers now (`reachedBy`). A deployment that stops refreshing would keep an
 *  organization's tokens and events after its person lost admin there: past this age it gets
 *  neither, until a refresh makes the claim again. A GOOGLE CLAIM is a mailbox's route, made
 *  again at each refresh of a grant that reads the mailbox. A person who connects again with no
 *  leave to read mail leaves the old route behind: the deployment's vault replaced the grant
 *  that made it, so that grant is never refreshed and never refused, and nothing but its age ends
 *  the pushes it gets. Not Slack, nor X: a Slack claim is made at the install and no refresh
 *  names its person, and an X account is its person's own. The limit is on only where
 *  `GITHUB_CLAIM_DAYS` or `GOOGLE_CLAIM_DAYS` is set: a deployment refreshes a grant when its
 *  provider refuses the person's token and at no set time, so a limit before deployments refresh
 *  on a schedule would end connections whose person still administers the account. */
const claimAgeOf = (env: Env, client: Client | undefined) => {
  const days = Number(
    {
      github: env.GITHUB_CLAIM_DAYS,
      google: env.GOOGLE_CLAIM_DAYS,
      slack: "",
      x: "",
      cloudflare: "",
    }[client?.kind || "x"],
  );
  return days > 0 ? days * 24 * 60 * 60_000 : 0;
};
/** How long a deployment's own statement on a request may last. */
const REQUEST_LASTS_MS = 10 * 60_000;
const WEBHOOK_BODY_MAX_BYTES = 1024 * 1024;
/** How long a calendar's channel token lasts with no refresh of a grant that reaches the
 *  calendar (`calendarConnected`). A deployment refreshes each grant once a day. */
const CALENDAR_TOKEN_MS = 7 * 24 * 60 * 60_000;
/** How long the Cloud remembers that it told a deployment of a mailbox or a calendar it connected
 *  (`toldOnce`). Past it, the next refresh tells again: a deployment that missed the word hears it. */
const TOLD_MS = 30 * 24 * 60 * 60_000;
/** Who signs the token of a Pub/Sub push. */
const GOOGLE_ISSUERS = ["https://accounts.google.com", "accounts.google.com"];
/** What a deployment's vault signs for a request its mind makes to an `ask/` route. */
const ASK_REQUESTED = "events.iterate.com/integration/ask-requested";
const TOKEN_REQUESTED = "events.iterate.com/integration/token-requested";
/** A deployment's name: a hostname, a lower-case DNS name of two labels or more
 *  (`isMindControlPlaneHostname` of `iterate/signed`, the same rule). */
const HOSTNAME = /^(?=.{1,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/;
/** An account a deployment asks to be connected to: a GitHub login in lower case, and nothing
 *  else. `#` and an installation's id is in the list only when GitHub's install page named that
 *  installation to `callback`: a deployment's own link must not, because the page a person reads
 *  shows names, so an id from the link would take an installation that the page did not name. */
const ACCOUNT = /^[a-z0-9-]{1,39}$/;
const encoder = new TextEncoder();

/** A deployment's control plane: its name is that hostname, so nothing is put before it. Its
 *  key is at `/keys/stack.json` there (`STACK_KEY_PATH` of `iterate/signed`), and a statement for
 *  it goes to `/statements` (`STATEMENTS_PATH`). */
const controlPlaneOf = (mind: string) => `https://${mind}`;
const json = (status: number, body: unknown) =>
  Response.json(body, { status, headers: { "cache-control": "no-store" } });
const refuse = (status: number, error: string) => json(status, { error });

type Cloud = Awaited<ReturnType<typeof cloudFrom>>;
const clouds = new WeakMap<Env, Promise<Cloud>>();

/** The Cloud's own things (`cloudFrom`), read once per isolate. */
export function cloudOf(env: Env): Promise<Cloud> {
  if (!clouds.has(env)) clouds.set(env, cloudFrom(env));
  return clouds.get(env)!;
}

/** A client's secrets (`CLOUD_CLIENT_SECRETS`, JSON by name). The App key is PKCS8 PEM. */
type ClientSecrets = {
  clientSecret: string;
  webhookSecret?: string;
  appPrivateKey?: string;
  /** X alone: the app's app-only Bearer Token, from X's developer console. A public post
   *  subscription belongs to the app, not to the bot's account, so it is made, listed and deleted
   *  with this token, not with the bot's (bot.ts `#postApi`). */
  bearerToken?: string;
};

/** The Cloud's own things: its keys (keys.ts) and its clients. */
async function cloudFrom(env: Env) {
  return {
    ...(await keysOf(env.CLOUD_KEY)),
    clients: JSON.parse(env.CLOUD_CLIENTS) as Record<string, Client>,
    secrets: JSON.parse(env.CLOUD_CLIENT_SECRETS) as Record<string, ClientSecrets>,
    /** What speaks for each deployment's hostname, as last read (`identityAt`). */
    askers: new Map<string, { answer: Promise<Identity>; until: number }>(),
    /** Whether each mind id is enrolled, as last read (`enrolledAt`). */
    enrolments: new Map<string, { answer: Promise<Enrolled>; until: number }>(),
    /** When `cloud.not-enrolled` or `cloud.enrolment-unread` was last logged for each hostname
     *  (`shutOut`). */
    notEnrolledSaid: new Map<string, number>(),
    /** The keys published at a certs address, as last read (`gmailPushed`). */
    certs: new Map<string, ReturnType<typeof createRemoteJWKSet>>(),
  };
}

/** Whether a request is for this handler: the Cloud Worker that mounts it (internal-packages/installer)
 *  asks before it serves anything of its own. */
export const handles = ({ pathname }: URL) =>
  pathname === "/.well-known/iterate-cloud" || pathname.startsWith("/clients/");

export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    const cloud = await cloudOf(env);
    const url = new URL(request.url);
    const get = request.method === "GET";
    if (get && url.pathname === "/.well-known/iterate-cloud")
      return json(200, await factsOf(url, cloud, env));
    const [, name = "", verb = ""] =
      /^\/clients\/([a-z0-9-]+)\/([a-z-]+(?:\/[a-z-]+)?)$/.exec(url.pathname) || [];
    const client = cloud.clients[name];
    if (!client) return refuse(404, "Not found");
    if (get && verb === "begin") return begin(request, url, name, client, env);
    if (get && verb === "callback") return callback(request, url, name, client, cloud, env);
    if (get && verb === "bot") return botConsent(url, name, client, cloud);
    if (client.kind === "x" && verb === "webhook" && (get || request.method === "POST"))
      return pushed(request, url, name, cloud, env);
    if (request.method !== "POST") return refuse(404, "Not found");
    if (client.kind === "google" && verb === "webhook")
      return gmailPushed(request, name, client, cloud, env);
    if (client.kind === "google" && verb === "calendar-webhook")
      return calendarPushed(request, name, cloud, env);
    if (verb === "token") return token(request, name, client, cloud, env);
    if (verb === "installation-token") return installationToken(request, name, client, cloud, env);
    if (verb === "webhook" || verb === "interactivity-webhook")
      return webhook(request, name, verb, client, cloud, env);
    if (client.kind === "x" && ["ask/subscribe", "ask/unsubscribe", "ask/list"].includes(verb))
      return postSubscriptions(request, name, verb, env);
    if (verb === "ask/reply") return reply(request, name, env);
    if (verb === "ask/release") return letGo(request, name, env);
    if (verb === "ask/mind-form") return mindFormWord(request, name, env);
    if (verb === "ask/status") return status(request, name, env);
    if (verb === "ask/forget") return forget(request, name, env);
    return refuse(404, "Not found");
  },
} satisfies ExportedHandler<Env>;

/** What a deployment reads before it connects: the Cloud's key, for its auth Worker to trust, and
 *  each client as a vault needs it to begin an OAuth attempt. Nothing here is secret. */
async function factsOf(url: URL, cloud: Cloud, env: Env) {
  const clients = await Promise.all(
    Object.entries(cloud.clients).map(async ([name, client]) => [
      name,
      {
        kind: client.kind,
        clientId: client.clientId,
        authorizationEndpoint: client.authorizationEndpoint,
        // where a vault sends the person's browser, with the provider's URL as `to` (`begin`)
        beginEndpoint: `${url.origin}/clients/${name}/begin`,
        redirectUri: `${url.origin}/clients/${name}/callback`,
        tokenEndpoint: `${url.origin}/clients/${name}/token`,
        urls: client.urls,
        scopes: client.scopes,
        ...(client.installUrl && {
          installUrl: client.installUrl,
          installationTokenEndpoint: `${url.origin}/clients/${name}/installation-token`,
        }),
        // the topic a deployment names when it asks Gmail to watch a mailbox (`gmailPushed`)
        ...(gmailPushOf(client) && { gmailTopic: gmailPushOf(client)!.topic }),
        // the account a person talks to at X, once an operator connected it (bot.ts)
        ...(client.kind === "x" && { bot: await env.BOT.get(env.BOT.idFromName(name)).self() }),
      },
    ]),
  );
  return {
    actor: "iterate-cloud",
    label: "iterate Cloud",
    key: cloud.signer.key,
    publicKey: cloud.signer.publicKey,
    clients: Object.fromEntries(clients),
  };
}

// ── the OAuth broker ─────────────────────────────────────────────────────────────────────────────

/** THE ONE PAGE A PERSON CONFIRMS ON, before the provider's own. A vault sends the browser here
 *  with `to`, the provider's URL it made: this client's authorize or install page, whose `state`
 *  is `<base64url of the vault's own callback URL>.<its own state>` and so names the deployment.
 *  The person reads which deployment gets access and presses Continue. That press is this
 *  browser's and for this state alone: the page's link carries a value that the page's cookie
 *  holds too, so no link someone else made can press for them. The provider's consent then ends
 *  on the deployment's own page, with nothing more to confirm (`callback`). This address sends
 *  nobody anywhere but to this client's own consent. */
async function begin(
  request: Request,
  url: URL,
  name: string,
  client: Client,
  env: Env,
): Promise<Response> {
  const to = URL.parse(url.searchParams.get("to") || "");
  const state = to?.searchParams.get("state") || "";
  const back = Buffer.from(state.split(".")[0] || "", "base64url").toString();
  const mind = mindOf(back);
  const signIn = signsIn(back);
  const pageOf = ({ origin, pathname }: URL) => origin + pathname;
  const consent =
    !!to &&
    ((pageOf(to) === pageOf(new URL(client.authorizationEndpoint)) &&
      to.searchParams.get("client_id") === client.clientId &&
      to.searchParams.get("redirect_uri") === `${url.origin}/clients/${name}/callback`) ||
      pageOf(to) === client.installUrl);
  // WHICH ACCOUNTS the deployment asks to be connected to (`accounts`, a GitHub App's alone): the
  // person's consent reaches every account they administer, and the deployment gets the
  // installations of these and no other. The page shows them, the press keeps them, and the
  // callback's proof carries them to the exchange.
  const wanted = (url.searchParams.get("accounts") || "").toLowerCase().split(",").filter(Boolean);
  if (!to || !mind || !consent)
    return refuse(400, "This link is not one an iterate deployment made.");
  // A PAGE GATE ALONE, for the person's sake, and only while the gate refuses: this hostname is
  // the URL's, with no proof, so in "log" mode a stranger's link makes this Worker read nothing.
  // The exchange decides (`askedBy`)
  const shut =
    env.CLOUD_ENROLMENT === "on" &&
    (await shutOutAt(mind, "begin", env.OUTBOX.get(env.OUTBOX.idFromName(mind)), env));
  if (shut) return refuse(shut.status, shut.why);
  if (wanted.length > DEPLOYMENTS_PER_ACCOUNT || wanted.some((each) => !ACCOUNT.test(each)))
    return refuse(400, "accounts is a list of account names");
  // A SIGN-IN asks Google who the person is and nothing more, so the page's words are true
  const asked = (to.searchParams.get("scope") || "").split(/\s+/).filter(Boolean);
  if (
    signIn &&
    (client.kind !== "google" ||
      wanted.length > 0 ||
      asked.length === 0 ||
      asked.some((scope) => !SIGN_IN_SCOPES.includes(scope)))
  )
    return refuse(400, "A sign-in is through Google, and asks for openid and email alone.");
  // A CLOUDFLARE CONNECT ASKS WHAT THE CLIENT IS FOR AND NO MORE: the page says that the
  // deployment reads the account and changes nothing, so a link with another scope is refused here
  if (client.kind === "cloudflare" && beyondClient(client, asked).length > 0)
    return refuse(
      400,
      `This connection reads a Cloudflare account and changes nothing: ${beyondClient(client, asked).join(", ")} is not asked through it.`,
    );
  // ONE APP, MANY DEPLOYMENTS: Google's "incremental authorization" adds every scope the person
  // ever gave this app to the new token, also one given through another deployment. So a link
  // may not ask for it, and Google is told to show its own consent each time, with the scopes of
  // this request, which Google's page names in words.
  if (to.searchParams.has("include_granted_scopes"))
    return refuse(
      400,
      "A deployment asks for its own access alone: include_granted_scopes is refused.",
    );
  if (client.kind === "google" && !signIn) {
    // beside whatever the deployment asked for (`select_account`), and never `none`
    const prompt = (to.searchParams.get("prompt") || "").split(" ").filter(Boolean);
    to.searchParams.set(
      "prompt",
      [...new Set([...prompt.filter((each) => each !== "none"), "consent"])].join(" "),
    );
  }
  // WHAT THE LINK ASKED is what the press agreed to: Google's scopes of this request go with the
  // press into the callback's proof, and the exchange refuses a token that reaches more (`beyond`)
  const named = client.kind === "google" ? asked.join(" ") : "";
  const cookie = await confirmCookieOf(name, state);
  const held = cookieOf(request, cookie);
  const go = url.searchParams.get("go");
  // pressed, in the browser the page was shown in (a second press after "back" counts too)
  if (go && (held === go || held?.startsWith(`ok.${go}.`)))
    return new Response(null, {
      status: 302,
      headers: {
        location: to.href,
        "set-cookie": `${cookie}=ok.${go}.${base64url(encoder.encode(wanted.join(",")))}${named ? `.${base64url(encoder.encode(named))}` : ""}; ${COOKIE}; Max-Age=3600`,
        "cache-control": "no-store",
        "referrer-policy": "no-referrer",
      },
    });
  const fresh = base64url(crypto.getRandomValues(new Uint8Array(16)));
  url.searchParams.set("go", fresh);
  const shown = confirmPage(client, mind, url.href, true, wanted, signIn);
  // as long as a vault's attempt may live
  shown.headers.append("set-cookie", `${cookie}=${fresh}; ${COOKIE}; Max-Age=3600`);
  return shown;
}

/** `__Host-`: set by this origin alone, so no other site under the same domain can plant it. */
const COOKIE = "HttpOnly; Secure; SameSite=Lax; Path=/";
/** The cookie that says this browser confirmed one attempt: named by the client and the state. */
const confirmCookieOf = async (name: string, state: string) =>
  `__Host-iterate-confirm-${base64url(await crypto.subtle.digest("SHA-256", encoder.encode(`${name}\n${state}`))).slice(0, 22)}`;
const cookieOf = (request: Request, name: string) =>
  (request.headers.get("cookie") || "")
    .split(/;\s*/)
    .find((each) => each.startsWith(`${name}=`))
    ?.slice(name.length + 1);

/** What a person reads before a deployment gets access: on `begin`, before the provider's
 *  consent, and on `callback` when the consent did not begin here. It says two things and no
 *  more: which deployment gets access, by its control plane's hostname, whole, and to what. The
 *  page's one link is its button. */
function confirmPage(
  client: Client,
  mind: string,
  href: string,
  before: boolean,
  wanted: string[],
  signIn = false,
): Response {
  const provider = PROVIDER_NAMES[client.kind];
  const hostname = `<b>${escaped(mind)}</b>`;
  const button = (label: string) => `<a class="go" href="${escaped(href)}">${label}</a>`;
  // a sign-in gives the deployment no access: it learns who the person is at the provider
  if (signIn)
    return page(
      `Sign in to ${mind} with ${provider}?`,
      `Sign in to ${hostname} with ${provider}?`,
      `<p class="note">It learns your email address and gets no access to your account.</p>
       ${button(before ? `Continue to ${provider}` : "Sign in")}`,
    );
  const whose = client.kind === "slack" ? "Slack workspace" : `${provider} account`;
  // A GITHUB APP'S INSTALLATIONS: the accounts the vault named, and an installation the person
  // chose at GitHub, which is named there, not here
  const named = wanted
    .filter((each) => !each.startsWith("#"))
    .map((each) => `<b>${escaped(each)}</b>`);
  const chosen = wanted.length > named.length;
  const installations =
    named.length > 0
      ? `Installations of: ${named.join(", ")}${chosen ? ", and the one you chose at GitHub" : ""}`
      : chosen
        ? "With the installation you chose at GitHub"
        : "";
  // A CLOUDFLARE CONNECT IS OF ONE ACCOUNT, the one the deployment runs in: Cloudflare's own page
  // asks which accounts, and the person reads here which one to pick and what the access is
  const cloudflare =
    client.kind === "cloudflare"
      ? `<p class="note">On Cloudflare's page, select only the account that ${hostname} runs in. It reads that account and queries its logs. It deploys and changes nothing.</p>`
      : "";
  return page(
    `Give ${mind} access to your ${whose}?`,
    `Give ${hostname} access to your ${whose}?`,
    `${cloudflare}${client.kind === "github" && installations ? `<p class="note">${installations}</p>` : ""}
     ${button(before ? `Continue to ${provider}` : `Connect ${provider}`)}`,
  );
}

/** THE ONE REDIRECT URI of a client. The `state` a vault sent is `<base64url of its own callback
 *  URL>.<its own state>`, so the Cloud needs no memory of the attempt. The person saw which
 *  deployment gets access and said yes in this browser, before the provider (`begin`), so the
 *  code goes straight on. A consent that did not begin here is asked now: a link someone else
 *  made cannot send a person's consent to a stranger's deployment unseen. That page's press comes
 *  back here, in the browser the page was shown in. The code goes on with a proof of where the
 *  Cloud sent it, which the exchange must show: ONE PROOF FOR ONE CODE, made after the press and
 *  never before, so no page holds a proof and nobody who has a code gets a second one.
 *
 *  A Google consent that did not begin here is refused: the press before Google keeps what the
 *  deployment asked for (`begin`), and a press here could not.
 *
 *  A callback whose state is not this Cloud's belongs to the platform the app served before
 *  (`passOn`), and goes there with its whole query: its own connects, and an installation someone
 *  changed on GitHub's side, which carries no state at all. */
async function callback(
  request: Request,
  url: URL,
  name: string,
  client: Client,
  cloud: Cloud,
  env: Env,
): Promise<Response> {
  const state = url.searchParams.get("state") || "";
  const [to = "", ...rest] = state.split(".");
  // the bot's own consent, which an operator began (`botConsent`): the Cloud keeps these tokens
  if (to === "bot")
    return botConnected(url, name, client, cloud, env, rest[0] || "", rest[1] || "");
  const back = Buffer.from(to, "base64url").toString();
  const mind = mindOf(back);
  const signIn = signsIn(back);
  if (mind && signIn && client.kind !== "google")
    return refuse(400, "A sign-in is through Google alone.");
  if (!mind)
    return client.passOn?.callback
      ? Response.redirect(`${client.passOn.callback}${url.search}`, 302)
      : refuse(400, "This link names no iterate deployment to return to.");
  const mine = `${url.origin}/clients/${name}/callback`;
  const forward = new URL(back);
  for (const [key, value] of url.searchParams) forward.searchParams.set(key, value);
  forward.searchParams.set("state", rest.join("."));
  // this page's own press (below): the deployment does not hear of it
  const go = url.searchParams.get("go");
  forward.searchParams.delete("go");
  const code = url.searchParams.get("code");
  const installed = url.searchParams.get("setup_action");
  // A GITHUB APP'S SETUP URL: the person installed the App, and GitHub sent them here with the
  // installation and no code. They go on to authorize the App, and come back here with one.
  if (!code && client.kind === "github" && installed && installed !== "request") {
    const authorize = new URL(client.authorizationEndpoint);
    authorize.searchParams.set("client_id", client.clientId);
    authorize.searchParams.set("redirect_uri", mine);
    authorize.searchParams.set("state", state);
    return Response.redirect(authorize.href, 302);
  }
  // a refusal at the provider carries no code: the deployment hears it as it came
  if (!code) return Response.redirect(forward.href, 302);
  // A CODE BELONGS TO THE DEPLOYMENT IT FIRST CAME FOR. The provider sends it here before anyone
  // else has it, so the first state it comes with is the one its own deployment made. Whoever
  // learns the code later gets no proof for another deployment (an install page's code has no
  // PKCE challenge to bind it).
  const digest = base64url(await crypto.subtle.digest("SHA-256", encoder.encode(code)));
  const sentTo = await routesOf(env).once(`code\n${name}\n${digest}`, 10 * 60_000, mind);
  if (sentTo && sentTo !== mind)
    return refuse(400, "This code was already sent on to another deployment. Start again there.");
  // THE PRESS IS READ BEFORE ANYTHING IS SIGNED: on the page before the provider (`ok.…`), or on
  // the page here (`here.<go>`, with the same value in the link). With neither, the person is
  // asked now, and the page's link holds no proof: it comes back to this address.
  const cookie = await confirmCookieOf(name, state);
  const held = cookieOf(request, cookie) || "";
  const confirmed = held.split(".");
  const before = confirmed[0] === "ok";
  // THE INSTALLATION THE PERSON CHOSE on the App's install page: GitHub names it in its return,
  // beside `setup_action` and nowhere else. An id on any other callback is somebody's own words.
  const installation =
    (installed && installed !== "request" && url.searchParams.get("installation_id")) || "";
  const chosen = /^\d{1,19}$/.test(installation) ? `#${installation}` : "";
  if (!before && !(go && held === `here.${go}`)) {
    // Google's one app serves many kinds of access, and the page here knows no scope
    if (client.kind === "google")
      return refuse(
        400,
        `This Google consent did not begin on ${mind}'s own page in this browser, or it began over an hour ago. Start again from ${mind}.`,
      );
    const fresh = base64url(crypto.getRandomValues(new Uint8Array(16)));
    const here = new URL(url);
    here.searchParams.set("go", fresh);
    const shown = confirmPage(client, mind, here.href, false, [chosen].filter(Boolean), signIn);
    shown.headers.append("set-cookie", `${cookie}=here.${fresh}; ${COOKIE}; Max-Age=3600`);
    return shown;
  }
  // ONE PROOF FOR ONE CODE: whoever has the code later (the deployment it went to has) gets no
  // second proof, for other accounts or another installation than the person agreed to
  if (await routesOf(env).once(`proof\n${name}\n${digest}`, 60 * 60_000, mind))
    return refuse(400, `This code was already sent on to ${mind}. Start again there.`);
  // a code that comes beside `setup_action` is from the App's install page, which names no
  // redirect URI; any other is from an authorize that named this address. The exchange must
  // repeat what was named, and the proof says which.
  // THE ACCOUNTS THE PERSON AGREED TO: the ones the page before the provider showed, which its
  // cookie kept, and the installation they chose on the App's install page. The proof carries
  // them, so the exchange connects these and no other.
  const wanted = [
    ...Buffer.from((before && confirmed[2]) || "", "base64url")
      .toString()
      .split(","),
    chosen,
  ].filter(Boolean);
  // and the scopes that the link before Google asked for, which the same cookie kept
  const named = Buffer.from((before && confirmed[3]) || "", "base64url").toString();
  const proof = await crypto.subtle.sign(
    "HMAC",
    cloud.proofKey,
    proofInput(
      name,
      mind,
      code,
      signIn ? "sign-in" : installed ? "install" : "authorize",
      wanted.join(","),
      named,
    ),
  );
  forward.searchParams.set(
    "cloud_proof",
    `${base64url(proof)}.${base64url(encoder.encode(wanted.join(",")))}${named ? `.${base64url(encoder.encode(named))}` : ""}`,
  );
  return new Response(null, {
    status: 302,
    headers: {
      location: forward.href,
      "set-cookie": `${cookie}=; ${COOKIE}; Max-Age=0`,
      "cache-control": "no-store",
      "referrer-policy": "no-referrer",
    },
  });
}

/** WHERE A DEPLOYMENT'S SIGN-IN WITH GOOGLE ENDS: its auth Worker's page (core/auth-worker). The
 *  deployment asks Google who a person is, with iterate's client, and checks Google's answer
 *  itself. A code for this page is a sign-in's: its exchange answers the id_token and no token
 *  that reaches the person's account (`token`). */
const SIGN_IN_CALLBACK = "/sign-in/google/callback";
const SIGN_IN_SCOPES = ["openid", "email"];
const signsIn = (href: string) => URL.parse(href)?.pathname === SIGN_IN_CALLBACK;

/** THE DEPLOYMENT A CALLBACK URL BELONGS TO: the one whose name is the URL's hostname, whole. A
 *  vault's own OAuth callback is on its control plane, `https://<mind>/secrets/oauth/callback`,
 *  and so is its sign-in's (`SIGN_IN_CALLBACK`). A code goes to those pages and no other, where
 *  the deployment completes it only in the browser that began. An address on another hostname of
 *  the same domain names another deployment: its code gets a proof for that name, which only a
 *  statement signed by the key that very hostname serves can redeem (`askedBy`, `token`). */
function mindOf(href: string): string | null {
  const back = URL.parse(href);
  if (!back || back.protocol !== "https:") return null;
  const callback =
    back.pathname === "/secrets/oauth/callback" || back.pathname === SIGN_IN_CALLBACK;
  return callback && HOSTNAME.test(back.hostname) ? back.hostname : null;
}

/** What a proof covers: the client, the deployment the code was sent to, the code, how the code
 *  was asked for, the accounts the person agreed to connect (`wanted`, joined by commas), and the
 *  scopes the page named (`named`, joined by spaces: Google's alone, no line for another client). */
const proofInput = (
  name: string,
  mind: string,
  code: string,
  how: "authorize" | "install" | "sign-in",
  wanted: string,
  named: string,
) => encoder.encode(`${name}\n${mind}\n${code}\n${how}\n${wanted}${named ? `\n${named}` : ""}`);

/** Google's short names for two scopes, which its token answer spells in full. */
const GOOGLE_SCOPE: Record<string, string> = {
  email: "https://www.googleapis.com/auth/userinfo.email",
  profile: "https://www.googleapis.com/auth/userinfo.profile",
};

/** Each kind's provider, as a page names it. */
const PROVIDER_NAMES = {
  github: "GitHub",
  google: "Google",
  x: "X",
  slack: "Slack",
  cloudflare: "Cloudflare",
} as const satisfies Record<Client["kind"], string>;

/** WHAT A CLOUDFLARE CONNECT ASKS OR GETS BEYOND WHAT ITS CLIENT IS FOR (`Client.scopes`): the
 *  scopes of a link, or of Cloudflare's token answer, that the client's own list does not name. A
 *  client with no list is for nothing: every scope is beyond it. */
function beyondClient(client: Client, scopes: string[]): string[] {
  const within = new Set(client.scopes || []);
  return scopes.filter((each) => !within.has(each));
}

/** WHAT A GOOGLE TOKEN REACHES BEYOND WHAT THE PAGE NAMED (`named`, from the proof): the scopes in
 *  Google's answer that the press did not agree to. The press's cookie lives until the first
 *  callback, and a deployment can send the browser to Google a second time in that while, with
 *  the same state and other words (`include_granted_scopes`, `prompt=none`): that code gets a
 *  proof too, and only Google's answer says what its token reaches. `openid` says who the person
 *  is and reaches nothing. An answer with no `scope` says nothing, which is not "no more". */
function beyond(named: string, scope: unknown): string[] {
  if (typeof scope !== "string") return ["a token whose scopes Google did not name"];
  const agreed = new Set(["openid", ...named.split(" ").map((each) => GOOGLE_SCOPE[each] || each)]);
  return scope
    .split(/\s+/)
    .filter(Boolean)
    .filter((each) => !agreed.has(GOOGLE_SCOPE[each] || each));
}

/** WHO ASKS: the deployment whose published key signed this request's statement. The statement
 *  names the deployment as `mind`, its control plane's hostname, and the key is read at that
 *  hostname (`askerKeyOf`), with the mind's id when its identity log proves one. It names the
 *  client and the SHA-256 of the body, so it is good for this request alone, and for ten minutes
 *  at most. */
async function askedBy(
  request: Request,
  body: string,
  type: string,
  name: string,
  env: Env,
): Promise<{ mind: string; id: string | null } | Response> {
  let signed: Signed;
  // what the text claims before any check: untrusted JSON, so nothing about it is known yet
  let claimed: { mind?: unknown } | null;
  try {
    signed = JSON.parse(
      // Workers Logs keep a header whole unless its name holds "auth" (or key, secret, token, jwt):
      // the new name keeps the statement out of the logs; the old one is read until minds send the new
      Buffer.from(
        request.headers.get("iterate-auth-statement") ||
          request.headers.get("iterate-statement") ||
          "",
        "base64url",
      ).toString(),
    );
    claimed = JSON.parse(signed.statement);
  } catch {
    return refuse(401, "a request carries a signed statement in iterate-auth-statement");
  }
  const mind = claimed?.mind;
  if (typeof mind !== "string" || !HOSTNAME.test(mind))
    return refuse(401, "the statement names no deployment: `mind` is its control plane's hostname");
  const outbox = env.OUTBOX.get(env.OUTBOX.idFromName(mind));
  const asker = await askerKeyOf(mind, signed, outbox, env);
  if ("why" in asker) return refuse(401, asker.why);
  const statement = await statementOf(signed, asker.publicKey);
  if (!statement) return refuse(401, "the statement's signature is wrong, or it has expired");
  const payload = (statement.payload || {}) as Record<string, unknown>;
  const bodyHash = Buffer.from(
    await crypto.subtle.digest("SHA-256", encoder.encode(body)),
  ).toString("hex");
  if (
    statement.expires > Date.now() + REQUEST_LASTS_MS ||
    statement.type !== type ||
    payload.client !== name ||
    payload.body !== bodyHash ||
    // an ask is one statement type for every `ask/` route, so it names its route too
    (type === ASK_REQUESTED && payload.path !== new URL(request.url).pathname) ||
    // a vault that says which Cloud it asks is held to it: a statement for another Cloud is not ours
    (payload.audience !== undefined && payload.audience !== new URL(request.url).origin)
  )
    return refuse(401, "the statement is for another request");
  // A STATEMENT COUNTS ONCE: whoever saw this request cannot send it again while it lasts. The
  // state that the log proved is kept with the nonce: only once a key that it lists signed
  if (!(await outbox.firstUse(statement.nonce, statement.expires, asker.identity)))
    return refuse(401, "the statement was already used");
  const id = asker.identity?.expected || null;
  // A MIND THAT IS NOT ENROLLED (`shutOut`) may still let an account go, say its word on the form
  // and read its own status
  if (!/\/ask\/(release|mind-form|status)$/.test(new URL(request.url).pathname)) {
    const exchange =
      type === TOKEN_REQUESTED &&
      new URLSearchParams(body).get("grant_type") === "authorization_code";
    const gate = type === ASK_REQUESTED ? "ask" : exchange ? "connect" : "token";
    const shut = await shutOut(mind, id, gate, env);
    if (shut) return refuse(shut.status, shut.why);
  }
  return { mind, id };
}

// ── who the Cloud serves: the minds that iterate enrolled ───────────────────────────────────────

/** The one method of the auth Worker's `Enrolments` entrypoint (core/auth-worker rpc.ts). */
type Enrolments = { enrolled(mind: string): Promise<boolean> };
type Enrolled = { enrolled: boolean } | { why: string };
type Gate = "begin" | "connect" | "token" | "ask" | "delivery";

/** Where an owner enrols a mind: iterate's Cloud app. */
const ENROL_AT = "cloud.iterate.com";

/** The words of a refusal, by where a mind that is not enrolled meets it. `who` is its hostname,
 *  and its id after the page. */
const NOT_ENROLLED: Record<Gate, (who: string) => string> = {
  begin: (who) =>
    `${who} is not enrolled in iterate Cloud, so it cannot connect an account through it. Its owner enrols at ${ENROL_AT}, then starts again from ${who}.`,
  connect: (who) =>
    `${who} is not enrolled in iterate Cloud: nothing is connected. Its owner enrols at ${ENROL_AT}, then connects again.`,
  token: (who) =>
    `${who} is not enrolled in iterate Cloud, so the Cloud gives it no new token. The connection is kept: after its owner enrols at ${ENROL_AT}, the next refresh works.`,
  ask: (who) =>
    `${who} is not enrolled in iterate Cloud, so the Cloud asks nothing for it. Its owner enrols at ${ENROL_AT}.`,
  delivery: (who) =>
    `${who} is not enrolled in iterate Cloud, so its deliveries wait. Its owner enrols at ${ENROL_AT}.`,
};

/** WHETHER THE CLOUD SERVES THE MIND AT THE HOSTNAME `mind`, whose log proves the id `id` (null:
 *  it serves no log): null to serve it, or the refusal.
 *  - iterate's members enrol a mind by its id (`ENROLMENTS`). The Cloud's own mind is served by its
 *    name, because a mind does not meld with itself (core/auth-worker minds.ts).
 *  - `CLOUD_ENROLMENT` = "on" refuses a mind that is not enrolled. Anything else ("log", the
 *    default) serves it and logs `cloud.not-enrolled` once a minute for each hostname. So the list
 *    of the minds that "on" would refuse is in Workers Logs before anyone sets it.
 *  - A read that failed refuses with 503 when "on", and serves when not: iterate's auth Worker
 *    signs every delivery too, so refusing adds no new point of failure. */
async function shutOut(
  mind: string,
  id: string | null,
  gate: Gate,
  env: Env,
): Promise<{ status: number; why: string } | null> {
  if (!env.ENROLMENTS || mind === env.MIND_HOSTNAME) return null;
  const on = env.CLOUD_ENROLMENT === "on";
  const read: Enrolled = id ? await enrolledAt(id, env.ENROLMENTS, env) : { enrolled: false };
  if ("enrolled" in read && read.enrolled) return null;
  // each line once a minute for each hostname: until iterate's auth Worker has `Enrolments`, every
  // read fails, and every refresh and ask would log it
  const { notEnrolledSaid } = await cloudOf(env);
  const event = "why" in read ? "cloud.enrolment-unread" : "cloud.not-enrolled";
  const said = `${event}\n${mind}`;
  if ((notEnrolledSaid.get(said) || 0) <= Date.now() - 60_000) {
    const oldest = notEnrolledSaid.size >= 1_000 ? notEnrolledSaid.keys().next().value : undefined;
    if (oldest) notEnrolledSaid.delete(oldest);
    notEnrolledSaid.set(said, Date.now());
    if ("why" in read) console.error({ event, mind, id, gate, refused: on, why: read.why });
    else console.warn({ event, mind, id, gate, refused: on });
  }
  if (!on) return null;
  if ("why" in read)
    return {
      status: 503,
      why: `iterate Cloud cannot read its enrolments now (${read.why}). Nothing changed: ask again later.`,
    };
  if (!id)
    return {
      status: 403,
      why: `${mind} serves no identity log, so iterate Cloud cannot tell which mind it is: it enrols minds by id. Deploy the mind again with a current release, then enrol it at ${ENROL_AT}.`,
    };
  return { status: 403, why: NOT_ENROLLED[gate](gate === "begin" ? mind : `${mind} (mind ${id})`) };
}

/** `shutOut` for a hostname whose id is not at hand: its log is read (`identityAt`) only where
 *  the gate is in place. */
async function shutOutAt(mind: string, gate: Gate, outbox: IdentityKept, env: Env) {
  if (!env.ENROLMENTS || mind === env.MIND_HOSTNAME) return null;
  const read = await identityAt(mind, outbox, env);
  return shutOut(mind, "identity" in read ? read.identity.expected : null, gate, env);
}

/** Whether the mind `id` is enrolled, kept a minute for each id: a rule that ends, or a new one,
 *  counts within a minute. A read that failed is not kept. */
function enrolledAt(id: string, enrolments: Enrolments, env: Env): Promise<Enrolled> {
  return cloudOf(env).then(({ enrolments: kept }) => {
    const known = kept.get(id);
    if (known && known.until > Date.now()) return known.answer;
    const answer = enrolments.enrolled(id).then(
      (enrolled): Enrolled => ({ enrolled }),
      (error: unknown): Enrolled => ({
        why: String(error instanceof Error ? error.message : error).slice(0, 200),
      }),
    );
    answer.then((read) => "why" in read && kept.get(id)?.answer === answer && kept.delete(id));
    const oldest = kept.size >= 1_000 ? kept.keys().next().value : undefined;
    if (oldest) kept.delete(oldest);
    kept.set(id, { answer, until: Date.now() + 60_000 });
    return answer;
  });
}

/** What speaks for a hostname: the state that its identity log proves, or the key at
 *  `/keys/stack.json` of a hostname that serves no log, or why there is none. */
type Identity =
  | { identity: PublishedMind }
  | { publicKey: string }
  // `serves`: the other mind that the hostname's log proves, when it proves one (`refusedAt`)
  | { why: string; serves?: string };

/** THE KEY THAT SPEAKS FOR THE DEPLOYMENT AT `mind`, with its mind id, or why there is none.
 *  The deployment's identity log decides (iterate/mind-identity-log `publishedMindOf`): the id is
 *  the hash of its genesis, and a statement counts only when a working key that the log lists
 *  now signed it, so a key that the log revoked counts no more. The last state read is kept in
 *  the hostname's Outbox, and a log that does not continue it is refused: a host cannot take a
 *  revoke back, or serve another mind's log at a hostname that this Cloud knows as one mind.
 *
 *  BOTH FORMS ARE READ: a deployment that serves no log, and of which no state is kept, is read
 *  as before, by the key at `/keys/stack.json`, with no id. Once a log was read at a hostname,
 *  the log alone decides there. */
async function askerKeyOf(
  mind: string,
  signed: Signed,
  outbox: DurableObjectStub<Outbox>,
  env: Env,
): Promise<{ publicKey: string; identity?: PublishedMind } | { why: string }> {
  const known = await identityAt(mind, outbox, env);
  if (!("identity" in known)) return known;
  for (const key of known.identity.current.workingKeys)
    if (key.purpose === "statements" && (await keyIdOf(key.publicKey)) === signed.signature?.key)
      return { publicKey: key.publicKey, identity: known.identity };
  return {
    why: `the identity log of ${mind} lists no such working key: the key that signed is not the mind's, or no longer`,
  };
}

/** `readIdentityAt`, kept a minute for each hostname, as the key at `/keys/stack.json` was: an ask
 *  and a refresh wait on no read, and a stranger who names a hostname makes this Worker read it
 *  once a minute at most. So a revoke counts within two minutes: this minute, and the minute
 *  that iterate/mind-identity-log keeps its own answer. A read that threw, or whose own fetch
 *  failed, is not kept: that is this Worker's way out, which may work at the next ask. A host
 *  that answered no log and no key is that host's fault, and is kept. */
function identityAt(mind: string, outbox: IdentityKept, env: Env): Promise<Identity> {
  return cloudOf(env).then(({ askers }) => {
    const kept = askers.get(mind);
    if (kept && kept.until > Date.now()) return kept.answer;
    let failed = false;
    const fetcher = (request: Request) =>
      fetch(request).catch((error: unknown) => {
        failed = true;
        throw error;
      });
    const answer = readIdentityAt(mind, outbox, fetcher);
    const drop = () => askers.get(mind)?.answer === answer && askers.delete(mind);
    answer.then(() => failed && drop(), drop);
    // the oldest answer goes: a full map never drops them all at once
    const oldest = askers.size >= 1_000 ? askers.keys().next().value : undefined;
    if (oldest) askers.delete(oldest);
    askers.set(mind, { answer, until: Date.now() + 60_000 });
    return answer;
  });
}

/** The state of the hostname's log, read on from the one kept in its Outbox. A newer state of a
 *  KNOWN hostname is kept at once, whatever the statement proves, so that a revoke stays read. A
 *  hostname of which nothing is kept gets a state only with a statement that verified
 *  (`firstUse`): a stranger's junk statement makes this Worker write nothing. */
async function readIdentityAt(
  mind: string,
  outbox: IdentityKept,
  fetcher: (request: Request) => Promise<Response>,
): Promise<Identity> {
  const kept = await outbox.keptIdentity();
  const read = await publishedMindOf(mind, fetcher, kept);
  if (!("why" in read)) {
    if (kept && read.head !== kept.head) await outbox.keepIdentity(read);
    return { identity: read };
  }
  if (kept) return refusedAt(mind, kept, outbox, read.why, fetcher);
  const published = await stackKeyOf(mind, fetcher);
  if (typeof published !== "string")
    return {
      why: `${controlPlaneOf(mind)} serves no identity log, and /keys/stack.json answers no key: ${published.why}`,
    };
  return { publicKey: published };
}

/** WHY A HOSTNAME THAT THIS CLOUD KNOWS AS ONE MIND IS REFUSED NOW, after a log that does not
 *  continue the state kept. When the hostname's log, read from its genesis, proves another mind,
 *  that is kept in its Outbox (`refusedIdentity`) for a person to see, and logged. A host that
 *  answers nothing keeps nothing: that may pass at the next read. Only a hostname of which a
 *  state is kept is read again, so a stranger makes this Worker ask no host for it. */
async function refusedAt(
  mind: string,
  kept: PublishedMind,
  outbox: IdentityKept,
  why: string,
  fetcher: (request: Request) => Promise<Response>,
): Promise<{ why: string; serves?: string }> {
  const now = await publishedMindOf(mind, fetcher);
  const other = "why" in now || now.expected === kept.expected ? null : now.expected;
  console.warn({ event: "cloud.asker-refused", mind, known: kept.expected, serves: other });
  if (!other)
    return { why: `${mind} serves no identity log that continues the one read here: ${why}` };
  await outbox.refusedIdentity(other);
  return {
    why: `${mind} is known here as the mind ${kept.expected}, and its log now proves the mind ${other}`,
    serves: other,
  };
}

/** What the identity readers keep for a hostname: its Outbox, called from the Worker or from
 *  inside the Outbox itself (`Outbox.#movedTo`). */
type IdentityKept = {
  keptIdentity(): Promise<PublishedMind | undefined>;
  keepIdentity(state: PublishedMind): Promise<void>;
  refusedIdentity(mind: string): Promise<void>;
};

/** A deployment's own public key, as its auth Worker publishes it on its control plane, or why
 *  there is none. Waited for five seconds, and kept a minute by `identityAt`: anyone can name any
 *  hostname in a statement, so a stranger must not make this Worker ask another host often, or
 *  wait on one. */
async function stackKeyOf(
  mind: string,
  fetcher: (request: Request) => Promise<Response>,
): Promise<string | { why: string }> {
  try {
    // a redirect is no answer: the key is the one this very hostname serves
    const answer = await fetcher(
      new Request(`${controlPlaneOf(mind)}/keys/stack.json`, {
        redirect: "manual",
        signal: AbortSignal.timeout(5_000),
      }),
    );
    const { publicKey } = (await answer.json().catch(() => ({}))) as { publicKey?: unknown };
    return answer.ok && typeof publicKey === "string"
      ? publicKey
      : { why: `it answered ${answer.status}` };
  } catch (error) {
    return { why: String(error).slice(0, 200) };
  }
}
/** A CODE EXCHANGE OR A REFRESH, as a deployment's vault sends it: a token request's form, with no
 *  client secret. The Cloud adds the client's credentials and sends it to the provider. An exchange
 *  must show the proof its code was sent on with. A refresh must hold a token sealed for this
 *  deployment. The answer is the provider's, with the refresh token sealed.
 *
 *  A REFRESH'S ANSWER MAY NOT ARRIVE, and the provider spent the refresh token for it. So the
 *  Cloud keeps that answer for two days, sealed under the spent token (`keptBy`), and gives it to
 *  a retry that shows the same token, with no second request to the token endpoint. A refresh that
 *  shows the new token ends the kept copy: the deployment stored it. And one refused refresh ends
 *  nothing the person connected; a second one on a later try does (`Routes.refused`). */
async function token(
  request: Request,
  name: string,
  client: Client,
  cloud: Cloud,
  env: Env,
): Promise<Response> {
  const body = await request.text();
  const asker = await askedBy(request, body, TOKEN_REQUESTED, name, env);
  if (asker instanceof Response) return asker;
  const form = new URLSearchParams(body);
  const grant = form.get("grant_type") || "";
  const out = new URLSearchParams({ grant_type: grant });
  /** Who the tokens are for at the provider, known from a sealed refresh token. */
  let person = "";
  /** The accounts the person agreed to connect: from the callback's proof, or the sealed token.
   *  A token sealed before that choice existed names none: every account they administer. */
  let wanted: string[] | undefined;
  /** The code is a sign-in's (`SIGN_IN_CALLBACK`): the answer is the id_token alone. */
  let signIn = false;
  /** The scopes the press before Google agreed to, from the callback's proof; a refresh has none: its
   *  token came from an exchange that this check passed. */
  let named = "";
  /** A refresh: where the answer to its token is kept, and under which key. */
  let spent: Awaited<ReturnType<typeof keptBy>> | undefined;
  const routes = routesOf(env);
  if (grant === "authorization_code") {
    const code = form.get("code") || "";
    const [mac = "", list = "", scopes = ""] = (form.get("cloud_proof") || "").split(".");
    const agreed = Buffer.from(list, "base64url").toString();
    named = Buffer.from(scopes, "base64url").toString();
    const provedFor = (how: "authorize" | "install" | "sign-in") =>
      crypto.subtle.verify(
        "HMAC",
        cloud.proofKey,
        Buffer.from(mac, "base64url"),
        proofInput(name, asker.mind, code, how, agreed, named),
      );
    wanted = agreed.split(",").filter(Boolean);
    signIn = await provedFor("sign-in");
    const authorized = signIn || (await provedFor("authorize"));
    if (!authorized && !(await provedFor("install")))
      return refuse(403, "the Cloud did not send this code to this deployment");
    out.set("code", code);
    // the redirect URI the authorize named, which the exchange repeats: this Cloud's own, which
    // the callback saw. A GitHub App's install page named none.
    if (authorized)
      out.set("redirect_uri", `${new URL(request.url).origin}/clients/${name}/callback`);
    if (form.get("code_verifier")) out.set("code_verifier", form.get("code_verifier")!);
  } else if (grant === "refresh_token") {
    const held = await unseal(cloud.sealKey, form.get("refresh_token") || "");
    if (!held || held.mind !== asker.mind || held.client !== name)
      return refuse(403, "this refresh token is not this deployment's");
    out.set("refresh_token", held.token);
    person = held.by || "";
    wanted = held.accounts;
    spent = await keptBy(held.token, name, asker.mind);
    if (held.after) await routes.forget(`answer\n${held.after}`);
  } else return refuse(400, "grant_type is authorization_code or refresh_token");

  const kept =
    spent &&
    (await unseal<{ tokens: Record<string, unknown>; at: number }>(
      spent.key,
      (await routes.kept(`answer\n${spent.name}`)) || "",
    ));
  let tokens = kept ? kept.tokens : null;
  // the access token's time ran on while its answer was kept
  if (kept && typeof kept.tokens.expires_in === "number")
    kept.tokens.expires_in = Math.max(
      0,
      kept.tokens.expires_in - Math.floor((Date.now() - kept.at) / 1000),
    );
  if (!tokens) {
    const { clientSecret } = cloud.secrets[name]!;
    const headers = new Headers({
      "content-type": "application/x-www-form-urlencoded",
      accept: "application/json",
    });
    // X takes a confidential client by HTTP Basic alone; GitHub, Google and Slack take it in the form
    if (client.kind === "x")
      headers.set("authorization", `Basic ${btoa(`${client.clientId}:${clientSecret}`)}`);
    else {
      out.set("client_id", client.clientId);
      out.set("client_secret", clientSecret);
    }
    const parsed = (answered: string): Record<string, unknown> | null => {
      try {
        return JSON.parse(answered);
      } catch {
        // a refusal that is no JSON goes back as it came
        return null;
      }
    };
    // only an answer that spent the token: one the provider did not replace still refreshes
    const keepWhatSpent = async (answer: Record<string, unknown> | null) => {
      if (
        spent &&
        typeof answer?.access_token === "string" &&
        typeof answer.refresh_token === "string"
      )
        await routes.keep(
          `answer\n${spent.name}`,
          KEPT_ANSWER_MS,
          await seal(spent.key, { tokens: answer, at: Date.now() }),
        );
    };
    // The provider has PROVIDER_WAIT_MS to answer. Its call is not ended then: it may spend the
    // refresh token for an answer that comes a second later, so the call goes on after the Cloud
    // answered, and what comes of it is kept as any other answer, for the retry.
    const asked = fetch(client.tokenEndpoint, { method: "POST", headers, body: out }).then(
      async (answer) => ({ answer, answered: await answer.text() }),
    );
    let limit: ReturnType<typeof setTimeout> | undefined;
    const first = await Promise.race([
      asked.catch(() => null),
      new Promise<"late">((resolve) => {
        limit = setTimeout(() => resolve("late"), PROVIDER_WAIT_MS);
      }),
    ]);
    clearTimeout(limit);
    // No word on the grant. A refresh token is shown again; a code is not, it may be spent.
    const again = spent ? "ask again with the same token" : "connect again";
    if (!first) return refuse(502, `no answer from the provider: ${again}`);
    if (first === "late") {
      waitUntil(asked.then(({ answered }) => keepWhatSpent(parsed(answered))).catch(() => {}));
      return refuse(
        504,
        `no answer from the provider in ${PROVIDER_WAIT_MS / 1000} seconds: ${again}`,
      );
    }
    const { answer, answered } = first;
    tokens = parsed(answered);
    if (typeof tokens?.access_token !== "string") {
      // The provider refused. A refresh it refuses twice means the person's grant is over (they
      // withdrew the app's access, or the token was spent elsewhere): what they connected for
      // this deployment ends with the second refusal. Not a 429, nor a 5xx: "too many requests"
      // and a failure say nothing about the grant, and the deployment asks again. Slack's routes
      // are claimed at the install alone, so one let go here would stay gone.
      if (person && answer.status < 500 && answer.status !== 429)
        await routes.refused(name, person, asker.mind);
      return new Response(answered, {
        status: answer.status,
        headers: {
          "content-type": answer.headers.get("content-type") || "text/plain",
          "cache-control": "no-store",
        },
      });
    }
    await keepWhatSpent(tokens);
  }
  if (person) await routes.refreshed(name, person, asker.mind);
  // A SIGN-IN'S ANSWER IS WHO THE PERSON IS, in Google's own signed words, which the deployment
  // checks itself. Whatever the consent was for, no token that reaches their account goes back.
  if (signIn) return json(200, { id_token: tokens.id_token });
  // The token is not revoked at Google: a revoke there ends the person's whole grant to iterate's
  // one app, the tokens of their other deployments with it. It goes nowhere from here.
  const more =
    client.kind === "google" && grant === "authorization_code" ? beyond(named, tokens.scope) : [];
  if (more.length > 0)
    return refuse(
      403,
      `Google's token reaches more than the page named (${more.join(", ")}). Nothing is connected: start again from ${asker.mind}.`,
    );
  // A CLOUDFLARE TOKEN THAT REACHES MORE THAN THE CLIENT IS FOR connects nothing, at the connect
  // and at every refresh, where Cloudflare's answer names the token's scopes. An answer that
  // names none is let through: the link was held to the client's list (`begin`), and Cloudflare
  // gives a consent no scope that the client is not registered for.
  if (client.kind === "cloudflare" && typeof tokens.scope === "string") {
    const over = beyondClient(client, tokens.scope.split(/\s+/).filter(Boolean));
    if (over.length > 0)
      return refuse(
        403,
        `Cloudflare's token reaches more than this connection is for (${over.join(", ")}). Nothing is connected: start again from ${asker.mind}.`,
      );
  }
  // WHAT THE PERSON AGREED TO AND ADMINISTERS NOW is what this deployment is connected to: at the
  // connect, and again at every refresh, so an account they no longer own leaves with the next one.
  const reached = await reachedBy(client, String(tokens.access_token), tokens, wanted);
  // A SLACK TOKEN IS THE WORKSPACE'S: the bot reads and writes as the workspace, whoever installed
  // the app. So a person who does not administer the workspace gets no token for a deployment, and
  // not only no events. Slack names the person at the install alone: a refresh goes on for the
  // workspace that an admin connected (`person`, from the sealed token), and for no other.
  if (
    client.kind === "slack" &&
    !reached.by &&
    !(person && person === String((tokens.team as { id?: unknown } | undefined)?.id || ""))
  )
    return refuse(403, "Only an admin or an owner of a Slack workspace can connect it.");
  if (reached.by) await routes.claim(name, reached.by, reached.accounts, asker.mind);
  // GMAIL AND CALENDAR: the deployment is told which mailbox and which calendar it connected
  // (`gmailConnected`, `calendarConnected`). The tokens do not wait on it: what is not told now
  // is told at the next refresh.
  const connect = grant === "authorization_code";
  let calendar = "";
  if (client.kind === "google") {
    const to = { origin: new URL(request.url).origin, name, client, mind: asker.mind };
    if (reached.by)
      await gmailConnected(to, reached.by, connect, env).catch((error) =>
        console.warn({ event: "cloud.gmail-connected-not-told", mind: asker.mind, error }),
      );
    calendar = await calendarConnected(to, tokens, connect, cloud, env).catch((error) => {
      console.warn({ event: "cloud.calendar-connected-not-told", mind: asker.mind, error });
      return "";
    });
  }
  // a new connect replaces the grant that was refused
  if (grant === "authorization_code" && reached.by)
    await routes.refreshed(name, reached.by, asker.mind);
  if (typeof tokens.refresh_token === "string")
    tokens.refresh_token = await seal(cloud.sealKey, {
      token: tokens.refresh_token,
      mind: asker.mind,
      client: name,
      // whose refused refresh ends what was connected: the mailbox's address, or the calendar's
      // for a grant that reads no mail
      by: reached.by || calendar || person,
      accounts: wanted,
      after: spent?.name,
    });
  return json(200, tokens);
}

/** WHAT A NEW TOKEN REACHES at the provider, by the ids its webhooks and its bot's messages name:
 *  an X user, or the GitHub App's installations that the person who consented agreed to connect
 *  (`wanted`) and administers: one on their own account, or on an organization they own. An installation hands out every repository
 *  it was given, so seeing it is not enough: a member of an organization must not get its events
 *  and its tokens by connecting a deployment of their own (core/os integrations/rules.ts
 *  `githubInstallationRefusal`, the same rule). The deployment that connected them gets their
 *  events. For Slack it is the workspace the app was installed into, when the person who installed
 *  it is an admin or an owner there (`users.info`). For Google it is the one mailbox the token
 *  reads, by its address, and nothing for a grant that reads no mail. `by` is the person at the
 *  provider, or for Slack the workspace and for Google the address, whose claim this is. */
async function reachedBy(
  client: Client,
  accessToken: string,
  answer: Record<string, unknown>,
  wanted: string[] | undefined,
): Promise<{ by: string; accounts: string[] }> {
  // SLACK'S OWN ANSWER names the workspace the bot token is for and the person who installed the
  // app. The workspace is claimed only when that person administers it: a workspace may let any
  // member install an app, and its events are everybody's messages, so a member must not get them
  // by connecting a deployment of their own (the rule the GitHub installations below have). A
  // member's install claims nothing and takes nothing away: what an admin connected stays.
  if (client.kind === "slack") {
    const none = { by: "", accounts: [] };
    const team = String((answer.team as { id?: unknown } | undefined)?.id || "");
    const installer = String((answer.authed_user as { id?: unknown } | undefined)?.id || "");
    if (!team || !installer) return none;
    const asked = await fetch(
      `${client.api}/api/users.info?${new URLSearchParams({ user: installer })}`,
      { headers: { authorization: `Bearer ${accessToken}` } },
    );
    const { ok, user } = (asked.ok ? await asked.json().catch(() => ({})) : {}) as {
      ok?: unknown;
      user?: {
        id?: unknown;
        team_id?: unknown;
        deleted?: unknown;
        is_admin?: unknown;
        is_owner?: unknown;
      };
    };
    const administers =
      ok === true &&
      user?.id === installer &&
      user.team_id === team &&
      user.deleted !== true &&
      (user.is_admin === true || user.is_owner === true);
    return administers ? { by: team, accounts: [team] } : none;
  }
  const ask = async (path: string): Promise<any> => {
    const answer = await fetch(`${client.api}${path}`, {
      headers: {
        authorization: `Bearer ${accessToken}`,
        accept: "application/json",
        "user-agent": "iterate-cloud",
      },
    });
    return answer.ok ? answer.json() : null;
  };
  if (client.kind === "github") {
    const user = await ask("/user");
    const { installations = [] } = (await ask("/user/installations?per_page=100")) || {};
    const administered: string[] = [];
    for (const { id, account } of installations as {
      id: number;
      account?: { id: number; login: string; type: string };
    }[]) {
      // only what the person agreed to connect: by the account's name, or by the installation
      // they chose at GitHub
      if (
        wanted &&
        ![`#${id}`, account?.login.toLowerCase()].some((each) => wanted.includes(each!))
      )
        continue;
      const membership =
        account?.type === "Organization"
          ? await ask(`/user/memberships/orgs/${encodeURIComponent(account.login)}`)
          : null;
      const owns =
        account?.type === "Organization"
          ? membership?.state === "active" && membership.role === "admin"
          : !!account && account.id === user?.id;
      if (owns) administered.push(String(id));
    }
    return { by: user?.id ? String(user.id) : "", accounts: administered };
  }
  if (client.kind === "x") {
    const id = String((await ask("/2/users/me"))?.data?.id || "");
    return { by: id, accounts: id ? [id] : [] };
  }
  // A GOOGLE TOKEN IS ONE ACCOUNT'S, and its mailbox is that person's own: nobody else administers
  // it. The route is the mailbox's, in Gmail's own word for it, which is the word its push names.
  // ONLY A GRANT THAT READS THE MAILBOX GETS ITS ROUTE: a push says when a mailbox changes, and a
  // person who gave a deployment their address alone, or leave to send, did not give it that. So
  // Gmail's profile is asked, which answers a grant that reads mail and no other, and the
  // account's address from elsewhere makes no route. Such a grant claims nothing, and so takes
  // nothing from a grant of the same account that does read mail. A request that fails claims
  // nothing either: the tokens Google just gave go back all the same.
  if (client.kind === "google") {
    const profile = await ask("/gmail/v1/users/me/profile").catch(() => null);
    const address = addressOf(profile?.emailAddress);
    return { by: address, accounts: address ? [address] : [] };
  }
  return { by: "", accounts: [] };
}

/** A GMAIL ADDRESS as a route has it, in lower case; "" for what is no plain address. The
 *  address is one segment of the path a deployment gets the mailbox's events on
 *  (`/integrations/<client>/<address>`), so one with a `/` in it names no mailbox here, nor one
 *  with a character that no Google address has. */
function addressOf(named: unknown): string {
  const address = typeof named === "string" ? named.trim().toLowerCase() : "";
  return /^[a-z0-9._+'-]{1,64}@[a-z0-9.-]{1,255}$/.test(address) ? address : "";
}

/** A GOOGLE CLIENT'S PUSH, when its config names all of it; else none, and the client takes no
 *  push. A half config must not half check: with no audience any subscription's token would
 *  pass, and with no service account a token that names no address would. */
function gmailPushOf(client: Client) {
  const push = client.kind === "google" ? client.gmailPush : undefined;
  return push?.topic && push.audience && push.serviceAccount ? push : undefined;
}

/** A GITHUB APP INSTALLATION'S TOKEN, for a deployment that connected the installation: the App's
 *  private key signs here and never leaves. The answer is GitHub's: `{ token, expires_at }`, good
 *  for an hour. */
async function installationToken(
  request: Request,
  name: string,
  client: Client,
  cloud: Cloud,
  env: Env,
): Promise<Response> {
  const body = await request.text();
  const asker = await askedBy(
    request,
    body,
    "events.iterate.com/integration/installation-token-requested",
    name,
    env,
  );
  if (asker instanceof Response) return asker;
  const { appPrivateKey } = cloud.secrets[name]!;
  if (client.kind !== "github" || !client.appId || !appPrivateKey)
    return refuse(404, `${name} is no GitHub App`);
  let id = "";
  try {
    id = String(JSON.parse(body).installationId);
  } catch {
    // no id: refused below
  }
  const connected: string[] = /^\d+$/.test(id) ? await routesOf(env).mindsOf(name, id) : [];
  if (!connected.includes(asker.mind))
    return refuse(403, `${asker.mind} has not connected installation ${id || "(none)"}`);
  const age = claimAgeOf(env, client);
  if (age && !(await routesOf(env).mindsOf(name, id, age)).includes(asker.mind))
    return refuse(
      403,
      `${asker.mind} connected installation ${id} too long ago: the grant of the person who connected it has not refreshed for ${env.GITHUB_CLAIM_DAYS} days. Refresh that grant, or connect GitHub again.`,
    );
  const answer = await fetch(`${client.api}/app/installations/${id}/access_tokens`, {
    method: "POST",
    headers: {
      authorization: `Bearer ${await appJwt(client.appId, appPrivateKey)}`,
      accept: "application/vnd.github+json",
      "user-agent": "iterate-cloud",
    },
  });
  return new Response(answer.body, {
    status: answer.status,
    headers: { "content-type": "application/json", "cache-control": "no-store" },
  });
}

/** A GitHub App's JWT (RS256, nine minutes): what GitHub mints an installation token for. */
async function appJwt(appId: string, pkcs8Pem: string): Promise<string> {
  const key = await crypto.subtle.importKey(
    "pkcs8",
    Buffer.from(pkcs8Pem.replace(/-----[^-]+-----|\s/g, ""), "base64"),
    { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" },
    false,
    ["sign"],
  );
  const now = Math.floor(Date.now() / 1000);
  const part = (value: object) => base64url(encoder.encode(JSON.stringify(value)));
  const signed = `${part({ alg: "RS256", typ: "JWT" })}.${part({ iat: now - 60, exp: now + 540, iss: appId })}`;
  const signature = await crypto.subtle.sign("RSASSA-PKCS1-v1_5", key, encoder.encode(signed));
  return `${signed}.${base64url(signature)}`;
}

// ── the bot ──────────────────────────────────────────────────────────────────────────────────────

/** The link's `until` when its proof is the Cloud's and it has not lapsed, else null. */
async function botLinkUntil(key: CryptoKey, name: string, until: string, proof: string) {
  const mine = await crypto.subtle.verify(
    "HMAC",
    key,
    Buffer.from(proof, "base64url"),
    encoder.encode(`bot-link\n${name}\n${Number(until)}`),
  );
  return mine && Number(until) > Date.now() ? Number(until) : null;
}

/** THE BOT'S CONSENT, from an operator's link: X's consent page for the bot's own account, with
 *  the scopes the bot needs. Whoever is signed in at X when they consent becomes the bot. Any other
 *  query of the link goes on to X as it is (a fake names its account there). */
async function botConsent(url: URL, name: string, client: Client, cloud: Cloud): Promise<Response> {
  const { until: given, proof, ...rest } = Object.fromEntries(url.searchParams);
  const until = await botLinkUntil(cloud.proofKey, name, given || "", proof || "");
  if (client.kind !== "x" || !until)
    return refuse(403, "This link is not the Cloud's, or it has lapsed.");
  const verifier = await botProofOf(cloud.proofKey, "verifier", name, until);
  const to = new URL(client.authorizationEndpoint);
  for (const [key, value] of Object.entries({
    ...rest,
    response_type: "code",
    client_id: client.clientId,
    redirect_uri: `${url.origin}/clients/${name}/callback`,
    scope: BOT_SCOPES,
    state: `bot.${until}.${proof}`,
    code_challenge: base64url(await crypto.subtle.digest("SHA-256", encoder.encode(verifier))),
    code_challenge_method: "S256",
  }))
    to.searchParams.set(key, value);
  return Response.redirect(to.href, 302);
}

/** X sent the bot's consent back: the Cloud redeems the code itself and keeps the bot's tokens. */
async function botConnected(
  url: URL,
  name: string,
  client: Client,
  cloud: Cloud,
  env: Env,
  given: string,
  proof: string,
): Promise<Response> {
  const until = await botLinkUntil(cloud.proofKey, name, given, proof);
  const code = url.searchParams.get("code");
  if (client.kind !== "x" || !until || !code)
    return refuse(403, "This consent was not begun by the Cloud, or it has lapsed.");
  const tokens = await tokensOf(client, cloud.secrets[name]!.clientSecret, {
    grant_type: "authorization_code",
    code,
    redirect_uri: `${url.origin}/clients/${name}/callback`,
    code_verifier: await botProofOf(cloud.proofKey, "verifier", name, until),
  });
  const me = await fetch(`${client.api}/2/users/me`, {
    headers: { authorization: `Bearer ${tokens.accessToken}` },
  });
  const self = (
    (await me.json().catch(() => null)) as { data?: { id: string; username: string } } | null
  )?.data;
  if (!me.ok || !self) return refuse(502, `X named no account for the bot: HTTP ${me.status}`);
  // one link connects one account: whoever finds the link afterwards cannot become the bot
  if (!(await env.BOT.get(env.BOT.idFromName(name)).firstUseOfLink(until)))
    return refuse(403, "This link was already used to connect the bot. Make a new one.");
  await env.BOT.get(env.BOT.idFromName(name)).setAccount(name, url.origin, tokens, {
    id: self.id,
    username: self.username,
  });
  return page(
    `The bot is @${self.username}`,
    `The bot is @${escaped(self.username)}`,
    `<p>What reaches @${escaped(self.username)} from a linked X account now goes to the deployment that
     linked it, and that deployment may answer as @${escaped(self.username)}.</p>`,
  );
}

/** X'S PUSH for the bot's account (its Activity API, delivered to the app's webhook; bot.ts).
 *
 *  GET is X's check that this address is the app's, when the webhook is registered and from time
 *  to time after: the answer is the token it sent, keyed with the app's client secret. A delivery
 *  is signed the same way, over its body. So this answer must never sign what could be a
 *  delivery: a token is letters, digits and base64's marks, and a delivery is a JSON object.
 *
 *  POST is a delivery: checked, taken once, and handed to the bot, which relays each message in
 *  it to the deployment that linked its sender, as a statement of the Cloud's mind. */
async function pushed(
  request: Request,
  url: URL,
  name: string,
  cloud: Cloud,
  env: Env,
): Promise<Response> {
  const key = await crypto.subtle.importKey(
    "raw",
    encoder.encode(cloud.secrets[name]!.clientSecret),
    { name: "HMAC", hash: "SHA-256" },
    false,
    ["sign", "verify"],
  );
  if (request.method === "GET") {
    const token = url.searchParams.get("crc_token") || "";
    if (!/^[\w+/=.:-]{1,512}$/.test(token)) return refuse(400, "X's check carries a crc_token");
    const answer = await crypto.subtle.sign("HMAC", key, encoder.encode(token));
    return json(200, { response_token: `sha256=${Buffer.from(answer).toString("base64")}` });
  }
  const body = await bodyWithin(request, WEBHOOK_BODY_MAX_BYTES);
  if (!body) return refuse(413, "Payload too large");
  const signature = /^sha256=([A-Za-z0-9+/]{43}=)$/.exec(
    request.headers.get("x-twitter-webhooks-signature-oauth2")?.trim() || "",
  )?.[1];
  const signedByX =
    !!signature &&
    (await crypto.subtle.verify("HMAC", key, Buffer.from(signature, "base64"), body.bytes));
  if (!signedByX) return refuse(401, "the signature is wrong");
  // what the body claims: X signed it, and its shape is still X's to change
  let event: (Pushed & { event_uuid?: unknown }) | undefined;
  try {
    event = (JSON.parse(body.text) as { data?: Pushed }).data;
  } catch {
    return refuse(400, "a delivery is JSON");
  }
  if (!event || typeof event !== "object" || Array.isArray(event))
    return json(200, { relayed: false });
  // Public posts use the durable inbox before X receives an acknowledgement.
  if (event.event_type === "post.create") {
    const post = publicPost(event);
    // X signed it, so X must not send it again: it is answered, and taken by nobody
    if (!post) {
      const id = typeof event.event_uuid === "string" ? event.event_uuid.slice(0, 64) : undefined;
      console.warn({ event: "cloud.x-post-not-taken", id });
      return json(200, { accepted: false });
    }
    const first = await env.OUTBOX.get(env.OUTBOX.idFromName(`inbox\n${name}`)).take({
      client: name,
      account: post.filter.user_id,
      id: `x-post:${post.event_uuid}`,
      type: "events.iterate.com/x/post-created",
      payload: post,
      publicPost: true,
    });
    return json(200, { accepted: true, redelivery: !first });
  }
  // X may send one event again: taken once (and the bot relays each message once, however it came)
  const id = typeof event.event_uuid === "string" ? event.event_uuid : "";
  if (id && (await routesOf(env).once(`delivery\n${name}\n${id}`, HELD_MS, "1")))
    return json(200, { relayed: false, redelivery: true });
  await env.BOT.get(env.BOT.idFromName(name)).pushed(event);
  return json(200, { relayed: true });
}

/** A DEPLOYMENT WATCHES AN X ACCOUNT'S PUBLIC POSTS, or lets go, or lists what it watches
 *  (bot.ts `subscribePost`). Signed as any ask is; it changes only the asker's own interest. */
async function postSubscriptions(
  request: Request,
  name: string,
  action: string,
  env: Env,
): Promise<Response> {
  const received = await bodyWithin(request, 4096);
  if (!received) return refuse(413, "request too large");
  const body = received.text;
  const asker = await askedBy(request, body, ASK_REQUESTED, name, env);
  if (asker instanceof Response) return asker;
  let parsed: unknown;
  try {
    parsed = JSON.parse(body);
  } catch {
    return refuse(400, "expected JSON");
  }
  const input = objectOf(parsed);
  if (!input) return refuse(400, "expected an object");
  const bot = env.BOT.get(env.BOT.idFromName(name));
  if (action === "ask/list") {
    if (Object.keys(input).length) return refuse(400, "list takes an empty object");
    return json(200, { subscriptions: await bot.postSubscriptionsOf(asker.mind) });
  }
  const userId = askedUserId(input);
  if (!userId) return refuse(400, 'expected { eventType: "post.create", userId }');
  const answer =
    action === "ask/subscribe"
      ? await bot.subscribePost(asker.mind, userId)
      : await bot.unsubscribePost(asker.mind, userId);
  if ("refused" in answer) return refuse(answer.refused.status, answer.refused.error);
  return json(200, answer);
}

/** A DEPLOYMENT LETS GO OF ONE ACCOUNT it connected: an installation of the App, an X account, a
 *  workspace. A person's consent reaches every account they administer, and a deployment may want
 *  fewer. That account's events stop coming here and its tokens are no longer minted for this
 *  deployment, and a later refresh of the person's grant does not bring it back. `again: true`
 *  takes that word back: the next exchange or refresh connects the account again, if the person
 *  still administers it. A deployment asks this for itself alone. */
async function letGo(request: Request, name: string, env: Env): Promise<Response> {
  const body = await request.text();
  const asker = await askedBy(request, body, ASK_REQUESTED, name, env);
  if (asker instanceof Response) return asker;
  // what the body claims before any check: untrusted JSON
  let asked: { account?: unknown; again?: unknown };
  try {
    asked = JSON.parse(body);
  } catch {
    return refuse(400, "a release is JSON");
  }
  const account = typeof asked.account === "string" ? asked.account : "";
  if (!/^[\w.-]{1,64}$/.test(account))
    return refuse(400, "a release is { account } or { account, again: true }");
  await routesOf(env).letGo(name, asker.mind, account, asked.again === true);
  const connected = (await routesOf(env).mindsOf(name, account)).includes(asker.mind);
  return json(200, { account, connected });
}

/** One deployment's row of `status`: what the Cloud holds for it, and no token and no person.
 *  `accounts` are the provider's own account ids: a GitHub installation, a Slack workspace, an X
 *  user, and for Google the mailbox's address. */
type StatusRow = {
  mind: string;
  accounts: { client: string; account: string; since: number | null }[];
  letGo: { client: string; account: string }[];
} & OutboxStatus;
type OutboxStatus = {
  /** The mind this hostname is pinned to (README "How each side knows the other"); null for one
   *  that never asked with an identity log. */
  id: string | null;
  /** Another mind that the hostname's log proved, and when: nothing is sent to it then. */
  movedTo: { id: string; at: number } | undefined;
  /** How many statements wait for the deployment, and since when. */
  held: number;
  oldestAt: number | null;
  lastRefused: Refusal | null;
};

/** How many deployments one answer of `status` holds. */
const STATUS_PAGE = 200;
/** How many rows of each kind (routes, claims, accounts let go) one `status` reads, at most. A
 *  status reads them all, a deployment's own too: the rows are keyed by client and account, not by
 *  deployment. Each row is a short key, so this is a few MB of one object's storage at most:
 *  20,000 routes is 1,000 accounts at the most deployments one account has (20), or 20,000 single
 *  connections. Past it, the answer says `partial` and the log `cloud.status-partial`. */
const STATUS_ROWS_READ = 20_000;

/** THE CLOUD'S OWN MIND asks: the asker `MIND_HOSTNAME`, pinned to an id, and to `MIND_ID` when that
 *  is set. It reads every deployment's status (`status`), and clears a hostname that moved
 *  (`forget`). */
function isCloudsOwnMind(asker: { mind: string; id: string | null }, env: Env) {
  return (
    !!env.MIND_HOSTNAME &&
    asker.mind === env.MIND_HOSTNAME &&
    !!asker.id &&
    (!env.MIND_ID || asker.id === env.MIND_ID)
  );
}

/** `POST /clients/<name>/ask/forget { hostname, known?, serves? }`: THE CLOUD FORGETS A HOSTNAME
 *  THAT MOVED to another mind (`#movedTo`). The hostname stays pinned to the mind it knew, so a new
 *  mind there (another owner, or the same owner's mind made again) is refused and gets nothing, and
 *  the old mind's statements wait. Two askers may end that:
 *  - the old mind itself, from any hostname: its log proves the id that the hostname is pinned to;
 *  - the Cloud's own mind, for an old mind that is gone: it names the pinned id (`known`) and the
 *    id the hostname's log proved instead in the last day (`serves`), as its status showed them.
 *  Dropped, and not to be undone: the hostname's connections, the accounts it let go, its calendar
 *  channels and refusals (`Routes.forgetMind`), and what its Outbox holds: the statements that
 *  wait and the pin. Its nonces stay. The next mind that asks from the hostname is pinned. A mind
 *  may clear its own hostname at any time, moved or not. */
async function forget(request: Request, name: string, env: Env): Promise<Response> {
  const received = await bodyWithin(request, 4096);
  if (!received) return refuse(413, "request too large");
  const asker = await askedBy(request, received.text, ASK_REQUESTED, name, env);
  if (asker instanceof Response) return asker;
  // what the body claims before any check: untrusted JSON
  let asked: { hostname?: unknown; known?: unknown; serves?: unknown };
  try {
    asked = JSON.parse(received.text || "{}");
  } catch {
    return refuse(400, "a forget ask is JSON: { hostname, known?, serves? }");
  }
  const { hostname, known, serves } = asked;
  if (typeof hostname !== "string" || !HOSTNAME.test(hostname))
    return refuse(400, "a forget ask names a hostname");
  const outbox = env.OUTBOX.get(env.OUTBOX.idFromName(hostname));
  const pinned = await outbox.status();
  if (!pinned.id) {
    // A HOSTNAME THAT SERVES NO MIND NOW: one that moved before the Cloud pinned ids. Only the
    // Cloud's own mind clears it, and only when nothing there takes a statement: no identity log,
    // no stack key, and a statement that has waited an hour. A mind with no log still serves its
    // stack key, so an older mind that only refuses is not cleared.
    if (!isCloudsOwnMind(asker, env))
      return refuse(409, `${hostname} is pinned to no mind: nothing waits to be cleared`);
    if (!pinned.oldestAt || pinned.oldestAt > Date.now() - UNPINNED_STALE_MS)
      return refuse(409, `${hostname} is pinned to no mind, and no statement there waited an hour`);
    const log = await publishedMindOf(hostname, fetch);
    if (!("why" in log)) return refuse(409, `${hostname} serves the log of ${log.expected}`);
    if (typeof (await stackKeyOf(hostname, fetch)) === "string")
      return refuse(409, `${hostname} serves a stack key`);
  }
  const itself = !!pinned.id && asker.id === pinned.id;
  const forGone =
    !pinned.id ||
    (isCloudsOwnMind(asker, env) &&
      known === pinned.id &&
      !!pinned.movedTo &&
      serves === pinned.movedTo.id &&
      pinned.movedTo.at > Date.now() - HELD_MS);
  if (!itself && !forGone)
    return refuse(
      403,
      `${hostname} is cleared by the mind it is pinned to, or by iterate's own mind with the ids that its status shows (known, and serves within a day)`,
    );
  const rows = await routesOf(env).forgetMind(hostname);
  const held = await outbox.forget();
  (await cloudOf(env)).askers.delete(hostname);
  console.warn({
    event: "cloud.mind-forgotten",
    mind: hostname,
    known: pinned.id,
    serves: pinned.movedTo?.id || null,
    by: asker.mind,
    rows,
    held,
  });
  return json(200, { mind: hostname, forgotten: pinned.id, rows, held });
}

/** WHAT THE CLOUD HOLDS FOR A DEPLOYMENT (`POST /clients/<name>/ask/status`): which accounts deliver
 *  to it, what it let go of, the mind its hostname is pinned to, another mind that hostname
 *  serves now, what waits in its outbox, and the last refusal. A deployment reads its own row.
 *  THE CLOUD'S OWN MIND reads every deployment's row, `STATUS_PAGE` at a time after `cursor` (a
 *  hostname): the hostname `MIND_HOSTNAME`, pinned to the id `MIND_ID` when that is set, else to
 *  an id at all. It is the list of who is connected for the Cloud's own page. No token, no secret
 *  and no person's id is in it: who connected an account (a route's `by`) stays here, and that
 *  list shows a Google mailbox by its domain alone. */
async function status(request: Request, name: string, env: Env): Promise<Response> {
  const received = await bodyWithin(request, 4096);
  if (!received) return refuse(413, "request too large");
  const asker = await askedBy(request, received.text, ASK_REQUESTED, name, env);
  if (asker instanceof Response) return asker;
  // what the body claims before any check: untrusted JSON
  let asked: { cursor?: unknown };
  try {
    asked = JSON.parse(received.text || "{}");
  } catch {
    return refuse(400, "a status ask is JSON: {} or { cursor }");
  }
  const every = isCloudsOwnMind(asker, env);
  const cursor = every && typeof asked.cursor === "string" ? asked.cursor : "";
  const { rows, next, partial } = await routesOf(env).statusRows(
    every ? null : asker.mind,
    cursor,
    STATUS_PAGE,
  );
  const { clients } = await cloudOf(env);
  const minds = await Promise.all(
    rows.map(async (row) => ({
      ...row,
      // EVERY DEPLOYMENT'S LIST shows a Google account, a person's mailbox address, by its domain
      // alone; a deployment's own row shows its own
      accounts: every
        ? row.accounts.map((each) =>
            clients[each.client]?.kind === "google"
              ? { ...each, account: `*@${each.account.split("@").at(-1)}` }
              : each,
          )
        : row.accounts,
      ...(await env.OUTBOX.get(env.OUTBOX.idFromName(row.mind)).status()),
    })),
  );
  return json(200, { minds: minds satisfies StatusRow[], cursor: next, partial });
}

/** A DEPLOYMENT'S WORD THAT IT READS THE MIND FORM (core/configs/default `sayMindForm`):
 *  `{ reads: true }` or `{ reads: false }`. The word changes no form: every other deployment
 *  gets the mind form alone (`statementFor`). It is answered, so that a mind that says it at its
 *  start meets no error. */
async function mindFormWord(request: Request, name: string, env: Env): Promise<Response> {
  const received = await bodyWithin(request, 4096);
  if (!received) return refuse(413, "request too large");
  const body = received.text;
  const asker = await askedBy(request, body, ASK_REQUESTED, name, env);
  if (asker instanceof Response) return asker;
  // what the body claims before any check: untrusted JSON
  let asked: { reads?: unknown };
  try {
    asked = JSON.parse(body);
  } catch {
    return refuse(400, "a mind-form word is JSON");
  }
  if (typeof asked.reads !== "boolean")
    return refuse(400, "a mind-form word is { reads: true } or { reads: false }");
  return json(200, { ok: true, reads: asked.reads });
}

/** A DEPLOYMENT'S ANSWER to a message the bot relayed, sent as the bot. A direct message goes only
 *  to an X account this deployment linked. A post goes only under a mention the Cloud delivered to
 *  this deployment, once, and only when that mention is the person's own post, not their reply in
 *  someone else's conversation: the bot says nothing a deployment merely asks it to say to
 *  strangers, and nothing twice in public. */
async function reply(request: Request, name: string, env: Env): Promise<Response> {
  const body = await request.text();
  const asker = await askedBy(request, body, ASK_REQUESTED, name, env);
  if (asker instanceof Response) return asker;
  // what the body claims before any check: untrusted JSON
  let answer: { kind?: unknown; to?: unknown; inReplyTo?: unknown; text?: unknown };
  try {
    answer = JSON.parse(body);
  } catch {
    return refuse(400, "a reply is JSON");
  }
  const bot = env.BOT.get(env.BOT.idFromName(name));
  const text = typeof answer.text === "string" ? answer.text : "";
  const to =
    answer.kind === "dm"
      ? String(answer.to || "")
      : answer.kind === "mention"
        ? await bot.mentionedBy(String(answer.inReplyTo || ""))
        : null;
  if (!to || !text || text.length > (answer.kind === "dm" ? 10_000 : 280))
    return refuse(
      400,
      'a reply is { kind: "dm", to, text } or { kind: "mention", inReplyTo, text }',
    );
  // WHAT THE BOT SAYS IN PUBLIC IS UNDER iterate'S NAME: it names nobody and links nowhere, so a
  // deployment cannot use it to reach or mislead a third person
  if (answer.kind === "mention" && /@|https?:|www\.|\w\.\w{2,}\//i.test(text))
    return refuse(400, "a public reply names no account and carries no link");
  const routes = env.ROUTES.get(env.ROUTES.idFromName("routes"));
  if (!(await routes.mindsOf(name, to)).includes(asker.mind))
    return refuse(403, `${asker.mind} has not linked the X account this reply is for`);
  try {
    return json(
      200,
      await bot.send(
        name,
        answer.kind === "dm"
          ? { kind: "dm", to, text }
          : { kind: "mention", inReplyTo: String(answer.inReplyTo), text },
      ),
    );
  } catch (error) {
    return refuse(502, error instanceof Error ? error.message : String(error));
  }
}

// ── Gmail's push ─────────────────────────────────────────────────────────────────────────────────

/** GMAIL'S PUSH. A deployment asks Gmail to watch a mailbox it connected (`users.watch`, with the
 *  person's token, which the Cloud never has) and names this client's topic. Gmail publishes each
 *  change of the mailbox there, and the topic's one push subscription delivers it to this address.
 *  A mailbox has one watch per Google project, so the deployments that connected one mailbox
 *  share it: none of them stops it, and it ends by itself a week after its last renewal.
 *
 *  ANYBODY CAN MAKE A PUSH SUBSCRIPTION TO THIS ADDRESS in a Google project of their own. So a
 *  push counts only with the token Pub/Sub signs for the Cloud's own subscription: Google's
 *  signature, this address as its audience, and the subscription's service account as its verified
 *  address. The token says that the push is the subscription's, and not that Gmail published
 *  it: that rests on the topic, where Gmail's own account is the only publisher (README.md). A push says that the mailbox changed and up to which history id, and nothing of the
 *  mail: it becomes `google/gmail-push-received` on `/integrations/<name>/<address>` for each
 *  deployment that connected the mailbox, kept and relayed as a webhook is (`webhook`), and the
 *  deployment reads the change with its own grant. Pub/Sub sends again whatever is not answered
 *  2xx, so its own push that is no Gmail notification is answered 200 and dropped. */
async function gmailPushed(
  request: Request,
  name: string,
  client: Client,
  cloud: Cloud,
  env: Env,
): Promise<Response> {
  const push = gmailPushOf(client);
  if (!push) return refuse(404, `${name} sends nothing here`);
  // Where Google publishes the keys that sign such a token. The key set is kept with the Cloud's
  // own things, which last as long as the isolate (`cloudOf`), so a push reads the keys only when
  // jose's copy of them is old (ten minutes) or the token names a key that the copy lacks.
  const certs = push.certs || "https://www.googleapis.com/oauth2/v3/certs";
  if (!cloud.certs.has(certs)) cloud.certs.set(certs, createRemoteJWKSet(new URL(certs)));
  const token = /^Bearer (\S+)$/.exec(request.headers.get("authorization") || "")?.[1] || "";
  const claims = await jwtVerify(token, cloud.certs.get(certs)!, {
    issuer: push.issuer || GOOGLE_ISSUERS,
    audience: push.audience,
    algorithms: ["RS256"],
  }).then(
    ({ payload }) => payload,
    () => null,
  );
  if (claims?.email !== push.serviceAccount || claims.email_verified !== true)
    return refuse(401, "the token is not the push subscription's");
  const body = await bodyWithin(request, WEBHOOK_BODY_MAX_BYTES);
  if (!body) return refuse(413, "Payload too large");
  // Pub/Sub's envelope: `{ message: { data, messageId, publishTime } }`, where `data` is base64
  // of Gmail's `{ emailAddress, historyId }`. Google's page shows the history id as a string; a
  // number is read the same.
  let message: { data?: unknown; messageId?: unknown; publishTime?: unknown } | undefined;
  let notified: { emailAddress?: unknown; historyId?: unknown } | null = null;
  try {
    ({ message } = JSON.parse(body.text));
    notified = JSON.parse(Buffer.from(String(message?.data || ""), "base64").toString());
  } catch {
    // neither: it is about no mailbox
  }
  const account = addressOf(notified?.emailAddress);
  const id = typeof message?.messageId === "string" ? message.messageId : "";
  const historyId = String(notified?.historyId || "");
  if (!account || !id || !/^\d+$/.test(historyId)) return json(200, { accepted: false });
  const first = await env.OUTBOX.get(env.OUTBOX.idFromName(`inbox\n${name}`)).take({
    client: name,
    account,
    id,
    type: "events.iterate.com/google/gmail-push-received",
    payload: {
      emailAddress: account,
      historyId,
      messageId: id,
      publishTime: typeof message?.publishTime === "string" ? message.publishTime : null,
    },
  });
  return json(200, first ? { accepted: true } : { accepted: true, redelivery: true });
}

/** THE DEPLOYMENT IS TOLD WHICH MAILBOX IT CONNECTED, and how to watch it: one statement of the
 *  Cloud's mind (`statementFor`), `google/gmail-connected` on `/integrations/<name>/<address>`, for that
 *  deployment alone. A mind's code cannot read the Cloud's facts, and the watch is its own call
 *  (`gmailPushed`), so the event carries what the call needs: the topic to name, and the origin
 *  of Gmail's API as this client has it (Google's, or a fake's on dev). Every connect tells,
 *  since the person may have connected the mailbox into another secret. A refresh tells when the
 *  deployment was not told yet (`toldOnce`): a grant connected before the Cloud routed mailboxes,
 *  or before this client took a push, and a word that never arrived. A client that takes no push
 *  has no topic, and tells nothing. */
async function gmailConnected(
  to: Connected,
  address: string,
  connect: boolean,
  env: Env,
): Promise<void> {
  const push = gmailPushOf(to.client);
  if (!push) return;
  await toldOnce(to.mind, connect, env, {
    path: `/integrations/${to.name}/${address}`,
    type: "events.iterate.com/google/gmail-connected",
    payload: { emailAddress: address, topic: push.topic, api: to.client.api },
  });
}

/** Which deployment connected an account through which client, and the Cloud's own origin. */
type Connected = { origin: string; name: string; client: Client; mind: string };
type Said = { path: string; type: string; payload: unknown };

/** One statement for one deployment alone, put into its outbox, which signs it when it sends it
 *  (`statementFor`): what the Cloud says to the deployment that asked, and to no other that
 *  connected the account. */
async function tell(mind: string, env: Env, said: Said): Promise<void> {
  await env.OUTBOX.get(env.OUTBOX.idFromName(mind)).put(mind, { ...said, at: Date.now() });
}

/** How long the Cloud waits for its mind to sign one statement. */
const MIND_SIGN_MS = 3_000;

/** A STATEMENT FOR ONE DEPLOYMENT (README "The Cloud signs as its own mind"), said at `at` and
 *  lasting until a day after it. ONE LANDING PLACE: for every other deployment it is the MIND
 *  FORM alone. The Cloud's mind signs it (`MIND_AUTH`), on `/minds/<its id><path>`, and `about`
 *  names the delivery, so that the deployment stores it once however often it comes. It throws
 *  when the Cloud's mind does not sign in three seconds: the statement then waits in the
 *  deployment's outbox, and is never sent in another form.
 *
 *  THE KEY FORM stays for the Cloud's OWN mind, iterate.com (`MIND_HOSTNAME`): no mind signs for
 *  itself (core/auth-worker `signedByStack`), and iterate.com's own accounts carry its GitHub
 *  mirror, which reads them on `/integrations/<name>/<account>`. A dev Cloud with no mind of its
 *  own (no `MIND_AUTH`) has the key form alone. The Cloud's own key signs it, on `path`. */
async function statementFor(
  env: Env,
  signer: Cloud["signer"],
  mind: string,
  said: Said & { at: number; about?: string[] },
): Promise<Signed> {
  const { at, about, ...fields } = said;
  const expires = at + HELD_MS;
  const auth = env.MIND_AUTH;
  if (!auth || !env.MIND_HOSTNAME || mind === env.MIND_HOSTNAME) return keyForm(signer, mind, said);
  let timer: ReturnType<typeof setTimeout> | undefined;
  try {
    return await Promise.race([
      auth.sign({
        mind,
        // the auth Worker writes `/minds/<its mind>` before it (core/auth-worker `Deliveries.sign`)
        path: fields.path,
        type: fields.type,
        // `Said.payload` is unknown only because providers' bodies pass through: every statement
        // the Cloud makes carries an object there (a delivery's fields, a word's fields)
        payload: fields.payload as Record<string, unknown>,
        about,
        // whole seconds, a day at most: it ends when the statement's day ends
        expiresInSeconds: Math.min(
          Math.max(Math.floor((expires - Date.now()) / 1000), 1),
          HELD_MS / 1000,
        ),
      }),
      new Promise<never>((_, reject) => {
        timer = setTimeout(
          () => reject(new Error("the mind did not sign in three seconds")),
          MIND_SIGN_MS,
        );
      }),
    ]);
  } finally {
    // a signature in time ends the wait: no timer is left to fire
    clearTimeout(timer);
  }
}

/** The key form of what is said for `mind`: the Cloud's own key signs it, on `path`, for a day
 *  from `at`. It carries no `about`. */
function keyForm(
  signer: Cloud["signer"],
  mind: string,
  { at, about: _about, ...fields }: Said & { at: number; about?: string[] },
): Promise<Signed> {
  return signer.sign({ mind, ...fields, at, expires: at + HELD_MS });
}

/** A held statement's fields as the key form says them: a mind-form statement's path without
 *  the `/minds/<its signer>` before it. `from` is set on a mind-form statement alone. */
function keyFormOf(signed: Signed): Said & { at: number; expires: number; from?: string } {
  // the Cloud's own text: its key or its mind signed exactly these fields, and nobody else
  // writes to the outbox's storage
  const statement = JSON.parse(signed.statement) as Said & {
    at: number;
    expires: number;
    from?: string;
  };
  const before = statement.from ? `/minds/${statement.from}` : "";
  return {
    ...statement,
    path:
      before && statement.path.startsWith(before)
        ? statement.path.slice(before.length)
        : statement.path,
  };
}

/** What a held row says, as `statementFor` takes it: its statement's fields, and the `about`
 *  held beside a key-form statement. */
function saidOf(held: Extract<Held, { mind: string }>): Said & { at: number; about?: string[] } {
  const { path, type, payload, at } = keyFormOf(held.signed);
  return { path, type, payload, at, about: held.about };
}

/** WHAT A HELD ROW SAYS WHEN ITS `signed` IS NO SIGNED STATEMENT, or null when it says nothing
 *  that can be read. Nothing here writes such a row. A deploy can: for some seconds two releases
 *  run side by side, and an inbox of the new one may call `put` on an Outbox that still runs the
 *  release before. When the two differ in what `put` takes, that Outbox keeps what it was given
 *  as the row's `signed`. The one known case is `put(mind, said)` taken as `put(mind, signed)`:
 *  the row then holds `said` whole, with its time and its `about`, and is signed here late
 *  (`Outbox.alarm`). At the head of a queue such a row would throw in every alarm. */
function saidUnsigned(
  held: Extract<Held, { mind: string }>,
): { said: (Said & { at: number; about?: string[] }) | null } | null {
  try {
    keyFormOf(held.signed);
    return null;
  } catch {
    // `|| {}`: a row may have no `signed` at all
    const { path, type, payload, at, about } = (held.signed || {}) as unknown as Partial<
      Said & { at: number; about: string[] }
    >;
    return path && type && at ? { said: { path, type, payload, at, about } } : { said: null };
  }
}

/** The row that says a deployment was told `type` on `path`. */
const toldRow = (mind: string, { type, path }: Pick<Said, "type" | "path">) =>
  `told\n${type}\n${mind}\n${path}`;

/** WHAT A DEPLOYMENT IS TOLD ONCE, and again only when it did not hear it: at a connect always
 *  (`again`), at a refresh when no row says it was told. The row is kept after the statement is
 *  in the deployment's outbox, so a word that could not be put there is told at the next
 *  refresh. A statement that waited its day in the outbox and was never taken takes the row with
 *  it (`Outbox.alarm`), so that one is told again too. */
async function toldOnce(mind: string, again: boolean, env: Env, said: Said): Promise<void> {
  const row = toldRow(mind, said);
  if (!again && (await routesOf(env).kept(row))) return;
  await tell(mind, env, said);
  await routesOf(env).keep(row, TOLD_MS, "1");
}

// ── Calendar's push ──────────────────────────────────────────────────────────────────────────────

/** A CALENDAR'S CHANNEL TOKEN. Google Calendar pushes a change to an HTTPS address that the
 *  watcher names (`events.watch`), with headers alone: no body, and NO SIGNATURE. The one thing a
 *  watcher can put on its channel is a token, which Google sends back with each push. So that
 *  token is the push's proof and its route. The Cloud makes it: `<id>.<HMAC of the id under the
 *  Cloud's key>`, where the id is random and a row says whose it is (`Routes.calendarChannel`).
 *  The deployment makes its channels with it (the watch is its own call, with the person's token,
 *  which the Cloud never has).
 *
 *  A NEW CONNECT MAKES A NEW TOKEN. The token lies in the clear on the deployment's log and in
 *  each channel at Google, so one that got out must end: the one before is good for a day more,
 *  for the channels that still carry it. A refresh keeps the token. The rows are kept at each
 *  connect and each refresh of a grant that reaches the calendar: one whose scope has a calendar
 *  scope, and for which Google names the primary calendar, whose id is the account's address.
 *  They last `CALENDAR_TOKEN_MS` after the last of them, and go at once when the Cloud lets go of
 *  the account for that deployment (`Routes.release`, `Routes.letGo`). A connect tells the
 *  deployment the token and where its channels deliver (`google/calendar-connected` on
 *  `/integrations/<name>/<address>`); a refresh tells when it made the token, or when the
 *  deployment was not told (`toldOnce`). Answers the calendar's address, or "". */
async function calendarConnected(
  to: Connected,
  tokens: Record<string, unknown>,
  connect: boolean,
  cloud: Cloud,
  env: Env,
): Promise<string> {
  const scopes = typeof tokens.scope === "string" ? tokens.scope.split(/\s+/) : [];
  if (!scopes.some((scope) => /^https:\/\/www\.googleapis\.com\/auth\/calendar(\.|$)/.test(scope)))
    return "";
  const primary = await fetch(`${to.client.api}/calendar/v3/calendars/primary`, {
    headers: { authorization: `Bearer ${String(tokens.access_token)}`, accept: "application/json" },
  }).then(
    (answer): Promise<{ id?: unknown } | null> =>
      answer.ok ? answer.json() : Promise.resolve(null),
    () => null,
  );
  const account = addressOf(primary?.id);
  if (!account) return "";
  const channel = await routesOf(env).calendarChannel(to.name, to.mind, account, connect);
  if (!channel) return "";
  await toldOnce(to.mind, connect || channel.made, env, {
    path: `/integrations/${to.name}/${account}`,
    type: "events.iterate.com/google/calendar-connected",
    payload: {
      emailAddress: account,
      api: to.client.api,
      address: `${to.origin}/clients/${to.name}/calendar-webhook`,
      token: `${channel.id}.${base64url(await crypto.subtle.sign("HMAC", cloud.proofKey, calendarTokenInput(to.name, channel.id)))}`,
    },
  });
  return account;
}

/** What the second half of a channel token signs: the client and the token's id. Its first line
 *  keeps it apart from every other text the same key signs (`proofInput`). */
const calendarTokenInput = (name: string, id: string) =>
  encoder.encode(`calendar-channel\n${name}\n${id}`);

/** CALENDAR'S PUSH on a channel. Its token says whose channel it is (`calendarConnected`). A
 *  token the Cloud did not make is refused here, before any row is read; one whose row is gone
 *  (replaced a day ago, lapsed, or let go) reaches nobody. A push says that the calendar changed
 *  and nothing of what: it becomes `google/calendar-push-received` on
 *  `/integrations/<name>/<address>` for the one deployment the token is for, and that deployment
 *  reads the change with its own grant. A message of a channel that comes again is relayed once:
 *  a channel is known by its token, its id and its expiration, so a channel id must be new, as
 *  Google asks. */
async function calendarPushed(
  request: Request,
  name: string,
  cloud: Cloud,
  env: Env,
): Promise<Response> {
  const header = (named: string, most: number) =>
    (request.headers.get(named)?.trim() || "").slice(0, most);
  const nobodys = () => refuse(404, "no deployment has this channel");
  // the whole header: a token with anything after it is not the Cloud's
  const [, id = "", mac = ""] =
    /^([\w-]{22})\.([\w-]{43})$/.exec(request.headers.get("x-goog-channel-token") || "") || [];
  const made =
    !!id &&
    (await crypto.subtle.verify(
      "HMAC",
      cloud.proofKey,
      Buffer.from(mac, "base64url"),
      calendarTokenInput(name, id),
    ));
  if (!made) return nobodys();
  const [mind, account] = ((await routesOf(env).kept(`calendar\n${name}\n${id}`)) || "").split(
    "\n",
  );
  if (!mind || !account) return nobodys();
  const channelId = header("x-goog-channel-id", 64);
  const messageNumber = header("x-goog-message-number", 20);
  if (!channelId || !/^\d+$/.test(messageNumber))
    return refuse(400, "a push names its channel and its number");
  const channel = `${id}\n${channelId}\n${header("x-goog-channel-expiration", 64)}`;
  const seen = `delivery\n${name}\n${channel}\n${messageNumber}`;
  if (await routesOf(env).once(seen, HELD_MS, "1"))
    return json(200, { accepted: true, redelivery: true });
  try {
    await tell(mind, env, {
      path: `/integrations/${name}/${account}`,
      type: "events.iterate.com/google/calendar-push-received",
      payload: {
        channelId,
        resourceId: header("x-goog-resource-id", 256),
        resourceState: header("x-goog-resource-state", 32),
        messageNumber,
      },
    });
  } catch (error) {
    // not told: the push is not seen, and Google tries it again after a 5xx
    await routesOf(env).forget(seen);
    console.warn({ event: "cloud.calendar-push-not-told", mind, error: String(error) });
    return refuse(503, "the deployment's outbox did not take the push: try again");
  }
  return json(200, { accepted: true });
}

// ── webhooks ─────────────────────────────────────────────────────────────────────────────────────

/** What one delivery is, once its provider's signature held. */
type Delivery = {
  /** What the provider hears in place of the usual answer: Slack's check of a new address. */
  answer?: Response;
  /** The provider's account the delivery is about: a GitHub installation, a Slack workspace. */
  account: string;
  /** The provider's own id of the delivery: one that comes again is relayed once. */
  id: string;
  type: string;
  payload: unknown;
  /** The delivery says the app was removed from the account: its deployments hear it, then
   *  nothing more. */
  ended?: boolean;
  /** GitHub alone: the person who withdrew the app's access, whose claims end. */
  withdrawnBy?: string;
};

/** THE APP'S WEBHOOK ADDRESSES: GitHub's one, and Slack's two (events and interactivity). A
 *  delivery the provider signed becomes, for each deployment that connected the account it is
 *  about, one statement of the Cloud's mind (`statementFor`): `<provider>/webhook-received` on the
 *  deployment's `/integrations/<name>/<account>`, with the payload os.iterate.com has always
 *  written for it, so what reads that event reads this one (the GitHub sync of a config repo). It
 *  waits in that deployment's outbox. The provider hears 200 as soon as the delivery is kept in
 *  the client's inbox, whatever a deployment or another object of the Cloud does: one slow
 *  deployment must not fail the app for all. A delivery about an account nobody connected is
 *  nobody's here.
 *
 *  Every delivery is also sent on, with its bytes and its provider's headers as they came, to the
 *  platform the app served before (`passOn`), whether or not a deployment here gets it. */
async function webhook(
  request: Request,
  name: string,
  route: "webhook" | "interactivity-webhook",
  client: Client,
  cloud: Cloud,
  env: Env,
): Promise<Response> {
  const { webhookSecret } = cloud.secrets[name]!;
  const here =
    client.kind === "slack" || (client.kind === "github" && route === "webhook") ? client.kind : "";
  if (!here || !webhookSecret) return refuse(404, `${name} sends nothing here`);
  const body = await bodyWithin(request, WEBHOOK_BODY_MAX_BYTES);
  if (!body) return refuse(413, "Payload too large");
  const header = (named: string) => request.headers.get(named)?.trim() || "";
  // GitHub signs the body; Slack signs `v0:<timestamp>:<body>`, and its timestamp must be fresh
  const timestamp = header("x-slack-request-timestamp");
  const signature =
    here === "github"
      ? /^sha256=([0-9a-f]{64})$/i.exec(header("x-hub-signature-256"))?.[1]
      : /^\d{1,12}$/.test(timestamp) && Math.abs(Date.now() / 1000 - Number(timestamp)) <= 300
        ? /^v0=([0-9a-f]{64})$/i.exec(header("x-slack-signature"))?.[1]
        : undefined;
  const key = await crypto.subtle.importKey(
    "raw",
    encoder.encode(webhookSecret),
    { name: "HMAC", hash: "SHA-256" },
    false,
    ["verify"],
  );
  const signed =
    here === "github"
      ? body.bytes
      : Buffer.concat([encoder.encode(`v0:${timestamp}:`), body.bytes]);
  const signedByProvider =
    !!signature && (await crypto.subtle.verify("HMAC", key, Buffer.from(signature, "hex"), signed));
  if (!signedByProvider) return refuse(401, "the signature is wrong");

  const delivery =
    here === "github"
      ? githubDelivery(body.text, header("x-github-delivery"), header("x-github-event"))
      : slackDelivery(body.text, route === "interactivity-webhook", timestamp);
  if (delivery.answer) return delivery.answer;
  // KEPT FIRST, ANSWERED AT ONCE: one write to this client's inbox, and the provider hears 200. The
  // inbox relays it after (`Outbox.alarm`): to the platform the app served before, unchanged, and
  // to each deployment that connected the account. So the provider's answer waits for no other
  // object, and what it sent survives one that fails for a while.
  const there = client.passOn?.[route];
  const { answer: _answered, ...relay } = delivery;
  const first = await env.OUTBOX.get(env.OUTBOX.idFromName(`inbox\n${name}`)).take(
    { client: name, ...relay },
    there
      ? {
          url: there,
          headers: [...request.headers].filter(([each]) =>
            /^(x-github-|x-hub-signature|x-slack-|content-type$|user-agent$)/.test(each),
          ),
          body: body.bytes,
        }
      : undefined,
  );
  return json(200, first ? { accepted: true } : { accepted: true, redelivery: true });
}

/** A GitHub App's delivery: about an installation, named by GitHub's delivery id. The payload is
 *  the one core/os writes for iterate's App, `{ delivery: { id, name }, installationId, body }`. */
function githubDelivery(text: string, id: string, event: string): Delivery {
  let body: {
    action?: unknown;
    installation?: { id?: unknown };
    sender?: { id?: unknown };
  } | null = null;
  try {
    body = JSON.parse(text);
  } catch {
    // not JSON: it is about no installation
  }
  const installationId = String(body?.installation?.id || "");
  return {
    account: installationId,
    id,
    type: "events.iterate.com/github/webhook-received",
    payload: { delivery: { id, name: event }, installationId, body },
    ended: event === "installation" && body?.action === "deleted",
    withdrawnBy:
      event === "github_app_authorization" && body?.sender?.id ? String(body.sender.id) : "",
  };
}

/** Slack's delivery: the Events API's JSON, or interactivity's `payload=<json>` form field, about
 *  a workspace (`slackWorkspaceOf`), named by its event or trigger id. The payload is the one
 *  core/os writes: `{ body, teamId, slackRequestTimestamp }`. Slack checks a new address with
 *  `url_verification`, which is answered and goes nowhere. */
function slackDelivery(text: string, interactivity: boolean, timestamp: string): Delivery {
  let body: SlackBody | null = null;
  try {
    body = JSON.parse((interactivity ? new URLSearchParams(text).get("payload") : text) || "");
  } catch {
    // neither: it is about no workspace
  }
  const teamId = slackWorkspaceOf(body);
  return {
    answer:
      body?.type === "url_verification" ? json(200, { challenge: body.challenge }) : undefined,
    account: teamId,
    id: String(body?.event_id || body?.trigger_id || ""),
    type: "events.iterate.com/slack/webhook-received",
    payload: { body, teamId, slackRequestTimestamp: timestamp },
    ended: body?.event?.type === "app_uninstalled",
  };
}

type SlackBody = {
  type?: unknown;
  challenge?: unknown;
  team_id?: unknown;
  team?: { id?: unknown };
  authorizations?: { team_id?: unknown }[];
  view?: { app_installed_team_id?: unknown };
  event?: { team?: unknown; type?: unknown };
  event_id?: unknown;
  trigger_id?: unknown;
};

/** THE WORKSPACE A DELIVERY IS FOR: the one the app is installed in. In a Slack Connect channel
 *  that is not always the workspace of the person who acted, and Slack names it apart where the
 *  two can differ: a modal's `view.app_installed_team_id`, and an event's
 *  `authorizations[0].team_id` (the installation the event is sent for; Slack lists one). Else
 *  `team.id`, `team_id`, or `event.team`. The order is that of Slack's own Bolt
 *  (slack_bolt/request/internals.py `extract_team_id`). Without it, what a person of another
 *  workspace does in a shared channel would go to the deployment that connected their workspace.
 *  A button press (`block_actions`) names the installation in `team.id` and the person's own
 *  workspace in `user.team_id`. An app installed for a whole organization gets `team: null` in a
 *  press: that names no workspace here, and the press reaches no deployment. */
function slackWorkspaceOf(body: SlackBody | null): string {
  return String(
    body?.view?.app_installed_team_id ||
      body?.team?.id ||
      body?.authorizations?.[0]?.team_id ||
      body?.team_id ||
      body?.event?.team ||
      "",
  );
}

// ── what the Cloud keeps ─────────────────────────────────────────────────────────────────────────

const routesOf = (env: Env) => env.ROUTES.get(env.ROUTES.idFromName("routes"));

/** How many deployments may connect one provider account: more is no household and no team, and
 *  every event of the account is signed and held once for each. */
const DEPLOYMENTS_PER_ACCOUNT = 20;

/** WHICH DEPLOYMENTS CONNECTED WHICH PROVIDER ACCOUNT, and a short memory of what came once. A
 *  row is one client, account and deployment, and names the person at the provider who claimed
 *  it: it lasts while that person's grant refreshes and they still administer the account. No row
 *  holds a token or a secret that the Cloud can read. One kind holds a person's token pair that
 *  the Cloud cannot read: a refresh's kept answer (`once answer <digest>`), for a day as a rule
 *  and two at most, sealed under the refresh token it spent, which the Cloud keeps nowhere.
 *
 *    route    <client> <account> <mind>          → the person
 *    claim    <client> <person> <mind> <account>   the same rows, by who claimed them
 *    refused  <client> <person> <mind>           → when the provider first refused their refresh
 *    once     <key>                                → { value, until } */
export class Routes extends DurableObject<Env> {
  /** What `by` administers now is what `mind` is connected to through them: `accounts`, and no
   *  other account this person claimed for it before. */
  async claim(client: string, by: string, accounts: string[], mind: string): Promise<void> {
    const mine = `claim\n${client}\n${by}\n${mind}\n`;
    for (const key of (await this.ctx.storage.list({ prefix: mine })).keys()) {
      const account = key.slice(mine.length);
      if (!accounts.includes(account)) await this.#unclaim(client, by, mind, account);
    }
    for (const account of accounts) {
      // the deployment let go of this one (`letGo`): its person's consent does not bring it back
      if (await this.ctx.storage.get(`left\n${client}\n${mind}\n${account}`)) continue;
      const others = (await this.mindsOf(client, account)).filter((each) => each !== mind);
      if (others.length >= DEPLOYMENTS_PER_ACCOUNT) continue;
      await this.ctx.storage.put({
        [`route\n${client}\n${account}\n${mind}`]: by,
        [`${mine}${account}`]: Date.now(),
      });
    }
  }

  /** A CALENDAR'S CHANNEL ROWS for `mind` (worker.ts `calendarConnected`): the id of its channel
   *  token, and whose that id is. A `connect` makes a new id, and the one before it is good for a
   *  day more; else the id that is there is kept, or one is made when there is none. Both rows
   *  last `CALENDAR_TOKEN_MS` from now. Answers the id, and whether it was made now.
   *
   *    once calendar-of <client> <mind> <account>   → the id
   *    once calendar <client> <id>                  → <mind> <account> */
  async calendarChannel(
    client: string,
    mind: string,
    account: string,
    connect: boolean,
  ): Promise<{ id: string; made: boolean } | null> {
    // the deployment let go of the account (`letGo`): no grant of it makes a token, until it
    // says it wants the account again
    if (await this.ctx.storage.get(`left\n${client}\n${mind}\n${account}`)) return null;
    const of = `calendar-of\n${client}\n${mind}\n${account}`;
    const before = await this.kept(of);
    const made = connect || !before;
    const id = made ? base64url(crypto.getRandomValues(new Uint8Array(16))) : before!;
    const whose = `${mind}\n${account}`;
    await this.keep(of, CALENDAR_TOKEN_MS, id);
    await this.keep(`calendar\n${client}\n${id}`, CALENDAR_TOKEN_MS, whose);
    if (before && made) {
      await this.keep(`calendar\n${client}\n${before}`, HELD_MS, whose);
      // so that a let-go ends the one before too
      await this.keep(`calendar-was\n${client}\n${mind}\n${account}`, HELD_MS, before);
    }
    return { id, made };
  }

  /** The Cloud lets go of `account` for `mind`: its calendar's channel token reaches nobody from
   *  now, and a later connect makes a new one. */
  async #calendarOver(client: string, mind: string, account: string): Promise<void> {
    for (const row of [`calendar-of`, `calendar-was`].map(
      (kind) => `${kind}\n${client}\n${mind}\n${account}`,
    )) {
      const id = await this.kept(row);
      if (id) await this.ctx.storage.delete([`once\n${row}`, `once\ncalendar\n${client}\n${id}`]);
    }
  }

  /** `by` no longer holds `account` for `mind`. The route stays while another person holds it too
   *  (two admins of one organization each connected it), in that person's name; else it goes. */
  async #unclaim(client: string, by: string, mind: string, account: string): Promise<void> {
    await this.ctx.storage.delete(`claim\n${client}\n${by}\n${mind}\n${account}`);
    const route = `route\n${client}\n${account}\n${mind}`;
    const claims = await this.ctx.storage.list({ prefix: `claim\n${client}\n` });
    const other = [...claims.keys()]
      .map((key) => key.split("\n"))
      .find(([, , , claimedFor, claimed]) => claimedFor === mind && claimed === account);
    // the deployment's own "let go" (`letGo`) outranks anybody's hold
    const left = await this.ctx.storage.get(`left\n${client}\n${mind}\n${account}`);
    if (other && !left) await this.ctx.storage.put(route, other[2]);
    else await this.ctx.storage.delete(route);
  }

  /** A deployment's own word on one account (worker.ts `letGo`): its row goes, and stays gone
   *  through every later claim, until the deployment says `again`. */
  async letGo(client: string, mind: string, account: string, again: boolean): Promise<void> {
    const left = `left\n${client}\n${mind}\n${account}`;
    if (again) {
      await this.ctx.storage.delete(left);
      return;
    }
    const route = `route\n${client}\n${account}\n${mind}`;
    const person = await this.ctx.storage.get<string>(route);
    await this.ctx.storage.delete([route, `claim\n${client}\n${person}\n${mind}\n${account}`]);
    await this.ctx.storage.put(left, Date.now());
    await this.#calendarOver(client, mind, account);
  }

  /** The deployments connected to `account`. With `freshMs`: only those whose person made the
   *  claim, or made it again by a refresh, within that time (worker.ts `claimAgeOf`). A route
   *  names the person who claimed it last, so theirs is the newest claim of it. */
  async mindsOf(client: string, account: string, freshMs = 0): Promise<string[]> {
    const prefix = `route\n${client}\n${account}\n`;
    const minds: string[] = [];
    for (const [row, by] of await this.ctx.storage.list<string>({ prefix })) {
      const mind = row.slice(prefix.length);
      const at = freshMs
        ? await this.ctx.storage.get<number>(`claim\n${client}\n${by}\n${mind}\n${account}`)
        : 0;
      if (!freshMs || (typeof at === "number" && Date.now() - at < freshMs)) minds.push(mind);
    }
    return minds;
  }

  /** EACH DEPLOYMENT'S ACCOUNTS (worker.ts `status`): its routes, with when its person last
   *  claimed each, and what it let go of, by hostname. For `only`, its row alone, whether or not
   *  it holds one here; else the deployments after `cursor` in order, `limit` of them, and the
   *  hostname to go on from (`cursor`), or null when none is left. No person's id is answered. */
  /** Drops every row of the deployment `mind` (worker.ts `forget`): its routes and claims, the
   *  accounts it let go, its refusals, and its calendar channels. Answers how many rows went. */
  async forgetMind(mind: string): Promise<number> {
    const at = { route: 3, claim: 3, left: 2, refused: 3 } as const;
    let rows = 0;
    for (const [kind, place] of Object.entries(at)) {
      const keys = [...(await this.ctx.storage.list({ prefix: `${kind}\n` })).keys()].filter(
        (key) => key.split("\n")[place] === mind,
      );
      for (const key of keys) {
        const [, client = "", , account = ""] = key.split("\n");
        if (kind === "route") await this.#calendarOver(client, mind, account);
      }
      for (let from = 0; from < keys.length; from += 128)
        await this.ctx.storage.delete(keys.slice(from, from + 128));
      rows += keys.length;
    }
    return rows;
  }

  async statusRows(
    only: string | null,
    cursor: string,
    limit: number,
  ): Promise<{
    rows: Omit<StatusRow, keyof OutboxStatus>[];
    next: string | null;
    partial: boolean;
  }> {
    const rows = new Map<string, Omit<StatusRow, keyof OutboxStatus>>();
    const rowOf = (mind: string) => {
      let row = rows.get(mind);
      if (!row) rows.set(mind, (row = { mind, accounts: [], letGo: [] }));
      return row;
    };
    if (only) rowOf(only);
    const bound = { limit: STATUS_ROWS_READ };
    const [routes, left] = await Promise.all([
      this.ctx.storage.list<string>({ prefix: "route\n", ...bound }),
      this.ctx.storage.list({ prefix: "left\n", ...bound }),
    ]);
    // every deployment's row reads each claim's time in one list; one deployment's, its own few
    const claims = only
      ? null
      : await this.ctx.storage.list<number>({ prefix: "claim\n", ...bound });
    for (const [key, by] of routes) {
      const [, client, account, mind] = key.split("\n");
      if (!client || !account || !mind || (only && mind !== only)) continue;
      const claim = `claim\n${client}\n${by}\n${mind}\n${account}`;
      const since = claims ? claims.get(claim) : await this.ctx.storage.get<number>(claim);
      rowOf(mind).accounts.push({ client, account, since: since || null });
    }
    for (const key of left.keys()) {
      const [, client, mind, account] = key.split("\n");
      if (!client || !account || !mind || (only && mind !== only)) continue;
      rowOf(mind).letGo.push({ client, account });
    }
    const after = [...rows.values()]
      .filter((row) => row.mind > cursor)
      .sort((a, b) => (a.mind < b.mind ? -1 : 1));
    const page = after.slice(0, limit);
    const partial = [routes, left, claims].some((read) => read?.size === STATUS_ROWS_READ);
    if (partial) console.warn({ event: "cloud.status-partial", read: STATUS_ROWS_READ });
    return { rows: page, next: after.length > limit ? page.at(-1)!.mind : null, partial };
  }

  /** Which clients deliver to `mind`, and for how many accounts at each: `{ github: 2 }`. A
   *  read for the Cloud's own page of a person's deployments (the installer's deployments.js),
   *  which asks only for a deployment the person's own Cloudflare account holds. */
  async clientsOf(mind: string): Promise<Record<string, number>> {
    const counts: Record<string, number> = {};
    for (const row of (await this.ctx.storage.list({ prefix: "route\n" })).keys()) {
      const [, client, , routed] = row.split("\n");
      if (client && routed === mind) counts[client] = (counts[client] || 0) + 1;
    }
    return counts;
  }

  /** Rows end. With `by`: what that person claimed, for `mind` alone when it is named (their
   *  grant no longer refreshes there), else everywhere (they withdrew the app's access). With
   *  `account` and no person: every deployment's row for it (the App was removed from it). */
  async release(client: string, by: string, mind = "", account = ""): Promise<void> {
    if (by) {
      const theirs = `${client}\n${by}\n${mind && `${mind}\n`}`;
      for (const key of (await this.ctx.storage.list({ prefix: `claim\n${theirs}` })).keys()) {
        const [, , , claimedFor, claimed] = key.split("\n");
        await this.#unclaim(client, by, claimedFor!, claimed!);
      }
      const refusals = await this.ctx.storage.list({ prefix: `refused\n${theirs}` });
      await this.ctx.storage.delete([...refusals.keys()]);
      // a Google person is an address, and their calendar's channel ends with their grant
      if (mind) await this.#calendarOver(client, mind, by);
      return;
    }
    const prefix = `route\n${client}\n${account}\n`;
    for (const [key, person] of await this.ctx.storage.list<string>({ prefix }))
      await this.ctx.storage.delete([
        key,
        `claim\n${client}\n${person}\n${key.slice(prefix.length)}\n${account}`,
      ]);
  }

  /** THE PROVIDER REFUSED A REFRESH of `by`'s grant for `mind`. The first refusal is remembered
   *  and ends nothing: the refresh token may have been spent for an answer that never arrived, and
   *  the deployment's next try may still bring that answer (worker.ts `token`). A refusal that
   *  comes an hour or more after the first ends what the person connected for that deployment. */
  async refused(client: string, by: string, mind: string): Promise<void> {
    const mark = `refused\n${client}\n${by}\n${mind}\n`;
    const first = await this.ctx.storage.get<number>(mark);
    if (first === undefined) await this.ctx.storage.put(mark, Date.now());
    else if (Date.now() - first >= REFUSAL_HOLD_MS) await this.release(client, by, mind);
  }

  /** A refresh of `by`'s grant for `mind` went through, or they connected it again: a refusal
   *  before it counts no more. */
  async refreshed(client: string, by: string, mind: string): Promise<void> {
    await this.ctx.storage.delete(`refused\n${client}\n${by}\n${mind}\n`);
  }

  /** The value kept under `key` (`keep`) while it lasts, or null. */
  async kept(key: string): Promise<string | null> {
    const kept = await this.ctx.storage.get<{ value: string; until: number }>(`once\n${key}`);
    return kept && kept.until > Date.now() ? kept.value : null;
  }

  async keep(key: string, ttlMs: number, value: string): Promise<void> {
    await this.ctx.storage.put(`once\n${key}`, { value, until: Date.now() + ttlMs });
    if (!(await this.ctx.storage.getAlarm())) await this.ctx.storage.setAlarm(Date.now() + HELD_MS);
  }

  async forget(key: string): Promise<void> {
    await this.ctx.storage.delete(`once\n${key}`);
  }

  /** WHAT CAME ONCE: the value first kept under `key`, while it lasts, or null when this is the
   *  first time, which keeps `value` for `ttlMs`. A code and the deployment it was sent to; a
   *  delivery already relayed. */
  async once(key: string, ttlMs: number, value: string): Promise<string | null> {
    const kept = await this.kept(key);
    if (kept) return kept;
    await this.keep(key, ttlMs, value);
    return null;
  }

  /** Once a day: what lasted its time goes. */
  override async alarm(): Promise<void> {
    const kept = await this.ctx.storage.list<{ until: number }>({ prefix: "once\n" });
    const over = [...kept].filter(([, { until }]) => until <= Date.now()).map(([key]) => key);
    for (let from = 0; from < over.length; from += 128)
      await this.ctx.storage.delete(over.slice(from, from + 128));
    if (kept.size > over.length) await this.ctx.storage.setAlarm(Date.now() + HELD_MS);
  }
}

/** A delivery as it is passed on: where to, its provider's headers, and its bytes as they came. */
type Passed = { url: string; headers: [string, string][]; body: Uint8Array };
/** A delivery the provider signed, as the inbox keeps it until it is relayed: `relayed` names the
 *  deployments whose outbox has it already, so a relay that failed half way goes on from there. */
type Relay = Omit<Delivery, "answer"> & {
  client: string;
  relayed?: string[];
  publicPost?: boolean;
};
/** `bytes`: about how large the row's content is, counted once when it is first held. */
type Held = { at: number; bytes?: number } &
  // `about`: the delivery's name for the mind form, which the key form does not carry
  (
    | { mind: string; signed: Signed; about?: string[] }
    | { passed: Passed }
    | { handOn: Passed; client: string }
    | { relay: Relay }
  );

/** WHAT AN OUTBOX'S THREE WRITERS TAKE (`put`, `pass`, `take`), CHECKED WHEN IT COMES. During a
 *  deploy two releases run side by side for some seconds, and an object of one may call an object
 *  of the other. A writer that keeps whatever it is given then writes a row that no release
 *  reads, and such a row at the head stops its queue. So a writer refuses what it does not read:
 *  the caller keeps its own copy and tries again, by then with the new release on both sides
 *  (`#drain`), and no row is written that no release reads. This release is the release before
 *  at the next deploy. */
function isSaid(value: unknown): value is Said & { at: number; about?: string[] } {
  const { path, type, at, about } = objectOf(value) || {};
  return (
    typeof path === "string" &&
    path !== "" &&
    typeof type === "string" &&
    type !== "" &&
    typeof at === "number" &&
    Number.isFinite(at) &&
    (about === undefined || (Array.isArray(about) && about.every((id) => typeof id === "string")))
  );
}
function isPassed(value: unknown): value is Passed {
  const { url, headers, body } = objectOf(value) || {};
  return typeof url === "string" && Array.isArray(headers) && body instanceof Uint8Array;
}
/** The fields by which an inbox routes a relay; the delivery's own payload is not looked at. */
function isRelay(value: unknown): value is Relay {
  const { client, account, id, type } = objectOf(value) || {};
  return (
    typeof client === "string" &&
    client !== "" &&
    typeof account === "string" &&
    typeof id === "string" &&
    typeof type === "string" &&
    type !== ""
  );
}

/** How a row of an inbox that did not go waits: how often it was tried, and when it is tried next. */
type Wait = { tries: number; until: number };
/** An inbox's mark that an account's relays wait aside (`Outbox.#handOver`): `stuck\n<account>`. */
const STUCK = "stuck\n";
/** Where an Outbox sets aside a statement's row that it cannot read (`Outbox.alarm`). */
const UNREAD = "unread:";
/** How long an inbox waits before it tries a row again: two seconds, doubled each time, five
 *  minutes at most. */
const inboxWaitMs = (tries: number) => Math.min(1_000 * 2 ** tries, 5 * 60_000);
/** How long an outbox waits before it tries its head again: ten seconds, doubled each time,
 *  fifteen minutes at most. */
const outboxWaitMs = (tries: number) => Math.min(5_000 * 2 ** tries, 15 * 60_000);

/** ONE DESTINATION'S OUTBOX: what waits for it, in the order it came, each sent until it is taken
 *  and deleted then. One per deployment holds signed statements for its `/statements`. One per
 *  client holds deliveries passed on to the platform the app served before. One more per client,
 *  its INBOX, holds what the provider just sent (`take`), until it is handed to those two kinds. A destination that
 *  does not answer is tried again, a little later each time, and what is a day old is dropped:
 *  the Cloud holds a customer's webhook no longer than that. The head blocks the rest, so order
 *  holds; an inbox is several queues, so that one destination's head blocks its own rows alone
 *  (`#handOver`). */
export class Outbox extends DurableObject<Env> {
  /** What is said for `mind`, HELD IN THE KEY FORM (`{ mind, signed }`), with `about` beside it.
   *  The Cloud's own key signs it here, with no call out, so a put fails for no one deployment.
   *  The row is signed again in the mind form when it is sent (`#signed`). Each release of this
   *  Worker reads that row shape, so a rollback to an earlier release sends each held row. */
  async put(mind: string, said: Said & { at: number; about?: string[] }): Promise<void> {
    if (!isSaid(said))
      throw new TypeError("Outbox.put takes (mind, { path, type, payload, at, about? })");
    const { signer } = await cloudOf(this.env);
    const signed = await keyForm(signer, mind, said);
    await this.#hold({
      mind,
      signed,
      about: said.about,
      at: Date.now(),
      bytes: JSON.stringify(signed).length,
    });
  }

  async pass(passed: Passed): Promise<void> {
    if (!isPassed(passed)) throw new TypeError("Outbox.pass takes { url, headers, body }");
    await this.#hold({ passed, at: Date.now(), bytes: passed.body.byteLength });
  }

  /** THE INBOX'S ONE WRITE for a delivery the provider signed: what is passed on unchanged (every
   *  delivery, a repeated one too) and what is relayed to the deployments (once: a delivery whose
   *  id came before is not kept again). Both rows and the id go in together. Answers whether the
   *  delivery is new. */
  async take(relay: Relay, passed?: Passed): Promise<boolean> {
    if (!isRelay(relay) || (passed && !isPassed(passed)))
      throw new TypeError(
        "Outbox.take takes ({ client, account, id, type, payload }, { url, headers, body }?)",
      );
    const seen = relay.id ? `seen:${relay.id}` : "";
    const first = !seen || !(await this.ctx.storage.get(seen));
    const at = Date.now();
    let next = (await this.ctx.storage.get<number>("next")) || 0;
    const row = (kind: "hand" | "item") => `${kind}:${String((next += 1)).padStart(12, "0")}`;
    const rows: Record<string, unknown> = {};
    // two queues: what is passed on unchanged waits for no relay that is stuck before it
    if (passed)
      rows[row("hand")] = {
        handOn: passed,
        client: relay.client,
        at,
        bytes: passed.body.byteLength,
      } satisfies Held;
    if (first)
      rows[row("item")] = {
        relay,
        at,
        bytes: JSON.stringify(relay.payload ?? null).length,
      } satisfies Held;
    if (first && seen) rows[seen] = at;
    await this.#keep({ ...rows, next });
    if (passed) await this.#boundKept("hand:");
    if (first) await this.#boundKept("item:");
    return first;
  }

  /** One of the inbox's rows, handed to where it goes. It throws when an object that every row
   *  needs does not answer. It answers the deployment whose own outbox did not take a relay (the
   *  first, when several did not), after it gave the relay to every other deployment of the
   *  account; and null when the row is handed over. Either way but null, the row waits. */
  async #forward(
    key: string,
    held: Extract<Held, { handOn: Passed } | { relay: Relay }>,
  ): Promise<{ mind: string; error: string } | null> {
    if ("handOn" in held) {
      await this.env.OUTBOX.get(this.env.OUTBOX.idFromName(`pass-on\n${held.client}`)).pass(
        held.handOn,
      );
      return null;
    }
    const { relay } = held;
    const { clients } = await cloudOf(this.env);
    // a deployment whose claim is too old (`claimAgeOf`) gets no delivery, as it gets no token
    const minds = relay.publicPost
      ? await this.env.BOT.get(this.env.BOT.idFromName(relay.client)).postSubscribers(relay.account)
      : relay.account
        ? await routesOf(this.env).mindsOf(
            relay.client,
            relay.account,
            claimAgeOf(this.env, clients[relay.client]),
          )
        : [];
    const relayed = relay.relayed || [];
    let refusedBy: { mind: string; error: string } | null = null;
    for (const mind of minds) {
      if (relayed.includes(mind)) continue;
      // A DEPLOYMENT'S OWN OUTBOX that does not answer, or does not take the statement, stops
      // this deployment's copy and no other's
      // what is said: the deployment's own outbox signs it in the mind form when it sends it,
      // so that a signature of the Cloud's mind that fails for one deployment holds back no
      // other's
      try {
        await this.env.OUTBOX.get(this.env.OUTBOX.idFromName(mind)).put(mind, {
          path: `/integrations/${relay.client}/${relay.account}`,
          type: relay.type,
          payload: relay.payload,
          at: held.at,
          ...(relay.id && { about: [`cloud:${relay.client}:${relay.id}`] }),
        });
      } catch (error) {
        refusedBy ||= { mind, error: String(error) };
        continue;
      }
      // kept after each deployment: a relay that fails further on does not write to this one again
      relayed.push(mind);
      await this.ctx.storage.put(key, { ...held, relay: { ...relay, relayed } } satisfies Held);
    }
    if (refusedBy) return refusedBy;
    // THE PROVIDER SAYS WHEN A CONNECTION ENDS: the deployments heard the event, and now their rows go
    if (relay.ended) await routesOf(this.env).release(relay.client, "", "", relay.account);
    if (relay.withdrawnBy) await routesOf(this.env).release(relay.client, relay.withdrawnBy);
    console.info({
      event: "cloud.relayed",
      client: relay.client,
      account: relay.account,
      deployments: minds.length,
    });
    return null;
  }

  /** AN INBOX'S ALARM. Its rows go to the Cloud's own objects, from queues that are each handed
   *  over in order until a row does not go (`#drain`):
   *
   *    hand:               what is passed on unchanged, all of it to one object
   *    item:               what is relayed to the deployments that connected its account
   *    wait\n<account>\n   the relays of an account one of whose deployments' outbox takes nothing
   *
   *  A row that does not go keeps its own queue and no other. So one deployment, or the platform
   *  the app served before, holds nobody else's deliveries, and an account's own stay in the
   *  order they came. Such a row is tried again later each time, whatever arrives meanwhile, and
   *  dropped with a line in the log when a day old. */
  async #handOver(): Promise<void> {
    const back = [
      await this.#drain("hand:", "waits:hand"),
      await this.#drain("item:", "waits:item"),
    ];
    // after the relays: an account that they just set aside is in this list
    const stuck = await this.ctx.storage.list<Wait>({ prefix: STUCK, limit: 1000 });
    for (const mark of stuck.keys())
      back.push(await this.#drain(`wait\n${mark.slice(STUCK.length)}\n`, mark));
    const next = Math.min(...back.filter((at) => at > 0));
    if (Number.isFinite(next)) await this.#alarmBy(next);
    else await this.#sweep();
  }

  /** The alarm at `at`, unless one is set for sooner. In an alarm's handler the alarm that fired
   *  is set no more, so one that is set was asked for since the handler began: by a delivery
   *  that came meanwhile (`#keep`), whose rows can be in a queue this pass has finished.
   *  A later alarm over it would leave them until then: up to a day, for the sweep's. No
   *  delivery comes between the read and the write: a Durable Object is handed no other event
   *  while it waits for its storage (Cloudflare's input gate), and an alarm is storage. */
  async #alarmBy(at: number): Promise<void> {
    const set = await this.ctx.storage.getAlarm();
    if (!set || at < set) await this.ctx.storage.setAlarm(at);
  }

  /** One queue of an inbox, handed over in order until a row does not go. Answers when to come
   *  back for it, or 0 when it is empty. `waits` is where the tries of its head are kept. For an
   *  account's own queue that row is also the account's mark (STUCK): it stays while the account
   *  has a row there, and goes with the last. */
  async #drain(prefix: string, waits: string): Promise<number> {
    const ofAccount = waits.startsWith(STUCK);
    for (;;) {
      const [head] = await this.ctx.storage.list<Held>({ prefix, limit: 1 });
      if (!head) {
        await this.ctx.storage.delete(waits);
        return 0;
      }
      const [key, held] = head;
      this.#working = key;
      if (!("handOn" in held || "relay" in held)) return 0;
      const wait = await this.ctx.storage.get<Wait>(waits);
      if (wait && Date.now() < wait.until) return wait.until;
      // a relay of an account that waits aside goes behind that account's rows: its order holds
      if (
        !ofAccount &&
        "relay" in held &&
        (await this.ctx.storage.get(`${STUCK}${held.relay.account}`))
      ) {
        await this.#setAside(key, held);
        if (wait) await this.ctx.storage.delete(waits);
        continue;
      }
      const refusedBy: { mind?: string; error: string } | null = await this.#forward(
        key,
        held,
      ).catch((error: unknown) => ({ error: String(error) }));
      if (refusedBy && Date.now() - held.at < HELD_MS) {
        console.warn({ event: "cloud.inbox-waits", key, ...refusedBy });
        // ONE DEPLOYMENT'S OUTBOX TAKES NOTHING: the relay, and what comes for its account after
        // it, wait in a queue of their own, and the rest of the inbox goes on
        if (refusedBy.mind && !ofAccount && "relay" in held) {
          // as `#forward` left it: with the deployments that did take it
          const now = await this.ctx.storage.get<Extract<Held, { relay: Relay }>>(key);
          await this.#setAside(key, now || held, {
            tries: 1,
            until: Date.now() + inboxWaitMs(1),
          });
          // the row after it starts its own count
          if (wait) await this.ctx.storage.delete(waits);
          continue;
        }
        const tries = (wait?.tries || 0) + 1;
        const until = Date.now() + inboxWaitMs(tries);
        await this.ctx.storage.put(waits, { tries, until } satisfies Wait);
        return until;
      }
      if (refusedBy) console.error({ event: "cloud.inbox-dropped", key, ...refusedBy });
      await this.ctx.storage.delete(key);
      // the row after it starts its own count
      if (wait) await this.ctx.storage.put(waits, { tries: 0, until: 0 } satisfies Wait);
    }
  }

  /** A relay moved behind its account's own rows, under the number it came with, and with the
   *  mark that the account waits when it is the first. One write: nothing is awaited between
   *  the two. */
  async #setAside(key: string, held: Extract<Held, { relay: Relay }>, mark?: Wait): Promise<void> {
    const { account } = held.relay;
    const moved = this.ctx.storage.put({
      [`wait\n${account}\n${key.slice(key.indexOf(":") + 1)}`]: held,
      ...(mark && { [`${STUCK}${account}`]: mark }),
    });
    await Promise.all([moved, this.ctx.storage.delete(key)]);
    await this.#bound(`wait\n${account}\n`);
  }

  async #hold(held: Held): Promise<void> {
    const next = ((await this.ctx.storage.get<number>("next")) || 0) + 1;
    await this.#keep({ next, [`item:${String(next).padStart(12, "0")}`]: held });
    await this.#boundKept("item:");
  }

  /** A WRITER KEEPS ITS ROWS AND WAKES THE QUEUE, OR KEEPS NOTHING. The rows, the count of tries
   *  and the alarm go to storage with no wait between them, and Cloudflare keeps such writes
   *  together or not at all. Nothing that can fail comes between the row and its alarm: a row
   *  that is kept is a row that an alarm comes for. */
  async #keep(rows: Record<string, unknown>): Promise<void> {
    const kept = this.ctx.storage.put({ ...rows, tries: 0 });
    await Promise.all([kept, this.ctx.storage.setAlarm(Date.now())]);
  }

  /** The bound of a queue after a write to it that is kept (`#keep`). A fault of the bound is
   *  the queue's and not the caller's: the row is held and its alarm is set, so the caller hears
   *  that. A caller that heard a failure would send the same row again, and the queue would hold
   *  it once more for each try. The fault is an error in the log, and the next write bounds the
   *  queue again. */
  async #boundKept(prefix: string): Promise<void> {
    await this.#bound(prefix).catch((error: unknown) =>
      console.error({
        event: "cloud.queue-bound-failed",
        queue: prefix.split(/[:\n]/)[0],
        error: String(error),
      }),
    );
  }

  /** ONE QUEUE HOLDS NO MORE THAN ITS BOUNDS (`QUEUE_MAX_ROWS`, `QUEUE_MAX_BYTES`), after each
   *  write to it. The newest rows stay; the older ones are deleted, with one line in the log that
   *  says whose they were, how many and from when, and nothing of their content. A row written
   *  before `bytes` was kept counts as a row of no bytes. Read in pages, so that a queue longer
   *  than its bounds (one from before them) is never in memory at once. */
  async #bound(prefix: string): Promise<void> {
    const rows: { key: string; bytes: number; stays: boolean }[] = [];
    for (;;) {
      const page = await this.ctx.storage.list<Held>({
        prefix,
        limit: 32,
        ...(rows.length && { startAfter: rows.at(-1)!.key }),
      });
      for (const [key, held] of page)
        rows.push({
          key,
          bytes: held.bytes || 0,
          // THE PROVIDER'S WORD THAT A CONNECTION ENDED is never over: `#forward` must hand it on,
          // because that is what ends the deployments' claims on the account. It leaves by age.
          stays: "relay" in held && Boolean(held.relay.ended || held.relay.withdrawnBy),
        });
      if (page.size < 32) break;
    }
    // from the newest back: `cut` is how many of the oldest rows are over
    let cut = rows.length;
    for (let bytes = 0; cut > 0 && rows.length - cut < QUEUE_MAX_ROWS; cut -= 1)
      if ((bytes += rows[cut - 1]!.bytes) > QUEUE_MAX_BYTES) break;
    const over = rows.slice(0, cut).filter(({ stays }) => !stays);
    if (over.length === 0) return;
    let first: Held | undefined;
    let last: Held | undefined;
    for (const { key } of over) {
      const held = await this.ctx.storage.get<Held>(key);
      if (!held) continue;
      first ||= held;
      last = held;
      // as for a statement that waited a day (`alarm`): what was to be told once is told again
      const unsigned = "mind" in held ? saidUnsigned(held) : null;
      const said = "mind" in held ? (unsigned ? unsigned.said : saidOf(held)) : null;
      if ("mind" in held && said) await this.#toldAgain(held.mind, said);
      await this.ctx.storage.delete(key);
    }
    const whose = !first
      ? {}
      : "mind" in first
        ? { mind: first.mind }
        : "relay" in first
          ? {
              client: first.relay.client,
              ...(prefix.startsWith("wait\n") && { account: first.relay.account }),
            }
          : "handOn" in first
            ? { client: first.client }
            : { url: first.passed.url };
    // a warning and no error: a full queue that lets its oldest rows go does what it is made for
    console.warn({
      event: "cloud.queue-over",
      queue: prefix.split(/[:\n]/)[0],
      ...whose,
      rows: over.length,
      bytes: over.reduce((sum, row) => sum + row.bytes, 0),
      from: first && new Date(first.at).toISOString(),
      to: last && new Date(last.at).toISOString(),
    });
  }

  /** The deployment's identity as its log said last (worker.ts `askerKeyOf`); none before a
   *  log was read at this hostname. Only `keepIdentity` writes it, with an answer of
   *  `publishedMindOf`, which checks it again (`identityStateFrom`) before it reads on from it. */
  async keptIdentity(): Promise<PublishedMind | undefined> {
    return this.ctx.storage.get<PublishedMind>("identity");
  }

  /** A newer state of the same mind's log. An older one, or another mind's, is never kept over
   *  it: two asks that read the log at once keep the later state. */
  async keepIdentity(state: PublishedMind): Promise<void> {
    if (await this.#isNewer(state)) await this.ctx.storage.put("identity", state);
  }

  async #isNewer(state: PublishedMind): Promise<boolean> {
    const kept = await this.keptIdentity();
    return !kept || (kept.expected === state.expected && kept.position < state.position);
  }

  /** The other mind that this hostname's log proved, while this Cloud knows the hostname as the
   *  mind it kept (worker.ts `refusedAt`), and when: shown to a person, never acted on. */
  async refusedIdentity(mind: string): Promise<void> {
    await this.ctx.storage.put("identityRefused", { mind, at: Date.now() });
  }

  /** Whether this is the first use of a deployment's statement (worker.ts `askedBy`): its nonce is
   *  kept while the statement lasts. Kept here because this object is the deployment's own. With
   *  it, `identity`: the state of the log whose key signed it, kept when it is newer. */
  async firstUse(nonce: string, expires: number, identity?: PublishedMind): Promise<boolean> {
    const used = await this.ctx.storage.list<number>({ prefix: "nonce:" });
    const over = [...used].filter(([, until]) => until <= Date.now()).map(([key]) => key);
    if (over.length) await this.ctx.storage.delete(over.slice(0, 128));
    if (used.has(`nonce:${nonce}`)) return false;
    const newer = identity && (await this.#isNewer(identity));
    await this.ctx.storage.put({ [`nonce:${nonce}`]: expires, ...(newer && { identity }) });
    return true;
  }

  /** THE STATEMENT OF A HELD ROW, signed in its place in the queue before it is sent. A row is
   *  held in the key form (`put`). For another
   *  deployment it is signed again here in the mind form (`statementFor`), with the same path,
   *  type, payload and `about`, and the rest of its day. Answers the signed row, or null, with a
   *  line in the log, when the Cloud's mind did not sign: the row waits, and is never sent in the
   *  key form. */
  async #signed(
    key: string,
    held: Extract<Held, { mind: string }>,
  ): Promise<Extract<Held, { signed: Signed }> | null> {
    if (keyFormOf(held.signed).from || !this.#takesMindForm(held.mind)) return held;
    const { signer } = await cloudOf(this.env);
    try {
      const signed = await statementFor(this.env, signer, held.mind, saidOf(held));
      const row = { mind: held.mind, signed, at: held.at, bytes: held.bytes };
      await this.ctx.storage.put(key, row satisfies Held);
      return row;
    } catch (error) {
      console.warn({ event: "cloud.mind-sign-failed", mind: held.mind, error: String(error) });
      return null;
    }
  }

  /** THE OTHER MIND THAT THIS HOSTNAME SERVES NOW, or null. A hostname that this Cloud knows as
   *  one mind (its kept identity, step 3) gets no statement while its log proves another: what
   *  the Cloud holds for it was for the mind it knew. `MIND_AUTH` signs for whatever mind a
   *  hostname serves when it signs, so this is read first. The read is `identityAt`'s, kept a
   *  minute for each hostname. A hostname of which no identity is kept, or whose log could not be
   *  read, is sent to as before: only another mind's proven log holds a row. */
  async #movedTo(mind: string): Promise<string | null> {
    const kept = await this.keptIdentity();
    if (!kept) return null;
    const read = await identityAt(mind, this, this.env);
    const serves = "serves" in read ? read.serves : undefined;
    if (!serves) return null;
    console.warn({ event: "cloud.mind-moved", mind, known: kept.expected, serves });
    return serves;
  }

  /** Drops what this outbox holds (worker.ts `forget`): the statements that wait, the pin and the
   *  last refusal. THE NONCES STAY: a statement counts once, before a clear and after it, so one
   *  that someone captured is not taken again. Answers how many statements were dropped. */
  async forget(): Promise<number> {
    const kept = await this.ctx.storage.list();
    const keys = [...kept.keys()].filter((key) => !key.startsWith("nonce:"));
    const held = keys.filter((key) => key.startsWith("item:")).length;
    // the alarm comes back when the last nonce ends, and sweeps them (`#sweep`)
    const last = Math.max(
      0,
      ...[...kept].map(([key, until]) => (key.startsWith("nonce:") ? Number(until) : 0)),
    );
    if (last) await this.ctx.storage.setAlarm(last);
    else await this.ctx.storage.deleteAlarm();
    for (let from = 0; from < keys.length; from += 128)
      await this.ctx.storage.delete(keys.slice(from, from + 128));
    return held;
  }

  /** What this outbox says of its deployment (`status`): the mind it is pinned to, another mind
   *  its hostname's log proved (`identityRefused`), what waits, and the last refusal. */
  async status(): Promise<OutboxStatus> {
    const [identity, moved, lastRefused, items] = await Promise.all([
      this.keptIdentity(),
      this.ctx.storage.get<{ mind: string; at: number }>("identityRefused"),
      this.ctx.storage.get<Refusal>("lastRefused"),
      this.ctx.storage.list<Held>({ prefix: "item:" }),
    ]);
    const statements = [...items.values()].filter((held) => "mind" in held);
    return {
      id: identity?.expected || null,
      movedTo: moved && { id: moved.mind, at: moved.at },
      held: statements.length,
      oldestAt: statements[0]?.at || null,
      lastRefused: lastRefused || null,
    };
  }

  /** Whether `statementFor` makes the mind form for this deployment. */
  #takesMindForm(mind: string): boolean {
    return !!this.env.MIND_AUTH && !!this.env.MIND_HOSTNAME && mind !== this.env.MIND_HOSTNAME;
  }

  /** AN INBOX REMEMBERS A DELIVERY'S ID for as long as its provider may send it again, a day. With
   *  nothing left to hand over, the ids older than that go, and the alarm comes back for the rest. */
  async #sweep(): Promise<void> {
    // a statement's nonce lasts as long as the statement (`firstUse`); after a clear no use may
    // come to sweep them, so this does
    const used = await this.ctx.storage.list<number>({ prefix: "nonce:", limit: 1000 });
    const spent = [...used].filter(([, until]) => until <= Date.now()).map(([key]) => key);
    for (let from = 0; from < spent.length; from += 128)
      await this.ctx.storage.delete(spent.slice(from, from + 128));
    const unreadEnds = await this.#sweepUnread();
    if (unreadEnds) await this.#alarmBy(unreadEnds);
    const seen = await this.ctx.storage.list<number>({ prefix: "seen:", limit: 1000 });
    if (seen.size === 0) return;
    const over = [...seen].filter(([, at]) => at <= Date.now() - HELD_MS).map(([key]) => key);
    for (let from = 0; from < over.length; from += 128)
      await this.ctx.storage.delete(over.slice(from, from + 128));
    if (seen.size > over.length) await this.#alarmBy(Date.now() + HELD_MS);
  }

  /** A ROW SET ASIDE AS UNREADABLE (`alarm`) IS KEPT A DAY from when it came, as every held row
   *  is, and no longer. Deletes the ones whose day is over, page after page, and answers when
   *  the next one ends, or 0 when none is left. */
  async #sweepUnread(): Promise<number> {
    const now = Date.now();
    let next = 0;
    let after: string | undefined;
    for (;;) {
      const page = await this.ctx.storage.list<Held>({
        prefix: UNREAD,
        limit: 1000,
        startAfter: after,
      });
      const old: string[] = [];
      // a key's order is not its row's age: every row is read, and the soonest end is kept
      for (const [key, row] of page) {
        const ends = (row.at || 0) + HELD_MS;
        if (ends <= now) old.push(key);
        else next = next ? Math.min(next, ends) : ends;
        after = key;
      }
      for (let from = 0; from < old.length; from += 128)
        await this.ctx.storage.delete(old.slice(from, from + 128));
      if (page.size < 1000) return next;
    }
  }

  /** Try now (README "What is kept": after a secret is put right). */
  async wake(): Promise<void> {
    await this.#keep({});
  }

  /** AN ALARM THAT THROWS IS A DEFECT, AND IT DOES NOT END THE QUEUE. Cloudflare tries a thrown
   *  alarm six times and then sets none: the queue would wait for the next arrival, and go on to
   *  throw at each one, with no delivery between them. So the throw is caught and said as an
   *  error, which the prd fault alarm pages, and the alarm is set again as for a head that was
   *  not taken (`outboxWaitMs`).
   *
   *  THE DAY'S BOUND HOLDS FOR A ROW THAT THROWS TOO, and for that row alone: the one this alarm
   *  worked on when it threw (`#working`), in whichever queue. A row that the alarm reads leaves
   *  when its day is over by the alarm's own path, with what that path owes it (the told row, a
   *  line in the log), and does not come here. So a row that still throws then is one that the
   *  alarm cannot read: it is read here for its time alone, and dropped when its day is over or
   *  it has no time. No other row is touched, and nothing holds a queue for longer than a row is
   *  held. */
  override async alarm(): Promise<void> {
    this.#working = "";
    try {
      await this.#send();
    } catch (error) {
      const key = this.#working;
      const rows = await this.ctx.storage.list<{ at?: number }>({ prefix: key, limit: 1 });
      // NaN for a row with no time, or one that is no object: not within its day
      const dropped = !!key && rows.has(key) && !(Date.now() - (rows.get(key)?.at ?? 0) < HELD_MS);
      if (dropped) await this.ctx.storage.delete(key);
      const tries = dropped ? 0 : ((await this.ctx.storage.get<number>("tries")) || 0) + 1;
      await this.ctx.storage.put("tries", tries);
      await this.ctx.storage.setAlarm(Date.now() + (dropped ? 0 : outboxWaitMs(tries)));
      console.error({
        event: "cloud.outbox-alarm-failed",
        row: key,
        dropped,
        tries,
        error: String(error),
      });
    }
  }

  /** The key of the row that the alarm works on, or "" before its first: what a throw is about. */
  #working = "";

  async #send(): Promise<void> {
    // an inbox has queues of its own (`take`, `#handOver`)
    for (const prefix of ["hand:", STUCK])
      if ((await this.ctx.storage.list({ prefix, limit: 1 })).size > 0) return this.#handOver();
    for (;;) {
      const [head] = await this.ctx.storage.list<Held>({ prefix: "item:", limit: 1 });
      if (!head) return this.#sweep();
      const [key, held] = head;
      this.#working = key;
      if ("handOn" in held || "relay" in held) return this.#handOver();
      // A ROW WHOSE `signed` IS NO SIGNED STATEMENT would stop every alarm at the head, and no
      // statement behind it would ever go (`saidUnsigned`). One that holds what was to be said is
      // signed now, in its place, with its own time and `about`: it then goes as any other. One
      // that says nothing readable is set aside, with a line in the log.
      const unsigned = "mind" in held ? saidUnsigned(held) : null;
      if ("mind" in held && unsigned) {
        const { said } = unsigned;
        if (said) {
          // ITS DAY IS OVER: it is not signed only to be dropped, and a signature that fails then
          // must not cost it its end. It ends as a signed row ends below
          if (Date.now() - held.at >= HELD_MS) {
            await this.#toldAgain(held.mind, said);
            await this.ctx.storage.delete(key);
            continue;
          }
          const { signer } = await cloudOf(this.env);
          const signed = await keyForm(signer, held.mind, said);
          await this.ctx.storage.put(key, {
            mind: held.mind,
            signed,
            about: said.about,
            at: held.at,
            bytes: held.bytes,
          } satisfies Held);
          console.warn({
            event: "cloud.outbox-row-signed-late",
            mind: held.mind,
            key,
            at: held.at,
          });
        } else {
          console.error({
            event: "cloud.outbox-row-unreadable",
            mind: held.mind,
            key,
            at: held.at,
          });
          // set aside under `unread:`, out of the queue, for the rest of its day (`#sweep`)
          await Promise.all([
            this.ctx.storage.put(`${UNREAD}${key}`, held),
            this.ctx.storage.delete(key),
          ]);
        }
        continue;
      }
      // A statement waits a day for its deployment, and is not sent after that. A delivery passed
      // on is always tried, and then waits a minute at most: its provider would not have tried the
      // other platform again at all, and one that platform cannot answer must not hold back every
      // delivery behind it.
      const waits = Date.now() - held.at < ("passed" in held ? 60_000 : HELD_MS);
      // A HOSTNAME THAT NOW SERVES ANOTHER MIND gets nothing (`#movedTo`), and a mind that is not
      // enrolled waits while the gate is "on" (`shutOut`). Else a statement is signed in its place
      // before it is sent (`#signed`), and a delivery passed on is always tried
      const moved = "mind" in held && waits ? await this.#movedTo(held.mind) : null;
      const shut =
        "mind" in held && waits && !moved
          ? await shutOutAt(held.mind, "delivery", this, this.env)
          : null;
      const sent =
        "passed" in held ? held : waits && !moved && !shut ? await this.#signed(key, held) : null;
      const answer: { took: boolean; refused?: Refusal } = sent
        ? await taken(sent)
        : shut
          ? { took: false, refused: { reason: shut.why, status: shut.status, at: Date.now() } }
          : { took: false };
      const took = answer.took;
      if (answer.refused) await this.ctx.storage.put("lastRefused", answer.refused);
      if (!took && waits) {
        const tries = ((await this.ctx.storage.get<number>("tries")) || 0) + 1;
        await this.ctx.storage.put("tries", tries);
        await this.ctx.storage.setAlarm(Date.now() + outboxWaitMs(tries));
        // a queue that waits never comes to `#sweep`: the rows set aside end here too, and the
        // alarm above comes back within 15 minutes for the rest
        await this.#sweepUnread();
        return;
      }
      if (!took && "passed" in held)
        console.warn({ event: "cloud.pass-on-dropped", url: held.passed.url });
      if (!took && "mind" in held) await this.#toldAgain(held.mind, saidOf(held));
      await this.ctx.storage.delete(key);
      await this.ctx.storage.put("tries", 0);
    }
  }

  /** What the deployment was to be told once and never took is told again (`toldOnce`): its told
   *  row goes. The routes object may fail for a while: the statement goes all the same, so that
   *  it holds back none behind it, and that word is then not told again until its row lapses. */
  async #toldAgain(mind: string, said: Pick<Said, "type" | "path">): Promise<void> {
    await routesOf(this.env)
      .forget(toldRow(mind, said))
      .catch((error) => console.warn({ event: "cloud.told-row-kept", mind, error: String(error) }));
  }
}

/** A deployment's refusal of a statement, as its outbox keeps the last one (`status`). */
type Refusal = { reason: string; status: number; at: number };

/** Whether the destination took what was held, or never will: either way the Cloud's copy goes.
 *  A deployment took a statement, or has seen it, or it has expired. A deployment that is down,
 *  or refuses it (`403 { refused }`: its owner did not let the Cloud's mind in, or it does not
 *  know the Cloud's key yet), is tried again, with its reason in the log, until the statement's
 *  day ends, and its refusal goes back to be kept (`lastRefused`). The platform a delivery
 *  is passed on to answered it, with a yes or with a refusal of its own: only its failure to
 *  answer (a 5xx, a 429, nothing) is tried again. Never followed, and never waited for long: a
 *  redirect or silence is no answer. */
async function taken(
  held: Extract<Held, { passed: Passed } | { signed: Signed }>,
): Promise<{ took: boolean; refused?: Refusal }> {
  const sent = { method: "POST", redirect: "manual", signal: AbortSignal.timeout(15_000) } as const;
  try {
    if ("passed" in held) {
      const { url, headers, body } = held.passed;
      const answer = await fetch(url, { ...sent, headers, body });
      await answer.body?.cancel();
      // the one record of what the other platform said: the Cloud keeps no copy of a delivery
      console.info({ event: "cloud.passed-on", url, status: answer.status });
      return { took: answer.status < 500 && answer.status !== 429 };
    }
    const answer = await fetch(`${controlPlaneOf(held.mind)}/statements`, {
      ...sent,
      headers: { "content-type": "application/json" },
      body: JSON.stringify(held.signed),
    });
    if (answer.ok) return { took: true };
    const { refused = "" } = (await answer.json().catch(() => ({}))) as { refused?: string };
    if (/seen|expired/i.test(refused)) return { took: true };
    console.info({
      event: "cloud.statement-refused",
      mind: held.mind,
      status: answer.status,
      refused,
    });
    return { took: false, refused: { reason: refused, status: answer.status, at: Date.now() } };
  } catch (error) {
    if ("passed" in held)
      console.warn({ event: "cloud.pass-on-failed", url: held.passed.url, error: String(error) });
    return { took: false };
  }
}

/** A request's body, or null when it is over `limit` bytes: refused on its `content-length`
 *  before a read, and read no further than the limit when it names none. Anyone can post to a
 *  webhook's address, so nothing larger is ever held. Its bytes are what the provider signed and
 *  what is passed on. */
async function bodyWithin(
  request: Request,
  limit: number,
): Promise<{ bytes: Uint8Array; text: string } | null> {
  if (Number(request.headers.get("content-length") || 0) > limit) return null;
  const chunks: Uint8Array[] = [];
  let size = 0;
  for await (const chunk of request.body || []) {
    size += chunk.byteLength;
    if (size > limit) return null;
    chunks.push(chunk);
  }
  const bytes = Buffer.concat(chunks);
  return { bytes, text: bytes.toString() };
}

// ── pages ────────────────────────────────────────────────────────────────────────────────────────

const escaped = (text: string) =>
  text.replace(/[&<>"']/g, (character) => `&#${character.charCodeAt(0)};`);

/** iterate's mark (internal-packages/installer/public/iterate-logo.svg), inline: the page's
 *  policy loads nothing, not even an image of its own origin. */
const LOGO = `<svg class="logo" viewBox="0 0 500 500" aria-hidden="true"><rect width="500" height="500" fill="#000"/><g fill="#fff" transform="translate(20 20) scale(.92)"><path d="M264.649 170.149H289.821L286.092 186.904L276.303 233.444L270.709 259.971L263.717 293.015L258.124 320.008L251.131 352.586L249.267 364.687V371.668L249.733 372.133H253.462L259.522 369.806L266.048 365.617L275.371 357.24L282.829 349.328L286.558 345.14L288.888 346.071L294.948 350.725L308 360.498L307.068 362.36L303.339 367.944L296.813 376.322L291.685 382.837L286.558 388.422L282.363 393.076L275.837 399.592L272.108 402.849L267.446 406.573L262.785 409.83L256.725 413.554L247.869 417.742L238.08 420.535L231.554 421H224.096L216.637 420.069L211.51 418.673L206.382 416.811L201.255 413.088L196.594 408.434L192.865 400.988L191.466 394.938L191 389.818V383.768L193.797 365.152L199.857 335.832L207.315 301.392L224.096 223.205L225.028 216.224V206.916L224.562 205.054L222.231 204.123L219.434 203.193L206.382 203.658L196.127 204.589H193.331V178.526L194.263 175.734L258.59 170.615L264.649 170.149Z"/><path d="M264.649 78H268.844L275.836 78.9308L282.362 80.7924L287.49 83.5848L292.151 87.7734L295.414 92.8928L297.278 96.616L299.143 105.924L299.609 113.836L299.143 118.49L298.677 122.213L296.812 128.729L293.549 134.779L290.286 138.502L286.091 141.76L282.362 143.621L278.167 145.018L274.438 145.948L267.912 146.414H260.92L254.394 145.483L249.267 144.087L244.139 141.294L239.944 138.037L236.681 133.383L233.884 127.332L232.486 121.282L232.02 117.559V108.716L232.952 101.735L234.816 95.6852L237.613 90.1004L240.41 86.3772L246.936 82.1886L252.529 79.8616L259.522 78.4654L264.649 78Z"/></g></svg>`;

/** A page a person reads on the Cloud's origin: plain HTML, no script, and no referrer, because a
 *  link on it may carry a code. A small card on a calm page, in the installer's colours. The
 *  heading is HTML (it may hold a bold hostname); the title is its text. */
function page(title: string, heading: string, body: string): Response {
  return new Response(
    `<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>${escaped(title)}</title>
<style>
:root{color-scheme:light dark;--page:#f7f7f7;--card:#fff;--text:#0a0a0a;--muted:#6f6f6f;--border:#e5e5e5;--button:#171717;--button-text:#fafafa}
@media(prefers-color-scheme:dark){:root{--page:#0a0a0a;--card:#171717;--text:#fafafa;--muted:#a1a1a1;--border:#2e2e2e;--button:#fafafa;--button-text:#171717}.logo{filter:invert(1)}}
*{box-sizing:border-box}
body{margin:0;min-height:100vh;display:flex;align-items:center;justify-content:center;padding:1rem;background:var(--page);color:var(--text);font:16px/1.5 ui-sans-serif,system-ui,-apple-system,"Segoe UI",Roboto,sans-serif;-webkit-font-smoothing:antialiased}
main{width:100%;max-width:24rem;padding:2rem 1.5rem 1.5rem;background:var(--card);border:1px solid var(--border);border-radius:.875rem;text-align:center;overflow-wrap:anywhere}
.logo{display:block;width:2.5rem;height:2.5rem;margin:0 auto 1.25rem;border-radius:.625rem}
h1{margin:0 0 1.5rem;font-size:1.25rem;line-height:1.4;font-weight:500;text-wrap:balance}
h1 b{font-weight:650}
p{margin:0 0 1.5rem}
.note{margin:-.75rem 0 1.5rem;font-size:.875rem;color:var(--muted)}
.note b{color:var(--text);font-weight:600}
.go{display:block;padding:.625rem 1rem;border-radius:.625rem;background:var(--button);color:var(--button-text);font-weight:500;text-decoration:none}
.go:hover{opacity:.9}
.go:focus-visible{outline:2px solid var(--button);outline-offset:2px}
</style>
<main>${LOGO}<h1>${heading}</h1>${body}</main></html>`,
    {
      headers: {
        "content-type": "text/html; charset=utf-8",
        "cache-control": "no-store",
        "referrer-policy": "no-referrer",
        // no script, and never inside another site's frame, where a click could be stolen
        "content-security-policy":
          "default-src 'none'; style-src 'unsafe-inline'; frame-ancestors 'none'",
      },
    },
  );
}