cve-lite-cli 1.0.5 → 1.1.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.
@@ -0,0 +1,224 @@
1
+ import { compareVersions, looksLikeVersion } from "../utils/version.js";
2
+ const packumentCache = new Map();
3
+ const DEFAULT_NPM_REGISTRY_URL = "https://registry.npmjs.org";
4
+ export async function resolveRecommendedParentUpgrade(finding, packages) {
5
+ if (finding.relationship !== "transitive")
6
+ return null;
7
+ const viaPath = getBestPath(finding);
8
+ if (!viaPath || viaPath.length < 3)
9
+ return null;
10
+ const directParentName = viaPath[1];
11
+ const immediateParentName = viaPath[viaPath.length - 2];
12
+ const vulnerableName = finding.pkg.name;
13
+ const directParent = findDirectDependency(packages, directParentName);
14
+ if (!directParent)
15
+ return null;
16
+ // Common reliable case:
17
+ // project -> sanitize-html -> lodash
18
+ if (viaPath.length === 3) {
19
+ return findUpgradeForExactDirectChild({
20
+ directParentName,
21
+ directParentVersion: directParent.version,
22
+ vulnerableName,
23
+ vulnerableInstalledVersion: finding.pkg.version,
24
+ vulnerableFixedVersion: finding.firstFixedVersion,
25
+ viaPath,
26
+ });
27
+ }
28
+ // Best-effort fallback for deeper chains.
29
+ return findUpgradeForImmediateIntermediate({
30
+ directParentName,
31
+ directParentVersion: directParent.version,
32
+ immediateParentName,
33
+ immediateParentInstalledVersion: findPackageVersion(packages, immediateParentName, viaPath.slice(0, -1)) ?? "",
34
+ vulnerableName,
35
+ viaPath,
36
+ });
37
+ }
38
+ function getBestPath(finding) {
39
+ const paths = finding.dependencyPaths ?? [];
40
+ if (paths.length === 0)
41
+ return null;
42
+ return [...paths].sort((a, b) => a.length - b.length)[0] ?? null;
43
+ }
44
+ function findDirectDependency(packages, name) {
45
+ for (const pkg of packages) {
46
+ if (pkg.name !== name)
47
+ continue;
48
+ const paths = pkg.paths ?? [];
49
+ if (paths.some(path => path.length === 2 && path[1] === name)) {
50
+ return pkg;
51
+ }
52
+ }
53
+ return null;
54
+ }
55
+ function findPackageVersion(packages, name, pathPrefix) {
56
+ for (const pkg of packages) {
57
+ if (pkg.name !== name)
58
+ continue;
59
+ const paths = pkg.paths ?? [];
60
+ if (paths.some(path => startsWithPath(path, pathPrefix))) {
61
+ return pkg.version;
62
+ }
63
+ }
64
+ return null;
65
+ }
66
+ function startsWithPath(path, prefix) {
67
+ if (prefix.length > path.length)
68
+ return false;
69
+ for (let i = 0; i < prefix.length; i++) {
70
+ if (path[i] !== prefix[i])
71
+ return false;
72
+ }
73
+ return true;
74
+ }
75
+ async function findUpgradeForExactDirectChild(args) {
76
+ const packument = await fetchPackument(args.directParentName);
77
+ const versions = Object.keys(packument?.versions ?? {})
78
+ .filter(looksLikeVersion)
79
+ .filter(version => compareVersions(version, args.directParentVersion) > 0)
80
+ .sort(compareVersions);
81
+ for (const version of versions) {
82
+ const manifest = packument?.versions?.[version];
83
+ const depRange = manifest?.dependencies?.[args.vulnerableName] ??
84
+ manifest?.optionalDependencies?.[args.vulnerableName];
85
+ if (!depRange)
86
+ continue;
87
+ const stillAllowsInstalled = versionSatisfiesRange(args.vulnerableInstalledVersion, depRange);
88
+ const allowsFixed = args.vulnerableFixedVersion
89
+ ? versionSatisfiesRange(args.vulnerableFixedVersion, depRange)
90
+ : true;
91
+ if (!stillAllowsInstalled && allowsFixed) {
92
+ return {
93
+ package: args.directParentName,
94
+ currentVersion: args.directParentVersion,
95
+ targetVersion: version,
96
+ viaPath: args.viaPath,
97
+ vulnerablePackage: args.vulnerableName,
98
+ confidence: "exact-direct-child",
99
+ reason: `${args.directParentName}@${version} no longer allows ${args.vulnerableName}@${args.vulnerableInstalledVersion}${args.vulnerableFixedVersion ? ` and allows ${args.vulnerableFixedVersion}+` : ""}`,
100
+ };
101
+ }
102
+ }
103
+ return null;
104
+ }
105
+ async function findUpgradeForImmediateIntermediate(args) {
106
+ if (!args.immediateParentInstalledVersion || !looksLikeVersion(args.immediateParentInstalledVersion)) {
107
+ return null;
108
+ }
109
+ const packument = await fetchPackument(args.directParentName);
110
+ const versions = Object.keys(packument?.versions ?? {})
111
+ .filter(looksLikeVersion)
112
+ .filter(version => compareVersions(version, args.directParentVersion) > 0)
113
+ .sort(compareVersions);
114
+ for (const version of versions) {
115
+ const manifest = packument?.versions?.[version];
116
+ const depRange = manifest?.dependencies?.[args.immediateParentName] ??
117
+ manifest?.optionalDependencies?.[args.immediateParentName];
118
+ if (!depRange)
119
+ continue;
120
+ const stillAllowsImmediateParentInstalled = versionSatisfiesRange(args.immediateParentInstalledVersion, depRange);
121
+ if (!stillAllowsImmediateParentInstalled) {
122
+ return {
123
+ package: args.directParentName,
124
+ currentVersion: args.directParentVersion,
125
+ targetVersion: version,
126
+ viaPath: args.viaPath,
127
+ vulnerablePackage: args.vulnerableName,
128
+ confidence: "best-effort",
129
+ reason: `${args.directParentName}@${version} no longer allows ${args.immediateParentName}@${args.immediateParentInstalledVersion} in the current path`,
130
+ };
131
+ }
132
+ }
133
+ return null;
134
+ }
135
+ async function fetchPackument(packageName) {
136
+ if (packumentCache.has(packageName)) {
137
+ return packumentCache.get(packageName) ?? null;
138
+ }
139
+ const url = `${DEFAULT_NPM_REGISTRY_URL}/${encodeURIComponent(packageName)
140
+ .replace(/%40/g, "@")
141
+ .replace(/%2F/g, "/")}`;
142
+ const response = await fetch(url);
143
+ if (!response.ok) {
144
+ packumentCache.set(packageName, null);
145
+ return null;
146
+ }
147
+ const json = (await response.json());
148
+ packumentCache.set(packageName, json);
149
+ return json;
150
+ }
151
+ function versionSatisfiesRange(version, rawRange) {
152
+ const range = rawRange.trim();
153
+ if (!range)
154
+ return false;
155
+ if (range === "*" || range === "latest")
156
+ return true;
157
+ const orParts = range.split("||").map(part => part.trim()).filter(Boolean);
158
+ return orParts.some(part => satisfiesAndRange(version, part));
159
+ }
160
+ function satisfiesAndRange(version, range) {
161
+ const normalized = normalizeRange(range);
162
+ if (!normalized)
163
+ return false;
164
+ const tokens = normalized.split(/\s+/).filter(Boolean);
165
+ return tokens.every(token => satisfiesComparator(version, token));
166
+ }
167
+ function normalizeRange(range) {
168
+ const trimmed = range.trim();
169
+ if (!trimmed)
170
+ return null;
171
+ if (looksLikeVersion(trimmed)) {
172
+ return `=${trimmed}`;
173
+ }
174
+ if (trimmed.startsWith("^")) {
175
+ const base = trimmed.slice(1);
176
+ if (!looksLikeVersion(base))
177
+ return null;
178
+ const [major, minor, patch] = parseCoreVersion(base);
179
+ if (major > 0)
180
+ return `>=${base} <${major + 1}.0.0`;
181
+ if (minor > 0)
182
+ return `>=${base} <0.${minor + 1}.0`;
183
+ return `>=${base} <0.0.${patch + 1}`;
184
+ }
185
+ if (trimmed.startsWith("~")) {
186
+ const base = trimmed.slice(1);
187
+ if (!looksLikeVersion(base))
188
+ return null;
189
+ const [major, minor] = parseCoreVersion(base);
190
+ return `>=${base} <${major}.${minor + 1}.0`;
191
+ }
192
+ return trimmed;
193
+ }
194
+ function satisfiesComparator(version, comparator) {
195
+ const token = comparator.trim();
196
+ if (!token)
197
+ return true;
198
+ const match = token.match(/^(<=|>=|<|>|=)?\s*([0-9]+\.[0-9]+\.[0-9]+(?:[-+][^\s]+)?)$/);
199
+ if (!match)
200
+ return false;
201
+ const operator = match[1] ?? "=";
202
+ const target = match[2];
203
+ const cmp = compareVersions(version, target);
204
+ switch (operator) {
205
+ case "<":
206
+ return cmp < 0;
207
+ case "<=":
208
+ return cmp <= 0;
209
+ case ">":
210
+ return cmp > 0;
211
+ case ">=":
212
+ return cmp >= 0;
213
+ case "=":
214
+ return cmp === 0;
215
+ default:
216
+ return false;
217
+ }
218
+ }
219
+ function parseCoreVersion(version) {
220
+ const [major, minor, patch] = version
221
+ .split(".")
222
+ .map(part => Number(part.replace(/[^0-9].*$/, "")));
223
+ return [major || 0, minor || 0, patch || 0];
224
+ }
package/dist/scanner.js CHANGED
@@ -4,18 +4,63 @@ import { loadCache, saveCache } from "./osv/cache.js";
4
4
  import { maxSeverity } from "./osv/severity.js";
