cve-lite-cli 1.24.0 → 1.26.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/README.md +83 -2
  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/audit-log/events.js +3 -0
  7. package/dist/audit-log/handle.js +20 -0
  8. package/dist/audit-log/index.js +16 -0
  9. package/dist/audit-log/ndjson-writer.js +28 -0
  10. package/dist/cli/args.js +75 -0
  11. package/dist/cli/fix-overrides-hook.js +64 -0
  12. package/dist/cli/help.js +24 -1
  13. package/dist/cli/overrides.js +67 -0
  14. package/dist/cli/validate.js +9 -1
  15. package/dist/index.js +310 -21
  16. package/dist/osv/cache.js +28 -4
  17. package/dist/output/formatters.js +22 -18
  18. package/dist/output/html-reporter.js +37 -8
  19. package/dist/output/logos.js +18 -0
  20. package/dist/output/multi-folder-html-reporter.js +3 -4
  21. package/dist/output/override-findings-html.js +63 -0
  22. package/dist/output/override-findings-json.js +3 -0
  23. package/dist/output/override-findings-sarif.js +52 -0
  24. package/dist/output/override-findings-terminal.js +106 -0
  25. package/dist/output/printers.js +66 -23
  26. package/dist/output/sarif.js +77 -8
  27. package/dist/output/write-outputs.js +7 -3
  28. package/dist/overrides/api.js +79 -0
  29. package/dist/overrides/composite.js +23 -0
  30. package/dist/overrides/context-builder.js +150 -0
  31. package/dist/overrides/context.js +3 -0
  32. package/dist/overrides/detectors/index.js +23 -0
  33. package/dist/overrides/detectors/oa001-orphaned-target.js +36 -0
  34. package/dist/overrides/detectors/oa002-floating-tag.js +40 -0
  35. package/dist/overrides/detectors/oa003-wrong-section.js +48 -0
  36. package/dist/overrides/detectors/oa004-surpassed-pin.js +49 -0
  37. package/dist/overrides/detectors/oa005-nested-ineffective.js +128 -0
  38. package/dist/overrides/detectors/oa006-coupled-platform-binary.js +170 -0
  39. package/dist/overrides/detectors/oa007-frozen-latest.js +69 -0
  40. package/dist/overrides/detectors/oa008-materialized.js +75 -0
  41. package/dist/overrides/detectors/platform-binary.js +37 -0
  42. package/dist/overrides/fixer.js +199 -0
  43. package/dist/overrides/index.js +5 -0
  44. package/dist/overrides/parsing/installed-tree.js +164 -0
  45. package/dist/overrides/parsing/json-pointer.js +8 -0
  46. package/dist/overrides/parsing/node-modules.js +19 -0
  47. package/dist/overrides/parsing/package-json.js +139 -0
  48. package/dist/overrides/parsing/registry.js +66 -0
  49. package/dist/overrides/types.js +2 -0
  50. package/dist/parsers/pnpm-lock.js +46 -3
  51. package/dist/parsers/yarn-lock.js +2 -2
  52. package/dist/remediation/fix-commands.js +59 -5
  53. package/dist/remediation/npm-registry.js +55 -43
  54. package/dist/remediation/npm-transitive-resolution.js +2 -2
  55. package/dist/remediation/transitive-chain-resolver.js +100 -0
  56. package/dist/scan/multi-folder-scan.js +37 -1
  57. package/dist/scanner.js +122 -46
  58. package/dist/types.js +13 -1
  59. package/dist/utils/baseline.js +16 -0
  60. package/dist/utils/create-pr.js +19 -4
  61. package/dist/utils/fix-runner.js +6 -0
  62. package/dist/utils/package-json.js +21 -0
  63. package/dist/utils/severity.js +16 -0
  64. package/dist/utils/string.js +34 -0
  65. package/dist/utils/validate-url.js +223 -0
  66. package/dist/utils/version.js +135 -2
  67. package/package.json +8 -2
  68. package/dist/learn/keypress.js +0 -50
  69. package/dist/learn/runner.js +0 -96
  70. package/dist/learn/scenario.js +0 -47
  71. package/dist/learn/session.js +0 -36
  72. package/dist/learn/types.js +0 -1
  73. package/dist/llm/client.js +0 -40
  74. package/dist/llm/config.js +0 -48
  75. package/dist/llm/explainer.js +0 -31
  76. package/dist/output/logo-base64.js +0 -1
  77. package/dist/output/owasp-logo-base64.js +0 -1
