# Authentication and Organizations

Better Auth owns identity, sessions, Organizations, platform roles and OAuth.

## Session outcomes [#session-outcomes]

Password sign-in can return a Session, a pending two-factor challenge, an unverified email, a Ban or a refusal. Treat those as distinct outcomes. `session-outcome.ts` and `two-factor-outcome.ts` provide the shared interpretation; hooks own navigation and error presentation.

The server registers two-factor, admin, organization, passkey, Expo and MCP OAuth plugins. Google and Apple sign-in are optional and off until configured ([Social sign-in](#social-sign-in-google-and-apple)). Email verification policy comes from `AUTH_SKIP_EMAIL_VERIFICATION`; setup makes the intended policy explicit. Server reads use Better Auth's signed Session snapshot (at most 60 s old) or the database; sensitive operations always read the database (see [Session reads](#session-reads)).

## Session reads [#session-reads]

The session row in the database is the authority for who is signed in. Better Auth's cookie cache (`session.cookieCache`: `compact`, signed with HMAC, `maxAge` 60 s) keeps a snapshot of the session and user in the `better-auth.session_data` cookie (`__Secure-` on https). Server reads use that snapshot while it is valid, so most requests read no session from the database ([ADR-0015](/docs/adr/0015-server-reads-the-session-from-the-cookie-cache)).

| Read                                                                                                                                                                                                                          | Source                                                                                 |
| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- |
| The browser's presentation read (`GET /api/auth/get-session`): the `/_auth` guard, `useSession`, tab focus                                                                                                                    | The snapshot while it is younger than 60 s; otherwise the database, which re-issues it |
| SSR guard and prefetches, every oRPC procedure, the files gateway (`getRequestSession`, once per request)                                                                                                                     | The same snapshot; otherwise the database, which re-issues it on that response         |
| Admin procedures and the `/admin` guard, billing, push registration, tool approvals and assistant runs, webhook endpoint and OAuth connection changes, presigned URL minting (`authoritativeSession`, `getAuthorizedSession`) | The database (`disableCookieCache`)                                                    |
| Every `/api/auth/*` request except `GET /get-session`: password, email, 2FA, passkeys, sessions, Organizations, invitations, impersonation, account deletion, OAuth                                                           | The database: `createAuth().handler` strips the snapshot (`withoutSessionSnapshot`)    |
| Membership in the Active Organization (`orgProcedure`, the files gateway)                                                                                                                                                     | The `member` table on every request, and RLS (`app.org_id()`) on every statement       |
| The read after this device changed its session (`useAuthMutation({ resetSession })`; `refreshAuthSession` on mobile)                                                                                                          | The database, which re-issues the snapshot                                             |

What a change looks like:

| Change                                                                                                                | UI shell                                                     | Data                                                                                                           |
| --------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------- |
| Sign-out on this device                                                                                               | Gone at once: Better Auth expires both cookies               | Refused at once                                                                                                |
| Sign-out in another tab of the same browser                                                                           | That tab leaves for `/login` at once (`session-identity.ts`) | Refused at once (same cookies)                                                                                 |
| Session revoked on another device: sign out everywhere, revoke a session, password change or reset, admin revoke, ban | Up to 60 s                                                   | Up to 60 s, then 401 and `/login`                                                                              |
| Presigned download and upload URLs                                                                                    | —                                                            | New URLs require a database session check; URLs minted before revocation work until expiry, at most 15 minutes |
| A copy of the cookies taken before a sign-out                                                                         | —                                                            | Up to 60 s, like a revocation                                                                                  |
| Member removed from the Active Organization                                                                           | May show the Organization for up to 60 s                     | Refused at once: 403 from the membership check, no rows through RLS                                            |
| Platform admin demoted                                                                                                | `/admin` and admin navigation re-read the role at once       | Admin procedures re-read it at once                                                                            |

The window is the snapshot's `maxAge`: a shorter one reads the database more often. `session.cookieCache.version` invalidates every snapshot at once; bump it when the session or user fields the server reads change. A new procedure that creates or reveals a credential builds on `userProcedure` or `adminProcedure` ([backend conventions](/docs/development/backend-conventions#sensitive-procedures-read-the-database-session)).

## Organizations and roles [#organizations-and-roles]

Signup provisions a personal Organization. A User may be a Member of several Organizations; the Session selects one Active Organization. Todos and files belong to that Organization. Platform role `admin` grants global administration; Org roles `owner`, `admin` and `member` do not grant platform administration.

Membership must be checked at the operation, even if the UI already selected an Organization. An MCP token has no active selection and stays pinned to the User's personal Organization. See [connecting agents](/docs/connect-your-agent).

## Invitations [#invitations]

An invitation email is the app writing to a stranger on a signed-in User's behalf, so `invite-member` is treated as outbound mail, not as a form. Four controls apply, all in `packages/auth` ([`invitation-policy.ts`](https://github.com/CarlosZiegler/template-cloudflare/blob/main/packages/auth/src/invitation-policy.ts)):

- **Role.** Only the Organization roles `owner` and `admin` hold `invitation: create`; a `member` holds no write permission. These are Better Auth's default roles, passed explicitly in the plugin configuration so a change is a visible diff.
- **Verified inviter.** The inviter's email must be verified, regardless of `AUTH_SKIP_EMAIL_VERIFICATION`. With the default `true`, an account signs in unverified and can create Organizations, but its first invitation is refused with `INVITER_EMAIL_NOT_VERIFIED` until the address is confirmed; the web dialog and the mobile invite group show that state and offer to send the verification email. The choice is deliberate: skipping verification is a sign-in convenience for the account holder, not a licence to send mail in their name.
- **Daily caps.** Rolling 24-hour counts on the `invitation` table: 20 per inviter across all Organizations (`INVITATION_DAILY_LIMIT_REACHED`) and 50 per Organization across all inviters (`ORGANIZATION_INVITATION_DAILY_LIMIT_REACHED`), both HTTP 429. Better Auth's `invitationLimit` caps pending invitations per Organization at 50 (`INVITATION_LIMIT_REACHED`). Constants live in `INVITATION_POLICY`.
- **Rate limit.** `/organization/invite-member` has its own `customRules` entry, 10 requests per 10 minutes per client IP, next to the credential endpoints.

The checks run in `beforeCreateInvitation`, before the row is written and before any mail is sent, and again in a root `hooks.before` for the `resend: true` path, which re-sends an existing invitation without creating one. Counting runs on the handle Better Auth already holds (the `auth.better-auth` system scope, ADR-0009): one inviter's invitations span Organizations, so no tenant scope could see them all. The email itself never puts inviter text in the subject; see [Email](/docs/features/email#user-controlled-text).

A refusal is a typed `APIError`; `packages/errors` maps each code to a message in every locale, and both clients show it through the shared mutation helper. Re-sending an existing invitation is not counted against the daily caps (the row already exists); the IP rule bounds it.

## Rate limits [#rate-limits]

Better Auth rate limiting is on everywhere except Vitest. Its Postgres storage uses a separate connection and one upsert per counted request, so a rolled-back failure still counts. The hourly auth cleanup sweeps expired rows. The key is the trusted client IP (`cf-connecting-ip` on Workers, resolved by `client-ip.ts`) and the auth path.

| Path                                         | Limit              | Reason                                                                     |
| -------------------------------------------- | ------------------ | -------------------------------------------------------------------------- |
| `/get-session`                               | Exempt             | The read can answer from the signed snapshot without a database statement. |
| `/jwks`                                      | Exempt             | Public keys; MCP loads them at most once a minute per isolate.             |
| `/sign-in/email`, `/sign-up/email`           | 5 per 60 seconds   | Limit credential guessing and account creation.                            |
| `/sign-in/social`                            | 10 per 60 seconds  | Limit provider redirects and native identity-token posts (Google, Apple).  |
| `/request-password-reset`, `/reset-password` | 3 per 60 seconds   | Limit password reset attempts.                                             |
| `/organization/invite-member`                | 10 per 600 seconds | Limit outbound invitations.                                                |

Every other path uses Better Auth's defaults: 100 per 10 seconds, with 3 per 10 seconds for built-in sign-in, sign-up, password change and email change paths unless overridden above. A 429 response carries `Retry-After`; the handler copies Better Auth 1.7.16’s `X-Retry-After` value to the standard header. Rate-limit tests opt in with `NODE_ENV=production`.

## Web and native [#web-and-native]

Web auth hooks coordinate TanStack Query, forms and redirects. Mobile uses the Better Auth Expo client, secure credential storage and native passkey integration. Its route gate revalidates the Session and hides private content during a transition. Logout, expiry or an authoritative 401 clears private state. A 403 does not automatically sign out an otherwise valid Session.

Every web form with a password field sets `method="post"`. The server-rendered ones (sign-in, sign-up, reset and change password) also keep submit disabled until `useHydrated()` is true, so a click before hydration never sends credentials in a GET URL.

## Social sign-in (Google and Apple) [#social-sign-in-google-and-apple]

Sign-up and sign-in with Google and Apple ship off. A provider is registered only when every one of its variables is set ([`packages/env/src/social.ts`](https://github.com/CarlosZiegler/template-cloudflare/blob/main/packages/env/src/social.ts)); with some missing it stays off, the server logs `Social sign-in with <provider> is off` once per isolate, and `pnpm doctor` names the missing variables. Clients read which providers are on from the public `appConfig.get` response (`auth.socialProviders`, names only, never a value) and show only those buttons, on the web sign-in and sign-up pages and in the app.

| Variable                      | Provider | Value                                                                                                                            | Secret |
| ----------------------------- | -------- | -------------------------------------------------------------------------------------------------------------------------------- | ------ |
| `GOOGLE_CLIENT_ID`            | Google   | OAuth client ID, type Web application                                                                                            | No     |
| `GOOGLE_CLIENT_SECRET`        | Google   | That client's secret                                                                                                             | Yes    |
| `APPLE_CLIENT_ID`             | Apple    | Services ID (`com.example.app.web`): the web flow's client and the client secret's `sub`                                         | No     |
| `APPLE_TEAM_ID`               | Apple    | 10-character Team ID: the client secret's `iss`                                                                                  | No     |
| `APPLE_KEY_ID`                | Apple    | 10-character ID of the Sign in with Apple key: the client secret's `kid`                                                         | No     |
| `APPLE_PRIVATE_KEY`           | Apple    | The key's `.p8` content (PKCS #8 PEM); one line with `\n` escapes is accepted                                                    | Yes    |
| `APPLE_APP_BUNDLE_IDENTIFIER` | Apple    | iOS bundle identifiers accepted as the native identity token's audience, comma-separated (`com.example.app,com.example.app.dev`) | No     |

Locally, `pnpm setup` offers both providers (skip them and nothing changes), reads the Apple key from the `.p8` path you give, refuses half a provider, and writes the values to `apps/web/.env` and `apps/web/.dev.vars`. Without prompts: `--google-client-id` with `GOOGLE_CLIENT_SECRET` in the environment of the setup command, and `--apple-client-id`, `--apple-team-id`, `--apple-key-id`, `--apple-key-file`, `--apple-bundle-ids` (default: `--mobile-id` and its `.dev` variant). Secrets never go in arguments.

In production all seven are Worker secrets, never `vars`: PR preview Workers are generated from `wrangler.jsonc` and would inherit a provider without its credentials. `pnpm run setup --worker-secrets` publishes the complete providers' local values to `<project>-web` with `wrangler secret bulk` (JSON on stdin); use it when development and production share the OAuth clients. Otherwise write the production values to a JSON file outside the repository, run the command below, and delete the file. The deploy workflows do not manage these secrets, and Worker secrets persist across deploys. A preview has none, so it shows no social buttons.

```sh
pnpm --filter web exec wrangler secret bulk social.json --name <project>-web --config wrangler.jsonc
```

### Google [#google]

<Steps>
<Step title="Consent screen">
In the Google Cloud console, open Google Auth Platform (APIs & Services → OAuth consent screen). Set the app name, a support email and your site's domain as an authorized domain. The scopes are `openid`, `email` and `profile`, which need no Google verification review. While the publishing status is Testing, only the test users you list can sign in; publish the app before launch.
</Step>

<Step title="OAuth client">
Credentials → Create credentials → OAuth client ID, type **Web application**. Add each origin under Authorized JavaScript origins and its callback under Authorized redirect URIs: `<origin>/api/auth/callback/google`, for example `https://app.example.com/api/auth/callback/google` and `http://localhost:3005/api/auth/callback/google` for development.
</Step>

<Step title="Variables">
Copy the client ID and secret into `GOOGLE_CLIENT_ID` and `GOOGLE_CLIENT_SECRET`.
</Step>
</Steps>

The server shows Google's account chooser every time (`prompt=select_account`) and accepts only the redirect flow: an ID token posted by a client is refused (`disableIdTokenSignIn`). The app uses the same redirect, so the server's callback is the only redirect URI to register.

### Apple [#apple]

<Steps>
<Step title="App ID">
In Apple Developer → Certificates, Identifiers & Profiles → Identifiers, open the iOS app's App ID and enable **Sign in with Apple**. Enable it on the `.dev` App ID too if development builds sign in.
</Step>

<Step title="Services ID">
Identifiers → + → Services IDs. Its identifier (for example `com.example.app.web`) is `APPLE_CLIENT_ID`. Enable Sign in with Apple → Configure: choose the primary App ID, add your host under Domains and Subdomains (no scheme) and `<origin>/api/auth/callback/apple` under Return URLs. Apple accepts only HTTPS and no `localhost`, so web sign-in with Apple needs a deployed or tunnelled HTTPS origin. If the portal asks you to verify the domain, put the file it offers in `apps/web/public/.well-known/`, deploy, and confirm with `curl` that the URL returns it before you verify.
</Step>

<Step title="Key">
Keys → + → Sign in with Apple (configure it with the primary App ID). Download the `.p8` (Apple offers it once): its ID is `APPLE_KEY_ID`, its content `APPLE_PRIVATE_KEY`. Your Team ID (Membership details) is `APPLE_TEAM_ID`.
</Step>

<Step title="Bundle identifiers">
`APPLE_APP_BUNDLE_IDENTIFIER` lists the app's bundle identifier, plus `<bundle id>.dev` when development builds sign in against the same server.
</Step>

<Step title="Email relay">
People who hide their address get a private relay address. Mail to it is delivered only from a registered source: Services → Sign in with Apple for Email Communication → register the domain or address of `EMAIL_FROM` (it must pass SPF). Otherwise the welcome, verification and password reset emails to `@privaterelay.appleid.com` are dropped.
</Step>
</Steps>

Apple's client secret is not a static value: it is an ES256 JWT signed with the `.p8` key and valid for at most six months. The server signs it itself with Web Crypto (workerd and Node alike), with a 30-day lifetime, keeps it in memory per isolate and signs a new one when less than a day is left, so nobody rotates it ([`apple-client-secret.ts`](https://github.com/CarlosZiegler/template-cloudflare/blob/main/packages/auth/src/apple-client-secret.ts)). A key that cannot sign (not a PKCS #8 P-256 key) keeps Apple off and logs why; every other sign-in method keeps working. Apple returns the web flow as a cross-site POST (`response_mode=form_post`), so `https://appleid.apple.com` is a trusted origin while Apple is on.

### Accounts and linking [#accounts-and-linking]

A social sign-up goes through the same database hooks as an email sign-up, so the User ends up the same: a personal Organization with an owner membership, the `user.created` and `org.created` audit entries, `auth.sign_in` for the Session, and the Active Organization set on it. A password User is welcomed once the address is verified; Google and Apple verify it first, so a social sign-up is welcomed at once.

| Situation                                                                                 | Result                                                                                                                                                                                                                                                                                                                                                         |
| ----------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| No User has the address                                                                   | A new User, as above.                                                                                                                                                                                                                                                                                                                                          |
| A User has the same address, verified, and the provider reports it verified               | The provider account is linked to that User, who is signed in.                                                                                                                                                                                                                                                                                                 |
| A User has the same address, not verified                                                 | Refused with `account_not_linked`. An unverified address may have been typed by someone else, and with `AUTH_SKIP_EMAIL_VERIFICATION=true` (the default) password sign-ups stay unverified. The person signs in with email and password (or resets the password) and verifies the address from the verification email; the next Google or Apple sign-in links. |
| The provider reports the address unverified                                               | Never linked. A new User is unverified like a password sign-up; with `AUTH_SKIP_EMAIL_VERIFICATION=false` it gets no Session until the address is verified.                                                                                                                                                                                                    |
| A different address, such as an Apple relay address next to a password account's real one | Never linked: a separate User.                                                                                                                                                                                                                                                                                                                                 |

Two-factor: Better Auth challenges only the credential sign-ins, so a User with two-factor on gets no Session from Google or Apple. The callback returns to the page with `?error=TWO_FACTOR_REQUIRED` (the native sign-in answers 403 with that code) and the person signs in with email, password and code. A provider account that was linked on that attempt stays linked.

No provider is a trusted provider (which would skip the provider's `email_verified`), different addresses never link (`allowDifferentEmails: false`), and linking never overwrites the User's name or image. Provider tokens are stored encrypted (`encryptOAuthTokens`); the template never calls Google or Apple with them. The policy lives in [`social-providers.ts`](https://github.com/CarlosZiegler/template-cloudflare/blob/main/packages/auth/src/social-providers.ts) and the `account` options of [`index.ts`](https://github.com/CarlosZiegler/template-cloudflare/blob/main/packages/auth/src/index.ts).

Apple sends the person's name only the first time they authorize the app (the web form post's `user` field, or the native credential's full name), never in the identity token, and Google may omit it. Without a name, the address's local part stands in (`profileName`); for a relay address that is its random local part, which the person can change in settings. The personal Organization is named after it. A relay address (`…@privaterelay.appleid.com`, always verified) is stable per app and person, so it signs in every time like any other address.

### Mobile [#mobile]

- **Apple, iOS only**: the native sheet (`expo-apple-authentication`, `ios.usesAppleSignIn` in the app config). The app creates a random nonce, gives Apple its SHA-256 and sends the raw nonce with the identity token (`signIn.social({ provider: "apple", idToken: { token, nonce } })`). Better Auth checks Apple's signature, the audience (`APPLE_APP_BUNDLE_IDENTIFIER`) and that the token's nonce is the SHA-256 of the raw one. The server refuses an Apple identity token without a nonce (`ID_TOKEN_NONCE_REQUIRED`), so a captured token cannot be replayed. On the first sign-in the app sends the name Apple returned.
- **Google**: the `@better-auth/expo` browser flow, with no native module and no extra client ID. The system browser goes to Google, then to the server's `/api/auth/callback/google`, and back to the app through its scheme (`<NATIVE_APP_SCHEME>://`, `-dev` for development builds), which the server trusts as a native origin.
- **App Store guideline 4.8**: on iOS the Google button appears only when Sign in with Apple is offered as well, and Apple comes first (`visibleSocialProviders` in `apps/mobile/src/features/auth/auth.social.ts`). Android never shows Apple.
- **Limits**: Expo Go cannot sign in with Apple (its identity token's audience is Expo Go's bundle identifier, not yours); use a development build. Google from a physical device needs an origin Google accepts as a redirect URI (HTTPS, or `localhost` on the simulator), so use a tunnel or a preview URL. On iOS a refused Google sign-in (for example `account_not_linked`) currently looks like a cancel, because the Expo plugin reads only the cookie from the browser result; Android shows the error.
- `expo-apple-authentication` and `expo-crypto` are native modules: rebuild the development client after pulling the change that added them.

## Extend safely [#extend-safely]

Add auth behavior to the server factory and its tests, then expose the outcome through a hook. Keep email callbacks, membership checks and audit recording in their existing owners. Test revoked Sessions and Organization changes as well as successful login. Never treat an impersonated admin's original identity as permission to access `/admin`.

## Key files [#key-files]

- [`packages/auth/src/index.ts`](https://github.com/CarlosZiegler/template-cloudflare/blob/main/packages/auth/src/index.ts)
- [`packages/auth/src/invitation-policy.ts`](https://github.com/CarlosZiegler/template-cloudflare/blob/main/packages/auth/src/invitation-policy.ts)
- [`packages/auth/src/social-providers.ts`](https://github.com/CarlosZiegler/template-cloudflare/blob/main/packages/auth/src/social-providers.ts)
- [`packages/auth/src/apple-client-secret.ts`](https://github.com/CarlosZiegler/template-cloudflare/blob/main/packages/auth/src/apple-client-secret.ts)
- [`packages/env/src/social.ts`](https://github.com/CarlosZiegler/template-cloudflare/blob/main/packages/env/src/social.ts)
- [`packages/auth/src/session-outcome.ts`](https://github.com/CarlosZiegler/template-cloudflare/blob/main/packages/auth/src/session-outcome.ts)
- [`packages/db/src/provision-organization.ts`](https://github.com/CarlosZiegler/template-cloudflare/blob/main/packages/db/src/provision-organization.ts)
- [`apps/web/src/features/auth/auth.sign-in.hooks.ts`](https://github.com/CarlosZiegler/template-cloudflare/blob/main/apps/web/src/features/auth/auth.sign-in.hooks.ts)
- [`apps/mobile/src/platform/auth/use-session-lifecycle.ts`](https://github.com/CarlosZiegler/template-cloudflare/blob/main/apps/mobile/src/platform/auth/use-session-lifecycle.ts)
