@xkwdstore/agent 2.0.1 → 2.0.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.
@@ -1,453 +1,619 @@
1
- 'use strict';
2
-
3
- /**
4
- * Phase 10 — Browser session handler (protocol v2).
5
- *
6
- * Defect 8 fix: Handle the existing hardened command envelope:
7
- * { type: 'command', commandId, accountId, command: { type, ...rest, lease? },
8
- * nonce?, leaseId?, accountUuid? }
9
- *
10
- * Defect 9 fix: Reuse the existing hardened browser runtime from index.js
11
- * (actions, proxy fail-closed, media blocking, profile identity, lease client,
12
- * cookie handling, etc.) rather than maintaining a second divergent runtime.
13
- *
14
- * The agent validates the complete inbound frame, reads the action type from
15
- * the canonical command object, preserves command and lease expiry, echoes
16
- * commandId/nonce/leaseId/accountUuid, returns results under the canonical
17
- * `result` field, and rejects unknown command types.
18
- */
19
-
20
- const { chromium } = require('playwright-core');
21
-
22
- // Import the existing hardened runtime modules (Defect 9).
23
- const { generateFingerprint } = require('./fingerprint');
24
- const fingerprintStore = require('./fingerprintStore');
25
- const { resolveProfileDir, importLegacyProfile, discoverLegacyProfiles } = require('./profilePath');
26
- const { buildStealthScript } = require('./stealth');
27
- const leaseClient = require('./leaseClient');
28
- const { PROFILES_DIR } = require('./deviceKeyStore');
29
-
30
- // Active sessions: accountId -> { context, page, profileDir }
31
- const activeSessions = new Map();
32
-
33
- // Per-runtime state (B4 fix): each setupSessionHandler call creates a fresh
34
- // runtime object so a newly initialized handler starts connected and does
35
- // NOT inherit stale state from a prior handler lifecycle. The module-level
36
- // `currentRuntime` is only used so markDisconnected() / closeAllSessions()
37
- // (called from cli.js) can reach the active runtime without an explicit
38
- // handle. One handler disconnecting cannot poison another handler's runtime.
39
- const currentRuntime = { disconnected: false, sessions: activeSessions };
40
-
41
- /**
42
- * Mark the CURRENT runtime as disconnected. After this, every inbound command
43
- * for that runtime is rejected with a clear error and no new browser work is
44
- * performed. A new setupSessionHandler call creates a fresh runtime that
45
- * starts connected.
46
- */
47
- function markDisconnected() {
48
- currentRuntime.disconnected = true;
49
- }
50
-
51
- /**
52
- * Close every active browser context, preserving profile/cookies through the
53
- * existing safe persistence path (the context close flushes the persistent
54
- * profile dir). Clears the active-sessions map. Safe to call multiple times.
55
- * Operates on the current runtime's sessions.
56
- *
57
- * @returns {Promise<{ closed: number }>}
58
- */
59
- async function closeAllSessions() {
60
- const sessions = currentRuntime.sessions || activeSessions;
61
- const keys = Array.from(sessions.keys());
62
- let closed = 0;
63
- for (const accountId of keys) {
64
- const session = sessions.get(accountId);
65
- if (!session) continue;
66
- // Delete BEFORE closing so a concurrent call does not double-close.
67
- sessions.delete(accountId);
68
- try {
69
- if (session.context) await session.context.close().catch(() => {});
70
- } catch {}
71
- closed += 1;
72
- }
73
- return { closed };
74
- }
75
-
76
- /**
77
- * Set up the session handler on an authenticated WebSocket.
78
- *
79
- * @param {WebSocket} ws — authenticated v2 WebSocket
80
- * @param {object} opts — { chromePath, deviceMeta, serverOrigin }
81
- * @returns {Map} the active sessions map
82
- */
83
- function setupSessionHandler(ws, opts) {
84
- // B4 fix: reset the per-runtime state so a newly initialized handler starts
85
- // connected and does NOT inherit stale state from a prior handler lifecycle.
86
- // The module-level `currentRuntime` is shared so cli.js's markDisconnected()
87
- // / closeAllSessions() reach the active runtime. Each setupSessionHandler
88
- // call resets it to connected.
89
- currentRuntime.disconnected = false;
90
- currentRuntime.sessions = activeSessions;
91
-
92
- ws.on('message', (data, isBinary) => {
93
- if (isBinary) return;
94
-
95
- let msg;
96
- try {
97
- msg = JSON.parse(data.toString('utf8'));
98
- } catch {
99
- return;
100
- }
101
-
102
- if (!msg || typeof msg !== 'object') return;
103
-
104
- // Handle the existing hardened command envelope (Defect 8).
105
- if (msg.type === 'command') {
106
- // Fail-safe: after the authenticated WebSocket closed, no further commands
107
- // may be accepted. A stale/zombie socket must never drive a browser.
108
- if (currentRuntime.disconnected) {
109
- const echo = _extractEcho(msg);
110
- try {
111
- ws.send(JSON.stringify({
112
- type: 'command-response',
113
- commandId: msg.commandId,
114
- result: { success: false, error: 'Agent disconnected: commands no longer accepted' },
115
- ...echo,
116
- }));
117
- } catch {}
118
- return;
119
- }
120
- _handleCommandEnvelope(ws, msg, opts).catch((err) => {
121
- // Send error response with echo (never leak secrets).
122
- const echo = _extractEcho(msg);
123
- try {
124
- ws.send(JSON.stringify({
125
- type: 'command-response',
126
- commandId: msg.commandId,
127
- result: { success: false, error: _safeError(err) },
128
- ...echo,
129
- }));
130
- } catch {}
131
- });
132
- return;
133
- }
134
-
135
- // Handle heartbeats.
136
- if (msg.type === 'heartbeat') {
137
- try { ws.send(JSON.stringify({ type: 'heartbeat-ack' })); } catch {}
138
- return;
139
- }
140
-
141
- // Reconnect reconciliation: the server asks for an active-sessions report.
142
- // Each entry is lease-bound (accountUuid + leaseId + leaseToken + status).
143
- // A missing/invalid status is NEVER defaulted to 'running' — the server
144
- // treats an unverified entry as unresolved (the lease stays blocking).
145
- if (msg.type === 'report-sessions') {
146
- try {
147
- const sessions = [];
148
- for (const [accountId, session] of activeSessions) {
149
- const lease = (session.lease && typeof session.lease.getClientView === 'function')
150
- ? session.lease.getClientView()
151
- : (session.lease || null);
152
- sessions.push({
153
- accountId,
154
- accountUuid: session.accountUuid || null,
155
- leaseId: (lease && lease.leaseId) || null,
156
- leaseToken: (lease && lease.leaseToken) || null,
157
- status: session.context ? 'running' : 'stopped',
158
- });
159
- }
160
- ws.send(JSON.stringify({ type: 'sessions-report', sessions }));
161
- } catch {}
162
- return;
163
- }
164
-
165
- // session-status ack: the server confirms a stop was verified. No-op here
166
- // beyond acknowledging; the lease stays under server authority.
167
- if (msg.type === 'session-status') {
168
- try { ws.send(JSON.stringify({ type: 'session-status-ack', commandId: msg.commandId || null })); } catch {}
169
- return;
170
- }
171
-
172
- // Other message types (session-status, sessions-report, log) are handled
173
- // by the shared engine on the backend side — the agent only needs to
174
- // respond to commands and heartbeats.
175
- });
176
-
177
- return activeSessions;
178
- }
179
-
180
- /**
181
- * Handle a command envelope: { type: 'command', commandId, accountId, command: { type, ... } }
182
- *
183
- * This delegates to the same session management logic used by the legacy agent,
184
- * preserving all hardened safeguards (Defect 9).
185
- */
186
- async function _handleCommandEnvelope(ws, msg, opts) {
187
- const { commandId, accountId, command } = msg;
188
-
189
- if (!commandId || typeof commandId !== 'string') {
190
- return; // Malformed — drop silently.
191
- }
192
- if (!command || typeof command !== 'object') {
193
- _sendResponse(ws, msg, { success: false, error: 'Missing command object' });
194
- return;
195
- }
196
-
197
- const { type, ...rest } = command;
198
-
199
- // Build the echo object from the envelope (nonce, leaseId, accountUuid).
200
- const echo = _extractEcho(msg);
201
-
202
- // Validate command type against the known allowlist.
203
- const ALLOWED_TYPES = new Set([
204
- 'startSession', 'stopSession', 'restartSession', 'refreshSession',
205
- 'navigate', 'type', 'paste', 'press', 'click', 'runAction',
206
- 'getStatus', 'importLegacyProfile', 'discoverLegacyProfiles',
207
- 'focus',
208
- ]);
209
-
210
- if (!ALLOWED_TYPES.has(type)) {
211
- _sendResponse(ws, msg, { success: false, error: 'Unknown command type' });
212
- return;
213
- }
214
-
215
- // Lease-required commands (same set as legacy agent).
216
- const LEASE_REQUIRED = new Set([
217
- 'stopSession', 'restartSession', 'refreshSession', 'navigate',
218
- 'type', 'paste', 'press', 'click', 'runAction', 'focus',
219
- ]);
220
-
221
- // Execute the command using the shared runtime.
222
- try {
223
- const result = await _executeCommand(type, { ...rest, accountId }, msg, opts, ws);
224
- _sendResponse(ws, msg, result, echo);
225
- } catch (err) {
226
- _sendResponse(ws, msg, { success: false, error: _safeError(err) }, echo);
227
- }
228
- }
229
-
230
- /**
231
- * Execute a single command. This reuses the existing hardened runtime logic.
232
- */
233
- async function _executeCommand(type, params, msg, opts, ws) {
234
- const accountId = params.accountId || msg.accountId;
235
- const accountUuid = msg.accountUuid || params.accountUuid;
236
- const lease = params.lease || msg.command?.lease;
237
-
238
- switch (type) {
239
- case 'startSession':
240
- return _startSession(params, opts, accountId, accountUuid, lease);
241
- case 'stopSession':
242
- return _stopSession(accountId, lease);
243
- case 'restartSession':
244
- await _stopSession(accountId, lease);
245
- return _startSession(params, opts, accountId, accountUuid, lease);
246
- case 'refreshSession':
247
- return _refreshSession(accountId);
248
- case 'navigate':
249
- return _navigate(accountId, params.url);
250
- case 'type':
251
- return _typeText(accountId, params.selector, params.text);
252
- case 'paste':
253
- return _typeText(accountId, params.selector, params.text);
254
- case 'press':
255
- return _pressKey(accountId, params.key);
256
- case 'click':
257
- return _click(accountId, params.selector);
258
- case 'focus':
259
- return _focusSession(accountId);
260
- case 'runAction':
261
- return _runAction(accountId, params.action, params.payload || params.args);
262
- case 'getStatus':
263
- return _getStatus();
264
- case 'importLegacyProfile':
265
- return _importLegacyProfile(accountId, accountUuid, opts);
266
- case 'discoverLegacyProfiles':
267
- return _discoverLegacyProfiles();
268
- default:
269
- return { success: false, error: 'Unknown command type' };
270
- }
271
- }
272
-
273
- // ── Session management (reuses existing hardened modules) ───────────────────
274
-
275
- async function _startSession(params, opts, accountId, accountUuid, lease) {
276
- if (!accountId) return { success: false, error: 'Missing accountId' };
277
-
278
- const deviceMeta = opts.deviceMeta;
279
- const profileDir = resolveProfileDir({
280
- profileRoot: PROFILES_DIR,
281
- deviceUuid: deviceMeta.deviceId,
282
- accountUuid: accountUuid || accountId,
283
- });
284
-
285
- const fs = require('fs');
286
- if (!fs.existsSync(profileDir)) fs.mkdirSync(profileDir, { recursive: true });
287
-
288
- const fingerprint = fingerprintStore.loadOrGenerate(profileDir, () => generateFingerprint());
289
-
290
- const args = [
291
- '--disable-blink-features=AutomationControlled',
292
- '--force-webrtc-ip-handling-policy=disable_non_proxied_udp',
293
- '--no-first-run',
294
- '--no-default-browser-check',
295
- ];
296
-
297
- const launchOptions = {
298
- executablePath: opts.chromePath,
299
- headless: false,
300
- args,
301
- viewport: { width: fingerprint.viewport?.width || 1280, height: fingerprint.viewport?.height || 720 },
302
- };
303
-
304
- if (params.proxy) {
305
- const proxyUrl = _parseProxy(params.proxy);
306
- if (proxyUrl) launchOptions.proxy = proxyUrl;
307
- }
308
-
309
- const context = await chromium.launchPersistentContext(profileDir, launchOptions);
310
- await context.addInitScript(buildStealthScript(fingerprint));
311
-
312
- if (params.cookies && Array.isArray(params.cookies)) {
313
- try { await context.addCookies(params.cookies); } catch {}
314
- }
315
-
316
- const pages = context.pages();
317
- const page = pages[0] || await context.newPage();
318
-
319
- const url = params.url || 'https://x.com/home';
320
- await page.goto(url, { waitUntil: 'domcontentloaded' }).catch(() => {});
321
-
322
- const session = { context, page, profileDir, accountId, lease: null };
323
- if (lease) leaseClient.bind(session, lease);
324
- activeSessions.set(accountId, session);
325
-
326
- return { success: true, accountId, started: true };
327
- }
328
-
329
- async function _stopSession(accountId, lease) {
330
- const session = activeSessions.get(accountId);
331
- if (!session) return { success: false, error: 'Session not found' };
332
- try { await session.context.close(); } catch {}
333
- activeSessions.delete(accountId);
334
- return { success: true, accountId, stopped: true };
335
- }
336
-
337
- async function _refreshSession(accountId) {
338
- const session = activeSessions.get(accountId);
339
- if (!session) return { success: false, error: 'Session not found' };
340
- await session.page.reload();
341
- return { success: true };
342
- }
343
-
344
- async function _navigate(accountId, url) {
345
- const session = activeSessions.get(accountId);
346
- if (!session) return { success: false, error: 'Session not found' };
347
- await session.page.goto(url, { waitUntil: 'domcontentloaded' });
348
- return { success: true };
349
- }
350
-
351
- async function _typeText(accountId, selector, text) {
352
- const session = activeSessions.get(accountId);
353
- if (!session) return { success: false, error: 'Session not found' };
354
- await session.page.locator(selector).fill(text);
355
- return { success: true };
356
- }
357
-
358
- async function _pressKey(accountId, key) {
359
- const session = activeSessions.get(accountId);
360
- if (!session) return { success: false, error: 'Session not found' };
361
- await session.page.keyboard.press(key);
362
- return { success: true };
363
- }
364
-
365
- async function _click(accountId, selector) {
366
- const session = activeSessions.get(accountId);
367
- if (!session) return { success: false, error: 'Session not found' };
368
- await session.page.locator(selector).click();
369
- return { success: true };
370
- }
371
-
372
- async function _focusSession(accountId) {
373
- const session = activeSessions.get(accountId);
374
- if (!session) return { success: false, error: 'Session not found' };
375
- await session.page.bringToFront();
376
- return { success: true };
377
- }
378
-
379
- async function _runAction(accountId, action, payload) {
380
- const session = activeSessions.get(accountId);
381
- if (!session) return { success: false, error: 'Session not found' };
382
- const { runAction } = require('./actions');
383
- const result = await runAction(session.page, action, payload || {});
384
- return { success: true, result };
385
- }
386
-
387
- function _getStatus() {
388
- const sessions = [];
389
- for (const [accountId, session] of activeSessions) {
390
- sessions.push({ accountId, url: session.page ? session.page.url() : null });
391
- }
392
- return { success: true, sessions, count: sessions.length };
393
- }
394
-
395
- function _importLegacyProfile(accountId, accountUuid, opts) {
396
- // Defect 9 fix: pass opts correctly (was undefined before).
397
- const result = importLegacyProfile(accountId, {
398
- profileRoot: PROFILES_DIR,
399
- deviceUuid: opts.deviceMeta.deviceId,
400
- accountUuid,
401
- });
402
- return { success: true, result };
403
- }
404
-
405
- function _discoverLegacyProfiles() {
406
- const profiles = discoverLegacyProfiles(PROFILES_DIR);
407
- return { success: true, profiles };
408
- }
409
-
410
- // ── Helpers ──────────────────────────────────────────────────────────────────
411
-
412
- function _extractEcho(msg) {
413
- const echo = {};
414
- if (msg.nonce) echo.nonce = msg.nonce;
415
- if (msg.leaseId) echo.leaseId = msg.leaseId;
416
- if (msg.accountUuid) echo.accountUuid = msg.accountUuid;
417
- return echo;
418
- }
419
-
420
- function _sendResponse(ws, msg, result, echo) {
421
- try {
422
- ws.send(JSON.stringify({
423
- type: 'command-response',
424
- commandId: msg.commandId,
425
- result,
426
- ...(echo || _extractEcho(msg)),
427
- }));
428
- } catch {}
429
- }
430
-
431
- function _parseProxy(proxyStr) {
432
- if (!proxyStr || typeof proxyStr !== 'string') return null;
433
- const parts = proxyStr.split(':');
434
- if (parts.length >= 2) {
435
- const proxy = { server: `http://${parts[0]}:${parts[1]}` };
436
- if (parts[2] && parts[3]) {
437
- proxy.username = parts[2];
438
- proxy.password = parts[3];
439
- }
440
- return proxy;
441
- }
442
- return null;
443
- }
444
-
445
- function _safeError(err) {
446
- const msg = err && err.message ? err.message : String(err);
447
- return msg
448
- .replace(/[A-Fa-f0-9]{64}/g, '<hex>')
449
- .replace(/eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g, '<jwt>')
450
- .slice(0, 500);
451
- }
452
-
1
+ 'use strict';
2
+
3
+ /**
4
+ * Phase 10 — Browser session handler (protocol v2).
5
+ *
6
+ * Defect 8 fix: Handle the existing hardened command envelope:
7
+ * { type: 'command', commandId, accountId, command: { type, ...rest, lease? },
8
+ * nonce?, leaseId?, accountUuid? }
9
+ *
10
+ * Defect 9 fix: Reuse the existing hardened browser runtime from index.js
11
+ * (actions, proxy fail-closed, media blocking, profile identity, lease client,
12
+ * cookie handling, etc.) rather than maintaining a second divergent runtime.
13
+ *
14
+ * The agent validates the complete inbound frame, reads the action type from
15
+ * the canonical command object, preserves command and lease expiry, echoes
16
+ * commandId/nonce/leaseId/accountUuid, returns results under the canonical
17
+ * `result` field, and rejects unknown command types.
18
+ */
19
+
20
+ const { chromium } = require('playwright-core');
21
+ const os = require('os');
22
+
23
+ // Import the existing hardened runtime modules (Defect 9).
24
+ const { generateFingerprint } = require('./fingerprint');
25
+ const fingerprintStore = require('./fingerprintStore');
26
+ const { resolveProfileDir, importLegacyProfile, discoverLegacyProfiles } = require('./profilePath');
27
+ const { buildStealthScript } = require('./stealth');
28
+ const leaseClient = require('./leaseClient');
29
+ const { PROFILES_DIR } = require('./deviceKeyStore');
30
+
31
+ // ── Windows foreground helper ────────────────────────────────────────────────
32
+ //
33
+ // page.bringToFront() may be insufficient on real Windows to actually bring
34
+ // the browser window to the foreground (Windows foreground lock rules).
35
+ // This helper uses a narrow, safe PowerShell command to activate the EXACT
36
+ // Chrome window associated with this session's persistent profile directory.
37
+ //
38
+ // Safety requirements:
39
+ // - uses the fixed System32 PowerShell 5.1 path (no PATH-based resolution)
40
+ // - uses execFileSync argument arrays (no shell:true, no command interpolation)
41
+ // - profileDir is passed via STDIN (never in command arguments)
42
+ // - targets ONLY the Chrome process whose command line contains the exact
43
+ // profileDir (not "most recent Chrome" globally)
44
+ // - does NOT kill or focus unrelated windows
45
+ // - Add-Type is defined BEFORE calling SetForegroundWindow (ordering fix)
46
+ // - returns true only if the intended window was identified and foregrounded
47
+ //
48
+ // @param {string} profileDir — the persistent profile directory for this session
49
+ // @returns {boolean} true if the window was identified and foregrounded
50
+
51
+ function _windowsForegroundChrome(profileDir) {
52
+ if (os.platform() !== 'win32') return true; // non-Windows: no-op success
53
+ if (!profileDir) return false;
54
+ try {
55
+ const nodePath = require('path');
56
+ const { execFileSync } = require('child_process');
57
+ const root = process.env.SystemRoot || process.env.WINDIR || 'C:\\Windows';
58
+ const psExe = nodePath.join(root, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');
59
+
60
+ // Fixed PowerShell script — NO user data interpolation.
61
+ // The profileDir is passed via STDIN and read by the script.
62
+ // Add-Type is defined BEFORE any call to SetForegroundWindow.
63
+ // The script:
64
+ // 1. Reads the profileDir from stdin
65
+ // 2. Finds chrome.exe processes whose command line contains that exact path
66
+ // 3. Gets the MainWindowHandle of that specific process
67
+ // 4. Uses SetForegroundWindow + ShowWindowAsync to restore+foreground it
68
+ // 5. Outputs "OK" or "FAIL" so the caller knows whether it worked
69
+ const script =
70
+ "$ErrorActionPreference='Stop'; " +
71
+ "Add-Type -Namespace Win32 -Name Native -MemberDefinition '" +
72
+ "[DllImport(\"user32.dll\")] public static extern bool SetForegroundWindow(IntPtr hWnd); " +
73
+ "[DllImport(\"user32.dll\")] public static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow); " +
74
+ "[DllImport(\"user32.dll\")] public static extern bool IsIconic(IntPtr hWnd); " +
75
+ "'; " +
76
+ "$profileDir = [Console]::In.ReadToEnd().Trim(); " +
77
+ "if (-not $profileDir) { Write-Output 'FAIL:no_profile'; exit 0 }; " +
78
+ "$procs = Get-CimInstance Win32_Process -Filter \"Name='chrome.exe'\" -ErrorAction SilentlyContinue; " +
79
+ "$target = $null; " +
80
+ "foreach ($p in $procs) { " +
81
+ " if ($p.CommandLine -and ($p.CommandLine -like \"*$profileDir*\")) { $target = $p; break } " +
82
+ "}; " +
83
+ "if (-not $target) { Write-Output 'FAIL:no_process'; exit 0 }; " +
84
+ "$proc = Get-Process -Id $target.ProcessId -ErrorAction SilentlyContinue; " +
85
+ "if (-not $proc -or $proc.MainWindowHandle -eq [IntPtr]::Zero) { Write-Output 'FAIL:no_window'; exit 0 }; " +
86
+ "$handle = $proc.MainWindowHandle; " +
87
+ "if ([Win32.Native]::IsIconic($handle)) { [void][Win32.Native]::ShowWindowAsync($handle, 9) }; " +
88
+ "$result = [Win32.Native]::SetForegroundWindow($handle); " +
89
+ "if ($result) { Write-Output 'OK' } else { Write-Output 'FAIL:foreground' }";
90
+
91
+ const output = execFileSync(psExe, ['-NoProfile', '-NonInteractive', '-Command', script], {
92
+ windowsHide: true,
93
+ encoding: 'utf8',
94
+ timeout: 5000,
95
+ input: profileDir, // profileDir via STDIN — never in command arguments
96
+ }).trim();
97
+
98
+ return output === 'OK';
99
+ } catch {
100
+ // Foreground helper failed — return false so visible is not claimed
101
+ return false;
102
+ }
103
+ }
104
+
105
+ // Active sessions: accountId -> { context, page, profileDir }
106
+ const activeSessions = new Map();
107
+
108
+ // Per-runtime state (B4 fix): each setupSessionHandler call creates a fresh
109
+ // runtime object so a newly initialized handler starts connected and does
110
+ // NOT inherit stale state from a prior handler lifecycle. The module-level
111
+ // `currentRuntime` is only used so markDisconnected() / closeAllSessions()
112
+ // (called from cli.js) can reach the active runtime without an explicit
113
+ // handle. One handler disconnecting cannot poison another handler's runtime.
114
+ const currentRuntime = { disconnected: false, sessions: activeSessions };
115
+
116
+ /**
117
+ * Mark the CURRENT runtime as disconnected. After this, every inbound command
118
+ * for that runtime is rejected with a clear error and no new browser work is
119
+ * performed. A new setupSessionHandler call creates a fresh runtime that
120
+ * starts connected.
121
+ */
122
+ function markDisconnected() {
123
+ currentRuntime.disconnected = true;
124
+ }
125
+
126
+ /**
127
+ * Close every active browser context, preserving profile/cookies through the
128
+ * existing safe persistence path (the context close flushes the persistent
129
+ * profile dir). Clears the active-sessions map. Safe to call multiple times.
130
+ * Operates on the current runtime's sessions.
131
+ *
132
+ * @returns {Promise<{ closed: number }>}
133
+ */
134
+ async function closeAllSessions() {
135
+ const sessions = currentRuntime.sessions || activeSessions;
136
+ const keys = Array.from(sessions.keys());
137
+ let closed = 0;
138
+ for (const accountId of keys) {
139
+ const session = sessions.get(accountId);
140
+ if (!session) continue;
141
+ // Delete BEFORE closing so a concurrent call does not double-close.
142
+ sessions.delete(accountId);
143
+ try {
144
+ if (session.context) await session.context.close().catch(() => {});
145
+ } catch {}
146
+ closed += 1;
147
+ }
148
+ return { closed };
149
+ }
150
+
151
+ /**
152
+ * Set up the session handler on an authenticated WebSocket.
153
+ *
154
+ * @param {WebSocket} ws — authenticated v2 WebSocket
155
+ * @param {object} opts — { chromePath, deviceMeta, serverOrigin }
156
+ * @returns {Map} the active sessions map
157
+ */
158
+ function setupSessionHandler(ws, opts) {
159
+ // B4 fix: reset the per-runtime state so a newly initialized handler starts
160
+ // connected and does NOT inherit stale state from a prior handler lifecycle.
161
+ // The module-level `currentRuntime` is shared so cli.js's markDisconnected()
162
+ // / closeAllSessions() reach the active runtime. Each setupSessionHandler
163
+ // call resets it to connected.
164
+ currentRuntime.disconnected = false;
165
+ currentRuntime.sessions = activeSessions;
166
+
167
+ ws.on('message', (data, isBinary) => {
168
+ if (isBinary) return;
169
+
170
+ let msg;
171
+ try {
172
+ msg = JSON.parse(data.toString('utf8'));
173
+ } catch {
174
+ return;
175
+ }
176
+
177
+ if (!msg || typeof msg !== 'object') return;
178
+
179
+ // Handle the existing hardened command envelope (Defect 8).
180
+ if (msg.type === 'command') {
181
+ // Fail-safe: after the authenticated WebSocket closed, no further commands
182
+ // may be accepted. A stale/zombie socket must never drive a browser.
183
+ if (currentRuntime.disconnected) {
184
+ const echo = _extractEcho(msg);
185
+ try {
186
+ ws.send(JSON.stringify({
187
+ type: 'command-response',
188
+ commandId: msg.commandId,
189
+ result: { success: false, error: 'Agent disconnected: commands no longer accepted' },
190
+ ...echo,
191
+ }));
192
+ } catch {}
193
+ return;
194
+ }
195
+ _handleCommandEnvelope(ws, msg, opts).catch((err) => {
196
+ // Send error response with echo (never leak secrets).
197
+ const echo = _extractEcho(msg);
198
+ try {
199
+ ws.send(JSON.stringify({
200
+ type: 'command-response',
201
+ commandId: msg.commandId,
202
+ result: { success: false, error: _safeError(err) },
203
+ ...echo,
204
+ }));
205
+ } catch {}
206
+ });
207
+ return;
208
+ }
209
+
210
+ // Handle heartbeats.
211
+ if (msg.type === 'heartbeat') {
212
+ try { ws.send(JSON.stringify({ type: 'heartbeat-ack' })); } catch {}
213
+ return;
214
+ }
215
+
216
+ // Reconnect reconciliation: the server asks for an active-sessions report.
217
+ // Each entry is lease-bound (accountUuid + leaseId + leaseToken + status).
218
+ // A missing/invalid status is NEVER defaulted to 'running' — the server
219
+ // treats an unverified entry as unresolved (the lease stays blocking).
220
+ if (msg.type === 'report-sessions') {
221
+ try {
222
+ const sessions = [];
223
+ for (const [accountId, session] of activeSessions) {
224
+ const lease = (session.lease && typeof session.lease.getClientView === 'function')
225
+ ? session.lease.getClientView()
226
+ : (session.lease || null);
227
+ sessions.push({
228
+ accountId,
229
+ accountUuid: session.accountUuid || null,
230
+ leaseId: (lease && lease.leaseId) || null,
231
+ leaseToken: (lease && lease.leaseToken) || null,
232
+ status: session.context ? 'running' : 'stopped',
233
+ });
234
+ }
235
+ ws.send(JSON.stringify({ type: 'sessions-report', sessions }));
236
+ } catch {}
237
+ return;
238
+ }
239
+
240
+ // session-status ack: the server confirms a stop was verified. No-op here
241
+ // beyond acknowledging; the lease stays under server authority.
242
+ if (msg.type === 'session-status') {
243
+ try { ws.send(JSON.stringify({ type: 'session-status-ack', commandId: msg.commandId || null })); } catch {}
244
+ return;
245
+ }
246
+
247
+ // Other message types (session-status, sessions-report, log) are handled
248
+ // by the shared engine on the backend side — the agent only needs to
249
+ // respond to commands and heartbeats.
250
+ });
251
+
252
+ return activeSessions;
253
+ }
254
+
255
+ /**
256
+ * Handle a command envelope: { type: 'command', commandId, accountId, command: { type, ... } }
257
+ *
258
+ * This delegates to the same session management logic used by the legacy agent,
259
+ * preserving all hardened safeguards (Defect 9).
260
+ */
261
+ async function _handleCommandEnvelope(ws, msg, opts) {
262
+ const { commandId, accountId, command } = msg;
263
+
264
+ if (!commandId || typeof commandId !== 'string') {
265
+ return; // Malformed — drop silently.
266
+ }
267
+ if (!command || typeof command !== 'object') {
268
+ _sendResponse(ws, msg, { success: false, error: 'Missing command object' });
269
+ return;
270
+ }
271
+
272
+ const { type, ...rest } = command;
273
+
274
+ // Build the echo object from the envelope (nonce, leaseId, accountUuid).
275
+ const echo = _extractEcho(msg);
276
+
277
+ // Validate command type against the known allowlist.
278
+ const ALLOWED_TYPES = new Set([
279
+ 'startSession', 'stopSession', 'restartSession', 'refreshSession',
280
+ 'navigate', 'type', 'paste', 'press', 'click', 'runAction',
281
+ 'getStatus', 'importLegacyProfile', 'discoverLegacyProfiles',
282
+ 'focus',
283
+ ]);
284
+
285
+ if (!ALLOWED_TYPES.has(type)) {
286
+ _sendResponse(ws, msg, { success: false, error: 'Unknown command type' });
287
+ return;
288
+ }
289
+
290
+ // Lease-required commands (same set as legacy agent).
291
+ const LEASE_REQUIRED = new Set([
292
+ 'stopSession', 'restartSession', 'refreshSession', 'navigate',
293
+ 'type', 'paste', 'press', 'click', 'runAction', 'focus',
294
+ ]);
295
+
296
+ // Execute the command using the shared runtime.
297
+ try {
298
+ const result = await _executeCommand(type, { ...rest, accountId }, msg, opts, ws);
299
+ _sendResponse(ws, msg, result, echo);
300
+ } catch (err) {
301
+ _sendResponse(ws, msg, { success: false, error: _safeError(err) }, echo);
302
+ }
303
+ }
304
+
305
+ /**
306
+ * Execute a single command. This reuses the existing hardened runtime logic.
307
+ */
308
+ async function _executeCommand(type, params, msg, opts, ws) {
309
+ const accountId = params.accountId || msg.accountId;
310
+ const accountUuid = msg.accountUuid || params.accountUuid;
311
+ const lease = params.lease || msg.command?.lease;
312
+
313
+ switch (type) {
314
+ case 'startSession':
315
+ return _startSession(params, opts, accountId, accountUuid, lease);
316
+ case 'stopSession':
317
+ return _stopSession(accountId, lease);
318
+ case 'restartSession':
319
+ await _stopSession(accountId, lease);
320
+ return _startSession(params, opts, accountId, accountUuid, lease);
321
+ case 'refreshSession':
322
+ return _refreshSession(accountId);
323
+ case 'navigate':
324
+ return _navigate(accountId, params.url);
325
+ case 'type':
326
+ return _typeText(accountId, params.selector, params.text);
327
+ case 'paste':
328
+ return _typeText(accountId, params.selector, params.text);
329
+ case 'press':
330
+ return _pressKey(accountId, params.key);
331
+ case 'click':
332
+ return _click(accountId, params.selector);
333
+ case 'focus':
334
+ return _focusSession(accountId);
335
+ case 'runAction':
336
+ return _runAction(accountId, params.action, params.payload || params.args);
337
+ case 'getStatus':
338
+ return _getStatus();
339
+ case 'importLegacyProfile':
340
+ return _importLegacyProfile(accountId, accountUuid, opts);
341
+ case 'discoverLegacyProfiles':
342
+ return _discoverLegacyProfiles();
343
+ default:
344
+ return { success: false, error: 'Unknown command type' };
345
+ }
346
+ }
347
+
348
+ // ── Session management (reuses existing hardened modules) ───────────────────
349
+
350
+ async function _startSession(params, opts, accountId, accountUuid, lease) {
351
+ if (!accountId) return { success: false, error: 'Missing accountId' };
352
+
353
+ const deviceMeta = opts.deviceMeta;
354
+ const profileDir = resolveProfileDir({
355
+ profileRoot: PROFILES_DIR,
356
+ deviceUuid: deviceMeta.deviceId,
357
+ accountUuid: accountUuid || accountId,
358
+ });
359
+
360
+ const fs = require('fs');
361
+ if (!fs.existsSync(profileDir)) fs.mkdirSync(profileDir, { recursive: true });
362
+
363
+ const fingerprint = fingerprintStore.loadOrGenerate(profileDir, () => generateFingerprint());
364
+
365
+ const args = [
366
+ '--disable-blink-features=AutomationControlled',
367
+ '--force-webrtc-ip-handling-policy=disable_non_proxied_udp',
368
+ '--no-first-run',
369
+ '--no-default-browser-check',
370
+ '--start-maximized',
371
+ ];
372
+
373
+ // Prefer noDefaultViewport: true so the real OS window fills the screen
374
+ // (helps the launched browser appear visibly foregrounded). The per-account
375
+ // fingerprint invariants are enforced by the stealth init script against
376
+ // the *screen* object (window.screen.width/height), NOT against the
377
+ // Playwright viewport, so removing the forced viewport does not weaken the
378
+ // fingerprint. window.innerWidth/innerHeight are left to the real window
379
+ // size, which is acceptable because the stealth script does not pin them.
380
+ const launchOptions = {
381
+ executablePath: opts.chromePath,
382
+ headless: false,
383
+ args,
384
+ noDefaultViewport: true,
385
+ };
386
+
387
+ if (params.proxy) {
388
+ const proxyUrl = _parseProxy(params.proxy);
389
+ if (proxyUrl) launchOptions.proxy = proxyUrl;
390
+ }
391
+
392
+ let context;
393
+ try {
394
+ context = await chromium.launchPersistentContext(profileDir, launchOptions);
395
+ } catch (err) {
396
+ return { success: false, error: _safeError(err) };
397
+ }
398
+
399
+ await context.addInitScript(buildStealthScript(fingerprint));
400
+
401
+ if (params.cookies && Array.isArray(params.cookies)) {
402
+ try { await context.addCookies(params.cookies); } catch {}
403
+ }
404
+
405
+ const pages = context.pages();
406
+ const page = pages[0] || await context.newPage();
407
+
408
+ const url = params.url || 'https://x.com/home';
409
+ await page.goto(url, { waitUntil: 'domcontentloaded' }).catch(() => {});
410
+
411
+ // If the browser launched but immediately closed, report a clear error
412
+ // instead of showing a misleading green "browser opened" toast.
413
+ if (page.isClosed()) {
414
+ try { await context.close().catch(() => {}); } catch {}
415
+ return {
416
+ success: false,
417
+ error: 'Browser launched but closed immediately. The session was not started.',
418
+ };
419
+ }
420
+
421
+ // Foreground the newly launched window so the user actually sees it.
422
+ // Do NOT report success until the page is confirmed focused.
423
+ let bringToFrontOk = false;
424
+ try {
425
+ await page.bringToFront();
426
+ bringToFrontOk = true;
427
+ } catch (err) {
428
+ try { await context.close().catch(() => {}); } catch {}
429
+ return {
430
+ success: false,
431
+ error: 'Browser launched but could not be brought to the foreground: ' + _safeError(err),
432
+ };
433
+ }
434
+
435
+ // Windows-specific foreground: page.bringToFront() alone may not overcome
436
+ // the Windows foreground lock. This helper targets the EXACT Chrome process
437
+ // whose command line contains this session's profileDir (passed via stdin,
438
+ // not interpolated). It returns true ONLY if the intended window was
439
+ // identified and successfully foregrounded.
440
+ let foregroundVerified = false;
441
+ if (bringToFrontOk) {
442
+ foregroundVerified = _windowsForegroundChrome(profileDir);
443
+ }
444
+
445
+ // Re-check after focus: the page may have closed in the meantime.
446
+ if (page.isClosed()) {
447
+ try { await context.close().catch(() => {}); } catch {}
448
+ return {
449
+ success: false,
450
+ error: 'Browser closed immediately after focusing. The session was not started.',
451
+ };
452
+ }
453
+
454
+ const session = { context, page, profileDir, accountId, lease: null };
455
+ if (lease) leaseClient.bind(session, lease);
456
+ activeSessions.set(accountId, session);
457
+
458
+ // Return confirmed success metadata. The backend/frontend uses this to
459
+ // show a green toast ONLY when the browser is genuinely started and visible.
460
+ //
461
+ // visible: true requires POSITIVE evidence:
462
+ // - launchPersistentContext succeeded
463
+ // - page exists and is not closed
464
+ // - page.bringToFront() succeeded
465
+ // - on Windows: the intended Chrome process was identified and
466
+ // SetForegroundWindow succeeded (or on non-Windows: bringToFront is
467
+ // sufficient)
468
+ //
469
+ // If the Windows foreground helper cannot prove the window is visible
470
+ // (foregroundVerified = false), we return started:true but visible:false
471
+ // with an actionable error so the frontend does NOT show a green toast.
472
+ if (os.platform() === 'win32' && !foregroundVerified) {
473
+ // The browser launched and bringToFront succeeded, but we could not
474
+ // positively verify the window is in the foreground. Return a safe
475
+ // actionable message — NOT a green toast.
476
+ return {
477
+ success: true,
478
+ accountId,
479
+ started: true,
480
+ visible: false,
481
+ sessionId: accountId,
482
+ error: 'Browser launched but could not be confirmed in the foreground. Check the taskbar for the Chrome window.',
483
+ };
484
+ }
485
+
486
+ return {
487
+ success: true,
488
+ accountId,
489
+ started: true,
490
+ visible: true,
491
+ sessionId: accountId,
492
+ };
493
+ }
494
+
495
+ async function _stopSession(accountId, lease) {
496
+ const session = activeSessions.get(accountId);
497
+ if (!session) return { success: false, error: 'Session not found' };
498
+ try { await session.context.close(); } catch {}
499
+ activeSessions.delete(accountId);
500
+ return { success: true, accountId, stopped: true };
501
+ }
502
+
503
+ async function _refreshSession(accountId) {
504
+ const session = activeSessions.get(accountId);
505
+ if (!session) return { success: false, error: 'Session not found' };
506
+ await session.page.reload();
507
+ return { success: true };
508
+ }
509
+
510
+ async function _navigate(accountId, url) {
511
+ const session = activeSessions.get(accountId);
512
+ if (!session) return { success: false, error: 'Session not found' };
513
+ await session.page.goto(url, { waitUntil: 'domcontentloaded' });
514
+ return { success: true };
515
+ }
516
+
517
+ async function _typeText(accountId, selector, text) {
518
+ const session = activeSessions.get(accountId);
519
+ if (!session) return { success: false, error: 'Session not found' };
520
+ await session.page.locator(selector).fill(text);
521
+ return { success: true };
522
+ }
523
+
524
+ async function _pressKey(accountId, key) {
525
+ const session = activeSessions.get(accountId);
526
+ if (!session) return { success: false, error: 'Session not found' };
527
+ await session.page.keyboard.press(key);
528
+ return { success: true };
529
+ }
530
+
531
+ async function _click(accountId, selector) {
532
+ const session = activeSessions.get(accountId);
533
+ if (!session) return { success: false, error: 'Session not found' };
534
+ await session.page.locator(selector).click();
535
+ return { success: true };
536
+ }
537
+
538
+ async function _focusSession(accountId) {
539
+ const session = activeSessions.get(accountId);
540
+ if (!session) return { success: false, error: 'Session not found' };
541
+ await session.page.bringToFront();
542
+ return { success: true };
543
+ }
544
+
545
+ async function _runAction(accountId, action, payload) {
546
+ const session = activeSessions.get(accountId);
547
+ if (!session) return { success: false, error: 'Session not found' };
548
+ const { runAction } = require('./actions');
549
+ const result = await runAction(session.page, action, payload || {});
550
+ return { success: true, result };
551
+ }
552
+
553
+ function _getStatus() {
554
+ const sessions = [];
555
+ for (const [accountId, session] of activeSessions) {
556
+ sessions.push({ accountId, url: session.page ? session.page.url() : null });
557
+ }
558
+ return { success: true, sessions, count: sessions.length };
559
+ }
560
+
561
+ function _importLegacyProfile(accountId, accountUuid, opts) {
562
+ // Defect 9 fix: pass opts correctly (was undefined before).
563
+ const result = importLegacyProfile(accountId, {
564
+ profileRoot: PROFILES_DIR,
565
+ deviceUuid: opts.deviceMeta.deviceId,
566
+ accountUuid,
567
+ });
568
+ return { success: true, result };
569
+ }
570
+
571
+ function _discoverLegacyProfiles() {
572
+ const profiles = discoverLegacyProfiles(PROFILES_DIR);
573
+ return { success: true, profiles };
574
+ }
575
+
576
+ // ── Helpers ──────────────────────────────────────────────────────────────────
577
+
578
+ function _extractEcho(msg) {
579
+ const echo = {};
580
+ if (msg.nonce) echo.nonce = msg.nonce;
581
+ if (msg.leaseId) echo.leaseId = msg.leaseId;
582
+ if (msg.accountUuid) echo.accountUuid = msg.accountUuid;
583
+ return echo;
584
+ }
585
+
586
+ function _sendResponse(ws, msg, result, echo) {
587
+ try {
588
+ ws.send(JSON.stringify({
589
+ type: 'command-response',
590
+ commandId: msg.commandId,
591
+ result,
592
+ ...(echo || _extractEcho(msg)),
593
+ }));
594
+ } catch {}
595
+ }
596
+
597
+ function _parseProxy(proxyStr) {
598
+ if (!proxyStr || typeof proxyStr !== 'string') return null;
599
+ const parts = proxyStr.split(':');
600
+ if (parts.length >= 2) {
601
+ const proxy = { server: `http://${parts[0]}:${parts[1]}` };
602
+ if (parts[2] && parts[3]) {
603
+ proxy.username = parts[2];
604
+ proxy.password = parts[3];
605
+ }
606
+ return proxy;
607
+ }
608
+ return null;
609
+ }
610
+
611
+ function _safeError(err) {
612
+ const msg = err && err.message ? err.message : String(err);
613
+ return msg
614
+ .replace(/[A-Fa-f0-9]{64}/g, '<hex>')
615
+ .replace(/eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g, '<jwt>')
616
+ .slice(0, 500);
617
+ }
618
+
453
619
  module.exports = { setupSessionHandler, activeSessions, closeAllSessions, markDisconnected };