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
@@ -105,7 +105,7 @@ function serializeDeps(resolvedMap, opts = {}) {
105
105
  const propertyOverrides = filterVersionProperties(opts.propertyOverrides, opts.versionPropertyNames);
106
106
  const omitted = Object.keys(opts.propertyOverrides || {}).length - Object.keys(propertyOverrides).length;
107
107
  if (omitted) opts.onOmittedProperties?.(omitted);
108
- const hasMavenHints = externalParents.length || importBoms.length || Object.keys(propertyOverrides).length;
108
+ const hasMavenHints = externalParents.length || importBoms.length || Object.keys(propertyOverrides).length || opts.reactor;
109
109
  // Application identities: the CMS/framework PRODUCT coordinates (type + core
110
110
  // version) and its inventoried PUBLIC component identities — vendor catalogue
111
111
  // info, no paths, private components never included. They are what no package
@@ -127,7 +127,7 @@ function serializeDeps(resolvedMap, opts = {}) {
127
127
  generatedAt,
128
128
  note,
129
129
  summary: { total: deps.length, byEcosystem, ...(applications.length ? { applications: applications.length } : {}) },
130
- ...(hasMavenHints ? { maven: { externalParents, importBoms, propertyOverrides } } : {}),
130
+ ...(hasMavenHints ? { maven: { externalParents, importBoms, propertyOverrides, ...(opts.reactor ? { reactor: opts.reactor } : {}) } } : {}),
131
131
  ...(applications.length ? { applications } : {}),
132
132
  deps,
133
133
  };
@@ -151,12 +151,16 @@ function deserializeDeps(descriptor) {
151
151
  if (!e || !e.ecosystem || !e.name) continue;
152
152
  const rec = makeDepRecord({
153
153
  ecosystem: e.ecosystem,
154
+ ...(e.ecosystem === 'binary' ? {provenance:'binary'} : {}),
154
155
  ecosystemType: e.ecosystemType || e.ecosystem,
155
156
  namespace: e.namespace || "",
156
157
  name: e.name,
157
158
  version: e.version || null,
158
159
  scope: e.scope || "prod",
159
- isDev: !!e.isDev,
160
+ // Older descriptors marked provided Maven and optional npm packages
161
+ // as dev-only even though they can run in production.
162
+ isDev: (e.ecosystem === 'maven' && e.scope === 'provided') ||
163
+ (e.ecosystem === 'npm' && e.scope === 'optional') ? false : !!e.isDev,
160
164
  // manifestPath intentionally omitted → manifestPaths/pomPaths = []
161
165
  });
162
166
  // Restore the full multi-version set (makeDepRecord only derives it from the
@@ -185,6 +189,7 @@ function deserializeDeps(descriptor) {
185
189
  externalParents: Array.isArray(mvn.externalParents) ? mvn.externalParents : [],
186
190
  importBoms: Array.isArray(mvn.importBoms) ? mvn.importBoms : [],
187
191
  propertyOverrides: (mvn.propertyOverrides && typeof mvn.propertyOverrides === "object") ? mvn.propertyOverrides : {},
192
+ reactor: mvn.reactor ? require('./maven-airgap').restoreReactorHints(mvn.reactor) : null,
188
193
  applications,
189
194
  };
190
195
  }
package/lib/epss.js CHANGED
@@ -5,7 +5,7 @@
5
5
  * plus a percentile rank against all scored CVEs. FIRST.org recomputes it daily.
6
6
  *
7
7
  * API: https://api.first.org/data/v1/epss?cve=CVE-a,CVE-b,… (batch ≤ ~100)
8
- * Cache: ~/.fad-checker/epss-cache.json, 24h TTL (aligned with the daily refresh).
8
+ * Cache: ~/.fad-checker/epss-cache.json, 4h TTL (aligned with the daily refresh).
9
9
  *
10
10
  * @author: N.BRAUN
11
11
  * @email: pp9ping@gmail.com
@@ -16,19 +16,18 @@ 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, "epss-cache.json");
19
- const CACHE_TTL_MS = 24 * 3600 * 1000;
19
+ const CACHE_TTL_MS = 4 * 3600 * 1000;
20
20
  const EPSS_BASE = "https://api.first.org/data/v1/epss";
21
21
  const BATCH = 100;
22
22
 
23
23
  function loadCache() {
24
- try { return JSON.parse(fs.readFileSync(CACHE_PATH, "utf8")); }
24
+ try { return require('./cache-repository').createCacheRepository(CACHE_DIR).get('catalogue','epss')?.value || { meta: { fetchedAt: 0 }, entries: {} }; }
25
25
  catch { return { meta: { fetchedAt: 0 }, entries: {} }; }
26
26
  }
27
27
 
28
28
  function saveCache(data) {
29
29
  try {
30
- fs.mkdirSync(CACHE_DIR, { recursive: true });
31
- fs.writeFileSync(CACHE_PATH, JSON.stringify(data));
30
+ require('./cache-repository').createCacheRepository(CACHE_DIR).put('catalogue','epss',data,{fetchedAt:data.meta?.fetchedAt||Date.now()});
32
31
  } catch { /* ignore */ }
33
32
  }
34
33
 
