Native Authentication
Bearer sessions, email OTP, Apple/Google ID-token sign-in, and the desktop OAuth bridge for native clients.
Native clients authenticate against the same Better Auth instance the web
app uses — same /api/auth/* endpoints, same user table, same sessions. The
web keeps its cookie sessions untouched; native clients add a Bearer token
transport, email OTP flows, ID-token sign-in for Apple and Google, and
a desktop OAuth bridge for GitHub/Google sign-in through the system browser.
Everything is configured in src/lib/auth.ts.
What it provides
- Bearer sessions for native clients (
bearer({ requireSignature: true })), additive to the web's cookies. - Email OTP for native email verification, passwordless sign-in, and
password reset (
emailOTPplugin) — the web keeps its link-based emails. - Apple sign-in via native ID token, verified against your iOS bundle ID — no Services ID or Apple OAuth client secret needed.
- Google sign-in via ID token with a web/iOS/Android audience allow-list.
- Desktop GitHub/Google sign-in through the system browser, with a PKCE-bound single-use code and a new, independent Bearer session.
- Trusted origins for app schemes, and per-endpoint rate limits on sensitive auth routes.
Important files
| File | Role |
|---|---|
src/lib/auth.ts | Better Auth config: plugins, providers, rate limits |
src/lib/auth-config/trusted-origins.ts | buildTrustedOrigins() + native-request detection |
src/lib/auth-config/google-id-token.ts | Google ID-token verifier (signature, issuer, expiry, audience) |
src/lib/auth-config/desktop-oauth.ts | Desktop OAuth flow logic: start validation, code issue, PKCE check |
src/lib/auth-config/desktop-oauth-plugin.ts | desktopOAuth() Better Auth plugin (/desktop-oauth/exchange) |
src/lib/auth-config/desktop-schemes.ts | DESKTOP_APP_SCHEMES allow-list |
src/app/api/desktop-auth/{start,complete}/route.ts | Browser-side bridge routes |
src/server/app/shared/session.ts | requireAppSession() — maps "no session" to 401 UNAUTHENTICATED |
.env.example | APP_SCHEME, DESKTOP_APP_SCHEMES, GOOGLE_IOS_CLIENT_ID, GOOGLE_ANDROID_CLIENT_ID, APPLE_APP_BUNDLE_IDENTIFIER |
Bearer sessions
The bearer plugin issues the session token in a set-auth-token response
header on sign-in/sign-up. Native clients store it (iOS: Keychain) and send
Authorization: Bearer <token> on every request:
POST /api/auth/sign-in/email ← { email, password }
200, header set-auth-token: <token.signature>
GET /api/app/v1/todos
Authorization: Bearer <token.signature>Key behaviors:
requireSignature: true— only signed tokens are accepted.- Sessions are database-backed and revocable: after
sign-outorrevoke-other-sessions, the old token stops resolving immediately. - Whenever a response carries a new
set-auth-token, the client must overwrite its stored token. - Web cookie sessions are unaffected — the plugin is additive.
Better Auth's get-session returns 200 with a null body for an
invalid or revoked token — not 401. The App API's requireAppSession guard
converts "no session" into a uniform 401 UNAUTHENTICATED, so business
endpoints behave correctly. Don't rely on /api/auth/get-session's status
code for auth decisions.
Trusted origins
Better Auth rejects requests without a trusted Origin
(403 MISSING_OR_NULL_ORIGIN). Native clients send their app scheme as the
Origin, so it must be registered:
| Variable | Purpose |
|---|---|
APP_SCHEME | Your production app scheme (e.g. soar://) — always trusted |
DEV_TRUSTED_ORIGINS | Comma-separated extra origins, honored only in development |
buildTrustedOrigins() trusts only APP_SCHEME in production; wildcard and
localhost entries are development-only by construction.
Email OTP
Native apps can't click email links, so the emailOTP plugin adds code-based
flows (6-digit code, 5-minute expiry, 3 attempts):
| Flow | Endpoints |
|---|---|
| Verify email | email-otp/send-verification-otp (type: "email-verification") → email-otp/verify-email |
| Passwordless sign-in | email-otp/send-verification-otp (type: "sign-in") → sign-in/email-otp |
| Password reset | forget-password/email-otp → email-otp/reset-password |
The web keeps its link-based verification and reset emails:
sendVerificationEmail skips the link email when the request comes from the
app scheme (isNativeAppRequest), so native users only ever receive the OTP,
and autoSignInAfterVerification signs the newly verified native user in
immediately.
Apple sign-in (native-only)
Apple sign-in is registered only when APPLE_APP_BUNDLE_IDENTIFIER is set, and
only for native ID tokens:
POST /api/auth/sign-in/social
{ "provider": "apple", "idToken": { "token": "<identityToken>", "nonce": "<sha256(rawNonce)>" } }- The token's audience must equal your iOS bundle identifier — that is the entire client configuration; no Apple Services ID or OAuth client secret.
- Better Auth compares the request nonce against the token's nonce claim
directly, and Apple stores
SHA-256(rawNonce)in the claim — so the client must send the hashed nonce. - The web UI does not offer Apple sign-in.
Google sign-in (multi-client)
Web sign-in keeps the standard OAuth redirect flow with
GOOGLE_CLIENT_ID/GOOGLE_CLIENT_SECRET. Native clients send an ID token
instead:
POST /api/auth/sign-in/social
{ "provider": "google", "idToken": { "token": "<googleIdToken>" } }A native Google ID token's aud is the platform client ID, so
src/lib/auth-config/google-id-token.ts installs a custom verifyIdToken that
checks the signature (Google JWKS), issuer, expiry, and an audience
allow-list built from:
| Variable | Audience |
|---|---|
GOOGLE_CLIENT_ID | Web client (also used by the redirect flow) |
GOOGLE_IOS_CLIENT_ID | iOS app |
GOOGLE_ANDROID_CLIENT_ID | Android app |
Create all clients in one Google Cloud project so they belong to the same
OAuth consent screen. account.accountLinking.enabled maps Apple, Google, and
password accounts with the same email to one Better Auth user.
Desktop OAuth bridge
Desktop apps have no native GitHub/Google ID-token SDK, and an embedded
webview is not an option: Google blocks embedded user agents, and RFC 8252
requires native apps to use an external browser. The host therefore ships a
bridge that runs the normal Web GitHub/Google sign-in in the system browser
and hands the desktop app a single-use code. It reuses the existing
GITHUB_* / GOOGLE_* Web OAuth apps — no new provider app and no new
redirect URL to register.
The bridge is client-agnostic. Today the Electron template uses it in Unified Mode; the Tauri template does not implement the client side yet.
Desktop main process System browser Host
──────────────────── ────────────── ────
state, code_verifier,
challenge = S256(verifier)
open start URL ──────────────────▶ GET /api/desktop-auth/start
?provider&scheme&state
&code_challenge
&code_challenge_method=S256 store flow (10 min)
Better Auth signInSocial
◀── 302 to GitHub/Google (+ OAuth state cookie)
user consents
──▶ /api/auth/callback/{provider} browser cookie session
──▶ GET /api/desktop-auth/complete?flow=…
single-use code (2 min)
◀── page → <scheme>://auth/callback?code&state
POST /api/auth/desktop-oauth/exchange { code, codeVerifier } (Origin: soar://)
verify S256, new session
◀── 200 { user } + set-auth-token| Endpoint | What it does |
|---|---|
GET /api/desktop-auth/start | Validates provider (GitHub or Google with its client ID set), scheme (allow-listed), state (16–128 base64url chars), and a 43-character S256 code_challenge. Stores the flow for 10 minutes, starts Better Auth's social sign-in with /api/desktop-auth/complete as the callback, forwards the OAuth state cookie, and redirects to the provider. Invalid input renders a 400 error page and never redirects. |
GET /api/desktop-auth/complete | Better Auth's success and error callback. Consumes the flow once and reads the browser session this round trip created (an older session yields session_missing). Issues a random code, stored hashed for 2 minutes and bound to the user and challenge, and returns a no-store hand-off page that redirects to <scheme>://auth/callback?code&state with an "Open the app" fallback button. Provider errors return as ?error=<code>&state. An unknown or expired flow shows an error page with no redirect, since there is no trusted scheme to return to. |
POST /api/auth/desktop-oauth/exchange | The desktopOAuth Better Auth plugin. Body { code, codeVerifier }. Consumes the code, checks base64url(sha256(codeVerifier)) against the challenge, and creates a new session (the admin plugin still blocks banned users). The bearer plugin turns it into a set-auth-token header, exactly like email sign-in. Any failure is 400 DESKTOP_OAUTH_INVALID_CODE; rate-limited to 10 requests per minute. |
Properties worth relying on:
- Independent desktop session. The exchange creates its own session, so the desktop and browser sessions are revoked separately. Signing out on the Web does not sign the desktop out. The browser keeps the cookie session from the round trip, the same as a normal Web social sign-in.
- PKCE-bound code. Only
codeandstatetravel through the custom scheme. Without the verifier, which never leaves the desktop main process, a code is useless, so another app that registers the same scheme can't redeem it. - No new tables. Flows and codes live in Better Auth's
verificationtable; codes are stored as SHA-256 hashes.
Configuration
| Variable | Purpose |
|---|---|
DESKTOP_APP_SCHEMES | Comma-separated schemes (without ://) the bridge may redirect to, e.g. soar-electron. Required in production, where only listed schemes are accepted. Development also accepts soar-electron and soar-tauri. Web schemes (http, https, javascript, data, file, …) are always rejected, so the bridge can't become an open redirect. |
APP_SCHEME | The exchange is a Better Auth POST, so the desktop's Origin: soar:// must still be trusted. |
GITHUB_CLIENT_ID / GOOGLE_CLIENT_ID | A provider is offered to desktop only when its Web client is configured. |
The desktop app must open start on the same origin as BETTER_AUTH_URL.
Better Auth sets the OAuth state cookie on the host that served start, but
the provider returns to BETTER_AUTH_URL. A mismatch — localhost vs a LAN
IP, or www vs the apex domain — fails the callback with state_mismatch.
For Electron, that means SOAR_API_BASE_URL and BETTER_AUTH_URL share one
origin.
These routes sit outside the frozen /api/app/v1 contract and are not in
docs/openapi.yaml.
Rate limits
rateLimit.customRules tightens the sensitive endpoints (enabled in
production): sign-in, sign-up, password reset, change-password/email, and all
OTP endpoints get small per-minute budgets, and clients must not auto-retry
sign-in or OTP requests on 429.
Client rules (what a native implementation must do)
- Store the token in secure storage only (Keychain — never UserDefaults/logs).
- Treat
set-auth-tokenon any response as "replace the stored token". - On
401: clear the stored token and local state, show sign-in. No retry loops, no silent fallback to another backend. - Send
Content-Type: application/jsonand a{}body even for empty POSTs. - Account deletion goes through
DELETE /api/app/v1/account(cascade cleanup), not a Better Auth endpoint — see Account Deletion.
