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.
- package/CHANGELOG.md +25 -0
- package/README.md +51 -141
- package/completions/vigievuln.bash +1 -1
- package/completions/vigievuln.zsh +1 -0
- package/lib/account-client.js +21 -14
- package/lib/account-session.js +6 -2
- package/lib/advisory-compression.js +25 -0
- package/lib/advisory-fixes.js +21 -0
- package/lib/advisory-store-sqlite.js +156 -0
- package/lib/advisory-store.js +484 -0
- package/lib/airgap-project.js +117 -0
- package/lib/application-plugins/runner.js +22 -13
- package/lib/application-plugins/wordpress.js +4 -3
- package/lib/application-providers/live-snapshot.js +1 -12
- package/lib/application-providers/snapshot-cache.js +27 -0
- package/lib/application-providers/wordfence-client.js +3 -3
- package/lib/attribution.js +2 -2
- package/lib/cache-archive-sqlite.js +215 -0
- package/lib/cache-archive.js +357 -26
- package/lib/cache-db.js +142 -0
- package/lib/cache-directory.js +18 -74
- package/lib/cache-policy.js +25 -0
- package/lib/cache-repository.js +48 -0
- package/lib/cache-startup.js +54 -0
- package/lib/certfr.js +9 -9
- package/lib/cli-command-routing.js +29 -6
- package/lib/cli-groups.js +32 -3
- package/lib/cli-project-commands.js +47 -6
- package/lib/cli-setup.js +300 -0
- package/lib/codecs/binary/pe-metadata.js +79 -0
- package/lib/codecs/binary/scan.js +4 -3
- package/lib/codecs/binary.codec.js +4 -2
- package/lib/codecs/composer/registry.js +8 -6
- package/lib/codecs/go/parse.js +7 -9
- package/lib/codecs/go/registry.js +7 -5
- package/lib/codecs/go.codec.js +5 -0
- package/lib/codecs/maven.codec.js +73 -8
- package/lib/codecs/npm/collect.js +12 -5
- package/lib/codecs/npm/parse.js +12 -5
- package/lib/codecs/npm/registry.js +42 -12
- package/lib/codecs/nuget/registry.js +8 -6
- package/lib/codecs/pypi/registry.js +8 -6
- package/lib/codecs/ruby/registry.js +7 -5
- package/lib/compression-dictionary.js +5 -0
- package/lib/coverage-diagnostics.js +26 -0
- package/lib/cve-download.js +157 -41
- package/lib/cve-legacy-ranges.js +59 -0
- package/lib/cve-match.js +85 -17
- package/lib/cve-npm-proxy.js +29 -0
- package/lib/cve-report.js +145 -58
- package/lib/cve-version-verdict.js +77 -0
- package/lib/deps-descriptor.js +8 -3
- package/lib/epss.js +13 -8
- package/lib/euvd.js +32 -8
- package/lib/gcve-feed.js +103 -0
- package/lib/gcve-index.js +181 -0
- package/lib/gcve.js +1 -1
- package/lib/github-publisher-maven.js +40 -0
- package/lib/hash-id.js +5 -5
- package/lib/hosted-proxy.js +6 -1
- package/lib/i18n.js +31 -8
- package/lib/json-cache.js +18 -0
- package/lib/json-export.js +16 -2
- package/lib/kev.js +7 -8
- package/lib/line-stream.js +23 -0
- package/lib/maven-airgap.js +80 -0
- package/lib/maven-cache.js +21 -0
- package/lib/maven-license.js +2 -1
- package/lib/maven-presence.js +2 -2
- package/lib/maven-reactor.js +23 -14
- package/lib/maven-repo.js +11 -6
- package/lib/merge-sources.js +25 -18
- package/lib/native-advisories.js +268 -0
- package/lib/nvd-bulk.js +145 -0
- package/lib/nvd-package-ranges.js +109 -0
- package/lib/nvd.js +52 -24
- package/lib/osv-db.js +253 -59
- package/lib/osv-legacy.js +57 -0
- package/lib/osv.js +241 -168
- package/lib/outdated.js +11 -12
- package/lib/package-metadata.js +141 -0
- package/lib/package-versions.js +52 -0
- package/lib/packagist-audit.js +6 -6
- package/lib/provenance.js +73 -19
- package/lib/providers/common.js +11 -1
- package/lib/providers/gcve.js +17 -0
- package/lib/providers/github.js +1 -0
- package/lib/providers/index.js +49 -26
- package/lib/providers/vigievuln.js +7 -0
- package/lib/proxy-cache.js +1 -1
- package/lib/proxy-scope.js +59 -0
- package/lib/proxy-throttle.js +71 -0
- package/lib/resource-cache/engine.js +36 -9
- package/lib/resource-cache/sqlite-store.js +95 -0
- package/lib/resource-cache/validate.js +5 -0
- package/lib/retire.js +24 -24
- package/lib/ruby-version.js +36 -0
- package/lib/sarif-export.js +1 -1
- package/lib/sbom-export.js +11 -7
- package/lib/snyk.js +32 -20
- package/lib/source-profile.js +67 -0
- package/lib/sqlite-driver.js +46 -0
- package/lib/transitive.js +69 -34
- package/lib/unmanaged.js +2 -1
- package/lib/vigievuln-advisories.js +47 -0
- package/package.json +7 -6
- package/vigievuln.js +380 -107
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const fs=require('node:fs');
|
|
4
|
+
const path=require('node:path');
|
|
5
|
+
const {openCacheDb}=require('./cache-db');
|
|
6
|
+
const {compress,decompress}=require('./advisory-compression');
|
|
7
|
+
const rules=require('./advisory-store');
|
|
8
|
+
const {validateRecord,validateQuery,validateCoverage,packageName,packageKeys,queryKey,coverageKey,advisoryId,queryCoversRecord,isWithdrawn,revision,wins,hash,key}=rules;
|
|
9
|
+
const DEFAULT_QUERY_TTL_MS=4 * 3600e3;
|
|
10
|
+
const parse=value=>JSON.parse(value);
|
|
11
|
+
const text=value=>JSON.stringify(value);
|
|
12
|
+
|
|
13
|
+
class SqliteAdvisoryStore {
|
|
14
|
+
constructor({cacheDir=require('./cache-directory').getCacheDir()}={}){
|
|
15
|
+
this.cacheDir=cacheDir;
|
|
16
|
+
this.db=openCacheDb({cacheDir});
|
|
17
|
+
}
|
|
18
|
+
close(){this.db.close()}
|
|
19
|
+
_rowRecord(source,id){return this.db.prepare('SELECT * FROM advisory_records WHERE source=? AND id=?').get(source,id)||null}
|
|
20
|
+
_record(source,id){
|
|
21
|
+
const row=this._rowRecord(source,id);if(!row)return null;
|
|
22
|
+
const body=decompress(row.envelope_deflate,row.envelope_bytes);
|
|
23
|
+
const record=parse(body.toString('utf8'));validateRecord(record);
|
|
24
|
+
if(record.source!==source||advisoryId(record)!==id||hash(text(record.document))!==row.document_sha256)throw Error('advisory record integrity mismatch');
|
|
25
|
+
const observations=this.db.prepare('SELECT fetched_at,provenance_json FROM advisory_observations WHERE source=? AND id=? ORDER BY provenance_key').all(source,id).map(x=>({fetchedAt:x.fetched_at,provenance:parse(x.provenance_json)}));
|
|
26
|
+
return {...record,contentChangedAt:row.content_changed_at,observations};
|
|
27
|
+
}
|
|
28
|
+
_putRecord(record){
|
|
29
|
+
const source=record.source,id=advisoryId(record),previous=this._record(source,id);
|
|
30
|
+
const winner=wins(record,previous);
|
|
31
|
+
if(winner){
|
|
32
|
+
const documentHash=hash(text(record.document));
|
|
33
|
+
const changedAt=previous&&hash(text(previous.document))===documentHash?previous.contentChangedAt:record.fetchedAt;
|
|
34
|
+
const encoded=Buffer.from(text(record));
|
|
35
|
+
if(encoded.length>16777216)throw Error('advisory record exceeds SQLite cache limit');
|
|
36
|
+
this.db.prepare(`INSERT INTO advisory_records(source,id,revision_ms,withdrawn,fetched_at,content_changed_at,document_sha256,envelope_deflate,envelope_bytes)
|
|
37
|
+
VALUES (?,?,?,?,?,?,?,?,?) ON CONFLICT(source,id) DO UPDATE SET revision_ms=excluded.revision_ms,
|
|
38
|
+
withdrawn=excluded.withdrawn,fetched_at=excluded.fetched_at,content_changed_at=excluded.content_changed_at,
|
|
39
|
+
document_sha256=excluded.document_sha256,envelope_deflate=excluded.envelope_deflate,envelope_bytes=excluded.envelope_bytes`).run(source,id,revision(record),isWithdrawn(record)?1:0,record.fetchedAt,changedAt,documentHash,compress(encoded),encoded.length);
|
|
40
|
+
this.db.prepare('DELETE FROM advisory_packages WHERE source=? AND id=?').run(source,id);
|
|
41
|
+
const insert=this.db.prepare('INSERT INTO advisory_packages(ecosystem,name_key,source,id) VALUES (?,?,?,?)');
|
|
42
|
+
for(const identity of packageKeys(record)){const [ecosystem,nameKey]=parse(identity);insert.run(ecosystem,nameKey,source,id)}
|
|
43
|
+
}
|
|
44
|
+
const provenance=record.provenance||{};
|
|
45
|
+
this.db.prepare(`INSERT INTO advisory_observations(source,id,provenance_key,fetched_at,provenance_json)
|
|
46
|
+
VALUES (?,?,?,?,?) ON CONFLICT(source,id,provenance_key) DO UPDATE SET fetched_at=max(fetched_at,excluded.fetched_at)`).run(source,id,hash(text(provenance)),record.fetchedAt,text(provenance));
|
|
47
|
+
}
|
|
48
|
+
_putQuery(query){
|
|
49
|
+
const source=query.source,ecosystem=query.ecosystem,nameKey=ecosystem==='Maven'?query.name:packageName(ecosystem,query.name),version=query.version;
|
|
50
|
+
const previous=this.db.prepare('SELECT fetched_at FROM advisory_queries WHERE source=? AND ecosystem=? AND name_key=? AND version=?').get(source,ecosystem,nameKey,version);
|
|
51
|
+
if(previous&&previous.fetched_at>query.fetchedAt)return;
|
|
52
|
+
this.db.prepare(`INSERT INTO advisory_queries(source,ecosystem,name_key,version,original_name,fetched_at,stale,provenance_json)
|
|
53
|
+
VALUES (?,?,?,?,?,?,?,?) ON CONFLICT(source,ecosystem,name_key,version) DO UPDATE SET original_name=excluded.original_name,
|
|
54
|
+
fetched_at=excluded.fetched_at,stale=excluded.stale,provenance_json=excluded.provenance_json`).run(source,ecosystem,nameKey,version,query.name,query.fetchedAt,query.provenance?.stale===true?1:0,text(query.provenance||{}));
|
|
55
|
+
this.db.prepare('DELETE FROM advisory_query_ids WHERE source=? AND ecosystem=? AND name_key=? AND version=?').run(source,ecosystem,nameKey,version);
|
|
56
|
+
const insert=this.db.prepare('INSERT INTO advisory_query_ids(source,ecosystem,name_key,version,id,ordinal,document_sha256) VALUES (?,?,?,?,?,?,?)');
|
|
57
|
+
for(let i=0;i<query.ids.length;i++)insert.run(source,ecosystem,nameKey,version,query.ids[i],i,query.provenance?.documentHashes?.[query.ids[i]]||null);
|
|
58
|
+
}
|
|
59
|
+
_putCoverage(coverage){
|
|
60
|
+
const source=coverage.source,ecosystem=coverage.ecosystem;
|
|
61
|
+
const current=this.db.prepare("SELECT fetched_at FROM advisory_coverage WHERE source=? AND ecosystem=? AND slot='current'").get(source,ecosystem);
|
|
62
|
+
const put=this.db.prepare(`INSERT INTO advisory_coverage(source,ecosystem,slot,fetched_at,complete,stale,entry_json)
|
|
63
|
+
VALUES (?,?,?,?,?,?,?) ON CONFLICT(source,ecosystem,slot) DO UPDATE SET fetched_at=excluded.fetched_at,
|
|
64
|
+
complete=excluded.complete,stale=excluded.stale,entry_json=excluded.entry_json`);
|
|
65
|
+
if(!current||coverage.fetchedAt>=current.fetched_at)put.run(source,ecosystem,'current',coverage.fetchedAt,coverage.complete?1:0,coverage.provenance?.stale===true?1:0,text(coverage));
|
|
66
|
+
if(coverage.complete){
|
|
67
|
+
const last=this.db.prepare("SELECT fetched_at FROM advisory_coverage WHERE source=? AND ecosystem=? AND slot='last_complete'").get(source,ecosystem);
|
|
68
|
+
if(!last||coverage.fetchedAt>=last.fetched_at)put.run(source,ecosystem,'last_complete',coverage.fetchedAt,1,coverage.provenance?.stale===true?1:0,text(coverage));
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
_commit({records=[],queries=[],coverages=[]}){
|
|
72
|
+
for(const record of records)this._putRecord(record);
|
|
73
|
+
for(const query of queries)this._putQuery(query);
|
|
74
|
+
for(const coverage of coverages)this._putCoverage(coverage);
|
|
75
|
+
}
|
|
76
|
+
commit({records=[],queries=[],coverages=[]}={}){
|
|
77
|
+
if(!Array.isArray(records)||!Array.isArray(queries)||!Array.isArray(coverages))throw Error('invalid advisory transaction');
|
|
78
|
+
const transaction=parse(text({records,queries,coverages}));
|
|
79
|
+
for(const record of transaction.records)validateRecord(record);
|
|
80
|
+
for(const query of transaction.queries)validateQuery(query);
|
|
81
|
+
for(const coverage of transaction.coverages)validateCoverage(coverage);
|
|
82
|
+
if(!records.length&&!queries.length&&!coverages.length)return;
|
|
83
|
+
return this.db.transaction(()=>{
|
|
84
|
+
const incoming=new Set(transaction.records.map(record=>key(record.source,advisoryId(record))));
|
|
85
|
+
for(const query of transaction.queries)for(const id of query.ids)if(!incoming.has(key(query.source,id))&&!this._rowRecord(query.source,id))throw Error(`missing advisory detail: ${id}`);
|
|
86
|
+
this._commit(transaction);
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
getRecord(source,id){return this._record(source,id)}
|
|
90
|
+
getQuery(tuple,{now=Date.now(),ttlMs=DEFAULT_QUERY_TTL_MS}={}){
|
|
91
|
+
if(!Number.isFinite(ttlMs)||ttlMs<0)throw Error('invalid advisory query TTL');
|
|
92
|
+
const source=tuple.source||'osv',ecosystem=tuple.ecosystem,nameKey=ecosystem==='Maven'?tuple.name:packageName(ecosystem,tuple.name);
|
|
93
|
+
const row=this.db.prepare('SELECT * FROM advisory_queries WHERE source=? AND ecosystem=? AND name_key=? AND version=?').get(source,ecosystem,nameKey,tuple.version);
|
|
94
|
+
if(!row)return null;
|
|
95
|
+
const ids=this.db.prepare('SELECT id FROM advisory_query_ids WHERE source=? AND ecosystem=? AND name_key=? AND version=? ORDER BY ordinal').all(source,ecosystem,nameKey,tuple.version).map(x=>x.id);
|
|
96
|
+
if(ids.some(id=>!this._rowRecord(source,id)))return null;
|
|
97
|
+
const provenance=parse(row.provenance_json);
|
|
98
|
+
return {source,ecosystem,name:row.original_name,version:row.version,ids,fetchedAt:row.fetched_at,complete:true,provenance,fresh:provenance.stale!==true&&now>=row.fetched_at&&now-row.fetched_at<ttlMs};
|
|
99
|
+
}
|
|
100
|
+
getSourceCoverage(source,ecosystem='*',options={}){return this._coverage({source,ecosystem},options)}
|
|
101
|
+
_coverage(tuple,{now=Date.now(),ttlMs=DEFAULT_QUERY_TTL_MS}={}){
|
|
102
|
+
const source=tuple.source||'osv';
|
|
103
|
+
let coverageEcosystem=tuple.ecosystem;
|
|
104
|
+
let current=this.db.prepare("SELECT * FROM advisory_coverage WHERE source=? AND ecosystem=? AND slot='current'").get(source,coverageEcosystem);
|
|
105
|
+
if(!current && source==='osv' && tuple.name){
|
|
106
|
+
coverageEcosystem=require('./airgap-project').packageScope(tuple.ecosystem,tuple.name);
|
|
107
|
+
current=this.db.prepare("SELECT * FROM advisory_coverage WHERE source=? AND ecosystem=? AND slot='current'").get(source,coverageEcosystem);
|
|
108
|
+
}
|
|
109
|
+
if(!current)return null;
|
|
110
|
+
const baseline=this.db.prepare("SELECT * FROM advisory_coverage WHERE source=? AND ecosystem=? AND slot='last_complete'").get(source,coverageEcosystem);
|
|
111
|
+
const unpack=row=>{const x=parse(row.entry_json);return {...x,fresh:x.provenance?.stale!==true&&now>=x.fetchedAt&&now-x.fetchedAt<ttlMs}};
|
|
112
|
+
return {...unpack(current),lastComplete:baseline?unpack(baseline):null};
|
|
113
|
+
}
|
|
114
|
+
getQuerySummary(source='osv',{now=Date.now(),ttlMs=DEFAULT_QUERY_TTL_MS}={}){
|
|
115
|
+
if(!Number.isFinite(ttlMs)||ttlMs<0)throw Error('invalid advisory query TTL');
|
|
116
|
+
const row=this.db.prepare(`SELECT COUNT(*) count,MIN(fetched_at) oldestFetchedAt,MAX(fetched_at) newestFetchedAt,
|
|
117
|
+
SUM(CASE WHEN stale=1 OR fetched_at>? OR fetched_at<=? THEN 1 ELSE 0 END) staleCount FROM advisory_queries WHERE source=?`).get(now,now-ttlMs,source);
|
|
118
|
+
return {count:row.count,oldestFetchedAt:row.oldestFetchedAt,newestFetchedAt:row.newestFetchedAt,staleCount:row.staleCount||0,complete:false,scope:'consulted-package-versions'};
|
|
119
|
+
}
|
|
120
|
+
getPackageRecords(ecosystem,name,{source='osv',includeWithdrawn=false}={}){
|
|
121
|
+
const pkgName=packageName(ecosystem,name);
|
|
122
|
+
const rows=source==null
|
|
123
|
+
? this.db.prepare('SELECT source,id FROM advisory_packages WHERE ecosystem=? AND name_key=? ORDER BY source,id').all(ecosystem,pkgName)
|
|
124
|
+
: this.db.prepare('SELECT source,id FROM advisory_packages WHERE ecosystem=? AND name_key=? AND source=? ORDER BY id').all(ecosystem,pkgName,source);
|
|
125
|
+
return rows.map(x=>this._record(x.source,x.id)).filter(record=>record&&(includeWithdrawn||!isWithdrawn(record)));
|
|
126
|
+
}
|
|
127
|
+
getPackageView(tuple,options={}){
|
|
128
|
+
const source=tuple.source||'osv',query=this.getQuery(tuple,options);
|
|
129
|
+
const records=this.getPackageRecords(tuple.ecosystem,tuple.name,{source,includeWithdrawn:true});
|
|
130
|
+
if(source==='osv'&&tuple.ecosystem==='Maven')for(const legacy of this.getPackageRecords(tuple.ecosystem,tuple.name,{source:'osv-legacy-maven',includeWithdrawn:true}))if(!this._rowRecord('osv',advisoryId(legacy)))records.push(legacy);
|
|
131
|
+
const queryRecords=query?query.ids.map(id=>this._record(source,id)):[];
|
|
132
|
+
const combined=new Map([...records,...queryRecords].filter(Boolean).map(record=>[key(record.source,advisoryId(record)),record]));
|
|
133
|
+
return {query,coverage:this._coverage(tuple,options),records:[...combined.values()],queryRecords,
|
|
134
|
+
querySuperseded:!!query&&[...combined.values()].some(record=>!queryCoversRecord(query,record))};
|
|
135
|
+
}
|
|
136
|
+
async importRecords(iterable,{source='osv',fetchedAt=Date.now(),provenance={transport:'seed'},batchSize=250,coverages=[],envelopes=false}={}){
|
|
137
|
+
if(!Number.isSafeInteger(batchSize)||batchSize<1||batchSize>1000)throw Error('invalid advisory import batch size');
|
|
138
|
+
for(const coverage of coverages)validateCoverage(coverage);
|
|
139
|
+
let count=0,batch=[];
|
|
140
|
+
this.db.exec('BEGIN IMMEDIATE');
|
|
141
|
+
try{
|
|
142
|
+
for await(const document of iterable){
|
|
143
|
+
const record=envelopes?document:{source,document,fetchedAt,provenance};validateRecord(record);
|
|
144
|
+
batch.push(record);count++;
|
|
145
|
+
if(batch.length>=batchSize){this._commit({records:batch});batch=[]}
|
|
146
|
+
}
|
|
147
|
+
if(batch.length)this._commit({records:batch});
|
|
148
|
+
for(const coverage of coverages)this._putCoverage(coverage);
|
|
149
|
+
this.db.exec('COMMIT');return count;
|
|
150
|
+
}catch(error){try{this.db.exec('ROLLBACK')}catch{}throw error}
|
|
151
|
+
}
|
|
152
|
+
importEnvelopes(iterable,options={}){return this.importRecords(iterable,{...options,envelopes:true})}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function openAdvisoryStore(options){return new SqliteAdvisoryStore(options)}
|
|
156
|
+
module.exports={SqliteAdvisoryStore,openAdvisoryStore};
|
|
@@ -0,0 +1,484 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// Native advisory documents are immutable entries in an append-only journal.
|
|
4
|
+
// Small, rebuildable hash shards point into it; ordinary scans read only requested
|
|
5
|
+
// packages and versions. Source identity is independent of transport provenance.
|
|
6
|
+
const fs = require('node:fs');
|
|
7
|
+
const path = require('node:path');
|
|
8
|
+
const crypto = require('node:crypto');
|
|
9
|
+
const { StringDecoder } = require('node:string_decoder');
|
|
10
|
+
const DEFAULT_QUERY_TTL_MS = 4 * 3600e3;
|
|
11
|
+
const MAX_TRANSACTION_BYTES = 32 * 1024 * 1024;
|
|
12
|
+
const hash = value => crypto.createHash('sha256').update(value).digest('hex');
|
|
13
|
+
const plain = value => !!value && typeof value === 'object' && !Array.isArray(value);
|
|
14
|
+
const key = (...parts) => JSON.stringify(parts);
|
|
15
|
+
function packageName(ecosystem, name) {
|
|
16
|
+
if (ecosystem === 'PyPI') return name.toLowerCase().replace(/[-_.]+/g, '-');
|
|
17
|
+
return ['Maven', 'npm', 'NuGet', 'Packagist'].includes(ecosystem) ? name.toLowerCase() : name;
|
|
18
|
+
}
|
|
19
|
+
function timestamp(value, label = 'fetchedAt') {
|
|
20
|
+
if (!Number.isSafeInteger(value) || value <= 0 || value > Date.now() + 300000) throw new Error(`invalid advisory ${label}`);
|
|
21
|
+
return value;
|
|
22
|
+
}
|
|
23
|
+
function string(value, label) {
|
|
24
|
+
if (typeof value !== 'string' || !value || value.length > 4096 || /[\x00-\x1f]/.test(value)) throw new Error(`invalid advisory ${label}`);
|
|
25
|
+
return value;
|
|
26
|
+
}
|
|
27
|
+
function source(value) { return string(value, 'source'); }
|
|
28
|
+
function date(value, label) {
|
|
29
|
+
if (value == null) return 0;
|
|
30
|
+
if (typeof value !== 'string' || !Number.isFinite(Date.parse(value))) throw new Error(`invalid advisory ${label}`);
|
|
31
|
+
return Date.parse(value);
|
|
32
|
+
}
|
|
33
|
+
const advisoryId = record => record.id || record.document.id || record.document.cveMetadata?.vulnId || record.document.cveMetadata?.cveId;
|
|
34
|
+
const nativeCve = record => ['gcve', 'cveproject'].includes(record.source);
|
|
35
|
+
function isWithdrawn(record) {
|
|
36
|
+
return !!(record.withdrawnAt || record.document.withdrawn || (nativeCve(record) && record.document.cveMetadata?.state === 'REJECTED'));
|
|
37
|
+
}
|
|
38
|
+
function validateRecord(input) {
|
|
39
|
+
if (!plain(input) || !plain(input.document)) throw new Error('invalid advisory record');
|
|
40
|
+
source(input.source); string(advisoryId(input), 'id'); timestamp(input.fetchedAt);
|
|
41
|
+
for (const field of ['modified', 'published', 'withdrawn']) date(input.document[field], field);
|
|
42
|
+
for (const field of ['modifiedAt', 'publishedAt', 'withdrawnAt']) date(input[field], field);
|
|
43
|
+
if (nativeCve(input)) for (const field of ['dateUpdated', 'datePublished', 'dateRejected']) date(input.document.cveMetadata?.[field], field);
|
|
44
|
+
if (input.provenance != null && !plain(input.provenance)) throw new Error('invalid advisory provenance');
|
|
45
|
+
if (input.source === 'osv' && input.document.affected != null) {
|
|
46
|
+
if (!Array.isArray(input.document.affected)) throw new Error('invalid OSV affected');
|
|
47
|
+
for (const affected of input.document.affected) {
|
|
48
|
+
if (!plain(affected)) throw new Error('invalid OSV affected entry');
|
|
49
|
+
if (affected.versions != null && (!Array.isArray(affected.versions) || affected.versions.some(v => typeof v !== 'string'))) throw new Error('invalid OSV versions');
|
|
50
|
+
if (affected.ranges != null && !Array.isArray(affected.ranges)) throw new Error('invalid OSV ranges');
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
return input;
|
|
54
|
+
}
|
|
55
|
+
function validateQuery(input) {
|
|
56
|
+
if (!plain(input) || input.complete !== true || !Array.isArray(input.ids)) throw new Error('incomplete advisory query');
|
|
57
|
+
source(input.source); string(input.ecosystem, 'ecosystem'); string(input.name, 'name'); string(input.version, 'version'); timestamp(input.fetchedAt);
|
|
58
|
+
for (const id of input.ids) string(id, 'query id');
|
|
59
|
+
if (new Set(input.ids).size !== input.ids.length) throw new Error('duplicate advisory query id');
|
|
60
|
+
if (input.provenance != null && !plain(input.provenance)) throw new Error('invalid query provenance');
|
|
61
|
+
return input;
|
|
62
|
+
}
|
|
63
|
+
function validateCoverage(input) {
|
|
64
|
+
if (!plain(input) || typeof input.complete !== 'boolean') throw new Error('invalid advisory seed coverage');
|
|
65
|
+
source(input.source); string(input.ecosystem, 'ecosystem'); timestamp(input.fetchedAt);
|
|
66
|
+
if (input.provenance != null && !plain(input.provenance)) throw new Error('invalid seed provenance');
|
|
67
|
+
if (input.recordCount != null && (!Number.isSafeInteger(input.recordCount) || input.recordCount < 0)) throw new Error('invalid seed record count');
|
|
68
|
+
if (input.sha256 != null && !/^[a-f0-9]{64}$/.test(input.sha256)) throw new Error('invalid seed checksum');
|
|
69
|
+
return input;
|
|
70
|
+
}
|
|
71
|
+
const recordKey = record => key(record.source, advisoryId(record));
|
|
72
|
+
// Maven coordinates are case-sensitive. Package shards remain folded for
|
|
73
|
+
// compatibility, but consultations must not share freshness or results
|
|
74
|
+
// across differently cased coordinates.
|
|
75
|
+
const queryKey = query => key(query.source || 'osv', query.ecosystem, query.ecosystem === 'Maven' ? query.name : packageName(query.ecosystem, query.name), query.version);
|
|
76
|
+
const coverageKey = coverage => key(coverage.source, coverage.ecosystem);
|
|
77
|
+
function packageKeys(record) {
|
|
78
|
+
// Other native schemas can supply explicit normalized package bindings without
|
|
79
|
+
// modifying or conflating their original documents.
|
|
80
|
+
const packages = ['osv', 'osv-legacy-maven'].includes(record.source) ? (record.document.affected || []).map(a => a.package) : (record.packages || []);
|
|
81
|
+
return [...new Set(packages.filter(p => plain(p) && typeof p.ecosystem === 'string' && p.ecosystem && typeof p.name === 'string' && p.name).map(p => {
|
|
82
|
+
return key(p.ecosystem, packageName(p.ecosystem, p.name));
|
|
83
|
+
}))];
|
|
84
|
+
}
|
|
85
|
+
function revision(record) {
|
|
86
|
+
return Math.max(date(record.document.modified, 'modified'), date(record.document.withdrawn, 'withdrawn'),
|
|
87
|
+
date(record.modifiedAt, 'modifiedAt'), date(record.withdrawnAt, 'withdrawnAt'),
|
|
88
|
+
nativeCve(record) ? date(record.document.cveMetadata?.dateUpdated, 'dateUpdated') : 0,
|
|
89
|
+
nativeCve(record) ? date(record.document.cveMetadata?.dateRejected, 'dateRejected') : 0);
|
|
90
|
+
}
|
|
91
|
+
function wins(incoming, existing) {
|
|
92
|
+
if (!existing) return true;
|
|
93
|
+
const newer = revision(incoming), older = revision(existing);
|
|
94
|
+
if (newer !== older) return newer > older;
|
|
95
|
+
// A stale response cannot resurrect a withdrawal at the same source revision.
|
|
96
|
+
if (isWithdrawn(incoming) !== isWithdrawn(existing)) return isWithdrawn(incoming);
|
|
97
|
+
return incoming.fetchedAt >= existing.fetchedAt;
|
|
98
|
+
}
|
|
99
|
+
function queryCoversRecord(query, record) {
|
|
100
|
+
if (!query) return false;
|
|
101
|
+
if ((record.contentChangedAt ?? record.fetchedAt) <= query.fetchedAt) return true;
|
|
102
|
+
const fingerprint = query.provenance?.documentHashes?.[advisoryId(record)];
|
|
103
|
+
return typeof fingerprint === 'string' && fingerprint === hash(JSON.stringify(record.document));
|
|
104
|
+
}
|
|
105
|
+
function selectAdvisoryRecord(incoming, existing) { return wins(incoming, existing) ? incoming : existing; }
|
|
106
|
+
function atomicJson(file, body, { durable = false } = {}) {
|
|
107
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
108
|
+
const temporary = `${file}.${process.pid}.${crypto.randomBytes(6).toString('hex')}.tmp`;
|
|
109
|
+
const serialized = JSON.stringify(body);
|
|
110
|
+
try {
|
|
111
|
+
const fd = fs.openSync(temporary, 'wx', 0o600);
|
|
112
|
+
try { fs.writeFileSync(fd, serialized); if (durable) fs.fsyncSync(fd); } finally { fs.closeSync(fd); }
|
|
113
|
+
fs.renameSync(temporary, file);
|
|
114
|
+
if (durable && process.platform !== 'win32') {
|
|
115
|
+
const directory = fs.openSync(path.dirname(file), 'r');
|
|
116
|
+
try { fs.fsyncSync(directory); } finally { fs.closeSync(directory); }
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
finally { try { fs.unlinkSync(temporary); } catch {} }
|
|
120
|
+
return hash(serialized);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function* journalTransactions(file, { allowTail = false } = {}) {
|
|
124
|
+
const fd = fs.openSync(file, 'r'), buffer = Buffer.alloc(64 * 1024), decoder = new StringDecoder('utf8');
|
|
125
|
+
let pending = '', offset = 0;
|
|
126
|
+
try {
|
|
127
|
+
let length;
|
|
128
|
+
while ((length = fs.readSync(fd, buffer, 0, buffer.length, null))) {
|
|
129
|
+
pending += decoder.write(buffer.subarray(0, length));
|
|
130
|
+
let end;
|
|
131
|
+
while ((end = pending.indexOf('\n')) >= 0) {
|
|
132
|
+
const line = pending.slice(0, end); pending = pending.slice(end + 1);
|
|
133
|
+
if (Buffer.byteLength(line) > MAX_TRANSACTION_BYTES) throw new Error('oversized advisory transaction');
|
|
134
|
+
const transaction = JSON.parse(line);
|
|
135
|
+
if (transaction.schema !== 1 || !Array.isArray(transaction.records) || !Array.isArray(transaction.queries) || !Array.isArray(transaction.coverages) || JSON.stringify({ schema: 1, records: transaction.records, queries: transaction.queries, coverages: transaction.coverages }) !== line) throw new Error('invalid advisory transaction');
|
|
136
|
+
for (const record of transaction.records) { validateRecord(record); packageKeys(record); }
|
|
137
|
+
for (const query of transaction.queries) validateQuery(query);
|
|
138
|
+
for (const coverage of transaction.coverages) validateCoverage(coverage);
|
|
139
|
+
yield { transaction, offset, line: line + '\n' };
|
|
140
|
+
offset += Buffer.byteLength(line) + 1;
|
|
141
|
+
}
|
|
142
|
+
if (Buffer.byteLength(pending) > MAX_TRANSACTION_BYTES) throw new Error('oversized advisory transaction');
|
|
143
|
+
}
|
|
144
|
+
pending += decoder.end();
|
|
145
|
+
if (pending && !allowTail) throw new Error('truncated advisory journal');
|
|
146
|
+
} finally { fs.closeSync(fd); }
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
class AdvisoryStore {
|
|
150
|
+
constructor({ cacheDir = require('./cache-directory').getCacheDir() } = {}) {
|
|
151
|
+
this.directory = path.join(cacheDir, 'advisory-store');
|
|
152
|
+
this.journal = path.join(this.directory, 'events.jsonl');
|
|
153
|
+
this.checkpoint = path.join(this.directory, 'checkpoint.json');
|
|
154
|
+
this.lock = path.join(this.directory, '.lock');
|
|
155
|
+
}
|
|
156
|
+
_size() { try { return fs.statSync(this.journal).size; } catch (e) { if (e.code === 'ENOENT') return 0; throw e; } }
|
|
157
|
+
_locked(action) {
|
|
158
|
+
fs.mkdirSync(this.directory, { recursive: true });
|
|
159
|
+
const deadline = Date.now() + 10000;
|
|
160
|
+
for (;;) {
|
|
161
|
+
try { fs.writeFileSync(this.lock, JSON.stringify({ pid: process.pid }), { flag: 'wx', mode: 0o600 }); break; }
|
|
162
|
+
catch (error) {
|
|
163
|
+
if (error.code !== 'EEXIST') throw error;
|
|
164
|
+
try {
|
|
165
|
+
const owner = JSON.parse(fs.readFileSync(this.lock, 'utf8'));
|
|
166
|
+
if (Number.isSafeInteger(owner.pid) && owner.pid > 0) {
|
|
167
|
+
try { process.kill(owner.pid, 0); } catch (e) { if (e.code === 'ESRCH') { fs.unlinkSync(this.lock); continue; } }
|
|
168
|
+
}
|
|
169
|
+
} catch { /* A writer may still be filling its lock file. */ }
|
|
170
|
+
if (Date.now() >= deadline) throw new Error('advisory store is busy');
|
|
171
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 10);
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
try {
|
|
175
|
+
this._recover();
|
|
176
|
+
try { return action(); }
|
|
177
|
+
catch (error) {
|
|
178
|
+
if (error.code !== 'ADVISORY_INDEX_INTEGRITY') throw error;
|
|
179
|
+
// A derived file can lag its durable manifest after a power loss.
|
|
180
|
+
// Rebuild under the existing lock and retry; never treat it as empty.
|
|
181
|
+
this._recover(true);
|
|
182
|
+
return action();
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
finally { fs.unlinkSync(this.lock); }
|
|
186
|
+
}
|
|
187
|
+
_indexFailure() { const error = new Error('advisory index integrity mismatch'); error.code = 'ADVISORY_INDEX_INTEGRITY'; return error; }
|
|
188
|
+
_relative(file) { return path.relative(this.directory, file).split(path.sep).join('/'); }
|
|
189
|
+
_flush(cache) {
|
|
190
|
+
for (const [file, shard] of cache) this._manifest[this._relative(file)] = atomicJson(file, shard);
|
|
191
|
+
}
|
|
192
|
+
_checkpoint(bytes) {
|
|
193
|
+
// Only the authoritative journal and small checksum manifest need fsync.
|
|
194
|
+
// Derived shards are verified lazily on every read and rebuilt on mismatch.
|
|
195
|
+
atomicJson(this.checkpoint, { schema: 2, bytes, shards: this._manifest }, { durable: true });
|
|
196
|
+
}
|
|
197
|
+
_shardFile(kind, identity) { return path.join(this.directory, kind, `${hash(identity).slice(0, 2)}.json`); }
|
|
198
|
+
_shard(kind, identity, cache) {
|
|
199
|
+
const file = this._shardFile(kind, identity);
|
|
200
|
+
if (cache?.has(file)) return cache.get(file);
|
|
201
|
+
let shard;
|
|
202
|
+
const expected = this._manifest?.[this._relative(file)];
|
|
203
|
+
try {
|
|
204
|
+
const serialized = fs.readFileSync(file, 'utf8');
|
|
205
|
+
if (hash(serialized) !== expected) throw this._indexFailure();
|
|
206
|
+
shard = JSON.parse(serialized); if (!plain(shard)) throw this._indexFailure();
|
|
207
|
+
}
|
|
208
|
+
catch (error) { if (error.code !== 'ENOENT') throw error; if (expected) throw this._indexFailure(); shard = Object.create(null); }
|
|
209
|
+
if (cache) cache.set(file, shard);
|
|
210
|
+
return shard;
|
|
211
|
+
}
|
|
212
|
+
_lookup(kind, identity, cache) { return this._shard(kind, identity, cache)[identity] || null; }
|
|
213
|
+
_readJson(pointer) {
|
|
214
|
+
if (!pointer) return null;
|
|
215
|
+
if (!Number.isSafeInteger(pointer.offset) || pointer.offset < 0 || !Number.isSafeInteger(pointer.length) || pointer.length <= 0 || pointer.length > MAX_TRANSACTION_BYTES) throw new Error('invalid advisory record pointer');
|
|
216
|
+
const buffer = Buffer.alloc(pointer.length), fd = fs.openSync(this.journal, 'r');
|
|
217
|
+
try { if (fs.readSync(fd, buffer, 0, buffer.length, pointer.offset) !== buffer.length) throw new Error('truncated advisory record'); }
|
|
218
|
+
finally { fs.closeSync(fd); }
|
|
219
|
+
if (hash(buffer) !== pointer.sha256) throw new Error('advisory record checksum mismatch');
|
|
220
|
+
return JSON.parse(buffer.toString('utf8'));
|
|
221
|
+
}
|
|
222
|
+
_record(identity, cache) {
|
|
223
|
+
const pointer = this._lookup('records', identity, cache), record = this._readJson(pointer);
|
|
224
|
+
if (record) validateRecord(record);
|
|
225
|
+
if (record && recordKey(record) !== identity) throw new Error('advisory record identity mismatch');
|
|
226
|
+
return record ? { ...record, contentChangedAt: pointer.contentChangedAt ?? record.fetchedAt, observations: pointer.observations || [{ fetchedAt: record.fetchedAt, provenance: record.provenance || {} }] } : null;
|
|
227
|
+
}
|
|
228
|
+
_query(tuple, { now = Date.now(), ttlMs = DEFAULT_QUERY_TTL_MS } = {}) {
|
|
229
|
+
if (!Number.isFinite(ttlMs) || ttlMs < 0) throw new Error('invalid advisory query TTL');
|
|
230
|
+
const identity = queryKey(tuple), query = this._readJson(this._lookup('queries', identity));
|
|
231
|
+
if (!query) return null;
|
|
232
|
+
validateQuery(query);
|
|
233
|
+
// Existing folded-key consultations may have been written for a different
|
|
234
|
+
// case. Treat them as a cache miss; never reuse them as evidence.
|
|
235
|
+
if (queryKey(query) !== identity) {
|
|
236
|
+
if (tuple.ecosystem === 'Maven') return null;
|
|
237
|
+
throw new Error('advisory query identity mismatch');
|
|
238
|
+
}
|
|
239
|
+
for (const id of query.ids) if (!this._record(key(query.source, id))) return null;
|
|
240
|
+
return { ...query, fresh: query.provenance?.stale !== true && now >= query.fetchedAt && now - query.fetchedAt < ttlMs };
|
|
241
|
+
}
|
|
242
|
+
_coverage(tuple, { now = Date.now(), ttlMs = DEFAULT_QUERY_TTL_MS } = {}) {
|
|
243
|
+
const identity = coverageKey({ ...tuple, source: tuple.source || 'osv' });
|
|
244
|
+
const entry = this._lookup('coverages', identity), coverage = this._readJson(entry?.current || entry);
|
|
245
|
+
if (!coverage) return null;
|
|
246
|
+
validateCoverage(coverage);
|
|
247
|
+
if (coverageKey(coverage) !== identity) throw new Error('advisory coverage identity mismatch');
|
|
248
|
+
const fresh = item => item.provenance?.stale !== true && now >= item.fetchedAt && now - item.fetchedAt < ttlMs;
|
|
249
|
+
const baseline = this._readJson(entry?.lastComplete) || (coverage.complete ? coverage : null);
|
|
250
|
+
if (baseline) {
|
|
251
|
+
validateCoverage(baseline);
|
|
252
|
+
if (!baseline.complete || coverageKey(baseline) !== identity) throw new Error('advisory baseline identity mismatch');
|
|
253
|
+
}
|
|
254
|
+
return { ...coverage, fresh: fresh(coverage), lastComplete: baseline ? { ...baseline, fresh: fresh(baseline) } : null };
|
|
255
|
+
}
|
|
256
|
+
_packageRecords(ecosystem, name, wantedSource, includeWithdrawn) {
|
|
257
|
+
const pkg = key(ecosystem, packageName(ecosystem, name)), refs = this._lookup('packages', pkg) || [];
|
|
258
|
+
if (!Array.isArray(refs) || refs.some(ref => typeof ref !== 'string')) throw new Error('invalid advisory package index');
|
|
259
|
+
return refs.map(identity => this._record(identity)).filter(record => {
|
|
260
|
+
if (!record || !packageKeys(record).includes(pkg)) throw new Error('advisory package identity mismatch');
|
|
261
|
+
return (!wantedSource || record.source === wantedSource) && (includeWithdrawn || !isWithdrawn(record));
|
|
262
|
+
});
|
|
263
|
+
}
|
|
264
|
+
_apply(transaction, offset, cache = new Map(), flush = true) {
|
|
265
|
+
let recordOffset = offset + Buffer.byteLength('{"schema":1,"records":[');
|
|
266
|
+
for (const record of transaction.records) {
|
|
267
|
+
validateRecord(record);
|
|
268
|
+
const serialized = JSON.stringify(record), length = Buffer.byteLength(serialized);
|
|
269
|
+
const identity = recordKey(record), previous = this._record(identity, cache);
|
|
270
|
+
const observations = previous?.observations || [], observation = { fetchedAt: record.fetchedAt, provenance: record.provenance || {} };
|
|
271
|
+
const observationIndex = observations.findIndex(item => JSON.stringify(item.provenance) === JSON.stringify(observation.provenance));
|
|
272
|
+
if (observationIndex < 0) observations.push(observation);
|
|
273
|
+
else if (observations[observationIndex].fetchedAt < observation.fetchedAt) observations[observationIndex] = observation;
|
|
274
|
+
if (wins(record, previous)) {
|
|
275
|
+
for (const pkg of packageKeys(previous || { source: 'osv', document: {} })) {
|
|
276
|
+
const shard = this._shard('packages', pkg, cache);
|
|
277
|
+
const refs = shard[pkg] || [];
|
|
278
|
+
shard[pkg] = refs.filter(ref => ref !== identity);
|
|
279
|
+
}
|
|
280
|
+
for (const pkg of packageKeys(record)) {
|
|
281
|
+
const shard = this._shard('packages', pkg, cache);
|
|
282
|
+
if (!shard[pkg]) shard[pkg] = [];
|
|
283
|
+
if (!shard[pkg].includes(identity)) shard[pkg].push(identity);
|
|
284
|
+
}
|
|
285
|
+
const contentChangedAt = previous && JSON.stringify(previous.document) === JSON.stringify(record.document) ? previous.contentChangedAt : record.fetchedAt;
|
|
286
|
+
this._shard('records', identity, cache)[identity] = { offset: recordOffset, length, sha256: hash(serialized), contentChangedAt, observations };
|
|
287
|
+
} else this._shard('records', identity, cache)[identity].observations = observations;
|
|
288
|
+
recordOffset += length + 1;
|
|
289
|
+
}
|
|
290
|
+
let queryOffset = recordOffset - (transaction.records.length ? 1 : 0) + Buffer.byteLength('],"queries":[');
|
|
291
|
+
for (const query of transaction.queries) {
|
|
292
|
+
validateQuery(query);
|
|
293
|
+
const serialized = JSON.stringify(query), length = Buffer.byteLength(serialized);
|
|
294
|
+
const identity = queryKey(query), shard = this._shard('queries', identity, cache), previous = this._readJson(shard[identity]);
|
|
295
|
+
if (!previous || query.fetchedAt >= previous.fetchedAt) shard[identity] = { offset: queryOffset, length, sha256: hash(serialized) };
|
|
296
|
+
queryOffset += length + 1;
|
|
297
|
+
}
|
|
298
|
+
let coverageOffset = queryOffset - (transaction.queries.length ? 1 : 0) + Buffer.byteLength('],"coverages":[');
|
|
299
|
+
for (const coverage of transaction.coverages) {
|
|
300
|
+
validateCoverage(coverage);
|
|
301
|
+
const serialized = JSON.stringify(coverage), length = Buffer.byteLength(serialized);
|
|
302
|
+
const identity = coverageKey(coverage), shard = this._shard('coverages', identity, cache), entry = shard[identity];
|
|
303
|
+
const previous = this._readJson(entry?.current || entry);
|
|
304
|
+
const priorCompletePointer = entry?.lastComplete || (previous?.complete ? entry?.current || entry : null);
|
|
305
|
+
const priorComplete = this._readJson(priorCompletePointer);
|
|
306
|
+
const pointer = { offset: coverageOffset, length, sha256: hash(serialized) };
|
|
307
|
+
// Latest collection status and historical completeness are independent:
|
|
308
|
+
// a partial refresh must be visible without erasing the older baseline.
|
|
309
|
+
const current = !previous || coverage.fetchedAt >= previous.fetchedAt ? pointer : entry.current || entry;
|
|
310
|
+
const lastComplete = coverage.complete && (!priorComplete || coverage.fetchedAt >= priorComplete.fetchedAt) ? pointer : priorCompletePointer;
|
|
311
|
+
shard[identity] = { current, lastComplete };
|
|
312
|
+
coverageOffset += length + 1;
|
|
313
|
+
}
|
|
314
|
+
if (flush) this._flush(cache);
|
|
315
|
+
}
|
|
316
|
+
_recover(force = false) {
|
|
317
|
+
const size = this._size();
|
|
318
|
+
let checkpoint = null;
|
|
319
|
+
try { checkpoint = JSON.parse(fs.readFileSync(this.checkpoint, 'utf8')); } catch {}
|
|
320
|
+
if (!force && checkpoint?.schema === 2 && checkpoint.bytes === size && plain(checkpoint.shards)) { this._manifest = checkpoint.shards; return; }
|
|
321
|
+
// All shards are derived. A crash between journal append and index updates
|
|
322
|
+
// is repaired from bounded journal lines, without loading the full database.
|
|
323
|
+
this._manifest = Object.create(null);
|
|
324
|
+
for (const kind of ['records', 'packages', 'queries', 'coverages']) fs.rmSync(path.join(this.directory, kind), { recursive: true, force: true });
|
|
325
|
+
if (!size) {
|
|
326
|
+
// An initialized empty store must itself be a valid portable journal.
|
|
327
|
+
const fd = fs.openSync(this.journal, 'a', 0o600); fs.closeSync(fd);
|
|
328
|
+
this._checkpoint(0); return;
|
|
329
|
+
}
|
|
330
|
+
const cache = new Map(); let offset = 0;
|
|
331
|
+
for (const item of journalTransactions(this.journal, { allowTail: true })) {
|
|
332
|
+
this._apply(item.transaction, item.offset, cache, false);
|
|
333
|
+
offset = item.offset + Buffer.byteLength(item.line);
|
|
334
|
+
}
|
|
335
|
+
this._flush(cache);
|
|
336
|
+
// An unterminated final transaction was never committed. Retain all complete
|
|
337
|
+
// transactions; never publish an incomplete query as verified coverage.
|
|
338
|
+
if (offset !== size) fs.truncateSync(this.journal, offset);
|
|
339
|
+
this._checkpoint(offset);
|
|
340
|
+
}
|
|
341
|
+
commit({ records = [], queries = [], coverages = [] } = {}) {
|
|
342
|
+
if (!Array.isArray(records) || !Array.isArray(queries) || !Array.isArray(coverages)) throw new Error('invalid advisory transaction');
|
|
343
|
+
// JSON round-trip rejects unserializable inputs and detaches caller objects.
|
|
344
|
+
const transaction = JSON.parse(JSON.stringify({ schema: 1, records, queries, coverages }));
|
|
345
|
+
for (const record of transaction.records) { validateRecord(record); packageKeys(record); }
|
|
346
|
+
for (const query of transaction.queries) validateQuery(query);
|
|
347
|
+
for (const coverage of transaction.coverages) validateCoverage(coverage);
|
|
348
|
+
const line = JSON.stringify(transaction) + '\n';
|
|
349
|
+
if (Buffer.byteLength(line) > MAX_TRANSACTION_BYTES) throw new Error('oversized advisory transaction; split the import into batches');
|
|
350
|
+
if (!records.length && !queries.length && !coverages.length) return;
|
|
351
|
+
return this._locked(() => {
|
|
352
|
+
const incoming = new Set(transaction.records.map(recordKey));
|
|
353
|
+
for (const query of transaction.queries) for (const id of query.ids) {
|
|
354
|
+
const identity = key(query.source, id);
|
|
355
|
+
if (!incoming.has(identity) && !this._lookup('records', identity)) throw new Error(`missing advisory detail: ${id}`);
|
|
356
|
+
}
|
|
357
|
+
const offset = this._size(), fd = fs.openSync(this.journal, 'a', 0o600);
|
|
358
|
+
try { fs.writeFileSync(fd, line); fs.fsyncSync(fd); } finally { fs.closeSync(fd); }
|
|
359
|
+
this._apply(transaction, offset);
|
|
360
|
+
this._checkpoint(offset + Buffer.byteLength(line));
|
|
361
|
+
});
|
|
362
|
+
}
|
|
363
|
+
getRecord(recordSource, id) {
|
|
364
|
+
return this._locked(() => this._record(key(recordSource, id)));
|
|
365
|
+
}
|
|
366
|
+
getQuery(tuple, { now = Date.now(), ttlMs = DEFAULT_QUERY_TTL_MS } = {}) {
|
|
367
|
+
return this._locked(() => this._query(tuple, { now, ttlMs }));
|
|
368
|
+
}
|
|
369
|
+
getSourceCoverage(recordSource, ecosystem = '*', options = {}) {
|
|
370
|
+
return this._locked(() => this._coverage({ source: recordSource, ecosystem }, options));
|
|
371
|
+
}
|
|
372
|
+
getQuerySummary(recordSource = 'osv', { now = Date.now(), ttlMs = DEFAULT_QUERY_TTL_MS } = {}) {
|
|
373
|
+
if (!Number.isFinite(ttlMs) || ttlMs < 0) throw new Error('invalid advisory query TTL');
|
|
374
|
+
return this._locked(() => {
|
|
375
|
+
const directory = path.join(this.directory, 'queries');
|
|
376
|
+
const files = Object.keys(this._manifest).filter(file => /^queries\/[a-f0-9]{2}\.json$/.test(file)).map(file => file.slice('queries/'.length));
|
|
377
|
+
let count = 0, oldestFetchedAt = null, newestFetchedAt = null, staleCount = 0;
|
|
378
|
+
for (const file of files) {
|
|
379
|
+
if (!/^[a-f0-9]{2}\.json$/.test(file)) continue;
|
|
380
|
+
let serialized;
|
|
381
|
+
try { serialized = fs.readFileSync(path.join(directory, file), 'utf8'); }
|
|
382
|
+
catch (error) { if (error.code === 'ENOENT') throw this._indexFailure(); throw error; }
|
|
383
|
+
if (hash(serialized) !== this._manifest[`queries/${file}`]) throw this._indexFailure();
|
|
384
|
+
const shard = JSON.parse(serialized);
|
|
385
|
+
if (!plain(shard)) throw new Error('invalid advisory query index');
|
|
386
|
+
for (const [identity, pointer] of Object.entries(shard)) {
|
|
387
|
+
const query = validateQuery(this._readJson(pointer));
|
|
388
|
+
if (queryKey(query) !== identity) throw new Error('advisory query identity mismatch');
|
|
389
|
+
if (query.source !== recordSource) continue;
|
|
390
|
+
count++;
|
|
391
|
+
oldestFetchedAt = oldestFetchedAt == null ? query.fetchedAt : Math.min(oldestFetchedAt, query.fetchedAt);
|
|
392
|
+
newestFetchedAt = newestFetchedAt == null ? query.fetchedAt : Math.max(newestFetchedAt, query.fetchedAt);
|
|
393
|
+
if (query.provenance?.stale === true || now < query.fetchedAt || now - query.fetchedAt >= ttlMs) staleCount++;
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
return { count, oldestFetchedAt, newestFetchedAt, staleCount, complete: false, scope: 'consulted-package-versions' };
|
|
397
|
+
});
|
|
398
|
+
}
|
|
399
|
+
getPackageRecords(ecosystem, name, { source: wantedSource = 'osv', includeWithdrawn = false } = {}) {
|
|
400
|
+
return this._locked(() => {
|
|
401
|
+
return this._packageRecords(ecosystem, name, wantedSource, includeWithdrawn);
|
|
402
|
+
});
|
|
403
|
+
}
|
|
404
|
+
getPackageView(tuple, options = {}) {
|
|
405
|
+
return this._locked(() => {
|
|
406
|
+
const wantedSource = tuple.source || 'osv', query = this._query(tuple, options);
|
|
407
|
+
const records = this._packageRecords(tuple.ecosystem, tuple.name, wantedSource, true);
|
|
408
|
+
if (wantedSource === 'osv' && tuple.ecosystem === 'Maven') {
|
|
409
|
+
for (const legacy of this._packageRecords(tuple.ecosystem, tuple.name, 'osv-legacy-maven', true)) {
|
|
410
|
+
// A native revision or withdrawal supersedes every projected legacy
|
|
411
|
+
// copy, including one whose old package association was removed.
|
|
412
|
+
if (!this._record(key('osv', advisoryId(legacy)))) records.push(legacy);
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
const queryRecords = query ? query.ids.map(id => this._record(key(wantedSource, id))) : [];
|
|
416
|
+
const combined = new Map([...records, ...queryRecords].map(record => [recordKey(record), record]));
|
|
417
|
+
return {
|
|
418
|
+
query,
|
|
419
|
+
coverage: this._coverage(tuple, options),
|
|
420
|
+
records: [...combined.values()], // includes tombstones for reconciliation
|
|
421
|
+
queryRecords, // includes valid API hits without indexable affected entries
|
|
422
|
+
querySuperseded: !!query && [...combined.values()].some(record => !queryCoversRecord(query, record)),
|
|
423
|
+
};
|
|
424
|
+
});
|
|
425
|
+
}
|
|
426
|
+
async importRecords(iterable, { source: recordSource = 'osv', fetchedAt = Date.now(), provenance = { transport: 'seed' }, batchSize = 250, coverages = [], envelopes = false } = {}) {
|
|
427
|
+
if (!Number.isSafeInteger(batchSize) || batchSize < 1 || batchSize > 1000) throw new Error('invalid advisory import batch size');
|
|
428
|
+
fs.mkdirSync(this.directory, { recursive: true });
|
|
429
|
+
const temporary = path.join(this.directory, `.import-${process.pid}-${crypto.randomBytes(8).toString('hex')}.jsonl`);
|
|
430
|
+
const fd = fs.openSync(temporary, 'wx', 0o600); let batch = [], batchBytes = 0, count = 0;
|
|
431
|
+
const flush = () => {
|
|
432
|
+
if (!batch.length) return;
|
|
433
|
+
const line = JSON.stringify({ schema: 1, records: batch, queries: [], coverages: [] }) + '\n';
|
|
434
|
+
if (Buffer.byteLength(line) > MAX_TRANSACTION_BYTES) throw new Error('oversized advisory import batch');
|
|
435
|
+
fs.writeFileSync(fd, line); batch = []; batchBytes = 0;
|
|
436
|
+
};
|
|
437
|
+
try {
|
|
438
|
+
try {
|
|
439
|
+
for await (const document of iterable) {
|
|
440
|
+
const record = envelopes ? document : { source: recordSource, document, fetchedAt, provenance };
|
|
441
|
+
validateRecord(record); packageKeys(record);
|
|
442
|
+
const bytes = Buffer.byteLength(JSON.stringify(record));
|
|
443
|
+
if (bytes > MAX_TRANSACTION_BYTES - 512) throw new Error('oversized native advisory record');
|
|
444
|
+
if (batchBytes + bytes > MAX_TRANSACTION_BYTES - 512) flush();
|
|
445
|
+
batch.push(record); batchBytes += bytes + 1; count++;
|
|
446
|
+
if (batch.length >= batchSize) flush();
|
|
447
|
+
}
|
|
448
|
+
flush();
|
|
449
|
+
if (!Array.isArray(coverages)) throw new Error('invalid seed coverages');
|
|
450
|
+
for (const coverage of coverages) validateCoverage(coverage);
|
|
451
|
+
if (coverages.length) fs.writeFileSync(fd, JSON.stringify({ schema: 1, records: [], queries: [], coverages }) + '\n');
|
|
452
|
+
} finally { fs.closeSync(fd); }
|
|
453
|
+
this.mergeJournal(temporary);
|
|
454
|
+
return count;
|
|
455
|
+
} finally { fs.rmSync(temporary, { force: true }); }
|
|
456
|
+
}
|
|
457
|
+
async importEnvelopes(iterable, options = {}) {
|
|
458
|
+
return this.importRecords(iterable, { ...options, envelopes: true });
|
|
459
|
+
}
|
|
460
|
+
mergeJournal(file) {
|
|
461
|
+
if (path.resolve(file) === path.resolve(this.journal)) return;
|
|
462
|
+
// Validate the entire source before exposing any imported advisory. Import
|
|
463
|
+
// writes each derived shard once; only pointer metadata, not native advisory
|
|
464
|
+
// bodies, accumulates in memory for a large seed.
|
|
465
|
+
for (const _item of journalTransactions(file)) { /* validation pass */ }
|
|
466
|
+
return this._locked(() => {
|
|
467
|
+
const cache = new Map(), fd = fs.openSync(this.journal, 'a', 0o600);
|
|
468
|
+
let offset = this._size();
|
|
469
|
+
try {
|
|
470
|
+
for (const item of journalTransactions(file)) {
|
|
471
|
+
fs.writeFileSync(fd, item.line);
|
|
472
|
+
this._apply(item.transaction, offset, cache, false);
|
|
473
|
+
offset += Buffer.byteLength(item.line);
|
|
474
|
+
}
|
|
475
|
+
fs.fsyncSync(fd);
|
|
476
|
+
} finally { fs.closeSync(fd); }
|
|
477
|
+
this._flush(cache);
|
|
478
|
+
this._checkpoint(offset);
|
|
479
|
+
});
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
function openAdvisoryStore(options) { return require('./advisory-store-sqlite').openAdvisoryStore(options); }
|
|
484
|
+
module.exports = { openAdvisoryStore, AdvisoryStore, DEFAULT_QUERY_TTL_MS, validateRecord, validateQuery, validateCoverage, packageName, packageKeys, queryKey, coverageKey, recordKey, advisoryId, queryCoversRecord, isWithdrawn, selectAdvisoryRecord, revision, wins, hash, key, journalTransactions };
|