vigievuln 1.1.2 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (107) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/README.md +51 -141
  3. package/completions/vigievuln.bash +1 -1
  4. package/completions/vigievuln.zsh +1 -0
  5. package/lib/account-client.js +21 -14
  6. package/lib/account-session.js +6 -2
  7. package/lib/advisory-compression.js +25 -0
  8. package/lib/advisory-fixes.js +21 -0
  9. package/lib/advisory-store-sqlite.js +156 -0
  10. package/lib/advisory-store.js +484 -0
  11. package/lib/airgap-project.js +117 -0
  12. package/lib/application-plugins/runner.js +22 -13
  13. package/lib/application-plugins/wordpress.js +4 -3
  14. package/lib/application-providers/live-snapshot.js +1 -12
  15. package/lib/application-providers/snapshot-cache.js +27 -0
  16. package/lib/application-providers/wordfence-client.js +3 -3
  17. package/lib/attribution.js +2 -2
  18. package/lib/cache-archive-sqlite.js +215 -0
  19. package/lib/cache-archive.js +357 -26
  20. package/lib/cache-db.js +142 -0
  21. package/lib/cache-directory.js +18 -74
  22. package/lib/cache-policy.js +25 -0
  23. package/lib/cache-repository.js +48 -0
  24. package/lib/cache-startup.js +54 -0
  25. package/lib/certfr.js +9 -9
  26. package/lib/cli-command-routing.js +29 -6
  27. package/lib/cli-groups.js +32 -3
  28. package/lib/cli-project-commands.js +47 -6
  29. package/lib/cli-setup.js +300 -0
  30. package/lib/codecs/binary/pe-metadata.js +79 -0
  31. package/lib/codecs/binary/scan.js +4 -3
  32. package/lib/codecs/binary.codec.js +4 -2
  33. package/lib/codecs/composer/registry.js +8 -6
  34. package/lib/codecs/go/parse.js +7 -9
  35. package/lib/codecs/go/registry.js +7 -5
  36. package/lib/codecs/go.codec.js +5 -0
  37. package/lib/codecs/maven.codec.js +73 -8
  38. package/lib/codecs/npm/collect.js +12 -5
  39. package/lib/codecs/npm/parse.js +12 -5
  40. package/lib/codecs/npm/registry.js +42 -12
  41. package/lib/codecs/nuget/registry.js +8 -6
  42. package/lib/codecs/pypi/registry.js +8 -6
  43. package/lib/codecs/ruby/registry.js +7 -5
  44. package/lib/compression-dictionary.js +5 -0
  45. package/lib/coverage-diagnostics.js +26 -0
  46. package/lib/cve-download.js +157 -41
  47. package/lib/cve-legacy-ranges.js +59 -0
  48. package/lib/cve-match.js +85 -17
  49. package/lib/cve-npm-proxy.js +29 -0
  50. package/lib/cve-report.js +145 -58
  51. package/lib/cve-version-verdict.js +77 -0
  52. package/lib/deps-descriptor.js +8 -3
  53. package/lib/epss.js +13 -8
  54. package/lib/euvd.js +32 -8
  55. package/lib/gcve-feed.js +103 -0
  56. package/lib/gcve-index.js +181 -0
  57. package/lib/gcve.js +1 -1
  58. package/lib/github-publisher-maven.js +40 -0
  59. package/lib/hash-id.js +5 -5
  60. package/lib/hosted-proxy.js +6 -1
  61. package/lib/i18n.js +31 -8
  62. package/lib/json-cache.js +18 -0
  63. package/lib/json-export.js +16 -2
  64. package/lib/kev.js +7 -8
  65. package/lib/line-stream.js +23 -0
  66. package/lib/maven-airgap.js +80 -0
  67. package/lib/maven-cache.js +21 -0
  68. package/lib/maven-license.js +2 -1
  69. package/lib/maven-presence.js +2 -2
  70. package/lib/maven-reactor.js +23 -14
  71. package/lib/maven-repo.js +11 -6
  72. package/lib/merge-sources.js +25 -18
  73. package/lib/native-advisories.js +268 -0
  74. package/lib/nvd-bulk.js +145 -0
  75. package/lib/nvd-package-ranges.js +109 -0
  76. package/lib/nvd.js +52 -24
  77. package/lib/osv-db.js +253 -59
  78. package/lib/osv-legacy.js +57 -0
  79. package/lib/osv.js +241 -168
  80. package/lib/outdated.js +11 -12
  81. package/lib/package-metadata.js +141 -0
  82. package/lib/package-versions.js +52 -0
  83. package/lib/packagist-audit.js +6 -6
  84. package/lib/provenance.js +73 -19
  85. package/lib/providers/common.js +11 -1
  86. package/lib/providers/gcve.js +17 -0
  87. package/lib/providers/github.js +1 -0
  88. package/lib/providers/index.js +49 -26
  89. package/lib/providers/vigievuln.js +7 -0
  90. package/lib/proxy-cache.js +1 -1
  91. package/lib/proxy-scope.js +59 -0
  92. package/lib/proxy-throttle.js +71 -0
  93. package/lib/resource-cache/engine.js +36 -9
  94. package/lib/resource-cache/sqlite-store.js +95 -0
  95. package/lib/resource-cache/validate.js +5 -0
  96. package/lib/retire.js +24 -24
  97. package/lib/ruby-version.js +36 -0
  98. package/lib/sarif-export.js +1 -1
  99. package/lib/sbom-export.js +11 -7
  100. package/lib/snyk.js +32 -20
  101. package/lib/source-profile.js +67 -0
  102. package/lib/sqlite-driver.js +46 -0
  103. package/lib/transitive.js +69 -34
  104. package/lib/unmanaged.js +2 -1
  105. package/lib/vigievuln-advisories.js +47 -0
  106. package/package.json +7 -6
  107. package/vigievuln.js +380 -107
