cve-lite-cli 1.17.3 → 1.18.1
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 +14 -0
- package/dist/advisory/osv-sync.js +3 -2
- package/dist/cli/args.js +54 -3
- package/dist/cli/config-command.js +40 -0
- package/dist/cli/config.js +66 -0
- package/dist/cli/help.js +8 -0
- package/dist/cli/validate.js +31 -0
- package/dist/constants.js +2 -0
- package/dist/index.js +66 -311
- package/dist/output/formatters.js +13 -5
- package/dist/output/html-reporter.js +10 -4
- package/dist/output/printers.js +20 -12
- package/dist/parsers/bun-lock.js +19 -0
- package/dist/parsers/package-lock.js +23 -0
- package/dist/parsers/pnpm-lock.js +20 -0
- package/dist/parsers/yarn-lock.js +60 -0
- package/dist/remediation/fix-commands.js +145 -14
- package/dist/remediation/npm-transitive-resolution.js +63 -0
- package/dist/scanner.js +58 -6
- package/dist/usage/scanner.js +3 -2
- package/dist/utils/fix-runner.js +127 -0
- package/dist/utils/network.js +58 -8
- package/dist/utils/package-json.js +124 -0
- package/dist/utils/severity.js +14 -0
- package/dist/utils/string.js +3 -0
- package/dist/utils/time.js +31 -0
- package/dist/utils/update-check.js +102 -0
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,26 +1,32 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { spawn } from "node:child_process";
|
|
3
|
-
import fs from "node:fs";
|
|
4
2
|
import path from "node:path";
|
|
5
3
|
import process from "node:process";
|
|
6
4
|
import { parseArgs } from "./cli/args.js";
|
|
7
5
|
import { printBanner, printHelp } from "./cli/help.js";
|
|
6
|
+
import { validateOptions } from "./cli/validate.js";
|
|
8
7
|
import { loadPackages, buildNoPackagesMessage } from "./parsers/index.js";
|
|
9
8
|
import { scanPackages, buildCoverageNotes, createAdvisorySource } from "./scanner.js";
|
|
10
9
|
import { syncOsvAdvisories } from "./advisory/osv-sync.js";
|
|
11
10
|
import { normalizeSeverity } from "./osv/severity.js";
|
|
12
|
-
import { severityOrder } from "./constants.js";
|
|
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";
|
|
15
14
|
import { buildSuggestedFixCommandPlan } from "./remediation/fix-commands.js";
|
|
16
15
|
import { scanProjectForPackageUsage } from "./usage/scanner.js";
|
|
17
16
|
import { getCliVersion } from "./utils/version-info.js";
|
|
18
|
-
import { isLikelyBlockedAdvisoryRequestError, isSslCertificateError, sslCertificateErrorHint,
|
|
19
|
-
import {
|
|
17
|
+
import { blockedAdvisoryRequestHint, fetchErrorCaCertHint, isLikelyBlockedAdvisoryRequestError, isRateLimitError, isServerError, isSslCertificateError, rateLimitAdvisoryRequestHint, serverAdvisoryRequestHint, sslCertificateErrorHint, } from "./utils/network.js";
|
|
18
|
+
import { formatAdvisoryDbFreshness } from "./utils/time.js";
|
|
19
|
+
import { pluralize } from "./utils/string.js";
|
|
20
|
+
import { formatAdvisorySourceLine, logInfo, logWarn, printCacheSummary, sortFindingsForOutput } from "./output/formatters.js";
|
|
21
|
+
import { countBySeverity } from "./utils/severity.js";
|
|
20
22
|
import { buildReportData, writeHtmlReport } from "./output/html-reporter.js";
|
|
21
23
|
import { writeOutputs } from "./output/write-outputs.js";
|
|
22
24
|
import { printSummary, printActionSummary, printSuggestedFixCommands, printSuggestedFixCommandSkips, printCoverage, printSkippedDependencies, printTable, printFinalStatus, printCompactOutput } from "./output/printers.js";
|
|
23
25
|
import { installSkill } from "./skills/install.js";
|
|
26
|
+
import { readConfig, validateCaCertFile } from "./cli/config.js";
|
|
27
|
+
import { runConfigCommand } from "./cli/config-command.js";
|
|
28
|
+
import { readDirectDependencyNames } from "./utils/package-json.js";
|
|
29
|
+
import { applyFixesIfRequested, printFixModeSummary, } from "./utils/fix-runner.js";
|
|
24
30
|
let parsedArgs = null;
|
|
25
31
|
try {
|
|
26
32
|
parsedArgs = parseArgs(process.argv.slice(2));
|
|
@@ -39,15 +45,48 @@ if (parsedArgs) {
|
|
|
39
45
|
process.exit(0);
|
|
40
46
|
}
|
|
41
47
|
else if (options.version) {
|
|
42
|
-
printBanner();
|
|
48
|
+
printBanner(options);
|
|
43
49
|
process.exit(0);
|
|
44
50
|
}
|
|
45
51
|
else {
|
|
46
52
|
const projectPath = path.resolve(projectArg || ".");
|
|
47
|
-
const batchSize = Number(options.batchSize ||
|
|
48
|
-
const searchDepth = Math.max(0, Number(options.searchDepth ||
|
|
53
|
+
const batchSize = Number(options.batchSize || DEFAULT_BATCH_SIZE);
|
|
54
|
+
const searchDepth = Math.max(0, Number(options.searchDepth || DEFAULT_SEARCH_DEPTH));
|
|
49
55
|
async function main() {
|
|
50
|
-
printBanner();
|
|
56
|
+
printBanner(options);
|
|
57
|
+
if (command === "config") {
|
|
58
|
+
const { configSubcommand } = parsedArgs;
|
|
59
|
+
if (!configSubcommand) {
|
|
60
|
+
console.error(chalk.red("Error: config requires a subcommand: set, unset, show"));
|
|
61
|
+
console.error(chalk.gray("Run `cve-lite --help` for usage."));
|
|
62
|
+
process.exit(1);
|
|
63
|
+
}
|
|
64
|
+
try {
|
|
65
|
+
runConfigCommand(configSubcommand);
|
|
66
|
+
}
|
|
67
|
+
catch (error) {
|
|
68
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
69
|
+
console.error(chalk.red(`Error: ${message}`));
|
|
70
|
+
process.exit(1);
|
|
71
|
+
}
|
|
72
|
+
process.exit(0);
|
|
73
|
+
}
|
|
74
|
+
const savedConfig = readConfig();
|
|
75
|
+
const resolvedCaCert = options.caCert ?? savedConfig.caCert;
|
|
76
|
+
if (resolvedCaCert) {
|
|
77
|
+
if (!options.caCert && savedConfig.caCert) {
|
|
78
|
+
try {
|
|
79
|
+
validateCaCertFile(resolvedCaCert);
|
|
80
|
+
}
|
|
81
|
+
catch (err) {
|
|
82
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
83
|
+
console.error(chalk.red(`Error: Saved ca-cert is no longer valid: ${message}`));
|
|
84
|
+
console.error(chalk.gray(`Run \`cve-lite config unset ca-cert\` to remove it.`));
|
|
85
|
+
process.exit(1);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
process.env.NODE_EXTRA_CA_CERTS = resolvedCaCert;
|
|
89
|
+
}
|
|
51
90
|
if (command === "advisories-sync") {
|
|
52
91
|
const spinner = createSpinner("Preparing advisory sync...", options);
|
|
53
92
|
const usePlainProgressLogs = !process.stdout.isTTY || !!options.json;
|
|
@@ -70,7 +109,7 @@ if (parsedArgs) {
|
|
|
70
109
|
else {
|
|
71
110
|
spinner.succeed(`Advisory sync complete (${result.advisoryCount} records)`);
|
|
72
111
|
}
|
|
73
|
-
console.log(`${chalk.gray("Advisory database:")} synced ${result.advisoryCount}
|
|
112
|
+
console.log(`${chalk.gray("Advisory database:")} synced ${result.advisoryCount} ${pluralize(result.advisoryCount, "record")} to ${chalk.cyan(result.dbPath)}`);
|
|
74
113
|
process.exit(0);
|
|
75
114
|
return;
|
|
76
115
|
}
|
|
@@ -79,26 +118,7 @@ if (parsedArgs) {
|
|
|
79
118
|
process.exit(0);
|
|
80
119
|
return;
|
|
81
120
|
}
|
|
82
|
-
|
|
83
|
-
throw new Error("--offline/--offline-db cannot be used with --osv-url");
|
|
84
|
-
}
|
|
85
|
-
if (options.noCache && (options.offline || options.offlineDb)) {
|
|
86
|
-
throw new Error("--no-cache cannot be used with --offline or --offline-db");
|
|
87
|
-
}
|
|
88
|
-
if (options.osvUrl) {
|
|
89
|
-
try {
|
|
90
|
-
new URL(options.osvUrl);
|
|
91
|
-
}
|
|
92
|
-
catch {
|
|
93
|
-
throw new Error(`Invalid value for --osv-url: ${options.osvUrl}`);
|
|
94
|
-
}
|
|
95
|
-
}
|
|
96
|
-
if (options.fix && options.json) {
|
|
97
|
-
throw new Error("--fix cannot be used with --json");
|
|
98
|
-
}
|
|
99
|
-
if (options.report && options.json) {
|
|
100
|
-
throw new Error("--report cannot be used with --json");
|
|
101
|
-
}
|
|
121
|
+
validateOptions(options);
|
|
102
122
|
let advisorySourceLine;
|
|
103
123
|
let advisoryDbFreshnessLine = null;
|
|
104
124
|
let advisoryDbWarning = null;
|
|
@@ -140,7 +160,7 @@ if (parsedArgs) {
|
|
|
140
160
|
}
|
|
141
161
|
let scanInput = loadPackages(projectPath, !!options.prodOnly, searchDepth);
|
|
142
162
|
let packages = scanInput.packages;
|
|
143
|
-
logInfo(`Parsed ${packages.length}
|
|
163
|
+
logInfo(`Parsed ${packages.length} ${pluralize(packages.length, "package")} from ${scanInput.source}${scanInput.filePath ? ` (${path.relative(projectPath, scanInput.filePath) || path.basename(scanInput.filePath)})` : ""}`, options);
|
|
144
164
|
printCacheSummary(options.cacheDir, options);
|
|
145
165
|
if (scanInput.warnings.length > 0) {
|
|
146
166
|
for (const warning of scanInput.warnings) {
|
|
@@ -260,22 +280,30 @@ if (parsedArgs) {
|
|
|
260
280
|
console.error(chalk.yellow(hint));
|
|
261
281
|
rest.forEach(line => console.error(chalk.gray(line)));
|
|
262
282
|
}
|
|
283
|
+
else if (isRateLimitError(errorMessage)) {
|
|
284
|
+
const [hint, ...rest] = rateLimitAdvisoryRequestHint();
|
|
285
|
+
console.error(chalk.yellow(hint));
|
|
286
|
+
rest.forEach(line => console.error(chalk.gray(line)));
|
|
287
|
+
}
|
|
288
|
+
else if (isServerError(errorMessage)) {
|
|
289
|
+
const [hint, ...rest] = serverAdvisoryRequestHint();
|
|
290
|
+
console.error(chalk.yellow(hint));
|
|
291
|
+
rest.forEach(line => console.error(chalk.gray(line)));
|
|
292
|
+
}
|
|
263
293
|
else if (isLikelyBlockedAdvisoryRequestError(errorMessage)) {
|
|
264
294
|
const [hint, ...rest] = blockedAdvisoryRequestHint();
|
|
265
295
|
console.error(chalk.yellow(hint));
|
|
266
296
|
rest.forEach(line => console.error(chalk.gray(line)));
|
|
267
297
|
}
|
|
298
|
+
else {
|
|
299
|
+
const [hint, ...rest] = fetchErrorCaCertHint();
|
|
300
|
+
console.error(chalk.yellow(hint));
|
|
301
|
+
rest.forEach(line => console.error(chalk.gray(line)));
|
|
302
|
+
}
|
|
268
303
|
process.exit(1);
|
|
269
304
|
});
|
|
270
305
|
}
|
|
271
306
|
}
|
|
272
|
-
function formatAdvisorySourceLine(sourceLabel) {
|
|
273
|
-
const match = sourceLabel.match(/^(.*) \((.*)\)$/);
|
|
274
|
-
if (!match) {
|
|
275
|
-
return sourceLabel;
|
|
276
|
-
}
|
|
277
|
-
return `${match[1]} (${chalk.cyan(match[2])})`;
|
|
278
|
-
}
|
|
279
307
|
async function scanProject(params) {
|
|
280
308
|
const directDependencyNames = readDirectDependencyNames(params.projectPath, !!params.options.prodOnly);
|
|
281
309
|
const findings = await scanPackages(params.scanInput.packages, params.batchSize, params.options, {
|
|
@@ -318,276 +346,3 @@ async function scanProject(params) {
|
|
|
318
346
|
allPackages: params.scanInput.packages,
|
|
319
347
|
};
|
|
320
348
|
}
|
|
321
|
-
async function applyFixesIfRequested(params) {
|
|
322
|
-
console.log("");
|
|
323
|
-
console.log(chalk.bold.cyan("Applying fixes (--fix)"));
|
|
324
|
-
if (!params.plan) {
|
|
325
|
-
return {
|
|
326
|
-
appliedFixCount: 0,
|
|
327
|
-
skippedCount: params.totalFindings,
|
|
328
|
-
skippedTransitiveCount: 0,
|
|
329
|
-
skippedNoValidatedTargetCount: params.totalFindings,
|
|
330
|
-
applied: [],
|
|
331
|
-
note: "No package-manager-native fix command is available for this project.",
|
|
332
|
-
};
|
|
333
|
-
}
|
|
334
|
-
const directTargets = params.plan.targets.filter(target => target.kind === "direct");
|
|
335
|
-
const transitiveTargets = params.plan.targets.filter(target => target.kind !== "direct");
|
|
336
|
-
const skippedDirect = params.plan.skipped.filter(skip => skip.relationship === "direct" || skip.relationship === "unknown");
|
|
337
|
-
if (directTargets.length === 0) {
|
|
338
|
-
const skippedCount = transitiveTargets.length + skippedDirect.length;
|
|
339
|
-
return {
|
|
340
|
-
appliedFixCount: 0,
|
|
341
|
-
skippedCount,
|
|
342
|
-
skippedTransitiveCount: transitiveTargets.length,
|
|
343
|
-
skippedNoValidatedTargetCount: skippedDirect.length,
|
|
344
|
-
applied: [],
|
|
345
|
-
note: "No validated direct dependency fixes were eligible for auto-apply.",
|
|
346
|
-
};
|
|
347
|
-
}
|
|
348
|
-
const commandLabel = commandLabelForPackageManager(params.plan.packageManager);
|
|
349
|
-
const total = directTargets.length;
|
|
350
|
-
const spinner = createSpinner(`Applying direct package fixes with ${commandLabel}... 0/${total}`, params.options);
|
|
351
|
-
for (let i = 0; i < directTargets.length; i++) {
|
|
352
|
-
const target = directTargets[i];
|
|
353
|
-
const commandParts = buildFixCommandParts(params.plan.packageManager, [target]);
|
|
354
|
-
spinner.update(`Applying direct fix ${i + 1}/${total}: ${commandParts.join(" ")}`);
|
|
355
|
-
const run = await runInstallCommand(commandParts[0], commandParts.slice(1), params.projectPath);
|
|
356
|
-
if (run.error) {
|
|
357
|
-
spinner.fail("Failed to apply fixes");
|
|
358
|
-
throw new Error(`Failed to apply fixes: ${run.error.message}`);
|
|
359
|
-
}
|
|
360
|
-
if ((run.status ?? 1) !== 0) {
|
|
361
|
-
spinner.fail(`Fix command failed (${commandLabel})`);
|
|
362
|
-
throw new Error(`Fix command exited with status ${run.status ?? 1}`);
|
|
363
|
-
}
|
|
364
|
-
}
|
|
365
|
-
spinner.succeed(`Applied ${directTargets.length} direct package fix${directTargets.length === 1 ? "" : "es"} with ${commandLabel}`);
|
|
366
|
-
const skippedCount = transitiveTargets.length + skippedDirect.length;
|
|
367
|
-
return {
|
|
368
|
-
appliedFixCount: directTargets.length,
|
|
369
|
-
skippedCount,
|
|
370
|
-
skippedTransitiveCount: transitiveTargets.length,
|
|
371
|
-
skippedNoValidatedTargetCount: skippedDirect.length,
|
|
372
|
-
applied: directTargets.map(target => ({
|
|
373
|
-
package: target.package,
|
|
374
|
-
from: target.currentVersion ?? "unknown",
|
|
375
|
-
to: target.targetVersion,
|
|
376
|
-
})),
|
|
377
|
-
note: null,
|
|
378
|
-
};
|
|
379
|
-
}
|
|
380
|
-
function buildFixCommandParts(packageManager, targets) {
|
|
381
|
-
if (packageManager === "npm") {
|
|
382
|
-
return ["npm", "install", ...targets.map(target => `${target.package}@${target.targetVersion}`)];
|
|
383
|
-
}
|
|
384
|
-
if (packageManager === "pnpm") {
|
|
385
|
-
return ["pnpm", "add", ...targets.map(target => `${target.package}@${target.targetVersion}`)];
|
|
386
|
-
}
|
|
387
|
-
if (packageManager === "bun") {
|
|
388
|
-
return ["bun", "add", ...targets.map(target => `${target.package}@${target.targetVersion}`)];
|
|
389
|
-
}
|
|
390
|
-
return ["yarn", "add", ...targets.map(target => `${target.package}@${target.targetVersion}`)];
|
|
391
|
-
}
|
|
392
|
-
async function runInstallCommand(command, args, cwd) {
|
|
393
|
-
return await new Promise(resolve => {
|
|
394
|
-
const child = spawn(command, args, {
|
|
395
|
-
cwd,
|
|
396
|
-
stdio: ["ignore", "pipe", "pipe"],
|
|
397
|
-
});
|
|
398
|
-
child.stdout.on("data", () => { });
|
|
399
|
-
child.stderr.on("data", () => { });
|
|
400
|
-
child.on("error", error => {
|
|
401
|
-
resolve({ status: null, error });
|
|
402
|
-
});
|
|
403
|
-
child.on("close", code => {
|
|
404
|
-
resolve({ status: code, error: null });
|
|
405
|
-
});
|
|
406
|
-
});
|
|
407
|
-
}
|
|
408
|
-
function commandLabelForPackageManager(packageManager) {
|
|
409
|
-
if (packageManager === "npm")
|
|
410
|
-
return "npm install";
|
|
411
|
-
if (packageManager === "pnpm")
|
|
412
|
-
return "pnpm add";
|
|
413
|
-
if (packageManager === "bun")
|
|
414
|
-
return "bun add";
|
|
415
|
-
return "yarn add";
|
|
416
|
-
}
|
|
417
|
-
function countBySeverity(findings) {
|
|
418
|
-
const counts = {
|
|
419
|
-
none: 0,
|
|
420
|
-
low: 0,
|
|
421
|
-
medium: 0,
|
|
422
|
-
high: 0,
|
|
423
|
-
critical: 0,
|
|
424
|
-
unknown: 0,
|
|
425
|
-
};
|
|
426
|
-
for (const finding of findings) {
|
|
427
|
-
counts[finding.severity] += 1;
|
|
428
|
-
}
|
|
429
|
-
return counts;
|
|
430
|
-
}
|
|
431
|
-
function printFixModeSummary(params) {
|
|
432
|
-
const result = params.fixResult;
|
|
433
|
-
if (!result)
|
|
434
|
-
return;
|
|
435
|
-
if (result.note) {
|
|
436
|
-
console.log(chalk.gray(result.note));
|
|
437
|
-
}
|
|
438
|
-
if (result.applied.length > 0) {
|
|
439
|
-
console.log("");
|
|
440
|
-
console.log(chalk.bold.cyan("Applied fixes"));
|
|
441
|
-
for (const item of result.applied) {
|
|
442
|
-
console.log(`- ${chalk.white(item.package)}: ${chalk.gray(item.from)} ${chalk.cyan("->")} ${chalk.green(item.to)}`);
|
|
443
|
-
}
|
|
444
|
-
}
|
|
445
|
-
console.log("");
|
|
446
|
-
console.log(chalk.bold.cyan("Fix summary"));
|
|
447
|
-
console.log(`- Applied fixes: ${chalk.green(String(result.appliedFixCount))}`);
|
|
448
|
-
console.log(`- Skipped findings: ${chalk.yellow(String(result.skippedCount))}`);
|
|
449
|
-
if (result.skippedCount > 0) {
|
|
450
|
-
console.log(` - Transitive (v1 skip): ${chalk.yellow(String(result.skippedTransitiveCount))}`);
|
|
451
|
-
console.log(` - No validated direct target: ${chalk.yellow(String(result.skippedNoValidatedTargetCount))}`);
|
|
452
|
-
}
|
|
453
|
-
console.log(`- Findings before fix: ${chalk.white(String(params.findingsBeforeFix))}`);
|
|
454
|
-
console.log(`- Remaining findings after fix: ${chalk.white(String(params.findingsAfterFix))}`);
|
|
455
|
-
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))}`);
|
|
456
|
-
}
|
|
457
|
-
function readDirectDependencyNames(projectPath, prodOnly) {
|
|
458
|
-
const packageJsonPath = path.join(projectPath, "package.json");
|
|
459
|
-
if (!fs.existsSync(packageJsonPath)) {
|
|
460
|
-
return null;
|
|
461
|
-
}
|
|
462
|
-
try {
|
|
463
|
-
const directNames = new Set();
|
|
464
|
-
const rootManifest = readPackageJsonObject(packageJsonPath);
|
|
465
|
-
if (!rootManifest) {
|
|
466
|
-
return null;
|
|
467
|
-
}
|
|
468
|
-
addDependencyNamesFromManifest(directNames, rootManifest, prodOnly);
|
|
469
|
-
const workspacePatterns = readWorkspacePatterns(rootManifest);
|
|
470
|
-
for (const workspacePackageJsonPath of resolveWorkspacePackageJsonPaths(projectPath, workspacePatterns)) {
|
|
471
|
-
const workspaceManifest = readPackageJsonObject(workspacePackageJsonPath);
|
|
472
|
-
if (!workspaceManifest)
|
|
473
|
-
continue;
|
|
474
|
-
addDependencyNamesFromManifest(directNames, workspaceManifest, prodOnly);
|
|
475
|
-
}
|
|
476
|
-
return directNames;
|
|
477
|
-
}
|
|
478
|
-
catch {
|
|
479
|
-
return null;
|
|
480
|
-
}
|
|
481
|
-
}
|
|
482
|
-
function readPackageJsonObject(filePath) {
|
|
483
|
-
try {
|
|
484
|
-
const raw = JSON.parse(fs.readFileSync(filePath, "utf8"));
|
|
485
|
-
return raw && typeof raw === "object" ? raw : null;
|
|
486
|
-
}
|
|
487
|
-
catch {
|
|
488
|
-
return null;
|
|
489
|
-
}
|
|
490
|
-
}
|
|
491
|
-
function addDependencyNamesFromManifest(target, manifest, prodOnly) {
|
|
492
|
-
const sections = [
|
|
493
|
-
isRecord(manifest.dependencies) ? manifest.dependencies : undefined,
|
|
494
|
-
isRecord(manifest.optionalDependencies) ? manifest.optionalDependencies : undefined,
|
|
495
|
-
];
|
|
496
|
-
if (!prodOnly) {
|
|
497
|
-
sections.push(isRecord(manifest.devDependencies) ? manifest.devDependencies : undefined);
|
|
498
|
-
}
|
|
499
|
-
for (const section of sections) {
|
|
500
|
-
if (!section)
|
|
501
|
-
continue;
|
|
502
|
-
for (const name of Object.keys(section)) {
|
|
503
|
-
target.add(name);
|
|
504
|
-
}
|
|
505
|
-
}
|
|
506
|
-
}
|
|
507
|
-
function readWorkspacePatterns(manifest) {
|
|
508
|
-
const workspaces = manifest.workspaces;
|
|
509
|
-
if (Array.isArray(workspaces)) {
|
|
510
|
-
return workspaces.filter((value) => typeof value === "string");
|
|
511
|
-
}
|
|
512
|
-
if (isRecord(workspaces) && Array.isArray(workspaces.packages)) {
|
|
513
|
-
return workspaces.packages.filter((value) => typeof value === "string");
|
|
514
|
-
}
|
|
515
|
-
return [];
|
|
516
|
-
}
|
|
517
|
-
function resolveWorkspacePackageJsonPaths(projectPath, patterns) {
|
|
518
|
-
const matches = new Set();
|
|
519
|
-
for (const pattern of patterns) {
|
|
520
|
-
const normalized = pattern.replace(/\\/g, "/").replace(/\/+$/, "");
|
|
521
|
-
if (!normalized)
|
|
522
|
-
continue;
|
|
523
|
-
for (const relativeDir of expandWorkspacePattern(projectPath, normalized.split("/").filter(Boolean), "")) {
|
|
524
|
-
const packageJsonPath = path.join(projectPath, relativeDir, "package.json");
|
|
525
|
-
if (fs.existsSync(packageJsonPath)) {
|
|
526
|
-
matches.add(packageJsonPath);
|
|
527
|
-
}
|
|
528
|
-
}
|
|
529
|
-
}
|
|
530
|
-
return [...matches];
|
|
531
|
-
}
|
|
532
|
-
function expandWorkspacePattern(projectPath, segments, currentRelativePath) {
|
|
533
|
-
if (segments.length === 0) {
|
|
534
|
-
return currentRelativePath ? [currentRelativePath] : [];
|
|
535
|
-
}
|
|
536
|
-
const [segment, ...rest] = segments;
|
|
537
|
-
if (segment === "*") {
|
|
538
|
-
const baseDir = currentRelativePath ? path.join(projectPath, currentRelativePath) : projectPath;
|
|
539
|
-
let entries = [];
|
|
540
|
-
try {
|
|
541
|
-
entries = fs.readdirSync(baseDir, { withFileTypes: true });
|
|
542
|
-
}
|
|
543
|
-
catch {
|
|
544
|
-
return [];
|
|
545
|
-
}
|
|
546
|
-
return entries
|
|
547
|
-
.filter(entry => entry.isDirectory())
|
|
548
|
-
.flatMap(entry => {
|
|
549
|
-
const nextRelativePath = currentRelativePath
|
|
550
|
-
? path.join(currentRelativePath, entry.name)
|
|
551
|
-
: entry.name;
|
|
552
|
-
return expandWorkspacePattern(projectPath, rest, nextRelativePath);
|
|
553
|
-
});
|
|
554
|
-
}
|
|
555
|
-
const nextRelativePath = currentRelativePath ? path.join(currentRelativePath, segment) : segment;
|
|
556
|
-
const nextAbsolutePath = path.join(projectPath, nextRelativePath);
|
|
557
|
-
if (!fs.existsSync(nextAbsolutePath) || !fs.statSync(nextAbsolutePath).isDirectory()) {
|
|
558
|
-
return [];
|
|
559
|
-
}
|
|
560
|
-
return expandWorkspacePattern(projectPath, rest, nextRelativePath);
|
|
561
|
-
}
|
|
562
|
-
function isRecord(value) {
|
|
563
|
-
return !!value && typeof value === "object" && !Array.isArray(value);
|
|
564
|
-
}
|
|
565
|
-
function formatAdvisoryDbFreshness(lastSyncAt) {
|
|
566
|
-
if (!lastSyncAt) {
|
|
567
|
-
return chalk.yellow("unknown");
|
|
568
|
-
}
|
|
569
|
-
const timestamp = Date.parse(lastSyncAt);
|
|
570
|
-
if (Number.isNaN(timestamp)) {
|
|
571
|
-
return chalk.yellow("unknown");
|
|
572
|
-
}
|
|
573
|
-
return `${relativeAge(timestamp)} ${chalk.gray(`(${lastSyncAt})`)}`;
|
|
574
|
-
}
|
|
575
|
-
function relativeAge(timestamp) {
|
|
576
|
-
const deltaMs = Math.max(0, Date.now() - timestamp);
|
|
577
|
-
const minute = 60 * 1000;
|
|
578
|
-
const hour = 60 * minute;
|
|
579
|
-
const day = 24 * hour;
|
|
580
|
-
if (deltaMs < minute) {
|
|
581
|
-
return "just synced";
|
|
582
|
-
}
|
|
583
|
-
if (deltaMs < hour) {
|
|
584
|
-
const minutes = Math.floor(deltaMs / minute);
|
|
585
|
-
return `synced ${minutes} minute${minutes === 1 ? "" : "s"} ago`;
|
|
586
|
-
}
|
|
587
|
-
if (deltaMs < day) {
|
|
588
|
-
const hours = Math.floor(deltaMs / hour);
|
|
589
|
-
return `synced ${hours} hour${hours === 1 ? "" : "s"} ago`;
|
|
590
|
-
}
|
|
591
|
-
const days = Math.floor(deltaMs / day);
|
|
592
|
-
return `synced ${days} day${days === 1 ? "" : "s"} ago`;
|
|
593
|
-
}
|
|
@@ -5,6 +5,7 @@ import { loadCache } from "../osv/cache.js";
|
|
|
5
5
|
import { inferSeverity } from "../osv/severity.js";
|
|
6
6
|
import { getPrimaryParent } from "../utils/finding.js";
|
|
7
7
|
import { calculatePathCoverage, formatDependencyPath } from "../utils/path-coverage.js";
|
|
8
|
+
import { pluralize } from "../utils/string.js";
|
|
8
9
|
export function formatSeverityLabel(severity) {
|
|
9
10
|
const lower = severity.toLowerCase();
|
|
10
11
|
if (lower === "critical")
|
|
@@ -26,6 +27,13 @@ export function formatRelationshipLabel(value) {
|
|
|
26
27
|
return chalk.yellow(value);
|
|
27
28
|
return chalk.gray(value);
|
|
28
29
|
}
|
|
30
|
+
export function formatAdvisorySourceLine(sourceLabel) {
|
|
31
|
+
const match = sourceLabel.match(/^(.*) \((.*)\)$/);
|
|
32
|
+
if (!match) {
|
|
33
|
+
return sourceLabel;
|
|
34
|
+
}
|
|
35
|
+
return `${match[1]} (${chalk.cyan(match[2])})`;
|
|
36
|
+
}
|
|
29
37
|
// MAL-* is the OSV prefix for malicious code advisories
|
|
30
38
|
function isMaliciousAdvisory(finding) {
|
|
31
39
|
return finding.vulnerabilities.some(v => v.id.startsWith("MAL-"));
|
|
@@ -48,7 +56,7 @@ export function getRecommendedAction(finding) {
|
|
|
48
56
|
return `No known fix exists for ${finding.pkg.name}. Consider replacing it with an actively maintained alternative.`;
|
|
49
57
|
}
|
|
50
58
|
if (finding.recommendedNpmTransitiveRemediation?.kind === "update-parent-within-range") {
|
|
51
|
-
return
|
|
59
|
+
return `${finding.recommendedNpmTransitiveRemediation.package} already permits ${finding.pkg.name}@${finding.recommendedNpmTransitiveRemediation.targetChildVersion} — run the lockfile refresh command to pick it up.`;
|
|
52
60
|
}
|
|
53
61
|
if (finding.recommendedNpmTransitiveRemediation?.kind === "upgrade-parent-to-version" &&
|
|
54
62
|
finding.recommendedNpmTransitiveRemediation.targetVersion) {
|
|
@@ -131,7 +139,7 @@ function formatParentUpgradeAction(vulnerableName, vulnerableVersion, parentName
|
|
|
131
139
|
return `${upgrade} to resolve vulnerable ${vulnerableName}@${vulnerableVersion}${pathText}.`;
|
|
132
140
|
}
|
|
133
141
|
const remainingCount = coverage.remainingPaths.length;
|
|
134
|
-
return `${upgrade} to resolve the ${vulnerableName}@${vulnerableVersion} path${pathText}; run it, then rescan. ${remainingCount} other known
|
|
142
|
+
return `${upgrade} to resolve the ${vulnerableName}@${vulnerableVersion} path${pathText}; run it, then rescan. ${remainingCount} other known ${pluralize(remainingCount, "path")} may still need separate parent upgrades.`;
|
|
135
143
|
}
|
|
136
144
|
export function summarizeNextAction(finding) {
|
|
137
145
|
// Prefer the registry-validated target over the raw advisory hint so this
|
|
@@ -149,7 +157,7 @@ export function summarizeNextAction(finding) {
|
|
|
149
157
|
return `No known fix exists for ${finding.pkg.name}. Consider replacing it with an actively maintained alternative.`;
|
|
150
158
|
}
|
|
151
159
|
if (finding.recommendedNpmTransitiveRemediation?.kind === "update-parent-within-range") {
|
|
152
|
-
return `
|
|
160
|
+
return `Lockfile refresh — ${finding.recommendedNpmTransitiveRemediation.package} already permits a safe version.`;
|
|
153
161
|
}
|
|
154
162
|
if (finding.recommendedNpmTransitiveRemediation?.kind === "upgrade-parent-to-version" &&
|
|
155
163
|
finding.recommendedNpmTransitiveRemediation.targetVersion) {
|
|
@@ -204,9 +212,9 @@ export function printCacheSummary(cacheDirOverride, options) {
|
|
|
204
212
|
const totalCount = advisoryCount + emptyCount;
|
|
205
213
|
if (totalCount === 0 && packageQueryCount === 0)
|
|
206
214
|
return;
|
|
207
|
-
console.log(chalk.gray(`Cache: ${packageQueryCount} package match
|
|
215
|
+
console.log(chalk.gray(`Cache: ${packageQueryCount} package match ${pluralize(packageQueryCount, "record")}, ${advisoryCount} advisory detail ${pluralize(advisoryCount, "record")}`) +
|
|
208
216
|
(emptyCount > 0
|
|
209
|
-
? chalk.gray(`, ${emptyCount} empty
|
|
217
|
+
? chalk.gray(`, ${emptyCount} empty ${pluralize(emptyCount, "lookup")}`)
|
|
210
218
|
: ""));
|
|
211
219
|
}
|
|
212
220
|
export function logInfo(message, options) {
|
|
@@ -5,6 +5,7 @@ import { serializeFinding } from "./formatters.js";
|
|
|
5
5
|
import { LOGO_BASE64 } from "./logo-base64.js";
|
|
6
6
|
import { OWASP_LOGO_BASE64 } from "./owasp-logo-base64.js";
|
|
7
7
|
import { isMajorVersionBump } from "../utils/version.js";
|
|
8
|
+
import { pluralize } from "../utils/string.js";
|
|
8
9
|
export function buildReportData(params) {
|
|
9
10
|
return {
|
|
10
11
|
projectPath: params.projectPath,
|
|
@@ -490,11 +491,12 @@ function renderFixPlan(plan) {
|
|
|
490
491
|
const skippedCount = plan.skipped.length;
|
|
491
492
|
const commandRows = plan.sections.map(section => {
|
|
492
493
|
const targetRows = section.targets.map(t => {
|
|
494
|
+
const displayVersion = t.displayTargetVersion ?? t.targetVersion;
|
|
493
495
|
const isMajor = t.currentVersion ? isMajorVersionBump(t.currentVersion, t.targetVersion) : false;
|
|
494
496
|
const breakBadge = isMajor ? ` <span class="break-badge">⚠ breaking</span>` : "";
|
|
495
497
|
const versionHtml = t.currentVersion
|
|
496
|
-
? `<span class="fix-target-pkg">${escapeHtml(t.package)}@${escapeHtml(t.currentVersion)}</span><span class="fix-target-arrow">→</span><span class="fix-target-to">${escapeHtml(
|
|
497
|
-
: `<span class="fix-target-pkg">${escapeHtml(t.package)}</span><span class="fix-target-arrow">→</span><span class="fix-target-to">${escapeHtml(
|
|
498
|
+
? `<span class="fix-target-pkg">${escapeHtml(t.package)}@${escapeHtml(t.currentVersion)}</span><span class="fix-target-arrow">→</span><span class="fix-target-to">${escapeHtml(displayVersion)}</span>`
|
|
499
|
+
: `<span class="fix-target-pkg">${escapeHtml(t.package)}</span><span class="fix-target-arrow">→</span><span class="fix-target-to">${escapeHtml(displayVersion)}</span>`;
|
|
498
500
|
const statsHtml = t.scannedVersions != null
|
|
499
501
|
? ` <span class="fix-target-stats">${t.scannedVersions} scanned${t.knownVulnerableVersions != null ? ` · ${t.knownVulnerableVersions} still vulnerable` : ""}</span>`
|
|
500
502
|
: "";
|
|
@@ -502,7 +504,7 @@ function renderFixPlan(plan) {
|
|
|
502
504
|
? ` <span class="fix-target-note">${escapeHtml(t.adjustmentNote)}</span>`
|
|
503
505
|
: "";
|
|
504
506
|
const coverageHtml = t.coverage === "partial"
|
|
505
|
-
? ` <span class="fix-target-coverage">Path-specific remediation. Run this command, then rescan; ${t.remainingPaths?.length ?? 0} other known
|
|
507
|
+
? ` <span class="fix-target-coverage">Path-specific remediation. Run this command, then rescan; ${t.remainingPaths?.length ?? 0} other known ${pluralize(t.remainingPaths?.length ?? 0, "path")} may still need separate parent upgrades.</span>`
|
|
506
508
|
: "";
|
|
507
509
|
return `<div class="fix-target-row">${versionHtml}${breakBadge}${statsHtml}${noteHtml}${coverageHtml}</div>`;
|
|
508
510
|
}).join("\n");
|
|
@@ -530,13 +532,17 @@ function renderFixPlan(plan) {
|
|
|
530
532
|
const skippedBadgePart = skippedCount > 0
|
|
531
533
|
? ` · <button class="skipped-toggle" onclick="toggleSkipped()">↓ ${skippedCount} skipped</button>`
|
|
532
534
|
: "";
|
|
535
|
+
const coverageText = plan.coveredFindingCount === plan.totalFindingCount
|
|
536
|
+
? `Running all commands should fix all ${plan.totalFindingCount} findings.`
|
|
537
|
+
: `Running all commands should fix <strong>${plan.coveredFindingCount}</strong> of <strong>${plan.totalFindingCount}</strong> findings.`;
|
|
533
538
|
return `<div class="fix-plan">
|
|
534
539
|
<div class="fix-plan-header">
|
|
535
540
|
<h2><span class="icon">✦</span> Suggested Fix Plan</h2>
|
|
536
|
-
<span class="badge">${directCount} direct
|
|
541
|
+
<span class="badge">${directCount} direct ${pluralize(directCount, "fix", "fixes")}${skippedBadgePart}</span>
|
|
537
542
|
</div>
|
|
538
543
|
<div class="fix-commands">${commandRows}
|
|
539
544
|
</div>${skippedSection}
|
|
545
|
+
<div style="padding:10px 18px;border-top:1px solid #21262d;font-size:11px;color:#8b949e">${coverageText}</div>
|
|
540
546
|
</div>`;
|
|
541
547
|
}
|
|
542
548
|
export async function writeHtmlReport(params) {
|
package/dist/output/printers.js
CHANGED
|
@@ -3,6 +3,7 @@ import { buildSuggestedFixCommandPlan } from "../remediation/fix-commands.js";
|
|
|
3
3
|
import { isMajorVersionBump } from "../utils/version.js";
|
|
4
4
|
import { getPrimaryParent } from "../utils/finding.js";
|
|
5
5
|
import { countUniqueAdvisories, formatSeverityLabel, formatRelationshipLabel } from "./formatters.js";
|
|
6
|
+
import { pluralize } from "../utils/string.js";
|
|
6
7
|
export function printSummary(findings, packageCount, scanInput) {
|
|
7
8
|
if (findings.length === 0) {
|
|
8
9
|
if (scanInput.mode === "manifest-fallback") {
|
|
@@ -36,13 +37,13 @@ export function printActionSummary(findings) {
|
|
|
36
37
|
const fixable = findings.filter(f => Boolean(f.firstFixedVersion)).length;
|
|
37
38
|
console.log("");
|
|
38
39
|
console.log(chalk.bold.cyan("Quick take"));
|
|
39
|
-
console.log(`- ${chalk.green(String(direct))} vulnerable
|
|
40
|
-
console.log(`- ${chalk.yellow(String(transitive))}
|
|
40
|
+
console.log(`- ${chalk.green(String(direct))} vulnerable ${pluralize(direct, "package")} look directly fixable in this project.`);
|
|
41
|
+
console.log(`- ${chalk.yellow(String(transitive))} ${pluralize(transitive, "issue")} come through other dependencies.`);
|
|
41
42
|
if (unknown > 0) {
|
|
42
|
-
console.log(`- ${chalk.magenta(String(unknown))}
|
|
43
|
+
console.log(`- ${chalk.magenta(String(unknown))} ${pluralize(unknown, "package")} could not be clearly classified as direct or transitive.`);
|
|
43
44
|
}
|
|
44
|
-
console.log(`- ${chalk.blueBright(String(uniqueAdvisories))}
|
|
45
|
-
console.log(`- ${chalk.blue(String(fixable))}
|
|
45
|
+
console.log(`- ${chalk.blueBright(String(uniqueAdvisories))} ${pluralize(uniqueAdvisories, "CVE")} matched overall.`);
|
|
46
|
+
console.log(`- ${chalk.blue(String(fixable))} ${pluralize(fixable, "package")} include a fixed-version hint from OSV.`);
|
|
46
47
|
}
|
|
47
48
|
export function printSuggestedFixCommands(findings, scanInput, options) {
|
|
48
49
|
const plan = buildSuggestedFixCommandPlan(findings, scanInput, options);
|
|
@@ -89,6 +90,13 @@ export function printSuggestedFixCommands(findings, scanInput, options) {
|
|
|
89
90
|
}
|
|
90
91
|
console.log(renderCommandCallout(section.command));
|
|
91
92
|
}
|
|
93
|
+
if (plan.coveredFindingCount > 0) {
|
|
94
|
+
console.log("");
|
|
95
|
+
const coverage = plan.coveredFindingCount === plan.totalFindingCount
|
|
96
|
+
? chalk.gray(`Running all commands above should fix all ${plan.totalFindingCount} findings.`)
|
|
97
|
+
: chalk.gray(`Running all commands above should fix ${chalk.white(String(plan.coveredFindingCount))} of ${chalk.white(String(plan.totalFindingCount))} findings.`);
|
|
98
|
+
console.log(coverage);
|
|
99
|
+
}
|
|
92
100
|
}
|
|
93
101
|
export function printSuggestedFixCommandSkips(findings, scanInput, options) {
|
|
94
102
|
const plan = buildSuggestedFixCommandPlan(findings, scanInput, options);
|
|
@@ -211,10 +219,10 @@ export function printFinalStatus(findings) {
|
|
|
211
219
|
const criticalCount = findings.filter(f => f.severity === "critical").length;
|
|
212
220
|
const highCount = findings.filter(f => f.severity === "high").length;
|
|
213
221
|
if (criticalCount > 0 || highCount > 0) {
|
|
214
|
-
console.log(chalk.redBright(`✖ Scan complete. ${findings.length}
|
|
222
|
+
console.log(chalk.redBright(`✖ Scan complete. ${findings.length} ${pluralize(findings.length, "issue")} found (${criticalCount} critical, ${highCount} high). Start with the priority fixes above.`));
|
|
215
223
|
return;
|
|
216
224
|
}
|
|
217
|
-
console.log(chalk.yellow(`▲ Scan complete. ${findings.length}
|
|
225
|
+
console.log(chalk.yellow(`▲ Scan complete. ${findings.length} ${pluralize(findings.length, "issue")} found. Review the suggested fix plan above.`));
|
|
218
226
|
}
|
|
219
227
|
function renderRow(cells, widths) {
|
|
220
228
|
const formatted = cells.map((cell, i) => {
|
|
@@ -289,7 +297,7 @@ export function printCompactOutput(findings, scanInput, options) {
|
|
|
289
297
|
let usageContext = "";
|
|
290
298
|
if (finding.usage) {
|
|
291
299
|
if (finding.usage.imported) {
|
|
292
|
-
usageContext = chalk.red(` (imported in ${finding.usage.files.length}
|
|
300
|
+
usageContext = chalk.red(` (imported in ${finding.usage.files.length} ${pluralize(finding.usage.files.length, "file")})`);
|
|
293
301
|
}
|
|
294
302
|
else {
|
|
295
303
|
usageContext = chalk.green(` (no direct import found)`);
|
|
@@ -305,7 +313,7 @@ export function printCompactOutput(findings, scanInput, options) {
|
|
|
305
313
|
console.log(` ${chalk.red(`⚠ Malicious: ${action}`)}`);
|
|
306
314
|
}
|
|
307
315
|
else if (finding.recommendedNpmTransitiveRemediation?.kind === "update-parent-within-range") {
|
|
308
|
-
console.log(` ${chalk.gray(`Fix:
|
|
316
|
+
console.log(` ${chalk.gray(`Fix: lockfile refresh — ${finding.recommendedNpmTransitiveRemediation.package} already permits a safe version`)}`);
|
|
309
317
|
}
|
|
310
318
|
else if (finding.recommendedParentUpgrade) {
|
|
311
319
|
console.log(` ${chalk.gray(`Fix: upgrade ${finding.recommendedParentUpgrade.package} to ${finding.recommendedParentUpgrade.targetVersion}`)}`);
|
|
@@ -349,7 +357,7 @@ export function printCompactOutput(findings, scanInput, options) {
|
|
|
349
357
|
console.log(formatFixCommandSummary(plan));
|
|
350
358
|
const compactValidationSummary = summarizeAdjustedValidation(plan.targets);
|
|
351
359
|
if (compactValidationSummary.checked > 0) {
|
|
352
|
-
console.log(chalk.gray(`Validation: scanned ${compactValidationSummary.checked} package
|
|
360
|
+
console.log(chalk.gray(`Validation: scanned ${compactValidationSummary.checked} package ${pluralize(compactValidationSummary.checked, "version")}; ${compactValidationSummary.vulnerable} ${pluralize(compactValidationSummary.vulnerable, "is", "are")} still known vulnerable.`));
|
|
353
361
|
}
|
|
354
362
|
console.log("");
|
|
355
363
|
for (const section of plan.sections.slice(0, 3)) {
|
|
@@ -420,10 +428,10 @@ export function printCompactOutput(findings, scanInput, options) {
|
|
|
420
428
|
// Footer
|
|
421
429
|
const urgentCount = counts.critical + counts.high;
|
|
422
430
|
if (urgentCount > 0) {
|
|
423
|
-
console.log(chalk.redBright(`✖ Scan complete. ${urgentCount} urgent
|
|
431
|
+
console.log(chalk.redBright(`✖ Scan complete. ${urgentCount} urgent ${pluralize(urgentCount, "issue")} found.`));
|
|
424
432
|
}
|
|
425
433
|
else {
|
|
426
|
-
console.log(chalk.yellow(`▲ Scan complete. ${findings.length}
|
|
434
|
+
console.log(chalk.yellow(`▲ Scan complete. ${findings.length} ${pluralize(findings.length, "issue")} found.`));
|
|
427
435
|
}
|
|
428
436
|
if (!options?.all) {
|
|
429
437
|
console.log(chalk.gray(`Run with ${chalk.whiteBright("--verbose")} for fix plan, paths, and full table.`));
|