vigievuln 1.2.0 → 1.3.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 (121) hide show
  1. package/CHANGELOG.md +23 -2
  2. package/README.md +13 -7
  3. package/lib/advisory-freshness.js +2 -0
  4. package/lib/airgap-project.js +35 -7
  5. package/lib/applicability-evidence.js +12 -0
  6. package/lib/artifacts/applications.js +54 -0
  7. package/lib/artifacts/cve-view.js +108 -0
  8. package/lib/artifacts/enrichment.js +86 -0
  9. package/lib/artifacts/go-main-identity.js +45 -0
  10. package/lib/artifacts/go-publisher-advisories.js +24 -0
  11. package/lib/artifacts/index.js +272 -0
  12. package/lib/artifacts/publisher-advisories.js +12 -0
  13. package/lib/artifacts/remediation-report.js +48 -0
  14. package/lib/artifacts/report-inventory.js +26 -0
  15. package/lib/artifacts/report.js +191 -0
  16. package/lib/artifacts/risk-report.js +120 -0
  17. package/lib/artifacts/sbom.js +68 -0
  18. package/lib/artifacts/scan.js +401 -0
  19. package/lib/cache-archive-sqlite.js +41 -25
  20. package/lib/certs/analyze.js +49 -13
  21. package/lib/charts.js +124 -32
  22. package/lib/cli-command-routing.js +20 -6
  23. package/lib/cli-groups.js +2 -1
  24. package/lib/cli-image.js +206 -0
  25. package/lib/codecs/binary/elf-metadata.js +42 -0
  26. package/lib/codecs/binary/go-buildinfo.js +37 -0
  27. package/lib/codecs/binary/metadata.js +7 -0
  28. package/lib/codecs/binary/pe-metadata.js +27 -1
  29. package/lib/codecs/binary/scan.js +44 -26
  30. package/lib/codecs/binary/sniff.js +16 -15
  31. package/lib/codecs/binary.codec.js +27 -4
  32. package/lib/codecs/go/parse.js +10 -4
  33. package/lib/codecs/go.codec.js +23 -6
  34. package/lib/codecs/gradle/parse.js +63 -2
  35. package/lib/codecs/gradle/versionless.js +175 -0
  36. package/lib/codecs/gradle.codec.js +20 -3
  37. package/lib/codecs/index.js +2 -2
  38. package/lib/codecs/maven.codec.js +9 -4
  39. package/lib/codecs/npm/collect.js +6 -11
  40. package/lib/codecs/nuget/parse.js +16 -5
  41. package/lib/codecs/nuget.codec.js +2 -1
  42. package/lib/codecs/pypi/parse.js +56 -15
  43. package/lib/codecs/pypi.codec.js +2 -0
  44. package/lib/csaf-export.js +46 -11
  45. package/lib/cve-download.js +33 -29
  46. package/lib/cve-match.js +10 -0
  47. package/lib/cve-packages-proxy.js +19 -0
  48. package/lib/cve-report.js +273 -165
  49. package/lib/deps-descriptor.js +25 -3
  50. package/lib/diagnostics.js +12 -0
  51. package/lib/diff.js +0 -0
  52. package/lib/epss.js +6 -6
  53. package/lib/euvd.js +34 -4
  54. package/lib/finding-enrichment.js +165 -0
  55. package/lib/finding-summary.js +4 -3
  56. package/lib/i18n.js +35 -9
  57. package/lib/image-network.js +54 -0
  58. package/lib/image-references.js +203 -0
  59. package/lib/image-registry.js +385 -0
  60. package/lib/image-update.js +39 -0
  61. package/lib/json-export.js +100 -10
  62. package/lib/kev.js +6 -6
  63. package/lib/maven-bom.js +2 -1
  64. package/lib/merge-sources.js +3 -0
  65. package/lib/native-advisories.js +9 -7
  66. package/lib/native-cna-identities.js +12 -0
  67. package/lib/native-package-match.js +159 -0
  68. package/lib/native-source-prepare.js +60 -0
  69. package/lib/nvd.js +34 -23
  70. package/lib/osv.js +33 -14
  71. package/lib/project-descriptor.js +3 -2
  72. package/lib/provenance.js +8 -2
  73. package/lib/providers/alpine.js +8 -0
  74. package/lib/providers/common.js +11 -3
  75. package/lib/providers/debian.js +11 -0
  76. package/lib/providers/euvd.js +2 -1
  77. package/lib/providers/freexian.js +13 -0
  78. package/lib/providers/github.js +1 -0
  79. package/lib/providers/go.js +2 -1
  80. package/lib/providers/index.js +18 -14
  81. package/lib/providers/nginx.js +5 -0
  82. package/lib/providers/nvd.js +1 -1
  83. package/lib/providers/osv.js +1 -1
  84. package/lib/providers/osvdb.js +2 -2
  85. package/lib/proxy-throttle.js +89 -29
  86. package/lib/purl.js +10 -2
  87. package/lib/record-freshness.js +22 -0
  88. package/lib/report-notices.js +47 -0
  89. package/lib/report-time.js +45 -0
  90. package/lib/request-failure.js +22 -0
  91. package/lib/resource-cache/engine.js +130 -26
  92. package/lib/resource-cache/snapshot-projection.js +33 -0
  93. package/lib/resource-cache/validate.js +22 -5
  94. package/lib/risk-evidence.js +18 -0
  95. package/lib/sarif-export.js +17 -9
  96. package/lib/sbom-export.js +38 -12
  97. package/lib/source-health.js +25 -8
  98. package/lib/source-image-scan.js +57 -0
  99. package/lib/source-profile.js +6 -3
  100. package/lib/sqlite-driver.js +15 -1
  101. package/lib/suppress.js +34 -13
  102. package/lib/system-inventory/advisories.js +169 -0
  103. package/lib/system-inventory/alpine-tracker.js +47 -0
  104. package/lib/system-inventory/collect.js +118 -0
  105. package/lib/system-inventory/current-debian.js +99 -0
  106. package/lib/system-inventory/distribution-sources.js +132 -0
  107. package/lib/system-inventory/freexian-ela.js +32 -0
  108. package/lib/system-inventory/freexian-release-evidence.js +35 -0
  109. package/lib/system-inventory/freexian-tracker.js +72 -0
  110. package/lib/system-inventory/historical-debian.js +196 -0
  111. package/lib/system-inventory/index.js +2 -0
  112. package/lib/system-inventory/nginx-advisories.js +39 -0
  113. package/lib/system-inventory/rpm-storage.js +86 -0
  114. package/lib/system-inventory/targeted.js +70 -0
  115. package/lib/system-inventory/versions.js +59 -0
  116. package/lib/transitive.js +11 -2
  117. package/lib/ui.js +8 -5
  118. package/lib/unmanaged.js +1 -1
  119. package/lib/xlsx-export.js +8 -2
  120. package/package.json +12 -3
  121. package/vigievuln.js +279 -127
package/lib/nvd.js CHANGED
@@ -46,9 +46,9 @@ function cachePath(cveId) {
46
46
  return path.join(NVD_CACHE_DIR, `${cveId}.json`);
47
47
  }
48
48
 
