iterate.com / cloud

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

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

import { createHmac, generateKeyPairSync } from "node:crypto";
import { exportJWK, generateKeyPair, SignJWT } from "jose";
import { expect, test, vi } from "vitest";
import { identityHashOf, type SignedRecord } from "../../../core/lib/src/mind-identity.ts";
import { newIdentityLog } from "../../../core/lib/src/test-support/identity-log.ts";
import { brokered } from "../../../core/secrets-worker/src/cloud-client.ts";
import { base64url, keyIdOf, signerOf, statementOf, type Signed } from "./signed.ts";
import { botLinkOf } from "./keys.ts";
import { waited } from "./test-workers.ts";
import { fieldAt, objectOf } from "./post-subscriptions.ts";
import cloud, {
  Bot,
  HELD_MS,
  Outbox,
  QUEUE_MAX_ROWS,
  Routes,
  type Client,
  type Env,
} from "./worker.ts";

const CLOUD = "https://cloud.example";
const PROVIDER = "https://provider.example";
/** The platform the apps served before the Cloud. */
const OS = "https://os.example/api/integrations";
const github: Client = {
  kind: "github",
  clientId: "Iv1.client",
  authorizationEndpoint: `${PROVIDER}/login/oauth/authorize`,
  tokenEndpoint: `${PROVIDER}/login/oauth/access_token`,
  api: PROVIDER,
  urls: [PROVIDER],
  appId: "42",
  installUrl: `${PROVIDER}/apps/iterate/installations/new`,
  passOn: { callback: `${OS}/github/callback`, webhook: `${OS}/github/webhook` },
};
const slack: Client = {
  kind: "slack",
  clientId: "slack-client",
  authorizationEndpoint: `${PROVIDER}/oauth/v2/authorize`,
  tokenEndpoint: `${PROVIDER}/api/oauth.v2.access`,
  api: PROVIDER,
  urls: [PROVIDER],
  passOn: {
    callback: `${OS}/slack/callback`,
    webhook: `${OS}/slack/webhook`,
    "interactivity-webhook": `${OS}/slack/interactivity-webhook`,
  },
};
/** Gmail's push: the topic of the client's Google project, and what the token of its one push
 *  subscription says. The provider of these tests stands in for Google's Pub/Sub too. */
const GMAIL_PUSH = {
  topic: "projects/iterate-example/topics/gmail-push",
  audience: `${CLOUD}/clients/google/webhook`,
  serviceAccount: "cloud-push@iterate-example.iam.gserviceaccount.com",
  issuer: PROVIDER,
  certs: `${PROVIDER}/oauth2/v3/certs`,
};
const google: Client = {
  kind: "google",
  clientId: "google-client",
  authorizationEndpoint: `${PROVIDER}/o/oauth2/v2/auth?access_type=offline&prompt=consent`,
  tokenEndpoint: `${PROVIDER}/token`,
  api: PROVIDER,
  urls: [PROVIDER],
  gmailPush: GMAIL_PUSH,
};
const cloudflare: Client = {
  kind: "cloudflare",
  clientId: "cloudflare-client",
  authorizationEndpoint: `${PROVIDER}/oauth2/auth`,
  tokenEndpoint: `${PROVIDER}/oauth2/token`,
  api: PROVIDER,
  urls: [PROVIDER],
  scopes: ["zone.read", "workers-observability.write", "offline_access"],
};
const x: Client = {
  kind: "x",
  clientId: "x-client",
  authorizationEndpoint: `${PROVIDER}/i/oauth2/authorize`,
  tokenEndpoint: `${PROVIDER}/2/oauth2/token`,
  api: PROVIDER,
  urls: [PROVIDER],
};

test("the Cloud publishes its key and each client's public facts, and no secret", async () => {
  const { env, cloudKey } = await setup();
  const facts = (await (await cloud.fetch(get("/.well-known/iterate-cloud"), env)).json()) as any;
  expect(facts).toMatchObject({
    actor: "iterate-cloud",
    key: cloudKey.key,
    publicKey: cloudKey.publicKey,
    clients: {
      github: {
        clientId: "Iv1.client",
        redirectUri: `${CLOUD}/clients/github/callback`,
        tokenEndpoint: `${CLOUD}/clients/github/token`,
        installationTokenEndpoint: `${CLOUD}/clients/github/installation-token`,
      },
    },
  });
  expect(JSON.stringify(facts)).not.toMatch(/client-secret|webhook-secret|PRIVATE/);
});

test("a Cloudflare connect reads one account and no more: the page says so, a link or a token that reaches more connects nothing, and no route is claimed", async () => {
  const { env, deployment, provider, proofFor } = await setup();
  const ada = await deployment("ada.example");
  const state = `${base64url(Buffer.from("https://iterate.ada.example/secrets/oauth/callback"))}.nonce.1`;
  const consent = `${cloudflare.authorizationEndpoint}?client_id=${cloudflare.clientId}&redirect_uri=${encodeURIComponent(`${CLOUD}/clients/cloudflare/callback`)}&state=${state}`;
  const begin = (scope: string) =>
    cloud.fetch(
      get(
        `/clients/cloudflare/begin?to=${encodeURIComponent(`${consent}&scope=${encodeURIComponent(scope)}`)}`,
      ),
      env,
    );
  const html = await (await begin("zone.read workers-observability.write offline_access")).text();
  expect(html).toContain("Give <b>iterate.ada.example</b> access to your Cloudflare account?");
  expect(html).toContain("select only the account that <b>iterate.ada.example</b> runs in");
  expect(html).toContain("It deploys and changes nothing.");
  // a link that asks a deploy, or the right to make tokens, is no link of this connection
  for (const more of ["zone.read workers-scripts.write", "account-api-tokens.write"]) {
    const refused = await begin(more);
    expect(refused).toMatchObject({ status: 400 });
    expect(await refused.text()).toContain("changes nothing");
  }

  // the exchange: the client secret in the form, the refresh token sealed, and no route claimed
  const exchange = await ada.ask("cloudflare:token", {
    grant_type: "authorization_code",
    code: "cf-c0de",
    code_verifier: "v3rifier",
    cloud_proof: await proofFor("ada.example", "cf-c0de", "cloudflare", "", ""),
  });
  expect(exchange).toMatchObject({ status: 200 });
  const tokens = (await exchange.json()) as { access_token: string; refresh_token: string };
  expect(tokens).toMatchObject({
    access_token: "cloudflare-access",
    refresh_token: expect.stringMatching(/^sealed\./),
  });
  expect(Object.fromEntries(provider.tokenRequests.at(-1)!)).toEqual({
    grant_type: "authorization_code",
    code: "cf-c0de",
    code_verifier: "v3rifier",
    redirect_uri: `${CLOUD}/clients/cloudflare/callback`,
    client_id: "cloudflare-client",
    client_secret: "cloudflare-secret",
  });
  const routes = env.ROUTES.get(env.ROUTES.idFromName("routes"));
  expect(await routes.clientsOf("ada.example")).toEqual({});

  // the refresh, with the deployment's own sealed token
  const refresh = await ada.ask("cloudflare:token", {
    grant_type: "refresh_token",
    refresh_token: tokens.refresh_token,
  });
  expect(await refresh.json()).toMatchObject({ access_token: "cloudflare-access" });
  expect(provider.tokenRequests.at(-1)!.get("refresh_token")).toBe("cloudflare-refresh");

  // a token that Cloudflare says reaches more connects nothing
  provider.cloudflareScope = "zone.read workers-scripts.write";
  const over = await ada.ask("cloudflare:token", {
    grant_type: "authorization_code",
    code: "cf-c0de-2",
    cloud_proof: await proofFor("ada.example", "cf-c0de-2", "cloudflare", "", ""),
  });
  expect(over).toMatchObject({ status: 403 });
  expect(await over.text()).toContain("workers-scripts.write");
});

test("a person confirms once, before the provider: the page says which deployment, and the consent then goes straight on", async () => {
  const { env } = await setup();
  const state = `${base64url(Buffer.from("https://iterate.ada.example/secrets/oauth/callback"))}.nonce.1`;
  const consent = `${github.authorizationEndpoint}?client_id=${github.clientId}&redirect_uri=${encodeURIComponent(`${CLOUD}/clients/github/callback`)}&state=${state}`;
  const begin = (to: string, more = "", cookie = "") =>
    cloud.fetch(
      new Request(`${CLOUD}/clients/github/begin?to=${encodeURIComponent(to)}${more}`, {
        headers: { cookie },
      }),
      env,
    );
  const shown = await begin(consent);
  const html = await shown.text();
  expect(html).toContain("Give <b>iterate.ada.example</b> access to your GitHub account?");
  expect(html).toContain("Continue to GitHub");
  expect(shown.headers.get("content-security-policy")).toContain("frame-ancestors 'none'");
  const [cookie] = shown.headers.get("set-cookie")!.split(";");
  expect(shown.headers.get("set-cookie")).toMatch(
    /^__Host-iterate-confirm-[\w-]{22}=[\w-]{22}; HttpOnly; Secure; SameSite=Lax; Path=\/; Max-Age=3600$/,
  );
  const link = new URL(/href="([^"]+)"/.exec(html)![1]!.replaceAll("&#38;", "&"));
  const go = `&go=${link.searchParams.get("go")}`;
  // THE PRESS IS THIS BROWSER'S: the link without the page's cookie, or with another page's,
  // shows the page again and goes nowhere
  const [bare, others] = [await begin(consent, go), await begin(consent, "&go=guess", cookie!)];
  expect([bare.status, others.status]).toEqual([200, 200]);
  const pressed = await begin(consent, go, cookie);
  expect([pressed.status, pressed.headers.get("location")]).toEqual([302, consent]);
  const [confirmed] = pressed.headers.get("set-cookie")!.split(";");
  expect(confirmed).toBe(`${cookie!.split("=")[0]}=ok.${link.searchParams.get("go")}.`);
  // with no account named, the page names no installation; with some, which
  expect(html).not.toContain("Installation");
  const naming = await (await begin(consent, "&accounts=Ada,owned")).text();
  expect(naming).toContain("Installations of: <b>ada</b>, <b>owned</b>");
  expect(await begin(consent, "&accounts=not%20a%20name")).toMatchObject({ status: 400 });
  // A LINK NAMES ACCOUNTS, NEVER AN INSTALLATION: the page shows names, so an installation's id
  // beside a name would take what the page did not say. An id comes from GitHub's install page
  // alone (`callback`).
  for (const hidden of ["ada,%2399", "%2399"])
    expect(await begin(consent, `&accounts=${hidden}`)).toMatchObject({ status: 400 });

  // THE PROVIDER'S CONSENT ENDS ON THE DEPLOYMENT'S OWN PAGE: no second page here, the code goes
  // on with its proof, and the cookie goes
  const back = (cookies: string, at = state) =>
    cloud.fetch(
      new Request(`${CLOUD}/clients/github/callback?code=c0de-1&state=${at}`, {
        headers: { cookie: cookies },
      }),
      env,
    );
  const on = await back(confirmed!);
  const forward = new URL(on.headers.get("location")!);
  expect(on).toMatchObject({ status: 302 });
  expect(forward.origin + forward.pathname).toBe(
    "https://iterate.ada.example/secrets/oauth/callback",
  );
  expect(Object.fromEntries(forward.searchParams)).toMatchObject({
    code: "c0de-1",
    state: "nonce.1",
  });
  expect(forward.searchParams.get("cloud_proof")).toMatch(/^[\w-]{43}\.[\w-]*$/);
  expect(on.headers.get("set-cookie")).toContain("Max-Age=0");
  // a page that was shown and not pressed confirms nothing, and a press for one attempt confirms
  // no other: both are asked on the callback
  const other = `${base64url(Buffer.from("https://iterate.ada.example/secrets/oauth/callback"))}.nonce.2`;
  expect([(await back(cookie!)).status, (await back(confirmed!, other)).status]).toEqual([
    200, 200,
  ]);
  // one proof for one code: the same return again, with the press's own cookie, gets no second
  const twice = await back(confirmed!);
  expect([twice.status, twice.headers.get("location")]).toEqual([400, null]);

  // the install page of the App is this client's consent too
  const install = await begin(`${github.installUrl}?state=${state}`);
  expect(await install.text()).toContain(
    "Give <b>iterate.ada.example</b> access to your GitHub account?",
  );
  // THIS ADDRESS SENDS NOBODY ANYWHERE ELSE: another site, another client's id, a callback that
  // is not this Cloud's, or a state that names no deployment
  for (const to of [
    `https://evil.example/login/oauth/authorize?client_id=${github.clientId}&state=${state}`,
    consent.replace(github.clientId, "someone-elses"),
    consent.replace(encodeURIComponent(CLOUD), encodeURIComponent("https://evil.example")),
    consent.replace(state, "os-state"),
    `${github.installUrl}/../../../evil?state=${state}`,
    "nonsense",
  ])
    expect(await begin(to)).toMatchObject({ status: 400 });
});

test("a consent that did not begin on the Cloud's page is asked on the callback, and the code goes on with one proof, after the press", async () => {
  const { env } = await setup();
  const state = `${base64url(Buffer.from("https://iterate.ada.example/secrets/oauth/callback"))}.nonce.1`;
  const back = (query: string, cookie = "") =>
    cloud.fetch(
      new Request(`${CLOUD}/clients/github/callback?${query}`, { headers: { cookie } }),
      env,
    );
  const linkOf = (html: string) =>
    new URL(/href="([^"]+)"/.exec(html)![1]!.replaceAll("&#38;", "&"));
  const installed = `code=c0de&state=${state}&setup_action=install&installation_id=7`;
  const page = await back(installed);
  const html = await page.text();
  expect(html).toContain("Give <b>iterate.ada.example</b> access to your GitHub account?");
  expect(html).toContain("With the installation you chose at GitHub");
  // NO PROOF BEFORE THE PRESS: the page's link comes back to this address, and holds none
  expect(html).not.toContain("cloud_proof");
  const link = linkOf(html);
  expect(link.origin + link.pathname).toBe(`${CLOUD}/clients/github/callback`);
  const go = link.searchParams.get("go")!;
  expect(page.headers.get("set-cookie")).toMatch(
    new RegExp(`^__Host-iterate-confirm-[\\w-]{22}=here\\.${go}; HttpOnly; Secure; SameSite=Lax`),
  );
  const [cookie] = page.headers.get("set-cookie")!.split(";");

  // a provider's refusal carries no code: it goes on at once
  const refused = await back(`error=access_denied&state=${state}`);
  expect(refused.headers.get("location")).toBe(
    "https://iterate.ada.example/secrets/oauth/callback?error=access_denied&state=nonce.1",
  );
  // the same code again for the same deployment shows the page again (a refreshed tab); for
  // another deployment it gets no page and no proof
  const again = await back(installed);
  const elsewhere = await back(
    `code=c0de&state=${base64url(Buffer.from("https://iterate.eve.example/secrets/oauth/callback"))}.n`,
  );
  expect([again.status, elsewhere.status]).toEqual([200, 400]);
  expect(again.headers.get("content-security-policy")).toContain("frame-ancestors 'none'");
  // THE PRESS IS THIS BROWSER'S: the link with no cookie, or with a value the page did not make,
  // shows the page again
  for (const [query, held] of [
    [`${installed}&go=${go}`, ""],
    [`${installed}&go=guess`, cookie!],
    [`${installed}&go=${go}`, `${cookie!.split("=")[0]}=${go}`],
  ] as const) {
    const unpressed = await back(query, held);
    expect(unpressed).toMatchObject({ status: 200 });
    expect(await unpressed.text()).not.toContain("cloud_proof");
  }
  const pressed = await back(`${installed}&go=${go}`, cookie);
  expect(pressed).toMatchObject({ status: 302 });
  expect(pressed.headers.get("set-cookie")).toContain("Max-Age=0");
  const forward = new URL(pressed.headers.get("location")!);
  expect(forward.origin + forward.pathname).toBe(
    "https://iterate.ada.example/secrets/oauth/callback",
  );
  expect(Object.fromEntries(forward.searchParams)).toMatchObject({
    code: "c0de",
    state: "nonce.1",
    installation_id: "7",
  });
  expect(forward.searchParams.has("go")).toBe(false);
  const [mac, list] = forward.searchParams.get("cloud_proof")!.split(".");
  expect(mac).toMatch(/^[\w-]{43}$/);
  expect(Buffer.from(list!, "base64url").toString()).toBe("#7");

  // ONE PROOF FOR ONE CODE (worker.ts `callback`): the deployment that has the code asks again
  const greedy = `code=c0de&state=${state}&setup_action=install&installation_id=99`;
  const asked = await back(greedy);
  const [own] = asked.headers.get("set-cookie")!.split(";");
  const second = await back(
    `${greedy}&go=${linkOf(await asked.text()).searchParams.get("go")}`,
    own,
  );
  expect(second).toMatchObject({ status: 400 });
  expect(second.headers.get("location")).toBeNull();
  expect(await second.text()).not.toContain("cloud_proof");
  // the same press again (the person went back): no second proof either
  expect(await back(`${installed}&go=${go}`, cookie)).toMatchObject({ status: 400 });

  // AN INSTALLATION IS GITHUB'S WORD, beside `setup_action` alone: an id on any other callback
  // is not on the page and not in the proof
  const bare = await back(`code=c0de-2&state=${state}&installation_id=7`);
  const shown = await bare.text();
  expect(shown).not.toContain("Installation");
  const [held] = bare.headers.get("set-cookie")!.split(";");
  const plain = await back(
    `code=c0de-2&state=${state}&installation_id=7&go=${linkOf(shown).searchParams.get("go")}`,
    held,
  );
  expect(new URL(plain.headers.get("location")!).searchParams.get("cloud_proof")).toMatch(
    /^[\w-]{43}\.$/,
  );
  // a state that names anything but a vault's callback on a hostname over https is not the
  // Cloud's: refused by a client that served nobody before (the one that did sends it there,
  // tested below). Any hostname is a deployment's name; an address with none names nobody.
  for (const to of [
    "http://iterate.ada.example/secrets/oauth/callback",
    "https://iterate.ada.example/api/anything",
    "https://localhost/secrets/oauth/callback",
    "https://192.0.2.7/secrets/oauth/callback",
    "nonsense",
  ]) {
    const bad = await cloud.fetch(
      get(`/clients/x/callback?code=c&state=${base64url(Buffer.from(to))}.n`),
      env,
    );
    expect(bad).toMatchObject({ status: 400 });
  }
});

test("a sign-in with Google: the page says so, the code goes to the deployment's sign-in page, and the exchange answers the id_token alone", async () => {
  const { env, deployment, provider } = await setup();
  const ada = await deployment("iterate.ada.example");
  const state = `${base64url(Buffer.from("https://iterate.ada.example/sign-in/google/callback"))}.n`;
  const consent = (client: Client, scope: string) =>
    `${new URL(client.authorizationEndpoint).origin}${new URL(client.authorizationEndpoint).pathname}?client_id=${client.clientId}&redirect_uri=${encodeURIComponent(`${CLOUD}/clients/${client.kind}/callback`)}&scope=${encodeURIComponent(scope)}&state=${state}`;
  const begin = (client: Client, scope: string, more = "", cookie = "") =>
    cloud.fetch(
      new Request(
        `${CLOUD}/clients/${client.kind}/begin?to=${encodeURIComponent(consent(client, scope))}${more}`,
        { headers: { cookie } },
      ),
      env,
    );
  // a sign-in asks who the person is and nothing more, through Google alone
  const refused = await Promise.all([
    begin(google, "openid email https://www.googleapis.com/auth/gmail.modify"),
    begin(google, ""),
    begin(google, "openid email", "&accounts=ada"),
    begin(github, "openid email"),
  ]);
  expect(refused.map(({ status }) => status)).toEqual([400, 400, 400, 400]);

  const shown = await begin(google, "openid email");
  const html = await shown.text();
  expect(html).toContain("Sign in to <b>iterate.ada.example</b> with Google?");
  expect(html).toContain("It learns your email address and gets no access to your account.");
  expect(html).not.toContain("access to your Google account?");
  const [cookie] = shown.headers.get("set-cookie")!.split(";");
  const go = new URL(/href="([^"]+)"/.exec(html)![1]!.replaceAll("&#38;", "&")).searchParams.get(
    "go",
  );
  const pressed = await begin(google, "openid email", `&go=${go}`, cookie);
  expect(pressed.headers.get("location")).toBe(consent(google, "openid email"));
  const [confirmed] = pressed.headers.get("set-cookie")!.split(";");

  const back = await cloud.fetch(
    new Request(`${CLOUD}/clients/google/callback?code=c0de&state=${state}`, {
      headers: { cookie: confirmed! },
    }),
    env,
  );
  const on = new URL(back.headers.get("location")!);
  expect(on.origin + on.pathname).toBe("https://iterate.ada.example/sign-in/google/callback");
  expect(Object.fromEntries(on.searchParams)).toMatchObject({ code: "c0de", state: "n" });
  // the same code, as another client's or with no press before: no sign-in goes on
  const elsewhere = await cloud.fetch(
    new Request(`${CLOUD}/clients/x/callback?code=c0de&state=${state}`),
    env,
  );
  expect(elsewhere).toMatchObject({ status: 400 });
  // and a sign-in that did not begin on the Cloud's page gets no page and no proof
  const unbegun = await cloud.fetch(
    new Request(`${CLOUD}/clients/google/callback?code=c0de-2&state=${state}`),
    env,
  );
  expect(unbegun).toMatchObject({ status: 400 });
  expect(await unbegun.text()).not.toContain("cloud_proof");

  const exchange = await ada.ask("google:token", {
    grant_type: "authorization_code",
    code: "c0de",
    code_verifier: "v3rifier",
    cloud_proof: on.searchParams.get("cloud_proof")!,
  });
  expect(exchange).toMatchObject({ status: 200 });
  // Google's own words of who signed in, and no token that reaches their account
  expect(await exchange.json()).toEqual({ id_token: "google.id.token" });
  expect(Object.fromEntries(provider.tokenRequests[0]!)).toEqual({
    grant_type: "authorization_code",
    code: "c0de",
    code_verifier: "v3rifier",
    redirect_uri: `${CLOUD}/clients/google/callback`,
    client_id: "google-client",
    client_secret: "google-secret",
  });
  // a sign-in connects nothing: no account's events go to the deployment
  const routes = env.ROUTES.get(env.ROUTES.idFromName("routes"));
  expect(await routes.clientsOf("iterate.ada.example")).toEqual({});
  // and the proof is for that deployment alone
  const eve = await deployment("iterate.eve.example");
  const stolen = await eve.ask("google:token", {
    grant_type: "authorization_code",
    code: "c0de",
    cloud_proof: on.searchParams.get("cloud_proof")!,
  });
  expect(stolen).toMatchObject({ status: 403 });
});

const GOOGLE_EMAIL = "https://www.googleapis.com/auth/userinfo.email";

test("a Google connect names what it asks for, asks Google to show its own consent, and takes nothing granted elsewhere", async () => {
  const { env } = await setup();
  const state = `${base64url(Buffer.from("https://iterate.ada.example/secrets/oauth/callback"))}.n`;
  const gmail = "https://www.googleapis.com/auth/gmail.modify";
  const to = (more = "") =>
    `${new URL(google.authorizationEndpoint).origin}${new URL(google.authorizationEndpoint).pathname}?client_id=${google.clientId}&redirect_uri=${encodeURIComponent(`${CLOUD}/clients/google/callback`)}&scope=${encodeURIComponent(`openid email ${gmail}`)}&state=${state}${more}`;
  const begin = (link: string, more = "", cookie = "") =>
    cloud.fetch(
      new Request(`${CLOUD}/clients/google/begin?to=${encodeURIComponent(link)}${more}`, {
        headers: { cookie },
      }),
      env,
    );
  // Google's "incremental authorization" would add what the person gave iterate's app through
  // ANOTHER deployment to this one's token: a deployment may not ask for it
  expect(await begin(to("&include_granted_scopes=true"))).toMatchObject({ status: 400 });
  const shown = await begin(to());
  const html = await shown.text();
  expect(html).toContain("Give <b>iterate.ada.example</b> access to your Google account?");
  // Google's own page names the scopes in words: this page lists none
  expect(html).not.toContain(gmail);
  const [cookie] = shown.headers.get("set-cookie")!.split(";");
  const go = new URL(/href="([^"]+)"/.exec(html)![1]!.replaceAll("&#38;", "&")).searchParams.get(
    "go",
  );
  const pressed = await begin(to(), `&go=${go}`, cookie);
  const onward = new URL(pressed.headers.get("location")!);
  // Google shows its consent page each time, with this request's scopes
  expect(Object.fromEntries(onward.searchParams)).toMatchObject({
    prompt: "consent",
    scope: `openid email ${gmail}`,
    state,
  });
  expect(onward.searchParams.has("include_granted_scopes")).toBe(false);
  // what the deployment asked of the prompt stays, beside the consent; `none` would skip it
  const chosen = await begin(to("&prompt=select_account%20none"));
  const [again] = chosen.headers.get("set-cookie")!.split(";");
  const press = new URL(
    /href="([^"]+)"/.exec(await chosen.text())![1]!.replaceAll("&#38;", "&"),
  ).searchParams.get("go");
  const sent = await begin(to("&prompt=select_account%20none"), `&go=${press}`, again);
  expect(new URL(sent.headers.get("location")!).searchParams.get("prompt")).toBe(
    "select_account consent",
  );

  // A GOOGLE CONSENT THAT DID NOT BEGIN HERE (worker.ts `callback`): no press, the page shown and
  // not pressed, and then the press
  const callback = (code: string, held = "") =>
    cloud.fetch(
      new Request(`${CLOUD}/clients/google/callback?code=${code}&state=${state}`, {
        headers: { cookie: held },
      }),
      env,
    );
  for (const unpressed of [await callback("g-1"), await callback("g-2", cookie)]) {
    expect(unpressed).toMatchObject({ status: 400 });
    const words = await unpressed.text();
    expect(words).toContain("Start again from iterate.ada.example");
    expect(words).not.toContain("cloud_proof");
    expect(words).not.toContain("href=");
  }
  const [confirmed] = pressed.headers.get("set-cookie")!.split(";");
  const on = await callback("g-3", confirmed);
  expect(on).toMatchObject({ status: 302 });
  // the proof carries the scopes that the page named, after the (empty) list of accounts
  const proof = new URL(on.headers.get("location")!).searchParams.get("cloud_proof")!;
  expect(proof).toMatch(/^[\w-]{43}\.\.[\w-]+$/);
  expect(Buffer.from(proof.split(".")[2]!, "base64url").toString()).toBe(`openid email ${gmail}`);
});

test("a Google token that reaches more than the page named connects nothing", async () => {
  const { env, deployment, provider } = await setup();
  const ada = await deployment("iterate.ada.example");
  const state = `${base64url(Buffer.from("https://iterate.ada.example/secrets/oauth/callback"))}.n`;
  const gmail = "https://www.googleapis.com/auth/gmail.modify";
  const drive = "https://www.googleapis.com/auth/drive";
  const link = `${google.authorizationEndpoint}&client_id=${google.clientId}&redirect_uri=${encodeURIComponent(`${CLOUD}/clients/google/callback`)}&scope=${encodeURIComponent(`openid email ${gmail}`)}&state=${state}`;
  const begin = (more = "", cookie = "") =>
    cloud.fetch(
      new Request(`${CLOUD}/clients/google/begin?to=${encodeURIComponent(link)}${more}`, {
        headers: { cookie },
      }),
      env,
    );
  const callback = (code: string, cookie: string) =>
    cloud.fetch(
      new Request(`${CLOUD}/clients/google/callback?code=${code}&state=${state}`, {
        headers: { cookie },
      }),
      env,
    );
  /** One press on the Cloud's page, and the proof of the code that came back with its cookie. */
  const proofOf = async (code: string) => {
    const shown = await begin();
    const [cookie] = shown.headers.get("set-cookie")!.split(";");
    const go = new URL(
      /href="([^"]+)"/.exec(await shown.text())![1]!.replaceAll("&#38;", "&"),
    ).searchParams.get("go");
    const [pressed] = (await begin(`&go=${go}`, cookie)).headers.get("set-cookie")!.split(";");
    const back = await callback(code, pressed!);
    return new URL(back.headers.get("location")!).searchParams.get("cloud_proof")!;
  };
  const exchange = async (code: string, proof: string) =>
    ada.ask("google:token", { grant_type: "authorization_code", code, cloud_proof: proof });

  // THE SECOND AUTHORIZATION (worker.ts `beyond` says how it comes about): a code whose token
  // reaches more than the page named.
  provider.googleScope = `openid ${GOOGLE_EMAIL} ${gmail} ${drive}`;
  const wide = await exchange("g-wide", await proofOf("g-wide"));
  expect(wide).toMatchObject({ status: 403 });
  const words = JSON.stringify(await wide.json());
  expect(words).toContain(drive);
  expect(words).not.toContain("google-access");
  expect(words).not.toContain("google-refresh");
  // Google's answer with no scopes says nothing about what the token reaches
  provider.googleScope = undefined;
  expect(await exchange("g-mute", await proofOf("g-mute"))).toMatchObject({ status: 403 });
  // the scopes in the proof are under its signature: other words there are no proof
  provider.googleScope = `openid ${GOOGLE_EMAIL} ${gmail} ${drive}`;
  const [mac, list] = (await proofOf("g-forged")).split(".");
  const forged = `${mac}.${list}.${base64url(Buffer.from(`openid email ${gmail} ${drive}`))}`;
  expect(await exchange("g-forged", forged)).toMatchObject({ status: 403 });

  // what the page named, in Google's own spelling of `email`, or less of it: the token goes on
  provider.googleScope = `${gmail} ${GOOGLE_EMAIL} openid`;
  const exact = await exchange("g-exact", await proofOf("g-exact"));
  expect(exact).toMatchObject({ status: 200 });
  expect(await exact.json()).toMatchObject({ access_token: "google-access" });
  provider.googleScope = "openid";
  expect(await exchange("g-less", await proofOf("g-less"))).toMatchObject({ status: 200 });
});

