@xkwdstore/agent 2.0.7 → 2.1.0

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.
@@ -19,6 +19,8 @@
19
19
 
20
20
  const { chromium } = require('playwright-core');
21
21
  const os = require('os');
22
+ const fs = require('fs');
23
+ const path = require('path');
22
24
 
23
25
  // Import the existing hardened runtime modules (Defect 9).
24
26
  const { generateFingerprint } = require('./fingerprint');
@@ -26,7 +28,22 @@ const fingerprintStore = require('./fingerprintStore');
26
28
  const { resolveProfileDir, importLegacyProfile, discoverLegacyProfiles } = require('./profilePath');
27
29
  const { buildStealthScript } = require('./stealth');
28
30
  const leaseClient = require('./leaseClient');
29
- const { PROFILES_DIR } = require('./deviceKeyStore');
31
+ const { PROFILES_DIR, getMachineRoot } = require('./deviceKeyStore');
32
+ const {
33
+ sanitizeLaunchArgs,
34
+ buildLaunchArgs,
35
+ buildProxyLaunchBinding,
36
+ parseProxyIdentity,
37
+ validateProxyConfig,
38
+ proxyIdentityFingerprint,
39
+ proxyRequiredForSession,
40
+ buildConsistencyPolicy,
41
+ fingerprintConsistencyProblems,
42
+ createSessionRuntimeDirs,
43
+ cleanupSessionRuntimeDirs,
44
+ buildSessionPreferences,
45
+ } = require('./browserIsolation');
46
+ const sessionRegistry = require('./sessionRegistry');
30
47
 
31
48
  // ── Exact-profile Chrome detection (recovery probe) ──────────────────────────
32
49
  //
@@ -210,7 +227,9 @@ async function closeAllSessions() {
210
227
  // Delete BEFORE closing so a concurrent call does not double-close.
211
228
  sessions.delete(accountId);
212
229
  try {
213
- if (session.context) await session.context.close().catch(() => {});
230
+ // Verified cleanup: close the context AND release the local resources
231
+ // (runtime dirs + registry lock) so a shutdown leaves nothing behind.
232
+ await _releaseLocalSessionResources(session);
214
233
  } catch {}
215
234
  closed += 1;
216
235
  }
@@ -415,7 +434,7 @@ async function _handleCommandEnvelope(ws, msg, opts) {
415
434
  'startSession', 'stopSession', 'restartSession', 'refreshSession',
416
435
  'navigate', 'type', 'paste', 'press', 'click', 'runAction',
417
436
  'getStatus', 'importLegacyProfile', 'discoverLegacyProfiles',
418
- 'focus',
437
+ 'focus', 'proxy-test',
419
438
  ]);
420
439
 
