Skip to content

0040. Sign-in with Better Auth on Workers and D1: email codes and Google, cookie sessions, and rate limits in D1

  • Status: Accepted
  • Date: 2026-11-18
  • Supersedes ADR 0025

ADR 0025 proposed Better Auth for dashboard sign-in and MCP OAuth, to become Accepted after a spike on Workers with D1 and on Node with Postgres, and a check of its OAuth plugin against the MCP authorization specification. Users, sessions, and the dashboard do not exist yet: the only credentials are cl_sk_ project keys and the cl_op_ operator token. apps/node does not exist either, so the Node and Postgres half of the spike cannot run against the real composition root.

The maintainer decided (2026-11-18): sign-in at launch is email one-time codes and Google; GitHub may come later, and passkeys later as the step-up for approvals. Approval stays by the mailed link only (ADR 0033).

A throwaway package ran Better Auth inside the repository’s test setup (@cloudflare/vitest-plugin, Miniflare, D1 migrations applied by applyD1Migrations) and under wrangler dev. It is not merged. Versions: better-auth 1.7.25 (with @better-auth/core and @better-auth/kysely-adapter 1.7.25, better-call 1.4.5, zod 4.6.7, jose 6.2.17), kysely 0.29.8, wrangler 4.158.0, workerd 1.20261104.1, @cloudflare/vitest-plugin 1.6.0, vitest 4.1.12, Node 24.12.0, compatibility date 2026-11-01. 29 tests passed.

Check Result
Email code: request, mail through a stub SystemMailer, verify, session Pass, in tests and under wrangler dev (the session cookie then authenticates a getSession call). Default storage of the code is plaintext; it must be configured (below). 3 wrong codes then the right one: TOO_MANY_ATTEMPTS; 10 concurrent wrong guesses then the right one: refused; after 5 minutes: OTP_EXPIRED. A refused system mail still answers { success: true }: Better Auth runs the send through runInBackgroundOrAwait, which catches the throw
D1 Pass both ways: the D1 binding passed as database (Better Auth’s built-in D1 dialect) and a Kysely instance over a small D1 dialect ({ db, type: "sqlite", transaction: false }). D1 has no interactive transactions; the code consumption is a single-row delete-and-return, so the attempt limit held without them
Migrations Generated with getMigrations(...).compileMigrations() from the configuration and checked in as one SQL file: users, sessions, accounts, verifications (our table names and snake_case columns through modelName and fields), three indexes, and our own auth_rate_limits
__Host- cookie Pass: __Host-cl_session=…; Max-Age=604800; Path=/; HttpOnly; Secure; SameSite=Lax, no Domain. advanced.useSecureCookies must stay off: it prefixes every name with __Secure-, giving __Secure-__Host-…. The OAuth state cookie is __Host-cl.state (5 minutes). Sign-out ends the session at once (no cookie cache)
CSRF Better Auth’s router accepts only application/json bodies (a form post answers 415), and refuses a cookie-carrying POST whose Origin is missing or not in trustedOrigins (403)
Google The authorization URL is Google’s, with redirect_uri {APP_ORIGIN}/api/auth/callback/google, a state, and PKCE S256. A forged state and a missing state cookie are refused (state_mismatch). With the token endpoint stubbed: a verified Google address links to the existing code user; email_verified: false neither links nor, with our hook, creates a user. By default Better Auth stores Google’s access and ID tokens in plaintext in accounts
Rate limits on D1 Pass with our customStorage: per IP, the 4th code request in a minute answers 429; per email across IPs, the 6th in 15 minutes; 8 concurrent requests from one IP let exactly 3 through. No IP address or email address in the table. Better Auth’s own database storage keys rows by ${ip}|${path} in plaintext, so it is not used
Bundle size The api Worker with Better Auth mounted: 2,750 KiB (gzip 480 KiB), from 1,504 KiB (gzip 257 KiB): +1,246 KiB (+223 KiB gzip). Every social provider is bundled. Cloudflare counts only the uncompressed size, limited to 64 MiB on both plans (limits page, checked 2026-11-18)
CPU time Not measurable locally on workerd; measured in Node 24 (same V8) on node:sqlite over 200 sign-ins: requesting a code median 0.4 ms (p95 1.3 ms), signing in median 0.8 ms (p95 3.1 ms); the first request of an instance about 29 ms and 9 ms (initialization). wrangler dev wall times: 13 to 33 ms per request with local D1
Session refresh getSession with query: { disableRefresh: true } never extends a session: with only such reads, the cookie is refused on day 8. Reading get-session daily through the auth routes returns a renewed __Host-cl_session with a fresh Max-Age, and a model browser that drops expired cookies still holds a working one on day 8 (fake clock)
Logs With the configuration below, no code, email address, or IP address appeared in any console call or Better Auth logger call, through a wrong code, a malformed request, an unknown route, a refused mail, and a success. Unconfigured, better-call prints any non-API error with console.error("# SERVER_ERROR: ", error), and Better Auth’s email-and-password sign-up logs the address of an existing account
Runtime Better Auth loads AsyncLocalStorage from node:async_hooks. Under wrangler dev at compatibility date 2026-11-01 it loaded without nodejs_compat; the vitest plugin enables nodejs_compat itself, so the tests do not show it

