Skip to content

feat(auth): auto-mint browser session from verified Cloudflare Access JWT - #228

Merged
nullStack65 merged 2 commits into
release/native-0.1.10from
feat/cf-access-auto-session
Nov 26, 2026
Merged

nullStack65 merged 2 commits into
release/native-0.1.10from
feat/cf-access-auto-session

Conversation

@nullStack65

Copy link
Copy Markdown
Owner

Summary

Eliminates the /pair redirect when founders open https://t3code.closura.ai (or https://t3code-staging.closura.ai) after authenticating through Cloudflare Access (closura.cloudflareaccess.com), by verifying the Cloudflare Access JWT fail-closed and automatically minting a founder-attributed T3 browser session cookie on GET /api/auth/session.

Key Changes

  1. Opt-in configuration (apps/server/src/auth/CloudflareAccessConfig.ts):
    • Disabled by default; requires T3CODE_CF_ACCESS_AUTH_ENABLED=true plus complete, unambiguous configuration:
      • T3CODE_CF_ACCESS_TEAM_DOMAIN (HTTPS origin, e.g. https://closura.cloudflareaccess.com)
      • T3CODE_CF_ACCESS_AUD (comma-separated audience tags so a single host can serve both production and staging Access apps)
      • T3CODE_CF_ACCESS_ALLOWED_ORIGINS (comma-separated HTTPS origins, e.g. https://t3code.closura.ai,https://t3code-staging.closura.ai)
      • T3CODE_CF_ACCESS_KAMERON_EMAIL / T3CODE_CF_ACCESS_JEFF_EMAIL (comma-separated email aliases per founder, normalized lowercase/trimmed, strictly disjoint)
    • Incomplete, non-HTTPS, or overlapping founder configurations fail closed with a warning.
  2. Fail-closed JWT verification & auto-session minting (apps/server/src/auth/CloudflareAccessAuth.ts):
    • Extracts JWT from Cf-Access-Jwt-Assertion header (with CF_Authorization cookie fallback); never trusts unverified email headers.
    • Verifies RS256 signature against ${teamDomain}/cdn-cgi/access/certs JWKS with 30m cache (cacheMaxAge), 30s rate-limited refresh on unknown kid (cooldownDuration), and 5s fetch timeout (timeoutDuration).
    • Enforces exact iss, exact aud, iat/exp, type === "app" (rejects service tokens), ManagedLimits.allowsRemoteClients, and exact founder email allowlist.
    • Handles mobile Safari/Chrome same-origin GET /api/auth/session requests that omit the Origin header by validating Host + X-Forwarded-Proto against T3CODE_CF_ACCESS_ALLOWED_ORIGINS, while rejecting cross-origin Origin and cross-site Sec-Fetch-Site.
    • Mints a standard browser-session-cookie (AuthStandardClientScopes, founder attributed, subject: cf-access:<sha256>, TTL capped at earlier of JWT exp and 8h).
  3. Session bootstrap & revocation (apps/server/src/auth/http.ts, apps/server/src/auth/EnvironmentAuth.ts, apps/server/src/server.ts):
    • GET /api/auth/session auto-mints and sets the HttpOnly; Secure; SameSite=Lax T3 session cookie on unauthenticated requests carrying a valid CF Access JWT, returning { authenticated: true, ... } immediately (zero /pair redirect).
    • EnvironmentAuth.assertCloudflareAccessSession rejects existing cf-access: sessions immediately if the feature flag is disabled, config/enrollment changes, remote clients are disallowed, or origin mismatches.

Verification

  • pnpm exec effect-tsgo tsrs -p apps/server/tsconfig.json --noEmit — 0 errors
  • vp test run src/auth/CloudflareAccessAuth.test.ts src/auth/http.test.ts src/auth/WorkOsAuth.test.ts src/auth/EnvironmentAuth.test.ts — 45/45 passed (covers config validation, RS256/iss/aud/exp/iat/type/alias verification, mobile GET without Origin, cross-origin/wrong-host/header-spoof rejection, founder attribution, JWKS kid rotation refresh, and ManagedPolicy remote-client enforcement).

Deploy: fleet

@coderabbitai

coderabbitai Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

Important

  • Trigger review

This repository does not receive automatic reviews because it has fewer than 10 stars.

Run configuration

  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@nullStack65

Copy link
Copy Markdown
Owner Author
{
  "reviewed_base": "6caa9994a0a4d72f057e9b6a9cf25c417dcec124",
  "reviewed_head": "6a8e4a89b027624decb7744cf038921d729cceeb",
  "reviewer": "Gemini 4 Neon, Antigravity",
  "author_session": "t3-thread:6a6b870263499e5c3c4ceec5efb20d31b46884a74e0c45beedb1a4cddb9ac991",
  "reviewer_session": "antigravity:c994b558-deac-4de7-93f6-39d0a0eb4d7b",
  "fresh_context": true,
  "review_kind": "full",
  "round_id": "antigravity:c994b558-deac-4de7-93f6-39d0a0eb4d7b",
  "prior_findings": [],
  "findings": [
    {
      "id": "F1",
      "severity": "important",
      "outcome": "open",
      "file": "apps/server/src/auth/EnvironmentAuth.ts",
      "line": 1808,
      "summary": "authenticateWebSocketUpgrade skips assertCloudflareAccessSession on the wsTicket path, allowing wsTickets minted from cf-access: sessions to bypass disabled/config-change revocation, ManagedLimits.allowsRemoteClients, and allowed-origin enforcement."
    },
    {
      "id": "F2",
      "severity": "nit",
      "outcome": "open",
      "file": "apps/server/src/persistence/AuthSessions.ts",
      "line": 390,
      "summary": "WorkOS parity hardening: AuthSessions.ts setFounderRows does not exclude cf-access:* subjects (allowing another auth:write client to overwrite cryptographically bound founder attribution), and EnvironmentAuth.ts revokePairedClientsThePolicyDisallows (line 2074) does not proactively revoke cf-access: browser sessions at startup when remote clients are disallowed."
    }
  ]
}

Independent Security & Correctness Review (6a8e4a89b027)

Verified Invariants

  • Cryptographic JWT verification (CloudflareAccessAuth.ts, CloudflareAccessConfig.ts): Strict RS256 pinning via jose jwtVerify (checked before key resolution; rejects none/HS256/mismatched key types), exact iss and aud (handles string and string[]), exp/nbf/iat (+60s skew) checks, type === "app" (rejects service tokens), email read exclusively from verified payload, trimmed/lowercased against disjoint founder allowlists. JWKS uses 30m cacheMaxAge, 30s cooldownDuration, 5s timeoutDuration, single-flight deduplication, and redirect: "manual" fail-closed.
  • Origin / CSRF / Mobile UX (auth/http.ts, CloudflareAccessAuth.ts, requestUrl.ts): Handles mobile Safari/Chrome same-origin GET /api/auth/session without Origin via requestUrl(request) (Host + strict X-Forwarded-Proto === "https" fail-closed) against HTTPS allowedOrigins, rejecting mismatched Origin and cross-site/same-site Sec-Fetch-Site. Sets HttpOnly; Path=/; SameSite=Lax; Secure with Cache-Control: no-store. CF_Authorization cookie parsing via Effect Cookies.parseHeader safely handles = and multiple cookies.
  • Verification: pnpm exec effect-tsgo tsrs -p apps/server/tsconfig.json --noEmit passed with 0 errors; vp test run on CloudflareAccessAuth.test.ts, http.test.ts, WorkOsAuth.test.ts, and EnvironmentAuth.test.ts passed 45/45 tests.

Findings

  • F1 (important) — apps/server/src/auth/EnvironmentAuth.ts:1808: In authenticateWebSocketUpgrade, the wsTicket branch calls yield* assertWorkOsSession(session, request, true); but omits yield* assertCloudflareAccessSession(session, request, true);. Because any authenticated cf-access: browser session can mint wsTickets (POST /api/auth/ws-ticket / /ws-ticket/:use), a ticket minted from a cf-access: session bypasses assertCloudflareAccessSession on WebSocket upgrades and authenticateMediaRequest (skipping disabled/config-change rejection, ManagedLimits.allowsRemoteClients, and allowedOrigins / Origin === requestOrigin checks). Add yield* assertCloudflareAccessSession(session, request, true); and a regression test.
  • F2 (nit) — apps/server/src/persistence/AuthSessions.ts:390 & apps/server/src/auth/EnvironmentAuth.ts:2074: Mirror WorkOS parity by excluding CLOUDFLARE_ACCESS_SUBJECT_PREFIX + "*" in setFounderRows (so another client cannot overwrite verified founder attribution) and including CLOUDFLARE_ACCESS_SUBJECT_PREFIX in revokePairedClientsThePolicyDisallows on startup.

@nullStack65

Copy link
Copy Markdown
Owner Author
{
  "reviewed_base": "6caa9994a0a4d72f057e9b6a9cf25c417dcec124",
  "reviewed_head": "eb132c6b08c38eac8fcc811f43d7542107140bae",
  "reviewer": "Gemini 4 Neon, Antigravity",
  "author_session": "t3-thread:6a6b870263499e5c3c4ceec5efb20d31b46884a74e0c45beedb1a4cddb9ac991",
  "reviewer_session": "antigravity:9da2c2a0-a67a-4507-b936-0adccb8c0770",
  "fresh_context": true,
  "review_kind": "focused_recheck",
  "round_id": "antigravity:c994b558-deac-4de7-93f6-39d0a0eb4d7b",
  "prior_findings": ["F1", "F2"],
  "findings": [
    {
      "id": "F1",
      "severity": "important",
      "outcome": "confirmed",
      "rechecked_head": "eb132c6b08c38eac8fcc811f43d7542107140bae",
      "file": "apps/server/src/auth/EnvironmentAuth.ts",
      "line": 1809,
      "summary": "authenticateWebSocketUpgrade now invokes assertCloudflareAccessSession(session, request, true) on the wsTicket path right after assertWorkOsSession; regression test verifies allowed-origin upgrade succeeds and mismatched-origin upgrade fails."
    },
    {
      "id": "F2",
      "severity": "nit",
      "outcome": "fixed",
      "rechecked_head": "eb132c6b08c38eac8fcc811f43d7542107140bae",
      "file": "apps/server/src/persistence/AuthSessions.ts",
      "line": 392,
      "summary": "WorkOS parity hardening applied: setFounderRows excludes CLOUDFLARE_ACCESS_SUBJECT_PREFIX + \"*\" (with regression test confirming setFounder returns false and preserves attributed founder), and revokePairedClientsThePolicyDisallows includes cf-access: browser sessions when remote clients are disallowed."
    }
  ]
}

Focused Cross-Family Re-Check (6a8e4a89b027..eb132c6b08c3)

  • F1 (important, confirmed): apps/server/src/auth/EnvironmentAuth.ts:1809 now runs yield* assertCloudflareAccessSession(session, request, true); on the wsTicket upgrade path, matching assertWorkOsSession. Every assertWorkOsSession call site now has a matching assertCloudflareAccessSession call. Regression test in CloudflareAccessAuth.test.ts confirms a wsTicket minted from a cf-access: session succeeds on an allowed origin and fails on a mismatched origin.
  • F2 (nit, fixed): apps/server/src/persistence/AuthSessions.ts:392 excludes CLOUDFLARE_ACCESS_SUBJECT_PREFIX + "*" in setFounderRows (regression test confirms setFounder returns false and preserves "jeff"), and apps/server/src/auth/EnvironmentAuth.ts:2075-2076 revokes cf-access: browser-session-cookie sessions on startup in revokePairedClientsThePolicyDisallows when !remoteAllowed.
  • Verification (eb132c6b08c3):
    • pnpm exec effect-tsgo tsrs -p apps/server/tsconfig.json --noEmit — passed (0 errors).
    • vp test run src/auth/CloudflareAccessAuth.test.ts src/auth/EnvironmentAuth.test.ts — passed (37/37 tests).
    • vp test run src/auth/SessionStore.test.ts src/auth/EnvironmentAuthPolicy.test.ts — passed (28/28 tests).
  • Regressions: None observed.

@nullStack65
nullStack65 merged commit 7682d14 into release/native-0.1.10 Nov 26, 2026
6 checks passed
@nullStack65
nullStack65 deleted the feat/cf-access-auto-session branch November 26, 2026 06:20
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant