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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/CONTRIBUTING.md +90 -0
  2. package/LICENSE +202 -0
  3. package/README.md +269 -2
  4. package/SECURITY.md +47 -0
  5. package/dist/assessment.d.ts +5 -0
  6. package/dist/assessment.js +398 -0
  7. package/dist/cli.d.ts +2 -0
  8. package/dist/cli.js +792 -0
  9. package/dist/config.d.ts +242 -0
  10. package/dist/config.js +298 -0
  11. package/dist/cve-now.d.ts +5 -0
  12. package/dist/cve-now.js +413 -0
  13. package/dist/delivery.d.ts +26 -0
  14. package/dist/delivery.js +394 -0
  15. package/dist/ecosystems.d.ts +25 -0
  16. package/dist/ecosystems.js +254 -0
  17. package/dist/engine.d.ts +26 -0
  18. package/dist/engine.js +307 -0
  19. package/dist/health.d.ts +17 -0
  20. package/dist/health.js +70 -0
  21. package/dist/heartbeat.d.ts +13 -0
  22. package/dist/heartbeat.js +74 -0
  23. package/dist/http.d.ts +8 -0
  24. package/dist/http.js +251 -0
  25. package/dist/index.d.ts +18 -0
  26. package/dist/index.js +15 -0
  27. package/dist/inventory.d.ts +3 -0
  28. package/dist/inventory.js +143 -0
  29. package/dist/lock.d.ts +3 -0
  30. package/dist/lock.js +112 -0
  31. package/dist/maintenance.d.ts +43 -0
  32. package/dist/maintenance.js +227 -0
  33. package/dist/models.d.ts +20 -0
  34. package/dist/models.js +602 -0
  35. package/dist/operations.d.ts +17 -0
  36. package/dist/operations.js +117 -0
  37. package/dist/providers.d.ts +209 -0
  38. package/dist/providers.js +459 -0
  39. package/dist/setup.d.ts +113 -0
  40. package/dist/setup.js +100 -0
  41. package/dist/source-error.d.ts +22 -0
  42. package/dist/source-error.js +56 -0
  43. package/dist/sources.d.ts +3 -0
  44. package/dist/sources.js +1071 -0
  45. package/dist/store.d.ts +71 -0
  46. package/dist/store.js +651 -0
  47. package/dist/types.d.ts +247 -0
  48. package/dist/types.js +1 -0
  49. package/dist/util.d.ts +6 -0
  50. package/dist/util.js +14 -0
  51. package/dist/vendor-sources.d.ts +24 -0
  52. package/dist/vendor-sources.js +56 -0
  53. package/docs/configuration.md +406 -0
  54. package/docs/quality-review.md +104 -0
  55. package/examples/advisories.json +17 -0
  56. package/examples/common-systems.yaml +243 -0
  57. package/examples/libraries.example.txt +16 -0
  58. package/examples/libraries.example.yaml +38 -0
  59. package/examples/library-watch.example.yaml +27 -0
  60. package/examples/security-watch.example.yaml +86 -0
  61. package/examples/systems.example.yaml +31 -0
  62. package/package.json +69 -4
