vigievuln 1.3.2 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (375) hide show
  1. package/CHANGELOG.md +63 -0
  2. package/README.md +34 -19
  3. package/completions/vigievuln.bash +14 -3
  4. package/completions/vigievuln.zsh +11 -8
  5. package/data/fingerprints/index.js +80 -0
  6. package/data/fingerprints/interpreters/javascript/bun.json +23 -0
  7. package/data/fingerprints/interpreters/javascript/deno.json +10 -0
  8. package/data/fingerprints/interpreters/javascript/electron.json +20 -0
  9. package/data/fingerprints/interpreters/javascript/gjs.json +8 -0
  10. package/data/fingerprints/interpreters/javascript/javascriptcore.json +14 -0
  11. package/data/fingerprints/interpreters/javascript/jscgtk.json +10 -0
  12. package/data/fingerprints/interpreters/javascript/node.json +26 -0
  13. package/data/fingerprints/interpreters/javascript/nwjs.json +8 -0
  14. package/data/fingerprints/interpreters/javascript/webkitgtk.json +10 -0
  15. package/data/fingerprints/interpreters/javascript/wpewebkit.json +10 -0
  16. package/data/fingerprints/interpreters/languages/dotnet.json +8 -0
  17. package/data/fingerprints/interpreters/languages/erlang.json +9 -0
  18. package/data/fingerprints/interpreters/languages/gawk.json +10 -0
  19. package/data/fingerprints/interpreters/languages/guile.json +9 -0
  20. package/data/fingerprints/interpreters/languages/java.json +8 -0
  21. package/data/fingerprints/interpreters/languages/julia.json +9 -0
  22. package/data/fingerprints/interpreters/languages/lua.json +11 -0
  23. package/data/fingerprints/interpreters/languages/luajit.json +10 -0
  24. package/data/fingerprints/interpreters/languages/perl.json +11 -0
  25. package/data/fingerprints/interpreters/languages/php.json +22 -0
  26. package/data/fingerprints/interpreters/languages/powershell.json +17 -0
  27. package/data/fingerprints/interpreters/languages/pypy.json +8 -0
  28. package/data/fingerprints/interpreters/languages/python.json +24 -0
  29. package/data/fingerprints/interpreters/languages/r.json +9 -0
  30. package/data/fingerprints/interpreters/languages/racket.json +9 -0
  31. package/data/fingerprints/interpreters/languages/raku.json +8 -0
  32. package/data/fingerprints/interpreters/languages/ruby.json +21 -0
  33. package/data/fingerprints/interpreters/languages/tcl.json +9 -0
  34. package/data/fingerprints/interpreters/shells/bash.json +10 -0
  35. package/data/fingerprints/interpreters/shells/dash.json +8 -0
  36. package/data/fingerprints/interpreters/shells/fish.json +9 -0
  37. package/data/fingerprints/interpreters/shells/ksh.json +8 -0
  38. package/data/fingerprints/interpreters/shells/zsh.json +9 -0
  39. package/data/fingerprints/services/databases/clickhouse.json +8 -0
  40. package/data/fingerprints/services/databases/elasticsearch.json +8 -0
  41. package/data/fingerprints/services/databases/etcd.json +9 -0
  42. package/data/fingerprints/services/databases/mariadb.json +9 -0
  43. package/data/fingerprints/services/databases/memcached.json +9 -0
  44. package/data/fingerprints/services/databases/mongo.json +8 -0
  45. package/data/fingerprints/services/databases/mysql.json +9 -0
  46. package/data/fingerprints/services/databases/opensearch.json +8 -0
  47. package/data/fingerprints/services/databases/postgres.json +18 -0
  48. package/data/fingerprints/services/databases/redis.json +9 -0
  49. package/data/fingerprints/services/databases/valkey.json +8 -0
  50. package/data/fingerprints/services/dns-directory/bind.json +8 -0
  51. package/data/fingerprints/services/dns-directory/dnsmasq.json +8 -0
  52. package/data/fingerprints/services/dns-directory/slapd.json +8 -0
  53. package/data/fingerprints/services/dns-directory/unbound.json +8 -0
  54. package/data/fingerprints/services/mail/cyrus.json +8 -0
  55. package/data/fingerprints/services/mail/dovecot.json +8 -0
  56. package/data/fingerprints/services/mail/exim.json +9 -0
  57. package/data/fingerprints/services/mail/opendkim.json +8 -0
  58. package/data/fingerprints/services/mail/opensmtpd.json +8 -0
  59. package/data/fingerprints/services/mail/postfix.json +8 -0
  60. package/data/fingerprints/services/mail/rspamd.json +8 -0
  61. package/data/fingerprints/services/mail/sendmail.json +8 -0
  62. package/data/fingerprints/services/messaging/kafka.json +8 -0
  63. package/data/fingerprints/services/messaging/mosquitto.json +8 -0
  64. package/data/fingerprints/services/messaging/nats.json +9 -0
  65. package/data/fingerprints/services/messaging/rabbitmq.json +8 -0
  66. package/data/fingerprints/services/remote-access/dropbear.json +8 -0
  67. package/data/fingerprints/services/remote-access/openssh.json +10 -0
  68. package/data/fingerprints/services/remote-access/proftpd.json +8 -0
  69. package/data/fingerprints/services/remote-access/samba.json +8 -0
  70. package/data/fingerprints/services/remote-access/vsftpd.json +8 -0
  71. package/data/fingerprints/services/web-proxies/apache.json +18 -0
  72. package/data/fingerprints/services/web-proxies/caddy.json +9 -0
  73. package/data/fingerprints/services/web-proxies/envoy.json +8 -0
  74. package/data/fingerprints/services/web-proxies/haproxy.json +10 -0
  75. package/data/fingerprints/services/web-proxies/lighttpd.json +8 -0
  76. package/data/fingerprints/services/web-proxies/nginx.json +14 -0
  77. package/data/fingerprints/services/web-proxies/squid.json +8 -0
  78. package/data/fingerprints/services/web-proxies/tomcat.json +8 -0
  79. package/data/fingerprints/services/web-proxies/traefik.json +9 -0
  80. package/data/fingerprints/services/web-proxies/varnish.json +8 -0
  81. package/lib/README.md +51 -0
  82. package/lib/{coverage-diagnostics.js → advisories/coverage-diagnostics.js} +1 -1
  83. package/lib/{cve-match.js → advisories/cve-match.js} +17 -12
  84. package/lib/{advisory-fixes.js → advisories/fixes.js} +1 -1
  85. package/lib/{advisory-freshness.js → advisories/freshness.js} +5 -1
  86. package/lib/{gap-adjudicate.js → advisories/gap-adjudicate.js} +3 -3
  87. package/lib/{native-package-match.js → advisories/native-package-match.js} +20 -11
  88. package/lib/{native-source-prepare.js → advisories/native-source-prepare.js} +15 -12
  89. package/lib/{native-advisories.js → advisories/native.js} +15 -13
  90. package/lib/{advisory-store-sqlite.js → advisories/store-sqlite.js} +5 -5
  91. package/lib/{advisory-store.js → advisories/store.js} +2 -2
  92. package/lib/{application-exports.js → applications/exports.js} +1 -1
  93. package/lib/{application-inventory.js → applications/inventory.js} +3 -1
  94. package/lib/applications/layout.js +199 -0
  95. package/lib/{application-providers → applications}/live-snapshot.js +10 -10
  96. package/lib/{application-plugins → applications/plugins}/drupal.js +2 -2
  97. package/lib/applications/plugins/ghost.js +36 -0
  98. package/lib/{application-plugins → applications/plugins}/index.js +1 -1
  99. package/lib/{application-plugins → applications/plugins}/prestashop.js +73 -15
  100. package/lib/applications/plugins/redmine.js +24 -0
  101. package/lib/{application-plugins → applications/plugins}/runner.js +89 -59
  102. package/lib/{application-plugins → applications/plugins}/spip.js +4 -4
  103. package/lib/{application-plugins → applications/plugins}/symfony.js +1 -1
  104. package/lib/{application-plugins → applications/plugins}/typo3.js +2 -2
  105. package/lib/{application-plugins → applications/plugins}/wave2-common.js +1 -1
  106. package/lib/{application-plugins → applications/plugins}/wordpress.js +52 -18
  107. package/lib/{application-providers → applications}/snapshot-cache.js +1 -1
  108. package/lib/{cms-snapshot-warm.js → applications/snapshot-warm.js} +21 -8
  109. package/lib/artifacts/access-warnings.js +24 -0
  110. package/lib/artifacts/applications.js +39 -8
  111. package/lib/artifacts/component-scope.js +12 -3
  112. package/lib/artifacts/cve-view.js +8 -5
  113. package/lib/artifacts/disk-wasm.mjs +3 -0
  114. package/lib/artifacts/disk.js +188 -0
  115. package/lib/artifacts/elf-product.js +215 -0
  116. package/lib/artifacts/enrichment.js +31 -17
  117. package/lib/artifacts/go-main-identity.js +135 -36
  118. package/lib/artifacts/go-publisher-advisories.js +4 -3
  119. package/lib/artifacts/image-products.js +181 -0
  120. package/lib/artifacts/index.js +36 -13
  121. package/lib/artifacts/install-version.js +44 -0
  122. package/lib/artifacts/inventory-scope.js +53 -3
  123. package/lib/artifacts/pe-product.js +28 -0
  124. package/lib/artifacts/product-advisories.js +212 -0
  125. package/lib/artifacts/product-catalog.js +67 -0
  126. package/lib/artifacts/release-catalogues.js +149 -0
  127. package/lib/artifacts/release-versions.js +101 -0
  128. package/lib/artifacts/remediation-report.js +1 -1
  129. package/lib/artifacts/report-inventory.js +17 -2
  130. package/lib/artifacts/report-path.js +29 -0
  131. package/lib/artifacts/report.js +85 -32
  132. package/lib/artifacts/retire.js +3 -3
  133. package/lib/artifacts/risk-report.js +12 -8
  134. package/lib/artifacts/sbom.js +33 -4
  135. package/lib/artifacts/scan.js +316 -69
  136. package/lib/artifacts/system-apps.js +98 -0
  137. package/lib/artifacts/system-maintenance.js +101 -0
  138. package/lib/artifacts/system-module-updates.js +104 -0
  139. package/lib/artifacts/system-report.js +232 -0
  140. package/lib/{airgap-project.js → cache/airgap-project.js} +25 -10
  141. package/lib/{cache-archive-sqlite.js → cache/archive.js} +6 -5
  142. package/lib/{cache-db.js → cache/db.js} +1 -1
  143. package/lib/{dump-format.js → cache/dump-format.js} +2 -2
  144. package/lib/{json-cache.js → cache/json.js} +1 -1
  145. package/lib/{proxy-cache.js → cache/proxy-cache.js} +9 -9
  146. package/lib/{proxy-scope.js → cache/proxy-scope.js} +1 -1
  147. package/lib/{record-freshness.js → cache/record-freshness.js} +1 -1
  148. package/lib/{cache-repository.js → cache/repository.js} +1 -1
  149. package/lib/{resource-cache → cache/resource}/engine.js +23 -16
  150. package/lib/{resource-cache → cache/resource}/fs-store.js +2 -2
  151. package/lib/{resource-cache → cache/resource}/sqlite-store.js +3 -3
  152. package/lib/{resource-cache → cache/resource}/validate.js +20 -5
  153. package/lib/{sqlite-driver.js → cache/sqlite-driver.js} +7 -5
  154. package/lib/certs/scan.js +17 -11
  155. package/lib/cli-collect.js +262 -0
  156. package/lib/cli-command-routing.js +30 -13
  157. package/lib/cli-groups.js +1 -1
  158. package/lib/cli-image.js +158 -47
  159. package/lib/cli-project-commands.js +10 -10
  160. package/lib/cli-setup.js +8 -8
  161. package/lib/cli-watch.js +3 -3
  162. package/lib/codecs/binary/elf-metadata.js +6 -0
  163. package/lib/codecs/binary/metadata.js +1 -1
  164. package/lib/codecs/binary/pe-metadata.js +47 -11
  165. package/lib/codecs/binary/scan.js +12 -4
  166. package/lib/codecs/binary.codec.js +1 -1
  167. package/lib/codecs/composer/platform.js +2 -2
  168. package/lib/codecs/composer/registry.js +12 -18
  169. package/lib/codecs/composer.codec.js +6 -5
  170. package/lib/codecs/go/parse.js +1 -1
  171. package/lib/codecs/go/registry.js +7 -7
  172. package/lib/codecs/go.codec.js +2 -2
  173. package/lib/codecs/gradle/parse.js +1 -1
  174. package/lib/codecs/gradle/versionless.js +2 -2
  175. package/lib/codecs/gradle.codec.js +7 -7
  176. package/lib/codecs/index.js +1 -1
  177. package/lib/{maven-airgap.js → codecs/maven/airgap.js} +4 -4
  178. package/lib/{maven-bom.js → codecs/maven/bom.js} +3 -3
  179. package/lib/codecs/maven/jar-scan.js +4 -4
  180. package/lib/{maven-license.js → codecs/maven/license.js} +2 -2
  181. package/lib/{core.js → codecs/maven/pom.js} +22 -11
  182. package/lib/{maven-reactor.js → codecs/maven/reactor.js} +18 -12
  183. package/lib/{transitive.js → codecs/maven/transitive.js} +79 -34
  184. package/lib/{maven-version.js → codecs/maven/version.js} +1 -1
  185. package/lib/codecs/maven.codec.js +18 -14
  186. package/lib/codecs/npm/collect.js +55 -8
  187. package/lib/codecs/npm/manifest-kind.js +16 -0
  188. package/lib/codecs/npm/parse.js +23 -7
  189. package/lib/codecs/npm/registry.js +28 -14
  190. package/lib/codecs/npm.codec.js +5 -5
  191. package/lib/codecs/nuget/registry.js +7 -7
  192. package/lib/codecs/nuget.codec.js +4 -4
  193. package/lib/codecs/pypi/registry.js +7 -7
  194. package/lib/codecs/pypi.codec.js +4 -4
  195. package/lib/codecs/recipes.js +2 -2
  196. package/lib/codecs/ruby/registry.js +7 -7
  197. package/lib/codecs/ruby.codec.js +2 -2
  198. package/lib/config.js +1 -1
  199. package/lib/{attribution.js → findings/attribution.js} +3 -3
  200. package/lib/findings/cve-descriptions.js +144 -0
  201. package/lib/{cve-record-coverage.js → findings/cve-record-coverage.js} +46 -41
  202. package/lib/{diff.js → findings/diff.js} +0 -0
  203. package/lib/{finding-enrichment.js → findings/enrichment.js} +45 -32
  204. package/lib/{eu-refs.js → findings/eu-refs.js} +3 -3
  205. package/lib/{gate.js → findings/gate.js} +1 -1
  206. package/lib/{malware.js → findings/malware.js} +30 -7
  207. package/lib/{merge-sources.js → findings/merge.js} +57 -9
  208. package/lib/{priority.js → findings/priority.js} +3 -3
  209. package/lib/findings/risk-evidence.js +24 -0
  210. package/lib/findings/severity.js +16 -0
  211. package/lib/{finding-summary.js → findings/summary.js} +5 -2
  212. package/lib/{suppress.js → findings/suppress.js} +2 -2
  213. package/lib/images/local-docker.js +72 -0
  214. package/lib/{image-network.js → images/network.js} +26 -16
  215. package/lib/{image-references.js → images/references.js} +29 -11
  216. package/lib/{image-registry.js → images/registry.js} +18 -9
  217. package/lib/{source-image-scan.js → images/source-scan.js} +3 -3
  218. package/lib/images/temp-roots.js +23 -0
  219. package/lib/{image-update.js → images/update.js} +3 -3
  220. package/lib/{dep-record.js → inventory/dep-record.js} +2 -2
  221. package/lib/{deps-descriptor.js → inventory/deps-descriptor.js} +3 -3
  222. package/lib/{descriptor-refs.js → inventory/descriptor-refs.js} +1 -1
  223. package/lib/{embedded.js → inventory/embedded.js} +4 -3
  224. package/lib/{license-policy.js → inventory/license-policy.js} +2 -2
  225. package/lib/{manifest-copy.js → inventory/manifest-copy.js} +2 -2
  226. package/lib/{module-names.js → inventory/module-names.js} +1 -1
  227. package/lib/{package-versions.js → inventory/package-versions.js} +2 -2
  228. package/lib/{parallel-walk.js → inventory/parallel-walk.js} +1 -1
  229. package/lib/{path-filter.js → inventory/path-filter.js} +1 -1
  230. package/lib/{private-deps.js → inventory/private-deps.js} +1 -1
  231. package/lib/{project-descriptor.js → inventory/project-descriptor.js} +3 -0
  232. package/lib/{purl.js → inventory/purl.js} +2 -2
  233. package/lib/{unmanaged.js → inventory/unmanaged.js} +6 -3
  234. package/lib/{commercial-support.js → maintenance/commercial-support.js} +5 -5
  235. package/lib/{outdated.js → maintenance/outdated.js} +20 -20
  236. package/lib/options-env.js +1 -1
  237. package/lib/{system-inventory/alpine-tracker.js → providers/alpine/tracker.js} +27 -7
  238. package/lib/{certfr.js → providers/certfr/enrich.js} +9 -9
  239. package/lib/{cve-download.js → providers/cveproject/download.js} +56 -36
  240. package/lib/{cve-legacy-ranges.js → providers/cveproject/legacy-ranges.js} +1 -1
  241. package/lib/{cve-npm-proxy.js → providers/cveproject/npm-proxy.js} +5 -5
  242. package/lib/{cve-packages-proxy.js → providers/cveproject/packages-proxy.js} +6 -6
  243. package/lib/{cve-version-verdict.js → providers/cveproject/version-verdict.js} +2 -2
  244. package/lib/{system-inventory/current-debian.js → providers/debian/current.js} +6 -6
  245. package/lib/{system-inventory/historical-debian.js → providers/debian/historical.js} +6 -6
  246. package/lib/providers/{debian.js → debian/index.js} +1 -0
  247. package/lib/{application-providers/drupal-advisories.js → providers/drupal/advisories.js} +13 -36
  248. package/lib/providers/{drupal.js → drupal/index.js} +4 -0
  249. package/lib/providers/{eol.js → eol/index.js} +1 -1
  250. package/lib/{epss.js → providers/epss/enrich.js} +16 -13
  251. package/lib/providers/{epss.js → epss/index.js} +2 -2
  252. package/lib/{euvd.js → providers/euvd/enrich.js} +13 -13
  253. package/lib/{system-inventory/freexian-ela.js → providers/freexian/ela.js} +6 -6
  254. package/lib/providers/{freexian.js → freexian/index.js} +3 -3
  255. package/lib/{system-inventory/freexian-release-evidence.js → providers/freexian/release-evidence.js} +8 -5
  256. package/lib/{system-inventory/freexian-tracker.js → providers/freexian/tracker.js} +33 -9
  257. package/lib/{gcve-feed.js → providers/gcve/feed.js} +4 -4
  258. package/lib/{gcve.js → providers/gcve/id.js} +1 -1
  259. package/lib/{gcve-index.js → providers/gcve/local-index.js} +4 -4
  260. package/lib/{application-providers/github-advisories.js → providers/github/advisories.js} +6 -2
  261. package/lib/providers/{github.js → github/index.js} +3 -1
  262. package/lib/{github-publisher-maven.js → providers/github/publisher-maven.js} +1 -1
  263. package/lib/providers/{go.js → go/index.js} +1 -1
  264. package/lib/{hash-id.js → providers/hashid/identify.js} +7 -7
  265. package/lib/providers/{hashid.js → hashid/index.js} +1 -1
  266. package/lib/providers/index.js +18 -13
  267. package/lib/{kev.js → providers/kev/enrich.js} +12 -9
  268. package/lib/{maven-cache.js → providers/maven/cache.js} +3 -3
  269. package/lib/providers/{maven.js → maven/index.js} +5 -3
  270. package/lib/{maven-presence.js → providers/maven/presence.js} +5 -5
  271. package/lib/{maven-repo.js → providers/maven/repo.js} +38 -21
  272. package/lib/providers/mit-kerberos/index.js +6 -0
  273. package/lib/{system-inventory/nginx-advisories.js → providers/nginx/advisories.js} +3 -3
  274. package/lib/providers/{npm.js → npm/index.js} +1 -1
  275. package/lib/providers/{nuget.js → nuget/index.js} +1 -1
  276. package/lib/{cpe.js → providers/nvd/cpe.js} +35 -47
  277. package/lib/{nvd.js → providers/nvd/enrich.js} +41 -40
  278. package/lib/providers/{nvd.js → nvd/index.js} +18 -4
  279. package/lib/{nvd-package-ranges.js → providers/nvd/package-ranges.js} +38 -22
  280. package/lib/{osv-db.js → providers/osv/db.js} +18 -16
  281. package/lib/providers/{osv.js → osv/index.js} +1 -1
  282. package/lib/{osv.js → providers/osv/query.js} +150 -80
  283. package/lib/providers/package-releases/index.js +26 -0
  284. package/lib/{packagist-audit.js → providers/packagist/audit.js} +31 -11
  285. package/lib/providers/{packagist.js → packagist/index.js} +1 -1
  286. package/lib/{proxy-throttle.js → providers/proxy-throttle.js} +17 -9
  287. package/lib/providers/{pypi.js → pypi/index.js} +1 -1
  288. package/lib/providers/redhat/bzip2.js +167 -0
  289. package/lib/providers/redhat/errata.js +75 -0
  290. package/lib/providers/redhat/index.js +10 -0
  291. package/lib/providers/redhat/oval.js +70 -0
  292. package/lib/providers/redhat/unfixed.js +127 -0
  293. package/lib/{registries.js → providers/registries.js} +4 -4
  294. package/lib/{retire.js → providers/retire/scan.js} +18 -18
  295. package/lib/providers/{ruby.js → ruby/index.js} +1 -1
  296. package/lib/providers/rubysec/advisories.js +177 -0
  297. package/lib/providers/rubysec/index.js +9 -0
  298. package/lib/{snyk.js → providers/snyk/client.js} +2 -2
  299. package/lib/{application-providers/spip-advisories.js → providers/spip/advisories.js} +5 -13
  300. package/lib/{vigievuln-advisories.js → providers/vigievuln/advisories.js} +4 -4
  301. package/lib/providers/wolfi/index.js +10 -0
  302. package/lib/providers/wolfi/secdb.js +47 -0
  303. package/lib/{application-providers/wordfence-client.js → providers/wordfence/client.js} +4 -4
  304. package/lib/providers/{wordfence.js → wordfence/index.js} +1 -1
  305. package/lib/{application-providers/wordfence-projection.js → providers/wordfence/projection.js} +14 -5
  306. package/lib/{resource-cache/wordfence.js → providers/wordfence/resource-cache.js} +2 -2
  307. package/lib/{application-providers/wordfence-v3.js → providers/wordfence/v3.js} +4 -5
  308. package/lib/providers/{wordpress.js → wordpress/index.js} +5 -0
  309. package/lib/providers/wpvulnerability/assess.js +181 -0
  310. package/lib/providers/wpvulnerability/index.js +12 -0
  311. package/lib/{charts.js → reports/charts.js} +25 -18
  312. package/lib/{csaf-export.js → reports/csaf-export.js} +16 -11
  313. package/lib/{cve-report.js → reports/cve-report.js} +453 -228
  314. package/lib/reports/detail.js +55 -0
  315. package/lib/{i18n.js → reports/i18n.js} +38 -2
  316. package/lib/{report-integrity.js → reports/integrity.js} +1 -1
  317. package/lib/{json-export.js → reports/json-export.js} +95 -24
  318. package/lib/{report-notices.js → reports/notices.js} +11 -6
  319. package/lib/{sarif-export.js → reports/sarif-export.js} +15 -10
  320. package/lib/{sbom-export.js → reports/sbom-export.js} +16 -11
  321. package/lib/{scan-completeness.js → scan/completeness.js} +1 -1
  322. package/lib/scan/coverage.js +114 -0
  323. package/lib/{provenance.js → scan/provenance.js} +12 -5
  324. package/lib/scan/reliability.js +157 -0
  325. package/lib/{source-health.js → scan/source-health.js} +52 -20
  326. package/lib/{source-profile.js → scan/source-profile.js} +3 -3
  327. package/lib/{hosted-proxy.js → service/hosted-proxy.js} +3 -3
  328. package/lib/{project-client.js → service/project-client.js} +20 -2
  329. package/lib/source-input.js +58 -0
  330. package/lib/system-inventory/advisories.js +89 -16
  331. package/lib/system-inventory/collect.js +33 -10
  332. package/lib/system-inventory/distribution-sources.js +32 -15
  333. package/lib/system-inventory/package-applicability.js +51 -0
  334. package/lib/system-inventory/targeted.js +8 -5
  335. package/lib/ui.js +11 -0
  336. package/package.json +49 -2
  337. package/vigievuln.js +483 -352
  338. package/lib/cache-archive.js +0 -676
  339. package/lib/osv-legacy.js +0 -57
  340. package/lib/risk-evidence.js +0 -18
  341. package/lib/scan-coverage.js +0 -61
  342. /package/lib/{application-plugins → applications/plugins}/joomla.js +0 -0
  343. /package/lib/{application-plugins → applications/plugins}/laravel.js +0 -0
  344. /package/lib/{application-plugins → applications/plugins}/magento.js +0 -0
  345. /package/lib/{application-plugins → applications/plugins}/plugin.interface.js +0 -0
  346. /package/lib/{application-plugins → applications/plugins}/select.js +0 -0
  347. /package/lib/{advisory-compression.js → cache/advisory-compression.js} +0 -0
  348. /package/lib/{compression-dictionary.js → cache/compression-dictionary.js} +0 -0
  349. /package/lib/{cache-directory.js → cache/directory.js} +0 -0
  350. /package/lib/{cache-policy.js → cache/policy.js} +0 -0
  351. /package/lib/{resource-cache → cache/resource}/snapshot-projection.js +0 -0
  352. /package/lib/{cache-startup.js → cache/startup.js} +0 -0
  353. /package/lib/{ruby-version.js → codecs/ruby/version.js} +0 -0
  354. /package/lib/{applicability-evidence.js → findings/applicability-evidence.js} +0 -0
  355. /package/lib/{line-stream.js → inventory/line-stream.js} +0 -0
  356. /package/lib/{package-metadata.js → inventory/package-metadata.js} +0 -0
  357. /package/lib/providers/{alpine.js → alpine/index.js} +0 -0
  358. /package/lib/providers/{certfr.js → certfr/index.js} +0 -0
  359. /package/lib/{native-cna-identities.js → providers/cveproject/cna-identities.js} +0 -0
  360. /package/lib/providers/{euvd.js → euvd/index.js} +0 -0
  361. /package/lib/providers/{gcve.js → gcve/index.js} +0 -0
  362. /package/lib/providers/{kev.js → kev/index.js} +0 -0
  363. /package/lib/providers/{nginx.js → nginx/index.js} +0 -0
  364. /package/lib/{nvd-bulk.js → providers/nvd/bulk.js} +0 -0
  365. /package/lib/providers/{osvdb.js → osvdb/index.js} +0 -0
  366. /package/lib/{request-failure.js → providers/request-failure.js} +0 -0
  367. /package/lib/providers/{retire.js → retire/index.js} +0 -0
  368. /package/lib/providers/{vigievuln.js → vigievuln/index.js} +0 -0
  369. /package/lib/{application-providers/wp-checksums.js → providers/wordpress/checksums.js} +0 -0
  370. /package/lib/{report-time.js → reports/time.js} +0 -0
  371. /package/lib/{xlsx-export.js → reports/xlsx-export.js} +0 -0
  372. /package/lib/{diagnostics.js → scan/diagnostics.js} +0 -0
  373. /package/lib/{account-client.js → service/account-client.js} +0 -0
  374. /package/lib/{account-session.js → service/account-session.js} +0 -0
  375. /package/lib/{account-terms.js → service/account-terms.js} +0 -0