49
- function readCache(cveId, offline = false) {
49
+ function readCache(cveId, offline = false, cacheDir = path.dirname(NVD_CACHE_DIR), options = {}) {
50
50
  try {
51
- const db=require('./cache-db').getCacheDb(path.dirname(NVD_CACHE_DIR));
51
+ const db=require('./cache-db').getCacheDb(cacheDir);
52
52
  const row=db.prepare(`SELECT kind,fetched_at,body_deflate,body_bytes,metadata_json FROM nvd_records WHERE cve=?
53
53
  ${offline ? 'ORDER BY fetched_at DESC LIMIT 1' : "AND kind='live' LIMIT 1"}`).get(cveId);
54
54
  if(!row)return null;
@@ -63,26 +63,29 @@ function readCache(cveId, offline = false) {
63
63
  if (offline) return body;
64
64
  // Schema mismatch → force re-fetch so newly-added fields (e.g. cwes) get populated.
65
65
  if ((metadata.schema || 1) < NVD_CACHE_SCHEMA) return null;
66
- if (require('./cache-policy').fresh(row.fetched_at,NVD_CACHE_TTL_MS)) return body;
66
+ const origin=require('./providers').resourceOrigin();
67
+ if (metadata.origin ? metadata.origin !== origin : origin !== 'direct') return null;
68
+ if (!options.forceUpdate && require('./cache-policy').fresh(row.fetched_at,NVD_CACHE_TTL_MS)) return body;
69
+ if (!metadata.stale && row.fetched_at > 0 && row.fetched_at <= Date.now() && require('./record-freshness').stableRecord('nvd',body,options)) return body;
67
70
  } catch { /* ignore */ }
68
71
  return null;
69
72
  }
70
73
 
71
- function writeCache(cveId, body, fetchedAt = Date.now()) {
72
- const db=require('./cache-db').getCacheDb(path.dirname(NVD_CACHE_DIR));
74
+ function writeCache(cveId, body, fetchedAt = Date.now(), cacheDir = path.dirname(NVD_CACHE_DIR), provenance = {}) {
75
+ const db=require('./cache-db').getCacheDb(cacheDir);
73
76
  const bytes=Buffer.from(JSON.stringify(body));
74
77
  db.prepare(`INSERT INTO nvd_records(cve,kind,fetched_at,revision_ms,body_deflate,body_bytes,metadata_json) VALUES (?,?,?,?,?,?,?)
75
78
  ON CONFLICT(cve,kind) DO UPDATE SET fetched_at=excluded.fetched_at,revision_ms=excluded.revision_ms,
76
- body_deflate=excluded.body_deflate,body_bytes=excluded.body_bytes,metadata_json=excluded.metadata_json`).run(cveId,'live',fetchedAt,null,require('./advisory-compression').compress(bytes),bytes.length,JSON.stringify({schema:NVD_CACHE_SCHEMA}));
79
+ body_deflate=excluded.body_deflate,body_bytes=excluded.body_bytes,metadata_json=excluded.metadata_json`).run(cveId,'live',fetchedAt,null,require('./advisory-compression').compress(bytes),bytes.length,JSON.stringify({schema:NVD_CACHE_SCHEMA,origin:require('./providers').resourceOrigin(),stale:provenance.stale === true}));
77
80
  }
78
81
 
79
82
  // A cached JSON null is an answered lookup with no NVD record, not a missing
80
83
  // cache entry. Keep the distinction when reporting offline coverage.
81
- function hasCachedAbsence(cveId) {
84
+ function hasCachedAbsence(cveId, options = {}) {
82
85
  try {
83
- const db=require('./cache-db').getCacheDb(path.dirname(NVD_CACHE_DIR));
86
+ const db=require('./cache-db').getCacheDb(options.cacheDir || path.dirname(NVD_CACHE_DIR));
84
87
  const row=db.prepare('SELECT fetched_at,body_deflate,body_bytes FROM nvd_records WHERE cve=? ORDER BY fetched_at DESC LIMIT 1').get(cveId);
85
- return !!row && row.fetched_at <= Date.now() && Date.now()-row.fetched_at < NVD_CACHE_TTL_MS && JSON.parse(require('./advisory-compression').decompress(row.body_deflate,row.body_bytes).toString('utf8')) === null;
88
+ return !!row && row.fetched_at > 1 && row.fetched_at <= Date.now() && (options.offline || Date.now()-row.fetched_at < NVD_CACHE_TTL_MS) && JSON.parse(require('./advisory-compression').decompress(row.body_deflate,row.body_bytes).toString('utf8')) === null;
86
89
  } catch { return false; }
87
90
  }
88
91
 
@@ -212,10 +215,12 @@ async function fetchFromMirror(cveId, opts = {}) {
212
215
  if (m.status === 404) return { absent: true };
213
216
  if (!m.ok) return { failed: true };
214
217
  const raw = await m.json();
215
- const extracted = extractFromNvdRecord(raw && raw.id ? raw : raw?.vulnerabilities?.[0]?.cve);
218
+ const record=raw && raw.id ? raw : raw?.vulnerabilities?.[0]?.cve;
219
+ if (String(record?.id||'').toUpperCase()!==String(cveId).toUpperCase()) return { failed: true };
220
+ const extracted = extractFromNvdRecord(record);
216
221
  if (!extracted) return { failed: true };
217
222
  extracted.via = MIRROR_NAME;
218
- writeCache(cveId, extracted, require('./providers/common').responseFetchedAt(m));
223
+ writeCache(cveId, extracted, require('./providers/common').responseFetchedAt(m), opts.cacheDir, {stale:m.headers.get('x-fad-proxy') === 'stale'});
219
224
  return { record: extracted };
220
225
  } catch { return { failed: true }; }
221
226
  }
@@ -238,8 +243,9 @@ async function fetchFromMirror(cveId, opts = {}) {
238
243
  */
239
244
  async function fetchOne(cveId, opts = {}) {
240
245
  const { fetcher = globalThis.fetch, verbose, offline, mirror = true } = opts;
241
- const cached = !offline && require("./providers").hasHostedProxy() ? null : readCache(cveId, offline);
246
+ const cached = readCache(cveId, offline, opts.cacheDir, opts);
242
247
  if (cached !== null && cached !== undefined) return cached;
248
+ if (offline && hasCachedAbsence(cveId,{cacheDir:opts.cacheDir,offline:true})) {opts.onAbsent?.(cveId);return null;}
243
249
  if (offline) return null;
244
250
  const headers = { "User-Agent": "vigievuln-nvd-enrich" };
245
251
  const key = getNvdApiKey();
@@ -251,30 +257,34 @@ async function fetchOne(cveId, opts = {}) {
251
257
 
252
258
  let nvdReason;
253
259
  try {
254
- const r = await providers.getResource("nvd", "cve", { id: cveId }, { fetcher, headers, ...deadline(), ...(providers.hasHostedProxy() && mirror ? {retryProxyDenied:false,noSourceRetry:true} : {}) });
255
- if (r.status === 404) { writeCache(cveId, null, require('./providers/common').responseFetchedAt(r)); return null; }
260
+ const r = await providers.getResource("nvd", "cve", { id: cveId }, { fetcher, headers, forceRefresh:opts.forceUpdate || require("./cache-policy").shouldForceUpdate(), ...deadline() });
261
+ if (r.status === 404) { writeCache(cveId, null, require('./providers/common').responseFetchedAt(r), opts.cacheDir, {stale:r.headers.get('x-fad-proxy') === 'stale'}); opts.onAbsent?.(cveId); return null; }
256
262
  if (r.ok) {
257
- const data = await r.json();
258
- const extracted = extractFromNvdRecord(data.vulnerabilities?.[0]?.cve);
259
- writeCache(cveId, extracted, require('./providers/common').responseFetchedAt(r));
263
+ let data;try { data=await r.json(); } catch { throw Object.assign(new Error('malformed NVD response'),{code:'NVD_INVALID_RESPONSE'}); }
264
+ if (Array.isArray(data?.vulnerabilities) && data.vulnerabilities.length===0 && data.totalResults===0) {writeCache(cveId,null,require('./providers/common').responseFetchedAt(r),opts.cacheDir);opts.onAbsent?.(cveId);return null;}
265
+ const record=Array.isArray(data?.vulnerabilities) && data.vulnerabilities.length===1 ? data.vulnerabilities[0]?.cve : null;
266
+ if (!record || String(record.id||'').toUpperCase()!==String(cveId).toUpperCase() || (data.totalResults!==undefined && data.totalResults!==1)) throw Object.assign(new Error('malformed NVD response'),{code:'NVD_INVALID_RESPONSE'});
267
+ let extracted;try { extracted=extractFromNvdRecord(record); } catch { throw Object.assign(new Error('malformed NVD response'),{code:'NVD_INVALID_RESPONSE'}); }
268
+ writeCache(cveId, extracted, require('./providers/common').responseFetchedAt(r), opts.cacheDir, {stale:r.headers.get('x-fad-proxy') === 'stale'});
260
269
  return extracted;
261
270
  }
262
271
  nvdReason = `HTTP ${r.status}`;
263
272
  } catch (err) {
264
- nvdReason = `network: ${err.message}`;
273
+ nvdReason = err.code==='NVD_INVALID_RESPONSE' ? err.message : `network: ${err.message}`;
265
274
  }
266
- if (verbose) console.warn(` NVD ${nvdReason} for ${cveId}`);
275
+ if (verbose) require('./ui').networkNotice(` NVD ${nvdReason} for ${cveId}`);
276
+ opts.onFailure?.(cveId,nvdReason);
267
277
  // A 4xx we caused (bad request…) is an answer, not an outage: nothing to fall back for.
268
278
  if (health.classifyMissReason(nvdReason) === "answered") return null;
269
279
 
270
280
  if (mirror) {
271
- const got = await fetchFromMirror(cveId, { fetcher });
281
+ const got = await fetchFromMirror(cveId, { ...opts, fetcher });
272
282
  if (got.record) {
273
- if (verbose) console.warn(` ${cveId} served by the NVD mirror (${MIRROR_NAME})`);
283
+ if (verbose) require('./ui').networkNotice(` ${cveId} served by the NVD mirror (${MIRROR_NAME})`);
274
284
  return got.record;
275
285
  }
276
286
  }
277
- const stale = require("./providers").hasHostedProxy() ? null : readCache(cveId, true);
287
+ const stale = require("./providers").hasHostedProxy() ? null : readCache(cveId, true, opts.cacheDir);
278
288
  if (stale) return stale;
279
289
  // Neither NVD nor its mirror produced this record: a coverage hole, reported under NVD.
280
290
  health.noteFanoutExhausted(url, [nvdReason]);
@@ -303,11 +313,12 @@ async function enrichMatches(matches, opts = {}) {
303
313
  const byId = new Map();
304
314
  const liveIds = [];
305
315
  for (const cveId of uniqueCves) {
306
- const cached = !offline && require("./providers").hasHostedProxy() ? null : readCache(cveId, offline);
316
+ const cached = readCache(cveId, offline, opts.cacheDir, opts);
307
317
  if (cached !== null && cached !== undefined) {
308
318
  byId.set(cveId, cached);
309
319
  continue;
310
320
  }
321
+ if (offline && hasCachedAbsence(cveId,{cacheDir:opts.cacheDir,offline:true})) {opts.onAbsent?.(cveId);byId.set(cveId,null);continue;}
311
322
  if (offline) { byId.set(cveId, null); continue; }
312
323
  liveIds.push(cveId);
313
324
  }
package/lib/osv.js CHANGED
@@ -282,7 +282,9 @@ function observation(response) {
282
282
  const stamp = Date.parse(headers?.get?.('x-fad-proxy-fetched-at') || '');
283
283
  const isProxy = require('./providers').hasProxyRoute();
284
284
  const valid = Number.isFinite(stamp) && stamp > 0 && stamp <= Date.now() + 300000;
285
- return { fetchedAt: valid ? stamp : isProxy ? 1 : Date.now(), stale: status === 'stale' || (isProxy && (!valid || Date.now()-stamp >= require('./cache-policy').DEFAULT_TTL_MS)) };
285
+ const reason=headers?.get?.('x-fad-proxy-reason'), rawStatus=headers?.get?.('x-fad-proxy-refresh-status'), refreshStatus=/^[45]\d\d$/.test(rawStatus||'') ? Number(rawStatus) : null;
286
+ const refreshFailure=reason==='refresh-failed' || refreshStatus ? {reason:reason==='refresh-failed'?'refresh-failed':'http-error',...(refreshStatus?{status:refreshStatus}:{})} : null;
287
+ return { fetchedAt: valid ? stamp : isProxy ? 1 : Date.now(), stale: status === 'stale' || (isProxy && (!valid || Date.now()-stamp >= require('./cache-policy').DEFAULT_TTL_MS)), ...(refreshFailure?{refreshFailure}:{}) };
286
288
  }
287
289
 
288
290
  // querybatch can paginate EACH query independently. An empty object is a valid
@@ -307,6 +309,7 @@ async function fetchBatchPages(batch, fetcher) {
307
309
  const item = data.results[i], slot = pending[i];
308
310
  results[slot.index].fetchedAt = Math.min(results[slot.index].fetchedAt, observed.fetchedAt);
309
311
  results[slot.index].stale ||= observed.stale;
312
+ if(observed.refreshFailure)results[slot.index].refreshFailure=observed.refreshFailure;
310
313
  if (!item || typeof item !== "object" || Array.isArray(item) || item.error
311
314
  || (item.vulns !== undefined && (!Array.isArray(item.vulns) || !item.vulns.every(v => validVulnId(v?.id)))))
312
315
  throw incompleteOsv("querybatch returned an invalid result");
@@ -324,6 +327,12 @@ async function fetchBatchPages(batch, fetcher) {
324
327
  return results;
325
328
  }
326
329
 
330
+ function staleSeverity(observation, offline, maxAgeMs) {
331
+ const p=observation?.provenance||observation||{};
332
+ const failure=p.refreshFailure || p.refreshError || p.error || Number(p.status)>=400 || p.reason==='refresh-failed';
333
+ const date=Number(observation?.fetchedAt), policyExceeded=Number.isFinite(maxAgeMs) && maxAgeMs>=0 && (!Number.isFinite(date) || date<=1 || date>Date.now() || Date.now()-date>maxAgeMs);
334
+ return !failure && !policyExceeded ? 'info' : undefined;
335
+ }
327
336
  async function queryBatch(deps, opts = {}) {
328
337
  if (!deps.length) return [];
329
338
  const { offline, fetcher = globalThis.fetch, onProgress, onWarning, queryTtlMs = 4 * 3600 * 1000 } = opts;
@@ -332,12 +341,12 @@ async function queryBatch(deps, opts = {}) {
332
341
  try {
333
342
  const tuple = d => ({source:'osv', ecosystem:osvEcosystemFor(d), name:osvPkgName(d), version:String(d.version).trim()});
334
343
  const views = [], pending = [], output = new Array(deps.length), warnings = [], reviewedFreshnessNotices = new Set();
335
- const warn = (type, message) => warnings.push({type,message});
344
+ const warn = (type, message, severity) => warnings.push({type,message,...(severity ? {severity} : {})});
336
345
  for (let i=0; i<deps.length; i++) {
337
346
  const q=tuple(deps[i]);
338
347
  const view=store.getPackageView(q,{ttlMs:queryTtlMs});
339
348
  views[i]=view;
340
- if (!offline && (require('./cache-policy').shouldForceUpdate() || !view.query || !view.query.fresh || view.querySuperseded)) pending.push({index:i, tuple:q});
349
+ if (!offline && (opts.forceUpdate || require('./cache-policy').shouldForceUpdate() || !view.query || !view.query.fresh || view.querySuperseded)) pending.push({index:i, tuple:q});
341
350
  }
342
351
  if (pending.length) {
343
352
  try {
@@ -356,6 +365,8 @@ async function queryBatch(deps, opts = {}) {
356
365
  while(cursor<ids.length) {
357
366
  const id=ids[cursor++];
358
367
  try {
368
+ const existing=store.getRecord('osv',id);
369
+ if (existing?.provenance?.origin === require('./providers').resourceOrigin() && !existing.provenance.stale && !existing.document?.withdrawn && existing.fetchedAt > 0 && existing.fetchedAt <= Date.now() && require('./record-freshness').stableRecord('osv',existing.document,opts)) { details.set(id,{body:existing.document,fetchedAt:existing.fetchedAt,stale:false,reusedStable:true}); if(onProgress)onProgress(++done,ids.length); continue; }
359
370
  const r=await require('./providers').getResource('osv','vuln',{id},{fetcher,forceRefresh:true,headers:{'User-Agent':'vigievuln-osv'}});
360
371
  if (!r.ok) throw Error(`HTTP ${r.status}`);
361
372
  const body=await r.json(); if (body?.id!==id) throw Error('invalid advisory detail');
@@ -366,7 +377,7 @@ async function queryBatch(deps, opts = {}) {
366
377
  }));
367
378
  if(failures.length)throw incompleteOsv(`${failures.length} advisory detail(s) unavailable (${failures[0]})`);
368
379
  const transport=require('./providers').hasProxyRoute()?'proxy':'direct';
369
- const records=[...details.values()].map(d=>({source:'osv',document:d.body,fetchedAt:d.fetchedAt,provenance:{transport,stale:d.stale}}));
380
+ const records=[...details.values()].filter(d=>!d.reusedStable).map(d=>({source:'osv',document:d.body,fetchedAt:d.fetchedAt,provenance:{transport,origin:require('./providers').resourceOrigin(),stale:d.stale,...(d.refreshFailure?{refreshFailure:d.refreshFailure}:{})}}));
370
381
  // Keep revision evidence independently of the write transaction: a full
371
382
  // disk must not allow an older API payload to resurrect a known withdrawal.
372
383
  const existingRecords=new Map(ids.map(id=>[id,store.getRecord('osv',id)]));
@@ -375,10 +386,11 @@ async function queryBatch(deps, opts = {}) {
375
386
  for(let i=0;i<pending.length;i++) {
376
387
  const entry=pending[i], result=fetched[i], ids=[...new Set(result.vulns.map(v=>v.id))];
377
388
  const relevant=ids.map(id=>details.get(id));
378
- const fetchedAt=Math.min(result.fetchedAt,...relevant.map(d=>d.fetchedAt));
389
+ const fetchedAt=Math.min(result.fetchedAt,...relevant.filter(d=>!d.reusedStable).map(d=>d.fetchedAt));
379
390
  const stale=result.stale || relevant.some(d=>d.stale);
391
+ const refreshFailure=result.refreshFailure || relevant.find(d=>d.refreshFailure)?.refreshFailure;
380
392
  const documentHashes=Object.fromEntries(ids.map(id=>[id,require('node:crypto').createHash('sha256').update(JSON.stringify(details.get(id).body)).digest('hex')]));
381
- queries.push({...entry.tuple,ids,fetchedAt,complete:true,provenance:{transport,stale,documentHashes}});
393
+ queries.push({...entry.tuple,ids,fetchedAt,complete:true,provenance:{transport,stale,...(refreshFailure?{refreshFailure}:{}),documentHashes}});
382
394
  }
383
395
  try {
384
396
  // A query is committed only after all its details are durable. Partial
@@ -397,13 +409,13 @@ async function queryBatch(deps, opts = {}) {
397
409
  if (!savedView.query.fresh) warn('source-stale',`OSV: the response for ${entry.tuple.name}@${entry.tuple.version} predates its saved consultation; newer local evidence is used.`);
398
410
  continue;
399
411
  }
400
- if(query.provenance.stale)warn('source-stale',`OSV: the source response was stale or its collection date is unknown for ${entry.tuple.name}@${entry.tuple.version}.`);
412
+ if(query.provenance.stale)warn('source-stale',`OSV: the source response was stale or its collection date is unknown for ${entry.tuple.name}@${entry.tuple.version}.`,staleSeverity(query,offline,opts.maxAdvisoryAgeMs));
401
413
  for(const id of query.ids) {
402
414
  const fetched=details.get(id).body;
403
415
  let existing=existingRecords.get(id);
404
416
  try { existing=store.getRecord('osv',id) || existing; }
405
417
  catch(error) { warn('source-unavailable',`OSV: saved revision of ${id} could not be reread (${error.message}); previously read revision evidence is retained.`); }
406
- const winner=require('./advisory-store').selectAdvisoryRecord(incomingRecords.get(id),existing).document;
418
+ const winner=require('./advisory-store').selectAdvisoryRecord(incomingRecords.get(id) || existing,existing).document;
407
419
  if(winner.withdrawn)continue;
408
420
  if(JSON.stringify(winner)!==JSON.stringify(fetched)) {
409
421
  const relevant=(winner.affected || []).filter(a=>a?.package?.ecosystem===entry.tuple.ecosystem && (entry.tuple.ecosystem === 'Maven' ? a.package.name === entry.tuple.name : packageKey(a.package.name,entry.tuple.ecosystem)===packageKey(entry.tuple.name,entry.tuple.ecosystem)));
@@ -426,7 +438,7 @@ async function queryBatch(deps, opts = {}) {
426
438
  if(output[i])continue;
427
439
  const d=deps[i],q=tuple(d),view=views[i], query=view.query;
428
440
  if (query && !query.fresh)
429
- warn('source-stale',`OSV: package/version consultation for ${q.name}@${q.version} is from ${new Date(query.fetchedAt).toISOString()}.`);
441
+ warn('source-stale',`OSV: package/version consultation for ${q.name}@${q.version} is ${query.fetchedAt>1 ? `from ${new Date(query.fetchedAt).toISOString()}` : 'of unknown age'}.`,staleSeverity(query,offline,opts.maxAdvisoryAgeMs));
430
442
  if (!query && (!view.coverage?.complete || opts.useStoredRanges === false)) {
431
443
  if (!unverified.has(q.ecosystem)) unverified.set(q.ecosystem, new Set());
432
444
  unverified.get(q.ecosystem).add(`${q.name}@${q.version}`);
@@ -434,7 +446,7 @@ async function queryBatch(deps, opts = {}) {
434
446
  // An exact consultation already covers the package/version. When a
435
447
  // newer advisory supersedes it, evaluate that advisory below; the age
436
448
  // of an unrelated older catalogue does not make the query stale.
437
- if (view.coverage && !view.coverage.fresh && !query) warn('source-stale',`OSV: ${q.ecosystem} seed is from ${new Date(view.coverage.fetchedAt).toISOString()}.`);
449
+ if (view.coverage && !view.coverage.fresh && !query) warn('source-stale',`OSV: ${q.ecosystem} seed is ${view.coverage.fetchedAt>1 ? `from ${new Date(view.coverage.fetchedAt).toISOString()}` : 'of unknown age'}.`,staleSeverity(view.coverage,offline,opts.maxAdvisoryAgeMs));
438
450
  const ids=new Set(query?.ids || []), found=[]; let unknown=false;
439
451
  for(const item of view.records) {
440
452
  const v=item.document;if(v.withdrawn)continue;
@@ -462,7 +474,7 @@ async function queryBatch(deps, opts = {}) {
462
474
  const d=deps[i],q=tuple(d);
463
475
  const ownQuery=store.getQuery({source:'vigievuln',ecosystem:q.ecosystem,name:q.name,version:'*'},{ttlMs:queryTtlMs});
464
476
  const ownKey=`${q.ecosystem}\0${q.name}`;
465
- if(ownQuery&&!ownQuery.fresh&&!reviewedFreshnessNotices.has(ownKey)){reviewedFreshnessNotices.add(ownKey);onWarning?.({type:'source-stale',message:`VigieVuln: reviewed advisory consultation for ${q.name} is from ${new Date(ownQuery.fetchedAt).toISOString()}.`});}
477
+ if(ownQuery&&!ownQuery.fresh&&!reviewedFreshnessNotices.has(ownKey)){reviewedFreshnessNotices.add(ownKey);const severity=staleSeverity(ownQuery,offline,opts.maxAdvisoryAgeMs);onWarning?.({type:'source-stale',...(severity?{severity}:{}),message:`VigieVuln: reviewed advisory consultation for ${q.name} is from ${new Date(ownQuery.fetchedAt).toISOString()}.`});}
466
478
  for(const item of store.getPackageRecords(q.ecosystem,q.name,{source:'vigievuln'})) {
467
479
  const v=item.document;
468
480
  if(v.withdrawn)continue;
@@ -476,15 +488,22 @@ async function queryBatch(deps, opts = {}) {
476
488
  }
477
489
  }
478
490
  }
479
- const staleWarnings=warnings.filter(w=>w.type==='source-stale');
480
491
  for(const warning of warnings)if(warning.type!=='source-stale')onWarning?.(warning);
481
- if(staleWarnings.length===1)onWarning?.(staleWarnings[0]);
492
+ for(const severity of [undefined,'info']) {
493
+ const staleWarnings=warnings.filter(w=>w.type==='source-stale' && w.severity===severity);
494
+ if(severity==='info' && staleWarnings.length) {
495
+ const dates=staleWarnings.flatMap(w=>w.message.match(/\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{3}Z/g)||[]).sort();
496
+ const oldestFetchedAt=dates[0]||null, unknownAgeCount=staleWarnings.filter(w=>w.message.includes('unknown age')).length;
497
+ onWarning?.({type:'cache-freshness',severity:'info',source:'osv',count:staleWarnings.length,oldestFetchedAt,unknownAgeCount,queryTtlMs,
498
+ message:`OSV: saved consultations were used${offline ? ' offline' : ''}${oldestFetchedAt ? `; oldest known collection ${oldestFetchedAt}` : ''}${unknownAgeCount ? '; some collection dates are unknown' : ''}.`});
499
+ } else if(staleWarnings.length===1)onWarning?.(staleWarnings[0]);
482
500
  else if(staleWarnings.length>1) {
483
501
  const dates=staleWarnings.flatMap(w=>w.message.match(/\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{3}Z/g)||[]).sort();
484
502
  const age=dates.length ? ` Oldest saved data: ${dates[0]}.` : '';
485
503
  const older=staleWarnings.some(w=>w.message.includes('predates')) ? ' A response predates a newer saved consultation.' : '';
486
504
  onWarning?.({type:'source-stale',message:`OSV: ${staleWarnings.length} freshness notices; cached advisory data is used${offline ? ' offline' : ''}.${age}${older}`});
487
505
  }
506
+ }
488
507
  return output.flat();
489
508
  } finally { if (!opts.store) store.close(); }
490
509
  }
@@ -498,7 +517,7 @@ function queryReviewedForDeps(resolvedDeps,opts={}) {
498
517
  if(!d || d.scope==='parent' || d.provenance==='binary')continue;
499
518
  const ecosystem=osvEcosystemFor(d),name=osvPkgName(d);if(!name)continue;
500
519
  const ownQuery=store.getQuery({source:'vigievuln',ecosystem,name,version:'*'},{ttlMs:opts.queryTtlMs ?? 4 * 3600000});
501
- if(ownQuery&&!ownQuery.fresh&&!warned.has(`${ecosystem}\0${name}`)){warned.add(`${ecosystem}\0${name}`);opts.onWarning?.({type:'source-stale',message:`VigieVuln: reviewed advisory consultation for ${name} is from ${new Date(ownQuery.fetchedAt).toISOString()}.`});}
520
+ if(ownQuery&&!ownQuery.fresh&&!warned.has(`${ecosystem}\0${name}`)){warned.add(`${ecosystem}\0${name}`);const severity=staleSeverity(ownQuery,opts.offline,opts.maxAdvisoryAgeMs);opts.onWarning?.({type:'source-stale',...(severity?{severity}:{}),message:`VigieVuln: reviewed advisory consultation for ${name} is from ${new Date(ownQuery.fetchedAt).toISOString()}.`});}
502
521
  for(const version of d.versions?.length?d.versions:[d.version]) {
503
522
  if(!version||/\$\{|SNAPSHOT/i.test(version))continue;
504
523
  for(const item of store.getPackageRecords(ecosystem,name,{source:'vigievuln'})) {
@@ -3,7 +3,7 @@
3
3
  const {cleanVersion} = require("./deps-descriptor");
4
4
  const SAFE_COORD = /^[A-Za-z0-9@._+\/-]+$/;
5
5
  /** Build a path-free descriptor. Unknown relations stay unknown, never direct. */
6
- function buildProjectDescriptor(resolved, {generator="vigievuln"} = {}) {
6
+ function buildProjectDescriptor(resolved, {generator="vigievuln", imageReferences, images=true} = {}) {
7
7
  const deps = [];
8
8
  for (const dep of resolved.values()) {
9
9
  if (!dep || typeof dep.ecosystem !== "string" || !SAFE_COORD.test(dep.ecosystem) ||
@@ -25,6 +25,7 @@ function buildProjectDescriptor(resolved, {generator="vigievuln"} = {}) {
25
25
  }
26
26
  }
27
27
  deps.sort((a,b)=>`${a.ecosystem}\0${a.namespace}\0${a.name}\0${a.version || ""}`.localeCompare(`${b.ecosystem}\0${b.namespace}\0${b.name}\0${b.version || ""}`));
28
- return {schema:"fad-deps/2",generator,deps};
28
+ const refs=require("./deps-descriptor").serializeImageReferences(imageReferences,{images});
29
+ return {schema:"fad-deps/2",generator,deps,...(refs.length?{imageReferences:refs}:{})};
29
30
  }
30
31
  module.exports={buildProjectDescriptor};
package/lib/provenance.js CHANGED
@@ -118,14 +118,15 @@ function collectDataSources({ cacheDir = DEFAULT_CACHE_DIR, options = {}, ecosys
118
118
  // this run. Do not label that optional cache as "not warmed".
119
119
  return !active || options.osvDb === true || !!store?.getSourceCoverage('osv',osvEcosystems[def.id.slice(6)],{ttlMs});
120
120
  }
121
- if (['cve','mavenCentral'].includes(def.id)) return uses('maven') || uses('gradle');
121
+ if (def.id === 'cve') return !active || [...active].some(id=>id !== 'binary');
122
+ if (def.id === 'mavenCentral') return uses('maven') || uses('gradle');
122
123
  if (['packagistAudit','packagist'].includes(def.id)) return uses('composer');
123
124
  if (def.id === 'npm') return uses('npm') || uses('yarn');
124
125
  if (['nuget','go','rubygems'].includes(def.id)) return uses(def.id === 'rubygems' ? 'ruby' : def.id);
125
126
  return true;
126
127
  };
127
128
  return SOURCE_DEFS.filter(applies).map(def => {
128
- if ((def.flag && options[def.flag] === false) || (def.id === "cve" && options.disableCveProject) || (def.id.startsWith("osvDb-") && options.osvDb === false) || (def.id === "gcve" && (options.gcve === false || options.disableGcve))) {
129
+ if ((def.flag && options[def.flag] === false) || (def.id === "cve" && options.disableCveProject) || (def.id.startsWith("osvDb-") && options.osvDb === false) || (["gcve","gcveDerived"].includes(def.id) && (options.gcve === false || options.disableGcve))) {
129
130
  return { id: def.id, label: def.label, status: "disabled", asOf: null, detail: null };
130
131
  }
131
132
  let coverage = null;
@@ -165,6 +166,9 @@ function runConfiguration(options = {}) {
165
166
  transitiveDepth: options.transitiveDepth != null ? String(options.transitiveDepth) : null,
166
167
  osv: options.osv !== false,
167
168
  advisoryQueryTtlHours: options.advisoryQueryTtlMs != null ? Number(options.advisoryQueryTtlMs) / 3600000 : (options.advisoryQueryTtl != null ? Number(options.advisoryQueryTtl) : 4),
169
+ reuseStableAdvisories: options.reuseStableAdvisories !== false,
170
+ stableAdvisoryAgeDays: options.stableAdvisoryAgeDays ?? 365,
171
+ forceUpdate: !!options.forceUpdate,
168
172
  packagistAudit: options.packagistAudit !== false,
169
173
  nvd: options.nvd !== false,
170
174
  epss: options.epss !== false,
@@ -175,6 +179,8 @@ function runConfiguration(options = {}) {
175
179
  licenses: !!options.licenses,
176
180
  typosquat: !!options.typosquat,
177
181
  certs: options.certs !== false,
182
+ images: options.images !== false,
183
+ imagePlatform: options.imagePlatform || "linux/amd64",
178
184
  certExpiryDays: options.certExpiryDays != null ? String(options.certExpiryDays) : null,
179
185
  failOn: options.failOn || "none",
180
186
  ignoreFile: options.ignore || null,
@@ -0,0 +1,8 @@
1
+ 'use strict';
2
+ module.exports={id:'alpine',ttlMs:86400000,build(type,params){
3
+ const base='https://security.alpinelinux.org';let url;
4
+ if(type==='package'){const name=params?.name;if(typeof name!=='string'||!/^[a-z0-9][a-z0-9+_.-]*$/.test(name))throw Error('invalid Alpine source package');url=`${base}/srcpkg/${encodeURIComponent(name)}`;}
5
+ else if(type==='vulnerability'){const id=params?.id;if(typeof id!=='string'||!/^CVE-\d{4}-\d{4,}$/.test(id))throw Error('invalid Alpine vulnerability ID');url=`${base}/vuln/${id}`;}
6
+ else throw Error('invalid Alpine tracker request');
7
+ return {url,init:{headers:{accept:'application/json'}}};
8
+ }};
@@ -3,6 +3,10 @@ const crypto = require("node:crypto");
3
3
  function requestKey(provider, operation, params, scope = "") {
4
4
  return JSON.stringify([provider, operation, params, scope]);
5
5
  }
6
+ // Public resource identity only: never expose credentials or request URLs.
7
+ function failureKey(provider, operation, params) {
8
+ return crypto.createHash('sha256').update(requestKey(provider, operation, params)).digest('hex');
9
+ }
6
10
  function credentialScope(headers = {}) {
7
11
  const h = new Headers(headers);
8
12
  const secret = [h.get("authorization") || "", h.get("apikey") || ""].join("\0");
@@ -11,8 +15,12 @@ function credentialScope(headers = {}) {
11
15
  // Only headers needed to interpret a public response belong in the cache.
12
16
  // Never persist cookies, authentication challenges or hop-by-hop headers.
13
17
  function responseHeaders(headers) {
14
- const link = headers?.get?.("link");
15
- return link ? { link } : {};
18
+ const result={};
19
+ for(const name of ['link','x-fad-proxy-scope','x-fad-proxy-checked-at']) {
20
+ const value=headers?.get?.(name);
21
+ if(value && value.length<=1024 && !/[\r\n]/.test(value))result[name]=value;
22
+ }
23
+ return result;
16
24
  }
17
25
  // Validators refer to the upstream representation and are stored privately;
18
26
  // a proxy may return a transformed body, so do not forward them as its ETag.
@@ -34,4 +42,4 @@ function cveId(value) {
34
42
  }
35
43
  function encodePath(value) { return String(value).split("/").map(encodeURIComponent).join("/"); }
36
44
 
37
- module.exports = { requestKey, credentialScope, cveId, encodePath, responseHeaders, cacheResponseHeaders, responseFetchedAt };
45
+ module.exports = { requestKey, failureKey, credentialScope, cveId, encodePath, responseHeaders, cacheResponseHeaders, responseFetchedAt };
@@ -0,0 +1,11 @@
1
+ 'use strict';
2
+ const BASE='https://salsa.debian.org/security-tracker-team/security-tracker';
3
+ module.exports={id:'debian',ttlMs:4*3600000,build(type,params={}){
4
+ if(type==='source-version' && /^[a-z0-9][a-z0-9+.-]{0,199}$/.test(params.name||'') && typeof params.version==='string' && /^[0-9][A-Za-z0-9.+:~\-]{0,149}$/.test(params.version))
5
+ return {url:`https://sources.debian.org/api/src/${encodeURIComponent(params.name)}/${encodeURIComponent(params.version)}/`};
6
+ if(type==='history' && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/.test(params.until||'') && Number.isFinite(Date.parse(params.until)))
7
+ return {url:`https://salsa.debian.org/api/v4/projects/security-tracker-team%2Fsecurity-tracker/repository/commits?until=${encodeURIComponent(params.until)}&per_page=1`};
8
+ if(type==='list' && /^[a-f0-9]{40}$/.test(params.commit||'') && ['CVE','DSA','DLA'].includes(params.list) && Array.isArray(params.packages) && params.packages.length>0 && params.packages.length<=1000 && params.packages.every(p=>typeof p==='string' && /^[a-z0-9][a-z0-9+.-]{0,199}$/.test(p)))
9
+ return {url:`${BASE}/-/raw/${params.commit}/data/${params.list}/list`};
10
+ throw Error('invalid Debian tracker request');
11
+ }};
@@ -1,9 +1,10 @@
1
1
  // ENISA European Vulnerability Database (EUVD). Two bulk reads, no per-CVE call:
2
2
  // the CVE ↔ EUVD id mapping dump (one CSV) and the exploited catalogue, paged.
3
3
  module.exports = {
4
- id: "euvd", ttlMs: 24 * 3600 * 1000,
4
+ id: "euvd", ttlMs: 24 * 3600 * 1000, revalidateTypes: ['vulnerability'],
5
5
  build(type, params) {
6
6
  const base = "https://euvdservices.enisa.europa.eu/api";
7
+ if (type === 'vulnerability') { const id=String(params?.id||''); if(!/^EUVD-\d{4}-\d{1,12}$/.test(id)) throw new Error('invalid EUVD identifier'); return {url:`${base}/enisaid?id=${encodeURIComponent(id)}`}; }
7
8
  if (type === "cves") return { url: `${base}/dump/cve-euvd-mapping` };
8
9
  if (type === "cve-mapping") return { url: `${base}/dump/cve-euvd-mapping` };
9
10
  if (type === "exploited") {
@@ -0,0 +1,13 @@
1
+ 'use strict';
2
+ module.exports={id:'freexian',ttlMs:86400000,snapshotProjection(type,params){
3
+ if(type!=='tracker')return null;
4
+ const parse=(body,p)=>require('../system-inventory/freexian-tracker').parseTrackerBytes(body,p);
5
+ return {id:'tracker-v1',sourceParams:{},maxSourceBytes:256*1024*1024,ttlMs:4*3600*1000,contentType:'application/json',async validate(body){await parse(body,{packages:[]});},async project(body,requestParams){const result=await parse(body,requestParams);return Buffer.from(JSON.stringify({packages:result.packages}));}};
6
+ },build(type,params){
7
+ const base='https://www.freexian.com/lts/extended/updates/';
8
+ if(type==='vulnerability' && Object.keys(params||{}).length===1 && typeof params.id==='string' && /^CVE-\d{4}-\d{4,7}$/i.test(params.id))return {url:`https://deb.freexian.com/extended-lts/tracker/${params.id.toUpperCase()}`};
9
+ if(type==='tracker' && Object.keys(params||{}).length===1 && Array.isArray(params.packages) && params.packages.length>0 && params.packages.length<=1000 && params.packages.every(p=>typeof p==='string' && /^[a-z0-9][a-z0-9+.-]{0,199}$/.test(p)))return {url:'https://deb.freexian.com/extended-lts/tracker/data/json'};
10
+ if(type==='index'&&Number.isSafeInteger(params?.page)&&params.page>0&&params.page<=10000&&Object.keys(params).length===1)return {url:params.page===1?base:`${base}page/${params.page}/`};
11
+ if(type==='advisory'&&typeof params?.slug==='string'&&/^ela-\d+-\d+-[a-z0-9][a-z0-9.+-]*$/.test(params.slug)&&Object.keys(params).length===1)return {url:`${base}${params.slug}/`};
12
+ throw Error('invalid Freexian advisory request');
13
+ }};
@@ -10,6 +10,7 @@ module.exports = {
10
10
  }
11
11
  if (type === "cve-maven") return { url: "https://api.github.com/repos/CVEProject/cvelistV5" };
12
12
  if (type === "cve-npm") return { url: "https://api.github.com/repos/CVEProject/cvelistV5", proxyOnly: true };
13
+ if (type === "cve-packages") return { url: "https://api.github.com/repos/CVEProject/cvelistV5", proxyOnly: true };
13
14
  if (type === "cve-release") return { url: "https://api.github.com/repos/CVEProject/cvelistV5/releases/latest" };
14
15
  if (type === "cve-archive" && /^[A-Za-z0-9._-]+$/.test(params?.tag || "") &&
15
16
  /^[A-Za-z0-9._-]+\.zip$/i.test(params?.name || ""))
@@ -4,8 +4,9 @@ module.exports = {
4
4
  build(operation, params) {
5
5
  // An escaped module path (proxy protocol: upper case as "!x"): no query, fragment or
6
6
  // percent-escape can reach the URL, and every segment is encoded on top.
7
- if (operation !== "module-latest" || typeof params?.module !== "string" || !/^[A-Za-z0-9.!_~+-]+(\/[A-Za-z0-9.!_~+-]+)*$/.test(params.module)
7
+ if (!['module-latest','module-info'].includes(operation) || typeof params?.module !== "string" || !/^[A-Za-z0-9.!_~+-]+(\/[A-Za-z0-9.!_~+-]+)*$/.test(params.module)
8
8
  || params.module.split("/").some(s => s === "." || s === "..")) throw new Error("invalid Go module request");
9
+ if(operation==='module-info') {const version=params.version;if(typeof version!=='string'||!/^v\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+incompatible)?$/.test(version))throw new Error('invalid Go module version');const escaped=version.replace(/[A-Z]/g,c=>'!'+c.toLowerCase());return {url:`https://proxy.golang.org/${encodePath(params.module)}/@v/${encodeURIComponent(escaped)}.info`};}
9
10
  return { url: `https://proxy.golang.org/${encodePath(params.module)}/@latest` };
10
11
  },
11
12
  };
@@ -11,15 +11,16 @@ const providers = [
11
11
  require("./ruby"), require("./go"), require("./nuget"),
12
12
  require("./wordfence"), require("./wordpress"), require("./github"), require("./drupal"),
13
13
  require("./maven"), require("./hashid"), require("./osvdb"), require("./retire"),
14
- require("./euvd"), require("./certfr"), require("./gcve"), require("./vigievuln"),
14
+ require("./euvd"), require("./certfr"), require("./gcve"), require("./vigievuln"), require("./alpine"), require("./debian"), require("./nginx"), require("./freexian"),
15
15
  ];
16
16
  const byId = new Map(providers.map(provider => [provider.id, provider]));
17
17
  let route = { hosted: false, proxyUrl: null, token: null, store: null, hostedStore: null, health: null, fetcher: null, maxBodyBytes: 32 * 1024 * 1024 };
18
18
  const inFlight = new Map();
19
- const proxyThrottle = require('../proxy-throttle').createProxyThrottle();
19
+ let proxyThrottle = require('../proxy-throttle').createProxyThrottle();
20
20
  const copyResponse = response => typeof response?.clone === "function" ? response.clone() : response;
21
21
 
22
22
  function configureResourceRoute(options = {}) {
23
+ if (options.resetRateLimit) proxyThrottle = require('../proxy-throttle').createProxyThrottle();
23
24
  if (options.proxyUrl != null && !/^https?:\/\//i.test(String(options.proxyUrl)))
24
25
  throw new Error("proxy-cache URL must be http(s)");
25
26
  route = { ...route, ...options, proxyUrl: options.proxyUrl ? String(options.proxyUrl).replace(/\/+$/, "") : null };
@@ -27,6 +28,7 @@ function configureResourceRoute(options = {}) {
27
28
  }
28
29
  function hasProxyRoute() { return !!route.proxyUrl; }
29
30
  function hasHostedProxy() { return !!route.proxyUrl && !!route.hosted; }
31
+ function resourceOrigin() { return route.proxyUrl ? `proxy:${crypto.createHash('sha256').update(route.proxyUrl).digest('hex')}` : 'direct'; }
30
32
  function getProvider(id) {
31
33
  const provider = byId.get(id);
32
34
  if (!provider) throw new Error(`unknown data provider: ${id}`);
@@ -51,6 +53,8 @@ function persist(store, key, response, body, ttlMs) {
51
53
 
52
54
  async function getResource(id, type, params, options = {}) {
53
55
  const provider = getProvider(id);
56
+ const failureKey = require('./common').failureKey(id, type, params);
57
+ const revalidate = !options.offline && !!(options.forceRefresh || require('../cache-policy').shouldForceUpdate()) && provider.revalidateTypes?.includes(type);
54
58
  const request = provider.build(type, params);
55
59
  if (request.proxyOnly && (!route.proxyUrl || options.direct || options.urlOverride))
56
60
  throw new Error(`${id}.${type} requires a proxy; direct bulk fallback is unavailable`);
@@ -68,7 +72,7 @@ async function getResource(id, type, params, options = {}) {
68
72
  const cachedFresh = entry && (options.offline
69
73
  ? Date.now() >= entry.fetchedAt && Date.now()-entry.fetchedAt < Math.min(entry.ttlMs,policy.DEFAULT_TTL_MS)
70
74
  : policy.fresh(entry.fetchedAt,entry.ttlMs));
71
- if (entry && !options.forceRefresh && cachedFresh) return cachedResponse(entry,'hit',store);
75
+ if (entry && !options.forceRefresh && !revalidate && cachedFresh) return cachedResponse(entry,'hit',store);
72
76
  if (options.offline) {
73
77
  if (entry) return cachedResponse(entry, "stale",store);
74
78
  throw new Error(`no cached ${id}.${type} result for ${JSON.stringify(params)}`);
@@ -88,11 +92,11 @@ async function getResource(id, type, params, options = {}) {
88
92
  if (route.token) proxyHeaders["x-fad-proxy-token"] = route.token;
89
93
  const sendProxy = () => fetcher(`${route.proxyUrl}/v1/resource`, { method: "POST", headers: proxyHeaders,
90
94
  redirect: "error", // Never forward a proxy credential to a redirected origin.
91
- body: JSON.stringify({ provider: id, type, params, headers: Object.fromEntries(headers.entries()) }),
95
+ body: JSON.stringify({ provider: id, type, params, headers: Object.fromEntries(headers.entries()), ...(revalidate ? {revalidate:true} : {}) }),
92
96
  ...((options.signal || route.hosted) ? { signal: options.signal || AbortSignal.timeout(options.requestTimeoutMs || 15000) } : {}) });
93
- const callProxy = () => route.hosted ? proxyThrottle.request(sendProxy, options.signal, {retryDenied: options.retryProxyDenied !== false, retryTransient: !options.noSourceRetry}) : sendProxy();
97
+ const callProxy = () => (route.proxyThrottle || proxyThrottle).request(sendProxy, options.signal, {label: `${id}.${type}`, retryDenied: options.retryProxyDenied !== false, retryTransient: route.hosted && !options.noSourceRetry, ...(route.proxyRateLimitMaxWaitMs != null ? {waitBudgetMs:route.proxyRateLimitMaxWaitMs} : {}), ...(route.proxyRateLimitMaxRetries != null ? {rateRetries:route.proxyRateLimitMaxRetries} : {})});
94
98
  response = route.health && !entry && !route.hosted && !options.noSourceRetry
95
- ? await require("../source-health").guardedFetch({ health: route.health,
99
+ ? await require("../source-health").guardedFetch({ health: route.health, requestKey: failureKey, handledRateLimit:true,
96
100
  fetch: callProxy, ...(route.sleep ? { sleep: route.sleep } : {}) })(request.url,
97
101
  options.signal ? { signal: options.signal } : undefined)
98
102
  : await callProxy();
@@ -112,18 +116,18 @@ async function getResource(id, type, params, options = {}) {
112
116
  if(!current)throw Error('cached resource disappeared during revalidation');
113
117
  return cachedResponse(current,'revalidated',store);
114
118
  }
115
- const proxyStamp=Date.parse(response.headers?.get?.("x-fad-proxy-fetched-at") || '');
116
- if (response.headers?.get?.("x-fad-proxy") === "stale" || (route.proxyUrl && Number.isFinite(proxyStamp) && Date.now()-proxyStamp >= policy.DEFAULT_TTL_MS))
117
- route.health?.markStale?.(id, response.headers.get("x-fad-proxy-fetched-at"));
119
+ if (response.headers?.get?.("x-fad-proxy") === "stale")
120
+ route.health?.markStale?.(id, response.headers.get("x-fad-proxy-fetched-at"),{reason:response.headers.get('x-fad-proxy-reason'),requestKey:failureKey,refreshStatus:response.headers.get('x-fad-proxy-refresh-status'),refreshCause:response.headers.get('x-fad-proxy-refresh-cause'),retryAfter:response.headers.get('retry-after')});
118
121
  if (hasHostedProxy() && route.health && !options.noSourceRetry && (response.status === 403 || response.status === 429 || response.status >= 500)) {
119
122
  const source = require('../source-health').sourceForUrl(request.url);
120
- if (source) route.health.markOutage(source.id, {url: request.url, code: `HTTP ${response.status}`});
123
+ if (source) route.health.markOutage(source.id, {url: request.url, code: require('../request-failure').responseFailure(response,{viaProxy:true}).reason, requestKey: failureKey});
121
124
  }
122
125
  if (entry && (response.status === 403 || response.status === 429 || response.status >= 500)) {
123
- route.health?.markStale?.(id, new Date(entry.fetchedAt).toISOString());
126
+ route.health?.markStale?.(id, new Date(entry.fetchedAt).toISOString(),{reason:'refresh-failed',requestKey:failureKey});
124
127
  return cachedResponse(entry, "stale",store);
125
128
  }
126
129
  if (!response.ok || !store || options.noStore) return response;
130
+ if (response.headers.get('x-fad-proxy') === 'stale') return response;
127
131
  // A mirror or batch without an upstream timestamp cannot establish freshness.
128
132
  if (hasHostedProxy() && (response.headers.get("x-fad-proxy") === "stale" || !Number.isFinite(Date.parse(response.headers.get("x-fad-proxy-fetched-at") || "")))) return response;
129
133
  const length = Number(response.headers.get("content-length"));
@@ -132,11 +136,11 @@ async function getResource(id, type, params, options = {}) {
132
136
  try { persist(store, key, response, body, Math.min(provider.ttlMs || policy.DEFAULT_TTL_MS, policy.DEFAULT_TTL_MS)); } catch { /* source result remains usable */ }
133
137
  return response;
134
138
  } catch (error) {
135
- if (entry) { route.health?.markStale?.(id, new Date(entry.fetchedAt).toISOString()); return cachedResponse(entry, "stale",store); }
139
+ if (entry) { route.health?.markStale?.(id, new Date(entry.fetchedAt).toISOString(),{reason:'refresh-failed',requestKey:failureKey}); return cachedResponse(entry, "stale",store); }
136
140
  if (route.health && !options.noSourceRetry && !options.urlOverride && !route.health.isDown(require("../source-health").sourceForUrl(request.url)?.id)) {
137
141
  const { sourceForUrl } = require("../source-health");
138
142
  const source = sourceForUrl(request.url);
139
- if (source) route.health.markOutage(source.id, { url: request.url, code: error.code || error.message });
143
+ if (source) route.health.markOutage(source.id, { url: request.url, code: error.code || error.message, requestKey: failureKey });
140
144
  }
141
145
  throw error;
142
146
  }
@@ -156,4 +160,4 @@ async function getResource(id, type, params, options = {}) {
156
160
  }
157
161
  }
158
162
 
159
- module.exports = { providers, getProvider, providerKey, configureResourceRoute, getResource, hasProxyRoute, hasHostedProxy };
163
+ module.exports = { providers, getProvider, providerKey, configureResourceRoute, getResource, hasProxyRoute, hasHostedProxy, resourceOrigin };
@@ -0,0 +1,5 @@
1
+ 'use strict';
2
+ module.exports={id:'nginx',ttlMs:86400000,build(type,params){
3
+ if(type!=='advisories'||!params||Object.keys(params).length)throw Error('invalid NGINX advisory request');
4
+ return {url:'https://raw.githubusercontent.com/nginx/nginx.org/master/xml/en/security_advisories.xml',init:{headers:{accept:'application/xml,text/xml'}}};
5
+ }};
@@ -1,6 +1,6 @@
1
1
  const { cveId, requestKey } = require("./common");
2
2
  module.exports = {
3
- id: "nvd", ttlMs: 7 * 24 * 3600 * 1000,
3
+ id: "nvd", ttlMs: 7 * 24 * 3600 * 1000, revalidateTypes: ['cve','cve-mirror'],
4
4
  key(type, params, scope) { return requestKey("nvd", type, type === "spip-advisories" ? {} : { id: cveId(params?.id) }, scope); },
5
5
  build(operation, params) {
6
6
  if (operation === "spip-advisories") return {
@@ -7,7 +7,7 @@ function normalizedQuery(q) {
7
7
  ...(typeof q?.page_token === "string" && q.page_token ? { page_token: q.page_token } : {}) } : null;
8
8
  }
9
9
  module.exports = {
10
- id: "osv", ttlMs: 12 * 3600 * 1000,
10
+ id: "osv", ttlMs: 12 * 3600 * 1000, revalidateTypes: ['vuln'],
11
11
  key(type, params, scope) {
12
12
  return requestKey("osv", type, type === "package-version" ? normalizedQuery(params) : params, scope);
13
13
  },
@@ -1,7 +1,7 @@
1
1
  module.exports = {
2
2
  id: "osvdb", ttlMs: 12 * 3600 * 1000,
3
3
  build(type, params) {
4
- if (type !== "ecosystem-archive" || !/^[A-Za-z0-9_.+-]+$/.test(params?.ecosystem || "")) throw new Error("invalid OSV archive request");
5
- return { url: `https://osv-vulnerabilities.storage.googleapis.com/${params.ecosystem}/all.zip` };
4
+ if (type !== "ecosystem-archive" || !/^[A-Za-z0-9_.+ -]+$/.test(params?.ecosystem || "")) throw new Error("invalid OSV archive request");
5
+ return { url: `https://osv-vulnerabilities.storage.googleapis.com/${encodeURIComponent(params.ecosystem)}/all.zip` };
6
6
  },
7
7
  };