@@ -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;
@@ -45,3 +63,118 @@ export function normalizeRawVersion(value) {
45
63
  return cleaned;
46
64
  return null;
47
65
  }
66
+ /**
67
+ * Extract the leading integer (major) from a version string. Returns null
68
+ * if the string does not start with a digit-only run.
69
+ */
70
+ export function majorVersion(value) {
71
+ if (!value)
72
+ return null;
73
+ const m = value.match(/^(\d+)/);
74
+ if (!m)
75
+ return null;
76
+ return Number(m[1]);
77
+ }
78
+ /**
79
+ * Coerce a partial or range-prefixed version into a concrete X.Y.Z form.
80
+ * Strips leading range operators (`^`, `~`, `>=`, `<=`, `>`, `<`, `=`), pads
81
+ * missing minor/patch with zeros. Returns null if the input cannot be
82
+ * interpreted as a version.
83
+ *
84
+ * Examples:
85
+ * "1" -> "1.0.0"
86
+ * "1.2" -> "1.2.0"
87
+ * "^1.2.3" -> "1.2.3"
88
+ * ">=2.0" -> "2.0.0"
89
+ * "latest" -> null
90
+ */
91
+ export function coerceVersion(input) {
92
+ if (!input)
93
+ return null;
94
+ const stripped = input.trim().replace(/^[\^~]|^[<>]=?|^=/, "").trim();
95
+ const m = stripped.match(/^(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:[-+][^\s]+)?/);
96
+ if (!m)
97
+ return null;
98
+ const [, major, minor = "0", patch = "0"] = m;
99
+ return `${major}.${minor}.${patch}`;
100
+ }
101
+ /**
102
+ * Does the string parse as a version range cve-lite recognises?
103
+ * Supports plain versions and the operators `^`, `~`, `>=`, `<=`, `>`, `<`, `=`.
104
+ * Does not support OR (`||`) or hyphen ranges (`1.0.0 - 2.0.0`) - if those
105
+ * surface in real projects, extend later.
106
+ */
107
+ export function isValidRange(input) {
108
+ if (!input)
109
+ return false;
110
+ const trimmed = input.trim();
111
+ if (!/^(?:\^|~|>=|<=|>|<|=)?\s*\d+(?:\.\d+)?(?:\.\d+)?(?:[-+][^\s]+)?$/.test(trimmed)) {
112
+ return false;
113
+ }
114
+ return coerceVersion(trimmed) !== null;
115
+ }
116
+ /**
117
+ * Does `version` satisfy `range`? Minimal subset of semver semantics covering
118
+ * what the OA detectors need: exact, `^`, `~`, `>=`, `<=`, `>`, `<`, `=`.
119
+ *
120
+ * Pre-releases follow semver convention: a pre-release version (e.g.
121
+ * "1.2.3-beta") satisfies a range only if the range explicitly mentions a
122
+ * pre-release component at the same major.minor.patch boundary.
123
+ */
124
+ export function satisfiesRange(version, range) {
125
+ const v = coerceVersion(version);
126
+ if (!v)
127
+ return false;
128
+ const trimmedRange = range.trim();
129
+ // Exact match (no operator)
130
+ if (/^\d/.test(trimmedRange)) {
131
+ return compareVersions(v, coerceVersion(trimmedRange) ?? "") === 0;
132
+ }
133
+ // `=` operator
134
+ if (trimmedRange.startsWith("=")) {
135
+ const target = coerceVersion(trimmedRange.slice(1));
136
+ return target !== null && compareVersions(v, target) === 0;
137
+ }
138
+ // `^` caret: same major, >= specified, < next major
139
+ if (trimmedRange.startsWith("^")) {
140
+ const target = coerceVersion(trimmedRange.slice(1));
141
+ if (!target)
142
+ return false;
143
+ if (compareVersions(v, target) < 0)
144
+ return false;
145
+ const tMajor = majorVersion(target);
146
+ const vMajor = majorVersion(v);
147
+ if (tMajor === null || vMajor === null)
148
+ return false;
149
+ return vMajor === tMajor;
150
+ }
151
+ // `~` tilde: same major.minor, >= specified
152
+ if (trimmedRange.startsWith("~")) {
153
+ const target = coerceVersion(trimmedRange.slice(1));
154
+ if (!target)
155
+ return false;
156
+ if (compareVersions(v, target) < 0)
157
+ return false;
158
+ const [vMaj, vMin] = v.split(".").map(Number);
159
+ const [tMaj, tMin] = target.split(".").map(Number);
160
+ return vMaj === tMaj && vMin === tMin;
161
+ }
162
+ // Comparators
163
+ for (const op of [">=", "<=", ">", "<"]) {
164
+ if (trimmedRange.startsWith(op)) {
165
+ const target = coerceVersion(trimmedRange.slice(op.length));
166
+ if (!target)
167
+ return false;
168
+ const cmp = compareVersions(v, target);
169
+ if (op === ">=")
170
+ return cmp >= 0;
171
+ if (op === "<=")
172
+ return cmp <= 0;
173
+ if (op === ">")
174
+ return cmp > 0;
175
+ if (op === "<")
176
+ return cmp < 0;
177
+ }
178
+ }
179
+ return false;
180
+ }
package/package.json CHANGED
@@ -1,15 +1,19 @@
1
1
  {
2
2
  "name": "cve-lite-cli",
3
- "version": "1.24.0",
3
+ "version": "1.26.0-beta.1",
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 .",
15
+ "lint:tests": "node scripts/check-test-hygiene.mjs",
16
+ "pretest": "node scripts/check-test-hygiene.mjs",
13
17
  "test": "node --experimental-vm-modules ./node_modules/jest/bin/jest.js --passWithNoTests",
14
18
  "test:watch": "node --experimental-vm-modules ./node_modules/jest/bin/jest.js --watch --passWithNoTests"
15
19
  },
