vigievuln 1.2.1 → 1.3.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 (107) hide show
  1. package/CHANGELOG.md +12 -2
  2. package/README.md +10 -4
  3. package/lib/airgap-project.js +35 -7
  4. package/lib/applicability-evidence.js +12 -0
  5. package/lib/artifacts/applications.js +54 -0
  6. package/lib/artifacts/cve-view.js +108 -0
  7. package/lib/artifacts/enrichment.js +86 -0
  8. package/lib/artifacts/go-main-identity.js +45 -0
  9. package/lib/artifacts/go-publisher-advisories.js +24 -0
  10. package/lib/artifacts/index.js +272 -0
  11. package/lib/artifacts/publisher-advisories.js +12 -0
  12. package/lib/artifacts/remediation-report.js +48 -0
  13. package/lib/artifacts/report-inventory.js +26 -0
  14. package/lib/artifacts/report.js +191 -0
  15. package/lib/artifacts/risk-report.js +120 -0
  16. package/lib/artifacts/sbom.js +68 -0
  17. package/lib/artifacts/scan.js +401 -0
  18. package/lib/cache-archive-sqlite.js +41 -25
  19. package/lib/charts.js +124 -32
  20. package/lib/cli-command-routing.js +20 -6
  21. package/lib/cli-groups.js +2 -1
  22. package/lib/cli-image.js +206 -0
  23. package/lib/codecs/binary/elf-metadata.js +42 -0
  24. package/lib/codecs/binary/go-buildinfo.js +37 -0
  25. package/lib/codecs/binary/metadata.js +7 -0
  26. package/lib/codecs/binary/scan.js +14 -13
  27. package/lib/codecs/binary/sniff.js +16 -15
  28. package/lib/codecs/binary.codec.js +22 -2
  29. package/lib/codecs/gradle/parse.js +63 -2
  30. package/lib/codecs/gradle/versionless.js +175 -0
  31. package/lib/codecs/gradle.codec.js +20 -3
  32. package/lib/codecs/index.js +2 -2
  33. package/lib/csaf-export.js +13 -6
  34. package/lib/cve-download.js +33 -29
  35. package/lib/cve-match.js +10 -0
  36. package/lib/cve-packages-proxy.js +19 -0
  37. package/lib/cve-report.js +273 -165
  38. package/lib/deps-descriptor.js +25 -3
  39. package/lib/diagnostics.js +12 -0
  40. package/lib/diff.js +0 -0
  41. package/lib/epss.js +6 -6
  42. package/lib/euvd.js +34 -4
  43. package/lib/finding-enrichment.js +165 -0
  44. package/lib/finding-summary.js +4 -3
  45. package/lib/i18n.js +34 -9
  46. package/lib/image-network.js +54 -0
  47. package/lib/image-references.js +203 -0
  48. package/lib/image-registry.js +385 -0
  49. package/lib/image-update.js +39 -0
  50. package/lib/json-export.js +50 -8
  51. package/lib/kev.js +6 -6
  52. package/lib/maven-bom.js +2 -1
  53. package/lib/merge-sources.js +3 -0
  54. package/lib/native-advisories.js +9 -7
  55. package/lib/native-cna-identities.js +12 -0
  56. package/lib/native-package-match.js +159 -0
  57. package/lib/native-source-prepare.js +60 -0
  58. package/lib/nvd.js +34 -23
  59. package/lib/osv.js +33 -14
  60. package/lib/project-descriptor.js +3 -2
  61. package/lib/provenance.js +8 -2
  62. package/lib/providers/alpine.js +8 -0
  63. package/lib/providers/common.js +11 -3
  64. package/lib/providers/debian.js +11 -0
  65. package/lib/providers/euvd.js +2 -1
  66. package/lib/providers/freexian.js +13 -0
  67. package/lib/providers/github.js +1 -0
  68. package/lib/providers/go.js +2 -1
  69. package/lib/providers/index.js +18 -14
  70. package/lib/providers/nginx.js +5 -0
  71. package/lib/providers/nvd.js +1 -1
  72. package/lib/providers/osv.js +1 -1
  73. package/lib/providers/osvdb.js +2 -2
  74. package/lib/proxy-throttle.js +89 -29
  75. package/lib/purl.js +10 -2
  76. package/lib/record-freshness.js +22 -0
  77. package/lib/report-notices.js +47 -0
  78. package/lib/report-time.js +45 -0
  79. package/lib/request-failure.js +22 -0
  80. package/lib/resource-cache/engine.js +130 -26
  81. package/lib/resource-cache/snapshot-projection.js +33 -0
  82. package/lib/resource-cache/validate.js +22 -5
  83. package/lib/risk-evidence.js +18 -0
  84. package/lib/sarif-export.js +17 -9
  85. package/lib/sbom-export.js +32 -12
  86. package/lib/source-health.js +25 -8
  87. package/lib/source-image-scan.js +57 -0
  88. package/lib/source-profile.js +6 -3
  89. package/lib/system-inventory/advisories.js +169 -0
  90. package/lib/system-inventory/alpine-tracker.js +47 -0
  91. package/lib/system-inventory/collect.js +118 -0
  92. package/lib/system-inventory/current-debian.js +99 -0
  93. package/lib/system-inventory/distribution-sources.js +132 -0
  94. package/lib/system-inventory/freexian-ela.js +32 -0
  95. package/lib/system-inventory/freexian-release-evidence.js +35 -0
  96. package/lib/system-inventory/freexian-tracker.js +72 -0
  97. package/lib/system-inventory/historical-debian.js +196 -0
  98. package/lib/system-inventory/index.js +2 -0
  99. package/lib/system-inventory/nginx-advisories.js +39 -0
  100. package/lib/system-inventory/rpm-storage.js +86 -0
  101. package/lib/system-inventory/targeted.js +70 -0
  102. package/lib/system-inventory/versions.js +59 -0
  103. package/lib/transitive.js +11 -2
  104. package/lib/ui.js +8 -5
  105. package/lib/unmanaged.js +1 -1
  106. package/package.json +12 -3
  107. package/vigievuln.js +204 -95
