Skip to content

fix(browser): restore replaced cookies through CDP identities - #14383

Merged
brennanb2025 merged 2 commits into
mainfrom
brennanb2025/sta-4097-cookie-rollback-sites
Aug 14, 2026
Merged

brennanb2025 merged 2 commits into
mainfrom
brennanb2025/sta-4097-cookie-rollback-sites

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

ELI5

When you import cookies and the import fails halfway, Orca tries to put your old cookies back. It was rebuilding them with an Electron API that cannot see or write a cookie's partition. So a cookie that was scoped to one specific site-embedding context came back as a plain, global cookie — same name, same value, wrong scope, forever. This makes the undo travel back through CDP instead, which does carry the partition.

What Changed

replaceCookiesForImportedDomains now snapshots CDP cookie identities before it removes anything, and undoes removals through restoreClearIdentities instead of cookies.set.

  • browser-cookie-import-policy.ts — the store parameter is now Pick<Cookies, 'get' | 'remove'> plus the CDP identity pair. set is gone from the type, so a partition-dropping reconstruction cannot be written against it. Returns { removed, identities }.
  • browser-cookie-import.ts — importValidatedCookies opens a CookieClearStore for replace-mode imports and rolls back through it. The lossless half of the rollback (removing the cookies this import wrote) is unchanged.
  • restoreImportedDomainCookies is deleted — both callers are gone.

The removal plan is fixed beside the snapshot that can undo it, and an incomplete snapshot aborts before the first mutation, so the restorable set always equals the mutated set.

Why

Two callers still rebuilt removed cookies with cookies.set. On Electron 43.1.0, measured against a real persist: jar:

  • cookies.get({}) returns partitioned cookies but strips partitionKey
  • cookies.set({ partitionKey }) silently ignores it — no error, attribute dropped
  • electron.d.ts v43 has no partitionKey anywhere; only CDP can see or write one

The concrete user-visible harm. In importValidatedCookies, replacedCookies holds the user's own pre-existing cookies, which the import already deleted. One cookies.set rejection aborts the whole import (if (replaced) break) and triggers this rollback. So a CHIPS cookie that kept you signed in to a site embedded inside another site came back as an ordinary top-level cookie: the partitioned original is gone, a wrongly-scoped twin is now sent in every context, and the auth material crosses the partition boundary it was created to respect. It survives restart, and re-importing re-downgrades it.

Every Firefox, Safari and JSON/paste import runs in replace-imported-domains mode, and these set rejections are deterministic (malformed value, oversize, prefix violation — the value is already run through stripNonPrintable), so retrying reproduces the failure identically.

Why not just delete the restore, as STA-4097 originally prescribed. The ticket assumed the rollback was putting imported cookies back and that leftover state was retryable. It is putting the user's originals back. Deleting it would destroy every pre-existing cookie for every imported domain — ordinary and partitioned alike — with no retry path, trading a downgrade of the partitioned minority for total loss of everything. That is the STA-4090 shape (a restore deleted with no replacement, which became a P0). Confirmed with the issue author; the ticket description has been corrected.

Reusing snapshotClearIdentities/restoreClearIdentities is what this module already converged on: STA-4061 was fixed by moving restore onto CDP, and CookieClearSession deliberately omits set for exactly this reason. This applies the same pattern to the two sites that were left out of scope there.

Failure-Mode Table

Cookie classes: bystander = outside the imported-domain scopes; in-scope = a cookie for a domain being imported (i.e. one the user asked to replace).

Site A — replaceCookiesForImportedDomains

Cookie Snapshot incomplete / CDP unavailable Success A remove rejects mid-plan Rollback itself also fails
Bystander, ordinary untouched untouched untouched untouched
Bystander, CHIPS untouched untouched untouched untouched
In-scope, ordinary untouched — aborts before mutating removed (intended; import replaces it) restored, value intact AggregateError; may stay removed
In-scope, CHIPS untouched — aborts before mutating removed (intended) restored with partitionKey AggregateError; may stay removed
Import's own cookies not written (import aborts) written next not written (import aborts) not written

Site B — importValidatedCookies rollback after a cookies.set rejection

