-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathdlx.mts
More file actions
350 lines (317 loc) · 9.76 KB
/
dlx.mts
File metadata and controls
350 lines (317 loc) · 9.76 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
/**
* DLX execution utilities for Socket CLI.
* Manages package execution via npx/pnpm dlx/yarn dlx commands.
*
* Key Functions:
* - spawnCdxgenDlx: Execute CycloneDX generator via dlx
* - spawnCoanaDlx: Execute Coana CLI tool via dlx
* - spawnDlx: Execute packages using dlx-style commands
* - spawnSynpDlx: Execute Synp converter via dlx
*
* Package Manager Detection:
* - Auto-detects npm, pnpm, or yarn based on lockfiles
* - Supports force-refresh and silent execution modes
*
* Integration:
* - Works with shadow binaries for security scanning
* - Handles version pinning and cache management
* - Configures environment for third-party tools
*/
import { createRequire } from 'node:module'
import { getOwn } from '@socketsecurity/registry/lib/objects'
import { spawn } from '@socketsecurity/registry/lib/spawn'
import { getDefaultOrgSlug } from '../commands/ci/fetch-default-org-slug.mts'
import constants, {
CI,
FLAG_QUIET,
FLAG_SILENT,
NPM,
PNPM,
VITEST,
YARN,
} from '../constants.mts'
import { getErrorCause } from './errors.mts'
import { findUp } from './fs.mts'
import { getDefaultApiToken, getDefaultProxyUrl } from './sdk.mts'
import { isYarnBerry } from './yarn-version.mts'
import type { ShadowBinOptions, ShadowBinResult } from '../shadow/npm-base.mts'
import type { CResult } from '../types.mts'
import type { SpawnExtra } from '@socketsecurity/registry/lib/spawn'
const require = createRequire(import.meta.url)
const { PACKAGE_LOCK_JSON, PNPM_LOCK_YAML, YARN_LOCK } = constants
export type DlxOptions = ShadowBinOptions & {
force?: boolean | undefined
agent?: 'npm' | 'pnpm' | 'yarn' | undefined
silent?: boolean | undefined
}
export type DlxPackageSpec = {
name: string
version: string
}
/**
* Regex to check if a version string contains range operators.
* Matches any version with range operators: ~, ^, >, <, =, x, X, *, spaces, or ||.
*/
const rangeOperatorsRegExp = /[~^><=xX* ]|\|\|/
/**
* Spawns a package using dlx-style execution (npx/pnpm dlx/yarn dlx).
* Automatically detects the appropriate package manager if not specified.
* Uses force/update flags to ensure the latest version within the range is fetched.
*/
export async function spawnDlx(
packageSpec: DlxPackageSpec,
args: string[] | readonly string[],
options?: DlxOptions | undefined,
spawnExtra?: SpawnExtra | undefined,
): Promise<ShadowBinResult> {
// If version is not pinned exactly, default to force and silent for better UX.
const isNotPinned = rangeOperatorsRegExp.test(packageSpec.version)
const {
agent,
force = false,
silent = isNotPinned,
...shadowOptions
} = options ?? {}
let finalShadowOptions = shadowOptions
let pm = agent
// Auto-detect package manager if not specified.
if (!pm) {
const pnpmLockPath = await findUp(PNPM_LOCK_YAML, { onlyFiles: true })
const yarnLockPath = pnpmLockPath
? undefined
: await findUp(YARN_LOCK, { onlyFiles: true })
const npmLockPath =
pnpmLockPath || yarnLockPath
? undefined
: await findUp(PACKAGE_LOCK_JSON, { onlyFiles: true })
if (pnpmLockPath) {
pm = PNPM
} else if (yarnLockPath) {
pm = YARN
} else if (npmLockPath) {
pm = NPM
} else {
// Default to npm if no lockfile found.
pm = NPM
}
}
const packageString = `${packageSpec.name}@${packageSpec.version}`
// Build command args based on package manager.
let spawnArgs: string[]
if (pm === PNPM) {
spawnArgs = []
// The --silent flag must come before dlx, not after.
if (silent) {
spawnArgs.push(FLAG_SILENT)
}
spawnArgs.push('dlx')
if (force) {
// For pnpm, set dlx-cache-max-age to 0 via env to force fresh download.
// This ensures we always get the latest version within the range.
finalShadowOptions = {
...finalShadowOptions,
env: {
...getOwn(finalShadowOptions, 'env'),
// Set dlx cache max age to 0 minutes to bypass cache.
// The npm_config_ prefix is how pnpm reads config from environment variables.
// See: https://pnpm.io/npmrc#settings
npm_config_dlx_cache_max_age: '0',
},
}
}
spawnArgs.push(packageString, ...args)
const shadowPnpmBin = /*@__PURE__*/ require(constants.shadowPnpmBinPath)
return await shadowPnpmBin(spawnArgs, finalShadowOptions, spawnExtra)
} else if (pm === YARN && isYarnBerry()) {
spawnArgs = ['dlx']
// Yarn dlx runs in a temporary environment by design and should always fetch fresh.
if (silent) {
spawnArgs.push(FLAG_QUIET)
}
spawnArgs.push(packageString, ...args)
const shadowYarnBin = /*@__PURE__*/ require(constants.shadowYarnBinPath)
return await shadowYarnBin(spawnArgs, finalShadowOptions, spawnExtra)
} else {
// Use npm exec/npx.
// For consistency, we'll use npx which is more commonly used for one-off execution.
spawnArgs = ['--yes']
if (force) {
// Use --force to bypass cache and get latest within range.
spawnArgs.push('--force')
}
if (silent) {
spawnArgs.push(FLAG_SILENT)
}
spawnArgs.push(packageString, ...args)
const shadowNpxBin = /*@__PURE__*/ require(constants.shadowNpxBinPath)
return await shadowNpxBin(spawnArgs, finalShadowOptions, spawnExtra)
}
}
export type CoanaDlxOptions = DlxOptions & {
coanaVersion?: string | undefined
}
/**
* Helper to spawn coana with dlx.
* Automatically uses force and silent when version is not pinned exactly.
* Returns a CResult with stdout extraction for backward compatibility.
*
* If SOCKET_CLI_COANA_LOCAL_PATH environment variable is set, uses the local
* Coana CLI at that path instead of downloading from npm.
*/
export async function spawnCoanaDlx(
args: string[] | readonly string[],
orgSlug?: string,
options?: CoanaDlxOptions | undefined,
spawnExtra?: SpawnExtra | undefined,
): Promise<CResult<string>> {
const {
coanaVersion,
env: spawnEnv,
ipc,
...dlxOptions
} = {
__proto__: null,
...options,
} as CoanaDlxOptions
const mixinsEnv: Record<string, string> = {
SOCKET_CLI_VERSION: constants.ENV.INLINED_SOCKET_CLI_VERSION,
}
const defaultApiToken = getDefaultApiToken()
if (defaultApiToken) {
mixinsEnv['SOCKET_CLI_API_TOKEN'] = defaultApiToken
}
if (orgSlug) {
mixinsEnv['SOCKET_ORG_SLUG'] = orgSlug
} else {
const orgSlugCResult = await getDefaultOrgSlug()
if (orgSlugCResult.ok) {
mixinsEnv['SOCKET_ORG_SLUG'] = orgSlugCResult.data
}
}
const proxyUrl = getDefaultProxyUrl()
if (proxyUrl) {
mixinsEnv['SOCKET_CLI_API_PROXY'] = proxyUrl
}
try {
const localCoanaPath = process.env['SOCKET_CLI_COANA_LOCAL_PATH']
// Use local Coana CLI if path is provided.
if (localCoanaPath) {
const isBinary =
!localCoanaPath.endsWith('.js') && !localCoanaPath.endsWith('.mjs')
const finalEnv = {
...process.env,
...constants.processEnv,
...mixinsEnv,
...spawnEnv,
}
const spawnArgs = isBinary ? args : [localCoanaPath, ...args]
const spawnResult = await spawn(
isBinary ? localCoanaPath : 'node',
spawnArgs,
{
cwd: dlxOptions.cwd,
env: finalEnv,
stdio: spawnExtra?.['stdio'] || 'inherit',
},
)
return { ok: true, data: spawnResult.stdout }
}
// Use npm/dlx version.
const result = await spawnDlx(
{
name: '@coana-tech/cli',
version:
coanaVersion ||
constants.ENV.INLINED_SOCKET_CLI_COANA_TECH_CLI_VERSION,
},
args,
{
force: true,
silent: true,
...dlxOptions,
env: {
...process.env,
...constants.processEnv,
...mixinsEnv,
...spawnEnv,
},
ipc: {
[constants.SOCKET_CLI_SHADOW_ACCEPT_RISKS]: true,
[constants.SOCKET_CLI_SHADOW_API_TOKEN]:
constants.SOCKET_PUBLIC_API_TOKEN,
[constants.SOCKET_CLI_SHADOW_SILENT]: true,
...ipc,
},
},
spawnExtra,
)
const output = await result.spawnPromise
// Print output when running in e2e-tests workflow for debugging.
// Respect the silent option from the caller.
if (CI && VITEST && !dlxOptions.silent) {
if (output.stdout) {
console.log(output.stdout)
}
if (output.stderr) {
console.error(output.stderr)
}
}
return { ok: true, data: output.stdout }
} catch (e) {
const stdout = (e as any)?.stdout
const stderr = (e as any)?.stderr
// Print output when running in e2e-tests workflow for debugging.
// Respect the silent option from the caller.
if (CI && VITEST && !dlxOptions.silent) {
if (stdout) {
console.log(stdout)
}
if (stderr) {
console.error(stderr)
}
}
const cause = getErrorCause(e)
const message = stderr || cause
return {
ok: false,
data: e,
message,
}
}
}
/**
* Helper to spawn cdxgen with dlx.
*/
export async function spawnCdxgenDlx(
args: string[] | readonly string[],
options?: DlxOptions | undefined,
spawnExtra?: SpawnExtra | undefined,
): Promise<ShadowBinResult> {
return await spawnDlx(
{
name: '@cyclonedx/cdxgen',
version: constants.ENV.INLINED_SOCKET_CLI_CYCLONEDX_CDXGEN_VERSION,
},
args,
{ force: false, silent: true, ...options },
spawnExtra,
)
}
/**
* Helper to spawn synp with dlx.
*/
export async function spawnSynpDlx(
args: string[] | readonly string[],
options?: DlxOptions | undefined,
spawnExtra?: SpawnExtra | undefined,
): Promise<ShadowBinResult> {
return await spawnDlx(
{
name: 'synp',
version: `${constants.ENV.INLINED_SOCKET_CLI_SYNP_VERSION}`,
},
args,
{ force: false, silent: true, ...options },
spawnExtra,
)
}