@@ -1,676 +0,0 @@
1
- /**
2
- * lib/cache-archive.js — export / import the entire ~/.fad-checker/ directory.
3
- *
4
- * Use case:
5
- * - Move the warmed-up CVE/OSV/NVD/POM caches between machines
6
- * - Snapshot the index before a scheduled refresh
7
- * - Share a known-good cache with a teammate
8
- *
9
- * Format:
10
- * .tar.gz — preferred when tar is available (Linux, macOS, Windows 10+)
11
- * .zip — fallback for Windows-only envs without tar
12
- *
13
- * The format is selected from the file extension. Tar uses native `tar`
14
- * binary (zero new deps).
15
- *
16
- * Import MERGES by default (`--replace` restores the old wholesale swap). The
17
- * air-gapped workflow ships a cache into an enclave that is already warm and holds
18
- * its own config.json — which `--export-cache` deliberately never bundles. Replacing
19
- * threw both away silently, and `--offline` on the resulting cold cache reports
20
- * 0 CVE / 0 EOL, which reads exactly like a clean project.
21
- *
22
- * @author: N.BRAUN
23
- * @email: pp9ping@gmail.com
24
- */
25
- const fs = require("fs");
26
- const path = require("path");
27
- const os = require("os");
28
- const { execFile, spawn } = require("child_process");
29
- const { promisify } = require("util");
30
- const execFileP = promisify(execFile);
31
-
32
- const FAD_CACHE_DIR = require("./cache-directory").getCacheDir({homeDir:os.homedir()});
33
-
34
- /**
35
- * Files inside ~/.fad-checker/ that hold secrets and should NOT be shipped by default.
36
- * Override by passing `includeConfig: true`.
37
- */
38
- const SENSITIVE_FILES = ["config.json"];
39
-
40
- /**
41
- * Never taken from an archive on a merging import. `config.json` is machine-local
42
- * (NVD key, private registry credentials) and is excluded from the export by default,
43
- * so an import that touched it could only ever lose the target's own.
44
- */
45
- const NEVER_IMPORT = ["config.json"];
46
-
47
- /**
48
- * Directories whose files only make sense together: the CVE index and the meta.json
49
- * that names the release it was built from. Merged per-file they could end up
50
- * describing two different builds, so the freshest side wins as a block.
51
- */
52
- const ATOMIC_DIRS = ["cve-data", "gcve-data", ...["maven", "npm", "pypi", "composer", "nuget", "go", "ruby"].map(e => `osv-db/records/${e}`)];
53
-
54
- function readJson(file) {
55
- try { return JSON.parse(fs.readFileSync(file, "utf8")); } catch { return null; }
56
- }
57
-
58
- /** Freshness of a cache file: its own stamp when it carries one, else the mtime. */
59
- function stampOf(file, json) {
60
- const declared = json?._fadSnapshot?.collectedAt ?? json?.collectedAt ?? json?.generatedAt;
61
- // A declared but invalid snapshot date must not acquire freshness from a copy's mtime.
62
- if (declared != null) {
63
- const stamp = typeof declared === "string" ? Date.parse(declared) : NaN;
64
- return Number.isFinite(stamp) ? stamp : 0;
65
- }
66
- const s = json?.meta?.fetchedAt ?? json?._fetchedAt ?? json?.fetchedAt;
67
- if (typeof s === "number" && s > 0) return s;
68
- try { return fs.statSync(file).mtimeMs; } catch { return 0; }
69
- }
70
-
71
- /**
72
- * An accumulating per-key cache — `{ meta|_fetchedAt, entries: {…} }`, the shape of
73
- * version/maven-exists/npm-registry/eol/epss/packagist/pypi/nuget/go-proxy/rubygems/
74
- * hash-id. Those merge key by key. Anything else (kev's full `body.byId` catalogue, an
75
- * OSV/NVD/POM cache entry, an OSV DB index) is a self-contained blob: newest wins.
76
- */
77
- const isEntryMap = j => !!j && typeof j === "object" && !!j.entries
78
- && typeof j.entries === "object" && !Array.isArray(j.entries);
79
-
80
- /** copyFileSync + keep the source mtime, so the next import still compares correctly. */
81
- function copyPreservingTime(src, dst) {
82
- fs.mkdirSync(path.dirname(dst), { recursive: true });
83
- fs.copyFileSync(src, dst);
84
- const st = fs.statSync(src);
85
- try { fs.utimesSync(dst, st.atime, st.mtime); } catch { /* best effort */ }
86
- }
87
-
88
- /**
89
- * Union of two entry maps. The fresher side wins on a key collision; the merged map
90
- * is stamped with the OLDER of the two — a union is only as fresh as its stalest half,
91
- * and antedating it would let a TTL check treat stale entries as just-fetched.
92
- */
93
- function mergeEntryMaps(srcFile, dstFile, srcJson, dstJson) {
94
- const srcStamp = stampOf(srcFile, srcJson), dstStamp = stampOf(dstFile, dstJson);
95
- const srcWins = srcStamp > dstStamp;
96
- const winner = srcWins ? srcJson : dstJson;
97
- const out = { ...winner };
98
- out.entries = srcWins
99
- ? { ...dstJson.entries, ...srcJson.entries }
100
- : { ...srcJson.entries, ...dstJson.entries };
101
- const older = Math.min(srcStamp, dstStamp);
102
- if (out.meta && typeof out.meta === "object" && typeof out.meta.fetchedAt === "number") out.meta = { ...out.meta, fetchedAt: older };
103
- if (typeof out._fetchedAt === "number") out._fetchedAt = older;
104
- if (typeof out.fetchedAt === "number") out.fetchedAt = older;
105
- fs.writeFileSync(dstFile, JSON.stringify(out));
106
- }
107
-
108
- /** Newest mtime anywhere under `dir` — the freshness of an atomic directory. */
109
- function newestMtime(dir) {
110
- let newest = 0;
111
- for (const ent of fs.readdirSync(dir, { withFileTypes: true })) {
112
- const p = path.join(dir, ent.name);
113
- if (ent.isDirectory()) newest = Math.max(newest, newestMtime(p));
114
- else if (ent.isFile()) newest = Math.max(newest, stampOf(p, readJson(p)));
115
- }
116
- return newest;
117
- }
118
-
119
- function copyTree(srcDir, dstDir) {
120
- fs.mkdirSync(dstDir, { recursive: true });
121
- for (const ent of fs.readdirSync(srcDir, { withFileTypes: true })) {
122
- const s = path.join(srcDir, ent.name), d = path.join(dstDir, ent.name);
123
- if (ent.isDirectory()) copyTree(s, d);
124
- else if (ent.isFile()) copyPreservingTime(s, d);
125
- }
126
- }
127
-
128
- // Seed metadata and its records must be validated and compared as a pair. A
129
- // forged file mtime must not replace a newer working snapshot, and a corrupt
130
- // download must never destroy the last usable copy.
131
- function osvSeedInfo(dir, name) {
132
- try {
133
- const expected = {maven:'Maven',npm:'npm',pypi:'PyPI',composer:'Packagist',nuget:'NuGet',go:'Go',ruby:'RubyGems'}[name];
134
- const metaFile = path.join(dir,'meta.json'), records = path.join(dir,'records.jsonl');
135
- for (const file of [metaFile,records]) { const st=fs.lstatSync(file); if (!st.isFile() || st.isSymbolicLink() || st.nlink !== 1) return null; }
136
- const meta=readJson(metaFile);
137
- if (!expected || meta?._schema !== 1 || meta.ecosystem !== expected || typeof meta.complete !== 'boolean' || !Number.isSafeInteger(meta._builtAt) || meta._builtAt <= 0 || meta._builtAt > Date.now()+300000 ||
138
- !Number.isSafeInteger(meta.recordCount) || meta.recordCount < 0 || !/^[a-f0-9]{64}$/.test(meta.sha256)) return null;
139
- const hash=require('crypto').createHash('sha256'), fd=fs.openSync(records,'r');
140
- try { const buf=Buffer.allocUnsafe(128*1024); for(let n;(n=fs.readSync(fd,buf,0,buf.length,null))>0;) hash.update(buf.subarray(0,n)); }
141
- finally { fs.closeSync(fd); }
142
- return hash.digest('hex') === meta.sha256 ? meta : null;
143
- } catch { return null; }
144
- }
145
-
146
- function mergeOsvSeed(src, dst, rel, stats) {
147
- const incoming=osvSeedInfo(src,path.basename(rel)), current=osvSeedInfo(dst,path.basename(rel));
148
- if (!incoming) { stats.skipped.push(rel + ': invalid OSV seed'); return; }
149
- if (current?.complete && !incoming.complete) { stats.skipped.push(rel + ': incomplete OSV seed'); return; }
150
- if (current && current._builtAt >= incoming._builtAt) { stats.kept++; return; }
151
- const suffix=require('crypto').randomBytes(8).toString('hex');
152
- const staged=`${dst}.stage-${suffix}`, backup=`${dst}.backup-${suffix}`;
153
- let moved=false;
154
- try {
155
- copyTree(src,staged);
156
- if (!osvSeedInfo(staged,path.basename(rel))) throw new Error('OSV seed changed during import');
157
- if (fs.existsSync(dst)) { fs.renameSync(dst,backup); moved=true; }
158
- try { fs.renameSync(staged,dst); } catch (error) { if(moved)fs.renameSync(backup,dst); moved=false; throw error; }
159
- if (moved) fs.rmSync(backup,{recursive:true,force:true});
160
- stats[current ? 'updated' : 'added']++;
161
- } finally { fs.rmSync(staged,{recursive:true,force:true}); }
162
- }
163
-
164
- function gcveSeedInfo(dir) {
165
- try {
166
- const file=path.join(dir,'index.json'), st=fs.lstatSync(file);
167
- if (!st.isFile() || st.isSymbolicLink() || st.nlink !== 1) return null;
168
- const index=require('./gcve-index').readGcveIndex(file);
169
- const at=Date.parse(index._fadSnapshot?.collectedAt);
170
- if (!index.directory?.verified || !Number.isFinite(at) || at <= 0 || at > Date.now()+300000) return null;
171
- return {at,complete:index.coverage.every(c=>c.complete === true)};
172
- } catch { return null; }
173
- }
174
-
175
- function mergeGcveSeed(src,dst,stats) {
176
- const incoming=gcveSeedInfo(src),current=gcveSeedInfo(dst);
177
- if (!incoming) {stats.skipped.push('gcve-data: invalid index');return;}
178
- if (current && (current.at >= incoming.at || (current.complete && !incoming.complete))) {stats.kept++;return;}
179
- const suffix=require('crypto').randomBytes(8).toString('hex'), staged=`${dst}.stage-${suffix}`,backup=`${dst}.backup-${suffix}`;
180
- let moved=false;
181
- try {
182
- copyTree(src,staged);
183
- if (!gcveSeedInfo(staged)) throw Error('GCVE seed changed during import');
184
- if (fs.existsSync(dst)) {fs.renameSync(dst,backup);moved=true;}
185
- try {fs.renameSync(staged,dst);} catch (error) {if(moved)fs.renameSync(backup,dst);moved=false;throw error;}
186
- if(moved)fs.rmSync(backup,{recursive:true,force:true});
187
- stats[current?'updated':'added']++;
188
- } finally {fs.rmSync(staged,{recursive:true,force:true});}
189
- }
190
-
191
- function mergeFile(srcFile, dstFile, rel, stats) {
192
- if (!fs.existsSync(dstFile)) { copyPreservingTime(srcFile, dstFile); stats.added++; return; }
193
- const srcJson = readJson(srcFile), dstJson = readJson(dstFile);
194
- if (isEntryMap(srcJson) && isEntryMap(dstJson)) {
195
- // Legacy Maven false values do not prove absence and must never override a
196
- // confirmed hit, even if their containing cache file is more recent.
197
- if (rel === "maven-exists-cache.json") {
198
- const { discardUnverifiedEntries } = require("./maven-presence");
199
- discardUnverifiedEntries(srcJson);
200
- discardUnverifiedEntries(dstJson);
201
- }
202
- mergeEntryMaps(srcFile, dstFile, srcJson, dstJson);
203
- stats.merged++;
204
- return;
205
- }
206
- if (stampOf(srcFile, srcJson) > stampOf(dstFile, dstJson)) { copyPreservingTime(srcFile, dstFile); stats.updated++; }
207
- else stats.kept++;
208
- }
209
-
210
- // Compact generations are immutable and identified by their manifest hash.
211
- // Never merge individual shards by mtime: a newer local shard may be corrupt.
212
- function mergeNvdBulk(src, dst, stats) {
213
- const {validateGeneration}=require('./nvd-bulk');
214
- fs.mkdirSync(dst,{recursive:true});
215
- for (const name of fs.readdirSync(src)) {
216
- const source=path.join(src,name), target=path.join(dst,name);
217
- if (fs.existsSync(target)) {
218
- try {validateGeneration(target);stats.kept++;continue;} catch { /* preserve and repair below */ }
219
- }
220
- const parent=path.dirname(dst), stage=fs.mkdtempSync(path.join(parent,'.nvd-stage-'));
221
- const staged=path.join(stage,name), backup=fs.mkdtempSync(path.join(parent,'.nvd-backup-'));
222
- const saved=path.join(backup,name); let moved=false;
223
- try {
224
- copyTree(source,staged);validateGeneration(staged);
225
- if (fs.existsSync(target)) {fs.renameSync(target,saved);moved=true;}
226
- try {fs.renameSync(staged,target);} catch (error) {if(moved)fs.renameSync(saved,target);moved=false;throw error;}
227
- stats[moved?'updated':'added']++;
228
- } finally {
229
- fs.rmSync(stage,{recursive:true,force:true});
230
- if (!moved) fs.rmSync(backup,{recursive:true,force:true});
231
- }
232
- }
233
- }
234
-
235
- function mergeResourceStore(srcDir, dstDir, stats) {
236
- const { createCacheStore } = require("./proxy-cache");
237
- const incoming = createCacheStore(srcDir), target = createCacheStore(dstDir);
238
- for (const file of fs.readdirSync(incoming.entriesDir)) {
239
- if (!/^[a-f0-9]{64}\.json$/.test(file)) continue;
240
- const meta = readJson(path.join(incoming.entriesDir, file));
241
- if (typeof meta?.url !== "string") continue;
242
- const source = incoming.get(meta.url);
243
- if (!source || !Number.isFinite(source.fetchedAt)) continue;
244
- const current = target.get(meta.url);
245
- if (current && current.fetchedAt >= source.fetchedAt) { stats.kept++; continue; }
246
- const tmp = path.join(target.entriesDir, ".tmp-import-" + require("node:crypto").randomBytes(8).toString("hex"));
247
- try {
248
- fs.copyFileSync(source.bodyPath, tmp);
249
- const { bodyPath, bodyFile, ...metadata } = source;
250
- target.commit(meta.url, tmp, metadata);
251
- stats[current ? "updated" : "added"]++;
252
- } finally { fs.rmSync(tmp, { force: true }); }
253
- }
254
- }
255
-
256
- // 1.1.3 used a Maven-only per-package projection with no schema field. Keep
257
- // it in its own namespace: it contains neither complete native records nor
258
- // withdrawal evidence. Do not convert the unpublished schema-2 indexes.
259
- function readLegacyMavenIndex(file) {
260
- const index = readJson(file);
261
- if (!index || index._schema != null || index.ecosystem !== 'Maven' ||
262
- !Number.isSafeInteger(index._builtAt) || index._builtAt <= 0 || index._builtAt > Date.now() + 300000 ||
263
- !index.byPackage || typeof index.byPackage !== 'object' || Array.isArray(index.byPackage)) return null;
264
- const records = new Map(), invalid = new Set();
265
- for (const [name, entries] of Object.entries(index.byPackage)) {
266
- if (!Array.isArray(entries)) throw new Error('invalid legacy Maven OSV index');
267
- for (const document of entries) {
268
- if (!document || typeof document.id !== 'string' || !Array.isArray(document.affected)) throw new Error('invalid legacy Maven OSV advisory');
269
- if (document.affected.some(a=>a?.package?.ecosystem !== 'Maven' || String(a?.package?.name || '').toLowerCase() !== name.toLowerCase())) throw new Error('invalid legacy Maven OSV package');
270
- const {affected, ...rest}=document, previous=records.get(document.id), signature=JSON.stringify(rest);
271
- if (previous && previous.signature !== signature) {invalid.add(document.id);continue;}
272
- if (!previous) records.set(document.id,{signature,document:{...rest,affected:[...affected]}});
273
- else previous.document.affected.push(...affected);
274
- }
275
- }
276
- for (const id of invalid) records.delete(id);
277
- return {builtAt:index._builtAt, documents:[...records.values()].map(r=>r.document), conflicting:invalid.size};
278
- }
279
-
280
- async function importLegacyMavenIndex(cacheDir, file = path.join(cacheDir,'osv-db','maven-index.json')) {
281
- const legacy = readLegacyMavenIndex(file);
282
- if (!legacy) throw new Error('unrecognized or experimental Maven OSV index');
283
- const store = require('./advisory-store').openAdvisoryStore({cacheDir});
284
- await store.importRecords(legacy.documents, {source:'osv-legacy-maven', fetchedAt:legacy.builtAt, provenance:{transport:'legacy',format:'vigievuln-1.1.3'}, coverages:[{source:'osv-legacy-maven',ecosystem:'Maven',fetchedAt:legacy.builtAt,complete:false,provenance:{transport:'legacy'}}]});
285
- return {count:legacy.documents.length,conflicting:legacy.conflicting};
286
- }
287
-
288
- // Validate and stream a complete native OSV seed. importRecords stages the entire
289
- // iterable and verifies each record before publishing it to the journal.
290
- function readNativeSeed(dir) {
291
- const meta = readJson(path.join(dir, 'meta.json'));
292
- const validEcos = new Set(['Maven','npm','PyPI','Packagist','NuGet','Go','RubyGems']);
293
- if (!meta || meta._schema !== 1 || meta.source !== 'osv' || meta.complete !== true ||
294
- !Number.isSafeInteger(meta._builtAt) || meta._builtAt <= 0 || meta._builtAt > Date.now() + 300000 ||
295
- !Number.isSafeInteger(meta.recordCount) || meta.recordCount < 0 || !/^[a-f0-9]{64}$/.test(meta.sha256) ||
296
- !Array.isArray(meta.ecosystems) || !meta.ecosystems.length || meta.ecosystems.some(e => !validEcos.has(e)) || new Set(meta.ecosystems).size !== meta.ecosystems.length)
297
- throw new Error('invalid native OSV seed metadata');
298
- const file = path.join(dir, 'osv.jsonl');
299
- if (!fs.statSync(file).isFile()) throw new Error('missing native OSV seed records');
300
- return {meta, file};
301
- }
302
- async function* nativeSeedRecords({meta,file}, onProgress) {
303
- const hash = require('node:crypto').createHash('sha256');
304
- const stream = fs.createReadStream(file); stream.on('data', chunk => hash.update(chunk));
305
- const lines = require('./line-stream').readTextLines(stream);
306
- let count = 0;
307
- try {
308
- for await (const line of lines) {
309
- if (!line || Buffer.byteLength(line) > 16 * 1024 * 1024) throw new Error('invalid or oversized native OSV seed record');
310
- const document = JSON.parse(line);
311
- if (!document || typeof document.id !== 'string' || (!Array.isArray(document.affected) && !(document.withdrawn && document.affected == null))) throw new Error('invalid native OSV seed record');
312
- count++; if (count % 1000 === 0) onProgress?.({phase:'index-osv',count,total:meta.recordCount}); yield document;
313
- }
314
- } finally { stream.destroy(); }
315
- if (count !== meta.recordCount || hash.digest('hex') !== meta.sha256) throw new Error('native OSV seed checksum or count mismatch');
316
- onProgress?.({phase:'index-build',count});
317
- }
318
-
319
- function readCveSeed(dir) {
320
- const meta=readJson(path.join(dir,'cveproject-meta.json'));
321
- if (!meta || meta._schema!==1 || meta.source!=='cveproject' || meta.complete!==false ||
322
- !Number.isSafeInteger(meta._builtAt) || meta._builtAt<=0 || meta._builtAt>Date.now()+300000 ||
323
- !Number.isSafeInteger(meta.recordCount) || meta.recordCount<0 || !/^[a-f0-9]{64}$/.test(meta.sha256)) throw new Error('invalid CVEProject seed metadata');
324
- const file=path.join(dir,'cveproject.jsonl');if(!fs.statSync(file).isFile())throw new Error('missing CVEProject seed records');
325
- return {meta,file};
326
- }
327
- async function* cveSeedEnvelopes({meta,file}, onProgress) {
328
- const hash=require('node:crypto').createHash('sha256'), stream=fs.createReadStream(file);
329
- stream.on('data',chunk=>hash.update(chunk));
330
- const lines=require('./line-stream').readTextLines(stream);let count=0;
331
- try {for await (const line of lines) {
332
- if(!line || Buffer.byteLength(line)>16*1024*1024)throw new Error('invalid or oversized CVEProject seed record');
333
- count++;if(count % 1000 === 0)onProgress?.({phase:'index-cve',count,total:meta.recordCount});yield require('./native-advisories').cveEnvelope(JSON.parse(line),{fetchedAt:meta._builtAt,provenance:{transport:'seed'}});
334
- }} finally {stream.destroy();}
335
- if(count!==meta.recordCount || hash.digest('hex')!==meta.sha256)throw new Error('CVEProject seed checksum or count mismatch');
336
- onProgress?.({phase:'index-build',count});
337
- }
338
-
339
- function mergeTree(srcDir, dstDir, stats, rel = "") {
340
- fs.mkdirSync(dstDir, { recursive: true });
341
- for (const ent of fs.readdirSync(srcDir, { withFileTypes: true })) {
342
- const relPath = rel ? `${rel}/${ent.name}` : ent.name;
343
- const s = path.join(srcDir, ent.name), d = path.join(dstDir, ent.name);
344
- if (NEVER_IMPORT.includes(relPath)) { stats.skipped.push(relPath); continue; }
345
- if (ent.isDirectory()) {
346
- if (relPath === "advisory-store") continue; // journal is merged separately; indexes are derived
347
- if (relPath === "resource-cache") { mergeResourceStore(s, d, stats); continue; }
348
- if (relPath === "nvd-cache/_bulk") { mergeNvdBulk(s,d,stats); continue; }
349
- if (relPath === "gcve-data") { mergeGcveSeed(s,d,stats); continue; }
350
- if (relPath === "osv-db/records") { stats.skipped.push("osv-db/records: obsolete partitioned OSV seed cannot be imported; obtain a current bundle"); continue; }
351
- if (ATOMIC_DIRS.includes(relPath)) {
352
- if (!fs.existsSync(d)) { copyTree(s, d); stats.added++; }
353
- else if (newestMtime(s) > newestMtime(d)) { fs.rmSync(d, { recursive: true, force: true }); copyTree(s, d); stats.updated++; }
354
- else stats.kept++;
355
- continue;
356
- }
357
- mergeTree(s, d, stats, relPath);
358
- } else if (ent.isFile()) {
359
- if (/^package-versions\/[a-f0-9]{2}$/.test(rel)) {
360
- const incoming=require('./package-versions').readRecord(s);
361
- if (!incoming) { stats.skipped.push(relPath + ': invalid package observation'); continue; }
362
- // Its name includes the body hash: a conflict becomes another file,
363
- // not a replacement. Preserve valid existing observations on collision.
364
- if (fs.existsSync(d) && require('./package-versions').readRecord(d)) {stats.kept++;continue;}
365
- copyPreservingTime(s,d);stats.added++;continue;
366
- }
367
- mergeFile(s, d, relPath, stats);
368
- }
369
- // symlinks and specials in a cache archive are not ours to reproduce — skipped
370
- }
371
- }
372
-
373
- /**
374
- * Node opens the archive and sets cwd: tar never has to parse a Windows drive/UNC
375
- * path (GNU tar treats ':' in -f as a remote host). '-' works with GNU and BSD tar.
376
- * Inherited file descriptors also keep large cache archives out of JS memory.
377
- */
378
- async function runTar(args, archive, cwd, writing, verbose) {
379
- if (verbose) console.log(`📦 tar ${args.join(" ")} (cwd: ${cwd}, archive: ${archive})`);
380
- const fd = fs.openSync(archive, writing ? "w" : "r");
381
- try {
382
- await new Promise((resolve, reject) => {
383
- const child = spawn("tar", args, {
384
- cwd,
385
- stdio: writing ? ["ignore", fd, "pipe"] : [fd, "ignore", "pipe"],
386
- });
387
- let stderr = "";
388
- child.stderr.setEncoding("utf8");
389
- child.stderr.on("data", chunk => { stderr = (stderr + chunk).slice(-64 * 1024); });
390
- child.on("error", reject);
391
- child.on("close", (code, signal) => {
392
- if (code === 0) resolve();
393
- else reject(new Error(`tar failed (${signal || code}): ${stderr.trim()}`));
394
- });
395
- });
396
- } finally {
397
- fs.closeSync(fd);
398
- }
399
- }
400
-
401
- async function exportCache(destFile, opts = {}) {
402
- const { verbose, includeConfig } = opts;
403
- const sourceDir = opts.sourceDir || FAD_CACHE_DIR;
404
- const origin = opts.proxyOrigin ? require("./proxy-scope").proxyOrigin(opts.proxyOrigin) : null;
405
- if (!fs.existsSync(sourceDir)) throw new Error(`no ~/.vigie-vuln/ directory to export`);
406
- const abs = path.resolve(destFile);
407
- fs.mkdirSync(path.dirname(abs), { recursive: true });
408
-
409
- const excludes = includeConfig ? [] : SENSITIVE_FILES.map(f => `${path.basename(sourceDir)}/${f}`);
410
- if (excludes.length && verbose) console.log(` excluding (use --include-config to keep): ${excludes.join(", ")}`);
411
-
412
- const ext = abs.toLowerCase();
413
- const markerDir = origin ? fs.mkdtempSync(path.join(os.tmpdir(), "vigievuln-archive-")) : null;
414
- const markerName = ".vigievuln-archive-origin.json";
415
- if (markerDir) fs.writeFileSync(path.join(markerDir, markerName), JSON.stringify({ version: 1, origin }), { mode: 0o600 });
416
- try {
417
- if (ext.endsWith(".tar.gz") || ext.endsWith(".tgz")) {
418
- const args = ["-czf", "-"];
419
- for (const e of excludes) args.push(`--exclude=${e}`);
420
- args.push(path.basename(sourceDir));
421
- if (markerDir) args.push("-C", markerDir, markerName);
422
- await runTar(args, abs, path.dirname(sourceDir), true, verbose);
423
- } else if (ext.endsWith(".zip")) {
424
- if (process.platform === "win32") {
425
- if (origin) throw new Error("Proxy-scoped ZIP export is unavailable on Windows; use tar.gz.");
426
- if (verbose) console.log(`📦 Compress-Archive -Path ${sourceDir}\\* -DestinationPath ${abs}`);
427
- // Powershell Compress-Archive doesn't have a clean exclude flag — manual copy
428
- await execFileP("powershell", ["-NoProfile", "-Command",
429
- `$src='${sourceDir}'; $dst='${abs}'; ${includeConfig ? `Compress-Archive -Path "$src\\*" -DestinationPath $dst -Force` : `$tmp=Join-Path $env:TEMP "vigievuln-stage-$(Get-Random)"; Copy-Item $src $tmp -Recurse; ${SENSITIVE_FILES.map(f => `Remove-Item -Force -ErrorAction SilentlyContinue (Join-Path $tmp '${f}')`).join("; ")}; Compress-Archive -Path "$tmp\\*" -DestinationPath $dst -Force; Remove-Item $tmp -Recurse -Force`}`]);
430
- } else {
431
- const args = ["-r", "-q", abs, path.basename(sourceDir)];
432
- for (const e of excludes) { args.push("-x"); args.push(e); }
433
- if (verbose) console.log(`📦 zip ${args.join(" ")}`);
434
- await execFileP("zip", args, { cwd: path.dirname(sourceDir), maxBuffer: 1024 * 1024 * 32 });
435
- if (markerDir) await execFileP("zip", ["-q", abs, markerName], { cwd: markerDir });
436
- }
437
- } else {
438
- throw new Error(`unknown archive extension on ${destFile} (expected .tar.gz, .tgz, or .zip)`);
439
- }
440
-
441
- } finally { if (markerDir) fs.rmSync(markerDir, { recursive: true, force: true }); }
442
- const size = fs.statSync(abs).size;
443
- return { path: abs, size, excluded: excludes };
444
- }
445
-
446
- /** Unpack an archive into `destParent`, which ends up holding a `.fad-checker/`. */
447
- async function extractTo(abs, destParent, verbose) {
448
- fs.mkdirSync(destParent, { recursive: true });
449
- const ext = abs.toLowerCase();
450
- if (ext.endsWith(".tar.gz") || ext.endsWith(".tgz")) {
451
- // --no-same-owner: tar restores the archived uid/gid when it runs as root. Real root
452
- // can chown to anything, so plain Docker is fine; MAPPED root cannot — a rootless
453
- // container, a userns-remapped daemon, anything under `unshare -r` — and there the
454
- // chown fails, tar aborts having written NOTHING, and the air-gapped run that
455
- // follows finds no cache and reports a clean project. Ownership inside the archive
456
- // is meaningless here (it is the importer's own cache) and the flag is already the
457
- // default for a non-root user, so this costs nothing on the paths that worked.
458
- const args = ["-xzf", "-", "--no-same-owner"];
459
- await runTar(args, abs, destParent, false, verbose);
460
- } else if (ext.endsWith(".zip")) {
461
- if (process.platform === "win32") {
462
- if (verbose) console.log(`📦 Expand-Archive -Path ${abs} -DestinationPath ${destParent}`);
463
- await execFileP("powershell", ["-NoProfile", "-Command",
464
- `Expand-Archive -Path '${abs}' -DestinationPath '${destParent}' -Force`]);
465
- } else {
466
- if (verbose) console.log(`📦 unzip ${abs} -d ${destParent}`);
467
- await execFileP("unzip", ["-o", "-q", abs, "-d", destParent], { maxBuffer: 1024 * 1024 * 32 });
468
- }
469
- } else {
470
- throw new Error(`unknown archive extension on ${abs} (expected .tar.gz, .tgz, or .zip)`);
471
- }
472
- }
473
-
474
- // Inspect only tar member names and, when necessary, the legacy Maven index.
475
- // A server seed containing hundreds of thousands of old NVD files must not be
476
- // expanded merely to discover its OSV partition is unusable. On ambiguity we
477
- // fall back to the normal validated import, preserving published 1.1.x caches.
478
- async function preflightSetupSeed(abs, onProgress) {
479
- if (!/\.(?:tar\.gz|tgz)$/i.test(abs)) return;
480
- const found={old:false,native:false,journal:false,details:false,index:null};
481
- const fd=fs.openSync(abs,'r');
482
- try {
483
- await new Promise((resolve,reject)=>{
484
- const child=spawn('tar',['-tzf','-'],{stdio:[fd,'pipe','pipe']});
485
- let stderr='', count=0;
486
- child.stderr.setEncoding('utf8');child.stderr.on('data',chunk=>{stderr=(stderr+chunk).slice(-4096)});
487
- const lines=require('node:readline').createInterface({input:child.stdout,crlfDelay:Infinity});
488
- lines.on('line',name=>{
489
- count++; if(count % 10000===0)onProgress?.({phase:'validating',count});
490
- const clean=name.replace(/^\.\//,'');
491
- if (!/^(?:\.vigie-vuln|\.fad-checker)\//.test(clean)) return;
492
- const rel=clean.slice(clean.indexOf('/')+1);
493
- if (rel.startsWith('osv-db/records/')) found.old=true;
494
- if (rel==='advisory-store/seed/osv.jsonl') found.native=true;
495
- if (rel==='advisory-store/events.jsonl') found.journal=true;
496
- if (/^osv-cache\/vuln_.+\.json$/.test(rel)) found.details=true;
497
- if (rel==='osv-db/maven-index.json') found.index=name;
498
- });
499
- child.on('error',reject);child.on('close',(code,signal)=>code===0?resolve():reject(new Error(`tar inspection failed (${signal || code}): ${stderr.trim()}`)));
500
- });
501
- } finally {fs.closeSync(fd);}
502
- if ((!found.old && !found.index) || found.native || found.journal || found.details) return;
503
- let oldIndex = !found.index;
504
- if (found.index) {
505
- const source=fs.openSync(abs,'r');
506
- try {
507
- const output=await new Promise((resolve,reject)=>{
508
- const child=spawn('tar',['-xOzf','-',found.index],{stdio:[source,'pipe','pipe']});
509
- const chunks=[];let size=0, tooLarge=false;
510
- child.stdout.on('data',chunk=>{size+=chunk.length;if(size>64*1024*1024){tooLarge=true;child.kill();}else chunks.push(chunk)});
511
- child.stderr.resume();child.on('error',reject);child.on('close',code=>resolve(!tooLarge && code===0?Buffer.concat(chunks).toString('utf8'):null));
512
- });
513
- if (output !== null) { try { oldIndex=JSON.parse(output)?._schema === 2; } catch { /* preserve ambiguous archives */ } }
514
- } finally {fs.closeSync(source);}
515
- }
516
- if (oldIndex) throw new Error('This server bundle uses an obsolete OSV seed format and contains no usable OSV advisories. Update the server and regenerate its bundle; setup was not saved.');
517
- }
518
-
519
- /**
520
- * Restore ~/.fad-checker/ from an archive.
521
- *
522
- * Default: MERGE — union with whatever the target already has, so an enclave never
523
- * loses the cache it warmed itself, nor its config.json.
524
- * opts.replace wholesale swap, previous dir kept as .fad-checker.bak-<ts>
525
- * opts.force wholesale swap with no backup (implies replace)
526
- */
527
- async function importCache(srcFile, opts = {}) {
528
- const { verbose, force } = opts;
529
- const targetDir = opts.targetDir || FAD_CACHE_DIR;
530
- const replace = !!(opts.replace || force);
531
- const abs = path.resolve(srcFile);
532
- if (!fs.existsSync(abs)) throw new Error(`archive not found: ${abs}`);
533
- if (opts.requireUsableSeed) { opts.onProgress?.({phase:'validating'}); await preflightSetupSeed(abs,opts.onProgress); }
534
-
535
- // Merge: unpack beside the cache (same filesystem), reconcile, drop the staging dir.
536
- fs.mkdirSync(path.dirname(targetDir), { recursive: true });
537
- const staging = fs.mkdtempSync(`${targetDir}.import-`);
538
- const stats = { added: 0, updated: 0, merged: 0, kept: 0, skipped: [] };
539
- try {
540
- opts.onProgress?.({phase:'extracting'});
541
- await extractTo(abs, staging, verbose);
542
- opts.onProgress?.({phase:'validating'});
543
- // Never promote links or special files into a live cache, including in
544
- // replace mode. A later cache write could otherwise escape the cache root.
545
- const inspect = dir => {
546
- for (const entry of fs.readdirSync(dir)) {
547
- const file = path.join(dir, entry), st = fs.lstatSync(file);
548
- if (st.isSymbolicLink() || (!st.isDirectory() && (!st.isFile() || st.nlink !== 1)))
549
- throw new Error("archive contains links or special files");
550
- if (st.isDirectory()) inspect(file);
551
- }
552
- };
553
- inspect(staging);
554
- if (opts.proxyOrigin) {
555
- const origin = require("./proxy-scope").proxyOrigin(opts.proxyOrigin);
556
- const marker = readJson(path.join(staging, ".vigievuln-archive-origin.json"));
557
- if (!marker || marker.version !== 1 || marker.origin !== origin) throw new Error("Archive proxy origin missing or does not match the active proxy scope.");
558
- }
559
- const modern = path.join(staging, '.vigie-vuln');
560
- const legacyDir = path.join(staging, '.fad-checker');
561
- // Windows Compress-Archive historically emitted the cache contents at
562
- // the ZIP root, whereas tar and Unix ZIP preserve the directory name.
563
- const flatWindowsZip = process.platform === 'win32' && abs.toLowerCase().endsWith('.zip');
564
- const incoming = fs.existsSync(modern) ? modern : fs.existsSync(legacyDir) ? legacyDir : flatWindowsZip ? staging : legacyDir;
565
- if (!fs.existsSync(incoming) || !fs.lstatSync(incoming).isDirectory()) {
566
- throw new Error(`archive holds no .vigie-vuln/ or .fad-checker/ directory — was it built with vigievuln --export-cache?`);
567
- }
568
- // A corrupt compact NVD generation must not be merged beside valid local
569
- // observations or cause any other part of this archive to be committed.
570
- if (fs.existsSync(path.join(incoming,'nvd-cache','_bulk')))
571
- require('./nvd-bulk').validateAll(path.join(incoming,'nvd-cache'));
572
- const storeDir = path.join(incoming, 'advisory-store');
573
- const journal = path.join(storeDir, 'events.jsonl');
574
- const seedDir = path.join(storeDir, 'seed');
575
- const hasJournal = fs.existsSync(journal), hasSeedDir = fs.existsSync(seedDir);
576
- const hasSeed = hasSeedDir && (fs.existsSync(path.join(seedDir,'meta.json')) || fs.existsSync(path.join(seedDir,'osv.jsonl')));
577
- const hasCveSeed = hasSeedDir && (fs.existsSync(path.join(seedDir,'cveproject-meta.json')) || fs.existsSync(path.join(seedDir,'cveproject.jsonl')));
578
- if (fs.existsSync(storeDir) && !hasJournal && !hasSeed && !hasCveSeed) throw new Error('archive advisory store has no journal or native seed');
579
- let usableJournalOsv = false;
580
- if (hasJournal) for (const item of require('./advisory-store').journalTransactions(journal)) {
581
- if (item.transaction.records.some(r => r.source === 'osv' && !r.document.withdrawn && r.document.affected?.some(a => a.package?.ecosystem && a.package?.name))) usableJournalOsv = true;
582
- }
583
- const seed = hasSeed ? readNativeSeed(seedDir) : null;
584
- const cveSeed = hasCveSeed ? readCveSeed(seedDir) : null;
585
- const gcveDir = path.join(incoming,'gcve-data');
586
- const gcve = fs.existsSync(gcveDir) && gcveSeedInfo(gcveDir) ? require('./gcve-index').readGcveIndex(path.join(gcveDir,'index.json')) : null;
587
- const legacyFile = path.join(incoming,'osv-db','maven-index.json');
588
- let legacy = null;
589
- if (fs.existsSync(legacyFile)) {
590
- try { legacy = readLegacyMavenIndex(legacyFile); } catch { /* warn below */ }
591
- if (!legacy && !seed) stats.skipped.push('osv-db/maven-index.json: unrecognized or experimental index; no legacy advisories imported');
592
- else if (legacy) stats.skipped.push(`Maven OSV legacy index is partial and cannot verify withdrawn advisories${legacy.conflicting ? `; ${legacy.conflicting} conflicting advisory IDs skipped` : ''}`);
593
- }
594
- // An unpublished, partitioned 1.2 seed cannot be interpreted by the
595
- // native store. Fail setup before modifying the destination if the bundle
596
- // otherwise contains no usable OSV advisories. Ordinary cache imports still
597
- // salvage their compatible entries and report the skipped old partition.
598
- const obsoleteOsv = opts.requireUsableSeed && (fs.existsSync(path.join(incoming,'osv-db','records')) || readJson(legacyFile)?._schema === 2);
599
- if (opts.requireUsableSeed && obsoleteOsv &&
600
- !(seed?.meta.recordCount > 0) && !usableJournalOsv && !(legacy?.documents?.length > 0)) {
601
- let usableDetails = false;
602
- const dir = path.join(incoming,'osv-cache');
603
- if (fs.existsSync(dir)) for (const name of fs.readdirSync(dir)) {
604
- if (!/^vuln_.+\.json$/.test(name)) continue;
605
- try {
606
- const file=path.join(dir,name), st=fs.lstatSync(file);
607
- if (!st.isFile() || st.isSymbolicLink() || st.size>16*1024*1024) continue;
608
- const cached=JSON.parse(fs.readFileSync(file,'utf8'));
609
- require('./advisory-store').validateRecord({source:'osv',document:cached.body,fetchedAt:cached._fetchedAt});
610
- if (!cached.body.withdrawn && cached.body.affected?.some(a=>a.package?.ecosystem && a.package?.name)) { usableDetails=true; break; }
611
- } catch { /* malformed historical entry */ }
612
- }
613
- if (!usableDetails) throw new Error('This server bundle uses an obsolete OSV seed format and contains no usable OSV advisories. Update the server and regenerate its bundle; setup was not saved.');
614
- }
615
-
616
- // Validate seed completely in a temporary store before any target mutation.
617
- const prepared = path.join(staging, 'prepared-store');
618
- if (hasSeed || hasCveSeed || legacy || gcve || (replace && hasJournal)) {
619
- const store = require('./advisory-store').openAdvisoryStore({cacheDir:prepared});
620
- if (seed) { opts.onProgress?.({phase:'index-osv',count:0,total:seed.meta.recordCount}); await store.importRecords(nativeSeedRecords(seed,opts.onProgress), {source:'osv', fetchedAt:seed.meta._builtAt, provenance:{transport:'seed'}, coverages:seed.meta.ecosystems.map(ecosystem => ({source:'osv', ecosystem, fetchedAt:seed.meta._builtAt, complete:true, provenance:{transport:'seed'}, sha256:seed.meta.sha256, recordCount:seed.meta.recordCount}))}); }
621
- if (cveSeed) { opts.onProgress?.({phase:'index-cve',count:0,total:cveSeed.meta.recordCount}); await store.importEnvelopes(cveSeedEnvelopes(cveSeed,opts.onProgress),{coverages:[{source:'cveproject',ecosystem:'*',fetchedAt:cveSeed.meta._builtAt,complete:false,provenance:{transport:'seed'}}]}); }
622
- if (legacy) await importLegacyMavenIndex(prepared, legacyFile);
623
- if (gcve) { opts.onProgress?.({phase:'index-gcve'}); await require('./native-advisories').importGcveIndex(store,gcve,{provenance:{transport:'seed'}}); }
624
- if (hasJournal) store.mergeJournal(journal);
625
- if (!fs.existsSync(store.journal)) fs.writeFileSync(store.journal, '', {mode:0o600});
626
- }
627
- if (replace) {
628
- if (fs.existsSync(path.join(incoming, 'osv-db', 'records'))) {
629
- stats.skipped.push('osv-db/records: obsolete partitioned OSV seed cannot be imported; obtain a current bundle');
630
- fs.rmSync(path.join(incoming, 'osv-db', 'records'), {recursive:true,force:true});
631
- }
632
- fs.rmSync(storeDir, {recursive:true, force:true});
633
- if (hasSeed || hasCveSeed || hasJournal || legacy || gcve) fs.renameSync(path.join(prepared, 'advisory-store'), storeDir);
634
- }
635
- const containsLegacyOsv = fs.existsSync(path.join(incoming,'osv-cache'));
636
- if (replace) {
637
- // Configuration contains machine-local credentials and is never
638
- // accepted from an imported archive, even for a replacement.
639
- for (const name of NEVER_IMPORT) {
640
- const src = path.join(targetDir, name), dst = path.join(incoming, name);
641
- fs.rmSync(dst, { force: true });
642
- if (fs.existsSync(src)) {
643
- const st = fs.lstatSync(src);
644
- if (!st.isFile() || st.isSymbolicLink() || st.nlink !== 1) throw new Error('unsafe local cache configuration');
645
- fs.copyFileSync(src, dst, fs.constants.COPYFILE_EXCL);
646
- try { fs.chmodSync(dst, 0o600); } catch { /* platform does not support chmod */ }
647
- }
648
- }
649
- if (fs.existsSync(targetDir) && !force) {
650
- const backup = `${targetDir}.bak-${Date.now()}`;
651
- fs.renameSync(targetDir, backup);
652
- if (verbose) console.log(`💾 existing ~/.vigie-vuln/ moved to ${backup}`);
653
- } else if (force && fs.existsSync(targetDir)) {
654
- fs.rmSync(targetDir, {recursive:true, force:true});
655
- }
656
- fs.renameSync(incoming, targetDir);
657
- if (containsLegacyOsv) require('./osv-legacy').importLegacyOsvDetails(require('./advisory-store').openAdvisoryStore({cacheDir:targetDir}),{cacheDir:targetDir,force:true});
658
- return {dir:targetDir, mode:'replace', stats};
659
- }
660
- fs.mkdirSync(targetDir, { recursive: true });
661
- opts.onProgress?.({phase:'merging'});
662
- if (hasSeed || hasCveSeed || hasJournal || legacy || gcve) {
663
- const store = require('./advisory-store').openAdvisoryStore({cacheDir:targetDir});
664
- if (hasSeed || hasCveSeed || legacy || gcve) store.mergeJournal(path.join(prepared,'advisory-store','events.jsonl'));
665
- else store.mergeJournal(journal);
666
- stats.merged++;
667
- }
668
- mergeTree(incoming, targetDir, stats);
669
- if (containsLegacyOsv) require('./osv-legacy').importLegacyOsvDetails(require('./advisory-store').openAdvisoryStore({cacheDir:targetDir}),{cacheDir:targetDir,force:true});
670
- } finally {
671
- fs.rmSync(staging, { recursive: true, force: true });
672
- }
673
- return { dir: targetDir, mode: "merge", stats };
674
- }
675
-
676
- module.exports = { exportCache, importCache, FAD_CACHE_DIR, mergeResourceStore, readLegacyMavenIndex, importLegacyMavenIndex };