Not covered: a real Google round trip, the deployed Worker’s CPU time and compatibility flags, Node with Postgres, and the OAuth provider plugin for MCP.

  • Use Better Auth, pinned to an exact version, for dashboard sign-in and sessions. MCP OAuth is not part of this decision (below).

  • It lives in a new package, adapters/auth-better-auth, the only package that imports better-auth (enforced by dependency-cruiser). It is given a Kysely instance and its dialect type, the SystemMailer port, the auth secret, the app origin, the Google client, the self-hosted allowlists, and a rate-limit store. It exports the mount for /api/auth/* and an implementation of a new core port:

    interface SessionVerifier {
    /**
    * The signed-in user of a request's `Cookie` header, or null. On a self-hosted
    * installation it also revokes the sessions of a user whose address left the allowlist.
    */
    verify(cookieHeader: string | undefined): Promise<{ userId: string } | null>;
    }

    The adapter never mints a scope. How core/auth turns the user into a scope is ADR 0041, which is Proposed; until it is accepted and built, no api action accepts a session.

  • On Cloudflare, adapters/cloudflare provides the Kysely dialect over the CONTROL_DB binding (no interactive transactions), and apps/workers wires it. Passing a Kysely instance, not the binding, is what lets apps/node pass Postgres the same way.

  • Its tables are in the control plane: users, sessions, accounts, verifications, generated from the configuration by Better Auth’s getMigrations and checked in as a numbered migration in adapters/cloudflare/migrations/control, plus auth_rate_limits. A Better Auth upgrade regenerates the schema and adds a migration when it changes.

  • The columns of users that core and other tables rely on, id, email, and email_verified, are a stable contract: a Better Auth upgrade or the fallback keeps them, and a test reads them through ControlStore.

  • apps/workers sets the nodejs_als compatibility flag explicitly. Better Auth needs AsyncLocalStorage; the spike’s probe under wrangler dev found it without a flag at compatibility date 2026-11-01, but the flag removes the doubt for the deployed Worker at the cost of nothing else.

  • The mount forwards only these routes to Better Auth and answers 404 to every other path under /api/auth/, so Better Auth’s other endpoints (email and password, account and session management, user update and deletion, the server-only OTP endpoints) cannot be reached whatever its configuration. A hand-written route table in the adapter is the list; a test checks the mount against it and that every Better Auth endpoint outside it answers 404.

    Route Purpose
    POST /api/auth/email-otp/send-verification-otp request a code
    POST /api/auth/sign-in/email-otp sign in with the code
    POST /api/auth/sign-in/social start Google
    GET /api/auth/callback/google Google’s callback
    GET /api/auth/get-session read the session (and extend it, below)
    POST /api/auth/sign-out sign out
    POST /api/auth/bootstrap the first-boot path (self-hosted, below)
  • surfaces/api-client gets a hand-written auth module next to the generated client, with requestCode, verifyCode, startGoogle, getSession, and signOut; the bootstrap route is called by the operator once, not through it. It names no Better Auth type or package and pins the route contract above, which the fallback must keep. The dashboard uses only it (with fetch), not better-auth/client.

  • The mount removes every token key, at any depth, from every response it forwards, errors included. Better Auth returns the session token in the sign-in body and as session.token in the session read; no response may carry a credential the client did not create (ADR 0007). A test walks every forwarded route.

  • The auth routes are not registry actions. Like endpoint actions they are HTTP-only and exempt from REST and MCP parity (ADR 0005, ADR 0019); the route table above is their single list, and the isolation fixture covers them: a session of one workspace’s user reaches no other workspace’s data through them, and the bootstrap route creates nothing once a user exists.

  • Email one-time codes (the emailOTP plugin, sign-in type only): 6 digits, valid 5 minutes, 3 attempts. The code is stored as an HMAC-SHA-256 keyed by the auth secret (storeOTP: { hash }); Better Auth’s "hashed" option is an unkeyed SHA-256, which a 6-digit code does not survive. Verification identifiers, which contain the address, are stored the same way (verification.storeIdentifier). The first sign-in of an address creates the user, with the address verified. Codes are mailed through SystemMailer (ADR 0029); the mail holds the code and fixed text only.
  • The code request answers the same whatever happens: a refused or unknown mail outcome is logged by code and alerted through SystemMailer’s failure handling, and the dashboard offers to send another code. This is Better Auth’s behaviour, and it also means the answer reveals nothing about the address.
  • Google (the google social provider, prompt: select_account): the callback is {APP_ORIGIN}/api/auth/callback/google; state is held in verifications and bound to the __Host-cl.state cookie; PKCE S256. Google is linked to an existing user only when Google reports email_verified and the existing address is verified (trustedProviders empty, Better Auth’s requireLocalEmailVerified default). A Google address that is not verified creates no user. Google’s tokens are never kept: database hooks clear them on account creation and on account update (the re-link path), since we call no Google API (ADR 0021); a test covers both.
  • Managed service: the abuse-screening extension point runs when a user is created (from ADR 0025).
  • Later: GitHub as a second provider, and passkeys as the fresh-presence step-up that ADR 0033 leaves open. SSO stays after launch.
  • The session cookie is __Host-cl_session: Secure, HttpOnly, SameSite=Lax, Path=/, no Domain. Better Auth’s other cookies are named __Host-cl.* with the same attributes. useSecureCookies is off and Secure is set by the attributes, because that option would prefix the __Host- names.
  • Sessions last 7 days and roll (expiresIn 7 days, updateAge 1 day). Sessions are rows checked on every request (no cookie cache), so sign-out and revocation take effect at once. Session rows store no IP address and no user agent.
  • Only the auth routes extend a session. SessionVerifier reads the session with getSession({ query: { disableRefresh: true } }), because an extension there would write a new expiry whose Set-Cookie an api response cannot carry, and the browser’s cookie would still expire after 7 days. The dashboard’s session read through GET /api/auth/get-session, on load, on focus, and at least hourly while open, is what extends the session and its cookie. A fake-clock test signs in, then for 8 days loads the dashboard and calls api actions daily, and the cookie is still accepted on day 8. It asserts that the session read returns a renewed __Host-cl_session Set-Cookie with a fresh Max-Age, and it models the browser: a cookie is dropped once its own Max-Age has passed, so the test fails if only the session row is extended.
  • sessions.token is stored as Better Auth writes it, in plaintext. The cookie holds the token with an HMAC signature by the auth secret, so reading the table alone does not give a usable cookie. This holds only while Better Auth’s bearer plugin is never enabled, since it accepts the bare token; the fallback below stores hashes instead.
  • CSRF: a cookie-authenticated request that is not a GET is accepted only with a JSON body and an Origin equal to APP_ORIGIN. Better Auth enforces this on its routes (JSON-only router and trustedOrigins: [APP_ORIGIN]); surfaces/http enforces the same rule for api actions authenticated by session. A test generated from the registry sends every non-GET api action with a session cookie: a foreign or missing Origin answers 403, and a form body answers 415. GET api actions change nothing. /mcp never accepts the session cookie.
  • A request with an Authorization header is authenticated by it alone; its cookies are ignored, and a bad key never falls back to the session.
  • Better Auth’s limiter runs with our customStorage: one atomic INSERT … ON CONFLICT DO UPDATE … RETURNING per check on auth_rate_limits(key_hash, window_start, count, expires_at), a fixed window, with the key stored as an HMAC of Better Auth’s ${ip}|${path} key. No IP address is stored.
  • Per IP: Better Auth’s rules (3 code requests and 3 code sign-ins per minute, 3 Google starts per 10 seconds, 100 requests per minute on the other auth routes).
  • The client IP comes from cf-connecting-ip on Workers; a container installation names its proxy’s header in CLIENT_IP_HEADER. The mount, before Better Auth, refuses an auth request without a usable client IP with a configuration error naming that variable, so no request falls into Better Auth’s single shared bucket, where one client could block every sign-in. A test covers it.
  • Per email, keyed by an HMAC of the address, checked in a before hook and stored in the same table: 5 code requests and 5 code sign-ins per 15 minutes, and at most 10 code requests and 15 code sign-ins per day. With 3 attempts per code, one address can be guessed at most 15 times a day, about 1 in 67,000 per day against a 6-digit code.
  • D1 suits the launch volume (one or two writes per auth request). If it becomes hot, the store moves to the rate-limiter Durable Object behind the same customStorage interface; on Postgres it is the same table.
  • A daily cron deletes expired rows of sessions, verifications, and auth_rate_limits.
  • BETTER_AUTH_SECRET signs the cookies and keys three HMACs, each with its own purpose prefix (otp:, identifier:, rl:), so no value of one purpose can stand for another.
  • Rotating it signs every user out, invalidates codes in flight, and resets the rate limits. Rotation is therefore rare and announced, and the deploy that rotates it is the only step.
  • Better Auth’s logger is replaced by one that maps only warn and error to logError, with the level and a fixed code, never its message or arguments (ADR 0032); info and debug are dropped. logError’s redaction does not mask 6-digit codes, so no free text from the library is logged.
  • onAPIError.throw is set, so an unexpected error leaves the handler instead of being printed by better-call; the mount logs a fixed message with the error’s name only, and answers 500.
  • A test like the spike’s stays in the suite: a whole sign-in, failures included, writes no code, address, or IP address to any log.
  • Sign-in is open only on the managed service (with abuse screening). A self-hosted installation lets in only the addresses of ALLOWED_EMAILS ∪ ADMIN_EMAILS. A code request for another address answers success and mails nothing. The list is checked on every sign-in, by a session.create hook, not only when a user is created. With neither variable set, every auth route, bootstrap included, refuses with a configuration error naming both.
  • An address removed from the list loses its sessions: SessionVerifier and the session read check the list, delete the sessions of a user it no longer allows, and answer as signed out, on that user’s next request. A test covers it.
  • ADMIN_EMAILS also names the approvers and owners of a self-hosted installation; what that means for memberships is in ADR 0041. The cloud mode refuses the variable, as today.
  • BOOTSTRAP_TOKEN, the first-boot path before mail is configured: a cl_boot_ token of at least 32 random characters, set by the operator. POST /api/auth/bootstrap with { "token", "email" } (JSON, same-origin, rate limited per IP) is an endpoint of our own small Better Auth plugin. It compares the token in constant time and requires the address to be in the list above. It then writes the user with one statement, INSERT INTO users … SELECT … WHERE NOT EXISTS (SELECT 1 FROM users), with the address marked verified; D1 runs it atomically, without an interactive transaction. If the statement inserted a row, the endpoint creates the session through Better Auth’s internal adapter and sets the cookie with Better Auth’s setSessionCookie, as its own sign-in endpoints do. A wrong token, a refused address, no inserted row, or an existing user all answer the same 404. The statement fills every column Better Auth requires of users, and the user-creation hooks that the statement bypasses (the ADMIN_EMAILS memberships of ADR 0041) are called by the endpoint itself. It creates no workspace: the user creates one next, as any user does (ADR 0041). A test sends two concurrent requests and exactly one user and one session result. The operator removes the variable afterwards. cl_boot_ joins CREDENTIAL_PREFIXES, so log redaction masks it. The cloud mode refuses the variable.