421
440
  if (!ALLOWED_TYPES.has(type)) {
@@ -450,9 +469,9 @@ async function _executeCommand(type, params, msg, opts, ws) {
450
469
  case 'startSession':
451
470
  return _startSession(params, opts, accountId, accountUuid, lease, ws);
452
471
  case 'stopSession':
453
- return _stopSession(accountId, lease, ws);
472
+ return _stopSession(accountId, lease, ws, opts);
454
473
  case 'restartSession':
455
- await _stopSession(accountId, lease, ws);
474
+ await _stopSession(accountId, lease, ws, opts);
456
475
  return _startSession(params, opts, accountId, accountUuid, lease, ws);
457
476
  case 'refreshSession':
458
477
  return _refreshSession(accountId);
@@ -480,6 +499,8 @@ async function _executeCommand(type, params, msg, opts, ws) {
480
499
  return _importLegacyProfile(accountId, accountUuid, opts);
481
500
  case 'discoverLegacyProfiles':
482
501
  return _discoverLegacyProfiles();
502
+ case 'proxy-test':
503
+ return _proxyTest(params);
483
504
  default:
484
505
  return { success: false, error: 'Unknown command type' };
485
506
  }
@@ -608,9 +629,59 @@ async function _startSessionLocked(params, opts, accountKey, accountId, accountU
608
629
  error: `PROFILE_IDENTITY_INCOMPLETE: ${(_safeError(err))}`,
609
630
  };
610
631
  }
611
- const fs = require('fs');
612
632
  if (!fs.existsSync(profileDir)) fs.mkdirSync(profileDir, { recursive: true });
613
633
 
634
+ // ── 2.1.0 BROKER/WORKER SPLIT: route browser work to the interactive worker ──
635
+ // When a worker bridge is configured (the machine-wide broker), the BROKER does
636
+ // not launch Chromium itself: it validates identity (above) and hands the TYPED
637
+ // browser command to the interactive worker, which owns the browser. The broker
638
+ // keeps the lease, the session-registry authority, and the server link.
639
+ if (opts.workerBridge && typeof opts.workerBridge.call === 'function') {
640
+ try {
641
+ if (typeof opts.workerBridge.ensureWorker === 'function') await opts.workerBridge.ensureWorker();
642
+ const proxy = _parseProxy(launchParams.proxy);
643
+ const res = await opts.workerBridge.call('startSession', {
644
+ accountUuid: resolvedAccountUuid,
645
+ accountId: accountKey,
646
+ profileDir,
647
+ requireProxy: _requireProxyForLaunch(launchParams),
648
+ proxy,
649
+ // Carried so a binding failure in the worker can name the exact central
650
+ // assignment in its error instead of failing opaquely.
651
+ proxyId: launchParams.proxyId != null ? launchParams.proxyId : null,
652
+ headless: false,
653
+ });
654
+ const session = {
655
+ context: null, page: null, profileDir, accountId: accountKey, lease: null,
656
+ accountUuid: resolvedAccountUuid, viaWorker: true, workerResult: res,
657
+ };
658
+ if (lease) leaseClient.bind(session, lease);
659
+ activeSessions.set(accountKey, session);
660
+ try { ws.send(JSON.stringify(leaseClient.boundStatusMessage(session, accountId, 'running'))); } catch { }
661
+ return { success: true, accountId, started: true, visible: true, sessionId: accountKey, viaWorker: true };
662
+ } catch (err) {
663
+ const code = (err && err.code) || 'WORKER_START_FAILED';
664
+ // Safe, credential-free diagnostic: the failing stage and the identity of
665
+ // the account/proxy/device involved, so a launch failure is diagnosable
666
+ // from the agent log alone.
667
+ try {
668
+ console.error('[session] startSession failed: ' + JSON.stringify({
669
+ code,
670
+ stage: (err && err.stage) || null,
671
+ accountId,
672
+ accountUuid: resolvedAccountUuid,
673
+ deviceId: (opts.deviceMeta && opts.deviceMeta.deviceId) || null,
674
+ proxyId: (err && err.proxyId != null) ? err.proxyId : (launchParams.proxyId != null ? launchParams.proxyId : null),
675
+ proxy: (err && err.proxy) || null,
676
+ networkMode: launchParams.networkMode || null,
677
+ reason: _safeError(err),
678
+ }));
679
+ } catch { /* logging must never change the outcome */ }
680
+ _sendStartError(code);
681
+ return { success: false, code, stage: (err && err.stage) || null, error: _safeError(err) };
682
+ }
683
+ }
684
+
614
685
  // ── Already RUNNING for this exact account/profile → adopt, do not relaunch ─
615
686
  // A second `launchPersistentContext` on the same profile dir cannot succeed
616
687
  // (Chrome locks it) and would race the live window. The identity contract has
@@ -635,7 +706,7 @@ async function _startSessionLocked(params, opts, accountKey, accountId, accountU
635
706
  };
636
707
  }
637
708
 
638
- // fingerprintStore.loadOrGenerate takes an OBJECT ({ profileDir, accountId,
709
+ // ── fingerprintStore.loadOrGenerate takes an OBJECT ({ profileDir, accountId,
639
710
  // options, generator }) — matching the hardened v1 runtime call. The
640
711
  // positional form threw "paths[0] must be of type string" and aborted every
641
712
  // launch. Live operator options (mobileView/locale/userAgent/timezone) are
