cve-lite-cli 1.30.0 → 1.32.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.
package/README.md CHANGED
@@ -98,6 +98,7 @@ cve-lite /path/to/project --sarif # SARIF output for GitHub Code Scann
98
98
  cve-lite /path/to/project --report # interactive HTML dashboard
99
99
  cve-lite /path/to/project --check-overrides # audit override hygiene alongside the CVE scan
100
100
  cve-lite /path/to/project --check-maintenance # flag CVE-blocking version drag and npm-deprecated direct deps
101
+ cve-lite /path/to/project --check-licenses # detect copyleft and unknown licenses alongside the CVE scan
101
102
  cve-lite advisories sync # sync advisory DB for offline use
102
103
  cve-lite advisories init # create an empty advisory DB to populate yourself
103
104
  cve-lite /path/to/project --offline # scan with no runtime API calls
@@ -203,13 +204,13 @@ For the full guide, see the [Release Cooldown Awareness guide](https://owasp.org
203
204
 
204
205
  Most security tooling is built around pipelines, not developers. Dependabot opens PRs you'll get to eventually. CI scanners block merges after the fact. Dashboards surface lists of CVE IDs with no clear path to fixing them. Developers learn to ignore it.
205
206
 
206
- CVE Lite CLI is built for the moment before you push. It reads your lockfile locally, queries [OSV](https://osv.dev), and produces copy-and-run `npm install`, `pnpm add`, `yarn add`, or `bun add` commands — not a list of identifiers. You see which packages are direct versus transitive, get parent-aware upgrade guidance, and can scan offline in restricted environments.
207
+ CVE Lite CLI is built for the moment before you push. It reads your lockfile locally, queries [OSV](https://osv.dev) and the npm registry advisory API, and produces copy-and-run `npm install`, `pnpm add`, `yarn add`, or `bun add` commands — not a list of identifiers. You see which packages are direct versus transitive, get parent-aware upgrade guidance, and can scan offline in restricted environments.
207
208
 
208
209
  The closer a security tool is to a developer's natural workflow, the more likely it is to be used.
209
210
 
210
211
  ## How it compares
211
212
 
212
- No other free tool combines all of the following: lockfile scanning across npm, pnpm, Yarn, and Bun; parent-aware transitive remediation that tells you which package to upgrade (not just which one is vulnerable); fix version validation before suggesting an upgrade; and a fully offline advisory DB for restricted environments.
213
+ No other free tool combines all of the following: lockfile scanning across npm, pnpm, Yarn, and Bun; parent-aware transitive remediation that tells you which package to upgrade (not just which one is vulnerable); fix version validation before suggesting an upgrade; a fully offline advisory DB for restricted environments; and CVE + license compliance scanning in a single pass.
213
214
 
214
215
  | Capability | CVE Lite CLI | npm audit | OSV-Scanner | Snyk CLI | Socket CLI |
215
216
  |---|:---:|:---:|:---:|:---:|:---:|
@@ -217,19 +218,20 @@ No other free tool combines all of the following: lockfile scanning across npm,
217
218
  | npm + pnpm + Yarn + Bun support | ✅ | ❌ | ✅ | ✅ | ✅ |
218
219
  | No account required | ✅ | ✅ | ✅ | ❌ | ❌ |
219
220
  | Free to use | ✅ | ✅ | ✅ | ❌ | ❌ |
220
- | Usage-aware reachability scanning | ✅ | ❌ | ❌ | ✅ | ⚠️ |
221
- | Direct vs transitive visibility | ✅ | ⚠️ | ✅ | ✅ | ✅ |
222
- | Dev vs runtime dependency labelling | ✅ | ⚠️ | ❌ | ⚠️ | ❌ |
223
- | Copy-and-run fix commands | ✅ | ❌ | ❌ | ✅ | ⚠️ |
224
- | Transitive parent update guidance | ✅ | ❌ | ⚠️ | ⚠️ | ⚠️ |
225
- | Suggested remediation plan | ✅ | ❌ | ⚠️ | ✅ | ⚠️ |
226
- | Ratcheting mode (baseline suppression) | ✅ | ❌ | ❌ | ⚠️ | ❌ |
227
- | Interactive HTML report | ✅ | ❌ | ❌ | ✅ | ❌ |
228
- | SARIF / GitHub Code Scanning output | ✅ | ❌ | ✅ | ✅ | ❌ |
229
- | JSON output | ✅ | ✅ | ✅ | ✅ | ✅ |
230
- | Offline/local advisory DB | ✅ | ❌ | ⚠️ | ❌ | ❌ |
231
- | Override hygiene auditing | ✅ | ❌ | ❌ | ❌ | ❌ |
232
- | Maintenance-risk detection (CVE-fix drag) | ✅ | ❌ | ❌ | ❌ | ❌ |
221
+ | [Usage-aware reachability scanning](https://owasp.org/cve-lite-cli/docs/cli-reference#scan-options) | ✅ | ❌ | ❌ | ✅ | ⚠️ |
222
+ | [Direct vs transitive visibility](https://owasp.org/cve-lite-cli/docs/reading-output) | ✅ | ⚠️ | ✅ | ✅ | ✅ |
223
+ | [Dev vs runtime dependency labelling](https://owasp.org/cve-lite-cli/docs/cli-reference#scan-options) | ✅ | ⚠️ | ❌ | ⚠️ | ❌ |
224
+ | [Copy-and-run fix commands](https://owasp.org/cve-lite-cli/docs/how-remediation-works) | ✅ | ❌ | ❌ | ✅ | ⚠️ |
225
+ | [Transitive parent update guidance](https://owasp.org/cve-lite-cli/docs/remediation-strategy) | ✅ | ❌ | ⚠️ | ⚠️ | ⚠️ |
226
+ | [Suggested remediation plan](https://owasp.org/cve-lite-cli/docs/remediation-strategy) | ✅ | ❌ | ⚠️ | ✅ | ⚠️ |
227
+ | [Ratcheting mode (baseline suppression)](https://owasp.org/cve-lite-cli/docs/ratcheting) | ✅ | ❌ | ❌ | ⚠️ | ❌ |
228
+ | [Interactive HTML report](https://owasp.org/cve-lite-cli/docs/html-report) | ✅ | ❌ | ❌ | ✅ | ❌ |
229
+ | [SARIF / GitHub Code Scanning output](https://owasp.org/cve-lite-cli/docs/sarif) | ✅ | ❌ | ✅ | ✅ | ❌ |
230
+ | [JSON output](https://owasp.org/cve-lite-cli/docs/cli-reference#output-options) | ✅ | ✅ | ✅ | ✅ | ✅ |
231
+ | [Offline/local advisory DB](https://owasp.org/cve-lite-cli/docs/offline-advisory-db) | ✅ | ❌ | ⚠️ | ❌ | ❌ |
232
+ | [Override hygiene auditing](https://owasp.org/cve-lite-cli/docs/override-hygiene) | ✅ | ❌ | ❌ | ❌ | ❌ |
233
+ | [Maintenance-risk detection (CVE-fix drag)](https://owasp.org/cve-lite-cli/docs/maintenance-risk) | ✅ | ❌ | ❌ | ❌ | ❌ |
234
+ | [License compliance scanning (copyleft / unknown)](https://owasp.org/cve-lite-cli/docs/cli-reference#license-scanning-options) | ✅ | ❌ | ❌ | ⚠️ | ⚠️ |
233
235
 
234
236
  <sub>✅ = built-in strength · ⚠️ = partial or workflow-dependent · ❌ = not a core strength</sub>
235
237
 
@@ -0,0 +1,77 @@
1
+ const NPM_ADVISORY_URL = "https://registry.npmjs.org/-/npm/v1/security/advisories/bulk";
2
+ function isValidAdvisory(a) {
3
+ return (typeof a === "object" &&
4
+ a !== null &&
5
+ (typeof a.ghsa_id === "string" || typeof a.id === "number") &&
6
+ typeof a.title === "string" &&
7
+ typeof a.vulnerable_versions === "string");
8
+ }
9
+ function normalizeAdvisory(advisory, pkgName) {
10
+ const id = advisory.ghsa_id ?? `NPM-${advisory.id}`;
11
+ return {
12
+ id,
13
+ aliases: advisory.cve_ids ?? [],
14
+ summary: advisory.title,
15
+ details: "",
16
+ affected: [
17
+ {
18
+ package: { ecosystem: "npm", name: pkgName },
19
+ ranges: [
20
+ {
21
+ type: "ECOSYSTEM",
22
+ events: [
23
+ { introduced: "0" },
24
+ ...(advisory.patched_versions
25
+ ? [{ fixed: advisory.patched_versions.replace(/^>=/, "") }]
26
+ : []),
27
+ ],
28
+ },
29
+ ],
30
+ },
31
+ ],
32
+ severity: [],
33
+ database_specific: {
34
+ severity: advisory.severity ?? "unknown",
35
+ },
36
+ };
37
+ }
38
+ export async function queryNpmAdvisoryGaps(packages, options = {}) {
39
+ if (options.offline || packages.length === 0)
40
+ return [];
41
+ const fetchImpl = options.fetchImpl ?? fetch;
42
+ const body = {};
43
+ for (const pkg of packages) {
44
+ body[pkg.name] = [pkg.version];
45
+ }
46
+ let data;
47
+ try {
48
+ const response = await fetchImpl(NPM_ADVISORY_URL, {
49
+ method: "POST",
50
+ headers: { "Content-Type": "application/json" },
51
+ body: JSON.stringify(body),
52
+ });
53
+ if (!response.ok)
54
+ return [];
55
+ data = (await response.json());
56
+ }
57
+ catch {
58
+ return [];
59
+ }
60
+ if (!data || typeof data !== "object" || Array.isArray(data))
61
+ return [];
62
+ const results = [];
63
+ for (const pkg of packages) {
64
+ const advisories = data[pkg.name];
65
+ if (!Array.isArray(advisories) || advisories.length === 0)
66
+ continue;
67
+ const vulns = [];
68
+ for (const raw of advisories) {
69
+ if (!isValidAdvisory(raw))
70
+ continue;
71
+ vulns.push(normalizeAdvisory(raw, pkg.name));
72
+ }
73
+ if (vulns.length > 0)
74
+ results.push({ pkg, vulns });
75
+ }
76
+ return results;
77
+ }
package/dist/cli/args.js CHANGED
@@ -8,6 +8,7 @@ export function parseArgs(argv) {
8
8
  }
9
9
  const options = {
10
10
  failOn: "critical",
11
+ incompletePolicy: "warn",
11
12
  batchSize: "100",
12
13
  searchDepth: "4",
13
14
  minSeverity: "medium"
@@ -369,6 +370,26 @@ export function parseArgs(argv) {
369
370
  options.checkMaintenance = true;
370
371
  continue;
371
372
  }
373
+ if (arg === "--incomplete-policy") {
374
+ const value = argv[++i];
375
+ if (value !== "warn" && value !== "error") {
376
+ throw new Error("--incomplete-policy must be one of: warn, error");
377
+ }
378
+ options.incompletePolicy = value;
379
+ continue;
380
+ }
381
+ if (arg.startsWith("--incomplete-policy=")) {
382
+ const value = arg.slice("--incomplete-policy=".length);
383
+ if (value !== "warn" && value !== "error") {
384
+ throw new Error("--incomplete-policy must be one of: warn, error");
385
+ }
386
+ options.incompletePolicy = value;
387
+ continue;
388
+ }
389
+ if (arg === "--check-licenses") {
390
+ options.checkLicenses = true;
391
+ continue;
392
+ }
372
393
  if (arg.startsWith("-")) {
373
394
  throw new Error(`Unknown option: ${arg}`);
374
395
  }
package/dist/cli/help.js CHANGED
@@ -50,7 +50,10 @@ export function printHelp() {
50
50
  " print, thread to JSON/SARIF/HTML, and count toward --fail-on",
51
51
  " --check-maintenance Also flag direct deps that block a transitive CVE fix via a major-version",
52
52
  " drag, or are marked deprecated on npm (DM001); counts toward --fail-on",
53
+ " --check-licenses Also detect copyleft (LC001) and unknown (LC002) licenses; informational",
54
+ " only - does not affect exit code or --fail-on",
53
55
  " --fail-on <severity> Exit non-zero at or above severity (default: critical)",
56
+ " --incomplete-policy <mode> Incomplete scan handling: warn or error (default: warn)",
54
57
  " --batch-size <number> OSV batch size (default: 100)",
55
58
  " --usage Scan project source files to check if vulnerable dependencies are imported",
56
59
  " --only-used Filter out findings for packages that are not imported in your source code",
@@ -80,6 +83,7 @@ export function printHelp() {
80
83
  " cve-lite . Scan the current directory",
81
84
  " cve-lite . --verbose Full output with fix plan and findings table",
82
85
  " cve-lite . --fail-on high Exit 1 if any high or critical findings are found",
86
+ " cve-lite . --incomplete-policy error Exit 3 if detection data is incomplete",
83
87
  " cve-lite . --json Write findings to a timestamped JSON file",
84
88
  " cve-lite . --report Generate an interactive HTML report",
85
89
  " cve-lite . --fix Apply validated direct dependency fixes and rescan",
@@ -2,13 +2,13 @@ import { validateCaCertFile } from "./config.js";
2
2
  import { validateOsvUrl } from "../utils/validate-url.js";
3
3
  export async function validateOptions(options) {
4
4
  if (options.allowPrivateOsvUrl && !options.osvUrl) {
5
- throw new Error("--allow-private-osv-url requires --osv-url");
5
+ throw new Error("--allow-private-osv-url requires --osv-url. Provide a custom OSV endpoint with --osv-url, or remove --allow-private-osv-url.");
6
6
  }
7
7
  if ((options.offline || options.offlineDb) && options.osvUrl) {
8
- throw new Error("--offline/--offline-db cannot be used with --osv-url");
8
+ throw new Error("--offline/--offline-db cannot be used with --osv-url. Choose offline mode (local DB) or online mode (custom OSV endpoint), not both.");
9
9
  }
10
10
  if (options.noCache && (options.offline || options.offlineDb)) {
11
- throw new Error("--no-cache cannot be used with --offline or --offline-db");
11
+ throw new Error("--no-cache cannot be used with --offline or --offline-db. Offline mode uses the local advisory DB directly; --no-cache only applies to online scans.");
12
12
  }
13
13
  let ssrfWarning;
14
14
  if (options.osvUrl) {
@@ -21,26 +21,26 @@ export async function validateOptions(options) {
21
21
  // SSRF defense: validate scheme, IP, and allow-private flag
22
22
  ssrfWarning = await validateOsvUrl(options.osvUrl, !!options.allowPrivateOsvUrl);
23
23
  }
24
+ if (options.createPr && options.json) {
25
+ throw new Error("--create-pr cannot be used with --json. Use --create-pr to open a pull request for applied fixes, or --json to save scan results as JSON, not both.");
26
+ }
24
27
  if (options.fix && options.json) {
25
- throw new Error("--fix cannot be used with --json");
28
+ throw new Error("--fix cannot be used with --json. Use --fix to apply validated fixes and rescan, or --json to save scan results as JSON, not both.");
26
29
  }
27
30
  if (options.fix && options.sarif) {
28
- throw new Error("--fix cannot be used with --sarif");
31
+ throw new Error("--fix cannot be used with --sarif. Use --fix to apply validated fixes and rescan, or --sarif to save scan results as SARIF, not both.");
29
32
  }
30
33
  if (options.fix && options.cdx) {
31
- throw new Error("--fix cannot be used with --cdx");
34
+ throw new Error("--fix cannot be used with --cdx. Use --fix to apply validated fixes and rescan, or --cdx to save a CycloneDX SBOM, not both.");
32
35
  }
33
36
  if (options.createPr && !options.fix) {
34
- throw new Error("--create-pr requires --fix");
35
- }
36
- if (options.createPr && options.json) {
37
- throw new Error("--create-pr cannot be used with --json");
37
+ throw new Error("--create-pr requires --fix. Add --fix to apply validated fixes before opening a pull request, or remove --create-pr.");
38
38
  }
39
39
  if (options.prBase && !options.createPr) {
40
- throw new Error("--base can only be used with --create-pr");
40
+ throw new Error("--base can only be used with --create-pr. Add --create-pr to select its target branch, or remove --base.");
41
41
  }
42
42
  if (options.report && options.json) {
43
- throw new Error("--report cannot be used with --json");
43
+ throw new Error("--report cannot be used with --json. Use --report to generate an HTML report, or --json to save scan results as JSON, not both.");
44
44
  }
45
45
  if (options.caCert) {
46
46
  try {
@@ -0,0 +1,26 @@
1
+ const EPSS_API_URL = "https://api.first.org/data/v1/epss";
2
+ export async function fetchEpssScores(cveIds, fetchImpl = fetch) {
3
+ const unique = [...new Set(cveIds.map(id => id.toUpperCase()).filter(id => id.startsWith("CVE-")))];
4
+ if (unique.length === 0)
5
+ return new Map();
6
+ try {
7
+ const url = `${EPSS_API_URL}?cve=${unique.join(",")}`;
8
+ const response = await fetchImpl(url);
9
+ if (!response.ok)
10
+ return new Map();
11
+ const json = await response.json();
12
+ const result = new Map();
13
+ for (const item of json.data ?? []) {
14
+ const epss = parseFloat(item.epss);
15
+ const percentile = parseFloat(item.percentile);
16
+ if (!isNaN(epss) && !isNaN(percentile)) {
17
+ const cve = item.cve.toUpperCase();
18
+ result.set(cve, { cve, epss, percentile });
19
+ }
20
+ }
21
+ return result;
22
+ }
23
+ catch {
24
+ return new Map();
25
+ }
26
+ }
package/dist/index.js CHANGED
@@ -29,6 +29,8 @@ import { printActionSummary, printCompactOutput, printCoverage, printFinalStatus
29
29
  import { renderOverrideFindings } from "./output/override-findings-terminal.js";
30
30
  import { detectDM001 } from "./maintenance/dm001-maintenance-risk.js";
31
31
  import { renderMaintenanceFindings } from "./output/maintenance-terminal.js";
32
+ import { detectLicenseIssues } from "./licenses/license-check.js";
33
+ import { renderLicenseFindings } from "./output/license-terminal.js";
32
34
  import { installSkill } from "./skills/install.js";
33
35
  import { readConfig, validateCaCertFile } from "./cli/config.js";
34
36
  import { runConfigCommand } from "./cli/config-command.js";
@@ -40,7 +42,7 @@ import { hasRootLockfile, findNestedLockfiles } from "./parsers/multi-package.js
40
42
  import { handleMultiFolderScan } from "./scan/multi-folder-scan.js";
41
43
  import { collectAdvisoryIdsForPackage, createPullRequestForFixes, } from "./utils/create-pr.js";
42
44
  import { readBaseline, writeBaseline, filterNewFindings, ratchetOutcome } from "./utils/baseline.js";
43
- import { formatDiagnosticMessage, getCompletenessImpact } from "./scan/completeness.js";
45
+ import { formatDiagnosticMessage, getCompletenessImpact, shouldFailForIncompleteScan } from "./scan/completeness.js";
44
46
  let parsedArgs = null;
45
47
  try {
46
48
  parsedArgs = parseArgs(process.argv.slice(2));
@@ -351,6 +353,8 @@ if (parsedArgs) {
351
353
  overrideFindings = auditResult.findings;
352
354
  }
353
355
  let maintenanceFindings = [];
356
+ let licenseFindings = [];
357
+ let licenseLimitedToDirectOnly = false;
354
358
  // Emit cve.detected for each CVE finding
355
359
  for (const f of scanState.sorted) {
356
360
  auditLogHandle.emit({
@@ -617,6 +621,18 @@ if (parsedArgs) {
617
621
  const directDependencies = scanState.allPackages.filter(p => directNames?.has(p.name));
618
622
  maintenanceFindings = await detectDM001(scanState.sorted, directDependencies, !!options.offline || !!options.offlineDb);
619
623
  }
624
+ if (options.checkLicenses) {
625
+ const directNames = readDirectDependencyNames(projectPath, !!options.prodOnly);
626
+ const directDeps = scanState.allPackages.filter(p => directNames?.has(p.name));
627
+ const licenseResult = await detectLicenseIssues({
628
+ lockfilePath: scanInput.filePath,
629
+ directDeps,
630
+ isNpm: scanInput.source === "package-lock" || scanInput.source === "npm-shrinkwrap",
631
+ isOffline: !!options.offline || !!options.offlineDb,
632
+ });
633
+ licenseFindings = licenseResult.findings;
634
+ licenseLimitedToDirectOnly = licenseResult.limitedToDirectOnly;
635
+ }
620
636
  await writeOutputs(options, {
621
637
  sorted: scanState.sorted,
622
638
  allPackages: scanState.allPackages,
@@ -627,6 +643,8 @@ if (parsedArgs) {
627
643
  completeness: scanState.completeness,
628
644
  overrideFindings,
629
645
  maintenanceFindings,
646
+ licenseFindings,
647
+ licenseLimitedToDirectOnly,
630
648
  }, scanInput, projectPath);
631
649
  if (!(options.json || options.sarif || options.cdx) || options.verbose) {
632
650
  const offline = !!options.offline || !!options.offlineDb;
@@ -658,6 +676,9 @@ if (parsedArgs) {
658
676
  if (options.checkMaintenance && maintenanceFindings.length > 0) {
659
677
  console.log("\n" + renderMaintenanceFindings(maintenanceFindings, { verbose: true }));
660
678
  }
679
+ if (options.checkLicenses) {
680
+ console.log("\n" + renderLicenseFindings(licenseFindings, { limitedToDirectOnly: licenseLimitedToDirectOnly }));
681
+ }
661
682
  printCoverage([...scanInput.notes, ...scanState.coverage]);
662
683
  printFinalStatus(scanState.sorted, overrideCount, scanState.completeness);
663
684
  if (showOverrideHint)
@@ -672,6 +693,8 @@ if (parsedArgs) {
672
693
  all: !!options.all,
673
694
  packageManager: compactPmLabel,
674
695
  completeness: scanState.completeness,
696
+ licenseFindings: options.checkLicenses ? licenseFindings : undefined,
697
+ licenseLimitedToDirectOnly: options.checkLicenses ? licenseLimitedToDirectOnly : undefined,
675
698
  });
676
699
  if (options.checkOverrides) {
677
700
  console.log("\n" + renderOverrideFindings(overrideFindings, { verbose: false, projectPath }));
@@ -702,6 +725,8 @@ if (parsedArgs) {
702
725
  overrideFindings: options.checkOverrides ? overrideFindings : undefined,
703
726
  // Same undefined-vs-[] convention as overrideFindings above.
704
727
  maintenanceFindings: options.checkMaintenance ? maintenanceFindings : undefined,
728
+ licenseFindings: options.checkLicenses ? licenseFindings : undefined,
729
+ licenseLimitedToDirectOnly: options.checkLicenses ? licenseLimitedToDirectOnly : undefined,
705
730
  completeness: scanState.completeness,
706
731
  });
707
732
  const { reportPath } = await writeHtmlReport({
@@ -735,7 +760,12 @@ if (parsedArgs) {
735
760
  reachesFailOn(maintenanceFindings, options.failOn);
736
761
  // In fix mode, remaining transitive findings cannot be auto-fixed.
737
762
  // Exiting non-zero would prevent the Action PR step from running.
738
- const exitCode = shouldFail && !options.fix ? 1 : 0;
763
+ const incompleteFailure = shouldFailForIncompleteScan(scanState.completeness, options.incompletePolicy);
764
+ const exitCode = incompleteFailure
765
+ ? EXIT_ERROR
766
+ : shouldFail && !options.fix
767
+ ? 1
768
+ : 0;
739
769
  // Emit scan.finished event and close audit-log
740
770
  auditLogHandle.emit({
741
771
  ts: new Date().toISOString(),
@@ -0,0 +1,137 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { fetchPackument } from "../remediation/npm-registry.js";
3
+ import { runWithConcurrency } from "../utils/array.js";
4
+ /**
5
+ * SPDX identifiers for copyleft licenses. Checked case-insensitively against
6
+ * individual tokens in a license expression so compound expressions like
7
+ * "(GPL-2.0 OR MIT)" are correctly flagged.
8
+ */
9
+ const COPYLEFT_SPDX = new Set([
10
+ "GPL-2.0",
11
+ "GPL-2.0-ONLY",
12
+ "GPL-2.0-OR-LATER",
13
+ "GPL-3.0",
14
+ "GPL-3.0-ONLY",
15
+ "GPL-3.0-OR-LATER",
16
+ "AGPL-3.0",
17
+ "AGPL-3.0-ONLY",
18
+ "AGPL-3.0-OR-LATER",
19
+ "LGPL-2.0",
20
+ "LGPL-2.0-ONLY",
21
+ "LGPL-2.0-OR-LATER",
22
+ "LGPL-2.1",
23
+ "LGPL-2.1-ONLY",
24
+ "LGPL-2.1-OR-LATER",
25
+ "LGPL-3.0",
26
+ "LGPL-3.0-ONLY",
27
+ "LGPL-3.0-OR-LATER",
28
+ ]);
29
+ const LICENSE_CHECK_CONCURRENCY = 10;
30
+ /**
31
+ * Returns true when the license string contains at least one copyleft SPDX
32
+ * identifier. Handles compound expressions like "(GPL-2.0 OR MIT)" by splitting
33
+ * on whitespace and parentheses.
34
+ */
35
+ export function isCopyleft(license) {
36
+ const tokens = license.split(/[\s()]+/).filter(Boolean);
37
+ return tokens.some((t) => COPYLEFT_SPDX.has(t.toUpperCase().replace(/\+$/, "")));
38
+ }
39
+ /**
40
+ * Returns true when the license field is absent, empty, "UNLICENSED", or defers
41
+ * to an external file ("SEE LICENSE IN ..."). These are all legally ambiguous.
42
+ */
43
+ export function isUnknownLicense(license) {
44
+ if (license == null || license.trim() === "")
45
+ return true;
46
+ const upper = license.trim().toUpperCase();
47
+ return upper === "UNLICENSED" || upper.startsWith("SEE LICENSE IN");
48
+ }
49
+ function sortLicenseFindings(findings) {
50
+ return findings.sort((a, b) => {
51
+ if (a.severity !== b.severity)
52
+ return a.severity === "high" ? -1 : 1;
53
+ return a.package.name.localeCompare(b.package.name);
54
+ });
55
+ }
56
+ function lcFinding(ruleId, name, version, license, relationship) {
57
+ const message = ruleId === "LC001"
58
+ ? `Copyleft license: ${license}`
59
+ : "No license declared - legally ambiguous";
60
+ return {
61
+ ruleId,
62
+ severity: ruleId === "LC001" ? "high" : "medium",
63
+ package: { name, version },
64
+ license,
65
+ relationship,
66
+ message,
67
+ };
68
+ }
69
+ /**
70
+ * Scans an npm lockfile v2/v3 packages map for copyleft (LC001) and unknown
71
+ * (LC002) licenses. Reads the license field directly from the lockfile - no
72
+ * network calls, works offline.
73
+ *
74
+ * The root entry (empty-string key) is always skipped. A package is "direct"
75
+ * when its bare name appears in the root entry's dependencies,
76
+ * devDependencies, or optionalDependencies.
77
+ */
78
+ export function detectNpmLicenses(rawPackages) {
79
+ const directNames = new Set();
80
+ const root = (rawPackages[""] ?? {});
81
+ for (const section of ["dependencies", "devDependencies", "optionalDependencies"]) {
82
+ for (const name of Object.keys(root[section] ?? {})) {
83
+ directNames.add(name);
84
+ }
85
+ }
86
+ const findings = [];
87
+ for (const [pkgPath, meta] of Object.entries(rawPackages)) {
88
+ if (!pkgPath || !pkgPath.includes("node_modules/"))
89
+ continue;
90
+ const typedMeta = meta;
91
+ const name = pkgPath.slice(pkgPath.lastIndexOf("node_modules/") + "node_modules/".length);
92
+ const version = typedMeta?.["version"];
93
+ if (!name || !version)
94
+ continue;
95
+ const license = typedMeta?.["license"] ?? null;
96
+ const relationship = directNames.has(name)
97
+ ? "direct"
98
+ : "transitive";
99
+ if (isUnknownLicense(license)) {
100
+ findings.push(lcFinding("LC002", name, version, null, relationship));
101
+ }
102
+ else if (isCopyleft(license)) {
103
+ findings.push(lcFinding("LC001", name, version, license, relationship));
104
+ }
105
+ }
106
+ return sortLicenseFindings(findings);
107
+ }
108
+ async function checkPackumentLicense(dep) {
109
+ try {
110
+ const packument = await fetchPackument(dep.name);
111
+ const license = packument?.license ?? null;
112
+ if (isUnknownLicense(license)) {
113
+ return lcFinding("LC002", dep.name, dep.version, null, "direct");
114
+ }
115
+ if (license && isCopyleft(license)) {
116
+ return lcFinding("LC001", dep.name, dep.version, license, "direct");
117
+ }
118
+ return null;
119
+ }
120
+ catch {
121
+ return null;
122
+ }
123
+ }
124
+ export async function detectLicenseIssues(opts) {
125
+ const { lockfilePath, directDeps, isNpm, isOffline } = opts;
126
+ if (isNpm && lockfilePath) {
127
+ const raw = JSON.parse(readFileSync(lockfilePath, "utf8"));
128
+ const rawPackages = (raw?.["packages"] ?? {});
129
+ return { findings: detectNpmLicenses(rawPackages), limitedToDirectOnly: false };
130
+ }
131
+ if (isOffline) {
132
+ return { findings: [], limitedToDirectOnly: true };
133
+ }
134
+ const results = await runWithConcurrency([...directDeps], LICENSE_CHECK_CONCURRENCY, checkPackumentLicense);
135
+ const findings = sortLicenseFindings(results.filter((f) => f !== null));
136
+ return { findings, limitedToDirectOnly: true };
137
+ }
@@ -0,0 +1 @@
1
+ export {};
package/dist/osv/cache.js CHANGED
@@ -3,7 +3,7 @@ import path from "node:path";
3
3
  import os from "node:os";
4
4
  import { CACHE_TTL_MS } from "../constants.js";
5
5
  function createEmptyCache() {
6
- return { version: 4, createdAt: new Date().toISOString(), entries: {}, queryEntries: {}, npmVersionEntries: {} };
6
+ return { version: 5, createdAt: new Date().toISOString(), entries: {}, queryEntries: {}, npmVersionEntries: {}, npmAdvisoryEntries: {} };
7
7
  }
8
8
  // v4 stores detail records as { vuln, cachedAt }. v1-v3 stored the OsvVuln (or
9
9
  // null for a known-empty lookup) directly, with no timestamp. Legacy records are
@@ -55,10 +55,10 @@ export function loadCache(cacheDirOverride, debugLog) {
55
55
  }
56
56
  const version = parsed.version;
57
57
  const rawEntries = parsed.entries;
58
- // Detail records: v4 already carries { vuln, cachedAt }; v1-v3 stored the record
58
+ // Detail records: v4 and v5 already carry { vuln, cachedAt }; v1-v3 stored the record
59
59
  // directly and are wrapped (and backdated) so the TTL applies uniformly.
60
- const entries = version === 4 ? readDetailEntries(rawEntries) : wrapLegacyDetailEntries(rawEntries);
61
- // Query records: v2 stored string[]; v3 and v4 store { vulnIds, cachedAt }; v1/unknown had none.
60
+ const entries = version === 4 || version === 5 ? readDetailEntries(rawEntries) : wrapLegacyDetailEntries(rawEntries);
61
+ // Query records: v2 stored string[]; v3, v4, and v5 store { vulnIds, cachedAt }; v1/unknown had none.
62
62
  const queryEntries = {};
63
63
  if (version === 2) {
64
64
  const rawQuery = parsed.queryEntries;
@@ -67,7 +67,7 @@ export function loadCache(cacheDirOverride, debugLog) {
67
67
  queryEntries[key] = { vulnIds: Array.isArray(vulnIds) ? vulnIds : [], cachedAt: epoch };
68
68
  }
69
69
  }
70
- else if (version === 3 || version === 4) {
70
+ else if (version === 3 || version === 4 || version === 5) {
71
71
  const rawQuery = parsed.queryEntries;
72
72
  for (const [key, value] of Object.entries(rawQuery ?? {})) {
73
73
  if (value && typeof value === "object" && "vulnIds" in value && "cachedAt" in value) {
@@ -77,7 +77,7 @@ export function loadCache(cacheDirOverride, debugLog) {
77
77
  }
78
78
  // npm publish-date records exist from v3 onward.
79
79
  const npmVersionEntries = {};
80
- if (version === 3 || version === 4) {
80
+ if (version === 3 || version === 4 || version === 5) {
81
81
  const rawNpmVersions = parsed.npmVersionEntries;
82
82
  for (const [key, value] of Object.entries(rawNpmVersions ?? {})) {
83
83
  if (value && typeof value === "object" && "publishedAt" in value && "cachedAt" in value) {
@@ -85,18 +85,29 @@ export function loadCache(cacheDirOverride, debugLog) {
85
85
  }
86
86
  }
87
87
  }
88
+ // npm advisory entries exist from v5 onward.
89
+ const npmAdvisoryEntries = {};
90
+ if (version === 5) {
91
+ const raw = parsed.npmAdvisoryEntries;
92
+ for (const [key, value] of Object.entries(raw ?? {})) {
93
+ if (value && typeof value === "object" && "vulnIds" in value && "cachedAt" in value) {
94
+ npmAdvisoryEntries[key] = value;
95
+ }
96
+ }
97
+ }
88
98
  const loaded = {
89
- version: 4,
99
+ version: 5,
90
100
  createdAt: String(parsed.createdAt ?? new Date().toISOString()),
91
101
  entries,
92
102
  queryEntries,
93
103
  npmVersionEntries,
104
+ npmAdvisoryEntries,
94
105
  };
95
106
  debugLog?.("Cache loaded", {
96
107
  path: filePath,
97
108
  queryEntries: Object.keys(loaded.queryEntries).length,
98
109
  detailEntries: Object.keys(loaded.entries).length,
99
- ...(version === 4 ? {} : { migratedFrom: version ?? "unknown" }),
110
+ ...(version === 5 ? {} : { migratedFrom: version ?? "unknown" }),
100
111
  });
101
112
  return loaded;
102
113
  }
@@ -241,6 +241,7 @@ export function serializeFinding(finding, plan) {
241
241
  recommendedParentUpgrade: finding.recommendedParentUpgrade,
242
242
  recommendedNpmTransitiveRemediation: finding.recommendedNpmTransitiveRemediation ?? null,
243
243
  cves: finding.cveAliases,
244
+ epssScores: finding.epssScores ?? null,
244
245
  dependencyPaths: finding.dependencyPaths,
245
246
  usage: finding.usage ?? null,
246
247
  maliciousUnverifiable: finding.maliciousUnverifiable ?? false,