cve-lite-cli 1.26.0 → 1.28.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 (43) hide show
  1. package/README.md +147 -398
  2. package/dist/advisory/osv-advisory-source.js +5 -3
  3. package/dist/cli/advisories-init.js +24 -0
  4. package/dist/cli/args.js +36 -0
  5. package/dist/cli/help.js +9 -5
  6. package/dist/cli/overrides.js +20 -16
  7. package/dist/constants.js +1 -0
  8. package/dist/index.js +61 -39
  9. package/dist/maintenance/dm001-maintenance-risk.js +63 -0
  10. package/dist/maintenance/types.js +1 -0
  11. package/dist/osv/cache.js +49 -50
  12. package/dist/output/debug.js +2 -1
  13. package/dist/output/formatters.js +17 -3
  14. package/dist/output/html-reporter.js +156 -102
  15. package/dist/output/logos.js +1 -1
  16. package/dist/output/maintenance-findings-html.js +56 -0
  17. package/dist/output/maintenance-findings-json.js +3 -0
  18. package/dist/output/maintenance-terminal.js +80 -0
  19. package/dist/output/override-findings-html.js +24 -28
  20. package/dist/output/override-findings-sarif.js +34 -24
  21. package/dist/output/override-findings-terminal.js +19 -2
  22. package/dist/output/printers.js +19 -6
  23. package/dist/output/sarif.js +14 -6
  24. package/dist/output/spinner.js +5 -0
  25. package/dist/output/write-outputs.js +3 -1
  26. package/dist/overrides/context-builder.js +29 -0
  27. package/dist/overrides/detectors/index.js +6 -0
  28. package/dist/overrides/detectors/oa009-stale-floor.js +80 -0
  29. package/dist/overrides/detectors/pd001-override-only-phantom.js +32 -0
  30. package/dist/overrides/detectors/pd002-transitive-only-phantom.js +34 -0
  31. package/dist/overrides/detectors/phantom-utils.js +21 -0
  32. package/dist/overrides/fixer.js +21 -1
  33. package/dist/remediation/cooldown.js +74 -0
  34. package/dist/remediation/fix-commands.js +42 -2
  35. package/dist/remediation/npm-registry.js +11 -0
  36. package/dist/remediation/parent-upgrade.js +114 -18
  37. package/dist/scan/multi-folder-scan.js +35 -10
  38. package/dist/scanner.js +86 -22
  39. package/dist/usage/scanner.js +60 -1
  40. package/dist/utils/network.js +77 -0
  41. package/dist/utils/sarif.js +4 -0
  42. package/dist/utils/severity.js +6 -0
  43. package/package.json +2 -1
@@ -1,3 +1,4 @@
1
+ import { relative } from "node:path";
1
2
  import { SEVERITY_ORDER } from "../utils/severity.js";
