@xkwdstore/agent 2.1.4 → 2.1.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +163 -0
- package/README.md +281 -278
- package/package.json +43 -42
- package/scripts/install-machine-agent.ps1 +385 -385
- package/src/actions/helpers.js +15 -21
- package/src/actions/session.js +142 -16
- package/src/brokerConnectionSupervisor.js +319 -263
- package/src/brokerHealth.js +113 -0
- package/src/brokerWorkerBridge.js +377 -352
- package/src/browserConnectivity.js +1461 -0
- package/src/browserIsolation.js +26 -1
- package/src/browserLaunch.js +136 -0
- package/src/cli.js +1290 -1108
- package/src/cookieInjection.js +255 -0
- package/src/enrollmentClient.js +51 -26
- package/src/index.js +75 -53
- package/src/proxyCapability.js +481 -0
- package/src/sessionAuth.js +439 -0
- package/src/sessionHandler.js +709 -108
- package/src/worker.js +707 -253
|
@@ -0,0 +1,481 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Capability-based proxy health assessment (2.1.5).
|
|
5
|
+
*
|
|
6
|
+
* WHY
|
|
7
|
+
* ---
|
|
8
|
+
* The previous preflight proved only that `https://api.ipify.org/` answered. A
|
|
9
|
+
* proxy can tunnel that endpoint (and x.com) perfectly while returning 403,
|
|
10
|
+
* refusing CONNECT, or silently black-holing Google/Alphabet destinations. That
|
|
11
|
+
* is exactly the production failure this module is built to detect: the proxy is
|
|
12
|
+
* NOT "down", it is *destination-restricted*, and the operator must be told which
|
|
13
|
+
* destinations fail so the provider can be fixed.
|
|
14
|
+
*
|
|
15
|
+
* WHAT
|
|
16
|
+
* ----
|
|
17
|
+
* Probe every managed destination (Google Search, Chrome Web Store, Google
|
|
18
|
+
* accounts, gstatic, clients2, update.googleapis.com, example.com, x.com,
|
|
19
|
+
* api.ipify.org) through the configured proxy with a real DNS/TCP/TLS/HTTP
|
|
20
|
+
* exchange, then classify:
|
|
21
|
+
*
|
|
22
|
+
* HEALTHY · DEGRADED · AUTHENTICATION_FAILED · CONNECT_TIMEOUT · DNS_FAILED ·
|
|
23
|
+
* TLS_FAILED · DESTINATION_UNREACHABLE · DESTINATION_RESTRICTED ·
|
|
24
|
+
* CONNECTION_REFUSED · UNREACHABLE · UNKNOWN
|
|
25
|
+
*
|
|
26
|
+
* `DESTINATION_RESTRICTED` is only reported with evidence: the proxy must have
|
|
27
|
+
* successfully carried at least one other destination in the same assessment
|
|
28
|
+
* (usually the baseline and/or the echo endpoint). A proxy that fails everything
|
|
29
|
+
* is a transport failure, not a destination restriction.
|
|
30
|
+
*
|
|
31
|
+
* SAFETY
|
|
32
|
+
* ------
|
|
33
|
+
* - Never falls back to a direct connection. If a proxy is configured, every
|
|
34
|
+
* probe tunnels through it (HTTP CONNECT or SOCKS5).
|
|
35
|
+
* - Bounded: per-destination timeout, bounded concurrency, short-lived cache and
|
|
36
|
+
* a per-proxy rate limit (proxy bandwidth is expensive).
|
|
37
|
+
* - Sanitized: never returns credentials, headers, cookies or full URLs with
|
|
38
|
+
* query strings.
|
|
39
|
+
* - No automatic proxy switching and no proxy assignment changes.
|
|
40
|
+
*/
|
|
41
|
+
|
|
42
|
+
const dns = require('dns');
|
|
43
|
+
const tls = require('tls');
|
|
44
|
+
const connectivity = require('./browserConnectivity');
|
|
45
|
+
|
|
46
|
+
/** Canonical proxy health states. */
|
|
47
|
+
const PROXY_HEALTH_STATES = Object.freeze({
|
|
48
|
+
HEALTHY: 'HEALTHY',
|
|
49
|
+
DEGRADED: 'DEGRADED',
|
|
50
|
+
AUTHENTICATION_FAILED: 'AUTHENTICATION_FAILED',
|
|
51
|
+
CONNECT_TIMEOUT: 'CONNECT_TIMEOUT',
|
|
52
|
+
DNS_FAILED: 'DNS_FAILED',
|
|
53
|
+
TLS_FAILED: 'TLS_FAILED',
|
|
54
|
+
DESTINATION_UNREACHABLE: 'DESTINATION_UNREACHABLE',
|
|
55
|
+
DESTINATION_RESTRICTED: 'DESTINATION_RESTRICTED',
|
|
56
|
+
CONNECTION_REFUSED: 'CONNECTION_REFUSED',
|
|
57
|
+
UNREACHABLE: 'UNREACHABLE',
|
|
58
|
+
UNKNOWN: 'UNKNOWN',
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Destinations the product depends on. `kind` drives the overall assessment:
|
|
63
|
+
* `baseline`/`echo` prove the proxy itself works; `target` destinations are the
|
|
64
|
+
* ones users actually need.
|
|
65
|
+
*/
|
|
66
|
+
const PROXY_DESTINATIONS = Object.freeze([
|
|
67
|
+
{ key: 'example', url: 'https://example.com', kind: 'baseline', label: 'Baseline (example.com)' },
|
|
68
|
+
{ key: 'ipify', url: 'https://api.ipify.org', kind: 'echo', label: 'Egress IP echo (api.ipify.org)' },
|
|
69
|
+
{ key: 'googleSearch', url: 'https://www.google.com', kind: 'target', label: 'Google Search' },
|
|
70
|
+
{ key: 'googleWebStore', url: 'https://chromewebstore.google.com', kind: 'target', label: 'Chrome Web Store' },
|
|
71
|
+
{ key: 'googleAccounts', url: 'https://accounts.google.com', kind: 'target', label: 'Google accounts/sign-in' },
|
|
72
|
+
{ key: 'googleStatic', url: 'https://www.gstatic.com', kind: 'target', label: 'Google static assets (gstatic)' },
|
|
73
|
+
{ key: 'googleClients2', url: 'https://clients2.google.com', kind: 'target', label: 'Google extension services (clients2)' },
|
|
74
|
+
{ key: 'googleUpdate', url: 'https://update.googleapis.com', kind: 'target', label: 'Google updater (update.googleapis.com)' },
|
|
75
|
+
{ key: 'x', url: 'https://x.com', kind: 'target', label: 'X (x.com)' },
|
|
76
|
+
]);
|
|
77
|
+
|
|
78
|
+
const PROXY_PROTOCOLS = Object.freeze(['http', 'https', 'socks5', 'socks5h', 'socks4']);
|
|
79
|
+
|
|
80
|
+
const DEFAULT_TIMEOUT_MS = 8000;
|
|
81
|
+
const DEFAULT_CONCURRENCY = 3;
|
|
82
|
+
const DEFAULT_CACHE_TTL_MS = 60000;
|
|
83
|
+
const DEFAULT_RATE_LIMIT_WINDOW_MS = 60000;
|
|
84
|
+
const DEFAULT_RATE_LIMIT_MAX = 2; // one assessment = up to 9 tunnelled requests
|
|
85
|
+
|
|
86
|
+
// ── Cache + rate limit (process-local, bounded) ──────────────────────────────
|
|
87
|
+
|
|
88
|
+
const _cache = new Map(); // key -> { at, report }
|
|
89
|
+
const _rate = new Map(); // key -> [timestamps]
|
|
90
|
+
const CACHE_MAX_ENTRIES = 50;
|
|
91
|
+
const RATE_MAX_KEYS = 200;
|
|
92
|
+
|
|
93
|
+
function _pruneMap(map, maxKeys) {
|
|
94
|
+
while (map.size > maxKeys) {
|
|
95
|
+
const oldest = map.keys().next().value;
|
|
96
|
+
map.delete(oldest);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** Test hook: clear cache/rate state deterministically. */
|
|
101
|
+
function _resetProxyHealthState() {
|
|
102
|
+
_cache.clear();
|
|
103
|
+
_rate.clear();
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function _cacheKey(proxyDesc, urls, timeoutMs) {
|
|
107
|
+
return JSON.stringify([proxyDesc.scheme, proxyDesc.host, proxyDesc.port, proxyDesc.authSet, timeoutMs, urls.slice().sort()]);
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function _rateKey(proxyDesc) {
|
|
111
|
+
return `${proxyDesc.scheme}://${proxyDesc.host}:${proxyDesc.port}`;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// ── Classification ───────────────────────────────────────────────────────────
|
|
115
|
+
|
|
116
|
+
/** Map a probe result code to one canonical per-destination state. */
|
|
117
|
+
function classifyDestinationState(probe) {
|
|
118
|
+
const code = String((probe && probe.code) || '');
|
|
119
|
+
const status = probe && probe.status;
|
|
120
|
+
if (probe && probe.ok === true) {
|
|
121
|
+
if (status === 401 || status === 403 || status === 407 || status === 451) return PROXY_HEALTH_STATES.DESTINATION_RESTRICTED;
|
|
122
|
+
if (status === 429) return PROXY_HEALTH_STATES.DEGRADED;
|
|
123
|
+
return PROXY_HEALTH_STATES.HEALTHY;
|
|
124
|
+
}
|
|
125
|
+
if (code === 'PROXY_AUTH_FAILED') return PROXY_HEALTH_STATES.AUTHENTICATION_FAILED;
|
|
126
|
+
if (code === 'PROXY_TARGET_DENIED') return PROXY_HEALTH_STATES.DESTINATION_RESTRICTED;
|
|
127
|
+
if (code === 'PROXY_CONNECT_TIMEOUT' || code === 'PROBE_CONNECT_TIMEOUT' || code === 'PROBE_OVERALL_TIMEOUT' || code === 'PROBE_HTTP_TIMEOUT' || code === 'PROXY_AUTH_TIMEOUT') {
|
|
128
|
+
return PROXY_HEALTH_STATES.CONNECT_TIMEOUT;
|
|
129
|
+
}
|
|
130
|
+
if (code === 'PROXY_TARGET_UNREACHABLE') return PROXY_HEALTH_STATES.DESTINATION_UNREACHABLE;
|
|
131
|
+
if (code === 'PROXY_TCP_REFUSED' || code === 'PROBE_TCP_REFUSED' || code === 'ECONNREFUSED') return PROXY_HEALTH_STATES.CONNECTION_REFUSED;
|
|
132
|
+
if (code === 'PROBE_DNS_FAILED' || code === 'PROXY_DNS_FAILED' || code === 'PROBE_DNS_TIMEOUT') return PROXY_HEALTH_STATES.DNS_FAILED;
|
|
133
|
+
if (code === 'TLS_CERTIFICATE_ERROR' || code === 'PROXY_TLS_FAILED' || code === 'PROBE_TLS_TIMEOUT') {
|
|
134
|
+
return PROXY_HEALTH_STATES.TLS_FAILED;
|
|
135
|
+
}
|
|
136
|
+
if (code === 'PROXY_CONNECT_REJECTED' || code === 'PROXY_TUNNEL_INVALID' || code === 'PROXY_PROTOCOL_MISMATCH' || code === 'PROXY_AUTH_UNSUPPORTED') {
|
|
137
|
+
return PROXY_HEALTH_STATES.UNREACHABLE;
|
|
138
|
+
}
|
|
139
|
+
if (code === 'PROBE_TCP_RESET' || code === 'PROXY_TUNNEL_CLOSED' || (probe && probe.silentDrop === true)) {
|
|
140
|
+
return PROXY_HEALTH_STATES.UNREACHABLE;
|
|
141
|
+
}
|
|
142
|
+
if (code === 'HTTP_CLIENT_STATUS' || code === 'HTTP_SERVER_ERROR') {
|
|
143
|
+
// Reachable but the origin said no: 4xx other than auth/limit is still a
|
|
144
|
+
// valid HTTP answer (e.g. gstatic 404 at /) and proves the tunnel works.
|
|
145
|
+
if (status === 401 || status === 403 || status === 407 || status === 451) return PROXY_HEALTH_STATES.DESTINATION_RESTRICTED;
|
|
146
|
+
if (status === 429) return PROXY_HEALTH_STATES.DEGRADED;
|
|
147
|
+
if (status >= 500) return PROXY_HEALTH_STATES.DEGRADED;
|
|
148
|
+
return PROXY_HEALTH_STATES.HEALTHY;
|
|
149
|
+
}
|
|
150
|
+
if (code === 'PROBE_TARGET_INVALID' || code === 'PROXY_FORMAT_INVALID') return PROXY_HEALTH_STATES.UNKNOWN;
|
|
151
|
+
return PROXY_HEALTH_STATES.UNKNOWN;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
const FATAL_TRANSPORT_STATES = new Set([
|
|
155
|
+
PROXY_HEALTH_STATES.AUTHENTICATION_FAILED,
|
|
156
|
+
PROXY_HEALTH_STATES.CONNECT_TIMEOUT,
|
|
157
|
+
PROXY_HEALTH_STATES.CONNECTION_REFUSED,
|
|
158
|
+
PROXY_HEALTH_STATES.DNS_FAILED,
|
|
159
|
+
PROXY_HEALTH_STATES.TLS_FAILED,
|
|
160
|
+
PROXY_HEALTH_STATES.UNREACHABLE,
|
|
161
|
+
]);
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* Derive the overall state from per-destination results + their kinds.
|
|
165
|
+
*
|
|
166
|
+
* @param {Array<{kind:string,state:string}>} entries
|
|
167
|
+
*/
|
|
168
|
+
function deriveOverallState(entries) {
|
|
169
|
+
if (!Array.isArray(entries) || entries.length === 0) return PROXY_HEALTH_STATES.UNKNOWN;
|
|
170
|
+
const withKind = (kind) => entries.filter((e) => e.kind === kind);
|
|
171
|
+
const baseline = [...withKind('baseline'), ...withKind('echo')];
|
|
172
|
+
const targets = withKind('target');
|
|
173
|
+
const all = entries;
|
|
174
|
+
|
|
175
|
+
// An authentication failure on any destination is fatal for the whole proxy.
|
|
176
|
+
if (all.some((e) => e.state === PROXY_HEALTH_STATES.AUTHENTICATION_FAILED)) return PROXY_HEALTH_STATES.AUTHENTICATION_FAILED;
|
|
177
|
+
|
|
178
|
+
const baselineOk = baseline.some((e) => e.state === PROXY_HEALTH_STATES.HEALTHY);
|
|
179
|
+
const baselineStates = new Set(baseline.map((e) => e.state));
|
|
180
|
+
|
|
181
|
+
// Confirmed destination restriction: the proxy demonstrably works for a
|
|
182
|
+
// baseline/echo destination, while a *target* is explicitly denied or the
|
|
183
|
+
// proxy refuses/resets that target (not merely a timeout — a timeout is not
|
|
184
|
+
// proof of a restriction).
|
|
185
|
+
const restrictedTargets = targets.filter((e) => e.state === PROXY_HEALTH_STATES.DESTINATION_RESTRICTED);
|
|
186
|
+
const refusedTargets = targets.filter((e) => e.state === PROXY_HEALTH_STATES.DESTINATION_UNREACHABLE
|
|
187
|
+
|| e.state === PROXY_HEALTH_STATES.UNREACHABLE
|
|
188
|
+
|| e.state === PROXY_HEALTH_STATES.CONNECTION_REFUSED);
|
|
189
|
+
if (baselineOk && (restrictedTargets.length > 0 || (targets.length > 0 && refusedTargets.length === targets.length))) {
|
|
190
|
+
return PROXY_HEALTH_STATES.DESTINATION_RESTRICTED;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
// No baseline worked: report the dominant transport failure.
|
|
194
|
+
if (!baselineOk) {
|
|
195
|
+
for (const s of [
|
|
196
|
+
PROXY_HEALTH_STATES.CONNECT_TIMEOUT,
|
|
197
|
+
PROXY_HEALTH_STATES.CONNECTION_REFUSED,
|
|
198
|
+
PROXY_HEALTH_STATES.DNS_FAILED,
|
|
199
|
+
PROXY_HEALTH_STATES.TLS_FAILED,
|
|
200
|
+
PROXY_HEALTH_STATES.UNREACHABLE,
|
|
201
|
+
]) {
|
|
202
|
+
if (baselineStates.has(s) || all.some((e) => e.state === s)) return s;
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
const healthyCount = entries.filter((e) => e.state === PROXY_HEALTH_STATES.HEALTHY).length;
|
|
207
|
+
if (healthyCount === entries.length) return PROXY_HEALTH_STATES.HEALTHY;
|
|
208
|
+
if (healthyCount > 0) return PROXY_HEALTH_STATES.DEGRADED;
|
|
209
|
+
const anyTransport = entries.find((e) => FATAL_TRANSPORT_STATES.has(e.state));
|
|
210
|
+
if (anyTransport) return anyTransport.state;
|
|
211
|
+
return PROXY_HEALTH_STATES.UNKNOWN;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/** Operator action text per overall state (no secrets, no bypass suggestions). */
|
|
215
|
+
function actionForState(state) {
|
|
216
|
+
switch (state) {
|
|
217
|
+
case PROXY_HEALTH_STATES.HEALTHY:
|
|
218
|
+
return 'No action required.';
|
|
219
|
+
case PROXY_HEALTH_STATES.DEGRADED:
|
|
220
|
+
return 'Some destinations failed while others worked. Re-test; if it persists, ask the proxy provider about the failing hosts.';
|
|
221
|
+
case PROXY_HEALTH_STATES.AUTHENTICATION_FAILED:
|
|
222
|
+
return 'Proxy credentials were rejected or expired. Update the proxy credentials in the proxy pool.';
|
|
223
|
+
case PROXY_HEALTH_STATES.DESTINATION_RESTRICTED:
|
|
224
|
+
return 'The proxy works but denies at least one required destination. Ask the proxy provider/administrator to allow the listed hosts; do not bypass the proxy.';
|
|
225
|
+
case PROXY_HEALTH_STATES.CONNECT_TIMEOUT:
|
|
226
|
+
return 'The proxy accepted no tunnel in time (silent drop / overloaded endpoint). Ask the provider to check the endpoint, or replace the proxy.';
|
|
227
|
+
case PROXY_HEALTH_STATES.CONNECTION_REFUSED:
|
|
228
|
+
return 'The proxy port refused the connection. Verify host/port and that the proxy is running.';
|
|
229
|
+
case PROXY_HEALTH_STATES.DNS_FAILED:
|
|
230
|
+
return 'The proxy host cannot be resolved from this device. Verify DNS and the proxy hostname.';
|
|
231
|
+
case PROXY_HEALTH_STATES.TLS_FAILED:
|
|
232
|
+
return 'TLS negotiation failed through the proxy. Check the proxy TLS endpoint/certificate; certificate verification is never disabled.';
|
|
233
|
+
case PROXY_HEALTH_STATES.DESTINATION_UNREACHABLE:
|
|
234
|
+
return 'The proxy reports the destination unreachable. Ask the provider to confirm egress to the listed hosts.';
|
|
235
|
+
case PROXY_HEALTH_STATES.UNREACHABLE:
|
|
236
|
+
return 'The proxy dropped the tunnel without a response. Verify the endpoint and credentials, then re-test.';
|
|
237
|
+
default:
|
|
238
|
+
return 'The health of this proxy could not be determined. Re-run the diagnostic.';
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
// ── Proxy host DNS / IP-family capability ────────────────────────────────────
|
|
243
|
+
|
|
244
|
+
/**
|
|
245
|
+
* Resolve the proxy host itself over both families (the browser connects to the
|
|
246
|
+
* proxy locally, so this is the only place where the device resolver matters).
|
|
247
|
+
* @returns {Promise<{host:string|null, ipv4:string[], ipv6:string[], error:string|null}>}
|
|
248
|
+
*/
|
|
249
|
+
async function resolveProxyFamilies(proxyDesc, opts = {}) {
|
|
250
|
+
const timeoutMs = Number.isFinite(opts.timeoutMs) ? Math.min(opts.timeoutMs, 5000) : 4000;
|
|
251
|
+
const out = { host: proxyDesc && proxyDesc.host ? proxyDesc.host : null, ipv4: [], ipv6: [], error: null };
|
|
252
|
+
if (!out.host) return out;
|
|
253
|
+
try {
|
|
254
|
+
const all = await Promise.race([
|
|
255
|
+
dns.promises.lookup(out.host, { all: true }),
|
|
256
|
+
new Promise((_, rej) => setTimeout(() => rej(Object.assign(new Error('dns timeout'), { code: 'PROBE_DNS_TIMEOUT' })), timeoutMs)),
|
|
257
|
+
]);
|
|
258
|
+
for (const a of all) {
|
|
259
|
+
if (a.family === 6) out.ipv6.push(a.address);
|
|
260
|
+
else out.ipv4.push(a.address);
|
|
261
|
+
}
|
|
262
|
+
} catch (err) {
|
|
263
|
+
out.error = (err && err.code) || 'PROBE_DNS_FAILED';
|
|
264
|
+
}
|
|
265
|
+
return out;
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/** TCP-connect capability of the proxy host per IP family (bounded). */
|
|
269
|
+
async function probeProxyFamilies(proxyDesc, families, opts = {}) {
|
|
270
|
+
const timeoutMs = Number.isFinite(opts.timeoutMs) ? Math.min(opts.timeoutMs, 5000) : 4000;
|
|
271
|
+
const results = [];
|
|
272
|
+
for (const family of [4, 6]) {
|
|
273
|
+
const addresses = family === 4 ? (families && families.ipv4) || [] : (families && families.ipv6) || [];
|
|
274
|
+
if (!addresses.length) {
|
|
275
|
+
results.push({ family, available: false, ok: false, code: 'NO_ADDRESS', ms: null });
|
|
276
|
+
continue;
|
|
277
|
+
}
|
|
278
|
+
const started = Date.now();
|
|
279
|
+
const net = require('net');
|
|
280
|
+
const ok = await new Promise((resolve) => {
|
|
281
|
+
const socket = net.connect({ host: addresses[0], port: proxyDesc.port, family });
|
|
282
|
+
const timer = setTimeout(() => { socket.destroy(); resolve(false); }, timeoutMs);
|
|
283
|
+
if (typeof timer.unref === 'function') timer.unref();
|
|
284
|
+
socket.once('connect', () => { clearTimeout(timer); socket.destroy(); resolve(true); });
|
|
285
|
+
socket.once('error', () => { clearTimeout(timer); resolve(false); });
|
|
286
|
+
});
|
|
287
|
+
results.push({ family, available: true, ok, code: ok ? null : 'TCP_UNREACHABLE', ms: Date.now() - started });
|
|
288
|
+
}
|
|
289
|
+
return results;
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
// ── Main assessment ──────────────────────────────────────────────────────────
|
|
293
|
+
|
|
294
|
+
/**
|
|
295
|
+
* Assess a proxy's capability per destination.
|
|
296
|
+
*
|
|
297
|
+
* @param {object} o
|
|
298
|
+
* @param {object|string} o.proxy configured proxy (string or Playwright object)
|
|
299
|
+
* @param {string[]} [o.urls] override the destination URL list (must stay public https)
|
|
300
|
+
* @param {number} [o.timeoutMs=8000]
|
|
301
|
+
* @param {number} [o.concurrency=3]
|
|
302
|
+
* @param {number} [o.cacheTtlMs=60000] short-lived cache (bandwidth control)
|
|
303
|
+
* @param {boolean} [o.bypassCache=false]
|
|
304
|
+
* @param {boolean} [o.checkFamilies=true] resolve/probe IPv4+IPv6 of the proxy host
|
|
305
|
+
* @param {function} [o.probe] injectable probe (tests)
|
|
306
|
+
* @returns {Promise<object>} sanitized report
|
|
307
|
+
*/
|
|
308
|
+
async function assessProxyHealth(o = {}) {
|
|
309
|
+
const checkedAt = new Date().toISOString();
|
|
310
|
+
const desc = connectivity.sanitizeProxyForReport(o.proxy || null);
|
|
311
|
+
if (!desc.configured || !desc.host) {
|
|
312
|
+
return {
|
|
313
|
+
checkedAt,
|
|
314
|
+
state: PROXY_HEALTH_STATES.UNKNOWN,
|
|
315
|
+
proxy: desc,
|
|
316
|
+
destinations: [],
|
|
317
|
+
summary: { total: 0, healthy: 0, failed: 0 },
|
|
318
|
+
action: 'A proxy is required for a capability assessment.',
|
|
319
|
+
cached: false,
|
|
320
|
+
rateLimited: false,
|
|
321
|
+
};
|
|
322
|
+
}
|
|
323
|
+
const timeoutMs = Number.isFinite(o.timeoutMs) ? Math.min(Math.max(o.timeoutMs, 1000), 30000) : DEFAULT_TIMEOUT_MS;
|
|
324
|
+
const concurrency = Math.max(1, Math.min(Number.isFinite(o.concurrency) ? o.concurrency : DEFAULT_CONCURRENCY, 5));
|
|
325
|
+
const cacheTtlMs = Number.isFinite(o.cacheTtlMs) ? o.cacheTtlMs : DEFAULT_CACHE_TTL_MS;
|
|
326
|
+
|
|
327
|
+
const catalog = Array.isArray(o.urls) && o.urls.length > 0
|
|
328
|
+
? o.urls.map((u) => {
|
|
329
|
+
const hit = PROXY_DESTINATIONS.find((d) => d.url === u);
|
|
330
|
+
return hit || { key: connectivity.safeOrigin(u) || u, url: u, kind: 'target', label: connectivity.safeOrigin(u) || u };
|
|
331
|
+
})
|
|
332
|
+
: PROXY_DESTINATIONS.slice();
|
|
333
|
+
const urls = catalog.map((d) => d.url);
|
|
334
|
+
const key = _cacheKey(desc, urls, timeoutMs);
|
|
335
|
+
|
|
336
|
+
// Cache: a short-lived result avoids burning proxy bandwidth on every status poll.
|
|
337
|
+
if (o.bypassCache !== true) {
|
|
338
|
+
const hit = _cache.get(key);
|
|
339
|
+
if (hit && (Date.now() - hit.at) < cacheTtlMs && hit.report && hit.report.state) {
|
|
340
|
+
return { ...hit.report, cached: true, cacheAgeMs: Date.now() - hit.at };
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
// Rate limit per proxy endpoint: 2 assessments / minute by default.
|
|
345
|
+
const rkey = _rateKey(desc);
|
|
346
|
+
const now = Date.now();
|
|
347
|
+
const windowMs = DEFAULT_RATE_LIMIT_WINDOW_MS;
|
|
348
|
+
const hits = (_rate.get(rkey) || []).filter((t) => now - t < windowMs);
|
|
349
|
+
const maxPerWindow = Number.isFinite(o.rateLimitMax) ? o.rateLimitMax : DEFAULT_RATE_LIMIT_MAX;
|
|
350
|
+
if (hits.length >= maxPerWindow && o.bypassRateLimit !== true) {
|
|
351
|
+
return {
|
|
352
|
+
checkedAt,
|
|
353
|
+
state: PROXY_HEALTH_STATES.UNKNOWN,
|
|
354
|
+
proxy: desc,
|
|
355
|
+
destinations: [],
|
|
356
|
+
summary: { total: 0, healthy: 0, failed: 0 },
|
|
357
|
+
action: `Rate limited to protect proxy bandwidth. Re-test in ${Math.ceil((windowMs - (now - hits[0])) / 1000)}s.`,
|
|
358
|
+
cached: false,
|
|
359
|
+
rateLimited: true,
|
|
360
|
+
retryAfterMs: Math.max(0, windowMs - (now - hits[0])),
|
|
361
|
+
};
|
|
362
|
+
}
|
|
363
|
+
hits.push(now);
|
|
364
|
+
_rate.set(rkey, hits);
|
|
365
|
+
_pruneMap(_rate, RATE_MAX_KEYS);
|
|
366
|
+
|
|
367
|
+
const probe = typeof o.probe === 'function' ? o.probe : connectivity.probeEndpoint;
|
|
368
|
+
const rawResults = new Array(catalog.length);
|
|
369
|
+
let cursor = 0;
|
|
370
|
+
const workers = Array.from({ length: Math.min(concurrency, catalog.length) }, async () => {
|
|
371
|
+
while (cursor < catalog.length) {
|
|
372
|
+
const idx = cursor++;
|
|
373
|
+
const d = catalog[idx];
|
|
374
|
+
let r;
|
|
375
|
+
try {
|
|
376
|
+
r = await probe({ url: d.url, proxy: o.proxy || null, timeoutMs });
|
|
377
|
+
} catch (err) {
|
|
378
|
+
r = { url: d.url, host: connectivity.safeOrigin(d.url), ok: false, code: (err && err.code) || 'PROBE_FAILED', status: null };
|
|
379
|
+
}
|
|
380
|
+
rawResults[idx] = { destination: d, probe: r };
|
|
381
|
+
}
|
|
382
|
+
});
|
|
383
|
+
await Promise.all(workers);
|
|
384
|
+
|
|
385
|
+
const destinations = rawResults.map(({ destination, probe: r }) => {
|
|
386
|
+
const state = classifyDestinationState(r);
|
|
387
|
+
return {
|
|
388
|
+
key: destination.key,
|
|
389
|
+
label: destination.label,
|
|
390
|
+
kind: destination.kind,
|
|
391
|
+
host: (r && r.host) || connectivity.safeOrigin(destination.url),
|
|
392
|
+
state,
|
|
393
|
+
code: (r && r.code) || null,
|
|
394
|
+
httpStatus: r && Number.isFinite(r.status) ? r.status : null,
|
|
395
|
+
ms: r && Number.isFinite(r.ms) ? r.ms : null,
|
|
396
|
+
dnsMs: r && Number.isFinite(r.dnsMs) ? r.dnsMs : null,
|
|
397
|
+
connectMs: r && Number.isFinite(r.connectMs) ? r.connectMs : null,
|
|
398
|
+
tlsMs: r && Number.isFinite(r.tlsMs) ? r.tlsMs : null,
|
|
399
|
+
tunnel: (r && r.tunnel) || null,
|
|
400
|
+
silentDrop: !!(r && r.silentDrop),
|
|
401
|
+
tlsAuthorized: !!(r && r.tls && r.tls.authorized),
|
|
402
|
+
redirectTo: (r && r.redirectTo) || null,
|
|
403
|
+
};
|
|
404
|
+
});
|
|
405
|
+
|
|
406
|
+
const state = deriveOverallState(destinations);
|
|
407
|
+
const healthy = destinations.filter((d) => d.state === PROXY_HEALTH_STATES.HEALTHY).length;
|
|
408
|
+
const failed = destinations.length - healthy;
|
|
409
|
+
const googleDestinations = destinations.filter((d) => d.key.startsWith('google'));
|
|
410
|
+
const googleHealthy = googleDestinations.filter((d) => d.state === PROXY_HEALTH_STATES.HEALTHY).length;
|
|
411
|
+
|
|
412
|
+
const families = o.checkFamilies === false
|
|
413
|
+
? { host: desc.host, ipv4: [], ipv6: [], error: null }
|
|
414
|
+
: await resolveProxyFamilies(desc, { timeoutMs });
|
|
415
|
+
const familyProbes = o.checkFamilies === false ? [] : await probeProxyFamilies(desc, families, { timeoutMs });
|
|
416
|
+
|
|
417
|
+
const report = {
|
|
418
|
+
checkedAt,
|
|
419
|
+
state,
|
|
420
|
+
proxy: desc,
|
|
421
|
+
protocol: desc.scheme || 'http',
|
|
422
|
+
protocolSupported: PROXY_PROTOCOLS.some((p) => String(desc.scheme || '').startsWith(p)),
|
|
423
|
+
destinations,
|
|
424
|
+
capability: {
|
|
425
|
+
google: { healthy: googleHealthy, total: googleDestinations.length, reachable: googleHealthy === googleDestinations.length },
|
|
426
|
+
baseline: destinations.filter((d) => d.kind === 'baseline' || d.kind === 'echo').map((d) => ({ key: d.key, state: d.state })),
|
|
427
|
+
x: (destinations.find((d) => d.key === 'x') || {}).state || null,
|
|
428
|
+
},
|
|
429
|
+
families: { ...families, probes: familyProbes },
|
|
430
|
+
summary: { total: destinations.length, healthy, failed, restricted: destinations.filter((d) => d.state === PROXY_HEALTH_STATES.DESTINATION_RESTRICTED).length },
|
|
431
|
+
action: actionForState(state),
|
|
432
|
+
cached: false,
|
|
433
|
+
rateLimited: false,
|
|
434
|
+
};
|
|
435
|
+
|
|
436
|
+
_cache.set(key, { at: Date.now(), report });
|
|
437
|
+
_pruneMap(_cache, CACHE_MAX_ENTRIES);
|
|
438
|
+
return report;
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
/** A compact, sanitized projection for API responses. */
|
|
442
|
+
function summarizeProxyHealth(report) {
|
|
443
|
+
if (!report || typeof report !== 'object') return null;
|
|
444
|
+
return {
|
|
445
|
+
checkedAt: report.checkedAt || null,
|
|
446
|
+
state: report.state || PROXY_HEALTH_STATES.UNKNOWN,
|
|
447
|
+
proxy: report.proxy || { configured: false },
|
|
448
|
+
protocol: report.protocol || null,
|
|
449
|
+
protocolSupported: report.protocolSupported !== false,
|
|
450
|
+
capability: report.capability || null,
|
|
451
|
+
families: report.families ? {
|
|
452
|
+
ipv4: (report.families.ipv4 || []).length,
|
|
453
|
+
ipv6: (report.families.ipv6 || []).length,
|
|
454
|
+
error: report.families.error || null,
|
|
455
|
+
probes: report.families.probes || [],
|
|
456
|
+
} : null,
|
|
457
|
+
destinations: (report.destinations || []).map((d) => ({
|
|
458
|
+
key: d.key, label: d.label, kind: d.kind, host: d.host, state: d.state,
|
|
459
|
+
code: d.code, httpStatus: d.httpStatus, ms: d.ms, silentDrop: d.silentDrop,
|
|
460
|
+
})),
|
|
461
|
+
summary: report.summary || null,
|
|
462
|
+
action: report.action || null,
|
|
463
|
+
cached: report.cached === true,
|
|
464
|
+
rateLimited: report.rateLimited === true,
|
|
465
|
+
retryAfterMs: report.retryAfterMs || null,
|
|
466
|
+
};
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
module.exports = {
|
|
470
|
+
PROXY_HEALTH_STATES,
|
|
471
|
+
PROXY_DESTINATIONS,
|
|
472
|
+
PROXY_PROTOCOLS,
|
|
473
|
+
classifyDestinationState,
|
|
474
|
+
deriveOverallState,
|
|
475
|
+
actionForState,
|
|
476
|
+
resolveProxyFamilies,
|
|
477
|
+
probeProxyFamilies,
|
|
478
|
+
assessProxyHealth,
|
|
479
|
+
summarizeProxyHealth,
|
|
480
|
+
_resetProxyHealthState,
|
|
481
|
+
};
|