cve-lite-cli 1.25.0 → 1.26.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 (39) hide show
  1. package/README.md +38 -13
  2. package/assets/OWASP_Logo_Black_TM.png +0 -0
  3. package/assets/logo-with-title-removebg-preview.png +0 -0
  4. package/dist/advisory/local-db.js +7 -1
  5. package/dist/advisory/osv-advisory-source.js +2 -1
  6. package/dist/cli/args.js +4 -0
  7. package/dist/cli/help.js +2 -1
  8. package/dist/cli/overrides.js +1 -1
  9. package/dist/cli/validate.js +9 -1
  10. package/dist/index.js +47 -16
  11. package/dist/osv/cache.js +5 -1
  12. package/dist/output/formatters.js +0 -15
  13. package/dist/output/html-reporter.js +11 -12
  14. package/dist/output/logos.js +18 -0
  15. package/dist/output/multi-folder-html-reporter.js +3 -4
  16. package/dist/output/override-findings-html.js +10 -4
  17. package/dist/output/override-findings-terminal.js +90 -21
  18. package/dist/output/printers.js +42 -16
  19. package/dist/parsers/pnpm-lock.js +46 -3
  20. package/dist/remediation/npm-registry.js +55 -73
  21. package/dist/scan/multi-folder-scan.js +13 -3
  22. package/dist/scanner.js +79 -59
  23. package/dist/utils/create-pr.js +1 -0
  24. package/dist/utils/fix-runner.js +6 -0
  25. package/dist/utils/package-json.js +21 -0
  26. package/dist/utils/severity.js +16 -0
  27. package/dist/utils/validate-url.js +223 -0
  28. package/dist/utils/version.js +20 -2
  29. package/package.json +6 -2
  30. package/dist/learn/keypress.js +0 -50
  31. package/dist/learn/runner.js +0 -96
  32. package/dist/learn/scenario.js +0 -47
  33. package/dist/learn/session.js +0 -36
  34. package/dist/learn/types.js +0 -1
  35. package/dist/llm/client.js +0 -40
  36. package/dist/llm/config.js +0 -48
  37. package/dist/llm/explainer.js +0 -31
  38. package/dist/output/logo-base64.js +0 -1
  39. package/dist/output/owasp-logo-base64.js +0 -1
package/dist/scanner.js CHANGED
@@ -9,7 +9,7 @@ import { LocalAdvisorySource } from "./advisory/local-advisory-source.js";
9
9
  import { LocalAdvisoryDatabase } from "./advisory/local-db.js";
10
10
  import { ADVISORY_DB_STALE_AFTER_MS, getDefaultAdvisoryDbPath } from "./advisory/osv-sync.js";
11
11
  import { resolveRecommendedParentUpgrade } from "./remediation/parent-upgrade.js";
12
- import { configureNpmRegistryDebug, fetchPackument, resolveLowestKnownNonVulnerableVersion, resolvePublishedFixVersion, resolveVersionPublishDate, } from "./remediation/npm-registry.js";
12
+ import { configureNpmRegistryDebug, fetchPackument, resolveLowestKnownNonVulnerableVersion, resolvePublishedFixVersion, } from "./remediation/npm-registry.js";
13
13
  import { countBySeverity } from "./utils/severity.js";
14
14
  import { resolveNpmTransitiveRemediation, resolveTransitiveRemediationViaRegistry } from "./remediation/npm-transitive-resolution.js";
15
15
  import { resolveChainFix } from "./remediation/transitive-chain-resolver.js";
@@ -108,6 +108,7 @@ export async function scanPackages(packages, batchSize, options, context, debugL
108
108
  const batchId = `b-${String(batchCounter).padStart(2, "0")}`;
109
109
  return advisorySource.queryBatch(c, { batchId });
110
110
  });
