This document describes the authentication, authorization, data-handling, and secure-coding practices used in OpenFrame OSS Frontend. It is written for engineers who work on the Next.js web console (apps/web), the Android mobile shell (apps/mobile), and the desktop Tauri runtime (apps/desktop). It also covers how secrets and environment configuration are managed across these surfaces.
This repository is the application layer only. It consumes
@flamingo-stack/openframe-frontend-coreas a published npm dependency (installed fromhttps://pkg.pr.new/flamingo-stack/openframe-oss-lib/@flamingo-stack/openframe-frontend-core@0.0.977) andasync_natsfrom the NATS Rust Client for the desktop runtime. Several security-critical primitives (token-store internals, gated identity providers, GraphQL schema enforcement) live upstream in those repositories; this document covers how this repository uses them, not their internal implementation.
- Authentication And Authorization
- Data Encryption And Secure Storage
- Input Validation And Sanitization
- Common Vulnerabilities And Mitigations
- Security Testing And Code Review
- Environment Variables And Secrets Management
Authentication is implemented as a client-side orchestration layer under apps/web/src/app/(auth)/auth, documented in detail in Auth architecture. The module does not implement cryptography or token issuance itself — it coordinates calls to the authentication gateway, normalizes responses, and keeps session state consistent across the browser, the Android WebView shell, and the desktop Tauri shell.
flowchart LR
Browser["Browser or Native Shell"] --> Layout["Auth Layout"]
Layout --> Forms["Login and Organization Forms"]
Forms --> Actions["useAuth Actions"]
Actions --> AuthClient["Auth API Client"]
AuthClient --> Gateway["Authentication Gateway"]
Gateway --> Session["Session and Tenant Services"]
Session --> SessionHook["useAuthSession"]
SessionHook --> Store["Persisted Auth Store"]
Store --> Guard["Route Guard and App Shell"]
useAuthSession (documented in Auth architecture) is the single place that decides whether the current client is authenticated. It queries the tenant /me endpoint through authApiClient and distinguishes:
- HTTP
401/403→ definitively signed out. - Transient network, gateway, or refresh-service failures → not signed out; prior session state is preserved and the query retries with exponential backoff.
This distinction matters for security reviews: never treat a non-401 failure as "safe to log the user out," and never treat the absence of an error as proof of authentication — always check the resolved session state before gating access to sensitive UI.
Credential renewal is centralized in the token-refresh manager (apps/web/src/lib/token-refresh-manager.ts, documented in Runtime and token refresh). Key properties engineers must preserve when touching authenticated request code:
- A
401alone does not prove the session is dead. The manager returns a three-state outcome —refreshed,transient, orterminal— and onlyterminalshould ever trigger sign-out. - Refresh calls are serialized within a browser tab and across tabs using the Web Locks API plus a token-free
localStoragerotation marker (of_token_rotated_at), preventing two tabs from racing a single-use refresh token. - A stale
401(the credential already rotated while the request was in flight) is recognized by comparing token epochs and is treated asrefreshed, not as a reason to clear a newer, still-valid credential. - In bearer mode, a successful rotation response without a replacement access token is treated as
terminal— the old refresh token may already be spent, so retaining it would produce a misleading authenticated UI state.
When writing new authenticated request code, always capture the token epoch before sending a request and pass it into refreshTokens(observedEpoch) so stale failures are classified correctly. Never call the boolean compatibility helper refreshAccessToken() to decide whether to sign a user out — use the three-state refreshTokens result instead.
- Android (
apps/mobile/android/app/src/main/java/ai/openframe/mobile/SecureTokenStore.java,TokenLifecycle.java,NativeAuthPlugin.java) stores the access/refresh token pair as a single combined AES-256-GCM blob in the Android Keystore, optionally gated behind biometric authentication using an RSA-2048/OAEP envelope. The refresh token never crosses the Capacitor bridge into the WebView — only the access token is exposed to page script asPageTokens, because a script in the page could exfiltrate a long-lived refresh token. - Desktop (
apps/desktop/src-tauri/src/tokens.rs) applies the same principle in Rust: the shell owns refresh, serializes it with a mutex to prevent racing refreshers, and only ever disposes the current custody epoch to the webview — never the refresh token itself. Refresh timing is deliberately tuned (seeREFRESH_MARGIN_SECS,WAKE_SETTLE_SECSin that file) to avoid rotating a credential while the host OS is asleep, since a lost rotation response can end the session irrecoverably.
When adding new native bridge methods that touch tokens, follow the existing pattern: the webview requests work through a narrow plugin method (
getTokens,setTokens,refreshTokens,clearTokens); it is never handed the refresh token directly.
Verified SSO identities and signup tickets (useSsoSignupTakeover, pendingSsoIdentityByTicket, documented in Auth architecture and Auth API Client) are held only in memory — never written to a route, localStorage, or logs. Apple-provided authorization codes are single-use; a failed registration attempt must distinguish a retryable request failure from a spent credential rather than prompting a pointless retry with a dead code.
SSO continuation and join endpoints (continueUrl, completeSsoRegistrationUrl, ssoJoinReturnUrl) return navigation URLs rather than performing fetch calls, because the redirect chain is what commits authentication cookies in the browser. ssoJoinReturnUrl is validated against a server-side allow-list rather than navigating directly to a caller-supplied destination — never bypass this by constructing a raw redirect URL client-side.
RouteGuard (apps/web/src/components/route-guard.tsx) enforces which pathnames are valid for the current application mode (oss-tenant, saas-tenant, saas-shared) by delegating to isRouteAllowedInCurrentMode. This is explicitly not an authorization boundary — it only prevents a page from rendering UI that is invalid for the current deployment mode. It performs no authentication check and no server-side enforcement.
Any API, GraphQL resolver, or backend service that
RouteGuardhappens to gate client-side access to must independently enforce its own authorization. Treat a denied route here as a UX improvement, never as the mechanism that protects sensitive data.
The Approvals module illustrates the repository's pattern for human-in-the-loop authorization of sensitive or automated actions (for example, actions proposed by Mingo AI or pending ticket operations). Key invariants worth preserving when extending this pattern:
- A decision is only reflected locally after the server-side approval mutation succeeds — never apply optimistic "approved" UI state before the backend accepts it.
- Approval decisions are recorded in a React-independent Zustand store (
approval-decisions.ts) specifically so the shared approval mutation can be called from any surface without a React dependency, and so a decision made in one surface (ticket board, Mingo thread, notification drawer) is reflected everywhere without waiting for the next poll. - Approval requests with type
CLIENTare excluded from the technician inbox by design — do not relax that filter without confirming the intended audience for the action.
| Data | Where it lives | Protection |
|---|---|---|
| Access/refresh tokens (web, bearer mode) | Token store (browser) | Owned by the token-store layer, never persisted inside useAuthStore |
| Access/refresh tokens (Android) | Android Keystore via SecureTokenStore.java |
AES-256-GCM, optional biometric-gated RSA-2048/OAEP envelope; hardware-backed where available |
| Access/refresh tokens (Desktop) | OS-level secure storage via apps/desktop/src-tauri/src/tokens.rs |
Shell-owned custody with single-flight refresh and a custody epoch to invalidate stale in-flight rotations |
Persisted user identity (User, isAuthenticated, tenantId) |
useAuthStore (Zustand, persisted) |
Only these three fields are persisted under AUTH_STORAGE_KEY; tokens are explicitly excluded |
| Announcement cache | localStorage key of.announcement.last |
Versioned (v: 1), 7-day TTL, fails open (treated as cache miss) on any storage or parse error — see Announcement Cache |
| Session health state | In-memory Zustand store | Not persisted; reset on sign-out/sign-in boundary — see Session Health |
- Never persist tokens through
useAuthStore. The auth store's persistence layer is deliberately scoped to non-sensitive identity fields (user,isAuthenticated,tenantId). Token custody is owned exclusively by the platform-specific token store (browser token store, AndroidSecureTokenStore, desktoptokens.rs). - Treat storage access as fallible, not authoritative. The announcement cache and session health modules both demonstrate the pattern required elsewhere: a read/write failure (blocked storage, quota, private browsing, malformed JSON) must be swallowed and treated as a cache miss, never surfaced as an application error or used to make a security decision.
- Prefer hardware-backed storage on native shells. The Android implementation generates its AES master key inside the AndroidKeyStore (non-exportable) and wraps content keys per-write with a biometric-gated RSA key when biometric login is enabled; it never stores a key material outside the Keystore boundary.
- Reset session-scoped state on tenant/session boundaries.
resetSessionHealth()and the auth store's logout path both clear state fully — including onboarding progress — so that a new user in a reused browser tab or native shell cannot inherit a previous session's local state.
Session Health treats an HTML 410 Gone response from the tenant gateway specifically as proof the workspace has been deleted, entering a terminal gone state that blocks further requests locally via SessionGoneError. This classification is intentionally narrow:
- A JSON
410from a tenant service (for example, a missing recording) is not tenant deletion. - A
410from the hub/discovery lookup is not tenant deletion.
When adding new request paths that call noteGatewayResponse, only pass responses that actually originate from the tenant gateway. Misclassifying a resource-level 410 as tenant deletion would incorrectly lock out an otherwise healthy session.
Forms across the web application use react-hook-form (7.71.1) with @hookform/resolvers (5.2.2) and zod (4.6.6) schemas. The pattern is consistent: a Zod schema defines the shape and constraints, zodResolver wires it into the form, and form.trigger() is called before any mutation is submitted. The Customer Policy Configuration module is a representative example — customerAiAssistantSchema validates the AI assistant form, and the validate() imperative handle short-circuits when a block is in "inherit defaults" mode so unused fields are not spuriously validated.
When adding a new form:
- Define a Zod schema rather than validating ad hoc in a submit handler.
- Call
trigger()(or the resolver equivalent) and check the boolean result before invoking a mutation. - Keep client-side validation defense-in-depth only — the backend GraphQL/REST layer remains the authoritative validator.
useOrganizationDomain (described in Auth architecture) is the single owner of tenant-domain sanitization for password signup, browser SSO continuation, and native Apple signup. It:
- Sanitizes input to the accepted subdomain character set before ever sending it to the server.
- Performs a debounced availability check for UX feedback.
- Re-checks availability at submit time to close the race between a stale debounced result and the actual submission — a classic time-of-check/time-of-use gap that would otherwise allow a submission based on outdated validation state.
Any new tenant-identifier input should reuse this hook rather than re-implementing subdomain sanitization, to avoid diverging validation rules between entry points.
The GraphQL layer (apps/web/src/graphql, see GraphQL) centralizes input normalization and domain mapping so individual features do not hand-construct GraphQL variables from raw UI state. Dashboard and device-count queries (see Customer Overview) use shared filter constants (DEVICE_STATUS, DEVICE_CONNECTIVITY) from @flamingo-stack/openframe-frontend-core rather than free-form strings, which prevents malformed or inconsistent filter values from reaching the backend.
requestDownloadLink in the Auth API Client posts a honeypot field alongside the email address, and signup, password-reset, and download-link flows attach a reCAPTCHA Enterprise header when NEXT_PUBLIC_RECAPTCHA_SITE_KEY is configured (see apps/web/.env.example). When that variable is unset — the default for OSS and local development — no token is sent, which is acceptable for self-hosted deployments but would be rejected by an edge firewall that enforces the check. Do not remove the reCAPTCHA header logic from a flow without confirming the deployment target does not require it.
The Android NativeAuthPlugin.exchangeTicket method explicitly restricts ticket-exchange requests to https URLs whose path matches the pinned /oauth/dev-exchange endpoint (with repeated-slash collapsing applied before comparison). This is a deliberate narrow allow-list, not a generic "fetch any URL" bridge method — the response's token headers are handed back to page script, so an unrestricted URL would turn the plugin into an arbitrary-request proxy. Any new native bridge method that accepts a URL from JavaScript must apply the same host/scheme/path validation pattern before dispatching a native HTTP request.
Risk: Refresh tokens rotate on use and are not compare-and-swap safe. Two browser tabs refreshing concurrently can leave one tab holding an already-spent token, producing spurious sign-outs.
Mitigation: The token-refresh manager serializes refresh attempts using the Web Locks API (openframe-token-refresh lock) plus a localStorage rotation-timestamp marker that other tabs observe via the storage event. A bounded wait (refresh timeout + 10 seconds) prevents an unresponsive lock holder from blocking other tabs indefinitely. See Runtime and token refresh.
Risk: Classifying a WAF block, gateway timeout, or 5xx as "the user is signed out" causes unnecessary forced sign-outs during infrastructure incidents, and can mask real attacks behind "expected" error noise.
Mitigation: The refresh manager and useAuthSession both use an explicit three/two-state outcome model (refreshed/transient/terminal, and authenticated/signed-out/error) instead of collapsing every failure into a boolean. Only a 401/403 from /me, or a terminal refresh outcome, clears the session.
Risk: The announcement pre-paint seed script (announcementSeedScript in Announcement Cache) runs in the document head before React hydrates, reading localStorage and cookies and writing data-announcement/CSS variables onto the document root.
Mitigation: Every check in the generated script is defensive: malformed JSON, an invalid cache version, a future or expired timestamp, or an invalid regular expression in excluded_paths all cause the script to do nothing rather than throw or act on untrusted data. When modifying this script, preserve the "any uncertainty → no-op" posture; it must never execute consumer-controlled values in a way that could inject markup or scripts.
Risk: On Android, if a biometric-gated RSA key becomes permanently invalidated (for example, after enrollment changes) but the old ciphertext is left in place, re-enabling biometric login can create an infinite BIOMETRIC_INVALIDATED → re-login loop.
Mitigation: SecureTokenStore.java deletes the biometric keypair and any gated ciphertext wrapped under the deleted key on every re-enable, forcing a fresh keypair bound to the current enrollment. Follow this pattern for any new biometric-gated secret.
Risk: On desktop, a refresh-token rotation POST that never receives a response (for example, because the OS suspended mid-request) can leave the shell holding a token the server already retired, ending the session unrecoverably once the server's grace window expires.
Mitigation: apps/desktop/src-tauri/src/tokens.rs tracks wake/sleep state via monotonic-vs-wall-clock divergence, delays rotation until the machine has been continuously awake for WAKE_SETTLE_SECS, and re-presents a refresh whose outcome is "in doubt" within a bounded window (LOST_ROTATION_RETRY_AFTER_SECS..LOST_ROTATION_RETRY_WITHIN_SECS) that is deliberately inside the server's refresh-token grace period. Do not shortcut this logic when touching desktop refresh code — the constants encode measured failure windows, not arbitrary tuning.
Risk: A compromised or vulnerable third-party package could be pulled into the web or mobile build.
Mitigation: renovate.json enables osvVulnerabilityAlerts and vulnerabilityAlerts org-wide, and enforces a 7-day minimum release age for ordinary npm dependencies (minimumReleaseAge: "7 days") before they are offered, reducing exposure to just-published malicious or broken releases. The @flamingo-stack/openframe-frontend-core dependency is pinned via a custom regex manager tied to the upstream repository's tagged releases rather than an arbitrary preview build, and is grouped with elevated PR priority so security-relevant updates to shared UI/auth code are not lost among routine dependency noise.
The devices feature includes an explicit outdated-client-banner.tsx and use-outdated-client-facet.ts (under apps/web/src/app/(app)/devices) surfacing agents running old client versions. Outdated managed-device agents are a security exposure (missed patches, deprecated protocols); keep this facet wired into device-list filtering rather than treating it as cosmetic.
renovate.json governs automated dependency hygiene for this repository:
osvVulnerabilityAlerts: trueandvulnerabilityAlerts.enabled: truesurface known CVEs across npm, GitHub Actions, and Dockerfile-managed dependencies.- GitHub Actions versions are grouped and given a 3-day minimum release age before being offered, balancing CI stability against prompt patching.
- Docker base images are pinned by digest (
pinDigests: true) and a Node major-version bump is deliberately excluded from automatic PRs (enabled: falseformatchUpdateTypes: ["major"]), since a runtime major bump is a decision, not a routine patch.
Per the ecosystem graph, this repository builds and publishes container images through two workflows:
| Workflow | Image | Purpose |
|---|---|---|
.github/workflows/release.yml |
ghcr.io/flamingo-stack/openframe-oss-frontend/openframe-oss-frontend |
Release build |
.github/workflows/test.yml |
ghcr.io/flamingo-stack/openframe-oss-frontend/openframe-oss-frontend |
Test/CI build |
Both workflows generate image metadata before publishing. Any change to authentication, token handling, or native bridge code should be validated through these CI pipelines before merge, since the published image is what downstream deployments actually run.
Because no automated code-review rule catalog is currently published for this repository, reviewers should apply the architectural invariants documented above as manual review criteria. When reviewing a pull request that touches authentication, tokens, or storage, confirm:
- No token ever reaches
useAuthStore's persisted fields. Onlyuser,isAuthenticated, andtenantIdbelong there. - No new code treats a non-
401/403response as "signed out." Check that failures are routed through the existing transient/terminal classification instead of a new ad hoc check. - No new native bridge method accepts an unrestricted URL or token value from JavaScript. Apply the scheme/host/path allow-list pattern used in
NativeAuthPlugin.exchangeTicket. - No new
localStorage/sessionStorageread assumes success. Wrap in try/catch and treat failure as a cache miss, matching the announcement-cache and session-health patterns. - No new form submits without schema validation. Use Zod plus
react-hook-form, and re-validate anything whose correctness could have gone stale between a debounced check and submission (the tenant-subdomain pattern). - No secret or credential is logged. Verified SSO identities, signup tickets, and reCAPTCHA tokens must never be written to
console.log, analytics events, or error-reporting payloads. - ESLint custom rules are respected. This repository ships custom ESLint rules under
apps/web/eslint-rules/(component-shape.mjs,form-label-scale.mjs,no-graphql-folder.mjs,react-hook-form-needs-no-memo.mjs, registered inapps/web/eslint-rules/index.mjs). Run the configured lint scripts before submitting a PR that touches forms or GraphQL-adjacent code, since these rules encode conventions the automated reviewer and CI expect.
For broader contribution and review expectations beyond security, see Contributing Guidelines and the general Testing documentation.
- Session edge cases: authenticated, signed-out (
401/403), and transient-failure states foruseAuthSession, per the matrix implied in Auth architecture. - Refresh races: stale-epoch
401s, cross-tab serialization, and bearer-mode rotation without a replacement access token, per Runtime and token refresh. - Session-health transition matrix: every transition in the
healthy/paused/gonestate machine, including that agonestate cannot be revived by anything exceptresetSessionHealth()— see Session Health. - Approval decision ordering: that local UI state never reflects an approval/rejection before the server mutation succeeds, per Approvals.
- Route guard policy: allowed/denied rendering for each application mode and shell combination, per Route Guard.
The web application's environment contract is defined in apps/web/.env.example. Every variable there is a NEXT_PUBLIC_* value, meaning it is bundled into client-side JavaScript and is not a secret:
# OpenFrame React Frontend Environment Variables
NEXT_PUBLIC_ENABLE_DEV_TICKET_OBSERVER=false
NEXT_PUBLIC_AUTH_CHECK_INTERVAL=60000
NEXT_PUBLIC_APP_MODE=oss-tenant
NEXT_PUBLIC_GTM_CONTAINER_ID=
NEXT_PUBLIC_RECAPTCHA_SITE_KEY=
NEXT_PUBLIC_BREW_CASK=
NEXT_PUBLIC_SUPABASE_HOST=
NEXT_PUBLIC_FEATURE_SCRIPT_SCHEDULE=false
NEXT_PUBLIC_PR_NUMBER_ENABLED=false| Variable | Purpose | Security Note |
|---|---|---|
NEXT_PUBLIC_ENABLE_DEV_TICKET_OBSERVER |
Enables automatic devTicket detection/exchange for SSO | Should remain false outside development; the dev-ticket flow is a non-production authentication shortcut |
NEXT_PUBLIC_AUTH_CHECK_INTERVAL |
Polling interval (ms) for session checks | Lowering it increases request volume against the auth gateway |
NEXT_PUBLIC_APP_MODE |
One of oss-tenant, saas-tenant, saas-shared |
Drives RouteGuard policy; do not treat as a secret, but do not misconfigure in production either |
NEXT_PUBLIC_RECAPTCHA_SITE_KEY |
reCAPTCHA Enterprise site key | Public by design (site keys are not secret); unset = no token sent, acceptable for OSS/local, refused by a SaaS edge that enforces the check |
NEXT_PUBLIC_BREW_CASK |
Homebrew cask name for the install command shown in the devices UI | Cosmetic; not security-sensitive |
NEXT_PUBLIC_SUPABASE_HOST |
Hub Supabase project host for direct (non-proxied) image loads | Only needed when pointing at a non-default hub project |
NEXT_PUBLIC_FEATURE_SCRIPT_SCHEDULE |
Feature flag for script scheduling | Not security-sensitive |
NEXT_PUBLIC_PR_NUMBER_ENABLED |
Shows a PR-number field on signup, for test registrations | Must stay disabled on staging and production |
No true secret belongs in
NEXT_PUBLIC_*variables. Anything prefixedNEXT_PUBLIC_is inlined into the client JavaScript bundle at build time and is visible to anyone who loads the page. Treat every value inapps/web/.env.exampleas public configuration, never as a credential.
This repository's client code does not hold backend credentials, database passwords, or signing keys. Authentication material is handled as follows:
- Session cookies and bearer tokens are issued by the backend authentication gateway and held by the browser's cookie jar or the platform-specific secure token store described in Data Encryption And Secure Storage — never by application environment variables.
- Native shell secrets (Android Keystore keys, desktop OS-level secure storage) are generated and held on-device; they are never derived from or exposed through build-time environment variables.
- reCAPTCHA uses only the public site key client-side; the corresponding secret key is a server-side concern outside this repository.
If your work requires a credential that is not already represented as a NEXT_PUBLIC_* configuration value or a platform-specific secure store entry, do not invent a new plaintext environment variable for it — raise the requirement so it can be routed through the appropriate backend or native secure-storage mechanism. For local environment setup beyond security, see Environment Setup and Local Development.
CI publishes images to ghcr.io/flamingo-stack/openframe-oss-frontend/openframe-oss-frontend from .github/workflows/release.yml and .github/workflows/test.yml. Any credential those workflows need (registry authentication, signing) is managed as CI-platform secrets, not as repository files — this document intentionally does not enumerate CI secret names, since they are not part of the application's own configuration surface.
- Copy
apps/web/.env.exampleto a local.envfile (not committed) and adjust values for your environment. - Keep
NEXT_PUBLIC_PR_NUMBER_ENABLEDandNEXT_PUBLIC_ENABLE_DEV_TICKET_OBSERVERdisabled unless you are actively testing the corresponding flow. - Do not commit a populated
.envfile.apps/web/.env.exampleexists specifically so real values stay out of version control.
For the broader local setup process, including how these variables fit into running the application, see Environment Setup, Local Development, and Quick Start.
This document focuses on security practices specific to this repository's authentication orchestration, token handling, and client-side storage. For the surrounding architecture these mechanisms plug into, see Auth, Route Guard, Session Health, and the Architecture Overview. For privacy and data-handling commitments at the product level, see apps/mobile/SECURITY.md, which documents the Flamingo AI Privacy Policy covering self-hosted OpenFrame deployments, OpenMSP, and the Flamingo website.