cve-lite-cli 1.41.5 → 1.42.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/README.md +22 -19
  2. package/dist/advisory/detail-resolution.js +62 -0
  3. package/dist/advisory/local-db.js +90 -15
  4. package/dist/advisory/osv-advisory-source.js +113 -62
  5. package/dist/advisory/osv-sync.js +18 -16
  6. package/dist/advisory/sqlite.js +50 -0
  7. package/dist/audit-log/ndjson-writer.js +6 -3
  8. package/dist/audit-log/open-error.js +22 -0
  9. package/dist/cli/args.js +145 -87
  10. package/dist/cli/flags.js +2 -0
  11. package/dist/cli/help.js +6 -2
  12. package/dist/cli/overrides.js +5 -2
  13. package/dist/cli/validate.js +45 -5
  14. package/dist/constants.js +10 -0
  15. package/dist/index.js +15 -6
  16. package/dist/licenses/license-check.js +17 -4
  17. package/dist/osv/cache.js +7 -13
  18. package/dist/output/cyclonedx.js +57 -18
  19. package/dist/output/finding-display.js +8 -1
  20. package/dist/output/formatters.js +52 -11
  21. package/dist/output/html-reporter.js +40 -8
  22. package/dist/output/override-findings-terminal.js +21 -13
  23. package/dist/output/printers.js +185 -76
  24. package/dist/output/sarif.js +182 -16
  25. package/dist/output/spdx.js +15 -1
  26. package/dist/output/write-outputs.js +29 -20
  27. package/dist/overrides/context-builder.js +1 -7
  28. package/dist/overrides/detectors/oa005-nested-ineffective.js +6 -1
  29. package/dist/overrides/detectors/oa008-materialized.js +33 -10
  30. package/dist/overrides/detectors/oa009-stale-floor.js +2 -2
  31. package/dist/overrides/detectors/oa010-vulnerable-floor.js +19 -13
  32. package/dist/overrides/detectors/phantom-utils.js +2 -10
  33. package/dist/overrides/fixer.js +13 -2
  34. package/dist/overrides/index.js +1 -0
  35. package/dist/overrides/types.js +15 -1
  36. package/dist/parsers/bun-lock.js +6 -0
  37. package/dist/parsers/index.js +177 -40
  38. package/dist/parsers/multi-package.js +4 -0
  39. package/dist/parsers/package-lock.js +6 -2
  40. package/dist/parsers/pnpm-lock.js +4 -7
  41. package/dist/parsers/requirements-txt.js +185 -0
  42. package/dist/parsers/utils.js +11 -6
  43. package/dist/parsers/yarn-lock.js +1 -5
  44. package/dist/remediation/fix-commands.js +60 -36
  45. package/dist/remediation/parent-update-child-note.js +3 -2
  46. package/dist/scan/completeness.js +57 -4
  47. package/dist/scan/multi-folder-scan.js +27 -13
  48. package/dist/scan/single-scan.js +118 -37
  49. package/dist/scanner.js +59 -36
  50. package/dist/types.js +1 -1
  51. package/dist/utils/array.js +5 -0
  52. package/dist/utils/baseline.js +8 -2
  53. package/dist/utils/chalk.js +1 -3
  54. package/dist/utils/create-pr.js +2 -2
  55. package/dist/utils/debug-bundle.js +37 -22
  56. package/dist/utils/debug-project.js +6 -5
  57. package/dist/utils/debug-redaction.js +1 -1
  58. package/dist/utils/effective-options.js +5 -1
  59. package/dist/utils/finding.js +4 -0
  60. package/dist/utils/fix-runner.js +110 -36
  61. package/dist/utils/import-type-queries.js +5 -1
  62. package/dist/utils/install-command.js +6 -0
  63. package/dist/utils/malicious.js +11 -0
  64. package/dist/utils/package-identity.js +12 -2
  65. package/dist/utils/path-coverage.js +1 -5
  66. package/dist/utils/sanitize.js +59 -0
  67. package/dist/utils/sbom-format.js +17 -8
  68. package/dist/utils/severity.js +61 -7
  69. package/dist/utils/url.js +175 -0
  70. package/dist/utils/version.js +44 -0
  71. package/dist/utils/vuln.js +11 -14
  72. package/package.json +2 -4
