cve-lite-cli 1.40.0 → 1.41.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 (68) hide show
  1. package/README.md +17 -11
  2. package/dist/advisory/local-advisory-source.js +9 -5
  3. package/dist/advisory/local-db.js +91 -13
  4. package/dist/advisory/osv-sync.js +187 -56
  5. package/dist/advisory/staging-directory.js +112 -0
  6. package/dist/cli/advisories-sync.js +16 -2
  7. package/dist/cli/args.js +46 -35
  8. package/dist/cli/config.js +4 -1
  9. package/dist/cli/help.js +4 -3
  10. package/dist/cli/validate.js +23 -1
  11. package/dist/constants.js +11 -25
  12. package/dist/index.js +8 -3
  13. package/dist/output/cyclonedx.js +23 -14
  14. package/dist/output/debug.js +68 -18
  15. package/dist/output/formatters.js +33 -5
  16. package/dist/output/html-reporter.js +55 -5
  17. package/dist/output/multi-folder-html-reporter.js +59 -3
  18. package/dist/output/output-dir.js +193 -7
  19. package/dist/output/printers.js +16 -5
  20. package/dist/output/sarif.js +131 -48
  21. package/dist/output/sbom-dependency-edges.js +16 -10
  22. package/dist/output/sbom-file.js +14 -6
  23. package/dist/output/scan-json.js +21 -3
  24. package/dist/output/spdx.js +61 -23
  25. package/dist/output/spinner.js +2 -1
  26. package/dist/output/write-outputs.js +142 -52
  27. package/dist/overrides/context-builder.js +23 -70
  28. package/dist/parsers/bun-lock.js +1 -2
  29. package/dist/parsers/index.js +22 -1
  30. package/dist/parsers/npm-lock-graph.js +39 -1
  31. package/dist/parsers/package-lock.js +25 -5
  32. package/dist/parsers/pnpm-lock.js +3 -2
  33. package/dist/parsers/utils.js +5 -3
  34. package/dist/parsers/yarn-lock-graph.js +5 -2
  35. package/dist/parsers/yarn-lock.js +1 -2
  36. package/dist/remediation/fix-commands.js +105 -44
  37. package/dist/remediation/npm-transitive-graph.js +30 -72
  38. package/dist/remediation/npm-transitive-resolution.js +24 -77
  39. package/dist/remediation/parent-upgrade-blockers.js +51 -0
  40. package/dist/remediation/parent-upgrade.js +5 -79
  41. package/dist/remediation/registry-parent-ranges.js +21 -0
  42. package/dist/remediation/transitive-chain-resolver.js +3 -3
  43. package/dist/scan/completeness.js +10 -4
  44. package/dist/scan/multi-folder-scan.js +133 -58
  45. package/dist/scan/single-scan.js +41 -25
  46. package/dist/scanner.js +257 -58
  47. package/dist/usage/scanner.js +19 -8
  48. package/dist/utils/array.js +11 -3
  49. package/dist/utils/debug-bundle.js +118 -0
  50. package/dist/utils/debug-project.js +102 -0
  51. package/dist/utils/debug-redaction.js +117 -0
  52. package/dist/utils/file.js +2 -1
  53. package/dist/utils/fix-runner.js +95 -13
  54. package/dist/utils/import-type-queries.js +322 -0
  55. package/dist/utils/network.js +13 -9
  56. package/dist/utils/npm-lockfile.js +12 -0
  57. package/dist/utils/osv-fetch.js +70 -0
  58. package/dist/utils/package-identity.js +43 -0
  59. package/dist/utils/package-manager-source.js +24 -0
  60. package/dist/utils/purl.js +37 -0
  61. package/dist/utils/registry-config.js +1 -16
  62. package/dist/utils/string.js +8 -0
  63. package/dist/utils/validate-url.js +1 -1
  64. package/dist/utils/version.js +30 -7
  65. package/dist/utils/versions/osv-range.js +191 -0
  66. package/dist/utils/versions/pep440.js +246 -0
  67. package/dist/utils/versions/scheme.js +10 -0
  68. package/package.json +3 -2
@@ -1,9 +1,12 @@
1
1
  import process from "node:process";
2
- import { syncOsvAdvisories } from "../advisory/osv-sync.js";
2
+ import fs from "node:fs";
3
+ import { AdvisorySyncError, getDefaultAdvisoryDbPath, syncOsvAdvisories } from "../advisory/osv-sync.js";
4
+ import { logWarn } from "../output/formatters.js";
3
5
  import { createSpinner } from "../output/spinner.js";
4
6
  import { chalk } from "../utils/chalk.js";
