Auth reference

The surface. Using Auth is the same ground with the code you write around it.

Config options

OptionDefaultMeaning
basePath/authWhere the handler mounts. Must match the OAuth redirect URIs you register
baseURLPUBLIC_ORIGINThis Worker’s public origin. Callbacks, the key set and magic-link URLs are built from it. A dev composition ignores it and serves on whatever host the request arrived at
disableSignUpfalseWhen true, sign-in never provisions a new user. An unknown address gets no email at all — replying no such account is an enumeration oracle
trustedOrigins—Every web origin and mobile deep-link scheme allowed as a redirect target and CSRF origin. Prefix match
google, apple, github, facebook, microsoftoff{ enabled: true } per provider
plugins[]Additional Better Auth plugins, composed after the fixed four
sessionSecretRotateEveryDaysunsetHow often, in days, the secrets manager rotates auth-session-secret by itself. Unset, nothing rotates it unattended. Nobody is signed out: the previous version keeps verifying for the session lifetime, and is retired once the JWKS keys sealed under it are re-encrypted. Must be longer than sessionExpiresIn, and is refused beside twoFactor()
retention.purgeAfterDays30How many days a soft-deleted account waits before the purge erases its data. Inside the window it cannot sign in and can be restored
retention.restoreUrlunsetAn http(s) page of yours that the deletion-scheduled mail’s restore button links to. Unset, the mail has no button and says to reply before the purge date
lifecycleEmailsall trueaccountSuspended, accountReinstated, deletionScheduled, deletionComplete. Set one to false to stop sending it
attestationno environmentsNative app attestation on the two send routes, per environment: environments.<env> with mode (enforce or test), and the ios and android apps allowed to attest; challengeExpiresIn, 300 seconds by default, 600 at most. Apple App Attest and Google Play Integrity are verified, and the test assertion in a test environment. An android app needs auth-play-integrity-service-account. Native app attestation
resolveScopesnoneA function, beside the config, that fills c.var.auth.scopes on every authenticated request. With none, every scope gate refuses every caller. Server-authoritative writes
onUserSuspended, onUserReinstated, onUserDeleted, onUserRestored, onUserPurgednoneFunctions, beside the config, each called once per transition with the event, the D1 binding and runtime: { env, waitUntil? }. env is typed as your own when you call auth<Env>(); waitUntil is absent when the hook fires from the purge Workflow. onUserRestored fires when a deleted account is restored inside its window, to undo what onUserDeleted did. A hook that throws is logged and changes nothing. Suspended and deleted accounts
onSessionRevokednoneA function, beside the config, called when a session row is deleted — a sign-out, a revoke, an admin ending somebody’s devices — with { id, userId }, the D1 binding and the same runtime

retention.purgeAfterDays is the default a Worker’s policy can replace. When the retention block in the Worker’s pithy.config.ts names purgeWindows.user, that window wins, and the manifest and pithy doctor say which one is in force. The same block’s classAges deletes an account left inactive too long: retention and legal holds.

Dev needs neither baseURL nor trustedOrigins: it resolves its own address and trusts its own origin, because local dev has no TLS and its port is assigned per run.

Bindings

BindingTypeWritten byWhat it is
DBd1pithy addWhere the tables live
AUTH_RATE_LIMITERratelimitpithy addThe edge guard on every auth route
AUTH_PURGEworkflowYouThe purge of one deleted account. Its class, AuthPurgeWorkflow, is exported from your Worker’s entry
AUTH_PURGE_DUEworkflowYouThe daily pass that starts every due purge, on the cron 0 2 * * *. Its class is AuthPurgeDueWorkflow

The rate limiter is written at 100 requests per 60 seconds, per client IP — a flood guard rather than a product rule. Cloudflare accepts a period of 10 or 60 and nothing else.

The two purge Workflows are yours to bind, because only the Worker that composes auth can run every capability’s purge contribution. pithy worker sync leaves the entries and the cron where you wrote them, and pithy doctor and pithy deploy do not count them against your app’s own Workflows. Unbound, a deletion still shuts the account and nothing is erased. The purge has the five lines each class takes.

Secrets

SecretOriginRotation
auth-session-secretMinted. Any random string workslocal
auth-google-credentialsGoogle Cloud Consolemanual
auth-apple-credentialsThe Apple Developer portalmanual
auth-github-credentialsGitHub developer settingsmanual
auth-facebook-credentialsThe Meta app dashboardmanual
auth-microsoft-credentialsThe Microsoft Entra admin centermanual
auth-play-integrity-service-accountGoogle Cloud Console, a service account’s JSON keymanual

Each provider credential is a typed JSON secret holding both halves together. Apple’s carries a third, optional field for the native flow’s audience, and its client secret expires within six months by construction. Microsoft’s carries a third, required field, tenantId, which decides who may sign in; an empty one is refused when it is stored. Add Microsoft sign-in has the values.

