@xkwdstore/agent 2.0.6 → 2.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +37 -11
- package/package.json +11 -2
- package/scripts/install-machine-agent.ps1 +351 -0
- package/scripts/worker-entry.js +53 -0
- package/src/actions/comment.js +153 -154
- package/src/actions/confirmation.js +129 -0
- package/src/actions/follow.js +179 -123
- package/src/actions/tweet.js +107 -107
- package/src/brokerWorkerBridge.js +352 -0
- package/src/browserIsolation.js +691 -0
- package/src/cli.js +490 -123
- package/src/deviceKeyStore.js +446 -71
- package/src/legacyStartup.js +195 -0
- package/src/machineLock.js +202 -0
- package/src/machineState.js +354 -0
- package/src/processLock.js +15 -2
- package/src/proxyEgress.js +28 -4
- package/src/sessionHandler.js +560 -33
- package/src/sessionRegistry.js +280 -0
- package/src/worker.js +253 -0
|
@@ -0,0 +1,691 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Browser isolation + privacy/fingerprint consistency hardening (2.1.0).
|
|
5
|
+
*
|
|
6
|
+
* STRICT PER-ACCOUNT BROWSER ISOLATION
|
|
7
|
+
* ------------------------------------
|
|
8
|
+
* This module owns the browser-side isolation invariants so they can be unit
|
|
9
|
+
* tested WITHOUT launching Chromium. It answers four questions deterministically:
|
|
10
|
+
*
|
|
11
|
+
* 1. WHICH flags may a production launch pass? (sanitizeLaunchArgs)
|
|
12
|
+
* A production session must never carry a security-weakening flag
|
|
13
|
+
* (`--no-sandbox`, `--disable-web-security`, `--ignore-certificate-errors`,
|
|
14
|
+
* `--disable-site-isolation-trials`, …). Any such flag is REJECTED, not
|
|
15
|
+
* silently dropped, so a regression is loud. Args are also de-duplicated
|
|
16
|
+
* last-wins so a second `--proxy-server=` cannot smuggle a different
|
|
17
|
+
* proxy into an account already bound to one.
|
|
18
|
+
*
|
|
19
|
+
* 2. WHAT isolated runtime paths does a session own? (sessionRuntimeDir)
|
|
20
|
+
* Every running session gets its OWN temp/downloads/crash/runtime tree:
|
|
21
|
+
* <machine>/state/sessions/<sessionKey>/{tmp,downloads,crash,ipc}
|
|
22
|
+
* so no account can read another account's download, temp file, or crash
|
|
23
|
+
* artifact. Session-scoped Chromium prefs point at these paths.
|
|
24
|
+
*
|
|
25
|
+
* 3. IS the session's proxy identity its own? (proxyIdentity, buildProxyOptions)
|
|
26
|
+
* The effective proxy is derived PER SESSION from that session's options
|
|
27
|
+
* only. A proxy identity hash (host+port+scheme+user, never the password)
|
|
28
|
+
* is recorded on the session for registry/diagnostics. Credentials may be
|
|
29
|
+
* delivered to Chromium WITHOUT putting them on the command line.
|
|
30
|
+
*
|
|
31
|
+
* 4. IS the browser state internally coherent? (buildConsistencyPolicy)
|
|
32
|
+
* timezone / locale / Accept-Language / UA / Client-Hints / platform are
|
|
33
|
+
* derived from ONE fingerprint so impossible combinations (Windows UA +
|
|
34
|
+
* macOS platform; Riyadh timezone + en-US-only languages) cannot occur.
|
|
35
|
+
* Stability beats randomness: no per-launch re-randomization.
|
|
36
|
+
*
|
|
37
|
+
* LEAK PREVENTION (proxy-required accounts)
|
|
38
|
+
* ----------------------------------------
|
|
39
|
+
* - WebRTC: `--force-webrtc-ip-handling-policy=disable_non_proxied_udp`
|
|
40
|
+
* (a supported Chromium control; NOT fingerprint deception).
|
|
41
|
+
* - QUIC/HTTP3: `--disable-quic` when the account REQUIRES a proxy, because a
|
|
42
|
+
* UDP/HTTP3 path is not guaranteed to follow an HTTP CONNECT proxy.
|
|
43
|
+
* - DNS: `--host-resolver-rules` maps resolution through the proxy for the
|
|
44
|
+
* proxy-requiring launch; SOCKS/HTTP-CONNECT remote-DNS limits are
|
|
45
|
+
* documented in docs/MACHINE-AGENT-2.1.0.md.
|
|
46
|
+
*
|
|
47
|
+
* This module adds NO anti-detection bypass. It removes deception, not adds it.
|
|
48
|
+
*/
|
|
49
|
+
|
|
50
|
+
const crypto = require('crypto');
|
|
51
|
+
const fs = require('fs');
|
|
52
|
+
const path = require('path');
|
|
53
|
+
|
|
54
|
+
// ── 1. Launch-argument security ──────────────────────────────────────────────
|
|
55
|
+
|
|
56
|
+
/** Flags that must NEVER appear in a production launch (fail closed). */
|
|
57
|
+
const FORBIDDEN_LAUNCH_ARG_PREFIXES = Object.freeze([
|
|
58
|
+
'--no-sandbox',
|
|
59
|
+
'--disable-web-security',
|
|
60
|
+
'--disable-site-isolation-trials',
|
|
61
|
+
'--ignore-certificate-errors',
|
|
62
|
+
'--ignore-certificate-errors-spki-list',
|
|
63
|
+
'--allow-running-insecure-content',
|
|
64
|
+
'--disable-features=IsolateOrigins',
|
|
65
|
+
'--disable-features=SitePerProcess',
|
|
66
|
+
'--single-process',
|
|
67
|
+
'--no-zygote',
|
|
68
|
+
'--disable-gpu-sandbox',
|
|
69
|
+
'--disable-setuid-sandbox',
|
|
70
|
+
'--unsafely-treat-insecure-origin-as-secure',
|
|
71
|
+
]);
|
|
72
|
+
|
|
73
|
+
/** Chromium switches that accept a value and are LAST-WINS; a duplicate is a
|
|
74
|
+
* proxy/identity smuggle vector, so callers must never pass two. */
|
|
75
|
+
const UNIQUE_VALUE_SWITCHES = Object.freeze([
|
|
76
|
+
'--proxy-server',
|
|
77
|
+
'--proxy-bypass-list',
|
|
78
|
+
'--host-resolver-rules',
|
|
79
|
+
'--user-data-dir',
|
|
80
|
+
'--remote-debugging-port',
|
|
81
|
+
'--remote-debugging-address',
|
|
82
|
+
'--window-size',
|
|
83
|
+
]);
|
|
84
|
+
|
|
85
|
+
class BrowserIsolationError extends Error {
|
|
86
|
+
constructor(message, code) {
|
|
87
|
+
super(message);
|
|
88
|
+
this.code = code || 'BROWSER_ISOLATION_ERROR';
|
|
89
|
+
this.name = 'BrowserIsolationError';
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Validate + normalize a launch-argument list.
|
|
95
|
+
*
|
|
96
|
+
* @param {string[]} args
|
|
97
|
+
* @param {object} [opts]
|
|
98
|
+
* @param {boolean} [opts.enforce=true] — throw on a forbidden flag (default).
|
|
99
|
+
* Tests may pass `enforce:false` only to observe a sanitized list; production
|
|
100
|
+
* must never.
|
|
101
|
+
* @param {boolean} [opts.production=false] — when true, a forbidden flag throws
|
|
102
|
+
* even if `enforce` was weakened.
|
|
103
|
+
* @returns {string[]} the sanitized args (forbidden flags removed only when
|
|
104
|
+
* enforce is false; otherwise the function threw)
|
|
105
|
+
* @throws {BrowserIsolationError} on any forbidden flag.
|
|
106
|
+
*/
|
|
107
|
+
function sanitizeLaunchArgs(args, opts = {}) {
|
|
108
|
+
const enforce = opts.enforce !== false || opts.production === true;
|
|
109
|
+
const list = Array.isArray(args) ? args.slice() : [];
|
|
110
|
+
const forbidden = [];
|
|
111
|
+
for (const arg of list) {
|
|
112
|
+
const a = String(arg);
|
|
113
|
+
for (const bad of FORBIDDEN_LAUNCH_ARG_PREFIXES) {
|
|
114
|
+
if (a === bad || a.startsWith(bad + '=')) { forbidden.push(a); break; }
|
|
115
|
+
}
|
|
116
|
+
// A `--disable-features` that disables isolation must also be caught when
|
|
117
|
+
// bundled: --disable-features=Foo,IsolateOrigins,SitePerProcess.
|
|
118
|
+
const df = /^--disable-features=(.+)$/.exec(a);
|
|
119
|
+
if (df) {
|
|
120
|
+
const feats = df[1].split(',').map((s) => s.trim()).filter(Boolean);
|
|
121
|
+
if (feats.some((f) => /^(IsolateOrigins|SitePerProcess|IsolateSandboxedIframes)$/i.test(f))) {
|
|
122
|
+
forbidden.push(a);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
if (forbidden.length > 0) {
|
|
127
|
+
if (enforce) {
|
|
128
|
+
throw new BrowserIsolationError(
|
|
129
|
+
'refusing to launch with a security-weakening Chromium flag: ' + forbidden.join(', '),
|
|
130
|
+
'LAUNCH_FLAG_FORBIDDEN',
|
|
131
|
+
);
|
|
132
|
+
}
|
|
133
|
+
// Non-enforcing mode (tests only): strip them and continue.
|
|
134
|
+
return list.filter((a) => !forbidden.includes(String(a)));
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
// De-duplicate last-wins value switches: keep the LAST occurrence of each.
|
|
138
|
+
const seen = new Set();
|
|
139
|
+
const out = [];
|
|
140
|
+
for (let i = list.length - 1; i >= 0; i--) {
|
|
141
|
+
const a = String(list[i]);
|
|
142
|
+
const sw = UNIQUE_VALUE_SWITCHES.find((s) => a === s || a.startsWith(s + '='));
|
|
143
|
+
if (sw) {
|
|
144
|
+
if (seen.has(sw)) continue;
|
|
145
|
+
seen.add(sw);
|
|
146
|
+
}
|
|
147
|
+
out.push(list[i]);
|
|
148
|
+
}
|
|
149
|
+
return out.reverse();
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** True when a proxy path is REQUIRED for this session (fail-closed default). */
|
|
153
|
+
function proxyRequiredForSession({ proxyStr, networkMode } = {}) {
|
|
154
|
+
const hasProxy = !!(proxyStr && String(proxyStr).trim());
|
|
155
|
+
// direct_allowed + no proxy is the ONLY combination that may run direct.
|
|
156
|
+
if (networkMode === 'direct_allowed' && !hasProxy) return false;
|
|
157
|
+
// Everything else — proxy_required, a missing/unknown mode (fail closed), or
|
|
158
|
+
// any configured proxy — means traffic must not escape directly.
|
|
159
|
+
return true;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* Build the network-leak-prevention args for one session.
|
|
164
|
+
*
|
|
165
|
+
* @param {object} opts
|
|
166
|
+
* @param {boolean} opts.requireProxy — account requires a proxy
|
|
167
|
+
* @param {string|null} [opts.proxyServerUrl] — e.g. http://host:port (no creds).
|
|
168
|
+
* When present a `--proxy-server` switch is emitted (used for the no-credential
|
|
169
|
+
* / direct-binding path).
|
|
170
|
+
* @param {string|null} [opts.proxyHostForDns] — the proxy HOST to exclude from
|
|
171
|
+
* the DNS pin. Supplied even when the server is passed out-of-band via the
|
|
172
|
+
* Playwright proxy option, so the DNS pin is always present for a proxied
|
|
173
|
+
* session.
|
|
174
|
+
* @param {string[]} [opts.baseArgs]
|
|
175
|
+
* @returns {string[]} the full sanitized arg list
|
|
176
|
+
*/
|
|
177
|
+
function buildLaunchArgs({ requireProxy, proxyServerUrl, proxyHostForDns, baseArgs } = {}) {
|
|
178
|
+
const args = Array.isArray(baseArgs) ? baseArgs.slice() : [
|
|
179
|
+
'--force-webrtc-ip-handling-policy=disable_non_proxied_udp',
|
|
180
|
+
'--no-first-run',
|
|
181
|
+
'--no-default-browser-check',
|
|
182
|
+
'--start-maximized',
|
|
183
|
+
];
|
|
184
|
+
|
|
185
|
+
// A proxy-required session keeps host/QUIC/WebRTC from escaping the proxy.
|
|
186
|
+
if (requireProxy) {
|
|
187
|
+
if (proxyServerUrl) {
|
|
188
|
+
args.push(`--proxy-server=${proxyServerUrl}`);
|
|
189
|
+
}
|
|
190
|
+
// Pin DNS to the proxy so a proxied account cannot leak the queried host via
|
|
191
|
+
// the OS resolver (HTTP/HTTPS CONNECT / SOCKS remote resolution). This is
|
|
192
|
+
// emitted whenever a proxy host is known, even when the credential-bearing
|
|
193
|
+
// server is passed through the Playwright proxy OPTION.
|
|
194
|
+
const dnsHost = proxyHostForDns || (proxyServerUrl ? _hostOnly(proxyServerUrl) : null);
|
|
195
|
+
if (dnsHost) {
|
|
196
|
+
args.push('--host-resolver-rules=MAP * ~NOTFOUND , EXCLUDE ' + dnsHost);
|
|
197
|
+
}
|
|
198
|
+
// A UDP/HTTP3 path is NOT guaranteed to follow an HTTP CONNECT proxy, so
|
|
199
|
+
// QUIC is disabled per-launch for a proxy-required session.
|
|
200
|
+
args.push('--disable-quic');
|
|
201
|
+
args.push('--force-webrtc-ip-handling-policy=disable_non_proxied_udp');
|
|
202
|
+
}
|
|
203
|
+
return sanitizeLaunchArgs(args, { enforce: true });
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
function _hostOnly(proxyServerUrl) {
|
|
207
|
+
try {
|
|
208
|
+
const u = new URL(proxyServerUrl);
|
|
209
|
+
return u.hostname;
|
|
210
|
+
} catch {
|
|
211
|
+
return proxyServerUrl;
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
// ── 2. Per-session runtime isolation ─────────────────────────────────────────
|
|
216
|
+
|
|
217
|
+
/** The four runtime paths a session owns exclusively. */
|
|
218
|
+
function sessionRuntimeDirs(sessionsRoot, sessionKey) {
|
|
219
|
+
const base = path.join(sessionsRoot, String(sessionKey));
|
|
220
|
+
return {
|
|
221
|
+
base,
|
|
222
|
+
tmp: path.join(base, 'tmp'),
|
|
223
|
+
downloads: path.join(base, 'downloads'),
|
|
224
|
+
crash: path.join(base, 'crash'),
|
|
225
|
+
ipc: path.join(base, 'ipc'),
|
|
226
|
+
};
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/**
|
|
230
|
+
* Create the per-session runtime tree. Fail-closed: a session that cannot get
|
|
231
|
+
* its own isolated runtime paths must not launch (it would fall back to shared
|
|
232
|
+
* OS temp paths and cross-contaminate).
|
|
233
|
+
*
|
|
234
|
+
* @returns {{base,tmp,downloads,crash,ipc}} created paths
|
|
235
|
+
*/
|
|
236
|
+
function createSessionRuntimeDirs(sessionsRoot, sessionKey) {
|
|
237
|
+
const dirs = sessionRuntimeDirs(sessionsRoot, sessionKey);
|
|
238
|
+
for (const d of [dirs.base, dirs.tmp, dirs.downloads, dirs.crash, dirs.ipc]) {
|
|
239
|
+
try {
|
|
240
|
+
fs.mkdirSync(d, { recursive: true, mode: 0o700 });
|
|
241
|
+
} catch (e) {
|
|
242
|
+
throw new BrowserIsolationError(
|
|
243
|
+
'could not create the isolated session runtime dir ' + d + ': ' + ((e && e.message) || 'unknown'),
|
|
244
|
+
'SESSION_RUNTIME_DIR_FAILED',
|
|
245
|
+
);
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
return dirs;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/** Remove a session runtime tree (best-effort; never throws). */
|
|
252
|
+
function cleanupSessionRuntimeDirs(sessionsRoot, sessionKey) {
|
|
253
|
+
const dirs = sessionRuntimeDirs(sessionsRoot, sessionKey);
|
|
254
|
+
try { fs.rmSync(dirs.base, { recursive: true, force: true }); return true; } catch { return false; }
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/**
|
|
258
|
+
* The Chromium prefs that point the browser at the session's OWN runtime dirs,
|
|
259
|
+
* plus the privacy/consistency prefs that remove personal-data leakage.
|
|
260
|
+
*
|
|
261
|
+
* These are applied as a per-profile preference file (Default/Preferences) or
|
|
262
|
+
* via Playwright launch args; the browser sees a self-contained profile that
|
|
263
|
+
* does not consult the host user's Chrome data.
|
|
264
|
+
*/
|
|
265
|
+
function buildSessionPreferences(runtimeDirs) {
|
|
266
|
+
const prefs = {
|
|
267
|
+
// ── C3: no personal-data integration, no sync, no autofill leakage ──
|
|
268
|
+
sync: { requested: false },
|
|
269
|
+
signin: { allowed: false, allowed_on_next_startup: false },
|
|
270
|
+
browser: {
|
|
271
|
+
// Never prompt to save passwords; never autofill the host user's data.
|
|
272
|
+
enable_spellchecking: false,
|
|
273
|
+
// Download into the SESSION dir, not the host user's Downloads.
|
|
274
|
+
download: runtimeDirs ? { default_directory: runtimeDirs.downloads, prompt_for_download: false } : {},
|
|
275
|
+
// Disable the password manager surfaces.
|
|
276
|
+
clear_data: {},
|
|
277
|
+
},
|
|
278
|
+
credentials_enable_service: false,
|
|
279
|
+
credentials_enable_autosignin: false,
|
|
280
|
+
autofill: { credit_card_enabled: false, profile_enabled: false },
|
|
281
|
+
profile: {
|
|
282
|
+
password_manager_enabled: false,
|
|
283
|
+
// Keep crash reports inside the session dir when they occur.
|
|
284
|
+
exit_type: 'Normal',
|
|
285
|
+
},
|
|
286
|
+
// Sync / Google account integration is off.
|
|
287
|
+
account_tracker_service_last_update: '0',
|
|
288
|
+
// Do not expose the host's recent tabs / session restore.
|
|
289
|
+
session: { restore_on_startup: 0 },
|
|
290
|
+
// Privacy: no network prediction (prefetch) leaking unintended requests.
|
|
291
|
+
network_prediction_options: 0,
|
|
292
|
+
// Downloads must not escape the generic OS Downloads folder.
|
|
293
|
+
download: runtimeDirs ? {
|
|
294
|
+
default_directory: runtimeDirs.downloads,
|
|
295
|
+
prompt_for_download: false,
|
|
296
|
+
directory_upgrade: true,
|
|
297
|
+
} : {},
|
|
298
|
+
};
|
|
299
|
+
return prefs;
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
// ── 3. Proxy identity (per session, never global) ────────────────────────────
|
|
303
|
+
|
|
304
|
+
/**
|
|
305
|
+
* Parse a raw proxy string ("host:port[:user:pass]") OR a Playwright-shaped
|
|
306
|
+
* proxy object into a normalized, validated proxy descriptor.
|
|
307
|
+
*
|
|
308
|
+
* @returns {{type:'http'|'https'|'socks5',host:string,port:number,username?:string,password?:string,server:string}|null}
|
|
309
|
+
*/
|
|
310
|
+
function parseProxyIdentity(proxyStr) {
|
|
311
|
+
if (!proxyStr) return null;
|
|
312
|
+
if (typeof proxyStr === 'object' && proxyStr.server) {
|
|
313
|
+
let u;
|
|
314
|
+
try { u = new URL(proxyStr.server); } catch { return null; }
|
|
315
|
+
const type = _schemeToType(u.protocol);
|
|
316
|
+
if (!type) return null;
|
|
317
|
+
const port = parseInt(u.port, 10) || (type === 'http' ? 80 : 1080);
|
|
318
|
+
if (!_validPort(port)) return null;
|
|
319
|
+
return {
|
|
320
|
+
type,
|
|
321
|
+
host: u.hostname,
|
|
322
|
+
port,
|
|
323
|
+
username: proxyStr.username || undefined,
|
|
324
|
+
password: proxyStr.password || undefined,
|
|
325
|
+
server: `${type}://${u.hostname}:${port}`,
|
|
326
|
+
};
|
|
327
|
+
}
|
|
328
|
+
if (typeof proxyStr !== 'string' || !proxyStr.trim()) return null;
|
|
329
|
+
|
|
330
|
+
const raw = proxyStr.trim();
|
|
331
|
+
// Accept an explicit scheme (socks5://host:port:user:pass) or bare host:port.
|
|
332
|
+
let scheme = 'http';
|
|
333
|
+
let body = raw;
|
|
334
|
+
const schemeMatch = /^(https?|socks5h?|socks4a?):\/\//i.exec(raw);
|
|
335
|
+
if (schemeMatch) {
|
|
336
|
+
scheme = schemeMatch[1].toLowerCase();
|
|
337
|
+
body = raw.slice(schemeMatch[0].length);
|
|
338
|
+
}
|
|
339
|
+
const parts = body.split(':');
|
|
340
|
+
if (parts.length < 2) return null;
|
|
341
|
+
|
|
342
|
+
// `userinfo@host:port` form (e.g. `user:pass@host:8080`). Split on the LAST
|
|
343
|
+
// '@' so a password containing '@' still works.
|
|
344
|
+
let userinfo = null;
|
|
345
|
+
const at = body.lastIndexOf('@');
|
|
346
|
+
if (at >= 0 && body.indexOf('@') === at) {
|
|
347
|
+
userinfo = body.slice(0, at);
|
|
348
|
+
body = body.slice(at + 1);
|
|
349
|
+
}
|
|
350
|
+
const host = body.split(':')[0];
|
|
351
|
+
const port = parseInt(body.split(':')[1], 10);
|
|
352
|
+
if (!host || !_validPort(port)) return null;
|
|
353
|
+
const type = _schemeToType(scheme + ':');
|
|
354
|
+
if (!type) return null;
|
|
355
|
+
|
|
356
|
+
let username;
|
|
357
|
+
let password;
|
|
358
|
+
if (userinfo !== null) {
|
|
359
|
+
const c = userinfo.indexOf(':');
|
|
360
|
+
if (c >= 0) { username = userinfo.slice(0, c); password = userinfo.slice(c + 1); }
|
|
361
|
+
else { username = userinfo; password = ''; }
|
|
362
|
+
} else {
|
|
363
|
+
const afterPort = body.split(':');
|
|
364
|
+
// Credentials may themselves contain ':' - re-join everything after the port.
|
|
365
|
+
if (afterPort.length >= 3 && afterPort[2] !== '') {
|
|
366
|
+
username = afterPort[2];
|
|
367
|
+
password = afterPort.length > 3 ? afterPort.slice(3).join(':') : '';
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
return { type, host, port, username, password, server: `${type}://${host}:${port}` };
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
function _schemeToType(protocolWithColon) {
|
|
374
|
+
const p = String(protocolWithColon || '').replace(':', '').toLowerCase();
|
|
375
|
+
if (p === 'http') return 'http';
|
|
376
|
+
if (p === 'https') return 'https';
|
|
377
|
+
if (p === 'socks5' || p === 'socks5h' || p === 'socks') return 'socks5';
|
|
378
|
+
return null;
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
function _validPort(port) {
|
|
382
|
+
return Number.isInteger(port) && port >= 1 && port <= 65535;
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
/**
|
|
386
|
+
* Validate a proxy descriptor fail-closed before Chromium is opened.
|
|
387
|
+
* @returns {{ok:true}|{ok:false,code:string,reason:string}}
|
|
388
|
+
*/
|
|
389
|
+
function validateProxyConfig(proxy) {
|
|
390
|
+
if (!proxy) return { ok: false, code: 'PROXY_MALFORMED', reason: 'proxy is missing or unparseable' };
|
|
391
|
+
if (!proxy.host || typeof proxy.host !== 'string') return { ok: false, code: 'PROXY_HOST_INVALID', reason: 'proxy host is missing' };
|
|
392
|
+
if (!_validPort(proxy.port)) return { ok: false, code: 'PROXY_PORT_INVALID', reason: 'proxy port is not a valid TCP port' };
|
|
393
|
+
if (!['http', 'https', 'socks5'].includes(proxy.type)) return { ok: false, code: 'PROXY_SCHEME_UNSUPPORTED', reason: 'unsupported proxy scheme' };
|
|
394
|
+
const hasUser = proxy.username !== undefined && proxy.username !== '';
|
|
395
|
+
const hasPass = proxy.password !== undefined && proxy.password !== '';
|
|
396
|
+
if (hasUser !== hasPass) {
|
|
397
|
+
return { ok: false, code: 'PROXY_CREDENTIAL_INCOMPLETE', reason: 'proxy credentials are incomplete (username and password must both be present)' };
|
|
398
|
+
}
|
|
399
|
+
return { ok: true };
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
/**
|
|
403
|
+
* Is `value` an at-rest AES-256-GCM envelope ({k,v,i,t}) rather than a usable
|
|
404
|
+
* proxy? An envelope reaching the worker means the SERVER dispatched an
|
|
405
|
+
* undecrypted secret — a server-side bug, not a malformed proxy. The two must be
|
|
406
|
+
* reported differently: "the proxy I was given is unusable" sends the operator
|
|
407
|
+
* hunting for a bad proxy, while "the server sent me an encrypted value" points
|
|
408
|
+
* at the actual defect.
|
|
409
|
+
*/
|
|
410
|
+
function looksLikeEncryptedEnvelope(value) {
|
|
411
|
+
return !!value && typeof value === 'object' && !Array.isArray(value) &&
|
|
412
|
+
typeof value.k === 'string' && typeof value.v === 'string' &&
|
|
413
|
+
typeof value.i === 'string' && typeof value.t === 'string' && !value.server;
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
/**
|
|
417
|
+
* Normalize whatever the broker hands the worker into a proxy identity, and
|
|
418
|
+
* classify any failure precisely. Accepts a raw connection string or an
|
|
419
|
+
* already-parsed identity object; returns a typed reason for anything else so
|
|
420
|
+
* the caller never has to emit an opaque "binding failed".
|
|
421
|
+
*
|
|
422
|
+
* @returns {{ok:true, identity:object}|{ok:false, code:string, detail:string}}
|
|
423
|
+
*/
|
|
424
|
+
function coerceProxyIdentity(value) {
|
|
425
|
+
if (value === null || value === undefined || value === '') {
|
|
426
|
+
return { ok: false, code: 'PROXY_ABSENT', detail: 'no proxy was provided' };
|
|
427
|
+
}
|
|
428
|
+
if (looksLikeEncryptedEnvelope(value)) {
|
|
429
|
+
return { ok: false, code: 'PROXY_PAYLOAD_ENCRYPTED', detail: 'the server sent an encrypted proxy envelope instead of a resolved proxy' };
|
|
430
|
+
}
|
|
431
|
+
if (typeof value !== 'string' && typeof value !== 'object') {
|
|
432
|
+
return { ok: false, code: 'PROXY_PAYLOAD_UNPARSEABLE', detail: 'proxy was neither a connection string nor a proxy object' };
|
|
433
|
+
}
|
|
434
|
+
const identity = parseProxyIdentity(value);
|
|
435
|
+
if (!identity) {
|
|
436
|
+
return { ok: false, code: 'PROXY_FORMAT_INVALID', detail: 'proxy could not be parsed into a host/port/scheme' };
|
|
437
|
+
}
|
|
438
|
+
const v = validateProxyConfig(identity);
|
|
439
|
+
if (!v.ok) return { ok: false, code: v.code, detail: v.reason };
|
|
440
|
+
return { ok: true, identity };
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
/** Credential-free description of a proxy for logs/errors: `scheme://host:port`. */
|
|
444
|
+
function maskProxyForLog(proxy) {
|
|
445
|
+
if (!proxy || !proxy.host) return '(none)';
|
|
446
|
+
return `${proxy.type || 'http'}://${proxy.host}:${proxy.port}`;
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
/**
|
|
450
|
+
* A STABLE, non-secret identity fingerprint for a proxy: host+port+scheme+user.
|
|
451
|
+
* The password is NEVER included. Used for the session registry so an operator
|
|
452
|
+
* can prove two concurrent sessions do not share a proxy without ever seeing a
|
|
453
|
+
* credential.
|
|
454
|
+
*/
|
|
455
|
+
function proxyIdentityFingerprint(proxy) {
|
|
456
|
+
if (!proxy) return null;
|
|
457
|
+
const material = [proxy.type, proxy.host, String(proxy.port), proxy.username || ''].join('|');
|
|
458
|
+
return crypto.createHash('sha256').update(material).digest('hex').slice(0, 16);
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
/**
|
|
462
|
+
* Build Chromium launch args that bind ONE session to ONE proxy WITHOUT putting
|
|
463
|
+
* the credential on the command line.
|
|
464
|
+
*
|
|
465
|
+
* Credential delivery (ordered by preference — D3):
|
|
466
|
+
* 1. `credentials` — Playwright's own authenticated-proxy path (username/
|
|
467
|
+
* password on the proxy option, never in argv);
|
|
468
|
+
* 2. `inline` — encoded into `--proxy-server=http://user:pass@host:port`
|
|
469
|
+
* (only for dev/test where the Playwright path is unavailable). The
|
|
470
|
+
* caller is told, so it can refuse `inline` in production.
|
|
471
|
+
*
|
|
472
|
+
* @returns {{ok:boolean,code?:string,args:string[],proxyOption:object|null,credentialMode:'playwright'|'inline'|'none'}}
|
|
473
|
+
*/
|
|
474
|
+
function buildProxyLaunchBinding(proxy, opts = {}) {
|
|
475
|
+
const check = validateProxyConfig(proxy);
|
|
476
|
+
if (!check.ok) {
|
|
477
|
+
return { ok: false, code: check.code, args: [], proxyOption: null, credentialMode: 'none' };
|
|
478
|
+
}
|
|
479
|
+
const hasCreds = proxy.username !== undefined && proxy.username !== '';
|
|
480
|
+
const proxyOption = { server: proxy.server };
|
|
481
|
+
const args = [];
|
|
482
|
+
|
|
483
|
+
let credentialMode = 'none';
|
|
484
|
+
if (hasCreds) {
|
|
485
|
+
if (opts.allowInlineCredentials === true) {
|
|
486
|
+
// Explicit dev/test opt-in: inline credentials (visible in argv — never
|
|
487
|
+
// used in production; callers must pass this deliberately).
|
|
488
|
+
const auth = `${encodeURIComponent(proxy.username)}:${encodeURIComponent(proxy.password || '')}@`;
|
|
489
|
+
args.push(`--proxy-server=${proxy.type}://${auth}${proxy.host}:${proxy.port}`);
|
|
490
|
+
credentialMode = 'inline';
|
|
491
|
+
} else {
|
|
492
|
+
// DEFAULT (production): credentials go through Playwright's authenticated-
|
|
493
|
+
// proxy path and never appear in argv. This is the secure default — a
|
|
494
|
+
// caller must opt IN to the visible-argv fallback.
|
|
495
|
+
proxyOption.username = proxy.username;
|
|
496
|
+
proxyOption.password = proxy.password;
|
|
497
|
+
credentialMode = 'playwright';
|
|
498
|
+
}
|
|
499
|
+
} else {
|
|
500
|
+
args.push(`--proxy-server=${proxy.server}`);
|
|
501
|
+
}
|
|
502
|
+
return { ok: true, args: sanitizeLaunchArgs(args, { enforce: true }), proxyOption, credentialMode };
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
// ── 4. Privacy / fingerprint consistency ─────────────────────────────────────
|
|
506
|
+
|
|
507
|
+
/**
|
|
508
|
+
* Language list for a locale, ordered for an Accept-Language header that is
|
|
509
|
+
* COHERENT with the locale (no "ar timezone + en-US-only languages").
|
|
510
|
+
*/
|
|
511
|
+
const LOCALE_LANGUAGE_POOL = Object.freeze({
|
|
512
|
+
'en-US': ['en-US', 'en'],
|
|
513
|
+
'en-GB': ['en-GB', 'en'],
|
|
514
|
+
'ar-SA': ['ar-SA', 'ar', 'en-US', 'en'],
|
|
515
|
+
ar: ['ar', 'en-US', 'en'],
|
|
516
|
+
'fr-FR': ['fr-FR', 'fr', 'en-US', 'en'],
|
|
517
|
+
'de-DE': ['de-DE', 'de', 'en-US', 'en'],
|
|
518
|
+
'es-ES': ['es-ES', 'es', 'en-US', 'en'],
|
|
519
|
+
'tr-TR': ['tr-TR', 'tr', 'en-US', 'en'],
|
|
520
|
+
'ru-RU': ['ru-RU', 'ru', 'en-US', 'en'],
|
|
521
|
+
'pt-BR': ['pt-BR', 'pt', 'en-US', 'en'],
|
|
522
|
+
'id-ID': ['id-ID', 'id', 'en-US', 'en'],
|
|
523
|
+
'ja-JP': ['ja-JP', 'ja', 'en-US', 'en'],
|
|
524
|
+
'ko-KR': ['ko-KR', 'ko', 'en-US', 'en'],
|
|
525
|
+
'zh-CN': ['zh-CN', 'zh', 'en-US', 'en'],
|
|
526
|
+
});
|
|
527
|
+
|
|
528
|
+
const LOCALE_TIMEZONE_POOL = Object.freeze({
|
|
529
|
+
'en-US': ['America/New_York', 'America/Chicago', 'America/Los_Angeles', 'America/Denver'],
|
|
530
|
+
'en-GB': ['Europe/London'],
|
|
531
|
+
'ar-SA': ['Asia/Riyadh', 'Asia/Dubai', 'Asia/Kuwait'],
|
|
532
|
+
ar: ['Asia/Riyadh', 'Asia/Dubai'],
|
|
533
|
+
'fr-FR': ['Europe/Paris'],
|
|
534
|
+
'de-DE': ['Europe/Berlin'],
|
|
535
|
+
'es-ES': ['Europe/Madrid'],
|
|
536
|
+
'tr-TR': ['Europe/Istanbul'],
|
|
537
|
+
'ru-RU': ['Europe/Moscow'],
|
|
538
|
+
'pt-BR': ['America/Sao_Paulo'],
|
|
539
|
+
'id-ID': ['Asia/Jakarta'],
|
|
540
|
+
'ja-JP': ['Asia/Tokyo'],
|
|
541
|
+
'ko-KR': ['Asia/Seoul'],
|
|
542
|
+
'zh-CN': ['Asia/Shanghai'],
|
|
543
|
+
});
|
|
544
|
+
|
|
545
|
+
/** Region → the country most associated with a timezone (for geolocation hints). */
|
|
546
|
+
const TIMEZONE_REGION_HINT = Object.freeze({
|
|
547
|
+
'Asia/Riyadh': { country: 'SA', latitude: 24.7136, longitude: 46.6753 },
|
|
548
|
+
'Asia/Dubai': { country: 'AE', latitude: 25.2048, longitude: 55.2708 },
|
|
549
|
+
'Asia/Kuwait': { country: 'KW', latitude: 29.3759, longitude: 47.9774 },
|
|
550
|
+
'America/New_York': { country: 'US', latitude: 40.7128, longitude: -74.006 },
|
|
551
|
+
'America/Chicago': { country: 'US', latitude: 41.8781, longitude: -87.6298 },
|
|
552
|
+
'America/Los_Angeles': { country: 'US', latitude: 34.0522, longitude: -118.2437 },
|
|
553
|
+
'America/Denver': { country: 'US', latitude: 39.7392, longitude: -104.9903 },
|
|
554
|
+
'Europe/London': { country: 'GB', latitude: 51.5074, longitude: -0.1278 },
|
|
555
|
+
'Europe/Paris': { country: 'FR', latitude: 48.8566, longitude: 2.3522 },
|
|
556
|
+
'Europe/Berlin': { country: 'DE', latitude: 52.52, longitude: 13.405 },
|
|
557
|
+
'Europe/Madrid': { country: 'ES', latitude: 40.4168, longitude: -3.7038 },
|
|
558
|
+
'Europe/Istanbul': { country: 'TR', latitude: 41.0082, longitude: 28.9784 },
|
|
559
|
+
'Europe/Moscow': { country: 'RU', latitude: 55.7558, longitude: 37.6173 },
|
|
560
|
+
'America/Sao_Paulo': { country: 'BR', latitude: -23.5505, longitude: -46.6333 },
|
|
561
|
+
'Asia/Jakarta': { country: 'ID', latitude: -6.2088, longitude: 106.8456 },
|
|
562
|
+
'Asia/Tokyo': { country: 'JP', latitude: 35.6762, longitude: 139.6503 },
|
|
563
|
+
'Asia/Seoul': { country: 'KR', latitude: 37.5665, longitude: 126.978 },
|
|
564
|
+
'Asia/Shanghai': { country: 'CN', latitude: 31.2304, longitude: 121.4737 },
|
|
565
|
+
});
|
|
566
|
+
|
|
567
|
+
/** Derive the platform (+ full version) from a User-Agent — never guessed. */
|
|
568
|
+
function platformFromUserAgent(ua) {
|
|
569
|
+
const s = String(ua || '').toLowerCase();
|
|
570
|
+
if (s.includes('windows nt 10.0') || s.includes('windows')) {
|
|
571
|
+
return { platform: 'Win32', userAgentDataPlatform: 'Windows', platformVersion: '10.0.0' };
|
|
572
|
+
}
|
|
573
|
+
if (s.includes('macintosh') || s.includes('mac os x')) {
|
|
574
|
+
return { platform: 'MacIntel', userAgentDataPlatform: 'macOS', platformVersion: '13.0.0' };
|
|
575
|
+
}
|
|
576
|
+
if (s.includes('linux') || s.includes('x11')) {
|
|
577
|
+
return { platform: 'Linux x86_64', userAgentDataPlatform: 'Linux', platformVersion: '6.0.0' };
|
|
578
|
+
}
|
|
579
|
+
return { platform: 'Win32', userAgentDataPlatform: 'Windows', platformVersion: '10.0.0' };
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
/**
|
|
583
|
+
* Build the coherent privacy/consistency policy for ONE session.
|
|
584
|
+
*
|
|
585
|
+
* Every value derives from ONE locale/timezone/UA triple, so the browser cannot
|
|
586
|
+
* present an impossible combination. Nothing is re-randomized per launch for a
|
|
587
|
+
* profile that already has a persisted fingerprint (stability > randomness).
|
|
588
|
+
*
|
|
589
|
+
* @param {object} fp — the effective fingerprint for this launch
|
|
590
|
+
* @returns {object} a frozen policy the runtime applies verbatim
|
|
591
|
+
*/
|
|
592
|
+
function buildConsistencyPolicy(fp) {
|
|
593
|
+
const locale = fp.locale || 'en-US';
|
|
594
|
+
const languages = (Array.isArray(fp.languages) && fp.languages.length)
|
|
595
|
+
? fp.languages.slice()
|
|
596
|
+
: (LOCALE_LANGUAGE_POOL[locale] || ['en-US', 'en']);
|
|
597
|
+
const allowedTz = LOCALE_TIMEZONE_POOL[locale] || null;
|
|
598
|
+
let timezone = fp.timezone || (allowedTz ? allowedTz[0] : 'America/New_York');
|
|
599
|
+
// Coherence guard: a locale whose timezone pool is known must keep the
|
|
600
|
+
// configured timezone inside it. This stops "Riyadh timezone + en-US locale"
|
|
601
|
+
// style impossible pairs from ever being applied.
|
|
602
|
+
if (allowedTz && !allowedTz.includes(timezone)) {
|
|
603
|
+
timezone = allowedTz[0];
|
|
604
|
+
}
|
|
605
|
+
const plat = platformFromUserAgent(fp.userAgent);
|
|
606
|
+
const regionHint = TIMEZONE_REGION_HINT[timezone] || null;
|
|
607
|
+
|
|
608
|
+
const acceptLanguage = languages.join(',') + (languages.some((l) => l === 'en' || l.startsWith('en'))
|
|
609
|
+
? ''
|
|
610
|
+
: ',en-US;q=0.8,en;q=0.7');
|
|
611
|
+
|
|
612
|
+
return Object.freeze({
|
|
613
|
+
locale,
|
|
614
|
+
languages,
|
|
615
|
+
acceptLanguage,
|
|
616
|
+
timezone,
|
|
617
|
+
platform: plat.platform,
|
|
618
|
+
userAgentDataPlatform: plat.userAgentDataPlatform,
|
|
619
|
+
platformVersion: plat.platformVersion,
|
|
620
|
+
userAgent: fp.userAgent || null,
|
|
621
|
+
isMobile: !!fp.isMobile,
|
|
622
|
+
// Geolocation is NOT spoofed — the geolocation API is denied (leak
|
|
623
|
+
// prevention). A coarse region hint exists only so a test can assert the
|
|
624
|
+
// timezone is plausible; nothing is fed to the page.
|
|
625
|
+
regionHint,
|
|
626
|
+
});
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
/**
|
|
630
|
+
* Assert that a fingerprint + policy pair is internally consistent. Returns an
|
|
631
|
+
* array of problems (empty ⇒ coherent). Used by tests and by the launch path to
|
|
632
|
+
* fail closed on an incoherent combination.
|
|
633
|
+
*
|
|
634
|
+
* IMPORTANT: this only flags a CONTRADICTION between two values that are both
|
|
635
|
+
* present. A fingerprint that simply does not carry locale/UA information (a
|
|
636
|
+
* minimal/mocked fingerprint) is NOT incoherent — there is nothing to contradict.
|
|
637
|
+
* Fail-closed applies to impossible combinations, not to absent optional fields,
|
|
638
|
+
* so a launch is never blocked merely because an operator left an option unset.
|
|
639
|
+
*/
|
|
640
|
+
function fingerprintConsistencyProblems(fp, policy) {
|
|
641
|
+
const problems = [];
|
|
642
|
+
if (!fp || !policy) return ['fingerprint or policy missing'];
|
|
643
|
+
const ua = String(fp.userAgent || '').toLowerCase();
|
|
644
|
+
const p = String(policy.platform || '');
|
|
645
|
+
if (ua.includes('windows') && !p.startsWith('Win')) problems.push('Windows UA with non-Windows platform ' + p);
|
|
646
|
+
if (ua.includes('macintosh') && !p.startsWith('Mac')) problems.push('macOS UA with non-macOS platform ' + p);
|
|
647
|
+
if ((ua.includes('x11') || ua.includes('linux')) && !p.startsWith('Linux')) problems.push('Linux UA with non-Linux platform ' + p);
|
|
648
|
+
|
|
649
|
+
// Locale ↔ Accept-Language: the primary language tag must agree. Only checked
|
|
650
|
+
// when BOTH a locale and a derived primary language are present.
|
|
651
|
+
const primary = String((policy.languages && policy.languages[0]) || '');
|
|
652
|
+
const loc = String(fp.locale || '');
|
|
653
|
+
const locBase = loc.split('-')[0].toLowerCase();
|
|
654
|
+
if (locBase && primary && !primary.toLowerCase().startsWith(locBase)) {
|
|
655
|
+
problems.push(`Accept-Language primary (${primary}) disagrees with locale (${fp.locale})`);
|
|
656
|
+
}
|
|
657
|
+
// Timezone ↔ locale pool. Only enforced when the fingerprint EXPLICITLY set a
|
|
658
|
+
// timezone (an operator override or a generated value); the policy derives a
|
|
659
|
+
// coherent default otherwise.
|
|
660
|
+
const allowedTz = LOCALE_TIMEZONE_POOL[fp.locale];
|
|
661
|
+
if (fp.timezone && allowedTz && !allowedTz.includes(fp.timezone)) {
|
|
662
|
+
problems.push(`timezone ${fp.timezone} is not coherent with locale ${fp.locale}`);
|
|
663
|
+
}
|
|
664
|
+
return problems;
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
module.exports = {
|
|
668
|
+
FORBIDDEN_LAUNCH_ARG_PREFIXES,
|
|
669
|
+
UNIQUE_VALUE_SWITCHES,
|
|
670
|
+
BrowserIsolationError,
|
|
671
|
+
sanitizeLaunchArgs,
|
|
672
|
+
buildLaunchArgs,
|
|
673
|
+
proxyRequiredForSession,
|
|
674
|
+
sessionRuntimeDirs,
|
|
675
|
+
createSessionRuntimeDirs,
|
|
676
|
+
cleanupSessionRuntimeDirs,
|
|
677
|
+
buildSessionPreferences,
|
|
678
|
+
parseProxyIdentity,
|
|
679
|
+
validateProxyConfig,
|
|
680
|
+
coerceProxyIdentity,
|
|
681
|
+
looksLikeEncryptedEnvelope,
|
|
682
|
+
maskProxyForLog,
|
|
683
|
+
proxyIdentityFingerprint,
|
|
684
|
+
buildProxyLaunchBinding,
|
|
685
|
+
buildConsistencyPolicy,
|
|
686
|
+
fingerprintConsistencyProblems,
|
|
687
|
+
platformFromUserAgent,
|
|
688
|
+
LOCALE_LANGUAGE_POOL,
|
|
689
|
+
LOCALE_TIMEZONE_POOL,
|
|
690
|
+
TIMEZONE_REGION_HINT,
|
|
691
|
+
};
|