@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,1461 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Browser connectivity diagnostics + navigation failure containment (2.1.5).
|
|
5
|
+
*
|
|
6
|
+
* WHY THIS MODULE EXISTS
|
|
7
|
+
* ----------------------
|
|
8
|
+
* A managed Chromium session can be left on a blank `about:blank` tab with a
|
|
9
|
+
* spinning loader when a proxy accepts TCP but never answers `CONNECT` (dead
|
|
10
|
+
* pool member, black-holed Google/X target, expired credentials that the pool
|
|
11
|
+
* answers by silence). Chromium keeps the navigation pending, Playwright's
|
|
12
|
+
* `page.goto()` only rejects when the caller's own timeout fires, and every
|
|
13
|
+
* call site that used `.catch(() => {})` threw the failure away. The operator
|
|
14
|
+
* then sees a permanently blank tab and no actionable error.
|
|
15
|
+
*
|
|
16
|
+
* This module fixes that at the shared layer:
|
|
17
|
+
*
|
|
18
|
+
* 1. `installNavigationGuard(context)` — sets a bounded default navigation /
|
|
19
|
+
* action timeout on the CONTEXT (so no future call site can forget one)
|
|
20
|
+
* and watches every page (existing and newly opened) for a stalled
|
|
21
|
+
* pending navigation. A tab that stays on `about:blank` with the
|
|
22
|
+
* Chromium "Loading <url>" title past the stall budget is replaced with
|
|
23
|
+
* a self-contained diagnostic page. No request is bypassed and no proxy
|
|
24
|
+
* setting is changed — the stalled navigation is only *reported*.
|
|
25
|
+
*
|
|
26
|
+
* 2. `navigateBounded(page, url, ...)` — a bounded navigation that never
|
|
27
|
+
* throws, always returns a typed result and paints the diagnostic page on
|
|
28
|
+
* failure instead of leaving a blank tab.
|
|
29
|
+
*
|
|
30
|
+
* 3. `probeConnectivity({ proxy })` — the per-endpoint DNS / TCP / TLS /
|
|
31
|
+
* HTTP diagnostic used by the operator CLI. It performs a real request
|
|
32
|
+
* through the configured proxy (HTTP CONNECT + TLS + GET) and NEVER falls
|
|
33
|
+
* back to a direct connection when a proxy is configured.
|
|
34
|
+
*
|
|
35
|
+
* 4. `classifyNavigationFailure(err, ctx)` — maps a Chromium/Playwright error
|
|
36
|
+
* to a typed, actionable code. Proxy, DNS, TLS and timeout failures stay
|
|
37
|
+
* distinct: a network fault is never reported as a logout.
|
|
38
|
+
*
|
|
39
|
+
* NON-NEGOTIABLES
|
|
40
|
+
* ---------------
|
|
41
|
+
* - No credential, cookie, token or Proxy-Authorization value is ever
|
|
42
|
+
* returned, logged or written into the diagnostic page.
|
|
43
|
+
* - Probe targets are public https origins only; the function refuses to
|
|
44
|
+
* emit an https request to a non-https or credential-bearing URL.
|
|
45
|
+
* - Nothing here disables TLS verification or bypasses the configured proxy.
|
|
46
|
+
*/
|
|
47
|
+
|
|
48
|
+
const dns = require('dns');
|
|
49
|
+
const net = require('net');
|
|
50
|
+
const tls = require('tls');
|
|
51
|
+
const path = require('path');
|
|
52
|
+
const os = require('os');
|
|
53
|
+
|
|
54
|
+
// ── Endpoints ────────────────────────────────────────────────────────────────
|
|
55
|
+
|
|
56
|
+
/** The public endpoints the operator-facing diagnostic walks. */
|
|
57
|
+
const CONNECTIVITY_ENDPOINTS = Object.freeze([
|
|
58
|
+
'https://example.com',
|
|
59
|
+
'https://www.google.com',
|
|
60
|
+
'https://chromewebstore.google.com',
|
|
61
|
+
'https://accounts.google.com',
|
|
62
|
+
'https://www.gstatic.com',
|
|
63
|
+
'https://clients2.google.com',
|
|
64
|
+
'https://update.googleapis.com',
|
|
65
|
+
'https://x.com',
|
|
66
|
+
'https://api.ipify.org',
|
|
67
|
+
]);
|
|
68
|
+
|
|
69
|
+
const DEFAULT_PROBE_TIMEOUT_MS = 8000;
|
|
70
|
+
const DEFAULT_NAVIGATION_TIMEOUT_MS = 45000;
|
|
71
|
+
/** A pending navigation younger than this is normal (TLS + TTFB). */
|
|
72
|
+
const DEFAULT_STALL_TIMEOUT_MS = 30000;
|
|
73
|
+
/** Absolute upper bound; independent of the title heuristic. */
|
|
74
|
+
const DEFAULT_HARD_STALL_TIMEOUT_MS = 120000;
|
|
75
|
+
const DIAGNOSTIC_PAGE_PREFIX = 'data:text/html;charset=utf-8,';
|
|
76
|
+
|
|
77
|
+
const USER_AGENT = 'XKWDStore-ConnectivityDiagnostic/1.0';
|
|
78
|
+
|
|
79
|
+
// ── Safe helpers ─────────────────────────────────────────────────────────────
|
|
80
|
+
|
|
81
|
+
function _intFromEnv(name, fallback) {
|
|
82
|
+
const raw = process.env[name];
|
|
83
|
+
const n = parseInt(raw, 10);
|
|
84
|
+
return Number.isFinite(n) && n >= 1000 ? n : fallback;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Reduce any URL to a safe, credential-free display string ("https://host").
|
|
89
|
+
* Never returns a query string, fragment, userinfo or path with a token.
|
|
90
|
+
*/
|
|
91
|
+
function safeOrigin(value) {
|
|
92
|
+
try {
|
|
93
|
+
const u = new URL(String(value));
|
|
94
|
+
if (u.protocol !== 'http:' && u.protocol !== 'https:') return null;
|
|
95
|
+
return `${u.protocol}//${u.hostname}${u.port ? ':' + u.port : ''}`;
|
|
96
|
+
} catch {
|
|
97
|
+
return null;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Describe a proxy WITHOUT its credentials. Only scheme/host/port plus booleans
|
|
103
|
+
* for credential presence are ever exposed.
|
|
104
|
+
*/
|
|
105
|
+
function sanitizeProxyForReport(proxy) {
|
|
106
|
+
if (!proxy) return { configured: false };
|
|
107
|
+
const parsed = parseProxyTarget(proxy);
|
|
108
|
+
if (!parsed) return { configured: true, scheme: null, host: null, port: null, authSet: false, parseable: false };
|
|
109
|
+
return {
|
|
110
|
+
configured: true,
|
|
111
|
+
scheme: parsed.scheme || (typeof proxy === 'object' && /^https:/i.test(String(proxy.server)) ? 'https' : 'http'),
|
|
112
|
+
host: parsed.host,
|
|
113
|
+
port: parsed.port,
|
|
114
|
+
authSet: !!(parsed.username || (proxy && typeof proxy === 'object' && (proxy.username || proxy.password))),
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** True only for a public https URL with no embedded credentials. */
|
|
119
|
+
function isProbeableUrl(value) {
|
|
120
|
+
try {
|
|
121
|
+
const u = new URL(String(value));
|
|
122
|
+
return u.protocol === 'https:' && !u.username && !u.password;
|
|
123
|
+
} catch {
|
|
124
|
+
return false;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* Normalize any accepted proxy spelling to {host,port,username,password}:
|
|
130
|
+
* "http://u:p@host:port", "host:port", "host:port:user:pass",
|
|
131
|
+
* or a Playwright proxy object {server,username,password}.
|
|
132
|
+
* Returns null when it cannot be parsed (callers fail closed, never direct).
|
|
133
|
+
*/
|
|
134
|
+
function parseProxyTarget(proxy) {
|
|
135
|
+
if (!proxy) return null;
|
|
136
|
+
if (typeof proxy === 'object') {
|
|
137
|
+
const server = proxy.server;
|
|
138
|
+
if (!server) return null;
|
|
139
|
+
let u;
|
|
140
|
+
try {
|
|
141
|
+
u = new URL(/^[a-z0-9]+:\/\//i.test(String(server)) ? String(server) : `http://${server}`);
|
|
142
|
+
} catch { return null; }
|
|
143
|
+
const port = parseInt(u.port, 10) || (u.protocol === 'https:' ? 443 : 80);
|
|
144
|
+
if (!u.hostname || !port) return null;
|
|
145
|
+
return {
|
|
146
|
+
host: u.hostname,
|
|
147
|
+
port,
|
|
148
|
+
username: proxy.username || u.username || undefined,
|
|
149
|
+
password: proxy.password || u.password || undefined,
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
let str = String(proxy).trim();
|
|
153
|
+
let scheme = 'http';
|
|
154
|
+
const m = /^([a-z0-9]+):\/\//i.exec(str);
|
|
155
|
+
if (m) { scheme = m[1].toLowerCase(); str = str.slice(m[0].length); }
|
|
156
|
+
let auth = null;
|
|
157
|
+
const at = str.lastIndexOf('@');
|
|
158
|
+
if (at >= 0) { auth = str.slice(0, at); str = str.slice(at + 1); }
|
|
159
|
+
const parts = str.split('/')[0].split(':');
|
|
160
|
+
if (parts.length < 2) return null;
|
|
161
|
+
const host = parts[0];
|
|
162
|
+
const port = parseInt(parts[1], 10);
|
|
163
|
+
let username;
|
|
164
|
+
let password;
|
|
165
|
+
if (auth) {
|
|
166
|
+
const i = auth.indexOf(':');
|
|
167
|
+
username = i < 0 ? auth : auth.slice(0, i);
|
|
168
|
+
password = i < 0 ? undefined : auth.slice(i + 1);
|
|
169
|
+
} else if (parts.length >= 3) {
|
|
170
|
+
username = parts[2];
|
|
171
|
+
password = parts[3];
|
|
172
|
+
}
|
|
173
|
+
if (!host || !Number.isFinite(port) || port <= 0 || port > 65535) return null;
|
|
174
|
+
return { host, port, username, password, scheme };
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
// ── Failure classification ───────────────────────────────────────────────────
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* Map a Chromium/Playwright navigation error to a typed, actionable failure.
|
|
181
|
+
*
|
|
182
|
+
* @param {Error|string} err
|
|
183
|
+
* @param {object} [ctx]
|
|
184
|
+
* @param {string} [ctx.url] the attempted navigation target (host is reported)
|
|
185
|
+
* @param {boolean} [ctx.proxyActive] a proxy-bound launch
|
|
186
|
+
* @param {boolean} [ctx.dnsPinned] `--host-resolver-rules` pin is in effect
|
|
187
|
+
* @returns {{code,stage,reason,message,hint,retryable}}
|
|
188
|
+
*/
|
|
189
|
+
function classifyNavigationFailure(err, ctx = {}) {
|
|
190
|
+
const raw = String((err && err.message) || err || '');
|
|
191
|
+
const lower = raw.toLowerCase();
|
|
192
|
+
const host = safeOrigin(ctx.url);
|
|
193
|
+
const where = host ? ` (${host})` : '';
|
|
194
|
+
const proxyHint = ctx.proxyActive
|
|
195
|
+
? ' The session is proxy-bound: verify the proxy is reachable and permits this target.'
|
|
196
|
+
: '';
|
|
197
|
+
|
|
198
|
+
const mk = (code, stage, reason, message, hint, retryable = true) => ({
|
|
199
|
+
code, stage, reason, message, hint, retryable,
|
|
200
|
+
});
|
|
201
|
+
|
|
202
|
+
if (/timeout|timed out|etimedout/.test(lower)) {
|
|
203
|
+
return mk(
|
|
204
|
+
'NAVIGATION_TIMEOUT',
|
|
205
|
+
'navigation',
|
|
206
|
+
'origin_navigation_timeout',
|
|
207
|
+
`The page did not finish loading within the navigation budget${where}.`,
|
|
208
|
+
'The request may be stalled in the proxy tunnel or at the origin.' + proxyHint,
|
|
209
|
+
);
|
|
210
|
+
}
|
|
211
|
+
if (/net::err_tunnel_connection_failed|net::err_proxy_connection_failed|net::err_proxy_auth|refused connect \(407\)|http 407|\b407\b|proxy auth/.test(lower)) {
|
|
212
|
+
return mk(
|
|
213
|
+
'PROXY_TUNNEL_FAILED',
|
|
214
|
+
'proxy',
|
|
215
|
+
'proxy_transport_failed',
|
|
216
|
+
`The proxy refused or could not open a tunnel${where}.`,
|
|
217
|
+
'Check the proxy endpoint, its credentials and whether it allows this target host.' + proxyHint,
|
|
218
|
+
);
|
|
219
|
+
}
|
|
220
|
+
if (/net::err_name_not_resolved|net::err_name_resolution_failed|enotfound|getaddrinfo|eai_again/.test(lower)) {
|
|
221
|
+
return mk(
|
|
222
|
+
'NAVIGATION_DNS_FAILED',
|
|
223
|
+
ctx.dnsPinned ? 'proxy' : 'navigation',
|
|
224
|
+
ctx.dnsPinned ? 'proxy_dns_pin_unresolved' : 'origin_dns_failed',
|
|
225
|
+
`The hostname could not be resolved${where}.`,
|
|
226
|
+
ctx.dnsPinned
|
|
227
|
+
? 'Name resolution is pinned to the proxy (--host-resolver-rules); the proxy did not resolve this host.'
|
|
228
|
+
: 'Check DNS on this device.' + proxyHint,
|
|
229
|
+
);
|
|
230
|
+
}
|
|
231
|
+
if (/net::err_cert|ssl|tls|certificate/.test(lower)) {
|
|
232
|
+
return mk(
|
|
233
|
+
'TLS_CERTIFICATE_ERROR',
|
|
234
|
+
'tls',
|
|
235
|
+
'tls_certificate_rejected',
|
|
236
|
+
`The TLS handshake or certificate validation failed${where}.`,
|
|
237
|
+
'A TLS-intercepting proxy or a clock/certificate-store problem can cause this. Certificate verification stays enabled.',
|
|
238
|
+
false,
|
|
239
|
+
);
|
|
240
|
+
}
|
|
241
|
+
if (/net::err_internet_disconnected|net::err_network_changed|net::err_network_io_suspended|net::err_network_access_denied/.test(lower)) {
|
|
242
|
+
return mk(
|
|
243
|
+
'NETWORK_UNAVAILABLE',
|
|
244
|
+
'network',
|
|
245
|
+
'host_network_unavailable',
|
|
246
|
+
'The operating system reports no usable network path.',
|
|
247
|
+
'Reconnect the device network and retry.',
|
|
248
|
+
);
|
|
249
|
+
}
|
|
250
|
+
if (/net::err_connection_refused|net::err_connection_reset|net::err_connection_closed|net::err_connection_timed_out|net::err_empty_response|econnrefused|econnreset/.test(lower)) {
|
|
251
|
+
return mk(
|
|
252
|
+
'NAVIGATION_UNREACHABLE',
|
|
253
|
+
'navigation',
|
|
254
|
+
'origin_unreachable',
|
|
255
|
+
`The connection to the origin was refused or closed${where}.`,
|
|
256
|
+
'The target or the proxy closed the connection.' + proxyHint,
|
|
257
|
+
);
|
|
258
|
+
}
|
|
259
|
+
if (/net::err_aborted|err_aborted/.test(lower)) {
|
|
260
|
+
return mk(
|
|
261
|
+
'NAVIGATION_ABORTED',
|
|
262
|
+
'navigation',
|
|
263
|
+
'origin_navigation_aborted',
|
|
264
|
+
`The navigation was aborted${where}.`,
|
|
265
|
+
'The origin may have redirected into a flow this profile cannot complete (e.g. a sign-in redirect).',
|
|
266
|
+
);
|
|
267
|
+
}
|
|
268
|
+
if (/net::err_blocked_by_client|net::err_blocked_by_response|net::err_blocked_by_admin|net::err_unsafe_port/.test(lower)) {
|
|
269
|
+
return mk(
|
|
270
|
+
'NAVIGATION_BLOCKED',
|
|
271
|
+
'policy',
|
|
272
|
+
'navigation_blocked',
|
|
273
|
+
`The browser, an extension or a network policy blocked this navigation${where}.`,
|
|
274
|
+
'Review browser policy and extension rules; no security control is bypassed automatically.',
|
|
275
|
+
false,
|
|
276
|
+
);
|
|
277
|
+
}
|
|
278
|
+
if (/net::err_http_response_code_failure/.test(lower)) {
|
|
279
|
+
return mk(
|
|
280
|
+
'ORIGIN_HTTP_ERROR',
|
|
281
|
+
'origin',
|
|
282
|
+
'origin_error_status',
|
|
283
|
+
`The origin answered with an error status and no usable page${where}.`,
|
|
284
|
+
'A 403/429 here is usually a bot/region block for this network egress. Check the proxy exit and retry later; no security control is bypassed.',
|
|
285
|
+
);
|
|
286
|
+
}
|
|
287
|
+
if (/net::err_invalid_response|net::err_response_headers_too_large/.test(lower)) {
|
|
288
|
+
return mk(
|
|
289
|
+
'ORIGIN_INVALID_RESPONSE',
|
|
290
|
+
'origin',
|
|
291
|
+
'origin_invalid_response',
|
|
292
|
+
`The origin (or an intercepting proxy) returned a malformed response${where}.`,
|
|
293
|
+
'Inspect the proxy response and the origin status with the connectivity diagnostic.',
|
|
294
|
+
);
|
|
295
|
+
}
|
|
296
|
+
return mk(
|
|
297
|
+
'NAVIGATION_FAILED',
|
|
298
|
+
'navigation',
|
|
299
|
+
'origin_navigation_failed',
|
|
300
|
+
`The navigation failed${where}.`,
|
|
301
|
+
'Run the browser connectivity diagnostic for per-host results.' + proxyHint,
|
|
302
|
+
);
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
/**
|
|
306
|
+
* Pure stall detector used by the watchdog. Chromium leaves a pending
|
|
307
|
+
* browser-initiated navigation on `about:blank` and reports the tab title as
|
|
308
|
+
* "Loading <url>" until it commits. That pair is the unambiguous stall signal.
|
|
309
|
+
*
|
|
310
|
+
* `confidence` is `high` for the explicit "Loading <url>" title and `low` when
|
|
311
|
+
* the only signal is a bare target URL in the tab title (older Chromium).
|
|
312
|
+
*
|
|
313
|
+
* @returns {{stalled:boolean, target:string|null, code:string|null, confidence:'high'|'low'|null}}
|
|
314
|
+
*/
|
|
315
|
+
function isStalledNavigation({ url, title } = {}) {
|
|
316
|
+
const u = String(url || '');
|
|
317
|
+
const t = String(title || '').trim();
|
|
318
|
+
const onBlank = u === 'about:blank' || u.startsWith('about:blank#') || u === '';
|
|
319
|
+
if (!onBlank) return { stalled: false, target: null, code: null, confidence: null };
|
|
320
|
+
const high = /^Loading\s+(https?:\/\/\S+)/i.exec(t);
|
|
321
|
+
if (high) return { stalled: true, target: safeOrigin(high[1]) || null, code: 'NAVIGATION_STALLED', confidence: 'high' };
|
|
322
|
+
const low = /^(https?:\/\/\S+)$/i.exec(t);
|
|
323
|
+
if (low) return { stalled: true, target: safeOrigin(low[1]) || null, code: 'NAVIGATION_STALLED', confidence: 'low' };
|
|
324
|
+
return { stalled: false, target: null, code: null, confidence: null };
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
// ── Diagnostic page ──────────────────────────────────────────────────────────
|
|
328
|
+
|
|
329
|
+
function _escapeHtml(value) {
|
|
330
|
+
return String(value == null ? '' : value)
|
|
331
|
+
.replace(/&/g, '&')
|
|
332
|
+
.replace(/</g, '<')
|
|
333
|
+
.replace(/>/g, '>')
|
|
334
|
+
.replace(/"/g, '"')
|
|
335
|
+
.replace(/'/g, ''');
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
/**
|
|
339
|
+
* A safe retry target: http(s) only, no credentials, and **query/fragment
|
|
340
|
+
* stripped** so a token or search parameter can never leak into the diagnostic
|
|
341
|
+
* page (or into a screenshot of it).
|
|
342
|
+
* @returns {string|null}
|
|
343
|
+
*/
|
|
344
|
+
function retryUrlFor(value) {
|
|
345
|
+
try {
|
|
346
|
+
const u = new URL(String(value || ''));
|
|
347
|
+
if (u.protocol !== 'https:' && u.protocol !== 'http:') return null;
|
|
348
|
+
if (u.username || u.password) return null;
|
|
349
|
+
return u.origin + (u.pathname && u.pathname !== '/' ? u.pathname : '/');
|
|
350
|
+
} catch {
|
|
351
|
+
return null;
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
/** True when the retry link drops a query string / fragment from the original. */
|
|
356
|
+
function retryWasSimplified(value) {
|
|
357
|
+
try {
|
|
358
|
+
const u = new URL(String(value || ''));
|
|
359
|
+
return !!(u.search || u.hash);
|
|
360
|
+
} catch {
|
|
361
|
+
return false;
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
/**
|
|
366
|
+
* Build a self-contained, script-free diagnostic page (HTML string). Only the
|
|
367
|
+
* classified code/stage/hint/host are shown — never cookies, tokens, headers or
|
|
368
|
+
* proxy credentials. When the target is a normal http(s) URL a plain RETRY link
|
|
369
|
+
* is included so the operator can resume browsing without any script running on
|
|
370
|
+
* the diagnostic page.
|
|
371
|
+
*/
|
|
372
|
+
function buildDiagnosticHtml(info = {}) {
|
|
373
|
+
const code = _escapeHtml(info.code || 'NAVIGATION_FAILED');
|
|
374
|
+
const stage = _escapeHtml(info.stage || 'navigation');
|
|
375
|
+
const reason = _escapeHtml(info.reason || 'origin_navigation_failed');
|
|
376
|
+
const host = _escapeHtml(info.host || info.targetHost || '');
|
|
377
|
+
const message = _escapeHtml(info.message || 'This browser navigation did not complete.');
|
|
378
|
+
const hint = _escapeHtml(info.hint || 'Run the browser connectivity diagnostic for per-host results.');
|
|
379
|
+
const account = _escapeHtml(info.accountLabel || '');
|
|
380
|
+
const retry = retryUrlFor(info.retryUrl || info.requestedUrl || info.url);
|
|
381
|
+
const retryNote = retry && retryWasSimplified(info.retryUrl || info.requestedUrl || info.url)
|
|
382
|
+
? ' (query parameters were removed from this link for safety)'
|
|
383
|
+
: '';
|
|
384
|
+
return `<!doctype html>
|
|
385
|
+
<html lang="en"><head><meta charset="utf-8">
|
|
386
|
+
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'">
|
|
387
|
+
<title>Navigation failed — ${code}</title>
|
|
388
|
+
<style>
|
|
389
|
+
body{font-family:"Segoe UI",system-ui,sans-serif;margin:0;padding:40px;background:#14161a;color:#e8eaed}
|
|
390
|
+
.card{max-width:760px;margin:0 auto;background:#1e2126;border:1px solid #333840;border-radius:12px;padding:28px}
|
|
391
|
+
h1{font-size:20px;margin:0 0 6px} .code{display:inline-block;background:#2b3038;border-radius:6px;padding:2px 8px;font-size:13px;margin-bottom:18px}
|
|
392
|
+
p{line-height:1.5;margin:8px 0;font-size:14px} .label{color:#9aa0a6;font-size:12px;text-transform:uppercase;letter-spacing:.04em}
|
|
393
|
+
ul{margin:10px 0 0;padding-left:20px;font-size:13px;color:#c6c9ce}
|
|
394
|
+
.retry{display:inline-block;margin:16px 0 4px;padding:9px 16px;border-radius:8px;background:#3b6ef6;color:#fff;text-decoration:none;font-size:14px}
|
|
395
|
+
.retry:hover{background:#2f5cd8}
|
|
396
|
+
</style></head>
|
|
397
|
+
<body><div class="card">
|
|
398
|
+
<div class="label">TW-Manager · browser navigation</div>
|
|
399
|
+
<h1>This page did not load</h1>
|
|
400
|
+
<div class="code">${code}</div>
|
|
401
|
+
<p>${message}</p>
|
|
402
|
+
${host ? `<p><span class="label">Target</span><br>${host}</p>` : ''}
|
|
403
|
+
${account ? `<p><span class="label">Session</span><br>${account}</p>` : ''}
|
|
404
|
+
<p><span class="label">Stage / reason</span><br>${stage} / ${reason}</p>
|
|
405
|
+
<p><span class="label">What to do</span><br>${hint}</p>
|
|
406
|
+
${retry ? `<a class="retry" href="${_escapeHtml(retry)}" rel="noreferrer">Retry this page</a><span style="font-size:12px;color:#9aa0a6">${retryNote}</span>` : ''}
|
|
407
|
+
<ul>
|
|
408
|
+
<li>The browser profile, cookies and installed extensions were not modified.</li>
|
|
409
|
+
<li>The configured proxy was not bypassed; only this navigation was stopped.</li>
|
|
410
|
+
<li>Run <code>browser-connectivity-diag</code> for DNS/TCP/TLS/HTTP results per host.</li>
|
|
411
|
+
</ul>
|
|
412
|
+
</div></body></html>`;
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
/** The diagnostic page as a self-contained data: URL (works with no network). */
|
|
416
|
+
function buildDiagnosticPage(info = {}) {
|
|
417
|
+
return DIAGNOSTIC_PAGE_PREFIX + encodeURIComponent(buildDiagnosticHtml(info));
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
/**
|
|
421
|
+
* Coalesce concurrent paints for the same page. `navigateBounded()` and the
|
|
422
|
+
* context watchdog can both decide to paint the same failure; without a lock one
|
|
423
|
+
* of them navigates away from the other's diagnostic page and reports
|
|
424
|
+
* `painted:false` even though the page is correct.
|
|
425
|
+
*/
|
|
426
|
+
const _paintLocks = new WeakMap();
|
|
427
|
+
|
|
428
|
+
/**
|
|
429
|
+
* Replace a stalled/failed page with the diagnostic page. Best effort and
|
|
430
|
+
* bounded: the first `page.goto(data:)` cancels the pending navigation
|
|
431
|
+
* (verified against a black-holed proxy); `setContent` is the fallback.
|
|
432
|
+
*
|
|
433
|
+
* @returns {Promise<{painted:boolean, via?:string}>}
|
|
434
|
+
*/
|
|
435
|
+
function paintNavigationFailure(page, info = {}, opts = {}) {
|
|
436
|
+
if (!page || typeof page.goto !== 'function') return Promise.resolve({ painted: false });
|
|
437
|
+
try { if (typeof page.isClosed === 'function' && page.isClosed()) return Promise.resolve({ painted: false }); } catch { /* ignore */ }
|
|
438
|
+
const inflight = _paintLocks.get(page);
|
|
439
|
+
if (inflight) return inflight;
|
|
440
|
+
const work = (async () => {
|
|
441
|
+
const timeout = Number.isFinite(opts.timeoutMs) ? opts.timeoutMs : 8000;
|
|
442
|
+
const info2 = { ...info, targetHost: info.targetHost || safeOrigin(info.url) };
|
|
443
|
+
try {
|
|
444
|
+
await page.goto(buildDiagnosticPage(info2), { waitUntil: 'load', timeout });
|
|
445
|
+
return { painted: true, via: 'goto-data-url' };
|
|
446
|
+
} catch { /* fall through */ }
|
|
447
|
+
try {
|
|
448
|
+
if (typeof page.setContent === 'function') {
|
|
449
|
+
await page.setContent(buildDiagnosticHtml(info2), { waitUntil: 'load', timeout });
|
|
450
|
+
return { painted: true, via: 'setContent' };
|
|
451
|
+
}
|
|
452
|
+
} catch { /* give up quietly: containment must never throw */ }
|
|
453
|
+
return { painted: false };
|
|
454
|
+
})();
|
|
455
|
+
_paintLocks.set(page, work);
|
|
456
|
+
return work.finally(() => { try { _paintLocks.delete(page); } catch { /* ignore */ } });
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
/**
|
|
460
|
+
* Bounded navigation. Never throws. On failure the diagnostic page is painted
|
|
461
|
+
* (so the tab never stays on `about:blank`) and a typed result is returned.
|
|
462
|
+
*
|
|
463
|
+
* @param {object} page Playwright page
|
|
464
|
+
* @param {string} url
|
|
465
|
+
* @param {object} [opts]
|
|
466
|
+
* @param {number} [opts.timeoutMs]
|
|
467
|
+
* @param {string} [opts.waitUntil]
|
|
468
|
+
* @param {boolean} [opts.proxyActive]
|
|
469
|
+
* @param {boolean} [opts.dnsPinned]
|
|
470
|
+
* @param {boolean} [opts.paintOnFailure=true]
|
|
471
|
+
* @param {string} [opts.accountLabel]
|
|
472
|
+
* @param {function} [opts.onFailure]
|
|
473
|
+
* @returns {Promise<{ok:boolean, url?:string, status?:number, ms:number, code?:string, stage?:string, reason?:string, painted?:boolean}>}
|
|
474
|
+
*/
|
|
475
|
+
async function navigateBounded(page, url, opts = {}) {
|
|
476
|
+
const timeoutMs = Number.isFinite(opts.timeoutMs) ? opts.timeoutMs : DEFAULT_NAVIGATION_TIMEOUT_MS;
|
|
477
|
+
const waitUntil = opts.waitUntil || 'domcontentloaded';
|
|
478
|
+
const t0 = Date.now();
|
|
479
|
+
try {
|
|
480
|
+
const response = await page.goto(url, { waitUntil, timeout: timeoutMs });
|
|
481
|
+
return {
|
|
482
|
+
ok: true,
|
|
483
|
+
url: (() => { try { return page.url(); } catch { return url; } })(),
|
|
484
|
+
status: response ? response.status() : null,
|
|
485
|
+
ms: Date.now() - t0,
|
|
486
|
+
};
|
|
487
|
+
} catch (err) {
|
|
488
|
+
const failure = classifyNavigationFailure(err, {
|
|
489
|
+
url,
|
|
490
|
+
proxyActive: opts.proxyActive === true,
|
|
491
|
+
dnsPinned: opts.dnsPinned === true,
|
|
492
|
+
});
|
|
493
|
+
const paint = opts.paintOnFailure === false
|
|
494
|
+
? { painted: false }
|
|
495
|
+
: await paintNavigationFailure(page, {
|
|
496
|
+
...failure,
|
|
497
|
+
url,
|
|
498
|
+
accountLabel: opts.accountLabel || null,
|
|
499
|
+
}, { timeoutMs: Math.min(8000, timeoutMs) });
|
|
500
|
+
const result = {
|
|
501
|
+
ok: false,
|
|
502
|
+
ms: Date.now() - t0,
|
|
503
|
+
requestedUrl: url,
|
|
504
|
+
...failure,
|
|
505
|
+
painted: paint.painted === true,
|
|
506
|
+
};
|
|
507
|
+
if (typeof opts.onFailure === 'function') {
|
|
508
|
+
try { opts.onFailure(result); } catch { /* diagnostics must never break a session */ }
|
|
509
|
+
}
|
|
510
|
+
return result;
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
// ── Navigation guard (context-wide watchdog) ─────────────────────────────────
|
|
515
|
+
|
|
516
|
+
/**
|
|
517
|
+
* Install the context-wide navigation guard.
|
|
518
|
+
*
|
|
519
|
+
* - bounds `page.goto`/action timeouts for every current and future page,
|
|
520
|
+
* - watches the MAIN-FRAME DOCUMENT REQUEST through CDP (Network domain) and
|
|
521
|
+
* paints the diagnostic page only when that request is genuinely outstanding
|
|
522
|
+
* with no response after the stall budget. This is a real network signal, not
|
|
523
|
+
* a window-title heuristic: a slow-but-responding page (headers received) is
|
|
524
|
+
* never interrupted, redirects reset the budget, downloads and cancelled
|
|
525
|
+
* navigations are ignored,
|
|
526
|
+
* - falls back to the `about:blank` + "Loading …" title heuristic only when CDP
|
|
527
|
+
* is unavailable (non-Chromium),
|
|
528
|
+
* - emits typed events (no secrets) so the caller can surface them in status.
|
|
529
|
+
*
|
|
530
|
+
* One guard per context (idempotent): installing twice returns the same guard,
|
|
531
|
+
* so no duplicate watchdogs or timers can exist.
|
|
532
|
+
*
|
|
533
|
+
* @param {object} context Playwright BrowserContext
|
|
534
|
+
* @param {object} [opts]
|
|
535
|
+
* @param {number} [opts.navigationTimeoutMs]
|
|
536
|
+
* @param {number} [opts.stallTimeoutMs]
|
|
537
|
+
* @param {number} [opts.hardStallTimeoutMs] fallback title-heuristic budget
|
|
538
|
+
* @param {number} [opts.pollIntervalMs] fallback polling period
|
|
539
|
+
* @param {boolean} [opts.useCdp=true]
|
|
540
|
+
* @param {function} [opts.onEvent] (event, detail) => void
|
|
541
|
+
* @returns {{stop:function, checkNow:function, options:object, stats:object}}
|
|
542
|
+
*/
|
|
543
|
+
const GUARD_KEY = Symbol.for('tw.nav.guard.v2');
|
|
544
|
+
|
|
545
|
+
function installNavigationGuard(context, opts = {}) {
|
|
546
|
+
if (!context || typeof context !== 'object') {
|
|
547
|
+
return { stop() {}, checkNow: async () => ({ stalled: 0, painted: 0 }), options: {}, stats: { mode: 'none' } };
|
|
548
|
+
}
|
|
549
|
+
// Idempotent: exactly one guard per context.
|
|
550
|
+
if (context[GUARD_KEY]) return context[GUARD_KEY];
|
|
551
|
+
|
|
552
|
+
const navigationTimeoutMs = Number.isFinite(opts.navigationTimeoutMs)
|
|
553
|
+
? opts.navigationTimeoutMs
|
|
554
|
+
: _intFromEnv('XKWDSTORE_NAV_TIMEOUT_MS', DEFAULT_NAVIGATION_TIMEOUT_MS);
|
|
555
|
+
const stallTimeoutMs = Number.isFinite(opts.stallTimeoutMs)
|
|
556
|
+
? opts.stallTimeoutMs
|
|
557
|
+
: _intFromEnv('XKWDSTORE_NAV_STALL_TIMEOUT_MS', DEFAULT_STALL_TIMEOUT_MS);
|
|
558
|
+
const hardStallTimeoutMs = Number.isFinite(opts.hardStallTimeoutMs)
|
|
559
|
+
? opts.hardStallTimeoutMs
|
|
560
|
+
: _intFromEnv('XKWDSTORE_NAV_HARD_STALL_TIMEOUT_MS', DEFAULT_HARD_STALL_TIMEOUT_MS);
|
|
561
|
+
const pollIntervalMs = Number.isFinite(opts.pollIntervalMs)
|
|
562
|
+
? Math.max(200, opts.pollIntervalMs)
|
|
563
|
+
: Math.max(1000, Math.min(5000, Math.floor(stallTimeoutMs / 4)));
|
|
564
|
+
const useCdp = opts.useCdp !== false;
|
|
565
|
+
const onEvent = typeof opts.onEvent === 'function' ? opts.onEvent : null;
|
|
566
|
+
const stats = { mode: 'cdp', painted: 0, stalled: 0, pagesWatched: 0, failuresPainted: 0 };
|
|
567
|
+
|
|
568
|
+
const emit = (event, detail) => {
|
|
569
|
+
if (!onEvent) return;
|
|
570
|
+
try { onEvent(event, detail); } catch { /* never break the browser on a log handler */ }
|
|
571
|
+
};
|
|
572
|
+
|
|
573
|
+
try { if (typeof context.setDefaultNavigationTimeout === 'function') context.setDefaultNavigationTimeout(navigationTimeoutMs); } catch { /* best effort */ }
|
|
574
|
+
try { if (typeof context.setDefaultTimeout === 'function') context.setDefaultTimeout(navigationTimeoutMs); } catch { /* best effort */ }
|
|
575
|
+
|
|
576
|
+
const pageStates = new WeakMap();
|
|
577
|
+
const timers = new Set();
|
|
578
|
+
const cdpSessions = new Set();
|
|
579
|
+
let stopped = false;
|
|
580
|
+
let guard = null;
|
|
581
|
+
let fallbackTimer = null;
|
|
582
|
+
let cdpAttached = 0;
|
|
583
|
+
let cdpAttempted = 0;
|
|
584
|
+
|
|
585
|
+
const trackTimer = (timer) => {
|
|
586
|
+
if (timer && typeof timer.unref === 'function') timer.unref();
|
|
587
|
+
if (timer) timers.add(timer);
|
|
588
|
+
return timer;
|
|
589
|
+
};
|
|
590
|
+
const clearTracked = (timer) => {
|
|
591
|
+
if (!timer) return;
|
|
592
|
+
try { clearTimeout(timer); } catch { /* ignore */ }
|
|
593
|
+
try { clearInterval(timer); } catch { /* ignore */ }
|
|
594
|
+
timers.delete(timer);
|
|
595
|
+
};
|
|
596
|
+
|
|
597
|
+
const newState = () => ({
|
|
598
|
+
startedAt: Date.now(),
|
|
599
|
+
pending: null,
|
|
600
|
+
stallTimer: null,
|
|
601
|
+
commitTimer: null,
|
|
602
|
+
painted: false,
|
|
603
|
+
painting: false,
|
|
604
|
+
mainFrameId: null,
|
|
605
|
+
cdp: null,
|
|
606
|
+
downloadAt: 0,
|
|
607
|
+
lastStallTarget: null,
|
|
608
|
+
unreachableUrl: null,
|
|
609
|
+
});
|
|
610
|
+
|
|
611
|
+
const paint = async (page, state, info) => {
|
|
612
|
+
if (stopped || state.painting) return false;
|
|
613
|
+
state.painting = true;
|
|
614
|
+
try {
|
|
615
|
+
const result = await paintNavigationFailure(page, info, { timeoutMs: 8000 });
|
|
616
|
+
if (result.painted) { stats.painted += 1; state.painted = true; }
|
|
617
|
+
return result.painted === true;
|
|
618
|
+
} catch {
|
|
619
|
+
return false;
|
|
620
|
+
} finally {
|
|
621
|
+
state.painting = false;
|
|
622
|
+
}
|
|
623
|
+
};
|
|
624
|
+
|
|
625
|
+
const paintStall = async (page, state, targetUrl, waitedMs) => {
|
|
626
|
+
stats.stalled += 1;
|
|
627
|
+
const target = safeOrigin(targetUrl) || null;
|
|
628
|
+
const ok = await paint(page, state, {
|
|
629
|
+
code: 'NAVIGATION_STALLED',
|
|
630
|
+
stage: 'navigation',
|
|
631
|
+
reason: 'origin_navigation_stalled',
|
|
632
|
+
message: `The navigation to ${target || 'the target host'} never completed and was stopped after ${Math.round(waitedMs / 1000)}s.`,
|
|
633
|
+
hint: 'The proxy tunnel or the origin stopped responding. Verify proxy reachability and per-host access, then retry.',
|
|
634
|
+
targetHost: target,
|
|
635
|
+
retryUrl: targetUrl,
|
|
636
|
+
accountLabel: opts.accountLabel || null,
|
|
637
|
+
});
|
|
638
|
+
emit('navigation_stalled', { code: 'NAVIGATION_STALLED', targetHost: target, waitedMs, painted: ok });
|
|
639
|
+
};
|
|
640
|
+
|
|
641
|
+
const scheduleStall = (page, state) => {
|
|
642
|
+
if (stopped || !state.pending) return;
|
|
643
|
+
clearTracked(state.stallTimer);
|
|
644
|
+
state.stallTimer = trackTimer(setTimeout(() => {
|
|
645
|
+
const p = state.pending;
|
|
646
|
+
if (stopped || !p || p.responded) return;
|
|
647
|
+
paintStall(page, state, p.url, Date.now() - p.startedAt).catch(() => { /* never throw */ });
|
|
648
|
+
}, stallTimeoutMs));
|
|
649
|
+
};
|
|
650
|
+
|
|
651
|
+
/**
|
|
652
|
+
* Late-attach safety net. A page created ALREADY navigating by the browser
|
|
653
|
+
* (new tab / middle-click / `Target.createTarget`, the same initiator class as
|
|
654
|
+
* the address bar) can start its Document request before our CDP session is
|
|
655
|
+
* enabled, so no `requestWillBeSent` is observed. Two reliable fallbacks:
|
|
656
|
+
* - no committed document (`page.url()` is empty) after the budget → stalled;
|
|
657
|
+
* - Chromium committed its own error page (`chrome-error://`) → actionable page.
|
|
658
|
+
* A page parked on `about:blank` (idle) is never touched.
|
|
659
|
+
*/
|
|
660
|
+
const armCommitWatchdog = (page, state) => {
|
|
661
|
+
if (stopped) return;
|
|
662
|
+
clearTracked(state.commitTimer);
|
|
663
|
+
const noDocumentBudget = Math.max(stallTimeoutMs, Math.min(hardStallTimeoutMs, stallTimeoutMs * 2));
|
|
664
|
+
state.commitTimer = trackTimer(setTimeout(async () => {
|
|
665
|
+
if (stopped || state.painted || state.painting) return;
|
|
666
|
+
let closed = false;
|
|
667
|
+
try { closed = typeof page.isClosed === 'function' && page.isClosed(); } catch { closed = false; }
|
|
668
|
+
if (closed) return;
|
|
669
|
+
let url = '';
|
|
670
|
+
try { url = page.url(); } catch { url = ''; }
|
|
671
|
+
if (url === '') {
|
|
672
|
+
let target = (state.pending && state.pending.url) || state.unreachableUrl || null;
|
|
673
|
+
// A late-attached pending navigation still has a history entry for the
|
|
674
|
+
// intended URL; use it so the diagnostic page can offer a real retry.
|
|
675
|
+
if (!target && state.cdp) {
|
|
676
|
+
try {
|
|
677
|
+
const h = await state.cdp.send('Page.getNavigationHistory');
|
|
678
|
+
const entry = h && Array.isArray(h.entries) ? h.entries[h.currentIndex] : null;
|
|
679
|
+
if (entry && entry.url) target = entry.url;
|
|
680
|
+
} catch { /* best effort */ }
|
|
681
|
+
}
|
|
682
|
+
const ok = await paint(page, state, {
|
|
683
|
+
code: 'NAVIGATION_STALLED',
|
|
684
|
+
stage: 'navigation',
|
|
685
|
+
reason: 'origin_navigation_stalled',
|
|
686
|
+
message: `A new tab started a navigation that never committed${target ? ` (${safeOrigin(target) || 'target'})` : ''} and was stopped after ${Math.round(noDocumentBudget / 1000)}s.`,
|
|
687
|
+
hint: 'The proxy tunnel or the origin stopped responding. Verify proxy reachability and per-host access, then retry.',
|
|
688
|
+
targetHost: safeOrigin(target) || null,
|
|
689
|
+
retryUrl: target,
|
|
690
|
+
accountLabel: opts.accountLabel || null,
|
|
691
|
+
});
|
|
692
|
+
stats.stalled += 1;
|
|
693
|
+
emit('navigation_stalled', { code: 'NAVIGATION_STALLED', targetHost: safeOrigin(target) || null, waitedMs: noDocumentBudget, painted: ok });
|
|
694
|
+
return;
|
|
695
|
+
}
|
|
696
|
+
if (url.startsWith('chrome-error://')) {
|
|
697
|
+
await paintChromeError(page, state, { url });
|
|
698
|
+
}
|
|
699
|
+
}, noDocumentBudget));
|
|
700
|
+
};
|
|
701
|
+
|
|
702
|
+
/** Paint the actionable page when Chromium itself shows an error page. */
|
|
703
|
+
const paintChromeError = async (page, state, committed = {}) => {
|
|
704
|
+
if (stopped || state.painted || state.painting) return false;
|
|
705
|
+
// Give an application-driven navigation (navigateBounded) a moment to paint
|
|
706
|
+
// its more specific failure first; the paint lock coalesces concurrent calls.
|
|
707
|
+
await new Promise((r) => setTimeout(r, 250));
|
|
708
|
+
if (stopped || state.painted) return false;
|
|
709
|
+
let current = '';
|
|
710
|
+
try { current = page.url(); } catch { current = ''; }
|
|
711
|
+
const errorUrl = committed.url || current;
|
|
712
|
+
// If the page moved on to a real document, nothing to do.
|
|
713
|
+
if (current && current !== '' && current !== 'about:blank' && !current.startsWith('chrome-error://')) return false;
|
|
714
|
+
if (!String(errorUrl).startsWith('chrome-error://')) return false;
|
|
715
|
+
const target = committed.unreachableUrl || state.unreachableUrl || (state.pending && state.pending.url) || null;
|
|
716
|
+
const ok = await paint(page, state, {
|
|
717
|
+
code: 'NAVIGATION_ERROR_PAGE',
|
|
718
|
+
stage: 'navigation',
|
|
719
|
+
reason: 'origin_navigation_failed',
|
|
720
|
+
message: `Chromium could not load the page${target ? ` (${safeOrigin(target) || 'target'})` : ''}.`,
|
|
721
|
+
hint: 'Check the proxy and per-host connectivity with the connectivity diagnostic, then retry.',
|
|
722
|
+
targetHost: safeOrigin(target) || null,
|
|
723
|
+
retryUrl: target,
|
|
724
|
+
accountLabel: opts.accountLabel || null,
|
|
725
|
+
});
|
|
726
|
+
if (ok) stats.failuresPainted += 1;
|
|
727
|
+
emit('navigation_failed', { code: 'NAVIGATION_ERROR_PAGE', painted: ok });
|
|
728
|
+
return ok;
|
|
729
|
+
};
|
|
730
|
+
|
|
731
|
+
const onDocumentStart = (page, state, params) => {
|
|
732
|
+
if (!params || params.type !== 'Document') return;
|
|
733
|
+
if (state.mainFrameId && params.frameId && params.frameId !== state.mainFrameId) return;
|
|
734
|
+
const existing = state.pending;
|
|
735
|
+
if (existing && existing.requestId === params.requestId) {
|
|
736
|
+
// Same request: a redirect or a retry of the same document. Progress.
|
|
737
|
+
if (params.redirectResponse) {
|
|
738
|
+
existing.startedAt = Date.now();
|
|
739
|
+
existing.url = (params.request && params.request.url) || existing.url;
|
|
740
|
+
scheduleStall(page, state);
|
|
741
|
+
}
|
|
742
|
+
return;
|
|
743
|
+
}
|
|
744
|
+
state.pending = {
|
|
745
|
+
requestId: params.requestId,
|
|
746
|
+
url: (params.request && params.request.url) || page.url(),
|
|
747
|
+
startedAt: Date.now(),
|
|
748
|
+
responded: false,
|
|
749
|
+
};
|
|
750
|
+
state.painted = false;
|
|
751
|
+
scheduleStall(page, state);
|
|
752
|
+
};
|
|
753
|
+
|
|
754
|
+
const onDocumentResponse = (state, params) => {
|
|
755
|
+
if (!state.pending || params.requestId !== state.pending.requestId) return;
|
|
756
|
+
state.pending.responded = true;
|
|
757
|
+
clearTracked(state.stallTimer);
|
|
758
|
+
state.stallTimer = null;
|
|
759
|
+
};
|
|
760
|
+
|
|
761
|
+
const onDocumentFinished = (page, state, params) => {
|
|
762
|
+
if (!state.pending || params.requestId !== state.pending.requestId) return;
|
|
763
|
+
clearTracked(state.stallTimer);
|
|
764
|
+
state.stallTimer = null;
|
|
765
|
+
state.pending = null;
|
|
766
|
+
};
|
|
767
|
+
|
|
768
|
+
const onDocumentFailed = async (page, state, params) => {
|
|
769
|
+
if (!state.pending || params.requestId !== state.pending.requestId) return;
|
|
770
|
+
clearTracked(state.stallTimer);
|
|
771
|
+
state.stallTimer = null;
|
|
772
|
+
const errorText = String(params.errorText || '');
|
|
773
|
+
const cancelled = params.canceled === true || /ERR_ABORTED/i.test(errorText);
|
|
774
|
+
state.pending = null;
|
|
775
|
+
// A cancelled document (download, user navigation, popup) is not a failure.
|
|
776
|
+
if (cancelled || state.downloadAt > 0) return;
|
|
777
|
+
// Genuine browser-side failure: Chrome would show its own error page. Paint
|
|
778
|
+
// the actionable page only when the tab has no usable document, so a loaded
|
|
779
|
+
// page is never replaced.
|
|
780
|
+
let url = '';
|
|
781
|
+
try { url = page.url(); } catch { url = ''; }
|
|
782
|
+
if (url && url !== 'about:blank' && !url.startsWith('chrome-error://')) return;
|
|
783
|
+
// Let the main-frame commit populate `unreachableUrl` (the intended URL) so
|
|
784
|
+
// the diagnostic page can offer a real retry.
|
|
785
|
+
await new Promise((r) => setTimeout(r, 150));
|
|
786
|
+
const attempted = params.documentURL || state.unreachableUrl || url || null;
|
|
787
|
+
const failure = classifyNavigationFailure(new Error(errorText), {
|
|
788
|
+
url: attempted,
|
|
789
|
+
proxyActive: opts.proxyActive === true,
|
|
790
|
+
dnsPinned: opts.dnsPinned === true,
|
|
791
|
+
});
|
|
792
|
+
const ok = await paint(page, state, { ...failure, retryUrl: attempted, accountLabel: opts.accountLabel || null });
|
|
793
|
+
if (ok) stats.failuresPainted += 1;
|
|
794
|
+
emit('navigation_failed', { code: failure.code, stage: failure.stage, painted: ok });
|
|
795
|
+
};
|
|
796
|
+
|
|
797
|
+
const resetAfterCommit = (state, url) => {
|
|
798
|
+
state.painted = false;
|
|
799
|
+
state.pending = null;
|
|
800
|
+
state.lastStallTarget = null;
|
|
801
|
+
clearTracked(state.stallTimer);
|
|
802
|
+
state.stallTimer = null;
|
|
803
|
+
if (url && url !== 'about:blank' && !url.startsWith('chrome-error://')) {
|
|
804
|
+
state.startedAt = Date.now();
|
|
805
|
+
state.unreachableUrl = null;
|
|
806
|
+
}
|
|
807
|
+
};
|
|
808
|
+
|
|
809
|
+
const attachCdp = async (page) => {
|
|
810
|
+
const state = pageStates.get(page);
|
|
811
|
+
if (!state || state.cdp || stopped || !useCdp) return;
|
|
812
|
+
if (typeof context.newCDPSession !== 'function') return;
|
|
813
|
+
cdpAttempted += 1;
|
|
814
|
+
let session;
|
|
815
|
+
try {
|
|
816
|
+
session = await context.newCDPSession(page);
|
|
817
|
+
await session.send('Network.enable');
|
|
818
|
+
await session.send('Page.enable');
|
|
819
|
+
} catch {
|
|
820
|
+
try { if (session) await session.detach(); } catch { /* ignore */ }
|
|
821
|
+
return;
|
|
822
|
+
}
|
|
823
|
+
if (stopped) { try { await session.detach(); } catch { /* ignore */ } return; }
|
|
824
|
+
state.cdp = session;
|
|
825
|
+
cdpAttached += 1;
|
|
826
|
+
cdpSessions.add(session);
|
|
827
|
+
session.on('Network.requestWillBeSent', (p) => onDocumentStart(page, state, p));
|
|
828
|
+
session.on('Network.responseReceived', (p) => onDocumentResponse(state, p));
|
|
829
|
+
session.on('Network.loadingFinished', (p) => onDocumentFinished(page, state, p));
|
|
830
|
+
session.on('Network.loadingFailed', (p) => { onDocumentFailed(page, state, p).catch(() => { /* ignore */ }); });
|
|
831
|
+
session.on('Page.frameNavigated', (p) => {
|
|
832
|
+
const frame = p && p.frame;
|
|
833
|
+
if (!frame) return;
|
|
834
|
+
if (!frame.parentId) {
|
|
835
|
+
state.mainFrameId = frame.id || state.mainFrameId;
|
|
836
|
+
if (frame.unreachableUrl) state.unreachableUrl = frame.unreachableUrl;
|
|
837
|
+
resetAfterCommit(state, frame.url);
|
|
838
|
+
// Chromium committed its own error page: replace it with the actionable
|
|
839
|
+
// page (after a short grace period so navigateBounded can paint a more
|
|
840
|
+
// specific code first).
|
|
841
|
+
if (typeof frame.url === 'string' && frame.url.startsWith('chrome-error://')) {
|
|
842
|
+
paintChromeError(page, state, { url: frame.url, unreachableUrl: frame.unreachableUrl }).catch(() => { /* ignore */ });
|
|
843
|
+
} else {
|
|
844
|
+
armCommitWatchdog(page, state);
|
|
845
|
+
}
|
|
846
|
+
}
|
|
847
|
+
});
|
|
848
|
+
emit('page_watched', { mode: 'cdp' });
|
|
849
|
+
};
|
|
850
|
+
|
|
851
|
+
const watch = (page) => {
|
|
852
|
+
if (!page || stopped || pageStates.has(page)) return;
|
|
853
|
+
const state = newState();
|
|
854
|
+
pageStates.set(page, state);
|
|
855
|
+
stats.pagesWatched += 1;
|
|
856
|
+
try {
|
|
857
|
+
// Playwright's own events are a reliable secondary signal (works even if
|
|
858
|
+
// CDP attach is unavailable) and reset the guard after a successful commit.
|
|
859
|
+
page.on('framenavigated', (frame) => {
|
|
860
|
+
try {
|
|
861
|
+
if (frame && typeof frame.parentFrame === 'function' && frame.parentFrame()) return;
|
|
862
|
+
resetAfterCommit(state, frame && frame.url ? frame.url() : '');
|
|
863
|
+
} catch { /* ignore */ }
|
|
864
|
+
});
|
|
865
|
+
// A download started from this tab must never be mistaken for a stall.
|
|
866
|
+
page.on('download', () => { state.downloadAt = Date.now(); });
|
|
867
|
+
page.on('close', () => {
|
|
868
|
+
clearTracked(state.stallTimer);
|
|
869
|
+
clearTracked(state.commitTimer);
|
|
870
|
+
const s = state.cdp;
|
|
871
|
+
state.cdp = null;
|
|
872
|
+
if (s) { cdpSessions.delete(s); try { s.detach().catch(() => {}); } catch { /* ignore */ } }
|
|
873
|
+
});
|
|
874
|
+
} catch { /* best effort */ }
|
|
875
|
+
attachCdp(page).then(() => {
|
|
876
|
+
// If no page could be CDP-attached, switch to the title fallback once.
|
|
877
|
+
if (!stopped && useCdp && (typeof context.newCDPSession !== 'function' || (cdpAttempted > 0 && cdpAttached === 0))) ensureFallback();
|
|
878
|
+
// Late-attach safety net (covers browser-initiated navigations that began
|
|
879
|
+
// before the CDP session was enabled).
|
|
880
|
+
armCommitWatchdog(page, state);
|
|
881
|
+
}).catch(() => { /* ignore */ });
|
|
882
|
+
};
|
|
883
|
+
|
|
884
|
+
const ensureFallback = () => {
|
|
885
|
+
if (fallbackTimer || stopped) return;
|
|
886
|
+
stats.mode = 'fallback';
|
|
887
|
+
fallbackTimer = trackTimer(setInterval(() => {
|
|
888
|
+
checkNowFallback().catch(() => { /* never throw from the watchdog */ });
|
|
889
|
+
}, pollIntervalMs));
|
|
890
|
+
emit('guard_mode', { mode: 'fallback' });
|
|
891
|
+
};
|
|
892
|
+
|
|
893
|
+
/** Title-heuristic fallback (non-Chromium only). */
|
|
894
|
+
const checkNowFallback = async () => {
|
|
895
|
+
if (stopped) return { stalled: 0, painted: 0 };
|
|
896
|
+
let pageList = [];
|
|
897
|
+
try { pageList = context.pages(); } catch { return { stalled: 0, painted: 0 }; }
|
|
898
|
+
let stalled = 0;
|
|
899
|
+
let painted = 0;
|
|
900
|
+
for (const page of pageList) {
|
|
901
|
+
const state = pageStates.get(page);
|
|
902
|
+
if (!state || state.painted || state.cdp || state.painting) continue;
|
|
903
|
+
let closed = false;
|
|
904
|
+
try { closed = typeof page.isClosed === 'function' && page.isClosed(); } catch { closed = false; }
|
|
905
|
+
if (closed) continue;
|
|
906
|
+
let url = '';
|
|
907
|
+
let title = '';
|
|
908
|
+
try { url = page.url(); } catch { url = ''; }
|
|
909
|
+
try { title = await page.title(); } catch { title = ''; }
|
|
910
|
+
const verdict = isStalledNavigation({ url, title });
|
|
911
|
+
if (!verdict.stalled) {
|
|
912
|
+
state.lastStallTarget = null;
|
|
913
|
+
state.startedAt = Date.now();
|
|
914
|
+
continue;
|
|
915
|
+
}
|
|
916
|
+
if (state.lastStallTarget !== verdict.target) {
|
|
917
|
+
state.lastStallTarget = verdict.target;
|
|
918
|
+
state.startedAt = Date.now();
|
|
919
|
+
}
|
|
920
|
+
const waited = Date.now() - state.startedAt;
|
|
921
|
+
const budget = verdict.confidence === 'high' ? stallTimeoutMs : hardStallTimeoutMs;
|
|
922
|
+
if (waited < budget) continue;
|
|
923
|
+
stalled += 1;
|
|
924
|
+
const ok = await paint(page, state, {
|
|
925
|
+
code: 'NAVIGATION_STALLED',
|
|
926
|
+
stage: 'navigation',
|
|
927
|
+
reason: 'origin_navigation_stalled',
|
|
928
|
+
message: `The navigation to ${verdict.target || 'the target host'} never completed and was stopped after ${Math.round(waited / 1000)}s.`,
|
|
929
|
+
hint: 'The proxy tunnel or the origin stopped responding. Verify proxy reachability and per-host access, then retry.',
|
|
930
|
+
targetHost: verdict.target,
|
|
931
|
+
accountLabel: opts.accountLabel || null,
|
|
932
|
+
});
|
|
933
|
+
if (ok) painted += 1;
|
|
934
|
+
stats.stalled += 1;
|
|
935
|
+
emit('navigation_stalled', { code: 'NAVIGATION_STALLED', targetHost: verdict.target, waitedMs: waited, painted: ok });
|
|
936
|
+
}
|
|
937
|
+
return { stalled, painted };
|
|
938
|
+
};
|
|
939
|
+
|
|
940
|
+
/**
|
|
941
|
+
* Evaluate the CURRENT state of every watched page. On the CDP path this is a
|
|
942
|
+
* no-op for healthy pages (the per-request timer does the work); it exists for
|
|
943
|
+
* tests and for a status check that wants a fresh verdict.
|
|
944
|
+
*/
|
|
945
|
+
const checkNow = async () => {
|
|
946
|
+
if (stopped) return { stalled: 0, painted: 0 };
|
|
947
|
+
let pageList = [];
|
|
948
|
+
try { pageList = context.pages(); } catch { return { stalled: 0, painted: 0 }; }
|
|
949
|
+
let stalled = 0;
|
|
950
|
+
let painted = 0;
|
|
951
|
+
for (const page of pageList) {
|
|
952
|
+
const state = pageStates.get(page);
|
|
953
|
+
if (!state || state.painted || state.painting) continue;
|
|
954
|
+
if (state.cdp) {
|
|
955
|
+
const p = state.pending;
|
|
956
|
+
if (!p || p.responded) continue;
|
|
957
|
+
const waited = Date.now() - p.startedAt;
|
|
958
|
+
if (waited < stallTimeoutMs) continue;
|
|
959
|
+
stalled += 1;
|
|
960
|
+
if (await paintStall(page, state, p.url, waited)) painted += 1;
|
|
961
|
+
}
|
|
962
|
+
}
|
|
963
|
+
if (stats.mode === 'fallback' || cdpAttached === 0) {
|
|
964
|
+
const r = await checkNowFallback();
|
|
965
|
+
return { stalled: stalled + r.stalled, painted: painted + r.painted };
|
|
966
|
+
}
|
|
967
|
+
return { stalled, painted };
|
|
968
|
+
};
|
|
969
|
+
|
|
970
|
+
try {
|
|
971
|
+
for (const page of context.pages()) watch(page);
|
|
972
|
+
if (typeof context.on === 'function') context.on('page', watch);
|
|
973
|
+
} catch { /* best effort */ }
|
|
974
|
+
|
|
975
|
+
const stop = () => {
|
|
976
|
+
stopped = true;
|
|
977
|
+
if (guard && context[GUARD_KEY] === guard) { try { delete context[GUARD_KEY]; } catch { /* ignore */ } }
|
|
978
|
+
clearTracked(fallbackTimer);
|
|
979
|
+
fallbackTimer = null;
|
|
980
|
+
for (const timer of Array.from(timers)) clearTracked(timer);
|
|
981
|
+
for (const session of Array.from(cdpSessions)) {
|
|
982
|
+
try { session.detach().catch(() => {}); } catch { /* ignore */ }
|
|
983
|
+
}
|
|
984
|
+
cdpSessions.clear();
|
|
985
|
+
for (const page of (() => { try { return context.pages(); } catch { return []; } })()) {
|
|
986
|
+
const state = pageStates.get(page);
|
|
987
|
+
if (state) { state.pending = null; clearTracked(state.stallTimer); clearTracked(state.commitTimer); }
|
|
988
|
+
}
|
|
989
|
+
try { if (typeof context.off === 'function') context.off('page', watch); } catch { /* ignore */ }
|
|
990
|
+
};
|
|
991
|
+
|
|
992
|
+
try {
|
|
993
|
+
if (typeof context.once === 'function') context.once('close', stop);
|
|
994
|
+
} catch { /* best effort */ }
|
|
995
|
+
|
|
996
|
+
guard = {
|
|
997
|
+
stop,
|
|
998
|
+
checkNow,
|
|
999
|
+
options: { navigationTimeoutMs, stallTimeoutMs, hardStallTimeoutMs, pollIntervalMs, cdp: useCdp },
|
|
1000
|
+
stats,
|
|
1001
|
+
};
|
|
1002
|
+
try { context[GUARD_KEY] = guard; } catch { /* best effort */ }
|
|
1003
|
+
return guard;
|
|
1004
|
+
}
|
|
1005
|
+
// ── Network probing (operator diagnostics) ───────────────────────────────────
|
|
1006
|
+
|
|
1007
|
+
function _withTimeout(promise, ms, code) {
|
|
1008
|
+
let timer;
|
|
1009
|
+
const timeout = new Promise((_, reject) => {
|
|
1010
|
+
timer = setTimeout(() => reject(Object.assign(new Error('probe timed out'), { code: code || 'PROBE_TIMEOUT' })), ms);
|
|
1011
|
+
if (typeof timer.unref === 'function') timer.unref();
|
|
1012
|
+
});
|
|
1013
|
+
return Promise.race([promise, timeout]).finally(() => { try { clearTimeout(timer); } catch { /* ignore */ } });
|
|
1014
|
+
}
|
|
1015
|
+
|
|
1016
|
+
function _statusLine(text) {
|
|
1017
|
+
const line = String(text).split('\r\n')[0] || '';
|
|
1018
|
+
const m = /^HTTP\/\d(?:\.\d)?\s+(\d{3})/.exec(line);
|
|
1019
|
+
return m ? parseInt(m[1], 10) : 0;
|
|
1020
|
+
}
|
|
1021
|
+
|
|
1022
|
+
function _headerValue(text, name) {
|
|
1023
|
+
const re = new RegExp('^' + name + ':\\s*(.+)$', 'im');
|
|
1024
|
+
const m = re.exec(String(text));
|
|
1025
|
+
return m ? m[1].trim() : null;
|
|
1026
|
+
}
|
|
1027
|
+
|
|
1028
|
+
function _probeCodeForConnectStatus(status) {
|
|
1029
|
+
if (status === 407) return 'PROXY_AUTH_FAILED';
|
|
1030
|
+
if (status === 403) return 'PROXY_TARGET_DENIED';
|
|
1031
|
+
if (status === 502 || status === 503 || status === 504) return 'PROXY_TARGET_UNREACHABLE';
|
|
1032
|
+
if (status >= 200 && status < 300) return null;
|
|
1033
|
+
if (!status || status < 100) return 'PROXY_TUNNEL_INVALID';
|
|
1034
|
+
return 'PROXY_CONNECT_REJECTED';
|
|
1035
|
+
}
|
|
1036
|
+
|
|
1037
|
+
/** Read exactly `n` bytes from a socket, bounded by `timeoutMs`. */
|
|
1038
|
+
function _readExactly(socket, n, timeoutMs, code) {
|
|
1039
|
+
return new Promise((resolve, reject) => {
|
|
1040
|
+
const chunks = [];
|
|
1041
|
+
let got = 0;
|
|
1042
|
+
let settled = false;
|
|
1043
|
+
const done = (fn, arg) => { if (settled) return; settled = true; cleanup(); fn(arg); };
|
|
1044
|
+
const onData = (chunk) => {
|
|
1045
|
+
chunks.push(chunk);
|
|
1046
|
+
got += chunk.length;
|
|
1047
|
+
if (got >= n) done(resolve, Buffer.concat(chunks).subarray(0, n));
|
|
1048
|
+
};
|
|
1049
|
+
const onEnd = () => done(reject, Object.assign(new Error('tunnel closed before the handshake completed'), { code: code || 'PROXY_TUNNEL_CLOSED', silentDrop: got === 0 }));
|
|
1050
|
+
const onError = (err) => done(reject, err);
|
|
1051
|
+
const onTimeout = () => done(reject, Object.assign(new Error('handshake timed out'), { code: code || 'PROXY_CONNECT_TIMEOUT' }));
|
|
1052
|
+
const timer = setTimeout(onTimeout, timeoutMs);
|
|
1053
|
+
if (typeof timer.unref === 'function') timer.unref();
|
|
1054
|
+
function cleanup() {
|
|
1055
|
+
clearTimeout(timer);
|
|
1056
|
+
socket.removeListener('data', onData);
|
|
1057
|
+
socket.removeListener('end', onEnd);
|
|
1058
|
+
socket.removeListener('close', onEnd);
|
|
1059
|
+
socket.removeListener('error', onError);
|
|
1060
|
+
}
|
|
1061
|
+
socket.on('data', onData);
|
|
1062
|
+
socket.once('end', onEnd);
|
|
1063
|
+
socket.once('close', onEnd);
|
|
1064
|
+
socket.once('error', onError);
|
|
1065
|
+
});
|
|
1066
|
+
}
|
|
1067
|
+
|
|
1068
|
+
function _tcpConnect({ host, port, timeoutMs, family }) {
|
|
1069
|
+
return new Promise((resolve, reject) => {
|
|
1070
|
+
const socket = net.connect(family ? { host, port, family } : { host, port });
|
|
1071
|
+
const timer = setTimeout(() => {
|
|
1072
|
+
socket.destroy();
|
|
1073
|
+
reject(Object.assign(new Error('tcp connect timed out'), { code: 'PROBE_CONNECT_TIMEOUT' }));
|
|
1074
|
+
}, timeoutMs);
|
|
1075
|
+
if (typeof timer.unref === 'function') timer.unref();
|
|
1076
|
+
socket.once('connect', () => { clearTimeout(timer); socket.setTimeout(0); resolve(socket); });
|
|
1077
|
+
socket.once('error', (err) => { clearTimeout(timer); reject(err); });
|
|
1078
|
+
});
|
|
1079
|
+
}
|
|
1080
|
+
|
|
1081
|
+
/** HTTP CONNECT tunnel (http / https proxies). Returns the raw tunnel socket. */
|
|
1082
|
+
async function _openHttpConnectTunnel({ proxy, targetHost, port, timeoutMs }) {
|
|
1083
|
+
const socket = await _tcpConnect({ host: proxy.host, port: proxy.port, timeoutMs });
|
|
1084
|
+
try {
|
|
1085
|
+
const lines = [
|
|
1086
|
+
`CONNECT ${targetHost}:${port} HTTP/1.1`,
|
|
1087
|
+
`Host: ${targetHost}:${port}`,
|
|
1088
|
+
];
|
|
1089
|
+
if (proxy.username) {
|
|
1090
|
+
lines.push('Proxy-Authorization: Basic ' + Buffer.from(`${proxy.username}:${proxy.password || ''}`).toString('base64'));
|
|
1091
|
+
}
|
|
1092
|
+
socket.write(lines.join('\r\n') + '\r\n\r\n');
|
|
1093
|
+
const head = await new Promise((resolve, reject) => {
|
|
1094
|
+
let buf = '';
|
|
1095
|
+
let timer = null;
|
|
1096
|
+
const onData = (chunk) => {
|
|
1097
|
+
buf += chunk.toString('latin1');
|
|
1098
|
+
if (buf.includes('\r\n\r\n')) {
|
|
1099
|
+
if (timer) clearTimeout(timer);
|
|
1100
|
+
socket.removeListener('data', onData);
|
|
1101
|
+
resolve(buf);
|
|
1102
|
+
}
|
|
1103
|
+
};
|
|
1104
|
+
const onEnd = () => reject(Object.assign(new Error('proxy closed the connection without answering CONNECT'), { code: 'PROXY_TUNNEL_CLOSED', silentDrop: buf.length === 0 }));
|
|
1105
|
+
timer = setTimeout(() => reject(Object.assign(new Error('proxy CONNECT timed out'), { code: 'PROXY_CONNECT_TIMEOUT' })), timeoutMs);
|
|
1106
|
+
if (typeof timer.unref === 'function') timer.unref();
|
|
1107
|
+
socket.on('data', onData);
|
|
1108
|
+
socket.once('end', onEnd);
|
|
1109
|
+
socket.once('close', onEnd);
|
|
1110
|
+
socket.once('error', (err) => { if (timer) clearTimeout(timer); reject(err); });
|
|
1111
|
+
socket.once('timeout', () => { if (timer) clearTimeout(timer); reject(Object.assign(new Error('proxy CONNECT timed out'), { code: 'PROXY_CONNECT_TIMEOUT' })); });
|
|
1112
|
+
});
|
|
1113
|
+
const status = _statusLine(head);
|
|
1114
|
+
const code = _probeCodeForConnectStatus(status);
|
|
1115
|
+
if (code) {
|
|
1116
|
+
const err = Object.assign(new Error(`proxy CONNECT returned ${status}`), { code, status });
|
|
1117
|
+
throw err;
|
|
1118
|
+
}
|
|
1119
|
+
return { socket, mode: 'http-connect', connectStatus: status };
|
|
1120
|
+
} catch (err) {
|
|
1121
|
+
try { socket.destroy(); } catch { /* ignore */ }
|
|
1122
|
+
throw err;
|
|
1123
|
+
}
|
|
1124
|
+
}
|
|
1125
|
+
|
|
1126
|
+
/** SOCKS5 / SOCKS5h tunnel with optional RFC 1929 username/password auth. */
|
|
1127
|
+
async function _openSocks5Tunnel({ proxy, targetHost, port, timeoutMs }) {
|
|
1128
|
+
const socket = await _tcpConnect({ host: proxy.host, port: proxy.port, timeoutMs });
|
|
1129
|
+
try {
|
|
1130
|
+
const wantsAuth = !!proxy.username;
|
|
1131
|
+
socket.write(Buffer.from(wantsAuth ? [0x05, 0x02, 0x00, 0x02] : [0x05, 0x01, 0x00]));
|
|
1132
|
+
const greeting = await _readExactly(socket, 2, timeoutMs, 'PROXY_CONNECT_TIMEOUT');
|
|
1133
|
+
if (greeting[0] !== 0x05) throw Object.assign(new Error('proxy is not SOCKS5'), { code: 'PROXY_PROTOCOL_MISMATCH' });
|
|
1134
|
+
const method = greeting[1];
|
|
1135
|
+
if (method === 0x02) {
|
|
1136
|
+
if (!wantsAuth) throw Object.assign(new Error('proxy requires authentication'), { code: 'PROXY_AUTH_FAILED' });
|
|
1137
|
+
const u = Buffer.from(String(proxy.username || ''));
|
|
1138
|
+
const p = Buffer.from(String(proxy.password || ''));
|
|
1139
|
+
const authReq = Buffer.concat([Buffer.from([0x01, u.length]), u, Buffer.from([p.length]), p]);
|
|
1140
|
+
socket.write(authReq);
|
|
1141
|
+
const authRes = await _readExactly(socket, 2, timeoutMs, 'PROXY_AUTH_TIMEOUT');
|
|
1142
|
+
if (authRes[1] !== 0x00) throw Object.assign(new Error('proxy rejected the credentials'), { code: 'PROXY_AUTH_FAILED' });
|
|
1143
|
+
} else if (method === 0xff) {
|
|
1144
|
+
throw Object.assign(new Error('proxy accepted none of the offered auth methods'), { code: 'PROXY_AUTH_FAILED' });
|
|
1145
|
+
} else if (method !== 0x00) {
|
|
1146
|
+
throw Object.assign(new Error('proxy selected an unsupported auth method'), { code: 'PROXY_AUTH_UNSUPPORTED' });
|
|
1147
|
+
}
|
|
1148
|
+
const hostBuf = Buffer.from(targetHost);
|
|
1149
|
+
const req = Buffer.concat([
|
|
1150
|
+
Buffer.from([0x05, 0x01, 0x00, 0x03, hostBuf.length]), hostBuf,
|
|
1151
|
+
Buffer.from([(port >> 8) & 0xff, port & 0xff]),
|
|
1152
|
+
]);
|
|
1153
|
+
socket.write(req);
|
|
1154
|
+
const replyHead = await _readExactly(socket, 4, timeoutMs, 'PROXY_CONNECT_TIMEOUT');
|
|
1155
|
+
if (replyHead[1] !== 0x00) {
|
|
1156
|
+
const map = {
|
|
1157
|
+
0x02: 'PROXY_TARGET_DENIED', 0x03: 'PROXY_TARGET_DENIED', 0x04: 'PROXY_TARGET_UNREACHABLE',
|
|
1158
|
+
0x05: 'PROXY_TARGET_UNREACHABLE', 0x06: 'PROXY_CONNECT_TIMEOUT', 0x07: 'PROXY_CONNECT_REJECTED', 0x08: 'PROXY_CONNECT_REJECTED',
|
|
1159
|
+
};
|
|
1160
|
+
throw Object.assign(new Error('SOCKS5 connect failed with reply ' + replyHead[1]), { code: map[replyHead[1]] || 'PROXY_CONNECT_REJECTED', status: 0 });
|
|
1161
|
+
}
|
|
1162
|
+
// Consume the bound address before TLS starts on the same socket.
|
|
1163
|
+
const atyp = replyHead[3];
|
|
1164
|
+
const addrLen = atyp === 0x01 ? 4 : atyp === 0x04 ? 16 : atyp === 0x03 ? (await _readExactly(socket, 1, timeoutMs))[0] : 0;
|
|
1165
|
+
if (addrLen) await _readExactly(socket, addrLen + 2, timeoutMs);
|
|
1166
|
+
return { socket, mode: 'socks5' };
|
|
1167
|
+
} catch (err) {
|
|
1168
|
+
try { socket.destroy(); } catch { /* ignore */ }
|
|
1169
|
+
throw err;
|
|
1170
|
+
}
|
|
1171
|
+
}
|
|
1172
|
+
|
|
1173
|
+
function _isSocksProxy(proxy) {
|
|
1174
|
+
return !!(proxy && /^socks/i.test(String(proxy.scheme || '').replace(':', '')));
|
|
1175
|
+
}
|
|
1176
|
+
|
|
1177
|
+
/**
|
|
1178
|
+
* Probe ONE https endpoint. With a proxy, the probe tunnels through the proxy
|
|
1179
|
+
* exactly like Chromium does (HTTP CONNECT or SOCKS5, then TLS with SNI, then
|
|
1180
|
+
* GET); it never falls back to a direct connection when a proxy is configured.
|
|
1181
|
+
*
|
|
1182
|
+
* @param {object} o
|
|
1183
|
+
* @param {string} o.url https URL (no credentials)
|
|
1184
|
+
* @param {object|string|null} [o.proxy]
|
|
1185
|
+
* @param {number} [o.timeoutMs]
|
|
1186
|
+
* @param {number} [o.family] force an IP family for the direct path (4 or 6)
|
|
1187
|
+
* @returns {Promise<object>} sanitized per-host result
|
|
1188
|
+
*/
|
|
1189
|
+
async function probeEndpoint(o = {}) {
|
|
1190
|
+
const url = String(o.url || '');
|
|
1191
|
+
const timeoutMs = Number.isFinite(o.timeoutMs) ? o.timeoutMs : DEFAULT_PROBE_TIMEOUT_MS;
|
|
1192
|
+
const started = Date.now();
|
|
1193
|
+
const result = {
|
|
1194
|
+
url,
|
|
1195
|
+
host: null,
|
|
1196
|
+
ok: false,
|
|
1197
|
+
dnsMs: null,
|
|
1198
|
+
connectMs: null,
|
|
1199
|
+
tlsMs: null,
|
|
1200
|
+
status: null,
|
|
1201
|
+
redirectTo: null,
|
|
1202
|
+
ms: 0,
|
|
1203
|
+
code: null,
|
|
1204
|
+
error: null,
|
|
1205
|
+
tunnel: null,
|
|
1206
|
+
silentDrop: false,
|
|
1207
|
+
receivedBytes: null,
|
|
1208
|
+
};
|
|
1209
|
+
if (!isProbeableUrl(url)) {
|
|
1210
|
+
return { ...result, code: 'PROBE_TARGET_INVALID', error: 'probe target must be a public https URL', ms: Date.now() - started };
|
|
1211
|
+
}
|
|
1212
|
+
const target = new URL(url);
|
|
1213
|
+
result.host = target.hostname;
|
|
1214
|
+
const port = target.port ? parseInt(target.port, 10) : 443;
|
|
1215
|
+
const proxy = o.proxy ? parseProxyTarget(o.proxy) : null;
|
|
1216
|
+
const proxyConfigured = !!o.proxy;
|
|
1217
|
+
|
|
1218
|
+
const finish = (patch) => ({ ...result, ...patch, ms: Date.now() - started });
|
|
1219
|
+
|
|
1220
|
+
return _withTimeout((async () => {
|
|
1221
|
+
let socket;
|
|
1222
|
+
let tlsSocket;
|
|
1223
|
+
try {
|
|
1224
|
+
let connectHost = target.hostname;
|
|
1225
|
+
const connectPort = port;
|
|
1226
|
+
|
|
1227
|
+
if (proxy) {
|
|
1228
|
+
const t0 = Date.now();
|
|
1229
|
+
const tunnel = _isSocksProxy(proxy)
|
|
1230
|
+
? await _openSocks5Tunnel({ proxy, targetHost: target.hostname, port, timeoutMs })
|
|
1231
|
+
: await _openHttpConnectTunnel({ proxy, targetHost: target.hostname, port, timeoutMs });
|
|
1232
|
+
socket = tunnel.socket;
|
|
1233
|
+
result.connectMs = Date.now() - t0;
|
|
1234
|
+
result.tunnel = tunnel.mode;
|
|
1235
|
+
} else if (proxyConfigured) {
|
|
1236
|
+
// A proxy was requested but could not be parsed: never probe directly.
|
|
1237
|
+
return finish({ code: 'PROXY_FORMAT_INVALID', error: 'configured proxy could not be parsed' });
|
|
1238
|
+
} else {
|
|
1239
|
+
const t0 = Date.now();
|
|
1240
|
+
const addrs = await _withTimeout(dns.promises.lookup(target.hostname, { all: false, family: o.family || 0 }), Math.min(timeoutMs, 5000), 'PROBE_DNS_TIMEOUT');
|
|
1241
|
+
result.dnsMs = Date.now() - t0;
|
|
1242
|
+
result.family = addrs.family || null;
|
|
1243
|
+
connectHost = addrs.address;
|
|
1244
|
+
}
|
|
1245
|
+
|
|
1246
|
+
const tConnect = Date.now();
|
|
1247
|
+
if (!socket) {
|
|
1248
|
+
socket = await _tcpConnect({ host: connectHost, port: connectPort, timeoutMs });
|
|
1249
|
+
result.connectMs = Date.now() - tConnect;
|
|
1250
|
+
}
|
|
1251
|
+
socket.setTimeout(0);
|
|
1252
|
+
|
|
1253
|
+
const tTls = Date.now();
|
|
1254
|
+
tlsSocket = await new Promise((resolve, reject) => {
|
|
1255
|
+
const s = tls.connect({ socket, servername: target.hostname, ALPNProtocols: ['http/1.1'] }, () => resolve(s));
|
|
1256
|
+
s.once('error', reject);
|
|
1257
|
+
s.setTimeout(timeoutMs, () => reject(Object.assign(new Error('tls handshake timed out'), { code: 'PROBE_TLS_TIMEOUT' })));
|
|
1258
|
+
});
|
|
1259
|
+
result.tlsMs = Date.now() - tTls;
|
|
1260
|
+
result.tls = { protocol: tlsSocket.getProtocol(), authorized: tlsSocket.authorized === true, alpn: tlsSocket.alpnProtocol || null };
|
|
1261
|
+
if (tlsSocket.authorized !== true) {
|
|
1262
|
+
return finish({ code: 'TLS_CERTIFICATE_ERROR', error: 'certificate verification failed' });
|
|
1263
|
+
}
|
|
1264
|
+
tlsSocket.setTimeout(0);
|
|
1265
|
+
|
|
1266
|
+
const pathPart = (target.pathname || '/') + (target.search || '');
|
|
1267
|
+
tlsSocket.write(
|
|
1268
|
+
`GET ${pathPart} HTTP/1.1\r\nHost: ${target.hostname}\r\nUser-Agent: ${USER_AGENT}\r\nAccept: */*\r\nConnection: close\r\n\r\n`,
|
|
1269
|
+
);
|
|
1270
|
+
const responseText = await new Promise((resolve, reject) => {
|
|
1271
|
+
let buf = '';
|
|
1272
|
+
const onData = (chunk) => {
|
|
1273
|
+
buf += chunk.toString('latin1');
|
|
1274
|
+
if (buf.includes('\r\n\r\n') || buf.length > 32768) { tlsSocket.removeListener('data', onData); resolve(buf); }
|
|
1275
|
+
};
|
|
1276
|
+
const onEnd = () => resolve(buf);
|
|
1277
|
+
tlsSocket.on('data', onData);
|
|
1278
|
+
tlsSocket.once('end', onEnd);
|
|
1279
|
+
tlsSocket.once('error', reject);
|
|
1280
|
+
tlsSocket.once('timeout', () => reject(Object.assign(new Error('http response timed out'), { code: 'PROBE_HTTP_TIMEOUT' })));
|
|
1281
|
+
});
|
|
1282
|
+
result.receivedBytes = responseText.length;
|
|
1283
|
+
const status = _statusLine(responseText);
|
|
1284
|
+
const redirectTo = _headerValue(responseText, 'location');
|
|
1285
|
+
return finish({
|
|
1286
|
+
ok: status > 0 && status < 500,
|
|
1287
|
+
status,
|
|
1288
|
+
redirectTo: redirectTo ? safeOrigin(redirectTo) || safeOrigin(target.origin + redirectTo) : null,
|
|
1289
|
+
code: status >= 400 && status < 500 ? 'HTTP_CLIENT_STATUS' : (status >= 500 ? 'HTTP_SERVER_ERROR' : null),
|
|
1290
|
+
error: status >= 400 && status < 500 ? `origin returned ${status} (reachable)` : null,
|
|
1291
|
+
});
|
|
1292
|
+
} catch (err) {
|
|
1293
|
+
const code = (err && err.code) || 'PROBE_FAILED';
|
|
1294
|
+
const sanitized = /^PROBE_|^PROXY_|^TLS_/.test(code)
|
|
1295
|
+
? code
|
|
1296
|
+
: /ENOTFOUND|EAI_AGAIN/.test(code) ? 'PROBE_DNS_FAILED'
|
|
1297
|
+
: /ECONNREFUSED/.test(code) ? 'PROBE_TCP_REFUSED'
|
|
1298
|
+
: /ECONNRESET/.test(code) ? 'PROBE_TCP_RESET'
|
|
1299
|
+
: /CERT|TLS|SSL/i.test(String(err && err.message)) ? 'TLS_CERTIFICATE_ERROR'
|
|
1300
|
+
: 'PROBE_FAILED';
|
|
1301
|
+
return finish({
|
|
1302
|
+
code: sanitized,
|
|
1303
|
+
error: sanitized,
|
|
1304
|
+
status: Number.isFinite(err && err.status) ? err.status : null,
|
|
1305
|
+
// A tunnel that closed with zero bytes is a silent drop, not a timeout.
|
|
1306
|
+
silentDrop: err && err.silentDrop === true,
|
|
1307
|
+
connectMs: result.connectMs,
|
|
1308
|
+
});
|
|
1309
|
+
} finally {
|
|
1310
|
+
try { if (tlsSocket) tlsSocket.destroy(); } catch { /* ignore */ }
|
|
1311
|
+
try { if (socket) socket.destroy(); } catch { /* ignore */ }
|
|
1312
|
+
}
|
|
1313
|
+
})(), Math.max(timeoutMs, 1000) * 3, 'PROBE_OVERALL_TIMEOUT').catch((err) => finish({
|
|
1314
|
+
code: (err && err.code) || 'PROBE_OVERALL_TIMEOUT',
|
|
1315
|
+
error: (err && err.code) || 'probe overall timeout',
|
|
1316
|
+
}));
|
|
1317
|
+
}
|
|
1318
|
+
|
|
1319
|
+
/**
|
|
1320
|
+
* Probe every endpoint, bounded and sanitized. Results are returned in the
|
|
1321
|
+
* order of the requested list; failures never throw.
|
|
1322
|
+
*
|
|
1323
|
+
* @param {object} [o]
|
|
1324
|
+
* @param {string[]} [o.urls]
|
|
1325
|
+
* @param {object|string|null} [o.proxy]
|
|
1326
|
+
* @param {number} [o.timeoutMs]
|
|
1327
|
+
* @param {number} [o.concurrency=4]
|
|
1328
|
+
* @returns {Promise<{checkedAt:string, proxy:object, results:object[], summary:object}>}
|
|
1329
|
+
*/
|
|
1330
|
+
async function probeConnectivity(o = {}) {
|
|
1331
|
+
const urls = Array.isArray(o.urls) && o.urls.length > 0 ? o.urls : CONNECTIVITY_ENDPOINTS;
|
|
1332
|
+
const timeoutMs = Number.isFinite(o.timeoutMs) ? o.timeoutMs : DEFAULT_PROBE_TIMEOUT_MS;
|
|
1333
|
+
const concurrency = Math.max(1, Math.min(Number.isFinite(o.concurrency) ? o.concurrency : 4, urls.length));
|
|
1334
|
+
const results = new Array(urls.length);
|
|
1335
|
+
let cursor = 0;
|
|
1336
|
+
const workers = Array.from({ length: concurrency }, async () => {
|
|
1337
|
+
while (cursor < urls.length) {
|
|
1338
|
+
const idx = cursor++;
|
|
1339
|
+
results[idx] = await probeEndpoint({ url: urls[idx], proxy: o.proxy || null, timeoutMs });
|
|
1340
|
+
}
|
|
1341
|
+
});
|
|
1342
|
+
await Promise.all(workers);
|
|
1343
|
+
const failures = results.filter((r) => !r.ok).map((r) => ({ url: r.url, host: r.host, code: r.code, status: r.status }));
|
|
1344
|
+
return {
|
|
1345
|
+
checkedAt: new Date().toISOString(),
|
|
1346
|
+
proxy: sanitizeProxyForReport(o.proxy || null),
|
|
1347
|
+
results,
|
|
1348
|
+
summary: {
|
|
1349
|
+
total: results.length,
|
|
1350
|
+
reachable: results.length - failures.length,
|
|
1351
|
+
failed: failures.length,
|
|
1352
|
+
failures,
|
|
1353
|
+
},
|
|
1354
|
+
};
|
|
1355
|
+
}
|
|
1356
|
+
|
|
1357
|
+
// ── NetLog helpers ───────────────────────────────────────────────────────────
|
|
1358
|
+
|
|
1359
|
+
/**
|
|
1360
|
+
* Resolve the sanitized NetLog destination. Returns null unless
|
|
1361
|
+
* `XKWDSTORE_NETLOG_DIR` is set, so normal launches are unaffected.
|
|
1362
|
+
*/
|
|
1363
|
+
function resolveNetlogPath(now = new Date()) {
|
|
1364
|
+
const dir = process.env.XKWDSTORE_NETLOG_DIR;
|
|
1365
|
+
if (!dir || !path.isAbsolute(dir)) return null;
|
|
1366
|
+
const stamp = now.toISOString().replace(/[:.]/g, '-');
|
|
1367
|
+
return path.join(dir, `netlog-${stamp}-${process.pid}.json`);
|
|
1368
|
+
}
|
|
1369
|
+
|
|
1370
|
+
/** Chromium switches to capture a NetLog (only when a path is provided). */
|
|
1371
|
+
function netlogLaunchArgs(netlogPath, opts = {}) {
|
|
1372
|
+
if (!netlogPath) return [];
|
|
1373
|
+
const mode = opts.captureMode || process.env.XKWDSTORE_NETLOG_MODE || 'Default';
|
|
1374
|
+
return [`--log-net-log=${netlogPath}`, `--net-log-capture-mode=${mode}`];
|
|
1375
|
+
}
|
|
1376
|
+
|
|
1377
|
+
// ── NetLog sanitization ──────────────────────────────────────────────────────
|
|
1378
|
+
|
|
1379
|
+
const NETLOG_REDACT_KEY = /authorization|proxy-authorization|cookie|set-cookie|password|passwd|token|secret|credential|api[-_]?key/i;
|
|
1380
|
+
const NETLOG_DROP_KEY = /^(headers|raw_headers|request_headers|response_headers|cookies|upload_data)$/i;
|
|
1381
|
+
|
|
1382
|
+
/**
|
|
1383
|
+
* Remove the sensitive parts of a URL embedded anywhere in a string: userinfo,
|
|
1384
|
+
* query string and fragment. Path and host are kept (they are what makes a
|
|
1385
|
+
* NetLog useful) but a `?token=…` can never survive.
|
|
1386
|
+
*/
|
|
1387
|
+
function scrubNetlogString(value) {
|
|
1388
|
+
return String(value).replace(/(https?:\/\/)([^\s"'<>\\]+)/gi, (_m, scheme, rest) => {
|
|
1389
|
+
const withoutAuth = rest.replace(/^[^/@]*@/, '');
|
|
1390
|
+
const withoutQuery = withoutAuth.split(/[?#]/)[0];
|
|
1391
|
+
return scheme + withoutQuery;
|
|
1392
|
+
});
|
|
1393
|
+
}
|
|
1394
|
+
|
|
1395
|
+
/**
|
|
1396
|
+
* Sanitize a parsed NetLog object in place (returns a new object):
|
|
1397
|
+
* - drops header/cookie/upload payload blocks entirely,
|
|
1398
|
+
* - redacts credential-looking keys,
|
|
1399
|
+
* - strips userinfo/query/fragment from every URL-like string.
|
|
1400
|
+
* NetLog capture is opt-in; this runs over the raw file before it is handed to
|
|
1401
|
+
* an operator, so a diagnostic file can never leak a token or a cookie.
|
|
1402
|
+
*/
|
|
1403
|
+
function sanitizeNetlogObject(value, depth = 0) {
|
|
1404
|
+
if (depth > 60 || value == null) return value;
|
|
1405
|
+
if (Array.isArray(value)) return value.map((v) => sanitizeNetlogObject(v, depth + 1));
|
|
1406
|
+
if (typeof value === 'string') return scrubNetlogString(value);
|
|
1407
|
+
if (typeof value === 'object') {
|
|
1408
|
+
const out = {};
|
|
1409
|
+
for (const [k, v] of Object.entries(value)) {
|
|
1410
|
+
if (NETLOG_DROP_KEY.test(k)) { out[k] = '<redacted>'; continue; }
|
|
1411
|
+
out[k] = NETLOG_REDACT_KEY.test(k) ? '<redacted>' : sanitizeNetlogObject(v, depth + 1);
|
|
1412
|
+
}
|
|
1413
|
+
return out;
|
|
1414
|
+
}
|
|
1415
|
+
return value;
|
|
1416
|
+
}
|
|
1417
|
+
|
|
1418
|
+
/**
|
|
1419
|
+
* Sanitize a NetLog FILE in place. The raw bytes are read into memory, the file
|
|
1420
|
+
* is overwritten with the sanitized JSON, so no raw copy remains on disk.
|
|
1421
|
+
* @returns {{ok:boolean, bytes?:number, error?:string}}
|
|
1422
|
+
*/
|
|
1423
|
+
function sanitizeNetlogFile(filePath) {
|
|
1424
|
+
const fs = require('fs');
|
|
1425
|
+
try {
|
|
1426
|
+
const raw = fs.readFileSync(filePath, 'utf8');
|
|
1427
|
+
const parsed = JSON.parse(raw);
|
|
1428
|
+
const clean = sanitizeNetlogObject(parsed);
|
|
1429
|
+
fs.writeFileSync(filePath, JSON.stringify(clean), { encoding: 'utf8', mode: 0o600 });
|
|
1430
|
+
return { ok: true, bytes: fs.statSync(filePath).size };
|
|
1431
|
+
} catch (err) {
|
|
1432
|
+
return { ok: false, error: String((err && err.message) || err).slice(0, 160) };
|
|
1433
|
+
}
|
|
1434
|
+
}
|
|
1435
|
+
|
|
1436
|
+
module.exports = {
|
|
1437
|
+
CONNECTIVITY_ENDPOINTS,
|
|
1438
|
+
DEFAULT_NAVIGATION_TIMEOUT_MS,
|
|
1439
|
+
DEFAULT_STALL_TIMEOUT_MS,
|
|
1440
|
+
DEFAULT_HARD_STALL_TIMEOUT_MS,
|
|
1441
|
+
classifyNavigationFailure,
|
|
1442
|
+
isStalledNavigation,
|
|
1443
|
+
retryUrlFor,
|
|
1444
|
+
safeOrigin,
|
|
1445
|
+
sanitizeProxyForReport,
|
|
1446
|
+
parseProxyTarget,
|
|
1447
|
+
buildDiagnosticHtml,
|
|
1448
|
+
buildDiagnosticPage,
|
|
1449
|
+
paintNavigationFailure,
|
|
1450
|
+
navigateBounded,
|
|
1451
|
+
installNavigationGuard,
|
|
1452
|
+
probeEndpoint,
|
|
1453
|
+
probeConnectivity,
|
|
1454
|
+
resolveNetlogPath,
|
|
1455
|
+
netlogLaunchArgs,
|
|
1456
|
+
scrubNetlogString,
|
|
1457
|
+
sanitizeNetlogObject,
|
|
1458
|
+
sanitizeNetlogFile,
|
|
1459
|
+
_internal: { _statusLine, _headerValue, _probeCodeForConnectStatus, _escapeHtml },
|
|
1460
|
+
defaultNetlogDir: path.join(os.tmpdir(), 'tw-netlog'),
|
|
1461
|
+
};
|