cve-lite-cli 1.34.0 → 1.35.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/dist/cli/advisories-init.js +13 -0
  2. package/dist/cli/advisories-sync.js +30 -0
  3. package/dist/cli/config-command.js +15 -0
  4. package/dist/cli/config.js +29 -0
  5. package/dist/cli/help.js +4 -4
  6. package/dist/cli/overrides.js +10 -1
  7. package/dist/constants.js +52 -0
  8. package/dist/index.js +25 -719
  9. package/dist/output/cyclonedx.js +12 -0
  10. package/dist/output/html-reporter.js +73 -38
  11. package/dist/output/multi-folder-html-reporter.js +16 -10
  12. package/dist/output/multi-folder-printer.js +1 -1
  13. package/dist/output/override-findings-sarif.js +1 -0
  14. package/dist/output/printers.js +427 -270
  15. package/dist/output/sarif.js +17 -1
  16. package/dist/output/sbom-dependency-edges.js +29 -19
  17. package/dist/overrides/admitted-scan.js +158 -0
  18. package/dist/overrides/api.js +16 -0
  19. package/dist/overrides/context-builder.js +4 -0
  20. package/dist/overrides/context.js +8 -1
  21. package/dist/overrides/detectors/index.js +2 -0
  22. package/dist/overrides/detectors/oa010-vulnerable-floor.js +123 -0
  23. package/dist/overrides/parsing/registry.js +53 -0
  24. package/dist/parsers/bun-lock-graph.js +182 -0
  25. package/dist/parsers/bun-lock.js +93 -132
  26. package/dist/parsers/index.js +75 -149
  27. package/dist/parsers/multi-package.js +5 -6
  28. package/dist/parsers/pnpm-lock-graph.js +94 -0
  29. package/dist/parsers/pnpm-lock.js +5 -5
  30. package/dist/parsers/yarn-lock-graph.js +148 -0
  31. package/dist/parsers/yarn-lock.js +3 -3
  32. package/dist/remediation/fix-commands.js +48 -7
  33. package/dist/scan/completeness.js +1 -1
  34. package/dist/scan/single-scan.js +643 -0
  35. package/dist/utils/file.js +11 -14
  36. package/dist/utils/version.js +10 -0
  37. package/package.json +1 -1