5
5
  import { createSpinner } from "./output/spinner.js";
6
6
  import { OsvAdvisorySource } from "./advisory/osv-advisory-source.js";
7
+ import { LocalAdvisorySource } from "./advisory/local-advisory-source.js";
8
+ import { LocalAdvisoryDatabase } from "./advisory/local-db.js";
9
+ import { getDefaultAdvisoryDbPath } from "./advisory/osv-sync.js";
10
+ import { resolveRecommendedParentUpgrade } from "./remediation/parent-upgrade.js";
7
11
  export function createAdvisorySource(options) {
8
- return new OsvAdvisorySource(options?.osvUrl);
12
+ const offline = !!options?.offline || !!options?.offlineDb;
13
+ if (offline) {
14
+ const dbPath = getDefaultAdvisoryDbPath(options?.offlineDb);
15
+ const db = new LocalAdvisoryDatabase(dbPath, { readonly: true });
16
+ return {
17
+ advisorySource: new LocalAdvisorySource(db),
18
+ offline: true,
19
+ sourceLabel: `local advisory database (${dbPath})`,
20
+ cleanup: () => db.close(),
21
+ };
22
+ }
23
+ return {
24
+ advisorySource: new OsvAdvisorySource(options?.osvUrl),
25
+ offline: false,
26
+ sourceLabel: options?.osvUrl
27
+ ? `custom OSV endpoint (${options.osvUrl})`
28
+ : "OSV (https://api.osv.dev)",
29
+ cleanup: () => { },
30
+ };
31
+ }
32
+ function getPackageCacheKey(pkg) {
33
+ return `${pkg.ecosystem}:${pkg.name}@${pkg.version}`;
9
34
  }
