@xkwdstore/agent 2.0.2 → 2.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,453 +1,874 @@
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
-
453
- module.exports = { setupSessionHandler, activeSessions, closeAllSessions, markDisconnected };
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
+ // ── Exact-profile Chrome detection (recovery probe) ──────────────────────────
32
+ //
33
+ // "activeSessions is empty" is NOT proof a browser stopped: an agent-process
34
+ // restart clears that map while Chrome may still be running. Recovery must use
35
+ // EXACT profile/process verification. We enumerate chrome.exe command lines and
36
+ // match the EXACT --user-data-dir against this account's resolved profile dir —
37
+ // never "newest Chrome", "any chrome.exe", window titles, or a global count.
38
+ function _chromeCommandLines() {
39
+ const root = process.env.SystemRoot || process.env.WINDIR || 'C:\\Windows';
40
+ const nodePath = require('path');
41
+ const { execFileSync } = require('child_process');
42
+ const psExe = nodePath.join(root, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');
43
+ const script =
44
+ "$ErrorActionPreference='SilentlyContinue'; " +
45
+ "$procs = Get-CimInstance Win32_Process -Filter \"Name='chrome.exe'\"; " +
46
+ "$lines = @(); foreach ($p in $procs) { if ($p.CommandLine) { $lines += [string]$p.CommandLine } }; " +
47
+ "Write-Output (ConvertTo-Json -Compress @{ lines = @($lines) })";
48
+ const out = execFileSync(psExe, ['-NoProfile', '-NonInteractive', '-Command', script], {
49
+ windowsHide: true,
50
+ encoding: 'utf8',
51
+ timeout: 8000,
52
+ }).trim();
53
+ const parsed = JSON.parse(out);
54
+ const lines = parsed && parsed.lines != null ? parsed.lines : [];
55
+ return Array.isArray(lines) ? lines : [lines];
56
+ }
57
+
58
+ // Test-only injectable Chrome-command-line provider (mirrors the atomicWrite
59
+ // directory-fsync hook). Tests inject synthetic command lines so exact-profile
60
+ // matching is provable without spawning real processes.
61
+ let _chromeLinesProvider = _chromeCommandLines;
62
+ function _setChromeLinesProvider(fn) { _chromeLinesProvider = typeof fn === 'function' ? fn : _chromeCommandLines; }
63
+
64
+ /**
65
+ * Return 'running' | 'stopped' | 'unknown' for whether a Chrome process still
66
+ * owns the EXACT profile directory. Fails closed to 'unknown' on any error.
67
+ */
68
+ function _detectProfileChromeRunning(profileDir) {
69
+ if (!profileDir) return 'unknown';
70
+ if (os.platform() !== 'win32') return 'unknown'; // no exact-profile inspection here
71
+ const nodePath = require('path');
72
+ try {
73
+ const target = nodePath.resolve(profileDir).replace(/[\\/]+$/, '').toLowerCase();
74
+ const lines = _chromeLinesProvider();
75
+ for (const line of lines) {
76
+ const m = /--user-data-dir=(?:"([^"]+)"|(\S+))/.exec(String(line));
77
+ if (!m) continue;
78
+ const got = (m[1] || m[2] || '').replace(/[\\/]+$/, '').toLowerCase();
79
+ if (got && nodePath.resolve(got) === target) return 'running';
80
+ }
81
+ return 'stopped';
82
+ } catch {
83
+ return 'unknown';
84
+ }
85
+ }
86
+
87
+ // ── Windows foreground helper ────────────────────────────────────────────────
88
+ //
89
+ // page.bringToFront() may be insufficient on real Windows to actually bring
90
+ // the browser window to the foreground (Windows foreground lock rules).
91
+ // This helper uses a narrow, safe PowerShell command to activate the EXACT
92
+ // Chrome window associated with this session's persistent profile directory.
93
+ //
94
+ // Safety requirements:
95
+ // - uses the fixed System32 PowerShell 5.1 path (no PATH-based resolution)
96
+ // - uses execFileSync argument arrays (no shell:true, no command interpolation)
97
+ // - profileDir is passed via STDIN (never in command arguments)
98
+ // - targets ONLY the Chrome process whose command line contains the exact
99
+ // profileDir (not "most recent Chrome" globally)
100
+ // - does NOT kill or focus unrelated windows
101
+ // - Add-Type is defined BEFORE calling SetForegroundWindow (ordering fix)
102
+ // - returns true only if the intended window was identified and foregrounded
103
+ //
104
+ // @param {string} profileDir — the persistent profile directory for this session
105
+ // @returns {boolean} true if the window was identified and foregrounded
106
+
107
+ function _windowsForegroundChrome(profileDir) {
108
+ if (os.platform() !== 'win32') return true; // non-Windows: no-op success
109
+ if (!profileDir) return false;
110
+ try {
111
+ const nodePath = require('path');
112
+ const { execFileSync } = require('child_process');
113
+ const root = process.env.SystemRoot || process.env.WINDIR || 'C:\\Windows';
114
+ const psExe = nodePath.join(root, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');
115
+
116
+ // Fixed PowerShell script — NO user data interpolation.
117
+ // The profileDir is passed via STDIN and read by the script.
118
+ // Add-Type is defined BEFORE any call to SetForegroundWindow.
119
+ // The script:
120
+ // 1. Reads the profileDir from stdin
121
+ // 2. Finds chrome.exe processes whose command line contains that exact path
122
+ // 3. Gets the MainWindowHandle of that specific process
123
+ // 4. Uses SetForegroundWindow + ShowWindowAsync to restore+foreground it
124
+ // 5. Outputs "OK" or "FAIL" so the caller knows whether it worked
125
+ const script =
126
+ "$ErrorActionPreference='Stop'; " +
127
+ "Add-Type -Namespace Win32 -Name Native -MemberDefinition '" +
128
+ "[DllImport(\"user32.dll\")] public static extern bool SetForegroundWindow(IntPtr hWnd); " +
129
+ "[DllImport(\"user32.dll\")] public static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow); " +
130
+ "[DllImport(\"user32.dll\")] public static extern bool IsIconic(IntPtr hWnd); " +
131
+ "'; " +
132
+ "$profileDir = [Console]::In.ReadToEnd().Trim(); " +
133
+ "if (-not $profileDir) { Write-Output 'FAIL:no_profile'; exit 0 }; " +
134
+ "$procs = Get-CimInstance Win32_Process -Filter \"Name='chrome.exe'\" -ErrorAction SilentlyContinue; " +
135
+ "$target = $null; " +
136
+ "foreach ($p in $procs) { " +
137
+ " if ($p.CommandLine -and ($p.CommandLine -like \"*$profileDir*\")) { $target = $p; break } " +
138
+ "}; " +
139
+ "if (-not $target) { Write-Output 'FAIL:no_process'; exit 0 }; " +
140
+ "$proc = Get-Process -Id $target.ProcessId -ErrorAction SilentlyContinue; " +
141
+ "if (-not $proc -or $proc.MainWindowHandle -eq [IntPtr]::Zero) { Write-Output 'FAIL:no_window'; exit 0 }; " +
142
+ "$handle = $proc.MainWindowHandle; " +
143
+ "if ([Win32.Native]::IsIconic($handle)) { [void][Win32.Native]::ShowWindowAsync($handle, 9) }; " +
144
+ "$result = [Win32.Native]::SetForegroundWindow($handle); " +
145
+ "if ($result) { Write-Output 'OK' } else { Write-Output 'FAIL:foreground' }";
146
+
147
+ const output = execFileSync(psExe, ['-NoProfile', '-NonInteractive', '-Command', script], {
148
+ windowsHide: true,
149
+ encoding: 'utf8',
150
+ timeout: 5000,
151
+ input: profileDir, // profileDir via STDIN — never in command arguments
152
+ }).trim();
153
+
154
+ return output === 'OK';
155
+ } catch {
156
+ // Foreground helper failed — return false so visible is not claimed
157
+ return false;
158
+ }
159
+ }
160
+
161
+ // Active sessions: accountId -> { context, page, profileDir }
162
+ const activeSessions = new Map();
163
+
164
+ // Per-runtime state (B4 fix): each setupSessionHandler call creates a fresh
165
+ // runtime object so a newly initialized handler starts connected and does
166
+ // NOT inherit stale state from a prior handler lifecycle. The module-level
167
+ // `currentRuntime` is only used so markDisconnected() / closeAllSessions()
168
+ // (called from cli.js) can reach the active runtime without an explicit
169
+ // handle. One handler disconnecting cannot poison another handler's runtime.
170
+ const currentRuntime = { disconnected: false, sessions: activeSessions };
171
+
172
+ /**
173
+ * Mark the CURRENT runtime as disconnected. After this, every inbound command
174
+ * for that runtime is rejected with a clear error and no new browser work is
175
+ * performed. A new setupSessionHandler call creates a fresh runtime that
176
+ * starts connected.
177
+ */
178
+ function markDisconnected() {
179
+ currentRuntime.disconnected = true;
180
+ }
181
+
182
+ /**
183
+ * Close every active browser context, preserving profile/cookies through the
184
+ * existing safe persistence path (the context close flushes the persistent
185
+ * profile dir). Clears the active-sessions map. Safe to call multiple times.
186
+ * Operates on the current runtime's sessions.
187
+ *
188
+ * @returns {Promise<{ closed: number }>}
189
+ */
190
+ async function closeAllSessions() {
191
+ const sessions = currentRuntime.sessions || activeSessions;
192
+ const keys = Array.from(sessions.keys());
193
+ let closed = 0;
194
+ for (const accountId of keys) {
195
+ const session = sessions.get(accountId);
196
+ if (!session) continue;
197
+ // Delete BEFORE closing so a concurrent call does not double-close.
198
+ sessions.delete(accountId);
199
+ try {
200
+ if (session.context) await session.context.close().catch(() => {});
201
+ } catch {}
202
+ closed += 1;
203
+ }
204
+ return { closed };
205
+ }
206
+
207
+ /**
208
+ * Set up the session handler on an authenticated WebSocket.
209
+ *
210
+ * @param {WebSocket} ws — authenticated v2 WebSocket
211
+ * @param {object} opts — { chromePath, deviceMeta, serverOrigin }
212
+ * @returns {Map} the active sessions map
213
+ */
214
+ function setupSessionHandler(ws, opts) {
215
+ // B4 fix: reset the per-runtime state so a newly initialized handler starts
216
+ // connected and does NOT inherit stale state from a prior handler lifecycle.
217
+ // The module-level `currentRuntime` is shared so cli.js's markDisconnected()
218
+ // / closeAllSessions() reach the active runtime. Each setupSessionHandler
219
+ // call resets it to connected.
220
+ currentRuntime.disconnected = false;
221
+ currentRuntime.sessions = activeSessions;
222
+
223
+ // ── Agent → server heartbeat (protocol v2) ────────────────────────────────
224
+ // The server closes the WS with 4002 "Heartbeat timeout" when no inbound
225
+ // frame refreshes lastHeartbeat for 3× HEARTBEAT_SECONDS (20s → 60s). The
226
+ // server never sends its own heartbeat frames, so a v2 agent that only
227
+ // RESPONDS to (never-sent) heartbeats is disconnected after ~60s. This
228
+ // mirrors the v1 agent: send an application-level {type:'heartbeat'} frame
229
+ // every 10s (well within the 60s budget and the server's per-type rate
230
+ // limit) plus a WS protocol ping to keep proxies from idling out.
231
+ let heartbeatTimer = null;
232
+ const HEARTBEAT_INTERVAL_MS = parseInt(process.env.AGENT_HEARTBEAT_INTERVAL_MS || '10000', 10);
233
+
234
+ function _stopAgentHeartbeat() {
235
+ if (heartbeatTimer) { clearInterval(heartbeatTimer); heartbeatTimer = null; }
236
+ }
237
+
238
+ function _startAgentHeartbeat() {
239
+ _stopAgentHeartbeat();
240
+ heartbeatTimer = setInterval(() => {
241
+ if (ws.readyState !== 1 /* OPEN */) return; // server handles reconnect/close
242
+ try {
243
+ ws.send(JSON.stringify({ type: 'heartbeat' }));
244
+ } catch {}
245
+ try { ws.ping(); } catch {}
246
+ }, HEARTBEAT_INTERVAL_MS);
247
+ // Do not let the heartbeat timer keep the process alive on its own.
248
+ if (typeof heartbeatTimer.unref === 'function') heartbeatTimer.unref();
249
+ }
250
+
251
+ _startAgentHeartbeat();
252
+ ws.on('close', _stopAgentHeartbeat);
253
+
254
+ ws.on('message', (data, isBinary) => {
255
+ if (isBinary) return;
256
+
257
+ let msg;
258
+ try {
259
+ msg = JSON.parse(data.toString('utf8'));
260
+ } catch {
261
+ return;
262
+ }
263
+
264
+ if (!msg || typeof msg !== 'object') return;
265
+
266
+ // Handle the existing hardened command envelope (Defect 8).
267
+ if (msg.type === 'command') {
268
+ // Fail-safe: after the authenticated WebSocket closed, no further commands
269
+ // may be accepted. A stale/zombie socket must never drive a browser.
270
+ if (currentRuntime.disconnected) {
271
+ const echo = _extractEcho(msg);
272
+ try {
273
+ ws.send(JSON.stringify({
274
+ type: 'command-response',
275
+ commandId: msg.commandId,
276
+ result: { success: false, error: 'Agent disconnected: commands no longer accepted' },
277
+ ...echo,
278
+ }));
279
+ } catch {}
280
+ return;
281
+ }
282
+ _handleCommandEnvelope(ws, msg, opts).catch((err) => {
283
+ // Send error response with echo (never leak secrets).
284
+ const echo = _extractEcho(msg);
285
+ try {
286
+ ws.send(JSON.stringify({
287
+ type: 'command-response',
288
+ commandId: msg.commandId,
289
+ result: { success: false, error: _safeError(err) },
290
+ ...echo,
291
+ }));
292
+ } catch {}
293
+ });
294
+ return;
295
+ }
296
+
297
+ // Handle heartbeats.
298
+ if (msg.type === 'heartbeat') {
299
+ try { ws.send(JSON.stringify({ type: 'heartbeat-ack' })); } catch {}
300
+ return;
301
+ }
302
+
303
+ // Reconnect reconciliation: the server asks for an active-sessions report.
304
+ // Each entry is lease-bound (accountUuid + leaseId + leaseToken + status).
305
+ // A missing/invalid status is NEVER defaulted to 'running' — the server
306
+ // treats an unverified entry as unresolved (the lease stays blocking).
307
+ if (msg.type === 'report-sessions') {
308
+ try {
309
+ const sessions = [];
310
+ for (const [accountId, session] of activeSessions) {
311
+ const lease = (session.lease && typeof session.lease.getClientView === 'function')
312
+ ? session.lease.getClientView()
313
+ : (session.lease || null);
314
+ sessions.push({
315
+ accountId,
316
+ accountUuid: session.accountUuid || null,
317
+ leaseId: (lease && lease.leaseId) || null,
318
+ leaseToken: (lease && lease.leaseToken) || null,
319
+ status: session.context ? 'running' : 'stopped',
320
+ });
321
+ }
322
+ ws.send(JSON.stringify({ type: 'sessions-report', sessions }));
323
+ } catch {}
324
+ return;
325
+ }
326
+
327
+ // Reconnect reconciliation: the server asks for the exact-profile liveness
328
+ // verdict for a stale lease this device owns (recovery probe). This lets a
329
+ // restarted agent process resolve its own stale recovery_required lease
330
+ // WITHOUT the lost in-memory token — the reply is nonce-bound and carries
331
+ // only the liveness verdict (never a token).
332
+ if (msg.type === 'recovery-probe') {
333
+ try {
334
+ const verdict = _recoveryVerdict(msg, opts);
335
+ ws.send(JSON.stringify({
336
+ type: 'recovery-probe-response',
337
+ probeId: msg.probeId,
338
+ nonce: msg.nonce,
339
+ accountUuid: msg.accountUuid,
340
+ leaseId: msg.leaseId || null,
341
+ verdict,
342
+ }));
343
+ } catch {}
344
+ return;
345
+ }
346
+
347
+ // session-status ack: the server confirms a stop was verified. No-op here
348
+ // beyond acknowledging; the lease stays under server authority.
349
+ if (msg.type === 'session-status') {
350
+ try { ws.send(JSON.stringify({ type: 'session-status-ack', commandId: msg.commandId || null })); } catch {}
351
+ return;
352
+ }
353
+
354
+ // Other message types (session-status, sessions-report, log) are handled
355
+ // by the shared engine on the backend side — the agent only needs to
356
+ // respond to commands and heartbeats.
357
+ });
358
+
359
+ return activeSessions;
360
+ }
361
+
362
+ /**
363
+ * Handle a command envelope: { type: 'command', commandId, accountId, command: { type, ... } }
364
+ *
365
+ * This delegates to the same session management logic used by the legacy agent,
366
+ * preserving all hardened safeguards (Defect 9).
367
+ */
368
+ async function _handleCommandEnvelope(ws, msg, opts) {
369
+ const { commandId, accountId, command } = msg;
370
+
371
+ if (!commandId || typeof commandId !== 'string') {
372
+ return; // Malformed — drop silently.
373
+ }
374
+ if (!command || typeof command !== 'object') {
375
+ _sendResponse(ws, msg, { success: false, error: 'Missing command object' });
376
+ return;
377
+ }
378
+
379
+ const { type, ...rest } = command;
380
+
381
+ // Build the echo object from the envelope (nonce, leaseId, accountUuid).
382
+ const echo = _extractEcho(msg);
383
+
384
+ // Validate command type against the known allowlist.
385
+ const ALLOWED_TYPES = new Set([
386
+ 'startSession', 'stopSession', 'restartSession', 'refreshSession',
387
+ 'navigate', 'type', 'paste', 'press', 'click', 'runAction',
388
+ 'getStatus', 'importLegacyProfile', 'discoverLegacyProfiles',
389
+ 'focus',
390
+ ]);
391
+
392
+ if (!ALLOWED_TYPES.has(type)) {
393
+ _sendResponse(ws, msg, { success: false, error: 'Unknown command type' });
394
+ return;
395
+ }
396
+
397
+ // Lease-required commands (same set as legacy agent).
398
+ const LEASE_REQUIRED = new Set([
399
+ 'stopSession', 'restartSession', 'refreshSession', 'navigate',
400
+ 'type', 'paste', 'press', 'click', 'runAction', 'focus',
401
+ ]);
402
+
403
+ // Execute the command using the shared runtime.
404
+ try {
405
+ const result = await _executeCommand(type, { ...rest, accountId }, msg, opts, ws);
406
+ _sendResponse(ws, msg, result, echo);
407
+ } catch (err) {
408
+ _sendResponse(ws, msg, { success: false, error: _safeError(err) }, echo);
409
+ }
410
+ }
411
+
412
+ /**
413
+ * Execute a single command. This reuses the existing hardened runtime logic.
414
+ */
415
+ async function _executeCommand(type, params, msg, opts, ws) {
416
+ const accountId = params.accountId || msg.accountId;
417
+ const accountUuid = msg.accountUuid || params.accountUuid;
418
+ const lease = params.lease || msg.command?.lease;
419
+
420
+ switch (type) {
421
+ case 'startSession':
422
+ return _startSession(params, opts, accountId, accountUuid, lease, ws);
423
+ case 'stopSession':
424
+ return _stopSession(accountId, lease, ws);
425
+ case 'restartSession':
426
+ await _stopSession(accountId, lease, ws);
427
+ return _startSession(params, opts, accountId, accountUuid, lease, ws);
428
+ case 'refreshSession':
429
+ return _refreshSession(accountId);
430
+ case 'navigate':
431
+ return _navigate(accountId, params.url);
432
+ case 'type':
433
+ return _typeText(accountId, params.selector, params.text);
434
+ case 'paste':
435
+ return _typeText(accountId, params.selector, params.text);
436
+ case 'press':
437
+ return _pressKey(accountId, params.key);
438
+ case 'click':
439
+ return _click(accountId, params.selector);
440
+ case 'focus':
441
+ return _focusSession(accountId);
442
+ case 'runAction':
443
+ return _runAction(accountId, params.action, params.payload || params.args);
444
+ case 'getStatus':
445
+ return _getStatus();
446
+ case 'importLegacyProfile':
447
+ return _importLegacyProfile(accountId, accountUuid, opts);
448
+ case 'discoverLegacyProfiles':
449
+ return _discoverLegacyProfiles();
450
+ default:
451
+ return { success: false, error: 'Unknown command type' };
452
+ }
453
+ }
454
+
455
+ // ── Session management (reuses existing hardened modules) ───────────────────
456
+
457
+ async function _startSession(params, opts, accountId, accountUuid, lease, ws) {
458
+ if (!accountId) return { success: false, error: 'Missing accountId' };
459
+
460
+ // Lease-bound error reporter: a FAILED start sends a lease-bound
461
+ // session-status 'error' so the server releases the lease it acquired for
462
+ // this attempt (parity with the hardened v1 runtime). Without it the lease
463
+ // stays 'acquiring' and blocks the account until it expires.
464
+ const _sendStartError = (error) => {
465
+ if (!ws || !lease) return;
466
+ try {
467
+ const tmp = {};
468
+ leaseClient.bind(tmp, lease);
469
+ ws.send(JSON.stringify(leaseClient.boundStatusMessage(tmp, accountId, 'error', { error })));
470
+ } catch {}
471
+ };
472
+
473
+ const deviceMeta = opts.deviceMeta;
474
+ // Phase 14 / schema-4: the profile identity requires ALL FOUR UUIDs
475
+ // (server/tenant/account/device). The command's options carry the
476
+ // server-assigned serverUuid + tenantUuid; the device UUID comes from this
477
+ // device's metadata. Without all four, resolveProfileDir throws
478
+ // PROFILE_IDENTITY_INCOMPLETE and no browser can ever launch.
479
+ const identity = params.options || params;
480
+ const serverUuid = identity.serverUuid || null;
481
+ const tenantUuid = identity.tenantUuid || null;
482
+ const resolvedAccountUuid = identity.accountUuid || accountUuid || null;
483
+
484
+ // Fail closed with a clear, actionable error if the server did not send the
485
+ // complete immutable tuple (a profile is never opened with a partial
486
+ // identity).
487
+ if (!serverUuid || !tenantUuid || !resolvedAccountUuid || !deviceMeta.deviceId) {
488
+ _sendStartError('PROFILE_IDENTITY_INCOMPLETE');
489
+ return {
490
+ success: false,
491
+ error: 'PROFILE_IDENTITY_INCOMPLETE: the server did not provide the full profile identity (serverUuid/tenantUuid/accountUuid). Cannot open a browser profile.',
492
+ };
493
+ }
494
+
495
+ const profileDir = resolveProfileDir({
496
+ profilesDir: PROFILES_DIR,
497
+ serverUuid,
498
+ tenantUuid,
499
+ accountUuid: resolvedAccountUuid,
500
+ deviceUuid: deviceMeta.deviceId,
501
+ }).dir;
502
+
503
+ const fs = require('fs');
504
+ if (!fs.existsSync(profileDir)) fs.mkdirSync(profileDir, { recursive: true });
505
+
506
+ // fingerprintStore.loadOrGenerate takes an OBJECT ({ profileDir, accountId,
507
+ // options, generator }) — matching the hardened v1 runtime call. The
508
+ // positional form threw "paths[0] must be of type string" and aborted every
509
+ // launch. Live operator options (mobileView/locale/userAgent/timezone) are
510
+ // re-applied on every launch; the randomized hardware identity is persisted
511
+ // inside the profile dir and stays stable across launches.
512
+ const launchOpts = params.options || {};
513
+ const fingerprint = fingerprintStore.loadOrGenerate({
514
+ profileDir,
515
+ accountId: String(accountId),
516
+ options: {
517
+ mobileView: launchOpts.mobileView || false,
518
+ locale: launchOpts.locale || null,
519
+ userAgent: launchOpts.userAgent || null,
520
+ timezone: launchOpts.timezone || null,
521
+ },
522
+ generator: generateFingerprint,
523
+ });
524
+
525
+ // ── Phase 16 fail-closed proxy policy (parity with the hardened v1 runtime) ──
526
+ // A missing/unknown networkMode ABORTS; no proxy + proxy_required ABORTS
527
+ // (never silently open a direct browser that leaks the real IP); a configured
528
+ // proxy must be reachable AND egress from a different IP (isolation), or the
529
+ // launch aborts. We never fall open to direct.
530
+ const proxyStr = launchOpts.proxy || null;
531
+ const networkMode = launchOpts.networkMode || null;
532
+
533
+ // Health-check the proxy only when one was configured. verifyProxyIsolation
534
+ // does the full fail-closed verification (CONNECT + TLS + GET through the
535
+ // proxy, plus an independent direct public-IP fetch and comparison) — a
536
+ // superset of the v1 TCP pre-check. A proxy that accepts TCP but egresses
537
+ // from the device's own IP (transparent/misconfigured) is refused.
538
+ let health = null;
539
+ if (proxyStr) {
540
+ const parsedProxy = _parseProxy(proxyStr);
541
+ if (!parsedProxy) {
542
+ health = { ok: false, reason: 'proxy_unreachable', code: 'PROXY_MALFORMED' };
543
+ } else {
544
+ const isolation = await require('./proxyEgress').verifyProxyIsolation(parsedProxy, {}).catch(() => ({ ok: false, code: 'PROXY_ISOLATION_ERROR' }));
545
+ health = isolation && isolation.ok
546
+ ? { ok: true, reason: 'proxy_ok', egressIp: isolation.egressIp, directIp: isolation.directIp }
547
+ : { ok: false, reason: 'proxy_isolation_failed: ' + ((isolation && (isolation.code || isolation.reason)) || 'unknown'), code: isolation && isolation.code };
548
+ }
549
+ }
550
+
551
+ const decision = require('./proxyPolicy').decideProxyLaunch({
552
+ proxyStr,
553
+ networkMode,
554
+ health,
555
+ });
556
+ if (decision.action === 'abort') {
557
+ _sendStartError(decision.error);
558
+ return { success: false, error: decision.error, code: decision.reason.toUpperCase() };
559
+ }
560
+
561
+ const args = [
562
+ '--disable-blink-features=AutomationControlled',
563
+ '--force-webrtc-ip-handling-policy=disable_non_proxied_udp',
564
+ '--no-first-run',
565
+ '--no-default-browser-check',
566
+ '--start-maximized',
567
+ ];
568
+
569
+ // Prefer noDefaultViewport: true so the real OS window fills the screen
570
+ // (helps the launched browser appear visibly foregrounded). The per-account
571
+ // fingerprint invariants are enforced by the stealth init script against
572
+ // the *screen* object (window.screen.width/height), NOT against the
573
+ // Playwright viewport, so removing the forced viewport does not weaken the
574
+ // fingerprint. window.innerWidth/innerHeight are left to the real window
575
+ // size, which is acceptable because the stealth script does not pin them.
576
+ const launchOptions = {
577
+ executablePath: opts.chromePath,
578
+ headless: false,
579
+ args,
580
+ noDefaultViewport: true,
581
+ };
582
+
583
+ if (decision.useProxy && proxyStr) {
584
+ const proxyUrl = _parseProxy(proxyStr);
585
+ if (proxyUrl) launchOptions.proxy = proxyUrl;
586
+ }
587
+
588
+ let context;
589
+ try {
590
+ context = await chromium.launchPersistentContext(profileDir, launchOptions);
591
+ } catch (err) {
592
+ _sendStartError(_safeError(err));
593
+ return { success: false, error: _safeError(err) };
594
+ }
595
+
596
+ await context.addInitScript(buildStealthScript(fingerprint));
597
+
598
+ // The server sends cookies in options (options.cookies); accept the flat
599
+ // params form too for robustness.
600
+ const cookiesToInject = launchOpts.cookies || params.cookies;
601
+ if (cookiesToInject && Array.isArray(cookiesToInject)) {
602
+ try { await context.addCookies(cookiesToInject); } catch {}
603
+ }
604
+
605
+ const pages = context.pages();
606
+ const page = pages[0] || await context.newPage();
607
+
608
+ const url = params.url || 'https://x.com/home';
609
+ await page.goto(url, { waitUntil: 'domcontentloaded' }).catch(() => {});
610
+
611
+ // If the browser launched but immediately closed, report a clear error
612
+ // instead of showing a misleading green "browser opened" toast.
613
+ if (page.isClosed()) {
614
+ try { await context.close().catch(() => {}); } catch {}
615
+ return {
616
+ success: false,
617
+ error: 'Browser launched but closed immediately. The session was not started.',
618
+ };
619
+ }
620
+
621
+ // Foreground the newly launched window so the user actually sees it.
622
+ // Do NOT report success until the page is confirmed focused.
623
+ let bringToFrontOk = false;
624
+ try {
625
+ await page.bringToFront();
626
+ bringToFrontOk = true;
627
+ } catch (err) {
628
+ try { await context.close().catch(() => {}); } catch {}
629
+ return {
630
+ success: false,
631
+ error: 'Browser launched but could not be brought to the foreground: ' + _safeError(err),
632
+ };
633
+ }
634
+
635
+ // Windows-specific foreground: page.bringToFront() alone may not overcome
636
+ // the Windows foreground lock. This helper targets the EXACT Chrome process
637
+ // whose command line contains this session's profileDir (passed via stdin,
638
+ // not interpolated). It returns true ONLY if the intended window was
639
+ // identified and successfully foregrounded.
640
+ let foregroundVerified = false;
641
+ if (bringToFrontOk) {
642
+ foregroundVerified = _windowsForegroundChrome(profileDir);
643
+ }
644
+
645
+ // Re-check after focus: the page may have closed in the meantime.
646
+ if (page.isClosed()) {
647
+ try { await context.close().catch(() => {}); } catch {}
648
+ return {
649
+ success: false,
650
+ error: 'Browser closed immediately after focusing. The session was not started.',
651
+ };
652
+ }
653
+
654
+ const session = { context, page, profileDir, accountId, lease: null };
655
+ if (lease) leaseClient.bind(session, lease);
656
+ activeSessions.set(accountId, session);
657
+
658
+ // ── Lease-bound session-status reporting (Phase 3 parity with v1) ──────────
659
+ // The server's session cache (`agent.sessions`) and the durable lease TTL
660
+ // are ONLY updated by lease-bound `session-status` frames — never by the
661
+ // command-response alone. Without this frame the server reports the session
662
+ // 'stopped' even though the local browser is running, and the lease never
663
+ // activates. The credential (leaseId + leaseToken) is echoed so the server
664
+ // can verify the holder; it is never logged, never persisted to disk.
665
+ const _sendStatus = (status, extra) => {
666
+ try { ws.send(JSON.stringify(leaseClient.boundStatusMessage(session, accountId, status, extra))); } catch {}
667
+ };
668
+ _sendStatus('running');
669
+
670
+ // A browser context closed outside our control (user closed the window,
671
+ // crash): report the verified stop so the server releases the lease — a
672
+ // dead local browser must not keep the account locked.
673
+ context.on('close', () => {
674
+ const closed = activeSessions.get(accountId);
675
+ if (closed === session) activeSessions.delete(accountId);
676
+ try { ws.send(JSON.stringify(leaseClient.boundStatusMessage(closed || session, accountId, 'stopped'))); } catch {}
677
+ });
678
+
679
+ // Return confirmed success metadata. The backend/frontend uses this to
680
+ // show a green toast ONLY when the browser is genuinely started and visible.
681
+ //
682
+ // visible: true requires POSITIVE evidence:
683
+ // - launchPersistentContext succeeded
684
+ // - page exists and is not closed
685
+ // - page.bringToFront() succeeded
686
+ // - on Windows: the intended Chrome process was identified and
687
+ // SetForegroundWindow succeeded (or on non-Windows: bringToFront is
688
+ // sufficient)
689
+ //
690
+ // If the Windows foreground helper cannot prove the window is visible
691
+ // (foregroundVerified = false), we return started:true but visible:false
692
+ // with an actionable error so the frontend does NOT show a green toast.
693
+ if (os.platform() === 'win32' && !foregroundVerified) {
694
+ // The browser launched and bringToFront succeeded, but we could not
695
+ // positively verify the window is in the foreground. Return a safe
696
+ // actionable message — NOT a green toast.
697
+ return {
698
+ success: true,
699
+ accountId,
700
+ started: true,
701
+ visible: false,
702
+ sessionId: accountId,
703
+ error: 'Browser launched but could not be confirmed in the foreground. Check the taskbar for the Chrome window.',
704
+ };
705
+ }
706
+
707
+ return {
708
+ success: true,
709
+ accountId,
710
+ started: true,
711
+ visible: true,
712
+ sessionId: accountId,
713
+ };
714
+ }
715
+
716
+ async function _stopSession(accountId, lease, ws) {
717
+ const session = activeSessions.get(accountId);
718
+ if (!session) return { success: false, error: 'Session not found' };
719
+ try { await session.context.close(); } catch {}
720
+ activeSessions.delete(accountId);
721
+ // Lease-bound stop ack: the server verifies the credential and releases the
722
+ // durable lease. This is the only thing that completes a takeover.
723
+ if (ws) {
724
+ try { ws.send(JSON.stringify(leaseClient.boundStatusMessage(session, accountId, 'stopped'))); } catch {}
725
+ }
726
+ return { success: true, accountId, stopped: true };
727
+ }
728
+
729
+ async function _refreshSession(accountId) {
730
+ const session = activeSessions.get(accountId);
731
+ if (!session) return { success: false, error: 'Session not found' };
732
+ await session.page.reload();
733
+ return { success: true };
734
+ }
735
+
736
+ async function _navigate(accountId, url) {
737
+ const session = activeSessions.get(accountId);
738
+ if (!session) return { success: false, error: 'Session not found' };
739
+ await session.page.goto(url, { waitUntil: 'domcontentloaded' });
740
+ return { success: true };
741
+ }
742
+
743
+ async function _typeText(accountId, selector, text) {
744
+ const session = activeSessions.get(accountId);
745
+ if (!session) return { success: false, error: 'Session not found' };
746
+ await session.page.locator(selector).fill(text);
747
+ return { success: true };
748
+ }
749
+
750
+ async function _pressKey(accountId, key) {
751
+ const session = activeSessions.get(accountId);
752
+ if (!session) return { success: false, error: 'Session not found' };
753
+ await session.page.keyboard.press(key);
754
+ return { success: true };
755
+ }
756
+
757
+ async function _click(accountId, selector) {
758
+ const session = activeSessions.get(accountId);
759
+ if (!session) return { success: false, error: 'Session not found' };
760
+ await session.page.locator(selector).click();
761
+ return { success: true };
762
+ }
763
+
764
+ async function _focusSession(accountId) {
765
+ const session = activeSessions.get(accountId);
766
+ if (!session) return { success: false, error: 'Session not found' };
767
+ await session.page.bringToFront();
768
+ return { success: true };
769
+ }
770
+
771
+ async function _runAction(accountId, action, payload) {
772
+ const session = activeSessions.get(accountId);
773
+ if (!session) return { success: false, error: 'Session not found' };
774
+ const { runAction } = require('./actions');
775
+ const result = await runAction(session.page, action, payload || {});
776
+ return { success: true, result };
777
+ }
778
+
779
+ function _getStatus() {
780
+ const sessions = [];
781
+ for (const [accountId, session] of activeSessions) {
782
+ sessions.push({ accountId, url: session.page ? session.page.url() : null });
783
+ }
784
+ return { success: true, sessions, count: sessions.length };
785
+ }
786
+
787
+ function _importLegacyProfile(accountId, accountUuid, opts) {
788
+ // Defect 9 fix: pass opts correctly (was undefined before).
789
+ const result = importLegacyProfile(accountId, {
790
+ profileRoot: PROFILES_DIR,
791
+ deviceUuid: opts.deviceMeta.deviceId,
792
+ accountUuid,
793
+ });
794
+ return { success: true, result };
795
+ }
796
+
797
+ function _discoverLegacyProfiles() {
798
+ const profiles = discoverLegacyProfiles(PROFILES_DIR);
799
+ return { success: true, profiles };
800
+ }
801
+
802
+ // ── Helpers ──────────────────────────────────────────────────────────────────
803
+
804
+ /**
805
+ * Compute the exact-profile liveness verdict for a recovery probe. Resolves the
806
+ * EXACT profile dir from the server-supplied immutable identity tuple (using the
807
+ * same hardened profile-path logic as launch) and matches it against live Chrome
808
+ * command lines. Returns 'running' | 'stopped' | 'unknown' (fail closed to
809
+ * 'unknown' whenever the profile cannot be resolved or inspected).
810
+ */
811
+ function _recoveryVerdict(msg, opts) {
812
+ const deviceMeta = (opts && opts.deviceMeta) || {};
813
+ const accountUuid = msg.accountUuid || null;
814
+ const serverUuid = msg.serverUuid || null;
815
+ const tenantUuid = msg.tenantUuid || null;
816
+ const deviceUuid = msg.deviceUuid || deviceMeta.deviceId || null;
817
+ if (!accountUuid || !serverUuid || !tenantUuid || !deviceUuid) return 'unknown';
818
+ let dir;
819
+ try {
820
+ dir = resolveProfileDir({
821
+ profilesDir: PROFILES_DIR,
822
+ serverUuid,
823
+ tenantUuid,
824
+ accountUuid,
825
+ deviceUuid,
826
+ }).dir;
827
+ } catch {
828
+ return 'unknown';
829
+ }
830
+ return _detectProfileChromeRunning(dir);
831
+ }
832
+
833
+ function _extractEcho(msg) {
834
+ const echo = {};
835
+ if (msg.nonce) echo.nonce = msg.nonce;
836
+ if (msg.leaseId) echo.leaseId = msg.leaseId;
837
+ if (msg.accountUuid) echo.accountUuid = msg.accountUuid;
838
+ return echo;
839
+ }
840
+
841
+ function _sendResponse(ws, msg, result, echo) {
842
+ try {
843
+ ws.send(JSON.stringify({
844
+ type: 'command-response',
845
+ commandId: msg.commandId,
846
+ result,
847
+ ...(echo || _extractEcho(msg)),
848
+ }));
849
+ } catch {}
850
+ }
851
+
852
+ function _parseProxy(proxyStr) {
853
+ if (!proxyStr || typeof proxyStr !== 'string') return null;
854
+ const parts = proxyStr.split(':');
855
+ if (parts.length >= 2) {
856
+ const proxy = { server: `http://${parts[0]}:${parts[1]}` };
857
+ if (parts[2] && parts[3]) {
858
+ proxy.username = parts[2];
859
+ proxy.password = parts[3];
860
+ }
861
+ return proxy;
862
+ }
863
+ return null;
864
+ }
865
+
866
+ function _safeError(err) {
867
+ const msg = err && err.message ? err.message : String(err);
868
+ return msg
869
+ .replace(/[A-Fa-f0-9]{64}/g, '<hex>')
870
+ .replace(/eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g, '<jwt>')
871
+ .slice(0, 500);
872
+ }
873
+
874
+ module.exports = { setupSessionHandler, activeSessions, closeAllSessions, markDisconnected, _detectProfileChromeRunning, _recoveryVerdict, _setChromeLinesProvider };