@@ -84,8 +84,8 @@ export function buildPullRequestBody(params) {
84
84
  const advisoryPackage = item.childPackage ?? item.package;
85
85
  const advisoryIds = collectAdvisoryIdsForPackage(params.findingsBeforeFix, advisoryPackage);
86
86
  const advisoryText = advisoryIds.length > 0 ? advisoryIds.join(", ") : "n/a";
87
- const childNote = formatParentUpdateChildNote(item);
88
- const versionLine = `- **${item.package}**: \`${item.from}\` → \`${item.to}\``;
87
+ const childNote = formatParentUpdateChildNote(item, { codeSpan: true });
88
+ const versionLine = `- **\`${item.package}\`**: \`${item.from}\` → \`${item.to}\``;
89
89
  lines.push(childNote ? `${versionLine} (${childNote})` : versionLine);
90
90
  lines.push(` - Advisories: ${advisoryText}`);
91
91
  }
@@ -1,26 +1,34 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
3
  import { getCliVersion } from "./version-info.js";
4
- import { summarizeEffectiveOptions } from "./effective-options.js";
4
+ import { resolveSearchDepth, summarizeEffectiveOptions } from "./effective-options.js";
5
5
  import { createBundleRedactor } from "./debug-redaction.js";
6
- import { findNpmLockfile } from "./npm-lockfile.js";
6
+ import { PACKAGE_MANAGER_BY_LOCKFILE } from "../constants.js";
7
+ import { selectScanLockfile } from "../parsers/index.js";
8
+ import { isMultiFolderScan } from "../parsers/multi-package.js";
7
9
  import { buildProjectJson as projectMetadata } from "./debug-project.js";
8
10
  export { redactDeep, redactPath } from "./debug-redaction.js";
