Authentication
Better Auth integration, secure sessions, invitations, and organization-scoped access
Configuration
Z8 uses Better Auth as the system authentication layer. System secrets, base URLs, and default social-provider credentials are environment-backed. Organization-specific identity settings are configured inside the product for each organization instead of through tenant-specific environment variables.
Typical auth maintenance commands from the repo root use pnpm:
pnpm --dir apps/webapp run auth:generate
pnpm --dir apps/webapp run auth:migrateIn practice this means:
BETTER_AUTH_SECRETand related auth secrets stay in environment configuration.- Default social providers such as Google, GitHub, LinkedIn, and Apple can be enabled from system env vars.
- Organization-scoped SSO and branded social OAuth are configured per organization in settings and resolved against the current org context at runtime.
- SCIM is part of the enterprise auth stack and is configured through Enterprise Identity Setup at
/settings/enterprise/identity-setupafter org-scoped SSO is configured. - Organization-specific credentials are entered through org settings and stored through the app's org-scoped secret handling instead of per-tenant env vars.
Session And Cookie Behavior
Better Auth is the source of truth for sessions, with database-backed session records and cookie-based web sessions. Z8 also uses secondary storage to speed up session lookups and auth rate limiting without moving revocation authority out of the database.
Key behaviors:
- Web requests use secure,
httpOnlysession cookies through the Next.js Better Auth integration. - Desktop clients can use bearer-token auth where cookies are not the primary transport.
- The store app (
apps/mobile) wraps the web app's own pages and has no separate data API. It signs in through the system browser and then uses the same session cookie as the web app. - Sessions carry
activeOrganizationId, which is the current org context used by authorization and data-access layers. - Organization-scoped routes and services should trust
session.session.activeOrganizationIdrather than user-supplied org identifiers. - Email verification and password-reset links are rewritten to the correct organization-aware base URL when auth emails are sent.
The auth surface supports email/password, required email verification, passkeys, 2FA, admin tooling, and Better Auth organization features in one shared session model.
Invitation And Onboarding Flows
Invitation acceptance and onboarding are part of the auth system, not separate ad hoc flows. The goal is to preserve organization context from the first email through post-login onboarding.
The current flow is:
- An org admin sends an invitation for a specific organization.
- Z8 sends the invitation email using the organization's resolved app URL.
- The invited user signs up or verifies their email.
- Pending invitation state is preserved so the user returns to the correct
accept-invitationflow after verification. - Better Auth accepts the invitation, adds the member to the organization, and records that org relationship on the user session.
- Onboarding reads
activeOrganizationIdso employee creation, role-based steps, and defaults stay scoped to the invited organization.
This is also why callback handling matters for enterprise auth. Social OAuth, SSO, verification redirects, and invitation acceptance all need to land the user back in the correct organization context instead of dropping them into a generic global session.
OAuth Security Features
| Feature | Description |
|---|---|
| PKCE | Proof Key for Code Exchange prevents code interception |
| State signing | HMAC-signed state prevents CSRF attacks |
| Nonce validation | OIDC nonce prevents replay attacks |
| Secure cookies | httpOnly cookies store OAuth state |
OAuth Flow
User clicks "Sign in with Google"
↓
Detect organization from context
↓
Load org-specific or default credentials
↓
Redirect to provider with PKCE challenge
↓
User authenticates with provider
↓
Callback with code + state
↓
Verify state signature + exchange code
↓
Link/create user account
↓
Establish session with organization contextOrganization-Scoped Sessions
Sessions are scoped to the active organization:
// Get session with organization context
const session = await auth.api.getSession({
headers: request.headers,
});
// session.session.activeOrganizationId
// session.user.idSwitching Organizations
// Switch active organization
await fetch('/api/organizations/switch', {
method: 'POST',
body: JSON.stringify({ organizationId }),
});Native App Login Handoff
The desktop client and the store app use a browser-based login handoff with a one-time, PKCE-bound authorization code:
/api/auth/app-login?app=mobile&redirect=z8mobile://auth/callback&challenge=<code-challenge>
/api/auth/app-login?app=desktop&redirect=z8://auth/callback&challenge=<code-challenge>Flow summary:
- The native app opens
/api/auth/app-loginin the browser. - If the user is not signed in, the route redirects to
/sign-inwith acallbackUrlback to the app-login request. - After sign-in, the route redirects back to the native deep link with a one-time code (a page with an "Open Z8" button when the browser asks for HTML).
- The client exchanges the code and its verifier through
/api/auth/app-exchange. Desktop receives a bearer session token.
The store app runs these steps from its web view:
- Signed out,
/sign-inshows an email screen in the shell.POST /api/auth/app-sign-inreturns the app-login URL. It is on the organization's verified custom sign-in domain when the email's domain belongs to exactly one organization (a verified custom domain under it, or a verified SSO provider domain), otherwise on the app origin. Only the domain decides, so the answer does not reveal whether an account exists. It does reveal, for an email domain, that the organization is a Z8 customer and which custom sign-in domain it uses. This was accepted because that domain is public anyway, through DNS and its branded sign-in page. - The system browser (
ASWebAuthenticationSessionon iOS, Custom Tabs on Android) signs in on that domain with its own methods. - The web view exchanges the code with
X-Z8-App-Type: mobileat its own origin. The request must carry that origin inOrigin. The response sets the Better Auth session cookie for the same session row and never returns the token, so the active organization, SSO provenance and revocation stay server-side.
Native Client Requests
The desktop client authenticates API requests with bearer session tokens. The store app's web view uses the session cookie like any browser. The app exchange endpoint uses X-Z8-App-Type (mobile or desktop) to identify the client for its code exchange; a code issued for one app type cannot be exchanged as the other.
Content Security Policy
The app implements a strict CSP with nonce-based script execution:
// CSP headers are set automatically
// Scripts must include the nonce
<script nonce={nonce}>...</script>CSP Reporting
CSP violations are reported to /api/csp-report for monitoring.