test("Google's own words for the default scopes connect: the same five in Google's order", async () => {
  const { env, deployment, provider } = await setup();
  const ada = await deployment("iterate.ada.example");
  const state = `${base64url(Buffer.from("https://iterate.ada.example/secrets/oauth/callback"))}.n`;
  // the production client's default scopes, in the order a deployment asks them
  // (scripts/production-clients.ts)
  const asked = [
    "openid",
    "https://www.googleapis.com/auth/userinfo.email",
    "https://www.googleapis.com/auth/gmail.modify",
    "https://www.googleapis.com/auth/gmail.send",
    "https://www.googleapis.com/auth/gmail.labels",
  ].join(" ");
  // `scope` in Google's token answer to that consent: Google sorts the words and adds none
  const answered = [
    "https://www.googleapis.com/auth/gmail.labels",
    "https://www.googleapis.com/auth/gmail.modify",
    "https://www.googleapis.com/auth/gmail.send",
    "https://www.googleapis.com/auth/userinfo.email",
    "openid",
  ].join(" ");
  const link = `${google.authorizationEndpoint}&client_id=${google.clientId}&redirect_uri=${encodeURIComponent(`${CLOUD}/clients/google/callback`)}&scope=${encodeURIComponent(asked)}&state=${state}`;
  const begin = (more = "", cookie = "") =>
    cloud.fetch(
      new Request(`${CLOUD}/clients/google/begin?to=${encodeURIComponent(link)}${more}`, {
        headers: { cookie },
      }),
      env,
    );
  const shown = await begin();
  const [cookie] = shown.headers.get("set-cookie")!.split(";");
  const go = new URL(
    /href="([^"]+)"/.exec(await shown.text())![1]!.replaceAll("&#38;", "&"),
  ).searchParams.get("go");
  const [pressed] = (await begin(`&go=${go}`, cookie)).headers.get("set-cookie")!.split(";");
  const back = await cloud.fetch(
    new Request(`${CLOUD}/clients/google/callback?code=g-real&state=${state}`, {
      headers: { cookie: pressed! },
    }),
    env,
  );
  const proof = new URL(back.headers.get("location")!).searchParams.get("cloud_proof")!;
  expect(Buffer.from(proof.split(".")[2]!, "base64url").toString()).toBe(asked);

  provider.googleScope = answered;
  const exchange = await ada.ask("google:token", {
    grant_type: "authorization_code",
    code: "g-real",
    cloud_proof: proof,
  });
  expect(exchange).toMatchObject({ status: 200 });
  expect(await exchange.json()).toMatchObject({ access_token: "google-access" });
});

test("Gmail's push for a mailbox reaches each deployment that connected it, signed by the Cloud's key, and no other", async () => {
  const { env, cloudKey, deployment, provider, proofFor } = await setup();
  // the topic a deployment names in `users.watch`: the mailbox's watch is the deployment's call
  const facts = (await (await cloud.fetch(get("/.well-known/iterate-cloud"), env)).json()) as any;
  expect(facts.clients.google).toMatchObject({ gmailTopic: GMAIL_PUSH.topic });
  expect(facts.clients.github).not.toHaveProperty("gmailTopic");

  provider.googleScope = "openid";
  const connect = async (mind: string) => {
    const at = await deployment(mind);
    const answer = await at.ask("google:token", {
      grant_type: "authorization_code",
      code: `g-${mind}`,
      cloud_proof: await proofFor(mind, `g-${mind}`, "google"),
    });
    expect(answer).toMatchObject({ status: 200 });
    return at;
  };
  // two deployments connect ada's mailbox, which Gmail spells its own way; a third connects bob's
  const ada = await connect("iterate.ada.example");
  const household = await connect("iterate.household.example");
  provider.gmailAddress = "bob@example.com";
  const bob = await connect("iterate.bob.example");
  const delivered = async () => {
    await handedOver(env, "google");
    for (const mind of ["iterate.ada.example", "iterate.household.example", "iterate.bob.example"])
      await (env.OUTBOX.get(env.OUTBOX.idFromName(mind)) as unknown as Outbox).alarm();
  };

  // each deployment was told which mailbox it connected, which is another test's matter
  await delivered();
  for (const each of [ada, household, bob]) each.statements.length = 0;

  // Gmail's notification names the mailbox and its newest history id, a number
  const token = await pushTokenOf();
  const pushed = await gmailPush(env, { emailAddress: "ada@example.com", historyId: 4242 }, "m-1", {
    authorization: `Bearer ${token}`,
  });
  expect([pushed.status, await pushed.json()]).toEqual([200, { accepted: true }]);
  await delivered();
  expect([ada, household, bob].map((each) => each.statements.length)).toEqual([1, 1, 0]);
  for (const [mind, at] of [
    ["iterate.ada.example", ada],
    ["iterate.household.example", household],
  ] as const)
    expect(await statementOf(at.statements[0]!, cloudKey.publicKey)).toMatchObject({
      mind,
      path: "/integrations/google/ada@example.com",
      type: "events.iterate.com/google/gmail-push-received",
      payload: {
        emailAddress: "ada@example.com",
        historyId: "4242",
        messageId: "m-1",
        publishTime: "2026-11-12T22:00:00.000Z",
      },
    });
  // the push carried Pub/Sub's token, which goes to no deployment: not whole, nor any of its parts
  for (const part of token.split(".")) expect(JSON.stringify(ada.statements)).not.toContain(part);

  // Pub/Sub sends a message again when its answer was lost: it is relayed once
  const again = await gmailPush(env, { emailAddress: "ada@example.com", historyId: 4242 }, "m-1");
  expect(await again.json()).toEqual({ accepted: true, redelivery: true });
  // a mailbox nobody connected: answered, so that Pub/Sub does not send it for ever, and nobody's
  const nobodys = await gmailPush(env, { emailAddress: "eve@example.com", historyId: 7 }, "m-2");
  expect(await nobodys.json()).toEqual({ accepted: true });
  await delivered();
  expect([ada, household, bob].map((each) => each.statements.length)).toEqual([1, 1, 0]);
  // Gmail's own spelling of the address in a push is read as the route has it
  await gmailPush(env, { emailAddress: "Bob@Example.com", historyId: "9" }, "m-3");
  await delivered();
  expect([ada, household, bob].map((each) => each.statements.length)).toEqual([1, 1, 1]);
  expect(await statementOf(bob.statements[0]!, cloudKey.publicKey)).toMatchObject({
    path: "/integrations/google/bob@example.com",
    payload: { emailAddress: "bob@example.com", historyId: "9" },
  });
});

test("a push is Gmail's only with the token of the Cloud's own subscription, and a mailbox is routed only for a grant that reads it", async () => {
  const { env, deployment, provider, proofFor } = await setup();
  provider.googleScope = "openid";
  /** One more Google account connected at `mind`, with a code of its own. */
  const connect = async (mind: string, at?: Awaited<ReturnType<typeof deployment>>) => {
    const code = `g-${mind}-${at ? "again" : "first"}`;
    return (at || (await deployment(mind))).ask("google:token", {
      grant_type: "authorization_code",
      code,
      cloud_proof: await proofFor(mind, code, "google"),
    });
  };
  const ada = await deployment("iterate.ada.example");
  expect(await connect("iterate.ada.example", ada)).toMatchObject({ status: 200 });
  const inbox = env.OUTBOX.get(env.OUTBOX.idFromName("inbox\ngoogle")) as unknown as Outbox;
  const notification = { emailAddress: "ada@example.com", historyId: 1 };

  // NOT THE SUBSCRIPTION'S (worker.ts `gmailPushed` says why each must be refused): no token,
  // another audience, another service account, an address Google did not verify, a token past
  // its time, another issuer, and one that another key signed.
  const { privateKey: other } = await generateKeyPair("RS256");
  const past = Math.floor(Date.now() / 1000) - 60;
  const refused = [
    {},
    ...[
      await pushTokenOf({ aud: "https://elsewhere.example/clients/google/webhook" }),
      await pushTokenOf({ email: "push@another-project.iam.gserviceaccount.com" }),
      await pushTokenOf({ email_verified: false }),
      await pushTokenOf({ iat: past - 3600, exp: past }),
      await pushTokenOf({ iss: "https://issuer.example" }),
      await pushTokenOf({}, other),
    ].map((token) => ({ authorization: `Bearer ${token}` })),
  ];
  for (const [index, sent] of refused.entries())
    expect(await gmailPush(env, notification, `refused-${index}`, sent)).toMatchObject({
      status: 401,
    });
  expect(await held(inbox)).toBe(0);
  // the subscription's own, and no Gmail notification: answered, or Pub/Sub sends it for ever
  for (const [index, data] of [
    {},
    { emailAddress: "ada@example.com" },
    "not base64 JSON",
  ].entries()) {
    const answer = await gmailPush(env, data, `empty-${index}`);
    expect([answer.status, await answer.json()]).toEqual([200, { accepted: false }]);
  }
  expect(await held(inbox)).toBe(0);
  expect(await (await gmailPush(env, notification, "m-1")).json()).toEqual({ accepted: true });
  expect(await held(inbox)).toBe(1);

  const routes = env.ROUTES.get(env.ROUTES.idFromName("routes")) as unknown as Routes;
  expect(await routes.mindsOf("google", "ada@example.com")).toEqual(["iterate.ada.example"]);
  // a grant that reads no mail makes no route, and its exchange goes on (worker.ts `reachedBy`)
  provider.gmailAddress = undefined;
  expect(await connect("iterate.grace.example")).toMatchObject({ status: 200 });
  expect(await routes.clientsOf("iterate.grace.example")).toEqual({});
  // such a grant beside one that reads mail, in the same deployment, takes no route away
  expect(await connect("iterate.ada.example", ada)).toMatchObject({ status: 200 });
  expect(await routes.mindsOf("google", "ada@example.com")).toEqual(["iterate.ada.example"]);
  // Gmail cannot be reached after Google answered the code: the tokens still go back
  provider.gmailAddress = "unreachable";
  expect(await connect("iterate.heidi.example")).toMatchObject({ status: 200 });
  expect(await routes.clientsOf("iterate.heidi.example")).toEqual({});
  // an address is one segment of the path a deployment gets its events on: no other is routed,
  // and none with a character that no Google address has
  for (const [index, odd] of ["eve/../../secrets@example.com", "eve%2fx@example.com"].entries()) {
    provider.gmailAddress = odd;
    expect(await connect(`iterate.eve-${index}.example`)).toMatchObject({ status: 200 });
    expect(await routes.clientsOf(`iterate.eve-${index}.example`)).toEqual({});
  }

  // a client whose push is not wholly named, or not at all, takes none and publishes no topic
  // (worker.ts `gmailPushOf`)
  const anyAudience = await pushTokenOf({ aud: "https://elsewhere.example" });
  const noAddress = await pushTokenOf({ email: undefined });
  for (const halfNamed of [
    { ...GMAIL_PUSH, audience: "" },
    { ...GMAIL_PUSH, serviceAccount: undefined },
    { ...GMAIL_PUSH, topic: "" },
    undefined,
  ]) {
    const bare = await setup();
    bare.env.CLOUD_CLIENTS = JSON.stringify({ google: { ...google, gmailPush: halfNamed } });
    for (const token of [anyAudience, noAddress, await pushTokenOf()])
      expect(
        await gmailPush(bare.env, notification, "m-1", { authorization: `Bearer ${token}` }),
      ).toMatchObject({ status: 404 });
    const facts = await (await cloud.fetch(get("/.well-known/iterate-cloud"), bare.env)).json();
    expect((facts as any).clients.google).not.toHaveProperty("gmailTopic");
  }
});

test("a deployment that connects a mailbox is told which one, and the topic to watch it with", async () => {
  const { env, cloudKey, deployment, provider, proofFor } = await setup();
  provider.googleScope = "openid";
  const ada = await deployment("iterate.ada.example");
  // in this test a namespace answers the object itself, not a stub (namespaceOf)
  const outbox = env.OUTBOX.get(env.OUTBOX.idFromName("iterate.ada.example")) as unknown as Outbox;
  let codes = 0;
  /** One more connect at ada's deployment; answers its sealed refresh token. */
  const connect = async () => {
    const code = `g-${(codes += 1)}`;
    const answer = await ada.ask("google:token", {
      grant_type: "authorization_code",
      code,
      cloud_proof: await proofFor("iterate.ada.example", code, "google"),
    });
    return ((await answer.json()) as { refresh_token: string }).refresh_token;
  };
  const refresh = (sealed: string) =>
    ada.ask("google:token", { grant_type: "refresh_token", refresh_token: sealed });
  /** How many statements the deployment has taken by now. */
  const told = async () => {
    await outbox.alarm();
    return ada.statements.length;
  };

  const sealed = await connect();
  expect(await told()).toBe(1);
  expect(await statementOf(ada.statements[0]!, cloudKey.publicKey)).toMatchObject({
    mind: "iterate.ada.example",
    path: "/integrations/google/ada@example.com",
    type: "events.iterate.com/google/gmail-connected",
    payload: { emailAddress: "ada@example.com", topic: GMAIL_PUSH.topic, api: PROVIDER },
  });
  // a refresh of a grant whose mailbox is routed already says nothing: the deployment was told
  expect(await refresh(sealed)).toMatchObject({ status: 200 });
  expect(await told()).toBe(1);
  // every connect tells: the person may have connected the mailbox into another secret
  await connect();
  expect(await told()).toBe(2);
  // a statement that waits out its day untaken is told again at the next refresh (worker.ts
  // `toldOnce`)
  const connectedAt = Date.now();
  vi.useFakeTimers({ toFake: ["Date"] });
  try {
    ada.down = true;
    await connect();
    expect(await told()).toBe(2);
    vi.setSystemTime(connectedAt + 25 * 60 * 60_000);
    expect(await told()).toBe(2);
    expect(await held(outbox)).toBe(0);
    ada.down = false;
    expect(await refresh(sealed)).toMatchObject({ status: 200 });
    expect(await told()).toBe(3);
    // and that refresh's word was taken: the next refresh says nothing
    expect(await refresh(sealed)).toMatchObject({ status: 200 });
    expect(await told()).toBe(3);
  } finally {
    vi.useRealTimers();
  }

  // a grant that reads no mail connected no mailbox
  provider.gmailAddress = undefined;
  await connect();
  expect(await told()).toBe(3);
  // and a client that takes no push names no topic to watch with: nothing is told
  provider.gmailAddress = "ada@example.com";
  env.CLOUD_CLIENTS = JSON.stringify({ google: { ...google, gmailPush: undefined } });
  const bare = await setup();
  bare.env.CLOUD_CLIENTS = env.CLOUD_CLIENTS;
  bare.provider.googleScope = "openid";
  const grace = await bare.deployment("iterate.grace.example");
  await grace.ask("google:token", {
    grant_type: "authorization_code",
    code: "g-bare",
    cloud_proof: await bare.proofFor("iterate.grace.example", "g-bare", "google"),
  });
  await (
    bare.env.OUTBOX.get(bare.env.OUTBOX.idFromName("iterate.grace.example")) as unknown as Outbox
  ).alarm();
  expect(grace.statements).toHaveLength(0);
});

test("a deployment that connects a Google calendar gets a channel token of its own, and a push with that token reaches it alone", async () => {
  const { env, cloudKey, deployment, provider, proofFor } = await setup();
  const calendar = "https://www.googleapis.com/auth/calendar";
  // a grant for the calendar alone: it reads no mail, and gets no mailbox's route
  provider.googleScope = `openid ${calendar}`;
  provider.gmailAddress = undefined;
  let codes = 0;
  type Deployed = Awaited<ReturnType<typeof deployment>>;
  /** One more connect at `at`; answers its sealed refresh token. */
  const connect = async (mind: string, at: Deployed, scope = calendar) => {
    const code = `g-${(codes += 1)}`;
    const answer = await at.ask("google:token", {
      grant_type: "authorization_code",
      code,
      cloud_proof: await proofFor(mind, code, "google", "", "", scope),
    });
    expect(answer).toMatchObject({ status: 200 });
    return ((await answer.json()) as { refresh_token: string }).refresh_token;
  };
  /** The statements `at` has taken by now, as the Cloud's key signed them. */
  const taken = async (mind: string, at: Deployed) => {
    await (env.OUTBOX.get(env.OUTBOX.idFromName(mind)) as unknown as Outbox).alarm();
    return Promise.all(at.statements.map((signed) => statementOf(signed, cloudKey.publicKey)));
  };
  /** Google's push on a channel: headers alone, no body, no signature. */
  const push = (token: string, number = "10", state = "exists") =>
    cloud.fetch(
      new Request(`${CLOUD}/clients/google/calendar-webhook`, {
        method: "POST",
        headers: {
          "x-goog-channel-id": "channel-1",
          "x-goog-resource-id": "resource-1",
          "x-goog-resource-state": state,
          "x-goog-message-number": number,
          "x-goog-channel-token": token,
        },
      }),
      env,
    );

  const ada = await deployment("iterate.ada.example");
  const sealed = await connect("iterate.ada.example", ada);
  const [told] = await taken("iterate.ada.example", ada);
  expect(told).toMatchObject({
    mind: "iterate.ada.example",
    path: "/integrations/google/ada@example.com",
    type: "events.iterate.com/google/calendar-connected",
    payload: {
      emailAddress: "ada@example.com",
      api: PROVIDER,
      address: `${CLOUD}/clients/google/calendar-webhook`,
      token: expect.stringMatching(/^[\w-]{22}\.[\w-]{43}$/),
    },
  });
  const { token } = told!.payload as { token: string };
  // a second deployment that connects the same calendar gets a token of its own
  const household = await deployment("iterate.household.example");
  await connect("iterate.household.example", household);
  const [theirs] = await taken("iterate.household.example", household);
  expect(theirs!.payload).not.toMatchObject({ token });

  // A PUSH WITH ADA'S TOKEN reaches ada's deployment, and no other that connected the calendar
  const pushed = await push(token);
  expect([pushed.status, await pushed.json()]).toEqual([200, { accepted: true }]);
  expect((await taken("iterate.ada.example", ada)).at(-1)).toMatchObject({
    path: "/integrations/google/ada@example.com",
    type: "events.iterate.com/google/calendar-push-received",
    payload: {
      channelId: "channel-1",
      resourceId: "resource-1",
      resourceState: "exists",
      messageNumber: "10",
    },
  });
  expect(await taken("iterate.household.example", household)).toHaveLength(1);
  // the same message of the channel again is relayed once; its next message is relayed
  expect(await (await push(token)).json()).toEqual({ accepted: true, redelivery: true });
  await push(token, "11");
  expect(await taken("iterate.ada.example", ada)).toHaveLength(3);
  // THE TOKEN IS THE PUSH'S ONLY PROOF: Google signs nothing here. None, or one the Cloud did
  // not make, reaches nobody.
  // nor does the id of a real token with another second half, which no row is read for
  for (const other of ["", "A".repeat(43), `${token}x`, `${token.slice(0, 23)}${"A".repeat(43)}`])
    expect(await push(other, "12")).toMatchObject({ status: 404 });
  expect(await taken("iterate.ada.example", ada)).toHaveLength(3);

  // a push names its channel and its message, at a length Google's own have
  const long = await cloud.fetch(
    new Request(`${CLOUD}/clients/google/calendar-webhook`, {
      method: "POST",
      headers: {
        "x-goog-channel-id": "c".repeat(300),
        "x-goog-resource-id": "r".repeat(300),
        "x-goog-resource-state": "s".repeat(300),
        "x-goog-message-number": "13",
        "x-goog-channel-token": token,
      },
    }),
    env,
  );
  expect(long).toMatchObject({ status: 200 });
  expect((await taken("iterate.ada.example", ada)).at(-1)!).toMatchObject({
    payload: {
      channelId: "c".repeat(64),
      resourceId: "r".repeat(256),
      resourceState: "s".repeat(32),
      messageNumber: "13",
    },
  });

  const refresh = () =>
    ada.ask("google:token", { grant_type: "refresh_token", refresh_token: sealed });
  const connectedAt = Date.now();
  const DAY = 24 * 60 * 60_000;
  vi.useFakeTimers({ toFake: ["Date"] });
  try {
    // a refresh keeps the token and says nothing
    vi.setSystemTime(connectedAt + 1000);
    expect(await refresh()).toMatchObject({ status: 200 });
    expect(await taken("iterate.ada.example", ada)).toHaveLength(4);
    // a new connect replaces the token, and the one before is good for a day more (worker.ts
    // `calendarConnected`)
    vi.setSystemTime(connectedAt + 2000);
    await connect("iterate.ada.example", ada);
    const replaced = (await taken("iterate.ada.example", ada)).at(-1)!;
    expect(replaced).toMatchObject({ type: "events.iterate.com/google/calendar-connected" });
    const { token: next } = replaced.payload as { token: string };
    expect(next).toMatch(/^[\w-]{22}\.[\w-]{43}$/);
    expect(next).not.toBe(token);
    expect(await push(token, "14")).toMatchObject({ status: 200 });
    expect(await push(next, "14")).toMatchObject({ status: 200 });
    vi.setSystemTime(connectedAt + 2000 + DAY + 1000);
    expect(await push(token, "15")).toMatchObject({ status: 404 });
    expect(await push(next, "15")).toMatchObject({ status: 200 });
    // a refresh does not bring the old token back
    expect(await refresh()).toMatchObject({ status: 200 });
    expect(await push(token, "16")).toMatchObject({ status: 404 });

    // THE TOKEN LASTS WHILE THE GRANT REFRESHES: a week with no refresh, and its pushes reach
    // nobody; the next refresh makes a new token, and tells
    const told = (await taken("iterate.ada.example", ada)).length;
    vi.setSystemTime(connectedAt + 10 * DAY);
    expect(await push(next, "20")).toMatchObject({ status: 404 });
    expect(await refresh()).toMatchObject({ status: 200 });
    const statements = await taken("iterate.ada.example", ada);
    expect(statements).toHaveLength(told + 1);
    const { token: third } = statements.at(-1)!.payload as { token: string };
    expect([third === next, third === token]).toEqual([false, false]);
    expect(await push(third, "21")).toMatchObject({ status: 200 });
    expect(await push(next, "21")).toMatchObject({ status: 404 });
    // THE CLOUD LETS GO OF THE ACCOUNT for this deployment: its token reaches nobody at once
    const routes = env.ROUTES.get(env.ROUTES.idFromName("routes")) as unknown as Routes;
    await routes.letGo("google", "iterate.ada.example", "ada@example.com", false);
    expect(await push(third, "22")).toMatchObject({ status: 404 });
  } finally {
    vi.useRealTimers();
  }

  // a grant with no calendar scope connected no calendar
  provider.googleScope = "openid";
  const grace = await deployment("iterate.grace.example");
  await connect("iterate.grace.example", grace, "");
  expect(await taken("iterate.grace.example", grace)).toEqual([]);
  // and another client's app has no such address
  expect(
    await cloud.fetch(
      new Request(`${CLOUD}/clients/github/calendar-webhook`, {
        method: "POST",
        headers: { "x-goog-channel-token": token },
      }),
      env,
    ),
  ).toMatchObject({ status: 404 });
});

test("a calendar the Cloud let go of gets no push on any of its tokens, and no refresh brings one back; a push not told is tried again", async () => {
  const { env, cloudKey, deployment, provider, proofFor } = await setup();
  const calendar = "https://www.googleapis.com/auth/calendar";
  provider.googleScope = `openid ${calendar}`;
  provider.gmailAddress = undefined;
  const ada = await deployment("iterate.ada.example");
  const outbox = env.OUTBOX.get(env.OUTBOX.idFromName("iterate.ada.example")) as unknown as Outbox;
  let codes = 0;
  const connect = async () => {
    const code = `g-${(codes += 1)}`;
    const answer = await ada.ask("google:token", {
      grant_type: "authorization_code",
      code,
      cloud_proof: await proofFor("iterate.ada.example", code, "google", "", "", calendar),
    });
    return ((await answer.json()) as { refresh_token: string }).refresh_token;
  };
  const tokens = async () => {
    await outbox.alarm();
    const said = await Promise.all(
      ada.statements.map((signed) => statementOf(signed, cloudKey.publicKey)),
    );
    return said
      .filter((each) => each?.type === "events.iterate.com/google/calendar-connected")
      .map((each) => (each!.payload as { token: string }).token);
  };
  const push = (token: string, number: string) =>
    cloud.fetch(
      new Request(`${CLOUD}/clients/google/calendar-webhook`, {
        method: "POST",
        headers: {
          "x-goog-channel-id": "channel-1",
          "x-goog-resource-id": "resource-1",
          "x-goog-resource-state": "exists",
          "x-goog-message-number": number,
          "x-goog-channel-token": token,
        },
      }),
      env,
    );

  // A PUSH THE CLOUD COULD NOT TELL is not taken as seen: Google's retry of it is told
  await connect();
  const [first] = await tokens();
  vi.spyOn(outbox, "put").mockRejectedValueOnce(new Error("the outbox is down"));
  expect(await push(first!, "5")).toMatchObject({ status: 503 });
  expect(await (await push(first!, "5")).json()).toEqual({ accepted: true });

  // two connects: the first token is good for a day more beside the second
  const sealed = await connect();
  const [, second] = await tokens();
  expect(await push(first!, "6")).toMatchObject({ status: 200 });
  // THE DEPLOYMENT LETS GO: neither token reaches it, and its next refresh makes none
  const routes = env.ROUTES.get(env.ROUTES.idFromName("routes")) as unknown as Routes;
  await routes.letGo("google", "iterate.ada.example", "ada@example.com", false);
  for (const token of [first!, second!])
    expect(await push(token, "7")).toMatchObject({ status: 404 });
  expect(
    await ada.ask("google:token", { grant_type: "refresh_token", refresh_token: sealed }),
  ).toMatchObject({ status: 200 });
  expect(await tokens()).toHaveLength(2);
  expect(await push(second!, "8")).toMatchObject({ status: 404 });
  // until the deployment says it wants the calendar again, and connects
  await routes.letGo("google", "iterate.ada.example", "ada@example.com", true);
  await connect();
  const all = await tokens();
  expect(all).toHaveLength(3);
  expect(await push(all[2]!, "9")).toMatchObject({ status: 200 });
});

test("a statement that is dropped untaken holds back none behind it while the routes object fails", async () => {
  const { env, deployment, provider, proofFor } = await setup();
  provider.googleScope = "openid";
  const ada = await deployment("iterate.ada.example");
  ada.down = true;
  for (const code of ["g-1", "g-2"])
    await ada.ask("google:token", {
      grant_type: "authorization_code",
      code,
      cloud_proof: await proofFor("iterate.ada.example", code, "google"),
    });
  // in this test a namespace answers the object itself, not a stub (namespaceOf)
  const outbox = env.OUTBOX.get(env.OUTBOX.idFromName("iterate.ada.example")) as unknown as Outbox;
  const routes = env.ROUTES.get(env.ROUTES.idFromName("routes")) as unknown as Routes;
  expect(await held(outbox)).toBe(2);
  vi.spyOn(routes, "forget").mockRejectedValue(new Error("the routes object is down"));
  const connectedAt = Date.now();
  vi.useFakeTimers({ toFake: ["Date"] });
  try {
    vi.setSystemTime(connectedAt + 25 * 60 * 60_000);
    await outbox.alarm();
    expect(await held(outbox)).toBe(0);
  } finally {
    vi.useRealTimers();
  }
});

