# 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. Email verification policy comes from `AUTH_SKIP_EMAIL_VERIFICATION`; setup makes the intended policy explicit. Current server authorization reads the database, with cookie caching disabled.

## 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.

## 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.

## 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/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)