@@ -55,6 +59,8 @@
55
59
  "files": [
56
60
  "dist",
57
61
  "README.md",
58
- "LICENSE"
62
+ "LICENSE",
63
+ "assets/logo-with-title-removebg-preview.png",
64
+ "assets/OWASP_Logo_Black_TM.png"
59
65
  ]
60
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
- }
@@ -1,96 +0,0 @@
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
- }
@@ -1,47 +0,0 @@
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
- }
@@ -1,36 +0,0 @@
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
- }
@@ -1 +0,0 @@
1
- export {};
@@ -1,40 +0,0 @@
1
- const PROVIDERS = {
2
- claude: {
3
- endpoint: "https://api.anthropic.com/v1/messages",
4
- model: "claude-haiku-4-5-20251001",
5
- },
6
- };
7
- async function doFetch(endpoint, apiKey, body) {
8
- return fetch(endpoint, {
9
- method: "POST",
10
- headers: {
11
- "x-api-key": apiKey,
12
- "anthropic-version": "2023-06-01",
13
- "content-type": "application/json",
14
- },
15
- body,
16
- signal: AbortSignal.timeout(15000),
17
- });
18
- }
19
- export async function callLlm(config, prompt) {
20
- const provider = PROVIDERS[config.provider];
21
- if (!provider) {
22
- throw new Error(`Unsupported LLM provider: "${config.provider}". Supported: ${Object.keys(PROVIDERS).join(", ")}`);
23
- }
24
- const body = JSON.stringify({
25
- model: provider.model,
26
- max_tokens: 200,
27
- messages: [{ role: "user", content: prompt }],
28
- });
29
- let response = await doFetch(provider.endpoint, config.apiKey, body);
30
- if (response.status === 429) {
31
- await new Promise(r => setTimeout(r, 2000));
32
- response = await doFetch(provider.endpoint, config.apiKey, body);
33
- }
34
- if (!response.ok) {
35
- const errText = await response.text();
36
- throw new Error(`LLM API error (${response.status}): ${errText}`);
37
- }
38
- const data = await response.json();
39
- return data.content.find(c => c.type === "text")?.text ?? "";
40
- }