Move away from `cross-spawn` (#1251)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Sindre Sorhus · committed by GitHub · parent 97dc613 · Browse files · 11 files·+540 added−8 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
11 files+540 added−8 removed
- tests:+347 added−0 removed
- other:+193 added−8 removed
Provenance
- Commit
4cafc3f- Tree
a3a4c4b- Author
Sindre Sorhus <sindresorhus@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
97dc613
11 files changed+540 added−8 removed
modified:docs/windows.md+1 added-1 removed
33 unmodified lines3435363738383940414250 unmodified lines33 unmodified lines// Runs `npm.cmd`await execa`npm run build`;```
This means `.cmd` and `.bat` files can be run directly. Unlike Node.js, Execa does not require a [shell](shell.md) (nor a `cmd.exe /c` prefix) for this. Relative paths (such as `./folder/executable`) and files whose path contains spaces also work without a shell, just like on Unix. This is thanks to [`cross-spawn`](https://github.com/moxystudio/node-cross-spawn?tab=readme-ov-file#why).This means `.cmd` and `.bat` files can be run directly. Unlike Node.js, Execa does not require a [shell](shell.md) (nor a `cmd.exe /c` prefix) for this. Relative paths (such as `./folder/executable`) and files whose path contains spaces also work without a shell, just like on Unix. Execa handles this automatically.
## Signals
Only few [signals](termination.md#other-signals) work on Windows with Node.js: [`SIGTERM`](termination.md#sigterm), [`SIGKILL`](termination.md#sigkill), [`SIGINT`](https://en.wikipedia.org/wiki/Signal_(IPC)#SIGINT) and [`SIGQUIT`](termination.md#sigquit). Also, sending signals from other processes is [not supported](termination.md#signal-name-and-description). Finally, the [`forceKillAfterDelay`](api.md#optionsforcekillafterdelay) option [is a noop](termination.md#forceful-termination) on Windows.50 unmodified linesadded:lib/arguments/command-file.js+186 added
1+import {openSync, readSync, closeSync} from 'node:fs';2+import {Buffer} from 'node:buffer';3+import path from 'node:path';4+import process from 'node:process';5+import which from 'which';6+import pathKey from 'path-key';7+8+/*9+On Windows, `node:child_process` cannot natively run many kinds of files (`.cmd`, `.bat`, shebang scripts, ...): without a shell it resolves neither `PATHEXT` nor shebangs, and it does not escape arguments. We resolve the command to its full file path and escape its arguments ourselves, so those work without an explicit shell, just like on Unix, where the OS handles all of this for us.10+*/11+export const parseCommandFile = (file, commandArguments, options) => {12+ // The arguments are cloned since a shebang interpreter might be prepended below, which must not mutate the caller's array13+ const parsed = {file, commandArguments: [...commandArguments], options};14+15+ // Under a shell, or on Unix, the OS resolves the file and escapes the arguments itself16+ if (options.shell || process.platform !== 'win32') {17+ return parsed;18+ }19+20+ return escapeWindowsCommand(parsed);21+};22+23+// Only `.exe` and `.com` files can be spawned directly; anything else needs `cmd.exe`24+const directlyExecutableRegExp = /\.(?:com|exe)$/i;25+26+// `.cmd` and `.bat` files re-expand their own arguments via `%*`/`%1`, so metacharacters must survive being interpreted by `cmd.exe` twice: once when the batch file is invoked and once when it forwards the arguments27+const batchFileRegExp = /\.(?:bat|cmd)$/i;28+29+const escapeWindowsCommand = parsed => {30+ // Resolve the file to an absolute path, following its shebang to the interpreter if any31+ const resolvedFile = resolveWithShebang(parsed);32+33+ // A directly executable file is spawned as-is, bypassing `cmd.exe` and its escaping34+ if (resolvedFile !== undefined && directlyExecutableRegExp.test(resolvedFile)) {35+ return parsed;36+ }37+38+ /*39+ `cmd.exe` treats CR and LF as command separators and offers no way to escape them, so allowing either would enable command injection.40+ Reject them instead.41+ */42+ for (const value of [parsed.file, ...parsed.commandArguments]) {43+ assertNoLineBreak(value);44+ }45+46+ const doubleEscape = resolvedFile !== undefined && batchFileRegExp.test(resolvedFile);47+ // POSIX separators must become Windows ones (`foo/bar` -> `foo\bar`), otherwise resolution always fails with ENOENT48+ const escapedFile = escapeMetaChars(path.normalize(parsed.file));49+ const escapedArguments = parsed.commandArguments.map(argument => escapeArgument(argument, doubleEscape));50+ const commandLine = `"${[escapedFile, ...escapedArguments].join(' ')}"`;51+52+ // Let `node:child_process` pass the already-escaped command line through untouched53+ parsed.options.windowsVerbatimArguments = true;54+ return {55+ file: process.env.comspec || 'cmd.exe',56+ commandArguments: ['/d', '/s', '/c', commandLine],57+ options: parsed.options,58+ };59+};60+61+// Resolve the command's absolute path, then, if it is a shebang script, resolve its interpreter instead, since Windows cannot run shebangs natively62+const resolveWithShebang = parsed => {63+ const resolvedFile = resolvePath(parsed);64+ const interpreter = resolvedFile !== undefined && readShebang(resolvedFile);65+ if (!interpreter) {66+ return resolvedFile;67+ }68+69+ // Run the interpreter with the script as its first argument, then resolve the interpreter's own path70+ parsed.commandArguments.unshift(resolvedFile);71+ parsed.file = interpreter;72+ return resolvePath(parsed);73+};74+75+// Search `PATH` for the command, first honoring `PATHEXT`, then ignoring it as a fallback76+const resolvePath = parsed => resolveInCwd(parsed, false) || resolveInCwd(parsed, true);77+78+const resolveInCwd = (parsed, ignorePathExtension) => {79+ const environment = parsed.options.env || process.env;80+81+ /*82+ `which` runs `stat` relative to the current directory but has no `cwd` option, so we temporarily switch into the target directory and restore it afterwards.83+84+ `process.chdir()` is disabled in worker threads and might be absent in non-Node runtimes.85+ */86+ const canChangeDirectory = process.chdir !== undefined && !process.chdir.disabled;87+ const originalDirectory = process.cwd();88+ if (canChangeDirectory) {89+ try {90+ process.chdir(parsed.options.cwd);91+ } catch {}92+ }93+94+ try {95+ const resolved = which.sync(parsed.file, {96+ path: environment[pathKey({env: environment})],97+ pathExt: ignorePathExtension ? path.delimiter : undefined,98+ });99+ // `cwd` is already an absolute path, so this returns an absolute path too100+ return path.resolve(parsed.options.cwd, resolved);101+ } catch {102+ return undefined;103+ } finally {104+ if (canChangeDirectory) {105+ process.chdir(originalDirectory);106+ }107+ }108+};109+110+const SHEBANG_BYTE_LENGTH = 150;111+112+// Read the file's first bytes to find its shebang interpreter, if it has one113+const readShebang = file => {114+ const buffer = Buffer.alloc(SHEBANG_BYTE_LENGTH);115+116+ try {117+ const fileDescriptor = openSync(file, 'r');118+ try {119+ readSync(fileDescriptor, buffer, 0, SHEBANG_BYTE_LENGTH, 0);120+ } finally {121+ closeSync(fileDescriptor);122+ }123+ } catch {124+ return undefined;125+ }126+127+ return parseShebang(buffer.toString());128+};129+130+const shebangRegExp = /^#!(?<line>.*)/;131+132+/*133+Extract the interpreter from a shebang line, e.g. `#!/usr/bin/env node` -> `node`.134+*/135+const parseShebang = contents => {136+ const shebangLine = contents.match(shebangRegExp)?.groups.line.trim();137+ if (!shebangLine) {138+ return undefined;139+ }140+141+ const [interpreterPath, argument] = shebangLine.split(' ');142+ const interpreter = interpreterPath.split('/').at(-1);143+ if (interpreter === 'env') {144+ return argument;145+ }146+147+ return argument ? `${interpreter} ${argument}` : interpreter;148+};149+150+const lineBreakRegExp = /[\n\r]/;151+152+const assertNoLineBreak = value => {153+ if (lineBreakRegExp.test(value)) {154+ throw new TypeError(`The command and its arguments cannot contain a line break on Windows without a shell.\nThis would allow a command injection with \`cmd.exe\`.\nInvalid value: ${JSON.stringify(`${value}`)}`);155+ }156+};157+158+// See https://web.archive.org/web/20241220221102/https://www.robvanderwoude.com/escapechars.php159+// eslint-disable-next-line regexp/sort-character-class-elements160+const metaCharsRegExp = /[()\][%!^"`<>&|;, *?]/g;161+162+// Prefix every `cmd.exe` metacharacter with a caret to neutralize it163+const escapeMetaChars = value => value.replaceAll(metaCharsRegExp, '^$&');164+165+const backslashRunRegExp = /\\+/g;166+167+const escapeArgument = (rawArgument, doubleEscape) => {168+ /*169+ Escape backslashes and double quotes for `cmd.exe`, following the algorithm at https://web.archive.org/web/20240930203505/https://qntm.org/cmd.170+171+ A run of backslashes only needs doubling when it precedes a double quote, or the end of the argument since that becomes a double quote once the argument is wrapped below. Otherwise the backslashes would be taken as escaping that quote. Every double quote is then escaped in turn.172+173+ Each backslash run is matched exactly once and consumed, so a long run cannot trigger the quadratic backtracking a naive pattern would, which would be a denial-of-service risk.174+ */175+ const argument = `${rawArgument}`176+ .replaceAll(backslashRunRegExp, (backslashes, offset, string) => {177+ const nextCharacter = string[offset + backslashes.length];178+ const precedesDoubleQuote = nextCharacter === '"' || nextCharacter === undefined;179+ return precedesDoubleQuote ? backslashes.repeat(2) : backslashes;180+ })181+ .replaceAll('"', '\\"');182+183+ // Wrap the whole argument in double quotes, then caret-escape the metacharacters, a second time when targeting a cmd-shim184+ const escapedArgument = escapeMetaChars(`"${argument}"`);185+ return doubleEscape ? escapeMetaChars(escapedArgument) : escapedArgument;186+};modified:lib/arguments/options.js+2 added-2 removed
1233456789101112131415164 unmodified lines2122232425252627282971 unmodified linesimport path from 'node:path';import process from 'node:process';import crossSpawn from 'cross-spawn';import {npmRunPathEnv} from 'npm-run-path';import {normalizeForceKillAfterDelay} from '../terminate/kill.js';import {normalizeKillSignal} from '../terminate/signal.js';import {validateCancelSignal} from '../terminate/cancel.js';import {validateGracefulCancel} from '../terminate/graceful.js';import {validateTimeout} from '../terminate/timeout.js';import {handleNodeOption} from '../methods/node.js';import {validateIpcInputOption} from '../ipc/ipc-input.js';import {validateEncoding, BINARY_ENCODINGS} from './encoding-option.js';import {parseCommandFile} from './command-file.js';import {normalizeCwd} from './cwd.js';import {normalizeFileUrl} from './file-url.js';import {normalizeFdSpecificOptions} from './specific.js';
4 unmodified lines const sanitizedOptions = {__proto__: null, ...rawOptions}; sanitizedOptions.cwd = normalizeCwd(sanitizedOptions.cwd); const [processedFile, processedArguments, processedOptions] = handleNodeOption(filePath, rawArguments, sanitizedOptions);
const {command: file, args: commandArguments, options: initialOptions} = crossSpawn._parse(processedFile, processedArguments, processedOptions); const {file, commandArguments, options: initialOptions} = parseCommandFile(processedFile, processedArguments, processedOptions);
const fdOptions = normalizeFdSpecificOptions(initialOptions); const options = addDefaultOptions(fdOptions); validateTimeout(options);71 unmodified linesadded:test/arguments/command-resolution.js+318 added
1+import {cp, mkdir} from 'node:fs/promises';2+import path from 'node:path';3+import process from 'node:process';4+import test from 'ava';5+import {execa, execaSync} from '../../index.js';6+import {setFixtureDirectory, FIXTURES_DIRECTORY} from '../helpers/fixtures-directory.js';7+8+setFixtureDirectory();9+10+const isWindows = process.platform === 'win32';11+12+// These tests cover the command resolution and argument escaping performed by13+// `lib/arguments/command-file.js`, which allows running scripts, `.cmd`/`.bat` files14+// and shebang scripts without a shell, and prevents command injection on Windows.15+// Most assertions use a roundtrip: an argument is passed in, the subprocess prints16+// its own `process.argv` back (see `test/fixtures/echo.js`), and we check it comes17+// back byte-identical. This exercises the escaping logic on whichever OS runs the18+// test, so Windows escaping is genuinely validated on CI.19+20+// `echo.js` prints `process.argv.slice(2).join('\n')`21+const testRoundtrip = async (t, commandArguments) => {22+ const expectedStdout = commandArguments.map(String).join('\n');23+24+ const {stdout} = await execa('echo.js', commandArguments);25+ t.is(stdout, expectedStdout);26+27+ const {stdout: stdoutSync} = execaSync('echo.js', commandArguments);28+ t.is(stdoutSync, expectedStdout);29+};30+31+test('Empty arguments and arguments with spaces', testRoundtrip, ['foo', '', 'bar', 'André Cruz']);32+test('Non-string arguments are coerced', testRoundtrip, [1234]);33+test('Arguments with shell special characters', testRoundtrip, [34+ 'foo',35+ '()',36+ 'foo',37+ '[]',38+ 'foo',39+ '%!',40+ 'foo',41+ '^<',42+ 'foo',43+ '>&',44+ 'foo',45+ '|;',46+ 'foo',47+ ', ',48+ 'foo',49+ '!=',50+ 'foo',51+ '\\*',52+ 'foo',53+ '"f"',54+ 'foo',55+ '?.',56+ 'foo',57+ '=`',58+ 'foo',59+ '\'',60+ 'foo',61+ '\\"',62+ 'bar\\',63+ '"foo|bar>baz"',64+ '"(foo|bar>baz|foz)"',65+]);66+// Backslashes and double quotes need specific escaping on Windows, so their combinations are the trickiest.67+test('Arguments with backslashes', testRoundtrip, ['a\\b', 'a\\\\b', '\\', '\\\\', 'a\\', 'trailing\\']);68+test('Arguments with backslashes and double quotes', testRoundtrip, ['a\\"b', '\\"', 'a"\\', '\\\\"', '"\\\\"']);69+// Backslashes, double quotes and shell metacharacters combined in a single argument are the trickiest to escape on Windows.70+test('Arguments combining backslashes, quotes and metacharacters', testRoundtrip, ['a\\"&b', '\\"()\\', 'c\\\\"|d', '%x%\\', '">&<"']);71+test('Arguments with tabs and whitespace', testRoundtrip, ['a\tb', '\t', ' spaces ', ' ']);72+// Several consecutive empty and whitespace-only arguments must each be preserved as a distinct argument.73+test('Arguments that are empty or whitespace-only', testRoundtrip, ['', '', 'a', '', ' ', '\t', '']);74+test('Arguments that look like flags', testRoundtrip, ['-e', '--foo=bar', '--', '-']);75+test('Arguments with Unicode characters', testRoundtrip, ['café', '🎉', '日本語', 'naïve']);76+// eslint-disable-next-line no-template-curly-in-string77+test('Arguments with shell variable syntax', testRoundtrip, ['$HOME', '${x}', '~', 'a=b,c', '`whoami`']);78+// Very long arguments must not be truncated nor corrupted by the escaping.79+test('Very long arguments', testRoundtrip, ['a'.repeat(10_000), `${'b'.repeat(1000)}\\"${'c'.repeat(1000)}`]);80+// A long run of consecutive backslashes right before a double quote (or the end of the81+// argument) must be doubled as a whole. This is both the input a length-dependent escaping82+// bug corrupts and the one a naive regex backtracks quadratically over, so a correct83+// roundtrip here guards correctness and the single-pass linear escaping at once.84+test('Arguments with long runs of backslashes before quotes', testRoundtrip, [85+ `${'\\'.repeat(1000)}"`,86+ '\\'.repeat(1000),87+ `a${'\\'.repeat(500)}"b${'\\'.repeat(500)}`,88+]);89+// Runs of backslashes of every length from 1 to 6, each right before a double quote, then90+// each at the very end of the argument. The bug this guards against doubled only the last91+// backslash of a run instead of the whole run, so it corrupted every length above 1.92+// Passing each length as its own argument pins down exactly which lengths would break.93+const backslashRunArguments = [94+ ...Array.from({length: 6}, (_, index) => `${'\\'.repeat(index + 1)}"x`),95+ ...Array.from({length: 6}, (_, index) => `end${'\\'.repeat(index + 1)}`),96+];97+test('Arguments with backslash runs of every length', testRoundtrip, backslashRunArguments);98+// Consecutive double quotes must each be escaped independently, not collapsed nor paired.99+test('Arguments with consecutive double quotes', testRoundtrip, ['""', '"""', 'a""b', '""""']);100+// A line break can be passed as an argument to a directly executable file (unlike a `.cmd`101+// on Windows, see below). `echo-argv.js` prints its arguments as JSON, so this verifies the102+// line break stays within a single argument rather than splitting it in two.103+test('Line breaks are kept within a single argument for executables', async t => {104+ const commandArguments = ['a\nb', 'a\r\nb', 'c'];105+ const {stdout} = await execa('echo-argv.js', commandArguments);106+ t.deepEqual(JSON.parse(stdout), commandArguments);107+108+ const {stdout: stdoutSync} = execaSync('echo-argv.js', commandArguments);109+ t.deepEqual(JSON.parse(stdoutSync), commandArguments);110+});111+112+// A command can be resolved from different kinds of file paths. Forward slashes113+// work even on Windows, where they are normalized to backslashes.114+const testResolvesCommand = async (t, file, options) => {115+ const {stdout} = await execa(file, ['foo'], options);116+ t.is(stdout, 'foo');117+118+ const {stdout: stdoutSync} = execaSync(file, ['foo'], options);119+ t.is(stdoutSync, 'foo');120+};121+122+test('Runs a command given as an absolute path', testResolvesCommand, path.join(FIXTURES_DIRECTORY, 'echo.js'));123+test('Runs a command given as a relative path with a custom cwd', testResolvesCommand, './echo.js', {cwd: FIXTURES_DIRECTORY});124+test('Runs a command given as a relative POSIX-style subpath', testResolvesCommand, 'test/fixtures/echo.js');125+test('Runs a command whose path contains a space', testResolvesCommand, 'command with space.js');126+test('Runs a command whose absolute path contains a space', testResolvesCommand, path.join(FIXTURES_DIRECTORY, 'command with space.js'));127+128+// A shebang script can be run without explicitly prepending its interpreter.129+// This is emulated on Windows, where shebangs are not natively supported.130+// The whole test suite implicitly relies on this (e.g. `echo.js`), so we assert it explicitly.131+test('Runs a shebang script without specifying its interpreter', async t => {132+ const {stdout} = await execa('echo.js', ['foo']);133+ t.is(stdout, 'foo');134+135+ const {stdout: stdoutSync} = execaSync('echo.js', ['foo']);136+ t.is(stdoutSync, 'foo');137+});138+139+// A space between `#!` and the interpreter path (e.g. `#! /usr/bin/env node`) is a valid,140+// real-world shebang variation. The reimplemented shebang parser must trim it, otherwise141+// on Windows the interpreter would resolve as ` /usr/bin/env` and fail with ENOENT.142+test('Runs a shebang script with a space after the "#!"', async t => {143+ const {stdout} = await execa('echo-space-shebang.js', ['foo']);144+ t.is(stdout, 'foo');145+146+ const {stdout: stdoutSync} = execaSync('echo-space-shebang.js', ['foo']);147+ t.is(stdoutSync, 'foo');148+});149+150+// Neither the caller's arguments array nor its options object should be mutated,151+// whether or not a shell is used (each path clones the arguments internally).152+const testNoMutation = async (t, options) => {153+ const commandArguments = ['foo', 'bar'];154+ const optionsCopy = {...options};155+156+ await execa('echo.js', commandArguments, options);157+ t.deepEqual(commandArguments, ['foo', 'bar']);158+ t.deepEqual(options, optionsCopy);159+160+ execaSync('echo.js', commandArguments, options);161+ t.deepEqual(commandArguments, ['foo', 'bar']);162+ t.deepEqual(options, optionsCopy);163+};164+165+test('Does not mutate arguments nor options', testNoMutation, {});166+test('Does not mutate arguments nor options with a shell', testNoMutation, {shell: true});167+168+if (isWindows) {169+ // A bare command name without an extension is resolved using `PATHEXT`.170+ test('Resolves command extension using PATHEXT (sync)', t => {171+ const {stdout} = execaSync('hello');172+ t.is(stdout, 'Hello World');173+ });174+175+ // A `.cmd` file needs `cmd.exe`, so its forward-slash path must be normalized to176+ // backslashes, otherwise it fails with ENOENT.177+ test('Runs a .cmd file given as a relative POSIX-style subpath', async t => {178+ const {stdout} = await execa('fixtures/hello.cmd', {cwd: path.join(FIXTURES_DIRECTORY, '..')});179+ t.is(stdout, 'Hello World');180+ });181+182+ /*183+ Metacharacters are double-escaped for batch files, since `cmd.exe` interprets them once when the batch file is invoked and once when it re-expands the arguments with `%*`.184+ The `cmd`-shims npm generates in `node_modules/.bin/` are the canonical example.185+ */186+ const setupCmdShim = async () => {187+ const binaryDirectory = path.join(FIXTURES_DIRECTORY, 'node_modules', '.bin');188+ await mkdir(binaryDirectory, {recursive: true});189+ const shimPath = path.join(binaryDirectory, 'echo-cmd-shim.cmd');190+ await cp(path.join(FIXTURES_DIRECTORY, 'echo-cmd-shim.cmd'), shimPath);191+ return shimPath;192+ };193+194+ test('Double-escapes metacharacters for node_modules/.bin cmd-shims', async t => {195+ const shimPath = await setupCmdShim();196+ const commandArgument = '"(foo|bar>baz|foz)"';197+ const {stdout} = await execa(shimPath, [commandArgument]);198+ t.is(stdout, commandArgument);199+200+ const {stdout: stdoutSync} = execaSync(shimPath, [commandArgument]);201+ t.is(stdoutSync, commandArgument);202+ });203+}204+205+// On Windows, `.cmd`/`.bat` files are run through `cmd.exe`, which interprets several206+// characters specially. Those must be escaped in arguments, otherwise they could expand207+// variables or inject commands (the "BatBadBut" class of vulnerabilities). `echo-shim.cmd`208+// forwards its arguments to `echo.js`, so the subprocess prints back the exact209+// `process.argv` it received: each argument must arrive unchanged and inert.210+if (isWindows) {211+ const testEscaping = async (t, commandArgument) => {212+ const {stdout} = await execa('echo-shim.cmd', [commandArgument]);213+ t.is(stdout, commandArgument);214+215+ const {stdout: stdoutSync} = execaSync('echo-shim.cmd', [commandArgument]);216+ t.is(stdoutSync, commandArgument);217+ };218+219+ // A `%VAR%` argument must be passed literally, not expanded by `cmd.exe`.220+ test('Does not expand environment variables in arguments', testEscaping, '%PATH%');221+ // Delayed expansion (`!VAR!`) must not be interpreted either.222+ test('Does not expand delayed environment variables in arguments', testEscaping, '!PATH!');223+ // An `&` must not be interpreted as a command separator.224+ test('Does not allow command injection via `&` in arguments', testEscaping, 'a&b');225+ // A `|` must not be interpreted as a pipe.226+ test('Does not allow command injection via `|` in arguments', testEscaping, 'a|whoami');227+ // Redirections (`<`, `>`) must not be interpreted.228+ test('Does not allow command injection via redirections in arguments', testEscaping, 'a>b<c');229+ // Parentheses must not be interpreted as command grouping.230+ test('Does not allow command injection via parentheses in arguments', testEscaping, '(whoami)');231+ // A quote followed by an injected command must stay inert.232+ test('Does not allow command injection via nested quotes in arguments', testEscaping, '"& whoami &"');233+ // Double quotes must be preserved.234+ test('Preserves double quotes in arguments', testEscaping, 'a"b"c');235+ // Carets are the escape character in `cmd.exe` and must be passed literally.236+ test('Preserves carets in arguments', testEscaping, 'a^b^^c');237+ // Backslashes, including trailing ones, must be preserved next to quotes.238+ test('Preserves backslashes and double quotes in arguments', testEscaping, 'a\\"b\\\\"c\\');239+240+ // Every kind of tricky argument must also roundtrip through `cmd.exe` unchanged, not241+ // just be inert. Unlike `echo.js` (which resolves to `node.exe` and bypasses `cmd.exe`),242+ // `echo-shim.cmd` forces the `cmd.exe` escaping path. This mirrors the roundtrip tests243+ // above, but validates the `cmd.exe`-specific escaping rather than Node's native escaping.244+ const testCmdRoundtrip = async (t, commandArguments) => {245+ const expectedStdout = commandArguments.join('\n');246+247+ const {stdout} = await execa('echo-shim.cmd', commandArguments);248+ t.is(stdout, expectedStdout);249+250+ const {stdout: stdoutSync} = execaSync('echo-shim.cmd', commandArguments);251+ t.is(stdoutSync, expectedStdout);252+ };253+254+ // eslint-disable-next-line no-template-curly-in-string255+ test('Roundtrips shell metacharacters through cmd.exe', testCmdRoundtrip, ['()', '[]', '%!', '^', '<', '>', '|', ';', ',', '=', '`', '*', '?', '$HOME', '${x}', '~']);256+ test('Roundtrips backslashes and double quotes through cmd.exe', testCmdRoundtrip, ['a\\b', 'a\\\\b', 'a\\', 'a\\"b', '\\"', 'a"\\', '\\\\"', '"\\\\"']);257+ // Long backslash runs must also roundtrip through the `cmd.exe` escaping specifically,258+ // which is where the backslash-doubling actually runs. Kept modest to stay under the259+ // `cmd.exe` command-line length limit once the backslashes are doubled.260+ test('Roundtrips long backslash runs before quotes through cmd.exe', testCmdRoundtrip, [`${'\\'.repeat(200)}"`, '\\'.repeat(200), `a${'\\'.repeat(100)}"b`]);261+ // The per-length sweep must roundtrip through `cmd.exe` too, since the corrupted doubling262+ // is exactly what this escaping path performs.263+ test('Roundtrips backslash runs of every length through cmd.exe', testCmdRoundtrip, backslashRunArguments);264+ // Consecutive double quotes must survive the `cmd.exe` escaping, each escaped on its own.265+ test('Roundtrips consecutive double quotes through cmd.exe', testCmdRoundtrip, ['""', '"""', 'a""b', '""""']);266+ test('Roundtrips arguments with spaces through cmd.exe', testCmdRoundtrip, ['a b', ' '.repeat(3), 'foo bar baz', 'André Cruz']);267+268+ /*269+ `.bat` files re-expand their arguments through `cmd.exe` exactly like `.cmd` files, so they need the same double-escaping.270+ `echo-shim.bat` is the `.bat` twin of `echo-shim.cmd`.271+ */272+ const testBatEscaping = async (t, commandArgument) => {273+ const {stdout} = await execa('echo-shim.bat', [commandArgument]);274+ t.is(stdout, commandArgument);275+276+ const {stdout: stdoutSync} = execaSync('echo-shim.bat', [commandArgument]);277+ t.is(stdoutSync, commandArgument);278+ };279+280+ // The same nested-quote injection must stay inert when the batch file is a `.bat`.281+ test('Does not allow command injection via nested quotes in `.bat` arguments', testBatEscaping, '"& whoami &"');282+ // Metacharacters must survive the double `cmd.exe` expansion for `.bat` files too.283+ test('Roundtrips shell metacharacters through a `.bat` file', testBatEscaping, '(foo|bar>baz|foz)');284+ // A `.bat` file not in `node_modules/.bin/` must still be double-escaped, since the location is irrelevant: any batch file re-expands its arguments.285+ test('Does not expand environment variables in `.bat` arguments', testBatEscaping, '%PATH%');286+ // Backslashes, double quotes and metacharacters combined are the trickiest to escape, and must survive the double `cmd.exe` expansion of a `.bat` file intact.287+ test('Preserves backslashes, quotes and metacharacters in `.bat` arguments', testBatEscaping, 'a\\"&b\\\\"|c\\');288+ // Several tricky arguments passed together must each be double-escaped independently and arrive in order, not merged nor reordered.289+ test('Roundtrips multiple tricky arguments through a `.bat` file', async t => {290+ const commandArguments = ['a b', 'c&d', '"e"', 'f\\"g', '%h%'];291+ const expectedStdout = commandArguments.join('\n');292+293+ const {stdout} = await execa('echo-shim.bat', commandArguments);294+ t.is(stdout, expectedStdout);295+296+ const {stdout: stdoutSync} = execaSync('echo-shim.bat', commandArguments);297+ t.is(stdoutSync, expectedStdout);298+ });299+300+ // `cmd.exe` interprets CR and LF as command separators and provides no way to escape301+ // them, so those are rejected to prevent command injection.302+ test('Rejects arguments containing a line break', t => {303+ t.throws(() => execa('echo-shim.cmd', ['a\r\nb']), {instanceOf: TypeError, message: /line break/});304+ t.throws(() => execaSync('echo-shim.cmd', ['a\r\nb']), {instanceOf: TypeError, message: /line break/});305+ });306+307+ // The command itself is validated too, not just its arguments.308+ test('Rejects a command containing a line break', t => {309+ t.throws(() => execa('echo\r\nshim.cmd', []), {instanceOf: TypeError, message: /line break/});310+ t.throws(() => execaSync('echo\r\nshim.cmd', []), {instanceOf: TypeError, message: /line break/});311+ });312+313+ // A shell escapes the arguments itself, so the line break rejection does not apply.314+ test('Does not reject line breaks when using a shell', async t => {315+ await t.notThrowsAsync(execa('echo-shim.cmd', ['a\r\nb'], {shell: true, reject: false}));316+ t.notThrows(() => execaSync('echo-shim.cmd', ['a\r\nb'], {shell: true, reject: false}));317+ });318+}added:test/fixtures/echo-argv.js+4 added
1234#!/usr/bin/env nodeimport process from 'node:process';
console.log(JSON.stringify(process.argv.slice(2)));added:test/fixtures/echo-cmd-shim.cmd+7 added
1+@IF EXIST "%~dp0\node.exe" (2+ "%~dp0\node.exe" "%~dp0\..\..\echo.js" %*3+) ELSE (4+ @SETLOCAL5+ @SET PATHEXT=%PATHEXT:;.JS;=;%6+ node "%~dp0\..\..\echo.js" %*7+)added:test/fixtures/echo-shim.bat+7 added
1+@IF EXIST "%~dp0\node.exe" (2+ "%~dp0\node.exe" "%~dp0\echo.js" %*3+) ELSE (4+ @SETLOCAL5+ @SET PATHEXT=%PATHEXT:;.JS;=;%6+ node "%~dp0\echo.js" %*7+)added:test/fixtures/echo-shim.cmd+7 added
1+@IF EXIST "%~dp0\node.exe" (2+ "%~dp0\node.exe" "%~dp0\echo.js" %*3+) ELSE (4+ @SETLOCAL5+ @SET PATHEXT=%PATHEXT:;.JS;=;%6+ node "%~dp0\echo.js" %*7+)added:test/fixtures/echo-space-shebang.js+4 added
1234#! /usr/bin/env nodeimport process from 'node:process';
console.log(process.argv.slice(2).join('\n'));modified:package.json+2 added-3 removed
50 unmodified lines51 "zx"52 ],53 "dependencies": {54 "@sindresorhus/merge-streams": "^4.0.0",55- "cross-spawn": "^7.0.6",55 "figures": "^6.1.0",56 "get-stream": "^9.0.1",57 "human-signals": "^8.0.1",58 "is-plain-obj": "^4.1.0",59 "is-stream": "^4.0.1",60 "npm-run-path": "^6.0.0",61+ "path-key": "^4.0.0",62 "pretty-ms": "^9.3.0",63 "signal-exit": "^4.1.0",64 "strip-final-newline": "^4.0.0",65+ "which": "^7.0.0",66 "yoctocolors": "^2.1.2"67 },68 "devDependencies": {69 "@types/node": "^26.1.0",3 unmodified lines73 "is-in-ci": "^2.0.0",74 "is-running": "^2.1.0",75 "log-process-errors": "^12.0.1",76 "path-exists": "^5.0.0",76- "path-key": "^4.0.0",77 "tempfile": "^6.0.1",78 "tsd": "^0.33.0",79 "typescript": "^6.0.3",80- "which": "^7.0.0",80 "xo": "^3.0.2"81 },82 "c8": {83 "reporter": [47 unmodified linesmodified:readme.md+2 added-2 removed
2 unmodified lines3 <img alt="execa logo" src="media/logo.svg" width="400">4 </picture>5 <br>6 7-[](https://codecov.io/gh/sindresorhus/execa)7+[](https://app.codecov.io/gh/sindresorhus/execa)8 9 > Process execution for humans10 11 <br>54 unmodified lines66 - [Simple syntax](#simple-syntax): promises and [template strings](docs/execution.md#template-string-syntax), like [`zx`](docs/bash.md).67 - [Script](#script) interface.68 - [No escaping](docs/escaping.md) nor quoting needed. No risk of shell injection.69 - Execute [locally installed binaries](#local-binaries) without `npx`.70-- Improved [Windows support](docs/windows.md): [shebangs](docs/windows.md#shebang), [`PATHEXT`](https://ss64.com/nt/path.html#pathext), [graceful termination](#graceful-termination), [and more](https://github.com/moxystudio/node-cross-spawn?tab=readme-ov-file#why).70+- Improved [Windows support](docs/windows.md): [shebangs](docs/windows.md#shebang), [`PATHEXT`](https://ss64.com/nt/path.html#pathext), [graceful termination](#graceful-termination), [and more](docs/windows.md).71 - [Detailed errors](#detailed-error), [verbose mode](#verbose-mode) and [custom logging](#custom-logging), for [debugging](docs/debugging.md).72 - [Pipe multiple subprocesses](#pipe-multiple-subprocesses) better than in shells: retrieve [intermediate results](docs/pipe.md#result), use multiple [sources](docs/pipe.md#multiple-sources-1-destination)/[destinations](docs/pipe.md#1-source-multiple-destinations), [unpipe](docs/pipe.md#unpipe).73 - [Split](#split-into-text-lines) the output into text lines, or [iterate](#iterate-over-text-lines) progressively over them.74 - Strip [unnecessary newlines](docs/lines.md#newlines).387 unmodified lines