Repository navigation
fix(browser): restore replaced cookies through CDP identities - #14383
Conversation
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.
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (2)
🚧 Files skipped from review as they are similar to previous changes (2)
📝 WalkthroughWalkthroughCookie replacement now uses CDP clear identities instead of reconstructing cookies with 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
src/main/browser/browser-cookie-import-policy.ts (1)
249-257: 🚀 Performance & Scalability | 🔵 Trivial | 💤 Low valueSkip 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 callsstore.removeagain for each additional cookie that shares the same coordinate, for example partitioned twins. The extra calls are redundant IPC work, andremovedthen contains one entry per cookie instead of one per deleted coordinate. The import flow only usesremoved.lengthfor a diagnostic count, so the count is reported higher than the number of removal operations.Consider reusing
attemptedKeysto 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
📒 Files selected for processing (5)
src/main/browser/browser-cookie-import-policy.test.tssrc/main/browser/browser-cookie-import-policy.tssrc/main/browser/browser-cookie-import-replace-partition-rollback.electron.test.tssrc/main/browser/browser-cookie-import-replacement.test.tssrc/main/browser/browser-cookie-import.ts
Electron QADesktop main-process QA on PR Exercised
Not exercised
Diagnostic lines (
|
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.
…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.




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
replaceCookiesForImportedDomainsnow snapshots CDP cookie identities before it removes anything, and undoes removals throughrestoreClearIdentitiesinstead ofcookies.set.browser-cookie-import-policy.ts— the store parameter is nowPick<Cookies, 'get' | 'remove'>plus the CDP identity pair.setis gone from the type, so a partition-dropping reconstruction cannot be written against it. Returns{ removed, identities }.browser-cookie-import.ts—importValidatedCookiesopens aCookieClearStorefor replace-mode imports and rolls back through it. The lossless half of the rollback (removing the cookies this import wrote) is unchanged.restoreImportedDomainCookiesis 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 realpersist:jar:cookies.get({})returns partitioned cookies but stripspartitionKeycookies.set({ partitionKey })silently ignores it — no error, attribute droppedelectron.d.tsv43 has nopartitionKeyanywhere; only CDP can see or write oneThe concrete user-visible harm. In
importValidatedCookies,replacedCookiesholds the user's own pre-existing cookies, which the import already deleted. Onecookies.setrejection 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-domainsmode, and these set rejections are deterministic (malformed value, oversize, prefix violation — the value is already run throughstripNonPrintable), 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/restoreClearIdentitiesis what this module already converged on: STA-4061 was fixed by moving restore onto CDP, andCookieClearSessiondeliberately omitssetfor 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 —
replaceCookiesForImportedDomainsremoverejects mid-planAggregateError; may stay removedpartitionKeyAggregateError; may stay removedSite B —
importValidatedCookiesrollback after acookies.setrejectionsetrejects → rollbackpartitionKeyremove)The snapshot happens inside site A, so an unavailable snapshot aborts there and
importValidatedCookiesreturnsok: falseon the replace-failure branch before a singlecookies.setruns — site B's rollback is never reached and the session is left exactly as it was.What this replaces
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 floorremoveTransplantableCookiesalready 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 CDPNetwork.setCookie, drives each rollback path, and reads the jar back throughNetwork.getAllCookies.Both fixtures were proved non-vacuous by mutation: dropping
partitionKeyfromcdpRestoreParamsFromIdentitymakes 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:
electronGetSawPartitionKeyassertscookies.getreally did strip the partition — so the fixture cannot pass on a cookie that was never partitioned in the first place.snapshotCalls,removeCallsBeforeThrow,restoreCalls,importedRemoveCalls) assert the failure path was reached, not just that the jar looks right at the end.browser-cookie-clear-storemock inbrowser-cookie-import-replacement.test.tswas a no-oprestoreClearIdentities: async () => undefined; it is now a real spy, so a rollback that never ran can no longer pass as one.cookies.setis 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.testdata. Clean boot, both imports succeeded, and the second one loggedremoved 3 existing cookies in imported domain scopes— which is the new replace path with theCookieClearStoreopen. The rollback path was not driven by hand (a mid-importcookies.setrejection 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:restoreClearIdentitiesattaches the debugger before it iterates, so an empty restore set would spin up a hiddenBrowserWindowto put nothing back — the oldcookies.setpath did nothing at all in that case. Guarded byreplaced.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.setaborts the whole import even when nothing was removed — is pre-existing and unchanged here: the oldreplacedCookieswas aCookie[]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 resurrectedchips-authwithpartitionKeyundefined.Commands run (macOS):
pnpm vitest run --config config/vitest.config.ts src/main/browser— 40 files, 637 tests, all passpnpm run typecheck(node + cli + web) — cleanpnpm run audit:code-quality:native,audit:code-quality:type-aware— cleanoxlint src/main/browser/,oxfmt --check— cleanpnpm run check:max-lines-ratchet— OK, no new bypasses (nomax-linesdisable 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-runon Linux like the existing one.Review
removeTransplantableCookiesalready uses on the Chromium import path.openCookieClearStorereuses an existingwebContentsfor the partition when one exists, which is the normal case for a browser session being imported into; the hidden-BrowserWindowpath is the fallback. OneNetwork.getAllCookiesper import. Already-shipped cost on the Chromium path.replaceCookiesForImportedDomainsis module-internal; both call sites are updated in this PR.Checklist
N/Awith reasonpnpm lint,pnpm typecheck,pnpm test, andpnpm buildpass (or CI will cover; local preferred)Author