Amendment (2026-11-19, ADR 0041, Accepted): there is no owner role. ADMIN_EMAILS users are admin of every workspace through membership rows, and approve as admins. Where this ADR says owners, read admins; under “What stays open”, ADR 0041’s last-owner rule is its last-admin rule.

Amendment (2026-11-20, ADR 0041’s installation admins): their memberships are written by a step that runs at every sign-in, after the list check and before the session is written, from the session.create hook. The bootstrap route creates its session through the same hook, so it calls nothing more itself; when it removes its user after a failed session, it first undoes that step.

If Better Auth stops working on either target (a later version breaks workerd or D1, or the Node and Postgres check fails), it is replaced by a small in-house auth adapter. It keeps the same SessionVerifier port, the routes of the table above and the auth module of surfaces/api-client, the users contract, the cookie name, and the rate-limit store. It provides email codes with an HMAC, 5 minutes and 3 attempts; Google through the authorization code flow with PKCE over fetch and WebCrypto, linking only on email_verified; and random session tokens stored as hashes. The switch needs a migration of the session, account, and verification tables, and signs everyone out. MCP OAuth would then be deferred and MCP keeps project keys.

  • Node and Postgres: deferred until before the open-source release, because apps/node does not exist. The check runs the same tests on Node with a Kysely Postgres dialect, before the first public release that offers container self-hosting. The conditional statements that rely on D1’s single writer (the bootstrap insert, and ADR 0041’s last-owner rule) need a row lock or SERIALIZABLE on Postgres.
  • MCP OAuth: the intended path is Better Auth’s @better-auth/oauth-provider plugin (published at 1.7.25). It needs its own spike against the MCP authorization specification (RFC 8707 resource indicators, RFC 9728 protected resource metadata, dynamic client registration or client metadata documents, rate-limited registration) before MCP OAuth is built. Until then MCP authenticates with project keys (ADR 0031). The grant model stays as ADR 0026 decides.
  • ADR 0025 is superseded; its methods, cookie sessions, CSRF rule, allowlists, first-boot path, SystemMailer delivery, and isolation-fixture coverage carry over, made concrete here.
  • ADR 0018’s rule table gains adapters/auth-better-auth among the adapters that import only core and adapters/webcrypto, and among the adapters that run on both targets. Unlike adapters/email-ses and adapters/webcrypto, its dependency also uses AsyncLocalStorage from node:async_hooks, which both targets provide; its own code imports no node:* or cloudflare:* module. apps/workers may import it. ADR 0018 carries an amendment line, and .dependency-cruiser.cjs carries the new layer and the better-auth-only-in-its-adapter rule from this change on.
  • ADR 0028 carries an amendment line: surfaces/api-client has a hand-written auth module beside the generated client.
  • The deploy gate of the change that builds sign-in checks what the spike could not:
    • the CPU time of a sign-in on a deployed Worker;
    • that the __Host- cookies work on http://localhost in Safari during development, which may need a development origin over HTTPS;
    • that the logger mapping passes only warn and error.
  • The Google OAuth client is created by the maintainer in Google Cloud: a Web application client with the authorized redirect URI {APP_ORIGIN}/api/auth/callback/google per environment, its ID and secret as platform secrets (GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET), and the consent screen published for external users with the openid, email, and profile scopes. The auth secret (BETTER_AUTH_SECRET) is a platform secret too.
  • A callback that refuses an unverified Google address answers a JSON 403 from Better Auth’s hook; the mount turns refused callbacks into a redirect to a dashboard error page.
  • The tests named above, and those of the spike’s table, become the adapter’s tests.
  • Better Auth ships patches often; upgrades are pinned bumps that rerun these tests and regenerate the schema.

