Skip to content

0051. MCP OAuth in the first release: Better Auth's authorization server, and grants that act as their user on one project

  • Status: Proposed. That claude.ai, ChatGPT, and Claude Code can connect to /mcp by OAuth, without an API key, in the first release is the maintainer’s decision of 2026-11-20, Accepted and not reopened. Four choices below are marked “decided in review”: they were made on 2026-11-20 by the orchestrating agent after the review passes on this pull request, not by the maintainer, and stay Proposed with the rest. Four more, marked “decided after the spike”, were made the same day by the orchestrating agent from the results of spike O0 and refined after the review passes on the amendment (findings), not by the maintainer, and stay Proposed too.
  • Date: 2026-11-20
  • Amends: ADR 0015 (MCP OAuth is in the first release), ADR 0026 (token prefixes; scopes chosen at consent), ADR 0031 (OAuth, the challenge seam, and scope ∩ role in dispatch), ADR 0040 (resolves its deferred MCP OAuth; the mount gains OAuth routes), ADR 0041 (the oauth_grant credential), ADR 0050 (its open item on MCP OAuth), and ADR 0021 (the refresh reuse window keeps an encrypted copy of a rotation’s tokens, below). See Consequences.

Customer.lite is configured by the user’s AI assistant through /mcp. Today /mcp accepts only a project API key: apps/workers passes an McpAuthenticator that returns a caller only for the api_key credential, and /mcp never reads a cookie (ADR 0031, ADR 0040). To connect, a user signs in, creates a key, and pastes it into their assistant. claude.ai and ChatGPT custom connectors expect OAuth instead, and a competitor (mailcheap.ai) already lets them connect by OAuth with no key, which lowers onboarding friction.

The maintainer decided on 2026-11-20 that claude.ai, ChatGPT, and Claude Code connect to /mcp without an API key, by OAuth, in the first release. Until then the plan put MCP OAuth after the MVP, behind its own spike (ADR 0040, “What stays open”).

