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,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,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 => !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};
@@ -0,0 +1,191 @@
1
+ 'use strict';
2
+ const crypto = require('node:crypto');
3
+ const {renderTime}=require('../report-time');
4
+ const { projectImageCves } = require('./cve-view');
5
+ const esc = value => String(value ?? '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#39;');
6
+ const tr = locale => (en, fr) => locale === 'fr' ? fr : en;
7
+ const artifactAnchor = id => 'image-' + crypto.createHash('sha256').update(String(id)).digest('hex').slice(0, 12);
8
+ const title = a => a?.imageUpdate?.reference || a?.metadata?.reference || a?.metadata?.acquisition?.reference || a?.metadata?.source || a?.id || '';
9
+ const location = r => `${r?.path || ''}${r?.line != null ? ':' + r.line : ''}`;
10
+ const platform = value => typeof value === 'string' ? value : [value?.os, value?.architecture, value?.variant].filter(Boolean).join('/');
11
+ function artifactTitle(artifact, artifacts = []) {
12
+ const label=title(artifact);
13
+ // Always expose content identity, including archive names reused across scans.
14
+ const meta=artifact.metadata||{}, p=platform(meta.platform), digest=meta.digest||meta.acquisition?.resolvedDigest||meta.configDigest||'';
15
+ const short=digest ? String(digest).slice(0,19) : String(artifact.id||'').slice(-12);
16
+ return [p,short].filter(Boolean).join(' · ')+' — '+label;
17
+ }
18
+ const visible = matches => (matches || []).filter(m => !m.suppressed && !m.cpeFiltered);
19
+ const linkedCves = cve => [...new Set([cve?.id,...(cve?.aliases||[]),...(cve?.upstream||[])].filter(id=>typeof id==='string' && /^CVE-\d{4}-\d{4,}$/i.test(id)).map(id=>id.toUpperCase()))];
20
+ // Native sources retain their own public record route; a GCVE is not an OSV advisory.
21
+ const advisoryUrl = id => `https://www.vigievuln.fr/${/^CVE-\d{4}-\d{4,}$/i.test(id)?'cve':/^GCVE-[0-9]+-/i.test(id)?'advisory/gcve':'advisory/osv'}/${encodeURIComponent(id)}`;
22
+ const safeUrl = value => typeof value==='string' && /^https?:\/\/[^\s<>"']+$/i.test(value) ? value : null;
23
+ function artifactGroups(projectInfo = {}, matches = []) {
24
+ const groups = new Map();
25
+ for (const artifact of projectInfo.artifacts || []) if (artifact?.id && !groups.has(artifact.id)) groups.set(artifact.id, {artifact, matches: []});
26
+ for (const match of matches || []) {
27
+ const id = match?.dep?.artifactTargetId || match?.artifactTargetId;
28
+ if (!id) continue;
29
+ if (!groups.has(id)) groups.set(id, {artifact: {id, metadata: {}, coverage: [], components: []}, matches: []});
30
+ groups.get(id).matches.push(match);
31
+ }
32
+ return [...groups.values()];
33
+ }
34
+ function definitionText(artifact, locale) {
35
+ const t=tr(locale),definitions=artifact.metadata?.definitions || [],discovery=artifact.metadata?.definitionDiscovery || {};
36
+ if (definitions.length) return definitions.map(d => `<code>${esc(location(d))}</code>${d.role ? ` (${esc(d.role)})` : ''}${d.declared ? ` — <code>${esc(d.declared)}</code>` : ''}${d.binding==='registry-reference-resolution' ? ` — ${esc(t('registry reference resolved to the scanned digest','référence de registre résolue vers l’empreinte analysée'))}` : ''}`).join('<br>');
37
+ if (discovery.status === 'not-supplied' || !discovery.status) return esc(t('Source definitions not provided.', 'Définitions source non fournies.'));
38
+ if (discovery.status === 'no-match' || discovery.status === 'none' || discovery.status === 'completed') return esc(t('No source definition was matched to this image.', 'Aucune définition source associée à cette image.'));
39
+ return esc(t('Source definition match is unavailable.', 'Association aux définitions source indisponible.'));
40
+ }
41
+ function renderImageSummary(a, locale) {
42
+ const t=tr(locale),meta=a.metadata||{},acq=meta.acquisition||{};
43
+ const cached=a.evidence==='cached-inventory',origin=cached?a.originalEvidence:a.evidence;
44
+ const collectors=(a.coverage||[]).filter(c=>c.capability==='inventory' && ['completed','complete'].includes(c.execution||c.status)).map(c=>c.collector).filter(Boolean);
45
+ const details=[...new Set(collectors)].map(c=>({apk:'APK',dpkg:'dpkg',rpm:'RPM','installed-applications':t('installed application metadata','métadonnées des applications installées'),'native-binaries':t('native binary metadata','métadonnées des binaires natifs')}[c]||c));
46
+ const evidence=origin==='sbom'?t('SBOM inventory; signature not verified','Inventaire issu du SBOM ; signature non vérifiée'):origin==='content-inventory'?t('Inventory extracted from image filesystem','Inventaire extrait du système de fichiers de l’image')+(details.length?` (${details.join(', ')})`:''):t('Inventory origin unavailable','Origine de l’inventaire indisponible');
47
+ const evidenceText=cached?evidence+' — '+(origin==='content-inventory'?t('saved inventory reused without rereading the image','inventaire enregistré réutilisé sans relire l’image'):t('saved inventory reused','inventaire enregistré réutilisé')):evidence;
48
+ const rows=[
49
+ [acq.kind?t('Acquisition','Acquisition'):t('Original format','Format d’origine'),`${esc(acq.kind||meta.format||a.kind||'—')} · <code>${esc(acq.reference||acq.source||meta.reference||meta.source||'—')}</code>`],
50
+ ...(meta.registryReference?.reference && a.imageUpdate?.reference===meta.registryReference.reference ? [[t('Associated registry reference','Référence de registre associée'),`<code>${esc(a.imageUpdate.reference)}</code> — ${t('linked by platform manifest digest','liée par l’empreinte du manifeste de plateforme')}${meta.registryReference.verifiedAt?` · ${renderTime(meta.registryReference.verifiedAt,locale)}`:''}`]] : []),
51
+ [t('Current manifest digest','Empreinte du manifeste actuel'),`<code>${esc(meta.digest||acq.resolvedDigest||meta.resolvedDigest||'—')}</code>`],
52
+ ...(meta.configDigest?[[t('Configuration digest','Empreinte de configuration'),`<code>${esc(meta.configDigest)}</code>`]]:[]),
53
+ [t('Platform','Plateforme'),esc(platform(meta.platform)||'—')],
54
+ [t('Distribution','Distribution'),esc([a.distribution?.id,a.distribution?.versionId].filter(Boolean).join(' ')||'—')],
55
+ [t('Evidence','Preuve'),esc(evidenceText)],
56
+ [t('Inventory date','Date de l’inventaire'),renderTime(a.inventoryAt||'—',locale)],
57
+ ...(a.imageUpdate ? [[t('Image update','Mise à jour de l’image'),require('./remediation-report').renderImageUpdateSummary(a,locale)]] : []),
58
+ [t('Source definitions','Définitions source'),definitionText(a,locale)]
59
+ ];
60
+ return `<table class="image-summary"><tbody>${rows.map(([label,value])=>`<tr><th scope="row">${label}</th><td>${value}</td></tr>`).join('')}</tbody></table>`;
61
+ }
62
+ const {componentIdentity,reportedComponents} = require('./report-inventory');
63
+ function renderAdvisoryObservations(artifact,locale){
64
+ const t=tr(locale),groups=new Map();
65
+ for(const item of artifact.advisoryObservations||[]){
66
+ const id=item.id||item.cveId,name=item.sourceName||item.dep?.sourceName||item.dep?.name,version=item.sourceVersion||item.dep?.sourceVersion||item.dep?.version;
67
+ const key=JSON.stringify([item.source||'',id,name,version,item.status]);
68
+ if(!groups.has(key))groups.set(key,{...item,id,name,version,packages:new Set()});
69
+ const group=groups.get(key);if(item.evidence?.conflictingFinding)group.evidence={...group.evidence,conflictingFinding:true};for(const pkg of item.packages||[item.dep?.name])if(pkg)group.packages.add(pkg);
70
+ }
71
+ if(!groups.size)return '';
72
+ const rows=[...groups.values()].map(item=>{
73
+ const url=safeUrl(item.sourceUrl||item.evidence?.advisoryURL)||(/^CVE-\d{4}-\d{4,}$/.test(item.id||'')?`https://www.vigievuln.fr/cve/${encodeURIComponent(item.id)}`:null);
74
+ const status=item.status==='possible'?t('Possibly affected','Potentiellement affecté'):item.status==='not-affected'?t('Not affected according to source','Non affecté selon la source'):item.status==='fixed'?t('Fixed according to source','Corrigé selon la source'):t('Not established','Non établi');
75
+ const evidence=item.evidence||{},comparison=evidence.comparison;
76
+ const reason=item.source==='freexian-tracker' && evidence.releaseStatus ? t('The tracker release status applies to a different archive source version; applicability to the installed version is undetermined.','Le statut du suivi concerne une autre version source de l’archive ; son applicabilité à la version installée reste indéterminée.') : evidence.versionRange ? t('Upstream version range cannot be evaluated.','La plage de versions amont ne peut pas être évaluée.') : evidence.statuses ? t('No usable tracker package/version verdict.','Le suivi ne fournit pas de verdict exploitable pour ce paquet et cette version.') : evidence.origin ? t('Package vendor provenance does not establish Debian origin.','La provenance du paquet ne permet pas d’établir une origine Debian.') : item.reason==='release status lacks an installed-version bound'?t('No version bound for this release.','Pas de borne de version pour cette distribution.'):item.reason==='package has explicitly different vendor provenance'?t('Package supplied by another vendor.','Paquet fourni par un autre éditeur.'):item.reason==='unrecognized or conflicting release status'?t('Unrecognised or conflicting distribution status.','Statut de distribution non reconnu ou contradictoire.'):item.reason||'';
77
+ const states=(item.states||[]).map(s=>`${s.repo}: ${s.fixed?t('fixed','corrigé'):t('possibly vulnerable','potentiellement vulnérable')}`).join('; ');
78
+ let detail=esc(states||reason||t('The source does not establish the status of this exact version.','La source ne permet pas de conclure pour cette version exacte.'));
79
+ if(comparison && evidence.releaseApplicability==='unknown'){
80
+ const rule=comparison.operator==='<'?`${esc(comparison.installedVersion)} &lt; ${esc(comparison.threshold)}`:t('No fixed version in the current source package rule.','Aucune version corrective dans la règle actuelle du paquet source.');
81
+ const context=(evidence.contextReleases||[]).map(c=>`${esc((c.releases||[]).join(', '))}: ${esc(c.note||'')}`).join('<br>');
82
+ detail=`${t('Current source package rule','Règle actuelle du paquet source')} : <code>${rule}</code><br>${evidence.reconciliation?t('This rule alone does not establish applicability to the unsupported release.','Cette règle seule ne détermine pas l’applicabilité à la distribution hors support.'):t('Applicability to this unsupported distribution is not established.','Applicabilité à cette distribution hors support non établie.')}${context?`<br><small>${t('Other releases marked not affected','Autres distributions déclarées non affectées')} : ${context}</small>`:''}`;
83
+ }
84
+ if(evidence.reconciliation?.assessments?.length){const notes=evidence.reconciliation.assessments.map(a=>{const proof=a.evidence?.releaseEvidence,link=safeUrl(proof?.sourceURL||a.evidence?.sourceURL);const label=esc(a.source||'');const ref=link?`<a href="${esc(link)}">${label}</a>`:label;const row=proof?.row;return row?`${ref} — ${esc(row.release)}: ${esc(row.fixedVersion)}`:ref;}).join(', ');detail+=`<br><small>${t('Release assessment','Évaluation de la distribution')} : ${notes}</small>`;}
85
+ if(evidence.conflictingFinding)detail+=`<br><strong>${t('Another source reports this package as affected; the finding remains visible.','Une autre source signale ce paquet comme affecté ; le résultat reste visible.')}</strong>`;
86
+ return `<tr><td>${url?`<a href="${esc(url)}">${esc(item.id)}</a>`:esc(item.id)}</td><td><code>${esc(item.name)}@${esc(item.version)}</code><br><small>${esc([...item.packages].join(', '))}</small></td><td>${status}</td><td>${detail}${item.observedAt?`<br>${renderTime(item.observedAt,locale)}`:''}</td></tr>`;
87
+ }).join('');
88
+ return `<details class="report-subsection"><summary><h4>${t('Additional advisory evidence','Vérifications complémentaires')} (${groups.size})</h4></summary><p>${t('These source observations are excluded from confirmed finding counts and remediation claims; check their individual evidence and any conflicting findings.','Ces observations des sources sont exclues des compteurs de vulnérabilités et des conclusions de correction ; consultez leurs preuves et les éventuels résultats contradictoires.')}</p><table><thead><tr><th>CVE</th><th>${t('Source package / installed packages','Paquet source / paquets installés')}</th><th>${t('Status','Statut')}</th><th>${t('Evidence','Preuve')}</th></tr></thead><tbody>${rows}</tbody></table></details>`;
89
+ }
90
+ function renderSeverityCounts(severity, locale) {
91
+ const t=tr(locale),labels={critical:t('Critical','Critiques'),high:t('High','Élevées'),medium:t('Medium','Moyennes'),low:t('Low','Faibles'),unknown:t('Unknown','Inconnues')};
92
+ return Object.entries(severity).filter(([,count])=>count>0).map(([band,count])=>`<span class="image-severity ${band}">${labels[band]} <strong>${count}</strong></span>`).join(' ') || '—';
93
+ }
94
+ function renderImageCves(projectInfo = {}, matches = [], locale = 'en', helpers = {}) {
95
+ const t=tr(locale),render=helpers.renderCveTable,minor=helpers.minorSection,groups=artifactGroups(projectInfo,matches),artifacts=groups.map(g=>g.artifact);
96
+ const explanation=`<p>${t('The CVE section shows linked CVE identifiers per image. Distribution advisories without linked CVEs remain in the image inventory section.','La section CVE présente les identifiants CVE liés à chaque image. Les avis de distribution sans CVE liée restent dans la section d’inventaire de l’image.')}</p>`;
97
+ const noFindings=t('No findings recorded; consult scan coverage before drawing conclusions.', 'Aucun résultat enregistré ; consultez la couverture de l’analyse avant de conclure.');
98
+ if(!groups.length)return explanation+`<p>${noFindings} ${t('Reference-only images have not been scanned.','Les images uniquement déclarées n’ont pas été analysées.')}</p>`;
99
+ return explanation+groups.map(({artifact,matches:rows})=>{
100
+ const anchor=artifactAnchor(artifact.id),heading=`${esc(artifactTitle(artifact,artifacts))} (${rows.length})`;
101
+ const detail=rows.length && typeof render==='function' ? render(rows,{image:artifact}) : `<p>${noFindings}</p>`;
102
+ const content=`${renderImageSummary(artifact,locale)}<p class="image-section-nav"><a class="report-section-link" href="#${anchor}">${t('Image inventory and coverage','Inventaire et couverture de l’image')}<span aria-hidden="true">→</span></a></p>${detail}`;
103
+ return typeof minor==='function' ? minor(heading,content,{id:anchor+'-cves'}) : `<details class="report-subsection" open id="${anchor}-cves"><summary><h3>${heading}</h3></summary><div>${content}</div></details>`;
104
+ }).join('');
105
+ }
106
+ function stats(group) {
107
+ const matches=visible(group.matches),components=new Set(),advisories=new Set(),cves=new Set(),severity={critical:0,high:0,medium:0,low:0,unknown:0},updates=new Map();
108
+ for(const m of matches) {
109
+ const dep=m.dep||{},key=dep.coordKey || [dep.ecosystem,dep.namespace,dep.name,dep.version,dep.architecture,dep.manifestPaths?.[0]].join(':');
110
+ components.add(key);advisories.add(m.advisoryId || m.cve?.id || '');
111
+ for(const id of linkedCves(m.cve))cves.add(id);
112
+
113
+ const fix=m.cve?.fixVersion || m.fixVersion;if(fix){const k=`${key}\0${fix}`, item=updates.get(k)||{dep,fix,advisories:new Set()};const advisory=m.advisoryId||m.cve?.id;if(advisory)item.advisories.add(advisory);updates.set(k,item);}
114
+ }
115
+ const cveRows=projectImageCves(matches);
116
+ for(const m of cveRows){const band=String(m.cve?.severity||'unknown').toLowerCase();severity[Object.hasOwn(severity,band)?band:'unknown']++;}
117
+ advisories.delete('');return {cveFindings:cveRows.length,findings:matches.length,components:components.size,advisories:advisories.size,cves:cves.size,severity,updates:[...updates.values()]};
118
+ }
119
+ function renderReferences(projectInfo, artifacts, locale) {
120
+ const t=tr(locale),all=projectInfo.imageReferences?.length ? projectInfo.imageReferences : artifacts.flatMap(a=>a.metadata?.declarations || []),groups=new Map();
121
+ for(const r of all){
122
+ const label=r.reference||r.declared||'',key=JSON.stringify([label,r.platform||null]);
123
+ if(!groups.has(key))groups.set(key,{label,platform:platform(r.platform),refs:[]});groups.get(key).refs.push(r);
124
+ }
125
+ if(!groups.size)return '';
126
+ const rows=[...groups.values()].map(group=>{
127
+ const locations=[...new Set(group.refs.map(location).filter(Boolean))],roles=[...new Set(group.refs.map(r=>r.role).filter(Boolean))],details=[];
128
+ for(const r of group.refs){
129
+ const ids=[...new Set([...(r.boundArtifactIds||[]),...(r.imageScan?.artifactIds||[])])].filter(id=>artifacts.some(a=>a.id===id));
130
+ const status=r.imageScan?.status||r.scanStatus,reason=r.imageScan?.reasonCode||r.blockReason||r.classification;
131
+ let value;
132
+ if(status==='assessment-failed')value=esc(t('Inventory acquired; advisory assessment failed','Inventaire obtenu ; analyse des avis échouée'))+(r.imageScan?.message?`: ${esc(r.imageScan.message)}`:'');
133
+ else if(ids.length){const text=status==='scanned'?t('Scanned image inventory','Inventaire de l’image analysée'):t('Image inventory acquired','Inventaire de l’image obtenu');value=ids.map(id=>`<a href="#${artifactAnchor(id)}">${esc(text)}</a>`).join(', ');}
134
+ else if(status==='failed')value=esc(t('Image acquisition failed','Récupération de l’image échouée'))+(r.imageScan?.message||r.scanReason?`: ${esc(r.imageScan?.message||r.scanReason)}`:'');
135
+ else if(reason==='local-build'||r.localBuild)value=esc(t('Local build; image cannot be acquired from a registry from this declaration.','Construction locale ; cette déclaration ne permet pas de récupérer l’image depuis un registre.'));
136
+ else if(reason==='unresolved'||reason==='unresolved-variables'||r.unresolved?.length)value=esc(t('Unresolved variable','Variable non résolue'))+(r.unresolved?.length?`: ${esc(r.unresolved.join(', '))}`:'');
137
+ else if(status==='not-scannable'||r.scanEligible===false)value=esc(t('Image cannot be scanned from this declaration','Cette déclaration ne permet pas d’analyser l’image'))+(reason?`: ${esc(reason)}`:'');
138
+ else value=esc(t('Image scan status unavailable.','État de l’analyse de l’image indisponible.'));
139
+ if(!details.includes(value))details.push(value);
140
+ }
141
+ return `<tr><td>${locations.length?locations.map(x=>`<code>${esc(x)}</code>`).join('<br>'):'—'}</td><td><code>${esc(group.label)}</code></td><td>${esc(group.platform||'—')}</td><td>${esc(roles.join(', ')||'—')}</td><td>${details.join('<br>')}</td></tr>`;
142
+ }).join('');
143
+ return `<details class="report-subsection" open><summary><h3>${t('Declared image references','Références d’images déclarées')}</h3></summary><table><thead><tr><th>${t('File','Fichier')}</th><th>${t('Declaration','Déclaration')}</th><th>${t('Platform','Plateforme')}</th><th>${t('Role','Rôle')}</th><th>${t('Status','État')}</th></tr></thead><tbody>${rows}</tbody></table></details>`;
144
+ }
145
+ function renderArtifactEvidence(projectInfo = {}, locale = 'en', matches = []) {
146
+ const t=tr(locale),groups=artifactGroups(projectInfo,matches),artifacts=groups.map(g=>g.artifact);
147
+ if(!groups.length && !(projectInfo.imageReferences||[]).length)return '';
148
+ const referenceNotice=projectInfo.provenance?.mode==='offline' && projectInfo.imageReferences?.length ? `<p>${t('Air-gap mode: Dockerfiles remain in the isolated environment and are not transferred; images they define cannot therefore be built during online preparation.','Mode air gap : les Dockerfiles restent dans l’environnement isolé et ne sont pas transférés ; les images qu’ils définissent ne peuvent donc pas être construites pendant la préparation en ligne.')}</p>`:'';
149
+ const overviewRows=groups.map(group=>{const a=group.artifact,s=stats(group),sev=Object.entries(s.severity).filter(([,v])=>v>0).map(([k,v])=>`${esc(k)}: ${v}`).join(' · ');return `<tr><td><a href="#${artifactAnchor(a.id)}">${esc(artifactTitle(a,artifacts))}</a></td><td>${Number(a.componentCount??a.components?.length??0)}</td><td>${s.components}</td><td>${s.findings}</td><td>${s.cveFindings}</td><td>${s.advisories}</td><td>${s.cves}</td><td>${sev}</td><td>${s.updates.length}</td></tr>`;}).join('');
150
+ const overview=overviewRows?`<table><thead><tr><th>${t('Image','Image')}</th><th>${t('Components','Composants')}</th><th>${t('Affected packages','Paquets affectés')}</th><th>${t('Raw findings','Résultats bruts')}</th><th>${t('CVE rows','Lignes CVE')}</th><th>${t('Advisories','Avis')}</th><th>${t('Unique CVEs','CVE distinctes')}</th><th>${t('CVE row severities','Sévérités des lignes CVE')}</th><th>${t('Update candidates','Corrections proposées')}</th></tr></thead><tbody>${overviewRows}</tbody></table>`:'';
151
+ const cards=groups.map(group=>{
152
+ const a=group.artifact,meta=a.metadata||{},acq=meta.acquisition||{},s=stats(group),anchor=artifactAnchor(a.id);
153
+ const definitions=(meta.definitions||[]).filter(d=>d.path && (['manifest-digest','index-digest','registry-reference-resolution'].includes(d.binding) || d.match==='exact-digest'));
154
+ const sourceAction=definitions.length ? t('If applicable, update these verified source declarations:', 'Si nécessaire, mettez à jour ces déclarations source vérifiées :')+' '+definitions.map(d=>`<code>${esc(location(d))}</code>`).join(', ') : t('No matching source declaration is available; identify the build or deployment definition before changing it.', 'Aucune déclaration source associée n’est disponible ; identifiez la définition de build ou de déploiement avant de la modifier.');
155
+ const imageAction=visible(group.matches).length ? `<p><strong>${t('Recommended image action','Action recommandée sur l’image')}:</strong> ${t('For a publisher-provided image, obtain and deploy a corrected image from its publisher. If you build the image, rebuild it from a corrected base and packages, republish it and deploy the replacement.','Pour une image fournie par un éditeur, procurez-vous et déployez une image corrigée auprès de cet éditeur. Si vous construisez l’image, reconstruisez-la à partir d’une base et de paquets corrigés, publiez-la de nouveau et déployez son remplacement.')} ${sourceAction} ${t('Scan the replacement image to verify the fixes and its coverage.','Analysez l’image de remplacement pour vérifier les corrections et la couverture.')} ${['available','current'].includes(a.imageUpdate?.status)?'':t('No replacement tag or digest has been verified from this evidence.','Aucun tag ni empreinte de remplacement n’a été vérifié à partir de ces éléments.')}</p>` : `<p><strong>${t('Recommended image action','Action recommandée sur l’image')}:</strong> ${t('No correction is proposed from the recorded findings; consult scan coverage before deciding the image is safe.','Aucune correction n’est proposée à partir des résultats enregistrés ; consultez la couverture avant de considérer l’image comme sûre.')}</p>`;
156
+ const rows=(a.coverage||[]).map(c=>`<tr><td>${esc(c.capability||'')}</td><td>${esc(c.collector||c.source||'')}</td><td>${esc(c.execution||c.status||'unknown')}</td><td>${esc(c.reason||c.message||c.result||'')}</td></tr>`).join('');
157
+ const updateIndex=new Map();
158
+ for(const update of s.updates){const key=componentIdentity(update.dep),list=updateIndex.get(key)||[];list.push(update);updateIndex.set(key,list);}
159
+ const findingIndex=new Map();
160
+ for(const match of visible(group.matches)){const key=componentIdentity(match.dep||{}),list=findingIndex.get(key)||[];list.push(match);findingIndex.set(key,list);}
161
+ const affectedKeys=new Set(findingIndex.keys());
162
+ const inventory=reportedComponents(a,group.matches),inventoryKeys=new Set(inventory.map(componentIdentity));
163
+ // Older or partial inventories can omit a component that is still supported
164
+ // by a finding. Keep its correction, and identify the source of this row.
165
+ for(const [key,findings] of findingIndex)if(!inventoryKeys.has(key)){inventory.push({...findings[0].dep,_fromFinding:true});inventoryKeys.add(key);}
166
+ inventory.sort((left,right)=>Number(affectedKeys.has(componentIdentity(right)))-Number(affectedKeys.has(componentIdentity(left))));
167
+ const components=inventory.map(c=>{
168
+ const updates=updateIndex.get(componentIdentity(c))||[];
169
+ const fixes=[...new Set(updates.map(u=>u.fix))],advisories=[...new Set((findingIndex.get(componentIdentity(c))||[]).map(m=>m.advisoryId||m.cve?.id).filter(Boolean))];
170
+ return `<tr><td><code>${esc(c.namespace?c.namespace+'/'+c.name:c.name||c.artifactId||c.coord||'')}</code><br>${esc(c.packageType||c.ecosystem||'')}${c._fromFinding?`<br><small>${t('From finding; not present in inventory','Issu d’un résultat ; absent de l’inventaire')}</small>`:''}</td><td>${esc(c.version||'—')}</td><td>${fixes.map(esc).join('<br>')||'—'}</td><td>${advisories.map(id=>`<a href="${advisoryUrl(id)}">${esc(id)}</a>`).join(', ')||'—'}</td><td>${esc(c.architecture||'—')}</td><td>${esc(c.artifactPath||'—')}</td><td>${esc((c.osPackageOwners||[]).map(o=>`${o.name}@${o.version}`).join(', ')||'—')}</td></tr>`;
171
+ }).join('');
172
+ const totals=[[t('Components','Composants'),Number(a.componentCount ?? a.components?.length ?? 0)],[t('Affected packages','Paquets affectés'),s.components],[t('Advisories','Avis'),s.advisories],[t('Unique CVEs','CVE distinctes'),s.cves]];
173
+ const totalsTable=`<table class="image-totals"><thead><tr>${totals.map(([label])=>`<th scope="col">${label}</th>`).join('')}</tr></thead><tbody><tr>${totals.map(([,value])=>`<td class="image-total-value">${value}</td>`).join('')}</tr><tr><td colspan="4"><span class="image-severity-label">${t('CVE row severities','Sévérités des lignes CVE')}</span>${renderSeverityCounts(s.severity,locale)}</td></tr></tbody>${group.matches.length?`<tfoot><tr><td colspan="4"><a class="report-section-link" href="#${anchor}-cves">${t('View vulnerability details','Voir les vulnérabilités')}<span aria-hidden="true">→</span></a></td></tr></tfoot>`:''}</table>`;
174
+ const noCve=visible(group.matches).filter(m=>m.dep?.ecosystem==='system' && !linkedCves(m.cve).length);
175
+ const noCveRows=noCve.map(m=>{
176
+ const dep=m.dep||{},c=m.cve||{},id=m.advisoryId||c.id||'—',url=safeUrl(c.advisorySource)||safeUrl(c.gcveSource)||safeUrl((c.osvRefs||[]).find(r=>safeUrl(r?.url))?.url);
177
+ const name=dep.namespace?`${dep.namespace}/${dep.name||dep.artifactId||''}`:dep.name||dep.artifactId||'—';
178
+ return `<tr><td><a href="${advisoryUrl(id)}"><code>${esc(id)}</code></a>${url?`<br><a href="${esc(url)}">${t("Original source","Source originale")}</a>`:""}</td><td>${esc(c.summary||c.description||'—')}</td><td>${renderTime(c.published||'—',locale)}</td><td><code>${esc(name)}</code> ${esc(dep.version||'')}</td><td>${esc(c.fixVersion||m.fixVersion||'—')}</td></tr>`;
179
+ }).join('');
180
+ const nonCveAdvisories=noCveRows?`<details open><summary>${t('Distribution advisories without linked CVEs','Avis de distribution sans CVE liée')} (${noCve.length})</summary><p>${t('No linked CVE or CVE severity is supplied for these advisory records. They may include security or maintenance updates.','Aucune CVE liée ni sévérité CVE n’est fournie pour ces avis. Ils peuvent concerner la sécurité ou la maintenance.')}</p><table><thead><tr><th>${t('Advisory','Avis')}</th><th>${t('Summary','Résumé')}</th><th>${t('Published','Publié')}</th><th>${t('Package','Paquet')}</th><th>${t('Candidate','Version proposée')}</th></tr></thead><tbody>${noCveRows}</tbody></table></details>`:'';
181
+ return `<details class="report-subsection" open id="${anchor}"><summary><h3>${esc(artifactTitle(a,artifacts))}</h3></summary><div>`+
182
+ renderImageSummary(a,locale)+
183
+ totalsTable+
184
+ imageAction+
185
+ (rows?`<details open><summary>${t('Coverage checks','Contrôles de couverture')}</summary><table><thead><tr><th>${t('Capability','Capacité')}</th><th>${t('Source','Source')}</th><th>${t('Execution','Exécution')}</th><th>${t('Result / limitation','Résultat / limite')}</th></tr></thead><tbody>${rows}</tbody></table></details>`:`<p>${t('Coverage information unavailable.','Informations de couverture indisponibles.')}</p>`)+
186
+ renderAdvisoryObservations(a,locale)+nonCveAdvisories+`<details class="report-subsection"><summary><h4>${t('Component inventory and candidate corrections','Inventaire des composants et corrections proposées')} (${inventory.length})</h4></summary><p>${t('System components and binaries are detailed only when associated with a CVE or advisory.','Les composants système et les binaires sont détaillés uniquement lorsqu’ils sont associés à une CVE ou un avis.')}</p><p>${t('Candidate versions come from individual advisories. Verify them in the replacement image; they do not establish that a particular image tag or digest is corrected.','Les versions proposées proviennent d’avis individuels. Vérifiez-les dans l’image de remplacement ; elles ne prouvent pas qu’un tag ou une empreinte d’image est corrigé.')}</p>`+
187
+ (components?`<table class="image-inventory"><thead><tr><th>${t('Component','Composant')}</th><th>${t('Installed','Installé')}</th><th>${t('Candidate corrections','Corrections proposées')}</th><th>${t('Advisories','Avis')}</th><th>Arch</th><th>${t('Location','Emplacement')}</th><th>${t('OS package owner','Paquet système propriétaire')}</th></tr></thead><tbody>${components}</tbody></table>`:`<p>${t('No component details to display.','Aucun composant à détailler.')}</p>`)+`</details></div></details>`;
188
+ }).join('');
189
+ return referenceNotice+overview+(groups.length?`<p>${t('A raw finding is an advisory affecting a component. An advisory can link several CVEs; the CVE section groups linked CVE identifiers while advisories without linked CVEs remain below.','Un résultat brut correspond à un avis affectant un composant. Un avis peut être lié à plusieurs CVE ; la section CVE regroupe les identifiants liés et les avis sans CVE liée restent ci-dessous.')}</p>`:'')+cards+renderReferences(projectInfo,artifacts,locale);
190
+ }
191
+ module.exports={artifactAnchor,artifactTitle,artifactGroups,renderImageCves,renderArtifactEvidence};