command-file.js
This file
Path
lib/arguments/command-file.js
201 lines · 8.6 KiB · JavaScript
Last changed by
Fix `preferLocal` argument escaping edge-case on Windows (#1259)Sindre Sorhusbefore adoptione771733
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–31why, one step back67/*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 itself15 if (options.shell || process.platform !== 'win32') {16 return parsed;17 }1819 return escapeWindowsCommand(parsed);20};2122// Only `.exe` and `.com` files can be spawned directly; anything else needs `cmd.exe`23const directlyExecutableRegExp = /\.(?:com|exe)$/i;2425// `.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 arguments26const batchFileRegExp = /\.(?:bat|cmd)$/i;2728const escapeWindowsCommand = parsed => {29 // Resolve the file to an absolute path, following its shebang to the interpreter if any30 const resolvedFile = resolveWithShebang(parsed);31Fix `preferLocal` argument escaping edge-case on Windows (#1259)Sindre Sorhusbefore adoptione771733
line 32why, one step back32 // A directly executable file is spawned by its resolved path, bypassing `cmd.exe` and its escapingMove away from `cross-spawn` (#1251)Sindre Sorhusbefore adoption4cafc3f
line 33why, one step back33 if (resolvedFile !== undefined && directlyExecutableRegExp.test(resolvedFile)) {Fix `preferLocal` argument escaping edge-case on Windows (#1259)Sindre Sorhusbefore adoptione771733
lines 34–38why, one step back34 if (parsed.options.argv0 === undefined) {35 parsed.options.argv0 = parsed.file;36 }3738 parsed.file = resolvedFile;Move away from `cross-spawn` (#1251)Sindre Sorhusbefore adoption4cafc3f
lines 39–49why, one step back39 return parsed;40 }4142 /*43 `cmd.exe` treats CR and LF as command separators and offers no way to escape them, so allowing either would enable command injection.44 Reject them instead.45 */46 for (const value of [parsed.file, ...parsed.commandArguments]) {47 assertNoLineBreak(value);48 }49Update dev dependencies (#1257)Sindre Sorhusbefore adoption5944b2d
line 50why, one step back50 const isDoubleEscape = resolvedFile !== undefined && batchFileRegExp.test(resolvedFile);Move away from `cross-spawn` (#1251)Sindre Sorhusbefore adoption4cafc3f
line 51why, one step back51 // POSIX separators must become Windows ones (`foo/bar` -> `foo\bar`), otherwise resolution always fails with ENOENTFix `preferLocal` argument escaping edge-case on Windows (#1259)Sindre Sorhusbefore adoptione771733
line 52why, one step back52 const escapedFile = escapeMetaChars(path.normalize(resolvedFile ?? parsed.file));Update dev dependencies (#1257)Sindre Sorhusbefore adoption5944b2d
line 53why, one step back53 const escapedArguments = parsed.commandArguments.map(argument => escapeArgument(argument, isDoubleEscape));Move away from `cross-spawn` (#1251)Sindre Sorhusbefore adoption4cafc3f
lines 54–78why, one step back54 const commandLine = `"${[escapedFile, ...escapedArguments].join(' ')}"`;5556 // Let `node:child_process` pass the already-escaped command line through untouched57 parsed.options.windowsVerbatimArguments = true;58 return {59 file: process.env.comspec || 'cmd.exe',60 commandArguments: ['/d', '/s', '/c', commandLine],61 options: parsed.options,62 };63};6465// Resolve the command's absolute path, then, if it is a shebang script, resolve its interpreter instead, since Windows cannot run shebangs natively66const resolveWithShebang = parsed => {67 const resolvedFile = resolvePath(parsed);68 const interpreter = resolvedFile !== undefined && readShebang(resolvedFile);69 if (!interpreter) {70 return resolvedFile;71 }7273 // Run the interpreter with the script as its first argument, then resolve the interpreter's own path74 parsed.commandArguments.unshift(resolvedFile);75 parsed.file = interpreter;76 return resolvePath(parsed);77};78Use `which-command` instead of `which` (#1253)Sindre Sorhusbefore adoption9a7a162
lines 79–80why, one step back79// Search `PATH` for the command, resolving its Windows executable extension via `PATHEXT`80const resolvePath = parsed => {Move away from `cross-spawn` (#1251)Sindre Sorhusbefore adoption4cafc3f
line 81why, one step back81 const environment = parsed.options.env || process.env;Fix `preferLocal` argument escaping edge-case on Windows (#1259)Sindre Sorhusbefore adoptione771733
lines 82–122why, one step back82 const cwd = parsed.options.cwd ?? process.cwd();83 const environmentPathExt = getWindowsEnvironmentValue(environment, 'PATHEXT');84 const commandExtension = path.extname(parsed.file);85 // Commands with an explicit extension must be tried verbatim so shebang scripts work even when their extension is excluded from PATHEXT.86 const pathExt = commandExtension === '' ? environmentPathExt : `${commandExtension}${path.delimiter}${environmentPathExt ?? ''}`;87 if (hasWindowsPathSeparator(parsed.file)) {88 return whichCommandSync(path.resolve(cwd, parsed.file), {cwd, pathExt});89 }9091 const searchPath = getWindowsEnvironmentValue(environment, 'PATH') ?? getWindowsEnvironmentValue(process.env, 'PATH') ?? '';92 const resolveOptions = {93 cwd,94 path: searchPath,95 pathExt,96 };9798 return shouldSearchCurrentDirectory(environment) ? whichCommandSync(parsed.file, resolveOptions) : resolvePathDirectories(parsed.file, resolveOptions);99};100101const hasWindowsPathSeparator = file => file.includes('/') || file.includes('\\') || file.includes(':');102103const shouldSearchCurrentDirectory = environment => getWindowsEnvironmentValue(process.env, 'NODEFAULTCURRENTDIRECTORYINEXEPATH') === undefined && getWindowsEnvironmentValue(environment, 'NODEFAULTCURRENTDIRECTORYINEXEPATH') === undefined;104105const resolvePathDirectories = (file, {cwd, path: searchPath, pathExt}) => {106 for (const directory of searchPath.split(path.delimiter)) {107 const unquotedDirectory = directory.length > 1 && directory.startsWith('"') && directory.endsWith('"') ? directory.slice(1, -1) : directory;108 if (unquotedDirectory === '') {109 continue;110 }111112 const resolvedFile = whichCommandSync(path.resolve(cwd, unquotedDirectory, file), {cwd, pathExt});113 if (resolvedFile !== undefined) {114 return resolvedFile;115 }116 }117};118119// Node sorts Windows environment keys and uses the first case-insensitive match when spawning.120const getWindowsEnvironmentValue = (environment, name) => {121 const environmentKey = Object.keys(environment).sort().find(key => key.toUpperCase() === name);122 return environmentKey === undefined ? undefined : environment[environmentKey];Move away from `cross-spawn` (#1251)Sindre Sorhusbefore adoption4cafc3f
lines 123–192why, one step back123};124125const SHEBANG_BYTE_LENGTH = 150;126127// Read the file's first bytes to find its shebang interpreter, if it has one128const readShebang = file => {129 const buffer = Buffer.alloc(SHEBANG_BYTE_LENGTH);130131 try {132 const fileDescriptor = openSync(file, 'r');133 try {134 readSync(fileDescriptor, buffer, 0, SHEBANG_BYTE_LENGTH, 0);135 } finally {136 closeSync(fileDescriptor);137 }138 } catch {139 return undefined;140 }141142 return parseShebang(buffer.toString());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 }155156 const [interpreterPath, argument] = shebangLine.split(' ');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;176177// Prefix every `cmd.exe` metacharacter with a caret to neutralize it178const escapeMetaChars = value => value.replaceAll(metaCharsRegExp, '^$&');179180const backslashRunRegExp = /\\+/g;181182const escapeArgument = (rawArgument, doubleEscape) => {183 /*184 Escape backslashes and double quotes for `cmd.exe`, following the algorithm at https://web.archive.org/web/20240930203505/https://qntm.org/cmd.185186 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.187188 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.189 */190 const argument = `${rawArgument}`191 .replaceAll(backslashRunRegExp, (backslashes, offset, string) => {192 const nextCharacter = string[offset + backslashes.length];Update dev dependencies (#1257)Sindre Sorhusbefore adoption5944b2d
lines 193–194why, one step back193 const isPrecedesDoubleQuote = nextCharacter === '"' || nextCharacter === undefined;194 return isPrecedesDoubleQuote ? backslashes.repeat(2) : backslashes;Move away from `cross-spawn` (#1251)Sindre Sorhusbefore adoption4cafc3f
lines 195–201why, one step back195 })196 .replaceAll('"', '\\"');197198 // Wrap the whole argument in double quotes, then caret-escape the metacharacters, a second time when targeting a cmd-shim199 const escapedArgument = escapeMetaChars(`"${argument}"`);200 return doubleEscape ? escapeMetaChars(escapedArgument) : escapedArgument;201};