@@ -662,6 +733,19 @@ async function _startSessionLocked(params, opts, accountKey, accountId, accountU
662
733
  const proxyStr = launchOpts.proxy || null;
663
734
  const networkMode = launchOpts.networkMode || null;
664
735
 
736
+ // ── 2.1.0 D4: validate the proxy CONFIG before opening Chromium ─────────────
737
+ // Malformed/credential-incomplete configs are rejected with a typed code so
738
+ // the server/UI can distinguish a config error from a reachability error, and
739
+ // a required-but-unusable proxy can never fall through to DIRECT.
740
+ const proxyIdentity = parseProxyIdentity(proxyStr);
741
+ if (proxyStr) {
742
+ const v = validateProxyConfig(proxyIdentity);
743
+ if (!v.ok) {
744
+ _sendStartError(v.code);
745
+ return { success: false, error: `${v.code}: ${v.reason}`, code: v.code };
746
+ }
747
+ }
748
+
665
749
  // Health-check the proxy only when one was configured. verifyProxyIsolation
666
750
  // does the full fail-closed verification (CONNECT + TLS + GET through the
667
751
  // proxy, plus an independent direct public-IP fetch and comparison) — a
@@ -669,7 +753,9 @@ async function _startSessionLocked(params, opts, accountKey, accountId, accountU
669
753
  // from the device's own IP (transparent/misconfigured) is refused.
670
754
  let health = null;
671
755
  if (proxyStr) {
672
- const parsedProxy = _parseProxy(proxyStr);
756
+ const parsedProxy = proxyIdentity
757
+ ? { server: proxyIdentity.server, username: proxyIdentity.username, password: proxyIdentity.password }
758
+ : null;
673
759
  if (!parsedProxy) {
674
760
  health = { ok: false, reason: 'proxy_unreachable', code: 'PROXY_MALFORMED' };
675
761
  } else {
@@ -690,13 +776,122 @@ async function _startSessionLocked(params, opts, accountKey, accountId, accountU
690
776
  return { success: false, error: decision.error, code: decision.reason.toUpperCase() };
691
777
  }
692
778
 
693
- const args = [
694
- '--disable-blink-features=AutomationControlled',
695
- '--force-webrtc-ip-handling-policy=disable_non_proxied_udp',
696
- '--no-first-run',
697
- '--no-default-browser-check',
698
- '--start-maximized',
699
- ];
779
+ // ── 2.1.0 B2: per-session isolated runtime dirs ─────────────────────────────
780
+ // temp / downloads / crash / ipc live UNDER THE MACHINE ROOT keyed by the
781
+ // session, so two concurrent accounts cannot read each other's downloads or
782
+ // temp files. Created BEFORE the local lock so the lock entry can record the
783
+ // exact runtime dir atomically (no post-hoc registry refresh).
784
+ const sessionsRoot = path.join(getMachineRoot(), 'state', 'sessions');
785
+ const sessionRegKey = sessionRegistry.sessionKey({ accountUuid: resolvedAccountUuid, accountId });
786
+ let runtimeDirs;
787
+ try {
788
+ runtimeDirs = createSessionRuntimeDirs(sessionsRoot, sessionRegKey);
789
+ } catch (e) {
790
+ _sendStartError('SESSION_RUNTIME_DIR_FAILED');
791
+ return { success: false, code: 'SESSION_RUNTIME_DIR_FAILED', error: _safeError(e) };
792
+ }
793
+
794
+ // Options used for every registry operation on this session (acquire / release
795
+ // / markRunning). Kept in one object so the account key can never drift.
796
+ const registryOpts = { accountUuid: resolvedAccountUuid, accountId };
797
+
798
+ // ── 2.1.0 E1/E2: AGENT-LOCAL profile lock (in addition to the server lease) ──
799
+ // The server lease is the GLOBAL authority; this local lock protects against a
800
+ // LOCAL duplicate launch/race (two agent instances, or a launch racing a live
801
+ // Chromium that still owns the profile dir). The registry entry records only
802
+ // non-secret metadata (never a lease token, never a proxy credential).
803
+ const localLock = sessionRegistry.acquireLocalLock({
804
+ accountUuid: resolvedAccountUuid,
805
+ accountId,
806
+ profilePath: profileDir,
807
+ leaseId: lease && lease.leaseId,
808
+ proxyIdentity: proxyIdentityFingerprint(proxyIdentity),
809
+ runtimeDir: runtimeDirs.base,
810
+ }); if (!localLock.acquired) {
811
+ // A stale entry whose owning process is gone was already reaped inside
812
+ // acquireLocalLock, so a refusal here is a genuinely LIVE local session.
813
+ cleanupSessionRuntimeDirs(sessionsRoot, sessionRegKey);
814
+ _sendStartError(localLock.code || 'LOCAL_SESSION_EXISTS');
815
+ return {
816
+ success: false,
817
+ code: localLock.code || 'LOCAL_SESSION_EXISTS',
818
+ error: localLock.code === 'LOCAL_PROFILE_LOCKED'
819
+ ? 'This browser profile is locked by another live local session on this device.'
820
+ : 'This account already has a live browser session on this device.',
821
+ };
822
+ }
823
+
824
+ // ── 2.1.0 C1: coherent privacy/consistency policy ───────────────────────────
825
+ // Every value derives from ONE locale/timezone/UA triple so impossible
826
+ // combinations cannot be presented. A detected incoherence fails closed
827
+ // instead of shipping an inconsistent fingerprint.
828
+ const consistency = buildConsistencyPolicy(fingerprint);
829
+ const incoherence = fingerprintConsistencyProblems(fingerprint, consistency);
830
+ if (incoherence.length > 0) {
831
+ cleanupSessionRuntimeDirs(sessionsRoot, sessionRegKey);
832
+ sessionRegistry.releaseLocalLock(registryOpts);
833
+ _sendStartError('FINGERPRINT_INCONSISTENT');
834
+ return {
835
+ success: false,
836
+ code: 'FINGERPRINT_INCONSISTENT',
837
+ error: 'Refusing to launch with an internally-inconsistent fingerprint: ' + incoherence.join('; '),
838
+ };
839
+ }
840
+
841
+ // ── 2.1.0 C/D: hardened launch args + per-session proxy binding ─────────────
842
+ // sanitizeLaunchArgs REJECTS any security-weakening flag, so a regression is
843
+ // loud rather than silently shipped. The effective proxy is derived from THIS
844
+ // session's options only — never a global browser setting — and its credential
845
+ // is delivered through Playwright's authenticated-proxy path (never argv).
846
+ const requireProxy = proxyRequiredForSession({ proxyStr, networkMode });
847
+ let proxyBinding = { ok: true, args: [], proxyOption: null, credentialMode: 'none' };
848
+ if (decision.useProxy && proxyIdentity) {
849
+ proxyBinding = buildProxyLaunchBinding(proxyIdentity, {
850
+ // Default (and production) behavior is the Playwright authenticated-proxy
851
+ // path, which keeps the credential OUT of Chromium's argv. Only an explicit
852
+ // dev/test opt-in can switch to visible-argv credentials.
853
+ allowInlineCredentials: process.env.XKWDSTORE_INLINE_PROXY_CREDENTIALS === 'true',
854
+ });
855
+ if (!proxyBinding.ok) {
856
+ cleanupSessionRuntimeDirs(sessionsRoot, sessionRegKey);
857
+ sessionRegistry.releaseLocalLock(registryOpts);
858
+ _sendStartError(proxyBinding.code || 'PROXY_UNAVAILABLE');
859
+ return { success: false, code: proxyBinding.code || 'PROXY_UNAVAILABLE', error: 'Proxy launch binding failed' };
860
+ }
861
+ }
862
+ // A proxy-required session that somehow has no binding must NOT launch direct.
863
+ if (requireProxy && !proxyBinding.proxyOption && proxyBinding.args.length === 0) {
864
+ cleanupSessionRuntimeDirs(sessionsRoot, sessionRegKey);
865
+ sessionRegistry.releaseLocalLock(registryOpts);
866
+ _sendStartError('PROXY_UNAVAILABLE');
867
+ return { success: false, code: 'PROXY_UNAVAILABLE', error: 'PROXY_UNAVAILABLE: a proxy is required but no usable proxy binding could be established.' };
868
+ }
869
+
870
+ const args = buildLaunchArgs({
871
+ requireProxy,
872
+ // When the binding supplies a Playwright proxy OPTION, the server is passed
873
+ // out-of-band — do not also emit a competing --proxy-server switch. The DNS
874
+ // pin is still applied via proxyHostForDns.
875
+ proxyServerUrl: requireProxy && !proxyBinding.proxyOption && proxyIdentity ? proxyIdentity.server : null,
876
+ proxyHostForDns: requireProxy && proxyIdentity ? proxyIdentity.host : null,
877
+ baseArgs: [
878
+ '--disable-blink-features=AutomationControlled',
879
+ '--force-webrtc-ip-handling-policy=disable_non_proxied_udp',
880
+ '--no-first-run',
881
+ '--no-default-browser-check',
882
+ '--start-maximized',
883
+ ],
884
+ });
885
+ // Append the credential-bearing binding args (already sanitized).
886
+ for (const a of proxyBinding.args) args.push(a);
887
+
888
+ // ── Chromium preferences: session-scoped downloads + no personal data (C3) ──
889
+ // Point downloads at the SESSION dir and disable the host user's Chrome sync /
890
+ // password manager / autofill surfaces. Written into the isolated profile so
891
+ // the browser never consults the host user's personal Chrome data.
892
+ try {
893
+ _writeSessionPreferences(profileDir, buildSessionPreferences(runtimeDirs));
894
+ } catch { /* prefs are best-effort hardening; launch safety is unaffected */ }
700
895
 
701
896
  // Prefer noDefaultViewport: true so the real OS window fills the screen
702
897
  // (helps the launched browser appear visibly foregrounded). The per-account
@@ -710,21 +905,30 @@ async function _startSessionLocked(params, opts, accountKey, accountId, accountU
710
905
  headless: false,
711
906
  args,
712
907
  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.
713
911
  };
714
912
 
715
- if (decision.useProxy && proxyStr) {
716
- const proxyUrl = _parseProxy(proxyStr);
717
- if (proxyUrl) launchOptions.proxy = proxyUrl;
913
+ if (proxyBinding.proxyOption) {
914
+ launchOptions.proxy = proxyBinding.proxyOption;
718
915
  }
719
916
 
720
917
  let context;
721
918
  try {
722
919
  context = await chromium.launchPersistentContext(profileDir, launchOptions);
723
920
  } catch (err) {
921
+ cleanupSessionRuntimeDirs(sessionsRoot, sessionRegKey);
922
+ sessionRegistry.releaseLocalLock(registryOpts);
724
923
  _sendStartError(_safeError(err));
725
924
  return { success: false, error: _safeError(err) };
726
925
  }
727
926
 
927
+ // Record the real browser PID for the local registry + orphan detection. The
928
+ // PID must be provable as AGENT-OWNED before any process is ever terminated.
929
+ const browserPid = _browserPidForContext(context);
930
+ sessionRegistry.markRunning({ ...registryOpts, browserPid });
931
+
728
932
  await context.addInitScript(buildStealthScript(fingerprint));
729
933
 
730
934
  // The server sends cookies in options (options.cookies); accept the flat
@@ -783,7 +987,20 @@ async function _startSessionLocked(params, opts, accountKey, accountId, accountU
783
987
  };
784
988
  }
785
989
 
786
- const session = { context, page, profileDir, accountId: accountKey, lease: null };
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
+ };
787
1004
  if (lease) leaseClient.bind(session, lease);
788
1005
  activeSessions.set(accountKey, session);
789
1006
 
@@ -862,10 +1079,79 @@ function _attachContextCloseReporter(context, session, accountKey, accountId, ws
862
1079
  const closed = activeSessions.get(accountKey);
863
1080
  if (closed && closed !== session) return;
864
1081
  if (closed === session) activeSessions.delete(accountKey);
1082
+ // The browser is ALREADY closed; mark it so the release path does not try to
1083
+ // close it again (which could recurse on a synchronously-emitting context).
1084
+ session._closeInitiated = true;
1085
+ // 2.1.0 F: release local resources (runtime dirs + local lock) BEFORE the
1086
+ // stop is reported. `stopped` must never be claimed while the profile lock
1087
+ // or the CDP listener still exists.
1088
+ _releaseLocalSessionResources(session).catch(() => {});
865
1089
  _reportStoppedOnce(session, accountId, ws);
866
1090
  });
867
1091
  }
868
1092
 
1093
+ /**
1094
+ * Release every AGENT-LOCAL resource a session owns, in order, and verify it:
1095
+ * 1. browser context closed (best-effort; the caller closes it on the API path)
1096
+ * 2. per-session runtime dirs removed
1097
+ * 3. agent-local profile lock released from the registry
1098
+ *
1099
+ * Only after this returns is `session-status: stopped` truthful. Safe to call
1100
+ * more than once (idempotent), and never throws.
1101
+ *
1102
+ * @returns {Promise<{contextClosed:boolean, runtimeCleaned:boolean, lockReleased:boolean}>}
1103
+ */
1104
+ async function _releaseLocalSessionResources(session) {
1105
+ const out = { contextClosed: false, runtimeCleaned: false, lockReleased: false };
1106
+ if (!session) return out;
1107
+
1108
+ // 1. context — idempotent. The context's own 'close' event ALSO calls this
1109
+ // function (via the close reporter), so a flag must guard the close() call
1110
+ // itself; otherwise close() → 'close' → close() recurses on a context whose
1111
+ // close event fires synchronously (e.g. a mock, or a crash teardown).
1112
+ try {
1113
+ if (session.context && !session._closeInitiated) {
1114
+ session._closeInitiated = true;
1115
+ if (typeof session.context.isClosed !== 'function' || !session.context.isClosed()) {
1116
+ await session.context.close().catch(() => {});
1117
+ }
1118
+ }
1119
+ out.contextClosed = true;
1120
+ } catch { /* a context that refuses to close is still reported via PID liveness */ }
1121
+
1122
+ // 3. local profile lock (registry) — release before deleting runtime dirs so a
1123
+ // concurrent launch cannot acquire the lock and then lose its dirs.
1124
+ try {
1125
+ if (session._localLockReleased) {
1126
+ out.lockReleased = true;
1127
+ } else {
1128
+ sessionRegistry.releaseLocalLock({
1129
+ accountUuid: session.accountUuid || null,
1130
+ accountId: session.accountId,
1131
+ });
1132
+ session._localLockReleased = true;
1133
+ out.lockReleased = true;
1134
+ }
1135
+ } catch { /* registry is diagnostic; a failure must not block the stop ack */ }
1136
+
1137
+ // 2. runtime dirs
1138
+ try {
1139
+ if (session.sessionsRoot && session.accountUuid) {
1140
+ cleanupSessionRuntimeDirs(session.sessionsRoot, sessionRegistry.sessionKey({
1141
+ accountUuid: session.accountUuid,
1142
+ accountId: session.accountId,
1143
+ }));
1144
+ } else if (session.sessionsRoot) {
1145
+ cleanupSessionRuntimeDirs(session.sessionsRoot, sessionRegistry.sessionKey({
1146
+ accountId: session.accountId,
1147
+ }));
1148
+ }
1149
+ out.runtimeCleaned = true;
1150
+ } catch { /* best-effort */ }
1151
+
1152
+ return out;
1153
+ }
1154
+
869
1155
  /**
870
1156
  * Report ONE verified, lease-bound `stopped` frame for a session.
871
1157
  *
@@ -888,14 +1174,43 @@ function _reportStoppedOnce(session, accountId, ws) {
888
1174
  return true;
889
1175
  }
890
1176
 
891
- async function _stopSession(accountId, lease, ws) {
1177
+ async function _stopSession(accountId, lease, ws, opts) {
892
1178
  // Account keys are stored as String(accountId) — normalize every lookup so a
893
1179
  // number/string mismatch can never make a LIVE session invisible (which would
894
1180
  // make a stop silently no-op and leave the browser running past its lease).
895
1181
  const accountKey = String(accountId);
896
1182
  const session = activeSessions.get(accountKey);
897
- if (!session) return { success: false, error: 'Session not found' };
898
- try { await session.context.close(); } catch {}
1183
+ if (!session) {
1184
+ // No in-memory session. An Agent restart may still have an Agent-OWNED
1185
+ // browser for this account: consult the LOCAL REGISTRY (never "any chrome")
1186
+ // and, when proven ours, terminate exactly that PID and release the lock.
1187
+ const recovered = await _stopOrphanedLocalSession(accountKey);
1188
+ if (recovered.stopped) {
1189
+ // Bind the report to the CALLER's lease credential when present, since the
1190
+ // in-memory session (and its token) is gone after a restart.
1191
+ const reporter = { lease: null };
1192
+ if (lease) leaseClient.bind(reporter, lease);
1193
+ try { ws.send(JSON.stringify(leaseClient.boundStatusMessage(reporter, accountId, 'stopped'))); } catch {}
1194
+ return { success: true, accountId, stopped: true, recovered: true };
1195
+ }
1196
+ return { success: false, error: 'Session not found' };
1197
+ }
1198
+
1199
+ // Verified stop. The context close fires the context's own 'close' handler,
1200
+ // which releases the local resources and reports the verified stop. To make
1201
+ // the ack TRUTHFUL (never claimed before local resources are gone), we run the
1202
+ // release explicitly here and only then emit the ack.
1203
+ 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.
1206
+ 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 */ }
1209
+ activeSessions.delete(accountKey);
1210
+ if (ws) _reportStoppedOnce(session, accountId, ws);
1211
+ return { success: true, accountId, stopped: true, viaWorker: true };
1212
+ }
1213
+ try { await _releaseLocalSessionResources(session); } catch { /* best-effort */ }
899
1214
  activeSessions.delete(accountKey);
