Universal Authentication Architecture
The BrokerOS mobile application utilizes Better Auth with the official Expo integration plugin (@better-auth/expo). This is the identical authentication engine powering the Next.js web application, ensuring unified user identities, role verification, and server-side session invalidation across all clients.
Authentication tokens are never stored in unencrypted storage (AsyncStorage). Instead, session tokens are securely sealed inside expo-secure-store, which leverages Android Keystore hardware-backed encryption.
Authentication Lifecycle
Step-by-Step Login Flow
1
App Boot & Session Check
When the app boots,
app/_layout.tsx invokes authClient.useSession(). If no valid token exists in expo-secure-store, the router redirects immediately to /(auth)/sign-in.2
Credential Verification
The agent submits their work email and password. The client transmits the payload to
POST /api/auth/sign-in/email.3
Encrypted Token Storage
Upon successful authentication, the session token is written to
expo-secure-store. On Android, this uses the Android Keystore system to protect keys inside dedicated hardware (TEE or Secure Element).4
Native SharedPreferences Injection
To allow the native Kotlin background worker (This copies the active Bearer token into Android native
CallUploadWorker.kt) to upload call recordings even after the JavaScript thread is paused or the app is closed, the dashboard shell calls:SharedPreferences (AutoDialerPrefs), accessible by native background workers.5
Dynamic Workspace Routing
The dashboard shell retrieves the userβs
roleId, queries the role definition from GET /roles, and renders the tailored bottom tab navigation matching that role.Client Configuration Code
The mobile auth client is configured inapps/mobile/lib/auth-client.ts:
Session Persistence & Auto-Revalidation
Sessions persist seamlessly across device reboots and app restarts:- When the app returns from the background,
authClient.useSession()reads the token fromexpo-secure-store. - A background HTTP ping revalidates the session against the backend.
- If an administrator invalidates the userβs session from the web dashboard (e.g., during employee offboarding), the mobile app clears local storage and forces an immediate return to the login screen.
Sign-Out Flow & Resource Cleanup
When an employee taps the sign-out icon in the top header, BrokerOS executes an orderly cleanup sequence:- Background GPS tracking stops immediately and deletes the stored tracking user ID
- Native Android telephony broadcast listeners are unregistered
- The session token is purged from both
expo-secure-storeand nativeSharedPreferences