test("a code exchange: the Cloud adds the client secret, seals the refresh token to the deployment, and records what the token reaches", async () => {
  const { env, deployment, provider, proofFor } = await setup();
  const ada = await deployment("iterate.ada.example");
  const exchange = await ada.ask("token", {
    grant_type: "authorization_code",
    code: "c0de",
    code_verifier: "v3rifier",
    redirect_uri: "whatever the vault says: the Cloud names its own",
    cloud_proof: await proofFor("iterate.ada.example", "c0de"),
  });
  expect(exchange).toMatchObject({ status: 200 });
  const tokens = (await exchange.json()) as any;
  expect(tokens).toMatchObject({
    access_token: "access-1",
    refresh_token: expect.stringMatching(/^sealed\./),
  });
  expect(tokens.refresh_token).not.toContain("refresh-1");
  expect(Object.fromEntries(provider.tokenRequests[0]!)).toEqual({
    grant_type: "authorization_code",
    code: "c0de",
    code_verifier: "v3rifier",
    redirect_uri: `${CLOUD}/clients/github/callback`,
    client_id: "Iv1.client",
    client_secret: "client-secret",
  });
  // the installations ada administers are hers to connect: her own, and an organization she owns.
  // One she can merely see, as a member or on another person's account, is not.
  const routes = env.ROUTES.get(env.ROUTES.idFromName("routes"));
  expect(
    await Promise.all(["7", "8", "9", "10"].map((id) => routes.mindsOf("github", id))),
  ).toEqual([["iterate.ada.example"], ["iterate.ada.example"], [], []]);
  // read the other way, for the Cloud's page of a person's deployments: what delivers to one
  expect(await routes.clientsOf("iterate.ada.example")).toEqual({ github: 2 });
  expect(await routes.clientsOf("iterate.someone-else.example")).toEqual({});

  // the refresh: the deployment's own sealed token, opened here
  const refresh = await ada.ask("token", {
    grant_type: "refresh_token",
    refresh_token: tokens.refresh_token,
  });
  const refreshed = (await refresh.json()) as { refresh_token: string };
  expect(refreshed).toMatchObject({ access_token: "access-2" });
  expect(provider.tokenRequests[1]!.get("refresh_token")).toBe("refresh-1");

  // another deployment holds ada's sealed token, or a code the Cloud sent to ada: neither works
  const eve = await deployment("iterate.eve.example");
  const stolen = await eve.ask("token", {
    grant_type: "refresh_token",
    refresh_token: tokens.refresh_token,
  });
  expect([stolen.status, await stolen.json()]).toEqual([
    403,
    { error: "this refresh token is not this deployment's" },
  ]);
  const hijacked = await eve.ask("token", {
    grant_type: "authorization_code",
    code: "c0de",
    cloud_proof: await proofFor("iterate.ada.example", "c0de"),
  });
  expect(hijacked).toMatchObject({ status: 403 });
  expect(provider.tokenRequests).toHaveLength(2);

  // ada stops being an owner of the organization: its installation leaves with her next refresh,
  // and her own account's stays
  provider.ownsOrganization = false;
  const later = (await (
    await ada.ask("token", { grant_type: "refresh_token", refresh_token: refreshed.refresh_token })
  ).json()) as { refresh_token: string };
  expect(await Promise.all(["7", "8"].map((id) => routes.mindsOf("github", id)))).toEqual([
    ["iterate.ada.example"],
    [],
  ]);
  // GitHub is busy (429): that says nothing about her grant, so what she connected stays
  provider.busy = true;
  const busyRefresh = await ada.ask("token", {
    grant_type: "refresh_token",
    refresh_token: later.refresh_token,
  });
  expect(busyRefresh).toMatchObject({ status: 429 });
  expect(await routes.mindsOf("github", "7")).toEqual(["iterate.ada.example"]);
  provider.busy = false;
  // GitHub refuses her refresh once: nothing ends on one refusal (the test below)
  provider.refreshes = false;
  const refusedRefresh = await ada.ask("token", {
    grant_type: "refresh_token",
    refresh_token: later.refresh_token,
  });
  expect(await refusedRefresh.json()).toEqual({ error: "bad_refresh_token" });
  expect(await routes.mindsOf("github", "7")).toEqual(["iterate.ada.example"]);

  // WHAT THE PERSON AGREED TO is all the deployment gets. cy names one organization and gets its
  // installation alone, at the connect and at each refresh. dee names none and gets none. fay
  // chose an installation on GitHub's own page, and gets that one.
  Object.assign(provider, { refreshes: true, ownsOrganization: true });
  const connectedBy = async (mind: string, beside: string, accounts: string) => {
    const one = await deployment(mind);
    const answered = await one.ask("token", {
      grant_type: "authorization_code",
      code: `code-${mind}`,
      cloud_proof: await proofFor(mind, `code-${mind}`, "github", beside, accounts),
    });
    const sealed = ((await answered.json()) as { refresh_token: string }).refresh_token;
    await one.ask("token", { grant_type: "refresh_token", refresh_token: sealed });
    return Promise.all(
      ["7", "8", "9", "10"].map(async (id) => (await routes.mindsOf("github", id)).includes(mind)),
    );
  };
  expect([
    await connectedBy("iterate.cy.example", "", "Owned,bob"),
    await connectedBy("iterate.dee.example", "", ""),
    await connectedBy("iterate.fay.example", "&installation_id=7&setup_action=install", ""),
  ]).toEqual([
    [false, true, false, false],
    [false, false, false, false],
    [true, false, false, false],
  ]);
  // a proof is for the accounts it was made with: with others, the Cloud did not send this code
  const forged = await proofFor("iterate.ada.example", "c0de-9", "github", "", "owned");
  const widened = `${forged.split(".")[0]}.${base64url(Buffer.from("ada,owned"))}`;
  expect(
    await ada.ask("token", {
      grant_type: "authorization_code",
      code: "c0de-9",
      cloud_proof: widened,
    }),
  ).toMatchObject({ status: 403 });
});

test("a refresh's lost answer is kept for the retry, and one refused refresh ends nothing", async () => {
  const { env, deployment, provider, proofFor } = await setup();
  const ada = await deployment("iterate.ada.example");
  // in this test a namespace answers the object itself, not a stub (namespaceOf)
  const routes = env.ROUTES.get(env.ROUTES.idFromName("routes")) as unknown as Routes;
  const { storage } = (routes as unknown as { ctx: DurableObjectState }).ctx;
  const refresh = (sealed: string) =>
    ada.ask("token", { grant_type: "refresh_token", refresh_token: sealed });
  type Tokens = { access_token: string; refresh_token: string; expires_in: number };
  const tokensOf = async (answer: Response) => (await answer.json()) as Tokens;
  const connected = await tokensOf(
    await ada.ask("token", {
      grant_type: "authorization_code",
      code: "c0de",
      cloud_proof: await proofFor("iterate.ada.example", "c0de"),
    }),
  );
  const keptAnswers = async () => [...(await storage.list({ prefix: "once\nanswer\n" })).values()];
  const HOUR = 60 * 60_000;
  const start = Date.now();
  vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout"] });
  vi.setSystemTime(start);
  try {
    // THE ANSWER IS LOST on its way to the deployment: GitHub spent refresh-1 for it
    const lost = await tokensOf(await refresh(connected.refresh_token));
    expect(lost).toMatchObject({ access_token: "access-2", expires_in: 28_800 });
    // what the Cloud keeps of it opens with the spent token alone: no token is readable in the row
    expect(await keptAnswers()).toHaveLength(1);
    expect(JSON.stringify(await keptAnswers())).not.toMatch(/access-2|refresh-2/);

    // THE RETRY shows the same token an hour later: it gets that answer, GitHub's token endpoint
    // is not asked again, and the claim is made again as a new answer makes it
    vi.setSystemTime(start + HOUR);
    const retried = await tokensOf(await refresh(connected.refresh_token));
    expect(retried).toMatchObject({
      access_token: "access-2",
      refresh_token: expect.stringMatching(/^sealed\./),
      expires_in: 28_800 - 3_600,
    });
    expect(provider.tokenRequests).toHaveLength(2);
    expect(await storage.get("claim\ngithub\n1\niterate.ada.example\n7")).toBe(start + HOUR);

    // THE NEW TOKEN IS SHOWN: the deployment stored the answer, so its kept copy goes. The spent
    // token is then GitHub's to refuse.
    const next = await tokensOf(await refresh(retried.refresh_token));
    expect(next).toMatchObject({ access_token: "access-3" });
    expect(provider.tokenRequests[2]!.get("refresh_token")).toBe("refresh-2");
    expect(await keptAnswers()).toHaveLength(1);
    await refresh(connected.refresh_token);
    expect(provider.tokenRequests[3]!.get("refresh_token")).toBe("refresh-1");

    // TWO DAYS: a kept answer lasts no longer
    vi.setSystemTime(start + 50 * HOUR);
    await refresh(retried.refresh_token);
    expect(provider.tokenRequests[4]!.get("refresh_token")).toBe("refresh-2");

    // NO ANSWER FROM THE PROVIDER: the Cloud says so, and nothing ends. A code is not a token
    // to show again.
    provider.unreachable = true;
    const unreached = await refresh(next.refresh_token);
    expect([unreached.status, await unreached.json()]).toEqual([
      502,
      { error: "no answer from the provider: ask again with the same token" },
    ]);
    const unexchanged = await ada.ask("token", {
      grant_type: "authorization_code",
      code: "c0de-2",
      cloud_proof: await proofFor("iterate.ada.example", "c0de-2"),
    });
    expect([unexchanged.status, await unexchanged.json()]).toEqual([
      502,
      { error: "no answer from the provider: connect again" },
    ]);
    provider.unreachable = false;
    expect(provider.tokenRequests).toHaveLength(5);

    // NONE IN 20 SECONDS: the Cloud says so and goes on waiting. GitHub's answer comes a second
    // later, and GitHub spent the token for it: it is kept as any other, and the retry gets it.
    const reached = Promise.withResolvers<void>();
    const answers = Promise.withResolvers<void>();
    provider.slow = { reached: reached.resolve, answers: answers.promise };
    const asking = refresh(next.refresh_token);
    await reached.promise;
    await vi.advanceTimersByTimeAsync(20_000);
    const late = await asking;
    expect([late.status, await late.json()]).toEqual([
      504,
      { error: "no answer from the provider in 20 seconds: ask again with the same token" },
    ]);
    provider.slow = undefined;
    const keptBefore = (await keptAnswers()).length;
    answers.resolve();
    await Promise.all(waited.splice(0));
    expect(await keptAnswers()).toHaveLength(keptBefore + 1);
    const found = await tokensOf(await refresh(next.refresh_token));
    expect(found).toMatchObject({ access_token: "access-6" });
    expect(provider.tokenRequests).toHaveLength(6);

    // ONE REFUSAL ENDS NOTHING, and neither does one more in the same hour
    provider.refreshes = false;
    expect(await (await refresh(found.refresh_token)).json()).toEqual({
      error: "bad_refresh_token",
    });
    vi.setSystemTime(start + 50 * HOUR + HOUR / 2);
    await refresh(found.refresh_token);
    expect(await routes.mindsOf("github", "7")).toEqual(["iterate.ada.example"]);
    // a good refresh between two refusals: the first one is forgotten
    provider.refreshes = true;
    const good = await tokensOf(await refresh(found.refresh_token));
    provider.refreshes = false;
    vi.setSystemTime(start + 80 * HOUR);
    await refresh(good.refresh_token);
    expect(await routes.mindsOf("github", "7")).toEqual(["iterate.ada.example"]);
    // A SECOND REFUSAL ON A LATER TRY: the person's grant is over, and what they connected ends
    vi.setSystemTime(start + 104 * HOUR);
    await refresh(good.refresh_token);
    expect(await routes.mindsOf("github", "7")).toEqual([]);
    expect(await routes.mindsOf("github", "8")).toEqual([]);

    // A NEW CONNECT BETWEEN TWO REFUSALS: the refusal before it was of the grant it replaced
    const connectAgain = async (code: string) => {
      provider.refreshes = true;
      const again = await tokensOf(
        await ada.ask("token", {
          grant_type: "authorization_code",
          code,
          cloud_proof: await proofFor("iterate.ada.example", code),
        }),
      );
      provider.refreshes = false;
      return again;
    };
    await refresh((await connectAgain("c0de-3")).refresh_token);
    const replaced = await connectAgain("c0de-4");
    vi.setSystemTime(start + 106 * HOUR);
    await refresh(replaced.refresh_token);
    expect(await routes.mindsOf("github", "7")).toEqual(["iterate.ada.example"]);
  } finally {
    vi.useRealTimers();
  }
});

test("a stack's statement is checked as ML-DSA-65 under its raw key, the Cloud's as P-256, and neither under the other's", async () => {
  const stack = await stackSignerOf();
  const cloud = await signerOf(await newJwk());
  const fields = { mind: "iterate.ada.example", path: "/", type: "t", payload: {}, at: 0 };
  const byStack = await stack.sign({ ...fields, expires: Date.now() + 60_000 });
  const byCloud = await cloud.sign({ ...fields, expires: Date.now() + 60_000 });
  expect(await statementOf(byStack, stack.publicKey)).toMatchObject({ type: "t" });
  expect(await statementOf(byCloud, cloud.publicKey)).toMatchObject({ type: "t" });
  // a signature that names the other format, under the right key id, is no signature of the key
  const relabel = (signed: Signed, format: Signed["signature"]["format"]) => ({
    ...signed,
    signature: { ...signed.signature, format },
  });
  expect(await statementOf(relabel(byStack, "p256"), stack.publicKey)).toBeNull();
  expect(await statementOf(relabel(byCloud, "ML-DSA-65"), cloud.publicKey)).toBeNull();
  // a changed byte
  const changed = { ...byStack, statement: byStack.statement.replace('"t"', '"u"') };
  expect(await statementOf(changed, stack.publicKey)).toBeNull();
});

test("a request is the deployment's only when its published key signed this very request", async () => {
  const { env, deployment, proofFor } = await setup();
  const ada = await deployment("iterate.ada.example");
  const body = new URLSearchParams({
    grant_type: "authorization_code",
    code: "c",
    cloud_proof: await proofFor("iterate.ada.example", "c"),
  }).toString();
  const post = (statement: string, sent = body) =>
    cloud.fetch(
      new Request(`${CLOUD}/clients/github/token`, {
        method: "POST",
        headers: { "iterate-statement": statement },
        body: sent,
      }),
      env,
    );
  const good = await ada.statement(
    "events.iterate.com/integration/token-requested",
    "github",
    body,
  );
  // the same statement on another body, a statement for another verb, another signer, none at all
  expect(await post(good, `${body}&code=other`)).toMatchObject({ status: 401 });
  expect(
    await post(
      await ada.statement(
        "events.iterate.com/integration/installation-token-requested",
        "github",
        body,
      ),
    ),
  ).toMatchObject({ status: 401 });
  const mallory = await deployment("iterate.mallory.example", { publishes: "iterate.ada.example" });
  expect(
    await post(
      await mallory.statement("events.iterate.com/integration/token-requested", "github", body),
    ),
  ).toMatchObject({ status: 401 });
  expect(await post("")).toMatchObject({ status: 401 });
  expect(await post(good)).toMatchObject({ status: 200 });
  // the very same request again: a statement counts once
  const replayed = await post(good);
  expect([replayed.status, await replayed.json()]).toEqual([
    401,
    { error: "the statement was already used" },
  ]);
});

test("a deployment that serves its identity log is read by it, and a key that the log revoked no longer counts", async () => {
  const { env, deployment } = await setup();
  const hostname = `iterate-${crypto.randomUUID().slice(0, 8)}.example`;
  const ada = await deployment(hostname, { log: true });
  const outbox = env.OUTBOX.get(env.OUTBOX.idFromName(hostname)) as unknown as {
    ctx: DurableObjectState;
  };
  // each read is kept a minute, here and in iterate/mind-identity-log: a step past both
  vi.useFakeTimers({ toFake: ["Date"] });
  const later = () => vi.setSystemTime(Date.now() + 61_000);
  try {
    expect(await (await saysMindForm(ada, true)).json()).toEqual({ ok: true, reads: true });
    // the state its log proves is kept beside the hostname's own rows: its id and its head
    expect(await outbox.ctx.storage.get("identity")).toMatchObject({
      expected: ada.log!.mind,
      position: 2,
    });
    // the owner revokes the stack's key: the next record lists no working key, and
    // /keys/stack.json still serves the key, which no longer counts
    const { identity, log } = ada;
    log!.records.push(await identity!.next(log!.records.at(-1)!, { workingKeys: [] }));
    later();
    const refused = await saysMindForm(ada, true);
    expect([refused.status, await refused.json()]).toEqual([
      401,
      {
        error: `the identity log of ${hostname} lists no such working key: the key that signed is not the mind's, or no longer`,
      },
    ]);
    // the revoke is kept at once for a known hostname, though no statement verified
    expect(await outbox.ctx.storage.get("identity")).toMatchObject({ position: 3 });
    // the host takes the revoke back: its log no longer continues the state kept, so it is refused
    log!.records.pop();
    later();
    const rolledBack = await saysMindForm(ada, true);
    expect([rolledBack.status, await rolledBack.json()]).toEqual([
      401,
      {
        error: expect.stringContaining(
          `${hostname} serves no identity log that continues the one read here`,
        ),
      },
    ]);
  } finally {
    vi.useRealTimers();
  }
});

test("a stranger's statement for a hostname of which nothing is kept writes nothing, and a hostname's log is read once a minute", async () => {
  const { env, deployment } = await setup();
  const hostname = `iterate-${crypto.randomUUID().slice(0, 8)}.example`;
  const ada = await deployment(hostname, { log: true });
  const mallory = await deployment(`mallory-${crypto.randomUUID().slice(0, 8)}.example`, {
    publishes: hostname,
  });
  const outbox = env.OUTBOX.get(env.OUTBOX.idFromName(hostname)) as unknown as {
    ctx: DurableObjectState;
  };
  // mallory names ada's hostname, whose log lists no key of hers
  const junk = await saysMindForm(mallory, true);
  expect([junk.status, await junk.json()]).toEqual([
    401,
    {
      error: `the identity log of ${hostname} lists no such working key: the key that signed is not the mind's, or no longer`,
    },
  ]);
  expect(await outbox.ctx.storage.list()).toEqual(new Map());
  // ada's own statement, in the same minute: the log is not read again, and its state is kept now
  expect(await (await saysMindForm(ada, true)).json()).toEqual({ ok: true, reads: true });
  expect(await saysMindForm(ada, false)).toMatchObject({ status: 200 });
  expect(ada).toMatchObject({ logReads: 1 });
  expect(await outbox.ctx.storage.get("identity")).toMatchObject({ expected: ada.log!.mind });
});

test("a hostname whose control plane did not answer is read again at the next ask", async () => {
  const { deployment } = await setup();
  const hostname = `iterate-${crypto.randomUUID().slice(0, 8)}.example`;
  const ada = await deployment(hostname);
  ada.unreachable = true;
  expect(await saysMindForm(ada, true)).toMatchObject({ status: 401 });
  // the fetch failed, which says nothing of the host: the next ask reads it again
  ada.unreachable = false;
  expect(await (await saysMindForm(ada, true)).json()).toEqual({ ok: true, reads: true });
});

test("a hostname whose log now proves another mind is refused, and the other mind is kept for a person to see", async () => {
  const { env, deployment } = await setup();
  const hostname = `iterate-${crypto.randomUUID().slice(0, 8)}.example`;
  const ada = await deployment(hostname, { log: true });
  expect(await (await saysMindForm(ada, true)).json()).toEqual({ ok: true, reads: true });
  const known = ada.log!.mind;
  // another genesis at the same hostname, which lists the very same stack key
  const other = await newIdentityLog([hostname]);
  ada.log = {
    mind: other.mind,
    records: [other.genesis, await other.next(other.genesis, { workingKeys: [ada.listed] })],
  };
  const warn = vi.spyOn(console, "warn");
  // each read is kept a minute, here and in iterate/mind-identity-log: after it, the hostname is
  // read again
  vi.useFakeTimers({ toFake: ["Date"] });
  try {
    vi.setSystemTime(Date.now() + 61_000);
    const refused = await saysMindForm(ada, true);
    expect([refused.status, await refused.json()]).toEqual([
      401,
      {
        error: `${hostname} is known here as the mind ${known}, and its log now proves the mind ${other.mind}`,
      },
    ]);
  } finally {
    vi.useRealTimers();
  }
  expect(warn).toHaveBeenCalledWith({
    event: "cloud.asker-refused",
    mind: hostname,
    known,
    serves: other.mind,
  });
  const outbox = env.OUTBOX.get(env.OUTBOX.idFromName(hostname)) as unknown as {
    ctx: DurableObjectState;
  };
  expect(await outbox.ctx.storage.get("identityRefused")).toMatchObject({ mind: other.mind });
  expect(await outbox.ctx.storage.get("identity")).toMatchObject({ expected: known });
});

test("the statement is read from iterate-auth-statement first and from iterate-statement still; with neither the request is a 401", async () => {
  const { env, deployment, proofFor } = await setup();
  const ada = await deployment("iterate.ada.example");
  const body = async () =>
    new URLSearchParams({
      grant_type: "authorization_code",
      code: "c",
      cloud_proof: await proofFor("iterate.ada.example", "c"),
    }).toString();
  const post = async (headers: Record<string, string>) => {
    const sent = await body();
    const named: Record<string, string> = {};
    for (const [name, who] of Object.entries(headers))
      named[name] =
        who === "ada"
          ? await ada.statement("events.iterate.com/integration/token-requested", "github", sent)
          : "not a statement";
    return (
      await cloud.fetch(
        new Request(`${CLOUD}/clients/github/token`, {
          method: "POST",
          headers: named,
          body: sent,
        }),
        env,
      )
    ).status;
  };

  expect({
    newName: await post({ "iterate-auth-statement": "ada" }),
    oldName: await post({ "iterate-statement": "ada" }),
    bothNewDecides: await post({ "iterate-auth-statement": "ada", "iterate-statement": "bad" }),
    bothNewWrong: await post({ "iterate-auth-statement": "bad", "iterate-statement": "ada" }),
    neither: await post({}),
  }).toEqual({ newName: 200, oldName: 200, bothNewDecides: 200, bothNewWrong: 401, neither: 401 });
});

test("the mind's own sender (core/secrets-worker brokered) is read by the Cloud: the two agree on the header", async () => {
  const { env, deployment, proofFor } = await setup();
  const ada = await deployment("iterate.ada.example");
  const body = new URLSearchParams({
    grant_type: "authorization_code",
    code: "c",
    cloud_proof: await proofFor("iterate.ada.example", "c"),
  }).toString();
  const type = "events.iterate.com/integration/token-requested";
  // the mind's sender signs with ada's key, and its fetch reaches this Cloud
  const stacks = globalThis.fetch;
  vi.stubGlobal("fetch", (input: Request | string, init?: RequestInit) =>
    input instanceof Request && input.url.startsWith(CLOUD)
      ? cloud.fetch(input, env)
      : stacks(input, init),
  );
  const sign = async () =>
    JSON.parse(
      Buffer.from(await ada.statement(type, "github", body), "base64url").toString(),
    ) as Signed;
  const answer = await brokered(
    sign,
    CLOUD,
    "github",
    type,
  )(new Request(`${CLOUD}/clients/github/token`, { method: "POST", body }));
  expect(answer).toMatchObject({ status: 200 });
});

test("a deployment is its control plane's hostname, whole: two hostnames of one domain are two deployments, and neither uses the other's code, grant or sealed token", async () => {
  for (const [one, other] of [
    ["cp.bo.example", "iterate.bo.example"],
    ["iterate.bo.example", "cp.bo.example"],
  ] as const) {
    const { env, deployment, provider, proofFor } = await setup();
    const mine = await deployment(one);
    const theirs = await deployment(other);
    // the page names the hostname as the callback address has it, with nothing taken off
    const state = `${base64url(Buffer.from(`https://${one}/secrets/oauth/callback`))}.n`;
    const consent = `${github.authorizationEndpoint}?client_id=${github.clientId}&redirect_uri=${encodeURIComponent(`${CLOUD}/clients/github/callback`)}&state=${state}`;
    const shown = await cloud.fetch(
      get(`/clients/github/begin?to=${encodeURIComponent(consent)}`),
      env,
    );
    expect(await shown.text()).toContain(`Give <b>${one}</b> access to your GitHub account?`);

    // A CODE: its proof is for `one`, and the other hostname's own key redeems nothing with it
    const exchange = {
      grant_type: "authorization_code",
      code: "c0de",
      cloud_proof: await proofFor(one, "c0de"),
    };
    const redeemed = await theirs.ask("token", exchange);
    expect([redeemed.status, await redeemed.json()]).toEqual([
      403,
      { error: "the Cloud did not send this code to this deployment" },
    ]);
    expect(provider.tokenRequests).toHaveLength(0);
    const connected = await mine.ask("token", exchange);
    const { refresh_token: sealed } = (await connected.json()) as { refresh_token: string };

    // A GRANT: what `one` connected is `one`'s, and no token is minted for the other hostname
    const routes = env.ROUTES.get(env.ROUTES.idFromName("routes")) as unknown as Routes;
    expect(await routes.mindsOf("github", "7")).toEqual([one]);
    const minted = await theirs.ask("installation-token", { installationId: "7" }, "json");
    expect([minted.status, await minted.json()]).toEqual([
      403,
      { error: `${other} has not connected installation 7` },
    ]);
    expect(await mine.ask("installation-token", { installationId: "7" }, "json")).toMatchObject({
      ok: true,
    });

    // A SEALED TOKEN: bound to the name it was sealed for, so it refreshes for `one` alone
    const refresh = { grant_type: "refresh_token", refresh_token: sealed };
    const spent = await theirs.ask("token", refresh);
    expect([spent.status, await spent.json()]).toEqual([
      403,
      { error: "this refresh token is not this deployment's" },
    ]);
    expect(await mine.ask("token", refresh)).toMatchObject({ status: 200 });
  }
});

