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,268 @@
1
+ 'use strict';
2
+ // Native CVE and GCVE envelopes for the shared store. Legacy indexes remain
3
+ // separate: they cannot establish withdrawals or native-source completeness.
4
+ const fs = require('node:fs');
5
+ const path = require('node:path');
6
+ const MAX_RECORD = 16 * 1024 * 1024;
7
+
8
+ function explicitNpmPackage(affected) {
9
+ const p=require('./gcve-index').explicitPackage(affected);
10
+ if(p?.ecosystem==='npm')return p;
11
+ if(affected?.packageURL!=null || affected?.purl!=null)return null;
12
+ // Some CNA records use a package name with an explicit npm registry
13
+ // collection instead of a PURL. A bare product/name is not sufficient.
14
+ const name=affected?.packageName,url=affected?.collectionURL;
15
+ if(typeof name==='string' && /^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/.test(name) &&
16
+ typeof url==='string' && /^https:\/\/(?:registry\.npmjs\.org\/?|www\.npmjs\.com\/package\/?)$/.test(url))
17
+ return {ecosystem:'npm',name};
18
+ return null;
19
+ }
20
+
21
+ function cveEnvelope(raw, { fetchedAt, provenance = {transport:'direct'} } = {}) {
22
+ const id = raw?.cveMetadata?.cveId;
23
+ if (!/^CVE-\d{4}-\d{4,}$/i.test(String(id || '')) || !['PUBLISHED','REJECTED','RESERVED'].includes(raw?.cveMetadata?.state)) throw new Error('invalid native CVEProject record');
24
+ const packages = [];
25
+ if (raw.cveMetadata.state === 'PUBLISHED') {
26
+ const projected = require('./cve-download').extractMavenRelevantCve(raw);
27
+ for (const a of projected?.affected || []) {
28
+ for (const name of (a.packageNames || [])) packages.push({ecosystem:'Maven',name});
29
+ if (a.product) packages.push({ecosystem:'CVEProduct',name:String(a.product).toLowerCase()});
30
+ }
31
+ // Preserve only explicitly typed npm package identities. Product names do
32
+ // not establish that an arbitrary npm package is the affected component.
33
+ for (const container of [raw.containers?.cna,...(Array.isArray(raw.containers?.adp)?raw.containers.adp:[])])
34
+ for (const affected of (Array.isArray(container?.affected)?container.affected:[])) {
35
+ const p=explicitNpmPackage(affected);
36
+ if (p) packages.push(p);
37
+ }
38
+ }
39
+ return {source:'cveproject',id:id.toUpperCase(),document:raw,fetchedAt,provenance,packages};
40
+ }
41
+ function gcveEnvelope(stored, { provenance = {transport:'direct'} } = {}) {
42
+ const {identity,explicitPackage}=require('./gcve-index');
43
+ const raw=stored?.raw, ident=identity(raw,stored?.gna), at=Date.parse(stored.collectedAt);
44
+ if (!Number.isSafeInteger(at) || at <= 0 || at > Date.now()+300000) throw new Error('invalid GCVE collection date');
45
+ const packages=[];
46
+ if (ident.recordType === 'advisory' && raw?.cveMetadata?.state === 'PUBLISHED') for (const a of raw?.containers?.cna?.affected || []) {
47
+ const p=explicitPackage(a);if (p) packages.push(p);
48
+ }
49
+ return {source:'gcve',id:ident.id,document:raw,fetchedAt:at,provenance:{...provenance,gna:ident.gna,sourceUrl:stored.sourceUrl || null},packages};
50
+ }
51
+ async function importGcveIndex(store,index,{provenance={transport:'direct'}}={}) {
52
+ if (!index || !Array.isArray(index.records) || !Array.isArray(index.coverage)) throw new Error('invalid GCVE index');
53
+ const times=index.coverage.map(c=>Date.parse(c.collectedAt));
54
+ if (!times.length || times.some(t=>!Number.isSafeInteger(t) || t<=0 || t>Date.now()+300000)) throw new Error('invalid GCVE coverage');
55
+ // Per-GNA membership is reconciled below. Global completeness remains
56
+ // partial because removed or uncollected GNAs have no absence proof.
57
+ const fetchedAt=Math.min(...times), complete=false;
58
+ // An independently timestamped membership proof per GNA establishes absence
59
+ // without fabricating a REJECTED record or deleting its native document.
60
+ const snapshots=new Map();
61
+ for (const c of index.coverage) {
62
+ if (!Number.isSafeInteger(c.gna) || c.gna<0 || snapshots.has(c.gna)) throw new Error('invalid GCVE GNA coverage');
63
+ snapshots.set(c.gna,{coverage:c,ids:new Set(),valid:true});
64
+ }
65
+ function* entries() {
66
+ for (const record of index.records) {
67
+ const envelope=gcveEnvelope(record,{provenance}), snapshot=snapshots.get(record.gna);
68
+ if (!snapshot) throw new Error('GCVE record has no GNA coverage');
69
+ if (Date.parse(record.collectedAt)!==Date.parse(snapshot.coverage.collectedAt) || record.sourceUrl !== snapshot.coverage.sourceUrl || snapshot.ids.has(envelope.id)) snapshot.valid=false;
70
+ snapshot.ids.add(envelope.id);yield envelope;
71
+ }
72
+ for (const [gna,snapshot] of snapshots) {
73
+ const c=snapshot.coverage;
74
+ if (!index.directory?.verified || typeof c.sourceUrl !== 'string' || !c.sourceUrl || !snapshot.valid || c.complete!==true || !Number.isSafeInteger(c.records) || c.records!==snapshot.ids.size) continue;
75
+ const document={id:`gna:${gna}`,gna,ids:[...snapshot.ids]};
76
+ if (Buffer.byteLength(JSON.stringify(document))>8*1024*1024) continue;
77
+ yield {source:'gcve-snapshot',id:document.id,document,fetchedAt:Date.parse(c.collectedAt),provenance:{...provenance,gna,sourceUrl:c.sourceUrl || null}};
78
+ }
79
+ }
80
+ await store.importEnvelopes(entries(),{coverages:[{source:'gcve',ecosystem:'*',fetchedAt,complete,provenance}]});
81
+ return {count:index.records.length,complete};
82
+ }
83
+ async function importCveDirectory(store, root, {fetchedAt=Date.now(),provenance={transport:'direct'}}={}) {
84
+ async function* entries() {
85
+ const dirs=[root];
86
+ while (dirs.length) {
87
+ const dir=dirs.pop();
88
+ for (const entry of await fs.promises.readdir(dir,{withFileTypes:true})) {
89
+ const file=path.join(dir,entry.name);
90
+ if (entry.isDirectory()) dirs.push(file);
91
+ else if (entry.isFile() && /^CVE-\d{4}-\d{4,}\.json$/i.test(entry.name)) {
92
+ const stat=await fs.promises.stat(file);if(stat.size>MAX_RECORD) throw new Error('CVEProject record exceeds size limit');
93
+ const raw=JSON.parse(await fs.promises.readFile(file,'utf8'));
94
+ if (raw?.cveMetadata?.cveId?.toLowerCase() !== entry.name.slice(0,-5).toLowerCase()) throw new Error('CVEProject record filename mismatch');
95
+ yield cveEnvelope(raw,{fetchedAt,provenance});
96
+ }
97
+ }
98
+ }
99
+ }
100
+ // This import cannot prove that absent historical records were withdrawn.
101
+ return store.importEnvelopes(entries(),{coverages:[{source:'cveproject',ecosystem:'*',fetchedAt,complete:false,provenance}]});
102
+ }
103
+ module.exports={cveEnvelope,gcveEnvelope,importGcveIndex,importCveDirectory,explicitNpmPackage};
104
+
105
+ function projectedCveEnvelope(document, fetchedAt, provenance = {transport:'proxy'}) {
106
+ if (!document || !/^CVE-\d{4}-\d{4,}$/i.test(String(document.id || '')) || !Array.isArray(document.affected)) throw new Error('invalid projected CVEProject record');
107
+ const packages=[];
108
+ for (const affected of document.affected) {
109
+ for (const name of (affected.packageNames || (affected.packageName ? [affected.packageName] : []))) packages.push({ecosystem:'Maven',name});
110
+ if (affected.product) packages.push({ecosystem:'CVEProduct',name:String(affected.product).toLowerCase()});
111
+ }
112
+ return {source:'cveproject-legacy',id:document.id.toUpperCase(),document,fetchedAt,provenance,packages};
113
+ }
114
+ module.exports.projectedCveEnvelope=projectedCveEnvelope;
115
+
116
+ /** Match native CVEProject records first; legacy projections never resurrect an ID
117
+ * for which any native revision or rejection is known. Legacy lacks per-record
118
+ * revision stamps, so its coverage remains explicitly partial. */
119
+ function matchCveStore(deps, store, legacyIndex = null) {
120
+ const {newIndex,addToIndex,extractMavenRelevantCve}=require('./cve-download');
121
+ const {matchDepsAgainstCves}=require('./cve-match');
122
+ const index=newIndex(), legacyStoreIndex=newIndex(), seen=new Set(), legacySeen=new Set();
123
+ for (const dep of deps.values()) {
124
+ if ((dep.ecosystem && dep.ecosystem !== 'maven') || dep.provenance === 'binary') continue;
125
+ const group=dep.groupId || dep.namespace, artifact=dep.artifactId || dep.name;
126
+ if (!group || !artifact) continue;
127
+ const candidates=[...store.getPackageRecords('Maven',`${group}:${artifact}`,{source:'cveproject'}),
128
+ ...store.getPackageRecords('CVEProduct',String(artifact).toLowerCase(),{source:'cveproject'})];
129
+ for (const record of candidates) {
130
+ if (seen.has(record.id)) continue;
131
+ seen.add(record.id);
132
+ const cve=extractMavenRelevantCve(record.document);if(cve)addToIndex(index,cve);
133
+ }
134
+ const projected=[...store.getPackageRecords('Maven',`${group}:${artifact}`,{source:'cveproject-legacy'}),
135
+ ...store.getPackageRecords('CVEProduct',String(artifact).toLowerCase(),{source:'cveproject-legacy'})];
136
+ for (const record of projected) if(!legacySeen.has(record.id)) {legacySeen.add(record.id);addToIndex(legacyStoreIndex,record.document);}
137
+ }
138
+ const uncertain = [], capture = {onUncertain:m=>uncertain.push(m)};
139
+ const legacyMatches=[...matchDepsAgainstCves(deps,legacyStoreIndex,capture), ...(legacyIndex ? matchDepsAgainstCves(deps,legacyIndex,capture) : [])];
140
+ // A product/vendor legacy candidate may point to a native record that has no
141
+ // package binding. Project that record before suppressing the legacy match.
142
+ const survivingLegacy=[];
143
+ // An uncertain legacy projection can still identify a native record with an
144
+ // explicit coordinate. Inspect it, but never promote the projection itself.
145
+ for (const match of [...legacyMatches, ...uncertain]) {
146
+ const native=store.getRecord('cveproject',match.cve.id);
147
+ if (!native) {if(match.confidence !== 'possible') survivingLegacy.push(match);continue;}
148
+ if (seen.has(native.id) || native.document.cveMetadata?.state !== 'PUBLISHED') continue;
149
+ seen.add(native.id);
150
+ const cve=extractMavenRelevantCve(native.document);if(cve)addToIndex(index,cve);
151
+ }
152
+ const candidates=matchDepsAgainstCves(deps,index,capture).concat(survivingLegacy), ids=new Set();
153
+ const matches=candidates.filter(m=>{const k=`${m.dep.coordKey}:${m.dep.version}|${m.cve.id}`;if(ids.has(k))return false;ids.add(k);return true;});
154
+ return {matches,coverage:store.getSourceCoverage('cveproject','*'),legacy:survivingLegacy.length > 0,
155
+ identityUncertain:uncertain.length > 0,uncertainCandidates:uncertain};
156
+ }
157
+ module.exports.matchCveStore=matchCveStore;
158
+
159
+ // A CNA sometimes labels ordinary npm release bounds "custom". For a
160
+ // version strictly above every affected upper bound, a matching independent
161
+ // OSV advisory can corroborate the negative without changing CVE semantics.
162
+ function corroboratedNpmNegative(store, record, name, version, entries) {
163
+ const compare=require('./osv-db').compareSemver;
164
+ if (!entries.length || entries.some(a => a.platforms?.length || a.defaultStatus !== 'unaffected' ||
165
+ !Array.isArray(a.versions) || !a.versions.length || a.versions.some(v =>
166
+ !v || v.status !== 'affected' || String(v.versionType || '').toLowerCase() !== 'custom' ||
167
+ v.changes?.length || (!!v.lessThan === !!v.lessThanOrEqual) ||
168
+ compare(String(version), String(v.lessThan || v.lessThanOrEqual)) !== 1))) return false;
169
+ const {packageName}=require('./advisory-store'), {vulnVerdict}=require('./osv-db');
170
+ const docs=store.getPackageRecords('npm',name,{source:'osv'}).filter(item => {
171
+ const doc=item.document;
172
+ return !item.withdrawnAt && !doc?.withdrawn && [doc?.id,...(doc?.aliases || [])].includes(record.id);
173
+ });
174
+ if(!docs.length)return false;
175
+ return docs.every(({document}) => {
176
+ const affected=(document.affected || []).filter(a => a?.package?.ecosystem==='npm' &&
177
+ typeof a.package.name==='string' && packageName('npm',a.package.name)===packageName('npm',name));
178
+ return affected.length > 0 && vulnVerdict(String(version),{...document,affected},'npm') === false;
179
+ });
180
+ }
181
+
182
+ /** Match explicit npm PURLs in native CVEProject records. A missing package
183
+ * or undecidable range is never interpreted as proof that it is unaffected. */
184
+ function matchNativeNpmCves(deps, store) {
185
+ const {extractAffectedRanges}=require('./cve-download');
186
+ const {affectedVerdict}=require('./cve-version-verdict');
187
+ const {osvPkgName}=require('./osv');
188
+ const {packageName}=require('./advisory-store');
189
+ const matches=[], unknown=[], seen=new Set();
190
+ for(const dep of deps.values()) {
191
+ if(!['npm','yarn'].includes(dep.ecosystem) || dep.provenance==='binary')continue;
192
+ const name=osvPkgName(dep);if(!name)continue;
193
+ const consulted=store.getQuery({source:'cveproject',ecosystem:'npm',name,version:'*'},{ttlMs:Number.MAX_SAFE_INTEGER});
194
+ for(const record of store.getPackageRecords('npm',name,{source:'cveproject'})) {
195
+ // A later complete package consultation proves that the old record no
196
+ // longer applies to this package; preserve a newer native update instead.
197
+ if(consulted && consulted.provenance?.stale!==true && consulted.fetchedAt >= (record.contentChangedAt || record.fetchedAt) && !consulted.ids.includes(record.id))continue;
198
+ const raw=record.document;if(raw?.cveMetadata?.state!=='PUBLISHED')continue;
199
+ const containers=[raw.containers?.cna,...(Array.isArray(raw.containers?.adp)?raw.containers.adp:[])];
200
+ const entries=containers.flatMap(c=>(Array.isArray(c?.affected)?c.affected:[])).filter(a=>{
201
+ const p=explicitNpmPackage(a);return p && packageName('npm',p.name)===packageName('npm',name);
202
+ });
203
+ if(!entries.length)continue;
204
+ for(const ver of dep.versions?.length?dep.versions:[dep.version]) {
205
+ if(!ver)continue;
206
+ const key=`${dep.coordKey||name}|${ver}|${record.id}`;if(seen.has(key))continue;
207
+ const results=entries.map(a=>{
208
+ // Version semantics and platform restrictions must be explicit.
209
+ if((a.platforms?.length) || !Array.isArray(a.versions) || a.versions.some(v=>
210
+ !v || (v.versionType && String(v.versionType).toLowerCase()!=='semver') ||
211
+ (!v.versionType && (v.lessThan!=null || v.lessThanOrEqual!=null))))return null;
212
+ const projected=extractAffectedRanges([a])[0];
213
+ return affectedVerdict(String(ver),projected.ranges,projected.defaultStatus);
214
+ });
215
+ if(results.some(x=>x===null) || (results.includes(true)&&results.includes(false))) {
216
+ if(!corroboratedNpmNegative(store,record,name,ver,entries)) unknown.push({id:record.id,package:name,version:ver});
217
+ continue;
218
+ }
219
+ if(!results.includes(true))continue;
220
+ seen.add(key);
221
+ const cna=raw.containers?.cna || {},descriptions=Array.isArray(cna.descriptions)?cna.descriptions:[],description=descriptions.find(d=>String(d?.lang||'').startsWith('en'))?.value || descriptions[0]?.value || '';
222
+ let score=null,severity='UNKNOWN',cvssVector=null;
223
+ for(const c of containers){for(const m of (Array.isArray(c?.metrics)?c.metrics:[])){const v=m?.cvssV3_1||m?.cvssV3_0||m?.cvssV4_0||m?.cvssV2_0;if(typeof v?.baseScore==='number'&&v.baseScore>=0&&v.baseScore<=10){score=v.baseScore;severity=String(v.baseSeverity|| (score>=9?'CRITICAL':score>=7?'HIGH':score>=4?'MEDIUM':score>0?'LOW':'NONE')).toUpperCase();cvssVector=v.vectorString||null;break;}}if(score!==null)break;}
224
+ matches.push({dep:ver===dep.version?dep:{...dep,version:ver},source:'CVEProject',confidence:'exact',cve:{id:record.id,description:String(description),severity,score,cvssVector,published:raw.cveMetadata.datePublished||null,modified:raw.cveMetadata.dateUpdated||null,fixVersion:null,fixEvaluation:'unknown'}});
225
+ }
226
+ }
227
+ }
228
+ return {matches,unknown};
229
+ }
230
+ module.exports.matchNativeNpmCves=matchNativeNpmCves;
231
+
232
+ /** Use the existing GCVE matcher on native candidates and filter legacy IDs
233
+ * superseded by any native revision, including rejected records. */
234
+ function matchGcveStore(deps, store, legacyIndex = null) {
235
+ const {buildGcveIndex,matchGcveDeps}=require('./gcve-index');
236
+ const {osvEcosystemFor,osvPkgName}=require('./osv');
237
+ const native=new Map();
238
+ for (const dep of deps.values()) {
239
+ if (dep.provenance === 'binary') continue;
240
+ const ecosystem=osvEcosystemFor(dep),name=osvPkgName(dep);if(!ecosystem || !name)continue;
241
+ for (const record of store.getPackageRecords(ecosystem,name,{source:'gcve'})) native.set(record.id,record);
242
+ }
243
+ const grouped=new Map(), snapshotCache=new Map();
244
+ for (const record of native.values()) {
245
+ const gna=record.provenance?.gna, sourceUrl=record.provenance?.sourceUrl;
246
+ if (!Number.isSafeInteger(gna)) throw new Error('GCVE record has no GNA provenance');
247
+ if (!snapshotCache.has(gna)) {
248
+ const proof=store.getRecord('gcve-snapshot',`gna:${gna}`);
249
+ snapshotCache.set(gna,proof ? {proof,ids:Array.isArray(proof.document.ids) ? new Set(proof.document.ids) : null} : null);
250
+ }
251
+ const cached=snapshotCache.get(gna), snapshot=cached?.proof;
252
+ const observed=Math.max(record.fetchedAt,...(record.observations || []).map(o=>o.fetchedAt).filter(Number.isFinite));
253
+ if (snapshot && snapshot.provenance?.gna===gna && sourceUrl && snapshot.provenance.sourceUrl===sourceUrl && snapshot.fetchedAt>observed && cached.ids && !cached.ids.has(record.id)) continue;
254
+ if (!grouped.has(gna)) grouped.set(gna,{gna,sourceUrl,collectedAt:new Date(record.fetchedAt).toISOString(),complete:false,records:[]});
255
+ grouped.get(gna).records.push(record.document);
256
+ }
257
+ const index=buildGcveIndex([...grouped.values()]);
258
+ const result=matchGcveDeps(deps,index);
259
+ if (legacyIndex) {
260
+ const legacy=matchGcveDeps(deps,legacyIndex);
261
+ result.matches.push(...legacy.matches.filter(m=>!store.getRecord('gcve',m.cve.gcve)));
262
+ result.unknown.push(...legacy.unknown.filter(m=>!store.getRecord('gcve',m.id)));
263
+ result.coverage=legacy.coverage;
264
+ } else result.coverage=[];
265
+ result.sourceCoverage=store.getSourceCoverage('gcve','*');
266
+ return result;
267
+ }
268
+ module.exports.matchGcveStore=matchGcveStore;
@@ -0,0 +1,145 @@
1
+ 'use strict';
2
+
3
+ // Optional compact NVD enrichment snapshots. The traditional per-CVE cache is
4
+ // still read and written separately. Each immutable generation is sharded so
5
+ // one lookup does not parse the entire mirror.
6
+ const fs = require('node:fs');
7
+ const path = require('node:path');
8
+ const crypto = require('node:crypto');
9
+ const hash = value => crypto.createHash('sha256').update(value).digest('hex');
10
+ const shardName = id => hash(id).slice(0, 2) + '.json';
11
+ const cached = new Map();
12
+ const MAX_CACHED_SHARDS = 4;
13
+ const MAX_SHARD_BYTES = 64 * 1024 * 1024;
14
+ const MAX_MANIFEST_BYTES = 128 * 1024;
15
+
16
+ function shard(root, generation, manifest, name) {
17
+ const expected = manifest.shards?.[name];
18
+ if (typeof expected !== 'string' || !/^[a-f0-9]{64}$/.test(expected)) return null;
19
+ const file = path.join(root, generation, name), cacheKey = file + ':' + expected;
20
+ if (cached.has(cacheKey)) { const item = cached.get(cacheKey); cached.delete(cacheKey); cached.set(cacheKey,item); return item; }
21
+ try {
22
+ if (fs.statSync(file).size > MAX_SHARD_BYTES) return null;
23
+ const bytes = fs.readFileSync(file);
24
+ if (hash(bytes) !== expected) return null;
25
+ const data = JSON.parse(bytes.toString('utf8'));
26
+ if (!data || typeof data !== 'object' || Array.isArray(data)) return null;
27
+ cached.set(cacheKey,data);
28
+ while (cached.size > MAX_CACHED_SHARDS) cached.delete(cached.keys().next().value);
29
+ return data;
30
+ } catch { return null; }
31
+ }
32
+
33
+ function readBulk(cacheDir, id) {
34
+ if (!/^CVE-\d{4}-\d{4,}$/i.test(id)) return null;
35
+ const root = path.join(cacheDir, '_bulk'); let names;
36
+ try { names = fs.readdirSync(root).filter(x => /^\d{10,16}-[a-f0-9]{64}$/.test(x)).sort().reverse(); }
37
+ catch { return null; }
38
+ for (const name of names) {
39
+ try {
40
+ const manifestFile=path.join(root,name,'manifest.json');
41
+ if (fs.statSync(manifestFile).size > MAX_MANIFEST_BYTES) continue;
42
+ const bytes = fs.readFileSync(manifestFile);
43
+ if (hash(bytes) !== name.split('-')[1]) continue;
44
+ const meta = JSON.parse(bytes.toString('utf8'));
45
+ if (meta.schema !== 1 || !Number.isSafeInteger(meta.fetchedAt) || meta.fetchedAt <= 0 || meta.fetchedAt > Date.now()+300000 || String(meta.fetchedAt) !== name.split('-')[0]) continue;
46
+ const data = shard(root,name,meta,shardName(id)), body = data?.[id];
47
+ if (body && typeof body === 'object' && !Array.isArray(body) && body.id === id) return {_schema:1,_fetchedAt:meta.fetchedAt,body};
48
+ } catch { /* Invalid generation cannot establish a cache hit. */ }
49
+ }
50
+ return null;
51
+ }
52
+
53
+ // Validate metadata without loading record shards. The generation name is
54
+ // content-addressed; an explicit name is needed for staged atomic imports.
55
+ function readManifest(dir, generationName = path.basename(dir)) {
56
+ if (!/^\d{10,16}-[a-f0-9]{64}$/.test(generationName)) throw new Error('invalid compact NVD generation name');
57
+ const manifestFile=path.join(dir,'manifest.json');
58
+ if (!fs.statSync(dir).isDirectory() || fs.statSync(manifestFile).size > MAX_MANIFEST_BYTES) throw new Error('invalid compact NVD manifest');
59
+ const bytes=fs.readFileSync(manifestFile);
60
+ if (hash(bytes)!==generationName.split('-')[1]) throw new Error('compact NVD manifest checksum mismatch');
61
+ const meta=JSON.parse(bytes.toString('utf8'));
62
+ if (meta?.schema!==1 || !Number.isSafeInteger(meta.fetchedAt) || meta.fetchedAt<=0 || meta.fetchedAt>Date.now()+300000 || String(meta.fetchedAt)!==generationName.split('-')[0] || !Number.isSafeInteger(meta.count) || meta.count<0 || !meta.shards || typeof meta.shards!=='object' || Array.isArray(meta.shards)) throw new Error('invalid compact NVD manifest');
63
+ const names=Object.keys(meta.shards);
64
+ if(names.length>256 || names.some(k=>!/^[a-f0-9]{2}\.json$/.test(k) || !/^[a-f0-9]{64}$/.test(meta.shards[k]))) throw new Error('invalid compact NVD shard list');
65
+ return meta;
66
+ }
67
+
68
+ function validateGeneration(dir, generationName = path.basename(dir)) {
69
+ const meta=readManifest(dir,generationName),names=Object.keys(meta.shards),actual=fs.readdirSync(dir);
70
+ if(actual.length!==names.length+1 || actual.some(k=>k!=='manifest.json' && !Object.hasOwn(meta.shards,k))) throw new Error('unexpected compact NVD snapshot file');
71
+ let total=0;
72
+ for(const shardFile of names) {
73
+ const file=path.join(dir,shardFile);
74
+ if(!fs.statSync(file).isFile() || fs.statSync(file).size>MAX_SHARD_BYTES)throw new Error('invalid compact NVD shard');
75
+ const raw=fs.readFileSync(file);
76
+ if(hash(raw)!==meta.shards[shardFile]) throw new Error('compact NVD shard checksum mismatch');
77
+ const entries=JSON.parse(raw.toString('utf8'));
78
+ if(!entries || typeof entries!=='object' || Array.isArray(entries)) throw new Error('invalid compact NVD shard');
79
+ for(const [id,body] of Object.entries(entries)) {
80
+ if(!/^CVE-\d{4}-\d{4,}$/.test(id) || shardName(id)!==shardFile || !body || typeof body!=='object' || Array.isArray(body) || body.id!==id) throw new Error('invalid compact NVD record');
81
+ total++;
82
+ }
83
+ }
84
+ if(total!==meta.count) throw new Error('compact NVD record count mismatch');
85
+ return {records:total,fetchedAt:meta.fetchedAt};
86
+ }
87
+
88
+ // Validate every input before an archive import can modify its target cache.
89
+ // This is intentionally independent of the lazy read cache.
90
+ function validateAll(cacheDir) {
91
+ const root=path.join(cacheDir,'_bulk');
92
+ if (!fs.existsSync(root)) return {generations:0,records:0};
93
+ if (!fs.statSync(root).isDirectory()) throw new Error('invalid compact NVD snapshot directory');
94
+ let generations=0, records=0;
95
+ for (const name of fs.readdirSync(root)) { const entry=validateGeneration(path.join(root,name),name); generations++;records+=entry.records; }
96
+ return {generations,records};
97
+ }
98
+
99
+ // This summary establishes only timestamp/count from valid metadata; lookup
100
+ // verifies the corresponding shard checksum before trusting any advisory.
101
+ function snapshotSummary(cacheDir) {
102
+ const root=path.join(cacheDir,'_bulk');let names;
103
+ try { names=fs.readdirSync(root); } catch {return null;}
104
+ let count=0,oldestFetchedAt=Infinity,newestFetchedAt=0,newestRecordCount=0;
105
+ for(const name of names) try {
106
+ const meta=readManifest(path.join(root,name),name);count++;
107
+ oldestFetchedAt=Math.min(oldestFetchedAt,meta.fetchedAt);
108
+ if(meta.fetchedAt>newestFetchedAt){newestFetchedAt=meta.fetchedAt;newestRecordCount=meta.count;}
109
+ } catch { /* Invalid metadata is not a source observation. */ }
110
+ return count ? {count,oldestFetchedAt,newestFetchedAt,newestRecordCount} : null;
111
+ }
112
+
113
+ // Writer is used by the server export job. The generation name incorporates
114
+ // the manifest hash, making it immutable and safe to merge with older seeds.
115
+ function createWriter(cacheDir, fetchedAt) {
116
+ if (!Number.isSafeInteger(fetchedAt) || fetchedAt <= 0 || fetchedAt > Date.now()+300000) throw new Error('invalid NVD snapshot time');
117
+ const root = path.join(cacheDir,'_bulk'); fs.mkdirSync(root,{recursive:true});
118
+ const tmp = fs.mkdtempSync(path.join(root,'.build-'));
119
+ const writers = new Map(); let count=0, finished=false;
120
+ return {
121
+ add(id, body) {
122
+ if (finished || !/^CVE-\d{4}-\d{4,}$/.test(id) || !body || body.id !== id) throw new Error('invalid NVD snapshot record');
123
+ const name = shardName(id); let item = writers.get(name);
124
+ if (!item) { item = {fd:fs.openSync(path.join(tmp,name),'wx',0o600),first:true,bytes:1}; writers.set(name,item); fs.writeFileSync(item.fd,'{'); }
125
+ const line=(item.first?'':',') + JSON.stringify(id) + ':' + JSON.stringify(body);
126
+ item.bytes+=Buffer.byteLength(line);
127
+ if (item.bytes + 1 > MAX_SHARD_BYTES) throw new Error('NVD snapshot shard exceeds size limit');
128
+ fs.writeFileSync(item.fd,line); item.first=false; count++;
129
+ },
130
+ finish() {
131
+ if (finished) throw new Error('NVD snapshot already finished'); finished=true;
132
+ try {
133
+ const shards={};
134
+ for (const [name,item] of writers) { fs.writeFileSync(item.fd,'}'); fs.closeSync(item.fd); item.fd=null; shards[name]=hash(fs.readFileSync(path.join(tmp,name))); }
135
+ const bytes=Buffer.from(JSON.stringify({schema:1,fetchedAt,count,shards}));
136
+ fs.writeFileSync(path.join(tmp,'manifest.json'),bytes,{flag:'wx',mode:0o600});
137
+ const generation = `${fetchedAt}-${hash(bytes)}`, dest=path.join(root,generation);
138
+ if (fs.existsSync(dest)) fs.rmSync(tmp,{recursive:true,force:true}); else fs.renameSync(tmp,dest);
139
+ return {generation,count};
140
+ } catch (error) { for(const item of writers.values()) if(item.fd!==null)try{fs.closeSync(item.fd)}catch{} fs.rmSync(tmp,{recursive:true,force:true}); throw error; }
141
+ },
142
+ abort() { if(finished)return; finished=true; for(const item of writers.values())try{fs.closeSync(item.fd)}catch{} fs.rmSync(tmp,{recursive:true,force:true}); }
143
+ };
144
+ }
145
+ module.exports = {readBulk,createWriter,shardName,validateAll,validateGeneration,snapshotSummary};
@@ -0,0 +1,109 @@
1
+ 'use strict';
2
+ const {parseCpe23,matchVersionRange,loadCpeCoordMap}=require('./cpe');
3
+
4
+ // NVD now carries native CNA/ADP affected entries independently of its CPEs.
5
+ // Reuse the native normalizer and version evaluator, including exclusions,
6
+ // version changes, platform restrictions and disagreement between providers.
7
+ function projectNvdAffected(record) {
8
+ const {extractAffectedRanges}=require('./cve-download');
9
+ const {normalizeLegacySplitRanges}=require('./cve-legacy-ranges');
10
+ if(!record || !/^CVE-\d{4}-\d+$/.test(record.id || '') || /^rejected$/i.test(record.vulnStatus || ''))return null;
11
+ const affected=[];
12
+ for(const group of Array.isArray(record.affected) ? record.affected : []) {
13
+ if(!group || typeof group.source!=='string' || !group.source || !Array.isArray(group.affectedData))continue;
14
+ const entries=group.affectedData.filter(a=>a && typeof a==='object' && !Array.isArray(a));
15
+ affected.push(...extractAffectedRanges(entries.map(a=>({...normalizeLegacySplitRanges(a,record.description),_affectedProvider:{kind:'nvd-affected',name:group.source}}))));
16
+ }
17
+ return {...record,source:'nvd',affected,fixVersion:null};
18
+ }
19
+
20
+ function matchNvdAffected(deps,matches,opts={}) {
21
+ const {newIndex,addToIndex}=require('./cve-download');
22
+ const {matchDepsAgainstCves}=require('./cve-match');
23
+ const index=newIndex(),seen=new Set(),records=new Map();
24
+ for(const m of matches) {
25
+ const c=m.cve;
26
+ if(!c || seen.has(c.id) || !Array.isArray(c.nvdAffected))continue;
27
+ seen.add(c.id);
28
+ const projected=projectNvdAffected({...c,affected:c.nvdAffected,vulnStatus:c.nvdVulnStatus});
29
+ if(projected){addToIndex(index,projected);records.set(c.id,c);}
30
+ }
31
+ return matchDepsAgainstCves(deps,index,opts).map(m=>{
32
+ const {branchFix,fixVersion,fixEvaluation,...metadata}=records.get(m.cve.id);
33
+ return {...m,cve:{...metadata,...m.cve,identityEvidence:m.cve.coordinateEvidence}};
34
+ });
35
+ }
36
+
37
+ // A package binding is a lookup candidate, NOT a finding. Read the full stored
38
+ // OSV documents independently of whether their ranges match this scan's version.
39
+ // This allows an older release scanned alone to reuse the same NVD evidence as
40
+ // it would in a reactor containing a newer release of that package.
41
+ function collectPackageNvdBindings(deps,store) {
42
+ const out=[],seen=new Set();
43
+ for(const dep of deps.values()) {
44
+ if(dep.ecosystem!=='maven' || dep.provenance==='binary')continue;
45
+ const coord=`${dep.groupId}:${dep.artifactId}`;
46
+ if(seen.has(coord))continue;
47
+ // Native affected entries can name an exact package absent from our CPE map.
48
+ // The CPE-only matcher below still requires its unique curated mapping.
49
+ seen.add(coord);
50
+ const ids=new Set();
51
+ for(const record of store.getPackageRecords('Maven',coord,{source:'osv'})) {
52
+ const document=record.document;
53
+ if(record.source!=='osv' || record.withdrawnAt || !document || document.withdrawn)continue;
54
+ if(!document.affected?.some(a=>a.package?.ecosystem==='Maven' && a.package.name===coord))continue;
55
+ const cves=[...new Set([document.id,...document.aliases||[]].filter(id=>/^CVE-\d{4}-\d+$/.test(id)))];
56
+ // Multi-CVE aggregate advisories don't identify which CVE belongs to which
57
+ // affected entry. Do not manufacture a package binding for every alias.
58
+ if(cves.length!==1 || ids.has(cves[0]))continue;
59
+ ids.add(cves[0]);
60
+ out.push({dep,source:'osv',bindingOnly:true,cve:{id:cves[0]}});
61
+ }
62
+ }
63
+ return out;
64
+ }
65
+
66
+ // Extend version coverage only for a CVE already bound by OSV to this exact
67
+ // Maven artifact. A one-to-one curated CPE must name the artifact itself;
68
+ // framework products, runtime constraints and negated configurations do not qualify.
69
+ function matchBoundNvdRanges(deps,matches,map=loadCpeCoordMap()) {
70
+ const out=[],seen=new Set(matches.filter(m=>!m.bindingOnly).flatMap(m=>[m.cve?.id,...m.cve?.aliases||[]].filter(Boolean).map(id=>`${m.dep?.coordKey}|${m.dep?.version}|${id}`)));
71
+ function leaves(node) {
72
+ if(!node || node.negate || (node.operator && node.operator!=='OR'))return [];
73
+ return [...(node.cpeMatch||[]),...(node.nodes||node.children||[]).flatMap(leaves)];
74
+ }
75
+ for(const match of matches) {
76
+ if(match.suppressed || match.cpeFiltered || !(match.source||'').split('+').includes('osv'))continue;
77
+ const {dep,cve}=match;
78
+ if(dep?.ecosystem!=='maven' || !/^CVE-\d{4}-\d+$/.test(cve?.id||''))continue;
79
+ const coord=`${dep.groupId}:${dep.artifactId}`;
80
+ const ranges=(cve.configurations||[]).flatMap(leaves).filter(r=>{
81
+ const c=parseCpe23(r.criteria||r.cpe23Uri);
82
+ if(r.vulnerable !== true || !c || c.part!=='a' || c.product!==dep.artifactId)return false;
83
+ const mapping=map.byVendorProduct?.[`${c.vendor}:${c.product}`];
84
+ if(mapping?.length!==1 || mapping[0]!==coord)return false;
85
+ // Unmodelled CPE qualifiers can restrict applicability to a deployment.
86
+ const fields=(r.criteria||r.cpe23Uri).split(':');
87
+ if(fields.length!==13 || fields.slice(6).some(x=>x!=='*'))return false;
88
+ if(['versionStartIncluding','versionStartExcluding','versionEndIncluding','versionEndExcluding'].some(k=>r[k]!=null && !/^[0-9][A-Za-z0-9._+-]*$/.test(r[k])))return false;
89
+ return true;
90
+ });
91
+ if(!ranges.length)continue;
92
+ for(const d of deps.values()) {
93
+ if(d.ecosystem!=='maven' || `${d.groupId}:${d.artifactId}`!==coord || d.provenance==='binary')continue;
94
+ for(const version of d.versions?.length?d.versions:[d.version]) {
95
+ if(typeof version!=='string' || !/^[0-9][A-Za-z0-9._+-]*$/.test(version))continue;
96
+ const key=`${d.coordKey}|${version}|${cve.id}`;
97
+ if(seen.has(key) || !ranges.some(r=>matchVersionRange(version,r)))continue;
98
+ seen.add(key);
99
+ out.push({dep:{...d,version},confidence:'exact',source:'nvd',cve:{
100
+ id:cve.id,description:cve.description,severity:cve.severity,score:cve.score,
101
+ configurations:cve.configurations,fixVersion:null,fixEvaluation:'unknown',
102
+ identityEvidence:'OSV package binding and unique artifact CPE'
103
+ }});
104
+ }
105
+ }
106
+ }
107
+ return out;
108
+ }
109
+ module.exports={matchBoundNvdRanges,collectPackageNvdBindings,projectNvdAffected,matchNvdAffected};