Skip to content
Myr

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

11 files+540 added−8 removed

modified:docs/windows.md+1 added-1 removed
added:lib/arguments/command-file.js+186 added
1import {openSync, readSync, closeSync} from 'node:fs';2import {Buffer} from 'node:buffer';3import path from 'node:path';4import process from 'node:process';5import which from 'which';6import pathKey from 'path-key';78/*9On 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*/11export 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};1415 // 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 }1920 return escapeWindowsCommand(parsed);21};2223// Only `.exe` and `.com` files can be spawned directly; anything else needs `cmd.exe`24const directlyExecutableRegExp = /\.(?:com|exe)$/i;2526// `.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 arguments27const batchFileRegExp = /\.(?:bat|cmd)$/i;2829const escapeWindowsCommand = parsed => {30 // Resolve the file to an absolute path, following its shebang to the interpreter if any31 const resolvedFile = resolveWithShebang(parsed);3233 // A directly executable file is spawned as-is, bypassing `cmd.exe` and its escaping34 if (resolvedFile !== undefined && directlyExecutableRegExp.test(resolvedFile)) {35 return parsed;36 }3738 /*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 }4546 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(' ')}"`;5152 // 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};6061// Resolve the command's absolute path, then, if it is a shebang script, resolve its interpreter instead, since Windows cannot run shebangs natively62const resolveWithShebang = parsed => {63 const resolvedFile = resolvePath(parsed);64 const interpreter = resolvedFile !== undefined && readShebang(resolvedFile);65 if (!interpreter) {66 return resolvedFile;67 }6869 // 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};7475// Search `PATH` for the command, first honoring `PATHEXT`, then ignoring it as a fallback76const resolvePath = parsed => resolveInCwd(parsed, false) || resolveInCwd(parsed, true);7778const resolveInCwd = (parsed, ignorePathExtension) => {79 const environment = parsed.options.env || process.env;8081 /*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.8384 `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 }9394 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};109110const SHEBANG_BYTE_LENGTH = 150;111112// Read the file's first bytes to find its shebang interpreter, if it has one113const readShebang = file => {114 const buffer = Buffer.alloc(SHEBANG_BYTE_LENGTH);115116 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 }126127 return parseShebang(buffer.toString());128};129130const shebangRegExp = /^#!(?<line>.*)/;131132/*133Extract the interpreter from a shebang line, e.g. `#!/usr/bin/env node` -> `node`.134*/135const parseShebang = contents => {136 const shebangLine = contents.match(shebangRegExp)?.groups.line.trim();137 if (!shebangLine) {138 return undefined;139 }140141 const [interpreterPath, argument] = shebangLine.split(' ');142 const interpreter = interpreterPath.split('/').at(-1);143 if (interpreter === 'env') {144 return argument;145 }146147 return argument ? `${interpreter} ${argument}` : interpreter;148};149150const lineBreakRegExp = /[\n\r]/;151152const 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};157158// See https://web.archive.org/web/20241220221102/https://www.robvanderwoude.com/escapechars.php159// eslint-disable-next-line regexp/sort-character-class-elements160const metaCharsRegExp = /[()\][%!^"`<>&|;, *?]/g;161162// Prefix every `cmd.exe` metacharacter with a caret to neutralize it163const escapeMetaChars = value => value.replaceAll(metaCharsRegExp, '^$&');164165const backslashRunRegExp = /\\+/g;166167const 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.170171 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.172173 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('"', '\\"');182183 // 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
added:test/arguments/command-resolution.js+318 added
1import {cp, mkdir} from 'node:fs/promises';2import path from 'node:path';3import process from 'node:process';4import test from 'ava';5import {execa, execaSync} from '../../index.js';6import {setFixtureDirectory, FIXTURES_DIRECTORY} from '../helpers/fixtures-directory.js';78setFixtureDirectory();910const isWindows = process.platform === 'win32';1112// 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.1920// `echo.js` prints `process.argv.slice(2).join('\n')`21const testRoundtrip = async (t, commandArguments) => {22 const expectedStdout = commandArguments.map(String).join('\n');2324 const {stdout} = await execa('echo.js', commandArguments);25 t.is(stdout, expectedStdout);2627 const {stdout: stdoutSync} = execaSync('echo.js', commandArguments);28 t.is(stdoutSync, expectedStdout);29};3031test('Empty arguments and arguments with spaces', testRoundtrip, ['foo', '', 'bar', 'André Cruz']);32test('Non-string arguments are coerced', testRoundtrip, [1234]);33test('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.67test('Arguments with backslashes', testRoundtrip, ['a\\b', 'a\\\\b', '\\', '\\\\', 'a\\', 'trailing\\']);68test('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.70test('Arguments combining backslashes, quotes and metacharacters', testRoundtrip, ['a\\"&b', '\\"()\\', 'c\\\\"|d', '%x%\\', '">&<"']);71test('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.73test('Arguments that are empty or whitespace-only', testRoundtrip, ['', '', 'a', '', ' ', '\t', '']);74test('Arguments that look like flags', testRoundtrip, ['-e', '--foo=bar', '--', '-']);75test('Arguments with Unicode characters', testRoundtrip, ['café', '🎉', '日本語', 'naïve']);76// eslint-disable-next-line no-template-curly-in-string77test('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.79test('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.84test('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.93const backslashRunArguments = [94 ...Array.from({length: 6}, (_, index) => `${'\\'.repeat(index + 1)}"x`),95 ...Array.from({length: 6}, (_, index) => `end${'\\'.repeat(index + 1)}`),96];97test('Arguments with backslash runs of every length', testRoundtrip, backslashRunArguments);98// Consecutive double quotes must each be escaped independently, not collapsed nor paired.99test('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.103test('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);107108 const {stdout: stdoutSync} = execaSync('echo-argv.js', commandArguments);109 t.deepEqual(JSON.parse(stdoutSync), commandArguments);110});111112// A command can be resolved from different kinds of file paths. Forward slashes113// work even on Windows, where they are normalized to backslashes.114const testResolvesCommand = async (t, file, options) => {115 const {stdout} = await execa(file, ['foo'], options);116 t.is(stdout, 'foo');117118 const {stdout: stdoutSync} = execaSync(file, ['foo'], options);119 t.is(stdoutSync, 'foo');120};121122test('Runs a command given as an absolute path', testResolvesCommand, path.join(FIXTURES_DIRECTORY, 'echo.js'));123test('Runs a command given as a relative path with a custom cwd', testResolvesCommand, './echo.js', {cwd: FIXTURES_DIRECTORY});124test('Runs a command given as a relative POSIX-style subpath', testResolvesCommand, 'test/fixtures/echo.js');125test('Runs a command whose path contains a space', testResolvesCommand, 'command with space.js');126test('Runs a command whose absolute path contains a space', testResolvesCommand, path.join(FIXTURES_DIRECTORY, 'command with space.js'));127128// 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.131test('Runs a shebang script without specifying its interpreter', async t => {132 const {stdout} = await execa('echo.js', ['foo']);133 t.is(stdout, 'foo');134135 const {stdout: stdoutSync} = execaSync('echo.js', ['foo']);136 t.is(stdoutSync, 'foo');137});138139// 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.142test('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');145146 const {stdout: stdoutSync} = execaSync('echo-space-shebang.js', ['foo']);147 t.is(stdoutSync, 'foo');148});149150// 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).152const testNoMutation = async (t, options) => {153 const commandArguments = ['foo', 'bar'];154 const optionsCopy = {...options};155156 await execa('echo.js', commandArguments, options);157 t.deepEqual(commandArguments, ['foo', 'bar']);158 t.deepEqual(options, optionsCopy);159160 execaSync('echo.js', commandArguments, options);161 t.deepEqual(commandArguments, ['foo', 'bar']);162 t.deepEqual(options, optionsCopy);163};164165test('Does not mutate arguments nor options', testNoMutation, {});166test('Does not mutate arguments nor options with a shell', testNoMutation, {shell: true});167168if (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 });174175 // 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 });181182 /*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 };193194 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);199200 const {stdout: stdoutSync} = execaSync(shimPath, [commandArgument]);201 t.is(stdoutSync, commandArgument);202 });203}204205// 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.210if (isWindows) {211 const testEscaping = async (t, commandArgument) => {212 const {stdout} = await execa('echo-shim.cmd', [commandArgument]);213 t.is(stdout, commandArgument);214215 const {stdout: stdoutSync} = execaSync('echo-shim.cmd', [commandArgument]);216 t.is(stdoutSync, commandArgument);217 };218219 // 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\\');239240 // 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');246247 const {stdout} = await execa('echo-shim.cmd', commandArguments);248 t.is(stdout, expectedStdout);249250 const {stdout: stdoutSync} = execaSync('echo-shim.cmd', commandArguments);251 t.is(stdoutSync, expectedStdout);252 };253254 // 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']);267268 /*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);275276 const {stdout: stdoutSync} = execaSync('echo-shim.bat', [commandArgument]);277 t.is(stdoutSync, commandArgument);278 };279280 // 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');292293 const {stdout} = await execa('echo-shim.bat', commandArguments);294 t.is(stdout, expectedStdout);295296 const {stdout: stdoutSync} = execaSync('echo-shim.bat', commandArguments);297 t.is(stdoutSync, expectedStdout);298 });299300 // `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 });306307 // 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 });312313 // 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
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
modified:package.json+2 added-3 removed
50 unmodified lines
51 "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 lines
73 "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 lines
modified:readme.md+2 added-2 removed
2 unmodified lines
3 <img alt="execa logo" src="media/logo.svg" width="400">4</picture>5<br>67[![Coverage Status](https://codecov.io/gh/sindresorhus/execa/branch/main/graph/badge.svg)](https://codecov.io/gh/sindresorhus/execa)7[![Coverage Status](https://codecov.io/gh/sindresorhus/execa/branch/main/graph/badge.svg)](https://app.codecov.io/gh/sindresorhus/execa)89> Process execution for humans1011<br>
54 unmodified lines
66- [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