@xkwdstore/agent 2.0.2 → 2.0.4

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.
@@ -1,339 +1,339 @@
1
- 'use strict';
2
-
3
- /**
4
- * Real proxy egress verification (Phase 8).
5
- *
6
- * A TCP connect to the proxy host:port (checkProxyHealth) only proves the port
7
- * is open — it does NOT prove the proxy actually tunnels traffic. A proxy that
8
- * accepts TCP but drops CONNECT, or is a transparent forward that would leak the
9
- * real IP, would still pass a TCP-only check and the browser could launch with
10
- * a broken/no-op proxy.
11
- *
12
- * verifyProxyEgress makes a real request THROUGH the proxy:
13
- * 1. open a TCP socket to the proxy;
14
- * 2. send an HTTP CONNECT to a known HTTPS endpoint (with Proxy-Authorization
15
- * when credentials are configured);
16
- * 3. require a 2xx "Connection established";
17
- * 4. upgrade the tunneled socket to TLS and GET the endpoint;
18
- * 5. parse the egress IP from the response body.
19
- *
20
- * The check succeeds only if the proxy really forwarded an HTTPS request to an
21
- * external host and returned a response. It NEVER falls back to a direct
22
- * connection. The pure helpers (buildConnectRequest, parseConnectStatus,
23
- * parseEgressIp, parseProxyForConnect) are unit-tested without any network.
24
- */
25
-
26
- const net = require('net');
27
- const tls = require('tls');
28
-
29
- const DEFAULT_EGRESS_URL = process.env.PROXY_EGRESS_CHECK_URL || 'https://api.ipify.org/';
30
- const EGRESS_TIMEOUT_MS = parseInt(process.env.PROXY_EGRESS_TIMEOUT_MS || '8000', 10);
31
- const TCP_CONNECT_TIMEOUT_MS = 4000;
32
-
33
- /**
34
- * Normalize a proxy (raw "host:port[:user:pass]" string or a Playwright-style
35
- * { server, username, password }) to { host, port, username, password }.
36
- * Returns null if it cannot be parsed.
37
- */
38
- function parseProxyForConnect(proxy) {
39
- if (typeof proxy === 'string' && proxy.trim()) {
40
- const parts = proxy.trim().split(':');
41
- const host = parts[0];
42
- const port = parseInt(parts[1], 10);
43
- if (!host || !port) return null;
44
- return { host, port, username: parts[2] || undefined, password: parts[3] || undefined };
45
- }
46
- if (proxy && proxy.server) {
47
- let u;
48
- try { u = new URL(proxy.server); } catch { return null; }
49
- const host = u.hostname;
50
- const port = parseInt(u.port, 10) || (u.protocol === 'https:' ? 443 : 80);
51
- if (!host || !port) return null;
52
- return { host, port, username: proxy.username, password: proxy.password };
53
- }
54
- return null;
55
- }
56
-
57
- /**
58
- * Build the HTTP CONNECT request line for tunneling to targetHost:targetPort.
59
- * `auth` is { username, password } when the proxy requires credentials.
60
- */
61
- function buildConnectRequest(targetHost, targetPort, auth) {
62
- const lines = [
63
- `CONNECT ${targetHost}:${targetPort} HTTP/1.1`,
64
- `Host: ${targetHost}:${targetPort}`,
65
- ];
66
- if (auth && auth.username != null && auth.username !== '') {
67
- const cred = Buffer.from(`${auth.username}:${auth.password || ''}`).toString('base64');
68
- lines.push(`Proxy-Authorization: Basic ${cred}`);
69
- }
70
- return lines.join('\r\n') + '\r\n\r\n';
71
- }
72
-
73
- /**
74
- * Parse the proxy's CONNECT response status. `data` is a Buffer (or string) of
75
- * the response header block. Returns { ok, status, line }. ok is true only for
76
- * a 2xx status.
77
- */
78
- function parseConnectStatus(data) {
79
- const text = Buffer.isBuffer(data) ? data.toString('utf8') : String(data);
80
- const line = text.split('\r\n')[0] || '';
81
- const m = /^HTTP\/\d(?:\.\d)?\s+(\d{3})/.exec(line);
82
- if (!m) return { ok: false, status: 0, line };
83
- const status = parseInt(m[1], 10);
84
- return { ok: status >= 200 && status < 300, status, line };
85
- }
86
-
87
- /**
88
- * Extract an IPv4 or IPv6 address from an echo-response body. ipify returns a
89
- * bare IP; we also tolerate JSON like {"ip":"..."}.
90
- */
91
- function parseEgressIp(body) {
92
- const text = (Buffer.isBuffer(body) ? body.toString('utf8') : String(body)).trim();
93
- const m = /(\b(?:\d{1,3}\.){3}\d{1,3}\b|(?:[0-9a-fA-F]{1,4}:){2,7}[0-9a-fA-F]{0,4})/.exec(text);
94
- return m ? m[1] : null;
95
- }
96
-
97
- /**
98
- * Perform the through-proxy egress check. Returns { ok, reason, egressIp? }.
99
- * Always resolves (never rejects); any error fails closed with { ok: false }.
100
- */
101
- function verifyProxyEgress(proxy, options = {}) {
102
- const egressUrl = options.egressUrl || DEFAULT_EGRESS_URL;
103
- const timeoutMs = options.timeoutMs || EGRESS_TIMEOUT_MS;
104
- const pc = parseProxyForConnect(proxy);
105
- if (!pc) return Promise.resolve({ ok: false, reason: 'invalid proxy' });
106
- let target;
107
- try { target = new URL(egressUrl); }
108
- catch { return Promise.resolve({ ok: false, reason: 'invalid egress url' }); }
109
- if (target.protocol !== 'https:') {
110
- return Promise.resolve({ ok: false, reason: 'egress url must be https' });
111
- }
112
- const targetHost = target.hostname;
113
- const targetPort = parseInt(target.port, 10) || 443;
114
-
115
- return new Promise((resolve) => {
116
- let settled = false;
117
- let socket = new net.Socket();
118
- const finish = (r) => {
119
- if (settled) return;
120
- settled = true;
121
- try { socket.destroy(); } catch {}
122
- resolve(r);
123
- };
124
- const timer = setTimeout(() => finish({ ok: false, reason: 'egress timeout' }), timeoutMs);
125
-
126
- socket.setTimeout(TCP_CONNECT_TIMEOUT_MS);
127
- socket.once('timeout', () => finish({ ok: false, reason: 'proxy connect timeout' }));
128
- socket.once('error', (err) => finish({ ok: false, reason: 'proxy connect error: ' + err.message }));
129
-
130
- socket.connect(pc.port, pc.host, () => {
131
- socket.write(buildConnectRequest(targetHost, targetPort, { username: pc.username, password: pc.password }));
132
- let buf = Buffer.alloc(0);
133
- const onConnectData = (chunk) => {
134
- buf = Buffer.concat([buf, chunk]);
135
- const headerEnd = buf.indexOf('\r\n\r\n');
136
- if (headerEnd === -1) {
137
- // Wait for the full header block; guard against a runaway response.
138
- if (buf.length > 8192) {
139
- socket.removeListener('data', onConnectData);
140
- clearTimeout(timer);
141
- finish({ ok: false, reason: 'proxy connect response too large' });
142
- }
143
- return;
144
- }
145
- const status = parseConnectStatus(buf.slice(0, headerEnd));
146
- socket.removeListener('data', onConnectData);
147
- if (!status.ok) {
148
- clearTimeout(timer);
149
- finish({ ok: false, reason: 'proxy refused connect (' + status.status + ')' });
150
- return;
151
- }
152
- // Upgrade the tunneled socket to TLS and issue the GET.
153
- let tlsDone = false;
154
- const finishTls = (r) => {
155
- if (tlsDone) return;
156
- tlsDone = true;
157
- clearTimeout(timer);
158
- try { tlsSocket.destroy(); } catch {}
159
- finish(r);
160
- };
161
- const tlsSocket = tls.connect({
162
- socket,
163
- servername: targetHost,
164
- rejectUnauthorized: true,
165
- });
166
- tlsSocket.setTimeout(timeoutMs);
167
- tlsSocket.once('secureConnect', () => {
168
- const path = (target.pathname || '/') + (target.search || '');
169
- const req =
170
- `GET ${path} HTTP/1.1\r\n` +
171
- `Host: ${targetHost}\r\n` +
172
- `Connection: close\r\n` +
173
- `User-Agent: tw-agent-egress-check\r\n\r\n`;
174
- tlsSocket.write(req);
175
- let respBuf = Buffer.alloc(0);
176
- tlsSocket.on('data', (c) => { respBuf = Buffer.concat([respBuf, c]); });
177
- tlsSocket.on('end', () => {
178
- const sep = respBuf.indexOf('\r\n\r\n');
179
- const body = sep === -1 ? respBuf : respBuf.slice(sep + 4);
180
- const ip = parseEgressIp(body);
181
- if (!ip) { finishTls({ ok: false, reason: 'egress response had no IP' }); return; }
182
- finishTls({ ok: true, reason: 'egress ok', egressIp: ip });
183
- });
184
- tlsSocket.on('error', (err) => finishTls({ ok: false, reason: 'egress tls error: ' + err.message }));
185
- tlsSocket.on('timeout', () => finishTls({ ok: false, reason: 'egress response timeout' }));
186
- });
187
- tlsSocket.on('error', (err) => finishTls({ ok: false, reason: 'egress tls handshake error: ' + err.message }));
188
- tlsSocket.on('timeout', () => finishTls({ ok: false, reason: 'egress tls handshake timeout' }));
189
- };
190
- socket.on('data', onConnectData);
191
- });
192
- });
193
- }
194
-
195
- // ── Phase 17: direct-IP vs proxy-IP comparison ───────────────────────────────
196
- //
197
- // A proxy that successfully tunnels is NOT proof of isolation: a transparent or
198
- // misconfigured proxy can egress from the DEVICE's own public IP, leaking the
199
- // real IP while looking "healthy". Proxy isolation is only real when the proxy
200
- // egress IP DIFFERS from the device's direct public IP, measured independently
201
- // (a direct connection that bypasses the proxy, sending no proxy credentials).
202
- // On a match the launch must FAIL CLOSED with PROXY_DIRECT_BYPASS_DETECTED.
203
-
204
- const DEFAULT_DIRECT_IP_URL = process.env.PROXY_DIRECT_IP_CHECK_URL || 'https://api.ipify.org/';
205
- const DIRECT_IP_TIMEOUT_MS = parseInt(process.env.PROXY_DIRECT_IP_TIMEOUT_MS || '8000', 10);
206
-
207
- /**
208
- * PURE comparison of the proxy egress IP against the device's direct public IP.
209
- * Proxy isolation holds ONLY when the two differ. Returns a STRUCTURED result:
210
- * PROXY_EGRESS_UNMEASURED — the proxy egress IP is missing (fail closed)
211
- * PROXY_DIRECT_IP_UNMEASURED — the direct IP is missing (fail closed; never
212
- * claim isolation without measuring both)
213
- * PROXY_DIRECT_BYPASS_DETECTED — egress === direct (proxy leaks the real IP)
214
- * PROXY_ISOLATION_OK — egress !== direct, isolation holds
215
- */
216
- function compareEgress(egressIp, directIp) {
217
- if (!egressIp) {
218
- return { ok: false, code: 'PROXY_EGRESS_UNMEASURED', reason: 'proxy egress IP was not measured' };
219
- }
220
- if (!directIp) {
221
- return { ok: false, code: 'PROXY_DIRECT_IP_UNMEASURED', reason: 'device direct public IP was not measured; refusing to claim isolation' };
222
- }
223
- if (String(egressIp).trim() === String(directIp).trim()) {
224
- return {
225
- ok: false,
226
- code: 'PROXY_DIRECT_BYPASS_DETECTED',
227
- reason: 'proxy egress IP matches the device direct IP — the proxy is leaking the real IP',
228
- egressIp,
229
- directIp,
230
- };
231
- }
232
- return {
233
- ok: true,
234
- code: 'PROXY_ISOLATION_OK',
235
- reason: 'proxy egress differs from the device direct IP',
236
- egressIp,
237
- directIp,
238
- };
239
- }
240
-
241
- /**
242
- * Measure the device's DIRECT public IP — a plain HTTPS GET to an IP-echo
243
- * service with NO proxy and NO credentials (creds never go to a public IP
244
- * service). Always resolves (never rejects); any error fails closed. Returns
245
- * { ok, ip?, reason?, code? }.
246
- */
247
- function fetchDirectPublicIp(options = {}) {
248
- const urlStr = options.directIpUrl || DEFAULT_DIRECT_IP_URL;
249
- const timeoutMs = options.timeoutMs || DIRECT_IP_TIMEOUT_MS;
250
- let target;
251
- try { target = new URL(urlStr); } catch {
252
- return Promise.resolve({ ok: false, code: 'PROXY_DIRECT_IP_INVALID_URL', reason: 'invalid direct ip url' });
253
- }
254
- if (target.protocol !== 'https:') {
255
- return Promise.resolve({ ok: false, code: 'PROXY_DIRECT_IP_INVALID_URL', reason: 'direct ip url must be https' });
256
- }
257
- const host = target.hostname;
258
- const port = parseInt(target.port, 10) || 443;
259
-
260
- return new Promise((resolve) => {
261
- let settled = false;
262
- let tlsSocket;
263
- const finish = (r) => {
264
- if (settled) return;
265
- settled = true;
266
- clearTimeout(timer);
267
- try { tlsSocket && tlsSocket.destroy(); } catch {}
268
- resolve(r);
269
- };
270
- const timer = setTimeout(() => finish({ ok: false, code: 'PROXY_DIRECT_IP_TIMEOUT', reason: 'direct ip check timeout' }), timeoutMs);
271
- try {
272
- tlsSocket = tls.connect({ host, port, servername: host, rejectUnauthorized: true });
273
- } catch (e) {
274
- clearTimeout(timer);
275
- return resolve({ ok: false, code: 'PROXY_DIRECT_IP_CONNECT_FAILED', reason: 'direct ip connect failed: ' + e.message });
276
- }
277
- tlsSocket.setTimeout(timeoutMs);
278
- tlsSocket.once('secureConnect', () => {
279
- const path = (target.pathname || '/') + (target.search || '');
280
- tlsSocket.write(
281
- `GET ${path} HTTP/1.1\r\n` +
282
- `Host: ${host}\r\n` +
283
- `Connection: close\r\n` +
284
- `User-Agent: tw-agent-direct-ip-check\r\n\r\n`,
285
- );
286
- let buf = Buffer.alloc(0);
287
- tlsSocket.on('data', (c) => { buf = Buffer.concat([buf, c]); });
288
- tlsSocket.on('end', () => {
289
- const sep = buf.indexOf('\r\n\r\n');
290
- const body = sep === -1 ? buf : buf.slice(sep + 4);
291
- const ip = parseEgressIp(body);
292
- if (!ip) return finish({ ok: false, code: 'PROXY_DIRECT_IP_NO_IP', reason: 'direct ip response had no IP' });
293
- finish({ ok: true, ip });
294
- });
295
- });
296
- tlsSocket.on('error', (err) => finish({ ok: false, code: 'PROXY_DIRECT_IP_ERROR', reason: 'direct ip error: ' + err.message }));
297
- tlsSocket.on('timeout', () => finish({ ok: false, code: 'PROXY_DIRECT_IP_TIMEOUT', reason: 'direct ip check timeout' }));
298
- });
299
- }
300
-
301
- /**
302
- * Orchestrate the full Phase 17 isolation check: measure the proxy egress IP
303
- * (or reuse a pre-measured `options.egressIp`), independently measure the
304
- * device direct IP, and compare. Credentials are never sent to the public IP
305
- * service (Proxy-Authorization is hop-by-hop to the proxy only; the direct
306
- * fetch uses no proxy and no creds). Returns a STRUCTURED { ok, code, reason,
307
- * egressIp?, directIp? }.
308
- */
309
- async function verifyProxyIsolation(proxy, options = {}) {
310
- let egressIp = options.egressIp;
311
- if (!egressIp) {
312
- const egress = await verifyProxyEgress(proxy, options);
313
- if (!egress.ok) {
314
- return { ok: false, code: 'PROXY_EGRESS_UNREACHABLE', reason: 'proxy egress failed: ' + egress.reason };
315
- }
316
- egressIp = egress.egressIp;
317
- }
318
- const direct = await fetchDirectPublicIp(options);
319
- if (!direct.ok) {
320
- return {
321
- ok: false,
322
- code: direct.code || 'PROXY_DIRECT_IP_UNMEASURED',
323
- reason: direct.reason || 'direct ip unmeasured',
324
- egressIp,
325
- };
326
- }
327
- return compareEgress(egressIp, direct.ip);
328
- }
329
-
330
- module.exports = {
331
- verifyProxyEgress,
332
- verifyProxyIsolation,
333
- fetchDirectPublicIp,
334
- compareEgress,
335
- buildConnectRequest,
336
- parseConnectStatus,
337
- parseEgressIp,
338
- parseProxyForConnect,
1
+ 'use strict';
2
+
3
+ /**
4
+ * Real proxy egress verification (Phase 8).
5
+ *
6
+ * A TCP connect to the proxy host:port (checkProxyHealth) only proves the port
7
+ * is open — it does NOT prove the proxy actually tunnels traffic. A proxy that
8
+ * accepts TCP but drops CONNECT, or is a transparent forward that would leak the
9
+ * real IP, would still pass a TCP-only check and the browser could launch with
10
+ * a broken/no-op proxy.
11
+ *
12
+ * verifyProxyEgress makes a real request THROUGH the proxy:
13
+ * 1. open a TCP socket to the proxy;
14
+ * 2. send an HTTP CONNECT to a known HTTPS endpoint (with Proxy-Authorization
15
+ * when credentials are configured);
16
+ * 3. require a 2xx "Connection established";
17
+ * 4. upgrade the tunneled socket to TLS and GET the endpoint;
18
+ * 5. parse the egress IP from the response body.
19
+ *
20
+ * The check succeeds only if the proxy really forwarded an HTTPS request to an
21
+ * external host and returned a response. It NEVER falls back to a direct
22
+ * connection. The pure helpers (buildConnectRequest, parseConnectStatus,
23
+ * parseEgressIp, parseProxyForConnect) are unit-tested without any network.
24
+ */
25
+
26
+ const net = require('net');
27
+ const tls = require('tls');
28
+
29
+ const DEFAULT_EGRESS_URL = process.env.PROXY_EGRESS_CHECK_URL || 'https://api.ipify.org/';
30
+ const EGRESS_TIMEOUT_MS = parseInt(process.env.PROXY_EGRESS_TIMEOUT_MS || '8000', 10);
31
+ const TCP_CONNECT_TIMEOUT_MS = 4000;
32
+
33
+ /**
34
+ * Normalize a proxy (raw "host:port[:user:pass]" string or a Playwright-style
35
+ * { server, username, password }) to { host, port, username, password }.
36
+ * Returns null if it cannot be parsed.
37
+ */
38
+ function parseProxyForConnect(proxy) {
39
+ if (typeof proxy === 'string' && proxy.trim()) {
40
+ const parts = proxy.trim().split(':');
41
+ const host = parts[0];
42
+ const port = parseInt(parts[1], 10);
43
+ if (!host || !port) return null;
44
+ return { host, port, username: parts[2] || undefined, password: parts[3] || undefined };
45
+ }
46
+ if (proxy && proxy.server) {
47
+ let u;
48
+ try { u = new URL(proxy.server); } catch { return null; }
49
+ const host = u.hostname;
50
+ const port = parseInt(u.port, 10) || (u.protocol === 'https:' ? 443 : 80);
51
+ if (!host || !port) return null;
52
+ return { host, port, username: proxy.username, password: proxy.password };
53
+ }
54
+ return null;
55
+ }
56
+
57
+ /**
58
+ * Build the HTTP CONNECT request line for tunneling to targetHost:targetPort.
59
+ * `auth` is { username, password } when the proxy requires credentials.
60
+ */
61
+ function buildConnectRequest(targetHost, targetPort, auth) {
62
+ const lines = [
63
+ `CONNECT ${targetHost}:${targetPort} HTTP/1.1`,
64
+ `Host: ${targetHost}:${targetPort}`,
65
+ ];
66
+ if (auth && auth.username != null && auth.username !== '') {
67
+ const cred = Buffer.from(`${auth.username}:${auth.password || ''}`).toString('base64');
68
+ lines.push(`Proxy-Authorization: Basic ${cred}`);
69
+ }
70
+ return lines.join('\r\n') + '\r\n\r\n';
71
+ }
72
+
73
+ /**
74
+ * Parse the proxy's CONNECT response status. `data` is a Buffer (or string) of
75
+ * the response header block. Returns { ok, status, line }. ok is true only for
76
+ * a 2xx status.
77
+ */
78
+ function parseConnectStatus(data) {
79
+ const text = Buffer.isBuffer(data) ? data.toString('utf8') : String(data);
80
+ const line = text.split('\r\n')[0] || '';
81
+ const m = /^HTTP\/\d(?:\.\d)?\s+(\d{3})/.exec(line);
82
+ if (!m) return { ok: false, status: 0, line };
83
+ const status = parseInt(m[1], 10);
84
+ return { ok: status >= 200 && status < 300, status, line };
85
+ }
86
+
87
+ /**
88
+ * Extract an IPv4 or IPv6 address from an echo-response body. ipify returns a
89
+ * bare IP; we also tolerate JSON like {"ip":"..."}.
90
+ */
91
+ function parseEgressIp(body) {
92
+ const text = (Buffer.isBuffer(body) ? body.toString('utf8') : String(body)).trim();
93
+ const m = /(\b(?:\d{1,3}\.){3}\d{1,3}\b|(?:[0-9a-fA-F]{1,4}:){2,7}[0-9a-fA-F]{0,4})/.exec(text);
94
+ return m ? m[1] : null;
95
+ }
96
+
97
+ /**
98
+ * Perform the through-proxy egress check. Returns { ok, reason, egressIp? }.
99
+ * Always resolves (never rejects); any error fails closed with { ok: false }.
100
+ */
101
+ function verifyProxyEgress(proxy, options = {}) {
102
+ const egressUrl = options.egressUrl || DEFAULT_EGRESS_URL;
103
+ const timeoutMs = options.timeoutMs || EGRESS_TIMEOUT_MS;
104
+ const pc = parseProxyForConnect(proxy);
105
+ if (!pc) return Promise.resolve({ ok: false, reason: 'invalid proxy' });
106
+ let target;
107
+ try { target = new URL(egressUrl); }
108
+ catch { return Promise.resolve({ ok: false, reason: 'invalid egress url' }); }
109
+ if (target.protocol !== 'https:') {
110
+ return Promise.resolve({ ok: false, reason: 'egress url must be https' });
111
+ }
112
+ const targetHost = target.hostname;
113
+ const targetPort = parseInt(target.port, 10) || 443;
114
+
115
+ return new Promise((resolve) => {
116
+ let settled = false;
117
+ let socket = new net.Socket();
118
+ const finish = (r) => {
119
+ if (settled) return;
120
+ settled = true;
121
+ try { socket.destroy(); } catch {}
122
+ resolve(r);
123
+ };
124
+ const timer = setTimeout(() => finish({ ok: false, reason: 'egress timeout' }), timeoutMs);
125
+
126
+ socket.setTimeout(TCP_CONNECT_TIMEOUT_MS);
127
+ socket.once('timeout', () => finish({ ok: false, reason: 'proxy connect timeout' }));
128
+ socket.once('error', (err) => finish({ ok: false, reason: 'proxy connect error: ' + err.message }));
129
+
130
+ socket.connect(pc.port, pc.host, () => {
131
+ socket.write(buildConnectRequest(targetHost, targetPort, { username: pc.username, password: pc.password }));
132
+ let buf = Buffer.alloc(0);
133
+ const onConnectData = (chunk) => {
134
+ buf = Buffer.concat([buf, chunk]);
135
+ const headerEnd = buf.indexOf('\r\n\r\n');
136
+ if (headerEnd === -1) {
137
+ // Wait for the full header block; guard against a runaway response.
138
+ if (buf.length > 8192) {
139
+ socket.removeListener('data', onConnectData);
140
+ clearTimeout(timer);
141
+ finish({ ok: false, reason: 'proxy connect response too large' });
142
+ }
143
+ return;
144
+ }
145
+ const status = parseConnectStatus(buf.slice(0, headerEnd));
146
+ socket.removeListener('data', onConnectData);
147
+ if (!status.ok) {
148
+ clearTimeout(timer);
149
+ finish({ ok: false, reason: 'proxy refused connect (' + status.status + ')' });
150
+ return;
151
+ }
152
+ // Upgrade the tunneled socket to TLS and issue the GET.
153
+ let tlsDone = false;
154
+ const finishTls = (r) => {
155
+ if (tlsDone) return;
156
+ tlsDone = true;
157
+ clearTimeout(timer);
158
+ try { tlsSocket.destroy(); } catch {}
159
+ finish(r);
160
+ };
161
+ const tlsSocket = tls.connect({
162
+ socket,
163
+ servername: targetHost,
164
+ rejectUnauthorized: true,
165
+ });
166
+ tlsSocket.setTimeout(timeoutMs);
167
+ tlsSocket.once('secureConnect', () => {
168
+ const path = (target.pathname || '/') + (target.search || '');
169
+ const req =
170
+ `GET ${path} HTTP/1.1\r\n` +
171
+ `Host: ${targetHost}\r\n` +
172
+ `Connection: close\r\n` +
173
+ `User-Agent: tw-agent-egress-check\r\n\r\n`;
174
+ tlsSocket.write(req);
175
+ let respBuf = Buffer.alloc(0);
176
+ tlsSocket.on('data', (c) => { respBuf = Buffer.concat([respBuf, c]); });
177
+ tlsSocket.on('end', () => {
178
+ const sep = respBuf.indexOf('\r\n\r\n');
179
+ const body = sep === -1 ? respBuf : respBuf.slice(sep + 4);
180
+ const ip = parseEgressIp(body);
181
+ if (!ip) { finishTls({ ok: false, reason: 'egress response had no IP' }); return; }
182
+ finishTls({ ok: true, reason: 'egress ok', egressIp: ip });
183
+ });
184
+ tlsSocket.on('error', (err) => finishTls({ ok: false, reason: 'egress tls error: ' + err.message }));
185
+ tlsSocket.on('timeout', () => finishTls({ ok: false, reason: 'egress response timeout' }));
186
+ });
187
+ tlsSocket.on('error', (err) => finishTls({ ok: false, reason: 'egress tls handshake error: ' + err.message }));
188
+ tlsSocket.on('timeout', () => finishTls({ ok: false, reason: 'egress tls handshake timeout' }));
189
+ };
190
+ socket.on('data', onConnectData);
191
+ });
192
+ });
193
+ }
194
+
195
+ // ── Phase 17: direct-IP vs proxy-IP comparison ───────────────────────────────
196
+ //
197
+ // A proxy that successfully tunnels is NOT proof of isolation: a transparent or
198
+ // misconfigured proxy can egress from the DEVICE's own public IP, leaking the
199
+ // real IP while looking "healthy". Proxy isolation is only real when the proxy
200
+ // egress IP DIFFERS from the device's direct public IP, measured independently
201
+ // (a direct connection that bypasses the proxy, sending no proxy credentials).
202
+ // On a match the launch must FAIL CLOSED with PROXY_DIRECT_BYPASS_DETECTED.
203
+
204
+ const DEFAULT_DIRECT_IP_URL = process.env.PROXY_DIRECT_IP_CHECK_URL || 'https://api.ipify.org/';
205
+ const DIRECT_IP_TIMEOUT_MS = parseInt(process.env.PROXY_DIRECT_IP_TIMEOUT_MS || '8000', 10);
206
+
207
+ /**
208
+ * PURE comparison of the proxy egress IP against the device's direct public IP.
209
+ * Proxy isolation holds ONLY when the two differ. Returns a STRUCTURED result:
210
+ * PROXY_EGRESS_UNMEASURED — the proxy egress IP is missing (fail closed)
211
+ * PROXY_DIRECT_IP_UNMEASURED — the direct IP is missing (fail closed; never
212
+ * claim isolation without measuring both)
213
+ * PROXY_DIRECT_BYPASS_DETECTED — egress === direct (proxy leaks the real IP)
214
+ * PROXY_ISOLATION_OK — egress !== direct, isolation holds
215
+ */
216
+ function compareEgress(egressIp, directIp) {
217
+ if (!egressIp) {
218
+ return { ok: false, code: 'PROXY_EGRESS_UNMEASURED', reason: 'proxy egress IP was not measured' };
219
+ }
220
+ if (!directIp) {
221
+ return { ok: false, code: 'PROXY_DIRECT_IP_UNMEASURED', reason: 'device direct public IP was not measured; refusing to claim isolation' };
222
+ }
223
+ if (String(egressIp).trim() === String(directIp).trim()) {
224
+ return {
225
+ ok: false,
226
+ code: 'PROXY_DIRECT_BYPASS_DETECTED',
227
+ reason: 'proxy egress IP matches the device direct IP — the proxy is leaking the real IP',
228
+ egressIp,
229
+ directIp,
230
+ };
231
+ }
232
+ return {
233
+ ok: true,
234
+ code: 'PROXY_ISOLATION_OK',
235
+ reason: 'proxy egress differs from the device direct IP',
236
+ egressIp,
237
+ directIp,
238
+ };
239
+ }
240
+
241
+ /**
242
+ * Measure the device's DIRECT public IP — a plain HTTPS GET to an IP-echo
243
+ * service with NO proxy and NO credentials (creds never go to a public IP
244
+ * service). Always resolves (never rejects); any error fails closed. Returns
245
+ * { ok, ip?, reason?, code? }.
246
+ */
247
+ function fetchDirectPublicIp(options = {}) {
248
+ const urlStr = options.directIpUrl || DEFAULT_DIRECT_IP_URL;
249
+ const timeoutMs = options.timeoutMs || DIRECT_IP_TIMEOUT_MS;
250
+ let target;
251
+ try { target = new URL(urlStr); } catch {
252
+ return Promise.resolve({ ok: false, code: 'PROXY_DIRECT_IP_INVALID_URL', reason: 'invalid direct ip url' });
253
+ }
254
+ if (target.protocol !== 'https:') {
255
+ return Promise.resolve({ ok: false, code: 'PROXY_DIRECT_IP_INVALID_URL', reason: 'direct ip url must be https' });
256
+ }
257
+ const host = target.hostname;
258
+ const port = parseInt(target.port, 10) || 443;
259
+
260
+ return new Promise((resolve) => {
261
+ let settled = false;
262
+ let tlsSocket;
263
+ const finish = (r) => {
264
+ if (settled) return;
265
+ settled = true;
266
+ clearTimeout(timer);
267
+ try { tlsSocket && tlsSocket.destroy(); } catch {}
268
+ resolve(r);
269
+ };
270
+ const timer = setTimeout(() => finish({ ok: false, code: 'PROXY_DIRECT_IP_TIMEOUT', reason: 'direct ip check timeout' }), timeoutMs);
271
+ try {
272
+ tlsSocket = tls.connect({ host, port, servername: host, rejectUnauthorized: true });
273
+ } catch (e) {
274
+ clearTimeout(timer);
275
+ return resolve({ ok: false, code: 'PROXY_DIRECT_IP_CONNECT_FAILED', reason: 'direct ip connect failed: ' + e.message });
276
+ }
277
+ tlsSocket.setTimeout(timeoutMs);
278
+ tlsSocket.once('secureConnect', () => {
279
+ const path = (target.pathname || '/') + (target.search || '');
280
+ tlsSocket.write(
281
+ `GET ${path} HTTP/1.1\r\n` +
282
+ `Host: ${host}\r\n` +
283
+ `Connection: close\r\n` +
284
+ `User-Agent: tw-agent-direct-ip-check\r\n\r\n`,
285
+ );
286
+ let buf = Buffer.alloc(0);
287
+ tlsSocket.on('data', (c) => { buf = Buffer.concat([buf, c]); });
288
+ tlsSocket.on('end', () => {
289
+ const sep = buf.indexOf('\r\n\r\n');
290
+ const body = sep === -1 ? buf : buf.slice(sep + 4);
291
+ const ip = parseEgressIp(body);
292
+ if (!ip) return finish({ ok: false, code: 'PROXY_DIRECT_IP_NO_IP', reason: 'direct ip response had no IP' });
293
+ finish({ ok: true, ip });
294
+ });
295
+ });
296
+ tlsSocket.on('error', (err) => finish({ ok: false, code: 'PROXY_DIRECT_IP_ERROR', reason: 'direct ip error: ' + err.message }));
297
+ tlsSocket.on('timeout', () => finish({ ok: false, code: 'PROXY_DIRECT_IP_TIMEOUT', reason: 'direct ip check timeout' }));
298
+ });
299
+ }
300
+
301
+ /**
302
+ * Orchestrate the full Phase 17 isolation check: measure the proxy egress IP
303
+ * (or reuse a pre-measured `options.egressIp`), independently measure the
304
+ * device direct IP, and compare. Credentials are never sent to the public IP
305
+ * service (Proxy-Authorization is hop-by-hop to the proxy only; the direct
306
+ * fetch uses no proxy and no creds). Returns a STRUCTURED { ok, code, reason,
307
+ * egressIp?, directIp? }.
308
+ */
309
+ async function verifyProxyIsolation(proxy, options = {}) {
310
+ let egressIp = options.egressIp;
311
+ if (!egressIp) {
312
+ const egress = await verifyProxyEgress(proxy, options);
313
+ if (!egress.ok) {
314
+ return { ok: false, code: 'PROXY_EGRESS_UNREACHABLE', reason: 'proxy egress failed: ' + egress.reason };
315
+ }
316
+ egressIp = egress.egressIp;
317
+ }
318
+ const direct = await fetchDirectPublicIp(options);
319
+ if (!direct.ok) {
320
+ return {
321
+ ok: false,
322
+ code: direct.code || 'PROXY_DIRECT_IP_UNMEASURED',
323
+ reason: direct.reason || 'direct ip unmeasured',
324
+ egressIp,
325
+ };
326
+ }
327
+ return compareEgress(egressIp, direct.ip);
328
+ }
329
+
330
+ module.exports = {
331
+ verifyProxyEgress,
332
+ verifyProxyIsolation,
333
+ fetchDirectPublicIp,
334
+ compareEgress,
335
+ buildConnectRequest,
336
+ parseConnectStatus,
337
+ parseEgressIp,
338
+ parseProxyForConnect,
339
339
  };