@xkwdstore/agent 2.0.1
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/README.md +245 -0
- package/package.json +55 -0
- package/src/actions/comment.js +138 -0
- package/src/actions/dbc.js +150 -0
- package/src/actions/follow.js +83 -0
- package/src/actions/helpers.js +754 -0
- package/src/actions/index.js +95 -0
- package/src/actions/like.js +245 -0
- package/src/actions/session.js +1611 -0
- package/src/actions/tweet.js +91 -0
- package/src/challengeCodec.js +32 -0
- package/src/chromeDetector.js +155 -0
- package/src/cli.js +529 -0
- package/src/configStore.js +98 -0
- package/src/deviceKeyStore.js +700 -0
- package/src/enrollmentClient.js +446 -0
- package/src/fingerprint.js +262 -0
- package/src/fingerprintStore.js +126 -0
- package/src/leaseClient.js +85 -0
- package/src/processLock.js +149 -0
- package/src/profilePath.js +1117 -0
- package/src/proxyEgress.js +339 -0
- package/src/proxyPolicy.js +77 -0
- package/src/secretStore.js +133 -0
- package/src/sessionHandler.js +453 -0
- package/src/stealth.js +1251 -0
- package/src/wsClient.js +234 -0
|
@@ -0,0 +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,
|
|
339
|
+
};
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Pure, side-effect-free proxy launch policy.
|
|
5
|
+
*
|
|
6
|
+
* Extracted from startSession() so the fail-closed proxy routing decision can
|
|
7
|
+
* be unit-tested without Playwright/Chrome. The agent calls decideProxyLaunch()
|
|
8
|
+
* with the configured proxy string, the network mode, and the proxy health
|
|
9
|
+
* result, then acts on the returned decision.
|
|
10
|
+
*
|
|
11
|
+
* FAIL-CLOSED RULES (Phase 2):
|
|
12
|
+
* - A proxy was provided → it MUST be reachable, or the launch ABORTS.
|
|
13
|
+
* We never silently fall back to a direct
|
|
14
|
+
* connection (that would leak the real IP for an
|
|
15
|
+
* account configured to use a proxy).
|
|
16
|
+
* - No proxy + proxy_required → ABORT. Do not open a direct browser.
|
|
17
|
+
* - No proxy + direct_allowed → launch direct (the user opted out of proxy).
|
|
18
|
+
* - Malformed proxy string → ABORT (treat as unreachable).
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* @param {object} opts
|
|
23
|
+
* @param {string|null|undefined} opts.proxyStr - raw proxy string (host:port[:user:pass]) or empty
|
|
24
|
+
* @param {string} [opts.networkMode] - 'proxy_required' | 'direct_allowed'. REQUIRED — a
|
|
25
|
+
* missing/unknown mode FAILS CLOSED (abort); the agent never coerces an
|
|
26
|
+
* unknown mode to 'direct_allowed' (that would leak the real IP). The backend
|
|
27
|
+
* persists an explicit mode per account (default 'proxy_required').
|
|
28
|
+
* @param {{ok:boolean, reason?:string}|null|undefined} opts.health - checkProxyHealth result
|
|
29
|
+
* (null/undefined when no proxy was configured or it could not be parsed)
|
|
30
|
+
* @returns {{action:'launch'|'abort', useProxy:boolean, reason:string, error?:string}}
|
|
31
|
+
*/
|
|
32
|
+
function decideProxyLaunch({ proxyStr, networkMode, health } = {}) {
|
|
33
|
+
// Phase 16: a missing/unknown network mode FAILS CLOSED. The agent never
|
|
34
|
+
// coerces an unknown mode to 'direct_allowed' — the safe default is to refuse
|
|
35
|
+
// the launch rather than risk a direct (real-IP) connection. The backend
|
|
36
|
+
// persists an explicit mode per account, so receiving none/unknown here is a
|
|
37
|
+
// contract violation, not a backward-compatible default.
|
|
38
|
+
const mode = networkMode === 'proxy_required' ? 'proxy_required'
|
|
39
|
+
: networkMode === 'direct_allowed' ? 'direct_allowed'
|
|
40
|
+
: null;
|
|
41
|
+
if (mode === null) {
|
|
42
|
+
return {
|
|
43
|
+
action: 'abort',
|
|
44
|
+
useProxy: false,
|
|
45
|
+
reason: 'network_mode_required',
|
|
46
|
+
error: 'Account network mode is missing or unknown; refusing to launch without an explicit proxy policy.',
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
const hasProxy = !!(proxyStr && String(proxyStr).trim());
|
|
50
|
+
|
|
51
|
+
if (hasProxy) {
|
|
52
|
+
// A proxy was configured — it must be reachable or we abort. Never fall
|
|
53
|
+
// open to direct.
|
|
54
|
+
if (!health || !health.ok) {
|
|
55
|
+
return {
|
|
56
|
+
action: 'abort',
|
|
57
|
+
useProxy: true,
|
|
58
|
+
reason: 'proxy_unreachable',
|
|
59
|
+
error: 'Proxy is not reachable. Check the proxy credentials/host or try again.',
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
return { action: 'launch', useProxy: true, reason: 'proxy_ok' };
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// No proxy configured.
|
|
66
|
+
if (mode === 'proxy_required') {
|
|
67
|
+
return {
|
|
68
|
+
action: 'abort',
|
|
69
|
+
useProxy: false,
|
|
70
|
+
reason: 'proxy_required_missing',
|
|
71
|
+
error: 'A proxy is required for this account but none is configured. Assign a proxy before launching.',
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
return { action: 'launch', useProxy: false, reason: 'direct_allowed' };
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
module.exports = { decideProxyLaunch };
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Protect a plaintext secret at rest (Phase 11).
|
|
5
|
+
*
|
|
6
|
+
* The local agent persists its long-lived device credential (a 365-day JWT) to
|
|
7
|
+
* config.json on the customer's PC. Storing it in plaintext means anyone who
|
|
8
|
+
* can read that file (a malicious process running as the same or a more
|
|
9
|
+
* privileged user, a copied disk image, a backup) can impersonate the device
|
|
10
|
+
* for a year. protectSecret wraps it so the on-disk form is not directly usable.
|
|
11
|
+
*
|
|
12
|
+
* On Windows, the agent uses DPAPI (CryptProtectData, current-user scope) via
|
|
13
|
+
* PowerShell — no native dependency to build or ship, and the protected blob is
|
|
14
|
+
* decryptable only by the same Windows user account on the same machine. On
|
|
15
|
+
* non-Windows (development / CI), DPAPI is unavailable, so we fall back to a
|
|
16
|
+
* plaintext envelope with a warning. The plaintext fallback is gated: it is
|
|
17
|
+
* only used when DPAPI cannot be reached, and it is clearly marked in the
|
|
18
|
+
* envelope so callers can refuse/warn. Production deployments run on Windows.
|
|
19
|
+
*
|
|
20
|
+
* Envelope shape: { scheme: 'dpapi' | 'plaintext', value: <string>, v: 1 }
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
const { execFileSync } = require('child_process');
|
|
24
|
+
const os = require('os');
|
|
25
|
+
const path = require('path');
|
|
26
|
+
|
|
27
|
+
const isWindows = os.platform() === 'win32';
|
|
28
|
+
const PS_TIMEOUT_MS = 15000;
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Absolute path to Windows PowerShell 5.1 — never bare `powershell`/`pwsh`.
|
|
32
|
+
* Mirrors deviceKeyStore._powershellExe() so DPAPI behaves identically.
|
|
33
|
+
*/
|
|
34
|
+
function _powershellExe() {
|
|
35
|
+
if (!isWindows) return 'powershell.exe';
|
|
36
|
+
const root = process.env.SystemRoot || process.env.WINDIR || 'C:\\Windows';
|
|
37
|
+
return path.join(root, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Protect `plaintext` with DPAPI (current-user scope) via the .NET ProtectedData
|
|
42
|
+
* API through PowerShell. Returns the protected blob as a base64 string. Throws
|
|
43
|
+
* if PowerShell / the System.Security assembly is unavailable — callers catch
|
|
44
|
+
* and fall back. We use ProtectedData directly (rather than ConvertTo/From-
|
|
45
|
+
* SecureString) because the SecureString cmdlets live in Microsoft.PowerShell.
|
|
46
|
+
* Security, whose auto-load is unreliable under -NoProfile on some installs.
|
|
47
|
+
*/
|
|
48
|
+
function dpApiProtect(plaintext) {
|
|
49
|
+
// Base64-encode the secret so it can be embedded in the PowerShell command
|
|
50
|
+
// without quoting/escaping issues.
|
|
51
|
+
const b64 = Buffer.from(plaintext, 'utf8').toString('base64');
|
|
52
|
+
const ps =
|
|
53
|
+
"[Console]::OutputEncoding = [System.Text.Encoding]::ASCII; " +
|
|
54
|
+
"Add-Type -AssemblyName System.Security; " +
|
|
55
|
+
"$b = [System.Security.Cryptography.ProtectedData]::Protect(" +
|
|
56
|
+
"[Convert]::FromBase64String('" + b64 + "'), " +
|
|
57
|
+
"$null, [System.Security.Cryptography.DataProtectionScope]::CurrentUser); " +
|
|
58
|
+
"[Console]::Out.Write([Convert]::ToBase64String($b))";
|
|
59
|
+
return execFileSync(_powershellExe(), ['-NoProfile', '-NonInteractive', '-Command', ps], {
|
|
60
|
+
windowsHide: true,
|
|
61
|
+
encoding: 'utf8',
|
|
62
|
+
timeout: PS_TIMEOUT_MS,
|
|
63
|
+
}).trim();
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Reverse dpApiProtect. `blob` is the base64 string returned by dpApiProtect.
|
|
68
|
+
* Returns the plaintext. Throws on any failure.
|
|
69
|
+
*/
|
|
70
|
+
function dpApiUnprotect(blob) {
|
|
71
|
+
const ps =
|
|
72
|
+
"[Console]::OutputEncoding = [System.Text.Encoding]::ASCII; " +
|
|
73
|
+
"Add-Type -AssemblyName System.Security; " +
|
|
74
|
+
"$b = [Convert]::FromBase64String('" + String(blob) + "'); " +
|
|
75
|
+
"$p = [System.Security.Cryptography.ProtectedData]::Unprotect(" +
|
|
76
|
+
"$b, $null, [System.Security.Cryptography.DataProtectionScope]::CurrentUser); " +
|
|
77
|
+
"[Console]::Out.Write([System.Text.Encoding]::UTF8.GetString($p))";
|
|
78
|
+
return execFileSync(_powershellExe(), ['-NoProfile', '-NonInteractive', '-Command', ps], {
|
|
79
|
+
windowsHide: true,
|
|
80
|
+
encoding: 'utf8',
|
|
81
|
+
timeout: PS_TIMEOUT_MS,
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Wrap a plaintext secret for at-rest storage. Returns an envelope. Always
|
|
87
|
+
* resolves (never throws): DPAPI failure falls back to a plaintext envelope.
|
|
88
|
+
*/
|
|
89
|
+
function protectSecret(plaintext) {
|
|
90
|
+
if (plaintext == null) return null;
|
|
91
|
+
if (isWindows) {
|
|
92
|
+
try {
|
|
93
|
+
return { scheme: 'dpapi', value: dpApiProtect(plaintext), v: 1 };
|
|
94
|
+
} catch (err) {
|
|
95
|
+
console.warn('[secretStore] DPAPI protection failed; falling back to plaintext: ' + (err && err.message));
|
|
96
|
+
}
|
|
97
|
+
} else if (typeof console !== 'undefined' && console.warn) {
|
|
98
|
+
// Non-Windows: DPAPI is not available. Plaintext fallback is intentional for
|
|
99
|
+
// dev/CI; production agents run on Windows where DPAPI is used.
|
|
100
|
+
console.warn('[secretStore] non-Windows host: device token stored as plaintext (no DPAPI).');
|
|
101
|
+
}
|
|
102
|
+
return { scheme: 'plaintext', value: plaintext, v: 1 };
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Unwrap an envelope (or a legacy plaintext string) back to plaintext. Returns
|
|
107
|
+
* null for a missing/unknown envelope (fail closed — never return an empty
|
|
108
|
+
* secret that could mask a missing one).
|
|
109
|
+
*/
|
|
110
|
+
function unprotectSecret(envelope) {
|
|
111
|
+
if (envelope == null) return null;
|
|
112
|
+
// Legacy pre-Phase-11 config stored the raw plaintext token string.
|
|
113
|
+
if (typeof envelope === 'string') return envelope;
|
|
114
|
+
if (typeof envelope !== 'object') return null;
|
|
115
|
+
if (envelope.scheme === 'plaintext') return envelope.value != null ? String(envelope.value) : null;
|
|
116
|
+
if (envelope.scheme === 'dpapi') {
|
|
117
|
+
try { return dpApiUnprotect(envelope.value); }
|
|
118
|
+
catch (err) {
|
|
119
|
+
console.error('[secretStore] DPAPI unprotect failed: ' + (err && err.message));
|
|
120
|
+
return null;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
// Unknown scheme — fail closed.
|
|
124
|
+
return null;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
module.exports = {
|
|
128
|
+
protectSecret,
|
|
129
|
+
unprotectSecret,
|
|
130
|
+
// Exposed for testing on Windows only (no-op guard on non-Windows).
|
|
131
|
+
_dpApiAvailable: isWindows,
|
|
132
|
+
_powershellExe,
|
|
133
|
+
};
|