@shieldaai/security-watch 0.0.0-stage → 0.1.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/CONTRIBUTING.md +90 -0
  2. package/LICENSE +202 -0
  3. package/README.md +269 -2
  4. package/SECURITY.md +47 -0
  5. package/dist/assessment.d.ts +5 -0
  6. package/dist/assessment.js +398 -0
  7. package/dist/cli.d.ts +2 -0
  8. package/dist/cli.js +792 -0
  9. package/dist/config.d.ts +242 -0
  10. package/dist/config.js +298 -0
  11. package/dist/cve-now.d.ts +5 -0
  12. package/dist/cve-now.js +413 -0
  13. package/dist/delivery.d.ts +26 -0
  14. package/dist/delivery.js +394 -0
  15. package/dist/ecosystems.d.ts +25 -0
  16. package/dist/ecosystems.js +254 -0
  17. package/dist/engine.d.ts +26 -0
  18. package/dist/engine.js +307 -0
  19. package/dist/health.d.ts +17 -0
  20. package/dist/health.js +70 -0
  21. package/dist/heartbeat.d.ts +13 -0
  22. package/dist/heartbeat.js +74 -0
  23. package/dist/http.d.ts +8 -0
  24. package/dist/http.js +251 -0
  25. package/dist/index.d.ts +18 -0
  26. package/dist/index.js +15 -0
  27. package/dist/inventory.d.ts +3 -0
  28. package/dist/inventory.js +143 -0
  29. package/dist/lock.d.ts +3 -0
  30. package/dist/lock.js +112 -0
  31. package/dist/maintenance.d.ts +43 -0
  32. package/dist/maintenance.js +227 -0
  33. package/dist/models.d.ts +20 -0
  34. package/dist/models.js +602 -0
  35. package/dist/operations.d.ts +17 -0
  36. package/dist/operations.js +117 -0
  37. package/dist/providers.d.ts +209 -0
  38. package/dist/providers.js +459 -0
  39. package/dist/setup.d.ts +113 -0
  40. package/dist/setup.js +100 -0
  41. package/dist/source-error.d.ts +22 -0
  42. package/dist/source-error.js +56 -0
  43. package/dist/sources.d.ts +3 -0
  44. package/dist/sources.js +1071 -0
  45. package/dist/store.d.ts +71 -0
  46. package/dist/store.js +651 -0
  47. package/dist/types.d.ts +247 -0
  48. package/dist/types.js +1 -0
  49. package/dist/util.d.ts +6 -0
  50. package/dist/util.js +14 -0
  51. package/dist/vendor-sources.d.ts +24 -0
  52. package/dist/vendor-sources.js +56 -0
  53. package/docs/configuration.md +406 -0
  54. package/docs/quality-review.md +104 -0
  55. package/examples/advisories.json +17 -0
  56. package/examples/common-systems.yaml +243 -0
  57. package/examples/libraries.example.txt +16 -0
  58. package/examples/libraries.example.yaml +38 -0
  59. package/examples/library-watch.example.yaml +27 -0
  60. package/examples/security-watch.example.yaml +86 -0
  61. package/examples/systems.example.yaml +31 -0
  62. package/package.json +69 -4
