Search

Sign in to launch Copilot/Codex from the palette.

Back to prompts

Sign in with Cloudflare Funnel

Public apps where people sign in with their own Cloudflare account and pay for everything they use: inference, sandboxes and background work. The host pays a fixed floor. OAuth setup, invariants, pitfalls, and a checklist.

Operating Docs Updated Oct 26, 2026 ~5.2k tokens
2.6% of 200k
# Sign in with Cloudflare Funnel

Put this at the start of a session when you build a public app that people sign in to with their own Cloudflare account. Everything that costs money per person is billed to that person, not to you. The host pays a small fixed floor and nothing that grows with users, idle time, or loops.

Reference app: [coil](https://coil.coey.dev). Stack: foldkit + Tailwind client, one Worker, Durable Objects. This goes with [Repo Shape](/prompts/repo-shape).

---

## The funnel: a `*.coey.dev` app with Sign in with Cloudflare

### Why this shape

A public app should cost the host nothing per user, and it should show the Cloudflare Developer Platform working. Each person signs in with their own Cloudflare account. The app runs on the host's Workers, but **every model call, every sandbox, every background job and every byte of per-user storage is billed to the person who caused it**.

The split is one-sided on purpose:

| Host account pays (fixed floor) | Signed-in person's account pays (everything else) |
|---|---|
| The public Worker that serves the landing page and routes requests | Workers AI and AI Gateway calls |
| The Directory and grant Durable Objects (small, request-driven, no alarms except grant expiry) | Containers, sandboxes, browsers and long-running Durable Objects |
| Static assets | Background jobs, polling, schedules and queues |
| | Per-user storage (R2, D1, KV, vectors) and anything that grows with use |

If you can't put a cost on the right side of this table, the feature doesn't ship in the funnel. Treat "host pays per user" as a bug, the same way you'd treat "host pays for inference".

### The deal with the person signing in

They lend the app a token that can spend their money. The app owes them:

- **One account, chosen on purpose.** The app never acts on an account they did not pick in its own UI.
- **Least authority.** Only the scopes the shipped features need. Their token is never shared, logged, or used for anything but their own calls.
- **A ceiling.** Per-user rate and spend limits they can see, so a bug or a hostile tab cannot drain their credits.
- **A clean exit.** Sign out revokes the token and deletes the grant. Grants nobody uses expire.

### The flow

```text
visitor -> https://<app>.coey.dev            (public landing, no gate)
        -> "Sign in with Cloudflare"
        -> dash.cloudflare.com OAuth consent  (person may tick several)
        -> /oauth/callback                    (code + PKCE exchange)
        -> /oauth/account picker if the token sees more than one account
        -> grant saved, encrypted, in that person's own Durable Object
        -> /oauth/gateway picker if more than one usable gateway
        -> app; each model call uses the person's token on the person's account
```

### Invariants (do not break these)

1. **Auth mode is set per instance:** `COIL_AUTH=cloudflare` or `access`. Internal instances use Access. The `*.coey.dev` instances use Cloudflare OAuth.
2. **No fallback to host inference for signed-in users.** A `cf:` user's Workers AI and AI Gateway calls go to `accounts/<their account>/...` with their bearer token. If that fails, show the error; never quietly bill the host.
   - **Exception, off by default:** an instance-wide model gateway (`COIL_MODEL_GATEWAY_URL` plus `MODEL_GATEWAY_SERVICE_TOKEN`) that pays with the **operator's** money. Public `*.coey.dev` instances leave it unset. If an operator turns it on for a demo, it needs an Access **service token** (never a personal `cloudflared access` token), a per-user daily budget returning `429`, a **global** daily budget that returns `503` once spent, and an expiry date in the config. It is a promotion, not a permanent way to pay.
3. **Read the account route fresh on every call.** Account ID, gateway and token come from the person's grant Durable Object at call time, not from a copy the thread keeps. Then a gateway switch applies on the next call, and an empty account ID can never be sent.
4. **Only gateways with authentication on.** A gateway with auth off ignores the user's token and returns `x-api-key header is required`. The picker greys these out and the server rejects them.
5. **Show whose bill it is.** The UI shows the account and gateway in use, today's usage against the person's limit, and lets the person switch (sidebar button: `/oauth/gateway`).
6. **Secrets never go to the browser and never get printed.** The OAuth client secret, session secret and token key are Worker secrets. Tokens are stored **encrypted** (AES-GCM with `TOKEN_ENC_KEY`) and never appear in logs, errors, receipts or `/oauth/me`.
7. **One grant per person, isolated.** Each grant lives in its own Durable Object: `GRANTS.idFromName(userId)`. The Directory maps sessions to user IDs and never holds tokens, so one bug cannot read everyone's tokens.
8. **The account is chosen on purpose.** After the callback, list the accounts the token can see. Exactly one: use it. More than one: show `/oauth/account` and save nothing until the person picks. Never default to the first.
9. **Least scopes.** Request only the scopes in the table below. Adding one is a reviewed change with a reason in the table.
10. **State and CSRF.** `state` (random, single use) and the PKCE verifier live in the 10-minute flow cookie and must match at the callback. Logout and account or gateway switches are POST only, check `Origin` is the app's own, and the session cookie is `SameSite=Lax`.
11. **Host compute only runs while a request from a signed-in person is in flight.** The host Worker has no cron triggers. Host Durable Objects set no alarms except the one that deletes unused grants (invariant 15). Polling, schedules, inbox watching, retries and fan-out run **in the person's account**, or don't run.
12. **Per-user compute lives on the person's account.** Containers, sandboxes, browser sessions and long-lived Durable Objects are created with the person's token on the person's account, never as a host binding. If an API can't do that yet, the feature runs on the person's own deploy (see "Background work" below) or isn't in the funnel.
13. **Every host-side cost has an owner, a ceiling and a kill switch.** Each host Durable Object instance knows its `userId`. Host spend is metered per user (requests, wall time) and capped. One `HOST_WORK_DISABLED=true` var turns off all host-side work except sign-in and sign-out, with no redeploy of code.
14. **No grant, no work.** If a person's grant is missing, expired, revoked, or the refresh fails, everything tied to that person stops: alarms are deleted, queues drained, containers stopped. Work is never kept alive "for when they come back".
15. **Unused grants expire on a timer, then everything else follows.** The grant Durable Object's one alarm deletes the grant after 30 days unused, and that runs invariant 14. That alarm runs once per grant per day at most.

### OAuth client (one per app, made by hand in the dashboard)

Go to Manage Account, then OAuth clients, on the account that owns the zone.

| Field | Value |
|---|---|
| Response type | Code |
| Grants | Authorization Code, Refresh Token |
| Token auth method | Client Secret Basic |
| Redirect URLs | `https://<app>.coey.dev/oauth/callback` only. Make a **separate** dev client for `http://localhost:<port>/oauth/callback` |
| Client URL | `https://<app>.coey.dev` |
| Scopes | `offline_access user-details.read ai.read aig.read aig.run` (see the scope table) |
| Do NOT request | `openid`: it is rejected for these clients |
| Publisher | TXT record `cloudflare_oauth_client_publisher=<value>` on `<app>.coey.dev`, then make the client **Public** |

| Scope | Why | Checked against |
|---|---|---|
| `offline_access` | Refresh without signing in again. Drop it if one-hour sessions are fine. | OAuth refresh grant |
| `user-details.read` | Show who is signed in | `/oauth2/userinfo` |
| `ai.read` | Run Workers AI models. `POST /accounts/{id}/ai/run` accepts **Workers AI Read or Write**, so Read is enough. | API reference, Accepted Permissions |
| `aig.read` | List gateways for the picker. `GET /accounts/{id}/ai-gateway/gateways` accepts AI Gateway Read or Write. | API reference, Accepted Permissions |
| `aig.run` | Call provider models through their gateway | AI Gateway authentication |

Do **not** request `ai.write` (it also allows changing Workers AI resources, such as finetunes) or `account-settings.read`: `GET /accounts` lists no required permission and returns the accounts the token was granted. Confirm both with the receipt: the account picker still lists accounts and a turn still runs. Only add one back if a real call fails without it, and write the failing call into this table.

- The **client secret is shown once.** Pipe it straight into `wrangler secret put OAUTH_CLIENT_SECRET`.
- No OAuth scope and no wrangler or cf token can create OAuth clients. It is a dashboard step every time.

### Worker config

- **Secrets:** `OAUTH_CLIENT_SECRET`, `SESSION_SECRET` and `TOKEN_ENC_KEY` (each `openssl rand -hex 32`), plus `MODEL_GATEWAY_SERVICE_TOKEN` only if the operator gateway is on.
- **Vars:** `OAUTH_CLIENT_ID`, `COIL_AUTH=cloudflare`, and optionally `COIL_USER_GATEWAY` (the preferred gateway name).
- **Always pass `CLOUDFLARE_ACCOUNT_ID=<id>`** to `wrangler secret` commands. The wrangler login covers several accounts, and the local jsonc files carry no account ID.
- **Instance config** lives in gitignored `deploy/<instance>.conf`. Copy `deploy/example.conf`. `wrangler.*.local.jsonc` is generated and gitignored.
- **Deploy:** `bash scripts/ship.sh deploy/<instance>.conf`. It runs biome, checks that the secrets exist, deploys, and runs an edge check.

### Session and cookies

- Choose cookies by **environment**, not by request scheme: prod always gets `__Host-`, `Secure`, `HttpOnly`, `SameSite=Lax`. Relaxed cookies only when `ENV=dev` and the host is localhost (WebKit drops `Secure` cookies on `http://localhost`). A proxy that rewrites the scheme must never downgrade prod cookies.
- The session lasts 30 days. The login flow cookie lasts 10 minutes. A Durable Object alarm deletes grants unused for 30 days.
- Refresh tokens inside the person's own Durable Object so two calls cannot race. Store the rotated refresh token. On `invalid_grant`, delete the grant and send the person to sign in again.
- Sign out is POST `/oauth/logout` with the `Origin` check. It revokes the token, deletes the grant and clears the cookie.
- Use **one Directory Durable Object name everywhere** (coil: `DIRECTORY_NAME='all'` in `src/directory-name.ts`). Two names means sessions written in one place are never read in the other. The Directory holds session-to-user mappings only, never tokens.

### Picking the account and gateway

- At consent, the person may tick several accounts. If the token sees more than one, send them to `/oauth/account` and save nothing until they pick (invariant 8). Never take the first.
- **Gateway choice** (`pickGateway`): `COIL_USER_GATEWAY` if it has auth on, else `default` if it has auth on, else the first gateway with auth on. If none qualify, explain how to turn auth on for a gateway. Do not just fail.
- If more than one gateway qualifies, send the person to `/oauth/gateway` after sign-in.

### Background work (polling, schedules, watchers)

This is where the host gets billed by accident. A per-user Durable Object alarm that reschedules itself "always" bills the host every 12 to 60 seconds, for every person who ever signed in, forever, even if they have nothing to do. Rules:

- **First choice: run it on the person's account.** With the person's consent and an extra reviewed scope (`workers_scripts.write`, add it to the scope table with its reason), deploy a small Worker to *their* account with *their* cron trigger. The host's job is to install, update and uninstall it. Sign-out uninstalls it.
- **Second choice: do the work on demand.** Fetch new data when the person opens the app or calls the API, with a short cache. No timer.
- **Last resort, host-side timer:** only while the person has something active, with a backoff (60s, then 5m, 15m, 1h when nothing changes), a hard cap on runs per user per day, and a stop when invariant 14 applies. The alarm handler checks for real work **before** it reschedules, and never reschedules from `finally`.
- Never call `setAlarm` in a constructor. Every wake-up (a request, a WebSocket, a deploy) would re-arm it.

### Model routing for `cf:` users

- **Workers AI models (`@cf/...`):** `api.cloudflare.com/client/v4/accounts/<acct>/ai/run/...` (or through their gateway) with `authorization: Bearer <user token>`.
- **Provider models (`gateway/...`, such as Opus):** `gateway.ai.cloudflare.com/v1/<acct>/<gateway>/anthropic` with `cf-aig-authorization: Bearer <user token>`. The person's **AI Gateway unified billing credits** pay for these. With no credits, the call returns `402 Insufficient unified billing credits` (code 2021). That is the person's account state, not an app bug.
- Rewrite Anthropic "thinking" to adaptive (coil: `rewriteBody` in `src/gateway.ts`) on **both** the host and the user path.

---

## Pitfalls seen in practice

| Symptom | Cause | Fix |
|---|---|---|
| `402 Insufficient unified billing credits` on Opus | The account's unified billing credits are empty. Every gateway on that account fails the same way. | Credits on that account, or a deliberate instance-wide model gateway (invariant 2). Don't keep switching gateways. |
| `401` straight after sign-in | The thread used a copy of the grant that was missing or empty (blank account ID) | Read the route fresh per call (invariant 3) |
| `x-api-key header is required` | The gateway has authentication off | Only allow gateways with auth on |
| Signed in, but threads can't see the grant | Two different Directory Durable Object names | One `DIRECTORY_NAME` constant |
| Cookies missing on localhost | `__Host-` or `Secure` cookies over http | Choose cookies by scheme |
| `openid` rejected at consent | The client may not request it | Leave `openid` out of the scopes |
| Wrong account billed | Person ticked several accounts; the grant took the first | Invariant 8: explicit picker, save nothing until chosen |
| One bug leaks every token | All grants in one shared Durable Object | Invariant 7: one encrypted grant per person |
| Concurrent 401s after refresh | Two refreshes raced and one stored a dead token | Refresh inside the person's own Durable Object |
| Consent screen asks for more than the app uses | `ai.write` or `account-settings.read` copied from an old list | Use the scope table; prove with the receipt |
| `wrangler secret put` lands on the wrong account | No `CLOUDFLARE_ACCOUNT_ID` | Always set it |
| Testing a gateway with the cf CLI login token returns 401 or 402 | That token isn't the user's OAuth token, and the cf CLI can't request `aig.run` | Test through the app's own receipt (`scripts/receipt-auth.mjs`) with a real session cookie |
| Host bill grows with signups, not with use | A per-user Durable Object alarm reschedules itself every minute, even when there is no work (seen on inbox.dog: about 14,000 alarms a day across two scripts for users with no active agents) | Invariants 11 and 14; background work runs on the person's account; reschedule only when there is real work |
| Alarms come back after you "fixed" them | `setAlarm` in the Durable Object constructor re-arms on every wake-up | Never arm in the constructor; arm in a request handler that checks for real work |
| Host pays for idle containers | Per-user sandbox containers started as a host binding with a long `sleepAfter` (seen across coil, coil-dev and speedrun: about 4,100 GiB-hours of allocated memory in 30 days for 3 CPU-hours of work) | Invariant 12: containers on the person's account; until then a short `sleepAfter` and a per-user cap on running containers |
| Dev instance bills like prod | A `-dev` instance with the same containers and alarms, left running | Dev instances go through the same caps, with `HOST_WORK_DISABLED=true` when nobody is using them |
| Live OAuth tokens in Workers Logs | `console.log(user)` with the whole user object, tokens included | Invariant 6; log IDs only; there is a unit test that fails if a test token appears in a log line |
| Every user's call shows up as the operator | `MODEL_GATEWAY_TOKEN` was a personal `cloudflared access` token shared by every user | Use an Access service token (`MODEL_GATEWAY_SERVICE_TOKEN`) with a per-user budget |

---

## Not this pattern: host inference

An operator tool (for example, **skin**) uses **host inference**. Its Worker's own `AI` binding or gateway pays for every call. That is fine for an operator's own tool or an Access-gated internal app. It is **not** the public `*.coey.dev` funnel.

Before you copy code, decide which one you are building:

| | Host inference (operator tools, Access apps) | User inference (this funnel) |
|---|---|---|
| Who pays | The host account | Each signed-in person |
| Auth | Access, or none | Sign in with Cloudflare (OAuth) |
| Model call | `env.AI` binding / host gateway | `accounts/<user acct>` + user token |
| Public sharing | Risky (the host pays for everyone) | Safe (no per-user cost to the host) |

The same split applies to **all** cost, not only inference. Host-side alarms, containers and storage that grow per user put an app in the left column even when every model call is billed correctly.

Apps that copied coil halfway and mixed these two usually broke in one of these ways: they fall back to `env.AI` for signed-in users, they keep a stale copy of the grant, or they leave the Durable Object name inconsistent. **Check them against the invariants above.**

---

## Proof (receipts) for an app in this funnel

- `scripts/receipt-auth.mjs <origin>` with a real session cookie file. It must check that anonymous requests are refused, a signed-in user can create a thread, the model switch works, a turn is sent, and the model answers. It must also check that a wrong or reused `state` is refused, a cross-origin POST to logout is refused, a multi-account token gets the picker, the per-user limit returns `429`, and a token is dead upstream after logout. Run it against prod after every auth or routing change. Keep the cookie file gitignored and short-lived; it is a live credential.
- Unit tests must cover: `pickGateway`, rejecting gateways with auth off, environment-based cookies, the fresh per-call route, that a `cf:` owner never touches `env.AI`, that grants are stored encrypted, and that a known test token never appears in any log line or in `/oauth/me`.
- `/oauth/me` returns `{ signedIn, account, gateway }` for quick manual checks.
- **Cost receipt** (`scripts/receipt-cost.mjs`), run against prod after every deploy and weekly. It queries Workers Observability and GraphQL analytics for the host account and fails if: the host Worker has a cron trigger; any host Durable Object alarm ran more than once per grant per day; a host container ran for a user with no request in the last hour; or host Durable Object wall time per signed-in user per day is over the budget in the config. Also turn on a **billing notification** on the host account for Workers and Containers usage, so a loop gets reported in hours, not on the invoice.

---

## New app checklist

- [ ] `deploy/example.conf` copied to `deploy/<instance>.conf` (gitignored); domain on a `coey.dev` subdomain
- [ ] OAuth client created by hand (table above); secret piped into the Worker
- [ ] `SESSION_SECRET` and `TOKEN_ENC_KEY` set; `CLOUDFLARE_ACCOUNT_ID` passed to every secret command
- [ ] Scopes match the scope table; no `ai.write`, no `account-settings.read`
- [ ] Separate dev OAuth client; prod allows only the https redirect
- [ ] Account picker shown when the token sees more than one account
- [ ] Per-user rate and spend limits on; operator gateway uses a service token
- [ ] Public landing, `/docs`, `/llms.txt` and `/robots.txt` served before the gate
- [ ] Publisher TXT record verified; client made Public
- [ ] Account and gateway shown in the UI; gateway picker reachable
- [ ] No `env.AI` fallback for `cf:` owners (grep for it)
- [ ] `receipt-auth.mjs` passes against prod
- [ ] Each new cost placed in the "who pays" table; nothing per user on the host side
- [ ] No cron on the host Worker; no `setAlarm` in constructors; no unconditional reschedule
- [ ] Containers, sandboxes and background jobs on the person's account (or capped and off by default)
- [ ] `HOST_WORK_DISABLED` kill switch tested; operator gateway unset on public instances
- [ ] `receipt-cost.mjs` passes against prod; billing notification set on the host account
- [ ] Social card: absolute `og:image`, `twitter:card`; landing not set to noindex

How to use this prompt

  1. Copy the prompt using the button above
  2. Paste it into your preferred AI coding assistant
  3. Adjust any placeholders or context as needed
  4. Let the agent implement the changes