vigievuln 1.1.2 → 1.2.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 (107) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/README.md +51 -141
  3. package/completions/vigievuln.bash +1 -1
  4. package/completions/vigievuln.zsh +1 -0
  5. package/lib/account-client.js +21 -14
  6. package/lib/account-session.js +6 -2
  7. package/lib/advisory-compression.js +25 -0
  8. package/lib/advisory-fixes.js +21 -0
  9. package/lib/advisory-store-sqlite.js +156 -0
  10. package/lib/advisory-store.js +484 -0
  11. package/lib/airgap-project.js +117 -0
  12. package/lib/application-plugins/runner.js +22 -13
  13. package/lib/application-plugins/wordpress.js +4 -3
  14. package/lib/application-providers/live-snapshot.js +1 -12
  15. package/lib/application-providers/snapshot-cache.js +27 -0
  16. package/lib/application-providers/wordfence-client.js +3 -3
  17. package/lib/attribution.js +2 -2
  18. package/lib/cache-archive-sqlite.js +215 -0
  19. package/lib/cache-archive.js +357 -26
  20. package/lib/cache-db.js +142 -0
  21. package/lib/cache-directory.js +18 -74
  22. package/lib/cache-policy.js +25 -0
  23. package/lib/cache-repository.js +48 -0
  24. package/lib/cache-startup.js +54 -0
  25. package/lib/certfr.js +9 -9
  26. package/lib/cli-command-routing.js +29 -6
  27. package/lib/cli-groups.js +32 -3
  28. package/lib/cli-project-commands.js +47 -6
  29. package/lib/cli-setup.js +300 -0
  30. package/lib/codecs/binary/pe-metadata.js +79 -0
  31. package/lib/codecs/binary/scan.js +4 -3
  32. package/lib/codecs/binary.codec.js +4 -2
  33. package/lib/codecs/composer/registry.js +8 -6
  34. package/lib/codecs/go/parse.js +7 -9
  35. package/lib/codecs/go/registry.js +7 -5
  36. package/lib/codecs/go.codec.js +5 -0
  37. package/lib/codecs/maven.codec.js +73 -8
  38. package/lib/codecs/npm/collect.js +12 -5
  39. package/lib/codecs/npm/parse.js +12 -5
  40. package/lib/codecs/npm/registry.js +42 -12
  41. package/lib/codecs/nuget/registry.js +8 -6
  42. package/lib/codecs/pypi/registry.js +8 -6
  43. package/lib/codecs/ruby/registry.js +7 -5
  44. package/lib/compression-dictionary.js +5 -0
  45. package/lib/coverage-diagnostics.js +26 -0
  46. package/lib/cve-download.js +157 -41
  47. package/lib/cve-legacy-ranges.js +59 -0
  48. package/lib/cve-match.js +85 -17
  49. package/lib/cve-npm-proxy.js +29 -0
  50. package/lib/cve-report.js +145 -58
  51. package/lib/cve-version-verdict.js +77 -0
  52. package/lib/deps-descriptor.js +8 -3
  53. package/lib/epss.js +13 -8
  54. package/lib/euvd.js +32 -8
  55. package/lib/gcve-feed.js +103 -0
  56. package/lib/gcve-index.js +181 -0
  57. package/lib/gcve.js +1 -1
  58. package/lib/github-publisher-maven.js +40 -0
  59. package/lib/hash-id.js +5 -5
  60. package/lib/hosted-proxy.js +6 -1
  61. package/lib/i18n.js +31 -8
  62. package/lib/json-cache.js +18 -0
  63. package/lib/json-export.js +16 -2
  64. package/lib/kev.js +7 -8
  65. package/lib/line-stream.js +23 -0
  66. package/lib/maven-airgap.js +80 -0
  67. package/lib/maven-cache.js +21 -0
  68. package/lib/maven-license.js +2 -1
  69. package/lib/maven-presence.js +2 -2
  70. package/lib/maven-reactor.js +23 -14
  71. package/lib/maven-repo.js +11 -6
  72. package/lib/merge-sources.js +25 -18
  73. package/lib/native-advisories.js +268 -0
  74. package/lib/nvd-bulk.js +145 -0
  75. package/lib/nvd-package-ranges.js +109 -0
  76. package/lib/nvd.js +52 -24
  77. package/lib/osv-db.js +253 -59
  78. package/lib/osv-legacy.js +57 -0
  79. package/lib/osv.js +241 -168
  80. package/lib/outdated.js +11 -12
  81. package/lib/package-metadata.js +141 -0
  82. package/lib/package-versions.js +52 -0
  83. package/lib/packagist-audit.js +6 -6
  84. package/lib/provenance.js +73 -19
  85. package/lib/providers/common.js +11 -1
  86. package/lib/providers/gcve.js +17 -0
  87. package/lib/providers/github.js +1 -0
  88. package/lib/providers/index.js +49 -26
  89. package/lib/providers/vigievuln.js +7 -0
  90. package/lib/proxy-cache.js +1 -1
  91. package/lib/proxy-scope.js +59 -0
  92. package/lib/proxy-throttle.js +71 -0
  93. package/lib/resource-cache/engine.js +36 -9
  94. package/lib/resource-cache/sqlite-store.js +95 -0
  95. package/lib/resource-cache/validate.js +5 -0
  96. package/lib/retire.js +24 -24
  97. package/lib/ruby-version.js +36 -0
  98. package/lib/sarif-export.js +1 -1
  99. package/lib/sbom-export.js +11 -7
  100. package/lib/snyk.js +32 -20
  101. package/lib/source-profile.js +67 -0
  102. package/lib/sqlite-driver.js +46 -0
  103. package/lib/transitive.js +69 -34
  104. package/lib/unmanaged.js +2 -1
  105. package/lib/vigievuln-advisories.js +47 -0
  106. package/package.json +7 -6
  107. package/vigievuln.js +380 -107
