Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions src/service/windows-taskxml.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { TASK, windowsServiceScriptPath, windowsLauncherVbsPath, windowsTaskXmlP
import { windowsWscript } from "./windows-scheduler";
import { join } from "node:path";
import { BUN_RUNTIME_PATH_ENV, BUN_RUNTIME_SOURCE_ENV } from "../lib/bun-runtime";
import { REAL_BUN_MIN_BYTES } from "../lib/bun-binary-validator.mjs";
import { serviceApiTokenFilePath } from "../lib/service-secrets";
import { windowsEnvIndirectBatchPathList, windowsEnvIndirectBatchValue } from "../lib/win-paths";
import { cachedCurrentWindowsIdentity, resolveCurrentWindowsPrincipal, WINDOWS_PRINCIPAL_LOOKUP_TIMEOUT_MS } from "../lib/windows-user-principal";
Expand Down Expand Up @@ -54,6 +55,10 @@ function taskXmlRunLevelAcceptable(principal: string): boolean {
return value === "leastprivilege" || value === "highestavailable";
}

/**
* Batch wrapper the scheduled task runs: restarts the proxy on exit, restores a transactional-update
* backup when the install is gone, and waits while bundled Bun is still npm's placeholder.
*/
export function buildWindowsServiceScript(
entry = cliEntry(),
port = resolveServiceListenPort(),
Expand Down Expand Up @@ -103,6 +108,15 @@ export function buildWindowsServiceScript(
")",
// Locale dates can contain parentheses. Keep timestamp expansion outside blocks.
'if not exist "%OCX_BUN%" goto bun_missing',
// An in-place npm install extracts the bun package's tiny placeholder before its postinstall
// swaps in the real binary. Executing it fails with exit 216 and, in an interactive session,
// a modal "Unsupported 16-Bit Application" dialog that blocks this loop until dismissed.
// The install can also remove the file between the exist check and this read; an empty size
// would turn the comparison into a syntax error that ends the wrapper.
'set "OCX_BUN_BYTES="',
'for %%F in ("%OCX_BUN%") do set "OCX_BUN_BYTES=%%~zF"',
'if not defined OCX_BUN_BYTES goto bun_not_ready',
`if %OCX_BUN_BYTES% LSS ${REAL_BUN_MIN_BYTES} goto bun_not_ready`,
cli ? 'if not exist "%OCX_CLI%" (' : null,
cli ? " call :restore_backup" : null,
cli ? ")" : null,
Expand All @@ -118,6 +132,10 @@ export function buildWindowsServiceScript(
":stopped",
"endlocal",
"exit /b 0",
":bun_not_ready",
'>>"%OCX_SERVICE_LOG%" echo [%DATE% %TIME%] bundled Bun is not ready (%OCX_BUN_BYTES% bytes, npm placeholder or mid-install); waiting for its postinstall, retrying in 5s - if this persists, reinstall opencodex with bun scripts allowed',
"ping -n 6 127.0.0.1 >nul",
"goto loop",
":bun_missing",
'>>"%OCX_SERVICE_LOG%" echo [%DATE% %TIME%] installation is incomplete: bundled Bun is missing; reinstall opencodex, then run ocx service repair',
"exit /b 3",
Expand Down
78 changes: 77 additions & 1 deletion tests/windows/windows-service-wrappers.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -211,7 +211,8 @@ for (const date of ["Wed 09/30/2026", "2026-09-30(수)", "2026/09/30 (水)"]) {
const cli = join(pkg, "src", "cli", "index.ts");
const log = join(dir, "service.log");
const backup = join(dir, ".ocx-backup-20260930 (test)!", "opencodex");
const child = '@echo off\r\necho FAKE-CHILD-STARTED\r\nexit /b 42\r\n';
// Pad past the real-Bun size gate with lines cmd never reaches after `exit /b`.
const child = '@echo off\r\necho FAKE-CHILD-STARTED\r\nexit /b 42\r\n' + "rem pad past the real-Bun size gate\r\n".repeat(40_000);
mkdirSync(join(pkg, "src", "cli"), { recursive: true });
if (scenario !== "missing bun" && scenario !== "restore bun" && scenario !== "empty backup" && scenario !== "standalone missing") writeFileSync(bun, child);
if (scenario !== "missing cli" && scenario !== "restore cli") writeFileSync(cli, "fixture");
Expand Down Expand Up @@ -253,3 +254,78 @@ for (const date of ["Wed 09/30/2026", "2026-09-30(수)", "2026/09/30 (水)"]) {
});
}
}

test.skipIf(process.platform !== "win32")("cmd waits out the npm Bun placeholder instead of executing it", async () => {
const { mkdtempSync, mkdirSync, writeFileSync, rmSync } = await import("node:fs");
const { tmpdir } = await import("node:os");
const { spawnSync } = await import("node:child_process");
const { buildWindowsServiceScript } = await import("../../src/service/windows-taskxml");
const dir = mkdtempSync(join(tmpdir(), "ocx-wrapper-placeholder-"));
try {
const pkg = join(dir, "package");
const bun = join(pkg, "bun.cmd");
const cli = join(pkg, "src", "cli", "index.ts");
const log = join(dir, "service.log");
mkdirSync(join(pkg, "src", "cli"), { recursive: true });
writeFileSync(cli, "fixture");
// An in-place npm install extracts bun/bin/bun.exe as a small placeholder that bun's
// postinstall replaces later; executing it exits 216 behind a modal 16-bit dialog.
writeFileSync(bun, "@echo off\r\necho PLACEHOLDER-EXECUTED\r\nexit /b 216\r\n");
writeFileSync(`${bun}.real`, '@echo off\r\necho FAKE-CHILD-STARTED\r\nexit /b 42\r\n' + "rem pad past the real-Bun size gate\r\n".repeat(40_000));
const batch = buildWindowsServiceScript({ bun, bunRuntimeSource: "bundled", cli }, 10100, []);
// The cooldown stands in for the postinstall finishing while the wrapper waits.
const body = batch.slice(batch.indexOf(":loop\r\n"))
.replace(/^"%OCX_BUN%" /m, 'call "%OCX_BUN%" ')
.replaceAll("ping -n 6 127.0.0.1 >nul", 'if exist "%OCX_BUN%.real" move /y "%OCX_BUN%.real" "%OCX_BUN%" >nul');
const file = join(dir, "wrapper.cmd");
writeFileSync(file, ["@echo off", "setlocal EnableExtensions DisableDelayedExpansion", 'set "ERRORLEVEL="',
`set "OCX_BUN=${bun}"`, `set "OCX_CLI=${cli}"`, `set "OCX_PKG_DIR=${pkg}"`,
`set "OCX_SERVICE_LOG=${log}"`, 'set "OCX_API_TOKEN_FILE=fixture"', body].join("\r\n"));
const result = spawnSync("cmd.exe", ["/d", "/c", file], { timeout: 10000, encoding: "utf8", env: { ...process.env, ERRORLEVEL: "42" } });
expect(result.error).toBeUndefined();
const output = readFileSync(log, "utf8");
expect(output).not.toContain("PLACEHOLDER-EXECUTED");
expect(output).toContain("bundled Bun is not ready (");
expect(output).toContain("FAKE-CHILD-STARTED");
expect(result.status).toBe(0);
} finally {
rmSync(dir, { recursive: true, force: true });
}
});

test.skipIf(process.platform !== "win32")("cmd waits when Bun disappears between the exist check and the size read", async () => {
const { mkdtempSync, mkdirSync, writeFileSync, rmSync } = await import("node:fs");
const { tmpdir } = await import("node:os");
const { spawnSync } = await import("node:child_process");
const { buildWindowsServiceScript } = await import("../../src/service/windows-taskxml");
const dir = mkdtempSync(join(tmpdir(), "ocx-wrapper-vanish-"));
try {
const pkg = join(dir, "package");
const bun = join(pkg, "bun.cmd");
const cli = join(pkg, "src", "cli", "index.ts");
const log = join(dir, "service.log");
mkdirSync(join(pkg, "src", "cli"), { recursive: true });
writeFileSync(cli, "fixture");
writeFileSync(`${bun}.real`, '@echo off\r\necho FAKE-CHILD-STARTED\r\nexit /b 42\r\n' + "rem pad past the real-Bun size gate\r\n".repeat(40_000));
const batch = buildWindowsServiceScript({ bun, bunRuntimeSource: "bundled", cli }, 10100, []);
// Neutralise the Bun exist guards so the size read itself meets the missing file, as it
// does when npm removes the package between those two lines.
const body = batch.slice(batch.indexOf(":loop\r\n"))
.replace('if not exist "%OCX_BUN%" (', "if 1==0 (")
.replace('if not exist "%OCX_BUN%" goto bun_missing', "rem exist guard removed")
.replace(/^"%OCX_BUN%" /m, 'call "%OCX_BUN%" ')
.replaceAll("ping -n 6 127.0.0.1 >nul", 'if exist "%OCX_BUN%.real" move /y "%OCX_BUN%.real" "%OCX_BUN%" >nul');
const file = join(dir, "wrapper.cmd");
writeFileSync(file, ["@echo off", "setlocal EnableExtensions DisableDelayedExpansion", 'set "ERRORLEVEL="',
`set "OCX_BUN=${bun}"`, `set "OCX_CLI=${cli}"`, `set "OCX_PKG_DIR=${pkg}"`,
`set "OCX_SERVICE_LOG=${log}"`, 'set "OCX_API_TOKEN_FILE=fixture"', body].join("\r\n"));
const result = spawnSync("cmd.exe", ["/d", "/c", file], { timeout: 10000, encoding: "utf8", env: { ...process.env, ERRORLEVEL: "42" } });
expect(result.error).toBeUndefined();
const output = readFileSync(log, "utf8");
expect(output).toContain("bundled Bun is not ready ( bytes");
expect(output).toContain("FAKE-CHILD-STARTED");
expect(result.status).toBe(0);
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
Loading