cve-lite-cli 1.36.1 → 1.37.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.
package/README.md CHANGED
@@ -40,7 +40,8 @@
40
40
  <br/>
41
41
 
42
42
  <p>
43
- 🏆 <strong>Ranked #5</strong> in <a href="https://www.helpnetsecurity.com/2026/07/08/20-latest-open-source-cybersecurity-tools/">Help Net Security's 20 open-source security tools</a> &nbsp;·&nbsp;
43
+ 🏆 <strong>Featured on <a href="https://www.youtube.com/watch?v=_Mmf3DLVuOQ">GitHub Open Source Friday</a></strong> &nbsp;·&nbsp;
44
+ <strong>Ranked #5</strong> in <a href="https://www.helpnetsecurity.com/2026/07/08/20-latest-open-source-cybersecurity-tools/">Help Net Security's 20 open-source security tools</a> &nbsp;·&nbsp;
44
45
  <strong><a href="https://www.bestpractices.dev/projects/12731">OpenSSF Best Practices</a></strong>
45
46
  </p>
46
47
 
@@ -129,6 +130,7 @@ cve-lite /path/to/project --fail-on high # exit non-zero on high severity and
129
130
  cve-lite /path/to/project --json # JSON output
130
131
  cve-lite /path/to/project --sarif # SARIF output for GitHub Code Scanning
131
132
  cve-lite /path/to/project --sbom spdx # SPDX 2.3 SBOM (also: --sbom cyclonedx)
133
+ cve-lite /path/to/project --sarif --output reports # write output files into ./reports
132
134
  cve-lite /path/to/project --report # interactive HTML dashboard
133
135
  cve-lite /path/to/project --check-overrides # audit override hygiene alongside the CVE scan
134
136
  cve-lite /path/to/project --check-maintenance # flag CVE-blocking version drag and npm-deprecated direct deps