test("a GitHub delivery becomes a statement signed by the Cloud's key, held until the deployment takes it", async () => {
  const { env, cloudKey, deployment, provider, proofFor } = await setup();
  const ada = await deployment("iterate.ada.example");
  await ada.ask("token", {
    grant_type: "authorization_code",
    code: "c0de",
    cloud_proof: await proofFor("iterate.ada.example", "c0de"),
  });
  const body = JSON.stringify({ action: "opened", installation: { id: 7 } });
  const deliver = async (
    signature: string,
    sent = body,
    delivery = "d-1",
    event = "pull_request",
  ) => {
    const answer = await cloud.fetch(
      new Request(`${CLOUD}/clients/github/webhook`, {
        method: "POST",
        headers: {
          "x-hub-signature-256": signature,
          "x-github-event": event,
          "x-github-delivery": delivery,
          authorization: "Bearer not-kept",
        },
        body: sent,
      }),
      env,
    );
    await handedOver(env, "github");
    return answer;
  };
  const sign = (text: string) =>
    `sha256=${createHmac("sha256", "webhook-secret").update(text).digest("hex")}`;

  expect(await deliver("sha256=" + "0".repeat(64))).toMatchObject({ status: 401 });
  // in this test a namespace answers the object itself, not a stub (namespaceOf)
  const outbox = env.OUTBOX.get(env.OUTBOX.idFromName("iterate.ada.example")) as unknown as Outbox;
  // a delivery about an installation nobody connected is kept, answered, and is nobody's
  const nobodys = JSON.stringify({ installation: { id: 999 } });
  expect(await (await deliver(sign(nobodys), nobodys, "d-0")).json()).toEqual({ accepted: true });
  expect(await held(outbox)).toBe(0);

  // the deployment is down: the provider still hears 200, and the Cloud holds the statement
  ada.down = true;
  expect(await (await deliver(sign(body))).json()).toEqual({ accepted: true });
  await outbox.alarm();
  expect(ada.statements).toHaveLength(0);
  expect(await held(outbox)).toBe(1);

  ada.down = false;
  await outbox.alarm();
  expect(await held(outbox)).toBe(0);
  const [signed] = ada.statements;
  const statement = await statementOf(signed!, cloudKey.publicKey);
  expect(statement).toMatchObject({
    mind: "iterate.ada.example",
    path: "/integrations/github/7",
    type: "events.iterate.com/github/webhook-received",
    payload: {
      delivery: { id: "d-1", name: "pull_request" },
      installationId: "7",
      body: { action: "opened", installation: { id: 7 } },
    },
  });
  expect(JSON.stringify(statement)).not.toContain("not-kept");
  expect(provider.tokenRequests).toHaveLength(1);

  // GitHub sends the same delivery again: it is relayed once
  expect(await (await deliver(sign(body))).json()).toEqual({ accepted: true, redelivery: true });
  expect(await held(outbox)).toBe(0);
  // the App is removed from the account: the deployment hears it, and then gets nothing more
  const removed = JSON.stringify({ action: "deleted", installation: { id: 7 } });
  await deliver(sign(removed), removed, "d-2", "installation");
  expect(await held(outbox)).toBe(1);
  await deliver(sign(body), body, "d-3");
  expect(await held(outbox)).toBe(1);
  await outbox.alarm();
  expect(await held(outbox)).toBe(0);

  // EVERY signed delivery was also passed on, unchanged, to the platform the app served before:
  // the one about nobody's installation and the repeated one too, and never the unsigned one
  const passOn = env.OUTBOX.get(env.OUTBOX.idFromName("pass-on\ngithub")) as unknown as Outbox;
  provider.osAnswers = 503;
  await passOn.alarm();
  expect([provider.passed.length, await held(passOn)]).toEqual([0, 5]);
  provider.osAnswers = 200;
  await passOn.alarm();
  expect(await held(passOn)).toBe(0);
  expect(provider.passed.map((sent) => sent.headers["x-github-delivery"])).toEqual([
    "d-0",
    "d-1",
    "d-1",
    "d-2",
    "d-3",
  ]);
  expect(provider.passed[1]).toMatchObject({
    url: `${OS}/github/webhook`,
    body,
    headers: { "x-hub-signature-256": sign(body), "x-github-event": "pull_request" },
  });
  expect(provider.passed[1]!.headers).not.toHaveProperty("authorization");
  // a refusal of its own is an answer: nothing is sent again
  provider.osAnswers = 401;
  await deliver(sign(body), body, "d-4");
  await passOn.alarm();
  expect(await held(passOn)).toBe(0);
  // ONE DELIVERY THE OTHER PLATFORM CANNOT ANSWER does not hold back those behind it: it waits a
  // minute at most, then goes, and the next one is sent
  provider.osAnswers = 503;
  await deliver(sign(body), body, "d-5");
  await deliver(sign(body), body, "d-6");
  await passOn.alarm();
  expect(await held(passOn)).toBe(2);
  const { storage } = (passOn as unknown as { ctx: DurableObjectState }).ctx;
  const [[first, stuck]] = [...(await storage.list<{ at: number }>({ prefix: "item:", limit: 1 }))];
  await storage.put(first, { ...stuck, at: Date.now() - 61_000 });
  await passOn.alarm();
  expect(await held(passOn)).toBe(1);
  provider.osAnswers = 200;
  await passOn.alarm();
  expect(await held(passOn)).toBe(0);
  expect(provider.passed.at(-1)!.headers["x-github-delivery"]).toBe("d-6");
});

test("with its mind's auth Worker, every statement for another deployment is in the mind form alone, and the Cloud's own mind keeps the key form", async () => {
  const { env, cloudKey, deployment, proofFor } = await setup();
  const { mindKey, auth } = await withMindAuth(env);
  const names = ["iterate.ada.example", "iterate.bob.example", "iterate.iterate.com"];
  const [ada, bob, own] = await Promise.all(names.map((name) => deployment(name)));
  ada!.letsMindIn = true;
  for (const [i, one] of [ada!, bob!, own!].entries())
    expect(
      await one.ask("token", {
        grant_type: "authorization_code",
        code: `code-${names[i]}`,
        cloud_proof: await proofFor(names[i]!, `code-${names[i]}`),
      }),
      `${names[i]} connects`,
    ).toMatchObject({ status: 200 });
  const info = vi.spyOn(console, "info");
  const warn = vi.spyOn(console, "warn");
  /** What each of the three took when its outbox sent: the statement read with the key that
   *  signed it, and its form; null for one that took nothing. */
  const took = async () => {
    const forms = [];
    for (const [i, at] of [ada!, bob!, own!].entries()) {
      await (env.OUTBOX.get(env.OUTBOX.idFromName(names[i]!)) as unknown as Outbox).alarm();
      const signed = at.statements.pop();
      expect(at.statements, `${names[i]} took one statement at most`).toHaveLength(0);
      const asMind = signed && (await statementOf(signed, mindKey.publicKey));
      forms.push(
        !signed
          ? null
          : asMind
            ? { form: "mind", ...asMind }
            : { form: "key", ...(await statementOf(signed, cloudKey.publicKey)) },
      );
    }
    return forms;
  };
  /** One delivery about installation 7, which all three connected. */
  const deliver = async (delivery: string) => {
    const body = JSON.stringify({ action: delivery, installation: { id: 7 } });
    await cloud.fetch(
      new Request(`${CLOUD}/clients/github/webhook`, {
        method: "POST",
        headers: {
          "x-hub-signature-256": `sha256=${createHmac("sha256", "webhook-secret").update(body).digest("hex")}`,
          "x-github-event": "pull_request",
          "x-github-delivery": delivery,
        },
        body,
      }),
      env,
    );
    await handedOver(env, "github");
    return took();
  };

  // ADA LET THE CLOUD'S MIND IN: the mind form. Bob did not: he refused it, and gets nothing in
  // another form; it waits in his outbox. The Cloud's own mind: the key form, never signed by its mind.
  const type = "events.iterate.com/github/webhook-received";
  expect(await deliver("d-1")).toMatchObject([
    {
      form: "mind",
      mind: "iterate.ada.example",
      from: "iterate.iterate.com",
      path: "/minds/iterate.iterate.com/integrations/github/7",
      type,
      about: ["cloud:github:d-1"],
    },
    null,
    { form: "key", mind: "iterate.iterate.com", path: "/integrations/github/7", type },
  ]);
  expect(bob).toMatchObject({ mindFormRefused: 1, keyFormRefused: 0 });
  expect(info).toHaveBeenCalledWith({
    event: "cloud.statement-refused",
    mind: "iterate.bob.example",
    status: 403,
    refused: "iterate.iterate.com is not let in here",
  });
  // bob's owner lets the Cloud's mind in: the held delivery goes, in the mind form
  bob!.letsMindIn = true;
  expect(await took()).toMatchObject([null, { form: "mind", about: ["cloud:github:d-1"] }, null]);

  // A DEPLOYMENT'S WORD on the form changes nothing now: it is answered, and kept nowhere
  expect(await (await saysMindForm(ada!, false)).json()).toEqual({ ok: true, reads: false });
  expect((await deliver("d-2")).map((one) => one && one.form)).toEqual(["mind", "mind", "key"]);

  // THE AUTH WORKER FAILS: each other deployment's statement waits in its own outbox, unsigned
  auth.fails = true;
  expect((await deliver("d-3")).map((one) => one && one.form)).toEqual([null, null, "key"]);
  expect(warn).toHaveBeenCalledWith({
    event: "cloud.mind-sign-failed",
    mind: "iterate.ada.example",
    error: "Error: the auth Worker does not answer",
  });
  auth.fails = false;
  expect(await took()).toMatchObject([
    { form: "mind", about: ["cloud:github:d-3"] },
    { form: "mind", about: ["cloud:github:d-3"] },
    null,
  ]);
  expect(auth.signedFor).not.toContain("iterate.iterate.com");

  // NO BINDING (a dev Cloud with no mind): the key form for everyone
  delete env.MIND_AUTH;
  expect((await deliver("d-4")).map((one) => one && one.form)).toEqual(["key", "key", "key"]);
});

test("a statement is held in the key form, as the Outbox of before held it, and is sent in the mind form alone", async () => {
  const { env, cloudKey, deployment } = await setup();
  const { mindKey, auth } = await withMindAuth(env);
  const ada = await deployment("iterate.ada.example");
  ada.letsMindIn = true;
  const outbox = env.OUTBOX.get(env.OUTBOX.idFromName("iterate.ada.example")) as unknown as Outbox;
  const storage = (outbox as unknown as { ctx: DurableObjectState }).ctx.storage;
  const at = Date.now();
  await outbox.put("iterate.ada.example", {
    path: "/integrations/github/7",
    type: "events.iterate.com/github/webhook-received",
    payload: { delivery: { id: "d-0" } },
    at,
    about: ["cloud:github:d-0"],
  });
  // the row has the shape a Worker of before reads, after a rollback: a statement signed by the
  // Cloud's key, and `about` beside it
  const [row] = [
    ...(await storage.list<{ signed: Signed; about?: string[] }>({ prefix: "item:" })).values(),
  ];
  expect(row?.about).toEqual(["cloud:github:d-0"]);
  expect(await statementOf(row!.signed, cloudKey.publicKey)).toMatchObject({
    mind: "iterate.ada.example",
    path: "/integrations/github/7",
    at,
    expires: at + HELD_MS,
  });

  // the Cloud's mind does not sign: the row waits, and nothing goes in the key form
  auth.fails = true;
  await outbox.alarm();
  expect({
    took: ada.statements.length,
    refused: ada.keyFormRefused,
    held: await held(outbox),
  }).toEqual({
    took: 0,
    refused: 0,
    held: 1,
  });
  // it signs: the same path, type, payload and about, in the mind form
  auth.fails = false;
  await outbox.alarm();
  expect(
    await Promise.all(ada.statements.map((one) => statementOf(one, mindKey.publicKey))),
  ).toMatchObject([
    {
      mind: "iterate.ada.example",
      from: "iterate.iterate.com",
      path: "/minds/iterate.iterate.com/integrations/github/7",
      payload: { delivery: { id: "d-0" } },
      about: ["cloud:github:d-0"],
      // it ends when the row's day ends: the Cloud's mind dates it when it signs
      expires: expect.any(Number),
    },
  ]);
  expect(await held(outbox)).toBe(0);
});

test("a held row whose statement is not signed is signed late and goes, one that says nothing is set aside, and the statements behind them go", async () => {
  const { env, cloudKey, deployment } = await setup();
  const ada = await deployment("iterate.ada.example");
  const outbox = env.OUTBOX.get(env.OUTBOX.idFromName("iterate.ada.example")) as unknown as Outbox;
  const storage = (outbox as unknown as { ctx: DurableObjectState }).ctx.storage;
  const at = Date.now() - 60_000;
  const said = (id: string) => ({
    path: "/integrations/github/7",
    type: "events.iterate.com/github/webhook-received",
    payload: { delivery: { id } },
    at,
    about: [`cloud:github:${id}`],
  });
  // the row an Outbox of the release before made of a `put(mind, said)`: `said` where the signed
  // statement belongs. It is the head of the queue, and a row that says nothing is behind it
  const unsigned = { mind: "iterate.ada.example", signed: said("d-0"), at, bytes: 1 };
  await storage.put("item:000000000000", unsigned);
  await storage.put("item:000000000000a", {
    mind: "iterate.ada.example",
    signed: {},
    at,
    bytes: 1,
  });
  await storage.put("item:000000000000b", { mind: "iterate.ada.example", at, bytes: 1 });
  await outbox.put("iterate.ada.example", { ...said("d-1"), at: Date.now() });
  expect(await held(outbox)).toBe(4);

  // the deployment is down: the unsigned row is signed in its place, with `about` beside it
  ada.down = true;
  await outbox.alarm();
  expect(await storage.get("item:000000000000")).toMatchObject({
    about: ["cloud:github:d-0"],
    at,
    signed: { statement: expect.any(String) },
  });

  ada.down = false;
  await outbox.alarm();
  expect(
    await Promise.all(ada.statements.map((one) => statementOf(one, cloudKey.publicKey))),
  ).toMatchObject([
    // its own time: the statement's day began when the delivery came
    { payload: { delivery: { id: "d-0" } }, at, expires: at + HELD_MS },
    { payload: { delivery: { id: "d-1" } } },
  ]);
  expect(await held(outbox)).toBe(0);
  // the rows that say nothing are set aside, out of the queue, and go when their day is over
  const aside = async () => [...(await storage.list({ prefix: "unread:" })).keys()];
  expect(await aside()).toEqual(["unread:item:000000000000a", "unread:item:000000000000b"]);
  await storage.put("unread:item:000000000000a", {
    mind: "iterate.ada.example",
    signed: {},
    at: Date.now() - HELD_MS,
  });
  await outbox.alarm();
  expect(await aside()).toEqual(["unread:item:000000000000b"]);
  // the alarm comes back when the day of the one that is left ends, and not a day from now
  expect(await storage.getAlarm()).toBe(at + HELD_MS);
  // a queue that waits for its deployment lets a row set aside go all the same
  await storage.put("unread:item:000000000000b", {
    mind: "iterate.ada.example",
    at: Date.now() - HELD_MS,
  });
  ada.down = true;
  await outbox.put("iterate.ada.example", { ...said("d-1b"), at: Date.now() });
  await outbox.alarm();
  expect({ aside: await aside(), held: await held(outbox) }).toEqual({ aside: [], held: 1 });
  ada.down = false;
  await outbox.alarm();
  expect(await held(outbox)).toBe(0);

  // a queue over its bound lets each kind of row go
  await storage.put("item:000000000000", unsigned);
  await storage.put("item:000000000000a", {
    mind: "iterate.ada.example",
    signed: {},
    at,
    bytes: 1,
  });
  await storage.put("item:000000000000b", { mind: "iterate.ada.example", at, bytes: 1 });
  ada.down = true;
  for (let n = 0; n < QUEUE_MAX_ROWS; n += 1)
    await outbox.put("iterate.ada.example", { ...said("d-2"), at: Date.now() });
  expect(await storage.get("item:000000000000")).toBeUndefined();
  expect(await storage.get("item:000000000000a")).toBeUndefined();
  expect(await storage.get("item:000000000000b")).toBeUndefined();
  expect(await held(outbox)).toBe(QUEUE_MAX_ROWS);
});

// What no row and no release can do to an Outbox's queue (README "What is kept").
test("an Outbox's writers refuse what they do not read, and keep no row of it", async () => {
  const { env, cloudKey } = await setup();
  const outbox = env.OUTBOX.get(env.OUTBOX.idFromName("iterate.ada.example")) as unknown as Outbox;
  const storage = (outbox as unknown as { ctx: DurableObjectState }).ctx.storage;
  const said = {
    path: "/integrations/github/7",
    type: "events.iterate.com/github/webhook-received",
    payload: {},
    at: Date.now(),
  };
  // what another release may send: a signed statement in place of what is said, and one
  // argument in place of two
  const signed = await cloudKey.sign({ mind: "iterate.ada.example", ...said, expires: 1 });
  const relay = { client: "github", account: "7", id: "d-1", type: said.type, payload: {} };
  const passed = { url: "https://os.example/hook", headers: [], body: new Uint8Array(1) };
  await expect(outbox.put("iterate.ada.example", signed as never)).rejects.toThrow(TypeError);
  await expect(outbox.put("iterate.ada.example", { ...said, at: "now" } as never)).rejects.toThrow(
    TypeError,
  );
  await expect(outbox.take({ relay, passed } as never)).rejects.toThrow(TypeError);
  await expect(outbox.take(relay, { ...passed, body: "text" } as never)).rejects.toThrow(TypeError);
  await expect(outbox.pass({ passed } as never)).rejects.toThrow(TypeError);
  expect({ rows: [...(await storage.list()).keys()], alarm: await storage.getAlarm() }).toEqual({
    rows: [],
    alarm: null,
  });
  // and what this release sends is taken
  await outbox.put("iterate.ada.example", said);
  expect(await held(outbox)).toBe(1);
});

test("a put whose queue cannot be bounded keeps its row once and wakes the queue, and the row that nothing reads is dropped at the head", async () => {
  const { env, deployment } = await setup();
  const ada = await deployment("iterate.ada.example");
  const outbox = env.OUTBOX.get(env.OUTBOX.idFromName("iterate.ada.example")) as unknown as Outbox;
  const storage = (outbox as unknown as { ctx: DurableObjectState }).ctx.storage;
  const errors = vi.spyOn(console, "error").mockImplementation(() => {});
  try {
    // a row that is no object, at the head: the bound throws when it reads it, and so does the alarm
    await storage.put("item:000000000000", null);
    await outbox.put("iterate.ada.example", {
      path: "/integrations/github/7",
      type: "events.iterate.com/github/webhook-received",
      payload: { delivery: { id: "d-1" } },
      at: Date.now(),
    });
    // the caller heard no failure, so it sends no second copy; the alarm is set for the row
    expect(await held(outbox)).toBe(2);
    expect(await storage.getAlarm()).toBeLessThanOrEqual(Date.now());
    expect(errors.mock.calls).toMatchObject([
      [{ event: "cloud.queue-bound-failed", queue: "item" }],
    ]);

    // the alarm does not throw: it drops the row, which has no time, and comes back at once
    await outbox.alarm();
    expect(errors.mock.calls.at(-1)).toMatchObject([
      { event: "cloud.outbox-alarm-failed", row: "item:000000000000", dropped: true },
    ]);
    expect(await storage.getAlarm()).toBeLessThanOrEqual(Date.now());
    await outbox.alarm();
    expect({ took: ada.statements.length, held: await held(outbox) }).toEqual({ took: 1, held: 0 });
  } finally {
    errors.mockRestore();
  }
});

test("an alarm that throws at its head is set again, later each time, and the head is dropped when its day is over", async () => {
  const { env, deployment } = await setup();
  const ada = await deployment("iterate.ada.example");
  const outbox = env.OUTBOX.get(env.OUTBOX.idFromName("iterate.ada.example")) as unknown as Outbox;
  const storage = (outbox as unknown as { ctx: DurableObjectState }).ctx.storage;
  const errors = vi.spyOn(console, "error").mockImplementation(() => {});
  vi.useFakeTimers({ toFake: ["Date"] });
  try {
    // a row of a kind this release does not know, as a later release may have left it: no path
    // through the alarm reads it, so the alarm throws
    const at = Date.now();
    await storage.put("item:000000000000", { later: true, at, bytes: 1 });
    await outbox.put("iterate.ada.example", {
      path: "/integrations/github/7",
      type: "events.iterate.com/github/webhook-received",
      payload: { delivery: { id: "d-1" } },
      at,
    });
    const waits: number[] = [];
    for (let tries = 1; tries <= 3; tries += 1) {
      await outbox.alarm();
      waits.push((await storage.getAlarm())! - Date.now());
      expect(errors.mock.calls.at(-1)).toMatchObject([
        { event: "cloud.outbox-alarm-failed", row: "item:000000000000", dropped: false, tries },
      ]);
    }
    expect(waits).toEqual([10_000, 20_000, 40_000]);
    // order holds while the row is held: the statement behind it waited
    expect({ took: ada.statements.length, held: await held(outbox) }).toEqual({ took: 0, held: 2 });

    // its day is over: the queue lets it go as any other row, and the statement behind it is
    // tried (it is a day old too, and is not sent: `HELD_MS`)
    vi.setSystemTime(at + HELD_MS);
    await outbox.alarm();
    expect(await held(outbox)).toBe(0);
  } finally {
    vi.useRealTimers();
    errors.mockRestore();
  }
});

test("an alarm that throws on a row of one queue drops that row alone when its day is over, and no row of another queue", async () => {
  const { env } = await setup();
  const inbox = env.OUTBOX.get(env.OUTBOX.idFromName("inbox\ngithub")) as unknown as Outbox;
  const storage = (inbox as unknown as { ctx: DurableObjectState }).ctx.storage;
  const errors = vi.spyOn(console, "error").mockImplementation(() => {});
  try {
    // a row that nothing reads in the queue of what is passed on, and a relay that is a day old
    // in the queue beside it: the alarm reads the relay, and owes it its own end
    const relay = {
      relay: { client: "github", account: "7", id: "d-old", type: "t", payload: {} },
      at: Date.now() - HELD_MS,
      bytes: 2,
    };
    await storage.put({ "hand:000000000001": null, "item:000000000002": relay });
    await inbox.alarm();
    expect(errors.mock.calls.at(-1)).toMatchObject([
      { event: "cloud.outbox-alarm-failed", row: "hand:000000000001", dropped: true },
    ]);
    expect([...(await storage.list({ prefix: "hand:" })).keys()]).toEqual([]);
    expect(await storage.get("item:000000000002")).toEqual(relay);
    // the queue that threw is empty now, and the alarm came back at once for the rest
    expect(await storage.getAlarm()).toBeLessThanOrEqual(Date.now());
  } finally {
    errors.mockRestore();
  }
});

test("an unsigned row whose day is over ends as a signed one does, with no signature: what it was to tell once is told again", async () => {
  const { env } = await setup();
  // the Cloud cannot sign now: its key does not read
  env.CLOUD_KEY = "{";
  const outbox = env.OUTBOX.get(env.OUTBOX.idFromName("iterate.ada.example")) as unknown as Outbox;
  const storage = (outbox as unknown as { ctx: DurableObjectState }).ctx.storage;
  const routes = env.ROUTES.get(env.ROUTES.idFromName("routes")) as unknown as Routes;
  const errors = vi.spyOn(console, "error").mockImplementation(() => {});
  try {
    // a word told once, in the unsigned form (`saidUnsigned`), and a day old
    const said = {
      path: "/integrations/google/ada@example.com",
      type: "events.iterate.com/google/gmail-connected",
      payload: {},
      at: Date.now() - HELD_MS,
    };
    const told = `told\n${said.type}\niterate.ada.example\n${said.path}`;
    await routes.keep(told, HELD_MS, "1");
    await storage.put("item:000000000001", {
      mind: "iterate.ada.example",
      signed: said,
      at: said.at,
      bytes: 1,
    });
    await outbox.alarm();
    expect(errors).not.toHaveBeenCalled();
    expect(await held(outbox)).toBe(0);
    expect(await routes.kept(told)).toBeNull();
  } finally {
    errors.mockRestore();
  }
});

test("a known hostname whose log now proves another mind gets nothing, even when that mind lets the Cloud's mind in, and its status says so", async () => {
  const { env, deployment, proofFor } = await setup();
  const { mindKey } = await withMindAuth(env);
  const hostname = `iterate-${crypto.randomUUID().slice(0, 8)}.example`;
  const ada = await deployment(hostname, { log: true });
  // the Cloud's own mind, at a hostname of this test alone: a log read is kept a minute
  env.MIND_HOSTNAME = `iterate-own-${crypto.randomUUID().slice(0, 8)}.example`;
  const own = await deployment(env.MIND_HOSTNAME, { log: true });
  ada.letsMindIn = true;
  // ada connects: her ask pins the hostname to her mind (step 3)
  expect(
    await ada.ask("token", {
      grant_type: "authorization_code",
      code: "code-ada",
      cloud_proof: await proofFor(hostname, "code-ada"),
    }),
  ).toMatchObject({ status: 200 });
  const known = ada.log!.mind;
  const outbox = env.OUTBOX.get(env.OUTBOX.idFromName(hostname)) as unknown as Outbox;
  await githubDelivery(env, "d-1");
  await outbox.alarm();
  expect(
    await Promise.all(ada.statements.splice(0).map((one) => statementOf(one, mindKey.publicKey))),
  ).toMatchObject([{ mind: hostname, about: ["cloud:github:d-1"] }]);

  // another genesis at the same hostname, which lists the same stack key and lets the Cloud's
  // mind in: what the Cloud holds for the hostname was for ada's mind, so it waits
  const other = await newIdentityLog([hostname]);
  ada.log = {
    mind: other.mind,
    records: [other.genesis, await other.next(other.genesis, { workingKeys: [ada.listed] })],
  };
  const warn = vi.spyOn(console, "warn");
  vi.useFakeTimers({ toFake: ["Date"] });
  try {
    // each read of a log is kept a minute: after it, the hostname is read again
    vi.setSystemTime(Date.now() + 61_000);
    await githubDelivery(env, "d-2");
    await outbox.alarm();
    expect({ took: ada.statements.length, held: await held(outbox) }).toEqual({ took: 0, held: 1 });
    expect(warn).toHaveBeenCalledWith({
      event: "cloud.mind-moved",
      mind: hostname,
      known,
      serves: other.mind,
    });
    // the Cloud's own mind reads it: pinned to ada's mind, and its hostname serves another
    const answer = await statusOf(own);
    expect(answer).toMatchObject({ status: 200 });
    expect((await answer.json()) as { minds: unknown[] }).toMatchObject({
      minds: [
        {
          mind: hostname,
          id: known,
          movedTo: { id: other.mind },
          held: 1,
          accounts: [
            { client: "github", account: "7" },
            { client: "github", account: "8" },
          ],
        },
      ],
    });
  } finally {
    vi.useRealTimers();
  }
});

test("a hostname that moved is cleared by its old mind from its new hostname: the rows and what waits are dropped, and the new mind there connects", async () => {
  const moved = await movedHostname();
  const { ada, hostname, x, outbox } = moved;
  // the new mind at the hostname cannot ask at all while the hostname is pinned (step 3), and a
  // stranger is refused: nothing is dropped
  expect(await ada.ask("ask/forget", { hostname }, "json")).toMatchObject({ status: 401 });
  const bob = await moved.deployment(`iterate-bob-${crypto.randomUUID().slice(0, 8)}.example`, {
    log: true,
  });
  expect(await bob.ask("ask/forget", { hostname }, "json")).toMatchObject({ status: 403 });
  expect(await held(outbox)).toBe(1);
  // the old mind, from its new hostname
  const warn = vi.spyOn(console, "warn");
  const cleared = await moved.adaMoved.ask("ask/forget", { hostname }, "json");
  expect([cleared.status, await cleared.json()]).toEqual([
    200,
    { mind: hostname, forgotten: x.mind, rows: 4, held: 1 },
  ]);
  expect(warn).toHaveBeenCalledWith({
    event: "cloud.mind-forgotten",
    mind: hostname,
    known: x.mind,
    serves: moved.y.mind,
    by: moved.movedTo,
    rows: 4,
    held: 1,
  });
  warn.mockRestore();
  expect(await held(outbox)).toBe(0);
  // the hostname is in no row of the Cloud's list now
  expect(await (await statusOf(moved.own)).json()).toEqual({
    minds: [],
    cursor: null,
    partial: false,
  });
  // the new mind at the hostname is pinned at its first ask, and connects
  expect(await moved.connect("code-new")).toMatchObject({ status: 200 });
  expect(await (await statusOf(ada)).json()).toMatchObject({
    minds: [{ mind: hostname, id: moved.y.mind, held: 0, lastRefused: null }],
  });

  // A MIND MAY CLEAR ITS OWN HOSTNAME at any time, and a statement it used before still counts once
  const body = "{}";
  const path = "/clients/github/ask/status";
  const signed = await moved.adaMoved.statement(
    "events.iterate.com/integration/ask-requested",
    "github",
    body,
    path,
  );
  const send = () =>
    cloud.fetch(
      new Request(`${CLOUD}${path}`, {
        method: "POST",
        headers: { "iterate-statement": signed },
        body,
      }),
      moved.env,
    );
  expect(await send()).toMatchObject({ status: 200 });
  const own = await moved.adaMoved.ask("ask/forget", { hostname: moved.movedTo }, "json");
  expect([own.status, await own.json()]).toEqual([
    200,
    { mind: moved.movedTo, forgotten: x.mind, rows: 0, held: 0 },
  ]);
  const again = await send();
  expect([again.status, await again.json()]).toEqual([
    401,
    { error: "the statement was already used" },
  ]);
  // the kept nonces end with their statements: the alarm comes back for them
  const swept = moved.env.OUTBOX.get(moved.env.OUTBOX.idFromName(moved.movedTo)) as unknown as {
    ctx: DurableObjectState;
  } & Outbox;
  expect(await swept.ctx.storage.getAlarm()).toBeGreaterThan(Date.now());
  vi.setSystemTime(Date.now() + HELD_MS + 1);
  await swept.alarm();
  expect(await swept.ctx.storage.list({ prefix: "nonce:" })).toMatchObject({ size: 0 });
  vi.useRealTimers();
});

