vigievuln 1.1.3 → 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 (102) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/README.md +47 -124
  3. package/completions/vigievuln.bash +1 -1
  4. package/completions/vigievuln.zsh +1 -0
  5. package/lib/advisory-compression.js +25 -0
  6. package/lib/advisory-fixes.js +21 -0
  7. package/lib/advisory-store-sqlite.js +156 -0
  8. package/lib/advisory-store.js +484 -0
  9. package/lib/airgap-project.js +117 -0
  10. package/lib/application-plugins/runner.js +22 -13
  11. package/lib/application-plugins/wordpress.js +4 -3
  12. package/lib/application-providers/live-snapshot.js +1 -12
  13. package/lib/application-providers/snapshot-cache.js +27 -0
  14. package/lib/application-providers/wordfence-client.js +3 -3
  15. package/lib/attribution.js +2 -2
  16. package/lib/cache-archive-sqlite.js +215 -0
  17. package/lib/cache-archive.js +350 -26
  18. package/lib/cache-db.js +142 -0
  19. package/lib/cache-directory.js +18 -74
  20. package/lib/cache-policy.js +25 -0
  21. package/lib/cache-repository.js +48 -0
  22. package/lib/cache-startup.js +54 -0
  23. package/lib/certfr.js +9 -9
  24. package/lib/cli-command-routing.js +29 -6
  25. package/lib/cli-groups.js +32 -3
  26. package/lib/cli-project-commands.js +26 -5
  27. package/lib/cli-setup.js +300 -0
  28. package/lib/codecs/binary/pe-metadata.js +79 -0
  29. package/lib/codecs/binary/scan.js +4 -3
  30. package/lib/codecs/binary.codec.js +4 -2
  31. package/lib/codecs/composer/registry.js +8 -6
  32. package/lib/codecs/go/parse.js +7 -9
  33. package/lib/codecs/go/registry.js +7 -5
  34. package/lib/codecs/go.codec.js +5 -0
  35. package/lib/codecs/maven.codec.js +72 -7
  36. package/lib/codecs/npm/collect.js +12 -5
  37. package/lib/codecs/npm/parse.js +12 -5
  38. package/lib/codecs/npm/registry.js +40 -11
  39. package/lib/codecs/nuget/registry.js +8 -6
  40. package/lib/codecs/pypi/registry.js +8 -6
  41. package/lib/codecs/ruby/registry.js +7 -5
  42. package/lib/compression-dictionary.js +5 -0
  43. package/lib/coverage-diagnostics.js +26 -0
  44. package/lib/cve-download.js +157 -41
  45. package/lib/cve-legacy-ranges.js +59 -0
  46. package/lib/cve-match.js +82 -13
  47. package/lib/cve-npm-proxy.js +29 -0
  48. package/lib/cve-report.js +142 -55
  49. package/lib/cve-version-verdict.js +77 -0
  50. package/lib/deps-descriptor.js +8 -3
  51. package/lib/epss.js +13 -8
  52. package/lib/euvd.js +32 -8
  53. package/lib/gcve-feed.js +103 -0
  54. package/lib/gcve-index.js +181 -0
  55. package/lib/gcve.js +1 -1
  56. package/lib/github-publisher-maven.js +40 -0
  57. package/lib/hash-id.js +5 -5
  58. package/lib/i18n.js +31 -8
  59. package/lib/json-cache.js +18 -0
  60. package/lib/json-export.js +16 -2
  61. package/lib/kev.js +7 -8
  62. package/lib/line-stream.js +23 -0
  63. package/lib/maven-airgap.js +80 -0
  64. package/lib/maven-cache.js +21 -0
  65. package/lib/maven-license.js +2 -1
  66. package/lib/maven-presence.js +2 -2
  67. package/lib/maven-reactor.js +23 -14
  68. package/lib/merge-sources.js +25 -18
  69. package/lib/native-advisories.js +268 -0
  70. package/lib/nvd-bulk.js +145 -0
  71. package/lib/nvd-package-ranges.js +109 -0
  72. package/lib/nvd.js +42 -16
  73. package/lib/osv-db.js +253 -59
  74. package/lib/osv-legacy.js +57 -0
  75. package/lib/osv.js +241 -170
  76. package/lib/outdated.js +11 -12
  77. package/lib/package-metadata.js +141 -0
  78. package/lib/package-versions.js +52 -0
  79. package/lib/packagist-audit.js +6 -6
  80. package/lib/provenance.js +73 -19
  81. package/lib/providers/common.js +11 -1
  82. package/lib/providers/gcve.js +17 -0
  83. package/lib/providers/github.js +1 -0
  84. package/lib/providers/index.js +33 -19
  85. package/lib/providers/vigievuln.js +7 -0
  86. package/lib/proxy-cache.js +1 -1
  87. package/lib/proxy-scope.js +59 -0
  88. package/lib/resource-cache/engine.js +25 -5
  89. package/lib/resource-cache/sqlite-store.js +95 -0
  90. package/lib/resource-cache/validate.js +5 -0
  91. package/lib/retire.js +24 -24
  92. package/lib/ruby-version.js +36 -0
  93. package/lib/sarif-export.js +1 -1
  94. package/lib/sbom-export.js +11 -7
  95. package/lib/snyk.js +32 -20
  96. package/lib/source-profile.js +67 -0
  97. package/lib/sqlite-driver.js +46 -0
  98. package/lib/transitive.js +69 -34
  99. package/lib/unmanaged.js +2 -1
  100. package/lib/vigievuln-advisories.js +47 -0
  101. package/package.json +7 -6
  102. package/vigievuln.js +358 -104
