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/README.md CHANGED
@@ -10,7 +10,7 @@
10
10
  [![CI](https://github.com/9pings/VigieVuln/actions/workflows/ci.yml/badge.svg)](https://github.com/9pings/VigieVuln/actions/workflows/ci.yml)
11
11
 
12
12
 
13
- **VigieVuln** is a polyglot dependency auditor built for **professional code audits**.
13
+ **VigieVuln 1.3.1** is a polyglot dependency auditor for code audits.
14
14
 
15
15
  It scans dependencies and **9 CMS/frameworks** in one pass without build tools, supports **air-gapped** workflows, detects private packages, binaries and certificates, and produces HTML, JSON and other reports.
16
16
 
@@ -31,6 +31,7 @@ It scans dependencies and **9 CMS/frameworks** in one pass without build tools,
31
31
  - **CMS & frameworks audited as instances**; Symfony, Laravel, WordPress, Drupal, Joomla, PrestaShop, TYPO3, Magento/Adobe Commerce and SPIP with per-instance inventory (core, plugins, themes, bundles, components) → [the dedicated guide](docs/CMS-FRAMEWORKS.md)
32
32
  - **Crypto material**; committed **certificates**, **private vs public keys** across PEM/OpenSSH/PuTTY/PGP and JKS/PKCS#12 keystores.
33
33
  - **Air-gapped flow**; **zero network under `--offline`** → [Benchmark](docs/BENCHMARK.md) · [Air-gapped](#air-gapped-audits)
34
+ - **Native image audits**; Docker/OCI archives, registries and rootfs inventories without Docker; Linux packages, ELF/Go metadata and publisher SBOMs, with explicit coverage. Image analysis in source scans is off by default; use `--images` or the separate `vigievuln image` command → [image guide](docs/IMAGES.md)
34
35
  - **Hosted proxy with a verified account**; `--set-proxy-cache vigievuln` → [hosted proxy](docs/USAGE.md#hosted-vigievuln-proxy)
35
36
  - **Project monitoring**; `vigievuln watch ./project --name 'My Project'` — one free project with up to **100 distinct direct dependency coordinates** → [monitoring guide](docs/USAGE.md#project-monitoring)
36
37
  - **Shared cache for a scanner fleet**; `vigievuln serve-cache` + `--proxy-cache` → [cache usage](docs/USAGE.md#shared-proxy-cache-server-serve-cache----proxy-cache)
@@ -43,6 +44,10 @@ It scans dependencies and **9 CMS/frameworks** in one pass without build tools,
43
44
 
44
45
  📖 **[Usage & all flags](docs/USAGE.md)** · **[Architecture](docs/ARCHITECTURE.md)** · **[Comparison vs other tools](docs/COMPARISON.md)** · **[Data sources](docs/DATA-SOURCES.md)**
45
46
 
47
+ > [!IMPORTANT]
48
+ > **Although VigieVuln is an excellent tool—comprehensive, rigorously tested, and regularly updated—it is still relatively new, and like any other scanner, it may occasionally produce errors.
49
+ > Whenever possible, cross-check important findings with another analysis tool — though, among the tools we compared, none offers reports as comprehensive as VigieVuln.**
50
+
46
51
  ## Quick start
47
52
 
48
53
  ```bash
@@ -50,22 +55,11 @@ npm install -g vigievuln
50
55
  vigievuln scan ./code # → ./vigievuln-report/cve-report.html
51
56
  ```
52
57
 
53
- A free [NVD API key](https://nvd.nist.gov/developers/request-an-api-key) (instant) gives 10× faster enrichment: `vigievuln --set-nvd-key YOUR_KEY`. A few common runs; full list via `vigievuln --help` or [docs/USAGE.md](docs/USAGE.md)
54
-
55
- ### Monitor a project
56
-
57
- Monitor your project's direct dependencies for new high, critical or known exploited vulnerabilities. Create and verify a [Vigie Vuln account](https://www.vigievuln.fr/account) first.
58
+ ### Faster scans using personal NVD API key
58
59
 
59
- ```bash
60
- vigievuln login # sign in and accept the terms
61
- vigievuln watch ./project --export deps.json # optional: review the inventory locally
62
- vigievuln watch ./project --name 'My Project' # upload or update the project
63
- vigievuln project status # check the monitoring status
64
- ```
65
-
66
- Review the inventory before sharing, enable alerts in your account and upload again when dependencies change. The free tier covers one project, 100 direct coordinates and a 0.5 MB descriptor; each upload renews monitoring for one month. [Monitoring guide](docs/USAGE.md#project-monitoring).
60
+ A free [NVD API key](https://nvd.nist.gov/developers/request-an-api-key) (instant) gives 10× faster enrichment: `vigievuln --set-nvd-key YOUR_KEY`. A few common runs; full list via `vigievuln --help` or [docs/USAGE.md](docs/USAGE.md)
67
61
 
68
- ### Official Vigie Vuln proxy cache
62
+ ### Faster scans using the VigieVuln DB European hosted cache
69
63
 
70
64
  Use [Vigie Vuln DB](https://www.vigievuln.fr/) as a European-hosted source for scans, including reviewed VigieVuln advisories for Maven and npm.
71
65
 
@@ -77,17 +71,17 @@ vigievuln setup --mode direct --sources all # switch back to direct sources
77
71
 
78
72
  The proxy receives package coordinates and CVE identifiers, not source code. Cached advisories remain usable offline; partial version evidence leaves other versions unknown. [Proxy guide](docs/USAGE.md#hosted-vigievuln-proxy).
79
73
 
80
- ### Interactive HTML samples
74
+ ### Include container images
81
75
 
82
- - **[Apache Dubbo 2.7.8 — open the report](https://9pings.github.io/VigieVuln/samples/dubbo.html)**: the project used for the report screenshot below, rescanned with VigieVuln 1.2.1; 105 Maven descriptors, direct/transitive CVEs, KEV matches, EOL and fix recommendations.
83
- - **[Multi-instance CMS & frameworks — open the report](https://9pings.github.io/VigieVuln/samples/multi-cms-frameworks.html)**: WordPress 6.4.2, Drupal 8.5.0, Symfony Demo (Symfony 7.1.1) and BookStack v24.10 (Laravel 10.48.22), with findings attributed to each instance.
76
+ Add `--images` to scan supported container images referenced by the project alongside its dependencies, without Docker; this option is off by default.
84
77
 
85
- These are standalone reports from real source scans, generated on **2026-11-04** with VigieVuln **1.2.1**. Dubbo uses the hosted proxy; the CMS sample uses its local cache offline and focuses on PHP dependencies. Missing Wordfence/Drupal advisory and WordPress checksum inputs are explicitly marked incomplete. [Sample scope, sources and reproduction commands](docs/samples/README.md).
78
+ ```bash
79
+ vigievuln scan ./code --images
80
+ ```
86
81
 
87
- > [!WARNING]
88
- > vigievuln is new and may still contain ( rare ) bugs. Treat its output as a strong first pass, **double-check anything critical**, and please [report issues](https://github.com/9pings/VigieVuln/issues); they get fixed fast.
82
+ The report keeps source and image findings in separate summaries and charts, highlighting vulnerable images and their most critical CVEs. [Image inputs, options and coverage](docs/IMAGES.md).
89
83
 
90
- ## Why use vigievuln for code audits?
84
+ ## Why use vigievuln ?
91
85
 
92
86
  An author-maintained comparison of audit workflows; see [`docs/COMPARISON.md`](docs/COMPARISON.md)
93
87
  for versions, sources and limitations. `⚠️` indicates partial or conditional support.
@@ -110,12 +104,7 @@ for versions, sources and limitations. `⚠️` indicates partial or conditional
110
104
  | **Share one cache across the fleet**, API keys server-side | ✅ `serve-cache` | ❌ | ⚠️ local DB | ⚠️ local DB | ⚠️ local DB | ⚠️ cloud |
111
105
 
112
106
 
113
- Offline dependency resolution depends on cached metadata. In the Dubbo test, a cold advisory seed alone produced 185 groups versus 734 with warm metadata and reported missing POMs; see the [benchmark](docs/BENCHMARK.md) for scope and warnings.
114
-
115
- **Deliberately not a goal: reachability.** A finding is a vulnerable version on the dependency
116
- graph, and the report says exactly that (in Methodology) instead of guessing at call paths. Deciding
117
- whether the vulnerable code is reachable in *this* application is the auditor's call, made with
118
- application context no scanner has.
107
+ **Deliberately not a goal: reachability.** ( That's an AI or human Job )
119
108
 
120
109
  ## More examples
121
110
 
@@ -134,39 +123,16 @@ vigievuln -s ./site --app-plugins wordpress --private-component wp-content/plugi
134
123
 
135
124
  > [!IMPORTANT]
136
125
  > **`--offline` reads the cache, it doesn't replace it.** On a *cold* cache there is nothing to
137
- > match against; an empty report is not evidence that the project is clean. Initialise it from
138
- > a seed or warm it online, then review coverage and freshness warnings in the offline report.
139
- > Cached advisories can match other applicable versions, but neither a partial cache nor an
140
- > old snapshot guarantees complete or current results.
126
+ > match against;
141
127
  > Air-gapped machines get their cache via [`--export-cache` / `--import-cache`](#air-gapped-audits).
142
128
 
143
- ## What it finds
144
-
145
- The report keeps the six root chapters. Sub-chapters appear only when they contain results and are numbered consecutively; application inventory and methodology remain available in scan context:
146
-
147
- | Chapter | Source | What it catches |
148
- | --- | --- | --- |
149
- | **0. Warnings** *(top)* | local heuristics | Missing lockfiles, unresolved Maven versions (BOM-managed), private packages absent from configured registries |
150
- | **Δ. Changes since baseline** *(top, with `--baseline`)* | diff vs prior JSON | New / fixed / unchanged findings per category + the list of **new production CVEs**; for repeat audits and `--fail-on-new` CI gating |
151
- | **1. CVE** *(X direct, Y indirect, Z dev)* | CVEProject + OSV.dev + Packagist + qualified publisher feeds + NVD/CPE | **Applications first when findings exist**; CMS/framework findings by instance and owner · **Production**; public CVE / GHSA in other prod deps, per ecosystem, per manifest, **prioritised** by CISA KEV + EPSS + CVSS · **Vendored JS vulns** ([retire.js](https://retirejs.github.io/)) — one row per physical library, linked CVEs + CWEs on the row, every advisory behind a click · **Dev** (`test`/`provided`, `dev`/`optional`/`peer`) · **Likely false positives** (CPE-filtered) |
152
- | **2. Unmanaged / unversioned components** | deps.dev + CIRCL (by checksum), retire.js, built-in X.509 | **Embedded binaries**; CVEs in libs shipped inside committed `.jar`/`.war`/`.ear` (fat-jars, shaded uber-jars) · **Native binaries** (`.dll`/`.exe`/`.so`/`.dylib`): available metadata and checksum evidence; metadata alone does not reliably identify a product or establish CVE applicability · **Vendored JavaScript** inventory (jQuery, Bootstrap, …) vulnerable *or not* · **Certificates & key material**; committed certs (expiry / weak key / weak signature / self-signed), **private vs public keys** (PEM/OpenSSH/PuTTY/PGP/SSH) and keystores, all parsed offline |
153
- | **3. Maintenance / EOL** *(X EOL, Y obsolete, Z outdated)* | endoflife.date · curated + registry flags · Maven Central / npm / Packagist / PyPI / NuGet | **End-of-Life** frameworks (+ an "Out of active support" band with `--eol-support`; Symfony/Laravel grouped as one row per framework; PHP runtime when the Composer constraint proves it), split **direct** (declared / parent-POM-inherited — bump these) vs **transitive** (bump the dep that pulls them in) · **Obsolete / deprecated / abandoned / yanked** · **Outdated** (newer version available, with release dates; direct deps only) |
154
- | **4. Licenses** *(opt-in: `--licenses`)* | registry metadata + Maven POMs → SPDX policy | Each dep's license normalised to SPDX and classified; copyleft (GPL/AGPL/LGPL/MPL), proprietary and unknown flagged for review |
155
- | **5. Fix Recommendations** | computed | Per-ecosystem pin recipes: Maven `<dependencyManagement>`, Gradle `constraints { }`, npm `overrides`, yarn `resolutions`, `composer require`, `pip install`, `dotnet add package` |
156
- | **6. Scan context & limitations** | provenance manifest + walk | **Scanned descriptors** (every manifest parsed) · **Ignored directories** (pruned paths + rule) · **Methodology, data sources & limitations** (data-source freshness, run config, explicit statement of **what vigievuln does *not* assess**) · **Application inventory & coverage** (also shown when no CVE matches) |
157
- | **Supply-chain risk** *(cross-cutting)* | OSV `MAL-…` + name heuristic | **Known-malicious** packages (always block the CI gate, any `--fail-on` level) and **suspected typosquats** (`--typosquat`: an npm/PyPI name one edit from a popular package; `lodahs`↔`lodash`) |
158
-
159
- The HTML report opens in any browser, contains every detail (CVSS vectors, references, full descriptions, CPE configurations, via-paths for transitives) and ships a Word-compatible `.doc` twin. Every match carries a **composite priority** (KEV-exploited > EPSS likelihood > CVSS severity), and the run can additionally emit a **CycloneDX 1.6 SBOM** (`--report-sbom`, vulnerabilities inline) and a **CSAF 2.0 VEX** (`--report-csaf`) for downstream tooling.
160
-
161
- <p align="center"><img src="docs/assets/report.png" alt="vigievuln HTML report; executive summary with severity tiles and a detailed CVE table with CWE, descriptions and fix versions" width="900"></p>
162
-
163
129
 
164
130
  ## CMS & frameworks
165
131
 
166
132
  See the [CMS coverage limits](docs/CMS-FRAMEWORKS.md#coverage-and-its-current-limits)
167
- and [shared-cache operating limits](docs/USAGE.md#shared-proxy-cache-server-serve-cache--proxy-cache).
133
+ and [shared-cache operating limits](docs/USAGE.md#shared-proxy-cache-server-serve-cache----proxy-cache).
168
134
 
169
- vigievuln doesn't just read the `composer.json` under a WordPress or Drupal site — it inventories the **instance**: core, plugins, themes, bundles and framework components with their observed versions, attributes every dependency CVE to the component that ships it, and reports each instance in its own sub-chapter — synthesis included even when it comes out clean. Any recognized layout is activated by the default `--app-plugins auto`; `none` opts out.
135
+ VigieVuln inventories the **instance**: core, plugins, themes, bundles and framework components with their observed versions, attributes dependency findings where ownership is established, and reports each instance in its own sub-chapter.
170
136
 
171
137
  | Product | Inventory | Advisory lane |
172
138
  | --- | --- | --- |
@@ -179,7 +145,7 @@ vigievuln doesn't just read the `composer.json` under a WordPress or Drupal site
179
145
  | **SPIP** | core (`$spip_version_branche` in `ecrire/inc_version.php`), dist plugins (`paquet.xml`), user plugins (`paquet.xml`/legacy `plugin.xml`) | **NVD product CVEs** (`cpe:2.3:a:spip:spip`) — the only machine-readable SPIP source; plugins stay honestly not-qualified |
180
146
  | **Joomla / Magento (Adobe Commerce)** | core, extensions/modules, themes | no machine-readable publisher feed exists; components locked as Composer packages read as covered by the **dependency lanes**, the rest stays honestly **not qualified**. A Magento source distribution reports its exact version from the root `composer.json` |
181
147
 
182
- Every advisory snapshot a live lane fetches is stamped and cached in the local SQLite database, **prepared from the air-gapped descriptor** by `cache prepare`, and reused automatically offline — the Wordfence API key never travels to the enclave. Private/custom components are inventoried separately and never sent to any publisher. → **[the dedicated guide](docs/CMS-FRAMEWORKS.md)** · [application usage](docs/USAGE.md#application-inventory-experimental)
148
+ Private/custom components are inventoried separately and never sent to any publisher. → **[the dedicated guide](docs/CMS-FRAMEWORKS.md)** · [application usage](docs/USAGE.md#application-inventory-experimental)
183
149
 
184
150
  ## Air-gapped audits
185
151
 
@@ -207,7 +173,22 @@ Review the descriptor before sharing and the report's coverage and freshness inf
207
173
  - [`docs/COMPARISON.md`](docs/COMPARISON.md); vs OSV-Scanner / Trivy / Grype / OWASP DC / Snyk, and how it stays build-free.
208
174
  - [`docs/BENCHMARK.md`](docs/BENCHMARK.md) — dated scanner comparisons on pinned projects, including warm and cold offline limitations.
209
175
  - [`docs/DATA-SOURCES.md`](docs/DATA-SOURCES.md); the public datasets vigievuln uses + their licenses.
210
- - [`CHANGELOG.md`](CHANGELOG.md) · [`CLAUDE.md`](CLAUDE.md); release history · code-level orientation for contributors.
176
+ - [`CHANGELOG.md`](CHANGELOG.md) · [`CLAUDE.md`](CLAUDE.md); current release notes · code-level orientation for contributors.
177
+
178
+ ### Interactive HTML samples
179
+
180
+ - **[Apache Dubbo 2.7.8 — open the report](https://9pings.github.io/VigieVuln/samples/dubbo.html)**: the project used for the report screenshot below, rescanned with VigieVuln 1.2.1; 105 Maven descriptors, direct/transitive CVEs, KEV matches, EOL and fix recommendations.
181
+ - **[Multi-instance CMS & frameworks — open the report](https://9pings.github.io/VigieVuln/samples/multi-cms-frameworks.html)**: WordPress 6.4.2, Drupal 8.5.0, Symfony Demo (Symfony 7.1.1) and BookStack v24.10 (Laravel 10.48.22), with findings attributed to each instance.
182
+
183
+ These are standalone reports from real source scans, generated on **2026-11-04** with VigieVuln **1.2.1**. Dubbo uses the hosted proxy; the CMS sample uses its local cache offline and focuses on PHP dependencies. Missing Wordfence/Drupal advisory and WordPress checksum inputs are explicitly marked incomplete. [Sample scope, sources and reproduction commands](docs/samples/README.md).
184
+
185
+ ### Resolution and coverage
186
+
187
+ - **Gradle:** without a lock, POM-based resolution can differ from Gradle. Locks cover only their recorded configurations, which may mix runtime, tests and build tools.
188
+ - **Python:** exact pins are checked; transitives require a supported resolved lockfile or complete inventory.
189
+ - **Coverage:** missing metadata or unavailable advisory sources can cause omissions or false positives. Review report warnings.
190
+
191
+ See [usage](docs/USAGE.md) and [measured results](docs/BENCHMARK.md).
211
192
 
212
193
  ## Contributing
213
194
 
@@ -217,14 +198,6 @@ with the coordinate and the manifest snippet that produced it. Dev setup, ground
217
198
  codec extension point → [`CONTRIBUTING.md`](CONTRIBUTING.md). Vulnerabilities in vigievuln
218
199
  itself → [`SECURITY.md`](SECURITY.md) (please report privately).
219
200
 
220
- **On AI assistance:** this codebase is written with heavy use of Claude Code; [`CLAUDE.md`](CLAUDE.md)
221
- in the repo root is exactly what it looks like. The bar it's held to is the one you can check
222
- yourself: the test suite (`npm test`), the zero-network guarantee enforced by a tripwire test and
223
- and the dated comparisons and limitations documented in [`docs/BENCHMARK.md`](docs/BENCHMARK.md). `vigievuln` itself uses **no LLM at runtime**; findings come from public
224
- vulnerability databases and deterministic parsers, and no report text is generated. Full
225
- statement, including where review actually caught a bad finding →
226
- [`AI_POLICY.md`](AI_POLICY.md). Where the code doesn't meet that bar, that's a bug report I want.
227
-
228
201
  ## License
229
202
 
230
203
  Apache-2.0; see [`LICENSE`](LICENSE).
@@ -7,7 +7,8 @@ const {openCacheDb}=require('./cache-db');
7
7
  const {packageName}=require('./advisory-store');
8
8
  const packageScope=(ecosystem,name)=>'project-package:'+JSON.stringify([ecosystem,ecosystem==='Maven'?name:packageName(ecosystem,name)]);
9
9
 
10
- function buildProjectScope(resolved,{applications=[],cves=[]}={}){
10
+ function buildProjectScope(resolved,{applications=[],cves=[],imageReferences=[],images=true,preferSbom=false}={}){
11
+ const refs=require("./deps-descriptor").serializeImageReferences(imageReferences,{images});
11
12
  const {osvEcosystemFor,osvPkgName}=require('./osv');
12
13
  const packages=new Map();
13
14
  for(const d of resolved.values()){
@@ -16,12 +17,33 @@ function buildProjectScope(resolved,{applications=[],cves=[]}={}){
16
17
  if(typeof name!=='string'||!name||name.includes('undefined'))continue;
17
18
  packages.set(JSON.stringify([ecosystem,name]),{ecosystem,name});
18
19
  }
19
- const project={schema:1,packages:[...packages.values()],cves:[...new Set(cves.filter(id=>/^CVE-\d{4}-\d{4,7}$/.test(id||'')))],retainAllNvd:applications.length>0||[...resolved.values()].some(d=>d.provenance==='binary'||d.ecosystem==='binary')};
20
+ const project={schema:1,packages:[...packages.values()],cves:[...new Set(cves.filter(id=>/^CVE-\d{4}-\d{4,7}$/.test(id||'')))],imageReferences:refs,imagePreferSbom:!!preferSbom,retainAllNvd:refs.length>0||applications.length>0||[...resolved.values()].some(d=>d.provenance==='binary'||d.ecosystem==='binary')};
20
21
  return project;
21
22
  }
22
23
 
24
+ function imageInventoryKeys(item,preferSbom=false){
25
+ const crypto=require('node:crypto'),hash=x=>crypto.createHash('sha256').update(JSON.stringify(x)).digest('hex');
26
+ const p=require('./image-registry').parseReference(item.reference),canonical=`${p.registry}/${p.repository}@${p.reference}`;
27
+ return [hash([canonical,item.platform||null,!!preferSbom]),hash([item.reference,item.platform||null,!!preferSbom])];
28
+ }
29
+ function validateImageSnapshotCompleteness(scope,repository){
30
+ const refs=require('./deps-descriptor').serializeImageReferences(scope?.imageReferences);
31
+ if(scope?.imageReferences != null && (!Array.isArray(scope.imageReferences) || scope.imageReferences.length!==refs.length))throw Error('invalid prepared image references');
32
+ for(const item of refs){
33
+ const entries=imageInventoryKeys(item,scope.imagePreferSbom).map(key=>repository.get('image-inventory',key)).filter(Boolean);
34
+ if(!entries.length)throw Error(`prepared image inventory is missing: ${item.reference}`);
35
+ let valid=false;
36
+ for(const entry of entries)try{require('./artifacts/scan').validateSnapshot(entry.value);valid=true;break}catch{}
37
+ if(!valid)throw Error(`prepared image inventory is invalid: ${item.reference}`);
38
+ }
39
+ return {images:refs.length};
40
+ }
41
+
23
42
  function buildProjectSnapshot(sourceDir,targetDir,project){
24
- if(project?.schema!==1||!Array.isArray(project.packages)||!project.packages.length)throw Error('invalid or empty prepared project scope');
43
+ if(project?.schema!==1||!Array.isArray(project.packages)||(!project.packages.length && !project.imageReferences?.length))throw Error('invalid or empty prepared project scope');
44
+ const imageRefs=require('./deps-descriptor').serializeImageReferences(project.imageReferences);
45
+ if(project.imageReferences?.length && imageRefs.length!==project.imageReferences.length)throw Error('invalid prepared image reference');
46
+ if(imageRefs.length)validateImageSnapshotCompleteness(project,require('./cache-repository').createCacheRepository(sourceDir));
25
47
  const db=openCacheDb({cacheDir:targetDir});
26
48
  const quote=s=>`'${s.replace(/'/g,"''")}'`;
27
49
  try{
@@ -59,13 +81,19 @@ function buildProjectSnapshot(sourceDir,targetDir,project){
59
81
  INSERT INTO advisory_queries SELECT q.* FROM source.advisory_queries q JOIN wanted_packages w ON w.ecosystem=q.ecosystem AND w.query_key=q.name_key;
60
82
  INSERT INTO advisory_query_ids SELECT q.* FROM source.advisory_query_ids q JOIN wanted_packages w ON w.ecosystem=q.ecosystem AND w.query_key=q.name_key;
61
83
  INSERT INTO advisory_coverage SELECT * FROM source.advisory_coverage WHERE source<>'osv';
62
- INSERT INTO cache_entries SELECT * FROM source.cache_entries WHERE namespace NOT IN ('airgap-project','airgap-cve-index') AND NOT (namespace='catalogue' AND key IN ('euvd-targeted','epss'));
84
+ INSERT INTO cache_entries SELECT * FROM source.cache_entries WHERE namespace NOT IN ('airgap-project','airgap-cve-index','image-inventory') AND NOT (namespace='catalogue' AND (key IN ('euvd-targeted','certfr-targeted','kev-targeted','epss') OR key GLOB 'image-tags-*'));
63
85
  INSERT INTO cache_snapshots SELECT * FROM source.cache_snapshots;
64
86
  INSERT INTO cve_lookup SELECT l.* FROM source.cve_lookup l WHERE EXISTS(SELECT 1 FROM wanted_packages w WHERE w.ecosystem='Maven' AND ((l.kind='package' AND l.lookup_key=lower(w.package_key)) OR (l.kind='product' AND l.lookup_key=lower(substr(w.package_key,instr(w.package_key,':')+1)))));
65
87
  INSERT INTO package_versions SELECT * FROM source.package_versions;
66
88
  INSERT INTO resource_bodies SELECT * FROM source.resource_bodies;
67
89
  INSERT INTO resource_chunks SELECT * FROM source.resource_chunks;
68
90
  INSERT INTO resources SELECT * FROM source.resources;`);
91
+ // Image inventories are scoped to reviewed references and platforms; other
92
+ // projects' registry identities and inventories must not enter the archive.
93
+ const insertImage=db.prepare("INSERT OR IGNORE INTO cache_entries SELECT * FROM source.cache_entries WHERE namespace='image-inventory' AND key=?");
94
+ for(const item of imageRefs)for(const prefer of [false,true])for(const key of imageInventoryKeys(item,prefer))insertImage.run(key);
95
+ const insertRegistry=db.prepare("INSERT OR IGNORE INTO cache_entries SELECT * FROM source.cache_entries WHERE namespace='catalogue' AND key=?");
96
+ for(const item of imageRefs){const ref=require('./image-registry').parseReference(item.reference),key='image-tags-'+require('node:crypto').createHash('sha256').update(`${ref.registry}/${ref.repository}`).digest('hex');insertRegistry.run(key);}
69
97
  if(!project.retainAllNvd)db.exec("UPDATE advisory_coverage SET complete=0,entry_json=json_set(entry_json,'$.complete',json('false')) WHERE source IN ('cveproject','cveproject-legacy')");
70
98
  // A project index proves coverage only for its exported package buckets.
71
99
  // Preserve the source timestamp and never claim global index completeness.
@@ -88,7 +116,7 @@ function buildProjectSnapshot(sourceDir,targetDir,project){
88
116
  // These per-CVE enrichments may contain observations from other projects.
89
117
  // Keep only CVEs actually encountered while preparing this descriptor.
90
118
  const keep=new Set(Array.isArray(project.cves)?project.cves:[]),zlib=require('node:zlib');
91
- const cached=db.prepare("SELECT * FROM source.cache_entries WHERE namespace='catalogue' AND key IN ('euvd-targeted','epss')").all();
119
+ const cached=db.prepare("SELECT * FROM source.cache_entries WHERE namespace='catalogue' AND key IN ('euvd-targeted','certfr-targeted','kev-targeted','epss')").all();
92
120
  const insertCache=db.prepare('INSERT INTO cache_entries(namespace,key,fetched_at,expires_at,stale,encoding,payload,metadata_json) VALUES(?,?,?,?,?,?,?,?)');
93
121
  for(const row of cached){
94
122
  const raw=row.encoding==='json+deflate'?zlib.inflateRawSync(row.payload,{maxOutputLength:134217728}):row.encoding==='json'?row.payload:null;
@@ -112,6 +140,6 @@ function buildProjectSnapshot(sourceDir,targetDir,project){
112
140
  db.exec('DETACH DATABASE source');
113
141
  db.exec('PRAGMA wal_checkpoint(TRUNCATE); PRAGMA journal_mode=DELETE');
114
142
  }finally{db.close()}
115
- return {packages:project.packages.length,fullNvd:!!project.retainAllNvd};
143
+ return {packages:project.packages.length,images:imageRefs.length,fullNvd:!!project.retainAllNvd};
116
144
  }
117
- module.exports={buildProjectScope,buildProjectSnapshot,packageScope};
145
+ module.exports={buildProjectScope,buildProjectSnapshot,validateImageSnapshotCompleteness,imageInventoryKeys,packageScope};
@@ -0,0 +1,12 @@
1
+ 'use strict';
2
+ // Preserve independent applicability proofs when sources describe one finding.
3
+ function applicabilityEvidence(...records){
4
+ const proofs=new Map();
5
+ for(const c of records){
6
+ for(const item of [...(c?.applicabilityEvidence||[]),...['historical','vendor','publisher'].flatMap(kind=>c?.[kind+'Evidence']?[{kind,evidence:c[kind+'Evidence']}]:[])]){
7
+ if(item && typeof item.kind==='string' && item.evidence && typeof item.evidence==='object')proofs.set(JSON.stringify(item),item);
8
+ }
9
+ }
10
+ return [...proofs.values()];
11
+ }
12
+ module.exports={applicabilityEvidence};
@@ -0,0 +1,58 @@
1
+ // Installed application metadata in an extracted image. Never execute package code.
2
+ const fs = require('fs');
3
+ const path = require('path');
4
+ const {makeDepRecord} = require('../dep-record');
5
+ const {isNpmPackageDescriptor,isProjectDescriptor} = require('./component-scope');
6
+ const MAX_METADATA = 16 * 1024 * 1024;
7
+ const handlers = [
8
+ {id:'npm', matches:(n,fp)=>n==='package.json' && isNpmPackageDescriptor(fp), parse:(text)=>{const j=JSON.parse(text);return j.name || j.version ? [{ecosystem:'npm',name:j.name,version:j.version}] : [];}},
9
+ {id:'composer-project', matches:(n,fp)=>n==='composer.json' && isProjectDescriptor(fp), parse:(text)=>{const j=JSON.parse(text);return j.name || j.version ? [{ecosystem:'composer',name:j.name,version:j.version}] : [];}},
10
+ {id:'pypi-project', matches:(n,fp)=>n==='pyproject.toml' && isProjectDescriptor(fp), parse:(text)=>{const j=require('smol-toml').parse(text),p=j.project || j.tool?.poetry || {};return p.name || p.version ? [{ecosystem:'pypi',name:p.name,version:p.version}] : [];}},
11
+ {id:'maven-project', matches:(n,fp)=>n==='pom.xml' && isProjectDescriptor(fp), async parse(text){const j=await require('xml2js').parseStringPromise(text),p=j.project;if(!p)return [];const parent=p.parent?.[0]||{},name=p.artifactId?.[0],namespace=p.groupId?.[0]||parent.groupId?.[0],version=p.version?.[0]||parent.version?.[0];if(!name)return [];if(!namespace || /\$\{/.test(String(namespace)+String(version)))throw Error('project coordinates are not literal');return [{ecosystem:'maven',namespace,name,version}];}},
12
+ {id:'pypi', matches:(n,fp)=>(n==='METADATA' && /\.dist-info$/i.test(path.basename(path.dirname(fp)))) || (n==='PKG-INFO' && /\.egg-info$/i.test(path.basename(path.dirname(fp)))), parse:(text)=>{const name=/^Name:\s*(.+)$/im.exec(text)?.[1]?.trim(), version=/^Version:\s*(.+)$/im.exec(text)?.[1]?.trim();return [{ecosystem:'pypi',name,version}];}},
13
+ {id:'composer', matches:(n,fp)=>n==='installed.json' && path.basename(path.dirname(fp))==='composer', parse:(text)=>{const j=JSON.parse(text), pkgs=Array.isArray(j)?j:j.packages;if(!Array.isArray(pkgs))throw Error('missing packages');return pkgs.map(p=>({ecosystem:'composer',name:p.name,version:p.version}));}},
14
+ {id:'composer-php', matches:(n,fp)=>n==='installed.php' && path.basename(path.dirname(fp))==='composer', parse:(text)=>{
15
+ // Composer's generated PHP is data, but parse literal version entries only.
16
+ // Never evaluate PHP or interpolate its expressions.
17
+ const re=/['"]([A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+)['"]\s*=>\s*(?:array\s*\(|\[)/g, starts=[]; let match;
18
+ while((match=re.exec(text))) starts.push({name:match[1],start:re.lastIndex});
19
+ return starts.map(item=>{let depth=1,end=item.start,quote=null;for(;end<text.length && depth;end++){const c=text[end];if(quote){if(c==='\\')end++;else if(c===quote)quote=null;continue}if(c==='\"'||c==="'"){quote=c;continue}if(c==='('||c==='[')depth++;else if(c===')'||c===']')depth--;}const block=depth?'':text.slice(item.start,end-1);const version=/['"]pretty_version['"]\s*=>\s*['"]([^'"\r\n]+)['"]/.exec(block)?.[1];return {ecosystem:'composer',name:item.name,version};});
20
+ }},
21
+ {id:'ruby', matches:(n,fp)=>n.endsWith('.gemspec') && path.dirname(fp).split(path.sep).includes('specifications'), parse:(text)=>{const name=/\b(?:s|spec)\.name\s*=\s*["']([^"']+)["']/.exec(text)?.[1],version=/\b(?:s|spec)\.version\s*=\s*(?:Gem::Version\.new\(\s*)?["']([^"']+)["']/.exec(text)?.[1];return [{ecosystem:'ruby',name,version}];}},
22
+ {id:'nuget', matches:n=>n.endsWith('.deps.json'), parse:(text)=>{const j=JSON.parse(text);return Object.entries(j.libraries||{}).filter(([,v])=>v?.type==='package').map(([key])=>{const i=key.lastIndexOf('/');return {ecosystem:'nuget',name:key.slice(0,i),version:key.slice(i+1)};});}},
23
+ ];
24
+ function valid(x) {return x && typeof x.name==='string' && x.name.trim() && typeof x.version==='string' && x.version.trim() && !/[\r\n\0]/.test(x.name+x.version);}
25
+ const archiveCollectors = [{id:'jar', async collect(root) {return require('../codecs/maven/jar-scan').scanEmbeddedJars(root,{defaultExcludes:false});}}];
26
+ async function collectInstalledApplications(root,opts={}) {
27
+ const activeHandlers=opts.handlers || handlers, archives=opts.archiveCollectors || archiveCollectors;
28
+ for(const h of activeHandlers) if(!h || typeof h.id!=='string' || typeof h.matches!=='function' || typeof h.parse!=='function') throw Error('Invalid installed metadata handler');
29
+ for(const h of archives) if(!h || typeof h.id!=='string' || typeof h.collect!=='function') throw Error('Invalid installed archive collector');
30
+ const deps=new Map(),warnings=[], coverage={files:0,records:0,handlers:{}}; const stack=[root], max=opts.maxMetadataBytes ?? MAX_METADATA;
31
+ function warning(fp,error) {warnings.push({type:'dependency-coverage',reason:'installed-metadata-error',manifestPath:fp,message:`installed metadata incomplete for ${fp}: ${error.message}`});}
32
+ function add(item,fp,source) {if(item.ecosystem==='composer' && typeof item.name==='string' && !item.namespace) {const slash=item.name.indexOf('/');if(slash>0)item={...item,namespace:item.name.slice(0,slash),name:item.name.slice(slash+1)};}if(!valid(item)){warning(fp,Error('missing package name or version'));return;} const dep=makeDepRecord({...item,manifestPath:fp,provenance:'installed',scope:'transitive'});dep.coordKey=`installed:${fp}:${item.ecosystem}:${item.name}@${item.version}`;dep.installEvidence={path:fp,source};deps.set(dep.coordKey,dep);}
33
+ while(stack.length) {const dir=stack.pop();let entries;try{entries=fs.readdirSync(dir,{withFileTypes:true})}catch(e){warning(dir,e);continue}for(const entry of entries){const fp=path.join(dir,entry.name);if(entry.isDirectory()){stack.push(fp);continue}if(!entry.isFile())continue;if(entry.name==='installed.php' && entries.some(e=>e.name==='installed.json' && e.isFile()))continue;for(const h of activeHandlers){if(!h.matches(entry.name,fp))continue;coverage.files++;coverage.handlers[h.id]=(coverage.handlers[h.id]||0)+1;try{const st=fs.statSync(fp);if(st.size>max)throw Error(`metadata exceeds ${max} bytes`);const parsed=await h.parse(fs.readFileSync(fp,'utf8'));for(const item of parsed)add(item,fp,h.id)}catch(e){warning(fp,e)}break;}}}
34
+ for(const collector of archives){try{const result=await collector.collect(root,opts);warnings.push(...(result.warnings||[]));coverage.handlers[collector.id]=(result.deps||[]).length;for(const item of result.deps||[]){const fp=item.manifestPaths?.[0]||root;if(!item.namespace && item.ecosystem==='maven'){warning(fp,Error('archive has no complete Maven coordinate'));continue}add({ecosystem:item.ecosystem,namespace:item.namespace,name:item.name,version:item.version},fp,collector.id);}}catch(e){warning(root,e)}}coverage.records=deps.size;coverage.complete=warnings.length===0;return {deps,warnings,coverage};
35
+ }
36
+ // Reclassify only an unidentifiable top-level JAR whose exact installed owner
37
+ // has itself been assessed. Corrupt archives and nested contents remain gaps.
38
+ function classifyOwnedArchiveWarnings(warnings, packages, assessedPackages) {
39
+ const assessed = assessedPackages instanceof Set ? assessedPackages : new Set();
40
+ const byPath = new Map();
41
+ const normalize = value => {
42
+ if(typeof value!=="string" || !value || value.includes("!") || value.includes("\\") || value.includes("\0") || value.split('/').includes('..'))return null;
43
+ return path.posix.normalize('/'+value.replace(/^\/+/,''));
44
+ };
45
+ for(const pkg of packages || []) {
46
+ if(!pkg?.manager || !pkg?.name || !pkg?.version || !assessed.has(`${pkg.manager}:${pkg.name}@${pkg.version}`))continue;
47
+ for(const owned of pkg.ownedPaths||[]) {const p=normalize(owned);if(p && !byPath.has(p))byPath.set(p,pkg);}
48
+ }
49
+ const remaining=[],informational=[];
50
+ for(const warning of warnings || []) {
51
+ const p=normalize(warning?.manifestPath);
52
+ const eligible=warning?.reason==='installed-metadata-error' && /\.jar$/i.test(p||'') && typeof warning.message==='string' && warning.message.endsWith(': archive has no complete Maven coordinate');
53
+ const owner=eligible?byPath.get(p):null;
54
+ if(owner)informational.push({warning,owner:{manager:owner.manager,name:owner.name,version:owner.version},path:p});else remaining.push(warning);
55
+ }
56
+ return {warnings:remaining,informational};
57
+ }
58
+ module.exports={collectInstalledApplications,handlers,archiveCollectors,classifyOwnedArchiveWarnings,MAX_METADATA};
@@ -0,0 +1,31 @@
1
+ 'use strict';
2
+
3
+ const IMAGE_COMPONENT_SCOPE='image-components/1';
4
+ const parts=value=>String(value||'').replace(/\\/g,'/').split('/').filter(Boolean);
5
+ const stores=new Set(['node_modules','vendor','site-packages','dist-packages','specifications','__pypackages__','.cache','.npm','.yarn','.m2','.gradle','.nuget']);
6
+ // Installed metadata is authoritative inside package stores; source manifests
7
+ // bundled there can be examples or fixtures belonging to the enclosing library.
8
+ const isProjectDescriptor=value=>!parts(value).some(n=>stores.has(n));
9
+
10
+ // Only a package root describes an installed npm component. Files such as
11
+ // pkg/dist/mjs/package.json set module-loading rules, not another package.
12
+ function isNpmPackageDescriptor(value) {
13
+ const names=parts(value);
14
+ if(names.at(-1)!=='package.json')return false;
15
+ const index=names.lastIndexOf('node_modules');
16
+ if(index<0)return true;
17
+ const tail=names.slice(index+1);
18
+ return tail[0]?.startsWith('@') ? tail.length===3 : tail.length===2 && !tail[0]?.startsWith('.');
19
+ }
20
+
21
+ function imageComponentRole(dep={}) {
22
+ if(dep.ecosystem==='system' || dep.ecosystem==='binary')return 'direct';
23
+ const source=dep.installEvidence?.source;
24
+ if(['pypi','composer','composer-php','ruby','nuget'].includes(source))return 'transitive';
25
+ if(dep.provenance==='binary-module')return dep.binaryEvidence?.original?.kind==='mod'?'direct':'transitive';
26
+ const paths=[dep.artifactPath,dep.installEvidence?.path,...(dep.manifestPaths||[])].filter(Boolean);
27
+ if(paths.some(p=>String(p).includes('!/') || parts(p).some(n=>stores.has(n)) || String(p).replace(/\\/g,'/').includes('usr/share/nodejs/')))return 'transitive';
28
+ return 'direct';
29
+ }
30
+
31
+ module.exports={IMAGE_COMPONENT_SCOPE,isNpmPackageDescriptor,isProjectDescriptor,imageComponentRole};
@@ -0,0 +1,108 @@
1
+ 'use strict';
2
+ // A presentation projection: distribution verdicts remain unchanged in the
3
+ // canonical findings and image inventory. Only explicit CVE relationships can
4
+ // produce CVE rows, with per-CVE enrichment kept separate.
5
+ const {computePriority}=require('../priority');
6
+ const CVE=/^CVE-\d{4}-\d{4,}$/i;
7
+ function isCve(id){return typeof id==='string' && CVE.test(id);}
8
+ function ids(cve){return [...new Set([cve?.id,...(cve?.aliases||[]),...(cve?.upstream||[])].filter(isCve).map(id=>id.toUpperCase()))];}
9
+ function rel(cve,id){return [cve.id,...(cve.aliases||[])].some(x=>String(x).toUpperCase()===id)?'identity':'upstream';}
10
+ function physical(dep,id){return JSON.stringify([dep.artifactTargetId,dep.ecosystem,dep.manager,dep.namespace || dep.groupId,dep.name || dep.artifactId,dep.version,dep.architecture,dep.artifactPath || dep.manifestPaths?.[0] || null,id]);}
11
+ function advisory(match,id){
12
+ const c=match.cve,notice=match.advisoryId || c.id;
13
+ if(!notice || String(notice).toUpperCase()===id)return null;
14
+ return {id:notice,fixVersion:c.fixVersion || null,description:c.description || c.summary || null,sourceURL:c.advisorySource || null,relationship:rel(c,id)};
15
+ }
16
+ function project(match,id){
17
+ const original=match.cve,relation=rel(original,id),record=(original.nvdEvidence?.records||[]).find(r=>String(r.id).toUpperCase()===id);
18
+ const perCve=(original.cveEvidence||[]).find(r=>String(r.id).toUpperCase()===id);
19
+ const identity=relation==='identity';
20
+ const c={...original,id,aliases:[],upstream:[],related:[],distributionAdvisories:[]};
21
+ // Preserve advisory identifiers from an observed OSV/GHSA source across the
22
+ // CVE-only projection; an alias alone does not prove a source was consulted.
23
+ const observedSources=String(match.source||'').split('+');
24
+ c.sourceGhsaIds=observedSources.some(s=>/^(?:osv|ghsa|github-publisher)$/i.test(s))?[...new Set([original.id,...(original.aliases||[]),match.advisoryId].filter(x=>typeof x==='string' && /^GHSA-[a-z0-9-]+$/i.test(x)))]:[];
25
+ const gnas=new Set(observedSources.map(s=>/^GCVE:GNA-(\d+)$/i.exec(s)?.[1]).filter(x=>x!==undefined));
26
+ c.sourceGcveIds=[...new Set([...(original.sourceGcveIds||[]),original.gcveEvidence?.kind==='derived-alias'?null:original.gcve,original.id,match.advisoryId].filter(x=>{const m=typeof x==='string'&&/^GCVE-(\d+)-[a-z0-9\-/]+$/i.exec(x);return m && gnas.has(m[1]);}))];
27
+ // Aggregated advisory risk can reflect another CVE. Replace it with this CVE's
28
+ // own evidence before computing priority.
29
+ for(const key of ['score','severity','severitySource','scoreSource','cvssVector','cvssVersion','cwes','nvdRefs','nvdEvidence','riskEvidence','kev','kevEvidence','kevDateAdded','kevDueDate','kevRansomware','epssScore','epssPercentile','epssEvidence','priority','description','summary','published','modified','advisorySource','osvRefs','fixVersion','cveEvidence','euvd','certfr','gcve','gcveEvidence','euvdEvidence','certfrEvidence','euvdDetails','euvdDetailsEvidence'])delete c[key];
30
+ const euvd=require('../euvd').normalizeEuvdDetailDates(perCve?.euvdDetails);
31
+ const hasOwn=identity && String(original.id||'').toUpperCase()===id;
32
+ const ownScore=hasOwn && original.score!=null, nvdScore=!ownScore && record?.score!=null, euvdScore=!ownScore && !nvdScore && euvd?.score!=null;
33
+ const scoreSource=ownScore?'original':nvdScore?'nvd':euvdScore?'euvd':null;
34
+ if(ownScore && original.scoreSource)c.scoreSource=original.scoreSource;
35
+ c.score=ownScore?original.score:nvdScore?record.score:euvdScore?euvd.score:null;
36
+ const knownOriginal=hasOwn && original.severity && original.severity!=='UNKNOWN';
37
+ const knownNvd=record?.severity && record.severity!=='UNKNOWN';
38
+ c.severity=knownOriginal?original.severity:knownNvd && scoreSource!=='euvd'?record.severity:scoreSource==='euvd' && euvd?.severity?euvd.severity:'UNKNOWN';
39
+ if(knownOriginal && original.severitySource)c.severitySource=original.severitySource;
40
+ if(hasOwn && String(original.riskEvidence?.id||'').toUpperCase()===id && ((ownScore && original.scoreSource===original.riskEvidence.source) || (knownOriginal && original.severitySource===original.riskEvidence.source)))c.riskEvidence={...original.riskEvidence};
41
+ c.description=record?.description || euvd?.description || (hasOwn ? original.description : '') || '';
42
+ if(euvd){c.euvdDetails={...euvd};if(euvdScore){c.scoreSource='euvd';if(!knownOriginal && c.severity!=='UNKNOWN')c.severitySource='euvd';c.riskEvidence={source:'euvd',id,relationship:'identity'};}}
43
+ const vectorSource=scoreSource==='original'?original:scoreSource==='nvd'?record:scoreSource==='euvd'?euvd:null;
44
+ for(const k of ['cvssVector','cvssVersion'])if(vectorSource?.[k]!=null)c[k]=vectorSource[k];
45
+ for(const k of ['cwes','published','modified']){const v=record?.[k] ?? euvd?.[k] ?? (hasOwn ? original[k] : null);if(v!=null)c[k]=v;}
46
+ if(record){c.nvdEvidence={...record,records:[{...record}]};if(record.references)c.nvdRefs=record.references;
47
+ if(!c.riskEvidence && (nvdScore || (!knownOriginal && knownNvd && scoreSource!=='euvd')))c.riskEvidence={source:'nvd',id,relationship:'identity'};}
48
+ if(perCve){c.cveEvidence=[{...perCve,...(euvd?{euvdDetails:euvd}:{})}];for(const key of ['kev','kevDateAdded','kevDueDate','kevRansomware','epssScore','epssPercentile','euvd','certfr','gcve','gcveEvidence','euvdEvidence','certfrEvidence','euvdDetailsEvidence'])if(perCve[key]!==undefined)c[key]=perCve[key];}
49
+ if(perCve?.gcveAlias){c.gcveAlias=perCve.gcveAlias;if(hasOwn && original.gcve && original.gcve!==perCve.gcveAlias){c.gcve=original.gcve;if(original.gcveEvidence)c.gcveEvidence=original.gcveEvidence;}else c.gcve=perCve.gcveAlias;}
50
+ // Older exported inventories can contain single-CVE evidence but not cveEvidence.
51
+ for(const [evidenceKey,keys] of [['kevEvidence',['kev','kevDateAdded','kevDueDate','kevRansomware']],['epssEvidence',['epssScore','epssPercentile']]]){
52
+ if(String(original[evidenceKey]?.id||'').toUpperCase()===id)for(const key of keys)if(c[key]===undefined && original[key]!==undefined)c[key]=original[key];
53
+ }
54
+ // Legacy findings may have only one CVE and no per-CVE observation array.
55
+ // Their original risk is safe to reuse only when it cannot represent another
56
+ // linked CVE and no explicit evidence points elsewhere.
57
+ if(hasOwn && !perCve && ids(original).length===1){
58
+ for(const key of ['euvd','certfr','gcve','gcveEvidence','euvdEvidence','certfrEvidence'])if(original[key]!==undefined)c[key]=original[key];
59
+ for(const [evidenceKey,keys] of [['kevEvidence',['kev','kevDateAdded','kevDueDate','kevRansomware']],['epssEvidence',['epssScore','epssPercentile']]]){
60
+ const evidenceId=original[evidenceKey]?.id;
61
+ if(!evidenceId || String(evidenceId).toUpperCase()===id)for(const key of keys)if(c[key]===undefined && original[key]!==undefined)c[key]=original[key];
62
+ }
63
+ }
64
+ const notice=advisory(match,id);if(notice)c.distributionAdvisories.push(notice);
65
+ c.fixVersion=notice?.fixVersion || (hasOwn ? original.fixVersion || null : null);
66
+ c.priority=computePriority(c);
67
+ return {...match,cve:c};
68
+ }
69
+ function merge(target,incoming){
70
+ const a=target.cve,b=incoming.cve;
71
+ a.applicabilityEvidence=require('../applicability-evidence').applicabilityEvidence(a,b);
72
+ a.sourceGhsaIds=[...new Set([...(a.sourceGhsaIds||[]),...(b.sourceGhsaIds||[])])];
73
+ a.sourceGcveIds=[...new Set([...(a.sourceGcveIds||[]),...(b.sourceGcveIds||[])])];
74
+ // Source applicability evidence survives consolidation with a distribution
75
+ // advisory that projects to the same CVE row.
76
+ for(const key of ['historicalEvidence','vendorEvidence'])if(!a[key] && b[key])a[key]=b[key];
77
+ target.source=[...new Set([target.source,incoming.source].flatMap(s=>String(s||'').split('+')).filter(Boolean))].sort().join('+');
78
+ for(const notice of b.distributionAdvisories){if(!a.distributionAdvisories.some(n=>n.id===notice.id && n.fixVersion===notice.fixVersion && n.sourceURL===notice.sourceURL))a.distributionAdvisories.push(notice);}
79
+ for(const field of ['references','relatedAdvisories'])a[field]=[...new Map([...(a[field]||[]),...(b[field]||[])].map(item=>[typeof item==='string'?item:item?.url,item]).filter(([url])=>url)).values()];
80
+ const fixes=[...new Set([a.fixVersion ?? null,b.fixVersion ?? null,...a.distributionAdvisories.map(n=>n.fixVersion ?? null)])];a.fixVersion=fixes.length===1 ? fixes[0] : null;
81
+ const compatibleScore=a.score==null || b.score==null || a.score===b.score;
82
+ const compatibleSeverity=!a.severity || a.severity==='UNKNOWN' || !b.severity || b.severity==='UNKNOWN' || a.severity===b.severity;
83
+ let acceptedRisk=false;
84
+ if((!a.severity || a.severity==='UNKNOWN') && b.severity && b.severity!=='UNKNOWN' && compatibleScore){a.severity=b.severity;if(b.severitySource)a.severitySource=b.severitySource;acceptedRisk=true;}
85
+ if(a.score==null && b.score!=null && compatibleSeverity){a.score=b.score;if(b.scoreSource)a.scoreSource=b.scoreSource;acceptedRisk=true;}
86
+ if(acceptedRisk && !a.riskEvidence && b.riskEvidence)a.riskEvidence={...b.riskEvidence};
87
+ if(compatibleScore && compatibleSeverity)for(const key of ['cvssVector','cvssVersion'])if(!a[key] && b[key])a[key]=b[key];
88
+ for(const key of ['description','cwes','nvdRefs','nvdEvidence','published','modified','kev','kevDateAdded','kevDueDate','kevRansomware','epssScore','epssPercentile','euvd','certfr','gcve','gcveEvidence','gcveAlias','euvdEvidence','certfrEvidence','euvdDetails','euvdDetailsEvidence'])if((a[key]==null || a[key]==='' || Array.isArray(a[key])&&!a[key].length) && b[key]!=null)a[key]=b[key];
89
+ for(const entry of b.cveEvidence||[]){
90
+ if(!Array.isArray(a.cveEvidence))a.cveEvidence=[];
91
+ const existing=a.cveEvidence.find(x=>x.id===entry.id);
92
+ if(!existing)a.cveEvidence.push({...entry});
93
+ else for(const [key,value] of Object.entries(entry))if((existing[key]==null || existing[key]==='') && value!=null)existing[key]=value;
94
+ }
95
+ a.priority=computePriority(a);
96
+ }
97
+ function projectImageCves(matches){
98
+ const output=[],byKey=new Map();
99
+ for(const match of matches||[]){
100
+ if(!match?.dep?.artifactTargetId || match.dep.ecosystem!=='system'){output.push(match);continue;}
101
+ for(const id of ids(match.cve)){
102
+ const key=physical(match.dep,id),row=project(match,id),existing=byKey.get(key);
103
+ if(existing)merge(existing,row);else{byKey.set(key,row);output.push(row);}
104
+ }
105
+ }
106
+ return output;
107
+ }
108
+ module.exports={projectImageCves};
@@ -0,0 +1,87 @@
1
+ 'use strict';
2
+ // Enrichment adds independent risk evidence; it never changes OS advisory verdicts.
3
+ const {createCacheRepository}=require('../cache-repository');
4
+ const {getCacheDir}=require('../cache-directory');
5
+ function cveIds(match){return [...new Set([match.cve?.id,...(match.cve?.aliases||[]),...(match.cve?.upstream||[])].filter(id=>/^CVE-\d{4}-\d{4,}$/i.test(id||'')))];}
6
+ function cveId(match){return cveIds(match)[0]||null;}
7
+ function relationship(cve,id){return cve.id===id || (cve.aliases||[]).includes(id) ? 'identity' : 'upstream';}
8
+ function proxies(matches){return matches.flatMap(m=>cveIds(m).map(id=>({...m,cve:{id}})));}
9
+ function cveEvidence(cve,id){if(!Array.isArray(cve.cveEvidence))cve.cveEvidence=[];let value=cve.cveEvidence.find(x=>x.id===id);if(!value){value={id};cve.cveEvidence.push(value);}return value;}
10
+ // Hosted proxies offer a targeted KEV operation. Persist both positive and
11
+ // negative observations so an air-gapped replay does not need a global catalog.
12
+ async function enrichKevCopies(copies,opts){
13
+ const repo=createCacheRepository(opts.cacheDir||getCacheDir()),wanted=[...new Set(copies.map(m=>m.cve.id))];
14
+ const targeted=repo.get('catalogue','kev-targeted')?.value || {entries:{}};
15
+ const hosted=opts.hostedProxy ?? require('../providers').hasHostedProxy();let failure=null;
16
+ if(hosted && !opts.offline){
17
+ try{
18
+ for(let i=0;i<wanted.length;i+=100){
19
+ const group=wanted.slice(i,i+100),res=await require('../providers').getResource('kev','cves',{ids:group},{fetcher:opts.fetcher,noStore:true,streaming:true});
20
+ if(!res.ok)throw Error(`KEV HTTP ${res.status}`);const body=await res.json();if(!Array.isArray(body?.items))throw Error('invalid KEV response');
21
+ const seen=new Map();for(const row of body.items){if(!row || !group.includes(row.cve) || seen.has(row.cve) || (row.kev!=null && (typeof row.kev!=='object'||Array.isArray(row.kev))))throw Error('invalid KEV record');seen.set(row.cve,row.kev||null);}
22
+ const stamp=Date.parse(res.headers?.get?.('x-fad-proxy-fetched-at')||'');const fetchedAt=Number.isFinite(stamp)&&stamp>0&&stamp<=Date.now()+300000?stamp:null,stale=fetchedAt===null || res.headers?.get?.('x-fad-proxy')==='stale';
23
+ for(const id of group)targeted.entries[id]={item:seen.get(id)||null,fetchedAt,stale};
24
+ repo.put('catalogue','kev-targeted',targeted);
25
+ }
26
+ }catch(error){failure=`KEV targeted lookup failed: ${error.message}`;}
27
+ }else if(!opts.offline)await require('../kev').enrichKev(copies,{...opts,hostedProxy:false});
28
+ else await require('../kev').enrichKev(copies,{...opts,offline:true});
29
+ const bulk=repo.get('catalogue','kev')?.value,hasBulk=!!bulk?.body?.byId && typeof bulk.body.byId==='object';let missing=0,stale=0;
30
+ for(const copy of copies){const saved=targeted.entries[copy.cve.id];if(saved && (opts.offline||hosted)){
31
+ if(saved.stale || !Number.isFinite(saved.fetchedAt) || saved.fetchedAt<=0 || saved.fetchedAt>Date.now()+300000)stale++;const item=saved.item;if(item){copy.cve.kev=true;copy.cve.kevDateAdded=item.dateAdded;copy.cve.kevDueDate=item.dueDate;copy.cve.kevRansomware=item.ransomware;}
32
+ }else if(!hasBulk)missing++;
33
+ }
34
+ return {complete:!failure && !missing && !stale,reason:failure || (missing?`KEV observations unavailable for ${missing} eligible CVE(s).`:`KEV observations stale for ${stale} eligible CVE(s).`)};
35
+ }
36
+
37
+ const enrichmentAdapters=[
38
+ {id:'kev',async run(matches,opts){const copies=proxies(matches);if(!copies.length)return {complete:true,notApplicable:true,reason:'No eligible CVE identifier.'};const state=await enrichKevCopies(copies,opts);const byId=new Map(copies.map(x=>[x.cve.id,x]));for(const m of matches){for(const id of cveIds(m)){const item=byId.get(id)?.cve;if(item?.kev){const record=cveEvidence(m.cve,id);for(const key of ['kev','kevDateAdded','kevDueDate','kevRansomware'])if(item[key]!==undefined)record[key]=item[key];}}const hit=cveIds(m).map(id=>byId.get(id)).find(x=>x?.cve.kev);if(hit?.cve.kev){m.cve.kev=true;m.cve.kevDateAdded=hit.cve.kevDateAdded;m.cve.kevDueDate=hit.cve.kevDueDate;m.cve.kevRansomware=hit.cve.kevRansomware;m.cve.kevEvidence={source:'kev',id:hit.cve.id,relationship:relationship(m.cve,hit.cve.id)};}}return state;}},
39
+ {id:'epss',async run(matches,opts){const copies=proxies(matches);if(!copies.length)return {complete:true,notApplicable:true,reason:'No eligible CVE identifier.'};await require('../epss').enrichEpss(copies,opts);const cache=createCacheRepository(opts.cacheDir||getCacheDir()).get('catalogue','epss')?.value;const byId=new Map(copies.map(x=>[x.cve.id,x]));for(const m of matches){for(const id of cveIds(m)){const item=byId.get(id)?.cve;if(item?.epssScore!=null || item?.epssPercentile!=null){const record=cveEvidence(m.cve,id);if(item.epssScore!=null)record.epssScore=item.epssScore;if(item.epssPercentile!=null)record.epssPercentile=item.epssPercentile;}}const hit=cveIds(m).map(id=>byId.get(id)).filter(Boolean).sort((a,b)=>(b.cve.epssScore??-1)-(a.cve.epssScore??-1))[0];if(hit?.cve.epssScore!=null){m.cve.epssScore=hit.cve.epssScore;m.cve.epssEvidence={source:'epss',id:hit.cve.id,relationship:relationship(m.cve,hit.cve.id)};}if(hit?.cve.epssPercentile!=null)m.cve.epssPercentile=hit.cve.epssPercentile;}return {complete:matches.every(m=>cveIds(m).every(id=>Object.hasOwn(cache?.entries||{},id))),reason:'EPSS scores are not cached for all eligible CVEs.'};}},
40
+ {id:'nvd',async run(matches,opts){
41
+ const copies=proxies(matches).map(m=>({...m,cve:{id:m.cve.id,severity:'UNKNOWN'}}));if(!copies.length)return {complete:true,notApplicable:true,reason:'No eligible CVE identifier.'};
42
+ const nvd=require('../nvd'),absent=new Set(),failures=[];
43
+ await nvd.enrichMatches(copies,{...opts,onAbsent:id=>absent.add(id),onFailure:(id,reason)=>failures.push({id,reason}),onProgress:(completed,total)=>opts.onEnrichmentProgress?.({source:'nvd',completed,total})});
44
+ if(opts.offline)for(const copy of copies)if(nvd.hasCachedAbsence(copy.cve.id,{cacheDir:opts.cacheDir,offline:true}))absent.add(copy.cve.id);
45
+ const byId=new Map(copies.map(x=>[x.cve.id,x]));
46
+ for(const m of matches){
47
+ const ids=cveIds(m), enriched=ids.map(id=>byId.get(id)).filter(x=>x?.source?.split('+').includes('nvd'));
48
+ for(const id of ids){const evidence=byId.get(id)?.cve?.nvdRecordEvidence;if(evidence)cveEvidence(m.cve,id).nvdRecordEvidence=evidence;}
49
+ const records=enriched.map(x=>({id:x.cve.id,relationship:relationship(m.cve,x.cve.id),severity:x.cve.severity||null,score:x.cve.score??null,
50
+ cvssVector:x.cve.cvssVector||null,cvssVersion:x.cve.cvssVersion||null,description:x.cve.description||null,
51
+ cwes:x.cve.cwes||[],references:x.cve.nvdRefs||[],published:x.cve.published||null,modified:x.cve.modified||null}));
52
+ if(records.length){m.cve.nvdEvidence={...records[0],records};const sources=new Set(String(m.source||'').split('+').filter(Boolean));sources.add('nvd');m.source=[...sources].sort().join('+');}
53
+ // A single explicitly related CVE can fill missing display metadata without
54
+ // changing the distribution's advisory identity or affected/fixed verdict.
55
+ // Multi-CVE advisories retain separate records and never acquire a made-up
56
+ // aggregate severity or score.
57
+ if(ids.length===1 && enriched.length===1){
58
+ const item=enriched[0].cve;let riskFilled=false;
59
+ if((!m.cve.severity || String(m.cve.severity).toUpperCase()==='UNKNOWN') && item.severity && item.severity!=='UNKNOWN'){
60
+ m.cve.severity=item.severity; m.cve.severitySource='nvd'; riskFilled=true;
61
+ }
62
+ if(m.cve.score==null && typeof item.score==='number' && Number.isFinite(item.score)){m.cve.score=item.score;m.cve.scoreSource='nvd';riskFilled=true;}
63
+ if(riskFilled)m.cve.riskEvidence={source:'nvd',id:item.id,relationship:relationship(m.cve,item.id)};
64
+ if(!m.cve.cvssVector && item.cvssVector)m.cve.cvssVector=item.cvssVector;
65
+ if(!m.cve.cvssVersion && item.cvssVersion)m.cve.cvssVersion=item.cvssVersion;
66
+ if(!m.cve.cwes?.length && item.cwes?.length)m.cve.cwes=item.cwes;
67
+ if(!m.cve.nvdRefs?.length && item.nvdRefs?.length)m.cve.nvdRefs=item.nvdRefs;
68
+ if(!m.cve.published && item.published)m.cve.published=item.published;
69
+ if(!m.cve.modified && item.modified)m.cve.modified=item.modified;
70
+ }
71
+ }
72
+ const complete=matches.every(m=>cveIds(m).every(id=>absent.has(id)||m.cve.nvdEvidence?.records.some(record=>record.id===id)));
73
+ return {complete,result:copies.every(copy=>absent.has(copy.cve.id))?'no-match':undefined,reason:failures.length?`NVD lookup failed: ${[...new Set(failures.map(f=>f.reason))].join('; ')} (${failures.length} CVE(s)).`:'NVD metadata unavailable for some eligible CVEs.'};
74
+ }},
75
+ ];
76
+ async function enrichArtifactFindings(matches,opts={}) {
77
+ const registry=opts.enrichmentAdapters||enrichmentAdapters;if(!Array.isArray(registry)||registry.some(a=>!a||typeof a.id!=='string'||typeof a.run!=='function'))throw Error('Invalid enrichment adapter registry');
78
+ const selected=opts.enrich || ['nvd','kev','epss','gcve','euvd','certfr'];if(!Array.isArray(selected))throw Error('Invalid enrichment selection');
79
+ const coverage=[],warnings=[];
80
+ const european=opts.europeanAdapters || require('../finding-enrichment').europeanAdapters;
81
+ const europeanIds=new Set(european.map(a=>a.id));
82
+ for(const id of selected.filter(id=>!europeanIds.has(id))){if(opts[id]===false){const reason=`${id} is excluded by the selected source profile.`;coverage.push({capability:'sources',collector:id,execution:'not-applicable',result:'not-consulted',expected:false,reason});continue;}const adapter=registry.find(a=>a.id===id);if(!adapter)throw Error(`Unknown enrichment adapter ${id}`);try{opts.onEnrichmentProgress?.({source:id,completed:0,total:matches.length});const result=await adapter.run(matches,opts);opts.onEnrichmentProgress?.({source:id,completed:matches.length,total:matches.length});if(!result||typeof result.complete!=='boolean')throw Error('Invalid enrichment result');coverage.push({capability:'sources',collector:id,execution:result.notApplicable?'not-applicable':result.complete?'completed':'partial',result:result.notApplicable?'not-applicable':result.complete?(result.result||'available'):'indeterminate',...(result.notApplicable?{expected:false,reason:result.reason}:!result.complete?{reason:result.reason}:{})});if(!result.complete)warnings.push({type:'source-unavailable',capability:'sources',source:id,message:result.reason||`${id} unavailable`});}catch(e){coverage.push({capability:'sources',collector:id,execution:'partial',result:'indeterminate',reason:e.message});warnings.push({type:'source-unavailable',capability:'sources',source:id,message:`${id}: ${e.message}`});}}
83
+ const selectedEuropean=european.filter(a=>selected.includes(a.id) || (a.parent && selected.includes(a.parent)));
84
+ if(selectedEuropean.length){const result=await require('../finding-enrichment').enrichEuropeanFindings(matches,{...opts,europeanAdapters:selectedEuropean});coverage.push(...result.coverage);warnings.push(...result.warnings);}
85
+ return {coverage,warnings};
86
+ }
87
+ module.exports={enrichArtifactFindings,enrichmentAdapters,cveId};