iterate.com / cloud

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

cloud / internal-packages / cloud-clientsmain at aacbc74

README.md

# The Cloud's clients

iterate's official apps at GitHub, Google, X, Slack and Cloudflare exist once. Every deployment uses them, and each
deployment runs in its owner's own Cloudflare account. This Worker stands between the two. It holds
what exists once and is ours: the apps' client secrets, a GitHub App's private key and webhook
secret, and the Cloud's signing key. It holds no token of any deployment and no token of any
person that it can read. One thing it does hold of a person: the answer to their last refresh, for
a day as a rule and two at most, sealed under the refresh token that answer spent. The Cloud does
not keep that token, so it cannot open the answer; only the deployment's retry can ("What is
kept").

| Route                                        | What it does                                                                                                                                                                                                                                                                                                                                                                                  |
| -------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `GET /.well-known/iterate-cloud`             | The Cloud's public key, and each client's public facts: what a deployment's vault needs to begin a connect.                                                                                                                                                                                                                                                                                   |
| `GET /clients/<name>/begin`                  | The one page a person confirms on, before the provider's own. A vault sends the browser here with the provider's URL as `to`. The page says which deployment gets access. The press of Continue is bound to this browser and this attempt by a cookie. For a GitHub App it also says which accounts' installations the deployment gets: the ones the vault named in `accounts`, and no other. |
| `GET /clients/<name>/callback`               | The app's one redirect URI. The code goes on to the deployment that began, with a proof of where the Cloud sent it: one proof for one code, made after the person's press and never before. A consent that did not begin on the Cloud's page is asked here first, and a Google one is refused.                                                                                                |
| `POST /clients/<name>/token`                 | A deployment's code exchange or refresh. The Cloud adds the client secret. The access token goes back as it came, the refresh token sealed to that deployment.                                                                                                                                                                                                                                |
| `POST /clients/<name>/installation-token`    | A GitHub App installation's token, minted with the App's key, for a deployment that connected the installation.                                                                                                                                                                                                                                                                               |
| `POST /clients/<name>/webhook`               | The app's webhook address: GitHub's, and Slack's events. A delivery the provider signed becomes `<provider>/webhook-received` on `/integrations/<name>/<account>` (a GitHub installation, a Slack workspace), held for each deployment that connected the account and signed for it as a statement of the Cloud's mind ("The Cloud signs as its own mind").                                   |
| `POST /clients/<name>/interactivity-webhook` | Slack's second address, for what people press: the same way.                                                                                                                                                                                                                                                                                                                                  |
| `POST /clients/<name>/webhook`, for Google   | Gmail's push for a mailbox, from the one Pub/Sub subscription of the client's topic. A push whose token is that subscription's becomes `google/gmail-push-received` on `/integrations/<name>/<address>`, the same way ("Gmail's push").                                                                                                                                                       |
| `POST /clients/<name>/calendar-webhook`      | For Google: Calendar's push on a channel that a deployment made with the token the Cloud gave it. It becomes `google/calendar-push-received` on `/integrations/<name>/<address>`, for that deployment alone ("Calendar's push").                                                                                                                                                              |

## A sign-in with Google

A deployment may let a person sign in with Google through iterate's Google client
(core/auth-worker). The Cloud lends the client secret and nothing more: Google is the identity
provider, and the deployment checks Google's signed id_token itself.

- The `state` names the deployment's sign-in page, `https://<its name>/sign-in/google/callback`,
  where a vault's connect names `/secrets/oauth/callback`. Google's client alone takes it.
- `begin` refuses a sign-in that asks for more than `openid` and `email`, and its page says "Sign in
  to `<its name>`": the deployment learns the address and gets no access.
- `token` answers a sign-in's code with `{ id_token }` alone. No access token and no refresh token
  goes back, whatever the consent was for.

The limit: the Cloud holds the client secret and the one redirect URI, so a deployment that offers
this sign-in trusts the Cloud not to send a person to Google on another's behalf.

## A connection to Cloudflare

