import assert from 'node:assert/strict'; import path from 'node:path'; import process from 'node:process'; import test from 'node:test'; import { cp, mkdir, unlink, writeFile, } from 'node:fs/promises'; import {assertThrows, assertRejects} from '../helpers/assert.js'; import {execa, execaSync} from '../../index.js'; import {setFixtureDirectory, FIXTURES_DIRECTORY} from '../helpers/fixtures-directory.js'; setFixtureDirectory(); const isWindows = process.platform === 'win32'; // These tests cover the command resolution and argument escaping performed by // `lib/arguments/command-file.js`, which allows running scripts, `.cmd`/`.bat` files // and shebang scripts without a shell, and prevents command injection on Windows. // Most assertions use a roundtrip: an argument is passed in, the subprocess prints // its own `process.argv` back (see `test/fixtures/echo.js`), and we check it comes // back byte-identical. This exercises the escaping logic on whichever OS runs the // test, so Windows escaping is genuinely validated on CI. // `echo.js` prints `process.argv.slice(2).join('\n')` const testRoundtrip = async commandArguments => { const expectedStdout = commandArguments.map(String).join('\n'); const {stdout} = await execa('echo.js', commandArguments); assert.equal(stdout, expectedStdout); const {stdout: stdoutSync} = execaSync('echo.js', commandArguments); assert.equal(stdoutSync, expectedStdout); }; test('Empty arguments and arguments with spaces', () => testRoundtrip(['foo', '', 'bar', 'André Cruz'])); test('Non-string arguments are coerced', () => testRoundtrip([1234])); test('Arguments with shell special characters', () => testRoundtrip([ 'foo', '()', 'foo', '[]', 'foo', '%!', 'foo', '^<', 'foo', '>&', 'foo', '|;', 'foo', ', ', 'foo', '!=', 'foo', '\\*', 'foo', '"f"', 'foo', '?.', 'foo', '=`', 'foo', '\'', 'foo', '\\"', 'bar\\', '"foo|bar>baz"', '"(foo|bar>baz|foz)"', ])); // Backslashes and double quotes need specific escaping on Windows, so their combinations are the trickiest. test('Arguments with backslashes', () => testRoundtrip(['a\\b', 'a\\\\b', '\\', '\\\\', 'a\\', 'trailing\\'])); test('Arguments with backslashes and double quotes', () => testRoundtrip(['a\\"b', '\\"', 'a"\\', '\\\\"', '"\\\\"'])); // Backslashes, double quotes and shell metacharacters combined in a single argument are the trickiest to escape on Windows. test('Arguments combining backslashes, quotes and metacharacters', () => testRoundtrip(['a\\"&b', '\\"()\\', 'c\\\\"|d', '%x%\\', '">&<"'])); test('Arguments with tabs and whitespace', () => testRoundtrip(['a\tb', '\t', ' spaces ', ' '])); // Several consecutive empty and whitespace-only arguments must each be preserved as a distinct argument. test('Arguments that are empty or whitespace-only', () => testRoundtrip(['', '', 'a', '', ' ', '\t', ''])); test('Arguments that look like flags', () => testRoundtrip(['-e', '--foo=bar', '--', '-'])); test('Arguments with Unicode characters', () => testRoundtrip(['café', '🎉', '日本語', 'naïve'])); // eslint-disable-next-line no-template-curly-in-string test('Arguments with shell variable syntax', () => testRoundtrip(['$HOME', '${x}', '~', 'a=b,c', '`whoami`'])); // Very long arguments must not be truncated nor corrupted by the escaping. test('Very long arguments', () => testRoundtrip(['a'.repeat(10_000), `${'b'.repeat(1000)}\\"${'c'.repeat(1000)}`])); // A long run of consecutive backslashes right before a double quote (or the end of the // argument) must be doubled as a whole. This is both the input a length-dependent escaping // bug corrupts and the one a naive regex backtracks quadratically over, so a correct // roundtrip here guards correctness and the single-pass linear escaping at once. test('Arguments with long runs of backslashes before quotes', () => testRoundtrip([ `${'\\'.repeat(1000)}"`, '\\'.repeat(1000), `a${'\\'.repeat(500)}"b${'\\'.repeat(500)}`, ])); // Runs of backslashes of every length from 1 to 6, each right before a double quote, then // each at the very end of the argument. The bug this guards against doubled only the last // backslash of a run instead of the whole run, so it corrupted every length above 1. // Passing each length as its own argument pins down exactly which lengths would break. const backslashRunArguments = [ ...Array.from({length: 6}, (_, index) => `${'\\'.repeat(index + 1)}"x`), ...Array.from({length: 6}, (_, index) => `end${'\\'.repeat(index + 1)}`), ]; test('Arguments with backslash runs of every length', () => testRoundtrip(backslashRunArguments)); // Consecutive double quotes must each be escaped independently, not collapsed nor paired. test('Arguments with consecutive double quotes', () => testRoundtrip(['""', '"""', 'a""b', '""""'])); // A line break can be passed as an argument to a directly executable file (unlike a `.cmd` // on Windows, see below). `echo-argv.js` prints its arguments as JSON, so this verifies the // line break stays within a single argument rather than splitting it in two. test('Line breaks are kept within a single argument for executables', async () => { const commandArguments = ['a\nb', 'a\r\nb', 'c']; const {stdout} = await execa('echo-argv.js', commandArguments); assert.deepEqual(JSON.parse(stdout), commandArguments); const {stdout: stdoutSync} = execaSync('echo-argv.js', commandArguments); assert.deepEqual(JSON.parse(stdoutSync), commandArguments); }); // A command can be resolved from different kinds of file paths. Forward slashes // work even on Windows, where they are normalized to backslashes. const testResolvesCommand = async (file, options) => { const {stdout} = await execa(file, ['foo'], options); assert.equal(stdout, 'foo'); const {stdout: stdoutSync} = execaSync(file, ['foo'], options); assert.equal(stdoutSync, 'foo'); }; test('Runs a command given as an absolute path', () => testResolvesCommand(path.join(FIXTURES_DIRECTORY, 'echo.js'))); test('Runs a command given as a relative path with a custom cwd', () => testResolvesCommand('./echo.js', {cwd: FIXTURES_DIRECTORY})); test('Runs a command given as a relative POSIX-style subpath', () => testResolvesCommand('test/fixtures/echo.js')); test('Runs a command whose path contains a space', () => testResolvesCommand('command with space.js')); test('Runs a command whose absolute path contains a space', () => testResolvesCommand(path.join(FIXTURES_DIRECTORY, 'command with space.js'))); // A shebang script can be run without explicitly prepending its interpreter. // This is emulated on Windows, where shebangs are not natively supported. // The whole test suite implicitly relies on this (e.g. `echo.js`), so we assert it explicitly. test('Runs a shebang script without specifying its interpreter', async () => { const {stdout} = await execa('echo.js', ['foo']); assert.equal(stdout, 'foo'); const {stdout: stdoutSync} = execaSync('echo.js', ['foo']); assert.equal(stdoutSync, 'foo'); }); // A space between `#!` and the interpreter path (e.g. `#! /usr/bin/env node`) is a valid, // real-world shebang variation. The reimplemented shebang parser must trim it, otherwise // on Windows the interpreter would resolve as ` /usr/bin/env` and fail with ENOENT. test('Runs a shebang script with a space after the "#!"', async () => { const {stdout} = await execa('echo-space-shebang.js', ['foo']); assert.equal(stdout, 'foo'); const {stdout: stdoutSync} = execaSync('echo-space-shebang.js', ['foo']); assert.equal(stdoutSync, 'foo'); }); /* Windows does not support shebangs natively, so Execa parses them itself, by reading the file's first bytes into a fixed-size buffer. A file which only contains a shebang line, without a trailing newline, is shorter than that buffer, which is zero-filled. Only the bytes actually read must be parsed, otherwise the interpreter would include those `\0` characters, which does not resolve to any file. The file is created by the test since Unix cannot execute it, so it must not be used by any other test. */ if (isWindows) { test('Runs a shebang script shorter than the shebang buffer', async t => { const filePath = path.join(FIXTURES_DIRECTORY, 'shebang-only.js'); await writeFile(filePath, '#!/usr/bin/env node'); t.after(() => unlink(filePath)); const {exitCode, stdout} = await execa('shebang-only.js'); assert.equal(exitCode, 0); assert.equal(stdout, ''); }); } // Neither the caller's arguments array nor its options object should be mutated, // whether or not a shell is used (each path clones the arguments internally). const testNoMutation = async options => { const commandArguments = ['foo', 'bar']; const optionsCopy = {...options}; await execa('echo.js', commandArguments, options); assert.deepEqual(commandArguments, ['foo', 'bar']); assert.deepEqual(options, optionsCopy); execaSync('echo.js', commandArguments, options); assert.deepEqual(commandArguments, ['foo', 'bar']); assert.deepEqual(options, optionsCopy); }; test('Does not mutate arguments nor options', () => testNoMutation({})); test('Does not mutate arguments nor options with a shell', () => testNoMutation({shell: true})); if (isWindows) { const nodeOnlyOptions = { extendEnv: false, env: { Path: path.dirname(process.execPath), PathExt: '.EXE', }, }; // A bare command name without an extension is resolved using `PATHEXT`. test('Resolves command extension using PATHEXT (sync)', () => { const {stdout} = execaSync('hello'); assert.equal(stdout, 'Hello World'); }); test('Uses PATHEXT extension order for direct executables', async t => { const binaryDirectory = path.join(FIXTURES_DIRECTORY, 'node_modules', '.bin'); await mkdir(binaryDirectory, {recursive: true}); const command = 'node-extension-order'; const executablePath = path.join(binaryDirectory, `${command}.exe`); const comPath = path.join(binaryDirectory, `${command}.com`); await Promise.all([ cp(process.execPath, executablePath), cp(process.execPath, comPath), ]); t.after(async () => { await Promise.all([unlink(executablePath), unlink(comPath)]); }); const options = { preferLocal: true, localDir: FIXTURES_DIRECTORY, extendEnv: false, env: { Path: path.dirname(process.execPath), PathExt: '.EXE;.COM', }, }; const nodeExpression = 'JSON.stringify({executablePath: process.execPath, argv0: process.argv0})'; const {stdout} = await execa(command, ['--print', nodeExpression], options); const {executablePath: actualExecutablePath, argv0} = JSON.parse(stdout); assert.equal(actualExecutablePath.toLowerCase(), executablePath.toLowerCase()); assert.equal(argv0, command); const {stdout: stdoutSync} = execaSync(command, ['--print', nodeExpression], options); const {executablePath: actualExecutablePathSync, argv0: argv0Sync} = JSON.parse(stdoutSync); assert.equal(actualExecutablePathSync.toLowerCase(), executablePath.toLowerCase()); assert.equal(argv0Sync, command); }); test('Respects NoDefaultCurrentDirectoryInExePath', async t => { const binaryDirectory = path.join(FIXTURES_DIRECTORY, 'node_modules', '.bin'); await mkdir(binaryDirectory, {recursive: true}); const command = 'node-current-directory'; const currentDirectoryExecutable = path.join(FIXTURES_DIRECTORY, `${command}.exe`); const pathExecutable = path.join(binaryDirectory, `${command}.exe`); await Promise.all([ cp(process.execPath, currentDirectoryExecutable), cp(process.execPath, pathExecutable), ]); const environmentName = 'NoDefaultCurrentDirectoryInExePath'; const originalValue = process.env[environmentName]; delete process.env[environmentName]; t.after(async () => { if (originalValue === undefined) { delete process.env[environmentName]; } else { process.env[environmentName] = originalValue; } await Promise.all([unlink(currentDirectoryExecutable), unlink(pathExecutable)]); }); const options = { cwd: FIXTURES_DIRECTORY, extendEnv: false, env: { Path: binaryDirectory, PathExt: '.EXE', }, }; const {stdout: currentDirectoryStdout} = await execa(command, ['--print', 'process.execPath'], options); assert.equal(currentDirectoryStdout.toLowerCase(), currentDirectoryExecutable.toLowerCase()); const {stdout: currentDirectoryStdoutSync} = execaSync(command, ['--print', 'process.execPath'], options); assert.equal(currentDirectoryStdoutSync.toLowerCase(), currentDirectoryExecutable.toLowerCase()); process.env[environmentName] = '1'; const {stdout} = await execa(command, ['--print', 'process.execPath'], options); assert.equal(stdout.toLowerCase(), pathExecutable.toLowerCase()); const {stdout: stdoutSync} = execaSync(command, ['--print', 'process.execPath'], options); assert.equal(stdoutSync.toLowerCase(), pathExecutable.toLowerCase()); }); test('Uses the resolved batch file when current-directory search is disabled', async t => { const binaryDirectory = path.join(FIXTURES_DIRECTORY, 'node_modules', '.bin'); await mkdir(binaryDirectory, {recursive: true}); const command = 'batch-current-directory'; const currentDirectoryBatchFile = path.join(FIXTURES_DIRECTORY, `${command}.cmd`); const pathBatchFile = path.join(binaryDirectory, `${command}.cmd`); await Promise.all([ writeFile(currentDirectoryBatchFile, '@echo current directory'), writeFile(pathBatchFile, '@echo PATH'), ]); const environmentName = 'NoDefaultCurrentDirectoryInExePath'; const originalValue = process.env[environmentName]; delete process.env[environmentName]; t.after(async () => { if (originalValue === undefined) { delete process.env[environmentName]; } else { process.env[environmentName] = originalValue; } await Promise.all([unlink(currentDirectoryBatchFile), unlink(pathBatchFile)]); }); const options = { cwd: FIXTURES_DIRECTORY, extendEnv: false, env: { Path: binaryDirectory, PathExt: '.CMD', [environmentName]: '', }, }; const {stdout} = await execa(command, options); assert.equal(stdout, 'PATH'); const {stdout: stdoutSync} = execaSync(command, options); assert.equal(stdoutSync, 'PATH'); delete options.env[environmentName]; process.env[environmentName] = ''; const {stdout: parentEnvironmentStdout} = await execa(command, options); assert.equal(parentEnvironmentStdout, 'PATH'); const {stdout: parentEnvironmentStdoutSync} = execaSync(command, options); assert.equal(parentEnvironmentStdoutSync, 'PATH'); }); test('Does not search PATH for drive-relative commands', async t => { const binaryDirectory = path.join(FIXTURES_DIRECTORY, 'node_modules', '.bin'); await mkdir(binaryDirectory, {recursive: true}); const commandName = 'node-drive-relative'; const pathExecutable = path.join(binaryDirectory, `${commandName}.exe`); await cp(process.execPath, pathExecutable); t.after(async () => { await unlink(pathExecutable); }); const drive = path.parse(FIXTURES_DIRECTORY).root.slice(0, 2); const command = `${drive}${commandName}`; const options = { cwd: FIXTURES_DIRECTORY, extendEnv: false, env: { Path: binaryDirectory, PathExt: '.EXE', }, }; await assertRejects(execa(command, [], options)); assertThrows(() => execaSync(command, [], options)); }); // A `.cmd` file needs `cmd.exe`, so its forward-slash path must be normalized to // backslashes, otherwise it fails with ENOENT. test('Runs a .cmd file given as a relative POSIX-style subpath', async () => { const {stdout} = await execa('fixtures/hello.cmd', {cwd: path.join(FIXTURES_DIRECTORY, '..')}); assert.equal(stdout, 'Hello World'); }); /* Metacharacters must survive `cmd.exe` interpreting them twice for batch files: once when the batch file is invoked and once when it re-expands the arguments with `%*`. The `cmd`-shims npm generates in `node_modules/.bin/` are the canonical example. */ const setupCmdShim = async () => { const binaryDirectory = path.join(FIXTURES_DIRECTORY, 'node_modules', '.bin'); await mkdir(binaryDirectory, {recursive: true}); const shimPath = path.join(binaryDirectory, 'echo-cmd-shim.cmd'); await cp(path.join(FIXTURES_DIRECTORY, 'echo-cmd-shim.cmd'), shimPath); return shimPath; }; test('Escapes metacharacters for node_modules/.bin cmd-shims', async () => { const shimPath = await setupCmdShim(); const commandArgument = '"(foo|bar>baz|foz)"'; const {stdout} = await execa(shimPath, [commandArgument]); assert.equal(stdout, commandArgument); const {stdout: stdoutSync} = execaSync(shimPath, [commandArgument]); assert.equal(stdoutSync, commandArgument); }); test('Escapes metacharacters for explicit batch files excluded from PATHEXT', async () => { const commandArgument = '"& whoami &"'; const command = path.join(FIXTURES_DIRECTORY, 'echo-shim.cmd'); const {stdout} = await execa(command, [commandArgument], nodeOnlyOptions); assert.equal(stdout, commandArgument); const {stdout: stdoutSync} = execaSync(command, [commandArgument], nodeOnlyOptions); assert.equal(stdoutSync, commandArgument); }); test('Runs an explicit shebang script excluded from PATHEXT', async () => { const command = path.join(FIXTURES_DIRECTORY, 'echo.js'); await testResolvesCommand(command, nodeOnlyOptions); }); test('Escapes metacharacters for preferLocal cmd-shims', async () => { await setupCmdShim(); const commandArgument = 'a&whoami'; const originalPathExt = process.env.PATHEXT; process.env.PATHEXT = '.EXE'; const options = { preferLocal: true, localDir: FIXTURES_DIRECTORY, extendEnv: false, env: { Path: path.dirname(process.execPath), PathExt: '.EXE;.CMD', }, }; try { const {stdout} = await execa('echo-cmd-shim', [commandArgument], options); assert.equal(stdout, commandArgument); const {stdout: stdoutSync} = execaSync('echo-cmd-shim', [commandArgument], options); assert.equal(stdoutSync, commandArgument); } finally { if (originalPathExt === undefined) { delete process.env.PATHEXT; } else { process.env.PATHEXT = originalPathExt; } } }); } // On Windows, `.cmd`/`.bat` files are run through `cmd.exe`, which interprets several // characters specially. Those must be escaped in arguments, otherwise they could expand // variables or inject commands (the "BatBadBut" class of vulnerabilities). `echo-shim.cmd` // forwards its arguments to `echo.js`, so the subprocess prints back the exact // `process.argv` it received: each argument must arrive unchanged and inert. if (isWindows) { const testEscaping = async commandArgument => { const {stdout} = await execa('echo-shim.cmd', [commandArgument]); assert.equal(stdout, commandArgument); const {stdout: stdoutSync} = execaSync('echo-shim.cmd', [commandArgument]); assert.equal(stdoutSync, commandArgument); }; // A `%VAR%` argument must be passed literally, not expanded by `cmd.exe`. test('Does not expand environment variables in arguments', () => testEscaping('%PATH%')); // Delayed expansion (`!VAR!`) must not be interpreted either. test('Does not expand delayed environment variables in arguments', () => testEscaping('!PATH!')); // An `&` must not be interpreted as a command separator. test('Does not allow command injection via `&` in arguments', () => testEscaping('a&b')); // A `|` must not be interpreted as a pipe. test('Does not allow command injection via `|` in arguments', () => testEscaping('a|whoami')); // Redirections (`<`, `>`) must not be interpreted. test('Does not allow command injection via redirections in arguments', () => testEscaping('a>b testEscaping('(whoami)')); // A quote followed by an injected command must stay inert. test('Does not allow command injection via nested quotes in arguments', () => testEscaping('"& whoami &"')); // Double quotes must be preserved. test('Preserves double quotes in arguments', () => testEscaping('a"b"c')); // Carets are the escape character in `cmd.exe` and must be passed literally. test('Preserves carets in arguments', () => testEscaping('a^b^^c')); // Backslashes, including trailing ones, must be preserved next to quotes. test('Preserves backslashes and double quotes in arguments', () => testEscaping('a\\"b\\\\"c\\')); // Every kind of tricky argument must also roundtrip through `cmd.exe` unchanged, not // just be inert. Unlike `echo.js` (which resolves to `node.exe` and bypasses `cmd.exe`), // `echo-shim.cmd` forces the `cmd.exe` escaping path. This mirrors the roundtrip tests // above, but validates the `cmd.exe`-specific escaping rather than Node's native escaping. const testCmdRoundtrip = async commandArguments => { const expectedStdout = commandArguments.join('\n'); const {stdout} = await execa('echo-shim.cmd', commandArguments); assert.equal(stdout, expectedStdout); const {stdout: stdoutSync} = execaSync('echo-shim.cmd', commandArguments); assert.equal(stdoutSync, expectedStdout); }; // eslint-disable-next-line no-template-curly-in-string test('Roundtrips shell metacharacters through cmd.exe', () => testCmdRoundtrip(['()', '[]', '%!', '^', '<', '>', '|', ';', ',', '=', '`', '*', '?', '$HOME', '${x}', '~'])); test('Roundtrips backslashes and double quotes through cmd.exe', () => testCmdRoundtrip(['a\\b', 'a\\\\b', 'a\\', 'a\\"b', '\\"', 'a"\\', '\\\\"', '"\\\\"'])); // Long backslash runs must also roundtrip through the `cmd.exe` escaping specifically, // which is where the backslash-doubling actually runs. Kept modest to stay under the // `cmd.exe` command-line length limit once the backslashes are doubled. test('Roundtrips long backslash runs before quotes through cmd.exe', () => testCmdRoundtrip([`${'\\'.repeat(200)}"`, '\\'.repeat(200), `a${'\\'.repeat(100)}"b`])); // The per-length sweep must roundtrip through `cmd.exe` too, since the corrupted doubling // is exactly what this escaping path performs. test('Roundtrips backslash runs of every length through cmd.exe', () => testCmdRoundtrip(backslashRunArguments)); // Consecutive double quotes must survive the `cmd.exe` escaping, each escaped on its own. test('Roundtrips consecutive double quotes through cmd.exe', () => testCmdRoundtrip(['""', '"""', 'a""b', '""""'])); test('Roundtrips arguments with spaces through cmd.exe', () => testCmdRoundtrip(['a b', ' '.repeat(3), 'foo bar baz', 'André Cruz'])); /* `.bat` files re-expand their arguments through `cmd.exe` exactly like `.cmd` files, so they need the same escaping. `echo-shim.bat` is the `.bat` twin of `echo-shim.cmd`. */ const testBatEscaping = async commandArgument => { const {stdout} = await execa('echo-shim.bat', [commandArgument]); assert.equal(stdout, commandArgument); const {stdout: stdoutSync} = execaSync('echo-shim.bat', [commandArgument]); assert.equal(stdoutSync, commandArgument); }; // The same nested-quote injection must stay inert when the batch file is a `.bat`. test('Does not allow command injection via nested quotes in `.bat` arguments', () => testBatEscaping('"& whoami &"')); // Metacharacters must survive the double `cmd.exe` expansion for `.bat` files too. test('Roundtrips shell metacharacters through a `.bat` file', () => testBatEscaping('(foo|bar>baz|foz)')); // A `.bat` file not in `node_modules/.bin/` must still be escaped against the double expansion, since the location is irrelevant: any batch file can re-expand its arguments. test('Does not expand environment variables in `.bat` arguments', () => testBatEscaping('%PATH%')); // Backslashes, double quotes and metacharacters combined are the trickiest to escape, and must survive the double `cmd.exe` expansion of a `.bat` file intact. test('Preserves backslashes, quotes and metacharacters in `.bat` arguments', () => testBatEscaping('a\\"&b\\\\"|c\\')); // Several tricky arguments passed together must each be escaped independently and arrive in order, not merged nor reordered. test('Roundtrips multiple tricky arguments through a `.bat` file', async () => { const commandArguments = ['a b', 'c&d', '"e"', 'f\\"g', '%h%']; const expectedStdout = commandArguments.join('\n'); const {stdout} = await execa('echo-shim.bat', commandArguments); assert.equal(stdout, expectedStdout); const {stdout: stdoutSync} = execaSync('echo-shim.bat', commandArguments); assert.equal(stdoutSync, expectedStdout); }); /* Unlike cmd-shims, some batch files read their own arguments with `%1` or `%~1` instead of forwarding them with `%*`, like Maven's `mvn.cmd`. `read-arguments.cmd` prints its first argument, then its second one when the first one is `-f`. `ECHO` ends lines with CRLF. */ const testReadArguments = async (commandArguments, expectedLines) => { const {stdout} = await execa('read-arguments.cmd', commandArguments); assert.deepEqual(stdout.split('\r\n'), expectedLines); const {stdout: stdoutSync} = execaSync('read-arguments.cmd', commandArguments); assert.deepEqual(stdoutSync.split('\r\n'), expectedLines); }; test('Passes arguments to batch files reading them with `%~1`', () => testReadArguments(['-f', 'C:\\repo\\pom.xml'], ['first is -f', 'file is "C:\\repo\\pom.xml"'])); test('Passes metacharacters to batch files reading them with `%~1`', () => testReadArguments(['-f', 'C:\\my repo\\a&b|c%PATH%.xml'], ['first is -f', 'file is "C:\\my repo\\a&b|c%PATH%.xml"'])); // Like Rust, only arguments that need quoting are quoted, so `%1` matches what the user passed, like when run from a terminal test('Only quotes arguments that need it for batch files reading them with `%1`', () => testReadArguments(['a b'], ['first is "a b"'])); // `cmd.exe` interprets CR and LF as command separators and provides no way to escape // them, so those are rejected to prevent command injection. test('Rejects arguments containing a line break', () => { assertThrows(() => execa('echo-shim.cmd', ['a\r\nb']), {instanceOf: TypeError, message: /line break/}); assertThrows(() => execaSync('echo-shim.cmd', ['a\r\nb']), {instanceOf: TypeError, message: /line break/}); }); // The command itself is validated too, not just its arguments. test('Rejects a command containing a line break', () => { assertThrows(() => execa('echo\r\nshim.cmd', []), {instanceOf: TypeError, message: /line break/}); assertThrows(() => execaSync('echo\r\nshim.cmd', []), {instanceOf: TypeError, message: /line break/}); }); // A shell escapes the arguments itself, so the line break rejection does not apply. test('Does not reject line breaks when using a shell', async () => { await assert.doesNotReject(execa('echo-shim.cmd', ['a\r\nb'], {shell: true, reject: false})); assert.doesNotThrow(() => execaSync('echo-shim.cmd', ['a\r\nb'], {shell: true, reject: false})); }); }