test("the Cloud's own mind clears a hostname pinned to no mind only when it serves no mind and a statement there waited an hour", async () => {
  const { env, deployment, proofFor } = await setup();
  await withMindAuth(env);
  const tag = crypto.randomUUID().slice(0, 8);
  const hostname = `iterate-${tag}.example`;
  env.MIND_HOSTNAME = `iterate-own-${tag}.example`;
  const own = await deployment(env.MIND_HOSTNAME, { log: true });
  const bob = await deployment(`iterate-bob-${tag}.example`, { log: true });
  // a mind with no identity log: nothing pins its hostname
  const ada = await deployment(hostname);
  expect(
    await ada.ask("token", {
      grant_type: "authorization_code",
      code: "code-ada",
      cloud_proof: await proofFor(hostname, "code-ada"),
    }),
  ).toMatchObject({ status: 200 });
  // the hostname stops serving a mind, and a statement waits there
  ada.unreachable = true;
  const outbox = env.OUTBOX.get(env.OUTBOX.idFromName(hostname)) as unknown as Outbox;
  await githubDelivery(env, "d-1");
  await outbox.alarm();
  expect(await held(outbox)).toBe(1);
  const forget = (who: typeof own) => who.ask("ask/forget", { hostname }, "json");
  expect(await forget(own)).toMatchObject({ status: 409 });
  vi.useFakeTimers({ toFake: ["Date"] });
  vi.setSystemTime(Date.now() + 61 * 60_000);
  // another mind cannot, and a hostname that serves its stack key is a mind's: one that only refuses
  expect(await forget(bob)).toMatchObject({ status: 409 });
  ada.unreachable = false;
  ada.down = true;
  expect(await forget(own)).toMatchObject({ status: 409 });
  expect(await held(outbox)).toBe(1);
  ada.unreachable = true;
  const warn = vi.spyOn(console, "warn");
  const cleared = await forget(own);
  expect([cleared.status, await cleared.json()]).toEqual([
    200,
    { mind: hostname, forgotten: null, rows: 4, held: 1 },
  ]);
  expect(warn).toHaveBeenCalledWith(
    expect.objectContaining({ event: "cloud.mind-forgotten", mind: hostname, known: null }),
  );
  warn.mockRestore();
  expect(await held(outbox)).toBe(0);
  vi.useRealTimers();
});

test("the Cloud's own mind clears a hostname that moved only with the ids its status shows; another mind cannot, and a hostname pinned to no mind has nothing to clear", async () => {
  const moved = await movedHostname();
  const { hostname, x, y, own } = moved;
  const wrongs: Record<string, string>[] = [
    { hostname },
    { hostname, known: y.mind, serves: x.mind },
    { hostname, known: x.mind, serves: "f".repeat(64) },
  ];
  for (const wrong of wrongs)
    expect(await own.ask("ask/forget", wrong, "json")).toMatchObject({ status: 403 });
  // the Cloud's own mind, at another id than MIND_ID, is another mind
  moved.env.MIND_ID = "e".repeat(64);
  expect(
    await own.ask("ask/forget", { hostname, known: x.mind, serves: y.mind }, "json"),
  ).toMatchObject({
    status: 403,
  });
  delete moved.env.MIND_ID;
  const cleared = await own.ask("ask/forget", { hostname, known: x.mind, serves: y.mind }, "json");
  expect([cleared.status, await cleared.json()]).toEqual([
    200,
    { mind: hostname, forgotten: x.mind, rows: 4, held: 1 },
  ]);
  // again: nothing is pinned there now
  expect(
    await own.ask("ask/forget", { hostname, known: x.mind, serves: y.mind }, "json"),
  ).toMatchObject({
    status: 409,
  });
  vi.useRealTimers();
});

test("a deployment reads its own status: its accounts, what waits for it and the last refusal, and no other deployment's", async () => {
  const { env, deployment, proofFor } = await setup();
  await withMindAuth(env);
  const [ada, bob] = await Promise.all(
    ["iterate.ada.example", "iterate.bob.example"].map((name) => deployment(name)),
  );
  ada!.letsMindIn = true;
  for (const [mind, one] of [
    ["iterate.ada.example", ada!],
    ["iterate.bob.example", bob!],
  ] as const)
    expect(
      await one.ask("token", {
        grant_type: "authorization_code",
        code: `code-${mind}`,
        cloud_proof: await proofFor(mind, `code-${mind}`),
      }),
    ).toMatchObject({ status: 200 });
  await githubDelivery(env, "d-1");
  for (const mind of ["iterate.ada.example", "iterate.bob.example"])
    await (env.OUTBOX.get(env.OUTBOX.idFromName(mind)) as unknown as Outbox).alarm();

  const bobs = (await (await statusOf(bob!, { cursor: "" })).json()) as {
    minds: Record<string, unknown>[];
    cursor: string | null;
  };
  expect(bobs).toEqual({
    minds: [
      {
        mind: "iterate.bob.example",
        id: null,
        accounts: [
          { client: "github", account: "7", since: expect.any(Number) },
          { client: "github", account: "8", since: expect.any(Number) },
        ],
        letGo: [],
        held: 1,
        oldestAt: expect.any(Number),
        lastRefused: {
          reason: "iterate.iterate.com is not let in here",
          status: 403,
          at: expect.any(Number),
        },
      },
    ],
    cursor: null,
    partial: false,
  });
  expect(await (await statusOf(ada!)).json()).toMatchObject({
    minds: [{ mind: "iterate.ada.example", held: 0, lastRefused: null }],
  });
  // ada lets go of one account: her row says so
  expect(await ada!.ask("ask/release", { account: "7" }, "json")).toMatchObject({ status: 200 });
  expect(await (await statusOf(ada!)).json()).toMatchObject({
    minds: [
      {
        mind: "iterate.ada.example",
        accounts: [{ client: "github", account: "8" }],
        letGo: [{ client: "github", account: "7" }],
      },
    ],
  });
});

test("the Cloud's own mind reads every deployment's row, a page at a time, only while its hostname is pinned to its id", async () => {
  const { env, deployment, proofFor } = await setup();
  await withMindAuth(env);
  const names = ["iterate.bob.example", "iterate.ada.example"];
  const [bob, ada] = await Promise.all(names.map((name) => deployment(name)));
  for (const [i, one] of [bob!, ada!].entries())
    expect(
      await one.ask("token", {
        grant_type: "authorization_code",
        code: `code-${i}`,
        cloud_proof: await proofFor(names[i]!, `code-${i}`),
      }),
    ).toMatchObject({ status: 200 });
  const minds = async (who: Parameters<typeof statusOf>[0]) => {
    const answer = await statusOf(who);
    const read = (await answer.json()) as { minds?: { mind: string }[] };
    if (!read.minds) throw new Error(`${answer.status} ${JSON.stringify(read)}`);
    return read.minds.map((row) => row.mind);
  };
  // with no identity log, the Cloud's own hostname is pinned to no id: its own row alone. It is a
  // hostname of this test alone: a log read is kept a minute
  const ownHost = `iterate-own-${crypto.randomUUID().slice(0, 8)}.example`;
  env.MIND_HOSTNAME = ownHost;
  const unpinned = await deployment(ownHost);
  expect(await minds(unpinned)).toEqual([ownHost]);
  // the same hostname with an identity log, once the key read above is no longer kept (a minute)
  const own = await deployment(ownHost, { log: true });
  vi.useFakeTimers({ toFake: ["Date"] });
  vi.setSystemTime(Date.now() + 61_000);
  try {
    expect(await minds(own)).toEqual(["iterate.ada.example", "iterate.bob.example"]);
    // no person's id: who connected an account stays with the Cloud
    const answer = (await (await statusOf(own)).json()) as {
      minds: { accounts: Record<string, unknown>[] }[];
    };
    expect(Object.keys(answer.minds[0]!.accounts[0]!)).toEqual(["client", "account", "since"]);
    // a Google mailbox: by its domain alone in every deployment's list, whole in its own row
    const routes = env.ROUTES.get(env.ROUTES.idFromName("routes")) as unknown as Routes;
    await routes.claim("google", "ada@mail.example", ["ada@mail.example"], "iterate.ada.example");
    const listed = (await (await statusOf(own)).json()) as {
      minds: { mind: string; accounts: { client: string; account: string }[] }[];
    };
    expect(
      listed.minds
        .find((row) => row.mind === "iterate.ada.example")!
        .accounts.filter((each) => each.client === "google"),
    ).toMatchObject([{ account: "*@mail.example" }]);
    const adas = (await (await statusOf(ada!)).json()) as {
      minds: { accounts: { client: string; account: string }[] }[];
    };
    expect(adas.minds[0]!.accounts.filter((each) => each.client === "google")).toMatchObject([
      { account: "ada@mail.example" },
    ]);
    // `MIND_ID` names another mind: the Cloud's hostname reads its own row alone
    env.MIND_ID = "0".repeat(64);
    expect(await minds(own)).toEqual([ownHost]);
    env.MIND_ID = own.log!.mind;
    expect(await minds(own)).toEqual(["iterate.ada.example", "iterate.bob.example"]);
    // a page at a time, in the order of the hostnames
    const first = await routes.statusRows(null, "", 1);
    expect({ rows: first.rows.map((row) => row.mind), next: first.next }).toEqual({
      rows: ["iterate.ada.example"],
      next: "iterate.ada.example",
    });
    const second = await routes.statusRows(null, first.next!, 1);
    expect({ rows: second.rows.map((row) => row.mind), next: second.next }).toEqual({
      rows: ["iterate.bob.example"],
      next: null,
    });
  } finally {
    vi.useRealTimers();
  }
});

test("an account two people connected for one deployment stays connected while either still holds it", async () => {
  const { env } = await setup();
  const routes = env.ROUTES.get(env.ROUTES.idFromName("routes")) as unknown as Routes;
  // two admins of one organization each connect it for the same deployment
  await routes.claim("github", "ada", ["7", "8"], "iterate.team.example");
  await routes.claim("github", "bob", ["7"], "iterate.team.example");
  // ada's grant ends: the organization bob also holds stays, and the account only she held goes
  await routes.release("github", "ada", "iterate.team.example");
  expect(await Promise.all(["7", "8"].map((id) => routes.mindsOf("github", id)))).toEqual([
    ["iterate.team.example"],
    [],
  ]);
  // ada connects it again, then stops administering it: bob's hold keeps it
  await routes.claim("github", "ada", ["7"], "iterate.team.example");
  await routes.claim("github", "ada", [], "iterate.team.example");
  expect(await routes.mindsOf("github", "7")).toEqual(["iterate.team.example"]);
  // the last holder's grant ends: now it goes
  await routes.release("github", "bob", "iterate.team.example");
  expect(await routes.mindsOf("github", "7")).toEqual([]);
  // the deployment's own "let go" outranks a hold: one holder's end does not bring the account back
  for (const person of ["ada", "bob", "cy"])
    await routes.claim("github", person, ["9"], "iterate.team.example");
  await routes.letGo("github", "iterate.team.example", "9", false);
  await routes.release("github", "ada", "iterate.team.example");
  expect(await routes.mindsOf("github", "9")).toEqual([]);
});

test("a callback this Cloud did not begin goes to the platform the app served before, and a Setup URL's return goes on to authorize", async () => {
  const { env, deployment, provider, proofFor } = await setup();
  const location = async (query: string, client = "github") =>
    (await cloud.fetch(get(`/clients/${client}/callback?${query}`), env)).headers.get("location");
  // os.iterate.com's own connect, and an installation someone changed at GitHub, with no state
  expect(await location("code=abc&installation_id=9&setup_action=install&state=os-state")).toBe(
    `${OS}/github/callback?code=abc&installation_id=9&setup_action=install&state=os-state`,
  );
  expect(await location("installation_id=9&setup_action=update")).toBe(
    `${OS}/github/callback?installation_id=9&setup_action=update`,
  );
  // a client that served nobody before refuses a state that is not the Cloud's
  expect(await cloud.fetch(get("/clients/x/callback?code=abc&state=os-state"), env)).toMatchObject({
    status: 400,
  });

  // GITHUB'S SETUP URL: the Cloud's own install comes back with no code, and goes on to authorize
  const state = `${base64url(Buffer.from("https://iterate.ada.example/secrets/oauth/callback"))}.n`;
  const authorize = new URL(
    (await location(`installation_id=7&setup_action=install&state=${state}`))!,
  );
  expect(authorize.origin + authorize.pathname).toBe(`${PROVIDER}/login/oauth/authorize`);
  expect(Object.fromEntries(authorize.searchParams)).toEqual({
    client_id: "Iv1.client",
    redirect_uri: `${CLOUD}/clients/github/callback`,
    state,
  });
  // an owner has yet to approve the install: the deployment hears it, with no code
  expect(await location(`installation_id=7&setup_action=request&state=${state}`)).toBe(
    "https://iterate.ada.example/secrets/oauth/callback?installation_id=7&setup_action=request&state=n",
  );

  // THE EXCHANGE REPEATS WHAT WAS NAMED: a code from the App's install page named no redirect
  // URI, and a code from an authorize named the Cloud's. The vault does not say which.
  const ada = await deployment("iterate.ada.example");
  const exchange = async (code: string, beside: string) => {
    await ada.ask("token", {
      grant_type: "authorization_code",
      code,
      redirect_uri: "whatever the vault says",
      cloud_proof: await proofFor("iterate.ada.example", code, "github", beside),
    });
    return provider.tokenRequests.at(-1)!.get("redirect_uri");
  };
  expect([
    await exchange("from-install", "&installation_id=7&setup_action=install"),
    await exchange("from-authorize", ""),
  ]).toEqual([null, `${CLOUD}/clients/github/callback`]);
});

test("a Slack workspace connects through the Cloud, and its events reach the deployment signed and the old platform unchanged", async () => {
  const { env, cloudKey, deployment, provider, proofFor } = await setup();
  const ada = await deployment("iterate.ada.example");
  // the install: the bot token goes to the deployment as it came, and the workspace is its to hear
  const installed = await ada.ask("slack:token", {
    grant_type: "authorization_code",
    code: "slack-code",
    cloud_proof: await proofFor("iterate.ada.example", "slack-code", "slack"),
  });
  expect(await installed.json()).toMatchObject({ access_token: "xoxb-1", team: { id: "T1" } });
  expect(Object.fromEntries(provider.tokenRequests[0]!)).toMatchObject({
    client_id: "slack-client",
    client_secret: "slack-secret",
    redirect_uri: `${CLOUD}/clients/slack/callback`,
  });

  const now = String(Math.floor(Date.now() / 1000));
  const deliver = async (
    body: string,
    { route = "webhook", timestamp = now, secret = "slack-signing" } = {},
  ) => {
    const answer = await cloud.fetch(
      new Request(`${CLOUD}/clients/slack/${route}`, {
        method: "POST",
        headers: {
          "x-slack-request-timestamp": timestamp,
          "x-slack-signature": `v0=${createHmac("sha256", secret).update(`v0:${timestamp}:${body}`).digest("hex")}`,
        },
        body,
      }),
      env,
    );
    await handedOver(env, "slack");
    return answer;
  };
  const outbox = env.OUTBOX.get(env.OUTBOX.idFromName("iterate.ada.example")) as unknown as Outbox;
  // Slack checks a new address: answered here, and passed on to nobody
  const checked = await deliver(JSON.stringify({ type: "url_verification", challenge: "c-1" }));
  expect(await checked.json()).toEqual({ challenge: "c-1" });
  // an event, and an interactive payload, which Slack sends as a form
  const event = JSON.stringify({ team_id: "T1", event_id: "Ev1", event: { type: "message" } });
  const pressed = `payload=${encodeURIComponent(JSON.stringify({ type: "block_actions", team: { id: "T1" }, trigger_id: "tr-1" }))}`;
  expect(await (await deliver(event)).json()).toEqual({ accepted: true });
  expect(await (await deliver(pressed, { route: "interactivity-webhook" })).json()).toEqual({
    accepted: true,
  });
  expect(await held(outbox)).toBe(2);
  // refused: another secret, and a signature older than five minutes
  const stale = String(Number(now) - 301);
  expect([
    (await deliver(event, { secret: "another" })).status,
    (await deliver(event, { timestamp: stale })).status,
  ]).toEqual([401, 401]);

  await outbox.alarm();
  const statements = await Promise.all(
    ada.statements.map((signed) => statementOf(signed, cloudKey.publicKey)),
  );
  expect(statements).toMatchObject([
    {
      mind: "iterate.ada.example",
      path: "/integrations/slack/T1",
      type: "events.iterate.com/slack/webhook-received",
      payload: {
        teamId: "T1",
        slackRequestTimestamp: now,
        body: { event_id: "Ev1", event: { type: "message" } },
      },
    },
    { path: "/integrations/slack/T1", payload: { body: { type: "block_actions" } } },
  ]);
  await (env.OUTBOX.get(env.OUTBOX.idFromName("pass-on\nslack")) as unknown as Outbox).alarm();
  expect(provider.passed).toMatchObject([
    { url: `${OS}/slack/webhook`, body: event, headers: { "x-slack-request-timestamp": now } },
    { url: `${OS}/slack/interactivity-webhook`, body: pressed },
  ]);

  // the app is removed from the workspace: the deployment hears it, and then nothing more
  const removed = JSON.stringify({
    team_id: "T1",
    event_id: "Ev2",
    event: { type: "app_uninstalled" },
  });
  const after = JSON.stringify({ team_id: "T1", event_id: "Ev3", event: { type: "message" } });
  await deliver(removed);
  expect(await held(outbox)).toBe(1);
  await deliver(after);
  expect(await held(outbox)).toBe(1);
});

test("in a Slack Connect channel a delivery goes to the deployment of the workspace the app is installed in, not to the one of the person who acted", async () => {
  const { env, cloudKey, deployment, proofFor } = await setup();
  // ada connected workspace T1 by an install; bob's deployment holds T2, the workspace that
  // shares a channel with T1
  const ada = await deployment("iterate.ada.example");
  await ada.ask("slack:token", {
    grant_type: "authorization_code",
    code: "slack-code",
    cloud_proof: await proofFor("iterate.ada.example", "slack-code", "slack"),
  });
  const bob = await deployment("iterate.bob.example");
  await (env.ROUTES.get(env.ROUTES.idFromName("routes")) as unknown as Routes).claim(
    "slack",
    "U9",
    ["T2"],
    "iterate.bob.example",
  );

  const now = String(Math.floor(Date.now() / 1000));
  const deliver = async (body: string, route = "webhook") => {
    const answer = await cloud.fetch(
      new Request(`${CLOUD}/clients/slack/${route}`, {
        method: "POST",
        headers: {
          "x-slack-request-timestamp": now,
          "x-slack-signature": `v0=${createHmac("sha256", "slack-signing").update(`v0:${now}:${body}`).digest("hex")}`,
        },
        body,
      }),
      env,
    );
    await handedOver(env, "slack");
    return answer.status;
  };
  // a person of T2 writes in the shared channel: the event is for the app's installation in T1
  // (`authorizations`), and names T2 as where it happened
  const written = JSON.stringify({
    team_id: "T2",
    is_ext_shared_channel: true,
    authorizations: [{ team_id: "T1", user_id: "B1", is_bot: true }],
    event_id: "Ev-shared",
    event: { type: "message", team: "T2", user_team: "T2" },
  });
  // the same person submits a modal that T1's app opened for them: Slack names the workspace
  // the app is installed in beside the person's own
  const submitted = `payload=${encodeURIComponent(
    JSON.stringify({
      type: "view_submission",
      team: { id: "T2" },
      user: { id: "U7", team_id: "T2" },
      view: { team_id: "T2", app_installed_team_id: "T1" },
      trigger_id: "tr-shared",
    }),
  )}`;
  // the same person presses a button of a message that T1's app posted: `team` is the workspace
  // the app is installed in, and the person's own is in `user.team_id` alone
  const pressed = `payload=${encodeURIComponent(
    JSON.stringify({
      type: "block_actions",
      team: { id: "T1" },
      user: { id: "U7", team_id: "T2" },
      trigger_id: "tr-pressed",
    }),
  )}`;
  // and an event of T2's own, where the app is installed too, is still T2's
  const own = JSON.stringify({
    team_id: "T2",
    authorizations: [{ team_id: "T2", user_id: "B2", is_bot: true }],
    event_id: "Ev-own",
    event: { type: "message", team: "T2" },
  });
  expect([
    await deliver(written),
    await deliver(submitted, "interactivity-webhook"),
    await deliver(pressed, "interactivity-webhook"),
    await deliver(own),
  ]).toEqual([200, 200, 200, 200]);

  for (const mind of ["iterate.ada.example", "iterate.bob.example"])
    await (env.OUTBOX.get(env.OUTBOX.idFromName(mind)) as unknown as Outbox).alarm();
  const got = async (mind: typeof ada) =>
    (
      await Promise.all(mind.statements.map((signed) => statementOf(signed, cloudKey.publicKey)))
    ).map((statement) => {
      const { teamId, body } = statement!.payload as {
        teamId: string;
        body: { event_id?: string; trigger_id?: string };
      };
      return [statement!.path, teamId, body.event_id || body.trigger_id];
    });
  expect(await got(ada)).toEqual([
    ["/integrations/slack/T1", "T1", "Ev-shared"],
    ["/integrations/slack/T1", "T1", "tr-shared"],
    ["/integrations/slack/T1", "T1", "tr-pressed"],
  ]);
  expect(await got(bob)).toEqual([["/integrations/slack/T2", "T2", "Ev-own"]]);
  // who pressed reaches ada's deployment as Slack sent it, beside the installation's workspace
  const press = await statementOf(ada.statements[2]!, cloudKey.publicKey);
  expect(press!.payload).toMatchObject({
    teamId: "T1",
    body: { type: "block_actions", user: { id: "U7", team_id: "T2" } },
  });
});

test("a delivery is kept and answered while another object of the Cloud fails, and reaches its deployment when that object answers again", async () => {
  const { env, cloudKey, deployment, provider, proofFor } = await setup();
  const ada = await deployment("iterate.ada.example");
  await ada.ask("token", {
    grant_type: "authorization_code",
    code: "c0de",
    cloud_proof: await proofFor("iterate.ada.example", "c0de"),
  });
  const body = JSON.stringify({ action: "opened", installation: { id: 7 } });
  const post = (delivery: string) =>
    cloud.fetch(
      new Request(`${CLOUD}/clients/github/webhook`, {
        method: "POST",
        headers: {
          "x-hub-signature-256": `sha256=${createHmac("sha256", "webhook-secret").update(body).digest("hex")}`,
          "x-github-event": "pull_request",
          "x-github-delivery": delivery,
        },
        body,
      }),
      env,
    );
  const inbox = env.OUTBOX.get(env.OUTBOX.idFromName("inbox\ngithub")) as unknown as Outbox;
  const outbox = env.OUTBOX.get(env.OUTBOX.idFromName("iterate.ada.example")) as unknown as Outbox;
  const passOn = env.OUTBOX.get(env.OUTBOX.idFromName("pass-on\ngithub")) as unknown as Outbox;

  // THE ONE OBJECT THAT KNOWS WHICH DEPLOYMENTS CONNECTED WHAT fails inside the platform, as it did
  // on production for two minutes on 2026-11-11: every call of it throws
  const routes = env.ROUTES.get(env.ROUTES.idFromName("routes")) as unknown as Routes;
  const mindsOf = routes.mindsOf.bind(routes);
  routes.mindsOf = async () => {
    throw new Error("internal error; reference = test");
  };
  // the provider hears 200 all the same, and nothing is lost: the delivery waits in the inbox
  expect(await post("d-1")).toMatchObject({ status: 200 });
  expect(await post("d-2")).toMatchObject({ status: 200 });
  await inbox.alarm();
  // what goes to the platform the app served before does not wait for that object
  expect([await held(inbox), await held(passOn), await held(outbox)]).toEqual([2, 2, 0]);
  await inbox.alarm();
  expect([await held(inbox), await held(outbox)]).toEqual([2, 0]);

  // the object answers again: both deliveries go on, in the order they came, each once, when the
  // time of the row that waited comes (an alarm before it tries nothing)
  routes.mindsOf = mindsOf;
  await inbox.alarm();
  expect([await held(inbox), await held(outbox)]).toEqual([2, 0]);
  vi.useFakeTimers({ toFake: ["Date"] });
  try {
    vi.setSystemTime(Date.now() + 5 * 60_000);
    await inbox.alarm();
  } finally {
    vi.useRealTimers();
  }
  expect([await held(inbox), await held(outbox)]).toEqual([0, 2]);
  await inbox.alarm();
  expect(await held(outbox)).toBe(2);
  await outbox.alarm();
  const statements = await Promise.all(
    ada.statements.map((signed) => statementOf(signed, cloudKey.publicKey)),
  );
  expect(statements).toMatchObject([
    { path: "/integrations/github/7", payload: { delivery: { id: "d-1" } } },
    { path: "/integrations/github/7", payload: { delivery: { id: "d-2" } } },
  ]);
  // and a delivery GitHub sends again while the first waits is still relayed once
  expect(await (await post("d-2")).json()).toEqual({ accepted: true, redelivery: true });
  await inbox.alarm();
  expect(await held(outbox)).toBe(0);
  expect(provider.tokenRequests).toHaveLength(1);
});

test("a deployment whose outbox takes nothing holds its own account's deliveries, in order, and no other deployment's; an arrival does not bring its next try forward", async () => {
  const { env, cloudKey, deployment, proofFor } = await setup();
  // ada connected installation 7 (and 8, an organization of hers); bob's deployment holds
  // installation 10, which is not ada's
  const ada = await deployment("iterate.ada.example");
  await ada.ask("token", {
    grant_type: "authorization_code",
    code: "c0de",
    cloud_proof: await proofFor("iterate.ada.example", "c0de"),
  });
  const bob = await deployment("iterate.bob.example");
  await (env.ROUTES.get(env.ROUTES.idFromName("routes")) as unknown as Routes).claim(
    "github",
    "u-bob",
    ["10"],
    "iterate.bob.example",
  );
  const post = (delivery: string, installation: number) => {
    const body = JSON.stringify({ action: "opened", installation: { id: installation } });
    return cloud.fetch(
      new Request(`${CLOUD}/clients/github/webhook`, {
        method: "POST",
        headers: {
          "x-hub-signature-256": `sha256=${createHmac("sha256", "webhook-secret").update(body).digest("hex")}`,
          "x-github-event": "pull_request",
          "x-github-delivery": delivery,
        },
        body,
      }),
      env,
    );
  };
  const inbox = env.OUTBOX.get(env.OUTBOX.idFromName("inbox\ngithub")) as unknown as Outbox;
  const adas = env.OUTBOX.get(env.OUTBOX.idFromName("iterate.ada.example")) as unknown as Outbox;
  const bobs = env.OUTBOX.get(env.OUTBOX.idFromName("iterate.bob.example")) as unknown as Outbox;
  /** The deliveries a deployment took, by GitHub's id, in the order it took them. */
  const took = async (mind: typeof ada, outbox: Outbox) => {
    await outbox.alarm();
    const statements = await Promise.all(
      mind.statements.map((signed) => statementOf(signed, cloudKey.publicKey)),
    );
    return statements.map(
      (statement) => (statement!.payload as { delivery: { id: string } }).delivery.id,
    );
  };

  // ADA'S OUTBOX TAKES NOTHING, each time it is asked: an object of the Cloud that fails for one
  // deployment alone
  const put = adas.put.bind(adas);
  let asked = 0;
  adas.put = async () => {
    asked += 1;
    throw new Error("the outbox of iterate.ada.example takes nothing");
  };
  vi.useFakeTimers({ toFake: ["Date"] });
  vi.spyOn(console, "warn").mockImplementation(() => {});
  try {
    const began = Date.now();
    await post("a-1", 7);
    await post("b-1", 10);
    await post("a-2", 7);
    await inbox.alarm();
    // bob's delivery went on, past ada's that did not; ada's second waits behind her first
    expect(await took(bob, bobs)).toEqual(["b-1"]);
    expect(asked).toBe(1);

    // a new delivery for bob a moment later goes on too, and ada's is not tried for it: its
    // next try keeps its own time
    vi.setSystemTime(began + 500);
    await post("b-2", 10);
    await inbox.alarm();
    expect(await took(bob, bobs)).toEqual(["b-1", "b-2"]);
    expect(asked).toBe(1);

    // its time comes, the outbox still takes nothing: tried once more, and later the next time
    vi.setSystemTime(began + 2_500);
    await inbox.alarm();
    expect(asked).toBe(2);
    vi.setSystemTime(began + 5_000);
    await inbox.alarm();
    expect(asked).toBe(2);

    // ada's outbox takes again: her deliveries go on in the order they came, each once
    adas.put = put;
    vi.setSystemTime(began + 60_000);
    await inbox.alarm();
    expect(await took(ada, adas)).toEqual(["a-1", "a-2"]);
    // and nothing of hers waits aside any more: the next one goes straight on
    await post("a-3", 7);
    await inbox.alarm();
    expect(await took(ada, adas)).toEqual(["a-1", "a-2", "a-3"]);
    expect(await held(inbox)).toBe(0);
  } finally {
    vi.useRealTimers();
    vi.restoreAllMocks();
  }
});

