@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,26 @@
1
+ import { Store } from './store.js';
2
+ import type { Assessment, Config, Decision, Evidence, HttpClient, Inventory } from './types.js';
3
+ export interface ScanReport {
4
+ at: string;
5
+ completed_at: string;
6
+ findings: Assessment[];
7
+ decisions: Record<string, Decision>;
8
+ degraded: boolean;
9
+ errors: {
10
+ source: string;
11
+ message: string;
12
+ }[];
13
+ evidence_count: number;
14
+ }
15
+ export declare function readFixture(path: string): Evidence[];
16
+ export declare function healthFinding(source: string, message: string, now?: number): Assessment;
17
+ export declare function runScan(options: {
18
+ config: Config;
19
+ inventory: Inventory;
20
+ store: Store;
21
+ http?: HttpClient;
22
+ fixture?: Evidence[];
23
+ now?: number;
24
+ onUrgent?: () => Promise<void>;
25
+ signal?: AbortSignal;
26
+ }): Promise<ScanReport>;
package/dist/engine.js ADDED
@@ -0,0 +1,307 @@
1
+ import { readFileSync, statSync } from 'node:fs';
2
+ import { z } from 'zod';
3
+ import { assess, decide } from './assessment.js';
4
+ import { collectSources } from './sources.js';
5
+ import { ModelAnalyzer, PROMPT_VERSION } from './models.js';
6
+ import { Store } from './store.js';
7
+ import { safeHttp } from './http.js';
8
+ import { missingCredentials } from './config.js';
9
+ import { hash, severityRank, timestamp } from './util.js';
10
+ const evidenceSchema = z
11
+ .object({
12
+ id: z.string().min(1),
13
+ source: z.string().min(1),
14
+ kind: z.enum(['advisory', 'news', 'kev', 'health']),
15
+ title: z.string(),
16
+ url: z.string(),
17
+ description: z.string(),
18
+ aliases: z.array(z.string()),
19
+ severity: z.enum(['unknown', 'low', 'medium', 'high', 'critical']),
20
+ modified_at: z.iso.datetime(),
21
+ fetched_at: z.iso.datetime(),
22
+ published_at: z.iso.datetime().optional(),
23
+ content_status: z.enum(['full', 'excerpt', 'unavailable']).optional(),
24
+ packages: z.array(z
25
+ .object({
26
+ ecosystem: z.string(),
27
+ name: z.string(),
28
+ range: z.string().optional(),
29
+ versions: z.array(z.string()).optional(),
30
+ matched_versions: z.array(z.string()).optional(),
31
+ fixed: z.string().optional(),
32
+ })
33
+ .strict()),
34
+ withdrawn: z.boolean().optional(),
35
+ exploited: z.boolean().optional(),
36
+ malware: z.boolean().optional(),
37
+ })
38
+ .strict();
39
+ export function readFixture(path) {
40
+ const stat = statSync(path);
41
+ if (!stat.isFile() || stat.size > 8_388_608)
42
+ throw new Error('Fixture must be a file of at most 8 MiB');
43
+ return z
44
+ .array(evidenceSchema)
45
+ .max(5000)
46
+ .parse(JSON.parse(readFileSync(path, 'utf8')));
47
+ }
48
+ export function healthFinding(source, message, now = Date.now()) {
49
+ return {
50
+ id: `health-${hash(source).slice(0, 20)}`,
51
+ event_id: `health:${source}`,
52
+ system_id: 'monitor',
53
+ category: 'health',
54
+ applicability: 'unknown',
55
+ source_severity: 'high',
56
+ priority: 'high',
57
+ title: `Monitoring needs attention: ${source}`,
58
+ summary: message,
59
+ reasons: ['Monitoring is incomplete; this is not a clean security result.'],
60
+ evidence_ids: [],
61
+ urls: [],
62
+ exploited: false,
63
+ updated_at: timestamp(now),
64
+ };
65
+ }
66
+ function checkCancellation(signal) {
67
+ if (signal?.aborted)
68
+ throw new DOMException('Scan canceled', 'AbortError');
69
+ }
70
+ function canRetainPriority(previous, current) {
71
+ return Boolean(previous &&
72
+ previous.active !== false &&
73
+ current.applicability !== 'not_affected' &&
74
+ !current.withdrawn &&
75
+ (previous.applicability === current.applicability ||
76
+ current.applicability === 'unknown' ||
77
+ current.applicability === 'conflicting') &&
78
+ severityRank[previous.priority] > severityRank[current.priority]);
79
+ }
80
+ function generalNews(assessment) {
81
+ return Boolean(assessment?.active !== false &&
82
+ assessment?.ai?.status === 'complete' &&
83
+ assessment.news_analysis?.classification === 'general_news' &&
84
+ assessment.news_analysis.impact === 'not_applicable');
85
+ }
86
+ export async function runScan(options) {
87
+ const { config, inventory, store, signal } = options;
88
+ checkCancellation(signal);
89
+ const now = options.now ?? Date.now();
90
+ const transport = options.http ?? safeHttp;
91
+ const http = (url, request) => {
92
+ checkCancellation(signal);
93
+ return transport(url, { ...request, ...(signal ? { signal } : {}) });
94
+ };
95
+ const previousById = new Map(store.findings().map((a) => [a.id, a]));
96
+ const decisions = {};
97
+ const persist = (assessment) => {
98
+ const decision = decide(assessment, config);
99
+ decisions[assessment.id] = decision;
100
+ store.saveAssessment(assessment, decision, now, config.digest_interval_hours * 3_600_000);
101
+ };
102
+ const retire = (assessment) => {
103
+ store.saveAssessment({
104
+ ...assessment,
105
+ active: false,
106
+ updated_at: timestamp(now),
107
+ reasons: [
108
+ ...assessment.reasons,
109
+ 'No longer in the current assessment. This does not establish remediation.',
110
+ ],
111
+ }, {
112
+ action: 'record',
113
+ channels: [],
114
+ reason: 'No current inventory/evidence match or monitoring issue recovered',
115
+ }, now);
116
+ };
117
+ const systemHashes = new Map(inventory.systems.map((system) => {
118
+ const { updated_at: _updated, ...context } = system;
119
+ return [system.id, hash(context)];
120
+ }));
121
+ const basis = (finding, evidenceById) => {
122
+ const { updated_at: _updated, ...assessment } = finding;
123
+ return hash({
124
+ assessment,
125
+ system: systemHashes.get(finding.system_id),
126
+ analysis: {
127
+ model: config.models.analysis,
128
+ verification: config.models.verification,
129
+ prompt: PROMPT_VERSION,
130
+ max_input_chars: config.models.max_input_chars,
131
+ },
132
+ evidence: finding.evidence_ids.map((id) => {
133
+ const item = evidenceById.get(id);
134
+ if (!item)
135
+ return null;
136
+ const { fetched_at: _fetched, ...content } = item;
137
+ const fetched = Date.parse(item.fetched_at);
138
+ return {
139
+ ...content,
140
+ fresh: generalNews(previousById.get(finding.id)) ||
141
+ (Number.isFinite(fetched) &&
142
+ fetched <= now + 300_000 &&
143
+ now - fetched <= Math.max(120_000, config.poll_interval_minutes * 120_000)),
144
+ };
145
+ }),
146
+ });
147
+ };
148
+ const interim = (finding, basisHash) => {
149
+ const previous = previousById.get(finding.id);
150
+ if (!config.models.enabled || !previous || previous.active === false)
151
+ return finding;
152
+ if (store.getMeta(`assessment-basis:${finding.id}`) === basisHash && previous.ai) {
153
+ // Retain unchanged analysis until reassessment; don't alternate record/digest/notify on every scan.
154
+ return {
155
+ ...finding,
156
+ priority: previous.priority,
157
+ applicability: previous.applicability,
158
+ ...(previous.relevance ? { relevance: previous.relevance } : {}),
159
+ ...(previous.news_analysis ? { news_analysis: previous.news_analysis } : {}),
160
+ summary: previous.summary,
161
+ reasons: previous.reasons,
162
+ ai: previous.ai,
163
+ };
164
+ }
165
+ return canRetainPriority(previous, finding) ? { ...finding, priority: previous.priority } : finding;
166
+ };
167
+ const cached = store.evidence();
168
+ if (!options.fixture && previousById.size) {
169
+ // Apply known inventory changes before yielding to network I/O. The worker can deliver concurrently.
170
+ const cachedById = new Map(cached.map((e) => [e.id, e]));
171
+ const current = assess(inventory, cached, config, now);
172
+ const ids = new Set(current.map((a) => a.id));
173
+ for (const finding of current)
174
+ if (previousById.has(finding.id))
175
+ persist(interim(finding, basis(finding, cachedById)));
176
+ for (const previous of previousById.values())
177
+ if (previous.category !== 'health' && previous.active !== false && !ids.has(previous.id))
178
+ retire(previous);
179
+ }
180
+ const result = options.fixture
181
+ ? { evidence: options.fixture, errors: [], checkpoints: {} }
182
+ : await collectSources(inventory, config, store.checkpoints(), http, now, cached);
183
+ checkCancellation(signal);
184
+ store.saveEvidence(result.evidence, result.checkpoints);
185
+ const evidence = store.evidence();
186
+ const evidenceById = new Map(evidence.map((e) => [e.id, e]));
187
+ const findings = assess(inventory, evidence, config, now);
188
+ const bases = new Map(findings.map((a) => [a.id, basis(a, evidenceById)]));
189
+ const errors = [...result.errors];
190
+ if (!options.fixture && missingCredentials(config).length)
191
+ errors.push({
192
+ source: 'credentials',
193
+ message: 'Configured model or delivery credentials are missing. Structured advisory matching continues; run doctor to see required variable names.',
194
+ });
195
+ if (!inventory.systems.length)
196
+ errors.push({
197
+ source: 'inventory',
198
+ message: 'Inventory is empty; add systems before enabling monitoring.',
199
+ });
200
+ if (!config.sources.cve_now &&
201
+ !config.sources.hacker_news &&
202
+ !config.sources.osv &&
203
+ !config.sources.github &&
204
+ !config.sources.kev &&
205
+ !config.sources.feeds.length &&
206
+ !options.fixture)
207
+ errors.push({ source: 'sources', message: 'All sources are disabled.' });
208
+ if (!options.fixture &&
209
+ (config.sources.hacker_news || config.sources.feeds.length) &&
210
+ !config.models.enabled)
211
+ errors.push({
212
+ source: 'models',
213
+ message: 'AI is disabled. System news receives candidate matching only; enable an analysis model to distinguish vulnerability impact from general system coverage.',
214
+ });
215
+ for (const system of inventory.systems) {
216
+ const updated = Date.parse(system.updated_at);
217
+ if (!Number.isFinite(updated) ||
218
+ updated > now + 300_000 ||
219
+ now - updated > config.inventory_stale_days * 86_400_000)
220
+ errors.push({
221
+ source: `inventory:${system.id}`,
222
+ message: 'Inventory timestamp is stale or in the future; verify installed versions and deployment context.',
223
+ });
224
+ }
225
+ // Reconcile every finding before delivery, including exclusions, withdrawals and removals.
226
+ // Otherwise an old pending alert could be sent while unrelated AI analysis is running.
227
+ findings.forEach((finding) => persist(interim(finding, bases.get(finding.id))));
228
+ const currentIds = new Set(findings.map((a) => a.id));
229
+ for (const previous of store.findings())
230
+ if (previous.category !== 'health' && previous.active !== false && !currentIds.has(previous.id))
231
+ retire(previous);
232
+ if (options.onUrgent) {
233
+ try {
234
+ await options.onUrgent();
235
+ }
236
+ catch {
237
+ checkCancellation(signal);
238
+ errors.push({
239
+ source: 'delivery',
240
+ message: 'Urgent delivery did not complete. The scan continued; inspect deliveries before retrying.',
241
+ });
242
+ }
243
+ }
244
+ checkCancellation(signal);
245
+ const analyzer = new ModelAnalyzer(config, store, http, options.now === undefined ? Date.now : () => now, signal);
246
+ const analyzed = [];
247
+ for (const finding of findings.sort((a, b) => severityRank[b.priority] - severityRank[a.priority])) {
248
+ checkCancellation(signal);
249
+ const system = inventory.systems.find((s) => s.id === finding.system_id);
250
+ // An unchanged conference/announcement does not become a vulnerability just
251
+ // because it leaves the rolling RSS window. Inventory/content changes still
252
+ // invalidate its basis; affected/excluded impact claims always check freshness.
253
+ const keepGeneral = config.models.enabled &&
254
+ generalNews(previousById.get(finding.id)) &&
255
+ store.getMeta(`assessment-basis:${finding.id}`) === bases.get(finding.id);
256
+ let enriched = keepGeneral && !options.fixture
257
+ ? interim(finding, bases.get(finding.id))
258
+ : system && !options.fixture
259
+ ? await analyzer.analyze(finding, system, evidence)
260
+ : finding;
261
+ checkCancellation(signal);
262
+ const previous = previousById.get(finding.id);
263
+ if ((enriched.ai?.status === 'unavailable' || enriched.ai?.status === 'conflicting') &&
264
+ canRetainPriority(previous, enriched)) {
265
+ enriched = {
266
+ ...enriched,
267
+ priority: previous.priority,
268
+ reasons: [...enriched.reasons, 'Previous priority retained pending valid AI reassessment.'],
269
+ };
270
+ }
271
+ if (enriched.ai?.status === 'unavailable' || enriched.ai?.status === 'conflicting') {
272
+ const code = enriched.reasons.find((r) => r.startsWith('MODEL_'))?.split(';')[0] ?? 'Analysis disagreement';
273
+ if (!errors.some((e) => e.source === 'models' && e.message === code))
274
+ errors.push({ source: 'models', message: code });
275
+ }
276
+ analyzed.push(enriched);
277
+ persist(enriched);
278
+ store.setMeta(`assessment-basis:${finding.id}`, bases.get(finding.id));
279
+ }
280
+ const groupedErrors = new Map();
281
+ for (const error of errors)
282
+ groupedErrors.set(error.source, [...(groupedErrors.get(error.source) ?? []), error.message]);
283
+ const healthFindings = [...groupedErrors].map(([source, messages]) => healthFinding(source, [...new Set(messages)].join(' '), now));
284
+ healthFindings.forEach(persist);
285
+ const active = new Set([...analyzed, ...healthFindings].map((a) => a.id));
286
+ for (const previous of store.findings())
287
+ if (!active.has(previous.id) && previous.active !== false)
288
+ retire(previous);
289
+ const report = {
290
+ at: timestamp(now),
291
+ completed_at: timestamp(options.now ?? Date.now()),
292
+ findings: [...analyzed, ...healthFindings],
293
+ decisions,
294
+ degraded: errors.length > 0,
295
+ errors,
296
+ evidence_count: evidence.length,
297
+ };
298
+ store.setMeta('last_scan', JSON.stringify({
299
+ at: report.completed_at,
300
+ started_at: report.at,
301
+ completed_at: report.completed_at,
302
+ degraded: report.degraded,
303
+ errors: report.errors,
304
+ findings: report.findings.length,
305
+ }));
306
+ return report;
307
+ }
@@ -0,0 +1,17 @@
1
+ import type { Config } from './types.js';
2
+ import { Store } from './store.js';
3
+ export interface HealthReport {
4
+ ok: boolean;
5
+ status: 'healthy' | 'starting' | 'degraded';
6
+ checked_at: string;
7
+ issues: string[];
8
+ last_scan_at: string | null;
9
+ worker_heartbeat_at: string | null;
10
+ delivery: {
11
+ failed: number;
12
+ unknown: number;
13
+ overdue_pending: number;
14
+ };
15
+ }
16
+ /** Read-only monitoring health check; does not assess system security or make network requests. */
17
+ export declare function checkHealth(store: Store, config: Config, now?: number, requireWorker?: boolean): HealthReport;
package/dist/health.js ADDED
@@ -0,0 +1,70 @@
1
+ import { Store } from './store.js';
2
+ function object(value) {
3
+ if (!value)
4
+ return undefined;
5
+ try {
6
+ const data = JSON.parse(value);
7
+ return data !== null && typeof data === 'object' && !Array.isArray(data)
8
+ ? data
9
+ : undefined;
10
+ }
11
+ catch {
12
+ return undefined;
13
+ }
14
+ }
15
+ function time(value) {
16
+ return typeof value === 'string' ? Date.parse(value) : NaN;
17
+ }
18
+ /** Read-only monitoring health check; does not assess system security or make network requests. */
19
+ export function checkHealth(store, config, now = Date.now(), requireWorker = true) {
20
+ const scan = object(store.getMeta('last_scan'));
21
+ const worker = object(store.getMeta('worker'));
22
+ const heartbeat = time(worker?.heartbeat_at);
23
+ const started = time(worker?.started_at);
24
+ const scanned = time(scan?.at);
25
+ const issues = [];
26
+ const startupGrace = worker?.status === 'running' && Number.isFinite(started) && now >= started && now - started <= 120_000;
27
+ if (requireWorker &&
28
+ (worker?.status !== 'running' ||
29
+ !Number.isFinite(heartbeat) ||
30
+ heartbeat > now + 5000 ||
31
+ now - heartbeat > 90_000))
32
+ issues.push('Worker heartbeat is missing, stopped or stale.');
33
+ if (!Number.isFinite(scanned)) {
34
+ if (!startupGrace || !requireWorker)
35
+ issues.push('No completed scan is recorded.');
36
+ }
37
+ else {
38
+ if (scanned > now + 5000 || now - scanned > Math.max(120_000, config.poll_interval_minutes * 120_000))
39
+ issues.push('The last completed scan is stale or has an invalid future timestamp.');
40
+ if (scan?.degraded !== false)
41
+ issues.push('The last scan reported degraded monitoring; inspect status and findings.');
42
+ }
43
+ const delivery = store.deliveryIssues(now, 300_000, config);
44
+ if (config.maintenance) {
45
+ const maintenance = object(store.getMeta('maintenance:last_run'));
46
+ if (maintenance?.ok === false)
47
+ issues.push('Scheduled maintenance failed; inspect status and backup storage.');
48
+ const lastSuccess = time(maintenance?.last_success_at);
49
+ if (requireWorker && !startupGrace && !Number.isFinite(lastSuccess))
50
+ issues.push('Scheduled maintenance has not completed successfully.');
51
+ if (Number.isFinite(lastSuccess) &&
52
+ (lastSuccess > now + 5000 || now - lastSuccess > config.maintenance.interval_hours * 7_200_000))
53
+ issues.push('Scheduled maintenance is overdue.');
54
+ }
55
+ if (delivery.failed)
56
+ issues.push('Current notifications have failed; inspect deliveries.');
57
+ if (delivery.unknown)
58
+ issues.push('Current notification receipt is uncertain; verify delivery before retrying.');
59
+ if (delivery.overdue_pending)
60
+ issues.push('Current notifications are overdue by more than five minutes.');
61
+ return {
62
+ ok: issues.length === 0,
63
+ status: issues.length ? 'degraded' : Number.isFinite(scanned) ? 'healthy' : 'starting',
64
+ checked_at: new Date(now).toISOString(),
65
+ issues,
66
+ last_scan_at: Number.isFinite(scanned) ? new Date(scanned).toISOString() : null,
67
+ worker_heartbeat_at: Number.isFinite(heartbeat) ? new Date(heartbeat).toISOString() : null,
68
+ delivery,
69
+ };
70
+ }
@@ -0,0 +1,13 @@
1
+ import type { Config, HttpClient } from './types.js';
2
+ import type { Store } from './store.js';
3
+ export interface ExternalHeartbeat {
4
+ status: 'accepted' | 'failed' | 'withheld';
5
+ checked_at: string;
6
+ last_success_at: string | null;
7
+ reason: string | null;
8
+ }
9
+ /** Sends no inventory or logs. A separate service alerts when healthy pings stop arriving. */
10
+ export declare class HeartbeatMonitor {
11
+ private nextAt;
12
+ tick(store: Store, config: Config, http: HttpClient, now?: number, signal?: AbortSignal): Promise<ExternalHeartbeat | undefined>;
13
+ }
@@ -0,0 +1,74 @@
1
+ import { checkHealth } from './health.js';
2
+ import { validateDestination } from './http.js';
3
+ /** Sends no inventory or logs. A separate service alerts when healthy pings stop arriving. */
4
+ export class HeartbeatMonitor {
5
+ nextAt = 0;
6
+ async tick(store, config, http, now = Date.now(), signal) {
7
+ const settings = config.monitoring;
8
+ if (!settings || signal?.aborted || now < this.nextAt)
9
+ return undefined;
10
+ this.nextAt = now + settings.interval_seconds * 1000;
11
+ let lastSuccess = null;
12
+ const saved = store.getMeta('external_heartbeat');
13
+ try {
14
+ const previous = JSON.parse(saved ?? 'null');
15
+ if (previous &&
16
+ typeof previous === 'object' &&
17
+ 'last_success_at' in previous &&
18
+ typeof previous.last_success_at === 'string' &&
19
+ Number.isFinite(Date.parse(previous.last_success_at)))
20
+ lastSuccess = previous.last_success_at;
21
+ }
22
+ catch {
23
+ // A malformed old receipt cannot establish a successful ping.
24
+ }
25
+ const report = {
26
+ status: 'withheld',
27
+ checked_at: new Date(now).toISOString(),
28
+ last_success_at: lastSuccess,
29
+ reason: null,
30
+ };
31
+ const health = checkHealth(store, config, now);
32
+ if (!health.ok || health.status !== 'healthy') {
33
+ report.reason = 'Monitoring is not healthy; no success ping was sent.';
34
+ }
35
+ else {
36
+ const endpoint = process.env[settings.heartbeat_url_env];
37
+ if (!endpoint) {
38
+ report.status = 'failed';
39
+ report.reason = 'External heartbeat destination is not configured.';
40
+ }
41
+ else {
42
+ try {
43
+ validateDestination(endpoint, settings.allow_private_endpoint);
44
+ const response = await http(endpoint, {
45
+ method: 'GET',
46
+ redirects: 0,
47
+ timeoutMs: 5000,
48
+ maxBytes: 4096,
49
+ allowPrivate: settings.allow_private_endpoint,
50
+ signal,
51
+ });
52
+ if (response.status >= 200 && response.status < 300) {
53
+ report.status = 'accepted';
54
+ report.last_success_at = report.checked_at;
55
+ }
56
+ else {
57
+ report.status = 'failed';
58
+ report.reason = `External heartbeat returned HTTP ${response.status}.`;
59
+ }
60
+ }
61
+ catch {
62
+ if (signal?.aborted)
63
+ return undefined;
64
+ report.status = 'failed';
65
+ report.reason = 'External heartbeat request failed; the destination may not have received it.';
66
+ }
67
+ }
68
+ }
69
+ if (signal?.aborted)
70
+ return undefined;
71
+ store.setMeta('external_heartbeat', JSON.stringify(report));
72
+ return report;
73
+ }
74
+ }
package/dist/http.d.ts ADDED
@@ -0,0 +1,8 @@
1
+ import type { HttpClient } from './types.js';
2
+ export declare class NetworkError extends Error {
3
+ readonly code: string;
4
+ constructor(code: string);
5
+ }
6
+ export declare function isPublicAddress(address: string): boolean;
7
+ export declare function validateDestination(value: string, allowPrivate?: boolean): URL;
8
+ export declare const safeHttp: HttpClient;