cve-lite-cli 1.14.0 → 1.16.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 +43 -3
- package/dist/cli/args.js +27 -0
- package/dist/cli/help.js +7 -0
- package/dist/index.js +48 -45
- package/dist/llm/client.js +40 -0
- package/dist/llm/config.js +48 -0
- package/dist/llm/explainer.js +31 -0
- package/dist/output/cyclonedx.js +88 -0
- package/dist/output/formatters.js +24 -4
- package/dist/output/html-reporter.js +5 -1
- package/dist/output/printers.js +37 -1
- package/dist/output/sarif.js +91 -0
- package/dist/output/spinner.js +1 -1
- package/dist/output/write-outputs.js +54 -0
- package/dist/parsers/pnpm-lock.js +25 -29
- package/dist/remediation/fix-commands.js +41 -2
- package/dist/skills/content.js +39 -0
- package/dist/skills/install.js +52 -0
- package/dist/utils/path-coverage.js +17 -0
- package/dist/utils/severity.js +7 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -89,7 +89,7 @@ No account. No configuration. No source code leaves your machine.
|
|
|
89
89
|
- **Offline advisory DB** — sync advisory data ahead of time and scan with zero runtime API calls, designed for enterprise and air-gapped environments
|
|
90
90
|
- **Interactive HTML report** — generate a self-contained dashboard with severity cards, a searchable findings table, and copy-ready fix commands (`--report`)
|
|
91
91
|
- **Auto-fix mode** — apply validated direct dependency fixes and rescan automatically (`--fix`)
|
|
92
|
-
- **CI-ready** — `--fail-on high` exits non-zero on findings at or above a severity threshold; a first-party [GitHub Action](https://github.com/marketplace/actions/cve-lite-cli) is available on the Marketplace
|
|
92
|
+
- **CI-ready** — `--fail-on high` exits non-zero on findings at or above a severity threshold; a first-party [GitHub Action](https://github.com/marketplace/actions/cve-lite-cli) is available on the Marketplace; `--sarif` writes SARIF 2.1.0 output for direct upload to GitHub Code Scanning; `--cdx` writes a CycloneDX 1.4 SBOM for Dependency-Track and compliance artifacts; `--json` integrates with SIEM tools and dashboards
|
|
93
93
|
- **Minimal footprint** — four runtime dependencies, intentionally kept small for a security tool
|
|
94
94
|
|
|
95
95
|
## What it looks like
|
|
@@ -132,7 +132,7 @@ CVE Lite CLI fits at every stage of the development workflow, not just CI.
|
|
|
132
132
|
|
|
133
133
|
**Local development** — run a scan before opening a PR. The default output is fast and minimal. `--verbose` adds the full fix plan with dependency paths and prioritized remediation commands. `--report` opens an interactive HTML dashboard.
|
|
134
134
|
|
|
135
|
-
**CI pipelines** — use `--fail-on high` to gate builds on severity. JSON output (`--json`) integrates with SIEM, dashboards, and custom automation. SARIF output
|
|
135
|
+
**CI pipelines** — use `--fail-on high` to gate builds on severity. JSON output (`--json`) integrates with SIEM, dashboards, and custom automation. SARIF output (`--sarif`) writes a SARIF 2.1.0 file for direct upload to GitHub Code Scanning — findings appear in the Security tab and annotate PRs.
|
|
136
136
|
|
|
137
137
|
**Restricted and enterprise environments** — sync the advisory database ahead of time with `cve-lite advisories sync`, then scan offline with `--offline`. No runtime outbound calls during the scan. Syncing ~217,065 advisory records completes in under 9 seconds.
|
|
138
138
|
|
|
@@ -143,8 +143,17 @@ CVE Lite CLI fits at every stage of the development workflow, not just CI.
|
|
|
143
143
|
with:
|
|
144
144
|
verbose: "true"
|
|
145
145
|
fail-on: high
|
|
146
|
+
sarif: "true"
|
|
147
|
+
|
|
148
|
+
- name: Upload to GitHub Code Scanning
|
|
149
|
+
uses: github/codeql-action/upload-sarif@v4
|
|
150
|
+
if: always()
|
|
151
|
+
with:
|
|
152
|
+
sarif_file: ${{ github.workspace }}
|
|
146
153
|
```
|
|
147
154
|
|
|
155
|
+
> **Note:** `if: always()` is required on the upload step. Without it, the upload is skipped when `--fail-on` exits non-zero — losing your findings in Code Scanning exactly when they matter most.
|
|
156
|
+
|
|
148
157
|
CVE Lite CLI scans its own dependencies in CI. See [`self-scan.yml`](https://github.com/OWASP/cve-lite-cli/blob/main/.github/workflows/self-scan.yml).
|
|
149
158
|
|
|
150
159
|
For full CI patterns including offline workflows, git hooks, and scripted automation, see the [CI and Workflow Integration guide](https://owasp.org/cve-lite-cli/docs/ci-integration).
|
|
@@ -248,6 +257,9 @@ cve-lite /path/to/project --fail-on high
|
|
|
248
257
|
# JSON output
|
|
249
258
|
cve-lite /path/to/project --json
|
|
250
259
|
|
|
260
|
+
# SARIF output for GitHub Code Scanning and other SARIF-compatible tools
|
|
261
|
+
cve-lite /path/to/project --sarif
|
|
262
|
+
|
|
251
263
|
# Generate an HTML vulnerability dashboard (opens in browser automatically)
|
|
252
264
|
cve-lite /path/to/project --report
|
|
253
265
|
cve-lite /path/to/project --report ./my-report --no-open
|
|
@@ -272,6 +284,9 @@ cve-lite /path/to/project --osv-url https://security.company.internal/osv
|
|
|
272
284
|
|
|
273
285
|
# Show version
|
|
274
286
|
cve-lite --version
|
|
287
|
+
|
|
288
|
+
# Install AI assistant skill files for Claude Code, Codex CLI, Gemini CLI, Cursor, and GitHub Copilot
|
|
289
|
+
cve-lite install-skill
|
|
275
290
|
```
|
|
276
291
|
|
|
277
292
|
### Why is `--usage` an opt-in flag?
|
|
@@ -296,6 +311,31 @@ See the [Fix mode guide](https://owasp.org/cve-lite-cli/docs/fix-mode) for outpu
|
|
|
296
311
|
|
|
297
312
|
For a deeper explanation of how the CLI chooses direct upgrades, parent upgrades, and npm `update` recommendations for transitive findings, see the [Remediation Strategy guide](https://owasp.org/cve-lite-cli/docs/remediation-strategy).
|
|
298
313
|
|
|
314
|
+
## AI assistant integration (`install-skill`)
|
|
315
|
+
|
|
316
|
+
CVE Lite CLI can teach your AI coding assistant how to analyze scan results and produce a prioritized remediation plan. Run this once in your project root:
|
|
317
|
+
|
|
318
|
+
```bash
|
|
319
|
+
cve-lite install-skill
|
|
320
|
+
```
|
|
321
|
+
|
|
322
|
+
This writes skill files for Claude Code, Codex CLI, Gemini CLI, Cursor, and GitHub Copilot into the current directory. Commit them so every developer on your team gets the context automatically.
|
|
323
|
+
|
|
324
|
+
Once installed, the workflow is:
|
|
325
|
+
|
|
326
|
+
```bash
|
|
327
|
+
# 1. Scan and save results to a JSON file
|
|
328
|
+
cve-lite . --json
|
|
329
|
+
|
|
330
|
+
# 2. Ask your AI assistant to analyze findings
|
|
331
|
+
# In Claude Code: /cve-lite
|
|
332
|
+
# In other tools: the skill is picked up automatically
|
|
333
|
+
```
|
|
334
|
+
|
|
335
|
+
The AI assistant reads the JSON output, prioritizes findings by severity and relationship, checks whether vulnerable packages are actually imported in your source code, and produces a concrete remediation plan with the exact commands to run.
|
|
336
|
+
|
|
337
|
+
See the [AI Assistant Integration guide](https://owasp.org/cve-lite-cli/docs/ai-assistant-integration) for the full workflow and what the skill teaches the assistant.
|
|
338
|
+
|
|
299
339
|
## HTML vulnerability report (`--report`)
|
|
300
340
|
|
|
301
341
|
Generate a self-contained HTML dashboard from any scan — severity cards, an interactive findings table with search, copy-ready fix commands, and breaking-change indicators on upgrades — all written to a local directory and opened automatically in your browser.
|
|
@@ -457,4 +497,4 @@ If CVE Lite CLI helps your release workflow, a [GitHub star](https://github.com/
|
|
|
457
497
|
|
|
458
498
|
## License
|
|
459
499
|
|
|
460
|
-
MIT
|
|
500
|
+
MIT — built in public and maintained as an OWASP Foundation Project by Sonu Kapoor.
|
package/dist/cli/args.js
CHANGED
|
@@ -30,6 +30,19 @@ export function parseArgs(argv) {
|
|
|
30
30
|
}
|
|
31
31
|
return { command: "advisories-sync", options };
|
|
32
32
|
}
|
|
33
|
+
if (argv[0] === "install-skill") {
|
|
34
|
+
for (let i = 1; i < argv.length; i++) {
|
|
35
|
+
const arg = argv[i];
|
|
36
|
+
if (arg === "-h" || arg === "--help") {
|
|
37
|
+
options.help = true;
|
|
38
|
+
continue;
|
|
39
|
+
}
|
|
40
|
+
if (arg.startsWith("-"))
|
|
41
|
+
throw new Error(`Unknown option: ${arg}`);
|
|
42
|
+
throw new Error(`Unexpected argument: ${arg}`);
|
|
43
|
+
}
|
|
44
|
+
return { command: "install-skill", options };
|
|
45
|
+
}
|
|
33
46
|
let projectArg;
|
|
34
47
|
for (let i = 0; i < argv.length; i++) {
|
|
35
48
|
const arg = argv[i];
|
|
@@ -161,6 +174,14 @@ export function parseArgs(argv) {
|
|
|
161
174
|
options.noCache = true;
|
|
162
175
|
continue;
|
|
163
176
|
}
|
|
177
|
+
if (arg === "--sarif") {
|
|
178
|
+
options.sarif = true;
|
|
179
|
+
continue;
|
|
180
|
+
}
|
|
181
|
+
if (arg === "--cdx") {
|
|
182
|
+
options.cdx = true;
|
|
183
|
+
continue;
|
|
184
|
+
}
|
|
164
185
|
if (arg.startsWith("-"))
|
|
165
186
|
throw new Error(`Unknown option: ${arg}`);
|
|
166
187
|
if (!projectArg) {
|
|
@@ -169,5 +190,11 @@ export function parseArgs(argv) {
|
|
|
169
190
|
}
|
|
170
191
|
throw new Error(`Unexpected argument: ${arg}`);
|
|
171
192
|
}
|
|
193
|
+
if (options.sarif && options.report) {
|
|
194
|
+
throw new Error("cannot combine --sarif and --report");
|
|
195
|
+
}
|
|
196
|
+
if (options.cdx && options.report) {
|
|
197
|
+
throw new Error("cannot combine --cdx and --report");
|
|
198
|
+
}
|
|
172
199
|
return { command: "scan", options, projectArg };
|
|
173
200
|
}
|
package/dist/cli/help.js
CHANGED
|
@@ -28,10 +28,13 @@ export function printHelp() {
|
|
|
28
28
|
"Usage:",
|
|
29
29
|
" cve-lite [projectPath] [options]",
|
|
30
30
|
" cve-lite advisories sync [options]",
|
|
31
|
+
" cve-lite install-skill",
|
|
31
32
|
"",
|
|
32
33
|
"Scan options:",
|
|
33
34
|
" --json Print JSON output",
|
|
34
35
|
" --report [dir] Generate an HTML report in [dir] (default: ./cve-report)",
|
|
36
|
+
" --sarif Write SARIF 2.1.0 output to a timestamped .sarif file",
|
|
37
|
+
" --cdx Write CycloneDX 1.4 SBOM to a timestamped .cdx.json file",
|
|
35
38
|
" --no-open Don't auto-open the report in the browser",
|
|
36
39
|
" --fix Apply validated direct dependency fixes and rescan",
|
|
37
40
|
" --osv-url <url> Use a custom OSV-compatible advisory endpoint",
|
|
@@ -52,6 +55,10 @@ export function printHelp() {
|
|
|
52
55
|
"Advisory sync options:",
|
|
53
56
|
" --output <path> Write the local advisory database to this path",
|
|
54
57
|
"",
|
|
58
|
+
"Other commands:",
|
|
59
|
+
" install-skill Install AI assistant skill files for Claude Code,",
|
|
60
|
+
" Codex CLI, Gemini CLI, Cursor, and GitHub Copilot",
|
|
61
|
+
"",
|
|
55
62
|
" -v, --version Show the CLI version",
|
|
56
63
|
" -h, --help Show this help message"
|
|
57
64
|
];
|
package/dist/index.js
CHANGED
|
@@ -16,9 +16,11 @@ import { buildSuggestedFixCommandPlan } from "./remediation/fix-commands.js";
|
|
|
16
16
|
import { scanProjectForPackageUsage } from "./usage/scanner.js";
|
|
17
17
|
import { getCliVersion } from "./utils/version-info.js";
|
|
18
18
|
import { isLikelyBlockedAdvisoryRequestError } from "./utils/network.js";
|
|
19
|
-
import { logInfo, logWarn, printCacheSummary,
|
|
19
|
+
import { logInfo, logWarn, printCacheSummary, sortFindingsForOutput } from "./output/formatters.js";
|
|
20
20
|
import { buildReportData, writeHtmlReport } from "./output/html-reporter.js";
|
|
21
|
+
import { writeOutputs } from "./output/write-outputs.js";
|
|
21
22
|
import { printSummary, printActionSummary, printSuggestedFixCommands, printSuggestedFixCommandSkips, printCoverage, printSkippedDependencies, printTable, printFinalStatus, printCompactOutput } from "./output/printers.js";
|
|
23
|
+
import { installSkill } from "./skills/install.js";
|
|
22
24
|
let parsedArgs = null;
|
|
23
25
|
try {
|
|
24
26
|
parsedArgs = parseArgs(process.argv.slice(2));
|
|
@@ -45,9 +47,7 @@ if (parsedArgs) {
|
|
|
45
47
|
const batchSize = Number(options.batchSize || 100);
|
|
46
48
|
const searchDepth = Math.max(0, Number(options.searchDepth || 4));
|
|
47
49
|
async function main() {
|
|
48
|
-
|
|
49
|
-
printBanner();
|
|
50
|
-
}
|
|
50
|
+
printBanner();
|
|
51
51
|
if (command === "advisories-sync") {
|
|
52
52
|
const spinner = createSpinner("Preparing advisory sync...", options);
|
|
53
53
|
const usePlainProgressLogs = !process.stdout.isTTY || !!options.json;
|
|
@@ -74,6 +74,11 @@ if (parsedArgs) {
|
|
|
74
74
|
process.exit(0);
|
|
75
75
|
return;
|
|
76
76
|
}
|
|
77
|
+
if (command === "install-skill") {
|
|
78
|
+
installSkill(process.cwd());
|
|
79
|
+
process.exit(0);
|
|
80
|
+
return;
|
|
81
|
+
}
|
|
77
82
|
if ((options.offline || options.offlineDb) && options.osvUrl) {
|
|
78
83
|
throw new Error("--offline/--offline-db cannot be used with --osv-url");
|
|
79
84
|
}
|
|
@@ -121,12 +126,14 @@ if (parsedArgs) {
|
|
|
121
126
|
}
|
|
122
127
|
throw error;
|
|
123
128
|
}
|
|
124
|
-
if (options.
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
129
|
+
if (!options.json) {
|
|
130
|
+
if (options.offline || options.offlineDb) {
|
|
131
|
+
console.log(chalk.gray("Offline mode:") + " " + chalk.yellow("enabled") + " " + chalk.gray("(no external advisory calls will be made)"));
|
|
132
|
+
}
|
|
133
|
+
console.log(`${chalk.gray("Advisory source:")} ${formatAdvisorySourceLine(advisorySourceLine)}`);
|
|
134
|
+
if (advisoryDbFreshnessLine) {
|
|
135
|
+
console.log(`${chalk.gray("Advisory DB freshness:")} ${advisoryDbFreshnessLine}`);
|
|
136
|
+
}
|
|
130
137
|
}
|
|
131
138
|
if (advisoryDbWarning) {
|
|
132
139
|
logWarn(advisoryDbWarning, options);
|
|
@@ -185,45 +192,40 @@ if (parsedArgs) {
|
|
|
185
192
|
remainingBySeverity: countBySeverity(scanState.sorted),
|
|
186
193
|
});
|
|
187
194
|
}
|
|
188
|
-
else
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
source: scanInput.source,
|
|
193
|
-
packageCount: packages.length,
|
|
194
|
-
findingCount: scanState.sorted.length,
|
|
195
|
+
else {
|
|
196
|
+
await writeOutputs(options, {
|
|
197
|
+
sorted: scanState.sorted,
|
|
198
|
+
allPackages: scanState.allPackages,
|
|
195
199
|
suggestedFixCommands: scanState.suggestedFixCommands,
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
200
|
+
coverage: scanState.coverage,
|
|
201
|
+
minSeverity: scanState.minSeverity,
|
|
202
|
+
tableFindings: scanState.tableFindings,
|
|
203
|
+
}, scanInput, projectPath);
|
|
204
|
+
if (!(options.json || options.sarif || options.cdx) || options.verbose) {
|
|
205
|
+
const offline = !!options.offline || !!options.offlineDb;
|
|
206
|
+
if (options.verbose) {
|
|
207
|
+
printSummary(scanState.sorted, packages.length, scanInput);
|
|
208
|
+
printActionSummary(scanState.sorted);
|
|
209
|
+
printSuggestedFixCommands(scanState.sorted, scanInput, { offline });
|
|
210
|
+
printSuggestedFixCommandSkips(scanState.sorted, scanInput, { offline });
|
|
211
|
+
if (scanInput.skippedDependencies.length > 0) {
|
|
212
|
+
printSkippedDependencies(scanInput.skippedDependencies);
|
|
213
|
+
}
|
|
214
|
+
if (scanState.sorted.length > 0) {
|
|
215
|
+
if (scanState.tableFindings.length > 0) {
|
|
216
|
+
printTable(scanState.tableFindings, options.all ? null : scanState.minSeverity);
|
|
217
|
+
}
|
|
218
|
+
else {
|
|
219
|
+
logInfo(`No findings met the table threshold of ${scanState.minSeverity}. Re-run with --all to show everything.`, options);
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
printCoverage([...scanInput.notes, ...scanState.coverage]);
|
|
223
|
+
printFinalStatus(scanState.sorted);
|
|
215
224
|
}
|
|
216
225
|
else {
|
|
217
|
-
|
|
226
|
+
printCompactOutput(scanState.sorted, scanInput, { offline, all: !!options.all });
|
|
218
227
|
}
|
|
219
228
|
}
|
|
220
|
-
printCoverage([...scanInput.notes, ...scanState.coverage]);
|
|
221
|
-
printFinalStatus(scanState.sorted);
|
|
222
|
-
}
|
|
223
|
-
else {
|
|
224
|
-
// Simplified output - cleaner, focused view
|
|
225
|
-
const offline = !!options.offline || !!options.offlineDb;
|
|
226
|
-
printCompactOutput(scanState.sorted, scanInput, { offline, all: !!options.all });
|
|
227
229
|
}
|
|
228
230
|
if (options.report) {
|
|
229
231
|
const outputDir = path.resolve(typeof options.report === "string" ? options.report : "./cve-report");
|
|
@@ -277,7 +279,7 @@ async function scanProject(params) {
|
|
|
277
279
|
scanFilePath: params.scanInput.filePath,
|
|
278
280
|
});
|
|
279
281
|
if (params.options.usage) {
|
|
280
|
-
|
|
282
|
+
logInfo(`Scanning project source for usage hints...`, params.options);
|
|
281
283
|
const pkgNames = new Set(findings.map(f => f.pkg.name));
|
|
282
284
|
const usageData = scanProjectForPackageUsage(params.projectPath, pkgNames);
|
|
283
285
|
for (const finding of findings) {
|
|
@@ -308,6 +310,7 @@ async function scanProject(params) {
|
|
|
308
310
|
minSeverity,
|
|
309
311
|
tableFindings,
|
|
310
312
|
suggestedFixCommands,
|
|
313
|
+
allPackages: params.scanInput.packages,
|
|
311
314
|
};
|
|
312
315
|
}
|
|
313
316
|
async function applyFixesIfRequested(params) {
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
const PROVIDERS = {
|
|
2
|
+
claude: {
|
|
3
|
+
endpoint: "https://api.anthropic.com/v1/messages",
|
|
4
|
+
model: "claude-haiku-4-5-20251001",
|
|
5
|
+
},
|
|
6
|
+
};
|
|
7
|
+
async function doFetch(endpoint, apiKey, body) {
|
|
8
|
+
return fetch(endpoint, {
|
|
9
|
+
method: "POST",
|
|
10
|
+
headers: {
|
|
11
|
+
"x-api-key": apiKey,
|
|
12
|
+
"anthropic-version": "2023-06-01",
|
|
13
|
+
"content-type": "application/json",
|
|
14
|
+
},
|
|
15
|
+
body,
|
|
16
|
+
signal: AbortSignal.timeout(15000),
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
export async function callLlm(config, prompt) {
|
|
20
|
+
const provider = PROVIDERS[config.provider];
|
|
21
|
+
if (!provider) {
|
|
22
|
+
throw new Error(`Unsupported LLM provider: "${config.provider}". Supported: ${Object.keys(PROVIDERS).join(", ")}`);
|
|
23
|
+
}
|
|
24
|
+
const body = JSON.stringify({
|
|
25
|
+
model: provider.model,
|
|
26
|
+
max_tokens: 200,
|
|
27
|
+
messages: [{ role: "user", content: prompt }],
|
|
28
|
+
});
|
|
29
|
+
let response = await doFetch(provider.endpoint, config.apiKey, body);
|
|
30
|
+
if (response.status === 429) {
|
|
31
|
+
await new Promise(r => setTimeout(r, 2000));
|
|
32
|
+
response = await doFetch(provider.endpoint, config.apiKey, body);
|
|
33
|
+
}
|
|
34
|
+
if (!response.ok) {
|
|
35
|
+
const errText = await response.text();
|
|
36
|
+
throw new Error(`LLM API error (${response.status}): ${errText}`);
|
|
37
|
+
}
|
|
38
|
+
const data = await response.json();
|
|
39
|
+
return data.content.find(c => c.type === "text")?.text ?? "";
|
|
40
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import os from "node:os";
|
|
4
|
+
function readConfigFile(filePath) {
|
|
5
|
+
try {
|
|
6
|
+
return JSON.parse(fs.readFileSync(filePath, "utf8"));
|
|
7
|
+
}
|
|
8
|
+
catch {
|
|
9
|
+
return {};
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
export function loadLlmConfig(projectRoot) {
|
|
13
|
+
const globalPath = path.join(os.homedir(), ".cve-lite", "config.json");
|
|
14
|
+
const projectPath = path.join(projectRoot ?? process.cwd(), ".cve-lite.json");
|
|
15
|
+
const globalLlm = readConfigFile(globalPath).llm ?? {};
|
|
16
|
+
const projectLlm = readConfigFile(projectPath).llm ?? {};
|
|
17
|
+
const merged = {
|
|
18
|
+
provider: projectLlm.provider ?? globalLlm.provider ?? "",
|
|
19
|
+
providers: { ...(globalLlm.providers ?? {}), ...(projectLlm.providers ?? {}) },
|
|
20
|
+
};
|
|
21
|
+
if (!merged.provider)
|
|
22
|
+
return null;
|
|
23
|
+
return merged;
|
|
24
|
+
}
|
|
25
|
+
export function resolveLlmConfig(projectRoot) {
|
|
26
|
+
const config = loadLlmConfig(projectRoot);
|
|
27
|
+
if (!config?.provider) {
|
|
28
|
+
throw new Error('No LLM provider configured. Create ~/.cve-lite/config.json or .cve-lite.json with an "llm" block.');
|
|
29
|
+
}
|
|
30
|
+
const providerConfig = config.providers[config.provider];
|
|
31
|
+
if (!providerConfig?.apiKey) {
|
|
32
|
+
throw new Error(`No API key configured for provider "${config.provider}". Add it under llm.providers.${config.provider}.apiKey.`);
|
|
33
|
+
}
|
|
34
|
+
return { provider: config.provider, apiKey: providerConfig.apiKey };
|
|
35
|
+
}
|
|
36
|
+
export function checkGitignore(projectRoot) {
|
|
37
|
+
const projectPath = path.join(projectRoot ?? process.cwd(), ".cve-lite.json");
|
|
38
|
+
if (!fs.existsSync(projectPath))
|
|
39
|
+
return true;
|
|
40
|
+
const gitignorePath = path.join(projectRoot ?? process.cwd(), ".gitignore");
|
|
41
|
+
try {
|
|
42
|
+
const lines = fs.readFileSync(gitignorePath, "utf8").split("\n");
|
|
43
|
+
return lines.some((l) => l.trim() === ".cve-lite.json");
|
|
44
|
+
}
|
|
45
|
+
catch {
|
|
46
|
+
return false;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { callLlm } from "./client.js";
|
|
2
|
+
import { runWithConcurrency } from "../utils/array.js";
|
|
3
|
+
export function buildPrompt(finding) {
|
|
4
|
+
const cve = finding.cveAliases[0] ?? finding.vulnerabilities[0]?.id ?? "unknown";
|
|
5
|
+
const summary = finding.vulnerabilities[0]?.summary ?? "No summary available";
|
|
6
|
+
const fixLine = finding.firstFixedVersion
|
|
7
|
+
? `Fix available: upgrade to ${finding.firstFixedVersion}`
|
|
8
|
+
: "No fix is currently available.";
|
|
9
|
+
return [
|
|
10
|
+
"You are a security advisor helping a developer understand a vulnerability.",
|
|
11
|
+
"",
|
|
12
|
+
`Package: ${finding.pkg.name}@${finding.pkg.version}`,
|
|
13
|
+
`Severity: ${finding.severity}`,
|
|
14
|
+
`CVE: ${cve}`,
|
|
15
|
+
`Summary: ${summary}`,
|
|
16
|
+
fixLine,
|
|
17
|
+
"",
|
|
18
|
+
"In one short paragraph, explain what this vulnerability does and whether a typical Node.js application using this package is at risk. Be direct and practical.",
|
|
19
|
+
].join("\n");
|
|
20
|
+
}
|
|
21
|
+
export async function explainFinding(finding, config) {
|
|
22
|
+
try {
|
|
23
|
+
return await callLlm(config, buildPrompt(finding));
|
|
24
|
+
}
|
|
25
|
+
catch {
|
|
26
|
+
return null;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
export async function explainFindings(findings, config) {
|
|
30
|
+
return runWithConcurrency(findings, 3, finding => explainFinding(finding, config));
|
|
31
|
+
}
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { randomUUID } from "node:crypto";
|
|
4
|
+
import { findSuggestedCommandForFinding } from "../remediation/fix-commands.js";
|
|
5
|
+
import { getRecommendedAction } from "./formatters.js";
|
|
6
|
+
import { getCliVersion } from "../utils/version-info.js";
|
|
7
|
+
export function buildPurl(name, version) {
|
|
8
|
+
const encodedName = name.startsWith("@") ? `%40${name.slice(1)}` : name;
|
|
9
|
+
return `pkg:npm/${encodedName}@${version}`;
|
|
10
|
+
}
|
|
11
|
+
export function buildCycloneDxBom(allPackages, findings, projectMeta, version, plan = null) {
|
|
12
|
+
const components = allPackages.map(pkg => {
|
|
13
|
+
const purl = buildPurl(pkg.name, pkg.version);
|
|
14
|
+
return {
|
|
15
|
+
type: "library",
|
|
16
|
+
"bom-ref": purl,
|
|
17
|
+
name: pkg.name,
|
|
18
|
+
version: pkg.version,
|
|
19
|
+
purl,
|
|
20
|
+
};
|
|
21
|
+
});
|
|
22
|
+
// Deduplicate vulnerabilities by CVE ID — one entry per CVE with multiple affects
|
|
23
|
+
const vulnMap = new Map();
|
|
24
|
+
for (const finding of findings) {
|
|
25
|
+
const cveIds = finding.cveAliases.length > 0
|
|
26
|
+
? finding.cveAliases
|
|
27
|
+
: finding.vulnerabilities.map(v => v.id);
|
|
28
|
+
const purl = buildPurl(finding.pkg.name, finding.pkg.version);
|
|
29
|
+
for (const cveId of cveIds) {
|
|
30
|
+
const existing = vulnMap.get(cveId);
|
|
31
|
+
if (existing) {
|
|
32
|
+
existing.affects.push({ ref: purl });
|
|
33
|
+
}
|
|
34
|
+
else {
|
|
35
|
+
// severity from first finding wins when the same CVE affects multiple packages
|
|
36
|
+
vulnMap.set(cveId, { finding, affects: [{ ref: purl }] });
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
const vulnerabilities = [];
|
|
41
|
+
for (const [cveId, { finding, affects }] of vulnMap) {
|
|
42
|
+
const runnableFixCommand = plan ? findSuggestedCommandForFinding(plan, finding) : null;
|
|
43
|
+
const recommendation = runnableFixCommand ?? getRecommendedAction(finding);
|
|
44
|
+
vulnerabilities.push({
|
|
45
|
+
id: cveId,
|
|
46
|
+
source: {
|
|
47
|
+
name: "OSV",
|
|
48
|
+
url: `https://osv.dev/vulnerability/${cveId}`,
|
|
49
|
+
},
|
|
50
|
+
ratings: [{ severity: finding.severity, method: "other" }],
|
|
51
|
+
affects,
|
|
52
|
+
recommendation,
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
const metadata = {
|
|
56
|
+
timestamp: new Date().toISOString(),
|
|
57
|
+
tools: [
|
|
58
|
+
{ vendor: "OWASP", name: "CVE Lite CLI", version },
|
|
59
|
+
],
|
|
60
|
+
};
|
|
61
|
+
if (projectMeta && projectMeta.name) {
|
|
62
|
+
const metaComponent = {
|
|
63
|
+
type: "application",
|
|
64
|
+
name: projectMeta.name,
|
|
65
|
+
};
|
|
66
|
+
if (projectMeta.version) {
|
|
67
|
+
metaComponent.version = projectMeta.version;
|
|
68
|
+
}
|
|
69
|
+
metadata.component = metaComponent;
|
|
70
|
+
}
|
|
71
|
+
return {
|
|
72
|
+
bomFormat: "CycloneDX",
|
|
73
|
+
specVersion: "1.4",
|
|
74
|
+
version: 1,
|
|
75
|
+
serialNumber: `urn:uuid:${randomUUID()}`,
|
|
76
|
+
metadata,
|
|
77
|
+
components,
|
|
78
|
+
vulnerabilities,
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
export function writeCycloneDxReport(allPackages, findings, plan, projectMeta) {
|
|
82
|
+
const ts = new Date().toISOString().replace(/[:.]/g, "-").slice(0, 19);
|
|
83
|
+
const filename = `cve-lite-scan-${ts}.cdx.json`;
|
|
84
|
+
const outputPath = path.join(process.cwd(), filename);
|
|
85
|
+
const bom = buildCycloneDxBom(allPackages, findings, projectMeta, getCliVersion(), plan);
|
|
86
|
+
fs.writeFileSync(outputPath, JSON.stringify(bom, null, 2));
|
|
87
|
+
return filename;
|
|
88
|
+
}
|
|
@@ -4,6 +4,7 @@ import { severityOrder } from "../constants.js";
|
|
|
4
4
|
import { loadCache } from "../osv/cache.js";
|
|
5
5
|
import { inferSeverity } from "../osv/severity.js";
|
|
6
6
|
import { getPrimaryParent } from "../utils/finding.js";
|
|
7
|
+
import { calculatePathCoverage, formatDependencyPath } from "../utils/path-coverage.js";
|
|
7
8
|
export function formatSeverityLabel(severity) {
|
|
8
9
|
const lower = severity.toLowerCase();
|
|
9
10
|
if (lower === "critical")
|
|
@@ -42,10 +43,12 @@ export function getRecommendedAction(finding) {
|
|
|
42
43
|
}
|
|
43
44
|
if (finding.recommendedNpmTransitiveRemediation?.kind === "upgrade-parent-to-version" &&
|
|
44
45
|
finding.recommendedNpmTransitiveRemediation.targetVersion) {
|
|
45
|
-
|
|
46
|
+
const coverage = calculatePathCoverage(finding.dependencyPaths, finding.recommendedNpmTransitiveRemediation.viaPath);
|
|
47
|
+
return formatParentUpgradeAction(finding.pkg.name, finding.pkg.version, finding.recommendedNpmTransitiveRemediation.package, finding.recommendedNpmTransitiveRemediation.currentVersion, finding.recommendedNpmTransitiveRemediation.targetVersion, coverage);
|
|
46
48
|
}
|
|
47
49
|
if (finding.recommendedParentUpgrade) {
|
|
48
|
-
|
|
50
|
+
const coverage = calculatePathCoverage(finding.dependencyPaths, finding.recommendedParentUpgrade.viaPath);
|
|
51
|
+
return formatParentUpgradeAction(finding.pkg.name, finding.pkg.version, finding.recommendedParentUpgrade.package, finding.recommendedParentUpgrade.currentVersion, finding.recommendedParentUpgrade.targetVersion, coverage);
|
|
49
52
|
}
|
|
50
53
|
const parent = getPrimaryParent(finding);
|
|
51
54
|
if (parent && directTarget) {
|
|
@@ -75,10 +78,16 @@ export function summarizeRisk(finding) {
|
|
|
75
78
|
risk = `Transitive issue. The current parent range can already absorb a safe ${finding.pkg.name} update via ${finding.recommendedNpmTransitiveRemediation.package}.`;
|
|
76
79
|
}
|
|
77
80
|
else if (finding.relationship === "transitive" && finding.recommendedNpmTransitiveRemediation?.kind === "upgrade-parent-to-version") {
|
|
78
|
-
|
|
81
|
+
const coverage = calculatePathCoverage(finding.dependencyPaths, finding.recommendedNpmTransitiveRemediation.viaPath);
|
|
82
|
+
risk = coverage.coverage === "complete"
|
|
83
|
+
? `Transitive issue. A specific parent upgrade target was found for ${finding.recommendedNpmTransitiveRemediation.package}.`
|
|
84
|
+
: `Transitive issue. A path-specific parent upgrade target was found for ${finding.recommendedNpmTransitiveRemediation.package}; run it, rescan, and review remaining paths separately.`;
|
|
79
85
|
}
|
|
80
86
|
else if (finding.relationship === "transitive" && finding.recommendedParentUpgrade) {
|
|
81
|
-
|
|
87
|
+
const coverage = calculatePathCoverage(finding.dependencyPaths, finding.recommendedParentUpgrade.viaPath);
|
|
88
|
+
risk = coverage.coverage === "complete"
|
|
89
|
+
? `Transitive issue. A specific parent upgrade target was found for ${finding.recommendedParentUpgrade.package}.`
|
|
90
|
+
: `Transitive issue. A path-specific parent upgrade target was found for ${finding.recommendedParentUpgrade.package}; run it, rescan, and review remaining paths separately.`;
|
|
82
91
|
}
|
|
83
92
|
else if (finding.relationship === "transitive" && (finding.validatedFirstFixedVersion ?? finding.firstFixedVersion)) {
|
|
84
93
|
const target = finding.validatedFirstFixedVersion ?? finding.firstFixedVersion;
|
|
@@ -104,6 +113,17 @@ export function summarizeRisk(finding) {
|
|
|
104
113
|
}
|
|
105
114
|
return risk;
|
|
106
115
|
}
|
|
116
|
+
function formatParentUpgradeAction(vulnerableName, vulnerableVersion, parentName, currentVersion, targetVersion, coverage) {
|
|
117
|
+
const pathText = coverage.coveredPaths[0]
|
|
118
|
+
? ` for ${formatDependencyPath(coverage.coveredPaths[0])}`
|
|
119
|
+
: "";
|
|
120
|
+
const upgrade = `Upgrade ${parentName} from ${currentVersion} to ${targetVersion}`;
|
|
121
|
+
if (coverage.coverage === "complete") {
|
|
122
|
+
return `${upgrade} to resolve vulnerable ${vulnerableName}@${vulnerableVersion}${pathText}.`;
|
|
123
|
+
}
|
|
124
|
+
const remainingCount = coverage.remainingPaths.length;
|
|
125
|
+
return `${upgrade} to resolve the ${vulnerableName}@${vulnerableVersion} path${pathText}; run it, then rescan. ${remainingCount} other known path${remainingCount === 1 ? "" : "s"} may still need separate parent upgrades.`;
|
|
126
|
+
}
|
|
107
127
|
export function summarizeNextAction(finding) {
|
|
108
128
|
// Prefer the registry-validated target over the raw advisory hint so this
|
|
109
129
|
// line agrees with the fix-command table. See getRecommendedAction.
|
|
@@ -163,6 +163,7 @@ button.header-link:hover{color:#58a6ff;border-color:#58a6ff}
|
|
|
163
163
|
.fix-target-to{font-family:'SF Mono','Cascadia Code','Fira Code',monospace;color:#3fb950}
|
|
164
164
|
.fix-target-stats{color:#6b7280;font-size:10px}
|
|
165
165
|
.fix-target-note{color:#6b7280;font-style:italic;font-size:10px}
|
|
166
|
+
.fix-target-coverage{flex-basis:100%;color:#6b7280;font-size:10px;line-height:1.45}
|
|
166
167
|
.break-badge{font-size:10px;font-weight:700;background:#fb850022;color:#fb8500;border:1px solid #fb850066;border-radius:4px;padding:1px 5px}
|
|
167
168
|
.tier-ok{display:inline-flex;align-items:center;gap:4px;font-size:10px;padding:2px 8px;border-radius:4px;background:#3fb95022;color:#3fb950;border:1px solid #3fb95033;margin-bottom:6px}
|
|
168
169
|
.tier-warn{display:inline-flex;align-items:center;gap:4px;font-size:10px;padding:2px 8px;border-radius:4px;background:#e3b34122;color:#e3b341;border:1px solid #e3b34133;margin-bottom:6px}
|
|
@@ -495,7 +496,10 @@ function renderFixPlan(plan) {
|
|
|
495
496
|
const noteHtml = t.adjusted && t.adjustmentNote
|
|
496
497
|
? ` <span class="fix-target-note">${escapeHtml(t.adjustmentNote)}</span>`
|
|
497
498
|
: "";
|
|
498
|
-
|
|
499
|
+
const coverageHtml = t.coverage === "partial"
|
|
500
|
+
? ` <span class="fix-target-coverage">Path-specific remediation. Run this command, then rescan; ${t.remainingPaths?.length ?? 0} other known path${(t.remainingPaths?.length ?? 0) === 1 ? "" : "s"} may still need separate parent upgrades.</span>`
|
|
501
|
+
: "";
|
|
502
|
+
return `<div class="fix-target-row">${versionHtml}${breakBadge}${statsHtml}${noteHtml}${coverageHtml}</div>`;
|
|
499
503
|
}).join("\n");
|
|
500
504
|
const targetsHtml = section.targets.length > 0
|
|
501
505
|
? `<div class="fix-targets-list">${targetRows}</div>`
|
package/dist/output/printers.js
CHANGED
|
@@ -215,6 +215,40 @@ function truncate(value, width) {
|
|
|
215
215
|
return value;
|
|
216
216
|
return plain.slice(0, Math.max(0, width - 1)) + "…";
|
|
217
217
|
}
|
|
218
|
+
function renderWrappedRow(cells, widths) {
|
|
219
|
+
const wrappedCells = cells.map((cell, i) => wrapCell(cell, widths[i]));
|
|
220
|
+
const rowHeight = Math.max(...wrappedCells.map(cellLines => cellLines.length));
|
|
221
|
+
const rows = [];
|
|
222
|
+
for (let lineIndex = 0; lineIndex < rowHeight; lineIndex++) {
|
|
223
|
+
const formatted = wrappedCells.map((cellLines, i) => {
|
|
224
|
+
const value = cellLines[lineIndex] ?? "";
|
|
225
|
+
const visible = stripAnsi(value);
|
|
226
|
+
return ` ${value}${" ".repeat(Math.max(0, widths[i] - visible.length))} `;
|
|
227
|
+
});
|
|
228
|
+
rows.push("│" + formatted.join("│") + "│");
|
|
229
|
+
}
|
|
230
|
+
return rows;
|
|
231
|
+
}
|
|
232
|
+
function wrapCell(value, width) {
|
|
233
|
+
const plain = stripAnsi(value);
|
|
234
|
+
if (plain.length <= width)
|
|
235
|
+
return [value];
|
|
236
|
+
if (width <= 0)
|
|
237
|
+
return [""];
|
|
238
|
+
const lines = [];
|
|
239
|
+
let remaining = plain.trim();
|
|
240
|
+
while (remaining.length > width) {
|
|
241
|
+
let breakAt = remaining.lastIndexOf(" ", width);
|
|
242
|
+
if (breakAt <= 0)
|
|
243
|
+
breakAt = width;
|
|
244
|
+
lines.push(remaining.slice(0, breakAt).trimEnd());
|
|
245
|
+
remaining = remaining.slice(breakAt).trimStart();
|
|
246
|
+
}
|
|
247
|
+
if (remaining.length > 0) {
|
|
248
|
+
lines.push(remaining);
|
|
249
|
+
}
|
|
250
|
+
return lines.length > 0 ? lines : [""];
|
|
251
|
+
}
|
|
218
252
|
export function printCompactOutput(findings, scanInput, options) {
|
|
219
253
|
console.log("");
|
|
220
254
|
if (findings.length === 0) {
|
|
@@ -509,7 +543,9 @@ function printParentUpgradeTargetsTable(targets, widthsOverride) {
|
|
|
509
543
|
console.log(renderRow(headers, widths));
|
|
510
544
|
console.log(line("├", "┼", "┤"));
|
|
511
545
|
for (const row of rows) {
|
|
512
|
-
|
|
546
|
+
for (const outputRow of renderWrappedRow(row.map(value => String(value)), widths)) {
|
|
547
|
+
console.log(outputRow);
|
|
548
|
+
}
|
|
513
549
|
}
|
|
514
550
|
console.log(line("└", "┴", "┘"));
|
|
515
551
|
}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { findSuggestedCommandForFinding } from "../remediation/fix-commands.js";
|
|
4
|
+
import { getRecommendedAction } from "./formatters.js";
|
|
5
|
+
import { getCliVersion } from "../utils/version-info.js";
|
|
6
|
+
import { severityToSarifLevel } from "../utils/severity.js";
|
|
7
|
+
const SARIF_RULE_NAME = "VulnerableDependency";
|
|
8
|
+
const LOCKFILE_NAMES = {
|
|
9
|
+
"package-lock": "package-lock.json",
|
|
10
|
+
"pnpm-lock": "pnpm-lock.yaml",
|
|
11
|
+
"yarn-lock": "yarn.lock",
|
|
12
|
+
"bun-lock": "bun.lockb",
|
|
13
|
+
"package-json": "package.json",
|
|
14
|
+
"unknown": "lockfile",
|
|
15
|
+
};
|
|
16
|
+
export function deriveLockfileUri(scanInput) {
|
|
17
|
+
if (scanInput.filePath)
|
|
18
|
+
return path.basename(scanInput.filePath);
|
|
19
|
+
return LOCKFILE_NAMES[scanInput.source] ?? "lockfile";
|
|
20
|
+
}
|
|
21
|
+
export function buildSarifOutput(findings, lockfileUri, version, plan) {
|
|
22
|
+
const ruleMap = new Map();
|
|
23
|
+
const results = [];
|
|
24
|
+
for (const finding of findings) {
|
|
25
|
+
const level = severityToSarifLevel(finding.severity);
|
|
26
|
+
const action = getRecommendedAction(finding);
|
|
27
|
+
const runnableFixCommand = plan ? findSuggestedCommandForFinding(plan, finding) : null;
|
|
28
|
+
const location = {
|
|
29
|
+
physicalLocation: {
|
|
30
|
+
artifactLocation: { uri: lockfileUri, uriBaseId: "%SRCROOT%" },
|
|
31
|
+
region: { startLine: 1 },
|
|
32
|
+
},
|
|
33
|
+
};
|
|
34
|
+
const ruleIds = finding.cveAliases.length > 0
|
|
35
|
+
? finding.cveAliases
|
|
36
|
+
: finding.vulnerabilities.map(v => v.id);
|
|
37
|
+
for (const ruleId of ruleIds) {
|
|
38
|
+
if (!ruleMap.has(ruleId)) {
|
|
39
|
+
ruleMap.set(ruleId, {
|
|
40
|
+
id: ruleId,
|
|
41
|
+
name: SARIF_RULE_NAME,
|
|
42
|
+
shortDescription: { text: ruleId },
|
|
43
|
+
fullDescription: { text: `Vulnerable dependency: ${ruleId}` },
|
|
44
|
+
helpUri: `https://osv.dev/vulnerability/${ruleId}`,
|
|
45
|
+
defaultConfiguration: { level },
|
|
46
|
+
properties: { tags: ["security", "dependency"] },
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
const result = {
|
|
50
|
+
ruleId,
|
|
51
|
+
level,
|
|
52
|
+
message: {
|
|
53
|
+
text: `${finding.pkg.name}@${finding.pkg.version} is vulnerable (${finding.severity}). ${action}`,
|
|
54
|
+
},
|
|
55
|
+
locations: [location],
|
|
56
|
+
};
|
|
57
|
+
if (runnableFixCommand) {
|
|
58
|
+
result.fixes = [{ description: { text: runnableFixCommand }, artifactChanges: [] }];
|
|
59
|
+
}
|
|
60
|
+
results.push(result);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
return {
|
|
64
|
+
$schema: "https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/Schemata/sarif-schema-2.1.0.json",
|
|
65
|
+
version: "2.1.0",
|
|
66
|
+
runs: [
|
|
67
|
+
{
|
|
68
|
+
tool: {
|
|
69
|
+
driver: {
|
|
70
|
+
name: "CVE Lite CLI",
|
|
71
|
+
version,
|
|
72
|
+
informationUri: "https://owasp.org/cve-lite-cli/",
|
|
73
|
+
rules: Array.from(ruleMap.values()),
|
|
74
|
+
},
|
|
75
|
+
},
|
|
76
|
+
results,
|
|
77
|
+
artifacts: [
|
|
78
|
+
{ location: { uri: lockfileUri, uriBaseId: "%SRCROOT%" } },
|
|
79
|
+
],
|
|
80
|
+
},
|
|
81
|
+
],
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
export function writeSarifReport(findings, lockfileUri, plan) {
|
|
85
|
+
const ts = new Date().toISOString().replace(/[:.]/g, "-").slice(0, 19);
|
|
86
|
+
const filename = `cve-lite-scan-${ts}.sarif`;
|
|
87
|
+
const outputPath = path.join(process.cwd(), filename);
|
|
88
|
+
const sarif = buildSarifOutput(findings, lockfileUri, getCliVersion(), plan);
|
|
89
|
+
fs.writeFileSync(outputPath, JSON.stringify(sarif, null, 2));
|
|
90
|
+
return filename;
|
|
91
|
+
}
|
package/dist/output/spinner.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import process from "node:process";
|
|
2
2
|
import { chalk } from "../utils/chalk.js";
|
|
3
3
|
export function createSpinner(initialMessage, options) {
|
|
4
|
-
const enabled =
|
|
4
|
+
const enabled = Boolean(process.stdout.isTTY);
|
|
5
5
|
if (!enabled) {
|
|
6
6
|
return {
|
|
7
7
|
update: () => { },
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { chalk } from "../utils/chalk.js";
|
|
4
|
+
import { serializeFinding } from "./formatters.js";
|
|
5
|
+
import { writeSarifReport, deriveLockfileUri } from "./sarif.js";
|
|
6
|
+
import { writeCycloneDxReport } from "./cyclonedx.js";
|
|
7
|
+
function readProjectMeta(projectPath) {
|
|
8
|
+
try {
|
|
9
|
+
const pkgPath = path.join(projectPath, "package.json");
|
|
10
|
+
if (!fs.existsSync(pkgPath))
|
|
11
|
+
return null;
|
|
12
|
+
const raw = fs.readFileSync(pkgPath, "utf-8");
|
|
13
|
+
const parsed = JSON.parse(raw);
|
|
14
|
+
if (!parsed.name)
|
|
15
|
+
return null;
|
|
16
|
+
return {
|
|
17
|
+
name: typeof parsed.name === "string" ? parsed.name : undefined,
|
|
18
|
+
version: typeof parsed.version === "string" ? parsed.version : undefined,
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
catch {
|
|
22
|
+
return null;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
export async function writeOutputs(options, scanState, scanInput, projectPath) {
|
|
26
|
+
if (options.json) {
|
|
27
|
+
const ts = new Date().toISOString().replace(/[:.]/g, "-").slice(0, 19);
|
|
28
|
+
const jsonFilename = `cve-lite-scan-${ts}.json`;
|
|
29
|
+
const jsonOutputPath = path.join(process.cwd(), jsonFilename);
|
|
30
|
+
fs.writeFileSync(jsonOutputPath, JSON.stringify({
|
|
31
|
+
projectPath,
|
|
32
|
+
mode: scanInput.mode,
|
|
33
|
+
source: scanInput.source,
|
|
34
|
+
packageCount: scanInput.packages.length,
|
|
35
|
+
findingCount: scanState.sorted.length,
|
|
36
|
+
suggestedFixCommands: scanState.suggestedFixCommands,
|
|
37
|
+
notes: [...scanInput.notes, ...scanState.coverage],
|
|
38
|
+
warnings: scanInput.warnings,
|
|
39
|
+
skippedDependencies: scanInput.skippedDependencies,
|
|
40
|
+
findings: scanState.sorted.map(finding => serializeFinding(finding, scanState.suggestedFixCommands)),
|
|
41
|
+
}, null, 2));
|
|
42
|
+
console.log(`${chalk.gray("JSON saved to")} ${chalk.cyan(jsonFilename)}`);
|
|
43
|
+
}
|
|
44
|
+
if (options.sarif) {
|
|
45
|
+
const lockfileUri = deriveLockfileUri(scanInput);
|
|
46
|
+
const sarifFilename = writeSarifReport(scanState.sorted, lockfileUri, scanState.suggestedFixCommands);
|
|
47
|
+
console.log(`${chalk.gray("SARIF report written to")} ${chalk.cyan(sarifFilename)}`);
|
|
48
|
+
}
|
|
49
|
+
if (options.cdx) {
|
|
50
|
+
const projectMeta = readProjectMeta(projectPath);
|
|
51
|
+
const cdxFilename = writeCycloneDxReport(scanState.allPackages, scanState.sorted, scanState.suggestedFixCommands, projectMeta);
|
|
52
|
+
console.log(`${chalk.gray("CycloneDX BOM written to")} ${chalk.cyan(cdxFilename)}`);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
@@ -3,6 +3,8 @@ import YAML from "yaml";
|
|
|
3
3
|
import { looksLikeVersion, normalizeRawVersion } from "../utils/version.js";
|
|
4
4
|
import { upsertPackage } from "./utils.js";
|
|
5
5
|
import { uniquePathArrays } from "../utils/array.js";
|
|
6
|
+
const MAX_PATHS_PER_PACKAGE = 5;
|
|
7
|
+
const MAX_PATH_DEPTH = 10;
|
|
6
8
|
export function loadFromPnpmLock(filePath, prodOnly) {
|
|
7
9
|
const content = fs.readFileSync(filePath, "utf8");
|
|
8
10
|
const parsed = YAML.parse(content);
|
|
@@ -61,27 +63,7 @@ function loadLegacy(parsed, prodOnly) {
|
|
|
61
63
|
}
|
|
62
64
|
}
|
|
63
65
|
}
|
|
64
|
-
|
|
65
|
-
const seenKeys = new Set();
|
|
66
|
-
while (queue.length > 0) {
|
|
67
|
-
const current = queue.shift();
|
|
68
|
-
if (seenKeys.has(current.key))
|
|
69
|
-
continue;
|
|
70
|
-
seenKeys.add(current.key);
|
|
71
|
-
const ref = parsePnpmPackageKey(current.key);
|
|
72
|
-
if (!ref)
|
|
73
|
-
continue;
|
|
74
|
-
const nextPath = [...current.path, ref.name];
|
|
75
|
-
const pkgKey = `${ref.name}@${ref.version}`;
|
|
76
|
-
const pkg = map.get(pkgKey);
|
|
77
|
-
if (pkg) {
|
|
78
|
-
pkg.paths = uniquePathArrays([...(pkg.paths ?? []), nextPath]).slice(0, 5);
|
|
79
|
-
}
|
|
80
|
-
const children = graph.get(current.key) ?? [];
|
|
81
|
-
for (const child of children) {
|
|
82
|
-
queue.push({ key: child, path: nextPath });
|
|
83
|
-
}
|
|
84
|
-
}
|
|
66
|
+
collectPnpmPaths(rootDeps, graph, map, parsePnpmPackageKey);
|
|
85
67
|
return [...map.values()];
|
|
86
68
|
}
|
|
87
69
|
function loadV9(parsed, prodOnly) {
|
|
@@ -136,28 +118,42 @@ function loadV9(parsed, prodOnly) {
|
|
|
136
118
|
}
|
|
137
119
|
}
|
|
138
120
|
}
|
|
121
|
+
collectPnpmPaths(rootDeps, graph, map, parsePnpmPackageKeyV9);
|
|
122
|
+
return [...map.values()];
|
|
123
|
+
}
|
|
124
|
+
function collectPnpmPaths(rootDeps, graph, map, parsePackageKey) {
|
|
139
125
|
const queue = rootDeps.map(dep => ({ key: dep, path: ["project"] }));
|
|
140
|
-
const
|
|
126
|
+
const visitedStates = new Set();
|
|
141
127
|
while (queue.length > 0) {
|
|
142
128
|
const current = queue.shift();
|
|
143
|
-
|
|
144
|
-
continue;
|
|
145
|
-
seenKeys.add(current.key);
|
|
146
|
-
const ref = parsePnpmPackageKeyV9(current.key);
|
|
129
|
+
const ref = parsePackageKey(current.key);
|
|
147
130
|
if (!ref)
|
|
148
131
|
continue;
|
|
149
132
|
const nextPath = [...current.path, ref.name];
|
|
133
|
+
const stateKey = `${ref.key}>${nextPath.join(">")}`;
|
|
134
|
+
if (visitedStates.has(stateKey))
|
|
135
|
+
continue;
|
|
136
|
+
visitedStates.add(stateKey);
|
|
150
137
|
const pkgKey = `${ref.name}@${ref.version}`;
|
|
151
138
|
const pkg = map.get(pkgKey);
|
|
152
139
|
if (pkg) {
|
|
153
|
-
pkg.paths = uniquePathArrays([...(pkg.paths ?? []), nextPath]).slice(0,
|
|
140
|
+
pkg.paths = uniquePathArrays([...(pkg.paths ?? []), nextPath]).slice(0, MAX_PATHS_PER_PACKAGE);
|
|
141
|
+
}
|
|
142
|
+
if (nextPath.length >= MAX_PATH_DEPTH)
|
|
143
|
+
continue;
|
|
144
|
+
if ((pkg?.paths?.length ?? 0) >= MAX_PATHS_PER_PACKAGE && !(pkg?.paths ?? []).some(path => pathsEqual(path, nextPath))) {
|
|
145
|
+
continue;
|
|
154
146
|
}
|
|
155
|
-
const children = graph.get(
|
|
147
|
+
const children = graph.get(ref.key) ?? [];
|
|
156
148
|
for (const child of children) {
|
|
157
149
|
queue.push({ key: child, path: nextPath });
|
|
158
150
|
}
|
|
159
151
|
}
|
|
160
|
-
|
|
152
|
+
}
|
|
153
|
+
function pathsEqual(left, right) {
|
|
154
|
+
if (left.length !== right.length)
|
|
155
|
+
return false;
|
|
156
|
+
return left.every((value, index) => value === right[index]);
|
|
161
157
|
}
|
|
162
158
|
function parsePnpmPackageKey(key) {
|
|
163
159
|
const cleaned = key.replace(/^\//, "").split("(")[0];
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { severityOrder } from "../constants.js";
|
|
2
2
|
import { compareVersions, looksLikeVersion } from "../utils/version.js";
|
|
3
3
|
import { getPrimaryParent } from "../utils/finding.js";
|
|
4
|
+
import { calculatePathCoverage, formatDependencyPath } from "../utils/path-coverage.js";
|
|
4
5
|
export function buildSuggestedFixCommandPlan(findings, scanInput, options) {
|
|
5
6
|
const packageManager = inferPackageManager(scanInput);
|
|
6
7
|
if (!packageManager)
|
|
@@ -130,6 +131,7 @@ export function buildSuggestedFixCommandPlan(findings, scanInput, options) {
|
|
|
130
131
|
finding.recommendedNpmTransitiveRemediation?.kind === "upgrade-parent-to-version" &&
|
|
131
132
|
finding.recommendedNpmTransitiveRemediation.targetVersion &&
|
|
132
133
|
isUpgradeTarget(finding.recommendedNpmTransitiveRemediation.currentVersion, finding.recommendedNpmTransitiveRemediation.targetVersion)) {
|
|
134
|
+
const coverage = calculatePathCoverage(finding.dependencyPaths, finding.recommendedNpmTransitiveRemediation.viaPath);
|
|
133
135
|
upsertTarget(targetsByPackage, {
|
|
134
136
|
package: finding.recommendedNpmTransitiveRemediation.package,
|
|
135
137
|
currentVersion: finding.recommendedNpmTransitiveRemediation.currentVersion,
|
|
@@ -141,7 +143,10 @@ export function buildSuggestedFixCommandPlan(findings, scanInput, options) {
|
|
|
141
143
|
severity: finding.severity,
|
|
142
144
|
adjusted: false,
|
|
143
145
|
adjustmentNote: null,
|
|
144
|
-
reason:
|
|
146
|
+
reason: buildParentUpgradeReason(finding, coverage),
|
|
147
|
+
coverage: coverage.coverage,
|
|
148
|
+
coveredPaths: coverage.coveredPaths,
|
|
149
|
+
remainingPaths: coverage.remainingPaths,
|
|
145
150
|
usage: finding.usage ?? null,
|
|
146
151
|
});
|
|
147
152
|
continue;
|
|
@@ -149,6 +154,7 @@ export function buildSuggestedFixCommandPlan(findings, scanInput, options) {
|
|
|
149
154
|
if (finding.relationship === "transitive" &&
|
|
150
155
|
finding.recommendedParentUpgrade &&
|
|
151
156
|
isUpgradeTarget(finding.recommendedParentUpgrade.currentVersion, finding.recommendedParentUpgrade.targetVersion)) {
|
|
157
|
+
const coverage = calculatePathCoverage(finding.dependencyPaths, finding.recommendedParentUpgrade.viaPath);
|
|
152
158
|
upsertTarget(targetsByPackage, {
|
|
153
159
|
package: finding.recommendedParentUpgrade.package,
|
|
154
160
|
currentVersion: finding.recommendedParentUpgrade.currentVersion,
|
|
@@ -160,7 +166,10 @@ export function buildSuggestedFixCommandPlan(findings, scanInput, options) {
|
|
|
160
166
|
severity: finding.severity,
|
|
161
167
|
adjusted: false,
|
|
162
168
|
adjustmentNote: null,
|
|
163
|
-
reason:
|
|
169
|
+
reason: buildParentUpgradeReason(finding, coverage),
|
|
170
|
+
coverage: coverage.coverage,
|
|
171
|
+
coveredPaths: coverage.coveredPaths,
|
|
172
|
+
remainingPaths: coverage.remainingPaths,
|
|
164
173
|
usage: finding.usage ?? null,
|
|
165
174
|
});
|
|
166
175
|
continue;
|
|
@@ -308,6 +317,11 @@ function upsertTarget(targetsByPackage, next) {
|
|
|
308
317
|
: "parent-upgrade",
|
|
309
318
|
displayTargetVersion: existing.displayTargetVersion ?? next.displayTargetVersion,
|
|
310
319
|
command: existing.command ?? next.command,
|
|
320
|
+
coverage: existing.coverage === "partial" || next.coverage === "partial"
|
|
321
|
+
? "partial"
|
|
322
|
+
: existing.coverage ?? next.coverage,
|
|
323
|
+
coveredPaths: mergePathArrays(existing.coveredPaths ?? [], next.coveredPaths ?? []),
|
|
324
|
+
remainingPaths: mergePathArrays(existing.remainingPaths ?? [], next.remainingPaths ?? []),
|
|
311
325
|
usage: existing.usage || next.usage,
|
|
312
326
|
};
|
|
313
327
|
if (looksLikeVersion(existing.targetVersion) && looksLikeVersion(next.targetVersion)) {
|
|
@@ -331,6 +345,31 @@ function upsertTarget(targetsByPackage, next) {
|
|
|
331
345
|
}
|
|
332
346
|
targetsByPackage.set(next.package, merged);
|
|
333
347
|
}
|
|
348
|
+
function buildParentUpgradeReason(finding, coverage) {
|
|
349
|
+
const coveredPath = coverage.coveredPaths[0];
|
|
350
|
+
const pathText = coveredPath ? ` for ${formatDependencyPath(coveredPath)}` : "";
|
|
351
|
+
const base = coverage.coverage === "complete"
|
|
352
|
+
? `Parent upgrade for vulnerable ${finding.pkg.name}@${finding.pkg.version}${pathText}`
|
|
353
|
+
: coveredPath
|
|
354
|
+
? `Path-specific parent upgrade for ${formatDependencyPath(coveredPath)} (${finding.pkg.name}@${finding.pkg.version})`
|
|
355
|
+
: `Path-specific parent upgrade for vulnerable ${finding.pkg.name}@${finding.pkg.version}`;
|
|
356
|
+
if (coverage.coverage === "complete")
|
|
357
|
+
return base;
|
|
358
|
+
const remainingCount = coverage.remainingPaths.length;
|
|
359
|
+
return `${base}; run this command, then rescan. ${remainingCount} other known path${remainingCount === 1 ? "" : "s"} may still need separate parent upgrades.`;
|
|
360
|
+
}
|
|
361
|
+
function mergePathArrays(left, right) {
|
|
362
|
+
const seen = new Set();
|
|
363
|
+
const output = [];
|
|
364
|
+
for (const path of [...left, ...right]) {
|
|
365
|
+
const key = path.join(">");
|
|
366
|
+
if (seen.has(key))
|
|
367
|
+
continue;
|
|
368
|
+
seen.add(key);
|
|
369
|
+
output.push(path);
|
|
370
|
+
}
|
|
371
|
+
return output;
|
|
372
|
+
}
|
|
334
373
|
function isUpgradeTarget(currentVersion, targetVersion) {
|
|
335
374
|
if (!currentVersion || !targetVersion || currentVersion === targetVersion)
|
|
336
375
|
return false;
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
export const SKILL_CONTENT = `Run \`cve-lite . --json\` in the project root. The results are saved to \`cve-lite-scan-<timestamp>.json\` in the current directory.
|
|
2
|
+
|
|
3
|
+
### Getting scan data
|
|
4
|
+
|
|
5
|
+
Key fields in each finding:
|
|
6
|
+
|
|
7
|
+
- \`package\`, \`version\` — the vulnerable package
|
|
8
|
+
- \`severity\` — \`critical | high | medium | low | unknown\`
|
|
9
|
+
- \`relationship\` — \`direct | transitive\`
|
|
10
|
+
- \`firstFixedVersion\` — minimum safe version, if known
|
|
11
|
+
- \`runnableFixCommand\` — exact install command to run, if available
|
|
12
|
+
- \`recommendedAction\` — human-readable fix guidance
|
|
13
|
+
- \`cves\` — CVE IDs
|
|
14
|
+
- \`dependencyPaths\` — chains showing how the package is pulled in
|
|
15
|
+
- \`usage.imported\` — whether the package is actually imported in source files
|
|
16
|
+
|
|
17
|
+
Top-level \`suggestedFixCommands\` contains grouped, copy-ready fix commands.
|
|
18
|
+
|
|
19
|
+
### Prioritization
|
|
20
|
+
|
|
21
|
+
1. Critical before high before medium before low
|
|
22
|
+
2. Direct dependencies before transitive
|
|
23
|
+
3. If \`usage.imported === false\`, flag as lower practical risk but do not dismiss
|
|
24
|
+
4. If \`runnableFixCommand\` is present, that is the exact command to run — prefer it over manual guidance
|
|
25
|
+
|
|
26
|
+
### Codebase analysis
|
|
27
|
+
|
|
28
|
+
- Cross-reference vulnerable packages against source file imports to confirm reachability
|
|
29
|
+
- Check \`package.json\` version constraints for direct dependency findings
|
|
30
|
+
- Use \`dependencyPaths\` to trace transitive chains and identify which parent package to upgrade
|
|
31
|
+
- Look for patterns: a single parent responsible for multiple transitive findings (fixing the parent clears all of them)
|
|
32
|
+
|
|
33
|
+
### Output
|
|
34
|
+
|
|
35
|
+
Produce:
|
|
36
|
+
- A prioritized list of findings with their fix commands
|
|
37
|
+
- For each finding: severity, direct/transitive, imported/unused, recommended action
|
|
38
|
+
- Any patterns worth highlighting (one parent causing multiple transitive issues)
|
|
39
|
+
- A summary of what remains after the suggested fix commands are applied`;
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { chalk } from "../utils/chalk.js";
|
|
4
|
+
import { SKILL_CONTENT } from "./content.js";
|
|
5
|
+
function writeClaudeCodeSkill(projectRoot) {
|
|
6
|
+
const dir = path.join(projectRoot, ".claude", "commands");
|
|
7
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
8
|
+
const content = `<!-- Run this skill with /cve-lite in any Claude Code session -->\n\n${SKILL_CONTENT}\n`;
|
|
9
|
+
fs.writeFileSync(path.join(dir, "cve-lite.md"), content, "utf-8");
|
|
10
|
+
}
|
|
11
|
+
function writeCursorSkill(projectRoot) {
|
|
12
|
+
const dir = path.join(projectRoot, ".cursor", "rules");
|
|
13
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
14
|
+
const frontMatter = "---\ndescription: CVE Lite CLI vulnerability analysis\nglobs: []\nalwaysApply: false\n---\n\n";
|
|
15
|
+
fs.writeFileSync(path.join(dir, "cve-lite.mdc"), frontMatter + SKILL_CONTENT + "\n", "utf-8");
|
|
16
|
+
}
|
|
17
|
+
function writeAppendSkill(projectRoot, relPath) {
|
|
18
|
+
const section = `## CVE Lite CLI\n\n${SKILL_CONTENT}\n`;
|
|
19
|
+
const filePath = path.join(projectRoot, relPath);
|
|
20
|
+
if (!fs.existsSync(filePath)) {
|
|
21
|
+
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
|
22
|
+
fs.writeFileSync(filePath, section, "utf-8");
|
|
23
|
+
return;
|
|
24
|
+
}
|
|
25
|
+
const existing = fs.readFileSync(filePath, "utf-8");
|
|
26
|
+
const marker = "## CVE Lite CLI";
|
|
27
|
+
const idx = existing.indexOf(marker);
|
|
28
|
+
if (idx === -1) {
|
|
29
|
+
const sep = existing.endsWith("\n") ? "\n" : "\n\n";
|
|
30
|
+
fs.writeFileSync(filePath, existing + sep + section, "utf-8");
|
|
31
|
+
return;
|
|
32
|
+
}
|
|
33
|
+
// Replace from marker to next ## heading (or end of file)
|
|
34
|
+
const afterMarker = existing.indexOf("\n## ", idx + marker.length);
|
|
35
|
+
const before = existing.slice(0, idx);
|
|
36
|
+
const after = afterMarker === -1 ? "" : existing.slice(afterMarker);
|
|
37
|
+
fs.writeFileSync(filePath, before + section + after, "utf-8");
|
|
38
|
+
}
|
|
39
|
+
export function installSkill(projectRoot) {
|
|
40
|
+
writeClaudeCodeSkill(projectRoot);
|
|
41
|
+
writeAppendSkill(projectRoot, "AGENTS.md");
|
|
42
|
+
writeAppendSkill(projectRoot, "GEMINI.md");
|
|
43
|
+
writeCursorSkill(projectRoot);
|
|
44
|
+
writeAppendSkill(projectRoot, ".github/copilot-instructions.md");
|
|
45
|
+
console.log("\nCVE Lite CLI skills installed:\n");
|
|
46
|
+
console.log(` ${chalk.green("✓")} Claude Code .claude/commands/cve-lite.md`);
|
|
47
|
+
console.log(` ${chalk.green("✓")} Codex CLI AGENTS.md (section written)`);
|
|
48
|
+
console.log(` ${chalk.green("✓")} Gemini CLI GEMINI.md (section written)`);
|
|
49
|
+
console.log(` ${chalk.green("✓")} Cursor .cursor/rules/cve-lite.mdc`);
|
|
50
|
+
console.log(` ${chalk.green("✓")} GitHub Copilot .github/copilot-instructions.md (section written)`);
|
|
51
|
+
console.log("\nCommit these files to your repo to share them with your team.");
|
|
52
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
export function calculatePathCoverage(knownPaths, coveredPath) {
|
|
2
|
+
const coveredPaths = coveredPath && coveredPath.length > 0 ? [coveredPath] : [];
|
|
3
|
+
const remainingPaths = knownPaths.filter(path => !coveredPaths.some(covered => pathsEqual(path, covered)));
|
|
4
|
+
return {
|
|
5
|
+
coverage: remainingPaths.length === 0 ? "complete" : "partial",
|
|
6
|
+
coveredPaths,
|
|
7
|
+
remainingPaths,
|
|
8
|
+
};
|
|
9
|
+
}
|
|
10
|
+
export function formatDependencyPath(path) {
|
|
11
|
+
return path.join(" -> ");
|
|
12
|
+
}
|
|
13
|
+
function pathsEqual(left, right) {
|
|
14
|
+
if (left.length !== right.length)
|
|
15
|
+
return false;
|
|
16
|
+
return left.every((value, index) => value === right[index]);
|
|
17
|
+
}
|