Repository navigation
reland(browser): route every cookie-import write through CDP identities, and never clear what it will not write back - #15030
Conversation
Reverts the revert 3c8410d (#14942) to restore the reviewed bf6dc6f tree. The defect that caused that revert is NOT fixed by this commit — it is fixed in the commits that follow, so the delta a reviewer must scrutinise stays small instead of hiding inside a 2000-line re-add. Conflict resolutions, all keep-both: - browser-cookie-import.ts: two hunks around the zero-import early return. #14683's undecryptable warning and decryptedCookies.length === 0 condition are kept alongside the reland's old-client gate and partitionSkippedCookies. The old-client gate stays above the early return, and so above any mutation. - en.json: both string sets (#14683's undecryptable copy and partitionSkipped). - crashpad-capture.test.ts: took HEAD wholesale; unrelated to this ticket. getStoragePath, and its positive-write assertion moves from cookies.set to the CDP identity store — adapted, not weakened, and now strictly stronger because it also asserts cookies.set carries no imported user data. Every decryption assertion is untouched.
STA-4300, change 1 of the reland fixes. No behaviour change yet — this only
adds the helper the later commits derive every skip scope from.
Deriving "family" inline in several places is what let the removal scope and
the write set disagree in STA-4090 and STA-4170, so there is exactly one.
The IP check runs on normalizeCookieDomain's OUTPUT, never the raw string.
psl treats an IPv4 literal as a dotted DNS name — psl.parse('127.0.0.1').domain
is '0.1' — and Chromium accepts many spellings of one address. new URL() inside
normalizeCookieDomain canonicalises 127.1 / 2130706433 / 0x7f.1 / 010.0.0.1 and
a trailing dot to a dotted quad first, so isIP() then catches all of them.
Mutation-proved: moving the check ahead of normalisation reddens the five
alternate-spelling cases and nothing else.
Bracketed IPv6 needs its own branch because isIP('[::1]') is 0; without it the
value falls through to psl, which throws, which returns the host — the right
answer for the wrong reason.
Returns null for a bare public suffix: naming `com` as a family would preserve
an entire TLD from removal and silently turn an import into a no-op.
STA-4300, change 2. Adds planImportWrites — pure, no I/O — so the write set and every removal scope can derive from one value instead of being computed twice. Not yet wired into the import paths; that is the next commits. TWO passes, and the second is not optional. Family-atomic skip is a property of the whole input: with a readable mixed.example row BEFORE an unreadable sub.mixed.example row, a per-row guard emits the readable one before anything knows the family will be skipped. Pass 1 classifies and collects the skipped families; pass 2 re-filters the provisional writes. Mutation-proved with a faithful one-pass guard (consult skippedFamilies as you go): the readable-before-unreadable case goes red and the unreadable-before- readable case still passes. That asymmetry is why both orders are tested and why only the first is the named detector. Family closure is at the registrable boundary because that is the boundary the removal scope actually expands to: importedDomainScopes turns an imported mixed.example into descendant roots, so a readable apex cookie drags a skipped subdomain's live session into the removal scope (STA-4300 §2b). hasUnrepresentableSkip surfaces a skip whose family cannot be named. A family we cannot name is one we cannot exclude from the removal plan, and clearing a family we cannot protect is the P0 this ticket exists to stop — so the caller refuses before mutating rather than proceeding and hoping.
…4300 §2b) Change 3. importValidatedCookies now plans before it opens the jar, and the replacement scope and the write set are the SAME array. bf6dc6f filtered replacementDomains per exact cookie (partition.status !== 'unreadable'). That is not sufficient: replaceCookiesForImportedDomains expands each imported domain into its descendant roots, so a readable cookie on mixed.example pulls sub.mixed.example into the removal scope — and a skipped cookie living there has its session removed with nothing written back. Same erasure as the P0, different path. plan.writes is family-closed, and because path A passes the very same array to replaceCookiesForImportedDomains and to writeImportedCookies, the two sets cannot drift apart. That is stronger than keeping them in sync: there is only one set. Also here, both before any mutation: - an unrepresentable skip (registrableFamily → null) refuses the import, because a family we cannot name is one we cannot exclude from the removal scope; - the old-client gate now keys off plan.skips rather than re-deriving the condition. Counters: partitionSkippedCookies is a BREAKDOWN of skippedCookies — the unreadable rows plus their family-suppressed siblings — added in exactly once, so totalCookies === importedCookies + skippedCookies keeps holding. Counting it separately is how a summary silently stops adding up. Full src/main/browser suite: 69 files, 729 tests, green.
… (STA-4300) Change 4 — this is the commit that fixes the shipped P0. bf6dc6f did: decryptedCookies.push({ ..., partition }) // write set built HERE if (partition.status === 'unreadable') { ... continue } // guard AFTER so an unreadable row discovered late could not retract a sibling already emitted, while removeTransplantableCookies cleared the ENTIRE jar. The mutation set was the whole jar and the write set a strict subset of it, which is how a mixed readable/unreadable source emptied a populated jar and repopulated only part of it. Now the row loop SCANS only. Nothing is emitted inside it — not decryptedCookies, not domainSet, not a staging row, not the imported count. Between scan and emit, planImportWrites closes the skip over whole registrable families, and emit walks the plan. Each scanned candidate carries its raw source row because buildChromiumCookieInsertParams needs it; a record holding only the derived fields compiles and then silently cannot stage. Also between scan and emit, both before any mutation: - an unrepresentable skip refuses the import; - any skipped family calls disableStaging. A staged image is a whole-database replacement on the next start, so it cannot express "preserve this family"; main's existing memoryFailed arm then reports restart-fallback-unavailable. Test contract change, deliberately stronger: "never stages a partitioned row whose ancestor bit is unreadable" asserted that an image WAS registered and merely omitted the row. That image would still have erased the preserved family on replay. It now asserts no image is registered at all — plus a new paired case proving a no-skip import still stages, so "disable on skip" cannot be implemented as "disable always" unnoticed. Honest note on detection: reverting the emit filter currently reddens only the staging assertion, because every end-to-end fixture in this module still starts with an EMPTY jar — where clear-then-write-all and clear-then-write-some are indistinguishable. That is the blind spot that let this ship. The populated-jar suite in the next commit is what actually detects the erasure. Full src/main/browser: 69 files, 730 tests, green.
…-4300 I2) Change 5, and the one that makes preservation observable. removeTransplantableCookies takes preserveFamilies. removableCookieEntries filters those families out, which keeps them out of the removal plan AND — since the CDP snapshot is taken from that same list — out of the restore set, so a preserved coordinate is never submitted to any mutation at all. When anything is preserved, the bulk clearData path is not used. clearData removes everything outside excludeOrigins, and its own comment concedes a rejection may already have emptied part of the jar; a preserved family is deliberately absent from the snapshot, so a partial delete followed by a rejection would destroy it with no identity able to restore it. Handing a dynamically derived preserve list to that primitive cannot be made safe, so a skip-bearing clear runs the frozen per-coordinate plan — which already excludes those families — as its primary path instead. Nothing is preserved on an ordinary import, so that path keeps today's single clearData call unchanged. New populated-jar suite. Every end-to-end fixture in this module starts with cookies.get returning [], and against an empty jar "clear then write all" and "clear then write some" are indistinguishable — which is why four independent gates missed the P0. These fixtures start populated. Mutation-proved, and this is the first detector in the change set that catches the actual erasure rather than a proxy: - drop the preserved-family filter → 6 of 8 red - use bulk clearData while preserving → 6 of 8 red, including "leaves a preserved family untouched", which is the erasure itself IPv4-literal and single-label host families are covered explicitly: psl reads 127.0.0.1 as the dotted DNS name '0.1', so a wrong family here would fail to match the preserve set and erase the live loopback session. Full src/main/browser: 70 files, 738 tests, green.
…aths Ports the pre-implementation reproduction into the PR. Verified RED against main's product code and GREEN with the fix, on both paths — I re-ran it both ways rather than assuming. Two assertions are INVERTED rather than deleted, and both are now stronger. The repro proved the defect by showing cookies.set was called WITHOUT a partitionKey; after the reland the import write path does not touch cookies.set for user data at all, so seeing the imported cookie there is itself the regression. The fixture's internal guard is inverted the same way. Non-vacuity, asserted in-run rather than in a report: ok:true with a nonzero importedCookies, the importer reaching its terminal step, the source really carrying its partition fields, and a CONTROL cookie written via CDP *with* a partitionKey and read back with it — so "partitionKey absent" cannot be confused with "the oracle cannot see partitions". electronVersion proves Electron ran. Fixture correction worth recording, because the original reproduction was invalid on this path and I did not catch it on first read: readJsonCookiePartition reads a NESTED partitionKey object, but the fixture wrote topLevelSite and hasCrossSiteAncestor at the entry's top level, where the importer never looks. The file/paste case therefore failed on main for a fixture-shape reason rather than for the defect — and its own non-vacuity check validated what the fixture wrote instead of what the parser reads, which is exactly how a check that looks rigorous proves nothing. Only the native half was ever a real reproduction. Partition keys use a schemeful SITE, not an origin: Chromium canonicalises https://app.example.com to https://example.com, measured via CDP.
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughThe change adds partition metadata readers for Chromium, Firefox, and JSON cookies. Import planning skips unreadable partition families before mutation and preserves readable partition keys during writes. Cookie clearing can preserve registrable families. CDP identity writes are shared by import and restoration, with validation and aggregate failure handling. Chromium storage paths come from Electron. Runtime and renderer layers report partition-skipped counts and display localized warnings. Tests cover unit, mock-based, concurrency, and Electron integration paths. 🚥 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: 2
🧹 Nitpick comments (6)
src/main/browser/browser-cookie-clear-preserve.test.ts (1)
115-141: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd a rejection-path test for preserved families.
The suite pins the snapshot and removal plans. It does not exercise a failing
removewhile a family is preserved. That path callsrestoreClearedCookies, which replays the snapshot throughrestoreClearIdentities. A regression that put a preserved coordinate back into the snapshot would still pass every current test, because no test makes the restore run.Add a case where
removeMockrejects for the non-preserved cookie and assert that the restored identities contain no preserved coordinate.src/main/browser/browser-cookie-import.ts (1)
1891-1949: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueConfirm the
skippedaccounting for a row that is both undecryptable and partition-skipped.The decrypt-failure branch at Line 1869 increments
skippedand continues, so the row never reaches theplannedSourceRowscheck at Line 1893.partitionSkippedstill counts it becausenativePlan.skipsis computed before decryption. The summary then reports that one row inside bothpartitionSkippedCookiesand thecookies-undecryptablewarning.The identity
totalCookies === importedCookies + skippedCookiesstill holds, andbrowser-cookie-import-undecryptable.test.tspins this exact case. State the overlap in the comment so a later reader does not treat the double attribution as a bug and "fix" it by subtracting.src/main/browser/browser-cookie-import-partition-fidelity.test.ts (1)
293-357: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueReset the write mock between the two imports in this test.
Line 325 arms
mockRejectedValueOncebefore the blocked import. Line 336 asserts the blocked import performed no write, so the queued rejection survives into the second import at Line 342. The test is correct today only because of that ordering, and the call-count assertion at Line 346 counts calls from both imports.Reset the mock after the blocked assertions and re-arm the rejection. The second import's assertions then depend on one import only.
♻️ Proposed change
expect(blockedSession.cookies.remove).not.toHaveBeenCalled() + cookieWriteMock.mockReset() + cookieWriteMock.mockRejectedValueOnce(new Error('plain cookie needs restart')) const result = await importCookiesFromBrowser(chromeBrowser(sourceCookiesPath), 'persist:test')src/main/browser/browser-cookie-clear-store.ts (1)
140-160: 🩺 Stability & Availability | 🔵 Trivial | 💤 Low valueConsider bounding the hidden-window load.
leaseHiddenCookieDebuggerawaitswindow.loadURLwith no time limit. Every cookie write now depends on this attach step. If the renderer never finishes creating,attach()never settles and the caller waits without an error.A timeout that destroys the window and rejects would keep the failure observable.
♻️ Optional bound on the load step
async function leaseHiddenCookieDebugger(targetSession: Session): Promise<CookieClearSession> { const window = openHiddenCookieWindow(targetSession) try { - await window.loadURL('data:text/html,<!doctype html><title>cookie-clear</title>') + await Promise.race([ + window.loadURL('data:text/html,<!doctype html><title>cookie-clear</title>'), + new Promise<never>((_, reject) => + setTimeout( + () => reject(new Error('Could not attach to the cookie session for an atomic clear')), + 10_000 + ).unref() + ) + ])src/main/browser/browser-cookie-import-partition-reland.electron.test.ts (1)
386-398: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winThree new Electron fixtures depend on
xvfb-runon Linux without a guard. Each fixture selectsxvfb-runas the executable whenprocess.platform === 'linux'. If the binary is not installed,spawnSyncreturns anerrorand the run fails with an opaque message instead of naming the missing dependency. The shared root cause is one unverified environment assumption repeated in three files.
src/main/browser/browser-cookie-import-partition-reland.electron.test.ts#L386-L398: confirm the Electron test job provisionsxvfb, or skip the suite whenxvfb-runis absent.src/main/browser/browser-cookie-import-partition-success.electron.test.ts#L209-L218: apply the same guard to this fixture'sspawnSynclaunch.src/main/browser/browser-cookie-import-validated-partition.electron.test.ts#L187-L192: apply the same guard to this fixture'sspawnSynclaunch.Extracting the shared launch logic into one Electron fixture-launch module would keep the guard in a single place.
src/main/runtime/rpc/methods/browser-schemas.ts (1)
152-152: 🗄️ Data Integrity & Integration | 🔵 Trivial | 💤 Low valueAccept an explicit boolean capability value.
z.literal(true).optional()rejectsfalsebefore the handler runs. Usez.boolean().optional()and change the runtime parameter type tosupportsPartitionSkippedCookies?: boolean.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 33cc6210-c0b9-4698-9653-44fc15b4a025
📒 Files selected for processing (32)
src/main/browser/browser-cookie-clear-preserve.test.tssrc/main/browser/browser-cookie-clear-store-lifecycle.test.tssrc/main/browser/browser-cookie-clear-store.test.tssrc/main/browser/browser-cookie-clear-store.tssrc/main/browser/browser-cookie-identity-restore.tssrc/main/browser/browser-cookie-import-clear.tssrc/main/browser/browser-cookie-import-google-exclusion.test.tssrc/main/browser/browser-cookie-import-partition-fidelity.test.tssrc/main/browser/browser-cookie-import-partition-reland.electron.test.tssrc/main/browser/browser-cookie-import-partition-success.electron.test.tssrc/main/browser/browser-cookie-import-plan-writes.test.tssrc/main/browser/browser-cookie-import-policy.tssrc/main/browser/browser-cookie-import-replacement.test.tssrc/main/browser/browser-cookie-import-test-database.tssrc/main/browser/browser-cookie-import-undecryptable.test.tssrc/main/browser/browser-cookie-import-validated-partition.electron.test.tssrc/main/browser/browser-cookie-import-write.test.tssrc/main/browser/browser-cookie-import-write.tssrc/main/browser/browser-cookie-import.test.tssrc/main/browser/browser-cookie-import.tssrc/main/browser/browser-cookie-registrable-family.test.tssrc/main/browser/browser-cookie-source-partition.test.tssrc/main/browser/browser-cookie-source-partition.tssrc/main/runtime/orca-runtime-browser.tssrc/main/runtime/rpc/methods/browser-schemas.tssrc/main/runtime/rpc/methods/browser.test.tssrc/renderer/src/i18n/locales/en.jsonsrc/renderer/src/lib/browser-cookie-import-toast.test.tssrc/renderer/src/lib/browser-cookie-import-toast.tssrc/renderer/src/store/slices/browser-session-host-selection.test.tssrc/renderer/src/store/slices/browser.tssrc/shared/browser-workspace-types.ts
Included review availability: Your plan includes up to 10 reviews per rolling hour; 1 remains after this review.
| return importValidatedCookies( | ||
| validated, | ||
| parsed.length, | ||
| targetPartition, | ||
| cookieImportTarget(targetPartition), | ||
| 'replace-imported-domains' | ||
| ) |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Description: Locate importCookiesFromFile callers and any capability plumbing.
rg -nP --type=ts -C6 '\bimportCookiesFromFile\s*\('
rg -nP --type=ts -C4 'supportsPartitionSkippedCookies|canReportPartitionSkippedCookies'Repository: stablyai/orca
Length of output: 151
🏁 Script executed:
#!/bin/bash
set -e
printf '%s\n' '--- candidate files ---'
fd -i 'browser-cookie-import|cookie' src | head -80
printf '%s\n' '--- importCookiesFromFile references ---'
rg -n -C5 '\bimportCookiesFromFile\b' src .
printf '%s\n' '--- capability identifiers ---'
rg -n -C4 'supportsPartitionSkippedCookies|canReportPartitionSkippedCookies|partitionSkippedCookies|readJsonCookiePartition|importValidatedCookies' src .Repository: stablyai/orca
Length of output: 50370
🏁 Script executed:
#!/bin/bash
set -e
file=$(fd -i -t f 'browser-cookie-import' . | head -1)
printf '%s\n' "--- $file: relevant definitions ---"
rg -n -C12 'importCookiesFromFile|importValidatedCookies|readJsonCookiePartition|canReportPartitionSkippedCookies' "$file"
printf '%s\n' '--- all callers and RPC handlers ---'
rg -n -C8 '\bimportCookiesFromFile\s*\(' .Repository: stablyai/orca
Length of output: 247
🏁 Script executed:
#!/bin/bash
set -e
printf '%s\n' '--- tracked source files ---'
git ls-files | rg '(^|/)(browser-cookie-import|.*cookie.*)\.(ts|tsx|js|jsx)$' | head -100
printf '%s\n' '--- references across tracked files ---'
git grep -n -C6 -E 'importCookiesFromFile|supportsPartitionSkippedCookies|canReportPartitionSkippedCookies|partitionSkippedCookies|readJsonCookiePartition|importValidatedCookies' -- '*.ts' '*.tsx' '*.js' '*.jsx' || trueRepository: stablyai/orca
Length of output: 50369
🏁 Script executed:
#!/bin/bash
set -e
grep -RIn -C6 -E 'importCookiesFromFile|supportsPartitionSkippedCookies|canReportPartitionSkippedCookies|partitionSkippedCookies|readJsonCookiePartition|importValidatedCookies' . --exclude-dir=.git --exclude-dir=node_modules || trueRepository: stablyai/orca
Length of output: 50369
🏁 Script executed:
#!/bin/bash
set -e
printf '%s\n' '--- src/main/browser/browser-cookie-import.ts ---'
sed -n '620,675p;750,835p' src/main/browser/browser-cookie-import.ts
printf '%s\n' '--- src/main/ipc/browser-session-profile-ipc.ts ---'
sed -n '1,105p' src/main/ipc/browser-session-profile-ipc.ts
printf '%s\n' '--- file-import RPC schema and handler references ---'
rg -n -C8 'profileImportFromFile|importFromFile|ProfileImportFromBrowser|supportsPartitionSkippedCookies|canReportPartitionSkippedCookies' src/main src/shared src/rendererRepository: stablyai/orca
Length of output: 38478
🏁 Script executed:
#!/bin/bash
set -e
sed -n '620,675p;750,835p' src/main/browser/browser-cookie-import.ts
sed -n '1,105p' src/main/ipc/browser-session-profile-ipc.ts
rg -n -C8 'profileImportFromFile|importFromFile|ProfileImportFromBrowser|supportsPartitionSkippedCookies|canReportPartitionSkippedCookies' src/main src/shared src/rendererRepository: stablyai/orca
Length of output: 38322
🏁 Script executed:
#!/bin/bash
set -e
printf '%s\n' '--- browser:session:importCookies callers and argument shapes ---'
rg -n -C10 "'browser:session:importCookies'|browser:session:importCookies|importCookies\(" src/main src/renderer src/shared
printf '%s\n' '--- result rendering and capability declarations ---'
rg -n -C8 'partitionSkippedCookies|supportsPartitionSkippedCookies|canReportPartitionSkippedCookies' src/renderer/src src/main/ipc src/shared | head -240Repository: stablyai/orca
Length of output: 12274
🏁 Script executed:
#!/bin/bash
set -e
rg -n -C10 "'browser:session:importCookies'|browser:session:importCookies|importCookies\(" src/main src/renderer src/shared
rg -n -C8 'partitionSkippedCookies|supportsPartitionSkippedCookies|canReportPartitionSkippedCookies' src/renderer/src src/main/ipc src/shared | head -240Repository: stablyai/orca
Length of output: 12155
Forward the file-import capability through the IPC path.
Extend importCookiesFromFile with CookieImportOptions and pass it to importValidatedCookies. Extend browser:session:importCookies arguments with supportsPartitionSkippedCookies, then pass canReportPartitionSkippedCookies: args.supportsPartitionSkippedCookies === true. Otherwise, unreadable JSON partitions can produce ok: true with unreported skipped cookies.
| 'auto.lib.browser.cookie.import.toast.partitionSkipped', | ||
| '{{value0}} cookies were not imported because their site-partition could not be read. Sign in to those sites again in Orca.', | ||
| { value0: summary.partitionSkippedCookies } | ||
| ), |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Provide singular and plural warning text.
If partitionSkippedCookies is 1 and the translation key is unavailable for the active locale, this fallback displays 1 cookies. Define singular and plural translation variants and update the test to cover both forms.
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 73f264ee-85ed-48c5-93d5-e1e41a664c82
📒 Files selected for processing (3)
src/main/browser/browser-cookie-import-partition-fidelity.test.tssrc/main/browser/browser-cookie-source-partition.test.tssrc/main/browser/browser-cookie-source-partition.ts
🚧 Files skipped from review as they are similar to previous changes (2)
- src/main/browser/browser-cookie-source-partition.test.ts
- src/main/browser/browser-cookie-source-partition.ts
Included review availability: Your plan includes up to 10 reviews per rolling hour; 0 remain after this review.
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/main/browser/browser-cookie-clear-store.ts (1)
64-74: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick winTreat
nullpartition keys as unpartitioned.
CdpCookie.partitionKeyallowsnull. The current check does not. Anullvalue reaches normalization and throws, which aborts atomic cookie snapshots. Returnundefinedfor bothundefinedandnull, and add a regression test.
🧹 Nitpick comments (1)
src/main/browser/browser-cookie-import-clear.ts (1)
109-112: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueShorten the multi-line implementation comments.
Keep the invariants. Reduce each
Whyblock to a brief, non-obvious statement.As per coding guidelines, “Comments must be concise, non-obvious, and brief—prefer one line; do not explain obvious behavior or walk through code.”
Also applies to: 190-216
Source: Coding guidelines
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 059195d7-d3dd-4910-8e11-46386097253a
📒 Files selected for processing (8)
src/main/browser/browser-cookie-clear-store.test.tssrc/main/browser/browser-cookie-clear-store.tssrc/main/browser/browser-cookie-import-clear.tssrc/main/browser/browser-cookie-import-concurrency.test.tssrc/main/browser/browser-cookie-import-partition-fidelity.test.tssrc/main/browser/browser-cookie-import.tssrc/main/browser/browser-cookie-source-partition.test.tssrc/main/browser/browser-cookie-source-partition.ts
🚧 Files skipped from review as they are similar to previous changes (2)
- src/main/browser/browser-cookie-source-partition.test.ts
- src/main/browser/browser-cookie-import.ts
Included review availability: Your plan includes up to 10 reviews per rolling hour; 0 remain after this review.
Electron QA — STA-4300 cookie-import partition preservationRan against a dev build of this branch, not another worktree.
(1) Ordinary import — provedA real Import Cookies → From Google Chrome → Brennan run completed in Settings → Browser. Store summary: Before — empty Default profile, no cookies imported. Import menu on the real Settings surface (Chrome / Comet / Firefox / Safari / From File…). After — profile source updated to Google Chrome (Brennan). Same import reporting on screen (Google-skip warning toast; accessibility tree also had (2) New
|
Reverts only the concurrency-serialization half of f7c27b7 so #15030 stays scoped to the STA-4300 reland. That commit mixed two concerns; this removes one of them and keeps the other. REMOVED (moves to STA-4601, a separate pre-existing P1): - acquireCookieMutationLock / withCookieMutationLock and the mutationLocks map; clear.ts goes back to withCookieClearLock - the import-wide lock in path A (mutationOwner on the target, acquire/release around replace + writes + rollback) - the widened lock around path B's clear + memory writes - browser-cookie-import-concurrency.test.ts KEPT (genuinely STA-4300 scope, not concurrency): - partitionKeyOpaque handling in readJsonCookiePartition and the CDP snapshot. An opaque partition key cannot be represented faithfully, so it reads as unreadable and its family is preserved — exactly the rule this ticket adds. 194e57a's refinement of that shape stays too. The concurrent-import interleaving is real and reachable (nothing serialises imports per partition, and the clear lock is released before the memory writes), but it predates this change and is not caused or worsened by it. It gets its own PR and its own review rather than riding a P0 reland whose history is that every additional fix introduced a new defect. src/main/browser: 71 files, 772 tests, green. Electron oracle still passes on both write paths and still goes red against main's product code.
Populated-jar Electron QA follow-up — STA-4300This is the populated-jar follow-up to the earlier empty-profile Electron QA on this PR. That run imported Chrome cookies into an empty Default profile and never loaded a page. This run exists because that is the exact blind spot that let #14729 pass review, readiness, Electron QA, and CI and still get reverted for erasing user sessions. Do not merge on the strength of the earlier empty-profile comment. Instance (CDP ownership verified)
RUN A — populated-jar survival: ERASED
Store summary after import:
Verdict A: ERASED RUN B — imported-session authenticitySame Chrome Brennan import as RUN A. Then loaded the imported domains in Orca. YouTube — SURVIVED. GitHub — NOT PROVEN. Rendered the logged-out marketing homepage (Sign in / Sign up). Chrome Brennan has Nord Account — NOT PROVEN. Verdict B: YouTube SURVIVED. GitHub NOT PROVEN (source had no live Why this mattersThe earlier empty-profile QA could not have seen RUN A. Against an empty jar, clearing then writing back 32 cookies looks successful. Against a populated jar, the pre-existing session disappeared while imported YouTube cookies still authenticated. That is the original revert class: jar-level green and user-visible broken can coexist. Did not merge. |
Correction to the populated-jar QA above — RUN A's "ERASED" is not a defect in this PRI wrote the brief for that QA run, and the pass criterion I set was wrong. Recording it here so nobody reads "ERASED" as a blocker on this PR. I asked for: a pre-existing logged-in session must survive an import into the same partition. A cookie import in replace mode is designed to do the opposite. On const initialCookies = await store.get({})and removes everything except the non-transplantable (Google) family, under the existing comment:
So a The missing piece was a control run. Without executing the same steps on What the populated-jar test should actually assertThe STA-4090 / STA-4170 failures were never about a successful import clearing unrelated cookies. They were about a failed or partial import leaving the jar cleared and not written back. The meaningful assertions are:
StandingRUN B (SURVIVED) stands as real evidence. RUN A should be read as "import clears the target jar, as designed," not as a finding against this PR. The earlier note in this thread to not merge on the strength of the empty-profile comment alone still holds — but RUN A is not the reason. Separately worth knowing, and out of scope here: importing cookies silently signs the user out of every unrelated site in that partition. That is pre-existing behaviour, not introduced by this PR, and may deserve its own ticket. |
Two concurrent cookie imports on one partition can erase a session. Nothing serialises imports per partition — neither the renderer IPC handler (browser-session-profile-ipc.ts) nor the runtime RPC method (orca-runtime-browser.ts) — and the clear lock covered only the clear itself, so it was released before the writes and before any rollback. Reachable interleaving: import A replaces cookies for its imported domains, releases the lock, and later fails a write; import B clears and writes; A's rollback then removes cookies B already wrote and reported as imported. Path B has the same shape: A clears, B clears, then A writes its cookies on top of B's jar. Fix: one lock spans the whole live-jar transaction on both paths — the clear/replace, the writes, and the rollback. withCookieClearLock becomes acquireCookieMutationLock/withCookieMutationLock so path A can hold it across a try/finally rather than a single callback. Rebased onto #15030 (STA-4300), which rewrote this file: imports now write through CDP identities, so path A's writes moved from an inline cookies.set() loop into writeImportedCookies(), path B's into the same helper, and — the part that matters for a lock — importValidatedCookies no longer holds the Electron Session at all. It receives a CookieImportTarget that hides the Session behind openWriteStore(), and openWriteStore() builds a FRESH adapter per call, so keying the lock on anything reachable from it would serialise nothing. The target therefore carries mutationLockOwner, set to session.fromPartition's instance, which is the same object the native path locks on. That is what keeps both paths on one key per partition. Deliberately bounded: this covers the LIVE JAR only. Staging and cold-start replay keep their existing semantics, so two other pre-existing hazards in that subsystem are untouched and still open — the crash window between the clear and the result, and a permanently-armed replay when replay keeps failing. Both need the pending-image operations to become provable, which is a different change. The lock is keyed per owner, so imports into different partitions still run concurrently. Mutation-proved against the rebased tree, every mutation structure-preserving (brace/paren balance pinned) and every one re-run rather than carried over: dropping path A's acquire reddens the file-import detector; keying path A's acquire on a fresh object instead of mutationLockOwner reddens it too — the lock-present-but-miskeyed shape this rebase risks; replacing path B's lock with a passthrough reddens the native detector; doing both reddens both, which rules out incidental serialisation; and neutering the cold-init probe's lock reddens the new probe detector. That last detector is new: neutering the probe lock previously left all 779 browser tests green, so the probe's protection was unproven. The concurrency suite's store stub also gained writeCookieIdentity and getStoragePath. Without them the STA-4300 code throws a TypeError that writeImportedCookies catches as a write rejection, so the imports would have taken the failure path while the ordering assertions still passed. Each real import test now asserts writeCookieIdentity was CALLED, and that cookies.set never was. src/main/browser: 72 files, 780 tests, green; typecheck, oxlint, type-aware code quality, oxfmt and the max-lines ratchet all clean.
* fix(browser): serialize cookie imports per partition (STA-4601) Two concurrent cookie imports on one partition can erase a session. Nothing serialises imports per partition — neither the renderer IPC handler (browser-session-profile-ipc.ts) nor the runtime RPC method (orca-runtime-browser.ts) — and the clear lock covered only the clear itself, so it was released before the writes and before any rollback. Reachable interleaving: import A replaces cookies for its imported domains, releases the lock, and later fails a write; import B clears and writes; A's rollback then removes cookies B already wrote and reported as imported. Path B has the same shape: A clears, B clears, then A writes its cookies on top of B's jar. Fix: one lock spans the whole live-jar transaction on both paths — the clear/replace, the writes, and the rollback. withCookieClearLock becomes acquireCookieMutationLock/withCookieMutationLock so path A can hold it across a try/finally rather than a single callback. Rebased onto #15030 (STA-4300), which rewrote this file: imports now write through CDP identities, so path A's writes moved from an inline cookies.set() loop into writeImportedCookies(), path B's into the same helper, and — the part that matters for a lock — importValidatedCookies no longer holds the Electron Session at all. It receives a CookieImportTarget that hides the Session behind openWriteStore(), and openWriteStore() builds a FRESH adapter per call, so keying the lock on anything reachable from it would serialise nothing. The target therefore carries mutationLockOwner, set to session.fromPartition's instance, which is the same object the native path locks on. That is what keeps both paths on one key per partition. Deliberately bounded: this covers the LIVE JAR only. Staging and cold-start replay keep their existing semantics, so two other pre-existing hazards in that subsystem are untouched and still open — the crash window between the clear and the result, and a permanently-armed replay when replay keeps failing. Both need the pending-image operations to become provable, which is a different change. The lock is keyed per owner, so imports into different partitions still run concurrently. Mutation-proved against the rebased tree, every mutation structure-preserving (brace/paren balance pinned) and every one re-run rather than carried over: dropping path A's acquire reddens the file-import detector; keying path A's acquire on a fresh object instead of mutationLockOwner reddens it too — the lock-present-but-miskeyed shape this rebase risks; replacing path B's lock with a passthrough reddens the native detector; doing both reddens both, which rules out incidental serialisation; and neutering the cold-init probe's lock reddens the new probe detector. That last detector is new: neutering the probe lock previously left all 779 browser tests green, so the probe's protection was unproven. The concurrency suite's store stub also gained writeCookieIdentity and getStoragePath. Without them the STA-4300 code throws a TypeError that writeImportedCookies catches as a write rejection, so the imports would have taken the failure path while the ordering assertions still passed. Each real import test now asserts writeCookieIdentity was CALLED, and that cookies.set never was. src/main/browser: 72 files, 780 tests, green; typecheck, oxlint, type-aware code quality, oxfmt and the max-lines ratchet all clean. * fix(browser): serialize native cookie staging * test(browser): pin native flush serialization * test(browser): pin staged cookie replay ordering * test(browser): remove vacuous staged replay detector * test(browser): detect stale native staging images * test(browser): guard cookie import ordering events * test(browser): cover staging lock boundary
…es, and never clear what it will not write back (stablyai#15030) * reland(browser): restore CDP-identity cookie-import writes (stablyai#14729) Reverts the revert 3c8410d (stablyai#14942) to restore the reviewed bf6dc6f tree. The defect that caused that revert is NOT fixed by this commit — it is fixed in the commits that follow, so the delta a reviewer must scrutinise stays small instead of hiding inside a 2000-line re-add. Conflict resolutions, all keep-both: - browser-cookie-import.ts: two hunks around the zero-import early return. stablyai#14683's undecryptable warning and decryptedCookies.length === 0 condition are kept alongside the reland's old-client gate and partitionSkippedCookies. The old-client gate stays above the early return, and so above any mutation. - en.json: both string sets (stablyai#14683's undecryptable copy and partitionSkipped). - crashpad-capture.test.ts: took HEAD wholesale; unrelated to this ticket. getStoragePath, and its positive-write assertion moves from cookies.set to the CDP identity store — adapted, not weakened, and now strictly stronger because it also asserts cookies.set carries no imported user data. Every decryption assertion is untouched. * fix(browser): add registrableFamily, one definition of a cookie family STA-4300, change 1 of the reland fixes. No behaviour change yet — this only adds the helper the later commits derive every skip scope from. Deriving "family" inline in several places is what let the removal scope and the write set disagree in STA-4090 and STA-4170, so there is exactly one. The IP check runs on normalizeCookieDomain's OUTPUT, never the raw string. psl treats an IPv4 literal as a dotted DNS name — psl.parse('127.0.0.1').domain is '0.1' — and Chromium accepts many spellings of one address. new URL() inside normalizeCookieDomain canonicalises 127.1 / 2130706433 / 0x7f.1 / 010.0.0.1 and a trailing dot to a dotted quad first, so isIP() then catches all of them. Mutation-proved: moving the check ahead of normalisation reddens the five alternate-spelling cases and nothing else. Bracketed IPv6 needs its own branch because isIP('[::1]') is 0; without it the value falls through to psl, which throws, which returns the host — the right answer for the wrong reason. Returns null for a bare public suffix: naming `com` as a family would preserve an entire TLD from removal and silently turn an import into a no-op. * fix(browser): plan every cookie's fate before any jar mutation STA-4300, change 2. Adds planImportWrites — pure, no I/O — so the write set and every removal scope can derive from one value instead of being computed twice. Not yet wired into the import paths; that is the next commits. TWO passes, and the second is not optional. Family-atomic skip is a property of the whole input: with a readable mixed.example row BEFORE an unreadable sub.mixed.example row, a per-row guard emits the readable one before anything knows the family will be skipped. Pass 1 classifies and collects the skipped families; pass 2 re-filters the provisional writes. Mutation-proved with a faithful one-pass guard (consult skippedFamilies as you go): the readable-before-unreadable case goes red and the unreadable-before- readable case still passes. That asymmetry is why both orders are tested and why only the first is the named detector. Family closure is at the registrable boundary because that is the boundary the removal scope actually expands to: importedDomainScopes turns an imported mixed.example into descendant roots, so a readable apex cookie drags a skipped subdomain's live session into the removal scope (STA-4300 §2b). hasUnrepresentableSkip surfaces a skip whose family cannot be named. A family we cannot name is one we cannot exclude from the removal plan, and clearing a family we cannot protect is the P0 this ticket exists to stop — so the caller refuses before mutating rather than proceeding and hoping. * fix(browser): derive path A's removal scope from the write plan (STA-4300 §2b) Change 3. importValidatedCookies now plans before it opens the jar, and the replacement scope and the write set are the SAME array. bf6dc6f filtered replacementDomains per exact cookie (partition.status !== 'unreadable'). That is not sufficient: replaceCookiesForImportedDomains expands each imported domain into its descendant roots, so a readable cookie on mixed.example pulls sub.mixed.example into the removal scope — and a skipped cookie living there has its session removed with nothing written back. Same erasure as the P0, different path. plan.writes is family-closed, and because path A passes the very same array to replaceCookiesForImportedDomains and to writeImportedCookies, the two sets cannot drift apart. That is stronger than keeping them in sync: there is only one set. Also here, both before any mutation: - an unrepresentable skip (registrableFamily → null) refuses the import, because a family we cannot name is one we cannot exclude from the removal scope; - the old-client gate now keys off plan.skips rather than re-deriving the condition. Counters: partitionSkippedCookies is a BREAKDOWN of skippedCookies — the unreadable rows plus their family-suppressed siblings — added in exactly once, so totalCookies === importedCookies + skippedCookies keeps holding. Counting it separately is how a summary silently stops adding up. Full src/main/browser suite: 69 files, 729 tests, green. * fix(browser): split path B into scan and emit, and never stage a skip (STA-4300) Change 4 — this is the commit that fixes the shipped P0. bf6dc6f did: decryptedCookies.push({ ..., partition }) // write set built HERE if (partition.status === 'unreadable') { ... continue } // guard AFTER so an unreadable row discovered late could not retract a sibling already emitted, while removeTransplantableCookies cleared the ENTIRE jar. The mutation set was the whole jar and the write set a strict subset of it, which is how a mixed readable/unreadable source emptied a populated jar and repopulated only part of it. Now the row loop SCANS only. Nothing is emitted inside it — not decryptedCookies, not domainSet, not a staging row, not the imported count. Between scan and emit, planImportWrites closes the skip over whole registrable families, and emit walks the plan. Each scanned candidate carries its raw source row because buildChromiumCookieInsertParams needs it; a record holding only the derived fields compiles and then silently cannot stage. Also between scan and emit, both before any mutation: - an unrepresentable skip refuses the import; - any skipped family calls disableStaging. A staged image is a whole-database replacement on the next start, so it cannot express "preserve this family"; main's existing memoryFailed arm then reports restart-fallback-unavailable. Test contract change, deliberately stronger: "never stages a partitioned row whose ancestor bit is unreadable" asserted that an image WAS registered and merely omitted the row. That image would still have erased the preserved family on replay. It now asserts no image is registered at all — plus a new paired case proving a no-skip import still stages, so "disable on skip" cannot be implemented as "disable always" unnoticed. Honest note on detection: reverting the emit filter currently reddens only the staging assertion, because every end-to-end fixture in this module still starts with an EMPTY jar — where clear-then-write-all and clear-then-write-some are indistinguishable. That is the blind spot that let this ship. The populated-jar suite in the next commit is what actually detects the erasure. Full src/main/browser: 69 files, 730 tests, green. * fix(browser): never remove a family the import declined to write (STA-4300 I2) Change 5, and the one that makes preservation observable. removeTransplantableCookies takes preserveFamilies. removableCookieEntries filters those families out, which keeps them out of the removal plan AND — since the CDP snapshot is taken from that same list — out of the restore set, so a preserved coordinate is never submitted to any mutation at all. When anything is preserved, the bulk clearData path is not used. clearData removes everything outside excludeOrigins, and its own comment concedes a rejection may already have emptied part of the jar; a preserved family is deliberately absent from the snapshot, so a partial delete followed by a rejection would destroy it with no identity able to restore it. Handing a dynamically derived preserve list to that primitive cannot be made safe, so a skip-bearing clear runs the frozen per-coordinate plan — which already excludes those families — as its primary path instead. Nothing is preserved on an ordinary import, so that path keeps today's single clearData call unchanged. New populated-jar suite. Every end-to-end fixture in this module starts with cookies.get returning [], and against an empty jar "clear then write all" and "clear then write some" are indistinguishable — which is why four independent gates missed the P0. These fixtures start populated. Mutation-proved, and this is the first detector in the change set that catches the actual erasure rather than a proxy: - drop the preserved-family filter → 6 of 8 red - use bulk clearData while preserving → 6 of 8 red, including "leaves a preserved family untouched", which is the erasure itself IPv4-literal and single-label host families are covered explicitly: psl reads 127.0.0.1 as the dotted DNS name '0.1', so a wrong family here would fail to match the preserve set and erase the live loopback session. Full src/main/browser: 70 files, 738 tests, green. * test(browser): pin STA-4300 end to end in real Electron, both write paths Ports the pre-implementation reproduction into the PR. Verified RED against main's product code and GREEN with the fix, on both paths — I re-ran it both ways rather than assuming. Two assertions are INVERTED rather than deleted, and both are now stronger. The repro proved the defect by showing cookies.set was called WITHOUT a partitionKey; after the reland the import write path does not touch cookies.set for user data at all, so seeing the imported cookie there is itself the regression. The fixture's internal guard is inverted the same way. Non-vacuity, asserted in-run rather than in a report: ok:true with a nonzero importedCookies, the importer reaching its terminal step, the source really carrying its partition fields, and a CONTROL cookie written via CDP *with* a partitionKey and read back with it — so "partitionKey absent" cannot be confused with "the oracle cannot see partitions". electronVersion proves Electron ran. Fixture correction worth recording, because the original reproduction was invalid on this path and I did not catch it on first read: readJsonCookiePartition reads a NESTED partitionKey object, but the fixture wrote topLevelSite and hasCrossSiteAncestor at the entry's top level, where the importer never looks. The file/paste case therefore failed on main for a fixture-shape reason rather than for the defect — and its own non-vacuity check validated what the fixture wrote instead of what the parser reads, which is exactly how a check that looks rigorous proves nothing. Only the native half was ever a real reproduction. Partition keys use a schemeful SITE, not an origin: Chromium canonicalises https://app.example.com to https://example.com, measured via CDP. * fix(browser): fail closed on lossy cookie identity recovery * fix(browser): preserve unreadable families before decrypt * fix(browser): reject malformed cookie partition sites * fix(browser): validate recovered cookie partition sites * fix(browser): reject empty JSON partition identities * fix(browser): fail closed and serialize cookie imports * fix(browser): reject malformed CDP opaque flags * fix(browser): roll back outcome-unknown cookie writes * revert(browser): move import serialization out to STA-4601 Reverts only the concurrency-serialization half of f7c27b7 so stablyai#15030 stays scoped to the STA-4300 reland. That commit mixed two concerns; this removes one of them and keeps the other. REMOVED (moves to STA-4601, a separate pre-existing P1): - acquireCookieMutationLock / withCookieMutationLock and the mutationLocks map; clear.ts goes back to withCookieClearLock - the import-wide lock in path A (mutationOwner on the target, acquire/release around replace + writes + rollback) - the widened lock around path B's clear + memory writes - browser-cookie-import-concurrency.test.ts KEPT (genuinely STA-4300 scope, not concurrency): - partitionKeyOpaque handling in readJsonCookiePartition and the CDP snapshot. An opaque partition key cannot be represented faithfully, so it reads as unreadable and its family is preserved — exactly the rule this ticket adds. 194e57a's refinement of that shape stays too. The concurrent-import interleaving is real and reachable (nothing serialises imports per partition, and the clear lock is released before the memory writes), but it predates this change and is not caused or worsened by it. It gets its own PR and its own review rather than riding a P0 reland whose history is that every additional fix introduced a new defect. src/main/browser: 71 files, 772 tests, green. Electron oracle still passes on both write paths and still goes red against main's product code.
* fix(browser): serialize cookie imports per partition (STA-4601) Two concurrent cookie imports on one partition can erase a session. Nothing serialises imports per partition — neither the renderer IPC handler (browser-session-profile-ipc.ts) nor the runtime RPC method (orca-runtime-browser.ts) — and the clear lock covered only the clear itself, so it was released before the writes and before any rollback. Reachable interleaving: import A replaces cookies for its imported domains, releases the lock, and later fails a write; import B clears and writes; A's rollback then removes cookies B already wrote and reported as imported. Path B has the same shape: A clears, B clears, then A writes its cookies on top of B's jar. Fix: one lock spans the whole live-jar transaction on both paths — the clear/replace, the writes, and the rollback. withCookieClearLock becomes acquireCookieMutationLock/withCookieMutationLock so path A can hold it across a try/finally rather than a single callback. Rebased onto stablyai#15030 (STA-4300), which rewrote this file: imports now write through CDP identities, so path A's writes moved from an inline cookies.set() loop into writeImportedCookies(), path B's into the same helper, and — the part that matters for a lock — importValidatedCookies no longer holds the Electron Session at all. It receives a CookieImportTarget that hides the Session behind openWriteStore(), and openWriteStore() builds a FRESH adapter per call, so keying the lock on anything reachable from it would serialise nothing. The target therefore carries mutationLockOwner, set to session.fromPartition's instance, which is the same object the native path locks on. That is what keeps both paths on one key per partition. Deliberately bounded: this covers the LIVE JAR only. Staging and cold-start replay keep their existing semantics, so two other pre-existing hazards in that subsystem are untouched and still open — the crash window between the clear and the result, and a permanently-armed replay when replay keeps failing. Both need the pending-image operations to become provable, which is a different change. The lock is keyed per owner, so imports into different partitions still run concurrently. Mutation-proved against the rebased tree, every mutation structure-preserving (brace/paren balance pinned) and every one re-run rather than carried over: dropping path A's acquire reddens the file-import detector; keying path A's acquire on a fresh object instead of mutationLockOwner reddens it too — the lock-present-but-miskeyed shape this rebase risks; replacing path B's lock with a passthrough reddens the native detector; doing both reddens both, which rules out incidental serialisation; and neutering the cold-init probe's lock reddens the new probe detector. That last detector is new: neutering the probe lock previously left all 779 browser tests green, so the probe's protection was unproven. The concurrency suite's store stub also gained writeCookieIdentity and getStoragePath. Without them the STA-4300 code throws a TypeError that writeImportedCookies catches as a write rejection, so the imports would have taken the failure path while the ordering assertions still passed. Each real import test now asserts writeCookieIdentity was CALLED, and that cookies.set never was. src/main/browser: 72 files, 780 tests, green; typecheck, oxlint, type-aware code quality, oxfmt and the max-lines ratchet all clean. * fix(browser): serialize native cookie staging * test(browser): pin native flush serialization * test(browser): pin staged cookie replay ordering * test(browser): remove vacuous staged replay detector * test(browser): detect stale native staging images * test(browser): guard cookie import ordering events * test(browser): cover staging lock boundary
* fix(browser): serialize cookie imports per partition (STA-4601) Two concurrent cookie imports on one partition can erase a session. Nothing serialises imports per partition — neither the renderer IPC handler (browser-session-profile-ipc.ts) nor the runtime RPC method (orca-runtime-browser.ts) — and the clear lock covered only the clear itself, so it was released before the writes and before any rollback. Reachable interleaving: import A replaces cookies for its imported domains, releases the lock, and later fails a write; import B clears and writes; A's rollback then removes cookies B already wrote and reported as imported. Path B has the same shape: A clears, B clears, then A writes its cookies on top of B's jar. Fix: one lock spans the whole live-jar transaction on both paths — the clear/replace, the writes, and the rollback. withCookieClearLock becomes acquireCookieMutationLock/withCookieMutationLock so path A can hold it across a try/finally rather than a single callback. Rebased onto stablyai#15030 (STA-4300), which rewrote this file: imports now write through CDP identities, so path A's writes moved from an inline cookies.set() loop into writeImportedCookies(), path B's into the same helper, and — the part that matters for a lock — importValidatedCookies no longer holds the Electron Session at all. It receives a CookieImportTarget that hides the Session behind openWriteStore(), and openWriteStore() builds a FRESH adapter per call, so keying the lock on anything reachable from it would serialise nothing. The target therefore carries mutationLockOwner, set to session.fromPartition's instance, which is the same object the native path locks on. That is what keeps both paths on one key per partition. Deliberately bounded: this covers the LIVE JAR only. Staging and cold-start replay keep their existing semantics, so two other pre-existing hazards in that subsystem are untouched and still open — the crash window between the clear and the result, and a permanently-armed replay when replay keeps failing. Both need the pending-image operations to become provable, which is a different change. The lock is keyed per owner, so imports into different partitions still run concurrently. Mutation-proved against the rebased tree, every mutation structure-preserving (brace/paren balance pinned) and every one re-run rather than carried over: dropping path A's acquire reddens the file-import detector; keying path A's acquire on a fresh object instead of mutationLockOwner reddens it too — the lock-present-but-miskeyed shape this rebase risks; replacing path B's lock with a passthrough reddens the native detector; doing both reddens both, which rules out incidental serialisation; and neutering the cold-init probe's lock reddens the new probe detector. That last detector is new: neutering the probe lock previously left all 779 browser tests green, so the probe's protection was unproven. The concurrency suite's store stub also gained writeCookieIdentity and getStoragePath. Without them the STA-4300 code throws a TypeError that writeImportedCookies catches as a write rejection, so the imports would have taken the failure path while the ordering assertions still passed. Each real import test now asserts writeCookieIdentity was CALLED, and that cookies.set never was. src/main/browser: 72 files, 780 tests, green; typecheck, oxlint, type-aware code quality, oxfmt and the max-lines ratchet all clean. * fix(browser): serialize native cookie staging * test(browser): pin native flush serialization * test(browser): pin staged cookie replay ordering * test(browser): remove vacuous staged replay detector * test(browser): detect stale native staging images * test(browser): guard cookie import ordering events * test(browser): cover staging lock boundary
…es, and never clear what it will not write back (stablyai#15030) * reland(browser): restore CDP-identity cookie-import writes (stablyai#14729) Reverts the revert 23fe91e (stablyai#14942) to restore the reviewed 210f961 tree. The defect that caused that revert is NOT fixed by this commit — it is fixed in the commits that follow, so the delta a reviewer must scrutinise stays small instead of hiding inside a 2000-line re-add. Conflict resolutions, all keep-both: - browser-cookie-import.ts: two hunks around the zero-import early return. stablyai#14683's undecryptable warning and decryptedCookies.length === 0 condition are kept alongside the reland's old-client gate and partitionSkippedCookies. The old-client gate stays above the early return, and so above any mutation. - en.json: both string sets (stablyai#14683's undecryptable copy and partitionSkipped). - crashpad-capture.test.ts: took HEAD wholesale; unrelated to this ticket. getStoragePath, and its positive-write assertion moves from cookies.set to the CDP identity store — adapted, not weakened, and now strictly stronger because it also asserts cookies.set carries no imported user data. Every decryption assertion is untouched. * fix(browser): add registrableFamily, one definition of a cookie family STA-4300, change 1 of the reland fixes. No behaviour change yet — this only adds the helper the later commits derive every skip scope from. Deriving "family" inline in several places is what let the removal scope and the write set disagree in STA-4090 and STA-4170, so there is exactly one. The IP check runs on normalizeCookieDomain's OUTPUT, never the raw string. psl treats an IPv4 literal as a dotted DNS name — psl.parse('127.0.0.1').domain is '0.1' — and Chromium accepts many spellings of one address. new URL() inside normalizeCookieDomain canonicalises 127.1 / 2130706433 / 0x7f.1 / 010.0.0.1 and a trailing dot to a dotted quad first, so isIP() then catches all of them. Mutation-proved: moving the check ahead of normalisation reddens the five alternate-spelling cases and nothing else. Bracketed IPv6 needs its own branch because isIP('[::1]') is 0; without it the value falls through to psl, which throws, which returns the host — the right answer for the wrong reason. Returns null for a bare public suffix: naming `com` as a family would preserve an entire TLD from removal and silently turn an import into a no-op. * fix(browser): plan every cookie's fate before any jar mutation STA-4300, change 2. Adds planImportWrites — pure, no I/O — so the write set and every removal scope can derive from one value instead of being computed twice. Not yet wired into the import paths; that is the next commits. TWO passes, and the second is not optional. Family-atomic skip is a property of the whole input: with a readable mixed.example row BEFORE an unreadable sub.mixed.example row, a per-row guard emits the readable one before anything knows the family will be skipped. Pass 1 classifies and collects the skipped families; pass 2 re-filters the provisional writes. Mutation-proved with a faithful one-pass guard (consult skippedFamilies as you go): the readable-before-unreadable case goes red and the unreadable-before- readable case still passes. That asymmetry is why both orders are tested and why only the first is the named detector. Family closure is at the registrable boundary because that is the boundary the removal scope actually expands to: importedDomainScopes turns an imported mixed.example into descendant roots, so a readable apex cookie drags a skipped subdomain's live session into the removal scope (STA-4300 §2b). hasUnrepresentableSkip surfaces a skip whose family cannot be named. A family we cannot name is one we cannot exclude from the removal plan, and clearing a family we cannot protect is the P0 this ticket exists to stop — so the caller refuses before mutating rather than proceeding and hoping. * fix(browser): derive path A's removal scope from the write plan (STA-4300 §2b) Change 3. importValidatedCookies now plans before it opens the jar, and the replacement scope and the write set are the SAME array. 210f961 filtered replacementDomains per exact cookie (partition.status !== 'unreadable'). That is not sufficient: replaceCookiesForImportedDomains expands each imported domain into its descendant roots, so a readable cookie on mixed.example pulls sub.mixed.example into the removal scope — and a skipped cookie living there has its session removed with nothing written back. Same erasure as the P0, different path. plan.writes is family-closed, and because path A passes the very same array to replaceCookiesForImportedDomains and to writeImportedCookies, the two sets cannot drift apart. That is stronger than keeping them in sync: there is only one set. Also here, both before any mutation: - an unrepresentable skip (registrableFamily → null) refuses the import, because a family we cannot name is one we cannot exclude from the removal scope; - the old-client gate now keys off plan.skips rather than re-deriving the condition. Counters: partitionSkippedCookies is a BREAKDOWN of skippedCookies — the unreadable rows plus their family-suppressed siblings — added in exactly once, so totalCookies === importedCookies + skippedCookies keeps holding. Counting it separately is how a summary silently stops adding up. Full src/main/browser suite: 69 files, 729 tests, green. * fix(browser): split path B into scan and emit, and never stage a skip (STA-4300) Change 4 — this is the commit that fixes the shipped P0. 210f961 did: decryptedCookies.push({ ..., partition }) // write set built HERE if (partition.status === 'unreadable') { ... continue } // guard AFTER so an unreadable row discovered late could not retract a sibling already emitted, while removeTransplantableCookies cleared the ENTIRE jar. The mutation set was the whole jar and the write set a strict subset of it, which is how a mixed readable/unreadable source emptied a populated jar and repopulated only part of it. Now the row loop SCANS only. Nothing is emitted inside it — not decryptedCookies, not domainSet, not a staging row, not the imported count. Between scan and emit, planImportWrites closes the skip over whole registrable families, and emit walks the plan. Each scanned candidate carries its raw source row because buildChromiumCookieInsertParams needs it; a record holding only the derived fields compiles and then silently cannot stage. Also between scan and emit, both before any mutation: - an unrepresentable skip refuses the import; - any skipped family calls disableStaging. A staged image is a whole-database replacement on the next start, so it cannot express "preserve this family"; main's existing memoryFailed arm then reports restart-fallback-unavailable. Test contract change, deliberately stronger: "never stages a partitioned row whose ancestor bit is unreadable" asserted that an image WAS registered and merely omitted the row. That image would still have erased the preserved family on replay. It now asserts no image is registered at all — plus a new paired case proving a no-skip import still stages, so "disable on skip" cannot be implemented as "disable always" unnoticed. Honest note on detection: reverting the emit filter currently reddens only the staging assertion, because every end-to-end fixture in this module still starts with an EMPTY jar — where clear-then-write-all and clear-then-write-some are indistinguishable. That is the blind spot that let this ship. The populated-jar suite in the next commit is what actually detects the erasure. Full src/main/browser: 69 files, 730 tests, green. * fix(browser): never remove a family the import declined to write (STA-4300 I2) Change 5, and the one that makes preservation observable. removeTransplantableCookies takes preserveFamilies. removableCookieEntries filters those families out, which keeps them out of the removal plan AND — since the CDP snapshot is taken from that same list — out of the restore set, so a preserved coordinate is never submitted to any mutation at all. When anything is preserved, the bulk clearData path is not used. clearData removes everything outside excludeOrigins, and its own comment concedes a rejection may already have emptied part of the jar; a preserved family is deliberately absent from the snapshot, so a partial delete followed by a rejection would destroy it with no identity able to restore it. Handing a dynamically derived preserve list to that primitive cannot be made safe, so a skip-bearing clear runs the frozen per-coordinate plan — which already excludes those families — as its primary path instead. Nothing is preserved on an ordinary import, so that path keeps today's single clearData call unchanged. New populated-jar suite. Every end-to-end fixture in this module starts with cookies.get returning [], and against an empty jar "clear then write all" and "clear then write some" are indistinguishable — which is why four independent gates missed the P0. These fixtures start populated. Mutation-proved, and this is the first detector in the change set that catches the actual erasure rather than a proxy: - drop the preserved-family filter → 6 of 8 red - use bulk clearData while preserving → 6 of 8 red, including "leaves a preserved family untouched", which is the erasure itself IPv4-literal and single-label host families are covered explicitly: psl reads 127.0.0.1 as the dotted DNS name '0.1', so a wrong family here would fail to match the preserve set and erase the live loopback session. Full src/main/browser: 70 files, 738 tests, green. * test(browser): pin STA-4300 end to end in real Electron, both write paths Ports the pre-implementation reproduction into the PR. Verified RED against main's product code and GREEN with the fix, on both paths — I re-ran it both ways rather than assuming. Two assertions are INVERTED rather than deleted, and both are now stronger. The repro proved the defect by showing cookies.set was called WITHOUT a partitionKey; after the reland the import write path does not touch cookies.set for user data at all, so seeing the imported cookie there is itself the regression. The fixture's internal guard is inverted the same way. Non-vacuity, asserted in-run rather than in a report: ok:true with a nonzero importedCookies, the importer reaching its terminal step, the source really carrying its partition fields, and a CONTROL cookie written via CDP *with* a partitionKey and read back with it — so "partitionKey absent" cannot be confused with "the oracle cannot see partitions". electronVersion proves Electron ran. Fixture correction worth recording, because the original reproduction was invalid on this path and I did not catch it on first read: readJsonCookiePartition reads a NESTED partitionKey object, but the fixture wrote topLevelSite and hasCrossSiteAncestor at the entry's top level, where the importer never looks. The file/paste case therefore failed on main for a fixture-shape reason rather than for the defect — and its own non-vacuity check validated what the fixture wrote instead of what the parser reads, which is exactly how a check that looks rigorous proves nothing. Only the native half was ever a real reproduction. Partition keys use a schemeful SITE, not an origin: Chromium canonicalises https://app.example.com to https://example.com, measured via CDP. * fix(browser): fail closed on lossy cookie identity recovery * fix(browser): preserve unreadable families before decrypt * fix(browser): reject malformed cookie partition sites * fix(browser): validate recovered cookie partition sites * fix(browser): reject empty JSON partition identities * fix(browser): fail closed and serialize cookie imports * fix(browser): reject malformed CDP opaque flags * fix(browser): roll back outcome-unknown cookie writes * revert(browser): move import serialization out to STA-4601 Reverts only the concurrency-serialization half of f7c27b7 so stablyai#15030 stays scoped to the STA-4300 reland. That commit mixed two concerns; this removes one of them and keeps the other. REMOVED (moves to STA-4601, a separate pre-existing P1): - acquireCookieMutationLock / withCookieMutationLock and the mutationLocks map; clear.ts goes back to withCookieClearLock - the import-wide lock in path A (mutationOwner on the target, acquire/release around replace + writes + rollback) - the widened lock around path B's clear + memory writes - browser-cookie-import-concurrency.test.ts KEPT (genuinely STA-4300 scope, not concurrency): - partitionKeyOpaque handling in readJsonCookiePartition and the CDP snapshot. An opaque partition key cannot be represented faithfully, so it reads as unreadable and its family is preserved — exactly the rule this ticket adds. 194e57a's refinement of that shape stays too. The concurrent-import interleaving is real and reachable (nothing serialises imports per partition, and the clear lock is released before the memory writes), but it predates this change and is not caused or worsened by it. It gets its own PR and its own review rather than riding a P0 reland whose history is that every additional fix introduced a new defect. src/main/browser: 71 files, 772 tests, green. Electron oracle still passes on both write paths and still goes red against main's product code.
* fix(browser): serialize cookie imports per partition (STA-4601) Two concurrent cookie imports on one partition can erase a session. Nothing serialises imports per partition — neither the renderer IPC handler (browser-session-profile-ipc.ts) nor the runtime RPC method (orca-runtime-browser.ts) — and the clear lock covered only the clear itself, so it was released before the writes and before any rollback. Reachable interleaving: import A replaces cookies for its imported domains, releases the lock, and later fails a write; import B clears and writes; A's rollback then removes cookies B already wrote and reported as imported. Path B has the same shape: A clears, B clears, then A writes its cookies on top of B's jar. Fix: one lock spans the whole live-jar transaction on both paths — the clear/replace, the writes, and the rollback. withCookieClearLock becomes acquireCookieMutationLock/withCookieMutationLock so path A can hold it across a try/finally rather than a single callback. Rebased onto stablyai#15030 (STA-4300), which rewrote this file: imports now write through CDP identities, so path A's writes moved from an inline cookies.set() loop into writeImportedCookies(), path B's into the same helper, and — the part that matters for a lock — importValidatedCookies no longer holds the Electron Session at all. It receives a CookieImportTarget that hides the Session behind openWriteStore(), and openWriteStore() builds a FRESH adapter per call, so keying the lock on anything reachable from it would serialise nothing. The target therefore carries mutationLockOwner, set to session.fromPartition's instance, which is the same object the native path locks on. That is what keeps both paths on one key per partition. Deliberately bounded: this covers the LIVE JAR only. Staging and cold-start replay keep their existing semantics, so two other pre-existing hazards in that subsystem are untouched and still open — the crash window between the clear and the result, and a permanently-armed replay when replay keeps failing. Both need the pending-image operations to become provable, which is a different change. The lock is keyed per owner, so imports into different partitions still run concurrently. Mutation-proved against the rebased tree, every mutation structure-preserving (brace/paren balance pinned) and every one re-run rather than carried over: dropping path A's acquire reddens the file-import detector; keying path A's acquire on a fresh object instead of mutationLockOwner reddens it too — the lock-present-but-miskeyed shape this rebase risks; replacing path B's lock with a passthrough reddens the native detector; doing both reddens both, which rules out incidental serialisation; and neutering the cold-init probe's lock reddens the new probe detector. That last detector is new: neutering the probe lock previously left all 779 browser tests green, so the probe's protection was unproven. The concurrency suite's store stub also gained writeCookieIdentity and getStoragePath. Without them the STA-4300 code throws a TypeError that writeImportedCookies catches as a write rejection, so the imports would have taken the failure path while the ordering assertions still passed. Each real import test now asserts writeCookieIdentity was CALLED, and that cookies.set never was. src/main/browser: 72 files, 780 tests, green; typecheck, oxlint, type-aware code quality, oxfmt and the max-lines ratchet all clean. * fix(browser): serialize native cookie staging * test(browser): pin native flush serialization * test(browser): pin staged cookie replay ordering * test(browser): remove vacuous staged replay detector * test(browser): detect stale native staging images * test(browser): guard cookie import ordering events * test(browser): cover staging lock boundary
















ELI5
Electron's
cookies.set()silently throws away a cookie's "which site was I embedded under" tag. So importing a partitioned (CHIPS) cookie quietly downgraded it into a different cookie the site can't read — and the import said "success".The first attempt at this fix shipped and was reverted 47 minutes later, because it cleared the whole cookie jar and then wrote back only part of it, erasing working logins. This reland fixes the original bug and that one: if any cookie in a site's family can't be written faithfully, the whole family is left completely alone — not written, and not deleted.
What Changed
Reverts the revert
3c8410d927(#14942) to restore the reviewed #14729 tree, then fixes the defect that caused it in separate, legible commits:registrableFamily()— one definition of "cookie family", used by every consumer of the skip set.planImportWrites()— decides every cookie's fate before any mutation. Two passes, because family-atomic skip is a property of the whole input.removeTransplantableCookiestakespreserveFamiliesand never submits a preserved coordinate to a removal or a restore.The shipped defect, exactly:
…followed by a jar-wide clear. The mutation set was the whole jar; the write set was a strict subset of it.
Two deliberate behaviour changes, stated rather than discovered later:
main's existingrestart-fallback-unavailablewarning already reports the degradation.clearData. Its own contract admits a rejection may already have emptied part of the jar, and a preserved family is deliberately absent from the snapshot, so a partial delete then a rejection would destroy it with nothing able to restore it. The ordinary no-skip import keeps today's singleclearDatacall unchanged.Why
cookies.set()cannot expresspartitionKey. That one API boundary produced four P0s (STA-4013 → 4061 → 4090 → 4170). Routing writes through CDP identities is the root fix; the invariant added here is what makes it safe:Linked Issue
STA-4300
Visual Proof
N/A— main-process cookie-import logic with no UI change. Behaviour is pinned by a real-Electron test that is red againstmainand green here, on both write paths. Electron QA evidence is being attached separately.Testing
pnpm vitest run --config config/vitest.config.ts src/main/browser— 71 files, 740 tests, greenpnpm typecheckclean;oxlintclean (verified alive by injecting a violation — it is silent when clean);oxfmt --checkclean; max-lines ratchet OK, nomax-linesdisable addedbrowser-cookie-import-partition-reland.electron.test.ts. Verified RED againstmain's product code and GREEN with the fix by reverting and re-running, not by assuming.Mutation proofs (each broken deliberately, then reverted):
registrableFamilyreadable-before-unreadablered,unreadable-before-readablegreen — the predicted asymmetryclearDatawhile preservingThe populated-jar suite is the point. Every pre-existing end-to-end fixture in this module starts with
cookies.getreturning[], and against an empty jar "clear then write all" and "clear then write some" are indistinguishable. That is why the original defect passed code review, a readiness audit, Electron QA and full CI. The new fixtures start populated.Platforms: macOS tested locally. Main-process only — no mobile, SSH, or Windows/WSL surface (no platform-specific paths, shells, or transports touched).
AI Disclosure
Review
#14683 liveness. This reland conflicts with #14683 (
886dec1d2a, merged hours earlier) inbrowser-cookie-import.ts. Both conflict hunks are keep-both. Its two suites still pass (13/13); its session double gainsgetStoragePath, and its positive-write assertion moves fromcookies.setto the CDP identity store — adapted, not weakened, and now strictly stronger because it also assertscookies.setcarries no imported user data. Every decryption assertion is untouched.Scope call for the merge decision. The revert restores one change that is not a CDP-write fix:
targetPartitionis derived fromtargetSession.getStoragePath()rather than accepted from the caller. It arrives with the revert and removing it means extra hand-written surgery on the reviewed tree, so it is kept — but flagged here rather than buried. Trivially removable as a follow-up if you'd rather it land separately.Concurrency split out — now #15095 (STA-4601). An earlier revision of this branch also serialized cookie imports per partition. That is a pre-existing defect independent of this reland, so at Brennan's direction it moved to its own PR against its own ticket, and this PR is scoped to partition preservation only. The net diff here contains no locking change.
Known limitation, disclosed rather than half-fixed. The pre-existing staged-image/replay subsystem has defects this PR deliberately does not touch: a crash window between the clear and the result, and a permanently-armed replay when replay keeps failing. (The third — concurrent imports — is now #15095.) This PR's guarantee is therefore bounded to this import's own mutations: it never removes a preserved coordinate. It does not promise immunity from a file-level replay. One case becomes newly reachable (skip + write rejection + a silently-failed prior-image clear + restart), which is stated rather than folded into "unchanged".
Agent skill upstream boundary
Notes
getStoragePathderivation); no new SQL, no string-interpolated queries, no new IPC surface.partitionSkippedCookiesis an optional summary field gated by an explicitsupportsPartitionSkippedCookiescapability; a client that cannot render the skip fails the import before any mutation rather than reporting a partial import as success. Followsdocs/reference/remote-wire-compatibility.md.clearDatafor a per-cookie removal pass, already bounded byCOOKIE_CLEAR_CONCURRENCY. The common no-skip path is unchanged.Checklist
N/Awith reason for visual proofpnpm lint,pnpm typecheck,pnpm testpass locallyAuthor