auth-play-integrity-service-account is the Google Cloud service account the Worker decodes Play Integrity tokens with, the JSON key file stored whole. Its private_key spans many lines, so pithy secrets asks for the file as one document. It applies only once some environment lists an android app; until then pithy secrets ls leaves it out and pithy doctor does not ask for it. The service account has the steps.

The session secret is written only when absent — a new value from update or pithy secrets rotate signs out every live session. An unattended rotation, turned on with sessionSecretRotateEveryDays, does not: a cookie or bearer token signed under the previous version is re-signed under the new one on its next request, and the previous version is kept for the session lifetime. Unattended rotation has the rest.

auth-caller-token-key is there only when you spread callerTokenRegistry into the project registry, for a backend that signs caller tokens. It is obtained, rotated manual: your backend holds the same value, so the kit never makes one.

Tables

All pithy_auth_*, all run by migrate:

users · sessions · accounts · verifications · jwks · rate_limit · devices · rotated_tokens · user_lifecycle · verification_outcomes · attestation_challenges · app_attest_keys

The first six are Better Auth’s. devices, rotated_tokens, user_lifecycle, verification_outcomes, attestation_challenges and app_attest_keys are Pithy’s own. rotated_tokens is the refresh-token reuse ledger. user_lifecycle is every suspension, reinstatement, deletion, restore and purge, with its actor and reason, and it has no foreign key to the user, so it outlives a purge. verification_outcomes is the verification ledger. attestation_challenges holds each outstanding attestation challenge as its SHA-256 only, and app_attest_keys each registered App Attest key: its id, public key, App ID, Apple environment and the counter of its last accepted assertion. A key belongs to an install of the app and names no person. Nothing writes to either unless an environment has an attestation block. A composed plugin adds its own under its own names, unprefixed.

Verification strategies

This is the only capability that implements bearer and session. Every other capability gates with the shared middleware and reads identity off the seam.

It also contributes a control-plane surface, which is a different thing entirely.

The management routes

Every one is control-plane and default-denied. They are shaped like every other route in the kit.

MethodPathScope
GET/auth/admin/usersauth:users:read
POST/auth/admin/users/searchauth:users:read
GET/auth/admin/users/:userIdauth:users:read
GET/auth/admin/devicesauth:devices:read
POST/auth/admin/sessions/revokeauth:sessions:revoke
POST/auth/admin/users/:userId/sessions/revokeauth:users:logout
POST/auth/admin/users/:userId/devices/revokeauth:devices:revoke
POST/auth/admin/users/:userId/suspendauth:users:suspend
POST/auth/admin/users/:userId/reinstateauth:users:suspend
DELETE/auth/admin/users/:userIdauth:users:delete
POST/auth/admin/users/:userId/restoreauth:users:delete
POST/auth/admin/users/:userId/exportauth:users:export
GET/auth/admin/verificationsauth:verifications:read

The user listing narrows on the server. GET /auth/admin/users takes state (active, suspended or deleted, judged as enforcement judges it, so a suspension past its end is active), verified (true or false), and a signup window: since, inclusive, and until, exclusive, both ISO-8601. A window that does not start before it ends is refused, and so is any value outside those. The query is strict and takes no search: a ?search= is validation/invalid_input (400), never every user as though they matched.

A search goes in a body. POST /auth/admin/users/search takes { search, state?, verified?, since?, until?, cursor?, limit? }: search is matched against email and display name, up to 200 characters, with % and _ matched as themselves, and the rest are the listing’s filters, verified as a JSON boolean. It pages on the same cursor, passed back in the body, and null reads as a first page. A search term is usually somebody’s address, and a query string is written to every request log between the client and the Worker. The route is a read, declared readInBody: true, so it shares auth:users:read with the listing and the default grant still holds it.

A scope per operation, not one admin flag. Reading a user is a privacy operation; revoking their sessions is an availability one. A support tool that looks people up should never be able to sign the customer base out, and an incident-response tool that kills a stolen session has no business reading every address in the user table.

The lifecycle routes each take a required reason, in the body, and every call is recorded with it. A suspension revokes every session the user holds; a reinstatement restores none. A deletion is soft unless the body names mode: "hard", and a soft one can be restored until its window closes. The export is POST …/export with { reason }, a read declared readInBody: true, and answers one document with every composed capability’s part, and no credential. Suspended and deleted accounts has the bodies and the responses. A person deletes their own account with DELETE /auth/account, outside the control plane, on their own session.

Scope matching is exact — no prefix rule — so a broader-sounding string grants none of them.

Every call is audited, reads included, under the control-plane actor kind.

The verification ledger

Every sign-in link and one-time code auth sends is recorded in pithy_auth_verification_outcomes: its type, magic_link or otp, the verification it carries, the account it signs in to, the pithy_email_jobs id of the mail that carried it, and when it was issued, expires and was used. Never the token, and never the address. Better Auth deletes a verification on its first use, so without the ledger a used link leaves nothing behind and an unused one looks like one still waiting.

