vigievuln 1.2.1 → 1.3.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 (110) hide show
  1. package/CHANGELOG.md +7 -1044
  2. package/README.md +37 -64
  3. package/lib/airgap-project.js +35 -7
  4. package/lib/applicability-evidence.js +12 -0
  5. package/lib/artifacts/applications.js +58 -0
  6. package/lib/artifacts/component-scope.js +31 -0
  7. package/lib/artifacts/cve-view.js +108 -0
  8. package/lib/artifacts/enrichment.js +87 -0
  9. package/lib/artifacts/go-main-identity.js +45 -0
  10. package/lib/artifacts/go-publisher-advisories.js +24 -0
  11. package/lib/artifacts/index.js +272 -0
  12. package/lib/artifacts/inventory-scope.js +50 -0
  13. package/lib/artifacts/publisher-advisories.js +12 -0
  14. package/lib/artifacts/remediation-report.js +48 -0
  15. package/lib/artifacts/report-inventory.js +26 -0
  16. package/lib/artifacts/report.js +199 -0
  17. package/lib/artifacts/risk-report.js +120 -0
  18. package/lib/artifacts/sbom.js +68 -0
  19. package/lib/artifacts/scan.js +411 -0
  20. package/lib/cache-archive-sqlite.js +41 -25
  21. package/lib/charts.js +143 -34
  22. package/lib/cli-command-routing.js +20 -6
  23. package/lib/cli-groups.js +2 -1
  24. package/lib/cli-image.js +206 -0
  25. package/lib/codecs/binary/elf-metadata.js +42 -0
  26. package/lib/codecs/binary/go-buildinfo.js +37 -0
  27. package/lib/codecs/binary/metadata.js +7 -0
  28. package/lib/codecs/binary/scan.js +14 -13
  29. package/lib/codecs/binary/sniff.js +16 -15
  30. package/lib/codecs/binary.codec.js +22 -2
  31. package/lib/codecs/gradle/parse.js +63 -2
  32. package/lib/codecs/gradle/versionless.js +175 -0
  33. package/lib/codecs/gradle.codec.js +20 -3
  34. package/lib/codecs/index.js +2 -2
  35. package/lib/csaf-export.js +13 -6
  36. package/lib/cve-download.js +33 -29
  37. package/lib/cve-match.js +10 -0
  38. package/lib/cve-packages-proxy.js +19 -0
  39. package/lib/cve-record-coverage.js +109 -0
  40. package/lib/cve-report.js +348 -181
  41. package/lib/deps-descriptor.js +25 -3
  42. package/lib/diagnostics.js +25 -0
  43. package/lib/diff.js +0 -0
  44. package/lib/epss.js +6 -6
  45. package/lib/euvd.js +40 -6
  46. package/lib/finding-enrichment.js +166 -0
  47. package/lib/finding-summary.js +5 -4
  48. package/lib/i18n.js +48 -10
  49. package/lib/image-network.js +54 -0
  50. package/lib/image-references.js +203 -0
  51. package/lib/image-registry.js +385 -0
  52. package/lib/image-update.js +39 -0
  53. package/lib/json-export.js +53 -9
  54. package/lib/kev.js +6 -6
  55. package/lib/maven-bom.js +2 -1
  56. package/lib/merge-sources.js +3 -0
  57. package/lib/native-advisories.js +9 -7
  58. package/lib/native-cna-identities.js +12 -0
  59. package/lib/native-package-match.js +159 -0
  60. package/lib/native-source-prepare.js +60 -0
  61. package/lib/nvd.js +79 -32
  62. package/lib/osv.js +33 -14
  63. package/lib/project-descriptor.js +3 -2
  64. package/lib/provenance.js +8 -2
  65. package/lib/providers/alpine.js +8 -0
  66. package/lib/providers/common.js +11 -3
  67. package/lib/providers/debian.js +11 -0
  68. package/lib/providers/euvd.js +2 -1
  69. package/lib/providers/freexian.js +13 -0
  70. package/lib/providers/github.js +1 -0
  71. package/lib/providers/go.js +2 -1
  72. package/lib/providers/index.js +23 -19
  73. package/lib/providers/nginx.js +5 -0
  74. package/lib/providers/nvd.js +1 -1
  75. package/lib/providers/osv.js +1 -1
  76. package/lib/providers/osvdb.js +2 -2
  77. package/lib/proxy-throttle.js +89 -29
  78. package/lib/purl.js +10 -2
  79. package/lib/record-freshness.js +22 -0
  80. package/lib/report-notices.js +82 -0
  81. package/lib/report-time.js +45 -0
  82. package/lib/request-failure.js +22 -0
  83. package/lib/resource-cache/engine.js +130 -26
  84. package/lib/resource-cache/snapshot-projection.js +33 -0
  85. package/lib/resource-cache/validate.js +22 -5
  86. package/lib/risk-evidence.js +18 -0
  87. package/lib/sarif-export.js +17 -9
  88. package/lib/sbom-export.js +32 -12
  89. package/lib/source-health.js +57 -16
  90. package/lib/source-image-scan.js +57 -0
  91. package/lib/source-profile.js +6 -3
  92. package/lib/system-inventory/advisories.js +170 -0
  93. package/lib/system-inventory/alpine-tracker.js +47 -0
  94. package/lib/system-inventory/collect.js +118 -0
  95. package/lib/system-inventory/current-debian.js +99 -0
  96. package/lib/system-inventory/distribution-sources.js +132 -0
  97. package/lib/system-inventory/freexian-ela.js +32 -0
  98. package/lib/system-inventory/freexian-release-evidence.js +35 -0
  99. package/lib/system-inventory/freexian-tracker.js +72 -0
  100. package/lib/system-inventory/historical-debian.js +196 -0
  101. package/lib/system-inventory/index.js +2 -0
  102. package/lib/system-inventory/nginx-advisories.js +39 -0
  103. package/lib/system-inventory/rpm-storage.js +86 -0
  104. package/lib/system-inventory/targeted.js +70 -0
  105. package/lib/system-inventory/versions.js +59 -0
  106. package/lib/transitive.js +11 -2
  107. package/lib/ui.js +8 -5
  108. package/lib/unmanaged.js +1 -1
  109. package/package.json +12 -3
  110. package/vigievuln.js +225 -102
