Skip to content

fix(desktop): keep bootstrap and retained Den sessions origin-coherent - #4050

Merged
reachjalil merged 1 commit into
devfrom
fix/bootstrap-session-origin-coherence
Aug 24, 2026
Merged

reachjalil merged 1 commit into
devfrom
fix/bootstrap-session-origin-coherence

Conversation

@reachjalil

Copy link
Copy Markdown
Member

Problem

On Desktop, a user connected to a self-hosted OpenWork server could reopen the app and have it briefly treat their organization server as the hosted default. If the Electron shell's bootstrap bridge was missing, delayed, or failing at first paint, the renderer fell back to https://app.openworklabs.com while localStorage still held the bearer token and active organization from the prior self-hosted session. The result was an invalid mixed state: hosted/fallback base URL, self-hosted token, self-hosted organization — and any Den feature that woke up in that window could send the retained credentials to an origin that never issued them.

This is a source-confirmed unsafe state transition: the fallback path in initializeDenBootstrapConfig() installed the hosted default as a fully "resolved-looking" bootstrap while readDenSettings() independently kept exposing the retained token and organization from storage. No production incident is claimed.

Root cause

Bootstrap resolution and retained-session hydration were independently authoritative:

  • the shell-read fallback produced a config indistinguishable from a genuinely resolved hosted selection, and
  • readDenSettings() unconditionally attached the stored token/org to whatever base URL the bootstrap snapshot currently held,

with nothing recording which origin issued the retained token and nothing guarding late async bootstrap results from earlier startup attempts.

Invariant

The Den base URL, bearer token, active organization, and bootstrap generation used for a credential-bearing operation must belong to one coherent, successfully resolved enrollment generation. When origin coherence is unknown, local workspace startup continues, Den-dependent authenticated operations stay unavailable, and retained credentials are sent nowhere.

Solution

  • Explicit resolution state. The bootstrap snapshot is now resolved (preload snapshot, shell IPC read, or explicit persist) or unresolved (in-memory fallback while the bridge is unavailable). The fallback is a recovery placeholder, never an authoritative hosted selection, and is still never persisted.
  • Session origin tag. writeDenSettings() records the issuing control-plane origin (openwork.den.sessionOrigin) next to the token; clearDenSession() removes it. Legacy untagged sessions are adopted for the origin the bootstrap actually resolves to, at authoritative boot-time resolution only.
  • One credential gate. readDenSettings() — the single choke point every Den credential consumer already uses — withholds the token and organization whenever the bootstrap is unresolved or resolved to a different origin than the one recorded with the token. Quarantine hides credentials without deleting them, and passive writes cannot delete a session they never saw; the session revives when its own origin resolves (including via the delayed background heal, which notifies listeners).
  • Startup generation guard. A monotonic generation counter ties each async bootstrap resolution (quick retries, background heal, shell refresh) to the startup attempt that began it; explicit persists retire in-flight generations, so a late result from an obsolete boot can never replace the current config.
  • Sanitized diagnostics. State transitions log fixed strings only — no tokens, cookies, grants, or URLs.

Preservation

  • A valid preload bootstrap remains the immediate fast path.
  • Genuinely configured hosted sessions keep working, including while the bridge is briefly down (their recorded origin matches the fallback origin).
  • Genuinely configured self-hosted sessions keep working and re-enable automatically once their own bootstrap resolves.
  • Local workspace startup is not blocked while Den bootstrap recovery is pending; logged-out and local-only users see no Den authentication.
  • Compatible retained state is never discarded: quarantine is storage-preserving and legacy sessions are adopted, not dropped.

Proof

Check Command Verdict
Testkit proof (exact head, local lane) pnpm --dir evals exec vitest run --config vitest.config.ts specs/den-bootstrap-origin-coherence.test.ts Passed
Focused matrix suite (13 tests, HTTP witnesses) pnpm --dir apps/app exec bun test --isolate tests/den-bootstrap-origin-coherence.test.ts Passed
App unit suite pnpm --filter @openwork/app exec bun test --isolate tests/ 872 pass; same 7 pre-existing failures also fail on the base commit (verified before this change)
App typecheck pnpm --filter @openwork/app run typecheck Passed
Evals PR lane pnpm evals:pr 40 passed, 2 named skips; world-attach.test.ts failed once on a parallel den-db asset-build race (ENOTEMPTY in build-assets.mjs, unrelated) and passed on isolated rerun
Adjacent credential-coherence spec pnpm --dir evals exec vitest run --config vitest.config.ts specs/desktop-server-credential-coherence.test.ts Passed

