Skip to content

Commit 9f406cf

Browse files
committed
fix(update): harden transactional swap per adversarial review
- verify the bundled Bun binary by size (>=10MB), not just its package.json, so the boot probe can never call a Bun-less tree healthy and reap the only backup - bounded EPERM/EBUSY/EACCES rename retry for the Windows AV/indexer class - staging/backup mkdir failures return phase errors with live untouched; an unexpected throw now reports and stops instead of falling back to the destructive in-place install - the Windows service wrapper (outside the package tree) restores the newest .ocx-backup-* sibling before declaring the install incomplete — the exact power-loss window the in-launcher probe cannot reach
1 parent 1ac6865 commit 9f406cf

5 files changed

Lines changed: 106 additions & 19 deletions

File tree

‎bin/ocx.mjs‎

Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -304,15 +304,13 @@ function runNpmSelfUpdate() {
304304
res = { status: 1 };
305305
}
306306
} catch (error) {
307-
// Transactional machinery itself failed (e.g. exotic install layout): legacy path.
308-
console.warn(`opencodex: transactional update unavailable (${error?.message ?? error}); falling back to in-place npm install.`);
309-
console.log(`$ npm install -g ${PKG}@${tag}`);
310-
res = spawnSync(installInvocation.file, installInvocation.args, {
311-
stdio: "inherit",
312-
timeout: 180000,
313-
windowsHide: true,
314-
...installInvocation.options,
315-
});
307+
// An unexpected throw means we cannot prove the live tree is untouched, so the
308+
// legacy in-place install (which deletes live first) is exactly the wrong rescue —
309+
// it recreates the #1849 destruction path. Report and stop; the boot probe and the
310+
// recovery marker cover the swap-window states.
311+
console.error(`opencodex: transactional update failed unexpectedly (${error?.message ?? error}). ` +
312+
"The live install was not knowingly modified; run 'ocx update' again or reinstall with npm install -g.");
313+
res = { status: 1 };
316314
}
317315
if (res.status === 0) {
318316
console.log(`\nUpdated${latest ? ` to v${latest}` : ""}.`);

‎src/service.ts‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1535,6 +1535,9 @@ export function buildWindowsServiceScript(entry = cliEntry(), port = resolveServ
15351535
windowsBatchSet("OCX_SERVICE_LOG", serviceLogPath(), "path"),
15361536
windowsBatchSet("OCX_BUN", bun, "path"),
15371537
windowsBatchSet("OCX_CLI", cli, "path"),
1538+
// Package root for the transactional-update restore path (#1942): cli is
1539+
// <pkg>\src\cli\index.ts, so the package dir is three levels up.
1540+
'for %%I in ("%OCX_CLI%\\..\\..\\..") do set "OCX_PKG_DIR=%%~fI"',
15381541
'if exist "%OCX_API_TOKEN_FILE%" (',
15391542
' set /p OPENCODEX_API_AUTH_TOKEN=<"%OCX_API_TOKEN_FILE%"',
15401543
")",
@@ -1547,10 +1550,16 @@ export function buildWindowsServiceScript(entry = cliEntry(), port = resolveServ
15471550
'>>"%OCX_SERVICE_LOG%" echo codex_home="%CODEX_HOME%"',
15481551
'>>"%OCX_SERVICE_LOG%" echo token_file="%OCX_API_TOKEN_FILE%"',
15491552
'if not exist "%OCX_BUN%" (',
1553+
" call :restore_backup",
1554+
")",
1555+
'if not exist "%OCX_BUN%" (',
15501556
' >>"%OCX_SERVICE_LOG%" echo [%DATE% %TIME%] installation is incomplete: bundled Bun is missing; reinstall opencodex, then run ocx service repair',
15511557
" exit /b 3",
15521558
")",
15531559
'if not exist "%OCX_CLI%" (',
1560+
" call :restore_backup",
1561+
")",
1562+
'if not exist "%OCX_CLI%" (',
15541563
' >>"%OCX_SERVICE_LOG%" echo [%DATE% %TIME%] installation is incomplete: CLI entry is missing; reinstall opencodex, then run ocx service repair',
15551564
" exit /b 3",
15561565
")",
@@ -1563,6 +1572,26 @@ export function buildWindowsServiceScript(entry = cliEntry(), port = resolveServ
15631572
" goto loop",
15641573
")",
15651574
"endlocal",
1575+
"goto :eof",
1576+
"",
1577+
// #1942/#1849: a power loss mid-swap leaves the live package dir missing/broken and
1578+
// a sibling .ocx-backup-* holding the previous version. This wrapper lives OUTSIDE
1579+
// the package tree, so it can restore when the launcher itself is gone — the exact
1580+
// window the in-launcher boot probe cannot reach.
1581+
":restore_backup",
1582+
'>>"%OCX_SERVICE_LOG%" echo [%DATE% %TIME%] install incomplete - looking for a transactional-update backup to restore',
1583+
'for /f "delims=" %%B in (\'dir /b /ad /o-n "%OCX_PKG_DIR%\\..\\.ocx-backup-*" 2^>nul\') do (',
1584+
' if exist "%OCX_PKG_DIR%\\..\\%%B\\opencodex\\package.json" (',
1585+
' if exist "%OCX_PKG_DIR%" rmdir /s /q "%OCX_PKG_DIR%" 2>nul',
1586+
' move "%OCX_PKG_DIR%\\..\\%%B\\opencodex" "%OCX_PKG_DIR%" >nul 2>&1',
1587+
' if exist "%OCX_PKG_DIR%\\package.json" (',
1588+
' >>"%OCX_SERVICE_LOG%" echo [%DATE% %TIME%] restored previous install from %%B',
1589+
" goto :eof",
1590+
" )",
1591+
" )",
1592+
")",
1593+
'>>"%OCX_SERVICE_LOG%" echo [%DATE% %TIME%] no restorable backup found',
1594+
"goto :eof",
15661595
].filter((line): line is string => Boolean(line));
15671596
return `${lines.join("\r\n")}\r\n`;
15681597
}

‎src/update/transactional-install.mjs‎

Lines changed: 63 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,16 @@ export function verifyInstallTree(packageDir, expectedVersion) {
3939
} catch {
4040
failures.push("bin/ocx.mjs absent");
4141
}
42+
// The bundled Bun binary is the load-bearing artifact: without it the launcher exits
43+
// before serving anything, and a boot probe that called this tree healthy would reap
44+
// the only backup (review High 3). Size-gate the real binary, not just its package.json.
45+
const bunPkgDir = join(packageDir, "node_modules", "bun");
46+
if (existsSync(bunPkgDir)) {
47+
const bunBinary = findLargestFile(bunPkgDir);
48+
if (!bunBinary || bunBinary.size < 10 * 1024 * 1024) {
49+
failures.push("bundled Bun binary missing or truncated (< 10MB)");
50+
}
51+
}
4252
// Sentinel direct deps: each must have an intact package.json. The bundled Bun dep is
4353
// the load-bearing one — without it the launcher cannot start the proxy at all.
4454
const deps = Object.keys(pkg.dependencies ?? {});
@@ -56,6 +66,42 @@ function stampedName(prefix) {
5666
return prefix + "-" + new Date().toISOString().replace(/[:.]/g, "-");
5767
}
5868

69+
/** Largest regular file under a directory tree (bounded depth) — locates the Bun binary. */
70+
function findLargestFile(root, depth = 3) {
71+
let best;
72+
let names = [];
73+
try { names = readdirSync(root); } catch { return undefined; }
74+
for (const name of names) {
75+
const full = join(root, name);
76+
let st;
77+
try { st = statSync(full); } catch { continue; }
78+
if (st.isFile()) {
79+
if (!best || st.size > best.size) best = { path: full, size: st.size };
80+
} else if (st.isDirectory() && depth > 0) {
81+
const sub = findLargestFile(full, depth - 1);
82+
if (sub && (!best || sub.size > best.size)) best = sub;
83+
}
84+
}
85+
return best;
86+
}
87+
88+
/** Bounded Windows-class rename retry: EPERM/EBUSY/EACCES from AV/indexers clears in ms. */
89+
function renameWithRetry(rename, from, to, attempts = 5) {
90+
for (let attempt = 0; ; attempt += 1) {
91+
try {
92+
rename(from, to);
93+
return;
94+
} catch (error) {
95+
const code = error?.code;
96+
const retryable = code === "EPERM" || code === "EBUSY" || code === "EACCES";
97+
if (!retryable || attempt >= attempts - 1) throw error;
98+
// Synchronous bounded backoff (launcher context has no async loop here).
99+
const until = Date.now() + 100 * (attempt + 1);
100+
while (Date.now() < until) { /* spin briefly; total worst case ~1.5s */ }
101+
}
102+
}
103+
}
104+
59105
function recoveryMarkerPath(scopeDir) {
60106
return join(scopeDir, ".ocx-recovery.json");
61107
}
@@ -111,8 +157,14 @@ export function transactionalNpmUpdate({
111157
const stagedPackage = join(stageRoot, "node_modules", ...pkgName.split("/"));
112158

113159
// D1: stage to the side. --prefix keeps npm entirely inside stageRoot; the live tree
114-
// and the npm bin shims are untouched until the swap.
115-
mkdirSync(stageRoot, { recursive: true });
160+
// and the npm bin shims are untouched until the swap. A failure HERE (mkdir EACCES,
161+
// ENOSPC) must NOT fall back to the destructive legacy install (review High 4): the
162+
// caller sees a normal phase failure with live untouched.
163+
try {
164+
mkdirSync(stageRoot, { recursive: true });
165+
} catch (error) {
166+
return { ok: false, phase: "stage", error: "could not create staging directory: " + (error?.message ?? String(error)) };
167+
}
116168
const spec = pkgName + "@" + (targetVersion || tag);
117169
log("Staging " + spec + " into " + stageRoot);
118170
const install = runNpm(["install", "--prefix", stageRoot, "--no-audit", "--no-fund", spec]);
@@ -131,20 +183,25 @@ export function transactionalNpmUpdate({
131183
// D3: swap. live -> backup, stage -> live, re-verify live, rollback on failure.
132184
const backupRoot = join(scopeDir, stampedName(".ocx-backup"));
133185
const backupPackage = join(backupRoot, "opencodex");
134-
mkdirSync(backupRoot, { recursive: true });
135186
try {
136-
rename(packageDir, backupPackage);
187+
mkdirSync(backupRoot, { recursive: true });
188+
} catch (error) {
189+
try { rmSync(stageRoot, { recursive: true, force: true }); } catch { /* best effort */ }
190+
return { ok: false, phase: "swap-backup", error: "could not create backup directory: " + (error?.message ?? String(error)) };
191+
}
192+
try {
193+
renameWithRetry(rename, packageDir, backupPackage);
137194
} catch (error) {
138195
try { rmSync(stageRoot, { recursive: true, force: true }); } catch { /* best effort */ }
139196
try { rmSync(backupRoot, { recursive: true, force: true }); } catch { /* best effort */ }
140197
return { ok: false, phase: "swap-backup", error: "could not move live tree aside: " + (error?.message ?? String(error)) };
141198
}
142199
try {
143-
rename(stagedPackage, packageDir);
200+
renameWithRetry(rename, stagedPackage, packageDir);
144201
} catch (error) {
145202
// Rollback: reverse the first rename. Double fault leaves the recovery marker.
146203
try {
147-
rename(backupPackage, packageDir);
204+
renameWithRetry(rename, backupPackage, packageDir);
148205
try { rmSync(stageRoot, { recursive: true, force: true }); } catch { /* best effort */ }
149206
try { rmSync(backupRoot, { recursive: true, force: true }); } catch { /* best effort */ }
150207
return { ok: false, phase: "swap-live", rolledBack: true, error: "could not place staged tree: " + (error?.message ?? String(error)) };
@@ -186,4 +243,3 @@ export function transactionalNpmUpdate({
186243
try { rmSync(stageRoot, { recursive: true, force: true }); } catch { /* best effort */ }
187244
return { ok: true, phase: "done", backup: backupPackage };
188245
}
189-

‎tests/service.test.ts‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -543,8 +543,11 @@ describe("Windows service task", () => {
543543
expect(script).toContain("installation is incomplete: bundled Bun is missing");
544544
expect(script).toContain("installation is incomplete: CLI entry is missing");
545545
expect(script.match(/exit \/b 3/g)).toHaveLength(2);
546-
// `goto loop` re-enters both checks before another child spawn.
547-
expect(script.slice(loopAt, launchAt).match(/if not exist/g)).toHaveLength(2);
546+
// #1942: each missing-artifact branch first attempts a transactional-update backup
547+
// restore, then re-checks before the hard stop — 2 artifacts x (probe + recheck).
548+
expect(script.slice(loopAt, launchAt).match(/if not exist/g)).toHaveLength(4);
549+
expect(script).toContain(":restore_backup");
550+
expect(script).toContain(".ocx-backup-*");
548551
});
549552

550553
test("rewrites profile-relative paths to env indirection so non-ASCII usernames survive OEM-codepage batch parsing", () => {

‎tests/update-transactional.test.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,8 @@ function writeTree(packageDir: string, version: string): void {
2323
}));
2424
writeFileSync(join(packageDir, "bin", "ocx.mjs"), "#!/usr/bin/env node\n" + "x".repeat(2048));
2525
writeFileSync(join(packageDir, "node_modules", "bun", "package.json"), JSON.stringify({ name: "bun" }));
26+
// The manifest size-gates the real Bun binary (>= 10MB); give the fixture one.
27+
writeFileSync(join(packageDir, "node_modules", "bun", "bun.exe"), Buffer.alloc(10 * 1024 * 1024 + 1024));
2628
writeFileSync(join(packageDir, "node_modules", "zod", "package.json"), JSON.stringify({ name: "zod" }));
2729
}
2830

@@ -170,4 +172,3 @@ describe("#1942 transactional update", () => {
170172
expect(existsSync(backupRoot)).toBe(false);
171173
});
172174
});
173-

0 commit comments

Comments
 (0)