10
35
  export async function scanPackages(packages, batchSize, options) {
11
- const offline = !!options.offline;
36
+ const sourceContext = createAdvisorySource({
37
+ osvUrl: options.osvUrl,
38
+ offline: options.offline,
39
+ offlineDb: options.offlineDb,
40
+ });
41
+ const offline = sourceContext.offline;
12
42
  const cacheDirOverride = options.cacheDir;
13
- const spinner = createSpinner("Scanning dependencies against OSV...", options);
14
- const advisorySource = createAdvisorySource({ osvUrl: options.osvUrl });
43
+ const spinner = createSpinner(offline
44
+ ? "Scanning dependencies against the local advisory database..."
45
+ : "Scanning dependencies against OSV...", options);
46
+ const advisorySource = sourceContext.advisorySource;
47
+ const cache = loadCache(cacheDirOverride);
15
48
  try {
16
- const chunks = chunk(packages, batchSize);
17
49
  const results = [];
50
+ const uncachedPackages = [];
18
51
  if (!offline) {
52
+ for (const pkg of packages) {
53
+ const cacheKey = getPackageCacheKey(pkg);
54
+ if (cacheKey in cache.queryEntries) {
55
+ const vulnIds = cache.queryEntries[cacheKey] ?? [];
56
+ if (vulnIds.length > 0) {
57
+ results.push({ pkg, vulnIds });
58
+ }
59
+ continue;
60
+ }
61
+ uncachedPackages.push(pkg);
62
+ }
63
+ const chunks = chunk(uncachedPackages, batchSize);
19
64
  for (let i = 0; i < chunks.length; i++) {
20
65
  spinner.update(`Scanning OSV batch ${i + 1}/${chunks.length}...`);
21
66
  const chunkItems = chunks[i];
@@ -25,17 +70,32 @@ export async function scanPackages(packages, batchSize, options) {
25
70
  const pkg = chunkItems[j];
26
71
  const row = rows[j];
27
72
  const vulnIds = (row?.vulnerabilities ?? []).map(v => v.id).filter(Boolean);
73
+ cache.queryEntries[getPackageCacheKey(pkg)] = vulnIds;
28
74
  if (vulnIds.length > 0) {
29
75
  results.push({ pkg, vulnIds });
30
76
  }
31
77
  }
32
78
  }
33
- spinner.succeed(`Queried OSV in ${chunks.length} batch${chunks.length === 1 ? "" : "es"}`);
79
+ if (chunks.length === 0) {
80
+ spinner.succeed("Loaded package matches from cache");
81
+ }
82
+ else {
83
+ spinner.succeed(`Queried OSV in ${chunks.length} batch${chunks.length === 1 ? "" : "es"}`);
84
+ }
34
85
  }
35
86
  else {
36
- spinner.succeed("Offline mode enabled; package matching was skipped");
87
+ const advisoryResult = await advisorySource.queryBatch(packages);
88
+ const rows = advisoryResult ?? [];
89
+ for (let i = 0; i < packages.length; i++) {
90
+ const pkg = packages[i];
91
+ const row = rows[i];
92
+ const vulnIds = (row?.vulnerabilities ?? []).map(v => v.id).filter(Boolean);
93
+ if (vulnIds.length > 0) {
94
+ results.push({ pkg, vulnIds });
95
+ }
96
+ }
97
+ spinner.succeed("Loaded package matches from the local advisory database");
37
98
  }
38
- const cache = loadCache(cacheDirOverride);
39
99
  const idSet = new Set(results.flatMap(r => r.vulnIds));
40
100
  const vulnMap = new Map();
41
101
  if (idSet.size > 0 && !offline) {
@@ -45,9 +105,11 @@ export async function scanPackages(packages, batchSize, options) {
45
105
  for (let i = 0; i < ids.length; i++) {
46
106
  const id = ids[i];
47
107
  detailSpinner.update(`Fetching vulnerability details ${i + 1}/${ids.length}...`);
48
- const cached = cache.entries[id];
49
- if (cached) {
50
- vulnMap.set(id, cached);
108
+ if (id in cache.entries) {
109
+ const cached = cache.entries[id];
110
+ if (cached) {
111
+ vulnMap.set(id, cached);
112
+ }
51
113
  continue;
52
114
  }
53
115
  try {
@@ -66,10 +128,32 @@ export async function scanPackages(packages, batchSize, options) {
66
128
  throw error;
67
129
  }
68
130
  }
131
+ else if (idSet.size > 0 && offline) {
132
+ const ids = [...idSet];
133
+ const detailSpinner = createSpinner("Loading local advisory details...", options);
134
+ try {
135
+ for (let i = 0; i < ids.length; i++) {
136
+ const id = ids[i];
137
+ detailSpinner.update(`Loading local advisory details ${i + 1}/${ids.length}...`);
138
+ try {
139
+ const detail = await advisorySource.getVuln(id);
140
+ vulnMap.set(id, detail);
141
+ }
142
+ catch {
143
+ // ignore missing local records so scans remain resilient to partial DB state
144
+ }
145
+ }
146
+ detailSpinner.succeed(`Loaded ${ids.length} local advisory detail record${ids.length === 1 ? "" : "s"}`);
147
+ }
148
+ catch (error) {
149
+ detailSpinner.fail("Failed while loading local advisory details");
150
+ throw error;
151
+ }
152
+ }
69
153
  if (!offline && idSet.size > 0) {
70
154
  saveCache(cache, cacheDirOverride);
71
155
  }
72
- return results.map(result => {
156
+ const findings = results.map(result => {
73
157
  const vulnerabilities = result.vulnIds
74
158
  .map(id => vulnMap.get(id))
75
159
  .filter((v) => Boolean(v));
@@ -85,14 +169,29 @@ export async function scanPackages(packages, batchSize, options) {
85
169
  cveAliases,
86
170
  dependencyPaths,
87
171
  relationship,
88
- firstFixedVersion
172
+ firstFixedVersion,
173
+ recommendedParentUpgrade: undefined,
89
174
  };
90
175
  });
176
+ for (const finding of findings) {
177
+ if (finding.relationship !== "transitive" || offline)
178
+ continue;
179
+ try {
180
+ finding.recommendedParentUpgrade = await resolveRecommendedParentUpgrade(finding, packages);
181
+ }
182
+ catch {
183
+ finding.recommendedParentUpgrade = undefined;
184
+ }
185
+ }
186
+ return findings;
91
187
  }
92
188
  catch (error) {
93
189
  spinner.fail("Scan failed");
94
190
  throw error;
95
191
  }
192
+ finally {
193
+ sourceContext.cleanup();
194
+ }
96
195
  }
97
196
  function classifyRelationship(paths) {
98
197
  if (paths.length === 0)
@@ -125,13 +224,13 @@ export function buildCoverageNotes(scanInput, offline) {
125
224
  "This MVP checks package versions against OSV advisories. It does not prove exploitability or runtime reachability.",
126
225
  "Installed node_modules contents are not verified in this scan.",
127
226
  "Container images, binaries, secrets, and IaC files are not scanned.",
128
- "Monorepo workspace boundaries are only partially modeled in this version."
227
+ "Monorepo workspace boundaries are only partially modeled in this version.",
129
228
  ];
130
229
  if (scanInput.mode === "manifest-fallback") {
131
230
  notes.push("Manifest fallback is limited to direct dependencies pinned to exact versions. It does not resolve transitive dependencies from package.json alone.");
132
231
  }
133
232
  if (offline) {
134
- notes.push("Offline mode only uses cached vulnerability details.");
233
+ notes.push("Offline mode uses the local advisory database and does not make outbound advisory API calls.");
135
234
  }
136
235
  return notes;
137
236
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cve-lite-cli",
3
- "version": "1.0.5",
3
+ "version": "1.1.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": {
@@ -9,14 +9,22 @@
9
9
  "scripts": {
10
10
  "build": "tsc -p tsconfig.json",
11
11
  "dev": "tsx src/index.ts .",
12
- "start": "node dist/index.js ."
12
+ "start": "node dist/index.js .",
13
+ "test": "node --experimental-vm-modules ./node_modules/jest/bin/jest.js --passWithNoTests",
14
+ "test:watch": "node --experimental-vm-modules ./node_modules/jest/bin/jest.js --watch --passWithNoTests"
13
15
  },
14
16
  "dependencies": {
17
+ "better-sqlite3": "^12.8.0",
18
+ "fflate": "^0.8.2",
15
19
  "yaml": "^2.7.1",
16
20
  "yarn-lockfile": "^1.1.0"
17
21
  },
18
22
  "devDependencies": {
23
+ "@types/better-sqlite3": "^7.6.13",
24
+ "@types/jest": "^30.0.0",
19
25
  "@types/node": "^24.0.0",
26
+ "jest": "^30.3.0",
27
+ "ts-jest": "^29.4.9",
20
28
  "tsx": "^4.19.2",
21
29
  "typescript": "^5.8.2"
22
30
  },