The testkit spec drives the real Den settings module against deterministic loopback control-plane witnesses — real HTTP servers that record every Authorization header they receive — plus a scriptable shell bridge and a main-process fetch seam that records what would leave the machine for non-loopback origins.

Negative proof

With a retained self-hosted token and an unresolved bootstrap, the witnesses record zero requests carrying an Authorization header to any origin, and the recorded main-process egress shows none addressed to the hosted fallback. When the bootstrap resolves to a different origin than the token's issuer, neither origin receives a credential-bearing request, while the quarantined session provably survives in storage.

Risk and rollback

  • Compatibility: pre-existing sessions have no origin tag; they are adopted at the first authoritative bootstrap resolution, matching the origin those builds already used. Until resolution succeeds, a legacy session is quarantined instead of being sent to an unproven origin — that withholding is the intended behavior change.
  • Blast radius is one module (apps/app/src/app/lib/den.ts); all gating flows through readDenSettings()/writeDenSettings(). Rolling back this commit restores prior behavior; the extra openwork.den.sessionOrigin key is ignored by older builds.

Scope exclusions

This PR does not redesign cross-server handoff, general desktop-policy convergence, deployment, or release behavior. It only enforces origin coherence between the desktop bootstrap and the retained Den session.

When the shell bootstrap bridge is missing or delayed at first paint, the
renderer fell back to the hosted default while localStorage still held a
bearer token and active organization from a prior self-hosted Den. That mixed
state could send retained credentials to an origin that was never proven to
own them.

Represent the fallback as an unresolved bootstrap instead of a resolved
hosted selection, record the issuing origin next to the token, and gate every
credential read through one origin-coherence check in readDenSettings():
credentials are only visible when the resolved bootstrap origin matches the
origin that issued them. Quarantined sessions stay in storage (passive writes
cannot delete what they never saw) and revive when their own origin resolves,
including through the delayed background heal. A startup generation counter
discards late bootstrap results from obsolete boots.

Valid preload bootstraps, hosted sessions, self-hosted sessions, and
local-only startup keep working; legacy untagged sessions are adopted for the
origin the bootstrap actually resolves to.
@vercel

vercel Bot commented Aug 24, 2026 •

Copy link
Copy Markdown
Contributor

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
openwork-app Ready Ready Preview Aug 24, 2026 11:05pm
openwork-den Ready Ready Preview Aug 24, 2026 11:05pm
openwork-den-worker-proxy Ready Ready Preview Aug 24, 2026 11:05pm
openwork-diagnostics Ready Ready Preview Aug 24, 2026 11:05pm
openwork-landing Ready Ready Preview, v0 Aug 24, 2026 11:05pm

@diff-warden diff-warden Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Warden security clearance: clear. No blocking findings (security or desktop↔den sync) in this diff (ac8a507e58ca443e443454edacfd463ec150f007). Automated clearance satisfies the required-review gate only — a human still reviews and merges. Analysis run

@reachjalil
reachjalil merged commit c7e3781 into dev Aug 24, 2026
18 checks passed
reachjalil added a commit that referenced this pull request Aug 24, 2026
A Desktop handoff for control plane B could partially succeed while control
plane A stayed active: the bearer token, active organization, durable
bootstrap origin, and renderer success state each transitioned independently,
so a bootstrap write failure, app exit, concurrent attempt, or missing
destination organization could leave a hybrid enrollment (B's token active
against A's persisted origin, A's organization leaking into B, or UI success
published before the durable commit).

Make the handoff a single enrollment transaction in exchangeHandoffAndSignIn,
which every entry point (deep link, pasted code, control action, prepared
bootstrap, enterprise activation) already funnels through:

- resolve the destination once (including its published runtime-config API
  base) and construct the exchange client from it, so the grant can only be
  sent to — and the credential can only come from — the origin that will be
  persisted; the redundant caller-supplied client option is removed
- persist the destination bootstrap durably, then confirm the committed
  bootstrap is the intended destination before anything becomes active,
  folding enterprise activation stamps and consumed-grant cleanup into the
  same commit instead of separate follow-up writes
- publish origin, token, and organization in one write; an organization never
  carries into a different origin unless the destination returns one
- roll back to the previous coherent enrollment when persistence, read-back
  confirmation, or activation fails, and report consumed one-time grants as
  non-retriable so entry points stop replaying spent grants
- serialize commits and reject late results from superseded attempts so
  concurrent handoffs cannot interleave or cross their fields

