Skip to content

Spike O0: Better Auth `mcp()` and `cimd()` on workerd and D1

  • Date: 2026-11-20
  • For: ADR 0051, “The spike before building”
  • Code: spike/mcp-oauth/ on the spike/mcp-oauth branch (#59). Throwaway; not merged. This document is what is kept.
  • ADR 0051 applies the changes listed at the end, with four decisions made after the spike: the reuse window with its encrypted replay copy cleared lazily on the chain’s next refresh and by the daily cron, the source-of-truth split between mcp_grants and the plugin’s token rows, accepting the family revocation with liveness computed where grants are read, and honouring revoked after dashboard sign-out.

No blocking check failed. Better Auth’s mcp() and cimd() can carry ADR 0051 on Workers and D1 with mechanism 1, a few settings, and some work in the mount. Several of the ADR’s assumptions about the plugin were wrong, and one of them matters for secrets at rest: the refresh reuse window keeps an encrypted copy of the issued tokens. The changes the ADR needs are listed under What ADR 0051 should change.

Plugin-side revocation does not respect grant boundaries, and dashboard sign-out reaches MCP tokens; both need decisions in the ADR. Claude Code connected over loopback by CIMD, refreshed, and was cut off by revocation. claude.ai and ChatGPT were not tested; they need a public HTTPS URL (below).

  • Versions: better-auth, @better-auth/core, @better-auth/mcp, @better-auth/oauth-provider, and @better-auth/cimd all at 1.7.25, the version the repository pins (1.7.26 is the latest). kysely 0.29.8, wrangler 4.158.0, @cloudflare/vitest-plugin 1.6.0, vitest 4.1.12, Node 24.12.0, compatibility date 2026-11-01 with nodejs_als. Claude Code 2.1.329.

  • D1 through adapters/cloudflare’s Kysely dialect (createD1Kysely, transaction: false), as the product does. Tables from getMigrations(...).compileMigrations(), checked in as migrations/0001_auth.sql, plus mcp_grants and stand-ins for projects and memberships.

  • 42 tests in @cloudflare/vitest-plugin (workerd, Miniflare D1), all passing; then wrangler dev on port 8811 with the real Claude Code CLI.

  • Configuration (spike/mcp-oauth/src/auth.ts):

    mcp({
    resource: `${appOrigin}/mcp`,
    loginPage: "/sign-in",
    consentPage: "/oauth/consent",
    scopes: ["read", "write", "send", "admin", "offline_access"], // no openid
    disableJwtPlugin: true, // opaque access tokens
    grantTypes: ["authorization_code", "refresh_token"],
    accessTokenExpiresIn: 3600,
    codeExpiresIn: 60,
    refreshTokenExpiresIn: 30 * 24 * 3600,
    refreshTokenReuseInterval: 10,
    prefix: { opaqueAccessToken: "cl_oat_", refreshToken: "cl_ort_" },
    generateOpaqueAccessToken: random256, // 256 random bits, base64url
    generateRefreshToken: random256,
    storeTokens: "hashed", // the default
    postLogin: {
    page: "/oauth/post-login",
    shouldRedirect: () => false,
    // Mechanism 1: our consent POST runs the plugin's consent inside consentGrant.run({ grantId }).
    consentReferenceId: () =>
    consentGrant.getStore()?.grantId ?? `unconsented:${crypto.randomUUID()}`,
    },
    }),
    cimd({ fetchClientMetadataResource: cimdFetch, metadataProfile: "mcp-2026-07-28" }),
  • The mount (spike/mcp-oauth/src/worker.ts) forwards only sign-up/email and sign-in/email (spike sign-in), get-session, oauth2/authorize (GET), oauth2/token, and oauth2/revoke, and answers 404 to the rest of /api/auth/*. POST /api/auth/oauth2/consent is our consent POST, which reaches the plugin’s consent endpoint only after core’s checks. /.well-known/ serves only the two documents the ADR names.

Check Result Evidence
Every token traces to our grant; several grants of one user and one client coexist Pass, with mechanism 1 The plugin stores consents per (client, user, referenceId), with no unique constraint on (client, user). postLogin.consentReferenceId decides the reference; it is called both by the authorize endpoint and by the consent endpoint. Our consent POST writes mcp_grants, then calls the plugin’s consent endpoint inside an AsyncLocalStorage holding the grant ID, so the consent row, the code’s verification value, every access-token row, and every refresh-token row carry referenceId = grantId, through rotations too. Two consents of one user to one client, for two projects, gave two grants, both usable, each reporting its own project; revoking one left the other working (test/grants.test.ts).
The plugin never issues a code without our consent POST, including for a stored consent and prompt=none Pass Outside our POST, consentReferenceId returns a fresh value, so the authorize endpoint never finds a stored consent: a second authorization for a client consented to before goes to the consent page, prompt=none answers consent_required (with iss), and without a session login_required. A sign-in carrying the authorization request continues to the consent page, not to the client. A CIMD document cannot set skip_consent (the plugin omits it from the metadata schema). A consent refused by core (not a member, scope above the role, forged signed query) issues no code and writes no grant. The plugin’s other endpoints (continue, register, create-client, userinfo, introspect) are 404 at the mount (test/consent.test.ts). This holds only while the mount is the only way to the plugin’s consent endpoint, and while no oauthClient row has skipConsent set (no seed or admin path may set it).
Tokens and codes are stored hashed Pass, with one exception Access tokens, refresh tokens, and codes are stored as the unkeyed SHA-256, base64url, of the value without its prefix. A scan of every table after authorize, refresh, a reuse within the window, and revocation found none of the values, with or without prefix (test/storage-and-logs.test.ts). Exception: with refreshTokenReuseInterval above 0, the plugin keeps the whole token response of a rotation (the new access token and the new refresh token) on the rotated row, in rotationReplayResponse, encrypted with BETTER_AUTH_SECRET. Nothing clears it after the window; it stays until the row is deleted.
The tables work on D1 without interactive transactions; concurrent refreshes rotate once Pass Rotation is the adapter’s incrementOne: one statement, UPDATE "oauthRefreshToken" SET revoked = ?, rotatedAt = ? WHERE id = ? AND revoked IS NULL AND id IN (SELECT id … LIMIT 1) RETURNING *, and the caller fails with invalid_grant when it returns no row. 8 concurrent refreshes of one token: one 200, seven invalid_grant, one live successor, which then works (with a 10-second window and with none).
A second refresh within the reuse window gets a new successor, not the first one Does not hold; the plugin does better The ADR assumed hash-only storage could not return the first successor, so a retry would fork the grant into two chains. The plugin returns the same response again, from the encrypted copy above: same access token, same refresh token, one live chain. This is the exception to hashed storage.
Item Finding
Second refresh within the reuse window Identical response, no fork (above), when the retry asks for the same scopes and resource. A refresh that runs truly concurrently with the first gets invalid_grant, not the replay: the copy is written only after the first response is built.
Reuse of a revoked refresh token The plugin deletes every refresh token of that (client, user) pair, and every access token issued with one: all of the user’s grants through that client, not only the reused one (all Claude Code connections of that user, for example). Our mcp_grants rows are untouched. It happens for a rotated token presented after the window (or with the window at 0, on a client’s plain retry), and also for a refresh token the client revoked itself and then presents again, or revokes again: revocation only marks the row revoked, without rotatedAt, so it is never “within the window” (test/plugin-revocation.test.ts). A retry within the window whose scope or resource differs from the first gets invalid_grant without that.
Opaque tokens with our prefixes Yes, for access and refresh tokens (prefix, not stored; 256-bit values through generateOpaqueAccessToken and generateRefreshToken). No JWT fallback needed: with disableJwtPlugin: true access tokens are opaque even with a resource. Codes have no prefix option and no generator hook: they are 32 characters of [A-Za-z0-9] (about 190 bits). The mount adds cl_oac_ to the code on its way to the redirect URI and strips it at the token endpoint, refusing a code without it; that works.
RFC 9207 iss Yes. On the code redirect, and on error redirects once the redirect URI is validated (invalid_request, invalid_scope, invalid_target, consent_required, access_denied). The metadata advertises authorization_response_iss_parameter_supported: true.
Issuer The auth mount’s base URL, {APP_ORIGIN}/api/auth, not the origin: the plugin takes the issuer from Better Auth’s baseURL plus basePath when the JWT plugin is off. RFC 8414 metadata is at /.well-known/oauth-authorization-server/api/auth; the plugin also answers /api/auth/.well-known/oauth-authorization-server, which the mount does not forward. No OIDC document without openid.
Metadata content code_challenge_methods_supported: ["S256"], client_id_metadata_document_supported: true, grant_types_supported: ["authorization_code", "refresh_token"], no registration_endpoint. Deviations: token_endpoint_auth_methods_supported is ["none", "client_secret_basic", "client_secret_post", "private_key_jwt"], and introspection_endpoint is advertised although the mount does not serve it. scopes_supported includes offline_access (it must, see below).
Root protected-resource document The plugin serves /.well-known/oauth-protected-resource as well as /.well-known/oauth-protected-resource/mcp for any request that reaches its handler, with no option to stop it. The mount does not forward it: 404. The path-inserted document names the issuer and read, write, send, admin (the plugin drops offline_access there). Claude Code probes the root document only on logout.
offline_access and refresh tokens The plugin issues a refresh token only when the request’s scopes include offline_access. Claude Code requested read write send admin offline_access: every scope of the authorization server metadata, ignoring the challenge’s scope="read write", with prompt=consent. claude.ai and ChatGPT: not tested.
Scopes at consent The plugin’s consent accepts only a subset of the scopes the client requested. The grant’s API scopes live in mcp_grants and need not match, but a user cannot tick a scope the client did not request into the token’s scopes. Claude Code requests all of them, so this does not bite there.
Resource (RFC 8707) Another resource answers invalid_target. A request without resource is accepted and gives a token with no audience, which our verifier refuses on /mcp. To answer invalid_target as the ADR says, the mount must refuse an authorization or token request without resource.
PKCE plain and a missing challenge answer invalid_request. A wrong verifier and a code without its prefix answer invalid_grant. A replayed code answers invalid_grant and deletes the tokens it issued.
Revocation (RFC 7009) Revoking a refresh token marks it revoked and deletes its access tokens; revoking an access token deletes it. A second revocation of the same refresh token (even within the window), or a refresh with it, ends all chains of the (client, user) pair (above). An unknown or already removed token answers 400 invalid_request, where RFC 7009 says 200. Claude Code’s claude mcp logout revokes both tokens; its second call got that 400.
CIMD transport on Workers Works with an injected fetchClientMetadataResource; under wrangler dev the Worker fetched Claude Code’s real document. cimd() itself enforces 5 KB, 5 seconds, status 200, a JSON content type, and client_id equal to the URL. It passes redirect: "error"; our transport sends redirect: "manual" and refuses any 3xx. Our transport refuses non-HTTPS, credentials in the URL, localhost, IP literals, and our own host (src/cimd-fetch.ts). Its cache and its fetch budgets (per client, per origin, global) are in memory, per plugin instance and isolate; revalidation defaults to 60 minutes and follows Cache-Control. No failure cache. The persisted client keeps the document’s name and redirect URIs and all server scopes. Redirect URIs match exactly except the loopback port. A private-use scheme such as com.example.app:/oauth/callback is accepted; refusing it needs validateRedirectUri.
Bundle size Spike Worker 3,064 KiB (gzip 522 KiB). The same Better Auth with only email and password: 2,489 KiB (gzip 418 KiB). So mcp() and cimd() plus the spike’s code add about 575 KiB (gzip 104 KiB). Today’s api Worker is 2,800 KiB; with the plugins about 3.3 MiB, far below the 64 MiB limit ADR 0040 recorded.
CPU time Not measurable locally. Wall times under wrangler dev with local D1: authorize 419 ms with a cold CIMD fetch of Claude Code’s document over the internet, consent 38 ms, token 54 to 75 ms, refresh 31 ms, /mcp with grant verification 6 to 15 ms.
Logs Nothing. Better Auth’s logger at debug, and every console method, wrote no line through a full authorization, a refresh, a reuse, a garbage refresh token, a replayed code, a bad code, a revocation, and an unknown client (test/storage-and-logs.test.ts).
Dashboard sign-out The plugin hooks session deletion: signing out of the session that consented marks that session’s access tokens revoked (the rows stay) and leaves refresh tokens issued with offline_access alone. The spike’s verifier did not read revoked, so /mcp kept accepting the token; the refresh still worked (test/plugin-revocation.test.ts). The product’s GrantVerifier must read revoked, or the ADR decides that grants do not depend on the session that consented and the coupling is removed (tokens are bound to the session by sessionId). It revokes refresh tokens whose scopes lack offline_access; given the row above, such a token exists only after a refresh that narrowed its scopes and dropped offline_access. A later refresh with one ends all chains as above. The spike’s sign-out test logged these effects but asserted nothing.
Initialization on Workers The provider writes to D1 when it initializes (it seeds the oauthResource row). When the instance was created in a request that ended before that write finished, every later auth request hung forever under wrangler dev. The instance must await auth.$context inside the request that creates it. Today’s signInFor cache in apps/workers creates the instance without awaiting, which is safe only because plain sign-in does no I/O at initialization.
Table names The plugin’s schema option renames its tables and columns in the generated DDL (oauth_access_tokens, reference_id). Not exercised at runtime with renamed tables.

Mechanism 1 works: the consent carries our grant ID as referenceId into the code and every token. Mechanisms 2 and 3 are not needed. Mechanism 2 as written would need more than the hook: generateOpaqueAccessToken, generateRefreshToken, and storeTokens.hash(token, type) receive no request, client, user, or consent, and codes have no generator hook. It would work only with the same AsyncLocalStorage set by the mount (from the grant of the presented refresh token at the token endpoint, and by recording the code’s hash in the consent POST, which sees every code).

claude mcp add --transport http -s local cl-oauth-spike http://localhost:8811/mcp, then claude mcp login cl-oauth-spike --no-browser in a pseudo-terminal. The sign-in and consent were driven with curl as a spike user; the redirect URL was pasted back.

  • Discovery: POST /mcp 401 with the challenge, then the path-inserted protected-resource document, then /.well-known/oauth-authorization-server/api/auth.
  • Client: CIMD, client_id https://claude.ai/oauth/claude-code-client-metadata, name “Claude Code”, document redirect URIs http://localhost/callback and http://127.0.0.1/callback; it used http://localhost:55133/callback. PKCE S256, resource http://localhost:8811/mcp, prompt=consent, scopes as above.
  • It accepted the cl_oac_ code with iss, exchanged it, and claude mcp get showed “Connected” (initialize, tools/list).
  • Refresh: after its access token was deleted, the next connection got 401 invalid_token, refreshed with the refresh token, and connected again with the same grant ID.
  • Revocation: after the grant was revoked (its row marked, its token rows deleted), the refresh got invalid_grant and claude mcp get showed “Needs authentication”.
  • A second login made a second grant (another project); claude mcp logout revoked both tokens at the revocation endpoint. The grant row itself stays unrevoked: the plugin’s revocation knows nothing of mcp_grants.
  • Not tested: what it does with a forbidden tool result or a 403 insufficient_scope. That needs a model turn, which this spike did not run.

Both need a public HTTPS origin; nothing was deployed or exposed. To run these checks, the maintainer would approve:

  1. A public HTTPS origin for the spike Worker: either a deployment of spike/mcp-oauth to a development Worker on the maintainer’s Cloudflare account (a workers.dev route, a new D1 database, BETTER_AUTH_SECRET set with wrangler secret put), or a tunnel such as cloudflared tunnel --url http://localhost:8811 to wrangler dev. Either way APP_ORIGIN is set to that origin.
  2. That origin is reachable by anyone while it runs, and the spike’s sign-up is open. It would need an allowlist of the maintainer’s address before it goes up, and it is torn down (Worker, D1 database, or tunnel) right after.
  3. Accounts: the maintainer’s claude.ai account (custom connector) and a ChatGPT account with developer mode for custom connectors. The spike does not use anyone’s account on its own.

The checks then: CIMD document fetch for each client ID; whether ChatGPT’s redirect URI matches its document, with and without iss; offline_access and refresh for each; revocation; what each does on a forbidden tool result and on a 403 insufficient_scope; whether each finds the authorization server from the protected-resource document; and ChatGPT’s token-endpoint authentication (OpenAI’s documentation says its document prefers private_key_jwt and also supports none; not observed).

  • External facts, Better Auth: replace “Not verified from the docs: …” with the results above.
  • Issuer and discovery: the issuer is {APP_ORIGIN}/api/auth, so the RFC 8414 document is at /.well-known/oauth-authorization-server/api/auth. scopes_supported must include offline_access for refresh tokens. The plugin’s document also lists client_secret_basic, client_secret_post, and private_key_jwt and an introspection_endpoint; either the mount rewrites the document or the ADR records them as deviations.
  • The protected resource: the root document is turned off by the mount’s route table; the recorded-deviation sentence can go.
  • Audience: the plugin accepts a request without resource; the mount refuses it to get invalid_target.
  • Tokens, refresh: replace “Only hashes are stored, so the first successor cannot be returned again: a retry within the window forks the grant into two valid refresh chains …” with the plugin’s actual behaviour: within the window the same response is returned, no fork, and a thief within the window gets the client’s own tokens rather than a chain of their own. The cost moves to secrets at rest: the response is kept encrypted with the auth secret on the rotated row, which a scheduled job must clear once the window has passed (or the window is 0, which turns a client’s retry into a revocation of all its grants through that client).
  • Tokens, codes: cl_oac_ is added and removed by the mount; codes are about 190 bits, not 256; 60 seconds is configurable.
  • Tokens, hashing: the plugin hashes by default (unkeyed SHA-256, base64url, of the unprefixed value); no adapter hashing is needed, except for the replay copy above.
  • Tokens, JWT fallback: not needed; disableJwtPlugin: true gives opaque tokens.
  • Revocation: reuse of a revoked refresh token (after the window, or one the client revoked itself) removes every refresh chain of the (user, client) pair, all of that user’s grants through the client, and leaves mcp_grants untouched; the Open item becomes whether to also revoke those grants. The revocation endpoint answers 400 to unknown tokens (RFC 7009: 200); the mount can map it. A client’s own revocation (Claude Code’s logout) removes tokens but not the grant, so “Connected apps” needs a rule for grants without tokens.
  • Consent: “the mount then passes the grant’s ID to the plugin as the consent’s reference” is done through postLogin.consentReferenceId reading an AsyncLocalStorage that the consent POST sets, and returning a fresh value elsewhere; the plugin’s consent endpoint must be reachable only through our POST. Mechanisms 2 and 3 can be dropped. The plugin lets a consent only narrow the client’s requested scopes.
  • CIMD: the 5 KB and 5-second limits are the plugin’s; the transport adds the SSRF rules and must turn redirect: "error" into manual. The cache is in memory per isolate; the 24-hour cap, the 5-minute failure cache, and the D1 rate limits per IP and host are ours to add (in the transport or isMetadataDocumentUrlAllowed). Refusing private-use redirect schemes needs validateRedirectUri.
  • Grant verification: GrantVerifier reads the access-token row’s revoked column, or the dashboard sign-out coupling is removed; the ADR says which.
  • Storage: one consent row per grant accumulates; the daily cron deletes those of revoked or expired grants.
  • Build order, S1: the adapter awaits Better Auth’s initialization in the request that creates the instance.
  • The spike: Claude Code over loopback is done; claude.ai and ChatGPT remain, behind the approval above.