5
- import { pluralize } from "../utils/string.js";
7
+ import { ensureSentence, pluralize } from "../utils/string.js";
6
8
  export async function runAdvisoriesSync({ options, fetchImpl }) {
9
+ const databaseExisted = fs.existsSync(getDefaultAdvisoryDbPath(options.output));
7
10
  const spinner = createSpinner("Preparing advisory sync...", options);
8
11
  const usePlainProgressLogs = !process.stdout.isTTY || !!options.json;
9
12
  const result = await syncOsvAdvisories({
@@ -19,7 +22,18 @@ export async function runAdvisoriesSync({ options, fetchImpl }) {
19
22
  }
20
23
  spinner.update(event.message);
21
24
  },
25
+ }).catch((error) => {
26
+ spinner.stop();
27
+ if (error instanceof AdvisorySyncError && error.databaseState === "unchanged") {
28
+ const stateMessage = databaseExisted
29
+ ? "The existing advisory database was not changed."
30
+ : "No advisory database was created.";
31
+ throw new Error(`${ensureSentence(error.message)} ${stateMessage}`, { cause: error });
32
+ }
33
+ throw error;
22
34
  });
35
+ for (const warning of result.warnings ?? [])
36
+ logWarn(warning, { json: options.json });
23
37
  if (usePlainProgressLogs) {
24
38
  console.log(`Advisory sync complete (${result.advisoryCount} records)`);
25
39
  }
package/dist/cli/args.js CHANGED
@@ -10,9 +10,27 @@ export const SBOM_FORMAT_ALIASES = {
10
10
  spdx: "spdx",
11
11
  "spdx2.3": "spdx",
12
12
  };
