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
@@ -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};
@@ -0,0 +1,109 @@
1
+ 'use strict';
2
+ // Record retrieval is distinct from dependency/advisory discovery. These facts
3
+ // describe already identified CVEs and must not invalidate inventory coverage.
4
+ const {failureKey}=require('./providers/common');
5
+ const recordSources=new Set(['nvd','euvd','euvd-details']);
6
+ const cveIds=cve=>[...new Set([cve?.id,...(cve?.aliases||[]),...(cve?.upstream||[])]
7
+ .filter(id=>typeof id==='string' && /^CVE-\d{4}-\d{4,}$/i.test(id)).map(id=>id.toUpperCase()))];
8
+ function reasonOf(value,fallback='unavailable') {
9
+ const text=String(value?.reason||value?.failure?.reason||value||'');
10
+ const status=value?.failure?.status || value?.statusCode || (typeof value?.status==='number'?value.status:null);
11
+ if(status===429 || /429|rate.limit/i.test(text))return 'rate limit';
12
+ if(/offline/i.test(text))return 'offline';
13
+ if(/disabled|excluded/i.test(text))return 'disabled';
14
+ if(/not.consulted/i.test(text))return 'not consulted';
15
+ if(/no.match|not.listed|not.found|404/i.test(text))return 'not listed';
16
+ if(/timeout|timed.out|ETIMEDOUT/i.test(text))return 'timeout';
17
+ if(status===403 || /403|forbidden/i.test(text))return 'access denied';
18
+ if(/invalid|malformed|mismatch/i.test(text))return 'invalid response';
19
+ if(/budget|request.limit/i.test(text))return 'request limit';
20
+ if(/stale|freshness|timestamp/i.test(text))return 'freshness unconfirmed';
21
+ const http=/HTTP\s*(\d{3})/i.exec(text);if(http)return `HTTP ${http[1]}`;
22
+ if(/network|unreachable|ENOTFOUND|ECONN/i.test(text))return 'network error';
23
+ return fallback;
24
+ }
25
+ function summarizeCveRecords(matches=[],opts={}) {
26
+ const selected=opts.enrich;
27
+ const enabled=name=>opts[name]!==false && (!Array.isArray(selected)||selected.includes(name));
28
+ const active={nvd:enabled('nvd'),euvd:enabled('euvd')};
29
+ const byId=new Map(),keys=new Set();
30
+ const consultations=opts.coverage||[];
31
+ for(const check of consultations)if(recordSources.has(check.collector))for(const key of check.requestKeys||[])keys.add(key);
32
+ function store(id,source,state){
33
+ if(!byId.has(id))byId.set(id,{id});
34
+ const record=byId.get(id),old=record[source];
35
+ // Different components can reference the same CVE: one usable record covers it.
36
+ const rank=s=>s.status==='available'?(s.stale?3:4):s.status==='no-match'?2:1;
37
+ const failures=[...new Set([...(old?.refreshFailureReasons||[]),...(state.refreshFailed?[state.reason||'unavailable']:[])])].sort();
38
+ const best=!old || rank(state)>rank(old)?state:old;
39
+ record[source]={...best,...(failures.length?{refreshFailed:true,refreshFailureReasons:failures}:{})};
40
+ }
41
+ for(const match of matches){const cve=match.cve||{},ids=cveIds(cve);
42
+ for(const id of ids){
43
+ const evidence=(cve.cveEvidence||[]).find(e=>String(e.id).toUpperCase()===id)||{};
44
+ const nvd=evidence.nvdRecordEvidence || (String(cve.id).toUpperCase()===id?cve.nvdRecordEvidence:null);
45
+ const nvdRecord=cve.nvdEvidence?.records?.some(r=>String(r.id).toUpperCase()===id);
46
+ const euvdEvidence=evidence.euvdDetailsEvidence || (ids.length===1?cve.euvdDetailsEvidence:null)||{};
47
+ const mapping=evidence.euvdEvidence || (ids.length===1?cve.euvdEvidence:null)||{};
48
+ const detail=evidence.euvdDetails || (ids.length===1?cve.euvdDetails:null);
49
+ const hasDetail=!!detail && /^EUVD-\d{4}-\d+$/.test(detail.id||'');
50
+ const sourceFailure=consultations.find(c=>['euvd','euvd-details'].includes(c.collector)&&['failed','partial'].includes(c.execution));
51
+ const euvdReason=euvdEvidence.failure || euvdEvidence.reason || mapping.reason || (mapping.status==='no-match'?'not listed':null) || (opts.offline?'offline':sourceFailure?.reason);
52
+ const states={nvd:nvd || (nvdRecord?{status:'available'}:{status:'unavailable',reason:opts.offline?'offline':'not consulted'}),
53
+ euvd:{status:hasDetail?'available':mapping.status==='no-match'?'no-match':'unavailable',stale:!!euvdEvidence.stale,
54
+ refreshFailed:!!mapping.refreshFailed || (hasDetail && !!euvdEvidence.failure),...((!hasDetail || euvdEvidence.stale || mapping.refreshFailed)?{reason:reasonOf(euvdReason)}:{})}};
55
+ for(const source of ['nvd','euvd']){const state=states[source];store(id,source,active[source]?{...state,...((state.reason || state.status!=='available')?{reason:reasonOf(state.reason,state.status==='no-match'?'not listed':'unavailable')}:{})}:{status:'disabled',reason:'disabled'});}
56
+ if(active.nvd){keys.add(failureKey('nvd','cve',{id}));keys.add(failureKey('nvd','cve-mirror',{id}));}
57
+ const euvdId=detail?.id || evidence.euvd?.id || (ids.length===1?cve.euvd?.id:null);
58
+ if(active.euvd && euvdId)keys.add(failureKey('euvd','vulnerability',{id:euvdId}));
59
+ }
60
+ }
61
+ const records=[...byId.values()].sort((a,b)=>a.id.localeCompare(b.id));
62
+ const groups={neither:[],nvdOnly:[],euvdOnly:[],refreshFailed:[],stale:[]};
63
+ for(const r of records){const n=r.nvd.status==='available',e=r.euvd.status==='available';
64
+ if(!n&&!e)groups.neither.push(r);else if(n&&!e)groups.nvdOnly.push(r);else if(e&&!n)groups.euvdOnly.push(r);
65
+ if(r.nvd.refreshFailed||r.euvd.refreshFailed)groups.refreshFailed.push(r);
66
+ if(r.nvd.stale||r.euvd.stale)groups.stale.push(r);
67
+ }
68
+ const counts=Object.fromEntries(Object.entries(groups).map(([key,rows])=>[key,rows.length]));
69
+ const reasons=(rows,sources)=>{const tally=new Map();for(const r of rows){const values=new Set(sources.filter(s=>active[s]&&r[s].status!=='available').map(s=>`${s.toUpperCase()}: ${r[s].reason}`));for(const v of values)tally.set(v,(tally.get(v)||0)+1);}return [...tally].sort().map(([k,n])=>`${k} ${n}`).join(', ');};
70
+ const problem=(active.nvd||active.euvd) && (counts.neither || (active.euvd&&counts.nvdOnly) || (active.nvd&&counts.euvdOnly) || counts.refreshFailed || counts.stale);
71
+ const parts=[];
72
+ if(counts.neither)parts.push(`${counts.neither} CVE record(s) obtained from neither NVD nor EUVD (${reasons(groups.neither,['nvd','euvd'])})`);
73
+ if(active.euvd && counts.nvdOnly)parts.push(`${counts.nvdOnly} obtained from NVD only (${reasons(groups.nvdOnly,['euvd'])})`);
74
+ if(active.nvd && counts.euvdOnly)parts.push(`${counts.euvdOnly} obtained from EUVD only (${reasons(groups.euvdOnly,['nvd'])})`);
75
+ if(counts.refreshFailed){const why=[...new Set(groups.refreshFailed.flatMap(r=>['nvd','euvd'].flatMap(source=>(r[source].refreshFailureReasons||[]).map(reason=>`${source.toUpperCase()}: ${reason}`))))].sort();parts.push(`${counts.refreshFailed} CVE record update(s) failed (${why.join(', ')})`);}
76
+ if(counts.stale)parts.push(`${counts.stale} CVE(s) use cached records with unconfirmed freshness`);
77
+ const affected=new Set([...groups.neither,...(active.euvd?groups.nvdOnly:[]),...(active.nvd?groups.euvdOnly:[]),...groups.refreshFailed,...groups.stale].map(r=>r.id));
78
+ const warning=problem?{type:'cve-enrichment-summary',severity:'warning',affectsCompleteness:false,count:affected.size,consultedCount:records.length,
79
+ counts,records,requestKeys:[...keys],message:`CVE records: ${parts.join('; ')}. Existing findings are retained; this describes enrichment only.`}:null;
80
+ return {warning,records,requestKeys:[...keys],coverage:{capability:'enrichment',collector:'cve-records',affectsCompleteness:false,
81
+ execution:!active.nvd&&!active.euvd?'not-applicable':counts.neither?'partial':'completed',...(!active.nvd&&!active.euvd?{expected:false}:{}),count:records.length,available:records.length-counts.neither,missing:counts.neither}};
82
+ }
83
+ // Report-owned wording only: never translate or reproduce upstream text.
84
+ function formatCveRecordWarning(warning, locale='en') {
85
+ if(!String(locale).toLowerCase().startsWith('fr'))return warning.message || '';
86
+ const records=warning.records || [],counts=warning.counts || {};
87
+ const active=source=>records.some(r=>r[source] && r[source].status!=='disabled');
88
+ const names={ 'rate limit':'limite de débit',offline:'hors ligne',disabled:'désactivé','not consulted':'non consulté','not listed':'non répertorié',timeout:'délai dépassé','access denied':'accès refusé','invalid response':'réponse invalide','request limit':'limite de requêtes','freshness unconfirmed':'actualisation non confirmée','network error':'erreur réseau',unavailable:'indisponible' };
89
+ const label=reason=>names[reason] || (/^HTTP \d{3}$/.test(reason||'')?reason:'indisponible');
90
+ const reasons=(rows,sources)=>{
91
+ const tally=new Map();
92
+ for(const r of rows)for(const source of sources)if(active(source)&&r[source]?.status!=='available'){
93
+ const text=`${source.toUpperCase()} : ${label(r[source]?.reason)}`;tally.set(text,(tally.get(text)||0)+1);
94
+ }
95
+ return [...tally].sort().map(([text,n])=>`${text} ${n}`).join(', ');
96
+ };
97
+ const groups={neither:records.filter(r=>r.nvd?.status!=='available'&&r.euvd?.status!=='available'),nvdOnly:records.filter(r=>r.nvd?.status==='available'&&r.euvd?.status!=='available'),euvdOnly:records.filter(r=>r.euvd?.status==='available'&&r.nvd?.status!=='available')};
98
+ const parts=[];
99
+ if(counts.neither)parts.push(`${counts.neither} fiche(s) CVE obtenue(s) ni auprès de NVD ni auprès d’EUVD (${reasons(groups.neither,['nvd','euvd'])})`);
100
+ if(active('euvd')&&counts.nvdOnly)parts.push(`${counts.nvdOnly} obtenue(s) uniquement auprès de NVD (${reasons(groups.nvdOnly,['euvd'])})`);
101
+ if(active('nvd')&&counts.euvdOnly)parts.push(`${counts.euvdOnly} obtenue(s) uniquement auprès d’EUVD (${reasons(groups.euvdOnly,['nvd'])})`);
102
+ if(counts.refreshFailed){
103
+ const why=[...new Set(records.flatMap(r=>['nvd','euvd'].flatMap(source=>(r[source]?.refreshFailureReasons||[]).map(reason=>`${source.toUpperCase()} : ${label(reason)}`))))].sort();
104
+ parts.push(`${counts.refreshFailed} actualisation(s) de fiche CVE échouée(s) (${why.join(', ')})`);
105
+ }
106
+ if(counts.stale)parts.push(`${counts.stale} CVE utilisent des fiches en cache dont l’actualisation n’est pas confirmée`);
107
+ return `Fiches CVE : ${parts.join(' ; ')}. Les résultats existants sont conservés ; cet avertissement concerne uniquement l’enrichissement.`;
108
+ }
109
+ module.exports={summarizeCveRecords,formatCveRecordWarning,cveIds,recordSources};