Amendment (2026-11-18, when the adapter was built): the adapter’s tests run on workerd and the control plane’s D1 through adapters/cloudflare’s Kysely dialect, as the spike did, so .dependency-cruiser.cjs lets adapters/auth-better-auth/test/ import cloudflare:*; its src imports none. On the managed service, sign-in fails closed until the abuse screening of user creation exists: it lets in only the addresses of ALLOWED_EMAILS, or any address with an explicit SIGN_IN_OPEN=true, and with neither every auth route refuses with a configuration error naming both. The default changes from “unset, open” to “unset, closed”. SIGN_IN_OPEN is refused with ALLOWED_EMAILS, and on a self-hosted installation.

Amendment (2026-11-18, after the adapter’s review): the per-address limits count every address, listed or not, and an address off the list takes the same path as a listed one, except that no mail is sent. The answers therefore do not reveal the list. With the code mail run after the response (runInBackground, which is waitUntil on Workers), neither does their timing. Two trade-offs are accepted. First, anyone who knows an address can spend its limits: 5 code requests and 5 code sign-ins per 15 minutes, and 10 and 15 a day. That locks its owner out of code sign-in for up to a day, though Google sign-in stays open to them. Second, while sign-in is open, anyone can have up to 10 code mails a day sent to any address from the system sender. The per-IP limits bound both, and the abuse screening of user creation is where to do better.

Amendment (2026-11-20, pending ADR 0051, Proposed): MCP OAuth, deferred here, is decided for the first release with Better Auth’s mcp() and cimd() plugins after their own spike. The mount’s route table gains the OAuth routes, behind MCP_OAUTH; the token and revocation routes accept form bodies and read no cookie.