Skip to content

Latest commit

 

History

History
287 lines (182 loc) · 30.6 KB

README.md

File metadata and controls

287 lines (182 loc) · 30.6 KB

Security

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-core as a published npm dependency (installed from https://pkg.pr.new/flamingo-stack/openframe-oss-lib/@flamingo-stack/openframe-frontend-core@0.0.977) and async_nats from 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.

Table Of Contents

Authentication And Authorization

Overview

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"]
Loading

Session Verification Is The Source Of Truth

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.

Token Refresh And Rotation

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 401 alone does not prove the session is dead. The manager returns a three-state outcome — refreshed, transient, or terminal — and only terminal should ever trigger sign-out.
  • Refresh calls are serialized within a browser tab and across tabs using the Web Locks API plus a token-free localStorage rotation 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 as refreshed, 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.

Native Shell Token Custody

  • 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 as PageTokens, 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 (see REFRESH_MARGIN_SECS, WAKE_SETTLE_SECS in 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.

SSO And Ticket-Based Flows

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.

Route-Level Authorization

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 RouteGuard happens 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.

Approval Workflows As An Authorization Pattern

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 CLIENT are excluded from the technician inbox by design — do not relax that filter without confirming the intended audience for the action.

Data Encryption And Secure Storage

Storage Classification

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

Principles For Secure Storage

  1. 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, Android SecureTokenStore, desktop tokens.rs).
  2. 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.
  3. 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.
  4. 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.

Tenant-Deletion Signal As A Storage Boundary

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 410 from a tenant service (for example, a missing recording) is not tenant deletion.
  • A 410 from 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.

Input Validation And Sanitization

Schema-Driven Form Validation

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.

Tenant Subdomain Validation

useOrganizationDomain (described in Auth architecture) is the single owner of tenant-domain sanitization for password signup, browser SSO continuation, and native Apple signup. It:

  1. Sanitizes input to the accepted subdomain character set before ever sending it to the server.
  2. Performs a debounced availability check for UX feedback.
  3. 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.

GraphQL And Query Input Normalization

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.

Honeypot And Bot Mitigation

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.

Native Deep-Link And URL Validation

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.

Common Vulnerabilities And Mitigations

Cross-Tab Credential Races (Refresh-Token Reuse)

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.

Treating Transient Failures As Session Termination

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.

Layout-Shift And Pre-Paint Script Injection Surface

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.

Native Keystore Key Invalidation Loop

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.

Lost Refresh Rotation During Device Sleep

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.

Dependency Supply-Chain Exposure

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.

Outdated-Client Risk

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.

Security Testing And Code Review

Automated Dependency And Vulnerability Scanning

renovate.json governs automated dependency hygiene for this repository:

  • osvVulnerabilityAlerts: true and vulnerabilityAlerts.enabled: true surface 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: false for matchUpdateTypes: ["major"]), since a runtime major bump is a decision, not a routine patch.

CI Delivery And Image Builds

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.

Review Focus Areas For This Repository

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:

  1. No token ever reaches useAuthStore's persisted fields. Only user, isAuthenticated, and tenantId belong there.
  2. No new code treats a non-401/403 response as "signed out." Check that failures are routed through the existing transient/terminal classification instead of a new ad hoc check.
  3. 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.
  4. No new localStorage/sessionStorage read assumes success. Wrap in try/catch and treat failure as a cache miss, matching the announcement-cache and session-health patterns.
  5. 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).
  6. 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.
  7. 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 in apps/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.

What To Test Explicitly

  • Session edge cases: authenticated, signed-out (401/403), and transient-failure states for useAuthSession, 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/gone state machine, including that a gone state cannot be revived by anything except resetSessionHealth() — 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.

Environment Variables And Secrets Management

Public Runtime Configuration

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 prefixed NEXT_PUBLIC_ is inlined into the client JavaScript bundle at build time and is visible to anyone who loads the page. Treat every value in apps/web/.env.example as public configuration, never as a credential.

Where Actual Credentials Live

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.

Build And Release Secrets

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.

Handling .env Files Locally

  1. Copy apps/web/.env.example to a local .env file (not committed) and adjust values for your environment.
  2. Keep NEXT_PUBLIC_PR_NUMBER_ENABLED and NEXT_PUBLIC_ENABLE_DEV_TICKET_OBSERVER disabled unless you are actively testing the corresponding flow.
  3. Do not commit a populated .env file. apps/web/.env.example exists 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.

Related Reading

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.