cve-lite-cli 1.18.0 → 1.18.2
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 +15 -0
- package/dist/advisory/local-advisory-source.js +1 -1
- package/dist/advisory/osv-advisory-source.js +83 -13
- package/dist/advisory/osv-sync.js +3 -2
- package/dist/cli/args.js +52 -0
- package/dist/cli/config-command.js +40 -0
- package/dist/cli/config.js +66 -0
- package/dist/cli/help.js +7 -0
- package/dist/cli/validate.js +9 -0
- package/dist/index.js +112 -130
- package/dist/learn/keypress.js +50 -0
- package/dist/learn/runner.js +96 -0
- package/dist/learn/scenario.js +47 -0
- package/dist/learn/session.js +36 -0
- package/dist/learn/types.js +1 -0
- package/dist/osv/cache.js +46 -7
- package/dist/output/debug.js +38 -0
- package/dist/output/finding-display.js +30 -0
- package/dist/output/formatters.js +4 -3
- package/dist/output/html-reporter.js +3 -2
- package/dist/output/multi-folder-html-reporter.js +323 -0
- package/dist/output/multi-folder-printer.js +46 -0
- package/dist/output/printers.js +16 -15
- package/dist/output/sarif.js +3 -9
- package/dist/output/spinner.js +1 -1
- package/dist/parsers/multi-package.js +58 -0
- package/dist/parsers/pnpm-lock.js +4 -0
- package/dist/parsers/yarn-lock.js +60 -0
- package/dist/remediation/fix-commands.js +127 -6
- package/dist/remediation/npm-registry.js +44 -1
- package/dist/remediation/parent-upgrade.js +14 -8
- package/dist/scan/multi-folder-scan.js +97 -0
- package/dist/scanner.js +100 -21
- package/dist/utils/fix-runner.js +131 -0
- package/dist/utils/network.js +18 -4
- package/dist/utils/string.js +3 -0
- package/dist/utils/time.js +4 -3
- package/package.json +1 -1
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import process from "node:process";
|
|
3
|
+
import { loadMultiplePackages } from "../parsers/multi-package.js";
|
|
4
|
+
import { scanPackages, buildCoverageNotes } from "../scanner.js";
|
|
5
|
+
import { sortFindingsForOutput } from "../output/formatters.js";
|
|
6
|
+
import { normalizeSeverity } from "../osv/severity.js";
|
|
7
|
+
import { selectFindingsForTable } from "../output/finding-display.js";
|
|
8
|
+
import { buildSuggestedFixCommandPlan } from "../remediation/fix-commands.js";
|
|
9
|
+
import { readDirectDependencyNames } from "../utils/package-json.js";
|
|
10
|
+
import { DEFAULT_SEARCH_DEPTH, severityOrder } from "../constants.js";
|
|
11
|
+
import { printMultiFolderResults } from "../output/multi-folder-printer.js";
|
|
12
|
+
import { writeMultiFolderHtmlReport } from "../output/multi-folder-html-reporter.js";
|
|
13
|
+
import { chalk } from "../utils/chalk.js";
|
|
14
|
+
import { getCliVersion } from "../utils/version-info.js";
|
|
15
|
+
export async function runMultiFolderScan(params) {
|
|
16
|
+
const searchDepth = Math.max(0, Number(params.options.searchDepth || DEFAULT_SEARCH_DEPTH));
|
|
17
|
+
const folders = loadMultiplePackages(params.projectRoot, !!params.options.prodOnly, searchDepth);
|
|
18
|
+
const offline = !!params.options.offline || !!params.options.offlineDb;
|
|
19
|
+
const results = [];
|
|
20
|
+
for (const { scanInput, subfolder } of folders) {
|
|
21
|
+
if (scanInput.packages.length === 0)
|
|
22
|
+
continue;
|
|
23
|
+
if (!params.options.json) {
|
|
24
|
+
process.stdout.write(`\n${chalk.bold.cyan(`📁 ${subfolder}/`)}\n`);
|
|
25
|
+
}
|
|
26
|
+
const subfolderAbs = path.join(params.projectRoot, subfolder);
|
|
27
|
+
const directDependencyNames = readDirectDependencyNames(subfolderAbs, !!params.options.prodOnly);
|
|
28
|
+
const findings = await scanPackages(scanInput.packages, params.batchSize, params.options, {
|
|
29
|
+
directDependencyNames,
|
|
30
|
+
scanSource: scanInput.source,
|
|
31
|
+
scanFilePath: scanInput.filePath,
|
|
32
|
+
});
|
|
33
|
+
const sorted = sortFindingsForOutput(findings);
|
|
34
|
+
const coverage = buildCoverageNotes(scanInput, offline);
|
|
35
|
+
const minSeverity = normalizeSeverity(params.options.minSeverity || "medium");
|
|
36
|
+
const tableFindings = params.options.all ? sorted : selectFindingsForTable(sorted, minSeverity);
|
|
37
|
+
const suggestedFixCommands = buildSuggestedFixCommandPlan(sorted, scanInput, { offline, subfolder });
|
|
38
|
+
results.push({
|
|
39
|
+
subfolder,
|
|
40
|
+
scanInput,
|
|
41
|
+
sorted,
|
|
42
|
+
suggestedFixCommands,
|
|
43
|
+
coverage,
|
|
44
|
+
minSeverity,
|
|
45
|
+
tableFindings,
|
|
46
|
+
allPackages: scanInput.packages,
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
return results;
|
|
50
|
+
}
|
|
51
|
+
export async function handleMultiFolderScan(params) {
|
|
52
|
+
const results = await runMultiFolderScan(params);
|
|
53
|
+
if (results.length === 0) {
|
|
54
|
+
console.log(chalk.yellow("No scannable packages found in any subfolder."));
|
|
55
|
+
process.exit(0);
|
|
56
|
+
return;
|
|
57
|
+
}
|
|
58
|
+
if (params.options.fix) {
|
|
59
|
+
console.error(chalk.yellow("--fix is not yet supported in multi-folder mode. Run cve-lite . from each subfolder individually."));
|
|
60
|
+
process.exit(1);
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
if (params.options.sarif || params.options.cdx) {
|
|
64
|
+
console.error(chalk.yellow("--sarif and --cdx are not yet supported in multi-folder mode."));
|
|
65
|
+
process.exit(1);
|
|
66
|
+
return;
|
|
67
|
+
}
|
|
68
|
+
if (params.options.json) {
|
|
69
|
+
const { serializeFinding } = await import("../output/formatters.js");
|
|
70
|
+
const allFindings = results.flatMap(r => r.sorted.map(f => ({ ...serializeFinding(f, r.suggestedFixCommands), subfolder: r.subfolder })));
|
|
71
|
+
console.log(JSON.stringify({
|
|
72
|
+
multiFolder: true,
|
|
73
|
+
folders: results.map(r => r.subfolder),
|
|
74
|
+
findings: allFindings,
|
|
75
|
+
scannedAt: new Date().toISOString(),
|
|
76
|
+
}, null, 2));
|
|
77
|
+
}
|
|
78
|
+
else {
|
|
79
|
+
printMultiFolderResults(results, params.options);
|
|
80
|
+
}
|
|
81
|
+
if (params.options.report) {
|
|
82
|
+
const outputDir = path.resolve(typeof params.options.report === "string" ? params.options.report : "./cve-report");
|
|
83
|
+
const cliVersion = getCliVersion();
|
|
84
|
+
const { reportPath } = await writeMultiFolderHtmlReport({
|
|
85
|
+
outputDir,
|
|
86
|
+
results,
|
|
87
|
+
projectPath: params.projectRoot,
|
|
88
|
+
cliVersion,
|
|
89
|
+
autoOpen: !params.options.noOpen,
|
|
90
|
+
});
|
|
91
|
+
console.log(`${chalk.gray("Report:")} ${chalk.cyan(reportPath)}`);
|
|
92
|
+
}
|
|
93
|
+
const failLevel = normalizeSeverity(params.options.failOn);
|
|
94
|
+
const allSorted = results.flatMap(r => r.sorted);
|
|
95
|
+
const shouldFail = allSorted.some(f => severityOrder[f.severity] >= severityOrder[failLevel]);
|
|
96
|
+
process.exit(shouldFail ? 1 : 0);
|
|
97
|
+
}
|
package/dist/scanner.js
CHANGED
|
@@ -8,12 +8,14 @@ import { LocalAdvisorySource } from "./advisory/local-advisory-source.js";
|
|
|
8
8
|
import { LocalAdvisoryDatabase } from "./advisory/local-db.js";
|
|
9
9
|
import { ADVISORY_DB_STALE_AFTER_MS, getDefaultAdvisoryDbPath } from "./advisory/osv-sync.js";
|
|
10
10
|
import { resolveRecommendedParentUpgrade } from "./remediation/parent-upgrade.js";
|
|
11
|
-
import { resolveLowestKnownNonVulnerableVersion, resolvePublishedFixVersion } from "./remediation/npm-registry.js";
|
|
11
|
+
import { configureNpmRegistryDebug, resolveLowestKnownNonVulnerableVersion, resolvePublishedFixVersion, } from "./remediation/npm-registry.js";
|
|
12
|
+
import { countBySeverity } from "./utils/severity.js";
|
|
12
13
|
import { resolveNpmTransitiveRemediation, resolveTransitiveRemediationViaRegistry } from "./remediation/npm-transitive-resolution.js";
|
|
13
14
|
import { loadNpmLockGraph } from "./parsers/npm-lock-graph.js";
|
|
14
15
|
import { buildPnpmWorkspaceMap } from "./parsers/pnpm-lock.js";
|
|
15
16
|
import { buildNpmWorkspaceMap } from "./parsers/package-lock.js";
|
|
16
17
|
import { buildBunWorkspaceMap } from "./parsers/bun-lock.js";
|
|
18
|
+
import { pluralize } from "./utils/string.js";
|
|
17
19
|
export function createAdvisorySource(options) {
|
|
18
20
|
const offline = !!options?.offline || !!options?.offlineDb;
|
|
19
21
|
if (offline) {
|
|
@@ -29,7 +31,7 @@ export function createAdvisorySource(options) {
|
|
|
29
31
|
};
|
|
30
32
|
}
|
|
31
33
|
return {
|
|
32
|
-
advisorySource: new OsvAdvisorySource(options?.osvUrl),
|
|
34
|
+
advisorySource: new OsvAdvisorySource(options?.osvUrl, options?.debugLog),
|
|
33
35
|
offline: false,
|
|
34
36
|
sourceLabel: options?.osvUrl
|
|
35
37
|
? `custom OSV endpoint (${options.osvUrl})`
|
|
@@ -42,11 +44,13 @@ export function createAdvisorySource(options) {
|
|
|
42
44
|
function getPackageCacheKey(pkg) {
|
|
43
45
|
return `${pkg.ecosystem}:${pkg.name}@${pkg.version}`;
|
|
44
46
|
}
|
|
45
|
-
export async function scanPackages(packages, batchSize, options, context) {
|
|
47
|
+
export async function scanPackages(packages, batchSize, options, context, debugLog) {
|
|
48
|
+
const log = debugLog ?? (() => { });
|
|
46
49
|
const sourceContext = createAdvisorySource({
|
|
47
50
|
osvUrl: options.osvUrl,
|
|
48
51
|
offline: options.offline,
|
|
49
52
|
offlineDb: options.offlineDb,
|
|
53
|
+
debugLog: log,
|
|
50
54
|
});
|
|
51
55
|
const offline = sourceContext.offline;
|
|
52
56
|
const cacheDirOverride = options.cacheDir;
|
|
@@ -54,28 +58,43 @@ export async function scanPackages(packages, batchSize, options, context) {
|
|
|
54
58
|
? "Scanning dependencies against the local advisory database..."
|
|
55
59
|
: "Scanning dependencies against OSV...", options);
|
|
56
60
|
const advisorySource = sourceContext.advisorySource;
|
|
57
|
-
|
|
61
|
+
if (!offline && options.debug) {
|
|
62
|
+
configureNpmRegistryDebug(log);
|
|
63
|
+
}
|
|
64
|
+
const cache = loadCache(cacheDirOverride, options.debug ? log : undefined);
|
|
58
65
|
try {
|
|
59
66
|
const results = [];
|
|
60
67
|
const uncachedPackages = [];
|
|
61
68
|
if (!offline) {
|
|
62
69
|
const nowMs = Date.now();
|
|
70
|
+
let hits = 0;
|
|
71
|
+
let misses = 0;
|
|
63
72
|
for (const pkg of packages) {
|
|
64
73
|
const cacheKey = getPackageCacheKey(pkg);
|
|
65
74
|
if (!options.noCache) {
|
|
66
75
|
const cached = cache.queryEntries[cacheKey];
|
|
67
76
|
if (cached && !isEntryStale(cached, nowMs)) {
|
|
77
|
+
hits += 1;
|
|
68
78
|
if (cached.vulnIds.length > 0) {
|
|
69
79
|
results.push({ pkg, vulnIds: cached.vulnIds });
|
|
70
80
|
}
|
|
71
81
|
continue;
|
|
72
82
|
}
|
|
73
83
|
}
|
|
84
|
+
misses += 1;
|
|
74
85
|
uncachedPackages.push(pkg);
|
|
75
86
|
}
|
|
76
87
|
const chunks = chunk(uncachedPackages, batchSize);
|
|
77
|
-
|
|
78
|
-
|
|
88
|
+
const reason = options.noCache ? "no-cache mode" : "stale or missing entry";
|
|
89
|
+
log("Cache check", { hits, misses, reason, uncachedBatches: chunks.length });
|
|
90
|
+
spinner.update(`Scanning OSV in ${chunks.length} parallel ${pluralize(chunks.length, "batch", "batches")}...`);
|
|
91
|
+
const osvScanStartedAt = Date.now();
|
|
92
|
+
let batchCounter = 0;
|
|
93
|
+
const allAdvisoryResults = await runWithConcurrency(chunks, 5, c => {
|
|
94
|
+
batchCounter += 1;
|
|
95
|
+
const batchId = `b-${String(batchCounter).padStart(2, "0")}`;
|
|
96
|
+
return advisorySource.queryBatch(c, { batchId });
|
|
97
|
+
});
|
|
79
98
|
for (let i = 0; i < chunks.length; i++) {
|
|
80
99
|
const chunkItems = chunks[i];
|
|
81
100
|
const rows = allAdvisoryResults[i] ?? [];
|
|
@@ -89,15 +108,22 @@ export async function scanPackages(packages, batchSize, options, context) {
|
|
|
89
108
|
}
|
|
90
109
|
}
|
|
91
110
|
}
|
|
111
|
+
if (chunks.length > 0) {
|
|
112
|
+
log("OSV scan complete", {
|
|
113
|
+
totalBatches: chunks.length,
|
|
114
|
+
totalDurationMs: Date.now() - osvScanStartedAt,
|
|
115
|
+
packagesWithVulns: results.length,
|
|
116
|
+
});
|
|
117
|
+
}
|
|
92
118
|
if (chunks.length === 0) {
|
|
93
119
|
spinner.succeed("Loaded package matches from cache");
|
|
94
120
|
}
|
|
95
121
|
else {
|
|
96
|
-
spinner.succeed(`Queried OSV in ${chunks.length}
|
|
122
|
+
spinner.succeed(`Queried OSV in ${chunks.length} ${pluralize(chunks.length, "batch", "batches")}`);
|
|
97
123
|
}
|
|
98
124
|
}
|
|
99
125
|
else {
|
|
100
|
-
const advisoryResult = await advisorySource.queryBatch(packages);
|
|
126
|
+
const advisoryResult = await advisorySource.queryBatch(packages, { batchId: "offline" });
|
|
101
127
|
const rows = advisoryResult ?? [];
|
|
102
128
|
for (let i = 0; i < packages.length; i++) {
|
|
103
129
|
const pkg = packages[i];
|
|
@@ -134,7 +160,7 @@ export async function scanPackages(packages, batchSize, options, context) {
|
|
|
134
160
|
cache.entries[id] = null;
|
|
135
161
|
}
|
|
136
162
|
}
|
|
137
|
-
detailSpinner.succeed(`Loaded ${ids.length} vulnerability detail
|
|
163
|
+
detailSpinner.succeed(`Loaded ${ids.length} vulnerability detail ${pluralize(ids.length, "record")}`);
|
|
138
164
|
}
|
|
139
165
|
catch (error) {
|
|
140
166
|
detailSpinner.fail("Failed while fetching vulnerability details");
|
|
@@ -156,7 +182,7 @@ export async function scanPackages(packages, batchSize, options, context) {
|
|
|
156
182
|
// ignore missing local records so scans remain resilient to partial DB state
|
|
157
183
|
}
|
|
158
184
|
}
|
|
159
|
-
detailSpinner.succeed(`Loaded ${ids.length} local advisory detail
|
|
185
|
+
detailSpinner.succeed(`Loaded ${ids.length} local advisory detail ${pluralize(ids.length, "record")}`);
|
|
160
186
|
}
|
|
161
187
|
catch (error) {
|
|
162
188
|
detailSpinner.fail("Failed while loading local advisory details");
|
|
@@ -164,7 +190,7 @@ export async function scanPackages(packages, batchSize, options, context) {
|
|
|
164
190
|
}
|
|
165
191
|
}
|
|
166
192
|
if (!offline && idSet.size > 0) {
|
|
167
|
-
saveCache(cache, cacheDirOverride);
|
|
193
|
+
saveCache(cache, cacheDirOverride, options.debug ? log : undefined);
|
|
168
194
|
}
|
|
169
195
|
const findings = results.map(result => {
|
|
170
196
|
const vulnerabilities = result.vulnIds
|
|
@@ -192,35 +218,59 @@ export async function scanPackages(packages, batchSize, options, context) {
|
|
|
192
218
|
};
|
|
193
219
|
});
|
|
194
220
|
const npmTransitiveGraph = context?.scanSource === "package-lock" && context.scanFilePath
|
|
195
|
-
? createNpmTransitiveGraphFromLockfile(context.scanFilePath)
|
|
221
|
+
? createNpmTransitiveGraphFromLockfile(context.scanFilePath, log, packages.length)
|
|
196
222
|
: null;
|
|
197
223
|
const npmWorkspaceMap = (() => {
|
|
198
224
|
try {
|
|
199
225
|
return context?.scanSource === "package-lock" && context.scanFilePath
|
|
200
226
|
? buildNpmWorkspaceMap(context.scanFilePath) : null;
|
|
201
227
|
}
|
|
202
|
-
catch {
|
|
228
|
+
catch (error) {
|
|
229
|
+
log("Workspace map", {
|
|
230
|
+
type: "npm",
|
|
231
|
+
status: "failed",
|
|
232
|
+
error: error instanceof Error ? error.message : String(error),
|
|
233
|
+
});
|
|
203
234
|
return null;
|
|
204
235
|
}
|
|
205
236
|
})();
|
|
237
|
+
if (npmWorkspaceMap) {
|
|
238
|
+
log("Workspace map", { type: "npm", workspaces: npmWorkspaceMap.size });
|
|
239
|
+
}
|
|
206
240
|
const pnpmWorkspaceMap = (() => {
|
|
207
241
|
try {
|
|
208
242
|
return context?.scanSource === "pnpm-lock" && context.scanFilePath
|
|
209
243
|
? buildPnpmWorkspaceMap(context.scanFilePath) : null;
|
|
210
244
|
}
|
|
211
|
-
catch {
|
|
245
|
+
catch (error) {
|
|
246
|
+
log("Workspace map", {
|
|
247
|
+
type: "pnpm",
|
|
248
|
+
status: "failed",
|
|
249
|
+
error: error instanceof Error ? error.message : String(error),
|
|
250
|
+
});
|
|
212
251
|
return null;
|
|
213
252
|
}
|
|
214
253
|
})();
|
|
254
|
+
if (pnpmWorkspaceMap) {
|
|
255
|
+
log("Workspace map", { type: "pnpm", workspaces: pnpmWorkspaceMap.size });
|
|
256
|
+
}
|
|
215
257
|
const bunWorkspaceMap = (() => {
|
|
216
258
|
try {
|
|
217
259
|
return context?.scanSource === "bun-lock" && context.scanFilePath
|
|
218
260
|
? buildBunWorkspaceMap(context.scanFilePath) : null;
|
|
219
261
|
}
|
|
220
|
-
catch {
|
|
262
|
+
catch (error) {
|
|
263
|
+
log("Workspace map", {
|
|
264
|
+
type: "bun",
|
|
265
|
+
status: "failed",
|
|
266
|
+
error: error instanceof Error ? error.message : String(error),
|
|
267
|
+
});
|
|
221
268
|
return null;
|
|
222
269
|
}
|
|
223
270
|
})();
|
|
271
|
+
if (bunWorkspaceMap) {
|
|
272
|
+
log("Workspace map", { type: "bun", workspaces: bunWorkspaceMap.size });
|
|
273
|
+
}
|
|
224
274
|
const lockfileWorkspaceMap = pnpmWorkspaceMap ?? bunWorkspaceMap ?? null;
|
|
225
275
|
const npmRemediationCache = new Map();
|
|
226
276
|
const parentUpgradeCache = new Map();
|
|
@@ -238,7 +288,7 @@ export async function scanPackages(packages, batchSize, options, context) {
|
|
|
238
288
|
if (!offline) {
|
|
239
289
|
await validateDirectFixTargets(findings, (finding) => {
|
|
240
290
|
updateAnalysisProgress("validating fix target for", `${finding.pkg.name}@${finding.pkg.version}`);
|
|
241
|
-
});
|
|
291
|
+
}, log);
|
|
242
292
|
}
|
|
243
293
|
for (const finding of findings) {
|
|
244
294
|
if (finding.relationship !== "transitive")
|
|
@@ -325,8 +375,19 @@ export async function scanPackages(packages, batchSize, options, context) {
|
|
|
325
375
|
}
|
|
326
376
|
}
|
|
327
377
|
else if (!offline) {
|
|
328
|
-
await validateDirectFixTargets(findings);
|
|
378
|
+
await validateDirectFixTargets(findings, undefined, log);
|
|
329
379
|
}
|
|
380
|
+
const severityCounts = countBySeverity(findings);
|
|
381
|
+
log("Findings classified", {
|
|
382
|
+
total: findings.length,
|
|
383
|
+
direct: findings.filter(finding => finding.relationship === "direct").length,
|
|
384
|
+
transitive: findings.filter(finding => finding.relationship === "transitive").length,
|
|
385
|
+
critical: severityCounts.critical,
|
|
386
|
+
high: severityCounts.high,
|
|
387
|
+
medium: severityCounts.medium,
|
|
388
|
+
low: severityCounts.low,
|
|
389
|
+
unknown: severityCounts.unknown,
|
|
390
|
+
});
|
|
330
391
|
return findings;
|
|
331
392
|
}
|
|
332
393
|
catch (error) {
|
|
@@ -337,9 +398,10 @@ export async function scanPackages(packages, batchSize, options, context) {
|
|
|
337
398
|
sourceContext.cleanup();
|
|
338
399
|
}
|
|
339
400
|
}
|
|
340
|
-
function createNpmTransitiveGraphFromLockfile(filePath) {
|
|
401
|
+
function createNpmTransitiveGraphFromLockfile(filePath, log, packageCount) {
|
|
341
402
|
try {
|
|
342
403
|
const lockGraph = loadNpmLockGraph(filePath, { includePaths: false });
|
|
404
|
+
log("npm transitive graph", { status: "built", nodes: packageCount });
|
|
343
405
|
return {
|
|
344
406
|
nodeIdsFor(name, version) {
|
|
345
407
|
return lockGraph.nodeIdsFor(name, version);
|
|
@@ -358,14 +420,26 @@ function createNpmTransitiveGraphFromLockfile(filePath) {
|
|
|
358
420
|
},
|
|
359
421
|
};
|
|
360
422
|
}
|
|
361
|
-
catch {
|
|
423
|
+
catch (error) {
|
|
424
|
+
log("npm transitive graph", {
|
|
425
|
+
status: "failed",
|
|
426
|
+
error: error instanceof Error ? error.message : String(error),
|
|
427
|
+
});
|
|
362
428
|
return null;
|
|
363
429
|
}
|
|
364
430
|
}
|
|
365
|
-
async function validateDirectFixTargets(findings, onFinding) {
|
|
431
|
+
async function validateDirectFixTargets(findings, onFinding, debugLog) {
|
|
366
432
|
const directCandidates = findings.filter(finding => finding.vulnerabilities.length > 0);
|
|
367
433
|
for (const finding of directCandidates) {
|
|
368
434
|
onFinding?.(finding);
|
|
435
|
+
const logFixValidation = () => {
|
|
436
|
+
debugLog?.("Fix validation", {
|
|
437
|
+
package: finding.pkg.name,
|
|
438
|
+
installed: finding.pkg.version,
|
|
439
|
+
resolvedFixVersion: finding.validatedFirstFixedVersion,
|
|
440
|
+
verified: Boolean(finding.validatedFirstFixedVersion),
|
|
441
|
+
});
|
|
442
|
+
};
|
|
369
443
|
const lowestKnownResolution = await resolveLowestKnownNonVulnerableVersion(finding.pkg.name, finding.pkg.version, finding.vulnerabilities);
|
|
370
444
|
const fixedVersionHint = finding.firstFixedVersion;
|
|
371
445
|
if (lowestKnownResolution.resolvedVersion) {
|
|
@@ -374,16 +448,19 @@ async function validateDirectFixTargets(findings, onFinding) {
|
|
|
374
448
|
finding.validatedTargetKnownVulnerableVersions = lowestKnownResolution.candidatesKnownVulnerable;
|
|
375
449
|
if (!fixedVersionHint || fixedVersionHint === lowestKnownResolution.resolvedVersion) {
|
|
376
450
|
finding.fixVersionValidationNote = null;
|
|
451
|
+
logFixValidation();
|
|
377
452
|
continue;
|
|
378
453
|
}
|
|
379
454
|
const hintResolution = await resolvePublishedFixVersion(finding.pkg.name, fixedVersionHint);
|
|
380
455
|
if (hintResolution.resolvedVersion === lowestKnownResolution.resolvedVersion &&
|
|
381
456
|
hintResolution.note) {
|
|
382
457
|
finding.fixVersionValidationNote = hintResolution.note;
|
|
458
|
+
logFixValidation();
|
|
383
459
|
continue;
|
|
384
460
|
}
|
|
385
461
|
finding.fixVersionValidationNote =
|
|
386
|
-
`Advisory fixed-version hint ${fixedVersionHint} is still known vulnerable for ${finding.pkg.name}; scanned ${lowestKnownResolution.candidatesChecked} package
|
|
462
|
+
`Advisory fixed-version hint ${fixedVersionHint} is still known vulnerable for ${finding.pkg.name}; scanned ${lowestKnownResolution.candidatesChecked} package ${pluralize(lowestKnownResolution.candidatesChecked, "version")} above current version (${lowestKnownResolution.candidatesKnownVulnerable} still known vulnerable); using lowest known non-vulnerable version ${lowestKnownResolution.resolvedVersion}.`;
|
|
463
|
+
logFixValidation();
|
|
387
464
|
continue;
|
|
388
465
|
}
|
|
389
466
|
if (!fixedVersionHint) {
|
|
@@ -391,6 +468,7 @@ async function validateDirectFixTargets(findings, onFinding) {
|
|
|
391
468
|
finding.fixVersionValidationNote = lowestKnownResolution.note;
|
|
392
469
|
finding.validatedTargetScannedVersions = null;
|
|
393
470
|
finding.validatedTargetKnownVulnerableVersions = null;
|
|
471
|
+
logFixValidation();
|
|
394
472
|
continue;
|
|
395
473
|
}
|
|
396
474
|
const resolution = await resolvePublishedFixVersion(finding.pkg.name, fixedVersionHint);
|
|
@@ -398,6 +476,7 @@ async function validateDirectFixTargets(findings, onFinding) {
|
|
|
398
476
|
finding.fixVersionValidationNote = resolution.note ?? lowestKnownResolution.note;
|
|
399
477
|
finding.validatedTargetScannedVersions = null;
|
|
400
478
|
finding.validatedTargetKnownVulnerableVersions = null;
|
|
479
|
+
logFixValidation();
|
|
401
480
|
}
|
|
402
481
|
}
|
|
403
482
|
function isAdvisoryDbStale(metadata) {
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { createSpinner } from "../output/spinner.js";
|
|
3
|
+
import { chalk } from "./chalk.js";
|
|
4
|
+
import { pluralize } from "./string.js";
|
|
5
|
+
export function buildFixCommandParts(packageManager, targets) {
|
|
6
|
+
if (packageManager === "npm") {
|
|
7
|
+
return ["npm", "install", ...targets.map(target => `${target.package}@${target.targetVersion}`)];
|
|
8
|
+
}
|
|
9
|
+
if (packageManager === "pnpm") {
|
|
10
|
+
return ["pnpm", "add", ...targets.map(target => `${target.package}@${target.targetVersion}`)];
|
|
11
|
+
}
|
|
12
|
+
if (packageManager === "bun") {
|
|
13
|
+
return ["bun", "add", ...targets.map(target => `${target.package}@${target.targetVersion}`)];
|
|
14
|
+
}
|
|
15
|
+
return ["yarn", "add", ...targets.map(target => `${target.package}@${target.targetVersion}`)];
|
|
16
|
+
}
|
|
17
|
+
export async function runInstallCommand(command, args, cwd, debugLog) {
|
|
18
|
+
const commandLine = [command, ...args].join(" ");
|
|
19
|
+
debugLog?.("Fix command", { command: commandLine, cwd });
|
|
20
|
+
return await new Promise(resolve => {
|
|
21
|
+
const child = spawn(command, args, {
|
|
22
|
+
cwd,
|
|
23
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
24
|
+
});
|
|
25
|
+
child.stdout.on("data", () => { });
|
|
26
|
+
child.stderr.on("data", () => { });
|
|
27
|
+
child.on("error", error => {
|
|
28
|
+
debugLog?.("Fix command finished", { command: commandLine, exitCode: null, error: error.message });
|
|
29
|
+
resolve({ status: null, error });
|
|
30
|
+
});
|
|
31
|
+
child.on("close", code => {
|
|
32
|
+
debugLog?.("Fix command finished", { command: commandLine, exitCode: code });
|
|
33
|
+
resolve({ status: code, error: null });
|
|
34
|
+
});
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
export function commandLabelForPackageManager(packageManager) {
|
|
38
|
+
if (packageManager === "npm")
|
|
39
|
+
return "npm install";
|
|
40
|
+
if (packageManager === "pnpm")
|
|
41
|
+
return "pnpm add";
|
|
42
|
+
if (packageManager === "bun")
|
|
43
|
+
return "bun add";
|
|
44
|
+
return "yarn add";
|
|
45
|
+
}
|
|
46
|
+
export async function applyFixesIfRequested(params) {
|
|
47
|
+
console.log("");
|
|
48
|
+
console.log(chalk.bold.cyan("Applying fixes (--fix)"));
|
|
49
|
+
if (!params.plan) {
|
|
50
|
+
return {
|
|
51
|
+
appliedFixCount: 0,
|
|
52
|
+
skippedCount: params.totalFindings,
|
|
53
|
+
skippedTransitiveCount: 0,
|
|
54
|
+
skippedNoValidatedTargetCount: params.totalFindings,
|
|
55
|
+
applied: [],
|
|
56
|
+
note: "No package-manager-native fix command is available for this project.",
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
const directTargets = params.plan.targets.filter(target => target.kind === "direct");
|
|
60
|
+
const transitiveTargets = params.plan.targets.filter(target => target.kind !== "direct");
|
|
61
|
+
const skippedDirect = params.plan.skipped.filter(skip => skip.relationship === "direct" || skip.relationship === "unknown");
|
|
62
|
+
if (directTargets.length === 0) {
|
|
63
|
+
const skippedCount = transitiveTargets.length + skippedDirect.length;
|
|
64
|
+
return {
|
|
65
|
+
appliedFixCount: 0,
|
|
66
|
+
skippedCount,
|
|
67
|
+
skippedTransitiveCount: transitiveTargets.length,
|
|
68
|
+
skippedNoValidatedTargetCount: skippedDirect.length,
|
|
69
|
+
applied: [],
|
|
70
|
+
note: "No validated direct dependency fixes were eligible for auto-apply.",
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
const commandLabel = commandLabelForPackageManager(params.plan.packageManager);
|
|
74
|
+
const total = directTargets.length;
|
|
75
|
+
const spinner = createSpinner(`Applying direct package fixes with ${commandLabel}... 0/${total}`, params.options);
|
|
76
|
+
const fixHint = `\nHint: Check that \`${params.plan.packageManager}\` is available and you have write access to node_modules.\nIf running in CI, ensure the install step has already run before cve-lite --fix.`;
|
|
77
|
+
for (let i = 0; i < directTargets.length; i++) {
|
|
78
|
+
const target = directTargets[i];
|
|
79
|
+
const commandParts = buildFixCommandParts(params.plan.packageManager, [target]);
|
|
80
|
+
spinner.update(`Applying direct fix ${i + 1}/${total}: ${commandParts.join(" ")}`);
|
|
81
|
+
const run = await runInstallCommand(commandParts[0], commandParts.slice(1), params.projectPath, params.debugLog);
|
|
82
|
+
if (run.error) {
|
|
83
|
+
spinner.fail("Failed to apply fixes");
|
|
84
|
+
throw new Error(`Failed to apply fixes: ${run.error.message}${fixHint}`);
|
|
85
|
+
}
|
|
86
|
+
if ((run.status ?? 1) !== 0) {
|
|
87
|
+
spinner.fail(`Fix command failed (${commandLabel})`);
|
|
88
|
+
throw new Error(`Fix command exited with status ${run.status ?? 1}${fixHint}`);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
spinner.succeed(`Applied ${directTargets.length} direct package ${pluralize(directTargets.length, "fix", "fixes")} with ${commandLabel}`);
|
|
92
|
+
const skippedCount = transitiveTargets.length + skippedDirect.length;
|
|
93
|
+
return {
|
|
94
|
+
appliedFixCount: directTargets.length,
|
|
95
|
+
skippedCount,
|
|
96
|
+
skippedTransitiveCount: transitiveTargets.length,
|
|
97
|
+
skippedNoValidatedTargetCount: skippedDirect.length,
|
|
98
|
+
applied: directTargets.map(target => ({
|
|
99
|
+
package: target.package,
|
|
100
|
+
from: target.currentVersion ?? "unknown",
|
|
101
|
+
to: target.targetVersion,
|
|
102
|
+
})),
|
|
103
|
+
note: null,
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
export function printFixModeSummary(params) {
|
|
107
|
+
const result = params.fixResult;
|
|
108
|
+
if (!result)
|
|
109
|
+
return;
|
|
110
|
+
if (result.note) {
|
|
111
|
+
console.log(chalk.gray(result.note));
|
|
112
|
+
}
|
|
113
|
+
if (result.applied.length > 0) {
|
|
114
|
+
console.log("");
|
|
115
|
+
console.log(chalk.bold.cyan("Applied fixes"));
|
|
116
|
+
for (const item of result.applied) {
|
|
117
|
+
console.log(`- ${chalk.white(item.package)}: ${chalk.gray(item.from)} ${chalk.cyan("->")} ${chalk.green(item.to)}`);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
console.log("");
|
|
121
|
+
console.log(chalk.bold.cyan("Fix summary"));
|
|
122
|
+
console.log(`- Applied fixes: ${chalk.green(String(result.appliedFixCount))}`);
|
|
123
|
+
console.log(`- Skipped findings: ${chalk.yellow(String(result.skippedCount))}`);
|
|
124
|
+
if (result.skippedCount > 0) {
|
|
125
|
+
console.log(` - Transitive (v1 skip): ${chalk.yellow(String(result.skippedTransitiveCount))}`);
|
|
126
|
+
console.log(` - No validated direct target: ${chalk.yellow(String(result.skippedNoValidatedTargetCount))}`);
|
|
127
|
+
}
|
|
128
|
+
console.log(`- Findings before fix: ${chalk.white(String(params.findingsBeforeFix))}`);
|
|
129
|
+
console.log(`- Remaining findings after fix: ${chalk.white(String(params.findingsAfterFix))}`);
|
|
130
|
+
console.log(`- Remaining severity mix: critical ${chalk.redBright(String(params.remainingBySeverity.critical))}, high ${chalk.red(String(params.remainingBySeverity.high))}, medium ${chalk.yellow(String(params.remainingBySeverity.medium))}, low ${chalk.blueBright(String(params.remainingBySeverity.low))}, unknown ${chalk.magenta(String(params.remainingBySeverity.unknown))}`);
|
|
131
|
+
}
|
package/dist/utils/network.js
CHANGED
|
@@ -9,10 +9,10 @@ export function extractErrorMessage(error) {
|
|
|
9
9
|
export function sslCertificateErrorHint() {
|
|
10
10
|
return [
|
|
11
11
|
"Hint: SSL certificate error — your network may be using a corporate proxy that intercepts HTTPS traffic.",
|
|
12
|
-
"Fix
|
|
13
|
-
"
|
|
14
|
-
"
|
|
15
|
-
"
|
|
12
|
+
"Fix (recommended): save your corporate CA certificate path once:",
|
|
13
|
+
" cve-lite config set ca-cert /path/to/corporate-ca.crt",
|
|
14
|
+
"Or pass it per-invocation:",
|
|
15
|
+
" cve-lite . --ca-cert /path/to/corporate-ca.crt",
|
|
16
16
|
];
|
|
17
17
|
}
|
|
18
18
|
export function blockedAdvisoryRequestHint() {
|
|
@@ -20,6 +20,13 @@ export function blockedAdvisoryRequestHint() {
|
|
|
20
20
|
"Hint: Outbound access to the OSV API may be blocked or restricted in this environment.",
|
|
21
21
|
"If that is expected, build the advisory DB on a machine with OSV access, then scan here with `--offline` or `--offline-db /path/to/advisories.db`.",
|
|
22
22
|
"Command to build the DB on a network-allowed machine: `cve-lite advisories sync --output /path/to/advisories.db`",
|
|
23
|
+
"If your network uses SSL inspection, try: cve-lite config set ca-cert /path/to/corporate-ca.crt",
|
|
24
|
+
];
|
|
25
|
+
}
|
|
26
|
+
export function fetchErrorCaCertHint() {
|
|
27
|
+
return [
|
|
28
|
+
"Hint: If your network uses a corporate SSL proxy, a CA certificate may be required.",
|
|
29
|
+
"Run: cve-lite config set ca-cert /path/to/corporate-ca.crt",
|
|
23
30
|
];
|
|
24
31
|
}
|
|
25
32
|
const OFFLINE_FALLBACK_LINES = [
|
|
@@ -38,6 +45,13 @@ export function serverAdvisoryRequestHint() {
|
|
|
38
45
|
...OFFLINE_FALLBACK_LINES,
|
|
39
46
|
];
|
|
40
47
|
}
|
|
48
|
+
export function offlineDbSyncHint(offlineDb) {
|
|
49
|
+
const lines = ["To build it, run: cve-lite advisories sync"];
|
|
50
|
+
if (offlineDb) {
|
|
51
|
+
lines.push(`Or to save it to the requested path: cve-lite advisories sync --output ${offlineDb}`);
|
|
52
|
+
}
|
|
53
|
+
return lines;
|
|
54
|
+
}
|
|
41
55
|
const SSL_ERROR_CODES = new Set([
|
|
42
56
|
"SELF_SIGNED_CERT_IN_CHAIN",
|
|
43
57
|
"CERT_UNTRUSTED",
|
package/dist/utils/time.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { chalk } from "./chalk.js";
|
|
2
|
+
import { pluralize } from "./string.js";
|
|
2
3
|
export function formatAdvisoryDbFreshness(lastSyncAt) {
|
|
3
4
|
if (!lastSyncAt) {
|
|
4
5
|
return chalk.yellow("unknown");
|
|
@@ -19,12 +20,12 @@ export function relativeAge(timestamp) {
|
|
|
19
20
|
}
|
|
20
21
|
if (deltaMs < hour) {
|
|
21
22
|
const minutes = Math.floor(deltaMs / minute);
|
|
22
|
-
return `synced ${minutes}
|
|
23
|
+
return `synced ${minutes} ${pluralize(minutes, "minute")} ago`;
|
|
23
24
|
}
|
|
24
25
|
if (deltaMs < day) {
|
|
25
26
|
const hours = Math.floor(deltaMs / hour);
|
|
26
|
-
return `synced ${hours}
|
|
27
|
+
return `synced ${hours} ${pluralize(hours, "hour")} ago`;
|
|
27
28
|
}
|
|
28
29
|
const days = Math.floor(deltaMs / day);
|
|
29
|
-
return `synced ${days}
|
|
30
|
+
return `synced ${days} ${pluralize(days, "day")} ago`;
|
|
30
31
|
}
|