2
3
  function esc(s) {
3
4
  return s
@@ -6,7 +7,7 @@ function esc(s) {
6
7
  .replace(/>/g, ">")
7
8
  .replace(/"/g, """);
8
9
  }
9
- export function renderOverrideFindingsHtml(findings) {
10
+ export function renderOverrideFindingsHtml(findings, projectPath) {
10
11
  // undefined = override hygiene was never requested -> render nothing, so a plain
11
12
  // `cve-lite .` report shows no Override hygiene panel at all. An empty array =
12
13
  // it ran and found nothing -> render the "no findings" reassurance.
@@ -21,38 +22,33 @@ export function renderOverrideFindingsHtml(findings) {
21
22
  </section>
22
23
  `;
23
24
  }
24
- const grouped = new Map();
25
- for (const sev of SEVERITY_ORDER)
26
- grouped.set(sev, []);
27
- for (const f of findings)
28
- grouped.get(f.severity)?.push(f);
29
- const rows = [];
30
- for (const sev of SEVERITY_ORDER) {
31
- const bucket = grouped.get(sev) ?? [];
32
- if (bucket.length === 0)
33
- continue;
34
- rows.push(` <tr class="severity-group ${esc(sev)}"><th>${esc(sev.toUpperCase())} (${bucket.length})</th><td></td><td></td><td></td></tr>`);
35
- for (const f of bucket) {
36
- const location = f.location.jsonPath
37
- ? `${esc(f.location.file)} › ${esc(f.location.jsonPath)}`
38
- : esc(f.location.file);
39
- const fixHtml = f.fix?.runnableCommand
40
- ? `<div class="fix-cmd-inline" style="margin-top:6px"><code>${esc(f.fix.runnableCommand)}</code><button class="copy-btn" data-cmd="${esc(f.fix.runnableCommand)}">Copy</button></div>`
41
- : "";
42
- rows.push(` <tr class="finding ${esc(f.severity)}">` +
43
- `<td>${esc(f.ruleId)}</td>` +
44
- `<td>${esc(f.package.name)}</td>` +
45
- `<td>${location}</td>` +
46
- `<td>${esc(f.message)}${fixHtml}</td>` +
47
- `</tr>`);
48
- }
49
- }
25
+ const sorted = [...findings].sort((a, b) => SEVERITY_ORDER.indexOf(a.severity) - SEVERITY_ORDER.indexOf(b.severity));
26
+ const rows = sorted.map(f => {
27
+ const location = f.location.jsonPath
28
+ ? `${esc(f.location.file)} › ${esc(f.location.jsonPath)}`
29
+ : esc(f.location.file);
30
+ const relPath = projectPath ? relative(process.cwd(), projectPath) : "";
31
+ const projectInfix = relPath && relPath !== "." ? ` ${relPath}` : "";
32
+ const runnableCmd = f.fix?.runnableCommand && projectInfix
33
+ ? f.fix.runnableCommand.replace("cve-lite overrides", `cve-lite${projectInfix} overrides`)
34
+ : f.fix?.runnableCommand;
35
+ const fixHtml = runnableCmd
36
+ ? `<div class="fix-cmd-inline" style="margin-top:6px"><code>${esc(runnableCmd)}</code><button class="copy-btn" data-cmd="${esc(runnableCmd)}">Copy</button></div>`
37
+ : "";
38
+ return (` <tr class="finding ${esc(f.severity)}">` +
39
+ `<td><span class="dep-node">${esc(f.ruleId)}</span></td>` +
40
+ `<td><div class="pkg-name">${esc(f.package.name)}</div></td>` +
41
+ `<td><span class="sev-badge ${esc(f.severity)}">${esc(f.severity)}</span></td>` +
42
+ `<td>${location}</td>` +
43
+ `<td>${esc(f.message)}${fixHtml}</td>` +
44
+ `</tr>`);
45
+ });
50
46
  return `
51
47
  <section class="override-hygiene">
52
48
  <h2>Override hygiene</h2>
53
49
  <table>
54
50
  <thead>
55
- <tr><th>Rule</th><th>Package</th><th>Location</th><th>Message</th></tr>
51
+ <tr><th>Rule</th><th>Package</th><th>Severity</th><th>Location</th><th>Message</th></tr>
56
52
  </thead>
57
53
  <tbody>
58
54
  ${rows.join("\n")}
@@ -1,4 +1,6 @@
1
1
  import { getCliVersion } from "../utils/version-info.js";
2
+ import { severityToSarifLevel } from "../utils/severity.js";
3
+ import { sarifFingerprintHash } from "../utils/sarif.js";
2
4
  const OA_RULES = [
3
5
  { id: "OA001", name: "OrphanedTarget", shortDescription: "Override target not in resolved tree", helpUri: "https://github.com/OWASP/cve-lite-cli/blob/main/docs/rules/OA001.md" },
4
6
  { id: "OA002", name: "FloatingTag", shortDescription: "Override pins to a moving tag", helpUri: "https://github.com/OWASP/cve-lite-cli/blob/main/docs/rules/OA002.md" },
@@ -8,14 +10,11 @@ const OA_RULES = [
8
10
  { id: "OA006", name: "CoupledPlatformBinary", shortDescription: "Override fights exact-pinned parent", helpUri: "https://github.com/OWASP/cve-lite-cli/blob/main/docs/rules/OA006.md" },
9
11
  { id: "OA007", name: "FrozenLatest", shortDescription: "\"latest\" tag has moved", helpUri: "https://github.com/OWASP/cve-lite-cli/blob/main/docs/rules/OA007.md" },
10
12
  { id: "OA008", name: "MaterializedVulnerable", shortDescription: "Vulnerable copy still on disk", helpUri: "https://github.com/OWASP/cve-lite-cli/blob/main/docs/rules/OA008.md" },
13
+ { id: "OA009", name: "StaleFloor", shortDescription: "Override floor already met by all parent declarations", helpUri: "https://github.com/OWASP/cve-lite-cli/blob/main/docs/rules/OA009.md" },
14
+ { id: "PD001", name: "OverrideOnlyPhantom", shortDescription: "Package imported in source but only present via override pin - declare it as a dependency", helpUri: "https://github.com/OWASP/cve-lite-cli/blob/main/docs/rules/PD001.md" },
15
+ { id: "PD002", name: "TransitiveOnlyPhantom", shortDescription: "Package imported in source but only present as a transitive dependency - declare it explicitly", helpUri: "https://github.com/OWASP/cve-lite-cli/blob/main/docs/rules/PD002.md" },
11
16
  ];
12
- const SEVERITY_TO_LEVEL = {
13
- critical: "error",
14
- high: "error",
15
- medium: "warning",
16
- low: "note",
17
- info: "note",
18
- };
17
+ const OA_RULE_INDEX = new Map(OA_RULES.map((r, i) => [r.id, i]));
19
18
  export function buildOverrideSarifComponent() {
20
19
  return {
21
20
  name: "cve-lite-cli-overrides",
@@ -30,23 +29,34 @@ export function buildOverrideSarifComponent() {
30
29
  };
31
30
  }
32
31
  export function buildOverrideSarifResults(findings) {
33
- return findings.map((f) => ({
34
- ruleId: f.ruleId,
35
- rule: { id: f.ruleId, toolComponent: { index: 0 } },
36
- level: SEVERITY_TO_LEVEL[f.severity] ?? "warning",
37
- message: { text: f.message },
38
- locations: [
39
- {
40
- physicalLocation: {
41
- artifactLocation: { uri: f.location.file, uriBaseId: "%SRCROOT%" },
42
- region: { startLine: f.location.line ?? 1 },
32
+ return findings.map((f) => {
33
+ const ruleIndex = OA_RULE_INDEX.get(f.ruleId);
34
+ if (ruleIndex === undefined) {
35
+ throw new Error(`OA_RULE_INDEX: unknown ruleId "${f.ruleId}" - add it to OA_RULES`);
36
+ }
37
+ return {
38
+ ruleId: f.ruleId,
39
+ ruleIndex,
40
+ rule: { id: f.ruleId, toolComponent: { index: 0 } },
41
+ kind: "open",
42
+ level: severityToSarifLevel(f.severity),
43
+ message: { text: f.message },
44
+ locations: [
45
+ {
46
+ physicalLocation: {
47
+ artifactLocation: { uri: f.location.file, uriBaseId: "%SRCROOT%" },
48
+ region: { startLine: f.location.line ?? 1 },
49
+ },
43
50
  },
51
+ ],
52
+ partialFingerprints: {
53
+ primaryLocationLineHash: sarifFingerprintHash(`${f.ruleId}:${f.package.name}:${f.location.file}`),
44
54
  },
45
- ],
46
- properties: {
47
- package: f.package.name,
48
- jsonPath: f.location.jsonPath,
49
- severity: f.severity,
50
- },
51
- }));
55
+ properties: {
56
+ package: f.package.name,
57
+ jsonPath: f.location.jsonPath,
58
+ severity: f.severity,
59
+ },
60
+ };
61
+ });
52
62
  }
@@ -1,3 +1,4 @@
1
+ import { relative } from "node:path";
1
2
  import { chalk, stripAnsi } from "../utils/chalk.js";
2
3
  import { formatSeverityLabel, SEVERITY_ORDER } from "../utils/severity.js";
3
4
  import { pluralize } from "../utils/string.js";
@@ -6,7 +7,6 @@ const COL_PKG_MAX = 30;
6
7
  const COL_MSG_MAX = 50;
7
8
  export function renderOverrideFindings(findings, options) {
8
9
  const lines = [];
9
- lines.push("");
10
10
  if (options?.verbose) {
11
11
  lines.push(chalk.bold.cyan("🔍 Override Hygiene"));
12
12
  }
@@ -53,15 +53,32 @@ export function renderOverrideFindings(findings, options) {
53
53
  lines.push(hr("├", "┼", "┤"));
54
54
  }
55
55
  lines.push(hr("└", "┴", "┘"));
56
+ const relPath = options?.projectPath
57
+ ? relative(process.cwd(), options.projectPath)
58
+ : "";
59
+ const projectInfix = relPath && relPath !== "." ? ` ${relPath}` : "";
56
60
  const seenRules = new Set();
57
61
  for (const f of sorted) {
58
62
  if (f.fix?.runnableCommand && !seenRules.has(f.ruleId)) {
59
63
  seenRules.add(f.ruleId);
60
- lines.push(chalk.bold.cyan(`> ${f.fix.runnableCommand}`));
64
+ const cmd = projectInfix
65
+ ? f.fix.runnableCommand.replace("cve-lite overrides", `cve-lite${projectInfix} overrides`)
66
+ : f.fix.runnableCommand;
67
+ lines.push(chalk.bold.cyan(`> ${cmd}`));
61
68
  }
62
69
  }
63
70
  lines.push("");
64
71
  }
72
+ const relPath = options?.projectPath
73
+ ? relative(process.cwd(), options.projectPath)
74
+ : "";
75
+ const projectInfix = relPath && relPath !== "." ? ` ${relPath}` : "";
76
+ const allFixableRules = new Set(findings.filter(f => f.fix?.runnableCommand).map(f => f.ruleId));
77
+ if (allFixableRules.size >= 2) {
78
+ const fixAllCmd = `cve-lite${projectInfix} overrides --fix`;
79
+ lines.push("💡 " + chalk.gray(`Tip: run ${fixAllCmd} to apply all auto-fixable fixes in one shot.`));
80
+ lines.push("");
81
+ }
65
82
  const worstSev = SEVERITY_ORDER.find(s => (grouped.get(s) ?? []).length > 0);
66
83
  const footerColor = worstSev === "critical" || worstSev === "high" ? chalk.redBright : chalk.yellow;
67
84
  lines.push(footerColor(`${findings.length} override hygiene ${pluralize(findings.length, "issue")} found.`));
@@ -1,8 +1,8 @@
1
1
  import { chalk, stripAnsi } from "../utils/chalk.js";
2
- import { buildSuggestedFixCommandPlan } from "../remediation/fix-commands.js";
2
+ import { buildSuggestedFixCommandPlan, UNVERIFIED_PARENT_UPGRADE_NOTE } from "../remediation/fix-commands.js";
3
3
  import { isMajorVersionBump } from "../utils/version.js";
4
4
  import { getPrimaryParent } from "../utils/finding.js";
5
- import { countUniqueAdvisories, formatRelationshipLabel, formatRelLabel, formatFixCommandWithPublishDates, } from "./formatters.js";
5
+ import { countUniqueAdvisories, formatRelationshipLabel, formatRelLabel, formatFixCommandWithPublishDates, formatCooldownWarning, } from "./formatters.js";
6
6
  import { formatSeverityLabel } from "../utils/severity.js";
7
7
  import { pluralize } from "../utils/string.js";
8
8
  import { selectFindingsForCompact } from "./finding-display.js";
@@ -56,6 +56,16 @@ export function printActionSummary(findings, overrideCount = 0, packageManager)
56
56
  console.log(`- ${chalk.yellow(String(overrideCount))} override hygiene ${pluralize(overrideCount, "issue")} found. Run ${chalk.white("cve-lite overrides --fix")} to address ${pluralize(overrideCount, "it", "them")}.`);
57
57
  }
58
58
  }
59
+ function printCooldownWarning(target) {
60
+ if (target.cooldownWarning) {
61
+ console.log(chalk.yellow(` ⚠ ${formatCooldownWarning(target.cooldownWarning)}`));
62
+ }
63
+ }
64
+ function printUnverifiedParentUpgradeWarning(target) {
65
+ if (target.confidence === "unverified") {
66
+ console.log(chalk.yellow(` ${UNVERIFIED_PARENT_UPGRADE_NOTE}`));
67
+ }
68
+ }
59
69
  function printChainProofLines(targets) {
60
70
  for (const target of targets) {
61
71
  if (!target.chainProof || !target.chainSafeVersion)
@@ -112,6 +122,10 @@ export function printSuggestedFixCommands(findings, scanInput, options) {
112
122
  else if (shouldRenderParentUpgradeTable(section.targets)) {
113
123
  printParentUpgradeTargetsTable(section.targets, sharedParentUpgradeTableWidths);
114
124
  }
125
+ for (const target of section.targets) {
126
+ printCooldownWarning(target);
127
+ printUnverifiedParentUpgradeWarning(target);
128
+ }
115
129
  console.log(renderCommandCallout(section.command, section.targets));
116
130
  printChainProofLines(section.targets);
117
131
  }
@@ -446,12 +460,11 @@ export function printCompactOutput(findings, scanInput, options) {
446
460
  console.log("");
447
461
  for (const section of plan.sections.slice(0, 3)) {
448
462
  console.log(`${section.title}`);
449
- if (section.kind === "direct-adjusted") {
450
- for (const target of section.targets) {
451
- if (!target.adjustmentNote)
452
- continue;
463
+ for (const target of section.targets) {
464
+ if (section.kind === "direct-adjusted" && target.adjustmentNote) {
453
465
  console.log(chalk.gray(` Note: ${target.adjustmentNote}`));
454
466
  }
467
+ printCooldownWarning(target);
455
468
  }
456
469
  console.log(renderCommandCallout(section.command, section.targets));
457
470
  printChainProofLines(section.targets);
@@ -3,7 +3,9 @@ import path from "node:path";
3
3
  import { getRecommendedAction } from "./formatters.js";
4
4
  import { getCliVersion } from "../utils/version-info.js";
5
5
  import { severityToSarifLevel } from "../utils/severity.js";
6
+ import { sarifFingerprintHash } from "../utils/sarif.js";
6
7
  import { buildOverrideSarifComponent, buildOverrideSarifResults } from "./override-findings-sarif.js";
8
+ const SARIF_SCHEMA = "https://docs.oasis-open.org/sarif/sarif/v2.1.0/errata01/os/schemas/sarif-schema-2.1.0.json";
7
9
  const LOCKFILE_NAMES = {
8
10
  "package-lock": "package-lock.json",
9
11
  "npm-shrinkwrap": "npm-shrinkwrap.json",
@@ -75,6 +77,7 @@ export function deriveLockfileUri(scanInput) {
75
77
  }
76
78
  export function buildSarifOutput(findings, lockfileUri, version, _plan, overrideFindings) {
77
79
  const ruleMap = new Map();
80
+ const ruleIndexMap = new Map();
78
81
  const results = [];
79
82
  for (const finding of findings) {
80
83
  const level = severityToSarifLevel(finding.severity);
@@ -90,6 +93,8 @@ export function buildSarifOutput(findings, lockfileUri, version, _plan, override
90
93
  : finding.vulnerabilities.map(v => v.id);
91
94
  for (const ruleId of ruleIds) {
92
95
  if (!ruleMap.has(ruleId)) {
96
+ // ruleMap.size before insertion = 0-based index of the new entry
97
+ ruleIndexMap.set(ruleId, ruleMap.size);
93
98
  const vuln = findVulnForRuleId(ruleId, finding.vulnerabilities);
94
99
  const summary = vuln?.summary;
95
100
  const details = vuln?.details;
@@ -102,29 +107,32 @@ export function buildSarifOutput(findings, lockfileUri, version, _plan, override
102
107
  fullDescription: { text: details ?? summary ?? `Vulnerable dependency: ${ruleId}` },
103
108
  ...(help !== undefined ? { help } : {}),
104
109
  helpUri: `https://osv.dev/vulnerability/${ruleId}`,
105
- defaultConfiguration: { level },
106
110
  properties: { tags: ["security", "dependency"] },
107
111
  });
108
112
  }
109
113
  results.push({
110
114
  ruleId,
115
+ ruleIndex: ruleIndexMap.get(ruleId),
116
+ kind: "open",
111
117
  level,
112
118
  message: {
113
119
  text: `${finding.pkg.name}@${finding.pkg.version} is vulnerable (${finding.severity}). ${action}`,
114
120
  },
115
121
  locations: [location],
122
+ partialFingerprints: {
123
+ primaryLocationLineHash: sarifFingerprintHash(`${ruleId}:${finding.pkg.name}@${finding.pkg.version}`),
124
+ },
116
125
  });
117
126
  }
118
127
  }
119
- const extensions = overrideFindings && overrideFindings.length > 0
120
- ? [buildOverrideSarifComponent()]
121
- : undefined;
128
+ const hasOverrides = overrideFindings != null && overrideFindings.length > 0;
129
+ const extensions = hasOverrides ? [buildOverrideSarifComponent()] : undefined;
122
130
  const allResults = [
123
131
  ...results,
124
- ...(overrideFindings ? buildOverrideSarifResults(overrideFindings) : []),
132
+ ...(hasOverrides ? buildOverrideSarifResults(overrideFindings) : []),
125
133
  ];
126
134
  return {
127
- $schema: "https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/Schemata/sarif-schema-2.1.0.json",
135
+ $schema: SARIF_SCHEMA,
128
136
  version: "2.1.0",
129
137
  runs: [
130
138
  {
@@ -7,6 +7,7 @@ export function createSpinner(initialMessage, options) {
7
7
  update: () => { },
8
8
  succeed: () => { },
9
9
  fail: () => { },
10
+ warn: () => { },
10
11
  stop: () => { }
11
12
  };
12
13
  }
@@ -36,6 +37,10 @@ export function createSpinner(initialMessage, options) {
36
37
  clearLine();
37
38
  console.log(chalk.red(`✗ ${message}`));
38
39
  },
40
+ warn(message) {
41
+ clearLine();
42
+ console.log(chalk.yellow(`⚠ ${message}`));
43
+ },
39
44
  stop() {
40
45
  clearLine();
41
46
  }
@@ -5,6 +5,7 @@ import { serializeFinding } from "./formatters.js";
5
5
  import { writeSarifReport, deriveLockfileUri } from "./sarif.js";
6
6
  import { writeCycloneDxReport } from "./cyclonedx.js";
7
7
  import { overrideFindingsToJson } from "./override-findings-json.js";
8
+ import { maintenanceFindingsToJson } from "./maintenance-findings-json.js";
8
9
  function readProjectMeta(projectPath) {
9
10
  try {
10
11
  const pkgPath = path.join(projectPath, "package.json");
@@ -41,7 +42,8 @@ export async function writeOutputs(options, scanState, scanInput, projectPath) {
41
42
  findings: scanState.sorted.map(finding => serializeFinding(finding, scanState.suggestedFixCommands)),
42
43
  };
43
44
  const overridePayload = overrideFindingsToJson(scanState.overrideFindings ?? []);
44
- const combined = { ...payload, ...overridePayload };
45
+ const maintenancePayload = maintenanceFindingsToJson(scanState.maintenanceFindings ?? []);
46
+ const combined = { ...payload, ...overridePayload, ...maintenancePayload };
45
47
  fs.writeFileSync(jsonOutputPath, JSON.stringify(combined, null, 2));
46
48
  console.log(`${chalk.gray("JSON saved to")} ${chalk.cyan(jsonFilename)}`);
47
49
  }
@@ -6,6 +6,7 @@ import { loadFromPackageLock } from "../parsers/package-lock.js";
6
6
  import { loadFromPnpmLock } from "../parsers/pnpm-lock.js";
7
7
  import { loadFromYarnLock } from "../parsers/yarn-lock.js";
8
8
  import { loadFromBunLock } from "../parsers/bun-lock.js";
9
+ import { scanAllImports } from "../usage/scanner.js";
9
10
  export function buildOverrideContext(projectPath, opts) {
10
11
  const pkgJsonPath = join(projectPath, "package.json");
11
12
  if (!existsSync(pkgJsonPath)) {
@@ -32,6 +33,7 @@ export function buildOverrideContext(projectPath, opts) {
32
33
  skipped.push({ ruleId: "OA004", reason: "node_modules missing" });
33
34
  skipped.push({ ruleId: "OA006", reason: "node_modules missing" });
34
35
  skipped.push({ ruleId: "OA008", reason: "node_modules missing" });
36
+ skipped.push({ ruleId: "OA009", reason: "node_modules missing" });
35
37
  }
36
38
  // installedVersions: top-level node_modules/<name>/package.json reads.
37
39
  const installedVersions = new Map();
@@ -52,8 +54,13 @@ export function buildOverrideContext(projectPath, opts) {
52
54
  const tree = nodeModulesExists
53
55
  ? walkInstalledTree(projectPath)
54
56
  : { installedCopies: new Map(), parentDeclarations: new Map() };
57
+ // Seed parentDeclarations with the root project's own dep fields so OA009 can
58
+ // detect stale floors when the root project is the sole consumer of a package.
59
+ // walkInstalledTree only reads node_modules manifests; it never sees the root.
60
+ seedRootDeclarations(parsed, tree.parentDeclarations);
55
61
  // OA007 registry: only when --check-network. Empty otherwise.
56
62
  const registryDistTags = new Map();
63
+ const importedPackageNames = scanAllImports(projectPath);
57
64
  return {
58
65
  projectPath,
59
66
  packageJson: parsed,
@@ -66,6 +73,7 @@ export function buildOverrideContext(projectPath, opts) {
66
73
  parentDeclarations: tree.parentDeclarations,
67
74
  registryDistTags,
68
75
  skippedDetectors: skipped,
76
+ importedPackageNames,
69
77
  auditLog: opts.auditLog,
70
78
  logger: opts.logger,
71
79
  };
@@ -136,6 +144,27 @@ function readLockfileNames(projectPath, pm) {
136
144
  }
137
145
  return { kind: "absent" };
138
146
  }
147
+ function seedRootDeclarations(pkg, parentDeclarations) {
148
+ const rootName = typeof pkg.name === "string" ? pkg.name : "<root>";
149
+ const rootVersion = typeof pkg.version === "string" ? pkg.version : "0.0.0";
150
+ const sections = [
151
+ { deps: pkg.dependencies, declaredIn: "dependencies" },
152
+ { deps: pkg.devDependencies, declaredIn: "dependencies" },
153
+ { deps: pkg.optionalDependencies, declaredIn: "optionalDependencies" },
154
+ { deps: pkg.peerDependencies, declaredIn: "peerDependencies" },
155
+ ];
156
+ for (const { deps, declaredIn } of sections) {
157
+ if (!deps || typeof deps !== "object" || Array.isArray(deps))
158
+ continue;
159
+ for (const [depName, declaredValue] of Object.entries(deps)) {
160
+ if (typeof declaredValue !== "string")
161
+ continue;
162
+ const list = parentDeclarations.get(depName) ?? [];
163
+ list.push({ parentName: rootName, parentVersion: rootVersion, declaredIn, declaredValue, exactVersion: false });
164
+ parentDeclarations.set(depName, list);
165
+ }
166
+ }
167
+ }
139
168
  function readInstalledVersionTopLevel(projectPath, name) {
140
169
  const p = join(projectPath, "node_modules", ...name.split("/"), "package.json");
141
170
  try {
@@ -6,6 +6,9 @@ import { detect as detectOA005 } from "./oa005-nested-ineffective.js";
6
6
  import { detect as detectOA006 } from "./oa006-coupled-platform-binary.js";
7
7
  import { detect as detectOA007 } from "./oa007-frozen-latest.js";
8
8
  import { detect as detectOA008 } from "./oa008-materialized.js";
9
+ import { detect as detectOA009 } from "./oa009-stale-floor.js";
10
+ import { detect as detectPD001 } from "./pd001-override-only-phantom.js";
11
+ import { detect as detectPD002 } from "./pd002-transitive-only-phantom.js";
9
12
  export const ALL_DETECTORS = [
10
13
  { ruleId: "OA001", detect: detectOA001 },
11
14
  { ruleId: "OA002", detect: detectOA002 },
@@ -15,6 +18,9 @@ export const ALL_DETECTORS = [
15
18
  { ruleId: "OA006", detect: detectOA006 },
16
19
  { ruleId: "OA007", detect: detectOA007 },
17
20
  { ruleId: "OA008", detect: detectOA008 },
21
+ { ruleId: "OA009", detect: detectOA009 },
22
+ { ruleId: "PD001", detect: detectPD001 },
23
+ { ruleId: "PD002", detect: detectPD002 },
18
24
  ];
19
25
  /** Verify subset - just OA001 and OA008 - for the post-fix verify path. */
20
26
  export const VERIFY_DETECTORS = [
@@ -0,0 +1,80 @@
1
+ import { jsonPointer } from "../parsing/json-pointer.js";
2
+ import { looksLikeVersion, coerceVersion, compareVersions } from "../../utils/version.js";
3
+ const RULE_ID = "OA009";
4
+ function majorOf(version) {
5
+ return parseInt(version.split(".")[0] ?? "0", 10);
6
+ }
7
+ function getDeclaredPackages(packageJson) {
8
+ const declared = new Set();
9
+ for (const section of ["dependencies", "devDependencies"]) {
10
+ const deps = packageJson[section];
11
+ if (deps && typeof deps === "object" && !Array.isArray(deps)) {
12
+ for (const name of Object.keys(deps)) {
13
+ declared.add(name);
14
+ }
15
+ }
16
+ }
17
+ return declared;
18
+ }
19
+ export function detect(ctx) {
20
+ if (ctx.skippedDetectors.some((s) => s.ruleId === RULE_ID))
21
+ return [];
22
+ const findings = [];
23
+ for (const entry of ctx.overrideEntries) {
24
+ if (typeof entry.value !== "string")
25
+ continue;
26
+ const pin = entry.value.trim();
27
+ if (looksLikeVersion(pin))
28
+ continue;
29
+ if (!pin.startsWith(">=") && !pin.startsWith("^"))
30
+ continue;
31
+ const floor = coerceVersion(pin);
32
+ if (!floor)
33
+ continue;
34
+ if (!ctx.installedVersions.has(entry.packageName))
35
+ continue;
36
+ const parents = ctx.parentDeclarations.get(entry.packageName) ?? [];
37
+ if (parents.length === 0)
38
+ continue;
39
+ const floorMajor = pin.startsWith("^") ? majorOf(floor) : -1;
40
+ const allParentsMeetFloor = parents.every((parent) => {
41
+ const parentFloor = coerceVersion(parent.declaredValue);
42
+ if (!parentFloor)
43
+ return false;
44
+ // For ^ ranges the allowed range is [floor, nextMajor). A parent in a
45
+ // different major cannot overlap, so the override is not redundant.
46
+ if (floorMajor >= 0 && majorOf(parentFloor) !== floorMajor)
47
+ return false;
48
+ return compareVersions(parentFloor, floor) >= 0;
49
+ });
50
+ if (!allParentsMeetFloor)
51
+ continue;
52
+ // Safety guard: if this package is imported in source but not declared in
53
+ // dependencies, the override is the only thing making it available. Removing
54
+ // it would create a phantom import (PD001). OA009 must not fire.
55
+ if (ctx.importedPackageNames.has(entry.packageName)) {
56
+ const declared = getDeclaredPackages(ctx.packageJson);
57
+ if (!declared.has(entry.packageName))
58
+ continue;
59
+ }
60
+ findings.push({
61
+ ruleId: RULE_ID,
62
+ severity: "low",
63
+ package: { name: entry.packageName },
64
+ location: { file: "package.json", jsonPath: jsonPointer(entry.path) },
65
+ message: "Override floor already met by all parent declarations",
66
+ details: `${entry.packageName} is floored to ${pin}, but every package that depends on it ` +
67
+ `already declares a minimum version that meets or exceeds the floor. ` +
68
+ `Removing the override is safe.`,
69
+ fix: {
70
+ type: "rfc6902",
71
+ patch: [{ op: "remove", path: jsonPointer(entry.path) }],
72
+ runnableCommand: `cve-lite overrides --fix --rule OA009`,
73
+ },
74
+ references: [
75
+ "https://github.com/OWASP/cve-lite-cli/blob/main/docs/rules/OA009.md",
76
+ ],
77
+ });
78
+ }
79
+ return findings;
80
+ }
@@ -0,0 +1,32 @@
1
+ import { getDeclaredPackages, installCmd } from "./phantom-utils.js";
2
+ const RULE_ID = "PD001";
3
+ export function detect(ctx) {
4
+ if (ctx.skippedDetectors.some((s) => s.ruleId === RULE_ID))
5
+ return [];
6
+ if (ctx.importedPackageNames.size === 0)
7
+ return [];
8
+ const declared = getDeclaredPackages(ctx.packageJson);
9
+ const overrideNames = new Set(ctx.overrideEntries.map((e) => e.packageName));
10
+ const cmd = installCmd(ctx.packageManager);
11
+ const findings = [];
12
+ for (const [pkgName, files] of ctx.importedPackageNames) {
13
+ if (declared.has(pkgName))
14
+ continue;
15
+ if (!overrideNames.has(pkgName))
16
+ continue;
17
+ const shown = files.slice(0, 3);
18
+ const extra = files.length > 3 ? ` (+${files.length - 3} more)` : "";
19
+ findings.push({
20
+ ruleId: RULE_ID,
21
+ severity: "high",
22
+ package: { name: pkgName },
23
+ location: { file: "package.json" },
24
+ message: `${pkgName} is imported in source but only present via an override pin - declare it as a dependency`,
25
+ details: `Imported in: ${shown.join(", ")}${extra}. ` +
26
+ `In pnpm strict mode (default on Vercel), override-only packages are not importable and will cause a deploy failure. ` +
27
+ `Run: ${cmd} ${pkgName}`,
28
+ references: ["https://github.com/OWASP/cve-lite-cli/blob/main/docs/rules/PD001.md"],
29
+ });
30
+ }
31
+ return findings;
32
+ }
@@ -0,0 +1,34 @@
1
+ import { getDeclaredPackages, installCmd } from "./phantom-utils.js";
2
+ const RULE_ID = "PD002";
3
+ export function detect(ctx) {
4
+ if (ctx.skippedDetectors.some((s) => s.ruleId === RULE_ID))
5
+ return [];
6
+ if (ctx.importedPackageNames.size === 0)
7
+ return [];
8
+ const declared = getDeclaredPackages(ctx.packageJson);
9
+ const overrideNames = new Set(ctx.overrideEntries.map((e) => e.packageName));
10
+ const cmd = installCmd(ctx.packageManager);
11
+ const findings = [];
12
+ for (const [pkgName, files] of ctx.importedPackageNames) {
13
+ if (declared.has(pkgName))
14
+ continue;
15
+ if (overrideNames.has(pkgName))
16
+ continue; // PD001 owns this
17
+ if (!ctx.lockfilePackageNames.has(pkgName))
18
+ continue; // not in graph
19
+ const shown = files.slice(0, 3);
20
+ const extra = files.length > 3 ? ` (+${files.length - 3} more)` : "";
21
+ findings.push({
22
+ ruleId: RULE_ID,
23
+ severity: "medium",
24
+ package: { name: pkgName },
25
+ location: { file: "package.json" },
26
+ message: `${pkgName} is imported in source but only present as a transitive dependency - declare it explicitly`,
27
+ details: `Imported in: ${shown.join(", ")}${extra}. ` +
28
+ `If the parent package drops or changes this dependency, your code will break without warning. ` +
29
+ `Run: ${cmd} ${pkgName}`,
30
+ references: ["https://github.com/OWASP/cve-lite-cli/blob/main/docs/rules/PD002.md"],
31
+ });
32
+ }
33
+ return findings;
34
+ }
@@ -0,0 +1,21 @@
1
+ export function getDeclaredPackages(packageJson) {
2
+ const declared = new Set();
3
+ for (const section of ["dependencies", "devDependencies", "peerDependencies", "optionalDependencies"]) {
4
+ const deps = packageJson[section];
5
+ if (deps && typeof deps === "object" && !Array.isArray(deps)) {
6
+ for (const name of Object.keys(deps)) {
7
+ declared.add(name);
8
+ }
9
+ }
10
+ }
11
+ return declared;
12
+ }
13
+ export function installCmd(pm) {
14
+ if (pm === "pnpm")
15
+ return "pnpm add";
16
+ if (pm === "yarn")
17
+ return "yarn add";
18
+ if (pm === "bun")
19
+ return "bun add";
20
+ return "npm install";
21
+ }