Skip to content
Myr

command-file.js

This file

Path

lib/arguments/command-file.js

233 lines · 11.6 KiB · JavaScript

Last changed by

Fix arguments of Windows batch files that read them with `%~1`Sindre Sorhusbefore adoption93bddc4

History of this file

Take it

Move away from `cross-spawn` (#1251)Sindre Sorhusbefore adoption4cafc3f

lines 1–4why, one step back
1import {openSync, readSync, closeSync} from 'node:fs';
2import {Buffer} from 'node:buffer';3import path from 'node:path';4import process from 'node:process';

Use `which-command` instead of `which` (#1253)Sindre Sorhusbefore adoption9a7a162

line 5why, one step back
5import {whichCommandSync} from 'which-command';

Move away from `cross-spawn` (#1251)Sindre Sorhusbefore adoption4cafc3f

lines 6–14why, one step back
6
7/*8On 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.9*/10export const parseCommandFile = (file, commandArguments, options) => {11 // The arguments are cloned since a shebang interpreter might be prepended below, which must not mutate the caller's array12 const parsed = {file, commandArguments: [...commandArguments], options};1314 // Under a shell, or on Unix, the OS resolves the file and escapes the arguments itself

TweaksSindre Sorhusbefore adoption698a1b8

line 15why, one step back
15 return options.shell || process.platform !== 'win32' ? parsed : escapeWindowsCommand(parsed);

Move away from `cross-spawn` (#1251)Sindre Sorhusbefore adoption4cafc3f

lines 16–24why, one step back
16};
1718// Only `.exe` and `.com` files can be spawned directly; anything else needs `cmd.exe`19const directlyExecutableRegExp = /\.(?:com|exe)$/i;2021const escapeWindowsCommand = parsed => {22 // Resolve the file to an absolute path, following its shebang to the interpreter if any23 const resolvedFile = resolveWithShebang(parsed);24

Fix `preferLocal` argument escaping edge-case on Windows (#1259)Sindre Sorhusbefore adoptione771733

line 25why, one step back
25 // A directly executable file is spawned by its resolved path, bypassing `cmd.exe` and its escaping

Move away from `cross-spawn` (#1251)Sindre Sorhusbefore adoption4cafc3f

line 26why, one step back
26 if (resolvedFile !== undefined && directlyExecutableRegExp.test(resolvedFile)) {

Fix `preferLocal` argument escaping edge-case on Windows (#1259)Sindre Sorhusbefore adoptione771733

lines 27–31why, one step back
27 if (parsed.options.argv0 === undefined) {
28 parsed.options.argv0 = parsed.file;29 }3031 parsed.file = resolvedFile;

Move away from `cross-spawn` (#1251)Sindre Sorhusbefore adoption4cafc3f

lines 32–42why, one step back
32 return parsed;
33 }3435 /*36 `cmd.exe` treats CR and LF as command separators and offers no way to escape them, so allowing either would enable command injection.37 Reject them instead.38 */39 for (const value of [parsed.file, ...parsed.commandArguments]) {40 assertNoLineBreak(value);41 }42

Fix arguments of Windows batch files that read them with `%~1`Sindre Sorhusbefore adoption93bddc4

lines 43–47why, one step back
43 /*
44 POSIX separators must become Windows ones (`foo/bar` -> `foo\bar`), otherwise resolution always fails with ENOENT.4546 Unlike Rust, which quotes the batch file's path, the file is caret-escaped. `cmd.exe` only interprets it once, and the file might not be resolved, for example when it is a `cmd.exe` builtin, which would not run if quoted.47 */

Fix `preferLocal` argument escaping edge-case on Windows (#1259)Sindre Sorhusbefore adoptione771733

line 48why, one step back
48 const escapedFile = escapeMetaChars(path.normalize(resolvedFile ?? parsed.file));

Fix arguments of Windows batch files that read them with `%~1`Sindre Sorhusbefore adoption93bddc4

line 49why, one step back
49 const escapedArguments = parsed.commandArguments.map(argument => escapeArgument(argument));

Move away from `cross-spawn` (#1251)Sindre Sorhusbefore adoption4cafc3f

lines 50–55why, one step back
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',

Fix arguments of Windows batch files that read them with `%~1`Sindre Sorhusbefore adoption93bddc4

lines 56–57why, one step back
56 // `/e:on` enables the command extensions the `%` escaping relies on, and `/v:off` disables delayed expansion so `!` is literal, even when the registry changes either default
57 commandArguments: ['/d', '/e:on', '/v:off', '/s', '/c', commandLine],

Move away from `cross-spawn` (#1251)Sindre Sorhusbefore adoption4cafc3f

lines 58–75why, one step back
58 options: parsed.options,
59 };60};6162// Resolve the command's absolute path, then, if it is a shebang script, resolve its interpreter instead, since Windows cannot run shebangs natively63const resolveWithShebang = parsed => {64 const resolvedFile = resolvePath(parsed);65 const interpreter = resolvedFile !== undefined && readShebang(resolvedFile);66 if (!interpreter) {67 return resolvedFile;68 }6970 // Run the interpreter with the script as its first argument, then resolve the interpreter's own path71 parsed.commandArguments.unshift(resolvedFile);72 parsed.file = interpreter;73 return resolvePath(parsed);74};75

Use `which-command` instead of `which` (#1253)Sindre Sorhusbefore adoption9a7a162

lines 76–77why, one step back
76// Search `PATH` for the command, resolving its Windows executable extension via `PATHEXT`
77const resolvePath = parsed => {

Move away from `cross-spawn` (#1251)Sindre Sorhusbefore adoption4cafc3f

line 78why, one step back
78 const environment = parsed.options.env || process.env;

Fix `preferLocal` argument escaping edge-case on Windows (#1259)Sindre Sorhusbefore adoptione771733

lines 79–119why, one step back
79 const cwd = parsed.options.cwd ?? process.cwd();
80 const environmentPathExt = getWindowsEnvironmentValue(environment, 'PATHEXT');81 const commandExtension = path.extname(parsed.file);82 // Commands with an explicit extension must be tried verbatim so shebang scripts work even when their extension is excluded from PATHEXT.83 const pathExt = commandExtension === '' ? environmentPathExt : `${commandExtension}${path.delimiter}${environmentPathExt ?? ''}`;84 if (hasWindowsPathSeparator(parsed.file)) {85 return whichCommandSync(path.resolve(cwd, parsed.file), {cwd, pathExt});86 }8788 const searchPath = getWindowsEnvironmentValue(environment, 'PATH') ?? getWindowsEnvironmentValue(process.env, 'PATH') ?? '';89 const resolveOptions = {90 cwd,91 path: searchPath,92 pathExt,93 };9495 return shouldSearchCurrentDirectory(environment) ? whichCommandSync(parsed.file, resolveOptions) : resolvePathDirectories(parsed.file, resolveOptions);96};9798const hasWindowsPathSeparator = file => file.includes('/') || file.includes('\\') || file.includes(':');99100const shouldSearchCurrentDirectory = environment => getWindowsEnvironmentValue(process.env, 'NODEFAULTCURRENTDIRECTORYINEXEPATH') === undefined && getWindowsEnvironmentValue(environment, 'NODEFAULTCURRENTDIRECTORYINEXEPATH') === undefined;101102const resolvePathDirectories = (file, {cwd, path: searchPath, pathExt}) => {103 for (const directory of searchPath.split(path.delimiter)) {104 const unquotedDirectory = directory.length > 1 && directory.startsWith('"') && directory.endsWith('"') ? directory.slice(1, -1) : directory;105 if (unquotedDirectory === '') {106 continue;107 }108109 const resolvedFile = whichCommandSync(path.resolve(cwd, unquotedDirectory, file), {cwd, pathExt});110 if (resolvedFile !== undefined) {111 return resolvedFile;112 }113 }114};115116// Node sorts Windows environment keys and uses the first case-insensitive match when spawning.117const getWindowsEnvironmentValue = (environment, name) => {118 const environmentKey = Object.keys(environment).sort().find(key => key.toUpperCase() === name);119 return environmentKey === undefined ? undefined : environment[environmentKey];

Move away from `cross-spawn` (#1251)Sindre Sorhusbefore adoption4cafc3f

lines 120–126why, one step back
120};
121122const SHEBANG_BYTE_LENGTH = 150;123124// Read the file's first bytes to find its shebang interpreter, if it has one125const readShebang = file => {126 const buffer = Buffer.alloc(SHEBANG_BYTE_LENGTH);

Fix shebang parsing reading past the end of a small fileSindre Sorhusbefore adoption7c1a631

line 127why, one step back
127 let bytesRead = 0;

Move away from `cross-spawn` (#1251)Sindre Sorhusbefore adoption4cafc3f

lines 128–131why, one step back
128
129 try {130 const fileDescriptor = openSync(file, 'r');131 try {

Fix shebang parsing reading past the end of a small fileSindre Sorhusbefore adoption7c1a631

line 132why, one step back
132 bytesRead = readSync(fileDescriptor, buffer, 0, SHEBANG_BYTE_LENGTH, 0);

Move away from `cross-spawn` (#1251)Sindre Sorhusbefore adoption4cafc3f

lines 133–139why, one step back
133 } finally {
134 closeSync(fileDescriptor);135 }136 } catch {137 return undefined;138 }139

Fix shebang parsing reading past the end of a small fileSindre Sorhusbefore adoption7c1a631

lines 140–142why, one step back
140 // A file shorter than the buffer leaves it zero-filled, so only the bytes actually read must be parsed.
141 // Otherwise, a shebang line which is not terminated by a newline would include those `\0` characters.142 return parseShebang(buffer.toString('utf8', 0, bytesRead));

Move away from `cross-spawn` (#1251)Sindre Sorhusbefore adoption4cafc3f

lines 143–155why, one step back
143};
144145const shebangRegExp = /^#!(?<line>.*)/;146147/*148Extract the interpreter from a shebang line, e.g. `#!/usr/bin/env node` -> `node`.149*/150const parseShebang = contents => {151 const shebangLine = contents.match(shebangRegExp)?.groups.line.trim();152 if (!shebangLine) {153 return undefined;154 }155

TweaksSindre Sorhusbefore adoption698a1b8

line 156why, one step back
156 const [interpreterPath, argument] = shebangLine.split(' ', 2);

Move away from `cross-spawn` (#1251)Sindre Sorhusbefore adoption4cafc3f

lines 157–176why, one step back
157 const interpreter = interpreterPath.split('/').at(-1);
158 if (interpreter === 'env') {159 return argument;160 }161162 return argument ? `${interpreter} ${argument}` : interpreter;163};164165const lineBreakRegExp = /[\n\r]/;166167const assertNoLineBreak = value => {168 if (lineBreakRegExp.test(value)) {169 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}`)}`);170 }171};172173// See https://web.archive.org/web/20241220221102/https://www.robvanderwoude.com/escapechars.php174// eslint-disable-next-line regexp/sort-character-class-elements175const metaCharsRegExp = /[()\][%!^"`<>&|;, *?]/g;176

Fix arguments of Windows batch files that read them with `%~1`Sindre Sorhusbefore adoption93bddc4

line 177why, one step back
177// Prefix every `cmd.exe` metacharacter with a caret to neutralize it. This is only used for the file, since arguments are quoted instead.

Move away from `cross-spawn` (#1251)Sindre Sorhusbefore adoption4cafc3f

lines 178–181why, one step back
178const escapeMetaChars = value => value.replaceAll(metaCharsRegExp, '^$&');
179180const backslashRunRegExp = /\\+/g;181

Fix arguments of Windows batch files that read them with `%~1`Sindre Sorhusbefore adoption93bddc4

lines 182–197why, one step back
182// Matches any character requiring quoting: anything except ASCII letters, digits, a few punctuation characters that `cmd.exe` never interprets, and non-ASCII characters other than control characters
183const quotedCharacterRegExp = /[^\w#$*+\-./:?@\\\u{80}-\u{10FFFF}]|\p{Control}/u;184185/*186Escape an argument the same way as Rust's `std::process::Command` does for batch files, which fixed the "BatBadBut" vulnerability (CVE-2024-24576): https://github.com/rust-lang/rust/blob/main/library/std/src/sys/args/windows.rs (`append_bat_arg()`). yt-dlp uses the same algorithm.187188Any argument containing a `cmd.exe` metacharacter is wrapped in double quotes, which keeps `cmd.exe` from interpreting it. `cmd.exe` might interpret it more than once: when invoking a batch file, then again when that batch file forwards it with `%*`, like npm cmd-shims do. Caret escaping depends on that count, so it breaks batch files reading their arguments directly with `%~1`, like Maven's `mvn.cmd`. Quoting does not, as long as the quotes stay balanced.189190Rust only uses this for batch files. We use it for any file run through `cmd.exe`, since it is also correct when `cmd.exe` interprets the argument only once.191192Limitations, which no escaping can fix since they depend on how the batch file uses its arguments:193- A batch file reading `%~1` gets the escaped argument without its surrounding quotes: double quotes are doubled, and trailing backslashes too.194- A batch file using `%~1` outside double quotes, or `%1` inside double quotes (like `if "%1" == ""`), lets `cmd.exe` interpret its metacharacters. Since `%1` includes the argument's surrounding quotes, the extra ones unquote it.195- A batch file forwarding its arguments with `call` expands `%` again, and one enabling delayed expansion expands `!` again.196*/197const escapeArgument = rawArgument => {

Move away from `cross-spawn` (#1251)Sindre Sorhusbefore adoption4cafc3f

line 198why, one step back
198 /*

Fix arguments of Windows batch files that read them with `%~1`Sindre Sorhusbefore adoption93bddc4

line 199why, one step back
199 Escape backslashes, following the algorithm at https://web.archive.org/web/20240930203505/https://qntm.org/cmd.

Move away from `cross-spawn` (#1251)Sindre Sorhusbefore adoption4cafc3f

lines 200–203why, one step back
200
201 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.202203 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.

Fix arguments of Windows batch files that read them with `%~1`Sindre Sorhusbefore adoption93bddc4

lines 204–207why, one step back
204
205 Double quotes are escaped as `""` instead of `\"`. Both are a literal double quote inside a quoted argument for the subprocess, but only `""` keeps the quotes balanced for `cmd.exe`, which does not know about backslashes. Otherwise, the metacharacters after the double quote would not be quoted anymore, allowing command injection.206207 `%` cannot be escaped inside double quotes, so it is replaced by `%%cd:~,%` instead. That is a literal `%` followed by an empty substring of the `%cd%` variable, which `cmd.exe` expands to nothing. This prevents `%VAR%` from being expanded.

Move away from `cross-spawn` (#1251)Sindre Sorhusbefore adoption4cafc3f

line 208why, one step back
208 */

Fix arguments of Windows batch files that read them with `%~1`Sindre Sorhusbefore adoption93bddc4

lines 209–214why, one step back
209 const argument = `${rawArgument}`;
210 if (!shouldQuoteArgument(argument)) {211 return argument;212 }213214 const escapedArgument = argument

Move away from `cross-spawn` (#1251)Sindre Sorhusbefore adoption4cafc3f

lines 215–216why, one step back
215 .replaceAll(backslashRunRegExp, (backslashes, offset, string) => {
216 const nextCharacter = string[offset + backslashes.length];

Update dev dependencies (#1257)Sindre Sorhusbefore adoption5944b2d

lines 217–218why, one step back
217 const isPrecedesDoubleQuote = nextCharacter === '"' || nextCharacter === undefined;
218 return isPrecedesDoubleQuote ? backslashes.repeat(2) : backslashes;

Move away from `cross-spawn` (#1251)Sindre Sorhusbefore adoption4cafc3f

line 219why, one step back
219 })

Fix arguments of Windows batch files that read them with `%~1`Sindre Sorhusbefore adoption93bddc4

lines 220–221why, one step back
220 .replaceAll('"', '""')
221 .replaceAll('%', '%%cd:~,%');

Move away from `cross-spawn` (#1251)Sindre Sorhusbefore adoption4cafc3f

line 222why, one step back
222

Fix arguments of Windows batch files that read them with `%~1`Sindre Sorhusbefore adoption93bddc4

line 223why, one step back
223 return `"${escapedArgument}"`;

Move away from `cross-spawn` (#1251)Sindre Sorhusbefore adoption4cafc3f

line 224why, one step back
224};

Fix arguments of Windows batch files that read them with `%~1`Sindre Sorhusbefore adoption93bddc4

lines 225–233why, one step back
225
226/*227An empty argument must be quoted, otherwise it would be dropped.228An argument ending with a backslash must be quoted, otherwise a batch file wrapping it in double quotes, like `"%~1"`, would have that backslash escape its closing double quote.229Since `"` and `%` require quoting, an unquoted argument never needs any escaping.230*/231const shouldQuoteArgument = argument => argument === ''232 || argument.endsWith('\\')233 || quotedCharacterRegExp.test(argument);