13
+ /** Severities `--fail-on` accepts, matched case-insensitively. */
14
+ export const FAIL_ON_SEVERITIES = ["critical", "high", "medium", "low"];
15
+ function parseFailOn(value) {
16
+ const valid = FAIL_ON_SEVERITIES.join(", ");
17
+ if (value === undefined || value === "" || value.startsWith("-")) {
18
+ throw new Error(`--fail-on requires a severity. Valid severities: ${valid}.`);
19
+ }
20
+ if (!FAIL_ON_SEVERITIES.includes(value.toLowerCase())) {
21
+ throw new Error(`Unknown --fail-on severity "${value}". Valid severities: ${valid}.`);
22
+ }
23
+ return value;
24
+ }
25
+ function requireFlagValue(flag, value, noun) {
26
+ if (value === undefined || value === "" || value.startsWith("-")) {
27
+ throw new Error(`${flag} requires a ${noun} argument`);
28
+ }
29
+ return value;
30
+ }
13
31
  function parseSbomFormat(value) {
14
32
  const valid = Object.keys(SBOM_FORMAT_ALIASES).join(", ");
15
- if (value === undefined || value.startsWith("-")) {
33
+ if (value === undefined || value === "" || value.startsWith("-")) {
16
34
  throw new Error(`--sbom requires a format. Valid formats: ${valid}.`);
17
35
  }
18
36
  const format = SBOM_FORMAT_ALIASES[value.toLowerCase()];
@@ -124,13 +142,10 @@ export function parseArgs(argv) {
124
142
  }
125
143
  if (sub === ConfigAction.Set) {
126
144
  const key = argv[2];
127
- const value = argv[3];
128
145
  if (key !== ConfigKey.CaCert) {
129
146
  throw new Error(`Unknown config key: ${key ?? "(none)"}. Valid keys: ${ConfigKey.CaCert}`);
130
147
  }
131
- if (!value) {
132
- throw new Error(`cve-lite config set ${ConfigKey.CaCert} requires a path argument`);
133
- }
148
+ const value = requireFlagValue(`cve-lite config set ${ConfigKey.CaCert}`, argv[3], "path");
134
149
  return { command: "config", options, configSubcommand: { action: ConfigAction.Set, key: ConfigKey.CaCert, value } };
135
150
  }
136
151
  if (sub === ConfigAction.Unset) {
@@ -167,27 +182,27 @@ export function parseArgs(argv) {
167
182
  continue;
168
183
  }
169
184
  if (arg === FLAG_AUDIT_LOG) {
170
- options.auditLog = argv[++i];
185
+ options.auditLog = requireFlagValue(FLAG_AUDIT_LOG, argv[++i], "path");
171
186
  continue;
172
187
  }
173
188
  if (arg.startsWith(`${FLAG_AUDIT_LOG}=`)) {
174
- options.auditLog = arg.slice(FLAG_AUDIT_LOG.length + 1);
189
+ options.auditLog = requireFlagValue(FLAG_AUDIT_LOG, arg.slice(FLAG_AUDIT_LOG.length + 1), "path");
175
190
  continue;
176
191
  }
177
192
  if (arg === FLAG_RULE) {
178
- options.rule = argv[++i];
193
+ options.rule = requireFlagValue(FLAG_RULE, argv[++i], "rule id");
179
194
  continue;
180
195
  }
181
196
  if (arg.startsWith(`${FLAG_RULE}=`)) {
182
- options.rule = arg.slice(FLAG_RULE.length + 1);
197
+ options.rule = requireFlagValue(FLAG_RULE, arg.slice(FLAG_RULE.length + 1), "rule id");
183
198
  continue;
184
199
  }
185
200
  if (arg === FLAG_FAIL_ON) {
186
- options.failOn = argv[++i] ?? options.failOn;
201
+ options.failOn = parseFailOn(argv[++i]);
187
202
  continue;
188
203
  }
189
204
  if (arg.startsWith(`${FLAG_FAIL_ON}=`)) {
190
- options.failOn = arg.slice(FLAG_FAIL_ON.length + 1);
205
+ options.failOn = parseFailOn(arg.slice(FLAG_FAIL_ON.length + 1));
191
206
  continue;
192
207
  }
193
208
  if (arg.startsWith("-")) {
@@ -261,11 +276,11 @@ export function parseArgs(argv) {
261
276
  continue;
262
277
  }
263
278
  if (arg === FLAG_OFFLINE_DB) {
264
- options.offlineDb = argv[++i];
279
+ options.offlineDb = requireFlagValue(FLAG_OFFLINE_DB, argv[++i], "path");
265
280
  continue;
266
281
  }
267
282
  if (arg.startsWith(`${FLAG_OFFLINE_DB}=`)) {
268
- options.offlineDb = arg.slice(FLAG_OFFLINE_DB.length + 1);
283
+ options.offlineDb = requireFlagValue(FLAG_OFFLINE_DB, arg.slice(FLAG_OFFLINE_DB.length + 1), "path");
269
284
  continue;
270
285
  }
271
286
  if (arg === FLAG_ALL) {
@@ -273,35 +288,35 @@ export function parseArgs(argv) {
273
288
  continue;
274
289
  }
275
290
  if (arg === FLAG_FAIL_ON) {
276
- options.failOn = argv[++i] ?? options.failOn;
291
+ options.failOn = parseFailOn(argv[++i]);
277
292
  continue;
278
293
  }
279
294
  if (arg.startsWith(`${FLAG_FAIL_ON}=`)) {
280
- options.failOn = arg.slice(FLAG_FAIL_ON.length + 1);
295
+ options.failOn = parseFailOn(arg.slice(FLAG_FAIL_ON.length + 1));
281
296
  continue;
282
297
  }
283
298
  if (arg === FLAG_BATCH_SIZE) {
284
- options.batchSize = argv[++i] ?? options.batchSize;
299
+ options.batchSize = requireFlagValue(FLAG_BATCH_SIZE, argv[++i], "number");
285
300
  continue;
286
301
  }
287
302
  if (arg.startsWith(`${FLAG_BATCH_SIZE}=`)) {
288
- options.batchSize = arg.slice(FLAG_BATCH_SIZE.length + 1);
303
+ options.batchSize = requireFlagValue(FLAG_BATCH_SIZE, arg.slice(FLAG_BATCH_SIZE.length + 1), "number");
289
304
  continue;
290
305
  }
291
306
  if (arg === FLAG_CACHE_DIR) {
292
- options.cacheDir = argv[++i];
307
+ options.cacheDir = requireFlagValue(FLAG_CACHE_DIR, argv[++i], "path");
293
308
  continue;
294
309
  }
295
310
  if (arg.startsWith(`${FLAG_CACHE_DIR}=`)) {
296
- options.cacheDir = arg.slice(FLAG_CACHE_DIR.length + 1);
311
+ options.cacheDir = requireFlagValue(FLAG_CACHE_DIR, arg.slice(FLAG_CACHE_DIR.length + 1), "path");
297
312
  continue;
298
313
  }
299
314
  if (arg === FLAG_OSV_URL) {
300
- options.osvUrl = argv[++i];
315
+ options.osvUrl = requireFlagValue(FLAG_OSV_URL, argv[++i], "url");
301
316
  continue;
302
317
  }
303
318
  if (arg.startsWith(`${FLAG_OSV_URL}=`)) {
304
- options.osvUrl = arg.slice(FLAG_OSV_URL.length + 1);
319
+ options.osvUrl = requireFlagValue(FLAG_OSV_URL, arg.slice(FLAG_OSV_URL.length + 1), "url");
305
320
  continue;
306
321
  }
307
322
  if (arg === FLAG_ALLOW_PRIVATE_OSV_URL) {
@@ -310,7 +325,7 @@ export function parseArgs(argv) {
310
325
  }
311
326
  if (arg === FLAG_OUTPUT) {
312
327
  const val = argv[++i];
313
- if (!val || val.startsWith("-")) {
328
+ if (!val || (val !== "-" && val.startsWith("-"))) {
314
329
  throw new Error("--output requires a directory argument");
315
330
  }
316
331
  options.output = val;
@@ -318,26 +333,26 @@ export function parseArgs(argv) {
318
333
  }
319
334
  if (arg.startsWith(`${FLAG_OUTPUT}=`)) {
320
335
  const val = arg.slice(FLAG_OUTPUT.length + 1);
321
- if (!val || val.startsWith("-")) {
336
+ if (!val || (val !== "-" && val.startsWith("-"))) {
322
337
  throw new Error("--output requires a directory argument");
323
338
  }
324
339
  options.output = val;
325
340
  continue;
326
341
  }
327
342
  if (arg === FLAG_SEARCH_DEPTH) {
328
- options.searchDepth = argv[++i] ?? options.searchDepth;
343
+ options.searchDepth = requireFlagValue(FLAG_SEARCH_DEPTH, argv[++i], "number");
329
344
  continue;
330
345
  }
331
346
  if (arg.startsWith(`${FLAG_SEARCH_DEPTH}=`)) {
332
- options.searchDepth = arg.slice(FLAG_SEARCH_DEPTH.length + 1);
347
+ options.searchDepth = requireFlagValue(FLAG_SEARCH_DEPTH, arg.slice(FLAG_SEARCH_DEPTH.length + 1), "number");
333
348
  continue;
334
349
  }
335
350
  if (arg === FLAG_MIN_SEVERITY) {
336
- options.minSeverity = argv[++i] ?? options.minSeverity;
351
+ options.minSeverity = requireFlagValue(FLAG_MIN_SEVERITY, argv[++i], "level");
337
352
  continue;
338
353
  }
339
354
  if (arg.startsWith(`${FLAG_MIN_SEVERITY}=`)) {
340
- options.minSeverity = arg.slice(FLAG_MIN_SEVERITY.length + 1);
355
+ options.minSeverity = requireFlagValue(FLAG_MIN_SEVERITY, arg.slice(FLAG_MIN_SEVERITY.length + 1), "level");
341
356
  continue;
342
357
  }
343
358
  if (arg === FLAG_USAGE || arg === FLAG_USAGE_HINTS) {
@@ -373,15 +388,11 @@ export function parseArgs(argv) {
373
388
  continue;
374
389
  }
375
390
  if (arg === FLAG_CA_CERT) {
376
- const val = argv[++i];
377
- if (!val) {
378
- throw new Error("--ca-cert requires a path argument");
379
- }
380
- options.caCert = val;
391
+ options.caCert = requireFlagValue(FLAG_CA_CERT, argv[++i], "path");
381
392
  continue;
382
393
  }
383
394
  if (arg.startsWith(`${FLAG_CA_CERT}=`)) {
384
- options.caCert = arg.slice(FLAG_CA_CERT.length + 1);
395
+ options.caCert = requireFlagValue(FLAG_CA_CERT, arg.slice(FLAG_CA_CERT.length + 1), "path");
385
396
  continue;
386
397
  }
387
398
  if (arg === FLAG_SARIF) {
@@ -407,11 +418,11 @@ export function parseArgs(argv) {
407
418
  continue;
408
419
  }
409
420
  if (arg === FLAG_AUDIT_LOG) {
410
- options.auditLog = argv[++i];
421
+ options.auditLog = requireFlagValue(FLAG_AUDIT_LOG, argv[++i], "path");
411
422
  continue;
412
423
  }
413
424
  if (arg.startsWith(`${FLAG_AUDIT_LOG}=`)) {
414
- options.auditLog = arg.slice(FLAG_AUDIT_LOG.length + 1);
425
+ options.auditLog = requireFlagValue(FLAG_AUDIT_LOG, arg.slice(FLAG_AUDIT_LOG.length + 1), "path");
415
426
  continue;
416
427
  }
417
428
  if (arg === FLAG_CHECK_OVERRIDES) {
@@ -4,6 +4,7 @@ import path from "node:path";
4
4
  import process from "node:process";
5
5
  import { chalk } from "../utils/chalk.js";
6
6
  import { createCertAwareFetch } from "../utils/network.js";
7
+ import { createOsvFetch } from "../utils/osv-fetch.js";
7
8
  export const ConfigAction = {
8
9
  Set: "set",
9
10
  Unset: "unset",
@@ -91,5 +92,7 @@ export function setupCaCert(options, debugLog) {
91
92
  nodeExtraCaCerts: process.env.NODE_EXTRA_CA_CERTS ?? null,
92
93
  });
93
94
  }
94
- return certFetch;
95
+ return options.osvUrl
96
+ ? createOsvFetch(options.osvUrl, !!options.allowPrivateOsvUrl, resolvedCaCert)
97
+ : certFetch;
95
98
  }
package/dist/cli/help.js CHANGED
@@ -2,6 +2,7 @@ import { chalk } from "../utils/chalk.js";
2
2
  import { getCliVersion } from "../utils/version-info.js";
3
3
  import { checkForUpdate } from "../utils/update-check.js";
4
4
  import { OVERRIDES_COMMAND } from "../constants.js";
5
+ import { isOutputStdout } from "../output/output-dir.js";
5
6
  const CLI_VERSION = getCliVersion();
6
7
  const CLI_BANNER = [
7
8
  `${chalk.green(">_")} ${chalk.bold.whiteBright(`CVE Lite CLI (${CLI_VERSION})`)}`,
@@ -13,7 +14,7 @@ const CLI_BANNER = [
13
14
  chalk.gray("Fast. Local. Developer-first.")
14
15
  ].join("\n");
15
16
  export function printBanner(options) {
16
- if (options?.json)
17
+ if (options?.json || isOutputStdout(options?.output))
17
18
  return;
18
19
  console.log(CLI_BANNER);
19
20
  console.log("");
@@ -37,7 +38,7 @@ export function printHelp() {
37
38
  " --sbom <format> Write an SBOM: cyclonedx (1.6) or spdx (2.3), to a timestamped file",
38
39
  " --sbom-inventory-only Omit the vulnerability overlay from --sbom, leaving a pure inventory",
39
40
  " --cdx Alias for --sbom cyclonedx",
40
- " --output <dir> Directory for --json, --sarif and --sbom files (default: current directory)",
41
+ " --output <path> Directory or file path for --json, --sarif and --sbom files (use '-' for stdout; default: current directory)",
41
42
  " --no-open Don't auto-open the report in the browser",
42
43
  " --fix Apply validated direct dependency fixes and rescan",
43
44
  " --ratchet Save current findings as baseline or, if baseline exists, only fail on new findings",
@@ -47,7 +48,7 @@ export function printHelp() {
47
48
  " --osv-url <url> Use a custom OSV-compatible advisory endpoint (HTTPS only)",
48
49
  " --allow-private-osv-url Allow --osv-url to resolve to private/reserved IPs",
49
50
  " --ca-cert <path> Path to a CA certificate file for corporate SSL proxies",
50
- " --debug Write verbose runtime/network diagnostics to a timestamped log file",
51
+ " --debug Write a redacted diagnostic bundle to attach to bug reports",
51
52
  " --verbose Show detailed output with fix plan, paths, and full table",
52
53
  " --prod-only Exclude dev dependencies where available",
53
54
  " --check-overrides Also audit package.json overrides (OA001-OA011, PD001-PD002); findings",
@@ -1,7 +1,8 @@
1
1
  import { validateCaCertFile } from "./config.js";
2
- import { FLAG_CDX, FLAG_CHECK_NETWORK, FLAG_CHECK_OVERRIDES, FLAG_CREATE_PR, FLAG_FIX, FLAG_JSON, FLAG_NO_CACHE, FLAG_OFFLINE, FLAG_OFFLINE_DB, FLAG_OSV_URL, FLAG_REPORT, FLAG_SARIF, FLAG_SBOM, } from "./flags.js";
2
+ import { FLAG_BATCH_SIZE, FLAG_CDX, FLAG_CHECK_NETWORK, FLAG_CHECK_OVERRIDES, FLAG_CREATE_PR, FLAG_FIX, FLAG_JSON, FLAG_NO_CACHE, FLAG_OFFLINE, FLAG_OFFLINE_DB, FLAG_OSV_URL, FLAG_REPORT, FLAG_SARIF, FLAG_SBOM, } from "./flags.js";
3
3
  import { validateOsvUrl } from "../utils/validate-url.js";
4
4
  import { resolveSbomFormat } from "../utils/sbom-format.js";
5
+ import { isOutputFile, isOutputStdout } from "../output/output-dir.js";
5
6
  function conflictMessage(flag, withFlag) {
6
7
  return `${flag} cannot be used with ${withFlag}.`;
7
8
  }
@@ -11,6 +12,13 @@ function requiresMessage(flag, requiredFlag) {
11
12
  return `${flag} requires ${requiredFlag}.`;
12
13
  }
13
14
  export async function validateOptions(options) {
15
+ // chunk() steps its index by this size. 0 stays put and a negative size walks backward, so either loops until OOM.
16
+ // Missing or empty keeps the default. Anything else must be digits only and at least 1.
17
+ if (options.batchSize !== undefined && options.batchSize !== "") {
18
+ if (!/^[0-9]+$/.test(options.batchSize) || Number(options.batchSize) < 1) {
19
+ throw new Error(`${FLAG_BATCH_SIZE} must be a positive integer`);
20
+ }
21
+ }
14
22
  if (options.allowPrivateOsvUrl && !options.osvUrl) {
15
23
  throw new Error(`${requiresMessage("--allow-private-osv-url", "--osv-url")} Provide a custom OSV endpoint with --osv-url, or remove --allow-private-osv-url.`);
16
24
  }
@@ -58,6 +66,20 @@ export async function validateOptions(options) {
58
66
  if (options.output && !(options.json || options.sarif || resolveSbomFormat(options))) {
59
67
  throw new Error("--output requires --json, --sarif or --sbom. Add one of them to write a file into the output directory, or remove --output.");
60
68
  }
69
+ const fileOutputsCount = (options.json ? 1 : 0) +
70
+ (options.sarif ? 1 : 0) +
71
+ (resolveSbomFormat(options) ? 1 : 0);
72
+ if (isOutputStdout(options.output) && options.report) {
73
+ throw new Error("--output cannot be stdout when --report is specified. Remove --report or select a file output target.");
74
+ }
75
+ if (options.output && fileOutputsCount > 1) {
76
+ if (isOutputFile(options.output)) {
77
+ throw new Error("--output cannot be a file path when multiple output formats are specified. Use an output directory instead.");
78
+ }
79
+ if (isOutputStdout(options.output)) {
80
+ throw new Error("--output cannot be stdout when multiple output formats are specified. Specify only one of --json, --sarif or --sbom, or use an output directory.");
81
+ }
82
+ }
61
83
  if (options.checkNetwork && !options.checkOverrides) {
62
84
  throw new Error(`${requiresMessage(FLAG_CHECK_NETWORK, FLAG_CHECK_OVERRIDES)} It lets the network-backed override rules run, so add ${FLAG_CHECK_OVERRIDES}, or remove ${FLAG_CHECK_NETWORK}.`);
63
85
  }
package/dist/constants.js CHANGED
@@ -20,25 +20,16 @@ export const MAL_GIT_SOURCE_COMPACT_MESSAGE = "Git source: verify repository and
20
20
  export const MAL_GIT_SOURCE_LEGEND_MESSAGE = "verify repository and org are trusted";
21
21
  export const MAL_GIT_SOURCE_PINNED_DISPLAY = "⚠ Git source (SHA-pinned)";
22
22
  export const MAL_GIT_SOURCE_FLOATING_DISPLAY = "⚠ Git source (floating ref)";
23
- /**
24
- * Supported lockfiles in precedence order, strongest signal first.
25
- *
26
- * This is the single source of truth for lockfile precedence. Root detection,
27
- * nested discovery and `chooseBestLockfile` all read it, so a repo resolves to
28
- * the same lockfile whether it sits at the root or in a subdirectory.
29
- *
30
- * npm-shrinkwrap.json outranks package-lock.json because npm itself ignores
31
- * package-lock.json when a shrinkwrap is present.
32
- */
23
+ /** npm ignores package-lock.json whenever npm-shrinkwrap.json is present. */
24
+ export const NPM_LOCKFILE_NAMES = ["npm-shrinkwrap.json", "package-lock.json"];
33
25
  /**
34
26
  * Every lockfile the scanner understands. Order here is not precedence: it only
35
27
  * fixes the set and the type. The two precedence lists below are what decide
36
- * which file wins, and they currently disagree with each other.
28
+ * which file wins.
37
29
  */
38
30
  export const LOCKFILE_NAMES = [
39
31
  "bun.lock",
40
- "npm-shrinkwrap.json",
41
- "package-lock.json",
32
+ ...NPM_LOCKFILE_NAMES,
42
33
  "pnpm-lock.yaml",
43
34
  "yarn.lock",
44
35
  ];
@@ -47,30 +38,25 @@ export const LOCKFILE_NAMES = [
47
38
  */
48
39
  export const LOCKFILE_PRIORITY_ROOT = [
49
40
  "bun.lock",
50
- "npm-shrinkwrap.json",
51
- "package-lock.json",
41
+ ...NPM_LOCKFILE_NAMES,
52
42
  "pnpm-lock.yaml",
53
43
  "yarn.lock",
54
44
  ];
55
45
  /**
56
46
  * Precedence when several lockfiles sit in the same directory below the root.
57
47
  *
58
- * This disagrees with the root order on six of the ten pairs: `bun.lock` ranks
59
- * last here and first at the root, and `npm-shrinkwrap.json` ranks last here
60
- * and second at the root. That is a real inconsistency, and the shrinkwrap
61
- * placement is a bug, since npm ignores `package-lock.json` whenever a
62
- * shrinkwrap is present.
48
+ * As at the root, npm-shrinkwrap.json outranks package-lock.json because npm
49
+ * ignores package-lock.json when a shrinkwrap is present.
63
50
  *
64
- * Both are preserved exactly as they were so that this change is behaviour
65
- * neutral. Reconciling them changes which lockfile is scanned on real projects,
66
- * so it belongs in its own change where that can be argued and tested.
51
+ * The shrinkwrap now also outranks bun.lock here, unlike root detection, which
52
+ * prefers Bun. The relative order of package-lock.json, pnpm, Yarn and Bun is
53
+ * retained; reconciling the other cross-manager choices is outside #1494.
67
54
  */
68
55
  export const LOCKFILE_PRIORITY_NESTED = [
69
- "package-lock.json",
56
+ ...NPM_LOCKFILE_NAMES,
70
57
  "pnpm-lock.yaml",
71
58
  "yarn.lock",
72
59
  "bun.lock",
73
- "npm-shrinkwrap.json",
74
60
  ];
75
61
  export const EXCLUDED_DIRS = new Set([
76
62
  ".git",
package/dist/index.js CHANGED
@@ -65,6 +65,7 @@ if (parsedArgs) {
65
65
  const searchDepth = Math.max(0, Number(options.searchDepth || DEFAULT_SEARCH_DEPTH));
66
66
  const debugSession = createDebugLogger(!!options.debug);
67
67
  const debugLog = debugSession.log;
68
+ let scanJsonPath;
68
69
  const scanStartedAt = Date.now();
69
70
  const auditLogHandle = createAuditLog(options.auditLog ?? process.env.CVE_LITE_AUDIT_LOG);
70
71
  async function main() {
@@ -133,7 +134,10 @@ if (parsedArgs) {
133
134
  options,
134
135
  fetchImpl: certFetch,
135
136
  auditLog: auditLogHandle,
137
+ debugLog,
138
+ onScanJsonPath: (jsonPath) => { scanJsonPath = jsonPath; },
136
139
  });
140
+ debugSession.finalize(projectPath, options, scanJsonPath);
137
141
  auditLogHandle.close();
138
142
  process.exit(exitCode);
139
143
  return;
@@ -149,7 +153,9 @@ if (parsedArgs) {
149
153
  auditLog: auditLogHandle,
150
154
  scanStartedAt,
151
155
  cliVersion,
156
+ onScanJsonPath: (jsonPath) => { scanJsonPath = jsonPath; },
152
157
  });
158
+ debugSession.finalize(projectPath, options, scanJsonPath);
153
159
  auditLogHandle.close();
154
160
  process.exit(exitCode);
155
161
  return;
@@ -157,9 +163,7 @@ if (parsedArgs) {
157
163
  main().catch((error) => {
158
164
  const errorMessage = error instanceof Error ? error.message : String(error);
159
165
  console.error(chalk.red(`Error: ${errorMessage}`));
160
- if (options.debug && error instanceof Error && error.stack) {
161
- debugLog("Unhandled error", { message: error.message, stack: error.stack });
162
- }
166
+ debugLog("Unhandled error", { message: errorMessage, stack: error instanceof Error ? error.stack : undefined });
163
167
  // Emit error event to audit-log
164
168
  auditLogHandle.emit({
165
169
  ts: new Date().toISOString(),
@@ -169,6 +173,7 @@ if (parsedArgs) {
169
173
  message: errorMessage,
170
174
  stack: error instanceof Error ? error.stack : undefined,
171
175
  });
176
+ debugSession.finalize(projectPath, options, scanJsonPath);
172
177
  auditLogHandle.close();
173
178
  formatHintLines(getNetworkErrorHint(error, errorMessage)).forEach((line) => console.error(line));
174
179
  process.exit(1);
@@ -2,35 +2,44 @@ import { randomUUID } from "node:crypto";
2
2
  import { findFixTargetForFinding, findSuggestedCommandForFinding } from "../remediation/fix-commands.js";
3
3
  import { getRecommendedAction } from "./formatters.js";
4
4
  import { getCliVersion } from "../utils/version-info.js";
5
- import { buildPurl } from "../utils/purl.js";
5
+ import { buildPurl, purlForSbom, sbomComponentRef } from "../utils/purl.js";
6
+ import { registryPackageName } from "../utils/package-identity.js";
6
7
  import { sbomTimestamp, writeSbomFile } from "./sbom-file.js";
7
8
  export { buildPurl };
8
9
  export function buildCycloneDxBom(allPackages, findings, projectMeta, version, plan = null) {
9
- const components = allPackages.map(pkg => {
10
- const purl = buildPurl(pkg.name, pkg.version);
11
- return {
10
+ const components = [];
11
+ for (const pkg of allPackages) {
12
+ const purl = purlForSbom(pkg);
13
+ if (!purl)
14
+ continue;
15
+ components.push({
12
16
  type: "library",
13
- "bom-ref": purl,
14
- name: pkg.name,
17
+ "bom-ref": sbomComponentRef(pkg, purl),
18
+ name: registryPackageName(pkg),
15
19
  version: pkg.version,
16
20
  purl,
17
- };
18
- });
21
+ ...(pkg.dev !== undefined
22
+ ? { scope: pkg.dev ? "excluded" : "required" }
23
+ : {}),
24
+ });
25
+ }
19
26
  // Deduplicate vulnerabilities by CVE ID - one entry per CVE with multiple affects
20
27
  const vulnMap = new Map();
21
28
  for (const finding of findings) {
22
29
  const cveIds = finding.cveAliases.length > 0
23
30
  ? finding.cveAliases
24
31
  : finding.vulnerabilities.map(v => v.id);
25
- const purl = buildPurl(finding.pkg.name, finding.pkg.version);
32
+ const purl = purlForSbom(finding.pkg);
33
+ if (!purl)
34
+ continue;
26
35
  for (const cveId of cveIds) {
27
36
  const existing = vulnMap.get(cveId);
28
37
  if (existing) {
29
- existing.affects.push({ ref: purl });
38
+ existing.affects.push({ ref: sbomComponentRef(finding.pkg, purl) });
30
39
  }
31
40
  else {
32
41
  // severity from first finding wins when the same CVE affects multiple packages
33
- vulnMap.set(cveId, { finding, affects: [{ ref: purl }] });
42
+ vulnMap.set(cveId, { finding, affects: [{ ref: sbomComponentRef(finding.pkg, purl) }] });
34
43
  }
35
44
  }
36
45
  }
@@ -97,8 +106,8 @@ export function buildCycloneDxBom(allPackages, findings, projectMeta, version, p
97
106
  vulnerabilities,
98
107
  };
99
108
  }
100
- export function writeCycloneDxReport(allPackages, findings, plan, projectMeta, outputDir) {
101
- const filename = `cve-lite-scan-${sbomTimestamp()}.cdx.json`;
109
+ export function writeCycloneDxReport(allPackages, findings, plan, projectMeta, outputDir, filename) {
110
+ const finalFilename = filename ?? `cve-lite-scan-${sbomTimestamp()}.cdx.json`;
102
111
  const bom = buildCycloneDxBom(allPackages, findings, projectMeta, getCliVersion(), plan);
103
- return writeSbomFile(filename, bom, "CycloneDX report", outputDir);
112
+ return writeSbomFile(finalFilename, bom, "CycloneDX report", outputDir);
104
113
  }
@@ -1,31 +1,46 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
+ import { createDebugBundle } from "../utils/debug-bundle.js";
3
4
  export function createDebugLogger(enabled) {
4
- if (!enabled) {
5
- return {
6
- log: () => { },
7
- announcePath: () => { },
8
- close: () => { },
9
- };
10
- }
5
+ if (!enabled)
6
+ return { log: () => { }, announcePath: () => { }, close: () => { }, finalize: () => null };
11
7
  const ts = new Date().toISOString().replace(/[:.]/g, "-").slice(0, 19);
12
8
  const filename = `cve-lite-debug-${ts}.log`;
13
9
  const outputPath = path.join(process.cwd(), filename);
14
- let announced = false;
10
+ const events = [];
11
+ let logWriteFailed = false;
12
+ let finalized = false;
13
+ let bundlePath = null;
15
14
  const log = (message, details) => {
16
15
  const time = new Date().toISOString();
17
- const payload = details === undefined
18
- ? ""
19
- : ` ${formatJson(details)}`;
20
- fs.appendFileSync(outputPath, `${time} [debug] ${message}${payload}\n`, "utf8");
21
- };
22
- const announcePath = () => {
23
- if (announced)
16
+ events.push({ timestamp: time, message, details });
17
+ // Retained locally for compatibility, not advertised as safe to attach.
18
+ if (logWriteFailed)
24
19
  return;
25
- announced = true;
26
- console.error(`[debug] Writing debug log to ./${filename}`);
20
+ try {
21
+ const payload = details === undefined ? "" : ` ${formatJson(details)}`;
22
+ fs.appendFileSync(outputPath, `${time} [debug] ${message}${payload}\n`, "utf8");
23
+ }
24
+ catch (error) {
25
+ logWriteFailed = true;
26
+ warnWriteFailure("the local debug log", filename, error, "continuing the scan.");
27
+ }
28
+ };
29
+ const finalize = (projectPath, options, scanJsonPath) => {
30
+ if (finalized)
31
+ return bundlePath;
32
+ finalized = true;
33
+ try {
34
+ bundlePath = createDebugBundle(events, options, projectPath, scanJsonPath);
35
+ const display = path.relative(process.cwd(), bundlePath) || bundlePath;
36
+ console.error(`[debug] Debug bundle written to ./${display} - attach this when reporting a problem.`);
37
+ }
38
+ catch (error) {
39
+ warnWriteFailure("the debug bundle", writeFailureName(error), error, "the scan result is unchanged.");
40
+ }
41
+ return bundlePath;
27
42
  };
28
- return { log, announcePath, close: () => { } };
43
+ return { log, announcePath: () => { }, close: () => { }, finalize };
29
44
  }
30
45
  function formatJson(details) {
31
46
  if (typeof details === "string")
@@ -37,3 +52,38 @@ function formatJson(details) {
37
52
  return String(details);
38
53
  }
39
54
  }
55
+ /** Shared by the legacy log and the bundle: name the file, then say why. */
56
+ function warnWriteFailure(subject, filename, error, followUp) {
57
+ const reason = failureReason(error) || "unknown error";
58
+ console.error(`[debug] Could not write ${subject} to ./${filename}: ${reason}; ${followUp}`);
59
+ }
60
+ function failureReason(error) {
61
+ // Read message and code off the object. `instanceof Error` is false for
62
+ // Node filesystem errors once this module is loaded in a different realm.
63
+ const record = error !== null && typeof error === "object" ? error : undefined;
64
+ const raw = typeof record?.message === "string" ? record.message : String(error);
65
+ const code = typeof record?.code === "string" ? record.code : "";
66
+ // Node ends filesystem errors with the absolute path. The relative name is
67
+ // already in the warning, and that path can itself contain a secret.
68
+ const detail = (code && raw.startsWith(`${code}:`) ? raw.slice(code.length + 1) : raw)
69
+ .replace(/,\s*[A-Za-z]+\s+'(?:\\'|[^'])*'$/, "")
70
+ .replace(/'(?:\\'|[^'])*'/g, "")
71
+ .replace(/(?:[A-Za-z]:[\\/]|\/)[^\s'"]+/g, "")
72
+ .replace(/[ \t]{2,}/g, " ")
73
+ .trim();
74
+ return code && raw.startsWith(`${code}:`) ? (detail ? `${code}: ${detail}` : code) : detail;
75
+ }
76
+ function writeFailureName(error) {
77
+ if (!error || typeof error !== "object")
78
+ return "cve-lite-debug";
79
+ const record = error;
80
+ const target = typeof record.path === "string" && record.path
81
+ ? record.path
82
+ : typeof record.writeTarget === "string" ? record.writeTarget : "";
83
+ if (!target)
84
+ return "cve-lite-debug";
85
+ const relative = path.relative(process.cwd(), target);
86
+ if (relative && !relative.startsWith("..") && !path.isAbsolute(relative))
87
+ return relative;
88
+ return path.basename(target);
89
+ }