vigievuln 1.2.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (121) hide show
  1. package/CHANGELOG.md +23 -2
  2. package/README.md +13 -7
  3. package/lib/advisory-freshness.js +2 -0
  4. package/lib/airgap-project.js +35 -7
  5. package/lib/applicability-evidence.js +12 -0
  6. package/lib/artifacts/applications.js +54 -0
  7. package/lib/artifacts/cve-view.js +108 -0
  8. package/lib/artifacts/enrichment.js +86 -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/publisher-advisories.js +12 -0
  13. package/lib/artifacts/remediation-report.js +48 -0
  14. package/lib/artifacts/report-inventory.js +26 -0
  15. package/lib/artifacts/report.js +191 -0
  16. package/lib/artifacts/risk-report.js +120 -0
  17. package/lib/artifacts/sbom.js +68 -0
  18. package/lib/artifacts/scan.js +401 -0
  19. package/lib/cache-archive-sqlite.js +41 -25
  20. package/lib/certs/analyze.js +49 -13
  21. package/lib/charts.js +124 -32
  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/pe-metadata.js +27 -1
  29. package/lib/codecs/binary/scan.js +44 -26
  30. package/lib/codecs/binary/sniff.js +16 -15
  31. package/lib/codecs/binary.codec.js +27 -4
  32. package/lib/codecs/go/parse.js +10 -4
  33. package/lib/codecs/go.codec.js +23 -6
  34. package/lib/codecs/gradle/parse.js +63 -2
  35. package/lib/codecs/gradle/versionless.js +175 -0
  36. package/lib/codecs/gradle.codec.js +20 -3
  37. package/lib/codecs/index.js +2 -2
  38. package/lib/codecs/maven.codec.js +9 -4
  39. package/lib/codecs/npm/collect.js +6 -11
  40. package/lib/codecs/nuget/parse.js +16 -5
  41. package/lib/codecs/nuget.codec.js +2 -1
  42. package/lib/codecs/pypi/parse.js +56 -15
  43. package/lib/codecs/pypi.codec.js +2 -0
  44. package/lib/csaf-export.js +46 -11
  45. package/lib/cve-download.js +33 -29
  46. package/lib/cve-match.js +10 -0
  47. package/lib/cve-packages-proxy.js +19 -0
  48. package/lib/cve-report.js +273 -165
  49. package/lib/deps-descriptor.js +25 -3
  50. package/lib/diagnostics.js +12 -0
  51. package/lib/diff.js +0 -0
  52. package/lib/epss.js +6 -6
  53. package/lib/euvd.js +34 -4
  54. package/lib/finding-enrichment.js +165 -0
  55. package/lib/finding-summary.js +4 -3
  56. package/lib/i18n.js +35 -9
  57. package/lib/image-network.js +54 -0
  58. package/lib/image-references.js +203 -0
  59. package/lib/image-registry.js +385 -0
  60. package/lib/image-update.js +39 -0
  61. package/lib/json-export.js +100 -10
  62. package/lib/kev.js +6 -6
  63. package/lib/maven-bom.js +2 -1
  64. package/lib/merge-sources.js +3 -0
  65. package/lib/native-advisories.js +9 -7
  66. package/lib/native-cna-identities.js +12 -0
  67. package/lib/native-package-match.js +159 -0
  68. package/lib/native-source-prepare.js +60 -0
  69. package/lib/nvd.js +34 -23
  70. package/lib/osv.js +33 -14
  71. package/lib/project-descriptor.js +3 -2
  72. package/lib/provenance.js +8 -2
  73. package/lib/providers/alpine.js +8 -0
  74. package/lib/providers/common.js +11 -3
  75. package/lib/providers/debian.js +11 -0
  76. package/lib/providers/euvd.js +2 -1
  77. package/lib/providers/freexian.js +13 -0
  78. package/lib/providers/github.js +1 -0
  79. package/lib/providers/go.js +2 -1
  80. package/lib/providers/index.js +18 -14
  81. package/lib/providers/nginx.js +5 -0
  82. package/lib/providers/nvd.js +1 -1
  83. package/lib/providers/osv.js +1 -1
  84. package/lib/providers/osvdb.js +2 -2
  85. package/lib/proxy-throttle.js +89 -29
  86. package/lib/purl.js +10 -2
  87. package/lib/record-freshness.js +22 -0
  88. package/lib/report-notices.js +47 -0
  89. package/lib/report-time.js +45 -0
  90. package/lib/request-failure.js +22 -0
  91. package/lib/resource-cache/engine.js +130 -26
  92. package/lib/resource-cache/snapshot-projection.js +33 -0
  93. package/lib/resource-cache/validate.js +22 -5
  94. package/lib/risk-evidence.js +18 -0
  95. package/lib/sarif-export.js +17 -9
  96. package/lib/sbom-export.js +38 -12
  97. package/lib/source-health.js +25 -8
  98. package/lib/source-image-scan.js +57 -0
  99. package/lib/source-profile.js +6 -3
  100. package/lib/sqlite-driver.js +15 -1
  101. package/lib/suppress.js +34 -13
  102. package/lib/system-inventory/advisories.js +169 -0
  103. package/lib/system-inventory/alpine-tracker.js +47 -0
  104. package/lib/system-inventory/collect.js +118 -0
  105. package/lib/system-inventory/current-debian.js +99 -0
  106. package/lib/system-inventory/distribution-sources.js +132 -0
  107. package/lib/system-inventory/freexian-ela.js +32 -0
  108. package/lib/system-inventory/freexian-release-evidence.js +35 -0
  109. package/lib/system-inventory/freexian-tracker.js +72 -0
  110. package/lib/system-inventory/historical-debian.js +196 -0
  111. package/lib/system-inventory/index.js +2 -0
  112. package/lib/system-inventory/nginx-advisories.js +39 -0
  113. package/lib/system-inventory/rpm-storage.js +86 -0
  114. package/lib/system-inventory/targeted.js +70 -0
  115. package/lib/system-inventory/versions.js +59 -0
  116. package/lib/transitive.js +11 -2
  117. package/lib/ui.js +8 -5
  118. package/lib/unmanaged.js +1 -1
  119. package/lib/xlsx-export.js +8 -2
  120. package/package.json +12 -3
  121. package/vigievuln.js +279 -127