9
- function detectPackageManager(projectPath) {
10
- if (fs.existsSync(path.join(projectPath, "pnpm-lock.yaml")))
11
- return "pnpm";
12
- if (fs.existsSync(path.join(projectPath, "bun.lockb")) || fs.existsSync(path.join(projectPath, "bun.lock")))
13
- return "bun";
14
- if (fs.existsSync(path.join(projectPath, "yarn.lock")))
15
- return "yarn";
16
- if (findNpmLockfile(projectPath))
17
- return "npm";
18
- return "unknown";
11
+ /** A multi-folder run reads several lockfiles, so no single one describes it. */
12
+ const MULTIPLE_LOCKFILES = "multiple";
13
+ /**
14
+ * The lockfile this run's scan reads, chosen by the scan's own rules, so the
15
+ * bundle describes that file rather than whatever sits at the scan root (#1514).
16
+ */
17
+ function scanLockfile(options, projectPath) {
18
+ const depth = resolveSearchDepth(options);
19
+ if (isMultiFolderScan(projectPath, depth))
20
+ return MULTIPLE_LOCKFILES;
21
+ return selectScanLockfile(projectPath, depth);
19
22
  }
20
- function readLockfileVersion(projectPath) {
21
- const lockPath = findNpmLockfile(projectPath);
22
- if (lockPath === null)
23
- return null;
23
+ function packageManagerFor(lockfile, projectPath) {
24
+ if (lockfile === MULTIPLE_LOCKFILES)
25
+ return MULTIPLE_LOCKFILES;
26
+ if (lockfile !== null)
27
+ return PACKAGE_MANAGER_BY_LOCKFILE[lockfile.name];
28
+ // bun.lockb is not scanned, but naming the manager still helps a report.
29
+ return fs.existsSync(path.join(projectPath, "bun.lockb")) ? "bun" : "unknown";
30
+ }
31
+ function readLockfileVersion(lockPath) {
24
32
  try {
25
33
  const parsed = JSON.parse(fs.readFileSync(lockPath, "utf8"));
26
34
  return typeof parsed.lockfileVersion === "number" ? parsed.lockfileVersion : null;
@@ -29,15 +37,21 @@ function readLockfileVersion(projectPath) {
29
37
  return null;
30
38
  }
31
39
  }
32
- export function buildEnvironmentJson(options, projectPath) {
33
- const packageManager = detectPackageManager(projectPath);
40
+ /** The npm lockfile the scan reads, or null when the scan reads another manager's. */
41
+ function npmLockfilePath(lockfile) {
42
+ if (lockfile === null || lockfile === MULTIPLE_LOCKFILES)
43
+ return null;
44
+ return PACKAGE_MANAGER_BY_LOCKFILE[lockfile.name] === "npm" ? lockfile.filePath : null;
45
+ }
46
+ export function buildEnvironmentJson(options, projectPath, lockfile = scanLockfile(options, projectPath)) {
47
+ const npmLockfile = npmLockfilePath(lockfile);
34
48
  return {
35
49
  cliVersion: getCliVersion(),
36
50
  nodeVersion: process.version,
37
51
  platform: process.platform,
38
52
  arch: process.arch,
39
- packageManager,
40
- lockfileVersion: packageManager === "npm" ? readLockfileVersion(projectPath) : null,
53
+ packageManager: packageManagerFor(lockfile, projectPath),
54
+ lockfileVersion: npmLockfile === null ? null : readLockfileVersion(npmLockfile),
41
55
  nodeModulesPresent: fs.existsSync(path.join(projectPath, "node_modules")),
42
56
  effectiveFlags: summarizeEffectiveOptions(options),
43
57
  osvEndpoint: {
@@ -79,8 +93,9 @@ export function createDebugBundle(events, options, projectPath, scanJsonPath) {
79
93
  }
80
94
  catch { /* An unavailable scan artifact does not prevent a diagnostic bundle. */ }
81
95
  }
82
- const environment = buildEnvironmentJson(options, projectPath);
83
- const project = projectMetadata(events, projectPath);
96
+ const lockfile = scanLockfile(options, projectPath);
97
+ const environment = buildEnvironmentJson(options, projectPath, lockfile);
98
+ const project = projectMetadata(events, projectPath, npmLockfilePath(lockfile));
84
99
  const redact = createBundleRedactor(projectPath, [events, options, environment, project, scan]);
85
100
  const ts = new Date().toISOString().replace(/[:.]/g, "-").slice(0, 19);
86
101
  // A unique directory prevents a same-second run from inheriting scan.json
@@ -39,9 +39,8 @@ function readWorkspaceGlobs(projectPath) {
39
39
  return null;
40
40
  }
41
41
  }
42
- /** Count package entries explicitly marked as links in npm's active lockfile. */
43
- function readNpmLinkEntryCount(projectPath) {
44
- const lockPath = findNpmLockfile(projectPath);
42
+ /** Count package entries explicitly marked as links in the npm lockfile the scan reads. */
43
+ function readNpmLinkEntryCount(lockPath) {
45
44
  if (lockPath === null)
46
45
  return null;
47
46
  try {
@@ -58,13 +57,15 @@ function readNpmLinkEntryCount(projectPath) {
58
57
  * Build project metadata from debug events and project declaration files.
59
58
  * Workspace member names/counts are intentionally never inferred from lockfile maps.
60
59
  */
61
- export function buildProjectJson(events, projectPath) {
60
+ export function buildProjectJson(events, projectPath,
61
+ /** The npm lockfile the scan reads, or null when it reads another manager's. */
62
+ npmLockfile = findNpmLockfile(projectPath)) {
62
63
  const project = {};
63
64
  const skippedRules = [];
64
65
  const workspaceGlobs = readWorkspaceGlobs(projectPath);
65
66
  if (workspaceGlobs !== null)
66
67
  project.workspaceGlobs = workspaceGlobs;
67
- const linkEntryCount = readNpmLinkEntryCount(projectPath);
68
+ const linkEntryCount = readNpmLinkEntryCount(npmLockfile);
68
69
  if (linkEntryCount !== null)
69
70
  project.linkEntryCount = linkEntryCount;
70
71
  for (const event of events) {
@@ -1,7 +1,7 @@
1
1
  import os from "node:os";
2
2
  import path from "node:path";
3
+ import { SECRET_KEY } from "./url.js";
3
4
  const URL_PATTERN = /[a-z][a-z\d+.-]*:\/\/[^\s<>"'`]+/gi;
4
- const SECRET_KEY = /^(?:password|passwd|_authToken|_auth|authToken|token|authorization|credentials?|apiKey|secret|accessToken|refreshToken)$/i;
5
5
  const PRIVATE_VALUE_KEY = /^(?:cacheDir|offlineDb|output|caCert|nodeExtraCaCerts|auditLog|report|osvUrl|proxy|httpsProxy|httpProxy)$/i;
6
6
  /** One context for every file: hostnames and credentials also occur bare in errors. */
7
7
  export function createBundleRedactor(projectPath, inputs) {
@@ -1,4 +1,8 @@
1
1
  import { DEFAULT_BATCH_SIZE, DEFAULT_SEARCH_DEPTH } from "../constants.js";
2
+ /** How deep nested lockfile discovery searches, resolved as the CLI resolves it. */
3
+ export function resolveSearchDepth(options) {
4
+ return Math.max(0, Number(options.searchDepth || DEFAULT_SEARCH_DEPTH));
5
+ }
2
6
  export function summarizeEffectiveOptions(options) {
3
7
  const summary = {
4
8
  json: options.json ?? false,
@@ -26,7 +30,7 @@ export function summarizeEffectiveOptions(options) {
26
30
  incompletePolicy: options.incompletePolicy,
27
31
  // Same normalization as the CLI entrypoint (src/index.ts).
28
32
  batchSize: Number(options.batchSize || DEFAULT_BATCH_SIZE),
29
- searchDepth: Math.max(0, Number(options.searchDepth || DEFAULT_SEARCH_DEPTH)),
33
+ searchDepth: resolveSearchDepth(options),
30
34
  };
31
35
  if (options.minSeverity !== undefined)
32
36
  summary.minSeverity = options.minSeverity;
@@ -1,3 +1,7 @@
1
+ import { isPep440Ecosystem } from "./version.js";
2
+ export function isGatableFinding(finding) {
3
+ return !isPep440Ecosystem(finding.pkg.ecosystem);
4
+ }
1
5
  export function isUnconfirmedFix(finding) {
2
6
  return finding.relationship === "direct"
3
7
  && finding.validatedFirstFixedVersion === null
@@ -7,34 +7,91 @@ import { pluralize } from "./string.js";
7
7
  import { isBreakingUpgrade } from "./version.js";
8
8
  import { installPackageSpec, isOptionShapedName } from "./package-identity.js";
9
9
  import { formatParentUpdateChildNote } from "../remediation/parent-update-child-note.js";
10
+ import { INSTALL_COMMANDS } from "./install-command.js";
11
+ import { shellQuote } from "./shell-quote.js";
12
+ const OUTPUT_LIMIT = 8 * 1024;
13
+ // Only these known codes can leave the package manager's error output.
14
+ const NPM_CODE = "(?:ERESOLVE|EACCES|ENOENT|ETARGET|EINTEGRITY|EAUTH|E401|E403|E404|ENOTFOUND|ECONNREFUSED|ETIMEDOUT)";
15
+ const PNPM_CODE = "ERR_PNPM_(?:OUTDATED_LOCKFILE|PEER_DEP_ISSUES|TARBALL_INTEGRITY|NO_OFFLINE_META|UNEXPECTED_STORE|FETCH_404|META_FETCH_FAIL|LOCKFILE_CONFIG_MISMATCH)";
16
+ const YARN_FAILURE_CODE = "(?:YN0001|YN0009|YN0016|YN0020|YN0021|YN0035|YN0047|YN0082)";
17
+ const CODE = new RegExp(`^(?:${NPM_CODE}|${PNPM_CODE}|${YARN_FAILURE_CODE})$`);
18
+ const ERROR_LINE = new RegExp(`^(?:npm (?:ERR!|error) (?:code )?(${NPM_CODE})\\b|\\[?(${PNPM_CODE})\\b\\]?|(?:➤\\s*)?(${YARN_FAILURE_CODE}):|(${NPM_CODE}|${PNPM_CODE})$)`);
19
+ const JSON_CODE = new RegExp(`^\\s*\\{.*?"code"\\s*:\\s*"(${NPM_CODE}|${PNPM_CODE})"`);
20
+ function fixErrorCode(output) {
21
+ let yarnFailureCode;
22
+ for (const line of output.split(/\r?\n/)) {
23
+ const match = line.trim().match(ERROR_LINE) ?? line.match(JSON_CODE);
24
+ const code = match?.[1] ?? match?.[2] ?? match?.[3] ?? match?.[4];
25
+ if (match?.[3])
26
+ yarnFailureCode = match[3];
27
+ else if (code)
28
+ return code;
29
+ }
30
+ return yarnFailureCode;
31
+ }
32
+ export function retainOutputTail(previous, chunk) {
33
+ if (chunk.byteLength >= OUTPUT_LIMIT) {
34
+ return Buffer.from(chunk.subarray(chunk.byteLength - OUTPUT_LIMIT));
35
+ }
36
+ const data = Buffer.concat([previous, chunk]);
37
+ return Buffer.from(data.subarray(Math.max(0, data.length - OUTPUT_LIMIT)));
38
+ }
39
+ export function formatRetryHint(commandParts, cwd, platform = process.platform, currentDirectory = process.cwd()) {
40
+ const pathApi = platform === "win32" ? path.win32 : path.posix;
41
+ const relativeDirectory = pathApi.relative(currentDirectory, cwd);
42
+ const crossDrive = platform === "win32" && pathApi.isAbsolute(relativeDirectory);
43
+ const parentDirectory = relativeDirectory === ".." || relativeDirectory.startsWith(`..${pathApi.sep}`);
44
+ const manualDirectory = crossDrive || parentDirectory;
45
+ const directory = manualDirectory ? "" : relativeDirectory;
46
+ if (platform === "win32") {
47
+ const quotePowerShell = (token) => "'" + token.replace(/'/g, "''") + "'";
48
+ const command = `& ${commandParts.map(quotePowerShell).join(" ")}`;
49
+ if (manualDirectory) {
50
+ return `Hint: In PowerShell, change to the project directory, then run ${command} for full details.`;
51
+ }
52
+ const changeDirectory = directory ? `Set-Location -LiteralPath ${quotePowerShell(directory)} -ErrorAction Stop; ` : "";
53
+ return `Hint: In PowerShell, run ${changeDirectory}${command} for full details.`;
54
+ }
55
+ if (manualDirectory) {
56
+ return `Hint: Change to the project directory, then run ${commandParts.map(shellQuote).join(" ")} for full details.`;
57
+ }
58
+ const changeDirectory = directory ? `cd ${shellQuote(`./${directory}`)} && ` : "";
59
+ return `Hint: Run ${changeDirectory}${commandParts.map(shellQuote).join(" ")} for full details.`;
60
+ }
10
61
  export async function runInstallCommand(command, args, cwd, debugLog) {
11
62
  const commandLine = [command, ...args].join(" ");
12
63
  debugLog?.("Fix command", { command: commandLine, cwd });
13
64
  return await new Promise(resolve => {
65
+ let stdout = Buffer.alloc(0);
66
+ let stderr = Buffer.alloc(0);
14
67
  const child = spawn(command, args, {
15
68
  cwd,
16
69
  stdio: ["ignore", "pipe", "pipe"],
17
70
  });
18
- child.stdout.on("data", () => { });
19
- child.stderr.on("data", () => { });
71
+ child.stdout.on("data", (chunk) => {
72
+ stdout = retainOutputTail(stdout, chunk);
73
+ });
74
+ child.stderr.on("data", (chunk) => {
75
+ stderr = retainOutputTail(stderr, chunk);
76
+ });
20
77
  child.on("error", error => {
21
- debugLog?.("Fix command finished", { command: commandLine, exitCode: null, error: error.message });
22
- resolve({ status: null, error });
78
+ const nodeCode = error.code;
79
+ const errorCode = nodeCode && CODE.test(nodeCode) ? nodeCode : undefined;
80
+ debugLog?.("Fix command finished", { command: commandLine, exitCode: null, errorCode });
81
+ resolve({ status: null, error, errorCode });
23
82
  });
24
83
  child.on("close", code => {
25
84
  debugLog?.("Fix command finished", { command: commandLine, exitCode: code });
26
- resolve({ status: code, error: null });
85
+ if (code === 0) {
86
+ resolve({ status: code, error: null });
87
+ return;
88
+ }
89
+ resolve({ status: code, error: null, errorCode: fixErrorCode(stderr.toString("utf8")) ?? fixErrorCode(stdout.toString("utf8")) });
27
90
  });
28
91
  });
29
92
  }
30
93
  export function commandLabelForPackageManager(packageManager) {
31
- if (packageManager === "npm")
32
- return "npm install";
33
- if (packageManager === "pnpm")
34
- return "pnpm add";
35
- if (packageManager === "bun")
36
- return "bun add";
37
- return "yarn add";
94
+ return INSTALL_COMMANDS[packageManager].join(" ");
38
95
  }
39
96
  // Categorize the fixes that --fix does NOT auto-apply. Direct upgrades and
40
97
  // within-range refreshes (parent-update) are auto-applied, so only parent
@@ -74,57 +131,72 @@ export function buildApplyCommands(packageManager, target) {
74
131
  return buildInstallApplyArgv(packageManager, target);
75
132
  }
76
133
  function buildInstallApplyArgv(packageManager, target) {
77
- const workspaces = (target.workspaces ?? []).filter(w => w !== ".");
134
+ const workspaces = target.workspaces ?? [];
78
135
  const pkgArg = installPackageSpec(target);
79
136
  if (isOptionShapedName(pkgArg))
80
137
  return [];
81
138
  const isDev = Boolean(target.isDev);
139
+ const [executable, subcommand] = INSTALL_COMMANDS[packageManager];
82
140
  if (packageManager === "npm") {
83
- const args = ["install"];
141
+ const args = [subcommand];
84
142
  if (isDev)
85
143
  args.push("-D");
86
- for (const ws of workspaces) {
144
+ for (const ws of workspaces.filter(w => w !== ".")) {
87
145
  args.push("-w", ws);
88
146
  }
89
147
  args.push(pkgArg);
90
- return [["npm", ...args]];
148
+ return [[executable, ...args]];
91
149
  }
92
150
  if (packageManager === "pnpm") {
93
151
  const args = [];
94
- for (const ws of workspaces) {
152
+ for (const ws of workspaces.filter(w => w !== ".")) {
95
153
  args.push("--filter", `./${ws}`);
96
154
  }
97
- args.push("add");
155
+ args.push(subcommand);
98
156
  if (isDev)
99
157
  args.push("-D");
100
158
  args.push(pkgArg);
101
- return [["pnpm", ...args]];
159
+ return [[executable, ...args]];
102
160
  }
103
161
  if (packageManager === "yarn") {
104
- if (workspaces.length === 0) {
105
- const args = ["add"];
162
+ const nonRoot = workspaces.filter(w => w !== ".");
163
+ if (nonRoot.length === 0) {
164
+ const args = [subcommand];
106
165
  if (isDev)
107
166
  args.push("-D");
108
167
  args.push(pkgArg);
109
- return [["yarn", ...args]];
168
+ return [[executable, ...args]];
110
169
  }
111
- return workspaces.map(ws => {
112
- const args = ["workspace", ws, "add"];
170
+ return nonRoot.map(ws => {
171
+ const args = ["workspace", ws, subcommand];
113
172
  if (isDev)
114
173
  args.push("-D");
115
174
  args.push(pkgArg);
116
- return ["yarn", ...args];
175
+ return [executable, ...args];
117
176
  });
118
177
  }
119
- // bun
120
- const args = ["add"];
121
- if (isDev)
122
- args.push("--dev");
123
- for (const ws of workspaces) {
124
- args.push("--filter", ws);
178
+ // bun. --filter for add only works from Bun 1.4.0, so run from the member
179
+ // directory via --cwd, which works on older releases and never edits root.
180
+ // When declared in both root and members, emit a plain add for the root
181
+ // alongside the member command(s).
182
+ const hasRoot = workspaces.includes(".");
183
+ const nonRoot = workspaces.filter(ws => ws !== ".");
184
+ const runs = [];
185
+ if (hasRoot || nonRoot.length === 0) {
186
+ const args = [subcommand];
187
+ if (isDev)
188
+ args.push("--dev");
189
+ args.push(pkgArg);
190
+ runs.push([executable, ...args]);
191
+ }
192
+ for (const ws of nonRoot) {
193
+ const args = [subcommand];
194
+ if (isDev)
195
+ args.push("--dev");
196
+ args.push("--cwd", ws, pkgArg);
197
+ runs.push([executable, ...args]);
125
198
  }
126
- args.push(pkgArg);
127
- return [["bun", ...args]];
199
+ return runs;
128
200
  }
129
201
  function buildParentUpdateApplyArgv(packageManager, target) {
130
202
  // Always build from structured fields. Never tokenize target.command: plan
@@ -199,7 +271,6 @@ export async function applyFixesIfRequested(params) {
199
271
  const commandLabel = commandLabelForPackageManager(params.plan.packageManager);
200
272
  const total = runnableTargets.length;
201
273
  const spinner = createSpinner(`Applying safe package fixes with ${commandLabel}... 0/${total}`, params.options);
202
- const fixHint = `\nHint: Check that \`${params.plan.packageManager}\` is available and you have write access to node_modules.\nIf running in CI, ensure the install step has already run before cve-lite --fix.`;
203
274
  // parent-update is keyed per child, so two children behind one parent produce
204
275
  // two targets. npm update names the child, so those commands differ. Two
205
276
  // parents that refresh the same child can still share `npm update <child>`.
@@ -209,6 +280,7 @@ export async function applyFixesIfRequested(params) {
209
280
  const target = runnableTargets[i];
210
281
  for (const commandParts of buildApplyCommands(params.plan.packageManager, target)) {
211
282
  const commandLine = commandParts.join(" ");
283
+ const retryHint = `\n${formatRetryHint(commandParts, params.projectPath)}\nCheck that \`${params.plan.packageManager}\` is available and you have write access to node_modules.\nIf running in CI, ensure the install step has already run before cve-lite --fix.`;
212
284
  if (seenCommands.has(commandLine))
213
285
  continue;
214
286
  seenCommands.add(commandLine);
@@ -216,11 +288,13 @@ export async function applyFixesIfRequested(params) {
216
288
  const run = await runCommand(commandParts[0], commandParts.slice(1), params.projectPath, params.debugLog);
217
289
  if (run.error) {
218
290
  spinner.fail("Failed to apply fixes");
219
- throw new Error(`Failed to apply fixes: ${run.error.message}${fixHint}`);
291
+ const detail = run.errorCode ? `\nPackage manager error: ${run.errorCode}` : "";
292
+ throw new Error(`Failed to apply fixes${detail}${retryHint}`);
220
293
  }
221
294
  if ((run.status ?? 1) !== 0) {
222
295
  spinner.fail(`Fix command failed (${commandLabel})`);
223
- throw new Error(`Fix command exited with status ${run.status ?? 1}${fixHint}`);
296
+ const detail = run.errorCode ? `\nPackage manager error: ${run.errorCode}` : "";
297
+ throw new Error(`Fix command exited with status ${run.status ?? 1}${detail}${retryHint}`);
224
298
  }
225
299
  }
226
300
  }
@@ -261,6 +261,11 @@ export function importTypeQueryOffsets(source) {
261
261
  addTypeQueries(tokens, queryStart ?? start, end, offsets);
262
262
  i = end - 1;
263
263
  }
264
+ collectSignatureTypeQueries(tokens, source, offsets);
265
+ return offsets;
266
+ }
267
+ /** Record type queries in function, class, method and arrow signatures. */
268
+ function collectSignatureTypeQueries(tokens, source, offsets) {
264
269
  const pairs = syntaxPairs(tokens);
265
270
  for (let i = 0; i < tokens.length; i++) {
266
271
  const text = tokens[i].text;
@@ -318,5 +323,4 @@ export function importTypeQueryOffsets(source) {
318
323
  }
319
324
  }
320
325
  }
321
- return offsets;
322
326
  }
@@ -0,0 +1,6 @@
1
+ export const INSTALL_COMMANDS = {
2
+ npm: ["npm", "install"],
3
+ pnpm: ["pnpm", "add"],
4
+ yarn: ["yarn", "add"],
5
+ bun: ["bun", "add"],
6
+ };
@@ -0,0 +1,11 @@
1
+ // MAL-* is the OSV prefix for malicious code advisories. Guarded because OSV
2
+ // records are external data - the declared `string` type on OsvVuln.id does
3
+ // not guarantee a malformed advisory record cannot have a missing/non-string id.
4
+ // Kept free of imports so the severity gate can use it without pulling in the
5
+ // advisory helpers.
6
+ export function isMaliciousVulnId(id) {
7
+ return typeof id === "string" && id.startsWith("MAL-");
8
+ }
9
+ export function hasMaliciousAdvisory(vulns) {
10
+ return vulns.some(v => isMaliciousVulnId(v.id));
11
+ }
@@ -13,13 +13,23 @@ export function packageInstanceKey(pkg) {
13
13
  export function packageNameKey(pkg) {
14
14
  return pkg.registryName ? `${pkg.name}\u0000${pkg.registryName}` : pkg.name;
15
15
  }
16
- export function npmAliasRegistryName(value) {
16
+ export function parseNpmAliasTarget(value) {
17
17
  if (typeof value !== "string" || !value.startsWith(NPM_ALIAS_PROTOCOL)) {
18
18
  return null;
19
19
  }
20
20
  const target = value.slice(NPM_ALIAS_PROTOCOL.length);
21
21
  const separator = target.lastIndexOf("@");
22
- return separator > 0 ? target.slice(0, separator) : target;
22
+ if (separator <= 0) {
23
+ return { name: target, spec: "" };
24
+ }
25
+ return {
26
+ name: target.slice(0, separator),
27
+ spec: target.slice(separator + 1).trim(),
28
+ };
29
+ }
30
+ export function npmAliasRegistryName(value) {
31
+ const parsed = parseNpmAliasTarget(value);
32
+ return parsed ? parsed.name : null;
23
33
  }
24
34
  /** Keep an npm alias when installing a newer version of its registry package. */
25
35
  export function installPackageSpec(target) {
@@ -1,3 +1,4 @@
1
+ import { pathsEqual } from "./array.js";
1
2
  export function calculatePathCoverage(knownPaths, coveredPath) {
2
3
  const coveredPaths = coveredPath && coveredPath.length > 0 ? [coveredPath] : [];
3
4
  const remainingPaths = knownPaths.filter(path => !coveredPaths.some(covered => pathsEqual(path, covered)));
@@ -10,8 +11,3 @@ export function calculatePathCoverage(knownPaths, coveredPath) {
10
11
  export function formatDependencyPath(path) {
11
12
  return path.join(" -> ");
12
13
  }
13
- function pathsEqual(left, right) {
14
- if (left.length !== right.length)
15
- return false;
16
- return left.every((value, index) => value === right[index]);
17
- }
@@ -0,0 +1,59 @@
1
+ /**
2
+ * Sanitization utilities for terminal output to prevent ANSI injection,
3
+ * terminal control escape sequences, and GitHub Actions workflow command injection
4
+ * (e.g. `\n::error::...` or legacy `##[error]...`).
5
+ */
6
+ export const ANSI_REGEX = /(?:\x1b\[|\u009b)[0-9:;<=>?]*[ -/]*[@-~]|(?:\x1b\]|\u009d)[^\x07\x1b\u009c\u009d]*(?:\x07|\x1b\\|\u009c)|(?:\x1b\]|\u009d)|\x1b[@-Z\\\]^_]/g;
7
+ // Non-SGR ANSI sequences (OSC, non-color CSI such as clear screen or cursor movements, 2-character escapes)
8
+ export const NON_SGR_ANSI_REGEX = /(?:\x1b\[|\u009b)[0-9:;<=>?]*[ -/]*[@A-Za-ln-z_`{|}~[\\\]^]|(?:\x1b\]|\u009d)[^\x07\x1b\u009c\u009d]*(?:\x07|\x1b\\|\u009c)|(?:\x1b\]|\u009d)|\x1b[@-Z\\\]^_]/g;
9
+ // Control characters in C0 (0x00-0x1F, 0x7F) and C1 (0x80-0x9F) ranges.
10
+ // 0x1B (ESC) is already included in 0x00-0x1F.
11
+ export const CONTROL_OR_ANSI_REGEX = /[\x00-\x1f\x7f\u0080-\u009f]/;
12
+ export const FIX_COMMAND_SUPPRESSED_MESSAGE = "Fix command suppressed: package, version, or subfolder contains control characters or a workflow command marker. Inspect package, version, and path inputs before rescanning.";
13
+ export function stripAnsi(text) {
14
+ return text.replace(ANSI_REGEX, "");
15
+ }
16
+ export function hasControlCharsOrAnsi(text) {
17
+ return CONTROL_OR_ANSI_REGEX.test(text);
18
+ }
19
+ /**
20
+ * Returns true if a package, version, parent identity, or command string contains control characters,
21
+ * ANSI escape sequences, or legacy workflow command markers (`##[`), preventing them from being safely
22
+ * presented or executed.
23
+ */
24
+ export function isMalformedOrUnsafeIdentity(value) {
25
+ if (!value)
26
+ return false;
27
+ return hasControlCharsOrAnsi(value) || /##\[/.test(value);
28
+ }
29
+ export function isCommandSuppressed(command) {
30
+ return isMalformedOrUnsafeIdentity(command);
31
+ }
32
+ /**
33
+ * Sanitizes untrusted strings (package names, versions, free-text lines) for terminal/stdout
34
+ * printing by stripping ANSI sequences and control characters, replacing newlines/tabs with spaces,
35
+ * and neutralizing legacy workflow command markers (`##[`).
36
+ */
37
+ export function sanitizeOutputString(value) {
38
+ if (!value)
39
+ return value;
40
+ return value
41
+ .replace(ANSI_REGEX, "")
42
+ .replace(/[\r\n\t\u0085]+/g, " ")
43
+ .replace(/[\x00-\x1f\x7f\u0080-\u009f]/g, "")
44
+ .replace(/##\[/g, "# #[");
45
+ }
46
+ /**
47
+ * Sanitizes a rendered table cell string, preserving chalk SGR color formatting
48
+ * while stripping non-color CSI escapes (e.g. clear-screen), OSC sequences (e.g. hyperlinks),
49
+ * carriage returns, BEL, other control characters, and legacy `##[` markers.
50
+ */
51
+ export function sanitizeTableCell(value) {
52
+ if (!value)
53
+ return value;
54
+ return value
55
+ .replace(NON_SGR_ANSI_REGEX, "")
56
+ .replace(/[\r\n\t\u0085]+/g, " ")
57
+ .replace(/[\x00-\x1a\x1c-\x1f\x7f\u0080-\u009f]/g, "")
58
+ .replace(/##\[/g, "# #[");
59
+ }
@@ -1,12 +1,21 @@
1
1
  /**
2
- * Resolves which SBOM format a run should emit, if any.
2
+ * Resolves all SBOM formats a run should emit, deduplicated.
3
3
  *
4
- * `--cdx` predates `--sbom` and remains supported, so it is honoured here as
5
- * well as in argument parsing. Keeping the alias in one place means callers
6
- * that build options programmatically behave the same as the CLI.
4
+ * `--sbom` takes precedence, and `--cdx` remains supported as a permanent
5
+ * alias that adds CycloneDX output if not already selected.
7
6
  */
8
- export function resolveSbomFormat(options) {
9
- if (options.sbom)
10
- return options.sbom;
11
- return options.cdx ? "cyclonedx" : undefined;
7
+ export function resolveSbomFormats(options) {
8
+ const formats = [];
9
+ if (options.sbom) {
10
+ const list = Array.isArray(options.sbom) ? options.sbom : [options.sbom];
11
+ for (const fmt of list) {
12
+ if (!formats.includes(fmt)) {
13
+ formats.push(fmt);
14
+ }
15
+ }
16
+ }
17
+ if (options.cdx && !formats.includes("cyclonedx")) {
18
+ formats.push("cyclonedx");
19
+ }
20
+ return formats;
12
21
  }