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
@@ -0,0 +1,59 @@
1
+ 'use strict';
2
+
3
+ // Isolation is local provenance, not a cryptographic signature of the bundle.
4
+ // Never populate this directory from the legacy, unscoped cache.
5
+ const fs = require('node:fs');
6
+ const path = require('node:path');
7
+ const os = require('node:os');
8
+ const crypto = require('node:crypto');
9
+ const preparedScopes=new Set();
10
+
11
+ function proxyOrigin(input) {
12
+ let url;
13
+ try { url = new URL(input); } catch { throw new Error('Proxy must be an HTTP(S) origin.'); }
14
+ if (!['https:', 'http:'].includes(url.protocol) || url.username || url.password || url.pathname !== '/' || url.search || url.hash)
15
+ throw new Error('Proxy must be an origin without credentials, path, query or fragment.');
16
+ return url.origin;
17
+ }
18
+
19
+ function requireHttpConsent(origin, {acceptedOrigin, allow = false} = {}) {
20
+ const canonical = proxyOrigin(origin);
21
+ if (canonical.startsWith('http://') && !allow && acceptedOrigin !== canonical)
22
+ throw new Error(`HTTP connection to ${canonical} is not encrypted. Run setup to confirm this server or pass --allow-insecure-http for this invocation.`);
23
+ return canonical;
24
+ }
25
+
26
+ const HTTP_WARNING = 'HTTP does not encrypt the connection: passwords, account sessions and proxy keys may be exposed. Use HTTPS on untrusted networks.';
27
+
28
+ function proxyScope(origin, {homeDir = os.homedir()} = {}) {
29
+ const canonical = proxyOrigin(origin);
30
+ const root = path.join(homeDir, '.vigie-vuln-proxy-scopes');
31
+ const id = crypto.createHash('sha256').update(canonical).digest('hex');
32
+ const scope = path.join(root, id);
33
+ let created = false;
34
+ for (const dir of [root, scope]) {
35
+ try { fs.mkdirSync(dir, {mode:0o700}); if (dir === scope) created = true; } catch (error) { if (error.code !== 'EEXIST') throw error; }
36
+ const st = fs.lstatSync(dir);
37
+ if (!st.isDirectory() || st.isSymbolicLink()) throw new Error('Unsafe proxy cache scope directory.');
38
+ }
39
+ const marker = path.join(scope, 'origin.json');
40
+ if (created) fs.writeFileSync(marker, JSON.stringify({version:1, origin:canonical}), {flag:'wx', mode:0o600});
41
+ if (!fs.existsSync(marker)) throw new Error('Proxy cache scope has no origin marker.');
42
+ const st = fs.lstatSync(marker);
43
+ if (!st.isFile() || st.isSymbolicLink() || st.nlink !== 1) throw new Error('Unsafe proxy cache scope marker.');
44
+ let meta;
45
+ try { meta = JSON.parse(fs.readFileSync(marker, 'utf8')); } catch { throw new Error('Invalid proxy cache scope marker.'); }
46
+ if (meta.version !== 1 || meta.origin !== canonical) throw new Error('Proxy cache scope origin mismatch.');
47
+ const cacheDir = path.join(scope, '.vigie-vuln');
48
+ if (fs.existsSync(cacheDir)) {
49
+ const cacheStat = fs.lstatSync(cacheDir);
50
+ if (!cacheStat.isDirectory() || cacheStat.isSymbolicLink()) throw new Error('Unsafe proxy cache directory.');
51
+ }
52
+ if(!preparedScopes.has(cacheDir)){
53
+ require('./cache-startup').prepareScopedCache(cacheDir);
54
+ preparedScopes.add(cacheDir);
55
+ }
56
+ return cacheDir;
57
+ }
58
+
59
+ module.exports = {proxyScope, proxyOrigin, requireHttpConsent, HTTP_WARNING};
@@ -0,0 +1,71 @@
1
+ 'use strict';
2
+
3
+ // The hosted service permits 7200 requests/minute per key. Leave headroom for
4
+ // concurrent scans and preflight, and coordinate all providers in this process.
5
+ function createProxyThrottle({ intervalMs = 10, maxPerMinute = 6000, sleep = (ms, signal) => require('node:timers/promises').setTimeout(ms, undefined, {signal}), now = Date.now, warn = console.error } = {}) {
6
+ let next = 0, blockedUntil = 0, warnedPacing = false, requests = 0, window = -1, count = 0;
7
+ const lastWarning = new Map();
8
+ function reserve(earliest) {
9
+ let slot = Math.max(now(), next, blockedUntil, earliest);
10
+ let current = Math.floor(slot / 60000);
11
+ if (current !== window) { window = current; count = 0; }
12
+ if (count >= maxPerMinute) {
13
+ slot = (window + 1) * 60000; window++; count = 0;
14
+ warn(`Proxy: request budget reached; waiting ${Math.ceil(Math.max(0, slot - now()) / 1000)}s for the next window.`);
15
+ }
16
+ count++;
17
+ next = slot + intervalMs;
18
+ return slot;
19
+ }
20
+ function abortError() { const error = new Error('Proxy request aborted while waiting for rate limit.'); error.name = 'AbortError'; return error; }
21
+ async function wait(ms, signal) {
22
+ if (signal?.aborted) throw abortError();
23
+ if (!signal) return sleep(ms);
24
+ let onAbort;
25
+ try { await Promise.race([sleep(ms, signal), new Promise((_, reject) => { onAbort = () => reject(abortError()); signal.addEventListener('abort', onAbort, {once:true}); })]); }
26
+ finally { signal.removeEventListener('abort', onAbort); }
27
+ }
28
+ async function acquire(signal) {
29
+ let slot = reserve(0);
30
+ if (++requests === 10 && !warnedPacing) { warnedPacing = true; warn('Proxy: pacing requests to respect the server rate limit.'); }
31
+ for (;;) {
32
+ if (slot < blockedUntil) slot = reserve(blockedUntil);
33
+ const delay = slot - now();
34
+ if (delay <= 0) break;
35
+ await wait(delay, signal);
36
+ }
37
+ }
38
+ function delayFrom(response) {
39
+ const raw = response.headers?.get?.('retry-after');
40
+ const seconds = raw && /^\d+$/.test(raw) ? Number(raw) : null;
41
+ const date = raw && seconds === null ? Date.parse(raw) : NaN;
42
+ return Math.max(1000, seconds !== null ? seconds * 1000 : Number.isFinite(date) ? date - now() : 10000);
43
+ }
44
+ async function request(fetcher, signal, {retryDenied = true, retryTransient = true} = {}) {
45
+ let limitRetries = 0, transientRetries = 0;
46
+ for (;;) {
47
+ await acquire(signal);
48
+ const response = await fetcher();
49
+ const limited = response.status === 429 || (retryDenied && response.status === 503 && response.headers?.get?.('x-fad-proxy') === 'denied');
50
+ if (!limited) {
51
+ if (!retryTransient || ![502,503,504].includes(response.status) || transientRetries++ >= 2 || (response.status === 503 && !retryDenied && response.headers?.get?.('x-fad-proxy') === 'denied')) return response;
52
+ if (response.body && !response.body.locked) void response.body.cancel().catch(() => {});
53
+ await wait(transientRetries * 500, signal);
54
+ continue;
55
+ }
56
+ if (limitRetries >= 3) return response;
57
+ limitRetries++;
58
+ const delay = delayFrom(response);
59
+ if (delay > 60000) { warn(`Proxy rate limit: retry requested after ${Math.ceil(delay / 1000)}s; stopping this request.`); return response; }
60
+ blockedUntil = Math.max(blockedUntil, now() + delay);
61
+ next = Math.max(next, blockedUntil);
62
+ if (!lastWarning.has(response.status) || now() - lastWarning.get(response.status) >= 10000) {
63
+ lastWarning.set(response.status, now());
64
+ warn(`Proxy rate limit (HTTP ${response.status}): waiting ${Math.ceil(delay / 1000)}s before retrying (attempt ${limitRetries}/3).`);
65
+ }
66
+ if (response.body && !response.body.locked) void response.body.cancel().catch(() => {});
67
+ }
68
+ }
69
+ return { request };
70
+ }
71
+ module.exports = { createProxyThrottle };
@@ -34,7 +34,7 @@ function slots(n) {
34
34
  };
