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
package/dist/index.js
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { spawn } from "node:child_process";
|
|
3
2
|
import path from "node:path";
|
|
4
3
|
import process from "node:process";
|
|
5
4
|
import { parseArgs } from "./cli/args.js";
|
|
@@ -12,18 +11,24 @@ import { normalizeSeverity } from "./osv/severity.js";
|
|
|
12
11
|
import { DEFAULT_BATCH_SIZE, DEFAULT_SEARCH_DEPTH, severityOrder } from "./constants.js";
|
|
13
12
|
import { chalk } from "./utils/chalk.js";
|
|
14
13
|
import { createSpinner } from "./output/spinner.js";
|
|
14
|
+
import { createDebugLogger } from "./output/debug.js";
|
|
15
15
|
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
|
-
import { blockedAdvisoryRequestHint, isLikelyBlockedAdvisoryRequestError, isRateLimitError, isServerError, isSslCertificateError, rateLimitAdvisoryRequestHint, serverAdvisoryRequestHint, sslCertificateErrorHint, } from "./utils/network.js";
|
|
18
|
+
import { blockedAdvisoryRequestHint, fetchErrorCaCertHint, isLikelyBlockedAdvisoryRequestError, isRateLimitError, isServerError, isSslCertificateError, offlineDbSyncHint, rateLimitAdvisoryRequestHint, serverAdvisoryRequestHint, sslCertificateErrorHint, } from "./utils/network.js";
|
|
19
19
|
import { formatAdvisoryDbFreshness } from "./utils/time.js";
|
|
20
|
+
import { pluralize } from "./utils/string.js";
|
|
20
21
|
import { formatAdvisorySourceLine, logInfo, logWarn, printCacheSummary, sortFindingsForOutput } from "./output/formatters.js";
|
|
21
22
|
import { countBySeverity } from "./utils/severity.js";
|
|
22
23
|
import { buildReportData, writeHtmlReport } from "./output/html-reporter.js";
|
|
23
24
|
import { writeOutputs } from "./output/write-outputs.js";
|
|
25
|
+
import { selectFindingsForTable } from "./output/finding-display.js";
|
|
24
26
|
import { printSummary, printActionSummary, printSuggestedFixCommands, printSuggestedFixCommandSkips, printCoverage, printSkippedDependencies, printTable, printFinalStatus, printCompactOutput } from "./output/printers.js";
|
|
25
27
|
import { installSkill } from "./skills/install.js";
|
|
28
|
+
import { readConfig, validateCaCertFile } from "./cli/config.js";
|
|
29
|
+
import { runConfigCommand } from "./cli/config-command.js";
|
|
26
30
|
import { readDirectDependencyNames } from "./utils/package-json.js";
|
|
31
|
+
import { applyFixesIfRequested, printFixModeSummary, } from "./utils/fix-runner.js";
|
|
27
32
|
let parsedArgs = null;
|
|
28
33
|
try {
|
|
29
34
|
parsedArgs = parseArgs(process.argv.slice(2));
|
|
@@ -49,8 +54,53 @@ if (parsedArgs) {
|
|
|
49
54
|
const projectPath = path.resolve(projectArg || ".");
|
|
50
55
|
const batchSize = Number(options.batchSize || DEFAULT_BATCH_SIZE);
|
|
51
56
|
const searchDepth = Math.max(0, Number(options.searchDepth || DEFAULT_SEARCH_DEPTH));
|
|
57
|
+
const debugSession = createDebugLogger(!!options.debug);
|
|
58
|
+
const debugLog = debugSession.log;
|
|
59
|
+
const scanStartedAt = Date.now();
|
|
52
60
|
async function main() {
|
|
53
61
|
printBanner(options);
|
|
62
|
+
debugSession.announcePath();
|
|
63
|
+
debugLog("CLI started", {
|
|
64
|
+
version: cliVersion,
|
|
65
|
+
args: process.argv.slice(2),
|
|
66
|
+
});
|
|
67
|
+
if (command === "config") {
|
|
68
|
+
const { configSubcommand } = parsedArgs;
|
|
69
|
+
if (!configSubcommand) {
|
|
70
|
+
console.error(chalk.red("Error: config requires a subcommand: set, unset, show"));
|
|
71
|
+
console.error(chalk.gray("Run `cve-lite --help` for usage."));
|
|
72
|
+
process.exit(1);
|
|
73
|
+
}
|
|
74
|
+
try {
|
|
75
|
+
runConfigCommand(configSubcommand);
|
|
76
|
+
}
|
|
77
|
+
catch (error) {
|
|
78
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
79
|
+
console.error(chalk.red(`Error: ${message}`));
|
|
80
|
+
process.exit(1);
|
|
81
|
+
}
|
|
82
|
+
process.exit(0);
|
|
83
|
+
}
|
|
84
|
+
const savedConfig = readConfig();
|
|
85
|
+
const resolvedCaCert = options.caCert ?? savedConfig.caCert;
|
|
86
|
+
if (resolvedCaCert) {
|
|
87
|
+
if (!options.caCert && savedConfig.caCert) {
|
|
88
|
+
try {
|
|
89
|
+
validateCaCertFile(resolvedCaCert);
|
|
90
|
+
}
|
|
91
|
+
catch (err) {
|
|
92
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
93
|
+
console.error(chalk.red(`Error: Saved ca-cert is no longer valid: ${message}`));
|
|
94
|
+
console.error(chalk.gray(`Run \`cve-lite config unset ca-cert\` to remove it.`));
|
|
95
|
+
process.exit(1);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
process.env.NODE_EXTRA_CA_CERTS = resolvedCaCert;
|
|
99
|
+
}
|
|
100
|
+
debugLog("Config loaded", {
|
|
101
|
+
caCert: resolvedCaCert ?? null,
|
|
102
|
+
nodeExtraCaCerts: process.env.NODE_EXTRA_CA_CERTS ?? null,
|
|
103
|
+
});
|
|
54
104
|
if (command === "advisories-sync") {
|
|
55
105
|
const spinner = createSpinner("Preparing advisory sync...", options);
|
|
56
106
|
const usePlainProgressLogs = !process.stdout.isTTY || !!options.json;
|
|
@@ -73,7 +123,7 @@ if (parsedArgs) {
|
|
|
73
123
|
else {
|
|
74
124
|
spinner.succeed(`Advisory sync complete (${result.advisoryCount} records)`);
|
|
75
125
|
}
|
|
76
|
-
console.log(`${chalk.gray("Advisory database:")} synced ${result.advisoryCount}
|
|
126
|
+
console.log(`${chalk.gray("Advisory database:")} synced ${result.advisoryCount} ${pluralize(result.advisoryCount, "record")} to ${chalk.cyan(result.dbPath)}`);
|
|
77
127
|
process.exit(0);
|
|
78
128
|
return;
|
|
79
129
|
}
|
|
@@ -91,8 +141,14 @@ if (parsedArgs) {
|
|
|
91
141
|
osvUrl: options.osvUrl,
|
|
92
142
|
offline: options.offline,
|
|
93
143
|
offlineDb: options.offlineDb,
|
|
144
|
+
debugLog,
|
|
94
145
|
});
|
|
95
146
|
advisorySourceLine = advisorySource.sourceLabel;
|
|
147
|
+
debugLog("Advisory source", {
|
|
148
|
+
mode: advisorySource.offline ? "offline" : "online",
|
|
149
|
+
url: options.osvUrl ?? (advisorySource.offline ? null : "https://api.osv.dev"),
|
|
150
|
+
label: advisorySourceLine,
|
|
151
|
+
});
|
|
96
152
|
if (advisorySource.offline) {
|
|
97
153
|
const metadata = advisorySource.advisoryDbMetadata;
|
|
98
154
|
advisoryDbFreshnessLine = formatAdvisoryDbFreshness(metadata?.lastSyncAt ?? null);
|
|
@@ -106,7 +162,8 @@ if (parsedArgs) {
|
|
|
106
162
|
}
|
|
107
163
|
catch (error) {
|
|
108
164
|
if (options.offline || options.offlineDb) {
|
|
109
|
-
|
|
165
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
166
|
+
throw new Error(`Offline advisory database is not available: ${reason}\n${offlineDbSyncHint(options.offlineDb).join("\n")}`);
|
|
110
167
|
}
|
|
111
168
|
throw error;
|
|
112
169
|
}
|
|
@@ -124,7 +181,17 @@ if (parsedArgs) {
|
|
|
124
181
|
}
|
|
125
182
|
let scanInput = loadPackages(projectPath, !!options.prodOnly, searchDepth);
|
|
126
183
|
let packages = scanInput.packages;
|
|
127
|
-
|
|
184
|
+
if (scanInput.filePath) {
|
|
185
|
+
debugLog("Lockfile selected", {
|
|
186
|
+
source: scanInput.source,
|
|
187
|
+
path: scanInput.filePath,
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
debugLog("Packages parsed", {
|
|
191
|
+
count: packages.length,
|
|
192
|
+
source: scanInput.source,
|
|
193
|
+
});
|
|
194
|
+
logInfo(`Parsed ${packages.length} ${pluralize(packages.length, "package")} from ${scanInput.source}${scanInput.filePath ? ` (${path.relative(projectPath, scanInput.filePath) || path.basename(scanInput.filePath)})` : ""}`, options);
|
|
128
195
|
printCacheSummary(options.cacheDir, options);
|
|
129
196
|
if (scanInput.warnings.length > 0) {
|
|
130
197
|
for (const warning of scanInput.warnings) {
|
|
@@ -132,6 +199,7 @@ if (parsedArgs) {
|
|
|
132
199
|
}
|
|
133
200
|
}
|
|
134
201
|
if (packages.length === 0) {
|
|
202
|
+
debugLog("Scan skipped", { reason: "no packages found", projectPath });
|
|
135
203
|
logWarn(buildNoPackagesMessage(projectPath), options);
|
|
136
204
|
process.exit(0);
|
|
137
205
|
return;
|
|
@@ -141,6 +209,7 @@ if (parsedArgs) {
|
|
|
141
209
|
batchSize,
|
|
142
210
|
options,
|
|
143
211
|
projectPath,
|
|
212
|
+
debugLog,
|
|
144
213
|
});
|
|
145
214
|
const findingsBeforeFix = scanState.sorted.length;
|
|
146
215
|
let fixResult = null;
|
|
@@ -150,12 +219,14 @@ if (parsedArgs) {
|
|
|
150
219
|
projectPath,
|
|
151
220
|
totalFindings: scanState.sorted.length,
|
|
152
221
|
options,
|
|
222
|
+
debugLog,
|
|
153
223
|
});
|
|
154
224
|
if (fixResult.appliedFixCount > 0) {
|
|
155
225
|
console.log(`${chalk.cyan("⠋")} ${chalk.gray("Rescanning project...")}`);
|
|
156
226
|
scanInput = loadPackages(projectPath, !!options.prodOnly, searchDepth);
|
|
157
227
|
packages = scanInput.packages;
|
|
158
228
|
if (packages.length === 0) {
|
|
229
|
+
debugLog("Scan skipped", { reason: "no packages found after fix rescan", projectPath });
|
|
159
230
|
logWarn(buildNoPackagesMessage(projectPath), options);
|
|
160
231
|
process.exit(0);
|
|
161
232
|
return;
|
|
@@ -165,6 +236,7 @@ if (parsedArgs) {
|
|
|
165
236
|
batchSize,
|
|
166
237
|
options,
|
|
167
238
|
projectPath,
|
|
239
|
+
debugLog,
|
|
168
240
|
});
|
|
169
241
|
}
|
|
170
242
|
}
|
|
@@ -231,6 +303,11 @@ if (parsedArgs) {
|
|
|
231
303
|
});
|
|
232
304
|
console.log(`${chalk.gray("Report:")} ${chalk.cyan(reportPath)}`);
|
|
233
305
|
}
|
|
306
|
+
debugLog("Scan finished", {
|
|
307
|
+
totalDurationMs: Date.now() - scanStartedAt,
|
|
308
|
+
findings: scanState.sorted.length,
|
|
309
|
+
packages: packages.length,
|
|
310
|
+
});
|
|
234
311
|
const failLevel = normalizeSeverity(options.failOn);
|
|
235
312
|
const shouldFail = scanState.sorted.some(f => severityOrder[f.severity] >= severityOrder[failLevel]);
|
|
236
313
|
process.exit(shouldFail ? 1 : 0);
|
|
@@ -239,6 +316,9 @@ if (parsedArgs) {
|
|
|
239
316
|
main().catch((error) => {
|
|
240
317
|
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
241
318
|
console.error(chalk.red(`Error: ${errorMessage}`));
|
|
319
|
+
if (options.debug && error instanceof Error && error.stack) {
|
|
320
|
+
debugLog("Unhandled error", { message: error.message, stack: error.stack });
|
|
321
|
+
}
|
|
242
322
|
if (isSslCertificateError(error)) {
|
|
243
323
|
const [hint, ...rest] = sslCertificateErrorHint();
|
|
244
324
|
console.error(chalk.yellow(hint));
|
|
@@ -259,6 +339,11 @@ if (parsedArgs) {
|
|
|
259
339
|
console.error(chalk.yellow(hint));
|
|
260
340
|
rest.forEach(line => console.error(chalk.gray(line)));
|
|
261
341
|
}
|
|
342
|
+
else {
|
|
343
|
+
const [hint, ...rest] = fetchErrorCaCertHint();
|
|
344
|
+
console.error(chalk.yellow(hint));
|
|
345
|
+
rest.forEach(line => console.error(chalk.gray(line)));
|
|
346
|
+
}
|
|
262
347
|
process.exit(1);
|
|
263
348
|
});
|
|
264
349
|
}
|
|
@@ -269,24 +354,44 @@ async function scanProject(params) {
|
|
|
269
354
|
directDependencyNames,
|
|
270
355
|
scanSource: params.scanInput.source,
|
|
271
356
|
scanFilePath: params.scanInput.filePath,
|
|
272
|
-
});
|
|
357
|
+
}, params.debugLog);
|
|
273
358
|
if (params.options.usage) {
|
|
274
359
|
logInfo(`Scanning project source for usage hints...`, params.options);
|
|
360
|
+
const usageStartedAt = Date.now();
|
|
275
361
|
const pkgNames = new Set(findings.map(f => f.pkg.name));
|
|
276
362
|
const usageData = scanProjectForPackageUsage(params.projectPath, pkgNames);
|
|
363
|
+
let matchedPackages = 0;
|
|
277
364
|
for (const finding of findings) {
|
|
278
365
|
const files = usageData[finding.pkg.name];
|
|
279
366
|
if (files) {
|
|
367
|
+
if (files.length > 0) {
|
|
368
|
+
matchedPackages += 1;
|
|
369
|
+
}
|
|
280
370
|
finding.usage = {
|
|
281
371
|
imported: files.length > 0,
|
|
282
372
|
files,
|
|
283
373
|
};
|
|
284
374
|
}
|
|
285
375
|
}
|
|
376
|
+
if (params.options.debug) {
|
|
377
|
+
params.debugLog("Usage scan", {
|
|
378
|
+
durationMs: Date.now() - usageStartedAt,
|
|
379
|
+
packagesChecked: pkgNames.size,
|
|
380
|
+
matchedPackages,
|
|
381
|
+
});
|
|
382
|
+
}
|
|
286
383
|
}
|
|
287
384
|
let finalFindings = findings;
|
|
288
385
|
if (params.options.onlyUsed) {
|
|
386
|
+
const beforeCount = finalFindings.length;
|
|
289
387
|
finalFindings = finalFindings.filter(f => f.usage?.imported);
|
|
388
|
+
if (params.options.debug) {
|
|
389
|
+
params.debugLog("Findings filtered", {
|
|
390
|
+
reason: "only-used",
|
|
391
|
+
before: beforeCount,
|
|
392
|
+
after: finalFindings.length,
|
|
393
|
+
});
|
|
394
|
+
}
|
|
290
395
|
}
|
|
291
396
|
const offline = !!params.options.offline || !!params.options.offlineDb;
|
|
292
397
|
const sorted = sortFindingsForOutput(finalFindings);
|
|
@@ -294,7 +399,7 @@ async function scanProject(params) {
|
|
|
294
399
|
const minSeverity = normalizeSeverity(params.options.minSeverity || "medium");
|
|
295
400
|
const tableFindings = params.options.all
|
|
296
401
|
? sorted
|
|
297
|
-
: sorted
|
|
402
|
+
: selectFindingsForTable(sorted, minSeverity);
|
|
298
403
|
const suggestedFixCommands = buildSuggestedFixCommandPlan(sorted, params.scanInput, { offline });
|
|
299
404
|
return {
|
|
300
405
|
sorted,
|
|
@@ -305,126 +410,3 @@ async function scanProject(params) {
|
|
|
305
410
|
allPackages: params.scanInput.packages,
|
|
306
411
|
};
|
|
307
412
|
}
|
|
308
|
-
async function applyFixesIfRequested(params) {
|
|
309
|
-
console.log("");
|
|
310
|
-
console.log(chalk.bold.cyan("Applying fixes (--fix)"));
|
|
311
|
-
if (!params.plan) {
|
|
312
|
-
return {
|
|
313
|
-
appliedFixCount: 0,
|
|
314
|
-
skippedCount: params.totalFindings,
|
|
315
|
-
skippedTransitiveCount: 0,
|
|
316
|
-
skippedNoValidatedTargetCount: params.totalFindings,
|
|
317
|
-
applied: [],
|
|
318
|
-
note: "No package-manager-native fix command is available for this project.",
|
|
319
|
-
};
|
|
320
|
-
}
|
|
321
|
-
const directTargets = params.plan.targets.filter(target => target.kind === "direct");
|
|
322
|
-
const transitiveTargets = params.plan.targets.filter(target => target.kind !== "direct");
|
|
323
|
-
const skippedDirect = params.plan.skipped.filter(skip => skip.relationship === "direct" || skip.relationship === "unknown");
|
|
324
|
-
if (directTargets.length === 0) {
|
|
325
|
-
const skippedCount = transitiveTargets.length + skippedDirect.length;
|
|
326
|
-
return {
|
|
327
|
-
appliedFixCount: 0,
|
|
328
|
-
skippedCount,
|
|
329
|
-
skippedTransitiveCount: transitiveTargets.length,
|
|
330
|
-
skippedNoValidatedTargetCount: skippedDirect.length,
|
|
331
|
-
applied: [],
|
|
332
|
-
note: "No validated direct dependency fixes were eligible for auto-apply.",
|
|
333
|
-
};
|
|
334
|
-
}
|
|
335
|
-
const commandLabel = commandLabelForPackageManager(params.plan.packageManager);
|
|
336
|
-
const total = directTargets.length;
|
|
337
|
-
const spinner = createSpinner(`Applying direct package fixes with ${commandLabel}... 0/${total}`, params.options);
|
|
338
|
-
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.`;
|
|
339
|
-
for (let i = 0; i < directTargets.length; i++) {
|
|
340
|
-
const target = directTargets[i];
|
|
341
|
-
const commandParts = buildFixCommandParts(params.plan.packageManager, [target]);
|
|
342
|
-
spinner.update(`Applying direct fix ${i + 1}/${total}: ${commandParts.join(" ")}`);
|
|
343
|
-
const run = await runInstallCommand(commandParts[0], commandParts.slice(1), params.projectPath);
|
|
344
|
-
if (run.error) {
|
|
345
|
-
spinner.fail("Failed to apply fixes");
|
|
346
|
-
throw new Error(`Failed to apply fixes: ${run.error.message}${fixHint}`);
|
|
347
|
-
}
|
|
348
|
-
if ((run.status ?? 1) !== 0) {
|
|
349
|
-
spinner.fail(`Fix command failed (${commandLabel})`);
|
|
350
|
-
throw new Error(`Fix command exited with status ${run.status ?? 1}${fixHint}`);
|
|
351
|
-
}
|
|
352
|
-
}
|
|
353
|
-
spinner.succeed(`Applied ${directTargets.length} direct package fix${directTargets.length === 1 ? "" : "es"} with ${commandLabel}`);
|
|
354
|
-
const skippedCount = transitiveTargets.length + skippedDirect.length;
|
|
355
|
-
return {
|
|
356
|
-
appliedFixCount: directTargets.length,
|
|
357
|
-
skippedCount,
|
|
358
|
-
skippedTransitiveCount: transitiveTargets.length,
|
|
359
|
-
skippedNoValidatedTargetCount: skippedDirect.length,
|
|
360
|
-
applied: directTargets.map(target => ({
|
|
361
|
-
package: target.package,
|
|
362
|
-
from: target.currentVersion ?? "unknown",
|
|
363
|
-
to: target.targetVersion,
|
|
364
|
-
})),
|
|
365
|
-
note: null,
|
|
366
|
-
};
|
|
367
|
-
}
|
|
368
|
-
function buildFixCommandParts(packageManager, targets) {
|
|
369
|
-
if (packageManager === "npm") {
|
|
370
|
-
return ["npm", "install", ...targets.map(target => `${target.package}@${target.targetVersion}`)];
|
|
371
|
-
}
|
|
372
|
-
if (packageManager === "pnpm") {
|
|
373
|
-
return ["pnpm", "add", ...targets.map(target => `${target.package}@${target.targetVersion}`)];
|
|
374
|
-
}
|
|
375
|
-
if (packageManager === "bun") {
|
|
376
|
-
return ["bun", "add", ...targets.map(target => `${target.package}@${target.targetVersion}`)];
|
|
377
|
-
}
|
|
378
|
-
return ["yarn", "add", ...targets.map(target => `${target.package}@${target.targetVersion}`)];
|
|
379
|
-
}
|
|
380
|
-
async function runInstallCommand(command, args, cwd) {
|
|
381
|
-
return await new Promise(resolve => {
|
|
382
|
-
const child = spawn(command, args, {
|
|
383
|
-
cwd,
|
|
384
|
-
stdio: ["ignore", "pipe", "pipe"],
|
|
385
|
-
});
|
|
386
|
-
child.stdout.on("data", () => { });
|
|
387
|
-
child.stderr.on("data", () => { });
|
|
388
|
-
child.on("error", error => {
|
|
389
|
-
resolve({ status: null, error });
|
|
390
|
-
});
|
|
391
|
-
child.on("close", code => {
|
|
392
|
-
resolve({ status: code, error: null });
|
|
393
|
-
});
|
|
394
|
-
});
|
|
395
|
-
}
|
|
396
|
-
function commandLabelForPackageManager(packageManager) {
|
|
397
|
-
if (packageManager === "npm")
|
|
398
|
-
return "npm install";
|
|
399
|
-
if (packageManager === "pnpm")
|
|
400
|
-
return "pnpm add";
|
|
401
|
-
if (packageManager === "bun")
|
|
402
|
-
return "bun add";
|
|
403
|
-
return "yarn add";
|
|
404
|
-
}
|
|
405
|
-
function printFixModeSummary(params) {
|
|
406
|
-
const result = params.fixResult;
|
|
407
|
-
if (!result)
|
|
408
|
-
return;
|
|
409
|
-
if (result.note) {
|
|
410
|
-
console.log(chalk.gray(result.note));
|
|
411
|
-
}
|
|
412
|
-
if (result.applied.length > 0) {
|
|
413
|
-
console.log("");
|
|
414
|
-
console.log(chalk.bold.cyan("Applied fixes"));
|
|
415
|
-
for (const item of result.applied) {
|
|
416
|
-
console.log(`- ${chalk.white(item.package)}: ${chalk.gray(item.from)} ${chalk.cyan("->")} ${chalk.green(item.to)}`);
|
|
417
|
-
}
|
|
418
|
-
}
|
|
419
|
-
console.log("");
|
|
420
|
-
console.log(chalk.bold.cyan("Fix summary"));
|
|
421
|
-
console.log(`- Applied fixes: ${chalk.green(String(result.appliedFixCount))}`);
|
|
422
|
-
console.log(`- Skipped findings: ${chalk.yellow(String(result.skippedCount))}`);
|
|
423
|
-
if (result.skippedCount > 0) {
|
|
424
|
-
console.log(` - Transitive (v1 skip): ${chalk.yellow(String(result.skippedTransitiveCount))}`);
|
|
425
|
-
console.log(` - No validated direct target: ${chalk.yellow(String(result.skippedNoValidatedTargetCount))}`);
|
|
426
|
-
}
|
|
427
|
-
console.log(`- Findings before fix: ${chalk.white(String(params.findingsBeforeFix))}`);
|
|
428
|
-
console.log(`- Remaining findings after fix: ${chalk.white(String(params.findingsAfterFix))}`);
|
|
429
|
-
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))}`);
|
|
430
|
-
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import process from "node:process";
|
|
2
|
+
function cleanup(handler) {
|
|
3
|
+
process.stdin.setRawMode(false);
|
|
4
|
+
process.stdin.pause();
|
|
5
|
+
process.stdin.removeListener("data", handler);
|
|
6
|
+
}
|
|
7
|
+
function listenOnStdin(onKey) {
|
|
8
|
+
process.stdin.setRawMode(true);
|
|
9
|
+
process.stdin.resume();
|
|
10
|
+
process.stdin.setEncoding("utf8");
|
|
11
|
+
const handler = (key) => {
|
|
12
|
+
if (key === "") {
|
|
13
|
+
cleanup(handler);
|
|
14
|
+
process.exit(0);
|
|
15
|
+
return;
|
|
16
|
+
}
|
|
17
|
+
onKey(key, handler);
|
|
18
|
+
};
|
|
19
|
+
process.stdin.on("data", handler);
|
|
20
|
+
}
|
|
21
|
+
export function waitForKeypress(valid) {
|
|
22
|
+
if (valid.length === 0)
|
|
23
|
+
throw new Error("waitForKeypress: valid keys array must not be empty");
|
|
24
|
+
return new Promise((resolve) => {
|
|
25
|
+
listenOnStdin((key, handler) => {
|
|
26
|
+
if (valid.includes(key.toLowerCase())) {
|
|
27
|
+
cleanup(handler);
|
|
28
|
+
resolve(key.toLowerCase());
|
|
29
|
+
}
|
|
30
|
+
});
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
export function waitForEnter() {
|
|
34
|
+
return new Promise((resolve) => {
|
|
35
|
+
listenOnStdin((key, handler) => {
|
|
36
|
+
if (key === "\r" || key === "\n") {
|
|
37
|
+
cleanup(handler);
|
|
38
|
+
resolve();
|
|
39
|
+
}
|
|
40
|
+
});
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
export function waitForAnyKey() {
|
|
44
|
+
return new Promise((resolve) => {
|
|
45
|
+
listenOnStdin((key, handler) => {
|
|
46
|
+
cleanup(handler);
|
|
47
|
+
resolve();
|
|
48
|
+
});
|
|
49
|
+
});
|
|
50
|
+
}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import os from "node:os";
|
|
2
|
+
import fs from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { fetchScenarioIndex, fetchScenario } from "./scenario.js";
|
|
5
|
+
import { runSession } from "./session.js";
|
|
6
|
+
import { loadPackages } from "../parsers/index.js";
|
|
7
|
+
import { scanPackages } from "../scanner.js";
|
|
8
|
+
import { chalk } from "../utils/chalk.js";
|
|
9
|
+
import { waitForKeypress } from "./keypress.js";
|
|
10
|
+
import { countBySeverity } from "../utils/severity.js";
|
|
11
|
+
function formatFindings(findings) {
|
|
12
|
+
const counts = countBySeverity(findings);
|
|
13
|
+
const total = findings.length;
|
|
14
|
+
const label = total === 1 ? "finding" : "findings";
|
|
15
|
+
const parts = [];
|
|
16
|
+
if (counts.critical > 0)
|
|
17
|
+
parts.push(`${counts.critical} critical`);
|
|
18
|
+
if (counts.high > 0)
|
|
19
|
+
parts.push(`${counts.high} high`);
|
|
20
|
+
if (counts.medium > 0)
|
|
21
|
+
parts.push(`${counts.medium} medium`);
|
|
22
|
+
if (counts.low > 0)
|
|
23
|
+
parts.push(`${counts.low} low`);
|
|
24
|
+
return parts.length > 0 ? `${total} ${label} (${parts.join(" · ")})` : `${total} ${label}`;
|
|
25
|
+
}
|
|
26
|
+
export async function runLearnCommand() {
|
|
27
|
+
let index;
|
|
28
|
+
try {
|
|
29
|
+
index = await fetchScenarioIndex();
|
|
30
|
+
}
|
|
31
|
+
catch {
|
|
32
|
+
console.error("Could not fetch scenario. Check your connection and try again.");
|
|
33
|
+
process.exit(1);
|
|
34
|
+
return;
|
|
35
|
+
}
|
|
36
|
+
console.log("\nCVE Lite CLI - Learn Mode\n");
|
|
37
|
+
console.log("Available scenarios:");
|
|
38
|
+
index.scenarios.forEach((s, i) => {
|
|
39
|
+
console.log(` ${i + 1}. ${s.title.padEnd(40)} (${s.difficulty})`);
|
|
40
|
+
});
|
|
41
|
+
const validKeys = index.scenarios.map((_, i) => String(i + 1));
|
|
42
|
+
process.stdout.write(`\nPick a scenario [1-${index.scenarios.length}]: `);
|
|
43
|
+
const choice = await waitForKeypress(validKeys);
|
|
44
|
+
console.log(choice);
|
|
45
|
+
const selected = index.scenarios[Number(choice) - 1];
|
|
46
|
+
let scenarioData;
|
|
47
|
+
try {
|
|
48
|
+
scenarioData = await fetchScenario(selected.id);
|
|
49
|
+
}
|
|
50
|
+
catch {
|
|
51
|
+
console.error("Could not fetch scenario. Check your connection and try again.");
|
|
52
|
+
process.exit(1);
|
|
53
|
+
return;
|
|
54
|
+
}
|
|
55
|
+
const { scenario, lockfileContent, fixedLockfileContent } = scenarioData;
|
|
56
|
+
const tempDir = path.join(os.tmpdir(), `cve-lite-learn-${selected.id}`);
|
|
57
|
+
fs.mkdirSync(tempDir, { recursive: true });
|
|
58
|
+
try {
|
|
59
|
+
console.log(`\nScenario: ${chalk.bold(scenario.title)}`);
|
|
60
|
+
console.log("-".repeat(42));
|
|
61
|
+
console.log(scenario.concept);
|
|
62
|
+
console.log("\nScanning...");
|
|
63
|
+
fs.writeFileSync(path.join(tempDir, "package-lock.json"), lockfileContent, "utf8");
|
|
64
|
+
const initialInput = loadPackages(tempDir, false, 4);
|
|
65
|
+
const initialFindings = await scanPackages(initialInput.packages, 100, { failOn: "critical", batchSize: "100", json: true });
|
|
66
|
+
if (initialFindings.length === 0) {
|
|
67
|
+
console.error("Unexpected: no findings. The scenario may be outdated - please update CVE Lite CLI.");
|
|
68
|
+
process.exit(1);
|
|
69
|
+
return;
|
|
70
|
+
}
|
|
71
|
+
await runSession(scenario);
|
|
72
|
+
console.log("\nIn a real project, you would run:\n");
|
|
73
|
+
console.log(` ${chalk.cyan(scenario.fixCommand)}`);
|
|
74
|
+
console.log("\nApplying the fix for this scenario...\n");
|
|
75
|
+
console.log("Rescanning...\n");
|
|
76
|
+
fs.writeFileSync(path.join(tempDir, "package-lock.json"), fixedLockfileContent, "utf8");
|
|
77
|
+
const fixedInput = loadPackages(tempDir, false, 4);
|
|
78
|
+
const fixedFindings = await scanPackages(fixedInput.packages, 100, { failOn: "critical", batchSize: "100", json: true });
|
|
79
|
+
console.log(`Before: ${formatFindings(initialFindings)}`);
|
|
80
|
+
console.log(`After: ${formatFindings(fixedFindings)}`);
|
|
81
|
+
const beforeCounts = countBySeverity(initialFindings);
|
|
82
|
+
const afterCounts = countBySeverity(fixedFindings);
|
|
83
|
+
const improved = fixedFindings.length < initialFindings.length ||
|
|
84
|
+
(beforeCounts.critical > 0 && afterCounts.critical === 0) ||
|
|
85
|
+
(beforeCounts.high > 0 && afterCounts.high === 0);
|
|
86
|
+
if (improved || fixedFindings.length === 0) {
|
|
87
|
+
console.log(chalk.green(`\n✓ ${scenario.successMessage}`));
|
|
88
|
+
}
|
|
89
|
+
else {
|
|
90
|
+
console.log(chalk.yellow("\nSome findings remain - the fix may be partially applied or the lockfile was not updated."));
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
finally {
|
|
94
|
+
fs.rmSync(tempDir, { recursive: true, force: true });
|
|
95
|
+
}
|
|
96
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import os from "node:os";
|
|
4
|
+
const BASE_URL = process.env["CVE_LITE_LEARN_BASE_URL"] ??
|
|
5
|
+
"https://raw.githubusercontent.com/OWASP/cve-lite-cli/main/examples/learn";
|
|
6
|
+
const CACHE_TTL_MS = 24 * 60 * 60 * 1000;
|
|
7
|
+
function getCacheDir(key) {
|
|
8
|
+
return path.join(os.homedir(), ".cache", "cve-lite", "learn", key);
|
|
9
|
+
}
|
|
10
|
+
async function fetchWithCache(url, cachePath) {
|
|
11
|
+
const cacheDir = path.dirname(cachePath);
|
|
12
|
+
if (fs.existsSync(cachePath)) {
|
|
13
|
+
const { mtimeMs } = fs.statSync(cachePath);
|
|
14
|
+
if (Date.now() - mtimeMs < CACHE_TTL_MS) {
|
|
15
|
+
return fs.readFileSync(cachePath, "utf8");
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
const res = await fetch(url);
|
|
19
|
+
if (!res.ok)
|
|
20
|
+
throw new Error(`Fetch failed: ${url} (${res.status})`);
|
|
21
|
+
const text = await res.text();
|
|
22
|
+
fs.mkdirSync(cacheDir, { recursive: true });
|
|
23
|
+
fs.writeFileSync(cachePath, text, "utf8");
|
|
24
|
+
return text;
|
|
25
|
+
}
|
|
26
|
+
export async function fetchScenarioIndex() {
|
|
27
|
+
const cachePath = path.join(getCacheDir("_index"), "index.json");
|
|
28
|
+
const text = await fetchWithCache(`${BASE_URL}/index.json`, cachePath);
|
|
29
|
+
const data = JSON.parse(text);
|
|
30
|
+
if (!Array.isArray(data?.scenarios)) {
|
|
31
|
+
throw new Error("Invalid index.json: missing scenarios array");
|
|
32
|
+
}
|
|
33
|
+
return data;
|
|
34
|
+
}
|
|
35
|
+
export async function fetchScenario(id) {
|
|
36
|
+
const cacheDir = getCacheDir(id);
|
|
37
|
+
const [scenarioText, lockfileContent, fixedLockfileContent] = await Promise.all([
|
|
38
|
+
fetchWithCache(`${BASE_URL}/${id}/scenario.json`, path.join(cacheDir, "scenario.json")),
|
|
39
|
+
fetchWithCache(`${BASE_URL}/${id}/package-lock.json`, path.join(cacheDir, "package-lock.json")),
|
|
40
|
+
fetchWithCache(`${BASE_URL}/${id}/package-lock-fixed.json`, path.join(cacheDir, "package-lock-fixed.json")),
|
|
41
|
+
]);
|
|
42
|
+
const scenario = JSON.parse(scenarioText);
|
|
43
|
+
if (!scenario.title || !Array.isArray(scenario.steps)) {
|
|
44
|
+
throw new Error(`Invalid scenario.json for ${id}`);
|
|
45
|
+
}
|
|
46
|
+
return { scenario, lockfileContent, fixedLockfileContent };
|
|
47
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { chalk } from "../utils/chalk.js";
|
|
2
|
+
import { waitForKeypress, waitForAnyKey } from "./keypress.js";
|
|
3
|
+
async function runStep(step, stepNumber, total) {
|
|
4
|
+
console.log(`\nFinding ${stepNumber} of ${total}`);
|
|
5
|
+
console.log(`Package: ${chalk.bold(step.finding)}`);
|
|
6
|
+
console.log(`Severity: ${chalk.red(step.severity.toUpperCase())}`);
|
|
7
|
+
if (step.type) {
|
|
8
|
+
console.log(`Type: ${step.type} dependency`);
|
|
9
|
+
}
|
|
10
|
+
console.log(`\n${step.question}`);
|
|
11
|
+
step.options.forEach(opt => console.log(` ${opt}`));
|
|
12
|
+
const validKeys = step.options.map((_, i) => String.fromCharCode(97 + i));
|
|
13
|
+
process.stdout.write(`\nYour answer [a-${String.fromCharCode(96 + step.options.length)}]: `);
|
|
14
|
+
const answer = await waitForKeypress(validKeys);
|
|
15
|
+
console.log(answer);
|
|
16
|
+
const correct = answer === step.correct.toLowerCase();
|
|
17
|
+
if (correct) {
|
|
18
|
+
console.log(chalk.green(`\n✓ ${step.correct_explanation}`));
|
|
19
|
+
}
|
|
20
|
+
else {
|
|
21
|
+
console.log(chalk.red(`\n✗ ${step.wrong_explanation}`));
|
|
22
|
+
}
|
|
23
|
+
process.stdout.write("\nPress any key to continue...");
|
|
24
|
+
await waitForAnyKey();
|
|
25
|
+
console.log();
|
|
26
|
+
return correct;
|
|
27
|
+
}
|
|
28
|
+
export async function runSession(scenario) {
|
|
29
|
+
let correct = 0;
|
|
30
|
+
for (let i = 0; i < scenario.steps.length; i++) {
|
|
31
|
+
if (await runStep(scenario.steps[i], i + 1, scenario.steps.length)) {
|
|
32
|
+
correct++;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
return correct;
|
|
36
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|