@shieldaai/security-watch 1.1.1 → 1.2.1

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/dist/epss.js ADDED
@@ -0,0 +1,166 @@
1
+ /**
2
+ * EPSS (FIRST's Exploit Prediction Scoring System): the estimated probability that a CVE is
3
+ * exploited in the next 30 days. Shown with a finding; it decides nothing. FIRST updates scores
4
+ * daily, so they are kept apart from everything that makes a finding revision, a review or a model
5
+ * analysis: a new score never re-sends an alert or reopens a review.
6
+ *
7
+ * Only CVE identifiers are sent, to `api.first.org`. No inventory data.
8
+ */
9
+ const ENDPOINT = 'https://api.first.org/data/v1/epss';
10
+ /** The API answers at most 100 rows a page; 50 identifiers keep one request one page. */
11
+ const BATCH = 50;
12
+ /** Requests per scan; the rest wait for the next scan, the longest unrefreshed first. */
13
+ const MAX_REQUESTS = 10;
14
+ /** A score is refreshed once a day, as FIRST publishes them. */
15
+ const REFRESH_MS = 86_400_000;
16
+ /** Identifiers kept at most. */
17
+ const MAX_IDENTIFIERS = 20_000;
18
+ /**
19
+ * A CVE no current finding needs is kept this long after its last lookup, so a scan without
20
+ * findings (an empty inventory for a moment) does not throw every score away.
21
+ */
22
+ const KEEP_UNUSED_MS = 30 * 86_400_000;
23
+ /** A score a successful answer left out is kept while FIRST's date is this recent. */
24
+ const KEEP_OMITTED_MS = 7 * 86_400_000;
25
+ const CVE = /^CVE-\d{4}-\d{4,19}$/;
26
+ const DATE = /^\d{4}-\d{2}-\d{2}$/;
27
+ /** Reads a stored cache, dropping anything malformed rather than failing the scan. */
28
+ export function readEpssCache(value) {
29
+ const cache = {};
30
+ if (!value)
31
+ return cache;
32
+ let parsed;
33
+ try {
34
+ parsed = JSON.parse(value);
35
+ }
36
+ catch {
37
+ return cache;
38
+ }
39
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
40
+ return cache;
41
+ for (const [id, raw] of Object.entries(parsed)) {
42
+ if (!CVE.test(id) || !raw || typeof raw !== 'object')
43
+ continue;
44
+ const entry = raw;
45
+ if (typeof entry.fetched !== 'number' || !Number.isFinite(entry.fetched))
46
+ continue;
47
+ const score = validScore(entry.score);
48
+ cache[id] = score ? { fetched: entry.fetched, score } : { fetched: entry.fetched };
49
+ }
50
+ return cache;
51
+ }
52
+ function validScore(value) {
53
+ if (!value || typeof value !== 'object')
54
+ return undefined;
55
+ const { probability, percentile, date } = value;
56
+ return typeof probability === 'number' &&
57
+ probability >= 0 &&
58
+ probability <= 1 &&
59
+ typeof percentile === 'number' &&
60
+ percentile >= 0 &&
61
+ percentile <= 1 &&
62
+ typeof date === 'string' &&
63
+ DATE.test(date)
64
+ ? { probability, percentile, date }
65
+ : undefined;
66
+ }
67
+ /** One row of the API's `data` array, or undefined when it is not one. */
68
+ function row(value) {
69
+ if (!value || typeof value !== 'object')
70
+ return undefined;
71
+ const { cve, epss, percentile, date } = value;
72
+ if (typeof cve !== 'string' || !CVE.test(cve.toUpperCase()))
73
+ return undefined;
74
+ // The API writes numbers as strings ("0.016400000").
75
+ const probability = typeof epss === 'string' && /^\d(?:\.\d{1,12})?$/.test(epss) ? Number(epss) : NaN;
76
+ const rank = typeof percentile === 'string' && /^\d(?:\.\d{1,12})?$/.test(percentile) ? Number(percentile) : NaN;
77
+ const score = validScore({ probability, percentile: rank, date });
78
+ return score ? { cve: cve.toUpperCase(), score } : undefined;
79
+ }
80
+ /**
81
+ * Looks up the CVEs that are due: never looked up, or looked up more than a day ago, the oldest
82
+ * first, in batches, within the scan's request budget. The first failure ends the lookups of this
83
+ * scan. The returned cache holds only the given CVEs.
84
+ */
85
+ export async function refreshEpss(identifiers, stored, http, now) {
86
+ const wanted = [...new Set(identifiers.map((id) => id.toUpperCase()).filter((id) => CVE.test(id)))].slice(0, MAX_IDENTIFIERS);
87
+ const cache = {};
88
+ for (const id of wanted)
89
+ if (stored[id])
90
+ cache[id] = stored[id];
91
+ const due = wanted
92
+ .filter((id) => !cache[id] || !(cache[id].fetched <= now) || now - cache[id].fetched >= REFRESH_MS)
93
+ .sort((a, b) => (cache[a]?.fetched ?? -1) - (cache[b]?.fetched ?? -1) || a.localeCompare(b));
94
+ let failed = 0;
95
+ let sent = 0;
96
+ for (let index = 0; index < due.length && sent < MAX_REQUESTS; index += BATCH) {
97
+ const batch = due.slice(index, index + BATCH);
98
+ sent++;
99
+ try {
100
+ const response = await http(`${ENDPOINT}?cve=${batch.join(',')}`, {
101
+ maxBytes: 200_000,
102
+ headers: { accept: 'application/json' },
103
+ });
104
+ if (response.status !== 200)
105
+ throw new Error('EPSS_HTTP');
106
+ const body = JSON.parse(response.body);
107
+ if (body.status !== 'OK' || !Array.isArray(body.data))
108
+ throw new Error('EPSS_SCHEMA');
109
+ const scores = new Map();
110
+ for (const item of body.data) {
111
+ const parsed = row(item);
112
+ if (parsed && batch.includes(parsed.cve))
113
+ scores.set(parsed.cve, parsed.score);
114
+ }
115
+ for (const id of batch) {
116
+ // A CVE FIRST has scored before and leaves out once keeps its recent score; the date shows its age.
117
+ const earlier = cache[id]?.score;
118
+ const score = scores.get(id) ??
119
+ (earlier && now - Date.parse(`${earlier.date}T00:00:00Z`) <= KEEP_OMITTED_MS ? earlier : undefined);
120
+ cache[id] = score ? { fetched: now, score } : { fetched: now };
121
+ }
122
+ }
123
+ catch {
124
+ // A cancelled scan fails here too; the engine checks for cancellation right after.
125
+ failed++;
126
+ break;
127
+ }
128
+ }
129
+ const pending = wanted.filter((id) => !cache[id] || !(cache[id].fetched <= now) || now - cache[id].fetched >= REFRESH_MS).length;
130
+ // Recently looked-up CVEs that no current finding needs, the most recent first, within the bound.
131
+ const unused = Object.entries(stored)
132
+ .filter(([id, entry]) => !(id in cache) && entry.fetched <= now && now - entry.fetched < KEEP_UNUSED_MS)
133
+ .sort(([, a], [, b]) => b.fetched - a.fetched)
134
+ .slice(0, Math.max(0, MAX_IDENTIFIERS - Object.keys(cache).length));
135
+ for (const [id, entry] of unused)
136
+ cache[id] = entry;
137
+ return { cache, failed, pending };
138
+ }
139
+ /**
140
+ * The CVEs a finding is about: its event when that is a CVE, and the CVE aliases of its advisory and
141
+ * known-exploited evidence (a library finding is often keyed by its GHSA identifier). Not the CVEs a
142
+ * news story cites: a roundup cites many.
143
+ */
144
+ export function findingCves(assessment, evidence) {
145
+ const ids = [assessment.event_id];
146
+ for (const id of assessment.evidence_ids) {
147
+ const item = evidence.get(id);
148
+ if (item && item.kind !== 'news' && item.kind !== 'health')
149
+ ids.push(...item.aliases);
150
+ }
151
+ return [...new Set(ids.map((id) => id.toUpperCase()).filter((id) => CVE.test(id)))].sort();
152
+ }
153
+ /**
154
+ * The finding with the cached score of its CVE, or the highest of its CVEs' scores, or without
155
+ * one. Never part of its conclusion.
156
+ */
157
+ export function attachEpss(assessment, cache, cves) {
158
+ const { epss: _old, ...rest } = assessment;
159
+ let best;
160
+ for (const cve of cves) {
161
+ const score = cache[cve.toUpperCase()]?.score;
162
+ if (score && (!best || score.probability > best.probability))
163
+ best = { cve: cve.toUpperCase(), ...score };
164
+ }
165
+ return best ? { ...rest, epss: best } : rest;
166
+ }
package/dist/heartbeat.js CHANGED
@@ -5,7 +5,10 @@ export class HeartbeatMonitor {
5
5
  nextAt = 0;
6
6
  async tick(store, config, http, now = Date.now(), signal) {
7
7
  const settings = config.monitoring;
8
- if (!settings || signal?.aborted || now < this.nextAt)
8
+ if (!settings || signal?.aborted)
9
+ return undefined;
10
+ // A next time further away than one interval means the clock was set back.
11
+ if (now < this.nextAt && this.nextAt - now <= settings.interval_seconds * 1000)
9
12
  return undefined;
10
13
  this.nextAt = now + settings.interval_seconds * 1000;
11
14
  let lastSuccess = null;
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export type { Severity, Category, Applicability, Channel, Provenance, DeploymentObservation, ArtifactKind, DeclaredVerification, DependencyLink, DependencyRelationship, DeclaredRemediation, InventoryEvidence, Component, Product, FindingLocation, System, Inventory, PackageClaim, CvssV4BaseScore, Evidence, ModelSpec, Config, Rule, Assessment, AiReviewReason, AiReview, Decision, Notification, HttpOptions, HttpResult, HttpClient, CoverageReceipt, InventoryDrift, RemediationEvidence, SourceResult, AiAnalysis, NewsAnalysis, } from './types.js';
1
+ export type { Severity, Category, Applicability, Channel, Provenance, DeploymentObservation, ArtifactKind, DeclaredVerification, DependencyLink, DependencyRelationship, DeclaredRemediation, InventoryEvidence, Component, Product, FindingLocation, System, Inventory, PackageClaim, CvssV4BaseScore, Evidence, ModelSpec, Config, Rule, Assessment, AiReviewReason, AiReview, Decision, Notification, HttpOptions, HttpResult, HttpClient, CoverageReceipt, InventoryDrift, RemediationEvidence, SourceResult, AiAnalysis, NewsAnalysis, NewsSignals, NewsStatement, EpssScore, } from './types.js';
2
2
  export { scorePilotResponses, type PilotResponseRegister, type PilotResponseScore, } from './pilot-responses.js';
3
3
  export { loadConfig, parseConfig, configSchema } from './config.js';
4
4
  export { loadInventory } from './inventory.js';
package/dist/inventory.js CHANGED
@@ -187,7 +187,7 @@ function record(value) {
187
187
  }
188
188
  /** Imports metadata only. No install scripts or package manager commands are executed. */
189
189
  function importLockfile(path) {
190
- const lock = JSON.parse(readBounded(path, 20 * 1024 * 1024));
190
+ const lock = JSON.parse(readBounded(path, 20 * 1024 * 1024).replace(/^\uFEFF/, ''));
191
191
  if (!record(lock) || (lock.lockfileVersion !== 2 && lock.lockfileVersion !== 3) || !record(lock.packages)) {
192
192
  throw new Error(`Expected package-lock v2 or v3 with a packages map: ${path}`);
193
193
  }
package/dist/manifests.js CHANGED
@@ -93,14 +93,12 @@ const npmPackageLock = (text) => {
93
93
  if (!record(value))
94
94
  continue;
95
95
  const version = string(value.version) ? value.version : undefined;
96
- if (version?.startsWith('npm:')) {
97
- const target = npmSpecifier(name, version);
98
- packages.push(found('npm', target.name, target.range, value.dev === true));
99
- }
100
- else if (version && /^(?:file|link|git|git\+|https?):/.test(version))
96
+ // `npm:` aliases, and Git (`github:user/repo#sha`), file and URL sources, as in package.json.
97
+ const target = version === undefined ? { name, range: undefined } : npmSpecifier(name, version);
98
+ if (!target)
101
99
  skipped++;
102
100
  else
103
- packages.push(found('npm', name, version, value.dev === true));
101
+ packages.push(found('npm', target.name, target.range, value.dev === true));
104
102
  visit(value.dependencies, depth + 1);
105
103
  }
106
104
  };
@@ -120,8 +118,9 @@ const yarnLock = (text) => {
120
118
  if (fields.resolution !== undefined) {
121
119
  const resolution = unquote(fields.resolution);
122
120
  const match = /^((?:@[^@/]+\/)?[^@]+)@npm:(.+)$/.exec(resolution);
121
+ // `lodash@npm:4.17.21::__archiveUrl=…`: the parameters after `::` are not the version.
123
122
  if (match)
124
- packages.push(found('npm', match[1], match[2]));
123
+ packages.push(found('npm', match[1], match[2].split('::')[0]));
125
124
  else
126
125
  skipped++;
127
126
  return;
@@ -319,7 +318,8 @@ const poetryLock = (text) => {
319
318
  if (!string(table.name))
320
319
  continue;
321
320
  const source = table['source.type'];
322
- if (source && source !== 'legacy') {
321
+ // pdm.lock writes these sources as keys of the package itself.
322
+ if ((source && source !== 'legacy') || table.git || table.path || table.url) {
323
323
  skipped++;
324
324
  continue;
325
325
  }
@@ -411,13 +411,14 @@ const pyprojectToml = (text) => {
411
411
  // ------------------------------------------------------------------------------------- Go and Rust
412
412
  const goMod = (text) => {
413
413
  const required = [];
414
+ // Keyed by module, or by module and version: `replace a v1.0.0 => b v1.1.0` applies to a v1.0.0 only.
414
415
  const replaced = new Map();
415
416
  let block;
416
417
  const replace = (line) => {
417
- const match = /^(\S+)(?:\s+\S+)?\s*=>\s*(\S+)(?:\s+(\S+))?$/.exec(line);
418
+ const match = /^(\S+)(?:\s+(\S+))?\s*=>\s*(\S+)(?:\s+(\S+))?$/.exec(line);
418
419
  if (!match)
419
420
  return;
420
- replaced.set(match[1], /^(?:\.|\/)/.test(match[2]) || !match[3] ? null : { name: match[2], version: match[3] });
421
+ replaced.set(match[2] ? `${match[1]} ${match[2]}` : match[1], /^(?:\.|\/)/.test(match[3]) || !match[4] ? null : { name: match[3], version: match[4] });
421
422
  };
422
423
  for (const raw of text.split(/\r?\n/)) {
423
424
  const line = raw.replace(/\/\/.*$/, '').trim();
@@ -451,7 +452,8 @@ const goMod = (text) => {
451
452
  const packages = [];
452
453
  let skipped = 0;
453
454
  for (const module of required) {
454
- const replacement = replaced.get(module.name);
455
+ const exact = `${module.name} ${module.version}`;
456
+ const replacement = replaced.has(exact) ? replaced.get(exact) : replaced.get(module.name);
455
457
  if (replacement === null)
456
458
  skipped++;
457
459
  else
@@ -948,6 +950,11 @@ function discover(root, warnings) {
948
950
  const locked = new Set(candidates
949
951
  .filter((file) => file.kind === 'lockfile')
950
952
  .map((file) => `${dirname(file.absolute)}\0${file.ecosystem}`));
953
+ // A requirements file often lists only some packages (requirements-dev.txt), so it does not hide
954
+ // the pyproject.toml beside it: that is read like a workspace member, for what the file lacks.
955
+ const resolved = new Set(candidates
956
+ .filter((file) => file.kind === 'lockfile' && file.read !== requirementsTxt)
957
+ .map((file) => `${dirname(file.absolute)}\0${file.ecosystem}`));
951
958
  const coveredBy = (file) => {
952
959
  for (let folder = dirname(dirname(file.absolute)); folder.length >= root.length; folder = dirname(folder)) {
953
960
  if (locked.has(`${folder}\0${file.ecosystem}`))
@@ -958,8 +965,11 @@ function discover(root, warnings) {
958
965
  return false;
959
966
  };
960
967
  return candidates
961
- .filter((file) => file.kind === 'lockfile' || !locked.has(`${dirname(file.absolute)}\0${file.ecosystem}`))
962
- .map((file) => (file.kind === 'manifest' && coveredBy(file) ? { ...file, workspace: true } : file))
968
+ .filter((file) => file.kind === 'lockfile' || !resolved.has(`${dirname(file.absolute)}\0${file.ecosystem}`))
969
+ .map((file) => file.kind === 'manifest' &&
970
+ (coveredBy(file) || locked.has(`${dirname(file.absolute)}\0${file.ecosystem}`))
971
+ ? { ...file, workspace: true }
972
+ : file)
963
973
  .sort((a, b) => Number(a.kind === 'manifest') - Number(b.kind === 'manifest'));
964
974
  }
965
975
  // ---------------------------------------------------------------------------------------- Package URLs
@@ -13,6 +13,12 @@ export declare function packageMentioned(text: string, component: {
13
13
  ecosystem: Ecosystem;
14
14
  name: string;
15
15
  }): boolean;
16
+ /**
17
+ * Where a sentence ends: after ".", "!" or "?" and before a capital letter or a digit, but not after
18
+ * a common abbreviation ("e.g.", "i.e.", "incl.", "vs.") or a single lower-case letter. After "etc." and
19
+ * initials ("the U.S. Package scams") it does end.
20
+ */
21
+ export declare const SENTENCE_END: RegExp;
16
22
  export interface InventoryMatcher {
17
23
  /** Identity keys of every inventory component. */
18
24
  packages: Set<string>;
package/dist/matching.js CHANGED
@@ -229,6 +229,12 @@ export function packageMentioned(text, component) {
229
229
  const artifact = mavenArtifact(component);
230
230
  if (artifact && packageMentioned(text, { ecosystem: 'Maven', name: artifact }))
231
231
  return true;
232
+ // PyPI names are kept in their normalised form (`ruamel-yaml`); prose writes the published one,
233
+ // `ruamel.yaml` or `typing_extensions`.
234
+ if (component.ecosystem === 'PyPI' && name.includes('-'))
235
+ for (const separator of ['.', '_'])
236
+ if (packageMentioned(text, { ecosystem: 'PyPI', name: name.replaceAll('-', separator) }))
237
+ return true;
232
238
  // One story is compared with every component, and a story that cites many advisories is
233
239
  // compared again for each of them: remember the answers for the texts seen last.
234
240
  let seen = recent.get(text);
@@ -390,7 +396,7 @@ const STRONG_LIBRARY_CUE = new RegExp('(?:^|[^\\p{L}])(?:npm|pypi|rubygems|crate
390
396
  * a common abbreviation ("e.g.", "i.e.", "incl.", "vs.") or a single lower-case letter. After "etc." and
391
397
  * initials ("the U.S. Package scams") it does end.
392
398
  */
393
- const SENTENCE_END = /(?<=[.!?])(?<!(?:^|[^\p{L}])(?:e\.g|i\.e|incl|vs|approx|cf|al|ca|no|nr|ver|v|\p{Ll})\.)\s+(?=[\p{Lu}\p{N}])/u;
399
+ export const SENTENCE_END = /(?<=[.!?])(?<!(?:^|[^\p{L}])(?:e\.g|i\.e|incl|vs|approx|cf|al|ca|no|nr|ver|v|\p{Ll})\.)\s+(?=[\p{Lu}\p{N}])/u;
394
400
  /** Words that name a flaw. */
395
401
  const FLAW_NOUN = '(?:flaws?|bugs?|vulnerabilit(?:y|ies)|escapes?|bypass(?:es)?|injections?)';
396
402
  /** Words for the kind of a flaw that may come before it ("remote code execution flaw"). */
@@ -0,0 +1,29 @@
1
+ import type { NewsSignals, Severity } from './types.js';
2
+ /**
3
+ * What a news article states about one finding's subject, read without a model: a CVSS score, a
4
+ * vendor's word rating, a report of exploitation, a public exploit. These only ever raise a
5
+ * finding's priority; a missing or negated statement lowers and dismisses nothing.
6
+ *
7
+ * A statement counts for the subject only when it is tied to it: the nearest advisory identifier
8
+ * before the statement in its sentence is the subject's (`CVE-X (CVSS score: 9.8)`, a list item
9
+ * `CVE-X (CVSS score: 9.3) - text`); or the article cites no other identifier and the sentence names
10
+ * the subject; or, for a score or rating, the article is about the subject alone and the sentence
11
+ * cites nothing. "It scores all five 9.2" in an article about five flaws is not read.
12
+ */
13
+ export interface SignalTarget {
14
+ /** Advisory identifiers of the finding's event, in any spelling. */
15
+ identifiers: string[];
16
+ /** Inventory names the finding matched: package, product and keyword names. */
17
+ names: string[];
18
+ }
19
+ export declare function scoreLevel(score: number): Severity;
20
+ /** Reads the articles for one finding. `undefined` when they state nothing about its subject. */
21
+ export declare function newsSignals(articles: readonly {
22
+ title: string;
23
+ description: string;
24
+ }[], target: SignalTarget): NewsSignals | undefined;
25
+ /** The level the signals give a finding, and one reason per signal, for the finding's reasons. */
26
+ export declare function signalLevel(signals: NewsSignals): {
27
+ level: Severity;
28
+ reasons: string[];
29
+ };
@@ -0,0 +1,271 @@
1
+ import { mentions, SENTENCE_END } from './matching.js';
2
+ import { cut, highest } from './util.js';
3
+ const IDENTIFIER = /\b(?:CVE-\d{4}-\d{4,19}|GHSA-[a-z\d]{4}-[a-z\d]{4}-[a-z\d]{4})\b/gi;
4
+ const normal = (id) => (/^cve-/i.test(id) ? id.toUpperCase() : id.toLowerCase());
5
+ /** At most this much of an article is read, and this many sentences. */
6
+ const MAX_TEXT = 40_000;
7
+ const MAX_SENTENCES = 2_000;
8
+ const EXCERPT = 160;
9
+ /** How far before a statement a hedging word counts. */
10
+ const HEDGE_WINDOW = 60;
11
+ /** How far after a report of exploitation its identifier may stand. */
12
+ const FOLLOWING_WINDOW = 160;
13
+ /**
14
+ * "CVSS score: 9.8", "CVSS v3.1 score of 9.8", "CVSSv4: 9.3", "CVSS 3.1: 5.5", "(CVSS 9.8)". A whole
15
+ * number counts only after "score" or "rating" or a colon: "CVSS v4 metrics" names a version.
16
+ */
17
+ const SCORE_AFTER = /^CVSS\s*(?:v(?:ersion)?\s*)?([234](?:\.[01])?)?\s*(?:\(\s*v?[234]\.[01]\s*\)\s*)?(?:[-:,\s]*(?:base|severity|risk|overall)\b)?(?:[-:,\s]*(score|rating)\b)?(?:\s+(?:of|is|was|at))?([\s:=]*)(\d{1,2}(?:\.\d)?)(?![\d%]|\.\d)/i;
18
+ /** A threshold, not a score: "a CVSS score of 7 or higher", "CVSS 9.0+". */
19
+ const THRESHOLD_AFTER = /^\s*(?:\+|(?:or|and)\s+(?:higher|above|more|greater|over|up|lower|less|below))/i;
20
+ const THRESHOLD_BEFORE = /\b(?:above|over|below|at least|at most|exceed(?:s|ing)?|greater than|less than|higher than|lower than|threshold|minimum|maximum)\s+(?:(?:an?|the)\s+)?$/i;
21
+ /** "9.2 CVSS rating", "9.2 out of 10 on CVSS 4.0", "rated 9.8/10 under the CVSS scale". */
22
+ const SCORE_BEFORE = /(?<![\d.])(\d{1,2}\.\d|10(?=\s*\/\s*10|\s+out of 10)|\d(?=\s*\/\s*10|\s+out of 10))(?:\s*\/\s*10|\s+out of 10)?(?:\s+(?:on|under|in|with|using))?(?:\s+the)?\s+$/i;
23
+ /** What may follow "CVSS" after a score written before it: a version, then a noun or the end. */
24
+ const AFTER_SCORE_BEFORE = /^CVSS\s*(?:v(?:ersion)?\s*)?(?:[234](?:\.[01])?)?\s*(?:score|rating|scale|base|severity|\(|[.,;)]|$)/i;
25
+ /** The CVSS version right after "CVSS", when a score came before it ("on CVSS 4.0"). */
26
+ const VERSION_AFTER = /^CVSS\s*(?:v(?:ersion)?\s*)?([234]\.[01])(?!\.?\d)/i;
27
+ /** A vendor's own word rating: "Severity: moderate" (Apache), "rated the vulnerability Important". */
28
+ const RATINGS = [
29
+ /\bseverity\s*:\s*(low|moderate|medium|important|high|critical)\b/i,
30
+ /\brat(?:ed|es)\s+(?:(?:it|this|the\s+(?:flaw|vulnerability|bug|issue)|CVE-\d{4}-\d{4,19}|GHSA(?:-[a-z\d]{4}){3})\s+)?(?:as\s+)?(?:an?\s+)?(low|moderate|medium|important|high|critical)\b(?![-\s]*(?:risk|rated|severity))/i,
31
+ ];
32
+ /** Statements that a subject is being exploited. Bound, not negated and not hedged to count. */
33
+ const EXPLOITED = new RegExp([
34
+ 'exploited in (?:the wild|attacks?|real[- ]world attacks)',
35
+ '(?:under|come under|subject to) (?:active )?(?:exploitation|attacks?)',
36
+ 'actively (?:being )?exploited',
37
+ 'active exploitation',
38
+ 'exploitation (?:attempts|activity)',
39
+ 'in-the-wild exploitation',
40
+ 'exploitation in the wild',
41
+ '(?:detected|observed|confirmed|seen|reported) (?:active |in-the-wild )?exploitation',
42
+ '(?:attackers|hackers|threat actors|adversaries|bad (?:guys|actors)|miscreants|criminals|crooks) (?:are |were |have been |had been |have |had )?(?:actively |now )?(?:exploiting|exploited|weaponi[sz]ing|abusing)',
43
+ 'used in (?:the wild|attacks|real[- ]world attacks)',
44
+ '(?:is|are|was|were|being|been) (?:actively |now |still )?(?:being )?exploited',
45
+ 'added\\b.{0,160}?(?:Known Exploited Vulnerabilities|\\bKEV\\b)',
46
+ ].join('|'), 'i');
47
+ /**
48
+ * Read only to recognise a denial ("not aware of attacks exploiting the flaw"). On its own it is
49
+ * not a report: researchers publish "videos demonstrating attacks using" a flaw.
50
+ */
51
+ const DENIED_ONLY = /\battacks? (?:exploiting|using|leveraging|targeting)/i;
52
+ /** Public exploit code: shown as a reason, it raises nothing. */
53
+ const PUBLIC_EXPLOIT = /proof[- ]of[- ]concept|\bPoC\b|exploit code|public(?:ly available)? exploits?\b|working exploits?\b|exploits? (?:is|was|were|has been|have been) (?:released|published)/i;
54
+ /**
55
+ * A denial of the statement that follows in the same clause: "no evidence that ... has been
56
+ * exploited", "neither ... nor ... report that it was used in attacks". "Without authentication"
57
+ * and "no patch" after a report do not deny it.
58
+ */
59
+ const NEGATION = /\b(?:no|not|never|neither|nor|none|nothing|nobody|no one|unaware|yet to|absence|lack of)\b|n['’]t\b/i;
60
+ /** How far before a statement a denial counts, within its clause. */
61
+ const NEGATION_WINDOW = 160;
62
+ /** Where a clause ends inside a sentence: "X was patched, but attackers exploit Y". */
63
+ const CLAUSE_BREAK = /;|,\s*(?:but|while|whereas|although|though|yet|and|or|so)\b|\s(?:but|while|whereas|although)\s|\s[–—]\s/gi;
64
+ /** Reports whose identifier follows them: "attackers are exploiting CVE-A", "added CVE-A to KEV". */
65
+ const OBJECT_FOLLOWS = /^(?:attackers|hackers|threat actors|adversaries|bad|miscreants|criminals|crooks|added|detected|observed|confirmed|seen|reported|exploitation|in-the-wild|proof|poc|exploit|public|working)/i;
66
+ /** Words just before a statement that only suppose it: "could be exploited", "suspected to be exploiting". */
67
+ const HEDGE = /\b(?:could|may|might|can|would|should|if|potential(?:ly)?|possibl[ey]|suspect(?:ed|s)?|alleged(?:ly)?|claims?|likely|unconfirmed|whether|unless|expects?)\b/i;
68
+ function sentences(text) {
69
+ const out = [];
70
+ for (const line of text.slice(0, MAX_TEXT).split(/\n+/)) {
71
+ for (const sentence of line.split(SENTENCE_END)) {
72
+ const trimmed = sentence.trim();
73
+ if (trimmed)
74
+ out.push(trimmed);
75
+ if (out.length >= MAX_SENTENCES)
76
+ return out;
77
+ }
78
+ }
79
+ return out;
80
+ }
81
+ export function scoreLevel(score) {
82
+ return score >= 9
83
+ ? 'critical'
84
+ : score >= 7
85
+ ? 'high'
86
+ : score >= 4
87
+ ? 'medium'
88
+ : score > 0
89
+ ? 'low'
90
+ : 'unknown';
91
+ }
92
+ function ratingLevel(word) {
93
+ const value = word.toLowerCase();
94
+ return value === 'critical'
95
+ ? 'critical'
96
+ : value === 'high' || value === 'important'
97
+ ? 'high'
98
+ : value === 'moderate' || value === 'medium'
99
+ ? 'medium'
100
+ : 'low';
101
+ }
102
+ /** Reads the articles for one finding. `undefined` when they state nothing about its subject. */
103
+ export function newsSignals(articles, target) {
104
+ const targets = new Set(target.identifiers.map(normal));
105
+ const names = [...new Set(target.names.filter((name) => name.trim().length >= 3))];
106
+ const signals = {};
107
+ for (const article of articles) {
108
+ const text = `${article.title}\n${article.description}`;
109
+ const cited = new Set((text.slice(0, MAX_TEXT).match(IDENTIFIER) ?? []).map(normal));
110
+ // Every identifier the article cites is this finding's: a sentence naming the subject is about it.
111
+ const singleSubject = [...cited].every((id) => targets.has(id));
112
+ /**
113
+ * An article about one subject: it cites one identifier, the finding's, or none and names the
114
+ * subject in its title (ZDI: "ZDI-26-1037: (0Day) Acme Router ... Vulnerability"). A score or
115
+ * rating in a sentence that cites nothing is about that subject ("The ZDI has assigned a CVSS
116
+ * rating of 7.6", "CISA gives the flaw a CVSS score of 5.0"). Not used for exploitation.
117
+ */
118
+ const articleSubject = !singleSubject
119
+ ? undefined
120
+ : cited.size === 1
121
+ ? [...cited][0]
122
+ : cited.size === 0
123
+ ? names.find((name) => mentions(article.title, name))
124
+ : undefined;
125
+ for (const sentence of sentences(text)) {
126
+ if (sentence.endsWith('?'))
127
+ continue; // "Is there a proof-of-concept available?"
128
+ const ids = [...sentence.matchAll(IDENTIFIER)].map((m) => ({ at: m.index, id: normal(m[0]) }));
129
+ const breaks = [...sentence.matchAll(CLAUSE_BREAK)].map((m) => m.index);
130
+ const clause = (at) => [
131
+ breaks.filter((index) => index < at).at(-1) ?? 0,
132
+ breaks.find((index) => index >= at) ?? sentence.length,
133
+ ];
134
+ /** An inventory name in the clause around `at`, when the article cites only the finding's identifiers. */
135
+ const namedIn = (at) => {
136
+ if (!singleSubject)
137
+ return undefined;
138
+ const [start, end] = clause(at);
139
+ const part = sentence.slice(start, end);
140
+ return names.find((name) => mentions(part, name));
141
+ };
142
+ /** A score or rating: the nearest identifier before it, as in lists; or a name in its clause. */
143
+ const boundScore = (at) => {
144
+ const nearest = ids.filter((item) => item.at < at).at(-1);
145
+ if (nearest)
146
+ return targets.has(nearest.id) ? nearest.id : undefined;
147
+ return ids.length ? undefined : namedIn(at);
148
+ };
149
+ /**
150
+ * A report: an identifier in its own clause, the one it names when the report reads
151
+ * "attackers are exploiting CVE-A" or "added CVE-A to KEV", else the nearest before it ("CVE-A
152
+ * is being exploited"), else shortly after it ("X has come under active exploitation ...,
153
+ * tracked as CVE-A"). With no identifier in its clause and none in the sentence, a name in its
154
+ * clause.
155
+ */
156
+ const boundReport = (match) => {
157
+ const [start, end] = clause(match.index);
158
+ const inClause = ids.filter((item) => item.at >= start && item.at < end);
159
+ const after = inClause.find((item) => item.at >= match.index && item.at - match.index <= FOLLOWING_WINDOW);
160
+ const before = inClause.filter((item) => item.at < match.index).at(-1);
161
+ const nearest = OBJECT_FOLLOWS.test(match[0]) ? (after ?? before) : (before ?? after);
162
+ if (nearest)
163
+ return targets.has(nearest.id) ? nearest.id : undefined;
164
+ return ids.length ? undefined : namedIn(match.index);
165
+ };
166
+ /** A denial before the statement, in its clause. */
167
+ const negated = (match) => {
168
+ const [start] = clause(match.index);
169
+ return NEGATION.test(sentence.slice(Math.max(start, match.index - NEGATION_WINDOW), match.index + match[0].length));
170
+ };
171
+ const excerpt = () => cut(sentence.replace(/\s+/g, ' '), EXCERPT);
172
+ for (const match of sentence.matchAll(/CVSS/gi)) {
173
+ const at = match.index;
174
+ const after = SCORE_AFTER.exec(sentence.slice(at, at + 80));
175
+ let score;
176
+ let version;
177
+ if (after) {
178
+ const [, written, word, separator, number] = after;
179
+ // "CVSS 4.0" names a version; it is a score only after "score" or "rating".
180
+ const isVersion = !written && !word && /^[234]\.[01]$/.test(number);
181
+ const stated = Boolean(word) || /[:=]/.test(separator) || number.includes('.');
182
+ const threshold = THRESHOLD_AFTER.test(sentence.slice(at + after[0].length, at + after[0].length + 20)) ||
183
+ THRESHOLD_BEFORE.test(sentence.slice(Math.max(0, at - 30), at));
184
+ if (!isVersion && stated && !threshold) {
185
+ score = Number(number);
186
+ version = written;
187
+ }
188
+ }
189
+ if (score === undefined && AFTER_SCORE_BEFORE.test(sentence.slice(at, at + 40))) {
190
+ const before = SCORE_BEFORE.exec(sentence.slice(Math.max(0, at - 40), at));
191
+ if (before) {
192
+ score = Number(before[1]);
193
+ version = VERSION_AFTER.exec(sentence.slice(at, at + 20))?.[1];
194
+ }
195
+ }
196
+ if (score === undefined || !(score > 0 && score <= 10))
197
+ continue;
198
+ const subject = boundScore(at) ?? (ids.length ? undefined : articleSubject);
199
+ if (!subject)
200
+ continue;
201
+ if (!signals.cvss || score > signals.cvss.score)
202
+ signals.cvss = {
203
+ score,
204
+ ...(version ? { version: version.includes('.') ? version : `${version}.x` } : {}),
205
+ level: scoreLevel(score),
206
+ subject,
207
+ excerpt: excerpt(),
208
+ };
209
+ }
210
+ for (const pattern of RATINGS) {
211
+ const match = pattern.exec(sentence);
212
+ if (!match)
213
+ continue;
214
+ // A "Severity:" field stands on a line of its own in Apache advisories.
215
+ const subject = boundScore(match.index + match[0].length) ?? (ids.length ? undefined : articleSubject);
216
+ if (!subject)
217
+ continue;
218
+ const level = ratingLevel(match[1]);
219
+ if (!signals.rating || highest(level, signals.rating.level) !== signals.rating.level)
220
+ signals.rating = { level, word: match[1].toLowerCase(), subject, excerpt: excerpt() };
221
+ }
222
+ // A denial counts before the statement in its clause; a hedge only just before it, since a
223
+ // merged sentence often goes on to "could".
224
+ const hedged = (match) => HEDGE.test(sentence.slice(Math.max(0, match.index - HEDGE_WINDOW), match.index + match[0].length));
225
+ for (const pattern of [EXPLOITED, DENIED_ONLY]) {
226
+ for (const match of sentence.matchAll(new RegExp(pattern.source, 'gi'))) {
227
+ const denied = negated(match);
228
+ if (!denied && (pattern === DENIED_ONLY || hedged(match)))
229
+ continue;
230
+ const subject = boundReport(match);
231
+ if (!subject)
232
+ continue;
233
+ if (denied)
234
+ signals.no_known_exploitation ??= { subject, excerpt: excerpt() };
235
+ else
236
+ signals.exploitation ??= { subject, excerpt: excerpt() };
237
+ }
238
+ }
239
+ for (const exploit of sentence.matchAll(new RegExp(PUBLIC_EXPLOIT.source, 'gi'))) {
240
+ if (negated(exploit) || hedged(exploit))
241
+ continue;
242
+ const subject = boundReport(exploit);
243
+ if (subject)
244
+ signals.public_exploit ??= { subject, excerpt: excerpt() };
245
+ }
246
+ }
247
+ }
248
+ return Object.keys(signals).length ? signals : undefined;
249
+ }
250
+ /** The level the signals give a finding, and one reason per signal, for the finding's reasons. */
251
+ export function signalLevel(signals) {
252
+ const reasons = [];
253
+ let level = 'unknown';
254
+ if (signals.cvss) {
255
+ level = highest(level, signals.cvss.level);
256
+ reasons.push(`An article states CVSS ${signals.cvss.version ? `${signals.cvss.version} ` : ''}${signals.cvss.score} for ${signals.cvss.subject}; no advisory severity is available yet.`);
257
+ }
258
+ if (signals.rating) {
259
+ level = highest(level, signals.rating.level);
260
+ reasons.push(`An article reports a "${signals.rating.word}" rating for ${signals.rating.subject}.`);
261
+ }
262
+ if (signals.exploitation) {
263
+ level = highest(level, 'critical');
264
+ reasons.push(`An article reports exploitation of ${signals.exploitation.subject}; not confirmed by a known-exploited catalog.`);
265
+ }
266
+ else if (signals.no_known_exploitation)
267
+ reasons.push(`An article says no exploitation of ${signals.no_known_exploitation.subject} is known.`);
268
+ if (signals.public_exploit)
269
+ reasons.push(`An article reports public exploit code for ${signals.public_exploit.subject}.`);
270
+ return { level, reasons };
271
+ }
@@ -56,7 +56,8 @@ export class MaintenanceScheduler {
56
56
  attempted +
57
57
  (previous.ok ? settings.interval_hours : Math.min(settings.interval_hours, 1)) * 3_600_000;
58
58
  }
59
- if (now < this.nextAt)
59
+ // A next time further away than one interval means the clock was set back.
60
+ if (now < this.nextAt && this.nextAt - now <= settings.interval_hours * 3_600_000)
60
61
  return undefined;
61
62
  this.nextAt = now + Math.min(settings.interval_hours, 1) * 3_600_000;
62
63
  const report = {