command-file.js
This file
Path
lib/arguments/command-file.js
160 lines · 6.6 KiB · JavaScript
Last changed by
Use `which-command` instead of `which` (#1253)Sindre Sorhusbefore adoption9a7a162
History of this fileTake it
Move away from `cross-spawn` (#1251)Sindre Sorhusbefore adoption4cafc3f
lines 1–4why, one step back1import {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 back5import {whichCommandSync} from 'which-command';Move away from `cross-spawn` (#1251)Sindre Sorhusbefore adoption4cafc3f
lines 6–74why, one step back6import 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};74Use `which-command` instead of `which` (#1253)Sindre Sorhusbefore adoption9a7a162
lines 75–76why, one step back75// Search `PATH` for the command, resolving its Windows executable extension via `PATHEXT`76const resolvePath = parsed => {Move away from `cross-spawn` (#1251)Sindre Sorhusbefore adoption4cafc3f
line 77why, one step back77 const environment = parsed.options.env || process.env;Use `which-command` instead of `which` (#1253)Sindre Sorhusbefore adoption9a7a162
lines 78–81why, one step back78 return whichCommandSync(parsed.file, {79 cwd: parsed.options.cwd,80 path: environment[pathKey({env: environment})],81 });Move away from `cross-spawn` (#1251)Sindre Sorhusbefore adoption4cafc3f
lines 82–160why, one step back82};8384const SHEBANG_BYTE_LENGTH = 150;8586// Read the file's first bytes to find its shebang interpreter, if it has one87const readShebang = file => {88 const buffer = Buffer.alloc(SHEBANG_BYTE_LENGTH);8990 try {91 const fileDescriptor = openSync(file, 'r');92 try {93 readSync(fileDescriptor, buffer, 0, SHEBANG_BYTE_LENGTH, 0);94 } finally {95 closeSync(fileDescriptor);96 }97 } catch {98 return undefined;99 }100101 return parseShebang(buffer.toString());102};103104const shebangRegExp = /^#!(?<line>.*)/;105106/*107Extract the interpreter from a shebang line, e.g. `#!/usr/bin/env node` -> `node`.108*/109const parseShebang = contents => {110 const shebangLine = contents.match(shebangRegExp)?.groups.line.trim();111 if (!shebangLine) {112 return undefined;113 }114115 const [interpreterPath, argument] = shebangLine.split(' ');116 const interpreter = interpreterPath.split('/').at(-1);117 if (interpreter === 'env') {118 return argument;119 }120121 return argument ? `${interpreter} ${argument}` : interpreter;122};123124const lineBreakRegExp = /[\n\r]/;125126const assertNoLineBreak = value => {127 if (lineBreakRegExp.test(value)) {128 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}`)}`);129 }130};131132// See https://web.archive.org/web/20241220221102/https://www.robvanderwoude.com/escapechars.php133// eslint-disable-next-line regexp/sort-character-class-elements134const metaCharsRegExp = /[()\][%!^"`<>&|;, *?]/g;135136// Prefix every `cmd.exe` metacharacter with a caret to neutralize it137const escapeMetaChars = value => value.replaceAll(metaCharsRegExp, '^$&');138139const backslashRunRegExp = /\\+/g;140141const escapeArgument = (rawArgument, doubleEscape) => {142 /*143 Escape backslashes and double quotes for `cmd.exe`, following the algorithm at https://web.archive.org/web/20240930203505/https://qntm.org/cmd.144145 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.146147 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.148 */149 const argument = `${rawArgument}`150 .replaceAll(backslashRunRegExp, (backslashes, offset, string) => {151 const nextCharacter = string[offset + backslashes.length];152 const precedesDoubleQuote = nextCharacter === '"' || nextCharacter === undefined;153 return precedesDoubleQuote ? backslashes.repeat(2) : backslashes;154 })155 .replaceAll('"', '\\"');156157 // Wrap the whole argument in double quotes, then caret-escape the metacharacters, a second time when targeting a cmd-shim158 const escapedArgument = escapeMetaChars(`"${argument}"`);159 return doubleEscape ? escapeMetaChars(escapedArgument) : escapedArgument;160};