@@ -142,7 +144,7 @@ For the full flag reference and exit codes see the [CLI Reference guide](https:/
142
144
 
143
145
  ## Override hygiene (`overrides`)
144
146
 
145
- `overrides` and `resolutions` are powerful, but they rot. CVE Lite CLI audits them across npm, pnpm, yarn, and bun, catching eleven classes of problem:
147
+ `overrides` and `resolutions` are powerful, but they rot. CVE Lite CLI audits them across npm, pnpm, yarn, and bun, catching twelve classes of problem:
146
148
 
147
149
  | Rule | What it catches |
148
150
  |---|---|
@@ -155,6 +157,7 @@ For the full flag reference and exit codes see the [CLI Reference guide](https:/
155
157
  | `OA007` | Frozen latest: registry has drifted past the pinned version (needs `--check-network`) |
156
158
  | `OA008` | Materialized vulnerable copy still on disk despite the override |
157
159
  | `OA009` | Stale floor: override range floor already met by all parent declarations |
160
+ | `OA010` | Vulnerable floor: override range admits a known-vulnerable version (needs `--check-network`) |
158
161
  | `PD001` | Override-only phantom: package imported in source but only present via an override pin |
159
162
  | `PD002` | Transitive-only phantom: package imported in source but only present as a transitive dependency |
160
163
 
@@ -386,7 +389,7 @@ Notable adopters include:
386
389
 
387
390
  ## Dependency footprint
388
391
 
389
- **Runtime:** `yaml` · `yarn-lockfile` · `better-sqlite3` · `fflate`
392
+ **Runtime:** `yaml` · `yarn-lockfile` · `better-sqlite3` · `fflate` · `semver`
390
393
 
391
394
  **Dev only:** `@types/node` · `tsx` · `typescript`
392
395
 
@@ -1,7 +1,7 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
3
  import Database from "better-sqlite3";
4
- import { compareVersions, isPreReleaseVersion, looksLikeVersion } from "../utils/version.js";
4
+ import { compareVersions, isPreReleaseVersion, looksLikeVersion, normalizeAdvisoryVersion } from "../utils/version.js";
5
5
  const SCHEMA_SQL = `
6
6
  CREATE TABLE IF NOT EXISTS advisories (
7
7
  id TEXT PRIMARY KEY,
@@ -206,10 +206,20 @@ function versionAtOrAboveIntroduced(version, introduced) {
206
206
  return true;
207
207
  return isPreReleaseVersion(version) && releaseCore(version) === introduced;
208
208
  }
209
+ /** OSV range types whose boundaries are versions we can order. GIT uses commit hashes. */
210
+ const COMPARABLE_RANGE_TYPES = new Set(["ECOSYSTEM", "SEMVER"]);
209
211
  function versionMatchesRange(version, row) {
210
212
  const introduced = row.introduced;
211
- const fixed = row.fixed;
212
- const lastAffected = row.last_affected;
213
+ // Defence in depth behind the range-type filter, which stops these rows being
214
+ // written in the first place. A database built by an earlier version still
215
+ // holds them, and a bound that is not a version must never decide the answer
216
+ // by silently failing to exclude (#1191).
217
+ const fixed = normalizeAdvisoryVersion(row.fixed);
218
+ const lastAffected = normalizeAdvisoryVersion(row.last_affected);
219
+ if (row.fixed && !fixed)
220
+ return false;
221
+ if (row.last_affected && !lastAffected)
222
+ return false;
213
223
  if (introduced && introduced !== "0" && !versionAtOrAboveIntroduced(version, introduced)) {
214
224
  return false;
215
225
  }
@@ -230,6 +240,15 @@ function deriveAdvisoryPackageRows(vuln) {
230
240
  continue;
231
241
  }
232
242
  for (const range of affected.ranges ?? []) {
243
+ // A GIT range expresses its boundaries as commit hashes, which are not
244
+ // versions and cannot be ordered against one. Storing them anyway left
245
+ // `versionMatchesRange` comparing a version to a hash, where
246
+ // `compareVersions` returns an ordering rather than rejecting the input,
247
+ // so the range failed to exclude and a patched version was reported as
248
+ // vulnerable (#1191). Keep only the range types whose boundaries are
249
+ // versions.
250
+ if (range.type && !COMPARABLE_RANGE_TYPES.has(range.type))
251
+ continue;
233
252
  const events = range.events ?? [];
234
253
  let introduced = null;
235
254
  for (const event of events) {
@@ -1,3 +1,17 @@
1
1
  // Project-wide audit-log event vocabulary. NDJSON stream: one event per line.
2
2
  // All events share { ts, type, schemaVersion }.
3
3
  export const AUDIT_LOG_SCHEMA_VERSION = 1;
4
+ /** Fields for a cve.fix.applied audit event from a suggested-fix target. */
5
+ export function buildCveFixAppliedEvent(params) {
6
+ return {
7
+ ts: params.ts,
8
+ type: "cve.fix.applied",
9
+ schemaVersion: AUDIT_LOG_SCHEMA_VERSION,
10
+ package: params.package,
11
+ fromVersion: params.fromVersion,
12
+ toVersion: params.toVersion,
13
+ mechanism: params.mechanism,
14
+ ...(params.childPackage ? { childPackage: params.childPackage } : {}),
15
+ ...(params.childTargetVersion ? { childTargetVersion: params.childTargetVersion } : {}),
16
+ };
17
+ }
package/dist/cli/args.js CHANGED
@@ -301,11 +301,17 @@ export function parseArgs(argv) {
301
301
  continue;
302
302
  }
303
303
  if (arg === "--output") {
304
- options.output = argv[++i];
304
+ const val = argv[++i];
305
+ if (!val || val.startsWith("-"))
306
+ throw new Error("--output requires a directory argument");
307
+ options.output = val;
305
308
  continue;
306
309
  }
307
310
  if (arg.startsWith("--output=")) {
308
- options.output = arg.slice("--output=".length);
311
+ const val = arg.slice("--output=".length);
312
+ if (!val || val.startsWith("-"))
313
+ throw new Error("--output requires a directory argument");
314
+ options.output = val;
309
315
  continue;
310
316
  }
311
317
  if (arg === "--search-depth") {
package/dist/cli/help.js CHANGED
@@ -37,6 +37,7 @@ export function printHelp() {
37
37
  " --sbom <format> Write an SBOM: cyclonedx (1.6) or spdx (2.3), to a timestamped file",
38
38
  " --sbom-inventory-only Omit the vulnerability overlay from --sbom, leaving a pure inventory",
39
39
  " --cdx Alias for --sbom cyclonedx",
40
+ " --output <dir> Directory for --json, --sarif and --sbom files (default: current directory)",
40
41
  " --no-open Don't auto-open the report in the browser",
41
42
  " --fix Apply validated direct dependency fixes and rescan",
42
43
  " --ratchet Save current findings as baseline or, if baseline exists, only fail on new findings",
@@ -87,6 +88,7 @@ export function printHelp() {
87
88
  " cve-lite . --fail-on high Exit 1 if any high or critical findings are found",
88
89
  " cve-lite . --incomplete-policy error Exit 3 if detection data is incomplete",
89
90
  " cve-lite . --json Write findings to a timestamped JSON file",
91
+ " cve-lite . --sarif --output out Write the SARIF file into ./out",
90
92
  " cve-lite . --report Generate an interactive HTML report",
91
93
  " cve-lite . --fix Apply validated direct dependency fixes and rescan",
92
94
  " cve-lite . --offline Scan using the local advisory database (no network)",
@@ -46,6 +46,9 @@ export async function validateOptions(options) {
46
46
  if (options.report && options.json) {
47
47
  throw new Error("--report cannot be used with --json. Use --report to generate an HTML report, or --json to save scan results as JSON, not both.");
48
48
  }
49
+ if (options.output && !(options.json || options.sarif || resolveSbomFormat(options))) {
50
+ throw new Error("--output requires --json, --sarif or --sbom. Add one of them to write a file into the output directory, or remove --output.");
51
+ }
49
52
  if (options.caCert) {
50
53
  try {
51
54
  validateCaCertFile(options.caCert);
@@ -1,5 +1,5 @@
1
1
  import { randomUUID } from "node:crypto";
2
- import { findSuggestedCommandForFinding } from "../remediation/fix-commands.js";
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
5
  import { buildPurl } from "../utils/purl.js";
@@ -49,6 +49,9 @@ export function buildCycloneDxBom(allPackages, findings, projectMeta, version, p
49
49
  addProperty("fix-version-published-at", finding.fixVersionPublishedAt);
50
50
  addProperty("versions-scanned", finding.validatedTargetScannedVersions);
51
51
  addProperty("versions-still-vulnerable", finding.validatedTargetKnownVulnerableVersions);
52
+ const planTarget = plan ? findFixTargetForFinding(plan, finding) : null;
53
+ addProperty("child-package", planTarget?.childPackage);
54
+ addProperty("child-target-version", planTarget?.childTargetVersion);
52
55
  vulnerabilities.push({
53
56
  id: cveId,
54
57
  source: {
@@ -94,8 +97,8 @@ export function buildCycloneDxBom(allPackages, findings, projectMeta, version, p
94
97
  vulnerabilities,
95
98
  };
96
99
  }
97
- export function writeCycloneDxReport(allPackages, findings, plan, projectMeta) {
100
+ export function writeCycloneDxReport(allPackages, findings, plan, projectMeta, outputDir) {
98
101
  const filename = `cve-lite-scan-${sbomTimestamp()}.cdx.json`;
99
102
  const bom = buildCycloneDxBom(allPackages, findings, projectMeta, getCliVersion(), plan);
100
- return writeSbomFile(filename, bom, "CycloneDX report");
103
+ return writeSbomFile(filename, bom, "CycloneDX report", outputDir);
101
104
  }
@@ -12,6 +12,7 @@ import { renderMaintenanceFindingsHtml } from "./maintenance-findings-html.js";
12
12
  import { renderLicenseFindingsHtml } from "./license-findings-html.js";
13
13
  import { PRIORITY_SIGNAL_LABELS, PRIORITY_SIGNAL_DESCRIPTIONS, PRIORITY_SIGNAL_LEGEND_DESCRIPTIONS } from "../utils/priority-signal.js";
14
14
  import { UNVERIFIED_PARENT_UPGRADE_NOTE } from "../remediation/fix-commands.js";
15
+ import { formatParentUpdateChildNote } from "../remediation/parent-update-child-note.js";
15
16
  import { getCompletenessImpact } from "../scan/completeness.js";
16
17
  export function serializeHtmlFinding(finding, plan) {
17
18
  return {
@@ -870,9 +871,12 @@ export function renderFixPlan(plan) {
870
871
  const displayVersion = t.targetVersion;
871
872
  const isMajor = t.currentVersion ? isBreakingUpgrade(t.currentVersion, t.targetVersion) : false;
872
873
  const breakBadge = isMajor ? ` <span class="break-badge">⚠ breaking</span>` : "";
873
- const versionHtml = t.currentVersion
874
- ? `<span class="fix-target-pkg">${escapeHtml(t.package)}@${escapeHtml(t.currentVersion)}</span><span class="fix-target-arrow">→</span><span class="fix-target-to">${escapeHtml(displayVersion)}</span>`
875
- : `<span class="fix-target-pkg">${escapeHtml(t.package)}</span><span class="fix-target-arrow">→</span><span class="fix-target-to">${escapeHtml(displayVersion)}</span>`;
874
+ const childNote = formatParentUpdateChildNote(t);
875
+ const versionHtml = childNote
876
+ ? `<span class="fix-target-pkg">${escapeHtml(t.package)}${t.currentVersion ? `@${escapeHtml(t.currentVersion)}` : ""}</span><span class="fix-target-note">${escapeHtml(childNote)}</span>`
877
+ : t.currentVersion
878
+ ? `<span class="fix-target-pkg">${escapeHtml(t.package)}@${escapeHtml(t.currentVersion)}</span><span class="fix-target-arrow">→</span><span class="fix-target-to">${escapeHtml(displayVersion)}</span>`
879
+ : `<span class="fix-target-pkg">${escapeHtml(t.package)}</span><span class="fix-target-arrow">→</span><span class="fix-target-to">${escapeHtml(displayVersion)}</span>`;
876
880
  const statsHtml = t.scannedVersions != null
877
881
  ? ` <span class="fix-target-stats">${t.scannedVersions} scanned${t.knownVulnerableVersions != null ? ` · ${t.knownVulnerableVersions} still vulnerable` : ""}</span>`
878
882
  : "";
@@ -0,0 +1,20 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ /** Directory for --json, --sarif and --sbom files: the working directory, or --output resolved against it and created when missing. */
4
+ export function resolveOutputDir(output) {
5
+ if (!output)
6
+ return process.cwd();
7
+ const dir = path.resolve(process.cwd(), output);
8
+ try {
9
+ fs.mkdirSync(dir, { recursive: true });
10
+ }
11
+ catch (err) {
12
+ throw new Error(`Failed to create output directory ${dir}: ${err instanceof Error ? err.message : String(err)}`, { cause: err });
13
+ }
14
+ return dir;
15
+ }
16
+ /** Path printed for a written file: relative to the working directory, or absolute when it lies outside it. */
17
+ export function displayOutputPath(outputPath) {
18
+ const relative = path.relative(process.cwd(), outputPath);
19
+ return relative.startsWith("..") ? outputPath : relative;
20
+ }
@@ -1,5 +1,6 @@
1
1
  import { chalk, stripAnsi } from "../utils/chalk.js";
2
- import { buildSuggestedFixCommandPlan, findFixTargetForFinding, UNVERIFIED_PARENT_UPGRADE_NOTE } from "../remediation/fix-commands.js";
2
+ import { buildSuggestedFixCommandPlan, planVersionForFinding, UNVERIFIED_PARENT_UPGRADE_NOTE } from "../remediation/fix-commands.js";
3
+ import { formatParentUpdateChildNote } from "../remediation/parent-update-child-note.js";
3
4
  import { isBreakingUpgrade } from "../utils/version.js";
4
5
  import { getPrimaryParent } from "../utils/finding.js";
5
6
  import { countUniqueAdvisories, countProdFindings, formatRelationshipLabel, formatRelLabel, formatRootDependencySummary, formatFixCommandWithPublishDates, formatCooldownWarning, } from "./formatters.js";
@@ -381,8 +382,9 @@ function findingToTableRow(finding, plan, skippedKeys) {
381
382
  // Prefer the version the fix plan will actually install. A package that is both
382
383
  // a direct finding and the parent of other findings needs a higher version than
383
384
  // its own advisory requires, and showing the lower one here contradicted the fix
384
- // command sitting a few lines above.
385
- const planTarget = plan ? findFixTargetForFinding(plan, finding)?.targetVersion : undefined;
385
+ // command sitting a few lines above. For parent-update this is the child's
386
+ // destination, not the parent's unchanged version stored on targetVersion.
387
+ const planTarget = plan ? planVersionForFinding(plan, finding) : undefined;
386
388
  const ownFixVersion = finding.validatedFirstFixedVersion ?? finding.firstFixedVersion;
387
389
  const fixVersion = planTarget ?? ownFixVersion ?? null;
388
390
  return {
@@ -422,6 +424,18 @@ function formatTargetDisplay(finding, fixVersion, isSkipped) {
422
424
  return chalk.yellow("⚠ Malicious");
423
425
  return chalk.yellow("⚠ no fix");
424
426
  }
427
+ function fixTargetContext(target) {
428
+ const childNote = formatParentUpdateChildNote(target);
429
+ const reason = target.reason ?? target.adjustmentNote ?? null;
430
+ if (childNote && reason) {
431
+ if (target.childPackage && target.childTargetVersion
432
+ && reason.includes(`${target.childPackage}@${target.childTargetVersion}`)) {
433
+ return reason;
434
+ }
435
+ return `${childNote}. ${reason}`;
436
+ }
437
+ return childNote ?? reason;
438
+ }
425
439
  function fixTargetToTableRow(target, context) {
426
440
  return {
427
441
  package: target.package,
@@ -441,7 +455,7 @@ function fixTargetToTableRow(target, context) {
441
455
  epss: context?.epss ?? null,
442
456
  signal: context?.prioritySignal ?? null,
443
457
  ids: context?.ids,
444
- context: target.reason ?? target.adjustmentNote ?? null,
458
+ context: fixTargetContext(target),
445
459
  };
446
460
  }
447
461
  /** The bold summary row under a fix table: only the validation counts carry values. */
@@ -5,6 +5,7 @@ import { getRecommendedAction, formatCooldownWarning } from "./formatters.js";
5
5
  import { getCliVersion } from "../utils/version-info.js";
6
6
  import { severityToSarifLevel } from "../utils/severity.js";
7
7
  import { sarifFingerprintHash } from "../utils/sarif.js";
8
+ import { displayOutputPath } from "./output-dir.js";
8
9
  import { buildOverrideSarifComponent, buildOverrideSarifResults } from "./override-findings-sarif.js";
9
10
  import { buildMaintenanceSarifComponent, buildMaintenanceSarifResults } from "./maintenance-findings-sarif.js";
10
11
  import { buildLicenseSarifComponent, buildLicenseSarifResults } from "./license-findings-sarif.js";
@@ -88,7 +89,8 @@ export function buildSarifOutput(findings, lockfileUri, version, plan, overrideF
88
89
  // If the recommended fix for this finding lands on a version inside the
89
90
  // project's configured release cooldown, surface that on the result so it
90
91
  // reaches Code Scanning (message text for humans, property for tooling).
91
- const cooldown = plan ? findFixTargetForFinding(plan, finding)?.cooldownWarning ?? null : null;
92
+ const planTarget = plan ? findFixTargetForFinding(plan, finding) : null;
93
+ const cooldown = planTarget?.cooldownWarning ?? null;
92
94
  const location = {
93
95
  physicalLocation: {
94
96
  artifactLocation: { uri: lockfileUri, uriBaseId: "%SRCROOT%" },
@@ -133,6 +135,10 @@ export function buildSarifOutput(findings, lockfileUri, version, plan, overrideF
133
135
  if (finding.validatedTargetKnownVulnerableVersions != null) {
134
136
  resultProperties.versionsStillVulnerable = finding.validatedTargetKnownVulnerableVersions;
135
137
  }
138
+ if (planTarget?.childPackage)
139
+ resultProperties.childPackage = planTarget.childPackage;
140
+ if (planTarget?.childTargetVersion)
141
+ resultProperties.childTargetVersion = planTarget.childTargetVersion;
136
142
  results.push({
137
143
  ruleId,
138
144
  ruleIndex: ruleIndexMap.get(ruleId),
@@ -192,10 +198,10 @@ export function buildSarifOutput(findings, lockfileUri, version, plan, overrideF
192
198
  ],
193
199
  };
194
200
  }
195
- export function writeSarifReport(findings, lockfileUri, plan, overrideFindings, maintenanceFindings, licenseFindings) {
201
+ export function writeSarifReport(findings, lockfileUri, plan, overrideFindings, maintenanceFindings, licenseFindings, outputDir = process.cwd()) {
196
202
  const ts = new Date().toISOString().replace(/[:.]/g, "-").slice(0, 19);
197
203
  const filename = `cve-lite-scan-${ts}.sarif`;
198
- const outputPath = path.join(process.cwd(), filename);
204
+ const outputPath = path.join(outputDir, filename);
199
205
  const sarif = buildSarifOutput(findings, lockfileUri, getCliVersion(), plan, overrideFindings, maintenanceFindings, licenseFindings);
200
206
  try {
201
207
  fs.writeFileSync(outputPath, JSON.stringify(sarif, null, 2));
@@ -207,5 +213,5 @@ export function writeSarifReport(findings, lockfileUri, plan, overrideFindings,
207
213
  catch { /* best-effort cleanup */ }
208
214
  throw new Error(`Failed to write SARIF report to ${outputPath}: ${err instanceof Error ? err.message : String(err)}`, { cause: err });
209
215
  }
210
- return filename;
216
+ return displayOutputPath(outputPath);
211
217
  }
@@ -1,14 +1,16 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
+ import { displayOutputPath } from "./output-dir.js";
3
4
  /**
4
- * Writes an SBOM document to a timestamped file in the working directory.
5
+ * Writes an SBOM document to a timestamped file in the output directory,
6
+ * which defaults to the working directory.
5
7
  *
6
8
  * A partial file left behind by a failed write would look like a valid SBOM to
7
9
  * whatever consumes it next, so the partial output is removed before the error
8
10
  * propagates.
9
11
  */
10
- export function writeSbomFile(filename, document, label) {
11
- const outputPath = path.join(process.cwd(), filename);
12
+ export function writeSbomFile(filename, document, label, outputDir = process.cwd()) {
13
+ const outputPath = path.join(outputDir, filename);
12
14
  try {
13
15
  fs.writeFileSync(outputPath, JSON.stringify(document, null, 2));
14
16
  }
@@ -19,7 +21,7 @@ export function writeSbomFile(filename, document, label) {
19
21
  catch { /* best-effort cleanup */ }
20
22
  throw new Error(`Failed to write ${label} to ${outputPath}: ${err instanceof Error ? err.message : String(err)}`, { cause: err });
21
23
  }
22
- return filename;
24
+ return displayOutputPath(outputPath);
23
25
  }
24
26
  /** Filesystem-safe UTC stamp shared by every SBOM filename. */
25
27
  export function sbomTimestamp() {
@@ -286,8 +286,8 @@ export function buildSpdxDocument(allPackages, findings, projectMeta, version, p
286
286
  relationships,
287
287
  };
288
288
  }
289
- export function writeSpdxReport(allPackages, findings, plan, projectMeta, options = {}) {
289
+ export function writeSpdxReport(allPackages, findings, plan, projectMeta, options = {}, outputDir) {
290
290
  const filename = `cve-lite-scan-${sbomTimestamp()}.spdx.json`;
291
291
  const doc = buildSpdxDocument(allPackages, findings, projectMeta, getCliVersion(), plan, options);
292
- return writeSbomFile(filename, doc, "SPDX SBOM");
292
+ return writeSbomFile(filename, doc, "SPDX SBOM", outputDir);
293
293
  }
@@ -10,6 +10,7 @@ import { resolveDependencyEdges } from "./sbom-dependency-edges.js";
10
10
  import { resolveSbomFormat } from "../utils/sbom-format.js";
11
11
  import { overrideFindingsToJson } from "./override-findings-json.js";
12
12
  import { maintenanceFindingsToJson } from "./maintenance-findings-json.js";
13
+ import { resolveOutputDir, displayOutputPath } from "./output-dir.js";
13
14
  function readProjectMeta(projectPath) {
14
15
  try {
15
16
  const pkgPath = path.join(projectPath, "package.json");
@@ -29,10 +30,11 @@ function readProjectMeta(projectPath) {
29
30
  }
30
31
  }
31
32
  export async function writeOutputs(options, scanState, scanInput, projectPath) {
33
+ const outputDir = resolveOutputDir(options.output);
32
34
  if (options.json) {
33
35
  const ts = new Date().toISOString().replace(/[:.]/g, "-").slice(0, 19);
34
36
  const jsonFilename = `cve-lite-scan-${ts}.json`;
35
- const jsonOutputPath = path.join(process.cwd(), jsonFilename);
37
+ const jsonOutputPath = path.join(outputDir, jsonFilename);
36
38
  const payload = {
37
39
  projectPath,
38
40
  mode: scanInput.mode,
@@ -58,11 +60,11 @@ export async function writeOutputs(options, scanState, scanInput, projectPath) {
58
60
  : {};
59
61
  const combined = { ...payload, ...overridePayload, ...maintenancePayload, ...licensePayload };
60
62
  fs.writeFileSync(jsonOutputPath, JSON.stringify(combined, null, 2));
61
- console.log(`${chalk.gray("JSON saved to")} ${chalk.cyan(jsonFilename)}`);
63
+ console.log(`${chalk.gray("JSON saved to")} ${chalk.cyan(displayOutputPath(jsonOutputPath))}`);
62
64
  }
63
65
  if (options.sarif) {
64
66
  const lockfileUri = deriveLockfileUri(scanInput);
65
- const sarifFilename = writeSarifReport(scanState.sorted, lockfileUri, scanState.suggestedFixCommands, scanState.overrideFindings, scanState.maintenanceFindings, scanState.licenseFindings);
67
+ const sarifFilename = writeSarifReport(scanState.sorted, lockfileUri, scanState.suggestedFixCommands, scanState.overrideFindings, scanState.maintenanceFindings, scanState.licenseFindings, outputDir);
66
68
  console.log(`${chalk.gray("SARIF report written to")} ${chalk.cyan(sarifFilename)}`);
67
69
  }
68
70
  const sbomFormat = resolveSbomFormat(options);
@@ -74,11 +76,11 @@ export async function writeOutputs(options, scanState, scanInput, projectPath) {
74
76
  // Resolved from the lockfile graph where available. Empty for pnpm,
75
77
  // Yarn and Bun, which falls back to path-derived edges.
76
78
  dependencyEdges: resolveDependencyEdges(scanInput, scanState.allPackages),
77
- });
79
+ }, outputDir);
78
80
  console.log(`${chalk.gray("SPDX SBOM written to")} ${chalk.cyan(spdxFilename)}`);
79
81
  }
80
82
  else {
81
- const cdxFilename = writeCycloneDxReport(scanState.allPackages, scanState.sorted, scanState.suggestedFixCommands, projectMeta);
83
+ const cdxFilename = writeCycloneDxReport(scanState.allPackages, scanState.sorted, scanState.suggestedFixCommands, projectMeta, outputDir);
82
84
  console.log(`${chalk.gray("CycloneDX BOM written to")} ${chalk.cyan(cdxFilename)}`);
83
85
  }
84
86
  }
@@ -1,4 +1,5 @@
1
1
  import { satisfiesRange, coerceVersion, compareVersions, looksLikeVersion, isValidRange } from "../../utils/version.js";
2
+ import { pluralize } from "../../utils/string.js";
2
3
  import { jsonPointer } from "../parsing/json-pointer.js";
3
4
  const RULE_ID = "OA008";
4
5
  /**
@@ -41,7 +42,7 @@ export function detect(ctx) {
41
42
  if (vulnerable.length === 0)
42
43
  continue;
43
44
  const versions = vulnerable.map(c => c.version);
44
- const distinct = Array.from(new Set(versions)).sort();
45
+ const distinct = Array.from(new Set(versions)).sort(compareVersions);
45
46
  findings.push({
46
47
  ruleId: RULE_ID,
47
48
  severity: "critical",
@@ -49,7 +50,7 @@ export function detect(ctx) {
49
50
  location: { file: "package.json", jsonPath: jsonPointer(entry.path) },
50
51
  message: "Override floor not applied - vulnerable copy still on disk",
51
52
  details: `Override demands ${entry.packageName} ${pinValue}, but ${vulnerable.length} ` +
52
- `installed copy${vulnerable.length === 1 ? "" : "ies"} (${distinct.join(", ")}) ` +
53
+ `installed ${pluralize(vulnerable.length, "copy", "copies")} (${distinct.join(", ")}) ` +
53
54
  `${vulnerable.length === 1 ? "is" : "are"} below the floor. ` +
54
55
  `The override is not effective everywhere - likely a parent declares this dep ` +
55
56
  `as exact and wins resolution.`,
@@ -89,7 +89,15 @@ export function buildSuggestedFixCommandPlan(findings, scanInput, options) {
89
89
  // validatedFirstFixedVersion is "did not validate" rather than "validation
90
90
  // failed" — fall back to the advisory hint instead of dropping the target.
91
91
  const validatedFieldOk = offline || !hasValidatedField || finding.validatedFirstFixedVersion !== null;
92
- const allVersionsVulnerable = finding.validatedTargetScannedVersions != null &&
92
+ // A confirmed fix version is a direct answer to "is there a safe upgrade",
93
+ // where the counter comparison below is only an inference about one. When
94
+ // the two disagree the confirmed version wins, because reporting a dead
95
+ // end in the same scan that names the fix is the worse failure. This also
96
+ // stops the rule depending on two counters that separate passes maintain
97
+ // (#1213).
98
+ const hasConfirmedFix = finding.validatedFirstFixedVersion != null;
99
+ const allVersionsVulnerable = !hasConfirmedFix &&
100
+ finding.validatedTargetScannedVersions != null &&
93
101
  finding.validatedTargetKnownVulnerableVersions != null &&
94
102
  finding.validatedTargetScannedVersions > 0 &&
95
103
  finding.validatedTargetKnownVulnerableVersions >= finding.validatedTargetScannedVersions;
@@ -98,7 +106,7 @@ export function buildSuggestedFixCommandPlan(findings, scanInput, options) {
98
106
  package: finding.pkg.name,
99
107
  version: finding.pkg.version,
100
108
  relationship: finding.relationship,
101
- reason: `No safe upgrade: all ${finding.validatedTargetScannedVersions} scanned ${pluralize(finding.validatedTargetScannedVersions ?? 0, "version")} are still known-vulnerable. This package may be unmaintained.`,
109
+ reason: `No safe upgrade: all ${finding.validatedTargetScannedVersions} scanned ${pluralize(finding.validatedTargetScannedVersions ?? 0, "version")} ${pluralize(finding.validatedTargetScannedVersions ?? 0, "is", "are")} still known-vulnerable. This package may be unmaintained.`,
102
110
  });
103
111
  continue;
104
112
  }
@@ -171,22 +179,14 @@ export function buildSuggestedFixCommandPlan(findings, scanInput, options) {
171
179
  if (packageManager === "npm" &&
172
180
  finding.relationship === "transitive" &&
173
181
  finding.recommendedNpmTransitiveRemediation?.kind === "update-parent-within-range") {
174
- upsertTarget(targetsByKey, finding, {
182
+ upsertTarget(targetsByKey, finding, parentUpdateTarget(finding, urgent, {
175
183
  package: finding.recommendedNpmTransitiveRemediation.package,
176
184
  currentVersion: finding.recommendedNpmTransitiveRemediation.currentVersion,
177
- targetVersion: finding.recommendedNpmTransitiveRemediation.targetChildVersion,
178
- scannedVersions: null,
179
- knownVulnerableVersions: null,
180
- kind: "parent-update",
181
- urgent,
182
- severity: finding.severity,
183
- adjusted: false,
184
- adjustmentNote: null,
185
+ childTargetVersion: finding.recommendedNpmTransitiveRemediation.targetChildVersion,
185
186
  reason: finding.recommendedNpmTransitiveRemediation.reason,
186
187
  command: buildNpmUpdateCommand(finding.recommendedNpmTransitiveRemediation.package, finding.recommendedNpmTransitiveRemediation.workspaces),
187
- usage: finding.usage ?? null,
188
188
  isDev: devLookup.get(`${finding.recommendedNpmTransitiveRemediation.package}@${finding.recommendedNpmTransitiveRemediation.currentVersion}`) ?? false,
189
- });
189
+ }));
190
190
  continue;
191
191
  }
192
192
  if (packageManager === "npm" &&
@@ -273,21 +273,13 @@ export function buildSuggestedFixCommandPlan(findings, scanInput, options) {
273
273
  : packageManager === "yarn"
274
274
  ? `yarn upgrade ${finding.pkg.name}`
275
275
  : `bun update ${finding.pkg.name}`;
276
- upsertTarget(targetsByKey, finding, {
276
+ upsertTarget(targetsByKey, finding, parentUpdateTarget(finding, urgent, {
277
277
  package: finding.pkg.name,
278
278
  currentVersion: finding.pkg.version,
279
- targetVersion: finding.recommendedNpmTransitiveRemediation.targetChildVersion,
280
- scannedVersions: null,
281
- knownVulnerableVersions: null,
282
- kind: "parent-update",
283
- urgent,
284
- severity: finding.severity,
285
- adjusted: false,
286
- adjustmentNote: null,
279
+ childTargetVersion: finding.recommendedNpmTransitiveRemediation.targetChildVersion,
287
280
  reason: `${finding.pkg.name}@${finding.pkg.version} can be refreshed to ${finding.recommendedNpmTransitiveRemediation.targetChildVersion}+ — no parent upgrade needed.`,
288
281
  command: lockfileRefreshCommand,
289
- usage: finding.usage ?? null,
290
- });
282
+ }));
291
283
  continue;
292
284
  }
293
285
  const primaryParent = getPrimaryParent(finding);
@@ -456,9 +448,20 @@ function devFlag(packageManager) {
456
448
  export function findFixTargetForFinding(plan, finding) {
457
449
  const target = plan.targets.find(item => {
458
450
  if (finding.recommendedNpmTransitiveRemediation?.kind === "update-parent-within-range") {
459
- return (item.kind === "parent-update" &&
460
- item.targetVersion === finding.recommendedNpmTransitiveRemediation.targetChildVersion &&
461
- (item.package === finding.recommendedNpmTransitiveRemediation.package || item.package === finding.pkg.name));
451
+ const rem = finding.recommendedNpmTransitiveRemediation;
452
+ if (item.kind !== "parent-update")
453
+ return false;
454
+ if (item.package !== rem.package && item.package !== finding.pkg.name)
455
+ return false;
456
+ // Parent-named parent-update: match only on child identity. Falling
457
+ // through to targetVersion compares the parent's version to the child's
458
+ // destination and can attach the wrong sibling.
459
+ if (item.childPackage) {
460
+ return item.childPackage === finding.pkg.name
461
+ && item.childTargetVersion === rem.targetChildVersion;
462
+ }
463
+ // Self-refresh / lockfile refresh: destination stays on targetVersion.
464
+ return item.targetVersion === rem.targetChildVersion;
462
465
  }
463
466
  if (finding.recommendedParentUpgrade) {
464
467
  if (item.package !== finding.recommendedParentUpgrade.package)
@@ -535,10 +538,11 @@ function packageManagerSourceLabel(scanInput) {
535
538
  // Install targets (direct / parent-upgrade) all mean "install <package>@<targetVersion>",
536
539
  // so findings that land on the same package merge into one target and the higher
537
540
  // version wins. A parent-update target means something else: "refresh <vulnerable
538
- // child> within <package>'s declared range", and its targetVersion is the CHILD's
539
- // version, not <package>'s. Merging it with an install target for the same package
540
- // compares versions of two different packages, and the child's version can end up
541
- // pinned onto the parent (`npm install axios@4.0.6`, where 4.0.6 is form-data's
541
+ // child> within <package>'s declared range". Its targetVersion is <package>'s own
542
+ // version (unchanged); the child's identity lives on childPackage / childTargetVersion
543
+ // when package is the parent. Merging it with an install target for the same package
544
+ // used to compare versions of two different packages, and the child's version could
545
+ // end up pinned onto the parent (`npm install axios@4.0.6`, where 4.0.6 is form-data's
542
546
  // version - #1007). Keep parent-update targets in their own keyspace, per child, so
543
547
  // they only ever merge with a refresh of the same child through the same package.
544
548
  function targetKey(finding, target) {
@@ -546,6 +550,47 @@ function targetKey(finding, target) {
546
550
  ? `parent-update:${target.package}>${finding.pkg.name}`
547
551
  : `install:${target.package}`;
548
552
  }
553
+ // Build a parent-update target whose targetVersion always belongs to `package`.
554
+ // When the named package is the parent of the finding, the child's version moves
555
+ // onto childPackage / childTargetVersion so renderers cannot treat it as an
556
+ // upgrade of the parent (#1152). When the named package is the child itself
557
+ // (deep-chain npm update, pnpm/yarn/bun lockfile refresh), targetVersion stays
558
+ // the child's destination.
559
+ function parentUpdateTarget(finding, urgent, args) {
560
+ const namesParent = args.package !== finding.pkg.name;
561
+ return {
562
+ package: args.package,
563
+ currentVersion: args.currentVersion,
564
+ targetVersion: namesParent ? args.currentVersion : args.childTargetVersion,
565
+ childPackage: namesParent ? finding.pkg.name : undefined,
566
+ childTargetVersion: namesParent ? args.childTargetVersion : undefined,
567
+ scannedVersions: null,
568
+ knownVulnerableVersions: null,
569
+ kind: "parent-update",
570
+ urgent,
571
+ severity: finding.severity,
572
+ adjusted: false,
573
+ adjustmentNote: null,
574
+ reason: args.reason,
575
+ command: args.command,
576
+ usage: finding.usage ?? null,
577
+ isDev: args.isDev,
578
+ };
579
+ }
580
+ /**
581
+ * The version of finding.pkg that the plan is aiming for.
582
+ * A parent-update that names a different package stores the child's destination
583
+ * on childTargetVersion, not on targetVersion (which is the parent's).
584
+ */
585
+ export function planVersionForFinding(plan, finding) {
586
+ const target = findFixTargetForFinding(plan, finding);
587
+ if (!target)
588
+ return undefined;
589
+ if (target.childPackage === finding.pkg.name && target.childTargetVersion) {
590
+ return target.childTargetVersion;
591
+ }
592
+ return target.targetVersion;
593
+ }
549
594
  function upsertTarget(targetsByKey, finding, next) {
550
595
  const key = targetKey(finding, next);
551
596
  const existing = targetsByKey.get(key);
@@ -576,6 +621,10 @@ function upsertTarget(targetsByKey, finding, next) {
576
621
  chainProof: existing.chainProof ?? next.chainProof,
577
622
  chainSafeVersion: existing.chainSafeVersion ?? next.chainSafeVersion,
578
623
  chainVulnerablePackage: existing.chainVulnerablePackage ?? next.chainVulnerablePackage,
624
+ childPackage: existing.childPackage ?? next.childPackage,
625
+ childTargetVersion: higherVersion(existing.childTargetVersion, next.childTargetVersion)
626
+ ?? existing.childTargetVersion
627
+ ?? next.childTargetVersion,
579
628
  // Conservative: if either contributing finding's recommendation is unverified,
580
629
  // keep the merged target unverified rather than overstate coverage.
581
630
  confidence: existing.confidence === "unverified" || next.confidence === "unverified"
@@ -668,6 +717,15 @@ function isUpgradeTarget(currentVersion, targetVersion) {
668
717
  }
669
718
  return true;
670
719
  }
720
+ function higherVersion(a, b) {
721
+ if (!a)
722
+ return b;
723
+ if (!b)
724
+ return a;
725
+ if (looksLikeVersion(a) && looksLikeVersion(b) && compareVersions(b, a) > 0)
726
+ return b;
727
+ return a;
728
+ }
671
729
  function buildSections(targets, packageManager) {
672
730
  const groups = [];
673
731
  const sectionOrder = [
@@ -343,12 +343,20 @@ async function confirmAgainstAdvisorySource(packageName, resolution, advisorySou
343
343
  // arithmetic, so it confirms the answer even when the range pass could not.
344
344
  if (confirmed === proposed && resolution.resolvedVersion)
345
345
  return resolution;
346
+ // Both counters describe the same set, so they have to advance together. The
347
+ // confirmation pass examined every candidate up to and including `confirmed`,
348
+ // which is `index + 1` versions, of which `index` were affected. Advancing
349
+ // only the vulnerable count left the pair equal for a single-version window,
350
+ // and `fix-commands` reads `knownVulnerable >= scanned` as "no safe upgrade",
351
+ // so a confirmed fix was reported as an unmaintained dead end (#1213).
352
+ const confirmedIndex = candidates.indexOf(confirmed);
346
353
  return {
347
354
  ...resolution,
348
355
  resolvedVersion: confirmed,
349
356
  verified: true,
350
357
  note: null,
351
- candidatesKnownVulnerable: resolution.candidatesKnownVulnerable + candidates.indexOf(confirmed),
358
+ candidatesChecked: resolution.candidatesChecked + confirmedIndex + 1,
359
+ candidatesKnownVulnerable: resolution.candidatesKnownVulnerable + confirmedIndex,
352
360
  publishedAt: packument?.time?.[confirmed] ?? null,
353
361
  };
354
362
  }
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Context note naming the child a parent-update target refreshes, or null.
3
+ * Leaf module so printers / fix-runner / create-pr can import without cycling through fix-commands.
4
+ */
5
+ export function formatParentUpdateChildNote(target) {
6
+ if (target.kind && target.kind !== "parent-update")
7
+ return null;
8
+ if (!target.childPackage || !target.childTargetVersion)
9
+ return null;
10
+ return `refresh ${target.childPackage} to ${target.childTargetVersion}`;
11
+ }
@@ -5,6 +5,7 @@ import { EXIT_OK, EXIT_FINDINGS, EXIT_ERROR } from "../types.js";
5
5
  import { loadMultiplePackages } from "../parsers/multi-package.js";
6
6
  import { scanPackages, buildCoverageNotes } from "../scanner.js";
7
7
  import { sortFindingsForOutput, serializeFinding, logInfo } from "../output/formatters.js";
8
+ import { resolveOutputDir, displayOutputPath } from "../output/output-dir.js";
8
9
  import { normalizeSeverity } from "../osv/severity.js";
9
10
  import { selectFindingsForTable } from "../output/finding-display.js";
10
11
  import { buildSuggestedFixCommandPlan } from "../remediation/fix-commands.js";
@@ -280,9 +281,9 @@ export async function handleMultiFolderScan(params) {
280
281
  };
281
282
  const ts = new Date().toISOString().replace(/[:.]/g, "-").slice(0, 19);
282
283
  const jsonFilename = `cve-lite-scan-${ts}.json`;
283
- const jsonOutputPath = path.join(process.cwd(), jsonFilename);
284
+ const jsonOutputPath = path.join(resolveOutputDir(params.options.output), jsonFilename);
284
285
  fs.writeFileSync(jsonOutputPath, JSON.stringify(payload, null, 2));
285
- console.log(`${chalk.gray("JSON saved to")} ${chalk.cyan(jsonFilename)}`);
286
+ console.log(`${chalk.gray("JSON saved to")} ${chalk.cyan(displayOutputPath(jsonOutputPath))}`);
286
287
  }
287
288
  else {
288
289
  printMultiFolderResults(results, params.options);
@@ -24,7 +24,8 @@ import { renderLicenseFindings } from "../output/license-terminal.js";
24
24
  import { readDirectDependencyNames, hasOverrideEntries } from "../utils/package-json.js";
25
25
  import { applyFixesIfRequested, printFixModeSummary, writeFixResultJson, } from "../utils/fix-runner.js";
26
26
  import { audit, buildOverrideContext } from "../overrides/index.js";
27
- import { collectAdvisoryIdsForPackage, createPullRequestForFixes, } from "../utils/create-pr.js";
27
+ import { buildFixResultAppliedEntries, createPullRequestForFixes, } from "../utils/create-pr.js";
28
+ import { buildCveFixAppliedEvent } from "../audit-log/events.js";
28
29
  import { readBaseline, writeBaseline, filterNewFindings, ratchetOutcome } from "../utils/baseline.js";
29
30
  import { formatDiagnosticMessage, getCompletenessImpact, shouldFailForIncompleteScan } from "./completeness.js";
30
31
  export async function handleSingleFolderScan(params) {
@@ -260,15 +261,15 @@ export async function handleSingleFolderScan(params) {
260
261
  // Emit cve.fix.applied for each target in the fix plan
261
262
  if (scanState.suggestedFixCommands?.targets) {
262
263
  for (const target of scanState.suggestedFixCommands.targets) {
263
- auditLog.emit({
264
+ auditLog.emit(buildCveFixAppliedEvent({
264
265
  ts: new Date().toISOString(),
265
- type: "cve.fix.applied",
266
- schemaVersion: 1,
267
266
  package: target.package,
268
267
  fromVersion: target.currentVersion ?? "unknown",
269
268
  toVersion: target.targetVersion,
270
269
  mechanism: target.kind,
271
- });
270
+ childPackage: target.childPackage,
271
+ childTargetVersion: target.childTargetVersion,
272
+ }));
272
273
  }
273
274
  }
274
275
  if (options.fix) {
@@ -286,12 +287,7 @@ export async function handleSingleFolderScan(params) {
286
287
  appliedWithinRangeRefreshCount: fixResult?.appliedWithinRangeRefreshCount ?? 0,
287
288
  findingsBeforeFix,
288
289
  findingsAfterFix: scanState.sorted.length,
289
- applied: (fixResult?.applied ?? []).map(entry => ({
290
- package: entry.package,
291
- from: entry.from,
292
- to: entry.to,
293
- advisories: collectAdvisoryIdsForPackage(findingsBeforeFixList, entry.package),
294
- })),
290
+ applied: buildFixResultAppliedEntries(fixResult?.applied ?? [], findingsBeforeFixList),
295
291
  notAutoApplied: {
296
292
  parentUpgradeCount: fixResult?.parentUpgradeCount ?? 0,
297
293
  breakingUpgradeCount: fixResult?.breakingUpgradeCount ?? 0,
package/dist/scanner.js CHANGED
@@ -2,7 +2,7 @@ import { fetchEpssScores } from "./epss/client.js";
2
2
  import { chunk, runWithConcurrency } from "./utils/array.js";
3
3
  import { isPrivateRegistrySource, isGitSource, hasCommitShaPinning } from "./utils/advisory.js";
4
4
  import { extractCveAliases, hasMaliciousAdvisory } from "./utils/vuln.js";
5
- import { compareVersions, isPreReleaseVersion, looksLikeVersion } from "./utils/version.js";
5
+ import { compareVersions, isPreReleaseVersion, normalizeAdvisoryVersion } from "./utils/version.js";
6
6
  import { loadCache, saveCache, isEntryStale } from "./osv/cache.js";
7
7
  import { maxSeverity } from "./osv/severity.js";
8
8
  import { createSpinner } from "./output/spinner.js";
@@ -201,7 +201,13 @@ export async function scanPackages(packages, batchSize, options, context, debugL
201
201
  const uncachedForNpm = [];
202
202
  for (const pkg of allNpmPkgs) {
203
203
  const key = getPackageCacheKey(pkg);
204
- const cached = cache.npmAdvisoryEntries[key];
204
+ // `--no-cache` was honoured for OSV queries and the registry publish-date
205
+ // lookups but never here, so a flag whose whole purpose is to take the
206
+ // cache out of the picture still served this block from it, and two
207
+ // consecutive --no-cache runs could disagree. Writing back is deliberate
208
+ // and matches the other caches, which a test already pins; only the read
209
+ // is skipped (#1166).
210
+ const cached = options.noCache ? undefined : cache.npmAdvisoryEntries[key];
205
211
  if (cached && !isEntryStale(cached, nowMs)) {
206
212
  const newCachedVulns = cached.vulns.filter(v => !existingVulnIds.has(v.id));
207
213
  if (newCachedVulns.length > 0) {
@@ -265,7 +271,12 @@ export async function scanPackages(packages, batchSize, options, context, debugL
265
271
  const nowMs = Date.now();
266
272
  const uncachedIds = [];
267
273
  for (const id of ids) {
268
- const cached = cache.entries[id];
274
+ // Same gap as the npm advisory block above: the advisory detail cache
275
+ // was read regardless of the flag, so a --no-cache run could still
276
+ // restore a previously cached detail, including a negative entry that
277
+ // marks the scan incomplete. The write below stays unguarded, as it is
278
+ // for the other caches (#1166).
279
+ const cached = options.noCache ? undefined : cache.entries[id];
269
280
  if (cached && !isEntryStale(cached, nowMs)) {
270
281
  if (cached.vuln) {
271
282
  vulnMap.set(id, cached.vuln);
@@ -852,9 +863,13 @@ function affectedEntryMatchesPackage(affected, packageName, ecosystem) {
852
863
  */
853
864
  function versionWithinAffectedWindow(version, introduced, fixed) {
854
865
  if (introduced && introduced !== "0") {
855
- if (!looksLikeVersion(introduced))
866
+ // Advisories write boundaries with fewer than three components, so `2` means
867
+ // 2.0.0. Normalizing rather than rejecting keeps the window usable, and a
868
+ // value that is not a version at all still returns null and bails (#1192).
869
+ const normalizedIntroduced = normalizeAdvisoryVersion(introduced);
870
+ if (!normalizedIntroduced)
856
871
  return false;
857
- if (compareVersions(version, introduced) < 0)
872
+ if (compareVersions(version, normalizedIntroduced) < 0)
858
873
  return false;
859
874
  }
860
875
  return compareVersions(version, fixed) < 0;
@@ -886,8 +901,13 @@ function collectAdvisoryFixes(vuln, packageName, ecosystem, installedVersion) {
886
901
  introduced = event.introduced;
887
902
  continue;
888
903
  }
889
- const fixed = event.fixed;
890
- if (!fixed || !looksLikeVersion(fixed) || isPreReleaseVersion(fixed))
904
+ // `fixed: "1.22"` is 1.22.0. Requiring a strict X.Y.Z here discarded the
905
+ // event, and a finding whose every candidate was discarded reported "no
906
+ // fix available", which tells a developer to stop looking for a fix that
907
+ // exists (#1192). A value that cannot be read in full is still dropped,
908
+ // so a commit hash from a GIT range never becomes a fix version.
909
+ const fixed = normalizeAdvisoryVersion(event.fixed);
910
+ if (!fixed || isPreReleaseVersion(fixed))
891
911
  continue;
892
912
  all.push(fixed);
893
913
  if (installedVersion && versionWithinAffectedWindow(installedVersion, introduced, fixed)) {
@@ -3,6 +3,7 @@ import fs from "node:fs";
3
3
  import path from "node:path";
4
4
  import { severityOrder } from "../constants.js";
5
5
  import { normalizeSeverity } from "../osv/severity.js";
6
+ import { formatParentUpdateChildNote } from "../remediation/parent-update-child-note.js";
6
7
  import { pluralize } from "./string.js";
7
8
  const DEPENDENCY_FILES_TO_STAGE = [
8
9
  "package.json",
@@ -51,6 +52,21 @@ export function collectAdvisoryIdsForPackage(findings, packageName) {
51
52
  }
52
53
  return [...ids].sort();
53
54
  }
55
+ /**
56
+ * Build `--fix` result JSON `applied[]` entries for Action/automation consumers.
57
+ * Advisories are looked up on the refreshed child when present (parent-update),
58
+ * otherwise on the named package - same rule as create-pr body lines.
59
+ */
60
+ export function buildFixResultAppliedEntries(applied, findingsBeforeFix) {
61
+ return applied.map(entry => ({
62
+ package: entry.package,
63
+ from: entry.from,
64
+ to: entry.to,
65
+ advisories: collectAdvisoryIdsForPackage(findingsBeforeFix, entry.childPackage ?? entry.package),
66
+ ...(entry.childPackage ? { childPackage: entry.childPackage } : {}),
67
+ ...(entry.childTargetVersion ? { childTargetVersion: entry.childTargetVersion } : {}),
68
+ }));
69
+ }
54
70
  export function buildPullRequestBody(params) {
55
71
  const overrideFixCount = params.overrideFixCount ?? 0;
56
72
  const lines = [
@@ -65,9 +81,12 @@ export function buildPullRequestBody(params) {
65
81
  lines.push("- _No direct CVE fixes in this PR._");
66
82
  }
67
83
  for (const item of params.fixResult.applied) {
68
- const advisoryIds = collectAdvisoryIdsForPackage(params.findingsBeforeFix, item.package);
84
+ const advisoryPackage = item.childPackage ?? item.package;
85
+ const advisoryIds = collectAdvisoryIdsForPackage(params.findingsBeforeFix, advisoryPackage);
69
86
  const advisoryText = advisoryIds.length > 0 ? advisoryIds.join(", ") : "n/a";
70
- lines.push(`- **${item.package}**: \`${item.from}\` → \`${item.to}\``);
87
+ const childNote = formatParentUpdateChildNote(item);
88
+ const versionLine = `- **${item.package}**: \`${item.from}\` → \`${item.to}\``;
89
+ lines.push(childNote ? `${versionLine} (${childNote})` : versionLine);
71
90
  lines.push(` - Advisories: ${advisoryText}`);
72
91
  }
