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
package/lib/charts.js CHANGED
@@ -13,8 +13,8 @@
13
13
  * a CSS class — a class would not survive the canvas rasterisation (the document
14
14
  * stylesheet is not applied to the serialised SVG).
15
15
  *
16
- * Charts: (1) CWE of direct vulns, (2) vulnerable indirect deps by introducing
17
- * component, (3) exposed applications or modules, and (4) fix-priority bands.
16
+ * Charts: (1) CWE distribution, (2) findings by component, (3) exposure or
17
+ * severity breakdown, and (4) fix-priority bands.
18
18
  * All four cards use donuts, including application reports. The legends show counts;
19
19
  * application categories and exposed instances may overlap.
20
20
  *
@@ -67,7 +67,6 @@ const sevKey = m => {
67
67
  return s in SEV_RANK ? s : "unknown";
68
68
  };
69
69
  const emptySeg = () => ({ critical: 0, high: 0, medium: 0, low: 0, unknown: 0 });
70
- const coordKeyOf = dep => dep.coordKey || `${dep.ecosystem === "npm" ? "npm:" : (dep.groupId || "") + ":"}${dep.artifactId}`;
71
70
 
72
71
  // Keep the top-N rows; fold the remainder into a single "+K more" aggregate row
73
72
  // (a chart must never silently drop categories).