@@ -0,0 +1,175 @@
1
+ // Recover an unversioned Gradle declaration from requests made elsewhere in the
2
+ // same project's classpaths. This is deliberately separate from Maven mediation.
3
+ const { resolveTransitiveDeps } = require("../../transitive");
4
+
5
+ const CLASSPATHS = {
6
+ api: ["compile", "runtime", "testCompile", "testRuntime"],
7
+ implementation: ["compile", "runtime", "testCompile", "testRuntime"],
8
+ compileOnly: ["compile"],
9
+ compileOnlyApi: ["compile"],
10
+ runtimeOnly: ["runtime", "testRuntime"],
11
+ providedCompile: ["compile", "runtime", "testCompile", "testRuntime"],
12
+ providedRuntime: ["runtime", "testRuntime"],
13
+ testImplementation: ["testCompile", "testRuntime"],
14
+ testCompileOnly: ["testCompile"],
15
+ testRuntimeOnly: ["testRuntime"],
16
+ };
17
+ function classpaths(dep) {
18
+ return [...new Set((dep.gradleConfigurations || []).flatMap(c => CLASSPATHS[c] || [`custom:${c}`]))];
19
+ }
20
+ function ownClasspaths(dep) {
21
+ const all = classpaths(dep);
22
+ // Production dependencies also reach test classpaths, but test-only requests
23
+ // cannot supply the version of a production declaration.
24
+ return dep.isDev ? all : all.filter(c => !c.startsWith("test"));
25
+ }
26
+ function exclusions(sets) {
27
+ if (!sets?.length) return [];
28
+ return [...new Set(sets[0])].filter(x => sets.every(s => s.includes(x))).map(x => {
29
+ const i = x.indexOf(":");
30
+ return { groupId: x.slice(0, i), artifactId: x.slice(i + 1) };
31
+ });
32
+ }
33
+ function exclusionsForClasspath(dep, cp) {
34
+ if (!dep.gradleDeclarations) return exclusions(dep.exclusionSets);
35
+ return exclusions(dep.gradleDeclarations.filter(d => (CLASSPATHS[d.configuration] || [`custom:${d.configuration}`]).includes(cp)).map(d => d.exclusions));
36
+ }
37
+
38
+ // Gradle compares numeric parts numerically; an extra numeric part is higher,
39
+ // including a trailing zero. Do not apply Maven's qualifier/range ordering.
40
+ function highestRelease(versions) {
41
+ const values = [...new Set(versions)];
42
+ if (values.includes(null)) return null;
43
+ if (values.length === 1) return values[0];
44
+ if (!values.length || values.some(v => !/^\d+(?:\.\d+)*$/.test(v))) return null;
45
+ return values.sort((a, b) => {
46
+ const x = a.split(".").map(BigInt), y = b.split(".").map(BigInt);
47
+ for (let i = 0; i < Math.min(x.length, y.length); i++) {
48
+ if (x[i] !== y[i]) return x[i] < y[i] ? -1 : 1;
49
+ }
50
+ return x.length - y.length;
51
+ }).at(-1);
52
+ }
53
+
54
+ async function recoverVersionlessGradle(deps, opts = {}) {
55
+ const pick = opts.only || (() => true);
56
+ const records = [...deps.values()].filter(d => pick(d) && d.ecosystemType === "gradle"
57
+ && d.provenance === "manifest" && !d.fromLockfile && !d.versionUnresolved
58
+ && d.manifestPaths?.length === 1 && (d.versions || []).length <= 1);
59
+ const usableRecords = new Set(records);
60
+ const targets = records.filter(d => !d.version && !d.managedOnly
61
+ && (opts.includeTestDeps || !d.isDev) && ownClasspaths(d).length);
62
+ if (!targets.length) return 0;
63
+ const groups = new Map();
64
+ for (const target of targets) for (const cp of ownClasspaths(target)) {
65
+ const manifest = target.manifestPaths[0];
66
+ const key = JSON.stringify([manifest, cp]);
67
+ if (!groups.has(key)) groups.set(key, { manifest, cp, targets: [] });
68
+ groups.get(key).targets.push(target);
69
+ }
70
+ const evidence = new Map(targets.map(d => [d.coordKey, []]));
71
+ for (const { manifest, cp, targets: localTargets } of groups.values()) {
72
+ // An omitted root can contribute any version on this classpath. Do not
73
+ // infer from a graph that silently dropped an unresolved or merged record.
74
+ const omittedRoot = [...deps.values()].some(d => d.ecosystemType === "gradle"
75
+ && d.provenance === "manifest" && !d.fromLockfile && !usableRecords.has(d)
76
+ && d.manifestPaths?.includes(manifest) && (d.managedOnly || classpaths(d).includes(cp)));
77
+ if (omittedRoot) continue;
78
+ // A cached effective POM may have been built while its parent was unavailable.
79
+ // Keep recovery's cache local to this classpath so missing-parent evidence is not lost.
80
+ const effCache = new Map();
81
+ const local = records.filter(d => d.manifestPaths[0] === manifest && (d.managedOnly || classpaths(d).includes(cp)));
82
+ const keys = new Set(local.filter(d => !d.managedOnly && !d.version).map(d => d.coordKey));
83
+ const rootDepMgmt = new Map(opts.bomDepMgmt || []);
84
+ for (const [key, m] of (opts.gradleBomDepMgmt || [])) if (m.manifestPath === manifest) rootDepMgmt.set(key, m);
85
+ // An ordinary direct version is a request, not a Gradle force. Keep the
86
+ // provenance of actual pins separate from the Maven traversal overrides.
87
+ const provenPins = new Map(rootDepMgmt);
88
+ for (const d of local) if (d.version) rootDepMgmt.set(d.coordKey, {
89
+ version: d.version, exclusions: exclusions(d.mgmtExclusionSets), ...(d.pinMinimum ? { minimum: true } : {}),
90
+ });
91
+ for (const d of local) if (d.version) {
92
+ if (d.managedOnly) provenPins.set(d.coordKey, { version: d.version, minimum: !!d.pinMinimum });
93
+ else {
94
+ const pin = provenPins.get(d.coordKey);
95
+ if ((typeof pin === "string" ? pin : pin?.version) !== d.version) provenPins.delete(d.coordKey);
96
+ }
97
+ }
98
+ let selected = new Map(), finalRequests = null;
99
+ // Re-walk after selecting versions so children belonging only to a discarded
100
+ // version cannot supply another declaration. A cycle/unstable graph stays unknown.
101
+ for (let pass = 0; pass < 8; pass++) {
102
+ const requests = new Map([...keys].map(k => [k, []]));
103
+ const graphRequests = new Map();
104
+ let incomplete = false;
105
+ const roots = local.filter(d => !d.managedOnly && (d.version || selected.get(d.coordKey))).map(d => ({
106
+ ...d, version: d.version || selected.get(d.coordKey), exclusions: exclusionsForClasspath(d, cp),
107
+ }));
108
+ const pins = new Map(rootDepMgmt);
109
+ for (const [key, version] of selected) pins.set(key, { version });
110
+ const resolved = await resolveTransitiveDeps(roots, {
111
+ ...opts, effCache, rootDepMgmt: pins,
112
+ runtimeDependencies: cp !== "compile" && cp !== "testCompile",
113
+ includedScopes: cp.startsWith("test") ? ["compile", "runtime", "provided", "test"] : ["compile", "runtime", "provided"],
114
+ versionRequestKeys: keys,
115
+ onVersionRequest: r => requests.get(r.key).push(r),
116
+ onGraphRequest: ({ key, version }) => {
117
+ if (!graphRequests.has(key)) graphRequests.set(key, new Set());
118
+ graphRequests.get(key).add(version);
119
+ },
120
+ onMissingPom: info => { incomplete = true; opts.onMissingPom?.(info); },
121
+ onPomCycle: info => { incomplete = true; opts.onPomCycle?.(info); },
122
+ onResolutionError: (...args) => { incomplete = true; opts.onResolutionError?.(...args); },
123
+ onDepthLimit: (...args) => { incomplete = true; opts.onDepthLimit?.(...args); },
124
+ });
125
+ // Maven mediates intermediate conflicts differently from Gradle. Do not
126
+ // infer a target through a graph whose selected intermediate is uncertain.
127
+ for (const [key, versions] of graphRequests) {
128
+ if (keys.has(key)) continue;
129
+ const pin = provenPins.get(key);
130
+ const pinnedVersion = typeof pin === "string" ? pin : pin?.version;
131
+ if (pinnedVersion && !pin?.minimum) continue;
132
+ const effective = [...versions].map(v => pinnedVersion && v && /^\d+(?:\.\d+)*$/.test(v) && /^\d+(?:\.\d+)*$/.test(pinnedVersion) ? highestRelease([v, pinnedVersion]) : v);
133
+ const distinct = new Set(effective);
134
+ if (distinct.has(null)) { incomplete = true; continue; }
135
+ if (distinct.size <= 1) continue;
136
+ const highest = highestRelease([...distinct]);
137
+ const chosen = roots.find(d => d.coordKey === key)?.version || resolved.get(key)?.version;
138
+ if (!highest || chosen !== highest) incomplete = true;
139
+ }
140
+ if (incomplete) break;
141
+ const next = new Map();
142
+ for (const [key, rs] of requests) {
143
+ const version = highestRelease(rs.map(r => r.version));
144
+ if (version) next.set(key, version);
145
+ }
146
+ if (next.size === selected.size && [...next].every(([k, v]) => selected.get(k) === v)) {
147
+ // An unresolved root could itself request a higher version elsewhere.
148
+ if (next.size === keys.size) finalRequests = requests;
149
+ break;
150
+ }
151
+ selected = next;
152
+ }
153
+ if (!finalRequests) continue;
154
+ for (const { coordKey: key } of localTargets) {
155
+ const version = selected.get(key);
156
+ evidence.get(key).push({
157
+ version, paths: finalRequests.get(key).filter(r => r.version === version).map(r => r.via),
158
+ });
159
+ }
160
+ }
161
+ let filled = 0;
162
+ for (const target of targets) {
163
+ const hits = evidence.get(target.coordKey);
164
+ if (hits.length !== ownClasspaths(target).length || new Set(hits.map(h => h.version)).size !== 1) continue;
165
+ const version = hits[0].version;
166
+ target.version = version;
167
+ target.versions = [version];
168
+ target.versionPaths = { [version]: [...target.manifestPaths] };
169
+ target.versionSource = { via: "gradle-graph", paths: [...new Map(hits.flatMap(h => h.paths).map(p => [JSON.stringify(p), p])).values()] };
170
+ filled++;
171
+ }
172
+ return filled;
173
+ }
174
+
175
+ module.exports = { recoverVersionlessGradle };
@@ -129,6 +129,9 @@ module.exports = {
129
129
  // -e is a groupId regex everywhere else (Maven collector, cleaned-POM rewrite).
130
130
  if (deps2Exclude && deps2Exclude.test(d.group)) return;
131
131
  const rec = makeDepRecord({ ecosystem: "maven", ecosystemType: "gradle", namespace: d.group, name: d.name, version: d.version, manifestPath, scope: d.scope, isDev: d.isDev });
132
+ if (d.configurations) rec.gradleConfigurations = [...d.configurations];
133
+ if (d.gradleDeclarations) rec.gradleDeclarations = d.gradleDeclarations.map(x => ({ configuration: x.configuration, exclusions: [...x.exclusions] }));
134
+ if (extra.versionUnresolved) rec.versionUnresolved = true;
132
135
  if (d.exclusionSets) rec.exclusionSets = d.exclusionSets.map(x => [...x]);
133
136
  if (extra.managedOnly) rec.managedOnly = true;
134
137
  // A constraint (not a force/strictly) is a FLOOR for transitives: Gradle keeps the
@@ -152,6 +155,9 @@ module.exports = {
152
155
  // the first module walked kept scope "test" with isDev false.
153
156
  if (rec.isDev === false && existing.isDev !== false) { existing.isDev = false; existing.scope = rec.scope; }
154
157
  if (rec.exclusionSets) existing.exclusionSets = (existing.exclusionSets || []).concat(rec.exclusionSets);
158
+ if (rec.gradleConfigurations) existing.gradleConfigurations = [...new Set([...(existing.gradleConfigurations || []), ...rec.gradleConfigurations])];
159
+ if (rec.gradleDeclarations) existing.gradleDeclarations = (existing.gradleDeclarations || []).concat(rec.gradleDeclarations);
160
+ if (rec.versionUnresolved) existing.versionUnresolved = true;
155
161
  if (!extra.managedOnly && existing.managedOnly) delete existing.managedOnly;
156
162
  };
157
163
 
@@ -172,7 +178,16 @@ module.exports = {
172
178
  const globalExcludes = [];
173
179
  for (const s of scripts) {
174
180
  const r = parseBuildScript(s.text, { catalog, properties, kotlin: s.kotlin });
175
- for (const b of r.platformBoms) if (b.group && b.name && !platformBoms.some(x => x.group === b.group && x.name === b.name)) platformBoms.push(b);
181
+ for (const b of r.platformBoms) {
182
+ if (b.inferred && buildFiles.length !== 1) {
183
+ // The current collector merges coordinates across scripts, losing which
184
+ // module owns a versionless occurrence. Do not apply one module's implicit
185
+ // Boot BOM to its neighbours until per-module Gradle resolution exists.
186
+ warnings.push({ type: "dependency-coverage", manifestPath: s.fp, message: "Implicit Spring Boot BOM not applied: multiple Gradle scripts require module-scoped resolution. Use a resolved Gradle lockfile or scan this module separately." });
187
+ continue;
188
+ }
189
+ if (b.group && b.name && !platformBoms.some(x => x.group === b.group && x.name === b.name)) platformBoms.push(b.inferred ? { ...b, manifestPath: s.fp } : b);
190
+ }
176
191
  const everything = isConventionPlugin(s.fp);
177
192
  for (const c of r.constraints) if (everything || c.global) globalPins.push({ ...c, fp: s.fp });
178
193
  for (const e of r.configExcludes) if (everything || e.global) globalExcludes.push({ ...e, fp: s.fp });
@@ -189,8 +204,10 @@ module.exports = {
189
204
  const r = parseBuildScript(s.text, { catalog, properties, kotlin: s.kotlin, extraExcludes: globalExcludes.filter(e => e.fp !== fp) });
190
205
  const applicable = r.constraints.map(c => ({ ...c, fp })).concat(globalPins.filter(p => p.fp !== fp));
191
206
  pins.push(...r.constraints.map(c => ({ ...c, fp })));
192
- for (const dep of r.deps) addRec({ ...dep, version: pinnedVersion(dep, applicable) }, fp);
193
- if (!inBuildSrc(fp)) warnings.push({ type: "no-lockfile", manifestPath: fp, message: `no gradle.lockfile next to ${path.relative(dir, fp) || path.basename(fp)} — versions resolved best-effort from the build script + version catalog (dynamic/programmatic deps may be missed). Enable Gradle dependency locking for exact coverage.` });
207
+ for (const dep of r.deps) addRec({ ...dep, version: pinnedVersion(dep, applicable) }, fp, {
208
+ versionUnresolved: r.unresolved.some(u => u.group === dep.group && u.name === dep.name),
209
+ });
210
+ if (!inBuildSrc(fp)) warnings.push({ type: "no-lockfile", manifestPath: fp, message: `no gradle.lockfile next to ${path.relative(dir, fp) || path.basename(fp)} — versions are resolved best-effort from the build script and version catalog. Without native Gradle resolution or a lockfile, POM-based transitive resolution can choose different versions than Gradle, causing incorrect alerts and omissions. Enable Gradle dependency locking for the configurations you need to audit.` });
194
211
  for (const u of r.unresolved) {
195
212
  if (pinnedVersion({ group: u.group, name: u.name, version: null }, applicable)) continue; // a constraint supplies it
196
213
  warnings.push({ type: "unresolved-versions", manifestPath: fp, message: `could not resolve the version variable for ${u.group}:${u.name} (${u.raw}) — excluded from CVE matching` });
@@ -87,7 +87,7 @@ async function detectCodecs(dir, opts = {}) {
87
87
  while (active < DETECT_CONCURRENCY && queue.length && remaining > 0) {
88
88
  const cur = queue.pop();
89
89
  active++;
90
- fs.promises.readdir(cur, { withFileTypes: true }).then(entries => {
90
+ fs.promises.readdir(cur, { withFileTypes: true }).then(async entries => {
91
91
  for (const e of entries) {
92
92
  if (e.isDirectory()) {
93
93
  const child = path.join(cur, e.name);
@@ -98,7 +98,7 @@ async function detectCodecs(dir, opts = {}) {
98
98
  const name = e.name;
99
99
  for (const m of matchers) {
100
100
  if (m.found) continue;
101
- if (m.exact.has(name) || m.exts.some(ext => name.endsWith(ext))) { m.found = true; remaining--; }
101
+ if (m.exact.has(name) || m.exts.some(ext => name.endsWith(ext)) || (m.codec.detectFile && await m.codec.detectFile(path.join(cur, name)))) { if (!m.found) { m.found = true; remaining--; } }
102
102
  }
103
103
  }
104
104
  }).catch(() => { /* unreadable dir → skip */ }).finally(() => { active--; pump(); });
@@ -60,7 +60,7 @@ function buildCsaf(resolvedDeps, cveMatches, opts = {}) {
60
60
  const pid = `PROD-${n++}`;
61
61
  const purl = purlFor(variant.dep);
62
62
  full_product_names.push({ product_id: pid,
63
- name: humanName(variant.dep) + (variant.location ? ` (${variant.location})` : ""),
63
+ name: humanName(variant.dep) + (variant.location ? ` (${variant.location})` : "") + (variant.dep.artifactTargetId ? ` [${variant.dep.artifactTargetId}${variant.dep.artifactPath ? `; ${variant.dep.artifactPath}` : ""}]` : ""),
64
64
  ...(purl ? { product_identification_helper: { purl } } : {}) });
65
65
  return { ...variant, pid };
66
66
  });
@@ -96,21 +96,23 @@ function buildCsaf(resolvedDeps, cveMatches, opts = {}) {
96
96
  let v = byCve.get(id);
97
97
  if (!v) {
98
98
  const cve = m.cve;
99
+ const risk=require('./risk-evidence'),scoreSafe=!risk.relatedRisk(cve,'scoreSource'),severitySafe=!risk.relatedRisk(cve,'severitySource'),kevRelated=risk.relatedSignal(cve,'kev'),epssRelated=risk.relatedSignal(cve,'epss');
99
100
  const notes = [];
101
+ const evidence=risk.evidenceObject(cve);if(Object.keys(evidence).length)notes.push({category:'other',title:'Related risk evidence',text:JSON.stringify(evidence)});
100
102
  if (cve.description) notes.push({ category: "description", text: cve.description, title: "Description" });
101
103
  const extras = [];
102
- if (cve.epssPercentile != null) extras.push(`EPSS percentile ${Math.round(cve.epssPercentile * 100)}%`);
103
- if (cve.kev) extras.push(`CISA KEV (known exploited)${cve.kevDueDate ? `, remediate by ${cve.kevDueDate}` : ""}`);
104
+ if (cve.epssPercentile != null) extras.push(`${epssRelated ? "Related upstream CVE EPSS percentile" : "EPSS percentile"} ${Math.round(cve.epssPercentile * 100)}%`);
105
+ if (cve.kev) extras.push(`${kevRelated ? "Related upstream CVE in CISA KEV" : "CISA KEV (known exploited)"}${cve.kevDueDate ? `, remediate by ${cve.kevDueDate}` : ""}`);
104
106
  if (euvdExploited(cve)) extras.push(`ENISA EUVD (exploited${cve.euvd.exploitedSince ? ` since ${cve.euvd.exploitedSince}` : ""})`);
105
107
  if (cve.priority?.band) extras.push(`vigievuln priority: ${cve.priority.band}${cve.priority.score != null ? ` (${cve.priority.score}/100)` : ""}`);
106
108
  if (extras.length) notes.push({ category: "other", text: extras.join("; "), title: "Prioritization" });
107
109
 
108
110
  const v3ver = cvssV3Version(cve.cvssVersion);
109
- const scores = (v3ver && cve.score != null) ? [{
111
+ const scores = (scoreSafe && v3ver && cve.score != null) ? [{
110
112
  cvss_v3: {
111
113
  version: v3ver,
112
114
  baseScore: cve.score,
113
- baseSeverity: cvssV3Severity(cve.severity, cve.score),
115
+ baseSeverity: cvssV3Severity(severitySafe ? cve.severity : null, cve.score),
114
116
  // Only carry the vector when it actually IS a v3 vector — a v4 (or
115
117
  // mismatched) vector string fails the v3 schema's vectorString pattern.
116
118
  ...((cve.cvssVector && /^CVSS:3\.[01]\//.test(cve.cvssVector)) ? { vectorString: cve.cvssVector } : {}),
@@ -127,11 +129,16 @@ function buildCsaf(resolvedDeps, cveMatches, opts = {}) {
127
129
  ...(notes.length ? { notes } : {}),
128
130
  product_status: { known_affected: [] },
129
131
  ...(scores.length ? { scores } : {}),
130
- ...(cve.kev ? { flags: [{ label: "exploited", product_ids: [] }] } : {}),
132
+ ...(cve.kev && !kevRelated ? { flags: [{ label: "exploited", product_ids: [] }] } : {}),
131
133
  ...(europeanReferences(cve).length ? { references: europeanReferences(cve).map(r => ({ category: "external", summary: r.title ? `${r.source} ${r.id} — ${r.title}` : `${r.source} ${r.id}`, url: r.url })) } : {}),
132
134
  };
133
135
  byCve.set(id, v);
134
136
  }
137
+ const relatedEvidence=require('./risk-evidence').evidenceObject(m.cve);
138
+ if(Object.keys(relatedEvidence).length){const text=JSON.stringify(relatedEvidence);v.notes ||= [];if(!v.notes.some(n=>n.title==='Related risk evidence' && n.text===text))v.notes.push({category:'other',title:'Related risk evidence',text});}
139
+ if(m.cve.historicalEvidence){const text=JSON.stringify({products:pids,evidence:m.cve.historicalEvidence});v.notes ||= [];if(!v.notes.some(n=>n.title==='Historical advisory evidence'&&n.text===text))v.notes.push({category:'other',title:'Historical advisory evidence',text});}
140
+ for(const evidence of require('./applicability-evidence').applicabilityEvidence(m.cve)){const text=JSON.stringify({products:pids,...evidence});v.notes ||= [];if(!v.notes.some(n=>n.title==='Applicability evidence'&&n.text===text))v.notes.push({category:'other',title:'Applicability evidence',text});}
141
+ if(m.cve.vendorEvidence){const text=JSON.stringify({products:pids,evidence:m.cve.vendorEvidence});v.notes ||= [];if(!v.notes.some(n=>n.title==='Vendor advisory evidence'&&n.text===text))v.notes.push({category:'other',title:'Vendor advisory evidence',text});}
135
142
  if (id.startsWith("CVE-") && m.advisoryId) {
136
143
  const system_name = String(m.source || "").includes("wordfence-v3") ? "Wordfence" :
137
144
  String(m.source || "").includes("drupal-security-advisories") ? "Drupal Security Advisory" : "Advisory";
@@ -429,7 +429,7 @@ function walkJsonFiles(dir, onFile) {
429
429
  }
430
430
 
431
431
  async function buildCveIndex(extractDir, opts = {}) {
432
- const { verbose, releaseTag } = opts;
432
+ const { verbose, releaseTag, cacheDir = path.dirname(CVE_DATA_DIR) } = opts;
433
433
  const index = newIndex();
434
434
  let processed = 0;
435
435
  let added = 0;
@@ -455,20 +455,23 @@ async function buildCveIndex(extractDir, opts = {}) {
455
455
  // Keep native records and REJECTED revisions alongside the legacy index.
456
456
  // This incremental import cannot infer withdrawals from absent files, so its
457
457
  // coverage is recorded as partial until a full reconciliation is available.
458
- const store = require('./advisory-store').openAdvisoryStore({cacheDir:path.dirname(CVE_DATA_DIR)});
459
- await require('./native-advisories').importCveDirectory(store,extractDir,{fetchedAt:Date.parse(index.meta.builtAt),provenance:{transport:'direct',releaseTag:releaseTag || null}});
460
- saveCveIndex(index);
458
+ const store = require('./advisory-store').openAdvisoryStore({cacheDir});
459
+ try { await require('./native-advisories').importCveDirectory(store,extractDir,{fetchedAt:Date.parse(index.meta.builtAt),provenance:{transport:'direct',releaseTag:releaseTag || null}}); }
460
+ finally { store.close(); }
461
+ saveCveIndex(index, cacheDir);
461
462
  return index;
462
463
  }
463
464
 
464
- function saveCveIndex(index) {
465
- const db=require('./cache-db').getCacheDb(path.dirname(CVE_DATA_DIR));
466
- const insert=db.prepare('INSERT INTO cve_lookup(kind,lookup_key,source,cve,affected_key,projection_json) VALUES (?,?,?,?,?,?)');
465
+ function saveCveIndex(index, cacheDir = path.dirname(CVE_DATA_DIR)) {
466
+ const db=require('./cache-db').getCacheDb(cacheDir);
467
+ const insert=db.prepare('INSERT OR IGNORE INTO cve_lookup(kind,lookup_key,source,cve,affected_key,projection_json) VALUES (?,?,?,?,?,?)');
468
+ const existing=db.prepare('SELECT projection_json FROM cve_lookup WHERE kind=? AND lookup_key=? AND source=? AND cve=? AND affected_key=?');
467
469
  db.transaction(()=>{
468
470
  db.exec('DELETE FROM cve_lookup');
469
471
  for(const [kind,buckets] of [['package',index.byPackageName],['product',index.byProduct]])for(const [lookup,entries] of Object.entries(buckets))for(const entry of entries){
470
472
  const projection=JSON.stringify(entry),key=require('node:crypto').createHash('sha256').update(projection).digest('hex');
471
- insert.run(kind,lookup,entry.source||'CVEProject',entry.id,key,projection);
473
+ const source=entry.source||'CVEProject',result=insert.run(kind,lookup,source,entry.id,key,projection);
474
+ if(!result.changes && existing.get(kind,lookup,source,entry.id,key)?.projection_json!==projection)throw Error('CVE index projection hash collision');
472
475
  }
473
476
  const stamp=Date.parse(index.meta.builtAt);
474
477
  db.prepare(`INSERT INTO cache_snapshots(namespace,fetched_at,complete,stale,record_count,metadata_json) VALUES (?,?,?,?,?,?)
@@ -477,8 +480,8 @@ function saveCveIndex(index) {
477
480
  });
478
481
  }
479
482
 
480
- function loadCveIndex() {
481
- const db=require('./cache-db').getCacheDb(path.dirname(CVE_DATA_DIR));
483
+ function loadCveIndex(cacheDir = path.dirname(CVE_DATA_DIR)) {
484
+ const db=require('./cache-db').getCacheDb(cacheDir);
482
485
  const snapshot=db.prepare("SELECT metadata_json FROM cache_snapshots WHERE namespace='cve_lookup'").get();
483
486
  if(!snapshot)return null;
484
487
  const statement=db.prepare('SELECT projection_json FROM cve_lookup WHERE kind=? AND lookup_key=?');
@@ -489,9 +492,9 @@ function loadCveIndex() {
489
492
  return {meta:JSON.parse(snapshot.metadata_json),byPackageName:bucket('package'),byProduct:bucket('product')};
490
493
  }
491
494
 
492
- function isCveIndexFresh(maxAgeHours = 4) {
495
+ function isCveIndexFresh(maxAgeHours = 4, cacheDir = path.dirname(CVE_DATA_DIR)) {
493
496
  try {
494
- const meta=loadCveIndex()?.meta;
497
+ const meta=loadCveIndex(cacheDir)?.meta;
495
498
  if (!meta.builtAt) return false;
496
499
  const age = Date.now() - new Date(meta.checkedAt || meta.builtAt).getTime();
497
500
  return age < maxAgeHours * 3600 * 1000;
@@ -499,39 +502,40 @@ function isCveIndexFresh(maxAgeHours = 4) {
499
502
  }
500
503
 
501
504
  async function downloadCveData(opts = {}) {
502
- const { verbose, force, revalidate } = opts;
503
- await fs.promises.mkdir(CVE_DATA_DIR, { recursive: true });
504
- if (!force && !revalidate && isCurrentCveIndex(loadCveIndex()) && isCveIndexFresh()) {
505
+ const { verbose, force, revalidate, cacheDir = path.dirname(CVE_DATA_DIR) } = opts;
506
+ const dataDir=path.join(cacheDir,'cve-data'), extractDir=path.join(dataDir,'extracted'), zipPath=path.join(dataDir,'cves.zip');
507
+ await fs.promises.mkdir(dataDir, { recursive: true });
508
+ if (!force && !revalidate && isCurrentCveIndex(loadCveIndex(cacheDir)) && isCveIndexFresh(4, cacheDir)) {
505
509
  if (verbose) console.log("CVE index is fresh (<4h); skipping download");
506
- return loadCveIndex();
510
+ return loadCveIndex(cacheDir);
507
511
  }
508
512
 
509
513
  if (verbose) console.log("📥 fetching latest CVE release metadata…");
510
514
  const { url, tag, name } = await fetchLatestRelease();
511
515
  if (verbose) console.log(` ${tag} → ${name}`);
512
- const cached=loadCveIndex();
513
- const db=require('./cache-db').getCacheDb(path.dirname(CVE_DATA_DIR));
516
+ const cached=loadCveIndex(cacheDir);
517
+ const db=require('./cache-db').getCacheDb(cacheDir);
514
518
  const snapshot=db.prepare("SELECT complete,stale FROM cache_snapshots WHERE namespace='cve_lookup'").get();
515
519
  if (!force && isCurrentCveIndex(cached) && snapshot?.complete === 1 && snapshot.stale === 0 && tag && cached.meta.releaseTag === tag) {
516
520
  const checkedAt=new Date().toISOString(), meta={...cached.meta,checkedAt};
517
521
  db.prepare("UPDATE cache_snapshots SET fetched_at=?,metadata_json=? WHERE namespace='cve_lookup'").run(Date.parse(checkedAt),JSON.stringify(meta));
518
522
  if (verbose) console.log('CVE release unchanged; retained local index');
519
- return loadCveIndex();
523
+ return loadCveIndex(cacheDir);
520
524
  }
521
525
 
522
526
  if (verbose) console.log("📥 downloading CVE zip (this may take a while)…");
523
- await download(url, CVE_ZIP_PATH, { verbose, tag, name });
527
+ await download(url, zipPath, { verbose, tag, name });
524
528
 
525
529
  if (verbose) console.log("📦 extracting…");
526
- try { await fs.promises.rm(CVE_EXTRACT_DIR, { recursive: true, force: true }); } catch {}
527
- await extractZip(CVE_ZIP_PATH, CVE_EXTRACT_DIR, { verbose });
530
+ try { await fs.promises.rm(extractDir, { recursive: true, force: true }); } catch {}
531
+ await extractZip(zipPath, extractDir, { verbose });
528
532
 
529
533
  if (verbose) console.log("🔎 building Maven CVE index…");
530
- const index = await buildCveIndex(CVE_EXTRACT_DIR, { verbose, releaseTag: tag });
534
+ const index = await buildCveIndex(extractDir, { verbose, releaseTag: tag, cacheDir });
531
535
 
532
536
  // cleanup heavy files
533
- try { await fs.promises.rm(CVE_EXTRACT_DIR, { recursive: true, force: true }); } catch {}
534
- try { await fs.promises.rm(CVE_ZIP_PATH, { force: true }); } catch {}
537
+ try { await fs.promises.rm(extractDir, { recursive: true, force: true }); } catch {}
538
+ try { await fs.promises.rm(zipPath, { force: true }); } catch {}
535
539
 
536
540
  return index;
537
541
  }
@@ -541,15 +545,15 @@ async function downloadCveData(opts = {}) {
541
545
  * downloading/refreshing as needed.
542
546
  */
543
547
  async function ensureCveIndex(opts = {}) {
544
- const { force, offline, verbose, ttlMs = 4 * 3600000 } = opts;
548
+ const { force, offline, verbose, ttlMs = 4 * 3600000, cacheDir = path.dirname(CVE_DATA_DIR) } = opts;
545
549
  if (!Number.isFinite(ttlMs) || ttlMs < 0) throw new Error("invalid CVEProject TTL");
546
- const cached = loadCveIndex();
550
+ const cached = loadCveIndex(cacheDir);
547
551
  if (offline) {
548
552
  if (!cached) throw new Error("--cve-offline set but no cached CVE index found");
549
553
  return cached;
550
554
  }
551
- if (!force && !require('./cache-policy').shouldForceUpdate() && isCurrentCveIndex(cached) && isCveIndexFresh(ttlMs / 3600000)) return cached;
552
- return downloadCveData({ verbose, force: !!force, revalidate: true });
555
+ if (!force && !require('./cache-policy').shouldForceUpdate() && isCurrentCveIndex(cached) && isCveIndexFresh(ttlMs / 3600000, cacheDir)) return cached;
556
+ return downloadCveData({ verbose, force: !!force, revalidate: true, cacheDir });
553
557
  }
554
558
 
555
559
  module.exports = {
package/lib/cve-match.js CHANGED
@@ -221,6 +221,10 @@ function commonExclusions(sets) {
221
221
 
222
222
  async function expandWithTransitives(resolvedDeps, opts = {}) {
223
223
  const { verbose } = opts;
224
+ // Gradle allows a direct declaration to omit its version when another request
225
+ // on the same classpath supplies it. Resolve these before seeding the graph:
226
+ // they remain DIRECT dependencies, with their own scopes and exclusions.
227
+ await require("./codecs/gradle/versionless").recoverVersionlessGradle(resolvedDeps, opts);
224
228
  // Root depMgmt: every dep in the Map that has a concrete version becomes a
225
229
  // version override for transitive resolution. This catches cases where the
226
230
  // project pins a transitive's version via <dependencyManagement>.
@@ -262,6 +266,12 @@ async function expandWithTransitives(resolvedDeps, opts = {}) {
262
266
  // A depMgmt-only pin is not a dependency: it must not seed the graph (it would drag
263
267
  // its whole subtree in). It still pins versions through rootDepMgmt above.
264
268
  .filter(d => !d.managedOnly);
269
+ // An inferred plugin BOM is scoped to its sole Gradle script. Never let it
270
+ // become a version pin for Maven roots or another Gradle module.
271
+ for (const [key, m] of (opts.gradleBomDepMgmt || [])) {
272
+ if (!rootDepMgmt.has(key) && directs.length && directs.every(d => d.ecosystemType === "gradle"
273
+ && d.manifestPaths?.length === 1 && d.manifestPaths[0] === m.manifestPath)) rootDepMgmt.set(key, { version: m.version, exclusions: [] });
274
+ }
265
275
 
266
276
  if (verbose) console.log(`🌳 Resolving transitives for ${directs.length} direct deps…`);
267
277
 
@@ -0,0 +1,19 @@
1
+ 'use strict';
2
+ // Native CVEProject records selected by explicit package identity; no product
3
+ // names, guessed aliases or unverified negative results enter the index.
4
+ const {packageName}=require('./advisory-store');
5
+ const tuple=(ecosystem,name)=>({source:'cveproject',ecosystem,name:packageName(ecosystem,name),version:'*'});
6
+ const key=p=>JSON.stringify([p.ecosystem,packageName(p.ecosystem,p.name)]);
7
+ function packageIdentities(deps){const found=new Map();for(const dep of deps.values()){if(dep.provenance==='binary')continue;const identity=require('./native-package-match').depIdentity(dep);if(identity)for(const ecosystem of [identity.ecosystem,...(identity.ecosystem.startsWith('system:deb:debian:')?['system:deb:debian:*']:[])])for(const name of identity.names){const p={ecosystem,name:packageName(ecosystem,name)};found.set(key(p),p);}}return [...found.values()].sort((a,b)=>key(a).localeCompare(key(b)));}
8
+ async function refreshPackageCves(deps,store,{ttlMs=4*3600000,getResource=require('./providers').getResource}={}){
9
+ const packages=packageIdentities(deps),needed=packages.filter(p=>require('./cache-policy').shouldForceUpdate() || !store.getQuery(tuple(p.ecosystem,p.name),{ttlMs})?.fresh);let incomplete=false,received=0;
10
+ for(let i=0;i<needed.length;i+=200){const batch=needed.slice(i,i+200),res=await getResource('github','cve-packages',{packages:batch},{forceRefresh:true});if(!res.ok)throw Error(`CVEProject package proxy HTTP ${res.status}`);const body=await res.json();if(!Array.isArray(body.records)||typeof body.complete!=='boolean'||body.scope!=='explicit-package-identities')throw Error('invalid CVEProject package proxy response');
11
+ const at=Date.parse(res.headers?.get('x-fad-proxy-fetched-at')||'');if(!Number.isFinite(at)||at<=0||at>Date.now()+300000)throw Error('CVEProject package response has no trustworthy source timestamp');
12
+ const stale=res.headers?.get('x-fad-proxy')==='stale'||Date.now()-at>=require('./cache-policy').DEFAULT_TTL_MS,byKey=new Map(batch.map(p=>[key(p),new Set()])),records=[];
13
+ for(const raw of body.records){const record=require('./native-advisories').cveEnvelope(raw,{fetchedAt:at,provenance:{transport:'proxy',stale}});let relevant=false;for(const container of [raw.containers?.cna,...(raw.containers?.adp||[])])for(const affected of container?.affected||[]){const p=require('./native-package-match').explicitNativePackage(affected,{source:'cveproject',record:raw,container});if(!p)continue;const k=key(p);if(byKey.has(k)){byKey.get(k).add(record.id);relevant=true;}}if(!relevant)throw Error('CVEProject package proxy returned an unrelated record');records.push(record);}
14
+ if(new Set(records.map(x=>x.id)).size!==records.length)throw Error('CVEProject package proxy returned duplicate records');
15
+ const queries=body.complete&&!stale?batch.map(p=>({...tuple(p.ecosystem,p.name),ids:[...byKey.get(key(p))].sort(),fetchedAt:at,complete:true,provenance:{transport:'proxy',scope:'explicit-package-identities'}})):[];store.commit({records,queries});received+=records.length;if(!body.complete||stale)incomplete=true;
16
+ }
17
+ return {packages:packages.length,requested:needed.length,received,incomplete};
18
+ }
19
+ module.exports={packageIdentities,refreshPackageCves,tuple};