73
92
  if (overrideFixCount > 0) {
@@ -6,6 +6,7 @@ import { chalk } from "./chalk.js";
6
6
  import { pluralize } from "./string.js";
7
7
  import { isBreakingUpgrade } from "./version.js";
8
8
  import { buildTargetCommand } from "../remediation/fix-commands.js";
9
+ import { formatParentUpdateChildNote } from "../remediation/parent-update-child-note.js";
9
10
  export async function runInstallCommand(command, args, cwd, debugLog) {
10
11
  const commandLine = [command, ...args].join(" ");
11
12
  debugLog?.("Fix command", { command: commandLine, cwd });
@@ -109,10 +110,18 @@ export async function applyFixesIfRequested(params) {
109
110
  const total = applyTargets.length;
110
111
  const spinner = createSpinner(`Applying safe package fixes with ${commandLabel}... 0/${total}`, params.options);
111
112
  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.`;
113
+ // parent-update is keyed per child, so two children behind one parent produce
114
+ // two targets with the same `npm update <parent>` command. Spawn each command
115
+ // once; the displayed plan already dedupes the same way.
116
+ const seenCommands = new Set();
112
117
  for (let i = 0; i < applyTargets.length; i++) {
113
118
  const target = applyTargets[i];
114
119
  for (const commandParts of buildApplyCommands(params.plan.packageManager, target)) {
115
- spinner.update(`Applying fix ${i + 1}/${total}: ${commandParts.join(" ")}`);
120
+ const commandLine = commandParts.join(" ");
121
+ if (seenCommands.has(commandLine))
122
+ continue;
123
+ seenCommands.add(commandLine);
124
+ spinner.update(`Applying fix ${i + 1}/${total}: ${commandLine}`);
116
125
  const run = await runCommand(commandParts[0], commandParts.slice(1), params.projectPath, params.debugLog);
117
126
  if (run.error) {
118
127
  spinner.fail("Failed to apply fixes");
@@ -133,6 +142,8 @@ export async function applyFixesIfRequested(params) {
133
142
  package: target.package,
134
143
  from: target.currentVersion ?? "unknown",
135
144
  to: target.targetVersion,
145
+ ...(target.childPackage ? { childPackage: target.childPackage } : {}),
146
+ ...(target.childTargetVersion ? { childTargetVersion: target.childTargetVersion } : {}),
136
147
  })),
137
148
  note: null,
138
149
  };
@@ -148,7 +159,9 @@ export function printFixModeSummary(params) {
148
159
  console.log("");
149
160
  console.log(chalk.bold.cyan("Applied fixes"));
150
161
  for (const item of result.applied) {
151
- console.log(`- ${chalk.white(item.package)}: ${chalk.gray(item.from)} ${chalk.cyan("->")} ${chalk.green(item.to)}`);
162
+ const childNote = formatParentUpdateChildNote(item);
163
+ const line = `- ${chalk.white(item.package)}: ${chalk.gray(item.from)} ${chalk.cyan("->")} ${chalk.green(item.to)}`;
164
+ console.log(childNote ? `${line} (${childNote})` : line);
152
165
  }
153
166
  }
154
167
  console.log("");
@@ -1,3 +1,4 @@
1
+ import semver from "semver";
1
2
  export function looksLikeVersion(value) {
2
3
  return /^[0-9]+\.[0-9]+\.[0-9]+(?:[-+][^/]+)?$/.test(value);
3
4
  }
@@ -172,101 +173,81 @@ export function coerceVersion(input) {
172
173
  return `${major}.${minor}.${patch}`;
173
174
  }
174
175
  /**
175
- * Does the string parse as a version range cve-lite recognises?
176
- * Supports plain versions and the operators `^`, `~`, `>=`, `<=`, `>`, `<`, `=`.
177
- * Does not support OR (`||`) or hyphen ranges (`1.0.0 - 2.0.0`) - if those
178
- * surface in real projects, extend later.
176
+ * Does the string parse as a version range?
177
+ *
178
+ * Delegates to semver so the full grammar is accepted: comparators, compound
179
+ * (`>=1.2.3 <2`), unions (`^1 || ^2`), wildcards (`1.x`), hyphen ranges and
180
+ * partials. The previous hand-rolled regex accepted a single comparator only,
181
+ * so every bounded range read as invalid. OA002 treats "not a valid range" as
182
+ * a floating tag, which made correct bounded overrides look like `latest`
183
+ * (#1216).
184
+ *
185
+ * Empty input stays `false`: callers treat the empty string as a floating tag,
186
+ * whereas semver reads it as `*`.
187
+ */
188
+ /**
189
+ * Normalize a version as it appears in an OSV advisory event to `X.Y.Z`.
190
+ *
191
+ * Advisories declare fix and introduced boundaries as exact versions, and those
192
+ * are routinely written with fewer than three components: `fixed: "1.22"` means
193
+ * 1.22.0. `looksLikeVersion` demands a strict `X.Y.Z`, so `collectAdvisoryFixes`
194
+ * discarded such an event and the finding then reported "no fix available",
195
+ * which is an instruction to stop looking (#1192).
196
+ *
197
+ * Deliberately a strict whole-string match rather than `semver.coerce`. Coercion
198
+ * reads leading digits out of anything, so a GIT range's commit hash becomes a
199
+ * plausible version:
200
+ *
201
+ * semver.coerce("74ea7cf4d1b1...") -> "74.0.0"
202
+ *
203
+ * which is the defect in #1191 rather than a fix for it. Anything this cannot
204
+ * read in full is rejected, so a non-version boundary never reaches a
205
+ * comparison.
206
+ *
207
+ * Note this is for ADVISORY versions only. It must not be used on manifest or
208
+ * override specs, where a bare `1.22` is the range `1.22.x` rather than 1.22.0.
179
209
  */
210
+ const ADVISORY_VERSION = /^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?(-[0-9A-Za-z.-]+)?(\+[0-9A-Za-z.-]+)?$/;
211
+ export function normalizeAdvisoryVersion(value) {
212
+ if (!value)
213
+ return null;
214
+ const match = ADVISORY_VERSION.exec(value.trim());
215
+ if (!match)
216
+ return null;
217
+ const [, major, minor = "0", patch = "0", prerelease = "", build = ""] = match;
218
+ return `${major}.${minor}.${patch}${prerelease}${build}`;
219
+ }
180
220
  export function isValidRange(input) {
181
- if (!input)
221
+ if (!input || !input.trim())
182
222
  return false;
183
- const trimmed = input.trim();
184
- if (!/^(?:\^|~|>=|<=|>|<|=)?\s*\d+(?:\.\d+)?(?:\.\d+)?(?:[-+][^\s]+)?$/.test(trimmed)) {
185
- return false;
186
- }
187
- return coerceVersion(trimmed) !== null;
223
+ return semver.validRange(input.trim(), { loose: true }) !== null;
188
224
  }
189
225
  /**
190
- * Does `version` satisfy `range`? Minimal subset of semver semantics covering
191
- * what the OA detectors need: exact, `^`, `~`, `>=`, `<=`, `>`, `<`, `=`.
226
+ * Does `version` satisfy `range`?
192
227
  *
193
- * Pre-releases follow semver convention: a pre-release version (e.g.
194
- * "1.2.3-beta") satisfies a range only if the range explicitly mentions a
195
- * pre-release component at the same major.minor.patch boundary.
228
+ * `includePrerelease` is deliberate. A pre-release install must still match an
229
+ * advisory range that covers it, otherwise a vulnerable `1.2.3-beta.1` is
230
+ * cleared by a `<1.2.3` advisory. That is the defect v1.34.0 fixed on the OSV
231
+ * path, and it survived here because the old implementation ran the version
232
+ * through `coerceVersion` first, which strips the pre-release tag and made the
233
+ * beta compare equal to the release.
234
+ *
235
+ * Messy inputs (`v1.2.3`, `2.0`) fall back to `coerceVersion`, which is kept
236
+ * for exactly that: lockfiles and manifests carry version strings semver will
237
+ * not parse.
196
238
  */
197
239
  export function satisfiesRange(version, range) {
198
- const v = coerceVersion(version);
199
- if (!v)
240
+ if (!version || !range)
241
+ return false;
242
+ const parsed = semver.parse(version.trim(), { loose: true });
243
+ const normalizedVersion = parsed ? parsed.version : coerceVersion(version);
244
+ if (!normalizedVersion)
200
245
  return false;
201
246
  const trimmedRange = range.trim();
202
- // Compound range: space-separated comparators are ANDed, so `>=5.7.0 <6`
203
- // means both. Operators may carry a space before their operand (`>= 5.7.0`),
204
- // so glue those back on before splitting. Without this the first comparator
205
- // won and every ceiling was silently discarded, which made `>=5.7.0 <6`
206
- // accept 99.0.0.
207
- const glued = trimmedRange.replace(/([<>]=?|=|\^|~)\s+/g, "$1");
208
- if (/\s/.test(glued)) {
209
- const parts = glued.split(/\s+/).filter(Boolean);
210
- return parts.every((part) => satisfiesRange(version, part));
211
- }
212
- // Exact match (no operator)
213
- if (/^\d/.test(trimmedRange)) {
214
- return compareVersions(v, coerceVersion(trimmedRange) ?? "") === 0;
215
- }
216
- // `=` operator
217
- if (trimmedRange.startsWith("=")) {
218
- const target = coerceVersion(trimmedRange.slice(1));
219
- return target !== null && compareVersions(v, target) === 0;
220
- }
221
- // `^` caret: >= floor, ceiling at the leftmost non-zero component of the
222
- // target (npm: ^1.2.0 -> <2.0.0; ^0.2.3 -> <0.3.0; ^0.0.3 -> <0.0.4).
223
- // Partial ranges keep their component count: ^0 admits all 0.x, ^0.0 admits 0.0.x.
224
- if (trimmedRange.startsWith("^")) {
225
- const target = coerceVersion(trimmedRange.slice(1));
226
- if (!target)
227
- return false;
228
- if (compareVersions(v, target) < 0)
229
- return false;
230
- const [vMaj, vMin, vPatch] = v.split(".").map(Number);
231
- const [tMaj, tMin, tPatch] = target.split(".").map(Number);
232
- const parts = trimmedRange.slice(1).split("-")[0].split(".");
233
- if (tMaj > 0)
234
- return vMaj === tMaj; // ^1, ^1.2, ^1.2.3
235
- if (tMin > 0)
236
- return vMaj === tMaj && vMin === tMin; // ^0.1, ^0.1.x
237
- if (parts.length >= 3)
238
- return vMaj === tMaj && vMin === tMin && vPatch === tPatch; // ^0.0.3 exact
239
- if (parts.length === 2)
240
- return vMaj === tMaj && vMin === tMin; // ^0.0 -> 0.0.x
241
- return vMaj === tMaj; // ^0 -> all 0.x
242
- }
243
- // `~` tilde: same major.minor, >= specified
244
- if (trimmedRange.startsWith("~")) {
245
- const target = coerceVersion(trimmedRange.slice(1));
246
- if (!target)
247
- return false;
248
- if (compareVersions(v, target) < 0)
249
- return false;
250
- const [vMaj, vMin] = v.split(".").map(Number);
251
- const [tMaj, tMin] = target.split(".").map(Number);
252
- return vMaj === tMaj && vMin === tMin;
253
- }
254
- // Comparators
255
- for (const op of [">=", "<=", ">", "<"]) {
256
- if (trimmedRange.startsWith(op)) {
257
- const target = coerceVersion(trimmedRange.slice(op.length));
258
- if (!target)
259
- return false;
260
- const cmp = compareVersions(v, target);
261
- if (op === ">=")
262
- return cmp >= 0;
263
- if (op === "<=")
264
- return cmp <= 0;
265
- if (op === ">")
266
- return cmp > 0;
267
- if (op === "<")
268
- return cmp < 0;
269
- }
270
- }
271
- return false;
247
+ if (!semver.validRange(trimmedRange, { loose: true }))
248
+ return false;
249
+ return semver.satisfies(normalizedVersion, trimmedRange, {
250
+ loose: true,
251
+ includePrerelease: true,
252
+ });
272
253
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cve-lite-cli",
3
- "version": "1.36.1",
3
+ "version": "1.37.0",
4
4
  "description": "Developer-friendly CLI for scanning JS/TS projects for dependency vulnerabilities using local lockfiles and OSV",
5
5
  "type": "module",
6
6
  "bin": {
@@ -21,6 +21,7 @@
21
21
  "dependencies": {
22
22
  "better-sqlite3": "^12.8.0",
23
23
  "fflate": "^0.8.3",
24
+ "semver": "^7.8.5",
24
25
  "yaml": "^2.7.1",
25
26
  "yarn-lockfile": "^1.1.0"
26
27
  },
@@ -28,6 +29,7 @@
28
29
  "@types/better-sqlite3": "^7.6.13",
29
30
  "@types/jest": "^30.0.0",
30
31
  "@types/node": "^24.0.0",
32
+ "@types/semver": "^7.8.0",
31
33
  "jest": "^30.4.2",
32
34
  "ts-jest": "^29.4.9",
33
35
  "tsx": "^4.22.0",
@@ -208,10 +208,13 @@ function countPhrase(rows, { adjective } = {}) {
208
208
  }
209
209
 
210
210
  /**
211
- * "GHSA-xxx (CVE-2026-84375)", capped. A single package can carry dozens of
212
- * advisories (tar@6.1.0 has 36), and listing them all produces a line nobody
213
- * can read. CVEs are shown in preference to GHSA ids because they are what a
214
- * reviewer recognises.
211
+ * "CVE-2026-84375", or the GHSA id when the finding carries no CVE alias.
212
+ *
213
+ * Capped, because a single package can carry dozens of advisories (tar@6.1.0
214
+ * has 36) and listing them all produces a line nobody can read. CVEs are shown
215
+ * in preference to GHSA ids, not alongside them, because they are what a
216
+ * reviewer recognises. That does mean this comment and the CLI's own findings
217
+ * table can name the same advisory differently.
215
218
  */
216
219
  const MAX_IDS = 3;
217
220