@@ -0,0 +1,1071 @@
1
+ import { XMLParser, XMLValidator } from 'fast-xml-parser';
2
+ import { defaultTreeAdapter, parse, parseFragment } from 'parse5';
3
+ import { compare, valid } from 'semver';
4
+ import { cleanText, hash, highest, timestamp } from './util.js';
5
+ import { collectCveNow, evidenceRelevant } from './cve-now.js';
6
+ import { VENDOR_FEEDS, vendorArticleBody, vendorArticleTarget } from './vendor-sources.js';
7
+ import { exactLibraryVersion, normalizeEcosystem, normalizePackageName, osvPackageNames, samePackage, } from './ecosystems.js';
8
+ import { PartialSourceError, SourceError, SourceHttpError, SourceItemFailures, sourceCanceled, throwSourceFailure, } from './source-error.js';
9
+ const OSV = 'https://api.osv.dev/v1';
10
+ const GITHUB = 'https://api.github.com/advisories';
11
+ const KEV = 'https://raw.githubusercontent.com/cisagov/kev-data/develop/known_exploited_vulnerabilities.json';
12
+ const HACKER_NEWS = 'https://feeds.feedburner.com/TheHackersNews';
13
+ const MAX_PAGES = 50;
14
+ const MAX_ADVISORIES = 5_000;
15
+ const MAX_FEED_ENTRIES = 500;
16
+ const HOUR = 3_600_000;
17
+ function record(value) {
18
+ if (!value || typeof value !== 'object' || Array.isArray(value))
19
+ throw new SourceError('Invalid source schema.');
20
+ return value;
21
+ }
22
+ function array(value, optional = false) {
23
+ if (value === undefined && optional)
24
+ return [];
25
+ if (!Array.isArray(value))
26
+ throw new SourceError('Invalid source schema.');
27
+ return value;
28
+ }
29
+ function string(value) {
30
+ if (typeof value !== 'string' || !value.trim())
31
+ throw new SourceError('Invalid source schema.');
32
+ return value;
33
+ }
34
+ function optionalString(value) {
35
+ if (value === undefined || value === null)
36
+ return undefined;
37
+ return string(value);
38
+ }
39
+ function date(value) {
40
+ const input = string(value);
41
+ if (!Number.isFinite(Date.parse(input)))
42
+ throw new SourceError('Invalid source date.');
43
+ return new Date(input).toISOString();
44
+ }
45
+ function aliases(values) {
46
+ return [
47
+ ...new Set(values
48
+ .filter((v) => typeof v === 'string' && v.length > 0)
49
+ .map((v) => /^cve-/i.test(v) ? v.toUpperCase() : /^ghsa-/i.test(v) ? `GHSA-${v.slice(5).toLowerCase()}` : v)),
50
+ ];
51
+ }
52
+ function aliasStrings(value) {
53
+ return array(value, true).map(string);
54
+ }
55
+ function severity(value) {
56
+ const normalized = typeof value === 'string' ? value.toLowerCase() : '';
57
+ if (normalized === 'moderate')
58
+ return 'medium';
59
+ return normalized === 'critical' || normalized === 'high' || normalized === 'medium' || normalized === 'low'
60
+ ? normalized
61
+ : 'unknown';
62
+ }
63
+ function scoreSeverity(score) {
64
+ if (typeof score !== 'number' || !Number.isFinite(score) || score < 0 || score > 10)
65
+ return 'unknown';
66
+ return score >= 9
67
+ ? 'critical'
68
+ : score >= 7
69
+ ? 'high'
70
+ : score >= 4
71
+ ? 'medium'
72
+ : score > 0
73
+ ? 'low'
74
+ : 'unknown';
75
+ }
76
+ // FIRST CVSS 3.0/3.1 base equations only. Unsupported vectors remain unknown.
77
+ function vectorSeverity(vector) {
78
+ if (typeof vector !== 'string')
79
+ return 'unknown';
80
+ if (/^(?:\d|10)(?:\.\d+)?$/.test(vector))
81
+ return scoreSeverity(Number(vector));
82
+ if (!/^CVSS:3\.[01]\//.test(vector))
83
+ return 'unknown';
84
+ const metrics = {};
85
+ for (const part of vector.split('/').slice(1)) {
86
+ const pieces = part.split(':');
87
+ if (pieces.length !== 2 || !pieces[0] || !pieces[1] || metrics[pieces[0]])
88
+ return 'unknown';
89
+ metrics[pieces[0]] = pieces[1];
90
+ }
91
+ if (metrics.S !== 'U' && metrics.S !== 'C')
92
+ return 'unknown';
93
+ const pick = (key, weights) => weights[metrics[key] ?? ''];
94
+ const av = pick('AV', { N: 0.85, A: 0.62, L: 0.55, P: 0.2 });
95
+ const ac = pick('AC', { L: 0.77, H: 0.44 });
96
+ const pr = pick('PR', { N: 0.85, L: metrics.S === 'C' ? 0.68 : 0.62, H: metrics.S === 'C' ? 0.5 : 0.27 });
97
+ const ui = pick('UI', { N: 0.85, R: 0.62 });
98
+ const c = pick('C', { N: 0, L: 0.22, H: 0.56 });
99
+ const i = pick('I', { N: 0, L: 0.22, H: 0.56 });
100
+ const a = pick('A', { N: 0, L: 0.22, H: 0.56 });
101
+ if (av === undefined ||
102
+ ac === undefined ||
103
+ pr === undefined ||
104
+ ui === undefined ||
105
+ c === undefined ||
106
+ i === undefined ||
107
+ a === undefined)
108
+ return 'unknown';
109
+ const iss = 1 - (1 - c) * (1 - i) * (1 - a);
110
+ const impact = metrics.S === 'U' ? 6.42 * iss : 7.52 * (iss - 0.029) - 3.25 * (iss - 0.02) ** 15;
111
+ if (impact <= 0)
112
+ return 'unknown';
113
+ const raw = Math.min((metrics.S === 'C' ? 1.08 : 1) * (impact + 8.22 * av * ac * pr * ui), 10);
114
+ const integer = Math.round(raw * 100_000);
115
+ const rounded = integer % 10_000 === 0 ? integer / 100_000 : (Math.floor(integer / 10_000) + 1) / 10;
116
+ return scoreSeverity(rounded);
117
+ }
118
+ function optionalRecord(value) {
119
+ return value === undefined || value === null ? {} : record(value);
120
+ }
121
+ function publicUrl(input, fallback) {
122
+ if (typeof input !== 'string')
123
+ return fallback;
124
+ try {
125
+ const url = new URL(input, fallback);
126
+ if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password)
127
+ return fallback;
128
+ return url.href;
129
+ }
130
+ catch {
131
+ return fallback;
132
+ }
133
+ }
134
+ function retainNewest(target, item) {
135
+ const previous = target.get(item.id);
136
+ if (!previous || Date.parse(item.modified_at) >= Date.parse(previous.modified_at))
137
+ target.set(item.id, item);
138
+ }
139
+ async function json(http, url, options = {}) {
140
+ const response = await http(url, { maxBytes: 8_000_000, ...options });
141
+ if (response.status !== 200)
142
+ throw new SourceHttpError('Source', response.status);
143
+ try {
144
+ return JSON.parse(response.body);
145
+ }
146
+ catch {
147
+ throw new SourceError('Source returned invalid JSON.');
148
+ }
149
+ }
150
+ function sourcePackage(ecosystem, name) {
151
+ let normalized;
152
+ try {
153
+ normalized = normalizeEcosystem(ecosystem);
154
+ }
155
+ catch {
156
+ return { ecosystem, name };
157
+ }
158
+ try {
159
+ return { ecosystem: normalized, name: normalizePackageName(normalized, name) };
160
+ }
161
+ catch {
162
+ throw new SourceError('Source returned an invalid package identity.');
163
+ }
164
+ }
165
+ function osvRanges(value) {
166
+ const ranges = array(value, true);
167
+ if (!ranges.length)
168
+ return undefined;
169
+ const expressions = [];
170
+ for (const raw of ranges) {
171
+ const range = record(raw);
172
+ if (range.type !== 'SEMVER')
173
+ return undefined;
174
+ const events = array(range.events);
175
+ if (!events.length)
176
+ throw new SourceError('Invalid OSV version range.');
177
+ const timeline = [];
178
+ const limits = [];
179
+ for (const rawEvent of events) {
180
+ const event = record(rawEvent);
181
+ const fields = ['introduced', 'fixed', 'last_affected', 'limit'].filter((field) => event[field] !== undefined);
182
+ if (fields.length !== 1)
183
+ throw new SourceError('Invalid OSV version range.');
184
+ const field = fields[0];
185
+ const version = string(event[field]);
186
+ if (field === 'limit' && version.includes('*')) {
187
+ limits.push('*');
188
+ continue;
189
+ }
190
+ const normalized = version === '0' && field === 'introduced' ? '0' : valid(version);
191
+ if (!normalized)
192
+ return undefined;
193
+ if (field === 'limit')
194
+ limits.push(normalized);
195
+ else
196
+ timeline.push({ field, version: normalized });
197
+ }
198
+ if (!timeline.some((event) => event.field === 'introduced'))
199
+ throw new SourceError('Invalid OSV version range.');
200
+ const versionOrder = (left, right) => left === right ? 0 : left === '0' ? -1 : right === '0' ? 1 : compare(left, right);
201
+ // OSV recommends sorted events but does not require source order. Limits apply
202
+ // independently to the whole range; they are not fix transitions.
203
+ timeline.sort((a, b) => versionOrder(a.version, b.version));
204
+ const maximum = limits.includes('*') ? undefined : limits.sort(versionOrder).at(-1);
205
+ let lower;
206
+ let open = false;
207
+ const expression = (upper) => [lower && `>=${lower}`, upper, maximum && `<${maximum}`].filter(Boolean).join(' ') || '*';
208
+ for (let index = 0; index < timeline.length; index++) {
209
+ const event = timeline[index];
210
+ const previous = timeline[index - 1];
211
+ // Conflicting transitions at one normalized version have no unambiguous order.
212
+ if (previous && versionOrder(event.version, previous.version) === 0 && event.field !== previous.field)
213
+ return undefined;
214
+ if (event.field === 'introduced') {
215
+ if (!open)
216
+ lower = event.version === '0' ? undefined : event.version;
217
+ open = true;
218
+ }
219
+ else if (open) {
220
+ expressions.push(expression(`${event.field === 'last_affected' ? '<=' : '<'}${event.version}`));
221
+ open = false;
222
+ }
223
+ }
224
+ if (open)
225
+ expressions.push(expression());
226
+ }
227
+ return expressions.length ? expressions.join(' || ') : undefined;
228
+ }
229
+ function osvRecord(raw, expectedId, matches, now) {
230
+ const data = record(raw);
231
+ if (string(data.id) !== expectedId)
232
+ throw new SourceError('OSV returned a mismatched advisory ID.');
233
+ const packageClaims = [];
234
+ const severities = [severity(optionalRecord(data.database_specific).severity)];
235
+ for (const rawSeverity of array(data.severity, true))
236
+ severities.push(vectorSeverity(record(rawSeverity).score));
237
+ for (const rawAffected of array(data.affected, true)) {
238
+ const affected = record(rawAffected);
239
+ // OSV can include a separate Git-only entry beside registry package entries.
240
+ if (affected.package === undefined) {
241
+ const ranges = array(affected.ranges);
242
+ if (!ranges.length ||
243
+ !ranges.every((rawRange) => {
244
+ const range = record(rawRange);
245
+ return range.type === 'GIT' && typeof range.repo === 'string' && range.repo.length > 0;
246
+ }))
247
+ throw new SourceError('OSV returned an affected entry without a package identity.');
248
+ continue;
249
+ }
250
+ const pkg = record(affected.package);
251
+ const { ecosystem, name } = sourcePackage(string(pkg.ecosystem), string(pkg.name));
252
+ const range = ecosystem === 'npm' ? osvRanges(affected.ranges) : undefined;
253
+ const versions = array(affected.versions, true).map(string);
254
+ const matched_versions = [
255
+ ...new Set(matches
256
+ .filter((query) => samePackage(query, { ecosystem, name }))
257
+ .map((query) => query.version)
258
+ .filter((version) => version !== undefined)),
259
+ ];
260
+ const fixed = array(affected.ranges, true)
261
+ .flatMap((rawRange) => array(record(rawRange).events, true))
262
+ .map((rawEvent) => optionalString(record(rawEvent).fixed))
263
+ .filter((v) => !!v);
264
+ packageClaims.push({
265
+ ecosystem,
266
+ name,
267
+ ...(range ? { range } : {}),
268
+ ...(versions.length ? { versions } : {}),
269
+ ...(matched_versions.length ? { matched_versions } : {}),
270
+ ...(fixed.length ? { fixed: [...new Set(fixed)].join(', ') } : {}),
271
+ });
272
+ severities.push(severity(optionalRecord(affected.database_specific).severity));
273
+ for (const rawSeverity of array(affected.severity, true))
274
+ severities.push(vectorSeverity(record(rawSeverity).score));
275
+ }
276
+ // Queries identify the package even when details omit it. Only a versioned query proves impact.
277
+ for (const query of matches)
278
+ if (!packageClaims.some((claim) => samePackage(claim, query))) {
279
+ const versions = [
280
+ ...new Set(matches
281
+ .filter((match) => samePackage(match, query))
282
+ .map((match) => match.version)
283
+ .filter((version) => version !== undefined)),
284
+ ];
285
+ packageClaims.push({
286
+ ecosystem: query.ecosystem,
287
+ name: query.name,
288
+ ...(versions.length ? { matched_versions: versions } : {}),
289
+ });
290
+ }
291
+ const canonical = `https://osv.dev/vulnerability/${encodeURIComponent(expectedId)}`;
292
+ return {
293
+ id: `osv:${expectedId}`,
294
+ source: 'osv',
295
+ kind: 'advisory',
296
+ title: cleanText(optionalString(data.summary) ?? expectedId, 500),
297
+ url: canonical,
298
+ description: cleanText(optionalString(data.details) ?? optionalString(data.summary) ?? expectedId, 16_000),
299
+ aliases: aliases([expectedId, ...aliasStrings(data.aliases)]),
300
+ severity: highest(...severities),
301
+ modified_at: date(data.modified),
302
+ fetched_at: timestamp(now),
303
+ ...(data.published ? { published_at: date(data.published) } : {}),
304
+ packages: packageClaims,
305
+ withdrawn: data.withdrawn === undefined || data.withdrawn === null ? false : !!date(data.withdrawn),
306
+ malware: /^MAL-/.test(expectedId),
307
+ };
308
+ }
309
+ async function osv(inventory, previous, http, now) {
310
+ const unique = new Map();
311
+ for (const system of inventory.systems)
312
+ for (const component of system.components) {
313
+ const ecosystem = normalizeEcosystem(component.ecosystem);
314
+ let version;
315
+ // Imported lockfiles may describe an unresolved Git/URL dependency instead of a registry version.
316
+ // Query its package name conservatively without turning that text into an exact-version match.
317
+ if (component.version) {
318
+ try {
319
+ version = exactLibraryVersion(component.version, ecosystem);
320
+ }
321
+ catch {
322
+ /* Applicability remains unknown. */
323
+ }
324
+ }
325
+ for (const name of osvPackageNames(ecosystem, component.name)) {
326
+ const key = JSON.stringify([ecosystem, name, version ?? null]);
327
+ unique.set(key, {
328
+ ecosystem,
329
+ name,
330
+ ...(version ? { version } : {}),
331
+ seen: new Set(),
332
+ });
333
+ }
334
+ }
335
+ const queries = [...unique.values()];
336
+ if (queries.length > 10_000)
337
+ throw new SourceError('OSV inventory exceeds the 10,000 unique package queries limit.');
338
+ const results = [];
339
+ const invalid = new SourceItemFailures();
340
+ try {
341
+ const matched = new Map();
342
+ for (let offset = 0; offset < queries.length; offset += 100) {
343
+ let pending = queries.slice(offset, offset + 100);
344
+ for (let page = 0; pending.length; page++) {
345
+ if (page >= MAX_PAGES)
346
+ throw new SourceError('OSV pagination limit reached; collection is incomplete.');
347
+ const body = JSON.stringify({
348
+ queries: pending.map((query) => ({
349
+ package: { ecosystem: query.ecosystem, name: query.name },
350
+ ...(query.version ? { version: query.version } : {}),
351
+ ...(query.page_token ? { page_token: query.page_token } : {}),
352
+ })),
353
+ });
354
+ const data = record(await json(http, `${OSV}/querybatch`, {
355
+ method: 'POST',
356
+ headers: { 'content-type': 'application/json' },
357
+ body,
358
+ }));
359
+ const results = array(data.results);
360
+ if (results.length !== pending.length)
361
+ throw new SourceError('OSV batch result count did not match the request.');
362
+ const next = [];
363
+ for (let index = 0; index < results.length; index++) {
364
+ const result = invalid.read(() => record(results[index]));
365
+ if (!result)
366
+ continue;
367
+ const query = pending[index];
368
+ const vulns = invalid.read(() => array(result.vulns, true));
369
+ for (const rawVuln of vulns ?? []) {
370
+ const id = invalid.read(() => {
371
+ const vuln = record(rawVuln);
372
+ if (vuln.modified !== undefined)
373
+ date(vuln.modified);
374
+ return string(vuln.id);
375
+ });
376
+ if (!id)
377
+ continue;
378
+ if (!matched.has(id))
379
+ matched.set(id, []);
380
+ if (!matched.get(id).some((match) => samePackage(match, query) && match.version === query.version))
381
+ matched.get(id).push(query);
382
+ if (matched.size > MAX_ADVISORIES)
383
+ throw new SourceError('OSV advisory limit reached; collection is incomplete.');
384
+ }
385
+ const token = optionalString(result.next_page_token);
386
+ if (token) {
387
+ if (query.seen.has(token))
388
+ throw new SourceError('OSV returned a repeated pagination token.');
389
+ query.seen.add(token);
390
+ next.push({ ...query, page_token: token });
391
+ }
392
+ }
393
+ pending = next;
394
+ }
395
+ }
396
+ const ids = new Set(matched.keys());
397
+ for (const item of previous)
398
+ if (item.source === 'osv' && item.id.startsWith('osv:'))
399
+ ids.add(item.id.slice(4));
400
+ if (ids.size > MAX_ADVISORIES)
401
+ throw new SourceError('OSV historical advisory limit reached; collection is incomplete.');
402
+ // Bounded parallelism; historical IDs are refreshed even when they disappear from exact-version queries.
403
+ const allIds = [...ids];
404
+ let failures = 0;
405
+ let firstFailure;
406
+ for (let index = 0; index < allIds.length; index += 4) {
407
+ const batch = allIds.slice(index, index + 4);
408
+ const settled = await Promise.allSettled(batch.map(async (id) => osvRecord(await json(http, `${OSV}/vulns/${encodeURIComponent(id)}`), id, matched.get(id) ?? [], now)));
409
+ const rejected = settled.filter((item) => item.status === 'rejected');
410
+ const canceled = rejected.find(({ reason }) => sourceCanceled(reason));
411
+ if (canceled)
412
+ throw canceled.reason;
413
+ for (const item of settled) {
414
+ if (item.status === 'fulfilled')
415
+ results.push(item.value);
416
+ else {
417
+ failures++;
418
+ firstFailure ??=
419
+ item.reason instanceof SourceError ? item.reason.message : 'Source request failed.';
420
+ }
421
+ }
422
+ if (rejected.length === batch.length ||
423
+ failures >= 8 ||
424
+ rejected.some(({ reason }) => reason instanceof SourceHttpError && [401, 403, 429].includes(reason.status)))
425
+ break;
426
+ }
427
+ if (failures)
428
+ throw new SourceError(`${failures} OSV advisory detail request(s) failed; collection is incomplete. ${firstFailure}`);
429
+ return invalid.finish('OSV', results);
430
+ }
431
+ catch (error) {
432
+ throwSourceFailure(error, results);
433
+ }
434
+ }
435
+ function githubRecord(raw, type, now) {
436
+ const data = record(raw);
437
+ const id = string(data.ghsa_id);
438
+ if (!/^GHSA-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}$/i.test(id))
439
+ throw new SourceError('Invalid GitHub advisory identifier.');
440
+ if (data.type !== undefined && data.type !== type)
441
+ throw new SourceError('GitHub returned an unexpected advisory type.');
442
+ const modified = date(data.updated_at);
443
+ if (Date.parse(modified) > now + 5 * 60_000)
444
+ throw new SourceError('Source returned a future modification timestamp; collection is incomplete.');
445
+ const packages = array(data.vulnerabilities).map((rawVulnerability) => {
446
+ const vulnerability = record(rawVulnerability);
447
+ const pkg = record(vulnerability.package);
448
+ const range = optionalString(vulnerability.vulnerable_version_range);
449
+ const patched = vulnerability.first_patched_version;
450
+ const fixed = typeof patched === 'object' && patched !== null
451
+ ? optionalString(record(patched).identifier)
452
+ : optionalString(patched);
453
+ return {
454
+ ...sourcePackage(string(pkg.ecosystem), string(pkg.name)),
455
+ ...(range ? { range } : {}),
456
+ ...(fixed ? { fixed } : {}),
457
+ };
458
+ });
459
+ const cvss = optionalRecord(data.cvss);
460
+ const cvssVersions = optionalRecord(data.cvss_severities);
461
+ const ratings = [severity(data.severity), scoreSeverity(cvss.score), vectorSeverity(cvss.vector_string)];
462
+ for (const value of Object.values(cvssVersions))
463
+ if (value)
464
+ ratings.push(scoreSeverity(record(value).score));
465
+ return {
466
+ id: `github:${id}`,
467
+ source: `github:${type}`,
468
+ kind: 'advisory',
469
+ title: cleanText(string(data.summary), 500),
470
+ url: `https://github.com/advisories/${encodeURIComponent(id)}`,
471
+ description: cleanText(optionalString(data.description) ?? string(data.summary), 16_000),
472
+ aliases: aliases([
473
+ id,
474
+ data.cve_id,
475
+ ...array(data.identifiers, true).map((item) => string(record(item).value)),
476
+ ]),
477
+ severity: highest(...ratings),
478
+ modified_at: modified,
479
+ fetched_at: timestamp(now),
480
+ published_at: date(data.published_at),
481
+ packages,
482
+ withdrawn: data.withdrawn_at === undefined || data.withdrawn_at === null ? false : !!date(data.withdrawn_at),
483
+ malware: type === 'malware',
484
+ };
485
+ }
486
+ function nextGithubLink(link) {
487
+ if (!link)
488
+ return undefined;
489
+ for (const part of link.split(',')) {
490
+ const parsed = part.match(/^\s*<([^>]+)>\s*;\s*rel\s*=\s*"?([a-z]+)"?\s*$/i);
491
+ if (!parsed?.[1] || !parsed[2])
492
+ throw new SourceError('GitHub returned invalid pagination.');
493
+ if (parsed[2].toLowerCase() !== 'next')
494
+ continue;
495
+ let url;
496
+ try {
497
+ url = new URL(parsed[1]);
498
+ }
499
+ catch {
500
+ throw new SourceError('GitHub returned invalid pagination.');
501
+ }
502
+ if (url.origin !== 'https://api.github.com' ||
503
+ url.pathname !== '/advisories' ||
504
+ url.username ||
505
+ url.password ||
506
+ url.hash)
507
+ throw new SourceError('GitHub returned an untrusted pagination destination.');
508
+ return url.href;
509
+ }
510
+ return undefined;
511
+ }
512
+ async function github(type, checkpoint, config, http, now) {
513
+ const previous = checkpoint === undefined ? now - 7 * 24 * HOUR : Date.parse(checkpoint);
514
+ if (!Number.isFinite(previous) || previous > now)
515
+ throw new SourceError('Invalid source checkpoint; reset it before collecting.');
516
+ const start = Math.max(0, previous - HOUR);
517
+ const url = new URL(GITHUB);
518
+ url.searchParams.set('type', type);
519
+ // GitHub's search-date parser rejects fractional seconds, unlike checkpoint timestamps.
520
+ const queryTime = (value) => timestamp(value).replace(/\.\d{3}Z$/, 'Z');
521
+ url.searchParams.set('modified', `${queryTime(start)}..${queryTime(now)}`);
522
+ url.searchParams.set('sort', 'updated');
523
+ url.searchParams.set('direction', 'asc');
524
+ url.searchParams.set('per_page', '100');
525
+ const headers = {
526
+ accept: 'application/vnd.github+json',
527
+ 'x-github-api-version': '2026-03-10',
528
+ };
529
+ const token = process.env[config.sources.github_token_env];
530
+ if (token)
531
+ headers.authorization = `Bearer ${token}`;
532
+ let next = url.href;
533
+ const seen = new Set();
534
+ const evidence = new Map();
535
+ const invalid = new SourceItemFailures();
536
+ try {
537
+ for (let page = 0; next; page++) {
538
+ if (page >= MAX_PAGES)
539
+ throw new SourceError('GitHub pagination limit reached; collection is incomplete.');
540
+ if (seen.has(next))
541
+ throw new SourceError('GitHub returned repeated pagination.');
542
+ seen.add(next);
543
+ const response = await http(next, { headers, maxBytes: 8_000_000, redirects: 0 });
544
+ if (response.status !== 200)
545
+ throw new SourceError(`Source returned HTTP ${response.status}.`);
546
+ let data;
547
+ try {
548
+ data = JSON.parse(response.body);
549
+ }
550
+ catch {
551
+ throw new SourceError('Source returned invalid JSON.');
552
+ }
553
+ const items = array(data);
554
+ if (items.length > 100)
555
+ throw new SourceError('GitHub returned more records than the requested page limit.');
556
+ for (const item of items) {
557
+ const parsed = invalid.read(() => githubRecord(item, type, now));
558
+ if (parsed)
559
+ retainNewest(evidence, parsed);
560
+ }
561
+ const link = Object.entries(response.headers).find(([key]) => key.toLowerCase() === 'link')?.[1];
562
+ next = nextGithubLink(link);
563
+ }
564
+ return invalid.finish('GitHub', [...evidence.values()]);
565
+ }
566
+ catch (error) {
567
+ throwSourceFailure(error, [...evidence.values()]);
568
+ }
569
+ }
570
+ async function kev(http, now, previous) {
571
+ const data = record(await json(http, KEV));
572
+ const entries = array(data.vulnerabilities);
573
+ if (!Number.isSafeInteger(data.count) || data.count !== entries.length || entries.length > 20_000)
574
+ throw new SourceError('Invalid or incomplete CISA KEV catalog.');
575
+ const released = date(data.dateReleased);
576
+ if (Date.parse(released) > now + 5 * 60_000)
577
+ throw new SourceError('Source returned a future modification timestamp; collection is incomplete.');
578
+ const old = new Map();
579
+ for (const item of previous)
580
+ if (item.source === 'kev')
581
+ retainNewest(old, item);
582
+ const invalid = new SourceItemFailures();
583
+ const results = [];
584
+ for (const raw of entries) {
585
+ const parsed = invalid.read(() => {
586
+ const item = record(raw);
587
+ const cve = string(item.cveID);
588
+ if (!/^CVE-\d{4}-\d{4,}$/i.test(cve))
589
+ throw new SourceError('Invalid CISA KEV identifier.');
590
+ const vendor = string(item.vendorProject);
591
+ const product = string(item.product);
592
+ const description = `${vendor} ${product}\n${string(item.shortDescription)}\nRequired action: ${string(item.requiredAction)}`;
593
+ const evidence = {
594
+ id: `kev:${cve.toUpperCase()}`,
595
+ source: 'kev',
596
+ kind: 'kev',
597
+ title: cleanText(string(item.vulnerabilityName), 500),
598
+ url: `https://www.cisa.gov/known-exploited-vulnerabilities-catalog?search_api_fulltext=${encodeURIComponent(cve)}`,
599
+ description: cleanText(description, 16_000),
600
+ aliases: aliases([cve]),
601
+ severity: 'unknown',
602
+ modified_at: released,
603
+ fetched_at: timestamp(now),
604
+ published_at: date(item.dateAdded),
605
+ packages: [],
606
+ exploited: true,
607
+ };
608
+ // KEV has a catalog release time, not entry modification times. An unchanged
609
+ // entry retains its content revision while fetched_at records this refresh.
610
+ const existing = old.get(evidence.id);
611
+ const content = (item) => hash([item.title, item.description, item.url, item.aliases, item.published_at, item.exploited]);
612
+ if (existing && content(existing) === content(evidence))
613
+ evidence.modified_at = existing.modified_at;
614
+ return evidence;
615
+ });
616
+ if (parsed)
617
+ results.push(parsed);
618
+ }
619
+ return invalid.finish('CISA KEV', results);
620
+ }
621
+ function xmlText(value) {
622
+ if (typeof value === 'string' || typeof value === 'number')
623
+ return String(value);
624
+ if (!value || typeof value !== 'object')
625
+ return '';
626
+ if (Array.isArray(value))
627
+ return value.map(xmlText).join(' ');
628
+ return Object.entries(value)
629
+ .filter(([key]) => !key.startsWith('@_') && !HIDDEN_HTML_ELEMENTS.has(key.toLowerCase()))
630
+ .map(([, child]) => xmlText(child))
631
+ .join(' ');
632
+ }
633
+ const HIDDEN_HTML_ELEMENTS = new Set(['script', 'style', 'template', 'noscript']);
634
+ const MAX_HTML_BYTES = 2_000_000;
635
+ const MAX_HTML_NODES = 100_000;
636
+ const MAX_HTML_DEPTH = 256;
637
+ function parseHtml(html, document = false) {
638
+ if (Buffer.byteLength(html) > MAX_HTML_BYTES)
639
+ throw new SourceError('HTML input exceeds the size limit.');
640
+ let nodes = 0;
641
+ let depth = 0;
642
+ const account = () => {
643
+ if (++nodes > MAX_HTML_NODES)
644
+ throw new SourceError('HTML structure exceeds the node limit.');
645
+ };
646
+ const treeAdapter = {
647
+ ...defaultTreeAdapter,
648
+ createDocument() {
649
+ account();
650
+ return defaultTreeAdapter.createDocument();
651
+ },
652
+ createDocumentFragment() {
653
+ account();
654
+ return defaultTreeAdapter.createDocumentFragment();
655
+ },
656
+ createElement(...args) {
657
+ account();
658
+ return defaultTreeAdapter.createElement(...args);
659
+ },
660
+ createCommentNode(...args) {
661
+ account();
662
+ return defaultTreeAdapter.createCommentNode(...args);
663
+ },
664
+ insertText(parent, text) {
665
+ if (parent.childNodes.at(-1)?.nodeName !== '#text')
666
+ account();
667
+ defaultTreeAdapter.insertText(parent, text);
668
+ },
669
+ insertTextBefore(parent, text, reference) {
670
+ if (parent.childNodes[parent.childNodes.indexOf(reference) - 1]?.nodeName !== '#text')
671
+ account();
672
+ defaultTreeAdapter.insertTextBefore(parent, text, reference);
673
+ },
674
+ onItemPush() {
675
+ if (++depth > MAX_HTML_DEPTH)
676
+ throw new SourceError('HTML structure exceeds the depth limit.');
677
+ },
678
+ onItemPop() {
679
+ depth--;
680
+ },
681
+ };
682
+ // parse5 builds an inert tree: it does not execute scripts or fetch resources.
683
+ return document
684
+ ? parse(html, { sourceCodeLocationInfo: true, scriptingEnabled: true, treeAdapter })
685
+ : parseFragment(html, { scriptingEnabled: true, treeAdapter });
686
+ }
687
+ function* visibleHtmlNodes(root) {
688
+ const pending = [{ node: root, depth: 0 }];
689
+ let visited = 0;
690
+ while (pending.length) {
691
+ const { node, depth } = pending.pop();
692
+ if (++visited > MAX_HTML_NODES || depth > MAX_HTML_DEPTH)
693
+ throw new SourceError('HTML structure exceeds the traversal limit.');
694
+ if (node.nodeName === '#comment' ||
695
+ ('tagName' in node && HIDDEN_HTML_ELEMENTS.has(node.tagName.toLowerCase())))
696
+ continue;
697
+ yield node;
698
+ if ('childNodes' in node) {
699
+ if (visited + pending.length + node.childNodes.length > MAX_HTML_NODES)
700
+ throw new SourceError('HTML structure exceeds the traversal limit.');
701
+ for (let index = node.childNodes.length - 1; index >= 0; index--)
702
+ pending.push({ node: node.childNodes[index], depth: depth + 1 });
703
+ }
704
+ }
705
+ }
706
+ function htmlText(root, limit = 16_000) {
707
+ const parts = [];
708
+ for (const node of visibleHtmlNodes(root))
709
+ if ('value' in node)
710
+ parts.push(node.value);
711
+ // Entity references have already been decoded once by the HTML parser.
712
+ return cleanText(parts.join(' ').replace(/\s+/g, ' ').trim(), limit);
713
+ }
714
+ function plainText(value, limit = 16_000) {
715
+ return htmlText(parseHtml(xmlText(value)), limit);
716
+ }
717
+ function list(value) {
718
+ return value === undefined ? [] : Array.isArray(value) ? value : [value];
719
+ }
720
+ function feedDate(value) {
721
+ const input = xmlText(value);
722
+ return input && Number.isFinite(Date.parse(input)) ? timestamp(Date.parse(input)) : undefined;
723
+ }
724
+ function newsWindow(source, checkpoint, lookbackMinutes, previous, inventory, now) {
725
+ const lookback = lookbackMinutes * 60_000;
726
+ const last = checkpoint === undefined ? now : Date.parse(checkpoint);
727
+ if (!Number.isFinite(last) || last > now)
728
+ throw new SourceError('Invalid news checkpoint; reset it before collecting.');
729
+ return {
730
+ // Revisit a small checkpoint overlap after an outage, even when the normal window is shorter.
731
+ cutoff: Math.max(0, Math.min(now - lookback, last - Math.min(5 * 60_000, lookback))),
732
+ tracked: new Set(previous
733
+ .filter((item) => item.source === source && item.kind === 'news' && evidenceRelevant(item, inventory))
734
+ .map((item) => item.id)),
735
+ previous: new Map(previous.filter((item) => item.source === source).map((item) => [item.id, item])),
736
+ };
737
+ }
738
+ function stabilizeUndated(result, previous) {
739
+ const content = (item) => hash([
740
+ item.title,
741
+ item.url,
742
+ item.description,
743
+ item.aliases,
744
+ item.severity,
745
+ item.published_at,
746
+ item.content_status,
747
+ ]);
748
+ for (const item of result.evidence) {
749
+ const old = previous.get(item.id);
750
+ if (result.undated.has(item.id) && old && content(old) === content(item))
751
+ item.modified_at = old.modified_at;
752
+ }
753
+ }
754
+ async function feed(url, source, http, now, window, entryLimit = MAX_FEED_ENTRIES) {
755
+ const response = await http(url, { maxBytes: 2_000_000 });
756
+ if (response.status !== 200)
757
+ throw new SourceError(`Source returned HTTP ${response.status}.`);
758
+ if (/<!\s*(?:DOCTYPE|ENTITY)\b/i.test(response.body))
759
+ throw new SourceError('Feed DTDs and entity declarations are not allowed.');
760
+ if (XMLValidator.validate(response.body) !== true)
761
+ throw new SourceError('Feed returned invalid XML.');
762
+ let parsed;
763
+ try {
764
+ parsed = record(new XMLParser({
765
+ ignoreAttributes: false,
766
+ processEntities: false,
767
+ parseTagValue: false,
768
+ parseAttributeValue: false,
769
+ removeNSPrefix: true,
770
+ }).parse(response.body));
771
+ }
772
+ catch {
773
+ throw new SourceError('Feed returned invalid XML.');
774
+ }
775
+ let entries;
776
+ if (parsed.rss !== undefined)
777
+ entries = list(record(record(parsed.rss).channel).item);
778
+ else if (parsed.feed !== undefined)
779
+ entries = list(record(parsed.feed).entry);
780
+ else
781
+ throw new SourceError('Unsupported feed format; RSS 2.0 or Atom is required.');
782
+ if (entries.length > entryLimit)
783
+ throw new SourceError('Feed entry limit reached; collection is incomplete.');
784
+ const fallback = new URL(url);
785
+ fallback.username = '';
786
+ fallback.password = '';
787
+ fallback.search = '';
788
+ fallback.hash = '';
789
+ const results = new Map();
790
+ const undated = new Set();
791
+ const invalid = new SourceItemFailures();
792
+ for (const rawEntry of entries) {
793
+ const parsed = invalid.read(() => {
794
+ const entry = record(rawEntry);
795
+ const title = plainText(entry.title, 500);
796
+ if (!title)
797
+ throw new SourceError('Feed entry is missing its title.');
798
+ const description = plainText(entry.encoded ?? entry.content ?? entry.description ?? entry.summary ?? '');
799
+ const links = list(entry.link);
800
+ const selectedLink = links.find((link) => typeof link === 'string' || !record(link)['@_rel'] || record(link)['@_rel'] === 'alternate');
801
+ const rawLink = typeof selectedLink === 'object' && selectedLink !== null
802
+ ? (record(selectedLink)['@_href'] ?? xmlText(selectedLink))
803
+ : selectedLink;
804
+ const link = publicUrl(rawLink, fallback.href);
805
+ const externalId = xmlText(entry.id ?? entry.guid).trim() || (link !== fallback.href ? link : '');
806
+ if (!externalId)
807
+ throw new SourceError('Feed entry is missing a stable ID or link.');
808
+ const published = feedDate(entry.published ?? entry.pubDate);
809
+ const sourceModified = feedDate(entry.updated) ?? published;
810
+ if ([sourceModified, published].some((value) => value && Date.parse(value) > now + 5 * 60_000))
811
+ throw new SourceError('Feed returned a future timestamp; collection is incomplete.');
812
+ const modified = sourceModified ?? timestamp(now);
813
+ const id = `${source}:entry:${hash(externalId).slice(0, 32)}`;
814
+ if (sourceModified && Date.parse(sourceModified) < window.cutoff && !window.tracked.has(id))
815
+ return undefined;
816
+ const foundAliases = `${title}\n${description}\n${link}`.match(/\b(?:CVE-\d{4}-\d{4,}|GHSA-[a-z\d]{4}-[a-z\d]{4}-[a-z\d]{4})\b/gi) ?? [];
817
+ const evidence = {
818
+ id,
819
+ source,
820
+ kind: 'news',
821
+ title,
822
+ url: link,
823
+ description,
824
+ aliases: aliases(foundAliases),
825
+ severity: severity(xmlText(entry.severity)),
826
+ modified_at: modified,
827
+ fetched_at: timestamp(now),
828
+ ...(published ? { published_at: published } : {}),
829
+ packages: [],
830
+ content_status: description ? 'excerpt' : 'unavailable',
831
+ };
832
+ return { evidence, dated: Boolean(sourceModified) };
833
+ });
834
+ if (!parsed)
835
+ continue;
836
+ const { evidence, dated } = parsed;
837
+ const id = evidence.id;
838
+ const modified = evidence.modified_at;
839
+ const old = results.get(id);
840
+ if (!old || Date.parse(modified) >= Date.parse(old.modified_at)) {
841
+ results.set(id, evidence);
842
+ if (dated)
843
+ undated.delete(id);
844
+ else
845
+ undated.add(id);
846
+ }
847
+ }
848
+ return { evidence: [...results.values()], undated, failure: invalid.message('Feed') };
849
+ }
850
+ function hackerNewsUrl(value) {
851
+ try {
852
+ const url = new URL(value);
853
+ if (url.protocol !== 'https:' ||
854
+ url.username ||
855
+ url.password ||
856
+ url.port ||
857
+ !['thehackernews.com', 'www.thehackernews.com'].includes(url.hostname) ||
858
+ !/^\/\d{4}\/\d{2}\/[^/]+\.html$/.test(url.pathname))
859
+ return undefined;
860
+ url.hash = '';
861
+ url.search = '';
862
+ return url.href;
863
+ }
864
+ catch {
865
+ return undefined;
866
+ }
867
+ }
868
+ /** Extract only the marked article body, never navigation/related-story text.
869
+ * Missing or malformed wrappers leave the feed excerpt explicitly incomplete. */
870
+ function articleBody(html) {
871
+ for (const node of visibleHtmlNodes(parseHtml(html, true))) {
872
+ if (!('tagName' in node) ||
873
+ node.namespaceURI !== 'http://www.w3.org/1999/xhtml' ||
874
+ !['div', 'article', 'section'].includes(node.tagName))
875
+ continue;
876
+ const attributes = new Map(node.attrs.map(({ name, value }) => [name, value]));
877
+ if (!(attributes.get('itemprop') ?? '').split(/\s+/).includes('articleBody') &&
878
+ !(attributes.get('class') ?? '')
879
+ .split(/\s+/)
880
+ .some((value) => ['articlebody', 'post-body'].includes(value)))
881
+ continue;
882
+ // Parser recovery can create or implicitly close nodes. Only an explicit
883
+ // source wrapper establishes that the complete article body was received.
884
+ return node.sourceCodeLocation?.startTag && node.sourceCodeLocation.endTag ? node : undefined;
885
+ }
886
+ return undefined;
887
+ }
888
+ async function hackerNews(http, now, window) {
889
+ const result = await feed(HACKER_NEWS, 'hacker_news', http, now, window);
890
+ const entries = result.evidence;
891
+ // RSS is a finite current window. Articles outside the fetch budget remain
892
+ // visible as excerpts; models cannot use them as complete dismissal evidence.
893
+ for (let offset = 0; offset < Math.min(entries.length, 50); offset += 4)
894
+ await Promise.all(entries.slice(offset, Math.min(offset + 4, 50)).map(async (entry) => {
895
+ const url = hackerNewsUrl(entry.url);
896
+ if (!url)
897
+ return;
898
+ try {
899
+ const response = await http(url, {
900
+ maxBytes: 2_000_000,
901
+ redirects: 3,
902
+ allowedRedirectOrigins: ['https://thehackernews.com', 'https://www.thehackernews.com'],
903
+ });
904
+ if (response.status !== 200)
905
+ return;
906
+ const body = articleBody(response.body);
907
+ if (!body)
908
+ return;
909
+ const full = htmlText(body, 16_001);
910
+ if (!full || full.length < entry.description.length)
911
+ return;
912
+ entry.description = full.slice(0, 16_000);
913
+ entry.content_status = full.length <= 16_000 ? 'full' : 'excerpt';
914
+ entry.url = url;
915
+ entry.aliases = aliases(`${entry.title}\n${entry.description}`.match(/\b(?:CVE-\d{4}-\d{4,}|GHSA-[a-z\d]{4}-[a-z\d]{4}-[a-z\d]{4})\b/gi) ?? []);
916
+ }
917
+ catch (error) {
918
+ if (sourceCanceled(error))
919
+ throw error;
920
+ // Fetch/parse failures must not erase the headline and feed excerpt.
921
+ // No transport exception text is persisted or exposed to model prompts.
922
+ }
923
+ }));
924
+ stabilizeUndated(result, window.previous);
925
+ return result;
926
+ }
927
+ async function vendorFeed(vendor, http, now, window) {
928
+ const profile = VENDOR_FEEDS[vendor];
929
+ // PHP's feed includes years of release history.
930
+ // Keep its larger item allowance separate from generic feeds and the shared 2 MB cap.
931
+ const result = await feed(profile.feed, `vendor:${vendor}`, http, now, window, vendor === 'php' ? 2000 : MAX_FEED_ENTRIES);
932
+ const entries = result.evidence.slice(0, 20);
933
+ for (let offset = 0; offset < entries.length; offset += 4)
934
+ await Promise.all(entries.slice(offset, offset + 4).map(async (entry) => {
935
+ const target = vendorArticleTarget(vendor, entry.url);
936
+ if (!target)
937
+ return;
938
+ try {
939
+ const response = await http(target.url, {
940
+ maxBytes: MAX_HTML_BYTES,
941
+ timeoutMs: 15_000,
942
+ minIntervalMs: 500,
943
+ redirects: 3,
944
+ allowedRedirectOrigins: [profile.origin],
945
+ headers: { accept: 'text/html' },
946
+ });
947
+ if (response.status !== 200)
948
+ return;
949
+ const body = vendorArticleBody(vendor, visibleHtmlNodes(parseHtml(response.body, true)), target.anchor);
950
+ if (!body)
951
+ return;
952
+ const text = htmlText(body, 16_001);
953
+ const normalize = (value) => value.replace(/\s+/g, ' ').trim().toLowerCase();
954
+ // A complete wrapper on an unrelated redirect/error page is not the requested article.
955
+ const visible = normalize(text);
956
+ const title = normalize(entry.title);
957
+ if (!visible.includes(title) || visible.replaceAll(title, '').trim().length < 40)
958
+ return;
959
+ entry.description = text.slice(0, 16_000);
960
+ entry.content_status = text.length <= 16_000 ? 'full' : 'excerpt';
961
+ entry.aliases = aliases(`${entry.title}\n${entry.description}`.match(/\b(?:CVE-\d{4}-\d{4,}|GHSA-[a-z\d]{4}-[a-z\d]{4}-[a-z\d]{4})\b/gi) ?? []);
962
+ }
963
+ catch (error) {
964
+ if (sourceCanceled(error))
965
+ throw error;
966
+ // Keep the validated feed excerpt when the vendor page cannot be read safely.
967
+ }
968
+ }));
969
+ stabilizeUndated(result, window.previous);
970
+ return result;
971
+ }
972
+ /** Collect source evidence and report failures without advancing failed sources' checkpoints. */
973
+ export async function collectSources(inventory, config, checkpoints, http, now = Date.now(), previousEvidence = []) {
974
+ const result = { evidence: [], errors: [], checkpoints: { ...checkpoints } };
975
+ const jobs = [];
976
+ const window = (source) => newsWindow(source, checkpoints[source], config.news_lookback_minutes ?? 60, previousEvidence, inventory, now);
977
+ if (config.sources.hacker_news)
978
+ jobs.push({ source: 'hacker_news', run: () => hackerNews(http, now, window('hacker_news')) });
979
+ if (config.sources.osv)
980
+ jobs.push({ source: 'osv', run: () => osv(inventory, previousEvidence, http, now) });
981
+ if (config.sources.github)
982
+ for (const type of ['reviewed', 'malware'])
983
+ jobs.push({
984
+ source: `github:${type}`,
985
+ run: () => github(type, checkpoints[`github:${type}`], config, http, now),
986
+ });
987
+ if (config.sources.kev)
988
+ jobs.push({ source: 'kev', run: () => kev(http, now, previousEvidence) });
989
+ for (const vendor of new Set(config.sources.vendor_feeds ?? [])) {
990
+ const source = `vendor:${vendor}`;
991
+ jobs.push({ source, run: () => vendorFeed(vendor, http, now, window(source)) });
992
+ }
993
+ for (const url of new Set(config.sources.feeds)) {
994
+ const source = `feed:${hash(url).slice(0, 16)}`;
995
+ jobs.push({
996
+ source,
997
+ run: async () => {
998
+ const current = window(source);
999
+ const result = await feed(url, source, http, now, current);
1000
+ stabilizeUndated(result, current.previous);
1001
+ return result;
1002
+ },
1003
+ });
1004
+ }
1005
+ if (config.sources.cve_now)
1006
+ jobs.push({
1007
+ source: 'cve_now',
1008
+ run: () => collectCveNow(inventory, checkpoints.cve_now, previousEvidence, result.evidence, http, now),
1009
+ });
1010
+ for (const job of jobs) {
1011
+ let collected = [];
1012
+ let failure;
1013
+ let incomplete = false;
1014
+ try {
1015
+ collected = await job.run();
1016
+ if (!Array.isArray(collected) && collected.failure) {
1017
+ failure = new SourceError(collected.failure);
1018
+ incomplete = true;
1019
+ }
1020
+ }
1021
+ catch (error) {
1022
+ if (sourceCanceled(error))
1023
+ throw error;
1024
+ failure = error;
1025
+ incomplete = true;
1026
+ if (error instanceof PartialSourceError)
1027
+ collected = error.evidence;
1028
+ }
1029
+ const evidence = (Array.isArray(collected) ? collected : collected.evidence).filter((item) => {
1030
+ const modified = Date.parse(item.modified_at);
1031
+ if (Number.isFinite(modified) && modified <= now + 5 * 60_000)
1032
+ return true;
1033
+ failure ??= new SourceError('Source returned an invalid or future modification timestamp; collection is incomplete.');
1034
+ incomplete = true;
1035
+ return false;
1036
+ });
1037
+ result.evidence.push(...evidence);
1038
+ if (!incomplete)
1039
+ result.checkpoints[job.source] = timestamp(now);
1040
+ if (!Array.isArray(collected) && collected.undated.size)
1041
+ result.errors.push({
1042
+ source: `${job.source}:timestamps`,
1043
+ 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.`,
1044
+ });
1045
+ if (job.source === 'hacker_news') {
1046
+ const missing = evidence.filter((item) => item.content_status !== 'full' && evidenceRelevant(item, inventory)).length;
1047
+ if (missing)
1048
+ result.errors.push({
1049
+ source: 'hacker_news:articles',
1050
+ message: `${missing} relevant The Hacker News article(s) could not be read in full; excerpts remain available for cautious review.`,
1051
+ });
1052
+ }
1053
+ if (job.source.startsWith('vendor:')) {
1054
+ const missing = evidence.filter((item) => item.content_status !== 'full' && evidenceRelevant(item, inventory)).length;
1055
+ if (missing)
1056
+ result.errors.push({
1057
+ source: `${job.source}:articles`,
1058
+ message: `${missing} relevant vendor article(s) could not be read in full; excerpts remain available for cautious review.`,
1059
+ });
1060
+ }
1061
+ if (incomplete)
1062
+ result.errors.push({
1063
+ source: job.source,
1064
+ // Transport errors can contain feed tokens or HTTP headers.
1065
+ message: failure instanceof SourceError
1066
+ ? failure.message
1067
+ : 'Source request failed; cached evidence was retained and its checkpoint was not advanced.',
1068
+ });
1069
+ }
1070
+ return result;
1071
+ }