@xkwdstore/agent 2.1.3 → 2.1.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.
@@ -44,6 +44,10 @@ const {
44
44
  buildSessionPreferences,
45
45
  } = require('./browserIsolation');
46
46
  const sessionRegistry = require('./sessionRegistry');
47
+ const sessionAuth = require('./sessionAuth');
48
+ const connectivity = require('./browserConnectivity');
49
+ const browserLaunch = require('./browserLaunch');
50
+ const { applyCookies } = require('./cookieInjection');
47
51
 
48
52
  // ── Exact-profile Chrome detection (recovery probe) ──────────────────────────
49
53
  //
@@ -348,7 +352,7 @@ function setupSessionHandler(ws, opts) {
348
352
  accountUuid: session.accountUuid || null,
349
353
  leaseId: (lease && lease.leaseId) || null,
350
354
  leaseToken: (lease && lease.leaseToken) || null,
351
- status: session.context ? 'running' : 'stopped',
355
+ status: (session.context || session.viaWorker) ? 'running' : 'stopped',
352
356
  });
353
357
  }
354
358
  ws.send(JSON.stringify({ type: 'sessions-report', sessions }));
@@ -433,7 +437,7 @@ async function _handleCommandEnvelope(ws, msg, opts) {
433
437
  const ALLOWED_TYPES = new Set([
434
438
  'startSession', 'stopSession', 'restartSession', 'refreshSession',
435
439
  'navigate', 'type', 'paste', 'press', 'click', 'runAction',
436
- 'getStatus', 'importLegacyProfile', 'discoverLegacyProfiles',
440
+ 'getStatus', 'checkAuth', 'importLegacyProfile', 'discoverLegacyProfiles',
437
441
  'focus', 'proxy-test',
438
442
  ]);
439
443
 
@@ -470,37 +474,46 @@ async function _executeCommand(type, params, msg, opts, ws) {
470
474
  return _startSession(params, opts, accountId, accountUuid, lease, ws);
471
475
  case 'stopSession':
472
476
  return _stopSession(accountId, lease, ws, opts);
473
- case 'restartSession':
474
- await _stopSession(accountId, lease, ws, opts);
477
+ case 'restartSession': {
478
+ // Restart uses the SAME inbound lease. Suppress the lease-bound `stopped`
479
+ // frame during the internal stop; otherwise the server releases the lease
480
+ // and the subsequent start can never bind to it.
481
+ const stopped = await _stopSession(accountId, lease, ws, opts, { suppressStopReport: true });
482
+ if (!stopped || stopped.success === false) return stopped;
475
483
  return _startSession(params, opts, accountId, accountUuid, lease, ws);
484
+ }
476
485
  case 'refreshSession':
477
- return _refreshSession(accountId);
486
+ return _refreshSession(accountId, opts);
487
+ case 'checkAuth':
488
+ return _checkAuth(accountId, opts);
478
489
  case 'navigate':
479
- return _navigate(accountId, params.url);
490
+ return _navigate(accountId, params.url, opts);
480
491
  case 'type':
481
- return _typeText(accountId, params.selector, params.text);
492
+ return _typeText(accountId, params.selector, params.text, opts);
482
493
  case 'paste':
483
- return _typeText(accountId, params.selector, params.text);
494
+ return _typeText(accountId, params.selector, params.text, opts);
484
495
  case 'press':
485
- return _pressKey(accountId, params.key);
496
+ return _pressKey(accountId, params.key, opts);
486
497
  case 'click':
487
- return _click(accountId, params.selector);
498
+ return _click(accountId, params.selector, opts);
488
499
  case 'focus':
489
- return _focusSession(accountId);
500
+ return _focusSession(accountId, opts);
490
501
  case 'runAction':
491
- return _runAction(accountId, params.action, params.payload || params.args);
502
+ return _runAction(accountId, params.action, params.payload || params.args, opts);
492
503
  case 'getStatus':
493
504
  // Account-scoped status contract (parity with the hardened index.js path).
494
505
  // Job readiness on the server uses getSessionStatus (registry), but any
495
506
  // caller of the getStatus command must receive a truthful per-account
496
- // { status:'running'|'stopped' } — never a bare sessions list.
497
- return _getStatus(accountId);
507
+ // { status, browserReady, authState } — never a bare sessions list.
508
+ return _getStatus(accountId, opts);
498
509
  case 'importLegacyProfile':
499
510
  return _importLegacyProfile(accountId, accountUuid, opts);
500
511
  case 'discoverLegacyProfiles':
501
512
  return _discoverLegacyProfiles();
502
513
  case 'proxy-test':
503
514
  return _proxyTest(params);
515
+ case 'connectivity-test':
516
+ return _connectivityTest(params);
504
517
  default:
505
518
  return { success: false, error: 'Unknown command type' };
506
519
  }
@@ -618,6 +631,13 @@ async function _startSessionLocked(params, opts, accountKey, accountId, accountU
618
631
  tenantUuid,
619
632
  accountUuid: resolvedAccountUuid,
620
633
  deviceUuid: deviceMeta.deviceId,
634
+ // Legacy layout migration inputs. index.js has always supplied these; the
635
+ // direct protocol handler omitted them, so a supported schema-2 profile
636
+ // could never be found from the v2 route. They are used only for legacy
637
+ // discovery/migration; the schema-4 identity remains authoritative.
638
+ serverUrl: opts.serverOrigin || null,
639
+ userId: launchParams.userId != null ? launchParams.userId : null,
640
+ accountId,
621
641
  }).dir;