900
1215
  // Lease-bound stop ack: the server verifies the credential and releases the
901
1216
  // durable lease. This is the only thing that completes a takeover.
@@ -913,6 +1228,35 @@ async function _stopSession(accountId, lease, ws) {
913
1228
  return { success: true, accountId, stopped: true };
914
1229
  }
915
1230
 
1231
+ /**
1232
+ * 2.1.0 F1/E2: stop an Agent-OWNED browser whose in-memory session is gone
1233
+ * (agent restart / crash recovery). Safety:
1234
+ * - only a PID recorded in OUR registry is touched (never "any chrome.exe");
1235
+ * - the registry entry must belong to this host;
1236
+ * - the lock is released so the account is not permanently blocked locally.
1237
+ *
1238
+ * The SERVER durable lease is NOT touched here — the caller sends the
1239
+ * lease-bound stopped frame, which is the only thing that releases it.
1240
+ *
1241
+ * @returns {Promise<{stopped:boolean, pid?:number}>}
1242
+ */
1243
+ async function _stopOrphanedLocalSession(accountKey) {
1244
+ try {
1245
+ const entry = sessionRegistry.readRegistry()[accountKey];
1246
+ if (!entry) return { stopped: false };
1247
+ if (entry.hostname && entry.hostname !== os.hostname()) return { stopped: false };
1248
+ if (entry.browserPid && sessionRegistry.isProcessRunning(entry.browserPid)) {
1249
+ // Proven Agent-owned (it is in our registry for this host) — terminate
1250
+ // exactly that PID, never a broad chrome.exe sweep.
1251
+ try { process.kill(entry.browserPid); } catch { /* already gone */ }
1252
+ }
1253
+ sessionRegistry.releaseLocalLock({ accountUuid: entry.accountUuid, accountId: entry.accountId });
1254
+ return { stopped: true, pid: entry.browserPid || null };
1255
+ } catch {
1256
+ return { stopped: false };
1257
+ }
1258
+ }
1259
+
916
1260
  async function _refreshSession(accountId) {
917
1261
  const session = activeSessions.get(String(accountId));
918
1262
  if (!session) return { success: false, error: 'Session not found' };
@@ -994,6 +1338,87 @@ function _discoverLegacyProfiles() {
994
1338
  return { success: true, profiles };
995
1339
  }
996
1340
 
1341
+ /**
1342
+ * Device-side proxy readiness test (no browser, no profile/account mutation).
1343
+ *
1344
+ * Runs the SAME canonical proxy normalization used by launch, performs a real
1345
+ * through-proxy HTTPS egress check (and, for proxy_required, the direct-IP
1346
+ * comparison), and returns TYPED, MASKED diagnostics. It never returns
1347
+ * credentials and never opens X.
1348
+ *
1349
+ * @param {object} params — { proxy, networkMode }
1350
+ * @returns {Promise<object>} { success, code, stage, latencyMs, egressIp,
1351
+ * directIp, protocol, host (masked), timestamp }
1352
+ */
1353
+ async function _proxyTest(params) {
1354
+ const started = Date.now();
1355
+ const proxyStr = params && params.proxy;
1356
+ const networkMode = params && params.networkMode;
1357
+
1358
+ let ident;
1359
+ try {
1360
+ ident = parseProxyIdentity(proxyStr);
1361
+ } catch (e) {
1362
+ return { success: false, code: e.code || 'PROXY_FORMAT_INVALID', stage: 'parse', timestamp: new Date().toISOString() };
1363
+ }
1364
+ if (!ident) {
1365
+ return { success: false, code: 'PROXY_FORMAT_INVALID', stage: 'parse', timestamp: new Date().toISOString() };
1366
+ }
1367
+ const v = validateProxyConfig(ident);
1368
+ if (!v.ok) {
1369
+ return { success: false, code: v.code, stage: 'validate', protocol: ident.type, host: ident.host, port: ident.port, timestamp: new Date().toISOString() };
1370
+ }
1371
+
1372
+ const requireProxy = proxyRequiredForSession({ proxyStr, networkMode });
1373
+ const proxyObj = { server: ident.server, username: ident.username, password: ident.password };
1374
+
1375
+ let iso;
1376
+ try {
1377
+ iso = await require('./proxyEgress').verifyProxyIsolation(proxyObj, {});
1378
+ } 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() };
1380
+ }
1381
+
1382
+ if (!iso || !iso.ok) {
1383
+ // The egress layer now returns a CANONICAL typed code, so we do not regex
1384
+ // the message here. `PROXY_EGRESS_UNREACHABLE` is only a legacy fallback.
1385
+ let code = (iso && iso.code) || 'PROXY_UNREACHABLE';
1386
+ if (String(code).startsWith('PROXY_DIRECT_IP_')) code = 'PROXY_DIRECT_IP_UNMEASURED';
1387
+ if (code === 'PROXY_EGRESS_UNREACHABLE') {
1388
+ const reason = String(iso && iso.reason);
1389
+ code = /refused connect \(407\)|auth/i.test(reason) ? 'PROXY_AUTH_FAILED'
1390
+ : /refused connect \(\d+\)/i.test(reason) ? 'PROXY_CONNECT_REJECTED'
1391
+ : /no IP/i.test(reason) ? 'PROXY_EGRESS_ENDPOINT_UNAVAILABLE'
1392
+ : /tls/i.test(reason) ? 'PROXY_TLS_FAILED'
1393
+ : /ENOTFOUND|getaddrinfo/i.test(reason) ? 'PROXY_DNS_FAILED'
1394
+ : /ECONNREFUSED|refused/i.test(reason) ? 'PROXY_TCP_REFUSED'
1395
+ : /timeout/i.test(reason) ? 'PROXY_CONNECT_TIMEOUT'
1396
+ : 'PROXY_UNREACHABLE';
1397
+ }
1398
+ return {
1399
+ success: false,
1400
+ code,
1401
+ stage: 'egress',
1402
+ protocol: ident.type, host: ident.host, port: ident.port,
1403
+ detail: (iso && iso.reason) ? String(iso.reason).slice(0, 200) : null,
1404
+ timestamp: new Date().toISOString(),
1405
+ };
1406
+ }
1407
+
1408
+ return {
1409
+ success: true,
1410
+ code: 'PROXY_ISOLATION_OK',
1411
+ stage: 'egress',
1412
+ latencyMs: Date.now() - started,
1413
+ egressIp: iso.egressIp || null,
1414
+ directIp: iso.directIp || null,
1415
+ protocol: ident.type,
1416
+ host: ident.host,
1417
+ port: ident.port,
1418
+ timestamp: new Date().toISOString(),
1419
+ };
1420
+ }
1421
+
997
1422
  // ── Helpers ──────────────────────────────────────────────────────────────────