Cookie Snapshot incomplete / CDP unavailable Success set rejects → rollback Rollback itself also fails
Bystander, ordinary untouched untouched untouched untouched
Bystander, CHIPS untouched untouched untouched untouched
In-scope, ordinary (user's original) untouched removed, replaced by import (intended) restored, value intact logged; may stay removed
In-scope, CHIPS (user's original) untouched removed, replaced by import (intended) restored with partitionKey logged; may stay removed
Import's own cookies not written live removed (lossless remove) may linger; import reports failure

The snapshot happens inside site A, so an unavailable snapshot aborts there and importValidatedCookies returns ok: false on the replace-failure branch before a single cookies.set runs — site B's rollback is never reached and the session is left exactly as it was.

What this replaces

Cookie Before this PR After
In-scope CHIPS, site A rollback silently DOWNGRADED to unpartitioned restored with partition
In-scope CHIPS, site B rollback silently DOWNGRADED to unpartitioned restored with partition
In-scope ordinary, either rollback restored restored

Independent review. A reviewer enumerated the outcome paths independently, without seeing this table first, and every populated cell agreed. Its one finding — that the Site B table had no explicit snapshot-unavailable column — is now fixed above.

Residual risk, stated honestly. The only remaining cell where a cookie can be lost is a double failure — a removal rejects and the CDP restore also rejects. That surfaces as an explicit AggregateError / diagnostic and a failed import, never as silent corruption, and it is the same floor removeTransplantableCookies already ships with. No path silently downgrades a cookie any more. Single-failure paths are all lossless.

Linked Issue

Fixes STA-4097

Follows STA-4061 (#14132) and STA-4065 (#14131), both of which flagged these two sites as known follow-up work.

Visual Proof

N/A — main-process cookie-store behavior with no UI surface. The observable state is the cookie jar, which is asserted directly against real Electron via CDP in the new fixtures below.

Testing

New real-Electron regression fixture — browser-cookie-import-replace-partition-rollback.electron.test.ts. Spawns the real Electron binary, seeds a genuine CHIPS cookie via CDP Network.setCookie, drives each rollback path, and reads the jar back through Network.getAllCookies.

Both fixtures were proved non-vacuous by mutation: dropping partitionKey from cdpRestoreParamsFromIdentity makes both fail with exactly the missing partition, and they pass again once reverted.

Anti-vacuity measures, given three fixtures in this module previously passed for the wrong reason:

  • electronGetSawPartitionKey asserts cookies.get really did strip the partition — so the fixture cannot pass on a cookie that was never partitioned in the first place.
  • Call counts (snapshotCalls, removeCallsBeforeThrow, restoreCalls, importedRemoveCalls) assert the failure path was reached, not just that the jar looks right at the end.
  • The browser-cookie-clear-store mock in browser-cookie-import-replacement.test.ts was a no-op restoreClearIdentities: async () => undefined; it is now a real spy, so a rollback that never ran can no longer pass as one.
  • That test also asserts cookies.set is called exactly for the two imported cookies — a third call would mean the partition-dropping reconstruction came back.

Unit coverage added for the new abort-before-mutating path and for CDP rollback failure surfacing both errors.

Real-Electron QA on the happy path (comment below): booted an isolated Orca dev build on this commit and ran Settings → Browser → Import Cookies → From File with throwaway app.acme-chips.test data. Clean boot, both imports succeeded, and the second one logged removed 3 existing cookies in imported domain scopes — which is the new replace path with the CookieClearStore open. The rollback path was not driven by hand (a mid-import cookies.set rejection is not reachable from the UI); it stays covered by the automated fixtures above.

Second commit (52e4c32) fixes a small regression this PR had introduced: restoreClearIdentities attaches the debugger before it iterates, so an empty restore set would spin up a hidden BrowserWindow to put nothing back — the old cookies.set path did nothing at all in that case. Guarded by replaced.identities.length > 0, with a test that also asserts the lossless half of the rollback still runs. Proved non-vacuous by mutation.

The related review point — that one rejected cookies.set aborts the whole import even when nothing was removed — is pre-existing and unchanged here: the old replacedCookies was a Cookie[] that was [] in the same case, and [] is equally truthy. Changing it alters import semantics and changes when the rollback fires, so it is filed separately as STA-4240 rather than riding along in a PR that is stabilizing exactly that machinery.

Reproduction of the original defect was built first, independently, against unmodified main: both sites resurrected chips-auth with partitionKey undefined.

Commands run (macOS):

  • pnpm vitest run --config config/vitest.config.ts src/main/browser — 40 files, 637 tests, all pass
  • pnpm run typecheck (node + cli + web) — clean
  • pnpm run audit:code-quality:native, audit:code-quality:type-aware — clean
  • oxlint src/main/browser/, oxfmt --check — clean
  • pnpm run check:max-lines-ratchet — OK, no new bypasses (no max-lines disable added)

Platforms: macOS. This is desktop main-process only — not mobile, not Windows/WSL, not SSH. Behavior is platform-independent (Electron/Chromium cookie store), and the fixture runs under xvfb-run on Linux like the existing one.

  • I manually tested these changes locally
  • Automated tests added/updated, or explained why not below

Review

  • Security — improves it. The bug broke cookie partition isolation: a CHIPS cookie scoped to one top-level site was resurrected unpartitioned and then sent in every context. No new attack surface; the CDP debugger attach is the same one removeTransplantableCookies already uses on the Chromium import path.
  • Performance — replace-mode imports now attach a debugger. openCookieClearStore reuses an existing webContents for the partition when one exists, which is the normal case for a browser session being imported into; the hidden-BrowserWindow path is the fallback. One Network.getAllCookies per import. Already-shipped cost on the Chromium path.
  • Cross-platform — no platform-specific code; no paths, shells, or shortcuts touched.
  • Remote SSH / mobile — not involved; this is local main-process session state.
  • Backwards compatibility — no wire format, no IPC, no persisted schema change. replaceCookiesForImportedDomains is module-internal; both call sites are updated in this PR.

Checklist

  • This PR is small and focused
  • I explained what changed and why (including ELI5)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

Author

  • X / Twitter: @BrennanKB5

Both remaining callers of the imported-domain replacement rolled back by
rebuilding cookies with cookies.set, which silently drops partitionKey.
The rollback in importValidatedCookies puts back the user's ORIGINAL
cookies that the import already deleted, so a CHIPS cookie came back as
an ordinary one and no restart recovered it.

Snapshot CDP identities before the first removal and undo through them,
the same machinery removeTransplantableCookies already uses. The store
type omits 'set' so the lossy reconstruction cannot be reintroduced, and
restoreImportedDomainCookies is deleted now that both callers are gone.
@coderabbitai

coderabbitai Bot commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 875a7145-7955-41a9-9e16-80ef1aa486d8

📥 Commits

Reviewing files that changed from the base of the PR and between 9ea55ab and 52e4c32.

📒 Files selected for processing (2)
  • src/main/browser/browser-cookie-import-replacement.test.ts
  • src/main/browser/browser-cookie-import.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/main/browser/browser-cookie-import-replacement.test.ts
  • src/main/browser/browser-cookie-import.ts

📝 Walkthrough

Walkthrough

Cookie replacement now uses CDP clear identities instead of reconstructing cookies with cookies.set. The policy snapshots removable cookies, validates identity coverage, removes each coordinate once, and restores identities on failure. The import flow removes partially imported cookies, restores prior identities, reports rollback failures, and disposes the clear store. Tests cover incomplete snapshots, failed removals, partitioned cookies, mid-import failures, and clear-store lifecycle calls.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly and concisely describes restoring replaced cookies through CDP identities.
Description check ✅ Passed The description covers the required sections, linked issue, testing, visual proof, risks, platform scope, and checklist.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

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

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai 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.

Actionable comments posted: 1

🧹 Nitpick comments (1)
src/main/browser/browser-cookie-import-policy.ts (1)

249-257: 🚀 Performance & Scalability | 🔵 Trivial | 💤 Low value

Skip coordinates that were already removed.

The comment at Line 245 states that one remove(url, name) deletes every cookie at that coordinate. The loop still calls store.remove again for each additional cookie that shares the same coordinate, for example partitioned twins. The extra calls are redundant IPC work, and removed then contains one entry per cookie instead of one per deleted coordinate. The import flow only uses removed.length for a diagnostic count, so the count is reported higher than the number of removal operations.

Consider reusing attemptedKeys to gate the removal itself.

♻️ Proposed refactor
   for (const { cookie, url } of removable) {
     const key = replaceRemovalKey(url, cookie.name)
-    if (!attemptedKeys.has(key)) {
-      attemptedKeys.add(key)
-      attemptedIdentities.push(...(identitiesByKey.get(key) ?? []))
+    if (attemptedKeys.has(key)) {
+      removed.push(cookie)
+      continue
     }
+    attemptedKeys.add(key)
+    attemptedIdentities.push(...(identitiesByKey.get(key) ?? []))
     try {

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 2d3c2817-1a03-4e3e-8661-d90a0ca1d958

📥 Commits

Reviewing files that changed from the base of the PR and between 45736ca and 9ea55ab.

📒 Files selected for processing (5)
  • src/main/browser/browser-cookie-import-policy.test.ts
  • src/main/browser/browser-cookie-import-policy.ts
  • src/main/browser/browser-cookie-import-replace-partition-rollback.electron.test.ts
  • src/main/browser/browser-cookie-import-replacement.test.ts
  • src/main/browser/browser-cookie-import.ts

@brennanb2025

brennanb2025 commented Aug 14, 2026 •

Copy link
Copy Markdown
Contributor Author

Electron QA

Desktop main-process QA on PR 9ea55ab99c (brennanb2025/sta-4097-cookie-rollback-sites). Isolated Orca dev build from this worktree (sta-4097-qa2), Playwright CDP only. No source changes.

Exercised

  • App boot on the PR commit. No main-process errors for browser-cookie-import, browser-cookie-import-policy, or browser-cookie-clear-store.
  • Settings → Browser → Session & Cookies → Import Cookies → From File… (importCookiesFromFile / replace-imported-domains).
  • Throwaway JSON only (app.acme-chips.test; qa_session, qa_pref, qa_csrf). No real accounts or cookies.
  • Happy-path import twice: empty jar, then replace of the 3 already-imported cookies.
  • Bonus: session cookie jar after import via Electron session.cookies.get on persist:orca-browser.

Not exercised

  • Rollback path was not driven by hand. A mid-import cookies.set rejection is not reachable from the UI. That path stays with the PR's automated Electron fixture (browser-cookie-import-replace-partition-rollback.electron.test.ts) plus unit tests. This run only covers the successful replace-imported-domains path.
  • Not tested: Firefox/Safari browser import, mobile, Windows/WSL, SSH, or any real-site cookies.

Diagnostic lines (cookie-import-diag.log + main console)

First import (empty jar):

[cookie-import] importValidatedCookies: 3 validated, 0 unsafe-domain skipped, 0 source-bound skipped, 0 non-transplantable skipped of 3 total, partition="persist:orca-browser"
[cookie-import]   removed 0 existing cookies in imported domain scopes
[cookie-import] importValidatedCookies result: imported=3 skipped=0 domains=1

Second import (replace path actually cleared the prior set):

[cookie-import] importValidatedCookies: 3 validated, 0 unsafe-domain skipped, 0 source-bound skipped, 0 non-transplantable skipped of 3 total, partition="persist:orca-browser"
[cookie-import]   removed 3 existing cookies in imported domain scopes
[cookie-import] importValidatedCookies result: imported=3 skipped=0 domains=1

removed N existing cookies in imported domain scopes is the new replace path + CookieClearStore open. After import, the Default profile showed source File, toast Imported 3 cookies from file into Default., and the jar contained qa_session, qa_pref, qa_csrf on .app.acme-chips.test.

Screenshots

Boot (clean isolated profile):

01-app-boot.png

Cookie import surface (Settings → Browser → Session & Cookies):

02-browser-settings-cookies.png

Import menu with From File…:

03-import-cookies-menu.png

Import result (profile source File, toast Imported 3 cookies from file into Default.):

06-reimport-success-toast.png


Independently corroborated. A second Electron QA run was executed in a separate worktree (sta-4097-qa) with its own isolated userData profile and a different throwaway cookie set (session_id, theme, prefs rather than qa_session, qa_pref, qa_csrf). It reproduced the same result: clean boot with no browser-cookie-import / browser-cookie-import-policy / browser-cookie-clear-store main-process errors, Imported 3 cookies from file into Default., and the same removed 0 → removed 3 existing cookies in imported domain scopes diagnostic pair across two successive imports. That run's duplicate comment was removed to keep this thread readable; its findings were identical and are folded in here.

restoreClearIdentities attaches the debugger before it iterates, so an
empty restore set would spin up a hidden BrowserWindow to put nothing
back. The old cookies.set restore was a no-op loop in that case.
@brennanb2025
brennanb2025 merged commit 3035aa9 into main Aug 14, 2026
44 checks passed
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…ai#14383)

* fix(browser): restore replaced cookies through CDP identities

Both remaining callers of the imported-domain replacement rolled back by
rebuilding cookies with cookies.set, which silently drops partitionKey.
The rollback in importValidatedCookies puts back the user's ORIGINAL
cookies that the import already deleted, so a CHIPS cookie came back as
an ordinary one and no restart recovered it.

Snapshot CDP identities before the first removal and undo through them,
the same machinery removeTransplantableCookies already uses. The store
type omits 'set' so the lossy reconstruction cannot be reintroduced, and
restoreImportedDomainCookies is deleted now that both callers are gone.

* fix(browser): skip the CDP rollback when nothing was replaced

restoreClearIdentities attaches the debugger before it iterates, so an
empty restore set would spin up a hidden BrowserWindow to put nothing
back. The old cookies.set restore was a no-op loop in that case.
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