622
642
  } catch (err) {
623
643
  const isIdentity = err && err.code === 'PROFILE_IDENTITY_INCOMPLETE';
@@ -631,11 +651,23 @@ async function _startSessionLocked(params, opts, accountKey, accountId, accountU
631
651
  }
632
652
  if (!fs.existsSync(profileDir)) fs.mkdirSync(profileDir, { recursive: true });
633
653
 
654
+ // The X account handle the server intends to restore. It is compared with the
655
+ // signed-in handle ONLY when it is a syntactically valid handle (never an email
656
+ // or phone number, which would otherwise be a permanent false mismatch).
657
+ const expectedUsername = launchParams.username || null;
658
+ const expectedHandle = sessionAuth.asExpectedHandle(expectedUsername);
659
+
634
660
  // ── 2.1.0 BROKER/WORKER SPLIT: route browser work to the interactive worker ──
635
661
  // When a worker bridge is configured (the machine-wide broker), the BROKER does
636
662
  // not launch Chromium itself: it validates identity (above) and hands the TYPED
637
663
  // browser command to the interactive worker, which owns the browser. The broker
638
664
  // keeps the lease, the session-registry authority, and the server link.
665
+ //
666
+ // The payload carries EVERYTHING the worker needs to restore a session: the
667
+ // normalized bootstrap cookies, the requested start URL, the expected account
668
+ // handle and the exact immutable profile identity (the worker re-validates the
669
+ // on-disk marker). Omitting them made a fresh/signed-out profile open signed
670
+ // out while a warm profile appeared to work.
639
671
  if (opts.workerBridge && typeof opts.workerBridge.call === 'function') {
640
672
  try {
641
673
  if (typeof opts.workerBridge.ensureWorker === 'function') await opts.workerBridge.ensureWorker();
@@ -644,21 +676,79 @@ async function _startSessionLocked(params, opts, accountKey, accountId, accountU
644
676
  accountUuid: resolvedAccountUuid,
645
677
  accountId: accountKey,
646
678
  profileDir,
679
+ serverUuid,
680
+ tenantUuid,
681
+ deviceUuid: deviceMeta.deviceId,
647
682
  requireProxy: _requireProxyForLaunch(launchParams),
648
683
  proxy,
649
684
  // Carried so a binding failure in the worker can name the exact central
650
685
  // assignment in its error instead of failing opaquely.
651
686
  proxyId: launchParams.proxyId != null ? launchParams.proxyId : null,
687
+ proxyFingerprint: proxy ? proxyIdentityFingerprint(proxy) : null,
688
+ // Bootstrap state. The backend normalized it to a Playwright array at the
689
+ // command chokepoint; the worker re-validates scope/expiry before writing.
690
+ cookies: Array.isArray(launchParams.cookies) ? launchParams.cookies : null,
691
+ url: launchParams.url || params.url || null,
692
+ expectedUsername,
693
+ expectedHandle,
652
694
  headless: false,
695
+ }, 180000);
696
+ if (!res || res.started !== true) {
697
+ throw Object.assign(new Error('interactive worker did not confirm the browser started'), {
698
+ code: 'WORKER_START_UNCONFIRMED',
699
+ stage: 'launch',
700
+ reason: (res && res.reason) || 'worker_start_unconfirmed',
701
+ });
702
+ }
703
+ const auth = sessionAuth.authSummary({
704
+ authState: res && res.authState,
705
+ reason: res && res.reason,
706
+ stage: res && res.stage,
707
+ handle: res && res.handle,
708
+ browserReady: res && res.browserReady,
653
709
  });
710
+ // Old agents silently ignore the new fields and return only `started`.
711
+ // Surface that as an explicit unsupported capability instead of claiming a
712
+ // verified session.
713
+ const unsupported = [];
714
+ if (!res || res.authState == null) unsupported.push('authVerification');
715
+ if (Array.isArray(launchParams.cookies) && launchParams.cookies.length > 0 && (!res || res.cookieState == null)) {
716
+ unsupported.push('cookieRestore');
717
+ }
654
718
  const session = {
655
- context: null, page: null, profileDir, accountId: accountKey, lease: null,
656
- accountUuid: resolvedAccountUuid, viaWorker: true, workerResult: res,
719
+ context: null,
720
+ page: null,
721
+ profileDir,
722
+ accountId: accountKey,
723
+ lease: null,
724
+ accountUuid: resolvedAccountUuid,
725
+ serverUuid,
726
+ tenantUuid,
727
+ viaWorker: true,
728
+ workerResult: res,
729
+ proxyIdentity: proxy ? proxyIdentityFingerprint(proxy) : null,
730
+ expectedUsername,
731
+ lastAuth: auth,
657
732
  };
658
733
  if (lease) leaseClient.bind(session, lease);
659
734
  activeSessions.set(accountKey, session);
660
735
  try { ws.send(JSON.stringify(leaseClient.boundStatusMessage(session, accountId, 'running'))); } catch { }
661
- return { success: true, accountId, started: true, visible: true, sessionId: accountKey, viaWorker: true };
736
+ return {
737
+ success: true,
738
+ accountId,
739
+ started: true,
740
+ visible: !res || res.visible !== false,
741
+ sessionId: accountKey,
742
+ viaWorker: true,
743
+ browserReady: auth.browserReady,
744
+ authState: auth.authState,
745
+ loggedIn: auth.loggedIn,
746
+ reason: auth.reason,
747
+ stage: auth.stage,
748
+ handle: auth.handle,
749
+ cookieState: (res && res.cookieState) || null,
750
+ unsupported: unsupported.length ? unsupported : undefined,
751
+ };
662
752
  } catch (err) {
663
753
  const code = (err && err.code) || 'WORKER_START_FAILED';
664
754
  // Safe, credential-free diagnostic: the failing stage and the identity of
@@ -674,11 +764,18 @@ async function _startSessionLocked(params, opts, accountKey, accountId, accountU
674
764
  proxyId: (err && err.proxyId != null) ? err.proxyId : (launchParams.proxyId != null ? launchParams.proxyId : null),
675
765
  proxy: (err && err.proxy) || null,
676
766
  networkMode: launchParams.networkMode || null,
677
- reason: _safeError(err),
767
+ reason: (err && err.reason) || _safeError(err),
678
768
  }));
679
769
  } catch { /* logging must never change the outcome */ }
680
770
  _sendStartError(code);
681
- return { success: false, code, stage: (err && err.stage) || null, error: _safeError(err) };
771
+ return {
772
+ success: false,
773
+ code,
774
+ stage: (err && err.stage) || null,
775
+ reason: (err && err.reason) || null,
776
+ authState: (err && err.authState) || null,
777
+ error: _safeError(err),
778
+ };
682
779
  }
683
780
  }
684
781
 
