diff --git a/apps/server/src/processRunner.test.ts b/apps/server/src/processRunner.test.ts index 0df630a8e3..2c9a9af46a 100644 --- a/apps/server/src/processRunner.test.ts +++ b/apps/server/src/processRunner.test.ts @@ -1,6 +1,25 @@ +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + import { describe, expect, it } from "vitest"; -import { runProcess, spawnDetachedProcess, spawnProcessSync } from "./processRunner"; +import { + makeRuntimeCommand, + resolveProcessLaunchPlan, + runProcess, + spawnDetachedProcess, + spawnProcessSync, +} from "./processRunner"; + +function withTempDir(run: (dir: string) => void): void { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-process-runner-")); + try { + run(dir); + } finally { + fs.rmSync(dir, { recursive: true, force: true }); + } +} describe("runProcess", () => { it("fails when output exceeds max buffer in default mode", async () => { @@ -37,3 +56,118 @@ describe("runProcess", () => { ).resolves.toBeUndefined(); }); }); + +describe("resolveProcessLaunchPlan", () => { + it("resolves native windows executables without using a shell", () => { + withTempDir((dir) => { + fs.writeFileSync(path.join(dir, "git.EXE"), "MZ"); + const plan = resolveProcessLaunchPlan("git", ["status"], { + env: { + PATH: dir, + PATHEXT: ".COM;.EXE;.BAT;.CMD", + }, + inheritParentEnv: false, + runtimeEnvironment: { + platform: "windows", + pathStyle: "windows", + isWsl: false, + windowsInteropMode: "windows-native", + wslDistroName: null, + }, + }); + + expect(plan.command).toBe(path.join(dir, "git.EXE")); + expect(plan.args).toEqual(["status"]); + expect(plan.shell).toBe(false); + }); + }); + + it("wraps windows batch launchers through cmd.exe without default shell mode", () => { + withTempDir((dir) => { + const wrapperPath = path.join(dir, "code.CMD"); + fs.writeFileSync(wrapperPath, "@echo off\r\n"); + const plan = resolveProcessLaunchPlan("code", ["C:\\repo\\a&b.ts"], { + env: { + PATH: dir, + PATHEXT: ".COM;.EXE;.BAT;.CMD", + COMSPEC: "C:\\Windows\\System32\\cmd.exe", + }, + inheritParentEnv: false, + runtimeEnvironment: { + platform: "windows", + pathStyle: "windows", + isWsl: false, + windowsInteropMode: "windows-native", + wslDistroName: null, + }, + }); + + expect(plan.command).toBe("C:\\Windows\\System32\\cmd.exe"); + expect(plan.args.slice(0, 3)).toEqual(["/d", "/s", "/c"]); + expect(plan.args[3]).toBe(`"${wrapperPath}" "C:\\repo\\a^&b.ts"`); + expect(plan.shell).toBe(false); + }); + }); + + it("keeps wsl-hosted commands on the linux direct exec path", () => { + const plan = resolveProcessLaunchPlan("code", ["/home/julius/repo"], { + runtimeEnvironment: { + platform: "linux", + pathStyle: "posix", + isWsl: true, + windowsInteropMode: "wsl-hosted", + wslDistroName: "Ubuntu", + }, + }); + + expect(plan.command).toBe("code"); + expect(plan.args).toEqual(["/home/julius/repo"]); + expect(plan.shell).toBe(false); + }); + + it("preserves explicit shell configuration", () => { + const plan = resolveProcessLaunchPlan("git", ["status"], { + shell: true, + runtimeEnvironment: { + platform: "windows", + pathStyle: "windows", + isWsl: false, + windowsInteropMode: "windows-native", + wslDistroName: null, + }, + }); + + expect(plan.command).toBe("git"); + expect(plan.args).toEqual(["status"]); + expect(plan.shell).toBe(true); + }); +}); + +describe("makeRuntimeCommand", () => { + it("uses the shared launch plan for batch commands on windows", () => { + withTempDir((dir) => { + const wrapperPath = path.join(dir, "code.CMD"); + fs.writeFileSync(wrapperPath, "@echo off\r\n"); + + const command = makeRuntimeCommand("code", ["C:\\repo\\a&b.ts"], { + env: { + PATH: dir, + PATHEXT: ".COM;.EXE;.BAT;.CMD", + COMSPEC: "C:\\Windows\\System32\\cmd.exe", + }, + extendEnv: false, + runtimeEnvironment: { + platform: "windows", + pathStyle: "windows", + isWsl: false, + windowsInteropMode: "windows-native", + wslDistroName: null, + }, + }); + + expect(command.command).toBe("C:\\Windows\\System32\\cmd.exe"); + expect(command.args).toEqual(["/d", "/s", "/c", `"${wrapperPath}" "C:\\repo\\a^&b.ts"`]); + expect(command.options.shell).toBe(false); + }); + }); +}); diff --git a/apps/server/src/processRunner.ts b/apps/server/src/processRunner.ts index 6bd3162faf..29cd1d624a 100644 --- a/apps/server/src/processRunner.ts +++ b/apps/server/src/processRunner.ts @@ -5,6 +5,8 @@ import { spawnSync, type StdioOptions, } from "node:child_process"; +import { statSync } from "node:fs"; +import { extname, join } from "node:path"; import type { ServerRuntimeEnvironment } from "@t3tools/contracts"; import { Effect, Exit, Scope } from "effect"; @@ -24,6 +26,11 @@ interface RuntimeShellOptions { shell?: boolean | string | undefined; } +interface ProcessLaunchPlanOptions extends RuntimeShellOptions { + env?: NodeJS.ProcessEnv | Record | undefined; + inheritParentEnv?: boolean | undefined; +} + export interface ProcessSpawnOptions extends ProcessSpawnBaseOptions { stdio?: StdioOptions | undefined; detached?: boolean | undefined; @@ -62,6 +69,20 @@ export interface ProcessRunResult { stderrTruncated?: boolean | undefined; } +export interface ProcessLaunchPlan { + readonly command: string; + readonly args: ReadonlyArray; + readonly shell: boolean | string; + readonly runtimeEnvironment: ServerRuntimeEnvironment; +} + +interface ResolvedWindowsCommand { + readonly path: string; + readonly kind: "native" | "batch"; +} + +const WINDOWS_BATCH_EXECUTABLE_EXTENSIONS = new Set([".CMD", ".BAT"]); + function commandLabel(command: string, args: readonly string[]): string { return [command, ...args].join(" "); } @@ -72,19 +93,214 @@ function resolveRuntimeEnvironment( return runtimeEnvironment ?? detectServerRuntimeEnvironment(); } -function shouldUseShell(options: RuntimeShellOptions): boolean | string { - if (options.shell !== undefined) { - return options.shell; - } - - return resolveRuntimeEnvironment(options.runtimeEnvironment).platform === "windows"; +function resolvePathEnvironmentVariable(env: NodeJS.ProcessEnv): string { + return env.PATH ?? env.Path ?? env.path ?? ""; } -function toSpawnOptions(options: ProcessSpawnOptions) { +function resolveWindowsPathExtensions(env: NodeJS.ProcessEnv): ReadonlyArray { + const rawValue = env.PATHEXT; + const fallback = [".COM", ".EXE", ".BAT", ".CMD"]; + if (!rawValue) return fallback; + + const parsed = rawValue + .split(";") + .map((entry) => entry.trim()) + .filter((entry) => entry.length > 0) + .map((entry) => (entry.startsWith(".") ? entry.toUpperCase() : `.${entry.toUpperCase()}`)); + return parsed.length > 0 ? Array.from(new Set(parsed)) : fallback; +} + +function resolveCommandCandidates( + command: string, + windowsPathExtensions: ReadonlyArray, +): ReadonlyArray { + const extension = extname(command); + const normalizedExtension = extension.toUpperCase(); + + if (extension.length > 0 && windowsPathExtensions.includes(normalizedExtension)) { + const commandWithoutExtension = command.slice(0, -extension.length); + return Array.from( + new Set([ + command, + `${commandWithoutExtension}${normalizedExtension}`, + `${commandWithoutExtension}${normalizedExtension.toLowerCase()}`, + ]), + ); + } + + const candidates: string[] = [command]; + for (const candidateExtension of windowsPathExtensions) { + candidates.push(`${command}${candidateExtension}`); + candidates.push(`${command}${candidateExtension.toLowerCase()}`); + } + return Array.from(new Set(candidates)); +} + +function stripWrappingQuotes(value: string): string { + return value.replace(/^"+|"+$/g, ""); +} + +function isExecutableFile( + filePath: string, + windowsPathExtensions: ReadonlyArray, +): boolean { + try { + const stat = statSync(filePath); + if (!stat.isFile()) return false; + const extension = extname(filePath); + if (extension.length === 0) return false; + if (windowsPathExtensions.length === 0) { + return true; + } + return windowsPathExtensions.includes(extension.toUpperCase()); + } catch { + return false; + } +} + +function resolveEffectiveEnvironment(options: ProcessLaunchPlanOptions): NodeJS.ProcessEnv { + const env = (options.env ?? {}) as NodeJS.ProcessEnv; + if (options.inheritParentEnv === false) { + return { ...env }; + } + + return { + ...process.env, + ...env, + }; +} + +function resolveWindowsCommand( + command: string, + env: NodeJS.ProcessEnv, +): ResolvedWindowsCommand | null { + const windowsPathExtensions = resolveWindowsPathExtensions(env); + const candidates = resolveCommandCandidates(command, windowsPathExtensions); + + const classify = (filePath: string): ResolvedWindowsCommand => { + const extension = extname(filePath).toUpperCase(); + return { + path: filePath, + kind: WINDOWS_BATCH_EXECUTABLE_EXTENSIONS.has(extension) ? "batch" : "native", + }; + }; + + if (command.includes("/") || command.includes("\\")) { + for (const candidate of candidates) { + if (isExecutableFile(candidate, windowsPathExtensions)) { + return classify(candidate); + } + } + return null; + } + + const pathEntries = resolvePathEnvironmentVariable(env) + .split(";") + .map((entry) => stripWrappingQuotes(entry.trim())) + .filter((entry) => entry.length > 0); + + for (const pathEntry of pathEntries) { + for (const candidate of candidates) { + const candidatePath = join(pathEntry, candidate); + if (isExecutableFile(candidatePath, windowsPathExtensions)) { + return classify(candidatePath); + } + } + } + + return null; +} + +function quoteWindowsBatchArgument(argument: string): string { + if (argument.length === 0) { + return '""'; + } + + const escaped = argument + .replaceAll("^", "^^") + .replaceAll("%", "%%") + .replaceAll("!", "^!") + .replaceAll("&", "^&") + .replaceAll("|", "^|") + .replaceAll("<", "^<") + .replaceAll(">", "^>") + .replaceAll("(", "^(") + .replaceAll(")", "^)") + .replaceAll('"', '""'); + return `"${escaped}"`; +} + +function buildWindowsBatchCommandLine( + command: string, + args: ReadonlyArray, +): string { + return [quoteWindowsBatchArgument(command), ...args.map(quoteWindowsBatchArgument)].join(" "); +} + +function resolveWindowsCommandShell(env: NodeJS.ProcessEnv): string { + return env.ComSpec ?? env.COMSPEC ?? process.env.ComSpec ?? process.env.COMSPEC ?? "cmd.exe"; +} + +export function resolveProcessLaunchPlan( + command: string, + args: ReadonlyArray, + options: ProcessLaunchPlanOptions = {}, +): ProcessLaunchPlan { + const runtimeEnvironment = resolveRuntimeEnvironment(options.runtimeEnvironment); + if (options.shell !== undefined) { + return { + command, + args: [...args], + shell: options.shell, + runtimeEnvironment, + }; + } + + if (runtimeEnvironment.platform !== "windows") { + return { + command, + args: [...args], + shell: false, + runtimeEnvironment, + }; + } + + const env = resolveEffectiveEnvironment(options); + const resolved = resolveWindowsCommand(command, env); + if (!resolved) { + return { + command, + args: [...args], + shell: false, + runtimeEnvironment, + }; + } + + if (resolved.kind === "batch") { + return { + command: resolveWindowsCommandShell(env), + args: ["/d", "/s", "/c", buildWindowsBatchCommandLine(resolved.path, args)], + shell: false, + runtimeEnvironment, + }; + } + + return { + command: resolved.path, + args: [...args], + shell: false, + runtimeEnvironment, + }; +} + +function toSpawnOptions( + options: ProcessSpawnOptions, + launchPlan: ProcessLaunchPlan, +) { return { cwd: options.cwd, env: options.env, - shell: shouldUseShell(options), + shell: launchPlan.shell, ...(options.stdio !== undefined ? { stdio: options.stdio } : {}), ...(options.detached !== undefined ? { detached: options.detached } : {}), }; @@ -93,9 +309,16 @@ function toSpawnOptions(options: ProcessSpawnOptions) { export function toRuntimeCommandOptions( options: RuntimeCommandOptions = {}, ): ChildProcess.CommandOptions { + const launchPlan = resolveProcessLaunchPlan("", [], { + env: options.env, + runtimeEnvironment: options.runtimeEnvironment, + shell: options.shell, + inheritParentEnv: options.extendEnv !== false, + }); + return { ...options, - shell: options.shell ?? shouldUseShell(options), + shell: launchPlan.shell, }; } @@ -104,7 +327,16 @@ export function makeRuntimeCommand( args: ReadonlyArray, options: RuntimeCommandOptions = {}, ): ChildProcess.StandardCommand { - return ChildProcess.make(command, [...args], toRuntimeCommandOptions(options)); + const launchPlan = resolveProcessLaunchPlan(command, args, { + env: options.env, + runtimeEnvironment: options.runtimeEnvironment, + shell: options.shell, + inheritParentEnv: options.extendEnv !== false, + }); + return ChildProcess.make(launchPlan.command, launchPlan.args, { + ...toRuntimeCommandOptions(options), + shell: launchPlan.shell, + }); } export interface ManagedChildProcess { @@ -132,7 +364,14 @@ function spawnProcess( args: readonly string[], options: ProcessSpawnOptions = {}, ): ChildProcessHandle { - return spawn(command, args, toSpawnOptions(options)); + const launchPlan = resolveProcessLaunchPlan(command, args, { + env: options.env, + runtimeEnvironment: options.runtimeEnvironment, + shell: options.shell, + inheritParentEnv: options.env === undefined, + }); + + return spawn(launchPlan.command, launchPlan.args, toSpawnOptions(options, launchPlan)); } export function spawnPipedProcess( @@ -151,10 +390,17 @@ export function spawnProcessSync( args: readonly string[], options: ProcessSpawnSyncOptions = {}, ) { - return spawnSync(command, args, { + const launchPlan = resolveProcessLaunchPlan(command, args, { + env: options.env, + runtimeEnvironment: options.runtimeEnvironment, + shell: options.shell, + inheritParentEnv: options.env === undefined, + }); + + return spawnSync(launchPlan.command, launchPlan.args, { cwd: options.cwd, env: options.env, - shell: shouldUseShell(options), + shell: launchPlan.shell, encoding: options.encoding ?? "utf8", ...(options.stdio !== undefined ? { stdio: options.stdio } : {}), ...(options.detached !== undefined ? { detached: options.detached } : {}), @@ -248,9 +494,10 @@ function normalizeBufferError( const DEFAULT_MAX_BUFFER_BYTES = 8 * 1024 * 1024; /** - * On Windows with `shell: true`, `child.kill()` only terminates the `cmd.exe` - * wrapper, leaving the actual command running. Use `taskkill /T` to kill the - * entire process tree instead. + * On Windows, commands may still execute through a `cmd.exe` wrapper for + * explicit shell usage or `.cmd` / `.bat` launchers. `child.kill()` only + * terminates the wrapper, leaving the actual command running. Use + * `taskkill /T` to kill the entire process tree instead. */ export function killProcessTree( child: ChildProcessHandle,