Skip to content

fix(local-installation): harden Windows process identity inspection - #681

Open
oldwinter53 wants to merge 2 commits into
mainfrom
oldwinter53/whi-999-win-process-identity
Open

oldwinter53 wants to merge 2 commits into
mainfrom
oldwinter53/whi-999-win-process-identity

Conversation

@oldwinter53

@oldwinter53 oldwinter53 commented Nov 24, 2026 •

Copy link
Copy Markdown

Summary

Fixes WHI-999: Windows native service install and stop failing with opaque Native process identity could not be inspected. errors.

Root Cause

In packages/local-installation/src/native-process-identity.ts, Windows process enumeration had four compounding reliability issues:

  1. WINDOWS_PROCESSES invoked $_.CreationDate.ToFileTimeUtc() under $ErrorActionPreference = 'Stop' without guarding $_.CreationDate. On Windows, system, protected, or exiting processes (such as System Idle Process PID 0, System PID 4, or EDR-protected processes) return $null for CreationDate, causing a terminating PowerShell error that fails the entire query.
  2. Get-CimInstance Win32_Process fetched all ~45 CIM properties per process instead of projecting only the four required fields, inflating WMI query latency and buffer pressure.
  3. windowsProcesses() invoked bare powershell.exe instead of the full %SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe path, failing with ENOENT under restricted PATH environments.
  4. runProcess() capped maxBuffer at 2 MB and discarded stderr and error codes behind a generic message, hiding the real failure cause in diagnostics.

