cve-lite-cli 1.13.0 → 1.15.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 +28 -0
- package/dist/cli/args.js +17 -0
- package/dist/cli/help.js +6 -0
- package/dist/index.js +24 -11
- package/dist/llm/client.js +40 -0
- package/dist/llm/config.js +48 -0
- package/dist/llm/explainer.js +31 -0
- package/dist/osv/cache.js +36 -11
- package/dist/output/formatters.js +26 -6
- package/dist/output/html-reporter.js +41 -3
- package/dist/output/printers.js +39 -3
- package/dist/output/spinner.js +1 -1
- package/dist/parsers/pnpm-lock.js +25 -29
- package/dist/remediation/fix-commands.js +41 -2
- package/dist/scanner.js +14 -11
- package/dist/skills/content.js +39 -0
- package/dist/skills/install.js +52 -0
- package/dist/utils/array.js +13 -0
- package/dist/utils/path-coverage.js +17 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -272,6 +272,9 @@ cve-lite /path/to/project --osv-url https://security.company.internal/osv
|
|
|
272
272
|
|
|
273
273
|
# Show version
|
|
274
274
|
cve-lite --version
|
|
275
|
+
|
|
276
|
+
# Install AI assistant skill files for Claude Code, Codex CLI, Gemini CLI, Cursor, and GitHub Copilot
|
|
277
|
+
cve-lite install-skill
|
|
275
278
|
```
|
|
276
279
|
|
|
277
280
|
### Why is `--usage` an opt-in flag?
|
|
@@ -296,6 +299,31 @@ See the [Fix mode guide](https://owasp.org/cve-lite-cli/docs/fix-mode) for outpu
|
|
|
296
299
|
|
|
297
300
|
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
301
|
|
|
302
|
+
## AI assistant integration (`install-skill`)
|
|
303
|
+
|
|
304
|
+
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:
|
|
305
|
+
|
|
306
|
+
```bash
|
|
307
|
+
cve-lite install-skill
|
|
308
|
+
```
|
|
309
|
+
|
|
310
|
+
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.
|
|
311
|
+
|
|
312
|
+
Once installed, the workflow is:
|
|
313
|
+
|
|
314
|
+
```bash
|
|
315
|
+
# 1. Scan and save results to a JSON file
|
|
316
|
+
cve-lite . --json
|
|
317
|
+
|
|
318
|
+
# 2. Ask your AI assistant to analyze findings
|
|
319
|
+
# In Claude Code: /cve-lite
|
|
320
|
+
# In other tools: the skill is picked up automatically
|
|
321
|
+
```
|
|
322
|
+
|
|
323
|
+
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.
|
|
324
|
+
|
|
325
|
+
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.
|
|
326
|
+
|
|
299
327
|
## HTML vulnerability report (`--report`)
|
|
300
328
|
|
|
301
329
|
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.
|
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];
|
|
@@ -157,6 +170,10 @@ export function parseArgs(argv) {
|
|
|
157
170
|
options.noOpen = true;
|
|
158
171
|
continue;
|
|
159
172
|
}
|
|
173
|
+
if (arg === "--no-cache") {
|
|
174
|
+
options.noCache = true;
|
|
175
|
+
continue;
|
|
176
|
+
}
|
|
160
177
|
if (arg.startsWith("-"))
|
|
161
178
|
throw new Error(`Unknown option: ${arg}`);
|
|
162
179
|
if (!projectArg) {
|
package/dist/cli/help.js
CHANGED
|
@@ -28,6 +28,7 @@ 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",
|
|
@@ -44,6 +45,7 @@ export function printHelp() {
|
|
|
44
45
|
" --offline Scan using the local advisory database",
|
|
45
46
|
" --offline-db <path> Use a specific local advisory database file",
|
|
46
47
|
" --cache-dir <path> Override cache directory",
|
|
48
|
+
" --no-cache Skip the query cache and fetch fresh results from OSV",
|
|
47
49
|
" --search-depth <number> Recursive search depth (default: 4)",
|
|
48
50
|
" --all Show all findings in the main table",
|
|
49
51
|
" --min-severity <level> Minimum severity shown in table (default: medium)",
|
|
@@ -51,6 +53,10 @@ export function printHelp() {
|
|
|
51
53
|
"Advisory sync options:",
|
|
52
54
|
" --output <path> Write the local advisory database to this path",
|
|
53
55
|
"",
|
|
56
|
+
"Other commands:",
|
|
57
|
+
" install-skill Install AI assistant skill files for Claude Code,",
|
|
58
|
+
" Codex CLI, Gemini CLI, Cursor, and GitHub Copilot",
|
|
59
|
+
"",
|
|
54
60
|
" -v, --version Show the CLI version",
|
|
55
61
|
" -h, --help Show this help message"
|
|
56
62
|
];
|
package/dist/index.js
CHANGED
|
@@ -19,6 +19,7 @@ import { isLikelyBlockedAdvisoryRequestError } from "./utils/network.js";
|
|
|
19
19
|
import { logInfo, logWarn, printCacheSummary, serializeFinding, sortFindingsForOutput } from "./output/formatters.js";
|
|
20
20
|
import { buildReportData, writeHtmlReport } from "./output/html-reporter.js";
|
|
21
21
|
import { printSummary, printActionSummary, printSuggestedFixCommands, printSuggestedFixCommandSkips, printCoverage, printSkippedDependencies, printTable, printFinalStatus, printCompactOutput } from "./output/printers.js";
|
|
22
|
+
import { installSkill } from "./skills/install.js";
|
|
22
23
|
let parsedArgs = null;
|
|
23
24
|
try {
|
|
24
25
|
parsedArgs = parseArgs(process.argv.slice(2));
|
|
@@ -45,9 +46,7 @@ if (parsedArgs) {
|
|
|
45
46
|
const batchSize = Number(options.batchSize || 100);
|
|
46
47
|
const searchDepth = Math.max(0, Number(options.searchDepth || 4));
|
|
47
48
|
async function main() {
|
|
48
|
-
|
|
49
|
-
printBanner();
|
|
50
|
-
}
|
|
49
|
+
printBanner();
|
|
51
50
|
if (command === "advisories-sync") {
|
|
52
51
|
const spinner = createSpinner("Preparing advisory sync...", options);
|
|
53
52
|
const usePlainProgressLogs = !process.stdout.isTTY || !!options.json;
|
|
@@ -74,9 +73,17 @@ if (parsedArgs) {
|
|
|
74
73
|
process.exit(0);
|
|
75
74
|
return;
|
|
76
75
|
}
|
|
76
|
+
if (command === "install-skill") {
|
|
77
|
+
installSkill(process.cwd());
|
|
78
|
+
process.exit(0);
|
|
79
|
+
return;
|
|
80
|
+
}
|
|
77
81
|
if ((options.offline || options.offlineDb) && options.osvUrl) {
|
|
78
82
|
throw new Error("--offline/--offline-db cannot be used with --osv-url");
|
|
79
83
|
}
|
|
84
|
+
if (options.noCache && (options.offline || options.offlineDb)) {
|
|
85
|
+
throw new Error("--no-cache cannot be used with --offline or --offline-db");
|
|
86
|
+
}
|
|
80
87
|
if (options.osvUrl) {
|
|
81
88
|
try {
|
|
82
89
|
new URL(options.osvUrl);
|
|
@@ -118,12 +125,14 @@ if (parsedArgs) {
|
|
|
118
125
|
}
|
|
119
126
|
throw error;
|
|
120
127
|
}
|
|
121
|
-
if (options.
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
128
|
+
if (!options.json) {
|
|
129
|
+
if (options.offline || options.offlineDb) {
|
|
130
|
+
console.log(chalk.gray("Offline mode:") + " " + chalk.yellow("enabled") + " " + chalk.gray("(no external advisory calls will be made)"));
|
|
131
|
+
}
|
|
132
|
+
console.log(`${chalk.gray("Advisory source:")} ${formatAdvisorySourceLine(advisorySourceLine)}`);
|
|
133
|
+
if (advisoryDbFreshnessLine) {
|
|
134
|
+
console.log(`${chalk.gray("Advisory DB freshness:")} ${advisoryDbFreshnessLine}`);
|
|
135
|
+
}
|
|
127
136
|
}
|
|
128
137
|
if (advisoryDbWarning) {
|
|
129
138
|
logWarn(advisoryDbWarning, options);
|
|
@@ -183,7 +192,10 @@ if (parsedArgs) {
|
|
|
183
192
|
});
|
|
184
193
|
}
|
|
185
194
|
else if (options.json) {
|
|
186
|
-
|
|
195
|
+
const ts = new Date().toISOString().replace(/[:.]/g, "-").slice(0, 19);
|
|
196
|
+
const jsonFilename = `cve-lite-scan-${ts}.json`;
|
|
197
|
+
const jsonOutputPath = path.join(process.cwd(), jsonFilename);
|
|
198
|
+
fs.writeFileSync(jsonOutputPath, JSON.stringify({
|
|
187
199
|
projectPath,
|
|
188
200
|
mode: scanInput.mode,
|
|
189
201
|
source: scanInput.source,
|
|
@@ -195,6 +207,7 @@ if (parsedArgs) {
|
|
|
195
207
|
skippedDependencies: scanInput.skippedDependencies,
|
|
196
208
|
findings: scanState.sorted.map(finding => serializeFinding(finding, scanState.suggestedFixCommands))
|
|
197
209
|
}, null, 2));
|
|
210
|
+
console.log(`${chalk.gray("JSON saved to")} ${chalk.cyan(jsonFilename)}`);
|
|
198
211
|
}
|
|
199
212
|
else if (options.verbose) {
|
|
200
213
|
// Verbose output - show all details
|
|
@@ -274,7 +287,7 @@ async function scanProject(params) {
|
|
|
274
287
|
scanFilePath: params.scanInput.filePath,
|
|
275
288
|
});
|
|
276
289
|
if (params.options.usage) {
|
|
277
|
-
|
|
290
|
+
logInfo(`Scanning project source for usage hints...`, params.options);
|
|
278
291
|
const pkgNames = new Set(findings.map(f => f.pkg.name));
|
|
279
292
|
const usageData = scanProjectForPackageUsage(params.projectPath, pkgNames);
|
|
280
293
|
for (const finding of findings) {
|
|
@@ -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
|
+
}
|
package/dist/osv/cache.js
CHANGED
|
@@ -2,7 +2,7 @@ import fs from "node:fs";
|
|
|
2
2
|
import path from "node:path";
|
|
3
3
|
import os from "node:os";
|
|
4
4
|
function createEmptyCache() {
|
|
5
|
-
return { version:
|
|
5
|
+
return { version: 3, createdAt: new Date().toISOString(), entries: {}, queryEntries: {} };
|
|
6
6
|
}
|
|
7
7
|
export function getCacheFilePath(cacheDirOverride) {
|
|
8
8
|
const baseDir = cacheDirOverride
|
|
@@ -11,6 +11,9 @@ export function getCacheFilePath(cacheDirOverride) {
|
|
|
11
11
|
fs.mkdirSync(baseDir, { recursive: true });
|
|
12
12
|
return path.join(baseDir, "osv-vulns.json");
|
|
13
13
|
}
|
|
14
|
+
export function isEntryStale(entry, nowMs) {
|
|
15
|
+
return nowMs - new Date(entry.cachedAt).getTime() > 30 * 60 * 1000;
|
|
16
|
+
}
|
|
14
17
|
export function loadCache(cacheDirOverride) {
|
|
15
18
|
const filePath = getCacheFilePath(cacheDirOverride);
|
|
16
19
|
if (!fs.existsSync(filePath)) {
|
|
@@ -18,19 +21,41 @@ export function loadCache(cacheDirOverride) {
|
|
|
18
21
|
}
|
|
19
22
|
try {
|
|
20
23
|
const parsed = JSON.parse(fs.readFileSync(filePath, "utf8"));
|
|
21
|
-
if (parsed
|
|
22
|
-
return
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
24
|
+
if (typeof parsed !== "object" || parsed === null)
|
|
25
|
+
return createEmptyCache();
|
|
26
|
+
const entries = (parsed.entries && typeof parsed.entries === "object")
|
|
27
|
+
? parsed.entries
|
|
28
|
+
: {};
|
|
29
|
+
// v2: queryEntries values are string[] — migrate to { vulnIds, cachedAt: epoch }
|
|
30
|
+
if (parsed.version === 2) {
|
|
31
|
+
const rawQuery = parsed.queryEntries;
|
|
32
|
+
const queryEntries = {};
|
|
33
|
+
for (const [key, vulnIds] of Object.entries(rawQuery ?? {})) {
|
|
34
|
+
queryEntries[key] = { vulnIds: Array.isArray(vulnIds) ? vulnIds : [], cachedAt: new Date(0).toISOString() };
|
|
35
|
+
}
|
|
36
|
+
return { version: 3, createdAt: String(parsed.createdAt ?? new Date().toISOString()), entries, queryEntries };
|
|
37
|
+
}
|
|
38
|
+
// v1 or unknown: no queryEntries
|
|
39
|
+
if (parsed.version !== 3) {
|
|
40
|
+
return { version: 3, createdAt: new Date().toISOString(), entries, queryEntries: {} };
|
|
28
41
|
}
|
|
42
|
+
const rawQuery = parsed.queryEntries;
|
|
43
|
+
const queryEntries = {};
|
|
44
|
+
for (const [key, value] of Object.entries(rawQuery ?? {})) {
|
|
45
|
+
if (value && typeof value === "object" && "vulnIds" in value && "cachedAt" in value) {
|
|
46
|
+
queryEntries[key] = value;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
return {
|
|
50
|
+
version: 3,
|
|
51
|
+
createdAt: String(parsed.createdAt ?? new Date().toISOString()),
|
|
52
|
+
entries,
|
|
53
|
+
queryEntries,
|
|
54
|
+
};
|
|
29
55
|
}
|
|
30
|
-
catch
|
|
31
|
-
|
|
56
|
+
catch {
|
|
57
|
+
return createEmptyCache();
|
|
32
58
|
}
|
|
33
|
-
return createEmptyCache();
|
|
34
59
|
}
|
|
35
60
|
export function saveCache(cache, cacheDirOverride) {
|
|
36
61
|
const filePath = getCacheFilePath(cacheDirOverride);
|
|
@@ -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")
|
|
@@ -35,17 +36,19 @@ export function getRecommendedAction(finding) {
|
|
|
35
36
|
return `Upgrade ${finding.pkg.name} to ${directTarget}+ in this project.`;
|
|
36
37
|
}
|
|
37
38
|
if (finding.relationship === "direct") {
|
|
38
|
-
return `
|
|
39
|
+
return `No known fix exists for ${finding.pkg.name}. Consider replacing it with an actively maintained alternative.`;
|
|
39
40
|
}
|
|
40
41
|
if (finding.recommendedNpmTransitiveRemediation?.kind === "update-parent-within-range") {
|
|
41
42
|
return `Update ${finding.recommendedNpmTransitiveRemediation.package} within its current dependency range to pull in vulnerable ${finding.pkg.name}@${finding.recommendedNpmTransitiveRemediation.targetChildVersion}.`;
|
|
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.
|
|
@@ -112,7 +132,7 @@ export function summarizeNextAction(finding) {
|
|
|
112
132
|
return `Upgrade ${finding.pkg.name} toward ${directTarget}.`;
|
|
113
133
|
}
|
|
114
134
|
if (finding.relationship === "direct") {
|
|
115
|
-
return `
|
|
135
|
+
return `No known fix exists for ${finding.pkg.name}. Consider replacing it with an actively maintained alternative.`;
|
|
116
136
|
}
|
|
117
137
|
if (finding.recommendedNpmTransitiveRemediation?.kind === "update-parent-within-range") {
|
|
118
138
|
return `Update ${finding.recommendedNpmTransitiveRemediation.package} within its current dependency range.`;
|
|
@@ -128,7 +128,7 @@ button.header-link:hover{color:#58a6ff;border-color:#58a6ff}
|
|
|
128
128
|
.cve-link{font-size:11px;color:#58a6ff;font-family:monospace;text-decoration:none;border-bottom:1px dotted #58a6ff66}
|
|
129
129
|
.cve-link:hover{color:#79c0ff}
|
|
130
130
|
.fix-hint{font-size:11px;color:#3fb950;font-family:monospace}
|
|
131
|
-
.fix-hint.none{color:#
|
|
131
|
+
.fix-hint.none{color:#e3b341}
|
|
132
132
|
.expand-icon{color:#8b949e;font-size:10px}
|
|
133
133
|
.detail-row{background:#0d1117;border-top:1px solid #21262d;display:none}
|
|
134
134
|
.detail-row.visible{display:table-row}
|
|
@@ -163,7 +163,11 @@ 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}
|
|
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}
|
|
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}
|
|
170
|
+
.tier-err{display:inline-flex;align-items:center;gap:4px;font-size:10px;padding:2px 8px;border-radius:4px;background:#ff000011;color:#ff7b72;border:1px solid #ff7b7222;margin-bottom:6px}
|
|
167
171
|
</style>
|
|
168
172
|
</head>
|
|
169
173
|
<body>
|
|
@@ -388,7 +392,7 @@ function renderFindingRow(finding, idx) {
|
|
|
388
392
|
? `<span class="fix-hint">${escapeHtml(finding.validatedFirstFixedVersion)}</span>`
|
|
389
393
|
: finding.firstFixedVersion
|
|
390
394
|
? `<span class="fix-hint">${escapeHtml(finding.firstFixedVersion)}</span>`
|
|
391
|
-
: `<span class="fix-hint none"
|
|
395
|
+
: `<span class="fix-hint none" title="No known fix — consider replacing this package">⚠ No fix</span>`;
|
|
392
396
|
const depPathHtml = finding.dependencyPaths.length > 0
|
|
393
397
|
? finding.dependencyPaths[0].map((node, i, arr) => {
|
|
394
398
|
const isLast = i === arr.length - 1;
|
|
@@ -403,6 +407,9 @@ function renderFindingRow(finding, idx) {
|
|
|
403
407
|
<button class="copy-btn" data-cmd="${escapeHtml(runnable)}">Copy</button>
|
|
404
408
|
</div>`
|
|
405
409
|
: `<p class="fix-cmd-note">${escapeHtml(finding.recommendedAction ?? "")}</p>`;
|
|
410
|
+
const contextColHtml = finding.relationship === "transitive"
|
|
411
|
+
? renderTransitiveContextCol(finding)
|
|
412
|
+
: "";
|
|
406
413
|
return ` <tr id="row-${idx}" onclick="toggleRow(${idx})">
|
|
407
414
|
<td><span class="expand-icon" id="icon-${idx}">▶</span></td>
|
|
408
415
|
<td><div class="pkg-name">${escapeHtml(finding.package)}</div><div class="pkg-version">${escapeHtml(finding.version)}</div></td>
|
|
@@ -422,6 +429,7 @@ function renderFindingRow(finding, idx) {
|
|
|
422
429
|
<h4>Dependency path</h4>
|
|
423
430
|
<div class="dep-path">${depPathHtml}</div>
|
|
424
431
|
</div>
|
|
432
|
+
${contextColHtml}
|
|
425
433
|
<div class="detail-col">
|
|
426
434
|
<h4>Recommended action</h4>
|
|
427
435
|
${recommendedActionHtml}
|
|
@@ -430,6 +438,33 @@ function renderFindingRow(finding, idx) {
|
|
|
430
438
|
</td>
|
|
431
439
|
</tr>`;
|
|
432
440
|
}
|
|
441
|
+
function renderTransitiveContextCol(finding) {
|
|
442
|
+
const hasFixAvailable = finding.runnableFixCommand != null ||
|
|
443
|
+
finding.recommendedNpmTransitiveRemediation != null ||
|
|
444
|
+
finding.recommendedParentUpgrade != null;
|
|
445
|
+
if (hasFixAvailable) {
|
|
446
|
+
const parentLine = finding.primaryParent
|
|
447
|
+
? `<p style="font-size:12px;color:#8b949e;margin-top:4px">Parent: ${escapeHtml(finding.primaryParent)}</p>`
|
|
448
|
+
: "";
|
|
449
|
+
return `<div class="detail-col" style="max-width:200px">
|
|
450
|
+
<h4>Context</h4>
|
|
451
|
+
<span class="tier-ok">✓ Fix available</span>
|
|
452
|
+
${parentLine}
|
|
453
|
+
</div>`;
|
|
454
|
+
}
|
|
455
|
+
if (finding.primaryParent) {
|
|
456
|
+
return `<div class="detail-col" style="max-width:200px">
|
|
457
|
+
<h4>Context</h4>
|
|
458
|
+
<span class="tier-warn">⚠ No safe version identified</span>
|
|
459
|
+
<p style="font-size:12px;color:#8b949e;margin-top:4px">Parent: ${escapeHtml(finding.primaryParent)}</p>
|
|
460
|
+
</div>`;
|
|
461
|
+
}
|
|
462
|
+
return `<div class="detail-col" style="max-width:200px">
|
|
463
|
+
<h4>Context</h4>
|
|
464
|
+
<span class="tier-err">✕ No parent identified</span>
|
|
465
|
+
<p style="font-size:12px;color:#8b949e;margin-top:4px">Run <code>npm ls ${escapeHtml(finding.package)}</code> to find which package pulls it in.</p>
|
|
466
|
+
</div>`;
|
|
467
|
+
}
|
|
433
468
|
function renderNotices(notes, warnings) {
|
|
434
469
|
if (notes.length === 0 && warnings.length === 0)
|
|
435
470
|
return "";
|
|
@@ -461,7 +496,10 @@ function renderFixPlan(plan) {
|
|
|
461
496
|
const noteHtml = t.adjusted && t.adjustmentNote
|
|
462
497
|
? ` <span class="fix-target-note">${escapeHtml(t.adjustmentNote)}</span>`
|
|
463
498
|
: "";
|
|
464
|
-
|
|
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>`;
|
|
465
503
|
}).join("\n");
|
|
466
504
|
const targetsHtml = section.targets.length > 0
|
|
467
505
|
? `<div class="fix-targets-list">${targetRows}</div>`
|
package/dist/output/printers.js
CHANGED
|
@@ -149,11 +149,11 @@ export function printTable(findings, threshold) {
|
|
|
149
149
|
f.severity,
|
|
150
150
|
f.relationship,
|
|
151
151
|
usageText,
|
|
152
|
-
f.firstFixedVersion ?? "
|
|
152
|
+
f.firstFixedVersion ?? chalk.yellow("⚠ no fix"),
|
|
153
153
|
f.vulnerabilities.map(v => v.id).join(", ")
|
|
154
154
|
];
|
|
155
155
|
});
|
|
156
|
-
const widths = headers.map((header, index) => Math.min(40, Math.max(header.length, ...rawRows.map(r => String(r[index]).length))));
|
|
156
|
+
const widths = headers.map((header, index) => Math.min(40, Math.max(header.length, ...rawRows.map(r => stripAnsi(String(r[index])).length))));
|
|
157
157
|
console.log("");
|
|
158
158
|
if (threshold) {
|
|
159
159
|
console.log(chalk.bold(`Showing ${threshold}+ findings in the main table. Use --all to show everything.`));
|
|
@@ -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
|
}
|
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: () => { },
|
|
@@ -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;
|
package/dist/scanner.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { chunk, unique } from "./utils/array.js";
|
|
1
|
+
import { chunk, unique, runWithConcurrency } from "./utils/array.js";
|
|
2
2
|
import { compareVersions, isPreReleaseVersion, looksLikeVersion } from "./utils/version.js";
|
|
3
|
-
import { loadCache, saveCache } from "./osv/cache.js";
|
|
3
|
+
import { loadCache, saveCache, isEntryStale } from "./osv/cache.js";
|
|
4
4
|
import { maxSeverity } from "./osv/severity.js";
|
|
5
5
|
import { createSpinner } from "./output/spinner.js";
|
|
6
6
|
import { OsvAdvisorySource } from "./advisory/osv-advisory-source.js";
|
|
@@ -56,28 +56,31 @@ export async function scanPackages(packages, batchSize, options, context) {
|
|
|
56
56
|
const results = [];
|
|
57
57
|
const uncachedPackages = [];
|
|
58
58
|
if (!offline) {
|
|
59
|
+
const nowMs = Date.now();
|
|
59
60
|
for (const pkg of packages) {
|
|
60
61
|
const cacheKey = getPackageCacheKey(pkg);
|
|
61
|
-
if (
|
|
62
|
-
const
|
|
63
|
-
if (
|
|
64
|
-
|
|
62
|
+
if (!options.noCache) {
|
|
63
|
+
const cached = cache.queryEntries[cacheKey];
|
|
64
|
+
if (cached && !isEntryStale(cached, nowMs)) {
|
|
65
|
+
if (cached.vulnIds.length > 0) {
|
|
66
|
+
results.push({ pkg, vulnIds: cached.vulnIds });
|
|
67
|
+
}
|
|
68
|
+
continue;
|
|
65
69
|
}
|
|
66
|
-
continue;
|
|
67
70
|
}
|
|
68
71
|
uncachedPackages.push(pkg);
|
|
69
72
|
}
|
|
70
73
|
const chunks = chunk(uncachedPackages, batchSize);
|
|
74
|
+
spinner.update(`Scanning OSV in ${chunks.length} parallel batch${chunks.length === 1 ? "" : "es"}...`);
|
|
75
|
+
const allAdvisoryResults = await runWithConcurrency(chunks, 5, c => advisorySource.queryBatch(c));
|
|
71
76
|
for (let i = 0; i < chunks.length; i++) {
|
|
72
|
-
spinner.update(`Scanning OSV batch ${i + 1}/${chunks.length}...`);
|
|
73
77
|
const chunkItems = chunks[i];
|
|
74
|
-
const
|
|
75
|
-
const rows = advisoryResult ?? [];
|
|
78
|
+
const rows = allAdvisoryResults[i] ?? [];
|
|
76
79
|
for (let j = 0; j < chunkItems.length; j++) {
|
|
77
80
|
const pkg = chunkItems[j];
|
|
78
81
|
const row = rows[j];
|
|
79
82
|
const vulnIds = (row?.vulnerabilities ?? []).map(v => v.id).filter(Boolean);
|
|
80
|
-
cache.queryEntries[getPackageCacheKey(pkg)] = vulnIds;
|
|
83
|
+
cache.queryEntries[getPackageCacheKey(pkg)] = { vulnIds, cachedAt: new Date().toISOString() };
|
|
81
84
|
if (vulnIds.length > 0) {
|
|
82
85
|
results.push({ pkg, vulnIds });
|
|
83
86
|
}
|
|
@@ -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
|
+
}
|
package/dist/utils/array.js
CHANGED
|
@@ -20,3 +20,16 @@ export function uniquePathArrays(paths) {
|
|
|
20
20
|
}
|
|
21
21
|
return output;
|
|
22
22
|
}
|
|
23
|
+
export async function runWithConcurrency(items, limit, fn) {
|
|
24
|
+
const results = new Array(items.length);
|
|
25
|
+
const queue = items.map((item, index) => ({ item, index }));
|
|
26
|
+
let next = 0;
|
|
27
|
+
async function worker() {
|
|
28
|
+
while (next < queue.length) {
|
|
29
|
+
const { item, index } = queue[next++];
|
|
30
|
+
results[index] = await fn(item);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
|
|
34
|
+
return results;
|
|
35
|
+
}
|
|
@@ -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
|
+
}
|