Skip to content

Commit 0deda7c

Browse files
committed
fix(service): use one UAC for create+run and fail closed on /run
Run elevated schtasks create and run inside a single privileged PowerShell process, treat any /run failure as install failure with rollback, and keep the create-denial marker on a structured CLI failure path.
1 parent d1ccd9f commit 0deda7c

6 files changed

Lines changed: 622 additions & 114 deletions

‎src/lib/windows-elevation.ts‎

Lines changed: 143 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
import { spawn, type ChildProcess, type SpawnOptions } from "node:child_process";
2-
import { existsSync } from "node:fs";
2+
import { existsSync, readFileSync, unlinkSync } from "node:fs";
3+
import { tmpdir } from "node:os";
34
import { join } from "node:path";
5+
import { randomBytes } from "node:crypto";
46

57
type ElevationSpawn = (
68
command: string,
@@ -19,6 +21,9 @@ export function setWindowsElevationSpawnForTests(next: ElevationSpawn | null): v
1921
export const WINDOWS_SCHTASKS_CREATE_ACCESS_DENIED_MARKER =
2022
"OCX_ERROR_CODE=WINDOWS_SCHTASKS_CREATE_ACCESS_DENIED";
2123

24+
export const OCX_SCHTASKS_CREATE_EXIT_PREFIX = "OCX_SCHTASKS_CREATE_EXIT=";
25+
export const OCX_SCHTASKS_RUN_EXIT_PREFIX = "OCX_SCHTASKS_RUN_EXIT=";
26+
2227
export type WindowsSchtasksOperation = "create" | "run" | "query" | "delete" | "end" | "other";
2328
export type WindowsSchtasksFailureReason = "access-denied" | "other";
2429

@@ -189,30 +194,21 @@ export interface WindowsElevationResult {
189194
stderr: string;
190195
}
191196

192-
/**
193-
* Launch a file with UAC elevation and wait for it to exit.
194-
* Throws WindowsElevationError for cancellation, timeout, launch failure, or signal termination.
195-
* Returns the elevated process exit code for completed launches (including non-zero).
196-
*/
197-
export function runWindowsElevated(file: string, args: string[], timeoutMs = 120_000): Promise<number> {
197+
function parsePrefixedExit(output: string, prefix: string): number | null {
198+
const match = output.match(new RegExp(`${prefix}(-?\\d+)`, "m"));
199+
if (!match) return null;
200+
const value = Number(match[1]);
201+
return Number.isFinite(value) ? value : null;
202+
}
203+
204+
/** Spawn non-elevated PowerShell to run a -Command script; classify UAC/cancel/timeout outcomes. */
205+
function runPowerShellCommand(commandScript: string, timeoutMs: number): Promise<WindowsElevationResult> {
198206
if (process.platform !== "win32") {
199207
return Promise.reject(new WindowsElevationError(
200208
"launch-failed",
201209
"Windows elevation is only supported on Windows.",
202210
));
203211
}
204-
const argumentList = buildWindowsElevatedArgumentList(args);
205-
// Touch .Handle so Windows PowerShell 5.1 keeps a process handle; ExitCode can
206-
// otherwise stay $null after -Wait and `exit $null` becomes exit 0 (false success).
207-
const script = [
208-
`$p = Start-Process -FilePath ${psSingleQuote(file)}`,
209-
argumentList.length > 0 ? ` -ArgumentList ${psSingleQuote(argumentList)}` : "",
210-
" -Verb RunAs -WindowStyle Hidden -PassThru -Wait;",
211-
"if ($null -eq $p) { exit 1223 }",
212-
"$null = $p.Handle",
213-
"if ($null -eq $p.ExitCode) { exit 1 }",
214-
"exit $p.ExitCode",
215-
].join("");
216212

217213
return new Promise((resolve, reject) => {
218214
let settled = false;
@@ -231,7 +227,7 @@ export function runWindowsElevated(file: string, args: string[], timeoutMs = 120
231227
try {
232228
child = elevationSpawn(
233229
windowsPowerShell(),
234-
["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command", script],
230+
["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command", commandScript],
235231
{
236232
windowsHide: true,
237233
stdio: ["ignore", "pipe", "pipe"],
@@ -275,7 +271,7 @@ export function runWindowsElevated(file: string, args: string[], timeoutMs = 120
275271

276272
child.once("close", (code, signal) => {
277273
if (timedOut) return;
278-
const detail = stderr.trim() || stdout.trim();
274+
const detail = [stderr.trim(), stdout.trim()].filter(Boolean).join("\n");
279275
if (typeof code === "number") {
280276
if (code === 1223 || windowsUacCancelledText(detail)) {
281277
settle(() => reject(new WindowsElevationError(
@@ -284,7 +280,7 @@ export function runWindowsElevated(file: string, args: string[], timeoutMs = 120
284280
)));
285281
return;
286282
}
287-
settle(() => resolve(code));
283+
settle(() => resolve({ exitCode: code, stdout, stderr }));
288284
return;
289285
}
290286
settle(() => reject(new WindowsElevationError(
@@ -294,3 +290,128 @@ export function runWindowsElevated(file: string, args: string[], timeoutMs = 120
294290
});
295291
});
296292
}
293+
294+
/**
295+
* Launch a file with UAC elevation and wait for it to exit.
296+
* Throws WindowsElevationError for cancellation, timeout, launch failure, or signal termination.
297+
* Returns the elevated process exit code for completed launches (including non-zero).
298+
*/
299+
export function runWindowsElevated(file: string, args: string[], timeoutMs = 120_000): Promise<number> {
300+
const argumentList = buildWindowsElevatedArgumentList(args);
301+
// Touch .Handle so Windows PowerShell 5.1 keeps a process handle; ExitCode can
302+
// otherwise stay $null after -Wait and `exit $null` becomes exit 0 (false success).
303+
const script = [
304+
`$p = Start-Process -FilePath ${psSingleQuote(file)}`,
305+
argumentList.length > 0 ? ` -ArgumentList ${psSingleQuote(argumentList)}` : "",
306+
" -Verb RunAs -WindowStyle Hidden -PassThru -Wait;",
307+
"if ($null -eq $p) { exit 1223 }",
308+
"$null = $p.Handle",
309+
"if ($null -eq $p.ExitCode) { exit 1 }",
310+
"exit $p.ExitCode",
311+
].join("");
312+
313+
return runPowerShellCommand(script, timeoutMs).then(result => result.exitCode);
314+
}
315+
316+
export interface ElevatedSchtasksCreateAndRunResult {
317+
createExitCode: number;
318+
/** null when /run was not attempted because /create failed. */
319+
runExitCode: number | null;
320+
stdout: string;
321+
stderr: string;
322+
}
323+
324+
/** Build the elevated (post-UAC) script that runs schtasks /create then /run without a second prompt. */
325+
export function buildElevatedSchtasksCreateAndRunScript(
326+
schtasksPath: string,
327+
createArgs: string[],
328+
runArgs: string[],
329+
resultPath: string,
330+
): string {
331+
const createList = buildWindowsElevatedArgumentList(createArgs);
332+
const runList = buildWindowsElevatedArgumentList(runArgs);
333+
const createPrefix = OCX_SCHTASKS_CREATE_EXIT_PREFIX;
334+
const runPrefix = OCX_SCHTASKS_RUN_EXIT_PREFIX;
335+
return [
336+
`$schtasks = ${psSingleQuote(schtasksPath)}`,
337+
`$resultPath = ${psSingleQuote(resultPath)}`,
338+
"function Invoke-OcxSchtasks([string]$ArgList) {",
339+
" $p = Start-Process -FilePath $schtasks -ArgumentList $ArgList -Wait -PassThru -WindowStyle Hidden",
340+
" if ($null -eq $p) { return 1 }",
341+
" $null = $p.Handle",
342+
" if ($null -eq $p.ExitCode) { return 1 }",
343+
" return [int]$p.ExitCode",
344+
"}",
345+
"function Write-OcxResult([int]$CreateCode, $RunCode) {",
346+
` $lines = @('${createPrefix}' + $CreateCode)`,
347+
` if ($null -ne $RunCode) { $lines += ('${runPrefix}' + $RunCode) }`,
348+
" Set-Content -LiteralPath $resultPath -Value ($lines -join [Environment]::NewLine) -Encoding ascii",
349+
"}",
350+
`$createCode = Invoke-OcxSchtasks ${psSingleQuote(createList)}`,
351+
"if ($createCode -ne 0) { Write-OcxResult $createCode $null; exit $createCode }",
352+
`$runCode = Invoke-OcxSchtasks ${psSingleQuote(runList)}`,
353+
"Write-OcxResult $createCode $runCode",
354+
"exit $runCode",
355+
].join("; ");
356+
}
357+
358+
function readElevatedResultFile(resultPath: string): string {
359+
try {
360+
if (!existsSync(resultPath)) return "";
361+
return readFileSync(resultPath, "utf8");
362+
} catch {
363+
return "";
364+
} finally {
365+
try { if (existsSync(resultPath)) unlinkSync(resultPath); } catch { /* ignore */ }
366+
}
367+
}
368+
369+
/**
370+
* Create and run the scheduler task inside one elevated PowerShell process (one UAC prompt).
371+
* Throws WindowsElevationError for UAC cancel/timeout/launch/signal failures.
372+
*/
373+
export async function runElevatedSchtasksCreateAndRun(
374+
schtasksPath: string,
375+
createArgs: string[],
376+
runArgs: string[],
377+
timeoutMs = 120_000,
378+
): Promise<ElevatedSchtasksCreateAndRunResult> {
379+
const resultPath = join(tmpdir(), `ocx-elev-schtasks-${randomBytes(8).toString("hex")}.txt`);
380+
const inner = buildElevatedSchtasksCreateAndRunScript(schtasksPath, createArgs, runArgs, resultPath);
381+
// One Start-Process -Verb RunAs elevates PowerShell; create and run execute inside that process.
382+
const launcher = [
383+
`$p = Start-Process -FilePath ${psSingleQuote(windowsPowerShell())}`,
384+
` -ArgumentList ${psSingleQuote(buildWindowsElevatedArgumentList([
385+
"-NoProfile",
386+
"-NonInteractive",
387+
"-ExecutionPolicy",
388+
"Bypass",
389+
"-Command",
390+
inner,
391+
]))}`,
392+
" -Verb RunAs -WindowStyle Hidden -PassThru -Wait;",
393+
"if ($null -eq $p) { exit 1223 }",
394+
"$null = $p.Handle",
395+
"if ($null -eq $p.ExitCode) { exit 1 }",
396+
"exit $p.ExitCode",
397+
].join("");
398+
399+
try {
400+
const result = await runPowerShellCommand(launcher, timeoutMs);
401+
const markerText = readElevatedResultFile(resultPath);
402+
const combined = `${markerText}\n${result.stdout}\n${result.stderr}`;
403+
const createExitCode = parsePrefixedExit(combined, OCX_SCHTASKS_CREATE_EXIT_PREFIX) ?? result.exitCode;
404+
const runExitCode = createExitCode === 0
405+
? (parsePrefixedExit(combined, OCX_SCHTASKS_RUN_EXIT_PREFIX) ?? result.exitCode)
406+
: null;
407+
return {
408+
createExitCode,
409+
runExitCode,
410+
stdout: result.stdout,
411+
stderr: result.stderr,
412+
};
413+
} catch (error) {
414+
readElevatedResultFile(resultPath);
415+
throw error;
416+
}
417+
}

‎src/server/startup-action-control.ts‎

Lines changed: 58 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -12,30 +12,58 @@ let activeInstall: StartupInstallAction | null = null;
1212

1313
const INSTALL_DETAIL_LIMIT = 2_000;
1414

15+
type FinalizeFn = typeof finalizeWindowsSchedulerServiceRegistration;
16+
let finalizeImpl: FinalizeFn = finalizeWindowsSchedulerServiceRegistration;
17+
18+
/** Test-only seam so elevation retry tests do not mock.module the service package. */
19+
export function setStartupInstallFinalizeForTests(next: FinalizeFn | null): void {
20+
finalizeImpl = next ?? finalizeWindowsSchedulerServiceRegistration;
21+
}
22+
1523
export function startupInstallArgv(action: StartupInstallAction): string[] {
1624
return action === "install-service"
1725
? ["service", "install"]
1826
: ["codex-shim", "install"];
1927
}
2028

29+
export interface CliInstallFailure {
30+
/** Machine marker such as OCX_ERROR_CODE=..., when present in any stream. */
31+
code: string | null;
32+
stdout: string;
33+
stderr: string;
34+
message: string;
35+
/** Bounded user-facing diagnostic (may append the marker if truncated away). */
36+
detail: string;
37+
}
38+
39+
function extractOcxErrorCode(text: string): string | null {
40+
const match = text.match(/OCX_ERROR_CODE=[A-Z0-9_]+/);
41+
return match ? match[0] : null;
42+
}
43+
2144
/**
22-
* Build the CLI failure text used for dashboard errors and elevation detection.
23-
* Combines stderr and stdout so a retry marker on either stream is preserved,
24-
* and caps length so API responses stay bounded.
45+
* Classify a CLI install failure, keeping the machine marker separate from the
46+
* truncated user-facing diagnostic.
2547
*/
26-
export function installFailureDetail(stdout: string, stderr: string, error: Error): string {
27-
const combined = [stderr.trim(), stdout.trim()].filter(Boolean).join("\n");
28-
const detail = combined || error.message;
29-
if (detail.length <= INSTALL_DETAIL_LIMIT) return detail;
30-
const truncated = detail.slice(0, INSTALL_DETAIL_LIMIT);
31-
// Keep the structured elevation marker even when truncating a large dump.
32-
if (
33-
detail.includes(WINDOWS_SCHTASKS_CREATE_ACCESS_DENIED_MARKER)
34-
&& !truncated.includes(WINDOWS_SCHTASKS_CREATE_ACCESS_DENIED_MARKER)
35-
) {
36-
return `${truncated}\n${WINDOWS_SCHTASKS_CREATE_ACCESS_DENIED_MARKER}… (truncated)`;
48+
export function classifyCliInstallFailure(stdout: string, stderr: string, error: Error): CliInstallFailure {
49+
const stdoutText = stdout.trim();
50+
const stderrText = stderr.trim();
51+
const message = error.message.trim();
52+
const combined = [stderrText, stdoutText, message].filter(Boolean).join("\n");
53+
const code = extractOcxErrorCode(combined);
54+
let detail = combined || message;
55+
if (detail.length > INSTALL_DETAIL_LIMIT) {
56+
const truncated = detail.slice(0, INSTALL_DETAIL_LIMIT);
57+
detail = code && !truncated.includes(code)
58+
? `${truncated}\n${code}… (truncated)`
59+
: `${truncated}… (truncated)`;
3760
}
38-
return `${truncated}… (truncated)`;
61+
return { code, stdout: stdoutText, stderr: stderrText, message, detail };
62+
}
63+
64+
/** @deprecated Prefer classifyCliInstallFailure; kept for existing tests. */
65+
export function installFailureDetail(stdout: string, stderr: string, error: Error): string {
66+
return classifyCliInstallFailure(stdout, stderr, error).detail;
3967
}
4068

4169
function runCliInstall(action: StartupInstallAction): Promise<{ stdout: string; stderr: string }> {
@@ -51,14 +79,24 @@ function runCliInstall(action: StartupInstallAction): Promise<{ stdout: string;
5179
maxBuffer: 256 * 1024,
5280
}, (error, stdout, stderr) => {
5381
if (error) {
54-
reject(new Error(installFailureDetail(stdout, stderr, error)));
82+
const failure = classifyCliInstallFailure(stdout, stderr, error);
83+
reject(Object.assign(new Error(failure.detail), { ocxInstallFailure: failure }));
5584
return;
5685
}
5786
resolve({ stdout, stderr });
5887
});
5988
});
6089
}
6190

91+
function installFailureCode(error: unknown): string | null {
92+
if (error && typeof error === "object" && "ocxInstallFailure" in error) {
93+
const failure = (error as { ocxInstallFailure?: CliInstallFailure }).ocxInstallFailure;
94+
if (failure?.code) return failure.code;
95+
}
96+
const detail = error instanceof Error ? error.message : String(error);
97+
return extractOcxErrorCode(detail);
98+
}
99+
62100
/** Execute the existing fixed CLI installer outside the proxy event loop. */
63101
export function runStartupInstallAction(action: StartupInstallAction): Promise<{ message: string }> {
64102
if (activeInstall) return Promise.reject(new Error(`Another startup installation is already running: ${activeInstall}`));
@@ -67,17 +105,17 @@ export function runStartupInstallAction(action: StartupInstallAction): Promise<{
67105
try {
68106
await runCliInstall(action);
69107
} catch (error) {
108+
const code = installFailureCode(error);
70109
const detail = error instanceof Error ? error.message : String(error);
71110
// Elevate only for a structured Task Scheduler /create access denial — never for
72111
// WinSW removal, asset writes, or generic permission errors.
73-
// finalizeWindowsSchedulerServiceRegistration verifies conflict-free state, rolls
74-
// back on failure, and writes install state only after checks pass.
75112
if (
76113
action === "install-service"
77114
&& process.platform === "win32"
78-
&& isWindowsSchtasksCreateAccessDenied(detail)
115+
&& (code === WINDOWS_SCHTASKS_CREATE_ACCESS_DENIED_MARKER
116+
|| isWindowsSchtasksCreateAccessDenied(detail))
79117
) {
80-
await finalizeWindowsSchedulerServiceRegistration();
118+
await finalizeImpl();
81119
} else {
82120
throw error;
83121
}

0 commit comments

Comments
 (0)