Crash windows between the durable bootstrap commit and the session write are
covered by the session-origin coherence gate introduced in #4050: the
transaction's single activation write stamps the issuing origin, so an
interrupted commit resumes as signed-out-at-the-destination, never as a
hybrid of two control planes.
reachjalil added a commit that referenced this pull request Aug 28, 2026
A Desktop handoff for control plane B could partially succeed while control
plane A stayed active: the bearer token, active organization, durable
bootstrap origin, and renderer success state each transitioned independently,
so a bootstrap write failure, app exit, concurrent attempt, or missing
destination organization could leave a hybrid enrollment (B's token active
against A's persisted origin, A's organization leaking into B, or UI success
published before the durable commit).

Make the handoff a single enrollment transaction in exchangeHandoffAndSignIn,
which every entry point (deep link, pasted code, control action, prepared
bootstrap, enterprise activation) already funnels through:

- resolve the destination once (including its published runtime-config API
  base) and construct the exchange client from it, so the grant can only be
  sent to — and the credential can only come from — the origin that will be
  persisted; the redundant caller-supplied client option is removed
- persist the destination bootstrap durably, then confirm the committed
  bootstrap is the intended destination before anything becomes active,
  folding enterprise activation stamps and consumed-grant cleanup into the
  same commit instead of separate follow-up writes
- publish origin, token, and organization in one write; an organization never
  carries into a different origin unless the destination returns one
- roll back to the previous coherent enrollment when persistence, read-back
  confirmation, or activation fails, and report consumed one-time grants as
  non-retriable so entry points stop replaying spent grants
- serialize commits and reject late results from superseded attempts so
  concurrent handoffs cannot interleave or cross their fields

Crash windows between the durable bootstrap commit and the session write are
covered by the session-origin coherence gate introduced in #4050: the
transaction's single activation write stamps the issuing origin, so an
interrupted commit resumes as signed-out-at-the-destination, never as a
hybrid of two control planes.
reachjalil added a commit that referenced this pull request Sep 3, 2026
* fix(desktop): commit cross-server handoffs atomically

A Desktop handoff for control plane B could partially succeed while control
plane A stayed active: the bearer token, active organization, durable
bootstrap origin, and renderer success state each transitioned independently,
so a bootstrap write failure, app exit, concurrent attempt, or missing
destination organization could leave a hybrid enrollment (B's token active
against A's persisted origin, A's organization leaking into B, or UI success
published before the durable commit).

Make the handoff a single enrollment transaction in exchangeHandoffAndSignIn,
which every entry point (deep link, pasted code, control action, prepared
bootstrap, enterprise activation) already funnels through:

- resolve the destination once (including its published runtime-config API
  base) and construct the exchange client from it, so the grant can only be
  sent to — and the credential can only come from — the origin that will be
  persisted; the redundant caller-supplied client option is removed
- persist the destination bootstrap durably, then confirm the committed
  bootstrap is the intended destination before anything becomes active,
  folding enterprise activation stamps and consumed-grant cleanup into the
  same commit instead of separate follow-up writes
- publish origin, token, and organization in one write; an organization never
  carries into a different origin unless the destination returns one
- roll back to the previous coherent enrollment when persistence, read-back
  confirmation, or activation fails, and report consumed one-time grants as
  non-retriable so entry points stop replaying spent grants
- serialize commits and reject late results from superseded attempts so
  concurrent handoffs cannot interleave or cross their fields

Crash windows between the durable bootstrap commit and the session write are
covered by the session-origin coherence gate introduced in #4050: the
transaction's single activation write stamps the issuing origin, so an
interrupted commit resumes as signed-out-at-the-destination, never as a
hybrid of two control planes.

* fix(desktop): verify the published API origin before routing the handoff grant

A destination's runtime-published denApiUrl is adopted for the one-time
handoff exchange only when it is same-origin with the destination web
origin or its deterministic hosted API sibling; every other published
value keeps the exchange on the destination's own /api/den proxy.

Cross-origin handoff commits now clear the previous origin's enterprise
activation stamp explicitly, so a new control plane can never inherit an
activation recorded against a different Den base URL.

This branch was successfully deployed

5 active deployments
Preview – openwork-den-worker-proxy — ac8a507e Deployed Aug 24, 2026 by vercel[bot]
Preview – openwork-landing — ac8a507e Deployed Aug 24, 2026 by vercel[bot]
Preview – openwork-den — ac8a507e Deployed Aug 24, 2026 by vercel[bot]
Preview – openwork-app — ac8a507e Deployed Aug 24, 2026 by vercel[bot]
Preview – openwork-diagnostics — ac8a507e Deployed Aug 24, 2026 by vercel[bot]
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