cve-lite-cli 1.0.4 → 1.0.6

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
@@ -1,5 +1,5 @@
1
1
  <div align="center">
2
- <img src="./assets/logo-with-title.png" alt="CVE Lite CLI" width="320"/>
2
+ <img src="https://github.com/sonukapoor/cve-lite-cli/blob/main/assets/logo-with-title.png" alt="CVE Lite CLI" width="320"/>
3
3
 
4
4
  <h1>CVE Lite CLI</h1>
5
5
  <p>Fast, developer-friendly vulnerability scanning for JavaScript and TypeScript projects.</p>
@@ -10,7 +10,7 @@
10
10
  <a href="#quick-start">Quick Start</a> •
11
11
  <a href="#features">Features</a> •
12
12
  <a href="#usage">Usage</a> •
13
- <a href="CONTRIBUTING.md">Contributing</a>
13
+ <a href="https://github.com/sonukapoor/cve-lite-cli/blob/main/src/docs/CONTRIBUTING.md">Contributing</a>
14
14
  </p>
15
15
 
16
16
  </div>
@@ -65,13 +65,16 @@ cve-lite /path/to/project --json
65
65
 
66
66
  # SARIF output
67
67
  cve-lite /path/to/project --sarif --output reports/scan.sarif
68
+
69
+ # Use a custom advisory endpoint
70
+ cve-lite /path/to/project --osv-url https://security.company.internal/osv
68
71
  ```
69
72
 
70
73
  ## What it looks like
71
74
 
72
75
  CVE Lite CLI produces a clean, summary-first console view by default, designed for fast triage before release.
73
76
 
74
- For deeper investigation, running with `--verbose` provides full details, including dependency paths, a complete fix plan, and a detailed table view.
77
+ 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.
75
78
 
76
79
  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.
77
80
 
@@ -96,16 +99,16 @@ cve-lite .
96
99
  ```
97
100
 
98
101
  <p align="center">
99
- <img src="./assets/default-output.png" alt="CVE Lite CLI default output screenshot" width="900"/>
102
+ <img src="https://github.com/sonukapoor/cve-lite-cli/blob/main/assets/default-output.png" alt="CVE Lite CLI default output screenshot" width="900"/>
100
103
  </p>
101
104
 
102
105
  Verbose examples:
103
106
 
104
107
  <p align="center">
105
- <img src="./assets/verbose-output-1.png" alt="CVE Lite CLI verbose output screenshot" width="900"/>
106
- <img src="./assets/verbose-output-2.png" alt="CVE Lite CLI verbose output screenshot" width="900"/>
107
- <img src="./assets/verbose-output-3.png" alt="CVE Lite CLI verbose output screenshot" width="900"/>
108
- <img src="./assets/verbose-output-4.png" alt="CVE Lite CLI verbose output screenshot" width="900"/>
108
+ <img src="https://github.com/sonukapoor/cve-lite-cli/blob/main/assets/verbose-output-1.png" alt="CVE Lite CLI verbose output screenshot" width="900"/>
109
+ <img src="https://github.com/sonukapoor/cve-lite-cli/blob/main/assets/verbose-output-2.png" alt="CVE Lite CLI verbose output screenshot" width="900"/>
110
+ <img src="https://github.com/sonukapoor/cve-lite-cli/blob/main/assets/verbose-output-3.png" alt="CVE Lite CLI verbose output screenshot" width="900"/>
111
+ <img src="https://github.com/sonukapoor/cve-lite-cli/blob/main/assets/verbose-output-4.png" alt="CVE Lite CLI verbose output screenshot" width="900"/>
109
112
  </p>
110
113
 
111
114
  ## Why this tool exists
@@ -136,6 +139,7 @@ The project emphasizes:
136
139
  - direct vs transitive visibility
137
140
  - top-priority fixes and a suggested remediation plan
138
141
  - JSON and SARIF output for automation
142
+ - configurable advisory endpoint support via `--osv-url` for internal proxies or mirrors
139
143
  - a small, reviewable runtime footprint
140
144
 
141
145
  That narrow scope is deliberate. CVE Lite CLI is not trying to be a full application security platform or a broad multi-surface scanner. It is trying to be a lightweight, understandable, developer-first tool for teams that want practical vulnerability scanning without extra cost or complexity.
@@ -154,13 +158,44 @@ Its role is narrower and workflow-focused:
154
158
 
155
159
  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.
156
160
 
