cve-lite-cli 1.12.1 → 1.14.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
@@ -6,6 +6,7 @@
6
6
  [![GitHub Marketplace](https://img.shields.io/badge/GitHub%20Marketplace-CVE%20Lite%20CLI-blue)](https://github.com/marketplace/actions/cve-lite-cli)
7
7
  [![License](https://img.shields.io/github/license/OWASP/cve-lite-cli)](https://github.com/OWASP/cve-lite-cli/blob/main/LICENSE)
8
8
  [![Protected by CVE Lite CLI](https://img.shields.io/badge/Protected_by-CVE_Lite_CLI-brightgreen)](https://github.com/OWASP/cve-lite-cli)
9
+ [![OpenSSF Best Practices](https://www.bestpractices.dev/projects/12731/badge)](https://www.bestpractices.dev/projects/12731)
9
10
 
10
11
  <div align="center">
11
12
  <a href="https://owasp.org/cve-lite-cli">
@@ -39,7 +40,8 @@
39
40
  <a href="https://owasp.org/cve-lite-cli/docs/html-report">HTML Report</a> •
40
41
  <a href="https://owasp.org/cve-lite-cli/docs/comparison">Compare</a> •
41
42
  <a href="https://owasp.org/cve-lite-cli/docs/roadmap">Roadmap</a> •
42
- <a href="https://github.com/OWASP/cve-lite-cli/blob/main/src/docs/CONTRIBUTING.md">Contributing</a>
43
+ <a href="https://github.com/OWASP/cve-lite-cli/blob/main/src/docs/CONTRIBUTING.md">Contributing</a> •
44
+ <a href="https://owasp.org/slack/invite">Join Slack</a>
43
45
  </p>
44
46
  </div>
45
47
 
@@ -110,7 +112,7 @@ No account. No configuration. No source code leaves your machine.
110
112
  </td>
111
113
  </tr>
112
114
  <tr>
113
- <td align="center"><sub>Default scan output · <a href="https://owasp.org/cve-lite-cli/docs/how-to-read-verbose-output">verbose output guide</a></sub></td>
115
+ <td align="center"><sub>Default scan output · <a href="https://owasp.org/cve-lite-cli/docs/reading-output">output guide</a></sub></td>
114
116
  <td align="center"><sub>Generated with <code>--report</code> · <a href="https://owasp.org/cve-lite-cli/docs/html-report">HTML report guide</a></sub></td>
115
117
  </tr>
116
118
  </table>
package/dist/cli/args.js CHANGED
@@ -157,6 +157,10 @@ export function parseArgs(argv) {
157
157
  options.noOpen = true;
158
158
  continue;
159
159
  }
160
+ if (arg === "--no-cache") {
161
+ options.noCache = true;
162
+ continue;
163
+ }
160
164
  if (arg.startsWith("-"))
161
165
  throw new Error(`Unknown option: ${arg}`);
162
166
  if (!projectArg) {
package/dist/cli/help.js CHANGED
@@ -44,6 +44,7 @@ export function printHelp() {
44
44
  " --offline Scan using the local advisory database",
45
45
  " --offline-db <path> Use a specific local advisory database file",
46
46
  " --cache-dir <path> Override cache directory",
47
+ " --no-cache Skip the query cache and fetch fresh results from OSV",
47
48
  " --search-depth <number> Recursive search depth (default: 4)",
48
49
  " --all Show all findings in the main table",
49
50
  " --min-severity <level> Minimum severity shown in table (default: medium)",
package/dist/index.js CHANGED
@@ -18,7 +18,7 @@ import { getCliVersion } from "./utils/version-info.js";
18
18
  import { isLikelyBlockedAdvisoryRequestError } from "./utils/network.js";
19
19
  import { logInfo, logWarn, printCacheSummary, serializeFinding, sortFindingsForOutput } from "./output/formatters.js";
20
20
  import { buildReportData, writeHtmlReport } from "./output/html-reporter.js";
21
- import { printSummary, printActionSummary, printPriorityFixes, printFixPlan, printSuggestedFixCommands, printSuggestedFixCommandSkips, printCoverage, printSkippedDependencies, printGroupSummary, printTable, printPathHints, printFinalStatus, printCompactOutput } from "./output/printers.js";
21
+ import { printSummary, printActionSummary, printSuggestedFixCommands, printSuggestedFixCommandSkips, printCoverage, printSkippedDependencies, printTable, printFinalStatus, printCompactOutput } from "./output/printers.js";
22
22
  let parsedArgs = null;
23
23
  try {
24
24
  parsedArgs = parseArgs(process.argv.slice(2));
@@ -77,6 +77,9 @@ if (parsedArgs) {
77
77
  if ((options.offline || options.offlineDb) && options.osvUrl) {
78
78
  throw new Error("--offline/--offline-db cannot be used with --osv-url");
79
79
  }
80
+ if (options.noCache && (options.offline || options.offlineDb)) {
81
+ throw new Error("--no-cache cannot be used with --offline or --offline-db");
82
+ }
80
83
  if (options.osvUrl) {
81
84
  try {
82
85
  new URL(options.osvUrl);
@@ -202,29 +205,25 @@ if (parsedArgs) {
202
205
  printSummary(scanState.sorted, packages.length, scanInput);
203
206
  printActionSummary(scanState.sorted);
204
207
  printSuggestedFixCommands(scanState.sorted, scanInput, { offline });
205
- printPriorityFixes(scanState.sorted);
206
- printFixPlan(scanState.sorted);
207
208
  printSuggestedFixCommandSkips(scanState.sorted, scanInput, { offline });
208
- printCoverage([...scanInput.notes, ...scanState.coverage]);
209
209
  if (scanInput.skippedDependencies.length > 0) {
210
210
  printSkippedDependencies(scanInput.skippedDependencies);
211
211
  }
212
212
  if (scanState.sorted.length > 0) {
213
- printGroupSummary(scanState.sorted);
214
213
  if (scanState.tableFindings.length > 0) {
215
214
  printTable(scanState.tableFindings, options.all ? null : scanState.minSeverity);
216
- printPathHints(scanState.tableFindings);
217
215
  }
218
216
  else {
219
217
  logInfo(`No findings met the table threshold of ${scanState.minSeverity}. Re-run with --all to show everything.`, options);
220
218
  }
221
219
  }
220
+ printCoverage([...scanInput.notes, ...scanState.coverage]);
222
221
  printFinalStatus(scanState.sorted);
223
222
  }
224
223
  else {
225
224
  // Simplified output - cleaner, focused view
226
225
  const offline = !!options.offline || !!options.offlineDb;
227
- printCompactOutput(scanState.sorted, scanInput, { offline });
226
+ printCompactOutput(scanState.sorted, scanInput, { offline, all: !!options.all });
228
227
  }
229
228
  if (options.report) {
230
229
  const outputDir = path.resolve(typeof options.report === "string" ? options.report : "./cve-report");
package/dist/osv/cache.js CHANGED
@@ -2,7 +2,7 @@ import fs from "node:fs";
2
2
  import path from "node:path";
3
3
  import os from "node:os";
4
4
  function createEmptyCache() {
5
- return { version: 2, createdAt: new Date().toISOString(), entries: {}, queryEntries: {} };
5
+ return { version: 3, createdAt: new Date().toISOString(), entries: {}, queryEntries: {} };
6
6
  }
7
7
  export function getCacheFilePath(cacheDirOverride) {
8
8
  const baseDir = cacheDirOverride
@@ -11,6 +11,9 @@ export function getCacheFilePath(cacheDirOverride) {
11
11
  fs.mkdirSync(baseDir, { recursive: true });
12
12
  return path.join(baseDir, "osv-vulns.json");
13
13
  }
14
+ export function isEntryStale(entry, nowMs) {
15
+ return nowMs - new Date(entry.cachedAt).getTime() > 30 * 60 * 1000;
16
+ }
14
17
  export function loadCache(cacheDirOverride) {
15
18
  const filePath = getCacheFilePath(cacheDirOverride);
16
19
  if (!fs.existsSync(filePath)) {
@@ -18,19 +21,41 @@ export function loadCache(cacheDirOverride) {
18
21
  }
19
22
  try {
20
23
  const parsed = JSON.parse(fs.readFileSync(filePath, "utf8"));
21
- if (parsed.entries && typeof parsed.entries === "object") {
22
- return {
23
- version: 2,
24
- createdAt: parsed.createdAt ?? new Date().toISOString(),
25
- entries: parsed.entries,
26
- queryEntries: parsed.queryEntries && typeof parsed.queryEntries === "object" ? parsed.queryEntries : {},
27
- };
24
+ if (typeof parsed !== "object" || parsed === null)
25
+ return createEmptyCache();
26
+ const entries = (parsed.entries && typeof parsed.entries === "object")
27
+ ? parsed.entries
28
+ : {};
29
+ // v2: queryEntries values are string[] — migrate to { vulnIds, cachedAt: epoch }
30
+ if (parsed.version === 2) {
31
+ const rawQuery = parsed.queryEntries;
32
+ const queryEntries = {};
33
+ for (const [key, vulnIds] of Object.entries(rawQuery ?? {})) {
34
+ queryEntries[key] = { vulnIds: Array.isArray(vulnIds) ? vulnIds : [], cachedAt: new Date(0).toISOString() };
35
+ }
36
+ return { version: 3, createdAt: String(parsed.createdAt ?? new Date().toISOString()), entries, queryEntries };
37
+ }
38
+ // v1 or unknown: no queryEntries
39
+ if (parsed.version !== 3) {
40
+ return { version: 3, createdAt: new Date().toISOString(), entries, queryEntries: {} };
28
41
  }
42
+ const rawQuery = parsed.queryEntries;
43
+ const queryEntries = {};
44
+ for (const [key, value] of Object.entries(rawQuery ?? {})) {
45
+ if (value && typeof value === "object" && "vulnIds" in value && "cachedAt" in value) {
46
+ queryEntries[key] = value;
47
+ }
48
+ }
49
+ return {
50
+ version: 3,
51
+ createdAt: String(parsed.createdAt ?? new Date().toISOString()),
52
+ entries,
53
+ queryEntries,
54
+ };
29
55
  }
30
- catch (_error) {
31
- // ignore corrupt cache
56
+ catch {
57
+ return createEmptyCache();
32
58
  }
33
- return createEmptyCache();
34
59
  }
35
60
  export function saveCache(cache, cacheDirOverride) {
36
61
  const filePath = getCacheFilePath(cacheDirOverride);
@@ -26,11 +26,16 @@ export function formatRelationshipLabel(value) {
26
26
  return chalk.gray(value);
27
27
  }
28
28
  export function getRecommendedAction(finding) {
29
- if (finding.relationship === "direct" && finding.firstFixedVersion) {
30
- return `Upgrade ${finding.pkg.name} to ${finding.firstFixedVersion}+ in this project.`;
29
+ // Prefer the registry-validated target over the raw advisory hint when
30
+ // available — they can disagree (the hint may not be published on npm or
31
+ // may itself be vulnerable), and the validated target is what the fix
32
+ // command actually uses.
33
+ const directTarget = finding.validatedFirstFixedVersion ?? finding.firstFixedVersion;
34
+ if (finding.relationship === "direct" && directTarget) {
35
+ return `Upgrade ${finding.pkg.name} to ${directTarget}+ in this project.`;
31
36
  }
32
37
  if (finding.relationship === "direct") {
33
- return `Review and upgrade ${finding.pkg.name} directly in this project.`;
38
+ return `No known fix exists for ${finding.pkg.name}. Consider replacing it with an actively maintained alternative.`;
34
39
  }
35
40
  if (finding.recommendedNpmTransitiveRemediation?.kind === "update-parent-within-range") {
36
41
  return `Update ${finding.recommendedNpmTransitiveRemediation.package} within its current dependency range to pull in vulnerable ${finding.pkg.name}@${finding.recommendedNpmTransitiveRemediation.targetChildVersion}.`;
@@ -43,16 +48,20 @@ export function getRecommendedAction(finding) {
43
48
  return `Upgrade ${finding.recommendedParentUpgrade.package} from ${finding.recommendedParentUpgrade.currentVersion} to ${finding.recommendedParentUpgrade.targetVersion} to stop pulling in vulnerable ${finding.pkg.name}.`;
44
49
  }
45
50
  const parent = getPrimaryParent(finding);
46
- if (parent && finding.firstFixedVersion) {
47
- return `Upgrade ${parent} — no safe version was identified automatically. Check for a release that resolves ${finding.pkg.name} to ${finding.firstFixedVersion}+.`;
51
+ if (parent && directTarget) {
52
+ return `Upgrade ${parent} — no safe version was identified automatically. Check for a release that resolves ${finding.pkg.name} to ${directTarget}+.`;
48
53
  }
49
54
  if (parent) {
50
55
  return `Review ${parent}; it currently pulls in vulnerable ${finding.pkg.name}.`;
51
56
  }
52
- if (finding.firstFixedVersion) {
53
- return `No dependency path found for ${finding.pkg.name}. Inspect your lockfile to identify which package pulls it in.`;
57
+ // No parent identifiable: either dependencyPaths is empty, or the path is
58
+ // a degenerate length-2 chain (project -> vulnerable, common when the
59
+ // package is hoisted to top-level node_modules). The advice is the same
60
+ // either way — inspect the lockfile or run `<pm> ls` to find the parent.
61
+ if (directTarget) {
62
+ return `No parent dependency was identified for ${finding.pkg.name} in the lockfile. Run \`npm ls ${finding.pkg.name}\` (or your package manager equivalent) to find which package pulls it in, then upgrade toward ${directTarget}+.`;
54
63
  }
55
- return `Inspect the dependency path for ${finding.pkg.name} and choose the safest upgrade path.`;
64
+ return `No parent dependency was identified for ${finding.pkg.name} in the lockfile. Run \`npm ls ${finding.pkg.name}\` (or your package manager equivalent) to find which package pulls it in.`;
56
65
  }
57
66
  export function summarizeRisk(finding) {
58
67
  let risk = "";
@@ -71,14 +80,16 @@ export function summarizeRisk(finding) {
71
80
  else if (finding.relationship === "transitive" && finding.recommendedParentUpgrade) {
72
81
  risk = `Transitive issue. A specific parent upgrade target was found for ${finding.recommendedParentUpgrade.package}.`;
73
82
  }
74
- else if (finding.relationship === "transitive" && finding.firstFixedVersion) {
75
- risk = `Transitive issue. Look for a parent dependency upgrade that pulls in ${finding.firstFixedVersion}+`;
83
+ else if (finding.relationship === "transitive" && (finding.validatedFirstFixedVersion ?? finding.firstFixedVersion)) {
84
+ const target = finding.validatedFirstFixedVersion ?? finding.firstFixedVersion;
85
+ risk = `Transitive issue. Look for a parent dependency upgrade that pulls in ${target}+`;
76
86
  }
77
87
  else if (finding.relationship === "transitive") {
78
88
  risk = "Transitive issue. Review the parent path and check whether an upstream package can be upgraded.";
79
89
  }
80
- else if (finding.firstFixedVersion) {
81
- risk = `A fixed-version hint exists. Aim for at least ${finding.firstFixedVersion}.`;
90
+ else if (finding.validatedFirstFixedVersion ?? finding.firstFixedVersion) {
91
+ const target = finding.validatedFirstFixedVersion ?? finding.firstFixedVersion;
92
+ risk = `A fixed-version hint exists. Aim for at least ${target}.`;
82
93
  }
83
94
  else {
84
95
  risk = "Review this finding and inspect the dependency path for the safest upgrade path.";
@@ -94,11 +105,14 @@ export function summarizeRisk(finding) {
94
105
  return risk;
95
106
  }
96
107
  export function summarizeNextAction(finding) {
97
- if (finding.relationship === "direct" && finding.firstFixedVersion) {
98
- return `Upgrade ${finding.pkg.name} toward ${finding.firstFixedVersion}.`;
108
+ // Prefer the registry-validated target over the raw advisory hint so this
109
+ // line agrees with the fix-command table. See getRecommendedAction.
110
+ const directTarget = finding.validatedFirstFixedVersion ?? finding.firstFixedVersion;
111
+ if (finding.relationship === "direct" && directTarget) {
112
+ return `Upgrade ${finding.pkg.name} toward ${directTarget}.`;
99
113
  }
100
114
  if (finding.relationship === "direct") {
101
- return `Review and upgrade ${finding.pkg.name} directly in this project.`;
115
+ return `No known fix exists for ${finding.pkg.name}. Consider replacing it with an actively maintained alternative.`;
102
116
  }
103
117
  if (finding.recommendedNpmTransitiveRemediation?.kind === "update-parent-within-range") {
104
118
  return `Update ${finding.recommendedNpmTransitiveRemediation.package} within its current dependency range.`;
@@ -111,11 +125,11 @@ export function summarizeNextAction(finding) {
111
125
  return `Upgrade ${finding.recommendedParentUpgrade.package} ${finding.recommendedParentUpgrade.currentVersion} -> ${finding.recommendedParentUpgrade.targetVersion}.`;
112
126
  }
113
127
  const parent = getPrimaryParent(finding);
114
- if (parent && finding.firstFixedVersion) {
115
- return `Upgrade ${parent} — no safe version identified. Find a release resolving ${finding.pkg.name} to ${finding.firstFixedVersion}+.`;
128
+ if (parent && directTarget) {
129
+ return `Upgrade ${parent} — no safe version identified. Find a release resolving ${finding.pkg.name} to ${directTarget}+.`;
116
130
  }
117
- if (finding.firstFixedVersion) {
118
- return `No dependency path found for ${finding.pkg.name}. Check your lockfile for which package pulls it in.`;
131
+ if (directTarget) {
132
+ return `No parent identified in the lockfile. Run \`npm ls ${finding.pkg.name}\` to find the parent, then upgrade toward ${directTarget}+.`;
119
133
  }
120
134
  return `Inspect the parent dependency chain for ${finding.pkg.name} and choose the safest available upgrade.`;
121
135
  }
@@ -128,7 +128,7 @@ button.header-link:hover{color:#58a6ff;border-color:#58a6ff}
128
128
  .cve-link{font-size:11px;color:#58a6ff;font-family:monospace;text-decoration:none;border-bottom:1px dotted #58a6ff66}
129
129
  .cve-link:hover{color:#79c0ff}
130
130
  .fix-hint{font-size:11px;color:#3fb950;font-family:monospace}
131
- .fix-hint.none{color:#8b949e}
131
+ .fix-hint.none{color:#e3b341}
132
132
  .expand-icon{color:#8b949e;font-size:10px}
133
133
  .detail-row{background:#0d1117;border-top:1px solid #21262d;display:none}
134
134
  .detail-row.visible{display:table-row}
@@ -164,6 +164,9 @@ button.header-link:hover{color:#58a6ff;border-color:#58a6ff}
164
164
  .fix-target-stats{color:#6b7280;font-size:10px}
165
165
  .fix-target-note{color:#6b7280;font-style:italic;font-size:10px}
166
166
  .break-badge{font-size:10px;font-weight:700;background:#fb850022;color:#fb8500;border:1px solid #fb850066;border-radius:4px;padding:1px 5px}
167
+ .tier-ok{display:inline-flex;align-items:center;gap:4px;font-size:10px;padding:2px 8px;border-radius:4px;background:#3fb95022;color:#3fb950;border:1px solid #3fb95033;margin-bottom:6px}
168
+ .tier-warn{display:inline-flex;align-items:center;gap:4px;font-size:10px;padding:2px 8px;border-radius:4px;background:#e3b34122;color:#e3b341;border:1px solid #e3b34133;margin-bottom:6px}
169
+ .tier-err{display:inline-flex;align-items:center;gap:4px;font-size:10px;padding:2px 8px;border-radius:4px;background:#ff000011;color:#ff7b72;border:1px solid #ff7b7222;margin-bottom:6px}
167
170
  </style>
168
171
  </head>
169
172
  <body>
@@ -388,7 +391,7 @@ function renderFindingRow(finding, idx) {
388
391
  ? `<span class="fix-hint">${escapeHtml(finding.validatedFirstFixedVersion)}</span>`
389
392
  : finding.firstFixedVersion
390
393
  ? `<span class="fix-hint">${escapeHtml(finding.firstFixedVersion)}</span>`
391
- : `<span class="fix-hint none">—</span>`;
394
+ : `<span class="fix-hint none" title="No known fix — consider replacing this package">⚠ No fix</span>`;
392
395
  const depPathHtml = finding.dependencyPaths.length > 0
393
396
  ? finding.dependencyPaths[0].map((node, i, arr) => {
394
397
  const isLast = i === arr.length - 1;
@@ -403,6 +406,9 @@ function renderFindingRow(finding, idx) {
403
406
  <button class="copy-btn" data-cmd="${escapeHtml(runnable)}">Copy</button>
404
407
  </div>`
405
408
  : `<p class="fix-cmd-note">${escapeHtml(finding.recommendedAction ?? "")}</p>`;
409
+ const contextColHtml = finding.relationship === "transitive"
410
+ ? renderTransitiveContextCol(finding)
411
+ : "";
406
412
  return ` <tr id="row-${idx}" onclick="toggleRow(${idx})">
407
413
  <td><span class="expand-icon" id="icon-${idx}">▶</span></td>
408
414
  <td><div class="pkg-name">${escapeHtml(finding.package)}</div><div class="pkg-version">${escapeHtml(finding.version)}</div></td>
@@ -422,6 +428,7 @@ function renderFindingRow(finding, idx) {
422
428
  <h4>Dependency path</h4>
423
429
  <div class="dep-path">${depPathHtml}</div>
424
430
  </div>
431
+ ${contextColHtml}
425
432
  <div class="detail-col">
426
433
  <h4>Recommended action</h4>
427
434
  ${recommendedActionHtml}
@@ -430,6 +437,33 @@ function renderFindingRow(finding, idx) {
430
437
  </td>
431
438
  </tr>`;
432
439
  }
440
+ function renderTransitiveContextCol(finding) {
441
+ const hasFixAvailable = finding.runnableFixCommand != null ||
442
+ finding.recommendedNpmTransitiveRemediation != null ||
443
+ finding.recommendedParentUpgrade != null;
444
+ if (hasFixAvailable) {
445
+ const parentLine = finding.primaryParent
446
+ ? `<p style="font-size:12px;color:#8b949e;margin-top:4px">Parent: ${escapeHtml(finding.primaryParent)}</p>`
447
+ : "";
448
+ return `<div class="detail-col" style="max-width:200px">
449
+ <h4>Context</h4>
450
+ <span class="tier-ok">✓ Fix available</span>
451
+ ${parentLine}
452
+ </div>`;
453
+ }
454
+ if (finding.primaryParent) {
455
+ return `<div class="detail-col" style="max-width:200px">
456
+ <h4>Context</h4>
457
+ <span class="tier-warn">⚠ No safe version identified</span>
458
+ <p style="font-size:12px;color:#8b949e;margin-top:4px">Parent: ${escapeHtml(finding.primaryParent)}</p>
459
+ </div>`;
460
+ }
461
+ return `<div class="detail-col" style="max-width:200px">
462
+ <h4>Context</h4>
463
+ <span class="tier-err">✕ No parent identified</span>
464
+ <p style="font-size:12px;color:#8b949e;margin-top:4px">Run <code>npm ls ${escapeHtml(finding.package)}</code> to find which package pulls it in.</p>
465
+ </div>`;
466
+ }
433
467
  function renderNotices(notes, warnings) {
434
468
  if (notes.length === 0 && warnings.length === 0)
435
469
  return "";
@@ -1,9 +1,8 @@
1
1
  import { chalk, stripAnsi } from "../utils/chalk.js";
2
- import { severityOrder } from "../constants.js";
3
- import { buildSuggestedFixCommandPlan, findSuggestedCommandForFinding } from "../remediation/fix-commands.js";
2
+ import { buildSuggestedFixCommandPlan } from "../remediation/fix-commands.js";
4
3
  import { isMajorVersionBump } from "../utils/version.js";
5
4
  import { getPrimaryParent } from "../utils/finding.js";
6
- import { formatSeverityLabel, formatRelationshipLabel, getRecommendedAction, summarizeRisk, summarizeNextAction } from "./formatters.js";
5
+ import { formatSeverityLabel, formatRelationshipLabel } from "./formatters.js";
7
6
  export function printSummary(findings, packageCount, scanInput) {
8
7
  if (findings.length === 0) {
9
8
  if (scanInput.mode === "manifest-fallback") {
@@ -22,7 +21,7 @@ export function printSummary(findings, packageCount, scanInput) {
22
21
  unknown: findings.filter(f => f.severity === "unknown").length
23
22
  };
24
23
  console.log(chalk.redBright(`✗ Found ${findings.length} package(s) with known OSV matches from ${scanInput.source}`));
25
- console.log(` ${formatSeverityLabel("critical")}: ${counts.critical} ${formatSeverityLabel("high")}: ${counts.high} ${formatSeverityLabel("medium")}: ${counts.medium} ${formatSeverityLabel("low")}: ${counts.low} ${formatSeverityLabel("unknown")}: ${counts.unknown}`);
24
+ console.log(renderSeverityTable(counts));
26
25
  }
27
26
  export function printActionSummary(findings) {
28
27
  if (findings.length === 0)
@@ -42,88 +41,6 @@ export function printActionSummary(findings) {
42
41
  console.log(`- ${chalk.blueBright(String(uniqueAdvisories))} unique advisories matched overall.`);
43
42
  console.log(`- ${chalk.blue(String(fixable))} package${fixable === 1 ? "" : "s"} include a fixed-version hint from OSV.`);
44
43
  }
45
- export function printPriorityFixes(findings) {
46
- if (findings.length === 0)
47
- return;
48
- const scored = [...findings].sort((a, b) => {
49
- const sevDelta = severityOrder[b.severity] - severityOrder[a.severity];
50
- if (sevDelta !== 0)
51
- return sevDelta;
52
- const relScore = (f) => f.relationship === "direct" ? 2 : f.relationship === "transitive" ? 1 : 0;
53
- const relDelta = relScore(b) - relScore(a);
54
- if (relDelta !== 0)
55
- return relDelta;
56
- const fixedDelta = Number(Boolean(b.firstFixedVersion)) - Number(Boolean(a.firstFixedVersion));
57
- if (fixedDelta !== 0)
58
- return fixedDelta;
59
- return a.pkg.name.localeCompare(b.pkg.name);
60
- });
61
- const top = scored.slice(0, 5);
62
- console.log("");
63
- console.log(chalk.bold.magenta("🚀 Top priority fixes"));
64
- for (const finding of top) {
65
- let usageNote = "";
66
- if (finding.usage) {
67
- usageNote = finding.usage.imported ? `, imported in ${finding.usage.files.length} file${finding.usage.files.length === 1 ? "" : "s"}` : `, no direct import found`;
68
- }
69
- console.log(`- ${chalk.whiteBright(finding.pkg.name)}@${chalk.white(finding.pkg.version)} (${formatSeverityLabel(finding.severity)}, ${formatRelationshipLabel(finding.relationship)}${usageNote})`);
70
- console.log(` Risk: ${summarizeRisk(finding)}`);
71
- const parent = getPrimaryParent(finding);
72
- if (parent)
73
- console.log(` Parent: ${parent}`);
74
- if (finding.recommendedNpmTransitiveRemediation?.kind === "update-parent-within-range") {
75
- console.log(` Target: npm update ${finding.recommendedNpmTransitiveRemediation.package} (pulls in ${finding.pkg.name}@${finding.recommendedNpmTransitiveRemediation.targetChildVersion} within range)`);
76
- }
77
- else if (finding.recommendedParentUpgrade) {
78
- console.log(` Target: ${finding.recommendedParentUpgrade.package} ${finding.recommendedParentUpgrade.currentVersion} -> ${finding.recommendedParentUpgrade.targetVersion}`);
79
- }
80
- console.log(` Next: ${summarizeNextAction(finding)}`);
81
- }
82
- }
83
- export function printFixPlan(findings) {
84
- if (findings.length === 0)
85
- return;
86
- const directUrgent = findings.filter(f => f.relationship === "direct" && (f.severity === "critical" || f.severity === "high"));
87
- const transitiveUrgent = findings.filter(f => f.relationship === "transitive" && (f.severity === "critical" || f.severity === "high"));
88
- const directMedium = findings.filter(f => f.relationship === "direct" && f.severity === "medium");
89
- console.log("");
90
- console.log(chalk.bold.green("📋 Suggested fix plan"));
91
- if (directUrgent.length > 0) {
92
- console.log(chalk.green("1) Upgrade these direct critical/high dependencies first:"));
93
- for (const finding of directUrgent.slice(0, 5)) {
94
- console.log(` - ${finding.pkg.name}@${finding.pkg.version}: ${getRecommendedAction(finding)}`);
95
- }
96
- }
97
- if (transitiveUrgent.length > 0) {
98
- console.log(chalk.yellow("2) Review these urgent transitive issues next:"));
99
- for (const finding of transitiveUrgent.slice(0, 5)) {
100
- console.log(` - ${finding.pkg.name}@${finding.pkg.version}: ${getRecommendedAction(finding)}`);
101
- }
102
- }
103
- if (directMedium.length > 0) {
104
- console.log(chalk.blue("3) Clean up these medium direct dependencies after the urgent fixes:"));
105
- for (const finding of directMedium.slice(0, 5)) {
106
- console.log(` - ${finding.pkg.name}@${finding.pkg.version}: ${getRecommendedAction(finding)}`);
107
- }
108
- }
109
- const grouped = new Map();
110
- for (const finding of findings) {
111
- const existing = grouped.get(finding.pkg.name) ?? [];
112
- existing.push(finding);
113
- grouped.set(finding.pkg.name, existing);
114
- }
115
- const dupes = [...grouped.entries()]
116
- .filter(([, items]) => items.length > 1)
117
- .sort((a, b) => b[1].length - a[1].length || a[0].localeCompare(b[0]))
118
- .slice(0, 5);
119
- if (dupes.length > 0) {
120
- console.log(chalk.magenta("4) Consolidate duplicated vulnerable packages where possible:"));
121
- for (const [name, items] of dupes) {
122
- const versions = [...new Set(items.map(item => item.pkg.version))].sort().join(", ");
123
- console.log(` - ${name}: vulnerable versions present -> ${versions}`);
124
- }
125
- }
126
- }
127
44
  export function printSuggestedFixCommands(findings, scanInput, options) {
128
45
  const plan = buildSuggestedFixCommandPlan(findings, scanInput, options);
129
46
  if (!plan)
@@ -219,18 +136,6 @@ export function printSkippedDependencies(skipped) {
219
136
  console.log(`${chalk.yellow("•")} ...and ${skipped.length - 10} more`);
220
137
  }
221
138
  }
222
- export function printGroupSummary(findings) {
223
- const direct = findings.filter(f => f.relationship === "direct");
224
- const transitive = findings.filter(f => f.relationship === "transitive");
225
- const unknown = findings.filter(f => f.relationship === "unknown");
226
- console.log("");
227
- console.log(chalk.bold.green("Where the issues are"));
228
- console.log(`- Direct dependencies: ${chalk.green(String(direct.length))}`);
229
- console.log(`- Transitive dependencies: ${chalk.yellow(String(transitive.length))}`);
230
- if (unknown.length > 0) {
231
- console.log(`- Unclear relationship: ${chalk.magenta(String(unknown.length))}`);
232
- }
233
- }
234
139
  export function printTable(findings, threshold) {
235
140
  const headers = ["Package", "Version", "Severity", "Type", "Usage", "Fixed", "IDs"];
236
141
  const rawRows = findings.map(f => {
@@ -244,11 +149,11 @@ export function printTable(findings, threshold) {
244
149
  f.severity,
245
150
  f.relationship,
246
151
  usageText,
247
- f.firstFixedVersion ?? "-",
152
+ f.firstFixedVersion ?? chalk.yellow("⚠ no fix"),
248
153
  f.vulnerabilities.map(v => v.id).join(", ")
249
154
  ];
250
155
  });
251
- const widths = headers.map((header, index) => Math.min(40, Math.max(header.length, ...rawRows.map(r => String(r[index]).length))));
156
+ const widths = headers.map((header, index) => Math.min(40, Math.max(header.length, ...rawRows.map(r => stripAnsi(String(r[index])).length))));
252
157
  console.log("");
253
158
  if (threshold) {
254
159
  console.log(chalk.bold(`Showing ${threshold}+ findings in the main table. Use --all to show everything.`));
@@ -277,26 +182,8 @@ export function printTable(findings, threshold) {
277
182
  console.log(renderRow(decorated, widths));
278
183
  }
279
184
  console.log(line("└", "┴", "┘"));
280
- console.log(chalk.gray("Tip: use --all to include low/unknown findings, or --min-severity high to focus only on urgent issues."));
281
- }
282
- export function printPathHints(findings) {
283
- const withPaths = findings.filter(f => (f.dependencyPaths ?? []).length > 0);
284
- if (withPaths.length === 0)
285
- return;
286
- console.log("");
287
- console.log(chalk.bold.cyan("Dependency paths to inspect"));
288
- for (const finding of withPaths.slice(0, 10)) {
289
- const examples = finding.dependencyPaths.slice(0, 3).map(p => p.join(" -> "));
290
- console.log(`- ${finding.pkg.name}@${finding.pkg.version}`);
291
- for (const example of examples) {
292
- console.log(` ${chalk.gray(example)}`);
293
- }
294
- if (finding.recommendedNpmTransitiveRemediation?.kind === "update-parent-within-range") {
295
- console.log(` Recommended parent update: ${chalk.bold.cyan(`npm update ${finding.recommendedNpmTransitiveRemediation.package}`)}`);
296
- }
297
- else if (finding.recommendedParentUpgrade) {
298
- console.log(` Recommended parent upgrade: ${chalk.bold.cyan(finding.recommendedParentUpgrade.package)} ${finding.recommendedParentUpgrade.currentVersion} -> ${finding.recommendedParentUpgrade.targetVersion}`);
299
- }
185
+ if (threshold) {
186
+ console.log(chalk.gray("Tip: use --all to include low/unknown findings, or --min-severity high to focus only on urgent issues."));
300
187
  }
301
188
  }
302
189
  export function printFinalStatus(findings) {
@@ -422,45 +309,6 @@ export function printCompactOutput(findings, scanInput, options) {
422
309
  }
423
310
  }
424
311
  }
425
- // Top Priority Fix section
426
- if (urgentFindings.length > 0) {
427
- const topFinding = urgentFindings[0];
428
- console.log("────────────────────────────────");
429
- console.log(chalk.bold("🚀 Top Priority Issue"));
430
- console.log("────────────────────────────────\n");
431
- if (topFinding.relationship === "direct" && topFinding.firstFixedVersion) {
432
- console.log(`Upgrade ${chalk.whiteBright(topFinding.pkg.name)} → ${topFinding.firstFixedVersion}`);
433
- }
434
- else if (topFinding.relationship === "direct") {
435
- console.log(`Upgrade ${chalk.whiteBright(topFinding.pkg.name)} to latest safe version`);
436
- }
437
- else if (topFinding.recommendedNpmTransitiveRemediation?.kind === "update-parent-within-range") {
438
- console.log(`Update ${chalk.whiteBright(topFinding.recommendedNpmTransitiveRemediation.package)} within current range`);
439
- }
440
- else if (topFinding.recommendedParentUpgrade) {
441
- console.log(`Upgrade ${chalk.whiteBright(topFinding.recommendedParentUpgrade.package)} ${topFinding.recommendedParentUpgrade.currentVersion} → ${topFinding.recommendedParentUpgrade.targetVersion}`);
442
- }
443
- else {
444
- const parent = getPrimaryParent(topFinding);
445
- if (parent) {
446
- console.log(`Upgrade ${chalk.whiteBright(parent)} to resolve ${topFinding.pkg.name}`);
447
- }
448
- else {
449
- console.log(`No dependency path found — inspect lockfile to identify which package pulls in ${chalk.whiteBright(topFinding.pkg.name)}`);
450
- }
451
- }
452
- if (plan) {
453
- const topFindingCommand = findSuggestedCommandForFinding(plan, topFinding);
454
- if (topFindingCommand) {
455
- console.log(chalk.gray("Command:"));
456
- console.log(renderCommandCallout(topFindingCommand));
457
- }
458
- else {
459
- console.log(chalk.gray("No confident automatic command is available for this issue yet."));
460
- }
461
- }
462
- console.log("");
463
- }
464
312
  // Summary
465
313
  console.log("────────────────────────────────");
466
314
  console.log("Summary");
@@ -490,7 +338,12 @@ export function printCompactOutput(findings, scanInput, options) {
490
338
  console.log(`${chalk.cyan(String(direct))} ${chalk.white("direct")}` +
491
339
  `${chalk.gray(" · ")}` +
492
340
  `${chalk.cyan(String(transitive))} ${chalk.white("transitive")}`);
493
- console.log("");
341
+ if (options?.all) {
342
+ printTable(findings, null);
343
+ }
344
+ else {
345
+ console.log("");
346
+ }
494
347
  // Footer
495
348
  const urgentCount = counts.critical + counts.high;
496
349
  if (urgentCount > 0) {
@@ -499,9 +352,39 @@ export function printCompactOutput(findings, scanInput, options) {
499
352
  else {
500
353
  console.log(chalk.yellow(`▲ Scan complete. ${findings.length} issue${findings.length === 1 ? "" : "s"} found.`));
501
354
  }
502
- console.log(chalk.gray(`Run with ${chalk.whiteBright("--verbose")} for fix plan, paths, and full table.`));
355
+ if (!options?.all) {
356
+ console.log(chalk.gray(`Run with ${chalk.whiteBright("--verbose")} for fix plan, paths, and full table.`));
357
+ }
503
358
  console.log("");
504
359
  }
360
+ function renderSeverityTable(counts) {
361
+ const labels = ["Critical", "High", "Medium", "Low", "Unknown"];
362
+ const coloredValues = [
363
+ chalk.redBright(String(counts.critical)),
364
+ chalk.red(String(counts.high)),
365
+ chalk.yellow(String(counts.medium)),
366
+ chalk.blueBright(String(counts.low)),
367
+ chalk.magenta(String(counts.unknown)),
368
+ ];
369
+ const rawValues = [
370
+ String(counts.critical),
371
+ String(counts.high),
372
+ String(counts.medium),
373
+ String(counts.low),
374
+ String(counts.unknown),
375
+ ];
376
+ const widths = labels.map((label, i) => Math.max(label.length, rawValues[i].length));
377
+ const line = (left, mid, right) => left + widths.map(w => "─".repeat(w + 2)).join(mid) + right;
378
+ const pad = (text, raw, width) => {
379
+ const pad = width - raw.length;
380
+ const left = Math.floor(pad / 2);
381
+ const right = pad - left;
382
+ return " ".repeat(left + 1) + text + " ".repeat(right + 1);
383
+ };
384
+ const headerRow = "│" + labels.map((label, i) => ` ${label.padStart(Math.floor((widths[i] - label.length) / 2) + label.length).padEnd(widths[i])} `).join("│") + "│";
385
+ const valueRow = "│" + coloredValues.map((val, i) => pad(val, rawValues[i], widths[i])).join("│") + "│";
386
+ return [line("┌", "┬", "┐"), headerRow, line("├", "┼", "┤"), valueRow, line("└", "┴", "┘")].join("\n");
387
+ }
505
388
  function colorFixSectionTitle(severity, title) {
506
389
  if (severity === "critical")
507
390
  return chalk.redBright(title);
@@ -56,21 +56,26 @@ export function loadNpmLockGraph(filePath, options) {
56
56
  resolveEdgesForParent(node.packagePath, dependencyRangesByNodeId.get(node.id) ?? {}, resolutionBasePathsByNodeId.get(node.id) ?? [node.packagePath], nodeIdByPackagePath, childNodeIdsByParentNodeId, parentNodeIdsByChildNodeId, rangeByParentNodeId);
57
57
  }
58
58
  if (options?.includePaths !== false) {
59
+ const MAX_PATHS_PER_NODE = 5;
60
+ const MAX_PATH_DEPTH = 10;
59
61
  const queue = entryPackages.map((entryNodeId) => ({
60
62
  nodeId: entryNodeId,
61
63
  path: ["project", nodesById.get(entryNodeId)?.name ?? entryNodeId],
62
64
  }));
63
- while (queue.length > 0) {
64
- const current = queue.shift();
65
- if (!current)
66
- continue;
65
+ let queueHead = 0;
66
+ while (queueHead < queue.length) {
67
+ const current = queue[queueHead++];
67
68
  rememberPath(pathSetByNodeId, current.nodeId, current.path);
69
+ if (current.path.length >= MAX_PATH_DEPTH)
70
+ continue;
68
71
  for (const childNodeId of childNodeIdsByParentNodeId.get(current.nodeId) ?? []) {
69
72
  const childNode = nodesById.get(childNodeId);
70
73
  if (!childNode)
71
74
  continue;
72
- const nextPath = [...current.path, childNode.name];
73
75
  const beforeSize = pathSetByNodeId.get(childNodeId)?.size ?? 0;
76
+ if (beforeSize >= MAX_PATHS_PER_NODE)
77
+ continue;
78
+ const nextPath = [...current.path, childNode.name];
74
79
  rememberPath(pathSetByNodeId, childNodeId, nextPath);
75
80
  const afterSize = pathSetByNodeId.get(childNodeId)?.size ?? 0;
76
81
  if (afterSize > beforeSize) {
@@ -1,9 +1,11 @@
1
1
  import fs from "node:fs";
2
2
  import { upsertPackage, normalizeNodeModulesPath } from "./utils.js";
3
+ import { loadNpmLockGraph } from "./npm-lock-graph.js";
3
4
  export function loadFromPackageLock(filePath, prodOnly) {
4
5
  const raw = JSON.parse(fs.readFileSync(filePath, "utf8"));
5
6
  const map = new Map();
6
7
  if (raw.packages && typeof raw.packages === "object") {
8
+ const graph = loadNpmLockGraph(filePath, { includePaths: true });
7
9
  for (const [pkgPath, meta] of Object.entries(raw.packages)) {
8
10
  if (!pkgPath || pkgPath === "")
9
11
  continue;
@@ -16,8 +18,10 @@ export function loadFromPackageLock(filePath, prodOnly) {
16
18
  continue;
17
19
  if (prodOnly && dev)
18
20
  continue;
19
- const pathParts = normalizeNodeModulesPath(pkgPath);
20
- upsertPackage(map, { name, version, ecosystem: "npm", dev, paths: [pathParts] });
21
+ const nodeIds = graph.nodeIdsFor(name, version);
22
+ const graphPaths = nodeIds.flatMap(id => graph.pathsFor(id));
23
+ const paths = graphPaths.length > 0 ? graphPaths : [normalizeNodeModulesPath(pkgPath)];
24
+ upsertPackage(map, { name, version, ecosystem: "npm", dev, paths });
21
25
  }
22
26
  }
23
27
  if (map.size === 0 && raw.dependencies && typeof raw.dependencies === "object") {
@@ -1,8 +1,39 @@
1
1
  import fs from "node:fs";
2
2
  import { parse as parseYarnLock } from "yarn-lockfile";
3
3
  import { upsertPackage } from "./utils.js";
4
+ function isYarnBerry(content) {
5
+ return content.startsWith('__metadata:') || content.includes('\n__metadata:');
6
+ }
7
+ function loadFromYarnBerryLock(content) {
8
+ const map = new Map();
9
+ const blocks = content.split(/\n\n+/);
10
+ for (const block of blocks) {
11
+ const lines = block.trim().split('\n');
12
+ if (!lines[0] || lines[0].startsWith('__metadata'))
13
+ continue;
14
+ const resolutionLine = lines.find((l) => l.trim().startsWith('resolution:'));
15
+ if (!resolutionLine)
16
+ continue;
17
+ const resMatch = resolutionLine.match(/resolution:\s+"(.+)"/);
18
+ if (!resMatch)
19
+ continue;
20
+ const resolution = resMatch[1];
21
+ const npmIdx = resolution.lastIndexOf('@npm:');
22
+ if (npmIdx < 0)
23
+ continue;
24
+ const name = resolution.slice(0, npmIdx);
25
+ const version = resolution.slice(npmIdx + 5);
26
+ if (!name || !version)
27
+ continue;
28
+ upsertPackage(map, { name, version, ecosystem: 'npm', paths: [['project', name]] });
29
+ }
30
+ return [...map.values()];
31
+ }
4
32
  export function loadFromYarnLock(filePath) {
5
33
  const content = fs.readFileSync(filePath, "utf8");
34
+ if (isYarnBerry(content)) {
35
+ return loadFromYarnBerryLock(content);
36
+ }
6
37
  const parsed = parseYarnLock(content);
7
38
  if (parsed.type !== "success" || !parsed.object) {
8
39
  throw new Error("Could not parse yarn.lock");
package/dist/scanner.js CHANGED
@@ -1,6 +1,6 @@
1
- import { chunk, unique } from "./utils/array.js";
1
+ import { chunk, unique, runWithConcurrency } from "./utils/array.js";
2
2
  import { compareVersions, isPreReleaseVersion, looksLikeVersion } from "./utils/version.js";
3
- import { loadCache, saveCache } from "./osv/cache.js";
3
+ import { loadCache, saveCache, isEntryStale } from "./osv/cache.js";
4
4
  import { maxSeverity } from "./osv/severity.js";
5
5
  import { createSpinner } from "./output/spinner.js";
6
6
  import { OsvAdvisorySource } from "./advisory/osv-advisory-source.js";
@@ -56,28 +56,31 @@ export async function scanPackages(packages, batchSize, options, context) {
56
56
  const results = [];
57
57
  const uncachedPackages = [];
58
58
  if (!offline) {
59
+ const nowMs = Date.now();
59
60
  for (const pkg of packages) {
60
61
  const cacheKey = getPackageCacheKey(pkg);
61
- if (cacheKey in cache.queryEntries) {
62
- const vulnIds = cache.queryEntries[cacheKey] ?? [];
63
- if (vulnIds.length > 0) {
64
- results.push({ pkg, vulnIds });
62
+ if (!options.noCache) {
63
+ const cached = cache.queryEntries[cacheKey];
64
+ if (cached && !isEntryStale(cached, nowMs)) {
65
+ if (cached.vulnIds.length > 0) {
66
+ results.push({ pkg, vulnIds: cached.vulnIds });
67
+ }
68
+ continue;
65
69
  }
66
- continue;
67
70
  }
68
71
  uncachedPackages.push(pkg);
69
72
  }
70
73
  const chunks = chunk(uncachedPackages, batchSize);
74
+ spinner.update(`Scanning OSV in ${chunks.length} parallel batch${chunks.length === 1 ? "" : "es"}...`);
75
+ const allAdvisoryResults = await runWithConcurrency(chunks, 5, c => advisorySource.queryBatch(c));
71
76
  for (let i = 0; i < chunks.length; i++) {
72
- spinner.update(`Scanning OSV batch ${i + 1}/${chunks.length}...`);
73
77
  const chunkItems = chunks[i];
74
- const advisoryResult = await advisorySource.queryBatch(chunkItems);
75
- const rows = advisoryResult ?? [];
78
+ const rows = allAdvisoryResults[i] ?? [];
76
79
  for (let j = 0; j < chunkItems.length; j++) {
77
80
  const pkg = chunkItems[j];
78
81
  const row = rows[j];
79
82
  const vulnIds = (row?.vulnerabilities ?? []).map(v => v.id).filter(Boolean);
80
- cache.queryEntries[getPackageCacheKey(pkg)] = vulnIds;
83
+ cache.queryEntries[getPackageCacheKey(pkg)] = { vulnIds, cachedAt: new Date().toISOString() };
81
84
  if (vulnIds.length > 0) {
82
85
  results.push({ pkg, vulnIds });
83
86
  }
@@ -20,3 +20,16 @@ export function uniquePathArrays(paths) {
20
20
  }
21
21
  return output;
22
22
  }
23
+ export async function runWithConcurrency(items, limit, fn) {
24
+ const results = new Array(items.length);
25
+ const queue = items.map((item, index) => ({ item, index }));
26
+ let next = 0;
27
+ async function worker() {
28
+ while (next < queue.length) {
29
+ const { item, index } = queue[next++];
30
+ results[index] = await fn(item);
31
+ }
32
+ }
33
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
34
+ return results;
35
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cve-lite-cli",
3
- "version": "1.12.1",
3
+ "version": "1.14.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": {