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
@@ -49,7 +49,7 @@ const NEVER_IMPORT = ["config.json"];
49
49
  * that names the release it was built from. Merged per-file they could end up
50
50
  * describing two different builds, so the freshest side wins as a block.
51
51
  */
52
- const ATOMIC_DIRS = ["cve-data"];
52
+ const ATOMIC_DIRS = ["cve-data", "gcve-data", ...["maven", "npm", "pypi", "composer", "nuget", "go", "ruby"].map(e => `osv-db/records/${e}`)];
53
53
 
54
54
  function readJson(file) {
55
55
  try { return JSON.parse(fs.readFileSync(file, "utf8")); } catch { return null; }
@@ -125,10 +125,80 @@ function copyTree(srcDir, dstDir) {
125
125
  }
126
126
  }
127
127
 
128
+ // Seed metadata and its records must be validated and compared as a pair. A
129
+ // forged file mtime must not replace a newer working snapshot, and a corrupt
130
+ // download must never destroy the last usable copy.
131
+ function osvSeedInfo(dir, name) {
132
+ try {
133
+ const expected = {maven:'Maven',npm:'npm',pypi:'PyPI',composer:'Packagist',nuget:'NuGet',go:'Go',ruby:'RubyGems'}[name];
134
+ const metaFile = path.join(dir,'meta.json'), records = path.join(dir,'records.jsonl');
135
+ for (const file of [metaFile,records]) { const st=fs.lstatSync(file); if (!st.isFile() || st.isSymbolicLink() || st.nlink !== 1) return null; }
136
+ const meta=readJson(metaFile);
137
+ if (!expected || meta?._schema !== 1 || meta.ecosystem !== expected || typeof meta.complete !== 'boolean' || !Number.isSafeInteger(meta._builtAt) || meta._builtAt <= 0 || meta._builtAt > Date.now()+300000 ||
138
+ !Number.isSafeInteger(meta.recordCount) || meta.recordCount < 0 || !/^[a-f0-9]{64}$/.test(meta.sha256)) return null;
139
+ const hash=require('crypto').createHash('sha256'), fd=fs.openSync(records,'r');
140
+ try { const buf=Buffer.allocUnsafe(128*1024); for(let n;(n=fs.readSync(fd,buf,0,buf.length,null))>0;) hash.update(buf.subarray(0,n)); }
141
+ finally { fs.closeSync(fd); }
142
+ return hash.digest('hex') === meta.sha256 ? meta : null;
143
+ } catch { return null; }
144
+ }
145
+
146
+ function mergeOsvSeed(src, dst, rel, stats) {
147
+ const incoming=osvSeedInfo(src,path.basename(rel)), current=osvSeedInfo(dst,path.basename(rel));
148
+ if (!incoming) { stats.skipped.push(rel + ': invalid OSV seed'); return; }
149
+ if (current?.complete && !incoming.complete) { stats.skipped.push(rel + ': incomplete OSV seed'); return; }
150
+ if (current && current._builtAt >= incoming._builtAt) { stats.kept++; return; }
151
+ const suffix=require('crypto').randomBytes(8).toString('hex');
152
+ const staged=`${dst}.stage-${suffix}`, backup=`${dst}.backup-${suffix}`;
153
+ let moved=false;
154
+ try {
155
+ copyTree(src,staged);
156
+ if (!osvSeedInfo(staged,path.basename(rel))) throw new Error('OSV seed changed during import');
157
+ if (fs.existsSync(dst)) { fs.renameSync(dst,backup); moved=true; }
158
+ try { fs.renameSync(staged,dst); } catch (error) { if(moved)fs.renameSync(backup,dst); moved=false; throw error; }
159
+ if (moved) fs.rmSync(backup,{recursive:true,force:true});
160
+ stats[current ? 'updated' : 'added']++;
161
+ } finally { fs.rmSync(staged,{recursive:true,force:true}); }
162
+ }
163
+
164
+ function gcveSeedInfo(dir) {
165
+ try {
166
+ const file=path.join(dir,'index.json'), st=fs.lstatSync(file);
167
+ if (!st.isFile() || st.isSymbolicLink() || st.nlink !== 1) return null;
168
+ const index=require('./gcve-index').readGcveIndex(file);
169
+ const at=Date.parse(index._fadSnapshot?.collectedAt);
170
+ if (!index.directory?.verified || !Number.isFinite(at) || at <= 0 || at > Date.now()+300000) return null;
171
+ return {at,complete:index.coverage.every(c=>c.complete === true)};
172
+ } catch { return null; }
173
+ }
174
+
175
+ function mergeGcveSeed(src,dst,stats) {
176
+ const incoming=gcveSeedInfo(src),current=gcveSeedInfo(dst);
177
+ if (!incoming) {stats.skipped.push('gcve-data: invalid index');return;}
178
+ if (current && (current.at >= incoming.at || (current.complete && !incoming.complete))) {stats.kept++;return;}
179
+ const suffix=require('crypto').randomBytes(8).toString('hex'), staged=`${dst}.stage-${suffix}`,backup=`${dst}.backup-${suffix}`;
180
+ let moved=false;
181
+ try {
182
+ copyTree(src,staged);
183
+ if (!gcveSeedInfo(staged)) throw Error('GCVE seed changed during import');
184
+ if (fs.existsSync(dst)) {fs.renameSync(dst,backup);moved=true;}
185
+ try {fs.renameSync(staged,dst);} catch (error) {if(moved)fs.renameSync(backup,dst);moved=false;throw error;}
186
+ if(moved)fs.rmSync(backup,{recursive:true,force:true});
187
+ stats[current?'updated':'added']++;
188
+ } finally {fs.rmSync(staged,{recursive:true,force:true});}
189
+ }
190
+
128
191
  function mergeFile(srcFile, dstFile, rel, stats) {
129
192
  if (!fs.existsSync(dstFile)) { copyPreservingTime(srcFile, dstFile); stats.added++; return; }
130
193
  const srcJson = readJson(srcFile), dstJson = readJson(dstFile);
131
194
  if (isEntryMap(srcJson) && isEntryMap(dstJson)) {
195
+ // Legacy Maven false values do not prove absence and must never override a
196
+ // confirmed hit, even if their containing cache file is more recent.
197
+ if (rel === "maven-exists-cache.json") {
198
+ const { discardUnverifiedEntries } = require("./maven-presence");
199
+ discardUnverifiedEntries(srcJson);
200
+ discardUnverifiedEntries(dstJson);
201
+ }
132
202
  mergeEntryMaps(srcFile, dstFile, srcJson, dstJson);
133
203
  stats.merged++;
134
204
  return;
@@ -137,6 +207,31 @@ function mergeFile(srcFile, dstFile, rel, stats) {
137
207
  else stats.kept++;
138
208
  }
139
209
 
210
+ // Compact generations are immutable and identified by their manifest hash.
211
+ // Never merge individual shards by mtime: a newer local shard may be corrupt.
212
+ function mergeNvdBulk(src, dst, stats) {
213
+ const {validateGeneration}=require('./nvd-bulk');
214
+ fs.mkdirSync(dst,{recursive:true});
215
+ for (const name of fs.readdirSync(src)) {
216
+ const source=path.join(src,name), target=path.join(dst,name);
217
+ if (fs.existsSync(target)) {
218
+ try {validateGeneration(target);stats.kept++;continue;} catch { /* preserve and repair below */ }
219
+ }
220
+ const parent=path.dirname(dst), stage=fs.mkdtempSync(path.join(parent,'.nvd-stage-'));
221
+ const staged=path.join(stage,name), backup=fs.mkdtempSync(path.join(parent,'.nvd-backup-'));
222
+ const saved=path.join(backup,name); let moved=false;
223
+ try {
224
+ copyTree(source,staged);validateGeneration(staged);
225
+ if (fs.existsSync(target)) {fs.renameSync(target,saved);moved=true;}
226
+ try {fs.renameSync(staged,target);} catch (error) {if(moved)fs.renameSync(saved,target);moved=false;throw error;}
227
+ stats[moved?'updated':'added']++;
228
+ } finally {
229
+ fs.rmSync(stage,{recursive:true,force:true});
230
+ if (!moved) fs.rmSync(backup,{recursive:true,force:true});
231
+ }
232
+ }
233
+ }
234
+
140
235
  function mergeResourceStore(srcDir, dstDir, stats) {
141
236
  const { createCacheStore } = require("./proxy-cache");
142
237
  const incoming = createCacheStore(srcDir), target = createCacheStore(dstDir);
@@ -158,6 +253,89 @@ function mergeResourceStore(srcDir, dstDir, stats) {
158
253
  }
159
254
  }
160
255
 
256
+ // 1.1.3 used a Maven-only per-package projection with no schema field. Keep
257
+ // it in its own namespace: it contains neither complete native records nor
258
+ // withdrawal evidence. Do not convert the unpublished schema-2 indexes.
259
+ function readLegacyMavenIndex(file) {
260
+ const index = readJson(file);
261
+ if (!index || index._schema != null || index.ecosystem !== 'Maven' ||
262
+ !Number.isSafeInteger(index._builtAt) || index._builtAt <= 0 || index._builtAt > Date.now() + 300000 ||
263
+ !index.byPackage || typeof index.byPackage !== 'object' || Array.isArray(index.byPackage)) return null;
264
+ const records = new Map(), invalid = new Set();
265
+ for (const [name, entries] of Object.entries(index.byPackage)) {
266
+ if (!Array.isArray(entries)) throw new Error('invalid legacy Maven OSV index');
267
+ for (const document of entries) {
268
+ if (!document || typeof document.id !== 'string' || !Array.isArray(document.affected)) throw new Error('invalid legacy Maven OSV advisory');
269
+ if (document.affected.some(a=>a?.package?.ecosystem !== 'Maven' || String(a?.package?.name || '').toLowerCase() !== name.toLowerCase())) throw new Error('invalid legacy Maven OSV package');
270
+ const {affected, ...rest}=document, previous=records.get(document.id), signature=JSON.stringify(rest);
271
+ if (previous && previous.signature !== signature) {invalid.add(document.id);continue;}
272
+ if (!previous) records.set(document.id,{signature,document:{...rest,affected:[...affected]}});
273
+ else previous.document.affected.push(...affected);
274
+ }
275
+ }
276
+ for (const id of invalid) records.delete(id);
277
+ return {builtAt:index._builtAt, documents:[...records.values()].map(r=>r.document), conflicting:invalid.size};
278
+ }
279
+
280
+ async function importLegacyMavenIndex(cacheDir, file = path.join(cacheDir,'osv-db','maven-index.json')) {
281
+ const legacy = readLegacyMavenIndex(file);
282
+ if (!legacy) throw new Error('unrecognized or experimental Maven OSV index');
283
+ const store = require('./advisory-store').openAdvisoryStore({cacheDir});
284
+ await store.importRecords(legacy.documents, {source:'osv-legacy-maven', fetchedAt:legacy.builtAt, provenance:{transport:'legacy',format:'vigievuln-1.1.3'}, coverages:[{source:'osv-legacy-maven',ecosystem:'Maven',fetchedAt:legacy.builtAt,complete:false,provenance:{transport:'legacy'}}]});
285
+ return {count:legacy.documents.length,conflicting:legacy.conflicting};
286
+ }
287
+
288
+ // Validate and stream a complete native OSV seed. importRecords stages the entire
289
+ // iterable and verifies each record before publishing it to the journal.
290
+ function readNativeSeed(dir) {
291
+ const meta = readJson(path.join(dir, 'meta.json'));
292
+ const validEcos = new Set(['Maven','npm','PyPI','Packagist','NuGet','Go','RubyGems']);
293
+ if (!meta || meta._schema !== 1 || meta.source !== 'osv' || meta.complete !== true ||
294
+ !Number.isSafeInteger(meta._builtAt) || meta._builtAt <= 0 || meta._builtAt > Date.now() + 300000 ||
295
+ !Number.isSafeInteger(meta.recordCount) || meta.recordCount < 0 || !/^[a-f0-9]{64}$/.test(meta.sha256) ||
296
+ !Array.isArray(meta.ecosystems) || !meta.ecosystems.length || meta.ecosystems.some(e => !validEcos.has(e)) || new Set(meta.ecosystems).size !== meta.ecosystems.length)
297
+ throw new Error('invalid native OSV seed metadata');
298
+ const file = path.join(dir, 'osv.jsonl');
299
+ if (!fs.statSync(file).isFile()) throw new Error('missing native OSV seed records');
300
+ return {meta, file};
301
+ }
302
+ async function* nativeSeedRecords({meta,file}, onProgress) {
303
+ const hash = require('node:crypto').createHash('sha256');
304
+ const stream = fs.createReadStream(file); stream.on('data', chunk => hash.update(chunk));
305
+ const lines = require('./line-stream').readTextLines(stream);
306
+ let count = 0;
307
+ try {
308
+ for await (const line of lines) {
309
+ if (!line || Buffer.byteLength(line) > 16 * 1024 * 1024) throw new Error('invalid or oversized native OSV seed record');
310
+ const document = JSON.parse(line);
311
+ if (!document || typeof document.id !== 'string' || (!Array.isArray(document.affected) && !(document.withdrawn && document.affected == null))) throw new Error('invalid native OSV seed record');
312
+ count++; if (count % 1000 === 0) onProgress?.({phase:'index-osv',count,total:meta.recordCount}); yield document;
313
+ }
314
+ } finally { stream.destroy(); }
315
+ if (count !== meta.recordCount || hash.digest('hex') !== meta.sha256) throw new Error('native OSV seed checksum or count mismatch');
316
+ onProgress?.({phase:'index-build',count});
317
+ }
318
+
319
+ function readCveSeed(dir) {
320
+ const meta=readJson(path.join(dir,'cveproject-meta.json'));
321
+ if (!meta || meta._schema!==1 || meta.source!=='cveproject' || meta.complete!==false ||
322
+ !Number.isSafeInteger(meta._builtAt) || meta._builtAt<=0 || meta._builtAt>Date.now()+300000 ||
323
+ !Number.isSafeInteger(meta.recordCount) || meta.recordCount<0 || !/^[a-f0-9]{64}$/.test(meta.sha256)) throw new Error('invalid CVEProject seed metadata');
324
+ const file=path.join(dir,'cveproject.jsonl');if(!fs.statSync(file).isFile())throw new Error('missing CVEProject seed records');
325
+ return {meta,file};
326
+ }
327
+ async function* cveSeedEnvelopes({meta,file}, onProgress) {
328
+ const hash=require('node:crypto').createHash('sha256'), stream=fs.createReadStream(file);
329
+ stream.on('data',chunk=>hash.update(chunk));
330
+ const lines=require('./line-stream').readTextLines(stream);let count=0;
331
+ try {for await (const line of lines) {
332
+ if(!line || Buffer.byteLength(line)>16*1024*1024)throw new Error('invalid or oversized CVEProject seed record');
333
+ count++;if(count % 1000 === 0)onProgress?.({phase:'index-cve',count,total:meta.recordCount});yield require('./native-advisories').cveEnvelope(JSON.parse(line),{fetchedAt:meta._builtAt,provenance:{transport:'seed'}});
334
+ }} finally {stream.destroy();}
335
+ if(count!==meta.recordCount || hash.digest('hex')!==meta.sha256)throw new Error('CVEProject seed checksum or count mismatch');
336
+ onProgress?.({phase:'index-build',count});
337
+ }
338
+
161
339
  function mergeTree(srcDir, dstDir, stats, rel = "") {
162
340
  fs.mkdirSync(dstDir, { recursive: true });
163
341
  for (const ent of fs.readdirSync(srcDir, { withFileTypes: true })) {
@@ -165,7 +343,11 @@ function mergeTree(srcDir, dstDir, stats, rel = "") {
165
343
  const s = path.join(srcDir, ent.name), d = path.join(dstDir, ent.name);
166
344
  if (NEVER_IMPORT.includes(relPath)) { stats.skipped.push(relPath); continue; }
167
345
  if (ent.isDirectory()) {
346
+ if (relPath === "advisory-store") continue; // journal is merged separately; indexes are derived
168
347
  if (relPath === "resource-cache") { mergeResourceStore(s, d, stats); continue; }
348
+ if (relPath === "nvd-cache/_bulk") { mergeNvdBulk(s,d,stats); continue; }
349
+ if (relPath === "gcve-data") { mergeGcveSeed(s,d,stats); continue; }
350
+ if (relPath === "osv-db/records") { stats.skipped.push("osv-db/records: obsolete partitioned OSV seed cannot be imported; obtain a current bundle"); continue; }
169
351
  if (ATOMIC_DIRS.includes(relPath)) {
170
352
  if (!fs.existsSync(d)) { copyTree(s, d); stats.added++; }
171
353
  else if (newestMtime(s) > newestMtime(d)) { fs.rmSync(d, { recursive: true, force: true }); copyTree(s, d); stats.updated++; }
@@ -174,6 +356,14 @@ function mergeTree(srcDir, dstDir, stats, rel = "") {
174
356
  }
175
357
  mergeTree(s, d, stats, relPath);
176
358
  } else if (ent.isFile()) {
359
+ if (/^package-versions\/[a-f0-9]{2}$/.test(rel)) {
360
+ const incoming=require('./package-versions').readRecord(s);
361
+ if (!incoming) { stats.skipped.push(relPath + ': invalid package observation'); continue; }
362
+ // Its name includes the body hash: a conflict becomes another file,
363
+ // not a replacement. Preserve valid existing observations on collision.
364
+ if (fs.existsSync(d) && require('./package-versions').readRecord(d)) {stats.kept++;continue;}
365
+ copyPreservingTime(s,d);stats.added++;continue;
366
+ }
177
367
  mergeFile(s, d, relPath, stats);
178
368
  }
179
369
  // symlinks and specials in a cache archive are not ours to reproduce — skipped
@@ -210,35 +400,45 @@ async function runTar(args, archive, cwd, writing, verbose) {
210
400
 
211
401
  async function exportCache(destFile, opts = {}) {
212
402
  const { verbose, includeConfig } = opts;
213
- if (!fs.existsSync(FAD_CACHE_DIR)) throw new Error(`no ~/.vigie-vuln/ directory to export`);
403
+ const sourceDir = opts.sourceDir || FAD_CACHE_DIR;
404
+ const origin = opts.proxyOrigin ? require("./proxy-scope").proxyOrigin(opts.proxyOrigin) : null;
405
+ if (!fs.existsSync(sourceDir)) throw new Error(`no ~/.vigie-vuln/ directory to export`);
214
406
  const abs = path.resolve(destFile);
215
407
  fs.mkdirSync(path.dirname(abs), { recursive: true });
216
408
 
217
- const excludes = includeConfig ? [] : SENSITIVE_FILES.map(f => `${path.basename(FAD_CACHE_DIR)}/${f}`);
409
+ const excludes = includeConfig ? [] : SENSITIVE_FILES.map(f => `${path.basename(sourceDir)}/${f}`);
218
410
  if (excludes.length && verbose) console.log(` excluding (use --include-config to keep): ${excludes.join(", ")}`);
219
411
 
220
412
  const ext = abs.toLowerCase();
413
+ const markerDir = origin ? fs.mkdtempSync(path.join(os.tmpdir(), "vigievuln-archive-")) : null;
414
+ const markerName = ".vigievuln-archive-origin.json";
415
+ if (markerDir) fs.writeFileSync(path.join(markerDir, markerName), JSON.stringify({ version: 1, origin }), { mode: 0o600 });
416
+ try {
221
417
  if (ext.endsWith(".tar.gz") || ext.endsWith(".tgz")) {
222
418
  const args = ["-czf", "-"];
223
419
  for (const e of excludes) args.push(`--exclude=${e}`);
224
- args.push(path.basename(FAD_CACHE_DIR));
225
- await runTar(args, abs, path.dirname(FAD_CACHE_DIR), true, verbose);
420
+ args.push(path.basename(sourceDir));
421
+ if (markerDir) args.push("-C", markerDir, markerName);
422
+ await runTar(args, abs, path.dirname(sourceDir), true, verbose);
226
423
  } else if (ext.endsWith(".zip")) {
227
424
  if (process.platform === "win32") {
228
- if (verbose) console.log(`📦 Compress-Archive -Path ${FAD_CACHE_DIR}\\* -DestinationPath ${abs}`);
425
+ if (origin) throw new Error("Proxy-scoped ZIP export is unavailable on Windows; use tar.gz.");
426
+ if (verbose) console.log(`📦 Compress-Archive -Path ${sourceDir}\\* -DestinationPath ${abs}`);
229
427
  // Powershell Compress-Archive doesn't have a clean exclude flag — manual copy
230
428
  await execFileP("powershell", ["-NoProfile", "-Command",
231
- `$src='${FAD_CACHE_DIR}'; $dst='${abs}'; ${includeConfig ? `Compress-Archive -Path "$src\\*" -DestinationPath $dst -Force` : `$tmp=Join-Path $env:TEMP "vigievuln-stage-$(Get-Random)"; Copy-Item $src $tmp -Recurse; ${SENSITIVE_FILES.map(f => `Remove-Item -Force -ErrorAction SilentlyContinue (Join-Path $tmp '${f}')`).join("; ")}; Compress-Archive -Path "$tmp\\*" -DestinationPath $dst -Force; Remove-Item $tmp -Recurse -Force`}`]);
429
+ `$src='${sourceDir}'; $dst='${abs}'; ${includeConfig ? `Compress-Archive -Path "$src\\*" -DestinationPath $dst -Force` : `$tmp=Join-Path $env:TEMP "vigievuln-stage-$(Get-Random)"; Copy-Item $src $tmp -Recurse; ${SENSITIVE_FILES.map(f => `Remove-Item -Force -ErrorAction SilentlyContinue (Join-Path $tmp '${f}')`).join("; ")}; Compress-Archive -Path "$tmp\\*" -DestinationPath $dst -Force; Remove-Item $tmp -Recurse -Force`}`]);
232
430
  } else {
233
- const args = ["-r", "-q", abs, path.basename(FAD_CACHE_DIR)];
431
+ const args = ["-r", "-q", abs, path.basename(sourceDir)];
234
432
  for (const e of excludes) { args.push("-x"); args.push(e); }
235
433
  if (verbose) console.log(`📦 zip ${args.join(" ")}`);
236
- await execFileP("zip", args, { cwd: path.dirname(FAD_CACHE_DIR), maxBuffer: 1024 * 1024 * 32 });
434
+ await execFileP("zip", args, { cwd: path.dirname(sourceDir), maxBuffer: 1024 * 1024 * 32 });
435
+ if (markerDir) await execFileP("zip", ["-q", abs, markerName], { cwd: markerDir });
237
436
  }
238
437
  } else {
239
438
  throw new Error(`unknown archive extension on ${destFile} (expected .tar.gz, .tgz, or .zip)`);
240
439
  }
241
440
 
441
+ } finally { if (markerDir) fs.rmSync(markerDir, { recursive: true, force: true }); }
242
442
  const size = fs.statSync(abs).size;
243
443
  return { path: abs, size, excluded: excludes };
244
444
  }
@@ -271,6 +471,51 @@ async function extractTo(abs, destParent, verbose) {
271
471
  }
272
472
  }
273
473
 
474
+ // Inspect only tar member names and, when necessary, the legacy Maven index.
475
+ // A server seed containing hundreds of thousands of old NVD files must not be
476
+ // expanded merely to discover its OSV partition is unusable. On ambiguity we
477
+ // fall back to the normal validated import, preserving published 1.1.x caches.
478
+ async function preflightSetupSeed(abs, onProgress) {
479
+ if (!/\.(?:tar\.gz|tgz)$/i.test(abs)) return;
480
+ const found={old:false,native:false,journal:false,details:false,index:null};
481
+ const fd=fs.openSync(abs,'r');
482
+ try {
483
+ await new Promise((resolve,reject)=>{
484
+ const child=spawn('tar',['-tzf','-'],{stdio:[fd,'pipe','pipe']});
485
+ let stderr='', count=0;
486
+ child.stderr.setEncoding('utf8');child.stderr.on('data',chunk=>{stderr=(stderr+chunk).slice(-4096)});
487
+ const lines=require('node:readline').createInterface({input:child.stdout,crlfDelay:Infinity});
488
+ lines.on('line',name=>{
489
+ count++; if(count % 10000===0)onProgress?.({phase:'validating',count});
490
+ const clean=name.replace(/^\.\//,'');
491
+ if (!/^(?:\.vigie-vuln|\.fad-checker)\//.test(clean)) return;
492
+ const rel=clean.slice(clean.indexOf('/')+1);
493
+ if (rel.startsWith('osv-db/records/')) found.old=true;
494
+ if (rel==='advisory-store/seed/osv.jsonl') found.native=true;
495
+ if (rel==='advisory-store/events.jsonl') found.journal=true;
496
+ if (/^osv-cache\/vuln_.+\.json$/.test(rel)) found.details=true;
497
+ if (rel==='osv-db/maven-index.json') found.index=name;
498
+ });
499
+ child.on('error',reject);child.on('close',(code,signal)=>code===0?resolve():reject(new Error(`tar inspection failed (${signal || code}): ${stderr.trim()}`)));
500
+ });
501
+ } finally {fs.closeSync(fd);}
502
+ if ((!found.old && !found.index) || found.native || found.journal || found.details) return;
503
+ let oldIndex = !found.index;
504
+ if (found.index) {
505
+ const source=fs.openSync(abs,'r');
506
+ try {
507
+ const output=await new Promise((resolve,reject)=>{
508
+ const child=spawn('tar',['-xOzf','-',found.index],{stdio:[source,'pipe','pipe']});
509
+ const chunks=[];let size=0, tooLarge=false;
510
+ child.stdout.on('data',chunk=>{size+=chunk.length;if(size>64*1024*1024){tooLarge=true;child.kill();}else chunks.push(chunk)});
511
+ child.stderr.resume();child.on('error',reject);child.on('close',code=>resolve(!tooLarge && code===0?Buffer.concat(chunks).toString('utf8'):null));
512
+ });
513
+ if (output !== null) { try { oldIndex=JSON.parse(output)?._schema === 2; } catch { /* preserve ambiguous archives */ } }
514
+ } finally {fs.closeSync(source);}
515
+ }
516
+ if (oldIndex) throw new Error('This server bundle uses an obsolete OSV seed format and contains no usable OSV advisories. Update the server and regenerate its bundle; setup was not saved.');
517
+ }
518
+
274
519
  /**
275
520
  * Restore ~/.fad-checker/ from an archive.
276
521
  *
@@ -281,16 +526,20 @@ async function extractTo(abs, destParent, verbose) {
281
526
  */
282
527
  async function importCache(srcFile, opts = {}) {
283
528
  const { verbose, force } = opts;
529
+ const targetDir = opts.targetDir || FAD_CACHE_DIR;
284
530
  const replace = !!(opts.replace || force);
285
531
  const abs = path.resolve(srcFile);
286
532
  if (!fs.existsSync(abs)) throw new Error(`archive not found: ${abs}`);
533
+ if (opts.requireUsableSeed) { opts.onProgress?.({phase:'validating'}); await preflightSetupSeed(abs,opts.onProgress); }
287
534
 
288
535
  // Merge: unpack beside the cache (same filesystem), reconcile, drop the staging dir.
289
- fs.mkdirSync(path.dirname(FAD_CACHE_DIR), { recursive: true });
290
- const staging = fs.mkdtempSync(`${FAD_CACHE_DIR}.import-`);
536
+ fs.mkdirSync(path.dirname(targetDir), { recursive: true });
537
+ const staging = fs.mkdtempSync(`${targetDir}.import-`);
291
538
  const stats = { added: 0, updated: 0, merged: 0, kept: 0, skipped: [] };
292
539
  try {
540
+ opts.onProgress?.({phase:'extracting'});
293
541
  await extractTo(abs, staging, verbose);
542
+ opts.onProgress?.({phase:'validating'});
294
543
  // Never promote links or special files into a live cache, including in
295
544
  // replace mode. A later cache write could otherwise escape the cache root.
296
545
  const inspect = dir => {
@@ -302,20 +551,93 @@ async function importCache(srcFile, opts = {}) {
302
551
  }
303
552
  };
304
553
  inspect(staging);
305
- const modern = path.join(staging, path.basename(FAD_CACHE_DIR));
306
- const legacy = path.join(staging, '.fad-checker');
554
+ if (opts.proxyOrigin) {
555
+ const origin = require("./proxy-scope").proxyOrigin(opts.proxyOrigin);
556
+ const marker = readJson(path.join(staging, ".vigievuln-archive-origin.json"));
557
+ if (!marker || marker.version !== 1 || marker.origin !== origin) throw new Error("Archive proxy origin missing or does not match the active proxy scope.");
558
+ }
559
+ const modern = path.join(staging, '.vigie-vuln');
560
+ const legacyDir = path.join(staging, '.fad-checker');
307
561
  // Windows Compress-Archive historically emitted the cache contents at
308
562
  // the ZIP root, whereas tar and Unix ZIP preserve the directory name.
309
563
  const flatWindowsZip = process.platform === 'win32' && abs.toLowerCase().endsWith('.zip');
310
- const incoming = fs.existsSync(modern) ? modern : fs.existsSync(legacy) ? legacy : flatWindowsZip ? staging : legacy;
564
+ const incoming = fs.existsSync(modern) ? modern : fs.existsSync(legacyDir) ? legacyDir : flatWindowsZip ? staging : legacyDir;
311
565
  if (!fs.existsSync(incoming) || !fs.lstatSync(incoming).isDirectory()) {
312
566
  throw new Error(`archive holds no .vigie-vuln/ or .fad-checker/ directory — was it built with vigievuln --export-cache?`);
313
567
  }
568
+ // A corrupt compact NVD generation must not be merged beside valid local
569
+ // observations or cause any other part of this archive to be committed.
570
+ if (fs.existsSync(path.join(incoming,'nvd-cache','_bulk')))
571
+ require('./nvd-bulk').validateAll(path.join(incoming,'nvd-cache'));
572
+ const storeDir = path.join(incoming, 'advisory-store');
573
+ const journal = path.join(storeDir, 'events.jsonl');
574
+ const seedDir = path.join(storeDir, 'seed');
575
+ const hasJournal = fs.existsSync(journal), hasSeedDir = fs.existsSync(seedDir);
576
+ const hasSeed = hasSeedDir && (fs.existsSync(path.join(seedDir,'meta.json')) || fs.existsSync(path.join(seedDir,'osv.jsonl')));
577
+ const hasCveSeed = hasSeedDir && (fs.existsSync(path.join(seedDir,'cveproject-meta.json')) || fs.existsSync(path.join(seedDir,'cveproject.jsonl')));
578
+ if (fs.existsSync(storeDir) && !hasJournal && !hasSeed && !hasCveSeed) throw new Error('archive advisory store has no journal or native seed');
579
+ let usableJournalOsv = false;
580
+ if (hasJournal) for (const item of require('./advisory-store').journalTransactions(journal)) {
581
+ if (item.transaction.records.some(r => r.source === 'osv' && !r.document.withdrawn && r.document.affected?.some(a => a.package?.ecosystem && a.package?.name))) usableJournalOsv = true;
582
+ }
583
+ const seed = hasSeed ? readNativeSeed(seedDir) : null;
584
+ const cveSeed = hasCveSeed ? readCveSeed(seedDir) : null;
585
+ const gcveDir = path.join(incoming,'gcve-data');
586
+ const gcve = fs.existsSync(gcveDir) && gcveSeedInfo(gcveDir) ? require('./gcve-index').readGcveIndex(path.join(gcveDir,'index.json')) : null;
587
+ const legacyFile = path.join(incoming,'osv-db','maven-index.json');
588
+ let legacy = null;
589
+ if (fs.existsSync(legacyFile)) {
590
+ try { legacy = readLegacyMavenIndex(legacyFile); } catch { /* warn below */ }
591
+ if (!legacy && !seed) stats.skipped.push('osv-db/maven-index.json: unrecognized or experimental index; no legacy advisories imported');
592
+ else if (legacy) stats.skipped.push(`Maven OSV legacy index is partial and cannot verify withdrawn advisories${legacy.conflicting ? `; ${legacy.conflicting} conflicting advisory IDs skipped` : ''}`);
593
+ }
594
+ // An unpublished, partitioned 1.2 seed cannot be interpreted by the
595
+ // native store. Fail setup before modifying the destination if the bundle
596
+ // otherwise contains no usable OSV advisories. Ordinary cache imports still
597
+ // salvage their compatible entries and report the skipped old partition.
598
+ const obsoleteOsv = opts.requireUsableSeed && (fs.existsSync(path.join(incoming,'osv-db','records')) || readJson(legacyFile)?._schema === 2);
599
+ if (opts.requireUsableSeed && obsoleteOsv &&
600
+ !(seed?.meta.recordCount > 0) && !usableJournalOsv && !(legacy?.documents?.length > 0)) {
601
+ let usableDetails = false;
602
+ const dir = path.join(incoming,'osv-cache');
603
+ if (fs.existsSync(dir)) for (const name of fs.readdirSync(dir)) {
604
+ if (!/^vuln_.+\.json$/.test(name)) continue;
605
+ try {
606
+ const file=path.join(dir,name), st=fs.lstatSync(file);
607
+ if (!st.isFile() || st.isSymbolicLink() || st.size>16*1024*1024) continue;
608
+ const cached=JSON.parse(fs.readFileSync(file,'utf8'));
609
+ require('./advisory-store').validateRecord({source:'osv',document:cached.body,fetchedAt:cached._fetchedAt});
610
+ if (!cached.body.withdrawn && cached.body.affected?.some(a=>a.package?.ecosystem && a.package?.name)) { usableDetails=true; break; }
611
+ } catch { /* malformed historical entry */ }
612
+ }
613
+ if (!usableDetails) throw new Error('This server bundle uses an obsolete OSV seed format and contains no usable OSV advisories. Update the server and regenerate its bundle; setup was not saved.');
614
+ }
615
+
616
+ // Validate seed completely in a temporary store before any target mutation.
617
+ const prepared = path.join(staging, 'prepared-store');
618
+ if (hasSeed || hasCveSeed || legacy || gcve || (replace && hasJournal)) {
619
+ const store = require('./advisory-store').openAdvisoryStore({cacheDir:prepared});
620
+ if (seed) { opts.onProgress?.({phase:'index-osv',count:0,total:seed.meta.recordCount}); await store.importRecords(nativeSeedRecords(seed,opts.onProgress), {source:'osv', fetchedAt:seed.meta._builtAt, provenance:{transport:'seed'}, coverages:seed.meta.ecosystems.map(ecosystem => ({source:'osv', ecosystem, fetchedAt:seed.meta._builtAt, complete:true, provenance:{transport:'seed'}, sha256:seed.meta.sha256, recordCount:seed.meta.recordCount}))}); }
621
+ if (cveSeed) { opts.onProgress?.({phase:'index-cve',count:0,total:cveSeed.meta.recordCount}); await store.importEnvelopes(cveSeedEnvelopes(cveSeed,opts.onProgress),{coverages:[{source:'cveproject',ecosystem:'*',fetchedAt:cveSeed.meta._builtAt,complete:false,provenance:{transport:'seed'}}]}); }
622
+ if (legacy) await importLegacyMavenIndex(prepared, legacyFile);
623
+ if (gcve) { opts.onProgress?.({phase:'index-gcve'}); await require('./native-advisories').importGcveIndex(store,gcve,{provenance:{transport:'seed'}}); }
624
+ if (hasJournal) store.mergeJournal(journal);
625
+ if (!fs.existsSync(store.journal)) fs.writeFileSync(store.journal, '', {mode:0o600});
626
+ }
627
+ if (replace) {
628
+ if (fs.existsSync(path.join(incoming, 'osv-db', 'records'))) {
629
+ stats.skipped.push('osv-db/records: obsolete partitioned OSV seed cannot be imported; obtain a current bundle');
630
+ fs.rmSync(path.join(incoming, 'osv-db', 'records'), {recursive:true,force:true});
631
+ }
632
+ fs.rmSync(storeDir, {recursive:true, force:true});
633
+ if (hasSeed || hasCveSeed || hasJournal || legacy || gcve) fs.renameSync(path.join(prepared, 'advisory-store'), storeDir);
634
+ }
635
+ const containsLegacyOsv = fs.existsSync(path.join(incoming,'osv-cache'));
314
636
  if (replace) {
315
637
  // Configuration contains machine-local credentials and is never
316
638
  // accepted from an imported archive, even for a replacement.
317
639
  for (const name of NEVER_IMPORT) {
318
- const src = path.join(FAD_CACHE_DIR, name), dst = path.join(incoming, name);
640
+ const src = path.join(targetDir, name), dst = path.join(incoming, name);
319
641
  fs.rmSync(dst, { force: true });
320
642
  if (fs.existsSync(src)) {
321
643
  const st = fs.lstatSync(src);
@@ -324,22 +646,31 @@ async function importCache(srcFile, opts = {}) {
324
646
  try { fs.chmodSync(dst, 0o600); } catch { /* platform does not support chmod */ }
325
647
  }
326
648
  }
327
- if (fs.existsSync(FAD_CACHE_DIR) && !force) {
328
- const backup = `${FAD_CACHE_DIR}.bak-${Date.now()}`;
329
- fs.renameSync(FAD_CACHE_DIR, backup);
649
+ if (fs.existsSync(targetDir) && !force) {
650
+ const backup = `${targetDir}.bak-${Date.now()}`;
651
+ fs.renameSync(targetDir, backup);
330
652
  if (verbose) console.log(`💾 existing ~/.vigie-vuln/ moved to ${backup}`);
331
- } else if (force && fs.existsSync(FAD_CACHE_DIR)) {
332
- fs.rmSync(FAD_CACHE_DIR, {recursive:true, force:true});
653
+ } else if (force && fs.existsSync(targetDir)) {
654
+ fs.rmSync(targetDir, {recursive:true, force:true});
333
655
  }
334
- fs.renameSync(incoming, FAD_CACHE_DIR);
335
- return {dir:FAD_CACHE_DIR, mode:'replace'};
656
+ fs.renameSync(incoming, targetDir);
657
+ if (containsLegacyOsv) require('./osv-legacy').importLegacyOsvDetails(require('./advisory-store').openAdvisoryStore({cacheDir:targetDir}),{cacheDir:targetDir,force:true});
658
+ return {dir:targetDir, mode:'replace', stats};
659
+ }
660
+ fs.mkdirSync(targetDir, { recursive: true });
661
+ opts.onProgress?.({phase:'merging'});
662
+ if (hasSeed || hasCveSeed || hasJournal || legacy || gcve) {
663
+ const store = require('./advisory-store').openAdvisoryStore({cacheDir:targetDir});
664
+ if (hasSeed || hasCveSeed || legacy || gcve) store.mergeJournal(path.join(prepared,'advisory-store','events.jsonl'));
665
+ else store.mergeJournal(journal);
666
+ stats.merged++;
336
667
  }
337
- fs.mkdirSync(FAD_CACHE_DIR, { recursive: true });
338
- mergeTree(incoming, FAD_CACHE_DIR, stats);
668
+ mergeTree(incoming, targetDir, stats);
669
+ if (containsLegacyOsv) require('./osv-legacy').importLegacyOsvDetails(require('./advisory-store').openAdvisoryStore({cacheDir:targetDir}),{cacheDir:targetDir,force:true});
339
670
  } finally {
340
671
  fs.rmSync(staging, { recursive: true, force: true });
341
672
  }
342
- return { dir: FAD_CACHE_DIR, mode: "merge", stats };
673
+ return { dir: targetDir, mode: "merge", stats };
343
674
  }
344
675
 
345
- module.exports = { exportCache, importCache, FAD_CACHE_DIR, mergeResourceStore };
676
+ module.exports = { exportCache, importCache, FAD_CACHE_DIR, mergeResourceStore, readLegacyMavenIndex, importLegacyMavenIndex };
@@ -0,0 +1,142 @@
1
+ 'use strict';
2
+
3
+ const path = require('node:path');
4
+ const crypto = require('node:crypto');
5
+ const {openSqlite} = require('./sqlite-driver');
6
+ const {DICTIONARY} = require('./compression-dictionary');
7
+
8
+ const APPLICATION_ID = 1448502092;
9
+ const SCHEMA_VERSION = 2;
10
+ const DICTIONARY_SHA256 = crypto.createHash('sha256').update(DICTIONARY).digest('hex');
11
+ const SCHEMA = `
12
+ PRAGMA application_id=${APPLICATION_ID};
13
+ PRAGMA user_version=${SCHEMA_VERSION};
14
+ CREATE TABLE cache_meta (key TEXT PRIMARY KEY, value TEXT NOT NULL) WITHOUT ROWID;
15
+ CREATE TABLE advisory_records (
16
+ source TEXT NOT NULL, id TEXT NOT NULL, revision_ms INTEGER NOT NULL,
17
+ withdrawn INTEGER NOT NULL CHECK(withdrawn IN (0,1)), fetched_at INTEGER NOT NULL CHECK(fetched_at>0),
18
+ content_changed_at INTEGER NOT NULL CHECK(content_changed_at>0),
19
+ document_sha256 TEXT NOT NULL CHECK(length(document_sha256)=64),
20
+ envelope_deflate BLOB NOT NULL, envelope_bytes INTEGER NOT NULL CHECK(envelope_bytes BETWEEN 1 AND 16777216),
21
+ PRIMARY KEY(source,id)
22
+ ) WITHOUT ROWID;
23
+ CREATE TABLE advisory_packages (
24
+ ecosystem TEXT NOT NULL, name_key TEXT NOT NULL, source TEXT NOT NULL, id TEXT NOT NULL,
25
+ PRIMARY KEY(ecosystem,name_key,source,id),
26
+ FOREIGN KEY(source,id) REFERENCES advisory_records(source,id) ON DELETE CASCADE
27
+ ) WITHOUT ROWID;
28
+ CREATE INDEX advisory_packages_record ON advisory_packages(source,id);
29
+ CREATE TABLE advisory_observations (
30
+ source TEXT NOT NULL, id TEXT NOT NULL, provenance_key TEXT NOT NULL,
31
+ fetched_at INTEGER NOT NULL CHECK(fetched_at>0), provenance_json TEXT NOT NULL CHECK(json_valid(provenance_json)),
32
+ PRIMARY KEY(source,id,provenance_key),
33
+ FOREIGN KEY(source,id) REFERENCES advisory_records(source,id) ON DELETE CASCADE
34
+ ) WITHOUT ROWID;
35
+ CREATE TABLE advisory_queries (
36
+ source TEXT NOT NULL, ecosystem TEXT NOT NULL, name_key TEXT NOT NULL, version TEXT NOT NULL,
37
+ original_name TEXT NOT NULL, fetched_at INTEGER NOT NULL CHECK(fetched_at>0),
38
+ stale INTEGER NOT NULL CHECK(stale IN (0,1)), provenance_json TEXT NOT NULL CHECK(json_valid(provenance_json)),
39
+ PRIMARY KEY(source,ecosystem,name_key,version)
40
+ ) WITHOUT ROWID;
41
+ CREATE INDEX advisory_queries_summary ON advisory_queries(source,fetched_at,stale);
42
+ CREATE TABLE advisory_query_ids (
43
+ source TEXT NOT NULL, ecosystem TEXT NOT NULL, name_key TEXT NOT NULL, version TEXT NOT NULL,
44
+ id TEXT NOT NULL, ordinal INTEGER NOT NULL CHECK(ordinal>=0), document_sha256 TEXT,
45
+ PRIMARY KEY(source,ecosystem,name_key,version,id),
46
+ FOREIGN KEY(source,ecosystem,name_key,version) REFERENCES advisory_queries(source,ecosystem,name_key,version) ON DELETE CASCADE,
47
+ FOREIGN KEY(source,id) REFERENCES advisory_records(source,id)
48
+ ) WITHOUT ROWID;
49
+ CREATE INDEX advisory_query_ids_record ON advisory_query_ids(source,id);
50
+ CREATE TABLE advisory_coverage (
51
+ source TEXT NOT NULL, ecosystem TEXT NOT NULL, slot TEXT NOT NULL CHECK(slot IN ('current','last_complete')),
52
+ fetched_at INTEGER NOT NULL CHECK(fetched_at>0), complete INTEGER NOT NULL CHECK(complete IN (0,1)),
53
+ stale INTEGER NOT NULL CHECK(stale IN (0,1)), entry_json TEXT NOT NULL CHECK(json_valid(entry_json)),
54
+ PRIMARY KEY(source,ecosystem,slot), CHECK(slot<>'last_complete' OR complete=1)
55
+ ) WITHOUT ROWID;
56
+ CREATE TABLE cache_entries (
57
+ namespace TEXT NOT NULL, key TEXT NOT NULL, fetched_at INTEGER NOT NULL CHECK(fetched_at>=0),
58
+ expires_at INTEGER, stale INTEGER NOT NULL DEFAULT 0 CHECK(stale IN (0,1)),
59
+ encoding TEXT NOT NULL CHECK(encoding IN ('json','text','binary','json+deflate','text+deflate','binary+deflate')), payload BLOB NOT NULL,
60
+ metadata_json TEXT NOT NULL CHECK(json_valid(metadata_json)), PRIMARY KEY(namespace,key)
61
+ ) WITHOUT ROWID;
62
+ CREATE INDEX cache_entries_expiry ON cache_entries(namespace,expires_at);
63
+ CREATE TABLE cache_snapshots (
64
+ namespace TEXT PRIMARY KEY, fetched_at INTEGER NOT NULL, complete INTEGER NOT NULL CHECK(complete IN (0,1)),
65
+ stale INTEGER NOT NULL CHECK(stale IN (0,1)), record_count INTEGER NOT NULL CHECK(record_count>=0),
66
+ metadata_json TEXT NOT NULL CHECK(json_valid(metadata_json))
67
+ ) WITHOUT ROWID;
68
+ CREATE TABLE nvd_records (
69
+ cve TEXT NOT NULL, kind TEXT NOT NULL CHECK(kind IN ('live','bulk')),
70
+ fetched_at INTEGER NOT NULL CHECK(fetched_at>0), revision_ms INTEGER,
71
+ body_deflate BLOB NOT NULL, body_bytes INTEGER NOT NULL CHECK(body_bytes BETWEEN 1 AND 16777216),
72
+ metadata_json TEXT NOT NULL CHECK(json_valid(metadata_json)),
73
+ PRIMARY KEY(cve,kind)
74
+ ) WITHOUT ROWID;
75
+ CREATE TABLE package_versions (
76
+ origin TEXT NOT NULL, ecosystem TEXT NOT NULL, name TEXT NOT NULL, version TEXT NOT NULL,
77
+ sha256 TEXT NOT NULL CHECK(length(sha256)=64), collected_at INTEGER NOT NULL CHECK(collected_at>0),
78
+ source_url TEXT NOT NULL, format TEXT NOT NULL, body BLOB NOT NULL,
79
+ PRIMARY KEY(origin,ecosystem,name,version,sha256)
80
+ ) WITHOUT ROWID;
81
+ CREATE TABLE cve_lookup (
82
+ kind TEXT NOT NULL CHECK(kind IN ('package','product')), lookup_key TEXT NOT NULL,
83
+ source TEXT NOT NULL, cve TEXT NOT NULL, affected_key TEXT NOT NULL,
84
+ projection_json TEXT NOT NULL CHECK(json_valid(projection_json)),
85
+ PRIMARY KEY(kind,lookup_key,source,cve,affected_key)
86
+ ) WITHOUT ROWID;
87
+ CREATE INDEX cve_lookup_record ON cve_lookup(source,cve);
88
+ CREATE TABLE resource_bodies (
89
+ body_id TEXT PRIMARY KEY, bytes INTEGER NOT NULL CHECK(bytes>=0), sha256 TEXT NOT NULL CHECK(length(sha256)=64)
90
+ ) WITHOUT ROWID;
91
+ CREATE TABLE resource_chunks (
92
+ body_id TEXT NOT NULL, ordinal INTEGER NOT NULL CHECK(ordinal>=0), data BLOB NOT NULL,
93
+ PRIMARY KEY(body_id,ordinal), FOREIGN KEY(body_id) REFERENCES resource_bodies(body_id) ON DELETE CASCADE
94
+ ) WITHOUT ROWID;
95
+ CREATE TABLE resources (
96
+ key TEXT PRIMARY KEY, body_id TEXT NOT NULL, fetched_at INTEGER NOT NULL CHECK(fetched_at>0),
97
+ ttl_ms INTEGER NOT NULL CHECK(ttl_ms>=0), content_type TEXT,
98
+ response_headers_json TEXT NOT NULL CHECK(json_valid(response_headers_json)),
99
+ metadata_json TEXT NOT NULL CHECK(json_valid(metadata_json)),
100
+ FOREIGN KEY(body_id) REFERENCES resource_bodies(body_id)
101
+ ) WITHOUT ROWID;
102
+ CREATE INDEX resources_eviction ON resources(fetched_at);
103
+ CREATE INDEX resources_body ON resources(body_id);
104
+ `;
105
+
106
+ function openCacheDb({cacheDir, readonly=false}={}) {
107
+ if (!cacheDir) throw new Error('cacheDir is required');
108
+ const file=path.join(cacheDir,'cache.sqlite');
109
+ const db=openSqlite(file,{readonly});
110
+ try {
111
+ if(!readonly){
112
+ db.exec('BEGIN IMMEDIATE');
113
+ try{
114
+ const id=db.prepare('PRAGMA application_id').get().application_id;
115
+ const version=db.prepare('PRAGMA user_version').get().user_version;
116
+ if(id===0&&version===0){
117
+ db.exec(SCHEMA);
118
+ db.prepare('INSERT INTO cache_meta(key,value) VALUES (?,?)').run('compression_dictionary_sha256',DICTIONARY_SHA256);
119
+ }else if(id!==APPLICATION_ID||version!==SCHEMA_VERSION)throw new Error('unsupported VigieVuln SQLite cache schema');
120
+ db.exec('COMMIT');
121
+ }catch(error){try{db.exec('ROLLBACK')}catch{}throw error}
122
+ }else{
123
+ const id=db.prepare('PRAGMA application_id').get().application_id;
124
+ const version=db.prepare('PRAGMA user_version').get().user_version;
125
+ if(id!==APPLICATION_ID||version!==SCHEMA_VERSION)throw new Error('unsupported VigieVuln SQLite cache schema');
126
+ }
127
+ if(db.prepare('SELECT value FROM cache_meta WHERE key=?').get('compression_dictionary_sha256')?.value!==DICTIONARY_SHA256)
128
+ throw new Error('unsupported VigieVuln cache compression dictionary');
129
+ return db;
130
+ } catch (error) {db.close();throw error}
131
+ }
132
+
133
+ const shared=new Map();
134
+ function getCacheDb(cacheDir=require('./cache-directory').getCacheDir()){
135
+ const key=path.resolve(cacheDir);
136
+ let db=shared.get(key);
137
+ if(!db){db=openCacheDb({cacheDir:key});shared.set(key,db)}
138
+ return db;
139
+ }
140
+ function closeCacheDbs(){for(const db of shared.values())db.close();shared.clear()}
141
+
142
+ module.exports={openCacheDb,getCacheDb,closeCacheDbs,APPLICATION_ID,SCHEMA_VERSION,SCHEMA,DICTIONARY_SHA256};