161
+ ## Network behavior and privacy
162
+
163
+ CVE Lite CLI is a local-first scanner. It parses dependency information locally, uses local caching to reduce repeated lookups, and in standard mode queries OSV for advisory data needed for matching.
164
+
165
+ It does not require a hosted account, cloud dashboard, or source code upload.
166
+
167
+ For the full explanation, see [Network Behavior and Privacy](https://github.com/sonukapoor/cve-lite-cli/blob/main/src/docs/network-and-privacy.md).
168
+
169
+ ### Planned support for stricter environments
170
+
171
+ Support for stricter network-controlled environments is planned on the roadmap, including:
172
+
173
+ - offline scanning mode with zero outbound calls
174
+ - custom advisory endpoint support for internal mirrors or proxies
175
+ - local advisory database input for controlled or air-gapped workflows
176
+
177
+ ## Detecting malicious package incidents
178
+
179
+ CVE Lite CLI can help detect malicious package incidents and supply-chain compromises **once the affected versions are represented in OSV or equivalent advisory data available through the configured advisory endpoint**.
180
+
181
+ In practice, that means the tool can catch incidents such as a compromised npm package **when the exact malicious version appears in your lockfile** and the advisory data has already been published and indexed. This makes the tool useful for real-world release checks after a malicious package disclosure becomes known.
182
+
183
+ It is important to be precise about the current scope:
184
+
185
+ - CVE Lite CLI is **advisory-driven**, not a behavioral malware detector
186
+ - it does **not** perform static malware analysis on package contents
187
+ - it does **not** detect a package compromise before advisory intelligence exists for it
188
+ - it works best with lockfiles because they capture the exact resolved version that was actually installed
189
+
190
+ So the practical model is: **local lockfile scan + advisory matching**. When malicious versions are published to OSV or mirrored through a compatible internal endpoint, CVE Lite CLI can flag those exact versions during a scan.
191
+
157
192
  ## How it works
158
193
 
159
194
  ### Architectural Philosophy
160
195
  CVE Lite CLI is designed as a **local-first, metadata-only** scanner. Unlike traditional SaaS security platforms that require code uploads or heavy agent installations, this tool operates directly within the developer's environment. It focuses on the "moment of release"—providing a high-speed, low-noise assessment of the dependency tree by analyzing resolved versions in project lockfiles.
161
196
 
162
197
  <p align="center">
163
- <img src="./assets/diagram.png" alt="CVE Lite CLI Workflow" width="800"/>
198
+ <img src="https://github.com/sonukapoor/cve-lite-cli/blob/main/assets/diagram.png" alt="CVE Lite CLI Workflow" width="800"/>
164
199
  </p>
165
200
 
166
201
  ### Workflow Specifications
@@ -174,22 +209,16 @@ CVE Lite CLI is designed as a **local-first, metadata-only** scanner. Unlike tra
174
209
 
175
210
  - **fast, low-friction workflow**
176
211
  Run it locally against a project without adopting a large security platform.
177
-
178
212
  - **practical remediation guidance**
179
213
  It does not stop at raw advisory output. It highlights top-priority fixes and suggests a fix plan.
180
-
181
214
  - **direct vs transitive visibility**
182
215
  The output makes it easier to see whether the risk comes from something you installed directly or from a nested package.
183
-
184
216
  - **developer-first**
185
217
  It is optimized for developers working with npm, pnpm, and Yarn lockfiles.
186
-
187
218
  - **budget-friendly**
188
219
  It is intended for developers and teams who want useful security checks without paying for a large commercial product.
189
-
190
220
  - **local-first**
191
221
  It reads your project locally and uses package/version matching against OSV advisories.
192
-
193
222
  - **release-focused**
194
223
  It is especially useful before a release, in CI, or during final dependency cleanup.
195
224
 
@@ -215,6 +244,7 @@ Instead of only showing advisory IDs, the CLI reports:
215
244
  - fixed-version hint when available
216
245
  - advisory IDs
217
246
  - dependency path hints
247
+ - recommended parent upgrade for transitive issues when available
218
248
 
219
249
  By default, the CLI now presents a cleaner summary-first view, with `--verbose` available for the full detailed output.
220
250
 
@@ -233,7 +263,7 @@ CVE Lite CLI organizes likely remediation work into a practical sequence, such a
233
263
 
234
264
  ### 5. Parent package hints for transitive issues
235
265
 
236
- For transitive vulnerabilities, the tool can point to the likely parent dependency to review. That makes the output more actionable than simply saying a nested package is vulnerable.
266
+ 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.
237
267
 
238
268
  ### 6. JSON output
239
269
 
@@ -299,7 +329,7 @@ Run it before a release, during dependency cleanup, or after a major package upg
299
329
 
300
330
  ### CI/CD
301
331
 
302
- This repository also uses CVE Lite CLI in its own GitHub Actions workflow to scan itself as part of CI. See [`self-scan.yml`](./.github/workflows/self-scan.yml).
332
+ This repository also uses CVE Lite CLI in its own GitHub Actions workflow to scan itself as part of CI. See [`self-scan.yml`](https://github.com/sonukapoor/cve-lite-cli/blob/main/.github/workflows/self-scan.yml).
303
333
 
304
334
  For CI, we recommend using `--verbose` so build logs include the full fix plan, dependency paths, and detailed table output when a scan fails.
305
335
 
@@ -408,6 +438,8 @@ If your goal is a practical developer-first CVE scan right before release, CVE L
408
438
 
409
439
  To keep the project honest, here is what it does **not** do in the current version:
410
440
 
441
+ - it does not detect malicious packages before they are represented in advisory data
442
+ - it does not perform behavioral malware detection or package content analysis
411
443
  - it does not prove exploitability
412
444
  - it does not verify runtime reachability
413
445
  - it does not scan container images, binaries, secrets, or IaC
@@ -442,7 +474,7 @@ CVE Lite CLI is evolving from a vulnerability scanner into a comprehensive remed
442
474
 
443
475
  This project is being shaped around real-world developer usability. Feedback on output clarity, remediation guidance, ecosystem coverage, and CI usage is especially valuable.
444
476
 
445
- To get started, see [CONTRIBUTING.md](./CONTRIBUTING.md).
477
+ To get started, see [CONTRIBUTING.md](https://github.com/sonukapoor/cve-lite-cli/blob/main/src/docs/CONTRIBUTING.md).
446
478
 
447
479
  ## Community and support
448
480
 
@@ -461,7 +493,7 @@ Helpful feedback includes:
461
493
 
462
494
  As the project grows, contribution and security guidance will be expanded further in dedicated project docs.
463
495
 
464
- For bug reports and feature requests, please use [GitHub Issues](https://github.com/sonukapoor/cve-lite-cli/issues). For contribution guidance, see [CONTRIBUTING.md](./CONTRIBUTING.md). For security-related reporting, see [SECURITY.md](./SECURITY.md).
496
+ For bug reports and feature requests, please use [GitHub Issues](https://github.com/sonukapoor/cve-lite-cli/issues). For contribution guidance, see [CONTRIBUTING.md](https://github.com/sonukapoor/cve-lite-cli/blob/main/src/docs/CONTRIBUTING.md). For security-related reporting, see [SECURITY.md](https://github.com/sonukapoor/cve-lite-cli/blob/main/src/docs/SECURITY.md).
465
497
 
466
498
  ## License
467
499
 
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,51 @@
1
+ export class OsvAdvisorySource {
2
+ baseUrl;
3
+ constructor(baseUrl = "https://api.osv.dev") {
4
+ this.baseUrl = baseUrl;
5
+ }
6
+ async queryBatch(packages) {
7
+ try {
8
+ const response = await fetch(`${this.baseUrl}/v1/querybatch`, {
9
+ method: "POST",
10
+ headers: {
11
+ "Content-Type": "application/json",
12
+ },
13
+ body: JSON.stringify({
14
+ queries: packages.map(p => ({
15
+ package: {
16
+ ecosystem: p.ecosystem,
17
+ name: p.name,
18
+ },
19
+ version: p.version,
20
+ })),
21
+ }),
22
+ });
23
+ if (!response.ok) {
24
+ throw new Error(`OSV batch query failed: ${response.status} ${response.statusText}`);
25
+ }
26
+ const data = await response.json();
27
+ return data.results.map((r, i) => ({
28
+ package: packages[i].name,
29
+ version: packages[i].version,
30
+ vulnerabilities: r.vulns || [],
31
+ }));
32
+ }
33
+ catch (error) {
34
+ const message = error instanceof Error ? error.message : String(error);
35
+ throw new Error(`OSV batch query failed for ${this.baseUrl}: ${message}`);
36
+ }
37
+ }
38
+ async getVuln(id) {
39
+ try {
40
+ const response = await fetch(`${this.baseUrl}/v1/vulns/${encodeURIComponent(id)}`);
41
+ if (!response.ok) {
42
+ throw new Error(`OSV vuln fetch failed for ${id}: ${response.status} ${response.statusText}`);
43
+ }
44
+ return response.json();
45
+ }
46
+ catch (error) {
47
+ const message = error instanceof Error ? error.message : String(error);
48
+ throw new Error(`OSV vuln fetch failed for ${id} via ${this.baseUrl}: ${message}`);
49
+ }
50
+ }
51
+ }
package/dist/cli/args.js CHANGED
@@ -56,6 +56,14 @@ export function parseArgs(argv) {
56
56
  options.cacheDir = arg.slice("--cache-dir=".length);
57
57
  continue;
58
58
  }
59
+ if (arg === "--osv-url") {
60
+ options.osvUrl = argv[++i];
61
+ continue;
62
+ }
63
+ if (arg.startsWith("--osv-url=")) {
64
+ options.osvUrl = arg.slice("--osv-url=".length);
65
+ continue;
66
+ }
59
67
  if (arg === "--search-depth") {
60
68
  options.searchDepth = argv[++i] ?? options.searchDepth;
61
69
  continue;
package/dist/cli/help.js CHANGED
@@ -26,6 +26,7 @@ export function printHelp() {
26
26
  "",
27
27
  "Options:",
28
28
  " --json Print JSON output",
29
+ " --osv-url <url> Use a custom OSV-compatible advisory endpoint",
29
30
  " --verbose Show detailed output with fix plan, paths, and full table",
30
31
  " --prod-only Exclude dev dependencies where available",
31
32
  " --fail-on <severity> Exit non-zero at or above severity (default: critical)",
package/dist/index.js CHANGED
@@ -22,6 +22,27 @@ async function main() {
22
22
  if (!options.json) {
23
23
  printBanner();
24
24
  }
25
+ if (options.offline) {
26
+ console.log(chalk.gray("Offline mode:") + " " + chalk.yellow("enabled") + " " + chalk.gray("(no external calls will be made)"));
27
+ throw new Error("Offline mode is not implemented yet. External calls are disabled.");
28
+ }
29
+ if (options.offline && options.osvUrl) {
30
+ throw new Error("--offline cannot be used with --osv-url");
31
+ }
32
+ if (options.osvUrl) {
33
+ console.log(`${chalk.gray("Advisory source:")} custom OSV endpoint (${chalk.cyan(options.osvUrl)})`);
34
+ }
35
+ else {
36
+ console.log(`${chalk.gray("Advisory source:")} OSV (${chalk.cyan("https://api.osv.dev")})`);
37
+ }
38
+ if (options.osvUrl) {
39
+ try {
40
+ new URL(options.osvUrl);
41
+ }
42
+ catch {
43
+ throw new Error(`Invalid value for --osv-url: ${options.osvUrl}`);
44
+ }
45
+ }
25
46
  const scanInput = loadPackages(projectPath, !!options.prodOnly, searchDepth);
26
47
  const packages = scanInput.packages;
27
48
  logInfo(`Parsed ${packages.length} package${packages.length === 1 ? "" : "s"} from ${scanInput.source}${scanInput.filePath ? ` (${path.relative(projectPath, scanInput.filePath) || path.basename(scanInput.filePath)})` : ""}`, options);
@@ -35,7 +56,7 @@ async function main() {
35
56
  logWarn(buildNoPackagesMessage(projectPath), options);
36
57
  process.exit(0);
37
58
  }
38
- const findings = await scanPackages(packages, batchSize, !!options.offline, options.cacheDir, options);
59
+ const findings = await scanPackages(packages, batchSize, options);
39
60
  const sorted = findings.sort((a, b) => severityOrder[b.severity] - severityOrder[a.severity]);
40
61
  const coverage = buildCoverageNotes(scanInput, !!options.offline);
41
62
  const minSeverity = normalizeSeverity(options.minSeverity || "medium");
@@ -1,16 +1,18 @@
1
1
  import { chalk } from "../utils/chalk.js";
2
+ import { severityOrder } from "../constants.js";
2
3
  import { loadCache } from "../osv/cache.js";
3
4
  import { inferSeverity } from "../osv/severity.js";
4
5
  export function formatSeverityLabel(severity) {
5
- if (severity === "critical")
6
+ const lower = severity.toLowerCase();
7
+ if (lower === "critical")
6
8
  return chalk.redBright(severity);
7
- if (severity === "high")
9
+ if (lower === "high")
8
10
  return chalk.red(severity);
9
- if (severity === "medium")
11
+ if (lower === "medium")
10
12
  return chalk.yellow(severity);
11
- if (severity === "low")
13
+ if (lower === "low")
12
14
  return chalk.blueBright(severity);
13
- if (severity === "unknown")
15
+ if (lower === "unknown")
14
16
  return chalk.magenta(severity);
15
17
  return severity;
16
18
  }
@@ -34,6 +36,9 @@ export function getRecommendedAction(finding) {
34
36
  if (finding.relationship === "direct") {
35
37
  return `Review and upgrade ${finding.pkg.name} directly in this project.`;
36
38
  }
39
+ if (finding.recommendedParentUpgrade) {
40
+ return `Upgrade ${finding.recommendedParentUpgrade.package} from ${finding.recommendedParentUpgrade.currentVersion} to ${finding.recommendedParentUpgrade.targetVersion} to stop pulling in vulnerable ${finding.pkg.name}.`;
41
+ }
37
42
  const parent = getPrimaryParent(finding);
38
43
  if (parent && finding.firstFixedVersion) {
39
44
  return `Review ${parent}; aim for a version that resolves ${finding.pkg.name} to ${finding.firstFixedVersion}+`;
@@ -53,6 +58,9 @@ export function summarizeRisk(finding) {
53
58
  if (finding.severity === "high" && finding.relationship === "direct") {
54
59
  return "High-severity direct dependency. A direct upgrade is likely the fastest path.";
55
60
  }
61
+ if (finding.relationship === "transitive" && finding.recommendedParentUpgrade) {
62
+ return `Transitive issue. A specific parent upgrade target was found for ${finding.recommendedParentUpgrade.package}.`;
63
+ }
56
64
  if (finding.relationship === "transitive" && finding.firstFixedVersion) {
57
65
  return `Transitive issue. Look for a parent dependency upgrade that pulls in ${finding.firstFixedVersion}+`;
58
66
  }
@@ -71,6 +79,9 @@ export function summarizeNextAction(finding) {
71
79
  if (finding.relationship === "direct") {
72
80
  return `Review and upgrade ${finding.pkg.name} directly in this project.`;
73
81
  }
82
+ if (finding.recommendedParentUpgrade) {
83
+ return `Upgrade ${finding.recommendedParentUpgrade.package} ${finding.recommendedParentUpgrade.currentVersion} -> ${finding.recommendedParentUpgrade.targetVersion}.`;
84
+ }
74
85
  if (finding.firstFixedVersion) {
75
86
  return `Upgrade the parent dependency chain so it resolves ${finding.pkg.name} to ${finding.firstFixedVersion}+`;
76
87
  }
@@ -85,14 +96,15 @@ export function serializeFinding(finding) {
85
96
  firstFixedVersion: finding.firstFixedVersion,
86
97
  recommendedAction: getRecommendedAction(finding),
87
98
  primaryParent: getPrimaryParent(finding),
99
+ recommendedParentUpgrade: finding.recommendedParentUpgrade,
88
100
  cves: finding.cveAliases,
89
101
  dependencyPaths: finding.dependencyPaths,
90
102
  vulnerabilities: finding.vulnerabilities.map(v => ({
91
103
  id: v.id,
92
104
  aliases: v.aliases ?? [],
93
105
  summary: v.summary ?? "",
94
- severity: inferSeverity(v)
95
- }))
106
+ severity: inferSeverity(v),
107
+ })),
96
108
  };
97
109
  }
98
110
  export function printCacheSummary(cacheDirOverride, options) {
@@ -100,14 +112,30 @@ export function printCacheSummary(cacheDirOverride, options) {
100
112
  return;
101
113
  const cache = loadCache(cacheDirOverride);
102
114
  const advisoryCount = Object.entries(cache.entries).filter(([, value]) => Boolean(value)).length;
103
- const negativeCount = Object.entries(cache.entries).filter(([, value]) => value === null).length;
104
- logInfo(`Cache summary: ${advisoryCount} advisory record${advisoryCount === 1 ? "" : "s"} cached, ${negativeCount} negative entr${negativeCount === 1 ? "y" : "ies"}`, options);
115
+ const emptyCount = Object.entries(cache.entries).filter(([, value]) => value === null).length;
116
+ const totalCount = advisoryCount + emptyCount;
117
+ if (totalCount === 0)
118
+ return;
119
+ console.log(chalk.gray(`Cache: ${advisoryCount} advisory detail record${advisoryCount === 1 ? "" : "s"}`) +
120
+ (emptyCount > 0
121
+ ? chalk.gray(`, ${emptyCount} empty lookup${emptyCount === 1 ? "" : "s"}`)
122
+ : ""));
105
123
  }
106
124
  export function logInfo(message, options) {
107
- if (!options?.json)
108
- console.log(chalk.cyan(`• ${message}`));
125
+ if (options?.json)
126
+ return;
127
+ console.log(chalk.gray(message));
109
128
  }
110
129
  export function logWarn(message, options) {
111
- if (!options?.json)
112
- console.log(chalk.yellow(`! ${message}`));
130
+ if (options?.json)
131
+ return;
132
+ console.log(chalk.yellow(message));
133
+ }
134
+ export function sortFindingsForOutput(findings) {
135
+ return [...findings].sort((a, b) => {
136
+ const sevDelta = severityOrder[b.severity] - severityOrder[a.severity];
137
+ if (sevDelta !== 0)
138
+ return sevDelta;
139
+ return a.pkg.name.localeCompare(b.pkg.name);
140
+ });
113
141
  }
@@ -64,6 +64,9 @@ export function printPriorityFixes(findings) {
64
64
  const parent = getPrimaryParent(finding);
65
65
  if (parent)
66
66
  console.log(` Parent: ${parent}`);
67
+ if (finding.recommendedParentUpgrade) {
68
+ console.log(` Target: ${finding.recommendedParentUpgrade.package} ${finding.recommendedParentUpgrade.currentVersion} -> ${finding.recommendedParentUpgrade.targetVersion}`);
69
+ }
67
70
  console.log(` Next: ${summarizeNextAction(finding)}`);
68
71
  }
69
72
  }
@@ -187,6 +190,9 @@ export function printPathHints(findings) {
187
190
  for (const example of examples) {
188
191
  console.log(` ${chalk.gray(example)}`);
189
192
  }
193
+ if (finding.recommendedParentUpgrade) {
194
+ console.log(` Recommended parent upgrade: ${chalk.bold.cyan(finding.recommendedParentUpgrade.package)} ${finding.recommendedParentUpgrade.currentVersion} -> ${finding.recommendedParentUpgrade.targetVersion}`);
195
+ }
190
196
  }
191
197
  }
192
198
  export function printFinalStatus(findings) {
@@ -235,11 +241,17 @@ export function printCompactOutput(findings) {
235
241
  .slice(0, 3);
236
242
  for (const finding of urgentFindings) {
237
243
  const sevLabel = finding.severity.toUpperCase().padEnd(8);
238
- const typeLabel = finding.relationship === "direct" ? "Direct dependency" :
239
- finding.relationship === "transitive" ? "Transitive dependency" : "Unknown dependency";
244
+ const typeLabel = finding.relationship === "direct"
245
+ ? "Direct dependency"
246
+ : finding.relationship === "transitive"
247
+ ? "Transitive dependency"
248
+ : "Unknown dependency";
240
249
  console.log(`${formatSeverityLabel(sevLabel)} ${chalk.whiteBright(finding.pkg.name)}@${finding.pkg.version}`);
241
250
  console.log(` ${typeLabel}`);
242
- if (finding.firstFixedVersion) {
251
+ if (finding.recommendedParentUpgrade) {
252
+ console.log(` ${chalk.gray(`Fix: upgrade ${finding.recommendedParentUpgrade.package} to ${finding.recommendedParentUpgrade.targetVersion}`)}`);
253
+ }
254
+ else if (finding.firstFixedVersion) {
243
255
  const action = finding.relationship === "direct"
244
256
  ? `upgrade to ${finding.firstFixedVersion}`
245
257
  : `upgrade parent chain to resolve ${finding.firstFixedVersion}+`;
@@ -265,6 +277,9 @@ export function printCompactOutput(findings) {
265
277
  else if (topFinding.relationship === "direct") {
266
278
  console.log(`Upgrade ${chalk.whiteBright(topFinding.pkg.name)} to latest safe version`);
267
279
  }
280
+ else if (topFinding.recommendedParentUpgrade) {
281
+ console.log(`Upgrade ${chalk.whiteBright(topFinding.recommendedParentUpgrade.package)} ${topFinding.recommendedParentUpgrade.currentVersion} → ${topFinding.recommendedParentUpgrade.targetVersion}`);
282
+ }
268
283
  else {
269
284
  const parent = getPrimaryParent(topFinding);
270
285
  if (parent) {
@@ -0,0 +1,224 @@
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 async function resolveRecommendedParentUpgrade(finding, packages) {
5
+ if (finding.relationship !== "transitive")
6
+ return null;
7
+ const viaPath = getBestPath(finding);
8
+ if (!viaPath || viaPath.length < 3)
9
+ return null;
10
+ const directParentName = viaPath[1];
11
+ const immediateParentName = viaPath[viaPath.length - 2];
12
+ const vulnerableName = finding.pkg.name;
13
+ const directParent = findDirectDependency(packages, directParentName);
14
+ if (!directParent)
15
+ return null;
16
+ // Common reliable case:
17
+ // project -> sanitize-html -> lodash
18
+ if (viaPath.length === 3) {
19
+ return findUpgradeForExactDirectChild({
20
+ directParentName,
21
+ directParentVersion: directParent.version,
22
+ vulnerableName,
23
+ vulnerableInstalledVersion: finding.pkg.version,
24
+ vulnerableFixedVersion: finding.firstFixedVersion,
25
+ viaPath,
26
+ });
27
+ }
28
+ // Best-effort fallback for deeper chains.
29
+ return findUpgradeForImmediateIntermediate({
30
+ directParentName,
31
+ directParentVersion: directParent.version,
32
+ immediateParentName,
33
+ immediateParentInstalledVersion: findPackageVersion(packages, immediateParentName, viaPath.slice(0, -1)) ?? "",
34
+ vulnerableName,
35
+ viaPath,
36
+ });
37
+ }
38
+ function getBestPath(finding) {
39
+ const paths = finding.dependencyPaths ?? [];
40
+ if (paths.length === 0)
41
+ return null;
42
+ return [...paths].sort((a, b) => a.length - b.length)[0] ?? null;
43
+ }
44
+ function findDirectDependency(packages, name) {
45
+ for (const pkg of packages) {
46
+ if (pkg.name !== name)
47
+ continue;
48
+ const paths = pkg.paths ?? [];
49
+ if (paths.some(path => path.length === 2 && path[1] === name)) {
50
+ return pkg;
51
+ }
52
+ }
53
+ return null;
54
+ }
55
+ function findPackageVersion(packages, name, pathPrefix) {
56
+ for (const pkg of packages) {
57
+ if (pkg.name !== name)
58
+ continue;
59
+ const paths = pkg.paths ?? [];
60
+ if (paths.some(path => startsWithPath(path, pathPrefix))) {
61
+ return pkg.version;
62
+ }
63
+ }
64
+ return null;
65
+ }
66
+ function startsWithPath(path, prefix) {
67
+ if (prefix.length > path.length)
68
+ return false;
69
+ for (let i = 0; i < prefix.length; i++) {
70
+ if (path[i] !== prefix[i])
71
+ return false;
72
+ }
73
+ return true;
74
+ }
75
+ async function findUpgradeForExactDirectChild(args) {
76
+ const packument = await fetchPackument(args.directParentName);
77
+ const versions = Object.keys(packument?.versions ?? {})
78
+ .filter(looksLikeVersion)
79
+ .filter(version => compareVersions(version, args.directParentVersion) > 0)
80
+ .sort(compareVersions);
81
+ for (const version of versions) {
82
+ const manifest = packument?.versions?.[version];
83
+ const depRange = manifest?.dependencies?.[args.vulnerableName] ??
84
+ manifest?.optionalDependencies?.[args.vulnerableName];
85
+ if (!depRange)
86
+ continue;
87
+ const stillAllowsInstalled = versionSatisfiesRange(args.vulnerableInstalledVersion, depRange);
88
+ const allowsFixed = args.vulnerableFixedVersion
89
+ ? versionSatisfiesRange(args.vulnerableFixedVersion, depRange)
90
+ : true;
91
+ if (!stillAllowsInstalled && allowsFixed) {
92
+ return {
93
+ package: args.directParentName,
94
+ currentVersion: args.directParentVersion,
95
+ targetVersion: version,
96
+ viaPath: args.viaPath,
97
+ vulnerablePackage: args.vulnerableName,
98
+ confidence: "exact-direct-child",
99
+ reason: `${args.directParentName}@${version} no longer allows ${args.vulnerableName}@${args.vulnerableInstalledVersion}${args.vulnerableFixedVersion ? ` and allows ${args.vulnerableFixedVersion}+` : ""}`,
100
+ };
101
+ }
102
+ }
103
+ return null;
104
+ }
105
+ async function findUpgradeForImmediateIntermediate(args) {
106
+ if (!args.immediateParentInstalledVersion || !looksLikeVersion(args.immediateParentInstalledVersion)) {
107
+ return null;
108
+ }
109
+ const packument = await fetchPackument(args.directParentName);
110
+ const versions = Object.keys(packument?.versions ?? {})
111
+ .filter(looksLikeVersion)
112
+ .filter(version => compareVersions(version, args.directParentVersion) > 0)
113
+ .sort(compareVersions);
114
+ for (const version of versions) {
115
+ const manifest = packument?.versions?.[version];
116
+ const depRange = manifest?.dependencies?.[args.immediateParentName] ??
117
+ manifest?.optionalDependencies?.[args.immediateParentName];
118
+ if (!depRange)
119
+ continue;
120
+ const stillAllowsImmediateParentInstalled = versionSatisfiesRange(args.immediateParentInstalledVersion, depRange);
121
+ if (!stillAllowsImmediateParentInstalled) {
122
+ return {
123
+ package: args.directParentName,
124
+ currentVersion: args.directParentVersion,
125
+ targetVersion: version,
126
+ viaPath: args.viaPath,
127
+ vulnerablePackage: args.vulnerableName,
128
+ confidence: "best-effort",
129
+ reason: `${args.directParentName}@${version} no longer allows ${args.immediateParentName}@${args.immediateParentInstalledVersion} in the current path`,
130
+ };
131
+ }
132
+ }
133
+ return null;
134
+ }
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
+ function versionSatisfiesRange(version, rawRange) {
152
+ const range = rawRange.trim();
153
+ if (!range)
154
+ return false;
155
+ if (range === "*" || range === "latest")
156
+ return true;
157
+ const orParts = range.split("||").map(part => part.trim()).filter(Boolean);
158
+ return orParts.some(part => satisfiesAndRange(version, part));
159
+ }
160
+ function satisfiesAndRange(version, range) {
161
+ const normalized = normalizeRange(range);
162
+ if (!normalized)
163
+ return false;
164
+ const tokens = normalized.split(/\s+/).filter(Boolean);
165
+ return tokens.every(token => satisfiesComparator(version, token));
166
+ }
167
+ function normalizeRange(range) {
168
+ const trimmed = range.trim();
169
+ if (!trimmed)
170
+ return null;
171
+ if (looksLikeVersion(trimmed)) {
172
+ return `=${trimmed}`;
173
+ }
174
+ if (trimmed.startsWith("^")) {
175
+ const base = trimmed.slice(1);
176
+ if (!looksLikeVersion(base))
177
+ return null;
178
+ const [major, minor, patch] = parseCoreVersion(base);
179
+ if (major > 0)
180
+ return `>=${base} <${major + 1}.0.0`;
181
+ if (minor > 0)
182
+ return `>=${base} <0.${minor + 1}.0`;
183
+ return `>=${base} <0.0.${patch + 1}`;
184
+ }
185
+ if (trimmed.startsWith("~")) {
186
+ const base = trimmed.slice(1);
187
+ if (!looksLikeVersion(base))
188
+ return null;
189
+ const [major, minor] = parseCoreVersion(base);
190
+ return `>=${base} <${major}.${minor + 1}.0`;
191
+ }
192
+ return trimmed;
193
+ }
194
+ function satisfiesComparator(version, comparator) {
195
+ const token = comparator.trim();
196
+ if (!token)
197
+ return true;
198
+ const match = token.match(/^(<=|>=|<|>|=)?\s*([0-9]+\.[0-9]+\.[0-9]+(?:[-+][^\s]+)?)$/);
199
+ if (!match)
200
+ return false;
201
+ const operator = match[1] ?? "=";
202
+ const target = match[2];
203
+ const cmp = compareVersions(version, target);
204
+ switch (operator) {
205
+ case "<":
206
+ return cmp < 0;
207
+ case "<=":
208
+ return cmp <= 0;
209
+ case ">":
210
+ return cmp > 0;
211
+ case ">=":
212
+ return cmp >= 0;
213
+ case "=":
214
+ return cmp === 0;
215
+ default:
216
+ return false;
217
+ }
218
+ }
219
+ function parseCoreVersion(version) {
220
+ const [major, minor, patch] = version
221
+ .split(".")
222
+ .map(part => Number(part.replace(/[^0-9].*$/, "")));
223
+ return [major || 0, minor || 0, patch || 0];
224
+ }
package/dist/scanner.js CHANGED
@@ -1,11 +1,18 @@
1
1
  import { chunk, unique } from "./utils/array.js";
2
2
  import { compareVersions, looksLikeVersion } from "./utils/version.js";
3
- import { osvQueryBatch, osvGetVuln } from "./osv/api.js";
4
3
  import { loadCache, saveCache } from "./osv/cache.js";
5
4
  import { maxSeverity } from "./osv/severity.js";
6
5
  import { createSpinner } from "./output/spinner.js";
7
- export async function scanPackages(packages, batchSize, offline, cacheDirOverride, options) {
6
+ import { OsvAdvisorySource } from "./advisory/osv-advisory-source.js";
7
+ import { resolveRecommendedParentUpgrade } from "./remediation/parent-upgrade.js";
8
+ export function createAdvisorySource(options) {
9
+ return new OsvAdvisorySource(options?.osvUrl);
10
+ }
11
+ export async function scanPackages(packages, batchSize, options) {
12
+ const offline = !!options.offline;
13
+ const cacheDirOverride = options.cacheDir;
8
14
  const spinner = createSpinner("Scanning dependencies against OSV...", options);
15
+ const advisorySource = createAdvisorySource({ osvUrl: options.osvUrl });
9
16
  try {
10
17
  const chunks = chunk(packages, batchSize);
11
18
  const results = [];
@@ -13,12 +20,12 @@ export async function scanPackages(packages, batchSize, offline, cacheDirOverrid
13
20
  for (let i = 0; i < chunks.length; i++) {
14
21
  spinner.update(`Scanning OSV batch ${i + 1}/${chunks.length}...`);
15
22
  const chunkItems = chunks[i];
16
- const batchResponse = await osvQueryBatch(chunkItems);
17
- const rows = batchResponse.results ?? [];
23
+ const advisoryResult = await advisorySource.queryBatch(chunkItems);
24
+ const rows = advisoryResult ?? [];
18
25
  for (let j = 0; j < chunkItems.length; j++) {
19
26
  const pkg = chunkItems[j];
20
27
  const row = rows[j];
21
- const vulnIds = (row?.vulns ?? []).map(v => v.id).filter(Boolean);
28
+ const vulnIds = (row?.vulnerabilities ?? []).map(v => v.id).filter(Boolean);
22
29
  if (vulnIds.length > 0) {
23
30
  results.push({ pkg, vulnIds });
24
31
  }
@@ -45,7 +52,7 @@ export async function scanPackages(packages, batchSize, offline, cacheDirOverrid
45
52
  continue;
46
53
  }
47
54
  try {
48
- const detail = await osvGetVuln(id);
55
+ const detail = await advisorySource.getVuln(id);
49
56
  vulnMap.set(id, detail);
50
57
  cache.entries[id] = detail;
51
58
  }
@@ -63,7 +70,7 @@ export async function scanPackages(packages, batchSize, offline, cacheDirOverrid
63
70
  if (!offline && idSet.size > 0) {
64
71
  saveCache(cache, cacheDirOverride);
65
72
  }
66
- return results.map(result => {
73
+ const findings = results.map(result => {
67
74
  const vulnerabilities = result.vulnIds
68
75
  .map(id => vulnMap.get(id))
69
76
  .filter((v) => Boolean(v));
@@ -79,9 +86,21 @@ export async function scanPackages(packages, batchSize, offline, cacheDirOverrid
79
86
  cveAliases,
80
87
  dependencyPaths,
81
88
  relationship,
82
- firstFixedVersion
89
+ firstFixedVersion,
90
+ recommendedParentUpgrade: undefined,
83
91
  };
84
92
  });
93
+ for (const finding of findings) {
94
+ if (finding.relationship !== "transitive" || offline)
95
+ continue;
96
+ try {
97
+ finding.recommendedParentUpgrade = await resolveRecommendedParentUpgrade(finding, packages);
98
+ }
99
+ catch {
100
+ finding.recommendedParentUpgrade = undefined;
101
+ }
102
+ }
103
+ return findings;
85
104
  }
86
105
  catch (error) {
87
106
  spinner.fail("Scan failed");
@@ -119,7 +138,7 @@ export function buildCoverageNotes(scanInput, offline) {
119
138
  "This MVP checks package versions against OSV advisories. It does not prove exploitability or runtime reachability.",
120
139
  "Installed node_modules contents are not verified in this scan.",
121
140
  "Container images, binaries, secrets, and IaC files are not scanned.",
122
- "Monorepo workspace boundaries are only partially modeled in this version."
141
+ "Monorepo workspace boundaries are only partially modeled in this version.",
123
142
  ];
124
143
  if (scanInput.mode === "manifest-fallback") {
125
144
  notes.push("Manifest fallback is limited to direct dependencies pinned to exact versions. It does not resolve transitive dependencies from package.json alone.");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cve-lite-cli",
3
- "version": "1.0.4",
3
+ "version": "1.0.6",
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": {