Skip to content

Commit 0757b10

Browse files
authored
Merge pull request #1347 from wade19990814-hue/fix/windows-popup-hidden-spawn
fix(windows): stop console popups from proxy-internal PowerShell lookups (#1278)
2 parents 2426179 + 6d49244 commit 0757b10

3 files changed

Lines changed: 148 additions & 16 deletions

File tree

‎src/codex/app-server-processes.ts‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
import { execFileSync } from "node:child_process";
1111
import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
1212
import { isProcessAlive, waitForExit } from "../lib/process-control";
13+
import { resolveTrustedWindowsPowerShellExe } from "../lib/windows-elevation";
1314
import { readCodexCatalogPath } from "./catalog/parsing";
1415

1516
export const STALE_CODEX_APP_SERVER_HINT =
@@ -345,8 +346,10 @@ export function listWindowsSnapshots(): ProcessSnapshot[] {
345346
" } catch { \"__OCX_ENUM_INCOMPLETE__\" }",
346347
"}",
347348
].join("\n");
348-
// Top-level exec failure propagates (see listDarwinSnapshots note).
349-
const output = execFileSync("powershell.exe", [
349+
// Top-level exec failure propagates (see listDarwinSnapshots note). The
350+
// executable resolves from the trusted System32 directory (never PATH), and
351+
// windowsHide keeps the enumeration console-less on desktop sessions (#1278).
352+
const output = execFileSync(resolveTrustedWindowsPowerShellExe(), [
350353
"-NoProfile", "-NoLogo", "-NonInteractive", "-WindowStyle", "Hidden",
351354
"-Command",
352355
psCommand,
@@ -457,7 +460,7 @@ function readDarwinProcStartMs(pid: number): number | null {
457460
/** Win32_Process.CreationDate → epoch ms, or null (Windows). */
458461
function readWindowsProcStartMs(pid: number): number | null {
459462
try {
460-
const out = execFileSync("powershell.exe", [
463+
const out = execFileSync(resolveTrustedWindowsPowerShellExe(), [
461464
"-NoProfile", "-NoLogo", "-NonInteractive", "-WindowStyle", "Hidden",
462465
"-Command",
463466
`(Get-CimInstance Win32_Process -Filter "ProcessId=${pid}").CreationDate.ToUniversalTime().ToString("o")`,
@@ -513,7 +516,7 @@ export function readProcessStartMsBatch(
513516
if (platform === "win32") {
514517
try {
515518
const filter = pids.map(pid => `ProcessId=${pid}`).join(" OR ");
516-
const stdout = execFileSync("powershell.exe", [
519+
const stdout = execFileSync(resolveTrustedWindowsPowerShellExe(), [
517520
"-NoProfile", "-NoLogo", "-NonInteractive", "-WindowStyle", "Hidden",
518521
"-Command",
519522
`Get-CimInstance Win32_Process -Filter "${filter}" | ForEach-Object { "$($_.ProcessId)\t$($_.CreationDate.ToUniversalTime().ToString("o"))" }`,

‎src/codex/user-identity.ts‎

Lines changed: 63 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@ import {
1717
} from "node:fs";
1818
import { isAbsolute, join, resolve } from "node:path";
1919

20+
import { resolveTrustedWindowsPowerShellExe } from "../lib/windows-elevation";
21+
2022
import type {
2123
ResolveCodexCoordinatorDatabasePath,
2224
ResolveCodexCatalogSerializationDatabasePath,
@@ -30,6 +32,13 @@ const POSIX_TMP_REQUIRED_MODE = 0o1003;
3032
const POSIX_TMP_PATH = "/tmp";
3133
const SID_PATTERN = /^S-1-(?:\d+-)+\d+$/i;
3234

35+
/**
36+
* Hard budget for the Windows identity-lookup PowerShell child. These lookups
37+
* run at startup and on config writes; a hung child must fail the lookup
38+
* (recoverable — the caller refuses) rather than wedge the proxy indefinitely.
39+
*/
40+
const WINDOWS_POWERSHELL_LOOKUP_TIMEOUT_MS = 8_000;
41+
3342
export class CodexUserIdentityRefusal extends Error {
3443
readonly code = "CODEX_USER_IDENTITY_REFUSED";
3544

@@ -43,24 +52,66 @@ function refuse(message: string, cause?: unknown): never {
4352
throw new CodexUserIdentityRefusal(message, cause === undefined ? undefined : { cause });
4453
}
4554

55+
function windowsIdentityPowerShellCommand(expression: string): string[] {
56+
return [
57+
resolveTrustedWindowsPowerShellExe(),
58+
"-NoLogo",
59+
"-NoProfile",
60+
"-NonInteractive",
61+
"-WindowStyle",
62+
"Hidden",
63+
"-Command",
64+
expression,
65+
];
66+
}
67+
68+
function windowsIdentityPowerShellSpawnOptions(): {
69+
stdin: "ignore";
70+
stdout: "pipe";
71+
stderr: "pipe";
72+
timeout: number;
73+
windowsHide: boolean;
74+
} {
75+
return {
76+
stdin: "ignore",
77+
stdout: "pipe",
78+
stderr: "pipe",
79+
timeout: WINDOWS_POWERSHELL_LOOKUP_TIMEOUT_MS,
80+
windowsHide: true,
81+
};
82+
}
83+
84+
/** Test-only readback of the trusted executable and static arguments (#1278). */
85+
export function windowsIdentityPowerShellCommandForTests(expression: string): string[] {
86+
return windowsIdentityPowerShellCommand(expression);
87+
}
88+
89+
/** Test-only readback of the spawn options shared by the identity lookups (#1278). */
90+
export function windowsIdentityPowerShellSpawnOptionsForTests(): ReturnType<
91+
typeof windowsIdentityPowerShellSpawnOptions
92+
> {
93+
return windowsIdentityPowerShellSpawnOptions();
94+
}
95+
4696
function powershellValue(expression: string): string {
97+
let command: string[];
98+
try {
99+
command = windowsIdentityPowerShellCommand(expression);
100+
} catch (cause) {
101+
refuse("Windows effective-account lookup could not start.", cause);
102+
}
47103
let result: ReturnType<typeof Bun.spawnSync>;
48104
try {
49-
result = Bun.spawnSync([
50-
"powershell.exe",
51-
"-NoLogo",
52-
"-NoProfile",
53-
"-NonInteractive",
54-
"-Command",
55-
expression,
56-
], {
57-
stdin: "ignore",
58-
stdout: "pipe",
59-
stderr: "pipe",
60-
});
105+
// `windowsHide` is the popup fix (#1278): the desktop proxy parent runs
106+
// without a console, so a console-subsystem child spawned without
107+
// CREATE_NO_WINDOW gets a fresh visible console window at startup and on
108+
// every config write. `-WindowStyle Hidden` alone does not stop the
109+
// allocation; the flag behind `windowsHide` does.
110+
result = Bun.spawnSync(command, windowsIdentityPowerShellSpawnOptions());
61111
} catch (cause) {
62112
refuse("Windows effective-account lookup could not start.", cause);
63113
}
114+
if (result.exitedDueToTimeout) refuse("Windows effective-account lookup timed out.");
64115
if (result.exitCode !== 0) refuse("Windows effective-account lookup failed.");
65116
const value = new TextDecoder().decode(result.stdout).trim();
66117
if (!value) refuse("Windows effective-account lookup returned an empty value.");

‎tests/windows-popup-fix.test.ts‎

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
/**
2+
* Regression coverage for the Windows console-popup fix (#1278).
3+
*
4+
* The desktop proxy parent runs without a console. Every console-subsystem
5+
* child it spawns without CREATE_NO_WINDOW (`windowsHide`) gets a fresh
6+
* visible console window — observed at startup, on config writes, and on
7+
* shutdown. The proxy-internal identity and process lookups must therefore
8+
* spawn PowerShell hidden, from the trusted System32 directory (never PATH),
9+
* and under a bounded timeout so a hung child cannot wedge those paths.
10+
*/
11+
import { afterEach, describe, expect, test } from "bun:test";
12+
13+
import { readProcessStartMsBatch } from "../src/codex/app-server-processes";
14+
import {
15+
resolveEffectiveUserIdentity,
16+
windowsIdentityPowerShellCommandForTests,
17+
windowsIdentityPowerShellSpawnOptionsForTests,
18+
} from "../src/codex/user-identity";
19+
import { setTrustedWindowsElevationExecutablesForTests } from "../src/lib/windows-elevation";
20+
21+
const TRUSTED_POWERSHELL = "C:\\trusted-system32\\WindowsPowerShell\\v1.0\\powershell.exe";
22+
23+
afterEach(() => {
24+
setTrustedWindowsElevationExecutablesForTests(null);
25+
});
26+
27+
describe("Windows identity lookup popup fix (#1278)", () => {
28+
test("builds a hidden non-interactive command from the trusted PowerShell path", () => {
29+
setTrustedWindowsElevationExecutablesForTests({ powershell: TRUSTED_POWERSHELL });
30+
const command = windowsIdentityPowerShellCommandForTests(
31+
"[System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value",
32+
);
33+
expect(command[0]).toBe(TRUSTED_POWERSHELL);
34+
expect(command).toContain("-NoProfile");
35+
expect(command).toContain("-NonInteractive");
36+
const windowStyle = command.indexOf("-WindowStyle");
37+
expect(windowStyle).toBeGreaterThan(0);
38+
expect(command[windowStyle + 1]).toBe("Hidden");
39+
expect(command[command.length - 2]).toBe("-Command");
40+
expect(command[command.length - 1])
41+
.toBe("[System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value");
42+
});
43+
44+
test("spawn options are hidden and bounded", () => {
45+
const options = windowsIdentityPowerShellSpawnOptionsForTests();
46+
expect(options.windowsHide).toBe(true);
47+
expect(options.stdin).toBe("ignore");
48+
// Assert the exact budget: the identity lookup contract is an 8-second
49+
// bound, and a looser assertion would let a silent re-tune through.
50+
expect(options.timeout).toBe(8_000);
51+
});
52+
53+
test("the hidden trusted lookup resolves the real token on Windows", () => {
54+
if (process.platform !== "win32") return;
55+
const identity = resolveEffectiveUserIdentity();
56+
expect(identity.platform).toBe("win32");
57+
if (identity.platform === "win32") {
58+
expect(identity.sid).toMatch(/^S-1-(?:\d+-)+\d+$/i);
59+
}
60+
});
61+
});
62+
63+
describe("Windows process-lookup popup fix (#1278)", () => {
64+
test("batch start-time lookup is trusted, bounded, and never throws cross-platform", () => {
65+
// On POSIX hosts the trusted System32 resolver throws inside the win32
66+
// branch's catch — the batch must degrade to nulls, exactly like a
67+
// missing/failed PowerShell, instead of propagating.
68+
const batch = readProcessStartMsBatch([process.pid], "win32");
69+
const startedAtMs = batch.get(process.pid) ?? null;
70+
if (process.platform === "win32") {
71+
expect(startedAtMs).not.toBeNull();
72+
expect(Number.isFinite(startedAtMs)).toBe(true);
73+
expect(startedAtMs!).toBeGreaterThan(0);
74+
} else {
75+
expect(startedAtMs).toBeNull();
76+
}
77+
});
78+
});

0 commit comments

Comments
 (0)