111
+ const cachedAt = new Date().toISOString();
111
112
  for (let i = 0; i < chunks.length; i++) {
112
113
  const chunkItems = chunks[i];
113
114
  const rows = allAdvisoryResults[i] ?? [];
@@ -115,7 +116,7 @@ export async function scanPackages(packages, batchSize, options, context, debugL
115
116
  const pkg = chunkItems[j];
116
117
  const row = rows[j];
117
118
  const vulnIds = (row?.vulnerabilities ?? []).map(v => v.id).filter(Boolean);
118
- cache.queryEntries[getPackageCacheKey(pkg)] = { vulnIds, cachedAt: new Date().toISOString() };
119
+ cache.queryEntries[getPackageCacheKey(pkg)] = { vulnIds, cachedAt };
119
120
  if (vulnIds.length > 0) {
120
121
  results.push({ pkg, vulnIds });
121
122
  }
@@ -310,7 +311,15 @@ export async function scanPackages(packages, batchSize, options, context, debugL
310
311
  const npmRemediationCache = new Map();
311
312
  const parentUpgradeCache = new Map();
312
313
  const directValidationCount = offline ? 0 : findings.length;
313
- const transitiveRemediationCount = findings.filter(finding => finding.relationship === "transitive").length;
314
+ let directCount = 0;
315
+ let transitiveCount = 0;
316
+ for (const finding of findings) {
317
+ if (finding.relationship === "direct")
318
+ directCount++;
319
+ else if (finding.relationship === "transitive")
320
+ transitiveCount++;
321
+ }
322
+ const transitiveRemediationCount = transitiveCount;
314
323
  const analysisStepCount = directValidationCount + transitiveRemediationCount;
315
324
  if (analysisStepCount > 0) {
316
325
  const analysisSpinner = createSpinner("Analyzing vulnerability findings...", options);
@@ -463,8 +472,8 @@ export async function scanPackages(packages, batchSize, options, context, debugL
463
472
  const severityCounts = countBySeverity(findings);
464
473
  log("Findings classified", {
465
474
  total: findings.length,
466
- direct: findings.filter(finding => finding.relationship === "direct").length,
467
- transitive: findings.filter(finding => finding.relationship === "transitive").length,
475
+ direct: directCount,
476
+ transitive: transitiveCount,
468
477
  critical: severityCounts.critical,
469
478
  high: severityCounts.high,
470
479
  medium: severityCounts.medium,
@@ -513,73 +522,84 @@ function createNpmTransitiveGraphFromLockfile(filePath, log, packageCount) {
513
522
  }
514
523
  async function validateDirectFixTargets(findings, onFinding, options) {
515
524
  const directCandidates = findings.filter(finding => finding.vulnerabilities.length > 0);
525
+ const results = await runWithConcurrency(directCandidates, 8, async (finding) => {
526
+ onFinding?.(finding);
527
+ return validateOneDirectFixTarget(finding, options);
528
+ });
529
+ return results.some(Boolean);
530
+ }
531
+ async function validateOneDirectFixTarget(finding, options) {
516
532
  let npmVersionCacheUpdated = false;
517
533
  const debugLog = options?.debugLog;
518
- for (const finding of directCandidates) {
519
- onFinding?.(finding);
520
- const logFixValidation = () => {
521
- debugLog?.("Fix validation", {
522
- package: finding.pkg.name,
523
- installed: finding.pkg.version,
524
- resolvedFixVersion: finding.validatedFirstFixedVersion,
525
- verified: Boolean(finding.validatedFirstFixedVersion),
526
- });
534
+ const logFixValidation = () => {
535
+ debugLog?.("Fix validation", {
536
+ package: finding.pkg.name,
537
+ installed: finding.pkg.version,
538
+ resolvedFixVersion: finding.validatedFirstFixedVersion,
539
+ verified: Boolean(finding.validatedFirstFixedVersion),
540
+ });
541
+ };
542
+ const lowestKnownResolution = await resolveLowestKnownNonVulnerableVersion(finding.pkg.name, finding.pkg.version, finding.vulnerabilities);
543
+ const fixedVersionHint = finding.firstFixedVersion;
544
+ const setPublishedDate = (resolution) => {
545
+ const date = resolution.publishedAt;
546
+ finding.fixVersionPublishedAt = date;
547
+ if (!date || !options?.cache)
548
+ return;
549
+ const cacheKey = `${finding.pkg.name}@${finding.validatedFirstFixedVersion}`;
550
+ const existing = options.cache.npmVersionEntries?.[cacheKey];
551
+ if (!options.noCache && existing?.publishedAt === date)
552
+ return;
553
+ options.cache.npmVersionEntries ??= {};
554
+ options.cache.npmVersionEntries[cacheKey] = {
555
+ publishedAt: date,
556
+ cachedAt: new Date().toISOString(),
527
557
  };
528
- const lowestKnownResolution = await resolveLowestKnownNonVulnerableVersion(finding.pkg.name, finding.pkg.version, finding.vulnerabilities);
529
- const fixedVersionHint = finding.firstFixedVersion;
530
- if (lowestKnownResolution.resolvedVersion) {
531
- finding.validatedFirstFixedVersion = lowestKnownResolution.resolvedVersion;
532
- finding.validatedTargetScannedVersions = lowestKnownResolution.candidatesChecked;
533
- finding.validatedTargetKnownVulnerableVersions = lowestKnownResolution.candidatesKnownVulnerable;
534
- if (!fixedVersionHint || fixedVersionHint === lowestKnownResolution.resolvedVersion) {
535
- finding.fixVersionValidationNote = null;
536
- npmVersionCacheUpdated = await attachFixVersionPublishDate(finding, options) || npmVersionCacheUpdated;
537
- logFixValidation();
538
- continue;
539
- }
540
- const hintResolution = await resolvePublishedFixVersion(finding.pkg.name, fixedVersionHint);
541
- if (hintResolution.resolvedVersion === lowestKnownResolution.resolvedVersion &&
542
- hintResolution.note) {
543
- finding.fixVersionValidationNote = hintResolution.note;
544
- npmVersionCacheUpdated = await attachFixVersionPublishDate(finding, options) || npmVersionCacheUpdated;
545
- logFixValidation();
546
- continue;
547
- }
548
- finding.fixVersionValidationNote =
549
- `Advisory fixed-version hint ${fixedVersionHint} is still known vulnerable for ${finding.pkg.name}; scanned ${lowestKnownResolution.candidatesChecked} package ${pluralize(lowestKnownResolution.candidatesChecked, "version")} above current version (${lowestKnownResolution.candidatesKnownVulnerable} still known vulnerable); using lowest known non-vulnerable version ${lowestKnownResolution.resolvedVersion}.`;
550
- npmVersionCacheUpdated = await attachFixVersionPublishDate(finding, options) || npmVersionCacheUpdated;
558
+ npmVersionCacheUpdated = true;
559
+ };
560
+ if (lowestKnownResolution.resolvedVersion) {
561
+ finding.validatedFirstFixedVersion = lowestKnownResolution.resolvedVersion;
562
+ finding.validatedTargetScannedVersions = lowestKnownResolution.candidatesChecked;
563
+ finding.validatedTargetKnownVulnerableVersions = lowestKnownResolution.candidatesKnownVulnerable;
564
+ if (!fixedVersionHint || fixedVersionHint === lowestKnownResolution.resolvedVersion) {
565
+ finding.fixVersionValidationNote = null;
566
+ setPublishedDate(lowestKnownResolution);
551
567
  logFixValidation();
552
- continue;
568
+ return npmVersionCacheUpdated;
553
569
  }
554
- if (!fixedVersionHint) {
555
- finding.validatedFirstFixedVersion = null;
556
- finding.fixVersionValidationNote = lowestKnownResolution.note;
557
- finding.validatedTargetScannedVersions = null;
558
- finding.validatedTargetKnownVulnerableVersions = null;
559
- finding.fixVersionPublishedAt = null;
570
+ const hintResolution = await resolvePublishedFixVersion(finding.pkg.name, fixedVersionHint);
571
+ if (hintResolution.resolvedVersion === lowestKnownResolution.resolvedVersion &&
572
+ hintResolution.note) {
573
+ finding.fixVersionValidationNote = hintResolution.note;
574
+ // date is for the validated version, not the hint
575
+ setPublishedDate(lowestKnownResolution);
560
576
  logFixValidation();
561
- continue;
577
+ return npmVersionCacheUpdated;
562
578
  }
563
- const resolution = await resolvePublishedFixVersion(finding.pkg.name, fixedVersionHint);
564
- finding.validatedFirstFixedVersion = resolution.resolvedVersion;
565
- finding.fixVersionValidationNote = resolution.note ?? lowestKnownResolution.note;
579
+ finding.fixVersionValidationNote =
580
+ `Advisory fixed-version hint ${fixedVersionHint} is still known vulnerable for ${finding.pkg.name}; scanned ${lowestKnownResolution.candidatesChecked} package ${pluralize(lowestKnownResolution.candidatesChecked, "version")} above current version (${lowestKnownResolution.candidatesKnownVulnerable} still known vulnerable); using lowest known non-vulnerable version ${lowestKnownResolution.resolvedVersion}.`;
581
+ setPublishedDate(lowestKnownResolution);
582
+ logFixValidation();
583
+ return npmVersionCacheUpdated;
584
+ }
585
+ if (!fixedVersionHint) {
586
+ finding.validatedFirstFixedVersion = null;
587
+ finding.fixVersionValidationNote = lowestKnownResolution.note;
566
588
  finding.validatedTargetScannedVersions = null;
567
589
  finding.validatedTargetKnownVulnerableVersions = null;
568
- npmVersionCacheUpdated = await attachFixVersionPublishDate(finding, options) || npmVersionCacheUpdated;
590
+ finding.fixVersionPublishedAt = null;
569
591
  logFixValidation();
592
+ return npmVersionCacheUpdated;
570
593
  }
594
+ const resolution = await resolvePublishedFixVersion(finding.pkg.name, fixedVersionHint);
595
+ finding.validatedFirstFixedVersion = resolution.resolvedVersion;
596
+ finding.fixVersionValidationNote = resolution.note ?? lowestKnownResolution.note;
597
+ finding.validatedTargetScannedVersions = null;
598
+ finding.validatedTargetKnownVulnerableVersions = null;
599
+ setPublishedDate(resolution);
600
+ logFixValidation();
571
601
  return npmVersionCacheUpdated;
572
602
  }
573
- async function attachFixVersionPublishDate(finding, options) {
574
- const version = finding.validatedFirstFixedVersion;
575
- if (!version) {
576
- finding.fixVersionPublishedAt = null;
577
- return false;
578
- }
579
- const { publishedAt, cacheWritten } = await resolveVersionPublishDate(finding.pkg.name, version, options);
580
- finding.fixVersionPublishedAt = publishedAt;
581
- return cacheWritten;
582
- }
583
603
  function isAdvisoryDbStale(metadata) {
584
604
  if (!metadata.lastSyncAt) {
585
605
  return true;
@@ -10,6 +10,7 @@ const DEPENDENCY_FILES_TO_STAGE = [
10
10
  "yarn.lock",
11
11
  "pnpm-lock.yaml",
12
12
  "bun.lock",
13
+ "bun.lockb",
13
14
  "npm-shrinkwrap.json",
14
15
  ];
15
16
  export function findingsMeetFailOnThreshold(findings, failOn) {
@@ -1,4 +1,6 @@
1
1
  import { spawn } from "node:child_process";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
2
4
  import { createSpinner } from "../output/spinner.js";
3
5
  import { chalk } from "./chalk.js";
4
6
  import { pluralize } from "./string.js";
@@ -43,6 +45,10 @@ export function commandLabelForPackageManager(packageManager) {
43
45
  return "bun add";
44
46
  return "yarn add";
45
47
  }
48
+ export function writeFixResultJson(json, projectPath) {
49
+ const outPath = path.join(projectPath, "cve-lite-fix-result.json");
50
+ fs.writeFileSync(outPath, JSON.stringify(json, null, 2), "utf8");
51
+ }
46
52
  export async function applyFixesIfRequested(params) {
47
53
  console.log("");
48
54
  console.log(chalk.bold.cyan("Applying fixes (--fix)"));
@@ -122,3 +122,24 @@ function expandWorkspacePattern(projectPath, segments, currentRelativePath) {
122
122
  export function isRecord(value) {
123
123
  return !!value && typeof value === "object" && !Array.isArray(value);
124
124
  }
125
+ export function hasOverrideEntries(dir) {
126
+ const pkgPath = path.join(dir, "package.json");
127
+ if (!fs.existsSync(pkgPath))
128
+ return false;
129
+ try {
130
+ const raw = JSON.parse(fs.readFileSync(pkgPath, "utf8"));
131
+ if (!raw || typeof raw !== "object")
132
+ return false;
133
+ if (isRecord(raw.overrides) && Object.keys(raw.overrides).length > 0)
134
+ return true;
135
+ const pnpm = raw.pnpm;
136
+ if (isRecord(pnpm) && isRecord(pnpm.overrides) && Object.keys(pnpm.overrides).length > 0)
137
+ return true;
138
+ if (isRecord(raw.resolutions) && Object.keys(raw.resolutions).length > 0)
139
+ return true;
140
+ return false;
141
+ }
142
+ catch {
143
+ return false;
144
+ }
145
+ }
@@ -1,3 +1,19 @@
1
+ import { chalk } from "./chalk.js";
2
+ export const SEVERITY_ORDER = ["critical", "high", "medium", "low", "unknown", "none"];
3
+ export function formatSeverityLabel(severity) {
4
+ const lower = severity.toLowerCase();
5
+ if (lower === "critical")
6
+ return chalk.redBright(severity);
7
+ if (lower === "high")
8
+ return chalk.red(severity);
9
+ if (lower === "medium")
10
+ return chalk.yellow(severity);
11
+ if (lower === "low")
12
+ return chalk.blueBright(severity);
13
+ if (lower === "unknown")
14
+ return chalk.magenta(severity);
15
+ return severity;
16
+ }
1
17
  export function countBySeverity(findings) {
2
18
  const counts = {
3
19
  none: 0,
@@ -0,0 +1,223 @@
1
+ import dns from "node:dns";
2
+ import { URL } from "node:url";
3
+ const OFFICIAL_OSV_HOSTS = ["api.osv.dev"];
4
+ // IPv4 special-purpose CIDRs — numerical match replaces error-prone regex
5
+ // https://www.iana.org/assignments/iana-ipv4-special-registry/iana-ipv4-special-registry.xhtml
6
+ const PRIVATE_IPV4_CIDRS = [
7
+ "0.0.0.0/8", // "this network"
8
+ "10.0.0.0/8", // private Class A
9
+ "100.64.0.0/10", // CGNAT
10
+ "127.0.0.0/8", // loopback
11
+ "169.254.0.0/16", // link-local
12
+ "172.16.0.0/12", // private Class B
13
+ "192.168.0.0/16", // private Class C
14
+ "192.0.0.0/24", // IETF Protocol
15
+ "192.0.2.0/24", // documentation (TEST-NET-1)
16
+ "198.18.0.0/15", // benchmark
17
+ "198.51.100.0/24", // documentation (TEST-NET-2)
18
+ "203.0.113.0/24", // documentation (TEST-NET-3)
19
+ "224.0.0.0/4", // multicast
20
+ "240.0.0.0/4", // reserved
21
+ "255.255.255.255/32", // broadcast
22
+ ];
23
+ // IPv6 ranges that are non-global or can tunnel/translate requests to IPv4.
24
+ // https://www.iana.org/assignments/iana-ipv6-special-registry/iana-ipv6-special-registry.xhtml
25
+ const PRIVATE_IPV6_CIDRS = [
26
+ "::/96", // IPv4-compatible (deprecated), including unspecified and loopback
27
+ "64:ff9b::/96", // well-known NAT64
28
+ "64:ff9b:1::/48", // local-use NAT64
29
+ "100::/64", // discard-only
30
+ "100:0:0:1::/64", // dummy prefix
31
+ "2001::/32", // Teredo
32
+ "2001:2::/48", // benchmark
33
+ "2001:db8::/32", // documentation
34
+ "2002::/16", // 6to4
35
+ "3fff::/20", // documentation
36
+ "5f00::/16", // SRv6 SIDs
37
+ "fc00::/7", // unique-local
38
+ "fe80::/10", // link-local
39
+ "ff00::/8", // multicast
40
+ ];
41
+ // IPv4-mapped IPv6 prefix
42
+ const IPV4_MAPPED_PREFIX = "::ffff:";
43
+ function ipv4ToU32(ip) {
44
+ const parts = ip.split(".");
45
+ if (parts.length !== 4)
46
+ return undefined;
47
+ let n = 0;
48
+ for (const part of parts) {
49
+ if (!/^\d+$/.test(part))
50
+ return undefined;
51
+ const value = Number(part);
52
+ if (value < 0 || value > 255)
53
+ return undefined;
54
+ n = (n << 8) + value;
55
+ }
56
+ return n >>> 0;
57
+ }
58
+ function ipv4InCidr(ip, cidr) {
59
+ const [base, bitsText] = cidr.split("/");
60
+ const bits = Number(bitsText);
61
+ const ipNum = ipv4ToU32(ip);
62
+ const baseNum = ipv4ToU32(base);
63
+ if (ipNum === undefined || baseNum === undefined)
64
+ return false;
65
+ if (!Number.isInteger(bits) || bits < 0 || bits > 32)
66
+ return false;
67
+ const mask = bits === 0 ? 0 : (0xffffffff << (32 - bits)) >>> 0;
68
+ return (ipNum & mask) === (baseNum & mask);
69
+ }
70
+ function isPrivateOrReservedIpv4(ip) {
71
+ return PRIVATE_IPV4_CIDRS.some(cidr => ipv4InCidr(ip, cidr));
72
+ }
73
+ // Parse an IPv6 address string into a 128-bit BigInt.
74
+ // Handles standard notation, compressed '::', and IPv4-mapped forms.
75
+ function ipv6ToBigInt(ip) {
76
+ const lower = ip.toLowerCase();
77
+ // Handle dotted-decimal IPv4-mapped form. Hex forms such as
78
+ // ::ffff:7f00:1 are ordinary IPv6 and are parsed by the generic path below.
79
+ if (lower.startsWith(IPV4_MAPPED_PREFIX) && lower.includes(".")) {
80
+ const suffix = ip.slice(IPV4_MAPPED_PREFIX.length);
81
+ const v4num = ipv4ToU32(suffix);
82
+ if (v4num === undefined)
83
+ return null;
84
+ return (0xffffn << 32n) | BigInt(v4num);
85
+ }
86
+ // ::a.b.c.d (IPv4-compatible, deprecated but still parseable)
87
+ if (lower.startsWith("::") && !lower.startsWith("::ffff:") && lower.includes(".")) {
88
+ const v4num = ipv4ToU32(lower.slice(2));
89
+ if (v4num === undefined)
90
+ return null;
91
+ return BigInt(v4num);
92
+ }
93
+ // Standard IPv6: split on '::' to handle compression
94
+ const parts = lower.split("::");
95
+ if (parts.length > 2)
96
+ return null;
97
+ let head;
98
+ let tail = [];
99
+ if (parts.length === 2) {
100
+ head = parts[0] ? parts[0].split(":") : [];
101
+ tail = parts[1] ? parts[1].split(":") : [];
102
+ }
103
+ else {
104
+ head = lower.split(":");
105
+ }
106
+ const hasCompression = parts.length === 2;
107
+ const explicitGroupCount = head.length + tail.length;
108
+ if ((!hasCompression && explicitGroupCount !== 8) ||
109
+ (hasCompression && explicitGroupCount >= 8)) {
110
+ return null;
111
+ }
112
+ // Expand compressed form: fill middle with zeros
113
+ const groups = [];
114
+ for (const g of head) {
115
+ if (!/^[0-9a-f]{1,4}$/i.test(g))
116
+ return null;
117
+ const val = parseInt(g, 16);
118
+ groups.push(val);
119
+ }
120
+ // Fill middle with zeros
121
+ const missing = 8 - head.length - tail.length;
122
+ for (let i = 0; i < missing; i++)
123
+ groups.push(0);
124
+ for (const g of tail) {
125
+ if (!/^[0-9a-f]{1,4}$/i.test(g))
126
+ return null;
127
+ const val = parseInt(g, 16);
128
+ groups.push(val);
129
+ }
130
+ if (groups.length !== 8)
131
+ return null;
132
+ let result = 0n;
133
+ for (const g of groups) {
134
+ result = (result << 16n) | BigInt(g);
135
+ }
136
+ return result;
137
+ }
138
+ function ipv6InCidr(ip, cidr) {
139
+ const [baseText, prefixText] = cidr.split("/");
140
+ const addr = ipv6ToBigInt(ip);
141
+ const base = ipv6ToBigInt(baseText);
142
+ const prefixLen = Number(prefixText);
143
+ if (addr === null ||
144
+ base === null ||
145
+ !Number.isInteger(prefixLen) ||
146
+ prefixLen < 0 ||
147
+ prefixLen > 128) {
148
+ return false;
149
+ }
150
+ const mask = prefixLen === 0 ? 0n : (~0n << BigInt(128 - prefixLen));
151
+ return (addr & mask) === (base & mask);
152
+ }
153
+ function isPrivateOrReservedIpv6(ip) {
154
+ return PRIVATE_IPV6_CIDRS.some(cidr => ipv6InCidr(ip, cidr));
155
+ }
156
+ export function isOfficialOsv(url) {
157
+ try {
158
+ const parsed = new URL(url);
159
+ return OFFICIAL_OSV_HOSTS.includes(parsed.hostname);
160
+ }
161
+ catch {
162
+ return false;
163
+ }
164
+ }
165
+ export function isPrivateOrReservedIp(ip) {
166
+ // Fast-path: pure IPv4 CIDR match
167
+ if (ipv4ToU32(ip) !== undefined) {
168
+ return isPrivateOrReservedIpv4(ip);
169
+ }
170
+ // Parse as BigInt (handles all IPv6 forms including ::ffff: mapped)
171
+ const addr = ipv6ToBigInt(ip);
172
+ if (addr === null)
173
+ return false;
174
+ // IPv4-mapped: extract embedded IPv4 and check against IPv4 CIDRs
175
+ if ((addr >> 32n) === 0xffffn) {
176
+ const embedded = Number(addr & 0xffffffffn);
177
+ const dotted = `${(embedded >>> 24) & 0xff}.${(embedded >>> 16) & 0xff}.${(embedded >>> 8) & 0xff}.${embedded & 0xff}`;
178
+ return isPrivateOrReservedIpv4(dotted);
179
+ }
180
+ // Pure IPv6: CIDR numerical match
181
+ return isPrivateOrReservedIpv6(ip);
182
+ }
183
+ // Strip brackets from IPv6 literal hostnames (e.g. "[::1]" → "::1")
184
+ function stripIpv6Brackets(hostname) {
185
+ if (hostname.startsWith("[") && hostname.endsWith("]")) {
186
+ return hostname.slice(1, -1);
187
+ }
188
+ return hostname;
189
+ }
190
+ export async function validateOsvUrl(url, allowPrivate) {
191
+ const parsed = new URL(url);
192
+ // Layer 1: HTTPS only
193
+ if (parsed.protocol !== "https:") {
194
+ throw new Error(`--osv-url requires https:// scheme, got ${parsed.protocol}`);
195
+ }
196
+ // Skip IP check for official hosts
197
+ if (isOfficialOsv(url))
198
+ return undefined;
199
+ // Layer 2: Resolve DNS and check ALL addresses
200
+ // Strip brackets from IPv6 literal hostnames — dns.lookup expects bare addresses
201
+ const lookupHost = stripIpv6Brackets(parsed.hostname);
202
+ const addresses = await new Promise((resolve, reject) => {
203
+ dns.lookup(lookupHost, { all: true }, (err, addresses) => {
204
+ if (err)
205
+ reject(err);
206
+ else
207
+ resolve(addresses);
208
+ });
209
+ });
210
+ // Check ALL resolved addresses - reject if ANY is private/reserved
211
+ const privateAddresses = addresses.filter(addr => isPrivateOrReservedIp(addr.address));
212
+ if (privateAddresses.length > 0) {
213
+ const ipList = privateAddresses.map(a => a.address).join(", ");
214
+ if (!allowPrivate) {
215
+ throw new Error(`--osv-url resolves to private/reserved IP (${ipList}). ` +
216
+ `Use --allow-private-osv-url for internal mirrors.`);
217
+ }
218
+ // Layer 3: Explicit bypass — return warning for caller to emit
219
+ return (`Warning: --allow-private-osv-url is set. ` +
220
+ `Requests may access internal host (${ipList}).`);
221
+ }
222
+ return undefined;
223
+ }
@@ -1,9 +1,27 @@
1
1
  export function looksLikeVersion(value) {
2
2
  return /^[0-9]+\.[0-9]+\.[0-9]+(?:[-+][^/]+)?$/.test(value);
3
3
  }
4
+ // module-level; safe to grow unbounded — a single scan sees at most
5
+ // a few hundred unique version strings, and the cache is discarded when the process exits.
6
+ const parsedVersionCache = new Map();
7
+ export function getVersionCacheSize() {
8
+ return parsedVersionCache.size;
9
+ }
10
+ function parseVersionTuple(v) {
11
+ const cached = parsedVersionCache.get(v);
12
+ if (cached)
13
+ return cached;
14
+ const parsed = v.split(/[.+-]/).map(n => {
15
+ const num = Number(n);
16
+ return Number.isFinite(num) ? num : n;
17
+ });
18
+ Object.freeze(parsed);
19
+ parsedVersionCache.set(v, parsed);
20
+ return parsed;
21
+ }
4
22
  export function compareVersions(a, b) {
5
- const pa = a.split(/[.+-]/).map(n => Number.isFinite(Number(n)) ? Number(n) : n);
6
- const pb = b.split(/[.+-]/).map(n => Number.isFinite(Number(n)) ? Number(n) : n);
23
+ const pa = parseVersionTuple(a);
24
+ const pb = parseVersionTuple(b);
7
25
  const len = Math.max(pa.length, pb.length);
8
26
  for (let i = 0; i < len; i++) {
9
27
  const av = pa[i] ?? 0;
package/package.json CHANGED
@@ -1,13 +1,15 @@
1
1
  {
2
2
  "name": "cve-lite-cli",
3
- "version": "1.25.0",
3
+ "version": "1.26.0",
4
4
  "description": "Developer-friendly CLI for scanning JS/TS projects for dependency vulnerabilities using local lockfiles and OSV",
5
5
  "type": "module",
6
6
  "bin": {
7
7
  "cve-lite": "./dist/index.js"
8
8
  },
9
9
  "scripts": {
10
+ "prebuild": "node scripts/clean-dist.mjs",
10
11
  "build": "tsc -p tsconfig.json",
12
+ "postbuild": "node scripts/check-dist.mjs",
11
13
  "dev": "tsx src/index.ts .",
12
14
  "start": "node dist/index.js .",
13
15
  "lint:tests": "node scripts/check-test-hygiene.mjs",
@@ -57,6 +59,8 @@
57
59
  "files": [
58
60
  "dist",
59
61
  "README.md",
60
- "LICENSE"
62
+ "LICENSE",
63
+ "assets/logo-with-title-removebg-preview.png",
64
+ "assets/OWASP_Logo_Black_TM.png"
61
65
  ]
62
66
  }
@@ -1,50 +0,0 @@
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
- }