@@ -65,7 +64,8 @@ async function enrichEpss(matches, opts = {}) {
65
64
 
66
65
  const cache = loadCache();
67
66
  const strictHosted = !offline && require("./providers").hasHostedProxy();
68
- const fresh = !strictHosted && cache.meta?.fetchedAt && (Date.now() - cache.meta.fetchedAt) < CACHE_TTL_MS;
67
+ const fresh = !strictHosted && cache.meta?.fetchedAt && require('./cache-policy').fresh(cache.meta.fetchedAt, CACHE_TTL_MS);
68
+ const previous = !fresh && !offline ? {entries:cache.entries, fetchedAt:cache.meta?.fetchedAt} : null;
69
69
  if (!fresh && !offline) cache.entries = {};
70
70
 
71
71
  const byId = new Map();
@@ -77,6 +77,7 @@ async function enrichEpss(matches, opts = {}) {
77
77
  }
78
78
 
79
79
  let done = 0;
80
+ let oldestFetchedAt = Date.now();
80
81
  const total = liveIds.length;
81
82
  const report = () => { if (onProgress) onProgress(done, total); };
82
83
  for (const group of chunk(liveIds, BATCH)) {
@@ -85,6 +86,7 @@ async function enrichEpss(matches, opts = {}) {
85
86
  const r = await require("./providers").getResource("epss", "scores", { ids: group },
86
87
  { fetcher, headers: { "User-Agent": "vigievuln-epss" } });
87
88
  if (r.ok) {
89
+ oldestFetchedAt = Math.min(oldestFetchedAt,require('./providers/common').responseFetchedAt(r));
88
90
  const parsed = parseEpssResponse(await r.json());
89
91
  for (const id of group) {
90
92
  // Not every CVE has an EPSS score; cache the null so we don't refetch.
@@ -105,8 +107,11 @@ async function enrichEpss(matches, opts = {}) {
105
107
  report();
106
108
  }
107
109
 
108
- cache.meta = { fetchedAt: fresh ? cache.meta.fetchedAt : Date.now() };
109
- if (!offline && !strictHosted) saveCache(cache);
110
+ cache.meta = { fetchedAt: fresh ? cache.meta.fetchedAt : oldestFetchedAt };
111
+ // Hosted responses must still be persisted for an air-gapped scan. The
112
+ // strict hosted path above revalidates online and never trusts this cache
113
+ // as a substitute for contacting the selected proxy.
114
+ if (!offline) { require('./cache-policy').preserveEntries(cache, previous); saveCache(cache); }
110
115
 
111
116
  for (const m of matches || []) {
112
117
  const v = byId.get(m.cve?.id);
package/lib/euvd.js CHANGED
@@ -13,7 +13,7 @@
13
13
  * priority band or the `--fail-on kev` gate: those stay on CISA KEV, whose semantics
14
14
  * users already script against.
15
15
  *
16
- * Cache: ~/.fad-checker/euvd-cache.json, 24h TTL. A failed refresh keeps serving the
16
+ * Cache: ~/.fad-checker/euvd-cache.json, 4h TTL. A failed refresh keeps serving the
17
17
  * stale snapshot; offline serves it whatever its age.
18
18
  *
19
19
  * @author: N.BRAUN
@@ -25,20 +25,19 @@ const os = require("os");
25
25
 
26
26
  const DEFAULT_CACHE_DIR = path.join(require("./cache-directory").getCacheDir());
27
27
  const CACHE_FILE = "euvd-cache.json";
28
- const CACHE_TTL_MS = 24 * 3600 * 1000;
28
+ const CACHE_TTL_MS = 4 * 3600 * 1000;
29
29
  const MAX_PAGES = 200;
30
30
  const MONTHS = { Jan: 1, Feb: 2, Mar: 3, Apr: 4, May: 5, Jun: 6, Jul: 7, Aug: 8, Sep: 9, Oct: 10, Nov: 11, Dec: 12 };
31
31
 
32
32
  const cachePath = dir => path.join(dir || DEFAULT_CACHE_DIR, CACHE_FILE);
33
33
 
34
34
  function readCache(dir) {
35
- try { return JSON.parse(fs.readFileSync(cachePath(dir), "utf8")); } catch { return null; }
35
+ try { return require('./cache-repository').createCacheRepository(dir || DEFAULT_CACHE_DIR).get('catalogue','euvd')?.value || null; } catch { return null; }
36
36
  }
37
37
 
38
38
  function writeCache(dir, body) {
39
39
  try {
40
- fs.mkdirSync(dir || DEFAULT_CACHE_DIR, { recursive: true });
41
- fs.writeFileSync(cachePath(dir), JSON.stringify({ _fetchedAt: Date.now(), body }));
40
+ require('./cache-repository').createCacheRepository(dir || DEFAULT_CACHE_DIR).put('catalogue','euvd',{ _fetchedAt: Date.now(), body });
42
41
  } catch { /* a cache is an optimisation */ }
43
42
  }
44
43
 
@@ -97,8 +96,10 @@ async function fetchSnapshot({ fetcher, verbose }) {
97
96
  * opts: { offline, verbose, fetcher, cacheDir }
98
97
  */
99
98
  async function enrichEuvd(matches, opts = {}) {
100
- const { offline, verbose, fetcher = globalThis.fetch, cacheDir, hostedProxy } = opts;
99
+ const { offline, verbose, fetcher = globalThis.fetch, cacheDir, hostedProxy, onStale } = opts;
101
100
  if (!(matches || []).some(m => m.cve?.id?.startsWith("CVE-"))) return matches;
101
+ const repository = require('./cache-repository').createCacheRepository(cacheDir || DEFAULT_CACHE_DIR);
102
+ const targeted = repository.get('catalogue','euvd-targeted')?.value || { entries: {} };
102
103
  if (hostedProxy && !offline) {
103
104
  const ids = [...new Set(matches.map(m => m.cve?.id).filter(id => /^CVE-\d{4}-\d{4,7}$/.test(id || "")))];
104
105
  const byId = new Map();
@@ -107,8 +108,18 @@ async function enrichEuvd(matches, opts = {}) {
107
108
  if (!res.ok) throw new Error(`hosted EUVD unavailable (HTTP ${res.status})`);
108
109
  const data = await res.json();
109
110
  if (!Array.isArray(data.items)) throw new Error("invalid hosted EUVD response");
110
- for (const item of data.items) byId.set(item.cve, item);
111
+ const requested=ids.slice(i,i+100), requestedSet=new Set(requested);
112
+ const received=new Map();
113
+ for (const item of data.items) {
114
+ if (!item || !requestedSet.has(item.cve) || received.has(item.cve)) throw new Error('invalid hosted EUVD record');
115
+ received.set(item.cve,item);byId.set(item.cve,item);
116
+ }
117
+ const rawDate=res.headers?.get?.('x-fad-proxy-fetched-at'),parsed=Date.parse(rawDate||'');
118
+ const fetchedAt=Number.isFinite(parsed)&&parsed>0&&parsed<=Date.now()+300000 ? parsed : null;
119
+ const stale=res.headers?.get?.('x-fad-proxy')==='stale' || fetchedAt===null;
120
+ for (const id of requested) targeted.entries[id]={item:received.get(id)||null,fetchedAt,stale};
111
121
  }
122
+ repository.put('catalogue','euvd-targeted',targeted);
112
123
  for (const m of matches) {
113
124
  const item = byId.get(m.cve?.id);
114
125
  if (item && (item.id || item.exploitedSince != null)) m.cve.euvd = { id: item.id || null, exploitedSince: item.exploitedSince ?? null };
@@ -117,9 +128,21 @@ async function enrichEuvd(matches, opts = {}) {
117
128
  }
118
129
 
119
130
 
131
+ const savedIds=new Set();
132
+ if (offline) {
133
+ let oldest=null,stale=false;
134
+ for (const m of matches) {
135
+ const entry=targeted.entries[m.cve?.id];if(!entry)continue;
136
+ savedIds.add(m.cve.id);
137
+ if(entry.stale || !entry.fetchedAt || Date.now()-entry.fetchedAt>=CACHE_TTL_MS){stale=true;if(entry.fetchedAt && (!oldest || entry.fetchedAt<oldest))oldest=entry.fetchedAt;}
138
+ const item=entry.item;
139
+ if(item && (item.id || item.exploitedSince != null))m.cve.euvd={id:item.id||null,exploitedSince:item.exploitedSince??null};
140
+ }
141
+ if(stale)onStale?.(oldest ? new Date(oldest).toISOString() : null);
142
+ }
120
143
  const cached = readCache(cacheDir);
121
144
  let body = cached?.body || null;
122
- const fresh = cached && Date.now() - cached._fetchedAt < CACHE_TTL_MS;
145
+ const fresh = cached && require('./cache-policy').fresh(cached._fetchedAt, CACHE_TTL_MS);
123
146
  if (!fresh && !offline) {
124
147
  try {
125
148
  body = await fetchSnapshot({ fetcher, verbose });
@@ -132,6 +155,7 @@ async function enrichEuvd(matches, opts = {}) {
132
155
 
133
156
  for (const m of matches || []) {
134
157
  const id = m.cve?.id;
158
+ if (savedIds.has(id)) continue;
135
159
  const euvd = id && body.byCve[id];
136
160
  const exploited = id && Object.prototype.hasOwnProperty.call(body.exploited || {}, id) ? body.exploited[id] : null;
137
161
  if (!euvd && exploited == null) continue;
@@ -0,0 +1,103 @@
1
+ 'use strict';
2
+ // Signed GCVE directory + bounded, explicit GNA origin allowlist. A verified
3
+ // directory establishes entry provenance, not trust in each GNA's assertions.
4
+ const crypto = require('node:crypto');
5
+ const { buildGcveIndex, readGcveIndex, writeGcveIndex } = require('./gcve-index');
6
+ const DIRECTORY = 'https://gcve.eu/dist/gcve.json';
7
+ const SIGNATURE = 'https://gcve.eu/dist/gcve.json.sigsha512';
8
+ const TRUSTED_KEY = `-----BEGIN PUBLIC KEY-----
9
+ MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAuZrjI/aiXgAd4rnrWfnR
10
+ FLeUzLZNfu6G+ytNQfRSI6NdAD2mBatwEbGtdDxO27DycgRiOmv6ILxpbMjCvtaD
11
+ TQwUuTKbPK/c3E827p0Ohe0zKUz2IE5WHNg6JGAvFiCkdTo3ALlsw+thB0IfkBEV
12
+ DYJ0OpQ1J7qXL2FJWcfC0PmYDasIfv/17t4UTe2T+TcpyYfL/B/wg3gzbCys9wk6
13
+ H0jbJI/PQTzVusb4rWTOLYafTtuQ7ihXhXoJT1bFYzn+Vi5hnV/zhJyvh6CIRutR
14
+ KWYHw6Ok+FzzJWESsG+SUd+ZprwDPpGhSLLM1vnNh6EZi8g9Ji1jXZnINCWd/iKd
15
+ /gnK0gvplHGh6m0FWb3/KNLnbmoQNjiisuq/rqsZLUt+Vg193i0xSjJBFT9hEYr8
16
+ D36OOmJyToyi9DVk2T5BbP8miNCdHJUdp78a4gez8k2Vxq4eOmmc0RHH7KZZg3vu
17
+ OX/Le9FU5h6BkZSeH4r5pDF06dd9hyH2q0zaOZ6gH5/vsl0rIzIzj/auhJoaxtWz
18
+ Qux/wIPbm1M7cQdeDyXATtKzaTDWCZdmkbCxW9qXpAsyEPo4FPUobiAYPdX7CzYE
19
+ SG5WO4MKf+BKqwi7y/EdIrMK0x+jB41/MulDrXdtnRNfgAwQVpqP4rqBAPeALNGW
20
+ xOT6PS8T0M9j11ZSP9ShiX0CAwEAAQ==
21
+ -----END PUBLIC KEY-----`;
22
+ const DEFAULT_ORIGINS = Object.freeze(['https://vulnerability.circl.lu']);
23
+ const MAX_DIRECTORY = 2 * 1024 * 1024, MAX_DUMP = 128 * 1024 * 1024, MAX_RECORD = 16 * 1024 * 1024;
24
+
25
+ async function readBounded(url, max, fetcher) {
26
+ const response = await fetcher(url, {redirect:'error', signal:AbortSignal.timeout(120000), headers:{'user-agent':'vigievuln-gcve/1'}});
27
+ if (!response.ok || !response.body) throw Error(`GCVE source returned HTTP ${response.status}`);
28
+ const length = Number(response.headers.get('content-length'));
29
+ if (Number.isFinite(length) && length > max) { await response.body.cancel(); throw Error('GCVE response exceeds size limit'); }
30
+ let size=0; const chunks=[];
31
+ for await (const chunk of response.body) { size+=chunk.length; if(size>max) throw Error('GCVE response exceeds size limit'); chunks.push(Buffer.from(chunk)); }
32
+ return Buffer.concat(chunks);
33
+ }
34
+ function verifyDirectory(data, signature, key = TRUSTED_KEY) {
35
+ const text = Buffer.from(signature).toString('ascii').replace(/[\r\n \t]/g,'');
36
+ if (!/^[A-Za-z0-9+/]+={0,2}$/.test(text) || !crypto.verify('RSA-SHA512', data, key, Buffer.from(text,'base64'))) throw Error('GCVE directory signature invalid');
37
+ const parsed = JSON.parse(new TextDecoder('utf-8',{fatal:true}).decode(data));
38
+ if (!Array.isArray(parsed) || parsed.some(x => !x || !Number.isSafeInteger(x.id) || x.id < 0)) throw Error('invalid GCVE directory');
39
+ const ids = new Set();
40
+ for (const x of parsed) { if (ids.has(x.id)) throw Error('duplicate GCVE GNA identifier'); ids.add(x.id); }
41
+ return parsed;
42
+ }
43
+ function dumpUrl(entry, allowedOrigins) {
44
+ if (!entry?.gcve_pull_api) return null;
45
+ let base; try { base = new URL(entry.gcve_pull_api); } catch { return null; }
46
+ if (base.protocol !== 'https:' || base.username || base.password || base.search || base.hash || !allowedOrigins.includes(base.origin)) return null;
47
+ // Do not allow an entry's path to select an unrelated handler.
48
+ if (base.pathname !== '/') return null;
49
+ return new URL(`/dumps/gna-${entry.id}.ndjson`,base).href;
50
+ }
51
+ function parseDump(bytes) {
52
+ const text = new TextDecoder('utf-8',{fatal:true}).decode(bytes), lines = text.split('\n');
53
+ const records = [];
54
+ for (let i=0;i<lines.length;i++) {
55
+ const line=lines[i].trim(); if (!line) continue;
56
+ if (Buffer.byteLength(line)>MAX_RECORD) throw Error('GCVE record exceeds size limit');
57
+ try { records.push(JSON.parse(line)); } catch { throw Error(`invalid GCVE NDJSON at line ${i+1}`); }
58
+ }
59
+ return records;
60
+ }
61
+ async function collectGcveIndex({fetcher=globalThis.fetch, allowedOrigins=DEFAULT_ORIGINS, trustedKey=TRUSTED_KEY} = {}) {
62
+ const [data,sig] = await Promise.all([readBounded(DIRECTORY,MAX_DIRECTORY,fetcher),readBounded(SIGNATURE,65536,fetcher)]);
63
+ const directory = verifyDirectory(data,sig,trustedKey), sources=[], diagnostics=[];
64
+ for (const gna of directory) {
65
+ if (!gna.gcve_pull_api || gna.id === 0) continue;
66
+ const url=dumpUrl(gna,allowedOrigins);
67
+ if (!url) { diagnostics.push({gna:gna.id,code:'not_collected',reason:'GNA origin not explicitly trusted or unsupported'}); continue; }
68
+ const bytes=await readBounded(url,MAX_DUMP,fetcher);
69
+ const records=parseDump(bytes);
70
+ sources.push({gna:gna.id,sourceUrl:url,collectedAt:new Date().toISOString(),complete:true,records});
71
+ }
72
+ if (!sources.length) throw Error('no configured GCVE GNA feed could be collected');
73
+ const index=buildGcveIndex(sources);
74
+ index.directory = { url:DIRECTORY, sha256:crypto.createHash('sha256').update(data).digest('hex'),
75
+ verified:true, eligible:directory.filter(x=>x.id!==0 && x.gcve_pull_api).length, notCollected:diagnostics.length, diagnostics };
76
+ return {index,diagnostics};
77
+ }
78
+ function proxyGcveFetcher(url,{signal}={}){
79
+ const {getResource}=require('./providers');
80
+ let type,params={};
81
+ if(url===DIRECTORY)type='directory';
82
+ else if(url===SIGNATURE)type='signature';
83
+ else {
84
+ const match=/^https:\/\/vulnerability\.circl\.lu\/dumps\/gna-([1-9][0-9]*)\.ndjson$/.exec(url);
85
+ if(!match)throw Error('GCVE proxy source URL is not allowed');
86
+ type='gna-dump';params={gna:Number(match[1])};
87
+ }
88
+ return getResource('gcve',type,params,{signal,streaming:true,requestTimeoutMs:120000});
89
+ }
90
+ /** Refresh atomically; failure preserves the old index. Offline never calls fetch. */
91
+ async function updateGcveIndex({cacheFile, offline=false, fetcher=globalThis.fetch, allowedOrigins=DEFAULT_ORIGINS, trustedKey=TRUSTED_KEY} = {}) {
92
+ if (!cacheFile) throw Error('GCVE cache file is required');
93
+ if (offline) return {index:readGcveIndex(cacheFile), diagnostics:[], offline:true};
94
+ const {index,diagnostics} = await collectGcveIndex({fetcher,allowedOrigins,trustedKey});
95
+ const path = require('node:path');
96
+ const parent = path.dirname(cacheFile);
97
+ const store = require('./advisory-store').openAdvisoryStore({cacheDir:path.basename(parent) === 'gcve-data' ? path.dirname(parent) : parent});
98
+ try { await require('./native-advisories').importGcveIndex(store,index); }
99
+ finally { store.close(); }
100
+ writeGcveIndex(cacheFile,index);
101
+ return {index,diagnostics,offline:false};
102
+ }
103
+ module.exports = { DIRECTORY, SIGNATURE, TRUSTED_KEY, DEFAULT_ORIGINS, readBounded, verifyDirectory, dumpUrl, parseDump, collectGcveIndex, proxyGcveFetcher, updateGcveIndex };
@@ -0,0 +1,181 @@
1
+ 'use strict';
2
+ // Conservative local GCVE matching. This module never performs network I/O.
3
+ // Records and typed relationships are retained; only explicit package coordinates
4
+ // are indexed. Unrecognised formats/versions remain unknown, never "not affected".
5
+ const path = require('node:path');
6
+ const { compareMavenVersions } = require('./maven-version');
7
+ const { osvEcosystemFor, osvPkgName } = require('./osv');
8
+ const FORMAT = 'vigievuln-gcve-index/1';
9
+ const MAX_RECORD = 16 * 1024 * 1024;
10
+ const validId = id => typeof id === 'string' && id.length <= 255 && /^GCVE-[0-9]+-[\x22-\x7e]+$/i.test(id);
11
+ const gcveKey = id => String(id || '').replace(/^gcve-/i, 'GCVE-');
12
+
13
+ function extensions(record) {
14
+ const blocks = [record?.x_gcve, record?.containers?.cna?.x_gcve];
15
+ for (const x of (record?.containers?.adp || [])) blocks.push(x?.x_gcve);
16
+ return blocks.flatMap(x => Array.isArray(x) ? x : x && typeof x === 'object' ? [x] : []);
17
+ }
18
+ function identity(record, gna) {
19
+ const extensionsFound = extensions(record).filter(x => validId(x?.vulnId));
20
+ const rawId = record?.cveMetadata?.vulnId || extensionsFound[0]?.vulnId;
21
+ if (!validId(rawId)) throw Error('GCVE record is missing a valid identifier');
22
+ const id = gcveKey(rawId), m = /^GCVE-([0-9]+)-/i.exec(id);
23
+ if (gna != null && String(Number(m[1])) !== String(Number(gna))) throw Error('GCVE record namespace does not match GNA');
24
+ if (extensionsFound.some(x => gcveKey(x.vulnId).toLowerCase() !== id.toLowerCase())) throw Error('ambiguous GCVE record identifiers');
25
+ const recordTypes = [...new Set(extensionsFound.map(x => String(x.recordType || 'advisory').toLowerCase()))];
26
+ const recordType = recordTypes.length ? (recordTypes.length === 1 ? recordTypes[0] : 'unknown') : 'advisory';
27
+ const relationships = extensionsFound.flatMap(x => Array.isArray(x.relationships) ? x.relationships : []);
28
+ // Only an explicit equal relationship or CVE ID carried by the very same CVE
29
+ // record is an alias. Opposes/subset/superset/related must not be merged.
30
+ const aliases = new Set();
31
+ const cve = record?.cveMetadata?.cveId;
32
+ if (typeof cve === 'string' && /^CVE-\d{4}-\d{4,}$/i.test(cve) && !relationships.some(r =>
33
+ String(r?.destId || '').toLowerCase() === cve.toLowerCase() && String(r?.type || '').toLowerCase() !== 'equal')) aliases.add(cve.toUpperCase());
34
+ for (const r of relationships) if (String(r?.type || '').toLowerCase() === 'equal' &&
35
+ (!r.srcId || String(r.srcId).toLowerCase() === id.toLowerCase()) &&
36
+ typeof r.destId === 'string' && (/^CVE-\d{4}-\d{4,}$/i.test(r.destId) || validId(r.destId)))
37
+ aliases.add(/^CVE-/i.test(r.destId) ? r.destId.toUpperCase() : gcveKey(r.destId));
38
+ return { id, gna: Number(m[1]), recordType, aliases:[...aliases], relationships };
39
+ }
40
+
41
+ function explicitPackage(a) {
42
+ // A purl unambiguously declares its ecosystem; never infer from a product name.
43
+ const purl = typeof a?.packageURL === 'string' ? a.packageURL : typeof a?.purl === 'string' ? a.purl : null;
44
+ if (purl) {
45
+ const m = /^pkg:([a-z]+)\/([^?#@]+)$/i.exec(purl);
46
+ if (!m) return null;
47
+ let value; try { value = decodeURIComponent(m[2]); } catch { return null; }
48
+ const eco = {maven:'Maven',npm:'npm',pypi:'PyPI',composer:'Packagist',nuget:'NuGet',golang:'Go',gem:'RubyGems'}[m[1].toLowerCase()];
49
+ if (!eco) return null;
50
+ if (eco === 'Maven') { const n=value.lastIndexOf('/'); if(n<1 || n===value.length-1) return null; value=value.slice(0,n)+':'+value.slice(n+1); }
51
+ return { ecosystem:eco, name:value };
52
+ }
53
+ // CVE Records sometimes carry a Maven g:a and a declared Maven collection.
54
+ if (typeof a?.packageName === 'string' && /^[A-Za-z0-9_.-]+:[A-Za-z0-9_.-]+$/.test(a.packageName) &&
55
+ typeof a.collectionURL === 'string' && /^https:\/\/(?:repo\.maven\.apache\.org|repo1\.maven\.org)\/maven2\/?$/i.test(a.collectionURL))
56
+ return { ecosystem:'Maven', name:a.packageName };
57
+ return null;
58
+ }
59
+ const keyOf = (eco, name) => `${eco}:${['npm','NuGet'].includes(eco) ? name.toLowerCase() : eco === 'PyPI' ? name.toLowerCase().replace(/[-_.]+/g, '-') : name}`;
60
+
61
+ function buildGcveIndex(sources) {
62
+ const byPackage = Object.create(null), records = [], coverage = [];
63
+ for (const source of sources || []) {
64
+ if (!source || !Number.isSafeInteger(source.gna) || source.gna < 0 || !Array.isArray(source.records)) throw Error('invalid GCVE source snapshot');
65
+ let matched = 0, unindexed = 0;
66
+ for (const raw of source.records) {
67
+ if (Buffer.byteLength(JSON.stringify(raw)) > MAX_RECORD) throw Error('GCVE record exceeds size limit');
68
+ const ident = identity(raw, source.gna);
69
+ const stored = { ...ident, sourceUrl:source.sourceUrl || null, collectedAt:source.collectedAt || null, raw };
70
+ records.push(stored);
71
+ if (ident.recordType !== 'advisory' || raw?.cveMetadata?.state !== 'PUBLISHED') { unindexed++; continue; }
72
+ let found = false;
73
+ for (const a of (raw?.containers?.cna?.affected || [])) {
74
+ const p = explicitPackage(a);
75
+ if (!p) continue;
76
+ const k = keyOf(p.ecosystem, p.name);
77
+ (byPackage[k] ||= []).push({ record:stored, affected:a }); found = true;
78
+ }
79
+ if (found) matched++; else unindexed++;
80
+ }
81
+ coverage.push({ gna:source.gna, sourceUrl:source.sourceUrl || null, collectedAt:source.collectedAt || null,
82
+ complete:source.complete === true, records:source.records.length, indexed:matched, unindexed });
83
+ }
84
+ const times = coverage.map(c => Date.parse(c.collectedAt)).filter(Number.isFinite);
85
+ return {format:FORMAT, builtAt:new Date().toISOString(), ...(times.length === coverage.length && times.length ? {_fadSnapshot:{collectedAt:new Date(Math.min(...times)).toISOString()}} : {}), coverage, byPackage, records};
86
+ }
87
+
88
+ function bound(v) { return typeof v === 'string' && v.length <= 256 && /^[0-9][A-Za-z0-9._+-]*$/.test(v) && !/\d{16}/.test(v); }
89
+ // true/false/null = affected/unaffected/undecidable for ONE affected entry.
90
+ function affectedVersion(version, a, ecosystem) {
91
+ if (typeof version !== 'string' || !version || !a || !Array.isArray(a.versions)) return null;
92
+ let unknown = false; const statuses = [];
93
+ for (const v of a.versions) {
94
+ if (!v || !['affected','unaffected','unknown'].includes(v.status) || typeof v.version !== 'string') { unknown=true; continue; }
95
+ const ranged = v.lessThan != null || v.lessThanOrEqual != null;
96
+ if (v.lessThan != null && v.lessThanOrEqual != null) { unknown=true; continue; }
97
+ if (!ranged) {
98
+ if (version === v.version) statuses.push(v.status);
99
+ else if (ecosystem === 'Maven' && String(v.versionType || '').toLowerCase() === 'maven' && bound(version) && bound(v.version)) {
100
+ if (compareMavenVersions(version,v.version) === 0) statuses.push(v.status);
101
+ } else unknown=true;
102
+ continue;
103
+ }
104
+ if (ecosystem !== 'Maven' || !bound(version) || String(v.versionType || '').toLowerCase() !== 'maven' ||
105
+ !(v.version === '0' || bound(v.version)) || !(v.lessThan === '*' || bound(v.lessThan ?? v.lessThanOrEqual))) { unknown=true; continue; }
106
+ const lower = v.version === '0' || compareMavenVersions(version, v.version) >= 0;
107
+ const upper = v.lessThan === '*' || (v.lessThan != null ? compareMavenVersions(version, v.lessThan) < 0 : compareMavenVersions(version, v.lessThanOrEqual) <= 0);
108
+ if (!lower || !upper) continue;
109
+ let state = v.status;
110
+ if (v.changes != null) {
111
+ if (!Array.isArray(v.changes) || v.changes.some(c => !bound(c?.at) || !['affected','unaffected','unknown'].includes(c.status))) { unknown=true; continue; }
112
+ const changes = [...v.changes].sort((a,b)=>compareMavenVersions(a.at,b.at));
113
+ for (const change of changes) if (compareMavenVersions(version,change.at) >= 0) state=change.status;
114
+ }
115
+ statuses.push(state);
116
+ }
117
+ if (statuses.includes('unknown') || (statuses.includes('affected') && statuses.includes('unaffected'))) return null;
118
+ if (unknown) return null;
119
+ if (statuses.includes('affected')) return true;
120
+ if (statuses.includes('unaffected')) return false;
121
+ if (a.defaultStatus === 'affected') return true;
122
+ if (a.defaultStatus === 'unaffected') return false;
123
+ return null;
124
+ }
125
+
126
+ function gcveMetrics(cna) {
127
+ for (const key of ['cvssV4_0', 'cvssV3_1', 'cvssV3_0', 'cvssV2_0']) {
128
+ for (const metric of Array.isArray(cna.metrics) ? cna.metrics : []) {
129
+ const cvss = metric?.[key], score = cvss?.baseScore;
130
+ if (typeof score !== 'number' || !Number.isFinite(score) || score < 0 || score > 10) continue;
131
+ const severity = key === 'cvssV2_0'
132
+ ? (score < 4 ? 'LOW' : score < 7 ? 'MEDIUM' : 'HIGH')
133
+ : (score === 0 ? 'NONE' : score < 4 ? 'LOW' : score < 7 ? 'MEDIUM' : score < 9 ? 'HIGH' : 'CRITICAL');
134
+ return { severity, score, cvssVector: typeof cvss.vectorString === 'string' ? cvss.vectorString : null };
135
+ }
136
+ }
137
+ return { severity:'UNKNOWN', score:null };
138
+ }
139
+
140
+ function matchGcveDeps(deps, index) {
141
+ if (!index || index.format !== FORMAT || !index.byPackage || !Array.isArray(index.coverage)) throw Error('invalid GCVE index');
142
+ const matches = [], unknown = [], seen = new Set();
143
+ for (const dep of deps.values()) {
144
+ if (dep.provenance === 'binary' || !['maven','npm','yarn','nuget','composer','pypi','go','ruby'].includes(dep.ecosystem)) continue;
145
+ const ecosystem = osvEcosystemFor(dep), name = osvPkgName(dep);
146
+ if (!ecosystem || !name) continue;
147
+ for (const ver of ((dep.versions?.length ? dep.versions : [dep.version]) || [])) {
148
+ if (!ver || /\$\{/.test(String(ver))) continue;
149
+ for (const item of index.byPackage[keyOf(ecosystem,name)] || []) {
150
+ const itemKey = `${dep.coordKey || name}|${ver}|${item.record.id}`;
151
+ if (seen.has(itemKey)) continue;
152
+ const result = affectedVersion(String(ver),item.affected,ecosystem);
153
+ if (result === null) { unknown.push({ id:item.record.id, package:name, version:ver }); continue; }
154
+ if (!result) continue;
155
+ seen.add(itemKey);
156
+ const meta = item.record, raw = meta.raw, cna = raw?.containers?.cna || {};
157
+ const description = (cna.descriptions || []).find(x => String(x.lang || '').startsWith('en'))?.value || (cna.descriptions || [])[0]?.value || '';
158
+ const realCve = meta.aliases.find(x=>/^CVE-\d{4}-\d{4,}$/i.test(x));
159
+ matches.push({ dep:ver === dep.version ? dep : {...dep,version:ver}, source:`GCVE:GNA-${meta.gna}`, confidence:'exact',
160
+ cve:{id:realCve || meta.id, gcve:meta.id, aliases:meta.aliases.filter(x=>x!==realCve).concat(realCve ? [meta.id] : []),
161
+ ...gcveMetrics(cna), description:String(description), published:raw?.cveMetadata?.datePublished || null,
162
+ modified:raw?.cveMetadata?.dateUpdated || null, fixVersion:null, fixEvaluation:'unknown', gcveSource:meta.sourceUrl, gcveRecordType:meta.recordType, gcveRelationships:meta.relationships} });
163
+ }
164
+ }
165
+ }
166
+ return {matches,unknown,coverage:index.coverage};
167
+ }
168
+
169
+ function readGcveIndex(file) {
170
+ const parent=path.dirname(file),cacheDir=path.basename(parent)==='gcve-data'?path.dirname(parent):parent;
171
+ const value=require('./cache-repository').createCacheRepository(cacheDir).get('catalogue','gcve')?.value;
172
+ if (value?.format !== FORMAT || !Array.isArray(value.coverage) || !value.byPackage || typeof value.byPackage !== 'object') throw Error('invalid GCVE index');
173
+ return value;
174
+ }
175
+ function writeGcveIndex(file, index) {
176
+ if (index?.format !== FORMAT) throw Error('invalid GCVE index');
177
+ const parent=path.dirname(file),cacheDir=path.basename(parent)==='gcve-data'?path.dirname(parent):parent;
178
+ require('./cache-repository').createCacheRepository(cacheDir).put('catalogue','gcve',index);
179
+ }
180
+
181
+ module.exports = { FORMAT, validId, identity, explicitPackage, buildGcveIndex, affectedVersion, matchGcveDeps, readGcveIndex, writeGcveIndex };
package/lib/gcve.js CHANGED
@@ -26,7 +26,7 @@ function gcveUrl(id) {
26
26
  function enrichGcve(matches) {
27
27
  for (const m of matches || []) {
28
28
  const id = gcveId(m.cve?.id);
29
- if (id) m.cve.gcve = id;
29
+ if (id && !m.cve.gcve) m.cve.gcve = id;
30
30
  }
31
31
  return matches;
32
32
  }
@@ -0,0 +1,40 @@
1
+ 'use strict';
2
+ // Normalize public repository advisories; never infer a Maven identity from a
3
+ // repository, product name or code path. Ranges are source claims, not fixes.
4
+ const {compareMavenVersions}=require('./maven-version');
5
+ const VERSION='[0-9][0-9A-Za-z._+-]*';
6
+ const validVersion=v=>typeof v==='string'&&new RegExp(`^${VERSION}$`).test(v)&&v.length<=128&&!/\.\.|\+\+|--|__|\d{16}/.test(v);
7
+ const unknown=()=>({type:'UNKNOWN',events:[]});
8
+ function window(lower,upper,inclusive){
9
+ if(!validVersion(lower)||!validVersion(upper))return null;
10
+ const c=compareMavenVersions(lower,upper);if(c>0||(!inclusive&&c===0))return null;
11
+ return {type:'ECOSYSTEM',events:[{introduced:lower},{[inclusive?'last_affected':'fixed']:upper}]};
12
+ }
13
+ function parsePublisherRange(input){
14
+ if(typeof input!=='string'||!input.trim()||input.length>2048)return {ranges:[unknown()],versions:[],unsupported:true};
15
+ const raw=input.trim(),ranges=[],versions=[];
16
+ if(new RegExp(`^${VERSION}$`).test(raw)){if(validVersion(raw))return {ranges,versions:[raw],unsupported:false};return {ranges:[unknown()],versions,unsupported:true};}
17
+ if(raw.startsWith('[')||raw.startsWith('(')){
18
+ // Maven interval union, e.g. [4.0.0,4.5.29],[5.0.0,5.1.4].
19
+ const re=new RegExp(`\\s*([\\[(])\\s*(${VERSION})\\s*,\\s*(${VERSION})\\s*([\\])])\\s*`,'gy');let offset=0;
20
+ while(offset<raw.length){re.lastIndex=offset;const m=re.exec(raw);if(!m||m[1]!=='[')return {ranges:[unknown()],versions:[],unsupported:true};const r=window(m[2],m[3],m[4]===']');if(!r)return {ranges:[unknown()],versions:[],unsupported:true};ranges.push(r);offset=re.lastIndex;if(offset===raw.length)break;if(raw[offset]!==','||offset===raw.length-1)return {ranges:[unknown()],versions:[],unsupported:true};offset++;}
21
+ return {ranges,versions,unsupported:false};
22
+ }
23
+ const part=new RegExp(`^(>=|<=|<|>)\\s*(${VERSION})$`);const pieces=raw.split(',').map(x=>x.trim());if(pieces.length<1||pieces.length>2)return {ranges:[unknown()],versions,unsupported:true};
24
+ const clauses=pieces.map(x=>part.exec(x));if(clauses.some(x=>!x||!validVersion(x[2])))return {ranges:[unknown()],versions,unsupported:true};
25
+ const lows=clauses.filter(x=>x[1]==='>='),highs=clauses.filter(x=>x[1]==='<'||x[1]==='<=');
26
+ if(clauses.some(x=>x[1]==='>')||lows.length>1||highs.length>1||(!lows.length&&!highs.length))return {ranges:[unknown()],versions,unsupported:true};
27
+ if(!highs.length)return {ranges:[{type:'ECOSYSTEM',events:[{introduced:lows[0][2]}]}],versions,unsupported:false};
28
+ const r=window(lows[0]?.[2]||'0',highs[0][2],highs[0][1]==='<=');return r?{ranges:[r],versions,unsupported:false}:{ranges:[unknown()],versions,unsupported:true};
29
+ }
30
+ function normalizePublisherMavenAdvisory(advisory,repository){
31
+ if(!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(repository||'')||!advisory||!/^GHSA-[23456789cfghjmpqrvwx]{4}-[23456789cfghjmpqrvwx]{4}-[23456789cfghjmpqrvwx]{4}$/i.test(advisory.ghsa_id||'')||!['published','withdrawn'].includes(advisory.state))throw Error('invalid publisher advisory');
32
+ let url;try{url=new URL(advisory.html_url)}catch{throw Error('invalid publisher advisory URL')}
33
+ if(url.protocol!=='https:'||url.hostname!=='github.com'||url.username||url.password||url.search||url.hash||url.pathname.toLowerCase()!==`/${repository}/security/advisories/${advisory.ghsa_id}`.toLowerCase())throw Error('publisher advisory URL does not match repository');
34
+ if(!Array.isArray(advisory.vulnerabilities)||advisory.vulnerabilities.length>10000 || (advisory.identifiers!=null&&!Array.isArray(advisory.identifiers)))throw Error('invalid publisher vulnerabilities');
35
+ const groups=new Map();
36
+ for(const item of advisory.vulnerabilities){if(String(item?.package?.ecosystem||'').toLowerCase()!=='maven')continue;const name=item.package.name;if(typeof name!=='string'||name.length>256||!/^[A-Za-z0-9_.-]+:[A-Za-z0-9_.-]+$/.test(name))continue;let group=groups.get(name);if(!group){group={package:{ecosystem:'Maven',name},ranges:[],versions:[]};groups.set(name,group)}const r=parsePublisherRange(item.vulnerable_version_range);group.ranges.push(...r.ranges);group.versions.push(...r.versions);}
37
+ const aliases=[...new Set([advisory.cve_id,...(advisory.identifiers||[]).filter(x=>x?.type==='CVE').map(x=>x.value)].filter(x=>/^CVE-\d{4}-\d{4,}$/i.test(x||'')).map(x=>x.toUpperCase()))];
38
+ return {id:'GHSA-'+advisory.ghsa_id.slice(5).toLowerCase(),aliases,summary:typeof advisory.summary==='string'?advisory.summary:'',modified:advisory.updated_at||null,published:advisory.published_at||null,...(advisory.withdrawn_at?{withdrawn:advisory.withdrawn_at}:{}),affected:[...groups.values()],references:[{type:'ADVISORY',url:url.href}],database_specific:{source:'github-publisher',repository}};
39
+ }
40
+ module.exports={parsePublisherRange,normalizePublisherMavenAdvisory};
package/lib/hash-id.js CHANGED
@@ -5,7 +5,7 @@
5
5
  * 1. deps.dev query-by-hash → exact package coordinate (whole published archive).
6
6
  * 2. CIRCL hashlookup → known OS/distro/CDN/NSRL file + free KnownMalicious flag.
7
7
  *
8
- * Cache-backed (~/.fad-checker/hash-id-cache.json, 24h) and --offline-aware: offline
8
+ * Cache-backed (~/.fad-checker/hash-id-cache.json, 4h) and --offline-aware: offline
9
9
  * reads cache only and never touches the network (project air-gapped principle).
10
10
  *
11
11
  * @author: N.BRAUN
@@ -17,7 +17,7 @@ const os = require("os");
17
17
 
18
18
  const CACHE_DIR = path.join(require("./cache-directory").getCacheDir());
19
19
  const CACHE_PATH = path.join(CACHE_DIR, "hash-id-cache.json");
20
- const CACHE_TTL_MS = 24 * 3600 * 1000;
20
+ const CACHE_TTL_MS = 4 * 3600 * 1000;
21
21
  const DEPSDEV = "https://api.deps.dev/v3/query";
22
22
  const CIRCL = "https://hashlookup.circl.lu/lookup/sha256";
23
23
 
@@ -46,12 +46,12 @@ function parseCircl(body) {
46
46
 
47
47
  function loadCache({ offline = false } = {}) {
48
48
  try {
49
- const d = JSON.parse(fs.readFileSync(CACHE_PATH, "utf8"));
50
- if (offline || Date.now() - (d._fetchedAt || 0) < CACHE_TTL_MS) return d.entries || {};
49
+ const d = require('./json-cache').load(CACHE_DIR,'hash-id',null);
50
+ if (offline || require('./cache-policy').fresh(d._fetchedAt || 0, CACHE_TTL_MS)) return d.entries || {};
51
51
  } catch { /* ignore */ }
52
52
  return {};
53
53
  }
54
- function saveCache(entries) { try { fs.mkdirSync(CACHE_DIR, { recursive: true }); fs.writeFileSync(CACHE_PATH, JSON.stringify({ _fetchedAt: Date.now(), entries })); } catch { /* ignore */ } }
54
+ function saveCache(entries) { require('./json-cache').save(CACHE_DIR,'hash-id',{ _fetchedAt: Date.now(), entries }); }
55
55
 
56
56
  async function lookupHash(hashes, opts = {}) {
57
57
  const { fetcher = globalThis.fetch, offline = false, cache } = opts;
@@ -38,11 +38,16 @@ async function createProxyKey(account) {
38
38
  async function checkHostedProxy(url, token, fetcher = globalThis.fetch) {
39
39
  let response;
40
40
  try {
41
- response = await fetcher(url + "/v1/proxy/status", { headers: { authorization: "Bearer " + token },
41
+ response = await fetcher(url + "/v1/proxy/status", { headers: { authorization: "Bearer " + token, "x-vigievuln-client-version": require('../package.json').version },
42
42
  redirect: "error", signal: AbortSignal.timeout(15000) });
43
43
  } catch { throw new Error("VigieVuln proxy is unreachable; check your connection and proxy endpoint"); }
44
44
  try {
45
45
  if (response.status === 401 || response.status === 403) throw new Error("VigieVuln proxy key is invalid, expired or revoked; create a key from your verified account");
46
+ if (response.status === 426) {
47
+ let data; try { data = await response.json(); } catch { /* keep the generic upgrade message */ }
48
+ const minimum = typeof data?.minimumCliVersion === 'string' && /^\d+\.\d+\.\d+$/.test(data.minimumCliVersion) ? ` ${data.minimumCliVersion} or newer` : '';
49
+ throw new Error(`VigieVuln${minimum} is required by the proxy. Update with npm install -g vigievuln@latest or visit https://github.com/9pings/VigieVuln/releases`);
50
+ }
46
51
  if (!response.ok) throw new Error(`VigieVuln proxy is unavailable (HTTP ${response.status})`);
47
52
  const data = await response.json();
48
53
  if (data.ok !== true || data.service !== "vigievuln-proxy") throw new Error("unexpected VigieVuln proxy response");