@@ -0,0 +1,117 @@
1
+ 'use strict';
2
+
3
+ // Project exports retain the complete advisory history for every resolved
4
+ // package, including versions other than the one in the descriptor.
5
+ const path=require('node:path');
6
+ const {openCacheDb}=require('./cache-db');
7
+ const {packageName}=require('./advisory-store');
8
+ const packageScope=(ecosystem,name)=>'project-package:'+JSON.stringify([ecosystem,ecosystem==='Maven'?name:packageName(ecosystem,name)]);
9
+
10
+ function buildProjectScope(resolved,{applications=[],cves=[]}={}){
11
+ const {osvEcosystemFor,osvPkgName}=require('./osv');
12
+ const packages=new Map();
13
+ for(const d of resolved.values()){
14
+ if(d.scope==='parent'||d.provenance==='binary'||d.ecosystem==='binary')continue;
15
+ const ecosystem=osvEcosystemFor(d),name=osvPkgName(d);
16
+ if(typeof name!=='string'||!name||name.includes('undefined'))continue;
17
+ packages.set(JSON.stringify([ecosystem,name]),{ecosystem,name});
18
+ }
19
+ const project={schema:1,packages:[...packages.values()],cves:[...new Set(cves.filter(id=>/^CVE-\d{4}-\d{4,7}$/.test(id||'')))],retainAllNvd:applications.length>0||[...resolved.values()].some(d=>d.provenance==='binary'||d.ecosystem==='binary')};
20
+ return project;
21
+ }
22
+
23
+ function buildProjectSnapshot(sourceDir,targetDir,project){
24
+ if(project?.schema!==1||!Array.isArray(project.packages)||!project.packages.length)throw Error('invalid or empty prepared project scope');
25
+ const db=openCacheDb({cacheDir:targetDir});
26
+ const quote=s=>`'${s.replace(/'/g,"''")}'`;
27
+ try{
28
+ db.exec(`ATTACH DATABASE ${quote(path.join(sourceDir,'cache.sqlite'))} AS source`);
29
+ // Pin one source snapshot while collecting identities and copying records.
30
+ db.exec('BEGIN');
31
+ db.exec('CREATE TEMP TABLE wanted_packages(ecosystem TEXT, package_key TEXT, query_key TEXT, PRIMARY KEY(ecosystem,query_key)) WITHOUT ROWID; CREATE TEMP TABLE wanted_advisories(source TEXT,id TEXT,PRIMARY KEY(source,id)) WITHOUT ROWID; CREATE TEMP TABLE wanted_cves(cve TEXT PRIMARY KEY) WITHOUT ROWID;');
32
+ const add=db.prepare('INSERT OR IGNORE INTO wanted_packages VALUES(?,?,?)');
33
+ for(const p of project.packages){if(!p||typeof p.ecosystem!=='string'||typeof p.name!=='string'||!p.name)throw Error('invalid project package');add.run(p.ecosystem,packageName(p.ecosystem,p.name),p.ecosystem==='Maven'?p.name:packageName(p.ecosystem,p.name));}
34
+ db.exec(`INSERT OR IGNORE INTO wanted_advisories SELECT source,id FROM source.advisory_records WHERE source NOT IN ('osv','vigievuln','cveproject','cveproject-legacy');
35
+ INSERT OR IGNORE INTO wanted_advisories SELECT p.source,p.id FROM source.advisory_packages p JOIN wanted_packages w ON w.ecosystem=p.ecosystem AND w.package_key=p.name_key;
36
+ INSERT OR IGNORE INTO wanted_advisories SELECT p.source,p.id FROM source.advisory_packages p JOIN wanted_packages w ON w.ecosystem='Maven' AND p.ecosystem='CVEProduct' AND p.name_key=lower(substr(w.package_key,instr(w.package_key,':')+1));
37
+ INSERT OR IGNORE INTO wanted_advisories SELECT q.source,q.id FROM source.advisory_query_ids q JOIN wanted_packages w ON w.ecosystem=q.ecosystem AND w.query_key=q.name_key;
38
+ INSERT OR IGNORE INTO wanted_cves SELECT DISTINCT l.cve FROM source.cve_lookup l JOIN wanted_packages w ON w.ecosystem='Maven' AND ((l.kind='package' AND l.lookup_key=lower(w.package_key)) OR (l.kind='product' AND l.lookup_key=lower(substr(w.package_key,instr(w.package_key,':')+1))));`);
39
+ if(project.retainAllNvd)db.exec("INSERT OR IGNORE INTO wanted_advisories SELECT source,id FROM source.advisory_records WHERE source IN ('cveproject','cveproject-legacy')");
40
+ const {decompress}=require('./advisory-compression');
41
+ const addCve=db.prepare('INSERT OR IGNORE INTO wanted_cves VALUES(?)');
42
+ // Some findings (for example a vendored JS advisory) have no retained
43
+ // package advisory or CVE lookup entry. Their explicitly warmed NVD records
44
+ // must still travel with the project snapshot.
45
+ for(const id of Array.isArray(project.cves)?project.cves:[]) {
46
+ if(/^CVE-\d{4}-\d{4,7}$/.test(id||'')) addCve.run(id);
47
+ }
48
+ const rows=db.prepare('SELECT r.envelope_deflate,r.envelope_bytes FROM source.advisory_records r JOIN wanted_advisories w USING(source,id)');
49
+ for(const row of rows.all()){
50
+ const text=decompress(row.envelope_deflate,row.envelope_bytes).toString('utf8');
51
+ for(const id of text.match(/CVE-\d{4}-\d{4,}/g)||[])addCve.run(id);
52
+ }
53
+ // Keep native revisions, including withdrawals, for retained index buckets.
54
+ db.exec("INSERT OR IGNORE INTO wanted_advisories SELECT r.source,r.id FROM source.advisory_records r JOIN wanted_cves c ON c.cve=r.id WHERE r.source IN ('cveproject','cveproject-legacy')");
55
+ {
56
+ db.exec(`INSERT INTO advisory_records SELECT r.* FROM source.advisory_records r JOIN wanted_advisories w USING(source,id);
57
+ INSERT INTO advisory_packages SELECT p.* FROM source.advisory_packages p JOIN wanted_advisories w USING(source,id);
58
+ INSERT INTO advisory_observations SELECT o.* FROM source.advisory_observations o JOIN wanted_advisories w USING(source,id);
59
+ INSERT INTO advisory_queries SELECT q.* FROM source.advisory_queries q JOIN wanted_packages w ON w.ecosystem=q.ecosystem AND w.query_key=q.name_key;
60
+ INSERT INTO advisory_query_ids SELECT q.* FROM source.advisory_query_ids q JOIN wanted_packages w ON w.ecosystem=q.ecosystem AND w.query_key=q.name_key;
61
+ INSERT INTO advisory_coverage SELECT * FROM source.advisory_coverage WHERE source<>'osv';
62
+ INSERT INTO cache_entries SELECT * FROM source.cache_entries WHERE namespace NOT IN ('airgap-project','airgap-cve-index') AND NOT (namespace='catalogue' AND key IN ('euvd-targeted','epss'));
63
+ INSERT INTO cache_snapshots SELECT * FROM source.cache_snapshots;
64
+ INSERT INTO cve_lookup SELECT l.* FROM source.cve_lookup l WHERE EXISTS(SELECT 1 FROM wanted_packages w WHERE w.ecosystem='Maven' AND ((l.kind='package' AND l.lookup_key=lower(w.package_key)) OR (l.kind='product' AND l.lookup_key=lower(substr(w.package_key,instr(w.package_key,':')+1)))));
65
+ INSERT INTO package_versions SELECT * FROM source.package_versions;
66
+ INSERT INTO resource_bodies SELECT * FROM source.resource_bodies;
67
+ INSERT INTO resource_chunks SELECT * FROM source.resource_chunks;
68
+ INSERT INTO resources SELECT * FROM source.resources;`);
69
+ if(!project.retainAllNvd)db.exec("UPDATE advisory_coverage SET complete=0,entry_json=json_set(entry_json,'$.complete',json('false')) WHERE source IN ('cveproject','cveproject-legacy')");
70
+ // A project index proves coverage only for its exported package buckets.
71
+ // Preserve the source timestamp and never claim global index completeness.
72
+ const indexSnapshot=db.prepare("SELECT * FROM source.cache_snapshots WHERE namespace='cve_lookup'").get();
73
+ if(indexSnapshot){
74
+ const indexMeta=JSON.parse(indexSnapshot.metadata_json);indexMeta.projectScoped=true;
75
+ db.prepare("UPDATE cache_snapshots SET complete=0,metadata_json=? WHERE namespace='cve_lookup'").run(JSON.stringify(indexMeta));
76
+ const marker=db.prepare("INSERT OR REPLACE INTO cache_entries(namespace,key,fetched_at,expires_at,stale,encoding,payload,metadata_json) VALUES('airgap-cve-index',?,?,NULL,?,'json',?,'{}')");
77
+ const existing=db.prepare("SELECT fetched_at,stale FROM source.cache_entries WHERE namespace='airgap-cve-index' AND key=?");
78
+ for(const p of project.packages.filter(p=>p.ecosystem==='Maven')){
79
+ const coord=p.name.toLowerCase(),artifact=coord.slice(coord.indexOf(':')+1);
80
+ const coverage=indexSnapshot.complete===1?indexSnapshot:existing.get(`p:${coord}`);
81
+ if(coverage){
82
+ marker.run(`p:${coord}`,coverage.fetched_at,coverage.stale,Buffer.from('{}'));
83
+ const productCoverage=indexSnapshot.complete===1?indexSnapshot:existing.get(`a:${artifact}`);
84
+ if(productCoverage)marker.run(`a:${artifact}`,productCoverage.fetched_at,productCoverage.stale,Buffer.from('{}'));
85
+ }
86
+ }
87
+ }
88
+ // These per-CVE enrichments may contain observations from other projects.
89
+ // Keep only CVEs actually encountered while preparing this descriptor.
90
+ const keep=new Set(Array.isArray(project.cves)?project.cves:[]),zlib=require('node:zlib');
91
+ const cached=db.prepare("SELECT * FROM source.cache_entries WHERE namespace='catalogue' AND key IN ('euvd-targeted','epss')").all();
92
+ const insertCache=db.prepare('INSERT INTO cache_entries(namespace,key,fetched_at,expires_at,stale,encoding,payload,metadata_json) VALUES(?,?,?,?,?,?,?,?)');
93
+ for(const row of cached){
94
+ const raw=row.encoding==='json+deflate'?zlib.inflateRawSync(row.payload,{maxOutputLength:134217728}):row.encoding==='json'?row.payload:null;
95
+ if(!raw)throw Error(`invalid ${row.key} cache encoding`);
96
+ const value=JSON.parse(Buffer.from(raw).toString('utf8'));
97
+ if(!value || !value.entries || typeof value.entries!=='object' || Array.isArray(value.entries))throw Error(`invalid ${row.key} cache`);
98
+ value.entries=Object.fromEntries(Object.entries(value.entries).filter(([id])=>keep.has(id)));
99
+ const bytes=Buffer.from(JSON.stringify(value)),compressed=bytes.length>=4096,metadata=JSON.parse(row.metadata_json);
100
+ delete metadata.uncompressedBytes;if(compressed)metadata.uncompressedBytes=bytes.length;
101
+ insertCache.run(row.namespace,row.key,row.fetched_at,row.expires_at,row.stale,compressed?'json+deflate':'json',compressed?zlib.deflateRawSync(bytes,{level:1}):bytes,JSON.stringify(metadata));
102
+ }
103
+ db.exec(project.retainAllNvd?'INSERT INTO nvd_records SELECT * FROM source.nvd_records':'INSERT INTO nvd_records SELECT n.* FROM source.nvd_records n JOIN wanted_cves w USING(cve)');
104
+ const global=db.prepare("SELECT slot,fetched_at,complete,stale,entry_json FROM source.advisory_coverage WHERE source='osv' AND ecosystem=?");
105
+ const insert=db.prepare('INSERT OR REPLACE INTO advisory_coverage(source,ecosystem,slot,fetched_at,complete,stale,entry_json) VALUES(?,?,?,?,?,?,?)');
106
+ for(const p of project.packages)for(const row of global.all(p.ecosystem)){
107
+ const ecosystem=packageScope(p.ecosystem,p.name),entry=JSON.parse(row.entry_json);entry.ecosystem=ecosystem;
108
+ insert.run('osv',ecosystem,row.slot,row.fetched_at,row.complete,row.stale,JSON.stringify(entry));
109
+ }
110
+ }
111
+ db.exec('COMMIT');
112
+ db.exec('DETACH DATABASE source');
113
+ db.exec('PRAGMA wal_checkpoint(TRUNCATE); PRAGMA journal_mode=DELETE');
114
+ }finally{db.close()}
115
+ return {packages:project.packages.length,fullNvd:!!project.retainAllNvd};
116
+ }
117
+ module.exports={buildProjectScope,buildProjectSnapshot,packageScope};
@@ -7,12 +7,12 @@ const { selectPlugins } = require("./select");
7
7
 
