Skip to content

Commit af04f67

Browse files
committed
fix(process): preserve arguments through Windows batch wrappers
1 parent d210305 commit af04f67

7 files changed

Lines changed: 92 additions & 36 deletions

File tree

‎src/process/exec.windows.test.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -258,7 +258,7 @@ describe("Windows command execution", () => {
258258
});
259259
const call = requireExecaCall(0);
260260
expect(call[0]).toBe(expectedTrustedCmdExe());
261-
expect(call[1][3]).toContain(`${shimPath} --version`);
261+
expect(call[1][3]).toContain(`"${shimPath}" "--version"`);
262262
});
263263
});
264264
});
@@ -289,11 +289,11 @@ describe("Windows command execution", () => {
289289
});
290290
});
291291

292-
it("escapes command arguments inside the trusted cmd.exe wrapper", async () => {
292+
it("quotes carets inside the trusted cmd.exe wrapper", async () => {
293293
await withMockedWindowsPlatform(async () => {
294294
await runCommandWithTimeout(["pnpm", "run", "value^with^carets"], { timeoutMs: 1_000 });
295295
const commandLine = String(requireExecaCall(0)[1][3]);
296-
expect(commandLine).toContain("value^^with^^carets");
296+
expect(commandLine).toContain('"value^with^carets"');
297297
});
298298
});
299299

‎src/process/supervisor/adapters/child.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -880,7 +880,7 @@ describe("createChildAdapter", () => {
880880
"/d",
881881
"/s",
882882
"/c",
883-
"pnpm.cmd --version",
883+
'""pnpm.cmd" "--version""',
884884
]);
885885
expect(spawnArgs.options?.detached).toBe(false);
886886
expect(spawnArgs.options?.windowsHide).toBe(true);

‎src/process/terminal-pty.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -214,7 +214,7 @@ describe("terminal PTY invocation", () => {
214214

215215
expect(mocks.spawn).toHaveBeenCalledWith(
216216
expectedComSpec,
217-
["/d", "/s", "/c", `""C:\\Program Files\\Codex\\codex${extension}" resume "thread title""`],
217+
`/d /s /c ""C:\\Program Files\\Codex\\codex${extension}" "resume" "thread title""`,
218218
expect.objectContaining({ cols: 80, rows: 24 }),
219219
);
220220
});

‎src/process/terminal-pty.ts‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -49,9 +49,8 @@ function resolveTerminalPtyInvocation(params: {
4949
file: string;
5050
args: string[];
5151
platform?: NodeJS.Platform;
52-
comSpec?: string;
5352
env: NodeJS.ProcessEnv;
54-
}): { file: string; args: string[] } {
53+
}): { file: string; args: string[] | string } {
5554
const platform = params.platform ?? process.platform;
5655
if (!isWindowsBatchCommand(params.file, platform)) {
5756
return { file: params.file, args: params.args };
@@ -73,8 +72,11 @@ function resolveTerminalPtyInvocation(params: {
7372
return { file: invocation.command, args: invocation.argv };
7473
}
7574
return {
76-
file: params.comSpec?.trim() || resolveTrustedWindowsCmdExe(platform),
77-
args: ["/d", "/s", "/c", buildWindowsCmdExeCommandLine(params.file, params.args)],
75+
file:
76+
resolveEnvironmentValue(params.env, "COMSPEC")?.trim() ||
77+
resolveTrustedWindowsCmdExe(platform),
78+
// node-pty preserves string tails verbatim; arrays would escape the prepared cmd quotes again.
79+
args: `/d /s /c ${buildWindowsCmdExeCommandLine(params.file, params.args)}`,
7880
};
7981
}
8082

@@ -92,12 +94,10 @@ export async function spawnTerminalPty(params: {
9294
// Passing it through makes interactive CLIs refuse to start in the web terminal.
9395
const terminalName = resolvePtyTerminalName(readPtyTerminalName(env, process.platform));
9496
setPtyTerminalName({ env, name: terminalName, platform: process.platform });
95-
const comSpec = resolveEnvironmentValue(env, "COMSPEC");
9697
const invocation = resolveTerminalPtyInvocation({
9798
file: params.file,
9899
args: params.args,
99100
env,
100-
...(comSpec ? { comSpec } : {}),
101101
});
102102
const pty = spawn(invocation.file, invocation.args, {
103103
name: terminalName,

‎src/process/windows-command.test.ts‎

Lines changed: 62 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
11
// Windows command tests cover command quoting and shell resolution on Windows.
2-
import { mkdir, writeFile } from "node:fs/promises";
2+
import { mkdir, readFile, writeFile } from "node:fs/promises";
33
import path from "node:path";
4-
import { describe, expect, it } from "vitest";
4+
import { describe, expect, it, vi } from "vitest";
55
import { withTempDir } from "../test-utils/temp-dir.js";
66
import { withMockedWindowsPlatform } from "../test-utils/vitest-spies.js";
77
import { runCommandWithTimeout } from "./exec.js";
8+
import { spawnTerminalPty } from "./terminal-pty.js";
89
import { resolveSafeChildProcessInvocation, resolveWindowsCommandShim } from "./windows-command.js";
910

1011
describe("Windows command helpers", () => {
@@ -189,13 +190,24 @@ describe.runIf(process.platform === "win32")("Windows batch argv preservation",
189190
{ name: "double quotes", args: ['say "hello"', "omega"] },
190191
{ name: "a caret", args: ["left^right", "omega"] },
191192
{ name: "a quoted trailing backslash", args: ["C:\\two words\\", "omega"] },
193+
{ name: "a caret beside a quote", args: ['left^"right', "omega"] },
194+
{ name: "a backslash before a quote", args: ['left\\"right', "omega"] },
195+
{ name: "two backslashes before a quote", args: ['left\\\\"right', "omega"] },
196+
{
197+
name: "permitted cmd punctuation",
198+
args: ["(round)", "[square]", "{curly}", "semi;colon", "eq=sign", "comma,value", "bang!"],
199+
},
192200
];
193201

194-
it.each(cases)(
195-
"preserves $name through a real .cmd wrapper",
196-
async ({ args }) => {
202+
it.each(
203+
cases.flatMap((testCase) =>
204+
["argv.cmd", "argv with spaces.cmd", "argv^caret.cmd"].map((file) => ({ ...testCase, file })),
205+
),
206+
)(
207+
"preserves $name through $file",
208+
async ({ args, file }) => {
197209
await withTempDir("openclaw-batch-argv-", async (cwd) => {
198-
const command = path.join(cwd, "argv.cmd");
210+
const command = path.join(cwd, file);
199211
await writeFile(
200212
path.join(cwd, "argv.cjs"),
201213
"process.stdout.write(JSON.stringify(process.argv.slice(2)))",
@@ -210,6 +222,50 @@ describe.runIf(process.platform === "win32")("Windows batch argv preservation",
210222
15_000,
211223
);
212224

225+
it.each(["argv.cmd", "argv with spaces.cmd", "argv^caret.cmd", "node.exe"])(
226+
"preserves the argument matrix through a real PTY running %s",
227+
async (file) => {
228+
await withTempDir("openclaw-batch-argv-pty-", async (cwd) => {
229+
const args = cases.flatMap((testCase) => testCase.args);
230+
const script = path.join(cwd, "argv.cjs");
231+
const output = path.join(cwd, "received.json");
232+
await writeFile(
233+
script,
234+
'require("node:fs").writeFileSync(require("node:path").join(__dirname, "received.json"), JSON.stringify(process.argv.slice(2)))',
235+
);
236+
const command = file === "node.exe" ? process.execPath : path.join(cwd, file);
237+
if (file !== "node.exe") {
238+
await writeFile(command, `@"${process.execPath}" "%~dp0argv.cjs" %*\r\n`);
239+
}
240+
const pty = await spawnTerminalPty({
241+
file: command,
242+
args: file === "node.exe" ? [script, ...args] : args,
243+
cwd,
244+
env: Object.fromEntries(
245+
Object.entries(process.env).filter(
246+
(entry): entry is [string, string] => typeof entry[1] === "string",
247+
),
248+
),
249+
cols: 120,
250+
rows: 24,
251+
});
252+
let exitCode: number | undefined;
253+
pty.onExit((event) => {
254+
exitCode = event.exitCode;
255+
});
256+
try {
257+
await vi.waitFor(() => expect(exitCode).toBe(0), { timeout: 5_000 });
258+
expect(JSON.parse(await readFile(output, "utf8"))).toEqual(args);
259+
} finally {
260+
if (exitCode === undefined) {
261+
pty.kill();
262+
}
263+
}
264+
});
265+
},
266+
15_000,
267+
);
268+
213269
it.each(["&", "|", "<", ">", "%", "\r", "\n"])(
214270
"continues to reject unsafe batch argument character %j before launch",
215271
async (character) => {

‎src/process/windows-command.ts‎

Lines changed: 17 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -172,24 +172,24 @@ export function isWindowsBatchCommand(
172172
return ext === ".cmd" || ext === ".bat";
173173
}
174174

175-
function escapeForWindowsCmdExe(arg: string): string {
176-
if (WINDOWS_UNSAFE_CMD_CHARS_RE.test(arg)) {
177-
throw new Error(
178-
`Unsafe Windows cmd.exe argument detected: ${JSON.stringify(arg)}. ` +
179-
"Pass an explicit shell-wrapper argv at the call site instead.",
180-
);
181-
}
182-
const escaped = arg.replace(/\^/g, "^^");
183-
if (!escaped.includes(" ") && !escaped.includes('"')) {
184-
return escaped;
185-
}
186-
return `"${escaped.replace(/"/g, '""')}"`;
187-
}
188-
189175
export function buildWindowsCmdExeCommandLine(command: string, args: readonly string[]): string {
190-
const escapedCommand = escapeForWindowsCmdExe(command);
191-
const commandLine = [escapedCommand, ...args.map(escapeForWindowsCmdExe)].join(" ");
192-
return escapedCommand.startsWith('"') ? `"${commandLine}"` : commandLine;
176+
const escaped = [command, ...args].map((arg) => {
177+
if (WINDOWS_UNSAFE_CMD_CHARS_RE.test(arg)) {
178+
throw new Error(
179+
`Unsafe Windows cmd.exe argument detected: ${JSON.stringify(arg)}. ` +
180+
"Pass an explicit shell-wrapper argv at the call site instead.",
181+
);
182+
}
183+
// Quote through cmd and the CRT; consume backslash runs once to avoid quadratic scans.
184+
const quoted = arg
185+
.replace(/\\+/g, (backslashes, offset) => {
186+
const next = arg[offset + backslashes.length];
187+
return next === '"' || next === undefined ? backslashes.repeat(2) : backslashes;
188+
})
189+
.replace(/"/g, '""');
190+
return `"${quoted}"`;
191+
});
192+
return `"${escaped.join(" ")}"`;
193193
}
194194

195195
export function resolveTrustedWindowsCmdExe(platform: NodeJS.Platform = process.platform): string {

‎src/tui/tui.local-auth.test.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@ describe("resolveLocalAuthSpawnInvocation", () => {
6666
}),
6767
).toEqual({
6868
command: "C:\\Windows\\System32\\cmd.exe",
69-
args: ["/d", "/s", "/c", "C:\\Users\\me\\AppData\\Roaming\\npm\\codex.cmd login"],
69+
args: ["/d", "/s", "/c", '""C:\\Users\\me\\AppData\\Roaming\\npm\\codex.cmd" "login""'],
7070
options: { windowsHide: true, windowsVerbatimArguments: true },
7171
});
7272
});
@@ -80,7 +80,7 @@ describe("resolveLocalAuthSpawnInvocation", () => {
8080
}),
8181
).toEqual({
8282
command: "C:\\Windows\\System32\\cmd.exe",
83-
args: ["/d", "/s", "/c", '""C:\\Program Files\\Codex\\codex.bat" login"'],
83+
args: ["/d", "/s", "/c", '""C:\\Program Files\\Codex\\codex.bat" "login""'],
8484
options: { windowsHide: true, windowsVerbatimArguments: true },
8585
});
8686
});

0 commit comments

Comments
 (0)