@@ -0,0 +1,413 @@
1
+ import { compare, valid } from 'semver';
2
+ import { cleanText, highest, timestamp } from './util.js';
3
+ import { normalizeEcosystem, normalizePackageName, samePackage } from './ecosystems.js';
4
+ import { SourceError, SourceHttpError, SourceItemFailures, sourceCanceled, throwSourceFailure, } from './source-error.js';
5
+ const ORIGIN = 'https://cve.now';
6
+ const MAX_ENTRIES = 5_000;
7
+ const MAX_PAGES = 200;
8
+ const MAX_DETAIL_FAILURES = 8;
9
+ const HOUR = 3_600_000;
10
+ function object(value) {
11
+ if (!value || typeof value !== 'object' || Array.isArray(value))
12
+ throw new SourceError('cve.now returned an invalid schema.');
13
+ return value;
14
+ }
15
+ function optionalObject(value) {
16
+ return value === null || value === undefined ? {} : object(value);
17
+ }
18
+ function list(value, optional = false) {
19
+ if (value === undefined && optional)
20
+ return [];
21
+ if (!Array.isArray(value))
22
+ throw new SourceError('cve.now returned an invalid schema.');
23
+ return value;
24
+ }
25
+ function text(value) {
26
+ if (typeof value !== 'string' || !value.trim())
27
+ throw new SourceError('cve.now returned an invalid schema.');
28
+ return value;
29
+ }
30
+ function optionalText(value) {
31
+ return value === null || value === undefined ? undefined : text(value);
32
+ }
33
+ function identifier(value) {
34
+ const id = text(value);
35
+ if (!/^[a-z0-9][a-z0-9._-]{2,127}$/i.test(id))
36
+ throw new SourceError('cve.now returned an invalid advisory identifier.');
37
+ return /^(?:CVE|GHSA)-/i.test(id) ? id.toUpperCase() : id;
38
+ }
39
+ function date(value, now) {
40
+ const parsed = Date.parse(text(value));
41
+ if (!Number.isFinite(parsed))
42
+ throw new SourceError('cve.now returned an invalid timestamp.');
43
+ if (parsed > now + 5 * 60_000)
44
+ throw new SourceError('cve.now returned a future timestamp; collection is incomplete.');
45
+ return timestamp(parsed);
46
+ }
47
+ function rating(value) {
48
+ if (typeof value === 'number' && Number.isFinite(value) && value >= 0 && value <= 10)
49
+ return value >= 9
50
+ ? 'critical'
51
+ : value >= 7
52
+ ? 'high'
53
+ : value >= 4
54
+ ? 'medium'
55
+ : value > 0
56
+ ? 'low'
57
+ : 'unknown';
58
+ const normalized = typeof value === 'string' ? value.toLowerCase() : '';
59
+ if (normalized === 'moderate')
60
+ return 'medium';
61
+ return ['critical', 'high', 'medium', 'low'].includes(normalized) ? normalized : 'unknown';
62
+ }
63
+ async function get(http, url, missingAllowed = false) {
64
+ const response = await http(url, { maxBytes: 8_000_000, redirects: 3, minIntervalMs: 1_100 });
65
+ if (missingAllowed && response.status === 404)
66
+ return undefined;
67
+ if (response.status !== 200)
68
+ throw new SourceHttpError('cve.now', response.status);
69
+ let value;
70
+ try {
71
+ value = JSON.parse(response.body);
72
+ }
73
+ catch {
74
+ throw new SourceError('cve.now returned invalid JSON.');
75
+ }
76
+ return object(value);
77
+ }
78
+ // cve.now normalizes OSV/CVE affected ranges to independent intervals. Only
79
+ // explicit npm semver intervals can establish an installed version's exclusion.
80
+ function intervals(value) {
81
+ const ranges = list(value, true);
82
+ if (!ranges.length)
83
+ return {};
84
+ const expressions = [];
85
+ const fixes = [];
86
+ let supported = true;
87
+ for (const raw of ranges) {
88
+ const interval = object(raw);
89
+ const introduced = optionalText(interval.introduced);
90
+ const fixed = optionalText(interval.fixed);
91
+ const last = optionalText(interval.lastAffected);
92
+ // Unsupported bounds must never turn an incomplete range into evidence of safety.
93
+ if (Object.keys(interval).some((key) => !['introduced', 'fixed', 'lastAffected'].includes(key)) ||
94
+ introduced === undefined ||
95
+ (fixed !== undefined && last !== undefined) ||
96
+ (introduced !== '0' && !valid(introduced)) ||
97
+ (fixed !== undefined && !valid(fixed)) ||
98
+ (last !== undefined && !valid(last))) {
99
+ supported = false;
100
+ continue;
101
+ }
102
+ const lower = introduced === '0' ? undefined : valid(introduced);
103
+ const upper = fixed ? valid(fixed) : last ? valid(last) : undefined;
104
+ if (lower &&
105
+ upper &&
106
+ (compare(lower, upper) > 0 || (fixed !== undefined && compare(lower, upper) === 0))) {
107
+ supported = false;
108
+ continue;
109
+ }
110
+ expressions.push([lower && `>=${lower}`, upper && `${fixed ? '<' : '<='}${upper}`].filter(Boolean).join(' ') || '*');
111
+ if (fixed)
112
+ fixes.push(valid(fixed));
113
+ }
114
+ return {
115
+ ...(supported && expressions.length ? { range: expressions.join(' || ') } : {}),
116
+ ...(fixes.length ? { fixed: [...new Set(fixes)].join(', ') } : {}),
117
+ };
118
+ }
119
+ function parseEntry(data, now, expected, matched) {
120
+ const id = identifier(data.id);
121
+ const aliases = [...new Set([id, ...list(data.aliases, true).map(identifier)])];
122
+ if (expected && !aliases.includes(expected))
123
+ throw new SourceError('cve.now returned a mismatched advisory identifier.');
124
+ if (!['published', 'rejected', 'withdrawn'].includes(text(data.status)))
125
+ throw new SourceError('cve.now returned an unsupported advisory status.');
126
+ const packages = [];
127
+ const products = [];
128
+ for (const raw of list(data.affected, true)) {
129
+ const affected = object(raw);
130
+ let name = optionalText(affected.package);
131
+ let ecosystem = optionalText(affected.ecosystem);
132
+ const product = optionalText(affected.product);
133
+ if (product)
134
+ products.push([optionalText(affected.vendor), product].filter(Boolean).join(' '));
135
+ if (!name || !ecosystem)
136
+ continue;
137
+ let knownEcosystem;
138
+ try {
139
+ knownEcosystem = normalizeEcosystem(ecosystem);
140
+ }
141
+ catch {
142
+ /* Other product ecosystems remain source data. */
143
+ }
144
+ if (knownEcosystem) {
145
+ ecosystem = knownEcosystem;
146
+ try {
147
+ name = normalizePackageName(knownEcosystem, name);
148
+ }
149
+ catch {
150
+ throw new SourceError('cve.now returned an invalid package identity.');
151
+ }
152
+ }
153
+ const versions = list(affected.versions, true).map(text);
154
+ packages.push({
155
+ ecosystem,
156
+ name,
157
+ ...(ecosystem.toLowerCase() === 'npm' ? intervals(affected.ranges) : {}),
158
+ ...(versions.length ? { versions } : {}),
159
+ ...(matched && ecosystem.toLowerCase() === 'npm' && name === matched.name
160
+ ? { matched_versions: [matched.version] }
161
+ : {}),
162
+ });
163
+ }
164
+ if (matched && !packages.some((claim) => claim.ecosystem === 'npm' && claim.name === matched.name))
165
+ packages.push({ ecosystem: 'npm', name: matched.name, matched_versions: [matched.version] });
166
+ const original = optionalText(data.originalDescription) ?? '';
167
+ // The summary is model-generated; use the original description as evidence.
168
+ const description = [
169
+ original,
170
+ products.length ? `Reported products: ${[...new Set(products)].join('; ')}` : '',
171
+ ]
172
+ .filter(Boolean)
173
+ .join('\n');
174
+ const score = optionalObject(data.severity);
175
+ const stated = optionalObject(data.statedSeverity);
176
+ const exploitation = optionalObject(data.exploitation);
177
+ const knownExploited = exploitation.kev !== undefined && exploitation.kev !== null;
178
+ if (knownExploited)
179
+ object(exploitation.kev);
180
+ const modified = date(data.modifiedAt ?? data.publishedAt ?? data.firstSeenAt, now);
181
+ const published = data.publishedAt ? date(data.publishedAt, now) : undefined;
182
+ if (data.firstSeenAt)
183
+ date(data.firstSeenAt, now);
184
+ return {
185
+ id: `cve_now:${id}`,
186
+ source: 'cve_now',
187
+ kind: 'advisory',
188
+ title: cleanText(text(data.title), 500),
189
+ description: cleanText(description, 16_000),
190
+ content_status: original && description.length <= 16_000 ? 'full' : description ? 'excerpt' : 'unavailable',
191
+ url: `${ORIGIN}/${encodeURIComponent(id)}`,
192
+ aliases,
193
+ packages,
194
+ severity: highest(rating(score.cvss), rating(stated.value)),
195
+ exploited: knownExploited,
196
+ malware: /^MAL-/i.test(id),
197
+ withdrawn: data.status !== 'published',
198
+ modified_at: modified,
199
+ fetched_at: timestamp(now),
200
+ ...(published ? { published_at: published } : {}),
201
+ };
202
+ }
203
+ export function evidenceRelevant(item, inventory) {
204
+ const names = new Set();
205
+ for (const system of inventory.systems) {
206
+ for (const component of system.components) {
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
+ }
219
+ const content = `${item.title}\n${item.description}`;
220
+ return [...names].some((name) => {
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
+ });
227
+ }
228
+ /** Collect recent CVEs, exact npm matches and updates to relevant tracked IDs.
229
+ * The publication-ordered listing does not cover every historical modification. */
230
+ export async function collectCveNow(inventory, checkpoint, previous, news, http, now) {
231
+ const collected = new Map();
232
+ try {
233
+ return await readCveNow(inventory, checkpoint, previous, news, http, now, collected);
234
+ }
235
+ catch (error) {
236
+ throwSourceFailure(error, [...collected.values()]);
237
+ }
238
+ }
239
+ async function settleQueries(queries) {
240
+ const results = await Promise.allSettled(queries);
241
+ const canceled = results.find((result) => result.status === 'rejected' && sourceCanceled(result.reason));
242
+ if (canceled?.status === 'rejected')
243
+ throw canceled.reason;
244
+ const failed = results.find((result) => result.status === 'rejected');
245
+ if (failed?.status === 'rejected')
246
+ throw failed.reason;
247
+ }
248
+ async function readCveNow(inventory, checkpoint, previous, news, http, now, collected) {
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.');
252
+ const cutoff = Math.max(0, last - HOUR);
253
+ const invalid = new SourceItemFailures();
254
+ const retain = (entry) => {
255
+ const old = collected.get(entry.id);
256
+ if (!old && collected.size >= MAX_ENTRIES)
257
+ throw new SourceError('cve.now advisory limit reached; collection is incomplete.');
258
+ // The stack endpoint deduplicates entries inside each request. Multiple
259
+ // requests can independently confirm versions for the same advisory revision.
260
+ if (old && old.modified_at === entry.modified_at) {
261
+ for (const claim of old.packages) {
262
+ if (!claim.matched_versions?.length)
263
+ continue;
264
+ const current = entry.packages.find((candidate) => candidate.ecosystem === claim.ecosystem && candidate.name === claim.name);
265
+ if (current)
266
+ current.matched_versions = [
267
+ ...new Set([...(current.matched_versions ?? []), ...claim.matched_versions]),
268
+ ];
269
+ else
270
+ entry.packages.push({
271
+ ecosystem: claim.ecosystem,
272
+ name: claim.name,
273
+ matched_versions: [...claim.matched_versions],
274
+ });
275
+ }
276
+ }
277
+ if (!old || Date.parse(entry.modified_at) >= Date.parse(old.modified_at))
278
+ collected.set(entry.id, entry);
279
+ };
280
+ const queries = new Map();
281
+ for (const system of inventory.systems)
282
+ for (const component of system.components)
283
+ if (component.ecosystem === 'npm' && component.version && valid(component.version)) {
284
+ // Commas separate the API's compact package list; do not let a malformed
285
+ // package name inject another query into that format.
286
+ if (!/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/i.test(component.name))
287
+ throw new SourceError('cve.now requires a valid npm package name.');
288
+ queries.set(JSON.stringify([component.name, component.version]), {
289
+ name: component.name,
290
+ version: component.version,
291
+ });
292
+ }
293
+ if (queries.size > 1_000)
294
+ throw new SourceError('cve.now package query limit reached; collection is incomplete.');
295
+ const allQueries = [...queries.values()];
296
+ for (let offset = 0; offset < allQueries.length; offset += 4)
297
+ await settleQueries(allQueries.slice(offset, offset + 4).map(async (query) => {
298
+ // The provider deduplicates advisories and returns only one matched pair in
299
+ // a multi-package request. Query pairs separately so no positive match is lost.
300
+ const url = new URL(`${ORIGIN}/stack`);
301
+ url.searchParams.set('p', `npm:${query.name}@${query.version}`);
302
+ url.searchParams.set('format', 'json');
303
+ const data = (await get(http, url.href));
304
+ if (data.packages !== 1)
305
+ throw new SourceError('cve.now package count did not match the request; collection is incomplete.');
306
+ const entries = list(data.entries);
307
+ if (entries.length > MAX_ENTRIES || data.nextCursor || data.truncated === true)
308
+ throw new SourceError('cve.now package matches are incomplete.');
309
+ for (const raw of entries) {
310
+ const parsed = invalid.read(() => {
311
+ const entry = object(raw);
312
+ const match = object(entry.matched);
313
+ if (match.ecosystem !== 'npm' || match.name !== query.name || match.version !== query.version)
314
+ throw new SourceError('cve.now returned an unrequested package match.');
315
+ return parseEntry(entry, now, undefined, query);
316
+ });
317
+ if (parsed)
318
+ retain(parsed);
319
+ }
320
+ }));
321
+ const wanted = new Map();
322
+ for (const item of previous)
323
+ if (item.source === 'cve_now' && item.id.startsWith('cve_now:') && evidenceRelevant(item, inventory))
324
+ wanted.set(identifier(item.id.slice(8)), false);
325
+ // CVEs mentioned by a newly read story may be much older than the recent feed.
326
+ // An unpublished identifier can return 404 without losing the news evidence.
327
+ for (const item of [...previous, ...news])
328
+ if (item.kind === 'news' && evidenceRelevant(item, inventory))
329
+ for (const id of item.aliases)
330
+ if (/^(?:CVE-\d{4}-\d{4,}|GHSA-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4})$/i.test(id)) {
331
+ const normalized = identifier(id);
332
+ if (!wanted.has(normalized))
333
+ wanted.set(normalized, true);
334
+ }
335
+ let cursor;
336
+ const seen = new Set();
337
+ let previousPublished = Infinity;
338
+ for (let page = 0;; page++) {
339
+ if (page >= MAX_PAGES)
340
+ throw new SourceError('cve.now pagination limit reached; collection is incomplete.');
341
+ const url = new URL(`${ORIGIN}/api/v1/entries`);
342
+ if (cursor)
343
+ url.searchParams.set('cursor', cursor);
344
+ const data = (await get(http, url.href));
345
+ const entries = list(data.entries);
346
+ if (entries.length > 100)
347
+ throw new SourceError('cve.now returned too many records on one page.');
348
+ let crossedCutoff = false;
349
+ for (const raw of entries) {
350
+ const parsed = invalid.read(() => {
351
+ const entry = object(raw);
352
+ const id = identifier(entry.id);
353
+ const published = Date.parse(date(entry.publishedAt ?? entry.firstSeenAt, now));
354
+ if (entry.firstSeenAt)
355
+ date(entry.firstSeenAt, now);
356
+ return { id, published };
357
+ });
358
+ if (!parsed)
359
+ continue;
360
+ const { id, published } = parsed;
361
+ if (published > previousPublished)
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);
366
+ else
367
+ crossedCutoff = true;
368
+ }
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
+ }
377
+ if (wanted.size > MAX_ENTRIES)
378
+ throw new SourceError('cve.now tracked advisory limit reached; collection is incomplete.');
379
+ const ids = [...wanted].filter(([id]) => !collected.has(`cve_now:${id}`));
380
+ let detailFailures = 0;
381
+ let firstFailure;
382
+ let stoppedEarly = false;
383
+ for (let offset = 0; offset < ids.length; offset += 4) {
384
+ const batch = ids.slice(offset, offset + 4);
385
+ const results = await Promise.allSettled(batch.map(async ([id, optional]) => {
386
+ const data = await get(http, `${ORIGIN}/api/v1/entries/${encodeURIComponent(id)}`, optional);
387
+ if (data)
388
+ retain(parseEntry(data, now, id));
389
+ }));
390
+ const failures = results.filter((result) => result.status === 'rejected');
391
+ const canceled = failures.find(({ reason }) => sourceCanceled(reason));
392
+ if (canceled)
393
+ throw canceled.reason;
394
+ detailFailures += failures.length;
395
+ for (const failure of failures)
396
+ firstFailure ??=
397
+ failure.reason instanceof SourceError ? failure.reason.message : 'cve.now request failed.';
398
+ // One inaccessible record should not hide later advisories. Stop after
399
+ // repeated failures, or an explicit authentication/rate-limit response,
400
+ // while retaining successful requests already in flight.
401
+ if (failures.length === batch.length ||
402
+ detailFailures >= MAX_DETAIL_FAILURES ||
403
+ failures.some(({ reason }) => reason instanceof SourceHttpError && [401, 429].includes(reason.status))) {
404
+ stoppedEarly = offset + batch.length < ids.length;
405
+ break;
406
+ }
407
+ }
408
+ if (detailFailures)
409
+ throw new SourceError(`${detailFailures} advisory detail request(s) failed; collection is incomplete. ${firstFailure}${stoppedEarly
410
+ ? ' The remaining detail requests were not sent to limit repeated upstream failures.'
411
+ : ''}`);
412
+ return invalid.finish('cve.now', [...collected.values()]);
413
+ }
@@ -0,0 +1,26 @@
1
+ import type { Config, HttpClient, Notification } from './types.js';
2
+ import { Store } from './store.js';
3
+ export interface EmailMessage {
4
+ url: string;
5
+ from: string;
6
+ to: string[];
7
+ subject: string;
8
+ text: string;
9
+ signal?: AbortSignal;
10
+ }
11
+ export interface EmailReceipt {
12
+ accepted: string[];
13
+ rejected: string[];
14
+ }
15
+ export type EmailSender = (message: EmailMessage) => Promise<EmailReceipt>;
16
+ export declare const sendEmail: EmailSender;
17
+ export declare function notificationText(job: Notification): {
18
+ subject: string;
19
+ text: string;
20
+ };
21
+ /** Sends due jobs; "accepted" means the destination accepted the request, not that a human read it. */
22
+ export declare function deliverPending(store: Store, config: Config, http: HttpClient, now?: number, emailSender?: EmailSender, signal?: AbortSignal): Promise<{
23
+ accepted: number;
24
+ failed: number;
25
+ unknown: number;
26
+ }>;