test("a delivery that comes while the inbox hands others over is not left for a later alarm: the alarm it asked for stays", async () => {
  const { env, deployment, proofFor } = await setup();
  const ada = await deployment("iterate.ada.example");
  await ada.ask("token", {
    grant_type: "authorization_code",
    code: "c0de",
    cloud_proof: await proofFor("iterate.ada.example", "c0de"),
  });
  const post = (delivery: string) => {
    const body = JSON.stringify({ action: "opened", installation: { id: 7 } });
    return cloud.fetch(
      new Request(`${CLOUD}/clients/github/webhook`, {
        method: "POST",
        headers: {
          "x-hub-signature-256": `sha256=${createHmac("sha256", "webhook-secret").update(body).digest("hex")}`,
          "x-github-event": "pull_request",
          "x-github-delivery": delivery,
        },
        body,
      }),
      env,
    );
  };
  const inbox = env.OUTBOX.get(env.OUTBOX.idFromName("inbox\ngithub")) as unknown as Outbox;
  const adas = env.OUTBOX.get(env.OUTBOX.idFromName("iterate.ada.example")) as unknown as Outbox;
  const passOn = env.OUTBOX.get(env.OUTBOX.idFromName("pass-on\ngithub")) as unknown as Outbox;
  const { storage } = (inbox as unknown as { ctx: DurableObjectState }).ctx;
  const waiting = async (prefix: string) => (await storage.list({ prefix })).size;

  // GitHub sends a second delivery while the inbox hands the first to ada's outbox: an await on
  // another object lets it in, after the queue of what is passed on has been handed over
  const put = adas.put.bind(adas);
  adas.put = async (mind, signed) => {
    adas.put = put;
    await post("d-2");
    return put(mind, signed);
  };
  await post("d-1");
  await inbox.alarm();
  // the relays of both went on; the second's pass-on row keeps its alarm for now (`#alarmBy`)
  expect([await held(adas), await held(passOn), await waiting("hand:")]).toEqual([2, 1, 1]);
  expect(await storage.getAlarm()).toBeLessThanOrEqual(Date.now());
  await inbox.alarm();
  expect([await held(passOn), await waiting("hand:")]).toEqual([2, 0]);
  // with nothing left, the alarm is the sweep of the ids a day on
  expect(await storage.getAlarm()).toBeGreaterThan(Date.now() + 23 * 60 * 60_000);
});

test("a deployment's outbox holds a thousand rows and sixteen mebibytes at most: the oldest go, with a line in the log", async () => {
  const { env, deployment, proofFor } = await setup();
  const ada = await deployment("ada.example");
  await ada.ask("token", {
    grant_type: "authorization_code",
    code: "c0de",
    cloud_proof: await proofFor("ada.example", "c0de"),
  });
  const post = (delivery: string, filler = "", event = "pull_request") => {
    const action = event === "installation" ? "deleted" : "opened";
    const body = JSON.stringify({ action, installation: { id: 7 }, filler });
    return cloud.fetch(
      new Request(`${CLOUD}/clients/github/webhook`, {
        method: "POST",
        headers: {
          "x-hub-signature-256": `sha256=${createHmac("sha256", "webhook-secret").update(body).digest("hex")}`,
          "x-github-event": event,
          "x-github-delivery": delivery,
        },
        body,
      }),
      env,
    );
  };
  const inbox = env.OUTBOX.get(env.OUTBOX.idFromName("inbox\ngithub")) as unknown as Outbox;
  const adas = env.OUTBOX.get(env.OUTBOX.idFromName("ada.example")) as unknown as Outbox;
  const { storage } = (adas as unknown as { ctx: DurableObjectState }).ctx;
  const held = async () => (await storage.list({ prefix: "item:" })).size;
  /** The deliveries ada's deployment takes when it is back, by GitHub's id. */
  const took = async () => {
    ada.statements.length = 0;
    await adas.alarm();
    return ada.statements.map(
      (signed) =>
        (JSON.parse(signed.statement) as { payload: { delivery: { id: string } } }).payload.delivery
          .id,
    );
  };
  const over = vi.spyOn(console, "warn").mockImplementation(() => {});
  /** The lines about queues that are over, each with the rows and bytes that went. */
  const lines = () =>
    over.mock.calls
      .map(([line]) => line as { event: string; queue: string; mind?: string; rows: number })
      .filter(({ event }) => event === "cloud.queue-over");
  type Storage = DurableObjectState["storage"];
  const rowsOf = async (from: Storage, prefix: string) => [
    ...(await from.list<{ bytes: number }>({ prefix })).values(),
  ];
  /** A QUEUE MADE LONG WITH NO DELIVERY: copies of one of its rows, written behind the others as
   *  the object numbers them. A thousand real deliveries cost this test seconds. */
  const fill = async (to: Storage, prefix: string, row: object, count: number) => {
    let next = (await to.get<number>("next")) || 0;
    const rows: Record<string, unknown> = {};
    for (let n = 0; n < count; n += 1)
      rows[`${prefix}${String((next += 1)).padStart(12, "0")}`] = row;
    await to.put({ ...rows, next });
  };
  const empty = async (from: Storage, prefix: string) =>
    from.delete([...(await from.list({ prefix })).keys()]);
  const inboxes = (inbox as unknown as { ctx: DurableObjectState }).ctx.storage;
  try {
    // what waited before this test is taken first
    await adas.alarm();
    expect(await held()).toBe(0);

    // BY COUNT: ada's deployment is away, and its outbox holds two rows more than the bound when
    // one more delivery comes: the three oldest go, in one line
    await post("d-1");
    await inbox.alarm();
    const [small] = await rowsOf(storage, "item:");
    await fill(storage, "item:", small!, QUEUE_MAX_ROWS + 1);
    await post("d-last");
    await inbox.alarm();
    expect(await held()).toBe(QUEUE_MAX_ROWS);
    expect(lines()).toMatchObject([{ queue: "item", mind: "ada.example", rows: 3 }]);
    // the line says nothing of what a delivery held
    expect(JSON.stringify(over.mock.calls)).not.toContain("opened");
    await empty(storage, "item:");

    // BY BYTES: a row counts the bytes of what it holds, and four rows of 4 MiB with a delivery
    // before them and one after are more than 16 MiB, so the two oldest go
    over.mockClear();
    await post("big-1", "x".repeat(100 * 1024));
    await inbox.alarm();
    const [big] = await rowsOf(storage, "item:");
    expect(big!.bytes).toBeGreaterThan(100 * 1024);
    await fill(storage, "item:", { ...big, bytes: 4 * 1024 * 1024 }, 4);
    await post("big-2", "x".repeat(100 * 1024));
    await inbox.alarm();
    expect(await held()).toBe(4);
    expect(lines()).toMatchObject([
      { queue: "item", mind: "ada.example", rows: 2, bytes: big!.bytes + 4 * 1024 * 1024 },
    ]);
    expect((await took()).at(-1)).toBe("big-2");

    // AN INBOX'S OWN QUEUES have the same bounds: nothing hands these deliveries on
    over.mockClear();
    await post("late-1");
    const [relay] = await rowsOf(inboxes, "item:");
    const [handed] = await rowsOf(inboxes, "hand:");
    await fill(inboxes, "item:", relay!, QUEUE_MAX_ROWS + 1);
    await fill(inboxes, "hand:", handed!, QUEUE_MAX_ROWS + 1);
    await post("late-2");
    expect(await inboxes.list({ prefix: "item:" })).toMatchObject({ size: QUEUE_MAX_ROWS });
    expect(await inboxes.list({ prefix: "hand:" })).toMatchObject({ size: QUEUE_MAX_ROWS });
    expect(lines()).toMatchObject([
      { queue: "hand", client: "github", rows: 3 },
      { queue: "item", client: "github", rows: 3 },
    ]);
    await empty(inboxes, "item:");
    await empty(inboxes, "hand:");

    // GITHUB'S WORD THAT THE INSTALLATION IS GONE is not over, however much comes after it: the
    // three oldest of the others go, and it stays to be handed on, which ends ada's claim
    await post("removed", "", "installation");
    await fill(inboxes, "item:", relay!, QUEUE_MAX_ROWS + 2);
    await post("after");
    const waiting = await rowsOf(inboxes, "item:");
    expect(waiting).toHaveLength(QUEUE_MAX_ROWS + 1);
    expect(waiting[0]).toMatchObject({ relay: { ended: true } });
  } finally {
    vi.restoreAllMocks();
  }
});

test("what an inbox cannot pass on holds no relay, and a relay that waited a day is dropped with a line in the log", async () => {
  const { env, deployment, proofFor } = await setup();
  const ada = await deployment("iterate.ada.example");
  await ada.ask("token", {
    grant_type: "authorization_code",
    code: "c0de",
    cloud_proof: await proofFor("iterate.ada.example", "c0de"),
  });
  const post = (delivery: string) => {
    const body = JSON.stringify({ action: "opened", installation: { id: 7 } });
    return cloud.fetch(
      new Request(`${CLOUD}/clients/github/webhook`, {
        method: "POST",
        headers: {
          "x-hub-signature-256": `sha256=${createHmac("sha256", "webhook-secret").update(body).digest("hex")}`,
          "x-github-event": "pull_request",
          "x-github-delivery": delivery,
        },
        body,
      }),
      env,
    );
  };
  const inbox = env.OUTBOX.get(env.OUTBOX.idFromName("inbox\ngithub")) as unknown as Outbox;
  const adas = env.OUTBOX.get(env.OUTBOX.idFromName("iterate.ada.example")) as unknown as Outbox;
  const passOn = env.OUTBOX.get(env.OUTBOX.idFromName("pass-on\ngithub")) as unknown as Outbox;
  /** The deliveries ada's deployment took, by GitHub's id. Read from each statement's text: one
   *  that the Cloud signed a day ago has expired by this test's clock. */
  const took = async () => {
    await adas.alarm();
    return ada.statements.map(
      (signed) =>
        (JSON.parse(signed.statement) as { payload: { delivery: { id: string } } }).payload.delivery
          .id,
    );
  };
  const warned = vi.spyOn(console, "warn").mockImplementation(() => {});
  const dropped = vi.spyOn(console, "error").mockImplementation(() => {});
  vi.useFakeTimers({ toFake: ["Date"] });
  try {
    const began = Date.now();
    // the object that passes deliveries on to the platform before takes nothing: the relay to
    // ada's deployment does not wait for it
    const pass = passOn.pass.bind(passOn);
    passOn.pass = async () => {
      throw new Error("the pass-on outbox takes nothing");
    };
    await post("d-1");
    await inbox.alarm();
    expect(await took()).toEqual(["d-1"]);
    passOn.pass = pass;

    // ada's outbox takes nothing for more than a day: her delivery waits aside, is tried again
    // later each time, and is dropped then
    const put = adas.put.bind(adas);
    adas.put = async () => {
      throw new Error("the outbox of iterate.ada.example takes nothing");
    };
    await post("d-2");
    await inbox.alarm();
    for (const minutes of [1, 10, 60, 600]) {
      vi.setSystemTime(began + minutes * 60_000);
      await inbox.alarm();
    }
    expect(dropped).not.toHaveBeenCalled();
    vi.setSystemTime(began + 24 * 60 * 60_000 + 1_000);
    await inbox.alarm();
    expect(dropped.mock.calls).toMatchObject([
      [{ event: "cloud.inbox-dropped", mind: "iterate.ada.example" }],
    ]);
    expect(warned.mock.calls.at(-1)).toMatchObject([
      { event: "cloud.inbox-waits", mind: "iterate.ada.example" },
    ]);

    // her account waits no more: the next delivery goes straight on
    adas.put = put;
    await post("d-3");
    await inbox.alarm();
    expect(await took()).toEqual(["d-1", "d-3"]);
    const state = (inbox as unknown as { ctx: DurableObjectState }).ctx;
    expect([...(await state.storage.list({ prefix: "stuck\n" })).keys()]).toEqual([]);
    expect([...(await state.storage.list({ prefix: "wait\n" })).keys()]).toEqual([]);
  } finally {
    vi.useRealTimers();
    vi.restoreAllMocks();
  }
});

test("with the gate on, a mind that is not enrolled connects nothing, gets no token and no ask, reads why on the page, and its deliveries wait; it may still read its status and say its word; once enrolled, all of it works", async () => {
  const { env, deployment, proofFor } = await setup();
  const { mindKey } = await withMindAuth(env);
  const hostname = `iterate-${crypto.randomUUID().slice(0, 8)}.example`;
  const ada = await deployment(hostname, { log: true });
  const id = ada.log!.mind;
  const who = `${hostname} (mind ${id})`;
  ada.letsMindIn = true;
  const enrolled = new Set<string>();
  env.ENROLMENTS = { enrolled: async (mind) => enrolled.has(mind) };
  // the person's press on the page comes first (`proofFor`), while the gate only logs
  const proofs = new Map<string, string>();
  for (const code of ["code-1", "code-2", "code-3"])
    proofs.set(code, await proofFor(hostname, code));
  const exchange = (code: string) =>
    ada.ask("token", { grant_type: "authorization_code", code, cloud_proof: proofs.get(code)! });
  // "log", the default: served, so ada connects
  expect(await exchange("code-1")).toMatchObject({ status: 200 });

  env.CLOUD_ENROLMENT = "on";
  const refusal = async (answer: Response) => [answer.status, await answer.json()];
  expect(await refusal(await exchange("code-2"))).toEqual([
    403,
    {
      error: `${who} is not enrolled in iterate Cloud: nothing is connected. Its owner enrols at cloud.iterate.com, then connects again.`,
    },
  ]);
  expect(
    await refusal(await ada.ask("installation-token", { installationId: "7" }, "json")),
  ).toEqual([
    403,
    {
      error: `${who} is not enrolled in iterate Cloud, so the Cloud gives it no new token. The connection is kept: after its owner enrols at cloud.iterate.com, the next refresh works.`,
    },
  ]);
  expect(await refusal(await ada.ask("ask/reply", {}, "json"))).toEqual([
    403,
    {
      error: `${who} is not enrolled in iterate Cloud, so the Cloud asks nothing for it. Its owner enrols at cloud.iterate.com.`,
    },
  ]);
  // the page before the provider says it, for the person's sake
  const state = `${base64url(Buffer.from(`https://${hostname}/secrets/oauth/callback`))}.nonce.1`;
  const consent = `${github.authorizationEndpoint}?client_id=${github.clientId}&redirect_uri=${encodeURIComponent(`${CLOUD}/clients/github/callback`)}&state=${state}`;
  const page = await cloud.fetch(
    get(`/clients/github/begin?to=${encodeURIComponent(consent)}`),
    env,
  );
  expect(await refusal(page)).toEqual([
    403,
    {
      error: `${hostname} is not enrolled in iterate Cloud, so it cannot connect an account through it. Its owner enrols at cloud.iterate.com, then starts again from ${hostname}.`,
    },
  ]);
  // what a mind may always ask
  expect(await saysMindForm(ada, true)).toMatchObject({ status: 200 });
  // its deliveries wait, and its status says why
  const outbox = env.OUTBOX.get(env.OUTBOX.idFromName(hostname)) as unknown as Outbox;
  await githubDelivery(env, "d-1");
  await outbox.alarm();
  expect({ took: ada.statements.length, held: await held(outbox) }).toEqual({ took: 0, held: 1 });
  expect(await (await statusOf(ada)).json()).toMatchObject({
    minds: [
      {
        mind: hostname,
        held: 1,
        lastRefused: {
          reason: `${who} is not enrolled in iterate Cloud, so its deliveries wait. Its owner enrols at cloud.iterate.com.`,
          status: 403,
        },
      },
    ],
  });

  // iterate enrols ada: within a minute, all of it works, and what waited arrives
  enrolled.add(id);
  vi.useFakeTimers({ toFake: ["Date"] });
  try {
    vi.setSystemTime(Date.now() + 61_000);
    expect(await exchange("code-3")).toMatchObject({ status: 200 });
    expect(await ada.ask("installation-token", { installationId: "7" }, "json")).toMatchObject({
      ok: true,
    });
    await outbox.alarm();
    expect(
      await Promise.all(ada.statements.splice(0).map((one) => statementOf(one, mindKey.publicKey))),
    ).toMatchObject([{ mind: hostname, about: ["cloud:github:d-1"] }]);
  } finally {
    vi.useRealTimers();
  }
});

test("in the default log mode a mind that is not enrolled is served, and the Cloud logs it once a minute; the Cloud's own mind is served by its name; a mind with no log is refused when on; a read that fails refuses with 503 when on and serves when not", async () => {
  const { env, deployment, proofFor } = await setup();
  await withMindAuth(env);
  let fails = false;
  const asked: string[] = [];
  env.ENROLMENTS = {
    enrolled: async (mind) => {
      asked.push(mind);
      if (fails) throw new Error("the auth Worker does not answer");
      return false;
    },
  };
  const hostname = `iterate-${crypto.randomUUID().slice(0, 8)}.example`;
  const ada = await deployment(hostname, { log: true });
  const warn = vi.spyOn(console, "warn");
  const notEnrolled = () =>
    warn.mock.calls.filter(
      ([line]) => (line as { event?: string })?.event === "cloud.not-enrolled",
    );
  for (const code of ["code-1", "code-2"])
    expect(
      await ada.ask("token", {
        grant_type: "authorization_code",
        code,
        cloud_proof: await proofFor(hostname, code),
      }),
    ).toMatchObject({ status: 200 });
  expect(notEnrolled()).toEqual([
    // the page before the provider reads nothing in this mode; the second minute has not come
    [
      {
        event: "cloud.not-enrolled",
        mind: hostname,
        id: ada.log!.mind,
        gate: "connect",
        refused: false,
      },
    ],
  ]);
  // the answer is kept a minute for each id
  expect(asked).toEqual([ada.log!.mind]);

  // the Cloud's own mind cannot enrol in its own Cloud: it is served by its name, with no read
  env.CLOUD_ENROLMENT = "on";
  const own = await deployment(env.MIND_HOSTNAME!);
  expect(
    await own.ask("token", {
      grant_type: "authorization_code",
      code: "code-own",
      cloud_proof: await proofFor(env.MIND_HOSTNAME!, "code-own"),
    }),
  ).toMatchObject({ status: 200 });
  expect(asked).toHaveLength(1);

  // a mind that serves no log has no id to enrol
  const bob = await deployment("iterate.bob.example");
  const refused = await bob.ask("installation-token", { installationId: "7" }, "json");
  expect([refused.status, await refused.json()]).toEqual([
    403,
    {
      error:
        "iterate.bob.example 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 cloud.iterate.com.",
    },
  ]);

  // a read that fails is not kept: refused with 503 when on, served when not
  const eve = await deployment(`iterate-${crypto.randomUUID().slice(0, 8)}.example`, { log: true });
  fails = true;
  const unread = await eve.ask("ask/reply", {}, "json");
  expect([unread.status, await unread.json()]).toEqual([
    503,
    {
      error:
        "iterate Cloud cannot read its enrolments now (the auth Worker does not answer). Nothing changed: ask again later.",
    },
  ]);
  env.CLOUD_ENROLMENT = "log";
  const error = vi.spyOn(console, "error");
  for (let ask = 0; ask < 2; ask++)
    expect(await eve.ask("ask/reply", {}, "json")).not.toMatchObject({ status: 503 });
  expect(asked).toEqual([ada.log!.mind, eve.log!.mind, eve.log!.mind, eve.log!.mind]);
  // a failed read is logged once a minute for each hostname, as `cloud.not-enrolled` is: the
  // first was in "on" mode, above
  expect(
    error.mock.calls.filter(
      ([line]) => (line as { event?: string })?.event === "cloud.enrolment-unread",
    ),
  ).toEqual([]);
  warn.mockRestore();
  error.mockRestore();
});

test("a member of a Slack workspace who is no admin gets no token and none of its events, and takes none from the deployment an admin connected", async () => {
  const { env, deployment, provider, proofFor } = await setup();
  const install = async (one: Awaited<ReturnType<typeof deployment>>, mind: string) =>
    one.ask("slack:token", {
      grant_type: "authorization_code",
      code: `code-${mind}`,
      cloud_proof: await proofFor(mind, `code-${mind}`, "slack"),
    });
  const connected = () =>
    (env.ROUTES.get(env.ROUTES.idFromName("routes")) as unknown as Routes).mindsOf("slack", "T1");

  // an admin connects the workspace to ada's deployment
  const ada = await deployment("iterate.ada.example");
  expect(await install(ada, "iterate.ada.example")).toMatchObject({ status: 200 });
  expect(await connected()).toEqual(["iterate.ada.example"]);

  // a member installs the same app for a deployment of their own: Slack let them, but the bot
  // token is the workspace's, so the Cloud hands over nothing of Slack's answer, and the
  // workspace's events are not theirs
  provider.slackInstaller = { id: "U2", team_id: "T1", is_admin: false, is_owner: false };
  const mallory = await deployment("iterate.mallory.example");
  const refused = await install(mallory, "iterate.mallory.example");
  expect(refused).toMatchObject({ status: 403 });
  expect(await refused.text()).toBe(
    JSON.stringify({ error: "Only an admin or an owner of a Slack workspace can connect it." }),
  );
  expect(await connected()).toEqual(["iterate.ada.example"]);

  // the same member installs it again for ada's deployment: no token, and what the admin
  // connected stays
  expect(await install(ada, "iterate.ada.example")).toMatchObject({ status: 403 });
  expect(await connected()).toEqual(["iterate.ada.example"]);

  // an owner who is no admin connects, and a person of another workspace does not
  provider.slackInstaller = { id: "U3", team_id: "T1", is_admin: false, is_owner: true };
  const grace = await deployment("iterate.grace.example");
  await install(grace, "iterate.grace.example");
  expect(await connected()).toEqual(["iterate.ada.example", "iterate.grace.example"]);
  provider.slackInstaller = { id: "U4", team_id: "T9", is_admin: true, is_owner: true };
  const eve = await deployment("iterate.eve.example");
  expect(await install(eve, "iterate.eve.example")).toMatchObject({ status: 403 });
  expect(await connected()).toEqual(["iterate.ada.example", "iterate.grace.example"]);
});

test("an installation's token is minted with the App's key, for a deployment that connected it alone", async () => {
  const { deployment, provider, proofFor } = await setup();
  const ada = await deployment("iterate.ada.example");
  await ada.ask("token", {
    grant_type: "authorization_code",
    code: "c0de",
    cloud_proof: await proofFor("iterate.ada.example", "c0de"),
  });
  const minted = await ada.ask("installation-token", { installationId: "7" }, "json");
  expect(await minted.json()).toEqual({ token: "ghs_installation", expires_at: "later" });
  const [, payload] = provider.appJwts[0]!.split(".");
  expect(JSON.parse(Buffer.from(payload!, "base64url").toString())).toMatchObject({ iss: "42" });

  const eve = await deployment("iterate.eve.example");
  const refused = await eve.ask("installation-token", { installationId: "7" }, "json");
  expect([refused.status, await refused.json()]).toEqual([
    403,
    { error: "iterate.eve.example has not connected installation 7" },
  ]);
  expect(provider.appJwts).toHaveLength(1);

  // A DEPLOYMENT LETS GO OF ONE ACCOUNT: no token is minted for it any more, a new consent of the
  // same person does not bring it back, and only its own word `again` does. Nobody lets go for
  // another deployment.
  const release = (who: typeof ada, fields: Record<string, unknown>) =>
    who.ask("ask/release", fields as Record<string, string>, "json");
  expect(await (await release(eve, { account: "7" })).json()).toEqual({
    account: "7",
    connected: false,
  });
  expect(await ada.ask("installation-token", { installationId: "7" }, "json")).toMatchObject({
    ok: true,
  });
  expect(await (await release(ada, { account: "7" })).json()).toEqual({
    account: "7",
    connected: false,
  });
  const connect = async (code: string) =>
    ada.ask("token", {
      grant_type: "authorization_code",
      code,
      cloud_proof: await proofFor("iterate.ada.example", code),
    });
  await connect("c0de-2");
  expect(await ada.ask("installation-token", { installationId: "7" }, "json")).toMatchObject({
    status: 403,
  });
  await release(ada, { account: "7", again: true });
  await connect("c0de-3");
  expect(await ada.ask("installation-token", { installationId: "7" }, "json")).toMatchObject({
    ok: true,
  });
  expect(await release(ada, { account: "" })).toMatchObject({ status: 400 });
});

test("with an age set, a GitHub claim that no refresh made again gets no token and no delivery, until a refresh makes it again", async () => {
  const { env, deployment, provider, proofFor } = await setup();
  const ada = await deployment("iterate.ada.example");
  const connected = await ada.ask("token", {
    grant_type: "authorization_code",
    code: "c0de",
    cloud_proof: await proofFor("iterate.ada.example", "c0de"),
  });
  const { refresh_token: sealed } = (await connected.json()) as { refresh_token: string };
  const token = () => ada.ask("installation-token", { installationId: "7" }, "json");
  // in this test a namespace answers the object itself, not a stub (namespaceOf)
  const outbox = env.OUTBOX.get(env.OUTBOX.idFromName("iterate.ada.example")) as unknown as Outbox;
  ada.down = true;
  /** One delivery about installation 7; answers how many statements the Cloud then holds for ada. */
  const deliver = async (delivery: string) => {
    const body = JSON.stringify({ action: "opened", installation: { id: 7 } });
    await cloud.fetch(
      new Request(`${CLOUD}/clients/github/webhook`, {
        method: "POST",
        headers: {
          "x-hub-signature-256": `sha256=${createHmac("sha256", "webhook-secret").update(body).digest("hex")}`,
          "x-github-event": "pull_request",
          "x-github-delivery": delivery,
        },
        body,
      }),
      env,
    );
    await handedOver(env, "github");
    return held(outbox);
  };
  const DAY = 24 * 60 * 60_000;
  const connectedAt = Date.now();
  vi.useFakeTimers({ toFake: ["Date"] });
  try {
    // NO AGE IS SET: a claim of any age stands, as before
    vi.setSystemTime(connectedAt + 400 * DAY);
    expect(await token()).toMatchObject({ ok: true });
    expect(await deliver("d-1")).toBe(1);

    // SEVEN DAYS ARE SET: the claim, 400 days old, gets no token and no delivery
    env.GITHUB_CLAIM_DAYS = "7";
    const refused = await token();
    expect([refused.status, await refused.json()]).toEqual([
      403,
      {
        error:
          "iterate.ada.example connected installation 7 too long ago: the grant of the person who connected it has not refreshed for 7 days. Refresh that grant, or connect GitHub again.",
      },
    ]);
    expect(provider.appJwts).toHaveLength(1);
    expect(await deliver("d-2")).toBe(1);

    // A REFRESH OF THE PERSON'S GRANT MAKES THE CLAIM AGAIN: GitHub says she still owns the account
    const refreshed = await ada.ask("token", {
      grant_type: "refresh_token",
      refresh_token: sealed,
    });
    expect(refreshed).toMatchObject({ status: 200 });
    expect(await token()).toMatchObject({ ok: true });
    expect(await deliver("d-3")).toBe(2);
    // six days later it still stands, and on the eighth day it does not
    vi.setSystemTime(connectedAt + 406 * DAY);
    expect(await token()).toMatchObject({ ok: true });
    vi.setSystemTime(connectedAt + 408 * DAY);
    expect(await token()).toMatchObject({ status: 403 });
    expect(await deliver("d-4")).toBe(2);
    // the route itself stays: the age ends no claim, a refresh brings its tokens and events back
    const routes = env.ROUTES.get(env.ROUTES.idFromName("routes")) as unknown as Routes;
    expect(await routes.mindsOf("github", "7")).toEqual(["iterate.ada.example"]);
  } finally {
    vi.useRealTimers();
  }
});

