@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.
- package/CHANGELOG.md +170 -0
- package/CONTRIBUTING.md +4 -2
- package/README.md +173 -48
- package/SECURITY.md +24 -9
- package/dist/assessment.d.ts +12 -1
- package/dist/assessment.js +223 -52
- package/dist/cli.js +340 -27
- package/dist/config.d.ts +62 -2
- package/dist/config.js +88 -5
- package/dist/coverage.d.ts +4 -0
- package/dist/coverage.js +11 -0
- package/dist/cve-now.d.ts +32 -2
- package/dist/cve-now.js +715 -126
- package/dist/cvss4.d.ts +3 -0
- package/dist/cvss4.js +39 -0
- package/dist/delivery.d.ts +34 -2
- package/dist/delivery.js +391 -98
- package/dist/ecosystems.d.ts +23 -0
- package/dist/ecosystems.js +88 -10
- package/dist/engine.d.ts +55 -1
- package/dist/engine.js +101 -20
- package/dist/everyday-words.d.ts +11 -0
- package/dist/everyday-words.js +256 -0
- package/dist/health.d.ts +7 -0
- package/dist/health.js +55 -3
- package/dist/http.d.ts +7 -0
- package/dist/http.js +31 -2
- package/dist/index.d.ts +22 -4
- package/dist/index.js +12 -4
- package/dist/inventory-evidence.d.ts +10 -0
- package/dist/inventory-evidence.js +206 -0
- package/dist/inventory.d.ts +273 -0
- package/dist/inventory.js +210 -17
- package/dist/maintenance.d.ts +5 -0
- package/dist/maintenance.js +73 -5
- package/dist/matching.d.ts +29 -0
- package/dist/matching.js +537 -0
- package/dist/models.d.ts +17 -4
- package/dist/models.js +359 -29
- package/dist/pilot-cases.d.ts +171 -0
- package/dist/pilot-cases.js +330 -0
- package/dist/pilot-input.d.ts +16 -0
- package/dist/pilot-input.js +125 -0
- package/dist/pilot-recall.d.ts +166 -0
- package/dist/pilot-recall.js +231 -0
- package/dist/pilot-report.d.ts +113 -0
- package/dist/pilot-report.js +279 -0
- package/dist/pilot-responses.d.ts +111 -0
- package/dist/pilot-responses.js +159 -0
- package/dist/python-version.d.ts +3 -0
- package/dist/python-version.js +30 -0
- package/dist/rehearsal.d.ts +440 -0
- package/dist/rehearsal.js +372 -0
- package/dist/sbom.d.ts +13 -0
- package/dist/sbom.js +193 -0
- package/dist/source-error.d.ts +17 -1
- package/dist/source-error.js +18 -3
- package/dist/sources.d.ts +2 -2
- package/dist/sources.js +699 -45
- package/dist/store.d.ts +38 -13
- package/dist/store.js +325 -23
- package/dist/types.d.ts +159 -2
- package/dist/util.d.ts +23 -0
- package/dist/util.js +81 -1
- package/dist/vendor/cvss4-reference.d.ts +2 -0
- package/dist/vendor/cvss4-reference.js +789 -0
- package/dist/word-filter.d.ts +3 -0
- package/dist/word-filter.js +3291 -0
- package/docs/alert-outcome-evaluation.md +150 -0
- package/docs/compatibility.md +35 -0
- package/docs/configuration.md +289 -29
- package/docs/cvss-v4-support.md +41 -0
- package/docs/offline-advisory-preview.md +114 -0
- package/docs/offline-rehearsal.md +44 -0
- package/docs/pilot-cases.md +58 -0
- package/docs/pilot-recall.md +124 -0
- package/docs/pilot-report.md +52 -0
- package/docs/validation/alert-outcome-evaluation-2026-11-05.json +2935 -0
- package/docs/validation/cvss-v4-reference-parity-2026-11-05.json +93 -0
- package/docs/validation/rehearsal-accepted-2026-11-05.json +175 -0
- package/docs/validation/rehearsal-unknown-2026-11-05.json +175 -0
- package/docs/vendor/cvss-v4-LICENSE.txt +22 -0
- package/docs/vendor/cvss-v4-provenance.json +38 -0
- package/examples/agent-advisories-2026.json +145 -0
- package/examples/agent-advisory-cases-2026.json +397 -0
- package/examples/libraries.example.txt +4 -2
- package/examples/libraries.example.yaml +2 -0
- package/examples/offline-advisory-preview.mjs +42 -0
- package/examples/rehearsal.json +75 -0
- package/examples/systems.example.yaml +4 -0
- package/package.json +23 -7
- package/docs/quality-review.md +0 -104
package/dist/cve-now.js
CHANGED
|
@@ -1,12 +1,35 @@
|
|
|
1
1
|
import { compare, valid } from 'semver';
|
|
2
2
|
import { cleanText, highest, timestamp } from './util.js';
|
|
3
|
-
import { normalizeEcosystem, normalizePackageName,
|
|
4
|
-
import {
|
|
3
|
+
import { normalizeEcosystem, normalizePackageName, packageKey } from './ecosystems.js';
|
|
4
|
+
import { inventoryMatcher } from './matching.js';
|
|
5
|
+
import { PartialSourceError, SourceError, SourceHttpError, SourceItemFailures, sourceCanceled, throwSourceFailure, } from './source-error.js';
|
|
5
6
|
const ORIGIN = 'https://cve.now';
|
|
6
7
|
const MAX_ENTRIES = 5_000;
|
|
7
|
-
|
|
8
|
+
/** Listing pages read in one poll: about three months of records at the 2026 publication rate. */
|
|
9
|
+
const MAX_PAGES = 600;
|
|
8
10
|
const MAX_DETAIL_FAILURES = 8;
|
|
11
|
+
/** Tracked records without a package match are re-read in turn, oldest first, this many per poll. */
|
|
12
|
+
const REFRESH_PER_POLL = 200;
|
|
9
13
|
const HOUR = 3_600_000;
|
|
14
|
+
/** Package lookups sent in one poll; more take turns. */
|
|
15
|
+
const MAX_LOOKUPS = 1_000;
|
|
16
|
+
/** New records remembered as still to be read. Beyond this the checkpoint is held instead. */
|
|
17
|
+
const MAX_OWED = 2_000;
|
|
18
|
+
/** Failed requests a record owed through the listing must have had before it is given up on. */
|
|
19
|
+
const OWED_ATTEMPTS = 3;
|
|
20
|
+
/** Room kept for new records from the listing however many stored records are re-read. */
|
|
21
|
+
const LISTING_ROOM = 1_000;
|
|
22
|
+
/** The checkpoint is held only when the poll listed at most this many new records. */
|
|
23
|
+
const HOLD_LISTED_MAX = 200;
|
|
24
|
+
/** How far past the cutoff the listing is read, to find records the service ingested late. */
|
|
25
|
+
const LATE_INGEST_DAYS = 7;
|
|
26
|
+
/** How long a listed record that the service answers for, but that cannot be used, is asked for again. */
|
|
27
|
+
const UNUSABLE_HOLD_HOURS = 24;
|
|
28
|
+
/** How long a listed record whose request fails (transport, HTTP 5xx) is asked for again. */
|
|
29
|
+
const UNREACHABLE_HOLD_HOURS = 72;
|
|
30
|
+
const FIRST_SCAN_HOURS = 24;
|
|
31
|
+
/** How long a cited identifier the service does not have is left alone before it is asked for again. */
|
|
32
|
+
const MISSING_RETRY_HOURS = 24;
|
|
10
33
|
function object(value) {
|
|
11
34
|
if (!value || typeof value !== 'object' || Array.isArray(value))
|
|
12
35
|
throw new SourceError('cve.now returned an invalid schema.');
|
|
@@ -44,6 +67,23 @@ function date(value, now) {
|
|
|
44
67
|
throw new SourceError('cve.now returned a future timestamp; collection is incomplete.');
|
|
45
68
|
return timestamp(parsed);
|
|
46
69
|
}
|
|
70
|
+
/**
|
|
71
|
+
* The first of several timestamps that is not in the future. The service sometimes stamps a record
|
|
72
|
+
* ahead of the clock (a scheduled publication date, for example). Such a stamp is not usable for
|
|
73
|
+
* ordering revisions, but it is no reason to reject the record or hold back the whole source.
|
|
74
|
+
*/
|
|
75
|
+
function settledDate(values, now) {
|
|
76
|
+
for (const value of values) {
|
|
77
|
+
if (value === null || value === undefined)
|
|
78
|
+
continue;
|
|
79
|
+
const parsed = Date.parse(text(value));
|
|
80
|
+
if (!Number.isFinite(parsed))
|
|
81
|
+
throw new SourceError('cve.now returned an invalid timestamp.');
|
|
82
|
+
if (parsed <= now + 5 * 60_000)
|
|
83
|
+
return timestamp(parsed);
|
|
84
|
+
}
|
|
85
|
+
return undefined;
|
|
86
|
+
}
|
|
47
87
|
function rating(value) {
|
|
48
88
|
if (typeof value === 'number' && Number.isFinite(value) && value >= 0 && value <= 10)
|
|
49
89
|
return value >= 9
|
|
@@ -147,7 +187,8 @@ function parseEntry(data, now, expected, matched) {
|
|
|
147
187
|
name = normalizePackageName(knownEcosystem, name);
|
|
148
188
|
}
|
|
149
189
|
catch {
|
|
150
|
-
|
|
190
|
+
// Keep the published spelling. A name this application cannot normalise matches no inventory
|
|
191
|
+
// entry, and must not discard the rest of the record or hold back the checkpoint.
|
|
151
192
|
}
|
|
152
193
|
}
|
|
153
194
|
const versions = list(affected.versions, true).map(text);
|
|
@@ -177,10 +218,12 @@ function parseEntry(data, now, expected, matched) {
|
|
|
177
218
|
const knownExploited = exploitation.kev !== undefined && exploitation.kev !== null;
|
|
178
219
|
if (knownExploited)
|
|
179
220
|
object(exploitation.kev);
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
221
|
+
// A stamp ahead of the clock cannot order revisions: fall back to the record's earlier stamps.
|
|
222
|
+
// Only a record with no usable time at all is refused.
|
|
223
|
+
const modified = settledDate([data.modifiedAt, data.publishedAt, data.firstSeenAt], now);
|
|
224
|
+
if (!modified)
|
|
225
|
+
date(data.modifiedAt ?? data.publishedAt ?? data.firstSeenAt, now);
|
|
226
|
+
const published = settledDate([data.publishedAt], now);
|
|
184
227
|
return {
|
|
185
228
|
id: `cve_now:${id}`,
|
|
186
229
|
source: 'cve_now',
|
|
@@ -200,55 +243,49 @@ function parseEntry(data, now, expected, matched) {
|
|
|
200
243
|
...(published ? { published_at: published } : {}),
|
|
201
244
|
};
|
|
202
245
|
}
|
|
246
|
+
/** A structured package claim for something in the inventory. */
|
|
247
|
+
function packageMatched(item, inventory) {
|
|
248
|
+
const { packages } = inventoryMatcher(inventory);
|
|
249
|
+
return item.packages.some((claim) => {
|
|
250
|
+
const key = packageKey(claim);
|
|
251
|
+
return key !== undefined && packages.has(key);
|
|
252
|
+
});
|
|
253
|
+
}
|
|
254
|
+
/**
|
|
255
|
+
* Whether a record concerns this inventory. Advisory text is matched only against terms the operator
|
|
256
|
+
* declared (products and keywords): an advisory names its packages in structured claims, and package
|
|
257
|
+
* names such as "send" or "buffer" appear in unrelated descriptions. News has no structured claims,
|
|
258
|
+
* so a package named in a story about packages also counts.
|
|
259
|
+
*/
|
|
203
260
|
export function evidenceRelevant(item, inventory) {
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
if (item.packages.some((claim) => samePackage(claim, component)))
|
|
208
|
-
return true;
|
|
209
|
-
names.add(component.name);
|
|
210
|
-
}
|
|
211
|
-
for (const product of system.products ?? []) {
|
|
212
|
-
names.add(product.name);
|
|
213
|
-
for (const keyword of product.keywords)
|
|
214
|
-
names.add(keyword);
|
|
215
|
-
}
|
|
216
|
-
for (const keyword of system.keywords ?? [])
|
|
217
|
-
names.add(keyword);
|
|
218
|
-
}
|
|
261
|
+
if (packageMatched(item, inventory))
|
|
262
|
+
return true;
|
|
263
|
+
const matcher = inventoryMatcher(inventory);
|
|
219
264
|
const content = `${item.title}\n${item.description}`;
|
|
220
|
-
return
|
|
221
|
-
const normalized = name.trim();
|
|
222
|
-
if (normalized.length < 3)
|
|
223
|
-
return false;
|
|
224
|
-
const escaped = normalized.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
225
|
-
return new RegExp(`(?<![\\p{L}\\p{N}_@/\\-])${escaped}(?![\\p{L}\\p{N}_@/\\-])`, 'iu').test(content);
|
|
226
|
-
});
|
|
265
|
+
return matcher.declared(content) || (item.kind === 'news' && matcher.packageNamed(content));
|
|
227
266
|
}
|
|
228
267
|
/** Collect recent CVEs, exact npm matches and updates to relevant tracked IDs.
|
|
229
|
-
* The publication-ordered listing does not cover every historical modification
|
|
230
|
-
|
|
268
|
+
* The publication-ordered listing does not cover every historical modification, and a record the
|
|
269
|
+
* service ingests more than LATE_INGEST_DAYS after its publication date is not found by it. */
|
|
270
|
+
export async function collectCveNow(inventory, checkpoint, previous, news, http, now, state = {}) {
|
|
231
271
|
const collected = new Map();
|
|
232
272
|
try {
|
|
233
|
-
return await readCveNow(inventory, checkpoint, previous, news, http, now, collected);
|
|
273
|
+
return await readCveNow(inventory, checkpoint, previous, news, http, now, collected, state);
|
|
234
274
|
}
|
|
235
275
|
catch (error) {
|
|
236
276
|
throwSourceFailure(error, [...collected.values()]);
|
|
237
277
|
}
|
|
238
278
|
}
|
|
239
|
-
async function
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
const last = checkpoint === undefined ? now - 7 * 24 * HOUR : Date.parse(checkpoint);
|
|
250
|
-
if (!Number.isFinite(last) || last > now)
|
|
251
|
-
throw new SourceError('Invalid cve.now checkpoint; reset it before collecting.');
|
|
279
|
+
async function readCveNow(inventory, checkpoint, previous, news, http, now, collected, state) {
|
|
280
|
+
// A new installation catches up on one day. Exact npm matches above cover all of history, so a
|
|
281
|
+
// longer sweep would mostly download records about unrelated software.
|
|
282
|
+
const parsedCheckpoint = checkpoint === undefined ? NaN : Date.parse(checkpoint);
|
|
283
|
+
// A checkpoint that cannot be read, or that lies ahead of the clock (the clock was set back),
|
|
284
|
+
// says nothing about what was read: start again as a new installation does. Failing instead
|
|
285
|
+
// would stop the source until someone edited the database.
|
|
286
|
+
const last = Number.isFinite(parsedCheckpoint) && parsedCheckpoint <= now
|
|
287
|
+
? parsedCheckpoint
|
|
288
|
+
: now - FIRST_SCAN_HOURS * HOUR;
|
|
252
289
|
const cutoff = Math.max(0, last - HOUR);
|
|
253
290
|
const invalid = new SourceItemFailures();
|
|
254
291
|
const retain = (entry) => {
|
|
@@ -277,6 +314,8 @@ async function readCveNow(inventory, checkpoint, previous, news, http, now, coll
|
|
|
277
314
|
if (!old || Date.parse(entry.modified_at) >= Date.parse(old.modified_at))
|
|
278
315
|
collected.set(entry.id, entry);
|
|
279
316
|
};
|
|
317
|
+
/** Records the package lookup matched, with the exact package versions that matched each one. */
|
|
318
|
+
const stackMatches = new Map();
|
|
280
319
|
const queries = new Map();
|
|
281
320
|
for (const system of inventory.systems)
|
|
282
321
|
for (const component of system.components)
|
|
@@ -290,21 +329,74 @@ async function readCveNow(inventory, checkpoint, previous, news, http, now, coll
|
|
|
290
329
|
version: component.version,
|
|
291
330
|
});
|
|
292
331
|
}
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
332
|
+
// Each package version is looked up in turn, the one tried longest ago first (one never tried
|
|
333
|
+
// comes before all others), so with more versions than one poll sends every version still gets
|
|
334
|
+
// its turn. Of those chosen for this poll, the ones whose last lookup failed are sent after the
|
|
335
|
+
// others: a few that keep failing end the lookups of a poll only once the rest have been sent.
|
|
336
|
+
// The listing and the records are read on every poll.
|
|
337
|
+
const lookupKey = (query) => `${query.name}@${query.version}`;
|
|
338
|
+
/** For each package version: when its lookup was last tried, and whether that lookup failed. */
|
|
339
|
+
const history = new Map();
|
|
340
|
+
try {
|
|
341
|
+
for (const entry of JSON.parse(state.lookups ?? '[]'))
|
|
342
|
+
if (Array.isArray(entry) && typeof entry[0] === 'string' && typeof entry[1] === 'number')
|
|
343
|
+
history.set(entry[0], { at: Math.min(entry[1], now), failed: entry[2] === 1 });
|
|
344
|
+
}
|
|
345
|
+
catch {
|
|
346
|
+
// An unreadable history only means every version is looked up as if for the first time.
|
|
347
|
+
}
|
|
348
|
+
const tried = (query) => history.get(lookupKey(query))?.at ?? -Infinity;
|
|
349
|
+
const failedBefore = (query) => history.get(lookupKey(query))?.failed === true;
|
|
350
|
+
const ordered = [...queries.values()].sort((a, b) => tried(a) - tried(b) || lookupKey(a).localeCompare(lookupKey(b)));
|
|
351
|
+
const chosen = ordered.slice(0, MAX_LOOKUPS);
|
|
352
|
+
const allQueries = [
|
|
353
|
+
...chosen.filter((query) => !failedBefore(query)),
|
|
354
|
+
...chosen.filter((query) => failedBefore(query)),
|
|
355
|
+
];
|
|
356
|
+
const notLookedUp = ordered.slice(MAX_LOOKUPS);
|
|
357
|
+
const failedLookups = new Set();
|
|
358
|
+
const pendingLookups = new Set();
|
|
359
|
+
// One lookup that fails says nothing about the others, nor about the listing: it is reported,
|
|
360
|
+
// and that package is looked up again on the next poll. Repeated failures, or a refusal to
|
|
361
|
+
// serve this client, end the lookups for this poll, as they end the detail requests.
|
|
362
|
+
let lookupFailed = 0;
|
|
363
|
+
let lookupUnsent = 0;
|
|
364
|
+
let firstLookupFailure;
|
|
365
|
+
for (let offset = 0; offset < allQueries.length; offset += 4) {
|
|
366
|
+
const batch = allQueries.slice(offset, offset + 4);
|
|
367
|
+
const results = await Promise.allSettled(batch.map(async (query) => {
|
|
298
368
|
// The provider deduplicates advisories and returns only one matched pair in
|
|
299
369
|
// a multi-package request. Query pairs separately so no positive match is lost.
|
|
300
370
|
const url = new URL(`${ORIGIN}/stack`);
|
|
301
371
|
url.searchParams.set('p', `npm:${query.name}@${query.version}`);
|
|
302
372
|
url.searchParams.set('format', 'json');
|
|
303
373
|
const data = (await get(http, url.href));
|
|
374
|
+
if (data.items !== undefined && data.entries === undefined) {
|
|
375
|
+
// Current format: a JSON Feed whose items name the matched record and package only.
|
|
376
|
+
// The full record, with its affected ranges, is read from the detail endpoint below.
|
|
377
|
+
const items = list(data.items);
|
|
378
|
+
if (items.length > MAX_ENTRIES || data.next_url)
|
|
379
|
+
throw new SourceError('cve.now package matches are incomplete.');
|
|
380
|
+
for (const raw of items) {
|
|
381
|
+
const id = invalid.read(() => {
|
|
382
|
+
const item = object(raw);
|
|
383
|
+
const match = object(object(item._cve_now).matched);
|
|
384
|
+
if (match.ecosystem !== 'npm' || match.name !== query.name || match.version !== query.version)
|
|
385
|
+
throw new SourceError('cve.now returned an unrequested package match.');
|
|
386
|
+
return identifier(item.id);
|
|
387
|
+
});
|
|
388
|
+
if (!id)
|
|
389
|
+
continue;
|
|
390
|
+
if (!stackMatches.has(id))
|
|
391
|
+
stackMatches.set(id, []);
|
|
392
|
+
stackMatches.get(id).push(query);
|
|
393
|
+
}
|
|
394
|
+
return;
|
|
395
|
+
}
|
|
304
396
|
if (data.packages !== 1)
|
|
305
397
|
throw new SourceError('cve.now package count did not match the request; collection is incomplete.');
|
|
306
398
|
const entries = list(data.entries);
|
|
307
|
-
if (entries.length > MAX_ENTRIES || data.nextCursor || data.truncated === true)
|
|
399
|
+
if (entries.length > MAX_ENTRIES || data.nextCursor || data.next_cursor || data.truncated === true)
|
|
308
400
|
throw new SourceError('cve.now package matches are incomplete.');
|
|
309
401
|
for (const raw of entries) {
|
|
310
402
|
const parsed = invalid.read(() => {
|
|
@@ -318,96 +410,593 @@ async function readCveNow(inventory, checkpoint, previous, news, http, now, coll
|
|
|
318
410
|
retain(parsed);
|
|
319
411
|
}
|
|
320
412
|
}));
|
|
413
|
+
const canceled = results.find((result) => result.status === 'rejected' && sourceCanceled(result.reason));
|
|
414
|
+
if (canceled?.status === 'rejected')
|
|
415
|
+
throw canceled.reason;
|
|
416
|
+
let failedHere = 0;
|
|
417
|
+
let blocked = false;
|
|
418
|
+
for (const result of results) {
|
|
419
|
+
if (result.status !== 'rejected')
|
|
420
|
+
continue;
|
|
421
|
+
// A timeout or a dropped connection is a failed lookup like any other.
|
|
422
|
+
failedLookups.add(lookupKey(batch[results.indexOf(result)]));
|
|
423
|
+
failedHere++;
|
|
424
|
+
lookupFailed++;
|
|
425
|
+
firstLookupFailure ??=
|
|
426
|
+
result.reason instanceof SourceError ? result.reason.message : 'cve.now request failed.';
|
|
427
|
+
if (result.reason instanceof SourceHttpError && [401, 429].includes(result.reason.status))
|
|
428
|
+
blocked = true;
|
|
429
|
+
}
|
|
430
|
+
if (failedHere === batch.length || lookupFailed >= MAX_DETAIL_FAILURES || blocked) {
|
|
431
|
+
lookupUnsent = allQueries.length - offset - batch.length;
|
|
432
|
+
for (const query of allQueries.slice(offset + batch.length))
|
|
433
|
+
pendingLookups.add(lookupKey(query));
|
|
434
|
+
break;
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
for (const query of notLookedUp)
|
|
438
|
+
pendingLookups.add(lookupKey(query));
|
|
439
|
+
lookupUnsent += notLookedUp.length;
|
|
440
|
+
// Only the versions in the inventory now are remembered; one tried this poll, answered or not,
|
|
441
|
+
// goes to the back of the queue, and one not sent keeps its place and its last outcome.
|
|
442
|
+
state.nextLookups = JSON.stringify([...queries.values()].map((query) => {
|
|
443
|
+
const key = lookupKey(query);
|
|
444
|
+
if (pendingLookups.has(key)) {
|
|
445
|
+
const before = tried(query);
|
|
446
|
+
return [key, Number.isFinite(before) ? before : 0, failedBefore(query) ? 1 : 0];
|
|
447
|
+
}
|
|
448
|
+
return [key, now, failedLookups.has(key) ? 1 : 0];
|
|
449
|
+
}));
|
|
450
|
+
// Packages whose lookup did not answer this poll: what earlier lookups said about them stands.
|
|
451
|
+
const unknownLookup = new Set([...failedLookups, ...pendingLookups].map((key) => key.slice(0, key.lastIndexOf('@'))));
|
|
321
452
|
const wanted = new Map();
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
//
|
|
453
|
+
/** Requests left out because one poll reads at most MAX_ENTRIES - LISTING_ROOM records besides the listing's. */
|
|
454
|
+
let dropped = 0;
|
|
455
|
+
/** Records named by a package lookup that were left out: their lookups are sent first next poll. */
|
|
456
|
+
const droppedMatches = new Set();
|
|
457
|
+
// Everything but new records from the listing shares MAX_ENTRIES - LISTING_ROOM requests, so the
|
|
458
|
+
// listing always has its room, however many records the lookups name.
|
|
459
|
+
const want = (id, reason) => {
|
|
460
|
+
if (wanted.has(id))
|
|
461
|
+
return;
|
|
462
|
+
if (wanted.size >= MAX_ENTRIES - LISTING_ROOM) {
|
|
463
|
+
dropped++;
|
|
464
|
+
if (reason === 'match')
|
|
465
|
+
droppedMatches.add(id);
|
|
466
|
+
}
|
|
467
|
+
else
|
|
468
|
+
wanted.set(id, reason);
|
|
469
|
+
};
|
|
470
|
+
for (const id of stackMatches.keys())
|
|
471
|
+
want(id, 'match');
|
|
472
|
+
const tracked = previous
|
|
473
|
+
.filter((item) => item.source === 'cve_now' && item.id.startsWith('cve_now:'))
|
|
474
|
+
.sort((a, b) => Date.parse(a.fetched_at) - Date.parse(b.fetched_at) || a.id.localeCompare(b.id));
|
|
475
|
+
// By every identifier a stored record is known under: a cited CVE may be served under another.
|
|
476
|
+
const stored = new Set(tracked.flatMap((item) => [item.id.slice(8), ...item.aliases].map((id) => id.toUpperCase())));
|
|
477
|
+
// CVEs mentioned by a relevant story may be much older than the recent listing. One that is not
|
|
478
|
+
// stored yet is read now; once stored it is refreshed in turn with the other tracked records.
|
|
479
|
+
const cited = new Set();
|
|
327
480
|
for (const item of [...previous, ...news])
|
|
328
481
|
if (item.kind === 'news' && evidenceRelevant(item, inventory))
|
|
329
482
|
for (const id of item.aliases)
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
const
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
483
|
+
// The length is bounded: text from a feed must not be able to produce an identifier that
|
|
484
|
+
// fails the whole collection.
|
|
485
|
+
if (/^(?:CVE-\d{4}-\d{4,19}|GHSA-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4})$/i.test(id))
|
|
486
|
+
cited.add(id.toUpperCase());
|
|
487
|
+
// An identifier the service did not have is asked for again once a day, not on every poll. When
|
|
488
|
+
// the record is published it also appears in the listing, so nothing waits for that day.
|
|
489
|
+
const askedAt = new Map();
|
|
490
|
+
try {
|
|
491
|
+
for (const entry of JSON.parse(state.missing ?? '[]'))
|
|
492
|
+
if (Array.isArray(entry) && typeof entry[0] === 'string' && typeof entry[1] === 'number')
|
|
493
|
+
askedAt.set(entry[0], entry[1]);
|
|
494
|
+
}
|
|
495
|
+
catch {
|
|
496
|
+
// An unreadable list only means every identifier is asked for once more.
|
|
497
|
+
}
|
|
498
|
+
const missing = new Map();
|
|
499
|
+
for (const id of cited) {
|
|
500
|
+
if (stored.has(id))
|
|
501
|
+
continue;
|
|
502
|
+
const asked = askedAt.get(id);
|
|
503
|
+
if (asked !== undefined && asked <= now && now - asked < MISSING_RETRY_HOURS * HOUR)
|
|
504
|
+
missing.set(id, asked);
|
|
505
|
+
else
|
|
506
|
+
want(id, 'cited');
|
|
507
|
+
}
|
|
508
|
+
// Records that decide a package result are re-read on every poll, the longest unread first.
|
|
509
|
+
// Records kept only because a declared term appears in their text, or because a story cites them,
|
|
510
|
+
// take turns, so the work per poll stays bounded however many accumulate.
|
|
511
|
+
let rotating = 0;
|
|
512
|
+
for (const item of tracked) {
|
|
513
|
+
const id = identifier(item.id.slice(8));
|
|
514
|
+
// The oldest read come first. Room is kept for the listing after everything else wanted for the
|
|
515
|
+
// packages (records the lookups named included), or a store with that many records for the
|
|
516
|
+
// inventory's packages would stop new records from being read at all.
|
|
517
|
+
if (packageMatched(item, inventory)) {
|
|
518
|
+
if (wanted.has(id))
|
|
359
519
|
continue;
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
throw new SourceError('cve.now returned out-of-order pagination; collection is incomplete.');
|
|
363
|
-
previousPublished = published;
|
|
364
|
-
if (published >= cutoff)
|
|
365
|
-
wanted.set(id, false);
|
|
520
|
+
if (wanted.size < MAX_ENTRIES - LISTING_ROOM)
|
|
521
|
+
wanted.set(id, 'tracked');
|
|
366
522
|
else
|
|
367
|
-
|
|
523
|
+
dropped++;
|
|
524
|
+
}
|
|
525
|
+
else if (rotating < REFRESH_PER_POLL &&
|
|
526
|
+
wanted.size < MAX_ENTRIES - LISTING_ROOM &&
|
|
527
|
+
(cited.has(id) || evidenceRelevant(item, inventory))) {
|
|
528
|
+
rotating++;
|
|
529
|
+
want(id, 'refresh');
|
|
368
530
|
}
|
|
369
|
-
const next = optionalText(data.nextCursor);
|
|
370
|
-
if (!next || crossedCutoff)
|
|
371
|
-
break;
|
|
372
|
-
if (!entries.length || next.length > 2_048 || seen.has(next))
|
|
373
|
-
throw new SourceError('cve.now returned invalid or repeated pagination.');
|
|
374
|
-
seen.add(next);
|
|
375
|
-
cursor = next;
|
|
376
531
|
}
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
532
|
+
let cursor;
|
|
533
|
+
const seen = new Set();
|
|
534
|
+
// The listing is ordered by publication time, newest first (checked against the live service on
|
|
535
|
+
// 2026-11-14: its cursor is [publishedAt, id]). A record the service ingested late keeps its old
|
|
536
|
+
// publication time and so sits further down than the records around its arrival. Reading
|
|
537
|
+
// LATE_INGEST_DAYS past the cutoff finds such records; `firstSeenAt` decides whether one is new.
|
|
538
|
+
const horizon = cutoff - LATE_INGEST_DAYS * 24 * HOUR;
|
|
539
|
+
let oldestOrdered = Infinity;
|
|
540
|
+
/** Whether any listed record so far carried a publication time. */
|
|
541
|
+
let dated = false;
|
|
542
|
+
const listed = [];
|
|
543
|
+
/** Listing entries without a usable identifier, by the time of the record listed before them. */
|
|
544
|
+
let refusedHeld = 0;
|
|
545
|
+
let refusedPassed = 0;
|
|
546
|
+
let firstRefused;
|
|
547
|
+
/** The listing went on past what one poll pages through; records older than this were not listed. */
|
|
548
|
+
let unlistedBefore;
|
|
549
|
+
// A failed listing must not discard what the package lookup found: those records are still read
|
|
550
|
+
// below, and the listing failure is reported afterwards.
|
|
551
|
+
let listingFailure;
|
|
552
|
+
try {
|
|
553
|
+
for (let page = 0;; page++) {
|
|
554
|
+
if (page >= MAX_PAGES) {
|
|
555
|
+
// Stopping here with an error would repeat on every poll and never recover. Read what was
|
|
556
|
+
// listed, say what was not, and let the checkpoint move.
|
|
557
|
+
unlistedBefore = Number.isFinite(oldestOrdered) ? oldestOrdered : now;
|
|
558
|
+
break;
|
|
559
|
+
}
|
|
560
|
+
const url = new URL(`${ORIGIN}/api/v1/entries`);
|
|
561
|
+
url.searchParams.set('limit', '100');
|
|
562
|
+
if (cursor)
|
|
563
|
+
url.searchParams.set('cursor', cursor);
|
|
564
|
+
const data = (await get(http, url.href));
|
|
565
|
+
// The listing has carried its records as `entries`, and later also as `items`.
|
|
566
|
+
const entries = list(data.entries ?? data.items);
|
|
567
|
+
if (entries.length > 100)
|
|
568
|
+
throw new SourceError('cve.now returned too many records on one page.');
|
|
569
|
+
let pastHorizon = false;
|
|
570
|
+
if (entries.some((raw) => raw?.publishedAt != null))
|
|
571
|
+
dated = true;
|
|
572
|
+
for (const raw of entries) {
|
|
573
|
+
// Where an entry that cannot be read sits: next to the record listed before it.
|
|
574
|
+
const neighbour = Number.isFinite(oldestOrdered) ? oldestOrdered : now;
|
|
575
|
+
let parsed;
|
|
576
|
+
try {
|
|
577
|
+
const entry = object(raw);
|
|
578
|
+
const id = identifier(entry.id);
|
|
579
|
+
if ((entry.publishedAt ?? undefined) === undefined &&
|
|
580
|
+
(entry.firstSeenAt ?? undefined) === undefined)
|
|
581
|
+
throw new SourceError('cve.now returned an invalid timestamp.');
|
|
582
|
+
const usable = (value) => (value === undefined ? undefined : Date.parse(value));
|
|
583
|
+
const published = usable(settledDate([entry.publishedAt], now));
|
|
584
|
+
const firstSeen = usable(settledDate([entry.firstSeenAt], now));
|
|
585
|
+
// The position in the listing: the publication time, or the arrival time when there is none.
|
|
586
|
+
// A publication time ahead of the clock (a scheduled publication) gives no position.
|
|
587
|
+
const ordered = entry.publishedAt !== undefined && entry.publishedAt !== null;
|
|
588
|
+
const position = ordered ? published : firstSeen;
|
|
589
|
+
// When the record became visible to a reader of this listing: the later of the two stamps.
|
|
590
|
+
// A record stamped ahead of the clock is new now, on every poll until its time comes.
|
|
591
|
+
const arrival = position === undefined ? now : Math.max(position, firstSeen ?? position);
|
|
592
|
+
parsed = { id, position, arrival, ordered };
|
|
593
|
+
}
|
|
594
|
+
catch (error) {
|
|
595
|
+
if (!(error instanceof SourceError))
|
|
596
|
+
throw error;
|
|
597
|
+
// Nothing can be requested for it. While it is recent it is owed; after that it is reported
|
|
598
|
+
// and passed over, or the checkpoint would wait for it for ever.
|
|
599
|
+
if (neighbour < cutoff)
|
|
600
|
+
continue;
|
|
601
|
+
firstRefused ??= error.message;
|
|
602
|
+
if (now - neighbour > UNUSABLE_HOLD_HOURS * HOUR)
|
|
603
|
+
refusedPassed++;
|
|
604
|
+
else
|
|
605
|
+
refusedHeld++;
|
|
606
|
+
continue;
|
|
607
|
+
}
|
|
608
|
+
const { id, position, arrival, ordered } = parsed;
|
|
609
|
+
if (position !== undefined) {
|
|
610
|
+
// Only a publication time places a record in the listing. A record without one is placed
|
|
611
|
+
// by its arrival, which says nothing about the records around it, unless the listing
|
|
612
|
+
// carries no publication times at all.
|
|
613
|
+
if (ordered || !dated) {
|
|
614
|
+
// Small disorder is harmless because paging continues well past the cutoff. A record
|
|
615
|
+
// this much newer than one already passed means the order cannot be relied on to stop.
|
|
616
|
+
if (position > oldestOrdered + LATE_INGEST_DAYS * 24 * HOUR)
|
|
617
|
+
throw new SourceError('cve.now returned out-of-order pagination; collection is incomplete.');
|
|
618
|
+
oldestOrdered = Math.min(oldestOrdered, position);
|
|
619
|
+
if (position < horizon)
|
|
620
|
+
pastHorizon = true;
|
|
621
|
+
}
|
|
622
|
+
}
|
|
623
|
+
if (arrival >= cutoff)
|
|
624
|
+
listed.push({ id, published: arrival });
|
|
625
|
+
}
|
|
626
|
+
// Both spellings have been served; reading only one silently stops after the first page.
|
|
627
|
+
const next = optionalText(data.nextCursor ?? data.next_cursor);
|
|
628
|
+
if (!next || pastHorizon)
|
|
629
|
+
break;
|
|
630
|
+
if (!entries.length || next.length > 2_048 || seen.has(next))
|
|
631
|
+
throw new SourceError('cve.now returned invalid or repeated pagination.');
|
|
632
|
+
seen.add(next);
|
|
633
|
+
cursor = next;
|
|
634
|
+
}
|
|
635
|
+
}
|
|
636
|
+
catch (error) {
|
|
637
|
+
if (sourceCanceled(error))
|
|
638
|
+
throw error;
|
|
639
|
+
listingFailure = error;
|
|
640
|
+
listed.length = 0;
|
|
641
|
+
}
|
|
642
|
+
// After a long outage the listing can hold more than one poll may read. Take the oldest first and
|
|
643
|
+
// record how far this poll got, so the next one continues instead of starting over.
|
|
644
|
+
let resume = now;
|
|
645
|
+
let deferred = 0;
|
|
646
|
+
// A listed record that is already stored was read on an earlier poll (the checkpoint's overlap):
|
|
647
|
+
// reading it again would spend the requests that new and owed records need. The stored records
|
|
648
|
+
// that decide a package result are re-read anyway.
|
|
649
|
+
const storedIds = new Set(tracked.map((item) => identifier(item.id.slice(8))));
|
|
650
|
+
const fresh = [...new Map(listed.map((entry) => [entry.id, entry])).values()]
|
|
651
|
+
.filter(({ id }) => !wanted.has(id) && !storedIds.has(id))
|
|
652
|
+
.sort((a, b) => a.published - b.published);
|
|
653
|
+
const room = Math.max(0, MAX_ENTRIES - wanted.size);
|
|
654
|
+
for (const { id } of fresh.slice(0, room))
|
|
655
|
+
wanted.set(id, 'listed');
|
|
656
|
+
if (fresh.length > room) {
|
|
657
|
+
deferred = fresh.length - room;
|
|
658
|
+
const reached = room ? fresh[room - 1].published : cutoff;
|
|
659
|
+
// The next cutoff is the checkpoint minus an hour, so this resumes exactly where it stopped.
|
|
660
|
+
resume = Math.min(now, reached + HOUR);
|
|
661
|
+
}
|
|
662
|
+
// Records listed on an earlier poll whose requests have not succeeded yet. They are remembered
|
|
663
|
+
// by identifier, so the checkpoint can move on without them and a record that keeps failing
|
|
664
|
+
// cannot make every poll read the same listing again.
|
|
665
|
+
const owedBefore = new Map();
|
|
666
|
+
try {
|
|
667
|
+
for (const entry of JSON.parse(state.owed ?? '[]'))
|
|
668
|
+
if (Array.isArray(entry) &&
|
|
669
|
+
typeof entry[0] === 'string' &&
|
|
670
|
+
/^[a-z0-9][a-z0-9._-]{2,127}$/i.test(entry[0]) &&
|
|
671
|
+
typeof entry[1] === 'number' &&
|
|
672
|
+
typeof entry[2] === 'number')
|
|
673
|
+
// A time ahead of the clock (the clock was set back) would never run out.
|
|
674
|
+
owedBefore.set(entry[0], {
|
|
675
|
+
failedAt: Math.min(entry[1], now),
|
|
676
|
+
arrival: entry[2],
|
|
677
|
+
// Lists written before attempts were counted: as many as were needed then.
|
|
678
|
+
attempts: typeof entry[3] === 'number' ? entry[3] : OWED_ATTEMPTS,
|
|
679
|
+
});
|
|
680
|
+
}
|
|
681
|
+
catch {
|
|
682
|
+
// An unreadable list only means those records are found again through the listing, or not at all.
|
|
683
|
+
}
|
|
684
|
+
for (const id of owedBefore.keys())
|
|
685
|
+
if (!wanted.has(id) && wanted.size < MAX_ENTRIES)
|
|
686
|
+
wanted.set(id, 'listed');
|
|
687
|
+
const arrivals = new Map([
|
|
688
|
+
...[...owedBefore].map(([id, { arrival }]) => [id, arrival]),
|
|
689
|
+
...listed.map((entry) => [entry.id, entry.published]),
|
|
690
|
+
]);
|
|
691
|
+
const storedCopy = new Map(tracked.map((item) => [identifier(item.id.slice(8)), item]));
|
|
692
|
+
/** The service answered about this record: a refusal for it, or content that cannot be used. */
|
|
693
|
+
const answered = (reason) => reason instanceof SourceHttpError
|
|
694
|
+
? reason.status >= 400 && reason.status < 500 && ![401, 403, 408, 429].includes(reason.status)
|
|
695
|
+
: reason instanceof SourceError;
|
|
696
|
+
// Records whose requests failed last time are asked for last. A few records that keep failing
|
|
697
|
+
// then cannot stop the others from being read, and the rule that ends a poll after repeated
|
|
698
|
+
// failures only cuts the poll short where nothing else is waiting.
|
|
699
|
+
const troubled = new Set();
|
|
700
|
+
try {
|
|
701
|
+
for (const id of JSON.parse(state.troubled ?? '[]'))
|
|
702
|
+
if (typeof id === 'string')
|
|
703
|
+
troubled.add(id);
|
|
704
|
+
}
|
|
705
|
+
catch {
|
|
706
|
+
// An unreadable list only means the usual order.
|
|
707
|
+
}
|
|
708
|
+
const pending = [...wanted].filter(([id]) => !collected.has(`cve_now:${id}`));
|
|
709
|
+
// Owed records come before the stored records re-read in turn for a declared term or a citation,
|
|
710
|
+
// so that a service that allows only so many requests per poll still reads them.
|
|
711
|
+
const owedFirst = ([id, why]) => why === 'listed' && owedBefore.has(id);
|
|
712
|
+
const ids = [
|
|
713
|
+
...pending.filter(([id, why]) => !troubled.has(id) && why !== 'refresh'),
|
|
714
|
+
// The ones tried least come first, so that a poll that ends at a batch that fails tries
|
|
715
|
+
// different ones each time.
|
|
716
|
+
...pending
|
|
717
|
+
.filter((entry) => troubled.has(entry[0]) && owedFirst(entry))
|
|
718
|
+
.sort(([a], [b]) => owedBefore.get(a).attempts - owedBefore.get(b).attempts),
|
|
719
|
+
...pending.filter(([id, why]) => !troubled.has(id) && why === 'refresh'),
|
|
720
|
+
...pending.filter((entry) => troubled.has(entry[0]) && !owedFirst(entry)),
|
|
721
|
+
];
|
|
722
|
+
let succeeded = 0;
|
|
723
|
+
const failures = [];
|
|
724
|
+
let unreachable = 0;
|
|
725
|
+
let stoppedAt = ids.length;
|
|
383
726
|
for (let offset = 0; offset < ids.length; offset += 4) {
|
|
384
727
|
const batch = ids.slice(offset, offset + 4);
|
|
385
|
-
const results = await Promise.allSettled(batch.map(async ([id,
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
728
|
+
const results = await Promise.allSettled(batch.map(async ([id, why]) => {
|
|
729
|
+
try {
|
|
730
|
+
const data = (await get(http, `${ORIGIN}/api/v1/entries/${encodeURIComponent(id)}`));
|
|
731
|
+
const matches = stackMatches.get(id);
|
|
732
|
+
// Each matched package version is positive evidence for that exact version.
|
|
733
|
+
for (const match of matches ?? [undefined]) {
|
|
734
|
+
const entry = parseEntry(data, now, id, match);
|
|
735
|
+
// What the service serves now is its current word on the record. If its modification
|
|
736
|
+
// time is older than the stored revision's (a time ahead of the clock was replaced by
|
|
737
|
+
// an earlier stamp, or the service moved the time back), the store would take this for
|
|
738
|
+
// an outdated copy and drop a real change: it is at least as new as what is stored.
|
|
739
|
+
const copy = storedCopy.get(id);
|
|
740
|
+
if (copy && Date.parse(entry.modified_at) < Date.parse(copy.modified_at))
|
|
741
|
+
entry.modified_at = copy.modified_at;
|
|
742
|
+
// The lookup for a package of this record did not answer this poll: the versions an
|
|
743
|
+
// earlier lookup matched are kept, or the finding would flip and alert again.
|
|
744
|
+
if (copy)
|
|
745
|
+
for (const claim of copy.packages)
|
|
746
|
+
if (claim.matched_versions?.length && unknownLookup.has(claim.name)) {
|
|
747
|
+
const current = entry.packages.find((candidate) => candidate.ecosystem === claim.ecosystem && candidate.name === claim.name);
|
|
748
|
+
if (current)
|
|
749
|
+
current.matched_versions = [
|
|
750
|
+
...new Set([...(current.matched_versions ?? []), ...claim.matched_versions]),
|
|
751
|
+
];
|
|
752
|
+
else
|
|
753
|
+
entry.packages.push({
|
|
754
|
+
ecosystem: claim.ecosystem,
|
|
755
|
+
name: claim.name,
|
|
756
|
+
matched_versions: [...claim.matched_versions],
|
|
757
|
+
});
|
|
758
|
+
}
|
|
759
|
+
retain(entry);
|
|
760
|
+
// The service now files the record under another identifier, with the stored one as an
|
|
761
|
+
// alias. The stored copy would never be refreshed again and would go stale under a
|
|
762
|
+
// complete receipt: it takes the same content.
|
|
763
|
+
if (copy && entry.id !== copy.id)
|
|
764
|
+
retain({ ...entry, id: copy.id });
|
|
765
|
+
}
|
|
766
|
+
succeeded++;
|
|
767
|
+
}
|
|
768
|
+
catch (error) {
|
|
769
|
+
if (sourceCanceled(error) || !answered(error))
|
|
770
|
+
throw error;
|
|
771
|
+
// A cited identifier may not be published yet, or not in a form that can be used. It is
|
|
772
|
+
// asked for again in a day; when it is published it also appears in the listing.
|
|
773
|
+
if (why === 'cited') {
|
|
774
|
+
missing.set(id, now);
|
|
775
|
+
return;
|
|
776
|
+
}
|
|
777
|
+
const copy = why === 'tracked' || why === 'refresh' ? storedCopy.get(id) : undefined;
|
|
778
|
+
// The service no longer serves a stored record. The stored copy stays as the last known
|
|
779
|
+
// content, and counts as checked now: letting it age would turn a result that rests on
|
|
780
|
+
// it into "unknown" without any source error, and it would be asked for first on every
|
|
781
|
+
// later poll.
|
|
782
|
+
const gone = error instanceof SourceHttpError;
|
|
783
|
+
// The service serves a stored record in a form that cannot be used (a status this
|
|
784
|
+
// application does not know, for one). For a record about an inventory package that is a
|
|
785
|
+
// change that cannot be read, and it is reported: the stored ranges may be out of date.
|
|
786
|
+
// Any other stored record keeps its last content.
|
|
787
|
+
if (copy && (gone || !packageMatched(copy, inventory)))
|
|
788
|
+
return retain({ ...copy, fetched_at: timestamp(now) });
|
|
789
|
+
throw error;
|
|
790
|
+
}
|
|
389
791
|
}));
|
|
390
|
-
const
|
|
391
|
-
|
|
392
|
-
if (canceled)
|
|
792
|
+
const canceled = results.find((result) => result.status === 'rejected' && sourceCanceled(result.reason));
|
|
793
|
+
if (canceled?.status === 'rejected')
|
|
393
794
|
throw canceled.reason;
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
795
|
+
let failed = 0;
|
|
796
|
+
let blocked = false;
|
|
797
|
+
for (const [position, result] of results.entries()) {
|
|
798
|
+
if (result.status !== 'rejected')
|
|
799
|
+
continue;
|
|
800
|
+
const [id, why] = batch[position];
|
|
801
|
+
const reason = result.reason;
|
|
802
|
+
failures.push({ id, why, reason });
|
|
803
|
+
// A record the service answered for says nothing about the service being unavailable.
|
|
804
|
+
if (answered(reason))
|
|
805
|
+
continue;
|
|
806
|
+
failed++;
|
|
807
|
+
unreachable++;
|
|
808
|
+
if (reason instanceof SourceHttpError && [401, 429].includes(reason.status))
|
|
809
|
+
blocked = true;
|
|
810
|
+
}
|
|
398
811
|
// One inaccessible record should not hide later advisories. Stop after
|
|
399
812
|
// repeated failures, or an explicit authentication/rate-limit response,
|
|
400
813
|
// while retaining successful requests already in flight.
|
|
401
|
-
if (
|
|
402
|
-
|
|
403
|
-
failures.some(({ reason }) => reason instanceof SourceHttpError && [401, 429].includes(reason.status))) {
|
|
404
|
-
stoppedEarly = offset + batch.length < ids.length;
|
|
814
|
+
if (failed === batch.length || unreachable >= MAX_DETAIL_FAILURES || blocked) {
|
|
815
|
+
stoppedAt = offset + batch.length;
|
|
405
816
|
break;
|
|
406
817
|
}
|
|
407
818
|
}
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
819
|
+
const stoppedEarly = stoppedAt < ids.length;
|
|
820
|
+
// A new record whose request failed, or was not sent because the poll ended early, is owed: it is
|
|
821
|
+
// remembered and asked for again on later polls, before the stored records re-read in turn. That
|
|
822
|
+
// cannot go on for ever. Once its requests have failed OWED_ATTEMPTS times and for long enough
|
|
823
|
+
// (counted from its first failure) it is reported and given up on. Nothing is given up on while
|
|
824
|
+
// no request at all succeeds: that is an outage, not a bad record. A failed request for a record
|
|
825
|
+
// named by a package lookup is reported, and that lookup is sent again first on the next poll.
|
|
826
|
+
let owed = 0;
|
|
827
|
+
let passed = 0;
|
|
828
|
+
let firstOwed;
|
|
829
|
+
let firstPassed;
|
|
830
|
+
let unreachedPassed = 0;
|
|
831
|
+
let firstUnreached;
|
|
832
|
+
const owedNow = new Map();
|
|
833
|
+
const expired = (failedAt, wasAnswered, attempts) => failedAt !== undefined &&
|
|
834
|
+
// A record is given up on only after its requests have failed several times, not because time
|
|
835
|
+
// passed while it waited behind others.
|
|
836
|
+
attempts >= OWED_ATTEMPTS &&
|
|
837
|
+
now - failedAt > (wasAnswered ? UNUSABLE_HOLD_HOURS : UNREACHABLE_HOLD_HOURS) * HOUR &&
|
|
838
|
+
// A request that failed (no answer, or a server error) is given up on only in a poll in which
|
|
839
|
+
// other records were read: while none can be read, it is an outage, not a bad record.
|
|
840
|
+
(wasAnswered || succeeded > 0);
|
|
841
|
+
for (const { id, why, reason } of failures) {
|
|
842
|
+
const message = reason instanceof SourceError ? reason.message : 'cve.now request failed.';
|
|
843
|
+
// A listed record that is already stored (the checkpoint's overlap, or a poll that was held)
|
|
844
|
+
// was read before: a failure to read it again is reported, but it is not owed.
|
|
845
|
+
if (why === 'listed' && !storedCopy.has(id)) {
|
|
846
|
+
const failedAt = owedBefore.get(id)?.failedAt;
|
|
847
|
+
const attempts = (owedBefore.get(id)?.attempts ?? 0) + 1;
|
|
848
|
+
if (expired(failedAt, answered(reason), attempts)) {
|
|
849
|
+
if (answered(reason)) {
|
|
850
|
+
passed++;
|
|
851
|
+
firstPassed ??= message;
|
|
852
|
+
}
|
|
853
|
+
else {
|
|
854
|
+
unreachedPassed++;
|
|
855
|
+
firstUnreached ??= message;
|
|
856
|
+
}
|
|
857
|
+
continue;
|
|
858
|
+
}
|
|
859
|
+
owedNow.set(id, { failedAt: failedAt ?? now, arrival: arrivals.get(id) ?? now, attempts });
|
|
860
|
+
}
|
|
861
|
+
owed++;
|
|
862
|
+
firstOwed ??= message;
|
|
863
|
+
}
|
|
864
|
+
// Not sent: still owed, with the time of its first failure if it has failed before.
|
|
865
|
+
let unsent = 0;
|
|
866
|
+
for (const [id, why] of ids.slice(stoppedAt)) {
|
|
867
|
+
if (why !== 'listed' || storedCopy.has(id))
|
|
868
|
+
continue;
|
|
869
|
+
// It keeps waiting, and is given up on only once its own requests have failed often enough.
|
|
870
|
+
const failedAt = owedBefore.get(id)?.failedAt ?? now;
|
|
871
|
+
const attempts = owedBefore.get(id)?.attempts ?? 0;
|
|
872
|
+
unsent++;
|
|
873
|
+
owedNow.set(id, { failedAt, arrival: arrivals.get(id) ?? now, attempts });
|
|
874
|
+
}
|
|
875
|
+
// A record named by a package lookup that could not be read is not stored and not owed: the
|
|
876
|
+
// lookups that named it are sent again first on the next poll, however many versions take turns.
|
|
877
|
+
const unreadMatches = [
|
|
878
|
+
...droppedMatches,
|
|
879
|
+
...failures.filter(({ why }) => why === 'match').map(({ id }) => id),
|
|
880
|
+
...ids
|
|
881
|
+
.slice(stoppedAt)
|
|
882
|
+
.filter(([, why]) => why === 'match')
|
|
883
|
+
.map(([id]) => id),
|
|
884
|
+
];
|
|
885
|
+
const again = new Set(unreadMatches.flatMap((id) => (stackMatches.get(id) ?? []).map(lookupKey)));
|
|
886
|
+
if (again.size)
|
|
887
|
+
state.nextLookups = JSON.stringify(JSON.parse(state.nextLookups ?? '[]').map(([key, at, failed]) => again.has(key) ? [key, history.get(key)?.at ?? 0, failed] : [key, at, failed]));
|
|
888
|
+
// Owed records that this poll had no room to ask for stay owed.
|
|
889
|
+
for (const [id, entry] of owedBefore)
|
|
890
|
+
if (!wanted.has(id) && !owedNow.has(id))
|
|
891
|
+
owedNow.set(id, entry);
|
|
892
|
+
// More than can be remembered: the oldest are kept, and the checkpoint stops just before the
|
|
893
|
+
// first one that is not, so the next poll finds the rest in the listing and nothing before them
|
|
894
|
+
// is read again.
|
|
895
|
+
const owedOrder = [...owedNow].sort((a, b) => a[1].arrival - b[1].arrival);
|
|
896
|
+
const remembered = new Map(owedOrder.slice(0, MAX_OWED));
|
|
897
|
+
const beyond = owedOrder.slice(MAX_OWED);
|
|
898
|
+
if (beyond.length)
|
|
899
|
+
resume = Math.max(last, Math.min(resume, beyond[0][1].arrival + HOUR));
|
|
900
|
+
// An entry with no usable identifier cannot be remembered. It is waited for from the poll that
|
|
901
|
+
// first saw one; its place in the listing says nothing when it sits above every dated record.
|
|
902
|
+
const refusedSince = refusedHeld
|
|
903
|
+
? typeof state.refusedSince === 'number' && state.refusedSince <= now
|
|
904
|
+
? state.refusedSince
|
|
905
|
+
: now
|
|
906
|
+
: undefined;
|
|
907
|
+
// After that it has been reported for a day and nothing more can be done about it: it is left
|
|
908
|
+
// alone, or it would be reported on every poll for as long as the service lists it.
|
|
909
|
+
if (refusedSince !== undefined && now - refusedSince > UNUSABLE_HOLD_HOURS * HOUR)
|
|
910
|
+
refusedHeld = 0;
|
|
911
|
+
state.nextRefusedSince = refusedSince ?? null;
|
|
912
|
+
// The poll in which a record first fails holds the checkpoint, as any incomplete collection
|
|
913
|
+
// does: most failures are gone on the next poll. From then on the record is carried by the list
|
|
914
|
+
// and the checkpoint moves. Holding means reading the listing since the checkpoint again, so it
|
|
915
|
+
// is only done while that is cheap: never over a backlog, where a service that fails now and
|
|
916
|
+
// then, or allows only so many requests, would have every poll read the same records again.
|
|
917
|
+
const firstFailure = [...remembered.keys()].some((id) => !owedBefore.has(id));
|
|
918
|
+
const small = listed.length <= HOLD_LISTED_MAX && !deferred && !beyond.length;
|
|
919
|
+
const holding = refusedHeld > 0 || (firstFailure && small);
|
|
920
|
+
state.nextOwed = JSON.stringify([...remembered].map(([id, { failedAt, arrival, attempts }]) => [id, failedAt, arrival, attempts]));
|
|
921
|
+
state.next = JSON.stringify([...missing].slice(0, MAX_ENTRIES));
|
|
922
|
+
// A record stays on the list until a request for it succeeds. One that was not sent this time,
|
|
923
|
+
// because the poll ended at another record that fails, would otherwise be first again next time.
|
|
924
|
+
const failedNow = new Set(failures.filter(({ why, reason }) => !answered(reason) || why === 'listed').map(({ id }) => id));
|
|
925
|
+
const notSent = new Set(ids.slice(stoppedAt).map(([id]) => id));
|
|
926
|
+
state.nextTroubled = JSON.stringify([...new Set([...failedNow, ...[...troubled].filter((id) => notSent.has(id))])].slice(0, 1_000));
|
|
927
|
+
const complete = [...collected.values()];
|
|
928
|
+
const refused = refusedHeld + refusedPassed;
|
|
929
|
+
// Whether everything the service has for the inventory's own packages was read: the package
|
|
930
|
+
// lookup, every record it named, and every stored record with a package match. What is missing
|
|
931
|
+
// then is something else, and version exclusions drawn from this source still hold.
|
|
932
|
+
// Records re-read in turn for a declared term or a citation are not among them.
|
|
933
|
+
const forPackages = (why) => why === 'match' || why === 'tracked';
|
|
934
|
+
const packageResults = !lookupFailed &&
|
|
935
|
+
!lookupUnsent &&
|
|
936
|
+
invalid.summary('cve.now') === undefined &&
|
|
937
|
+
!dropped &&
|
|
938
|
+
!failures.some(({ why }) => forPackages(why)) &&
|
|
939
|
+
!ids.slice(stoppedAt).some(([, why]) => forPackages(why))
|
|
940
|
+
? 'complete'
|
|
941
|
+
: undefined;
|
|
942
|
+
const problems = [
|
|
943
|
+
lookupFailed || lookupUnsent
|
|
944
|
+
? `${lookupFailed + lookupUnsent} package lookup request(s) failed or were not sent; those packages are looked up again on later polls${notLookedUp.length
|
|
945
|
+
? ` (${queries.size} package versions are more than the ${MAX_LOOKUPS} one poll looks up)`
|
|
946
|
+
: ''}.${firstLookupFailure ? ` ${firstLookupFailure}` : ''}`
|
|
947
|
+
: '',
|
|
948
|
+
owed
|
|
949
|
+
? `${owed} advisory detail request(s) failed; collection is incomplete. ${firstOwed}${stoppedEarly
|
|
950
|
+
? ' The remaining detail requests were not sent to limit repeated upstream failures.'
|
|
951
|
+
: ''}`
|
|
952
|
+
: unsent
|
|
953
|
+
? `${unsent} advisory detail request(s) were not sent; collection is incomplete.`
|
|
954
|
+
: '',
|
|
955
|
+
remembered.size && !holding
|
|
956
|
+
? `${remembered.size} new record(s) are still to be read and are asked for again on the next poll.`
|
|
957
|
+
: '',
|
|
958
|
+
beyond.length
|
|
959
|
+
? `${beyond.length} more new record(s) are left for the next poll, which continues from there.`
|
|
960
|
+
: '',
|
|
961
|
+
passed ? `${passed} advisory record(s) could not be used and were skipped. ${firstPassed}` : '',
|
|
962
|
+
unreachedPassed
|
|
963
|
+
? `${unreachedPassed} advisory record(s) could not be read for three days and were given up on. ${firstUnreached}`
|
|
964
|
+
: '',
|
|
965
|
+
refused
|
|
966
|
+
? `cve.now: ${refused} invalid item(s) were skipped. ${firstRefused} Collection remains incomplete${refusedHeld ? ' and its checkpoint was not advanced' : ''}.`
|
|
967
|
+
: '',
|
|
968
|
+
invalid.summary('cve.now') ?? '',
|
|
969
|
+
unlistedBefore !== undefined
|
|
970
|
+
? `cve.now lists more records since the last complete poll than one poll pages through; records published before ${timestamp(unlistedBefore)} and after the last checkpoint were not read.`
|
|
971
|
+
: '',
|
|
972
|
+
deferred
|
|
973
|
+
? `cve.now listed ${deferred} more new record(s) than one poll reads; the oldest were collected and the next poll continues from there.`
|
|
974
|
+
: '',
|
|
975
|
+
dropped
|
|
976
|
+
? `${dropped} requested record(s) were not read because one poll reads at most ${MAX_ENTRIES - LISTING_ROOM} records besides new ones from the listing; the longest unread are read first on the next poll.`
|
|
977
|
+
: '',
|
|
978
|
+
].filter(Boolean);
|
|
979
|
+
if (listingFailure) {
|
|
980
|
+
// The listing finds new records; the package lookup and the stored records were read all the
|
|
981
|
+
// same. The checkpoint stays, and anything else this poll found is reported with it.
|
|
982
|
+
const message = listingFailure instanceof SourceError ? listingFailure.message : 'Source request failed.';
|
|
983
|
+
const text = [message, ...problems].join(' ');
|
|
984
|
+
if (!complete.length)
|
|
985
|
+
throw new SourceError(text);
|
|
986
|
+
throw new PartialSourceError(`${text} Valid records were retained; collection remains incomplete and its checkpoint was not advanced.`, complete, undefined, packageResults);
|
|
987
|
+
}
|
|
988
|
+
if (problems.length) {
|
|
989
|
+
// A listing entry that could not be read at all, or more unread records than are remembered:
|
|
990
|
+
// the checkpoint stays, and the next poll reads the listing from it again.
|
|
991
|
+
if (holding && owed && !complete.length)
|
|
992
|
+
throw new SourceError(problems.join(' '));
|
|
993
|
+
if (holding)
|
|
994
|
+
throw new PartialSourceError(owed || unsent
|
|
995
|
+
? `${problems.join(' ')} Valid records were retained; collection remains incomplete and its checkpoint was not advanced.`
|
|
996
|
+
: problems.join(' '), complete, undefined, packageResults);
|
|
997
|
+
// Everything listed up to `resume` was read, is remembered as still to be read, or was reported
|
|
998
|
+
// and given up on: the checkpoint moves.
|
|
999
|
+
throw new PartialSourceError(problems.join(' '), complete, timestamp(resume), packageResults);
|
|
1000
|
+
}
|
|
1001
|
+
return complete;
|
|
413
1002
|
}
|