Skip to content

Commit 681c882

Browse files
committed
fix(windows): preflight scheduler registration before teardown
1 parent 87e3ff9 commit 681c882

6 files changed

Lines changed: 408 additions & 4 deletions

File tree

‎docs-site/src/content/docs/reference/cli/lifecycle.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -282,6 +282,13 @@ automatically. If that fallback cannot determine the token state, it retains the
282282
error. Foreign tasks and operations can never emit the automatic-elevation marker. Approve the
283283
dashboard UAC prompt or rerun `ocx service install` in an elevated PowerShell window.
284284

285+
For a fresh install where the OpenCodex scheduler task is confirmed absent, UAC approval now
286+
happens before the installer stops any existing proxy. The task is registered without being run;
287+
only after registration succeeds does OpenCodex stop the old listener, publish the service assets,
288+
and start the scheduled task. Cancelling or denying UAC therefore leaves the working proxy and its
289+
Codex routing in place. Existing or conflicting scheduler registrations continue to fail closed
290+
rather than being deleted as an unsafe best-effort rollback.
291+
285292
### `ocx codex-shim <install|status|uninstall|remove>`
286293

287294
Wrap a script-based `codex` launcher on PATH with a lightweight autostart script. Real `codex.exe`

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

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -164,10 +164,17 @@ function runCliInstall(
164164
const cli = join(import.meta.dir, "..", "cli", "index.ts");
165165
const argv = [cli, ...startupInstallArgv(action, options)];
166166
return new Promise((resolve, reject) => {
167+
const timeout = process.platform === "win32" && action === "install-service"
168+
? 0
169+
: 60_000;
167170
execFile(bun, argv, {
168171
encoding: "utf8",
169172
env: process.env,
170-
timeout: 60_000,
173+
// A fresh Windows scheduler install now owns its UAC prompt inside this CLI
174+
// transaction. Killing only the CLI at 60s can orphan its elevated schtasks child,
175+
// which may register the task after the Dashboard has reported failure. Keep the
176+
// async request/attempt lock alive until Windows returns approval or cancellation.
177+
timeout,
171178
windowsHide: true,
172179
maxBuffer: 256 * 1024,
173180
}, (error, stdout, stderr) => {

‎src/service.ts‎

Lines changed: 173 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ import {
2929
runWindowsElevated,
3030
toWindowsSchtasksError,
3131
WindowsElevationError,
32+
WindowsSchtasksError,
3233
type ElevatedSchedulerOutcome,
3334
type ElevatedSchtasksCreateAndRunExecution,
3435
type ElevatedSchtasksCreateAndRunResult,
@@ -1506,6 +1507,11 @@ export function buildWindowsSchtasksCreateArgs(script = windowsServiceScriptPath
15061507
return ["/create", "/tn", TASK, "/xml", xml, "/f"];
15071508
}
15081509

1510+
/** Build the fixed scheduler-create command from an explicit staged XML document. */
1511+
export function buildWindowsSchtasksCreateArgsForXml(xml: string): string[] {
1512+
return ["/create", "/tn", TASK, "/xml", xml, "/f"];
1513+
}
1514+
15091515
/**
15101516
* VBS launcher that starts the batch wrapper with a hidden window (style 0).
15111517
* bWaitOnReturn=True keeps wscript.exe resident for the wrapper's lifetime so the
@@ -1823,6 +1829,84 @@ function writeWindowsSchedulerAssets(): void {
18231829
writeServiceAssetWithRetry(windowsTaskXmlPath(), `\uFEFF${buildWindowsTaskXml(script)}`, "utf16le");
18241830
}
18251831

1832+
function stageWindowsSchedulerRegistrationXml(): string {
1833+
if (!existsSync(getConfigDir())) mkdirSync(getConfigDir(), { recursive: true, mode: 0o700 });
1834+
const path = join(getConfigDir(), `.opencodex-service-task.${randomUUID()}.xml`);
1835+
// This document points at the canonical launcher but does not publish or rewrite that
1836+
// launcher. UAC can therefore be refused while the current proxy still owns its port.
1837+
writeServiceAssetWithRetry(
1838+
path,
1839+
`\uFEFF${buildWindowsTaskXml(windowsServiceScriptPath(), windowsLauncherVbsPath())}`,
1840+
"utf16le",
1841+
);
1842+
return path;
1843+
}
1844+
1845+
export interface FreshWindowsSchedulerRegistrationDeps {
1846+
create?: (args: string[]) => void;
1847+
elevate?: (args: string[]) => Promise<void>;
1848+
probe?: () => WindowsSchedulerTaskProbe;
1849+
queryXml?: () => string;
1850+
rollback?: () => Promise<string | null>;
1851+
}
1852+
1853+
export async function registerFreshWindowsSchedulerTask(
1854+
xmlPath: string,
1855+
deps: FreshWindowsSchedulerRegistrationDeps = {},
1856+
): Promise<void> {
1857+
const args = buildWindowsSchtasksCreateArgsForXml(xmlPath);
1858+
try {
1859+
(deps.create ?? schtasks)(args);
1860+
} catch (error) {
1861+
if (
1862+
!(error instanceof WindowsSchtasksError)
1863+
|| error.operation !== "create"
1864+
|| error.reason !== "access-denied"
1865+
) {
1866+
throw error;
1867+
}
1868+
// The elevated command is still the fixed trusted schtasks executable plus the
1869+
// owned create shape. It registers only; the task is not run until cleanup commits.
1870+
await (deps.elevate ?? elevateSchtasks)(args);
1871+
}
1872+
1873+
const rollbackTask = deps.rollback ?? (() => rollbackElevatedSchedulerTask(TASK));
1874+
const probe = (deps.probe ?? (() => probeWindowsSchedulerTask(TASK)))();
1875+
if (probe.status === "absent") {
1876+
throw new Error("Task Scheduler reported success, but the new registration is absent; no service cleanup was started.");
1877+
}
1878+
if (probe.status === "unknown") {
1879+
const rollback = await rollbackTask();
1880+
throw new Error(
1881+
`Task Scheduler registration was not verifiably present after create (${probe.detail}).`
1882+
+ (rollback ? ` Cleanup also failed: ${rollback}` : " The unverified registration was rolled back."),
1883+
);
1884+
}
1885+
1886+
let registeredXml = "";
1887+
let queryDetail: string | null = null;
1888+
try {
1889+
registeredXml = (deps.queryXml ?? (() => querySchtasks(["/query", "/tn", TASK, "/xml"])))();
1890+
} catch (error) {
1891+
queryDetail = error instanceof Error ? error.message : String(error);
1892+
}
1893+
if (!registeredXml.trim()) {
1894+
const rollback = await rollbackTask();
1895+
throw new Error(
1896+
"Task Scheduler registration was created, but its live XML could not be verified."
1897+
+ (queryDetail ? ` Query failed: ${queryDetail}` : " The query returned an empty document.")
1898+
+ (rollback ? ` Cleanup also failed: ${rollback}` : " The unverified registration was rolled back."),
1899+
);
1900+
}
1901+
if (!windowsTaskRegistrationHealthy(registeredXml)) {
1902+
const rollback = await rollbackTask();
1903+
throw new Error(
1904+
"Task Scheduler registration was created but failed the OpenCodex action/trigger verification."
1905+
+ (rollback ? ` Cleanup also failed: ${rollback}` : " The invalid registration was rolled back."),
1906+
);
1907+
}
1908+
}
1909+
18261910
function installWindows(): void {
18271911
recordOwnedConfigPath(getConfigDir(), serviceStatePath());
18281912
// Transactional backend switch: installing the scheduler backend removes a native
@@ -2437,6 +2521,82 @@ export async function installServiceSafely(
24372521
await install();
24382522
}
24392523

2524+
export interface FreshWindowsSchedulerInstallDeps {
2525+
stageRegistrationXml?: () => string;
2526+
register?: (xmlPath: string) => Promise<void>;
2527+
prepare?: () => Promise<void>;
2528+
publishAssets?: () => void;
2529+
runTask?: () => void;
2530+
writeState?: () => void;
2531+
rollbackTask?: () => Promise<string | null>;
2532+
removeStagedXml?: (xmlPath: string) => void;
2533+
}
2534+
2535+
/**
2536+
* Fresh Windows scheduler install with UAC before the destructive commit.
2537+
*
2538+
* The registration is created but never run before `prepare`: UAC cancellation and
2539+
* create failure therefore cannot stop the existing proxy or trigger its native-routing
2540+
* cleanup. This path is used only after Task Scheduler absence was proved, so rollback
2541+
* can delete the exact registration this attempt created without touching prior state.
2542+
*/
2543+
export async function installFreshWindowsSchedulerSafely(
2544+
deps: FreshWindowsSchedulerInstallDeps = {},
2545+
): Promise<void> {
2546+
const stage = deps.stageRegistrationXml ?? stageWindowsSchedulerRegistrationXml;
2547+
const register = deps.register ?? registerFreshWindowsSchedulerTask;
2548+
const prepare = deps.prepare ?? (() => prepareServiceInstall("scheduler"));
2549+
const publishAssets = deps.publishAssets ?? writeWindowsSchedulerAssets;
2550+
const runTask = deps.runTask ?? startWindows;
2551+
const writeState = deps.writeState ?? (() => writeServiceInstallState("scheduler"));
2552+
const rollbackTask = deps.rollbackTask ?? (() => rollbackElevatedSchedulerTask(TASK));
2553+
const removeStagedXml = deps.removeStagedXml ?? ((path: string) => {
2554+
if (existsSync(path)) unlinkSync(path);
2555+
});
2556+
2557+
let stagedXml: string | null = null;
2558+
let registered = false;
2559+
let started = false;
2560+
try {
2561+
stagedXml = stage();
2562+
await register(stagedXml);
2563+
registered = true;
2564+
2565+
// The destructive boundary begins only after Task Scheduler accepted the definition.
2566+
await prepare();
2567+
publishAssets();
2568+
runTask();
2569+
started = true;
2570+
writeState();
2571+
} catch (error) {
2572+
const detail = error instanceof Error ? error.message : String(error);
2573+
if (registered && !started) {
2574+
const rollback = await rollbackTask();
2575+
throw new Error(
2576+
`${detail}\n`
2577+
+ (rollback
2578+
? `The new Task Scheduler registration may remain: ${rollback}`
2579+
: "The new Task Scheduler registration was rolled back. The previous proxy/routing state was not assumed restored."),
2580+
);
2581+
}
2582+
if (started) {
2583+
throw new Error(
2584+
`${detail}\nThe scheduler task started, but install state was not published. `
2585+
+ "The task was left in place; inspect `ocx service status` before retrying.",
2586+
);
2587+
}
2588+
throw error;
2589+
} finally {
2590+
if (stagedXml) {
2591+
try { removeStagedXml(stagedXml); } catch (error) {
2592+
console.error(
2593+
`⚠️ Failed to remove temporary Task Scheduler XML ${stagedXml}: ${error instanceof Error ? error.message : String(error)}`,
2594+
);
2595+
}
2596+
}
2597+
}
2598+
}
2599+
24402600
/**
24412601
* If a service is installed, stop it so the process manager doesn't respawn after `ocx stop`.
24422602
* Returns true if a service was found and stopped.
@@ -2812,7 +2972,19 @@ export async function serviceCommand(...args: (string | undefined)[]): Promise<v
28122972
// restart-loops on EADDRINUSE, and the old standalone process makes the install
28132973
// verification report a false success.
28142974
try {
2815-
await installServiceSafely(backend, ops.install);
2975+
if (process.platform === "win32" && backend === "scheduler") {
2976+
const scheduler = probeWindowsSchedulerTask(TASK);
2977+
if (scheduler.status === "unknown") {
2978+
throw new Error(`Task Scheduler state could not be verified before install: ${scheduler.detail}`);
2979+
}
2980+
if (scheduler.status === "absent") {
2981+
await installFreshWindowsSchedulerSafely();
2982+
} else {
2983+
await installServiceSafely(backend, ops.install);
2984+
}
2985+
} else {
2986+
await installServiceSafely(backend, ops.install);
2987+
}
28162988
} catch (error) {
28172989
console.error(`❌ Service install cleanup failed: ${error instanceof Error ? error.message : String(error)}`);
28182990
process.exitCode = 1;

‎structure/05_gui-and-management-api.md‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -197,6 +197,29 @@ the effective-token elevation probe may classify it as access denied only when t
197197
to be non-elevated. An unavailable probe remains `other` and cannot trigger UAC. Query, run, delete,
198198
native-service, file-write, and foreign task failures never use this fallback.
199199

200+
For a fresh scheduler install whose task is proven absent, registration is the non-destructive
201+
first phase. OpenCodex writes a unique temporary XML definition and asks Task Scheduler to create
202+
the owned task without running it. Only after that succeeds may service-manager cleanup stop the
203+
existing proxy, publish the canonical scheduler assets, run the task, and write install state.
204+
UAC cancellation or create failure removes the temporary XML before any manager/proxy stop, so the
205+
working proxy's shutdown cleanup cannot strip Codex routing merely because elevation was refused.
206+
The Dashboard does not apply its ordinary 60-second child timeout to this Windows service command:
207+
killing only the CLI could orphan the already-launched elevated child, which might register a task
208+
after the UI reported failure. The asynchronous request and install-attempt lock remain pending
209+
until Windows returns approval or cancellation; other proxy requests keep running normally.
210+
Existing or conflicting registrations stay on the older fail-closed path because deleting or
211+
replacing them cannot be called a rollback without an exact prior-registration snapshot.
212+
213+
```text
214+
[Decision Log]
215+
- 목적과 의도: Keep a refused fresh Windows service install from stopping a working proxy and removing managed Codex routing.
216+
- 기존 구현 및 제약 조건: The generic installer stopped service managers and the standalone proxy before the first scheduler create attempt; the Dashboard UAC path depended on assets produced by that already-destructive failure.
217+
- 검토한 주요 대안: Reject every non-elevated caller up front, restart and re-inject after failure, snapshot every runtime/config artifact for rollback, or separate registration approval from the destructive commit.
218+
- 선택한 방식: When scheduler absence is proven, create but do not run the owned registration from a temporary XML first; cleanup and canonical asset publication begin only after registration succeeds.
219+
- 다른 대안 대신 이 방식을 선택한 이유: An early rejection breaks Dashboard UAC, while a best-effort restart cannot prove that manager, proxy, and routing state were restored. The two-phase boundary makes denial/cancellation a real pre-commit failure.
220+
- 장점, 단점 및 영향: Fresh-install UAC failure preserves the live proxy and routing. Failures after registration remain explicit partial-install cases, and existing/conflicting scheduler recovery remains conservative until exact prior-state restoration is available.
221+
```
222+
200223
```text
201224
[Decision Log]
202225
- 목적과 의도: Make Windows scheduler installation recovery work on non-English systems without broadening the commands that may request UAC.

0 commit comments

Comments
 (0)