8
8
  const DEFAULT_SKIP = new Set([".git", ".idea", ".vscode", "node_modules", "vendor", "dist", "build", "out", "target"]);
9
9
  const posix = p => p.split(path.sep).join("/");
10
- const WORDFENCE_MAX_LOCAL_AGE_MS = 3600000;
10
+ const WORDFENCE_MAX_LOCAL_AGE_MS = 4 * 3600000;
11
11
  function staleWordfenceSnapshot(meta, now, autoCached = false) {
12
12
  if (!autoCached && meta?.completeness !== "targeted") return false;
13
13
  const collectedAt = Date.parse(meta?.collectedAt);
14
14
  return meta?.stale === true || !Number.isFinite(collectedAt) || collectedAt > now + 60000 ||
15
- now - collectedAt > WORDFENCE_MAX_LOCAL_AGE_MS;
15
+ now - collectedAt >= WORDFENCE_MAX_LOCAL_AGE_MS;
16
16
  }
17
17
  function privatePath(value) {
18
18
  if (typeof value !== "string" || !value || path.isAbsolute(value) || posix(value).split("/").includes(".."))
@@ -112,25 +112,33 @@ async function runApplicationPlugins(root, opts = {}) {
112
112
  const hostedOnline = !opts.offline && require("../providers").hasHostedProxy();
113
113
  const wordfenceProxyOnline = !opts.offline && require("../providers").hasProxyRoute();
114
114
  const liveWordfenceUrl = opts.offline ? null : opts.liveWordfenceUrl || null;
115
+ const forceCachedSource = (pluginId,file,configured,live,defaultUrl) => {
116
+ if (opts.offline || configured || live || !opts.advisoryCacheDir || !selectedPluginIds.has(pluginId) || !require('../cache-policy').shouldForceUpdate()) return live || null;
117
+ return require('../application-providers/snapshot-cache').exists(path.join(opts.advisoryCacheDir,file)) ? defaultUrl : null;
118
+ };
115
119
  // Drupal's live operation is scoped to the inventoried public package identities.
116
120
  // Never refresh a bulk catalogue here, and never replace an operator-selected file.
117
121
  const liveDrupalAdvisoriesUrl = opts.offline ? null : (opts.liveDrupalAdvisoriesUrl ||
118
122
  (hostedOnline && !opts.drupalAdvisoriesPath && selectedPluginIds.has("drupal")
119
- ? require("../application-providers/live-snapshot").DRUPAL_ADVISORIES_URL : null));
123
+ ? require("../application-providers/live-snapshot").DRUPAL_ADVISORIES_URL : null) ||
124
+ forceCachedSource('drupal','drupal-security-advisories.json',opts.drupalAdvisoriesPath,null,require('../application-providers/live-snapshot').DRUPAL_ADVISORIES_URL));
125
+ const livePrestashopAdvisoriesUrl=forceCachedSource('prestashop','github-prestashop-advisories.json',opts.prestashopAdvisoriesPath,opts.livePrestashopAdvisoriesUrl,require('../application-providers/live-snapshot').PRESTASHOP_GITHUB_ADVISORIES_URL);
126
+ const liveTypo3AdvisoriesUrl=forceCachedSource('typo3','github-typo3-advisories.json',opts.typo3AdvisoriesPath,opts.liveTypo3AdvisoriesUrl,require('../application-providers/live-snapshot').TYPO3_GITHUB_ADVISORIES_URL);
127
+ const liveSpipAdvisoriesUrl=forceCachedSource('spip','spip-security-advisories.json',opts.spipAdvisoriesPath,opts.liveSpipAdvisoriesUrl,require('../application-providers/spip-advisories').SPIP_ADVISORIES_URL);
120
128
  const autoCachedSources = new Set();
