vigievuln 1.1.3 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +15 -0
- package/README.md +47 -124
- package/completions/vigievuln.bash +1 -1
- package/completions/vigievuln.zsh +1 -0
- 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 +350 -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 +26 -5
- 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 +72 -7
- package/lib/codecs/npm/collect.js +12 -5
- package/lib/codecs/npm/parse.js +12 -5
- package/lib/codecs/npm/registry.js +40 -11
- 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 +82 -13
- package/lib/cve-npm-proxy.js +29 -0
- package/lib/cve-report.js +142 -55
- 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/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/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 +42 -16
- package/lib/osv-db.js +253 -59
- package/lib/osv-legacy.js +57 -0
- package/lib/osv.js +241 -170
- 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 +33 -19
- package/lib/providers/vigievuln.js +7 -0
- package/lib/proxy-cache.js +1 -1
- package/lib/proxy-scope.js +59 -0
- package/lib/resource-cache/engine.js +25 -5
- 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 +358 -104
|
@@ -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 };
|
|
@@ -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};
|