@shieldaai/security-watch 0.1.0-alpha.0 → 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.
Files changed (92) hide show
  1. package/CHANGELOG.md +170 -0
  2. package/CONTRIBUTING.md +4 -2
  3. package/README.md +173 -48
  4. package/SECURITY.md +24 -9
  5. package/dist/assessment.d.ts +12 -1
  6. package/dist/assessment.js +223 -52
  7. package/dist/cli.js +340 -27
  8. package/dist/config.d.ts +62 -2
  9. package/dist/config.js +88 -5
  10. package/dist/coverage.d.ts +4 -0
  11. package/dist/coverage.js +11 -0
  12. package/dist/cve-now.d.ts +32 -2
  13. package/dist/cve-now.js +715 -126
  14. package/dist/cvss4.d.ts +3 -0
  15. package/dist/cvss4.js +39 -0
  16. package/dist/delivery.d.ts +34 -2
  17. package/dist/delivery.js +391 -98
  18. package/dist/ecosystems.d.ts +23 -0
  19. package/dist/ecosystems.js +88 -10
  20. package/dist/engine.d.ts +55 -1
  21. package/dist/engine.js +101 -20
  22. package/dist/everyday-words.d.ts +11 -0
  23. package/dist/everyday-words.js +256 -0
  24. package/dist/health.d.ts +7 -0
  25. package/dist/health.js +55 -3
  26. package/dist/http.d.ts +7 -0
  27. package/dist/http.js +31 -2
  28. package/dist/index.d.ts +22 -4
  29. package/dist/index.js +12 -4
  30. package/dist/inventory-evidence.d.ts +10 -0
  31. package/dist/inventory-evidence.js +206 -0
  32. package/dist/inventory.d.ts +273 -0
  33. package/dist/inventory.js +210 -17
  34. package/dist/maintenance.d.ts +5 -0
  35. package/dist/maintenance.js +73 -5
  36. package/dist/matching.d.ts +29 -0
  37. package/dist/matching.js +537 -0
  38. package/dist/models.d.ts +17 -4
  39. package/dist/models.js +359 -29
  40. package/dist/pilot-cases.d.ts +171 -0
  41. package/dist/pilot-cases.js +330 -0
  42. package/dist/pilot-input.d.ts +16 -0
  43. package/dist/pilot-input.js +125 -0
  44. package/dist/pilot-recall.d.ts +166 -0
  45. package/dist/pilot-recall.js +231 -0
  46. package/dist/pilot-report.d.ts +113 -0
  47. package/dist/pilot-report.js +279 -0
  48. package/dist/pilot-responses.d.ts +111 -0
  49. package/dist/pilot-responses.js +159 -0
  50. package/dist/python-version.d.ts +3 -0
  51. package/dist/python-version.js +30 -0
  52. package/dist/rehearsal.d.ts +440 -0
  53. package/dist/rehearsal.js +372 -0
  54. package/dist/sbom.d.ts +13 -0
  55. package/dist/sbom.js +193 -0
  56. package/dist/source-error.d.ts +17 -1
  57. package/dist/source-error.js +18 -3
  58. package/dist/sources.d.ts +2 -2
  59. package/dist/sources.js +699 -45
  60. package/dist/store.d.ts +38 -13
  61. package/dist/store.js +325 -23
  62. package/dist/types.d.ts +159 -2
  63. package/dist/util.d.ts +23 -0
  64. package/dist/util.js +81 -1
  65. package/dist/vendor/cvss4-reference.d.ts +2 -0
  66. package/dist/vendor/cvss4-reference.js +789 -0
  67. package/dist/word-filter.d.ts +3 -0
  68. package/dist/word-filter.js +3291 -0
  69. package/docs/alert-outcome-evaluation.md +150 -0
  70. package/docs/compatibility.md +35 -0
  71. package/docs/configuration.md +289 -29
  72. package/docs/cvss-v4-support.md +41 -0
  73. package/docs/offline-advisory-preview.md +114 -0
  74. package/docs/offline-rehearsal.md +44 -0
  75. package/docs/pilot-cases.md +58 -0
  76. package/docs/pilot-recall.md +124 -0
  77. package/docs/pilot-report.md +52 -0
  78. package/docs/validation/alert-outcome-evaluation-2026-11-05.json +2935 -0
  79. package/docs/validation/cvss-v4-reference-parity-2026-11-05.json +93 -0
  80. package/docs/validation/rehearsal-accepted-2026-11-05.json +175 -0
  81. package/docs/validation/rehearsal-unknown-2026-11-05.json +175 -0
  82. package/docs/vendor/cvss-v4-LICENSE.txt +22 -0
  83. package/docs/vendor/cvss-v4-provenance.json +38 -0
  84. package/examples/agent-advisories-2026.json +145 -0
  85. package/examples/agent-advisory-cases-2026.json +397 -0
  86. package/examples/libraries.example.txt +4 -2
  87. package/examples/libraries.example.yaml +2 -0
  88. package/examples/offline-advisory-preview.mjs +42 -0
  89. package/examples/rehearsal.json +75 -0
  90. package/examples/systems.example.yaml +4 -0
  91. package/package.json +23 -7
  92. package/docs/quality-review.md +0 -104
