@xkwdstore/agent 2.0.3 → 2.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -4,10 +4,12 @@ Terminal-only, cryptographically authenticated CLI for XKWDStore browser automat
4
4
 
5
5
  ## Installation
6
6
 
7
- > **@xkwdstore/agent 2.0.2 is now publicly available on npm.**
7
+ > **@xkwdstore/agent 2.0.3 is the last version published on npm.**
8
8
  >
9
- > Version 2.0.2 (Protocol-v2 Windows browser-launch fix) is the current
10
- > published version on the official npm registry.
9
+ > The current source version is **2.0.5** (window-truth visibility fix,
10
+ > lifecycle cause codes, cookie parity, stopped-frame dedupe). It is
11
+ > NOT claimed to be published unless the release workflow has published it — see
12
+ > `reports/` for the authoritative publication state.
11
13
 
12
14
  End users install by downloading the installer file first, then running it
13
15
  (the installer explicitly forbids piping a remote script directly into
@@ -28,7 +30,7 @@ curl -L -o "%TEMP%\xkwdstore-install.ps1" https://raw.githubusercontent.com/Essa
28
30
  The generated launcher runs the pinned command:
29
31
 
30
32
  ```powershell
31
- npx --yes @xkwdstore/agent@2.0.2 start
33
+ npx --yes @xkwdstore/agent@2.0.5 start
32
34
  ```
33
35
 
34
36
  Automated installer tests use `-NoLaunch` or a mocked `npx` command so the
@@ -173,14 +175,15 @@ Windows runner (pending CI billing restoration).
173
175
  ## Version Management
174
176
 
175
177
  The agent does NOT update itself. To use a newer version, change the version
176
- number in the command. The pinned future command for this release is:
178
+ number in the command. The pinned command for this release is:
177
179
 
178
180
  ```powershell
179
- npx --yes @xkwdstore/agent@2.0.2 start
181
+ npx --yes @xkwdstore/agent@2.0.5 start
180
182
  ```
181
183
 
182
- > Version 2.0.2 is the current published version. Version 2.0.1 was the
183
- > previous release. The pinned command reflects the latest published version.
184
+ > 2.0.5 is the current local agent version (window-truth visibility fix,
185
+ > lifecycle cause codes, cookie parity, stopped-frame dedupe).
186
+ > 2.0.3 was the previous release.
184
187
  >
185
188
  > The server checks compatibility at startup and displays a clear message if
186
189
  > the agent version is no longer supported.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xkwdstore/agent",
3
- "version": "2.0.3",
3
+ "version": "2.0.5",
4
4
  "description": "XKWDStore Agent — terminal-only, cryptographically authenticated CLI for browser automation",
5
5
  "main": "src/cli.js",
6
6
  "bin": {
package/src/cli.js CHANGED
@@ -24,7 +24,7 @@ const crypto = require('crypto');
24
24
  const os = require('os');
25
25
  const path = require('path');
26
26
 
27
- const CLI_VERSION = '2.0.3';
27
+ const CLI_VERSION = '2.0.5';
28
28
  const PROTOCOL_VERSION = 2;
29
29
 
30
30
  // ── Command parsing ──────────────────────────────────────────────────────────
@@ -319,63 +319,135 @@ async function start(serverOrigin, flags) {
319
319
  const { setupSessionHandler, closeAllSessions, markDisconnected } = require('./sessionHandler');
320
320
  const sessions = setupSessionHandler(ws, { chromePath, deviceMeta, serverOrigin });
321
321
 
322
- // 8a. Fail-safe: an authenticated WebSocket closure is not a recoverable
323
- // event in this release. The agent must stop accepting commands, close every
324
- // active browser context (preserving profiles/cookies via the existing
325
- // safe persistence path), clear the sessions map, release the process
326
- // lock, print a clear terminal error, and exit non-zero. We deliberately
327
- // prefer a safe exit over incomplete automatic reconnection here; a future
328
- // reconnect implementation is allowed only if it rebinds the full session
329
- // handler, reconciles every lease, and is covered by deterministic tests.
322
+ // 8a. Disconnect handling with bounded auto-reconnect.
323
+ //
324
+ // The server deliberately closes the WS in two situations where the agent is
325
+ // EXPECTED to reconnect (the dashboard's Restart Agent button promises "the
326
+ // agent will reconnect in a few seconds"):
327
+ // - graceful 'agent-restart' message → code 1000 'agent-restart'
328
+ // - fallback restart → code 4002 'Server-initiated restart'
329
+ // In BOTH cases the local browser sessions are meant to STAY OPEN (only the
330
+ // WS is re-established) — see localAgentServer.restartAgent. On reconnect the
331
+ // server requests a sessions-report and reconciles every lease-bound session
332
+ // itself, so lease reconciliation is server-driven and authoritative.
333
+ //
334
+ // Any OTHER close (heartbeat timeout 4002 'Heartbeat timeout', network 1006,
335
+ // protocol error) is a genuine disconnect: the agent marks itself
336
+ // disconnected, closes every browser context (preserving profiles/cookies),
337
+ // and retries with exponential backoff. After MAX_WS_RECONNECTS consecutive
338
+ // failures the agent exits non-zero with a clear message (the original
339
+ // fail-safe).
330
340
  //
331
341
  // Race guard: `shuttingDown` is set by the deliberate Ctrl+C/SIGTERM path
332
342
  // BEFORE ws.close() is called, so the close event emitted during a
333
- // deliberate shutdown does NOT run the unexpected-disconnect fail-safe.
334
- // This prevents closeAllSessions() from being executed concurrently twice
335
- // and processLock.releaseLock() from being called twice.
336
- let disconnected = false;
343
+ // deliberate shutdown does NOT run this handler.
337
344
  let shuttingDown = false;
338
- ws.on('close', (code, reason) => {
339
- // If a deliberate shutdown is in progress, the close event is expected —
340
- // do NOT run the unexpected-disconnect fail-safe.
345
+ let reconnectAttempts = 0;
346
+ const MAX_WS_RECONNECTS = 10;
347
+ const RECONNECT_BASE_MS = 1000;
348
+ const RECONNECT_MAX_MS = 60000;
349
+
350
+ const _connectOpts = () => ({
351
+ serverOrigin,
352
+ deviceId: deviceMeta.deviceId,
353
+ publicKeyFingerprint: deviceMeta.publicKeyFingerprint,
354
+ privateKeyB64Url,
355
+ protocolVersion: PROTOCOL_VERSION,
356
+ });
357
+
358
+ const _isRestartClose = (code, reasonStr) =>
359
+ (code === 1000 && /agent-restart/i.test(reasonStr))
360
+ || (code === 4002 && /server-initiated restart/i.test(reasonStr));
361
+
362
+ const _delayMs = () => Math.min(RECONNECT_BASE_MS * Math.pow(2, reconnectAttempts), RECONNECT_MAX_MS)
363
+ + Math.floor(Math.random() * 1000);
364
+
365
+ async function _handleWsClose(code, reason) {
341
366
  if (shuttingDown) return;
342
- if (disconnected) return;
343
- disconnected = true;
344
- markDisconnected();
345
367
  const reasonStr = reason ? reason.toString() : '';
346
- console.error(`\n✗ Connection to server lost (code ${code}${reasonStr ? ': ' + reasonStr : ''}).`);
347
- console.error(' Closing all browser sessions and shutting down safely...');
348
368
 
349
- // 4003 = authentication failed (revoked/unknown key). Unlike the initial
350
- // connect path, a 4003 on an ESTABLISHED connection means the device was
351
- // revoked mid-session. The auto-recovery on initial connect handles the
352
- // common case (stored revoked key at startup). For mid-session revocation,
353
- // the agent exits with a clear message — the user should investigate.
354
- const isAuthFailure = code === 4003;
355
-
356
- closeAllSessions().then(({ closed }) => {
369
+ // Deliberate server-initiated restart: rebind WITHOUT touching sessions.
370
+ if (_isRestartClose(code, reasonStr)) {
371
+ console.log('\nℹ️ Server requested a connection restart. Reconnecting (browser sessions stay open)...');
372
+ // Do NOT markDisconnected / closeAllSessions here — the local browsers
373
+ // remain valid; the server reconciles their leases from our
374
+ // sessions-report after we reconnect.
375
+ try { ws.removeAllListeners('close'); } catch {}
376
+ } else {
377
+ // Genuine disconnect: fail-safe. No further commands may run, and every
378
+ // browser context is closed (profiles persist on close).
379
+ console.error(`\n✗ Connection to server lost (code ${code}${reasonStr ? ': ' + reasonStr : ''}).`);
380
+ console.error(' Closing all browser sessions and shutting down safely...');
381
+ markDisconnected();
382
+ const { closed } = await closeAllSessions().catch(() => ({ closed: 0 }));
357
383
  if (closed > 0) console.error(` Closed ${closed} browser session(s).`);
358
- }).catch(() => {}).finally(() => {
359
- try { ws.close(1000, 'Agent shutting down after disconnect'); } catch {}
384
+ try { ws.removeAllListeners('close'); } catch {}
385
+ }
386
+
387
+ // 4003 = revoked mid-session: the credential is dead — re-enroll requires
388
+ // user interaction, so exit with a clear message (no auto-retry loop).
389
+ if (code === 4003) {
390
+ console.error('\n❌ Authentication failed — this device was revoked during the session.');
391
+ console.error(' The server-scoped identity for ' + serverOrigin + ' has been cleared.');
392
+ console.error(' Run `xkwd-agent start` again to re-authorize this computer.');
393
+ try {
394
+ const { deletePrivateKey, deleteMetadata } = require('./deviceKeyStore');
395
+ deletePrivateKey({ serverOrigin });
396
+ deleteMetadata({ serverOrigin });
397
+ } catch {}
360
398
  processLock.releaseLock();
399
+ console.error('Agent stopped.');
400
+ process.exit(1);
401
+ }
361
402
 
362
- if (isAuthFailure) {
363
- console.error('\n❌ Authentication failed — this device was revoked during the session.');
364
- console.error(' The server-scoped identity for ' + serverOrigin + ' has been cleared.');
365
- console.error(' Run `xkwd-agent start` again to re-authorize this computer.');
366
- // Server-scoped cleanup so the next start re-enrolls
367
- try {
368
- const { deletePrivateKey, deleteMetadata } = require('./deviceKeyStore');
369
- deletePrivateKey({ serverOrigin });
370
- deleteMetadata({ serverOrigin });
371
- } catch {}
372
- } else {
373
- console.error('\nTo reconnect, run `xkwd-agent start` again.');
374
- }
403
+ // Bounded reconnect with backoff + jitter (a fresh challenge every time —
404
+ // network loss never re-enrolls; only a 4003 does, handled above).
405
+ reconnectAttempts += 1;
406
+ if (reconnectAttempts > MAX_WS_RECONNECTS) {
407
+ console.error(`\n❌ Could not reconnect after ${MAX_WS_RECONNECTS} attempts.`);
408
+ console.error(' Run `xkwd-agent start` again.');
409
+ processLock.releaseLock();
375
410
  console.error('Agent stopped.');
376
411
  process.exit(1);
377
- });
378
- });
412
+ }
413
+ const delay = _delayMs();
414
+ console.log(` Reconnecting in ${Math.round(delay / 1000)}s (attempt ${reconnectAttempts}/${MAX_WS_RECONNECTS})...`);
415
+ setTimeout(() => { _reconnect().catch(() => {}); }, delay);
416
+ }
417
+
418
+ async function _reconnect() {
419
+ try {
420
+ ws = await connectWebSocket(_connectOpts());
421
+ reconnectAttempts = 0; // reset on a successful re-establish
422
+ // Rebind the FULL session handler on the new socket (fresh runtime
423
+ // state: connected, heartbeat timer, command envelope handling).
424
+ setupSessionHandler(ws, { chromePath, deviceMeta, serverOrigin });
425
+ // A sessions-report request arrives from the server right after
426
+ // authentication; the handler answers it from the live sessions map,
427
+ // which lets the server reconcile/restore every lease.
428
+ console.log('✓ Reconnected.');
429
+ ws.on('close', (code, reason) => { _handleWsClose(code, reason).catch(() => {}); });
430
+ } catch (err) {
431
+ if (_is4003Error(err)) {
432
+ // Fall into the 4003 exit path via the same handler logic.
433
+ await _handleWsClose(4003, Buffer.from('revoked during reconnect'));
434
+ return;
435
+ }
436
+ reconnectAttempts += 1;
437
+ if (reconnectAttempts > MAX_WS_RECONNECTS) {
438
+ console.error(`\n❌ Could not reconnect after ${MAX_WS_RECONNECTS} attempts: ${err.message}`);
439
+ console.error(' Run `xkwd-agent start` again.');
440
+ processLock.releaseLock();
441
+ console.error('Agent stopped.');
442
+ process.exit(1);
443
+ }
444
+ const delay = _delayMs();
445
+ console.log(` Reconnect failed (${err.message}). Retrying in ${Math.round(delay / 1000)}s (attempt ${reconnectAttempts}/${MAX_WS_RECONNECTS})...`);
446
+ setTimeout(() => { _reconnect().catch(() => {}); }, delay);
447
+ }
448
+ }
449
+
450
+ ws.on('close', (code, reason) => { _handleWsClose(code, reason).catch(() => {}); });
379
451
 
380
452
  // 9. Clean shutdown on Ctrl+C
381
453
  async function shutdown(signal) {
@@ -28,29 +28,158 @@ const { buildStealthScript } = require('./stealth');
28
28
  const leaseClient = require('./leaseClient');
29
29
  const { PROFILES_DIR } = require('./deviceKeyStore');
30
30
 
31
- // ── Windows foreground helper ────────────────────────────────────────────────
31
+ // ── Browser-lifecycle diagnostics ────────────────────────────────────────────
32
+ //
33
+ // A browser session that ends by itself previously left NO local trace: the
34
+ // only signal was the lease being released server-side, so "who closed this
35
+ // browser?" could not be answered from the agent. Every path that can end a
36
+ // session now emits one line with a CAUSE CODE. Records only the cause code,
37
+ // the account id and a monotonic timestamp — never cookie/token/credential
38
+ // values and never the profile directory contents.
39
+ //
40
+ // START_SESSION a session was created and registered
41
+ // STOP_COMMAND an explicit stopSession command closed it
42
+ // STOP_NOT_FOUND a stopSession command arrived with no active session
43
+ // STOP_CLOSE_FAILED a stopSession command could NOT confirm the close
44
+ // (fail-closed: no 'stopped' frame was sent, the session
45
+ // stays registered, the lease stays blocking/recoverable)
46
+ // CONTEXT_CLOSE the Playwright context closed (any cause)
47
+ // CONTEXT_CLOSE_DUP a second close event for an already-removed session
48
+ // PAGE_CLOSE a page closed
49
+ // PAGE_CRASH a page crashed
50
+ // BROWSER_DISCONNECTED the underlying browser disconnected
51
+ // CLOSE_ALL_SESSIONS closeAllSessions() ran (agent shutdown / WS loss)
52
+ function _logLifecycle(cause, accountId, extra) {
53
+ try {
54
+ const detail = extra ? ' ' + JSON.stringify(extra) : '';
55
+ process.stderr.write(`[session-lifecycle] ${new Date().toISOString()} ${cause} account=${accountId}${detail}\n`);
56
+ } catch {}
57
+ }
58
+
59
+ // ── Exact-profile Chrome detection (recovery probe) ──────────────────────────
60
+ //
61
+ // "activeSessions is empty" is NOT proof a browser stopped: an agent-process
62
+ // restart clears that map while Chrome may still be running. Recovery must use
63
+ // EXACT profile/process verification. We enumerate chrome.exe command lines and
64
+ // match the EXACT --user-data-dir against this account's resolved profile dir —
65
+ // never "newest Chrome", "any chrome.exe", window titles, or a global count.
66
+ function _chromeCommandLines() {
67
+ const root = process.env.SystemRoot || process.env.WINDIR || 'C:\\Windows';
68
+ const nodePath = require('path');
69
+ const { execFileSync } = require('child_process');
70
+ const psExe = nodePath.join(root, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');
71
+ const script =
72
+ "$ErrorActionPreference='SilentlyContinue'; " +
73
+ "$procs = Get-CimInstance Win32_Process -Filter \"Name='chrome.exe'\"; " +
74
+ "$lines = @(); foreach ($p in $procs) { if ($p.CommandLine) { $lines += [string]$p.CommandLine } }; " +
75
+ "Write-Output (ConvertTo-Json -Compress @{ lines = @($lines) })";
76
+ const out = execFileSync(psExe, ['-NoProfile', '-NonInteractive', '-Command', script], {
77
+ windowsHide: true,
78
+ encoding: 'utf8',
79
+ timeout: 8000,
80
+ }).trim();
81
+ const parsed = JSON.parse(out);
82
+ const lines = parsed && parsed.lines != null ? parsed.lines : [];
83
+ return Array.isArray(lines) ? lines : [lines];
84
+ }
85
+
86
+ // Test-only injectable Chrome-command-line provider (mirrors the atomicWrite
87
+ // directory-fsync hook). Tests inject synthetic command lines so exact-profile
88
+ // matching is provable without spawning real processes.
89
+ let _chromeLinesProvider = _chromeCommandLines;
90
+ function _setChromeLinesProvider(fn) { _chromeLinesProvider = typeof fn === 'function' ? fn : _chromeCommandLines; }
91
+
92
+ // Test-only injectable window-probe provider: tests inject synthetic probe
93
+ // output lines so the multi-process selection + visibility verdict are provable
94
+ // without spawning a real Windows session.
95
+ let _windowProbeProvider = null;
96
+ function _setWindowProbeProvider(fn) { _windowProbeProvider = typeof fn === 'function' ? fn : null; }
97
+
98
+ /**
99
+ * Return 'running' | 'stopped' | 'unknown' for whether a Chrome process still
100
+ * owns the EXACT profile directory. Fails closed to 'unknown' on any error.
101
+ */
102
+ function _detectProfileChromeRunning(profileDir) {
103
+ if (!profileDir) return 'unknown';
104
+ if (os.platform() !== 'win32') return 'unknown'; // no exact-profile inspection here
105
+ const nodePath = require('path');
106
+ try {
107
+ const target = nodePath.resolve(profileDir).replace(/[\\/]+$/, '').toLowerCase();
108
+ const lines = _chromeLinesProvider();
109
+ for (const line of lines) {
110
+ const m = /--user-data-dir=(?:"([^"]+)"|(\S+))/.exec(String(line));
111
+ if (!m) continue;
112
+ const got = (m[1] || m[2] || '').replace(/[\\/]+$/, '').toLowerCase();
113
+ if (got && nodePath.resolve(got) === target) return 'running';
114
+ }
115
+ return 'stopped';
116
+ } catch {
117
+ return 'unknown';
118
+ }
119
+ }
120
+
121
+ // ── Windows window-visibility helper ─────────────────────────────────────────
32
122
  //
33
123
  // page.bringToFront() may be insufficient on real Windows to actually bring
34
124
  // 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.
125
+ // This helper uses a narrow, safe PowerShell command to locate the EXACT
126
+ // Chrome window associated with this session's persistent profile directory,
127
+ // un-minimize it, attempt to activate it, and REPORT what it actually observed.
128
+ //
129
+ // Two defects are fixed here (both produced a FALSE `visible: false`):
37
130
  //
38
- // Safety requirements:
131
+ // (a) FIRST-MATCH PROCESS SELECTION. The previous script stopped at the
132
+ // FIRST chrome.exe whose command line contained the profile dir
133
+ // (`$target = $p; break`). Chromium is a multi-process tree — one root
134
+ // browser process plus renderer / gpu-process / utility / crashpad-handler
135
+ // children — and EVERY child carries the same `--user-data-dir`.
136
+ // Verified on the real Windows host: 10 processes matched the profile and
137
+ // 9 of them reported `MainWindowHandle = 0`; ONLY the root browser process
138
+ // owns a window. Whether the old code succeeded was therefore decided by
139
+ // CIM enumeration order rather than by window truth.
140
+ //
141
+ // (b) SetForegroundWindow AS THE VISIBILITY VERDICT. The old code derived
142
+ // `visible` from SetForegroundWindow()'s BOOL return value. That API is
143
+ // subject to the Windows foreground lock: it returns FALSE whenever the
144
+ // current foreground process refuses to yield, even though the Chrome
145
+ // window is genuinely present, un-minimized and on screen. The dashboard's
146
+ // `started === true && visible === true` gate then reported "did not
147
+ // appear visibly" for a browser that WAS visible.
148
+ //
149
+ // The fix separates the two questions:
150
+ // * PRESENCE/VISIBILITY — what `visible` now means: a real, non-minimized
151
+ // top-level window exists for THIS profile. Proven with IsWindowVisible()
152
+ // plus a sane window rect. A refused foreground switch no longer makes a
153
+ // genuinely visible browser report as invisible.
154
+ // * FOCUS — still best effort and still attempted (un-minimize via
155
+ // ShowWindowAsync SW_RESTORE, then SetForegroundWindow), but reported
156
+ // separately as `focused` instead of being conflated with visibility.
157
+ //
158
+ // Safety requirements (unchanged):
39
159
  // - uses the fixed System32 PowerShell 5.1 path (no PATH-based resolution)
40
160
  // - uses execFileSync argument arrays (no shell:true, no command interpolation)
41
161
  // - profileDir is passed via STDIN (never in command arguments)
42
- // - targets ONLY the Chrome process whose command line contains the exact
162
+ // - only ever considers Chrome processes whose command line contains the exact
43
163
  // profileDir (not "most recent Chrome" globally)
164
+ // - scans EVERY match but only ever selects a process that actually owns a
165
+ // window; it never guesses or fabricates a handle
44
166
  // - 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
167
+ // - Add-Type is defined BEFORE any user32 call (ordering fix)
47
168
  //
48
169
  // @param {string} profileDir — the persistent profile directory for this session
49
- // @returns {boolean} true if the window was identified and foregrounded
170
+ // @returns {{visible:boolean, focused:boolean, pid:number|null, hwnd:number, reason:string}}
50
171
 
51
- function _windowsForegroundChrome(profileDir) {
52
- if (os.platform() !== 'win32') return true; // non-Windows: no-op success
53
- if (!profileDir) return false;
172
+ function _windowsWindowState(profileDir) {
173
+ // Non-Windows: bringToFront() is sufficient, there is no foreground lock.
174
+ if (os.platform() !== 'win32') {
175
+ return { visible: true, focused: true, pid: null, hwnd: 0, reason: 'non_windows' };
176
+ }
177
+ if (!profileDir) {
178
+ return { visible: false, focused: false, pid: null, hwnd: 0, reason: 'no_profile' };
179
+ }
180
+ if (typeof _windowProbeProvider === 'function') {
181
+ return _parseWindowProbe(_windowProbeProvider(profileDir));
182
+ }
54
183
  try {
55
184
  const nodePath = require('path');
56
185
  const { execFileSync } = require('child_process');
@@ -59,47 +188,174 @@ function _windowsForegroundChrome(profileDir) {
59
188
 
60
189
  // Fixed PowerShell script — NO user data interpolation.
61
190
  // 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' }";
191
+ // Add-Type is defined BEFORE any user32 call.
192
+ //
193
+ // The script OBSERVES and ACTS, but does NOT decide which process is "the
194
+ // browser". It reports EVERY chrome.exe whose command line contains the
195
+ // exact profile path together with what Windows says about that process's
196
+ // window. The selection rule then lives in `_selectWindowOwner` in JS, where
197
+ // it is unit-testable — the previous version decided inside the script with
198
+ // a `break` on the FIRST match, which selected a windowless child whenever
199
+ // CIM happened to enumerate a renderer/gpu/utility process first.
200
+ //
201
+ // Output layout (one line, `|`-delimited, no user data):
202
+ // <status>|<focusedPostAttempt>|<cand>;<cand>;...
203
+ // <cand> = pid:hasWindow:isRoot:hwnd:shown:iconic:w:h
204
+ // Focus is attempted on the process JS would pick (same rule, computed
205
+ // in-script) so the attempt is not wasted on a windowless child.
206
+ const script = [
207
+ "$ErrorActionPreference='SilentlyContinue';",
208
+ 'Add-Type -Namespace Win32 -Name Native -MemberDefinition \'',
209
+ '[DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr hWnd); ',
210
+ '[DllImport("user32.dll")] public static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow); ',
211
+ '[DllImport("user32.dll")] public static extern bool IsIconic(IntPtr hWnd); ',
212
+ '[DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr hWnd); ',
213
+ '[DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow(); ',
214
+ '[DllImport("user32.dll")] public static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect); ',
215
+ '[StructLayout(LayoutKind.Sequential)] public struct RECT { public int Left; public int Top; public int Right; public int Bottom; }',
216
+ '\';',
217
+ '$profileDir = [Console]::In.ReadToEnd().Trim();',
218
+ "if (-not $profileDir) { Write-Output 'no_profile|False|'; exit 0 };",
219
+ "$procs = Get-CimInstance Win32_Process -Filter \"Name='chrome.exe'\";",
220
+ '$matched = @();',
221
+ 'foreach ($p in $procs) {',
222
+ ' if ($p.CommandLine -and ($p.CommandLine -like "*$profileDir*")) { $matched += $p }',
223
+ '};',
224
+ "if ($matched.Count -eq 0) { Write-Output 'no_process|False|'; exit 0 };",
225
+ // Observation pass: describe EVERY candidate, including windowless
226
+ // children (hasWindow=0). Nothing here short-circuits.
227
+ '$rows = @();',
228
+ 'foreach ($p in $matched) {',
229
+ ' $cand = Get-Process -Id $p.ProcessId;',
230
+ ' $isRoot = 0;',
231
+ ' if ($p.CommandLine -and ($p.CommandLine -notmatch "--type=")) { $isRoot = 1 };',
232
+ ' $hnd = [IntPtr]::Zero;',
233
+ ' if ($cand -and $cand.MainWindowHandle) { $hnd = $cand.MainWindowHandle };',
234
+ ' $hasWin = 0; $shown = $false; $iconic = $false; $w = 0; $h = 0;',
235
+ ' if ($hnd -ne [IntPtr]::Zero) {',
236
+ ' $hasWin = 1;',
237
+ ' $shown = [bool][Win32.Native]::IsWindowVisible($hnd);',
238
+ ' $iconic = [bool][Win32.Native]::IsIconic($hnd);',
239
+ ' $r = New-Object Win32.Native+RECT;',
240
+ ' if ([Win32.Native]::GetWindowRect($hnd, [ref]$r)) { $w = $r.Right - $r.Left; $h = $r.Bottom - $r.Top };',
241
+ ' };',
242
+ " $rows += ('{0}:{1}:{2}:{3}:{4}:{5}:{6}:{7}' -f $p.ProcessId, $hasWin, $isRoot, [int64]$hnd, $shown, $iconic, $w, $h)",
243
+ '};',
244
+ // Focus pass: target the root browser process that owns a window, else
245
+ // any window owner. Best effort — the result is reported, never treated
246
+ // as proof of visibility.
247
+ '$pick = $null;',
248
+ 'foreach ($row in $rows) { $f = $row.Split(":"); if ($f[1] -eq "1" -and $f[2] -eq "1") { $pick = $f[3]; break } };',
249
+ 'if (-not $pick) { foreach ($row in $rows) { $f = $row.Split(":"); if ($f[1] -eq "1") { $pick = $f[3]; break } } };',
250
+ '$focused = $false;',
251
+ 'if ($pick -and $pick -ne "0") {',
252
+ ' $h2 = [IntPtr][int64]$pick;',
253
+ ' if ([Win32.Native]::IsIconic($h2)) { [void][Win32.Native]::ShowWindowAsync($h2, 9) };',
254
+ ' [void][Win32.Native]::SetForegroundWindow($h2);',
255
+ ' Start-Sleep -Milliseconds 150;',
256
+ ' $focused = [bool]([Win32.Native]::GetForegroundWindow() -eq $h2)',
257
+ '};',
258
+ "Write-Output ('candidates|' + $focused + '|' + ($rows -join ';'))",
259
+ ].join(' ');
90
260
 
91
261
  const output = execFileSync(psExe, ['-NoProfile', '-NonInteractive', '-Command', script], {
92
262
  windowsHide: true,
93
263
  encoding: 'utf8',
94
- timeout: 5000,
264
+ // The previous 5s budget silently swallowed the real reason for a
265
+ // `visible:false`: Add-Type compiles C#, then Get-CimInstance reads the
266
+ // command line of every chrome.exe (a Chromium tree is 40+ processes).
267
+ // A timeout aborted the probe and the bare `catch` turned it into
268
+ // "not visible". The budget is now generous and a timeout is reported
269
+ // explicitly instead of being indistinguishable from a missing window.
270
+ timeout: 20000,
95
271
  input: profileDir, // profileDir via STDIN — never in command arguments
96
272
  }).trim();
97
273
 
98
- return output === 'OK';
99
- } catch {
100
- // Foreground helper failed — return false so visible is not claimed
101
- return false;
274
+ return _parseWindowProbe(output);
275
+ } catch (err) {
276
+ // The probe failed — fail closed, but never claim a reason we did not prove.
277
+ const reason = err && err.killed ? 'probe_timeout' : 'probe_failed';
278
+ return { visible: false, focused: false, pid: null, hwnd: 0, reason };
279
+ }
280
+ }
281
+
282
+ /**
283
+ * Select WHICH candidate process owns the browser window.
284
+ *
285
+ * A Chromium tree attaches the same `--user-data-dir` to every child process,
286
+ * but only the ROOT browser process owns a top-level window — verified on the
287
+ * real Windows host: of 10 processes matching one profile, 9 reported
288
+ * MainWindowHandle = 0. Selection rule:
289
+ *
290
+ * 1. a ROOT process (no `--type=`) that owns a window — the real browser
291
+ * 2. otherwise any process that owns a window — defensive fallback
292
+ * 3. otherwise nothing — never fabricate a window
293
+ *
294
+ * A windowless child is NEVER selected and never stops the scan.
295
+ *
296
+ * @param {Array<{pid:number,hasWindow:boolean,isRoot:boolean,hwnd:number,shown:boolean,iconic:boolean,w:number,h:number}>} candidates
297
+ * @returns {object|null} the selected candidate, or null when none owns a window
298
+ */
299
+ function _selectWindowOwner(candidates) {
300
+ if (!Array.isArray(candidates) || candidates.length === 0) return null;
301
+ const withWindow = candidates.filter((c) => c && c.hasWindow && c.hwnd);
302
+ if (withWindow.length === 0) return null;
303
+ return withWindow.find((c) => c.isRoot) || withWindow[0];
304
+ }
305
+
306
+ /**
307
+ * Parse the `|`-delimited window-probe output into a structured verdict.
308
+ *
309
+ * The ONE rule that matters: a window that EXISTS and is SHOWN is visible.
310
+ * SetForegroundWindow's refusal (the Windows foreground lock) is a FOCUS
311
+ * outcome and must never be reported as "the browser is not visible".
312
+ *
313
+ * @param {string} output — raw probe line (or injected test fixture)
314
+ * @returns {{visible:boolean, focused:boolean, pid:number|null, hwnd:number, reason:string}}
315
+ */
316
+ function _parseWindowProbe(output) {
317
+ const parts = String(output == null ? '' : output).trim().split('|');
318
+ const status = parts[0];
319
+
320
+ if (status !== 'candidates') {
321
+ // Transport-level outcome: no profile, no matching process, timeout, etc.
322
+ return { visible: false, focused: false, pid: null, hwnd: 0, reason: status || 'probe_failed' };
102
323
  }
324
+
325
+ const focused = parts[1] === 'True';
326
+ const raw = parts[2] || '';
327
+ const candidates = raw
328
+ .split(';')
329
+ .filter(Boolean)
330
+ .map((row) => {
331
+ const f = row.split(':');
332
+ return {
333
+ pid: parseInt(f[0], 10),
334
+ hasWindow: f[1] === '1',
335
+ isRoot: f[2] === '1',
336
+ hwnd: parseInt(f[3], 10) || 0,
337
+ shown: f[4] === 'True',
338
+ iconic: f[5] === 'True',
339
+ w: parseInt(f[6], 10) || 0,
340
+ h: parseInt(f[7], 10) || 0,
341
+ };
342
+ });
343
+
344
+ const owner = _selectWindowOwner(candidates);
345
+ if (!owner) {
346
+ // Processes matched but none owns a window: a real "not visible" finding.
347
+ return { visible: false, focused, pid: null, hwnd: 0, reason: 'no_window' };
348
+ }
349
+
350
+ // A real window: shown, not minimized, with a sane on-screen rect.
351
+ const hasRealWindow = owner.hwnd !== 0 && owner.shown && !owner.iconic && owner.w >= 100 && owner.h >= 100;
352
+ return {
353
+ visible: hasRealWindow,
354
+ focused,
355
+ pid: Number.isFinite(owner.pid) ? owner.pid : null,
356
+ hwnd: owner.hwnd,
357
+ reason: hasRealWindow ? 'window_visible' : 'window_not_visible',
358
+ };
103
359
  }
104
360
 
105
361
  // Active sessions: accountId -> { context, page, profileDir }
@@ -140,6 +396,10 @@ async function closeAllSessions() {
140
396
  if (!session) continue;
141
397
  // Delete BEFORE closing so a concurrent call does not double-close.
142
398
  sessions.delete(accountId);
399
+ // Deliberate close: the context close listener must not send its own
400
+ // 'stopped' frame for an agent-initiated shutdown.
401
+ session.stopping = true;
402
+ _logLifecycle('CLOSE_ALL_SESSIONS', accountId);
143
403
  try {
144
404
  if (session.context) await session.context.close().catch(() => {});
145
405
  } catch {}
@@ -164,6 +424,37 @@ function setupSessionHandler(ws, opts) {
164
424
  currentRuntime.disconnected = false;
165
425
  currentRuntime.sessions = activeSessions;
166
426
 
427
+ // ── Agent → server heartbeat (protocol v2) ────────────────────────────────
428
+ // The server closes the WS with 4002 "Heartbeat timeout" when no inbound
429
+ // frame refreshes lastHeartbeat for 3× HEARTBEAT_SECONDS (20s → 60s). The
430
+ // server never sends its own heartbeat frames, so a v2 agent that only
431
+ // RESPONDS to (never-sent) heartbeats is disconnected after ~60s. This
432
+ // mirrors the v1 agent: send an application-level {type:'heartbeat'} frame
433
+ // every 10s (well within the 60s budget and the server's per-type rate
434
+ // limit) plus a WS protocol ping to keep proxies from idling out.
435
+ let heartbeatTimer = null;
436
+ const HEARTBEAT_INTERVAL_MS = parseInt(process.env.AGENT_HEARTBEAT_INTERVAL_MS || '10000', 10);
437
+
438
+ function _stopAgentHeartbeat() {
439
+ if (heartbeatTimer) { clearInterval(heartbeatTimer); heartbeatTimer = null; }
440
+ }
441
+
442
+ function _startAgentHeartbeat() {
443
+ _stopAgentHeartbeat();
444
+ heartbeatTimer = setInterval(() => {
445
+ if (ws.readyState !== 1 /* OPEN */) return; // server handles reconnect/close
446
+ try {
447
+ ws.send(JSON.stringify({ type: 'heartbeat' }));
448
+ } catch {}
449
+ try { ws.ping(); } catch {}
450
+ }, HEARTBEAT_INTERVAL_MS);
451
+ // Do not let the heartbeat timer keep the process alive on its own.
452
+ if (typeof heartbeatTimer.unref === 'function') heartbeatTimer.unref();
453
+ }
454
+
455
+ _startAgentHeartbeat();
456
+ ws.on('close', _stopAgentHeartbeat);
457
+
167
458
  ws.on('message', (data, isBinary) => {
168
459
  if (isBinary) return;
169
460
 
@@ -237,6 +528,26 @@ function setupSessionHandler(ws, opts) {
237
528
  return;
238
529
  }
239
530
 
531
+ // Reconnect reconciliation: the server asks for the exact-profile liveness
532
+ // verdict for a stale lease this device owns (recovery probe). This lets a
533
+ // restarted agent process resolve its own stale recovery_required lease
534
+ // WITHOUT the lost in-memory token — the reply is nonce-bound and carries
535
+ // only the liveness verdict (never a token).
536
+ if (msg.type === 'recovery-probe') {
537
+ try {
538
+ const verdict = _recoveryVerdict(msg, opts);
539
+ ws.send(JSON.stringify({
540
+ type: 'recovery-probe-response',
541
+ probeId: msg.probeId,
542
+ nonce: msg.nonce,
543
+ accountUuid: msg.accountUuid,
544
+ leaseId: msg.leaseId || null,
545
+ verdict,
546
+ }));
547
+ } catch {}
548
+ return;
549
+ }
550
+
240
551
  // session-status ack: the server confirms a stop was verified. No-op here
241
552
  // beyond acknowledging; the lease stays under server authority.
242
553
  if (msg.type === 'session-status') {
@@ -312,12 +623,12 @@ async function _executeCommand(type, params, msg, opts, ws) {
312
623
 
313
624
  switch (type) {
314
625
  case 'startSession':
315
- return _startSession(params, opts, accountId, accountUuid, lease);
626
+ return _startSession(params, opts, accountId, accountUuid, lease, ws);
316
627
  case 'stopSession':
317
- return _stopSession(accountId, lease);
628
+ return _stopSession(accountId, lease, ws);
318
629
  case 'restartSession':
319
- await _stopSession(accountId, lease);
320
- return _startSession(params, opts, accountId, accountUuid, lease);
630
+ await _stopSession(accountId, lease, ws);
631
+ return _startSession(params, opts, accountId, accountUuid, lease, ws);
321
632
  case 'refreshSession':
322
633
  return _refreshSession(accountId);
323
634
  case 'navigate':
@@ -347,20 +658,109 @@ async function _executeCommand(type, params, msg, opts, ws) {
347
658
 
348
659
  // ── Session management (reuses existing hardened modules) ───────────────────
349
660
 
350
- async function _startSession(params, opts, accountId, accountUuid, lease) {
661
+ async function _startSession(params, opts, accountId, accountUuid, lease, ws) {
351
662
  if (!accountId) return { success: false, error: 'Missing accountId' };
352
663
 
664
+ // Lease-bound error reporter: a FAILED start sends a lease-bound
665
+ // session-status 'error' so the server releases the lease it acquired for
666
+ // this attempt (parity with the hardened v1 runtime). Without it the lease
667
+ // stays 'acquiring' and blocks the account until it expires.
668
+ const _sendStartError = (error) => {
669
+ if (!ws || !lease) return;
670
+ try {
671
+ const tmp = {};
672
+ leaseClient.bind(tmp, lease);
673
+ ws.send(JSON.stringify(leaseClient.boundStatusMessage(tmp, accountId, 'error', { error })));
674
+ } catch {}
675
+ };
676
+
353
677
  const deviceMeta = opts.deviceMeta;
678
+ // Phase 14 / schema-4: the profile identity requires ALL FOUR UUIDs
679
+ // (server/tenant/account/device). The command's options carry the
680
+ // server-assigned serverUuid + tenantUuid; the device UUID comes from this
681
+ // device's metadata. Without all four, resolveProfileDir throws
682
+ // PROFILE_IDENTITY_INCOMPLETE and no browser can ever launch.
683
+ const identity = params.options || params;
684
+ const serverUuid = identity.serverUuid || null;
685
+ const tenantUuid = identity.tenantUuid || null;
686
+ const resolvedAccountUuid = identity.accountUuid || accountUuid || null;
687
+
688
+ // Fail closed with a clear, actionable error if the server did not send the
689
+ // complete immutable tuple (a profile is never opened with a partial
690
+ // identity).
691
+ if (!serverUuid || !tenantUuid || !resolvedAccountUuid || !deviceMeta.deviceId) {
692
+ _sendStartError('PROFILE_IDENTITY_INCOMPLETE');
693
+ return {
694
+ success: false,
695
+ error: 'PROFILE_IDENTITY_INCOMPLETE: the server did not provide the full profile identity (serverUuid/tenantUuid/accountUuid). Cannot open a browser profile.',
696
+ };
697
+ }
698
+
354
699
  const profileDir = resolveProfileDir({
355
- profileRoot: PROFILES_DIR,
700
+ profilesDir: PROFILES_DIR,
701
+ serverUuid,
702
+ tenantUuid,
703
+ accountUuid: resolvedAccountUuid,
356
704
  deviceUuid: deviceMeta.deviceId,
357
- accountUuid: accountUuid || accountId,
358
- });
705
+ }).dir;
359
706
 
360
707
  const fs = require('fs');
361
708
  if (!fs.existsSync(profileDir)) fs.mkdirSync(profileDir, { recursive: true });
362
709
 
363
- const fingerprint = fingerprintStore.loadOrGenerate(profileDir, () => generateFingerprint());
710
+ // fingerprintStore.loadOrGenerate takes an OBJECT ({ profileDir, accountId,
711
+ // options, generator }) — matching the hardened v1 runtime call. The
712
+ // positional form threw "paths[0] must be of type string" and aborted every
713
+ // launch. Live operator options (mobileView/locale/userAgent/timezone) are
714
+ // re-applied on every launch; the randomized hardware identity is persisted
715
+ // inside the profile dir and stays stable across launches.
716
+ const launchOpts = params.options || {};
717
+ const fingerprint = fingerprintStore.loadOrGenerate({
718
+ profileDir,
719
+ accountId: String(accountId),
720
+ options: {
721
+ mobileView: launchOpts.mobileView || false,
722
+ locale: launchOpts.locale || null,
723
+ userAgent: launchOpts.userAgent || null,
724
+ timezone: launchOpts.timezone || null,
725
+ },
726
+ generator: generateFingerprint,
727
+ });
728
+
729
+ // ── Phase 16 fail-closed proxy policy (parity with the hardened v1 runtime) ──
730
+ // A missing/unknown networkMode ABORTS; no proxy + proxy_required ABORTS
731
+ // (never silently open a direct browser that leaks the real IP); a configured
732
+ // proxy must be reachable AND egress from a different IP (isolation), or the
733
+ // launch aborts. We never fall open to direct.
734
+ const proxyStr = launchOpts.proxy || null;
735
+ const networkMode = launchOpts.networkMode || null;
736
+
737
+ // Health-check the proxy only when one was configured. verifyProxyIsolation
738
+ // does the full fail-closed verification (CONNECT + TLS + GET through the
739
+ // proxy, plus an independent direct public-IP fetch and comparison) — a
740
+ // superset of the v1 TCP pre-check. A proxy that accepts TCP but egresses
741
+ // from the device's own IP (transparent/misconfigured) is refused.
742
+ let health = null;
743
+ if (proxyStr) {
744
+ const parsedProxy = _parseProxy(proxyStr);
745
+ if (!parsedProxy) {
746
+ health = { ok: false, reason: 'proxy_unreachable', code: 'PROXY_MALFORMED' };
747
+ } else {
748
+ const isolation = await require('./proxyEgress').verifyProxyIsolation(parsedProxy, {}).catch(() => ({ ok: false, code: 'PROXY_ISOLATION_ERROR' }));
749
+ health = isolation && isolation.ok
750
+ ? { ok: true, reason: 'proxy_ok', egressIp: isolation.egressIp, directIp: isolation.directIp }
751
+ : { ok: false, reason: 'proxy_isolation_failed: ' + ((isolation && (isolation.code || isolation.reason)) || 'unknown'), code: isolation && isolation.code };
752
+ }
753
+ }
754
+
755
+ const decision = require('./proxyPolicy').decideProxyLaunch({
756
+ proxyStr,
757
+ networkMode,
758
+ health,
759
+ });
760
+ if (decision.action === 'abort') {
761
+ _sendStartError(decision.error);
762
+ return { success: false, error: decision.error, code: decision.reason.toUpperCase() };
763
+ }
364
764
 
365
765
  const args = [
366
766
  '--disable-blink-features=AutomationControlled',
@@ -384,8 +784,8 @@ async function _startSession(params, opts, accountId, accountUuid, lease) {
384
784
  noDefaultViewport: true,
385
785
  };
386
786
 
387
- if (params.proxy) {
388
- const proxyUrl = _parseProxy(params.proxy);
787
+ if (decision.useProxy && proxyStr) {
788
+ const proxyUrl = _parseProxy(proxyStr);
389
789
  if (proxyUrl) launchOptions.proxy = proxyUrl;
390
790
  }
391
791
 
@@ -393,14 +793,20 @@ async function _startSession(params, opts, accountId, accountUuid, lease) {
393
793
  try {
394
794
  context = await chromium.launchPersistentContext(profileDir, launchOptions);
395
795
  } catch (err) {
796
+ _sendStartError(_safeError(err));
396
797
  return { success: false, error: _safeError(err) };
397
798
  }
398
799
 
399
800
  await context.addInitScript(buildStealthScript(fingerprint));
400
801
 
401
- if (params.cookies && Array.isArray(params.cookies)) {
402
- try { await context.addCookies(params.cookies); } catch {}
403
- }
802
+ // The server sends cookies in options (options.cookies); accept the flat
803
+ // params form too for robustness. The value is normally the JSON TEXT of a
804
+ // cookie array, so it MUST be normalized before injection — the previous
805
+ // `Array.isArray()` guard silently dropped every string payload and left the
806
+ // browser unauthenticated. Injection happens BEFORE the first navigation so
807
+ // the initial request already carries the account session.
808
+ const cookiesToInject = launchOpts.cookies || params.cookies;
809
+ const cookieDiag = await _injectCookies(context, cookiesToInject);
404
810
 
405
811
  const pages = context.pages();
406
812
  const page = pages[0] || await context.newPage();
@@ -432,14 +838,15 @@ async function _startSession(params, opts, accountId, accountUuid, lease) {
432
838
  };
433
839
  }
434
840
 
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;
841
+ // Windows-specific window verification: page.bringToFront() alone may not
842
+ // overcome the Windows foreground lock. The probe targets the EXACT Chrome
843
+ // process whose command line contains this session's profileDir (passed via
844
+ // stdin, not interpolated). It reports VISIBILITY (a real, non-minimized
845
+ // window exists for this profile) separately from FOCUS (the foreground
846
+ // switch was allowed). See _windowsWindowState for the two defects fixed.
847
+ let windowState = { visible: bringToFrontOk, focused: bringToFrontOk, pid: null, hwnd: 0, reason: 'not_probed' };
441
848
  if (bringToFrontOk) {
442
- foregroundVerified = _windowsForegroundChrome(profileDir);
849
+ windowState = _windowsWindowState(profileDir);
443
850
  }
444
851
 
445
852
  // Re-check after focus: the page may have closed in the meantime.
@@ -451,9 +858,60 @@ async function _startSession(params, opts, accountId, accountUuid, lease) {
451
858
  };
452
859
  }
453
860
 
454
- const session = { context, page, profileDir, accountId, lease: null };
861
+ const session = { context, page, profileDir, accountId, lease: null, stopping: false };
455
862
  if (lease) leaseClient.bind(session, lease);
456
863
  activeSessions.set(accountId, session);
864
+ _logLifecycle('START_SESSION', accountId, { visible: windowState.visible, focused: windowState.focused, reason: windowState.reason });
865
+
866
+ // ── Lease-bound session-status reporting (Phase 3 parity with v1) ──────────
867
+ // The server's session cache (`agent.sessions`) and the durable lease TTL
868
+ // are ONLY updated by lease-bound `session-status` frames — never by the
869
+ // command-response alone. Without this frame the server reports the session
870
+ // 'stopped' even though the local browser is running, and the lease never
871
+ // activates. The credential (leaseId + leaseToken) is echoed so the server
872
+ // can verify the holder; it is never logged, never persisted to disk.
873
+ const _sendStatus = (status, extra) => {
874
+ try { ws.send(JSON.stringify(leaseClient.boundStatusMessage(session, accountId, status, extra))); } catch {}
875
+ };
876
+ _sendStatus('running');
877
+
878
+ // A browser context closed outside our control (user closed the window,
879
+ // crash): report the verified stop so the server releases the lease — a
880
+ // dead local browser must not keep the account locked.
881
+ //
882
+ // 'stopping' is set by _stopSession / closeAllSessions so a deliberate close
883
+ // does NOT send a second 'stopped' frame: the command path already acks it,
884
+ // and two identical lease-bound stops for one stop were a duplicate.
885
+ context.on('close', () => {
886
+ const closed = activeSessions.get(accountId);
887
+ if (session.stopping) {
888
+ _logLifecycle('CONTEXT_CLOSE', accountId, { duplicate: true, reason: 'command_initiated' });
889
+ return;
890
+ }
891
+ if (closed !== session) {
892
+ // The session was already replaced/removed — never report a stop for a
893
+ // session that is no longer the active one.
894
+ _logLifecycle('CONTEXT_CLOSE_DUP', accountId);
895
+ return;
896
+ }
897
+ _logLifecycle('CONTEXT_CLOSE', accountId);
898
+ activeSessions.delete(accountId);
899
+ try { ws.send(JSON.stringify(leaseClient.boundStatusMessage(closed || session, accountId, 'stopped'))); } catch {}
900
+ });
901
+
902
+ // Page-level causes: a closed/crashed page is the leading hypothesis for a
903
+ // browser that appears to quit on its own (closing the LAST page ends a
904
+ // persistent context). Recorded so the next occurrence is identifiable.
905
+ try {
906
+ page.on('close', () => _logLifecycle('PAGE_CLOSE', accountId, { pagesLeft: context.pages().length }));
907
+ page.on('crash', () => _logLifecycle('PAGE_CRASH', accountId));
908
+ } catch {}
909
+ try {
910
+ const browser = typeof context.browser === 'function' ? context.browser() : null;
911
+ if (browser && typeof browser.on === 'function') {
912
+ browser.on('disconnected', () => _logLifecycle('BROWSER_DISCONNECTED', accountId));
913
+ }
914
+ } catch {}
457
915
 
458
916
  // Return confirmed success metadata. The backend/frontend uses this to
459
917
  // show a green toast ONLY when the browser is genuinely started and visible.
@@ -462,41 +920,88 @@ async function _startSession(params, opts, accountId, accountUuid, lease) {
462
920
  // - launchPersistentContext succeeded
463
921
  // - page exists and is not closed
464
922
  // - page.bringToFront() succeeded
465
- // - on Windows: the intended Chrome process was identified and
466
- // SetForegroundWindow succeeded (or on non-Windows: bringToFront is
467
- // sufficient)
923
+ // - on Windows: a real, non-minimized top-level Chrome window was found for
924
+ // THIS exact profile (IsWindowVisible + sane window rect). A refused
925
+ // SetForegroundWindow is a FOCUS outcome and does NOT mean invisible —
926
+ // reporting it as visible:false was the false negative fixed here.
927
+ // (on non-Windows: bringToFront is sufficient)
468
928
  //
469
- // If the Windows foreground helper cannot prove the window is visible
470
- // (foregroundVerified = false), we return started:true but visible:false
929
+ // If no real window can be proven, we return started:true but visible:false
471
930
  // 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.
931
+ if (os.platform() === 'win32' && !windowState.visible) {
932
+ // The browser launched and bringToFront succeeded, but we could not find a
933
+ // real on-screen window for this profile. Return a safe actionable message
934
+ // — NOT a green toast. `reason` says which evidence was missing.
476
935
  return {
477
936
  success: true,
478
937
  accountId,
479
938
  started: true,
480
939
  visible: false,
481
940
  sessionId: accountId,
482
- error: 'Browser launched but could not be confirmed in the foreground. Check the taskbar for the Chrome window.',
941
+ reason: windowState.reason,
942
+ error: 'Browser launched but no visible window could be confirmed. Check the taskbar for the Chrome window.',
943
+ cookieDiagnostics: cookieDiag,
483
944
  };
484
945
  }
485
946
 
947
+ // The window is proven present. `focused` is reported for diagnostics only —
948
+ // a window that exists on screen is visible whether or not it holds focus.
486
949
  return {
487
950
  success: true,
488
951
  accountId,
489
952
  started: true,
490
953
  visible: true,
491
954
  sessionId: accountId,
955
+ cookieDiagnostics: cookieDiag,
492
956
  };
493
957
  }
494
958
 
495
- async function _stopSession(accountId, lease) {
959
+ async function _stopSession(accountId, lease, ws) {
496
960
  const session = activeSessions.get(accountId);
497
961
  if (!session) return { success: false, error: 'Session not found' };
498
- try { await session.context.close(); } catch {}
499
- activeSessions.delete(accountId);
962
+ // Mark BEFORE closing: context.close() fires the session's `close` listener,
963
+ // which would otherwise send its own 'stopped' frame and produce TWO
964
+ // identical lease-bound stops for one stop command (a duplicate ack the
965
+ // server had to absorb). The explicit ack below is now the single one.
966
+ session.stopping = true;
967
+ _logLifecycle('STOP_COMMAND', accountId);
968
+
969
+ // ── FAIL-CLOSED stop ───────────────────────────────────────────────────────
970
+ // A lease-bound `status: 'stopped'` means, and must ONLY ever mean, that the
971
+ // local browser context close was POSITIVELY CONFIRMED. The previous shape
972
+ // swallowed a close failure (`catch {}`) and then sent `stopped` anyway, so a
973
+ // failed close could make the backend release the durable lease while the
974
+ // browser was still alive — fail-OPEN, and the account could then be acquired
975
+ // by another device while two live browsers existed for it.
976
+ //
977
+ // Now: if the close cannot be confirmed we send NO stopped frame, keep the
978
+ // session registered, and report an explicit failure. The lease stays
979
+ // blocking/recoverable (a human/operator or recovery path resolves it), which
980
+ // is strictly safer than claiming a stop we did not observe.
981
+ try {
982
+ await session.context.close();
983
+ } catch {
984
+ // Close was NOT confirmed. Revert the deliberate-close marking so a later
985
+ // real context close (user closes the window, crash, browser disconnect) is
986
+ // reported normally by the context close listener instead of being
987
+ // suppressed as a duplicate.
988
+ session.stopping = false;
989
+ // NEVER delete an entry here. If this session is still the registered one it
990
+ // must stay (it may still be live — never erase evidence). If the map has
991
+ // been REPLACED by a newer session for this account, that replacement must
992
+ // not be evicted either. A failed close therefore touches no map state.
993
+ _logLifecycle('STOP_CLOSE_FAILED', accountId);
994
+ // Safe, generic failure: no credentials, no token, no raw driver text.
995
+ return { success: false, accountId, error: 'Browser close could not be confirmed' };
996
+ }
997
+
998
+ // Only after a confirmed close.
999
+ if (activeSessions.get(accountId) === session) activeSessions.delete(accountId);
1000
+ // Lease-bound stop ack: the server verifies the credential and releases the
1001
+ // durable lease. This is the only thing that completes a takeover.
1002
+ if (ws) {
1003
+ try { ws.send(JSON.stringify(leaseClient.boundStatusMessage(session, accountId, 'stopped'))); } catch {}
1004
+ }
500
1005
  return { success: true, accountId, stopped: true };
501
1006
  }
502
1007
 
@@ -573,8 +1078,230 @@ function _discoverLegacyProfiles() {
573
1078
  return { success: true, profiles };
574
1079
  }
575
1080
 
1081
+ // ── Account cookie restoration ───────────────────────────────────────────────
1082
+ //
1083
+ // The backend stores an account's cookies as the JSON TEXT of a Playwright
1084
+ // cookie array (accounts.db.json `cookies`) and forwards that value verbatim in
1085
+ // the startSession command options — so it arrives here as a STRING.
1086
+ //
1087
+ // The original hardened runtime (index.js) parsed BOTH shapes: a JSON string
1088
+ // (with a base64-wrapped fallback) and an already-parsed array. This runtime
1089
+ // only accepted an array (`Array.isArray`) and swallowed everything else in a
1090
+ // bare `catch {}`, so every string payload was dropped silently: the browser
1091
+ // opened with no account session at all (X saw an anonymous visitor even though
1092
+ // auth_token/ct0/twid were present in the account record). Restoring the
1093
+ // hardened runtime's normalization makes both runtimes accept the same
1094
+ // payloads.
1095
+ //
1096
+ // Payloads are normalized EXACTLY as stored — domain, sameSite and every other
1097
+ // stored field are never rewritten; only fields Playwright requires are filled
1098
+ // in when absent. Injection happens BEFORE the first navigation so the very
1099
+ // first request is already authenticated.
1100
+
1101
+ /**
1102
+ * Canonicalize a sameSite value. Returns 'Strict' | 'Lax' | 'None' when the
1103
+ * value is recognized (case-insensitively), otherwise null so the caller can
1104
+ * OMIT it. Returning 'None' for an unknown value would silently relax the
1105
+ * cookie's cross-site posture AND is rejected by Playwright, whose `sameSite`
1106
+ * is an optional enum of exactly those three values.
1107
+ */
1108
+ function _canonSameSite(value) {
1109
+ if (value == null) return null;
1110
+ switch (String(value).trim().toLowerCase()) {
1111
+ case 'strict': return 'Strict';
1112
+ case 'lax': return 'Lax';
1113
+ case 'none': return 'None';
1114
+ default: return null;
1115
+ }
1116
+ }
1117
+
1118
+ // Playwright: only -1 or a positive unix timestamp up to this bound is allowed.
1119
+ const MAX_COOKIE_EXPIRES_SECONDS = 253402300799;
1120
+
1121
+ /** Playwright's expires constraint: -1, or a positive value within its bound. */
1122
+ function _validExpires(value) {
1123
+ if (value == null || value === '') return null;
1124
+ const n = Number(value);
1125
+ if (!Number.isFinite(n)) return null;
1126
+ if (n === -1) return -1;
1127
+ if (n <= 0 || n > MAX_COOKIE_EXPIRES_SECONDS) return null;
1128
+ return n;
1129
+ }
1130
+
1131
+ /** A `url` scope Playwright will accept (not about:blank, not a data: URL). */
1132
+ function _usableUrl(value) {
1133
+ if (typeof value !== 'string' || !value) return null;
1134
+ if (value === 'about:blank' || value.startsWith('data:')) return null;
1135
+ try {
1136
+ const u = new URL(value);
1137
+ if (u.protocol !== 'http:' && u.protocol !== 'https:') return null;
1138
+ return value;
1139
+ } catch {
1140
+ return null;
1141
+ }
1142
+ }
1143
+
1144
+ /**
1145
+ * Normalize any supported cookie payload into a Playwright cookie array.
1146
+ * Supported (pre-existing) formats: a JS array, or a string containing a JSON
1147
+ * array either directly or base64-wrapped. Returns { cookies, source }.
1148
+ */
1149
+ function _normalizeCookiePayload(cookiesData) {
1150
+ let raw = null;
1151
+ let source = null;
1152
+
1153
+ if (Array.isArray(cookiesData)) {
1154
+ raw = cookiesData;
1155
+ source = 'array';
1156
+ } else if (typeof cookiesData === 'string') {
1157
+ const text = cookiesData.trim();
1158
+ if (!text) return { cookies: [], source: 'empty_string' };
1159
+ try {
1160
+ raw = JSON.parse(text);
1161
+ source = 'json_string';
1162
+ } catch {
1163
+ try {
1164
+ raw = JSON.parse(Buffer.from(text, 'base64').toString());
1165
+ source = 'base64_json';
1166
+ } catch { raw = null; }
1167
+ }
1168
+ } else if (cookiesData && typeof cookiesData === 'object') {
1169
+ // A wrapper object is NOT itself a cookie. Only an explicit `cookies`
1170
+ // array is accepted, so arbitrary objects can never become cookies.
1171
+ if (Array.isArray(cookiesData.cookies)) {
1172
+ raw = cookiesData.cookies;
1173
+ source = 'object.cookies';
1174
+ }
1175
+ }
1176
+
1177
+ if (!Array.isArray(raw)) return { cookies: [], source: source || 'unsupported' };
1178
+
1179
+ const cookies = [];
1180
+ let unrecognizedSameSite = 0;
1181
+ for (const c of raw) {
1182
+ if (!c || typeof c !== 'object') continue;
1183
+ if (typeof c.name !== 'string' || !c.name) continue;
1184
+ if (c.value == null) continue;
1185
+ const out = { name: c.name, value: String(c.value) };
1186
+
1187
+ // ── Scope: Playwright requires url XOR (domain + path) ──
1188
+ // The explicit domain/path pair wins when a record carries both (a shape
1189
+ // Playwright rejects outright).
1190
+ const hasDomain = typeof c.domain === 'string' && c.domain;
1191
+ if (hasDomain) {
1192
+ out.domain = c.domain;
1193
+ // The ONLY field this normalizer defaults, because Playwright mandates a
1194
+ // path whenever a domain is used.
1195
+ out.path = (typeof c.path === 'string' && c.path) ? c.path : '/';
1196
+ } else {
1197
+ const url = _usableUrl(c.url);
1198
+ if (!url) continue;
1199
+ out.url = url;
1200
+ }
1201
+
1202
+ // ── Optional fields: included ONLY when the stored record supplied them ──
1203
+ // Inventing secure/sameSite/httpOnly/expires would silently change how the
1204
+ // browser treats the cookie.
1205
+ const expires = _validExpires(c.expires);
1206
+ if (expires !== null) out.expires = expires;
1207
+ if (typeof c.httpOnly === 'boolean') out.httpOnly = c.httpOnly;
1208
+ if (typeof c.secure === 'boolean') out.secure = c.secure;
1209
+ if (c.sameSite != null) {
1210
+ const raw = String(c.sameSite).trim();
1211
+ if (raw) {
1212
+ const sameSite = _canonSameSite(raw);
1213
+ if (sameSite) out.sameSite = sameSite;
1214
+ else unrecognizedSameSite += 1; // omitted, never reinterpreted
1215
+ }
1216
+ }
1217
+
1218
+ cookies.push(out);
1219
+ }
1220
+ return { cookies, source: source || 'array', unrecognizedSameSite };
1221
+ }
1222
+
1223
+ /**
1224
+ * Restore account cookies into the persistent context. Never throws (a cookie
1225
+ * problem must not abort a launch), and NEVER fails silently: counts and any
1226
+ * error are returned for diagnostics and logged. Cookie VALUES are never
1227
+ * logged — only names/counts.
1228
+ */
1229
+ async function _injectCookies(context, cookiesData) {
1230
+ const diag = {
1231
+ cookiesProvided: false,
1232
+ cookieSource: null,
1233
+ cookiesParsed: 0,
1234
+ cookiesInjected: 0,
1235
+ cookieError: null,
1236
+ };
1237
+ if (cookiesData == null || cookiesData === '') return diag;
1238
+ diag.cookiesProvided = true;
1239
+
1240
+ const { cookies, source } = _normalizeCookiePayload(cookiesData);
1241
+ diag.cookieSource = source;
1242
+ diag.cookiesParsed = cookies.length;
1243
+
1244
+ if (cookies.length === 0) {
1245
+ console.log(`[session] No cookies to inject (source=${source})`);
1246
+ return diag;
1247
+ }
1248
+
1249
+ const names = cookies.map((c) => c.name);
1250
+ const authCookiePresent = names.includes('auth_token');
1251
+ const csrfCookiePresent = names.includes('ct0');
1252
+
1253
+ try {
1254
+ await context.addCookies(cookies);
1255
+ diag.cookiesInjected = cookies.length;
1256
+ console.log(`[session] Injected ${cookies.length} cookies (source=${source}) authCookiePresent=${authCookiePresent} csrfCookiePresent=${csrfCookiePresent}`);
1257
+ return diag;
1258
+ } catch (err) {
1259
+ diag.cookieError = _safeError(err);
1260
+ console.error(`[session] Cookie injection failed for ${cookies.length} cookies: ${diag.cookieError}`);
1261
+ // One malformed entry must not discard the whole set: retry individually
1262
+ // and keep every cookie Playwright does accept.
1263
+ for (const c of cookies) {
1264
+ try {
1265
+ await context.addCookies([c]);
1266
+ diag.cookiesInjected += 1;
1267
+ } catch { /* this single entry is unusable — the rest are kept */ }
1268
+ }
1269
+ console.log(`[session] Injected ${diag.cookiesInjected}/${cookies.length} cookies after per-cookie retry (authCookiePresent=${authCookiePresent})`);
1270
+ return diag;
1271
+ }
1272
+ }
1273
+
576
1274
  // ── Helpers ──────────────────────────────────────────────────────────────────
577
1275
 
1276
+ /**
1277
+ * Compute the exact-profile liveness verdict for a recovery probe. Resolves the
1278
+ * EXACT profile dir from the server-supplied immutable identity tuple (using the
1279
+ * same hardened profile-path logic as launch) and matches it against live Chrome
1280
+ * command lines. Returns 'running' | 'stopped' | 'unknown' (fail closed to
1281
+ * 'unknown' whenever the profile cannot be resolved or inspected).
1282
+ */
1283
+ function _recoveryVerdict(msg, opts) {
1284
+ const deviceMeta = (opts && opts.deviceMeta) || {};
1285
+ const accountUuid = msg.accountUuid || null;
1286
+ const serverUuid = msg.serverUuid || null;
1287
+ const tenantUuid = msg.tenantUuid || null;
1288
+ const deviceUuid = msg.deviceUuid || deviceMeta.deviceId || null;
1289
+ if (!accountUuid || !serverUuid || !tenantUuid || !deviceUuid) return 'unknown';
1290
+ let dir;
1291
+ try {
1292
+ dir = resolveProfileDir({
1293
+ profilesDir: PROFILES_DIR,
1294
+ serverUuid,
1295
+ tenantUuid,
1296
+ accountUuid,
1297
+ deviceUuid,
1298
+ }).dir;
1299
+ } catch {
1300
+ return 'unknown';
1301
+ }
1302
+ return _detectProfileChromeRunning(dir);
1303
+ }
1304
+
578
1305
  function _extractEcho(msg) {
579
1306
  const echo = {};
580
1307
  if (msg.nonce) echo.nonce = msg.nonce;
@@ -616,4 +1343,4 @@ function _safeError(err) {
616
1343
  .slice(0, 500);
617
1344
  }
618
1345
 
619
- module.exports = { setupSessionHandler, activeSessions, closeAllSessions, markDisconnected };
1346
+ module.exports = { setupSessionHandler, activeSessions, closeAllSessions, markDisconnected, _detectProfileChromeRunning, _recoveryVerdict, _setChromeLinesProvider, _setWindowProbeProvider, _windowsWindowState, _parseWindowProbe, _selectWindowOwner, _logLifecycle };