test("with an age set, a mailbox's claim that no refresh made again gets no push, until a refresh of a grant that reads the mailbox makes it again", async () => {
  const { env, deployment, provider, proofFor } = await setup();
  provider.googleScope = "openid";
  const ada = await deployment("iterate.ada.example");
  const connected = await ada.ask("google:token", {
    grant_type: "authorization_code",
    code: "g-1",
    cloud_proof: await proofFor("iterate.ada.example", "g-1", "google"),
  });
  const { refresh_token: sealed } = (await connected.json()) as { refresh_token: string };
  const refresh = () =>
    ada.ask("google:token", { grant_type: "refresh_token", refresh_token: sealed });
  // in this test a namespace answers the object itself, not a stub (namespaceOf)
  const outbox = env.OUTBOX.get(env.OUTBOX.idFromName("iterate.ada.example")) as unknown as Outbox;
  // what the Cloud told the deployment at the connect is taken first: this test counts pushes
  await outbox.alarm();
  ada.down = true;
  /** One push about ada's mailbox; answers how many statements the Cloud then holds for ada. */
  const pushed = async (messageId: string) => {
    await gmailPush(env, { emailAddress: "ada@example.com", historyId: 1 }, messageId);
    await handedOver(env, "google");
    return held(outbox);
  };
  const DAY = 24 * 60 * 60_000;
  const connectedAt = Date.now();
  vi.useFakeTimers({ toFake: ["Date"] });
  try {
    // NO AGE IS SET: a claim of any age stands, and GitHub's age is not Google's
    vi.setSystemTime(connectedAt + 400 * DAY);
    expect(await pushed("m-1")).toBe(1);
    env.GITHUB_CLAIM_DAYS = "7";
    expect(await pushed("m-2")).toBe(2);

    // SEVEN DAYS ARE SET: the claim, 400 days old, gets no push
    env.GOOGLE_CLAIM_DAYS = "7";
    expect(await pushed("m-3")).toBe(2);
    // THE PERSON NARROWED THE GRANT, and it reads no mail now: its refresh makes no claim
    provider.gmailAddress = undefined;
    expect(await refresh()).toMatchObject({ status: 200 });
    expect(await pushed("m-4")).toBe(2);
    // A REFRESH OF A GRANT THAT READS THE MAILBOX makes the claim again
    provider.gmailAddress = "ada@example.com";
    expect(await refresh()).toMatchObject({ status: 200 });
    // (that refresh also told the deployment of its mailbox again: the word was a year old)
    expect(await pushed("m-5")).toBe(4);
    // six days later it still stands, and on the eighth day it does not
    vi.setSystemTime(connectedAt + 406 * DAY);
    expect(await pushed("m-6")).toBe(5);
    vi.setSystemTime(connectedAt + 408 * DAY);
    expect(await pushed("m-7")).toBe(5);
    // the route itself stays: the age ends no claim, a refresh brings its pushes back
    const routes = env.ROUTES.get(env.ROUTES.idFromName("routes")) as unknown as Routes;
    expect(await routes.mindsOf("google", "ada@example.com")).toEqual(["iterate.ada.example"]);
  } finally {
    vi.useRealTimers();
  }
});

test("the bot relays what a linked X account says to it, and that deployment alone answers as the bot", async () => {
  const { env, cloudKey, deployment, provider, proofFor } = await setup();
  // an operator's link starts X's consent as the bot's account; a link the Cloud did not make does not
  const link = await botLinkOf(env.CLOUD_KEY, CLOUD, "x");
  const consent = await cloud.fetch(new Request(link), env);
  const atX = new URL(consent.headers.get("location")!);
  expect(Object.fromEntries(atX.searchParams)).toMatchObject({
    client_id: "x-client",
    redirect_uri: `${CLOUD}/clients/x/callback`,
    scope: expect.stringContaining("dm.write"),
    code_challenge_method: "S256",
  });
  // the proof with its first character changed, never to itself: one proof in 64 starts with "_"
  const forged = link.replace(/proof=(.)/, (_, first) => `proof=${first === "_" ? "-" : "_"}`);
  expect(forged).not.toBe(link);
  expect(await cloud.fetch(new Request(forged), env)).toMatchObject({ status: 403 });
  const connected = await cloud.fetch(
    get(`/clients/x/callback?code=bot&state=${atX.searchParams.get("state")}`),
    env,
  );
  expect(await connected.text()).toContain("The bot is @iterate");
  expect(provider.tokenRequests[0]!.get("code_verifier")).toMatch(/^[\w-]{43}$/);
  // the same link again connects nobody: one link, one account
  expect(
    await cloud.fetch(
      get(`/clients/x/callback?code=bot&state=${atX.searchParams.get("state")}`),
      env,
    ),
  ).toMatchObject({ status: 403 });

  // ada links her X account, 111, from her deployment; eve links nothing
  const ada = await deployment("iterate.ada.example");
  const eve = await deployment("iterate.eve.example");
  const linked = await ada.ask("x:token", {
    grant_type: "authorization_code",
    code: "111",
    cloud_proof: await proofFor("iterate.ada.example", "111", "x"),
  });
  expect(linked).toMatchObject({ status: 200 });

  // two direct messages reach the bot: one from ada's account, one from an account nobody linked
  provider.dms.push(
    { id: "5", sender_id: "111", text: "hello bot", created_at: "t5" },
    { id: "6", sender_id: "999", text: "who are you", created_at: "t6" },
  );
  // two mentions by ada: her own post, and her reply inside someone else's conversation
  provider.mentions.push(
    {
      id: "50",
      author_id: "111",
      text: "@iterate ship it",
      created_at: "t50",
      conversation_id: "50",
    },
    { id: "51", author_id: "111", text: "@iterate look", created_at: "t51", conversation_id: "9" },
    {
      id: "52",
      author_id: "111",
      text: "@iterate again",
      created_at: "t52",
      conversation_id: "52",
    },
  );
  // in this test a namespace answers the object itself, not a stub (namespaceOf)
  const outbox = env.OUTBOX.get(env.OUTBOX.idFromName("iterate.ada.example")) as unknown as Outbox;
  const bot = env.BOT.get(env.BOT.idFromName("x")) as unknown as Bot;
  await bot.alarm();
  await outbox.alarm();
  const statements = await Promise.all(
    ada.statements.map((signed) => statementOf(signed, cloudKey.publicKey)),
  );
  expect(statements).toMatchObject([
    {
      mind: "iterate.ada.example",
      path: "/integrations/x/111",
      type: "events.iterate.com/x/message-received",
      payload: {
        kind: "dm",
        id: "5",
        text: "hello bot",
        from: { xUserId: "111" },
        bot: { username: "iterate" },
        reply: `${CLOUD}/clients/x/ask/reply`,
      },
    },
    { path: "/integrations/x/111", payload: { kind: "mention", id: "50", ownThread: true } },
    { payload: { kind: "mention", id: "51", ownThread: false } },
    { payload: { kind: "mention", id: "52", ownThread: true } },
  ]);
  // a second read brings nothing twice
  await bot.alarm();
  await outbox.alarm();
  expect(ada.statements).toHaveLength(4);

  // X PUSHES: at its first alarm the bot registered the app's webhook here and subscribed its own
  // account to mentions and direct messages, once
  expect(provider).toMatchObject({
    webhooks: [{ id: "made-1", url: `${CLOUD}/clients/x/webhook` }],
    subscriptions: ["post.mention.create", "dm.received"].map((event_type) => ({
      event_type,
      filter: { user_id: "1" },
      webhook_id: "made-1",
    })),
  });
  expect(provider.subscriptions).toHaveLength(2);
  // X's check of the address: its token, keyed with the app's client secret. Never for what
  // could be a delivery, which is signed the same way.
  const keyed = (text: string) =>
    `sha256=${createHmac("sha256", "x-secret").update(text).digest("base64")}`;
  const crc = await cloud.fetch(get("/clients/x/webhook?crc_token=abc123"), env);
  expect(await crc.json()).toEqual({ response_token: keyed("abc123") });
  expect([
    (
      await cloud.fetch(
        get(`/clients/x/webhook?crc_token=${encodeURIComponent('{"data":{}}')}`),
        env,
      )
    ).status,
    (await cloud.fetch(get("/clients/github/webhook?crc_token=abc123"), env)).status,
  ]).toEqual([400, 404]);
  // a pushed mention and a pushed direct message go the same way as ones the read found
  const push = async (data: Record<string, unknown>, signature?: string) => {
    const body = JSON.stringify({ data });
    const pushed = await cloud.fetch(
      new Request(`${CLOUD}/clients/x/webhook`, {
        method: "POST",
        headers: { "x-twitter-webhooks-signature-oauth2": signature || keyed(body) },
        body,
      }),
      env,
    );
    await outbox.alarm();
    return { status: pushed.status, ...((await pushed.json()) as object) };
  };
  const mentioned = {
    event_uuid: "u-1",
    event_type: "post.mention.create",
    filter: { user_id: "1" },
    payload: { id: "60", text: "@iterate now", author_id: "111", conversation_id: "60" },
  };
  const messaged = {
    event_uuid: "-7",
    event_type: "dm.received",
    filter: { user_id: "1" },
    payload: {
      direct_message_events: [
        {
          type: "message_create",
          id: "7",
          created_timestamp: "1784928224372",
          message_create: { sender_id: "111", message_data: { text: "pushed hello" } },
        },
      ],
    },
  };
  expect([await push(mentioned), await push(messaged)]).toEqual([
    { status: 200, relayed: true },
    { status: 200, relayed: true },
  ]);
  expect(
    (
      await Promise.all(
        ada.statements.slice(4).map((each) => statementOf(each, cloudKey.publicKey)),
      )
    ).map((statement) => statement?.payload),
  ).toMatchObject([
    { kind: "mention", id: "60", ownThread: true, from: { xUserId: "111" } },
    { kind: "dm", id: "7", text: "pushed hello", at: "2026-07-24T21:23:44.372Z" },
  ]);
  // once: the same delivery again, the same post under a new delivery, and the read that finds
  // both after the push. Not X's: a wrong signature. Not the bot's: another account's event.
  provider.mentions.push({
    id: "60",
    author_id: "111",
    text: "@iterate now",
    created_at: "t60",
    conversation_id: "60",
  });
  provider.dms.push({ id: "7", sender_id: "111", text: "pushed hello", created_at: "t7" });
  expect([
    await push(mentioned),
    await push({ ...mentioned, event_uuid: "u-2" }),
    await push({ ...mentioned, event_uuid: "u-3" }, keyed("another body")),
    await push({ ...messaged, event_uuid: "u-4", filter: { user_id: "2" } }),
  ]).toMatchObject([
    { status: 200, redelivery: true },
    { status: 200, relayed: true },
    { status: 401 },
    { status: 200 },
  ]);
  await bot.alarm();
  await outbox.alarm();
  expect(ada.statements).toHaveLength(6);
  expect(provider.subscriptions).toHaveLength(2);

  // ada's deployment answers both; the bot says nothing for a deployment that did not link the person
  const dm = await ada.ask("x:ask/reply", { kind: "dm", to: "111", text: "hello ada" }, "json");
  expect([dm.status, await dm.json()]).toEqual([200, { id: "sent-1" }]);
  const post = await ada.ask(
    "x:ask/reply",
    { kind: "mention", inReplyTo: "50", text: "shipped" },
    "json",
  );
  expect(post).toMatchObject({ status: 200 });
  expect(provider).toMatchObject({
    sent: [
      { path: "/2/dm_conversations/with/111/messages", body: { text: "hello ada" } },
      { path: "/2/tweets", body: { text: "shipped", reply: { in_reply_to_tweet_id: "50" } } },
    ],
  });
  // refused: another deployment; an account nobody linked; a post the Cloud never delivered; a
  // second answer to the mention already answered; a mention inside someone else's conversation;
  // and a public answer that names an account or carries a link
  const mention = (inReplyTo: string, text: string) =>
    ada.ask("x:ask/reply", { kind: "mention", inReplyTo, text }, "json");
  const refusals = [
    await eve.ask("x:ask/reply", { kind: "dm", to: "111", text: "hi" }, "json"),
    await ada.ask("x:ask/reply", { kind: "dm", to: "999", text: "hi" }, "json"),
    await mention("777", "hi"),
    await mention("50", "again"),
    await mention("51", "hi"),
    await mention("52", "@bob look at this"),
    await mention("52", "free money at scam.example/now"),
  ];
  expect(refusals.map((refused) => refused.status)).toEqual([403, 403, 400, 400, 400, 400, 400]);
  expect(provider.sent).toHaveLength(2);
});

test("two allowed deployments share one X subscription to an account's posts, and each gets each post once", async () => {
  const { env, provider, deployment, cloudKey } = await setup();
  env.X_POST_SUBSCRIPTIONS = JSON.stringify({
    limit: 2,
    minds: ["iterate.ada.example", "iterate.eve.example"],
  });
  const ada = await deployment("iterate.ada.example");
  const eve = await deployment("iterate.eve.example");
  const outsider = await deployment("iterate.outsider.example");
  await connectedBot(env, provider);
  const calls = provider.activity.length;
  const fields = { eventType: "post.create", userId: "300637864" };
  const body = JSON.stringify(fields);
  const path = "/clients/x/ask/subscribe";
  const signed = await ada.statement(
    "events.iterate.com/integration/ask-requested",
    "x",
    body,
    path,
  );
  const asked = (statement: string, sent = body) =>
    cloud.fetch(
      new Request(`${CLOUD}${path}`, {
        method: "POST",
        headers: { "iterate-statement": statement },
        body: sent,
      }),
      env,
    );
  expect(await asked("forged")).toMatchObject({ status: 401 });
  expect(await asked(signed, JSON.stringify({ ...fields, userId: "99" }))).toMatchObject({
    status: 401,
  });
  const subscribed = await asked(signed);
  expect(subscribed).toMatchObject({ status: 200 });
  expect(await subscribed.json()).toEqual({ ...fields, subscribed: true });
  // the same statement again is a replay
  expect(await asked(signed)).toMatchObject({ status: 401 });
  expect(await eve.ask("x:ask/subscribe", fields, "json")).toMatchObject({ status: 200 });
  const refused = await outsider.ask("x:ask/subscribe", fields, "json");
  expect(refused).toMatchObject({ status: 403 });
  expect(await refused.json()).toMatchObject({
    error: "iterate.outsider.example may not subscribe to public posts",
  });
  expect(
    await ada.ask("x:ask/subscribe", { ...fields, eventType: "dm.received" }, "json"),
  ).toMatchObject({ status: 400 });
  expect(await ada.ask("x:ask/subscribe", { ...fields, userId: "../bad" }, "json")).toMatchObject({
    status: 400,
  });
  expect(postSubscriptionsAtX(provider)).toHaveLength(1);
  expect(await (await ada.ask("x:ask/list", {}, "json")).json()).toEqual({
    subscriptions: [{ userId: fields.userId, eventType: "post.create" }],
  });

  const reply = {
    event_uuid: "delivery-1",
    event_type: "post.create",
    filter: { user_id: fields.userId },
    payload: {
      id: "42",
      author_id: fields.userId,
      text: "new update",
      conversation_id: "40",
      in_reply_to_tweet_id: "41",
      referenced_tweets: [{ type: "replied_to", id: "41" }],
    },
  };
  expect(await (await xDelivery(env, reply)).json()).toEqual({
    accepted: true,
    redelivery: false,
  });
  expect(await (await xDelivery(env, reply)).json()).toEqual({ accepted: true, redelivery: true });
  // X signed it, so it is answered 200: a 400 would only make X send it again
  const foreign = await xDelivery(env, {
    ...reply,
    event_uuid: "delivery-2",
    payload: { ...reply.payload, id: "43", author_id: "99" },
  });
  expect(foreign).toMatchObject({ status: 200 });
  expect(await foreign.json()).toEqual({ accepted: false });
  await handedOver(env, "x");
  for (const mind of ["iterate.ada.example", "iterate.eve.example"])
    await (env.OUTBOX.get(env.OUTBOX.idFromName(mind)) as unknown as Outbox).alarm();
  expect(ada.statements).toHaveLength(1);
  expect(eve.statements).toHaveLength(1);
  expect(outsider.statements).toHaveLength(0);
  expect(await statementOf(ada.statements[0]!, cloudKey.publicKey)).toMatchObject({
    path: "/integrations/x/300637864",
    type: "events.iterate.com/x/post-created",
    payload: { payload: { id: "42", in_reply_to_tweet_id: "41", conversation_id: "40" } },
  });

  expect(await ada.ask("x:ask/unsubscribe", fields, "json")).toMatchObject({ status: 200 });
  expect(postSubscriptionsAtX(provider)).toHaveLength(1);
  expect(await (await eve.ask("x:ask/unsubscribe", fields, "json")).json()).toEqual({
    ...fields,
    subscribed: false,
  });
  expect(provider.subscriptions.map((row) => row.event_type)).toEqual([
    "post.mention.create",
    "dm.received",
  ]);
  // the one create and the one delete carried the app's token, not the bot's
  expect(provider.activity.slice(calls)).toEqual([
    { call: "POST /2/activity/subscriptions", token: "x-app" },
    { call: expect.stringMatching(/^DELETE \/2\/activity\/subscriptions\/\d+$/), token: "x-app" },
  ]);
});

test("public post subscriptions stop at the configured number of accounts, and are off with no config", async () => {
  const { env, provider, deployment } = await setup();
  env.X_POST_SUBSCRIPTIONS = JSON.stringify({ limit: 1, minds: ["iterate.ada.example"] });
  const ada = await deployment("iterate.ada.example");
  await connectedBot(env, provider);
  const first = { eventType: "post.create", userId: "12" };
  expect(await ada.ask("x:ask/subscribe", first, "json")).toMatchObject({ status: 200 });
  const second = await ada.ask("x:ask/subscribe", { ...first, userId: "13" }, "json");
  expect(second).toMatchObject({ status: 429 });
  expect(await second.json()).toMatchObject({ error: "subscription quota reached" });
  delete env.X_POST_SUBSCRIPTIONS;
  const off = await ada.ask("x:ask/subscribe", { ...first, userId: "13" }, "json");
  expect(off).toMatchObject({ status: 403 });
  expect(await off.json()).toMatchObject({ error: "public post subscriptions are not enabled" });
  // a deployment can still let go while the service is off
  expect(await ada.ask("x:ask/unsubscribe", first, "json")).toMatchObject({ status: 200 });
  expect(postSubscriptionsAtX(provider)).toHaveLength(0);
});

test("a subscription X refuses leaves no row, and one X says it has already is found in X's list", async () => {
  const { env, provider, deployment } = await setup();
  env.X_POST_SUBSCRIPTIONS = JSON.stringify({ limit: 2, minds: ["iterate.ada.example"] });
  const ada = await deployment("iterate.ada.example");
  const bot = await connectedBot(env, provider);
  const fields = { eventType: "post.create", userId: "12" };
  provider.xPostStatus = 503;
  const failed = await ada.ask("x:ask/subscribe", fields, "json");
  expect(failed).toMatchObject({ status: 502 });
  expect(await failed.json()).toMatchObject({ error: "X refused the subscription: HTTP 503" });
  expect(await (await ada.ask("x:ask/list", {}, "json")).json()).toEqual({ subscriptions: [] });
  provider.xPostStatus = 200;
  expect(await ada.ask("x:ask/subscribe", fields, "json")).toMatchObject({ status: 200 });
  expect(postSubscriptionsAtX(provider)).toHaveLength(1);

  // X made this one earlier and answers a create of it with 400 DuplicateSubscription
  provider.subscriptions.push({
    subscription_id: "777",
    event_type: "post.create",
    filter: { user_id: "13" },
  });
  const existing = { ...fields, userId: "13" };
  expect(await (await ada.ask("x:ask/subscribe", existing, "json")).json()).toEqual({
    ...existing,
    subscribed: true,
  });
  expect(await ada.ask("x:ask/unsubscribe", existing, "json")).toMatchObject({ status: 200 });
  expect(provider.subscriptions.map((row) => row.subscription_id)).not.toContain("777");

  // X lost the first one: its delete answers 400 SubscriptionIdInvalid, and the row goes
  provider.subscriptions.splice(
    provider.subscriptions.findIndex((row) => fieldAt(row, "filter", "user_id") === "12"),
    1,
  );
  expect(await ada.ask("x:ask/unsubscribe", fields, "json")).toMatchObject({ status: 200 });
  expect(await (await ada.ask("x:ask/list", {}, "json")).json()).toEqual({ subscriptions: [] });
  const calls = provider.activity.length;
  await bot.alarm();
  expect(provider.activity.slice(calls)).toEqual([]);
});

test("with no app token for X, a subscribe answers 503 and nothing is stored or asked of X", async () => {
  const { env, provider, deployment } = await setup({ xAppToken: false });
  env.X_POST_SUBSCRIPTIONS = JSON.stringify({ limit: 1, minds: ["iterate.ada.example"] });
  const ada = await deployment("iterate.ada.example");
  await connectedBot(env, provider);
  const calls = provider.activity.length;
  const refused = await ada.ask(
    "x:ask/subscribe",
    { eventType: "post.create", userId: "12" },
    "json",
  );
  expect(refused).toMatchObject({ status: 503 });
  expect(await refused.json()).toMatchObject({ error: "the Cloud has no app token for X" });
  expect(await (await ada.ask("x:ask/list", {}, "json")).json()).toEqual({ subscriptions: [] });
  expect(provider.activity.slice(calls)).toEqual([]);
});

test("a delete X refuses leaves an orphan that the next alarm deletes, and a subscribe revives it with no create", async () => {
  const { env, provider, deployment } = await setup();
  env.X_POST_SUBSCRIPTIONS = JSON.stringify({ limit: 1, minds: ["iterate.ada.example"] });
  const ada = await deployment("iterate.ada.example");
  const bot = await connectedBot(env, provider);
  const fields = { eventType: "post.create", userId: "12" };
  expect(await ada.ask("x:ask/subscribe", fields, "json")).toMatchObject({ status: 200 });
  provider.xDeleteStatus = 500;
  expect(await (await ada.ask("x:ask/unsubscribe", fields, "json")).json()).toEqual({
    ...fields,
    subscribed: false,
  });
  expect(postSubscriptionsAtX(provider)).toHaveLength(1);
  expect(await (await ada.ask("x:ask/list", {}, "json")).json()).toEqual({ subscriptions: [] });
  const creates = creationsAtX(provider);
  expect(await ada.ask("x:ask/subscribe", fields, "json")).toMatchObject({ status: 200 });
  expect(creationsAtX(provider)).toBe(creates);
  expect(await ada.ask("x:ask/unsubscribe", fields, "json")).toMatchObject({ status: 200 });
  provider.xDeleteStatus = 200;
  await bot.alarm();
  expect(postSubscriptionsAtX(provider)).toHaveLength(0);
});

test("an orphan X still keeps after a day is dropped with an error in the log that names it, and holds its place no more", async () => {
  const { env, provider, deployment } = await setup();
  env.X_POST_SUBSCRIPTIONS = JSON.stringify({ limit: 1, minds: ["iterate.ada.example"] });
  const ada = await deployment("iterate.ada.example");
  const bot = await connectedBot(env, provider);
  const fields = { eventType: "post.create", userId: "12" };
  const other = { ...fields, userId: "13" };
  expect(await ada.ask("x:ask/subscribe", fields, "json")).toMatchObject({ status: 200 });
  const [{ subscription_id: subscriptionId }] = postSubscriptionsAtX(provider);
  vi.spyOn(console, "warn").mockImplementation(() => {});
  const leaked = vi.spyOn(console, "error").mockImplementation(() => {});
  vi.useFakeTimers({ toFake: ["Date"] });
  try {
    const began = Date.now();
    provider.xDeleteStatus = 500;
    expect(await ada.ask("x:ask/unsubscribe", fields, "json")).toMatchObject({ status: 200 });

    // within the day the alarm asks X again, says nothing, and the orphan holds its place
    vi.setSystemTime(began + 23 * 60 * 60_000);
    const asked = provider.activity.length;
    await bot.alarm();
    expect(provider.activity.slice(asked)).toMatchObject([
      { call: `DELETE /2/activity/subscriptions/${subscriptionId}` },
    ]);
    expect(leaked).not.toHaveBeenCalled();
    expect(await ada.ask("x:ask/subscribe", other, "json")).toMatchObject({ status: 429 });

    // after the day the row goes, and the log names what an operator deletes at X
    vi.setSystemTime(began + 24 * 60 * 60_000 + 1_000);
    await bot.alarm();
    expect(leaked.mock.calls).toMatchObject([
      [{ event: "bot.post-subscription-leaked", userId: "12", subscriptionId }],
    ]);
    expect(postSubscriptionsAtX(provider)).toHaveLength(1);
    const after = provider.activity.length;
    await bot.alarm();
    expect(provider.activity.slice(after)).toEqual([]);
    expect(await ada.ask("x:ask/subscribe", other, "json")).toMatchObject({ status: 200 });
  } finally {
    vi.useRealTimers();
    vi.restoreAllMocks();
  }
});

test("a subscription leaves the bot's alarm where it was, and an alarm with no orphan asks X nothing about them", async () => {
  const { env, provider, deployment } = await setup();
  env.X_POST_SUBSCRIPTIONS = JSON.stringify({ limit: 1, minds: ["iterate.ada.example"] });
  const ada = await deployment("iterate.ada.example");
  const bot = await connectedBot(env, provider);
  const before = await alarmOf(bot);
  expect(
    await ada.ask("x:ask/subscribe", { eventType: "post.create", userId: "12" }, "json"),
  ).toMatchObject({ status: 200 });
  expect(await alarmOf(bot)).toBe(before);
  const asked = provider.activity.length;
  await bot.alarm();
  expect(provider.activity.slice(asked)).toEqual([]);
});

// ── the fixture: a Cloud, a provider, and deployments that sign as a real one does ───────────────

const get = (path: string) => new Request(`${CLOUD}${path}`);

/** The key that signs a push's token, as the provider's certs address publishes it. One for all
 *  tests: an RSA key takes long to make. */
const pubsub = (async () => {
  const { privateKey, publicKey } = await generateKeyPair("RS256");
  return {
    privateKey,
    jwk: { ...(await exportJWK(publicKey)), kid: "pubsub-1", alg: "RS256", use: "sig" },
  };
})();
/** A push's token as Pub/Sub signs it for the subscription, or with other `claims`, or by `key`. */
async function pushTokenOf(claims: Record<string, unknown> = {}, key?: CryptoKey) {
  const now = Math.floor(Date.now() / 1000);
  return new SignJWT({
    iss: PROVIDER,
    aud: GMAIL_PUSH.audience,
    email: GMAIL_PUSH.serviceAccount,
    email_verified: true,
    iat: now,
    exp: now + 3600,
    ...claims,
  })
    .setProtectedHeader({ alg: "RS256", kid: "pubsub-1" })
    .sign(key || (await pubsub).privateKey);
}
/** Pub/Sub's push of one Gmail notification to the Cloud, with the subscription's token unless
 *  `sent` says what goes in its place: `{}` for none. */
async function gmailPush(
  env: Env,
  data: unknown,
  messageId: string,
  sent?: { authorization?: string },
) {
  return cloud.fetch(
    new Request(`${CLOUD}/clients/google/webhook`, {
      method: "POST",
      headers: {
        "content-type": "application/json",
        ...(sent || { authorization: `Bearer ${await pushTokenOf()}` }),
      },
      body: JSON.stringify({
        message: {
          data:
            typeof data === "string" ? data : Buffer.from(JSON.stringify(data)).toString("base64"),
          messageId,
          publishTime: "2026-11-12T22:00:00.000Z",
        },
        subscription: "projects/iterate-example/subscriptions/gmail-push-to-cloud",
      }),
    }),
    env,
  );
}

/** What the Cloud does by itself after a delivery: the client's inbox hands over what it kept, to
 *  the platform the app served before and to each deployment's outbox. */
async function handedOver(env: Env, client: string) {
  await (env.OUTBOX.get(env.OUTBOX.idFromName(`inbox\n${client}`)) as unknown as Outbox).alarm();
}

/** THE AUTH WORKER OF THE CLOUD'S MIND, as core/auth-worker `signedByStack` signs for another
 *  mind: its key, the minds it signed for, and a switch that makes it fail. */
async function withMindAuth(env: Env) {
  const mindKey = await stackSignerOf();
  const auth = { fails: false, signedFor: [] as string[] };
  env.MIND_HOSTNAME = "iterate.iterate.com";
  env.MIND_AUTH = {
    async sign({ mind, path, type, payload, about, expiresInSeconds = 300 }) {
      if (auth.fails) throw new Error("the auth Worker does not answer");
      auth.signedFor.push(mind);
      const at = Date.now();
      return mindKey.sign({
        mind,
        from: "iterate.iterate.com",
        path: `/minds/iterate.iterate.com${path}`,
        type,
        payload,
        about,
        at,
        expires: at + expiresInSeconds * 1000,
      } as Parameters<typeof mindKey.sign>[0]);
    },
  };
  return { mindKey, auth };
}

/** A deployment says whether it reads the mind form, as core/configs/default `sayMindForm` asks. */
function saysMindForm(
  who: { ask: (route: string, fields: Record<string, string>, as: "json") => Promise<Response> },
  reads: unknown,
) {
  return who.ask("ask/mind-form", { reads } as unknown as Record<string, string>, "json");
}

/** One GitHub delivery about installation 7, handed over to each deployment that connected it. */
async function githubDelivery(env: Env, delivery: string) {
  const body = JSON.stringify({ action: delivery, installation: { id: 7 } });
  await cloud.fetch(
    new Request(`${CLOUD}/clients/github/webhook`, {
      method: "POST",
      headers: {
        "x-hub-signature-256": `sha256=${createHmac("sha256", "webhook-secret").update(body).digest("hex")}`,
        "x-github-event": "pull_request",
        "x-github-delivery": delivery,
      },
      body,
    }),
    env,
  );
  await handedOver(env, "github");
}