package/dist/sources.js CHANGED
@@ -1,7 +1,8 @@
1
1
  import { XMLParser, XMLValidator } from 'fast-xml-parser';
2
2
  import { defaultTreeAdapter, parse, parseFragment } from 'parse5';
3
3
  import { compare, valid } from 'semver';
4
- import { cleanText, hash, highest, timestamp } from './util.js';
4
+ import { cvssV4BaseScore } from './cvss4.js';
5
+ import { cleanText, hash, highest, singleLine, timestamp } from './util.js';
5
6
  import { collectCveNow, evidenceRelevant } from './cve-now.js';
6
7
  import { VENDOR_FEEDS, vendorArticleBody, vendorArticleTarget } from './vendor-sources.js';
7
8
  import { exactLibraryVersion, normalizeEcosystem, normalizePackageName, osvPackageNames, samePackage, } from './ecosystems.js';
@@ -13,7 +14,20 @@ const HACKER_NEWS = 'https://feeds.feedburner.com/TheHackersNews';
13
14
  const MAX_PAGES = 50;
14
15
  const MAX_ADVISORIES = 5_000;
15
16
  const MAX_FEED_ENTRIES = 500;
17
+ const LATE_ENTRY_DAYS = 7;
16
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;
17
31
  function record(value) {
18
32
  if (!value || typeof value !== 'object' || Array.isArray(value))
19
33
  throw new SourceError('Invalid source schema.');
@@ -42,6 +56,16 @@ function date(value) {
42
56
  throw new SourceError('Invalid source date.');
43
57
  return new Date(input).toISOString();
44
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
+ }
45
69
  function aliases(values) {
46
70
  return [
47
71
  ...new Set(values
@@ -115,6 +139,31 @@ function vectorSeverity(vector) {
115
139
  const rounded = integer % 10_000 === 0 ? integer / 100_000 : (Math.floor(integer / 10_000) + 1) / 10;
116
140
  return scoreSeverity(rounded);
117
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
+ }
118
167
  function optionalRecord(value) {
119
168
  return value === undefined || value === null ? {} : record(value);
120
169
  }
@@ -159,7 +208,9 @@ function sourcePackage(ecosystem, name) {
159
208
  return { ecosystem: normalized, name: normalizePackageName(normalized, name) };
160
209
  }
161
210
  catch {
162
- throw new SourceError('Source returned an invalid package identity.');
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 };
163
214
  }
164
215
  }
165
216
  function osvRanges(value) {
@@ -231,9 +282,12 @@ function osvRecord(raw, expectedId, matches, now) {
231
282
  if (string(data.id) !== expectedId)
232
283
  throw new SourceError('OSV returned a mismatched advisory ID.');
233
284
  const packageClaims = [];
285
+ const vectors = vectorCollector();
234
286
  const severities = [severity(optionalRecord(data.database_specific).severity)];
235
- for (const rawSeverity of array(data.severity, true))
236
- severities.push(vectorSeverity(record(rawSeverity).score));
287
+ for (const rawSeverity of array(data.severity, true)) {
288
+ const item = record(rawSeverity);
289
+ severities.push(vectors.score(item.score, item.type));
290
+ }
237
291
  for (const rawAffected of array(data.affected, true)) {
238
292
  const affected = record(rawAffected);
239
293
  // OSV can include a separate Git-only entry beside registry package entries.
@@ -259,8 +313,10 @@ function osvRecord(raw, expectedId, matches, now) {
259
313
  ];
260
314
  const fixed = array(affected.ranges, true)
261
315
  .flatMap((rawRange) => array(record(rawRange).events, true))
262
- .map((rawEvent) => optionalString(record(rawEvent).fixed))
263
- .filter((v) => !!v);
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);
264
320
  packageClaims.push({
265
321
  ecosystem,
266
322
  name,
@@ -270,8 +326,10 @@ function osvRecord(raw, expectedId, matches, now) {
270
326
  ...(fixed.length ? { fixed: [...new Set(fixed)].join(', ') } : {}),
271
327
  });
272
328
  severities.push(severity(optionalRecord(affected.database_specific).severity));
273
- for (const rawSeverity of array(affected.severity, true))
274
- severities.push(vectorSeverity(record(rawSeverity).score));
329
+ for (const rawSeverity of array(affected.severity, true)) {
330
+ const item = record(rawSeverity);
331
+ severities.push(vectors.score(item.score, item.type));
332
+ }
275
333
  }
276
334
  // Queries identify the package even when details omit it. Only a versioned query proves impact.
277
335
  for (const query of matches)
@@ -298,6 +356,7 @@ function osvRecord(raw, expectedId, matches, now) {
298
356
  description: cleanText(optionalString(data.details) ?? optionalString(data.summary) ?? expectedId, 16_000),
299
357
  aliases: aliases([expectedId, ...aliasStrings(data.aliases)]),
300
358
  severity: highest(...severities),
359
+ ...vectors.details(),
301
360
  modified_at: date(data.modified),
302
361
  fetched_at: timestamp(now),
303
362
  ...(data.published ? { published_at: date(data.published) } : {}),
@@ -394,8 +453,13 @@ async function osv(inventory, previous, http, now) {
394
453
  }
395
454
  }
396
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()));
397
459
  for (const item of previous)
398
- if (item.source === 'osv' && item.id.startsWith('osv:'))
460
+ if (item.source === 'osv' &&
461
+ item.id.startsWith('osv:') &&
462
+ (item.packages ?? []).some((claim) => names.has(claim.name.toLowerCase())))
399
463
  ids.add(item.id.slice(4));
400
464
  if (ids.size > MAX_ADVISORIES)
401
465
  throw new SourceError('OSV historical advisory limit reached; collection is incomplete.');
@@ -403,16 +467,27 @@ async function osv(inventory, previous, http, now) {
403
467
  const allIds = [...ids];
404
468
  let failures = 0;
405
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]));
406
476
  for (let index = 0; index < allIds.length; index += 4) {
407
477
  const batch = allIds.slice(index, index + 4);
408
478
  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));
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));
411
481
  if (canceled)