A deployment reads its own Cloudflare account through a consent that its vault refreshes (the
template's `cloudflare.md`): the account's settings and analytics, the names of what it holds,
and its Workers' logs. A client of the kind `cloudflare` brokers that consent. It is a Cloudflare
OAuth client of its own, registered with the read scopes and the one write that the log query
needs, so Cloudflare gives no consent of it a scope that deploys.

- **`scopes` is the most a connect asks and gets.** `begin` refuses a link that asks a scope
  the client's list does not name, so the page's words are true: "It deploys and changes
  nothing." The exchange and each refresh refuse a token whose answer names a scope beyond the
  list.
- **The page tells the person which account to pick.** Cloudflare's consent asks which accounts
  the app may reach, and the Cloud does not know the deployment's account. The page says: only
  the account that the deployment runs in. The deployment checks what the consent reaches, and
  keeps none that reaches another account.
- **It claims no route.** Cloudflare sends this client no webhook, so a connect records nothing
  at the Cloud, and a refused refresh ends nothing here.
- **The refresh token is sealed to the deployment**, as every client's is. The Cloud cannot read
  the account, and the deployment cannot refresh without the Cloud.

## Gmail's push

A deployment that connected a Gmail mailbox through iterate's Google client gets an event when
the mailbox changes, with no polling.

- **The watch is the deployment's call.** It asks Gmail to watch the mailbox (`users.watch`) with
  the person's token, which the Cloud never has, and names the client's topic. Gmail ends a watch
  after seven days, so the deployment asks again every day.
- **The Cloud tells the deployment which mailbox it connected.** A mind's code cannot read the
  Cloud's facts. So at each connect of a grant that reads mail, the Cloud writes
  `google/gmail-connected` on `/integrations/<name>/<address>`, for that deployment alone, with
  `{ emailAddress, topic, api }`: the topic to name in the watch, and the origin of Gmail's API as
  this client has it. A refresh tells too when the deployment was not told yet: a grant
  connected before the Cloud routed mailboxes or before the client took a push, and a word that
  the deployment never took (the Cloud holds a statement for a day). The topic is also
  `gmailTopic` in the client's public facts.
- **One topic, one push subscription.** The topic is in the Google project of the OAuth client:
  Gmail refuses a topic of another project. Its one push subscription delivers to
  `POST /clients/<name>/webhook`, and Pub/Sub signs each push with a token for that
  subscription. Anybody can make a subscription to this address in a project of their own. So
  the Cloud takes a push only when Google signed its token, the token's audience is the one the
  subscription was made with, and its verified address is the subscription's service account.
- **Routed by the address, for a grant that reads the mailbox.** At a connect, and again at each
  refresh, the Cloud asks Gmail which mailbox the new token reads (its profile) and records
  `client, address, deployment`. A grant that reads no mail gets no route: a push says when a
  mailbox changes, and the person gave that only with leave to read it. A push for the address
  becomes `google/gmail-push-received` on `/integrations/<name>/<address>`, a statement of the
  Cloud's mind, for each deployment that connected the mailbox. Its payload is
  `{ emailAddress, historyId, messageId, publishTime }`: that the mailbox changed, and nothing of
  the mail. The deployment reads the change itself (`users.history.list`).
- **A mailbox has one watch per Google project.** Deployments that connected the same mailbox
  share it, and what one of them does to it, it does to all. So no deployment stops the watch
  (`users.stop` would end the others' events), and each asks for the same watch: one that names
  labels of its own would change what the others get. The watch ends by itself a week after its
  last renewal, and a push for an address nobody connected is dropped. The Cloud cannot hold a
  deployment to this: the call is the deployment's, with the person's token.
- **Gmail drops some.** It sends at most one notification a second for a mailbox, and says that
  one may be late or lost. A deployment that must miss nothing also reads the history at its
  daily renewal.

At Google Cloud, in the OAuth client's project: the Pub/Sub API on; a topic; on the topic, the
role Pub/Sub Publisher for `gmail-api-push@system.gserviceaccount.com` **and for nobody else**; a
service account with no role and no key; the role Service Account Token Creator for the project's
Pub/Sub service agent (`service-<project number>@gcp-sa-pubsub.iam.gserviceaccount.com`); and one
push subscription on the topic, to `https://<cloud>/clients/<name>/webhook`, with authentication
on, that service account, and the same address as its audience. The client's `gmailPush` in
`CLOUD_CLIENTS` then names `{ topic, audience, serviceAccount }`. A client that does not name all
three takes no push: the address answers 404.

What the token proves, and what it does not: that a push is the Cloud's own subscription's. It
does not prove that Gmail published the message. Whoever may publish to the topic can make a push
about any mailbox, so Gmail's account is the topic's only publisher. `gmailPush` has two more
fields, `issuer` and `certs`, for a fake that stands in for Google on dev. Production's config
never names them (`scripts/production-clients.ts`): they say whose signature counts.

## Calendar's push

Google Calendar pushes a change to an HTTPS address that the watcher names, with no Pub/Sub. A
push has headers alone: no body, and no signature.

- **The channel is the deployment's.** It asks Calendar to watch the person's primary calendar
  (`events.watch`) with the person's token, and names the Cloud's address and a token for the
  channel. Only the user and client that made a channel can stop it.
- **The token is the push's only proof, and its route.** The Cloud makes it: a random id and
  the HMAC of that id under the Cloud's key, so that the Cloud refuses a token it did not make
  before it reads a row. A row says whose the id is. At each connect of a grant with a calendar
  scope the Cloud writes `google/calendar-connected` on `/integrations/<name>/<address>` for that
  deployment, with `{ emailAddress, api, address, token }`: the calendar (the id of the primary
  calendar is the account's address), the origin of Google's API as this client has it, where a
  channel delivers, and the token. Two deployments that connected one calendar have a token each.
- **A new connect makes a new token.** The token lies in the clear on the deployment's log and
  in each channel at Google. So a connect replaces it, and the one before is good for a day
  more, for the channels that still carry it. To end a token that got out, connect again.
- **A push with a token the Cloud made** becomes `google/calendar-push-received` for that one
  deployment, with `{ channelId, resourceId, resourceState, messageNumber }`: that the calendar
  changed, and nothing of what. The deployment reads the change itself (`events.list` with its
  sync token). A push with any other token gets 404. A message of a channel that comes again is
  relayed once; a channel is known by its token, id and expiration, so each channel a deployment
  makes has a new id, as Google asks.
- **The token lasts while the grant refreshes.** Its rows are kept again at each connect and
  refresh of a grant that reaches the calendar, and lapse seven days after the last one. They go
  at once when the Cloud lets go of the account for that deployment: its grant was refused twice,
  or the deployment let go itself. A grant that simply stops refreshing gets pushes for up to
  seven days more, while a channel of it lives (the deployment makes two-day channels).
- **One address, two grants, a day's gap.** A Google person is known here by their address. A
  deployment may hold two grants of one address: one that reads mail, and one for the calendar
  alone. When Google refuses one of them twice, the Cloud lets go of what that address connected
  for the deployment: the mailbox's route and the calendar's token both go. The grant that still
  works brings its own back at its next refresh, which a deployment makes once a day, so up to a
  day of pushes is missed, and the deployment's daily read finds what they were about.
- **Calendar drops some.** Google says so. A deployment that must miss nothing also reads the
  changes once a day.

Nothing is made in Google's console for this. On production the scope
`https://www.googleapis.com/auth/calendar` is among the client's default scopes
(`scripts/production-clients.ts`). A grant made before it was there has no calendar: the person
connects Google again.

## An app that served another platform first

iterate's apps at GitHub and Slack served os.iterate.com before the Cloud, and each has addresses
that exist once: its webhook address, and for a GitHub App the address its install page returns to.
When those point at the Cloud, a client's `passOn` keeps the other platform working:

- **A callback the Cloud did not begin** (its `state` is not the Cloud's, or it has none) is
  redirected to `passOn.callback` with its whole query.
- **Every delivery the provider signed** is also sent on to `passOn.webhook` (or
  `passOn["interactivity-webhook"]`), with its bytes and its provider's headers as they came,
  whether or not a deployment here gets it. It goes through an outbox per client: a 5xx, a 429 or
  no answer is tried again for a day at most, and any other answer is final.

**A GitHub App's install, both ways.** With "Request user authorization (OAuth) during
installation" on, GitHub returns from the install page with a code, and the Cloud's callback sends
it on to the deployment. With a Setup URL, GitHub returns with the installation and no code: the
Cloud then sends the person on to authorize the App, and they come back with a code. The exchange
repeats a redirect URI only when the authorize named one; the callback's proof says which, so a
vault need not know how the App is set up.

**Slack.** A workspace installs the app through the Cloud's client like any other connect; the bot
token is the secret's access token. Slack's check of a new address (`url_verification`) is
answered here and passed on to nobody. `app_uninstalled` ends the workspace's connections.

A Slack delivery goes to the deployments of the workspace the app is installed in
(`slackWorkspaceOf`), and its payload's `teamId` is that workspace. In a channel shared by Slack
Connect, the person who acted can be of another workspace. For what people press
(`block_actions`), Slack names the installation in `team.id` and the person in `user.id` with
`user.team_id`. Two things for a deployment that handles a press (the default config handles
none, `core/configs/default/slack.ts`):

- Who pressed is `body.user`, never `teamId`. A press is an instruction, so its handler checks the
  person as a message's sender is checked (`slackSenderMay`): a full member of the installation's
  workspace, whose confirmed email is a member's.
- An app installed for a whole organization gets `team: null` in a press. `slackWorkspaceOf` then
  names no workspace, and the press reaches no deployment. Slack's Bolt takes `user.team_id` in
  that case.

## The bot at X

One X account is iterate's own (@iterate). A person talks to it by direct message or by
mentioning it. An operator connects that account once, with a link only the Cloud's key can make
(`scripts/bot-link.ts`). Its tokens are the only tokens this Worker keeps, sealed under the Cloud's
key. A person links their own X account from their deployment
(`beginOAuth(path, { client: { cloud: "x", origin: "https://cloud.iterate.com" } })`); that account's tokens stay in the deployment.

- **In, by push:** X sends the bot's events as they happen (its Activity API) to
  `POST /clients/<client>/webhook`: a post that mentions the bot, and an unencrypted direct
  message. X signs each delivery with the app's client secret, and checks the address with
  `GET /clients/<client>/webhook?crc_token=…`. At its first alarm after it is connected, the
  bot's object registers that webhook at X and subscribes its own account (`src/bot.ts`).
- **In, by read:** the net under the push. The bot's object reads what reached the account every
  minute while X does not push here (the log says why, `bot.push-refused`, and X is asked again
  after ten minutes), and every five minutes
  when it does (`bot.read-fallback` marks a message the push missed).
- Either way, a message from a linked account goes to the deployment that linked it, once, as
  `x/message-received` on `/integrations/<client>/<x user id>`, signed as a statement of the
  Cloud's mind ("The Cloud signs as its own mind"). A message from an account nobody linked is
  dropped.
- **Not read:** a message typed in X's app is X's encrypted Chat. X's API lists and pushes only
  unencrypted direct messages; a Chat message needs keys of the bot's own. A person reaches the
  bot today by mentioning it.
- **Out:** the deployment answers at `POST /clients/<client>/ask/reply`, a request its vault signs.
  The bot sends a direct message only to an account that deployment linked. It posts in public
  once per mention, only under a mention that is the person's own post (not their reply in someone
  else's conversation), and only text that names no account and carries no link.
- **These limits are the bot's.** They hold for what @iterate says. A person's own grant goes
  from their deployment's vault to X with their own token, never through this Worker, and does
  what its scopes allow: with `tweet.write` and `dm.write` it posts and sends as that person.

## How each side knows the other

- **A deployment's name is its control plane's hostname.** `iterate.ada.com` by convention, or
  any hostname its owner chose (`cp.ada.com`). The Cloud knows this one form of a name, and no
  rule reads a name's labels:
  - A statement names its deployment as `mind`, with that hostname (src/signed.ts, the format
    of `iterate/signed` on a stack). A deployment signs each request with the key that its auth
    Worker publishes at `https://<name>/keys/stack.json`: its stack's working key, ML-DSA-65,
    which signs nothing until the mind's identity lists it. The statement names this Cloud, the
    client, the route and the hash of the body, lasts ten minutes at most, and counts once. The
    Cloud's own key is P-256; the signature's `format` says which check runs.
  - A callback address belongs to the deployment whose name is the address's hostname, whole:
    `https://<name>/secrets/oauth/callback`. The page a person confirms on shows that hostname.
  - Two hostnames of one domain are two deployments. A code, a connected account and a sealed
    refresh token are each bound to one name, and a statement under another name uses none of
    them.
- **What makes any hostname safe as a name.** A mind's own code answers on every hostname of its
  zones but the control plane's. If that code could serve `/keys/stack.json`, it could publish a
  key as a deployment named by its hostname, and a person would read that hostname on the
  Cloud's page as the mind's. So the stack's boundary Worker answers `/keys/stack.json` itself, with
  404, on every hostname but the control plane's (core/boundary-worker src/host-session.ts): a
  mind's own code can publish no key, and the one name of a mind that has a key is its control
  plane's hostname. The mind's code never gets `/.well-known/iterate` either: there the boundary
  gives the auth Worker's answer, the mind's signed identity log, on each hostname that the log
  lists. The Cloud follows no redirect
  when it reads a key.
- **The Cloud is its key.** A deployment trusts it by a member's consent on the installer's
  enrolment page, confined to `/integrations/`: the deployment's `/keys/enrol` gives the name
  `iterate-cloud` only to the key that the Cloud's origin publishes at `/.well-known/iterate-cloud`.
  Everything the Cloud writes to a deployment is a statement posted to `https://<name>/statements`:
  for another deployment, signed by the Cloud's mind; for the Cloud's own mind and on dev, signed
  by that key ("The Cloud signs as its own mind").
- **There is no register of deployments.** A deployment gets an account's events and tokens by
  connecting that account: at the code exchange the Cloud asks the provider what the new token
  reaches, and records `client, account, deployment`.

## The Cloud signs as its own mind

The Cloud's own mind is iterate's, and its name is its control plane's hostname
(`iterate.iterate.com`), as any deployment's is. Every statement for another deployment, a relayed
delivery and a word for one deployment alike, is in the mind form alone (`statementFor` in
src/worker.ts). It has one landing place on the deployment.

- **The mind form.** The auth Worker of the Cloud's own mind signs it with that mind's stack key
  (binding `MIND_AUTH`, the mind's name `MIND_HOSTNAME`):
  `{ mind: <the deployment>, from: <the Cloud's mind> }` on
  `/minds/<the Cloud's mind>/integrations/<name>/<account>`. A relayed delivery with an id names
  it in `about` (`cloud:<name>:<id>`), so the deployment stores it once, however often it comes.
  It lands there if the deployment's owner let the Cloud's mind in with a rule that reaches that
  path (core/configs/default/minds.md), as an event of that mind. Its config's
  `processMindEvent` reads it.
- **The key form** is left for two cases. It is signed by the Cloud's own key, on
  `/integrations/<name>/<account>`, where the deployment trusts that key.
  - The Cloud's own mind, `MIND_HOSTNAME`: no mind signs for itself (core/auth-worker
    `signedByStack`), and iterate.com's own accounts carry its GitHub mirror, which reads them on
    `/integrations/<name>/<account>`.
  - A Cloud with no mind of its own (no `MIND_AUTH` or no `MIND_HOSTNAME`), as on dev.

**Signed again at send time, in the deployment's own outbox.** Each statement, a delivery or a
word, is held for its deployment in the key form, signed by the Cloud's own key with no call out, and its `about` is
kept beside it. That deployment's outbox signs it again in the mind form when it sends it, with the
same path, type, payload and `about`, and the rest of its day. So a signature of the Cloud's mind
that fails for one deployment holds back no other's. When `MIND_AUTH` does not sign in three
seconds, nothing is sent, the statement stays held, and the next alarm tries again
(`cloud.mind-sign-failed`). No statement for another deployment goes in the key form. Each release
of this Worker reads a held row's shape, so a rollback to an earlier release sends every held
row.

**A deployment that refuses the mind form** ("is not let in here", "the key is not one this mind
knows", "adds events under" for a rule that does not reach the path) gets the same statement again,
with a wait that grows to 15 minutes, until its day ends. Each refusal is in the log with its reason
(`cloud.statement-refused`). Its queue waits behind it. A refusal that says the statement was seen
or expired counts as taken. So a mind moves over by itself as soon as its owner lets the Cloud's
mind in, within the statement's day.

`POST /clients/<name>/ask/mind-form` (core/configs/default `sayMindForm`) is still answered,
`{ ok: true, reads }`, so a deployment on an older release does not fail at its connect. The word
changes nothing.

## What the Cloud holds for a deployment: its status

`POST /clients/<name>/ask/status` is an ask like any other. It answers, for each deployment:

- `mind`, its control plane's hostname, and `id`, the mind its hostname is pinned to (null for one
  that never asked with an identity log);
- `movedTo`: another mind that the hostname's log proved, and when;
- `accounts`: each account that delivers to it, `{ client, account, since }`. `account` is the
  provider's own id: a GitHub installation, a Slack workspace, an X user, and for Google the
  mailbox's address;
- `letGo`: each account it let go of;
- `held` and `oldestAt`: how many statements wait in its outbox, and since when;
- `lastRefused`: its last refusal of a statement, `{ reason, status, at }`.

No token, no secret and no person's id is in it: who connected an account stays here. The list of
every deployment shows a Google account, a person's mailbox address, by its domain alone
(`*@example.com`); a deployment's own row shows its own.

A status reads every row of each kind (routes, claims, accounts let go), a deployment's own too:
the rows are keyed by client and account. It reads 20,000 of each at most, which is 1,000 accounts
at the most deployments one account has (20), or 20,000 single connections. Past that, the answer
says `partial: true`, and the log `cloud.status-partial`.

- **A deployment reads its own row.**
- **The Cloud's own mind reads every deployment's row,** 200 at a time: an answer's `cursor` is the hostname to ask on from with `{ cursor }`, and null after the last. That is
  the hostname `MIND_HOSTNAME`, when it asks with an identity log, and with the id `MIND_ID` when
  that is set. It is the list for the Cloud's own page, so whoever reads that mind's page reads
  it.

**A hostname that serves another mind gets nothing.** `MIND_AUTH` signs for whatever mind a
hostname serves when it signs. So before an outbox signs, it reads the hostname's identity log,
kept a minute. When the hostname is pinned to one mind and its log now proves another, nothing is
sent: the statement waits, and the log says so (`cloud.mind-moved { mind, known, serves }`). What
the Cloud holds for the hostname was for the mind it knew, and that mind may come back, or its
hostname may have been taken. A hostname that is pinned to no mind, or whose log could not be read,
is sent to as before.

**Clearing a hostname that moved: `POST /clients/<name>/ask/forget { hostname, known?, serves? }`.**
The pin stays until someone clears it. So an owner who erases a mind and deploys a new one at the
same domain has a new mind id, and that mind is refused until the hostname is cleared. Two askers
may clear it:

- the old mind itself, from any hostname: its log proves the id that the hostname is pinned to. So a
  mind may clear its own hostname at any time, moved or not: one ask of any of its agents drops
  all its connections at the Cloud;
- the Cloud's own mind, for an old mind that is gone: `known` is the pinned id and `serves` is the
  other id that the hostname's log proved in the last day, as `ask/status` shows them (`id` and
  `movedTo`);
- the Cloud's own mind, for a hostname that is pinned to NO mind and serves none now: it names the
  hostname alone. The Cloud clears it only when no identity log and no `/keys/stack.json` answers
  there, and a statement in its outbox has waited an hour. These are the hostnames that moved before
  the Cloud pinned ids: no id proves their owner, so
  the ask is the Cloud's own word, and an owner whose mind was only down for that hour connects
  each account again.

The clear drops the hostname's routes, claims, accounts let go, refusals and calendar channels, and
what its Outbox holds: the statements that wait and the pin. The nonces stay until their
statements end, so a statement used before the clear is refused after it too. It cannot be undone:
the statements that waited are lost, and each account is connected again through the provider. The
next mind that asks from the hostname is pinned. The Worker logs
`cloud.mind-forgotten { mind, known, serves, by, rows, held }`.

## Who the Cloud serves: the minds that iterate enrolled

A member of iterate enrols a mind by its id: a rule on iterate's `/minds/<id>` that lets the mind
add events under its own context. iterate's auth Worker answers whether it holds, over its
`Enrolments` entrypoint (binding `ENROLMENTS`; core/auth-worker `enrolledHere`). The Cloud keeps
each answer a minute for each id, so a rule that ends, or a new one, counts within a minute.

The gate (`shutOut`) is on every ask and token, and on each statement the Outbox sends. While it
is `on`, it is on the page before the provider (`begin`) too. That page names a hostname with no
proof, so in `log` mode it reads nothing for it. A mind may always let an account go, say its word on the form,
and read its own status. The Cloud's own mind (`MIND_HOSTNAME`) is served by its name, because a
mind does not meld with itself.

`CLOUD_ENROLMENT` says what a mind that is not enrolled meets:

- **Not set, or `log`:** it is served, and the Worker logs
  `cloud.not-enrolled { mind, id, gate, refused: false }` once a minute for each hostname. So the
  minds that `on` would refuse are in Workers Logs before anyone sets it.
- **`on`:** it is refused with 403 and words that say where its owner enrols. A connection is kept,
  and the next refresh after an enrolment works. Its statements wait in its Outbox, with the words
  as `lastRefused`, until it is enrolled or a day passes. A mind that serves no identity log has no
  id to enrol, so it is refused too.

A read that fails (`cloud.enrolment-unread`, once a minute for each hostname) is refused with 503
when `on`, and served when not.
Without the binding (a dev Cloud), every mind is served.

## What is kept

Everything below is kept under a deployment's name, its control plane's hostname. The Cloud reads
a row only for the name that is in it. So a deployment whose control plane moves to another
hostname is a new deployment here: it connects its accounts again, and what was kept for the
name before lapses as said below, or stays unread.

- **Routes:** which deployments connected which provider account, and the person at the provider
  who connected it. No token, no secret. A route lasts while that person's grant refreshes and
  they still administer the account: each refresh shows again what they administer, and GitHub's
  own events end a removed installation and a withdrawn authorization. A refresh the provider
  refuses ends what they connected only the second time, an hour or more after the first: the
  first refusal may come from an answer that was lost (below). At most 20 deployments connect one account. A deployment that
  never refreshes that grant keeps its route: nothing shows the Cloud that the person lost the
  account. `GITHUB_CLAIM_DAYS` is the limit for that: with it, a GitHub claim older than that
  many days gets no installation token and no delivery until the person's grant refreshes again
  (the route itself stays). The dev Cloud sets it to 14 (internal-packages/installer
  wrangler.jsonc). Production does not set it yet: a deployment that does not refresh each grant
  on a schedule refreshes only after GitHub refused the person's token, and works with
  installation tokens alone, so the limit would cut it. A Gmail mailbox's route is by its
  address and is its own person's: nobody else administers a mailbox. It is made again at each
  refresh of a grant that reads the mailbox. A person who connects again with no leave to read
  mail leaves the old route behind, and no refusal ends it, because the deployment's vault
  replaced the grant that made it. `GOOGLE_CLAIM_DAYS` is the limit for that, in the same way: a
  mailbox's claim older than that many days gets no push. It is set nowhere yet.
- **An inbox per client:** a delivery the provider signed, from the moment it comes until it is
  handed on, and its id for a day so that one sent again is relayed once. The webhook's address
  writes there and answers 200: it waits for no other object of the Cloud, so a delivery survives
  one that fails for a while (on 2026-11-11 the routes object failed for two minutes, and 24
  deliveries got 503). The inbox hands each delivery to the outboxes below, and tries again while
  one of them, or the routes object, does not answer. A delivery that is a day old is dropped.
- **An outbox per deployment:** signed events not yet taken. One is deleted when the deployment
  takes it and dropped after a day. A deployment that is down, or does not trust the key yet, is
  tried again. During a deploy two releases run side by side for some seconds, so a change of
  what `Outbox.put` takes can make a row whose `signed` is no signed statement: keep `put` able
  to take what the release before sends. Such a row holds back nothing behind it. One that
  holds what was to be said is signed at the head and goes, with its own time and `about`
  (`cloud.outbox-row-signed-late { mind, key, at }`). One that says nothing readable is set aside
  under `unread:` for the rest of its day (`cloud.outbox-row-unreadable { mind, key, at }`).
- **What no row and no release can do to a queue** (the guards after 23 Nov 2026, when one such
  row stopped every delivery to iterate.com for three hours):
  - _A writer refuses what it does not read._ `put`, `pass` and `take` check what they are given
    and throw a `TypeError` on anything else, with no row written. The caller keeps its copy and
    tries again, by then with one release on both sides. So change what a writer takes in two
    deploys: first the writer takes both forms, then the caller sends the new one
    ([the rule](../../rules/structure/calls-between-objects-survive-a-rollout.md)).
  - _A writer keeps its row and wakes the queue, or keeps nothing._ The row and its alarm are one
    write. The bound runs after it, and a fault there is `cloud.queue-bound-failed { queue, error }`
    in the log, never a failure for the caller, who would send the row a second time.
  - _An alarm that throws does not end the queue._ The throw is caught:
    `cloud.outbox-alarm-failed { row, dropped, tries, error }`, and the alarm comes back after
    10 s, doubled each time, 15 minutes at most. `row` is the row that the alarm worked on, in
    whichever queue. When that row still throws after its day is over, it is dropped
    (`dropped: true`), and no other row is touched: a row that the alarm reads leaves by the
    alarm's own path. So nothing holds a queue for longer than a row is held.
  - Each of these three lines is an error, and the prd fault alarm reads this Worker
    (`apps/prd-fault-alarm` of the iterate mind's `/repos/config`): a burst pages within 15 minutes.
- **Each of these queues is a buffer with three bounds,** whichever comes first: a day, 1,000 rows,
  and about 16 MiB (`HELD_MS`, `QUEUE_MAX_ROWS`, `QUEUE_MAX_BYTES`). A queue is one deployment's
  outbox, one inbox's queue, or one account's rows that wait aside in an inbox. After each write
  the oldest rows over a bound are deleted, and the log line `cloud.queue-over` says whose they
  were, how many, and from when: nothing of their content. So a deployment that is away for long
  loses the oldest of what came for it, and the Cloud keeps no copy. A provider's word that a
  connection ended is the one row that count and bytes never delete: it leaves by age alone.
- **The bot's own tokens,** sealed. They are ours.
- **A refresh's answer, for two days,** when the provider replaced the refresh token in it. An
  answer that does not arrive leaves the deployment with a spent token, so a retry that shows the
  same token gets the kept answer, and the provider's token endpoint is not asked again. The row
  is sealed under a key made from the spent token, which the Cloud does not keep: it opens for
  that retry alone. It goes when a refresh shows the new token. A provider that does not answer
  in 20 seconds gets the deployment a 504, one that cannot be reached a 502, and nothing ends.
  After a 504 the Cloud goes on waiting for the provider, and keeps an answer that comes late
  the same way, since the provider spent the token for it.
- **Nothing else.** A refresh token is sealed under a key derived from the Cloud's key, bound to
  the deployment it was issued to, and handed back. Another deployment cannot spend it, and no
  table of tokens exists to steal.

## Config

Three Worker secrets, each JSON text:

- `CLOUD_KEY`: the Cloud's P-256 private key, a JWK.
- `CLOUD_CLIENTS`: each client's public facts by name (`Client` in src/worker.ts): its kind, client
  id, the provider's endpoints and API origin, a GitHub App's id and install page, a Google
  client's `gmailPush`.
- `CLOUD_CLIENT_SECRETS`: by the same names,
  `{ clientSecret, webhookSecret?, appPrivateKey?, bearerToken? }`. The App key is PKCS8 PEM.
  `bearerToken` is X's alone: the X app's app-only Bearer Token, for public post subscriptions.

Moving a client from a fake to the real provider is a change of its entry in the last two.

## Mounted in the Cloud's one Worker

The Cloud is one Worker, `internal-packages/installer`, and this package is a handler in it:

```js
import clients, { Bot, handles, Outbox, Routes } from "@iterate-com/cloud-clients";
export { Bot, Outbox, Routes };
// in its fetch, before its own routes:
if (handles(new URL(request.url))) return clients.fetch(request, env);
```

That Worker's config then needs: the Durable Object bindings `ROUTES`, `OUTBOX` and `BOT` for
those three classes (SQLite-backed), the three secrets below, the compatibility flag
`global_fetch_strictly_public`, and `/clients/*` and `/.well-known/iterate-cloud` among the paths
its Worker answers before its assets. After a deployment enrols, one call delivers what was held
for it at once: `env.OUTBOX.get(env.OUTBOX.idFromName(name)).wake()`, where `name` is the
deployment's control plane's hostname.

## The dev Cloud

The one Cloud Worker on dev, `https://iterate-cloud.iterate-dev-preview.workers.dev`
(internal-packages/installer). Its clients point at fakes: GitHub, Google and Slack at the pet shop
(internal-packages/dummy-petshop), X at `dev/fake-x`, a fake with direct messages and mentions
whose controls let a check say something to the bot and read what the bot sent.
`scripts/dev-petshop.ts <origin>` registers the dev GitHub App at the pet shop again if the shop
dropped it, and `scripts/dev-petshop.ts <origin> fire` has the shop deliver one signed webhook.

### This package alone

`wrangler.jsonc` here deploys this package as a Worker of its own:

- `iterate-cloud-clients-dev`, on the dev account at workers.dev;
- with no installer, and its own `Routes`, `Outbox` and `Bot`.

To deploy it:

1. Put the three secrets of "Config" with `wrangler secret bulk`, from clients of its own at the pet
   shop.
2. Run `pnpm deploy:dev`.

Without `MIND_AUTH` it sends the key form alone. A proof of the mind form adds a dev mind's auth
Worker and hostname to the config, as its comment shows. This is how the proofs of #1203 and #1204
ran. Delete the Worker at the proof's end.

The config has no production env. Production's clients run in `iterate-cloud-prd`, the installer's
script. Two configs must never name one script. So this config takes that name only in the change
that removes it from the installer's config. That is when the installer goes (Jonas's decision),
with a migration that deletes the installer's `Deployer` class.

## Production

`scripts/production-clients.ts` makes the two client secrets from iterate's existing apps, as
production's Doppler config holds them. `scripts/synthetic-delivery.ts` sends a signed delivery
about nobody to a webhook address: the check before a provider is pointed at it.

### The apps' default scopes

`scopes` in a client's public facts are what a vault asks for when the deployment names none
(core/secrets-worker `normalizeSecretOAuth`). A deployment may name fewer or more, and `begin`
lets it, except a sign-in. `urls` is the pin of the secret, and a deployment cannot change it.
Production's, from `scripts/production-clients.ts`:

- Google: Gmail (`gmail.modify`, `gmail.send`, `gmail.labels`) and `calendar`, with `openid` and
  `userinfo.email`; pinned to `gmail.googleapis.com`, `www.googleapis.com` (Calendar and Drive)
  and `docs.googleapis.com`, so that a deployment that asks for `drive` or `documents` itself can
  use them. Those two are not defaults: `drive` is restricted at Google and `documents`
  sensitive, and until iterate's app is verified for them Google shows its "unverified app"
  page.
- X: `tweet.read users.read dm.read offline.access`, pinned to `api.x.com` (media uploads too,
  `POST /2/media/upload`). A deployment that asks for `tweet.write` or `dm.write` acts as the
  person, and X bills every call to iterate's X account.

A template mind names its own scopes in `cloud-scopes.ts` (core/configs/default). A grant keeps
the scopes and the pin it was made with. A change of either reaches a deployment when the person
connects again.

## Public X post subscriptions

A deployment may ask the Cloud to watch an X account's own posts, with no link to that account.
The service is off until the Cloud Worker has `X_POST_SUBSCRIPTIONS`, as JSON
`{ "limit": 2, "minds": ["iterate.iterate.com"] }`: `limit` is how many X accounts are watched in
all (1 to 100), and `minds` names the deployments that may ask, each by its control plane's
hostname. Anyone who publishes a key can sign an
ask, and X bills each delivered post to the Cloud's X account, so the Cloud names who may spend it.

A deployment signs the usual `events.iterate.com/integration/ask-requested` statement over the
route and the body, and POSTs to:

- `/clients/x/ask/subscribe` and `/clients/x/ask/unsubscribe`, with exactly
  `{ "eventType": "post.create", "userId": "300637864" }`. Both answer 200
  `{ userId, eventType, subscribed }`.
- `/clients/x/ask/list`, with `{}`. It answers 200 `{ subscriptions: [{ userId, eventType }] }`:
  the asker's own.

Refusals: 400 for another body, 401 for a statement that does not sign this request, 403 while the
service is off or for a deployment not in `minds`, 429 when `limit` accounts are watched already,
503 while the bot is not connected, X does not push to the Cloud yet, or the Cloud has no app
token for X, and 502 when X refuses.

The Cloud subscribes once per account, to its bot's webhook, and keeps which deployments asked.
Such a subscription belongs to the X app, not to the bot's account: X lets the bot's token make
one but answers its delete with 400 `UserNotAuthorized`. So the Cloud makes, lists and deletes
them with the app's app-only Bearer Token, `bearerToken` in `CLOUD_CLIENT_SECRETS` for the client
(Doppler's `ITERATE__INTEGRATIONS__X` field `appBearerToken`, read by
`scripts/production-clients.ts`). A deployment's unsubscribe removes only its own interest; the last one deletes
the subscription at X. A create that X refuses or does not answer leaves nothing behind: the
deployment asks again. A create that X says it has already (400 `DuplicateSubscription`; a 409 too) takes X's id from
its list; when X
does not give the list, the ask answers 502 and the log has `bot.post-subscription-unnamed` with
the account, for an operator to delete at X. A
delete that X refuses leaves the subscription orphaned, with X's answer in the log: the bot's
alarm tries the delete again, and after a day it logs `bot.post-subscription-leaked` with X's id
for an operator to delete at X. An id X does not have any more (its 400 `SubscriptionIdInvalid`,
or a 404) counts as deleted.

Each post X delivers goes to `/integrations/x/<userId>` as `events.iterate.com/x/post-created`,
signed by the Cloud, to every deployment that watches its author, through the inbox and the
outboxes. Its payload has `event_uuid`, `event_type`, `filter.user_id` and the post: `id`,
`author_id`, `text`, and when X sends them `created_at`, `conversation_id`,
`in_reply_to_tweet_id` and `referenced_tweets` (a reply, a quote and a repost are posts too). A
post by anybody else is answered and dropped. The Cloud takes one delivery id once; X may send the
same post under a new delivery id, so a consumer deduplicates by post id.