@@ -0,0 +1,37 @@
1
+ // Go linker build-info blob; supports inline and pre-1.18 pointer formats.
2
+ const MAGIC = Buffer.from('\xff Go buildinf:', 'latin1');
3
+ function extractGoBuildInfo({read, segments, mapped, max}) {
4
+ try {
5
+ let budget = max, skipped = false;
6
+ for (const s of segments.filter(x => x.type === 1 && (x.flags & 2) && x.filesz)) {
7
+ if (s.filesz > budget) { skipped = true; continue; }
8
+ budget -= s.filesz;
9
+ const b = read(s.offset,s.filesz);
10
+ for (let pos = b.indexOf(MAGIC); pos >= 0; pos = b.indexOf(MAGIC,pos+1)) {
11
+ if ((s.vaddr+pos)%16 || pos+32>b.length) continue;
12
+ const ptrSize=b[pos+14], flags=b[pos+15]; if (![4,8].includes(ptrSize) || (flags & ~3)) continue;
13
+ const le=!(flags&1);
14
+ const ptr=(buf,p) => { const n=ptrSize===4 ? BigInt(le?buf.readUInt32LE(p):buf.readUInt32BE(p)) : le?buf.readBigUInt64LE(p):buf.readBigUInt64BE(p); if(n>BigInt(Number.MAX_SAFE_INTEGER)) throw Error('pointer overflow'); return Number(n); };
15
+ const memory=(addr,n)=>read(mapped(addr,n),n);
16
+ let version, mod;
17
+ if (flags&2) {
18
+ let p=pos+32;
19
+ const string=()=>{ let n=0, mult=1, c, count=0; do { if(p>=b.length || count++>=8) throw Error('varint'); c=b[p++]; n+=(c&127)*mult; mult*=128; } while(c&128); if(!Number.isSafeInteger(n) || n>max || p+n>b.length) throw Error('string bounds'); const t=b.toString('latin1',p,p+n); p+=n; return t; };
20
+ version=string(); mod=string();
21
+ } else {
22
+ const str=addr=>{ if(!addr)return ''; const hdr=memory(addr,ptrSize*2), start=ptr(hdr,0), len=ptr(hdr,ptrSize); if(len>max) throw Error('string limit'); return memory(start,len).toString('latin1'); };
23
+ version=str(ptr(b,pos+16)); mod=str(ptr(b,pos+16+ptrSize));
24
+ }
25
+ if (!version.startsWith('go')) continue;
26
+ // Module text is surrounded by 16-byte sentinels, as in debug/buildinfo.
27
+ if (mod.length >= 33 && mod[mod.length-17] === '\n') mod=Buffer.from(mod.slice(16,-16),'latin1').toString('utf8'); else mod='';
28
+ const modules=[],settings={}; let last=null;
29
+ for (const line of mod.split('\n')) { const f=line.split('\t'); if ((f[0]==='mod'||f[0]==='dep') && f.length>=3) { last={kind:f[0],path:f[1],version:f[2],sum:f[3]||null}; modules.push(last); } else if(f[0]==='=>' && last && f.length>=2) last.replace={path:f[1],version:f[2] || null,sum:f[3]||null}; else if(f[0]==='build' && f.length===2) { const i=f[1].indexOf('='); if(i>0) {const key=f[1].slice(0,i),value=f[1].slice(i+1);if(/^[A-Za-z0-9_.-]{1,80}$/.test(key) && value.length<=1024) {if(Object.hasOwn(settings,key))settings[key]=null;else settings[key]=value;}} } }
30
+ return { version, modules, settings };
31
+ }
32
+ }
33
+ if (skipped) return {status:'unavailable',reason:'Go build information search exceeded metadata limit'};
34
+ } catch { return {status:'unavailable',reason:'Malformed Go build information'}; }
35
+ return null;
36
+ }
37
+ module.exports={extractGoBuildInfo};
@@ -0,0 +1,7 @@
1
+ // Format registry keeps new binary parsers independent of the walker.
2
+ const extractors = new Map([
3
+ ['pe', (fd,size) => require('./pe-metadata').extractPeMetadataFile(fd,size)],
4
+ ['elf', (fd,size,opts) => require('./elf-metadata').extractElfMetadataFile(fd,size,opts)],
5
+ ]);
6
+ function extractMetadata(kind,fd,size,opts) { const fn=extractors.get(kind); return fn ? fn(fd,size,opts) : {format:kind,status:'unsupported'}; }
7
+ module.exports={extractors,extractMetadata};
@@ -3,9 +3,8 @@
3
3
  * (.dll/.exe/.so/.dylib) and hash each. Dependency archives (.jar/.war/.ear) are
