@shieldaai/security-watch 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (110) hide show
  1. package/CHANGELOG.md +170 -0
  2. package/CONTRIBUTING.md +92 -0
  3. package/LICENSE +202 -0
  4. package/README.md +394 -2
  5. package/SECURITY.md +62 -0
  6. package/dist/assessment.d.ts +16 -0
  7. package/dist/assessment.js +569 -0
  8. package/dist/cli.d.ts +2 -0
  9. package/dist/cli.js +1105 -0
  10. package/dist/config.d.ts +302 -0
  11. package/dist/config.js +381 -0
  12. package/dist/coverage.d.ts +4 -0
  13. package/dist/coverage.js +11 -0
  14. package/dist/cve-now.d.ts +35 -0
  15. package/dist/cve-now.js +1002 -0
  16. package/dist/cvss4.d.ts +3 -0
  17. package/dist/cvss4.js +39 -0
  18. package/dist/delivery.d.ts +58 -0
  19. package/dist/delivery.js +687 -0
  20. package/dist/ecosystems.d.ts +48 -0
  21. package/dist/ecosystems.js +332 -0
  22. package/dist/engine.d.ts +80 -0
  23. package/dist/engine.js +388 -0
  24. package/dist/everyday-words.d.ts +11 -0
  25. package/dist/everyday-words.js +256 -0
  26. package/dist/health.d.ts +24 -0
  27. package/dist/health.js +122 -0
  28. package/dist/heartbeat.d.ts +13 -0
  29. package/dist/heartbeat.js +74 -0
  30. package/dist/http.d.ts +15 -0
  31. package/dist/http.js +280 -0
  32. package/dist/index.d.ts +36 -0
  33. package/dist/index.js +23 -0
  34. package/dist/inventory-evidence.d.ts +10 -0
  35. package/dist/inventory-evidence.js +206 -0
  36. package/dist/inventory.d.ts +276 -0
  37. package/dist/inventory.js +336 -0
  38. package/dist/lock.d.ts +3 -0
  39. package/dist/lock.js +112 -0
  40. package/dist/maintenance.d.ts +48 -0
  41. package/dist/maintenance.js +295 -0
  42. package/dist/matching.d.ts +29 -0
  43. package/dist/matching.js +537 -0
  44. package/dist/models.d.ts +33 -0
  45. package/dist/models.js +932 -0
  46. package/dist/operations.d.ts +17 -0
  47. package/dist/operations.js +117 -0
  48. package/dist/pilot-cases.d.ts +171 -0
  49. package/dist/pilot-cases.js +330 -0
  50. package/dist/pilot-input.d.ts +16 -0
  51. package/dist/pilot-input.js +125 -0
  52. package/dist/pilot-recall.d.ts +166 -0
  53. package/dist/pilot-recall.js +231 -0
  54. package/dist/pilot-report.d.ts +113 -0
  55. package/dist/pilot-report.js +279 -0
  56. package/dist/pilot-responses.d.ts +111 -0
  57. package/dist/pilot-responses.js +159 -0
  58. package/dist/providers.d.ts +209 -0
  59. package/dist/providers.js +459 -0
  60. package/dist/python-version.d.ts +3 -0
  61. package/dist/python-version.js +30 -0
  62. package/dist/rehearsal.d.ts +440 -0
  63. package/dist/rehearsal.js +372 -0
  64. package/dist/sbom.d.ts +13 -0
  65. package/dist/sbom.js +193 -0
  66. package/dist/setup.d.ts +113 -0
  67. package/dist/setup.js +100 -0
  68. package/dist/source-error.d.ts +38 -0
  69. package/dist/source-error.js +71 -0
  70. package/dist/sources.d.ts +3 -0
  71. package/dist/sources.js +1725 -0
  72. package/dist/store.d.ts +96 -0
  73. package/dist/store.js +953 -0
  74. package/dist/types.d.ts +404 -0
  75. package/dist/types.js +1 -0
  76. package/dist/util.d.ts +29 -0
  77. package/dist/util.js +94 -0
  78. package/dist/vendor/cvss4-reference.d.ts +2 -0
  79. package/dist/vendor/cvss4-reference.js +789 -0
  80. package/dist/vendor-sources.d.ts +24 -0
  81. package/dist/vendor-sources.js +56 -0
  82. package/dist/word-filter.d.ts +3 -0
  83. package/dist/word-filter.js +3291 -0
  84. package/docs/alert-outcome-evaluation.md +150 -0
  85. package/docs/compatibility.md +35 -0
  86. package/docs/configuration.md +666 -0
  87. package/docs/cvss-v4-support.md +41 -0
  88. package/docs/offline-advisory-preview.md +114 -0
  89. package/docs/offline-rehearsal.md +44 -0
  90. package/docs/pilot-cases.md +58 -0
  91. package/docs/pilot-recall.md +124 -0
  92. package/docs/pilot-report.md +52 -0
  93. package/docs/validation/alert-outcome-evaluation-2026-11-05.json +2935 -0
  94. package/docs/validation/cvss-v4-reference-parity-2026-11-05.json +93 -0
  95. package/docs/validation/rehearsal-accepted-2026-11-05.json +175 -0
  96. package/docs/validation/rehearsal-unknown-2026-11-05.json +175 -0
  97. package/docs/vendor/cvss-v4-LICENSE.txt +22 -0
  98. package/docs/vendor/cvss-v4-provenance.json +38 -0
  99. package/examples/advisories.json +17 -0
  100. package/examples/agent-advisories-2026.json +145 -0
  101. package/examples/agent-advisory-cases-2026.json +397 -0
  102. package/examples/common-systems.yaml +243 -0
  103. package/examples/libraries.example.txt +18 -0
  104. package/examples/libraries.example.yaml +40 -0
  105. package/examples/library-watch.example.yaml +27 -0
  106. package/examples/offline-advisory-preview.mjs +42 -0
  107. package/examples/rehearsal.json +75 -0
  108. package/examples/security-watch.example.yaml +86 -0
  109. package/examples/systems.example.yaml +35 -0
  110. package/package.json +85 -4
