@xkwdstore/agent 2.1.1 → 2.1.3

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/src/index.js ADDED
@@ -0,0 +1,2013 @@
1
+ 'use strict';
2
+
3
+ // ── Polyfill: globalThis.crypto for Node < 19 (needed by Playwright in pkg) ──
4
+ if (!globalThis.crypto) {
5
+ const { webcrypto } = require('crypto');
6
+ globalThis.crypto = webcrypto;
7
+ }
8
+
9
+ /**
10
+ * XKWDStore Agent
11
+ *
12
+ * Runs on the customer PC. Connects to the VPS via WebSocket,
13
+ * receives browser commands, and executes them locally using Playwright (Chromium).
14
+ *
15
+ * Features:
16
+ * - Connects to VPS via secure WebSocket
17
+ * - Authenticates with device token (stored after pairing)
18
+ * - Launches a local Playwright Chromium browser
19
+ * - Keeps per-account browser profiles locally
20
+ * - Keeps cookies/localStorage locally
21
+ * - Applies profile/fingerprint settings from VPS account config
22
+ * - Executes automation locally (tweet, like, follow, etc.)
23
+ * - Avatar/banner uploads are routed to the correct input by label, never by
24
+ * a guessed index — so a header-pool image can never land in the avatar slot
25
+ * - Bandwidth saver: blocks image/video/font requests to x.com / twitter.com
26
+ * CDNs at the network layer so residential proxy bandwidth is not wasted on
27
+ * tweet media the automation doesn't need. Disabled per-session via
28
+ * options.blockMedia=false. Automatically and temporarily re-enabled for
29
+ * actions that genuinely need to see images (getProfileInfo, checkStatus,
30
+ * humanResume, autoLogin, checkLoginState, updateProfile) and restored
31
+ * right after, so profile info and captcha previews still work.
32
+ * - Reports status/logs/results back to VPS
33
+ * - Auto-reconnects on disconnect (exponential backoff with jitter)
34
+ * - Visible, controllable, stoppable by the user
35
+ *
36
+ * Usage:
37
+ * node src/index.js — interactive mode (prompts for pairing code)
38
+ * node src/index.js --pair=CODE — pair with a code
39
+ * node src/index.js --server=URL — specify server URL
40
+ *
41
+ * Config file: .kwdstore-agent/config.json
42
+ * Profiles: .kwdstore-agent/profiles/account-{accountId}/
43
+ * Logs: .kwdstore-agent/logs/
44
+ */
45
+
46
+ const path = require('path');
47
+ const fs = require('fs');
48
+ const os = require('os');
49
+ const { chromium } = require('playwright');
50
+ const WebSocket = require('ws');
51
+ const { runAction } = require('./actions');
52
+ const { generateFingerprint } = require('./fingerprint');
53
+ const fingerprintStore = require('./fingerprintStore');
54
+ const { resolveProfileDir, importLegacyProfile, discoverLegacyProfiles } = require('./profilePath');
55
+ const { buildStealthScript } = require('./stealth');
56
+ const leaseClient = require('./leaseClient');
57
+ const updater = require('./updater');
58
+ const configStore = require('./configStore');
59
+
60
+ // ── Config ───────────────────────────────────────────────────────────────────
61
+
62
+ const HOME_DIR = os.homedir();
63
+ // New data dir. Falls back through legacy paths if they exist, so
64
+ // already-paired customer PCs keep their device token and profiles after
65
+ // the rename to XKWDStore Agent.
66
+ const DATA_DIR_NEW = path.join(HOME_DIR, '.xkwdstore-agent');
67
+ const DATA_DIR_PREV = path.join(HOME_DIR, '.kwdstore-agent');
68
+ const DATA_DIR_LEGACY = path.join(HOME_DIR, '.local-tw-manager');
69
+ const DATA_DIR = (fs.existsSync(DATA_DIR_LEGACY) && !fs.existsSync(DATA_DIR_NEW) && !fs.existsSync(DATA_DIR_PREV))
70
+ ? DATA_DIR_LEGACY
71
+ : (fs.existsSync(DATA_DIR_PREV) && !fs.existsSync(DATA_DIR_NEW))
72
+ ? DATA_DIR_PREV
73
+ : DATA_DIR_NEW;
74
+ const CONFIG_PATH = path.join(DATA_DIR, 'config.json');
75
+ const PROFILES_DIR = path.join(DATA_DIR, 'profiles');
76
+ const LOGS_DIR = path.join(DATA_DIR, 'logs');
77
+ const EXTENSIONS_DIR = path.join(DATA_DIR, 'extensions');
78
+
79
+ // Ensure directories exist
80
+ [DATA_DIR, PROFILES_DIR, LOGS_DIR].forEach(d => {
81
+ if (!fs.existsSync(d)) fs.mkdirSync(d, { recursive: true });
82
+ });
83
+
84
+ function loadConfig() {
85
+ // configStore unwraps the DPAPI-protected device token (Phase 11) to plaintext
86
+ // in memory and applies defaults. The on-disk file never holds the plaintext.
87
+ const cfg = configStore.loadConfig(CONFIG_PATH);
88
+ if (!cfg.profileRoot) cfg.profileRoot = PROFILES_DIR;
89
+ return cfg;
90
+ }
91
+
92
+ function saveConfig(config) {
93
+ // configStore protects the device token at rest before writing.
94
+ configStore.saveConfig(CONFIG_PATH, config);
95
+ }
96
+
97
+ function log(message) {
98
+ const ts = new Date().toISOString();
99
+ const line = `[${ts}] ${message}`;
100
+ console.log(line);
101
+ try {
102
+ const logFile = path.join(LOGS_DIR, 'agent.log');
103
+ // Size-based rotation: when agent.log exceeds 5 MB, rotate to agent.log.1
104
+ // before appending. Prevents unbounded growth on long-running customer PCs.
105
+ try {
106
+ const stats = fs.statSync(logFile);
107
+ if (stats.size > 5 * 1024 * 1024) {
108
+ const rotated = path.join(LOGS_DIR, 'agent.log.1');
109
+ try { if (fs.existsSync(rotated)) fs.unlinkSync(rotated); } catch {}
110
+ try { fs.renameSync(logFile, rotated); } catch {}
111
+ }
112
+ } catch {} // file may not exist yet
113
+ fs.appendFileSync(logFile, line + '\n', 'utf8');
114
+ } catch {}
115
+ }
116
+
117
+ // ── Browser session management ───────────────────────────────────────────────
118
+
119
+ // Active sessions: accountId -> { context, page, profileDir }
120
+ const activeSessions = new Map();
121
+
122
+ // ── Helper functions for Firefox auto-download ──────────────────────────────
123
+
124
+ /**
125
+ * Recursive directory copy (synchronous). Used to copy Playwright's
126
+ * bundled Firefox into the data directory for persistence.
127
+ */
128
+ function copyDirSync(src, dst) {
129
+ fs.mkdirSync(dst, { recursive: true });
130
+ for (const entry of fs.readdirSync(src, { withFileTypes: true })) {
131
+ const srcPath = path.join(src, entry.name);
132
+ const dstPath = path.join(dst, entry.name);
133
+ if (entry.isDirectory()) {
134
+ copyDirSync(srcPath, dstPath);
135
+ } else {
136
+ fs.copyFileSync(srcPath, dstPath);
137
+ }
138
+ }
139
+ }
140
+
141
+ /**
142
+ * Get total size of a directory tree (in bytes).
143
+ */
144
+ function getDirSizeSync(dir) {
145
+ let total = 0;
146
+ try {
147
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
148
+ const fullPath = path.join(dir, entry.name);
149
+ if (entry.isDirectory()) {
150
+ total += getDirSizeSync(fullPath);
151
+ } else {
152
+ total += fs.statSync(fullPath).size;
153
+ }
154
+ }
155
+ } catch {}
156
+ return total;
157
+ }
158
+
159
+ /**
160
+ * Download a file with progress logging. Uses https with redirect following.
161
+ */
162
+ function downloadFileWithProgress(url, destPath, timeoutMs = 10 * 60 * 1000) {
163
+ return new Promise((resolve, reject) => {
164
+ const https = require('https');
165
+ const http = require('http');
166
+ let totalBytes = 0;
167
+ let downloadedBytes = 0;
168
+ let lastProgressLog = 0;
169
+
170
+ const doReq = (u, redirectsLeft) => {
171
+ const lib = u.startsWith('https') ? https : http;
172
+ const req = lib.get(u, { timeout: timeoutMs }, (resp) => {
173
+ if (resp.statusCode >= 300 && resp.statusCode < 400 && resp.headers.location) {
174
+ if (redirectsLeft <= 0) return reject(new Error('Too many redirects'));
175
+ resp.destroy();
176
+ return doReq(resp.headers.location, redirectsLeft - 1);
177
+ }
178
+ if (resp.statusCode !== 200) {
179
+ return reject(new Error(`HTTP ${resp.statusCode} for ${u}`));
180
+ }
181
+ totalBytes = parseInt(resp.headers['content-length'] || '0', 10);
182
+ const file = fs.createWriteStream(destPath);
183
+ resp.on('data', (chunk) => {
184
+ downloadedBytes += chunk.length;
185
+ // Log progress every 10 MB
186
+ if (totalBytes > 0 && downloadedBytes - lastProgressLog >= 10 * 1024 * 1024) {
187
+ const pct = ((downloadedBytes / totalBytes) * 100).toFixed(0);
188
+ const dlMB = (downloadedBytes / 1024 / 1024).toFixed(0);
189
+ const totalMB = (totalBytes / 1024 / 1024).toFixed(0);
190
+ process.stdout.write(`\r ↓ ${dlMB}/${totalMB} MB (${pct}%) `);
191
+ lastProgressLog = downloadedBytes;
192
+ }
193
+ });
194
+ resp.pipe(file);
195
+ file.on('finish', () => {
196
+ file.close();
197
+ if (totalBytes > 0) {
198
+ const totalMB = (totalBytes / 1024 / 1024).toFixed(0);
199
+ process.stdout.write(`\r ↓ ${totalMB}/${totalMB} MB (100%) \n`);
200
+ }
201
+ resolve(destPath);
202
+ });
203
+ file.on('error', (err) => {
204
+ try { fs.unlinkSync(destPath); } catch {}
205
+ reject(err);
206
+ });
207
+ });
208
+ req.on('error', reject);
209
+ req.on('timeout', () => { req.destroy(); reject(new Error('Download timed out')); });
210
+ };
211
+ doReq(url, 5);
212
+ });
213
+ }
214
+
215
+ /**
216
+ * Minimal ZIP extractor using Node's built-in zlib.
217
+ * Handles Store (0) + Deflate (8) ZIP methods.
218
+ */
219
+ function extractZip(zipPath, destDir) {
220
+ const zlib = require('zlib');
221
+ const buf = fs.readFileSync(zipPath);
222
+ // Find End-of-Central-Directory signature
223
+ let eocd = -1;
224
+ for (let i = buf.length - 22; i >= Math.max(0, buf.length - 65557); i--) {
225
+ if (buf[i] === 0x50 && buf[i + 1] === 0x4b && buf[i + 2] === 0x05 && buf[i + 3] === 0x06) {
226
+ eocd = i;
227
+ break;
228
+ }
229
+ }
230
+ if (eocd === -1) throw new Error('Not a valid ZIP (no EOCD)');
231
+
232
+ const cdOffset = buf.readUInt32LE(eocd + 16);
233
+ const cdEntries = buf.readUInt16LE(eocd + 10);
234
+
235
+ let pos = cdOffset;
236
+ for (let i = 0; i < cdEntries; i++) {
237
+ if (buf.readUInt32LE(pos) !== 0x02014b50) throw new Error(`Bad central directory entry at ${pos}`);
238
+ const compMethod = buf.readUInt16LE(pos + 10);
239
+ const compSize = buf.readUInt32LE(pos + 20);
240
+ const nameLen = buf.readUInt16LE(pos + 28);
241
+ const extraLen = buf.readUInt16LE(pos + 30);
242
+ const commentLen = buf.readUInt16LE(pos + 32);
243
+ const localHeaderOffset = buf.readUInt32LE(pos + 42);
244
+ const name = buf.slice(pos + 46, pos + 46 + nameLen).toString('utf8');
245
+ pos += 46 + nameLen + extraLen + commentLen;
246
+
247
+ const lhNameLen = buf.readUInt16LE(localHeaderOffset + 26);
248
+ const lhExtraLen = buf.readUInt16LE(localHeaderOffset + 28);
249
+ const dataStart = localHeaderOffset + 30 + lhNameLen + lhExtraLen;
250
+
251
+ if (name.endsWith('/')) {
252
+ fs.mkdirSync(path.join(destDir, name), { recursive: true });
253
+ continue;
254
+ }
255
+
256
+ const filePath = path.join(destDir, name);
257
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
258
+
259
+ let content;
260
+ if (compMethod === 0) {
261
+ content = buf.slice(dataStart, dataStart + compSize);
262
+ } else if (compMethod === 8) {
263
+ content = zlib.inflateRawSync(buf.slice(dataStart, dataStart + compSize));
264
+ } else {
265
+ throw new Error(`Unsupported ZIP compression method ${compMethod} for ${name}`);
266
+ }
267
+ fs.writeFileSync(filePath, content);
268
+ }
269
+ }
270
+
271
+ /**
272
+ * Parse proxy string (host:port:user:pass) into Playwright proxy format.
273
+ */
274
+ function parseProxy(proxyStr) {
275
+ if (!proxyStr || !proxyStr.trim()) return undefined;
276
+ const parts = proxyStr.trim().split(':');
277
+ if (parts.length >= 4) {
278
+ const [host, port, user, ...passParts] = parts;
279
+ return {
280
+ server: `http://${host}:${port}`,
281
+ username: user,
282
+ password: passParts.join(':'),
283
+ };
284
+ } else if (parts.length === 2) {
285
+ const [host, port] = parts;
286
+ return { server: `http://${host}:${port}` };
287
+ }
288
+ return undefined;
289
+ }
290
+
291
+ /**
292
+ * Lightweight proxy health check — opens a TCP connection to the proxy host:port
293
+ * with a short timeout. Fails fast (≤4s) instead of letting the browser hang on a
294
+ * dead proxy for the full network timeout. Returns { ok, reason }.
295
+ *
296
+ * CRITICAL: a falsy/missing proxy resolves { ok: false } so callers can fail
297
+ * closed. The previous duplicate boolean implementation resolved `true` for a
298
+ * missing proxy and was shadowed by this one, so `if (!healthy)` tested a truthy
299
+ * object and a DEAD proxy still launched a direct browser (real-IP leak).
300
+ */
301
+ function checkProxyHealth(proxyStr) {
302
+ const net = require('net');
303
+ let host, port;
304
+ if (typeof proxyStr === 'string') {
305
+ const parts = proxyStr.trim().split(':');
306
+ host = parts[0];
307
+ port = parseInt(parts[1], 10);
308
+ } else if (proxyStr && proxyStr.server) {
309
+ // Parsed proxy object from parseProxy(): { server: 'http://host:port', ... }
310
+ try {
311
+ const url = new URL(proxyStr.server);
312
+ host = url.hostname;
313
+ port = parseInt(url.port, 10) || (url.protocol === 'https:' ? 443 : 80);
314
+ } catch { return Promise.resolve({ ok: false, reason: 'invalid proxy server url' }); }
315
+ } else {
316
+ return Promise.resolve({ ok: false, reason: 'invalid proxy' });
317
+ }
318
+ if (!host || !port) return Promise.resolve({ ok: false, reason: 'invalid host/port' });
319
+ return new Promise((resolve) => {
320
+ let settled = false;
321
+ const socket = new net.Socket();
322
+ const finish = (ok, reason) => {
323
+ if (settled) return;
324
+ settled = true;
325
+ try { socket.destroy(); } catch {}
326
+ resolve({ ok, reason });
327
+ };
328
+ socket.setTimeout(4000);
329
+ socket.once('connect', () => finish(true, 'connected'));
330
+ socket.once('timeout', () => finish(false, 'timeout'));
331
+ socket.once('error', (err) => finish(false, err.message));
332
+ try { socket.connect(port, host); } catch (e) { finish(false, e.message); }
333
+ });
334
+ }
335
+ async function injectCookies(context, cookiesData) {
336
+ if (!cookiesData) return;
337
+ try {
338
+ let cookies = [];
339
+ if (typeof cookiesData === 'string') {
340
+ // Try JSON parse, then base64, then raw
341
+ try { cookies = JSON.parse(cookiesData); }
342
+ catch { try { cookies = JSON.parse(Buffer.from(cookiesData, 'base64').toString()); } catch {} }
343
+ } else if (Array.isArray(cookiesData)) {
344
+ cookies = cookiesData;
345
+ }
346
+ if (cookies.length === 0) {
347
+ log(`[session] No cookies to inject (empty)`);
348
+ return;
349
+ }
350
+
351
+ // Inject cookies EXACTLY as stored — do NOT modify domains, sameSite,
352
+ // or any other field. The stored data is the source of truth.
353
+ // Only add required Playwright fields if missing (path, secure, httpOnly).
354
+ const normalized = cookies.map(c => ({
355
+ name: c.name,
356
+ value: c.value,
357
+ domain: c.domain,
358
+ path: c.path || '/',
359
+ expires: c.expires || -1,
360
+ httpOnly: c.httpOnly !== undefined ? c.httpOnly : false,
361
+ secure: c.secure !== undefined ? c.secure : true,
362
+ sameSite: c.sameSite || 'None',
363
+ }));
364
+
365
+ await context.addCookies(normalized);
366
+ log(`[session] Injected ${normalized.length} cookies (as stored, unmodified)`);
367
+ } catch (err) {
368
+ log(`[session] Cookie injection error: ${err.message}`);
369
+ }
370
+ }
371
+
372
+ /**
373
+ * Phase 15 — explicit, safeguarded legacy-profile import.
374
+ *
375
+ * Pulls a pre-hardening `account-<id>` profile into the schema-3 namespaced path
376
+ * (backup → temp copy → marker verify → atomic promotion → preserve original).
377
+ * Never automatic; the backend dispatches this only after enforcing recent auth,
378
+ * confirmation, no active lease, and a conflict check. Returns a command result.
379
+ */
380
+ function importLegacyProfileCommand(accountId, options = {}) {
381
+ const { ProfileIdentityError } = require('./profilePath');
382
+ try {
383
+ const res = importLegacyProfile({
384
+ profilesDir: PROFILES_DIR,
385
+ accountId,
386
+ serverUuid: options.serverUuid,
387
+ tenantUuid: options.tenantUuid,
388
+ accountUuid: options.accountUuid,
389
+ deviceUuid: options.deviceUuid || config.deviceId,
390
+ });
391
+ log(`[session] Imported legacy account-${accountId} profile into ${path.basename(res.dir)} (original preserved at ${path.basename(res.preservedOriginal)})`);
392
+ return { success: true, dir: res.dir, preservedOriginal: res.preservedOriginal };
393
+ } catch (e) {
394
+ log(`[session] ⚠️ Legacy import refused for account ${accountId}: ${e.message}`);
395
+ const msg = e instanceof ProfileIdentityError ? e.message : `Legacy import failed: ${e.message}`;
396
+ return { success: false, error: msg };
397
+ }
398
+ }
399
+
400
+ /**
401
+ * Start a browser session for an account.
402
+ */
403
+ async function startSession(accountId, options = {}, lease) {
404
+ if (activeSessions.has(accountId)) {
405
+ // Focus existing session instead of creating duplicate
406
+ const existing = activeSessions.get(accountId);
407
+ // Check if the browser is actually still alive
408
+ try {
409
+ // Try a simple operation to verify the browser is responsive
410
+ await existing.page.evaluate(() => document.title).catch(() => null);
411
+ await existing.page.bringToFront();
412
+ return { success: true, sessionId: accountId, status: 'running', message: 'Already running — focused existing window' };
413
+ } catch {
414
+ // Browser is dead — clean up and restart
415
+ try { await existing.context.close(); } catch {}
416
+ activeSessions.delete(accountId);
417
+ sendToServer(leaseClient.boundStatusMessage(existing, accountId, 'stopped'));
418
+ }
419
+ }
420
+
421
+ // Chrome/Chromium required. The automation uses Chrome with stealth
422
+ // spoofing to avoid Playwright detection.
423
+ if (!checkBrowserAvailable()) {
424
+ return { success: false, error: 'Google Chrome is required. Please install Chrome, then restart XKWDStore Agent.' };
425
+ }
426
+
427
+ currentAction = `startSession:${accountId}`;
428
+ // Phase 14: namespace the on-disk profile by an IMMUTABLE identity tuple from
429
+ // the backend — server UUID + tenant UUID + account UUID + device UUID — so a
430
+ // re-paired device, a rebuilt DB (reused numeric ids), or a server URL change
431
+ // can never inherit another account's profile/cookies. resolveProfileDir FAILS
432
+ // CLOSED if any identity is missing/malformed (no recyclable fallbacks), moves
433
+ // a schema-2 namespaced profile into the new path on first resolve (preserving
434
+ // data), and quarantines (never stamp-and-reuse) an unmarked/corrupt/mismatched
435
+ // dir. Phase 15: an account-<id> legacy dir is NEVER auto-imported here — it is
436
+ // surfaced as migrationRequired for an explicit, safeguarded import.
437
+ let profileDir, migrated, quarantined, migrationRequired;
438
+ try {
439
+ ({ dir: profileDir, migrated, quarantined, migrationRequired } = resolveProfileDir({
440
+ profilesDir: PROFILES_DIR,
441
+ serverUuid: options.serverUuid,
442
+ tenantUuid: options.tenantUuid,
443
+ accountUuid: options.accountUuid,
444
+ deviceUuid: options.deviceUuid || config.deviceId,
445
+ serverUrl: config.serverUrl, // legacy schema-2 path migration
446
+ userId: options.userId, // legacy schema-2 path migration
447
+ accountId, // account-<id> legacy discovery (no auto-import)
448
+ }));
449
+ } catch (e) {
450
+ // Fail closed: never open a browser profile with an incomplete/unverifiable
451
+ // identity (rule 17). A missing server/tenant/account/device UUID means the
452
+ // backend has not provided a complete identity — refuse the launch.
453
+ log(`[session] ⚠️ Refusing to open a profile for account ${accountId}: ${e.message}`);
454
+ return { success: false, error: `Profile identity incomplete: ${e.message}` };
455
+ }
456
+ if (!fs.existsSync(profileDir)) fs.mkdirSync(profileDir, { recursive: true });
457
+ if (migrated) log(`[session] Migrated legacy profile into namespaced dir for account ${accountId}`);
458
+ if (quarantined) {
459
+ log(`[session] ⚠️ Quarantined a bad/corrupt profile for account ${accountId} → ${path.basename(quarantined)}; starting fresh`);
460
+ }
461
+ if (migrationRequired) {
462
+ log(`[session] ℹ️ A pre-hardening account-${accountId} profile exists; explicit import is required (not auto-imported)`);
463
+ }
464
+
465
+ const proxy = parseProxy(options.proxy);
466
+ // networkMode: 'proxy_required' = a working proxy is mandatory; if the
467
+ // configured proxy is dead OR no proxy is configured, ABORT the launch
468
+ // (fail closed) rather than opening a direct browser that leaks the
469
+ // customer's real IP. 'direct_allowed' = direct connection is acceptable
470
+ // when no proxy is configured. Phase 16: the persisted mode is passed
471
+ // through UNMODIFIED — a missing/unknown mode FAILS CLOSED in proxyPolicy
472
+ // (never coerced to direct_allowed, which would leak the real IP). The
473
+ // backend persists an explicit mode per account (default proxy_required).
474
+ const networkMode = options.networkMode;
475
+
476
+ // Health-check the proxy only when one was configured, then ask the pure
477
+ // policy for a fail-closed launch decision (tested without Playwright).
478
+ // Phase 8: a TCP connect is not enough — a proxy that accepts TCP but does
479
+ // not tunnel would still pass. After the TCP pre-check, run a real
480
+ // through-proxy egress verification (CONNECT + TLS + GET). The launch aborts
481
+ // unless the proxy actually forwarded an external request.
482
+ let health = null;
483
+ if (proxy) {
484
+ const tcp = await checkProxyHealth(proxy);
485
+ if (!tcp.ok) {
486
+ health = tcp;
487
+ } else {
488
+ // Phase 17: a working tunnel is not enough. Independently measure the
489
+ // device's DIRECT public IP and require the proxy egress IP to DIFFER. A
490
+ // proxy that egresses from the device's own IP (transparent / misconfigured)
491
+ // leaks the real IP → refuse the launch (PROXY_DIRECT_BYPASS_DETECTED).
492
+ // verifyProxyIsolation does the through-proxy egress + the direct-IP fetch
493
+ // (no proxy creds to the public IP service) + the comparison.
494
+ const isolation = await require('./proxyEgress').verifyProxyIsolation(proxy, {});
495
+ if (isolation.ok) {
496
+ health = { ok: true, reason: 'proxy_ok', egressIp: isolation.egressIp, directIp: isolation.directIp };
497
+ } else {
498
+ health = { ok: false, reason: 'proxy_isolation_failed: ' + (isolation.code || isolation.reason), code: isolation.code };
499
+ }
500
+ }
501
+ }
502
+ const decision = require('./proxyPolicy').decideProxyLaunch({
503
+ proxyStr: options.proxy,
504
+ networkMode,
505
+ health,
506
+ });
507
+ if (decision.action === 'abort') {
508
+ let host = '';
509
+ try { if (proxy) host = new URL(proxy.server).host; } catch {}
510
+ const code = health && health.code ? ` [${health.code}]` : '';
511
+ const detail = health && health.reason && String(health.reason).startsWith('proxy_isolation_failed')
512
+ ? health.reason
513
+ : decision.reason;
514
+ log(`[session] ${detail}${code}${host ? ` (${host})` : ''} — aborting session for ${accountId}`);
515
+ return { success: false, error: decision.error, code: health && health.code };
516
+ }
517
+ if (decision.useProxy) {
518
+ const egressIp = health && health.egressIp ? ` (egress ${health.egressIp})` : '';
519
+ log(`[session] Proxy ${new URL(proxy.server).host} is reachable and tunnels egress${egressIp}`);
520
+ }
521
+
522
+ // Generate per-account fingerprint profile (includes UA, timezone, screen, etc.)
523
+ // Phase 4: the randomized HARDWARE fingerprint is persisted inside the
524
+ // namespaced profile dir and reloaded verbatim on every subsequent launch, so
525
+ // it stays stable across agent upgrades. Live fields (UA/Chrome version,
526
+ // locale, timezone) are re-applied each launch from the account options —
527
+ // this is also what carries the configured timezone into the browser.
528
+ const fingerprint = fingerprintStore.loadOrGenerate({
529
+ profileDir,
530
+ accountId,
531
+ options: {
532
+ mobileView: options.mobileView,
533
+ locale: options.locale,
534
+ userAgent: options.userAgent,
535
+ timezone: options.timezone,
536
+ chromeVersion: DETECTED_CHROME_VERSION,
537
+ },
538
+ generator: generateFingerprint,
539
+ });
540
+
541
+ // Use fingerprint's screen size for viewport (randomized per-account)
542
+ const viewport = options.mobileView
543
+ ? { width: 390, height: 844 }
544
+ : { width: fingerprint.screen.width, height: fingerprint.screen.height };
545
+
546
+ const launchOptions = {
547
+ headless: false, // Always visible on customer PC
548
+ executablePath: resolveChromiumPath(),
549
+ viewport,
550
+ args: [
551
+ // ── Anti-automation-detection flags ──
552
+ '--disable-blink-features=AutomationControlled',
553
+ // NOTE: site-isolation disable flags (--disable-features=IsolateOrigins,
554
+ // site-per-process / --disable-site-isolation-trials) were removed: they
555
+ // weakened a Chrome security control that prevents cross-origin data
556
+ // exfiltration. Security takes priority over any detection benefit.
557
+ // Remove Playwright/automation indicators
558
+ // ── WebRTC IP leak prevention ──
559
+ '--force-webrtc-ip-handling-policy=disable_non_proxied_udp',
560
+ '--webrtc-ip-handling-policy=disable_non_proxied_udp',
561
+ // ── Privacy / stealth ──
562
+ '--disable-notifications',
563
+ '--disable-popup-blocking',
564
+ '--disable-prompt-on-repost',
565
+ '--disable-default-apps',
566
+ '--disable-translate',
567
+ '--disable-media-router',
568
+ '--disable-print-preview',
569
+ '--disable-background-networking',
570
+ '--disable-component-update',
571
+ '--disable-domain-reliability',
572
+ '--disable-client-side-phishing-detection',
573
+ '--disable-sync',
574
+ '--metrics-recording-only',
575
+ '--no-first-run',
576
+ '--no-default-browser-check',
577
+ '--disable-background-timer-throttling',
578
+ '--disable-renderer-backgrounding',
579
+ '--disable-backgrounding-occluded-windows',
580
+ '--disable-ipc-flooding-protection',
581
+ // ── Disable automation tell-tales ──
582
+ '--password-store=basic',
583
+ '--use-mock-keychain',
584
+ // ── GPU / performance ──
585
+ // ── Language / locale ──
586
+ '--lang=' + (fingerprint.locale || 'en-US'),
587
+ '--accept-lang=' + (fingerprint.languages || ['en-US', 'en']).join(','),
588
+ ],
589
+ };
590
+
591
+ // ── Extension loading (Chromium mode) ──
592
+ // Chromium extensions are loaded via --load-extension= flag, not by copying
593
+ // .xpi files into the profile. The EXTENSIONS_DIR is still created for future
594
+ // use if the user wants to load unpacked Chrome extensions via launch args.
595
+
596
+ if (proxy) {
597
+ // Chromium handles proxy auth via Playwright's proxy config.
598
+ launchOptions.proxy = { ...proxy };
599
+ log(`[session] Proxy configured: ${proxy.server} user=${proxy.username || '(none)'}`);
600
+ } else {
601
+ log(`[session] WARNING: No proxy configured for account ${accountId} — browser will use direct connection (real IP visible!)`);
602
+ }
603
+ // Use per-account user-agent from fingerprint
604
+ launchOptions.userAgent = fingerprint.userAgent;
605
+ // Use per-account locale from fingerprint
606
+ launchOptions.locale = fingerprint.locale;
607
+ // Use per-account timezone from fingerprint
608
+ launchOptions.timezoneId = fingerprint.timezone;
609
+ // Set screen size to match fingerprint
610
+ launchOptions.screen = { width: fingerprint.screen.width, height: fingerprint.screen.height };
611
+
612
+ log(`[session] Starting Chrome for account ${accountId} proxy=${proxy ? 'yes' : 'no'} mobile=${!!options.mobileView} ua=${fingerprint.userAgent.slice(-30)} tz=${fingerprint.timezone}`);
613
+
614
+ try {
615
+ const context = await chromium.launchPersistentContext(profileDir, launchOptions);
616
+ const page = context.pages()[0] || await context.newPage();
617
+
618
+ // ── Bandwidth saver: block heavy media from x.com / twitter.com CDNs ──
619
+ // Residential proxy bandwidth is expensive. Tweets, timeline scrolling,
620
+ // and profile pages pull in megabytes of images/videos/fonts that the
621
+ // automation does not need. We abort those requests at the network layer
622
+ // before they ever reach the proxy.
623
+ //
624
+ // What is blocked (only on x.com / twitter.com / their CDNs):
625
+ // - image/* (tweet images, avatars, banners, emoji sprites)
626
+ // - video/* (tweet videos, GIF previews as mp4)
627
+ // - audio/* (rare, but cheap to block)
628
+ // - font/*, woff, woff2 (icon fonts only — page text still renders)
629
+ //
630
+ // What is NOT blocked:
631
+ // - Document/script/css/xhr/fetch — the app must still work.
632
+ // - Uploads (avatar/banner) — those use <input type=file>, not GETs.
633
+ // - First-party navigation to x.com itself.
634
+ //
635
+ // Tunable per session via options.blockMedia (default: true).
636
+ //
637
+ // Per-action override: certain actions (getProfileInfo, checkStatus,
638
+ // humanResume, autoLogin, checkLoginState) need to actually see images
639
+ // (avatars, banners, captcha previews). runActionCommand flips
640
+ // `mediaAllowed` to true only for the duration of those actions, then
641
+ // restores the block. The route handler below reads this flag on every
642
+ // request, so the toggle takes effect immediately for in-flight navigations.
643
+ //
644
+ // NOTE: media blocking is OFF by default for now. Residential proxy
645
+ // bandwidth savings vs. blank-looking pages is a trade-off — when pages
646
+ // render without images, operators think "nothing opened" and keep
647
+ // re-launching sessions (which wastes more than it saves). Enable
648
+ // explicitly per session via options.blockMedia=true once the operator
649
+ // is comfortable with image-less pages.
650
+ const blockMedia = options.blockMedia === true;
651
+ let mediaAllowed = false; // toggled per-action by runActionCommand
652
+ const setMediaAllowed = (v) => { mediaAllowed = !!v; };
653
+
654
+ if (blockMedia) {
655
+ const MEDIA_HOSTS = [
656
+ 'x.com', 'twitter.com',
657
+ 'pbs.twimg.com', // tweet images, avatars, banners
658
+ 'video.twimg.com', // tweet videos
659
+ 'ton.twimg.com', // emoji sprites, icon sheets
660
+ 'abs.twimg.com', // static icons/fonts
661
+ 'pbs-h2.twimg.com',
662
+ 'video-h2.twimg.com',
663
+ ];
664
+ const MEDIA_RESOURCE_TYPES = new Set(['image', 'media', 'font']);
665
+ const blockedContentTypePrefixes = ['image/', 'video/', 'audio/'];
666
+ let blockedCount = 0;
667
+
668
+ await context.route('**/*', (route) => {
669
+ // Per-action override: when an action needs images, let everything through.
670
+ if (mediaAllowed) return route.continue();
671
+
672
+ const req = route.request();
673
+ const url = req.url();
674
+ let parsed;
675
+ try { parsed = new URL(url); } catch { return route.continue(); }
676
+ const host = parsed.hostname.toLowerCase();
677
+ const isMediaHost = MEDIA_HOSTS.some(h => host === h || host.endsWith('.' + h));
678
+ if (!isMediaHost) return route.continue();
679
+
680
+ const resourceType = req.resourceType();
681
+ const contentType = (req.headers()['content-type'] || '').toLowerCase();
682
+
683
+ const isMedia =
684
+ MEDIA_RESOURCE_TYPES.has(resourceType) ||
685
+ blockedContentTypePrefixes.some(p => contentType.startsWith(p)) ||
686
+ /\.(png|jpe?g|gif|webp|svg|ico|bmp|mp4|m4v|webm|mov|woff2?|ttf|otf)(\?|#|$)/i.test(parsed.pathname + parsed.search);
687
+
688
+ if (isMedia) {
689
+ blockedCount++;
690
+ return route.abort();
691
+ }
692
+ return route.continue();
693
+ });
694
+
695
+ // Periodically log how much we've saved so the operator can see it works.
696
+ const blockLogTimer = setInterval(() => {
697
+ if (blockedCount > 0) log(`[session] Media blocked for ${accountId}: ${blockedCount} requests`);
698
+ }, 30000);
699
+ context.on('close', () => clearInterval(blockLogTimer));
700
+ log(`[session] Media blocking enabled for account ${accountId} (images/videos/fonts on x.com CDNs will not be fetched through the proxy)`);
701
+ }
702
+
703
+ // ── Stealth: comprehensive per-account anti-detection ─────────────────
704
+ try {
705
+ const stealthScript = buildStealthScript(fingerprint);
706
+ await context.addInitScript(stealthScript);
707
+ } catch (e) {
708
+ log(`[session] Stealth script injection failed (non-fatal): ${e.message}`);
709
+ }
710
+
711
+ // ── HTTP headers: Accept-Language must match fingerprint locale ──────
712
+ try {
713
+ const acceptLang = fingerprint.languages.join(',');
714
+ await context.setExtraHTTPHeaders({
715
+ 'Accept-Language': acceptLang,
716
+ });
717
+ } catch (e) {
718
+ log(`[session] HTTP header injection failed (non-fatal): ${e.message}`);
719
+ }
720
+
721
+ // Inject cookies BEFORE navigation so the session is authenticated
722
+ if (options.cookies) {
723
+ await injectCookies(context, options.cookies);
724
+ } else {
725
+ log(`[session] No cookies provided for account ${accountId} — will need manual login`);
726
+ }
727
+
728
+ // Configure DBC (Death By Captcha) if credentials provided
729
+ if (options.dbcUsername && options.dbcPassword) {
730
+ try {
731
+ const dbc = require('./actions/dbc');
732
+ dbc.configure(options.dbcUsername, options.dbcPassword);
733
+ log(`[session] DBC configured for captcha solving`);
734
+ } catch (e) {
735
+ log(`[session] DBC setup failed: ${e.message}`);
736
+ }
737
+ }
738
+
739
+ // Navigate to x.com
740
+ await page.goto('https://x.com/home', {
741
+ waitUntil: 'domcontentloaded',
742
+ timeout: 60000,
743
+ }).catch((e) => {
744
+ log(`[session] Navigation to x.com/home failed: ${e.message}`);
745
+ });
746
+
747
+ // Wait for network to settle
748
+ await page.waitForLoadState('networkidle', { timeout: 10000 }).catch(() => {});
749
+
750
+ // ── Session warm-up: simulate human browsing before first action ──────
751
+ // Real users don't immediately perform actions — they scroll, read, hover
752
+ try {
753
+ const { sessionWarmup } = require('./actions/helpers');
754
+ log(`[session] Warm-up browsing for account ${accountId}...`);
755
+ await sessionWarmup(page, 5000);
756
+ log(`[session] Warm-up done for account ${accountId}`);
757
+ } catch (e) {
758
+ log(`[session] Warm-up failed (non-fatal): ${e.message}`);
759
+ }
760
+
761
+ // ── Image Video Block: only block media at network level when enabled ──
762
+ // Do NOT inject CSS that hides images with opacity:0 — this makes the
763
+ // browser look broken to operators. Media blocking is handled at the
764
+ // network layer above (blockMedia option) which is OFF by default.
765
+ // The extension is installed in the profile but we can't access its
766
+ // browser.storage.local API from outside the extension context.
767
+ //
768
+ // Only apply network-level media blocking if blockMedia is explicitly true.
769
+ if (blockMedia) {
770
+ try {
771
+ await context.route('**/*', (route) => {
772
+ if (mediaAllowed) return route.continue();
773
+ const req = route.request();
774
+ const resourceType = req.resourceType();
775
+ if (resourceType === 'image' || resourceType === 'media' || resourceType === 'font') {
776
+ return route.abort();
777
+ }
778
+ const url = req.url();
779
+ try {
780
+ const parsed = new URL(url);
781
+ if (/\.(png|jpe?g|gif|webp|svg|ico|bmp|avif|mp4|m4v|webm|mov|avi|mkv|mp3|m4a|ogg|wav|flac|aac|woff2?|ttf|otf|eot)(\?|#|$)/i.test(parsed.pathname + parsed.search)) {
782
+ return route.abort();
783
+ }
784
+ } catch {}
785
+ return route.continue();
786
+ }).catch(() => {});
787
+ log(`[session] Image Video Block: network blocking enabled for account ${accountId}`);
788
+ } catch (e) {
789
+ log(`[session] Image Video Block setup skipped (non-fatal): ${e.message}`);
790
+ }
791
+ }
792
+
793
+ // Log if the browser closes unexpectedly
794
+ context.on('close', () => {
795
+ log(`[session] Browser context closed for account ${accountId}`);
796
+ const closed = activeSessions.get(accountId);
797
+ activeSessions.delete(accountId);
798
+ sendToServer(leaseClient.boundStatusMessage(closed, accountId, 'stopped'));
799
+ });
800
+ page.on('close', () => {
801
+ log(`[session] Page closed for account ${accountId}`);
802
+ });
803
+
804
+ const sessionObj = { context, page, profileDir, setMediaAllowed };
805
+ // Phase 3: bind the lease credential to the active session (in-memory only).
806
+ // It is echoed back in every session-status/stop-ack/error message so the
807
+ // server can verify the holder; never logged, never persisted to disk.
808
+ if (lease) leaseClient.bind(sessionObj, lease);
809
+ activeSessions.set(accountId, sessionObj);
810
+ log(`[session] Browser started for account ${accountId}`);
811
+
812
+ // Report status to VPS (lease-bound so the server can activate the lease).
813
+ sendToServer(leaseClient.boundStatusMessage(sessionObj, accountId, 'running'));
814
+
815
+ return { success: true, sessionId: accountId, status: 'running', message: 'Browser opened locally on customer PC', migrationRequired: !!migrationRequired };
816
+ } catch (err) {
817
+ lastError = err.message;
818
+ log(`[session] Failed to start for account ${accountId}: ${err.message}`);
819
+ // A failed start sends an error status with the lease credential so the
820
+ // server can release the lease it acquired for this attempt.
821
+ const tmpSession = lease ? (() => { const s = {}; leaseClient.bind(s, lease); return s; })() : null;
822
+ sendToServer(leaseClient.boundStatusMessage(tmpSession, accountId, 'error', { error: err.message }));
823
+ return { success: false, error: err.message };
824
+ } finally {
825
+ currentAction = null;
826
+ }
827
+ }
828
+
829
+ /**
830
+ * Stop a browser session for an account.
831
+ */
832
+ async function stopSession(accountId) {
833
+ const session = activeSessions.get(accountId);
834
+ if (!session) {
835
+ return { success: true, status: 'stopped', message: 'No active session' };
836
+ }
837
+
838
+ try {
839
+ // Save cookies before closing
840
+ const cookies = await session.context.cookies().catch(() => []);
841
+ log(`[session] Saved ${cookies.length} cookies for account ${accountId}`);
842
+
843
+ await session.context.close();
844
+ activeSessions.delete(accountId);
845
+ log(`[session] Browser stopped for account ${accountId}`);
846
+
847
+ // Lease-bound stop ack: the server verifies the credential and releases the
848
+ // durable lease. This is the only thing that completes a takeover.
849
+ sendToServer(leaseClient.boundStatusMessage(session, accountId, 'stopped'));
850
+
851
+ return { success: true, status: 'stopped' };
852
+ } catch (err) {
853
+ log(`[session] Stop error for account ${accountId}: ${err.message}`);
854
+ activeSessions.delete(accountId);
855
+ return { success: false, error: err.message };
856
+ }
857
+ }
858
+
859
+ /**
860
+ * Close EVERY active browser session. Used when the WebSocket to the server
861
+ * drops (crash, network failure, PC sleep, agent restart) so no account is
862
+ * left with a live browser on a disconnected agent. Cookies are saved, the
863
+ * context is closed, and each closed session is reported 'stopped' to the
864
+ * server once reconnected (we cannot send while disconnected; the
865
+ * context.on('close') handler in startSession also reports stopped).
866
+ */
867
+ async function closeAllSessions() {
868
+ const ids = Array.from(activeSessions.keys());
869
+ if (ids.length === 0) return;
870
+ log(`[session] WebSocket dropped — closing ${ids.length} active browser session(s)`);
871
+ for (const accountId of ids) {
872
+ const session = activeSessions.get(accountId);
873
+ try {
874
+ // Save cookies before closing so the session can resume later.
875
+ const cookies = await session.context.cookies().catch(() => []);
876
+ log(`[session] Saved ${cookies.length} cookies for account ${accountId} (WS drop)`);
877
+ await session.context.close();
878
+ } catch (err) {
879
+ log(`[session] Close error for account ${accountId} during WS drop: ${err.message}`);
880
+ }
881
+ activeSessions.delete(accountId);
882
+ }
883
+ log(`[session] All browser sessions closed after WS disconnect`);
884
+ }
885
+
886
+ /**
887
+ * Restart a browser session.
888
+ */
889
+ async function restartSession(accountId, options = {}, lease) {
890
+ await stopSession(accountId);
891
+ await new Promise(r => setTimeout(r, 500));
892
+ return startSession(accountId, options, lease);
893
+ }
894
+
895
+ /**
896
+ * Refresh (reload) a browser session.
897
+ */
898
+ async function refreshSession(accountId) {
899
+ const session = activeSessions.get(accountId);
900
+ if (!session) return { success: false, error: 'No active session' };
901
+ try {
902
+ await session.page.reload({ waitUntil: 'domcontentloaded', timeout: 30000 });
903
+ return { success: true, status: 'running' };
904
+ } catch (err) {
905
+ return { success: false, error: err.message };
906
+ }
907
+ }
908
+
909
+ /**
910
+ * Navigate to a URL.
911
+ */
912
+ async function navigate(accountId, url) {
913
+ const session = activeSessions.get(accountId);
914
+ if (!session) return { success: false, error: 'No active session' };
915
+ try {
916
+ await session.page.goto(url, { waitUntil: 'domcontentloaded', timeout: 30000 });
917
+ return { success: true, url: session.page.url() };
918
+ } catch (err) {
919
+ return { success: false, error: err.message };
920
+ }
921
+ }
922
+
923
+ /**
924
+ * Focus / bring to front the browser window for an account.
925
+ */
926
+ async function focusSession(accountId) {
927
+ const session = activeSessions.get(accountId);
928
+ if (!session) return { success: false, error: 'No active session' };
929
+ try {
930
+ // Bring the page to front
931
+ await session.page.bringToFront();
932
+ log(`[session] Focused browser for account ${accountId}`);
933
+ return { success: true, message: 'Browser focused' };
934
+ } catch (err) {
935
+ return { success: false, error: err.message };
936
+ }
937
+ }
938
+
939
+ /**
940
+ * Type text into a selector or focused element.
941
+ */
942
+ async function typeText(accountId, selector, text) {
943
+ const session = activeSessions.get(accountId);
944
+ if (!session) return { success: false, error: 'No active session' };
945
+ try {
946
+ if (selector) {
947
+ const el = session.page.locator(selector).first();
948
+ await el.waitFor({ state: 'visible', timeout: 10000 });
949
+ await el.click();
950
+ await session.page.keyboard.press('Control+a');
951
+ await session.page.keyboard.press('Backspace');
952
+ // Humanized typing
953
+ const { humanType } = require('./actions/helpers');
954
+ await humanType(session.page, text);
955
+ } else {
956
+ const { humanType } = require('./actions/helpers');
957
+ await humanType(session.page, text);
958
+ }
959
+ return { success: true, url: session.page.url() };
960
+ } catch (err) {
961
+ return { success: false, error: err.message };
962
+ }
963
+ }
964
+
965
+ /**
966
+ * Press a key.
967
+ */
968
+ async function pressKey(accountId, key) {
969
+ const session = activeSessions.get(accountId);
970
+ if (!session) return { success: false, error: 'No active session' };
971
+ try {
972
+ await session.page.keyboard.press(key);
973
+ return { success: true };
974
+ } catch (err) {
975
+ return { success: false, error: err.message };
976
+ }
977
+ }
978
+
979
+ /**
980
+ * Click at a selector or coordinates.
981
+ */
982
+ async function click(accountId, selector, x, y) {
983
+ const session = activeSessions.get(accountId);
984
+ if (!session) return { success: false, error: 'No active session' };
985
+ try {
986
+ if (selector) {
987
+ const { humanClick } = require('./actions/helpers');
988
+ await humanClick(session.page, selector);
989
+ } else if (x != null && y != null) {
990
+ await session.page.mouse.click(x, y);
991
+ }
992
+ return { success: true, url: session.page.url() };
993
+ } catch (err) {
994
+ return { success: false, error: err.message };
995
+ }
996
+ }
997
+
998
+ /**
999
+ * Run an automation action (tweet, like, follow, etc.)
1000
+ * Delegates to the action dispatcher module.
1001
+ */
1002
+ async function runActionCommand(accountId, action, payload) {
1003
+ let session = activeSessions.get(accountId);
1004
+ if (!session) return { success: false, error: 'No active session' };
1005
+
1006
+ // Check if the browser is still alive before running the action
1007
+ try {
1008
+ await session.page.evaluate(() => document.title).catch(() => null);
1009
+ } catch {
1010
+ // Browser is dead — clean up and report stopped (lease-bound).
1011
+ log(`[action] Browser dead for account ${accountId}, cleaning up...`);
1012
+ try { await session.context.close(); } catch {}
1013
+ activeSessions.delete(accountId);
1014
+ sendToServer(leaseClient.boundStatusMessage(session, accountId, 'stopped'));
1015
+ return { success: false, error: 'Browser session was closed. Please start the session again.' };
1016
+ }
1017
+
1018
+ try {
1019
+ log(`[action] Running action '${action}' for account ${accountId}`);
1020
+
1021
+ // ── Per-action media override ───────────────────────────────────────
1022
+ // Most actions only manipulate the DOM (click, type, scroll) and don't
1023
+ // need to actually see tweet images. But a few actions read profile info
1024
+ // (avatar/banner URLs), solve captchas (need to see the challenge image),
1025
+ // or verify login state — those need media to load at least once.
1026
+ // We temporarily unblock media for those, reload so already-blocked images
1027
+ // get a chance to fetch, run the action, then restore the block.
1028
+ const MEDIA_REQUIRED_ACTIONS = new Set([
1029
+ 'getProfileInfo', // captures avatar/banner URLs from the DOM
1030
+ 'checkStatus', // inspects profile state
1031
+ 'humanResume', // may need to see captcha challenge images
1032
+ 'autoLogin', // login flow may include image challenges
1033
+ 'checkLoginState', // verifies the post-login page
1034
+ 'updateProfile', // profile editor preview shows avatar/banner
1035
+ ]);
1036
+ const needsMedia = MEDIA_REQUIRED_ACTIONS.has(action);
1037
+ const hadMediaBlock = typeof session.setMediaAllowed === 'function';
1038
+ if (needsMedia && hadMediaBlock) {
1039
+ log(`[action] Temporarily allowing media for '${action}' on account ${accountId}`);
1040
+ session.setMediaAllowed(true);
1041
+ // Give already-blocked images on the current page a chance to re-fetch.
1042
+ // We retry broken <img> by re-assigning their src; this triggers a fresh
1043
+ // request that now passes the route handler (mediaAllowed=true).
1044
+ try {
1045
+ await session.page.evaluate(() => {
1046
+ const imgs = Array.from(document.querySelectorAll('img[src]'));
1047
+ for (const img of imgs) {
1048
+ if (!img.naturalWidth || img.naturalWidth === 0) {
1049
+ const s = img.src;
1050
+ img.src = '';
1051
+ img.src = s;
1052
+ }
1053
+ }
1054
+ }).catch(() => {});
1055
+ } catch (e) {
1056
+ log(`[action] Media re-fetch trigger failed (non-fatal): ${e.message}`);
1057
+ }
1058
+ }
1059
+
1060
+ let result;
1061
+ try {
1062
+ result = await runAction(session.page, action, payload);
1063
+ } finally {
1064
+ // Always restore the block, even if the action threw.
1065
+ if (needsMedia && hadMediaBlock) {
1066
+ session.setMediaAllowed(false);
1067
+ log(`[action] Media block restored after '${action}' for account ${accountId}`);
1068
+ }
1069
+ }
1070
+ log(`[action] Action '${action}' completed for account ${accountId}: ${result.success ? 'success' : 'failed'}`);
1071
+
1072
+ // After a successful action, simulate human post-action behavior before
1073
+ // the backend closes the browser — scroll, pause, browse, mouse movement.
1074
+ // We intentionally isolate this from the action result: if the post-action
1075
+ // browsing throws (e.g. page navigated away, network hiccup), the main
1076
+ // action (e.g. comment) was still successful and must not be reported as
1077
+ // failed. The post-action error is logged and attached as a warning only.
1078
+ //
1079
+ // Additionally, for bulk actions where the backend immediately closes the
1080
+ // browser (comment, like, follow, retweet, tweet), running post-action
1081
+ // behavior is wasted time and increases the chance of a server-side
1082
+ // command timeout. Skip it for those actions; keep it for long-lived sessions
1083
+ // (profile/info/automation connect) where the browser stays open.
1084
+ const shortLivedActions = ['comment', 'like', 'follow', 'unfollow', 'retweet', 'tweet', 'reply'];
1085
+ if (result.success && !shortLivedActions.includes(action)) {
1086
+ try {
1087
+ const { humanPostAction } = require('./actions/helpers');
1088
+ log(`[action] Post-action human behavior for account ${accountId}...`);
1089
+ await humanPostAction(session.page);
1090
+ log(`[action] Post-action behavior done for account ${accountId}`);
1091
+ } catch (postErr) {
1092
+ log(`[action] Post-action behavior failed for account ${accountId} (non-fatal): ${postErr.message}`);
1093
+ result.postActionWarning = postErr.message;
1094
+ }
1095
+ } else if (result.success && shortLivedActions.includes(action)) {
1096
+ log(`[action] Skipping post-action behavior for short-lived action '${action}' (backend will close browser)`);
1097
+ }
1098
+
1099
+ return result;
1100
+ } catch (err) {
1101
+ log(`[action] Action '${action}' failed for account ${accountId}: ${err.message}`);
1102
+ const result = { success: false, error: err.message };
1103
+ if (err.partialFailures) result.partialFailures = err.partialFailures;
1104
+ if (err.failureContext) result.failureContext = err.failureContext;
1105
+ return result;
1106
+ }
1107
+ }
1108
+
1109
+ // ── WebSocket connection to VPS ──────────────────────────────────────────────
1110
+
1111
+ let ws = null;
1112
+ let config = loadConfig();
1113
+ let heartbeatTimer = null;
1114
+ let reconnectTimer = null;
1115
+ let heartbeatSeconds = 20;
1116
+ // Phase 11: ack-then-activate rotation. When the server sends a new credential
1117
+ // pair we stage it (persist immediately) and ack; we keep the PREVIOUS
1118
+ // credential in memory so we can revert if the server aborts the rotation (the
1119
+ // ack didn't arrive, or the WS dropped) — the old credential is still valid in
1120
+ // that case, so reverting avoids orphaning ourselves. Cleared once the server
1121
+ // confirms activation.
1122
+ let _preRotationCreds = null;
1123
+ // Exponential backoff with jitter: 1s, 2s, 4s, 8s, 16s, 30s (capped) + ±25% jitter.
1124
+ // Without this, a flapping VPS gets hammered at a fixed 5s cadence.
1125
+ let reconnectAttempts = 0;
1126
+ const RECONNECT_BASE_MS = 1000;
1127
+ const RECONNECT_MAX_MS = 15000; // Reduced from 30s to 15s for faster recovery
1128
+
1129
+ function nextReconnectDelay() {
1130
+ const exp = Math.min(RECONNECT_MAX_MS, RECONNECT_BASE_MS * Math.pow(2, reconnectAttempts));
1131
+ const jitter = exp * (0.75 + Math.random() * 0.5); // 75%–125% of exp
1132
+ return Math.min(RECONNECT_MAX_MS, Math.round(jitter));
1133
+ }
1134
+
1135
+ function sendToServer(message) {
1136
+ if (ws && ws.readyState === WebSocket.OPEN) {
1137
+ ws.send(JSON.stringify(message));
1138
+ }
1139
+ }
1140
+
1141
+ function handleCommand(msg) {
1142
+ const { commandId, accountId, command } = msg;
1143
+ const cmd = command || {};
1144
+ const accountIdStr = String(accountId);
1145
+ const { type, ...rest } = cmd;
1146
+
1147
+ // Phase 20: every lease-bound command carries a credential block (cmd.lease)
1148
+ // with a per-command nonce + leaseId + accountUuid. The agent MUST echo that
1149
+ // binding back on the command-response so the server can prove the response
1150
+ // is a fresh, bound reply (constant-time nonce compare) and not a replay /
1151
+ // cross-device guess. Read-only / discovery commands carry no lease and echo
1152
+ // nothing. We capture it once here and include it on every response path.
1153
+ const echo = {};
1154
+ if (cmd.lease && cmd.lease.nonce) {
1155
+ echo.nonce = String(cmd.lease.nonce);
1156
+ if (cmd.lease.leaseId) echo.leaseId = String(cmd.lease.leaseId);
1157
+ if (cmd.lease.accountUuid) echo.accountUuid = String(cmd.lease.accountUuid);
1158
+ }
1159
+
1160
+ // Phase 3/6: commands that use an active browser session must be bound to
1161
+ // that session's lease. startSession binds a NEW lease (no existing session
1162
+ // to verify against). getStatus is read-only and does not require a lease.
1163
+ const LEASE_REQUIRED = new Set([
1164
+ 'stopSession', 'restartSession', 'refreshSession', 'navigate', 'type',
1165
+ 'paste', 'press', 'click', 'runAction', 'focus',
1166
+ ]);
1167
+
1168
+ (async () => {
1169
+ let result;
1170
+ try {
1171
+ if (LEASE_REQUIRED.has(type)) {
1172
+ const session = activeSessions.get(accountIdStr);
1173
+ const v = leaseClient.verifyCommandLease(session, cmd);
1174
+ if (!v.ok) {
1175
+ // Never reveal whether a guessed leaseId exists; return a generic
1176
+ // authorization error. Still echo the nonce/lease so the server
1177
+ // resolves this (failure) result rather than timing out.
1178
+ result = { success: false, error: 'Command not authorized for this session.' };
1179
+ sendToServer({ type: 'command-response', commandId, result, ...echo });
1180
+ return;
1181
+ }
1182
+ }
1183
+
1184
+ switch (type) {
1185
+ case 'startSession':
1186
+ // Bind the new lease carried by the start command.
1187
+ result = await startSession(accountIdStr, rest.options || {}, rest.lease || cmd.lease);
1188
+ break;
1189
+ case 'stopSession':
1190
+ result = await stopSession(accountIdStr);
1191
+ break;
1192
+ case 'restartSession':
1193
+ result = await restartSession(accountIdStr, rest.options || {}, rest.lease || cmd.lease);
1194
+ break;
1195
+ case 'refreshSession':
1196
+ result = await refreshSession(accountIdStr);
1197
+ break;
1198
+ case 'navigate':
1199
+ // Special case: 'focus' URL means focus the browser window
1200
+ if (rest.url === 'focus') {
1201
+ result = await focusSession(accountIdStr);
1202
+ } else {
1203
+ result = await navigate(accountIdStr, rest.url);
1204
+ }
1205
+ break;
1206
+ case 'type':
1207
+ result = await typeText(accountIdStr, rest.selector, rest.text);
1208
+ break;
1209
+ case 'paste':
1210
+ result = await typeText(accountIdStr, rest.selector, rest.text);
1211
+ break;
1212
+ case 'press':
1213
+ result = await pressKey(accountIdStr, rest.key);
1214
+ break;
1215
+ case 'click':
1216
+ result = await click(accountIdStr, rest.selector, rest.x, rest.y);
1217
+ break;
1218
+ case 'runAction':
1219
+ result = await runActionCommand(accountIdStr, rest.action, rest.payload);
1220
+ break;
1221
+ case 'getStatus': {
1222
+ const session = activeSessions.get(accountIdStr);
1223
+ result = session
1224
+ ? { success: true, status: 'running', url: session.page.url() }
1225
+ : { success: true, status: 'stopped' };
1226
+ break;
1227
+ }
1228
+ case 'importLegacyProfile': {
1229
+ // Phase 15: the ONLY path that pulls a pre-hardening account-<id> profile
1230
+ // forward. Never automatic. The backend has already enforced the
1231
+ // safeguards (recent auth, confirmation, no active lease, conflict check)
1232
+ // before dispatching; the agent performs the data-preserving, atomic,
1233
+ // verified promotion and preserves the original aside.
1234
+ result = importLegacyProfileCommand(accountIdStr, rest.options || {});
1235
+ break;
1236
+ }
1237
+ case 'discoverLegacyProfiles': {
1238
+ // List pre-hardening account-<id> dirs the agent can see, so the
1239
+ // dashboard can offer explicit import. No data is touched.
1240
+ result = { success: true, profiles: discoverLegacyProfiles(PROFILES_DIR) };
1241
+ break;
1242
+ }
1243
+ default:
1244
+ result = { success: false, error: `Unknown command type: ${type}` };
1245
+ }
1246
+ } catch (err) {
1247
+ result = { success: false, error: err.message };
1248
+ if (err.partialFailures) result.partialFailures = err.partialFailures;
1249
+ if (err.failureContext) result.failureContext = err.failureContext;
1250
+ }
1251
+
1252
+ sendToServer({
1253
+ type: 'command-response',
1254
+ commandId,
1255
+ result,
1256
+ ...echo, // Phase 20: echo the lease nonce/binding for lease-bound commands
1257
+ });
1258
+ })();
1259
+ }
1260
+
1261
+ async function connect(serverUrl, token, pairingCode, deviceName, pairingEmail) {
1262
+ // Phase 12: credentials (device token / pairing code) must NEVER travel in
1263
+ // the WebSocket URL — they'd be logged by reverse proxies / CDNs / browser
1264
+ // history. Exchange the credential for a one-time handshake ticket over HTTP
1265
+ // (TLS), then open the WS with ?ticket=<ticket> only. The ticket is
1266
+ // single-use and short-lived, so it is useless if intercepted.
1267
+ const httpBase = String(serverUrl)
1268
+ .replace(/^ws:/i, 'http:')
1269
+ .replace(/^wss:/i, 'https:')
1270
+ // Strip the WS path (e.g. /ws/local-agent) so HTTP endpoints resolve
1271
+ // at the server root, not under the WS path.
1272
+ .replace(/\/ws\/[^/]+$/i, '')
1273
+ .replace(/\/+$/, '');
1274
+
1275
+ // Phase 10: two-level credentials take precedence over the legacy 365d JWT.
1276
+ // A device paired under Phase 10 has a rotating refresh credential
1277
+ // (`config.deviceRefresh`) and a short-lived access JWT
1278
+ // (`config.deviceAccessToken`). Devices paired before Phase 10 still have a
1279
+ // legacy `deviceToken` and keep using it until an acknowledged migration.
1280
+ const twoLevel = !pairingCode && !!config.deviceRefresh;
1281
+ const legacy = !pairingCode && !config.deviceRefresh && !!token;
1282
+
1283
+ let ticket;
1284
+ try {
1285
+ if (pairingCode) {
1286
+ const r = await fetch(`${httpBase}/api/agent/pair`, {
1287
+ method: 'POST',
1288
+ headers: { 'Content-Type': 'application/json' },
1289
+ body: JSON.stringify({
1290
+ pairingCode,
1291
+ deviceName: deviceName || '',
1292
+ // Phase 13: identify the target account so the server can rate-limit
1293
+ // per user / per challenge and reject a valid code that belongs to a
1294
+ // different account. Optional — omitting falls back to per-IP limiting.
1295
+ email: pairingEmail || '',
1296
+ }),
1297
+ });
1298
+ const data = await r.json().catch(() => ({}));
1299
+ if (!r.ok || !data.ticket) throw new Error(data.error || `pairing failed (${r.status})`);
1300
+ // Phase 10: persist the two-level credentials (access JWT + rotating
1301
+ // refresh). The refresh is DPAPI-protected at rest by saveConfig. The
1302
+ // long-lived credential is delivered here over HTTP, never in a WS frame.
1303
+ config.deviceAccessToken = data.deviceAccessToken || null;
1304
+ config.deviceRefresh = data.deviceRefresh || null;
1305
+ config.deviceId = data.deviceId || config.deviceId || null;
1306
+ if (config.deviceAccessToken && config.deviceRefresh) saveConfig(config);
1307
+ ticket = data.ticket;
1308
+ } else if (twoLevel) {
1309
+ // Exchange the short-lived access JWT for a WS ticket; if it has expired,
1310
+ // rotate it via /refresh (rotation-on-use) and retry once.
1311
+ let r = await fetch(`${httpBase}/api/agent/ticket`, {
1312
+ method: 'POST',
1313
+ headers: { 'Content-Type': 'application/json' },
1314
+ body: JSON.stringify({ deviceAccessToken: config.deviceAccessToken, deviceName: deviceName || '' }),
1315
+ });
1316
+ let data = await r.json().catch(() => ({}));
1317
+ if (!r.ok || !data.ticket) {
1318
+ const rr = await fetch(`${httpBase}/api/agent/refresh`, {
1319
+ method: 'POST',
1320
+ headers: { 'Content-Type': 'application/json' },
1321
+ body: JSON.stringify({ deviceRefresh: config.deviceRefresh }),
1322
+ });
1323
+ const rd = await rr.json().catch(() => ({}));
1324
+ if (!rr.ok || !rd.deviceAccessToken) {
1325
+ throw new Error(rd.error || `refresh failed (${rr.status})`);
1326
+ }
1327
+ config.deviceAccessToken = rd.deviceAccessToken;
1328
+ config.deviceRefresh = rd.deviceRefresh || config.deviceRefresh;
1329
+ saveConfig(config);
1330
+ r = await fetch(`${httpBase}/api/agent/ticket`, {
1331
+ method: 'POST',
1332
+ headers: { 'Content-Type': 'application/json' },
1333
+ body: JSON.stringify({ deviceAccessToken: config.deviceAccessToken, deviceName: deviceName || '' }),
1334
+ });
1335
+ data = await r.json().catch(() => ({}));
1336
+ if (!r.ok || !data.ticket) throw new Error(data.error || `ticket request failed (${r.status})`);
1337
+ }
1338
+ ticket = data.ticket;
1339
+ } else if (legacy) {
1340
+ const r = await fetch(`${httpBase}/api/agent/ticket`, {
1341
+ method: 'POST',
1342
+ headers: { 'Content-Type': 'application/json' },
1343
+ body: JSON.stringify({ deviceToken: token, deviceName: deviceName || '' }),
1344
+ });
1345
+ const data = await r.json().catch(() => ({}));
1346
+ if (!r.ok || !data.ticket) throw new Error(data.error || `ticket request failed (${r.status})`);
1347
+ ticket = data.ticket;
1348
+ } else {
1349
+ throw new Error('No device credential or pairing code');
1350
+ }
1351
+ } catch (err) {
1352
+ const msg = String(err.message || err);
1353
+ log(`[agent] Handshake failed: ${msg}`);
1354
+ // A rejected/revoked credential must NOT retry forever with the same dead cred.
1355
+ if (!pairingCode && /Invalid or revoked|revoked device token|family revoked|reuse detected/i.test(msg)) {
1356
+ log('[agent] ❌ Device credential rejected by server. Please re-pair.');
1357
+ return;
1358
+ }
1359
+ scheduleReconnect();
1360
+ return;
1361
+ }
1362
+
1363
+ const url = new URL(serverUrl);
1364
+ url.searchParams.set('ticket', ticket);
1365
+
1366
+ log(`[agent] Connecting to ${serverUrl}...`);
1367
+ ws = new WebSocket(url.toString());
1368
+
1369
+ ws.on('open', () => {
1370
+ log('[agent] WebSocket connected');
1371
+ if (reconnectTimer) { clearTimeout(reconnectTimer); reconnectTimer = null; }
1372
+ reconnectAttempts = 0; // reset backoff after a successful connect
1373
+ restartScheduled = false; // reset auto-restart trigger
1374
+ // Notify updater that we're connected — skip update checks while working
1375
+ if (updater.setWsConnected) updater.setWsConnected(true);
1376
+ });
1377
+
1378
+ ws.on('message', (data) => {
1379
+ let msg;
1380
+ try { msg = JSON.parse(data.toString()); } catch { return; }
1381
+
1382
+ switch (msg.type) {
1383
+ case 'authenticated':
1384
+ log(`[agent] Authenticated! Device ID: ${msg.deviceId}`);
1385
+ // Phase 14: persist this device's immutable UUID so it can be bound into
1386
+ // every profile identity marker (server/tenant/account/DEVICE). It is an
1387
+ // identifier, not a credential, so it is stored as plaintext.
1388
+ if (msg.deviceId && msg.deviceId !== config.deviceId) {
1389
+ config.deviceId = msg.deviceId;
1390
+ saveConfig(config);
1391
+ }
1392
+ // Save the device token for future connections
1393
+ if (msg.deviceToken && msg.deviceToken !== token) {
1394
+ config.deviceToken = msg.deviceToken;
1395
+ saveConfig(config);
1396
+ log('[agent] Device token saved to config');
1397
+ }
1398
+ heartbeatSeconds = msg.heartbeatSeconds || 20;
1399
+ startHeartbeat();
1400
+ // Send initial health report
1401
+ sendHealthReport();
1402
+ break;
1403
+
1404
+ case 'heartbeat-ack':
1405
+ // Heartbeat acknowledged
1406
+ break;
1407
+
1408
+ case 'command':
1409
+ handleCommand(msg);
1410
+ break;
1411
+
1412
+ case 'agent-restart':
1413
+ // Server (or dashboard) asked us to restart the agent connection.
1414
+ // Browser sessions stay open — we only drop and re-establish the WS.
1415
+ log('[agent] Restart requested by server — reconnecting WebSocket...');
1416
+ handleAgentRestart();
1417
+ break;
1418
+
1419
+ case 'device_token_rotated':
1420
+ // Phase 11: the server rotated our LEGACY device credential. Persist the
1421
+ // new token (DPAPI-protected at rest via saveConfig) and reconnect. The
1422
+ // old token has been revoked server-side, so we MUST switch.
1423
+ if (msg.deviceToken && msg.deviceToken !== token) {
1424
+ config.deviceToken = msg.deviceToken;
1425
+ saveConfig(config);
1426
+ token = msg.deviceToken;
1427
+ log('[agent] Device token rotated by server — reconnecting with new token');
1428
+ // Drop the current WS; the close handler schedules a reconnect that
1429
+ // reads the freshly-saved config.deviceToken (now `token`).
1430
+ try { ws.close(4001, 'Token rotated locally'); } catch {}
1431
+ }
1432
+ break;
1433
+
1434
+ case 'device_credentials_rotating':
1435
+ // Phase 11: ack-then-activate. The server has minted a new credential
1436
+ // pair and is waiting for us to acknowledge we have persisted it BEFORE
1437
+ // it revokes the old one. Persist the new pair now (the refresh is
1438
+ // DPAPI-protected at rest by saveConfig), keep the previous credential
1439
+ // so we can revert on an abort, then send the ack. The server closes
1440
+ // this WS once it activates; we then reconnect with the new pair.
1441
+ if (msg.deviceAccessToken && msg.deviceRefresh && msg.rotationId) {
1442
+ _preRotationCreds = {
1443
+ deviceAccessToken: config.deviceAccessToken,
1444
+ deviceRefresh: config.deviceRefresh,
1445
+ };
1446
+ config.deviceAccessToken = msg.deviceAccessToken;
1447
+ config.deviceRefresh = msg.deviceRefresh;
1448
+ saveConfig(config);
1449
+ log('[agent] Staged rotated credentials; sending ack');
1450
+ sendToServer({ type: 'device_credentials_acked', rotationId: msg.rotationId });
1451
+ }
1452
+ break;
1453
+
1454
+ case 'device_credentials_activated':
1455
+ // The server committed the rotation (old credential revoked). The new
1456
+ // pair we staged is now authoritative; drop the revert buffer. The server
1457
+ // closes the WS right after this; the close handler reconnects with the
1458
+ // new credentials.
1459
+ _preRotationCreds = null;
1460
+ log('[agent] Credential rotation activated by server');
1461
+ break;
1462
+
1463
+ case 'device_credentials_rotation_aborted':
1464
+ // The server did NOT activate (our ack didn't arrive in time, or the WS
1465
+ // dropped). The old credential is still valid server-side, so revert to
1466
+ // it — otherwise we'd be left holding a new refresh the server never set
1467
+ // as current and would be orphaned after the access JWT expires.
1468
+ if (_preRotationCreds) {
1469
+ config.deviceAccessToken = _preRotationCreds.deviceAccessToken;
1470
+ config.deviceRefresh = _preRotationCreds.deviceRefresh;
1471
+ saveConfig(config);
1472
+ _preRotationCreds = null;
1473
+ log('[agent] Credential rotation aborted by server — reverted to previous credentials');
1474
+ }
1475
+ break;
1476
+
1477
+ case 'report-sessions':
1478
+ // Phase 5: server (on reconnect) asks which sessions are still active.
1479
+ // Report each with its lease credential so the server can reconcile
1480
+ // durable recovery_required leases (prove active → restore).
1481
+ sendToServer({ type: 'sessions-report', sessions: leaseClient.sessionsReport(activeSessions) });
1482
+ break;
1483
+
1484
+ default:
1485
+ log(`[agent] Unknown message: ${msg.type}`);
1486
+ }
1487
+ });
1488
+
1489
+ ws.on('close', (code, reason) => {
1490
+ const reasonStr = reason ? reason.toString() : '';
1491
+ log(`[agent] Disconnected: ${code} ${reasonStr}`);
1492
+ stopHeartbeat();
1493
+
1494
+ // Notify updater that we're disconnected — allow update checks now
1495
+ if (updater.setWsConnected) updater.setWsConnected(false);
1496
+
1497
+ // A WS disconnect means the server can no longer reach us. Immediately
1498
+ // close every open browser session so no account is left with a live
1499
+ // browser on a disconnected agent. This also lets the server release the
1500
+ // leases and makes the accounts re-launchable right away.
1501
+ closeAllSessions();
1502
+
1503
+ if (code === 4003) {
1504
+ // Auth failure — don't reconnect with same token
1505
+ log('[agent] ❌ Authentication failed. Please re-pair.');
1506
+ return;
1507
+ }
1508
+
1509
+ // Check if this is a 502/503 server error
1510
+ if (reasonStr.includes('502') || reasonStr.includes('503')) {
1511
+ log(`[agent] ⚠️ Server temporarily unavailable (${reasonStr}). This is normal during server restarts.`);
1512
+ log(`[agent] ✅ Auto-recovery active: Will reconnect automatically or self-restart after 12 attempts (~5 min)`);
1513
+ log(`[agent] 💡 Tip: You can also manually restart the agent if needed`);
1514
+ }
1515
+
1516
+ // Auto-reconnect after 5 seconds
1517
+ scheduleReconnect();
1518
+ });
1519
+
1520
+ ws.on('error', (err) => {
1521
+ const errMsg = err.message || String(err);
1522
+ if (errMsg.includes('502') || errMsg.includes('503')) {
1523
+ log(`[agent] ⚠️ Server returned ${errMsg} — temporarily unavailable, will retry...`);
1524
+ } else {
1525
+ log(`[agent] WebSocket error: ${errMsg}`);
1526
+ }
1527
+ });
1528
+ }
1529
+
1530
+ function startHeartbeat() {
1531
+ stopHeartbeat();
1532
+ // Send heartbeat more frequently than the server's timeout to keep WebSocket alive
1533
+ const interval = Math.min(heartbeatSeconds, 10) * 1000;
1534
+ heartbeatTimer = setInterval(() => {
1535
+ // Send application-level heartbeat
1536
+ sendToServer({ type: 'heartbeat', health: getHealthData() });
1537
+ // Also send WebSocket ping to keep connection alive through proxies
1538
+ if (ws && ws.readyState === WebSocket.OPEN) {
1539
+ try { ws.ping(); } catch {}
1540
+ }
1541
+ }, interval);
1542
+ }
1543
+
1544
+ function stopHeartbeat() {
1545
+ if (heartbeatTimer) { clearInterval(heartbeatTimer); heartbeatTimer = null; }
1546
+ }
1547
+
1548
+ /**
1549
+ * Restart the agent's WebSocket connection (does NOT touch browser sessions).
1550
+ * Used by the dashboard "Restart Agent" button to recover stuck state.
1551
+ */
1552
+ function handleAgentRestart() {
1553
+ try {
1554
+ // Mark this as a manual restart so we don't wait for the delayed auto-reconnect
1555
+ if (reconnectTimer) { clearTimeout(reconnectTimer); reconnectTimer = null; }
1556
+ stopHeartbeat();
1557
+ if (ws) {
1558
+ try { ws.removeAllListeners('close'); } catch {}
1559
+ try { ws.close(1000, 'agent-restart'); } catch {}
1560
+ ws = null;
1561
+ }
1562
+ } catch (err) {
1563
+ log(`[agent] Restart cleanup error: ${err.message}`);
1564
+ }
1565
+ // Reconnect almost immediately using the saved device credential (two-level
1566
+ // refresh takes precedence over the legacy device token).
1567
+ if (config.serverUrl && (config.deviceRefresh || config.deviceToken)) {
1568
+ log('[agent] Reconnecting in 1s...');
1569
+ setTimeout(() => {
1570
+ try {
1571
+ connect(config.serverUrl, config.deviceAccessToken || config.deviceToken, null, os.hostname());
1572
+ } catch (err) {
1573
+ log(`[agent] Reconnect failed: ${err.message}`);
1574
+ scheduleReconnect();
1575
+ }
1576
+ }, 1000);
1577
+ } else {
1578
+ log('[agent] No saved credential — restart skipped. Please re-pair the device.');
1579
+ }
1580
+ }
1581
+
1582
+ // ── Health report ────────────────────────────────────────────────────────────
1583
+ const AGENT_VERSION = '1.1.0';
1584
+ let currentAction = null;
1585
+ let lastError = null;
1586
+
1587
+ function getHealthData() {
1588
+ const browserOk = checkBrowserAvailable();
1589
+ return {
1590
+ agentVersion: AGENT_VERSION,
1591
+ platform: process.platform,
1592
+ arch: process.arch,
1593
+ hostname: os.hostname(),
1594
+ chromiumAvailable: browserOk,
1595
+ browserStatus: browserOk ? 'ready' : 'missing',
1596
+ activeSessions: activeSessions.size,
1597
+ currentAction: currentAction || null,
1598
+ lastError: lastError || null,
1599
+ lastHeartbeat: new Date().toISOString(),
1600
+ };
1601
+ }
1602
+
1603
+ function sendHealthReport() {
1604
+ sendToServer({ type: 'health', health: getHealthData() });
1605
+ }
1606
+
1607
+ function getFirefoxPaths() {
1608
+ return {
1609
+ win32: [
1610
+ 'C:\\Program Files\\Mozilla Firefox\\firefox.exe',
1611
+ 'C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe',
1612
+ ],
1613
+ darwin: ['/Applications/Firefox.app/Contents/MacOS/firefox'],
1614
+ linux: ['/usr/bin/firefox', '/usr/bin/firefox-esr', '/snap/bin/firefox'],
1615
+ };
1616
+ }
1617
+
1618
+ /**
1619
+ * Return the path to the system-installed Firefox executable, or undefined
1620
+ * if not found. Used as last-resort fallback when neither Playwright's
1621
+ * bundled Firefox nor the auto-downloaded Firefox is available.
1622
+ */
1623
+ function getSystemFirefoxPath() {
1624
+ try {
1625
+ const paths = getFirefoxPaths()[process.platform] || [];
1626
+ for (const p of paths) {
1627
+ if (fs.existsSync(p)) return p;
1628
+ }
1629
+ } catch {}
1630
+ return undefined;
1631
+ }
1632
+
1633
+ // ── Playwright Firefox auto-download ─────────────────────────────────────────
1634
+ // The pkg-packaged .exe can't use Playwright's bundled Firefox (the path
1635
+ // resolves inside the pkg snapshot which doesn't exist). Instead, on first
1636
+ // run we download Playwright's patched Windows Firefox build from the CDN
1637
+ // into the data directory (~/.xkwdstore-agent/firefox/firefox/firefox.exe).
1638
+ // This is a one-time ~120 MB download, cached permanently.
1639
+ const PW_FIREFOX_DIR = path.join(DATA_DIR, 'firefox');
1640
+ const PW_FIREFOX_EXE = path.join(PW_FIREFOX_DIR, 'firefox', 'firefox.exe');
1641
+
1642
+ function getPlaywrightFirefoxPath() {
1643
+ if (fs.existsSync(PW_FIREFOX_EXE)) return PW_FIREFOX_EXE;
1644
+ return undefined;
1645
+ }
1646
+
1647
+ /**
1648
+ * Ensure Playwright's patched Firefox is available in the data directory.
1649
+ * Downloads + extracts it on first run. Returns the path to firefox.exe.
1650
+ * Subsequent calls are instant (checks if file exists).
1651
+ */
1652
+ async function ensurePlaywrightFirefox() {
1653
+ // 1. Already downloaded — instant return
1654
+ if (fs.existsSync(PW_FIREFOX_EXE)) {
1655
+ return PW_FIREFOX_EXE;
1656
+ }
1657
+
1658
+ // 2. Try Playwright's bundled path (works when running from source)
1659
+ try {
1660
+ const bundled = firefox.executablePath();
1661
+ if (bundled && fs.existsSync(bundled)) {
1662
+ // Copy into data dir so it persists
1663
+ const srcDir = path.dirname(bundled); // .../firefox-XXXX/firefox
1664
+ const destDir = path.join(PW_FIREFOX_DIR, 'firefox');
1665
+ fs.mkdirSync(PW_FIREFOX_DIR, { recursive: true });
1666
+ copyDirSync(srcDir, destDir);
1667
+ log(`[agent] Playwright Firefox copied from cache to ${PW_FIREFOX_EXE}`);
1668
+ return PW_FIREFOX_EXE;
1669
+ }
1670
+ } catch {}
1671
+
1672
+ // 3. Download from CDN (first run on customer PC)
1673
+ const browsersJson = JSON.parse(
1674
+ fs.readFileSync(path.join(__dirname, '..', 'node_modules', 'playwright-core', 'browsers.json'), 'utf8')
1675
+ );
1676
+ const ff = browsersJson.browsers.find(b => b.name === 'firefox');
1677
+ if (!ff) throw new Error('Firefox not registered in playwright-core');
1678
+ const revision = ff.revision;
1679
+ const downloadUrl = `https://cdn.playwright.dev/builds/firefox/${revision}/firefox-win64.zip`;
1680
+
1681
+ console.log('');
1682
+ console.log(' ⏳ First run: downloading Playwright Firefox (~120 MB, one-time)...');
1683
+ console.log(` URL: ${downloadUrl}`);
1684
+ console.log('');
1685
+
1686
+ const tmpZip = path.join(DATA_DIR, 'firefox-download.zip');
1687
+ await downloadFileWithProgress(downloadUrl, tmpZip);
1688
+
1689
+ // Extract
1690
+ fs.mkdirSync(PW_FIREFOX_DIR, { recursive: true });
1691
+ const tmpExtract = path.join(DATA_DIR, 'firefox-extract-tmp');
1692
+ fs.rmSync(tmpExtract, { recursive: true, force: true });
1693
+ fs.mkdirSync(tmpExtract, { recursive: true });
1694
+
1695
+ console.log(' ⏳ Extracting...');
1696
+ extractZip(tmpZip, tmpExtract);
1697
+
1698
+ // The zip contains a "firefox/" folder — move it into place
1699
+ const extractedFirefox = path.join(tmpExtract, 'firefox');
1700
+ if (fs.existsSync(extractedFirefox)) {
1701
+ fs.rmSync(path.join(PW_FIREFOX_DIR, 'firefox'), { recursive: true, force: true });
1702
+ fs.renameSync(extractedFirefox, path.join(PW_FIREFOX_DIR, 'firefox'));
1703
+ } else {
1704
+ // Files at root of zip
1705
+ fs.renameSync(tmpExtract, path.join(PW_FIREFOX_DIR, 'firefox'));
1706
+ }
1707
+
1708
+ // Cleanup
1709
+ try { fs.unlinkSync(tmpZip); } catch {}
1710
+ try { fs.rmSync(tmpExtract, { recursive: true, force: true }); } catch {}
1711
+
1712
+ if (!fs.existsSync(PW_FIREFOX_EXE)) {
1713
+ throw new Error('Firefox extraction failed — firefox.exe not found after extract');
1714
+ }
1715
+
1716
+ const sizeMB = (getDirSizeSync(PW_FIREFOX_DIR) / 1024 / 1024).toFixed(0);
1717
+ console.log(` ✓ Playwright Firefox installed (${sizeMB} MB) — cached for future runs`);
1718
+ console.log('');
1719
+ log(`[agent] Playwright Firefox downloaded to ${PW_FIREFOX_EXE} (${sizeMB} MB)`);
1720
+ return PW_FIREFOX_EXE;
1721
+ }
1722
+
1723
+ /**
1724
+ * Resolve the best available Firefox executable path.
1725
+ * Priority: Playwright patched (auto-downloaded) > Playwright bundled > system.
1726
+ */
1727
+ function resolveChromiumPath() {
1728
+ // 1. Try system Chrome (most stealthy — real Chrome, not Chromium)
1729
+ const chromePaths = {
1730
+ win32: [
1731
+ 'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe',
1732
+ 'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe',
1733
+ path.join(os.homedir(), 'AppData\\Local\\Google\\Chrome\\Application\\chrome.exe'),
1734
+ ],
1735
+ darwin: ['/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'],
1736
+ linux: ['/usr/bin/google-chrome', '/usr/bin/google-chrome-stable', '/usr/bin/chromium', '/usr/bin/chromium-browser'],
1737
+ };
1738
+ const paths = chromePaths[process.platform] || [];
1739
+ for (const p of paths) {
1740
+ if (fs.existsSync(p)) {
1741
+ log(`[browser] Using system Chrome: ${p}`);
1742
+ return p;
1743
+ }
1744
+ }
1745
+
1746
+ // 2. Try Playwright's bundled Chromium
1747
+ try {
1748
+ const { chromium } = require('playwright');
1749
+ const bundled = chromium.executablePath();
1750
+ if (bundled && fs.existsSync(bundled)) {
1751
+ log(`[browser] Using Playwright bundled Chromium: ${bundled}`);
1752
+ return bundled;
1753
+ }
1754
+ } catch {}
1755
+
1756
+ // 3. Fallback: let Playwright auto-resolve
1757
+ log(`[browser] No system Chrome found — using Playwright default Chromium`);
1758
+ return undefined;
1759
+ }
1760
+
1761
+ function checkBrowserAvailable() {
1762
+ // Check system Chrome
1763
+ const chromePaths = {
1764
+ win32: [
1765
+ 'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe',
1766
+ 'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe',
1767
+ ],
1768
+ darwin: ['/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'],
1769
+ linux: ['/usr/bin/google-chrome', '/usr/bin/google-chrome-stable'],
1770
+ };
1771
+ const paths = chromePaths[process.platform] || [];
1772
+ for (const p of paths) {
1773
+ if (fs.existsSync(p)) return true;
1774
+ }
1775
+ // Check Playwright's bundled Chromium
1776
+ try {
1777
+ const { chromium } = require('playwright');
1778
+ const bundled = chromium.executablePath();
1779
+ if (bundled && fs.existsSync(bundled)) return true;
1780
+ } catch {}
1781
+ return false;
1782
+ }
1783
+
1784
+ /**
1785
+ * Detect the installed Chrome version.
1786
+ * Returns a version string like "125" or null if detection fails.
1787
+ */
1788
+ function detectChromeVersion() {
1789
+ try {
1790
+ const chromePaths = {
1791
+ win32: [
1792
+ 'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe',
1793
+ 'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe',
1794
+ ],
1795
+ darwin: ['/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'],
1796
+ linux: ['/usr/bin/google-chrome', '/usr/bin/google-chrome-stable'],
1797
+ };
1798
+ const paths = chromePaths[process.platform] || [];
1799
+ const exePath = paths.find(p => fs.existsSync(p));
1800
+ if (!exePath) return null;
1801
+ const { execSync } = require('child_process');
1802
+ const output = execSync(`"${exePath}" --version`, { timeout: 5000, encoding: 'utf-8' });
1803
+ const match = output.match(/Chrome\s+(\d+)/i);
1804
+ return match ? match[1] : null;
1805
+ } catch { return null; }
1806
+ }
1807
+
1808
+ // Detect Chrome version once at startup
1809
+ const DETECTED_CHROME_VERSION = detectChromeVersion();
1810
+
1811
+ function scheduleReconnect() {
1812
+ if (reconnectTimer) return;
1813
+ reconnectAttempts += 1;
1814
+ const delay = nextReconnectDelay();
1815
+ log(`[agent] Scheduling reconnect in ${delay}ms (attempt ${reconnectAttempts})`);
1816
+ reconnectTimer = setTimeout(() => {
1817
+ reconnectTimer = null;
1818
+ if (config.serverUrl && (config.deviceRefresh || config.deviceToken)) {
1819
+ log(`[agent] Reconnecting to ${config.serverUrl}...`);
1820
+ connect(config.serverUrl, config.deviceAccessToken || config.deviceToken, null, os.hostname());
1821
+ }
1822
+ }, delay);
1823
+
1824
+ // ── Auto-restart: if we've failed too many times in a row, force a clean restart ──
1825
+ // This recovers from "stuck" states where the WS keeps getting 502/closed.
1826
+ // After 12 failed attempts (~5+ minutes of retries), trigger a self-restart
1827
+ // which will check for updates first, then relaunch the agent fresh.
1828
+ // IMPORTANT: We track the last restart time to prevent restart loops.
1829
+ if (reconnectAttempts >= 12 && !restartScheduled && !recentlyRestarted()) {
1830
+ restartScheduled = true;
1831
+ recordRestartTime();
1832
+ log(`[agent] ⚠️ Too many failed reconnects (${reconnectAttempts}) — server may be restarting. Self-restart in 30s...`);
1833
+ setTimeout(() => {
1834
+ log(`[agent] 🔄 Force restarting agent to recover from server unavailability...`);
1835
+ if (updater.forceCheckAndRestart) {
1836
+ updater.forceCheckAndRestart(`Excessive reconnect failures (${reconnectAttempts})`).catch(e => {
1837
+ log(`[agent] forceCheckAndRestart failed: ${e.message}`);
1838
+ if (updater.triggerSelfRestart) updater.triggerSelfRestart();
1839
+ });
1840
+ } else if (updater.triggerSelfRestart) {
1841
+ updater.triggerSelfRestart();
1842
+ }
1843
+ }, 30 * 1000);
1844
+ }
1845
+ }
1846
+
1847
+ // Track restart attempts to prevent infinite restart loops
1848
+ const _lastRestartAt = { value: 0 };
1849
+ const RESTART_COOLDOWN_MS = 10 * 60 * 1000; // 10 minutes between auto-restarts
1850
+
1851
+ function recentlyRestarted() {
1852
+ return Date.now() - _lastRestartAt.value < RESTART_COOLDOWN_MS;
1853
+ }
1854
+
1855
+ function recordRestartTime() {
1856
+ _lastRestartAt.value = Date.now();
1857
+ }
1858
+
1859
+ let restartScheduled = false;
1860
+
1861
+ // ── Interactive CLI ──────────────────────────────────────────────────────────
1862
+
1863
+ const readline = require('readline');
1864
+
1865
+ function prompt(question) {
1866
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
1867
+ return new Promise(resolve => {
1868
+ rl.question(question, answer => {
1869
+ rl.close();
1870
+ resolve(answer.trim());
1871
+ });
1872
+ });
1873
+ }
1874
+
1875
+ async function main() {
1876
+ console.log('');
1877
+ console.log('╔══════════════════════════════════════════════════╗');
1878
+ console.log('║ XKWDStore Agent v' + AGENT_VERSION + ' ║');
1879
+ console.log('║ Browser runs on your PC (Chrome / Chromium)║');
1880
+ console.log('╚══════════════════════════════════════════════════╝');
1881
+ console.log('');
1882
+
1883
+ // ── Step 1: Ensure Chromium/Chrome is available ──
1884
+ // On first run, this downloads Playwright's Chromium (~150 MB, one-time).
1885
+ // If system Google Chrome is installed, it will be used instead (more stealthy).
1886
+ let browserOk = checkBrowserAvailable();
1887
+ if (!browserOk) {
1888
+ try {
1889
+ console.log('Downloading Playwright Chromium (~150 MB, one-time)...');
1890
+ const { execSync } = require('child_process');
1891
+ execSync('npx playwright install chromium', { stdio: 'inherit', timeout: 10 * 60 * 1000 });
1892
+ browserOk = true;
1893
+ } catch (e) {
1894
+ console.log('✗ Could not download Playwright Chromium: ' + e.message);
1895
+ console.log(' Please install Google Chrome manually, then restart the agent.');
1896
+ console.log('');
1897
+ }
1898
+ }
1899
+ if (browserOk) {
1900
+ console.log('✓ Chrome/Chromium ready — Browser Ready');
1901
+ } else {
1902
+ console.log('✗ Google Chrome or Chromium is required.');
1903
+ console.log(' Please install Google Chrome or Chromium, then restart XKWDStore Agent.');
1904
+ console.log(' Download: https://www.google.com/chrome/ or https://www.chromium.org/');
1905
+ console.log('');
1906
+ console.log('Agent will continue running but browser sessions will fail until Chrome/Chromium is installed.');
1907
+ console.log('');
1908
+ }
1909
+
1910
+ // Parse command line args
1911
+ const args = process.argv.slice(2);
1912
+ const pairArg = args.find(a => a.startsWith('--pair='));
1913
+ const serverArg = args.find(a => a.startsWith('--server='));
1914
+
1915
+ // ── Step 2: Check server URL ──
1916
+ let serverUrl = serverArg ? serverArg.split('=')[1] : config.serverUrl;
1917
+ if (!serverUrl) {
1918
+ serverUrl = await prompt('Enter KWDStore server URL (e.g. wss://x.kwdstore.com): ');
1919
+ if (!serverUrl) {
1920
+ console.log('Server URL is required.');
1921
+ process.exit(1);
1922
+ }
1923
+ if (!serverUrl.startsWith('ws://') && !serverUrl.startsWith('wss://')) {
1924
+ serverUrl = serverUrl.replace(/^http/, 'ws');
1925
+ }
1926
+ config.serverUrl = serverUrl;
1927
+ saveConfig(config);
1928
+ }
1929
+
1930
+ // Append WS path if not present
1931
+ if (!serverUrl.includes('/ws/local-agent')) {
1932
+ serverUrl = serverUrl.replace(/\/+$/, '') + '/ws/local-agent';
1933
+ }
1934
+
1935
+ console.log(`Server: ${serverUrl}`);
1936
+ console.log(`Device: ${os.hostname()}`);
1937
+ console.log(`Chrome: ${browserOk ? 'Ready' : 'Missing'}`);
1938
+ console.log('');
1939
+
1940
+ // ── Auto-updater ───────────────────────────────────────────────────────────
1941
+ // Polls manifest.json on GitHub (raw URL) every ~10 min. When a newer
1942
+ // version is published, downloads the new .exe from GitHub Releases,
1943
+ // verifies SHA256, swaps the .exe, and relaunches.
1944
+ // Enabled by default in the packaged .exe.
1945
+ const autoUpdateEnabled = process.pkg;
1946
+ if (autoUpdateEnabled) {
1947
+ const agentDir = path.dirname(process.execPath);
1948
+ updater.start({
1949
+ serverUrl,
1950
+ agentDir,
1951
+ onShutdownRequest: () => shutdown(),
1952
+ });
1953
+ } else {
1954
+ log('[updater] Disabled (running from source, not packaged .exe)');
1955
+ }
1956
+
1957
+ // ── Step 3: Check device credential or pair ──
1958
+ if ((config.deviceRefresh || config.deviceToken) && !pairArg) {
1959
+ console.log('✓ Found saved device credential. Connecting...');
1960
+ connect(serverUrl, config.deviceAccessToken || config.deviceToken, null, os.hostname());
1961
+ return;
1962
+ }
1963
+
1964
+ // Need to pair
1965
+ let pairingCode = pairArg ? pairArg.split('=')[1] : null;
1966
+ let pairingEmail = null;
1967
+ if (!pairingCode) {
1968
+ console.log('No device credential found. You need to pair this device.');
1969
+ console.log('Go to your KWDStore dashboard → Pair Agent → get a pairing code.');
1970
+ console.log('');
1971
+ // Phase 13: the dashboard shows your account email alongside the code.
1972
+ // Enter both so the server can rate-limit per user / per challenge and
1973
+ // reject a code that belongs to a different account.
1974
+ pairingEmail = await prompt('Enter your account email: ');
1975
+ pairingCode = await prompt('Enter pairing code: ');
1976
+ if (!pairingCode) {
1977
+ console.log('Pairing code is required.');
1978
+ process.exit(1);
1979
+ }
1980
+ }
1981
+
1982
+ console.log(`Pairing with code ${pairingCode}...`);
1983
+ connect(serverUrl, null, pairingCode, os.hostname(), pairingEmail);
1984
+ }
1985
+
1986
+ // ── Graceful shutdown ────────────────────────────────────────────────────────
1987
+
1988
+ async function shutdown() {
1989
+ log('[agent] Shutting down...');
1990
+ try { updater.stop(); } catch {}
1991
+ stopHeartbeat();
1992
+ if (reconnectTimer) clearTimeout(reconnectTimer);
1993
+
1994
+ // Close all browser sessions
1995
+ for (const [accountId] of activeSessions) {
1996
+ await stopSession(accountId);
1997
+ }
1998
+
1999
+ if (ws) {
2000
+ try { ws.close(1000, 'Agent shutting down'); } catch {}
2001
+ }
2002
+ process.exit(0);
2003
+ }
2004
+
2005
+ process.on('SIGINT', shutdown);
2006
+ process.on('SIGTERM', shutdown);
2007
+
2008
+ // ── Start ────────────────────────────────────────────────────────────────────
2009
+
2010
+ main().catch(err => {
2011
+ console.error('Failed to start agent:', err.message);
2012
+ process.exit(1);
2013
+ });