Authentication
Configure and extend Better Auth without creating a second session authority.
Better Auth 1.6 is the only authentication and session implementation. The pre-release schema has
one canonical identity, users.id; domain and wire code may call it user_id, but there is no
second stored application-user key.
Included flows
| Flow | Contract |
|---|---|
| Email/password signup | 8–128 characters, Bun password hashing, verification required, no immediate auto sign-in |
| Email verification | sent on signup/sign-in, successful verification signs the user in |
| Password sign-in | only a valid verified identity receives a session |
| Password reset | reset email through the typed mailer; successful reset revokes existing sessions |
| Magic link | 15-minute expiry, token stored hashed, successful token is single-use |
| Google OAuth | enabled only when both server credentials exist; missing config fails closed |
| Account linking | explicit linking only; implicit email-based linking is disabled |
| Session | secure Better Auth cookie, 7-day expiry, 1-day update age |
| Sign-out | Better Auth session revocation plus browser query/client-state clearing |
| Native clients | the same Better Auth session, carried by the Expo integration; see below |
Google is the only included social provider. Adding providers to match a competitor is not a release requirement.
Narrowing these flows is not a configuration flag. emailAndPassword.enabled gates the email
sign-in and sign-up endpoints only; password reset and verification email are gated on their
callbacks, and the magic-link plugin is independent of it. Read
Narrowing authentication to social providers
before turning email authentication off.
Request path
The Hono app mounts Better Auth directly:
browser authClient
→ /auth/*
→ Better Auth handler
→ Better Auth tables in PostgresProtected product routes use:
HttpOnly session cookie
→ sessionAuth
→ auth.api.getSession(headers)
→ c.var.user_id = session.user.id
→ ownership-scoped repository queryThe browser uses credentials: 'include' for both Better Auth and the typed Hono RPC client. It
does not store an access token in local storage. Do not add custom access/refresh JWTs, a second
cookie, a second password implementation, or another session table. A native client reaches the same
handler and the same session; see Native clients.
Database ownership
dbmate owns these Better Auth-compatible tables:
users;auth_sessions;auth_accounts;auth_verifications;auth_rate_limits.
Better Auth uses its supported pg adapter while application repositories use bun:sql. Better
Auth CLI output may be inspected to discover a schema change, but the reviewed change must become a
dbmate migration. Never run a second migration authority against a buyer database.
Sessions and accounts reference users.id with cascading database deletes. The application
soft-deletes the user, then removes live sessions and reusable account credentials transactionally.
Authorization contract
Authentication proves identity; it does not prove resource ownership, role, or billing entitlement.
For a private resource:
- mount
sessionAuth; - read identity only through
requireUserId(c); - pass that ID into service and repository methods;
- include the ownership predicate in the read/write SQL;
- use a non-disclosing 404 for absent and wrong-owner private records;
- apply billing entitlement separately when the feature requires it.
Do not accept a user_id, owner ID, role, or entitlement from request input. Consult the optional
Add an authenticated route playbook for a maintained
implementation and verification route.
Email behavior
Verification, reset, and magic-link callbacks use the typed mailer. In development/test without
Resend, the complete message and action URL are logged so the flow is deterministic. In production,
RESEND_API_KEY is required and the log fallback cannot start.
Treat local logs as sensitive: they contain short-lived authentication URLs. Do not send console breadcrumbs to error monitoring, publish logs, or enable the fallback in a shared/production environment.
Origins, cookies, and proxy IPs
FRONTEND_URL, optional MARKETING_SITE_URL, and CORS_ORIGIN define trusted browser origins.
Hono permits credentials only for that configured set. Better Auth uses the same trusted origins.
When AUTH_CROSS_SITE_COOKIES=true, unsafe product requests also require an exact Origin or
Referer origin from that set. Better Auth, signed webhooks, public marketing forms, and the Sentry
tunnel keep their own non-browser authentication boundaries.
Set TRUSTED_PROXY_PROFILE to direct, railway, aws-alb, or gcp-cloud-run. The Bun boundary
ignores forwarding headers in direct mode. For managed ingress profiles it requires peer metadata
before accepting the provider's expected forwarding shape and overwrites the internal client-IP
header. Prevent direct access around the selected ingress.
Better Auth and application endpoint rate limits are database-backed. Atomic fixed-window updates share each application budget across replicas.
Native clients
The mobile edition is one Expo client on this API, accepted through
docs/decisions/0005-mobile-edition-expo-client-on-the-existing-backend.md. It uses Better Auth's
first-party Expo integration, not a token layer of its own: @better-auth/expo is pinned to the
same 1.6.x version as better-auth, and its expo() server plugin is registered in
apps/server/src/lib/auth.ts.
A native session is a Better Auth session. There is one token format, one 7-day expiry, one
revocation path, and one auth_sessions row, and sessionAuth resolves a native caller through the
same auth.api.getSession(headers) call as a browser caller.
Application scheme and trusted origins
MOBILE_APP_SCHEME declares the URI scheme the mobile application registers, without the ://. It
is validated as a URI scheme and defaults to the neutral app rather than the product brand,
because the scaffold's brand rewrite cannot turn an arbitrary display name into a valid scheme. A
deployment that ships a mobile client must set it to that client's real scheme, and the Expo
application's scheme must be the same value.
The server derives trusted native origins from it and appends them to Better Auth's trusted origins, next to the browser origins:
| Origin | Trusted in | Purpose |
|---|---|---|
<scheme>:// | every environment | the released application |
<scheme>-dev:// | development, test | the dev-client build variant |
exp:// | development only | Expo Go |
Native origins are deliberately not added to CORS_ORIGIN. They are not browser origins, and the
Hono CORS allowlist stays browser-only.
Session hand-off
native client
→ POST /auth/sign-in/magic-link { callbackURL: "<scheme>://..." }
→ emailed link opens in the device browser
→ GET /auth/magic-link/verify
→ 302 to "<scheme>://...?cookie=<Set-Cookie>"
→ operating system opens the application
→ client stores the value in expo-secure-store
→ subsequent requests send it as a normal Cookie headerThe expo plugin appends the Set-Cookie value to the redirect only when the redirect target is a
non-http origin that is already trusted, so an unlisted scheme receives no session. Better Auth
validates callbackURL, newUserCallbackURL, errorCallbackURL, and redirectTo against the same
list: a magic link for an untrusted scheme is refused with INVALID_CALLBACK_URL before any email
is sent, and a link whose callback was rewritten afterwards is refused at verification without
setting a cookie.
advanced.disableOriginCheck: false is set explicitly. Better Auth otherwise skips redirect and
origin validation whenever NODE_ENV=test, which would leave that boundary unproven by this
repository's own suite. Do not remove it to make a test pass.
CORS and the origin check
A React Native client is not subject to CORS, so the browser allowlist is not what admits it. It
sets the Cookie header directly and adds expo-origin, which the expo plugin uses as the request
origin when no browser Origin header is present.
expo-origin is deliberately absent from the Hono CORS allowHeaders list in
apps/server/src/app.ts. A cross-origin browser request carrying a custom header requires a
preflight, and that preflight fails for any origin outside CORS_ORIGIN, so no page can forge the
header. Adding it to allowHeaders would remove that property; do not add it.
When AUTH_CROSS_SITE_COOKIES=true, unsafe product requests require a trusted browser origin. A
native client has none, so csrfProtection also accepts a request whose expo-origin matches a
trusted application scheme. That is not a weaker check: a non-browser client carries no ambient
credentials and is not a CSRF vector, and no browser can send the header cross-origin.
An Expo web build is an ordinary browser client. It sends no expo-origin, uses cookies with
credentials: 'include', and its origin must be listed in CORS_ORIGIN.
Google OAuth on native
Native Google sign-in uses the plugin's authorization proxy and stays on the server origin, so the Google Cloud console configuration is the one this repository already documents:
- keep
GOOGLE_CLIENT_IDandGOOGLE_CLIENT_SECRETas the existing web credentials; - keep
SERVER_URL/auth/callback/googleas the only authorized redirect URI; - register the application scheme in the Expo application, not in the Google console.
The client opens SERVER_URL/auth/expo-authorization-proxy?authorizationURL=... in a system
authentication session. The proxy refuses a non-https authorization URL and one that points back
at this server's own origin, sets the signed OAuth state cookie, and redirects to Google. Google
returns to /auth/callback/google, and the expo plugin appends the session cookie to the
application-scheme redirect exactly as it does for a magic link. The callbackURL the client sends
must be an allowlisted application scheme.
Native ID-token sign-in through @react-native-google-signin is a different path and is not
enabled. It needs separate iOS and Android OAuth client IDs and an explicit audience decision for
the ID token; treat adding it as a provider change with its own tests.
Out of scope
Decision 0005 excludes local-first sync and offline writes, in-app purchases in the core billing
contract, and a second mobile framework. Push notifications are in scope for the mobile edition but
still owe the contract 0.7.0 named: device-token registration, storage scoped to users.id,
delivery, and revocation on sign-out and account deletion.
Account deletion and billing
Deleting an application account cannot silently cancel a remote provider subscription. The server
therefore returns 409 CONFLICT while the latest local subscription is active, trialing, past due,
or canceled with paid time remaining.
The buyer must cancel through the selected provider's Billing portal and wait until the paid period ends. Only then can the application soft-delete the user and remove sessions/accounts in one transaction. Deletion is a terminal authentication state: Better Auth rejects every later session creation for that user, and a database trigger closes the status-check/session-insert race. A fresh magic link therefore cannot restore a deleted account. Product-specific data retention or immediate statutory erasure requirements may require a separate reviewed cancellation-and-deletion workflow before launch.
Verification
The real Postgres HTTP suite proves:
- password signup, verification, authenticated session resolution, and logout;
- password reset and revocation of existing sessions;
- magic-link signup and single-use replay rejection;
- a fresh magic link cannot recreate a deleted user's session;
- optional Google behavior fails closed when credentials are absent;
- a native magic-link sign-in returns the session through the application-scheme deep link, and the stored token resolves identity on a protected route;
- a forged native token and an expired native session are both rejected with 401;
- a magic link is refused for an untrusted scheme and refused again when its callback is rewritten;
- unauthenticated requests return 401;
- cross-owner private records use non-disclosing 404 behavior;
- account deletion cannot orphan an active provider subscription.
Run:
RUN_DB_INTEGRATION_TESTS=1 \
DATABASE_URL=postgresql://app:app@localhost:5432/app?sslmode=disable \
bun --filter ./apps/server testAuth changes require this suite plus a production-like browser test of cookies, redirects, email delivery, and exact deployed origins. Unit tests alone are insufficient.
Common failures
| Failure | Inspect |
|---|---|
| Sign-in loops to login | web/API origins, cookie, credentials: include, and Better Auth base URL |
| Verification/reset email absent | local server log or Resend sender/domain/provider error |
| Magic link already invalid | expiry, exact origin, or expected single-use replay protection |
| Google button/action fails | both Google credentials and SERVER_URL/auth/callback/google registration |
| Native sign-in never returns | MOBILE_APP_SCHEME, the Expo scheme, and the callbackURL the client sent |
| Native request returns 403 | expo-origin against the trusted schemes when cross-site cookies are on |
| Requests all share one rate bucket | selected TRUSTED_PROXY_PROFILE and provider forwarding shape |
| Delete account returns 409 | cancel Billing, then wait for the recorded paid period to end |
Do not weaken verification, cookie policy, trusted origins, redirect validation, account-linking policy, proxy trust, or rate limits to make these failures disappear.