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,199 @@
1
+ 'use strict';
2
+ const crypto = require('node:crypto');
3
+ const {renderTime}=require('../report-time');
4
+ const { projectImageCves } = require('./cve-view');
5
+ const esc = value => String(value ?? '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#39;');
6
+ const tr = locale => (en, fr) => locale === 'fr' ? fr : en;
7
+ const artifactAnchor = id => 'image-' + crypto.createHash('sha256').update(String(id)).digest('hex').slice(0, 12);
8
+ const title = a => a?.imageUpdate?.reference || a?.metadata?.reference || a?.metadata?.acquisition?.reference || a?.metadata?.source || a?.id || '';
9
+ const location = r => `${r?.path || ''}${r?.line != null ? ':' + r.line : ''}`;
10
+ const platform = value => typeof value === 'string' ? value : [value?.os, value?.architecture, value?.variant].filter(Boolean).join('/');
11
+ function artifactTitle(artifact, artifacts = []) {
12
+ const label=title(artifact);
13
+ // Always expose content identity, including archive names reused across scans.
14
+ const meta=artifact.metadata||{}, p=platform(meta.platform), digest=meta.digest||meta.acquisition?.resolvedDigest||meta.configDigest||'';
15
+ const short=digest ? String(digest).slice(0,19) : String(artifact.id||'').slice(-12);
16
+ return [p,short].filter(Boolean).join(' · ')+' — '+label;
17
+ }
18
+ const visible = matches => (matches || []).filter(m => !m.suppressed && !m.cpeFiltered);
19
+ const linkedCves = cve => [...new Set([cve?.id,...(cve?.aliases||[]),...(cve?.upstream||[])].filter(id=>typeof id==='string' && /^CVE-\d{4}-\d{4,}$/i.test(id)).map(id=>id.toUpperCase()))];
20
+ // Native sources retain their own public record route; a GCVE is not an OSV advisory.
21
+ const advisoryUrl = id => `https://www.vigievuln.fr/${/^CVE-\d{4}-\d{4,}$/i.test(id)?'cve':/^GCVE-[0-9]+-/i.test(id)?'advisory/gcve':'advisory/osv'}/${encodeURIComponent(id)}`;
22
+ const safeUrl = value => typeof value==='string' && /^https?:\/\/[^\s<>"']+$/i.test(value) ? value : null;
23
+ function artifactGroups(projectInfo = {}, matches = []) {
24
+ const groups = new Map();
25
+ for (const artifact of projectInfo.artifacts || []) if (artifact?.id && !groups.has(artifact.id)) groups.set(artifact.id, {artifact, matches: []});
26
+ for (const match of matches || []) {
27
+ const id = match?.dep?.artifactTargetId || match?.artifactTargetId;
28
+ if (!id) continue;
29
+ if (!groups.has(id)) groups.set(id, {artifact: {id, metadata: {}, coverage: [], components: []}, matches: []});
30
+ groups.get(id).matches.push(match);
31
+ }
32
+ return [...groups.values()];
33
+ }
34
+ function definitionText(artifact, locale) {
35
+ const t=tr(locale),definitions=artifact.metadata?.definitions || [],discovery=artifact.metadata?.definitionDiscovery || {};
36
+ if (definitions.length) return definitions.map(d => `<code>${esc(location(d))}</code>${d.role ? ` (${esc(d.role)})` : ''}${d.declared ? ` — <code>${esc(d.declared)}</code>` : ''}${d.binding==='registry-reference-resolution' ? ` — ${esc(t('registry reference resolved to the scanned digest','référence de registre résolue vers l’empreinte analysée'))}` : ''}`).join('<br>');
37
+ if (discovery.status === 'not-supplied' || !discovery.status) return esc(t('Source definitions not provided.', 'Définitions source non fournies.'));
38
+ if (discovery.status === 'no-match' || discovery.status === 'none' || discovery.status === 'completed') return esc(t('No source definition was matched to this image.', 'Aucune définition source associée à cette image.'));
39
+ return esc(t('Source definition match is unavailable.', 'Association aux définitions source indisponible.'));
40
+ }
41
+ function renderImageSummary(a, locale) {
42
+ const t=tr(locale),meta=a.metadata||{},acq=meta.acquisition||{};
43
+ const cached=a.evidence==='cached-inventory',origin=cached?a.originalEvidence:a.evidence;
44
+ const collectors=(a.coverage||[]).filter(c=>c.capability==='inventory' && ['completed','complete'].includes(c.execution||c.status)).map(c=>c.collector).filter(Boolean);
45
+ const details=[...new Set(collectors)].map(c=>({apk:'APK',dpkg:'dpkg',rpm:'RPM','installed-applications':t('installed application metadata','métadonnées des applications installées'),'native-binaries':t('native binary metadata','métadonnées des binaires natifs')}[c]||c));
46
+ const evidence=origin==='sbom'?t('SBOM inventory; signature not verified','Inventaire issu du SBOM ; signature non vérifiée'):origin==='content-inventory'?t('Inventory extracted from image filesystem','Inventaire extrait du système de fichiers de l’image')+(details.length?` (${details.join(', ')})`:''):t('Inventory origin unavailable','Origine de l’inventaire indisponible');
47
+ const evidenceText=cached?evidence+' — '+(origin==='content-inventory'?t('saved inventory reused without rereading the image','inventaire enregistré réutilisé sans relire l’image'):t('saved inventory reused','inventaire enregistré réutilisé')):evidence;
48
+ const rows=[
49
+ [acq.kind?t('Acquisition','Acquisition'):t('Original format','Format d’origine'),`${esc(acq.kind||meta.format||a.kind||'—')} · <code>${esc(acq.reference||acq.source||meta.reference||meta.source||'—')}</code>`],
50
+ ...(meta.registryReference?.reference && a.imageUpdate?.reference===meta.registryReference.reference ? [[t('Associated registry reference','Référence de registre associée'),`<code>${esc(a.imageUpdate.reference)}</code> — ${t('linked by platform manifest digest','liée par l’empreinte du manifeste de plateforme')}${meta.registryReference.verifiedAt?` · ${renderTime(meta.registryReference.verifiedAt,locale)}`:''}`]] : []),
51
+ [t('Current manifest digest','Empreinte du manifeste actuel'),`<code>${esc(meta.digest||acq.resolvedDigest||meta.resolvedDigest||'—')}</code>`],
52
+ ...(meta.configDigest?[[t('Configuration digest','Empreinte de configuration'),`<code>${esc(meta.configDigest)}</code>`]]:[]),
53
+ [t('Platform','Plateforme'),esc(platform(meta.platform)||'—')],
54
+ [t('Distribution','Distribution'),esc([a.distribution?.id,a.distribution?.versionId].filter(Boolean).join(' ')||'—')],
55
+ [t('Evidence','Preuve'),esc(evidenceText)],
56
+ [t('Inventory date','Date de l’inventaire'),renderTime(a.inventoryAt||'—',locale)],
57
+ ...(a.imageUpdate ? [[t('Image update','Mise à jour de l’image'),require('./remediation-report').renderImageUpdateSummary(a,locale)]] : []),
58
+ [t('Source definitions','Définitions source'),definitionText(a,locale)]
59
+ ];
60
+ return `<table class="image-summary"><tbody>${rows.map(([label,value])=>`<tr><th scope="row">${label}</th><td>${value}</td></tr>`).join('')}</tbody></table>`;
61
+ }
62
+ const {componentIdentity,reportedComponents} = require('./report-inventory');
63
+ function renderAdvisoryObservations(artifact,locale){
64
+ const t=tr(locale),groups=new Map();
65
+ for(const item of artifact.advisoryObservations||[]){
66
+ const id=item.id||item.cveId,name=item.sourceName||item.dep?.sourceName||item.dep?.name,version=item.sourceVersion||item.dep?.sourceVersion||item.dep?.version;
67
+ const key=JSON.stringify([item.source||'',id,name,version,item.status]);
68
+ if(!groups.has(key))groups.set(key,{...item,id,name,version,packages:new Set()});
69
+ const group=groups.get(key);if(item.evidence?.conflictingFinding)group.evidence={...group.evidence,conflictingFinding:true};for(const pkg of item.packages||[item.dep?.name])if(pkg)group.packages.add(pkg);
70
+ }
71
+ if(!groups.size)return '';
72
+ const rows=[...groups.values()].map(item=>{
73
+ const url=safeUrl(item.sourceUrl||item.evidence?.advisoryURL)||(/^CVE-\d{4}-\d{4,}$/.test(item.id||'')?`https://www.vigievuln.fr/cve/${encodeURIComponent(item.id)}`:null);
74
+ const status=item.status==='possible'?t('Possibly affected','Potentiellement affecté'):item.status==='not-affected'?t('Not affected according to source','Non affecté selon la source'):item.status==='fixed'?t('Fixed according to source','Corrigé selon la source'):t('Not established','Non établi');
75
+ const evidence=item.evidence||{},comparison=evidence.comparison;
76
+ const reason=item.source==='freexian-tracker' && evidence.releaseStatus ? t('The tracker release status applies to a different archive source version; applicability to the installed version is undetermined.','Le statut du suivi concerne une autre version source de l’archive ; son applicabilité à la version installée reste indéterminée.') : evidence.versionRange ? t('Upstream version range cannot be evaluated.','La plage de versions amont ne peut pas être évaluée.') : evidence.statuses ? t('No usable tracker package/version verdict.','Le suivi ne fournit pas de verdict exploitable pour ce paquet et cette version.') : evidence.origin ? t('Package vendor provenance does not establish Debian origin.','La provenance du paquet ne permet pas d’établir une origine Debian.') : item.reason==='release status lacks an installed-version bound'?t('No version bound for this release.','Pas de borne de version pour cette distribution.'):item.reason==='package has explicitly different vendor provenance'?t('Package supplied by another vendor.','Paquet fourni par un autre éditeur.'):item.reason==='unrecognized or conflicting release status'?t('Unrecognised or conflicting distribution status.','Statut de distribution non reconnu ou contradictoire.'):item.reason||'';
77
+ const states=(item.states||[]).map(s=>`${s.repo}: ${s.fixed?t('fixed','corrigé'):t('possibly vulnerable','potentiellement vulnérable')}`).join('; ');
78
+ let detail=esc(states||reason||t('The source does not establish the status of this exact version.','La source ne permet pas de conclure pour cette version exacte.'));
79
+ if(comparison && evidence.releaseApplicability==='unknown'){
80
+ const rule=comparison.operator==='<'?`${esc(comparison.installedVersion)} &lt; ${esc(comparison.threshold)}`:t('No fixed version in the current source package rule.','Aucune version corrective dans la règle actuelle du paquet source.');
81
+ const context=(evidence.contextReleases||[]).map(c=>`${esc((c.releases||[]).join(', '))}: ${esc(c.note||'')}`).join('<br>');
82
+ detail=`${t('Current source package rule','Règle actuelle du paquet source')} : <code>${rule}</code><br>${evidence.reconciliation?t('This rule alone does not establish applicability to the unsupported release.','Cette règle seule ne détermine pas l’applicabilité à la distribution hors support.'):t('Applicability to this unsupported distribution is not established.','Applicabilité à cette distribution hors support non établie.')}${context?`<br><small>${t('Other releases marked not affected','Autres distributions déclarées non affectées')} : ${context}</small>`:''}`;
83
+ }
84
+ if(evidence.reconciliation?.assessments?.length){const notes=evidence.reconciliation.assessments.map(a=>{const proof=a.evidence?.releaseEvidence,link=safeUrl(proof?.sourceURL||a.evidence?.sourceURL);const label=esc(a.source||'');const ref=link?`<a href="${esc(link)}">${label}</a>`:label;const row=proof?.row;return row?`${ref} — ${esc(row.release)}: ${esc(row.fixedVersion)}`:ref;}).join(', ');detail+=`<br><small>${t('Release assessment','Évaluation de la distribution')} : ${notes}</small>`;}
85
+ if(evidence.conflictingFinding)detail+=`<br><strong>${t('Another source reports this package as affected; the finding remains visible.','Une autre source signale ce paquet comme affecté ; le résultat reste visible.')}</strong>`;
86
+ return `<tr><td>${url?`<a href="${esc(url)}">${esc(item.id)}</a>`:esc(item.id)}</td><td><code>${esc(item.name)}@${esc(item.version)}</code><br><small>${esc([...item.packages].join(', '))}</small></td><td>${status}</td><td>${detail}${item.observedAt?`<br>${renderTime(item.observedAt,locale)}`:''}</td></tr>`;
87
+ }).join('');
88
+ return `<details class="report-subsection"><summary><h4>${t('Additional advisory evidence','Vérifications complémentaires')} (${groups.size})</h4></summary><p>${t('These source observations are excluded from confirmed finding counts and remediation claims; check their individual evidence and any conflicting findings.','Ces observations des sources sont exclues des compteurs de vulnérabilités et des conclusions de correction ; consultez leurs preuves et les éventuels résultats contradictoires.')}</p><table><thead><tr><th>CVE</th><th>${t('Source package / installed packages','Paquet source / paquets installés')}</th><th>${t('Status','Statut')}</th><th>${t('Evidence','Preuve')}</th></tr></thead><tbody>${rows}</tbody></table></details>`;
89
+ }
90
+ function renderSeverityCounts(severity, locale) {
91
+ const t=tr(locale),labels={critical:t('Critical','Critiques'),high:t('High','Élevées'),medium:t('Medium','Moyennes'),low:t('Low','Faibles'),unknown:t('Unknown','Inconnues')};
92
+ return Object.entries(severity).filter(([,count])=>count>0).map(([band,count])=>`<span class="image-severity ${band}">${labels[band]} <strong>${count}</strong></span>`).join(' ') || '—';
93
+ }
94
+ function renderImageCves(projectInfo = {}, matches = [], locale = 'en', helpers = {}) {
95
+ const t=tr(locale),render=helpers.renderCveTable,minor=helpers.minorSection,groups=artifactGroups(projectInfo,matches),artifacts=groups.map(g=>g.artifact);
96
+ const explanation=`<p>${t('The CVE section shows linked CVE identifiers per image. Distribution advisories without linked CVEs remain in the image inventory section.','La section CVE présente les identifiants CVE liés à chaque image. Les avis de distribution sans CVE liée restent dans la section d’inventaire de l’image.')}</p>`;
97
+ const noFindings=t('No findings recorded; consult scan coverage before drawing conclusions.', 'Aucun résultat enregistré ; consultez la couverture de l’analyse avant de conclure.');
98
+ if(!groups.length)return explanation+`<p>${noFindings} ${t('Reference-only images have not been scanned.','Les images uniquement déclarées n’ont pas été analysées.')}</p>`;
99
+ return explanation+groups.map(({artifact,matches:rows})=>{
100
+ const anchor=artifactAnchor(artifact.id),heading=`${esc(artifactTitle(artifact,artifacts))} (${rows.length})`;
101
+ const detail=rows.length && typeof render==='function' ? render(rows,{image:artifact}) : `<p>${noFindings}</p>`;
102
+ const content=`${renderImageSummary(artifact,locale)}<p class="image-section-nav"><a class="report-section-link" href="#${anchor}">${t('Image inventory and coverage','Inventaire et couverture de l’image')}<span aria-hidden="true">→</span></a></p>${detail}`;
103
+ return typeof minor==='function' ? minor(heading,content,{id:anchor+'-cves'}) : `<details class="report-subsection" open id="${anchor}-cves"><summary><h3>${heading}</h3></summary><div>${content}</div></details>`;
104
+ }).join('');
105
+ }
106
+ function stats(group) {
107
+ const matches=visible(group.matches),components=new Set(),advisories=new Set(),cves=new Set(),severity={critical:0,high:0,medium:0,low:0,unknown:0},updates=new Map();
108
+ for(const m of matches) {
109
+ const dep=m.dep||{},key=dep.coordKey || [dep.ecosystem,dep.namespace,dep.name,dep.version,dep.architecture,dep.manifestPaths?.[0]].join(':');
110
+ components.add(key);advisories.add(m.advisoryId || m.cve?.id || '');
111
+ for(const id of linkedCves(m.cve))cves.add(id);
112
+
113
+ const fix=m.cve?.fixVersion || m.fixVersion;if(fix){const k=`${key}\0${fix}`, item=updates.get(k)||{dep,fix,advisories:new Set()};const advisory=m.advisoryId||m.cve?.id;if(advisory)item.advisories.add(advisory);updates.set(k,item);}
114
+ }
115
+ const cveRows=projectImageCves(matches);
116
+ for(const m of cveRows){const band=String(m.cve?.severity||'unknown').toLowerCase();severity[Object.hasOwn(severity,band)?band:'unknown']++;}
117
+ advisories.delete('');return {cveFindings:cveRows.length,findings:matches.length,components:components.size,advisories:advisories.size,cves:cves.size,severity,updates:[...updates.values()]};
118
+ }
119
+ function renderReferences(projectInfo, artifacts, locale) {
120
+ const t=tr(locale),all=projectInfo.imageReferences?.length ? projectInfo.imageReferences : artifacts.flatMap(a=>a.metadata?.declarations || []),groups=new Map();
121
+ for(const r of all){
122
+ const label=r.reference||r.declared||'',key=JSON.stringify([label,r.platform||null]);
123
+ if(!groups.has(key))groups.set(key,{label,platform:platform(r.platform),refs:[]});groups.get(key).refs.push(r);
124
+ }
125
+ if(!groups.size)return '';
126
+ const rows=[...groups.values()].map(group=>{
127
+ const locations=[...new Set(group.refs.map(location).filter(Boolean))],roles=[...new Set(group.refs.map(r=>r.role).filter(Boolean))],details=[];
128
+ for(const r of group.refs){
129
+ const ids=[...new Set([...(r.boundArtifactIds||[]),...(r.imageScan?.artifactIds||[])])].filter(id=>artifacts.some(a=>a.id===id));
130
+ const status=r.imageScan?.status||r.scanStatus,reason=r.imageScan?.reasonCode||r.blockReason||r.classification;
131
+ let value;
132
+ if(status==='assessment-failed')value=esc(t('Inventory acquired; advisory assessment failed','Inventaire obtenu ; analyse des avis échouée'))+(r.imageScan?.message?`: ${esc(r.imageScan.message)}`:'');
133
+ else if(ids.length){const text=status==='scanned'?t('Scanned image inventory','Inventaire de l’image analysée'):t('Image inventory acquired','Inventaire de l’image obtenu');value=ids.map(id=>`<a href="#${artifactAnchor(id)}">${esc(text)}</a>`).join(', ');}
134
+ else if(status==='failed')value=esc(t('Image acquisition failed','Récupération de l’image échouée'))+(r.imageScan?.message||r.scanReason?`: ${esc(r.imageScan?.message||r.scanReason)}`:'');
135
+ else if(reason==='local-build'||r.localBuild)value=esc(t('Local build; image cannot be acquired from a registry from this declaration.','Construction locale ; cette déclaration ne permet pas de récupérer l’image depuis un registre.'));
136
+ else if(reason==='unresolved'||reason==='unresolved-variables'||r.unresolved?.length)value=esc(t('Unresolved variable','Variable non résolue'))+(r.unresolved?.length?`: ${esc(r.unresolved.join(', '))}`:'');
137
+ else if(status==='not-scannable'||r.scanEligible===false)value=esc(t('Image cannot be scanned from this declaration','Cette déclaration ne permet pas d’analyser l’image'))+(reason?`: ${esc(reason)}`:'');
138
+ else value=esc(t('Image scan status unavailable.','État de l’analyse de l’image indisponible.'));
139
+ if(!details.includes(value))details.push(value);
140
+ }
141
+ return `<tr><td>${locations.length?locations.map(x=>`<code>${esc(x)}</code>`).join('<br>'):'—'}</td><td><code>${esc(group.label)}</code></td><td>${esc(group.platform||'—')}</td><td>${esc(roles.join(', ')||'—')}</td><td>${details.join('<br>')}</td></tr>`;
142
+ }).join('');
143
+ return `<details class="report-subsection" open><summary><h3>${t('Declared image references','Références d’images déclarées')}</h3></summary><table><thead><tr><th>${t('File','Fichier')}</th><th>${t('Declaration','Déclaration')}</th><th>${t('Platform','Plateforme')}</th><th>${t('Role','Rôle')}</th><th>${t('Status','État')}</th></tr></thead><tbody>${rows}</tbody></table></details>`;
144
+ }
145
+ function renderArtifactEvidence(projectInfo = {}, locale = 'en', matches = []) {
146
+ const t=tr(locale),groups=artifactGroups(projectInfo,matches),artifacts=groups.map(g=>g.artifact);
147
+ if(!groups.length && !(projectInfo.imageReferences||[]).length)return '';
148
+ const referenceNotice=projectInfo.provenance?.mode==='offline' && projectInfo.imageReferences?.length ? `<p>${t('Air-gap mode: Dockerfiles remain in the isolated environment and are not transferred; images they define cannot therefore be built during online preparation.','Mode air gap : les Dockerfiles restent dans l’environnement isolé et ne sont pas transférés ; les images qu’ils définissent ne peuvent donc pas être construites pendant la préparation en ligne.')}</p>`:'';
149
+ const overviewRows=groups.map(group=>{const a=group.artifact,s=stats(group),sev=Object.entries(s.severity).filter(([,v])=>v>0).map(([k,v])=>`${esc(k)}: ${v}`).join(' · ');return `<tr><td><a href="#${artifactAnchor(a.id)}">${esc(artifactTitle(a,artifacts))}</a></td><td>${Number(a.componentCount??a.components?.length??0)}</td><td>${s.components}</td><td>${s.findings}</td><td>${s.cveFindings}</td><td>${s.advisories}</td><td>${s.cves}</td><td>${sev}</td><td>${s.updates.length}</td></tr>`;}).join('');
150
+ const overview=overviewRows?`<table><thead><tr><th>${t('Image','Image')}</th><th>${t('Components','Composants')}</th><th>${t('Affected packages','Paquets affectés')}</th><th>${t('Raw findings','Résultats bruts')}</th><th>${t('CVE rows','Lignes CVE')}</th><th>${t('Advisories','Avis')}</th><th>${t('Unique CVEs','CVE distinctes')}</th><th>${t('CVE row severities','Sévérités des lignes CVE')}</th><th>${t('Update candidates','Corrections proposées')}</th></tr></thead><tbody>${overviewRows}</tbody></table>`:'';
151
+ const cards=groups.map(group=>{
152
+ const a=group.artifact,meta=a.metadata||{},acq=meta.acquisition||{},s=stats(group),anchor=artifactAnchor(a.id);
153
+ const definitions=(meta.definitions||[]).filter(d=>d.path && (['manifest-digest','index-digest','registry-reference-resolution'].includes(d.binding) || d.match==='exact-digest'));
154
+ const sourceAction=definitions.length ? t('If applicable, update these verified source declarations:', 'Si nécessaire, mettez à jour ces déclarations source vérifiées :')+' '+definitions.map(d=>`<code>${esc(location(d))}</code>`).join(', ') : t('No matching source declaration is available; identify the build or deployment definition before changing it.', 'Aucune déclaration source associée n’est disponible ; identifiez la définition de build ou de déploiement avant de la modifier.');
155
+ const imageAction=visible(group.matches).length ? `<p><strong>${t('Recommended image action','Action recommandée sur l’image')}:</strong> ${t('For a publisher-provided image, obtain and deploy a corrected image from its publisher. If you build the image, rebuild it from a corrected base and packages, republish it and deploy the replacement.','Pour une image fournie par un éditeur, procurez-vous et déployez une image corrigée auprès de cet éditeur. Si vous construisez l’image, reconstruisez-la à partir d’une base et de paquets corrigés, publiez-la de nouveau et déployez son remplacement.')} ${sourceAction} ${t('Scan the replacement image to verify the fixes and its coverage.','Analysez l’image de remplacement pour vérifier les corrections et la couverture.')} ${['available','current'].includes(a.imageUpdate?.status)?'':t('No replacement tag or digest has been verified from this evidence.','Aucun tag ni empreinte de remplacement n’a été vérifié à partir de ces éléments.')}</p>` : `<p><strong>${t('Recommended image action','Action recommandée sur l’image')}:</strong> ${t('No correction is proposed from the recorded findings; consult scan coverage before deciding the image is safe.','Aucune correction n’est proposée à partir des résultats enregistrés ; consultez la couverture avant de considérer l’image comme sûre.')}</p>`;
156
+ const rows=(a.coverage||[]).map(c=>`<tr><td>${esc(c.capability||'')}</td><td>${esc(c.collector||c.source||'')}</td><td>${esc(c.execution||c.status||'unknown')}</td><td>${esc(c.reason||c.message||c.result||'')}</td></tr>`).join('');
157
+ const updateIndex=new Map();
158
+ for(const update of s.updates){const key=componentIdentity(update.dep),list=updateIndex.get(key)||[];list.push(update);updateIndex.set(key,list);}
159
+ const findingIndex=new Map();
160
+ for(const match of visible(group.matches)){const key=componentIdentity(match.dep||{}),list=findingIndex.get(key)||[];list.push(match);findingIndex.set(key,list);}
161
+ const affectedKeys=new Set(findingIndex.keys());
162
+ const inventory=reportedComponents(a,group.matches),inventoryKeys=new Set(inventory.map(componentIdentity));
163
+ // Older or partial inventories can omit a component that is still supported
164
+ // by a finding. Keep its correction, and identify the source of this row.
165
+ for(const [key,findings] of findingIndex)if(!inventoryKeys.has(key)){inventory.push({...findings[0].dep,_fromFinding:true});inventoryKeys.add(key);}
166
+ inventory.sort((left,right)=>Number(affectedKeys.has(componentIdentity(right)))-Number(affectedKeys.has(componentIdentity(left))));
167
+ const componentRows=items=>items.map(c=>{
168
+ const key=componentIdentity(c),updates=updateIndex.get(key)||[],findings=findingIndex.get(key)||[];
169
+ const fixes=[...new Set(updates.map(u=>u.fix))];
170
+ const advisories=[...new Set(findings.flatMap(m=>[m.advisoryId||m.cve?.id,...linkedCves(m.cve)]).filter(Boolean))];
171
+ const links=advisories.map(id=>/^CVE-\d{4}-\d{4,}$/i.test(id)
172
+ ? `<a href="#${anchor}-cves">${esc(id)}</a>`
173
+ : `<a href="${advisoryUrl(id)}">${esc(id)}</a>`).join(', ');
174
+ return `<tr><td><code>${esc(c.namespace?c.namespace+'/'+c.name:c.name||c.artifactId||c.coord||'')}</code><br>${esc(c.packageType||c.ecosystem||'')}${c._fromFinding?`<br><small>${t('From finding; not present in inventory','Issu d’un résultat ; absent de l’inventaire')}</small>`:''}</td><td>${esc(c.version||'—')}</td><td>${fixes.map(esc).join('<br>')||'—'}</td><td>${links||'—'}</td><td>${esc(c.architecture||'—')}</td><td>${esc(c.artifactPath||'—')}</td><td>${esc((c.osPackageOwners||[]).map(o=>`${o.name}@${o.version}`).join(', ')||'—')}</td></tr>`;
175
+ }).join('');
176
+ const table=items=>items.length?`<table class="image-inventory"><thead><tr><th>${t('Component','Composant')}</th><th>${t('Installed','Installé')}</th><th>${t('Candidate corrections','Corrections proposées')}</th><th>${t('Advisories','Avis')}</th><th>Arch</th><th>${t('Location','Emplacement')}</th><th>${t('OS package owner','Paquet système propriétaire')}</th></tr></thead><tbody>${componentRows(items)}</tbody></table>`:`<p>${t('No components observed.','Aucun composant observé.')}</p>`;
177
+ const direct=inventory.filter(c=>c.imageRole==='direct'),subdeps=inventory.filter(c=>c.imageRole==='transitive'),unclassified=inventory.filter(c=>!['direct','transitive'].includes(c.imageRole));
178
+ const componentSections=`<h5>${t('Direct image components','Composants directs de l’image')} (${direct.length})</h5>${table(direct)}`+
179
+ `<h5>${t('Image sub-dependencies','Sous-dépendances de l’image')} (${subdeps.length})</h5>${table(subdeps)}`+
180
+ (unclassified.length?`<h5>${t('Unclassified image components','Composants de l’image non classés')} (${unclassified.length})</h5>${table(unclassified)}`:'');
181
+ const totals=[[t('Components','Composants'),Number(a.componentCount ?? a.components?.length ?? 0)],[t('Affected packages','Paquets affectés'),s.components],[t('Advisories','Avis'),s.advisories],[t('Unique CVEs','CVE distinctes'),s.cves]];
182
+ const totalsTable=`<table class="image-totals"><thead><tr>${totals.map(([label])=>`<th scope="col">${label}</th>`).join('')}</tr></thead><tbody><tr>${totals.map(([,value])=>`<td class="image-total-value">${value}</td>`).join('')}</tr><tr><td colspan="4"><span class="image-severity-label">${t('CVE row severities','Sévérités des lignes CVE')}</span>${renderSeverityCounts(s.severity,locale)}</td></tr></tbody>${group.matches.length?`<tfoot><tr><td colspan="4"><a class="report-section-link" href="#${anchor}-cves">${t('View vulnerability details','Voir les vulnérabilités')}<span aria-hidden="true">→</span></a></td></tr></tfoot>`:''}</table>`;
183
+ const noCve=visible(group.matches).filter(m=>m.dep?.ecosystem==='system' && !linkedCves(m.cve).length);
184
+ const noCveRows=noCve.map(m=>{
185
+ const dep=m.dep||{},c=m.cve||{},id=m.advisoryId||c.id||'—',url=safeUrl(c.advisorySource)||safeUrl(c.gcveSource)||safeUrl((c.osvRefs||[]).find(r=>safeUrl(r?.url))?.url);
186
+ const name=dep.namespace?`${dep.namespace}/${dep.name||dep.artifactId||''}`:dep.name||dep.artifactId||'—';
187
+ return `<tr><td><a href="${advisoryUrl(id)}"><code>${esc(id)}</code></a>${url?`<br><a href="${esc(url)}">${t("Original source","Source originale")}</a>`:""}</td><td>${esc(c.summary||c.description||'—')}</td><td>${renderTime(c.published||'—',locale)}</td><td><code>${esc(name)}</code> ${esc(dep.version||'')}</td><td>${esc(c.fixVersion||m.fixVersion||'—')}</td></tr>`;
188
+ }).join('');
189
+ const nonCveAdvisories=noCveRows?`<details open><summary>${t('Distribution advisories without linked CVEs','Avis de distribution sans CVE liée')} (${noCve.length})</summary><p>${t('No linked CVE or CVE severity is supplied for these advisory records. They may include security or maintenance updates.','Aucune CVE liée ni sévérité CVE n’est fournie pour ces avis. Ils peuvent concerner la sécurité ou la maintenance.')}</p><table><thead><tr><th>${t('Advisory','Avis')}</th><th>${t('Summary','Résumé')}</th><th>${t('Published','Publié')}</th><th>${t('Package','Paquet')}</th><th>${t('Candidate','Version proposée')}</th></tr></thead><tbody>${noCveRows}</tbody></table></details>`:'';
190
+ return `<details class="report-subsection" open id="${anchor}"><summary><h3>${esc(artifactTitle(a,artifacts))}</h3></summary><div>`+
191
+ renderImageSummary(a,locale)+
192
+ totalsTable+
193
+ imageAction+
194
+ (rows?`<details open><summary>${t('Coverage checks','Contrôles de couverture')}</summary><table><thead><tr><th>${t('Capability','Capacité')}</th><th>${t('Source','Source')}</th><th>${t('Execution','Exécution')}</th><th>${t('Result / limitation','Résultat / limite')}</th></tr></thead><tbody>${rows}</tbody></table></details>`:`<p>${t('Coverage information unavailable.','Informations de couverture indisponibles.')}</p>`)+
195
+ renderAdvisoryObservations(a,locale)+nonCveAdvisories+`<details class="report-subsection"><summary><h4>${t('Component inventory and candidate corrections','Inventaire des composants et corrections proposées')} (${inventory.length})</h4></summary><p>${t('Libraries are listed with or without findings; system packages and native binaries are detailed when associated with an advisory. Roles describe the image inventory, not project dependency scope.','Les bibliothèques sont listées avec ou sans résultat ; les paquets système et binaires natifs sont détaillés lorsqu’un avis leur est associé. Les rôles décrivent l’inventaire de l’image et non la portée des dépendances du projet.')}</p><p>${t('Candidate versions come from individual advisories. Verify them in the replacement image; they do not establish that a particular image tag or digest is corrected.','Les versions proposées proviennent d’avis individuels. Vérifiez-les dans l’image de remplacement ; elles ne prouvent pas qu’un tag ou une empreinte d’image est corrigé.')}</p>${componentSections}</details></div></details>`;
196
+ }).join('');
197
+ return referenceNotice+overview+(groups.length?`<p>${t('A raw finding is an advisory affecting a component. An advisory can link several CVEs; the CVE section groups linked CVE identifiers while advisories without linked CVEs remain below.','Un résultat brut correspond à un avis affectant un composant. Un avis peut être lié à plusieurs CVE ; la section CVE regroupe les identifiants liés et les avis sans CVE liée restent ci-dessous.')}</p>`:'')+cards+renderReferences(projectInfo,artifacts,locale);
198
+ }
199
+ module.exports={artifactAnchor,artifactTitle,artifactGroups,renderImageCves,renderArtifactEvidence};
@@ -0,0 +1,120 @@
1
+ 'use strict';
2
+ // NVD context concerns the identified CVE, not the distribution's own
3
+ // affected-version decision. All values are untrusted report evidence.
4
+ const esc=value=>String(value ?? '').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;').replace(/'/g,'&#39;');
5
+ const {renderTime}=require('../report-time');
6
+ const CVE=/^CVE-\d{4}-\d{4,}$/i;
7
+ const words={
8
+ en:{linked:'Linked CVEs',identity:'Same vulnerability',upstream:'Upstream CVE',unspecified:'Unspecified',associated:'associated CVE',
9
+ distribution:'Distribution advisories',candidate:'Advisory-specific candidate',original:'Original source',evidence:'Linked CVE evidence',explanation:'CVE metrics provide context; the original advisory remains the source of the affected-version verdict.',
10
+ cve:'CVE',relationship:'Relationship',severity:'Severity',score:'CVSS',vector:'Vector',cwe:'CWE',published:'Published',modified:'Modified',description:'Description',references:'References',unknown:'Not available'},
11
+ fr:{linked:'CVE liées',identity:'Même vulnérabilité',upstream:'CVE en amont',unspecified:'Non précisée',associated:'CVE associée',
12
+ distribution:'Avis de distribution',candidate:'Version candidate propre à cet avis',original:'Source originale',evidence:'Données des CVE liées',explanation:'Les métriques des CVE apportent du contexte ; l’avis d’origine reste la source du verdict sur les versions affectées.',
13
+ cve:'CVE',relationship:'Relation',severity:'Sévérité',score:'CVSS',vector:'Vecteur',cwe:'CWE',published:'Publication',modified:'Modification',description:'Description',references:'Références',unknown:'Non disponible'},
14
+ };
15
+ function dict(locale){return String(locale||'en').toLowerCase().startsWith('fr')?words.fr:words.en;}
16
+ function cveLink(id){if(!CVE.test(String(id||'')))return '';const name=String(id).toUpperCase();return `<a href="https://www.vigievuln.fr/cve/${esc(name)}" target="_blank" rel="noopener noreferrer">${esc(name)}</a>`;}
17
+ function safeLink(value){try{const url=new URL(typeof value==='string'?value:value?.url);if(!['http:','https:'].includes(url.protocol)||url.username||url.password)return '';const href=url.href;return `<a href="${esc(href)}" target="_blank" rel="noopener noreferrer">${esc(href)}</a>`;}catch{return '';}}
18
+ function number(value){return typeof value==='number' && Number.isFinite(value) && value>=0 && value<=10 ? String(value) : '';}
19
+ function records(cve){return Array.isArray(cve?.nvdEvidence?.records)?cve.nvdEvidence.records.filter(r=>r && CVE.test(String(r.id||''))):[];}
20
+ function renderLinkedCves(cve,locale){
21
+ const t=dict(locale),own=String(cve?.id||'').toUpperCase(),items=new Map();
22
+ for(const id of cve?.upstream||[])if(CVE.test(String(id))&&String(id).toUpperCase()!==own)items.set(String(id).toUpperCase(),null);
23
+ for(const record of records(cve)){const id=String(record.id).toUpperCase();if(id!==own)items.set(id,record);}
24
+ if(!items.size)return '';
25
+ return `<div class="linked-cves"><span>${esc(t.linked)}:</span> ${[...items].map(([id,record])=>{
26
+ const severity=typeof record?.severity==='string' && record.severity.toUpperCase()!=='UNKNOWN'?record.severity:null,score=number(record?.score);
27
+ return cveLink(id)+(severity||score?` <small>(${esc([severity,score].filter(Boolean).join(' · '))})</small>`:'');
28
+ }).join(', ')}</div>`;
29
+ }
30
+ function renderRiskAttribution(cve,locale){
31
+ const t=dict(locale),risk=cve?.riskEvidence;if(!risk || !['nvd','euvd'].includes(risk.source) || !['identity','upstream'].includes(risk.relationship) || !CVE.test(String(risk.id||'')))return '';
32
+ const kind=risk.relationship==='upstream'?t.associated:t.identity;
33
+ return `<span class="risk-attribution">${risk.source==='euvd'?'ENISA EUVD':'NVD'} · ${cveLink(risk.id)} (${esc(kind)})</span>`;
34
+ }
35
+ function renderRiskEvidence(cve,locale,options={}){
36
+ const t=dict(locale),items=records(cve);if(!items.length)return '';
37
+ const value=v=>v===null||v===undefined||v===''?esc(t.unknown):esc(v);
38
+ const field=(label,content)=>`<div><label>${esc(label)}</label><span>${content}</span></div>`;
39
+ const body=items.map(record=>{
40
+ const relationship=record.relationship==='upstream'?t.upstream:record.relationship==='identity'?t.identity:t.unspecified;
41
+ const sev=record.severity && String(record.severity).toUpperCase()!=='UNKNOWN'?record.severity:null;
42
+ const score=number(record.score),vector=[record.cvssVersion,record.cvssVector].filter(Boolean).join(' · ');
43
+ const cwes=Array.isArray(record.cwes)?record.cwes.filter(x=>typeof x==='string').join(', '):'';
44
+ const refs=Array.isArray(record.references)?record.references.map(safeLink).filter(Boolean):[];
45
+ const id=String(record.id).toUpperCase(),nvd=`<a href="https://nvd.nist.gov/vuln/detail/${esc(id)}" target="_blank" rel="noopener noreferrer">NVD</a>`;
46
+ const own=options.omitRepeated && id===String(cve.id||'').toUpperCase();
47
+ const equal=(a,b)=>JSON.stringify(a)===JSON.stringify(b);
48
+ const sameSet=(a,b)=>Array.isArray(a)&&Array.isArray(b)&&equal([...new Set(a)].sort(),[...new Set(b)].sort());
49
+ const shown=[];
50
+ if(!own || (sev && sev!==cve.severity))shown.push(field(t.severity,value(sev)));
51
+ if(!own || (record.score!=null && record.score!==cve.score))shown.push(field(t.score,value(score)));
52
+ if(!own || (record.cvssVector && (record.cvssVector!==cve.cvssVector || record.cvssVersion!==cve.cvssVersion)))shown.push(field(t.vector,value(vector)));
53
+ if(!own || (record.cwes?.length && !sameSet(record.cwes,cve.cwes)))shown.push(field(t.cwe,value(cwes)));
54
+ for(const key of ['published','modified'])if(!own || (record[key] && record[key]!==cve[key]))shown.push(field(t[key],record[key]?renderTime(record[key],locale):esc(t.unknown)));
55
+ const mainRefs=new Set([...(cve.nvdRefs||[]),...(cve.osvRefs||[])].map(safeLink));
56
+ const uniqueRefs=[...new Set(refs)].filter(ref=>!own || !mainRefs.has(ref));
57
+ const references=uniqueRefs.length?`<div class="panel-title">${esc(t.references)}</div><ul class="ref-list">${uniqueRefs.map(ref=>`<li>${ref}</li>`).join('')}</ul>`:'';
58
+ if(own && !shown.length && !references)return '';
59
+ shown.push(field('Source',nvd));
60
+ return `<div class="panel-block"><h4>${cveLink(id)}${own?'':` · ${esc(relationship)}`}</h4><div class="kv">${shown.join('')}</div>${references}</div>`;
61
+ }).join('');
62
+ if(!body)return '';
63
+ return `<section class="linked-cve-evidence"><h4>${esc(t.evidence)}</h4><p>${esc(t.explanation)}</p>${body}</section>`;
64
+ }
65
+ function renderEuvdEvidence(cve,locale,options={}){
66
+ const t=dict(locale),detail=require('../euvd').normalizeEuvdDetailDates(cve?.euvdDetails);
67
+ if(!detail || !/^EUVD-\d{4}-\d{1,12}$/.test(String(detail.id||'')))return '';
68
+ const field=(label,content)=>`<div><label>${esc(label)}</label><span>${content}</span></div>`;
69
+ const source=`<a href="https://euvd.enisa.europa.eu/vulnerability/${esc(detail.id)}" target="_blank" rel="noopener noreferrer">${esc(detail.id)}</a>`;
70
+ const omit=!!options.omitRepeated,shown=[];
71
+ if(detail.severity && (!omit || detail.severity!==cve.severity))shown.push(field(t.severity,esc(detail.severity)));
72
+ if(detail.score!=null && (!omit || detail.score!==cve.score))shown.push(field(t.score,esc(number(detail.score)||t.unknown)));
73
+ if(detail.cvssVector && (!omit || detail.cvssVector!==cve.cvssVector || detail.cvssVersion!==cve.cvssVersion))shown.push(field(t.vector,esc([detail.cvssVersion,detail.cvssVector].filter(Boolean).join(' '))));
74
+ for(const key of ['published','modified'])if(detail[key] && (!omit || detail[key]!==cve[key]))shown.push(field(t[key],renderTime(detail[key],locale)));
75
+ const mainRefs=new Set([...(cve.nvdRefs||[]),...(cve.osvRefs||[])].map(safeLink));
76
+ const refs=Array.isArray(detail.references)?[...new Set(detail.references.map(safeLink).filter(Boolean))].filter(ref=>!omit || !mainRefs.has(ref)):[];
77
+ return `<section class="linked-cve-evidence panel-block"><h4>ENISA EUVD · ${source}</h4><p>${esc(t.explanation)}</p>${shown.length?`<div class="kv">${shown.join('')}</div>`:''}${refs.length?`<div class="panel-title">${esc(t.references)}</div><ul class="ref-list">${refs.map(ref=>`<li>${ref}</li>`).join('')}</ul>`:''}</section>`;
78
+ }
79
+
80
+ function renderDistributionAdvisories(cve,locale){
81
+ const t=dict(locale),advisories=Array.isArray(cve?.distributionAdvisories)?cve.distributionAdvisories:[];
82
+ if(!advisories.length)return '';
83
+ const body=advisories.map(item=>{
84
+ const id=String(item?.id||'');if(!id)return '';
85
+ const link=/^[A-Za-z0-9._:+-]{1,256}$/.test(id)?`<a href="https://www.vigievuln.fr/advisory/osv/${encodeURIComponent(id)}" target="_blank" rel="noopener noreferrer">${esc(id)}</a>`:esc(id);
86
+ const origin=safeLink(item.sourceURL),relationship=item.relationship==='upstream'?t.upstream:item.relationship==='identity'?t.identity:t.unspecified;
87
+ return `<div class="panel-block"><h4>${link}</h4><div class="kv"><div><label>${esc(t.relationship)}</label><span>${esc(relationship)}</span></div><div><label>${esc(t.candidate)}</label><span>${esc(item.fixVersion || t.unknown)}</span></div></div>${origin?`<div>${esc(t.original)}: ${origin}</div>`:''}</div>`;
88
+ }).join('');
89
+ return body?`<section class="distribution-advisories"><h4>${esc(t.distribution)}</h4>${body}</section>`:'';
90
+ }
91
+
92
+ function renderHistoricalEvidence(cve,locale){
93
+ const proofs=require('../applicability-evidence').applicabilityEvidence(cve).filter(p=>p.kind==='historical');
94
+ return proofs.map(({evidence:e})=>{
95
+ const fr=String(locale).startsWith('fr'),d=e.distribution||{},commit=String(e.commit||'');
96
+ const field=(label,value)=>`<div><label>${esc(label)}</label><span>${value}</span></div>`;
97
+ const fields=[field('Distribution',esc([d.id,d.versionId,d.codename].filter(Boolean).join(' · ')))];
98
+ if(e.scope==='release-specific-ela'){
99
+ fields.push(field(fr?'Avis':'Advisory',safeLink(e.sourceURL)),field(fr?'Publication':'Published',renderTime(e.publishedAt,locale)),field(fr?'Version corrective':'Fixed version',esc(e.fixVersion||'—')));
100
+ return `<section class="panel-block"><h4>${esc(e.advisoryId||'ELA')} · Freexian</h4><div class="kv">${fields.join('')}</div><p>${fr?'Comparaison au seuil correctif publié pour le paquet source de cette distribution ; aucune borne d’introduction n’est déclarée. Le correctif est publié dans le dépôt Extended LTS : vérifiez sa disponibilité pour l’image ou migrez vers une distribution maintenue.':'Comparison with the published fixed threshold for this release’s source package; no introduction bound is declared. The fix is published in the Extended LTS repository: check its availability for the image or migrate to a supported distribution.'}</p></section>`;
101
+ }
102
+ const source=/^[a-f0-9]{40}$/.test(commit)?`<a href="https://salsa.debian.org/security-tracker-team/security-tracker/-/tree/${commit}">${esc(commit.slice(0,12))}</a>`:esc(commit||'—');
103
+ fields.push(field(fr?'Date limite des données':'Evidence cutoff',renderTime(e.cutoff,locale)),field(fr?'Révision de la source':'Source revision',source));
104
+ const inherited=e.scope==='inherited-source-note';
105
+ if(e.comparisonThreshold)fields.push(field(fr?'Seuil de comparaison':'Comparison threshold',esc(e.comparisonThreshold)));
106
+ if(e.trackerUrgency)fields.push(field(fr?'Urgence selon Debian':'Debian urgency',esc(e.trackerUrgency)));
107
+ const annotations=(e.annotations||[]).map(x=>[x.kind,x.note].filter(Boolean).join(' — '));
108
+ if(annotations.length)fields.push(field(fr?'Décision de maintenance':'Maintenance decision',esc(annotations.join('; '))));
109
+ const explanation=inherited?(fr?'La règle générale du paquet source est appliquée selon la priorité des règles du tracker Debian. Son seuil de comparaison ne constitue pas une proposition de mise à jour pour cette release.':'The source package’s general rule is applied with Debian tracker precedence. Its comparison threshold is not an update recommendation for this release.'):(fr?'La version source inventoriée est évaluée avec la règle propre à cette distribution.':'The inventoried source version is evaluated against the rule specific to this distribution.');
110
+ return `<section class="panel-block"><h4>${fr?'Preuve de portée historique':'Historical applicability evidence'}</h4><div class="kv">${fields.join('')}</div><p>${explanation} ${fr?'Ce snapshot historique ne couvre pas les vulnérabilités publiées après sa date limite.':'This historical snapshot does not cover vulnerabilities published after its cutoff.'}</p>${e.originStatus==='distribution-context'?`<p class="muted">${fr?'Origine déduite du contexte de distribution et de l’identité déclarée par le paquet ; contenu du paquet non authentifié.':'Origin follows the distribution context and declared package identity; package contents are not authenticated.'}</p>`:''}</section>`;
111
+ }).join('');
112
+ }
113
+ function renderVendorEvidence(cve,locale){
114
+ return require('../applicability-evidence').applicabilityEvidence(cve).filter(p=>p.kind==='vendor').map(({evidence:e})=>{
115
+ const fr=String(locale).startsWith('fr');
116
+ const fields=[[fr?'Version amont':'Upstream version',esc(e.upstreamVersion||'—')],[fr?'Versions affectées':'Affected versions',esc(e.versionRange||'—')],[fr?'Origine déclarée':'Declared origin',esc(e.packageOrigin?.declared||'—')],['Source',safeLink(e.advisoryURL||e.sourceURL)],[fr?'Consultation':'Consulted',renderTime(e.observedAt,locale)]];
117
+ return `<section class="panel-block"><h4>${fr?'Avis du fournisseur':'Vendor advisory'}</h4><div class="kv">${fields.map(([label,value])=>`<div><label>${label}</label><span>${value}</span></div>`).join('')}</div><p class="muted">${fr?'Correspondance de version fondée sur l’origine déclarée du paquet. L’applicabilité à la configuration effective et la signature du paquet ne sont pas vérifiées.':'Version match based on the declared package origin. Applicability to the runtime configuration and package signature are not verified.'}</p></section>`;
118
+ }).join('');
119
+ }
120
+ module.exports={renderLinkedCves,renderRiskEvidence,renderRiskAttribution,renderEuvdEvidence,renderDistributionAdvisories,renderHistoricalEvidence,renderVendorEvidence};
@@ -0,0 +1,68 @@
1
+ 'use strict';
2
+ // Import publisher inventories as unverified evidence; no signature tools invoked.
3
+ const fs=require('node:fs');
4
+ const {makeDepRecord}=require('../dep-record');
5
+ const MAX_BYTES=32*1024*1024, MAX_PACKAGES=250000;
6
+ const adapters=new Map([
7
+ ['maven',p=>({ecosystem:'maven',namespace:p.namespace,name:p.name})],
8
+ ['composer',p=>({ecosystem:'composer',namespace:p.namespace,name:p.name})],
9
+ ...[['npm','npm'],['pypi','pypi'],['nuget','nuget'],['golang','go'],['gem','ruby']].map(([type,ecosystem])=>[type,p=>({ecosystem,name:p.namespace?`${p.namespace}/${p.name}`:p.name})]),
10
+ ...['deb','rpm','apk'].map(type=>[type,p=>({system:true,type,name:p.name,namespace:p.namespace})]),
11
+ ]);
12
+ function parsePurl(value) {
13
+ if(typeof value!=='string'||!value.startsWith('pkg:'))return null;
14
+ try {let s=value.slice(4).split('#',1)[0];const q=s.indexOf('?'),query=q<0?'':s.slice(q+1);if(q>=0)s=s.slice(0,q);const slash=s.indexOf('/');if(slash<1)return null;const type=s.slice(0,slash).toLowerCase();s=s.slice(slash+1);const at=s.lastIndexOf('@');const version=at>=0?decodeURIComponent(s.slice(at+1)):null;if(at>=0)s=s.slice(0,at);const parts=s.split('/').map(decodeURIComponent);const name=parts.pop();if(!name)return null;const qualifiers={};for(const [k,v] of new URLSearchParams(query))qualifiers[k.toLowerCase()]=v;return {type,namespace:parts.join('/'),name,version,qualifiers};}catch{return null}
15
+ }
16
+ // Evidence adapters accept only explicit publisher distribution declarations.
17
+ const distributionAdapters = [
18
+ {id:'purl-distro', extract({purl}) {const value=purl?.qualifiers?.distro;if(!value)return null;const m=/^([a-z][a-z0-9._-]*)-([0-9][a-z0-9._+-]*)$/i.exec(value);return m?{id:m[1].toLowerCase(),versionId:m[2],evidence:{type:'purl-distro',value}}:null;}},
19
+ {id:'purl-os-qualifiers', extract({purl}) {const id=purl?.qualifiers?.os_name, versionId=purl?.qualifiers?.os_version;if(!id||!versionId)return null;return {id:id.toLowerCase(),versionId,evidence:{type:'purl-os-qualifiers',osName:id,osVersion:versionId}};}},
20
+ {id:'cyclonedx-os', extract({component,format}) {if(format!=='cyclonedx' || component?.type!=='operating-system' || typeof component.name!=='string' || typeof component.version!=='string')return null;const id=component.name.toLowerCase(), versionId=component.version;if(!/^[a-z][a-z0-9._-]*$/.test(id)||!/^[0-9][a-z0-9._+-]*$/i.test(versionId))return null;return {id,versionId,evidence:{type:'cyclonedx-operating-system',name:component.name,version:versionId}};}},
21
+ ];
22
+ function readSbom(input,opts={}) {
23
+ const max=opts.maxBytes??MAX_BYTES,warnings=[],deps=new Map(),systemPackages=[];let doc=input;
24
+ const activeAdapters=opts.purlAdapters || adapters;
25
+ const scopes=opts.distributionAdapters || distributionAdapters;if(!Array.isArray(scopes) || scopes.some(a=>!a || typeof a.id!=='string' || typeof a.extract!=='function'))throw Error('Invalid SBOM distribution adapter registry');if(!(activeAdapters instanceof Map) || [...activeAdapters].some(([key,fn])=>typeof key!=='string'||typeof fn!=='function'))throw Error('Invalid SBOM adapter registry');
26
+ const warn=(reason,message)=>warnings.push({type:'dependency-coverage',reason,message});
27
+ if(typeof input==='string'){const st=fs.statSync(input);if(st.size>max)throw Error('SBOM exceeds size limit');doc=JSON.parse(fs.readFileSync(input,'utf8'));}
28
+ if(!doc || typeof doc!=='object' || Array.isArray(doc))throw Error('Invalid SBOM document');
29
+ if(Buffer.byteLength(JSON.stringify(doc))>max)throw Error('SBOM exceeds size limit');
30
+ let subjectDigests=[], platform=null, wrapper=false;
31
+ if(typeof doc.payload==='string' && Array.isArray(doc.signatures)) {if(doc.payload.length>Math.ceil(max*4/3)+8 || !/^[A-Za-z0-9+/]*={0,2}$/.test(doc.payload))throw Error('Invalid or oversized DSSE payload');const b=Buffer.from(doc.payload,'base64');if(b.length>max)throw Error('DSSE payload exceeds limit');doc=JSON.parse(b.toString('utf8'));wrapper=true;}
32
+ if(Array.isArray(doc.subject) && doc.predicate && typeof doc.predicate==='object') {wrapper=true;for(const subject of doc.subject)for(const [alg,value] of Object.entries(subject.digest||{}))if(typeof value==='string')subjectDigests.push(`${alg.toLowerCase()}:${value.toLowerCase()}`);doc=doc.predicate;}
33
+ const expected=opts.expectedDigest?.toLowerCase();
34
+ let externalBinding=null;
35
+ if(opts.boundSubjectDigest!==undefined || opts.boundSubjectEvidence!==undefined) {
36
+ const digest=String(opts.boundSubjectDigest||'').toLowerCase(), evidence=opts.boundSubjectEvidence;
37
+ if(!/^sha256:[0-9a-f]{64}$/.test(digest) || !evidence || evidence.type!=='oci-manifest-subject' || typeof evidence.manifestDigest!=='string' || !/^sha256:[0-9a-f]{64}$/i.test(evidence.manifestDigest))throw Error('Invalid external SBOM subject binding');
38
+ if(subjectDigests.length && !subjectDigests.includes(digest))throw Error('SBOM subject conflicts with OCI manifest subject');
39
+ externalBinding={digest,...evidence};if(!subjectDigests.includes(digest))subjectDigests.push(digest);
40
+ }
41
+ if(expected && subjectDigests.length && !subjectDigests.includes(expected))throw Error('SBOM subject digest does not match expected artifact');
42
+ if(!subjectDigests.length)warn('sbom-unattached','SBOM has no artifact subject digest; its association with this artifact is unverified.');
43
+ warn('sbom-unverified','SBOM publisher identity and signatures were not verified.');
44
+ let format,packages,root=null;
45
+ if(typeof doc.spdxVersion==='string'&&doc.spdxVersion.startsWith('SPDX-2.')){format='spdx2';packages=doc.packages||[];const described=(doc.relationships||[]).filter(r=>r.relationshipType==='DESCRIBES' && (!doc.SPDXID || r.spdxElementId===doc.SPDXID)).map(r=>r.relatedSpdxElement);root=packages.find(p=>described.includes(p.SPDXID))||null;}
46
+ else if(doc.bomFormat==='CycloneDX'){format='cyclonedx';packages=doc.components||[];root=doc.metadata?.component||null;}
47
+ else throw Error('Unsupported SBOM format');
48
+ if(!Array.isArray(packages)||packages.length> (opts.maxPackages??MAX_PACKAGES))throw Error('Invalid or oversized SBOM package list');
49
+ const source=typeof input==='string'?input:(opts.source||'(SBOM)');
50
+ function purls(p){if(format==='cyclonedx')return p.purl?[p.purl]:[];return (p.externalRefs||[]).filter(x=>String(x.referenceType||'').toLowerCase().endsWith('purl')).map(x=>x.referenceLocator);}
51
+ const rootComponent=root?{name:root.name||null,version:root.versionInfo||root.version||null,purl:purls(root)[0]||null}:null;
52
+ const rootPurl=parsePurl(rootComponent?.purl);if(rootPurl?.qualifiers?.arch)platform={architecture:rootPurl.qualifiers.arch};
53
+ const candidates=[];
54
+ function collectScope(component,purl){for(const adapter of scopes){const value=adapter.extract({component,purl,format});if(!value)continue;if(typeof value.id!=='string' || !/^[a-z][a-z0-9._-]*$/.test(value.id) || typeof value.versionId!=='string' || !/^[0-9][a-z0-9._+-]*$/i.test(value.versionId))throw Error('Invalid SBOM distribution evidence');candidates.push(value);}}
55
+ if(root)collectScope(root,rootPurl);
56
+ for(const [i,p] of packages.entries()) {const ps=purls(p), parsed=ps.map(parsePurl).find(Boolean);collectScope(p,parsed);if(!parsed && p===root)continue;if(!parsed){warn('sbom-package-unidentified',`SBOM package ${i+1} has no supported package URL.`);continue;}const adapter=activeAdapters.get(parsed.type);if(!adapter){warn('sbom-package-unsupported',`SBOM package URL type ${parsed.type} is unsupported.`);continue;}const item=adapter(parsed),version=parsed.version;if(!item || typeof item.name!=='string' || !item.name || (!item.system && typeof item.ecosystem!=='string')){warn('sbom-adapter-invalid',`SBOM adapter ${parsed.type} did not provide a valid identity.`);continue;}if(!version){warn('sbom-version-unknown',`SBOM package ${parsed.name} has no version in its package URL.`);continue;}
57
+ const evidence={source,purl:ps.find(x=>parsePurl(x)?.type===parsed.type),qualifiers:parsed.qualifiers,verification:'unverified'};
58
+ if(item.system){systemPackages.push({name:item.name,version,architecture:parsed.qualifiers.arch || null,sourceName:null,sourceVersion:null,manager:item.type,manifestPath:source,ecosystem:'system',provenance:'sbom',distribution:null,qualifiers:parsed.qualifiers,evidence});continue;}
59
+ const dep=makeDepRecord({...item,version,manifestPath:source,provenance:'sbom',scope:'transitive'});dep.coordKey=`sbom:${source}:${i}:${parsed.type}:${parsed.namespace}/${parsed.name}@${version}`;dep.sbomEvidence=evidence;deps.set(dep.coordKey,dep);
60
+ }
61
+ const unique=new Map(candidates.map(c=>[`${c.id}\0${c.versionId}`,c]));let distribution=null;
62
+ if(unique.size===1)distribution=[...unique.values()][0];else if(unique.size>1)warn('sbom-distribution-conflict','SBOM declares conflicting distribution identities; no common advisory scope can be selected.');else if(systemPackages.length)warn('sbom-distribution-unknown','SBOM system packages have no explicit distribution identity; advisory scope is unknown.');
63
+ const missingSource=systemPackages.filter(pkg=>!pkg.sourceName || !pkg.sourceVersion).length;
64
+ if(missingSource)warn('sbom-system-source-unknown',`${missingSource} system packages lack source package name or version; distro advisory assessment may be incomplete.`);
65
+ for(const pkg of systemPackages)pkg.distribution=distribution;
66
+ return {deps,systemPackages,distribution,metadata:{format,subjectDigests,externalBinding,platform,rootComponent,verification:'unverified',wrapper,coverage:{packages:packages.length,dependencies:deps.size,systemPackages:systemPackages.length,warnings:warnings.length}},warnings};
67
+ }
68
+ module.exports={readSbom,parsePurl,adapters,distributionAdapters,MAX_BYTES,MAX_PACKAGES};