Skip to content

fix(windows): stop string stdin throwing in the sync child-process chokepoint - #19304

Closed
brennanb2025 wants to merge 1 commit into
mainfrom
brennanb2025/sta6700-cookie-import
Closed

brennanb2025 wants to merge 1 commit into
mainfrom
brennanb2025/sta6700-cookie-import

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

Fixes STA-6700. Also unblocks STA-3706 — see below, because it is not the same cause.

The defect

src/shared/child-process/run-process.ts passes encoding: 'buffer' to spawnSync. That is documented and valid for spawnSync's output — but when input is a string, node does pipe.input = Buffer.from(input, options.encoding), and Buffer.from(str, 'buffer') throws ERR_UNKNOWN_ENCODING.

Reproduced directly (node v26.5.0, macOS — this is Node semantics, not Windows behaviour):

input encoding result
'hello' 'buffer' throws ERR_UNKNOWN_ENCODING: Unknown encoding: buffer
Buffer 'buffer' ok
'hello' omitted ok
none 'buffer' ok

So runProcessSync throws for any caller passing a string input — and ProcessSpec.input is typed input?: string, so the API actively invites the broken usage.

Blast radius is one call site today. Across src/, config/, tests/ and scripts/ — including the untyped .mjs callers — src/main/browser/browser-cookie-key.ts:150 is the only caller that passes input — the PowerShell DPAPI master-key decrypt. The throw is caught, logged, and returned as null, which the Chromium prepare step renders as "Could not access Brave encryption key. The OS may have denied access."

That message is wrong, and that is the real user cost. The OS denied nothing. Windows users see a permissions error for what is a string-encoding bug, and every Chromium cookie import aborts before it starts.

