cve-lite-cli 1.2.0 → 1.4.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
@@ -2,6 +2,7 @@
2
2
  [![npm version](https://img.shields.io/npm/v/cve-lite-cli)](https://www.npmjs.com/package/cve-lite-cli)
3
3
  [![npm downloads](https://img.shields.io/npm/dm/cve-lite-cli)](https://www.npmjs.com/package/cve-lite-cli)
4
4
  [![CI](https://img.shields.io/github/actions/workflow/status/sonukapoor/cve-lite-cli/ci.yml?branch=main)](https://github.com/sonukapoor/cve-lite-cli/actions)
5
+ [![GitHub Marketplace](https://img.shields.io/badge/GitHub%20Marketplace-CVE%20Lite%20CLI-blue)](https://github.com/marketplace/actions/cve-lite-cli)
5
6
  [![License](https://img.shields.io/github/license/sonukapoor/cve-lite-cli)](https://github.com/sonukapoor/cve-lite-cli/blob/main/LICENSE)
6
7
 
7
8
  <div align="center">
@@ -32,6 +33,8 @@
32
33
  <a href="#what-is-cve-lite-cli">What is CVE Lite CLI</a><br/>
33
34
  <a href="#new-offline-advisory-db-support">Offline advisory DB support</a><br/>
34
35
  <a href="#why-offline-mode-matters">Why offline mode matters</a><br/>
36
+ <a href="docs/case-studies/owasp-juice-shop.md">OWASP Juice Shop case study</a><br/>
37
+ <a href="docs/case-studies/nestjs.md">NestJS case study</a><br/>
35
38
  <a href="#what-it-looks-like">What it looks like</a><br/>
36
39
  <a href="#why-this-tool-exists">Why this tool exists</a><br/>
37
40
  <a href="#project-scope-and-differentiation">Project scope and differentiation</a>
@@ -75,6 +78,8 @@ It is designed to be:
75
78
  - usable in enterprise and restricted-network environments
76
79
  - capable of zero-runtime-network scans through a local advisory database
77
80
 
81
+ For real-world remediation examples, see the [OWASP Juice Shop case study](docs/case-studies/owasp-juice-shop.md) and the [NestJS case study](docs/case-studies/nestjs.md).
82
+
78
83
  ## New: Offline advisory DB support
79
84
 
80
85
  CVE Lite CLI now supports a local advisory database workflow for teams that cannot allow runtime outbound advisory API calls.
@@ -111,6 +116,8 @@ Offline advisory DB support makes CVE Lite CLI more practical for:
111
116
 
112
117
  This is one of the most important differentiators in the project today because it improves both trust and adoptability, not just convenience.
113
118
 
119
+ The project also ships a reusable first-party GitHub Action, now available on the [GitHub Marketplace](https://github.com/marketplace/actions/cve-lite-cli), for teams that want a low-friction CI integration path.
120
+
114
121
  ## Quick start
115
122
 
116
123
  Install globally:
@@ -147,18 +154,21 @@ cve-lite /path/to/project --min-severity high
147
154
  # Recommended for CI logs when you want full context
148
155
  cve-lite /path/to/project --verbose
149
156
 
157
+ # Limit the scan to production dependencies where supported by the lockfile
158
+ cve-lite /path/to/project --prod-only
159
+
150
160
  # Fail a build on high severity and above
151
161
  cve-lite /path/to/project --fail-on high
152
162
 
153
163
  # JSON output
154
164
  cve-lite /path/to/project --json
155
165
 
156
- # SARIF output
157
- cve-lite /path/to/project --sarif --output reports/scan.sarif
158
-
159
166
  # Use a custom advisory endpoint
160
167
  cve-lite /path/to/project --osv-url https://security.company.internal/osv
161
168
 
169
+ # Show the CLI version
170
+ cve-lite --version
171
+
162
172
  # Build the local advisory DB for offline scans
163
173
  cve-lite advisories sync
164
174
 
@@ -201,14 +211,46 @@ cve-lite /path/to/project --offline
201
211
 
202
212
  CVE Lite CLI produces a clean, summary-first console view by default, designed for fast triage before release.
203
213
 
204
- For deeper investigation, running with `--verbose` provides full details, including dependency paths, parent upgrade guidance for transitive issues when available, a complete fix plan, and a detailed table view.
214
+ The default output is designed to stay concise while still surfacing the most important next step, including package-manager-aware fix commands when confident targets exist.
215
+
216
+ The most important section to look for in the output is:
217
+
218
+ ```text
219
+ 🛠 Copy And Run These Fix Commands
220
+ ```
221
+
222
+ That is one of the clearest differentiators in CVE Lite CLI. Instead of only showing advisories and severity counts, the tool tries to turn the findings into concrete commands developers can copy and run immediately.
223
+
224
+ For example, the tool can now suggest a concrete next command such as:
225
+
226
+ ```bash
227
+ npm install jsonwebtoken@4.2.2 express-jwt@2.1.0 sanitize-html@2.17.2
228
+ ```
229
+
230
+ The exact command adapts to the dependency file used for the scan, so `package-lock.json`, `pnpm-lock.yaml`, and `yarn.lock` can each produce a package-manager-specific suggestion.
231
+
232
+ For deeper investigation, running with `--verbose` provides the fuller remediation context, including the `Copy And Run These Fix Commands` section, dependency paths, parent upgrade guidance for transitive issues when available, a complete fix plan, skipped-item context for unresolved urgent findings, and a detailed table view.
205
233
 
206
234
  That is the core idea: install it, point it at your project, and immediately get a practical fix plan instead of a wall of raw advisories.
207
235
 
236
+ That local loop matters a lot in practice. In the NestJS case study, one dependency path required several `tar` upgrades in sequence as the dependency graph changed after each install. If a team only relied on pipeline scanners, they would likely:
237
+
238
+ 1. upgrade `tar`
239
+ 2. push a branch
240
+ 3. wait for CI or a scheduled scanner to report back
241
+ 4. learn they need to upgrade `tar` again
242
+ 5. repeat the full cycle
243
+
244
+ That kind of branch-and-pipeline remediation can easily burn hours or days for one CVE path, and in slower teams it can stretch into weeks. CVE Lite CLI brings that feedback loop down to a local scan-fix-rescan workflow that can happen in the same session, and its local caching keeps consecutive rescans extremely fast instead of redoing the same advisory lookups from scratch each time.
245
+
208
246
  The final status line also gives the scan a clear ending, which makes terminal use and screenshots easier to read.
209
247
 
210
248
  See the example below using OWASP Juice Shop for real output samples.
211
249
 
250
+ For real-world case studies, see the [OWASP Juice Shop case study](docs/case-studies/owasp-juice-shop.md) and the [NestJS case study](docs/case-studies/nestjs.md).
251
+
252
+ If you maintain an open-source JavaScript or TypeScript project and want CVE Lite CLI evaluated on it, open an issue and share the repository. Strong candidates may be turned into future public case studies.
253
+
212
254
  ## Example: Scanning OWASP Juice Shop (Real Output)
213
255
 
214
256
  CVE Lite CLI can be used against real-world vulnerable applications such as the OWASP Juice Shop.
@@ -231,11 +273,12 @@ cve-lite .
231
273
 
232
274
  Verbose examples:
233
275
 
276
+ Look for the `Copy And Run These Fix Commands` section in the screenshots below. That is the part of the output that turns findings into direct remediation steps.
277
+
234
278
  <p align="center">
235
279
  <img src="https://raw.githubusercontent.com/sonukapoor/cve-lite-cli/main/assets/verbose-output-1.png" alt="CVE Lite CLI verbose output screenshot" width="900"/>
236
280
  <img src="https://raw.githubusercontent.com/sonukapoor/cve-lite-cli/main/assets/verbose-output-2.png" alt="CVE Lite CLI verbose output screenshot" width="900"/>
237
281
  <img src="https://raw.githubusercontent.com/sonukapoor/cve-lite-cli/main/assets/verbose-output-3.png" alt="CVE Lite CLI verbose output screenshot" width="900"/>
238
- <img src="https://raw.githubusercontent.com/sonukapoor/cve-lite-cli/main/assets/verbose-output-4.png" alt="CVE Lite CLI verbose output screenshot" width="900"/>
239
282
  </p>
240
283
 
241
284
  ## Why this tool exists
@@ -265,7 +308,7 @@ The project emphasizes:
265
308
  - npm, pnpm, and Yarn lockfile support
266
309
  - direct vs transitive visibility
267
310
  - top-priority fixes and a suggested remediation plan
268
- - JSON and SARIF output for automation
311
+ - JSON output for automation
269
312
  - offline scanning through a local advisory database
270
313
  - configurable advisory endpoint support via `--osv-url` for internal proxies or mirrors
271
314
  - a small, reviewable runtime footprint
@@ -284,7 +327,20 @@ Its role is narrower and workflow-focused:
284
327
  - built to highlight top-priority fixes and a suggested remediation plan
285
328
  - intentionally lightweight in runtime footprint and setup
286
329
 
287
- This section is here to make the scope clear. CVE Lite CLI aims to complement the broader security ecosystem by being a practical, low-friction option for JS/TS dependency checks close to release time.
330
+ The closest OWASP comparisons are:
331
+
332
+ - **OWASP Dependency-Check**
333
+ A broader dependency analysis tool that covers many ecosystems and use cases beyond the lockfile-first JavaScript/TypeScript workflow emphasized here.
334
+
335
+ - **OWASP dep-scan**
336
+ A broader dependency and security analysis tool with wider language and environment coverage than this project is trying to provide.
337
+
338
+ - **OWASP Dependency-Track**
339
+ More SBOM- and platform-oriented, with a different operational model than a lightweight local CLI focused on developer checks close to release time.
340
+
341
+ CVE Lite CLI is intentionally narrower: it is JavaScript/TypeScript focused, lockfile-first, local-first, designed for fast local checks and simple CI gates, and built to surface direct vs transitive visibility, top-priority fixes, suggested remediation guidance, offline advisory DB workflows, and a small, reviewable runtime footprint.
342
+
343
+ This section is here to make the scope clear. CVE Lite CLI is meant to complement the broader OWASP ecosystem by serving a practical developer workflow close to release time.
288
344
 
289
345
  One of the clearest examples of that focus is offline support: CVE Lite CLI is built to let teams explicitly sync advisory data and then scan locally, instead of forcing every environment to depend on runtime outbound vulnerability API access.
290
346
 
@@ -395,7 +451,7 @@ CVE Lite CLI is designed as a **local-first, metadata-only** scanner. Unlike tra
395
451
  - **fast, low-friction workflow**
396
452
  Run it locally against a project without adopting a large security platform.
397
453
  - **practical remediation guidance**
398
- It does not stop at raw advisory output. It highlights top-priority fixes and suggests a fix plan.
454
+ It does not stop at raw advisory output. It highlights top-priority fixes, suggests a fix plan, and generates package-manager-aware commands developers can copy and run when confident upgrade targets exist.
399
455
  - **direct vs transitive visibility**
400
456
  The output makes it easier to see whether the risk comes from something you installed directly or from a nested package.
401
457
  - **developer-first**
@@ -437,11 +493,24 @@ Instead of only showing advisory IDs, the CLI reports:
437
493
 
438
494
  By default, the CLI now presents a cleaner summary-first view, with `--verbose` available for the full detailed output.
439
495
 
440
- ### 3. Top priority fixes
496
+ ### 3. Copy-and-run fix commands
497
+
498
+ This is one of the most important parts of the CLI output.
499
+
500
+ When confident upgrade targets exist, CVE Lite CLI shows a dedicated `Copy And Run These Fix Commands` section so developers can move straight from findings to action.
501
+
502
+ The commands are:
503
+
504
+ - package-manager-aware
505
+ - grouped by severity and fix type
506
+ - designed to be copied directly from the terminal
507
+ - shown before the deeper remediation detail in verbose mode
508
+
509
+ ### 4. Top priority fixes
441
510
 
442
511
  The CLI highlights the most important issues first, so developers can focus on the findings most likely to matter immediately.
443
512
 
444
- ### 4. Suggested fix plan
513
+ ### 5. Suggested fix plan
445
514
 
446
515
  CVE Lite CLI organizes likely remediation work into a practical sequence, such as:
447
516
 
@@ -450,24 +519,14 @@ CVE Lite CLI organizes likely remediation work into a practical sequence, such a
450
519
  - medium direct cleanup after that
451
520
  - duplicated vulnerable packages to consolidate
452
521
 
453
- ### 5. Parent package hints for transitive issues
522
+ ### 6. Parent package hints for transitive issues
454
523
 
455
524
  For transitive vulnerabilities, CVE Lite CLI can show the dependency path and, when it can determine one reliably, recommend the parent package upgrade to make. That makes the output more actionable than simply saying a nested package is vulnerable.
456
525
 
457
- ### 6. JSON output
526
+ ### 7. JSON output
458
527
 
459
528
  Structured JSON output makes it easier to integrate with scripts, logs, or pipeline artifacts.
460
529
 
461
- ### 7. SARIF output
462
-
463
- CVE Lite CLI supports SARIF (Static Analysis Results Interchange Format) output for security tooling and code-scanning workflows. SARIF is a standardized JSON-based format for security and code analysis results, which means CI systems, scanners, and code analysis platforms can all understand the same output without custom adapters. This is important because it makes CVE Lite CLI more than just a terminal tool: you can export findings into a format that fits modern DevSecOps workflows, archive results as build artifacts, and integrate vulnerability scans into automated release pipelines. For developers and teams, SARIF support helps security results travel cleanly from a local scan into CI/CD and other tooling, instead of being trapped in plain console output.
464
-
465
- Example:
466
-
467
- ```bash
468
- cve-lite /path/to/project --sarif --output reports/scan.sarif
469
- ```
470
-
471
530
  ### 8. CI-friendly behavior
472
531
 
473
532
  The CLI can be used in CI/CD pipelines and can fail builds based on severity thresholds.
@@ -557,7 +616,7 @@ jobs:
557
616
  runs-on: ubuntu-latest
558
617
  steps:
559
618
  - uses: actions/checkout@v4
560
- - uses: sonukapoor/cve-lite-cli@v1.1.1
619
+ - uses: sonukapoor/cve-lite-cli@v1.2.0
561
620
  with:
562
621
  verbose: "true"
563
622
  fail-on: high
@@ -576,7 +635,7 @@ jobs:
576
635
  runs-on: ubuntu-latest
577
636
  steps:
578
637
  - uses: actions/checkout@v4
579
- - uses: sonukapoor/cve-lite-cli@v1.1.1
638
+ - uses: sonukapoor/cve-lite-cli@v1.2.0
580
639
  with:
581
640
  sync-advisories: "true"
582
641
  offline: "true"
@@ -585,7 +644,7 @@ jobs:
585
644
  fail-on: high
586
645
  ```
587
646
 
588
- For CI, we recommend using `--verbose` so build logs include the full fix plan, dependency paths, and detailed table output when a scan fails.
647
+ For CI, we recommend using `--verbose` so build logs include the full fix plan, dependency paths, detailed table output, and suggested fix commands when a scan fails.
589
648
 
590
649
  Use it as a release gate in CI:
591
650
 
@@ -593,12 +652,6 @@ Use it as a release gate in CI:
593
652
  cve-lite . --verbose --fail-on high
594
653
  ```
595
654
 
596
- Export SARIF in CI:
597
-
598
- ```bash
599
- cve-lite . --verbose --sarif --output reports/scan.sarif
600
- ```
601
-
602
655
  ### Scripted automation
603
656
 
604
657
  Use JSON output for custom reporting:
package/dist/cli/args.js CHANGED
@@ -12,6 +12,10 @@ export function parseArgs(argv) {
12
12
  options.help = true;
13
13
  continue;
14
14
  }
15
+ if (arg === "-v" || arg === "--version") {
16
+ options.version = true;
17
+ continue;
18
+ }
15
19
  if (arg === "--output") {
16
20
  options.output = argv[++i];
17
21
  continue;
@@ -33,6 +37,10 @@ export function parseArgs(argv) {
33
37
  options.help = true;
34
38
  continue;
35
39
  }
40
+ if (arg === "-v" || arg === "--version") {
41
+ options.version = true;
42
+ continue;
43
+ }
36
44
  if (arg === "--json") {
37
45
  options.json = true;
38
46
  continue;
package/dist/cli/help.js CHANGED
@@ -1,6 +1,8 @@
1
1
  import { chalk } from "../utils/chalk.js";
2
+ import { getCliVersion } from "../utils/version-info.js";
3
+ const CLI_VERSION = getCliVersion();
2
4
  const CLI_BANNER = [
3
- `${chalk.green(">_")} ${chalk.bold.whiteBright("CVE Lite CLI")}`,
5
+ `${chalk.green(">_")} ${chalk.bold.whiteBright(`CVE Lite CLI (${CLI_VERSION})`)}`,
4
6
  chalk.gray("────────────────────────────────"),
5
7
  `${chalk.green("✔")} Scan dependencies`,
6
8
  `${chalk.green("✔")} Highlight critical issues`,
@@ -21,6 +23,8 @@ export function printHelp() {
21
23
  "",
22
24
  "Fast local-first CVE scanner for JS/TS projects using lockfiles + OSV",
23
25
  "",
26
+ `Version: ${CLI_VERSION}`,
27
+ "",
24
28
  "Usage:",
25
29
  " cve-lite [projectPath] [options]",
26
30
  " cve-lite advisories sync [options]",
@@ -42,6 +46,7 @@ export function printHelp() {
42
46
  "Advisory sync options:",
43
47
  " --output <path> Write the local advisory database to this path",
44
48
  "",
49
+ " -v, --version Show the CLI version",
45
50
  " -h, --help Show this help message"
46
51
  ];
47
52
  console.log(lines.join("\n"));
package/dist/index.js CHANGED
@@ -10,161 +10,186 @@ import { normalizeSeverity } from "./osv/severity.js";
10
10
  import { severityOrder } from "./constants.js";
11
11
  import { chalk } from "./utils/chalk.js";
12
12
  import { createSpinner } from "./output/spinner.js";
13
+ import { buildSuggestedFixCommandPlan } from "./remediation/fix-commands.js";
14
+ import { getCliVersion } from "./utils/version-info.js";
13
15
  import { logInfo, logWarn, printCacheSummary, serializeFinding } from "./output/formatters.js";
14
- import { printSummary, printActionSummary, printPriorityFixes, printFixPlan, printCoverage, printSkippedDependencies, printGroupSummary, printTable, printPathHints, printFinalStatus, printCompactOutput } from "./output/printers.js";
15
- const { command, options, projectArg } = parseArgs(process.argv.slice(2));
16
- if (options.help) {
17
- printHelp();
18
- process.exit(0);
16
+ import { printSummary, printActionSummary, printPriorityFixes, printFixPlan, printSuggestedFixCommands, printSuggestedFixCommandSkips, printCoverage, printSkippedDependencies, printGroupSummary, printTable, printPathHints, printFinalStatus, printCompactOutput } from "./output/printers.js";
17
+ let parsedArgs = null;
18
+ try {
19
+ parsedArgs = parseArgs(process.argv.slice(2));
19
20
  }
20
- const projectPath = path.resolve(projectArg || ".");
21
- const batchSize = Number(options.batchSize || 100);
22
- const searchDepth = Math.max(0, Number(options.searchDepth || 4));
23
- async function main() {
24
- if (!options.json) {
21
+ catch (error) {
22
+ const message = error instanceof Error ? error.message : String(error);
23
+ console.error(chalk.red(`Error: ${message}`));
24
+ console.error(chalk.gray("Run `cve-lite --help` to see supported options."));
25
+ process.exit(1);
26
+ }
27
+ if (parsedArgs) {
28
+ const { command, options, projectArg } = parsedArgs;
29
+ const cliVersion = getCliVersion();
30
+ if (options.help) {
31
+ printHelp();
32
+ process.exit(0);
33
+ }
34
+ else if (options.version) {
25
35
  printBanner();
36
+ process.exit(0);
26
37
  }
27
- if (command === "advisories-sync") {
28
- const spinner = createSpinner("Preparing advisory sync...", options);
29
- const usePlainProgressLogs = !process.stdout.isTTY || !!options.json;
30
- const result = await syncOsvAdvisories({
31
- outputPath: options.output,
32
- onProgress: event => {
33
- if (event.phase === "complete") {
34
- return;
35
- }
38
+ else {
39
+ const projectPath = path.resolve(projectArg || ".");
40
+ const batchSize = Number(options.batchSize || 100);
41
+ const searchDepth = Math.max(0, Number(options.searchDepth || 4));
42
+ async function main() {
43
+ if (!options.json) {
44
+ printBanner();
45
+ }
46
+ if (command === "advisories-sync") {
47
+ const spinner = createSpinner("Preparing advisory sync...", options);
48
+ const usePlainProgressLogs = !process.stdout.isTTY || !!options.json;
49
+ const result = await syncOsvAdvisories({
50
+ outputPath: options.output,
51
+ onProgress: event => {
52
+ if (event.phase === "complete") {
53
+ return;
54
+ }
55
+ if (usePlainProgressLogs) {
56
+ console.log(event.message);
57
+ return;
58
+ }
59
+ spinner.update(event.message);
60
+ },
61
+ });
36
62
  if (usePlainProgressLogs) {
37
- console.log(event.message);
38
- return;
63
+ console.log(`Advisory sync complete (${result.advisoryCount} records)`);
39
64
  }
40
- spinner.update(event.message);
41
- },
42
- });
43
- if (usePlainProgressLogs) {
44
- console.log(`Advisory sync complete (${result.advisoryCount} records)`);
45
- }
46
- else {
47
- spinner.succeed(`Advisory sync complete (${result.advisoryCount} records)`);
48
- }
49
- console.log(`${chalk.gray("Advisory database:")} synced ${result.advisoryCount} record${result.advisoryCount === 1 ? "" : "s"} to ${chalk.cyan(result.dbPath)}`);
50
- process.exit(0);
51
- return;
52
- }
53
- if ((options.offline || options.offlineDb) && options.osvUrl) {
54
- throw new Error("--offline/--offline-db cannot be used with --osv-url");
55
- }
56
- if (options.osvUrl) {
57
- try {
58
- new URL(options.osvUrl);
59
- }
60
- catch {
61
- throw new Error(`Invalid value for --osv-url: ${options.osvUrl}`);
62
- }
63
- }
64
- let advisorySourceLine;
65
- let advisoryDbFreshnessLine = null;
66
- let advisoryDbWarning = null;
67
- try {
68
- const advisorySource = createAdvisorySource({
69
- osvUrl: options.osvUrl,
70
- offline: options.offline,
71
- offlineDb: options.offlineDb,
72
- });
73
- advisorySourceLine = advisorySource.sourceLabel;
74
- if (advisorySource.offline) {
75
- const metadata = advisorySource.advisoryDbMetadata;
76
- advisoryDbFreshnessLine = formatAdvisoryDbFreshness(metadata?.lastSyncAt ?? null);
77
- if (advisorySource.advisoryDbIsStale) {
78
- advisoryDbWarning = metadata?.lastSyncAt
79
- ? "The local advisory DB appears stale. Re-run `cve-lite advisories sync` to refresh it."
80
- : "The local advisory DB has no recorded sync timestamp. Re-run `cve-lite advisories sync` to refresh it.";
65
+ else {
66
+ spinner.succeed(`Advisory sync complete (${result.advisoryCount} records)`);
67
+ }
68
+ console.log(`${chalk.gray("Advisory database:")} synced ${result.advisoryCount} record${result.advisoryCount === 1 ? "" : "s"} to ${chalk.cyan(result.dbPath)}`);
69
+ process.exit(0);
70
+ return;
81
71
  }
82
- }
83
- advisorySource.cleanup();
84
- }
85
- catch (error) {
86
- if (options.offline || options.offlineDb) {
87
- throw new Error(`Offline advisory database is not available: ${error instanceof Error ? error.message : String(error)}`);
88
- }
89
- throw error;
90
- }
91
- if (options.offline || options.offlineDb) {
92
- console.log(chalk.gray("Offline mode:") + " " + chalk.yellow("enabled") + " " + chalk.gray("(no external advisory calls will be made)"));
93
- }
94
- console.log(`${chalk.gray("Advisory source:")} ${formatAdvisorySourceLine(advisorySourceLine)}`);
95
- if (advisoryDbFreshnessLine) {
96
- console.log(`${chalk.gray("Advisory DB freshness:")} ${advisoryDbFreshnessLine}`);
97
- }
98
- if (advisoryDbWarning) {
99
- logWarn(advisoryDbWarning, options);
100
- }
101
- const scanInput = loadPackages(projectPath, !!options.prodOnly, searchDepth);
102
- const packages = scanInput.packages;
103
- logInfo(`Parsed ${packages.length} package${packages.length === 1 ? "" : "s"} from ${scanInput.source}${scanInput.filePath ? ` (${path.relative(projectPath, scanInput.filePath) || path.basename(scanInput.filePath)})` : ""}`, options);
104
- printCacheSummary(options.cacheDir, options);
105
- if (scanInput.warnings.length > 0) {
106
- for (const warning of scanInput.warnings) {
107
- logWarn(warning, options);
108
- }
109
- }
110
- if (packages.length === 0) {
111
- logWarn(buildNoPackagesMessage(projectPath), options);
112
- process.exit(0);
113
- return;
114
- }
115
- const findings = await scanPackages(packages, batchSize, options);
116
- const sorted = findings.sort((a, b) => severityOrder[b.severity] - severityOrder[a.severity]);
117
- const coverage = buildCoverageNotes(scanInput, !!options.offline || !!options.offlineDb);
118
- const minSeverity = normalizeSeverity(options.minSeverity || "medium");
119
- const tableFindings = options.all ? sorted : sorted.filter(f => severityOrder[f.severity] >= severityOrder[minSeverity]);
120
- if (options.json) {
121
- console.log(JSON.stringify({
122
- projectPath,
123
- mode: scanInput.mode,
124
- source: scanInput.source,
125
- packageCount: packages.length,
126
- findingCount: sorted.length,
127
- notes: [...scanInput.notes, ...coverage],
128
- warnings: scanInput.warnings,
129
- skippedDependencies: scanInput.skippedDependencies,
130
- findings: sorted.map(serializeFinding)
131
- }, null, 2));
132
- }
133
- else if (options.verbose) {
134
- // Verbose output - show all details
135
- printSummary(sorted, packages.length, scanInput);
136
- printActionSummary(sorted);
137
- printPriorityFixes(sorted);
138
- printFixPlan(sorted);
139
- printCoverage([...scanInput.notes, ...coverage]);
140
- if (scanInput.skippedDependencies.length > 0) {
141
- printSkippedDependencies(scanInput.skippedDependencies);
142
- }
143
- if (sorted.length > 0) {
144
- printGroupSummary(sorted);
145
- if (tableFindings.length > 0) {
146
- printTable(tableFindings, options.all ? null : minSeverity);
147
- printPathHints(tableFindings);
72
+ if ((options.offline || options.offlineDb) && options.osvUrl) {
73
+ throw new Error("--offline/--offline-db cannot be used with --osv-url");
74
+ }
75
+ if (options.osvUrl) {
76
+ try {
77
+ new URL(options.osvUrl);
78
+ }
79
+ catch {
80
+ throw new Error(`Invalid value for --osv-url: ${options.osvUrl}`);
81
+ }
82
+ }
83
+ let advisorySourceLine;
84
+ let advisoryDbFreshnessLine = null;
85
+ let advisoryDbWarning = null;
86
+ try {
87
+ const advisorySource = createAdvisorySource({
88
+ osvUrl: options.osvUrl,
89
+ offline: options.offline,
90
+ offlineDb: options.offlineDb,
91
+ });
92
+ advisorySourceLine = advisorySource.sourceLabel;
93
+ if (advisorySource.offline) {
94
+ const metadata = advisorySource.advisoryDbMetadata;
95
+ advisoryDbFreshnessLine = formatAdvisoryDbFreshness(metadata?.lastSyncAt ?? null);
96
+ if (advisorySource.advisoryDbIsStale) {
97
+ advisoryDbWarning = metadata?.lastSyncAt
98
+ ? "The local advisory DB appears stale. Re-run `cve-lite advisories sync` to refresh it."
99
+ : "The local advisory DB has no recorded sync timestamp. Re-run `cve-lite advisories sync` to refresh it.";
100
+ }
101
+ }
102
+ advisorySource.cleanup();
103
+ }
104
+ catch (error) {
105
+ if (options.offline || options.offlineDb) {
106
+ throw new Error(`Offline advisory database is not available: ${error instanceof Error ? error.message : String(error)}`);
107
+ }
108
+ throw error;
109
+ }
110
+ if (options.offline || options.offlineDb) {
111
+ console.log(chalk.gray("Offline mode:") + " " + chalk.yellow("enabled") + " " + chalk.gray("(no external advisory calls will be made)"));
112
+ }
113
+ console.log(`${chalk.gray("Advisory source:")} ${formatAdvisorySourceLine(advisorySourceLine)}`);
114
+ if (advisoryDbFreshnessLine) {
115
+ console.log(`${chalk.gray("Advisory DB freshness:")} ${advisoryDbFreshnessLine}`);
116
+ }
117
+ if (advisoryDbWarning) {
118
+ logWarn(advisoryDbWarning, options);
119
+ }
120
+ const scanInput = loadPackages(projectPath, !!options.prodOnly, searchDepth);
121
+ const packages = scanInput.packages;
122
+ logInfo(`Parsed ${packages.length} package${packages.length === 1 ? "" : "s"} from ${scanInput.source}${scanInput.filePath ? ` (${path.relative(projectPath, scanInput.filePath) || path.basename(scanInput.filePath)})` : ""}`, options);
123
+ printCacheSummary(options.cacheDir, options);
124
+ if (scanInput.warnings.length > 0) {
125
+ for (const warning of scanInput.warnings) {
126
+ logWarn(warning, options);
127
+ }
128
+ }
129
+ if (packages.length === 0) {
130
+ logWarn(buildNoPackagesMessage(projectPath), options);
131
+ process.exit(0);
132
+ return;
133
+ }
134
+ const findings = await scanPackages(packages, batchSize, options);
135
+ const sorted = findings.sort((a, b) => severityOrder[b.severity] - severityOrder[a.severity]);
136
+ const coverage = buildCoverageNotes(scanInput, !!options.offline || !!options.offlineDb);
137
+ const minSeverity = normalizeSeverity(options.minSeverity || "medium");
138
+ const tableFindings = options.all ? sorted : sorted.filter(f => severityOrder[f.severity] >= severityOrder[minSeverity]);
139
+ const suggestedFixCommands = buildSuggestedFixCommandPlan(sorted, scanInput);
140
+ if (options.json) {
141
+ console.log(JSON.stringify({
142
+ projectPath,
143
+ mode: scanInput.mode,
144
+ source: scanInput.source,
145
+ packageCount: packages.length,
146
+ findingCount: sorted.length,
147
+ suggestedFixCommands,
148
+ notes: [...scanInput.notes, ...coverage],
149
+ warnings: scanInput.warnings,
150
+ skippedDependencies: scanInput.skippedDependencies,
151
+ findings: sorted.map(serializeFinding)
152
+ }, null, 2));
153
+ }
154
+ else if (options.verbose) {
155
+ // Verbose output - show all details
156
+ printSummary(sorted, packages.length, scanInput);
157
+ printActionSummary(sorted);
158
+ printSuggestedFixCommands(sorted, scanInput);
159
+ printPriorityFixes(sorted);
160
+ printFixPlan(sorted);
161
+ printSuggestedFixCommandSkips(sorted, scanInput);
162
+ printCoverage([...scanInput.notes, ...coverage]);
163
+ if (scanInput.skippedDependencies.length > 0) {
164
+ printSkippedDependencies(scanInput.skippedDependencies);
165
+ }
166
+ if (sorted.length > 0) {
167
+ printGroupSummary(sorted);
168
+ if (tableFindings.length > 0) {
169
+ printTable(tableFindings, options.all ? null : minSeverity);
170
+ printPathHints(tableFindings);
171
+ }
172
+ else {
173
+ logInfo(`No findings met the table threshold of ${minSeverity}. Re-run with --all to show everything.`, options);
174
+ }
175
+ }
176
+ printFinalStatus(sorted);
148
177
  }
149
178
  else {
150
- logInfo(`No findings met the table threshold of ${minSeverity}. Re-run with --all to show everything.`, options);
179
+ // Simplified output - cleaner, focused view
180
+ printCompactOutput(sorted, scanInput);
151
181
  }
182
+ const failLevel = normalizeSeverity(options.failOn);
183
+ const shouldFail = sorted.some(f => severityOrder[f.severity] >= severityOrder[failLevel]);
184
+ process.exit(shouldFail ? 1 : 0);
185
+ return;
152
186
  }
153
- printFinalStatus(sorted);
154
- }
155
- else {
156
- // Simplified output - cleaner, focused view
157
- printCompactOutput(sorted);
187
+ main().catch((error) => {
188
+ console.error(chalk.red(`Error: ${error instanceof Error ? error.message : String(error)}`));
189
+ process.exit(1);
190
+ });
158
191
  }
159
- const failLevel = normalizeSeverity(options.failOn);
160
- const shouldFail = sorted.some(f => severityOrder[f.severity] >= severityOrder[failLevel]);
161
- process.exit(shouldFail ? 1 : 0);
162
- return;
163
192
  }
164
- main().catch((error) => {
165
- console.error(chalk.red(`Error: ${error instanceof Error ? error.message : String(error)}`));
166
- process.exit(1);
167
- });
168
193
  function formatAdvisorySourceLine(sourceLabel) {
169
194
  const match = sourceLabel.match(/^(.*) \((.*)\)$/);
170
195
  if (!match) {
@@ -94,6 +94,8 @@ export function serializeFinding(finding) {
94
94
  severity: finding.severity,
95
95
  relationship: finding.relationship,
96
96
  firstFixedVersion: finding.firstFixedVersion,
97
+ validatedFirstFixedVersion: finding.validatedFirstFixedVersion ?? null,
98
+ fixVersionValidationNote: finding.fixVersionValidationNote ?? null,
97
99
  recommendedAction: getRecommendedAction(finding),
98
100
  primaryParent: getPrimaryParent(finding),
99
101
  recommendedParentUpgrade: finding.recommendedParentUpgrade,
@@ -1,5 +1,6 @@
1
1
  import { chalk, stripAnsi } from "../utils/chalk.js";
2
2
  import { severityOrder } from "../constants.js";
3
+ import { buildSuggestedFixCommandPlan } from "../remediation/fix-commands.js";
3
4
  import { formatSeverityLabel, formatRelationshipLabel, getPrimaryParent, getRecommendedAction, summarizeRisk, summarizeNextAction } from "./formatters.js";
4
5
  export function printSummary(findings, packageCount, scanInput) {
5
6
  if (findings.length === 0) {
@@ -57,7 +58,7 @@ export function printPriorityFixes(findings) {
57
58
  });
58
59
  const top = scored.slice(0, 5);
59
60
  console.log("");
60
- console.log(chalk.bold.magenta("Top priority fixes"));
61
+ console.log(chalk.bold.magenta("🚀 Top priority fixes"));
61
62
  for (const finding of top) {
62
63
  console.log(`- ${chalk.whiteBright(finding.pkg.name)}@${chalk.white(finding.pkg.version)} (${formatSeverityLabel(finding.severity)}, ${formatRelationshipLabel(finding.relationship)})`);
63
64
  console.log(` Risk: ${summarizeRisk(finding)}`);
@@ -77,7 +78,7 @@ export function printFixPlan(findings) {
77
78
  const transitiveUrgent = findings.filter(f => f.relationship === "transitive" && (f.severity === "critical" || f.severity === "high"));
78
79
  const directMedium = findings.filter(f => f.relationship === "direct" && f.severity === "medium");
79
80
  console.log("");
80
- console.log(chalk.bold.green("Suggested fix plan"));
81
+ console.log(chalk.bold.green("📋 Suggested fix plan"));
81
82
  if (directUrgent.length > 0) {
82
83
  console.log(chalk.green("1) Upgrade these direct critical/high dependencies first:"));
83
84
  for (const finding of directUrgent.slice(0, 5)) {
@@ -114,6 +115,56 @@ export function printFixPlan(findings) {
114
115
  }
115
116
  }
116
117
  }
118
+ export function printSuggestedFixCommands(findings, scanInput) {
119
+ const plan = buildSuggestedFixCommandPlan(findings, scanInput);
120
+ if (!plan)
121
+ return;
122
+ if (plan.sections.length === 0)
123
+ return;
124
+ console.log("");
125
+ console.log(chalk.bold.yellow("🛠 Copy And Run These Fix Commands"));
126
+ console.log(`${chalk.gray("Detected package manager:")} ${chalk.cyan(plan.packageManager)} ${chalk.gray(`(${plan.sourceLabel})`)}`);
127
+ console.log(chalk.white(formatFixCommandSummary(plan)));
128
+ for (const section of plan.sections) {
129
+ console.log("");
130
+ console.log(colorFixSectionTitle(section.severity, section.title));
131
+ if (section.kind === "direct-adjusted") {
132
+ for (const target of section.targets) {
133
+ if (!target.adjustmentNote)
134
+ continue;
135
+ console.log(chalk.gray(` Note: ${target.adjustmentNote}`));
136
+ }
137
+ }
138
+ console.log(renderCommandCallout(section.command));
139
+ }
140
+ }
141
+ export function printSuggestedFixCommandSkips(findings, scanInput) {
142
+ const plan = buildSuggestedFixCommandPlan(findings, scanInput);
143
+ if (!plan || plan.skipped.length === 0)
144
+ return;
145
+ const unpublishable = plan.skipped.filter(skipped => skipped.reason.includes("not published on npm"));
146
+ const remaining = plan.skipped.filter(skipped => !skipped.reason.includes("not published on npm"));
147
+ if (unpublishable.length > 0) {
148
+ console.log("");
149
+ console.log(chalk.gray("Unpublishable fixed-version hints:"));
150
+ for (const skipped of unpublishable.slice(0, 5)) {
151
+ console.log(`- ${skipped.package}@${skipped.version}: ${skipped.reason}`);
152
+ }
153
+ if (unpublishable.length > 5) {
154
+ console.log(`- ...and ${unpublishable.length - 5} more`);
155
+ }
156
+ }
157
+ if (remaining.length > 0) {
158
+ console.log("");
159
+ console.log(chalk.gray("Not included automatically:"));
160
+ for (const skipped of remaining.slice(0, 5)) {
161
+ console.log(`- ${skipped.package}@${skipped.version}: ${skipped.reason}`);
162
+ }
163
+ if (remaining.length > 5) {
164
+ console.log(`- ...and ${remaining.length - 5} more`);
165
+ }
166
+ }
167
+ }
117
168
  export function printCoverage(notes) {
118
169
  if (notes.length === 0)
119
170
  return;
@@ -224,7 +275,7 @@ function truncate(value, width) {
224
275
  return value;
225
276
  return plain.slice(0, Math.max(0, width - 1)) + "…";
226
277
  }
227
- export function printCompactOutput(findings) {
278
+ export function printCompactOutput(findings, scanInput) {
228
279
  console.log("");
229
280
  if (findings.length === 0) {
230
281
  console.log(chalk.greenBright("✔ Scan complete. No known vulnerabilities found."));
@@ -265,11 +316,34 @@ export function printCompactOutput(findings) {
265
316
  }
266
317
  console.log("");
267
318
  }
319
+ const plan = scanInput ? buildSuggestedFixCommandPlan(findings, scanInput) : null;
320
+ if (plan) {
321
+ if (plan?.sections.length) {
322
+ console.log("────────────────────────────────");
323
+ console.log(chalk.bold.yellow("🛠 Copy And Run These Fix Commands"));
324
+ console.log("────────────────────────────────\n");
325
+ console.log(`${chalk.gray("Detected package manager:")} ${chalk.cyan(plan.packageManager)} ${chalk.gray(`(${plan.sourceLabel})`)}`);
326
+ console.log(formatFixCommandSummary(plan));
327
+ console.log("");
328
+ for (const section of plan.sections.slice(0, 3)) {
329
+ console.log(`${section.title}`);
330
+ if (section.kind === "direct-adjusted") {
331
+ for (const target of section.targets) {
332
+ if (!target.adjustmentNote)
333
+ continue;
334
+ console.log(chalk.gray(` Note: ${target.adjustmentNote}`));
335
+ }
336
+ }
337
+ console.log(renderCommandCallout(section.command));
338
+ console.log("");
339
+ }
340
+ }
341
+ }
268
342
  // Top Priority Fix section
269
343
  if (urgentFindings.length > 0) {
270
344
  const topFinding = urgentFindings[0];
271
345
  console.log("────────────────────────────────");
272
- console.log(chalk.bold("🚀 Top Priority Fix"));
346
+ console.log(chalk.bold("🚀 Top Priority Issue"));
273
347
  console.log("────────────────────────────────\n");
274
348
  if (topFinding.relationship === "direct" && topFinding.firstFixedVersion) {
275
349
  console.log(`Upgrade ${chalk.whiteBright(topFinding.pkg.name)} → ${topFinding.firstFixedVersion}`);
@@ -289,6 +363,16 @@ export function printCompactOutput(findings) {
289
363
  console.log(`Upgrade parent chain to resolve ${chalk.whiteBright(topFinding.pkg.name)}`);
290
364
  }
291
365
  }
366
+ if (plan) {
367
+ const topFindingCommand = findSuggestedCommandForFinding(plan, topFinding);
368
+ if (topFindingCommand) {
369
+ console.log(chalk.gray("Command:"));
370
+ console.log(renderCommandCallout(topFindingCommand));
371
+ }
372
+ else {
373
+ console.log(chalk.gray("No confident automatic command is available for this issue yet."));
374
+ }
375
+ }
292
376
  console.log("");
293
377
  }
294
378
  // Summary
@@ -332,3 +416,54 @@ export function printCompactOutput(findings) {
332
416
  console.log(chalk.gray(`Run with ${chalk.whiteBright("--verbose")} for fix plan, paths, and full table.`));
333
417
  console.log("");
334
418
  }
419
+ function colorFixSectionTitle(severity, title) {
420
+ if (severity === "critical")
421
+ return chalk.redBright(title);
422
+ if (severity === "high")
423
+ return chalk.magenta(title);
424
+ if (severity === "medium")
425
+ return chalk.yellow(title);
426
+ if (severity === "low")
427
+ return chalk.green(title);
428
+ return chalk.gray(title);
429
+ }
430
+ function formatFixCommandSummary(plan) {
431
+ if (!plan)
432
+ return "";
433
+ const packageCount = plan.targets.length;
434
+ const sectionCount = plan.sections.length;
435
+ const severityCounts = new Map();
436
+ for (const section of plan.sections) {
437
+ severityCounts.set(section.severity, (severityCounts.get(section.severity) ?? 0) + 1);
438
+ }
439
+ const severitySummary = ["critical", "high", "medium", "low", "unknown"]
440
+ .filter(severity => (severityCounts.get(severity) ?? 0) > 0)
441
+ .map(severity => `${severityCounts.get(severity)} ${severity}`)
442
+ .join(", ");
443
+ const packageLabel = packageCount === 1 ? "package" : "packages";
444
+ const sectionLabel = sectionCount === 1 ? "group" : "groups";
445
+ return `${sectionCount} command ${sectionLabel} ready across ${packageCount} ${packageLabel}${severitySummary ? ` (${severitySummary})` : ""}.`;
446
+ }
447
+ function renderCommandCallout(command) {
448
+ return chalk.bold.cyan(`> ${command}`);
449
+ }
450
+ function findSuggestedCommandForFinding(plan, finding) {
451
+ const target = plan.targets.find(item => {
452
+ if (finding.recommendedParentUpgrade) {
453
+ return (item.package === finding.recommendedParentUpgrade.package &&
454
+ item.targetVersion === finding.recommendedParentUpgrade.targetVersion);
455
+ }
456
+ const directTarget = finding.validatedFirstFixedVersion ?? finding.firstFixedVersion;
457
+ return item.package === finding.pkg.name && item.targetVersion === directTarget;
458
+ });
459
+ if (!target)
460
+ return null;
461
+ return `${packageManagerCommandPrefix(plan.packageManager)} ${target.package}@${target.targetVersion}`;
462
+ }
463
+ function packageManagerCommandPrefix(packageManager) {
464
+ if (packageManager === "npm")
465
+ return "npm install";
466
+ if (packageManager === "pnpm")
467
+ return "pnpm add";
468
+ return "yarn add";
469
+ }
@@ -0,0 +1,267 @@
1
+ import { severityOrder } from "../constants.js";
2
+ import { compareVersions, looksLikeVersion } from "../utils/version.js";
3
+ export function buildSuggestedFixCommandPlan(findings, scanInput) {
4
+ const packageManager = inferPackageManager(scanInput);
5
+ if (!packageManager)
6
+ return null;
7
+ const prioritizedFindings = [...findings]
8
+ .filter(f => f.severity === "critical" || f.severity === "high")
9
+ .sort((a, b) => {
10
+ const sevDelta = severityOrder[b.severity] - severityOrder[a.severity];
11
+ if (sevDelta !== 0)
12
+ return sevDelta;
13
+ const relScore = (finding) => finding.relationship === "direct" ? 1 : 0;
14
+ const relDelta = relScore(b) - relScore(a);
15
+ if (relDelta !== 0)
16
+ return relDelta;
17
+ return a.pkg.name.localeCompare(b.pkg.name);
18
+ });
19
+ const targetsByPackage = new Map();
20
+ const skippedByKey = new Map();
21
+ const orderedFindings = [
22
+ ...prioritizedFindings,
23
+ ...findings
24
+ .filter(f => f.severity !== "critical" && f.severity !== "high")
25
+ .sort((a, b) => {
26
+ const sevDelta = severityOrder[b.severity] - severityOrder[a.severity];
27
+ if (sevDelta !== 0)
28
+ return sevDelta;
29
+ const relScore = (finding) => finding.relationship === "direct" ? 1 : 0;
30
+ const relDelta = relScore(b) - relScore(a);
31
+ if (relDelta !== 0)
32
+ return relDelta;
33
+ return a.pkg.name.localeCompare(b.pkg.name);
34
+ }),
35
+ ];
36
+ for (const finding of orderedFindings) {
37
+ const urgent = finding.severity === "critical" || finding.severity === "high";
38
+ if (finding.relationship === "direct" || finding.relationship === "unknown") {
39
+ const hasValidatedField = Object.prototype.hasOwnProperty.call(finding, "validatedFirstFixedVersion");
40
+ const directTarget = finding.validatedFirstFixedVersion ?? finding.firstFixedVersion;
41
+ if (directTarget &&
42
+ isUpgradeTarget(finding.pkg.version, directTarget) &&
43
+ (!hasValidatedField || finding.validatedFirstFixedVersion !== null)) {
44
+ upsertTarget(targetsByPackage, {
45
+ package: finding.pkg.name,
46
+ targetVersion: directTarget,
47
+ kind: "direct",
48
+ urgent,
49
+ severity: finding.severity,
50
+ adjusted: Boolean(finding.fixVersionValidationNote &&
51
+ finding.validatedFirstFixedVersion &&
52
+ finding.validatedFirstFixedVersion !== finding.firstFixedVersion),
53
+ adjustmentNote: finding.fixVersionValidationNote &&
54
+ finding.validatedFirstFixedVersion &&
55
+ finding.validatedFirstFixedVersion !== finding.firstFixedVersion
56
+ ? finding.fixVersionValidationNote
57
+ : null,
58
+ reason: `Direct upgrade target for ${finding.pkg.name}@${finding.pkg.version}`,
59
+ });
60
+ }
61
+ else if (finding.fixVersionValidationNote) {
62
+ skippedByKey.set(`${finding.relationship}:${finding.pkg.name}@${finding.pkg.version}`, {
63
+ package: finding.pkg.name,
64
+ version: finding.pkg.version,
65
+ relationship: finding.relationship,
66
+ reason: finding.fixVersionValidationNote,
67
+ });
68
+ }
69
+ else if (finding.firstFixedVersion) {
70
+ skippedByKey.set(`${finding.relationship}:${finding.pkg.name}@${finding.pkg.version}`, {
71
+ package: finding.pkg.name,
72
+ version: finding.pkg.version,
73
+ relationship: finding.relationship,
74
+ reason: `Fixed-version hint ${directTarget} is not an upgrade from installed ${finding.pkg.version}.`,
75
+ });
76
+ }
77
+ else {
78
+ skippedByKey.set(`${finding.relationship}:${finding.pkg.name}@${finding.pkg.version}`, {
79
+ package: finding.pkg.name,
80
+ version: finding.pkg.version,
81
+ relationship: finding.relationship,
82
+ reason: urgent
83
+ ? "No safe upgrade target is known for this urgent direct dependency."
84
+ : "No safe upgrade target is known for this direct dependency.",
85
+ });
86
+ }
87
+ continue;
88
+ }
89
+ if (finding.relationship === "transitive" &&
90
+ finding.recommendedParentUpgrade &&
91
+ isUpgradeTarget(finding.recommendedParentUpgrade.currentVersion, finding.recommendedParentUpgrade.targetVersion)) {
92
+ upsertTarget(targetsByPackage, {
93
+ package: finding.recommendedParentUpgrade.package,
94
+ targetVersion: finding.recommendedParentUpgrade.targetVersion,
95
+ kind: "parent-upgrade",
96
+ urgent,
97
+ severity: finding.severity,
98
+ adjusted: false,
99
+ adjustmentNote: null,
100
+ reason: `Parent upgrade for vulnerable ${finding.pkg.name}@${finding.pkg.version}`,
101
+ });
102
+ continue;
103
+ }
104
+ if (finding.relationship === "transitive" && finding.recommendedParentUpgrade) {
105
+ skippedByKey.set(`${finding.relationship}:${finding.pkg.name}@${finding.pkg.version}`, {
106
+ package: finding.pkg.name,
107
+ version: finding.pkg.version,
108
+ relationship: finding.relationship,
109
+ reason: `Suggested parent target ${finding.recommendedParentUpgrade.package}@${finding.recommendedParentUpgrade.targetVersion} is not an upgrade from installed ${finding.recommendedParentUpgrade.currentVersion}.`,
110
+ });
111
+ continue;
112
+ }
113
+ skippedByKey.set(`${finding.relationship}:${finding.pkg.name}@${finding.pkg.version}`, {
114
+ package: finding.pkg.name,
115
+ version: finding.pkg.version,
116
+ relationship: finding.relationship,
117
+ reason: finding.relationship === "transitive"
118
+ ? "No specific parent upgrade target was found for this transitive issue."
119
+ : "No confident automatic fix command could be generated for this issue.",
120
+ });
121
+ }
122
+ const targets = [...targetsByPackage.values()].sort((a, b) => {
123
+ const sevDelta = severityOrder[b.severity] - severityOrder[a.severity];
124
+ if (sevDelta !== 0)
125
+ return sevDelta;
126
+ const urgentDelta = Number(b.urgent) - Number(a.urgent);
127
+ if (urgentDelta !== 0)
128
+ return urgentDelta;
129
+ const kindScore = (target) => target.kind === "direct" ? 1 : 0;
130
+ const kindDelta = kindScore(b) - kindScore(a);
131
+ if (kindDelta !== 0)
132
+ return kindDelta;
133
+ return a.package.localeCompare(b.package);
134
+ });
135
+ const skipped = [...skippedByKey.values()].sort((a, b) => a.package.localeCompare(b.package));
136
+ const sections = buildSections(targets, packageManager);
137
+ const command = targets.length > 0
138
+ ? `${commandPrefix(packageManager)} ${targets.map(target => `${target.package}@${target.targetVersion}`).join(" ")}`
139
+ : null;
140
+ return {
141
+ packageManager,
142
+ sourceLabel: packageManagerSourceLabel(scanInput),
143
+ command,
144
+ sections,
145
+ targets,
146
+ skipped,
147
+ };
148
+ }
149
+ function inferPackageManager(scanInput) {
150
+ if (scanInput.source === "package-lock")
151
+ return "npm";
152
+ if (scanInput.source === "pnpm-lock")
153
+ return "pnpm";
154
+ if (scanInput.source === "yarn-lock")
155
+ return "yarn";
156
+ return null;
157
+ }
158
+ function commandPrefix(packageManager) {
159
+ if (packageManager === "npm")
160
+ return "npm install";
161
+ if (packageManager === "pnpm")
162
+ return "pnpm add";
163
+ return "yarn add";
164
+ }
165
+ function packageManagerSourceLabel(scanInput) {
166
+ if (scanInput.filePath) {
167
+ return scanInput.filePath.split(/[/\\]/).pop() ?? scanInput.source;
168
+ }
169
+ if (scanInput.source === "package-lock")
170
+ return "package-lock.json";
171
+ if (scanInput.source === "pnpm-lock")
172
+ return "pnpm-lock.yaml";
173
+ if (scanInput.source === "yarn-lock")
174
+ return "yarn.lock";
175
+ return scanInput.source;
176
+ }
177
+ function upsertTarget(targetsByPackage, next) {
178
+ const existing = targetsByPackage.get(next.package);
179
+ if (!existing) {
180
+ targetsByPackage.set(next.package, next);
181
+ return;
182
+ }
183
+ const merged = {
184
+ ...existing,
185
+ urgent: existing.urgent || next.urgent,
186
+ severity: severityOrder[next.severity] > severityOrder[existing.severity] ? next.severity : existing.severity,
187
+ adjusted: existing.adjusted || next.adjusted,
188
+ adjustmentNote: existing.adjustmentNote ?? next.adjustmentNote ?? null,
189
+ kind: existing.kind === "direct" || next.kind === "direct" ? "direct" : "parent-upgrade",
190
+ };
191
+ if (looksLikeVersion(existing.targetVersion) && looksLikeVersion(next.targetVersion)) {
192
+ if (compareVersions(next.targetVersion, existing.targetVersion) > 0) {
193
+ merged.targetVersion = next.targetVersion;
194
+ merged.reason = next.reason;
195
+ }
196
+ targetsByPackage.set(next.package, merged);
197
+ return;
198
+ }
199
+ if (next.kind === "direct" && existing.kind !== "direct") {
200
+ merged.targetVersion = next.targetVersion;
201
+ merged.reason = next.reason;
202
+ merged.adjustmentNote = next.adjustmentNote ?? merged.adjustmentNote;
203
+ }
204
+ targetsByPackage.set(next.package, merged);
205
+ }
206
+ function isUpgradeTarget(currentVersion, targetVersion) {
207
+ if (!currentVersion || !targetVersion || currentVersion === targetVersion)
208
+ return false;
209
+ if (looksLikeVersion(currentVersion) && looksLikeVersion(targetVersion)) {
210
+ return compareVersions(targetVersion, currentVersion) > 0;
211
+ }
212
+ return true;
213
+ }
214
+ function buildSections(targets, packageManager) {
215
+ const groups = [];
216
+ const commandForTargets = (items) => `${commandPrefix(packageManager)} ${items.map(target => `${target.package}@${target.targetVersion}`).join(" ")}`;
217
+ const sectionOrder = [
218
+ { kind: "urgent", severity: "critical" },
219
+ { kind: "urgent", severity: "high" },
220
+ { kind: "direct", severity: "medium" },
221
+ { kind: "direct", severity: "low" },
222
+ { kind: "direct", severity: "unknown" },
223
+ { kind: "direct-adjusted", severity: "medium" },
224
+ { kind: "direct-adjusted", severity: "low" },
225
+ { kind: "direct-adjusted", severity: "unknown" },
226
+ { kind: "parent-upgrade", severity: "medium" },
227
+ { kind: "parent-upgrade", severity: "low" },
228
+ { kind: "parent-upgrade", severity: "unknown" },
229
+ ];
230
+ for (const entry of sectionOrder) {
231
+ const sectionTargets = targets.filter(target => {
232
+ const targetKind = target.urgent ? "urgent" : target.adjusted ? "direct-adjusted" : target.kind;
233
+ return targetKind === entry.kind && target.severity === entry.severity;
234
+ });
235
+ if (sectionTargets.length === 0)
236
+ continue;
237
+ groups.push({
238
+ key: `${entry.kind}:${entry.severity}`,
239
+ kind: entry.kind,
240
+ severity: entry.severity,
241
+ title: buildSectionTitle(entry.kind, entry.severity),
242
+ command: commandForTargets(sectionTargets),
243
+ targets: sectionTargets,
244
+ });
245
+ }
246
+ return groups;
247
+ }
248
+ function buildSectionTitle(kind, severity) {
249
+ const severityTitle = severity === "unknown"
250
+ ? "Unknown severity"
251
+ : `${capitalize(severity)} severity`;
252
+ if (kind === "urgent") {
253
+ return severity === "critical"
254
+ ? "Critical severity fix commands"
255
+ : "High severity fix commands";
256
+ }
257
+ if (kind === "direct") {
258
+ return `${severityTitle} direct fixes`;
259
+ }
260
+ if (kind === "direct-adjusted") {
261
+ return `${severityTitle} direct fixes (registry-adjusted)`;
262
+ }
263
+ return `${severityTitle} parent upgrades`;
264
+ }
265
+ function capitalize(value) {
266
+ return value.charAt(0).toUpperCase() + value.slice(1);
267
+ }
@@ -0,0 +1,67 @@
1
+ import { compareVersions, looksLikeVersion } from "../utils/version.js";
2
+ const packumentCache = new Map();
3
+ const DEFAULT_NPM_REGISTRY_URL = "https://registry.npmjs.org";
4
+ export function clearPackumentCache() {
5
+ packumentCache.clear();
6
+ }
7
+ export async function fetchPackument(packageName) {
8
+ if (packumentCache.has(packageName)) {
9
+ return packumentCache.get(packageName) ?? null;
10
+ }
11
+ const url = `${DEFAULT_NPM_REGISTRY_URL}/${encodeURIComponent(packageName)
12
+ .replace(/%40/g, "@")
13
+ .replace(/%2F/g, "/")}`;
14
+ try {
15
+ const response = await fetch(url);
16
+ if (!response.ok) {
17
+ packumentCache.set(packageName, null);
18
+ return null;
19
+ }
20
+ const json = (await response.json());
21
+ packumentCache.set(packageName, json);
22
+ return json;
23
+ }
24
+ catch {
25
+ packumentCache.set(packageName, null);
26
+ return null;
27
+ }
28
+ }
29
+ export async function packageVersionExists(packageName, version) {
30
+ const packument = await fetchPackument(packageName);
31
+ if (!packument)
32
+ return null;
33
+ return Boolean(packument.versions && version in packument.versions);
34
+ }
35
+ export async function resolvePublishedFixVersion(packageName, fixedVersionHint) {
36
+ const packument = await fetchPackument(packageName);
37
+ if (!packument) {
38
+ return {
39
+ resolvedVersion: null,
40
+ note: `Fixed-version hint ${fixedVersionHint} could not be verified against the npm registry for ${packageName}.`,
41
+ verified: false,
42
+ };
43
+ }
44
+ const publishedVersions = Object.keys(packument.versions ?? {})
45
+ .filter(looksLikeVersion)
46
+ .sort(compareVersions);
47
+ if (publishedVersions.includes(fixedVersionHint)) {
48
+ return {
49
+ resolvedVersion: fixedVersionHint,
50
+ note: null,
51
+ verified: true,
52
+ };
53
+ }
54
+ const nearestPublishedVersion = publishedVersions.find(version => compareVersions(version, fixedVersionHint) >= 0) ?? null;
55
+ if (nearestPublishedVersion) {
56
+ return {
57
+ resolvedVersion: nearestPublishedVersion,
58
+ note: `Advisory fixed-version hint ${fixedVersionHint} is not published on npm for ${packageName}; using nearest published version ${nearestPublishedVersion}.`,
59
+ verified: true,
60
+ };
61
+ }
62
+ return {
63
+ resolvedVersion: null,
64
+ note: `Advisory fixed-version hint ${fixedVersionHint} is not published on npm for ${packageName}, and no published version >= ${fixedVersionHint} was found.`,
65
+ verified: true,
66
+ };
67
+ }
@@ -1,6 +1,5 @@
1
1
  import { compareVersions, looksLikeVersion } from "../utils/version.js";
2
- const packumentCache = new Map();
3
- const DEFAULT_NPM_REGISTRY_URL = "https://registry.npmjs.org";
2
+ import { fetchPackument } from "./npm-registry.js";
4
3
  export async function resolveRecommendedParentUpgrade(finding, packages) {
5
4
  if (finding.relationship !== "transitive")
6
5
  return null;
@@ -132,22 +131,6 @@ async function findUpgradeForImmediateIntermediate(args) {
132
131
  }
133
132
  return null;
134
133
  }
135
- async function fetchPackument(packageName) {
136
- if (packumentCache.has(packageName)) {
137
- return packumentCache.get(packageName) ?? null;
138
- }
139
- const url = `${DEFAULT_NPM_REGISTRY_URL}/${encodeURIComponent(packageName)
140
- .replace(/%40/g, "@")
141
- .replace(/%2F/g, "/")}`;
142
- const response = await fetch(url);
143
- if (!response.ok) {
144
- packumentCache.set(packageName, null);
145
- return null;
146
- }
147
- const json = (await response.json());
148
- packumentCache.set(packageName, json);
149
- return json;
150
- }
151
134
  function versionSatisfiesRange(version, rawRange) {
152
135
  const range = rawRange.trim();
153
136
  if (!range)
package/dist/scanner.js CHANGED
@@ -8,6 +8,7 @@ import { LocalAdvisorySource } from "./advisory/local-advisory-source.js";
8
8
  import { LocalAdvisoryDatabase } from "./advisory/local-db.js";
9
9
  import { ADVISORY_DB_STALE_AFTER_MS, getDefaultAdvisoryDbPath } from "./advisory/osv-sync.js";
10
10
  import { resolveRecommendedParentUpgrade } from "./remediation/parent-upgrade.js";
11
+ import { resolvePublishedFixVersion } from "./remediation/npm-registry.js";
11
12
  export function createAdvisorySource(options) {
12
13
  const offline = !!options?.offline || !!options?.offlineDb;
13
14
  if (offline) {
@@ -174,9 +175,14 @@ export async function scanPackages(packages, batchSize, options) {
174
175
  dependencyPaths,
175
176
  relationship,
176
177
  firstFixedVersion,
178
+ validatedFirstFixedVersion: null,
179
+ fixVersionValidationNote: null,
177
180
  recommendedParentUpgrade: undefined,
178
181
  };
179
182
  });
183
+ if (!offline) {
184
+ await validateDirectFixTargets(findings);
185
+ }
180
186
  for (const finding of findings) {
181
187
  if (finding.relationship !== "transitive" || offline)
182
188
  continue;
@@ -197,6 +203,18 @@ export async function scanPackages(packages, batchSize, options) {
197
203
  sourceContext.cleanup();
198
204
  }
199
205
  }
206
+ async function validateDirectFixTargets(findings) {
207
+ const directCandidates = findings.filter(finding => (finding.relationship === "direct" || finding.relationship === "unknown") &&
208
+ Boolean(finding.firstFixedVersion));
209
+ for (const finding of directCandidates) {
210
+ const targetVersion = finding.firstFixedVersion;
211
+ if (!targetVersion)
212
+ continue;
213
+ const resolution = await resolvePublishedFixVersion(finding.pkg.name, targetVersion);
214
+ finding.validatedFirstFixedVersion = resolution.resolvedVersion;
215
+ finding.fixVersionValidationNote = resolution.note;
216
+ }
217
+ }
200
218
  function isAdvisoryDbStale(metadata) {
201
219
  if (!metadata.lastSyncAt) {
202
220
  return true;
@@ -0,0 +1,12 @@
1
+ import fs from "node:fs";
2
+ export function getCliVersion() {
3
+ try {
4
+ const packageJsonPath = new URL("../../package.json", import.meta.url);
5
+ const raw = fs.readFileSync(packageJsonPath, "utf8");
6
+ const parsed = JSON.parse(raw);
7
+ return parsed.version ?? "0.0.0";
8
+ }
9
+ catch {
10
+ return "0.0.0";
11
+ }
12
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cve-lite-cli",
3
- "version": "1.2.0",
3
+ "version": "1.4.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": {