A sign-up has no account when its link is sent, so its row joins its mail by the job id from the start and gains the account when the link is used. The row is written once the email seam answers: a withheld mail is recorded with its suppressed job, and one the seam failed to queue with no job at all. It is stamped used when the link or code opens a session.

GET /auth/admin/verifications?since=…&until=…&type=…&state=…&cursor=…&limit=…

Every parameter is optional. since and until bound the issue time, ISO-8601, and default to the 30 days ending now; a window that does not start before it ends is refused. The response carries the window it covered, counts, and a page of verifications, newest first, with nextCursor. counts has one entry per type, zeros included, with issued, used, expired and pending, and the last three add up to issued. It always covers the whole window and every type and state, whatever type and state narrow the rows to. A row’s state is judged at the moment of the read, so an unused link becomes expired the moment its expiry passes, with nothing written.

Join emailJobId to the email capability’s job and suppression reads to see which sign-ins failed because the mail never landed. The purge erases an account’s rows with the rest of it, and the export carries them as verifications. Each read is audited as auth/admin_verifications_listed, with the window and how many rows it returned.

The route is a GET, so pithy dashboard connect offers auth:verifications:read by default. A connection made before it existed does not hold it: add it with --update, naming every scope the connection already holds beside it, or with --update --scope all.

Rate limiting

Two limiters, two jobs.

Tier 1 is Cloudflare’s native limiter, per client IP, at the edge, with no storage round-trip. It runs in front of every auth route and blunts floods and credential-stuffing before they reach anything else.

Tier 2 is Better Auth’s own, database-backed, keyed per action and identity — the send-rate caps on magic link and one-time code. Database-backed because in-memory limiting is per-isolate on Workers and therefore useless.

Native app attestation

With an attestation block for the environment, the two send routes take an attestation in the x-pithy-attestation header in place of a Turnstile token. A request carrying one is judged by it alone, and a failure never falls through to Turnstile. A request without one goes to Turnstile when it is composed, and is refused with auth/attestation_missing when it is not.

MethodPathStrategy
POST/auth/attestation/challengepublic. Answers { challenge, expiresAt }: single use, five minutes by default. Mounted only when some environment has a block
POST/auth/attestation/ios/keyspublic. Registers an App Attest key once, from { challenge, keyId, attestation }, and answers { keyId, registeredAt }. Mounted only when some environment has a block

An iOS app registers each App Attest key once: auth checks Apple’s certificate chain against the App Attestation root pinned in the package, the App ID against the environment’s ios apps, and the key’s Apple environment, then stores the key. Each send after that carries an assertion by the key, and auth verifies its signature and requires its counter to rise. An Android app sends a Play Integrity token whose requestHash is the unpadded base64url of the binding; the Worker decodes it through Google with auth-play-integrity-service-account, and requires the package, PLAY_RECOGNIZED, MEETS_DEVICE_INTEGRITY and a fresh timestamp. The refusals are auth/attestation_missing (400), auth/attestation_failed (403, with the failed check at the start of detail) and auth/attestation_config (500, which includes a missing service account or Google refusing it). Google unreachable, or answering 429 or a 5xx, is core/upstream_failed. Test mode accepts the test assertion pithy-test-attestation, and only where the Worker’s ENVIRONMENT is dev, staging or feature. Native app attestation has the config, the wire format and the flow.

Device headers

HeaderMeaning
x-pithy-device-idA client-generated stable id, at most 128 characters. The only required one: without it, nothing is registered
x-pithy-platformios, android or web. web when absent on a first registration
x-pithy-device-nameA human label
x-pithy-device-modelThe hardware model
x-pithy-os-versionThe operating system’s version
x-pithy-app-versionThe app’s version
x-pithy-push-tokenThe push token

Peer capabilities

Required: secrets, email.

Optional: turnstile — auto-gates the magic-link and one-time-code send routes with zero config; a request carrying a native app attestation is judged by that instead. audit — records sign-in, token refresh and device revocation, and with mcp() composed every agent grant and tool call.

Suspended and deleted accounts

A suspended or deleted account is refused at every request, sign-in and token refresh. Auth’s own routes answer auth/account_suspended or auth/account_deleted, both 403. Suspended and deleted accounts has the states, the screens, the mail and the purge contribution.

Agents acting as a user

mcp({ floor }), exported from @pithy-sh/auth beside auth(), gives the Worker an MCP endpoint of its own: Better Auth’s OAuth provider composed into this instance, a consent screen, and every route that opts in as a tool, called as the person who approved the agent. It refuses to compose without auth(), with a different database, or beside an OAuth provider already in plugins. A grant, a refusal and a revocation are audited as auth/mcp_grant_approved, auth/mcp_grant_denied and auth/mcp_grant_revoked, and every tool call as mcp/tool_call, under the person with actorKind: "agent". Letting your users’ agents in has the config, the floor, the flow and what the tool-call event records.

What is not here

Refusals carry an auth/ error code rather than a sentence a client has to parse.

No password. Ever.

No impersonation. No route mints a session and no read projects a session token.

No roles or permissions. Auth answers who is this.

ESC