@@ -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};
@@ -0,0 +1,401 @@
1
+ 'use strict';
2
+
3
+ const fs = require('node:fs');
4
+ const path = require('node:path');
5
+ const crypto = require('node:crypto');
6
+ const { makeDepRecord } = require('../dep-record');
7
+ const { openArtifact } = require('./index');
8
+ const { collectInstalledApplications } = require('./applications');
9
+ const { collectSystemInventory, assessSystemInventory, syncSystemAdvisories } = require('../system-inventory');
10
+
11
+ const SNAPSHOT_SCHEMA = 'vigievuln-artifact-inventory/1';
12
+ const sha = value => crypto.createHash('sha256').update(value).digest('hex');
13
+ function normalizeWarnings(values = [], capability = 'inventory') {
14
+ return values.map(value => typeof value === 'string'
15
+ ? { type: capability === 'inventory' ? 'dependency-coverage' : 'source-unavailable', capability, message: value }
16
+ : { capability, ...value });
17
+ }
18
+ function coverageRecords(values = [], targetId, capability) {
19
+ return values.map((value, index) => {
20
+ const execution = value.execution || ({ complete: 'completed', completed: 'completed', unsupported: 'partial',
21
+ incomplete: 'partial', unknown: 'partial', missing: 'not-run', failed: 'failed', absent: 'not-applicable' })[value.status] || 'partial';
22
+ return { ...value, artifactTargetId: targetId, capability: value.capability || capability,
23
+ collector: value.collector || value.source || `${capability}-${index}`, execution,
24
+ result: value.result || (execution === 'not-applicable' ? 'not-applicable' : 'indeterminate') };
25
+ });
26
+ }
27
+ function portable(value, root, replacement = '') {
28
+ if (typeof value === 'string') return value.split(root + path.sep).join(replacement).split(root.replace(/\\/g, '/') + '/').join(replacement);
29
+ if (Array.isArray(value)) return value.map(v => portable(v, root, replacement));
30
+ if (value && typeof value === 'object') return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, portable(v, root, replacement)]));
31
+ return value;
32
+ }
33
+ function qualify(dep, targetId) {
34
+ const out = { ...dep, artifactTargetId: targetId };
35
+ out.artifactPath = dep.manifestPaths?.[0] || dep.manifestPath || dep.installEvidence?.path || null;
36
+ out.coordKey = `artifact:${targetId}:${dep.coordKey || [dep.manager, dep.name, dep.version, out.artifactPath].join(':')}`;
37
+ return out;
38
+ }
39
+ const PACKAGE_TYPES = { dpkg: 'deb', deb: 'deb', apk: 'apk', rpm: 'rpm' };
40
+ function systemDep(pkg, targetId, distribution) {
41
+ const dep = makeDepRecord({ ecosystem: 'system', namespace: distribution?.id || '', name: pkg.name,
42
+ version: pkg.version, manifestPath: pkg.manifestPath, provenance: pkg.provenance || 'installed', scope: 'runtime' });
43
+ dep.coordKey = [pkg.manager || '', pkg.name || '', pkg.version || '', pkg.architecture || '', pkg.manifestPath || ''].map(value => encodeURIComponent(String(value))).join(':');
44
+ return qualify({ ...dep, manager: pkg.manager, packageType: pkg.packageType || PACKAGE_TYPES[pkg.manager] || null,
45
+ architecture: pkg.architecture, sourceName: pkg.sourceName, sourceVersion: pkg.sourceVersion,
46
+ distribution, systemEvidence: pkg.evidence || null, packageMetadata:pkg.packageMetadata || null, packageOrigin:pkg.packageOrigin || null }, targetId);
47
+ }
48
+
49
+ async function inventoryTarget(target, options = {}) {
50
+ const system = await collectSystemInventory(target.root, options);
51
+ const applications = await collectInstalledApplications(target.root, options);
52
+ const binaries = await require('../codecs/binary.codec').collect(target.root, { ...options, defaultExcludes: false, srcRoot: target.root });
53
+ const order = (a, b) => JSON.stringify([a.ecosystem, a.manager, a.namespace, a.name, a.version, a.architecture, a.manifestPath, a.manifestPaths]).localeCompare(JSON.stringify([b.ecosystem, b.manager, b.namespace, b.name, b.version, b.architecture, b.manifestPath, b.manifestPaths]));
54
+ const packages = portable(system.packages, target.root).map(p => ({ ...p, ...(p.ownedPaths ? { ownedPaths: [...p.ownedPaths].sort() } : {}) })).sort(order);
55
+ const appDeps = portable([...applications.deps.values(), ...binaries.deps.values()], target.root).sort(order);
56
+ const id = target.kind === 'rootfs' && target.metadata.format === 'directory'
57
+ ? `rootfs-inventory:sha256:${sha(JSON.stringify({ distribution: system.distribution, packages, deps: appDeps }))}` : target.id;
58
+ const owners = new Map();
59
+ const pathKey = value => path.posix.normalize('/' + String(value || '').replace(/\\/g, '/').replace(/^\/+/, ''));
60
+ for (const pkg of packages) for (const ownedPath of pkg.ownedPaths || []) {
61
+ const keys = new Set([pathKey(ownedPath)]);
62
+ // Resolve directory aliases such as merged-/usr, never follow the file's own
63
+ // symlink: ownership of a link does not confer ownership of its destination.
64
+ try {
65
+ const root = fs.realpathSync(target.root), parent = fs.realpathSync(path.dirname(path.join(root, ownedPath.replace(/^\/+/, ''))));
66
+ if (parent === root || parent.startsWith(root + path.sep)) keys.add(pathKey(path.relative(root, path.join(parent, path.basename(ownedPath)))));
67
+ } catch { /* Removed/unavailable owned paths do not create invented evidence. */ }
68
+ for (const key of keys) {
69
+ const list = owners.get(key) || [];
70
+ list.push({ name: pkg.name, version: pkg.version, manager: pkg.manager, evidencePath: pkg.manifestPath });
71
+ owners.set(key, list);
72
+ }
73
+ }
74
+ const deps = [...packages.map(p => systemDep(p, id, system.distribution)), ...appDeps.map(d => {
75
+ const evidence = d.binaryEvidence?.binaryPath || d.installEvidence?.path || d.manifestPaths?.[0];
76
+ // A shared aggregate manifest does not prove that every package it names is OS-owned.
77
+ const aggregate = ['composer', 'composer-php', 'nuget'].includes(d.installEvidence?.source);
78
+ const owned = evidence && !aggregate ? owners.get(pathKey(evidence)) : null;
79
+ return qualify(owned?.length ? { ...d, osPackageOwners: owned } : d, id);
80
+ })];
81
+ const warnings = portable(normalizeWarnings([...(system.warnings || []), ...applications.warnings, ...binaries.warnings,
82
+ ...(target.metadata.warnings || [])]), target.root);
83
+ const coverage = coverageRecords(system.coverage, id, 'inventory');
84
+ coverage.push({ artifactTargetId: id, capability: 'inventory', collector: 'installed-applications',
85
+ execution: applications.warnings.length ? 'partial' : 'completed', result: 'indeterminate', count: applications.deps.size });
86
+ coverage.push({ artifactTargetId: id, capability: 'inventory', collector: 'native-binaries',
87
+ execution: binaries.warnings.length ? 'partial' : 'completed', result: 'indeterminate', count: [...binaries.deps.values()].filter(d => d.ecosystem === 'binary').length });
88
+ if (target.metadata.warnings?.length) coverage.push({ artifactTargetId: id, capability: 'inventory', collector: 'artifact-reader', execution: 'partial', result: 'indeterminate' });
89
+ const source = options.source || path.basename(target.metadata.source || target.root);
90
+ const acquisition = options.registry ? { kind: 'registry', reference: source } : {
91
+ kind: target.metadata.format === 'directory' ? 'rootfs-directory' : target.metadata.format === 'oci-layout' && target.metadata.source && fs.statSync(target.metadata.source).isDirectory() ? 'oci-layout' : 'archive', source,
92
+ };
93
+ return { id, kind: target.kind, metadata: { ...target.metadata, source, acquisition, definitions: [], definitionDiscovery: {status:'not-supplied'} },
94
+ evidence: 'content-inventory', inventoryAt: new Date().toISOString(), distribution: system.distribution,
95
+ packages, deps, coverage, warnings, componentCount: deps.length };
96
+ }
97
+
98
+ function sbomTarget(input, options = {}) {
99
+ const parsed = require('./sbom').readSbom(input, options);
100
+ const id = 'sbom-inventory:sha256:' + sha(JSON.stringify(typeof input === 'string' ? JSON.parse(fs.readFileSync(input, 'utf8')) : input));
101
+ // A root component's name is not an os-release identity.
102
+ const mismatch = options.distribution && parsed.distribution && (options.distribution.id !== parsed.distribution.id || options.distribution.versionId !== parsed.distribution.versionId);
103
+ if (mismatch) parsed.warnings.push({ type: 'dependency-coverage', reason: 'sbom-distribution-conflict', message: 'Requested distribution conflicts with publisher SBOM distribution evidence.' });
104
+ const distribution = parsed.warnings.some(w => w.reason === 'sbom-distribution-conflict') ? null : (options.distribution || parsed.distribution || null);
105
+ const packages = parsed.systemPackages;
106
+ const deps = [...packages.map(p => systemDep(p, id, distribution)), ...[...parsed.deps.values()].map(d => qualify(d, id))];
107
+ return { id, kind: 'sbom', metadata: { ...parsed.metadata, source: typeof input === 'string' ? path.basename(input) : options.source,
108
+ digest: options.expectedDigest || parsed.metadata.subjectDigests?.[0] || null, platform: options.platform || parsed.metadata.platform,
109
+ acquisition: options.registry ? { kind: 'registry', reference: options.registryReference || options.source } : { kind: 'sbom', source: typeof input === 'string' ? path.basename(input) : options.source || null }, definitions: [], definitionDiscovery: {status:'not-supplied'} },
110
+ evidence: 'sbom', inventoryAt: new Date().toISOString(), distribution, packages, deps,
111
+ warnings: parsed.warnings, coverage: [{ artifactTargetId: id, capability: 'inventory', collector: 'sbom',
112
+ execution: 'partial', result: 'indeterminate', reason: 'Publisher inventory; component completeness and signature not verified.' }], componentCount: deps.length };
113
+ }
114
+
115
+ function createSnapshot(targets) {
116
+ const content = { schema: SNAPSHOT_SCHEMA, generatedAt: new Date().toISOString(), targets };
117
+ return { ...content, integrity: { algorithm: 'sha256', digest: sha(JSON.stringify(content)) } };
118
+ }
119
+ function validateSnapshot(doc) {
120
+ if (!doc || typeof doc !== 'object' || Array.isArray(doc)) throw Error('invalid artifact inventory schema or integrity');
121
+ const { integrity, ...content } = doc;
122
+ if (content.schema !== SNAPSHOT_SCHEMA || !Array.isArray(content.targets) || !content.targets.length || integrity?.algorithm !== 'sha256' || integrity.digest !== sha(JSON.stringify(content))) throw Error('invalid artifact inventory schema or integrity');
123
+ const targetIds = new Set(), componentIds = new Set();
124
+ for (const target of content.targets) {
125
+ if (!target || typeof target.id !== 'string' || !target.id || targetIds.has(target.id) || !target.metadata || !Array.isArray(target.deps) || !Array.isArray(target.packages) || !Array.isArray(target.coverage) || !Array.isArray(target.warnings)) throw Error('invalid or duplicate artifact inventory target');
126
+ targetIds.add(target.id);
127
+ for (const dep of target.deps) {
128
+ if (typeof dep?.coordKey !== 'string' || !dep.coordKey || componentIds.has(dep.coordKey) || dep.artifactTargetId !== target.id || typeof dep.ecosystem !== 'string' || typeof dep.name !== 'string') throw Error('invalid or duplicate artifact inventory component');
129
+ componentIds.add(dep.coordKey);
130
+ }
131
+ for (const record of target.coverage) if (record.artifactTargetId && record.artifactTargetId !== target.id) throw Error('artifact inventory coverage target mismatch');
132
+ }
133
+ return content.targets;
134
+ }
135
+ function readSnapshot(file, options = {}) {
136
+ if (fs.statSync(file).size > (options.maxSnapshotBytes ?? 128 * 1024 * 1024)) throw Error('artifact inventory exceeds configured size limit');
137
+ return validateSnapshot(JSON.parse(fs.readFileSync(file, 'utf8'))).map(t => ({ ...t, evidence: 'cached-inventory', originalEvidence: t.evidence }));
138
+ }
139
+ async function writeSnapshot(file, targets) {
140
+ const absolute = path.resolve(file);
141
+ await fs.promises.mkdir(path.dirname(absolute), { recursive: true });
142
+ const temp = absolute + '.' + crypto.randomUUID() + '.tmp';
143
+ try { await fs.promises.writeFile(temp, JSON.stringify(createSnapshot(targets), null, 2) + '\n', { mode: 0o600 }); await fs.promises.rename(temp, absolute); }
144
+ finally { await fs.promises.rm(temp, { force: true }); }
145
+ }
146
+
147
+ async function acquireInventories(input, options = {}) {
148
+ if (options.inventory) return readSnapshot(input, options);
149
+ if (options.sbom) return [sbomTarget(input, options)];
150
+ const cache = options.registry ? require('../cache-repository').createCacheRepository(options.cacheDir) : null;
151
+ const legacyCacheKey = sha(JSON.stringify([input, options.platform || null, !!options.preferSbom]));
152
+ const ref = options.registry ? require('../image-registry').parseReference(input) : null;
153
+ const cacheKey = ref ? sha(JSON.stringify([`${ref.registry}/${ref.repository}@${ref.reference}`, options.platform || null, !!options.preferSbom])) : legacyCacheKey;
154
+ if (options.registry && options.offline) {
155
+ const saved = cache.get('image-inventory', cacheKey) || cache.get('image-inventory', legacyCacheKey);
156
+ if (!saved?.value || saved.value.schema !== SNAPSHOT_SCHEMA) throw Error('image inventory is not cached; import an inventory/archive or prepare this reference online');
157
+ const targets = validateSnapshot(saved.value);
158
+ return targets.map(target => ({ ...target, evidence: 'cached-inventory', originalEvidence: target.evidence,
159
+ warnings: [...target.warnings, { type: 'cached-image-resolution', severity:'info', capability: 'sources', message: 'Using the prepared image digest and inventory offline; the registry tag is not re-resolved in this mode.' }] }));
160
+ }
161
+ const persist = targets => {
162
+ validateSnapshot(createSnapshot(targets));
163
+ if (cache) cache.put('image-inventory', cacheKey, createSnapshot(targets));
164
+ return targets;
165
+ };
166
+ if (cache && !options.forceUpdate && !require('../cache-policy').shouldForceUpdate()) {
167
+ let targets;
168
+ try {
169
+ const saved = cache.get('image-inventory', cacheKey) || cache.get('image-inventory', legacyCacheKey);
170
+ if (saved?.value) targets = validateSnapshot(saved.value);
171
+ } catch { /* Invalid snapshots must be rebuilt from verified content online. */ }
172
+ const digest = targets?.[0]?.metadata?.acquisition?.indexDigest;
173
+ // Publisher SBOMs can be updated independently of the image digest.
174
+ if (digest && targets.every(t => t.evidence === 'content-inventory' && t.metadata?.acquisition?.indexDigest === digest)) {
175
+ const current = ref.reference.includes(':') ? ref.reference : await require('../image-registry').fetchRegistryDigest(input,
176
+ {...options, fetcher:options.registryFetcher || options.fetcher, limits:options.registryLimits});
177
+ if (current === digest) return targets.map(target => ({...target, evidence:'cached-inventory', originalEvidence:target.evidence}));
178
+ }
179
+ }
180
+ let registry = null, opened = null, sbomAttempt = null;
181
+ try {
182
+ if (options.registry) {
183
+ if (options.preferSbom) {
184
+ try {
185
+ const discovered = await require('../image-registry').fetchRegistrySboms(input, { ...options, fetcher: options.registryFetcher || options.fetcher, limits: options.registryLimits });
186
+ // Never drop image platforms when only a subset has publisher metadata.
187
+ const subjects = new Set(discovered.documents.map(d => d.expectedDigest));
188
+ if (discovered.documents.length && subjects.size >= (discovered.metadata.platforms?.length || 1)) {
189
+ const targets = discovered.documents.map(item => sbomTarget(item.document, { ...options, expectedDigest: item.expectedDigest,
190
+ ...(item.source?.binding?.kind === 'oci-subject' ? { boundSubjectDigest: item.expectedDigest,
191
+ boundSubjectEvidence: { type: 'oci-manifest-subject', manifestDigest: item.source.manifestDigest } } : {}),
192
+ platform: item.platform, registryReference: input, source: `${input}@${item.expectedDigest}` }));
193
+ // Prefer metadata only when every component can actually be assessed.
194
+ // Signature verification remains explicitly outside this evidence.
195
+ const unusable = targets.some(t => t.warnings.some(w => w.reason !== 'sbom-unverified'));
196
+ if (!unusable) {
197
+ for (const target of targets) { target.metadata.registryEvidence = discovered.metadata; target.metadata.acquisition.resolvedDigest = target.metadata.digest; target.metadata.acquisition.indexDigest = discovered.metadata.digest; }
198
+ return persist(targets);
199
+ }
200
+ sbomAttempt = { status: 'fallback', reason: 'Publisher inventory lacks component identity, distribution, or source-package evidence.' };
201
+ } else sbomAttempt = { status: 'fallback', reason: 'Publisher inventory is not available for every selected image platform.' };
202
+ } catch (error) {
203
+ sbomAttempt = { status: 'fallback', reason: 'Publisher inventory could not be validated; full image content was requested.' };
204
+ }
205
+ }
206
+ registry = await require('../image-registry').fetchRegistryImage(input, { ...options, fetcher: options.registryFetcher || options.fetcher, limits: options.registryLimits });
207
+ }
208
+ opened = await openArtifact(registry?.path || input, { ...options, limits: options.artifactLimits });
209
+ const targets = [];
210
+ for (const target of opened.targets) {
211
+ if (options.platform) {
212
+ const platform = target.metadata.platform;
213
+ if (!platform || [platform.os, platform.architecture, platform.variant].filter(Boolean).join('/') !== options.platform && [platform.os, platform.architecture].join('/') !== options.platform) continue;
214
+ }
215
+ const inventory = await inventoryTarget(target, { ...options, source: registry ? input : undefined });
216
+ if (registry) { inventory.metadata.registryEvidence = registry.metadata; inventory.metadata.acquisition.resolvedDigest = inventory.metadata.digest || null; inventory.metadata.acquisition.indexDigest = registry.metadata.digest; }
217
+ if (sbomAttempt) inventory.metadata.publisherInventory = sbomAttempt;
218
+ targets.push(inventory);
219
+ }
220
+ if (!targets.length) throw Error('no artifact matches the requested platform');
221
+ return persist(targets);
222
+ } finally { if (opened) await opened.cleanup(); if (registry) await registry.cleanup(); }
223
+ }
224
+
225
+ async function assessInventories(targets, options = {}) {
226
+ options.onArtifactProgress?.({stage:'Component identities'});
227
+ targets=targets.map(target=>JSON.parse(JSON.stringify(target)));
228
+ for(const target of targets){
229
+ for(const pkg of target.packages){const origin=require('../system-inventory/distribution-sources').identifyPackageOrigin(pkg,options);if(origin)pkg.packageOrigin=origin;}
230
+ for(const dep of target.deps){const origin=require('../system-inventory/distribution-sources').identifyPackageOrigin(dep,options);if(origin)dep.packageOrigin=origin;}
231
+ const identity=await require('./go-main-identity').resolveGoMainIdentities(target,options);
232
+ for(const dep of identity.deps){const qualified=qualify(dep,target.id);if(!target.deps.some(d=>d.coordKey===qualified.coordKey))target.deps.push(qualified);}
233
+ target.coverage.push({...identity.coverage,artifactTargetId:target.id,capability:'inventory'});
234
+ target.warnings.push(...identity.warnings);
235
+ }
236
+ const resolvedDeps = new Map(), cveMatches = [], warnings = [], artifacts = [], warmed = new Set();
237
+ const nativeDeps=new Map();
238
+ for(const target of targets)for(const dep of target.deps||[])if(dep.ecosystem!=='binary' && (!dep.osPackageOwners?.length || dep.binaryEvidence))nativeDeps.set(dep.coordKey,dep);
239
+ let native={matches:[],unknown:[],coverage:{status:'not-applicable'}},nativePreparation={sources:[],coverage:[],warnings:[]};
240
+ if(nativeDeps.size){
241
+ const nativeOptions={...options};
242
+ try{
243
+ options.onArtifactProgress?.({stage:'Native advisory preparation'});
244
+ nativePreparation=await require('../native-source-prepare').prepareNativeSources(nativeDeps,nativeOptions);
245
+ if(nativePreparation.sources.length){
246
+ const store=require('../advisory-store').openAdvisoryStore({cacheDir:options.cacheDir});
247
+ options.onArtifactProgress?.({stage:'Native advisory matching'});
248
+ try{native=require('../native-advisories').matchNativePackages(nativeDeps,store,{sources:nativePreparation.sources});}finally{store.close();}
249
+ }
250
+ }catch(error){nativePreparation.warnings.push(`Native advisory scan failed: ${error.message}`);native.coverage={status:'incomplete',reason:error.message};}
251
+ }
252
+ for (const original of targets) {
253
+ const target = JSON.parse(JSON.stringify(original));
254
+ let targetWarnings = normalizeWarnings(target.warnings);
255
+ const assessedPackages = new Set();
256
+ const coverage = [...target.coverage];
257
+ options.onArtifactProgress?.({stage:'Distribution advisories'});
258
+ const distroKey = JSON.stringify(target.distribution);
259
+ if (options.osv !== false && !options.offline && target.packages.length && !warmed.has(distroKey) && !require('../providers').hasHostedProxy()) {
260
+ warmed.add(distroKey);
261
+ try {
262
+ const scope=require('../system-inventory').scope(target.distribution,options);
263
+ const cached=scope && require('../cache-repository').createCacheRepository(options.cacheDir).getSnapshot('system-osv:'+scope.ecosystem);
264
+ const age=Date.now()-(cached?.fetchedAt||0);
265
+ if(options.refresh || !cached?.complete || cached.stale || age<0 || age>=require('../cache-policy').DEFAULT_TTL_MS)
266
+ await syncSystemAdvisories(target.distribution, options);
267
+ }
268
+ catch (error) { targetWarnings.push({ type: 'source-unavailable', capability: 'sources', message: `System advisory refresh failed: ${error.message}` }); }
269
+ }
270
+ for (const dep of target.deps) resolvedDeps.set(dep.coordKey, dep);
271
+ for(const source of nativePreparation.coverage){
272
+ coverage.push(...coverageRecords([{...source,collector:`native-${source.source}`}],target.id,'sources'));
273
+ if(source.issue && source.issue!=='refresh-failed')targetWarnings.push({type:'source-unavailable',severity:source.issue==='missing-source'?'info':undefined,capability:'sources',source:source.source,message:`${source.source}: ${source.reason}.`});
274
+ }
275
+ for(const warning of nativePreparation.warnings)targetWarnings.push(typeof warning==='string'?{type:'source-unavailable',capability:'sources',message:warning}:{capability:'sources',...warning});
276
+ const nativeUnknown=native.unknown.filter(item=>!item.artifactTargetId||item.artifactTargetId===target.id);
277
+ if(nativeUnknown.length){coverage.push({artifactTargetId:target.id,capability:'sources',collector:'native-comparisons',execution:'partial',result:'indeterminate',count:nativeUnknown.length});targetWarnings.push({type:'source-unavailable',severity:'info',capability:'sources',message:`${nativeUnknown.length} native advisory package/version comparison(s) are undecidable.`});}
278
+ if (target.packages.length && options.osv === false) {
279
+ coverage.push({ artifactTargetId: target.id, capability: 'advisories', collector: 'system-osv', execution: 'not-applicable', result: 'not-consulted', expected:false, reason: 'OSV is excluded by source configuration.' });
280
+ } else if (target.packages.length) {
281
+ const systemInventory = { distribution: target.distribution, packages: target.packages.filter(p=>!['third-party','ambiguous'].includes(p.packageOrigin?.status)) };
282
+ const excluded=target.packages.length-systemInventory.packages.length;
283
+ if(excluded){const reason='Distribution OSV ranges do not establish applicability for packages declaring another vendor.';coverage.push({artifactTargetId:target.id,capability:'advisories',collector:'system-osv-vendor-scope',execution:'partial',result:'indeterminate',count:excluded,reason});targetWarnings.push({type:'dependency-coverage',severity:'info',capability:'advisories',message:reason});}
284
+ const hostedOnline = !options.offline && require('../providers').hasHostedProxy();
285
+ let assessment;
286
+ try {
287
+ assessment = hostedOnline ? await require('../system-inventory').assessTargetedSystemInventory(systemInventory, options)
288
+ : await assessSystemInventory(systemInventory, options);
289
+ if (options.offline && assessment.coverage.some(c => c.status === 'missing')) {
290
+ const targeted = await require('../system-inventory').assessTargetedSystemInventory(systemInventory, options);
291
+ if (targeted.coverage.some(c => c.consulted > c.unknown)) assessment = targeted;
292
+ }
293
+ } catch(error) {
294
+ assessment={matches:[],coverage:[{source:'system-osv',status:'incomplete',reason:error.message}],warnings:[`System OSV assessment failed: ${error.message}`]};
295
+ }
296
+ if (assessment.coverage.length && assessment.coverage.every(c=>c.status==='complete')) for(const pkg of systemInventory.packages) assessedPackages.add(`${pkg.manager}:${pkg.name}@${pkg.version}`);
297
+ coverage.push(...coverageRecords(assessment.coverage, target.id, 'advisories'));
298
+ targetWarnings.push(...normalizeWarnings(assessment.warnings, 'advisories'));
299
+ for (const match of assessment.matches) {
300
+ const dep = systemDep(match.dep, target.id, target.distribution);
301
+ const full = resolvedDeps.get(dep.coordKey) || dep;
302
+ const cve = { ...match.cve, score: match.cve.score ?? match.cve.cvss ?? null,
303
+ fixVersion: match.cve.fixVersion || match.fixVersion || null,
304
+ osvRefs: match.cve.osvRefs || match.cve.references || [] };
305
+ cveMatches.push({ ...match, dep: full, cve });
306
+ }
307
+ }
308
+ options.onArtifactProgress?.({stage:'Distribution security trackers'});
309
+ const distribution=await require('../system-inventory/distribution-sources').assessDistributionSources({distribution:target.distribution,packages:target.packages},{...options,confirmedMatches:[...cveMatches,...native.matches].filter(m=>m.dep?.artifactTargetId===target.id)});
310
+ coverage.push(...coverageRecords(distribution.coverage,target.id,'advisories'));
311
+ targetWarnings.push(...normalizeWarnings(distribution.warnings,'advisories'));
312
+ for(const match of distribution.matches){const dep=systemDep(match.dep,target.id,target.distribution);cveMatches.push({...match,dep:resolvedDeps.get(dep.coordKey)||dep});}
313
+ options.onArtifactProgress?.({stage:'Application advisories'});
314
+ const appDeps = new Map(target.deps.filter(d => d.ecosystem !== 'system' && d.ecosystem !== 'binary' && (!d.osPackageOwners?.length || !!d.binaryEvidence)).map(d => [d.coordKey, d]));
315
+ if (appDeps.size && options.osv === false) {
316
+ coverage.push({ artifactTargetId: target.id, capability:'advisories',collector:'osv-application',execution:'not-applicable',result:'not-consulted',expected:false,reason:'OSV is excluded by source configuration.' });
317
+ } else if (appDeps.size) {
318
+ const appWarnings = [];
319
+ try {
320
+ const matches = await require('../osv').queryOsvForDeps(appDeps, { ...options, allowStaleFallback: true,
321
+ onWarning: warning => appWarnings.push(typeof warning === 'string' ? { type: 'osv-coverage', message: warning } : warning) });
322
+ cveMatches.push(...matches);
323
+ const incomplete=appWarnings.some(w=>!require('../diagnostics').isInformational(w));
324
+ coverage.push({ artifactTargetId: target.id, capability: 'advisories', collector: 'osv-application',
325
+ execution: incomplete ? 'partial' : 'completed', result: matches.length ? 'affected' : incomplete ? 'indeterminate' : 'no-match', count: appDeps.size });
326
+ } catch (error) {
327
+ appWarnings.push({ type: 'source-unavailable', message: `Application advisory scan failed: ${error.message}` });
328
+ coverage.push({ artifactTargetId: target.id, capability: 'advisories', collector: 'osv-application', execution: 'failed', result: 'indeterminate' });
329
+ }
330
+ targetWarnings.push(...normalizeWarnings(appWarnings, 'advisories'));
331
+ }
332
+ options.onArtifactProgress?.({stage:'Publisher advisories'});
333
+ const publisher=await require('./publisher-advisories').assessPublisherAdvisories(appDeps,options);
334
+ cveMatches.push(...publisher.matches);
335
+ coverage.push(...coverageRecords(publisher.coverage,target.id,'advisories'));
336
+ targetWarnings.push(...normalizeWarnings(publisher.warnings,'advisories'));
337
+ const identifiedBinaryPaths=new Set(target.deps.filter(d=>d.binaryEvidence?.source==='go-vcs-and-module-proxy').map(d=>d.binaryEvidence.binaryPath));
338
+ const unknownBinaries = target.deps.filter(d => d.ecosystem === 'binary' && !d.osPackageOwners?.length && !identifiedBinaryPaths.has(d.artifactPath));
339
+ if (unknownBinaries.length) {
340
+ coverage.push({ artifactTargetId: target.id, capability: 'advisories', collector: 'native-binaries', execution: 'partial', result: 'indeterminate', count: unknownBinaries.length, reason: 'Native binary identities cannot all be established from embedded metadata.' });
341
+ targetWarnings.push({ type: 'dependency-coverage', severity:'info', capability: 'advisories', message: `${unknownBinaries.length} native binaries have no authenticated package/version identity.` });
342
+ }
343
+ const archiveContext=require('./applications').classifyOwnedArchiveWarnings(targetWarnings,target.packages,assessedPackages);
344
+ if(archiveContext.informational.length){
345
+ targetWarnings=archiveContext.warnings;
346
+ // Reclassify the collector only when none of its original inventory
347
+ // diagnostics remain; never hide malformed archives or unresolved files.
348
+ if(!targetWarnings.some(w=>w.capability==='inventory' && !require('../diagnostics').isInformational(w)))
349
+ for(const check of coverage)if(check.collector==='installed-applications' && check.execution==='partial')check.execution='completed';
350
+ targetWarnings.push(...archiveContext.informational.map(({warning,owner,path})=>({...warning,severity:'info',type:'os-owned-component',owner,
351
+ message:`${path} is covered by its installed OS package ${owner.name}@${owner.version}; no independent Maven identity is declared.`})));
352
+ }
353
+ for (const check of coverage) {
354
+ if (['completed', 'not-applicable'].includes(check.execution)) continue;
355
+ if (check.collector==='native-binaries' || check.collector==='native-comparisons' || check.collector==='go-main-identity' || check.collector==='system-osv-vendor-scope' || check.issue==='missing-source') continue;
356
+ if (targetWarnings.some(w => w.capability === check.capability && !require('../diagnostics').isInformational(w))) continue;
357
+ targetWarnings.push({ type: check.capability === 'inventory' ? 'dependency-coverage' : 'source-unavailable',
358
+ capability: check.capability, message: `${check.collector || check.source || check.capability}: ${check.reason || check.execution}; coverage is incomplete.` });
359
+ }
360
+ warnings.push(...targetWarnings.map(w => ({ artifactTargetId: target.id, ...w })));
361
+ artifacts.push({ id: target.id, kind: target.kind, metadata: target.metadata, evidence: target.evidence,
362
+ originalEvidence: target.originalEvidence, distribution: target.distribution, inventoryAt: target.inventoryAt,
363
+ componentCount: target.deps.length, coverage, advisoryObservations:distribution.observations, components: target.deps.map(d => ({ ecosystem: d.ecosystem, packageType: d.packageType,
364
+ namespace: d.namespace, name: d.name, version: d.version, sourceName:d.sourceName || null, sourceVersion:d.sourceVersion || null, packageOrigin:d.packageOrigin || null, architecture: d.architecture, artifactPath: d.artifactPath,
365
+ provenance: d.provenance, coordKey: d.coordKey, binaryEvidence:d.binaryEvidence, osPackageOwners: d.osPackageOwners || [],
366
+ purl: require('../purl').purlFor(d) })) });
367
+ }
368
+ const combined=require('../merge-sources').mergeBySource(cveMatches,native.matches);
369
+ cveMatches.splice(0,cveMatches.length,...combined);
370
+ for (const artifact of artifacts) {
371
+ options.onArtifactProgress?.({stage:'Image updates'});
372
+ try { artifact.imageUpdate=await require('../image-update').resolveImageUpdate(artifact.metadata,options); }
373
+ catch (error) { artifact.imageUpdate={status:'unknown',reference:artifact.metadata?.acquisition?.reference||null,reason:`Image update lookup unavailable: ${error.message}`,verifiedFix:false}; }
374
+ const matches = cveMatches.filter(m => m.dep?.artifactTargetId === artifact.id);
375
+ options.onArtifactProgress?.({stage:'CVE enrichment'});
376
+ const enrichment = await require('./enrichment').enrichArtifactFindings(matches, options);
377
+ artifact.coverage.push(...enrichment.coverage.map(c => ({ ...c, artifactTargetId: artifact.id })));
378
+ warnings.push(...enrichment.warnings.map(w => ({ ...w, artifactTargetId: artifact.id })));
379
+ }
380
+ require('../priority').attachPriority(cveMatches);
381
+ const diagnostics=require('../diagnostics').partitionDiagnostics(warnings);
382
+ return { resolvedDeps, cveMatches: require('../finding-summary').uniqueFindings(cveMatches), ...diagnostics, artifacts };
383
+ }
384
+
385
+ function incompleteCapabilities(result, required = ['inventory', 'advisories', 'sources']) {
386
+ const gaps = [];
387
+ for (const target of result.artifacts) {
388
+ for (const capability of required) {
389
+ if (capability === 'sources') {
390
+ if (result.warnings.some(w => w.artifactTargetId === target.id && /source|osv/.test(w.type))) gaps.push({ target: target.id, capability });
391
+ } else {
392
+ const records = target.coverage.filter(c => c.capability === capability);
393
+ if (!records.length || records.some(c => !['completed', 'not-applicable'].includes(c.execution))) gaps.push({ target: target.id, capability });
394
+ }
395
+ }
396
+ }
397
+ return gaps;
398
+ }
399
+
400
+ module.exports = { acquireInventories, assessInventories, inventoryTarget, sbomTarget, readSnapshot, writeSnapshot,
401
+ createSnapshot, validateSnapshot, incompleteCapabilities, coverageRecords, systemDep, SNAPSHOT_SCHEMA };