@@ -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,6 +125,69 @@ 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);
@@ -144,6 +207,31 @@ function mergeFile(srcFile, dstFile, rel, stats) {
144
207
  else stats.kept++;
145
208
  }
146
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
+
147
235
  function mergeResourceStore(srcDir, dstDir, stats) {
148
236
  const { createCacheStore } = require("./proxy-cache");
149
237
  const incoming = createCacheStore(srcDir), target = createCacheStore(dstDir);
@@ -165,6 +253,89 @@ function mergeResourceStore(srcDir, dstDir, stats) {
165
253
  }
166
254
  }
167
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
+
168
339
  function mergeTree(srcDir, dstDir, stats, rel = "") {
169
340
  fs.mkdirSync(dstDir, { recursive: true });
170
341
  for (const ent of fs.readdirSync(srcDir, { withFileTypes: true })) {
@@ -172,7 +343,11 @@ function mergeTree(srcDir, dstDir, stats, rel = "") {
172
343
  const s = path.join(srcDir, ent.name), d = path.join(dstDir, ent.name);
173
344
  if (NEVER_IMPORT.includes(relPath)) { stats.skipped.push(relPath); continue; }
174
345
  if (ent.isDirectory()) {
346
+ if (relPath === "advisory-store") continue; // journal is merged separately; indexes are derived
175
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; }
176
351
  if (ATOMIC_DIRS.includes(relPath)) {
177
352
  if (!fs.existsSync(d)) { copyTree(s, d); stats.added++; }
178
353
  else if (newestMtime(s) > newestMtime(d)) { fs.rmSync(d, { recursive: true, force: true }); copyTree(s, d); stats.updated++; }
@@ -181,6 +356,14 @@ function mergeTree(srcDir, dstDir, stats, rel = "") {
181
356
  }
182
357
  mergeTree(s, d, stats, relPath);
183
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
+ }
184
367
  mergeFile(s, d, relPath, stats);
185
368
  }
186
369
  // symlinks and specials in a cache archive are not ours to reproduce — skipped
@@ -217,35 +400,45 @@ async function runTar(args, archive, cwd, writing, verbose) {
217
400
 
218
401
  async function exportCache(destFile, opts = {}) {
219
402
  const { verbose, includeConfig } = opts;
220
- 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`);
221
406
  const abs = path.resolve(destFile);
222
407
  fs.mkdirSync(path.dirname(abs), { recursive: true });
223
408
 
224
- 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}`);
225
410
  if (excludes.length && verbose) console.log(` excluding (use --include-config to keep): ${excludes.join(", ")}`);
226
411
 
227
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 {
228
417
  if (ext.endsWith(".tar.gz") || ext.endsWith(".tgz")) {
229
418
  const args = ["-czf", "-"];
230
419
  for (const e of excludes) args.push(`--exclude=${e}`);
231
- args.push(path.basename(FAD_CACHE_DIR));
232
- 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);
233
423
  } else if (ext.endsWith(".zip")) {
234
424
  if (process.platform === "win32") {
235
- 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}`);
236
427
  // Powershell Compress-Archive doesn't have a clean exclude flag — manual copy
237
428
  await execFileP("powershell", ["-NoProfile", "-Command",
238
- `$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`}`]);
239
430
  } else {
240
- const args = ["-r", "-q", abs, path.basename(FAD_CACHE_DIR)];
431
+ const args = ["-r", "-q", abs, path.basename(sourceDir)];
241
432
  for (const e of excludes) { args.push("-x"); args.push(e); }
242
433
  if (verbose) console.log(`📦 zip ${args.join(" ")}`);
243
- 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 });
244
436
  }
245
437
  } else {
246
438
  throw new Error(`unknown archive extension on ${destFile} (expected .tar.gz, .tgz, or .zip)`);
247
439
  }
