cve-lite-cli 1.18.1 → 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 CHANGED
@@ -212,8 +212,10 @@ CVE Lite CLI has been evaluated against real open-source projects to verify that
212
212
  - [Ghost](https://owasp.org/cve-lite-cli/docs/case-studies/ghost) — 26 vulnerable packages across 4,447 resolved in a professionally maintained CMS — every one transitive, including a critical XSS in the library responsible for making user content safe
213
213
  - [Astro](https://owasp.org/cve-lite-cli/docs/case-studies/astro) — verified baseline scan of a modern pnpm monorepo (2,228 packages, 34 findings at revision `221bb4b`) with a critical transitive SDK chain and four generated fix command groups
214
214
  - [Turborepo](https://owasp.org/cve-lite-cli/docs/case-studies/turborepo) — verified baseline scan of a build-system pnpm monorepo (1,776 packages, 13 findings at revision `c85d410`) with a critical no-fix sandbox beta, all-transitive risk, and zero auto-generated fix commands on this snapshot
215
+ - [Visual Studio Code](https://owasp.org/cve-lite-cli/docs/case-studies/vscode) — verified baseline scan of the VS Code root npm lockfile (1,374 packages, 9 findings at revision `bc678ca`) with two direct Anthropic SDK advisories, a high-severity gulp toolchain chain, and two generated fix command groups
216
+ - [Storybook](https://owasp.org/cve-lite-cli/docs/case-studies/storybook) — verified baseline scan of a Yarn Berry monorepo (3,008 packages, 92 findings at revision `cc19ae1`) spanning cross-framework sandbox templates, five critical transitive chains, and one direct vite fix command
215
217
 
216
- In-repo lockfile fixtures for Astro and Turborepo live under [`examples/`](examples/readme.md) — clone the repo and scan immediately without downloading full upstream checkouts.
218
+ In-repo lockfile fixtures for Astro, Turborepo, Visual Studio Code, and Storybook live under [`examples/`](examples/readme.md) — clone the repo and scan immediately without downloading full upstream checkouts.
217
219
 
218
220
  These are not demos. They are documented scans against real codebases with real findings, recorded before and after applying fix commands.
219
221
 
@@ -229,6 +231,7 @@ If you maintain an open-source JavaScript or TypeScript project and want CVE Lit
229
231
  - **[As AI speeds coding, CVE Lite CLI keeps security deliberately AI-free](https://www.csoonline.com/article/4176701/as-ai-speeds-coding-cve-lite-cli-keeps-security-deliberately-ai-free.html)** — CSO Online (Shweta Sharma), May 2026
230
232
  - **[CVE Lite CLI: The Dependency Scanner That Actually Tells You What to Run](https://medium.com/@techlatest.net/cve-lite-cli-the-dependency-scanner-that-actually-tells-you-what-to-run-not-just-whats-broken-f6b518199981)** — Medium (TechLatest.Net), May 2026
231
233
  - **[AI Security Is Changing Fast — These 6 Open-Source Tools Prove It](https://medium.com/@techlatest.net/ai-security-is-changing-fast-these-6-open-source-tools-prove-it-5c5c9081cff7)** — Medium (TechLatest.Net), May 2026
234
+ - **[Hottest cybersecurity open-source tools of the month: May 2026](https://www.helpnetsecurity.com/2026/05/28/hottest-cybersecurity-open-source-tools-of-the-month-may-2026/)** — Help Net Security Monthly Roundup, May 2026
232
235
  - **[CVE Lite CLI: Open-source dependency vulnerability scanner](https://www.helpnetsecurity.com/2026/05/20/cve-lite-cli-open-source-dependency-vulnerability-scanner/)** — Help Net Security, May 2026
233
236
  - **[Review of CVE Lite CLI](https://developmentcurated.com/testing-and-security/review-of-cve-lite-cli/)** — Development Curated (Sebastian Raiffen, IT Security Consultant), April 2026
234
237
 
@@ -3,7 +3,7 @@ export class LocalAdvisorySource {
3
3
  constructor(db) {
4
4
  this.db = db;
5
5
  }
6
- queryBatch(packages) {
6
+ queryBatch(packages, _meta) {
7
7
  const results = packages.map(pkg => ({
8
8
  package: pkg.name,
9
9
  version: pkg.version,
@@ -1,26 +1,57 @@
1
1
  import { extractErrorMessage } from "../utils/network.js";
2
2
  export class OsvAdvisorySource {
3
3
  baseUrl;
4
- constructor(baseUrl = "https://api.osv.dev") {
4
+ debugLog;
5
+ constructor(baseUrl = "https://api.osv.dev", debugLog) {
5
6
  this.baseUrl = baseUrl;
7
+ this.debugLog = debugLog;
6
8
  }
7
- async queryBatch(packages) {
9
+ async queryBatch(packages, meta) {
10
+ const requestUrl = `${this.baseUrl}/v1/querybatch`;
11
+ const payload = {
12
+ queries: packages.map(p => ({
13
+ package: {
14
+ ecosystem: p.ecosystem,
15
+ name: p.name,
16
+ },
17
+ version: p.version,
18
+ })),
19
+ };
20
+ const startedAt = this.debugLog ? Date.now() : 0;
8
21
  try {
9
- const response = await fetch(`${this.baseUrl}/v1/querybatch`, {
22
+ if (this.debugLog) {
23
+ this.debugLog("OSV request", {
24
+ batchId: meta?.batchId ?? null,
25
+ method: "POST",
26
+ url: requestUrl,
27
+ headers: {
28
+ "Content-Type": "application/json",
29
+ },
30
+ queryCount: packages.length,
31
+ sample: packages.slice(0, 3).map(p => ({
32
+ ecosystem: p.ecosystem,
33
+ name: p.name,
34
+ version: p.version,
35
+ })),
36
+ });
37
+ }
38
+ const response = await fetch(requestUrl, {
10
39
  method: "POST",
11
40
  headers: {
12
41
  "Content-Type": "application/json",
13
42
  },
14
- body: JSON.stringify({
15
- queries: packages.map(p => ({
16
- package: {
17
- ecosystem: p.ecosystem,
18
- name: p.name,
19
- },
20
- version: p.version,
21
- })),
22
- }),
43
+ body: JSON.stringify(payload),
23
44
  });
45
+ if (this.debugLog) {
46
+ this.debugLog("OSV response", {
47
+ batchId: meta?.batchId ?? null,
48
+ method: "POST",
49
+ url: requestUrl,
50
+ status: response.status,
51
+ statusText: response.statusText,
52
+ durationMs: Date.now() - startedAt,
53
+ });
54
+ }
24
55
  if (!response.ok) {
25
56
  throw new Error(`OSV batch query failed: ${response.status} ${response.statusText}`);
26
57
  }
@@ -32,19 +63,58 @@ export class OsvAdvisorySource {
32
63
  }));
33
64
  }
34
65
  catch (error) {
66
+ if (this.debugLog) {
67
+ this.debugLog("OSV request failed", {
68
+ batchId: meta?.batchId ?? null,
69
+ method: "POST",
70
+ url: requestUrl,
71
+ durationMs: Date.now() - startedAt,
72
+ error: error instanceof Error
73
+ ? { message: error.message, stack: error.stack }
74
+ : String(error),
75
+ });
76
+ }
35
77
  const message = extractErrorMessage(error);
36
78
  throw new Error(`OSV batch query failed for ${this.baseUrl}: ${message}`);
37
79
  }
38
80
  }
39
81
  async getVuln(id) {
82
+ const requestUrl = `${this.baseUrl}/v1/vulns/${encodeURIComponent(id)}`;
83
+ const startedAt = this.debugLog ? Date.now() : 0;
40
84
  try {
41
- const response = await fetch(`${this.baseUrl}/v1/vulns/${encodeURIComponent(id)}`);
85
+ if (this.debugLog) {
86
+ this.debugLog("OSV request", {
87
+ method: "GET",
88
+ url: requestUrl,
89
+ headers: {},
90
+ });
91
+ }
92
+ const response = await fetch(requestUrl);
93
+ if (this.debugLog) {
94
+ this.debugLog("OSV response", {
95
+ method: "GET",
96
+ url: requestUrl,
97
+ status: response.status,
98
+ statusText: response.statusText,
99
+ durationMs: Date.now() - startedAt,
100
+ });
101
+ }
42
102
  if (!response.ok) {
43
103
  throw new Error(`OSV vuln fetch failed for ${id}: ${response.status} ${response.statusText}`);
44
104
  }
45
105
  return response.json();
46
106
  }
47
107
  catch (error) {
108
+ if (this.debugLog) {
109
+ this.debugLog("OSV request failed", {
110
+ method: "GET",
111
+ url: requestUrl,
112
+ durationMs: Date.now() - startedAt,
113
+ error: error instanceof Error
114
+ ? { message: error.message, stack: error.stack }
115
+ : String(error),
116
+ });
117
+ }
48
118
  const message = extractErrorMessage(error);
49
119
  throw new Error(`OSV vuln fetch failed for ${id} via ${this.baseUrl}: ${message}`);
50
120
  }
package/dist/cli/args.js CHANGED
@@ -97,6 +97,10 @@ export function parseArgs(argv) {
97
97
  options.json = true;
98
98
  continue;
99
99
  }
100
+ if (arg === "--debug") {
101
+ options.debug = true;
102
+ continue;
103
+ }
100
104
  if (arg === "--verbose") {
101
105
  options.verbose = true;
102
106
  continue;
package/dist/cli/help.js CHANGED
@@ -42,6 +42,7 @@ export function printHelp() {
42
42
  " --fix Apply validated direct dependency fixes and rescan",
43
43
  " --osv-url <url> Use a custom OSV-compatible advisory endpoint",
44
44
  " --ca-cert <path> Path to a CA certificate file for corporate SSL proxies",
45
+ " --debug Write verbose runtime/network diagnostics to a timestamped log file",
45
46
  " --verbose Show detailed output with fix plan, paths, and full table",
46
47
  " --prod-only Exclude dev dependencies where available",
47
48
  " --fail-on <severity> Exit non-zero at or above severity (default: critical)",
package/dist/index.js CHANGED
@@ -11,16 +11,18 @@ import { normalizeSeverity } from "./osv/severity.js";
11
11
  import { DEFAULT_BATCH_SIZE, DEFAULT_SEARCH_DEPTH, severityOrder } from "./constants.js";
12
12
  import { chalk } from "./utils/chalk.js";
13
13
  import { createSpinner } from "./output/spinner.js";
14
+ import { createDebugLogger } from "./output/debug.js";
14
15
  import { buildSuggestedFixCommandPlan } from "./remediation/fix-commands.js";
15
16
  import { scanProjectForPackageUsage } from "./usage/scanner.js";
16
17
  import { getCliVersion } from "./utils/version-info.js";
17
- import { blockedAdvisoryRequestHint, fetchErrorCaCertHint, 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";
18
19
  import { formatAdvisoryDbFreshness } from "./utils/time.js";
19
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";
26
28
  import { readConfig, validateCaCertFile } from "./cli/config.js";
@@ -52,8 +54,16 @@ if (parsedArgs) {
52
54
  const projectPath = path.resolve(projectArg || ".");
53
55
  const batchSize = Number(options.batchSize || DEFAULT_BATCH_SIZE);
54
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();
55
60
  async function main() {
56
61
  printBanner(options);
62
+ debugSession.announcePath();
63
+ debugLog("CLI started", {
64
+ version: cliVersion,
65
+ args: process.argv.slice(2),
66
+ });
57
67
  if (command === "config") {
58
68
  const { configSubcommand } = parsedArgs;
59
69
  if (!configSubcommand) {
@@ -87,6 +97,10 @@ if (parsedArgs) {
87
97
  }
88
98
  process.env.NODE_EXTRA_CA_CERTS = resolvedCaCert;
89
99
  }
100
+ debugLog("Config loaded", {
101
+ caCert: resolvedCaCert ?? null,
102
+ nodeExtraCaCerts: process.env.NODE_EXTRA_CA_CERTS ?? null,
103
+ });
90
104
  if (command === "advisories-sync") {
91
105
  const spinner = createSpinner("Preparing advisory sync...", options);
92
106
  const usePlainProgressLogs = !process.stdout.isTTY || !!options.json;
@@ -127,8 +141,14 @@ if (parsedArgs) {
127
141
  osvUrl: options.osvUrl,
128
142
  offline: options.offline,
129
143
  offlineDb: options.offlineDb,
144
+ debugLog,
130
145
  });
131
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
+ });
132
152
  if (advisorySource.offline) {
133
153
  const metadata = advisorySource.advisoryDbMetadata;
134
154
  advisoryDbFreshnessLine = formatAdvisoryDbFreshness(metadata?.lastSyncAt ?? null);
@@ -142,7 +162,8 @@ if (parsedArgs) {
142
162
  }
143
163
  catch (error) {
144
164
  if (options.offline || options.offlineDb) {
145
- throw new Error(`Offline advisory database is not available: ${error instanceof Error ? error.message : String(error)}`);
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")}`);
146
167
  }
147
168
  throw error;
148
169
  }
@@ -160,6 +181,16 @@ if (parsedArgs) {
160
181
  }
161
182
  let scanInput = loadPackages(projectPath, !!options.prodOnly, searchDepth);
162
183
  let packages = scanInput.packages;
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
+ });
163
194
  logInfo(`Parsed ${packages.length} ${pluralize(packages.length, "package")} from ${scanInput.source}${scanInput.filePath ? ` (${path.relative(projectPath, scanInput.filePath) || path.basename(scanInput.filePath)})` : ""}`, options);
164
195
  printCacheSummary(options.cacheDir, options);
165
196
  if (scanInput.warnings.length > 0) {
@@ -168,6 +199,7 @@ if (parsedArgs) {
168
199
  }
169
200
  }
170
201
  if (packages.length === 0) {
202
+ debugLog("Scan skipped", { reason: "no packages found", projectPath });
171
203
  logWarn(buildNoPackagesMessage(projectPath), options);
172
204
  process.exit(0);
173
205
  return;
@@ -177,6 +209,7 @@ if (parsedArgs) {
177
209
  batchSize,
178
210
  options,
179
211
  projectPath,
212
+ debugLog,
180
213
  });
181
214
  const findingsBeforeFix = scanState.sorted.length;
182
215
  let fixResult = null;
@@ -186,12 +219,14 @@ if (parsedArgs) {
186
219
  projectPath,
187
220
  totalFindings: scanState.sorted.length,
188
221
  options,
222
+ debugLog,
189
223
  });
190
224
  if (fixResult.appliedFixCount > 0) {
191
225
  console.log(`${chalk.cyan("⠋")} ${chalk.gray("Rescanning project...")}`);
192
226
  scanInput = loadPackages(projectPath, !!options.prodOnly, searchDepth);
193
227
  packages = scanInput.packages;
194
228
  if (packages.length === 0) {
229
+ debugLog("Scan skipped", { reason: "no packages found after fix rescan", projectPath });
195
230
  logWarn(buildNoPackagesMessage(projectPath), options);
196
231
  process.exit(0);
197
232
  return;
@@ -201,6 +236,7 @@ if (parsedArgs) {
201
236
  batchSize,
202
237
  options,
203
238
  projectPath,
239
+ debugLog,
204
240
  });
205
241
  }
206
242
  }
@@ -267,6 +303,11 @@ if (parsedArgs) {
267
303
  });
268
304
  console.log(`${chalk.gray("Report:")} ${chalk.cyan(reportPath)}`);
269
305
  }
306
+ debugLog("Scan finished", {
307
+ totalDurationMs: Date.now() - scanStartedAt,
308
+ findings: scanState.sorted.length,
309
+ packages: packages.length,
310
+ });
270
311
  const failLevel = normalizeSeverity(options.failOn);
271
312
  const shouldFail = scanState.sorted.some(f => severityOrder[f.severity] >= severityOrder[failLevel]);
272
313
  process.exit(shouldFail ? 1 : 0);
@@ -275,6 +316,9 @@ if (parsedArgs) {
275
316
  main().catch((error) => {
276
317
  const errorMessage = error instanceof Error ? error.message : String(error);
277
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
+ }
278
322
  if (isSslCertificateError(error)) {
279
323
  const [hint, ...rest] = sslCertificateErrorHint();
280
324
  console.error(chalk.yellow(hint));
@@ -310,24 +354,44 @@ async function scanProject(params) {
310
354
  directDependencyNames,
311
355
  scanSource: params.scanInput.source,
312
356
  scanFilePath: params.scanInput.filePath,
313
- });
357
+ }, params.debugLog);
314
358
  if (params.options.usage) {
315
359
  logInfo(`Scanning project source for usage hints...`, params.options);
360
+ const usageStartedAt = Date.now();
316
361
  const pkgNames = new Set(findings.map(f => f.pkg.name));
317
362
  const usageData = scanProjectForPackageUsage(params.projectPath, pkgNames);
363
+ let matchedPackages = 0;
318
364
  for (const finding of findings) {
319
365
  const files = usageData[finding.pkg.name];
320
366
  if (files) {
367
+ if (files.length > 0) {
368
+ matchedPackages += 1;
369
+ }
321
370
  finding.usage = {
322
371
  imported: files.length > 0,
323
372
  files,
324
373
  };
325
374
  }
326
375
  }
376
+ if (params.options.debug) {
377
+ params.debugLog("Usage scan", {
378
+ durationMs: Date.now() - usageStartedAt,
379
+ packagesChecked: pkgNames.size,
380
+ matchedPackages,
381
+ });
382
+ }
327
383
  }
328
384
  let finalFindings = findings;
329
385
  if (params.options.onlyUsed) {
386
+ const beforeCount = finalFindings.length;
330
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
+ }
331
395
  }
332
396
  const offline = !!params.options.offline || !!params.options.offlineDb;
333
397
  const sorted = sortFindingsForOutput(finalFindings);
@@ -335,7 +399,7 @@ async function scanProject(params) {
335
399
  const minSeverity = normalizeSeverity(params.options.minSeverity || "medium");
336
400
  const tableFindings = params.options.all
337
401
  ? sorted
338
- : sorted.filter(f => severityOrder[f.severity] >= severityOrder[minSeverity] || f.severity === "unknown");
402
+ : selectFindingsForTable(sorted, minSeverity);
339
403
  const suggestedFixCommands = buildSuggestedFixCommandPlan(sorted, params.scanInput, { offline });
340
404
  return {
341
405
  sorted,
@@ -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 {};