@@ -0,0 +1,24 @@
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
+ /**
17
+ * Since when a worker starting at `startedAt` has been catching up without recording a scan. It is
18
+ * kept across restarts until a scan is recorded, so a worker killed during every scan cannot renew
19
+ * its startup grace by restarting; a restart after a recorded scan starts afresh. The time between
20
+ * the previous worker's last sign of life and this start does not count.
21
+ */
22
+ export declare function catchingUpFrom(store: Store, startedAt: string): string;
23
+ /** Read-only monitoring health check; does not assess system security or make network requests. */
24
+ export declare function checkHealth(store: Store, config: Config, now?: number, requireWorker?: boolean): HealthReport;
package/dist/health.js ADDED
@@ -0,0 +1,122 @@
1
+ import { Store } from './store.js';
2
+ /** How long a running worker may take over its first scan before health reports none. */
3
+ const FIRST_SCAN_GRACE = 3_600_000;
4
+ /** How long a worker that died may have run after its last heartbeat (written every 15 seconds). */
5
+ const CRASH_MARGIN = 60_000;
6
+ function object(value) {
7
+ if (!value)
8
+ return undefined;
9
+ try {
10
+ const data = JSON.parse(value);
11
+ return data !== null && typeof data === 'object' && !Array.isArray(data)
12
+ ? data
13
+ : undefined;
14
+ }
15
+ catch {
16
+ return undefined;
17
+ }
18
+ }
19
+ function time(value) {
20
+ return typeof value === 'string' ? Date.parse(value) : NaN;
21
+ }
22
+ /**
23
+ * Since when a worker starting at `startedAt` has been catching up without recording a scan. It is
24
+ * kept across restarts until a scan is recorded, so a worker killed during every scan cannot renew
25
+ * its startup grace by restarting; a restart after a recorded scan starts afresh. The time between
26
+ * the previous worker's last sign of life and this start does not count.
27
+ */
28
+ export function catchingUpFrom(store, startedAt) {
29
+ try {
30
+ const previous = JSON.parse(store.getMeta('worker') ?? 'null');
31
+ const scan = JSON.parse(store.getMeta('last_scan') ?? 'null');
32
+ const since = time(previous?.catching_up_since);
33
+ const scanned = time(scan?.at);
34
+ const seen = Math.max(...[time(previous?.heartbeat_at), time(previous?.started_at)].filter(Number.isFinite));
35
+ const start = Date.parse(startedAt);
36
+ if (!Number.isFinite(since) || since > start || scanned >= since)
37
+ return startedAt;
38
+ // Only running time counts: the time the worker was stopped moves the start forward. A clean stop
39
+ // records its last moment. A worker that died may have run up to a heartbeat interval past its
40
+ // last heartbeat, so that much more of the gap counts as running: a crash loop, down for seconds,
41
+ // cannot renew the grace however soon it dies.
42
+ const gap = Number.isFinite(seen) && seen >= since && seen <= start ? start - seen : 0;
43
+ const down = previous?.status === 'stopped' ? gap : Math.max(0, gap - CRASH_MARGIN);
44
+ return new Date(since + down).toISOString();
45
+ }
46
+ catch {
47
+ return startedAt;
48
+ }
49
+ }
50
+ /** Read-only monitoring health check; does not assess system security or make network requests. */
51
+ export function checkHealth(store, config, now = Date.now(), requireWorker = true) {
52
+ const scan = object(store.getMeta('last_scan'));
53
+ const worker = object(store.getMeta('worker'));
54
+ const heartbeat = time(worker?.heartbeat_at);
55
+ const started = time(worker?.started_at);
56
+ const scanned = time(scan?.at);
57
+ const issues = [];
58
+ const staleAfter = Math.max(120_000, config.poll_interval_minutes * 120_000);
59
+ // The first scan reads a day of advisories and every package lookup at about a request a second:
60
+ // it can take well over the two minutes later scans need, so a running worker that has not
61
+ // finished one yet is healthy for up to an hour.
62
+ // Measured from when the worker began catching up, which survives restarts until a scan is
63
+ // recorded: a worker killed during every scan does not renew its grace by restarting.
64
+ const catchingUpSince = time(worker?.catching_up_since);
65
+ const graceFrom = Number.isFinite(catchingUpSince) && catchingUpSince <= started ? catchingUpSince : started;
66
+ const startupGrace = worker?.status === 'running' &&
67
+ Number.isFinite(started) &&
68
+ now >= started &&
69
+ (Number.isFinite(scanned) && scanned >= started
70
+ ? now - started <= 120_000
71
+ : now - graceFrom <= FIRST_SCAN_GRACE);
72
+ /** Whether this check passes only because a worker is still catching up. */
73
+ let catchingUp = false;
74
+ if (requireWorker &&
75
+ (worker?.status !== 'running' ||
76
+ !Number.isFinite(heartbeat) ||
77
+ heartbeat > now + 5000 ||
78
+ now - heartbeat > 90_000))
79
+ issues.push('Worker heartbeat is missing, stopped or stale.');
80
+ if (!Number.isFinite(scanned)) {
81
+ if (!startupGrace || !requireWorker)
82
+ issues.push('No completed scan is recorded.');
83
+ }
84
+ else {
85
+ const stale = now - scanned > staleAfter;
86
+ if (stale && startupGrace && requireWorker && scanned < started)
87
+ catchingUp = true;
88
+ else if (scanned > now + 5000 || stale)
89
+ issues.push('The last completed scan is stale or has an invalid future timestamp.');
90
+ if (scan?.degraded !== false)
91
+ issues.push('The last scan reported degraded monitoring; inspect status and findings.');
92
+ }
93
+ const delivery = store.deliveryIssues(now, 300_000, config);
94
+ if (config.maintenance) {
95
+ const maintenance = object(store.getMeta('maintenance:last_run'));
96
+ if (maintenance?.ok === false)
97
+ issues.push('Scheduled maintenance failed; inspect status and backup storage.');
98
+ const lastSuccess = time(maintenance?.last_success_at);
99
+ if (requireWorker && !startupGrace && !Number.isFinite(lastSuccess))
100
+ issues.push('Scheduled maintenance has not completed successfully.');
101
+ if (Number.isFinite(lastSuccess) &&
102
+ (lastSuccess > now + 5000 || now - lastSuccess > config.maintenance.interval_hours * 7_200_000))
103
+ issues.push('Scheduled maintenance is overdue.');
104
+ }
105
+ if (delivery.failed)
106
+ issues.push('Current notifications have failed; inspect deliveries.');
107
+ if (delivery.unknown)
108
+ issues.push('Current notification receipt is uncertain; verify delivery before retrying.');
109
+ if (delivery.overdue_pending)
110
+ issues.push('Current notifications are overdue by more than five minutes.');
111
+ return {
112
+ ok: issues.length === 0,
113
+ // While a worker catches up the check passes, but it is "starting": no success is reported to
114
+ // an external heartbeat until a scan completes.
115
+ status: issues.length ? 'degraded' : Number.isFinite(scanned) && !catchingUp ? 'healthy' : 'starting',
116
+ checked_at: new Date(now).toISOString(),
117
+ issues,
118
+ last_scan_at: Number.isFinite(scanned) ? new Date(scanned).toISOString() : null,
119
+ worker_heartbeat_at: Number.isFinite(heartbeat) ? new Date(heartbeat).toISOString() : null,
120
+ delivery,
121
+ };
122
+ }
@@ -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,15 @@
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
+ /**
8
+ * Whether an unencrypted connection to this address stays on this machine or a private network:
9
+ * loopback, RFC 1918, carrier-grade NAT (also used by overlay networks), link-local and IPv6
10
+ * unique-local addresses. Addresses that wrap a public IPv4 address (NAT64, 6to4, Teredo),
11
+ * multicast and reserved ranges are not private.
12
+ */
13
+ export declare function privateAddress(address: string): boolean;
14
+ export declare function validateDestination(value: string, allowPrivate?: boolean): URL;
15
+ export declare const safeHttp: HttpClient;
package/dist/http.js ADDED
@@ -0,0 +1,280 @@
1
+ import { request as httpsRequest } from 'node:https';
2
+ import { request as httpRequest } from 'node:http';
3
+ import { lookup } from 'node:dns';
4
+ import { isIP } from 'node:net';
5
+ import ipaddr from 'ipaddr.js';
6
+ export class NetworkError extends Error {
7
+ code;
8
+ constructor(code) {
9
+ super(code);
10
+ this.code = code;
11
+ this.name = 'NetworkError';
12
+ }
13
+ }
14
+ const originSchedules = new Map();
15
+ const MAX_COOLDOWN_MS = 3_600_000;
16
+ function pumpOrigin(origin, schedule) {
17
+ clearTimeout(schedule.timer);
18
+ schedule.timer = undefined;
19
+ const delay = Math.max(0, schedule.nextStart, schedule.cooldown) - Date.now();
20
+ if (!schedule.queue.length) {
21
+ if (schedule.active)
22
+ return;
23
+ if (delay <= 0)
24
+ originSchedules.delete(origin);
25
+ else {
26
+ schedule.timer = setTimeout(() => pumpOrigin(origin, schedule), delay);
27
+ schedule.timer.unref();
28
+ }
29
+ return;
30
+ }
31
+ if (delay > 0) {
32
+ schedule.timer = setTimeout(() => pumpOrigin(origin, schedule), delay);
33
+ return;
34
+ }
35
+ const waiter = schedule.queue.shift();
36
+ waiter.cleanup();
37
+ schedule.active++;
38
+ schedule.nextStart = Date.now() + schedule.interval;
39
+ waiter.ready(() => {
40
+ schedule.active--;
41
+ pumpOrigin(origin, schedule);
42
+ });
43
+ pumpOrigin(origin, schedule);
44
+ }
45
+ function originSlot(origin, options, deadline) {
46
+ const interval = options.minIntervalMs ?? 0;
47
+ if (!Number.isFinite(interval) || interval < 0 || interval > MAX_COOLDOWN_MS)
48
+ throw new NetworkError('INVALID_REQUEST_INTERVAL');
49
+ let schedule = originSchedules.get(origin);
50
+ if (!schedule && !interval)
51
+ return Promise.resolve(() => { });
52
+ if (!schedule) {
53
+ schedule = { queue: [], interval, nextStart: 0, cooldown: 0, active: 0 };
54
+ originSchedules.set(origin, schedule);
55
+ }
56
+ const current = schedule;
57
+ current.interval = Math.max(current.interval, interval);
58
+ return new Promise((resolve, reject) => {
59
+ const remove = (code) => {
60
+ const index = current.queue.indexOf(waiter);
61
+ if (index < 0)
62
+ return;
63
+ current.queue.splice(index, 1);
64
+ waiter.cleanup();
65
+ waiter.fail(new NetworkError(code));
66
+ pumpOrigin(origin, current);
67
+ };
68
+ const abort = () => remove('REQUEST_ABORTED');
69
+ const timer = setTimeout(() => remove('REQUEST_TIMEOUT'), Math.max(0, deadline - Date.now()));
70
+ const waiter = {
71
+ ready: resolve,
72
+ fail: reject,
73
+ cleanup: () => {
74
+ clearTimeout(timer);
75
+ options.signal?.removeEventListener('abort', abort);
76
+ },
77
+ };
78
+ current.queue.push(waiter);
79
+ options.signal?.addEventListener('abort', abort, { once: true });
80
+ if (options.signal?.aborted)
81
+ abort();
82
+ else if (deadline <= Date.now())
83
+ remove('REQUEST_TIMEOUT');
84
+ else
85
+ pumpOrigin(origin, current);
86
+ });
87
+ }
88
+ function recordCooldown(origin, status, retryAfter) {
89
+ const schedule = originSchedules.get(origin);
90
+ if (!schedule || ![403, 429].includes(status) || typeof retryAfter !== 'string')
91
+ return;
92
+ const value = retryAfter.trim();
93
+ const until = /^\d+$/.test(value) ? Date.now() + Number(value) * 1000 : Date.parse(value);
94
+ if (!(until > Date.now()))
95
+ return;
96
+ schedule.cooldown = Math.max(schedule.cooldown, Math.min(until, Date.now() + MAX_COOLDOWN_MS));
97
+ pumpOrigin(origin, schedule);
98
+ }
99
+ export function isPublicAddress(address) {
100
+ try {
101
+ const parsed = ipaddr.process(address);
102
+ // ::a.b.c.d, the deprecated IPv4-compatible form: a stack that still routes it reaches the
103
+ // embedded IPv4 address, which may be this machine. Written with a dotted quad the address is
104
+ // judged as that IPv4 address; written in hexadecimal it is no public destination.
105
+ if (parsed.kind() === 'ipv6' && parsed.parts.slice(0, 6).every((part) => part === 0))
106
+ return false;
107
+ return parsed.range() === 'unicast';
108
+ }
109
+ catch {
110
+ return false;
111
+ }
112
+ }
113
+ /**
114
+ * Whether an unencrypted connection to this address stays on this machine or a private network:
115
+ * loopback, RFC 1918, carrier-grade NAT (also used by overlay networks), link-local and IPv6
116
+ * unique-local addresses. Addresses that wrap a public IPv4 address (NAT64, 6to4, Teredo),
117
+ * multicast and reserved ranges are not private.
118
+ */
119
+ export function privateAddress(address) {
120
+ try {
121
+ return ['private', 'loopback', 'linkLocal', 'carrierGradeNat', 'uniqueLocal', 'unspecified'].includes(ipaddr.process(address).range());
122
+ }
123
+ catch {
124
+ return false;
125
+ }
126
+ }
127
+ export function validateDestination(value, allowPrivate = false) {
128
+ let url;
129
+ try {
130
+ url = new URL(value);
131
+ }
132
+ catch {
133
+ throw new NetworkError('INVALID_URL');
134
+ }
135
+ if (url.username ||
136
+ url.password ||
137
+ url.hash ||
138
+ !['https:', ...(allowPrivate ? ['http:'] : [])].includes(url.protocol))
139
+ throw new NetworkError('DESTINATION_DENIED');
140
+ // A trailing dot names the same host ("localhost.").
141
+ const host = url.hostname.replace(/^\[|\]$/g, '').replace(/\.+$/, '');
142
+ if (!allowPrivate &&
143
+ (host === 'localhost' || host.endsWith('.localhost') || (isIP(host) && !isPublicAddress(host))))
144
+ throw new NetworkError('DESTINATION_DENIED');
145
+ // Permission to reach a private destination is not permission to send a request in the clear
146
+ // across the internet: plain HTTP is only for private and local addresses.
147
+ if (url.protocol === 'http:' && isIP(host) && !privateAddress(host))
148
+ throw new NetworkError('DESTINATION_DENIED');
149
+ return url;
150
+ }
151
+ export const safeHttp = async (value, options = {}) => {
152
+ if (options.signal?.aborted)
153
+ throw new NetworkError('REQUEST_ABORTED');
154
+ const url = validateDestination(value, options.allowPrivate);
155
+ const maxBytes = options.maxBytes ?? 4_194_304;
156
+ const timeoutMs = options.timeoutMs ?? 20_000;
157
+ const deadline = Date.now() + timeoutMs;
158
+ if (Buffer.byteLength(options.body ?? '') > 2_097_152)
159
+ throw new NetworkError('REQUEST_TOO_LARGE');
160
+ const secureLookup = (hostname, lookupOptions, callback) => {
161
+ lookup(hostname, { all: true, verbatim: true }, (error, addresses) => {
162
+ if (error || !addresses.length) {
163
+ callback(new NetworkError('DNS_FAILED'), '', 4);
164
+ return;
165
+ }
166
+ if (!options.allowPrivate && addresses.some((a) => !isPublicAddress(a.address))) {
167
+ callback(new NetworkError('DESTINATION_DENIED'), '', 4);
168
+ return;
169
+ }
170
+ // A name that resolves to a public address must not receive a plain HTTP request.
171
+ if (url.protocol === 'http:' && addresses.some((a) => !privateAddress(a.address))) {
172
+ callback(new NetworkError('DESTINATION_DENIED'), '', 4);
173
+ return;
174
+ }
175
+ // Resolve and validate the addresses actually used by the socket, including redirects.
176
+ if (lookupOptions.all)
177
+ callback(null, addresses);
178
+ else
179
+ callback(null, addresses[0].address, addresses[0].family);
180
+ });
181
+ };
182
+ const release = await originSlot(url.origin, options, deadline);
183
+ let response;
184
+ try {
185
+ if (options.signal?.aborted)
186
+ throw new NetworkError('REQUEST_ABORTED');
187
+ if (deadline <= Date.now())
188
+ throw new NetworkError('REQUEST_TIMEOUT');
189
+ response = await new Promise((resolve, reject) => {
190
+ const request = url.protocol === 'https:' ? httpsRequest : httpRequest;
191
+ let connected = false;
192
+ const req = request(url, {
193
+ method: options.method ?? 'GET',
194
+ lookup: secureLookup,
195
+ agent: false,
196
+ signal: options.signal,
197
+ headers: {
198
+ 'user-agent': 'Shielda-Security-Watch/1.0',
199
+ 'accept-encoding': 'identity',
200
+ ...options.headers,
201
+ },
202
+ }, (res) => {
203
+ recordCooldown(url.origin, res.statusCode ?? 0, res.headers['retry-after']);
204
+ const chunks = [];
205
+ let size = 0;
206
+ res.on('data', (chunk) => {
207
+ size += chunk.length;
208
+ if (size > maxBytes) {
209
+ clearTimeout(timer);
210
+ reject(new NetworkError('RESPONSE_TOO_LARGE'));
211
+ res.destroy();
212
+ req.destroy();
213
+ return;
214
+ }
215
+ chunks.push(chunk);
216
+ });
217
+ res.on('error', () => {
218
+ clearTimeout(timer);
219
+ reject(new NetworkError(options.signal?.aborted ? 'REQUEST_ABORTED' : 'RESPONSE_FAILED'));
220
+ });
221
+ res.on('end', () => {
222
+ clearTimeout(timer);
223
+ const headers = Object.fromEntries(Object.entries(res.headers).map(([k, v]) => [k, Array.isArray(v) ? v.join(',') : (v ?? '')]));
224
+ resolve({ status: res.statusCode ?? 0, headers, body: Buffer.concat(chunks).toString('utf8') });
225
+ });
226
+ });
227
+ const timer = setTimeout(() => req.destroy(new NetworkError('REQUEST_TIMEOUT')), Math.max(0, deadline - Date.now()));
228
+ req.on('socket', (socket) => {
229
+ if (!socket.connecting)
230
+ connected = true;
231
+ else
232
+ socket.once('connect', () => (connected = true));
233
+ });
234
+ req.on('error', (error) => {
235
+ clearTimeout(timer);
236
+ const code = 'code' in error ? error.code : undefined;
237
+ const connectionFailed = !connected &&
238
+ (['ECONNREFUSED', 'ENETUNREACH', 'EHOSTUNREACH'].includes(String(code)) ||
239
+ (error instanceof NetworkError && error.code === 'REQUEST_TIMEOUT'));
240
+ reject(options.signal?.aborted
241
+ ? new NetworkError('REQUEST_ABORTED')
242
+ : connectionFailed
243
+ ? new NetworkError('CONNECTION_FAILED')
244
+ : error instanceof NetworkError
245
+ ? error
246
+ : new NetworkError('REQUEST_FAILED'));
247
+ });
248
+ if (options.body)
249
+ req.write(options.body);
250
+ req.end();
251
+ });
252
+ }
253
+ finally {
254
+ release();
255
+ }
256
+ if ([301, 302, 303, 307, 308].includes(response.status)) {
257
+ const redirects = options.redirects ?? 2;
258
+ if (redirects <= 0 || (options.method && options.method !== 'GET'))
259
+ throw new NetworkError('REDIRECT_DENIED');
260
+ const location = response.headers.location;
261
+ if (!location)
262
+ throw new NetworkError('INVALID_REDIRECT');
263
+ let destination;
264
+ try {
265
+ destination = new URL(location, url).href;
266
+ }
267
+ catch {
268
+ throw new NetworkError('INVALID_REDIRECT');
269
+ }
270
+ const next = validateDestination(destination, options.allowPrivate);
271
+ if (options.allowedRedirectOrigins && !options.allowedRedirectOrigins.includes(next.origin))
272
+ throw new NetworkError('REDIRECT_DENIED');
273
+ const nextOptions = { ...options, redirects: redirects - 1 };
274
+ // Never send authentication headers to a different origin.
275
+ if (next.origin !== url.origin)
276
+ nextOptions.headers = { accept: options.headers?.accept ?? '*/*' };
277
+ return safeHttp(next.href, nextOptions);
278
+ }
279
+ return response;
280
+ };
@@ -0,0 +1,36 @@
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';
2
+ export { scorePilotResponses, type PilotResponseRegister, type PilotResponseScore, } from './pilot-responses.js';
3
+ export { loadConfig, parseConfig, configSchema } from './config.js';
4
+ export { loadInventory } from './inventory.js';
5
+ export { assess, decide } from './assessment.js';
6
+ export { collectSources } from './sources.js';
7
+ export { ModelAnalyzer, validateAnalysis } from './models.js';
8
+ export type { ModelState } from './models.js';
9
+ export { PROVIDERS, PROVIDER_IDS, providerDefinition } from './providers.js';
10
+ export type { ProviderDefinition, ProviderProtocol, ModelProvider, OutputFormat } from './providers.js';
11
+ export { Store, readPilotReport, SCHEMA_VERSION } from './store.js';
12
+ export type { PilotReport, PilotWindow } from './pilot-report.js';
13
+ export { createPilotCasePacket, scorePilotCases } from './pilot-cases.js';
14
+ export type { PilotCasePacket, PilotScore, PilotFeedback } from './pilot-cases.js';
15
+ export { createPilotResponseTemplate, scorePilotRecall, type PilotIncidentReference, type PilotRecallScore, } from './pilot-recall.js';
16
+ export { deliverPending, notificationText, sendEmail, smtpProblem } from './delivery.js';
17
+ export type { DeliveryOptions, EmailMessage, EmailReceipt, EmailSender } from './delivery.js';
18
+ export { safeHttp } from './http.js';
19
+ export { acquireLock } from './lock.js';
20
+ export { runScan, readFixture } from './engine.js';
21
+ export { checkHealth } from './health.js';
22
+ export type { HealthReport } from './health.js';
23
+ export { ECOSYSTEMS, normalizeEcosystem, normalizePackageName, parseLibraryList } from './ecosystems.js';
24
+ export type { Ecosystem, Library } from './ecosystems.js';
25
+ export { HeartbeatMonitor } from './heartbeat.js';
26
+ export type { ExternalHeartbeat } from './heartbeat.js';
27
+ export { MaintenanceScheduler } from './operations.js';
28
+ export type { MaintenanceRun } from './operations.js';
29
+ export { verifyBackup, readPilotBackupReport } from './maintenance.js';
30
+ export { runRehearsal, readRehearsal } from './rehearsal.js';
31
+ export type { RehearsalReport, RehearsalScenario, RehearsalSink } from './rehearsal.js';
32
+ export type { RetentionPolicy, PruneCounts, PruneReport, BackupVerification } from './maintenance.js';
33
+ export { importCycloneDx } from './sbom.js';
34
+ export type { SbomImport } from './sbom.js';
35
+ export { compareInventories, attachLocation, attachRemediation } from './inventory-evidence.js';
36
+ export { refreshCoverage } from './coverage.js';
package/dist/index.js ADDED
@@ -0,0 +1,23 @@
1
+ export { scorePilotResponses, } from './pilot-responses.js';
2
+ export { loadConfig, parseConfig, configSchema } from './config.js';
3
+ export { loadInventory } from './inventory.js';
4
+ export { assess, decide } from './assessment.js';
5
+ export { collectSources } from './sources.js';
6
+ export { ModelAnalyzer, validateAnalysis } from './models.js';
7
+ export { PROVIDERS, PROVIDER_IDS, providerDefinition } from './providers.js';
8
+ export { Store, readPilotReport, SCHEMA_VERSION } from './store.js';
9
+ export { createPilotCasePacket, scorePilotCases } from './pilot-cases.js';
10
+ export { createPilotResponseTemplate, scorePilotRecall, } from './pilot-recall.js';
11
+ export { deliverPending, notificationText, sendEmail, smtpProblem } from './delivery.js';
12
+ export { safeHttp } from './http.js';
13
+ export { acquireLock } from './lock.js';
14
+ export { runScan, readFixture } from './engine.js';
15
+ export { checkHealth } from './health.js';
16
+ export { ECOSYSTEMS, normalizeEcosystem, normalizePackageName, parseLibraryList } from './ecosystems.js';
17
+ export { HeartbeatMonitor } from './heartbeat.js';
18
+ export { MaintenanceScheduler } from './operations.js';
19
+ export { verifyBackup, readPilotBackupReport } from './maintenance.js';
20
+ export { runRehearsal, readRehearsal } from './rehearsal.js';
21
+ export { importCycloneDx } from './sbom.js';
22
+ export { compareInventories, attachLocation, attachRemediation } from './inventory-evidence.js';
23
+ export { refreshCoverage } from './coverage.js';
@@ -0,0 +1,10 @@
1
+ import type { Assessment, Config, Evidence, Inventory, InventoryDrift } from './types.js';
2
+ /** Compares declarations; a changed or removed declaration never proves deployed remediation. */
3
+ export declare function compareInventories(previous: Inventory | undefined, current: Inventory): InventoryDrift[];
4
+ /**
5
+ * Copy the inventory's own names and notes onto a finding so a notification says where to look.
6
+ * This is the operator's text, not evidence: it never changes applicability, priority or routing.
7
+ */
8
+ export declare function attachLocation(finding: Assessment, inventory: Inventory): Assessment;
9
+ /** Cited guidance and operator observations, never an automatic closure or configuration attestation. */
10
+ export declare function attachRemediation(finding: Assessment, inventory: Inventory, evidence: Evidence[], config: Config, now: number): Assessment;