@@ -90,10 +89,10 @@ function capRows(rows, topN, { stacked = false, t = EN_T } = {}) {
90
89
  // ---------------------------------------------------------------- aggregators
91
90
 
92
91
  /** Chart 1 — CWE distribution of DIRECT production vulns, with per-severity counts. */
93
- function cweByCriticality(prodMatches, { topN = 7, t = EN_T, cweTitle = cweName } = {}) {
92
+ function cweByCriticality(prodMatches, { topN = 7, t = EN_T, cweTitle = cweName, includeTransitive = false } = {}) {
94
93
  const map = new Map();
95
94
  for (const m of prodMatches || []) {
96
- if (m.dep && m.dep.scope === "transitive") continue; // direct (declared) only
95
+ if (!includeTransitive && m.dep && m.dep.scope === "transitive") continue; // source direct findings by default
97
96
  const cwes = Array.isArray(m.cve && m.cve.cwes) ? m.cve.cwes : [];
98
97
  if (!cwes.length) continue; // a "by CWE" chart only counts categorised findings
99
98
  const sev = sevKey(m);
@@ -123,6 +122,74 @@ function readableDepLabel(coordKey) {
123
122
  return tail || s;
124
123
  }
125
124
 
125
+ /** Findings grouped by actual image identity, with per-severity counts. */
126
+ function findingsByImage(matches, artifacts = [], { topN = 7, t = EN_T } = {}) {
127
+ const by = new Map(), targets = new Map((artifacts || []).map(a => [a.id, a]));
128
+ for (const match of matches || []) {
129
+ const id = match.dep?.artifactTargetId; if (!id) continue;
130
+ if (!by.has(id)) by.set(id, { segments: emptySeg(), total: 0 });
131
+ const group = by.get(id); group.segments[sevKey(match)]++; group.total++;
132
+ }
133
+ const rows = [...by].map(([id, group]) => {
134
+ const m = targets.get(id)?.metadata || {};
135
+ const source = m.acquisition?.reference || m.registryEvidence?.reference || m.tags?.[0] || m.source || id;
136
+ const platform = m.platform && typeof m.platform === 'object' ? [m.platform.os, m.platform.architecture, m.platform.variant].filter(Boolean).join('/') : m.platform;
137
+ return { key: id, label: platform ? `${source} (${platform})` : source, segments: group.segments, total: group.total };
138
+ }).sort((a, b) => b.total - a.total || String(a.label).localeCompare(String(b.label)));
139
+ return capRows(rows, topN, { stacked: true, t });
140
+ }
141
+
142
+ /** Group each finding by image, application or module; show shared owners
143
+ * together and retain unknown ownership in an unattributed group. */
144
+ function findingsByComponent(matches, { artifacts = [], applications = [], moduleNames = new Map(), topN = 7, t = EN_T } = {}) {
145
+ const images = new Map(artifacts.map(a => [a.id, a]));
146
+ const apps = new Map(applications.map(a => [a.id, a]));
147
+ const groups = new Map(), occurrences = [], indexed = new Map();
148
+ for (const m of matches || []) {
149
+ const identity = m.findingId ? JSON.stringify([m.dep?.artifactTargetId || null, m.findingId]) : null;
150
+ const prior = identity && indexed.get(identity);
151
+ if (!prior) {
152
+ const copy = { ...m, dep: { ...m.dep, manifestPaths: [...(m.dep?.manifestPaths || [])] }, applicationIds: [...(m.applicationIds || [])] };
153
+ occurrences.push(copy); if (identity) indexed.set(identity, copy);
154
+ } else {
155
+ prior.applicationIds.push(...(m.applicationIds || []));
156
+ prior.dep.manifestPaths.push(...(m.dep?.manifestPaths || []));
157
+ if (SEV_RANK[sevKey(m)] > SEV_RANK[sevKey(prior)]) prior.cve = m.cve;
158
+ }
159
+ }
160
+ for (const m of occurrences) {
161
+ const artifact = m.dep?.artifactTargetId;
162
+ let key, label;
163
+ if (artifact) {
164
+ const meta = images.get(artifact)?.metadata || {};
165
+ const source = meta.acquisition?.reference || meta.registryReference?.reference || meta.tags?.[0] || meta.source || artifact;
166
+ const platform = meta.platform && typeof meta.platform === 'object' ? [meta.platform.os, meta.platform.architecture, meta.platform.variant].filter(Boolean).join('/') : meta.platform;
167
+ key = `image:${artifact}`; label = platform ? `${source} (${platform})` : source;
168
+ } else {
169
+ const appIds = [...new Set((m.applicationIds || []).filter(Boolean))];
170
+ // When parsed descriptors are available, they are the authoritative
171
+ // module inventory. A dependency's own metadata path is not a project module.
172
+ const paths = [...new Set((m.dep?.manifestPaths || []).filter(path => path && (!moduleNames.size || moduleNames.has(path))))];
173
+ if (appIds.length === 1) {
174
+ const app = apps.get(appIds[0]); key = `application:${appIds[0]}`;
175
+ label = `${app?.type || t('Application')} · ${app?.root || appIds[0]}`;
176
+ } else if (appIds.length > 1) {
177
+ appIds.sort(); key = `shared-applications:${JSON.stringify(appIds)}`;
178
+ label = `${t('Shared')}: ${appIds.map(id => apps.get(id)?.root || id).join(', ')}`;
179
+ } else if (!appIds.length && paths.length === 1) {
180
+ key = `module:${paths[0]}`; label = moduleNames.get(paths[0]) || paths[0];
181
+ } else if (paths.length > 1) {
182
+ paths.sort(); key = `shared-modules:${JSON.stringify(paths)}`;
183
+ label = `${t('Shared')}: ${paths.map(path => moduleNames.get(path) || path).join(', ')}`;
184
+ } else { key = '__unattributed__'; label = t('Unattributed'); }
185
+ }
186
+ if (!groups.has(key)) groups.set(key, { key, label, segments: emptySeg(), total: 0 });
187
+ const group = groups.get(key); group.segments[sevKey(m)]++; group.total++;
188
+ }
189
+ const rows = [...groups.values()].sort((a,b) => b.total - a.total || String(a.label).localeCompare(String(b.label)));
190
+ return capRows(rows, topN, { stacked: true, t });
191
+ }
192
+
126
193
  /** Chart 2 — sub-dep CVEs grouped by their ROOT (direct) dep, by severity.
127
194
  * Counts CVEs (a sub-dep with 3 CVEs contributes 3), each in its own bucket. */
128
195
  function vulnSubdepsByDep(prodMatches, { topN = 7, t = EN_T } = {}) {
@@ -214,12 +281,16 @@ const MAJOR_SEVERITIES = new Set(["critical", "high"]);
214
281
  * @param {Map<string,string>} moduleNames absolute descriptor path → label (lib/module-names.js)
215
282
  */
216
283
  function mostVulnerableComponents(prodMatches, moduleNames, { topN = 7, t = EN_T } = {}) {
217
- const by = new Map();
284
+ const by = new Map(), seen = new Map();
218
285
  for (const m of prodMatches || []) {
219
286
  const sev = sevKey(m);
220
287
  if (!MAJOR_SEVERITIES.has(sev)) continue;
221
288
  for (const file of (m.dep && m.dep.manifestPaths) || []) {
222
289
  if (!file) continue;
290
+ if (!seen.has(file)) seen.set(file, new Set());
291
+ const identity = m.findingId || m;
292
+ if (seen.get(file).has(identity)) continue;
293
+ seen.get(file).add(identity);
223
294
  let e = by.get(file);
224
295
  if (!e) { e = { segments: emptySeg(), total: 0 }; by.set(file, e); }
225
296
  e.segments[sev]++; e.total++;
@@ -249,11 +320,16 @@ function mostVulnerableComponents(prodMatches, moduleNames, { topN = 7, t = EN_T
249
320
  function mostVulnerableApplications(prodMatches, applications = [], coverage = [], { topN = 7, t = EN_T } = {}) {
250
321
  const by = new Map();
251
322
  const unique = new Set();
323
+ const seen = new Map();
252
324
  for (const m of prodMatches || []) {
253
325
  const sev = sevKey(m);
254
326
  if (!MAJOR_SEVERITIES.has(sev)) continue;
255
327
  for (const appId of m.applicationIds || []) {
256
- unique.add(m.findingId || `${m.cve && m.cve.id}|${coordKeyOf(m.dep || {})}|${m.dep && m.dep.version}`);
328
+ const identity = m.findingId || m;
329
+ unique.add(identity);
330
+ if (!seen.has(appId)) seen.set(appId, new Set());
331
+ if (seen.get(appId).has(identity)) continue;
332
+ seen.get(appId).add(identity);
257
333
  let e = by.get(appId);
258
334
  if (!e) { e = { segments: emptySeg(), total: 0 }; by.set(appId, e); }
259
335
  e.segments[sev]++; e.total++;
@@ -374,7 +450,18 @@ function donutChart({ slices, width = 250, note, centerValue, t = EN_T }) {
374
450
  parts.push(`<text x="11" y="${ly}" ${FONT} font-size="7.5" fill="#4b5563">${esc(legendTxt(s))}</text>`);
375
451
  ly += 11;
376
452
  }
377
- if (note) { parts.push(`<text x="0" y="${ly}" ${FONT} font-size="7" font-style="italic" fill="#9ca3af">${esc(note)}</text>`); ly += 11; }
453
+ if (note) {
454
+ const limit = Math.max(16, Math.floor(width / 4));
455
+ let line = '';
456
+ for (const word of String(note).split(/\s+/)) {
457
+ if (line && `${line} ${word}`.length > limit) {
458
+ parts.push(`<text x="0" y="${ly}" ${FONT} font-size="7" font-style="italic" fill="#9ca3af">${esc(line)}</text>`);
459
+ ly += 11; line = '';
460
+ }
461
+ line += (line ? ' ' : '') + word;
462
+ }
463
+ if (line) { parts.push(`<text x="0" y="${ly}" ${FONT} font-size="7" font-style="italic" fill="#9ca3af">${esc(line)}</text>`); ly += 11; }
464
+ }
378
465
  return { body: parts.join(""), width, height: ly + 2 };
379
466
  }
380
467
 
@@ -397,41 +484,44 @@ function emptyCard(id, title, note) {
397
484
  /**
398
485
  * Build the four-chart "Overview" row. Returns "" when there is nothing to plot.
399
486
  */
400
- function renderCharts(payload = {}, opts = {}) {
487
+ function renderChartsGroup(payload = {}, opts = {}) {
401
488
  // Injected by the report so this module needs no i18n dependency of its own; identity
402
489
  // by default, which keeps every existing caller and test rendering English.
403
490
  const t = typeof opts.t === "function" ? opts.t : EN_T;
404
491
  const prod = payload.prodMatches || [];
492
+ const imageMatches = prod.filter(m => !!m.dep?.artifactTargetId);
493
+ const sourceMatches = prod.filter(m => !m.dep?.artifactTargetId);
494
+ const hasImages = !!payload.hasImages || imageMatches.length > 0 || (payload.artifacts || []).length > 0;
495
+ const imageOnly = hasImages && !sourceMatches.length;
405
496
  const cweTitle = typeof opts.cweName === "function" ? opts.cweName : cweName;
406
- // Application scans announce their own axis (plan §6.3): chart 1 carries the CWEs of
407
- // the DIRECT application findings (core/framework/components/extensions), chart 2 the
408
- // indirect CVEs grouped by their introducing component. Package-manager scope and
409
- // non-application findings are never silently mixed into these lanes.
497
+ // Include direct application and source findings, plus image findings, in the
498
+ // CWE distribution; the component chart includes all production findings.
410
499
  const applications = payload.applications || [];
411
500
  const appScan = applications.length > 0;
412
- const cwe = appScan
413
- ? cweByCriticality(prod.filter(m => m.applicationRelation === "direct"), { t, cweTitle })
414
- : cweByCriticality(prod, { t, cweTitle });
415
- const origins = appScan ? vulnByApplicationOrigin(prod, payload.applicationInventory || [], { t }) : null;
416
- const subs = appScan ? origins.rows : vulnSubdepsByDep(prod, { t });
417
- const unattr = appScan ? origins.unknown : unattributedSubdeps(prod);
418
- const scope = directVsTransitive(prod, t);
501
+ const cweInput = appScan ? sourceMatches.filter(m => m.applicationRelation === "direct" || (!m.applicationIds?.length && m.dep?.scope !== 'transitive')).concat(imageMatches)
502
+ : sourceMatches.filter(m => m.dep?.scope !== 'transitive').concat(imageMatches);
503
+ const cwe = cweByCriticality(cweInput, { t, cweTitle, includeTransitive: hasImages });
504
+ const subs = findingsByComponent(prod, { artifacts: payload.artifacts || [], applications, moduleNames: payload.moduleNames instanceof Map ? payload.moduleNames : new Map(), t });
505
+ const unattr = 0;
506
+ const scope = directVsTransitive(sourceMatches, t);
419
507
  const prio = fixPriority(prod, t);
420
508
  // On a multi-module tree, "which of my modules is worst" is actionable; the direct vs
421
509
  // transitive split is not module-specific and keeps its slot on a single-descriptor scan,
422
510
  // where ranking one component against itself would say nothing.
423
511
  const moduleNames = payload.moduleNames instanceof Map ? payload.moduleNames : new Map();
424
512
  const multiModule = (Number(payload.descriptorCount) || 0) > 1;
425
- const components = multiModule ? mostVulnerableComponents(prod, moduleNames, { t }) : [];
513
+ const components = multiModule ? mostVulnerableComponents(sourceMatches, moduleNames, { t }) : [];
426
514
  // Application scans rank exposed instances instead of modules (plan §6.4): plugins,
427
515
  // themes and extensions count as the direct lane, their dependencies as indirect.
428
- const appChart = appScan ? mostVulnerableApplications(prod, applications, payload.coverage || [], { t }) : null;
516
+ const appChart = appScan ? mostVulnerableApplications(sourceMatches, applications, payload.coverage || [], { t }) : null;
429
517
 
430
- if (!(cwe.length || subs.length || scope.length || prio.length || unattr || components.length || (appChart && appChart.rows.length))) return "";
518
+ if (!hasImages && !payload.showEmpty && !(cwe.length || subs.length || scope.length || prio.length || unattr || components.length || (appChart && appChart.rows.length))) return "";
431
519
 
432
520
  const interactive = opts.interactive !== false; // copy button only in the interactive HTML
433
521
 
434
- const cweSlices = colorizeCategories(cwe.map(r => ({ key: r.key, label: r.key, name: r.name,
522
+ const imageSeverity = SEV_SERIES.map(s => ({ ...s, label:t(s.label), value:imageMatches.filter(m => sevKey(m) === s.key).length })).filter(s => s.value);
523
+ const moduleUnique = new Set(sourceMatches.filter(m => MAJOR_SEVERITIES.has(sevKey(m)) && (m.dep?.manifestPaths || []).some(Boolean)).map(m => m.findingId || m)).size;
524
+ const cweSlices = colorizeCategories(cwe.map(r => ({ key: r.key, label: r.more ? r.label : r.key, name: r.name,
435
525
  value: r.total, segments: r.segments, more: r.more })));
436
526
  const subSlices = colorizeCategories(subs.map(r => ({ key: r.key, label: r.label,
437
527
  value: r.total, segments: r.segments, more: r.more })));
@@ -442,22 +532,22 @@ function renderCharts(payload = {}, opts = {}) {
442
532
 
443
533
  // Share one viewBox width so the four donuts remain aligned.
444
534
  const W = Math.max(250, legendBoxWidth(cweSlices), legendBoxWidth(subSlices, note2),
445
- legendBoxWidth(appChart ? appChart.rows : multiModule ? components : scope), legendBoxWidth(prio));
535
+ legendBoxWidth(imageOnly ? imageSeverity : appChart ? appChart.rows : multiModule ? components : scope), legendBoxWidth(prio));
446
536
 
447
- const card1 = cwe.length
448
- ? chartCard({ t, id: "chart-cwe", title: t("CWE — direct vulns (by criticality)"), interactive,
537
+ const cweHeading = hasImages ? t("CWE — findings (by severity)") : t("CWE — direct vulns (by criticality)");
538
+ const card1 = cwe.length
539
+ ? chartCard({ t, id: "chart-cwe", title: cweHeading, interactive,
449
540
  ...donutChart({ slices: cweSlices, width: W, t }) })
450
- : emptyCard("chart-cwe", t("CWE — direct vulns (by criticality)"), t("No categorised direct CVE."));
541
+ : emptyCard("chart-cwe", cweHeading, hasImages ? t("No categorised finding.") : t("No categorised direct CVE."));
451
542
 
452
543
  const card2 = (subs.length || unattr)
453
544
  ? chartCard({ t, id: "chart-subdeps",
454
- title: appScan ? t("Indirect CVEs per direct dependency") : t("Sub-dep CVEs per dependency"),
545
+ title: t("Findings per component"),
455
546
  interactive, ...donutChart({ slices: subSlices, width: W, note: note2, t }) })
456
547
  : emptyCard("chart-subdeps",
457
- appScan ? t("Indirect CVEs per direct dependency") : t("Sub-dep CVEs per dependency"),
458
- appScan ? t("No indirect application CVE.") : t("No vulnerable transitive deps."));
548
+ t("Findings per component"), t("No production CVE."));
459
549
 
460
- const card3 = appChart
550
+ const card3 = imageOnly ? (imageSeverity.length ? chartCard({ t, id: 'chart-image-severity', title:t('Findings by severity'), interactive, ...donutChart({slices:imageSeverity,width:W,t}) }) : emptyCard('chart-image-severity',t('Findings by severity'),t('No production CVE.'))) : appChart
461
551
  ? (appChart.rows.length
462
552
  ? chartCard({ t, id: "chart-instances", title: t("Most vulnerable instances"), interactive,
463
553
  ...donutChart({ slices: appChart.rows, width: W, centerValue: appChart.unique, t,
@@ -466,8 +556,8 @@ function renderCharts(payload = {}, opts = {}) {
466
556
  : emptyCard("chart-instances", t("Most vulnerable instances"), t("No critical or high application CVE.")))
467
557
  : multiModule
468
558
  ? (components.length
469
- ? chartCard({ t, id: "chart-components", title: t("Most vulnerable components"), interactive, ...donutChart({ slices: components, width: W, t }) })
470
- : emptyCard("chart-components", t("Most vulnerable components"), t("No critical or high production CVE.")))
559
+ ? chartCard({ t, id: "chart-components", title: t("Most vulnerable components"), interactive, ...donutChart({ slices: components, width: W, centerValue: moduleUnique, note:t('Shared findings count once per affected module.'), t }) })
560
+ : emptyCard("chart-components", t("Most vulnerable components"), t("No critical or high production findings attributed to a project descriptor.")))
471
561
  : (scope.length
472
562
  ? chartCard({ t, id: "chart-scope", title: t("Direct vs transitive (by severity)"), interactive, ...donutChart({ slices: scope, width: W, t }) })
473
563
  : emptyCard("chart-scope", t("Direct vs transitive (by severity)"), t("No production CVE.")));
@@ -479,8 +569,27 @@ function renderCharts(payload = {}, opts = {}) {
479
569
  return `<section class="charts-row" aria-label="${esc(t("Overview charts"))}">${card1}${card2}${card3}${card4}</section>`;
480
570
  }
481
571
 
572
+ // Source and image occurrences must stay in separate overview rows, even when
573
+ // the same package and advisory occur in both inventories.
574
+ function renderCharts(payload = {}, opts = {}) {
575
+ const matches = payload.prodMatches || [];
576
+ const source = matches.filter(m => !m.dep?.artifactTargetId);
577
+ const images = matches.filter(m => !!m.dep?.artifactTargetId);
578
+ const hasImages = !!payload.hasImages || images.length > 0 || (payload.artifacts || []).length > 0;
579
+ const sourceRow = payload.hasSourceProject === false ? "" : renderChartsGroup({...payload, prodMatches:source, artifacts:[], hasImages:false, showEmpty:hasImages && payload.hasSourceProject === true}, opts);
580
+ const translate = typeof opts.t === 'function' ? opts.t : EN_T;
581
+ const labelledSource = sourceRow ? `<h2 class="charts-heading">${esc(translate('Project overview'))}</h2>${sourceRow}` : '';
582
+ if (!hasImages) return labelledSource;
583
+ const imageRow = renderChartsGroup({...payload, prodMatches:images, applications:[], moduleNames:new Map(), descriptorCount:0, hasImages:true}, opts)
584
+ .replace(/id="chart-/g, 'id="image-chart-')
585
+ .replace(`aria-label="${esc(translate("Overview charts"))}"`, `aria-label="${esc(translate("Image overview charts"))}"`);
586
+ return labelledSource + `<h2 class="charts-heading">${esc(translate('Image overview'))}</h2>` + imageRow;
587
+ }
588
+
482
589
  module.exports = {
483
590
  cweByCriticality,
591
+ findingsByImage,
592
+ findingsByComponent,
484
593
  vulnSubdepsByDep,
485
594
  unattributedSubdeps,
486
595
  directVsTransitive,
@@ -3,15 +3,14 @@
3
3
  const COMMAND_HELP = `
4
4
  Commands:
5
5
  scan <dir> [options] scan a source tree (alias of -s <dir>)
6
+ image <archive|rootfs> [options] scan an image natively; image --help
6
7
  setup configure sources and proxy
7
- watch <dir> --name <name> collect and upload a project
8
- watch <dir> --id <id> update an explicitly selected project
8
+ watch <dir> --name <name>|--id <id> collect and upload a project
9
9
  watch <dir> --export <file> export descriptor locally
10
10
  login | logout | whoami aliases of auth login | logout | status
11
11
  config show show masked configuration
12
12
  cache export|import <file> transfer the complete local cache
13
- cache prepare <descriptor> --output <file> prepare a project archive online
14
-
13
+ cache prepare <descriptor|inventory> --output <file> prepare an offline archive online
15
14
  watch --help: privacy, safe updates; free account: 1 project,
16
15
  100 distinct direct coordinates (versions count once). Legacy commands remain supported.`;
17
16
 
@@ -37,11 +36,26 @@ function routeArguments(input) {
37
36
  }
38
37
  if (command === 'cache') {
39
38
  if (args.length === 1 || args.some(a => a === '--help' || a === '-h'))
40
- return { help: 'Usage: vigievuln cache prepare <descriptor.json> --output <archive.tar.gz> [source options]\n vigievuln cache export <file> [--verbose] [source options]\n vigievuln cache import <file> [--replace] [--force] [--verbose] [source options]\nPrepare warms the descriptor and writes a project archive in one invocation. Export copies the complete local cache.' };
39
+ return { help: 'Usage: vigievuln cache prepare <descriptor-or-inventory.json> --output <archive.tar.gz> [source options]\n vigievuln cache export <file> [--verbose] [source options]\n vigievuln cache import <file> [--replace] [--force] [--verbose] [source options]\nPrepare warms the source descriptor or artifact inventory and writes an offline archive. Export copies the complete local cache.' };
41
40
  const [, operation, file, ...rest] = args;
42
41
  if (operation === 'prepare') {
43
42
  if (!file || file.startsWith('-')) throw new Error('usage: vigievuln cache prepare <descriptor.json> --output <archive.tar.gz>');
44
43
  if (rest.some(a=>/^--(?:export-cache|import-cache|prepare-offline|import-anonymized)(?:=|$)/.test(a))) throw new Error('cache prepare cannot be combined with another cache or descriptor command');
44
+ let artifact=false;
45
+ try {
46
+ const fs=require('node:fs'),stat=fs.statSync(file);
47
+ if(stat.isFile() && stat.size<=128*1024*1024)artifact=JSON.parse(fs.readFileSync(file,'utf8'))?.schema==='vigievuln-artifact-inventory/1';
48
+ } catch { /* Descriptor parsing reports invalid inputs in the regular path. */ }
49
+ if(artifact){
50
+ const args=[],outputs=[];
51
+ for(let i=0;i<rest.length;i++){
52
+ if(rest[i]==='--output'){if(!rest[i+1]||rest[i+1].startsWith('-'))throw Error('--output requires a value');outputs.push(rest[++i]);}
53
+ else if(rest[i].startsWith('--output='))outputs.push(rest[i].slice('--output='.length));
54
+ else args.push(rest[i]);
55
+ }
56
+ if(outputs.length!==1 || !outputs[0])throw Error('cache prepare requires exactly one --output');
57
+ return {args:['image','--inventory',file,'--no-report','--prepare-cache',outputs[0],...args]};
58
+ }
45
59
  return {args:['--prepare-offline',file,...rest]};
46
60
  }
47
61
  if (!['export', 'import'].includes(operation) || !file || file.startsWith('-'))
@@ -50,7 +64,7 @@ function routeArguments(input) {
50
64
  for (let i = 0; i < rest.length; i++) {
51
65
  const arg = rest[i];
52
66
  if (allowed.includes(arg)) continue;
53
- const match = /^(--config|--source-profile|--proxy-cache)(?:=(.*))?$/.exec(arg);
67
+ const match = /^(--config|--source-profile|--proxy-cache|--cache-dir)(?:=(.*))?$/.exec(arg);
54
68
  if (match) {
55
69
  const value = match[2] === undefined ? rest[++i] : match[2];
56
70
  if (!value || value.startsWith('-')) throw new Error(`${match[1]} requires a value`);
package/lib/cli-groups.js CHANGED
@@ -22,12 +22,13 @@ const DISABLE = {
22
22
  retire: "retire", "vendored-js-inventory": "vendoredJsInventory",
23
23
  maven: "maven", gradle: "gradle", npm: "npm", yarn: "yarn", nuget: "nuget",
24
24
  composer: "composer", pypi: "pypi", go: "go", ruby: "ruby",
25
- binaries: "binaries", jars: "jars", certs: "certs", js: "js",
25
+ binaries: "binaries", jars: "jars", certs: "certs", js: "js", images: "images",
26
26
  "default-excludes": "defaultExcludes",
27
27
  };
28
28
 
29
29
  /** Token → option key, for things that are OFF unless asked for. */
30
30
  const ACTIVATE = {
31
+ images: "images",
31
32
  licenses: "licenses", "eol-support": "eolSupport", typosquat: "typosquat", snyk: "snyk",
32
33
  "osv-db": "osvDb", "nvd-cpe-match": "nvdCpeMatch", "cve-refresh": "cveRefresh",
33
34
  "osv-db-refresh": "osvDbRefresh", "retire-refresh": "retireRefresh", "cve-offline": "cveOffline", "gcve-offline": "gcveOffline",
@@ -0,0 +1,206 @@
1
+ 'use strict';
2
+
3
+ const fs = require('node:fs');
4
+ const path = require('node:path');
5
+ const { Command, InvalidArgumentError } = require('commander');
6
+ const { acquireInventories, assessInventories, writeSnapshot, incompleteCapabilities } = require('./artifacts/scan');
7
+
8
+ const REPORTS = Object.freeze({
9
+ json: { name: 'findings.json', write: (p, f) => require('./json-export').writeFindings(p, f) },
10
+ html: { name: 'cve-report.html', write: (p, f) => fs.writeFileSync(f, require('./cve-report').generateHtmlReport(p)) },
11
+ doc: { name: 'cve-report.doc', write: (p, f) => fs.writeFileSync(f, require('./cve-report').generateWordReport(p)) },
12
+ sbom: { name: 'sbom.cdx.json', write: (p, f) => require('./sbom-export').writeCycloneDx(p.resolvedDeps, p.cveMatches, f, { projectInfo: p.projectInfo, toolVersion: p.toolVersion }) },
13
+ csaf: { name: 'vex.csaf.json', write: (p, f) => require('./csaf-export').writeCsaf(p.resolvedDeps, p.cveMatches, f, { projectInfo: p.projectInfo, toolVersion: p.toolVersion }) },
14
+ sarif: { name: 'findings.sarif.json', write: (p, f) => require('./sarif-export').writeSarif(p.cveMatches, f, { projectInfo: p.projectInfo, toolVersion: p.toolVersion }) },
15
+ xlsx: { name: 'report.xlsx', write: (p, f) => require('./xlsx-export').writeXlsx(p, f) },
16
+ });
17
+
18
+ function jsonFile(file) {
19
+ if (fs.statSync(file).size > 1024 * 1024) throw Error('configuration file is too large');
20
+ const value = JSON.parse(fs.readFileSync(file, 'utf8'));
21
+ if (!value || typeof value !== 'object' || Array.isArray(value)) throw Error('configuration must be a JSON object');
22
+ return value;
23
+ }
24
+ function distribution(value) {
25
+ const match = /^([a-z][a-z0-9_-]*):([^\s:]+)$/.exec(value);
26
+ if (!match) throw new InvalidArgumentError('expected distribution-id:release, e.g. debian:12');
27
+ return { id: match[1], versionId: match[2] };
28
+ }
29
+ // Compare existing files by inode and resolve parent symlinks for new outputs.
30
+ function canonicalFile(file) {
31
+ const absolute = path.resolve(file); let current = absolute, suffix = [];
32
+ while (!fs.existsSync(current)) { const parent = path.dirname(current); if (parent === current) break; suffix.unshift(path.basename(current)); current = parent; }
33
+ try { current = fs.realpathSync(current); } catch { /* unresolved path */ }
34
+ return path.join(current, ...suffix);
35
+ }
36
+ function sameFile(a,b) {
37
+ if (canonicalFile(a) === canonicalFile(b)) return true;
38
+ try { const x=fs.statSync(a),y=fs.statSync(b); return x.dev===y.dev && x.ino===y.ino; } catch { return false; }
39
+ }
40
+ function reportFiles(opts) {
41
+ if (opts.report === false) return [];
42
+ const explicit=Object.keys(REPORTS).filter(format=>opts['report'+format[0].toUpperCase()+format.slice(1)]!==undefined);
43
+ const selected=opts.reports?opts.reports.split(',').map(s=>s.trim()):explicit.length?explicit:['html','json'];
44
+ const formats=[...new Set([...selected,...explicit])];
45
+ if(formats.some(format=>!REPORTS[format]))throw Error('unknown report format');
46
+ return formats.map(format=>{const specified=opts['report'+format[0].toUpperCase()+format.slice(1)];return {format,file:path.resolve(typeof specified==='string'?specified:path.join(opts.reportOutput,REPORTS[format].name))};});
47
+ }
48
+ function makeCommand() {
49
+ const command = new Command().name('vigievuln image').description('Native image, rootfs and publisher-inventory audit. No Docker or package-manager execution.')
50
+ .argument('[input]', 'Docker/OCI/rootfs archive, directory, registry reference or inventory')
51
+ .option('--config <file>', 'read scan configuration from a JSON file')
52
+ .option('--source-profile <profile>', 'advisory operator scope: all, us, eu or proxy')
53
+ .option('--proxy <url>', 'corporate forward proxy for outbound connections')
54
+ .option('--proxy-cache <url|vigievuln|default>', 'use a shared advisory proxy')
55
+ .option('--proxy-rate-limit-wait-ms <milliseconds>', 'maximum proxy retry wait per request (default: 45000)', Number)
56
+ .option('--reuse-stable-advisories', 'reuse cached individual advisories unchanged for at least the configured age', true)
57
+ .option('--no-reuse-stable-advisories', 'refresh older individual advisories using normal cache lifetimes')
58
+ .option('--stable-advisory-age-days <days>', 'minimum unchanged advisory age for reuse (default: 365)', Number)
59
+ .option('--force-update', 'revalidate consulted online sources, retaining cached data on failure')
60
+ .option('--proxy-cache-token <token>', 'shared advisory proxy authentication token')
61
+ .option('--vigievuln-proxy [domain]', 'use the hosted VigieVuln proxy, fr or com')
62
+ .option('--allow-insecure-http', 'allow HTTP to the configured advisory proxy for this invocation')
63
+ .option('--registry', 'obtain input directly from an OCI registry; offline uses a prepared cached inventory')
64
+ .option('--platform <os/arch[/variant]>', 'select an image platform; otherwise inspect all available platforms')
65
+ .option('--prefer-sbom', 'prefer publisher SBOMs when associated with the selected images; signatures remain unverified')
66
+ .option('--registry-auth <file>', 'JSON credentials {username,password,token,authOrigins}; never invokes credential helpers')
67
+ .option('--insecure', 'allow HTTP registry endpoints explicitly')
68
+ .option('--inventory', 'input is an exported VigieVuln artifact inventory')
69
+ .option('--sbom', 'input is a CycloneDX/SPDX or attestation JSON document')
70
+ .option('--expected-digest <digest>', 'require a supplied SBOM subject to agree with this image digest')
71
+ .option('--advisory-config <file>', 'JSON custom distribution advisory scope and optional source URL')
72
+ .option('--distribution <id:release>', 'explicit distribution scope for imported advisories or SBOM', distribution)
73
+ .option('--offline', 'zero network access; use imported advisory snapshots and cached inventories')
74
+ .option('--enrich <sources>', 'enrichment sources: nvd,kev,epss,gcve,euvd,certfr or none', value => value === 'none' ? [] : value.split(',').map(s => s.trim()), ['nvd', 'kev', 'epss', 'gcve', 'euvd', 'certfr'])
75
+ .option('--no-osv', 'exclude OSV advisory matching')
76
+ .option('--no-distro-advisories', 'exclude independent distribution tracker consultations')
77
+ .option('--no-publisher-advisories', 'exclude publisher advisory feeds')
78
+ .option('--no-nvd', 'exclude NVD enrichment')
79
+ .option('--no-kev', 'exclude CISA KEV enrichment')
80
+ .option('--no-epss', 'exclude EPSS enrichment')
81
+ .option('--no-gcve', 'exclude native GCVE advisory matching and derived aliases')
82
+ .option('--no-euvd', 'exclude ENISA EUVD enrichment')
83
+ .option('--no-certfr', 'exclude CERT-FR enrichment')
84
+ .option('--cache-dir <directory>', 'cache directory containing prepared vulnerability data')
85
+ .option('--prepare-cache <file>', 'warm and export advisory cache for an inventory')
86
+ .option('--definitions <directory>', 'find image declarations in source; only explicit matching digests bind to scanned images')
87
+ .option('--export-inventory <file>', 'save portable inventory independently of image contents')
88
+ .option('--import-advisories <file>', 'import a native OSV JSON/JSONL/ZIP dataset for --distribution')
89
+ .option('--snapshot-complete', 'declare imported dataset complete for the stated distribution release')
90
+ .option('--sync-advisories', 'prepare a distribution advisory snapshot online; requires --distribution when no image is supplied')
91
+ .option('--limits <file>', 'JSON resource policy {artifactLimits,registryLimits,maxMetadataBytes,...}')
92
+ .option('--report-output <directory>', 'report directory', './vigievuln-report')
93
+ .option('-r, --reports <formats>', 'comma-separated report formats: ' + Object.keys(REPORTS).join(','))
94
+ .option('--no-report', 'write no reports; inventory export and CI gates remain active')
95
+ .option('--fail-on <severity>', 'fail with exit 1 for matching findings: low,medium,high,critical,kev', 'none')
96
+ .option('--fail-on-incomplete [capabilities]', 'exit 2 for incomplete inventory/advisories/sources', false)
97
+ .option('--lang <language>', 'report language: en or fr', 'en');
98
+ for (const format of Object.keys(REPORTS)) command.option(`--report-${format} [file]`, `write ${format} report`);
99
+ return command;
100
+ }
101
+
102
+ async function run(args, injected = {}) {
103
+ const command = makeCommand();
104
+ command.parse(args, { from: 'user' });
105
+ const setup = require('./image-network').configureImageNetwork(command, injected);
106
+ try {
107
+ const opts = setup.options, input = command.args[0];
108
+ for (const warning of setup.warnings) console.warn(`⚠ ${warning}`);
109
+ if (![opts.registry, opts.inventory, opts.sbom].filter(Boolean).length) opts.mode = 'artifact';
110
+ if ([opts.registry, opts.inventory, opts.sbom].filter(Boolean).length > 1) throw Error('--registry, --inventory and --sbom are mutually exclusive');
111
+ if (opts.preferSbom && !opts.registry) throw Error('--prefer-sbom requires --registry');
112
+ if (opts.prepareCache && (!opts.inventory || opts.offline)) throw Error('--prepare-cache requires an inventory and online mode');
113
+ if (!['en', 'fr'].includes(opts.lang)) throw Error('--lang must be en or fr');
114
+ if (!['none', 'low', 'medium', 'high', 'critical', 'kev'].includes(opts.failOn)) throw Error('invalid --fail-on severity');
115
+ const required = opts.failOnIncomplete ? (opts.failOnIncomplete === true ? 'inventory,advisories,sources' : opts.failOnIncomplete).split(',').map(x => x.trim()) : [];
116
+ if (required.some(x => !['inventory', 'advisories', 'sources'].includes(x))) throw Error('invalid --fail-on-incomplete capability');
117
+ const cacheDir = opts.cacheDir;
118
+ const policy = opts.limits ? jsonFile(opts.limits) : {};
119
+ const credentials = opts.registryAuth ? jsonFile(opts.registryAuth) : {
120
+ token: process.env.VIGIEVULN_REGISTRY_TOKEN, username: process.env.VIGIEVULN_REGISTRY_USER, password: process.env.VIGIEVULN_REGISTRY_PASSWORD,
121
+ };
122
+ const options = { ...policy, ...opts, cacheDir, credentials, authOrigins: credentials.authOrigins || [],
123
+ ...(opts.advisoryConfig ? { advisoryConfig: typeof opts.advisoryConfig === 'string' ? jsonFile(opts.advisoryConfig) : opts.advisoryConfig } : {}) };
124
+ if (opts.osv === false && (opts.importAdvisories || opts.syncAdvisories)) throw Error('OSV advisories are excluded by the selected source profile');
125
+ if (opts.importAdvisories) {
126
+ if (!opts.distribution) throw Error('--import-advisories requires --distribution');
127
+ const imported = await require('./system-inventory').importSystemAdvisories(opts.importAdvisories, { ...options, complete: !!opts.snapshotComplete });
128
+ console.log(`Imported ${imported.recordCount} advisory records for ${imported.ecosystem}.`);
129
+ }
130
+ if (!input) {
131
+ if (opts.syncAdvisories) {
132
+ if (!opts.distribution) throw Error('--sync-advisories requires --distribution when no image is supplied');
133
+ const synced = await require('./system-inventory').syncSystemAdvisories(opts.distribution, options);
134
+ console.log(`Prepared ${synced.recordCount} advisory records for ${synced.ecosystem}.`);
135
+ return { synced };
136
+ }
137
+ if (opts.importAdvisories) return {};
138
+ throw Error('an image/archive/rootfs/inventory input is required; see vigievuln image --help');
139
+ }
140
+ const reports = reportFiles(opts);
141
+ const outputs = [...(opts.exportInventory ? [{label:'inventory',file:path.resolve(opts.exportInventory)}] : []), ...(opts.prepareCache ? [{label:'cache',file:path.resolve(opts.prepareCache)}] : []), ...reports.map(r => ({label:r.format,file:r.file}))];
142
+ if (reports.length) outputs.push({label:'checksums',file:path.join(path.dirname(reports[0].file),'SHA256SUMS')});
143
+ for (let i=0;i<outputs.length;i++) {
144
+ if (fs.existsSync(input) && sameFile(input,outputs[i].file)) throw Error(`${outputs[i].label} output must not overwrite the input artifact`);
145
+ for(let j=0;j<i;j++) if(sameFile(outputs[i].file,outputs[j].file)) throw Error('output paths must be distinct');
146
+ }
147
+ const targets = await acquireInventories(input, options);
148
+ const savedReferences = new Map();
149
+ for (const target of targets) for (const ref of target.metadata?.declarations || []) if (ref?.id && !savedReferences.has(ref.id)) savedReferences.set(ref.id, ref);
150
+ let imageReferences = [...savedReferences.values()];
151
+ if (opts.definitions) {
152
+ const discovery = require('./image-references').discoverImageReferences(path.resolve(opts.definitions));
153
+ imageReferences = require('./image-references').bindImageDefinitions(targets, discovery.references);
154
+ for (const target of targets) target.metadata.definitionDiscovery = { status: discovery.warnings.length ? 'incomplete' : target.metadata.definitions.length ? 'matched' : 'no-match', source: path.basename(path.resolve(opts.definitions)) };
155
+ if (discovery.warnings.length) for (const target of targets) target.warnings.push(...discovery.warnings.map(w => ({ ...w, capability: 'inventory' })));
156
+ }
157
+ if (opts.exportInventory) await writeSnapshot(opts.exportInventory, targets);
158
+ const result = await assessInventories(targets, options);
159
+ if (opts.prepareCache) {
160
+ const gaps = incompleteCapabilities(result, ['advisories', 'sources']);
161
+ if (gaps.length) console.warn('⚠ Prepared cache has incomplete advisory or source coverage; review the scan notices.');
162
+ const prepared = await require('./cache-archive-sqlite').exportCache(opts.prepareCache, { sourceDir: cacheDir,
163
+ proxyOrigin: options.proxyCache ? require('./proxy-scope').proxyOrigin(options.proxyCache) : undefined });
164
+ console.log(`Prepared cache: ${prepared.path}`);
165
+ }
166
+ const toolVersion = require('../package.json').version;
167
+ const payload = { ...result, toolVersion, locale: opts.lang,
168
+ projectInfo: { name: path.basename(input), src: '(artifact inventory)', toolVersion, generatedAt: new Date().toISOString(),
169
+ artifacts: result.artifacts, ...(imageReferences.length ? { imageReferences } : {}), provenance: { mode: opts.offline ? 'offline' : 'online',notices:[...(setup.notices||[]),...(result.notices||[])],
170
+ dataSources: result.artifacts.flatMap(a => a.coverage.filter(c => c.capability === 'advisories' || c.capability === 'sources').map(c => ({
171
+ label: c.ecosystem || c.source || c.collector, status: c.execution === 'not-applicable' ? 'disabled' : c.execution === 'completed' ? 'cached' : 'missing',
172
+ asOf: c.fetchedAt ? new Date(c.fetchedAt).toISOString() : null, detail: c.reason || c.execution }))) } } };
173
+ let written = [];
174
+ if (opts.report !== false) {
175
+ for (const { format, file } of reports) {
176
+ await fs.promises.mkdir(path.dirname(file), { recursive: true });
177
+ await REPORTS[format].write(payload, file);
178
+ written.push(file);
179
+ }
180
+ if (written.length) {
181
+ const checksum = path.join(path.dirname(written[0]), 'SHA256SUMS');
182
+ require('./report-integrity').writeChecksums(written, checksum, { baseDir: path.dirname(checksum) });
183
+ }
184
+ }
185
+ const gate = require('./gate').evaluateGate(result.cveMatches, opts.failOn);
186
+ const gaps = incompleteCapabilities(result, required);
187
+ if (opts.failOn === 'kev') {
188
+ gaps.push(...incompleteCapabilities(result, ['advisories']));
189
+ for (const artifact of result.artifacts) {
190
+ const hasCve = result.cveMatches.some(m => m.dep.artifactTargetId === artifact.id);
191
+ const kev = artifact.coverage.find(c => c.capability === 'sources' && c.collector === 'kev');
192
+ if (hasCve && (!kev || kev.execution !== 'completed')) gaps.push({ target: artifact.id, capability: 'kev' });
193
+ }
194
+ }
195
+ const malicious = result.cveMatches.some(m => m.malicious && !m.suppressed);
196
+ const exitCode = gaps.length ? 2 : gate.failed || malicious ? 1 : 0;
197
+ process.exitCode = exitCode;
198
+ console.log(`${result.artifacts.length} artifact(s), ${result.resolvedDeps.size} components, ${result.cveMatches.length} findings, ${result.warnings.length} warning(s).`);
199
+ for (const warning of result.warnings) console.warn(`⚠ ${warning.message}`);
200
+ for (const file of written) console.log(file);
201
+ if (gaps.length) console.warn(`Required coverage incomplete: ${[...new Set(gaps.map(g => g.capability))].join(', ')}.`);
202
+ return { ...result, written, exitCode };
203
+ } finally { setup.restore(); }
204
+ }
205
+
206
+ module.exports = { run, makeCommand, REPORTS };
@@ -0,0 +1,42 @@
1
+ // Parse file-backed ELF structures without executing the inspected file.
2
+ const fs = require('fs');
3
+ const MAX_SEGMENT = 32 * 1024 * 1024;
4
+ function extractElfMetadataFile(fd, size, options = {}) {
5
+ try {
6
+ const max = options.maxMetadataBytes || MAX_SEGMENT;
7
+ function read(pos, n) {
8
+ if (!Number.isSafeInteger(pos) || !Number.isSafeInteger(n) || pos < 0 || n < 0 || n > max || pos + n > size) throw Error('ELF bounds or metadata limit');
9
+ const b = Buffer.alloc(n); let off = 0;
10
+ while (off < n) { const got = fs.readSync(fd, b, off, n - off, pos + off); if (!got) throw Error('ELF truncated'); off += got; }
11
+ return b;
12
+ }
13
+ const h = read(0, 16);
14
+ if (!h.subarray(0, 4).equals(Buffer.from([127,69,76,70])) || ![1,2].includes(h[4]) || ![1,2].includes(h[5])) throw Error('unsupported ELF class or byte order');
15
+ const bits = h[4] === 1 ? 32 : 64, le = h[5] === 1;
16
+ const u16 = (b,p) => le ? b.readUInt16LE(p) : b.readUInt16BE(p);
17
+ const u32 = (b,p) => le ? b.readUInt32LE(p) : b.readUInt32BE(p);
18
+ const word = (b,p) => { const v = bits === 32 ? BigInt(u32(b,p)) : le ? b.readBigUInt64LE(p) : b.readBigUInt64BE(p); if (v > BigInt(Number.MAX_SAFE_INTEGER)) throw Error('ELF integer exceeds safe range'); return Number(v); };
19
+ const header = read(0, bits === 32 ? 52 : 64);
20
+ const phoff = word(header, bits === 32 ? 28 : 32), phentsize = u16(header, bits === 32 ? 42 : 54), phnum = u16(header, bits === 32 ? 44 : 56);
21
+ if (phnum > 4096 || (phnum && phentsize < (bits === 32 ? 32 : 56))) throw Error('unsupported ELF program header table');
22
+ const table = read(phoff, phnum * phentsize), segments = [];
23
+ for (let i = 0; i < phnum; i++) { const p = i * phentsize; const type = u32(table,p), flags = u32(table,p + (bits === 32 ? 24 : 4)); const offset = word(table,p + (bits === 32 ? 4 : 8)), vaddr = word(table,p + (bits === 32 ? 8 : 16)), filesz = word(table,p + (bits === 32 ? 16 : 32)); if (offset + filesz > size) throw Error('ELF segment outside file'); segments.push({ type, flags, offset, vaddr, filesz }); }
24
+ const mapped = (addr,n) => { const s = segments.find(x => x.type === 1 && addr >= x.vaddr && addr - x.vaddr + n <= x.filesz); if (!s) throw Error('ELF unmapped address'); return s.offset + addr - s.vaddr; };
25
+ const result = { format:'elf', bits, endian: le ? 'little' : 'big', machine: u16(header,18), type: u16(header,16), needed: [] };
26
+ const interp = segments.find(s => s.type === 3); if (interp && interp.filesz) result.interpreter = read(interp.offset,interp.filesz).toString('utf8').replace(/\0.*$/s,'');
27
+ for (const s of segments.filter(x => x.type === 4)) {
28
+ const b = read(s.offset,s.filesz); let p = 0;
29
+ while (p + 12 <= b.length) { const namesz = u32(b,p), descsz = u32(b,p+4), type = u32(b,p+8); p += 12; const a = Math.ceil(namesz/4)*4, d = Math.ceil(descsz/4)*4; if (p + a + d > b.length) break; if (type === 3 && b.subarray(p,p+namesz).toString('ascii').replace(/\0+$/,'') === 'GNU' && descsz <= 1024) result.buildId = b.subarray(p+a,p+a+descsz).toString('hex'); p += a+d; }
30
+ }
31
+ const dynamic = segments.find(s => s.type === 2);
32
+ if (dynamic) {
33
+ const b = read(dynamic.offset,dynamic.filesz), step = bits === 32 ? 8 : 16; let str = null, strsz = null, soname = null; const needed=[];
34
+ for (let p=0; p+step<=b.length; p+=step) { const tag=word(b,p), val=word(b,p+step/2); if (!tag) break; if(tag===5) str=val; else if(tag===10) strsz=val; else if(tag===1) needed.push(val); else if(tag===14) soname=val; }
35
+ if (str !== null && strsz !== null && strsz <= max) { const strings=read(mapped(str,strsz),strsz); const get = n => { if(n>=strings.length) throw Error('ELF string offset'); const end=strings.indexOf(0,n); if(end<0) throw Error('ELF unterminated string'); return strings.toString('utf8',n,end); }; result.needed=needed.map(get); if(soname!==null) result.soname=get(soname); }
36
+ }
37
+ result.go = require('./go-buildinfo').extractGoBuildInfo({read, segments, mapped, max});
38
+ if (!result.go) delete result.go;
39
+ return result;
40
+ } catch (error) { return { format:'elf', status:'unavailable', reason:error.message }; }
41
+ }
42
+ module.exports = { extractElfMetadataFile, MAX_SEGMENT };