Changes

  • Guard $_.CreationDate -is [datetime] before calling .ToFileTimeUtc() (defaulting to 0), isolate $env:PSModulePath to Windows PowerShell built-in modules, and project only -Property ProcessId,ParentProcessId,CreationDate,CommandLine while preserving the Get-CimInstance Win32_Process substring matched by processInspection.
  • Resolve the full %SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe path (using the package's process.env.SystemRoot ?? "C:\Windows" default) and pass systemRoot through windowsSnapshot.
  • Raise inspector maxBuffer to 16 MiB and include failure codes, timeout signals, and CLIXML-decoded stderr excerpts sanitized via the package's shared redact and excerptLine helpers (@linger/local-installation/redaction).
  • Add unit tests in packages/local-installation/src/native-process-identity.test.ts and packages/local-installation/src/native-process-windows.test.ts.

Verification

  • pnpm --filter @linger/local-installation typecheck
  • pnpm --filter @linger/local-installation lint
  • pnpm --filter @linger/local-installation build
  • pnpm --filter @linger/local-installation exec vitest run src/native-process-identity.test.ts src/native-process-windows.test.ts src/native-process-win32.test.ts
  • pnpm --filter @linger/linger-installer typecheck && pnpm --filter @linger/linger-installer lint && pnpm --filter @linger/linger-installer build
  • Direct Node 26 .ts import check for native-process-identity.ts (matching native-process-worker.mjs)
  • scripts/ci/check-changed-files.sh and pnpm env:inventory:check

@linger-review linger-review Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Request changes (1 P1, 1 P2)

Scope: base main, merge base afa1c47d. I reviewed 1 commit (e9e2184f) and 3 files. Helper skills loaded: coderbook, ponytail-review, karpathy-guidelines. The review ran in a separate session.

Findings

P1

1. Secret redaction is a verbatim copy of the package's existing redactor (packages/local-installation/src/native-process-identity.ts:34-45, :48-56)

  • Problem: redactInspectionText copies redact() in packages/local-installation/src/redaction.ts:2-17 character for character: stripVTControlCharacters, the key/value regex, the Bearer regex and the URL-userinfo regex. STDERR_EXCERPT_LIMIT = 240 plus the slice-and-ellipsis code in sanitizeInspectionStderr also copies excerptLine(line, 240) from redaction.ts:19-21.
  • Why it matters: The same package now has two copies of the redaction rule. The next fix to redact() (a new secret key, or a fix like the existing quadratic-backtracking note) will not reach the inspector path. Its error messages would then leak what the rest of the package redacts.
  • Fix: Use import { excerptLine, redact } from "./redaction.js";, delete redactInspectionText and STDERR_EXCERPT_LIMIT, and make sanitizeInspectionStderr return excerptLine(redact(raw).replace(/\s+/g, " ").trim()). This is safe to import directly: redaction.ts imports only node:util, and native-process-worker.mjs:6 already loads it as source before any build. That is the same constraint this module's header comment describes.

P2

2. The ENOENT fallback to bare powershell.exe is speculative, and one of its branches can never run (packages/local-installation/src/native-process-identity.ts:162-174, :212-222)

  • Problem: windowsPowerShellExecutable() always returns a full ...\System32\WindowsPowerShell\v1.0\powershell.exe path. That makes executable === "powershell.exe" in the catch block always false. The fallback only runs when the System32 copy of Windows PowerShell 5.1 is missing, which does not happen on supported Windows. If it ever ran, it would resolve powershell.exe through PATH, the restricted-PATH lookup this PR set out to avoid. A wrong SystemRoot would also already break windowsListeners in the same windowsSnapshot, because it spawns ${systemRoot}\System32\netstat.exe with no fallback. Separately, SystemRoot || WINDIR with a .trim() adds a second default policy. The rest of the package uses process.env.SystemRoot ?? "C:\\Windows" (native-process.ts:235, :856, native-database.ts:39).
  • Fix: Delete the try/catch fallback and its test (falls back to bare powershell.exe ...). Call runProcess(windowsPowerShellExecutable(systemRoot), args, ...) directly, with the same SystemRoot ?? "C:\\Windows" default the other call sites use. About 20 lines go away.

Verified as fine

  • The inspector still filters itself out after the query change. The new script still contains the substring Get-CimInstance Win32_Process, and the full executable path still matches \bpowershell(?:\.exe)?\b, so processInspection (native-process-identity.ts:283-288) still excludes the supervisor's own PowerShell child. That keeps the self-inspection guard working for both old and new releases. The test row added at native-process-windows.test.ts:65-70 covers it.
  • Null CreationDate now degrades instead of failing the whole query. Rows whose CreationDate is null get created = 0 (native-process-identity.ts:123, :157). windowsLeaseTree requires candidate.created >= parent.created (:303), so a child with a null CreationDate falls out of the tree. Before this PR the whole enumeration failed in that case, so dropping the row is the safer outcome.
  • PowerShell exit 1 is reported through the enumeration error, not swallowed. runProcess resolves exit code 1 instead of rejecting (:98-108), so a terminating PowerShell error under $ErrorActionPreference = 'Stop' reaches the new Native processes could not be enumerated (exit 1: ...) message (:223-229). Note that the opaque identity could not be inspected message from the bug report only comes from the reject path: spawn error, timeout, maxBuffer, or an exit code other than 0 or 1. The 16 MiB buffer and the full path address those causes. The CreationDate guard covers the separate exit-1 case.
  • The error-message changes do not affect identity checks. nativeProcessIdentity still catches every error and returns undefined (:431-433). The new messages only show up through nativeLeaseProcesses and windowsSnapshot.
  • Repository rules hold. The added lines contain no CJK. No behavior depends on natural-language text: the failure detail is built from error.code and error.signal and is used only for display. $env:PSModulePath is set only inside the child PowerShell process.

Unverified: I could not run the changed PowerShell script on Windows. Whether -Property ... | ForEach-Object together with the PSModulePath override behaves as intended on real hosts rests only on string-content tests (native-process-identity.test.ts:57-66).

Process notes

  • There is one commit and no merge commits, and the branch is up to date with main. mergeStateStatus is BLOCKED, which is the required review.

CI

  • All checks that ran passed: packages, installer, desktop, web, repository-gate and CodeQL. The other jobs were skipped by path filters.
  • No CI job runs packages/local-installation on Windows, so neither the new PowerShell script nor native-process-windows-live.test.ts ran against real WMI. I ran no tests locally.

Automated review by Claude Code


Automated review of e9e2184 by Claude Code.

@linger-review linger-review Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Approve with nits (1 P3)

Scope: base main, merge base afa1c47d; 2 commits, 3 files reviewed (full merge-base diff plus e9e2184f..d2c2eef1). Helper skills loaded: coderbook, ponytail-review, karpathy-guidelines. Ran in a separate session. Follow-up on e9e2184.

Previous findings

  • P1 "Redaction regex copied verbatim from redaction.ts": Resolved. native-process-identity.ts:5 now imports excerptLine and redact from @linger/local-installation/redaction, and sanitizeInspectionStderr (:35-40) composes them. The local regex and STDERR_EXCERPT_LIMIT are gone.
  • P2 "ENOENT fallback is defensive and has an unreachable branch": Resolved. windowsProcesses (:183-201) now makes a single runProcess call with the system path. The fallback and its test are removed, and windowsPowerShellExecutable (:147-157) uses the same process.env.SystemRoot ?? "C:\\Windows" default as process.ts:12 and native-process.ts:856.

Findings

P3

  • PR description is stale (packages/local-installation/src/native-process-identity.ts:147). The body still says the path is resolved "with WINDIR / C:\Windows defaults and ENOENT fallback to powershell.exe". After d2c2eef1 the code reads neither WINDIR nor any fallback. Please update the Changes section so it matches the code.

Verified as fine

  • The self-reference import resolves on every load path. In source, the default condition in packages/local-installation/package.json exports maps it to src/redaction.ts. I loaded native-process-identity.ts directly with Node 26.5 type stripping, which is how native-process-worker.mjs:10 loads it: sanitizeInspectionStderr returned a 240-char excerpt, and windowsPowerShellExecutable() returned the System32 path. The installer bundles the worker with esbuild (apps/linger-installer/scripts/build.mjs:13-24), which resolves package exports. The tsc build of native-process.ts sees .ts types via the types condition.
  • Null CreationDate now maps to 0 (:107, :141). This cannot let a stranger into a lease tree. windowsLeaseTree (:270-276) and native-process.ts:784 adopt a child only when created >= parent.created, so a 0 child joins only under a parent that is also 0. The owner is the worker itself, found by its .job command line, so it is not a protected or system process. Birth identities (:354, :417, native-process.ts:187,663) for such processes just compare unequal, which is the safe direction.
  • The Get-CimInstance Win32_Process substring that processInspection matches is kept in the projected query (:105).
  • runProcess keeps its exit-code-1 contract (:81-93), and only stderr and the new error detail are added. Callers of windowsProcesses/windowsSnapshot (native-process.ts:200,234,657,856,898, native-process-identity.ts:351,410) are unchanged.
  • The error text is redacted with the package's shared redactor before it reaches messages that can be logged.
  • No CJK in added lines or commit messages, no env vars added, no contract or doc changes needed.

Process notes

  • d2c2eef1 only applies the review fixes to e9e2184f. Since main takes rebase merges, consider squashing it into the first commit. No merge commits.

CI
All required checks pass: check (packages), check (installer), check (desktop), check (web), repository-gate, CodeQL. The others were skipped as not applicable. I ran only a direct Node import smoke test of the module (it passed). No Windows host was available, so the PowerShell script itself was checked against the code and the string-level tests, not run on Windows.

Automated review by Claude Code


Automated review of d2c2eef by Claude Code.

@linger-review linger-review Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Approve (0 findings)

Scope: follow-up on d2c2eef (same head SHA as the previous review; only the PR description changed since). Base main, merge base afa1c47d, 2 commits, 3 files reviewed. I loaded the review rubric's coderbook (sections 2/3/5), ponytail-review (sections 1–3) and karpathy-guidelines (sections 2/3) and applied them inline without loading them as separate skills. Ran in a separate session.

Previous findings

  • Resolved: "PR description still mentions the removed WINDIR fallback". The Changes section now says the path resolves from process.env.SystemRoot ?? "C:\Windows" and no longer mentions WINDIR or a bare powershell.exe fallback. That matches packages/local-installation/src/native-process-identity.ts:146-157.

Findings

None.

Verified as fine

I re-checked the whole merge-base diff for P0/P1 issues:

  • Null CreationDate → created = 0 (native-process-identity.ts:108, :141): windowsLeaseTree admits a child only when candidate.created >= parent.created (:272), so a child with created = 0 is dropped as a reused PID instead of being misattributed. The supervisor still has to match .${lease}.job (:263). The birth string win32:pid:0 (:354) only shows up for a process that is already exiting, and it fails the birth equality check in native-process.ts:187/:663, which leaves the process treated as not running. Before this change, the whole enumeration threw.
  • Inspection self-exclusion still works: the new script still contains Get-CimInstance Win32_Process and runs under powershell.exe, so processInspection (:251-256) keeps excluding the supervisor's own snapshot child. The new test row 22 in native-process-windows.test.ts covers this with the full-path command line.
  • $env:PSModulePath = $PSHOME\Modules: Get-CimInstance (CimCmdlets) and ConvertTo-Json (Microsoft.PowerShell.Utility) both ship in $PSHOME\Modules for Windows PowerShell 5.1.
  • PowerShell path: windowsPowerShellExecutable copies the existing taskkill resolution pattern in process.ts:12,23 (process.env.SystemRoot ?? "C:\\Windows" + path.win32.join), and || "C:\\Windows" guards an empty SystemRoot. windowsSnapshot passes its systemRoot through (:240). nativeProcessIdentity falls back to the default (:351).
  • Self-reference import @linger/local-installation/redaction: the package exports ./* maps to src/*.ts by default and to dist/*.js under linger-production. The installer bundles native-process-worker.mjs with esbuild bundle: true (apps/linger-installer/scripts/build.mjs:16-20), so the import resolves at bundle time; in source mode, Node's package self-reference resolves it to src/redaction.ts, which imports only node:util. It reuses redact/excerptLine (redaction.ts) instead of adding a second redactor.
  • Failure message: stderr is CLIXML-decoded, redacted, whitespace-collapsed and capped at 240 chars (sanitizeInspectionStderr, :36-41), so a long or secret-bearing stderr can't flood or leak into the status message.
  • No CJK in added lines or commit messages; no env var, contract or doc ownership changes.

Process notes

  • d2c2eef ("reuse package redactor and simplify Windows PowerShell resolution") only patches code that e9e2184 added in this PR. main takes rebase merges, so consider squashing it into e9e2184 (git rebase -i --autosquash).
  • Merge state is BLOCKED, which looks like it is waiting on required review, not on a behind branch.

CI

All relevant checks pass: check (packages), check (installer), check (desktop), check (web), repository-gate, CodeQL. Go, TeamHub, contracts and web-test jobs were skipped as unaffected. CI has no Windows runtime test of the PowerShell script itself; I reviewed it from the code. I ran no tests myself.

Automated review by Claude Code


Automated review of d2c2eef by Claude 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