Skip to content

fix(browser): scope a native cookie import's clear to the domains it imports (STA-4797) - #15375

Merged
brennanb2025 merged 4 commits into
mainfrom
brennan/sta-4797-cookie-import-clears-the-entire-partition-jar-silently
Aug 19, 2026
Merged

brennanb2025 merged 4 commits into
mainfrom
brennan/sta-4797-cookie-import-clears-the-entire-partition-jar-silently

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Aug 18, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 10 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​884 $\color{#cf222e}{\Huge{\mathbf{−}}}$​226 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​658
Prod 7 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​439 $\color{#cf222e}{\Huge{\mathbf{−}}}$​123 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​316

Fixes STA-4797.

The defect

A native cookie import (Settings → Browser → Import Cookies → From Google Chrome) cleared the entire target partition's cookie jar, keeping only the non-transplantable google.com family. Every unrelated site you were signed into in that partition was silently signed out — no warning before, no disclosure after. Observed in Electron QA on 2026-08-17: a working the-internet.herokuapp.com login was destroyed by an import that brought over github.com, nordaccount.com and youtube.com.

The stated rationale — mixing stale and imported cookies makes sites reject the session — reaches only as far as the domains being imported. Beyond them a clear has nothing to reconcile. The file/paste path already did the narrow thing through replaceCookiesForImportedDomains; the two import paths simply disagreed about scope, and the narrow one is the defensible shape.

The fix

The native import's clear now covers only the domains it writes, through one shared predicate.

  • browser-cookie-import-policy.ts — importedDomainScope() / domainIsInImportedScope() are exported as the single scope definition used by all three clears, so they cannot drift apart. (NON_TRANSPLANTABLE_HOST_KEY_SQL and NON_TRANSPLANTABLE_CLEAR_EXCLUDED_ORIGINS lost their last production callers and are gone.)
  • browser-cookie-import-clear.ts — removeTransplantableCookies takes a required importScope. It is deliberately not defaulted: a default would be the whole jar again. The scope test runs before the removal-URL derivation, so an unaddressable cookie parked in an unrelated corner of the jar no longer fails an import that was never going to touch it.
  • The bulk clearData shortcut is gone, and clearData leaves CookieClearSession for the same structural reason set already had. It clears by exclusion, so the only scope it can express is "everything except google.com" — the defect itself. An include list is no better: it matches at the registrable-domain boundary, so it would still take host-only siblings the import does not replace, and a partial delete followed by a rejection would destroy them with no identity to restore from (the STA-4090/4170 shape). The frozen per-coordinate plan is now the only removal path, and it covers the imported domains rather than the jar.
  • browser-cookie-staged-image-clear.ts (new) — this is the half that is easy to miss. The staged image is a copy of the live jar that replaces it wholesale on the next cold start, so its DELETE FROM cookies WHERE NOT (<google>) was a second whole-partition wipe. Narrowing the live clear alone would have re-erased the partition one restart later. It now clears to the identical scope through the identical predicate.

The scope is named from the emitted plan — the same rows the writes come from — so the removal set is the write set. Google stays exempt by policy (STA-3811), unchanged.

Scope note

The ticket offered a fallback ("at minimum, disclose before destroying"). This PR does the preferred fix instead, which makes the fallback unnecessary: the destroyed scope is now exactly the imported scope, and the summary's existing domains field already names it. No wire or summary-type change, so nothing here is a mixed-version concern.

Testing

Fixtures in this module start with an empty cookie jar, which is why a full gate stack — review, readiness audit, Electron QA, CI — previously passed a session-erasing defect.

browser-cookie-import-scope.test.ts (new) uses a populated jar holding a session for a site outside the import set, and reads the staged file itself so the restart path is observed rather than assumed:

  1. the unrelated site's cookie survives, the stale in-scope cookie is still removed, Google stays exempt, and a blank-domain cookie no longer aborts the import;
  2. a subdomain of an imported domain is cleared while a lookalike registrable domain is not;
  3. the staged cold-start image keeps the out-of-scope rows.

All three fail against pre-fix source (verified by reverting only the fix's source files and re-running): case 3 comes back with 2 staged rows where 3 are expected — the unrelated site's row missing from the restart image.

The real-Electron partition test now seeds both an in-scope stale cookie (still removed) and an out-of-scope live one (now survives), so the behaviour is proven against a real Electron cookie jar, not only mocks. That expectation was mutation-checked to confirm the fixture genuinely runs.

Existing tests that only pinned the bulk-clearData path were rewritten to pin the per-coordinate removal, and two cases that had become vacuous were re-seeded: one forced its rejection on a domain the import never covered (so nothing entered the removal plan at all). The STA-4170 mid-clear-arrival hooks moved from clearData to snapshotClearIdentities — the same window — and were mutation-verified to still go red.

src/main/browser: 72 files, 773 tests, all passing. Typecheck and oxlint clean.


Rebased onto #15095

This branch was rebased after #15095 (serialize cookie imports per partition) landed. That PR re-indented the whole native import inside a per-partition lock, so the textual conflict was large and mostly indentation. Rather than resolve it line by line, browser-cookie-import.ts was reset to main's version and the five edits above re-applied on top — git diff origin/main for that file is now exactly those edits, and withCookieMutationLock / acquireCookieMutationLock / mutationLockOwner are untouched. The scoped staged-image delete sits inside the same BEGIN/COMMIT it did before.

#15095's new native concurrency detector read "has the second import started clearing yet?" off clearData call counts. Removing the bulk clearData path takes that signal away, so the assertion no longer measured anything. It is re-anchored on the removals themselves — remove:old-a present while remove:old-b is absent — which distinguishes "the first import cleared" from "the second import cleared" in a way a call count could not, and the completed run pins the exact removal sequence (which incidentally records that each import now clears only its own domain).

Its seeded jar had to move onto the imported domains, for the same reason its own comment already gave for not leaving the jar empty: under a scoped clear, a jar holding only an unrelated site is the empty-jar case in disguise — the clear removes nothing and every assertion passes vacuously.

Mutation-checked: with the per-partition lock removed, that detector still fails. #15095's protection is intact.

@coderabbitai

coderabbitai Bot commented Aug 18, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Cookie import cleanup now uses explicit imported-domain scopes. Live removal follows a frozen, per-cookie plan with rollback and mutation locking. Staged Chromium databases record scope metadata and merge only matching cookies, while legacy images retain whole-image replay. Pending imports now support structured metadata, validation, Windows-safe staged-file consumption, and retry preservation. Tests cover domain filtering, preserved cookie families, concurrency, rollback, schema drift, cold-start replay, and future formats.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 40.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly identifies the browser fix: native cookie clearing is limited to imported domains.
Description check ✅ Passed The description explains the defect, fix, scope, rationale, linked issue, testing, regressions, and limitations; it is mostly complete despite omitted template sections.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

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

❤️ Share

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

144-147: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Reduce repeated rationale comments.

Keep one short comment where the shared scope contract is defined. Remove or shorten repeated explanations at downstream call sites.

  • src/main/browser/browser-cookie-import-policy.ts#L144-L147: reduce the scope rationale to one brief contract comment.
  • src/main/browser/browser-cookie-import-clear.ts#L48-L50: shorten the clearData rationale.
  • src/main/browser/browser-cookie-import-clear.ts#L186-L188: shorten the required-scope rationale.
  • src/main/browser/browser-cookie-import-clear.ts#L217-L223: shorten the per-coordinate removal rationale.
  • src/main/browser/browser-cookie-import.ts#L1929-L1938: reference the shared scope contract briefly.
  • src/main/browser/browser-cookie-import.ts#L2026-L2031: reduce the repeated live-clear rationale.
  • src/main/browser/browser-cookie-staged-image-clear.ts#L11-L17: reduce the staged-image rationale.

As per coding guidelines: “Comments must be concise, non-obvious, and brief—prefer one line.”

Source: Coding guidelines

src/main/browser/browser-cookie-import-scope.test.ts (1)

146-156: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Extract the partition session mock into a helper.

The same session literal is repeated three times. Only cookies.get differs between the three copies. A helper keeps the fixture in one place, so a future field added to the session shape needs one edit instead of three.

♻️ Proposed helper
+function mockPartitionSession(
+  jarCookies: Record<string, unknown>[],
+  storagePath: string,
+  remove: ReturnType<typeof vi.fn>
+) {
+  return {
+    cookies: {
+      get: vi.fn().mockResolvedValue(jarCookies),
+      set: vi.fn(async () => undefined),
+      remove,
+      flushStore: vi.fn().mockResolvedValue(undefined)
+    },
+    clearData: vi.fn().mockResolvedValue(undefined),
+    setUserAgent: vi.fn(),
+    getStoragePath: () => storagePath
+  }
+}

Then each call site becomes:

-    sessionFromPartitionMock.mockReturnValue({
-      cookies: {
-        get: vi
-          .fn()
-          .mockResolvedValue(populatedTargetJar().filter((cookie) => cookie.domain !== '')),
-        set: vi.fn(async () => undefined),
-        remove: cookiesRemoveMock,
-        flushStore: vi.fn().mockResolvedValue(undefined)
-      },
-      clearData: vi.fn().mockResolvedValue(undefined),
-      setUserAgent: vi.fn(),
-      getStoragePath: () => join(tmpDir, 'userData', 'Partitions', 'test')
-    })
+    sessionFromPartitionMock.mockReturnValue(
+      mockPartitionSession(
+        populatedTargetJar().filter((cookie) => cookie.domain !== ''),
+        join(tmpDir, 'userData', 'Partitions', 'test'),
+        cookiesRemoveMock
+      )
+    )

Also applies to: 182-213, 231-243

src/main/browser/browser-cookie-import-partition.electron.test.ts (1)

79-86: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Rename the preserved cookie so its name matches its role.

The cookie named stale is the one that must survive the import, and its value is keep-me. The cookie that must be removed is named superseded. The name stale now contradicts the assertion it supports. Rename it to something like unrelated in both the fixture and the remainingNames expectation.

♻️ Proposed rename
   await targetSession.cookies.set({
     url: 'https://stale.example/',
-    name: 'stale',
+    name: 'unrelated',
     value: 'keep-me',
     secure: true
   })
       'partitioned-google',
-      'stale'
+      'unrelated'

Keep the expected array sorted after the rename.

Also applies to: 220-221


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 543f1b46-9a8a-4915-8e04-6d94e1adf34f

📥 Commits

Reviewing files that changed from the base of the PR and between ccb2305 and d44981f18facc572e758336d2fe23217cd42c9c3.

📒 Files selected for processing (11)
  • src/main/browser/browser-cookie-clear-preserve.test.ts
  • src/main/browser/browser-cookie-import-clear-atomicity.test.ts
  • src/main/browser/browser-cookie-import-clear.ts
  • src/main/browser/browser-cookie-import-google-exclusion.test.ts
  • src/main/browser/browser-cookie-import-partition-rollback.electron.test.ts
  • src/main/browser/browser-cookie-import-partition.electron.test.ts
  • src/main/browser/browser-cookie-import-policy.test.ts
  • src/main/browser/browser-cookie-import-policy.ts
  • src/main/browser/browser-cookie-import-scope.test.ts
  • src/main/browser/browser-cookie-import.ts
  • src/main/browser/browser-cookie-staged-image-clear.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 6 remain after this review.

@brennanb2025
brennanb2025 force-pushed the brennan/sta-4797-cookie-import-clears-the-entire-partition-jar-silently branch from 769952f to 5ac83f9 Compare August 18, 2026 22:41
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Electron QA — PR #15375 / STA-4797

Worktree: /Users/brennanbenson/orca/workspaces/orca/sta-4797-cookie-import-clears-the-entire-partiti
Branch: brennan/sta-4797-cookie-import-clears-the-entire-partition-jar-silently
Date: 2026-08-18
Outcome: Visible native-import gate not completed. Identity + isolated launch succeeded. Native Chrome import was not invoked (would read real user browser profiles). File import was not invoked (native OS picker cannot be driven via CDP). Renderer never mounted, so Settings → Browser → Import Cookies could not be exercised.

Gate this PR actually needs

A native cookie import (importCookiesFromBrowser, Settings → Browser → Import Cookies → From Google Chrome) must:

  1. Preserve an unrelated signed-in cookie (e.g. the-internet.herokuapp.com / out-of-scope host)
  2. Replace an in-scope stale cookie on a domain the import writes
  3. Preserve the non-transplantable google.com family
  4. Leave the staged cold-start image equally narrow (same predicate as the live clear)

This is the native Chromium path. The file/paste path already used replaceCookiesForImportedDomains and is not the defect.

Launch

  • Unique ORCA_DEV_USER_DATA_PATH: isolated temp profile
  • CDP port 9333 (free at launch)
  • Renderer 5173 (free at launch)
  • Launched only this worktree via config/scripts/run-electron-vite-dev.mjs
  • Interaction: Playwright CDP only. No computer-use, no OS automation, no real browser profile import.

window.api.app.getIdentity()

name: Orca: brennan/sta-4797-cookie-import-clears-the-entire-partition-jar-silently
isDev: true
devBranch: brennan/sta-4797-cookie-import-clears-the-entire-partition-jar-silently
devWorktreeName: sta-4797-cookie-import-clears-the-entire-partiti
devRepoRoot: /Users/brennanbenson/orca/workspaces/orca/sta-4797-cookie-import-clears-the-entire-partiti

Dock tile present: Orca/ brennan-sta-4797-cookie-import-clears-the-entire-partition-jar-silently

Isolated backing state (before any import)

  • Default session profile: { id: "default", partition: "persist:orca-browser", source: null }
  • Partitions/orca-browser/ exists; no partition Cookies file yet (Electron creates it only after a cookie is stored)
  • No cookie-import-staging/ directory
  • No cookie-import-diag.log
  • Native import not invoked
  • sessionDetectBrowsers() returned real installed Chrome / Comet / Firefox / Safari profiles. Metadata only; no cookies were read or imported.

Visible rendered state

React never mounted. #root stayed empty. Uncropped CDP screenshot of the launched worktree window:

02-product-renderer-uncropped.png

Renderer console (fatal for the module graph):

Error: Module "node:path" has been externalized for browser compatibility.
Cannot access "node:path.posix" in client code.
    at src/shared/quick-open-filter.ts:9

That import is already on origin/main. It is not introduced by this PR. It blocked Settings → Browser in this electron-vite dev launch, so the Import Cookies dropdown could not be opened.

Labeled diagnostic overlay (not product UI; injected after the blank render so identity/API evidence is visible):

03-qa-diagnostic-overlay.png

Why the exact native import was not driven

browser:session:importFromBrowser always resolves the source via detectInstalledBrowsers(), which points at the user's real Chrome/Comet/Firefox/Safari profiles. Clicking From Google Chrome would copy those cookies into the isolated partition. That is forbidden for this QA.

There is no renderer/IPC path to point native import at a disposable Chromium Cookies fixture without editing production code.

From File… opens dialog.showOpenDialog. CDP cannot complete that native picker, and OS-level dialog automation is also forbidden.

Backing tests run in this worktree (disposable fixtures only)

src/main/browser/browser-cookie-import-scope.test.ts                         3 passed
src/main/browser/browser-cookie-import-partition.electron.test.ts             1 passed
src/main/browser/browser-cookie-import-partition-rollback.electron.test.ts    1 passed

These cover the four-way gate against a disposable source DB and a populated target jar (unrelated session preserved, in-scope stale cookie removed, Google family kept, staged image equally narrow). They are not a substitute for the visible Settings import surface.

No performance concern observed on these paths. No STA-4797 live-jar regression was proven or disproven in the running app, because the native import was not executed there.

Remaining gap

Until either:

  1. the electron-vite renderer mounts (the node:path boot error is a pre-existing main issue), and
  2. native import can be aimed at a disposable Chromium Cookies DB without reading a real user profile,

this PR does not have a truthful before/after of Settings → Browser → Import Cookies → From Google Chrome on a populated jar.

Do not treat the blank window or the diagnostic overlay as proof that the import scope is correct in the product UI.

Not done

  • No production code edits
  • No commits / no push
  • No images committed to the repo
  • No real browser profiles or user cookies were imported

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 7d23cb15-cb9b-431e-9747-29dea3a340ca

📥 Commits

Reviewing files that changed from the base of the PR and between 5ac83f9 and 8b1ddc2.

📒 Files selected for processing (8)
  • src/main/browser/browser-cookie-import-scope.test.ts
  • src/main/browser/browser-cookie-import.ts
  • src/main/browser/browser-cookie-staged-import.ts
  • src/main/browser/browser-session-cookie-staging.scoped.test.ts
  • src/main/browser/browser-session-cookie-staging.ts
  • src/main/browser/browser-session-meta-store.ts
  • src/main/browser/browser-session-registry.persistence.test.ts
  • src/main/browser/browser-session-registry.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 8 remain after this review.

Comment on lines +113 to 134
copyFileSync(stagedPath, liveCookiesPath)
// Why: stale WAL/SHM sidecars would corrupt CookieMonster's read of the freshly swapped DB.
let sidecarCopyFailed = false
for (const suffix of ['-wal', '-shm']) {
try {
unlinkSync(liveCookiesPath + suffix)
} catch {
/* may not exist */
}
const stagingSidecar = stagedPath + suffix
if (!existsSync(stagingSidecar)) {
continue
}
try {
copyFileSync(stagingSidecar, liveCookiesPath + suffix)
} catch {
sidecarCopyFailed = true
}
}
const stagingSidecar = stagedPath + suffix
if (!existsSync(stagingSidecar)) {
if (sidecarCopyFailed) {
// Why: sidecar copy failed → inconsistent replay; keep this entry for retry.
continue

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

Prevent partial replay when a sidecar copy fails.

Line 113 replaces the live database before Lines 122-130 copy the staged WAL and SHM files. If a sidecar copy fails, Line 134 retains the pending entry but leaves the live database replaced and its prior sidecars removed. A WAL-backed staged image can then lose committed frames before the retry occurs.

Stage the complete database bundle before replacing the live bundle, or restore the prior live database and sidecars on failure. Add a regression test for a -wal copy failure.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Review complete — LAND

Final reviewed head: 8b1ddc256e

No P0, P1, or P2 findings remain after the same-model senior review loop and closing readiness audit.

Meaningful fixes made during review:

  • Rebased onto the current cookie-import serialization path and updated the concurrency detector to assert scoped per-cookie removal rather than the removed bulk clear.
  • Fixed a cold-start data-loss path: a failed in-memory import could leave a whole-DB snapshot that later overwrote unrelated cookies created or rotated after the import. New staged imports now transactionally merge only the recorded imported-domain scope.
  • Added rollback, schema/version validation, retry idempotence, self-contained staging, and durable replay consumption.
  • Added versioned pending-import metadata. Legacy string entries remain readable, unknown future formats fail closed, and downgraded builds cannot mistake new scoped stages for legacy whole-image replays.

Validation:

  • Local bounded browser suite: 74 files / 788 tests passed
  • Focused changed-area suite: 6 files / 51 tests passed
  • Real Electron partition and rollback fixtures passed
  • Typecheck, affected-file lint, formatting, and git diff --check passed
  • Full GitHub matrix passed: every Node 24/26 shard, static analysis, typecheck, compatibility gates, package, Windows package, and final aggregate verification
  • Performance review found no hot-path or polling work; the new scan is bounded to explicit import/cold-start replay and mutates only matching host keys

Electron evidence and uncropped screenshots are attached in the Electron QA comment. The exact isolated worktree identity and disposable partition fixtures were verified. The visible Settings import flow was not driven: the renderer hit a pre-existing main-branch node:path boot error, and invoking native Chrome import would have read real user browser data. That limitation is not a regression from this PR and is recorded in the evidence comment.

This is desktop browser-cookie code only; mobile, SSH, and remote-wire validation were not applicable. Windows compatibility is covered by the passing Windows package job and the retry-safe file handling review.

…imports (STA-4797)

A native import (Settings -> Browser -> Import Cookies -> From Google Chrome)
cleared the entire target partition's cookie jar, keeping only the
non-transplantable google.com family. Every unrelated site the user was signed
into in that partition was silently signed out, with no warning before and no
disclosure after. Importing three sites signed you out of every other one.

The stated rationale -- mixing stale and imported cookies makes sites reject the
session -- reaches only as far as the domains being imported. Beyond them a
clear has nothing to reconcile. The file/paste path already did the narrow
thing via replaceCookiesForImportedDomains; the two import paths simply
disagreed about scope, and the narrow one is the defensible shape.

The clear now covers only the domains the import writes, through one shared
predicate:

- browser-cookie-import-policy.ts: importedDomainScope() /
  domainIsInImportedScope() are exported as the single scope definition used by
  all three clears, so they cannot drift apart.
- browser-cookie-import-clear.ts: removeTransplantableCookies takes a required
  importScope. It is not defaulted -- a default would be the whole jar again.
  The scope test runs before the removal-URL derivation, so an unaddressable
  cookie parked in an unrelated corner of the jar no longer fails an import that
  was never going to touch it.
- The bulk clearData shortcut is gone, and clearData leaves CookieClearSession
  for the same structural reason 'set' already had. clearData clears by
  exclusion, so the only scope it can express is "everything except google.com"
  -- the defect. An include list is no better: it matches at the
  registrable-domain boundary, so it would still take host-only siblings the
  import does not replace, and a partial delete followed by a rejection would
  destroy them with no identity to restore from. The frozen per-coordinate plan
  is now the only removal path, and it covers the imported domains rather than
  the jar.
- browser-cookie-staged-image-clear.ts (new): the staged image is a copy of the
  live jar that replaces it wholesale on the next cold start, so its
  DELETE FROM cookies WHERE NOT (<google>) was a second whole-partition wipe.
  Narrowing the live clear alone would have re-erased the partition one restart
  later. It now clears to the identical scope, through the identical predicate.

The scope is named from the emitted plan, so the removal set is the write set.
Google stays exempt by policy (STA-3811), unchanged.

No wire or summary change: the summary's existing `domains` field already names
the imported domains, which is now exactly the scope that was cleared.

Tests: fixtures in this module start with an empty cookie jar, which is why a
full gate stack passed a session-erasing defect before. browser-cookie-import-
scope.test.ts uses a populated jar with a session for a site outside the import
set, and reads the staged file itself so the restart path is observed rather
than assumed. All three cases fail against pre-fix source. The real-Electron
partition test now seeds both an in-scope stale cookie (still removed) and an
out-of-scope live one (now survives).
…TA-4797)

Scoping the clear made the `Could not clear existing cookies` throw in
removableCookieEntries dead: a cookie whose domain does not normalize is now
skipped by the scope test above it, so nothing reaches the URL derivation with
anything but an already-parsed hostname.

Rather than leave a fail-closed branch that cannot fire — this module has been
misread before when a dead safety leg looked like a live one — the impossibility
is now structural. cookieRemovalUrl takes a normalizeCookieDomain output and
returns a string: `new URL` cannot throw on a host that already parsed as one,
and assigning pathname never throws. Both callers lose their null branch,
including the silent `if (url)` skip in replaceCookiesForImportedDomains, which
would have narrowed a removal plan without saying so.

The identically-worded throw in assertClearIdentitiesCoverRemovable is untouched
— that one is live and is what keeps the mutated set inside the restorable set.
…d clear (STA-4797)

#15095's detector read "has the second import started clearing yet?" off
clearData call counts. Scoping the clear removed the bulk clearData path, so
that signal is gone and the assertion measured nothing.

It now reads the same question off the removals themselves, which is strictly
more specific: the seeded jar holds a stale cookie for each import's own domain,
so `remove:old-a` present with `remove:old-b` absent proves the first import
cleared and the second has not — where a call count could not tell the two
apart. The completed run then pins the exact removal sequence, which also
records that each import clears only its own domain.

The seed had to move onto the imported domains for the same reason its own
comment already gave for not leaving the jar empty: under a scoped clear, a jar
holding only an unrelated site is the empty-jar case wearing a disguise -- the
clear returns having removed nothing and every assertion passes vacuously.

Mutation-checked: with the per-partition lock removed this test still fails, so
#15095's protection is intact and the re-anchoring did not hollow it out.
@brennanb2025
brennanb2025 force-pushed the brennan/sta-4797-cookie-import-clears-the-entire-partition-jar-silently branch from 8b1ddc2 to 214fa5e Compare August 19, 2026 02:39
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Rebase + revalidation update for 214fa5e003:

  • Rebased cleanly onto origin/main at 12724068b7, including the dev-renderer mount fix. git range-diff shows all four PR commits are patch-identical to the previously reviewed versions.
  • Same-model senior review: CLEAN — no meaningful correctness, regression, data-loss, security, cross-platform/remote, scope, or performance findings.
  • End readiness audit: PASS / CLEAN — no P0, P1, or P2 findings.
  • Local validation: typecheck passed; targeted oxlint passed; git diff --check passed; browser suite passed 74 files / 788 tests, including the native Electron partition-preservation and rollback fixtures.
  • Electron CDP validation: confirmed the exact dev branch identity, renderer mounted with 0 console errors, navigated through visible Settings → Browser, and opened the real Import Cookies menu. Backing state remained the default profile with no import in progress; no real browser profile was imported.
  • Fresh GitHub CI: 45 successful, 1 skipped, merge state CLEAN.

Settings → Browser → Import Cookies

The destructive real-profile import path was intentionally not exercised against the developer machine. Domain-scoped preservation, transactional rollback, and cold-start replay remain covered by the passing Electron/unit fixtures.

Status: LAND / ready to merge.

@brennanb2025
brennanb2025 merged commit d4a8da9 into main Aug 19, 2026
46 checks passed
paidaxingyo666 pushed a commit to paidaxingyo666/Manta that referenced this pull request Aug 21, 2026
…imports (STA-4797) (stablyai#15375)

* fix(browser): scope a native cookie import's clear to the domains it imports (STA-4797)

A native import (Settings -> Browser -> Import Cookies -> From Google Chrome)
cleared the entire target partition's cookie jar, keeping only the
non-transplantable google.com family. Every unrelated site the user was signed
into in that partition was silently signed out, with no warning before and no
disclosure after. Importing three sites signed you out of every other one.

The stated rationale -- mixing stale and imported cookies makes sites reject the
session -- reaches only as far as the domains being imported. Beyond them a
clear has nothing to reconcile. The file/paste path already did the narrow
thing via replaceCookiesForImportedDomains; the two import paths simply
disagreed about scope, and the narrow one is the defensible shape.

The clear now covers only the domains the import writes, through one shared
predicate:

- browser-cookie-import-policy.ts: importedDomainScope() /
  domainIsInImportedScope() are exported as the single scope definition used by
  all three clears, so they cannot drift apart.
- browser-cookie-import-clear.ts: removeTransplantableCookies takes a required
  importScope. It is not defaulted -- a default would be the whole jar again.
  The scope test runs before the removal-URL derivation, so an unaddressable
  cookie parked in an unrelated corner of the jar no longer fails an import that
  was never going to touch it.
- The bulk clearData shortcut is gone, and clearData leaves CookieClearSession
  for the same structural reason 'set' already had. clearData clears by
  exclusion, so the only scope it can express is "everything except google.com"
  -- the defect. An include list is no better: it matches at the
  registrable-domain boundary, so it would still take host-only siblings the
  import does not replace, and a partial delete followed by a rejection would
  destroy them with no identity to restore from. The frozen per-coordinate plan
  is now the only removal path, and it covers the imported domains rather than
  the jar.
- browser-cookie-staged-image-clear.ts (new): the staged image is a copy of the
  live jar that replaces it wholesale on the next cold start, so its
  DELETE FROM cookies WHERE NOT (<google>) was a second whole-partition wipe.
  Narrowing the live clear alone would have re-erased the partition one restart
  later. It now clears to the identical scope, through the identical predicate.

The scope is named from the emitted plan, so the removal set is the write set.
Google stays exempt by policy (STA-3811), unchanged.

No wire or summary change: the summary's existing `domains` field already names
the imported domains, which is now exactly the scope that was cleared.

Tests: fixtures in this module start with an empty cookie jar, which is why a
full gate stack passed a session-erasing defect before. browser-cookie-import-
scope.test.ts uses a populated jar with a session for a site outside the import
set, and reads the staged file itself so the restart path is observed rather
than assumed. All three cases fail against pre-fix source. The real-Electron
partition test now seeds both an in-scope stale cookie (still removed) and an
out-of-scope live one (now survives).

* refactor(browser): drop the unreachable removal-URL failure branch (STA-4797)

Scoping the clear made the `Could not clear existing cookies` throw in
removableCookieEntries dead: a cookie whose domain does not normalize is now
skipped by the scope test above it, so nothing reaches the URL derivation with
anything but an already-parsed hostname.

Rather than leave a fail-closed branch that cannot fire — this module has been
misread before when a dead safety leg looked like a live one — the impossibility
is now structural. cookieRemovalUrl takes a normalizeCookieDomain output and
returns a string: `new URL` cannot throw on a host that already parsed as one,
and assigning pathname never throws. Both callers lose their null branch,
including the silent `if (url)` skip in replaceCookiesForImportedDomains, which
would have narrowed a removal plan without saying so.

The identically-worded throw in assertClearIdentitiesCoverRemovable is untouched
— that one is live and is what keeps the mutated set inside the restorable set.

* test(browser): re-anchor the native concurrency detector on the scoped clear (STA-4797)

stablyai#15095's detector read "has the second import started clearing yet?" off
clearData call counts. Scoping the clear removed the bulk clearData path, so
that signal is gone and the assertion measured nothing.

It now reads the same question off the removals themselves, which is strictly
more specific: the seeded jar holds a stale cookie for each import's own domain,
so `remove:old-a` present with `remove:old-b` absent proves the first import
cleared and the second has not — where a call count could not tell the two
apart. The completed run then pins the exact removal sequence, which also
records that each import clears only its own domain.

The seed had to move onto the imported domains for the same reason its own
comment already gave for not leaving the jar empty: under a scoped clear, a jar
holding only an unrelated site is the empty-jar case wearing a disguise -- the
clear returns having removed nothing and every assertion passes vacuously.

Mutation-checked: with the per-partition lock removed this test still fails, so
stablyai#15095's protection is intact and the re-anchoring did not hollow it out.

* fix(browser): merge staged cookie imports by domain scope (STA-4797)
dallascrilley pushed a commit to dallascrilley/orca that referenced this pull request Aug 27, 2026
…imports (STA-4797) (stablyai#15375)

* fix(browser): scope a native cookie import's clear to the domains it imports (STA-4797)

A native import (Settings -> Browser -> Import Cookies -> From Google Chrome)
cleared the entire target partition's cookie jar, keeping only the
non-transplantable google.com family. Every unrelated site the user was signed
into in that partition was silently signed out, with no warning before and no
disclosure after. Importing three sites signed you out of every other one.

The stated rationale -- mixing stale and imported cookies makes sites reject the
session -- reaches only as far as the domains being imported. Beyond them a
clear has nothing to reconcile. The file/paste path already did the narrow
thing via replaceCookiesForImportedDomains; the two import paths simply
disagreed about scope, and the narrow one is the defensible shape.

The clear now covers only the domains the import writes, through one shared
predicate:

- browser-cookie-import-policy.ts: importedDomainScope() /
  domainIsInImportedScope() are exported as the single scope definition used by
  all three clears, so they cannot drift apart.
- browser-cookie-import-clear.ts: removeTransplantableCookies takes a required
  importScope. It is not defaulted -- a default would be the whole jar again.
  The scope test runs before the removal-URL derivation, so an unaddressable
  cookie parked in an unrelated corner of the jar no longer fails an import that
  was never going to touch it.
- The bulk clearData shortcut is gone, and clearData leaves CookieClearSession
  for the same structural reason 'set' already had. clearData clears by
  exclusion, so the only scope it can express is "everything except google.com"
  -- the defect. An include list is no better: it matches at the
  registrable-domain boundary, so it would still take host-only siblings the
  import does not replace, and a partial delete followed by a rejection would
  destroy them with no identity to restore from. The frozen per-coordinate plan
  is now the only removal path, and it covers the imported domains rather than
  the jar.
- browser-cookie-staged-image-clear.ts (new): the staged image is a copy of the
  live jar that replaces it wholesale on the next cold start, so its
  DELETE FROM cookies WHERE NOT (<google>) was a second whole-partition wipe.
  Narrowing the live clear alone would have re-erased the partition one restart
  later. It now clears to the identical scope, through the identical predicate.

The scope is named from the emitted plan, so the removal set is the write set.
Google stays exempt by policy (STA-3811), unchanged.

No wire or summary change: the summary's existing `domains` field already names
the imported domains, which is now exactly the scope that was cleared.

Tests: fixtures in this module start with an empty cookie jar, which is why a
full gate stack passed a session-erasing defect before. browser-cookie-import-
scope.test.ts uses a populated jar with a session for a site outside the import
set, and reads the staged file itself so the restart path is observed rather
than assumed. All three cases fail against pre-fix source. The real-Electron
partition test now seeds both an in-scope stale cookie (still removed) and an
out-of-scope live one (now survives).

* refactor(browser): drop the unreachable removal-URL failure branch (STA-4797)

Scoping the clear made the `Could not clear existing cookies` throw in
removableCookieEntries dead: a cookie whose domain does not normalize is now
skipped by the scope test above it, so nothing reaches the URL derivation with
anything but an already-parsed hostname.

Rather than leave a fail-closed branch that cannot fire — this module has been
misread before when a dead safety leg looked like a live one — the impossibility
is now structural. cookieRemovalUrl takes a normalizeCookieDomain output and
returns a string: `new URL` cannot throw on a host that already parsed as one,
and assigning pathname never throws. Both callers lose their null branch,
including the silent `if (url)` skip in replaceCookiesForImportedDomains, which
would have narrowed a removal plan without saying so.

The identically-worded throw in assertClearIdentitiesCoverRemovable is untouched
— that one is live and is what keeps the mutated set inside the restorable set.

* test(browser): re-anchor the native concurrency detector on the scoped clear (STA-4797)

stablyai#15095's detector read "has the second import started clearing yet?" off
clearData call counts. Scoping the clear removed the bulk clearData path, so
that signal is gone and the assertion measured nothing.

It now reads the same question off the removals themselves, which is strictly
more specific: the seeded jar holds a stale cookie for each import's own domain,
so `remove:old-a` present with `remove:old-b` absent proves the first import
cleared and the second has not — where a call count could not tell the two
apart. The completed run then pins the exact removal sequence, which also
records that each import clears only its own domain.

The seed had to move onto the imported domains for the same reason its own
comment already gave for not leaving the jar empty: under a scoped clear, a jar
holding only an unrelated site is the empty-jar case wearing a disguise -- the
clear returns having removed nothing and every assertion passes vacuously.

Mutation-checked: with the per-partition lock removed this test still fails, so
stablyai#15095's protection is intact and the re-anchoring did not hollow it out.

* fix(browser): merge staged cookie imports by domain scope (STA-4797)
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…imports (STA-4797) (stablyai#15375)

* fix(browser): scope a native cookie import's clear to the domains it imports (STA-4797)

A native import (Settings -> Browser -> Import Cookies -> From Google Chrome)
cleared the entire target partition's cookie jar, keeping only the
non-transplantable google.com family. Every unrelated site the user was signed
into in that partition was silently signed out, with no warning before and no
disclosure after. Importing three sites signed you out of every other one.

The stated rationale -- mixing stale and imported cookies makes sites reject the
session -- reaches only as far as the domains being imported. Beyond them a
clear has nothing to reconcile. The file/paste path already did the narrow
thing via replaceCookiesForImportedDomains; the two import paths simply
disagreed about scope, and the narrow one is the defensible shape.

The clear now covers only the domains the import writes, through one shared
predicate:

- browser-cookie-import-policy.ts: importedDomainScope() /
  domainIsInImportedScope() are exported as the single scope definition used by
  all three clears, so they cannot drift apart.
- browser-cookie-import-clear.ts: removeTransplantableCookies takes a required
  importScope. It is not defaulted -- a default would be the whole jar again.
  The scope test runs before the removal-URL derivation, so an unaddressable
  cookie parked in an unrelated corner of the jar no longer fails an import that
  was never going to touch it.
- The bulk clearData shortcut is gone, and clearData leaves CookieClearSession
  for the same structural reason 'set' already had. clearData clears by
  exclusion, so the only scope it can express is "everything except google.com"
  -- the defect. An include list is no better: it matches at the
  registrable-domain boundary, so it would still take host-only siblings the
  import does not replace, and a partial delete followed by a rejection would
  destroy them with no identity to restore from. The frozen per-coordinate plan
  is now the only removal path, and it covers the imported domains rather than
  the jar.
- browser-cookie-staged-image-clear.ts (new): the staged image is a copy of the
  live jar that replaces it wholesale on the next cold start, so its
  DELETE FROM cookies WHERE NOT (<google>) was a second whole-partition wipe.
  Narrowing the live clear alone would have re-erased the partition one restart
  later. It now clears to the identical scope, through the identical predicate.

The scope is named from the emitted plan, so the removal set is the write set.
Google stays exempt by policy (STA-3811), unchanged.

No wire or summary change: the summary's existing `domains` field already names
the imported domains, which is now exactly the scope that was cleared.

Tests: fixtures in this module start with an empty cookie jar, which is why a
full gate stack passed a session-erasing defect before. browser-cookie-import-
scope.test.ts uses a populated jar with a session for a site outside the import
set, and reads the staged file itself so the restart path is observed rather
than assumed. All three cases fail against pre-fix source. The real-Electron
partition test now seeds both an in-scope stale cookie (still removed) and an
out-of-scope live one (now survives).

* refactor(browser): drop the unreachable removal-URL failure branch (STA-4797)

Scoping the clear made the `Could not clear existing cookies` throw in
removableCookieEntries dead: a cookie whose domain does not normalize is now
skipped by the scope test above it, so nothing reaches the URL derivation with
anything but an already-parsed hostname.

Rather than leave a fail-closed branch that cannot fire — this module has been
misread before when a dead safety leg looked like a live one — the impossibility
is now structural. cookieRemovalUrl takes a normalizeCookieDomain output and
returns a string: `new URL` cannot throw on a host that already parsed as one,
and assigning pathname never throws. Both callers lose their null branch,
including the silent `if (url)` skip in replaceCookiesForImportedDomains, which
would have narrowed a removal plan without saying so.

The identically-worded throw in assertClearIdentitiesCoverRemovable is untouched
— that one is live and is what keeps the mutated set inside the restorable set.

* test(browser): re-anchor the native concurrency detector on the scoped clear (STA-4797)

stablyai#15095's detector read "has the second import started clearing yet?" off
clearData call counts. Scoping the clear removed the bulk clearData path, so
that signal is gone and the assertion measured nothing.

It now reads the same question off the removals themselves, which is strictly
more specific: the seeded jar holds a stale cookie for each import's own domain,
so `remove:old-a` present with `remove:old-b` absent proves the first import
cleared and the second has not — where a call count could not tell the two
apart. The completed run then pins the exact removal sequence, which also
records that each import clears only its own domain.

The seed had to move onto the imported domains for the same reason its own
comment already gave for not leaving the jar empty: under a scoped clear, a jar
holding only an unrelated site is the empty-jar case wearing a disguise -- the
clear returns having removed nothing and every assertion passes vacuously.

Mutation-checked: with the per-partition lock removed this test still fails, so
stablyai#15095's protection is intact and the re-anchoring did not hollow it out.

* fix(browser): merge staged cookie imports by domain scope (STA-4797)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant