Skip to content

fix(browser): route every cookie-import write through CDP identities (STA-4300) - #14729

Merged
brennanb2025 merged 12 commits into
mainfrom
brennanb2025/sta-4300-cdp-cookie-writes
Aug 16, 2026
Merged

brennanb2025 merged 12 commits into
mainfrom
brennanb2025/sta-4300-cdp-cookie-writes

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Aug 15, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 13 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1417 $\color{#cf222e}{\Huge{\mathbf{−}}}$​50 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1367
Prod 12 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​610 $\color{#cf222e}{\Huge{\mathbf{−}}}$​206 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​404

ELI5

Some sites store a cookie that only works inside one specific parent site — a "partitioned" (CHIPS) cookie. When Orca imported cookies from Chrome, it wrote them through an Electron API that cannot express that "only inside this parent site" part, so the attribute was quietly dropped. The import said "success", the cookie was there, and the site still could not see it.

This routes every cookie-import write through CDP, which can express it. If we cannot read a cookie's partition faithfully from the source, we now skip that cookie and tell you — we never write a downgraded copy.

What Changed

Both remaining user-data writes moved from session.cookies.set() to CDP Network.setCookie, through the identity machinery PR #14383 already built for the rollback path:

  • browser-cookie-import.ts — importValidatedCookies (file / paste / Safari / Firefox) and the native Chromium import's in-memory load.
  • importValidatedCookies no longer receives a Session at all. It takes a CookieImportWriteStore, which has no set on it, so the lossy write is not merely unused — it cannot be named. Same guard fix(browser): restore replaced cookies through CDP identities #14383 applied to the clear path.
  • New browser-cookie-source-partition.ts reads partition identity from the source: Chromium's top_frame_site_key + has_cross_site_ancestor for the native path, and a partitionKey object for JSON exports.
  • New browser-cookie-import-write.ts owns the write phase: plan → identity → write, with the skip decision in one place.
  • targetPartition hardening: the native path's partition directory now comes from targetSession.getStoragePath() instead of join(userData, 'Partitions', partitionString).
  • Reporting: partitionSkippedCookies on the import summary, plus a warning toast.

The one attach change: attachCookieClearSession falls back to its own hidden window if it cannot lease the debugger of an existing tab.

Why

Four P0s in this module came from one API boundary that cannot express cookie identity — STA-4013 → STA-4061 → STA-4090 → STA-4170. Each fix was correct and each spawned the next, because the lossy write stayed available. #14383 removed it from the clear path; this removes it from the import path, which is the last one that touches user data.

Named user-visible harm for each behavior change (nothing here changes without one):

Change Concrete harm it prevents
Route import writes through CDP A CHIPS cookie from Chrome is imported unpartitioned. The import reports success, the cookie is in the jar, and the site cannot see its own session — the user re-authenticates with no error to explain why. Measured, see Testing.
Skip + report an unreadable partition Same harm, but where we cannot even name the right partition. Guessing the ancestor bit files the cookie under a partition the site never reads, which is indistinguishable from losing it — except it looks like a clean success.
Read partitionKey from JSON exports Chrome DevTools / Cookie-Editor exports carry partitionKey. The reader discarded it at parse time, so pasted exports lost CHIPS cookies the same silent way.
Derive the partition dir from getStoragePath() targetPartition arrives from IPC and was pasted into a filesystem path unsanitized, so persist:../.. resolved a Cookies DB outside Partitions/ and staged a replacement over it. It also drifts if Chromium changes how a partition name maps to a directory.
Hidden-window fallback on debugger attach CDP is now load-bearing for every write. Attaching to a live tab throws when DevTools already owns its debugger, so without this a user with DevTools open on that profile gets "import failed" instead of an import.

No max-lines disable was added. browser-cookie-import.test.ts crossed the cap, so the new cases were split into browser-cookie-import-partition-fidelity.test.ts instead of suppressing it.

Failure-mode table

Both write paths × cookie kind × outcome. Every cell either preserves the cookie or reports it. No cell silently downgrades or silently loses a cookie.

Path A — validated import (importValidatedCookies: file, paste, Safari, Firefox)

Sources feed this path with a partition read each: JSON partitionKey, Firefox moz_cookies.isPartitionedAttributeSet, and Safari (no partition field exists in its format).

Cookie Write succeeds Write rejected CDP unavailable
Ordinary Written unpartitioned via Network.setCookie. Nothing to lose. Run stops at the first rejection; every cookie this import wrote is removed and every replaced cookie is restored from its CDP identity; ok:false. Attach throws at the snapshot (or, on an empty jar, at the first write). Nothing was written and nothing was removed; ok:false. Jar untouched.
__Host- Written hostOnly at path /, which is what Chromium requires. Verified on real Electron. As above. As above.
Partitioned (CHIPS) partitionKey carried to Network.setCookie and stored. Verified on real Electron. As above. As above.
Partitioned, source partition unreadable Skipped, never written, and its domain is excluded from the replace scope so the existing session it never replaces is not erased. Counted in partitionSkippedCookies, logged by domain only, surfaced as a warning toast. n/a — no write is attempted. n/a.
Partitioned, unreadable, client too old to report it Import fails before the jar is touched — no clear, no removal, no write — with a reason telling the user to update Orca. Only reachable from a remote client older than this change. n/a. n/a.

CookieImportMode is replace-imported-domains at every call site, so a rejection always has the CDP restore behind it. Mutation set = restore set by construction: the removal plan and its identities are fixed together in replaceCookiesForImportedDomains (STA-4170's invariant), and this change does not re-read the jar anywhere.

Path B — native Chromium import (importCookiesFromBrowser)

Cookie Write succeeds Write rejected CDP unavailable
Ordinary Written unpartitioned via Network.setCookie. Counted in memoryFailed; the staged DB is registered so the cookie lands on the next cold start. If staging is unavailable, restart-fallback-unavailable warning. (Pre-existing behavior, unchanged.) Attach throws during the clear, before any write; ok:false and the staging file is discarded. On an empty jar the clear does not attach, so the first write throws instead — every cookie is then counted failed and the staged replay covers them.
__Host- Written hostOnly at path /. As above. As above.
Partitioned (CHIPS) partitionKey read from top_frame_site_key + has_cross_site_ancestor and stored. Verified on real Electron. As above. As above.
Partitioned, source schema cannot describe it (partition site present, no ancestor column) Skipped everywhere. Not written, and not staged — excluded from the staging DB, from domainSet, and from imported. Counted in partitionSkippedCookies. n/a. n/a.
Partitioned, unreadable, client too old to report it Import fails before the clear, staging discarded, jar untouched. Only reachable from a pre-change remote client. n/a. n/a.

Two cells deserve calling out as deliberate rather than incidental:

  • Absent partitionKey on a JSON cookie is read as unpartitioned, not as unreadable. Every mainstream exporter omits the field for ordinary cookies; treating absence as unreadable would reject whole exports. Absence is a faithful read.
  • A source schema with no top_frame_site_key column at all is read as unpartitioned. That schema predates cookie partitioning, so it genuinely has no partitioned rows.

Three defects the review loop found in this PR, and their fixes

All three were introduced by the skip logic in this change, and all three are recorded here rather than quietly amended, because each is the same shape as the bug this PR is meant to end.

  1. A skipped cookie erased the session it never replaced (validated path). replaceCookiesForImportedDomains received every importable domain, including domains whose only source cookie was skipped for an unreadable partition. So the import cleared the user's working cookies for that domain and then wrote nothing in their place — a strictly worse outcome than the downgrade this PR removes. Fixed by excluding unreadable-partition cookies from the replace scope. This is the mutation-set-wider-than-the-write-set failure STA-4170 was, in a new place.

  2. The staged cold-start replay re-introduced the downgrade (native path). The first draft folded skipped cookies into memoryFailed so the staging DB would carry them, on the reasoning that staging copies the source's own partition columns verbatim. That reasoning was wrong: when the source schema has no has_cross_site_ancestor column, buildChromiumCookieInsertParams fills the target's column with the target's default, which is a guessed ancestor bit — exactly the silent misfile the write path refuses to make, arriving by the back door one restart later. Fixed by excluding unreadable rows from staging entirely, so the cookie is skipped in every channel and reported once.

  3. An older remote client would have rendered a skip as a plain success (wire compatibility). partitionSkippedCookies is a new field on the import summary, and a client predating it ignores the field — so the host would skip cookies, the old client would show "Imported N cookies", and the loss would be silent again, over the wire this time. Remedied with capability negotiation: browser.profileImportFromBrowser takes an optional supportsPartitionSkippedCookies: true, current clients send it, and a host that would have to skip a cookie for a client that did not declare support fails the import before touching the jar — no clear, no removal, no write — with a reason telling the user to update Orca, rather than publishing a loss the client would render as success. The local Electron IPC path sends no flag and stays permissive, because main and renderer are always the same build. importCookiesFromFile has no remote RPC, so it carries no wire exposure.

Every fix is mutation-proved: reverting any one of them fails its test and only its test. I re-ran each mutation myself rather than taking the reviewer's word for it.

Firefox source-model correction from final review

Firefox records two independent facts:

  • originAttributes.partitionKey is dFPI / Total Cookie Protection storage isolation that Firefox imposed on an ordinary cookie. Its components can include port or ancestor context, so component count is not a CHIPS discriminator. Chromium re-derives its own third-party isolation after import; writing this cookie unpartitioned is faithful.
  • moz_cookies.isPartitionedAttributeSet records whether the server sent Partitioned. That is the real CHIPS signal. Firefox records no Chromium cross-site-ancestor bit, so this identity cannot be rebuilt and the cookie must be skipped and reported.

Final readiness caught that the earlier implementation inferred CHIPS from originAttributes component count. That could skip ordinary dFPI cookies and silently downgrade real Firefox CHIPS cookies. Fixed in adf4e62b32: the importer schema-probes and selects isPartitionedAttributeSet, ignores originAttributes shape for CHIPS classification, imports flag-zero dFPI rows, and skips flag-one CHIPS rows. The regression contains both row types. f2d8b46a08 also carries the old-client reporting capability into this Firefox path, so an older remote client fails before the target jar is read, cleared, or written.

Safari stands as originally argued. ITP is browser-imposed and is not recorded in Cookies.binarycookies at all, so there is no server-declared partition identity to drop and nothing to guess.

The one cell this change does not improve, stated plainly: importValidatedCookies still strips non-printable bytes from cookie values before writing. That is pre-existing, orthogonal to partition identity, and changing it risks turning a currently-imported cookie into a rejected one (STA-4240 territory). Left exactly as it was.

Linked Issue

Fixes STA-4300 — https://linear.app/stably/issue/STA-4300/p1-route-all-cookie-import-writes-through-cdp-identities-ends-the

Visual Proof

Before/after captured end to end on real Electron (macOS): #14729 (comment)

Driven through the real UI — Settings → Browser → Session & Cookies → Import Cookies → From File… — with a cookie JSON containing one ordinary cookie plus one CHIPS cookie whose partitionKey has topLevelSite but no hasCrossSiteAncestor.

  • BEFORE (main) — only the success toast: "Imported 2 cookies from file into Default." The partial-partition cookie is silently downgraded and lands in the jar unpartitioned. No warning of any kind.
  • AFTER (this branch) — the new warning toast renders alongside the success toast, and the jar contains only the readable cookie. importedCookies: 1, partitionSkippedCookies: 1.

Jar contents were verified on both instances, so the screenshots are backed by the actual cookie store, not just the toast text. The only automation seam was the native file-open dialog; no product code was modified to capture this.

Known cosmetic nit, deliberately left: the string reads "1 cookies" for a singular count. That matches the convention of every pre-existing toast in this module ("Imported {n} of {m} cookies", "None of the {n} cookies"), and fixing only this one string would make it the odd one out while touching four locale catalogs. Worth a separate sweep across the module's strings if wanted.

Testing

Desktop main-process change. Not mobile, not Windows/WSL, not SSH. Tested on macOS.

The defect was reproduced first, on real Electron, by a separate agent before any fix was written (3983fcd5d5, first commit on this branch). On main the import returns ok:true with importedCookies: 2 and no warning, while the partitioned cookie comes back through Network.getAllCookies with partitionKey: null.

Real-Electron regression tests (spawn the electron binary, write through the real import, read the jar back through CDP — session.cookies.get() strips partitionKey, so it cannot observe this either way and any test asserting through it would be vacuous):

  • browser-cookie-import-partition-success.electron.test.ts — native path, full import end to end, CHIPS partition intact.
  • browser-cookie-import-validated-partition.electron.test.ts — validated path, full import end to end: CHIPS and __Host- CHIPS both stored partitioned, ordinary cookie unchanged, unreadable partition skipped and counted.

Mutation-proved — each mutation was applied, the test run confirmed failing, then reverted:

Mutation Result
Drop partitionKey from the built identity partition-success.electron fails: expected null to deeply equal { … }
Restore the over-wide replace scope the skipped-domain replace test fails, and only that one
Let unreadable rows back into the staging DB the never-stages test fails, and only that one
Disable the client-capability guard the blocked-client assertions fail, and only that test
Stop the renderer sending supportsPartitionSkippedCookies the store's RPC-params assertion fails, and only that test
Infer Firefox CHIPS from originAttributes component count instead of isPartitionedAttributeSet the Firefox source-partition and fidelity tests fail
Make the Chromium source read always return unpartitioned partition-success.electron fails, same signature
Make the JSON partition read return unpartitioned validated-partition.electron fails
Downgrade a legacy partitioned row instead of skipping it Exactly 2 tests fail — the unit test and the integration test for that cell — and only those

Vacuous-test trap (this module has been bitten three times): a store mock missing writeCookieIdentity throws a TypeError the per-cookie catch swallows, routing every write down the rejected path while the suite still looks green. Guards against it here:

  • Every new test asserts the write was attempted — toHaveBeenCalledTimes(n) and the identity argument — not just the end state.
  • browser-cookie-import.test.ts and browser-cookie-import-partition-fidelity.test.ts install unreachableCookieSet, which throws if cookies.set is called for any user cookie. Only the __init probe (no user data) is allowed through. If the lossy write ever returns, those suites fail rather than pass quietly.
  • Skip paths assert the store was not called for the skipped cookie.

Also covered: the skip log line contains only the domain, never the cookie name or value.

Commands:

npx vitest run --config config/vitest.config.ts src/main/browser src/main/runtime/rpc/methods/browser.test src/renderer/src/store/slices/browser.test
#   -> 48 files, 734 tests
npx vitest run --config config/vitest.config.ts browser-cookie-import-toast
npx tsc --noEmit -p config/tsconfig.node.json
npx tsc --noEmit -p config/tsconfig.tc.web.json
npx oxlint && node config/scripts/check-max-lines-ratchet.mjs
npm run audit:code-quality:native && npm run audit:code-quality:type-aware
npm run verify:localization-catalog && npm run verify:localization-extraction && npm run verify:localization-coverage

All green.

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

Review

  • Security — strictly reduces attack surface: targetPartition no longer reaches a filesystem path from a caller-supplied string. Cookie values are never logged; the skip line carries only the domain.
  • Cross-platform — no platform-conditional code added. Path handling moved from string concatenation to Electron's own getStoragePath(), which is more correct on Windows, not less. The Electron fixtures use the existing xvfb-run wrapper on Linux.
  • Remote SSH / mobile — browser.profileImportFromBrowser gains one optional request field, supportsPartitionSkippedCookies: true. Additive and back-compatible per docs/reference/remote-wire-compatibility.md: an old host ignores an unknown key, an old client simply omits it, and no stream opcode was added. What the host publishes also changed — the summary carries a new optional counter — which is precisely why the host refuses to skip a cookie for a client that has not declared it can report one.
  • Backwards compatibility — partitionSkippedCookies is a new optional field on BrowserCookieImportSummary. Older renderers ignore it.
  • Performance — the validated path now opens the CDP store for every import that writes a cookie, where before it opened it only in replace mode. Since every call site uses replace mode, the only newly-affected case is an import into a jar with nothing to remove, which now attaches a debugger it previously skipped. One attach per import, and the native path already did this unconditionally.

Notes on adjacent tickets

  • STA-4183 (P3) is not subsumed — the ticket suggested it might be. It is about the clear path's rollback restoring a stale value for a cookie that arrived at the same coordinate mid-clear. That is a snapshot-timing problem, not an identity-fidelity one: the rollback was already CDP-backed after fix(browser): restore replaced cookies through CDP identities #14383, and nothing here changes when the snapshot is taken relative to the removal. It should stay open.
  • STA-4240 (P3) is out of scope as specified — one rejected write still aborts the whole validated import when cookies were replaced. That contract is preserved deliberately, because it is what makes the rollback correct.

Author

  • X / Twitter: @BrennanKB5

@coderabbitai

coderabbitai Bot commented Aug 15, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Cookie imports preserve readable Chromium, JSON, and Firefox partition identities. Unreadable partition metadata is skipped, counted, staged for replay when applicable, and reported in the import summary. Cookie writes use a shared CDP identity store with rollback support and failure handling. Chromium storage paths come from the target session. Unit and Electron tests cover partition parsing, CHIPS preservation, host-prefixed cookies, legacy schemas, and renderer warnings.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 36.67% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly and concisely describes the main change: routing all cookie-import writes through CDP identities.
Description check ✅ Passed The description covers the required change, rationale, issue, visual proof, testing, review considerations, and author details.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

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

❤️ Share

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (2)
src/main/browser/browser-cookie-import-validated-partition.electron.test.ts (1)

156-231: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Duplicated Electron fixture harness across both partition regression tests. Both files build a temp root, bundle browser-cookie-import.ts with Vite in cjs lib mode, strip ELECTRON_RUN_AS_NODE, select xvfb-run on Linux, spawn Electron, and read result.json with the same status assertions. The shared root cause is a missing helper module for that harness.

  • src/main/browser/browser-cookie-import-validated-partition.electron.test.ts#L156-L231: replace the inline harness with a shared helper that takes the exported symbol name, bundle file name, and fixture main source.
  • src/main/browser/browser-cookie-import-partition-success.electron.test.ts#L155-L223: call the same helper, and keep only the Chromium source-database setup local to this file.
src/renderer/src/lib/browser-cookie-import-toast.test.ts (1)

88-96: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Remove the duplicate negative test.

This test uses the same summary as does not infer a Google warning from generic skipped cookies on lines 98-107 and asserts the same warningToastMock expectation. The existing test already proves that a generic skippedCookies value emits no warning. Delete one of the two, or give this one a distinct input such as partitionSkippedCookies: 0.

♻️ Proposed change to make the new test distinct
-  it('does not infer a partition warning from generic skipped cookies', () => {
+  it('does not warn when the partition-skipped count is zero', () => {
     emitBrowserCookieImportToast(
-      { ...summary, importedCookies: 2, skippedCookies: 1 },
+      { ...summary, importedCookies: 2, skippedCookies: 1, partitionSkippedCookies: 0 },
       'Imported 2 cookies.',
       'Local Mac'
     )
 
     expect(warningToastMock).not.toHaveBeenCalled()
   })

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: f3c3b473-2e4a-4298-962d-dbcca5f6cf2e

📥 Commits

Reviewing files that changed from the base of the PR and between 5464525 and 3e742e3.

📒 Files selected for processing (19)
  • src/main/browser/browser-cookie-clear-store.test.ts
  • src/main/browser/browser-cookie-clear-store.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-fidelity.test.ts
  • src/main/browser/browser-cookie-import-partition-success.electron.test.ts
  • src/main/browser/browser-cookie-import-replacement.test.ts
  • src/main/browser/browser-cookie-import-test-database.ts
  • src/main/browser/browser-cookie-import-validated-partition.electron.test.ts
  • src/main/browser/browser-cookie-import-write.test.ts
  • src/main/browser/browser-cookie-import-write.ts
  • src/main/browser/browser-cookie-import.test.ts
  • src/main/browser/browser-cookie-import.ts
  • src/main/browser/browser-cookie-source-partition.test.ts
  • src/main/browser/browser-cookie-source-partition.ts
  • src/renderer/src/i18n/locales/en.json
  • src/renderer/src/lib/browser-cookie-import-toast.test.ts
  • src/renderer/src/lib/browser-cookie-import-toast.ts
  • src/shared/browser-workspace-types.ts

"restartFallbackUnavailablePartial": "Imported {{value0}} of {{value1}} cookies. The rest could not be loaded, and the restart fallback was unavailable. Try the import again.",
"googleCookiesSkipped": "Google cookies were not imported. Open a browser in Orca on {{value0}} with this profile, then sign into Google."
"googleCookiesSkipped": "Google cookies were not imported. Open a browser in Orca on {{value0}} with this profile, then sign into Google.",
"partitionSkipped": "{{value0}} cookies were not imported because their site-partition could not be read. Sign in to those sites again in Orca."

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.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🌐 Web query:

i18next 26 pluralization suffixes _one _other with count option

💡 Result:

In i18next v26, pluralization relies entirely on the Intl.PluralRules API [1][2]. This system uses CLDR (Common Locale Data Repository) plural categories as suffixes to determine which translation string to use based on the provided count [3]. When using the count option in your translation function, i18next automatically selects the appropriate key based on the plural rules of the current language [3]. Key aspects of pluralization in i18next v26: 1. The count option: You must pass the count variable to the translation function (e.g., i18next.t('key', { count: 1 })) [4][5]. The variable name must be exactly count [4][5]. If it is not provided, i18next cannot resolve the correct plural form and will not fall back to a base key [4][5]. 2. Plural suffixes: The _one and _other suffixes are standard for English and many other languages [4][3]. The _other suffix acts as the mandatory fallback; omitting it may result in the raw key name being returned [3]. 3. Additional categories: Depending on the language's specific grammar, you may also use other categories such as _zero, _two, _few, or _many [4][6][3]. 4. Intl.PluralRules requirement: As of v24 and continuing into v26, the Intl.PluralRules API is mandatory [4][7][1]. In environments where this API is not supported (such as older React Native environments using Hermes), you must install an Intl polyfill to ensure pluralization works correctly [4][7]. Without the polyfill, i18next will degrade and may only resolve basic English-style _one/_other forms [4][7]. Example structure: { "key_one": "item", "key_other": "items" } Usage: i18next.t('key', { count: 1 }); // Returns "item" i18next.t('key', { count: 5 }); // Returns "items"

Citations:


🏁 Script executed:

#!/bin/bash
set -eu

printf '%s\n' '--- relevant source and test references ---'
rg -n -C 5 'partitionSkipped|browser-cookie-import-toast|found_theme_(one|other)|RESERVED_PLACEHOLDER_NAMES|I18NEXT_OPTION_NAMES' \
  src/renderer/src config/scripts 2>/dev/null | head -n 240

printf '%s\n' '--- translation call sites ---'
rg -n -C 6 'partitionSkipped' src/renderer/src

Repository: stablyai/orca

Length of output: 22091


🏁 Script executed:

#!/bin/bash
set -eu

printf '%s\n' '--- toast test assertion ---'
sed -n '80,95p' src/renderer/src/lib/browser-cookie-import-toast.test.ts

printf '%s\n' '--- translation implementation and option handling ---'
rg -n -C 8 'function translate|const translate|export .*translate|I18NEXT_OPTION_NAMES|RESERVED_PLACEHOLDER_NAMES|count' \
  src/renderer/src/i18n config/scripts | head -n 320

printf '%s\n' '--- plural call patterns ---'
rg -n -C 5 'translate\([^,]+_(one|other)|\{ count:|count:' src/renderer/src config/scripts | head -n 260

Repository: stablyai/orca

Length of output: 50369


🏁 Script executed:

#!/bin/bash
set -eu

printf '%s\n' '--- localization placeholder contract ---'
rg -n -C 12 'RESERVED_PLACEHOLDER_NAMES|I18NEXT_OPTION_NAMES' config/scripts/localization-source-references.mjs

printf '%s\n' '--- explicit plural call-site patterns ---'
rg -n -C 8 "found_theme_one|found_theme_other|translate\(.*_one|translate\(.*_other" \
  src/renderer/src/components src/renderer/src/lib | head -n 180

printf '%s\n' '--- partitionSkipped across catalogs ---'
rg -n -C 2 '"partitionSkipped(_one|_other)?"' src/renderer/src/i18n/locales

Repository: stablyai/orca

Length of output: 364


🏁 Script executed:

#!/bin/bash
set -eu

printf '%s\n' '--- locate localization reference scripts ---'
fd -i 'localization-source-references' . || true
fd -i 'localization' config src/renderer/src/i18n 2>/dev/null | head -n 120

printf '%s\n' '--- candidate reserved-option declarations ---'
rg -n -C 10 'RESERVED_PLACEHOLDER_NAMES|I18NEXT_OPTION_NAMES|reserved.*placeholder|placeholder.*reserved' \
  . --glob '*.mjs' --glob '*.js' --glob '*.ts' --glob '*.tsx' | head -n 180

printf '%s\n' '--- explicit partition key and call-site context ---'
rg -n -C 8 'partitionSkipped|found_theme_one|found_theme_other' \
  src/renderer/src/i18n/locales src/renderer/src/lib src/renderer/src/components/settings/WarpThemeImportModal.tsx

Repository: stablyai/orca

Length of output: 21699


🏁 Script executed:

#!/bin/bash
set -eu

python3 - <<'PY'
import json
from pathlib import Path

catalog = json.loads(Path("src/renderer/src/i18n/locales/en.json").read_text())
toast = catalog["auto"]["lib"]["browser"]["cookie"]["import"]["toast"]
source = Path("src/renderer/src/lib/browser-cookie-import-toast.ts").read_text()
test = Path("src/renderer/src/lib/browser-cookie-import-toast.test.ts").read_text()
warp = Path("src/renderer/src/components/settings/WarpThemeImportModal.tsx").read_text()

assert "partitionSkipped" in toast
assert toast["partitionSkipped"] == (
    "{{value0}} cookies were not imported because their site-partition could not be read. "
    "Sign in to those sites again in Orca."
)
assert "'auto.lib.browser.cookie.import.toast.partitionSkipped'" in source
assert "{ value0: summary.partitionSkippedCookies }" in source
assert "'1 cookies were not imported" in test
assert "preview.themes.length === 1" in warp
assert "found_theme_one" in warp and "found_theme_other" in warp
assert "{ value0: preview.themes.length }" in warp

print("partitionSkipped uses one base key and value0 interpolation")
print("singleton test currently expects the ungrammatical plural message")
print("existing found_theme plural forms are selected explicitly by call-site branching")
PY

Repository: stablyai/orca

Length of output: 358


Fix the singular warning text. Use explicit singular/plural keys selected in browser-cookie-import-toast.ts, with value0 interpolation. Do not use count or i18next plural resolution. Update the toast assertion to expect “1 cookie was not imported…”.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Visual QA — warning toast (macOS, real Electron, playwright-cli + CDP)

Driven end to end in the running app: Settings → Browser → Session & Cookies → Import Cookies → From File… with a cookie JSON containing one ordinary cookie plus one CHIPS cookie whose partitionKey has topLevelSite but no hasCrossSiteAncestor (the unreadable-partition case). The only seam is the native macOS file-open dialog, which was stubbed in the main process via the V8 inspector to return the fixture path — everything below the dialog (JSON parse → validate → CDP Network.setCookie → summary → toast) ran unmodified.

Both toasts shown below with the sonner stack hover-expanded (the real UI behavior for revealing stacked toasts — the warning persists 12s, the success toast 4s).

BEFORE — main (5464525)

Only the success toast renders: "Imported 2 cookies from file into Default." The partial-partition cookie is silently downgraded to unpartitioned — partial-chips lands in the jar, no warning of any kind.

05-before-main-toast.png

AFTER — this branch (3e742e3)

The new warning toast appears alongside the success toast: "1 cookies were not imported because their site-partition could not be read. Sign in to those sites again in Orca." Summary: importedCookies: 1, partitionSkippedCookies: 1; the jar contains only plain-auth — partial-chips is skipped, never written.

07-after-expanded.png

Default (non-hovered) stacking state, showing both toasts present in the toaster:

06-after-final.png

Backing state (verified through the main-process inspector on the live instances)

  • Branch jar (persist:orca-browser): plain-auth present, partial-chips absent (total 1 cookie) — skipped, not downgraded.
  • Main jar: plain-auth and partial-chips both present (total 2 cookies) — the silent downgrade this PR fixes.
  • Renderer store after the branch import: { status: "success", summary: { totalCookies: 2, importedCookies: 1, skippedCookies: 1, partitionSkippedCookies: 1, domains: ["plain.example"] } }.

No defects observed. Minor note (matches the PR's specified string): "1 cookies" is not pluralized for singular counts — same convention as the pre-existing success toasts.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Independent verification of the review-loop fixes (090841558a)

I re-verified the two fixes rather than taking the reviewer's report at face value. Both findings are real and both were introduced by my skip logic:

Mutation applied Result
Restore the over-wide replace scope (importableCookies.map(...) with no filter) does not replace existing cookies for a domain whose only source cookie is skipped fails — and only that test
Remove the unreadable guard so those rows reach the staging DB again never stages a partitioned row whose ancestor bit is unreadable fails — and only that test

Both reverted; suite green.

The staging finding is the more important one. My original reasoning — "skip the in-memory write but let the staged cold-start replay carry it, since staging copies the source's own partition columns verbatim" — was wrong. When the source schema lacks has_cross_site_ancestor, buildChromiumCookieInsertParams fills the target's column with the target's default. That is a guessed ancestor bit: the same silent misfile the write path refuses to make, arriving one restart later through a channel I had argued was more faithful. The failure-mode table in the PR body has been corrected; it previously claimed the staged replay covered this cell.

I also proved the suite's structural guard is live rather than silently clean. unreachableCookieSet throws if cookies.set is called for any user cookie (only the __init probe is allowed). Injecting a single targetSession.cookies.set into the native write path fails 6 tests with Error: cookies.set was called for user cookie probe; removing it returns the suite to green. The guard is not a no-op.

Local gates after the merge: src/main/browser 45 files / 671 tests pass, both typechecks clean, oxlint clean, max-lines ratchet clean, no max-lines disable added.

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

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-import.ts (1)

1736-1752: 🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

Exclude unreadable partition cookies from the write set.

decryptedCookies is later passed to writeImportedCookies at Lines 1838-1852. The continue at Line 1752 runs after the cookie was pushed at Line 1736. The memory phase therefore still receives the unreadable cookie. This can cause a partitionless CDP write or classify the cookie as a memory-write failure instead of a partition skip.

Move decryptedCookies.push(...) below the unreadable-partition guard. The PR objective requires unreadable partition cookies to be skipped instead of written with downgraded identity.

Proposed fix
       const value = decryptedValue.toString('latin1')
 
-      decryptedCookies.push({
-        decryptedValue,
-        value,
-        domain,
-        name,
-        path,
-        secure,
-        httpOnly,
-        sameSite,
-        expirationDate: expiresUtc > 0 ? expiresUtc : undefined,
-        partition
-      })
-
       if (partition.status === 'unreadable') {
         partitionSkipped++
         skipped++
         continue
       }
 
+      decryptedCookies.push({
+        decryptedValue,
+        value,
+        domain,
+        name,
+        path,
+        secure,
+        httpOnly,
+        sameSite,
+        expirationDate: expiresUtc > 0 ? expiresUtc : undefined,
+        partition
+      })
+
       const cleanDomain = domain.startsWith('.') ? domain.slice(1) : domain

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 21733426-bf6a-4e2e-9c9e-35f9bcc6d9b3

📥 Commits

Reviewing files that changed from the base of the PR and between 0908415 and 1a5e2b9.

📒 Files selected for processing (7)
  • src/main/browser/browser-cookie-import-partition-fidelity.test.ts
  • src/main/browser/browser-cookie-import.ts
  • src/main/runtime/orca-runtime-browser.ts
  • src/main/runtime/rpc/methods/browser-schemas.ts
  • src/main/runtime/rpc/methods/browser.test.ts
  • src/renderer/src/store/slices/browser.test.ts
  • src/renderer/src/store/slices/browser.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/main/browser/browser-cookie-import-partition-fidelity.test.ts

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Review-loop verdict, stated honestly

The codex review loop is NOT a clean pass. Its final same-model round stalled waiting on its own subagents after surfacing the Firefox boundary, so no post-fix clean verification completed and I interrupted it rather than let it hang. Concerns it had not yet re-verified are unverified, not clean. I am recording that rather than implying a green review.

What the loop did deliver, all merged and each independently mutation-verified by me:

  1. 090841558a — over-wide replace scope, and unreadable rows reaching the staging DB
  2. 1a5e2b9c30 — the missing client-capability gate for the new summary field
  3. Its $ref-oss finding: no direct cookie-import implementation precedent exists, and CDP Network.getAllCookies / Network.setCookie is confirmed as the standard, non-hacky identity boundary on stock Electron. That is the approach this PR takes.
  4. Its verdict on the Firefox boundary — which refuted my reasoning, and is fixed in 584c180887.

On the Firefox boundary specifically

I asked the reviewer to challenge my claim rather than accept it, and it was right to. Firefox packs two different things into originAttributes: dFPI isolation the browser imposed (where my "faithful, not a downgrade" reasoning holds), and isPartitionedAttributeSet, which means the server sent Partitioned — a real CHIPS cookie we were importing unpartitioned. That is precisely the defect class this PR exists to end, sitting in a source I had argued past. Now skipped and reported, with the dFPI case importing exactly as before so no working cookie is dropped.

Safari stands as originally argued: ITP is browser-imposed and absent from Cookies.binarycookies, so there is no server-declared identity to lose.

What a human reviewer should still look at

Because the loop did not converge, these are the places I would spend review attention:

  • The Firefox partitionKey component-count heuristic in readFirefoxOriginAttributesPartition. It is deliberately conservative — 2 components means dFPI, more means the partitioned attribute — but it is a heuristic over a serialization format, and someone who knows Firefox's OriginAttributes suffix grammar first-hand should sanity-check it. Getting it wrong in the safe direction skips a cookie and reports it; getting it wrong in the unsafe direction is a silent downgrade, which is why it defaults to skipping whenever it cannot classify.
  • Whether failing the import outright is the right remedy for an old remote client, versus some softer signal.

Local gates on 584c180887: 48 files / 740 tests pass, both typechecks clean, oxlint clean, ratchet clean, type-aware audit clean, localization verifiers clean. No max-lines disable anywhere in this PR.

@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: 17329183-283d-4164-875c-483016a0d04e

📥 Commits

Reviewing files that changed from the base of the PR and between cd67136 and 584c180.

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

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Electron CDP visual proof (STA-4300)

Validated on an isolated dev instance of this worktree via Playwright CDP. No product code was edited and screenshots were not committed.

Identity (window.api.app.getIdentity()):

  • name: Orca: brennanb2025/sta-4300-cdp-cookie-writes
  • isDev: true
  • devBranch: brennanb2025/sta-4300-cdp-cookie-writes
  • devRepoRoot: /Users/brennanbenson/orca/workspaces/orca/sta-4300-cdp-cookie-writes
  • Isolated ORCA_DEV_USER_DATA_PATH, CDP 9334, renderer 5175

Live user path: Settings → Browser → Session & Cookies → Import Cookies → From Google Chrome → stably.ai.

Live import result: 942 source cookies, 871 imported, 71 skipped (googleCookiesSkipped: 71). partitionSkippedCookies was absent. Diag log: memory load: 800 OK, 71 failed, 0 partition-unreadable. Profile row updated to Google Chrome (stably.ai).

Console: 0 renderer errors. Unrelated warnings only (Radix tooltip control, React Grab outdated).

Isolated Browser settings (empty profile)

01-browser-settings-session-cookies.png

Import Cookies menu

02-import-cookies-dropdown.png

Chrome profile picker

03-chrome-profiles-submenu.png

After live Chrome import

04-after-chrome-import.png

Live summary toasts (same helper, re-fired after the 12s toasts expired)

Success + Google-skip copy from the live summary (partitionSkippedCookies still unset):

05-import-result-toasts.png

Partition-skip warning copy (helper demo)

This Chrome profile had 0 unreadable partitions, so the STA-4300 toast did not fire from the live import. The same emitBrowserCookieImportToast helper was then given partitionSkippedCookies: 2 to photograph the reporting copy:

06-partition-skipped-toast.png

Not verified: a live source cookie whose partition is unreadable; native From File… dialog; the remote-client fail-closed path for old clients that cannot report partition skips.

@brennanb2025
brennanb2025 merged commit bf6dc6f into main Aug 16, 2026
45 checks passed
@AmethystLiang

Copy link
Copy Markdown
Contributor

@brennanb2025 we reverted #14729 in #14942 because importing a Chromium profile can remove working site sessions for cookies the import then skips.

Please reland with a fix that never clears a destination session unless that cookie will actually be written or staged.

Reland ticket: https://linear.app/stably/issue/STA-4556/reland-14729-cookie-import-cdp-writes-after-revert-14942

AmethystLiang pushed a commit that referenced this pull request Aug 17, 2026
…(STA-4300) (#14729)

* test(browser): repro STA-4300 CHIPS partition downgrade on native cookie import success path

* fix(browser): route every cookie-import write through CDP identities (STA-4300)

* test(browser): cover partition fidelity on both import write paths (STA-4300)

* fix(browser): never stage unreadable cookie partitions (STA-4300)

* fix(browser): gate partition skips on client support (STA-4300)

* test(browser): anchor the client partition-skip capability assertion (STA-4300)

* fix(browser): skip Firefox CHIPS cookies whose Chromium identity cannot be rebuilt (STA-4300)

* fix(browser): tolerate a Firefox schema without originAttributes (STA-4300)

* docs(browser): correct a comment that still named the removed cookies.set write

* fix(browser): block lossy Firefox cookie import on old clients

* fix(browser): read Firefox CHIPS from schema flag
brennanb2025 added a commit that referenced this pull request Aug 17, 2026
…es, and never clear what it will not write back (#15030)

* reland(browser): restore CDP-identity cookie-import writes (#14729)

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.

* 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 #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.
paidaxingyo666 pushed a commit to paidaxingyo666/Manta that referenced this pull request Aug 21, 2026
…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.
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…(STA-4300) (stablyai#14729)

* test(browser): repro STA-4300 CHIPS partition downgrade on native cookie import success path

* fix(browser): route every cookie-import write through CDP identities (STA-4300)

* test(browser): cover partition fidelity on both import write paths (STA-4300)

* fix(browser): never stage unreadable cookie partitions (STA-4300)

* fix(browser): gate partition skips on client support (STA-4300)

* test(browser): anchor the client partition-skip capability assertion (STA-4300)

* fix(browser): skip Firefox CHIPS cookies whose Chromium identity cannot be rebuilt (STA-4300)

* fix(browser): tolerate a Firefox schema without originAttributes (STA-4300)

* docs(browser): correct a comment that still named the removed cookies.set write

* fix(browser): block lossy Firefox cookie import on old clients

* fix(browser): read Firefox CHIPS from schema flag
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…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.
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.

2 participants