# OAuth kit (TypeScript)

Reference for @omazyai/sdk/oauth. The MCP authorization server a product mounts beside its MCP doors, on Cloudflare's Workers OAuth provider, with seats, live permissions, keys and connected apps.

Source: https://docs.omazy.ai/build-on-omazy/kits/oauth/

:::note[Reviewed, still a preview]
Six independent security reviews of the kit are done, and the proofs from each run as regression tests. It is a preview in `@omazyai/sdk` 0.5.3, TypeScript only, and runs on Cloudflare Workers only. Its interface may change before 1.0.

Open a door with it only on these setup rules: name `platformDoors`, give every platform door a list of known clients, supply `checkSeat`, use a consistent refresh store (the Durable Object or D1, see [Refresh tokens](#refresh-tokens)), bind the rate limits, and pin `@cloudflare/workers-oauth-provider` and `@omazyai/sdk` at exact versions. The [threat model](#threat-model) and the [checklist](#for-the-reviewer) say what each rule covers.
:::

```ts
import { authorizationServer, signInCodes } from '@omazyai/sdk/oauth'
```

The kit is the authorization server claude.ai, ChatGPT, Cursor and Claude
Code use to connect to your [MCP doors](/build-on-omazy/kits/mcp/). It wraps
[`@cloudflare/workers-oauth-provider`](https://github.com/cloudflare/workers-oauth-provider),
which does the OAuth 2.1 protocol, and adds what the library leaves to the
application: the consent page, which clients may connect where, sign-in
through your product, refresh family revocation, keys and connected apps.

A token names one seat at one door and nothing else. What the seat may do is
read by the guard's `can()` on every call, so a removed role takes effect on
the next call.

Install the library at the exact version the kit is tested with:

```sh
npm i @omazyai/sdk @cloudflare/workers-oauth-provider@1.3.0
```

Bind a KV namespace, the refresh lock and a rate limit, and add the
`global_fetch_strictly_public` compatibility flag so Client ID Metadata
Documents work:

```jsonc
// wrangler.jsonc
{
  "compatibility_flags": ["global_fetch_strictly_public"],
  "kv_namespaces": [{ "binding": "OAUTH_KV", "id": "..." }],
  "durable_objects": { "bindings": [{ "name": "OAUTH_REFRESH", "class_name": "OAuthRefreshLock" }] },
  "migrations": [{ "tag": "oauth-refresh-1", "new_sqlite_classes": ["OAuthRefreshLock"] }],
  "ratelimits": [
    { "name": "AUTHORIZE_LIMIT", "namespace_id": "1001", "simple": { "limit": 30, "period": 60 } },
    { "name": "TOKEN_LIMIT", "namespace_id": "1002", "simple": { "limit": 60, "period": 60 } }
  ]
}
```

## Mounting it

```ts
import { createGuard } from '@omazyai/sdk/guard'
import { mcpServer } from '@omazyai/sdk/mcp'
import { authorizationServer, durableObjectRefreshStore } from '@omazyai/sdk/oauth'

// The refresh lock, one Durable Object per grant (see Refresh tokens).
export { OAuthRefreshLock } from '@omazyai/sdk/oauth'

export default {
  async fetch(req: Request, env: Env, exec: ExecutionContext) {
    const oauth = authorizationServer({
      issuer: 'https://mcp.acme.com',
      kv: env.OAUTH_KV,
      productName: 'Acme',
      doors: { platform: 'https://mcp.acme.com/platform', org: 'https://mcp.acme.com/org' },
      platformDoors: ['platform'],   // required: the doors whose seats have no tenant, or []
      doorLabels: { org: 'your branch' },
      signIn: {
        url: 'https://app.acme.com/mcp-sign-in',
        authenticate: (code, state) => redeemSignInCode(env, code, state),   // back channel
      },
      chooseSeat: (person, door) => seatFor(env, person, door),
      checkSeat: (grant, door) => seatStillHeld(env, grant.seat),
      clients: {
        // Exact client ids: the metadata document URL each vendor publishes.
        platform: { known: [CLAUDE_CLIENT_ID, CHATGPT_CLIENT_ID], others: 'block', unverified: 'block' },
        org: { knownDomains: ['claude.ai', 'chatgpt.com'] },
      },
      keys: {
        personal: { prefix: (door) => `acme_mcp_${door}_` },
        service: { prefix: (door) => `acme_svc_${door}_` },
      },
      refresh: { store: durableObjectRefreshStore(env.OAUTH_REFRESH) },   // required: there is a platform door
      rateLimit: { authorize: env.AUTHORIZE_LIMIT, token: env.TOKEN_LIMIT, authorizePer48: env.AUTHORIZE_LIMIT_48, tokenPer48: env.TOKEN_LIMIT_48 },
      onEvent: (e) => alert(env, e),
    })
    const guard = createGuard({ registry: reg, can, secret: env.GUARD_SECRET, store: guardStore(env) })
    const org = mcpServer({ registry: reg, guard, door: 'org', ...oauth.door('org'), info: { name: 'acme-org', version: '1' } })
    return (await oauth.route(req, exec)) ?? org.fetch(req, env, exec)
  },
}
```

`oauth.door('org')` gives the door its `resolveSeat` and its
`resourceMetadataUrl`, so an unauthenticated request gets a `401` with
`WWW-Authenticate: Bearer resource_metadata="..."`.

`oauth.route(req)` answers the kit's own routes and returns `null` for
anything else:

| Route | What it is |
|---|---|
| `/.well-known/oauth-protected-resource/<door>` | RFC 9728 metadata for each door |
| `/.well-known/oauth-authorization-server` | RFC 8414 metadata, from the library |
| `/authorize` | The consent page (GET) and the decision (POST) |
| `/oauth/callback` | Where your sign-in sends the browser back |
| `/oauth/token` | Code exchange, refresh and revocation, from the library, with refresh reuse checked first |
| `/oauth/register` | RFC 7591 registration, only when switched on |

### Options

| Option | What it is |
|---|---|
| `issuer` | The issuer URL. Fixed in configuration, never taken from the request's host |
| `kv` | The KV namespace. The library's records and the kit's (under `omazy-oauth:`) share it |
| `doors` | Each door and its canonical resource URL: https, lowercase host, no fragment |
| `productName`, `doorLabels` | Shown on the consent page |
| `signIn.url` | Your sign-in page, or a function of the door |
| `signIn.authenticate(code, state, req)` | Redeems the one-time code over the back channel. `state` is the callback's state, already matched to the browser; refuse a code not issued for it. Null refuses |
| `chooseSeat(person, door, req)` | The seat this person takes at this door, such as which tenant; null refuses |
| `checkSeat(grant, door, req)` | Required at every door; without it the kit throws at start. Whether the seat is still held. Run on every `resolveSeat` (access token or key) and on every refresh and code exchange. False refuses the call, and at a refresh or code exchange revokes the grant; a throw refuses the call, and at the token endpoint answers `503` and revokes nothing |
| `clients` | The policy per door; see [Clients](#clients). A platform door needs one, with a non-empty `known` list |
| `platformDoors` | Required. Doors whose seats have no tenant (an operator door), or `[]`. Stricter rules hold there: a client policy with a `known` list, a consistent refresh store, no `knownDomains`, no service keys unless listed. A seat with no tenant is refused at every other door. The kit never guesses from a door's name |
| `registration` | `{ enabled, perHourPerIp = 10, perHourPer48 = 10 x perHourPerIp, clientTtlDays = 90 }`. Off by default. Each number is a whole number of at least 1 |
| `clientMetadataDocuments` | Client ID Metadata Documents. On by default |
| `clientMetadataFallback` | Default `false`: a document that stops answering stops working. `{ maxAgeSeconds }` (60 to 3600) keeps the last good copy that long through a client's outage |
| `rateLimit` | `{ authorize, token }`: Workers Rate Limiting bindings. `authorize` counts every GET `/authorize` per address (`authorize:<ip>`) before any work, since each writes to KV unauthenticated. `token` counts every POST to `/oauth/token` per address (`token:<ip>`) before the body is read. An IPv6 address counts by its /64 (`authorize:2001:db8:1:2::/64`). `authorizePer48` and `tokenPer48` count it by its /48 as well (`token:2001:db8:1::/48`); bind them with a higher limit. Without any of them the kit warns at start; see [Addresses](#addresses) |
| `clientIpHeader` | The header that carries the caller's address. Default `cf-connecting-ip`, which Cloudflare sets. Name another only when your own front sets it and a caller cannot. Its value must be one IPv4 or IPv6 address. Wherever an address is counted (rate limits, registration, Turnstile), a request without one is refused, never put in a shared bucket. A header any caller can send (`x-forwarded-for`, `x-real-ip`, `forwarded`, `true-client-ip` and the like) throws at start unless `trustClientIpHeader` is set |
| `trustClientIpHeader` | Opt in: `clientIpHeader` names a header a caller can also send, and your own front overwrites it on every request |
| `turnstile` | `{ siteKey, verify, after = 3 }`, `after` a whole number of at least 1. `turnstileVerifier(secret)` gives a `verify` |
| `keys` | Key prefixes and limits; see [Keys](#keys) |
| `refresh` | `{ store, acceptKvRace, tombstoneCacheSeconds }`: where refreshes are locked per grant, rotated tokens marked, revoked grants and keys tombstoned, and each person's grants and keys indexed, and how long `resolveSeat` may remember a grant has no tombstone (default 0); see [Refresh tokens](#refresh-tokens) |
| `ttl` | Shorter lifetimes only, in whole seconds of at least 60: access at most 3600 s, refresh at most 30 days |
| `onEvent` | Security events: refresh and code reuse, refresh contention, grants revoked at a refresh or code exchange (`grant_revoked`, reason `seat_gone` or `person_revoked`), blocked clients, refused metadata documents, failed sign-ins, Turnstile failures, registration and authorize limits |

Every numeric option is checked at start: a value that is not a whole
number in range (`NaN`, `Infinity`, a fraction, zero) throws. A comparison
with `NaN` is always false, so it would pass every check and lift the limit
it sets.

## The flow

1. The client calls a door without a token and gets a `401` naming the
   door's metadata. It reads the metadata, then the server's.
2. It opens `/authorize` with `resource` naming one door, `code_challenge`
   and `code_challenge_method=S256`. The kit refuses a request without
   `resource`, even where the library would pick the only resource, and
   refuses one without S256 PKCE, confidential clients included. The kit
   works out the client's status at the door first. An error goes back to the
   client's redirect URI (with `state` and `iss`) only when the door knows the
   client; for every other client (blocked, unverified, verified, or no
   valid `resource`) it is shown on the kit's own page and never redirected,
   so the authorization origin is not an open redirect.
3. The consent page shows the client's name, whether it is known, verified by
   its metadata document or not verified, where access will be sent, and a
   warning when that is an app on the person's computer. It cannot be framed
   and is not cached. Its form carries a handle that works once, for ten
   minutes, in the browser that opened it.
4. On Continue, the browser goes to your sign-in with `state`, `door` and
   `return_to`. You check `return_to` is exactly `oauth.callbackUrl`, sign
   the person in your own way, issue a one-time `code` for that `state`, and,
   after the person clicks to continue, post the same `state` and the code to
   `return_to` (or `error=access_denied`).
5. The kit checks the `state` belongs to this browser, redeems the code
   through `authenticate` with that state, asks `chooseSeat`, and issues the
   authorization code to the client. A code issued for another flow's state
   is refused. A code that reaches a callback that fails is spent anyway.
6. The client exchanges it with its PKCE verifier. Access tokens last one
   hour; refresh tokens 30 days from the first exchange, rotated on every
   use.

### Your sign-in page

The kit never owns identity. `signInCodes(kv)` is a ready-made code store for
a sign-in that can reach the same KV namespace:

```ts
const store = durableObjectRefreshStore(env.OAUTH_REFRESH)   // the server's refresh store
const codes = signInCodes(env.OAUTH_KV, { store })           // 120 s, single use, bound to one state, stored hashed

// On your sign-in page, before anything else:
const state = params.get('state')
if (params.get('return_to') !== 'https://mcp.acme.com/oauth/callback' || !state) throw new Error('bad sign-in request')

// Once the person is signed in, one click, then a form POST to the callback:
const code = await codes.issue({ kind: 'member', id: person.id, name: person.name }, { state })
return html(`<p>Connect the app that sent you here?</p>
  <form method="post" action="https://mcp.acme.com/oauth/callback">
    <input type="hidden" name="state" value="${escape(state)}">
    <input type="hidden" name="code" value="${escape(code)}">
    <button>Continue</button>
  </form>`)

// In the kit's options:
signIn: { url: 'https://app.acme.com/mcp-sign-in', authenticate: (code, state) => codes.redeem(code, state) }
```

Compare `return_to` to the exact callback URL (`oauth.callbackUrl`), not to
an origin or a prefix, and build the form's action from your own copy of it.

Pass `store`, the same refresh store as the server's, when it is a
consistent one (`durableObjectRefreshStore`, `d1RefreshStore`). A redeem
then claims the code there, under a lock, so a code is single use across
locations. Without it a redeem deletes the code from KV, and a location
whose KV cache still holds the code could redeem it once more within about
60 seconds (it would still need the same flow's `state`, which only the
browser that consented has). `ttlSeconds` is a whole number; below 60 counts
as 60.

Return the code by form POST, or after one click, never by an automatic
redirect. Anyone can send a signed-in person a link to your sign-in page
with their own `state`; an automatic redirect would issue a code for it with
no click, and put the code in the address bar, the history and request
logs. The kit spends any code that reaches a callback that fails, but the
click is what keeps the person in the loop.

The form POST works only when your sign-in page is on the same site as the
issuer. The callback needs the kit's flow cookie, which is `SameSite=Lax`,
and a browser sends a Lax cookie on a cross-site request only for a
top-level GET. `app.acme.com` posting to `mcp.acme.com` is the same site
(`acme.com`), so the cookie goes and the POST works. A sign-in on another
site, such as `acme-login.com` or a hosted identity provider's domain, posts
without the cookie, and the callback answers that the sign-in has expired.
There, use the one-click GET instead: show a Continue link (or a button in a
`method="get"` form) to the callback with `state` and `code` in the query.
The click keeps the person in the loop; the code then sits in that one URL,
single use and spent within seconds, so keep it out of your own logs. A
sign-in that lives on another host with its own storage keeps its own codes,
binds each to the `state` it was issued for, and exposes a redeem endpoint
that takes the code and the state for `authenticate` to call.

Person ids may hold letters, digits and `.`, `_`, `@`, `-`: they are part of
the library's token format and KV keys. An id that starts with one of your key
prefixes is refused at sign-in.

## Clients

Each client at a door is one of:

| Status | Means | Default |
|---|---|---|
| `known` | Its exact client id is on the door's `known` list. Or, where the door opts in with `knownDomains`, its metadata document is on a listed host and every redirect URI the document lists stays on that host | allowed |
| `verified` | It has a Client ID Metadata Document, every redirect URI it lists stays on the document's host (or is a loopback address), and it is not known | allowed at a tenant door; `others: 'block'` refuses. Refused at a platform door |
| `unverified` | No metadata document (dynamically registered, or pre-registered and not on the list), or a document whose redirect URIs go to another host | refused; `unverified: 'allow'` allows |

`known` takes exact client ids only: the full URL of a metadata document,
such as the one Claude or ChatGPT publishes, or the id of a pre-registered
client. A bare domain there is refused at start: any document on that domain,
including one an attacker can place through an upload or an open redirect,
would pass. `knownDomains` is the opt-in for matching by host, and it is
refused on a platform door.

A platform door hands out tokens for operator seats, so it is strict by
default: it needs a policy with a non-empty `known` list, and it refuses
every client not on it. Setting `others` or `unverified` to `allow` there, or
an empty `known` list, throws at start unless the policy also sets
`dangerouslyAllowUnlistedClients: true`. Any metadata document can call
itself "Claude"; only the exact client id says it is.

The library follows HTTP redirects when it fetches a metadata document and
offers no hook to stop it. The kit fetches the same URL itself, with the
library's own headers (its `User-Agent` among them) and redirects refused,
after the library has validated it, and refuses a client whose URL
redirects. It then requires the document it read to match the library's:
the same name and redirect URIs, the name on the consent page, and the
request's redirect URI listed. A server that answers the library and the kit
differently, by `User-Agent`, by order or by timing, is refused. A good
answer is remembered for five minutes per isolate, with what it said.

The library is not patched to refuse redirects itself: it is a peer
dependency your Worker installs, so a patch in the kit would not reach your
deploy. What is left is two fetches of one URL: a server may still redirect
the library to a document identical to the one at the URL, which changes
nothing.

A metadata document its owner withdraws stops working on the next
authorization: the kit turns off the library's last-good copy, which would
otherwise answer for 24 hours whenever the origin returns 404, 408, 429 or
5xx. A product that would rather ride out a client's outage sets
`clientMetadataFallback: { maxAgeSeconds }`, at most an hour. Where the
document's own `Cache-Control` allows it, the Workers Cache API may still
serve it within one location until that lifetime ends.

A refused client gets a page on the kit's origin saying it cannot connect,
never a redirect to its own URI, and `onEvent` gets `client_blocked`. The policy is checked again when the person clicks
Continue.

The policy also holds after consent. Every refresh, every code exchange and
every `resolveSeat` checks the grant's client against the door's policy as
it stands now, so a client you block, or take off a `known` list, stops at
once: its refresh token and code answer `invalid_grant` (with
`client_blocked`), and its access token resolves to no seat. The grant
itself is kept, so allowing the client again brings it back. This check
makes no network call: the status recorded at consent (known, verified,
unverified) stands unless the lists move it. The grant also records which
list made the client known: its exact id, or its host under `knownDomains`.
A client known by its host stays known while the host is listed, since its
redirect URIs were bound to the host at consent. A client known by its id
and no longer on the list is looked up again, to see what its metadata
document makes it now, even when its host is listed: the host counts only
when every redirect URI it lists stays on the host. That lookup goes
through the same redirect check as consent (a document that redirects is
refused), and its answer is remembered for five minutes per server
instance, so a delisted client costs one fetch, not one per call. Build the
server once per isolate, at module scope, for that memory to help.
Pre-register a client with `oauth.api().createClient(...)` and put
its id on the `known` list.

Dynamic registration is deprecated by MCP 2026-07-28. Switch it on only for a
client that needs it, and allow unverified clients only at the doors that
must take them.

## Addresses

The authorize and token limits, the registration count and Turnstile count
per caller address, read from `clientIpHeader`:

- The value must be exactly one IPv4 or IPv6 address. A list
  (`203.0.113.1, 198.51.100.2`), a name or anything else is no address, and
  the request is refused where addresses are counted.
- An IPv4 address counts as itself. An IPv6 address counts by its /64: one
  customer is usually handed a whole /64, so counting each address would let
  one host open a fresh bucket for every request. An IPv4-mapped IPv6
  address counts as the IPv4 address, and so does a 6to4 address
  (2002::/16): the 32 bits after `2002:` are the IPv4 address that owns
  the whole /48.
- A /64 is not the end of it: a free tunnel broker, or a hosting account,
  hands out a whole /48, which holds 65,536 /64s and so 65,536 fresh
  buckets. `rateLimit.authorizePer48` and `rateLimit.tokenPer48` count every
  IPv6 request by its /48 as well (`authorize:2001:db8:1::/48`,
  `token:2001:db8:1::/48`), after its /64. A Workers Rate Limiting binding
  carries its own limit, so bind these two with a higher limit than
  `authorize` and `token`, ten times is a fair start: a company or a
  mobile carrier may put many people behind one /48. Without them the kit
  warns at start. Registration counts the /48 too, at `perHourPer48`
  (default ten times `perHourPerIp`).
- `x-forwarded-for`, `x-real-ip`, `forwarded`, `true-client-ip` and similar
  headers are ones any caller can send, and Cloudflare passes them on as
  sent. Naming one throws at start unless you set `trustClientIpHeader:
  true`, which says your own front overwrites it on every request.

MCP clients hosted on Cloudflare Workers reach your Worker from Cloudflare's
own addresses, and many such clients share one of them. Size the limits for
that: a limit that suits one person's laptop would let one busy Worker-hosted
client lock out every other client behind the same address.

## Seats and live permissions

The grant stores the person and the seat, encrypted by the library. On every
call `resolveSeat` checks the token is for this door, runs `checkSeat`, and
hands the seat to the door. The guard then runs your `can()` for the
capability. Nothing the token says can widen what the seat may do.

`checkSeat` is required at every door, a tenant door too. It also runs
inside the library on every refresh and code exchange, with the grant's own
seat, before any token is minted. A seat it says is gone revokes the grant
there (tombstone first), answers `invalid_grant`, and `onEvent` gets
`grant_revoked` with reason `seat_gone`. A `checkSeat` that throws answers
`503` `temporarily_unavailable`, revokes nothing and leaves the refresh
token good for the retry. Without it, a seat the person no longer held kept
its keys and access tokens, and its grants kept refreshing for good.

A person may connect the same client to two seats (two branches). Connecting
the same client to the same seat again replaces the earlier grant.

## Refresh tokens

A refresh token is rotated on every use. The kit keeps the hash of each
rotated token, and one that comes back revokes the whole grant. It also takes
a lock per grant for the length of a refresh, so two refreshes of one grant at
the same moment cannot both pass: the second gets `503` with
`temporarily_unavailable` and `Retry-After`, and `onEvent` gets
`refresh_contended`. The lock lasts at most 30 seconds, longer than the
library can take: it may wait 10 seconds on a client's metadata document
and another 10 on its keys.

The lock is taken only for a token the grant holds: its SHA-256, the
library's own hash, must equal the grant record's current or previous
refresh token. Any other token is checked against the rotated marks without
the lock and goes to the library, which refuses it. A made-up token costs one
KV read and writes nothing.

The token is marked retired before the library sees it, and the mark is
removed only if the library refuses it with a 4xx. So a second presentation
of the same token, at any moment after the first began, is a reuse, however
long the library takes. A 5xx or an exception keeps the mark: the client
signs in again rather than risk a token that was rotated twice.

A mark lives for the refresh lifetime, even after the grant it revoked is
gone: if the grant comes back (below), the same token is still a reuse.

### Revoked grants stay revoked

The library keeps grants in KV and writes the whole grant back on every
refresh. Each location reads KV through its own cache for up to about 60
seconds, and the last write wins. So a refresh in a location that still has
a grant cached, after the grant was revoked somewhere else, writes it back,
and the revoked grant is live again everywhere. A thief caught by reuse
detection, or an app the person just disconnected, would keep refreshing.

The kit cannot stop that write: the library makes it. It keeps the fact of
the revocation instead. Every revocation (reuse detection, `revokeApp`,
`personLostRole`, a grant replaced by connecting the same client to the
same seat again, a client revoking its own refresh token at the token
endpoint, and an authorization code presented twice) writes a tombstone for the grant to the refresh store, kept for
the refresh lifetime plus an hour, longer than any token of the grant can
live. The kit reads it:

- at the token endpoint, before the library sees a refresh token or an
  authorization code that names a grant present in KV;
- in `resolveSeat`, once the library has validated an access token;
- in `connectedApps`, for each grant listed.

A tombstoned grant is revoked again (its KV records deleted once more) and
answers `invalid_grant`, resolves to no seat, or is left off the list. An
access token minted by a refresh that slipped through before the tombstone
landed stops on its first call.

`revokeApp`, `connectedApps` and `personLostRole` find a person's grants
through the person's index in the refresh store, and KV's listing for older
grants. KV's `list()` is eventually consistent: a grant or key made in the
last minute or so can be missing from it, so a revocation that found its
targets by listing missed what was just made. The kit enters each grant in
the index when it is made, before the client has its code, and renews the
entry on every refresh; each key is entered when it is minted.
`personLostRole` first records a revocation of the person (at the door or
tenant given) for a little over a year: everything made for them before that
moment is refused at its next refresh, code exchange or `resolveSeat`, even
if the index missed it, and revoked there (`grant_revoked`, reason
`person_revoked`). A grant or key made after it is not covered.

A client's own revocation (RFC 7009: a body with `token` and no
`grant_type`, which the library serves at `/oauth/token`) revokes the whole
grant for a current or previous refresh token the client holds, and only
that token for an access token. The kit reads the grant before the library
runs. For a refresh token of that grant sent by the grant's own client (read
as below, so a `Bearer` header beside credentials in the body does not hide
it), it does the revocation itself: it has the library authenticate the client,
with the same credentials on a revocation of a token that names nothing
(the library answers that 200 once the client is authenticated, and its
usual 400 or 401 when not), then tombstones the grant and revokes it. The
library would authenticate and revoke in one step, which left nothing to do
when the tombstone write failed after it. It fails closed: when the
tombstone cannot be written the answer is `503` with
`temporarily_unavailable`, never a 200 that claims the revocation held, and
`onEvent` gets `oauth_error` with code `revocation_unrecorded`. Nothing is
revoked then, for a public or a confidential client, so the client's retry
finishes the job. This works for every client authentication method: a
client assertion (`private_key_jwt`) is spent by the check as the library
would spend it, and the kit answers the request without handing it on.

Revoking an access token (RFC 7009, the token is an access token) is the
library's: it deletes that one token record in KV, with no tombstone. Other
locations stop accepting it within about 60 seconds, as their KV caches
expire; until then it can still resolve there. The grant and its other
tokens are untouched. To stop everything at once, revoke the refresh token
(the whole grant, tombstoned) or call `revokeApp`.

An authorization code is exchanged once. The library marks a code used in
its grant in KV and, when the code comes back, revokes the grant (RFC 9700)
without a tombstone; and a location whose cache still holds the grant from
before the exchange would exchange the code again. So the kit records each
exchange by the grant's own client in the refresh store, under the grant's
lock, for the code's ten minutes. The record is pending, with the lock's
holder, while the library works, and is settled when it answers: dropped
when the library refuses the code (a wrong verifier, say), and kept as used
otherwise, a 5xx or an exception included. A request that finds an exchange
still pending got the lock only because it lapsed under that exchange, whose
outcome is not known yet: it gets `503` `temporarily_unavailable` and tries
again, never a replay's answer. A request naming another client takes no
lock and leaves no record: the library refuses a code issued to another
client before it reads anything else. So someone holding a code without its
verifier cannot make the real client's first exchange wait, or count as a
replay. A code presented again, by the grant's own client
once the library has authenticated it, is answered by the kit: tombstone,
revocation, then the library's `400` `invalid_grant` "Authorization code
already used", and `onEvent` gets `code_reuse`. A wrong secret gets the
library's own answer and revokes nothing. Once the kit's record shows a code
was used, the library is never asked about it again, since a location whose
cache still holds the grant from before the exchange would exchange it a
second time: another client, or a request that names none, gets `400`
`invalid_grant` from the kit and revokes nothing. A tombstone that cannot be
written answers `503` with nothing revoked, as above.

### Which client a request names

Every one of these checks turns on which client a token request is from,
and the library decides that for itself when it authenticates the client.
The kit reads it with one function, `tokenRequestClient`, copied line for
line from the library's own (`parseBasicAuthorizationHeader` and the client
authentication in `parseTokenEndpointRequest`, version 1.3.0), over the body
as `tokenForm` reads it with the library's parser:

- the Authorization header's scheme is the text up to the first space or
  tab, compared without case. Basic credentials name their decoded user
  name; Basic the library cannot decode, or Basic beside any client
  parameter in the body, names no client. Any other scheme (Bearer, DPoP)
  is ignored;
- otherwise a client assertion names `client_id`, else the assertion's
  issuer, read without checking its signature;
- otherwise `client_id`. A parameter sent twice is refused.

`oauth-parity.test.ts` runs a table of awkward requests through the kit's
function and through the library, under Bun and under workerd, and fails
when they name different clients. When the pinned library changes, that
test is the first to run.

This needs a consistent store. On the KV default the tombstone sits behind
the same per-location cache as the grant, so it does not close the gap:
that is one more reason a platform door refuses the KV store unless the
product passes `acceptKvRace: true`.

Where the lock, the marks and the tombstones live decides how exact this is:

| Store | Lock | Marks and tombstones | Gap |
|---|---|---|---|
| KV (default) | In this isolate's memory | KV | Two isolates can refresh one token at once. A mark or a tombstone written in one location reaches the others within about 60 seconds, so a replay from another region in that window passes, a revoked grant written back from a stale cache comes back, and a revoked key or a person's revocation reaches other locations as late. The person index is a KV listing, which lags as long |
| `durableObjectRefreshStore(env.OAUTH_REFRESH)` | One Durable Object per grant | The same object | None known |
| `d1RefreshStore(env.DB)` | A conditional upsert in D1 | D1 | None known, while reads go to the primary (no read replica session) |

The store also holds each person's index of grants and keys, each client's
index of grants, the revocations `personLostRole` writes, and the keys'
tombstones. D1 needs the new tables: run `applyOAuthD1Migrations` again
(migration `0003_oauth_person_index`, additive); `prune` clears what has
expired. The Durable Object keeps them in objects of the same class, one per
person, client or key, with no new migration.

With a consistent store, `resolveSeat` reads the grant's tombstone and the
person's revocations at once, on every MCP request that carries an OAuth
access token, and a key's tombstone and its owner's revocations on every
request with a key. For
heavy MCP traffic use the Durable Object store: each grant has its own
object, so the reads spread out and none of them queue behind one database.
`connectedApps` reads every grant's tombstone and last use at once.

`refresh.tombstoneCacheSeconds` (0 to 5, default 0) lets `resolveSeat`
remember, per server instance, that a grant has no tombstone, and skip the
store for that long. The trade-off: a revocation made in another isolate
(another request, location or server instance) takes up to that many
seconds to stop an access token. A revocation by the same server instance
applies at once, and refreshes, code exchanges and `connectedApps` always
read the store. Leave it at 0 unless the store's load matters more than
those seconds, and build the server once per isolate, at module scope, so
the memory lasts beyond one request.

A platform door refuses the KV default at start, unless the product passes
`refresh: { acceptKvRace: true }` and accepts the gap. A tenant door starts on
it, and the kit warns at start, unless `acceptKvRace` is set.

```ts
// The Durable Object: export it from the Worker and bind it.
export { OAuthRefreshLock } from '@omazyai/sdk/oauth'
// wrangler.jsonc
// "durable_objects": { "bindings": [{ "name": "OAUTH_REFRESH", "class_name": "OAuthRefreshLock" }] },
// "migrations": [{ "tag": "oauth-refresh-1", "new_sqlite_classes": ["OAuthRefreshLock"] }]
authorizationServer({ ..., refresh: { store: durableObjectRefreshStore(env.OAUTH_REFRESH) } })

// Or D1: create the tables on every deploy (additive), prune from a cron.
await applyOAuthD1Migrations(env.DB)
authorizationServer({ ..., refresh: { store: d1RefreshStore(env.DB) } })
```

## Keys

For clients that cannot run OAuth, such as Claude Code with a pasted key, or
a tenant's own integration.

```ts
// A personal key: the person's own seat. At most 90 days, at most R2.
const { key, info } = await oauth.keys.createPersonal({ principal, seat, name: 'Laptop', days: 30 })

// A service key: a service principal in one tenant, with a tool allow list. At most 365 days, R2 unless set.
const svc = await oauth.keys.createService({ owner: principal, tenant: 'branch-1', door: 'org', name: 'Zapier', tools: ['orders_list'] })
```

- Show `key` once. Only its SHA-256 is stored; it cannot be read again.
- Each door has its own prefix, so a key for one door is refused at another.
- The caps hold whatever the configuration says: a personal key never
  outlives 90 days or reaches past R2, a service key never outlives 365 days.
  A service key is capped at R2 unless `keys.service.maxTier` names another
  tier, at most R3; R4 throws at start unless `keys.service.allowR4` is set.
  A personal key for a seat with no tenant is refused unless its door is a
  platform door. Each kind's cap is applied again on every call. A tier that is not R0
  to R4 in the options throws at start.
- A service key belongs to a tenant, so it is refused at a platform door
  unless `keys.service.platformDoors` lists that door. The kit does not know
  the product's tenants: check the tenant exists and the owner belongs to it
  before `createService`, and have `checkSeat` refuse a service seat whose
  tenant or owner is gone.
- A service key's principal is `{ kind: 'service', id: 'sk_...' }`; its
  owner is the person who minted it. Check the person may mint before calling
  `createService` (Joya makes it an R3 capability).
- `keys.list(personId)`, `keys.listService(tenant)`, `keys.revoke(personId, id)`,
  `keys.transferService(from, id, toPrincipal)`.
- A key record lives in KV, which each location reads through a cache for
  about 60 seconds. With the server's refresh store (the server passes it to
  its `keys`), a revoked key gets a tombstone there first, which `resolve`,
  `list` and `transferService` read: a revoked key stops at once in every
  location, and `transferService` refuses it (false), so a location whose
  cache still holds it cannot write it back. Each key is entered in its
  owner's index in the store when it is minted, so `list` and
  `personLostRole` find a key made a moment ago. A key moved with
  `transferService` is covered by its new owner's revocations from the
  moment it moved, not by the old owner's.

### Keys outside the Worker

`Keys` and its constants also have their own entry, `@omazyai/sdk/oauth/keys`.
It loads neither the OAuth provider nor `cloudflare:workers`, so a Node script
that mints a key, or a plain `bun test`, imports it with no stand-in and no
warning from the provider. `@omazyai/sdk/oauth` still exports the same `Keys`.

```ts
import { Keys, memoryKv } from '@omazyai/sdk/oauth/keys'

// The same prefix and limits as the Worker's `keys` option, so the record is
// the one `door(name).resolveSeat` finds.
const keys = new Keys(kv, ['platform'], { personal: { prefix: (d) => `acme_mcp_${d}_` } }, ['platform'])
const { key, info } = await keys.createPersonal({ principal, seat, name: 'Laptop', days: 30 })
```

`kv` is anything with the KV namespace's `get`, `put`, `delete` and `list`:
the binding in a Worker, a wrapper over `wrangler kv` in a script, or
`memoryKv()` in a test. The fourth argument lists the platform doors, as
`platformDoors` does for `authorizationServer`.

The fifth argument is optional: the refresh store, for key tombstones, the
owner index and person revocations. The entry exports
`durableObjectRefreshStore`, `d1RefreshStore`, `applyOAuthD1Migrations`,
`OAuthRefreshLock` and `kvRefreshStore` for it, and loads no provider.

```ts
const keys = new Keys(env.OAUTH_KV, ['platform'], { personal: { prefix: (d) => `acme_mcp_${d}_` } }, ['platform'], durableObjectRefreshStore(env.OAUTH_REFRESH))
```

Without a store, `Keys` works as before, with the KV window: a revoked key
still resolves for up to about 60 seconds in a location whose KV cache holds
it, `transferService` there can write it back for good, and a key minted in
the last minute can be missing from `list` and `revokeOwned`. With a store,
use the same one everywhere a key is resolved or revoked. A script that only
mints keys and cannot reach the store may leave it out: the key is then
missing from the index for its first minute, which a person's revocation
still covers.

Joya uses keys on KV alone today. It should bind the `OAuthRefreshLock`
Durable Object (or use its D1 with `applyOAuthD1Migrations`) and pass that
store as `refresh.store` to `authorizationServer`, which hands it to its
keys, and as the fifth argument wherever it builds `Keys` itself in the
Worker.

## Connected apps

The data for a connected apps page; you build the page.

```ts
const { apps, keys } = await oauth.connectedApps(personId)
// apps: [{ grantId, clientId, clientName, status, door, seatId, tenant, createdAt, expiresAt, lastUsedAt }]
await oauth.revokeApp(personId, grantId)   // false when the grant is not theirs
```

Last use is written at most every five minutes per grant or key.

When a person loses a role, call:

```ts
await oauth.personLostRole(personId, { tenant: 'branch-1' })   // or { door: 'platform' }, or all
```

It first records in the refresh store that everything made for the person
there before now is revoked, then revokes each grant and key it finds through
the person's index and KV's listing, and returns how many. Move a service key
to another owner first if it should stay. Revoking a grant or a key is a KV
delete, which other locations see within about 60 seconds, and a tombstone in
the refresh store, which a consistent store answers at once everywhere; see
[Revoked grants stay revoked](#revoked-grants-stay-revoked). `checkSeat`
reads your own store on every call, refresh and code exchange, so it stops a
lost seat as fast as your store does.

## Housekeeping

KV expires tokens and keys on its own. Run the library's sweep from a Cron
Trigger for orphaned records:

```ts
await oauth.api().purgeExpiredData()
```

`oauth.api()` is the library's helpers with two changed: `revokeGrant` goes
through the kit, tombstone first, as `revokeApp` does, and `deleteClient`
tombstones and revokes every grant of the client (found through the client's
index in the refresh store and a listing of every grant in KV) before the
library deletes the client. Without that, a grant revoked through the
library's own helper came back from a location whose KV cache still held
it.

## Not covered yet

- **Node.** The library runs on Workers only. A Node product would wrap
  `oidc-provider` behind the same interface; not built.
- **D1.** Grants and tokens live in KV, the library's own model. Only the
  refresh lock, marks, tombstones, indexes and person revocations can move
  to D1 or a Durable Object; see
  [Refresh tokens](#refresh-tokens).
- **Scopes.** The server grants one scope, `mcp`. Permissions are per seat,
  read live, so the kit has no step-up by scope.

## Threat model

What the kit defends, how, and what is left.

| Threat | Defence | Left over |
|---|---|---|
| A token used at another door (confused deputy across doors) | Every grant and token is bound to one resource by the library. `resolveSeat` checks the audience and that the stored seat is for this door. Keys carry a prefix per door | None known |
| A stolen authorization code | PKCE S256 required on every request, public and confidential clients. Codes are single use, ten minutes, and stored hashed. Each exchange is recorded in the refresh store under the grant's lock, so a location whose KV cache holds the grant from before the exchange cannot exchange it again; a code presented twice revokes and tombstones its grant | A client that leaks its verifier with the code. On the KV default the record has the same cache delay as the grant |
| PKCE downgrade (the library's GHSA-qgp8-v765-qxx9) | The kit checks `code_challenge_method=S256` in the raw request and in the parsed one before consent | Pinned at 1.3.0, which has the fix |
| An open redirect, or tokens sent to a host the client does not own (GHSA-4pc9-x2fx-p7vj) | Exact redirect URI match by the library. Error redirects go only to a client the door knows; blocked, unverified and verified clients, and requests without a valid `resource`, get the kit's own error page. The consent page shows the redirect host and warns on loopback | Cancel on the consent page returns to the client, after the person saw its redirect host. A person who ignores the host on the page |
| Cross-site request forgery on consent | The form's handle is single use, ten minutes, bound to the browser by a `__Host-` cookie. A post without the cookie, with another handle or a used one, is refused | Two posts at once from the same browser with the same handle (KV has no compare and swap) |
| Clickjacking | `frame-ancestors 'none'`, `X-Frame-Options: DENY`, no script unless Turnstile | None known |
| A malicious client name (script on the authorization origin) | Every client string is escaped; CSP `default-src 'none'` | None known |
| An impersonating client (calls itself "Claude") | Status shows known, verified by domain, or not verified. Per door allow list by exact client id; matching by metadata host only where a door opts in, and then only when every redirect URI stays on that host. A document whose redirect URIs leave its host is unverified. Never by name. Unverified clients refused by default. A platform door needs a known list and refuses every other client unless `dangerouslyAllowUnlistedClients` is set | A verified domain that is itself malicious, at a tenant door where `others` is `allow` |
| A client blocked, or taken off a `known` list, after people connected it | The door's policy is checked again against the grant's client on every refresh, code exchange and `resolveSeat`; a refused client gets `invalid_grant` and no seat | A metadata document that changes its redirect URIs after consent keeps the status it had then |
| A trusted domain's open redirect or user upload used as a metadata document | `known` needs the exact URL; a metadata URL that answers with a redirect is refused (the kit checks with `redirect: 'manual'` and the library's headers, since the library follows redirects), and the document the kit reads must match the library's | A document the attacker can write at the exact known URL. A redirect to an identical document |
| A stolen sign-in code | Single use (across locations when `signInCodes` has the consistent store), 120 s, hashed, and issued for one flow's `state`: `redeem` refuses it with any other state, and the callback's state must match the cookie of the browser that consented. An attacker who runs his own flow has his own state, so the victim's code is refused (and spent). A code for the attacker's state, issued in the victim's browser, fails at the callback without his cookie and is spent there. The sign-in returns it by form POST after a click, so it is not in a URL | A product with its own code store that does not bind codes to the state. Without the store, a second redeem from a location whose KV cache holds the code, with the same flow's state |
| Login CSRF (an attacker's code pushed into a victim's browser) | The callback `state` is bound to the browser that clicked Continue, and the code to that state, so a code from another flow is refused | The product's sign-in must compare `return_to` to the exact callback URL |
| A stolen refresh token | Rotated on every use and bound to client and door. A rotated token presented again revokes the whole grant, and with it every access and refresh token of the family. One refresh per grant at a time, under a lock | On the KV default only: two isolates refreshing one token at once, and a replay from another region within about 60 seconds. A Durable Object or D1 store closes both; a platform door requires one unless the product accepts the race |
| A revoked grant written back by a refresh in a location whose KV cache still holds it (the library writes the whole grant on every refresh) | Every revocation writes a tombstone to the refresh store first, kept longer than any token of the grant. The token endpoint checks it before the library sees a refresh token or a code, `resolveSeat` after an access token validates, `connectedApps` for each grant. A tombstoned grant is revoked again | On the KV default the tombstone has the same cache delay as the grant, so a revoked grant can come back; a platform door refuses that store unless the product accepts the race |
| A stolen access token | One hour. Revoking the app, losing the seat (`checkSeat`, required at every door) or a role change (guard) stops it on the next call that reads the change. `checkSeat` and `can()` read the product's own store, so they act as fast as it does. Revoking the app deletes the grant and its tokens in KV and tombstones the grant, and `personLostRole` records a revocation of the person; `resolveSeat` reads both on every call | On the KV default, a revoked token can still work in another location for up to about 60 seconds. Revoking one access token alone (RFC 7009) is a KV delete with no tombstone: other locations stop it within about 60 seconds |
| A grant or key made just before the person loses a role (KV's listing lags) | Each grant and key is entered in the person's index in the refresh store when it is made. `personLostRole` first records a revocation of the person, checked at every refresh, code exchange and `resolveSeat`, then revokes what the index and the listing find. `checkSeat` runs at refresh and code exchange too | On the KV default the index is a KV listing and the revocation sits behind the KV cache, so both lag about 60 seconds |
| Stale permissions in tokens | Tokens hold no permissions; `can()` runs on every call | None |
| A leaked key | Hashed at rest, shown once, expiry capped, personal capped at R2, service capped at R2 by default and limited to its tools and one tenant, no service keys at a platform door unless listed, revoked with the person. With a consistent store a revoked key is tombstoned: it stops at once everywhere, and `transferService` refuses it | A key in a log or a repository is valid until it expires or is revoked. Without a store (`Keys` alone) or on the KV default, a revoked key works in another location for about 60 seconds |
| A limit lifted by a bad number (`NaN` from a missing variable) | Every numeric option must be a whole number in range, checked at start | None known |
| Registration spam | Off by default; when on, a counter per address per hour | KV counters are approximate; use a rate limit binding in front for a hard cap |
| Consent brute force or bots, or KV write floods on `/authorize` | `rateLimit.authorize` counts every GET per address before any work; Turnstile after repeated attempts from one address | Many addresses. Without the binding there is no limit (the kit warns) |
| One caller using up a limit for everyone (requests with no address, through a proxy or a service binding) | A request without the caller's address is refused wherever addresses are counted; `clientIpHeader` names a header your own front sets | MCP clients hosted on Workers share Cloudflare's addresses, so they share a bucket; size the limits for that |
| One caller getting a fresh bucket per request (a new IPv6 address, or a made-up header value) | IPv6 counts by /64, and by /48 with `authorizePer48` and `tokenPer48`; 6to4 by its IPv4 address. The header's value must be one IP address. A header any caller can send is refused at start without `trustClientIpHeader` | A product that sets `trustClientIpHeader` with no front that overwrites the header. A product without the /48 bindings, against a caller with a /48. A caller with many /48s or IPv4 addresses |
| Floods on the token endpoint, or a grant's lock held by a stranger | `rateLimit.token` counts every POST per address. The refresh lock is taken only for a token the grant holds, so a made-up token writes nothing and cannot hold a lock | Many addresses. Without the binding there is no limit (the kit warns) |
| A person id shaped like a key | An id that starts with a key prefix is refused at sign-in; a token with `:` is never read as a key | None known |
| A metadata document withdrawn by its owner | No last-good fallback by default, so a 404 or an outage refuses the client | A document cached by the Cache API under its own `Cache-Control`; a product that turns the fallback on, for up to an hour |
| SSRF through a client metadata URL | The library fetches with `global_fetch_strictly_public`, 5 KB, 10 s | The flag must be set; the library warns when it is not |
| Host header injection | The issuer and door URLs are fixed in configuration; routes compare against them | A product that builds the issuer from the request |

## For the reviewer

The kit is the riskiest code in the SDK. Before any door opens, a second
engineer reads `typescript/src/oauth/` line by line and checks:

1. **Resource required.** `authorizeGet` refuses a request without exactly
   one `resource`, before `beginConsent`. Try a single-door server, where the
   library would default it.
2. **PKCE.** Both the raw query and `request.codeChallengeMethod` must say
   S256, for confidential clients too. The token endpoint verifies the
   verifier (the library). Try `plain`, a missing method, and a code
   exchanged without a verifier.
3. **Redirect safety.** No error redirects to a client the door does not
   know: the client's status is worked out before any error is sent back,
   and a library error's `redirectTo` is followed only for a known client.
   Every redirect uses `authorizationErrorRedirect` on a request from the
   library, never on request input. Try a blocked metadata client, a
   registered client, and a request without `resource`.
4. **Consent binding.** `approveConsent` and `denyConsent` get the original
   request (for the cookie) and the handle from the form. The request that
   is completed comes from storage, never from the form. The client policy is
   checked again after approval.
5. **Callback.** `finishUpstream` checks the browser cookie; the callback's
   `state` goes to `authenticate`, and `signInCodes` refuses a code issued
   for another state; the door in the stored data must match the stored
   request's resource; `chooseSeat`'s seat must be for that door, and may
   have no tenant only at a door in `platformDoors`; person ids are
   restricted to a safe alphabet.
6. **Refresh reuse.** The check in `token()` runs before the library sees
   the request, on a body read with the library's own parser
   (`request.formData()`; media type split on `;`, trimmed and lower-cased;
   no parameter but `resource` repeated). A body with a `%` that starts no
   escape is refused, since parsers disagree on it. A POST the kit cannot
   read is refused, never passed on. The lock is taken only when the
   token's SHA-256 equals the grant record's `refreshTokenId` or
   `previousRefreshTokenId`; any other token gets the marker check without
   it and goes to the library. A token is marked retired before the library
   is called and unmarked only on a 4xx; the marker lives as long as a grant
   can, and is never dropped on reuse. Confirm the
   revocation covers access tokens (`revokeGrant` deletes them), and that
   every revocation goes through `bury` (tombstone first), `api().revokeGrant`
   and `api().deleteClient` included, a client's own
   RFC 7009 revocation of a refresh token (`revocation`, after
   `clientCheck`) and a replayed code (`codeReplayed`) included, both of
   which answer 503 with nothing revoked when the tombstone cannot be
   written. Confirm a code is exchanged under the grant's lock, recorded
   before the library runs and unrecorded only on a 4xx (`redeem`), and every use of a
   grant (refresh, code exchange, `resolveSeat`, `connectedApps`) through
   `risen` or `revokedOnCall`, and every refresh and code exchange through
   `beforeMint` (the library's `tokenExchangeCallback`): the person's
   revocations, `checkSeat`, and the index entries renewed. The lock is
   taken before the marker is read and released after it is written; check
   the Durable Object and D1 stores hold it for one holder only.
7. **resolveSeat.** Audience compared to this door's resource; seat door and
   principal id compared to the token's; the grant's tombstone and the
   door's client policy as it stands now (`stillAllowed`, also run on
   refresh and code exchange); the person's revocations; `checkSeat`
   failures and throws refuse; keys checked for prefix, door, expiry, the R2
   cap, their tombstone and their owner's revocations on every call.
8. **Keys.** The secret is never stored or logged; 32 random bytes; prefixes
   cannot overlap; caps cannot be raised by configuration; a tier in the
   options is checked with `isTier`; service keys are capped at R2 by default
   and refused at platform doors not listed. With a store, `drop` writes the
   tombstone before any KV delete, and `transferService` refuses a revoked key.
   Revocation never finds its targets by KV's listing alone: the person's
   index in the store, and the person's revocation for what it missed.
9. **Pages.** Every interpolated value goes through `escapeHtml`; the CSP
   allows script only from Turnstile under a nonce; no page is cached.
10. **Library pin.** `@cloudflare/workers-oauth-provider` is exactly 1.3.0 in
    `peerDependencies` and the lockfile. Read the library's advisories and
    changelog before any upgrade, and run this kit's tests on the new
    version.
11. **Events.** `onEvent` never receives a token, a code or a key.
12. **Deployment.** The product sets `global_fetch_strictly_public`, fixes
    the issuer, compares `return_to` to the exact callback URL on its
    sign-in page, binds its sign-in codes to the state, supplies `checkSeat`,
    blocks unverified clients on the platform door, lists exact client ids
    there, binds a refresh store, sets `rateLimit.authorize` and
    `rateLimit.token`, and runs
    `purgeExpiredData` on a cron.

The tests in `typescript/test/oauth.test.ts` cover each item above with a
negative case. `oauth.workerd.test.ts` runs the whole flow under workerd with
a real KV namespace, on every `bun test`: `esbuild` and `miniflare` are
devDependencies, because some bugs (how workerd parses a form) do not show
under Bun.