412
482
  throw canceled.reason;
413
- for (const item of settled) {
483
+ for (const [position, item] of settled.entries()) {
414
484
  if (item.status === 'fulfilled')
415
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
+ }
416
491
  else {
417
492
  failures++;
418
493
  firstFailure ??=
@@ -432,10 +507,46 @@ async function osv(inventory, previous, http, now) {
432
507
  throwSourceFailure(error, results);
433
508
  }
434
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
+ }
435
546
  function githubRecord(raw, type, now) {
436
547
  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))
548
+ const id = githubIdentifier(data);
549
+ if (!id)
439
550
  throw new SourceError('Invalid GitHub advisory identifier.');
440
551
  if (data.type !== undefined && data.type !== type)
441
552
  throw new SourceError('GitHub returned an unexpected advisory type.');
@@ -447,9 +558,9 @@ function githubRecord(raw, type, now) {
447
558
  const pkg = record(vulnerability.package);
448
559
  const range = optionalString(vulnerability.vulnerable_version_range);
449
560
  const patched = vulnerability.first_patched_version;
450
- const fixed = typeof patched === 'object' && patched !== null
561
+ const fixed = singleLine((typeof patched === 'object' && patched !== null
451
562
  ? optionalString(record(patched).identifier)
452
- : optionalString(patched);
563
+ : optionalString(patched)) ?? '');
453
564
  return {
454
565
  ...sourcePackage(string(pkg.ecosystem), string(pkg.name)),
455
566
  ...(range ? { range } : {}),
@@ -458,10 +569,14 @@ function githubRecord(raw, type, now) {
458
569
  });
459
570
  const cvss = optionalRecord(data.cvss);
460
571
  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));
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
+ }
465
580
  return {
466
581
  id: `github:${id}`,
467
582
  source: `github:${type}`,
@@ -475,6 +590,7 @@ function githubRecord(raw, type, now) {
475
590
  ...array(data.identifiers, true).map((item) => string(record(item).value)),
476
591
  ]),