/** A HOSTNAME THAT MOVED (README "What the Cloud holds for a deployment: its status"): ada's
 *  mind (`x`) connected GitHub at `hostname` and took a delivery; it now lives at `movedTo` too,
 *  where its one log lists that stack's key. Then a new genesis (`y`) at `hostname` lets the
 *  Cloud's mind in, and a second delivery waits in the hostname's Outbox. The clock is a fake one,
 *  a minute on, so that each log is read again; the caller ends it. */
async function movedHostname() {
  const { env, deployment, proofFor } = await setup();
  await withMindAuth(env);
  const tag = crypto.randomUUID().slice(0, 8);
  const hostname = `iterate-${tag}.example`;
  const movedTo = `iterate-${tag}-new.example`;
  env.MIND_HOSTNAME = `iterate-own-${tag}.example`;
  const own = await deployment(env.MIND_HOSTNAME, { log: true });
  const ada = await deployment(hostname, { log: true });
  const adaMoved = await deployment(movedTo, { log: true });
  // ada's one log, which names both hostnames and lists each one's stack key
  const x = await newIdentityLog([hostname, movedTo]);
  const xLog = {
    mind: x.mind,
    records: [x.genesis, await x.next(x.genesis, { workingKeys: [ada.listed, adaMoved.listed] })],
  };
  ada.log = xLog;
  adaMoved.log = xLog;
  ada.letsMindIn = true;
  const connect = async (code: string) =>
    ada.ask("token", {
      grant_type: "authorization_code",
      code,
      cloud_proof: await proofFor(hostname, code),
    });
  expect(await connect("code-ada")).toMatchObject({ status: 200 });
  const outbox = env.OUTBOX.get(env.OUTBOX.idFromName(hostname)) as unknown as Outbox;
  await githubDelivery(env, "d-1");
  await outbox.alarm();
  expect(ada.statements.splice(0)).toHaveLength(1);
  const y = await newIdentityLog([hostname]);
  ada.log = {
    mind: y.mind,
    records: [y.genesis, await y.next(y.genesis, { workingKeys: [ada.listed] })],
  };
  vi.useFakeTimers({ toFake: ["Date"] });
  vi.setSystemTime(Date.now() + 61_000);
  await githubDelivery(env, "d-2");
  await outbox.alarm();
  expect({ took: ada.statements.length, held: await held(outbox) }).toEqual({ took: 0, held: 1 });
  return { env, deployment, own, ada, adaMoved, hostname, movedTo, x, y, outbox, connect };
}

/** A deployment asks for its status, as a vault sends an ask. */
function statusOf(
  who: { ask: (route: string, fields: Record<string, string>, as: "json") => Promise<Response> },
  fields: Record<string, string> = {},
) {
  return who.ask("ask/status", fields, "json");
}

async function held(outbox: Outbox) {
  const state = (outbox as unknown as { ctx: DurableObjectState }).ctx;
  return (await state.storage.list({ prefix: "item:" })).size;
}

/** A STACK'S KEY, as core/auth-worker `stackKeyOf` holds one: ML-DSA-65, its raw public half as
 *  `/keys/stack.json` shows it, and `sign`, which signs a statement's fields as `signedByStack`
 *  does (iterate/signed `signedMlDsa65`), the DSSE bytes written out here. */
async function stackSignerOf() {
  const algorithm = { name: "ML-DSA-65" } as const;
  const pair = (await crypto.subtle.generateKey(algorithm, true, [
    "sign",
    "verify",
  ])) as CryptoKeyPair;
  const publicKey = base64url(
    (await crypto.subtle.exportKey("raw-public" as "raw", pair.publicKey)) as ArrayBuffer,
  );
  const key = await keyIdOf(publicKey);
  const encoder = new TextEncoder();
  const type = "application/vnd.iterate.statement+json";
  return {
    key,
    publicKey,
    async sign(fields: Record<string, unknown>): Promise<Signed> {
      const nonce = base64url(crypto.getRandomValues(new Uint8Array(16)));
      const statement = JSON.stringify({ ...fields, nonce });
      const body = encoder.encode(statement);
      const bytes = Buffer.concat([
        encoder.encode(`DSSEv1 ${encoder.encode(type).length} ${type} ${body.length} `),
        body,
      ]);
      const sig = await crypto.subtle.sign(algorithm, pair.privateKey, bytes);
      return { statement, signature: { format: "ML-DSA-65", key, sig: base64url(sig) } };
    },
  };
}

async function newJwk() {
  const pair = (await crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, true, [
    "sign",
    "verify",
  ])) as CryptoKeyPair;
  return (await crypto.subtle.exportKey("jwk", pair.privateKey)) as JsonWebKey;
}

async function setup({ xAppToken = true } = {}) {
  const cloudJwk = await newJwk();
  const cloudKey = await signerOf(cloudJwk);
  const appKey = generateKeyPairSync("rsa", { modulusLength: 2048 })
    .privateKey.export({ type: "pkcs8", format: "pem" })
    .toString();
  const env = {
    CLOUD_KEY: JSON.stringify(cloudJwk),
    CLOUD_CLIENTS: JSON.stringify({ github, google, x, slack, cloudflare }),
    CLOUD_CLIENT_SECRETS: JSON.stringify({
      github: {
        clientSecret: "client-secret",
        webhookSecret: "webhook-secret",
        appPrivateKey: appKey,
      },
      google: { clientSecret: "google-secret" },
      // the X app's app-only token, which public post subscriptions take; `xAppToken: false`: none
      x: { clientSecret: "x-secret", ...(xAppToken && { bearerToken: "x-app" }) },
      slack: { clientSecret: "slack-secret", webhookSecret: "slack-signing" },
      cloudflare: { clientSecret: "cloudflare-secret" },
    }),
  } as Env;
  env.ROUTES = namespaceOf(Routes, env);
  env.OUTBOX = namespaceOf(Outbox, env);
  env.BOT = namespaceOf(Bot, env);

  const provider = {
    /** Cloudflare: the scopes its token answer names. */
    cloudflareScope: "zone.read workers-observability.write offline_access",
    tokenRequests: [] as URLSearchParams[],
    appJwts: [] as string[],
    /** GitHub: whether ada is still an owner of `owned`, and whether her grant still refreshes. */
    ownsOrganization: true,
    refreshes: true,
    /** The provider answers a refresh 429: too many requests, and no word on the grant. */
    busy: false,
    /** The provider's token endpoint does not answer: the request fails, or runs out of time. */
    unreachable: false,
    /** Its next token answer waits: `reached` says the request came, `answers` lets it go. */
    slow: undefined as { reached: () => void; answers: Promise<void> } | undefined,
    /** Google: the `scope` of its next token answers; none when unset. */
    googleScope: undefined as string | undefined,
    /** Google: the mailbox Gmail names for the token; none: the grant reads no mail;
     *  "unreachable": the request to Gmail fails. */
    gmailAddress: "Ada@Example.com" as string | undefined,
    /** Google: the id of the account's primary calendar, which is the account's address. */
    calendarId: "Ada@Example.com",
    /** Slack: the person whose install the next token exchange answers, as `users.info` says. */
    slackInstaller: { id: "U1", team_id: "T1", is_admin: true, is_owner: false },
    /** X: whose access token is whose, what was sent to the bot, and what the bot sent. */
    xUsers: new Map<string, { id: string; username: string }>(),
    dms: [] as { id: string; sender_id: string; text: string; created_at: string }[],
    mentions: [] as {
      id: string;
      author_id: string;
      text: string;
      created_at: string;
      conversation_id: string;
    }[],
    sent: [] as { path: string; body: unknown }[],
    /** What X pushes to, and for which events: the app's webhooks and its subscriptions. */
    webhooks: [] as { id: string; url: string }[],
    subscriptions: [] as Record<string, unknown>[],
    /** X's Activity API: each call to its subscriptions with the token it carried, and how it
     *  answers a create of a public post subscription and a delete. */
    activity: [] as { call: string; token: string }[],
    xPostStatus: 200,
    xDeleteStatus: 200,
    /** The platform the apps served before: what was passed on to it, and how it answers. */
    passed: [] as { url: string; headers: Record<string, string>; body: string }[],
    osAnswers: 200,
  };
  /** `letsMindIn`: its owner let the Cloud's mind in, so it takes a statement that names a `from`;
   *  `mindFormRefused` counts the ones it refused. `knowsNoCloudKey`: it trusts no key of the
   *  Cloud's, as a mind of the stack does unless a member enrolled one, so it refuses the key
   *  form; `keyFormRefused` counts those. */
  type Deployment = {
    publicKey: string;
    /** The identity log its control plane serves at `/.well-known/iterate`; none: it serves none. */
    log?: { mind: string; records: SignedRecord[] };
    /** How often the Cloud read that log. */
    logReads: number;
    /** Its control plane does not answer: each fetch of it fails. */
    unreachable?: boolean;
    statements: Signed[];
    down: boolean;
    letsMindIn?: boolean;
    mindFormRefused: number;
    knowsNoCloudKey?: boolean;
    keyFormRefused: number;
  };
  const deployments = new Map<string, Deployment>();

  vi.stubGlobal("fetch", async (input: RequestInfo | URL, init?: RequestInit) => {
    const request = new Request(input, init);
    const url = new URL(request.url);
    if (url.origin === PROVIDER) {
      if (url.pathname === "/login/oauth/access_token") {
        if (provider.unreachable) throw new TypeError("fetch failed");
        const form = new URLSearchParams(await request.text());
        provider.tokenRequests.push(form);
        if (provider.slow) {
          provider.slow.reached();
          await provider.slow.answers;
        }
        const n = provider.tokenRequests.length;
        // GitHub answers a refused grant with 200 and an error
        if (form.get("grant_type") === "refresh_token" && provider.busy)
          return Response.json({ error: "rate_limited" }, { status: 429 });
        if (form.get("grant_type") === "refresh_token" && !provider.refreshes)
          return Response.json({ error: "bad_refresh_token" });
        return Response.json({
          access_token: `access-${n}`,
          refresh_token: `refresh-${n}`,
          expires_in: 28_800,
        });
      }
      if (url.pathname === "/oauth2/token") {
        provider.tokenRequests.push(new URLSearchParams(await request.text()));
        return Response.json({
          access_token: "cloudflare-access",
          refresh_token: "cloudflare-refresh",
          expires_in: 3600,
          scope: provider.cloudflareScope,
        });
      }
      // Google answers an access token beside the id_token, whatever was asked
      if (url.pathname === "/token") {
        provider.tokenRequests.push(new URLSearchParams(await request.text()));
        return Response.json({
          access_token: "google-access",
          refresh_token: "google-refresh",
          id_token: "google.id.token",
          scope: provider.googleScope,
        });
      }
      if (url.pathname === "/oauth2/v3/certs") return Response.json({ keys: [(await pubsub).jwk] });
      const googles = request.headers.get("authorization") === "Bearer google-access";
      if (googles && url.pathname === "/gmail/v1/users/me/profile") {
        if (provider.gmailAddress === "unreachable") throw new TypeError("fetch failed");
        return provider.gmailAddress
          ? Response.json({ emailAddress: provider.gmailAddress, historyId: "1" })
          : Response.json({ error: { code: 403, status: "PERMISSION_DENIED" } }, { status: 403 });
      }
      if (googles && url.pathname === "/calendar/v3/calendars/primary")
        return Response.json({ id: provider.calendarId, summary: "Ada" });
      // the account's address, which Google answers to a grant that reads no mail too
      if (googles && url.pathname === "/oauth2/v2/userinfo")
        return Response.json({ id: "108", email: "grace@example.com", verified_email: true });
      if (url.pathname === "/user") return Response.json({ id: 1, login: "ada" });
      // ada's own account, an organization she owns, and one she is only a member of
      if (url.pathname === "/user/installations")
        return Response.json({
          installations: [
            { id: 7, account: { id: 1, login: "ada", type: "User" } },
            { id: 8, account: { id: 20, login: "owned", type: "Organization" } },
            { id: 9, account: { id: 30, login: "joined", type: "Organization" } },
            { id: 10, account: { id: 2, login: "bob", type: "User" } },
          ],
        });
      if (url.pathname === "/user/memberships/orgs/owned")
        return Response.json({
          state: "active",
          role: provider.ownsOrganization ? "admin" : "member",
        });
      if (url.pathname === "/user/memberships/orgs/joined")
        return Response.json({ state: "active", role: "member" });
      if (url.pathname === "/app/installations/7/access_tokens") {
        provider.appJwts.push(request.headers.get("authorization")!.slice("Bearer ".length));
        return Response.json({ token: "ghs_installation", expires_at: "later" }, { status: 201 });
      }
    }
    if (url.origin === new URL(OS).origin) {
      if (provider.osAnswers < 500)
        provider.passed.push({
          url: request.url,
          headers: Object.fromEntries(request.headers),
          body: await request.text(),
        });
      return new Response(null, { status: provider.osAnswers });
    }
    // Slack answers a bot token, the workspace it is for and the person who installed the app
    if (url.origin === PROVIDER && url.pathname === "/api/oauth.v2.access") {
      provider.tokenRequests.push(new URLSearchParams(await request.text()));
      return Response.json({
        ok: true,
        access_token: "xoxb-1",
        team: { id: "T1", name: "Ada" },
        authed_user: { id: provider.slackInstaller.id },
      });
    }
    // who that person is in the workspace, asked with the bot token
    if (url.origin === PROVIDER && url.pathname === "/api/users.info") {
      if (request.headers.get("authorization") !== "Bearer xoxb-1")
        return Response.json({ ok: false, error: "invalid_auth" });
      const known = url.searchParams.get("user") === provider.slackInstaller.id;
      return Response.json(
        known
          ? { ok: true, user: provider.slackInstaller }
          : { ok: false, error: "user_not_found" },
      );
    }
    if (url.origin === PROVIDER && url.pathname === "/2/oauth2/token") {
      const form = new URLSearchParams(await request.text());
      provider.tokenRequests.push(form);
      if (request.headers.get("authorization") !== `Basic ${btoa("x-client:x-secret")}`)
        return Response.json({ error: "invalid_client" }, { status: 401 });
      // the code names who consented: `bot` is the bot's account, anything else a person's id
      const who =
        form.get("code") === "bot"
          ? { id: "1", username: "iterate" }
          : { id: form.get("code")!, username: "ada" };
      const access = `x-access-${provider.tokenRequests.length}`;
      provider.xUsers.set(access, who);
      return Response.json({
        access_token: access,
        refresh_token: `x-refresh-${access}`,
        expires_in: 7200,
      });
    }
    const bearer = (request.headers.get("authorization") || "").slice("Bearer ".length);
    // X's subscriptions, as production answered on 2026-11-13: a public post subscription is the
    // app's, so only the app's token lists, makes and deletes it; the bot's makes only its own
    if (url.origin === PROVIDER && url.pathname.startsWith("/2/activity/subscriptions")) {
      provider.activity.push({ call: `${request.method} ${url.pathname}`, token: bearer });
      const app = bearer === "x-app";
      const errors = (message: string) =>
        Response.json({ errors: [{ message }], title: "Invalid Request" }, { status: 400 });
      if (request.method === "DELETE") {
        const id = url.pathname.split("/").at(-1);
        if (!app)
          return errors(
            `UserNotAuthorized: Subscription ${id} does not belong to the authenticated user`,
          );
        if (provider.xDeleteStatus !== 200)
          return Response.json({ title: "refused" }, { status: provider.xDeleteStatus });
        const index = provider.subscriptions.findIndex((row) => row.subscription_id === id);
        if (index < 0)
          return errors(
            `SubscriptionIdInvalid: Subscription ${id} not found or does not belong to instance 1`,
          );
        provider.subscriptions.splice(index, 1);
        return Response.json({ data: { deleted: true }, meta: { sent: "now" } });
      }
      if (app && request.method === "GET") return Response.json({ data: provider.subscriptions });
      const asked = objectOf(request.method === "POST" ? await request.clone().json() : null);
      if (asked?.event_type === "post.create") {
        if (!app) return Response.json({ title: "Unauthorized", status: 401 }, { status: 401 });
        if (provider.xPostStatus !== 200)
          return Response.json({ title: "refused" }, { status: provider.xPostStatus });
        if (
          postSubscriptionsAtX(provider).some(
            (row) => fieldAt(row, "filter", "user_id") === fieldAt(asked, "filter", "user_id"),
          )
        )
          return errors(
            "DuplicateSubscription: A subscription already exists for event type 'post.create' with the same filters",
          );
        // its id is `subscription_id`
        const subscription = {
          ...asked,
          subscription_id: String(100 + provider.subscriptions.length),
        };
        provider.subscriptions.push(subscription);
        return Response.json({ data: { subscription } });
      }
    }
    const xUser = provider.xUsers.get(bearer);
    if (url.origin === PROVIDER && xUser) {
      if (url.pathname === "/2/users/me") return Response.json({ data: xUser });
      if (url.pathname === "/2/dm_events")
        return Response.json({ data: provider.dms.toReversed() });
      if (url.pathname === `/2/users/${xUser.id}/mentions`)
        return Response.json({
          data: provider.mentions
            .filter((post) => Number(post.id) > Number(url.searchParams.get("since_id") || 0))
            .toReversed(),
        });
      if (url.pathname === "/2/webhooks" || url.pathname === "/2/activity/subscriptions") {
        const rows = url.pathname === "/2/webhooks" ? provider.webhooks : provider.subscriptions;
        // as X answered on production: the list of subscriptions is not given, a webhook's is
        if (request.method === "GET")
          return url.pathname === "/2/webhooks"
            ? Response.json({ data: rows })
            : Response.json({ title: "Forbidden", status: 403 }, { status: 403 });
        const made = { id: `made-${rows.length + 1}`, ...((await request.json()) as object) };
        rows.push(made as { id: string; url: string });
        return Response.json({ data: made });
      }
      if (request.method === "POST") {
        provider.sent.push({ path: url.pathname, body: await request.json() });
        return Response.json({ data: { id: `sent-${provider.sent.length}` } }, { status: 201 });
      }
    }
    // a deployment answers on its control plane's hostname, which is its name, and on no other
    const deployment = deployments.get(url.hostname);
    if (deployment?.unreachable) throw new TypeError("fetch failed");
    if (deployment?.log && url.pathname === "/.well-known/iterate") {
      // `?after=<hash>`: the records after that one, as a mind's log answers
      const { mind, records } = deployment.log;
      deployment.logReads += 1;
      const hashes = await Promise.all(records.map(({ record }) => identityHashOf(record)));
      const after = url.searchParams.get("after");
      const at = after ? hashes.indexOf(after) : -1;
      if (after && at < 0) return new Response(null, { status: 404 });
      return Response.json({
        version: 1,
        mind,
        head: hashes.at(-1),
        records: records.slice(at + 1),
      });
    }
    if (deployment && url.pathname === "/keys/stack.json")
      return Response.json({
        mind: url.hostname,
        key: await keyIdOf(deployment.publicKey),
        publicKey: deployment.publicKey,
        algorithm: "ML-DSA-65",
        listed: true,
      });
    if (deployment && url.pathname === "/statements") {
      if (deployment.down) return Response.json({ refused: "unknown key" }, { status: 403 });
      const sent = (await request.json()) as Signed;
      // as core/auth-worker's `mindKeyOf` answers a mind that no rule lets in
      const { from } = JSON.parse(sent.statement) as { from?: string };
      if (from && !deployment.letsMindIn) {
        deployment.mindFormRefused += 1;
        return Response.json({ refused: `${from} is not let in here` }, { status: 403 });
      }
      // as core/auth-worker answers a statement that no key it knows signed
      if (!from && deployment.knowsNoCloudKey) {
        deployment.keyFormRefused += 1;
        return Response.json({ refused: "the key is not one this mind knows" }, { status: 403 });
      }
      deployment.statements.push(sent);
      return Response.json({ ok: true });
    }
    return new Response("no such host in this test", { status: 599 });
  });

  /** A deployment whose control plane's hostname is `mind`, which signs as `publishes` (itself,
   *  unless it lies). With `log`, it serves its identity log: a genesis, and a record that lists
   *  the stack's key (`listed`) as its working key, as the owner's command lists it. */
  const deployment = async (mind: string, { publishes = mind, log = false } = {}) => {
    const key = await stackSignerOf();
    const listed = {
      signs: "raw",
      algorithm: "ML-DSA-65",
      publicKey: key.publicKey,
      label: "stack",
      purpose: "statements",
    } as const;
    const identity = log ? await newIdentityLog([mind]) : undefined;
    const record: Deployment = {
      publicKey: key.publicKey,
      log: identity && {
        mind: identity.mind,
        records: [
          identity.genesis,
          await identity.next(identity.genesis, { workingKeys: [listed] }),
        ],
      },
      logReads: 0,
      statements: [],
      down: false,
      mindFormRefused: 0,
      keyFormRefused: 0,
    };
    deployments.set(mind, record);
    const statement = async (type: string, client: string, body: string, path?: string) => {
      const hash = Buffer.from(
        await crypto.subtle.digest("SHA-256", new TextEncoder().encode(body)),
      ).toString("hex");
      const at = Date.now();
      const signed = await key.sign({
        mind: publishes,
        path: "/",
        type,
        payload: { client, body: hash, path },
        at,
        expires: at + 60_000,
      });
      return base64url(Buffer.from(JSON.stringify(signed)));
    };
    /** A signed request to one of the Cloud's routes, as a vault sends it: `<verb>` of GitHub's
     *  client, or `<client>:<verb>` of another's. An `ask/` route's statement names the route. */
    const ask = async (
      route: string,
      fields: Record<string, string>,
      as: "form" | "json" = "form",
    ) => {
      const [client, verb] = route.includes(":") ? route.split(":") : ["github", route];
      const body = as === "json" ? JSON.stringify(fields) : new URLSearchParams(fields).toString();
      const path = `/clients/${client}/${verb}`;
      const asks = verb!.startsWith("ask/") ? "ask" : verb;
      return cloud.fetch(
        new Request(`${CLOUD}${path}`, {
          method: "POST",
          headers: {
            "iterate-statement": await statement(
              `events.iterate.com/integration/${asks}-requested`,
              client!,
              body,
              path,
            ),
          },
          body,
        }),
        env,
      );
    };
    return Object.assign(record, { ask, statement, identity, listed });
  };

  /** The proof the Cloud's callback puts on a code it sends to `mind`, for `client`, after a
   *  browser confirmed on the Cloud's page that `mind` gets the installations on `accounts`.
   *  `beside` is what else the provider sent (`&setup_action=install` from a GitHub App's install
   *  page, `&installation_id=7`). */
  // ONE PROOF FOR ONE CODE: a test that shows a code's proof twice shows the one the Cloud made
  const made = new Map<string, string>();
  const proofFor = async (
    mind: string,
    code: string,
    client = "github",
    beside = "",
    accounts = "ada,owned,joined,bob",
    /** The scopes the consent asks for, which the Cloud's page names (Google's alone). */
    scope = "",
  ) => {
    const asked = [mind, code, client, beside, accounts, scope].join("\n");
    if (!made.has(asked))
      made.set(asked, await newProofFor(mind, code, client, beside, accounts, scope));
    return made.get(asked)!;
  };
  const newProofFor = async (
    mind: string,
    code: string,
    client: string,
    beside: string,
    accounts: string,
    scope: string,
  ) => {
    const state = `${base64url(Buffer.from(`https://${mind}/secrets/oauth/callback`))}.n`;
    const { authorizationEndpoint, clientId } = JSON.parse(env.CLOUD_CLIENTS)[client] as Client;
    // Google's authorize address has a query of its own
    const to = `${authorizationEndpoint}${authorizationEndpoint.includes("?") ? "&" : "?"}client_id=${clientId}&redirect_uri=${encodeURIComponent(`${CLOUD}/clients/${client}/callback`)}${scope && `&scope=${encodeURIComponent(scope)}`}&state=${state}`;
    const begin = (more: string, cookie: string) =>
      cloud.fetch(
        new Request(
          `${CLOUD}/clients/${client}/begin?to=${encodeURIComponent(to)}&accounts=${accounts}${more}`,
          { headers: { cookie } },
        ),
        env,
      );
    const shown = await begin("", "");
    const [first] = shown.headers.get("set-cookie")!.split(";");
    const go = new URL(
      /href="([^"]+)"/.exec(await shown.text())![1]!.replaceAll("&#38;", "&"),
    ).searchParams.get("go");
    const [confirmed] = (await begin(`&go=${go}`, first!)).headers.get("set-cookie")!.split(";");
    const back = await cloud.fetch(
      new Request(`${CLOUD}/clients/${client}/callback?code=${code}&state=${state}${beside}`, {
        headers: { cookie: confirmed! },
      }),
      env,
    );
    return new URL(back.headers.get("location")!).searchParams.get("cloud_proof")!;
  };

  return { env, cloudKey, provider, deployment, proofFor };
}

/** A Durable Object namespace in memory: one instance per name, its storage a Map. */
function namespaceOf<T>(
  Class: new (state: DurableObjectState, env: Env) => T,
  env: Env,
): DurableObjectNamespace<T & Rpc.DurableObjectBranded> {
  const instances = new Map<string, T>();
  return {
    idFromName: (name: string) => name,
    get: (name: string) => {
      if (!instances.has(name)) {
        const state = stateOf();
        const made = new Class(state, env) as T & { alarm?: () => Promise<void> };
        // as the platform does: the alarm that fires is not set any more while its handler runs,
        // so `getAlarm()` in the handler answers an alarm set since it began, or null
        const alarm = made.alarm?.bind(made);
        if (alarm)
          made.alarm = async () => {
            await state.storage.deleteAlarm();
            await alarm();
          };
        instances.set(name, made);
      }
      return instances.get(name)!;
    },
  } as unknown as DurableObjectNamespace<T & Rpc.DurableObjectBranded>;
}

function stateOf(): DurableObjectState {
  const rows = new Map<string, unknown>();
  /** The keys in order, made again after a write: a queue's bound lists it at each write. */
  let sorted: string[] | null = null;
  let alarmAt: number | null = null;
  const storage = {
    get: async (key: string) => rows.get(key),
    put: async (entry: string | Record<string, unknown>, value?: unknown) => {
      if (typeof entry === "string") rows.set(entry, value);
      else for (const [key, each] of Object.entries(entry)) rows.set(key, each);
      sorted = null;
    },
    delete: async (keys: string | string[]) => {
      for (const key of [keys].flat()) rows.delete(key);
      sorted = null;
    },
    list: async ({ prefix = "", limit = Infinity, startAfter = "" } = {}) => {
      sorted ||= [...rows.keys()].sort();
      const found = new Map<string, unknown>();
      for (const key of sorted) {
        if (found.size >= limit) break;
        if (key.startsWith(prefix) && key > startAfter) found.set(key, rows.get(key));
      }
      return found;
    },
    setAlarm: async (at: number) => {
      alarmAt = at;
    },
    getAlarm: async () => alarmAt,
    deleteAlarm: async () => {
      alarmAt = null;
    },
    deleteAll: async () => {
      rows.clear();
      sorted = null;
    },
  };
  return { storage } as unknown as DurableObjectState;
}

/** The X client's bot, connected by an operator, after its first alarm made X push to the Cloud. */
async function connectedBot(
  env: Env,
  provider: { xUsers: Map<string, { id: string; username: string }> },
) {
  const bot = env.BOT.get(env.BOT.idFromName("x")) as unknown as Bot;
  provider.xUsers.set("bot", { id: "1", username: "iterate" });
  await bot.setAccount(
    "x",
    CLOUD,
    { accessToken: "bot", refreshToken: "refresh", expiresAt: Date.now() + 3600000 },
    { id: "1", username: "iterate" },
  );
  await bot.alarm();
  return bot;
}

/** When the bot's next alarm fires. */
async function alarmOf(bot: Bot) {
  return (bot as unknown as { ctx: DurableObjectState }).ctx.storage.getAlarm();
}

/** One delivery of X's Activity API to the Cloud, signed with the client's secret as X signs. */
async function xDelivery(env: Env, data: unknown) {
  const body = JSON.stringify({ data });
  const signature = createHmac("sha256", "x-secret").update(body).digest("base64");
  return cloud.fetch(
    new Request(`${CLOUD}/clients/x/webhook`, {
      method: "POST",
      headers: { "x-twitter-webhooks-signature-oauth2": `sha256=${signature}` },
      body,
    }),
    env,
  );
}

/** X's subscriptions to public posts, as the fake provider holds them. */
function postSubscriptionsAtX(provider: { subscriptions: Record<string, unknown>[] }) {
  return provider.subscriptions.filter((row) => row.event_type === "post.create");
}

/** How many subscriptions X was asked to make, the bot's own among them. */
function creationsAtX(provider: { activity: { call: string }[] }) {
  return provider.activity.filter(({ call }) => call === "POST /2/activity/subscriptions").length;
}