Introduced by b7e79b7ca6 (#15746, "one chokepoint for every child process"). run-process.test.ts had three runProcessSync tests and none passed input, so the consolidation shipped a regression through the exact path it was consolidating.

The fix — at the chokepoint, not the call site

input: spec.input === undefined ? undefined : Buffer.from(spec.input, 'utf8'),

encoding: 'buffer' stays, and the reason is symmetry rather than necessity: runProcess (the async path) already writes stdin via child.stdin?.end(spec.input), which defaults to utf8. Converting here makes the sync path match the async one instead of quietly diverging from it — that, not the stdout shape, is the argument for 'utf8'.

Dropping encoding: 'buffer' would also have worked; the Buffer-returning default is documented in the overload set (SpawnSyncOptionsWithBufferEncoding). Keeping it simply leaves 'buffer' meaning one thing. The code comment names the surprise that caused this — that encoding governs stdin decoding and stdout shape.

browser-cookie-key.ts is untouched.

The missing test is the headline

  • writes string input to the child stdin — writes string stdin to a child and asserts it arrived. Uses process.execPath, so it runs on every OS: this would have caught fix(windows): one chokepoint for every child process #15746 in CI on Linux, with no Windows host needed.
  • encodes non-ASCII stdin as utf8 — asserts the child receives 6 bytes for héllo, pinning the encoding choice (latin1 would report 5).

One edge checked by measurement rather than reasoning: converting to a Buffer flips the truthiness of an empty-string input, since node gates on if (options.input) and a zero-length Buffer is truthy. All three cases — empty string, empty Buffer, undefined — produce eof:0 and status 0, so they are observationally identical and no special case was added. No caller passes '' today regardless.

Evidence

stage result
Red, at unmodified a87a19c996 2 failed / 16 passed, TypeError: Unknown encoding: buffer
Green, after fix 18 / 18
Ablation (input: spec.input restored on the committed fix) exactly 2 failed / 16 passed, same production error
Restored, re-verified 18 / 18

The ablation threw at runtime rather than at import, so it exercised the code rather than failing to compile. Both new tests are discriminating — only they flip, and only on this line.

Wider sweep across src/shared/child-process and src/main/browser: 189 files, 1,785 passed, 0 failed, 48 skipped. Typecheck clean on all three projects (node, web, cli).

Why this closes STA-3706 too — and why that is not a grouping

These are two sequential stages, not one cause. The timeline settles it: STA-3706 was filed 2026-08-08 at v1.4.176-rc.1, before this regression; STA-6700 is v1.4.197, after. They were never observed together because 6700 now aborts the import one stage earlier than 3706 ever ran.

STA-3706's fix is already on main — isAppBoundEncryptedCookie, the v20 classification before decrypt, and the "app-bound encryption / import from a file instead" toast, with 28 green tests. None of it is touched here.

So fixing 6700 unmasks 3706's landed fix: Chrome/Edge 140+ Windows users go from a false "key access denied" error to the correct actionable app-bound toast, and Brave (still v10) gets a real import.

Boundary, stated not buried

The mechanism is Node semantics and is reproduced above on macOS. The end-to-end Windows cookie import is unproven — that needs a Windows host with a real Chrome profile. No real browser profile was read at any point; the fixtures are piped-payload and héllo, and the change contains no cookie values, host keys or decryption keys.

…okepoint

`runProcessSync` passed `encoding: 'buffer'` to `spawnSync`. That is valid for
the output shape the reads below depend on, but `encoding` also decodes a
string `input`, and `Buffer.from(str, 'buffer')` throws ERR_UNKNOWN_ENCODING
before the child starts. Encode the input to bytes instead.

The only caller in the tree that passes `input` is the Windows DPAPI master-key
decrypt, so every Chromium cookie import on Windows aborted and rendered the
caught throw as "The OS may have denied access" -- an error the OS never
raised.

The sync path had three tests and none passed `input`, which is how #15746
shipped a regression through the very chokepoint it was consolidating.
@coderabbitai

coderabbitai Bot commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: 32684724-c9f1-47aa-9b90-3871eb911ecb

📥 Commits

Reviewing files that changed from the base of the PR and between a87a19c and 14f62bf.

📒 Files selected for processing (2)
  • src/shared/child-process/run-process.test.ts
  • src/shared/child-process/run-process.ts

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


📝 Walkthrough

Walkthrough

runProcessSync now encodes defined string input as UTF-8 before passing it to spawnSync. New tests verify echoed input and the six-byte UTF-8 encoding of héllo.

Merge Risk: ⚪ Minimal · up to 14f62

String stdin is now reliably passed as UTF-8 bytes to synchronous child processes, preventing the Windows cookie-import failure while preserving buffer-based output handling. The covered change is ready to merge.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 1 functions across 2 files.
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 Windows-related sync child-process stdin failure and the fix. It is concise and relevant to the primary change.
Description check ✅ Passed The description gives a detailed explanation of the defect, root cause, fix, tests, scope, linked issues, and Windows verification boundary. It does not follow the template headings and omits the requ…
✨ Finishing Touches
📝 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.

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

✅ No new issues found.

Reviewed changes

Reviewed the single-commit fix for the sync child-process chokepoint, plus its two new tests.

  • Encode string input to a Buffer at the chokepoint — runProcessSync now passes Buffer.from(spec.input, 'utf8') instead of the raw string, so encoding: 'buffer' only governs the stdout/stderr Buffer shape the .toString('utf8') reads rely on, and no longer trips ERR_UNKNOWN_ENCODING on string stdin.
  • Two discriminating tests — one round-trips piped-payload through stdin via process.execPath (cross-OS), one pins the utf8 choice by asserting héllo arrives as 6 bytes.

I reproduced the underlying Node semantics directly (spawnSync with { input: 'hello', encoding: 'buffer' } throws Unknown encoding: buffer), so the mechanism is confirmed and the fix is correct and minimal. The change only alters behavior when input is a string — previously an unconditional throw, now correct utf8 delivery — so the ~19 callers that omit input (undefined) see no change. The async runProcess path already writes string input via child.stdin.end(spec.input) under utf8, so the two paths now agree on utf8.

ℹ️ Nitpicks

  • The comments in run-process.ts and run-process.test.ts say encoding "decodes" string stdin (and "decodes a string input"). That option actually encodes the input string and decodes the output; a one-word swap if you touch either comment again is all that's needed.

Pullfrog  | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Status: reviewed CLEAN · manual validation platform-gated

Independent review — CLEAN

A wholly fresh reviewer (same model, no involvement in authoring) re-ran the load-bearing claims rather than accepting them. It reproduced the four-row spawnSync matrix, the red-then-green, and the 189-file / 1,785-test sweep to the digit, and went past the PR in four places:

  • Ran an ablation this PR did not. Flipping 'utf8' → 'latin1' fails exactly 1 test, which establishes that the two new tests are independently discriminating rather than one exercising the other's setup.
  • Extended the empty-string edge from 3 cases to 9, crossing undefined / Buffer.alloc(0) against stdio pipe, ignore and inherit — inherit because cli-launch-redirect.ts:63 is a real sync caller using it. Every pair is byte-identical, so the if (options.input) truthiness flip changes nothing observable. No special case needed.
  • Tried to falsify the regression attribution rather than confirm it, suspecting a later commit had made the latent bug reachable. It had not: git log -S "encoding: 'buffer'" shows the line is unique to b7e79b7ca6, and the DPAPI call site already passed input in that same commit. fix(windows): one chokepoint for every child process #15746 is the correct attribution.
  • Confirmed the blast radius is tighter than stated: browser-cookie-key.ts:150 is the only input-passing caller in the whole repo, including the untyped .mjs callers.

It also read node's spawnSync source at runtime to confirm the failing branch carries no process.platform check — which is what makes the "would have caught #15746 on Linux CI" claim true rather than hopeful, since the new tests use process.execPath, carry no skipIf, and match the default test glob.

Two review findings, both acted on

The reviewer caught an error in this PR's own description: it claimed the Buffer-returning stdout default was "undocumented". It is documented, in @types/node's SpawnSyncOptionsWithBufferEncoding overload. The decision to keep encoding: 'buffer' is still correct, but the stated reason was wrong, and the body has been corrected — it now gives the better argument the reviewer supplied: converting here makes the sync path match the async path, which already defaults to utf8 via child.stdin?.end(). The runProcessSync call count was also overstated and is now removed in favour of the claim that actually carries the argument.

One nit was assessed and deliberately not acted on: spec.input === undefined narrows a previously-tolerated input: null, which now throws where it once no-opped. It is unreachable — ProcessSpec.input is string | undefined and no caller passes null — and closing it would cost a force-push plus a fresh look at a chokepoint twelve production sites depend on, to buy nothing reachable. Worth taking if the file is open for another reason.

Manual validation: mechanism proven here, end-to-end is Windows-gated

Stated plainly rather than implied:

  • Proven on this machine: the spawnSync failure and its fix, the child actually receiving string stdin, the utf8 byte count, and the ablations. This is Node-level behaviour with no platform branch, so it is genuinely validated, not merely inferred.
  • Not proven: that a real Windows Chromium cookie import now succeeds end to end. That needs a Windows host with a real Chrome/Edge/Brave profile, and no such run was performed. No real browser profile was read at any point; the fixtures are piped-payload and héllo, and the change contains no cookie values, host keys or decryption keys.

The causal chain to the user-visible message was confirmed by reading: the throw is caught at browser-cookie-key.ts:117, returns null, and browser-cookie-chromium-prepare.ts:245 renders that as "The OS may have denied access" after the staging DB is discarded — so the import aborts before any cookie is read, and the permissions message is misleading.

Gates

Typecheck clean across all three projects (node, web, cli). oxfmt --check, oxlint, and the max-lines ratchet clean — the +4 lines are comments, so the effective count is unchanged. Root lockfile byte-identical to origin/main.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Windows validation: PASS on the real machine, with an honest caveat on browser coverage

Run on a real Windows host with $electron over CDP against isolated dev profiles. The end-to-end gap this PR previously carried is now closed for the mechanism — but not against a real browser's cookie store, and that distinction is stated rather than glossed.

What could not be tested, and why

On that machine the only Chromium browser Orca detects is Microsoft Edge. Chrome is not installed (only "Chrome for Testing", under a root Orca does not scan) and Brave is not installed at all.

Edge is installed, but it was running, and the import aborts before it ever reaches the DPAPI path:

"Could not copy Microsoft Edge cookies database. Try closing Microsoft Edge first."

That is a snapshot/copy failure at browser-cookie-chromium-prepare.ts:119, before getEncryptionKey is called — unrelated to this PR and unaffected by it. Closing the browser would have unblocked it; that was declined, since it is a live session on someone's primary machine.

Two independent proofs on the real Windows host

1. Direct probe of the chokepoint, using the app's own PowerShell DPAPI script and the same spawnSync option shape, touching no browser profile (Node v24.18.0):

pre-fix  (input is a string):  ERR_UNKNOWN_ENCODING — "Unknown encoding: buffer"
post-fix (input is a Buffer):  threw null, status 0, stdoutBytes 330

Note it throws synchronously out of spawnSync, so it propagates past runProcessSync into getWindowsEncryptionKey's outer catch, which returns null — which is precisely how a string-encoding bug becomes a permissions message.

2. Full UI before/after through Settings → Browser → Session & Cookies → Import Cookies, against synthetic Chromium profiles built for this test: a real CurrentUser DPAPI-wrapped master key, with cookies generated for the run on .example.com / .example.org / .example.net. No real profile was read, copied or opened.

BEFORE (fix ablated) AFTER (14f62bf733)
Brave (all v10) "Could not access Brave encryption key. The OS may have denied access." "Imported 6 cookies from Brave into Default." — importedCookies: 6, skippedCookies: 0
Chrome (all v20) "Could not access Google Chrome encryption key. The OS may have denied access." "Orca cannot decrypt 4 of this browser's cookies because they use app-bound encryption. You can import cookies from a file using 'From File…'." — warning.reason: "app-bound-encryption"

Both after-states are exactly what the fix predicts: the misleading permissions error is gone, v10 cookies import for real, and v20 cookies produce the correct actionable app-bound message rather than a false permissions failure. That second row is also the first live confirmation that fixing this unmasks STA-3706's already-landed app-bound handling.

The build state was verified in the running bundle rather than assumed. Before: spawnSync(...{...t.options,input:e.input,...,encoding: + backtick-buffer. After: input:e.input===void 0?void 0:Buffer.from(e.input, + backtick-utf8. (The bundler emits template literals, so a double-quote grep finds nothing — worth knowing for anyone else verifying a packaged build.)

Evidence handling

Four screenshots were captured and transferred back as numbered base64 with sha256 verification end to end. All four were opened and inspected before being reported: they show an empty isolated dev profile with no projects or workspaces, the Browser settings pane, and the resulting toast. No cookie values, host keys, decryption keys, tokens, private repository names, or unrelated workspace content appear in any of them.

What remains unproven

A real Chrome, Edge or Brave profile on a real user's machine was not imported. The synthetic profiles exercise the genuine DPAPI unwrap path and the genuine v10/v20 classification, so the mechanism is proven on Windows — but the last mile, against a browser store Orca did not create, is still untested. Anyone with Chrome or Brave installed and closed can close that gap in about a minute.

@nwparker

Copy link
Copy Markdown
Contributor

Closing as superseded by merged #28225 (3308eb3d00aaf9219ab88609ee24d4150765a94a). Thank you for identifying and testing the synchronous string-stdin encoding failure.

I compared this PR’s complete diff with the current runner: encoding: null now fixes the same failure at its shared source. The merged regression cases exercise string input, Unicode bytes, stdout/stderr decoding and binary capture, covering the regression this PR tests. The current runner and byte-capture suites also pass in this audit. The implementation now lives in src/packages/process-host; no independent production or regression scope remains here.

#18670 is closed with that fix linked. App-bound cookie encryption remains a separate concern in #13192.

@nwparker nwparker closed this Oct 18, 2026
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