Skip to content

Commit 52920d3

Browse files
committed
fix: address issue #696
Fixes #696
1 parent be177ea commit 52920d3

3 files changed

Lines changed: 87 additions & 10 deletions

File tree

‎src/tray/windows.ts‎

Lines changed: 54 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -150,8 +150,16 @@ function quoteRunValue(value: string): string {
150150
return `\"${value}\"`;
151151
}
152152

153-
/** Command persisted under HKCU Run. Every value is an owned absolute package/home path. */
154-
export function buildWindowsTrayRunCommand(entry: WindowsTrayEntry, powershell = windowsPowerShellPath()): string {
153+
function installedTrayLauncherPath(): string {
154+
return join(getConfigDir(), "opencodex-tray.vbs");
155+
}
156+
157+
function quoteVbsPath(value: string): string {
158+
return value.replace(/\\/g, "\\\\").replace(/"/g, "\"\"");
159+
}
160+
161+
/** Full PowerShell invocation used by the owned VBS launcher (not written to HKCU Run). */
162+
export function buildWindowsTrayPowerShellCommand(entry: WindowsTrayEntry, powershell = windowsPowerShellPath()): string {
155163
return [
156164
quoteRunValue(powershell),
157165
"-NoLogo",
@@ -169,6 +177,27 @@ export function buildWindowsTrayRunCommand(entry: WindowsTrayEntry, powershell =
169177
].join(" ");
170178
}
171179

180+
/** Short HKCU Run command (must stay ≤260 chars under long Windows user/npm paths). */
181+
export function buildWindowsTrayRunCommand(entry: WindowsTrayEntry & { launcherPath: string }): string {
182+
const wscript = join(process.env.SystemRoot ?? "C:\\Windows", "System32", "wscript.exe");
183+
return `${quoteRunValue(wscript)} //B //NoLogo ${quoteRunValue(entry.launcherPath)}`;
184+
}
185+
186+
export function buildWindowsTrayLauncherScript(entry: WindowsTrayEntry, powershell = windowsPowerShellPath()): string {
187+
const command = buildWindowsTrayPowerShellCommand(entry, powershell);
188+
// VBS CreateObject("WScript.Shell").Run command, 0, False — hidden, non-blocking.
189+
return [
190+
"' OpenCodex owned tray launcher — do not edit by hand.",
191+
`CreateObject("WScript.Shell").Run "${quoteVbsPath(command)}", 0, False`,
192+
"",
193+
].join("\r\n");
194+
}
195+
196+
/** @deprecated Prefer buildWindowsTrayPowerShellCommand; kept for callers that still expect the long form. */
197+
export function buildWindowsTrayLegacyRunCommand(entry: WindowsTrayEntry, powershell = windowsPowerShellPath()): string {
198+
return buildWindowsTrayPowerShellCommand(entry, powershell);
199+
}
200+
172201
function readState(): WindowsTrayState | null {
173202
try {
174203
const state = JSON.parse(readFileSync(trayStatePath(), "utf8")) as Partial<WindowsTrayState>;
@@ -204,7 +233,11 @@ function replaceOwnedFile(path: string, contents: string | Buffer): void {
204233
}
205234
}
206235

207-
function writeState(entry: WindowsTrayEntry, runValue: string, runCommand: string): void {
236+
function writeState(
237+
entry: WindowsTrayEntry & { launcherPath: string },
238+
runValue: string,
239+
runCommand: string,
240+
): void {
208241
const path = trayStatePath();
209242
replaceOwnedFile(path, JSON.stringify({ version: TRAY_STATE_VERSION, ...entry, runValue, runCommand }, null, 2) + "\n");
210243
}
@@ -376,7 +409,8 @@ function trayStatusFrom(registered: string | null): WindowsTrayStatus {
376409
const running = heartbeatProcessAlive(heartbeat);
377410
const registrationOwned = state !== null
378411
&& registered === state.runCommand
379-
&& [state.bun, state.cli, state.script, ...installedTrayIconPaths()].every(path => existsSync(path));
412+
&& [state.bun, state.cli, state.script, ...(state.launcherPath ? [state.launcherPath] : []), ...installedTrayIconPaths()]
413+
.every(path => existsSync(path));
380414
const stale = windowsTrayRegistrationIsStale({
381415
registered: registered !== null,
382416
registrationOwned,
@@ -479,7 +513,12 @@ export function installWindowsTray(startNow = true): WindowsTrayStatus {
479513
}
480514
recordOwnedConfigPath(getConfigDir(), trayStatePath());
481515
if (!existsSync(getConfigDir())) mkdirSync(getConfigDir(), { recursive: true, mode: 0o700 });
482-
const runCommand = buildWindowsTrayRunCommand(entry);
516+
const launcherPath = installedTrayLauncherPath();
517+
const entryWithLauncher = { ...entry, launcherPath };
518+
const runCommand = buildWindowsTrayRunCommand(entryWithLauncher);
519+
if (runCommand.length > 260) {
520+
throw new Error(`Tray Run command exceeds the Windows 260-character limit (${runCommand.length} chars).`);
521+
}
483522
const runValue = windowsTrayRunValue(entry.opencodexHome);
484523
const existing = readOwnedRunValue(runValue);
485524
const state = readState();
@@ -489,6 +528,9 @@ export function installWindowsTray(startNow = true): WindowsTrayStatus {
489528
if (existsSync(entry.script) && (!state || resolve(state.script) !== resolve(entry.script))) {
490529
throw new Error(`Refusing to overwrite an unowned tray script at ${entry.script}.`);
491530
}
531+
if (existsSync(launcherPath) && state?.launcherPath && resolve(state.launcherPath) !== resolve(launcherPath)) {
532+
throw new Error(`Refusing to overwrite an unowned tray launcher at ${launcherPath}.`);
533+
}
492534
if (!state && iconPairs.some(pair => existsSync(pair.installed))) {
493535
throw new Error("Refusing to overwrite unowned Windows tray icon assets.");
494536
}
@@ -503,6 +545,7 @@ export function installWindowsTray(startNow = true): WindowsTrayStatus {
503545

504546
const previousStateBytes = existsSync(trayStatePath()) ? readFileSync(trayStatePath()) : null;
505547
const previousScriptBytes = existsSync(entry.script) ? readFileSync(entry.script) : null;
548+
const previousLauncherBytes = existsSync(launcherPath) ? readFileSync(launcherPath) : null;
506549
const previousIconBytes = new Map(iconPairs.map(pair => [
507550
pair.installed,
508551
existsSync(pair.installed) ? readFileSync(pair.installed) : null,
@@ -512,6 +555,10 @@ export function installWindowsTray(startNow = true): WindowsTrayStatus {
512555
if (previousScriptBytes) replaceOwnedFile(entry.script, previousScriptBytes);
513556
else if (existsSync(entry.script)) unlinkSync(entry.script);
514557
} catch { /* rollback best-effort */ }
558+
try {
559+
if (previousLauncherBytes) replaceOwnedFile(launcherPath, previousLauncherBytes);
560+
else if (existsSync(launcherPath)) unlinkSync(launcherPath);
561+
} catch { /* rollback best-effort */ }
515562
for (const [path, contents] of previousIconBytes) {
516563
try {
517564
if (contents) replaceOwnedFile(path, contents);
@@ -539,8 +586,9 @@ export function installWindowsTray(startNow = true): WindowsTrayStatus {
539586
if (!hardenedDir.ok) throw new Error("Windows tray directory ACL hardening did not complete; refusing to install persistence.");
540587
replaceOwnedFile(entry.script, readFileSync(sourceScript));
541588
for (const pair of iconPairs) replaceOwnedFile(pair.installed, readFileSync(pair.source));
589+
replaceOwnedFile(launcherPath, buildWindowsTrayLauncherScript(entry));
542590
runRegistry(["add", RUN_KEY, "/v", runValue, "/t", "REG_SZ", "/d", runCommand, "/f", "/reg:64"]);
543-
writeState(entry, runValue, runCommand);
591+
writeState(entryWithLauncher, runValue, runCommand);
544592
} catch (error) {
545593
restorePreviousInstall();
546594
throw error;
@@ -550,9 +598,6 @@ export function installWindowsTray(startNow = true): WindowsTrayStatus {
550598
restorePreviousInstall();
551599
throw new Error("The tray startup registration was installed, but the tray process did not become healthy.");
552600
}
553-
if (state?.launcherPath && existsSync(state.launcherPath)) {
554-
try { unlinkSync(state.launcherPath); } catch { /* old owned VBS is inert after a committed Run replacement */ }
555-
}
556601
return getWindowsTrayStatus();
557602
}
558603

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
import { describe, expect, test } from "bun:test";
2+
import {
3+
buildWindowsTrayRunCommand,
4+
buildWindowsTrayPowerShellCommand,
5+
} from "../src/tray/windows";
6+
7+
describe("windows tray Run registration (#696)", () => {
8+
test("short wscript Run command stays within the 260-character Windows limit under long paths", () => {
9+
const longHome = "C:\\Users\\VeryLongWindowsUserNameForTestingPaths\\AppData\\Roaming\\npm\\node_modules\\@bitkyc08\\opencodex";
10+
const entry = {
11+
bun: `${longHome}\\node_modules\\bun\\bin\\bun.exe`,
12+
cli: `${longHome}\\src\\cli\\index.ts`,
13+
script: "C:\\Users\\VeryLongWindowsUserNameForTestingPaths\\.opencodex\\opencodex-tray.ps1",
14+
codexHome: "C:\\Users\\VeryLongWindowsUserNameForTestingPaths\\.codex",
15+
opencodexHome: "C:\\Users\\VeryLongWindowsUserNameForTestingPaths\\.opencodex",
16+
launcherPath: "C:\\Users\\VeryLongWindowsUserNameForTestingPaths\\.opencodex\\opencodex-tray.vbs",
17+
};
18+
const runCommand = buildWindowsTrayRunCommand(entry);
19+
expect(runCommand.length).toBeLessThanOrEqual(260);
20+
expect(runCommand.toLowerCase()).toContain("wscript.exe");
21+
expect(runCommand).toContain("opencodex-tray.vbs");
22+
// The long PowerShell form still exists for the VBS body, but must not be the Run value.
23+
expect(buildWindowsTrayPowerShellCommand(entry).length).toBeGreaterThan(260);
24+
});
25+
});

‎tests/windows-tray.test.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import { describe, expect, test } from "bun:test";
22
import { existsSync, readFileSync } from "node:fs";
33
import { join } from "node:path";
44
import {
5+
buildWindowsTrayPowerShellCommand,
56
buildWindowsTrayRunCommand,
67
parseWindowsTrayRunValue,
78
readWindowsTrayRunValueWithAsyncRunner,
@@ -38,11 +39,17 @@ describe("Windows tray packaging and command safety", () => {
3839
});
3940

4041
test("quotes metacharacter and Unicode paths without shell interpolation", () => {
41-
const powershellCommand = buildWindowsTrayRunCommand(entry, "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe");
42+
const powershellCommand = buildWindowsTrayPowerShellCommand(entry, "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe");
4243
expect(powershellCommand).toContain(`-File "${entry.script}"`);
4344
expect(powershellCommand).toContain(`-OpenCodexHome "${entry.opencodexHome}"`);
4445
expect(powershellCommand).not.toContain("cmd /c");
4546
expect(powershellCommand).not.toContain("-Command");
47+
const runCommand = buildWindowsTrayRunCommand({
48+
...entry,
49+
launcherPath: `${entry.opencodexHome}\\opencodex-tray.vbs`,
50+
});
51+
expect(runCommand.toLowerCase()).toContain("wscript.exe");
52+
expect(runCommand.length).toBeLessThanOrEqual(260);
4653
});
4754

4855
test("rejects quote and control-character path injection", () => {

0 commit comments

Comments
 (0)