998
1423
 
999
1424
  /**
@@ -1044,20 +1469,109 @@ function _sendResponse(ws, msg, result, echo) {
1044
1469
  } catch {}
1045
1470
  }
1046
1471
 
1472
+ /**
1473
+ * Whether the launch requires a proxy (fail-closed default) — used by the broker
1474
+ * when forwarding a start to the interactive worker.
1475
+ */
1476
+ function _requireProxyForLaunch(launchParams) {
1477
+ const proxyStr = launchParams && launchParams.proxy;
1478
+ const networkMode = launchParams && launchParams.networkMode;
1479
+ return proxyRequiresForSessionSafe(proxyStr, networkMode);
1480
+ }
1481
+
1482
+ /** Thin wrapper so the broker and worker agree on the fail-closed rule. */
1483
+ function proxyRequiresForSessionSafe(proxyStr, networkMode) {
1484
+ const hasProxy = !!(proxyStr && String(proxyStr).trim());
1485
+ if (networkMode === 'direct_allowed' && !hasProxy) return false;
1486
+ return true;
1487
+ }
1488
+
1047
1489
  function _parseProxy(proxyStr) {
1048
- if (!proxyStr || typeof proxyStr !== 'string') return null;
1049
- const parts = proxyStr.split(':');
1050
- if (parts.length >= 2) {
1051
- const proxy = { server: `http://${parts[0]}:${parts[1]}` };
1052
- if (parts[2] && parts[3]) {
1053
- proxy.username = parts[2];
1054
- proxy.password = parts[3];
1055
- }
1056
- return proxy;
1057
- }
1490
+ // Delegate to the canonical agent-side parser so TEST and LAUNCH can never
1491
+ // disagree, and so a scheme-prefixed proxy (e.g. `socks5://u:p@h:port`) or a
1492
+ // bare `host:port:user:pass` both normalize identically. The canonical parser
1493
+ // is fail-closed (returns null on malformed input).
1494
+ const { parseProxyIdentity } = require('./browserIsolation');
1495
+ const p = parseProxyIdentity(proxyStr);
1496
+ if (!p) return null;
1497
+ return {
1498
+ server: p.server, // e.g. http://host:port or socks5://host:port
1499
+ host: p.host,
1500
+ port: p.port,
1501
+ type: p.type,
1502
+ username: p.username,
1503
+ password: p.password,
1504
+ };
1505
+ }
1506
+
1507
+ /**
1508
+ * Best-effort resolution of the Chromium browser PID behind a Playwright
1509
+ * BrowserContext, for the LOCAL registry (+ orphan detection). We deliberately
1510
+ * do NOT guess: if Playwright cannot report a PID, we return null and the
1511
+ * registry records the agent PID instead (orphan detection then falls back to
1512
+ * exact-profile command-line matching — never a broad chrome.exe kill).
1513
+ */
1514
+ function _browserPidForContext(context) {
1515
+ try {
1516
+ const browser = typeof context.browser === 'function' ? context.browser() : null;
1517
+ if (!browser) return null;
1518
+ // Playwright's internal transport carries the browser process; _browserType
1519
+ // is private but stable enough to read defensively. Absence is fine.
1520
+ const proc = browser._process || (browser._connection && browser._connection._transport && browser._connection._transport._proc);
1521
+ if (proc && typeof proc.pid === 'number') return proc.pid;
1522
+ } catch { /* fall through */ }
1058
1523
  return null;
1059
1524
  }