477
592
  severity: highest(...ratings),
593
+ ...vectors.details(),
478
594
  modified_at: modified,
479
595
  fetched_at: timestamp(now),
480
596
  published_at: date(data.published_at),
@@ -509,11 +625,30 @@ function nextGithubLink(link) {
509
625
  }
510
626
  return undefined;
511
627
  }
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)
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))
515
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;
516
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);
517
652
  const url = new URL(GITHUB);
518
653
  url.searchParams.set('type', type);
519
654
  // GitHub's search-date parser rejects fractional seconds, unlike checkpoint timestamps.
@@ -533,10 +668,297 @@ async function github(type, checkpoint, config, http, now) {
533
668
  const seen = new Set();
534
669
  const evidence = new Map();
535
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
+ };
536
950
  try {
537
951
  for (let page = 0; next; page++) {
538
- if (page >= MAX_PAGES)
539
- throw new SourceError('GitHub pagination limit reached; collection is incomplete.');
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
+ }
540
962
  if (seen.has(next))
541
963
  throw new SourceError('GitHub returned repeated pagination.');
542
964
  seen.add(next);
@@ -554,14 +976,131 @@ async function github(type, checkpoint, config, http, now) {
554
976
  if (items.length > 100)
555
977
  throw new SourceError('GitHub returned more records than the requested page limit.');
556
978
  for (const item of items) {
557
- const parsed = invalid.read(() => githubRecord(item, type, now));
558
- if (parsed)
559
- retainNewest(evidence, parsed);
979
+ rows++;
980
+ const updated = updatedAt(item);
981
+ if (Number.isFinite(updated))
982
+ reachedRow = Math.max(reachedRow, updated);
983
+ if (read(item))
984
+ readableRows++;
560
985
  }
561
986
  const link = Object.entries(response.headers).find(([key]) => key.toLowerCase() === 'link')?.[1];
562
987
  next = nextGithubLink(link);
563
988
  }
564
- return invalid.finish('GitHub', [...evidence.values()]);
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()];
565
1104
  }
