@shieldaai/security-watch 0.0.0-stage → 1.0.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 +170 -0
- package/CONTRIBUTING.md +92 -0
- package/LICENSE +202 -0
- package/README.md +394 -2
- package/SECURITY.md +62 -0
- package/dist/assessment.d.ts +16 -0
- package/dist/assessment.js +569 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +1105 -0
- package/dist/config.d.ts +302 -0
- package/dist/config.js +381 -0
- package/dist/coverage.d.ts +4 -0
- package/dist/coverage.js +11 -0
- package/dist/cve-now.d.ts +35 -0
- package/dist/cve-now.js +1002 -0
- package/dist/cvss4.d.ts +3 -0
- package/dist/cvss4.js +39 -0
- package/dist/delivery.d.ts +58 -0
- package/dist/delivery.js +687 -0
- package/dist/ecosystems.d.ts +48 -0
- package/dist/ecosystems.js +332 -0
- package/dist/engine.d.ts +80 -0
- package/dist/engine.js +388 -0
- package/dist/everyday-words.d.ts +11 -0
- package/dist/everyday-words.js +256 -0
- package/dist/health.d.ts +24 -0
- package/dist/health.js +122 -0
- package/dist/heartbeat.d.ts +13 -0
- package/dist/heartbeat.js +74 -0
- package/dist/http.d.ts +15 -0
- package/dist/http.js +280 -0
- package/dist/index.d.ts +36 -0
- package/dist/index.js +23 -0
- package/dist/inventory-evidence.d.ts +10 -0
- package/dist/inventory-evidence.js +206 -0
- package/dist/inventory.d.ts +276 -0
- package/dist/inventory.js +336 -0
- package/dist/lock.d.ts +3 -0
- package/dist/lock.js +112 -0
- package/dist/maintenance.d.ts +48 -0
- package/dist/maintenance.js +295 -0
- package/dist/matching.d.ts +29 -0
- package/dist/matching.js +537 -0
- package/dist/models.d.ts +33 -0
- package/dist/models.js +932 -0
- package/dist/operations.d.ts +17 -0
- package/dist/operations.js +117 -0
- package/dist/pilot-cases.d.ts +171 -0
- package/dist/pilot-cases.js +330 -0
- package/dist/pilot-input.d.ts +16 -0
- package/dist/pilot-input.js +125 -0
- package/dist/pilot-recall.d.ts +166 -0
- package/dist/pilot-recall.js +231 -0
- package/dist/pilot-report.d.ts +113 -0
- package/dist/pilot-report.js +279 -0
- package/dist/pilot-responses.d.ts +111 -0
- package/dist/pilot-responses.js +159 -0
- package/dist/providers.d.ts +209 -0
- package/dist/providers.js +459 -0
- package/dist/python-version.d.ts +3 -0
- package/dist/python-version.js +30 -0
- package/dist/rehearsal.d.ts +440 -0
- package/dist/rehearsal.js +372 -0
- package/dist/sbom.d.ts +13 -0
- package/dist/sbom.js +193 -0
- package/dist/setup.d.ts +113 -0
- package/dist/setup.js +100 -0
- package/dist/source-error.d.ts +38 -0
- package/dist/source-error.js +71 -0
- package/dist/sources.d.ts +3 -0
- package/dist/sources.js +1725 -0
- package/dist/store.d.ts +96 -0
- package/dist/store.js +953 -0
- package/dist/types.d.ts +404 -0
- package/dist/types.js +1 -0
- package/dist/util.d.ts +29 -0
- package/dist/util.js +94 -0
- package/dist/vendor/cvss4-reference.d.ts +2 -0
- package/dist/vendor/cvss4-reference.js +789 -0
- package/dist/vendor-sources.d.ts +24 -0
- package/dist/vendor-sources.js +56 -0
- package/dist/word-filter.d.ts +3 -0
- package/dist/word-filter.js +3291 -0
- package/docs/alert-outcome-evaluation.md +150 -0
- package/docs/compatibility.md +35 -0
- package/docs/configuration.md +666 -0
- package/docs/cvss-v4-support.md +41 -0
- package/docs/offline-advisory-preview.md +114 -0
- package/docs/offline-rehearsal.md +44 -0
- package/docs/pilot-cases.md +58 -0
- package/docs/pilot-recall.md +124 -0
- package/docs/pilot-report.md +52 -0
- package/docs/validation/alert-outcome-evaluation-2026-11-05.json +2935 -0
- package/docs/validation/cvss-v4-reference-parity-2026-11-05.json +93 -0
- package/docs/validation/rehearsal-accepted-2026-11-05.json +175 -0
- package/docs/validation/rehearsal-unknown-2026-11-05.json +175 -0
- package/docs/vendor/cvss-v4-LICENSE.txt +22 -0
- package/docs/vendor/cvss-v4-provenance.json +38 -0
- package/examples/advisories.json +17 -0
- package/examples/agent-advisories-2026.json +145 -0
- package/examples/agent-advisory-cases-2026.json +397 -0
- package/examples/common-systems.yaml +243 -0
- package/examples/libraries.example.txt +18 -0
- package/examples/libraries.example.yaml +40 -0
- package/examples/library-watch.example.yaml +27 -0
- package/examples/offline-advisory-preview.mjs +42 -0
- package/examples/rehearsal.json +75 -0
- package/examples/security-watch.example.yaml +86 -0
- package/examples/systems.example.yaml +35 -0
- package/package.json +85 -4
package/dist/sources.js
ADDED
|
@@ -0,0 +1,1725 @@
|
|
|
1
|
+
import { XMLParser, XMLValidator } from 'fast-xml-parser';
|
|
2
|
+
import { defaultTreeAdapter, parse, parseFragment } from 'parse5';
|
|
3
|
+
import { compare, valid } from 'semver';
|
|
4
|
+
import { cvssV4BaseScore } from './cvss4.js';
|
|
5
|
+
import { cleanText, hash, highest, singleLine, timestamp } from './util.js';
|
|
6
|
+
import { collectCveNow, evidenceRelevant } from './cve-now.js';
|
|
7
|
+
import { VENDOR_FEEDS, vendorArticleBody, vendorArticleTarget } from './vendor-sources.js';
|
|
8
|
+
import { exactLibraryVersion, normalizeEcosystem, normalizePackageName, osvPackageNames, samePackage, } from './ecosystems.js';
|
|
9
|
+
import { PartialSourceError, SourceError, SourceHttpError, SourceItemFailures, sourceCanceled, throwSourceFailure, } from './source-error.js';
|
|
10
|
+
const OSV = 'https://api.osv.dev/v1';
|
|
11
|
+
const GITHUB = 'https://api.github.com/advisories';
|
|
12
|
+
const KEV = 'https://raw.githubusercontent.com/cisagov/kev-data/develop/known_exploited_vulnerabilities.json';
|
|
13
|
+
const HACKER_NEWS = 'https://feeds.feedburner.com/TheHackersNews';
|
|
14
|
+
const MAX_PAGES = 50;
|
|
15
|
+
const MAX_ADVISORIES = 5_000;
|
|
16
|
+
const MAX_FEED_ENTRIES = 500;
|
|
17
|
+
const LATE_ENTRY_DAYS = 7;
|
|
18
|
+
const HOUR = 3_600_000;
|
|
19
|
+
/** How long a GitHub record that cannot be read is asked for again before it can be given up on. */
|
|
20
|
+
const UNREADABLE_HOLD_HOURS = 24;
|
|
21
|
+
/** Failed reads, in runs that read other records, before such a record is given up on. */
|
|
22
|
+
const OWED_GITHUB_ATTEMPTS = 3;
|
|
23
|
+
/** How many such records are remembered, and how many are asked for by identifier in one run. */
|
|
24
|
+
const MAX_UNREADABLE = 10_000;
|
|
25
|
+
const REFETCH_PER_RUN = 10;
|
|
26
|
+
const REFETCH_WITHOUT_TOKEN = 2;
|
|
27
|
+
/** Without a token, rows listed beyond which a row without an identifier no longer holds the listing. */
|
|
28
|
+
const HOLD_ROWS_WITHOUT_TOKEN = 300;
|
|
29
|
+
/** Update times of rows without an identifier remembered per package, the latest kept. */
|
|
30
|
+
const ROW_VERSIONS = 50;
|
|
31
|
+
function record(value) {
|
|
32
|
+
if (!value || typeof value !== 'object' || Array.isArray(value))
|
|
33
|
+
throw new SourceError('Invalid source schema.');
|
|
34
|
+
return value;
|
|
35
|
+
}
|
|
36
|
+
function array(value, optional = false) {
|
|
37
|
+
if (value === undefined && optional)
|
|
38
|
+
return [];
|
|
39
|
+
if (!Array.isArray(value))
|
|
40
|
+
throw new SourceError('Invalid source schema.');
|
|
41
|
+
return value;
|
|
42
|
+
}
|
|
43
|
+
function string(value) {
|
|
44
|
+
if (typeof value !== 'string' || !value.trim())
|
|
45
|
+
throw new SourceError('Invalid source schema.');
|
|
46
|
+
return value;
|
|
47
|
+
}
|
|
48
|
+
function optionalString(value) {
|
|
49
|
+
if (value === undefined || value === null)
|
|
50
|
+
return undefined;
|
|
51
|
+
return string(value);
|
|
52
|
+
}
|
|
53
|
+
function date(value) {
|
|
54
|
+
const input = string(value);
|
|
55
|
+
if (!Number.isFinite(Date.parse(input)))
|
|
56
|
+
throw new SourceError('Invalid source date.');
|
|
57
|
+
return new Date(input).toISOString();
|
|
58
|
+
}
|
|
59
|
+
/** A news story is linked to at most this many advisories: the first identifiers it cites. */
|
|
60
|
+
const MAX_STORY_IDENTIFIERS = 100;
|
|
61
|
+
/**
|
|
62
|
+
* The advisory identifiers a story cites, in the order they appear. A roundup can list hundreds;
|
|
63
|
+
* each one becomes a lookup and a candidate finding, so only the first ones are followed.
|
|
64
|
+
*/
|
|
65
|
+
function citedIdentifiers(text) {
|
|
66
|
+
// The number has a bounded length: a longer run of digits is not an identifier.
|
|
67
|
+
return aliases(text.match(/\b(?:CVE-\d{4}-\d{4,19}|GHSA-[a-z\d]{4}-[a-z\d]{4}-[a-z\d]{4})\b/gi) ?? []).slice(0, MAX_STORY_IDENTIFIERS);
|
|
68
|
+
}
|
|
69
|
+
function aliases(values) {
|
|
70
|
+
return [
|
|
71
|
+
...new Set(values
|
|
72
|
+
.filter((v) => typeof v === 'string' && v.length > 0)
|
|
73
|
+
.map((v) => /^cve-/i.test(v) ? v.toUpperCase() : /^ghsa-/i.test(v) ? `GHSA-${v.slice(5).toLowerCase()}` : v)),
|
|
74
|
+
];
|
|
75
|
+
}
|
|
76
|
+
function aliasStrings(value) {
|
|
77
|
+
return array(value, true).map(string);
|
|
78
|
+
}
|
|
79
|
+
function severity(value) {
|
|
80
|
+
const normalized = typeof value === 'string' ? value.toLowerCase() : '';
|
|
81
|
+
if (normalized === 'moderate')
|
|
82
|
+
return 'medium';
|
|
83
|
+
return normalized === 'critical' || normalized === 'high' || normalized === 'medium' || normalized === 'low'
|
|
84
|
+
? normalized
|
|
85
|
+
: 'unknown';
|
|
86
|
+
}
|
|
87
|
+
function scoreSeverity(score) {
|
|
88
|
+
if (typeof score !== 'number' || !Number.isFinite(score) || score < 0 || score > 10)
|
|
89
|
+
return 'unknown';
|
|
90
|
+
return score >= 9
|
|
91
|
+
? 'critical'
|
|
92
|
+
: score >= 7
|
|
93
|
+
? 'high'
|
|
94
|
+
: score >= 4
|
|
95
|
+
? 'medium'
|
|
96
|
+
: score > 0
|
|
97
|
+
? 'low'
|
|
98
|
+
: 'unknown';
|
|
99
|
+
}
|
|
100
|
+
// FIRST CVSS 3.0/3.1 base equations only. Unsupported vectors remain unknown.
|
|
101
|
+
function vectorSeverity(vector) {
|
|
102
|
+
if (typeof vector !== 'string')
|
|
103
|
+
return 'unknown';
|
|
104
|
+
if (/^(?:\d|10)(?:\.\d+)?$/.test(vector))
|
|
105
|
+
return scoreSeverity(Number(vector));
|
|
106
|
+
if (!/^CVSS:3\.[01]\//.test(vector))
|
|
107
|
+
return 'unknown';
|
|
108
|
+
const metrics = {};
|
|
109
|
+
for (const part of vector.split('/').slice(1)) {
|
|
110
|
+
const pieces = part.split(':');
|
|
111
|
+
if (pieces.length !== 2 || !pieces[0] || !pieces[1] || metrics[pieces[0]])
|
|
112
|
+
return 'unknown';
|
|
113
|
+
metrics[pieces[0]] = pieces[1];
|
|
114
|
+
}
|
|
115
|
+
if (metrics.S !== 'U' && metrics.S !== 'C')
|
|
116
|
+
return 'unknown';
|
|
117
|
+
const pick = (key, weights) => weights[metrics[key] ?? ''];
|
|
118
|
+
const av = pick('AV', { N: 0.85, A: 0.62, L: 0.55, P: 0.2 });
|
|
119
|
+
const ac = pick('AC', { L: 0.77, H: 0.44 });
|
|
120
|
+
const pr = pick('PR', { N: 0.85, L: metrics.S === 'C' ? 0.68 : 0.62, H: metrics.S === 'C' ? 0.5 : 0.27 });
|
|
121
|
+
const ui = pick('UI', { N: 0.85, R: 0.62 });
|
|
122
|
+
const c = pick('C', { N: 0, L: 0.22, H: 0.56 });
|
|
123
|
+
const i = pick('I', { N: 0, L: 0.22, H: 0.56 });
|
|
124
|
+
const a = pick('A', { N: 0, L: 0.22, H: 0.56 });
|
|
125
|
+
if (av === undefined ||
|
|
126
|
+
ac === undefined ||
|
|
127
|
+
pr === undefined ||
|
|
128
|
+
ui === undefined ||
|
|
129
|
+
c === undefined ||
|
|
130
|
+
i === undefined ||
|
|
131
|
+
a === undefined)
|
|
132
|
+
return 'unknown';
|
|
133
|
+
const iss = 1 - (1 - c) * (1 - i) * (1 - a);
|
|
134
|
+
const impact = metrics.S === 'U' ? 6.42 * iss : 7.52 * (iss - 0.029) - 3.25 * (iss - 0.02) ** 15;
|
|
135
|
+
if (impact <= 0)
|
|
136
|
+
return 'unknown';
|
|
137
|
+
const raw = Math.min((metrics.S === 'C' ? 1.08 : 1) * (impact + 8.22 * av * ac * pr * ui), 10);
|
|
138
|
+
const integer = Math.round(raw * 100_000);
|
|
139
|
+
const rounded = integer % 10_000 === 0 ? integer / 100_000 : (Math.floor(integer / 10_000) + 1) / 10;
|
|
140
|
+
return scoreSeverity(rounded);
|
|
141
|
+
}
|
|
142
|
+
/** At most 32 v4 candidates per advisory. Overflow fails collection instead of truncating a severity floor. */
|
|
143
|
+
function vectorCollector() {
|
|
144
|
+
const details = { base_scores: [], unsupported_vectors: 0 };
|
|
145
|
+
let candidates = 0;
|
|
146
|
+
return {
|
|
147
|
+
score(vector, declaredType) {
|
|
148
|
+
const v4 = declaredType === 'CVSS_V4' || (typeof vector === 'string' && vector.startsWith('CVSS:4'));
|
|
149
|
+
if (!v4)
|
|
150
|
+
return vectorSeverity(vector);
|
|
151
|
+
if (++candidates > 32)
|
|
152
|
+
throw new SourceError('CVSS v4 candidate limit exceeded; advisory not accepted.');
|
|
153
|
+
const scored = declaredType === undefined || declaredType === 'CVSS_V4' ? cvssV4BaseScore(vector) : undefined;
|
|
154
|
+
if (!scored) {
|
|
155
|
+
details.unsupported_vectors++;
|
|
156
|
+
return 'unknown';
|
|
157
|
+
}
|
|
158
|
+
if (!details.base_scores.some((item) => item.vector === scored.vector))
|
|
159
|
+
details.base_scores.push(scored);
|
|
160
|
+
return scoreSeverity(scored.score);
|
|
161
|
+
},
|
|
162
|
+
details() {
|
|
163
|
+
return candidates ? { cvss_v4: details } : {};
|
|
164
|
+
},
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
function optionalRecord(value) {
|
|
168
|
+
return value === undefined || value === null ? {} : record(value);
|
|
169
|
+
}
|
|
170
|
+
function publicUrl(input, fallback) {
|
|
171
|
+
if (typeof input !== 'string')
|
|
172
|
+
return fallback;
|
|
173
|
+
try {
|
|
174
|
+
const url = new URL(input, fallback);
|
|
175
|
+
if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password)
|
|
176
|
+
return fallback;
|
|
177
|
+
return url.href;
|
|
178
|
+
}
|
|
179
|
+
catch {
|
|
180
|
+
return fallback;
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
function retainNewest(target, item) {
|
|
184
|
+
const previous = target.get(item.id);
|
|
185
|
+
if (!previous || Date.parse(item.modified_at) >= Date.parse(previous.modified_at))
|
|
186
|
+
target.set(item.id, item);
|
|
187
|
+
}
|
|
188
|
+
async function json(http, url, options = {}) {
|
|
189
|
+
const response = await http(url, { maxBytes: 8_000_000, ...options });
|
|
190
|
+
if (response.status !== 200)
|
|
191
|
+
throw new SourceHttpError('Source', response.status);
|
|
192
|
+
try {
|
|
193
|
+
return JSON.parse(response.body);
|
|
194
|
+
}
|
|
195
|
+
catch {
|
|
196
|
+
throw new SourceError('Source returned invalid JSON.');
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
function sourcePackage(ecosystem, name) {
|
|
200
|
+
let normalized;
|
|
201
|
+
try {
|
|
202
|
+
normalized = normalizeEcosystem(ecosystem);
|
|
203
|
+
}
|
|
204
|
+
catch {
|
|
205
|
+
return { ecosystem, name };
|
|
206
|
+
}
|
|
207
|
+
try {
|
|
208
|
+
return { ecosystem: normalized, name: normalizePackageName(normalized, name) };
|
|
209
|
+
}
|
|
210
|
+
catch {
|
|
211
|
+
// Keep the published spelling. A name this application cannot normalise matches no inventory
|
|
212
|
+
// entry; rejecting it would discard the advisory's other packages and hold back the checkpoint.
|
|
213
|
+
return { ecosystem: normalized, name };
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
function osvRanges(value) {
|
|
217
|
+
const ranges = array(value, true);
|
|
218
|
+
if (!ranges.length)
|
|
219
|
+
return undefined;
|
|
220
|
+
const expressions = [];
|
|
221
|
+
for (const raw of ranges) {
|
|
222
|
+
const range = record(raw);
|
|
223
|
+
if (range.type !== 'SEMVER')
|
|
224
|
+
return undefined;
|
|
225
|
+
const events = array(range.events);
|
|
226
|
+
if (!events.length)
|
|
227
|
+
throw new SourceError('Invalid OSV version range.');
|
|
228
|
+
const timeline = [];
|
|
229
|
+
const limits = [];
|
|
230
|
+
for (const rawEvent of events) {
|
|
231
|
+
const event = record(rawEvent);
|
|
232
|
+
const fields = ['introduced', 'fixed', 'last_affected', 'limit'].filter((field) => event[field] !== undefined);
|
|
233
|
+
if (fields.length !== 1)
|
|
234
|
+
throw new SourceError('Invalid OSV version range.');
|
|
235
|
+
const field = fields[0];
|
|
236
|
+
const version = string(event[field]);
|
|
237
|
+
if (field === 'limit' && version.includes('*')) {
|
|
238
|
+
limits.push('*');
|
|
239
|
+
continue;
|
|
240
|
+
}
|
|
241
|
+
const normalized = version === '0' && field === 'introduced' ? '0' : valid(version);
|
|
242
|
+
if (!normalized)
|
|
243
|
+
return undefined;
|
|
244
|
+
if (field === 'limit')
|
|
245
|
+
limits.push(normalized);
|
|
246
|
+
else
|
|
247
|
+
timeline.push({ field, version: normalized });
|
|
248
|
+
}
|
|
249
|
+
if (!timeline.some((event) => event.field === 'introduced'))
|
|
250
|
+
throw new SourceError('Invalid OSV version range.');
|
|
251
|
+
const versionOrder = (left, right) => left === right ? 0 : left === '0' ? -1 : right === '0' ? 1 : compare(left, right);
|
|
252
|
+
// OSV recommends sorted events but does not require source order. Limits apply
|
|
253
|
+
// independently to the whole range; they are not fix transitions.
|
|
254
|
+
timeline.sort((a, b) => versionOrder(a.version, b.version));
|
|
255
|
+
const maximum = limits.includes('*') ? undefined : limits.sort(versionOrder).at(-1);
|
|
256
|
+
let lower;
|
|
257
|
+
let open = false;
|
|
258
|
+
const expression = (upper) => [lower && `>=${lower}`, upper, maximum && `<${maximum}`].filter(Boolean).join(' ') || '*';
|
|
259
|
+
for (let index = 0; index < timeline.length; index++) {
|
|
260
|
+
const event = timeline[index];
|
|
261
|
+
const previous = timeline[index - 1];
|
|
262
|
+
// Conflicting transitions at one normalized version have no unambiguous order.
|
|
263
|
+
if (previous && versionOrder(event.version, previous.version) === 0 && event.field !== previous.field)
|
|
264
|
+
return undefined;
|
|
265
|
+
if (event.field === 'introduced') {
|
|
266
|
+
if (!open)
|
|
267
|
+
lower = event.version === '0' ? undefined : event.version;
|
|
268
|
+
open = true;
|
|
269
|
+
}
|
|
270
|
+
else if (open) {
|
|
271
|
+
expressions.push(expression(`${event.field === 'last_affected' ? '<=' : '<'}${event.version}`));
|
|
272
|
+
open = false;
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
if (open)
|
|
276
|
+
expressions.push(expression());
|
|
277
|
+
}
|
|
278
|
+
return expressions.length ? expressions.join(' || ') : undefined;
|
|
279
|
+
}
|
|
280
|
+
function osvRecord(raw, expectedId, matches, now) {
|
|
281
|
+
const data = record(raw);
|
|
282
|
+
if (string(data.id) !== expectedId)
|
|
283
|
+
throw new SourceError('OSV returned a mismatched advisory ID.');
|
|
284
|
+
const packageClaims = [];
|
|
285
|
+
const vectors = vectorCollector();
|
|
286
|
+
const severities = [severity(optionalRecord(data.database_specific).severity)];
|
|
287
|
+
for (const rawSeverity of array(data.severity, true)) {
|
|
288
|
+
const item = record(rawSeverity);
|
|
289
|
+
severities.push(vectors.score(item.score, item.type));
|
|
290
|
+
}
|
|
291
|
+
for (const rawAffected of array(data.affected, true)) {
|
|
292
|
+
const affected = record(rawAffected);
|
|
293
|
+
// OSV can include a separate Git-only entry beside registry package entries.
|
|
294
|
+
if (affected.package === undefined) {
|
|
295
|
+
const ranges = array(affected.ranges);
|
|
296
|
+
if (!ranges.length ||
|
|
297
|
+
!ranges.every((rawRange) => {
|
|
298
|
+
const range = record(rawRange);
|
|
299
|
+
return range.type === 'GIT' && typeof range.repo === 'string' && range.repo.length > 0;
|
|
300
|
+
}))
|
|
301
|
+
throw new SourceError('OSV returned an affected entry without a package identity.');
|
|
302
|
+
continue;
|
|
303
|
+
}
|
|
304
|
+
const pkg = record(affected.package);
|
|
305
|
+
const { ecosystem, name } = sourcePackage(string(pkg.ecosystem), string(pkg.name));
|
|
306
|
+
const range = ecosystem === 'npm' ? osvRanges(affected.ranges) : undefined;
|
|
307
|
+
const versions = array(affected.versions, true).map(string);
|
|
308
|
+
const matched_versions = [
|
|
309
|
+
...new Set(matches
|
|
310
|
+
.filter((query) => samePackage(query, { ecosystem, name }))
|
|
311
|
+
.map((query) => query.version)
|
|
312
|
+
.filter((version) => version !== undefined)),
|
|
313
|
+
];
|
|
314
|
+
const fixed = array(affected.ranges, true)
|
|
315
|
+
.flatMap((rawRange) => array(record(rawRange).events, true))
|
|
316
|
+
// Kept whole on one line: the notification's Fix line shows a version whole or counts it as
|
|
317
|
+
// too long to show, never a cut one, which would be another version.
|
|
318
|
+
.map((rawEvent) => singleLine(optionalString(record(rawEvent).fixed) ?? ''))
|
|
319
|
+
.filter((v) => v.length > 0);
|
|
320
|
+
packageClaims.push({
|
|
321
|
+
ecosystem,
|
|
322
|
+
name,
|
|
323
|
+
...(range ? { range } : {}),
|
|
324
|
+
...(versions.length ? { versions } : {}),
|
|
325
|
+
...(matched_versions.length ? { matched_versions } : {}),
|
|
326
|
+
...(fixed.length ? { fixed: [...new Set(fixed)].join(', ') } : {}),
|
|
327
|
+
});
|
|
328
|
+
severities.push(severity(optionalRecord(affected.database_specific).severity));
|
|
329
|
+
for (const rawSeverity of array(affected.severity, true)) {
|
|
330
|
+
const item = record(rawSeverity);
|
|
331
|
+
severities.push(vectors.score(item.score, item.type));
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
// Queries identify the package even when details omit it. Only a versioned query proves impact.
|
|
335
|
+
for (const query of matches)
|
|
336
|
+
if (!packageClaims.some((claim) => samePackage(claim, query))) {
|
|
337
|
+
const versions = [
|
|
338
|
+
...new Set(matches
|
|
339
|
+
.filter((match) => samePackage(match, query))
|
|
340
|
+
.map((match) => match.version)
|
|
341
|
+
.filter((version) => version !== undefined)),
|
|
342
|
+
];
|
|
343
|
+
packageClaims.push({
|
|
344
|
+
ecosystem: query.ecosystem,
|
|
345
|
+
name: query.name,
|
|
346
|
+
...(versions.length ? { matched_versions: versions } : {}),
|
|
347
|
+
});
|
|
348
|
+
}
|
|
349
|
+
const canonical = `https://osv.dev/vulnerability/${encodeURIComponent(expectedId)}`;
|
|
350
|
+
return {
|
|
351
|
+
id: `osv:${expectedId}`,
|
|
352
|
+
source: 'osv',
|
|
353
|
+
kind: 'advisory',
|
|
354
|
+
title: cleanText(optionalString(data.summary) ?? expectedId, 500),
|
|
355
|
+
url: canonical,
|
|
356
|
+
description: cleanText(optionalString(data.details) ?? optionalString(data.summary) ?? expectedId, 16_000),
|
|
357
|
+
aliases: aliases([expectedId, ...aliasStrings(data.aliases)]),
|
|
358
|
+
severity: highest(...severities),
|
|
359
|
+
...vectors.details(),
|
|
360
|
+
modified_at: date(data.modified),
|
|
361
|
+
fetched_at: timestamp(now),
|
|
362
|
+
...(data.published ? { published_at: date(data.published) } : {}),
|
|
363
|
+
packages: packageClaims,
|
|
364
|
+
withdrawn: data.withdrawn === undefined || data.withdrawn === null ? false : !!date(data.withdrawn),
|
|
365
|
+
malware: /^MAL-/.test(expectedId),
|
|
366
|
+
};
|
|
367
|
+
}
|
|
368
|
+
async function osv(inventory, previous, http, now) {
|
|
369
|
+
const unique = new Map();
|
|
370
|
+
for (const system of inventory.systems)
|
|
371
|
+
for (const component of system.components) {
|
|
372
|
+
const ecosystem = normalizeEcosystem(component.ecosystem);
|
|
373
|
+
let version;
|
|
374
|
+
// Imported lockfiles may describe an unresolved Git/URL dependency instead of a registry version.
|
|
375
|
+
// Query its package name conservatively without turning that text into an exact-version match.
|
|
376
|
+
if (component.version) {
|
|
377
|
+
try {
|
|
378
|
+
version = exactLibraryVersion(component.version, ecosystem);
|
|
379
|
+
}
|
|
380
|
+
catch {
|
|
381
|
+
/* Applicability remains unknown. */
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
for (const name of osvPackageNames(ecosystem, component.name)) {
|
|
385
|
+
const key = JSON.stringify([ecosystem, name, version ?? null]);
|
|
386
|
+
unique.set(key, {
|
|
387
|
+
ecosystem,
|
|
388
|
+
name,
|
|
389
|
+
...(version ? { version } : {}),
|
|
390
|
+
seen: new Set(),
|
|
391
|
+
});
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
const queries = [...unique.values()];
|
|
395
|
+
if (queries.length > 10_000)
|
|
396
|
+
throw new SourceError('OSV inventory exceeds the 10,000 unique package queries limit.');
|
|
397
|
+
const results = [];
|
|
398
|
+
const invalid = new SourceItemFailures();
|
|
399
|
+
try {
|
|
400
|
+
const matched = new Map();
|
|
401
|
+
for (let offset = 0; offset < queries.length; offset += 100) {
|
|
402
|
+
let pending = queries.slice(offset, offset + 100);
|
|
403
|
+
for (let page = 0; pending.length; page++) {
|
|
404
|
+
if (page >= MAX_PAGES)
|
|
405
|
+
throw new SourceError('OSV pagination limit reached; collection is incomplete.');
|
|
406
|
+
const body = JSON.stringify({
|
|
407
|
+
queries: pending.map((query) => ({
|
|
408
|
+
package: { ecosystem: query.ecosystem, name: query.name },
|
|
409
|
+
...(query.version ? { version: query.version } : {}),
|
|
410
|
+
...(query.page_token ? { page_token: query.page_token } : {}),
|
|
411
|
+
})),
|
|
412
|
+
});
|
|
413
|
+
const data = record(await json(http, `${OSV}/querybatch`, {
|
|
414
|
+
method: 'POST',
|
|
415
|
+
headers: { 'content-type': 'application/json' },
|
|
416
|
+
body,
|
|
417
|
+
}));
|
|
418
|
+
const results = array(data.results);
|
|
419
|
+
if (results.length !== pending.length)
|
|
420
|
+
throw new SourceError('OSV batch result count did not match the request.');
|
|
421
|
+
const next = [];
|
|
422
|
+
for (let index = 0; index < results.length; index++) {
|
|
423
|
+
const result = invalid.read(() => record(results[index]));
|
|
424
|
+
if (!result)
|
|
425
|
+
continue;
|
|
426
|
+
const query = pending[index];
|
|
427
|
+
const vulns = invalid.read(() => array(result.vulns, true));
|
|
428
|
+
for (const rawVuln of vulns ?? []) {
|
|
429
|
+
const id = invalid.read(() => {
|
|
430
|
+
const vuln = record(rawVuln);
|
|
431
|
+
if (vuln.modified !== undefined)
|
|
432
|
+
date(vuln.modified);
|
|
433
|
+
return string(vuln.id);
|
|
434
|
+
});
|
|
435
|
+
if (!id)
|
|
436
|
+
continue;
|
|
437
|
+
if (!matched.has(id))
|
|
438
|
+
matched.set(id, []);
|
|
439
|
+
if (!matched.get(id).some((match) => samePackage(match, query) && match.version === query.version))
|
|
440
|
+
matched.get(id).push(query);
|
|
441
|
+
if (matched.size > MAX_ADVISORIES)
|
|
442
|
+
throw new SourceError('OSV advisory limit reached; collection is incomplete.');
|
|
443
|
+
}
|
|
444
|
+
const token = optionalString(result.next_page_token);
|
|
445
|
+
if (token) {
|
|
446
|
+
if (query.seen.has(token))
|
|
447
|
+
throw new SourceError('OSV returned a repeated pagination token.');
|
|
448
|
+
query.seen.add(token);
|
|
449
|
+
next.push({ ...query, page_token: token });
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
pending = next;
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
const ids = new Set(matched.keys());
|
|
456
|
+
// Stored records are refreshed while their package is in the inventory: one for a package that
|
|
457
|
+
// was removed concerns no finding, and re-reading all of history would grow without end.
|
|
458
|
+
const names = new Set(queries.map((query) => query.name.toLowerCase()));
|
|
459
|
+
for (const item of previous)
|
|
460
|
+
if (item.source === 'osv' &&
|
|
461
|
+
item.id.startsWith('osv:') &&
|
|
462
|
+
(item.packages ?? []).some((claim) => names.has(claim.name.toLowerCase())))
|
|
463
|
+
ids.add(item.id.slice(4));
|
|
464
|
+
if (ids.size > MAX_ADVISORIES)
|
|
465
|
+
throw new SourceError('OSV historical advisory limit reached; collection is incomplete.');
|
|
466
|
+
// Bounded parallelism; historical IDs are refreshed even when they disappear from exact-version queries.
|
|
467
|
+
const allIds = [...ids];
|
|
468
|
+
let failures = 0;
|
|
469
|
+
let firstFailure;
|
|
470
|
+
// A stored record that OSV no longer serves is gone, not a failed request: it must not stop the
|
|
471
|
+
// refresh of the records after it, and, as with cve.now, its last known content stays current.
|
|
472
|
+
// Letting it age out would turn every exclusion resting on it into an urgent "unknown" on every
|
|
473
|
+
// scan while OSV itself answers normally.
|
|
474
|
+
const gone = (id, reason) => !matched.has(id) && reason instanceof SourceHttpError && reason.status === 404;
|
|
475
|
+
const storedCopy = new Map(previous.filter((item) => item.source === 'osv').map((item) => [item.id.slice(4), item]));
|
|
476
|
+
for (let index = 0; index < allIds.length; index += 4) {
|
|
477
|
+
const batch = allIds.slice(index, index + 4);
|
|
478
|
+
const settled = await Promise.allSettled(batch.map(async (id) => osvRecord(await json(http, `${OSV}/vulns/${encodeURIComponent(id)}`), id, matched.get(id) ?? [], now)));
|
|
479
|
+
const rejected = settled.filter((item, position) => item.status === 'rejected' && !gone(batch[position], item.reason));
|
|
480
|
+
const canceled = settled.find((item) => item.status === 'rejected' && sourceCanceled(item.reason));
|
|
481
|
+
if (canceled)
|
|
482
|
+
throw canceled.reason;
|
|
483
|
+
for (const [position, item] of settled.entries()) {
|
|
484
|
+
if (item.status === 'fulfilled')
|
|
485
|
+
results.push(item.value);
|
|
486
|
+
else if (gone(batch[position], item.reason)) {
|
|
487
|
+
const copy = storedCopy.get(batch[position]);
|
|
488
|
+
if (copy)
|
|
489
|
+
results.push({ ...copy, fetched_at: timestamp(now) });
|
|
490
|
+
}
|
|
491
|
+
else {
|
|
492
|
+
failures++;
|
|
493
|
+
firstFailure ??=
|
|
494
|
+
item.reason instanceof SourceError ? item.reason.message : 'Source request failed.';
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
if (rejected.length === batch.length ||
|
|
498
|
+
failures >= 8 ||
|
|
499
|
+
rejected.some(({ reason }) => reason instanceof SourceHttpError && [401, 403, 429].includes(reason.status)))
|
|
500
|
+
break;
|
|
501
|
+
}
|
|
502
|
+
if (failures)
|
|
503
|
+
throw new SourceError(`${failures} OSV advisory detail request(s) failed; collection is incomplete. ${firstFailure}`);
|
|
504
|
+
return invalid.finish('OSV', results);
|
|
505
|
+
}
|
|
506
|
+
catch (error) {
|
|
507
|
+
throwSourceFailure(error, results);
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
/**
|
|
511
|
+
* A GitHub advisory's identifier: its `ghsa_id`, or else the identifier its own links end with, so a
|
|
512
|
+
* renamed or reshaped `ghsa_id` field does not leave a record without one.
|
|
513
|
+
*/
|
|
514
|
+
function githubIdentifier(raw) {
|
|
515
|
+
if (typeof raw !== 'object' || raw === null || Array.isArray(raw))
|
|
516
|
+
return undefined;
|
|
517
|
+
const data = raw;
|
|
518
|
+
const id = /^GHSA-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}$/i;
|
|
519
|
+
if (typeof data.ghsa_id === 'string' && id.test(data.ghsa_id))
|
|
520
|
+
return data.ghsa_id;
|
|
521
|
+
for (const link of [data.html_url, data.url])
|
|
522
|
+
if (typeof link === 'string') {
|
|
523
|
+
const match = /\/advisories\/(GHSA-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4})(?:[/?#]|$)/i.exec(link);
|
|
524
|
+
if (match)
|
|
525
|
+
return match[1];
|
|
526
|
+
}
|
|
527
|
+
return undefined;
|
|
528
|
+
}
|
|
529
|
+
/** The package names a GitHub row names, normalised as stored claims are and in lower case, read as far as the row allows. */
|
|
530
|
+
function githubPackageNames(raw) {
|
|
531
|
+
const vulnerabilities = typeof raw === 'object' && raw !== null ? raw.vulnerabilities : undefined;
|
|
532
|
+
if (!Array.isArray(vulnerabilities))
|
|
533
|
+
return [];
|
|
534
|
+
return vulnerabilities.flatMap((vulnerability) => {
|
|
535
|
+
const pkg = typeof vulnerability === 'object' && vulnerability !== null
|
|
536
|
+
? vulnerability.package
|
|
537
|
+
: undefined;
|
|
538
|
+
const fields = typeof pkg === 'object' && pkg !== null ? pkg : {};
|
|
539
|
+
const name = fields.name;
|
|
540
|
+
if (typeof name !== 'string' || !name.trim())
|
|
541
|
+
return [];
|
|
542
|
+
const ecosystem = typeof fields.ecosystem === 'string' ? fields.ecosystem : '';
|
|
543
|
+
return [sourcePackage(ecosystem, name.trim()).name.toLowerCase()];
|
|
544
|
+
});
|
|
545
|
+
}
|
|
546
|
+
function githubRecord(raw, type, now) {
|
|
547
|
+
const data = record(raw);
|
|
548
|
+
const id = githubIdentifier(data);
|
|
549
|
+
if (!id)
|
|
550
|
+
throw new SourceError('Invalid GitHub advisory identifier.');
|
|
551
|
+
if (data.type !== undefined && data.type !== type)
|
|
552
|
+
throw new SourceError('GitHub returned an unexpected advisory type.');
|
|
553
|
+
const modified = date(data.updated_at);
|
|
554
|
+
if (Date.parse(modified) > now + 5 * 60_000)
|
|
555
|
+
throw new SourceError('Source returned a future modification timestamp; collection is incomplete.');
|
|
556
|
+
const packages = array(data.vulnerabilities).map((rawVulnerability) => {
|
|
557
|
+
const vulnerability = record(rawVulnerability);
|
|
558
|
+
const pkg = record(vulnerability.package);
|
|
559
|
+
const range = optionalString(vulnerability.vulnerable_version_range);
|
|
560
|
+
const patched = vulnerability.first_patched_version;
|
|
561
|
+
const fixed = singleLine((typeof patched === 'object' && patched !== null
|
|
562
|
+
? optionalString(record(patched).identifier)
|
|
563
|
+
: optionalString(patched)) ?? '');
|
|
564
|
+
return {
|
|
565
|
+
...sourcePackage(string(pkg.ecosystem), string(pkg.name)),
|
|
566
|
+
...(range ? { range } : {}),
|
|
567
|
+
...(fixed ? { fixed } : {}),
|
|
568
|
+
};
|
|
569
|
+
});
|
|
570
|
+
const cvss = optionalRecord(data.cvss);
|
|
571
|
+
const cvssVersions = optionalRecord(data.cvss_severities);
|
|
572
|
+
const vectors = vectorCollector();
|
|
573
|
+
const ratings = [severity(data.severity), scoreSeverity(cvss.score), vectors.score(cvss.vector_string)];
|
|
574
|
+
for (const [version, value] of Object.entries(cvssVersions))
|
|
575
|
+
if (value) {
|
|
576
|
+
const item = record(value);
|
|
577
|
+
ratings.push(scoreSeverity(item.score));
|
|
578
|
+
ratings.push(vectors.score(item.vector_string, version === 'cvss_v4' ? 'CVSS_V4' : version === 'cvss_v3' ? 'CVSS_V3' : version));
|
|
579
|
+
}
|
|
580
|
+
return {
|
|
581
|
+
id: `github:${id}`,
|
|
582
|
+
source: `github:${type}`,
|
|
583
|
+
kind: 'advisory',
|
|
584
|
+
title: cleanText(string(data.summary), 500),
|
|
585
|
+
url: `https://github.com/advisories/${encodeURIComponent(id)}`,
|
|
586
|
+
description: cleanText(optionalString(data.description) ?? string(data.summary), 16_000),
|
|
587
|
+
aliases: aliases([
|
|
588
|
+
id,
|
|
589
|
+
data.cve_id,
|
|
590
|
+
...array(data.identifiers, true).map((item) => string(record(item).value)),
|
|
591
|
+
]),
|
|
592
|
+
severity: highest(...ratings),
|
|
593
|
+
...vectors.details(),
|
|
594
|
+
modified_at: modified,
|
|
595
|
+
fetched_at: timestamp(now),
|
|
596
|
+
published_at: date(data.published_at),
|
|
597
|
+
packages,
|
|
598
|
+
withdrawn: data.withdrawn_at === undefined || data.withdrawn_at === null ? false : !!date(data.withdrawn_at),
|
|
599
|
+
malware: type === 'malware',
|
|
600
|
+
};
|
|
601
|
+
}
|
|
602
|
+
function nextGithubLink(link) {
|
|
603
|
+
if (!link)
|
|
604
|
+
return undefined;
|
|
605
|
+
for (const part of link.split(',')) {
|
|
606
|
+
const parsed = part.match(/^\s*<([^>]+)>\s*;\s*rel\s*=\s*"?([a-z]+)"?\s*$/i);
|
|
607
|
+
if (!parsed?.[1] || !parsed[2])
|
|
608
|
+
throw new SourceError('GitHub returned invalid pagination.');
|
|
609
|
+
if (parsed[2].toLowerCase() !== 'next')
|
|
610
|
+
continue;
|
|
611
|
+
let url;
|
|
612
|
+
try {
|
|
613
|
+
url = new URL(parsed[1]);
|
|
614
|
+
}
|
|
615
|
+
catch {
|
|
616
|
+
throw new SourceError('GitHub returned invalid pagination.');
|
|
617
|
+
}
|
|
618
|
+
if (url.origin !== 'https://api.github.com' ||
|
|
619
|
+
url.pathname !== '/advisories' ||
|
|
620
|
+
url.username ||
|
|
621
|
+
url.password ||
|
|
622
|
+
url.hash)
|
|
623
|
+
throw new SourceError('GitHub returned an untrusted pagination destination.');
|
|
624
|
+
return url.href;
|
|
625
|
+
}
|
|
626
|
+
return undefined;
|
|
627
|
+
}
|
|
628
|
+
/**
|
|
629
|
+
* Where a GitHub scan's window starts, and since when every modification has been read through an
|
|
630
|
+
* unbroken chain of scans. A catch-up over more updates than one scan reads moves the window start on
|
|
631
|
+
* from scan to scan; the chain still covers everything since the scan that began it.
|
|
632
|
+
*/
|
|
633
|
+
function githubWindow(checkpoint, since, now) {
|
|
634
|
+
const saved = checkpoint === undefined ? undefined : Date.parse(checkpoint);
|
|
635
|
+
if (saved !== undefined && !Number.isFinite(saved))
|
|
636
|
+
throw new SourceError('Invalid source checkpoint; reset it before collecting.');
|
|
637
|
+
// A checkpoint ahead of the clock (a clock that was wrong, then corrected) would never be reached:
|
|
638
|
+
// collection starts as on a new installation, as cve.now does.
|
|
639
|
+
const previous = saved === undefined || saved > now ? now - 7 * 24 * HOUR : saved;
|
|
640
|
+
const start = Math.max(0, previous - HOUR);
|
|
641
|
+
const chained = since ? Date.parse(since) : NaN;
|
|
642
|
+
return { start, chainStart: Number.isFinite(chained) && chained <= start ? chained : start };
|
|
643
|
+
}
|
|
644
|
+
async function github(type, checkpoint, config, http, now, inventory, stored, since,
|
|
645
|
+
/**
|
|
646
|
+
* Records GitHub served in a form that cannot be read, remembered by identifier
|
|
647
|
+
* (`pending`: [id, first met, failed attempts]) and those given up on (`skipped`); the next
|
|
648
|
+
* values are set for the following run.
|
|
649
|
+
*/
|
|
650
|
+
unreadable = {}) {
|
|
651
|
+
const { start, chainStart } = githubWindow(checkpoint, since, now);
|
|
652
|
+
const url = new URL(GITHUB);
|
|
653
|
+
url.searchParams.set('type', type);
|
|
654
|
+
// GitHub's search-date parser rejects fractional seconds, unlike checkpoint timestamps.
|
|
655
|
+
const queryTime = (value) => timestamp(value).replace(/\.\d{3}Z$/, 'Z');
|
|
656
|
+
url.searchParams.set('modified', `${queryTime(start)}..${queryTime(now)}`);
|
|
657
|
+
url.searchParams.set('sort', 'updated');
|
|
658
|
+
url.searchParams.set('direction', 'asc');
|
|
659
|
+
url.searchParams.set('per_page', '100');
|
|
660
|
+
const headers = {
|
|
661
|
+
accept: 'application/vnd.github+json',
|
|
662
|
+
'x-github-api-version': '2026-03-10',
|
|
663
|
+
};
|
|
664
|
+
const token = process.env[config.sources.github_token_env];
|
|
665
|
+
if (token)
|
|
666
|
+
headers.authorization = `Bearer ${token}`;
|
|
667
|
+
let next = url.href;
|
|
668
|
+
const seen = new Set();
|
|
669
|
+
const evidence = new Map();
|
|
670
|
+
const invalid = new SourceItemFailures();
|
|
671
|
+
// A record that cannot be read is remembered by its identifier, as cve.now remembers the records
|
|
672
|
+
// it still owes, so the checkpoint keeps moving. It is asked for by identifier on later runs and
|
|
673
|
+
// given up on only after OWED_GITHUB_ATTEMPTS failed reads in runs that read other records and a
|
|
674
|
+
// day after it was first met. A stored copy of a record whose newer version could not be read is
|
|
675
|
+
// never confirmed as current: it ages, and exclusions resting on it go to review. A run that can
|
|
676
|
+
// read nothing is a format outage: the checkpoint waits, so that the whole window is listed again
|
|
677
|
+
// once GitHub serves the usual format.
|
|
678
|
+
const key = (id) => id.toUpperCase();
|
|
679
|
+
const pending = new Map();
|
|
680
|
+
/** Records stored from this type, by key: a given-up record with a stored copy matters most. */
|
|
681
|
+
const withCopy = new Set(stored.filter((item) => item.source === `github:${type}`).map((item) => key(item.id.slice(7))));
|
|
682
|
+
/** Records given up on, by key, with the identifier as GitHub wrote it. */
|
|
683
|
+
const skipped = new Map();
|
|
684
|
+
try {
|
|
685
|
+
for (const entry of JSON.parse(unreadable.pending ?? '[]'))
|
|
686
|
+
if (Array.isArray(entry) &&
|
|
687
|
+
typeof entry[0] === 'string' &&
|
|
688
|
+
typeof entry[1] === 'number' &&
|
|
689
|
+
typeof entry[2] === 'number')
|
|
690
|
+
pending.set(key(entry[0]), {
|
|
691
|
+
id: entry[0],
|
|
692
|
+
firstMet: Math.min(entry[1], now),
|
|
693
|
+
attempts: entry[2],
|
|
694
|
+
updated: typeof entry[3] === 'number' && entry[3] <= now ? entry[3] : NaN,
|
|
695
|
+
});
|
|
696
|
+
for (const id of JSON.parse(unreadable.skipped ?? '[]'))
|
|
697
|
+
if (typeof id === 'string')
|
|
698
|
+
skipped.set(key(id), id);
|
|
699
|
+
}
|
|
700
|
+
catch {
|
|
701
|
+
// An unreadable list only means those records are found again when GitHub next updates them.
|
|
702
|
+
}
|
|
703
|
+
/** Records met in this run that could not be read: the identifier as GitHub wrote it, and when it was updated. */
|
|
704
|
+
const unreadableNow = new Map();
|
|
705
|
+
/**
|
|
706
|
+
* Records that could not be read and give no identifier at all, and whether one was updated within
|
|
707
|
+
* the last day. Such a record cannot be asked for by name: the packages it names are remembered, and
|
|
708
|
+
* stored records for them are not confirmed as current until each is read again.
|
|
709
|
+
*/
|
|
710
|
+
let unidentified = 0;
|
|
711
|
+
let unidentifiedRecent = false;
|
|
712
|
+
/**
|
|
713
|
+
* The earliest update among such rows updated within the last day: the listing is read again from
|
|
714
|
+
* it, so a row that regains its identifier is read. Each row holds for at most a day after its own
|
|
715
|
+
* update, and never once a run reaches the page limit.
|
|
716
|
+
*/
|
|
717
|
+
let unidentifiedHold = Infinity;
|
|
718
|
+
/**
|
|
719
|
+
* By package: when a row without an identifier naming it was first seen (`at`), the exact update
|
|
720
|
+
* times of such rows seen (`versions`, the latest ROW_VERSIONS) and the latest of them (`updated`;
|
|
721
|
+
* Infinity when a row had none). Saved as `at` (no times) or `[at, ...versions]`.
|
|
722
|
+
*/
|
|
723
|
+
const blocked = new Map();
|
|
724
|
+
/** Packages named by such rows in this run: kept while their rows are still listed. */
|
|
725
|
+
const seenNow = new Set();
|
|
726
|
+
/** The update times of such rows listed in this run, by package: never trimmed away. */
|
|
727
|
+
const listedNow = new Map();
|
|
728
|
+
try {
|
|
729
|
+
const saved = JSON.parse(unreadable.unconfirmed || '{}');
|
|
730
|
+
if (typeof saved === 'object' && saved !== null && !Array.isArray(saved))
|
|
731
|
+
for (const [name, value] of Object.entries(saved)) {
|
|
732
|
+
// `at` alone (a row without an update time), or `[at, ...the updates of its rows]`.
|
|
733
|
+
const [at, ...rest] = Array.isArray(value) ? value : [value];
|
|
734
|
+
const versions = rest.filter((v) => typeof v === 'number' && Number.isFinite(v));
|
|
735
|
+
if (typeof at === 'number' && Number.isFinite(at))
|
|
736
|
+
blocked.set(name, {
|
|
737
|
+
at: Math.min(at, now),
|
|
738
|
+
updated: versions.length && versions.length === rest.length ? Math.max(...versions) : Infinity,
|
|
739
|
+
versions,
|
|
740
|
+
});
|
|
741
|
+
}
|
|
742
|
+
}
|
|
743
|
+
catch {
|
|
744
|
+
// An unreadable list only means those records are confirmed as before.
|
|
745
|
+
}
|
|
746
|
+
/**
|
|
747
|
+
* The update times kept for a package: every one listed in this run, then the latest others, up to
|
|
748
|
+
* ROW_VERSIONS (more when more were listed), without repeats. A time listed now is never evicted,
|
|
749
|
+
* or its row would look new on every run.
|
|
750
|
+
*/
|
|
751
|
+
const trimVersions = (name, all) => {
|
|
752
|
+
const unique = [...new Set(all)];
|
|
753
|
+
const listed = listedNow.get(name) ?? new Set();
|
|
754
|
+
const others = unique.filter((v) => !listed.has(v));
|
|
755
|
+
const room = Math.max(0, ROW_VERSIONS - unique.filter((v) => listed.has(v)).length);
|
|
756
|
+
// slice(-0) would keep them all.
|
|
757
|
+
const keep = new Set([...unique.filter((v) => listed.has(v)), ...(room ? others.slice(-room) : [])]);
|
|
758
|
+
return unique.filter((v) => keep.has(v));
|
|
759
|
+
};
|
|
760
|
+
/**
|
|
761
|
+
* Whether a stored record may have been replaced by such a row: read before the row was first
|
|
762
|
+
* seen, and not already at the row's version (its own update is earlier than the row's).
|
|
763
|
+
*/
|
|
764
|
+
const waits = (item, only) => [...(only ? [only] : ['*', ...item.packages.map((claim) => claim.name.toLowerCase())])].some((name) => {
|
|
765
|
+
const entry = blocked.get(name);
|
|
766
|
+
if (!entry)
|
|
767
|
+
return false;
|
|
768
|
+
if (only && only !== '*' && !item.packages.some((claim) => claim.name.toLowerCase() === only))
|
|
769
|
+
return false;
|
|
770
|
+
return Date.parse(item.fetched_at) < entry.at && !(Date.parse(item.modified_at) >= entry.updated);
|
|
771
|
+
});
|
|
772
|
+
const names = new Set(inventory.systems.flatMap((system) => system.components.map((component) => component.name.toLowerCase())));
|
|
773
|
+
/** Rows of the listing, readable or not, and the latest update time among them. */
|
|
774
|
+
let rows = 0;
|
|
775
|
+
let readableRows = 0;
|
|
776
|
+
let reachedRow = -Infinity;
|
|
777
|
+
/**
|
|
778
|
+
* A format outage: the listing had rows and none of them could be read, and some were first met
|
|
779
|
+
* within the last day. A window that has held only records that cannot be read for longer than
|
|
780
|
+
* that holds bad records, not an outage, so the checkpoint may move again.
|
|
781
|
+
*/
|
|
782
|
+
const outage = () => rows > 0 &&
|
|
783
|
+
readableRows === 0 &&
|
|
784
|
+
(unidentifiedRecent ||
|
|
785
|
+
[...unreadableNow.keys()].some((k) => {
|
|
786
|
+
const entry = pending.get(k);
|
|
787
|
+
return !entry || now - entry.firstMet <= UNREADABLE_HOLD_HOURS * HOUR;
|
|
788
|
+
}));
|
|
789
|
+
const updatedAt = (item) => {
|
|
790
|
+
const updated = typeof item === 'object' && item !== null
|
|
791
|
+
? Date.parse(String(item.updated_at))
|
|
792
|
+
: NaN;
|
|
793
|
+
return Number.isFinite(updated) && updated <= now ? updated : NaN;
|
|
794
|
+
};
|
|
795
|
+
const ghsaId = githubIdentifier;
|
|
796
|
+
const read = (item) => {
|
|
797
|
+
const parsed = invalid.read(() => githubRecord(item, type, now));
|
|
798
|
+
const id = ghsaId(item);
|
|
799
|
+
if (parsed) {
|
|
800
|
+
retainNewest(evidence, parsed);
|
|
801
|
+
// Read now: what earlier runs could not read is settled. Another revision of it in this run
|
|
802
|
+
// that cannot be read is still reported.
|
|
803
|
+
if (id) {
|
|
804
|
+
pending.delete(key(id));
|
|
805
|
+
skipped.delete(key(id));
|
|
806
|
+
}
|
|
807
|
+
}
|
|
808
|
+
else if (id)
|
|
809
|
+
unreadableNow.set(key(id), { id, updated: updatedAt(item) });
|
|
810
|
+
else {
|
|
811
|
+
unidentified++;
|
|
812
|
+
// Without a usable update time it has no day of its own: it makes a listing that can read
|
|
813
|
+
// nothing a format outage, but beside readable rows it does not hold the listing.
|
|
814
|
+
const updated = updatedAt(item);
|
|
815
|
+
if (!Number.isFinite(updated))
|
|
816
|
+
unidentifiedRecent = true;
|
|
817
|
+
else if (now - updated <= UNREADABLE_HOLD_HOURS * HOUR) {
|
|
818
|
+
unidentifiedRecent = true;
|
|
819
|
+
unidentifiedHold = Math.min(unidentifiedHold, updated);
|
|
820
|
+
}
|
|
821
|
+
// Held back from when the row is first seen, not from its update: GitHub may list a row late,
|
|
822
|
+
// after a stored record was confirmed. A row seen before (its exact update time is among those
|
|
823
|
+
// remembered for the package) keeps that time, so listing it again does not make records read
|
|
824
|
+
// since wait again.
|
|
825
|
+
const named = githubPackageNames(item);
|
|
826
|
+
const version = Number.isFinite(updated) ? updated : Infinity;
|
|
827
|
+
if (Number.isFinite(version))
|
|
828
|
+
for (const name of named.length ? named : ['*'])
|
|
829
|
+
listedNow.set(name, (listedNow.get(name) ?? new Set()).add(version));
|
|
830
|
+
for (const name of named.length ? named : ['*']) {
|
|
831
|
+
seenNow.add(name);
|
|
832
|
+
const entry = blocked.get(name);
|
|
833
|
+
// Seen before only if a row with exactly this update was seen for the package.
|
|
834
|
+
const seen = entry?.versions.includes(version) ?? false;
|
|
835
|
+
blocked.set(name, {
|
|
836
|
+
at: entry && seen ? entry.at : now,
|
|
837
|
+
updated: Math.max(entry?.updated ?? -Infinity, version),
|
|
838
|
+
// Trimmed only when saved, once every row of the run is known.
|
|
839
|
+
versions: Number.isFinite(version) && !seen
|
|
840
|
+
? [...(entry?.versions ?? []), version]
|
|
841
|
+
: (entry?.versions ?? []),
|
|
842
|
+
});
|
|
843
|
+
}
|
|
844
|
+
}
|
|
845
|
+
return parsed;
|
|
846
|
+
};
|
|
847
|
+
/** Records given up on in this run. */
|
|
848
|
+
let passed = 0;
|
|
849
|
+
/** Records asked for by identifier and read in this run. */
|
|
850
|
+
let recovered = 0;
|
|
851
|
+
/** By-identifier requests refused for this client (rate limit), and requests that failed. */
|
|
852
|
+
let refused = false;
|
|
853
|
+
let requestsFailed = 0;
|
|
854
|
+
/**
|
|
855
|
+
* Settles the remembered records for the next run, and says where the next run must start when
|
|
856
|
+
* the listing has to be read again: during a format outage, for remembered records beyond the cap,
|
|
857
|
+
* and once records can be read again while some are still remembered.
|
|
858
|
+
*/
|
|
859
|
+
const settle = (readSomething, holdUnidentified = true) => {
|
|
860
|
+
const nextPending = new Map(pending);
|
|
861
|
+
for (const [k, { id, updated }] of unreadableNow) {
|
|
862
|
+
const before = pending.get(k) ?? { id, firstMet: now, attempts: 0, updated };
|
|
863
|
+
// A run whose listing could read nothing is a format outage, not a bad record.
|
|
864
|
+
const attempts = before.attempts + (readSomething ? 1 : 0);
|
|
865
|
+
if (attempts >= OWED_GITHUB_ATTEMPTS && now - before.firstMet > UNREADABLE_HOLD_HOURS * HOUR) {
|
|
866
|
+
nextPending.delete(k);
|
|
867
|
+
skipped.set(k, before.id);
|
|
868
|
+
passed++;
|
|
869
|
+
}
|
|
870
|
+
else {
|
|
871
|
+
// Listed again: it is remembered, so it no longer waits for a turn among those given up on.
|
|
872
|
+
skipped.delete(k);
|
|
873
|
+
nextPending.set(k, {
|
|
874
|
+
id: before.id,
|
|
875
|
+
firstMet: before.firstMet,
|
|
876
|
+
attempts,
|
|
877
|
+
updated: Number.isFinite(updated) ? updated : before.updated,
|
|
878
|
+
});
|
|
879
|
+
}
|
|
880
|
+
}
|
|
881
|
+
let rewind;
|
|
882
|
+
const earliest = (entries) => Math.min(...entries.map((entry) => entry.updated).filter(Number.isFinite));
|
|
883
|
+
// Bounded: the records first met longest ago are kept. The rest are not given up on: the
|
|
884
|
+
// listing is read again from the oldest of them.
|
|
885
|
+
const ordered = [...nextPending].sort((a, b) => a[1].firstMet - b[1].firstMet);
|
|
886
|
+
// Beyond the cap the records whose day has passed are given up on first, then the newest: the
|
|
887
|
+
// checkpoint must always be able to move.
|
|
888
|
+
const overdue = (entry) => now - entry.firstMet > UNREADABLE_HOLD_HOURS * HOUR;
|
|
889
|
+
const byPriority = [...ordered].sort((a, b) => Number(overdue(a[1])) - Number(overdue(b[1])) || a[1].firstMet - b[1].firstMet);
|
|
890
|
+
for (const [k, entry] of byPriority.slice(MAX_UNREADABLE)) {
|
|
891
|
+
skipped.set(k, entry.id);
|
|
892
|
+
passed++;
|
|
893
|
+
}
|
|
894
|
+
const keptKeys = new Set(byPriority.slice(0, MAX_UNREADABLE).map(([k]) => k));
|
|
895
|
+
const kept = ordered.filter(([k]) => keptKeys.has(k));
|
|
896
|
+
// Records read again by identifier: the format is back. What is still remembered is listed again.
|
|
897
|
+
if (recovered && kept.length)
|
|
898
|
+
rewind = Math.min(rewind ?? Infinity, earliest(kept.map(([, entry]) => entry)));
|
|
899
|
+
// Nothing in the listing could be read: the window is listed again on the next run.
|
|
900
|
+
if (!readSomething)
|
|
901
|
+
rewind = start;
|
|
902
|
+
// Without a token, a long window is not listed again for it: GitHub allows 60 requests an hour.
|
|
903
|
+
if (holdUnidentified && Number.isFinite(unidentifiedHold) && (token || rows <= HOLD_ROWS_WITHOUT_TOKEN))
|
|
904
|
+
rewind = Math.min(rewind ?? Infinity, unidentifiedHold);
|
|
905
|
+
// A package stays remembered while a stored record for it, read before its row was met, waits to
|
|
906
|
+
// be read again.
|
|
907
|
+
const waitingFor = (name) => stored.some((item) => item.source === `github:${type}` &&
|
|
908
|
+
!evidence.has(item.id) &&
|
|
909
|
+
item.packages.some((claim) => names.has(claim.name.toLowerCase())) &&
|
|
910
|
+
waits(item, name));
|
|
911
|
+
unreadable.nextUnconfirmed = JSON.stringify(Object.fromEntries([...blocked]
|
|
912
|
+
.filter(([name]) => seenNow.has(name) || waitingFor(name))
|
|
913
|
+
.sort((a, b) => b[1].at - a[1].at)
|
|
914
|
+
.slice(0, MAX_UNREADABLE)
|
|
915
|
+
.map(([name, { at, updated, versions }]) => [
|
|
916
|
+
name,
|
|
917
|
+
Number.isFinite(updated) ? [at, ...trimVersions(name, versions)] : at,
|
|
918
|
+
])));
|
|
919
|
+
unreadable.nextPending = JSON.stringify(kept.map(([, { id, firstMet, attempts, updated }]) => [
|
|
920
|
+
id,
|
|
921
|
+
firstMet,
|
|
922
|
+
attempts,
|
|
923
|
+
...(Number.isFinite(updated) ? [updated] : []),
|
|
924
|
+
]));
|
|
925
|
+
// A record given up on that still has a stored copy is never forgotten, or that copy would be
|
|
926
|
+
// confirmed again. Beyond the cap, the oldest without one are dropped; the order, which is the
|
|
927
|
+
// order of turns for asking again, is kept.
|
|
928
|
+
const list = [...skipped];
|
|
929
|
+
let excess = list.filter(([k]) => !withCopy.has(k)).length - MAX_UNREADABLE;
|
|
930
|
+
const keep = list.filter(([k]) => withCopy.has(k) || excess-- <= 0);
|
|
931
|
+
unreadable.nextSkipped = JSON.stringify(keep.map(([, id]) => id));
|
|
932
|
+
return rewind !== undefined && Number.isFinite(rewind) ? rewind : undefined;
|
|
933
|
+
};
|
|
934
|
+
const problems = (rewind) => {
|
|
935
|
+
const parts = [];
|
|
936
|
+
if (unreadableNow.size)
|
|
937
|
+
parts.push(`GitHub: ${unreadableNow.size} record(s) could not be read; each is asked for again by identifier on later runs.`);
|
|
938
|
+
if (passed)
|
|
939
|
+
parts.push(`GitHub: ${passed} record(s) could not be read three times over a day and were given up on; their stored copies are no longer confirmed as current.`);
|
|
940
|
+
if (unidentified)
|
|
941
|
+
parts.push(`GitHub: ${unidentified} record(s) could not be read and give no identifier; stored records for the packages they name are not confirmed as current until each is read again${Number.isFinite(unidentifiedHold) ? ', and the listing is read again from the earliest updated within the last day' : ''}.`);
|
|
942
|
+
if (refused)
|
|
943
|
+
parts.push('GitHub refused requests for single records (rate limit); they are asked for again later.');
|
|
944
|
+
if (requestsFailed)
|
|
945
|
+
parts.push(`GitHub: ${requestsFailed} request(s) for single records failed; they are asked for again later.`);
|
|
946
|
+
if (rewind !== undefined)
|
|
947
|
+
parts.push('The next run lists the records since the oldest that could not be read again.');
|
|
948
|
+
return parts.join(' ');
|
|
949
|
+
};
|
|
950
|
+
try {
|
|
951
|
+
for (let page = 0; next; page++) {
|
|
952
|
+
if (page >= MAX_PAGES) {
|
|
953
|
+
// Records arrive oldest update first, so everything up to the last one read is complete.
|
|
954
|
+
// The next start is the checkpoint minus an hour: continue exactly from that record. Rows
|
|
955
|
+
// that could not be read count as progress: they are remembered by identifier.
|
|
956
|
+
if (rows < MAX_PAGES * 90 || !Number.isFinite(reachedRow) || reachedRow <= start)
|
|
957
|
+
throw new SourceError('GitHub pagination limit reached; collection is incomplete.');
|
|
958
|
+
const rewind = settle(!outage(), false);
|
|
959
|
+
const note = problems(rewind);
|
|
960
|
+
throw new PartialSourceError(`GitHub returned more updated advisories than one run reads; the oldest were collected and the next run continues from there.${note ? ` ${note}` : ''}`, [...evidence.values()], timestamp(Math.min(now, (rewind ?? reachedRow) + HOUR)));
|
|
961
|
+
}
|
|
962
|
+
if (seen.has(next))
|
|
963
|
+
throw new SourceError('GitHub returned repeated pagination.');
|
|
964
|
+
seen.add(next);
|
|
965
|
+
const response = await http(next, { headers, maxBytes: 8_000_000, redirects: 0 });
|
|
966
|
+
if (response.status !== 200)
|
|
967
|
+
throw new SourceError(`Source returned HTTP ${response.status}.`);
|
|
968
|
+
let data;
|
|
969
|
+
try {
|
|
970
|
+
data = JSON.parse(response.body);
|
|
971
|
+
}
|
|
972
|
+
catch {
|
|
973
|
+
throw new SourceError('Source returned invalid JSON.');
|
|
974
|
+
}
|
|
975
|
+
const items = array(data);
|
|
976
|
+
if (items.length > 100)
|
|
977
|
+
throw new SourceError('GitHub returned more records than the requested page limit.');
|
|
978
|
+
for (const item of items) {
|
|
979
|
+
rows++;
|
|
980
|
+
const updated = updatedAt(item);
|
|
981
|
+
if (Number.isFinite(updated))
|
|
982
|
+
reachedRow = Math.max(reachedRow, updated);
|
|
983
|
+
if (read(item))
|
|
984
|
+
readableRows++;
|
|
985
|
+
}
|
|
986
|
+
const link = Object.entries(response.headers).find(([key]) => key.toLowerCase() === 'link')?.[1];
|
|
987
|
+
next = nextGithubLink(link);
|
|
988
|
+
}
|
|
989
|
+
// Remembered records that this window did not list are asked for by identifier, the longest
|
|
990
|
+
// waiting first, a few per run: two without a token, whose requests GitHub limits to 60 an hour.
|
|
991
|
+
const asked = [...pending.values()]
|
|
992
|
+
.filter((entry) => !unreadableNow.has(key(entry.id)) && !evidence.has(`github:${entry.id}`))
|
|
993
|
+
.sort((a, b) => a.firstMet - b.firstMet)
|
|
994
|
+
.slice(0, token ? REFETCH_PER_RUN : REFETCH_WITHOUT_TOKEN);
|
|
995
|
+
// With room left, up to two records given up on are asked for again per run, so a record lost
|
|
996
|
+
// to a long partial format change is found again once GitHub serves it readably.
|
|
997
|
+
const budget = token ? REFETCH_PER_RUN : REFETCH_WITHOUT_TOKEN;
|
|
998
|
+
// Records given up on are asked for in turn. With two requests to spare, one goes to the next
|
|
999
|
+
// record with a stored copy (its copy is never confirmed until it is read) and one to the next
|
|
1000
|
+
// record in turn, so neither kind can take every turn; with one, they simply take turns.
|
|
1001
|
+
const room = budget - asked.length;
|
|
1002
|
+
// Stored records for the inventory that a row without an identifier may have replaced, the
|
|
1003
|
+
// longest unread first: read again by identifier, so that they can be confirmed again. One that
|
|
1004
|
+
// cannot be read is remembered like any other. They keep one request of the room left.
|
|
1005
|
+
const stale = stored
|
|
1006
|
+
.filter((item) => {
|
|
1007
|
+
const k = key(item.id.slice(7));
|
|
1008
|
+
return (item.source === `github:${type}` &&
|
|
1009
|
+
!evidence.has(item.id) &&
|
|
1010
|
+
!unreadableNow.has(k) &&
|
|
1011
|
+
!pending.has(k) &&
|
|
1012
|
+
!skipped.has(k) &&
|
|
1013
|
+
waits(item) &&
|
|
1014
|
+
item.packages.some((claim) => names.has(claim.name.toLowerCase())));
|
|
1015
|
+
})
|
|
1016
|
+
.sort((a, b) => Date.parse(a.fetched_at) - Date.parse(b.fetched_at));
|
|
1017
|
+
const turns = room - (stale.length && room >= 1 ? 1 : 0);
|
|
1018
|
+
const waiting = [...skipped].filter(([k]) => !unreadableNow.has(k) && !pending.has(k));
|
|
1019
|
+
const picks = [];
|
|
1020
|
+
const copyFirst = turns >= 2 ? waiting.find(([k]) => withCopy.has(k)) : undefined;
|
|
1021
|
+
if (copyFirst)
|
|
1022
|
+
picks.push(copyFirst);
|
|
1023
|
+
for (const entry of waiting) {
|
|
1024
|
+
if (picks.length >= Math.min(turns, 2))
|
|
1025
|
+
break;
|
|
1026
|
+
if (!picks.includes(entry))
|
|
1027
|
+
picks.push(entry);
|
|
1028
|
+
}
|
|
1029
|
+
const again = picks.map(([, id]) => ({ id, firstMet: now, attempts: 0, updated: NaN }));
|
|
1030
|
+
// To the back of the queue, so the next run asks others.
|
|
1031
|
+
for (const [k, id] of picks) {
|
|
1032
|
+
skipped.delete(k);
|
|
1033
|
+
skipped.set(k, id);
|
|
1034
|
+
}
|
|
1035
|
+
const refresh = stale
|
|
1036
|
+
.slice(0, Math.max(0, room - picks.length))
|
|
1037
|
+
.map((item) => ({ id: item.id.slice(7), firstMet: now, attempts: 0, updated: NaN }));
|
|
1038
|
+
for (const entry of [...asked, ...again, ...refresh]) {
|
|
1039
|
+
const givenUp = again.includes(entry);
|
|
1040
|
+
try {
|
|
1041
|
+
const response = await http(`${GITHUB}/${encodeURIComponent(entry.id)}`, {
|
|
1042
|
+
headers,
|
|
1043
|
+
maxBytes: 1_000_000,
|
|
1044
|
+
redirects: 0,
|
|
1045
|
+
});
|
|
1046
|
+
// GitHub answers that it has no such record, or serves it in a form that cannot be read: a
|
|
1047
|
+
// failed read. A refusal for this client ends the requests; any other failure says nothing
|
|
1048
|
+
// about the record.
|
|
1049
|
+
// A record given up on that still cannot be read stays given up on, without a new report.
|
|
1050
|
+
if (response.status === 404) {
|
|
1051
|
+
if (!givenUp)
|
|
1052
|
+
unreadableNow.set(key(entry.id), { id: entry.id, updated: NaN });
|
|
1053
|
+
}
|
|
1054
|
+
else if (response.status === 403 || response.status === 429) {
|
|
1055
|
+
refused = true;
|
|
1056
|
+
break;
|
|
1057
|
+
}
|
|
1058
|
+
else if (response.status !== 200)
|
|
1059
|
+
throw new SourceError(`Source returned HTTP ${response.status}.`);
|
|
1060
|
+
else {
|
|
1061
|
+
const body = JSON.parse(response.body);
|
|
1062
|
+
// An answer without an identifier is a failed read of the record asked for, not a row of
|
|
1063
|
+
// the listing without one.
|
|
1064
|
+
if (ghsaId(body) && read(body)) {
|
|
1065
|
+
if (!refresh.includes(entry))
|
|
1066
|
+
recovered++;
|
|
1067
|
+
}
|
|
1068
|
+
else if (givenUp)
|
|
1069
|
+
unreadableNow.delete(key(entry.id));
|
|
1070
|
+
else
|
|
1071
|
+
unreadableNow.set(key(entry.id), { id: entry.id, updated: NaN });
|
|
1072
|
+
}
|
|
1073
|
+
}
|
|
1074
|
+
catch (error) {
|
|
1075
|
+
if (sourceCanceled(error))
|
|
1076
|
+
throw error;
|
|
1077
|
+
// A failed request says nothing about the record: it is reported and asked for again.
|
|
1078
|
+
requestsFailed++;
|
|
1079
|
+
}
|
|
1080
|
+
}
|
|
1081
|
+
const rewind = settle(!outage());
|
|
1082
|
+
// Every record modified since the window's start has been read. A stored record fetched after
|
|
1083
|
+
// that start and not among them is unchanged, so it is confirmed as current: without this an
|
|
1084
|
+
// exclusion drawn from it would turn into an "unknown" two poll intervals after it was first
|
|
1085
|
+
// read, while GitHub answers normally. Only records for the inventory's packages matter, and
|
|
1086
|
+
// never one whose newer version could not be read.
|
|
1087
|
+
const unconfirmed = new Set([...unreadableNow.keys(), ...pending.keys(), ...skipped.keys()]);
|
|
1088
|
+
// A record that could not be read and has no identifier may be the new version of a stored one
|
|
1089
|
+
// for a package it names.
|
|
1090
|
+
for (const item of stored)
|
|
1091
|
+
if (item.source === `github:${type}` &&
|
|
1092
|
+
!evidence.has(item.id) &&
|
|
1093
|
+
!unconfirmed.has(key(item.id.slice(7))) &&
|
|
1094
|
+
Date.parse(item.fetched_at) >= chainStart &&
|
|
1095
|
+
!waits(item) &&
|
|
1096
|
+
Date.parse(item.fetched_at) <= now &&
|
|
1097
|
+
item.packages.some((claim) => names.has(claim.name.toLowerCase())))
|
|
1098
|
+
evidence.set(item.id, { ...item, fetched_at: timestamp(now) });
|
|
1099
|
+
const note = problems(rewind);
|
|
1100
|
+
// The checkpoint moves on, unless the listing must be read again from an earlier point.
|
|
1101
|
+
if (note)
|
|
1102
|
+
throw new PartialSourceError(note, [...evidence.values()], timestamp(rewind === undefined ? now : Math.min(now, rewind + HOUR)));
|
|
1103
|
+
return [...evidence.values()];
|
|
1104
|
+
}
|
|
1105
|
+
catch (error) {
|
|
1106
|
+
throwSourceFailure(error, [...evidence.values()]);
|
|
1107
|
+
}
|
|
1108
|
+
}
|
|
1109
|
+
async function kev(http, now, previous) {
|
|
1110
|
+
const data = record(await json(http, KEV));
|
|
1111
|
+
const entries = array(data.vulnerabilities);
|
|
1112
|
+
if (!Number.isSafeInteger(data.count) || data.count !== entries.length || entries.length > 20_000)
|
|
1113
|
+
throw new SourceError('Invalid or incomplete CISA KEV catalog.');
|
|
1114
|
+
const released = date(data.dateReleased);
|
|
1115
|
+
if (Date.parse(released) > now + 5 * 60_000)
|
|
1116
|
+
throw new SourceError('Source returned a future modification timestamp; collection is incomplete.');
|
|
1117
|
+
const old = new Map();
|
|
1118
|
+
for (const item of previous)
|
|
1119
|
+
if (item.source === 'kev')
|
|
1120
|
+
retainNewest(old, item);
|
|
1121
|
+
const invalid = new SourceItemFailures();
|
|
1122
|
+
const results = [];
|
|
1123
|
+
for (const raw of entries) {
|
|
1124
|
+
const parsed = invalid.read(() => {
|
|
1125
|
+
const item = record(raw);
|
|
1126
|
+
const cve = string(item.cveID);
|
|
1127
|
+
if (!/^CVE-\d{4}-\d{4,}$/i.test(cve))
|
|
1128
|
+
throw new SourceError('Invalid CISA KEV identifier.');
|
|
1129
|
+
const vendor = string(item.vendorProject);
|
|
1130
|
+
const product = string(item.product);
|
|
1131
|
+
const description = `${vendor} ${product}\n${string(item.shortDescription)}\nRequired action: ${string(item.requiredAction)}`;
|
|
1132
|
+
const evidence = {
|
|
1133
|
+
id: `kev:${cve.toUpperCase()}`,
|
|
1134
|
+
source: 'kev',
|
|
1135
|
+
kind: 'kev',
|
|
1136
|
+
title: cleanText(string(item.vulnerabilityName), 500),
|
|
1137
|
+
url: `https://www.cisa.gov/known-exploited-vulnerabilities-catalog?search_api_fulltext=${encodeURIComponent(cve)}`,
|
|
1138
|
+
description: cleanText(description, 16_000),
|
|
1139
|
+
aliases: aliases([cve]),
|
|
1140
|
+
severity: 'unknown',
|
|
1141
|
+
modified_at: released,
|
|
1142
|
+
fetched_at: timestamp(now),
|
|
1143
|
+
published_at: date(item.dateAdded),
|
|
1144
|
+
packages: [],
|
|
1145
|
+
exploited: true,
|
|
1146
|
+
};
|
|
1147
|
+
// KEV has a catalog release time, not entry modification times. An unchanged
|
|
1148
|
+
// entry retains its content revision while fetched_at records this refresh.
|
|
1149
|
+
const existing = old.get(evidence.id);
|
|
1150
|
+
const content = (item) => hash([item.title, item.description, item.url, item.aliases, item.published_at, item.exploited]);
|
|
1151
|
+
if (existing && content(existing) === content(evidence))
|
|
1152
|
+
evidence.modified_at = existing.modified_at;
|
|
1153
|
+
return evidence;
|
|
1154
|
+
});
|
|
1155
|
+
if (parsed)
|
|
1156
|
+
results.push(parsed);
|
|
1157
|
+
}
|
|
1158
|
+
return invalid.finish('CISA KEV', results);
|
|
1159
|
+
}
|
|
1160
|
+
function xmlText(value) {
|
|
1161
|
+
if (typeof value === 'string' || typeof value === 'number')
|
|
1162
|
+
return String(value);
|
|
1163
|
+
if (!value || typeof value !== 'object')
|
|
1164
|
+
return '';
|
|
1165
|
+
if (Array.isArray(value))
|
|
1166
|
+
return value.map(xmlText).join(' ');
|
|
1167
|
+
return Object.entries(value)
|
|
1168
|
+
.filter(([key]) => !key.startsWith('@_') && !HIDDEN_HTML_ELEMENTS.has(key.toLowerCase()))
|
|
1169
|
+
.map(([, child]) => xmlText(child))
|
|
1170
|
+
.join(' ');
|
|
1171
|
+
}
|
|
1172
|
+
const HIDDEN_HTML_ELEMENTS = new Set(['script', 'style', 'template', 'noscript']);
|
|
1173
|
+
const MAX_HTML_BYTES = 2_000_000;
|
|
1174
|
+
const MAX_HTML_NODES = 100_000;
|
|
1175
|
+
const MAX_HTML_DEPTH = 256;
|
|
1176
|
+
function parseHtml(html, document = false) {
|
|
1177
|
+
if (Buffer.byteLength(html) > MAX_HTML_BYTES)
|
|
1178
|
+
throw new SourceError('HTML input exceeds the size limit.');
|
|
1179
|
+
let nodes = 0;
|
|
1180
|
+
let depth = 0;
|
|
1181
|
+
const account = () => {
|
|
1182
|
+
if (++nodes > MAX_HTML_NODES)
|
|
1183
|
+
throw new SourceError('HTML structure exceeds the node limit.');
|
|
1184
|
+
};
|
|
1185
|
+
const treeAdapter = {
|
|
1186
|
+
...defaultTreeAdapter,
|
|
1187
|
+
createDocument() {
|
|
1188
|
+
account();
|
|
1189
|
+
return defaultTreeAdapter.createDocument();
|
|
1190
|
+
},
|
|
1191
|
+
createDocumentFragment() {
|
|
1192
|
+
account();
|
|
1193
|
+
return defaultTreeAdapter.createDocumentFragment();
|
|
1194
|
+
},
|
|
1195
|
+
createElement(...args) {
|
|
1196
|
+
account();
|
|
1197
|
+
return defaultTreeAdapter.createElement(...args);
|
|
1198
|
+
},
|
|
1199
|
+
createCommentNode(...args) {
|
|
1200
|
+
account();
|
|
1201
|
+
return defaultTreeAdapter.createCommentNode(...args);
|
|
1202
|
+
},
|
|
1203
|
+
insertText(parent, text) {
|
|
1204
|
+
if (parent.childNodes.at(-1)?.nodeName !== '#text')
|
|
1205
|
+
account();
|
|
1206
|
+
defaultTreeAdapter.insertText(parent, text);
|
|
1207
|
+
},
|
|
1208
|
+
insertTextBefore(parent, text, reference) {
|
|
1209
|
+
if (parent.childNodes[parent.childNodes.indexOf(reference) - 1]?.nodeName !== '#text')
|
|
1210
|
+
account();
|
|
1211
|
+
defaultTreeAdapter.insertTextBefore(parent, text, reference);
|
|
1212
|
+
},
|
|
1213
|
+
onItemPush() {
|
|
1214
|
+
if (++depth > MAX_HTML_DEPTH)
|
|
1215
|
+
throw new SourceError('HTML structure exceeds the depth limit.');
|
|
1216
|
+
},
|
|
1217
|
+
onItemPop() {
|
|
1218
|
+
depth--;
|
|
1219
|
+
},
|
|
1220
|
+
};
|
|
1221
|
+
// parse5 builds an inert tree: it does not execute scripts or fetch resources.
|
|
1222
|
+
return document
|
|
1223
|
+
? parse(html, { sourceCodeLocationInfo: true, scriptingEnabled: true, treeAdapter })
|
|
1224
|
+
: parseFragment(html, { scriptingEnabled: true, treeAdapter });
|
|
1225
|
+
}
|
|
1226
|
+
function* visibleHtmlNodes(root) {
|
|
1227
|
+
const pending = [{ node: root, depth: 0 }];
|
|
1228
|
+
let visited = 0;
|
|
1229
|
+
while (pending.length) {
|
|
1230
|
+
const { node, depth } = pending.pop();
|
|
1231
|
+
if (++visited > MAX_HTML_NODES || depth > MAX_HTML_DEPTH)
|
|
1232
|
+
throw new SourceError('HTML structure exceeds the traversal limit.');
|
|
1233
|
+
if (node.nodeName === '#comment' ||
|
|
1234
|
+
('tagName' in node && HIDDEN_HTML_ELEMENTS.has(node.tagName.toLowerCase())))
|
|
1235
|
+
continue;
|
|
1236
|
+
yield node;
|
|
1237
|
+
if ('childNodes' in node) {
|
|
1238
|
+
if (visited + pending.length + node.childNodes.length > MAX_HTML_NODES)
|
|
1239
|
+
throw new SourceError('HTML structure exceeds the traversal limit.');
|
|
1240
|
+
for (let index = node.childNodes.length - 1; index >= 0; index--)
|
|
1241
|
+
pending.push({ node: node.childNodes[index], depth: depth + 1 });
|
|
1242
|
+
}
|
|
1243
|
+
}
|
|
1244
|
+
}
|
|
1245
|
+
function htmlText(root, limit = 16_000) {
|
|
1246
|
+
const parts = [];
|
|
1247
|
+
for (const node of visibleHtmlNodes(root))
|
|
1248
|
+
if ('value' in node)
|
|
1249
|
+
parts.push(node.value);
|
|
1250
|
+
// Entity references have already been decoded once by the HTML parser.
|
|
1251
|
+
return cleanText(parts.join(' ').replace(/\s+/g, ' ').trim(), limit);
|
|
1252
|
+
}
|
|
1253
|
+
function plainText(value, limit = 16_000) {
|
|
1254
|
+
return htmlText(parseHtml(xmlText(value)), limit);
|
|
1255
|
+
}
|
|
1256
|
+
function list(value) {
|
|
1257
|
+
return value === undefined ? [] : Array.isArray(value) ? value : [value];
|
|
1258
|
+
}
|
|
1259
|
+
function feedDate(value) {
|
|
1260
|
+
const input = xmlText(value);
|
|
1261
|
+
return input && Number.isFinite(Date.parse(input)) ? timestamp(Date.parse(input)) : undefined;
|
|
1262
|
+
}
|
|
1263
|
+
function listedEntries(value) {
|
|
1264
|
+
if (value === undefined)
|
|
1265
|
+
return undefined;
|
|
1266
|
+
try {
|
|
1267
|
+
const ids = JSON.parse(value);
|
|
1268
|
+
if (Array.isArray(ids) && ids.every((id) => typeof id === 'string'))
|
|
1269
|
+
return new Set(ids);
|
|
1270
|
+
}
|
|
1271
|
+
catch {
|
|
1272
|
+
/* An unreadable memory behaves like a first run. */
|
|
1273
|
+
}
|
|
1274
|
+
return undefined;
|
|
1275
|
+
}
|
|
1276
|
+
function newsWindow(source, checkpoint, listed, lookbackMinutes, previous, inventory, now) {
|
|
1277
|
+
const lookback = lookbackMinutes * 60_000;
|
|
1278
|
+
const last = checkpoint === undefined ? now : Date.parse(checkpoint);
|
|
1279
|
+
if (!Number.isFinite(last) || last > now)
|
|
1280
|
+
throw new SourceError('Invalid news checkpoint; reset it before collecting.');
|
|
1281
|
+
return {
|
|
1282
|
+
// Revisit a small checkpoint overlap after an outage, even when the normal window is shorter.
|
|
1283
|
+
cutoff: Math.max(0, Math.min(now - lookback, last - Math.min(5 * 60_000, lookback))),
|
|
1284
|
+
...(checkpoint === undefined ? {} : { listed: listedEntries(listed) }),
|
|
1285
|
+
lateCutoff: Math.max(0, last - LATE_ENTRY_DAYS * 24 * HOUR),
|
|
1286
|
+
tracked: new Set(previous
|
|
1287
|
+
.filter((item) => item.source === source && item.kind === 'news' && evidenceRelevant(item, inventory))
|
|
1288
|
+
.map((item) => item.id)),
|
|
1289
|
+
previous: new Map(previous.filter((item) => item.source === source).map((item) => [item.id, item])),
|
|
1290
|
+
};
|
|
1291
|
+
}
|
|
1292
|
+
function stabilizeUndated(result, previous) {
|
|
1293
|
+
const content = (item) => hash([
|
|
1294
|
+
item.title,
|
|
1295
|
+
item.url,
|
|
1296
|
+
item.description,
|
|
1297
|
+
item.aliases,
|
|
1298
|
+
item.severity,
|
|
1299
|
+
item.published_at,
|
|
1300
|
+
item.content_status,
|
|
1301
|
+
]);
|
|
1302
|
+
for (const item of result.evidence) {
|
|
1303
|
+
const old = previous.get(item.id);
|
|
1304
|
+
if (result.undated.has(item.id) && old && content(old) === content(item))
|
|
1305
|
+
item.modified_at = old.modified_at;
|
|
1306
|
+
}
|
|
1307
|
+
}
|
|
1308
|
+
async function feed(url, source, http, now, window, entryLimit = MAX_FEED_ENTRIES) {
|
|
1309
|
+
const response = await http(url, { maxBytes: 2_000_000 });
|
|
1310
|
+
if (response.status !== 200)
|
|
1311
|
+
throw new SourceError(`Source returned HTTP ${response.status}.`);
|
|
1312
|
+
if (/<!\s*(?:DOCTYPE|ENTITY)\b/i.test(response.body))
|
|
1313
|
+
throw new SourceError('Feed DTDs and entity declarations are not allowed.');
|
|
1314
|
+
if (XMLValidator.validate(response.body) !== true)
|
|
1315
|
+
throw new SourceError('Feed returned invalid XML.');
|
|
1316
|
+
let parsed;
|
|
1317
|
+
try {
|
|
1318
|
+
parsed = record(new XMLParser({
|
|
1319
|
+
ignoreAttributes: false,
|
|
1320
|
+
processEntities: false,
|
|
1321
|
+
parseTagValue: false,
|
|
1322
|
+
parseAttributeValue: false,
|
|
1323
|
+
removeNSPrefix: true,
|
|
1324
|
+
}).parse(response.body));
|
|
1325
|
+
}
|
|
1326
|
+
catch {
|
|
1327
|
+
throw new SourceError('Feed returned invalid XML.');
|
|
1328
|
+
}
|
|
1329
|
+
let entries;
|
|
1330
|
+
if (parsed.rss !== undefined)
|
|
1331
|
+
entries = list(record(record(parsed.rss).channel).item);
|
|
1332
|
+
else if (parsed.feed !== undefined)
|
|
1333
|
+
entries = list(record(parsed.feed).entry);
|
|
1334
|
+
else
|
|
1335
|
+
throw new SourceError('Unsupported feed format; RSS 2.0 or Atom is required.');
|
|
1336
|
+
if (entries.length > entryLimit)
|
|
1337
|
+
throw new SourceError('Feed entry limit reached; collection is incomplete.');
|
|
1338
|
+
const fallback = new URL(url);
|
|
1339
|
+
fallback.username = '';
|
|
1340
|
+
fallback.password = '';
|
|
1341
|
+
fallback.search = '';
|
|
1342
|
+
fallback.hash = '';
|
|
1343
|
+
const results = new Map();
|
|
1344
|
+
const undated = new Set();
|
|
1345
|
+
const listed = [];
|
|
1346
|
+
const invalid = new SourceItemFailures();
|
|
1347
|
+
for (const rawEntry of entries) {
|
|
1348
|
+
const parsed = invalid.read(() => {
|
|
1349
|
+
const entry = record(rawEntry);
|
|
1350
|
+
const title = plainText(entry.title, 500);
|
|
1351
|
+
if (!title)
|
|
1352
|
+
throw new SourceError('Feed entry is missing its title.');
|
|
1353
|
+
const description = plainText(entry.encoded ?? entry.content ?? entry.description ?? entry.summary ?? '');
|
|
1354
|
+
const links = list(entry.link);
|
|
1355
|
+
const selectedLink = links.find((link) => typeof link === 'string' || !record(link)['@_rel'] || record(link)['@_rel'] === 'alternate');
|
|
1356
|
+
const rawLink = typeof selectedLink === 'object' && selectedLink !== null
|
|
1357
|
+
? (record(selectedLink)['@_href'] ?? xmlText(selectedLink))
|
|
1358
|
+
: selectedLink;
|
|
1359
|
+
const link = publicUrl(rawLink, fallback.href);
|
|
1360
|
+
const externalId = xmlText(entry.id ?? entry.guid).trim() || (link !== fallback.href ? link : '');
|
|
1361
|
+
if (!externalId)
|
|
1362
|
+
throw new SourceError('Feed entry is missing a stable ID or link.');
|
|
1363
|
+
const published = feedDate(entry.published ?? entry.pubDate);
|
|
1364
|
+
const sourceModified = feedDate(entry.updated) ?? published;
|
|
1365
|
+
if ([sourceModified, published].some((value) => value && Date.parse(value) > now + 5 * 60_000))
|
|
1366
|
+
throw new SourceError('Feed returned a future timestamp; collection is incomplete.');
|
|
1367
|
+
const modified = sourceModified ?? timestamp(now);
|
|
1368
|
+
const id = `${source}:entry:${hash(externalId).slice(0, 32)}`;
|
|
1369
|
+
listed.push(id);
|
|
1370
|
+
if (sourceModified && Date.parse(sourceModified) < window.cutoff && !window.tracked.has(id)) {
|
|
1371
|
+
// A feed can list an entry after the time it is stamped with (publication lag, or a date
|
|
1372
|
+
// without a time). An entry that was not listed at the last poll is new to this monitor,
|
|
1373
|
+
// whatever its stamp says; one that was listed and left out stays out.
|
|
1374
|
+
const late = window.listed !== undefined &&
|
|
1375
|
+
!window.listed.has(id) &&
|
|
1376
|
+
!window.previous.has(id) &&
|
|
1377
|
+
Date.parse(sourceModified) >= window.lateCutoff;
|
|
1378
|
+
if (!late)
|
|
1379
|
+
return undefined;
|
|
1380
|
+
}
|
|
1381
|
+
const evidence = {
|
|
1382
|
+
id,
|
|
1383
|
+
source,
|
|
1384
|
+
kind: 'news',
|
|
1385
|
+
title,
|
|
1386
|
+
url: link,
|
|
1387
|
+
description,
|
|
1388
|
+
aliases: citedIdentifiers(`${title}\n${description}\n${link}`),
|
|
1389
|
+
severity: severity(xmlText(entry.severity)),
|
|
1390
|
+
modified_at: modified,
|
|
1391
|
+
fetched_at: timestamp(now),
|
|
1392
|
+
...(published ? { published_at: published } : {}),
|
|
1393
|
+
packages: [],
|
|
1394
|
+
content_status: description ? 'excerpt' : 'unavailable',
|
|
1395
|
+
};
|
|
1396
|
+
return { evidence, dated: Boolean(sourceModified) };
|
|
1397
|
+
});
|
|
1398
|
+
if (!parsed)
|
|
1399
|
+
continue;
|
|
1400
|
+
const { evidence, dated } = parsed;
|
|
1401
|
+
const id = evidence.id;
|
|
1402
|
+
const modified = evidence.modified_at;
|
|
1403
|
+
const old = results.get(id);
|
|
1404
|
+
if (!old || Date.parse(modified) >= Date.parse(old.modified_at)) {
|
|
1405
|
+
results.set(id, evidence);
|
|
1406
|
+
if (dated)
|
|
1407
|
+
undated.delete(id);
|
|
1408
|
+
else
|
|
1409
|
+
undated.add(id);
|
|
1410
|
+
}
|
|
1411
|
+
}
|
|
1412
|
+
return { evidence: [...results.values()], undated, listed, failure: invalid.message('Feed') };
|
|
1413
|
+
}
|
|
1414
|
+
function hackerNewsUrl(value) {
|
|
1415
|
+
try {
|
|
1416
|
+
const url = new URL(value);
|
|
1417
|
+
if (url.protocol !== 'https:' ||
|
|
1418
|
+
url.username ||
|
|
1419
|
+
url.password ||
|
|
1420
|
+
url.port ||
|
|
1421
|
+
!['thehackernews.com', 'www.thehackernews.com'].includes(url.hostname) ||
|
|
1422
|
+
!/^\/\d{4}\/\d{2}\/[^/]+\.html$/.test(url.pathname))
|
|
1423
|
+
return undefined;
|
|
1424
|
+
url.hash = '';
|
|
1425
|
+
url.search = '';
|
|
1426
|
+
return url.href;
|
|
1427
|
+
}
|
|
1428
|
+
catch {
|
|
1429
|
+
return undefined;
|
|
1430
|
+
}
|
|
1431
|
+
}
|
|
1432
|
+
/** Extract only the marked article body, never navigation/related-story text.
|
|
1433
|
+
* Missing or malformed wrappers leave the feed excerpt explicitly incomplete. */
|
|
1434
|
+
function articleBody(html) {
|
|
1435
|
+
for (const node of visibleHtmlNodes(parseHtml(html, true))) {
|
|
1436
|
+
if (!('tagName' in node) ||
|
|
1437
|
+
node.namespaceURI !== 'http://www.w3.org/1999/xhtml' ||
|
|
1438
|
+
!['div', 'article', 'section'].includes(node.tagName))
|
|
1439
|
+
continue;
|
|
1440
|
+
const attributes = new Map(node.attrs.map(({ name, value }) => [name, value]));
|
|
1441
|
+
if (!(attributes.get('itemprop') ?? '').split(/\s+/).includes('articleBody') &&
|
|
1442
|
+
!(attributes.get('class') ?? '')
|
|
1443
|
+
.split(/\s+/)
|
|
1444
|
+
.some((value) => ['articlebody', 'post-body'].includes(value)))
|
|
1445
|
+
continue;
|
|
1446
|
+
// Parser recovery can create or implicitly close nodes. Only an explicit
|
|
1447
|
+
// source wrapper establishes that the complete article body was received.
|
|
1448
|
+
return node.sourceCodeLocation?.startTag && node.sourceCodeLocation.endTag ? node : undefined;
|
|
1449
|
+
}
|
|
1450
|
+
return undefined;
|
|
1451
|
+
}
|
|
1452
|
+
async function hackerNews(http, now, window) {
|
|
1453
|
+
const result = await feed(HACKER_NEWS, 'hacker_news', http, now, window);
|
|
1454
|
+
const entries = result.evidence;
|
|
1455
|
+
// RSS is a finite current window. Articles outside the fetch budget remain
|
|
1456
|
+
// visible as excerpts; models cannot use them as complete dismissal evidence.
|
|
1457
|
+
for (let offset = 0; offset < Math.min(entries.length, 50); offset += 4)
|
|
1458
|
+
await Promise.all(entries.slice(offset, Math.min(offset + 4, 50)).map(async (entry) => {
|
|
1459
|
+
const url = hackerNewsUrl(entry.url);
|
|
1460
|
+
if (!url)
|
|
1461
|
+
return;
|
|
1462
|
+
try {
|
|
1463
|
+
const response = await http(url, {
|
|
1464
|
+
maxBytes: 2_000_000,
|
|
1465
|
+
redirects: 3,
|
|
1466
|
+
allowedRedirectOrigins: ['https://thehackernews.com', 'https://www.thehackernews.com'],
|
|
1467
|
+
});
|
|
1468
|
+
if (response.status !== 200)
|
|
1469
|
+
return;
|
|
1470
|
+
const body = articleBody(response.body);
|
|
1471
|
+
if (!body)
|
|
1472
|
+
return;
|
|
1473
|
+
const full = htmlText(body, 16_001);
|
|
1474
|
+
if (!full || full.length < entry.description.length)
|
|
1475
|
+
return;
|
|
1476
|
+
entry.description = full.slice(0, 16_000);
|
|
1477
|
+
entry.content_status = full.length <= 16_000 ? 'full' : 'excerpt';
|
|
1478
|
+
entry.url = url;
|
|
1479
|
+
entry.aliases = citedIdentifiers(`${entry.title}\n${entry.description}`);
|
|
1480
|
+
}
|
|
1481
|
+
catch (error) {
|
|
1482
|
+
if (sourceCanceled(error))
|
|
1483
|
+
throw error;
|
|
1484
|
+
// Fetch/parse failures must not erase the headline and feed excerpt.
|
|
1485
|
+
// No transport exception text is persisted or exposed to model prompts.
|
|
1486
|
+
}
|
|
1487
|
+
}));
|
|
1488
|
+
stabilizeUndated(result, window.previous);
|
|
1489
|
+
return result;
|
|
1490
|
+
}
|
|
1491
|
+
async function vendorFeed(vendor, http, now, window) {
|
|
1492
|
+
const profile = VENDOR_FEEDS[vendor];
|
|
1493
|
+
// PHP's feed includes years of release history.
|
|
1494
|
+
// Keep its larger item allowance separate from generic feeds and the shared 2 MB cap.
|
|
1495
|
+
const result = await feed(profile.feed, `vendor:${vendor}`, http, now, window, vendor === 'php' ? 2000 : MAX_FEED_ENTRIES);
|
|
1496
|
+
const entries = result.evidence.slice(0, 20);
|
|
1497
|
+
for (let offset = 0; offset < entries.length; offset += 4)
|
|
1498
|
+
await Promise.all(entries.slice(offset, offset + 4).map(async (entry) => {
|
|
1499
|
+
const target = vendorArticleTarget(vendor, entry.url);
|
|
1500
|
+
if (!target)
|
|
1501
|
+
return;
|
|
1502
|
+
try {
|
|
1503
|
+
const response = await http(target.url, {
|
|
1504
|
+
maxBytes: MAX_HTML_BYTES,
|
|
1505
|
+
timeoutMs: 15_000,
|
|
1506
|
+
minIntervalMs: 500,
|
|
1507
|
+
redirects: 3,
|
|
1508
|
+
allowedRedirectOrigins: [profile.origin],
|
|
1509
|
+
headers: { accept: 'text/html' },
|
|
1510
|
+
});
|
|
1511
|
+
if (response.status !== 200)
|
|
1512
|
+
return;
|
|
1513
|
+
const body = vendorArticleBody(vendor, visibleHtmlNodes(parseHtml(response.body, true)), target.anchor);
|
|
1514
|
+
if (!body)
|
|
1515
|
+
return;
|
|
1516
|
+
const text = htmlText(body, 16_001);
|
|
1517
|
+
const normalize = (value) => value.replace(/\s+/g, ' ').trim().toLowerCase();
|
|
1518
|
+
// A complete wrapper on an unrelated redirect/error page is not the requested article.
|
|
1519
|
+
const visible = normalize(text);
|
|
1520
|
+
const title = normalize(entry.title);
|
|
1521
|
+
if (!visible.includes(title) || visible.replaceAll(title, '').trim().length < 40)
|
|
1522
|
+
return;
|
|
1523
|
+
entry.description = text.slice(0, 16_000);
|
|
1524
|
+
entry.content_status = text.length <= 16_000 ? 'full' : 'excerpt';
|
|
1525
|
+
entry.aliases = citedIdentifiers(`${entry.title}\n${entry.description}`);
|
|
1526
|
+
}
|
|
1527
|
+
catch (error) {
|
|
1528
|
+
if (sourceCanceled(error))
|
|
1529
|
+
throw error;
|
|
1530
|
+
// Keep the validated feed excerpt when the vendor page cannot be read safely.
|
|
1531
|
+
}
|
|
1532
|
+
}));
|
|
1533
|
+
stabilizeUndated(result, window.previous);
|
|
1534
|
+
return result;
|
|
1535
|
+
}
|
|
1536
|
+
/** Collect source evidence and report failures without advancing failed sources' checkpoints. */
|
|
1537
|
+
export async function collectSources(inventory, config, checkpoints, http, now = Date.now(), previousEvidence = [], previousCoverage = []) {
|
|
1538
|
+
const result = { evidence: [], errors: [], checkpoints: { ...checkpoints }, coverage: [] };
|
|
1539
|
+
const jobs = [];
|
|
1540
|
+
const githubUnreadable = {
|
|
1541
|
+
reviewed: {},
|
|
1542
|
+
malware: {},
|
|
1543
|
+
};
|
|
1544
|
+
const window = (source) => newsWindow(source, checkpoints[source], checkpoints[`${source}:listed`], config.news_lookback_minutes ?? 60, previousEvidence, inventory, now);
|
|
1545
|
+
if (config.sources.hacker_news)
|
|
1546
|
+
jobs.push({ source: 'hacker_news', run: () => hackerNews(http, now, window('hacker_news')) });
|
|
1547
|
+
if (config.sources.osv)
|
|
1548
|
+
jobs.push({ source: 'osv', run: () => osv(inventory, previousEvidence, http, now) });
|
|
1549
|
+
if (config.sources.github)
|
|
1550
|
+
for (const type of ['reviewed', 'malware']) {
|
|
1551
|
+
githubUnreadable[type].pending = checkpoints[`github:${type}:unreadable`];
|
|
1552
|
+
githubUnreadable[type].skipped = checkpoints[`github:${type}:skipped`];
|
|
1553
|
+
githubUnreadable[type].unconfirmed = checkpoints[`github:${type}:unconfirmed`];
|
|
1554
|
+
jobs.push({
|
|
1555
|
+
source: `github:${type}`,
|
|
1556
|
+
run: () => github(type, checkpoints[`github:${type}`], config, http, now, inventory, previousEvidence, checkpoints[`github:${type}:since`], githubUnreadable[type]),
|
|
1557
|
+
});
|
|
1558
|
+
}
|
|
1559
|
+
if (config.sources.kev)
|
|
1560
|
+
jobs.push({ source: 'kev', run: () => kev(http, now, previousEvidence) });
|
|
1561
|
+
for (const vendor of new Set(config.sources.vendor_feeds ?? [])) {
|
|
1562
|
+
const source = `vendor:${vendor}`;
|
|
1563
|
+
jobs.push({ source, run: () => vendorFeed(vendor, http, now, window(source)) });
|
|
1564
|
+
}
|
|
1565
|
+
for (const url of new Set(config.sources.feeds)) {
|
|
1566
|
+
const source = `feed:${hash(url).slice(0, 16)}`;
|
|
1567
|
+
jobs.push({
|
|
1568
|
+
source,
|
|
1569
|
+
run: async () => {
|
|
1570
|
+
const current = window(source);
|
|
1571
|
+
const result = await feed(url, source, http, now, current);
|
|
1572
|
+
stabilizeUndated(result, current.previous);
|
|
1573
|
+
return result;
|
|
1574
|
+
},
|
|
1575
|
+
});
|
|
1576
|
+
}
|
|
1577
|
+
const cveNowState = {
|
|
1578
|
+
missing: checkpoints['cve_now:missing'],
|
|
1579
|
+
troubled: checkpoints['cve_now:troubled'],
|
|
1580
|
+
owed: checkpoints['cve_now:owed'],
|
|
1581
|
+
lookups: checkpoints['cve_now:lookups'],
|
|
1582
|
+
refusedSince: Number(checkpoints['cve_now:refused_since']) || undefined,
|
|
1583
|
+
};
|
|
1584
|
+
if (config.sources.cve_now)
|
|
1585
|
+
jobs.push({
|
|
1586
|
+
source: 'cve_now',
|
|
1587
|
+
run: () => collectCveNow(inventory, checkpoints.cve_now, previousEvidence, result.evidence, http, now, cveNowState),
|
|
1588
|
+
});
|
|
1589
|
+
for (const job of jobs) {
|
|
1590
|
+
const errorStart = result.errors.length;
|
|
1591
|
+
let collected = [];
|
|
1592
|
+
let failure;
|
|
1593
|
+
let incomplete = false;
|
|
1594
|
+
let packageResults;
|
|
1595
|
+
try {
|
|
1596
|
+
collected = await job.run();
|
|
1597
|
+
if (!Array.isArray(collected) && collected.failure) {
|
|
1598
|
+
failure = new SourceError(collected.failure);
|
|
1599
|
+
incomplete = true;
|
|
1600
|
+
}
|
|
1601
|
+
}
|
|
1602
|
+
catch (error) {
|
|
1603
|
+
if (sourceCanceled(error))
|
|
1604
|
+
throw error;
|
|
1605
|
+
failure = error;
|
|
1606
|
+
incomplete = true;
|
|
1607
|
+
if (error instanceof PartialSourceError) {
|
|
1608
|
+
collected = error.evidence;
|
|
1609
|
+
// An ordered source that ran out of room continues from the last record it processed.
|
|
1610
|
+
if (error.resume) {
|
|
1611
|
+
result.checkpoints[job.source] = error.resume;
|
|
1612
|
+
// A GitHub catch-up goes on next time; remember where its chain of scans began.
|
|
1613
|
+
if (job.source.startsWith('github:'))
|
|
1614
|
+
result.checkpoints[`${job.source}:since`] = timestamp(githubWindow(checkpoints[job.source], checkpoints[`${job.source}:since`], now).chainStart);
|
|
1615
|
+
}
|
|
1616
|
+
packageResults = error.packageResults;
|
|
1617
|
+
}
|
|
1618
|
+
}
|
|
1619
|
+
// Identifiers cve.now did not have, and when each was last asked for.
|
|
1620
|
+
if (job.source === 'cve_now' && cveNowState.next !== undefined)
|
|
1621
|
+
result.checkpoints['cve_now:missing'] = cveNowState.next;
|
|
1622
|
+
// Identifiers whose requests failed, so that the next poll asks for them last.
|
|
1623
|
+
if (job.source === 'cve_now' && cveNowState.nextTroubled !== undefined)
|
|
1624
|
+
result.checkpoints['cve_now:troubled'] = cveNowState.nextTroubled;
|
|
1625
|
+
// New records still to be read, so that the checkpoint can move on without them.
|
|
1626
|
+
if (job.source === 'cve_now' && cveNowState.nextOwed !== undefined)
|
|
1627
|
+
result.checkpoints['cve_now:owed'] = cveNowState.nextOwed;
|
|
1628
|
+
if (job.source === 'cve_now' && cveNowState.nextLookups !== undefined)
|
|
1629
|
+
result.checkpoints['cve_now:lookups'] = cveNowState.nextLookups;
|
|
1630
|
+
if (job.source === 'github:reviewed' || job.source === 'github:malware') {
|
|
1631
|
+
const state = githubUnreadable[job.source === 'github:reviewed' ? 'reviewed' : 'malware'];
|
|
1632
|
+
if (state.nextPending !== undefined)
|
|
1633
|
+
result.checkpoints[`${job.source}:unreadable`] = state.nextPending;
|
|
1634
|
+
if (state.nextSkipped !== undefined)
|
|
1635
|
+
result.checkpoints[`${job.source}:skipped`] = state.nextSkipped;
|
|
1636
|
+
if (state.nextUnconfirmed !== undefined)
|
|
1637
|
+
result.checkpoints[`${job.source}:unconfirmed`] = state.nextUnconfirmed;
|
|
1638
|
+
}
|
|
1639
|
+
if (job.source === 'cve_now' && cveNowState.nextRefusedSince !== undefined)
|
|
1640
|
+
result.checkpoints['cve_now:refused_since'] = String(cveNowState.nextRefusedSince ?? '');
|
|
1641
|
+
const evidence = (Array.isArray(collected) ? collected : collected.evidence).filter((item) => {
|
|
1642
|
+
const modified = Date.parse(item.modified_at);
|
|
1643
|
+
if (Number.isFinite(modified) && modified <= now + 5 * 60_000)
|
|
1644
|
+
return true;
|
|
1645
|
+
failure ??= new SourceError('Source returned an invalid or future modification timestamp; collection is incomplete.');
|
|
1646
|
+
incomplete = true;
|
|
1647
|
+
// The record left out here may be one for an inventory package.
|
|
1648
|
+
packageResults = undefined;
|
|
1649
|
+
return false;
|
|
1650
|
+
});
|
|
1651
|
+
result.evidence.push(...evidence);
|
|
1652
|
+
if (!incomplete) {
|
|
1653
|
+
result.checkpoints[job.source] = timestamp(now);
|
|
1654
|
+
if (job.source.startsWith('github:'))
|
|
1655
|
+
result.checkpoints[`${job.source}:since`] = '';
|
|
1656
|
+
}
|
|
1657
|
+
// Remember what the feed listed, so the next poll can tell a late arrival from an old entry.
|
|
1658
|
+
if (!Array.isArray(collected) && !incomplete)
|
|
1659
|
+
result.checkpoints[`${job.source}:listed`] = JSON.stringify(collected.listed.slice(0, 2_000));
|
|
1660
|
+
if (!Array.isArray(collected) && collected.undated.size)
|
|
1661
|
+
result.errors.push({
|
|
1662
|
+
source: `${job.source}:timestamps`,
|
|
1663
|
+
message: `${collected.undated.size} news item(s) have no valid publication or update time; included as first-seen evidence because their age cannot be verified.`,
|
|
1664
|
+
});
|
|
1665
|
+
if (job.source === 'hacker_news') {
|
|
1666
|
+
const missing = evidence.filter((item) => item.content_status !== 'full' && evidenceRelevant(item, inventory)).length;
|
|
1667
|
+
if (missing)
|
|
1668
|
+
result.errors.push({
|
|
1669
|
+
source: 'hacker_news:articles',
|
|
1670
|
+
message: `${missing} relevant The Hacker News article(s) could not be read in full; excerpts remain available for cautious review.`,
|
|
1671
|
+
});
|
|
1672
|
+
}
|
|
1673
|
+
if (job.source.startsWith('vendor:')) {
|
|
1674
|
+
const missing = evidence.filter((item) => item.content_status !== 'full' && evidenceRelevant(item, inventory)).length;
|
|
1675
|
+
if (missing)
|
|
1676
|
+
result.errors.push({
|
|
1677
|
+
source: `${job.source}:articles`,
|
|
1678
|
+
message: `${missing} relevant vendor article(s) could not be read in full; excerpts remain available for cautious review.`,
|
|
1679
|
+
});
|
|
1680
|
+
}
|
|
1681
|
+
if (incomplete)
|
|
1682
|
+
result.errors.push({
|
|
1683
|
+
source: job.source,
|
|
1684
|
+
// Transport errors can contain feed tokens or HTTP headers.
|
|
1685
|
+
message: failure instanceof SourceError
|
|
1686
|
+
? failure.message
|
|
1687
|
+
: 'Source request failed; cached evidence was retained and its checkpoint was not advanced.',
|
|
1688
|
+
});
|
|
1689
|
+
const errors = result.errors.slice(errorStart).map((error) => error.message);
|
|
1690
|
+
const complete = !incomplete && errors.length === 0;
|
|
1691
|
+
const previousReceipt = previousCoverage.find((receipt) => receipt.source === job.source);
|
|
1692
|
+
const lastSuccess = complete
|
|
1693
|
+
? timestamp(now)
|
|
1694
|
+
: previousReceipt
|
|
1695
|
+
? previousReceipt.last_success_at
|
|
1696
|
+
: checkpoints[job.source];
|
|
1697
|
+
const successTime = lastSuccess ? Date.parse(lastSuccess) : NaN;
|
|
1698
|
+
result.coverage.push({
|
|
1699
|
+
source: job.source,
|
|
1700
|
+
attempted_at: timestamp(now),
|
|
1701
|
+
...(lastSuccess ? { last_success_at: lastSuccess } : {}),
|
|
1702
|
+
...(Number.isFinite(successTime)
|
|
1703
|
+
? {
|
|
1704
|
+
fresh_until: timestamp(successTime + Math.max(120_000, (config.poll_interval_minutes ?? 30) * 120_000)),
|
|
1705
|
+
}
|
|
1706
|
+
: {}),
|
|
1707
|
+
status: complete ? 'complete' : evidence.length ? 'partial' : 'failed',
|
|
1708
|
+
...(!complete && packageResults ? { package_results: packageResults } : {}),
|
|
1709
|
+
freshness: !Number.isFinite(successTime)
|
|
1710
|
+
? 'never'
|
|
1711
|
+
: successTime <= now + 300_000 &&
|
|
1712
|
+
now - successTime <= Math.max(120_000, (config.poll_interval_minutes ?? 30) * 120_000)
|
|
1713
|
+
? 'fresh'
|
|
1714
|
+
: 'stale',
|
|
1715
|
+
evidence_count: evidence.length,
|
|
1716
|
+
errors,
|
|
1717
|
+
scope: job.source === 'osv'
|
|
1718
|
+
? 'Configured package identities/versions and tracked advisories; no absence-of-vulnerability guarantee.'
|
|
1719
|
+
: job.source === 'cve_now'
|
|
1720
|
+
? 'Recent, tracked and news-cited CVEs plus exact npm queries; not exhaustive historical coverage.'
|
|
1721
|
+
: 'Configured bounded feed/advisory collection; not exhaustive vulnerability coverage.',
|
|
1722
|
+
});
|
|
1723
|
+
}
|
|
1724
|
+
return result;
|
|
1725
|
+
}
|