121
129
  const withCachedFallback = (configured, liveUrl, pluginId, file) => {
122
130
  if (configured || liveUrl || !opts.advisoryCacheDir || !selectedPluginIds.has(pluginId)) return configured || null;
123
131
  const cached = path.join(opts.advisoryCacheDir, file);
124
- if (!fs.existsSync(cached)) return configured || null;
132
+ if (!require('../application-providers/snapshot-cache').exists(cached)) return configured || null;
125
133
  autoCachedSources.add(cached);
126
134
  return cached;
127
135
  };
128
136
  const wordfenceFeedPath = withCachedFallback(opts.wordfenceFeedPath, liveWordfenceUrl, "wordpress",
129
137
  "wordfence-v3-targeted.json") || withCachedFallback(null, liveWordfenceUrl, "wordpress", "wordfence-v3.json");
130
138
  const drupalAdvisoriesPath = withCachedFallback(opts.drupalAdvisoriesPath, liveDrupalAdvisoriesUrl, "drupal", "drupal-security-advisories.json");
131
- const prestashopAdvisoriesPath = withCachedFallback(opts.prestashopAdvisoriesPath, opts.livePrestashopAdvisoriesUrl, "prestashop", "github-prestashop-advisories.json");
132
- const typo3AdvisoriesPath = withCachedFallback(opts.typo3AdvisoriesPath, opts.liveTypo3AdvisoriesUrl, "typo3", "github-typo3-advisories.json");
133
- const spipAdvisoriesPath = withCachedFallback(opts.spipAdvisoriesPath, opts.liveSpipAdvisoriesUrl, "spip", "spip-security-advisories.json");
139
+ const prestashopAdvisoriesPath = withCachedFallback(opts.prestashopAdvisoriesPath, livePrestashopAdvisoriesUrl, "prestashop", "github-prestashop-advisories.json");
140
+ const typo3AdvisoriesPath = withCachedFallback(opts.typo3AdvisoriesPath, liveTypo3AdvisoriesUrl, "typo3", "github-typo3-advisories.json");
141
+ const spipAdvisoriesPath = withCachedFallback(opts.spipAdvisoriesPath, liveSpipAdvisoriesUrl, "spip", "spip-security-advisories.json");
134
142
  // A locally configured advisory source is validated once, before discovery: readability,
135
143
  // size limit, JSON decoding, provider schema and — when requested — freshness. An
136
144
  // unusable source fails the scan before any report is written, even when no instance