35
35
  }
36
36
  const { pipeline } = require("node:stream/promises");
37
- const { responseHeaders } = require("../providers/common");
37
+ const { responseHeaders, cacheResponseHeaders } = require("../providers/common");
38
38
  const { sourceForUrl } = require("../source-health");
39
39
 
40
40
  const DEFAULT_TTL_MS = 24 * 3600 * 1000;
@@ -54,6 +54,7 @@ const TTL_BY_SOURCE = {
54
54
  };
55
55
 
56
56
  const DEFAULT_MAX_BODY_BYTES = 32 * 1024 * 1024;
57
+ const NPM_PROJECTION_MAX_BYTES = 64 * 1024 * 1024;
57
58
  const DEFAULT_MAX_TRANSFER_BYTES = 1024 * 1024 * 1024;
58
59
  const DEFAULT_MAX_STORE_BYTES = 2 * 1024 * 1024 * 1024;
59
60
  const DEFAULT_UPSTREAM_TIMEOUT_MS = 120000;
@@ -304,6 +305,8 @@ function createResourceEngine(opts = {}) {
304
305
  const release = entry.body ? () => {} : store.acquire(entry); // an in-memory body pins nothing
305
306
  res.writeHead(200, {
306
307
  ...responseHeaders(new Headers(entry.responseHeaders || {})),
308
+ ...(['rejected','storage-error'].includes(entry.responseHeaders?.['x-vigievuln-durable'])
309
+ ? {'x-vigievuln-durable':entry.responseHeaders['x-vigievuln-durable']} : {}),
307
310
  "content-type": entry.contentType || "application/octet-stream",
308
311
  "content-length": entry.bytes,
309
312
  "x-fad-proxy": tag,
@@ -332,10 +335,23 @@ function createResourceEngine(opts = {}) {
332
335
  return withUpstream(async signal => {
333
336
  stats.upstream++;
334
337
  const headers = upstreamHeadersFor(target, reqHeaders, keys);
338
+ let conditional=false;
339
+ if(method==='GET' && body==null && stale && typeof store.touch==='function') {
340
+ const saved=stale.responseHeaders||{};
341
+ if(saved.etag) {headers['if-none-match']=saved.etag;conditional=true;}
342
+ else if(saved['last-modified']) {headers['if-modified-since']=saved['last-modified'];conditional=true;}
343
+ }
335
344
  if (body != null && reqHeaders["content-type"]) headers["content-type"] = reqHeaders["content-type"];
336
345
  const up = await fetcher(target, { method, headers, signal,
337
346
  ...(body == null ? {} : { body }), redirect: "follow" });
338
- const fetchedAt = Date.now(), retainedHeaders = responseHeaders(up.headers);
347
+ const fetchedAt = Date.now(), retainedHeaders = cacheResponseHeaders(up.headers);
348
+ if(up.status===304 && conditional) {
349
+ await store.touch(cacheKey,stale,{fetchedAt,ttlMs,responseHeaders:{...stale.responseHeaders,...retainedHeaders}});
350
+ const current=await store.get(cacheKey);
351
+ if(!current)throw Error('cached resource disappeared during revalidation');
352
+ if(res && !res.destroyed)serveEntry(res,current,'revalidated');
353
+ return {stored:true,status:200,bytes:current.bytes};
354
+ }
339
355
  const contentType = up.headers.get("content-type") || "application/octet-stream";
340
356
  const json = expectsJson(resource) && method !== "HEAD";
341
357
  if (json && up.status === 200 && !up.body) throw new Error("invalid upstream JSON response");
@@ -348,7 +364,7 @@ function createResourceEngine(opts = {}) {
348
364
  return { stored: false, status: up.status, staleServed: true };
349
365
  }
350
366
  if (res && !res.destroyed) {
351
- res.writeHead(up.status, { "content-type": contentType, "x-fad-proxy": "pass" });
367
+ res.writeHead(up.status, { "content-type": contentType, "x-fad-proxy": "pass", "x-fad-proxy-fetched-at": new Date(fetchedAt).toISOString() });
352
368
  if (up.body) await pipeline(Readable.fromWeb(up.body), byteLimit(maxTransferBytes), res, { signal });
353
369
  else res.end();
354
370
  } else await up.body?.cancel();
@@ -358,7 +374,8 @@ function createResourceEngine(opts = {}) {
358
374
  try {
359
375
  // JSON must be fully validated even when too large for a store row. Bound
360
376
  // that read independently of the (potentially 1 GB) archive transfer cap.
361
- const transferLimit = json ? Math.min(maxTransferBytes, Math.max(DEFAULT_MAX_BODY_BYTES, maxBodyBytes)) : maxTransferBytes;
377
+ const largeNpm = resource?.provider === 'npm' && resource.type === 'package' && typeof transform === 'function';
378
+ const transferLimit = json ? Math.min(maxTransferBytes, Math.max(DEFAULT_MAX_BODY_BYTES, maxBodyBytes, largeNpm ? NPM_PROJECTION_MAX_BYTES : 0)) : maxTransferBytes;
362
379
  if (Number(up.headers.get("content-length")) > transferLimit) {
363
380
  await up.body.cancel(); throw new Error("proxy transfer limit exceeded");
364
381
  }
@@ -368,13 +385,20 @@ function createResourceEngine(opts = {}) {
368
385
  const replaced = json || (bytes <= cacheLimitBytes && transform && resource) ? await transformSlots(async () => {
369
386
  if (signal.aborted) throw signal.reason;
370
387
  const buffer = await writer.read();
371
- if (json) validateResourceJson(resource, parseUpstreamJson(buffer));
372
- const result = bytes <= cacheLimitBytes && transform && resource ? await transform(resource, buffer) : null;
388
+ const parsed = json ? parseUpstreamJson(buffer) : undefined;
389
+ if (json) validateResourceJson(resource, parsed);
390
+ const transformContext={
391
+ requestedUrl: target, sourceUrl: up.url || target, collectedAt: fetchedAt,
392
+ authenticated: !!(headers.authorization || headers.apiKey || headers.cookie),
393
+ };
394
+ const result = (bytes <= cacheLimitBytes || largeNpm) && transform && resource ? await transform(resource, buffer, parsed, transformContext) : null;
395
+ if(['rejected','storage-error'].includes(transformContext.durableWarning))retainedHeaders['x-vigievuln-durable']=transformContext.durableWarning;
373
396
  if (json && result) validateResourceJson(resource, parseUpstreamJson(result));
397
+ if (largeNpm && bytes > cacheLimitBytes && (!result || result.length > cacheLimitBytes)) throw new Error('oversized npm metadata could not be projected safely');
374
398
  if (signal.aborted) throw signal.reason;
375
399
  return result;
376
400
  }) : null;
377
- if (bytes <= cacheLimitBytes) {
401
+ if (bytes <= cacheLimitBytes || (largeNpm && replaced && replaced.length <= cacheLimitBytes)) {
378
402
  if (replaced) {
379
403
  await writer.abort();
380
404
  const kept = { ...metadata, bytes: replaced.length };
@@ -441,7 +465,7 @@ function createResourceEngine(opts = {}) {
441
465
  // the shared base immediately and the next reader sees the fresh one.
442
466
  stats.stale++;
443
467
  serveEntry(res, entry, "stale");
444
- viaInflight(cacheKey, target, { reqHeaders, method, body, ttlMs, cacheLimitBytes, resource, ctx }).catch(() => {});
468
+ viaInflight(cacheKey, target, { reqHeaders, stale:entry, method, body, ttlMs, cacheLimitBytes, resource, ctx }).catch(() => {});
445
469
  return;
446
470
  }
447
471
  // Blocking miss (or expired with --no-swr). Coalesce on an already-running fetch.
@@ -501,6 +525,9 @@ function createResourceEngine(opts = {}) {
501
525
  const waits = [];
502
526
  const reserved = [];
503
527
  let awaitedBytes = 0, oldestStale = null;
528
+ // A batched response is only as fresh as its oldest member. Missing items
529
+ // are fetched during this request, so its start is a conservative timestamp.
530
+ const oldestFetchedAt = entries.reduce((oldest, entry) => entry ? Math.min(oldest, entry.fetchedAt) : oldest, Date.now());
504
531
  const markStale = entry => { oldestStale = Math.min(oldestStale ?? entry.fetchedAt, entry.fetchedAt); };
505
532
  const assignResult = (i, body) => {
506
533
  awaitedBytes += Buffer.byteLength(JSON.stringify(body));
@@ -575,7 +602,7 @@ function createResourceEngine(opts = {}) {
575
602
  return sendJson(res, 502, { error: error.message }, { "x-fad-proxy": "error" });
576
603
  }
577
604
  return sendJson(res, 200, batch.merge(results), { "x-fad-proxy": oldestStale != null ? "stale" : reserved.length ? "miss" : "hit",
578
- ...(oldestStale != null ? { "x-fad-proxy-fetched-at": new Date(oldestStale).toISOString() } : {}) });
605
+ "x-fad-proxy-fetched-at": new Date(oldestStale ?? oldestFetchedAt).toISOString() });
579
606
  }
580
607
 
581
608
  const wordfenceProjection = require("./wordfence").createWordfenceProjection({
@@ -0,0 +1,95 @@
1
+ 'use strict';
2
+
3
+ const fs=require('node:fs');
4
+ const path=require('node:path');
5
+ const os=require('node:os');
6
+ const crypto=require('node:crypto');
7
+ const {Readable}=require('node:stream');
8
+ const {getCacheDb}=require('../cache-db');
9
+ const CHUNK=1024*1024;
10
+ const DEFAULT_CACHE_DIR=()=>require('../cache-directory').getProxyCacheDir();
11
+ const preparedDefaults=new Set();
12
+
13
+ function location(dir){
14
+ const name=path.basename(dir),parent=path.basename(path.dirname(dir));
15
+ if(name==='resource-cache')return {root:path.dirname(dir),prefix:'resource-cache:'};
16
+ if(parent==='hosted-resources')return {root:path.dirname(path.dirname(dir)),prefix:`hosted:${name}:`};
17
+ return {root:dir,prefix:'serve-cache:'};
18
+ }
19
+
20
+ function createCacheStore(dir=DEFAULT_CACHE_DIR()){
21
+ if(dir===DEFAULT_CACHE_DIR()&&!preparedDefaults.has(dir)){
22
+ require('../cache-startup').prepareServeCache();
23
+ preparedDefaults.add(dir);
24
+ }
25
+ const {root,prefix}=location(dir),db=getCacheDb(root),pinned=new Map(),pending=new Set();
26
+ const full=key=>prefix+key;
27
+ let maxStoreBytes=Infinity,maxEntries=Infinity;
28
+ const resource=db.prepare('SELECT r.*,b.bytes FROM resources r JOIN resource_bodies b USING(body_id) WHERE r.key=?');
29
+ const count=()=>db.prepare('SELECT COUNT(*) n FROM resources WHERE key LIKE ?').get(prefix+'%').n;
30
+ const total=()=>db.prepare('SELECT COALESCE(SUM(b.bytes),0) n FROM resources r JOIN resource_bodies b USING(body_id) WHERE r.key LIKE ?').get(prefix+'%').n;
31
+ const removeBody=id=>{
32
+ if((pinned.get(id)||0)>0){pending.add(id);return}
33
+ db.prepare('DELETE FROM resource_bodies WHERE body_id=? AND NOT EXISTS (SELECT 1 FROM resources WHERE body_id=?)').run(id,id);
34
+ pending.delete(id);
35
+ };
36
+ const evict=key=>{const old=resource.get(key);if(!old)return false;db.prepare('DELETE FROM resources WHERE key=?').run(key);removeBody(old.body_id);return true};
37
+ const makeRoom=(extra=0,keepKey=null,adding=false)=>{
38
+ if(extra>maxStoreBytes)throw Error('proxy store quota exceeded');
39
+ while(total()+extra>maxStoreBytes||count()+(adding?1:0)>maxEntries){
40
+ const rows=db.prepare('SELECT key,body_id FROM resources WHERE key LIKE ? ORDER BY fetched_at LIMIT 100').all(prefix+'%');
41
+ const victim=rows.find(row=>row.key!==keepKey && !(pinned.get(row.body_id)||0));
42
+ if(!victim)throw Error('proxy store quota exceeded (active readers are pinned)');
43
+ evict(victim.key);
44
+ }
45
+ };
46
+ function publish(key,body,meta){
47
+ const id=crypto.createHash('sha256').update(body).digest('hex'),fullKey=full(key),old=resource.get(fullKey);
48
+ makeRoom(body.length,fullKey,!old);
49
+ db.transaction(()=>{
50
+ db.prepare('INSERT OR IGNORE INTO resource_bodies(body_id,bytes,sha256) VALUES (?,?,?)').run(id,body.length,id);
51
+ if(!db.prepare('SELECT 1 FROM resource_chunks WHERE body_id=? LIMIT 1').get(id)){
52
+ const put=db.prepare('INSERT INTO resource_chunks(body_id,ordinal,data) VALUES (?,?,?)');
53
+ for(let i=0;i<body.length;i+=CHUNK)put.run(id,i/CHUNK,body.subarray(i,i+CHUNK));
54
+ }
55
+ db.prepare(`INSERT INTO resources(key,body_id,fetched_at,ttl_ms,content_type,response_headers_json,metadata_json)
56
+ VALUES (?,?,?,?,?,?,?) ON CONFLICT(key) DO UPDATE SET body_id=excluded.body_id,fetched_at=excluded.fetched_at,
57
+ ttl_ms=excluded.ttl_ms,content_type=excluded.content_type,response_headers_json=excluded.response_headers_json,
58
+ metadata_json=excluded.metadata_json`).run(fullKey,id,meta.fetchedAt,meta.ttlMs,meta.contentType||null,
59
+ JSON.stringify(meta.responseHeaders||{}),JSON.stringify({url:key}));
60
+ });
61
+ if(old&&old.body_id!==id)removeBody(old.body_id);
62
+ }
63
+ return {
64
+ dir,kind:'sqlite',maxEntryBytes:256*1024*1024,
65
+ configureLimits(bytes,entries){maxStoreBytes=bytes;maxEntries=entries;makeRoom()},
66
+ claimOwner(){return ()=>{}},
67
+ get(key){const row=resource.get(full(key));if(!row)return null;return {url:key,bodyId:row.body_id,fetchedAt:row.fetched_at,
68
+ ttlMs:row.ttl_ms,contentType:row.content_type,responseHeaders:JSON.parse(row.response_headers_json),bytes:row.bytes}},
69
+ touch(key,entry,meta){
70
+ const r=db.prepare('UPDATE resources SET fetched_at=?,ttl_ms=?,response_headers_json=? WHERE key=? AND body_id=? AND fetched_at=?')
71
+ .run(meta.fetchedAt,meta.ttlMs,JSON.stringify(meta.responseHeaders||{}),full(key),entry.bodyId,entry.fetchedAt);
72
+ return r.changes>0;
73
+ },
74
+ acquire(entry){if(!entry.bodyId)return ()=>{};const id=entry.bodyId;pinned.set(id,(pinned.get(id)||0)+1);let done=false;
75
+ return ()=>{if(done)return;done=true;const n=pinned.get(id)-1;if(n)pinned.set(id,n);else{pinned.delete(id);if(pending.has(id))removeBody(id)}}},
76
+ openBody(entry){if(entry.bodyPath)return fs.createReadStream(entry.bodyPath);
77
+ const getChunk=db.prepare('SELECT data FROM resource_chunks WHERE body_id=? AND ordinal=?');
78
+ return Readable.from((function*(){for(let ordinal=0;;ordinal++){
79
+ const row=getChunk.get(entry.bodyId,ordinal);if(!row)return;yield Buffer.from(row.data);
80
+ }})())},
81
+ readBody(entry){if(entry.bodyPath)return fs.readFileSync(entry.bodyPath);
82
+ return Buffer.concat(db.prepare('SELECT data FROM resource_chunks WHERE body_id=? ORDER BY ordinal').all(entry.bodyId).map(row=>Buffer.from(row.data)))},
83
+ createWriter(){const file=path.join(os.tmpdir(),'vigievuln-resource-'+crypto.randomBytes(12).toString('hex'));
84
+ return {account(){},sink(){return fs.createWriteStream(file,{flags:'wx',mode:0o600})},bytes(){return fs.statSync(file).size},
85
+ read(){return fs.readFileSync(file)},commit(key,meta){try{publish(key,fs.readFileSync(file),meta)}finally{fs.rmSync(file,{force:true})}},
86
+ detach(meta){const timer=setTimeout(()=>fs.rmSync(file,{force:true}),30000);timer.unref?.();return {...meta,bodyPath:file}},
87
+ abort(){fs.rmSync(file,{force:true})}}},
88
+ put(key,body,meta){publish(key,Buffer.from(body),meta)},
89
+ purge(key){return evict(full(key))},
90
+ clear(){let n=0;for(const row of db.prepare('SELECT key FROM resources WHERE key LIKE ?').all(prefix+'%'))if(evict(row.key))n++;return n},
91
+ size:count,bodyBytes:total,diskBytes:total,
92
+ };
93
+ }
94
+
95
+ module.exports={createCacheStore,DEFAULT_CACHE_DIR};
@@ -94,6 +94,8 @@ const RESOURCES = {
94
94
  "maven/preflight": NONE,
95
95
  "github/cve-release": NONE,
96
96
  "github/cve-maven": T.obj({ keys: T.arr(T.str(/^[pa]:[a-z0-9][a-z0-9._:+-]*$/, 220), 1, 200) }),
97
+ "github/cve-npm": T.obj({ names: T.arr(T.str(/^(@[a-z0-9][a-z0-9._~-]*\/)?[a-z0-9._~-][a-z0-9._~-]*$/, 214), 1, 200) }),
98
+ "vigievuln/advisories": T.obj({ packages: T.arr(T.obj({ecosystem:T.oneOf(['Maven','npm']),name:OSV_NAME}),1,200) }),
97
99
  "github/cve-archive": T.obj({ tag: T.str(/^[A-Za-z0-9._-]+$/, 100), name: T.str(/^[A-Za-z0-9._-]+\.zip$/i, 200) }),
98
100
  "github/publisher-advisories": T.obj({ repo: T.str(/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/, 200), page: T.int(1, 1000), perPage: T.int(1, 100) }, ["page", "perPage"]),
99
101
  "hashid/depsdev-sha1": T.obj({ base64: T.str(/^[A-Za-z0-9+/]{27}=$/, 28) }),
@@ -112,6 +114,9 @@ const RESOURCES = {
112
114
  "certfr/index": T.obj({ kind: T.oneOf(["avis", "alerte"]) }),
113
115
  "certfr/advisory": T.obj({ kind: T.oneOf(["avis", "alerte"]), ref: T.str(/^CERT(?:FR|A)-\d{4}-(?:AVI|ALE)-\d{1,5}$/, 30),
114
116
  rev: (v, at) => { if (typeof v !== "string" || v.length > 40 || !/^[0-9T:.+-]*$/.test(v)) throw new ValidationError(`${at}: invalid value`, at); return v; } }, ["rev"]),
117
+ "gcve/directory": NONE,
118
+ "gcve/signature": NONE,
119
+ "gcve/gna-dump": T.obj({ gna: T.int(1,1000000) }),
115
120
  };
116
121
 
117
122
  /** Request headers a client may forward upstream (lower-case names), each strictly typed. */
package/lib/retire.js CHANGED
@@ -26,7 +26,7 @@ const { promisify } = require("util");
26
26
  const execFileP = promisify(execFile);
27
27
 
28
28
  const RETIRE_CACHE_DIR = path.join(require("./cache-directory").getCacheDir(), "retire-cache");
29
- const RETIRE_CACHE_TTL_MS = 24 * 3600 * 1000;
29
+ const RETIRE_CACHE_TTL_MS = 4 * 3600 * 1000;
30
30
 
31
31
  // retire's own signature DB. By default retire caches it in /tmp/.retire-cache
32
32
  // (outside ~/.fad-checker/, with a 1h TTL → a network refetch on expiry). For the
@@ -64,22 +64,25 @@ function cacheKey(srcDir) {
64
64
  const RETIRE_CACHE_SCHEMA = 2;
65
65
 
66
66
  function readCache(srcDir) {
67
- const p = path.join(RETIRE_CACHE_DIR, cacheKey(srcDir));
68
- if (!fs.existsSync(p)) return null;
69
67
  try {
70
- const data = JSON.parse(fs.readFileSync(p, "utf8"));
68
+ const data = require('./cache-repository').createCacheRepository(path.dirname(RETIRE_CACHE_DIR)).get('retire-results',cacheKey(srcDir))?.value;
71
69
  if (!(data._schema >= RETIRE_CACHE_SCHEMA)) return null; // legacy / pre-verbose → re-scan
72
- if (Date.now() - data._fetchedAt < RETIRE_CACHE_TTL_MS) return data.body;
70
+ if (require('./cache-policy').fresh(data._fetchedAt, RETIRE_CACHE_TTL_MS)) return data.body;
73
71
  } catch { /* ignore */ }
74
72
  return null;
75
73
  }
76
74
 
77
75
  function writeCache(srcDir, body) {
78
- fs.mkdirSync(RETIRE_CACHE_DIR, { recursive: true });
79
- fs.writeFileSync(path.join(RETIRE_CACHE_DIR, cacheKey(srcDir)),
80
- JSON.stringify({ _schema: RETIRE_CACHE_SCHEMA, _fetchedAt: Date.now(), body }));
76
+ require('./cache-repository').createCacheRepository(path.dirname(RETIRE_CACHE_DIR)).put('retire-results',cacheKey(srcDir),
77
+ { _schema: RETIRE_CACHE_SCHEMA, _fetchedAt: Date.now(), body });
81
78
  }
82
79
 
80
+ function cachedSignatureEntry(){
81
+ try{return require('./cache-repository').createCacheRepository(path.dirname(RETIRE_SIG_DIR)).get('auxiliary','retire-signatures')||null}
82
+ catch{return null}
83
+ }
84
+ function cachedSignatures(){return cachedSignatureEntry()?.value || null}
85
+
83
86
  function findRetireBin() {
84
87
  const local = path.join(__dirname, "..", "node_modules", ".bin", "retire");
85
88
  if (fs.existsSync(local)) return local;
@@ -131,13 +134,13 @@ function findRetireLauncher() {
131
134
  */
132
135
  async function warmRetireSignatures(opts = {}) {
133
136
  const { verbose, force, offline } = opts;
134
- const present = fs.existsSync(RETIRE_SIG_FILE);
135
- if (offline) return present ? { ok: true, path: RETIRE_SIG_FILE, cached: true }
137
+ const present = !!cachedSignatures();
138
+ if (offline) return present ? { ok: true, cached: true }
136
139
  : { ok: false, error: "offline: no local retire signatures" };
137
140
  const hostedOnline = require("./providers").hasHostedProxy();
138
- if (!force && !hostedOnline && present) {
141
+ if (!force && !hostedOnline && present && require('./cache-policy').fresh(cachedSignatureEntry()?.fetchedAt)) {
139
142
  if (verbose) console.log(`retire: signatures already present (${RETIRE_SIG_FILE})`);
140
- return { ok: true, path: RETIRE_SIG_FILE, cached: true };
143
+ return { ok: true, cached: true };
141
144
  }
142
145
  try {
143
146
  const res = await require("./providers").getResource("retire", "signatures", {},
@@ -146,13 +149,9 @@ async function warmRetireSignatures(opts = {}) {
146
149
  const text = await res.text();
147
150
  const repo = JSON.parse(text);
148
151
  if (!repo || typeof repo !== "object" || Array.isArray(repo)) throw new Error("invalid retire signatures");
149
- fs.mkdirSync(RETIRE_SIG_DIR, { recursive: true });
150
- // Failed/truncated refreshes must leave the offline snapshot intact.
151
- const temp = `${RETIRE_SIG_FILE}.${crypto.randomBytes(8).toString("hex")}.tmp`;
152
- try { fs.writeFileSync(temp, text); fs.renameSync(temp, RETIRE_SIG_FILE); }
153
- finally { try { fs.unlinkSync(temp); } catch { /* renamed or not created */ } }
154
- if (verbose) console.log(`retire: signatures warmed → ${RETIRE_SIG_FILE}`);
155
- return { ok: true, path: RETIRE_SIG_FILE };
152
+ require('./cache-repository').createCacheRepository(path.dirname(RETIRE_SIG_DIR)).put('auxiliary','retire-signatures',text);
153
+ if (verbose) console.log('retire: signatures warmed into SQLite cache');
154
+ return { ok: true };
156
155
  } catch (e) {
157
156
  if (verbose) console.warn(`retire: signature warm failed — ${e.message}`);
158
157
  return { ok: false, error: e.message };
@@ -162,10 +161,9 @@ async function warmRetireSignatures(opts = {}) {
162
161
  // Hosted online: always consult the proxy (including its stale/source-health signal).
163
162
  // Offline: only report local availability, even with --force and a configured proxy.
164
163
  async function ensureSignatures({ verbose, offline, fetcher } = {}) {
165
- if (offline) return fs.existsSync(RETIRE_SIG_FILE);
166
- if (!require("./providers").hasHostedProxy() && fs.existsSync(RETIRE_SIG_FILE)) return true;
164
+ if (offline) return !!cachedSignatures();
167
165
  const r = await warmRetireSignatures({ verbose, fetcher });
168
- return !!r.ok;
166
+ return !!r.ok || (!require('./providers').hasHostedProxy() && !!cachedSignatures());
169
167
  }
170
168
 
171
169
  // Directories retire never needs to walk. Mirrors the per-walker default SKIP sets
@@ -332,7 +330,7 @@ async function runRetire(srcDir, opts = {}) {
332
330
  if (!force && !hostedOnline) {
333
331
  const cached = readCache(srcDir);
334
332
  if (cached) {
335
- if (verbose) console.log("retire: using cached results (<24h)");
333
+ if (verbose) console.log("retire: using cached results (<4h)");
336
334
  return cached;
337
335
  }
338
336
  }
@@ -370,7 +368,9 @@ async function runRetire(srcDir, opts = {}) {
370
368
  try { fs.rmSync(tmpDir, { recursive: true, force: true }); } catch { /* best effort */ }
371
369
  };
372
370
 
373
- const args = buildRetireArgs({ srcDir, outPath: tmpOut, ignoreFile: tmpIgnore, jsRepo: haveSig ? RETIRE_SIG_FILE : null });
371
+ const signatureFile=haveSig?path.join(tmpDir,'jsrepository-v5.json'):null;
372
+ if(signatureFile)fs.writeFileSync(signatureFile,cachedSignatures(),{mode:0o600,flag:'wx'});
373
+ const args = buildRetireArgs({ srcDir, outPath: tmpOut, ignoreFile: tmpIgnore, jsRepo: signatureFile });
374
374
  if (verbose) console.log(`retire: scanning ${srcDir}…${haveSig ? " (local signatures)" : ""}`);
375
375
 
376
376
  let execErr = null;
@@ -0,0 +1,36 @@
1
+ 'use strict';
2
+
3
+ // RubyGems version ordering, not SemVer: alphabetic segments precede numeric
4
+ // segments, numeric segments use arbitrary precision, and '-' denotes '.pre.'.
5
+ // Only nonempty, bounded, literal version strings are accepted; branches,
6
+ // constraints and platform suffixes outside Gem::Version's grammar are unknown.
7
+ // Reference: https://guides.rubygems.org/patterns/#semantic-versioning
8
+ const VERSION = /^[0-9]+(?:\.[0-9A-Za-z]+)*(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;
9
+
10
+ function segments(version) {
11
+ if (typeof version !== 'string' || !version || version.length > 1024 || !VERSION.test(version)) return null;
12
+ const tokens = version.replace(/-/g, '.pre.').match(/[0-9]+|[A-Za-z]+/g)
13
+ .map(token => /^\d+$/.test(token) ? BigInt(token) : token);
14
+ const firstLabel = tokens.findIndex(token => typeof token === 'string');
15
+ const release = tokens.slice(0, firstLabel < 0 ? tokens.length : firstLabel);
16
+ const prerelease = firstLabel < 0 ? [] : tokens.slice(firstLabel);
17
+ // Zero padding is insignificant both before the first prerelease label and
18
+ // at the end. Preserve zeros inside either section: 1.0.1 differs from 1.1.
19
+ while (release.length && release.at(-1) === 0n) release.pop();
20
+ while (prerelease.length && prerelease.at(-1) === 0n) prerelease.pop();
21
+ return [...release, ...prerelease];
22
+ }
23
+
24
+ function compareRubyVersions(a, b) {
25
+ const left = segments(a), right = segments(b);
26
+ if (!left || !right) return null;
27
+ for (let i = 0; i < Math.max(left.length, right.length); i++) {
28
+ const x = left[i] ?? 0n, y = right[i] ?? 0n;
29
+ if (x === y) continue;
30
+ if (typeof x !== typeof y) return typeof x === 'string' ? -1 : 1;
31
+ return x < y ? -1 : 1;
32
+ }
33
+ return 0;
34
+ }
35
+
36
+ module.exports = { compareRubyVersions };
@@ -99,7 +99,7 @@ function buildSarif(matches, opts = {}) {
99
99
  const bits = [`${coord}@${m.dep.version || "?"}`];
100
100
  if (cve.kev) bits.push("CISA-KEV (exploited)");
101
101
  if (cve.epssPercentile != null) bits.push(`EPSS ${Math.round(cve.epssPercentile * 100)}%`);
102
- if (cve.fixVersion) bits.push(`fix ≥ ${cve.fixVersion}`);
102
+ if (cve.fixVersion) bits.push(`advisory-specific candidate ${cve.fixVersion}; package-wide safety unverified`);
103
103
  const text = `${id} in ${bits.join(" · ")}${cve.description ? ` — ${cve.description.slice(0, 300)}` : ""}`;
104
104
 
105
105
  const locations = (m.dep.manifestPaths || m.dep.pomPaths || [])
@@ -26,11 +26,13 @@ function cvssMethod(cvssVersion) {
26
26
  // Point the advisory source at the right database for the id type — a GHSA/OSV id
27
27
  // has no page on nvd.nist.gov, so the old hardcoded NVD url was a dead link.
28
28
  function advisorySource(id, source) {
29
- if (String(source || "").includes("wordfence-v3")) return { name: "Wordfence", url: "https://www.wordfence.com/threat-intel/vulnerabilities/" };
30
- if (String(source || "").includes("drupal-security-advisories")) return { name: "Drupal Security Advisories", url: "https://www.drupal.org/security" };
31
- if (/^CVE-/i.test(id)) return { name: "NVD", url: `https://nvd.nist.gov/vuln/detail/${encodeURIComponent(id)}` };
32
- if (/^GHSA-/i.test(id)) return { name: "GitHub Advisory Database", url: `https://github.com/advisories/${encodeURIComponent(id)}` };
33
- return { name: (source || "").includes("nvd") ? "NVD" : "OSV", url: `https://osv.dev/vulnerability/${encodeURIComponent(id)}` };
29
+ const sources = new Set(String(source || "cache").split('+'));
30
+ if (sources.has("wordfence-v3")) return { name: "Wordfence", url: "https://www.wordfence.com/threat-intel/vulnerabilities/" };
31
+ if (sources.has("drupal-security-advisories")) return { name: "Drupal Security Advisories", url: "https://www.drupal.org/security" };
32
+ if (sources.has("CVEProject") && /^CVE-/i.test(id)) return { name: "CVEProject", url: `https://www.cve.org/CVERecord?id=${encodeURIComponent(id)}` };
33
+ if (sources.has("osv")) return { name: "OSV", url: `https://osv.dev/vulnerability/${encodeURIComponent(id)}` };
34
+ if (sources.has("nvd") && /^CVE-/i.test(id)) return { name: "NVD", url: `https://nvd.nist.gov/vuln/detail/${encodeURIComponent(id)}` };
35
+ return { name: source || "cache" };
34
36
  }
35
37
 
36
38
  // Stable, UNIQUE bom-ref. Declared deps use their purl (unchanged). Embedded
@@ -126,8 +128,8 @@ function buildCycloneDx(resolvedDeps, cveMatches, opts = {}) {
126
128
  id,
127
129
  source: advisorySource(id, m.source),
128
130
  ratings: cve.score != null ? [{
129
- source: { name: String(m.source || "").includes("wordfence-v3") ? "Wordfence" :
130
- String(m.source || "").includes("drupal-security-advisories") ? "Drupal Security Advisories" : "NVD" },
131
+ // A merged finding does not identify which source supplied the score.
132
+ ...(m.source && !m.source.includes('+') ? { source: { name: advisorySource(id, m.source).name } } : {}),
131
133
  score: cve.score,
132
134
  severity: cdxSeverity(cve.severity),
133
135
  method: cvssMethod(cve.cvssVersion),
@@ -141,6 +143,8 @@ function buildCycloneDx(resolvedDeps, cveMatches, opts = {}) {
141
143
  };
142
144
  byCve.set(id, v);
143
145
  }
146
+ for (const source of String(m.source || 'cache').split('+').filter(Boolean))
147
+ if (!v.properties.some(p => p.name === 'vigievuln:source' && p.value === source)) v.properties.push({ name: 'vigievuln:source', value: source });
144
148
  for (const ref of refs) if (ref && !v.affects.some(a => a.ref === ref)) v.affects.push({ ref });
145
149
  if (m.cpeFiltered) v.properties.push({ name: "fad:cpe-filtered", value: "true" });
146
150
  // One property per physical occurrence: consumers must be able to relate the SBOM