248
440
 
441
+ } finally { if (markerDir) fs.rmSync(markerDir, { recursive: true, force: true }); }
249
442
  const size = fs.statSync(abs).size;
250
443
  return { path: abs, size, excluded: excludes };
251
444
  }
@@ -278,6 +471,51 @@ async function extractTo(abs, destParent, verbose) {
278
471
  }
279
472
  }
280
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
+
281
519
  /**
282
520
  * Restore ~/.fad-checker/ from an archive.
283
521
  *
@@ -288,16 +526,20 @@ async function extractTo(abs, destParent, verbose) {
288
526
  */
289
527
  async function importCache(srcFile, opts = {}) {
290
528
  const { verbose, force } = opts;
529
+ const targetDir = opts.targetDir || FAD_CACHE_DIR;
291
530
  const replace = !!(opts.replace || force);
292
531
  const abs = path.resolve(srcFile);
293
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); }
294
534
 
295
535
  // Merge: unpack beside the cache (same filesystem), reconcile, drop the staging dir.
296
- fs.mkdirSync(path.dirname(FAD_CACHE_DIR), { recursive: true });
297
- const staging = fs.mkdtempSync(`${FAD_CACHE_DIR}.import-`);
536
+ fs.mkdirSync(path.dirname(targetDir), { recursive: true });
537
+ const staging = fs.mkdtempSync(`${targetDir}.import-`);
298
538
  const stats = { added: 0, updated: 0, merged: 0, kept: 0, skipped: [] };
299
539
  try {
540
+ opts.onProgress?.({phase:'extracting'});
300
541
  await extractTo(abs, staging, verbose);
542
+ opts.onProgress?.({phase:'validating'});
301
543
  // Never promote links or special files into a live cache, including in
302
544
  // replace mode. A later cache write could otherwise escape the cache root.
303
545
  const inspect = dir => {
@@ -309,20 +551,93 @@ async function importCache(srcFile, opts = {}) {
309
551
  }
310
552
  };
311
553
  inspect(staging);
312
- const modern = path.join(staging, path.basename(FAD_CACHE_DIR));
313
- 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');
314
561
  // Windows Compress-Archive historically emitted the cache contents at
315
562
  // the ZIP root, whereas tar and Unix ZIP preserve the directory name.
316
563
  const flatWindowsZip = process.platform === 'win32' && abs.toLowerCase().endsWith('.zip');
317
- 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;
318
565
  if (!fs.existsSync(incoming) || !fs.lstatSync(incoming).isDirectory()) {
319
566
  throw new Error(`archive holds no .vigie-vuln/ or .fad-checker/ directory — was it built with vigievuln --export-cache?`);
320
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'));
321
636
  if (replace) {
322
637
  // Configuration contains machine-local credentials and is never
323
638
  // accepted from an imported archive, even for a replacement.
324
639
  for (const name of NEVER_IMPORT) {
325
- 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);
326
641
  fs.rmSync(dst, { force: true });
327
642
  if (fs.existsSync(src)) {
328
643
  const st = fs.lstatSync(src);
@@ -331,22 +646,31 @@ async function importCache(srcFile, opts = {}) {
331
646
  try { fs.chmodSync(dst, 0o600); } catch { /* platform does not support chmod */ }
332
647
  }
333
648
  }
334
- if (fs.existsSync(FAD_CACHE_DIR) && !force) {
335
- const backup = `${FAD_CACHE_DIR}.bak-${Date.now()}`;
336
- fs.renameSync(FAD_CACHE_DIR, backup);
649
+ if (fs.existsSync(targetDir) && !force) {
650
+ const backup = `${targetDir}.bak-${Date.now()}`;
651
+ fs.renameSync(targetDir, backup);
337
652
  if (verbose) console.log(`💾 existing ~/.vigie-vuln/ moved to ${backup}`);
338
- } else if (force && fs.existsSync(FAD_CACHE_DIR)) {
339
- fs.rmSync(FAD_CACHE_DIR, {recursive:true, force:true});
653
+ } else if (force && fs.existsSync(targetDir)) {
654
+ fs.rmSync(targetDir, {recursive:true, force:true});
340
655
  }
341
- fs.renameSync(incoming, FAD_CACHE_DIR);
342
- 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++;
343
667
  }
344
- fs.mkdirSync(FAD_CACHE_DIR, { recursive: true });
345
- 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});
346
670
  } finally {
347
671
  fs.rmSync(staging, { recursive: true, force: true });
348
672
  }
349
- return { dir: FAD_CACHE_DIR, mode: "merge", stats };
673
+ return { dir: targetDir, mode: "merge", stats };
350
674
  }
351
675
 
352
- 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};