4
4
  * owned by the Maven codec's jar-scan.js, not here.
5
5
  *
6
- * Selection requires BOTH an allowlisted extension AND a confirming magic byte
7
- * (sniff.js), so images/fonts/assets — even with a spoofed extension — are never
8
- * hashed or reported.
6
+ * ELF magic is recognized regardless of filename; PE and Mach-O also require
7
+ * an appropriate extension. Other data and spoofed extensions are rejected.
9
8
  *
10
9
  * @author: N.BRAUN
11
10
  * @email: pp9ping@gmail.com
@@ -28,7 +27,7 @@ const MAGIC_BYTES = 8; // enough for every signature we sniff
28
27
  const MAX_FILE_BYTES = 512 * 1024 * 1024;
29
28
  const HASH_CHUNK_BYTES = 1024 * 1024;
30
29
 
31
- function inspectFile(fp, kind, detectOnly) {
30
+ function inspectFile(fp, kind, detectOnly, opts = {}) {
32
31
  let fd;
33
32
  try {
34
33
  fd = fs.openSync(fp, "r");
@@ -36,9 +35,12 @@ function inspectFile(fp, kind, detectOnly) {
36
35
  if (!before.isFile()) throw Error("not a regular file");
37
36
  const magic = Buffer.alloc(MAGIC_BYTES);
38
37
  const n = fs.readSync(fd, magic, 0, magic.length, 0);
39
- if (sniffKind(magic.subarray(0, n)) !== kind) return null;
40
- if (detectOnly) return {};
41
- if (before.size > MAX_FILE_BYTES) throw Error(`file size ${before.size} exceeds binary scan limit ${MAX_FILE_BYTES} bytes`);
38
+ const actual = sniffKind(magic.subarray(0, n));
39
+ if (!actual || (actual !== "elf" && actual !== kind)) return null;
40
+ kind = actual;
41
+ if (detectOnly) return { kind };
42
+ const limit = opts.maxFileBytes ?? MAX_FILE_BYTES;
43
+ if (before.size > limit) throw Error(`file size ${before.size} exceeds binary scan limit ${limit} bytes`);
42
44
  const sha1 = crypto.createHash("sha1"), sha256 = crypto.createHash("sha256");
43
45
  const chunk = Buffer.alloc(Math.min(HASH_CHUNK_BYTES, before.size));
44
46
  let offset = 0;
@@ -48,11 +50,11 @@ function inspectFile(fp, kind, detectOnly) {
48
50
  sha1.update(chunk.subarray(0, count)); sha256.update(chunk.subarray(0, count));
49
51
  offset += count;
50
52
  }
51
- const metadata = kind === "pe" ? require("./pe-metadata").extractPeMetadataFile(fd, before.size) : null;
53
+ const metadata = require("./metadata").extractMetadata(kind, fd, before.size, opts);
52
54
  const after = fs.fstatSync(fd);
53
55
  if (after.size !== before.size || after.mtimeMs !== before.mtimeMs || after.ctimeMs !== before.ctimeMs)
54
56
  throw Error("file changed during binary scan");
55
- return { size: offset, sha1: sha1.digest("hex"), sha256: sha256.digest("hex"), metadata };
57
+ return { kind, size: offset, sha1: sha1.digest("hex"), sha256: sha256.digest("hex"), metadata };
56
58
  } finally { if (fd !== undefined) fs.closeSync(fd); }
57
59
  }
58
60
 
@@ -73,12 +75,11 @@ function scanBinaries(dir, opts = {}) {
73
75
  if (e.isDirectory()) { if (!skipDir(fp, e.name)) stack.push(fp); continue; }
74
76
  if (!e.isFile()) continue;
75
77
  const ext = extKind(e.name);
76
- if (!ext) continue; // not an allowlisted extension
77
78
  try {
78
- if (onProgress) onProgress(fp);
79
- const h = inspectFile(fp, ext, opts.detectOnly);
79
+ const h = inspectFile(fp, ext, opts.detectOnly, opts);
80
80
  if (!h) continue;
81
- out.push({ path: fp, kind: ext, ...h, declaredName: e.name });
81
+ if (onProgress) onProgress(fp);
82
+ out.push({ path: fp, ...h, declaredName: e.name });
82
83
  if (opts.detectOnly) return out;
83
84
  } catch (error) { warn(fp, error); }
84
85
  }
@@ -1,26 +1,27 @@
1
1
  /**
2
2
  * lib/codecs/binary/sniff.js — file-type confirmation for the binary codec.
3
3
  *
4
- * Two gates: extKind() (extension allowlist) AND sniffKind() (magic bytes). A
5
- * candidate is accepted only when both agree, so an image renamed `.so` (PNG
6
- * magic) is rejected. We never trust the extension alone.
4
+ * ELF is identified by magic irrespective of filename. PE and Mach-O retain
5
+ * extension and magic confirmation, avoiding ambiguous signatures.
7
6
  *
8
7
  * @author: N.BRAUN
9
8
  * @email: pp9ping@gmail.com
10
9
  */
11
10
 
12
- // Magic-byte signatures → family. Mach-O has four (32/64-bit + fat, both endian).
11
+ // Format detectors are ordered; extensions remain hints for formats whose
12
+ // signatures can overlap other file types (notably Mach-O fat binaries).
13
+ const detectors = [
14
+ { kind: "pe", matches: b => b[0] === 0x4d && b[1] === 0x5a },
15
+ { kind: "elf", matches: b => b[0] === 0x7f && b[1] === 0x45 && b[2] === 0x4c && b[3] === 0x46 },
16
+ { kind: "zip", matches: b => b[0] === 0x50 && b[1] === 0x4b && b[2] === 0x03 && b[3] === 0x04 },
17
+ { kind: "macho", matches: b => {
18
+ const signatures = [0xfeedface, 0xfeedfacf, 0xcafebabe, 0xcafebabf];
19
+ return signatures.includes(b.readUInt32BE(0)) || signatures.includes(b.readUInt32LE(0));
20
+ } },
21
+ ];
13
22
  function sniffKind(buf) {
14
- if (!buf || buf.length < 4) return null;
15
- const b0 = buf[0], b1 = buf[1], b2 = buf[2], b3 = buf[3];
16
- if (b0 === 0x4d && b1 === 0x5a) return "pe"; // MZ
17
- if (b0 === 0x7f && b1 === 0x45 && b2 === 0x4c && b3 === 0x46) return "elf"; // \x7FELF
18
- if (b0 === 0x50 && b1 === 0x4b && b2 === 0x03 && b3 === 0x04) return "zip"; // PK\x03\x04
19
- const be = ((b0 << 24) | (b1 << 16) | (b2 << 8) | b3) >>> 0;
20
- const le = ((b3 << 24) | (b2 << 16) | (b1 << 8) | b0) >>> 0;
21
- const machO = new Set([0xfeedface, 0xfeedfacf, 0xcafebabe, 0xcafebabf]);
22
- if (machO.has(be) || machO.has(le)) return "macho";
23
- return null;
23
+ if (!buf || buf.length < 4) return null;
24
+ return detectors.find(d => d.matches(buf))?.kind || null;
24
25
  }
25
26
 
26
27
  const EXT_PE = /\.(dll|exe)$/i;
@@ -34,4 +35,4 @@ function extKind(name) {
34
35
  return null;
35
36
  }
36
37
 
37
- module.exports = { sniffKind, extKind };
38
+ module.exports = { sniffKind, extKind, detectors };
@@ -17,7 +17,11 @@ module.exports = {
17
17
  id: "binary",
18
18
  label: "Binaries",
19
19
  osvEcosystem: null, // no OSV ecosystem until identified
20
- manifestNames: ["*.dll", "*.exe", "*.so", "*.dylib"], // lets detectCodecs include us in auto mode
20
+ manifestNames: ["*.dll", "*.exe", "*.so", "*.dylib"],
21
+ async detectFile(fp) {
22
+ const fs = require("fs"); let handle;
23
+ try { handle = await fs.promises.open(fp, "r"); const b = Buffer.alloc(4); const { bytesRead } = await handle.read(b, 0, 4, 0); return require("./binary/sniff").sniffKind(b.subarray(0, bytesRead)) === "elf"; } catch { return false; } finally { if (handle) await handle.close(); }
24
+ }, // lets detectCodecs include us in auto mode
21
25
 
22
26
  detect(dir) {
23
27
  try {
@@ -31,7 +35,7 @@ module.exports = {
31
35
  const out = new Map();
32
36
  const warnings = [];
33
37
  let records;
34
- try { records = scanBinaries(dir, { onProgress: opts.onBinaryProgress, onWarning: warning => warnings.push(warning), srcRoot: opts.srcRoot || dir, excludePath: opts.excludePath, defaultExcludes: opts.defaultExcludes }); }
38
+ try { records = scanBinaries(dir, { ...opts, onProgress: opts.onBinaryProgress, onWarning: warning => warnings.push(warning), srcRoot: opts.srcRoot || dir, excludePath: opts.excludePath, defaultExcludes: opts.defaultExcludes }); }
35
39
  catch (e) { return { deps: out, warnings: [{ type: "dependency-coverage", reason: "binary-scan-error", ecosystem: "binary", manifestPath: dir, message: `binary scan failed: ${e.message}` }] }; }
36
40
  for (const r of records) {
37
41
  const record = makeDepRecord({
@@ -45,6 +49,22 @@ module.exports = {
45
49
  });
46
50
  if (r.metadata) record.binaryMetadata = r.metadata;
47
51
  out.set(`binary:${r.path}`, record);
52
+ const goVersion = /^go(\d+)\.(\d+)(?:\.(\d+))?$/.exec(r.metadata?.go?.version || "");
53
+ if (goVersion) {
54
+ const version = `v${goVersion[1]}.${goVersion[2]}.${goVersion[3] || "0"}`;
55
+ const dep = makeDepRecord({ ecosystem: "go", name: "stdlib", version, manifestPath: r.path, provenance: "binary-module", scope: "transitive" });
56
+ dep.coordKey = `binary-module:${r.path}:stdlib@${version}`;
57
+ dep.binaryEvidence = { binaryPath: r.path, source: "go-buildinfo", runtimeVersion: r.metadata.go.version, symbolReachability: "unknown" };
58
+ out.set(dep.coordKey, dep);
59
+ }
60
+ for (const module of r.metadata?.go?.modules || []) {
61
+ const selected = module.replace || module;
62
+ if (!selected.path || !/^v\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.+-]+)?$/.test(selected.version || "")) continue;
63
+ const dep = makeDepRecord({ ecosystem: "go", name: selected.path, version: selected.version, manifestPath: r.path, provenance: "binary-module", scope: "transitive" });
64
+ dep.coordKey = `binary-module:${r.path}:${selected.path}@${selected.version}`;
65
+ dep.binaryEvidence = { binaryPath: r.path, source: "go-buildinfo", original: module };
66
+ out.set(dep.coordKey, dep);
67
+ }
48
68
  }
49
69
  return { deps: out, warnings };
50
70
  },
@@ -20,7 +20,7 @@
20
20
  * @author: N.BRAUN
21
21
  * @email: pp9ping@gmail.com
22
22
  */
23
- const { resolveLibraryAccessor, findCatalogVersion } = require("./catalog");
23
+ const { resolveLibraryAccessor, findCatalogVersion, normKey } = require("./catalog");
24
24
  const { compareMavenVersions } = require("../../maven-version");
25
25
 
26
26
  const COORD = "[A-Za-z0-9_.\\-]+";
@@ -79,6 +79,8 @@ function resolveVer(raw, ctx) {
79
79
  m = v.match(/\$\{?([\w.]+)\}?/);
80
80
  if (m) {
81
81
  const k = m[1];
82
+ if (ctx.ambiguousVars?.has(k)) return null;
83
+ if (ctx.extVars?.has(k) && m[0] !== v) return null;
82
84
  if (ctx.localVars && ctx.localVars[k] != null) return ctx.localVars[k];
83
85
  if (ctx.properties && ctx.properties[k] != null) return ctx.properties[k];
84
86
  }
@@ -338,6 +340,38 @@ function findExcludes(clean, mask, from, to) {
338
340
  return out;
339
341
  }
340
342
 
343
+ // Spring Boot imports its matching BOM only when BOTH plugins are applied. Limit
344
+ // inference to a top-level plugins block: pluginManagement, apply false, comments
345
+ // and strings do not establish that either plugin runs in this project.
346
+ function springBootBom(clean, mask, blocks, ctx) {
347
+ const applied = new Map();
348
+ for (const block of blocks) {
349
+ if (block.header !== "plugins" || enclosingBlocks(blocks, block.open).length) continue;
350
+ const declarations = [...clean.slice(block.open + 1, block.close).matchAll(
351
+ /\b(?:id\s*(?:\(\s*)?(["'])([^"']+)\1\s*\)?|alias\s*\(\s*libs\.plugins\.([\w.]+)\s*\))/g
352
+ )].filter(m => mask[block.open + 1 + m.index] !== " ");
353
+ for (let i = 0; i < declarations.length; i++) {
354
+ const m = declarations[i];
355
+ const start = block.open + 1 + m.index + m[0].length;
356
+ const end = i + 1 < declarations.length ? block.open + 1 + declarations[i + 1].index : block.close;
357
+ const suffix = clean.slice(start, end);
358
+ if (/\bapply\s*(?:\(\s*)?false\b/.test(mask.slice(start, end))) continue;
359
+ const plugin = m[3] && Object.entries(ctx.catalog?.plugins || {}).find(([alias]) => normKey(alias) === normKey(m[3]))?.[1];
360
+ const id = m[2] || plugin?.id;
361
+ const versionExpr = suffix.match(/^\s*\.?\s*version\s*(?:\(\s*)?(["'])(.*?)\1/s);
362
+ let version = versionExpr ? versionExpr[2] : plugin?.version;
363
+ // Only resolve a whole variable here; resolveVer's best-effort dependency
364
+ // parsing would turn "4.${patch}" into just the value of patch.
365
+ if (version?.includes("$")) version = /^\$(?:[\w.]+|\{[\w.]+\})$/.test(version) ? resolveVer(version, ctx) : null;
366
+ if (id) applied.set(id, version || null);
367
+ }
368
+ }
369
+ const version = applied.get("org.springframework.boot");
370
+ // Unknown and dynamic versions cannot identify a concrete BOM safely.
371
+ if (!applied.has("io.spring.dependency-management") || !version || !/^\d[\w.\-]*$/.test(version)) return null;
372
+ return { group: "org.springframework.boot", name: "spring-boot-dependencies", version, inferred: true };
373
+ }
374
+
341
375
  /**
342
376
  * Best-effort parse of a build.gradle / build.gradle.kts.
343
377
  * @param opts { catalog, properties, kotlin, extraExcludes } — catalog from
@@ -359,6 +393,28 @@ function parseBuildScript(text, opts = {}) {
359
393
  const { clean, mask } = lexScript(src);
360
394
  for (const m of clean.matchAll(/\b(?:val|def)\s+(\w+)\s*=\s*["']([^"']*)["']/g)) ctx.localVars[m[1]] = m[2];
361
395
  const blocks = scriptBlocks(clean, mask);
396
+ if (!opts.kotlin) {
397
+ // Recognize only literal assignments directly in a top-level Groovy ext
398
+ // block. Any other assignment to the same name makes its value uncertain.
399
+ const assignments = [...mask.matchAll(/\b([A-Za-z_]\w*)\s*(?:\*\*=|<<=|>>>=|>>=|\+=|-=|\*=|\/=|%=|&=|\|=|\^=|=(?!=))/g)];
400
+ const extAssignments = assignments.filter(m => {
401
+ const parents = enclosingBlocks(blocks, m.index);
402
+ return parents.length === 1 && parents[0].header === "ext" && !/[\w.]/.test(mask[m.index - 1] || "");
403
+ });
404
+ // Indexed or method-based writes may compute the property name at runtime.
405
+ const indirectWrite = /\b(?:ext|(?:project\s*\.\s*)?ext)\s*(?:\[|\.\s*(?:set|setProperty)\s*\()|\b(?:setProperty|setExtProperty)\s*\(/.test(mask);
406
+ ctx.ambiguousVars = new Set();
407
+ ctx.extVars = new Set();
408
+ for (const m of extAssignments) {
409
+ const name = m[1];
410
+ const literal = clean.slice(m.index + m[0].length).match(/^[ \t]*(["'])(\d[\w.\-]*)\1(?=[ \t]*(?:;|\n|}|$))/);
411
+ const mutated = new RegExp(`(?:\\b${name}\\s*(?:\\+\\+|--)|(?:\\+\\+|--)\\s*(?:[A-Za-z_]\\w*\\s*\\.\\s*)*${name}\\b)`).test(mask);
412
+ if (!literal || indirectWrite || mutated || assignments.filter(a => a[1] === name).length !== 1 || !/^\w+\s*=$/.test(m[0])) {
413
+ ctx.ambiguousVars.add(name);
414
+ delete ctx.localVars[name];
415
+ } else { ctx.localVars[name] = literal[2]; ctx.extVars.add(name); }
416
+ }
417
+ }
362
418
  const blockAt = new Map(blocks.map(b => [b.open, b]));
363
419
  const isGlobal = idx => enclosingBlocks(blocks, idx).some(b => GLOBAL_HEADER.test(b.header));
364
420
 
@@ -380,6 +436,9 @@ function parseBuildScript(text, opts = {}) {
380
436
  if (coord && coord.group && coord.name && !platformBoms.some(b => b.group === coord.group && b.name === coord.name)) platformBoms.push(coord);
381
437
  blankSpans.push([pm.index, end + 1]);
382
438
  }
439
+ // Keep an explicit platform declaration authoritative when it names this BOM.
440
+ const bootBom = springBootBom(clean, mask, blocks, ctx);
441
+ if (bootBom && !platformBoms.some(b => b.group === bootBom.group && b.name === bootBom.name)) platformBoms.push(bootBom);
383
442
 
384
443
  // 2. force(…) / forcedModules = [ … ] — a FORCE is a version constraint that wins over
385
444
  // every other requirement, not a dependency: it only applies if something brings the
@@ -507,10 +566,12 @@ function parseBuildScript(text, opts = {}) {
507
566
  const scope = depScope(d.config);
508
567
  const existing = byKey.get(key);
509
568
  if (!existing) {
510
- byKey.set(key, { group: d.group, name: d.name, version, configuration: d.config, ...scope, exclusionSets: [exclusions] });
569
+ byKey.set(key, { group: d.group, name: d.name, version, configuration: d.config, configurations: [d.config], ...scope, exclusionSets: [exclusions], gradleDeclarations: [{ configuration: d.config, exclusions }] });
511
570
  continue;
512
571
  }
513
572
  existing.exclusionSets.push(exclusions);
573
+ existing.gradleDeclarations.push({ configuration: d.config, exclusions });
574
+ if (!existing.configurations.includes(d.config)) existing.configurations.push(d.config);
514
575
  // The WIDEST scope wins (a production declaration beats a test one, whatever the
515
576
  // order): `testImplementation` listed above `implementation` used to file the dep as
516
577
  // test-only — out of the production count and the CI gate. The version follows the
@@ -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";