What is built and decided:

  • Sign-in with Better Auth 1.7.25 on Workers and D1, cookie sessions, the /api/auth/* mount with a fixed route table, rate limits in D1, and the self-hosted allowlists (ADR 0040).
  • Users, memberships with admin and member, and the action fields principal (project_key, user, any), target (project, workspace, actor), scope, and role (ADR 0041). In code, TARGET_RULES allows project_key on project actions and user on workspace and actor actions; CREDENTIALS maps project_key to api_key and user to session; admit in core/src/actions/invoke.ts is the one gate. any is not built yet. ADR 0041 already decides that a grant acts as its user, is bound to one project, gets the grant’s scopes ∩ the user’s current role, and reaches only any actions.
  • Grant scopes read, write, send, and admin, bound to one project (ADR 0026). workflows.activate needs scope admin and role admin.
  • A live change records its principal as { kind: "grant", id } (ADR 0044), so a grant’s ID must keep naming its user for as long as live changes are kept, unless the user is deleted. ADR 0050 binds its confirmation tokens to “the grant’s ID”.

External facts, checked on 2026-11-20:

  • MCP specification. The current version is 2026-07-28. Its authorization section requires:
    • Protected Resource Metadata (RFC 9728), which clients use to find the authorization server; a 401 with WWW-Authenticate: Bearer resource_metadata="…" on a missing, invalid, or expired token; and (SHOULD) a scope parameter in that challenge.
    • For insufficient scope (SHOULD), a 403 with error="insufficient_scope", the scopes the operation needs, and resource_metadata.
    • Authorization server metadata through RFC 8414 or OpenID Connect Discovery (at least one); OAuth 2.1, so authorization code with PKCE; and (SHOULD) RFC 9207 iss in authorization responses, advertised with authorization_response_iss_parameter_supported.
    • Resource indicators (RFC 8707): clients send resource in the authorization and token requests, and the server accepts only tokens issued for itself. Tokens are never passed through to other services and never sent in query strings.
    • Client registration: Client ID Metadata Documents (CIMD) are SHOULD for authorization servers; Dynamic Client Registration (RFC 7591) is MAY and marked deprecated, kept for backwards compatibility; clients try a pre-registered client, then CIMD, then DCR.
    • Public clients’ refresh tokens are rotated or sender-constrained (OAuth 2.1).
  • Clients.
    • Claude (claude.ai, Desktop, mobile, and Claude Code share one auth stack) uses CIMD when the authorization server metadata has client_id_metadata_document_supported: true and none in token_endpoint_auth_methods_supported, and otherwise DCR. claude.ai’s callback is https://claude.ai/api/mcp/auth_callback. Claude Code publishes its own client metadata document and redirects to http://localhost/callback or http://127.0.0.1/callback on any port. Claude requires PKCE S256, a 401 (not a 200) for the challenge, a resource URL that matches exactly, a form-encoded token endpoint, invalid_grant for a bad refresh token, and answers within 10 seconds (30 for refresh).
    • ChatGPT supports CIMD (preferred), DCR, and predefined clients, with PKCE, and sends resource. Without RFC 9207 iss it uses a per-callback redirect URI under https://chatgpt.com/connector/oauth/; with it, a stable one. A public report shows its CIMD redirect_uris once disagreed with the URI it sent. Not verified: the stable URI’s exact value and developer-mode specifics.
    • A CIMD client ID names an application, not a user: every claude.ai user who connects presents the same client ID.
  • Better Auth. The latest release is 1.7.26 (better-auth, @better-auth/oauth-provider, @better-auth/mcp, @better-auth/cimd). The documented route for MCP is mcp() from @better-auth/mcp, an OAuth 2.1 authorization server built on @better-auth/oauth-provider (not to be combined with oauthProvider()), aimed at the 2026-07-28 profile. Its options include resource (the token audience), loginPage, consentPage, scopes, opt-in DCR, and refreshTokenReuseInterval (default 30 seconds). cimd() from @better-auth/cimd adds CIMD; its bundled fetch transport is Node-only, so a Worker injects its own. The provider requires PKCE with S256 only, rotates refresh tokens, and offers RFC 7009 revocation, RFC 8414 metadata, and resource-server helpers. Access tokens are JWTs (RFC 9068) when a resource is requested with the JWT plugin, else opaque. The docs left hashed storage of tokens, a token-prefix hook, RFC 9207 iss, D1 compatibility of the new tables, revocation on refresh-token reuse, and an application reference on a consent unverified; spike O0 checked them (Spike results).

A grant is a delegated credential: it is admitted exactly where a project key is, on any actions, and its user’s current role applies on top of its scopes. It names one user, one project, and a set of API scopes, and nothing about it changes after consent.

MCP_OAUTH (configuration, off by default) gates everything here: the metadata documents, the OAuth routes of the mount, and the acceptance of grants on /mcp. Off, /.well-known/* and the routes answer 404 and /mcp accepts project keys only, as today. It may be turned on in a non-production deployment once slice 1 below is complete and in production once slice 2 is, and its default becomes on once slices 1 to 3 are.

  • Better Auth’s mcp() plugin, with cimd(), in adapters/auth-better-auth, pinned to the exact better-auth version like the rest of the adapter. Building our own was weighed: it means owning OAuth 2.1, PKCE, RFC 8414, RFC 8707, RFC 9728, CIMD, rotation, and revocation, and following a specification that changed three times in a year. Better Auth already runs our sign-in on both targets, and ADR 0040’s fallback clause stands: if the plugin fails a blocking spike check below, MCP OAuth is built in-house behind the same port and routes, and /mcp keeps project keys until it is.
  • Flow. Authorization code with PKCE S256 only (plain refused), and refresh tokens. No implicit grant, no password grant, no client_credentials, no device flow.
  • Issuer and discovery. The issuer is the auth mount’s base URL, {APP_ORIGIN}/api/auth: with the JWT plugin off, the plugin takes it from Better Auth’s baseURL and basePath. The authorization server metadata (RFC 8414) is served at the location RFC 8414 derives from that issuer, /.well-known/oauth-authorization-server/api/auth on the app origin, under the /.well-known/ that ADR 0028 reserves for this. The plugin also answers /api/auth/.well-known/oauth-authorization-server, which the mount does not forward. Without openid the plugin serves no OIDC discovery document. The metadata advertises code_challenge_methods_supported: ["S256"], client_id_metadata_document_supported: true, authorization_response_iss_parameter_supported: true (we send iss, RFC 9207, on the code redirect and on error redirects once the redirect URI is validated), grant_types_supported: ["authorization_code", "refresh_token"], and scopes_supported: read, write, send, admin, and offline_access. offline_access is needed because the plugin issues a refresh token only when the request includes it; Claude Code requests every scope the metadata lists. We issue no ID tokens; openid is not offered.
  • Discovery risk of a path issuer. A client that ignores the protected-resource document’s authorization_servers and probes the root /.well-known/oauth-authorization-server gets 404. Claude Code follows the document; claude.ai and ChatGPT are checked in S2’s public-URL test. If one of them probes the root, the fallback is an origin issuer: Better Auth mounted so its base URL is {APP_ORIGIN}. Serving the same document at the root is not the fallback: its issuer would still be {APP_ORIGIN}/api/auth, which fails a client that checks it against the URL it fetched, as RFC 8414 §3.3 requires.
  • Recorded metadata deviations. The plugin’s document also lists client_secret_basic, client_secret_post, and private_key_jwt in token_endpoint_auth_methods_supported, and an introspection_endpoint that the mount answers with 404. We serve the document as the plugin builds it. client_secret_* cannot be used: no client has a secret (CIMD clients have none and DCR is off). private_key_jwt can be, by a client whose document declares it: see Client authentication under Client registration.
  • The protected resource. The resource is {APP_ORIGIN}/mcp, exactly the URL the user enters. Its metadata (RFC 9728) is served only at the path-inserted location, /.well-known/oauth-protected-resource/mcp, naming the issuer as the only authorization server and the four scopes. The 401 challenge names that URL, so clients do not need to probe. The plugin would also serve /.well-known/oauth-protected-resource to any request that reaches its handler, with no option to stop it; the mount’s route table does not forward that path, so it answers 404.
  • Audience (RFC 8707). Authorization and token requests must carry resource equal to {APP_ORIGIN}/mcp; any other value answers invalid_target. Every token records it, and only tokens whose audience is {APP_ORIGIN}/mcp are accepted. The plugin accepts a request without resource and issues a token with no audience, so the mount closes that gap:
    • an authorization_code token request without resource answers invalid_target;
    • an authorization request without it is answered with an error page on our origin, never a redirect: the redirect URI is not validated yet at that point, so a redirect would be an open redirect;
    • a refresh request may omit it: the refresh token carries the resource it was issued for;
    • the token and revocation routes refuse a body that is not application/x-www-form-urlencoded (invalid_request) before the mount reads it to strip the code prefix.
  • Where grants are accepted (decided in review). Only on /mcp. A surface accepts grants only when a GrantVerifier is wired into it, and apps/workers wires one into /mcp alone, so REST keeps project keys and sessions and a grant token there is not a credential (401). /mcp keeps accepting project keys.
  • Tokens.
    • Access tokens are opaque: cl_oat_ and 256 random bits, valid 1 hour. The plugin is configured with disableJwtPlugin: true, prefix, and a 256-bit generateOpaqueAccessToken. Opaque, because every request reads the grant and the membership anyway (below), so a self-contained JWT saves no lookup and would add a signing key to rotate and keep.
    • Refresh tokens are cl_ort_ and 256 random bits, rotated by the plugin on every use. Rotation is one conditional UPDATE … WHERE … revoked IS NULL … RETURNING * on D1, so concurrent refreshes of one token yield one successor (the others answer invalid_grant), and a retry within the window gets the replay below.
    • Reuse window (decided after the spike). refreshTokenReuseInterval is set to 10 seconds. Within it, a retry that asks for the same scopes and resource gets the same response again, not a new successor: the plugin keeps the rotation’s whole response (the new access and refresh tokens) on the rotated row, in rotationReplayResponse, encrypted with the auth secret. The chain does not fork; a thief who presents a stolen refresh token within the window gets the client’s own tokens, not a chain of their own. The plugin never clears that copy. The adapter clears expired copies lazily: every refresh request first sets rotationReplayResponse to null on the rows of the refresh token’s chain, found by its referenceId (the grant ID), whose rotationReplayExpiresAt has passed, and the existing daily cron does the same for every row as a backstop; tests check both. A live copy is protected like sessions.token, which ADR 0040 keeps as Better Auth writes it: reading the table alone gives nothing usable without the auth secret. That is the departure from ADR 0021’s hashes, recorded here. The bound is honest, not tight: a copy is normally gone at the chain’s next refresh after its window, otherwise within a day, crons are best effort, and D1 Time Travel and backups keep the encrypted value for their own retention. A window of 0 was rejected: it would turn a client’s ordinary retry into the family revocation below.
    • A refresh token expires after 30 days unused, and every grant expires 90 days after consent, whatever its use, after which the user consents again. All values are configuration.
    • Authorization codes are not grant tokens: cl_oac_, valid 60 seconds (codeExpiresIn), once, bound to the client, the redirect URI, the PKCE challenge, and the resource. The plugin has no prefix option or generator for codes, which are 32 characters of [A-Za-z0-9] (about 190 bits): the mount adds cl_oac_ on the way to the redirect URI and strips it at the token endpoint, where a code without it is invalid_grant. A replayed code is invalid_grant and revokes what it issued.
    • Only SHA-256 hashes of access tokens, refresh tokens, and codes are stored (ADR 0021), apart from the encrypted replay copy above. This is the plugin’s default (storeTokens: "hashed"): an unkeyed SHA-256, base64url, of the value without its prefix. The values are random, so an unkeyed hash suffices.
    • No JWT fallback is needed: with disableJwtPlugin: true, access tokens are opaque even when a resource is requested.
    • Revocation (RFC 7009). Built (amended): the mount answers revocation itself. An access token is marked revoked. A refresh token, whether the newest of its chain, rotated, or revoked already, ends its whole grant: the grant’s revoked_at is set through ControlStore.endGrant and every token row that names the grant is deleted. A grant has one chain, so this is RFC 7009’s “other tokens of the same authorization grant”, and it cannot lose a race with a concurrent rotation, which marking only the row given could. A token it does not find, and an access token revoked already, are answered 200, as RFC 7009 says. A revocation whose client_id is not the token’s client (looked up by hash) is refused with 401 invalid_client before anything changes.
  • Storage. In the control plane (D1, or Postgres’s control schema):
    • The plugin’s tables for clients, resources, consents, access tokens, and refresh tokens, generated by getMigrations and checked in as a numbered migration like 0005_auth, with our table names and snake_case columns through the plugin’s schema option (the spike saw the generated DDL honour it, not yet a run against renamed tables).
    • mcp_grants(id, user_id, client_id, workspace_id, project_id, api_scopes, created_at, expires_at, revoked_at). It is owned by core, behind ControlStore.
    • Source of truth (decided after the spike). mcp_grants owns a grant’s identity, user, project, scopes, expiry, and our revocations; the plugin’s token rows own token liveness. A grant is usable only when both agree: its row is neither revoked nor expired, and it has a live token. A token is live when its row is neither revoked nor expired. One rule in core, over ControlStore and the adapter’s token lookup, decides a grant’s liveness for both the verifier and listing, so the two cannot disagree.
    • A grant is never deleted. revoked_at records only revocations by us or the user (grants.revoke, member removal, deletions, the allowlist). No ended_reason column: the audit log, when it comes, records why. A grant whose token chains the plugin ended is not written to: its liveness is computed where it is read (below). Revoking a grant sets revoked_at and deletes its token rows, so { kind: "grant", id } in a live change (ADR 0044) and later in the audit log always resolves to a user, unless the user is deleted.
    • A daily cron deletes expired codes and tokens, token rows whose grant is revoked or expired (built: the grants are read through ControlStore.findGrants and judged by core’s isGrantRowLive; a row whose grant is unknown is deleted too), CIMD documents past their cache time, and client-assertion jti rows past expiresAt (below), and clears expired replay copies (above). Deleting the consent rows of ended grants (each consent creates one) comes with S3.

Client registration (decided in review: CIMD only at launch)

Section titled “Client registration (decided in review: CIMD only at launch)”
  • CIMD. The authorization server accepts an HTTPS URL as client_id and fetches its metadata document. The fetch follows the outbound-webhook SSRF rules (architecture): HTTPS only, no IP-literal hosts in private, loopback, link-local, or metadata ranges, none of our own hostnames, and no redirects at all. It reads at most 5 KB within 5 seconds, requires the document’s client_id to equal its URL, and caches the document for at most 24 hours. Fetches are rate-limited per client IP and per host in auth_rate_limits, and a failed fetch is cached as a failure for 5 minutes. Built (amended):

    • The fetch limits apply only to a client not yet stored in oauth_clients. They are checked when such a client is resolved, before cimd() runs, so a refused request spends none of cimd()’s per-isolate budget (and an admitted one is charged even when cimd() serves it from its cache). Past 20 an hour from one client IP, or 60 an hour to one host, the request is refused: the client gets invalid_client, and nothing is fetched. The IP’s limit is checked first, so a refused IP spends nothing of the host’s.
    • A stored client’s document is fetched again without them. When a fetch of it is refused anyway, by these limits or by cimd()’s per-isolate budget, the stored client is served as stored. A flood of new client_ids on a shared host (https://claude.ai/<random>) therefore cannot lock out the clients already stored there, at authorize or at refresh.
    • The per-host limit stays keyed by host, not by client_id: its job is to bound the fetches we send to one host, which random paths would escape. Counting only clients not yet stored limits the lockout to clients not stored: one that has never connected, or whose row the cron pruned (once no token names it), which can be a well-known client such as Claude Code’s. Anyone who spends a shared host’s budget every window with random paths, at authorize or at the token endpoint, keeps such a client from connecting for as long as they keep it up. This affects availability only, and it is accepted for staging. The fix, which must land before S2 or production (#99): never prune, or seed, the rows of known clients, or a high per-host cap plus a per-client_id key.
    • A client’s JWKS goes through the same transport and is not limited here.
    • The authorize endpoint answers its own 429 page, before the plugin runs, past 30 requests in 10 minutes from one client IP. It has no per-host limit: anyone could spend a shared client’s, with no session.
    • Every per-IP limit, sign-in’s included, keys IPv6 by its /64 and IPv4 by the whole address (ipKeyOf); every per-host limit keys on the host lowercased without trailing dots (hostKeyOf). A request without a usable client IP is refused and logged, and a failing limit store refuses the fetch.
    • The failure cache and the 24-hour cap remain S2’s.
    • cimd() (with metadataProfile: "mcp-2026-07-28") itself enforces the 5 KB, the 5 seconds, status 200, a JSON content type, and client_id equal to the URL. Its cache and fetch budgets are in memory, per isolate, revalidating after 60 minutes or as Cache-Control says, with no failure cache; the 24-hour cap, the failure cache, and the D1 rate limits are ours, in the transport or isMetadataDocumentUrlAllowed.
    • On Workers the adapter passes cimd() a fetchClientMetadataResource over fetch with the SSRF checks. cimd() asks for redirect: "error"; the transport sends redirect: "manual" and refuses any 3xx. On Node it uses the resolver-pinned check.
  • From the document, only client_name (at most 100 characters) and redirect_uris are used. logo_uri, client_uri, policy_uri, and tos_uri are never fetched or shown.

  • Redirect URIs are matched exactly against the document’s list, except the loopback port (RFC 8252): each must be https with a host name, or http on localhost, 127.0.0.1, or [::1]. No fragments, no wildcards, no other schemes; private-use schemes such as cursor:// are refused at launch. The plugin matches exactly with the loopback-port exception, but accepts private-use schemes from a document, so the adapter passes validateRedirectUri. That callback, (uri, registeredUris, defaultResult) => boolean, replaces the plugin’s decision rather than adding to it: returning true accepts a URI the document does not list. It is therefore defaultResult && schemeAllowed(uri), where schemeAllowed accepts only https with a host name and http on the loopback hosts. An S1 test checks that an https redirect URI the document does not list is refused.

  • Client authentication. No client secret exists. The plugin’s native behaviour is the default: cimd() 1.7.25 takes the client’s method from the document’s singular token_endpoint_auth_method (default none), and:

    • none gives a public client;
    • private_key_jwt with jwks or jwks_uri gives a client the plugin authenticates by a signed assertion at the token endpoint. The jwks_uri fetch goes through cimd()’s fetchClientMetadataResource, our SSRF transport, and the transport also requires jwks_uri to be on the client_id’s origin. Each assertion’s jti is recorded as a single-use row (oauthClientAssertion) that the plugin never prunes, so the daily cron deletes those past expiresAt;
    • any other method is refused (the plugin already refuses symmetric ones).

    ChatGPT, by OpenAI’s Apps SDK documentation (read 2026-11-20, not observed), lists token_endpoint_auth_methods_supported: ["none", "private_key_jwt"], prefers private_key_jwt in the singular field, publishes its keys at /oauth/jwks.json on its origin, and picks from the intersection with our metadata, so it becomes a private_key_jwt client and sends an assertion. It gets its stable client_id and redirect URI only when the iss we send (RFC 9207) matches the issuer exactly, which it does. S2’s public-URL test records ChatGPT’s declared method and what it sends at the token endpoint. Only if ChatGPT fails there is the alternative used: a public client, by the transport rewriting the document’s method to none and the plugin’s overrides advertising only none in token_endpoint_auth_methods_supported (which changes the “served as the plugin builds it” rule above); DCR behind MCP_OAUTH_DCR (below) is the last fallback. An S1 test checks the singular field: none gives a public client, private_key_jwt with a same-origin jwks_uri is accepted, and anything else is refused.

  • DCR is off at launch. It comes back only if the spike or a client slice shows a target client failing on CIMD; ChatGPT’s reported redirect mismatch is the concrete test. In that case it is turned on behind MCP_OAUTH_DCR with this design:

    • Every client registered is public; a request for another authentication method is answered with none (RFC 7591 lets the server replace metadata). Only authorization_code and refresh_token grant types, code responses, and redirect URIs as above, 1 to 5 of at most 512 characters.
    • Per IP, 100 registrations an hour (claude.ai and ChatGPT register from shared server addresses, so a tight per-IP limit would block their users; the spike records the addresses they register from).
    • A deployment-wide cap of MCP_OAUTH_MAX_PENDING_CLIENTS (proposed 10,000) clients no user has consented to, each deleted 24 hours after registration. At 100 an hour, one IP registers 2,400 a day, so five IPs fill the cap. The cap therefore bounds storage, not availability: over it, registration answers 429 and raises an operator alert (ADR 0038), and it never blocks CIMD clients or clients already registered.
  • Both are dashboard pages on the app origin, using the existing session. The plugin’s loginPage and its consentPage are both the dashboard route /oauth/consent (amended in S1), which signs a signed-out user in and returns to the same request. The request’s signature lasts 60 seconds, which a sign-in can outlast, so the page re-signs: when the mount’s consent POST finds the signature ended, it answers request_expired with restart, the client’s own authorization request without the signature parameters; the page saves the user’s choice (or denial), follows restart once, and restores it for the user to confirm, or sends the denial, so the client still gets access_denied. Any other refusal is shown in plain words and never re-signs. Sign-in uses only the methods of ADR 0040, and the self-hosted allowlists and the managed service’s sign-in gate apply unchanged.

  • The consent page shows, as text only:

    • the signed-in account’s address, with a link to switch accounts;
    • the redirect host: “claude.ai”, “chatgpt.com”, “an app on this computer” for loopback, or the host itself. The client_name is shown only next to the host, marked as the name the application gave itself;
    • the line “Continue only if you just started connecting from yourself.”;
    • the user’s workspaces and projects (workspaces.list and projects.list, as a session), from which the user picks exactly one project;
    • the scopes, as check boxes with plain descriptions, limited to those the client requested and, of those, to what the user’s role in that workspace allows (member: read, write, send; admin: all four); with no project, an empty state says to create one first.
  • Preselected scopes (decided in review): read and write only, for every host, and only when the client requested them. admin is never preselected; a user whose role allows it ticks it themselves.

  • Consent is always asked, even for a client the user consented to before, and prompt=none answers consent_required: the project is chosen per authorization, and a renewed connection is otherwise a refresh, which needs no page.

  • Each consent creates a new grant. It never replaces an earlier one: the same CIMD client ID is shared by every user of a client, so replacing “this user’s grant for this client” would let a consent made in someone else’s connection end the user’s own. A reconnect leaves the old grant to expire or be revoked from “Connected apps”.

  • The consent POST goes through the auth mount as JSON with Origin equal to APP_ORIGIN (ADR 0040’s CSRF rule). The mount asks core to check that the user is a member of the chosen project’s workspace and that every chosen scope is within their role, and core writes the mcp_grants row. The mount then calls the plugin’s consent endpoint inside an AsyncLocalStorage that holds the grant’s ID. The AsyncLocalStorage lives only in adapters/auth-better-auth, never in core; it needs the nodejs_als compatibility flag, which apps/workers already sets (ADR 0040). The plugin’s postLogin.consentReferenceId (with shouldRedirect always false) returns that ID there, so the consent, the code, and every token of the grant carry it as referenceId, through rotations too (mechanism 1, which the spike proved). Everywhere else it returns a fresh value, so a stored consent never matches and the authorize endpoint never issues a code by itself. That holds only while:

    • the plugin’s consent endpoint is reachable only through our consent POST, and the mount answers 404 to its continue, client-management, registration, introspection, and userinfo endpoints;
    • no client row has skipConsent set (a CIMD document cannot set it; no seed or admin path may). Should one be set, the code it gets carries a fresh reference that names no grant, so its token is refused on /mcp; a test checks that.

    This rests on how 1.7.25 calls consentReferenceId. S1 pins 1.7.25; the invariant test “no code without our consent POST” is the guard against an upgrade changing it, and any version bump reruns the spike’s tests before it merges.

  • The plugin lets a consent only narrow the scopes the client requested. /mcp enforces the grant’s API scopes, which mcp_grants records, so the grant holds only scopes both requested and chosen (amended in S1): a consent POST that chooses a scope the client did not request is refused scope_not_requested, and no grant is written.

  • The consent POST checks the session and the signature before it forwards anything, a denial included, and is limited per user and per client IP (auth_rate_limits) before core writes a grant. A grant whose consent the plugin answers without a code is revoked at once, since nothing could use it.

  • The authorize endpoint never redirects to an unvalidated host: when the plugin’s answer would send the browser off our origin to a host that is neither loopback nor the origin of the client’s client_id document, the mount answers its own error page instead (S1).

  • The dashboard is served with Content-Security-Policy: frame-ancestors 'none' on every response, the SPA fallback included, by its static-asset headers (ADR 0028), so the consent page cannot be framed to trick a click.

  • Denying answers the client access_denied, as OAuth requires.

  • principal names the credentials an action admits: project_key admits an API key, user admits only a session, and any admits all three. A grant is a new credential, oauth_grant, which acts as its user (ADR 0041) but is not a session, so user does not admit it. CREDENTIALS becomes:

    Principal Credentials
    project_key api_key
    user session
    any api_key, session, oauth_grant
  • core/auth gains GrantCaller { principal: "user", credential: "oauth_grant", userId, grantId, scope: ProjectScope, apiScopes }. A new core port, GrantVerifier.verify(bearerToken) → { grantId, userId, project: ProjectRef, apiScopes } | null, is implemented by the adapter over the plugin’s token lookup and mcp_grants through ControlStore; core mints the ProjectScope from the ProjectRef, as it does for keys. The verifier only reads. It looks the access token up by hash and answers null (invalid_token) when it finds no row (the plugin deleted it, as it does in a family revocation), when the row is expired or marked revoked by the plugin (as dashboard sign-out does), when its audience is not {APP_ORIGIN}/mcp, or when its grant (referenceId) is revoked, expired, or no longer matches the token’s user and client. A grant whose token chains the plugin ended thus needs re-authentication at once: the client’s refresh fails and it asks the user to connect again. A caller’s principal says whom the request acts for (here the user), which is not an action’s principal declaration, the credentials it admits: a GrantCaller is a user caller, yet principal: "user" actions do not admit it.

  • What a grant reaches, which keeps ADR 0041’s table:

    Target Grant
    project, any actions its project, if action.scope is in the grant’s apiScopes and the user’s current role in the project’s workspace is at least action.role
    workspace, any actions (today only the sending-domain actions of ADR 0039) its project’s workspace, by the same two checks
    user-only actions of any target (workspaces, projects, members, API keys, workspaces.setSendApproval, billing, grant management) never: forbidden, as for a project key
    actor never

    Decided here because ADR 0041 left it to this ADR: workspace-level and user-only actions stay session-only. An assistant that holds a grant can no more create keys, workspaces, projects, or members, turn off approval, or manage grants than one that holds a key.

  • Scope ∩ role, every request, in two places of core. authenticateRequest checks that the grant’s user still has a membership in the project’s workspace; without one the grant is invalid_token (401), and the read path deletes nothing. Dispatch (invokeApiAction), after admit, checks the scope like a key’s and reads the role like a session’s; a missing scope or a role that is too low is forbidden. Both read memberships on every call with no cache, and no adapter checks memberships. A demotion applies on the next call.

  • Tenant selection. A grant’s project and workspace are fixed. The Customer-Lite-Project and Customer-Lite-Workspace headers are ignored, and one that names another tenant answers not_found (ADR 0041).

  • CSRF. ADR 0040’s CSRF rule applies to cookie-authenticated requests only. A grant arrives as a bearer token on /mcp, which reads no cookie, so the rule does not apply to it. The token and revocation endpoints are called by clients with form bodies and no cookie; the mount accepts form bodies only on these routes and ignores cookies there. They, and the metadata documents, answer CORS with Access-Control-Allow-Origin: * and no credentials. /mcp keeps refusing requests with an Origin header (ADR 0031).

  • Error wording. Core’s forbidden messages name the credential (key, session, or grant) rather than always “API key”.

The authentication seam and its challenges

Section titled “The authentication seam and its challenges”
  • authenticateRequest returns { caller } | { refusal: "missing" | "invalid_token" } for REST and MCP alike, which closes ADR 0031’s open item. Core returns only the reason; each surface builds its own WWW-Authenticate:
    • /mcp, missing: 401 Bearer resource_metadata="{APP_ORIGIN}/.well-known/oauth-protected-resource/mcp", scope="read write".
    • /mcp, invalid_token (unknown, expired, revoked, of another audience, or a grant whose membership is gone): 401 with the same parameters and error="invalid_token". An unknown cl_sk_ key gets the same, so a client can fall back to OAuth.
    • /api/*: 401 Bearer, without resource_metadata; REST is not an OAuth protected resource.
    • With MCP_OAUTH off, /mcp answers 401 Bearer without resource_metadata, as today.
  • The bearer value selects the credential by its form: cl_sk_ a project key; cl_oat_ a grant; anything else is invalid_token. The Authorization header is never logged.
  • A grant without the needed scope is a dispatch refusal of its own, missing_scope, that carries the scope the action needs. Until slice 4, MCP answers it as a forbidden tool result whose message names the scope and says to reconnect and tick it; a role that is too low is a plain forbidden. Slice 4 may turn missing_scope into the specification’s HTTP 403 insufficient_scope step-up, if the spike shows the target clients follow it.
  • ADR 0050’s confirmation tokens bind the credential identity, which for a grant is its grant ID, not its access token. A token previewed through a grant is confirmed only through the same grant: it survives an access-token refresh, and it is refused through a session, a project key, or another grant. A reconnect creates a new grant, so the assistant previews again.
  • A grant never counts as a human approval (ADR 0033, ADR 0044). Approval stays by the mailed link, an endpoint action no grant reaches. A later dashboard approval needs proof of fresh human presence, which no grant can supply. workspaces.setSendApproval is user-only, so the assistant cannot turn approval off.
  • Live changes made through a grant record { kind: "grant", id: grantId }; the grant row, kept after revocation, names its user.
  • grants.list and grants.revoke are user-only actor actions: a user lists their own grants (client identity as on the consent page, project, scopes, created, expires) and revokes one. They are REST routes and MCP tools; over MCP they answer forbidden to keys and grants, like every user-only action, and on REST a grant token is not a credential. The dashboard lists them on a bare “Connected apps” page.

  • “Connected apps” and grants.list compute liveness when they list: a grant is listed as live only when its row is neither revoked nor expired, and it either has a live token or is younger than the code lifetime plus a margin (60 seconds plus 60), which covers the time between consent and the client’s code exchange. A grant whose chains the plugin ended is never shown as live, with no cron delay.

  • These revoke grants (set revoked_at, delete their tokens):

    • grants.revoke;
    • members.remove, for the removed user’s grants on that workspace’s projects, in the same batch as the membership and conditional on it being gone (… WHERE NOT EXISTS (SELECT 1 FROM memberships …)), so a removal refused by the last-admin rule revokes nothing;
    • deleting a user, a workspace, or a project;
    • on the managed service, disabling a user. No disablement exists yet; the abuse screening that adds it revokes grants with sessions.
  • A self-hosted user whose address left ALLOWED_EMAILS ∪ ADMIN_EMAILS is refused at once: GrantVerifier checks the list like SessionVerifier and answers invalid_token. The daily cron then revokes their grants.

  • Family revocation (decided after the spike). The plugin deletes every refresh token of a (user, client) pair, and every access token issued with one, when it sees a revoked refresh token again: all of the user’s grants through that client, not only the one concerned. Its triggers:

    • a refresh with a rotated token after the reuse window;
    • a refresh with a refresh token the client revoked itself (revocation only marks the row, without rotatedAt, so it is never “within the window”);
    • a revocation of a refresh token that is already revoked, whether rotated or not, even within the window;
    • so any client that retries a refresh after revoking, or revokes twice.

    The deletion is three deleteMany calls, not atomic on D1: a rotation of another chain of the same pair between them can leave a fresh refresh token behind, which then simply keeps working. Claude Code’s logout revokes both its tokens at the revocation endpoint (observed), so a later retry of its refresh token, or a second revocation, would end every Claude Code grant of that user; that consequence is inferred from the plugin’s source, not observed with Claude Code. This is accepted for the first release because it fails safe: the user reconnects. Our grants stay consistent with it without being written to: the verifier finds no token row and answers invalid_token, and listing computes liveness (above), so the dead grant is not shown as live. revoked_at is not set.

  • Dashboard sign-out (decided after the spike). The plugin hooks session deletion: signing out of the session that consented marks that session’s access tokens revoked, keeps refresh tokens whose scopes include offline_access, and revokes the others. The verifier honours revoked, so sign-out ends the current access tokens; a client that holds an offline_access refresh token refreshes and keeps working, so MCP access survives sign-out without decoupling grants from sessions. A client that did not request offline_access holds no refresh token and must connect again after sign-out; S2 checks that claude.ai and ChatGPT request it. The spike observed the revoked marks but its test asserted nothing; S1’s test asserts both halves.

  • Admins viewing and revoking other members’ grants is not in the first release (decided in review); removing the member covers the urgent case, and the workspace view comes with the audit log.

  • Phishing through a real client. The consent page’s host is not proof that the person consenting started the connection. An attacker can add our server as a custom connector in their own claude.ai or ChatGPT account and send the resulting authorization URL to a victim. The victim sees “claude.ai”, consents, and the code goes to claude.ai’s callback for the attacker’s session, so the attacker’s connector holds a grant on the victim’s project. PKCE does not help, because the attacker’s client started the flow. The mitigations are partial: the “Continue only if you started this” line, the account shown, admin never preselected, every grant listed in “Connected apps” with its creation time, and a consent never replacing the victim’s own grant. Requiring a recent sign-in before admin can be ticked is Open. A grant with admin held by an admin can activate sending workflows; ADR 0050’s confirmation and, where on, ADR 0033’s approval are what stand between it and sends.
  • Token theft and replay. One-hour access tokens; rotating refresh tokens with the reuse window above; audience binding to /mcp; tokens only in the Authorization header, never in a query string; no token passthrough, since /mcp calls no other service with them. Tokens are not sender-constrained (DPoP): the target clients do not all send it, and the plugin’s replay store would need a shared store on Workers. A stolen access token is usable for up to an hour. A stolen refresh token is usable until the grant is revoked or expires, or until the client’s next refresh after the thief’s makes the plugin revoke the whole (user, client) family; presented within the reuse window it returns the client’s own tokens. Both are accepted.
  • Logs (ADR 0032). cl_oat_, cl_ort_, and cl_oac_ join CREDENTIAL_PREFIXES, so logError masks them. The plugin’s messages reach logs only as fixed codes through ADR 0040’s logger mapping, and no request URL, which may carry a code, is logged.
  • Responses. The token endpoint returns access_token and refresh_token to the client that proved the code and its PKCE verifier; no other response carries a token. ADR 0040’s rule that strips every token key from forwarded responses stays, and the new routes are added to its test.
  • Tenant isolation. The isolation fixture runs every any action through a grant bound to workspace A’s first project: A’s other project and workspace B answer not_found, a header naming them answers not_found, and a grant whose user left A answers 401. Grant management and the consent route are in the fixture too: a user sees and revokes only their own grants, and cannot consent to a project of a workspace they are not a member of.

MCP OAuth is core authentication and ships in the open-source edition too, behind the same MCP_OAUTH flag. It needs nothing beyond sign-in’s settings and an APP_ORIGIN that the client can reach (a public HTTPS origin for claude.ai and ChatGPT; loopback suffices for Claude Code). It runs only on the Cloudflare target until ADR 0040’s Node and Postgres check, which then covers it. Nothing in it is cloud-only.

A throwaway spike, like ADR 0040’s, runs mcp() and cimd() at the pinned version on workerd and D1. Its checks:

  • Blocking: if one fails and the plugin cannot be configured to pass it, the in-house fallback applies.
    • Every token can be traced to our grant, and several grants of one user and one client coexist. The spike tries, in order:

      1. the consent carries our grant ID as a reference into every code and token;
      2. the adapter’s token-generator hook records each token’s hash → grant ID in core’s store, so the grant ID never travels through the plugin’s consent;
      3. (with 1 or 2 for tracing) if several plugin consents of one user and one client cannot coexist: one plugin consent per (user, client), with mcp_grants, keyed per issuance, as the source of truth. The cost is recorded: an attacker’s connection through the same client can replace the victim’s plugin consent, which ends the victim’s connection (denial of service) but gives the attacker no privilege over it.

      Only if none works does the in-house fallback apply.

    • The plugin never issues a code without our consent POST, including for a stored consent and for prompt=none.

    • Tokens and codes are stored hashed.

    • The generated tables work on D1 without interactive transactions. Concurrent refreshes of one token rotate it once: a conditional UPDATE … WHERE on the unrotated token, with its change count checked. A retry within the reuse window leaves exactly one live refresh chain. (As first written, this check expected the retry to get a new successor, since hash-only storage could not return the first; the spike replaced it with what it protects, because the plugin returns the first again.)

  • Recorded, each one changing this ADR if it fails:
    • what the plugin does on a second refresh within the reuse window;
    • opaque tokens with our prefixes, or the JWT fallback;
    • RFC 9207 iss;
    • whether the root protected-resource document can be turned off;
    • offline_access and refresh tokens per client;
    • whether the plugin revokes a whole grant on refresh-token reuse;
    • the CIMD transport on Workers;
    • the bundle size and CPU time added;
    • logs.
  • It then connects Claude Code (loopback), claude.ai, and ChatGPT through a tunnel to a development deployment, by CIMD, and records:
    • refresh and revocation for each;
    • whether ChatGPT’s redirect URI matches its document;
    • what each client does on a forbidden for a missing scope, and on a 403 insufficient_scope.

Its results are recorded below and in the findings; the decision text above already reflects them.

Spike O0 ran better-auth, @better-auth/mcp, @better-auth/oauth-provider, and @better-auth/cimd 1.7.25 on workerd and D1, through adapters/cloudflare’s Kysely dialect, in 42 tests and under wrangler dev, then connected the real Claude Code CLI. Its code is not merged. No blocking check failed:

Blocking check Result
Tracing and coexisting grants Pass, with mechanism 1 (the consent’s referenceId); mechanisms 2 and 3 are not needed
No code without our consent POST, stored consent and prompt=none included Pass, while the conditions under the consent POST above hold
Tokens and codes stored hashed Pass, except the encrypted replay copy, now cleared lazily and by the daily cron
D1 without interactive transactions; concurrent refreshes rotate once Pass: 8 concurrent refreshes gave one success and one live successor
A retry within the window leaves exactly one live refresh chain (replaced after the spike; first written as “gets a new successor”) Pass: the plugin returns the same response again, from the encrypted copy

Recorded:

  • Opaque tokens with our prefixes, and iss: as above. The root protected-resource document is off by the mount.
  • offline_access: needed for a refresh token; Claude Code requests it.
  • Reuse and revocation: the (user, client) family revocation above.
  • CIMD on Workers: works with the injected transport; it fetched Claude Code’s real document.
  • Bundle size: mcp() and cimd() add about 575 KiB (gzip 104 KiB) to a Worker with Better Auth; today’s api Worker of 2,800 KiB would be about 3.3 MiB, far below the 64 MiB limit ADR 0040 records.
  • CPU time was not measurable locally; wall times under wrangler dev with local D1 were 31 to 75 ms for consent, token, and refresh, and 6 to 15 ms for /mcp with grant verification.
  • Logs: nothing written through success, errors, reuse, and revocation.
  • Initialization on Workers: the provider writes to D1 when it initializes; an instance created in a request that ended first made every later auth request hang. The adapter awaits auth.$context in the request that creates the instance.

Clients:

  • Claude Code: verified over loopback, by CIMD (https://claude.ai/oauth/claude-code-client-metadata): discovery from the 401 challenge, consent, the cl_oac_ code with iss, a connected session, refresh after a 401 invalid_token, “Needs authentication” after the grant was revoked, and revocation of both tokens on logout. That a retry after its logout would end its other grants is inferred, not observed. Not observed: its handling of a forbidden tool result or a 403 insufficient_scope, which needs a model turn.
  • claude.ai and ChatGPT: not tested. They need a public HTTPS origin, a deployment or a tunnel, which needs the maintainer’s approval. They are tested before S2, with the checks listed above, plus: whether each requests offline_access; ChatGPT’s declared token-endpoint authentication method and what it sends at the token endpoint (see Client authentication); and whether each finds the authorization server from the protected-resource document or probes the root /.well-known/oauth-authorization-server (see the discovery risk above).

Two preparation pull requests, then thin vertical slices, each usable on its own behind MCP_OAUTH:

Pull request Builds Tests
O0 docs(adr): record the MCP OAuth spike the throwaway spike above; results as an amendment here the spike’s checks
P1 refactor(auth): authentication refusals and the 401 challenge { caller } | { refusal } for REST and MCP; each surface writes WWW-Authenticate the 401 bodies and headers of both surfaces, unchanged except the challenge
P2 feat(api): any principal for project actions (ADR 0041’s remaining work) any in TARGET_RULES, sessions on project actions with the Customer-Lite-Project header, project actions become any (merged in #58); projects.create and projects.list (in progress) the session cases of the isolation fixture; ADR 0040’s 8-day session test
S1 feat(mcp): Claude Code connects by OAuth (non-production deployments only) MCP_OAUTH; mcp() and cimd() pinned at 1.7.25 in the adapter, with its initialization awaited (auth.$context) in the request that creates it; the migration and mcp_grants behind ControlStore; the metadata documents and the mount’s route table, with the code prefix, the resource rules, the form-body check, the revocation rules, and validateRedirectUri; oauth_grant, GrantVerifier honouring revoked, GrantCaller, and scope ∩ role in dispatch; the prefixes; a minimal consent page; the lazy replay-copy clearing and the daily cron every any action through a grant in the isolation fixture, user-only actions forbidden to grants on MCP, and a grant token on /api/* answering 401; the invariant tests below; then the deploy gate, on staging once L1 is deployed with it: Claude Code connects over loopback by CIMD to the staging Worker, calls a read tool, refreshes, and is revoked
L1 feat(auth): D1 limits on authorize and CIMD fetches (built) in D1, the authorize limit per client IP, and the CIMD fetch limits per client IP and per host for a client not yet stored, IPv6 keyed by its /64; the hard prerequisite of MCP_OAUTH=true on any publicly reachable deployment, staging included each limit refuses past its count and keys on its IP or host; a flood of new client_ids on a host leaves its stored clients authorizing and refreshing
S2 feat(mcp): claude.ai and ChatGPT connect by OAuth first, the spike’s public-URL test of both clients, with the maintainer’s approval; the failure cache, and the 24-hour cap; RFC 7009 revocation by a private_key_jwt client without client_id; the client’s name on the consent page; public-HTTPS connection; the full consent page (account, host line, project choice, scopes); user guides and the llms.txt entry a full authorization in a browser test; the deploy gate for both clients
S3 feat(api): grants.list and grants.revoke the actions, the bare “Connected apps” list with liveness computed, revocation on member removal, the cron’s deletion of consent rows of ended grants; the mount’s token-row SQL moved into one module beside GrantStore; an expires_at index on the token tables when they grow each revocation path answers 401 on the next MCP call; a family revocation, and the client’s own RFC 7009 revocation, each take the grant off the list at once
S4 feat(mcp): what the spike proved necessary only if the spike or a slice shows the need: DCR behind MCP_OAUTH_DCR; the 403 insufficient_scope step-up as for S1, for what it adds

P1 and P2 do not depend on each other; S1 needs O0, P1, and P2; L1, S2, and S3 need S1, and S2 needs L1. After S1 alone, MCP_OAUTH may be turned on only in a deployment that is not publicly reachable, such as a local wrangler dev. Staging, which is publicly reachable, runs with MCP_OAUTH=true only once L1 is deployed there, and S1’s deploy gate runs on staging after that. L1 meets that prerequisite only with both of its amendments in: per-host limits that only clients not yet stored can spend, and IPv6 keyed by its /64. Production follows S2; the default becomes on after S3.

Invariant tests that stay in the suite from S1 on (ADR 0006):

  • No code is ever issued without our consent POST, for a stored consent and for prompt=none. This is also the upgrade guard for the consentReferenceId mechanism.
  • Two concurrent consent POSTs of one user and one client each give a grant whose tokens carry its own grant ID.
  • A client row with skipConsent set still gets no token that /mcp accepts.
  • The mount’s route table: every plugin endpoint outside it (continue, client management, registration, introspection, userinfo, the plugin’s own consent, the root protected-resource document) answers 404.
  • An https redirect URI the client’s document does not list is refused, and so is a private-use scheme it does list.
  • An authorization_code token request without resource answers invalid_target; a code without cl_oac_ answers invalid_grant; revoking an unknown token answers 200.
  • The authorization server and protected-resource metadata match a snapshot.
  • An ADR 0050 confirmation token previewed through a grant is confirmed through it after an access-token refresh, and refused through a session, a project key, and another grant of the same user.
  • A grant on the approval path is refused: it reaches no endpoint action and no user-only action (forbidden).
  • A scan of every control-plane table after a full authorization, refresh, and revocation finds no raw cl_oat_, cl_ort_, or cl_oac_ value.
  • A demotion between two calls of the same grant applies on the second call.
  • Every dashboard response, the SPA fallback included, carries frame-ancestors 'none'.
  • A whole authorization, refresh, reuse, and revocation writes no token, code, address, or IP address to any log.
  • After the reuse window, the chain’s next refresh, and separately the daily cron, leave no rotationReplayResponse past its window.
  • Signing out of the dashboard session that consented makes the grant’s current access token invalid_token on /mcp, and a refresh with its offline_access refresh token then gives a token that works.
  • A user connects claude.ai, ChatGPT, or Claude Code by entering {APP_ORIGIN}/mcp, signing in, choosing a project and scopes, and consenting. No key is created or pasted. Project keys keep working on /mcp and REST.
  • The first release grows by O0, P1, P2, S1, L1, S2, and S3, with S4 only if needed. P2 was needed for the dashboard anyway. The launch critical path now includes the spike and S1.
  • A user whose grant lacks a scope reconnects and ticks it, which creates a second grant; the old one stays in “Connected apps” until it expires or is revoked.
  • Amendment lines:
    • ADR 0015: MCP OAuth for claude.ai, ChatGPT, and Claude Code is in scope for the first release.
    • ADR 0026: grant tokens carry cl_oat_ and cl_ort_, and authorization codes cl_oac_; scopes are chosen at consent within the user’s role.
    • ADR 0031: its open items on MCP OAuth and the challenge seam are decided here, and the scope ∩ role check of a grant runs in dispatch, not in the authenticator.
    • ADR 0040: its deferred MCP OAuth is decided here; the mount’s route table gains the OAuth routes, of which the token and revocation routes accept form bodies and read no cookie.
    • ADR 0041: a grant is the oauth_grant credential, admitted only by any actions.
    • ADR 0050: its open item on MCP OAuth points here.
    • ADR 0021: from a refresh rotation until it is cleared, the rotation’s tokens are kept encrypted with the auth secret, like sessions.token (ADR 0040), not hashed.
  • Open:
    • claude.ai and ChatGPT: the spike’s public-URL test, before S2, with the maintainer’s approval.
    • Requiring a recent sign-in before admin can be ticked on the consent page.
    • Per-grant request rate limits on /mcp, with those for keys.
    • A tool that tells the assistant which project its grant is bound to, if assistants turn out to need it.
    • Private-use redirect schemes for desktop clients, and an Origin allowlist for browser-based clients (ADR 0031).
    • Sender-constrained tokens (DPoP) once the target clients send them.