@@ -139,10 +147,10 @@ async function runApplicationPlugins(root, opts = {}) {
139
147
  const validatedLocalSources = new Map();
140
148
  const validateLocalSource = (snapshotPath, label, validate) => {
141
149
  if (!snapshotPath || validatedLocalSources.has(snapshotPath)) return;
142
- const stat = fs.statSync(snapshotPath);
150
+ const {stat,bytes}=require('../application-providers/snapshot-cache').read(snapshotPath,
151
+ {preferCache:autoCachedSources.has(snapshotPath)});
143
152
  if (!stat.isFile() || stat.size > 128 * 1024 * 1024)
144
153
  throw new Error(`${label} advisory snapshot must be a JSON file of at most 128 MiB`);
145
- const bytes = fs.readFileSync(snapshotPath);
146
154
  const snapshot = JSON.parse(bytes.toString("utf8"));
147
155
  validate(snapshot);
148
156
  // Give an expired cache a chance to revalidate before applying the strict
@@ -187,11 +195,11 @@ async function runApplicationPlugins(root, opts = {}) {
187
195
  wordfenceApiKey: opts.wordfenceApiKey || null,
188
196
  liveDrupalAdvisoriesUrl,
189
197
  prestashopAdvisoriesPath,
190
- livePrestashopAdvisoriesUrl: opts.livePrestashopAdvisoriesUrl || null,
198
+ livePrestashopAdvisoriesUrl,
191
199
  typo3AdvisoriesPath,
192
- liveTypo3AdvisoriesUrl: opts.liveTypo3AdvisoriesUrl || null,
200
+ liveTypo3AdvisoriesUrl,
193
201
  spipAdvisoriesPath,
194
- liveSpipAdvisoriesUrl: opts.liveSpipAdvisoriesUrl || null,
202
+ liveSpipAdvisoriesUrl,
195
203
  spipAdvisoriesApiKey: opts.spipAdvisoriesApiKey || null,
196
204
  wpChecksumsPath: opts.wpChecksumsPath || null,
197
205
  liveWpChecksumsUrl: opts.liveWpChecksumsUrl || null,
@@ -210,10 +218,11 @@ async function runApplicationPlugins(root, opts = {}) {
210
218
  const local = validatedLocalSources.get(wordfenceFeedPath)?.snapshot;
211
219
  const localStale = staleWordfenceSnapshot(local?._fadSnapshot, context.now,
212
220
  autoCachedSources.has(wordfenceFeedPath));
221
+ const forceRefresh = !opts.offline && autoCachedSources.has(wordfenceFeedPath) && require('../cache-policy').shouldForceUpdate();
213
222
  let assessed;
214
223
  let refreshError;
215
224
  let usedLocal = true;
216
- if (plugin.id === "wordpress" && wordfenceProxyOnline && localStale) {
225
+ if (plugin.id === "wordpress" && wordfenceProxyOnline && (localStale || forceRefresh)) {
217
226
  try {
218
227
  assessed = await plugin.assess(app, components, { ...context, wordfenceFeedPath: null,
219
228
  liveWordfenceUrl: require("../application-providers/wordfence-projection").SOURCE_URL });
@@ -168,7 +168,7 @@ module.exports = {
168
168
  // an explicit --wp-checksums or live URL always wins.
169
169
  const cachedPath = ctx.advisoryCacheDir && core?.version
170
170
  ? path.join(ctx.advisoryCacheDir, `wordpress-checksums-${core.version}-${ctx.wpChecksumsLocale || "en_US"}.json`) : null;
171
- if (!cachedPath || !fs.existsSync(cachedPath)) return notRun("CMS_PROVIDER_UNCONFIGURED");
171
+ if (!cachedPath || !require('../application-providers/snapshot-cache').exists(cachedPath)) return notRun("CMS_PROVIDER_UNCONFIGURED");
172
172
  ctx.autoCachedSources?.add(cachedPath);
173
173
  ctxSnapshotPath = cachedPath;
174
174
  }
@@ -183,9 +183,10 @@ module.exports = {
183
183
  cached = ctx.snapshotCache.get(key);
184
184
  if (!cached) {
185
185
  const validated = ctx.validatedLocalSources?.get(checksumsPath);
186
- const stat = validated?.stat || fs.statSync(checksumsPath);
186
+ const source=validated||require('../application-providers/snapshot-cache').read(checksumsPath);
187
+ const stat = source.stat;
187
188
  if (!stat.isFile() || stat.size > 128 * 1024 * 1024) throw new Error("WordPress checksums snapshot must be a JSON file of at most 128 MiB");
188
- const bytes = validated?.bytes || fs.readFileSync(checksumsPath);
189
+ const bytes = source.bytes;
189
190
  const snapshot = validated?.snapshot || JSON.parse(bytes.toString("utf8"));
190
191
  // The runner only validates explicitly configured paths; a per-instance
191
192
  // cached fallback enforces the same freshness bound itself.
@@ -6,8 +6,6 @@
6
6
  */
7
7
  const { responseFetchedAt } = require("../providers/common");
8
8
  const crypto = require("node:crypto");
9
- const fs = require("node:fs");
10
- const path = require("node:path");
11
9
  const { indexFeed } = require("./wordfence-v3");
12
10
  const { validateSnapshot: validateGithubAdvisories } = require("./github-advisories");
13
11
  const { validateChecksums } = require("./wp-checksums");
@@ -161,16 +159,7 @@ async function fetchWordpressChecksums(version, locale = "en_US", { fetchImpl =
161
159
  }
162
160
 
163
161
  function writeSnapshotAtomically(filePath, snapshot) {
164
- const dir = path.dirname(filePath);
165
- fs.mkdirSync(dir, { recursive: true });
166
- const temp = path.join(dir, `.${path.basename(filePath)}.tmp-${process.pid}`);
167
- try {
168
- fs.writeFileSync(temp, `${JSON.stringify(snapshot, null, "\t")}\n`);
169
- fs.renameSync(temp, filePath);
170
- } catch (error) {
171
- try { fs.unlinkSync(temp); } catch { /* best-effort cleanup of the staged temp file */ }
172
- throw error;
173
- }
162
+ require('./snapshot-cache').write(filePath,snapshot);
174
163
  }
175
164
 
176
165
  module.exports = { DRUPAL_ADVISORIES_URL, WORDFENCE_PRODUCTION_URL, GITHUB_ADVISORIES_URL, PRESTASHOP_GITHUB_ADVISORIES_URL, TYPO3_GITHUB_ADVISORIES_URL, fetchDrupalAdvisories, fetchWordfenceFeed, fetchGithubAdvisories, fetchWordpressChecksums, mergeDrupalSnapshots, writeSnapshotAtomically };
@@ -0,0 +1,27 @@
1
+ 'use strict';
2
+
3
+ const fs=require('node:fs');
4
+ const path=require('node:path');
5
+ const {createCacheRepository}=require('../cache-repository');
6
+
7
+ function slot(file){
8
+ const dir=path.dirname(file);
9
+ return {root:path.basename(dir)==='advisory-snapshots'?path.dirname(dir):dir,key:path.basename(file)};
10
+ }
11
+ function cached(file){
12
+ const {root,key}=slot(file);
13
+ try{return createCacheRepository(root).get('application-snapshot',key)}catch{return null}
14
+ }
15
+ function exists(file){return !!cached(file)||fs.existsSync(file)}
16
+ function read(file,{preferCache=false}={}){
17
+ if(!preferCache&&fs.existsSync(file)){const stat=fs.statSync(file);return {bytes:fs.readFileSync(file),stat}}
18
+ const entry=cached(file);
19
+ if(entry){const bytes=Buffer.from(JSON.stringify(entry.value));return {bytes,stat:{size:bytes.length,mtimeMs:entry.fetchedAt,mtime:new Date(entry.fetchedAt),isFile:()=>true}}}
20
+ if(fs.existsSync(file)){const stat=fs.statSync(file);return {bytes:fs.readFileSync(file),stat}}
21
+ throw Object.assign(new Error(`ENOENT: no such advisory snapshot: ${file}`),{code:'ENOENT'});
22
+ }
23
+ function write(file,snapshot){
24
+ const {root,key}=slot(file),stamp=Date.parse(snapshot?._fadSnapshot?.collectedAt);
25
+ createCacheRepository(root).put('application-snapshot',key,snapshot,{fetchedAt:Number.isFinite(stamp)?stamp:Date.now()});
26
+ }
27
+ module.exports={exists,read,write};
@@ -1,5 +1,4 @@
1
1
  const crypto = require("node:crypto");
2
- const fs = require("node:fs");
3
2
  const path = require("node:path");
4
3
  const { FORMAT, MAX_RESPONSE_BYTES, componentQueries, queriesOf, keyOf, indexProjection, projectFeed, mergeProjections } = require("./wordfence-projection");
5
4
  const CACHE_FILE = "wordfence-v3-targeted.json";
@@ -57,8 +56,9 @@ function cacheProjection(dir, snapshot) {
57
56
  const file = path.join(dir, CACHE_FILE);
58
57
  let previous = null;
59
58
  try {
60
- if (fs.statSync(file).size > MAX_RESPONSE_BYTES) throw new Error("Wordfence cache limit exceeded");
61
- previous = JSON.parse(fs.readFileSync(file, "utf8")); indexProjection(previous);
59
+ const cached=require('./snapshot-cache').read(file,{preferCache:true});
60
+ if (cached.stat.size > MAX_RESPONSE_BYTES) throw new Error("Wordfence cache limit exceeded");
61
+ previous = JSON.parse(cached.bytes.toString('utf8')); indexProjection(previous);
62
62
  }
63
63
  catch { previous = null; }
64
64
  const merged = mergeProjections(previous, snapshot);
@@ -95,13 +95,13 @@ function attributeMatchOrigins(matches) {
95
95
  // 2. Declared → narrow to the manifest(s) that declare THIS version, and take the
96
96
  // scope from those declarations. `isDev` on the record is coord-wide, so a version
97
97
  // declared only at test scope would otherwise inherit the coordinate's production
98
- // flag. Dev only when EVERY declaration of this version is test/provided — the same
98
+ // flag. Dev only when EVERY declaration of this version is test/dev — the same
99
99
  // widest-wins rule the masked branch uses.
100
100
  const declared = dep.versionPaths && dep.versionPaths[ver];
101
101
  if (Array.isArray(declared) && declared.length) {
102
102
  const scopes = dep.versionScopes && dep.versionScopes[ver];
103
103
  const isDev = Array.isArray(scopes) && scopes.length
104
- ? scopes.every(s => s === "test" || s === "provided" || s === "dev")
104
+ ? scopes.every(s => s === "test" || s === "dev")
105
105
  : undefined;
106
106
  const narrow = !sameList(declared, dep.manifestPaths);
107
107
  const occurrences = Array.isArray(dep.occurrences)
@@ -0,0 +1,215 @@
1
+ 'use strict';
2
+
3
+ const fs=require('node:fs');
4
+ const path=require('node:path');
5
+ const os=require('node:os');
6
+ const crypto=require('node:crypto');
7
+ const zlib=require('node:zlib');
8
+ const {execFile}=require('node:child_process');
9
+ const {promisify}=require('node:util');
10
+ const run=promisify(execFile);
11
+ const {openCacheDb,closeCacheDbs,SCHEMA_VERSION}=require('./cache-db');
12
+ const {proxyOrigin:canonicalOrigin}=require('./proxy-scope');
13
+ const FORMAT='vigievuln-sqlite-cache';
14
+ const ALLOWED=new Set(['.vigie-vuln/','.vigie-vuln/cache.sqlite','.vigie-vuln/cli-bundle-meta.json','.vigievuln-archive-origin.json']);
15
+ const sha256=file=>new Promise((resolve,reject)=>{const hash=crypto.createHash('sha256'),stream=fs.createReadStream(file);stream.on('data',part=>hash.update(part));stream.on('error',reject);stream.on('end',()=>resolve(hash.digest('hex')))});
16
+ async function inspectArchive(file){
17
+ let names,details;
18
+ try{
19
+ ({stdout:names}=await run('tar',['-tzf',file],{maxBuffer:64*1024}));
20
+ ({stdout:details}=await run('tar',['-tvzf',file],{maxBuffer:128*1024}));
21
+ }catch(error){
22
+ // Distinguish a malformed archive from an unavailable or resource-starved
23
+ // tar process. Do not include stderr or command arguments: both can contain
24
+ // private local paths and attacker-controlled member names.
25
+ const code=error?.code;
26
+ if(typeof code==='string' && /^[A-Z][A-Z0-9_]{0,31}$/.test(code))throw Error(`cannot inspect cache bundle: tar process failed (${code})`);
27
+ if(typeof code==='number')throw Error(`unsupported cache bundle: tar exited with status ${code}`);
28
+ if(typeof error?.signal==='string' && /^SIG[A-Z0-9]+$/.test(error.signal))throw Error(`cannot inspect cache bundle: tar terminated (${error.signal})`);
29
+ throw Error('cannot inspect cache bundle: tar failed');
30
+ }
31
+ const listed=names.trim().split(/\r?\n/).filter(Boolean);
32
+ if(!listed.length||listed.length>4||!listed.includes('.vigie-vuln/cache.sqlite')||!listed.includes('.vigie-vuln/cli-bundle-meta.json')||listed.some(name=>!ALLOWED.has(name)))throw Error('unsupported cache bundle: missing or unexpected archive entries');
33
+ const types=details.trim().split(/\r?\n/);
34
+ if(types.length!==listed.length||types.some(line=>!['-','d'].includes(line[0])))throw Error('cache bundle contains links or special files');
35
+ }
36
+ function verifyDb(file){
37
+ const db=openCacheDb({cacheDir:path.dirname(file),readonly:true});
38
+ try{
39
+ const integrity=db.prepare('PRAGMA integrity_check').get();
40
+ if(Object.values(integrity)[0]!=='ok')throw Error('SQLite cache integrity check failed');
41
+ if(db.prepare('PRAGMA foreign_key_check').get())throw Error('SQLite cache foreign key check failed');
42
+ return {advisories:db.prepare('SELECT COUNT(*) AS count FROM advisory_records').get().count};
43
+ }finally{db.close()}
44
+ }
45
+ function verifyStandaloneSnapshot(file){
46
+ const wal=file+'-wal';
47
+ // The snapshot directory is private to this export. A nonempty WAL can
48
+ // contain committed pages absent from the main file and must never be lost.
49
+ try{if(fs.statSync(wal).size>0)throw Error('cache snapshot has uncheckpointed WAL data')}catch(error){if(error.code!=='ENOENT')throw error}
50
+ const db=openCacheDb({cacheDir:path.dirname(file),readonly:true});
51
+ try{if(db.prepare('PRAGMA journal_mode').get().journal_mode.toLowerCase()==='wal')throw Error('cache snapshot is still in WAL mode')}
52
+ finally{db.close()}
53
+ }
54
+ function mergeDatabase(targetFile,incomingFile){
55
+ const target=openCacheDb({cacheDir:path.dirname(targetFile)});
56
+ const quote=file=>`'${file.replace(/'/g,"''")}'`;
57
+ try{
58
+ target.exec(`ATTACH DATABASE ${quote(incomingFile)} AS incoming`);
59
+ const incomingCve=target.prepare("SELECT * FROM incoming.cache_snapshots WHERE namespace='cve_lookup'").get();
60
+ const localCve=target.prepare("SELECT * FROM cache_snapshots WHERE namespace='cve_lookup'").get();
61
+ const decodeMap=row=>{
62
+ if(!row||!row.encoding.startsWith('json'))return null;
63
+ const bytes=row.encoding.endsWith('+deflate')?zlib.inflateRawSync(Buffer.from(row.payload),{maxOutputLength:134217728}):Buffer.from(row.payload);
64
+ const value=JSON.parse(bytes.toString('utf8'));
65
+ return value&&typeof value==='object'&&!Array.isArray(value)&&value.entries&&typeof value.entries==='object'&&!Array.isArray(value.entries)?value:null;
66
+ };
67
+ const localMaps=target.prepare("SELECT * FROM cache_entries WHERE namespace='auxiliary'").all();
68
+ const incomingMaps=new Map(target.prepare("SELECT * FROM incoming.cache_entries WHERE namespace='auxiliary'").all().map(row=>[row.key,row]));
69
+ const mergedMaps=[];
70
+ for(const localRow of localMaps){
71
+ const incomingRow=incomingMaps.get(localRow.key);if(!incomingRow)continue;
72
+ const local=decodeMap(localRow),incoming=decodeMap(incomingRow);if(!local||!incoming)continue;
73
+ const preferIncoming=incomingRow.fetched_at>=localRow.fetched_at;
74
+ const entries={...(preferIncoming?local.entries:incoming.entries),...(preferIncoming?incoming.entries:local.entries)};
75
+ if(localRow.key==='maven-exists-cache.json'){
76
+ for(const key of new Set([...Object.keys(local.entries),...Object.keys(incoming.entries)])){
77
+ if(local.entries[key]===true||incoming.entries[key]===true)entries[key]=true;
78
+ }
79
+ require('./maven-presence').discardUnverifiedEntries({entries});
80
+ }
81
+ const stamp=Math.min(localRow.fetched_at,incomingRow.fetched_at);
82
+ mergedMaps.push({key:localRow.key,stamp,value:{...local,...incoming,meta:{...local.meta,...incoming.meta,fetchedAt:stamp},entries}});
83
+ }
84
+ target.transaction(()=>{
85
+ target.exec(`CREATE TEMP TABLE local_index_scopes AS SELECT key,fetched_at FROM cache_entries WHERE namespace='airgap-cve-index';
86
+ CREATE TEMP TABLE winning_records AS
87
+ SELECT i.source,i.id FROM incoming.advisory_records i LEFT JOIN advisory_records t USING(source,id)
88
+ WHERE t.id IS NULL OR i.revision_ms>t.revision_ms OR
89
+ (i.revision_ms=t.revision_ms AND i.withdrawn>t.withdrawn) OR
90
+ (i.revision_ms=t.revision_ms AND i.withdrawn=t.withdrawn AND i.fetched_at>=t.fetched_at);
91
+ CREATE UNIQUE INDEX winning_records_key ON winning_records(source,id);
92
+ DELETE FROM advisory_packages WHERE EXISTS(SELECT 1 FROM winning_records w WHERE w.source=advisory_packages.source AND w.id=advisory_packages.id);
93
+ INSERT INTO advisory_records SELECT i.* FROM incoming.advisory_records i JOIN winning_records w USING(source,id) WHERE 1
94
+ ON CONFLICT(source,id) DO UPDATE SET revision_ms=excluded.revision_ms,withdrawn=excluded.withdrawn,
95
+ fetched_at=excluded.fetched_at,content_changed_at=CASE WHEN excluded.document_sha256=advisory_records.document_sha256
96
+ THEN advisory_records.content_changed_at ELSE excluded.fetched_at END,
97
+ document_sha256=excluded.document_sha256,envelope_deflate=excluded.envelope_deflate,envelope_bytes=excluded.envelope_bytes;
98
+ INSERT INTO advisory_packages SELECT p.* FROM incoming.advisory_packages p JOIN winning_records w USING(source,id);
99
+ INSERT INTO advisory_observations SELECT * FROM incoming.advisory_observations WHERE 1
100
+ ON CONFLICT(source,id,provenance_key) DO UPDATE SET fetched_at=max(advisory_observations.fetched_at,excluded.fetched_at);
101
+ CREATE TEMP TABLE winning_queries AS
102
+ SELECT i.source,i.ecosystem,i.name_key,i.version FROM incoming.advisory_queries i
103
+ LEFT JOIN advisory_queries t USING(source,ecosystem,name_key,version)
104
+ WHERE t.source IS NULL OR i.fetched_at>=t.fetched_at;
105
+ CREATE UNIQUE INDEX winning_queries_key ON winning_queries(source,ecosystem,name_key,version);
106
+ DELETE FROM advisory_query_ids WHERE EXISTS(SELECT 1 FROM winning_queries w WHERE w.source=advisory_query_ids.source
107
+ AND w.ecosystem=advisory_query_ids.ecosystem AND w.name_key=advisory_query_ids.name_key AND w.version=advisory_query_ids.version);
108
+ INSERT INTO advisory_queries SELECT i.* FROM incoming.advisory_queries i JOIN winning_queries w USING(source,ecosystem,name_key,version) WHERE 1
109
+ ON CONFLICT(source,ecosystem,name_key,version) DO UPDATE SET original_name=excluded.original_name,
110
+ fetched_at=excluded.fetched_at,stale=excluded.stale,provenance_json=excluded.provenance_json;
111
+ INSERT INTO advisory_query_ids SELECT q.* FROM incoming.advisory_query_ids q JOIN winning_queries w USING(source,ecosystem,name_key,version);
112
+ INSERT INTO advisory_coverage SELECT * FROM incoming.advisory_coverage WHERE 1
113
+ ON CONFLICT(source,ecosystem,slot) DO UPDATE SET fetched_at=excluded.fetched_at,complete=excluded.complete,
114
+ stale=excluded.stale,entry_json=excluded.entry_json WHERE excluded.fetched_at>=advisory_coverage.fetched_at;
115
+ INSERT INTO cache_entries SELECT * FROM incoming.cache_entries WHERE 1
116
+ ON CONFLICT(namespace,key) DO UPDATE SET fetched_at=excluded.fetched_at,expires_at=excluded.expires_at,
117
+ stale=excluded.stale,encoding=excluded.encoding,payload=excluded.payload,metadata_json=excluded.metadata_json
118
+ WHERE excluded.fetched_at>=cache_entries.fetched_at;
119
+ INSERT INTO cache_snapshots SELECT * FROM incoming.cache_snapshots WHERE namespace<>'cve_lookup'
120
+ ON CONFLICT(namespace) DO UPDATE SET fetched_at=excluded.fetched_at,complete=excluded.complete,
121
+ stale=excluded.stale,record_count=excluded.record_count,metadata_json=excluded.metadata_json
122
+ WHERE excluded.fetched_at>=cache_snapshots.fetched_at;
123
+ INSERT INTO nvd_records SELECT * FROM incoming.nvd_records WHERE 1
124
+ ON CONFLICT(cve,kind) DO UPDATE SET fetched_at=excluded.fetched_at,revision_ms=excluded.revision_ms,
125
+ body_deflate=excluded.body_deflate,body_bytes=excluded.body_bytes,metadata_json=excluded.metadata_json WHERE excluded.fetched_at>=nvd_records.fetched_at;
126
+ INSERT OR IGNORE INTO package_versions SELECT * FROM incoming.package_versions;
127
+ INSERT OR IGNORE INTO resource_bodies SELECT * FROM incoming.resource_bodies;
128
+ INSERT OR IGNORE INTO resource_chunks SELECT * FROM incoming.resource_chunks;
129
+ INSERT INTO resources SELECT * FROM incoming.resources WHERE 1
130
+ ON CONFLICT(key) DO UPDATE SET body_id=excluded.body_id,fetched_at=excluded.fetched_at,ttl_ms=excluded.ttl_ms,
131
+ content_type=excluded.content_type,response_headers_json=excluded.response_headers_json,metadata_json=excluded.metadata_json
132
+ WHERE excluded.fetched_at>=resources.fetched_at;
133
+ DROP TABLE winning_records; DROP TABLE winning_queries;`);
134
+ if(incomingCve){
135
+ const scoped=!!JSON.parse(incomingCve.metadata_json).projectScoped;
136
+ if(scoped){
137
+ // Replace only covered buckets. Empty buckets are evidence too; do not
138
+ // erase the rest of a previously imported index or a complete local one.
139
+ if(!localCve || localCve.complete!==1 || incomingCve.fetched_at>=localCve.fetched_at){
140
+ target.exec("DELETE FROM cve_lookup WHERE EXISTS (SELECT 1 FROM incoming.cache_entries m LEFT JOIN local_index_scopes old ON old.key=m.key WHERE m.namespace='airgap-cve-index' AND m.key=(CASE cve_lookup.kind WHEN 'package' THEN 'p:' ELSE 'a:' END)||cve_lookup.lookup_key AND (old.key IS NULL OR m.fetched_at>=old.fetched_at))");
141
+ target.exec("INSERT OR IGNORE INTO cve_lookup SELECT i.* FROM incoming.cve_lookup i LEFT JOIN incoming.cache_entries m ON m.namespace='airgap-cve-index' AND m.key=(CASE i.kind WHEN 'package' THEN 'p:' ELSE 'a:' END)||i.lookup_key LEFT JOIN local_index_scopes old ON old.key=(CASE i.kind WHEN 'package' THEN 'p:' ELSE 'a:' END)||i.lookup_key WHERE old.key IS NULL OR m.fetched_at>=old.fetched_at");
142
+ }
143
+ if(!localCve)target.exec("INSERT INTO cache_snapshots SELECT * FROM incoming.cache_snapshots WHERE namespace='cve_lookup'");
144
+ }else if(!localCve || incomingCve.fetched_at>=localCve.fetched_at || JSON.parse(localCve.metadata_json).projectScoped){
145
+ target.exec("DELETE FROM cve_lookup; INSERT INTO cve_lookup SELECT * FROM incoming.cve_lookup; DELETE FROM cache_snapshots WHERE namespace='cve_lookup'; INSERT INTO cache_snapshots SELECT * FROM incoming.cache_snapshots WHERE namespace='cve_lookup'");
146
+ }
147
+ }
148
+ target.exec('DROP TABLE local_index_scopes');
149
+ const updateMap=target.prepare('UPDATE cache_entries SET fetched_at=?,encoding=?,payload=?,metadata_json=? WHERE namespace=? AND key=?');
150
+ for(const item of mergedMaps){
151
+ const bytes=Buffer.from(JSON.stringify(item.value)),compressed=bytes.length>=4096;
152
+ updateMap.run(item.stamp,compressed?'json+deflate':'json',compressed?zlib.deflateRawSync(bytes,{level:1}):bytes,
153
+ JSON.stringify(compressed?{uncompressedBytes:bytes.length}:{}),'auxiliary',item.key);
154
+ }
155
+ });
156
+ target.exec('DETACH DATABASE incoming');
157
+ }finally{target.close()}
158
+ }
159
+ async function importCache(source,{targetDir=require('./cache-directory').getCacheDir(),proxyOrigin,replace=false,force=false,onProgress,requireUsableSeed=false}={}){
160
+ const abs=path.resolve(source);if(!fs.statSync(abs).isFile())throw Error('cache bundle is not a file');
161
+ onProgress?.({phase:'validating'});await inspectArchive(abs);
162
+ const stage=fs.mkdtempSync(path.join(path.dirname(targetDir),'vigievuln-sqlite-import-'));
163
+ try{
164
+ onProgress?.({phase:'extracting'});
165
+ await run('tar',['-xzf',abs,'--no-same-owner','-C',stage],{maxBuffer:64*1024});
166
+ const root=path.join(stage,'.vigie-vuln'),file=path.join(root,'cache.sqlite'),manifestPath=path.join(root,'cli-bundle-meta.json');
167
+ for(const item of [root,file,manifestPath]){const st=fs.lstatSync(item);if(st.isSymbolicLink()||st.nlink!==1&&st.isFile()||!(st.isFile()||st.isDirectory()))throw Error('unsafe cache bundle entry')}
168
+ const manifest=JSON.parse(fs.readFileSync(manifestPath,'utf8'));
169
+ if(manifest.format!==FORMAT||manifest.schemaVersion!==SCHEMA_VERSION||manifest.payload?.file!=='cache.sqlite'||manifest.payload?.bytes!==fs.statSync(file).size||manifest.payload?.sha256!==await sha256(file))throw Error('cache bundle checksum or format mismatch');
170
+ if(proxyOrigin){const marker=JSON.parse(fs.readFileSync(path.join(stage,'.vigievuln-archive-origin.json'),'utf8'));if(marker.origin!==canonicalOrigin(proxyOrigin))throw Error('cache bundle proxy origin mismatch')}
171
+ onProgress?.({phase:'checking'});
172
+ const summary=verifyDb(file);
173
+ if(requireUsableSeed&&summary.advisories===0)throw Error('SQLite cache bundle contains no advisories');
174
+ fs.mkdirSync(targetDir,{recursive:true,mode:0o700});
175
+ const targetFile=path.join(targetDir,'cache.sqlite');
176
+ if(!fs.existsSync(targetFile)||replace||force){
177
+ closeCacheDbs();
178
+ const backup=fs.existsSync(targetFile)?`${targetDir}.bak-${Date.now()}.sqlite`:null;
179
+ if(backup)fs.renameSync(targetFile,backup);
180
+ for(const suffix of ['-wal','-shm'])fs.rmSync(targetFile+suffix,{force:true});
181
+ try{fs.renameSync(file,targetFile)}catch(error){if(backup)fs.renameSync(backup,targetFile);throw error}
182
+ if(backup&&force)fs.rmSync(backup,{force:true});
183
+ return {dir:targetDir,mode:'replace',stats:{added:1,updated:0,merged:0,kept:0,skipped:[]}};
184
+ }
185
+ onProgress?.({phase:'merging'});mergeDatabase(targetFile,file);
186
+ return {dir:targetDir,mode:'merge',stats:{added:0,updated:0,merged:1,kept:0,skipped:[]}};
187
+ }finally{fs.rmSync(stage,{recursive:true,force:true})}
188
+ }
189
+ async function exportCache(destination,{sourceDir=require('./cache-directory').getCacheDir(),proxyOrigin,project=null}={}){
190
+ const stage=fs.mkdtempSync(path.join(os.tmpdir(),'vigievuln-sqlite-export-'));
191
+ const root=path.join(stage,'.vigie-vuln');fs.mkdirSync(root);
192
+ try{
193
+ if(project)require('./airgap-project').buildProjectSnapshot(sourceDir,root,project);
194
+ else {
195
+ const source=openCacheDb({cacheDir:sourceDir});
196
+ try{source.prepare('VACUUM INTO ?').run(path.join(root,'cache.sqlite'))}finally{source.close()}
197
+ }
198
+ const file=path.join(root,'cache.sqlite');verifyStandaloneSnapshot(file);verifyDb(file);
199
+ const payload={file:'cache.sqlite',bytes:fs.statSync(file).size,sha256:await sha256(file)};
200
+ fs.writeFileSync(path.join(root,'cli-bundle-meta.json'),JSON.stringify({format:FORMAT,schemaVersion:SCHEMA_VERSION,minimumCliVersion:'1.2.0',createdAt:new Date().toISOString(),payload}));
201
+ if(proxyOrigin)fs.writeFileSync(path.join(stage,'.vigievuln-archive-origin.json'),JSON.stringify({version:1,origin:canonicalOrigin(proxyOrigin)}));
202
+ const abs=path.resolve(destination);fs.mkdirSync(path.dirname(abs),{recursive:true});
203
+ const temporary=path.join(path.dirname(abs),`.${path.basename(abs)}.${crypto.randomUUID()}.tmp`);
204
+ try {
205
+ // Enumerate exactly the files accepted by the reader. SQLite may create
206
+ // sidecars in a temporary directory; never include them implicitly.
207
+ const args=['-czf',temporary,'-C',stage,'.vigie-vuln/cache.sqlite','.vigie-vuln/cli-bundle-meta.json'];if(proxyOrigin)args.push('.vigievuln-archive-origin.json');
208
+ await run('tar',args,{maxBuffer:64*1024});
209
+ verifyStandaloneSnapshot(file);
210
+ fs.renameSync(temporary,abs);
211
+ } finally {fs.rmSync(temporary,{force:true})}
212
+ return {path:abs,size:fs.statSync(abs).size,excluded:['config.json'],scope:project?'project':'full'};
213
+ }finally{fs.rmSync(stage,{recursive:true,force:true})}
214
+ }
215
+ module.exports={importCache,exportCache,mergeDatabase,FORMAT};