-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathagent.ts
More file actions
506 lines (465 loc) · 15.6 KB
/
agent.ts
File metadata and controls
506 lines (465 loc) · 15.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
/**
* @fileoverview Package manager agent for executing npm, pnpm, and yarn commands.
* Provides cross-platform utilities with optimized flags and security defaults.
*
* SECURITY: Array-Based Arguments Prevent Command Injection
*
* All functions in this module (execNpm, execPnpm, execYarn) use array-based
* arguments when calling spawn(). This is the PRIMARY DEFENSE against command
* injection attacks.
*
* When arguments are passed as an array:
* spawn(cmd, ['install', packageName, '--flag'], options)
*
* Node.js handles escaping automatically. Each argument is passed directly to
* the OS without shell interpretation. Shell metacharacters like ; | & $ ( )
* are treated as LITERAL STRINGS, not as commands.
*
* Example: If packageName = "lodash; rm -rf /", the package manager will try to
* install a package literally named "lodash; rm -rf /" (which doesn't exist),
* rather than executing the malicious command.
*
* This approach is secure even when shell: true is used on Windows for .cmd
* file resolution, because Node.js properly escapes each array element.
*/
import process from 'node:process'
import { execBin } from './bin'
import {
NPM_BIN_PATH,
NPM_REAL_EXEC_PATH,
PACKAGE_LOCK_JSON,
PNPM_LOCK_YAML,
YARN_LOCK,
} from './constants/agents'
import {
getExecPath,
getNodeNoWarningsFlags,
supportsNodeRun,
} from './constants/node'
import { WIN32 } from './constants/platform'
import { isDebug } from './debug'
import { getCI } from './env/ci'
import { findUpSync } from './fs'
import { getOwn } from './objects'
import { spawn } from './spawn'
import type { SpawnOptions } from './spawn'
// Note: npm flag checking is done with regex patterns in the is*Flag functions below.
const pnpmIgnoreScriptsFlags = new Set([
'--ignore-scripts',
'--no-ignore-scripts',
])
const pnpmFrozenLockfileFlags = new Set([
'--frozen-lockfile',
'--no-frozen-lockfile',
])
const pnpmInstallCommands = new Set(['install', 'i'])
// Commands that support --ignore-scripts flag in pnpm:
// Installation-related: install, add, update, remove, link, unlink, import, rebuild.
const pnpmInstallLikeCommands = new Set([
'install',
'i',
'add',
'update',
'up',
'remove',
'rm',
'link',
'ln',
'unlink',
'import',
'rebuild',
'rb',
])
// Commands that support --ignore-scripts flag in yarn:
// Similar to npm/pnpm: installation-related commands.
const yarnInstallLikeCommands = new Set([
'install',
'add',
'upgrade',
'remove',
'link',
'unlink',
'import',
])
export interface PnpmOptions extends SpawnOptions {
allowLockfileUpdate?: boolean
}
export interface ExecScriptOptions extends SpawnOptions {
prepost?: boolean | undefined
}
/**
* Execute npm commands with optimized flags and settings.
*
* SECURITY: Uses array-based arguments to prevent command injection. All elements
* in the args array are properly escaped by Node.js when passed to spawn().
*
* @example
* ```typescript
* await execNpm(['install', '--save', 'lodash'])
* await execNpm(['run', 'build'], { cwd: '/tmp/project' })
* ```
*/
export function execNpm(args: string[], options?: SpawnOptions | undefined) {
const useDebug = isDebug()
const terminatorPos = args.indexOf('--')
const npmArgs = (
terminatorPos === -1 ? args : args.slice(0, terminatorPos)
).filter(
(a: string) =>
!isNpmAuditFlag(a) && !isNpmFundFlag(a) && !isNpmProgressFlag(a),
)
const otherArgs = terminatorPos === -1 ? [] : args.slice(terminatorPos)
const logLevelArgs =
// The default value of loglevel is "notice". We default to "warn" which is
// one level quieter.
useDebug || npmArgs.some(isNpmLoglevelFlag) ? [] : ['--loglevel', 'warn']
// SECURITY: Array-based arguments prevent command injection. Each element is
// passed directly to the OS without shell interpretation.
//
// NOTE: We don't apply hardening flags to npm because:
// 1. npm is a trusted system tool installed with Node.js
// 2. npm requires full system access (filesystem, network, child processes)
// 3. Hardening flags would prevent npm from functioning (even with --allow-* grants)
// 4. The permission model is intended for untrusted user code, not package managers
//
// We also use the npm binary wrapper instead of calling cli.js directly because
// cli.js exports a function that needs to be invoked with process as an argument.
const npmBin = NPM_BIN_PATH
return spawn(
npmBin,
[
// Even though '--loglevel=error' is passed npm will still run through
// code paths for 'audit' and 'fund' unless '--no-audit' and '--no-fund'
// flags are passed.
'--no-audit',
'--no-fund',
// Add `--no-progress` and `--silent` flags to fix input being swallowed
// by the spinner when running the command with recent versions of npm.
'--no-progress',
// Add '--loglevel=error' if a loglevel flag is not provided and the
// SOCKET_DEBUG environment variable is not truthy.
...logLevelArgs,
...npmArgs,
...otherArgs,
],
{
__proto__: null,
// On Windows, npm is a .cmd file that requires shell to execute.
shell: WIN32,
...options,
} as SpawnOptions,
)
}
/**
* Execute pnpm commands with optimized flags and settings.
*
* SECURITY: Uses array-based arguments to prevent command injection. All elements
* in the args array are properly escaped by Node.js when passed to execBin().
*
* @example
* ```typescript
* await execPnpm(['install'])
* await execPnpm(['add', 'lodash'], { allowLockfileUpdate: true })
* ```
*/
export function execPnpm(args: string[], options?: PnpmOptions | undefined) {
const { allowLockfileUpdate, ...extBinOpts } = {
__proto__: null,
...options,
} as PnpmOptions
const useDebug = isDebug()
const terminatorPos = args.indexOf('--')
const pnpmArgs = (
terminatorPos === -1 ? args : args.slice(0, terminatorPos)
).filter((a: string) => !isNpmProgressFlag(a))
const otherArgs = terminatorPos === -1 ? [] : args.slice(terminatorPos)
const firstArg = pnpmArgs[0]
const supportsIgnoreScripts = firstArg
? pnpmInstallLikeCommands.has(firstArg)
: false
// pnpm uses --loglevel for all commands.
const logLevelArgs =
useDebug || pnpmArgs.some(isPnpmLoglevelFlag) ? [] : ['--loglevel', 'warn']
// Only add --ignore-scripts for commands that support it.
const hasIgnoreScriptsFlag = pnpmArgs.some(isPnpmIgnoreScriptsFlag)
const ignoreScriptsArgs =
!supportsIgnoreScripts || hasIgnoreScriptsFlag ? [] : ['--ignore-scripts']
// In CI environments, pnpm uses --frozen-lockfile by default which prevents lockfile updates.
// For commands that need to update the lockfile (like install with new packages/overrides),
// we need to explicitly add --no-frozen-lockfile in CI mode if not already present.
const frozenLockfileArgs = []
if (
getCI() &&
allowLockfileUpdate &&
firstArg &&
isPnpmInstallCommand(firstArg) &&
!pnpmArgs.some(isPnpmFrozenLockfileFlag)
) {
frozenLockfileArgs.push('--no-frozen-lockfile')
}
// Note: pnpm doesn't have a --no-progress flag. It uses --reporter instead.
// We removed --no-progress as it causes "Unknown option" errors with pnpm.
// SECURITY: Array-based arguments prevent command injection. Each element is
// passed directly to the OS without shell interpretation.
return execBin(
'pnpm',
[
// Add '--loglevel=warn' if a loglevel flag is not provided and debug is off.
...logLevelArgs,
// Add '--ignore-scripts' by default for security (only for installation commands).
...ignoreScriptsArgs,
// Add '--no-frozen-lockfile' in CI when lockfile updates are needed.
...frozenLockfileArgs,
...pnpmArgs,
...otherArgs,
],
extBinOpts,
)
}
/**
* Execute a package.json script using the detected package manager.
* Picks pnpm, npm, or yarn by walking up to the nearest lockfile; falls back
* to running `node --run` or `npm run` directly when no lockfile is found.
* Honors `shell: true` by passing through to `spawn()` unchanged.
*
* @param scriptName - The package.json script to run
* @param args - Either the script arguments or an options object
* @param options - Spawn options plus `prepost` to force npm-style pre/post scripts
* @returns The spawned `ChildProcess`-like promise from the underlying runner.
*/
export function execScript(
scriptName: string,
args?: string[] | readonly string[] | ExecScriptOptions | undefined,
options?: ExecScriptOptions | undefined,
) {
// Handle overloaded signatures: execScript(name, options) or execScript(name, args, options).
let resolvedOptions: ExecScriptOptions | undefined
let resolvedArgs: string[]
if (!Array.isArray(args) && args !== null && typeof args === 'object') {
resolvedOptions = args as ExecScriptOptions
resolvedArgs = []
} else {
resolvedOptions = options
resolvedArgs = (args || []) as string[]
}
const { prepost, ...spawnOptions } = {
__proto__: null,
...resolvedOptions,
} as ExecScriptOptions
// If shell: true is passed, run the command directly as a shell command.
if (spawnOptions.shell === true) {
return spawn(scriptName, resolvedArgs, spawnOptions)
}
const useNodeRun = !prepost && supportsNodeRun()
// Detect package manager based on lockfile by traversing up from current directory.
const cwd =
(getOwn(spawnOptions, 'cwd') as string | undefined) ?? process.cwd()
// Check for pnpm-lock.yaml.
const pnpmLockPath = findUpSync(PNPM_LOCK_YAML, { cwd }) as string | undefined
if (pnpmLockPath) {
return execPnpm(['run', scriptName, ...resolvedArgs], spawnOptions)
}
// Check for package-lock.json.
// When in an npm workspace, use npm run to ensure workspace binaries are available.
const packageLockPath = findUpSync(PACKAGE_LOCK_JSON, { cwd }) as
| string
| undefined
if (packageLockPath) {
return execNpm(['run', scriptName, ...resolvedArgs], spawnOptions)
}
// Check for yarn.lock.
const yarnLockPath = findUpSync(YARN_LOCK, { cwd }) as string | undefined
if (yarnLockPath) {
return execYarn(['run', scriptName, ...resolvedArgs], spawnOptions)
}
return spawn(
getExecPath(),
[
...getNodeNoWarningsFlags(),
...(useNodeRun ? ['--run'] : [NPM_REAL_EXEC_PATH, 'run']),
scriptName,
...resolvedArgs,
],
{
...spawnOptions,
},
)
}
/**
* Execute yarn commands with optimized flags and settings.
*
* SECURITY: Uses array-based arguments to prevent command injection. All elements
* in the args array are properly escaped by Node.js when passed to execBin().
*
* @example
* ```typescript
* await execYarn(['install'])
* await execYarn(['add', 'lodash'], { cwd: '/tmp/project' })
* ```
*/
export function execYarn(
args: string[],
options?: import('./spawn').SpawnOptions,
) {
const useDebug = isDebug()
const terminatorPos = args.indexOf('--')
const yarnArgs = (
terminatorPos === -1 ? args : args.slice(0, terminatorPos)
).filter((a: string) => !isNpmProgressFlag(a))
const otherArgs = terminatorPos === -1 ? [] : args.slice(terminatorPos)
const firstArg = yarnArgs[0]
const supportsIgnoreScripts = firstArg
? yarnInstallLikeCommands.has(firstArg)
: false
// Yarn uses --silent flag for quieter output.
const logLevelArgs =
useDebug || yarnArgs.some(isNpmLoglevelFlag) ? [] : ['--silent']
// Only add --ignore-scripts for commands that support it.
const hasIgnoreScriptsFlag = yarnArgs.some(isPnpmIgnoreScriptsFlag)
const ignoreScriptsArgs =
!supportsIgnoreScripts || hasIgnoreScriptsFlag ? [] : ['--ignore-scripts']
// SECURITY: Array-based arguments prevent command injection. Each element is
// passed directly to the OS without shell interpretation.
return execBin(
'yarn',
[
// Add '--silent' if a loglevel flag is not provided and debug is off.
...logLevelArgs,
// Add '--ignore-scripts' by default for security (only for installation commands).
...ignoreScriptsArgs,
...yarnArgs,
...otherArgs,
],
{
__proto__: null,
...options,
} as SpawnOptions,
)
}
/**
* Check if a command argument is an npm audit flag.
*
* @example
* ```typescript
* isNpmAuditFlag('--no-audit') // true
* isNpmAuditFlag('--audit') // true
* isNpmAuditFlag('--save') // false
* ```
*/
/*@__NO_SIDE_EFFECTS__*/
export function isNpmAuditFlag(cmdArg: string): boolean {
return /^--(no-)?audit(=.*)?$/.test(cmdArg)
}
/**
* Check if a command argument is an npm fund flag.
*
* @example
* ```typescript
* isNpmFundFlag('--no-fund') // true
* isNpmFundFlag('--fund') // true
* isNpmFundFlag('--save') // false
* ```
*/
/*@__NO_SIDE_EFFECTS__*/
export function isNpmFundFlag(cmdArg: string): boolean {
return /^--(no-)?fund(=.*)?$/.test(cmdArg)
}
/**
* Check if a command argument is an npm loglevel flag.
*
* @example
* ```typescript
* isNpmLoglevelFlag('--loglevel') // true
* isNpmLoglevelFlag('--silent') // true
* isNpmLoglevelFlag('-s') // true
* isNpmLoglevelFlag('--save') // false
* ```
*/
/*@__NO_SIDE_EFFECTS__*/
export function isNpmLoglevelFlag(cmdArg: string): boolean {
// https://docs.npmjs.com/cli/v11/using-npm/logging#setting-log-levels
if (/^--loglevel(=.*)?$/.test(cmdArg)) {
return true
}
// Check for long form flags
if (/^--(silent|verbose|info|warn|error|quiet)$/.test(cmdArg)) {
return true
}
// Check for shorthand flags
return /^-(s|q|d|dd|ddd|v)$/.test(cmdArg)
}
/**
* Check if a command argument is an npm node-options flag.
*
* @example
* ```typescript
* isNpmNodeOptionsFlag('--node-options') // true
* isNpmNodeOptionsFlag('--node-options=--max-old-space-size=4096') // true
* isNpmNodeOptionsFlag('--save') // false
* ```
*/
/*@__NO_SIDE_EFFECTS__*/
export function isNpmNodeOptionsFlag(cmdArg: string): boolean {
// https://docs.npmjs.com/cli/v9/using-npm/config#node-options
return /^--node-options(=.*)?$/.test(cmdArg)
}
/**
* Check if a command argument is an npm progress flag.
*
* @example
* ```typescript
* isNpmProgressFlag('--no-progress') // true
* isNpmProgressFlag('--progress') // true
* isNpmProgressFlag('--save') // false
* ```
*/
/*@__NO_SIDE_EFFECTS__*/
export function isNpmProgressFlag(cmdArg: string): boolean {
return /^--(no-)?progress(=.*)?$/.test(cmdArg)
}
/**
* Check if a command argument is a pnpm frozen-lockfile flag.
*
* @example
* ```typescript
* isPnpmFrozenLockfileFlag('--frozen-lockfile') // true
* isPnpmFrozenLockfileFlag('--no-frozen-lockfile') // true
* isPnpmFrozenLockfileFlag('--save') // false
* ```
*/
/*@__NO_SIDE_EFFECTS__*/
export function isPnpmFrozenLockfileFlag(cmdArg: string): boolean {
return pnpmFrozenLockfileFlags.has(cmdArg)
}
/**
* Check if a command argument is a pnpm ignore-scripts flag.
*
* @example
* ```typescript
* isPnpmIgnoreScriptsFlag('--ignore-scripts') // true
* isPnpmIgnoreScriptsFlag('--no-ignore-scripts') // true
* isPnpmIgnoreScriptsFlag('--save') // false
* ```
*/
/*@__NO_SIDE_EFFECTS__*/
export function isPnpmIgnoreScriptsFlag(cmdArg: string): boolean {
return pnpmIgnoreScriptsFlags.has(cmdArg)
}
/**
* Check if a command argument is a pnpm install command.
*
* @example
* ```typescript
* isPnpmInstallCommand('install') // true
* isPnpmInstallCommand('i') // true
* isPnpmInstallCommand('run') // false
* ```
*/
/*@__NO_SIDE_EFFECTS__*/
export function isPnpmInstallCommand(cmdArg: string): boolean {
return pnpmInstallCommands.has(cmdArg)
}
/**
* Alias for isNpmLoglevelFlag — pnpm uses the same `--loglevel` surface.
*/
export const isPnpmLoglevelFlag = isNpmLoglevelFlag