@xkwdstore/agent 2.1.4 → 2.1.6
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/CHANGELOG.md +163 -0
- package/README.md +281 -278
- package/package.json +43 -42
- package/scripts/install-machine-agent.ps1 +385 -385
- package/src/actions/helpers.js +15 -21
- package/src/actions/session.js +142 -16
- package/src/brokerConnectionSupervisor.js +319 -263
- package/src/brokerHealth.js +113 -0
- package/src/brokerWorkerBridge.js +377 -352
- package/src/browserConnectivity.js +1461 -0
- package/src/browserIsolation.js +26 -1
- package/src/browserLaunch.js +136 -0
- package/src/cli.js +1290 -1108
- package/src/cookieInjection.js +255 -0
- package/src/enrollmentClient.js +51 -26
- package/src/index.js +75 -53
- package/src/proxyCapability.js +481 -0
- package/src/sessionAuth.js +439 -0
- package/src/sessionHandler.js +709 -108
- package/src/worker.js +707 -253
package/src/sessionHandler.js
CHANGED
|
@@ -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
|
-
|
|
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
|
|
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,
|
|
656
|
-
|
|
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 {
|
|
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 {
|
|
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
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
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,
|
|
@@ -874,6 +992,9 @@ async function _startSessionLocked(params, opts, accountKey, accountId, accountU
|
|
|
874
992
|
// pin is still applied via proxyHostForDns.
|
|
875
993
|
proxyServerUrl: requireProxy && !proxyBinding.proxyOption && proxyIdentity ? proxyIdentity.server : null,
|
|
876
994
|
proxyHostForDns: requireProxy && proxyIdentity ? proxyIdentity.host : null,
|
|
995
|
+
// Credentials present => Chromium's authenticated-proxy HTTP/2 path, which
|
|
996
|
+
// stalls on Google properties. Pin HTTP/1.1 for this case only.
|
|
997
|
+
proxyAuthenticated: Boolean(proxyIdentity && proxyIdentity.username !== undefined && proxyIdentity.username !== ''),
|
|
877
998
|
baseArgs: [
|
|
878
999
|
'--disable-blink-features=AutomationControlled',
|
|
879
1000
|
'--force-webrtc-ip-handling-policy=disable_non_proxied_udp',
|
|
@@ -900,19 +1021,14 @@ async function _startSessionLocked(params, opts, accountKey, accountId, accountU
|
|
|
900
1021
|
// Playwright viewport, so removing the forced viewport does not weaken the
|
|
901
1022
|
// fingerprint. window.innerWidth/innerHeight are left to the real window
|
|
902
1023
|
// size, which is acceptable because the stealth script does not pin them.
|
|
903
|
-
const launchOptions = {
|
|
904
|
-
|
|
1024
|
+
const launchOptions = browserLaunch.buildChromiumLaunchOptions({
|
|
1025
|
+
chromePath: opts.chromePath,
|
|
905
1026
|
headless: false,
|
|
906
1027
|
args,
|
|
1028
|
+
proxy: proxyBinding.proxyOption || null,
|
|
1029
|
+
captureNetlog: true,
|
|
907
1030
|
noDefaultViewport: true,
|
|
908
|
-
|
|
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
|
-
}
|
|
1031
|
+
});
|
|
916
1032
|
|
|
917
1033
|
let context;
|
|
918
1034
|
try {
|
|
@@ -924,6 +1040,20 @@ async function _startSessionLocked(params, opts, accountKey, accountId, accountU
|
|
|
924
1040
|
return { success: false, error: _safeError(err) };
|
|
925
1041
|
}
|
|
926
1042
|
|
|
1043
|
+
// ── 2.1.5 navigation containment ────────────────────────────────────────────
|
|
1044
|
+
// Bound navigation for this context and every future page, and replace a tab
|
|
1045
|
+
// that is stuck on about:blank (a proxy that never answers CONNECT) with an
|
|
1046
|
+
// actionable diagnostic page. Nothing is bypassed; the stall is only reported.
|
|
1047
|
+
let navGuard = null;
|
|
1048
|
+
try {
|
|
1049
|
+
navGuard = connectivity.installNavigationGuard(context, {
|
|
1050
|
+
accountLabel: resolvedAccountUuid || accountKey || null,
|
|
1051
|
+
onEvent: (event, detail) => {
|
|
1052
|
+
try { log('[session] navigation guard: ' + event + ' ' + JSON.stringify(detail || {})); } catch { /* safe */ }
|
|
1053
|
+
},
|
|
1054
|
+
});
|
|
1055
|
+
} catch { /* containment is best effort */ }
|
|
1056
|
+
|
|
927
1057
|
// Record the real browser PID for the local registry + orphan detection. The
|
|
928
1058
|
// PID must be provable as AGENT-OWNED before any process is ever terminated.
|
|
929
1059
|
const browserPid = _browserPidForContext(context);
|
|
@@ -931,18 +1061,77 @@ async function _startSessionLocked(params, opts, accountKey, accountId, accountU
|
|
|
931
1061
|
|
|
932
1062
|
await context.addInitScript(buildStealthScript(fingerprint));
|
|
933
1063
|
|
|
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
1064
|
const pages = context.pages();
|
|
942
1065
|
const page = pages[0] || await context.newPage();
|
|
943
1066
|
|
|
944
|
-
|
|
945
|
-
|
|
1067
|
+
// ── One canonical startup sequence (shared with the machine worker) ────────
|
|
1068
|
+
// Verify the EXISTING profile session BEFORE writing any cookie. A warmer,
|
|
1069
|
+
// newer native session must never be overwritten by a stale account import.
|
|
1070
|
+
// Only a profile that is proven signed out (or has no auth cookies at all) is
|
|
1071
|
+
// eligible for bootstrap restore. Navigation and proxy failures are classified
|
|
1072
|
+
// separately from a logout.
|
|
1073
|
+
const session = {
|
|
1074
|
+
context,
|
|
1075
|
+
page,
|
|
1076
|
+
profileDir,
|
|
1077
|
+
accountId: accountKey,
|
|
1078
|
+
lease: null,
|
|
1079
|
+
// 2.1.0 isolation metadata (non-secret; used for verified cleanup + registry).
|
|
1080
|
+
accountUuid: resolvedAccountUuid || null,
|
|
1081
|
+
serverUuid,
|
|
1082
|
+
tenantUuid,
|
|
1083
|
+
runtimeDirs,
|
|
1084
|
+
sessionsRoot,
|
|
1085
|
+
proxyIdentity: proxyIdentityFingerprint(proxyIdentity),
|
|
1086
|
+
browserPid,
|
|
1087
|
+
consistency,
|
|
1088
|
+
expectedUsername,
|
|
1089
|
+
lastAuth: null,
|
|
1090
|
+
navGuard,
|
|
1091
|
+
};
|
|
1092
|
+
if (lease) leaseClient.bind(session, lease);
|
|
1093
|
+
activeSessions.set(accountKey, session);
|
|
1094
|
+
_attachContextCloseReporter(context, session, accountKey, accountId, ws);
|
|
1095
|
+
|
|
1096
|
+
const cookiesToRestore = Array.isArray(launchOpts.cookies) ? launchOpts.cookies
|
|
1097
|
+
: (Array.isArray(params.cookies) ? params.cookies : null);
|
|
1098
|
+
let restore;
|
|
1099
|
+
try {
|
|
1100
|
+
restore = await sessionAuth.restoreAndVerify({
|
|
1101
|
+
page,
|
|
1102
|
+
context,
|
|
1103
|
+
cookies: cookiesToRestore,
|
|
1104
|
+
url: params.url || launchOpts.url || null,
|
|
1105
|
+
expectedUsername,
|
|
1106
|
+
applyCookies,
|
|
1107
|
+
navigationTimeoutMs: 45000,
|
|
1108
|
+
verifyTimeoutMs: 8000,
|
|
1109
|
+
});
|
|
1110
|
+
} catch (err) {
|
|
1111
|
+
restore = {
|
|
1112
|
+
authState: sessionAuth.AUTH_STATE.UNKNOWN,
|
|
1113
|
+
reason: 'startup_verification_failed',
|
|
1114
|
+
stage: 'verify',
|
|
1115
|
+
browserReady: true,
|
|
1116
|
+
};
|
|
1117
|
+
}
|
|
1118
|
+
session.lastAuth = restore;
|
|
1119
|
+
|
|
1120
|
+
// A startup navigation that never completed must not leave the visible tab on
|
|
1121
|
+
// about:blank with a permanent spinner: paint the actionable diagnostic page.
|
|
1122
|
+
if (restore && restore.navigationOk === false) {
|
|
1123
|
+
try {
|
|
1124
|
+
const failure = connectivity.classifyNavigationFailure(
|
|
1125
|
+
Object.assign(new Error(restore.reason || 'navigation failed'), { code: restore.code }),
|
|
1126
|
+
{ url: params.url || launchOpts.url || 'https://x.com/home', proxyActive: !!proxyBinding.proxyOption, dnsPinned: requireProxy && !!proxyIdentity },
|
|
1127
|
+
);
|
|
1128
|
+
await connectivity.paintNavigationFailure(page, {
|
|
1129
|
+
...failure,
|
|
1130
|
+
url: params.url || launchOpts.url || 'https://x.com/home',
|
|
1131
|
+
accountLabel: resolvedAccountUuid || accountKey,
|
|
1132
|
+
});
|
|
1133
|
+
} catch { /* containment is best effort */ }
|
|
1134
|
+
}
|
|
946
1135
|
|
|
947
1136
|
// If the browser launched but immediately closed, report a clear error
|
|
948
1137
|
// instead of showing a misleading green "browser opened" toast.
|
|
@@ -951,6 +1140,8 @@ async function _startSessionLocked(params, opts, accountKey, accountId, accountU
|
|
|
951
1140
|
return {
|
|
952
1141
|
success: false,
|
|
953
1142
|
error: 'Browser launched but closed immediately. The session was not started.',
|
|
1143
|
+
stage: 'launch',
|
|
1144
|
+
reason: 'browser_closed_during_startup',
|
|
954
1145
|
};
|
|
955
1146
|
}
|
|
956
1147
|
|
|
@@ -987,23 +1178,6 @@ async function _startSessionLocked(params, opts, accountKey, accountId, accountU
|
|
|
987
1178
|
};
|
|
988
1179
|
}
|
|
989
1180
|
|
|
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
1181
|
// ── Lease-bound session-status reporting (Phase 3 parity with v1) ──────────
|
|
1008
1182
|
// The server's session cache (`agent.sessions`) and the durable lease TTL
|
|
1009
1183
|
// are ONLY updated by lease-bound `session-status` frames — never by the
|
|
@@ -1016,13 +1190,6 @@ async function _startSessionLocked(params, opts, accountKey, accountId, accountU
|
|
|
1016
1190
|
};
|
|
1017
1191
|
_sendStatus('running');
|
|
1018
1192
|
|
|
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
1193
|
// Return confirmed success metadata. The backend/frontend uses this to
|
|
1027
1194
|
// show a green toast ONLY when the browser is genuinely started and visible.
|
|
1028
1195
|
//
|
|
@@ -1037,6 +1204,7 @@ async function _startSessionLocked(params, opts, accountKey, accountId, accountU
|
|
|
1037
1204
|
// If the Windows foreground helper cannot prove the window is visible
|
|
1038
1205
|
// (foregroundVerified = false), we return started:true but visible:false
|
|
1039
1206
|
// with an actionable error so the frontend does NOT show a green toast.
|
|
1207
|
+
const auth = sessionAuth.authSummary(restore);
|
|
1040
1208
|
if (os.platform() === 'win32' && !foregroundVerified) {
|
|
1041
1209
|
// The browser launched and bringToFront succeeded, but we could not
|
|
1042
1210
|
// positively verify the window is in the foreground. Return a safe
|
|
@@ -1047,6 +1215,14 @@ async function _startSessionLocked(params, opts, accountKey, accountId, accountU
|
|
|
1047
1215
|
started: true,
|
|
1048
1216
|
visible: false,
|
|
1049
1217
|
sessionId: accountId,
|
|
1218
|
+
browserReady: true,
|
|
1219
|
+
authState: auth.authState,
|
|
1220
|
+
loggedIn: auth.loggedIn,
|
|
1221
|
+
reason: auth.reason,
|
|
1222
|
+
stage: auth.stage,
|
|
1223
|
+
handle: auth.handle,
|
|
1224
|
+
cookieState: restore.cookieState || null,
|
|
1225
|
+
code: restore.code || null,
|
|
1050
1226
|
error: 'Browser launched but could not be confirmed in the foreground. Check the taskbar for the Chrome window.',
|
|
1051
1227
|
};
|
|
1052
1228
|
}
|
|
@@ -1057,6 +1233,14 @@ async function _startSessionLocked(params, opts, accountKey, accountId, accountU
|
|
|
1057
1233
|
started: true,
|
|
1058
1234
|
visible: true,
|
|
1059
1235
|
sessionId: accountId,
|
|
1236
|
+
browserReady: true,
|
|
1237
|
+
authState: auth.authState,
|
|
1238
|
+
loggedIn: auth.loggedIn,
|
|
1239
|
+
reason: auth.reason,
|
|
1240
|
+
stage: auth.stage,
|
|
1241
|
+
handle: auth.handle,
|
|
1242
|
+
cookieState: restore.cookieState || null,
|
|
1243
|
+
code: restore.code || null,
|
|
1060
1244
|
};
|
|
1061
1245
|
}
|
|
1062
1246
|
|
|
@@ -1079,6 +1263,7 @@ function _attachContextCloseReporter(context, session, accountKey, accountId, ws
|
|
|
1079
1263
|
const closed = activeSessions.get(accountKey);
|
|
1080
1264
|
if (closed && closed !== session) return;
|
|
1081
1265
|
if (closed === session) activeSessions.delete(accountKey);
|
|
1266
|
+
try { if (session.navGuard) session.navGuard.stop(); } catch { /* safe */ }
|
|
1082
1267
|
// The browser is ALREADY closed; mark it so the release path does not try to
|
|
1083
1268
|
// close it again (which could recurse on a synchronously-emitting context).
|
|
1084
1269
|
session._closeInitiated = true;
|
|
@@ -1169,12 +1354,16 @@ async function _releaseLocalSessionResources(session) {
|
|
|
1169
1354
|
*/
|
|
1170
1355
|
function _reportStoppedOnce(session, accountId, ws) {
|
|
1171
1356
|
if (!session || session._stopReported) return false;
|
|
1357
|
+
// A restart stops the old browser and starts a new one under the SAME inbound
|
|
1358
|
+
// lease. A lease-bound `stopped` frame would release that lease before the
|
|
1359
|
+
// restart can re-activate it, so the restart path suppresses it deliberately.
|
|
1360
|
+
if (session._suppressStopReport) return false;
|
|
1172
1361
|
session._stopReported = true;
|
|
1173
1362
|
try { ws.send(JSON.stringify(leaseClient.boundStatusMessage(session, accountId, 'stopped'))); } catch {}
|
|
1174
1363
|
return true;
|
|
1175
1364
|
}
|
|
1176
1365
|
|
|
1177
|
-
async function _stopSession(accountId, lease, ws, opts) {
|
|
1366
|
+
async function _stopSession(accountId, lease, ws, opts, controls = {}) {
|
|
1178
1367
|
// Account keys are stored as String(accountId) — normalize every lookup so a
|
|
1179
1368
|
// number/string mismatch can never make a LIVE session invisible (which would
|
|
1180
1369
|
// make a stop silently no-op and leave the browser running past its lease).
|
|
@@ -1200,12 +1389,25 @@ async function _stopSession(accountId, lease, ws, opts) {
|
|
|
1200
1389
|
// which releases the local resources and reports the verified stop. To make
|
|
1201
1390
|
// the ack TRUTHFUL (never claimed before local resources are gone), we run the
|
|
1202
1391
|
// release explicitly here and only then emit the ack.
|
|
1392
|
+
if (controls.suppressStopReport) session._suppressStopReport = true;
|
|
1203
1393
|
if (session.viaWorker && opts && opts.workerBridge && typeof opts.workerBridge.call === 'function') {
|
|
1204
|
-
// The browser belongs to the interactive worker: ask it to stop
|
|
1205
|
-
// the
|
|
1394
|
+
// The browser belongs to the interactive worker: ask it to stop and only ack
|
|
1395
|
+
// after the worker CONFIRMS the real browser closed. A thrown/timed-out
|
|
1396
|
+
// worker call must not be reported as a successful stop.
|
|
1397
|
+
let workerRes;
|
|
1206
1398
|
try {
|
|
1207
|
-
await opts.workerBridge.call('stopSession', { accountUuid: session.accountUuid || null, accountId: session.accountId },
|
|
1208
|
-
} catch {
|
|
1399
|
+
workerRes = await opts.workerBridge.call('stopSession', { accountUuid: session.accountUuid || null, accountId: session.accountId }, 45000);
|
|
1400
|
+
} catch (err) {
|
|
1401
|
+
return {
|
|
1402
|
+
success: false,
|
|
1403
|
+
code: (err && err.code) || 'WORKER_STOP_UNVERIFIED',
|
|
1404
|
+
stage: 'stop',
|
|
1405
|
+
error: 'The interactive worker did not confirm the browser closed; the session is still tracked locally.',
|
|
1406
|
+
};
|
|
1407
|
+
}
|
|
1408
|
+
if (!workerRes || workerRes.stopped !== true) {
|
|
1409
|
+
return { success: false, code: 'WORKER_STOP_UNVERIFIED', stage: 'stop', error: 'The interactive worker did not confirm the browser closed.' };
|
|
1410
|
+
}
|
|
1209
1411
|
activeSessions.delete(accountKey);
|
|
1210
1412
|
if (ws) _reportStoppedOnce(session, accountId, ws);
|
|
1211
1413
|
return { success: true, accountId, stopped: true, viaWorker: true };
|
|
@@ -1257,51 +1459,225 @@ async function _stopOrphanedLocalSession(accountKey) {
|
|
|
1257
1459
|
}
|
|
1258
1460
|
}
|
|
1259
1461
|
|
|
1260
|
-
|
|
1462
|
+
/**
|
|
1463
|
+
* Route a typed browser command to the process that OWNS the page.
|
|
1464
|
+
*
|
|
1465
|
+
* The broker records worker-owned sessions with `page: null`; using the
|
|
1466
|
+
* broker-local page there was always wrong. This helper is the single bridge
|
|
1467
|
+
* between the broker's command surface and the worker's typed surface. An old
|
|
1468
|
+
* worker that does not understand a command is surfaced as an explicit
|
|
1469
|
+
* UNSUPPORTED_CAPABILITY (never silently treated as success).
|
|
1470
|
+
*/
|
|
1471
|
+
async function _workerCall(session, opts, command, payload, timeoutMs) {
|
|
1472
|
+
const bridge = opts && opts.workerBridge;
|
|
1473
|
+
if (!bridge || typeof bridge.call !== 'function') {
|
|
1474
|
+
return { success: false, code: 'UNSUPPORTED_CAPABILITY', stage: 'worker_bridge', error: 'No interactive worker bridge is available for this session.' };
|
|
1475
|
+
}
|
|
1476
|
+
try {
|
|
1477
|
+
return await bridge.call(command, payload, timeoutMs || 120000);
|
|
1478
|
+
} catch (err) {
|
|
1479
|
+
const code = (err && err.code) || 'WORKER_CALL_FAILED';
|
|
1480
|
+
if (code === 'UNKNOWN_COMMAND' || code === 'WORKER_UNSUPPORTED') {
|
|
1481
|
+
return {
|
|
1482
|
+
success: false,
|
|
1483
|
+
code: 'UNSUPPORTED_CAPABILITY',
|
|
1484
|
+
stage: 'worker_bridge',
|
|
1485
|
+
capability: command,
|
|
1486
|
+
error: `The connected agent build does not support the '${command}' browser command. Update the agent on this device.`,
|
|
1487
|
+
};
|
|
1488
|
+
}
|
|
1489
|
+
return {
|
|
1490
|
+
success: false,
|
|
1491
|
+
code,
|
|
1492
|
+
stage: (err && err.stage) || null,
|
|
1493
|
+
reason: (err && err.reason) || null,
|
|
1494
|
+
authState: (err && err.authState) || null,
|
|
1495
|
+
error: _safeError(err),
|
|
1496
|
+
};
|
|
1497
|
+
}
|
|
1498
|
+
}
|
|
1499
|
+
|
|
1500
|
+
async function _checkAuth(accountId, opts) {
|
|
1261
1501
|
const session = activeSessions.get(String(accountId));
|
|
1262
|
-
if (!session)
|
|
1263
|
-
|
|
1264
|
-
|
|
1502
|
+
if (!session) {
|
|
1503
|
+
return {
|
|
1504
|
+
success: true, browserReady: false, authState: sessionAuth.AUTH_STATE.UNKNOWN,
|
|
1505
|
+
loggedIn: false, state: 'no_browser', reason: 'no_browser', stage: 'status',
|
|
1506
|
+
};
|
|
1507
|
+
}
|
|
1508
|
+
if (session.viaWorker) {
|
|
1509
|
+
const res = await _workerCall(session, opts, 'checkAuth', { accountId: session.accountId, accountUuid: session.accountUuid }, 30000);
|
|
1510
|
+
if (res && res.authState) session.lastAuth = res;
|
|
1511
|
+
return res;
|
|
1512
|
+
}
|
|
1513
|
+
const verified = await sessionAuth.verifyXAuth(session.page, session.context, {
|
|
1514
|
+
expectedUsername: session.expectedUsername,
|
|
1515
|
+
timeoutMs: 5000,
|
|
1516
|
+
});
|
|
1517
|
+
session.lastAuth = verified;
|
|
1518
|
+
return { success: true, browserReady: true, ...sessionAuth.authSummary(verified) };
|
|
1265
1519
|
}
|
|
1266
1520
|
|
|
1267
|
-
async function
|
|
1521
|
+
async function _refreshSession(accountId, opts) {
|
|
1268
1522
|
const session = activeSessions.get(String(accountId));
|
|
1269
|
-
if (!session)
|
|
1270
|
-
|
|
1271
|
-
|
|
1523
|
+
if (!session) {
|
|
1524
|
+
return {
|
|
1525
|
+
success: false, code: 'SESSION_NOT_FOUND', browserReady: false,
|
|
1526
|
+
authState: sessionAuth.AUTH_STATE.UNKNOWN, reason: 'no_browser',
|
|
1527
|
+
};
|
|
1528
|
+
}
|
|
1529
|
+
if (session.viaWorker) {
|
|
1530
|
+
const res = await _workerCall(session, opts, 'refreshSession', { accountId: session.accountId, accountUuid: session.accountUuid }, 60000);
|
|
1531
|
+
if (res && res.authState) session.lastAuth = res;
|
|
1532
|
+
return res;
|
|
1533
|
+
}
|
|
1534
|
+
// Bounded refresh: a stalled reload must not leave the visible tab blank.
|
|
1535
|
+
let current = '';
|
|
1536
|
+
try { current = session.page.url(); } catch { current = ''; }
|
|
1537
|
+
const target = sessionAuth.isAuthorizedXUrl(current) ? current : 'https://x.com/home';
|
|
1538
|
+
const nav = await connectivity.navigateBounded(session.page, target, {
|
|
1539
|
+
timeoutMs: 30000,
|
|
1540
|
+
proxyActive: !!session.proxyIdentity,
|
|
1541
|
+
dnsPinned: !!session.proxyIdentity,
|
|
1542
|
+
accountLabel: session.accountUuid || session.accountId,
|
|
1543
|
+
});
|
|
1544
|
+
const verified = await sessionAuth.verifyXAuth(session.page, session.context, {
|
|
1545
|
+
expectedUsername: session.expectedUsername,
|
|
1546
|
+
timeoutMs: 5000,
|
|
1547
|
+
});
|
|
1548
|
+
session.lastAuth = verified;
|
|
1549
|
+
return {
|
|
1550
|
+
success: nav.ok,
|
|
1551
|
+
browserReady: true,
|
|
1552
|
+
...(nav.ok ? {} : { code: nav.code, stage: nav.stage, reason: nav.reason, error: nav.message, painted: nav.painted === true }),
|
|
1553
|
+
...sessionAuth.authSummary(verified),
|
|
1554
|
+
};
|
|
1555
|
+
}
|
|
1556
|
+
|
|
1557
|
+
async function _navigate(accountId, url, opts) {
|
|
1558
|
+
const session = activeSessions.get(String(accountId));
|
|
1559
|
+
if (!session) return { success: false, error: 'Session not found', code: 'SESSION_NOT_FOUND' };
|
|
1560
|
+
if (!sessionAuth.isAuthorizedXUrl(url)) {
|
|
1561
|
+
return { success: false, code: 'NAVIGATION_TARGET_REFUSED', stage: 'navigation', error: 'Navigation target is not an authorized X origin.' };
|
|
1562
|
+
}
|
|
1563
|
+
if (session.viaWorker) {
|
|
1564
|
+
return _workerCall(session, opts, 'navigate', { accountId: session.accountId, accountUuid: session.accountUuid, url }, 60000);
|
|
1565
|
+
}
|
|
1566
|
+
const nav = await connectivity.navigateBounded(session.page, url, {
|
|
1567
|
+
timeoutMs: 45000,
|
|
1568
|
+
proxyActive: !!session.proxyIdentity,
|
|
1569
|
+
dnsPinned: !!session.proxyIdentity,
|
|
1570
|
+
accountLabel: session.accountUuid || session.accountId,
|
|
1571
|
+
});
|
|
1572
|
+
if (nav.ok) return { success: true };
|
|
1573
|
+
return {
|
|
1574
|
+
success: false,
|
|
1575
|
+
code: nav.code,
|
|
1576
|
+
stage: nav.stage,
|
|
1577
|
+
reason: nav.reason,
|
|
1578
|
+
error: nav.message,
|
|
1579
|
+
painted: nav.painted === true,
|
|
1580
|
+
};
|
|
1272
1581
|
}
|
|
1273
1582
|
|
|
1274
|
-
async function _typeText(accountId, selector, text) {
|
|
1583
|
+
async function _typeText(accountId, selector, text, opts) {
|
|
1275
1584
|
const session = activeSessions.get(String(accountId));
|
|
1276
|
-
if (!session) return { success: false, error: 'Session not found' };
|
|
1585
|
+
if (!session) return { success: false, error: 'Session not found', code: 'SESSION_NOT_FOUND' };
|
|
1586
|
+
if (session.viaWorker) {
|
|
1587
|
+
return _workerCall(session, opts, 'type', { accountId: session.accountId, accountUuid: session.accountUuid, selector, text }, 60000);
|
|
1588
|
+
}
|
|
1277
1589
|
await session.page.locator(selector).fill(text);
|
|
1278
1590
|
return { success: true };
|
|
1279
1591
|
}
|
|
1280
1592
|
|
|
1281
|
-
async function _pressKey(accountId, key) {
|
|
1593
|
+
async function _pressKey(accountId, key, opts) {
|
|
1282
1594
|
const session = activeSessions.get(String(accountId));
|
|
1283
|
-
if (!session) return { success: false, error: 'Session not found' };
|
|
1595
|
+
if (!session) return { success: false, error: 'Session not found', code: 'SESSION_NOT_FOUND' };
|
|
1596
|
+
if (session.viaWorker) {
|
|
1597
|
+
return _workerCall(session, opts, 'press', { accountId: session.accountId, accountUuid: session.accountUuid, key }, 60000);
|
|
1598
|
+
}
|
|
1284
1599
|
await session.page.keyboard.press(key);
|
|
1285
1600
|
return { success: true };
|
|
1286
1601
|
}
|
|
1287
1602
|
|
|
1288
|
-
async function _click(accountId, selector) {
|
|
1603
|
+
async function _click(accountId, selector, opts) {
|
|
1289
1604
|
const session = activeSessions.get(String(accountId));
|
|
1290
|
-
if (!session) return { success: false, error: 'Session not found' };
|
|
1605
|
+
if (!session) return { success: false, error: 'Session not found', code: 'SESSION_NOT_FOUND' };
|
|
1606
|
+
if (session.viaWorker) {
|
|
1607
|
+
return _workerCall(session, opts, 'click', { accountId: session.accountId, accountUuid: session.accountUuid, selector }, 60000);
|
|
1608
|
+
}
|
|
1291
1609
|
await session.page.locator(selector).click();
|
|
1292
1610
|
return { success: true };
|
|
1293
1611
|
}
|
|
1294
1612
|
|
|
1295
|
-
async function _focusSession(accountId) {
|
|
1613
|
+
async function _focusSession(accountId, opts) {
|
|
1296
1614
|
const session = activeSessions.get(String(accountId));
|
|
1297
|
-
if (!session) return { success: false, error: 'Session not found' };
|
|
1615
|
+
if (!session) return { success: false, error: 'Session not found', code: 'SESSION_NOT_FOUND' };
|
|
1616
|
+
if (session.viaWorker) {
|
|
1617
|
+
return _workerCall(session, opts, 'focus', { accountId: session.accountId, accountUuid: session.accountUuid }, 30000);
|
|
1618
|
+
}
|
|
1298
1619
|
await session.page.bringToFront();
|
|
1299
1620
|
return { success: true };
|
|
1300
1621
|
}
|
|
1301
1622
|
|
|
1302
|
-
|
|
1623
|
+
// Actions that may run while signed out (they diagnose or perform the login).
|
|
1624
|
+
const AUTH_EXEMPT_ACTIONS = new Set([
|
|
1625
|
+
'autoLogin', 'checkLoginState', 'checkStatus', 'humanResume', 'connectAutomation',
|
|
1626
|
+
]);
|
|
1627
|
+
|
|
1628
|
+
/**
|
|
1629
|
+
* Return {ok:true} only when the live session is verified signed in. Definite
|
|
1630
|
+
* failures (signed_out / wrong_account / challenge_required) and observed
|
|
1631
|
+
* unknown states block the action BEFORE any side effect. The "no_browser_signal"
|
|
1632
|
+
* unknown (a test/legacy page without DOM access) is not treated as evidence.
|
|
1633
|
+
*/
|
|
1634
|
+
async function _authPreflight(session) {
|
|
1635
|
+
const verified = await sessionAuth.verifyXAuth(session.page, session.context, {
|
|
1636
|
+
expectedUsername: session.expectedUsername,
|
|
1637
|
+
timeoutMs: 4000,
|
|
1638
|
+
});
|
|
1639
|
+
session.lastAuth = verified;
|
|
1640
|
+
const s = verified.authState;
|
|
1641
|
+
const definite = s === sessionAuth.AUTH_STATE.SIGNED_OUT
|
|
1642
|
+
|| s === sessionAuth.AUTH_STATE.WRONG_ACCOUNT
|
|
1643
|
+
|| s === sessionAuth.AUTH_STATE.CHALLENGE_REQUIRED;
|
|
1644
|
+
const observedUnknown = s === sessionAuth.AUTH_STATE.UNKNOWN && verified.reason !== 'no_browser_signal';
|
|
1645
|
+
if (definite || observedUnknown) {
|
|
1646
|
+
return { ok: false, verified, code: 'AUTH_UNVERIFIED' };
|
|
1647
|
+
}
|
|
1648
|
+
return { ok: true, verified };
|
|
1649
|
+
}
|
|
1650
|
+
|
|
1651
|
+
async function _runAction(accountId, action, payload, opts) {
|
|
1303
1652
|
const session = activeSessions.get(String(accountId));
|
|
1304
|
-
if (!session) return { success: false, error: 'Session not found' };
|
|
1653
|
+
if (!session) return { success: false, error: 'Session not found', code: 'SESSION_NOT_FOUND' };
|
|
1654
|
+
// The worker owns the page; it performs the same preflight and the action in
|
|
1655
|
+
// one process, so no script/page crosses the bridge.
|
|
1656
|
+
if (session.viaWorker) {
|
|
1657
|
+
return _workerCall(session, opts, 'runAction', {
|
|
1658
|
+
accountId: session.accountId,
|
|
1659
|
+
accountUuid: session.accountUuid,
|
|
1660
|
+
action,
|
|
1661
|
+
payload: payload || {},
|
|
1662
|
+
}, 300000);
|
|
1663
|
+
}
|
|
1664
|
+
if (!AUTH_EXEMPT_ACTIONS.has(action)) {
|
|
1665
|
+
const gate = await _authPreflight(session);
|
|
1666
|
+
if (!gate.ok) {
|
|
1667
|
+
const a = gate.verified.authState;
|
|
1668
|
+
const code = a === sessionAuth.AUTH_STATE.WRONG_ACCOUNT ? 'WRONG_ACCOUNT'
|
|
1669
|
+
: a === sessionAuth.AUTH_STATE.CHALLENGE_REQUIRED ? 'CHALLENGE_REQUIRED'
|
|
1670
|
+
: 'AUTH_UNVERIFIED';
|
|
1671
|
+
return {
|
|
1672
|
+
success: false,
|
|
1673
|
+
code,
|
|
1674
|
+
error: 'The X session is not verified as signed in; the action was not started.',
|
|
1675
|
+
failureStage: 'pre_action',
|
|
1676
|
+
browserReady: true,
|
|
1677
|
+
...sessionAuth.authSummary(gate.verified),
|
|
1678
|
+
};
|
|
1679
|
+
}
|
|
1680
|
+
}
|
|
1305
1681
|
const { runAction } = require('./actions');
|
|
1306
1682
|
// Return the ACTION result at the TOP level. The server places this value in
|
|
1307
1683
|
// the command-response `result` field and reads success/code/outcome/
|
|
@@ -1312,15 +1688,82 @@ async function _runAction(accountId, action, payload) {
|
|
|
1312
1688
|
return await runAction(session.page, action, payload || {});
|
|
1313
1689
|
}
|
|
1314
1690
|
|
|
1315
|
-
function _getStatus(accountId) {
|
|
1691
|
+
async function _getStatus(accountId, opts) {
|
|
1316
1692
|
const key = String(accountId || '');
|
|
1317
1693
|
const session = key ? activeSessions.get(key) : null;
|
|
1318
|
-
if (session
|
|
1319
|
-
|
|
1320
|
-
|
|
1321
|
-
|
|
1694
|
+
if (!session) {
|
|
1695
|
+
// Explicit no-browser state. A status check must never open a window.
|
|
1696
|
+
return {
|
|
1697
|
+
success: true,
|
|
1698
|
+
status: 'stopped',
|
|
1699
|
+
accountId: key || null,
|
|
1700
|
+
url: null,
|
|
1701
|
+
browserReady: false,
|
|
1702
|
+
authState: sessionAuth.AUTH_STATE.UNKNOWN,
|
|
1703
|
+
loggedIn: false,
|
|
1704
|
+
state: 'no_browser',
|
|
1705
|
+
reason: 'no_browser',
|
|
1706
|
+
stage: 'status',
|
|
1707
|
+
};
|
|
1322
1708
|
}
|
|
1323
|
-
|
|
1709
|
+
if (session.viaWorker) {
|
|
1710
|
+
const res = await _workerCall(session, opts, 'getStatus', { accountId: session.accountId, accountUuid: session.accountUuid }, 15000);
|
|
1711
|
+
if (res && res.running === false) {
|
|
1712
|
+
return {
|
|
1713
|
+
success: true, status: 'stopped', accountId: key, url: null,
|
|
1714
|
+
browserReady: false, authState: sessionAuth.AUTH_STATE.UNKNOWN, loggedIn: false,
|
|
1715
|
+
state: 'no_browser', reason: res.reason || 'no_browser', stage: 'status',
|
|
1716
|
+
};
|
|
1717
|
+
}
|
|
1718
|
+
if (res && res.success === false) {
|
|
1719
|
+
return {
|
|
1720
|
+
success: true, status: 'running', accountId: key, url: null,
|
|
1721
|
+
browserReady: true, authState: sessionAuth.AUTH_STATE.UNKNOWN, loggedIn: false,
|
|
1722
|
+
code: res.code || 'STATUS_UNVERIFIED', reason: res.reason || 'worker_status_unavailable',
|
|
1723
|
+
unsupported: res.code === 'UNSUPPORTED_CAPABILITY' ? ['getStatus'] : undefined,
|
|
1724
|
+
};
|
|
1725
|
+
}
|
|
1726
|
+
const auth = res || {};
|
|
1727
|
+
return {
|
|
1728
|
+
success: true,
|
|
1729
|
+
status: 'running',
|
|
1730
|
+
accountId: key,
|
|
1731
|
+
url: auth.url || null,
|
|
1732
|
+
pageStalled: auth.pageStalled === true || auth.url === 'about:blank',
|
|
1733
|
+
browserReady: true,
|
|
1734
|
+
authState: auth.authState || sessionAuth.AUTH_STATE.UNKNOWN,
|
|
1735
|
+
loggedIn: auth.authState === sessionAuth.AUTH_STATE.AUTHENTICATED,
|
|
1736
|
+
reason: auth.reason || null,
|
|
1737
|
+
stage: auth.stage || 'status',
|
|
1738
|
+
handle: auth.handle || null,
|
|
1739
|
+
browser: auth.browser || null,
|
|
1740
|
+
connectivity: auth.connectivity || null,
|
|
1741
|
+
};
|
|
1742
|
+
}
|
|
1743
|
+
let url = null;
|
|
1744
|
+
try { url = session.page && !session.page.isClosed() ? session.page.url() : null; } catch { url = null; }
|
|
1745
|
+
const auth = sessionAuth.authSummary(session.lastAuth || {
|
|
1746
|
+
authState: sessionAuth.AUTH_STATE.UNKNOWN, reason: 'not_checked', browserReady: true,
|
|
1747
|
+
});
|
|
1748
|
+
return {
|
|
1749
|
+
success: true,
|
|
1750
|
+
status: 'running',
|
|
1751
|
+
accountId: key,
|
|
1752
|
+
url,
|
|
1753
|
+
// A tab parked on about:blank is never a healthy state; surface it so the UI
|
|
1754
|
+
// can offer the connectivity diagnostic instead of silently showing a spinner.
|
|
1755
|
+
pageStalled: url === 'about:blank',
|
|
1756
|
+
browserReady: true,
|
|
1757
|
+
authState: auth.authState,
|
|
1758
|
+
loggedIn: auth.loggedIn,
|
|
1759
|
+
reason: auth.reason,
|
|
1760
|
+
stage: auth.stage,
|
|
1761
|
+
handle: auth.handle,
|
|
1762
|
+
browser: browserLaunch.describeBrowser(opts && opts.chromePath),
|
|
1763
|
+
connectivity: session.navGuard
|
|
1764
|
+
? { guard: session.navGuard.options, stalledPainted: session.navGuard.stats.painted }
|
|
1765
|
+
: null,
|
|
1766
|
+
};
|
|
1324
1767
|
}
|
|
1325
1768
|
|
|
1326
1769
|
function _importLegacyProfile(accountId, accountUuid, opts) {
|
|
@@ -1372,11 +1815,32 @@ async function _proxyTest(params) {
|
|
|
1372
1815
|
const requireProxy = proxyRequiredForSession({ proxyStr, networkMode });
|
|
1373
1816
|
const proxyObj = { server: ident.server, username: ident.username, password: ident.password };
|
|
1374
1817
|
|
|
1818
|
+
// ── Capability-based health (2.1.5) ────────────────────────────────────────
|
|
1819
|
+
// A single ipify response is NOT proof a proxy is usable for the operator's
|
|
1820
|
+
// destinations. Assess every managed destination (bounded, cached, rate
|
|
1821
|
+
// limited) so a proxy that works for X but denies Google is reported as
|
|
1822
|
+
// DESTINATION_RESTRICTED instead of "reachable".
|
|
1823
|
+
const proxyCapability = require('./proxyCapability');
|
|
1824
|
+
let capability = null;
|
|
1825
|
+
try {
|
|
1826
|
+
const report = await proxyCapability.assessProxyHealth({
|
|
1827
|
+
proxy: proxyObj,
|
|
1828
|
+
bypassCache: params && params.refresh === true,
|
|
1829
|
+
});
|
|
1830
|
+
capability = proxyCapability.summarizeProxyHealth(report);
|
|
1831
|
+
} catch (e) {
|
|
1832
|
+
capability = {
|
|
1833
|
+
state: proxyCapability.PROXY_HEALTH_STATES.UNKNOWN,
|
|
1834
|
+
destinations: [],
|
|
1835
|
+
action: 'The proxy capability assessment could not be completed.',
|
|
1836
|
+
};
|
|
1837
|
+
}
|
|
1838
|
+
|
|
1375
1839
|
let iso;
|
|
1376
1840
|
try {
|
|
1377
1841
|
iso = await require('./proxyEgress').verifyProxyIsolation(proxyObj, {});
|
|
1378
1842
|
} catch (e) {
|
|
1379
|
-
|
|
1843
|
+
iso = { ok: false, code: (e && e.code) || 'PROXY_EGRESS_UNREACHABLE' };
|
|
1380
1844
|
}
|
|
1381
1845
|
|
|
1382
1846
|
if (!iso || !iso.ok) {
|
|
@@ -1398,25 +1862,161 @@ async function _proxyTest(params) {
|
|
|
1398
1862
|
return {
|
|
1399
1863
|
success: false,
|
|
1400
1864
|
code,
|
|
1865
|
+
healthCode: capability ? capabilityCodeForState(capability.state) : code,
|
|
1866
|
+
state: capability ? capability.state : null,
|
|
1401
1867
|
stage: 'egress',
|
|
1402
1868
|
protocol: ident.type, host: ident.host, port: ident.port,
|
|
1403
1869
|
detail: (iso && iso.reason) ? String(iso.reason).slice(0, 200) : null,
|
|
1870
|
+
capability,
|
|
1404
1871
|
timestamp: new Date().toISOString(),
|
|
1405
1872
|
};
|
|
1406
1873
|
}
|
|
1407
1874
|
|
|
1875
|
+
const capabilityOk = capability && capability.state === proxyCapability.PROXY_HEALTH_STATES.HEALTHY;
|
|
1876
|
+
// Backward-compatible success code for existing API/UI consumers; the richer
|
|
1877
|
+
// state is exposed separately (`state`, `healthCode`, `capability`).
|
|
1408
1878
|
return {
|
|
1409
|
-
success:
|
|
1410
|
-
code: 'PROXY_ISOLATION_OK',
|
|
1411
|
-
|
|
1879
|
+
success: capabilityOk,
|
|
1880
|
+
code: capabilityOk ? 'PROXY_ISOLATION_OK' : (capabilityCodeForState(capability.state)),
|
|
1881
|
+
healthCode: capabilityOk ? 'PROXY_HEALTHY' : capabilityCodeForState(capability.state),
|
|
1882
|
+
state: capability.state,
|
|
1883
|
+
stage: 'capability',
|
|
1884
|
+
isolationCode: 'PROXY_ISOLATION_OK',
|
|
1412
1885
|
latencyMs: Date.now() - started,
|
|
1413
1886
|
egressIp: iso.egressIp || null,
|
|
1414
1887
|
directIp: iso.directIp || null,
|
|
1415
1888
|
protocol: ident.type,
|
|
1416
1889
|
host: ident.host,
|
|
1417
1890
|
port: ident.port,
|
|
1891
|
+
capability,
|
|
1892
|
+
action: capability.action || null,
|
|
1893
|
+
timestamp: new Date().toISOString(),
|
|
1894
|
+
};
|
|
1895
|
+
}
|
|
1896
|
+
|
|
1897
|
+
/**
|
|
1898
|
+
* Map a capability state to a stable API code. `PROXY_AUTH_FAILED` is kept for
|
|
1899
|
+
* the UI's existing auth-failure presentation; every other state gets a
|
|
1900
|
+
* `PROXY_`-prefixed code so consumers can distinguish restriction from timeout.
|
|
1901
|
+
*/
|
|
1902
|
+
function capabilityCodeForState(state) {
|
|
1903
|
+
const cap = require('./proxyCapability');
|
|
1904
|
+
if (state === cap.PROXY_HEALTH_STATES.AUTHENTICATION_FAILED) return 'PROXY_AUTH_FAILED';
|
|
1905
|
+
if (!state) return 'PROXY_UNREACHABLE';
|
|
1906
|
+
return 'PROXY_' + state;
|
|
1907
|
+
}
|
|
1908
|
+
|
|
1909
|
+
/**
|
|
1910
|
+
* Per-endpoint browser connectivity diagnostic + capability assessment (2.1.5).
|
|
1911
|
+
*
|
|
1912
|
+
* Walks the public endpoints the operator actually needs (Google Search, Chrome
|
|
1913
|
+
* Web Store, Google sign-in, gstatic, clients2, update.googleapis.com, X,
|
|
1914
|
+
* example.com, api.ipify.org) with a real DNS/TCP/TLS/HTTP probe. When a proxy is
|
|
1915
|
+
* supplied the probe tunnels THROUGH it (HTTP CONNECT or SOCKS5 + TLS + GET) and
|
|
1916
|
+
* never falls back to a direct connection. The result carries a capability state
|
|
1917
|
+
* so a proxy that works for X but denies Google is reported as
|
|
1918
|
+
* DESTINATION_RESTRICTED instead of "healthy".
|
|
1919
|
+
*
|
|
1920
|
+
* The requested URL list is limited to the documented public allowlist: the
|
|
1921
|
+
* command channel can never be used to probe arbitrary internal hosts (SSRF).
|
|
1922
|
+
*
|
|
1923
|
+
* Sanitized: no credential, cookie or Proxy-Authorization value is returned.
|
|
1924
|
+
*
|
|
1925
|
+
* @param {object} params { proxy?, networkMode?, urls?, timeoutMs?, direct?, refresh? }
|
|
1926
|
+
* @returns {Promise<object>} { success, code, state, proxy, results, capability, ... }
|
|
1927
|
+
*/
|
|
1928
|
+
async function _connectivityTest(params) {
|
|
1929
|
+
const started = Date.now();
|
|
1930
|
+
const proxyStr = params && params.proxy;
|
|
1931
|
+
const timeoutMs = Number.isFinite(params && params.timeoutMs) ? params.timeoutMs : 8000;
|
|
1932
|
+
const proxyCapability = require('./proxyCapability');
|
|
1933
|
+
|
|
1934
|
+
// Destination allowlist (SSRF prevention). Only the documented endpoints may
|
|
1935
|
+
// be probed; anything else is refused, never silently ignored.
|
|
1936
|
+
let urls;
|
|
1937
|
+
if (Array.isArray(params && params.urls) && params.urls.length > 0) {
|
|
1938
|
+
const allowed = new Set(connectivity.CONNECTIVITY_ENDPOINTS);
|
|
1939
|
+
const bad = params.urls.filter((u) => !allowed.has(String(u)));
|
|
1940
|
+
if (bad.length > 0) {
|
|
1941
|
+
return {
|
|
1942
|
+
success: false,
|
|
1943
|
+
code: 'PROBE_TARGET_NOT_ALLOWED',
|
|
1944
|
+
stage: 'validation',
|
|
1945
|
+
error: 'Only the documented public connectivity endpoints may be probed.',
|
|
1946
|
+
timestamp: new Date().toISOString(),
|
|
1947
|
+
};
|
|
1948
|
+
}
|
|
1949
|
+
urls = params.urls.map(String);
|
|
1950
|
+
}
|
|
1951
|
+
|
|
1952
|
+
let proxyObj = null;
|
|
1953
|
+
if (proxyStr) {
|
|
1954
|
+
const ident = parseProxyIdentity(proxyStr);
|
|
1955
|
+
if (!ident) {
|
|
1956
|
+
return { success: false, code: 'PROXY_FORMAT_INVALID', stage: 'parse', timestamp: new Date().toISOString() };
|
|
1957
|
+
}
|
|
1958
|
+
const v = validateProxyConfig(ident);
|
|
1959
|
+
if (!v.ok) {
|
|
1960
|
+
return { success: false, code: v.code, stage: 'validate', timestamp: new Date().toISOString() };
|
|
1961
|
+
}
|
|
1962
|
+
proxyObj = { server: ident.server, username: ident.username, password: ident.password };
|
|
1963
|
+
}
|
|
1964
|
+
|
|
1965
|
+
const out = {
|
|
1966
|
+
success: false,
|
|
1967
|
+
code: 'CONNECTIVITY_OK',
|
|
1968
|
+
stage: 'connectivity',
|
|
1969
|
+
latencyMs: 0,
|
|
1418
1970
|
timestamp: new Date().toISOString(),
|
|
1419
1971
|
};
|
|
1972
|
+
|
|
1973
|
+
if (proxyObj) {
|
|
1974
|
+
// Capability-based assessment: per-destination states + overall state.
|
|
1975
|
+
const report = await proxyCapability.assessProxyHealth({
|
|
1976
|
+
proxy: proxyObj,
|
|
1977
|
+
urls,
|
|
1978
|
+
timeoutMs,
|
|
1979
|
+
bypassCache: params && params.refresh === true,
|
|
1980
|
+
});
|
|
1981
|
+
const summary = proxyCapability.summarizeProxyHealth(report);
|
|
1982
|
+
out.state = summary.state;
|
|
1983
|
+
out.proxy = summary.proxy;
|
|
1984
|
+
out.protocol = summary.protocol;
|
|
1985
|
+
out.protocolSupported = summary.protocolSupported;
|
|
1986
|
+
out.destinations = summary.destinations;
|
|
1987
|
+
out.capability = summary.capability;
|
|
1988
|
+
out.families = summary.families;
|
|
1989
|
+
out.cached = summary.cached;
|
|
1990
|
+
out.rateLimited = summary.rateLimited;
|
|
1991
|
+
out.retryAfterMs = summary.retryAfterMs;
|
|
1992
|
+
out.action = summary.action;
|
|
1993
|
+
out.summary = { total: summary.destinations.length, healthy: (report.summary || {}).healthy || 0, failed: (report.summary || {}).failed || 0, restricted: (report.summary || {}).restricted || 0 };
|
|
1994
|
+
out.code = summary.state;
|
|
1995
|
+
out.success = summary.state === proxyCapability.PROXY_HEALTH_STATES.HEALTHY;
|
|
1996
|
+
} else {
|
|
1997
|
+
const report = await connectivity.probeConnectivity({ proxy: null, urls, timeoutMs });
|
|
1998
|
+
out.proxy = report.proxy;
|
|
1999
|
+
out.results = report.results.map((r) => ({
|
|
2000
|
+
url: r.url, host: r.host, ok: r.ok, status: r.status, ms: r.ms,
|
|
2001
|
+
dnsMs: r.dnsMs, connectMs: r.connectMs, tlsMs: r.tlsMs, code: r.code, redirectTo: r.redirectTo,
|
|
2002
|
+
}));
|
|
2003
|
+
out.summary = report.summary;
|
|
2004
|
+
out.code = report.summary.failed === 0 ? 'CONNECTIVITY_OK' : 'CONNECTIVITY_PARTIAL';
|
|
2005
|
+
out.success = report.summary.failed === 0;
|
|
2006
|
+
}
|
|
2007
|
+
|
|
2008
|
+
// Optionally compare the device's own direct path. Explicitly opt-in so a
|
|
2009
|
+
// configured proxy is never silently bypassed by routine diagnostics.
|
|
2010
|
+
if (proxyObj && params && params.direct === true) {
|
|
2011
|
+
const direct = await connectivity.probeConnectivity({
|
|
2012
|
+
proxy: null,
|
|
2013
|
+
urls: urls || ['https://example.com', 'https://www.google.com', 'https://x.com'],
|
|
2014
|
+
timeoutMs,
|
|
2015
|
+
});
|
|
2016
|
+
out.direct = { proxy: direct.proxy, summary: direct.summary, results: direct.results };
|
|
2017
|
+
}
|
|
2018
|
+
out.latencyMs = Date.now() - started;
|
|
2019
|
+
return out;
|
|
1420
2020
|
}
|
|
1421
2021
|
|
|
1422
2022
|
// ── Helpers ──────────────────────────────────────────────────────────────────
|
|
@@ -1593,4 +2193,5 @@ module.exports = {
|
|
|
1593
2193
|
_stopOrphanedLocalSession,
|
|
1594
2194
|
recoverOrphanedSessions,
|
|
1595
2195
|
_proxyTest,
|
|
2196
|
+
_connectivityTest,
|
|
1596
2197
|
};
|