@@ -690,20 +787,41 @@ async function _startSessionLocked(params, opts, accountKey, accountId, accountU
690
787
  // this start carries, so every subsequent command/status for the account is
691
788
  // verified against the CURRENT authoritative credential rather than a stale
692
789
  // in-memory one from a previous reservation.
790
+ //
791
+ // A CHANGE in the central proxy assignment must not silently keep using the
792
+ // old binding: the session is stopped (without releasing the lease) and a
793
+ // fresh launch below re-binds it.
693
794
  const existingSession = activeSessions.get(accountKey);
694
- if (existingSession && existingSession.context) {
695
- if (lease) leaseClient.bind(existingSession, lease);
696
- // (The in-flight guard is released by _startSession's finally on return.)
697
- try { ws.send(JSON.stringify(leaseClient.boundStatusMessage(existingSession, accountId, 'running'))); } catch {}
698
- return {
699
- success: true,
700
- accountId,
701
- started: true,
702
- visible: true,
703
- sessionId: accountKey,
704
- alreadyRunning: true,
705
- status: 'running',
706
- };
795
+ if (existingSession && (existingSession.context || existingSession.viaWorker)) {
796
+ const newProxyFp = proxyIdentityFingerprint(_parseProxy(launchParams.proxy));
797
+ const proxyChanged = !!(existingSession.proxyIdentity && newProxyFp && existingSession.proxyIdentity !== newProxyFp);
798
+ if (proxyChanged) {
799
+ await _stopSession(accountId, lease, ws, opts, { suppressStopReport: true });
800
+ } else {
801
+ if (lease) leaseClient.bind(existingSession, lease);
802
+ // (The in-flight guard is released by _startSession's finally on return.)
803
+ try { ws.send(JSON.stringify(leaseClient.boundStatusMessage(existingSession, accountId, 'running'))); } catch {}
804
+ const auth = sessionAuth.authSummary(existingSession.lastAuth || {
805
+ authState: sessionAuth.AUTH_STATE.UNKNOWN,
806
+ reason: 'adopted_without_verification',
807
+ browserReady: true,
808
+ });
809
+ return {
810
+ success: true,
811
+ accountId,
812
+ started: true,
813
+ visible: true,
814
+ sessionId: accountKey,
815
+ alreadyRunning: true,
816
+ status: 'running',
817
+ browserReady: auth.browserReady,
818
+ authState: auth.authState,
819
+ loggedIn: auth.loggedIn,
820
+ reason: auth.reason,
821
+ stage: auth.stage,
822
+ handle: auth.handle,
823
+ };
824
+ }
707
825
  }
708
826
 
709
827
  // ── fingerprintStore.loadOrGenerate takes an OBJECT ({ profileDir, accountId,
@@ -900,19 +1018,14 @@ async function _startSessionLocked(params, opts, accountKey, accountId, accountU
900
1018
  // Playwright viewport, so removing the forced viewport does not weaken the
901
1019
  // fingerprint. window.innerWidth/innerHeight are left to the real window
902
1020
  // size, which is acceptable because the stealth script does not pin them.
903
- const launchOptions = {
904
- executablePath: opts.chromePath,
1021
+ const launchOptions = browserLaunch.buildChromiumLaunchOptions({
1022
+ chromePath: opts.chromePath,
905
1023
  headless: false,
906
1024
  args,
1025
+ proxy: proxyBinding.proxyOption || null,
1026
+ captureNetlog: true,
907
1027
  noDefaultViewport: true,
908
- // 2.1.0 B4: Chromium's CDP endpoint is loopback-only and ephemeral. Playwright
909
- // does this per-context, but we assert it explicitly so a future change that
910
- // tries to expose DevTools to a LAN/Tailscale interface fails closed.
911
- };
912
-
913
- if (proxyBinding.proxyOption) {
914
- launchOptions.proxy = proxyBinding.proxyOption;
915
- }
1028
+ });
916
1029
 
917
1030
  let context;
918
1031
  try {
@@ -924,6 +1037,20 @@ async function _startSessionLocked(params, opts, accountKey, accountId, accountU
924
1037
  return { success: false, error: _safeError(err) };
925
1038
  }
926
1039
 
1040
+ // ── 2.1.5 navigation containment ────────────────────────────────────────────
1041
+ // Bound navigation for this context and every future page, and replace a tab
1042
+ // that is stuck on about:blank (a proxy that never answers CONNECT) with an
1043
+ // actionable diagnostic page. Nothing is bypassed; the stall is only reported.
1044
+ let navGuard = null;
1045
+ try {
1046
+ navGuard = connectivity.installNavigationGuard(context, {
1047
+ accountLabel: resolvedAccountUuid || accountKey || null,
1048
+ onEvent: (event, detail) => {
1049
+ try { log('[session] navigation guard: ' + event + ' ' + JSON.stringify(detail || {})); } catch { /* safe */ }
1050
+ },
1051
+ });
1052
+ } catch { /* containment is best effort */ }
1053
+
927
1054
  // Record the real browser PID for the local registry + orphan detection. The
928
1055
  // PID must be provable as AGENT-OWNED before any process is ever terminated.
929
1056
  const browserPid = _browserPidForContext(context);
@@ -931,18 +1058,77 @@ async function _startSessionLocked(params, opts, accountKey, accountId, accountU
931
1058
 
932
1059
  await context.addInitScript(buildStealthScript(fingerprint));
933
1060
 
934
- // The server sends cookies in options (options.cookies); accept the flat
935
- // params form too for robustness.
936
- const cookiesToInject = launchOpts.cookies || params.cookies;
937
- if (cookiesToInject && Array.isArray(cookiesToInject)) {
938
- try { await context.addCookies(cookiesToInject); } catch {}
939
- }
940
-
941
1061
  const pages = context.pages();
942
1062
  const page = pages[0] || await context.newPage();
943
1063
 
944
- const url = params.url || 'https://x.com/home';
945
- await page.goto(url, { waitUntil: 'domcontentloaded' }).catch(() => {});
1064
+ // ── One canonical startup sequence (shared with the machine worker) ────────
1065
+ // Verify the EXISTING profile session BEFORE writing any cookie. A warmer,
1066
+ // newer native session must never be overwritten by a stale account import.
1067
+ // Only a profile that is proven signed out (or has no auth cookies at all) is
1068
+ // eligible for bootstrap restore. Navigation and proxy failures are classified
1069
+ // separately from a logout.
1070
+ const session = {
1071
+ context,
1072
+ page,
1073
+ profileDir,
1074
+ accountId: accountKey,
1075
+ lease: null,
1076
+ // 2.1.0 isolation metadata (non-secret; used for verified cleanup + registry).
1077
+ accountUuid: resolvedAccountUuid || null,
1078
+ serverUuid,
1079
+ tenantUuid,
1080
+ runtimeDirs,
1081
+ sessionsRoot,
1082
+ proxyIdentity: proxyIdentityFingerprint(proxyIdentity),
1083
+ browserPid,
1084
+ consistency,
1085
+ expectedUsername,
1086
+ lastAuth: null,
1087
+ navGuard,
1088
+ };
1089
+ if (lease) leaseClient.bind(session, lease);
1090
+ activeSessions.set(accountKey, session);
1091
+ _attachContextCloseReporter(context, session, accountKey, accountId, ws);
1092
+
1093
+ const cookiesToRestore = Array.isArray(launchOpts.cookies) ? launchOpts.cookies
1094
+ : (Array.isArray(params.cookies) ? params.cookies : null);
1095
+ let restore;
1096
+ try {
1097
+ restore = await sessionAuth.restoreAndVerify({
1098
+ page,
1099
+ context,
1100
+ cookies: cookiesToRestore,
1101
+ url: params.url || launchOpts.url || null,
1102
+ expectedUsername,
1103
+ applyCookies,
1104
+ navigationTimeoutMs: 45000,
1105
+ verifyTimeoutMs: 8000,
1106
+ });
1107
+ } catch (err) {
1108
+ restore = {
1109
+ authState: sessionAuth.AUTH_STATE.UNKNOWN,
1110
+ reason: 'startup_verification_failed',
1111
+ stage: 'verify',
1112
+ browserReady: true,
1113
+ };
1114
+ }
1115
+ session.lastAuth = restore;
1116
+
1117
+ // A startup navigation that never completed must not leave the visible tab on
1118
+ // about:blank with a permanent spinner: paint the actionable diagnostic page.
1119
+ if (restore && restore.navigationOk === false) {
1120
+ try {
1121
+ const failure = connectivity.classifyNavigationFailure(
1122
+ Object.assign(new Error(restore.reason || 'navigation failed'), { code: restore.code }),
1123
+ { url: params.url || launchOpts.url || 'https://x.com/home', proxyActive: !!proxyBinding.proxyOption, dnsPinned: requireProxy && !!proxyIdentity },
1124
+ );
1125
+ await connectivity.paintNavigationFailure(page, {
1126
+ ...failure,
1127
+ url: params.url || launchOpts.url || 'https://x.com/home',
1128
+ accountLabel: resolvedAccountUuid || accountKey,
1129
+ });
1130
+ } catch { /* containment is best effort */ }
1131
+ }
946
1132
 
947
1133
  // If the browser launched but immediately closed, report a clear error
948
1134
  // instead of showing a misleading green "browser opened" toast.
@@ -951,6 +1137,8 @@ async function _startSessionLocked(params, opts, accountKey, accountId, accountU
951
1137
  return {
952
1138
  success: false,
953
1139
  error: 'Browser launched but closed immediately. The session was not started.',
1140
+ stage: 'launch',
1141
+ reason: 'browser_closed_during_startup',
954
1142
  };
955
1143
  }
956
1144
 
@@ -987,23 +1175,6 @@ async function _startSessionLocked(params, opts, accountKey, accountId, accountU
987
1175
  };
988
1176
  }
989
1177
 
990
- const session = {
991
- context,
992
- page,
993
- profileDir,
994
- accountId: accountKey,
995
- lease: null,
996
- // 2.1.0 isolation metadata (non-secret; used for verified cleanup + registry).
997
- accountUuid: resolvedAccountUuid || null,
998
- runtimeDirs,
999
- sessionsRoot,
1000
- proxyIdentity: proxyIdentityFingerprint(proxyIdentity),
1001
- browserPid,
1002
- consistency,
1003
- };
1004
- if (lease) leaseClient.bind(session, lease);
1005
- activeSessions.set(accountKey, session);
1006
-
1007
1178
  // ── Lease-bound session-status reporting (Phase 3 parity with v1) ──────────
1008
1179
  // The server's session cache (`agent.sessions`) and the durable lease TTL
1009
1180
  // are ONLY updated by lease-bound `session-status` frames — never by the
@@ -1016,13 +1187,6 @@ async function _startSessionLocked(params, opts, accountKey, accountId, accountU
1016
1187
  };
1017
1188
  _sendStatus('running');
1018
1189
 
1019
- // A browser context closed outside our control (user closed the window,
1020
- // crash): report the verified stop so the server releases the lease — a
1021
- // dead local browser must not keep the account locked. Wired through the
1022
- // shared reporter so the API stop and the context close collapse to ONE
1023
- // authoritative report per session.
1024
- _attachContextCloseReporter(context, session, accountKey, accountId, ws);
1025
-
1026
1190
  // Return confirmed success metadata. The backend/frontend uses this to
1027
1191
  // show a green toast ONLY when the browser is genuinely started and visible.
1028
1192
  //
@@ -1037,6 +1201,7 @@ async function _startSessionLocked(params, opts, accountKey, accountId, accountU
1037
1201
  // If the Windows foreground helper cannot prove the window is visible
1038
1202
  // (foregroundVerified = false), we return started:true but visible:false
1039
1203
  // with an actionable error so the frontend does NOT show a green toast.
1204
+ const auth = sessionAuth.authSummary(restore);
1040
1205
  if (os.platform() === 'win32' && !foregroundVerified) {
1041
1206
  // The browser launched and bringToFront succeeded, but we could not
1042
1207
  // positively verify the window is in the foreground. Return a safe
@@ -1047,6 +1212,14 @@ async function _startSessionLocked(params, opts, accountKey, accountId, accountU
1047
1212
  started: true,
1048
1213
  visible: false,
1049
1214
  sessionId: accountId,
1215
+ browserReady: true,
1216
+ authState: auth.authState,
1217
+ loggedIn: auth.loggedIn,
1218
+ reason: auth.reason,
1219
+ stage: auth.stage,
1220
+ handle: auth.handle,
1221
+ cookieState: restore.cookieState || null,
1222
+ code: restore.code || null,
1050
1223
  error: 'Browser launched but could not be confirmed in the foreground. Check the taskbar for the Chrome window.',
1051
1224
  };
1052
1225
  }
@@ -1057,6 +1230,14 @@ async function _startSessionLocked(params, opts, accountKey, accountId, accountU
1057
1230
  started: true,
1058
1231
  visible: true,
1059
1232
  sessionId: accountId,
1233
+ browserReady: true,
1234
+ authState: auth.authState,
1235
+ loggedIn: auth.loggedIn,
1236
+ reason: auth.reason,
1237
+ stage: auth.stage,
1238
+ handle: auth.handle,
1239
+ cookieState: restore.cookieState || null,
1240
+ code: restore.code || null,
1060
1241
  };
1061
1242
  }
1062
1243
 
@@ -1079,6 +1260,7 @@ function _attachContextCloseReporter(context, session, accountKey, accountId, ws
1079
1260
  const closed = activeSessions.get(accountKey);
1080
1261
  if (closed && closed !== session) return;
1081
1262
  if (closed === session) activeSessions.delete(accountKey);
1263
+ try { if (session.navGuard) session.navGuard.stop(); } catch { /* safe */ }
1082
1264
  // The browser is ALREADY closed; mark it so the release path does not try to
1083
1265
  // close it again (which could recurse on a synchronously-emitting context).
1084
1266
  session._closeInitiated = true;
@@ -1169,12 +1351,16 @@ async function _releaseLocalSessionResources(session) {
1169
1351
  */
1170
1352
  function _reportStoppedOnce(session, accountId, ws) {
1171
1353
  if (!session || session._stopReported) return false;
1354
+ // A restart stops the old browser and starts a new one under the SAME inbound
1355
+ // lease. A lease-bound `stopped` frame would release that lease before the
1356
+ // restart can re-activate it, so the restart path suppresses it deliberately.
1357
+ if (session._suppressStopReport) return false;
1172
1358
  session._stopReported = true;
1173
1359
  try { ws.send(JSON.stringify(leaseClient.boundStatusMessage(session, accountId, 'stopped'))); } catch {}
1174
1360
  return true;
1175
1361
  }
1176
1362
 
1177
- async function _stopSession(accountId, lease, ws, opts) {
1363
+ async function _stopSession(accountId, lease, ws, opts, controls = {}) {
1178
1364
  // Account keys are stored as String(accountId) — normalize every lookup so a
1179
1365
  // number/string mismatch can never make a LIVE session invisible (which would
1180
1366
  // make a stop silently no-op and leave the browser running past its lease).
@@ -1200,12 +1386,25 @@ async function _stopSession(accountId, lease, ws, opts) {
1200
1386
  // which releases the local resources and reports the verified stop. To make
1201
1387
  // the ack TRUTHFUL (never claimed before local resources are gone), we run the
1202
1388
  // release explicitly here and only then emit the ack.
1389
+ if (controls.suppressStopReport) session._suppressStopReport = true;
1203
1390
  if (session.viaWorker && opts && opts.workerBridge && typeof opts.workerBridge.call === 'function') {
1204
- // The browser belongs to the interactive worker: ask it to stop, then remove
1205
- // the broker-side session entry. Only after the worker confirms do we ack.
1391
+ // The browser belongs to the interactive worker: ask it to stop and only ack
1392
+ // after the worker CONFIRMS the real browser closed. A thrown/timed-out
1393
+ // worker call must not be reported as a successful stop.
1394
+ let workerRes;
1206
1395
  try {
1207
- await opts.workerBridge.call('stopSession', { accountUuid: session.accountUuid || null, accountId: session.accountId }, 30000);
1208
- } catch { /* fall through: still remove our entry; worker will clean up */ }
1396
+ workerRes = await opts.workerBridge.call('stopSession', { accountUuid: session.accountUuid || null, accountId: session.accountId }, 45000);
1397
+ } catch (err) {
1398
+ return {
1399
+ success: false,
1400
+ code: (err && err.code) || 'WORKER_STOP_UNVERIFIED',
1401
+ stage: 'stop',
1402
+ error: 'The interactive worker did not confirm the browser closed; the session is still tracked locally.',
1403
+ };
1404
+ }
1405
+ if (!workerRes || workerRes.stopped !== true) {
1406
+ return { success: false, code: 'WORKER_STOP_UNVERIFIED', stage: 'stop', error: 'The interactive worker did not confirm the browser closed.' };
1407
+ }
1209
1408
  activeSessions.delete(accountKey);
1210
1409
  if (ws) _reportStoppedOnce(session, accountId, ws);
1211
1410
  return { success: true, accountId, stopped: true, viaWorker: true };
@@ -1257,51 +1456,225 @@ async function _stopOrphanedLocalSession(accountKey) {
1257
1456
  }
1258
1457
  }
1259
1458
 
1260
- async function _refreshSession(accountId) {
1459
+ /**
1460
+ * Route a typed browser command to the process that OWNS the page.
1461
+ *
1462
+ * The broker records worker-owned sessions with `page: null`; using the
1463
+ * broker-local page there was always wrong. This helper is the single bridge
1464
+ * between the broker's command surface and the worker's typed surface. An old
1465
+ * worker that does not understand a command is surfaced as an explicit
1466
+ * UNSUPPORTED_CAPABILITY (never silently treated as success).
1467
+ */
1468
+ async function _workerCall(session, opts, command, payload, timeoutMs) {
1469
+ const bridge = opts && opts.workerBridge;
1470
+ if (!bridge || typeof bridge.call !== 'function') {
1471
+ return { success: false, code: 'UNSUPPORTED_CAPABILITY', stage: 'worker_bridge', error: 'No interactive worker bridge is available for this session.' };
1472
+ }
1473
+ try {
1474
+ return await bridge.call(command, payload, timeoutMs || 120000);
1475
+ } catch (err) {
1476
+ const code = (err && err.code) || 'WORKER_CALL_FAILED';
1477
+ if (code === 'UNKNOWN_COMMAND' || code === 'WORKER_UNSUPPORTED') {
1478
+ return {
1479
+ success: false,
1480
+ code: 'UNSUPPORTED_CAPABILITY',
1481
+ stage: 'worker_bridge',
1482
+ capability: command,
1483
+ error: `The connected agent build does not support the '${command}' browser command. Update the agent on this device.`,
1484
+ };
1485
+ }
1486
+ return {
1487
+ success: false,
1488
+ code,
1489
+ stage: (err && err.stage) || null,
1490
+ reason: (err && err.reason) || null,
1491
+ authState: (err && err.authState) || null,
1492
+ error: _safeError(err),
1493
+ };
1494
+ }
1495
+ }
1496
+
1497
+ async function _checkAuth(accountId, opts) {
1261
1498
  const session = activeSessions.get(String(accountId));
1262
- if (!session) return { success: false, error: 'Session not found' };
1263
- await session.page.reload();
1264
- return { success: true };
1499
+ if (!session) {
1500
+ return {
1501
+ success: true, browserReady: false, authState: sessionAuth.AUTH_STATE.UNKNOWN,
1502
+ loggedIn: false, state: 'no_browser', reason: 'no_browser', stage: 'status',
1503
+ };
1504
+ }
1505
+ if (session.viaWorker) {
1506
+ const res = await _workerCall(session, opts, 'checkAuth', { accountId: session.accountId, accountUuid: session.accountUuid }, 30000);
1507
+ if (res && res.authState) session.lastAuth = res;
1508
+ return res;
1509
+ }
1510
+ const verified = await sessionAuth.verifyXAuth(session.page, session.context, {
1511
+ expectedUsername: session.expectedUsername,
1512
+ timeoutMs: 5000,
1513
+ });
1514
+ session.lastAuth = verified;
1515
+ return { success: true, browserReady: true, ...sessionAuth.authSummary(verified) };
1265
1516
  }
1266
1517
 
1267
- async function _navigate(accountId, url) {
1518
+ async function _refreshSession(accountId, opts) {
1268
1519
  const session = activeSessions.get(String(accountId));
1269
- if (!session) return { success: false, error: 'Session not found' };
1270
- await session.page.goto(url, { waitUntil: 'domcontentloaded' });
1271
- return { success: true };
1520
+ if (!session) {
1521
+ return {
1522
+ success: false, code: 'SESSION_NOT_FOUND', browserReady: false,
1523
+ authState: sessionAuth.AUTH_STATE.UNKNOWN, reason: 'no_browser',
1524
+ };
1525
+ }
1526
+ if (session.viaWorker) {
1527
+ const res = await _workerCall(session, opts, 'refreshSession', { accountId: session.accountId, accountUuid: session.accountUuid }, 60000);
1528
+ if (res && res.authState) session.lastAuth = res;
1529
+ return res;
1530
+ }
1531
+ // Bounded refresh: a stalled reload must not leave the visible tab blank.
1532
+ let current = '';
1533
+ try { current = session.page.url(); } catch { current = ''; }
1534
+ const target = sessionAuth.isAuthorizedXUrl(current) ? current : 'https://x.com/home';
1535
+ const nav = await connectivity.navigateBounded(session.page, target, {
1536
+ timeoutMs: 30000,
1537
+ proxyActive: !!session.proxyIdentity,
1538
+ dnsPinned: !!session.proxyIdentity,
1539
+ accountLabel: session.accountUuid || session.accountId,
1540
+ });
1541
+ const verified = await sessionAuth.verifyXAuth(session.page, session.context, {
1542
+ expectedUsername: session.expectedUsername,
1543
+ timeoutMs: 5000,
1544
+ });
1545
+ session.lastAuth = verified;
1546
+ return {
1547
+ success: nav.ok,
1548
+ browserReady: true,
1549
+ ...(nav.ok ? {} : { code: nav.code, stage: nav.stage, reason: nav.reason, error: nav.message, painted: nav.painted === true }),
1550
+ ...sessionAuth.authSummary(verified),
1551
+ };
1552
+ }
1553
+
1554
+ async function _navigate(accountId, url, opts) {
1555
+ const session = activeSessions.get(String(accountId));
1556
+ if (!session) return { success: false, error: 'Session not found', code: 'SESSION_NOT_FOUND' };
1557
+ if (!sessionAuth.isAuthorizedXUrl(url)) {
1558
+ return { success: false, code: 'NAVIGATION_TARGET_REFUSED', stage: 'navigation', error: 'Navigation target is not an authorized X origin.' };
1559
+ }
1560
+ if (session.viaWorker) {
1561
+ return _workerCall(session, opts, 'navigate', { accountId: session.accountId, accountUuid: session.accountUuid, url }, 60000);
1562
+ }
1563
+ const nav = await connectivity.navigateBounded(session.page, url, {
1564
+ timeoutMs: 45000,
1565
+ proxyActive: !!session.proxyIdentity,
1566
+ dnsPinned: !!session.proxyIdentity,
1567
+ accountLabel: session.accountUuid || session.accountId,
1568
+ });
1569
+ if (nav.ok) return { success: true };
1570
+ return {
1571
+ success: false,
1572
+ code: nav.code,
1573
+ stage: nav.stage,
1574
+ reason: nav.reason,
1575
+ error: nav.message,
1576
+ painted: nav.painted === true,
1577
+ };
1272
1578
  }
1273
1579
 
1274
- async function _typeText(accountId, selector, text) {
1580
+ async function _typeText(accountId, selector, text, opts) {
1275
1581
  const session = activeSessions.get(String(accountId));
1276
- if (!session) return { success: false, error: 'Session not found' };
1582
+ if (!session) return { success: false, error: 'Session not found', code: 'SESSION_NOT_FOUND' };
1583
+ if (session.viaWorker) {
1584
+ return _workerCall(session, opts, 'type', { accountId: session.accountId, accountUuid: session.accountUuid, selector, text }, 60000);
1585
+ }
1277
1586
  await session.page.locator(selector).fill(text);
1278
1587
  return { success: true };
1279
1588
  }
1280
1589
 
1281
- async function _pressKey(accountId, key) {
1590
+ async function _pressKey(accountId, key, opts) {
1282
1591
  const session = activeSessions.get(String(accountId));
1283
- if (!session) return { success: false, error: 'Session not found' };
1592
+ if (!session) return { success: false, error: 'Session not found', code: 'SESSION_NOT_FOUND' };
1593
+ if (session.viaWorker) {
1594
+ return _workerCall(session, opts, 'press', { accountId: session.accountId, accountUuid: session.accountUuid, key }, 60000);
1595
+ }
1284
1596
  await session.page.keyboard.press(key);
1285
1597
  return { success: true };
1286
1598
  }
1287
1599
 
1288
- async function _click(accountId, selector) {
1600
+ async function _click(accountId, selector, opts) {
1289
1601
  const session = activeSessions.get(String(accountId));
1290
- if (!session) return { success: false, error: 'Session not found' };
1602
+ if (!session) return { success: false, error: 'Session not found', code: 'SESSION_NOT_FOUND' };
1603
+ if (session.viaWorker) {
1604
+ return _workerCall(session, opts, 'click', { accountId: session.accountId, accountUuid: session.accountUuid, selector }, 60000);
1605
+ }
1291
1606
  await session.page.locator(selector).click();
1292
1607
  return { success: true };
1293
1608
  }
1294
1609
 
1295
- async function _focusSession(accountId) {
1610
+ async function _focusSession(accountId, opts) {
1296
1611
  const session = activeSessions.get(String(accountId));
1297
- if (!session) return { success: false, error: 'Session not found' };
1612
+ if (!session) return { success: false, error: 'Session not found', code: 'SESSION_NOT_FOUND' };
1613
+ if (session.viaWorker) {
1614
+ return _workerCall(session, opts, 'focus', { accountId: session.accountId, accountUuid: session.accountUuid }, 30000);
1615
+ }
1298
1616
  await session.page.bringToFront();
1299
1617
  return { success: true };
1300
1618
  }
1301
1619
 
1302
- async function _runAction(accountId, action, payload) {
1620
+ // Actions that may run while signed out (they diagnose or perform the login).
1621
+ const AUTH_EXEMPT_ACTIONS = new Set([
1622
+ 'autoLogin', 'checkLoginState', 'checkStatus', 'humanResume', 'connectAutomation',
1623
+ ]);
1624
+
1625
+ /**
1626
+ * Return {ok:true} only when the live session is verified signed in. Definite
1627
+ * failures (signed_out / wrong_account / challenge_required) and observed
1628
+ * unknown states block the action BEFORE any side effect. The "no_browser_signal"
1629
+ * unknown (a test/legacy page without DOM access) is not treated as evidence.
1630
+ */
1631
+ async function _authPreflight(session) {
1632
+ const verified = await sessionAuth.verifyXAuth(session.page, session.context, {
1633
+ expectedUsername: session.expectedUsername,
1634
+ timeoutMs: 4000,
1635
+ });
1636
+ session.lastAuth = verified;
1637
+ const s = verified.authState;
1638
+ const definite = s === sessionAuth.AUTH_STATE.SIGNED_OUT
1639
+ || s === sessionAuth.AUTH_STATE.WRONG_ACCOUNT
1640
+ || s === sessionAuth.AUTH_STATE.CHALLENGE_REQUIRED;
1641
+ const observedUnknown = s === sessionAuth.AUTH_STATE.UNKNOWN && verified.reason !== 'no_browser_signal';
1642
+ if (definite || observedUnknown) {
1643
+ return { ok: false, verified, code: 'AUTH_UNVERIFIED' };
1644
+ }
1645
+ return { ok: true, verified };
1646
+ }
1647
+
1648
+ async function _runAction(accountId, action, payload, opts) {
1303
1649
  const session = activeSessions.get(String(accountId));
1304
- if (!session) return { success: false, error: 'Session not found' };
1650
+ if (!session) return { success: false, error: 'Session not found', code: 'SESSION_NOT_FOUND' };
1651
+ // The worker owns the page; it performs the same preflight and the action in
1652
+ // one process, so no script/page crosses the bridge.
1653
+ if (session.viaWorker) {
1654
+ return _workerCall(session, opts, 'runAction', {
1655
+ accountId: session.accountId,
1656
+ accountUuid: session.accountUuid,
1657
+ action,
1658
+ payload: payload || {},
1659
+ }, 300000);
1660
+ }
1661
+ if (!AUTH_EXEMPT_ACTIONS.has(action)) {
1662
+ const gate = await _authPreflight(session);
1663
+ if (!gate.ok) {
1664
+ const a = gate.verified.authState;
1665
+ const code = a === sessionAuth.AUTH_STATE.WRONG_ACCOUNT ? 'WRONG_ACCOUNT'
1666
+ : a === sessionAuth.AUTH_STATE.CHALLENGE_REQUIRED ? 'CHALLENGE_REQUIRED'
1667
+ : 'AUTH_UNVERIFIED';
1668
+ return {
1669
+ success: false,
1670
+ code,
1671
+ error: 'The X session is not verified as signed in; the action was not started.',
1672
+ failureStage: 'pre_action',
1673
+ browserReady: true,
1674
+ ...sessionAuth.authSummary(gate.verified),
1675
+ };
1676
+ }
1677
+ }
1305
1678
  const { runAction } = require('./actions');
1306
1679
  // Return the ACTION result at the TOP level. The server places this value in
1307
1680
  // the command-response `result` field and reads success/code/outcome/
@@ -1312,15 +1685,82 @@ async function _runAction(accountId, action, payload) {
1312
1685
  return await runAction(session.page, action, payload || {});
1313
1686
  }
1314
1687
 
1315
- function _getStatus(accountId) {
1688
+ async function _getStatus(accountId, opts) {
1316
1689
  const key = String(accountId || '');
1317
1690
  const session = key ? activeSessions.get(key) : null;
1318
- if (session && session.context) {
1319
- let url = null;
1320
- try { url = session.page && !session.page.isClosed() ? session.page.url() : null; } catch { url = null; }
1321
- return { success: true, status: 'running', accountId: key, url };
1691
+ if (!session) {
1692
+ // Explicit no-browser state. A status check must never open a window.
1693
+ return {
1694
+ success: true,
1695
+ status: 'stopped',
1696
+ accountId: key || null,
1697
+ url: null,
1698
+ browserReady: false,
1699
+ authState: sessionAuth.AUTH_STATE.UNKNOWN,
1700
+ loggedIn: false,
1701
+ state: 'no_browser',
1702
+ reason: 'no_browser',
1703
+ stage: 'status',
1704
+ };
1322
1705
  }
1323
- return { success: true, status: 'stopped', accountId: key || null, url: null };
1706
+ if (session.viaWorker) {
1707
+ const res = await _workerCall(session, opts, 'getStatus', { accountId: session.accountId, accountUuid: session.accountUuid }, 15000);
1708
+ if (res && res.running === false) {
1709
+ return {
1710
+ success: true, status: 'stopped', accountId: key, url: null,
1711
+ browserReady: false, authState: sessionAuth.AUTH_STATE.UNKNOWN, loggedIn: false,
1712
+ state: 'no_browser', reason: res.reason || 'no_browser', stage: 'status',
1713
+ };
1714
+ }
1715
+ if (res && res.success === false) {
1716
+ return {
1717
+ success: true, status: 'running', accountId: key, url: null,
1718
+ browserReady: true, authState: sessionAuth.AUTH_STATE.UNKNOWN, loggedIn: false,
1719
+ code: res.code || 'STATUS_UNVERIFIED', reason: res.reason || 'worker_status_unavailable',
1720
+ unsupported: res.code === 'UNSUPPORTED_CAPABILITY' ? ['getStatus'] : undefined,
1721
+ };
1722
+ }
1723
+ const auth = res || {};
1724
+ return {
1725
+ success: true,
1726
+ status: 'running',
1727
+ accountId: key,
1728
+ url: auth.url || null,
1729
+ pageStalled: auth.pageStalled === true || auth.url === 'about:blank',
1730
+ browserReady: true,
1731
+ authState: auth.authState || sessionAuth.AUTH_STATE.UNKNOWN,
1732
+ loggedIn: auth.authState === sessionAuth.AUTH_STATE.AUTHENTICATED,
1733
+ reason: auth.reason || null,
1734
+ stage: auth.stage || 'status',
1735
+ handle: auth.handle || null,
1736
+ browser: auth.browser || null,
1737
+ connectivity: auth.connectivity || null,
1738
+ };
1739
+ }
1740
+ let url = null;
1741
+ try { url = session.page && !session.page.isClosed() ? session.page.url() : null; } catch { url = null; }
1742
+ const auth = sessionAuth.authSummary(session.lastAuth || {
1743
+ authState: sessionAuth.AUTH_STATE.UNKNOWN, reason: 'not_checked', browserReady: true,
1744
+ });
1745
+ return {
1746
+ success: true,
1747
+ status: 'running',
1748
+ accountId: key,
1749
+ url,
1750
+ // A tab parked on about:blank is never a healthy state; surface it so the UI
1751
+ // can offer the connectivity diagnostic instead of silently showing a spinner.
1752
+ pageStalled: url === 'about:blank',
1753
+ browserReady: true,
1754
+ authState: auth.authState,
1755
+ loggedIn: auth.loggedIn,
1756
+ reason: auth.reason,
1757
+ stage: auth.stage,
1758
+ handle: auth.handle,
1759
+ browser: browserLaunch.describeBrowser(opts && opts.chromePath),
1760
+ connectivity: session.navGuard
1761
+ ? { guard: session.navGuard.options, stalledPainted: session.navGuard.stats.painted }
1762
+ : null,
1763
+ };
1324
1764
  }
1325
1765
 
1326
1766
  function _importLegacyProfile(accountId, accountUuid, opts) {
@@ -1372,11 +1812,32 @@ async function _proxyTest(params) {
1372
1812
  const requireProxy = proxyRequiredForSession({ proxyStr, networkMode });
1373
1813
  const proxyObj = { server: ident.server, username: ident.username, password: ident.password };
1374
1814
 
1815
+ // ── Capability-based health (2.1.5) ────────────────────────────────────────
1816
+ // A single ipify response is NOT proof a proxy is usable for the operator's
1817
+ // destinations. Assess every managed destination (bounded, cached, rate
1818
+ // limited) so a proxy that works for X but denies Google is reported as
1819
+ // DESTINATION_RESTRICTED instead of "reachable".
1820
+ const proxyCapability = require('./proxyCapability');
1821
+ let capability = null;
1822
+ try {
1823
+ const report = await proxyCapability.assessProxyHealth({
1824
+ proxy: proxyObj,
1825
+ bypassCache: params && params.refresh === true,
1826
+ });
1827
+ capability = proxyCapability.summarizeProxyHealth(report);
1828
+ } catch (e) {
1829
+ capability = {
1830
+ state: proxyCapability.PROXY_HEALTH_STATES.UNKNOWN,
1831
+ destinations: [],
1832
+ action: 'The proxy capability assessment could not be completed.',
1833
+ };
1834
+ }
1835
+
1375
1836
  let iso;
1376
1837
  try {
1377
1838
  iso = await require('./proxyEgress').verifyProxyIsolation(proxyObj, {});
1378
1839
  } catch (e) {
1379
- return { success: false, code: (e && e.code) || 'PROXY_EGRESS_UNREACHABLE', stage: 'egress', protocol: ident.type, host: ident.host, port: ident.port, timestamp: new Date().toISOString() };
1840
+ iso = { ok: false, code: (e && e.code) || 'PROXY_EGRESS_UNREACHABLE' };
1380
1841
  }
1381
1842
 
1382
1843
  if (!iso || !iso.ok) {
@@ -1398,25 +1859,161 @@ async function _proxyTest(params) {
1398
1859
  return {
1399
1860
  success: false,
1400
1861
  code,
1862
+ healthCode: capability ? capabilityCodeForState(capability.state) : code,
1863
+ state: capability ? capability.state : null,
1401
1864
  stage: 'egress',
1402
1865
  protocol: ident.type, host: ident.host, port: ident.port,
1403
1866
  detail: (iso && iso.reason) ? String(iso.reason).slice(0, 200) : null,
1867
+ capability,
1404
1868
  timestamp: new Date().toISOString(),
1405
1869
  };
1406
1870
  }
1407
1871
 
1872
+ const capabilityOk = capability && capability.state === proxyCapability.PROXY_HEALTH_STATES.HEALTHY;
1873
+ // Backward-compatible success code for existing API/UI consumers; the richer
1874
+ // state is exposed separately (`state`, `healthCode`, `capability`).
1408
1875
  return {
1409
- success: true,
1410
- code: 'PROXY_ISOLATION_OK',
1411
- stage: 'egress',
1876
+ success: capabilityOk,
1877
+ code: capabilityOk ? 'PROXY_ISOLATION_OK' : (capabilityCodeForState(capability.state)),
1878
+ healthCode: capabilityOk ? 'PROXY_HEALTHY' : capabilityCodeForState(capability.state),
1879
+ state: capability.state,
1880
+ stage: 'capability',
1881
+ isolationCode: 'PROXY_ISOLATION_OK',
1412
1882
  latencyMs: Date.now() - started,
1413
1883
  egressIp: iso.egressIp || null,
1414
1884
  directIp: iso.directIp || null,
1415
1885
  protocol: ident.type,
1416
1886
  host: ident.host,
1417
1887
  port: ident.port,
1888
+ capability,
1889
+ action: capability.action || null,
1890
+ timestamp: new Date().toISOString(),
1891
+ };
1892
+ }
1893
+
1894
+ /**
1895
+ * Map a capability state to a stable API code. `PROXY_AUTH_FAILED` is kept for
1896
+ * the UI's existing auth-failure presentation; every other state gets a
1897
+ * `PROXY_`-prefixed code so consumers can distinguish restriction from timeout.
1898
+ */
1899
+ function capabilityCodeForState(state) {
1900
+ const cap = require('./proxyCapability');
1901
+ if (state === cap.PROXY_HEALTH_STATES.AUTHENTICATION_FAILED) return 'PROXY_AUTH_FAILED';
1902
+ if (!state) return 'PROXY_UNREACHABLE';
1903
+ return 'PROXY_' + state;
1904
+ }
1905
+
1906
+ /**
1907
+ * Per-endpoint browser connectivity diagnostic + capability assessment (2.1.5).
1908
+ *
1909
+ * Walks the public endpoints the operator actually needs (Google Search, Chrome
1910
+ * Web Store, Google sign-in, gstatic, clients2, update.googleapis.com, X,
1911
+ * example.com, api.ipify.org) with a real DNS/TCP/TLS/HTTP probe. When a proxy is
1912
+ * supplied the probe tunnels THROUGH it (HTTP CONNECT or SOCKS5 + TLS + GET) and
1913
+ * never falls back to a direct connection. The result carries a capability state
1914
+ * so a proxy that works for X but denies Google is reported as
1915
+ * DESTINATION_RESTRICTED instead of "healthy".
1916
+ *
1917
+ * The requested URL list is limited to the documented public allowlist: the
1918
+ * command channel can never be used to probe arbitrary internal hosts (SSRF).
1919
+ *
1920
+ * Sanitized: no credential, cookie or Proxy-Authorization value is returned.
1921
+ *
1922
+ * @param {object} params { proxy?, networkMode?, urls?, timeoutMs?, direct?, refresh? }
1923
+ * @returns {Promise<object>} { success, code, state, proxy, results, capability, ... }
1924
+ */
1925
+ async function _connectivityTest(params) {
1926
+ const started = Date.now();
1927
+ const proxyStr = params && params.proxy;
1928
+ const timeoutMs = Number.isFinite(params && params.timeoutMs) ? params.timeoutMs : 8000;
1929
+ const proxyCapability = require('./proxyCapability');
1930
+
1931
+ // Destination allowlist (SSRF prevention). Only the documented endpoints may
1932
+ // be probed; anything else is refused, never silently ignored.
1933
+ let urls;
1934
+ if (Array.isArray(params && params.urls) && params.urls.length > 0) {
1935
+ const allowed = new Set(connectivity.CONNECTIVITY_ENDPOINTS);
1936
+ const bad = params.urls.filter((u) => !allowed.has(String(u)));
1937
+ if (bad.length > 0) {
1938
+ return {
1939
+ success: false,
1940
+ code: 'PROBE_TARGET_NOT_ALLOWED',
1941
+ stage: 'validation',
1942
+ error: 'Only the documented public connectivity endpoints may be probed.',
1943
+ timestamp: new Date().toISOString(),
1944
+ };
1945
+ }
1946
+ urls = params.urls.map(String);
1947
+ }
1948
+
1949
+ let proxyObj = null;
1950
+ if (proxyStr) {
1951
+ const ident = parseProxyIdentity(proxyStr);
1952
+ if (!ident) {
1953
+ return { success: false, code: 'PROXY_FORMAT_INVALID', stage: 'parse', timestamp: new Date().toISOString() };
1954
+ }
1955
+ const v = validateProxyConfig(ident);
1956
+ if (!v.ok) {
1957
+ return { success: false, code: v.code, stage: 'validate', timestamp: new Date().toISOString() };
1958
+ }
1959
+ proxyObj = { server: ident.server, username: ident.username, password: ident.password };
1960
+ }
1961
+
1962
+ const out = {
1963
+ success: false,
1964
+ code: 'CONNECTIVITY_OK',
1965
+ stage: 'connectivity',
1966
+ latencyMs: 0,
1418
1967
  timestamp: new Date().toISOString(),
1419
1968
  };
1969
+
1970
+ if (proxyObj) {
1971
+ // Capability-based assessment: per-destination states + overall state.
1972
+ const report = await proxyCapability.assessProxyHealth({
1973
+ proxy: proxyObj,
1974
+ urls,
1975
+ timeoutMs,
1976
+ bypassCache: params && params.refresh === true,
1977
+ });
1978
+ const summary = proxyCapability.summarizeProxyHealth(report);
1979
+ out.state = summary.state;
1980
+ out.proxy = summary.proxy;
1981
+ out.protocol = summary.protocol;
1982
+ out.protocolSupported = summary.protocolSupported;
1983
+ out.destinations = summary.destinations;
1984
+ out.capability = summary.capability;
1985
+ out.families = summary.families;
1986
+ out.cached = summary.cached;
1987
+ out.rateLimited = summary.rateLimited;
1988
+ out.retryAfterMs = summary.retryAfterMs;
1989
+ out.action = summary.action;
1990
+ out.summary = { total: summary.destinations.length, healthy: (report.summary || {}).healthy || 0, failed: (report.summary || {}).failed || 0, restricted: (report.summary || {}).restricted || 0 };
1991
+ out.code = summary.state;
1992
+ out.success = summary.state === proxyCapability.PROXY_HEALTH_STATES.HEALTHY;
1993
+ } else {
1994
+ const report = await connectivity.probeConnectivity({ proxy: null, urls, timeoutMs });
1995
+ out.proxy = report.proxy;
1996
+ out.results = report.results.map((r) => ({
1997
+ url: r.url, host: r.host, ok: r.ok, status: r.status, ms: r.ms,
1998
+ dnsMs: r.dnsMs, connectMs: r.connectMs, tlsMs: r.tlsMs, code: r.code, redirectTo: r.redirectTo,
1999
+ }));
2000
+ out.summary = report.summary;
2001
+ out.code = report.summary.failed === 0 ? 'CONNECTIVITY_OK' : 'CONNECTIVITY_PARTIAL';
2002
+ out.success = report.summary.failed === 0;
2003
+ }
2004
+
2005
+ // Optionally compare the device's own direct path. Explicitly opt-in so a
2006
+ // configured proxy is never silently bypassed by routine diagnostics.
2007
+ if (proxyObj && params && params.direct === true) {
2008
+ const direct = await connectivity.probeConnectivity({
2009
+ proxy: null,
2010
+ urls: urls || ['https://example.com', 'https://www.google.com', 'https://x.com'],
2011
+ timeoutMs,
2012
+ });
2013
+ out.direct = { proxy: direct.proxy, summary: direct.summary, results: direct.results };
2014
+ }
2015
+ out.latencyMs = Date.now() - started;
2016
+ return out;
1420
2017
  }
1421
2018
 
1422
2019
  // ── Helpers ──────────────────────────────────────────────────────────────────
@@ -1593,4 +2190,5 @@ module.exports = {
1593
2190
  _stopOrphanedLocalSession,
1594
2191
  recoverOrphanedSessions,
1595
2192
  _proxyTest,
2193
+ _connectivityTest,
1596
2194
  };