package/lib/i18n.js CHANGED
@@ -187,6 +187,28 @@ const fr = {
187
187
  "obsolete": ["obsolète", "obsolètes"],
188
188
  "outdated": "en retard",
189
189
  "unmanaged native binary": "binaire natif non géré",
190
+ "Unverified PE metadata": "Métadonnées PE non vérifiées",
191
+ "Analysis limitation:": "Limite d’analyse :",
192
+ "The binaries in this chapter are not automatically correlated with CVEs. Their metadata may be incomplete, ambiguous or modified, and therefore cannot always reliably identify the exact product and build. Available information is shown to help with manual verification.": "Les binaires présentés dans ce chapitre ne font pas l’objet d’une corrélation automatique avec les CVE. Leurs métadonnées peuvent être incomplètes, ambiguës ou modifiées ; elles ne permettent donc pas toujours d’identifier de façon fiable le produit et le build exacts. Les informations disponibles sont affichées pour faciliter leur vérification manuelle.",
193
+ "Company": "Éditeur",
194
+ "Product version": "Version du produit",
195
+ "Suggested version": "Version proposée",
196
+ "Advisory-specific candidate": "Version candidate pour cet avis",
197
+ "Advisory candidate": "Version candidate pour cet avis",
198
+ "Package-wide safety has not been verified.": "L’absence d’autres vulnérabilités dans cette version n’a pas été vérifiée.",
199
+ "This exact version was verified unaffected by this advisory; other versions remain unknown.": "Cette version précise a été vérifiée comme non affectée par cet avis ; les autres versions restent indéterminées.",
200
+ "Advisory-specific candidate: {ver}. Review other advisories before changing {dep}.": "Version candidate pour cet avis : {ver}. Examinez les autres avis avant de modifier {dep}.",
201
+ "Latest release to review for {dep}: {ver}": "Dernière version à examiner pour {dep} : {ver}",
202
+ "Release to review": "Version à examiner",
203
+ "Package-wide correction": "Correction de l’ensemble du paquet",
204
+ "Advisory candidates address individual advisories only. Other vulnerabilities may affect those versions. No package-wide correction or pin is generated without checking the target version against all advisories. Rescan candidate versions and review compatibility and lockfiles.": "Les versions candidates concernent uniquement chaque avis individuel. D’autres vulnérabilités peuvent affecter ces versions. Aucune correction globale du paquet ni aucun épinglage n’est généré sans vérifier la version cible contre tous les avis. Analysez les versions candidates et vérifiez la compatibilité et les fichiers de verrouillage.",
205
+ "Suggested changes for manual review": "Modifications proposées à vérifier manuellement",
206
+ "Review these proposed changes manually: affected ranges, other vulnerabilities, dependency constraints and compatibility can make a suggested version unsuitable. Re-resolve and test the project after changes.": "Vérifiez manuellement ces propositions : les plages affectées, les autres vulnérabilités, les contraintes de dépendances et la compatibilité peuvent rendre une version proposée inadaptée. Résolvez à nouveau les dépendances et testez le projet après modification.",
207
+ "CVEs": "CVE",
208
+ "File version": "Version du fichier",
209
+ "File description": "Description du fichier",
210
+ "Internal name": "Nom interne",
211
+ "Original filename": "Nom de fichier d’origine",
190
212
  "unmanaged native binaries": "binaires natifs non gérés",
191
213
  "scan alert": "alerte de scan",
192
214
  "scan alerts": "alertes de scan",
@@ -249,7 +271,6 @@ const fr = {
249
271
  "Dependency": "Dépendance",
250
272
  "Description": "Description",
251
273
  "Fix Version": "Version corrigée",
252
- "Fix version": "Version corrigée",
253
274
  "Fixed in": "Corrigée dans",
254
275
  "Source": "Source",
255
276
  "Sources": "Sources",
@@ -315,8 +336,6 @@ const fr = {
315
336
  "External links": "Liens externes",
316
337
  "Base score": "Score de base",
317
338
  "CVSS base score": "Score de base CVSS",
318
- "CVEs covered": "CVE couvertes",
319
- "Pin to ≥": "Épingler à ≥",
320
339
  "Maven Central latest": "Dernière sur Maven Central",
321
340
  "Identity (by checksum)": "Identité (par empreinte)",
322
341
  "SHA-256": "SHA-256",
@@ -369,9 +388,7 @@ const fr = {
369
388
  "Other": "Autre",
370
389
 
371
390
  // ---- Recommended action ----
372
- "Pin {dep} ≥ {ver}": "Épingler {dep} à ≥ {ver}",
373
391
  "No fixed version published — upgrade or replace": "Aucune version corrigée publiée — mettre à niveau ou remplacer",
374
- "or update {dep} {from} → {to}": "ou mettre à jour {dep} {from} → {to}",
375
392
  "pulled in by {dep}": "apportée par {dep}",
376
393
  "Add an <exclusion> in the declaring POM": "Ajouter une <exclusion> dans le POM déclarant",
377
394
  "Add an exclude in the dependency": "Ajouter un exclude sur la dépendance",
@@ -384,7 +401,7 @@ const fr = {
384
401
  "Replace or remove the vendored binary": "Remplacer ou supprimer le binaire embarqué",
385
402
 
386
403
  // ---- Chapter titles ----
387
- "{direct} direct, {indirect} indirect, {dev} dev": "{direct} en direct, {indirect} en indirect, {dev} en dev",
404
+ "{direct} direct prod, {indirect} indirect prod, {devDirect} direct dev/test, {devIndirect} indirect dev/test": "{direct} en direct prod, {indirect} en indirect prod, {devDirect} en direct dev/test, {devIndirect} en indirect dev/test",
388
405
  "Production": "Production",
389
406
  "Vendored JS vulns": "Vulnérabilités JS embarqué",
390
407
  "Dev dependencies": "Dépendances de développement",
@@ -413,6 +430,8 @@ const fr = {
413
430
  "Ignored directories": "Répertoires ignorés",
414
431
  "Methodology, data sources & limitations": "Méthodologie, sources de données et limites",
415
432
  "Warnings & scan-completeness": "Avertissements et complétude du scan",
433
+ "Cached source data used; dates indicate the saved response and may need refreshing.": "Données de sources en cache utilisées ; les dates indiquent les réponses conservées, qui peuvent nécessiter une actualisation.",
434
+ "unknown date": "date inconnue",
416
435
  "Changes since baseline": "Évolution depuis la référence",
417
436
  "+{n} new prod CVE": ["+{n} nouvelle CVE de prod", "+{n} nouvelles CVE de prod"],
418
437
  "All": "Toutes",
@@ -438,6 +457,12 @@ const fr = {
438
457
  "No directories were excluded from the scan.": "Aucun répertoire n'a été exclu du scan.",
439
458
  "No actionable recommendations.": "Aucune recommandation actionnable.",
440
459
  "No provenance manifest available for this run.": "Aucun manifeste de provenance pour cette exécution.",
460
+ "Source coverage limitations": "Limites de couverture des sources",
461
+ "The configured Maven transitive depth was reached; deeper dependencies were not explored.": "La profondeur transitive Maven configurée a été atteinte ; les dépendances situées au-delà n’ont pas été explorées.",
462
+ "Some product-only candidates lack a reliable Maven package identity; independent OSV evidence is used when available.": "Certaines fiches ne précisent que le produit, sans identité Maven fiable ; les éléments indépendants d’OSV sont utilisés lorsqu’ils existent.",
463
+ "The Maven lookup uses a partial native or legacy projection; some source records may not be represented.": "La recherche Maven utilise une projection partielle des fiches natives ou historiques ; certaines fiches de la source peuvent ne pas être représentées.",
464
+ "Partial source coverage: {missing} GNA source(s) not collected; {unindexed} source records lack explicit package coordinates. These records are not necessarily relevant to this project.": "Couverture partielle : {missing} source(s) GNA non collectée(s) ; {unindexed} fiches de la source ne précisent pas de coordonnées de paquet. Elles ne concernent pas nécessairement ce projet.",
465
+ "NVD returned no record for {n} package-linked CVE(s) at the last consultation.": "NVD n’a renvoyé aucune fiche pour {n} CVE liée(s) à un paquet lors de la dernière consultation.",
441
466
  "No dependency descriptors were parsed (deps came only from registries or committed binaries).": "Aucun descripteur de dépendances n'a été analysé (les dépendances proviennent uniquement des registres ou de binaires versionnés).",
442
467
  "No license data — the license scan is off by default (enable with <code>--licenses</code>); also empty when offline or registries return none.": "Aucune donnée de licence — l'analyse des licences est désactivée par défaut (activez-la avec <code>--licenses</code>) ; elle est également vide hors ligne ou si les registres n'en renvoient aucune.",
443
468
 
@@ -472,11 +497,9 @@ const fr = {
472
497
 
473
498
  // ---- Chapter 5 — fix recommendations ----
474
499
  "Direct deps to update": "Dépendances directes à mettre à jour",
475
- "Every direct dep with at least one CVE matched. The \"Pin to ≥\" column shows the highest fix-version declared across the CVEs for that dep. When that's missing, the dep needs a manual triage (no clean fix is published).": "Toute dépendance directe pour laquelle au moins une CVE a été trouvée. La colonne « Épingler à ≥ » indique la version corrigée la plus élevée déclarée parmi les CVE de cette dépendance. À défaut, la dépendance demande un tri manuel (aucun correctif propre n'est publié).",
476
500
  "— (manual triage)": "— (tri manuel)",
477
501
  "{n} CVE:": "{n} CVE :",
478
502
  "{n} additional pins omitted from the snippet — see the table below.": ["{n} épinglage supplémentaire omis de l'extrait — voir le tableau ci-dessous.", "{n} épinglages supplémentaires omis de l'extrait — voir le tableau ci-dessous."],
479
- "— (no clean fix declared)": "— (aucun correctif propre déclaré)",
480
503
  "(no update available)": "(aucune mise à jour disponible)",
481
504
  "latest released {date}": "dernière publiée le {date}",
482
505
  "{n} CVE in transitives": "{n} CVE dans les transitives",
@@ -0,0 +1,18 @@
1
+ 'use strict';
2
+
3
+ const {createCacheRepository} = require('./cache-repository');
4
+
5
+ function load(cacheDir, key, fallback) {
6
+ try { return createCacheRepository(cacheDir).get('auxiliary', key)?.value ?? fallback; }
7
+ catch { return fallback; }
8
+ }
9
+
10
+ function save(cacheDir, key, value) {
11
+ try {
12
+ createCacheRepository(cacheDir).put('auxiliary', key, value, {
13
+ fetchedAt: Number.isSafeInteger(value?.meta?.fetchedAt) && value.meta.fetchedAt > 0 ? value.meta.fetchedAt : Date.now(),
14
+ });
15
+ } catch { /* Optional cache. */ }
16
+ }
17
+
18
+ module.exports = {load, save};
@@ -66,11 +66,18 @@ function cveFinding(m) {
66
66
  euvdExploited: euvdExploited(c),
67
67
  euvdExploitedSince: c.euvd?.exploitedSince || null,
68
68
  gcve: c.gcve || null,
69
+ gcveSource: c.gcveSource || null,
70
+ gcveRecordType: c.gcveRecordType || null,
71
+ gcveRelationships: c.gcveRelationships || [],
69
72
  certfr: (c.certfr || []).map(a => a.ref),
70
73
  priority: c.priority ? { band: c.priority.band, score: c.priority.score } : null,
71
74
  cwes: c.cwes || [],
72
75
  fixVersion: c.fixVersion || null,
73
- source: m.source || null,
76
+ ...(c.fixVersion && c.fixEvidence ? { fixEvidence: c.fixEvidence } : {}),
77
+ ...(c.fixVersion ? { fixScope: 'advisory', packageFixVerified: false } : {}),
78
+ ...(c.fixConflict ? { fixConflict: c.fixConflict } : {}),
79
+ source: m.source || "cache",
80
+ ...(Array.isArray(c.affectedProviders) && c.affectedProviders.length ? { affectedProviders: c.affectedProviders } : {}),
74
81
  confidence: m.confidence || null,
75
82
  malicious: !!m.malicious,
76
83
  cpeFiltered: !!m.cpeFiltered,
@@ -102,6 +109,11 @@ function buildFindings(payload = {}) {
102
109
 
103
110
  const uniqueCveMatches = uniqueFindings(cveMatches);
104
111
  const findingSummary = summarizeFindings(uniqueCveMatches);
112
+ // Count diagnostic signals as well as incomplete application capabilities.
113
+ // Several signals can describe the same gap; this is not a count of sources.
114
+ const applicationCoverageIncomplete = coverage.filter(c => c.execution === "partial" || c.execution === "not-run" || c.execution === "failed").length;
115
+ const coverageWarningTypes = new Set(["source-unavailable", "source-stale", "dependency-coverage", "osv-coverage", "go-coverage", "unresolved-versions", "no-lockfile", "parse-error", "missing-include", "local-replace", "private-libs"]);
116
+ const coverageWarnings = warnings.filter(w => coverageWarningTypes.has(w.type)).length;
105
117
 
106
118
  return {
107
119
  schema: "fad-findings/1",
@@ -131,7 +143,9 @@ function buildFindings(payload = {}) {
131
143
  excludedDirs: excludedDirs.length,
132
144
  applications: applications.length,
133
145
  applicationComponents: applicationInventory.length,
134
- coverageIncomplete: coverage.filter(c => c.execution === "partial" || c.execution === "not-run" || c.execution === "failed").length,
146
+ applicationCoverageIncomplete,
147
+ coverageWarnings,
148
+ coverageIncomplete: applicationCoverageIncomplete + coverageWarnings,
135
149
  },
136
150
  findingSummary,
137
151
  cve: uniqueCveMatches.map(cveFinding),
package/lib/kev.js CHANGED
@@ -5,7 +5,7 @@
5
5
  * exploited in the wild. Membership is the strongest "patch this now" signal.
6
6
  *
7
7
  * Feed: https://www.cisa.gov/sites/default/files/feeds/known_exploited_vulnerabilities.json
8
- * Cache: ~/.fad-checker/kev-cache.json, 24h TTL.
8
+ * Cache: ~/.fad-checker/kev-cache.json, 4h TTL.
9
9
  *
10
10
  * @author: N.BRAUN
11
11
  * @email: pp9ping@gmail.com
@@ -16,21 +16,20 @@ const os = require("os");
16
16
 
17
17
  const CACHE_DIR = path.join(require("./cache-directory").getCacheDir());
18
18
  const CACHE_PATH = path.join(CACHE_DIR, "kev-cache.json");
19
- const CACHE_TTL_MS = 24 * 3600 * 1000;
19
+ const CACHE_TTL_MS = 4 * 3600 * 1000;
20
20
  const KEV_URL = "https://www.cisa.gov/sites/default/files/feeds/known_exploited_vulnerabilities.json";
21
21
 
22
22
  function readCache({ offline = false } = {}) {
23
23
  try {
24
- const data = JSON.parse(fs.readFileSync(CACHE_PATH, "utf8"));
25
- if (offline || Date.now() - data._fetchedAt < CACHE_TTL_MS) return data.body;
24
+ const data = require('./cache-repository').createCacheRepository(CACHE_DIR).get('catalogue','kev')?.value;
25
+ if (offline || require('./cache-policy').fresh(data._fetchedAt, CACHE_TTL_MS)) return data.body;
26
26
  } catch { /* ignore */ }
27
27
  return null;
28
28
  }
29
29
 
30
- function writeCache(body) {
30
+ function writeCache(body, fetchedAt = Date.now()) {
31
31
  try {
32
- fs.mkdirSync(CACHE_DIR, { recursive: true });
33
- fs.writeFileSync(CACHE_PATH, JSON.stringify({ _fetchedAt: Date.now(), body }));
32
+ require('./cache-repository').createCacheRepository(CACHE_DIR).put('catalogue','kev',{ _fetchedAt: fetchedAt, body });
34
33
  } catch { /* ignore */ }
35
34
  }
36
35
 
@@ -81,7 +80,7 @@ async function enrichKev(matches, opts = {}) {
81
80
  { fetcher, headers: { "User-Agent": "vigievuln-kev" } });
82
81
  if (r.ok) {
83
82
  index = indexKevCatalog(await r.json());
84
- writeCache(index);
83
+ writeCache(index, require('./providers/common').responseFetchedAt(r));
85
84
  } else if (verbose) {
86
85
  console.warn(` KEV HTTP ${r.status}`);
87
86
  }
@@ -0,0 +1,23 @@
1
+ 'use strict';
2
+ const {StringDecoder}=require('node:string_decoder');
3
+
4
+ // JSONL is delimited by LF, not the additional Unicode separators that the
5
+ // readline module treats as line endings. Decode incrementally across chunks.
6
+ async function* readTextLines(stream,{maxBytes=16*1024*1024}={}) {
7
+ const decoder=new StringDecoder('utf8');let pending='';
8
+ try {
9
+ for await(const chunk of stream) {
10
+ pending+=typeof chunk==='string'?chunk:decoder.write(chunk);let at;
11
+ while((at=pending.indexOf('\n'))!==-1) {
12
+ const line=pending.slice(0,at);pending=pending.slice(at+1);
13
+ if(Buffer.byteLength(line)>maxBytes)throw Error('line exceeds size limit');
14
+ yield line;
15
+ }
16
+ if(pending.length>maxBytes)throw Error('line exceeds size limit');
17
+ }
18
+ pending+=decoder.end();
19
+ if(Buffer.byteLength(pending)>maxBytes)throw Error('line exceeds size limit');
20
+ if(pending)yield pending;
21
+ } finally {stream.destroy();}
22
+ }
23
+ module.exports={readTextLines};
@@ -0,0 +1,80 @@
1
+ 'use strict';
2
+
3
+ // Reconstruct Maven's per-module resolution without exporting project paths,
4
+ // POMs, arbitrary properties or application source.
5
+ const {coord}=require('./core');
6
+ const {resolveDepVersion}=require('./cve-match');
7
+ const {localChain,chainPropertyOverrides}=require('./maven-reactor');
8
+ const {cleanVersion,filterVersionProperties}=require('./deps-descriptor');
9
+ const IDENT=/^[A-Za-z0-9_.-]+$/;
10
+ const EXCLUSION=/^[A-Za-z0-9_.*-]+$/;
11
+ const SCOPES=new Set(['compile','runtime','provided','test','system','import']);
12
+ const text=x=>typeof x==='string'&&x.length<=4096?x:null;
13
+ const ident=x=>{x=text(x);return x&&IDENT.test(x)?x:null};
14
+ const version=x=>{x=text(x);return x?cleanVersion(x):null};
15
+ const nodeValue=(node,key,props)=>resolveDepVersion(coord(node?.[key]?.[0])||'',props)||null;
16
+
17
+ function nodeHint(node,props,exclude){
18
+ const groupId=ident(nodeValue(node,'groupId',props)),artifactId=ident(nodeValue(node,'artifactId',props));
19
+ if(!groupId||!artifactId||(exclude&&exclude.test(groupId)))return null;
20
+ const scope=coord(node.scope?.[0])||null,type=ident(nodeValue(node,'type',props)),classifier=ident(nodeValue(node,'classifier',props));
21
+ const exclusions=[];
22
+ for(const x of node.exclusions?.[0]?.exclusion||[]){
23
+ const g=text(nodeValue(x,'groupId',props)||'*'),a=text(nodeValue(x,'artifactId',props)||'*');
24
+ if(g&&a&&EXCLUSION.test(g)&&EXCLUSION.test(a))exclusions.push({groupId:g,artifactId:a});
25
+ }
26
+ return {groupId,artifactId,version:version(nodeValue(node,'version',props)),
27
+ ...(scope&&SCOPES.has(scope)?{scope}:{}),...(type?{type}:{}),...(classifier?{classifier}:{}),
28
+ ...(coord(node.optional?.[0])==='true'?{optional:true}:{}),...(exclusions.length?{exclusions}:{})};
29
+ }
30
+
31
+ function buildReactorHints({store,propsByPom},{exclude,versionPropertyNames=[]}={}){
32
+ if(!store||!propsByPom)return null;
33
+ const modules=[];
34
+ for(const pom of Object.keys(propsByPom)){
35
+ if(!store.byPath[pom])continue;
36
+ const {chain,externalParent}=localChain(pom,store),props=propsByPom[pom]?.properties||{},dependencies=[],management=[];
37
+ for(const member of chain){
38
+ const entry=propsByPom[member]||{};
39
+ for(const node of entry.dependencies||[]){const h=nodeHint(node,props,exclude);if(h)dependencies.push(h)}
40
+ for(const node of entry.dependencyManagement||[]){
41
+ const h=nodeHint(node,entry.properties||{},exclude);if(!h)continue;
42
+ if(h.scope==='import'&&((h.version&&store.byId[`${h.groupId}:${h.artifactId}:${h.version}`])||store.byId[`${h.groupId}:${h.artifactId}`]))continue;
43
+ management.push(h);
44
+ }
45
+ }
46
+ const parent=externalParent&&ident(externalParent.groupId)&&ident(externalParent.artifactId)&&version(externalParent.version)
47
+ ? {groupId:externalParent.groupId,artifactId:externalParent.artifactId,version:version(externalParent.version)} : null;
48
+ modules.push({dependencies,management,...(parent&&!(exclude&&exclude.test(parent.groupId))?{parent}:{}),
49
+ overrides:filterVersionProperties(chainPropertyOverrides(chain,store),versionPropertyNames)});
50
+ }
51
+ return modules.length?{schema:1,modules}:null;
52
+ }
53
+
54
+ function restoreReactorHints(hints){
55
+ if(!hints||hints.schema!==1||!Array.isArray(hints.modules)||hints.modules.length>5000)throw Error('invalid Maven reactor hints');
56
+ const store={byPath:{},byId:{},excludedById:{},missingById:{},anyMissingById:{}},propsByPom={};let total=0;
57
+ const readNode=x=>{
58
+ if(!x||!ident(x.groupId)||!ident(x.artifactId)||x.version!=null&&!version(x.version)||x.scope!=null&&!SCOPES.has(x.scope)||x.type!=null&&!ident(x.type)||x.classifier!=null&&!ident(x.classifier)||x.optional!=null&&typeof x.optional!=='boolean'||x.exclusions!=null&&!Array.isArray(x.exclusions))throw Error('invalid Maven reactor dependency');
59
+ const n={groupId:[x.groupId],artifactId:[x.artifactId]};
60
+ for(const k of ['version','scope','type','classifier'])if(x[k])n[k]=[x[k]];
61
+ if(x.optional)n.optional=['true'];
62
+ if(x.exclusions?.length){if(x.exclusions.length>1000)throw Error('too many Maven exclusions');n.exclusions=[{exclusion:x.exclusions.map(e=>{
63
+ if(!e||!text(e.groupId)||!EXCLUSION.test(e.groupId)||!text(e.artifactId)||!EXCLUSION.test(e.artifactId))throw Error('invalid Maven exclusion');
64
+ return {groupId:[e.groupId],artifactId:[e.artifactId]};})}];}
65
+ return n;
66
+ };
67
+ for(const [i,m] of hints.modules.entries()){
68
+ if(!m||!Array.isArray(m.dependencies)||!Array.isArray(m.management)||!m.overrides||typeof m.overrides!=='object'||Array.isArray(m.overrides))throw Error('invalid Maven reactor module');
69
+ total+=m.dependencies.length+m.management.length;if(total>100000)throw Error('too many Maven reactor entries');
70
+ const overrides=filterVersionProperties(m.overrides,Object.keys(m.overrides));
71
+ if(Object.keys(overrides).length!==Object.keys(m.overrides).length)throw Error('invalid Maven version overrides');
72
+ let parent=null;
73
+ if(m.parent){if(!ident(m.parent.groupId)||!ident(m.parent.artifactId)||!version(m.parent.version))throw Error('invalid Maven reactor parent');parent={groupId:m.parent.groupId,artifactId:m.parent.artifactId,version:m.parent.version};}
74
+ const id=`@module-${i}`;
75
+ store.byPath[id]={pomPath:id,parentInfo:parent,properties:overrides};
76
+ propsByPom[id]={properties:{},dependencies:m.dependencies.map(readNode),dependencyManagement:m.management.map(readNode)};
77
+ }
78
+ return {store,propsByPom};
79
+ }
80
+ module.exports={buildReactorHints,restoreReactorHints};
@@ -0,0 +1,21 @@
1
+ 'use strict';
2
+
3
+ const path = require('node:path');
4
+ const {createCacheRepository} = require('./cache-repository');
5
+
6
+ function slot(file) {
7
+ const dir=path.dirname(file);
8
+ return {cacheDir:path.basename(dir)==='poms-cache'?path.dirname(dir):dir,
9
+ key:path.basename(file),namespace:file.endsWith('.pom')?'maven-pom':'maven-metadata'};
10
+ }
11
+ function read(file) {
12
+ const {cacheDir,key,namespace}=slot(file);
13
+ try { return createCacheRepository(cacheDir).get(namespace,key); }
14
+ catch { return null; }
15
+ }
16
+ function write(file,value) {
17
+ const {cacheDir,key,namespace}=slot(file);
18
+ try { createCacheRepository(cacheDir).put(namespace,key,value); }
19
+ catch { /* Optional cache. */ }
20
+ }
21
+ module.exports={read,write};
@@ -43,7 +43,8 @@ function collectMavenLicenses(resolved, opts = {}) {
43
43
  if (dep.ecosystem !== "maven" || !dep.version) continue;
44
44
  const p = cachedPomPath(dep.namespace || dep.groupId, dep.name || dep.artifactId, dep.version, cacheDir);
45
45
  let xml;
46
- try { xml = fs.readFileSync(p, "utf8"); } catch { continue; }
46
+ xml = require('./maven-cache').read(p)?.value;
47
+ if(!xml || xml==='__NOT_FOUND__')continue;
47
48
  const names = licensesFromPomXml(xml);
48
49
  if (names.length) out.push({ dep, licenses: names, source: "pom" });
49
50
  }
@@ -9,7 +9,7 @@ const core = require("./core");
9
9
  const { existsInAny } = require("./maven-repo");
10
10
  const { isAbsentStatus } = require("./private-deps");
11
11
 
12
- const MAX_AGE_MS = 7 * 24 * 3600 * 1000;
12
+ const MAX_AGE_MS = 4 * 3600 * 1000;
13
13
  const ABSENCE_EVIDENCE = "all-repositories-404-or-410/1";
14
14
 
15
15
  function repositoryKey(repos) {
@@ -50,7 +50,7 @@ async function checkMavenLibExist(groupId, artifactId, repos, cache, opts = {})
50
50
  const entry = cache?.entries?.[key];
51
51
  if (entry === true) return true;
52
52
  if (confirmedAbsence(entry) && entry.repositories === repositories
53
- && (opts.offline || (now >= entry.checkedAt && now - entry.checkedAt < MAX_AGE_MS))) return false;
53
+ && (opts.offline || require('./cache-policy').fresh(entry.checkedAt, MAX_AGE_MS, now))) return false;
54
54
  if (cache?.entries) delete cache.entries[key];
55
55
  if (opts.offline) return null;
56
56
 
@@ -31,7 +31,7 @@
31
31
  * @email: pp9ping@gmail.com
32
32
  */
33
33
  const core = require("./core");
34
- const { effectivePom, resolveTransitiveDeps, fetchMetadataVersions } = require("./transitive");
34
+ const { effectivePom, resolveTransitiveDeps, fetchMetadataVersions, managedKey } = require("./transitive");
35
35
  const { resolveDepVersion } = require("./cve-match");
36
36
  const { isVersionRange, resolveVersionRange, compareMavenVersions } = require("./maven-version");
37
37
 
@@ -109,7 +109,8 @@ async function moduleManagement(chain, externalParent, store, propsByPom, opts)
109
109
  if (!local && isConcrete(v)) externalBoms.push({ groupId: g, artifactId: a, version: v });
110
110
  continue;
111
111
  }
112
- setIf(`${g}:${a}`, { version: v, scope: coord(node.scope?.[0]) || null, exclusions: exclusionsOf(node, props), source: null });
112
+ const type = resolveDepVersion(coord(node.type?.[0]) || 'jar', props), classifier = resolveDepVersion(coord(node.classifier?.[0]) || '', props);
113
+ setIf(managedKey({groupId:g,artifactId:a,type,classifier}), { version: v, scope: coord(node.scope?.[0]) || null, exclusions: exclusionsOf(node, props), source: null });
113
114
  }
114
115
  }
115
116
  const imported = [];
@@ -119,15 +120,15 @@ async function moduleManagement(chain, externalParent, store, propsByPom, opts)
119
120
  try { eff = await effectivePom(externalParent.groupId, externalParent.artifactId, externalParent.version, { ...opts, propertyOverrides: chainPropertyOverrides(chain, store) }); } catch { eff = null; }
120
121
  for (const d of eff?.depMgmt || []) {
121
122
  const e = { version: d.version, scope: d.scopeDeclared ? d.scope : null, exclusions: d.exclusions || [], source: { via: "parent", bom: coordStr } };
122
- if (d.fromImport) imported.push([`${d.groupId}:${d.artifactId}`, e]);
123
- else setIf(`${d.groupId}:${d.artifactId}`, e);
123
+ if (d.fromImport) imported.push([managedKey(d), e]);
124
+ else setIf(managedKey(d), e);
124
125
  }
125
126
  }
126
127
  for (const bom of externalBoms) {
127
128
  const coordStr = `${bom.groupId}:${bom.artifactId}:${bom.version}`;
128
129
  let eff = null;
129
130
  try { eff = await effectivePom(bom.groupId, bom.artifactId, bom.version, opts); } catch { eff = null; }
130
- for (const d of eff?.depMgmt || []) setIf(`${d.groupId}:${d.artifactId}`, { version: d.version, scope: d.scopeDeclared ? d.scope : null, exclusions: d.exclusions || [], source: { via: "bom", bom: coordStr } });
131
+ for (const d of eff?.depMgmt || []) setIf(managedKey(d), { version: d.version, scope: d.scopeDeclared ? d.scope : null, exclusions: d.exclusions || [], source: { via: "bom", bom: coordStr } });
131
132
  }
132
133
  for (const [k, e] of imported) setIf(k, e);
133
134
  return out;
@@ -140,14 +141,17 @@ async function moduleManagement(chain, externalParent, store, propsByPom, opts)
140
141
  async function moduleDirects(pomPath, chain, externalParent, mgmt, store, propsByPom, opts) {
141
142
  const props = propsByPom[pomPath]?.properties || {};
142
143
  const out = [];
143
- const seen = new Set();
144
+ const seen = new Map();
144
145
  const add = async (d) => {
145
146
  const key = `${d.groupId}:${d.artifactId}`;
146
147
  if (opts.deps2Exclude && opts.deps2Exclude.test(d.groupId)) return; // -e: private, never scanned
147
148
  if (/\$\{/.test(key)) return;
148
- if (seen.has(key)) return;
149
- seen.add(key);
150
- const m = mgmt.get(key);
149
+ if (seen.has(key)) {
150
+ if (seen.get(key) !== managedKey(d)) opts.onVariantCollision?.({groupId:d.groupId,artifactId:d.artifactId});
151
+ return;
152
+ }
153
+ seen.set(key, managedKey(d));
154
+ const m = mgmt.get(managedKey(d));
151
155
  let version = d.version;
152
156
  let versionSource = null;
153
157
  if (!isConcrete(version) && !isVersionRange(String(version || ""))) {
@@ -162,7 +166,7 @@ async function moduleDirects(pomPath, chain, externalParent, mgmt, store, propsB
162
166
  if (scope === "test" && !opts.includeTestDeps) return;
163
167
  const ex = [...(d.exclusions || []), ...(m?.exclusions || [])];
164
168
  out.push({ groupId: d.groupId, artifactId: d.artifactId, version: isConcrete(version) ? String(version) : null,
165
- scope, exclusions: ex, declaredIn: d.declaredIn, versionSource, optional: !!d.optional });
169
+ scope, exclusions: ex, type:d.type || 'jar', classifier:d.classifier || '', declaredIn: d.declaredIn, versionSource, optional: !!d.optional });
166
170
  };
167
171
  for (const pom of chain) {
168
172
  for (const node of propsByPom[pom]?.dependencies || []) {
@@ -170,7 +174,7 @@ async function moduleDirects(pomPath, chain, externalParent, mgmt, store, propsB
170
174
  const a = resolveDepVersion(coord(node.artifactId?.[0]), props);
171
175
  if (!g || !a) continue;
172
176
  await add({ groupId: g, artifactId: a, version: resolveDepVersion(coord(node.version?.[0]), props) || null,
173
- scope: coord(node.scope?.[0]) || null, exclusions: exclusionsOf(node, props),
177
+ scope: coord(node.scope?.[0]) || null, type:resolveDepVersion(coord(node.type?.[0]) || 'jar', props), classifier:resolveDepVersion(coord(node.classifier?.[0]) || '', props), exclusions: exclusionsOf(node, props),
174
178
  optional: node.optional?.[0] === "true", declaredIn: pom });
175
179
  }
176
180
  }
@@ -181,7 +185,7 @@ async function moduleDirects(pomPath, chain, externalParent, mgmt, store, propsB
181
185
  try { eff = await effectivePom(externalParent.groupId, externalParent.artifactId, externalParent.version, { ...opts, propertyOverrides: chainPropertyOverrides(chain, store) }); } catch { eff = null; }
182
186
  for (const d of eff?.deps || []) {
183
187
  await add({ groupId: d.groupId, artifactId: d.artifactId, version: d.version || null,
184
- scope: d.scopeDeclared ? d.scope : null, exclusions: d.exclusions || [], optional: d.optional,
188
+ scope: d.scopeDeclared ? d.scope : null, type:d.type, classifier:d.classifier, exclusions: d.exclusions || [], optional: d.optional,
185
189
  declaredIn: pomPath, inheritedFrom: `${externalParent.groupId}:${externalParent.artifactId}:${externalParent.version}` });
186
190
  }
187
191
  }
@@ -203,12 +207,17 @@ async function resolveModule(pomPath, store, propsByPom, opts) {
203
207
  maxDepth: opts.maxDepth || 6,
204
208
  includedScopes: opts.includeTestDeps ? ["compile", "runtime", "provided", "test"] : ["compile", "runtime", "provided"],
205
209
  });
206
- } catch { transitives = new Map(); }
210
+ } catch {
211
+ // Preserve a usable partial report, but never make a failed traversal
212
+ // indistinguishable from a complete graph with no transitives.
213
+ opts.onResolutionError?.();
214
+ transitives = new Map();
215
+ }
207
216
  }
208
217
  return { pomPath, directs, transitives };
209
218
  }
210
219
 
211
- const DEV_SCOPES = new Set(["test", "provided"]);
220
+ const DEV_SCOPES = new Set(["test"]);
212
221
 
213
222
  /**
214
223
  * Resolve every module and rebuild the maven-codec records of `resolved` from the union.
package/lib/maven-repo.js CHANGED
@@ -128,7 +128,7 @@ function buildRepoList(userRepos, extraRepos = [], { mirrors = true } = {}) {
128
128
  for (const r of userRepos || []) push(r);
129
129
  for (const r of extraRepos || []) push(r);
130
130
  push(MAVEN_CENTRAL);
131
- if (mirrors) for (const m of DEFAULT_CENTRAL_MIRRORS) push(m);
131
+ if (mirrors && !require('./providers').hasHostedProxy()) for (const m of DEFAULT_CENTRAL_MIRRORS) push(m);
132
132
  return out;
133
133
  }
134
134
 
@@ -189,10 +189,12 @@ async function tryRepos(repos, pathSuffix, opts = {}) {
189
189
  if (ah) headers.Authorization = ah;
190
190
  let r;
191
191
  try {
192
- r = await withDeadline(timeoutMs, signal => require("./providers").getResource("maven", "artifact",
193
- { path: pathSuffix.replace(/^\/+/, ""), method },
194
- { fetcher, headers, signal, ...(url === `https://repo1.maven.org/maven2/${pathSuffix.replace(/^\/+/, "")}`
195
- ? {} : { urlOverride: url, direct: true }) }));
192
+ const providers = require("./providers");
193
+ const official = repo.url === MAVEN_CENTRAL.url && !repo.auth && !repo.token;
194
+ const params = { path: pathSuffix.replace(/^\/+/, ""), method };
195
+ if (official && providers.hasHostedProxy()) r = await providers.getResource("maven", "artifact", params, {fetcher, headers, requestTimeoutMs:timeoutMs});
196
+ else r = await withDeadline(timeoutMs, signal => providers.getResource("maven", "artifact", params,
197
+ { fetcher, headers, signal, ...(official ? {} : { urlOverride: url, direct: true }) }));
196
198
  } catch (err) {
197
199
  // Unreachable or timed out: a mirror that does this once will do it for every
198
200
  // remaining coordinate, so take it out of the rotation for the run.
@@ -234,7 +236,10 @@ async function reachableRepos(repos, opts = {}) {
234
236
  const ah = repoAuthHeader(repo);
235
237
  if (ah) headers.Authorization = ah;
236
238
  try {
237
- await withDeadline(timeoutMs, signal => require("./providers").getResource("maven", "preflight", {},
239
+ const providers = require("./providers");
240
+ if (providers.hasHostedProxy() && repo.url === MAVEN_CENTRAL.url && !repo.auth && !repo.token)
241
+ await providers.getResource("maven", "preflight", {}, {fetcher, headers, requestTimeoutMs:timeoutMs});
242
+ else await withDeadline(timeoutMs, signal => providers.getResource("maven", "preflight", {},
238
243
  { fetcher, headers, signal, urlOverride: repo.url, direct: true }));
239
244
  return repo;
240
245
  } catch {
@@ -39,25 +39,23 @@ function mergeBySource(existing, additions) {
39
39
  // knew the advisory by its GHSA alone (Packagist: no `cve` field) and the incoming one
40
40
  // is CVE-keyed with that GHSA in its aliases — the same advisory emitted twice.
41
41
  // The primary id is tried first so an exact-key match always wins over an alias one.
42
- const findSlot = m => {
42
+ const findSlots = m => {
43
+ const slots = new Set();
43
44
  for (const id of idsOf(m)) {
44
45
  const k = keyOf(m, id);
45
- if (byKey.has(k)) return k;
46
- if (aliasIndex.has(k)) return aliasIndex.get(k);
46
+ if (byKey.has(k)) slots.add(k);
47
+ if (aliasIndex.has(k) && byKey.has(aliasIndex.get(k))) slots.add(aliasIndex.get(k));
47
48
  }
48
- return null;
49
+ return [...slots];
49
50
  };
50
51
  const isCve = id => /^CVE-/i.test(String(id || ""));
51
52
 
52
53
  for (const m of existing || []) {
53
- const rec = { ...m, source: m.source || "fad" };
54
+ const rec = { ...m, source: m.source || "cache" };
54
55
  // `existing` is normally the output of a previous merge, but two of its records
55
56
  // can still be one advisory (e.g. both came from one lane's alias pair) — fold
56
57
  // them the same way as additions rather than overwriting by key.
57
- const slot = findSlot(rec);
58
- if (slot) { mergeInto(slot, rec); continue; }
59
- byKey.set(primary(rec), rec);
60
- register(rec, primary(rec));
58
+ absorb(rec);
61
59
  }
62
60
  function mergeInto(targetKey, m) {
63
61
  const prev = byKey.get(targetKey);
@@ -78,18 +76,17 @@ function mergeBySource(existing, additions) {
78
76
  cve: {
79
77
  ...prev.cve,
80
78
  ...m.cve,
79
+ ...require('./advisory-fixes').mergeAdvisoryFixes(prev.cve,m.cve),
81
80
  id,
82
81
  // an advisory's identity is the UNION of its ids — dropping the
83
82
  // previous aliases on merge would unlink the alias index. Both primary
84
83
  // ids join it too, so the one not displayed stays an alias.
85
84
  aliases: [...new Set([...(prev.cve.aliases || []), ...(m.cve.aliases || []),
86
- prev.cve.id, m.cve.id].filter(Boolean))].filter(a => a !== id),
85
+ prev.cve.id, m.cve.id, prev.cve.ghsa, m.cve.ghsa].filter(Boolean))].filter(a => a !== id),
87
86
  ghsa: prev.cve.ghsa || m.cve.ghsa || null,
88
- // the fix on the dep's own branch: two sources may state it differently
89
- // (fixed 5.3.41 vs last affected 5.3.40) — keep the one an upgrade must meet.
90
- ...((prev.cve.branchFix || m.cve.branchFix) ? { branchFix: require("./maven-version").stricterBranchFix(prev.cve.branchFix, m.cve.branchFix) } : {}),
91
87
  // keep highest non-null score
92
88
  score: Math.max(prev.cve.score ?? 0, m.cve.score ?? 0) || prev.cve.score || m.cve.score,
89
+ cvssVector: m.cve.cvssVector || prev.cve.cvssVector || null,
93
90
  // prefer non-UNKNOWN severity
94
91
  severity: (prev.cve.severity && prev.cve.severity !== "UNKNOWN") ? prev.cve.severity : m.cve.severity,
95
92
  // prefer the longer description
@@ -99,12 +96,22 @@ function mergeBySource(existing, additions) {
99
96
  byKey.set(targetKey, merged);
100
97
  register(merged, targetKey);
101
98
  }
99
+ function absorb(rec) {
100
+ const slots = findSlots(rec);
101
+ if (!slots.length) { byKey.set(primary(rec), rec); register(rec, primary(rec)); return; }
102
+ const target = slots[0];
103
+ // One new alias can connect two previously independent groups. Fold the
104
+ // whole component so a conflicting target cannot survive in a second row.
105
+ for (const other of slots.slice(1)) {
106
+ mergeInto(target, byKey.get(other));
107
+ byKey.delete(other);
108
+ for (const [alias, slot] of aliasIndex) if (slot === other) aliasIndex.set(alias, target);
109
+ }
110
+ mergeInto(target, rec);
111
+ }
102
112
  for (const m of additions || []) {
103
- const slot = findSlot(m);
104
- if (slot) { mergeInto(slot, m); continue; }
105
- const rec = { ...m, source: m.source || "osv" };
106
- byKey.set(primary(m), rec);
107
- register(rec, primary(m));
113
+ const rec = { ...m, source: m.source || "cache" };
114
+ absorb(rec);
108
115
  }
109
116
  const merged = [...byKey.values()];
110
117
  const rank = { CRITICAL: 4, HIGH: 3, MEDIUM: 2, LOW: 1, NONE: 0, UNKNOWN: 0 };