566
1105
  catch (error) {
567
1106
  throwSourceFailure(error, [...evidence.values()]);
@@ -721,7 +1260,20 @@ function feedDate(value) {
721
1260
  const input = xmlText(value);
722
1261
  return input && Number.isFinite(Date.parse(input)) ? timestamp(Date.parse(input)) : undefined;
723
1262
  }
724
- function newsWindow(source, checkpoint, lookbackMinutes, previous, inventory, now) {
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) {
725
1277
  const lookback = lookbackMinutes * 60_000;
726
1278
  const last = checkpoint === undefined ? now : Date.parse(checkpoint);
727
1279
  if (!Number.isFinite(last) || last > now)
@@ -729,6 +1281,8 @@ function newsWindow(source, checkpoint, lookbackMinutes, previous, inventory, no
729
1281
  return {
730
1282
  // Revisit a small checkpoint overlap after an outage, even when the normal window is shorter.
731
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),
732
1286
  tracked: new Set(previous
733
1287
  .filter((item) => item.source === source && item.kind === 'news' && evidenceRelevant(item, inventory))
734
1288
  .map((item) => item.id)),
@@ -788,6 +1342,7 @@ async function feed(url, source, http, now, window, entryLimit = MAX_FEED_ENTRIE
788
1342
  fallback.hash = '';
789
1343
  const results = new Map();
790
1344
  const undated = new Set();
1345
+ const listed = [];
791
1346
  const invalid = new SourceItemFailures();
792
1347
  for (const rawEntry of entries) {
793
1348
  const parsed = invalid.read(() => {
@@ -811,9 +1366,18 @@ async function feed(url, source, http, now, window, entryLimit = MAX_FEED_ENTRIE
811
1366
  throw new SourceError('Feed returned a future timestamp; collection is incomplete.');
812
1367
  const modified = sourceModified ?? timestamp(now);
813
1368
  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) ?? [];
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
+ }
817
1381
  const evidence = {
818
1382
  id,
819
1383
  source,
@@ -821,7 +1385,7 @@ async function feed(url, source, http, now, window, entryLimit = MAX_FEED_ENTRIE
821
1385
  title,
822
1386
  url: link,
823
1387
  description,
824
- aliases: aliases(foundAliases),
1388
+ aliases: citedIdentifiers(`${title}\n${description}\n${link}`),
825
1389
  severity: severity(xmlText(entry.severity)),
826
1390
  modified_at: modified,
827
1391
  fetched_at: timestamp(now),
@@ -845,7 +1409,7 @@ async function feed(url, source, http, now, window, entryLimit = MAX_FEED_ENTRIE
845
1409
  undated.add(id);
846
1410
  }
847
1411
  }
848
- return { evidence: [...results.values()], undated, failure: invalid.message('Feed') };
1412
+ return { evidence: [...results.values()], undated, listed, failure: invalid.message('Feed') };
849
1413
  }
850
1414
  function hackerNewsUrl(value) {
851
1415
  try {
@@ -912,7 +1476,7 @@ async function hackerNews(http, now, window) {
912
1476
  entry.description = full.slice(0, 16_000);
913
1477
  entry.content_status = full.length <= 16_000 ? 'full' : 'excerpt';
914
1478
  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) ?? []);
1479
+ entry.aliases = citedIdentifiers(`${entry.title}\n${entry.description}`);
916
1480
  }
917
1481
  catch (error) {
918
1482
  if (sourceCanceled(error))
@@ -958,7 +1522,7 @@ async function vendorFeed(vendor, http, now, window) {
958
1522
  return;
959
1523
  entry.description = text.slice(0, 16_000);
960
1524
  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) ?? []);
1525
+ entry.aliases = citedIdentifiers(`${entry.title}\n${entry.description}`);
962
1526
  }
963
1527
  catch (error) {
964
1528
  if (sourceCanceled(error))
@@ -970,20 +1534,28 @@ async function vendorFeed(vendor, http, now, window) {
970
1534
  return result;
971
1535
  }
972
1536
  /** 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 } };
1537
+ export async function collectSources(inventory, config, checkpoints, http, now = Date.now(), previousEvidence = [], previousCoverage = []) {
1538
+ const result = { evidence: [], errors: [], checkpoints: { ...checkpoints }, coverage: [] };
975
1539
  const jobs = [];
976
- const window = (source) => newsWindow(source, checkpoints[source], config.news_lookback_minutes ?? 60, previousEvidence, inventory, now);
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);
977
1545
  if (config.sources.hacker_news)
978
1546
  jobs.push({ source: 'hacker_news', run: () => hackerNews(http, now, window('hacker_news')) });
979
1547
  if (config.sources.osv)
980
1548
  jobs.push({ source: 'osv', run: () => osv(inventory, previousEvidence, http, now) });
981
1549
  if (config.sources.github)
982
- for (const type of ['reviewed', 'malware'])
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`];
983
1554
  jobs.push({
984
1555
  source: `github:${type}`,
985
- run: () => github(type, checkpoints[`github:${type}`], config, http, now),
1556
+ run: () => github(type, checkpoints[`github:${type}`], config, http, now, inventory, previousEvidence, checkpoints[`github:${type}:since`], githubUnreadable[type]),
986
1557
  });
1558
+ }
987
1559
  if (config.sources.kev)
988
1560
  jobs.push({ source: 'kev', run: () => kev(http, now, previousEvidence) });
989
1561
  for (const vendor of new Set(config.sources.vendor_feeds ?? [])) {
@@ -1002,15 +1574,24 @@ export async function collectSources(inventory, config, checkpoints, http, now =
1002
1574
  },
1003
1575
  });
1004
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
+ };
1005
1584
  if (config.sources.cve_now)
1006
1585
  jobs.push({
1007
1586
  source: 'cve_now',
1008
- run: () => collectCveNow(inventory, checkpoints.cve_now, previousEvidence, result.evidence, http, now),
1587
+ run: () => collectCveNow(inventory, checkpoints.cve_now, previousEvidence, result.evidence, http, now, cveNowState),
1009
1588
  });
1010
1589
  for (const job of jobs) {
1590
+ const errorStart = result.errors.length;
1011
1591
  let collected = [];
1012
1592
  let failure;
1013
1593
  let incomplete = false;
1594
+ let packageResults;
1014
1595
  try {
1015
1596
  collected = await job.run();
1016
1597
  if (!Array.isArray(collected) && collected.failure) {
@@ -1023,20 +1604,59 @@ export async function collectSources(inventory, config, checkpoints, http, now =
1023
1604
  throw error;
1024
1605
  failure = error;
1025
1606
  incomplete = true;
1026
- if (error instanceof PartialSourceError)
1607
+ if (error instanceof PartialSourceError) {
1027
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;
1028
1638
  }
1639
+ if (job.source === 'cve_now' && cveNowState.nextRefusedSince !== undefined)
1640
+ result.checkpoints['cve_now:refused_since'] = String(cveNowState.nextRefusedSince ?? '');
1029
1641
  const evidence = (Array.isArray(collected) ? collected : collected.evidence).filter((item) => {
1030
1642
  const modified = Date.parse(item.modified_at);
1031
1643
  if (Number.isFinite(modified) && modified <= now + 5 * 60_000)
1032
1644
  return true;
1033
1645
  failure ??= new SourceError('Source returned an invalid or future modification timestamp; collection is incomplete.');
1034
1646
  incomplete = true;
1647
+ // The record left out here may be one for an inventory package.
1648
+ packageResults = undefined;
1035
1649
  return false;
1036
1650
  });
1037
1651
  result.evidence.push(...evidence);
1038
- if (!incomplete)
1652
+ if (!incomplete) {
1039
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));
1040
1660
  if (!Array.isArray(collected) && collected.undated.size)
1041
1661
  result.errors.push({
1042
1662
  source: `${job.source}:timestamps`,
@@ -1066,6 +1686,40 @@ export async function collectSources(inventory, config, checkpoints, http, now =
1066
1686
  ? failure.message
1067
1687
  : 'Source request failed; cached evidence was retained and its checkpoint was not advanced.',
1068
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
+ });
1069
1723
  }
1070
1724
  return result;
1071
1725
  }