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,45 @@
1
+ 'use strict';
2
+ // Bind a Go main module to a version only when independent Go proxy VCS
3
+ // provenance matches the clean revision embedded in the binary. OCI labels
4
+ // propose a lookup; neither a label nor an image tag proves a version alone.
5
+ const {makeDepRecord}=require('../dep-record');
6
+ const VERSION=/^v\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+incompatible)?$/;
7
+ function repo(value){try{const u=new URL(value);if(u.protocol!=='https:'||u.username||u.password||u.port||u.search||u.hash)return null;const pathname=u.pathname.replace(/\/+$/,'').replace(/\.git$/i,'');if(!pathname||pathname==='/'||pathname.split('/').some(x=>x==='.'||x==='..'))return null;return `${u.hostname.toLowerCase()}${pathname}`;}catch{return null;}}
8
+ function escapeModule(value){return value.replace(/[A-Z]/g,c=>'!'+c.toLowerCase());}
9
+ function tagRef(module,source,version){const suffix=module.slice(source.length).split('/').filter(Boolean);if(/^v(?:[2-9]|[1-9]\d+)$/.test(suffix.at(-1)||''))suffix.pop();return `refs/tags/${suffix.length?suffix.join('/')+'/':''}${version}`;}
10
+ async function resolveGoMainIdentities(target,options={}){
11
+ const metadata=target?.metadata||{},labels=metadata.imageConfig?.labels||{},version=labels['org.opencontainers.image.version'],source=repo(labels['org.opencontainers.image.source']);
12
+ const outputs=[],warnings=[],seen=new Set();let candidates=0,unavailable=0,conflicts=0,stale=0;
13
+ if(!source || !VERSION.test(version||'') || !/^sha256:[a-f0-9]{64}$/i.test(metadata.configDigest||''))return {deps:outputs,warnings,coverage:{collector:'go-main-identity',execution:'not-applicable',result:'no-candidate',count:0}};
14
+ const lookup=options.lookup || (async(module,ver)=>{const providers=require('../providers'),response=await providers.getResource('go','module-info',{module:escapeModule(module),version:ver},{offline:false,fetcher:options.fetcher,...(options.store?{store:options.store}:{})});if(!response.ok)throw Error(`Go proxy HTTP ${response.status}`);const proxied=providers.hasProxyRoute(),stamp=Date.parse(response.headers.get('x-fad-proxy-fetched-at')||'');if(proxied&&(!Number.isFinite(stamp)||stamp<=0||stamp>Date.now()+300000))throw Error('Go proxy evidence has no valid observation timestamp');return {info:await response.json(),observedAt:proxied?stamp:Date.now(),stale:proxied&&response.headers.get('x-fad-proxy')==='stale'};});
15
+ let repository;const cacheRepo=()=>repository||(repository=require('../cache-repository').createCacheRepository(options.cacheDir||require('../cache-directory').getCacheDir()));
16
+ const cache=new Map();
17
+ for(const binary of target.deps||[]){
18
+ if(binary.ecosystem!=='binary')continue;const go=binary.binaryMetadata?.go,settings=go?.settings||{},main=(go?.modules||[]).filter(m=>m.kind==='mod');
19
+ if(main.length!==1 || main[0].version!=='(devel)' || main[0].replace || !main[0].path || !(main[0].path===source || main[0].path.startsWith(source+'/')))continue;
20
+ const module=main[0].path,revision=settings['vcs.revision'],binaryPath=binary.artifactPath||binary.manifestPaths?.[0];
21
+ if(settings.vcs!=='git'||settings['vcs.modified']!=='false'||!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/i.test(revision||'')||!binaryPath||!/^[a-f0-9]{64}$/i.test(binary.hashes?.sha256||'')){conflicts++;continue;}
22
+ if((settings.GOOS && metadata.platform?.os && settings.GOOS!==metadata.platform.os)||(settings.GOARCH && metadata.platform?.architecture && settings.GOARCH!==metadata.platform.architecture)){conflicts++;continue;}
23
+ candidates++;let info,observation,key=JSON.stringify([module,version,source,revision.toLowerCase()]);try{
24
+ if(options.offline){const saved=cacheRepo().get('go-main-identity',key);if(!saved)throw Error('no cached Go proxy version evidence');observation={info:saved.value,observedAt:saved.fetchedAt,stale:saved.stale};}
25
+ else{const requestKey=`${module}\0${version}`;if(!cache.has(requestKey))cache.set(requestKey,Promise.resolve().then(()=>lookup(module,version)));const value=await cache.get(requestKey);observation=value?.info?value:{info:value,observedAt:Date.now(),stale:false};}
26
+ if(!Number.isFinite(observation.observedAt)||observation.observedAt<=0||observation.observedAt>Date.now()+300000)throw Error('invalid Go proxy evidence timestamp');
27
+ info=observation.info;
28
+ }catch(error){
29
+ let saved;try{if(!options.offline)saved=cacheRepo().get('go-main-identity',key);}catch{}
30
+ if(saved && Number.isFinite(saved.fetchedAt) && saved.fetchedAt>0 && saved.fetchedAt<=Date.now()+300000){observation={info:saved.value,observedAt:saved.fetchedAt,stale:true};info=observation.info;warnings.push({type:'source-unavailable',capability:'identity',source:'go-proxy',message:`Go module version refresh failed for ${module}@${version}; cached evidence is stale: ${error.message}`});}
31
+ else{unavailable++;warnings.push({type:'source-unavailable',capability:'identity',source:'go-proxy',message:`Go module version evidence unavailable for ${module}@${version}: ${error.message}`});continue;}
32
+ }
33
+ const origin=info?.Origin||{};
34
+ if(info?.Version!==version||origin.VCS!=='git'||repo(origin.URL)!==source||origin.Ref!==tagRef(module,source,version)||String(origin.Hash||'').toLowerCase()!==revision.toLowerCase()){conflicts++;if(!options.offline)try{cacheRepo().delete('go-main-identity',key);}catch{}continue;}
35
+ if(observation.stale){stale++;if(!warnings.some(w=>w.source==='go-proxy' && w.message.includes(`${module}@${version}`)))warnings.push({type:'source-unavailable',capability:'identity',source:'go-proxy',message:`Go module version evidence is stale for ${module}@${version}.`});}
36
+ if(!options.offline)try{cacheRepo().put('go-main-identity',key,info,{fetchedAt:observation.observedAt,stale:!!observation.stale,metadata:{source:'go-module-proxy',module,version}});}catch(error){warnings.push({type:'source-unavailable',capability:'identity',source:'go-proxy-cache',message:`Could not cache Go module version evidence: ${error.message}`});}
37
+ const occurrence=`${binaryPath}\0${module}\0${version}`;if(seen.has(occurrence))continue;seen.add(occurrence);
38
+ const dep=makeDepRecord({ecosystem:'go',name:module,version,manifestPath:binaryPath,provenance:'binary-module',scope:'runtime'});
39
+ dep.coordKey=`binary-module:${binaryPath}:${module}@${version}`;
40
+ dep.binaryEvidence={binaryPath,source:'go-vcs-and-module-proxy',binarySha256:binary.hashes.sha256,original:main[0],revision,modified:false,configDigest:metadata.configDigest,declaredSource:labels['org.opencontainers.image.source'],declaredVersion:version,proxyOrigin:{VCS:origin.VCS,URL:origin.URL,Ref:origin.Ref,Hash:origin.Hash},observedAt:observation.observedAt,stale:!!observation.stale,verification:'vcs-metadata-consistent',symbolReachability:'unknown'};
41
+ outputs.push(dep);
42
+ }
43
+ return {deps:outputs,warnings,coverage:{collector:'go-main-identity',execution:unavailable||conflicts||stale?'partial':candidates?'completed':'not-applicable',result:outputs.length?'identified':unavailable?'unavailable':conflicts?'conflicting-evidence':'no-match',count:outputs.length,candidates,conflicts,stale}};
44
+ }
45
+ module.exports={resolveGoMainIdentities};
@@ -0,0 +1,24 @@
1
+ 'use strict';
2
+ // Publisher advisories are separate from CVEProject/OSV. Only a verified Go
3
+ // main-module repository and exact typed package can produce a candidate.
4
+ const {createCacheRepository}=require('../cache-repository');
5
+ const {compareSemver}=require('../osv-db');
6
+ const GHSA=/^GHSA-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}$/i,CVE=/^CVE-\d{4}-\d{4,}$/i;
7
+ function repository(dep){const e=dep.binaryEvidence;if(e?.source!=='go-vcs-and-module-proxy'||e.verification!=='vcs-metadata-consistent')return null;try{const u=new URL(e.proxyOrigin.URL);if(u.protocol!=='https:'||u.hostname!=='github.com'||u.username||u.password||u.port||u.search||u.hash)return null;const m=/^\/([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+?)(?:\.git)?\/?$/.exec(u.pathname);if(!m)return null;const root=`github.com/${m[1]}/${m[2]}`;return dep.name===root||dep.name?.startsWith(root+'/')?`${m[1]}/${m[2]}`:null;}catch{return null;}}
8
+ function affected(version,range){if(typeof range!=='string'||range.length>500||compareSemver(version,version)==null)return null;const branches=range.split(/\s*\|\|\s*/);if(!branches.length||branches.length>20)return null;let unknown=false;for(const branch of branches){const parts=branch.split(',').map(x=>x.trim());if(!parts.length||parts.some(x=>!x))return null;let yes=true;for(const part of parts){const m=/^(<=|>=|<|>|=)?\s*(v?\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?)$/.exec(part);if(!m){unknown=true;yes=false;break;}const cmp=compareSemver(version,m[2]);if(cmp==null){unknown=true;yes=false;break;}const op=m[1]||'=';if(!({'<':cmp<0,'<=':cmp<=0,'>':cmp>0,'>=':cmp>=0,'=':cmp===0}[op]))yes=false;}if(yes)return true;}return unknown?null:false;}
9
+ async function assessGoPublisherAdvisories(deps,options={}){
10
+ const groups=new Map();for(const dep of deps instanceof Map?deps.values():deps||[]){if(dep.ecosystem!=='go'||!dep.version)continue;const repo=repository(dep);if(repo){if(!groups.has(repo))groups.set(repo,[]);groups.get(repo).push(dep);}}
11
+ const matches=[],coverage=[],warnings=[];if(!groups.size)return {matches,coverage,warnings};const cache=createCacheRepository(options.cacheDir||require('../cache-directory').getCacheDir()),providers=require('../providers');
12
+ for(const [repo,items] of groups){let snapshot,observedAt,stale=false,failed=null;let cached=null;try{cached=cache.get('publisher-go-advisories',repo);}catch{}
13
+ try{if(options.offline){if(!cached)throw Error('publisher advisory snapshot is not cached');snapshot=cached.value;observedAt=cached.fetchedAt;stale=cached.stale;}else{
14
+ const advisories=[];let end=false;observedAt=Date.now();const max=options.maxPublisherPages??10;if(!Number.isSafeInteger(max)||max<1||max>100)throw Error('invalid publisher page limit');
15
+ for(let page=1;page<=max;page++){const res=await providers.getResource('github','publisher-advisories',{repo,page,perPage:100},{fetcher:options.fetcher,signal:AbortSignal.timeout(options.publisherTimeoutMs??30000),headers:{Accept:'application/vnd.github+json','User-Agent':'vigievuln-publisher-advisories'}});if(!res.ok)throw Error(`GitHub publisher advisory HTTP ${res.status}`);let stamp=Date.now();if(providers.hasProxyRoute()){stamp=Date.parse(res.headers.get('x-fad-proxy-fetched-at')||'');if(!Number.isFinite(stamp)||stamp<=0||stamp>Date.now()+300000)throw Error('publisher advisory response has no trustworthy source timestamp');stale||=res.headers.get('x-fad-proxy')==='stale';}observedAt=Math.min(observedAt,stamp);const body=await res.json();if(!Array.isArray(body)||body.length>100)throw Error('invalid publisher advisory response');for(const a of body){if(!a||!GHSA.test(a.ghsa_id||'')||!Array.isArray(a.vulnerabilities))throw Error('invalid publisher advisory record');}advisories.push(...body);const hasNext=/rel\s*=\s*"?next"?/i.test(res.headers.get('link')||'');if(!hasNext&&body.length<100){end=true;break;}}
16
+ if(!end)throw Error('publisher advisory pagination limit reached');snapshot={advisories};cache.put('publisher-go-advisories',repo,snapshot,{fetchedAt:observedAt,stale,metadata:{source:'github-publisher',repo}});
17
+ }}catch(error){failed=error.message;if(!options.offline&&cached){snapshot=cached.value;observedAt=cached.fetchedAt;stale=true;try{cache.put('publisher-go-advisories',repo,snapshot,{fetchedAt:observedAt,stale:true,metadata:{source:'github-publisher',repo}})}catch{}}else snapshot=null;}
18
+ if(!snapshot||!Array.isArray(snapshot.advisories)||!Number.isFinite(observedAt)||observedAt<=0||observedAt>Date.now()+300000){warnings.push({type:'source-unavailable',source:'github-publisher',message:`Publisher advisory feed unavailable for ${repo}: ${failed||'invalid cached evidence'}`});coverage.push({collector:'github-publisher',execution:'partial',result:'indeterminate',repository:repo});continue;}
19
+ let unknown=0;for(const dep of items)for(const advisory of snapshot.advisories){if(!GHSA.test(advisory?.ghsa_id||'')||!Array.isArray(advisory.vulnerabilities)){unknown++;continue;}for(const v of advisory.vulnerabilities){if(String(v?.package?.ecosystem||'').toLowerCase()!=='go'||v.package.name!==dep.name)continue;const verdict=affected(dep.version,v.vulnerable_version_range);if(verdict===null){unknown++;continue;}if(!verdict)continue;const id=CVE.test(advisory.cve_id||'')?advisory.cve_id.toUpperCase():advisory.ghsa_id;const score=Number.isFinite(advisory.cvss?.score)&&advisory.cvss.score>=0&&advisory.cvss.score<=10?advisory.cvss.score:null;const severity=String(advisory.severity||'UNKNOWN').toUpperCase().replace('MODERATE','MEDIUM');matches.push({dep,source:'github-publisher',confidence:'exact',advisoryId:advisory.ghsa_id,cve:{id,aliases:id===advisory.ghsa_id?[]:[advisory.ghsa_id],description:typeof advisory.description==='string'?advisory.description:'',severity:['CRITICAL','HIGH','MEDIUM','LOW'].includes(severity)?severity:'UNKNOWN',score,fixVersion:typeof v.patched_versions==='string'&&/^v?\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(v.patched_versions)?v.patched_versions:null,published:advisory.published_at||null,modified:advisory.updated_at||null,advisorySource:advisory.html_url||null,publisherEvidence:{repository:repo,observedAt,stale,range:v.vulnerable_version_range,scope:'explicit-go-package'}}});}}
20
+ if(stale||failed)warnings.push({type:'source-unavailable',source:'github-publisher',message:`Publisher advisory evidence for ${repo} is stale${failed?`: ${failed}`:'.'}`});coverage.push({collector:'github-publisher',execution:stale||unknown?'partial':'completed',result:unknown?'indeterminate':'consulted',repository:repo,unknown,count:matches.filter(m=>items.includes(m.dep)).length,observedAt,fetchedAt:observedAt,scope:'explicit-go-package'});
21
+ }
22
+ return {matches,coverage,warnings};
23
+ }
24
+ module.exports={assessGoPublisherAdvisories,affected,repository};
@@ -0,0 +1,272 @@
1
+ 'use strict';
2
+
3
+ // Image archives are untrusted data. Nothing in them is executed, and no archive
4
+ // path is ever handed directly to a host filesystem API.
5
+ const fs = require('node:fs');
6
+ const fsp = fs.promises;
7
+ const path = require('node:path');
8
+ const os = require('node:os');
9
+ const crypto = require('node:crypto');
10
+ const zlib = require('node:zlib');
11
+ const { Transform } = require('node:stream');
12
+ const { pipeline } = require('node:stream/promises');
13
+ const tar = require('tar-stream');
14
+ const fzstd = require('fzstd');
15
+
16
+ const DEFAULT_LIMITS = Object.freeze({ maxBytes: 20 * 1024 ** 3, maxFileBytes: 8 * 1024 ** 3, maxEntries: 1000000, maxMetadataBytes: 16 * 1024 ** 2, maxDepth: 256 });
17
+ function limits(options) {
18
+ const result = { ...DEFAULT_LIMITS, ...(options.limits || {}) };
19
+ for (const [k, v] of Object.entries(result)) if (!Number.isSafeInteger(v) || v < 1) throw new Error(`Invalid artifact limit ${k}`);
20
+ return result;
21
+ }
22
+ function cleanName(value, lim) {
23
+ if (typeof value !== 'string' || value.includes('\0') || value.includes('\\') || value.startsWith('/') || /^[A-Za-z]:/.test(value)) throw new Error(`Unsafe archive path: ${value}`);
24
+ const parts = value.split('/').filter(p => p && p !== '.');
25
+ if (parts.includes('..') || parts.length > lim.maxDepth) throw new Error(`Unsafe archive path: ${value}`);
26
+ return parts.join('/');
27
+ }
28
+ function digest(buffer) { return crypto.createHash('sha256').update(buffer).digest('hex'); }
29
+ function digestVerifier(value, options) {
30
+ const match = /^([a-z][a-z0-9]*):([a-f0-9]+)$/.exec(String(value));
31
+ const algorithms = { sha256: () => crypto.createHash('sha256'), sha512: () => crypto.createHash('sha512'), ...(options.digestAlgorithms || {}) };
32
+ if (!match || !Object.hasOwn(algorithms, match[1]) || typeof algorithms[match[1]] !== 'function') throw new Error('Unsupported or invalid image digest');
33
+ const hash = algorithms[match[1]]();
34
+ if (!hash || typeof hash.update !== 'function' || typeof hash.digest !== 'function') throw new Error('Invalid digest adapter');
35
+ return { algorithm: match[1], expected: match[2], hash };
36
+ }
37
+ async function hashFile(file, algorithm = 'sha256') {
38
+ const h = crypto.createHash(algorithm); for await (const c of fs.createReadStream(file)) h.update(c); return h.digest('hex');
39
+ }
40
+ function layerDiffIds(config, count, state) {
41
+ const ids = config.rootfs?.diff_ids;
42
+ if (ids === undefined) { state.warnings.push('Image configuration does not declare layer diff_ids; uncompressed layer content is not bound to the configuration.'); return null; }
43
+ if (!Array.isArray(ids) || ids.length !== count || ids.some(id => typeof id !== 'string')) throw new Error('Image configuration layer diff_ids count or format is invalid');
44
+ if (config.rootfs?.type && config.rootfs.type !== 'layers') throw new Error('Unsupported image rootfs type');
45
+ return ids;
46
+ }
47
+ async function decompressor(file, options) {
48
+ const fd = await fsp.open(file, 'r'); const head = Buffer.alloc(4); await fd.read(head, 0, 4, 0); await fd.close();
49
+ if (head[0] === 0x1f && head[1] === 0x8b) return zlib.createGunzip();
50
+ if (head.readUInt32LE(0) === 0xfd2fb528) {
51
+ if (!options.preferPortableZstd && typeof zlib.createZstdDecompress === 'function') return zlib.createZstdDecompress();
52
+ let decoder; return new Transform({
53
+ construct(cb) { decoder = new fzstd.Decompress(chunk => this.push(Buffer.from(chunk))); cb(); },
54
+ transform(chunk, enc, cb) { try { decoder.push(chunk); cb(); } catch (e) { cb(e); } },
55
+ flush(cb) { try { decoder.push(new Uint8Array(0), true); cb(); } catch (e) { cb(e); } }
56
+ });
57
+ }
58
+ for (const codec of options.compressions || []) {
59
+ if (typeof codec.probe !== 'function' || typeof codec.create !== 'function') throw new Error('Invalid compression adapter');
60
+ if (await codec.probe(head, file)) return codec.create();
61
+ }
62
+ return new Transform({ transform(c, e, cb) { cb(null, c); } });
63
+ }
64
+ async function readTar(file, workspace, state, options, expectedDiffId) {
65
+ const verifier = expectedDiffId !== undefined ? digestVerifier(expectedDiffId, options) : null;
66
+ const entries = []; const extract = tar.extract(); let failure;
67
+ extract.on('entry', (header, stream, next) => {
68
+ (async () => {
69
+ const name = cleanName(header.name, state.limits);
70
+ if (Buffer.byteLength(header.name) + Buffer.byteLength(header.linkname || '') + Buffer.byteLength(JSON.stringify(header.pax || {})) > state.limits.maxMetadataBytes) throw new Error('Archive metadata size limit exceeded');
71
+ if (++state.entries > state.limits.maxEntries) throw new Error('Archive entry limit exceeded');
72
+ if (!Number.isSafeInteger(header.size) || header.size < 0 || header.size > state.limits.maxFileBytes) throw new Error(`Archive file size limit exceeded: ${name}`);
73
+ state.bytes += header.size;
74
+ if (state.bytes > state.limits.maxBytes) throw new Error('Archive decompressed size limit exceeded');
75
+ const entry = { name, type: header.type, linkname: header.linkname, size: header.size };
76
+ if (header.type === 'file' || header.type === 'contiguous-file') {
77
+ entry.file = path.join(workspace, `entry-${state.serial++}`);
78
+ await pipeline(stream, fs.createWriteStream(entry.file, { mode: 0o600, flags: 'wx' }));
79
+ } else { for await (const _ of stream) {} }
80
+ entries.push(entry); next();
81
+ })().catch(e => { failure = e; stream.destroy(); extract.destroy(e); });
82
+ });
83
+ const decoder = await decompressor(file, options);
84
+ // Count the full uncompressed stream, including padding and metadata headers.
85
+ let streamBytes = 0;
86
+ const counter = new Transform({ transform(c, e, cb) { if (verifier) verifier.hash.update(c); streamBytes += c.length; if (streamBytes > state.limits.maxBytes + state.limits.maxEntries * 2048) cb(new Error('Archive stream size limit exceeded')); else cb(null, c); } });
87
+ try { await pipeline(fs.createReadStream(file), decoder, counter, extract); } catch (e) { throw failure || e; }
88
+ if (verifier && verifier.hash.digest('hex') !== verifier.expected) throw new Error(`Image layer diff_id mismatch: ${expectedDiffId}`);
89
+ return entries;
90
+ }
91
+ async function safePath(root, name, lim, followFinal = false) {
92
+ let parts = cleanName(name, lim).split('/').filter(Boolean), resolved = [], hops = 0;
93
+ while (parts.length) {
94
+ const p = parts.shift();
95
+ if (p === '..') { if (!resolved.length) throw new Error('Link escapes artifact root'); resolved.pop(); continue; }
96
+ if (!p || p === '.') continue;
97
+ const candidate = path.join(root, ...resolved, p); let st;
98
+ try { st = await fsp.lstat(candidate); } catch (e) { if (e.code !== 'ENOENT' && e.code !== 'ENOTDIR') throw e; }
99
+ if (st && st.isSymbolicLink() && (parts.length || followFinal)) {
100
+ if (++hops > 40) throw new Error('Too many symbolic links');
101
+ const link = await fsp.readlink(candidate);
102
+ if (link.includes('\\') || link.includes('\0')) throw new Error('Unsafe symbolic link');
103
+ if (link.startsWith('/')) resolved = [];
104
+ parts = [...link.split('/'), ...parts]; continue;
105
+ }
106
+ resolved.push(p);
107
+ }
108
+ return path.join(root, ...resolved);
109
+ }
110
+ async function remove(p) { await fsp.rm(p, { recursive: true, force: true }); }
111
+ async function parents(root, name, lim) {
112
+ const parts = cleanName(name, lim).split('/').filter(Boolean); parts.pop(); let current = '';
113
+ for (const part of parts) {
114
+ current = current ? `${current}/${part}` : part;
115
+ const p = await safePath(root, current, lim, true); let st;
116
+ try { st = await fsp.lstat(p); } catch (e) { if (e.code !== 'ENOENT') throw e; }
117
+ if (st && !st.isDirectory()) await remove(p);
118
+ await fsp.mkdir(p, { recursive: true, mode: 0o700 });
119
+ }
120
+ }
121
+ async function applyLayer(root, entries, state, whiteouts) {
122
+ const lim = state.limits;
123
+ if (whiteouts) for (const e of entries) {
124
+ const base = path.posix.basename(e.name), dir = path.posix.dirname(e.name);
125
+ if (!base.startsWith('.wh.')) continue;
126
+ const parent = await safePath(root, dir === '.' ? '' : dir, lim, true);
127
+ if (base === '.wh..wh..opq') {
128
+ let names = []; try { names = await fsp.readdir(parent); } catch (err) { if (err.code !== 'ENOENT' && err.code !== 'ENOTDIR') throw err; }
129
+ for (const n of names) await remove(path.join(parent, n));
130
+ } else {
131
+ const name = base.slice(4); if (!name || name === '.' || name === '..') throw new Error('Invalid whiteout');
132
+ await remove(await safePath(root, path.posix.join(dir, name), lim));
133
+ }
134
+ }
135
+ const deferred = new Map();
136
+ for (const e of entries) {
137
+ if (!e.name || (whiteouts && path.posix.basename(e.name).startsWith('.wh.'))) continue;
138
+ if (!['file', 'contiguous-file', 'directory', 'symlink', 'link'].includes(e.type)) { state.warnings.push(`Unsupported archive entry type ${e.type}: ${e.name}`); continue; }
139
+ deferred.delete(e.name);
140
+ await parents(root, e.name, lim);
141
+ const p = await safePath(root, e.name, lim);
142
+ if (e.type === 'directory') {
143
+ let st; try { st = await fsp.lstat(p); } catch (err) { if (err.code !== 'ENOENT') throw err; }
144
+ if (st && !st.isDirectory()) await remove(p);
145
+ await fsp.mkdir(p, { recursive: true, mode: 0o700 });
146
+ } else if (e.type === 'link') {
147
+ // The last entry at a path wins, including when an earlier hardlink is deferred.
148
+ await remove(p);
149
+ const target = await safePath(root, cleanName(e.linkname, lim), lim, true);
150
+ let st; try { st = await fsp.stat(target); } catch (err) { if (err.code !== 'ENOENT') throw err; }
151
+ if (st) { if (!st.isFile()) throw new Error(`Invalid hardlink target: ${e.linkname}`); await fsp.link(target, p); }
152
+ else deferred.set(e.name, e);
153
+ } else {
154
+ await remove(p);
155
+ if (e.type === 'symlink') {
156
+ if (typeof e.linkname !== 'string' || e.linkname.includes('\0') || e.linkname.includes('\\')) throw new Error(`Unsafe link: ${e.name}`);
157
+ // Store absolute container links as relative host links; never point outside root.
158
+ const targetParts = e.linkname.startsWith('/') ? [] : e.name.split('/').slice(0, -1);
159
+ for (const segment of e.linkname.split('/')) { if (!segment || segment === '.') continue; if (segment === '..') { if (!targetParts.length) throw new Error(`Link escapes artifact root: ${e.name}`); targetParts.pop(); } else targetParts.push(segment); }
160
+ const target = path.join(root, ...targetParts); await fsp.symlink(path.relative(path.dirname(p), target) || '.', p);
161
+ } else await fsp.copyFile(e.file, p);
162
+ }
163
+ }
164
+ while (deferred.size) {
165
+ let progress = false;
166
+ for (const [name, e] of deferred) {
167
+ const target = await safePath(root, cleanName(e.linkname, lim), lim, true);
168
+ let st; try { st = await fsp.stat(target); } catch (err) { if (err.code === 'ENOENT') continue; throw err; }
169
+ if (!st.isFile()) throw new Error(`Invalid hardlink target: ${e.linkname}`);
170
+ await parents(root, name, lim);
171
+ const p = await safePath(root, name, lim); await remove(p); await fsp.link(target, p);
172
+ deferred.delete(name); progress = true;
173
+ }
174
+ if (!progress) throw new Error('Unresolved hardlink target');
175
+ }
176
+ }
177
+ async function readJson(file, state) {
178
+ const stat = await fsp.stat(file); if (stat.size > state.limits.maxMetadataBytes) throw new Error('Image metadata size limit exceeded');
179
+ try { return JSON.parse(await fsp.readFile(file, 'utf8')); } catch (e) { throw new Error(`Invalid image metadata: ${e.message}`); }
180
+ }
181
+ function entryMap(entries) {
182
+ const map = new Map(); for (const e of entries) { if (map.has(e.name)) throw new Error(`Duplicate archive entry: ${e.name}`); map.set(e.name, e); } return map;
183
+ }
184
+ function need(map, name, lim) { const e = map.get(cleanName(name, lim)); if (!e || !e.file) throw new Error(`Missing image archive entry: ${name}`); return e.file; }
185
+ async function openArtifact(input, options = {}) {
186
+ const lim = limits(options); const abs = path.resolve(input); const stat = await fsp.stat(abs);
187
+ for (const adapter of options.sources || []) {
188
+ if (!adapter || typeof adapter.probe !== 'function' || typeof adapter.open !== 'function') throw new Error('Invalid artifact source adapter');
189
+ if (await adapter.probe(abs, { stat, options })) {
190
+ const result = await adapter.open(abs, options);
191
+ if (!result || !Array.isArray(result.targets) || typeof result.cleanup !== 'function' || result.targets.some(t => !t || typeof t.id !== 'string' || typeof t.kind !== 'string' || typeof t.root !== 'string' || !t.metadata || typeof t.metadata !== 'object')) throw new Error('Invalid artifact source result');
192
+ return result;
193
+ }
194
+ }
195
+ const temp = await fsp.mkdtemp(path.join(options.tmpdir || os.tmpdir(), 'vigievuln-artifact-'));
196
+ const state = { limits: lim, entries: 0, bytes: 0, serial: 0, warnings: [] }; let cleaned = false;
197
+ const cleanup = async () => { if (!cleaned) { cleaned = true; await remove(temp); } };
198
+ try {
199
+ const targets = [];
200
+ const root = async () => { const dir = path.join(temp, `root-${targets.length}`); await fsp.mkdir(dir); return dir; };
201
+ const makeTarget = (r, kind, id, metadata) => targets.push({ id, kind, metadata: { ...metadata, warnings: [...state.warnings] }, root: r });
202
+ let map, layoutDir;
203
+ if (stat.isDirectory()) {
204
+ if (fs.existsSync(path.join(abs, 'oci-layout')) && fs.existsSync(path.join(abs, 'index.json'))) layoutDir = abs;
205
+ else { makeTarget(abs, 'rootfs', `rootfs:${abs}`, { format: 'directory', source: abs }); return { targets, cleanup }; }
206
+ } else if (stat.isFile()) {
207
+ const entries = await readTar(abs, temp, state, options);
208
+ const names = new Set(entries.map(e => e.name));
209
+ if (!names.has('manifest.json') && !(names.has('oci-layout') && names.has('index.json'))) {
210
+ const r = await root(); await applyLayer(r, entries, state, false);
211
+ makeTarget(r, 'rootfs', `rootfs:sha256:${await hashFile(abs)}`, { format: 'rootfs-archive', source: abs });
212
+ return { targets, cleanup };
213
+ }
214
+ map = entryMap(entries);
215
+ } else throw new Error('Artifact must be a directory or archive file');
216
+ const get = async name => {
217
+ name = cleanName(name, lim);
218
+ if (map) return need(map, name, lim);
219
+ const p = path.join(layoutDir, ...name.split('/')); const real = await fsp.realpath(p), base = await fsp.realpath(layoutDir);
220
+ if (real !== base && !real.startsWith(base + path.sep)) throw new Error(`OCI path escapes layout: ${name}`);
221
+ return real;
222
+ };
223
+ if (map && map.has('manifest.json')) {
224
+ const manifest = await readJson(await get('manifest.json'), state);
225
+ if (!Array.isArray(manifest) || !manifest.length) throw new Error('Invalid Docker image manifest');
226
+ for (const item of manifest) {
227
+ if (!item || !Array.isArray(item.Layers) || typeof item.Config !== 'string') throw new Error('Invalid Docker image manifest entry');
228
+ const warningStart = state.warnings.length;
229
+ const configFile = await get(item.Config), config = await readJson(configFile, state), configHash = await hashFile(configFile);
230
+ const diffIds = layerDiffIds(config, item.Layers.length, state), r = await root();
231
+ for (const [index, layer] of item.Layers.entries()) await applyLayer(r, await readTar(await get(layer), temp, state, options, diffIds?.[index]), state, true);
232
+ makeTarget(r, 'image', `docker:sha256:${configHash}`, { format: 'docker-save', source: abs, tags: item.RepoTags || [], platform: { os: config.os, architecture: config.architecture, variant: config.variant }, imageConfig: { labels: Object.fromEntries(['org.opencontainers.image.source','org.opencontainers.image.version','org.opencontainers.image.revision'].filter(k=>typeof config.config?.Labels?.[k]==='string').map(k=>[k,config.config.Labels[k]])) }, configDigest: `sha256:${configHash}`, layers: item.Layers });
233
+ targets[targets.length - 1].metadata.warnings = state.warnings.slice(warningStart);
234
+ }
235
+ } else {
236
+ const layout = await readJson(await get('oci-layout'), state); if (!layout.imageLayoutVersion) throw new Error('Invalid OCI layout');
237
+ const blob = async desc => {
238
+ if (!desc || typeof desc.digest !== 'string' || !Number.isSafeInteger(desc.size) || desc.size < 0) throw new Error('Invalid OCI descriptor');
239
+ const verifier = digestVerifier(desc.digest, options);
240
+ const file = await get(`blobs/${verifier.algorithm}/${verifier.expected}`), st = await fsp.stat(file);
241
+ if (st.size !== desc.size) throw new Error(`OCI descriptor integrity mismatch: ${desc.digest}`);
242
+ for await (const chunk of fs.createReadStream(file)) verifier.hash.update(chunk);
243
+ if (verifier.hash.digest('hex') !== verifier.expected) throw new Error(`OCI descriptor integrity mismatch: ${desc.digest}`);
244
+ return file;
245
+ };
246
+ const index = await readJson(await get('index.json'), state), globalWarnings = [];
247
+ const visit = async (desc, ancestry = [], platform) => {
248
+ if (desc.artifactType || desc.annotations?.['vnd.docker.reference.type'] === 'attestation-manifest' || (desc.platform?.os === 'unknown' && desc.platform?.architecture === 'unknown')) {
249
+ globalWarnings.push(`Skipped non-image artifact ${desc.digest || '(unknown digest)'}`); return;
250
+ }
251
+ if (ancestry.includes(desc.digest) || ancestry.length >= lim.maxDepth) throw new Error('OCI index cycle or depth limit');
252
+ const document = await readJson(await blob(desc), state);
253
+ if (Array.isArray(document.manifests)) { for (const child of document.manifests) await visit(child, [...ancestry, desc.digest], child.platform || platform); return; }
254
+ if (document.artifactType || document.subject || (document.config?.mediaType && !['application/vnd.oci.image.config.v1+json', 'application/vnd.docker.container.image.v1+json'].includes(document.config.mediaType))) {
255
+ globalWarnings.push(`Skipped non-image artifact ${desc.digest}`); return;
256
+ }
257
+ if (!document.config || !Array.isArray(document.layers)) throw new Error('Invalid OCI image manifest');
258
+ const warningStart = state.warnings.length;
259
+ const config = await readJson(await blob(document.config), state), diffIds = layerDiffIds(config, document.layers.length, state), r = await root();
260
+ for (const [index, layer] of document.layers.entries()) await applyLayer(r, await readTar(await blob(layer), temp, state, options, diffIds?.[index]), state, true);
261
+ makeTarget(r, 'image', `oci:${desc.digest}`, { format: 'oci-layout', source: abs, digest: desc.digest, tags: desc.annotations?.['org.opencontainers.image.ref.name'] ? [desc.annotations['org.opencontainers.image.ref.name']] : [], platform: platform || { os: config.os, architecture: config.architecture, variant: config.variant }, imageConfig: { labels: Object.fromEntries(['org.opencontainers.image.source','org.opencontainers.image.version','org.opencontainers.image.revision'].filter(k=>typeof config.config?.Labels?.[k]==='string').map(k=>[k,config.config.Labels[k]])) }, configDigest: document.config.digest, layers: document.layers.map(l => l.digest) });
262
+ targets[targets.length - 1].metadata.warnings = state.warnings.slice(warningStart);
263
+ };
264
+ if (!Array.isArray(index.manifests) || !index.manifests.length) throw new Error('Invalid OCI index');
265
+ for (const desc of index.manifests) await visit(desc, [], desc.platform);
266
+ if (!targets.length) throw new Error('OCI index contains no runnable image manifests');
267
+ for (const target of targets) target.metadata.warnings.push(...globalWarnings);
268
+ }
269
+ return { targets, cleanup };
270
+ } catch (e) { await cleanup(); throw e; }
271
+ }
272
+ module.exports = { openArtifact, DEFAULT_LIMITS };
@@ -0,0 +1,50 @@
1
+ 'use strict';
2
+
3
+ // A saved inventory is validated before this transformation. Filtering an old
4
+ // snapshot cannot reconstruct descriptors that its collectors never observed.
5
+ const { IMAGE_COMPONENT_SCOPE, isNpmPackageDescriptor, imageComponentRole } = require('./component-scope');
6
+ const SCOPE_REASON = 'image-inventory-scope-outdated';
7
+ const SCOPE_MESSAGE = 'The saved image inventory predates the current component scope or contains package metadata fragments. Reacquire the image to establish its current inventory.';
8
+
9
+ function pathsOf(value) {
10
+ return [value?.artifactPath, value?.manifestPath, value?.installEvidence?.path,
11
+ ...(Array.isArray(value?.manifestPaths) ? value.manifestPaths : [])]
12
+ .filter(p => typeof p === 'string');
13
+ }
14
+ function isFragmentPath(path) {
15
+ return /(?:^|[\\/])package\.json$/i.test(path) && !isNpmPackageDescriptor(path);
16
+ }
17
+ function isNpmFragment(dep) {
18
+ return dep?.ecosystem === 'npm' && dep?.installEvidence?.source === 'npm'
19
+ && pathsOf(dep).some(isFragmentPath);
20
+ }
21
+ function applyComponentScope(target, { checkPolicy = true } = {}) {
22
+ const result = structuredClone(target);
23
+ // Publisher SBOM contents are explicit evidence, not filesystem descriptors.
24
+ if (result.kind === 'sbom') return result;
25
+ let filtered = false;
26
+ result.deps = (result.deps || []).filter(dep => {
27
+ if (isNpmFragment(dep)) { filtered = true; return false; }
28
+ dep.imageRole = imageComponentRole(dep);
29
+ dep.scope = dep.imageRole === 'transitive' ? 'transitive' : 'runtime';
30
+ return true;
31
+ });
32
+ result.warnings = (result.warnings || []).filter(w => {
33
+ if (w?.reason === 'installed-metadata-error' && pathsOf(w).some(isFragmentPath)) { filtered = true; return false; }
34
+ return true;
35
+ });
36
+ result.coverage = result.coverage || [];
37
+ result.componentCount = result.deps.length;
38
+ if (checkPolicy && (result.metadata?.componentScope !== IMAGE_COMPONENT_SCOPE || filtered)) {
39
+ const existing = result.coverage.find(c => c.collector === 'installed-applications');
40
+ if (existing) {
41
+ if (!['failed', 'partial'].includes(existing.execution)) existing.execution = 'partial';
42
+ existing.result = 'indeterminate';
43
+ existing.reason = SCOPE_MESSAGE;
44
+ } else result.coverage.push({artifactTargetId:result.id,capability:'inventory',collector:'installed-applications',execution:'partial',result:'indeterminate',reason:SCOPE_MESSAGE});
45
+ if (!result.warnings.some(w => w?.reason === SCOPE_REASON))
46
+ result.warnings.push({type:'dependency-coverage',capability:'inventory',reason:SCOPE_REASON,message:SCOPE_MESSAGE});
47
+ }
48
+ return result;
49
+ }
50
+ module.exports = { applyComponentScope, SCOPE_REASON, SCOPE_MESSAGE };
@@ -0,0 +1,12 @@
1
+ 'use strict';
2
+ const adapters=Object.freeze([{id:'github-go-publisher',operatorRegion:'us',assess:(deps,options)=>require('./go-publisher-advisories').assessGoPublisherAdvisories(deps,options)}]);
3
+ async function assessPublisherAdvisories(deps,options={}){
4
+ if(options.publisherAdvisories===false)return {matches:[],warnings:[],coverage:[{collector:'publisher-advisories',execution:'not-applicable',result:'not-consulted',expected:false,reason:'Publisher advisory source excluded by configuration.'}]};
5
+ const selected=options.publisherAdvisoryAdapters||adapters;if(!Array.isArray(selected)||selected.some(a=>!a||typeof a.id!=='string'||typeof a.assess!=='function'))throw Error('Invalid publisher advisory adapter registry');
6
+ const result={matches:[],warnings:[],coverage:[]},region=options.publisherSourceRegion||options.sourceProfile;
7
+ for(const adapter of selected){
8
+ if(['eu','us'].includes(region)&&adapter.operatorRegion!==region){result.coverage.push({collector:adapter.id,execution:'not-applicable',result:'not-consulted',expected:false,reason:'Source operator is outside the selected region or its region is not established.'});continue;}
9
+ try{const response=await adapter.assess(deps,options);for(const name of Object.keys(result)){if(!Array.isArray(response?.[name]))throw Error(`Invalid publisher ${name}`);result[name].push(...response[name]);}}catch(error){result.warnings.push({type:'source-unavailable',source:adapter.id,message:`${adapter.id}: ${error.message}`});result.coverage.push({collector:adapter.id,execution:'failed',result:'indeterminate',reason:error.message});}
10
+ }return result;
11
+ }
12
+ module.exports={adapters,assessPublisherAdvisories};
@@ -0,0 +1,48 @@
1
+ 'use strict';
2
+
3
+ const {renderTime}=require('../report-time');
4
+ const esc=value=>String(value??'').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;').replace(/'/g,'&#39;');
5
+ const tr=locale=>(en,fr)=>locale==='fr'?fr:en;
6
+ function observation(artifact) {
7
+ const value=artifact?.imageUpdate;
8
+ return value && ['available','current'].includes(value.status) && value.targetTag && value.targetReference ? value : null;
9
+ }
10
+
11
+ // Registry observations identify a release candidate, not a vulnerability verdict.
12
+ // The row names the action; the evidence panel explains its limits and provenance.
13
+ function renderImageCveAction(match,artifact,locale='en') {
14
+ const t=tr(locale),update=observation(artifact);
15
+ let action;
16
+ if(update?.status==='available') {
17
+ action=`<strong>${update.reasonCode==='rebuilt-tag'?t('Update rebuilt image','Actualiser l’image reconstruite'):t('Update image','Mettre à jour l’image')}</strong><br><code>${esc(update.targetReference)}</code>`;
18
+ } else if(update?.status==='current') {
19
+ action=`<strong>${t('Change branch or rebuild the image','Changer de branche ou reconstruire l’image')}</strong>`;
20
+ } else {
21
+ action=`<strong>${t('Update or rebuild the image','Mettre à jour ou reconstruire l’image')}</strong>`;
22
+ }
23
+ const fix=match.cve?.fixVersion||match.fixVersion;
24
+ if(fix) {
25
+ action+=`<small>${t('Component:','Composant :')} <code>${esc(fix)}</code></small>`;
26
+ }
27
+ return action;
28
+ }
29
+
30
+ function renderImageUpdateSummary(artifact,locale='en') {
31
+ const t=tr(locale),update=observation(artifact),raw=artifact?.imageUpdate;
32
+ let text;
33
+ if(update) {
34
+ text=`${t('Latest image observed in branch','Dernière image observée de la branche')} <code>${esc(update.branch)}</code> : <code>${esc(update.targetReference)}</code>. `;
35
+ if(update.status==='current')text+=t('No newer comparable version was observed. Use a maintained branch or rebuild with updated packages and binaries.','Aucune version comparable plus récente n’a été observée. Choisissez une branche maintenue ou reconstruisez avec les paquets et binaires mis à jour.')+' ';
36
+ if(update.reasonCode==='rebuilt-tag')text+=t('The tag is unchanged but its platform manifest digest differs from the scanned image.','Le tag est inchangé, mais l’empreinte de son manifeste de plateforme diffère de l’image analysée.')+' ';
37
+ text+=t('The registry tag does not establish that the vulnerabilities are fixed; scan the replacement image.','Le tag du registre ne prouve pas que les vulnérabilités sont corrigées ; analysez l’image de remplacement.');
38
+ if(update.observedAt)text+=`<br>${t('Registry consulted on','Registre consulté le')} ${renderTime(update.observedAt,locale)}.`;
39
+ if(update.targetDigest)text+=`<br>${t('Candidate manifest digest','Empreinte du manifeste proposé')} : <code>${esc(update.targetDigest)}</code>`;
40
+ if(update.platformDigest && update.platformDigest!==update.targetDigest)text+=`<br>${t('Candidate platform manifest digest','Empreinte du manifeste de plateforme proposé')} : <code>${esc(update.platformDigest)}</code>`;
41
+ } else {
42
+ text=t('No replacement tag or digest has been verified. Update the publisher image, or update the affected packages and binaries and rebuild the image.','Aucun tag ni empreinte de remplacement n’a été vérifié. Mettez à jour l’image de l’éditeur, ou mettez à jour les paquets et binaires concernés puis reconstruisez l’image.');
43
+ if(raw?.reason && raw.reasonCode!=='no-reference')text+=`<br>${esc(raw.reason)}`;
44
+ }
45
+ return `<div class="image-update-evidence">${text}</div>`;
46
+ }
47
+
48
+ module.exports={renderImageCveAction,renderImageUpdateSummary};
@@ -0,0 +1,26 @@
1
+ 'use strict';
2
+
3
+ // Presentation only. Acquisition snapshots retain the full inventory for
4
+ // advisory matching and offline replay.
5
+ const componentIdentity = dep => JSON.stringify([
6
+ dep.packageType || dep.ecosystem || '', dep.namespace || '',
7
+ dep.name || dep.artifactId || dep.coord || '', dep.version || '', dep.architecture || '',
8
+ ]);
9
+ const needsAdvisory = dep => dep.ecosystem === 'system' || dep.ecosystem === 'binary' ||
10
+ dep.provenance === 'binary' || dep.provenance === 'embedded' || dep.osPackageOwners?.length > 0;
11
+ function reportedComponents(artifact, matches = []) {
12
+ const affected = new Set(matches.filter(match =>
13
+ (match.dep?.artifactTargetId || match.artifactTargetId) === artifact.id &&
14
+ !match.cpeFiltered && (match.cve?.id || match.advisoryId)
15
+ ).map(match => componentIdentity(match.dep || {})));
16
+ return (artifact.components || []).filter(dep => (['direct','transitive'].includes(dep.imageRole) && !['system','binary'].includes(dep.ecosystem)) || !needsAdvisory(dep) || affected.has(componentIdentity(dep)));
17
+ }
18
+ function reportArtifacts(artifacts, matches) {
19
+ return artifacts.map(artifact => {
20
+ if (!Array.isArray(artifact.components)) return artifact;
21
+ const components = reportedComponents(artifact, matches);
22
+ return {...artifact, componentCount:artifact.componentCount ?? artifact.components.length, components,
23
+ componentDetailsFiltered:!!artifact.componentDetailsFiltered || components.length !== artifact.components.length};
24
+ });
25
+ }
26
+ module.exports = {componentIdentity, reportedComponents, reportArtifacts};