Repository navigation
fix(windows): copy the daemon host exe verbatim instead of renaming it (MDE T1036) - #17865
Conversation
Six Microsoft Defender for Endpoint incidents fired against Orca 1.4.192 in eight days on one enterprise Windows 11 / Intune tenant. All six were behavioural process-tree scoring, not signature hits; two escalated to multi-stage incidents mapped to ATT&CK Execution and Collection. Add a reference doc mapping each attack-technique-shaped behaviour to the code that produces it and to why it exists: the renamed daemon image (T1036), the per-process PEB read, encoded policy-bypassed PowerShell (T1049), caret-escaped cmd.exe lines, and computer-use screen capture plus runtime-compiled MSIL (T1113). Records that signing is not the gate -- reputation is signer plus hash-keyed prevalence -- and carries the two evidence gaps the report noted. Adds an engineer checklist, deployment guidance for admins (AV path exclusions do not suppress EDR behavioural alerts; an MDE alert suppression rule does), and an explicit pre-deployment warning about computer use.
Review corrections to the EDR posture doc. The "encoded, policy-bypassing PowerShell" list conflated three different shapes and was incomplete. Split it into the three tiers an EDR actually scores differently -- bypass plus encoding, encoding alone, and bypass alone -- and add the sites it missed, including windows-mobile-firewall.ts, which encodes a script and launches it elevated through Start-Process -Verb RunAs. system-fonts.ts (-Command) and desktop-script-provider-bridge.ts (-File) were listed as encoded and are not. Notes that a raw grep under-reports, because the hook sites reach -EncodedCommand through wrapWindowsPowerShellEncodedCommand. Attribute the in-payload Set-ExecutionPolicy move to #16576 rather than to #16003's measurement, which keyed on -WindowStyle Hidden + -EncodedCommand, and record that the launcher's own tradeoff is unverified on a real box. Admin guidance was missing two ways a suppression rule pinned to one full path misses real activity: the .staging-<hex> sibling that exists mid-update, which is when the update-cluster incidents fire, and the userData fallback when LOCALAPPDATA is unset. Also: state the measurement conditions on the process-table timings, note that Hermes has surface even though we have no telemetry for it, note that the uninstaller names are electron-builder-generated and in no repo file, drop a volatile line count, and mark the per-operation computer-use shape as being addressed by an unmerged change. Drops the duplicated AGENTS.md section, keeping the indexed bullet.
There was a problem hiding this comment.
Important
No code defects found — the name derivation, NSIS macro, docs, and tests all check out — but this PR changes terminal-survival behavior on Windows and its only real proof has not run on this branch yet. Hold merge until the packaged survival E2E passes (details below).
Reviewed changes
- Daemon host exe copied verbatim —
DAEMON_HOST_EXE_NAMEis replaced bydaemonHostExeName(execPath)(winPath.basename), so the relocated image is a byte-for-byte, name-included copy of the signed app exe. Survival is a property of the path, not the name. - NSIS uninstall macro — now kills the app's own image name (which reaches the relocated daemon) plus the legacy
orca-terminal-daemon.exe, with balancedPush $0/Pop $0stack discipline. - Docs — new
docs/reference/windows-daemon-host-relocation.mdallowlisted in.gitignoreand linked fromAGENTS.md. - Tests — existing assertions updated to
Orca.exe; two new tests pin the verbatim-copy (same name, same bytes) and dev-channel-rename invariants.
⚠️ Survival proof is still outstanding
I verified the load-bearing claims against the pinned [email protected]: allowOnlyOneInstallerInstance.nsh does have the path-scoped PowerShell primary branch and the taskkill /IM fallback, and ${APP_EXECUTABLE_FILENAME} is defined as "${PRODUCT_FILENAME}.exe". I also confirmed nothing in src/ identifies the daemon by image name (identity is PID + command line, daemon-entry.js), and the new tests would fail if the rename were reintroduced. What remains unproven is the runtime behavior itself — none of the four workflow_dispatch harnesses has a passing run on this branch yet, and a mistake in the name derivation would only surface as terminals dying across an update.
Technical details
# Merge gate: packaged survival E2E
## Required outcome
- `win-update-survival-e2e.yml` with `expect: survival` — the primary proof; this is the one that catches a mistake in the naming change.
- `win-crash-survival-e2e.yml` with `expect: survival` — daemon survives a main-process crash.
- `windows-terminal-restart-e2e.yml` — terminal restart behavior.
- `win-update-e2e.yml` — old-name daemon and new-name daemon coexist across the version boundary.
- Manual uninstall smoke test: install → open a terminal → uninstall → no surviving daemon and no `%LOCALAPPDATA%\Orca\daemon-host` tree (the NSIS edit is exercised only by a real uninstall; no workflow covers it).
## Why this blocks
The fallback-branch trade (cold-restore on no-PowerShell hosts) is deliberate and documented, and the primary branch is provably unaffected. But the unit tests can only pin the copy-plan invariants, not survival — so the packaged harnesses are the only evidence that the change actually preserves live terminals.DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
0bbaa34 to
fb3d93e
Compare
fb3d93e to
642de5e
Compare
There was a problem hiding this comment.
Important
The two follow-up commits are clean — I found no new code defects in the user-scoped uninstall kill or the doc corrections. The standing merge gate is unchanged: none of the four packaged survival E2E harnesses has a passing run on this branch yet, so this should still not merge until win-update-survival-e2e with expect: survival and the manual uninstall smoke test pass.
Reviewed changes
- Scoped the uninstall
taskkillto the current user —ReadEnvStr USERNAMEnow feeds a/FI "USERNAME eq $1"filter on both kills, replacing the intermediatecmd.exe /cexpansion. An emptyUSERNAMEfalls back to an unfiltered kill, and the stack stays balanced (three pushes, twonsExecpops, three restores). - Corrected the relocation doc — the fallback-branch table now matches
IS_POWERSHELL_AVAILABLEexactly (process-scopeGet-ExecutionPolicy,Get-CimInstanceresolution), and the GPO/effective-policy gap, the empty-OriginalFilenamecalibration, and thecustomCheckAppRunningrejection rationale are all stated accurately. - Reconciled
windows-edr-posture.md— the rename is now documented as historical and the remediation-table row points at the relocation doc instead of reading as outstanding work.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
…tion Three claims in this doc became false once the rest of the Windows EDR set landed, and two told engineers the opposite of what the release does. The process-table section still described one shared snapshot taken with `Memory | CommandLine | CreationTime`, argued that splitting the cache per field set "would restore exactly the fan-out it exists to prevent", and concluded the shape was unfixable because "the information is only in the PEB". The split shipped (identity opens no handle at all), `Memory` is retired, and the command line now comes from the kernel through `ProcessCommandLineInformation` -- `ReadProcessMemory` is absent from the compiled addon and a ratchet asserts it against the import table. An engineer reading the old text would have concluded both fixes were dead ends. The PowerShell site inventories were stale in three of four lists: the port scan went native, every `-ExecutionPolicy Bypass` + `-EncodedCommand` pair was dropped as a measured no-op, and of the unencoded-bypass list only `wsl-cli-scripts.ts` survives. Regenerated against the merged tree, including the sites that reach the flag through `wrapWindowsPowerShellEncodedCommand` and never spell it, which a raw `rg` misses. Incident-evidence sections are left alone: they record what the tenant observed on 1.4.192, not what the code does now.
Microsoft Defender for Endpoint flagged `orca-terminal-daemon.exe` as MITRE T1036 (Masquerading): Orca copied its own `Orca.exe` into %LOCALAPPDATA% under a different name, specifically so the NSIS updater's `taskkill /IM Orca.exe` could not match, then ran it detached. Because that process is what every other flagged action was attributed to, the name mismatch acted as a reputation multiplier on unrelated findings. The rename was never what made the daemon survive. In app-builder-lib 26.15.3 the installer's FIND_PROCESS/KILL_PROCESS select processes whose image path is under $INSTDIR; `taskkill /IM` is only the fallback for hosts where PowerShell is missing or blocked. Survival is a property of the path, and %LOCALAPPDATA%\Orca\daemon-host is outside $INSTDIR whatever the file is called. Derive the host exe name from process.execPath so the copy is byte-for-byte, name included — it keeps its Authenticode signature and carries no renamed-image signal. On the no-PowerShell fallback the daemon is now killed with the app and terminals cold-restore, which is the documented pre-relocation outcome the update harness already asserts, not a regression. The uninstall macro no longer needs a distinct name to find the daemon; it kills the app's own image name (plus the legacy name, for hosts left by older builds). Adds docs/reference/windows-daemon-host-relocation.md with the survival contract, the rejected alternatives and their measured costs, and the invariants to keep.
Scope the uninstall taskkill to the current user with `/FI "USERNAME eq %USERNAME%"` via cmd.exe, matching upstream's per-user KILL_PROCESS — without it an elevated machine-wide uninstall reaches another logged-on user's session, so the "no collateral" claim in the comment was overstated. Comment the rmSync-before-publish: Windows refuses to delete a running image, so a live daemon already hosted in this version's dir (same-version reinstall, or a dev channel reusing a version) throws and materialization fails open. Doc corrections: - The fallback selector is the full per-user `taskkill /F /IM "<app>.exe" /FI "PID ne $pid" /FI "USERNAME eq %USERNAME%"`, not a bare `taskkill /IM`. - The probe reads `Get-ExecutionPolicy -Scope Process`, not the effective policy, and GPO writes MachinePolicy/UserPolicy — so GPO-managed hosts take the primary path-scoped branch. Narrow the fallback triggers accordingly. - Drop the Authenticode sentence: the old name was equally byte-identical and equally signed, so a filename has no bearing on signature validity. - Name the new update-abort path: the daemon now matches FIND_PROCESS, so on the fallback branch an unkillable host reaches the retry loop's MessageBox /SD IDCANCEL and Quits, aborting a silent update. - Correct the customCheckAppRunning rejection. It is ~6 lines, not a rewrite; it is wrong because forcing the PowerShell branch where PowerShell is absent makes FIND/KILL silently no-op and leaves the real app running with files in use. - Bound the win honestly: OriginalFilename is empty on the shipped binary, so the strongest T1036 indicator never fired, and the residual copy-and-run-detached shape still maps to T1036.005. Reconcile docs/reference/windows-edr-posture.md, which documents the rename as a live finding and would otherwise contradict this change. Content-only edit: markdown under docs/reference/ is not oxfmt-formatted as a matter of practice and nothing in CI gates it, so the file is left consistent with its neighbours.
The uninstall macro routed both taskkills through `"$SYSDIR\cmd.exe" /C` purely
so `%USERNAME%` would expand — two extra interpreter spawns on the uninstall
path, in a change whose whole point is not adding scored behaviour, and the
exact `cmd.exe /c` shape the new AGENTS.md EDR bullet warns about. NSIS reads
the variable itself with ReadEnvStr, so the spawns buy nothing.
Verified on Windows 11 that the generated command line does what the filter is
there for: a copy of cmd.exe running as orca-nonexistent-probe.exe (pid 34244)
was terminated by `taskkill /F /IM "orca-nonexistent-probe.exe" /FI "USERNAME eq
<user>"` — SUCCESS, exit 0, process gone.
Guarded on an empty USERNAME because the degenerate case is silent: taskkill
rejects an empty filter value outright ("The search filter cannot be
recognized") and kills nothing, which would leave exactly the orphaned daemon
this macro exists to reap. `*` is rejected as a filter value too, so there is no
branchless spelling. With no USERNAME to scope by it kills unfiltered, as the
macro did before the filter was added. Stack stays balanced: three pushes, two
nsExec pops, three restores.
Also strike the last stale row in windows-edr-posture.md's remediation table.
"Copying our own image under a different name" read as outstanding work; it is
done by this change, so the row now points at the relocation doc. Same class of
staleness as the section reconciled in the previous commit, and git would not
have flagged it either.
281038f to
1e126f8
Compare
…n-host-materialization Conflicts, and how each was resolved: - config/nsis/daemon-host-uninstall.nsh: main deleted it (#17906 consolidated every NSIS hook into config/nsis/orca-installer-hooks.nsh, because electron-builder accepts exactly one `nsis.include`). Took the deletion; the rewritten uninstall macro is ported into the hooks file in the next commit. Doc references repointed at the surviving file. - docs/reference/windows-edr-posture.md: add/add. This branch's base (#17856) squash-landed on main, and #18151 then corrected several process-table claims there. Took main's corrected text and re-applied only this branch's daemon-host edits (the rename removal, T1036.005, the spawn-tree line, the checklist row). - .gitignore, AGENTS.md: kept both sides' added lines.
… include The uninstall macro this branch rewrote lived in config/nsis/daemon-host-uninstall.nsh, which main no longer includes: #17906 consolidated every Windows installer hook into config/nsis/orca-installer-hooks.nsh because electron-builder accepts exactly one `nsis.include`. Merged as-is, the rewritten macro would have been dead code while the shipped uninstaller kept running main's stale sweep — `taskkill /F /IM orca-terminal-daemon.exe`, which matches nothing now that the relocated host is a verbatim Orca.exe copy. The RMDir that follows then cannot delete the running image, so a live orphaned daemon and its ~224 MB tree would survive every uninstall. Ported into the live include: the ${APP_EXECUTABLE_FILENAME} kill, the USERNAME filter that keeps an elevated machine-wide uninstall out of another logged-on user's session, and the register save/restore around both. The legacy orca-terminal-daemon.exe kill stays so hosts left by older builds are still reaped. The ratchet that was meant to catch exactly this pinned only the legacy image name, which main's stale macro already satisfied, so it passed both ways. It now asserts the app-exe kill and the USERNAME filter, against comment-stripped script — the prose above the macro names both image names, so a toContain over the raw file proves nothing.
📝 WalkthroughWalkthroughThe daemon host relocation now copies the application executable verbatim and resolves the relocated path from its source basename. Tests cover byte identity, alternate executable names, and idempotent materialization. Genuine uninstall now terminates both the application executable and the legacy daemon name, with per-user filtering when available. Windows reference, EDR, contributor, and crash-survival documentation was updated. Merge Risk: 🔵 Low · up to The relocated daemon now keeps the application executable name, but its idempotence coverage does not verify that existing destination contents survive a second materialization. This is a bounded regression-risk gap that should be addressed before relying on the test. 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
Full details: Description checkExplanation The description provides detailed change rationale, risks, testing results, and required manual E2E steps, but it does not follow the repository template. It omits the required Linked Issue, Visual Proof or an explicit N/A explanation, checklist sections, Agent skill upstream boundary, and other required headings. Resolution Restructure the description using the repository template. Add a linked issue in the
✨ Finishing Touches📝 Generate docstrings
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Team
Run ID: 0005eef8-43de-432c-b632-aba5bd29bc7d
📒 Files selected for processing (11)
.gitignoreAGENTS.mdconfig/nsis/orca-installer-hooks.nshconfig/scripts/electron-builder-markdown-associations.test.mjsdocs/reference/windows-daemon-host-relocation.mddocs/reference/windows-edr-posture.mdsrc/main/daemon/daemon-host-relocation.test.tssrc/main/daemon/daemon-host-relocation.tstests/tools/win-crash-survival-e2e/README.mdtests/tools/win-crash-survival-e2e/crash-step.mjstests/tools/win-crash-survival-e2e/run.mjs
Included review availability: Your plan provides up to 10 included reviews per hour; 0 remain after this review.
| // A recopy would rm the dest; a sentinel inside it must survive the 2nd call. | ||
| const sentinel = join(dest, 'sentinel.txt') | ||
| writeFileSync(sentinel, 'keep') | ||
| const result = materializeRelocatedDaemonHost() |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Assert that the sentinel survives the second materialization.
Line 234 can rematerialize the destination and still return Orca.exe. The test then passes even if the second call deletes sentinel.txt. Add an assertion for the sentinel after this call.
Proposed fix
const result = materializeRelocatedDaemonHost()
+ expect(existsSync(sentinel)).toBe(true)
expect(result?.execPath).toBe(join(dest, 'Orca.exe'))📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| const result = materializeRelocatedDaemonHost() | |
| const result = materializeRelocatedDaemonHost() | |
| expect(existsSync(sentinel)).toBe(true) |
There was a problem hiding this comment.
Important
The port is correct — and it fixes a latent bug — but it makes the uninstall sweep live for the first time, and the only real exercise of that sweep (the manual uninstall smoke test) still has no recorded run.
Reviewed changes
- Ported the daemon-host uninstall sweep into the live NSIS include — the sweep previously lived in a standalone
config/nsis/daemon-host-uninstall.nshthatelectron-builder.config.cjsnever referenced (nsis.includehas always pointed atorca-installer-hooks.nsh), so it was dead code and an uninstall would have orphaned the daemon. It now runs fromcustomUnInstallin the merged include, preserving the${isUpdated}guard, the user-scoped filter, and the balanced stack. - Added a regression test —
keeps the daemon-host uninstall sweep across the include renameasserts, against comment-stripped script, the app-exe and legacytaskkills, the/FI "USERNAME eqfilter, and the${ifNot} ${isUpdated}guard. - Updated doc and comment references —
windows-daemon-host-relocation.md,windows-edr-posture.md, and thedaemon-host-relocation.tsmarker comment now nameorca-installer-hooks.nsh; no staledaemon-host-uninstallreference remains except the test's explanatory comment.
⚠️ The uninstall sweep is now live — prove it before merging
Before this commit the daemon cleanup was in a file that never shipped, so no prior revision of this PR could actually reap an orphaned daemon. This is the first revision where that code runs, and its only real exercise is the manual smoke test (install → open a terminal → uninstall → confirm no surviving daemon and no %LOCALAPPDATA%\Orca\daemon-host tree), which no workflow covers and which has no recorded run on this branch. The survival E2E gate is unaffected by this delta — the copy plan did not change — but the smoke test is now load-bearing rather than a formality.
Technical details
# Uninstall sweep now live — run the manual smoke test
## Affected sites
- config/nsis/orca-installer-hooks.nsh:66-96 — `customUnInstall` daemon sweep, previously dead code in `daemon-host-uninstall.nsh`
## Required outcome
- Manual uninstall smoke test on Windows: install → open a terminal → uninstall → confirm no surviving daemon and no `%LOCALAPPDATA%\Orca\daemon-host` tree.
## Open questions for the human (optional)
- None — the code is correct; the outstanding item is evidence, not a fix.ℹ️ Nitpicks
- The PR body still describes
config/nsis/daemon-host-uninstall.nshin the "What else is in the diff" and "File overlap" sections, but that file no longer exists after the rename toorca-installer-hooks.nsh.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
…t (MDE T1036) (stablyai#17865) * docs(windows): document the EDR signal surface Six Microsoft Defender for Endpoint incidents fired against Orca 1.4.192 in eight days on one enterprise Windows 11 / Intune tenant. All six were behavioural process-tree scoring, not signature hits; two escalated to multi-stage incidents mapped to ATT&CK Execution and Collection. Add a reference doc mapping each attack-technique-shaped behaviour to the code that produces it and to why it exists: the renamed daemon image (T1036), the per-process PEB read, encoded policy-bypassed PowerShell (T1049), caret-escaped cmd.exe lines, and computer-use screen capture plus runtime-compiled MSIL (T1113). Records that signing is not the gate -- reputation is signer plus hash-keyed prevalence -- and carries the two evidence gaps the report noted. Adds an engineer checklist, deployment guidance for admins (AV path exclusions do not suppress EDR behavioural alerts; an MDE alert suppression rule does), and an explicit pre-deployment warning about computer use. * docs(windows): correct the PowerShell flag inventory and admin paths Review corrections to the EDR posture doc. The "encoded, policy-bypassing PowerShell" list conflated three different shapes and was incomplete. Split it into the three tiers an EDR actually scores differently -- bypass plus encoding, encoding alone, and bypass alone -- and add the sites it missed, including windows-mobile-firewall.ts, which encodes a script and launches it elevated through Start-Process -Verb RunAs. system-fonts.ts (-Command) and desktop-script-provider-bridge.ts (-File) were listed as encoded and are not. Notes that a raw grep under-reports, because the hook sites reach -EncodedCommand through wrapWindowsPowerShellEncodedCommand. Attribute the in-payload Set-ExecutionPolicy move to stablyai#16576 rather than to stablyai#16003's measurement, which keyed on -WindowStyle Hidden + -EncodedCommand, and record that the launcher's own tradeoff is unverified on a real box. Admin guidance was missing two ways a suppression rule pinned to one full path misses real activity: the .staging-<hex> sibling that exists mid-update, which is when the update-cluster incidents fire, and the userData fallback when LOCALAPPDATA is unset. Also: state the measurement conditions on the process-table timings, note that Hermes has surface even though we have no telemetry for it, note that the uninstaller names are electron-builder-generated and in no repo file, drop a volatile line count, and mark the per-operation computer-use shape as being addressed by an unmerged change. Drops the duplicated AGENTS.md section, keeping the indexed bullet. * docs(windows): reconcile the EDR posture doc with the shipped remediation Three claims in this doc became false once the rest of the Windows EDR set landed, and two told engineers the opposite of what the release does. The process-table section still described one shared snapshot taken with `Memory | CommandLine | CreationTime`, argued that splitting the cache per field set "would restore exactly the fan-out it exists to prevent", and concluded the shape was unfixable because "the information is only in the PEB". The split shipped (identity opens no handle at all), `Memory` is retired, and the command line now comes from the kernel through `ProcessCommandLineInformation` -- `ReadProcessMemory` is absent from the compiled addon and a ratchet asserts it against the import table. An engineer reading the old text would have concluded both fixes were dead ends. The PowerShell site inventories were stale in three of four lists: the port scan went native, every `-ExecutionPolicy Bypass` + `-EncodedCommand` pair was dropped as a measured no-op, and of the unencoded-bypass list only `wsl-cli-scripts.ts` survives. Regenerated against the merged tree, including the sites that reach the flag through `wrapWindowsPowerShellEncodedCommand` and never spell it, which a raw `rg` misses. Incident-evidence sections are left alone: they record what the tenant observed on 1.4.192, not what the code does now. * fix(windows): copy the daemon host exe verbatim instead of renaming it Microsoft Defender for Endpoint flagged `orca-terminal-daemon.exe` as MITRE T1036 (Masquerading): Orca copied its own `Orca.exe` into %LOCALAPPDATA% under a different name, specifically so the NSIS updater's `taskkill /IM Orca.exe` could not match, then ran it detached. Because that process is what every other flagged action was attributed to, the name mismatch acted as a reputation multiplier on unrelated findings. The rename was never what made the daemon survive. In app-builder-lib 26.15.3 the installer's FIND_PROCESS/KILL_PROCESS select processes whose image path is under $INSTDIR; `taskkill /IM` is only the fallback for hosts where PowerShell is missing or blocked. Survival is a property of the path, and %LOCALAPPDATA%\Orca\daemon-host is outside $INSTDIR whatever the file is called. Derive the host exe name from process.execPath so the copy is byte-for-byte, name included — it keeps its Authenticode signature and carries no renamed-image signal. On the no-PowerShell fallback the daemon is now killed with the app and terminals cold-restore, which is the documented pre-relocation outcome the update harness already asserts, not a regression. The uninstall macro no longer needs a distinct name to find the daemon; it kills the app's own image name (plus the legacy name, for hosts left by older builds). Adds docs/reference/windows-daemon-host-relocation.md with the survival contract, the rejected alternatives and their measured costs, and the invariants to keep. * fix(windows): apply daemon-host relocation review corrections Scope the uninstall taskkill to the current user with `/FI "USERNAME eq %USERNAME%"` via cmd.exe, matching upstream's per-user KILL_PROCESS — without it an elevated machine-wide uninstall reaches another logged-on user's session, so the "no collateral" claim in the comment was overstated. Comment the rmSync-before-publish: Windows refuses to delete a running image, so a live daemon already hosted in this version's dir (same-version reinstall, or a dev channel reusing a version) throws and materialization fails open. Doc corrections: - The fallback selector is the full per-user `taskkill /F /IM "<app>.exe" /FI "PID ne $pid" /FI "USERNAME eq %USERNAME%"`, not a bare `taskkill /IM`. - The probe reads `Get-ExecutionPolicy -Scope Process`, not the effective policy, and GPO writes MachinePolicy/UserPolicy — so GPO-managed hosts take the primary path-scoped branch. Narrow the fallback triggers accordingly. - Drop the Authenticode sentence: the old name was equally byte-identical and equally signed, so a filename has no bearing on signature validity. - Name the new update-abort path: the daemon now matches FIND_PROCESS, so on the fallback branch an unkillable host reaches the retry loop's MessageBox /SD IDCANCEL and Quits, aborting a silent update. - Correct the customCheckAppRunning rejection. It is ~6 lines, not a rewrite; it is wrong because forcing the PowerShell branch where PowerShell is absent makes FIND/KILL silently no-op and leaves the real app running with files in use. - Bound the win honestly: OriginalFilename is empty on the shipped binary, so the strongest T1036 indicator never fired, and the residual copy-and-run-detached shape still maps to T1036.005. Reconcile docs/reference/windows-edr-posture.md, which documents the rename as a live finding and would otherwise contradict this change. Content-only edit: markdown under docs/reference/ is not oxfmt-formatted as a matter of practice and nothing in CI gates it, so the file is left consistent with its neighbours. * fix(windows): expand USERNAME in NSIS instead of spawning cmd.exe The uninstall macro routed both taskkills through `"$SYSDIR\cmd.exe" /C` purely so `%USERNAME%` would expand — two extra interpreter spawns on the uninstall path, in a change whose whole point is not adding scored behaviour, and the exact `cmd.exe /c` shape the new AGENTS.md EDR bullet warns about. NSIS reads the variable itself with ReadEnvStr, so the spawns buy nothing. Verified on Windows 11 that the generated command line does what the filter is there for: a copy of cmd.exe running as orca-nonexistent-probe.exe (pid 34244) was terminated by `taskkill /F /IM "orca-nonexistent-probe.exe" /FI "USERNAME eq <user>"` — SUCCESS, exit 0, process gone. Guarded on an empty USERNAME because the degenerate case is silent: taskkill rejects an empty filter value outright ("The search filter cannot be recognized") and kills nothing, which would leave exactly the orphaned daemon this macro exists to reap. `*` is rejected as a filter value too, so there is no branchless spelling. With no USERNAME to scope by it kills unfiltered, as the macro did before the filter was added. Stack stays balanced: three pushes, two nsExec pops, three restores. Also strike the last stale row in windows-edr-posture.md's remediation table. "Copying our own image under a different name" read as outstanding work; it is done by this change, so the row now points at the relocation doc. Same class of staleness as the section reconciled in the previous commit, and git would not have flagged it either. * fix(windows): port the daemon-host uninstall sweep into the live NSIS include The uninstall macro this branch rewrote lived in config/nsis/daemon-host-uninstall.nsh, which main no longer includes: stablyai#17906 consolidated every Windows installer hook into config/nsis/orca-installer-hooks.nsh because electron-builder accepts exactly one `nsis.include`. Merged as-is, the rewritten macro would have been dead code while the shipped uninstaller kept running main's stale sweep — `taskkill /F /IM orca-terminal-daemon.exe`, which matches nothing now that the relocated host is a verbatim Orca.exe copy. The RMDir that follows then cannot delete the running image, so a live orphaned daemon and its ~224 MB tree would survive every uninstall. Ported into the live include: the ${APP_EXECUTABLE_FILENAME} kill, the USERNAME filter that keeps an elevated machine-wide uninstall out of another logged-on user's session, and the register save/restore around both. The legacy orca-terminal-daemon.exe kill stays so hosts left by older builds are still reaped. The ratchet that was meant to catch exactly this pinned only the legacy image name, which main's stale macro already satisfied, so it passed both ways. It now asserts the app-exe kill and the USERNAME filter, against comment-stripped script — the prose above the macro names both image names, so a toContain over the raw file proves nothing. --------- Co-authored-by: Orca Worker <orca-worker@localhost>

The MDE finding
Microsoft Defender for Endpoint flagged
orca-terminal-daemon.exein incidents C, D, E and F (same PID). Root cause 1 in the report is that the daemon relocation reads as masquerading, and it is the base multiplier on every other flagged action: each one is attributed to a low-reputation binary running from%LOCALAPPDATA%under a name that does not match its origin.The old comment said it plainly:
The behavioural signature: a process copies its own image into a user-writable directory under a different name, specifically so a kill-by-image-name cannot match it, then runs detached and survives the installer. MITRE T1036 (Masquerading) plus defence evasion. The reporter's comparison across VS Code, Cursor, Antigravity IDE and T3 Code found no fork that does this.
Signing is not the issue — a byte-for-byte copy of a signed PE retains its Authenticode signature, and the report confirms the file showed
Valid CN=SignPath Foundation. The problem is the runtime behaviour, and specifically the name mismatch.Key finding: the rename was never what made the daemon survive
In the pinned
[email protected],FIND_PROCESS/KILL_PROCESSintemplates/nsis/include/allowOnlyOneInstallerInstance.nshhave two branches:powershell.exeruns,Get-CimInstanceresolves, andGet-ExecutionPolicy -Scope Processis notRestrictedGet-CimInstance Win32_Processwhere$_.Path.StartsWith('$INSTDIR', 'CurrentCultureIgnoreCase')— path-scopedtaskkill /F /IM "<AppName>.exe" /FI "PID ne $pid" /FI "USERNAME eq %USERNAME%"; per-machine: the same without the username filter — image-name-scopedThe probe reads the process scope, not the effective policy, and Group Policy writes
MachinePolicy/UserPolicy— so a GPO-managed host whose effective policy isRestrictedstill exits 0 and takes the primary branch. (Reviewer-verified: on such a host the shipped probe exits 0; a probe rewritten to test effective policy exits 1.) The fallback is reached only whenpowershell.exeis absent,Get-CimInstancedoes not resolve, PowerShell is blocked outright (WDAC/AppLocker, Server Core), or an inheritedPSExecutionPolicyPreference=Restrictedis in the environment.So on essentially every machine the updater's kill sweep matches on image path. The default per-user install is
%LOCALAPPDATA%\Programs\Orca; the daemon host is%LOCALAPPDATA%\Orca\daemon-host— not a prefix, so it is out of range whatever the file is called. File deletion is not the killer either: Windows will not delete a running image, soRMDir /r "$INSTDIR"cannot end the daemon on its own.Survival is a property of the path. The premise in the old comment was already false for the primary code path.
Options evaluated, with measurements
Measured on this machine (Electron 43.4.1, installed 1.4.193 build):
Orca.exe— 235,555,328 bytes (224.6 MiB)icudtl.dat10.4 MiB,v8_context_snapshot.bin0.71 MiB,snapshot_blob.bin0.35 MiB%LOCALAPPDATA%\Orca\daemon-host\1.4.193-adhoc.*— 246 MB (the source comment's "~260MB" checks out)(A) Move materialization into the NSIS installer — rejected
Writing 246 MB at install time doubles the install footprint and lengthens the window in which the app is down during a silent update (electron-updater runs the same NSIS installer). Two harder problems:
INSTALL_MODE_PER_ALL_USERS) runs elevated as the installing admin, so$LOCALAPPDATAis the wrong user's. Every other user on that machine still needs the runtime path.Partial signal reduction, large cost, and the riskiest change of the three.
(B) Ship a distinct signed
orca-terminal-daemon.exein the installer — rejectedA second 224.6 MiB PE. electron-builder's NSIS uses solid LZMA with a 64 MB dictionary, so a copy 224 MB downstream does not dedupe — the compressed installer grows by roughly a whole compressed Electron binary, paid by every user on every update download.
It also does not remove the runtime copy: the helper still has to reach
%LOCALAPPDATA%to escape the sweep, it is just copied verbatim once there. So it buys exactly the same signal reduction as (C) at a large and permanent download cost. Strictly dominated.(C) Stop the name from being a taskkill dodge — shipped
The
customCheckAppRunningvariant (force the path-scoped kill on both branches) was rejected — but not for size. It is ~6 lines (!include "getProcessInfo.nsh",Var pid, and a macro pinningIsPowerShellAvailable, reusing upstream's dialog, retry loop and elevated handling wholesale). It is wrong because forcing the PowerShell branch on a host where PowerShell is genuinely absent makesFIND_PROCESSandKILL_PROCESSsilently no-op, so the installer proceeds with the real app still running and its files in use — worse than the cold restore it would prevent. Not worth doing ever, not merely not now.What shipped:
DAEMON_HOST_EXE_NAMEis gone; the host exe name is derived fromprocess.execPath.The relocated image is a byte-for-byte, name-included copy. No image-name mismatch, no
taskkilldodge. Nothing else about relocation changes — same path, same marker, same atomic staging/publish, same prune veto, same fail-open.What this actually buys — calibrated
Two things bound the win, and both belong in the record:
OriginalFilenameis empty (onlyInternalName = Orca), so there was no embedded name fororca-terminal-daemon.exeto contradict.%LOCALAPPDATA%and running it detached underELECTRON_RUN_AS_NODE=1— is still execution from a non-standard user-writable location, which maps to T1036.005 and is a standard heuristic on its own.Expect the score to drop. Do not expect all six incidents to clear. This removes the literal indicator and the incriminating source comment; it does not stop the process being scored.
Behaviour changes and new failure modes
taskkill /IMbranch, the daemon is now killed with the app and terminals cold-restore on relaunch. That is the documented pre-relocation outcome and a first-class harness profile (--expect cold-restore), not a break. Relocation is fail-open end to end anyway.FIND_PROCESSunder the app's image name, so it enters the retry loop atallowOnlyOneInstallerInstance.nsh:136-141. If thetaskkillthere fails to end it (an elevated or otherwise unkillable host), the loop reachesMessageBox … /SD IDCANCELandQuits, aborting a silent update. Under the old distinct name the daemon was invisible to that loop. Low probability — fallback branch and an unkillable daemon — but a real new path, documented.CHECK_APP_RUNNINGruns twice per update (the new installer, plus the old uninstaller viaun.onInit's silent path, which does run underONE_CLICK); both are path-scoped.What else is in the diff
config/nsis/daemon-host-uninstall.nsh— the macro no longer has a distinct image name to hunt for, so it kills the app's own image name plus the legacyorca-terminal-daemon.exe, each scoped with/FI "USERNAME eq $1"where$1comes from NSIS's ownReadEnvStr USERNAME. That matches upstream's per-userKILL_PROCESSso an elevated machine-wide uninstall cannot reach another logged-on user's session, without the twocmd.exespawns an earlier revision used just to expand%USERNAME%— adding scoredcmd.exe /cbehaviour in a PR about reducing it would have been an odd note to end on.cmd.exerunning asorca-nonexistent-probe.exe(pid 34244) was terminated bytaskkill /F /IM "orca-nonexistent-probe.exe" /FI "USERNAME eq <user>"—SUCCESS, exit 0, process gone.USERNAME, because that case fails silently:taskkillrejects an empty filter value outright (ERROR: The search filter cannot be recognized) and kills nothing, leaving exactly the orphaned daemon the macro exists to reap.*is rejected as a filter value too, so there is no branchless spelling. With noUSERNAMEto scope by it kills unfiltered, as the macro did before the filter existed.USERNAMEis set in every session an uninstaller runs in, so this is a backstop, not the expected path.nsExecpops, three restores. The${isUpdated}guard is untouched. A path-scoped PowerShell kill was drafted and dropped — spawningpowershell.exefrom an installer to hunt processes by path cuts against the point of this PR.src/main/daemon/daemon-host-relocation.ts— a comment on thermSync(dest)before publish: Windows refuses to delete a running image, so a live daemon already hosted in this version's dir (same-version reinstall, or a dev channel reusing a version) throws and materialization fails open to the install-dir host.docs/reference/windows-daemon-host-relocation.md(new) — survival contract, the two-branch kill table, rejected options with these numbers, the new abort path, the calibrated residual, and the invariants (name derived fromexecPath; daemon identified by PID + command line, never image name). Linked fromAGENTS.md, allowlisted in.gitignore.docs/reference/windows-edr-posture.md(docs(windows): document the EDR signal surface #17856's doc) — it documents the rename as a live finding and goes stale the moment this lands, which git would not flag as a conflict. Reconciled to describe the rename as historical-to-these-incidents, cross-referenced to the new doc, with theOriginalFilenameand T1036.005 calibration added. The remediation table's "Copying our own image under a different name" row read as outstanding work when this PR is what completes it, so it now points at the relocation doc. Content-only edit — markdown indocs/reference/is notoxfmt-formatted as a matter of practice (all 24 existing files there failoxfmt --check, and no CI job gates markdown formatting:pr.ymlrunsoxlintonly). I ran the formatter over it by reflex, saw ~100 lines of whole-file churn, and reverted it — the diff stays at 23/10 and the file stays consistent with all 24 of its neighbours.tests/tools/win-crash-survival-e2e/that named the old exe.De-risking evidence
tests/tools/win-update-e2e/daemon-processes.mjs:41-52finds the daemon by command line (daemon-entry.js), never by exe name — deliberately, with a comment anticipating "a relocated Phase 1 host may run from a differently-named copied binary". That header comment is stale on base and becomes correct again with this change.src/matches the daemon by image name; everytaskkillinsrc/is PID-scoped (/pid … /t /f). Daemon identity is PID + command line + PID-file records.tests/tools/daemon-relocation-spike/) usedHOST_EXE = 'Orca.exe'— a verbatim-named copy is the configuration originally proven to boot as a run-as-node host.Orca Nightly.exe) is followed rather than replaced by a fixed name.Verification
node config/scripts/run-typecheck-projects-in-parallel.mjs(pnpm tc)vitest run src/main/daemon/daemon-host-relocation.test.tsvitest run src/main/daemon/oxlinton changed files (incl.--report-unused-disable-directives-severity warn)oxfmt --checkon changed code fileswindows-edr-posture.mddeliberately left unformatted, matching every doc in that directory)node config/scripts/check-max-lines-ratchet.mjsThe 11 failures are pre-existing and environmental: all six files are node-pty/PTY-spawn tests, and the same 11 fail identically on the base commit
f088872554in this worktree (visible asCannot read properties of undefined (reading 'onData')— node-pty's native binding absent).pnpm install's native rebuild fails here withMSB3491on@vscode/windows-process-tree(MAX_PATH — the agent worktree path is too long for MSBuild), which takes node-pty's rebuild down with it. None of those tests importdaemon-host-relocation.pnpm tcandpnpm testwere run via their underlying scripts for the same reason (pnpm re-runs the failing postinstall).daemon-host-relocation.tssits at 299/300 counted lines. Nomax-linesdisable and no baseline bump; the one-line arrow keeps it under. Splitting a 299-line file to buy two lines would be worse, so the next edit there should be a deliberate follow-up.E2E that MUST pass before merge
No unit test can prove terminal survival. All four are
workflow_dispatch, so they need a manual dispatch against this branch:.github/workflows/win-update-survival-e2e.ymlwithexpect: survival— the primary proof. Builds an installer from this branch and updates it over itself. This is the one that would catch a mistake in the naming change..github/workflows/win-crash-survival-e2e.ymlwithexpect: survival— daemon survives a main-process crash..github/workflows/windows-terminal-restart-e2e.yml(accepts arefinput)..github/workflows/win-update-e2e.yml— release-tag to release-tag, useful for confirming an old-name daemon and a new-name daemon coexist across the version boundary.The NSIS macro edit is only exercised by a real uninstall, which no workflow covers; smoke-test it by hand (install → open a terminal → uninstall → confirm no surviving daemon and no
%LOCALAPPDATA%\Orca\daemon-hosttree).Risks for a reviewer
daemon-host/<old>/orca-terminal-daemon.exe; new builds materializedaemon-host/<new>/Orca.exe. Separate version dirs, no migration.[email protected]; re-readallowOnlyOneInstallerInstance.nshon an electron-builder bump.windows-edr-posture.mdwill conflict textually if docs(windows): document the EDR signal surface #17856 revises that section before merging.File overlap
OrcaWin/win-edr-posture-docs) — resolved by rebasing onto it, as instructed..gitignore: both allowlist lines kept, sortedwindows-daemon-host-relocation.md→windows-edr-posture.md→windows-process-enumeration.md.AGENTS.md: both bullets kept in the existing Cross-Platform Support list, relocation bullet before the EDR-signal one, no new section. Plus the content reconciliation of their doc described above.config/nsis/daemon-host-uninstall.nshonly; it does not touchconfig/electron-builder.config.cjs(thensis.includepath is unchanged) or.github/workflows/release-cut.yml.