1060
1525
 
1526
+ /**
1527
+ * Write the session-scoped Chromium preferences into the isolated profile so
1528
+ * downloads land in the SESSION dir and the host user's Chrome personal data
1529
+ * (sync, password manager, autofill) is never consulted (Part C3).
1530
+ *
1531
+ * Best-effort: a preference write failure does not weaken isolation (the
1532
+ * profile dir is already dedicated to this account); it only loses the
1533
+ * download-path pin.
1534
+ */
1535
+ function _writeSessionPreferences(profileDir, prefs) {
1536
+ try {
1537
+ const defaultDir = path.join(profileDir, 'Default');
1538
+ fs.mkdirSync(defaultDir, { recursive: true, mode: 0o700 });
1539
+ const prefsPath = path.join(defaultDir, 'Preferences');
1540
+ let existing = {};
1541
+ try { existing = JSON.parse(fs.readFileSync(prefsPath, 'utf8')); } catch { existing = {}; }
1542
+ const merged = { ...existing, ...prefs };
1543
+ fs.writeFileSync(prefsPath, JSON.stringify(merged, null, 2), { encoding: 'utf8', mode: 0o600 });
1544
+ } catch { /* best-effort */ }
1545
+ }
1546
+
1547
+ /**
1548
+ * 2.1.0 F1: crash recovery. Find Agent-OWNED orphaned browsers (registry entry
1549
+ * whose owning agent process is gone but whose browser PID is alive) and release
1550
+ * their local locks so a restarted agent can re-open those accounts. The orphan
1551
+ * PID is NOT killed automatically — it may hold a recoverable profile; the
1552
+ * server's recovery probe decides liveness. Killing happens only on an explicit
1553
+ * stop for that proven-owned PID.
1554
+ */
1555
+ function recoverOrphanedSessions() {
1556
+ const out = { orphans: 0, released: 0 };
1557
+ try {
1558
+ const orphans = sessionRegistry.findOrphans();
1559
+ out.orphans = orphans.length;
1560
+ for (const entry of orphans) {
1561
+ // Release the stale LOCAL lock so the profile is not permanently blocked.
1562
+ // The SERVER durable lease is untouched (server recovery remains
1563
+ // authoritative).
1564
+ try {
1565
+ sessionRegistry.releaseLocalLock({ accountUuid: entry.accountUuid, accountId: entry.accountId });
1566
+ out.released += 1;
1567
+ } catch { /* best-effort */ }
1568
+ }
1569
+ // Also reap fully dead entries so the registry cannot grow unbounded.
1570
+ sessionRegistry.reapDeadEntries();
1571
+ } catch { /* recovery is best-effort and must never block startup */ }
1572
+ return out;
1573
+ }
1574
+
1061
1575
  function _safeError(err) {
1062
1576
  const msg = err && err.message ? err.message : String(err);
1063
1577
  return msg
@@ -1066,4 +1580,17 @@ function _safeError(err) {
1066
1580
  .slice(0, 500);
1067
1581
  }
1068
1582
 
1069
- module.exports = { setupSessionHandler, activeSessions, closeAllSessions, markDisconnected, _detectProfileChromeRunning, _recoveryVerdict, _setChromeLinesProvider, _attachContextCloseReporter };
1583
+ module.exports = {
1584
+ setupSessionHandler,
1585
+ activeSessions,
1586
+ closeAllSessions,
1587
+ markDisconnected,
1588
+ _detectProfileChromeRunning,
1589
+ _recoveryVerdict,
1590
+ _setChromeLinesProvider,
1591
+ _attachContextCloseReporter,
1592
+ _releaseLocalSessionResources,
1593
+ _stopOrphanedLocalSession,
1594
+ recoverOrphanedSessions,
1595
+ _proxyTest,
1596
+ };