@@ -0,0 +1,643 @@
1
+ import path from "node:path";
2
+ import { loadPackages, buildNoPackagesMessage } from "../parsers/index.js";
3
+ import { scanPackages, buildCoverageNotes, createAdvisorySource } from "../scanner.js";
4
+ import { normalizeSeverity } from "../osv/severity.js";
5
+ import { OVERRIDES_COMMAND } from "../constants.js";
6
+ import { chalk } from "../utils/chalk.js";
7
+ import { buildSuggestedFixCommandPlan } from "../remediation/fix-commands.js";
8
+ import { scanProjectForPackageUsage } from "../usage/scanner.js";
9
+ import { offlineDbSyncHint } from "../utils/network.js";
10
+ import { formatAdvisoryDbFreshness } from "../utils/time.js";
11
+ import { pluralize } from "../utils/string.js";
12
+ import { EXIT_ERROR } from "../types.js";
13
+ import { formatAdvisorySourceLine, logInfo, logWarn, printCacheSummary, sortFindingsForOutput, } from "../output/formatters.js";
14
+ import { countBySeverity, reachesFailOn } from "../utils/severity.js";
15
+ import { buildReportData, writeHtmlReport } from "../output/html-reporter.js";
16
+ import { writeOutputs } from "../output/write-outputs.js";
17
+ import { selectFindingsForTable } from "../output/finding-display.js";
18
+ import { printActionSummary, printCompactOutput, printCoverage, printFinalStatus, printOverrideHint, printSkippedDependencies, printSuggestedFixCommands, printSuggestedFixCommandSkips, printSummary, printTable, } from "../output/printers.js";
19
+ import { renderOverrideFindings } from "../output/override-findings-terminal.js";
20
+ import { detectDM001 } from "../maintenance/dm001-maintenance-risk.js";
21
+ import { renderMaintenanceFindings } from "../output/maintenance-terminal.js";
22
+ import { detectLicenseIssues } from "../licenses/license-check.js";
23
+ import { renderLicenseFindings } from "../output/license-terminal.js";
24
+ import { readDirectDependencyNames, hasOverrideEntries } from "../utils/package-json.js";
25
+ import { applyFixesIfRequested, printFixModeSummary, writeFixResultJson, } from "../utils/fix-runner.js";
26
+ import { audit, buildOverrideContext } from "../overrides/index.js";
27
+ import { collectAdvisoryIdsForPackage, createPullRequestForFixes, } from "../utils/create-pr.js";
28
+ import { readBaseline, writeBaseline, filterNewFindings, ratchetOutcome } from "../utils/baseline.js";
29
+ import { formatDiagnosticMessage, getCompletenessImpact, shouldFailForIncompleteScan } from "./completeness.js";
30
+ export async function handleSingleFolderScan(params) {
31
+ const { projectPath, projectArg, batchSize, searchDepth, options, debugLog, fetchImpl, auditLog, scanStartedAt, cliVersion, } = params;
32
+ let advisorySourceLine = "";
33
+ let advisoryDbFreshnessLine = null;
34
+ let advisoryDbWarning = null;
35
+ try {
36
+ const advisorySource = createAdvisorySource({
37
+ osvUrl: options.osvUrl,
38
+ offline: options.offline,
39
+ offlineDb: options.offlineDb,
40
+ debugLog,
41
+ fetchImpl,
42
+ });
43
+ advisorySourceLine = advisorySource.sourceLabel;
44
+ debugLog("Advisory source", {
45
+ mode: advisorySource.offline ? "offline" : "online",
46
+ url: options.osvUrl ?? (advisorySource.offline ? null : "https://api.osv.dev"),
47
+ label: advisorySourceLine,
48
+ });
49
+ if (advisorySource.offline) {
50
+ const metadata = advisorySource.advisoryDbMetadata;
51
+ advisoryDbFreshnessLine = formatAdvisoryDbFreshness(metadata?.lastSyncAt ?? null);
52
+ if (advisorySource.advisoryDbIsStale) {
53
+ advisoryDbWarning = metadata?.lastSyncAt
54
+ ? "The local advisory DB appears stale. Re-run `cve-lite advisories sync` to refresh it."
55
+ : "The local advisory DB has no recorded sync timestamp. Re-run `cve-lite advisories sync` to refresh it.";
56
+ }
57
+ }
58
+ advisorySource.cleanup();
59
+ }
60
+ catch (error) {
61
+ if (options.offline || options.offlineDb) {
62
+ const reason = error instanceof Error ? error.message : String(error);
63
+ throw new Error(`Offline advisory database is not available: ${reason}\n${offlineDbSyncHint(options.offlineDb).join("\n")}`);
64
+ }
65
+ throw error;
66
+ }
67
+ if (!options.json && !options.ratchet) {
68
+ if (options.offline || options.offlineDb) {
69
+ console.log(chalk.gray("Offline mode:") + " " + chalk.yellow("enabled") + " " + chalk.gray("(no external advisory calls will be made)"));
70
+ }
71
+ if (advisorySourceLine) {
72
+ console.log(`${chalk.gray("Advisory source:")} ${formatAdvisorySourceLine(advisorySourceLine)}`);
73
+ }
74
+ if (advisoryDbFreshnessLine) {
75
+ console.log(`${chalk.gray("Advisory DB freshness:")} ${advisoryDbFreshnessLine}`);
76
+ }
77
+ }
78
+ if (advisoryDbWarning) {
79
+ logWarn(advisoryDbWarning, options);
80
+ }
81
+ let scanInput = loadPackages(projectPath, !!options.prodOnly, searchDepth);
82
+ let packages = scanInput.packages;
83
+ if (scanInput.filePath) {
84
+ debugLog("Lockfile selected", {
85
+ source: scanInput.source,
86
+ path: scanInput.filePath,
87
+ });
88
+ }
89
+ debugLog("Packages parsed", {
90
+ count: packages.length,
91
+ source: scanInput.source,
92
+ });
93
+ // Emit scan.started event after loading packages
94
+ const scanStartTime = Date.now();
95
+ auditLog.emit({
96
+ ts: new Date().toISOString(),
97
+ type: "scan.started",
98
+ schemaVersion: 1,
99
+ projectPath,
100
+ mode: scanInput.mode,
101
+ source: scanInput.source,
102
+ flags: {
103
+ fix: options.fix === true,
104
+ json: options.json === true,
105
+ prodOnly: options.prodOnly === true,
106
+ offline: options.offline === true,
107
+ checkOverrides: options.checkOverrides === true,
108
+ },
109
+ });
110
+ if (!options.ratchet) {
111
+ logInfo(`Parsed ${packages.length} ${pluralize(packages.length, "package")} from ${scanInput.source}${scanInput.filePath ? ` (${path.relative(projectPath, scanInput.filePath) || path.basename(scanInput.filePath)})` : ""}`, options);
112
+ printCacheSummary(options.cacheDir, options);
113
+ }
114
+ if (scanInput.warnings.length > 0) {
115
+ for (const warning of scanInput.warnings) {
116
+ logWarn(warning, options);
117
+ }
118
+ }
119
+ if (packages.length === 0) {
120
+ debugLog("Scan skipped", { reason: "no packages found", projectPath });
121
+ logWarn(buildNoPackagesMessage(projectPath), options);
122
+ auditLog.emit({
123
+ ts: new Date().toISOString(),
124
+ type: "scan.finished",
125
+ schemaVersion: 1,
126
+ durationMs: Date.now() - scanStartTime,
127
+ findingsCount: 0,
128
+ exitCode: 0,
129
+ });
130
+ return 0;
131
+ }
132
+ if (!options.json && !options.ratchet)
133
+ console.log();
134
+ let scanState = await scanProject({
135
+ scanInput,
136
+ batchSize,
137
+ options,
138
+ projectPath,
139
+ debugLog,
140
+ fetchImpl,
141
+ });
142
+ const findingsBeforeFixList = scanState.sorted;
143
+ const findingsBeforeFix = findingsBeforeFixList.length;
144
+ let fixResult = null;
145
+ let baseline = readBaseline(projectArg ?? ".");
146
+ let suppressedCount = 0;
147
+ // Collect override findings if --check-overrides is set.
148
+ // Boundary: override hygiene is independent of the CVE ratchet/baseline. The
149
+ // baseline only ever records CVE findings (see src/utils/baseline.ts), so a
150
+ // --ratchet run skips the override audit entirely - override findings are never
151
+ // baselined or suppressed.
152
+ let overrideFindings = [];
153
+ if (options.checkOverrides && !options.ratchet) {
154
+ const overrideCtx = buildOverrideContext(projectPath, {
155
+ auditLog,
156
+ logger: {
157
+ info: (msg) => debugLog("oa.info", { message: msg }),
158
+ warn: (msg) => debugLog("oa.warn", { message: msg }),
159
+ error: (msg) => debugLog("oa.error", { message: msg }),
160
+ debug: (msg) => debugLog("oa.debug", { message: msg }),
161
+ },
162
+ checkNetwork: !!options.checkNetwork,
163
+ });
164
+ const auditResult = await audit(overrideCtx, { checkNetwork: !!options.checkNetwork });
165
+ overrideFindings = auditResult.findings;
166
+ }
167
+ let maintenanceFindings = [];
168
+ let licenseFindings = [];
169
+ let licenseLimitedToDirectOnly = false;
170
+ // Emit cve.detected for each CVE finding
171
+ for (const f of scanState.sorted) {
172
+ auditLog.emit({
173
+ ts: new Date().toISOString(),
174
+ type: "cve.detected",
175
+ schemaVersion: 1,
176
+ package: { name: f.pkg.name, version: f.pkg.version },
177
+ severity: f.severity,
178
+ cveAliases: f.cveAliases,
179
+ vulnerabilityIds: f.vulnerabilities.map((v) => v.id),
180
+ });
181
+ }
182
+ if (options.fix) {
183
+ fixResult = await applyFixesIfRequested({
184
+ plan: scanState.suggestedFixCommands,
185
+ projectPath,
186
+ totalFindings: scanState.sorted.length,
187
+ options,
188
+ debugLog,
189
+ });
190
+ if (fixResult.appliedFixCount > 0) {
191
+ console.log(`${chalk.cyan("⠋")} ${chalk.gray("Rescanning project...")}`);
192
+ scanInput = loadPackages(projectPath, !!options.prodOnly, searchDepth);
193
+ packages = scanInput.packages;
194
+ if (packages.length === 0) {
195
+ debugLog("Scan skipped", { reason: "no packages found after fix rescan", projectPath });
196
+ logWarn(buildNoPackagesMessage(projectPath), options);
197
+ auditLog.emit({
198
+ ts: new Date().toISOString(),
199
+ type: "scan.finished",
200
+ schemaVersion: 1,
201
+ durationMs: Date.now() - scanStartTime,
202
+ findingsCount: 0,
203
+ exitCode: 0,
204
+ });
205
+ return 0;
206
+ }
207
+ scanState = await scanProject({
208
+ scanInput,
209
+ batchSize,
210
+ options,
211
+ projectPath,
212
+ debugLog,
213
+ fetchImpl,
214
+ });
215
+ }
216
+ }
217
+ let overridesFixHookResult = null;
218
+ // Override hygiene is opt-in. Only run the fix hook (which can patch
219
+ // package.json) when --check-overrides was requested, so `cve-lite . --fix`
220
+ // stays a pure CVE operation and never touches overrides unasked.
221
+ if (options.fix && fixResult && options.checkOverrides) {
222
+ const { runOverridesFixHook } = await import("../cli/fix-overrides-hook.js");
223
+ const projectPathResolved = path.resolve(projectArg ?? ".");
224
+ // Collect CVE-touched targets from cve-lite's fix result.
225
+ const cveFixTargets = fixResult.applied.map((entry) => ({
226
+ name: entry.package,
227
+ version: entry.to,
228
+ }));
229
+ // Create a simple logger adapter if needed
230
+ const hookLogger = {
231
+ info: (msg) => debugLog("hook.info", { message: msg }),
232
+ warn: (msg) => debugLog("hook.warn", { message: msg }),
233
+ error: (msg) => debugLog("hook.error", { message: msg }),
234
+ debug: (msg) => debugLog("hook.debug", { message: msg }),
235
+ };
236
+ overridesFixHookResult = await runOverridesFixHook({
237
+ projectPath: projectPathResolved,
238
+ auditLog,
239
+ logger: hookLogger,
240
+ cveFixTargets,
241
+ });
242
+ if (!overridesFixHookResult.verifyOk) {
243
+ debugLog("overrides-fix-hook verify failed", {
244
+ failures: overridesFixHookResult.verifyFailures,
245
+ });
246
+ console.log(chalk.red(`Overrides fix verify failed:\n${overridesFixHookResult.verifyFailures
247
+ .map((v) => ` ${v.ruleId} ${v.package}: ${v.reason}`)
248
+ .join("\n")}`));
249
+ auditLog.emit({
250
+ ts: new Date().toISOString(),
251
+ type: "scan.finished",
252
+ schemaVersion: 1,
253
+ durationMs: Date.now() - scanStartTime,
254
+ findingsCount: scanState.sorted.length + overrideFindings.length,
255
+ exitCode: 2,
256
+ });
257
+ return 2;
258
+ }
259
+ }
260
+ // Emit cve.fix.applied for each target in the fix plan
261
+ if (scanState.suggestedFixCommands?.targets) {
262
+ for (const target of scanState.suggestedFixCommands.targets) {
263
+ auditLog.emit({
264
+ ts: new Date().toISOString(),
265
+ type: "cve.fix.applied",
266
+ schemaVersion: 1,
267
+ package: target.package,
268
+ fromVersion: target.currentVersion ?? "unknown",
269
+ toVersion: target.targetVersion,
270
+ mechanism: target.kind,
271
+ });
272
+ }
273
+ }
274
+ if (options.fix) {
275
+ printFixModeSummary({
276
+ fixResult,
277
+ findingsBeforeFix,
278
+ findingsAfterFix: scanState.sorted.length,
279
+ remainingBySeverity: countBySeverity(scanState.sorted),
280
+ });
281
+ // Write fix result JSON for Action-level PR creation.
282
+ // Written even when appliedFixCount is 0 so the Action can detect
283
+ // the nothing-to-fix case without parsing stdout.
284
+ const fixResultJson = {
285
+ appliedFixCount: fixResult?.appliedFixCount ?? 0,
286
+ appliedWithinRangeRefreshCount: fixResult?.appliedWithinRangeRefreshCount ?? 0,
287
+ findingsBeforeFix,
288
+ findingsAfterFix: scanState.sorted.length,
289
+ applied: (fixResult?.applied ?? []).map(entry => ({
290
+ package: entry.package,
291
+ from: entry.from,
292
+ to: entry.to,
293
+ advisories: collectAdvisoryIdsForPackage(findingsBeforeFixList, entry.package),
294
+ })),
295
+ notAutoApplied: {
296
+ parentUpgradeCount: fixResult?.parentUpgradeCount ?? 0,
297
+ breakingUpgradeCount: fixResult?.breakingUpgradeCount ?? 0,
298
+ noFixCount: fixResult?.noFixCount ?? 0,
299
+ },
300
+ };
301
+ writeFixResultJson(fixResultJson, projectPath);
302
+ if (options.createPr && fixResult) {
303
+ // Override hygiene fixes also land in package.json (staged by create-pr), so
304
+ // a PR is warranted when either CVE fixes or override fixes were applied.
305
+ const overrideFixCount = overridesFixHookResult?.applied ?? 0;
306
+ if (fixResult.appliedFixCount === 0 && overrideFixCount === 0) {
307
+ logWarn("Skipping pull request creation: no direct fixes were applied.", options);
308
+ }
309
+ else {
310
+ console.log("");
311
+ console.log(chalk.bold.cyan("Creating pull request (--create-pr)"));
312
+ const prResult = await createPullRequestForFixes({
313
+ projectPath,
314
+ baseBranch: options.prBase ?? "main",
315
+ fixResult,
316
+ findingsBeforeFix: findingsBeforeFixList,
317
+ findingsAfterFix: scanState.sorted,
318
+ overrideFixCount,
319
+ });
320
+ if (prResult.skipped) {
321
+ logWarn(prResult.skipReason ?? "Pull request was not created.", options);
322
+ }
323
+ else if (prResult.prUrl) {
324
+ console.log(`${chalk.gray("Pull request:")} ${chalk.cyan(prResult.prUrl)}`);
325
+ console.log(`${chalk.gray("Branch:")} ${chalk.cyan(prResult.branchName)}`);
326
+ }
327
+ else {
328
+ logWarn(`Branch ${prResult.branchName} was pushed, but no pull request URL was returned.`, options);
329
+ }
330
+ }
331
+ }
332
+ }
333
+ else {
334
+ // --ratchet: with no baseline yet, save the current findings. With an
335
+ // existing baseline, GATE instead of re-saving - fail on findings not in the
336
+ // baseline. Re-saving here would silently absorb a new vulnerability into a
337
+ // fresh baseline, so a ratcheted CI job could never fail on a regression.
338
+ if (options.ratchet) {
339
+ const { hasDetectionGap } = getCompletenessImpact(scanState.completeness);
340
+ if (hasDetectionGap) {
341
+ console.log(chalk.red("Scan data is incomplete. Refusing to create or evaluate a baseline from partial detection data."));
342
+ for (const diagnostic of scanState.completeness.diagnostics) {
343
+ if (diagnostic.impact !== "detection")
344
+ continue;
345
+ console.log(chalk.red(` ${formatDiagnosticMessage(diagnostic.code, diagnostic.count, diagnostic.affectedPackageCount)}`));
346
+ }
347
+ auditLog.emit({
348
+ ts: new Date().toISOString(),
349
+ type: "scan.finished",
350
+ schemaVersion: 1,
351
+ durationMs: Date.now() - scanStartTime,
352
+ findingsCount: scanState.sorted.length,
353
+ exitCode: EXIT_ERROR,
354
+ });
355
+ return EXIT_ERROR;
356
+ }
357
+ const outcome = ratchetOutcome(baseline, scanState.sorted);
358
+ if (outcome.action === "save") {
359
+ writeBaseline(projectArg ?? ".", scanState.sorted);
360
+ const count = scanState.sorted.length;
361
+ console.log(chalk.green(`✓ Baseline saved to .cve-lite/baseline.json with ${count} ${count === 1 ? "finding" : "findings"}. Future scans will only report findings above this baseline.`));
362
+ if (options.checkOverrides) {
363
+ console.log(chalk.gray(`Note: override hygiene (--check-overrides) is not part of the ratchet baseline; run \`${OVERRIDES_COMMAND}\` to audit overrides.`));
364
+ }
365
+ auditLog.emit({
366
+ ts: new Date().toISOString(),
367
+ type: "scan.finished",
368
+ schemaVersion: 1,
369
+ durationMs: Date.now() - scanStartTime,
370
+ findingsCount: scanState.sorted.length,
371
+ exitCode: 0,
372
+ });
373
+ return 0;
374
+ }
375
+ const { newFindings, suppressedCount: sc } = outcome;
376
+ const suppressedLabel = `${sc} existing ${sc === 1 ? "finding" : "findings"} suppressed`;
377
+ if (newFindings.length === 0) {
378
+ console.log(chalk.green(`No new findings above baseline - ${suppressedLabel}`));
379
+ auditLog.emit({
380
+ ts: new Date().toISOString(),
381
+ type: "scan.finished",
382
+ schemaVersion: 1,
383
+ durationMs: Date.now() - scanStartTime,
384
+ findingsCount: scanState.sorted.length,
385
+ exitCode: 0,
386
+ });
387
+ return 0;
388
+ }
389
+ console.log(chalk.red(`${newFindings.length} new ${newFindings.length === 1 ? "finding" : "findings"} above baseline - ${suppressedLabel}`));
390
+ for (const f of newFindings) {
391
+ const ids = f.vulnerabilities.map(v => v.id).join(", ");
392
+ console.log(` ${chalk.yellow(f.severity)} ${f.pkg.name}@${f.pkg.version}${ids ? ` (${ids})` : ""}`);
393
+ }
394
+ console.log(chalk.gray("To accept these, re-baseline intentionally by deleting .cve-lite/baseline.json and re-running --ratchet."));
395
+ auditLog.emit({
396
+ ts: new Date().toISOString(),
397
+ type: "scan.finished",
398
+ schemaVersion: 1,
399
+ durationMs: Date.now() - scanStartTime,
400
+ findingsCount: newFindings.length,
401
+ exitCode: 1,
402
+ });
403
+ return 1;
404
+ }
405
+ // auto-apply baseline if it exists - filter before output
406
+ if (baseline) {
407
+ const filtered = filterNewFindings(scanState.sorted, baseline);
408
+ scanState.sorted = filtered.newFindings;
409
+ scanState.tableFindings = scanState.tableFindings.filter(f => filtered.newFindings.some(nf => nf.pkg.name === f.pkg.name && nf.pkg.version === f.pkg.version));
410
+ suppressedCount = filtered.suppressedCount;
411
+ }
412
+ // Maintenance risk findings are derived from CVE findings (via
413
+ // recommendedParentUpgrade), so they must be computed from the same
414
+ // baseline-filtered set everything below uses (JSON, rendering,
415
+ // --fail-on). Computing this earlier - before the baseline filter above -
416
+ // let a DM001 finding on an already-baselined CVE keep failing
417
+ // --fail-on forever, even as printFinalStatus reported a clean scan.
418
+ // This point is unreached in --ratchet mode (which always returns above),
419
+ // so packument fetches never run wastefully there.
420
+ if (options.checkMaintenance) {
421
+ const directNames = readDirectDependencyNames(projectPath, !!options.prodOnly);
422
+ const directDependencies = scanState.allPackages.filter(p => directNames?.has(p.name));
423
+ maintenanceFindings = await detectDM001(scanState.sorted, directDependencies, !!options.offline || !!options.offlineDb);
424
+ }
425
+ if (options.checkLicenses) {
426
+ const directNames = readDirectDependencyNames(projectPath, !!options.prodOnly);
427
+ const directDeps = scanState.allPackages.filter(p => directNames?.has(p.name));
428
+ const licenseResult = await detectLicenseIssues({
429
+ lockfilePath: scanInput.filePath,
430
+ directDeps,
431
+ isNpm: scanInput.source === "package-lock" || scanInput.source === "npm-shrinkwrap",
432
+ isOffline: !!options.offline || !!options.offlineDb,
433
+ });
434
+ licenseFindings = licenseResult.findings;
435
+ licenseLimitedToDirectOnly = licenseResult.limitedToDirectOnly;
436
+ }
437
+ await writeOutputs(options, {
438
+ sorted: scanState.sorted,
439
+ allPackages: scanState.allPackages,
440
+ suggestedFixCommands: scanState.suggestedFixCommands,
441
+ coverage: scanState.coverage,
442
+ minSeverity: scanState.minSeverity,
443
+ tableFindings: scanState.tableFindings,
444
+ completeness: scanState.completeness,
445
+ overrideFindings,
446
+ maintenanceFindings,
447
+ licenseFindings,
448
+ licenseLimitedToDirectOnly,
449
+ }, scanInput, projectPath);
450
+ if (!(options.json || options.sarif || options.sbom) || options.verbose) {
451
+ const offline = !!options.offline || !!options.offlineDb;
452
+ const showOverrideHint = !options.checkOverrides && !options.ratchet && hasOverrideEntries(projectPath);
453
+ if (options.verbose) {
454
+ const overrideCount = options.checkOverrides ? overrideFindings.length : 0;
455
+ printSummary(scanState.sorted, packages.length, scanInput);
456
+ const pmLabel = scanState.suggestedFixCommands
457
+ ? `${chalk.cyan(scanState.suggestedFixCommands.packageManager)} ${chalk.gray(`(${scanState.suggestedFixCommands.sourceLabel})`)}`
458
+ : undefined;
459
+ printActionSummary(scanState.sorted, overrideCount, pmLabel);
460
+ printSuggestedFixCommands(scanState.sorted, scanInput, { offline, overrideCount });
461
+ printSuggestedFixCommandSkips(scanState.sorted, scanInput, { offline });
462
+ if (scanInput.skippedDependencies.length > 0) {
463
+ printSkippedDependencies(scanInput.skippedDependencies);
464
+ }
465
+ if (scanState.sorted.length > 0) {
466
+ if (scanState.tableFindings.length > 0) {
467
+ const skippedKeys = new Set((scanState.suggestedFixCommands?.skipped ?? []).map(s => `${s.package}@${s.version}`));
468
+ printTable(scanState.tableFindings, options.all ? null : scanState.minSeverity, skippedKeys, scanState.suggestedFixCommands);
469
+ }
470
+ else {
471
+ logInfo(`No findings met the table threshold of ${scanState.minSeverity}. Re-run with --all to show everything.`, options);
472
+ }
473
+ }
474
+ if (options.checkOverrides && overrideFindings.length > 0) {
475
+ console.log("\n" + renderOverrideFindings(overrideFindings, { verbose: true, projectPath }));
476
+ }
477
+ if (options.checkMaintenance && maintenanceFindings.length > 0) {
478
+ console.log("\n" + renderMaintenanceFindings(maintenanceFindings, { verbose: true }));
479
+ }
480
+ if (options.checkLicenses) {
481
+ console.log("\n" + renderLicenseFindings(licenseFindings, { limitedToDirectOnly: licenseLimitedToDirectOnly }));
482
+ }
483
+ printCoverage([...scanInput.notes, ...scanState.coverage]);
484
+ printFinalStatus(scanState.sorted, overrideCount, scanState.completeness);
485
+ if (showOverrideHint)
486
+ printOverrideHint();
487
+ }
488
+ else {
489
+ const compactPmLabel = scanState.suggestedFixCommands
490
+ ? `${chalk.cyan(scanState.suggestedFixCommands.packageManager)} ${chalk.gray(`(${scanState.suggestedFixCommands.sourceLabel})`)}`
491
+ : undefined;
492
+ printCompactOutput(scanState.sorted, scanInput, {
493
+ offline,
494
+ all: !!options.all,
495
+ packageManager: compactPmLabel,
496
+ completeness: scanState.completeness,
497
+ licenseFindings: options.checkLicenses ? licenseFindings : undefined,
498
+ licenseLimitedToDirectOnly: options.checkLicenses ? licenseLimitedToDirectOnly : undefined,
499
+ });
500
+ if (options.checkOverrides) {
501
+ console.log("\n" + renderOverrideFindings(overrideFindings, { verbose: false, projectPath }));
502
+ }
503
+ if (options.checkMaintenance && maintenanceFindings.length > 0) {
504
+ console.log("\n" + renderMaintenanceFindings(maintenanceFindings, { verbose: false }));
505
+ }
506
+ if (showOverrideHint)
507
+ printOverrideHint();
508
+ }
509
+ }
510
+ }
511
+ if (options.report) {
512
+ const outputDir = path.resolve(typeof options.report === "string" ? options.report : "./cve-report");
513
+ const reportData = buildReportData({
514
+ projectPath,
515
+ cliVersion,
516
+ packageManager: scanInput.source,
517
+ lockfileSource: scanInput.filePath ? path.basename(scanInput.filePath) : scanInput.source,
518
+ packageCount: packages.length,
519
+ findings: scanState.sorted,
520
+ suggestedFixCommands: scanState.suggestedFixCommands,
521
+ notes: [...scanInput.notes, ...scanState.coverage],
522
+ warnings: scanInput.warnings,
523
+ skippedDependencies: scanInput.skippedDependencies,
524
+ // undefined (not []) when override checking was not requested, so the HTML
525
+ // report omits the Override hygiene panel entirely on a plain scan.
526
+ overrideFindings: options.checkOverrides ? overrideFindings : undefined,
527
+ // Same undefined-vs-[] convention as overrideFindings above.
528
+ maintenanceFindings: options.checkMaintenance ? maintenanceFindings : undefined,
529
+ licenseFindings: options.checkLicenses ? licenseFindings : undefined,
530
+ licenseLimitedToDirectOnly: options.checkLicenses ? licenseLimitedToDirectOnly : undefined,
531
+ completeness: scanState.completeness,
532
+ });
533
+ const { reportPath } = await writeHtmlReport({
534
+ outputDir,
535
+ data: reportData,
536
+ autoOpen: !options.noOpen,
537
+ });
538
+ console.log(`${chalk.gray("Report:")} ${chalk.cyan(reportPath)}`);
539
+ }
540
+ debugLog("Scan finished", {
541
+ totalDurationMs: Date.now() - scanStartedAt,
542
+ findings: scanState.sorted.length,
543
+ packages: packages.length,
544
+ });
545
+ if (baseline) {
546
+ if (scanState.sorted.length === 0) {
547
+ console.log(chalk.green(`No new findings above baseline - ${suppressedCount} existing ${suppressedCount === 1 ? "finding" : "findings"} suppressed`));
548
+ }
549
+ else {
550
+ console.log(chalk.yellow(`${scanState.sorted.length} new ${scanState.sorted.length === 1 ? "finding" : "findings"} above baseline - ${suppressedCount} existing ${suppressedCount === 1 ? "finding" : "findings"} suppressed`));
551
+ }
552
+ }
553
+ // Override hygiene findings count toward --fail-on too, using the shared
554
+ // reachesFailOn helper from src/utils/severity.ts, the same logic used by
555
+ // the standalone `overrides` command. Without this, a CI run
556
+ // of `cve-lite . --check-overrides --fail-on high` would exit 0 despite high-severity
557
+ // override findings, giving a false sense of protection. overrideFindings is empty
558
+ // unless --check-overrides (and non-ratchet), so this is a no-op otherwise.
559
+ const shouldFail = reachesFailOn(scanState.sorted, options.failOn) ||
560
+ reachesFailOn(overrideFindings, options.failOn) ||
561
+ reachesFailOn(maintenanceFindings, options.failOn);
562
+ // In fix mode, remaining transitive findings cannot be auto-fixed.
563
+ // Exiting non-zero would prevent the Action PR step from running.
564
+ const incompleteFailure = shouldFailForIncompleteScan(scanState.completeness, options.incompletePolicy);
565
+ const exitCode = incompleteFailure
566
+ ? EXIT_ERROR
567
+ : shouldFail && !options.fix
568
+ ? 1
569
+ : 0;
570
+ // Emit scan.finished event and return exitCode
571
+ auditLog.emit({
572
+ ts: new Date().toISOString(),
573
+ type: "scan.finished",
574
+ schemaVersion: 1,
575
+ durationMs: Date.now() - scanStartTime,
576
+ findingsCount: scanState.sorted.length + overrideFindings.length,
577
+ exitCode,
578
+ });
579
+ return exitCode;
580
+ }
581
+ export async function scanProject(params) {
582
+ const directDependencyNames = readDirectDependencyNames(params.projectPath, !!params.options.prodOnly);
583
+ const { findings, completeness } = await scanPackages(params.scanInput.packages, params.batchSize, params.options, {
584
+ directDependencyNames,
585
+ scanSource: params.scanInput.source,
586
+ scanFilePath: params.scanInput.filePath,
587
+ }, params.debugLog, params.fetchImpl);
588
+ if (params.options.usage) {
589
+ logInfo(`Scanning project source for usage hints...`, params.options);
590
+ const usageStartedAt = Date.now();
591
+ const pkgNames = new Set(findings.map(f => f.pkg.name));
592
+ const usageData = scanProjectForPackageUsage(params.projectPath, pkgNames);
593
+ let matchedPackages = 0;
594
+ for (const finding of findings) {
595
+ const files = usageData[finding.pkg.name];
596
+ if (files) {
597
+ if (files.length > 0) {
598
+ matchedPackages += 1;
599
+ }
600
+ finding.usage = {
601
+ imported: files.length > 0,
602
+ files,
603
+ };
604
+ }
605
+ }
606
+ if (params.options.debug) {
607
+ params.debugLog("Usage scan", {
608
+ durationMs: Date.now() - usageStartedAt,
609
+ packagesChecked: pkgNames.size,
610
+ matchedPackages,
611
+ });
612
+ }
613
+ }
614
+ let finalFindings = findings;
615
+ if (params.options.onlyUsed) {
616
+ const beforeCount = finalFindings.length;
617
+ finalFindings = finalFindings.filter(f => f.usage?.imported);
618
+ if (params.options.debug) {
619
+ params.debugLog("Findings filtered", {
620
+ reason: "only-used",
621
+ before: beforeCount,
622
+ after: finalFindings.length,
623
+ });
624
+ }
625
+ }
626
+ const offline = !!params.options.offline || !!params.options.offlineDb;
627
+ const sorted = sortFindingsForOutput(finalFindings);
628
+ const coverage = buildCoverageNotes(params.scanInput, offline);
629
+ const minSeverity = normalizeSeverity(params.options.minSeverity || "medium");
630
+ const tableFindings = params.options.all
631
+ ? sorted
632
+ : selectFindingsForTable(sorted, minSeverity);
633
+ const suggestedFixCommands = buildSuggestedFixCommandPlan(sorted, params.scanInput, { offline });
634
+ return {
635
+ sorted,
636
+ coverage,
637
+ minSeverity,
638
+ tableFindings,
639
+ suggestedFixCommands,
640
+ allPackages: params.scanInput.packages,
641
+ completeness,
642
+ };
643
+ }
@@ -1,6 +1,6 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
- import { EXCLUDED_DIRS } from "../constants.js";
3
+ import { EXCLUDED_DIRS, LOCKFILE_PRIORITY_NESTED } from "../constants.js";
4
4
  export function safeReadText(filePath) {
5
5
  try {
6
6
  return fs.readFileSync(filePath, "utf8");
@@ -59,18 +59,15 @@ export function chooseBestLockfile(candidates) {
59
59
  const bDepth = b.split(path.sep).length;
60
60
  if (aDepth !== bDepth)
61
61
  return aDepth - bDepth;
62
- const score = (file) => {
63
- const name = path.basename(file);
64
- if (name === "package-lock.json")
65
- return 0;
66
- if (name === "pnpm-lock.yaml")
67
- return 1;
68
- if (name === "yarn.lock")
69
- return 2;
70
- if (name === "bun.lock")
71
- return 3;
72
- return 4;
73
- };
74
- return score(a) - score(b);
62
+ return lockfileRank(a) - lockfileRank(b);
75
63
  })[0];
76
64
  }
65
+ /**
66
+ * Position in LOCKFILE_PRIORITY_NESTED, with anything unrecognised sorting last.
67
+ * Shared with root detection so both paths agree on precedence.
68
+ */
69
+ function lockfileRank(filePath) {
70
+ const name = path.basename(filePath);
71
+ const index = LOCKFILE_PRIORITY_NESTED.findIndex(candidate => candidate === name);
72
+ return index === -1 ? LOCKFILE_PRIORITY_NESTED.length : index;
73
+ }