Skip to content

Commit 10ffa9f

Browse files
martinrrmCopilot
andauthored
fix(libnpmexec): escape inferred executable names for selected shell (#10044)
## Summary When `npx <package>` infers an executable from package `bin` metadata, the executable name becomes part of a synthetic npm script. On Windows, that script is ultimately interpreted by `cmd.exe`. This change protects the inferred executable token according to the selected shell instead of forwarding it unquoted. Supporting dependency PR: npm/promise-spawn#166 ## Changes ### `lib/run-script.js` - Escape the executable token when no explicit `call` script was supplied. - Select the escaping strategy from `scriptShell`, including POSIX shells selected on Windows. - For `cmd.exe`, protect command separators, spaces, command keywords, and other cmd metacharacters. - Reject executable names containing double quotes, percent signs, exclamation marks, or control characters that cannot be safely represented as a cmd executable token. - Preserve `call` as an intentionally supplied shell script; its arguments are not treated as inferred executable names. ### `lib/index.js` - On a matching npx-cache hit, select the inferred command from the installed package manifest rather than mutable registry metadata. This cache-manifest adjustment is related hardening and may be split into a separate change during review if preferred. ### Tests and documentation - Add unit coverage for cmd.exe token encoding and rejection cases. - Add coverage for POSIX escaping when a POSIX shell is selected on Windows. - Add normalized-bin registry regressions covering command separators and cache metadata mismatches. - Document the shell-specific executable handling and rejected cmd.exe characters. ## Dependency status The required promise-spawn fix is released and bundled as @npmcli/[email protected] through #10152. This branch is rebased onto latest and no longer carries a duplicate bundled dependency diff. ## Validation - Focused and full libnpmexec tests, eslint, and template-oss postlint pass locally on Node 24.15.0. - Mutation testing confirms the shell and cache regressions fail without the production changes. - Added PowerShell-specific construction coverage and a Windows runtime test for inferred executable invocation. - The npm/cli CI matrix passes on Linux, macOS, and Windows across all configured Node versions. - No vulnerability reproduction or malicious command execution was run. ## Review status Ready for review. --------- Co-authored-by: Copilot <[email protected]> Copilot-Session: 3e53db77-0fe4-4320-8ada-f2962ddd303c Copilot-Session: 155db33f-8c59-4859-a9b9-374c3a77e721
1 parent 89e9555 commit 10ffa9f

5 files changed

Lines changed: 361 additions & 8 deletions

File tree

‎workspaces/libnpmexec/README.md‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ await libexec({
2828

2929
- `opts`:
3030
- `args`: List of pkgs to execute **Array<String>**, defaults to `[]`
31-
- `call`: An alternative command to run when using `packages` option **String**, defaults to empty string.
31+
- `call`: An alternative shell script to run when using `packages` option **String**, defaults to empty string. Unlike an executable selected from `args` or a package's `bin`, this is intentionally interpreted as shell syntax.
3232
- `cache`: The path location to where the npm cache folder is placed **String**
3333
- `npxCache`: The path location to where the npx cache folder is placed **String**
3434
- `chalk`: Chalk instance to use for colors? **Required**
@@ -42,6 +42,14 @@ await libexec({
4242
- `yes`: Should skip download confirmation prompt when fetching missing packages from the registry? **Boolean**
4343
- `registry`, `cache`, and more options that are forwarded to [@npmcli/arborist](https://github.com/npm/cli/blob/latest/workspaces/arborist/README.md) and [pacote](https://github.com/npm/pacote/#options) **Object**
4444

45+
Executable names are escaped for the selected shell, including POSIX shells and
46+
PowerShell used on Windows. For inferred PowerShell invocations, arguments are
47+
also escaped as literal strings. With `cmd.exe`, executable names containing double
48+
quotes, percent signs, exclamation marks, or control characters are rejected
49+
with `EINVALIDCOMMAND`. Use a bin name without these characters. On a matching
50+
npx-cache hit, command selection uses the installed package's `bin` rather than
51+
the registry's bin metadata.
52+
4553
## LICENSE
4654

4755
[ISC](./LICENSE)

‎workspaces/libnpmexec/lib/index.js‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -267,8 +267,8 @@ const exec = async (opts) => {
267267
})
268268
const lockPath = join(installDir, 'concurrency.lock')
269269
const npxTree = await withLock(lockPath, () => npxArb.loadActual())
270-
await Promise.all(needInstall.map(async ({ spec }) => {
271-
const { manifest } = await missingFromTree({
270+
await Promise.all(needInstall.map(async ({ spec, manifest: requestedManifest }) => {
271+
const { manifest, node } = await missingFromTree({
272272
spec,
273273
tree: npxTree,
274274
flatOptions,
@@ -281,6 +281,10 @@ const exec = async (opts) => {
281281
} else {
282282
add.push(manifest._id)
283283
}
284+
} else if (needPackageCommandSwap && commandManifest === requestedManifest) {
285+
// A cache hit must use the installed bin, not mutable registry metadata.
286+
commandManifest = node.package
287+
args[0] = getBinFromManifest(commandManifest)
284288
}
285289
}))
286290

‎workspaces/libnpmexec/lib/run-script.js‎

Lines changed: 22 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,10 @@ const runScript = require('@npmcli/run-script')
33
const pkgJson = require('@npmcli/package-json')
44
const { log, output } = require('proc-log')
55
const noTTY = require('./no-tty.js')
6-
const isWindowsShell = require('./is-windows.js')
6+
const isWindows = require('./is-windows.js')
7+
8+
const isCmd = shell => /(?:^|[\\/])cmd(?:\.exe)?$/i.test(shell)
9+
const isPowerShell = shell => /(?:^|[\\/])(?:powershell|pwsh)(?:\.exe)?$/i.test(shell)
710

811
const run = async ({
912
args,
@@ -15,10 +18,24 @@ const run = async ({
1518
runPath,
1619
scriptShell,
1720
}) => {
18-
// escape executable path
19-
// necessary for preventing bash/cmd keywords from overriding
20-
if (!isWindowsShell) {
21-
if (args.length > 0) {
21+
if (!call && args.length > 0) {
22+
const shell = scriptShell || (isWindows ? process.env.ComSpec || 'cmd' : 'sh')
23+
if (isCmd(shell)) {
24+
// Variable expansion (including delayed expansion) and embedded quotes
25+
// cannot be safely escaped here. Control characters are invalid filenames.
26+
if (/["%!]/.test(args[0]) || [...args[0]].some(c => c.charCodeAt(0) < 32)) {
27+
throw Object.assign(
28+
new Error(`Invalid executable name for cmd.exe: ${JSON.stringify(args[0])}`),
29+
{ code: 'EINVALIDCOMMAND' }
30+
)
31+
}
32+
// Protect both cmd.exe's metacharacter parsing and executable-name parsing.
33+
args[0] = `"${args[0]}"`.replace(/[ ^&()<>|";,*?=@]/g, '^$&')
34+
} else if (isPowerShell(shell)) {
35+
// Encode the whole invocation to avoid promise-spawn's POSIX argument escaping.
36+
const quotedArgs = args.map(arg => `'${arg.replace(/['\u2018-\u201b]/g, '$&$&')}'`)
37+
args = [`& ${quotedArgs.join(' ')}`]
38+
} else {
2239
// single-quote so shell metacharacters in the executable name are taken
2340
// literally; double quotes still expand $(), backticks, $var and "
2441
args[0] = `'${args[0].replace(/'/g, `'\\''`)}'`

‎workspaces/libnpmexec/test/registry.js‎

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ const t = require('tap')
33
const { setup, createPkg, merge } = require('./fixtures/setup.js')
44
const crypto = require('node:crypto')
55
const { existsSync } = require('node:fs')
6+
const PackageJson = require('@npmcli/package-json')
67

78
t.test('run from registry - no local packages', async t => {
89
const { fixtures, package } = createPkg({ versions: ['2.0.0'] })
@@ -126,6 +127,81 @@ t.test('avoid install when exec from registry an available pkg', async t => {
126127
})
127128
})
128129

130+
const binNames = [
131+
'two words',
132+
'bin&echo cli170-injected',
133+
'bin^name',
134+
'bin(name)',
135+
"bin'name",
136+
'bin;name',
137+
'bin=name',
138+
'if',
139+
]
140+
const posixBinNames = [
141+
'bin!name',
142+
'bin$(echo injected>cli170-marker)',
143+
'bin`echo injected>cli170-marker`',
144+
"bin';echo injected>cli170-marker;#",
145+
]
146+
147+
for (const binName of [...binNames, ...posixBinNames]) {
148+
t.test(`executes normalized bin name literally: ${binName}`, {
149+
skip: process.platform === 'win32' && posixBinNames.includes(binName),
150+
}, async t => {
151+
const { pkg, fixtures, package: mockPackage } = createPkg({
152+
versions: ['1.0.0'],
153+
bin: { [binName]: 'bin-file.js' },
154+
})
155+
const normalized = await new PackageJson().fromContent(pkg).normalize()
156+
t.same(Object.keys(normalized.content.bin), [binName], 'payload survives normalization')
157+
158+
const { exec, path, registry, readOutput } = setup(t, { testdir: fixtures })
159+
await mockPackage({ registry, path })
160+
const args = ['an argument', 'literal&argument', 'literal^argument', '"quoted"']
161+
await exec({ args: ['@npmcli/create-index', ...args] })
162+
t.match(await readOutput('@npmcli-create-index'), { value: 'packages-1.0.0', args })
163+
t.notOk(existsSync(resolve(path, 'cli170-marker')), 'no injected command ran')
164+
})
165+
}
166+
167+
for (const binName of [
168+
'renamed-bin',
169+
'create-index&echo injected>cli170-marker',
170+
'create-index$(echo injected>cli170-marker)',
171+
'create-index%CLI170_COMMAND%',
172+
]) {
173+
t.test(`cache hit ignores registry bin metadata: ${binName}`, async t => {
174+
const { pkg, fixtures, package: mockPackage } = createPkg({ versions: ['1.0.0'] })
175+
const { exec, path, registry, readOutput, rmOutput } = setup(t, { testdir: fixtures })
176+
await mockPackage({ registry, path })
177+
await exec({ args: ['@npmcli/create-index'] })
178+
await rmOutput('@npmcli-create-index')
179+
180+
const altered = await new PackageJson().fromContent({
181+
...pkg,
182+
bin: { [binName]: 'bin-file.js' },
183+
}).normalize()
184+
t.same(Object.keys(altered.content.bin), [binName], 'payload survives normalization')
185+
await mockPackage({
186+
registry,
187+
path,
188+
tarballs: [],
189+
times: 1,
190+
manifest: registry.manifest({
191+
name: pkg.name,
192+
packuments: [altered.content],
193+
}),
194+
})
195+
196+
await exec({ args: ['@npmcli/create-index', 'cached argument'] })
197+
t.match(await readOutput('@npmcli-create-index'), {
198+
value: 'packages-1.0.0',
199+
args: ['cached argument'],
200+
})
201+
t.notOk(existsSync(resolve(path, 'cli170-marker')), 'no injected command ran')
202+
})
203+
}
204+
129205
t.test('run multiple from registry', async t => {
130206
const indexPkg = createPkg({
131207
versions: ['2.0.0'],

0 commit comments

Comments
 (0)