@xkwdstore/agent 2.1.3 → 2.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/worker.js CHANGED
@@ -1,13 +1,16 @@
1
1
  'use strict';
2
2
 
3
3
  /**
4
- * Interactive Browser Worker entry point (TW-manager Agent 2.1.0).
4
+ * Interactive Browser Worker entry point (TW-manager Agent 2.1.x).
5
5
  *
6
6
  * Runs INSIDE an interactive Windows desktop session. It is spawned by the
7
7
  * machine-wide Broker and connects back over a loopback-only, token-authenticated
8
8
  * channel. It:
9
9
  *
10
10
  * - launches and drives Chromium for account sessions
11
+ * - restores a valid X session from the persistent profile and verifies it
12
+ * - applies eligible bootstrap cookies ONLY after the profile is proven signed
13
+ * out, then verifies again
11
14
  * - understands ONLY typed browser commands (see brokerWorkerBridge)
12
15
  * - NEVER reads the device private key
13
16
  * - NEVER enrolls / registers the device
@@ -22,7 +25,14 @@
22
25
  */
23
26
 
24
27
  const path = require('path');
25
- const os = require('os');
28
+ const fs = require('fs');
29
+
30
+ const connectivity = require('./browserConnectivity');
31
+ const browserLaunch = require('./browserLaunch');
32
+
33
+ const AUTH_EXEMPT_ACTIONS = new Set([
34
+ 'autoLogin', 'checkLoginState', 'checkStatus', 'humanResume', 'connectAutomation',
35
+ ]);
26
36
 
27
37
  function parseArgs(argv) {
28
38
  const out = {};
@@ -38,6 +48,15 @@ function parseArgs(argv) {
38
48
  return out;
39
49
  }
40
50
 
51
+ /** Fail closed unless `child` is inside `root` after realpath-normalization. */
52
+ function _isContained(root, child) {
53
+ try {
54
+ const r = path.resolve(root).replace(/[\\/]+$/, '').toLowerCase();
55
+ const c = path.resolve(child).replace(/[\\/]+$/, '').toLowerCase();
56
+ return c === r || c.startsWith(r + path.sep) || c.startsWith(r + '/');
57
+ } catch { return false; }
58
+ }
59
+
41
60
  /**
42
61
  * Build the worker's command handler. The worker owns the browser lifecycle; the
43
62
  * broker owns everything else. Each command is bound to an account+lease supplied
@@ -48,19 +67,100 @@ function buildWorkerHandler(opts) {
48
67
  // The real browser runtime: reuse the hardened session handler's primitives.
49
68
  const bi = require('./browserIsolation');
50
69
  const sessionRegistry = require('./sessionRegistry');
51
- const { getMachineRoot } = require('./deviceKeyStore');
70
+ const { getMachineRoot, PROFILES_DIR } = require('./deviceKeyStore');
71
+ const { readIdentityMarker } = require('./profilePath');
72
+ const { applyCookies } = require('./cookieInjection');
73
+ const authState = require('./sessionAuth');
52
74
 
53
75
  // Per-account live contexts owned by THIS worker process.
54
- const contexts = new Map(); // accountKey -> { context, runtimeDirs, sessionsRoot, profileDir }
76
+ // accountKey -> { context, page, runtimeDirs, sessionsRoot, profileDir,
77
+ // accountUuid, accountId, lock, lastAuth }
78
+ const contexts = new Map();
79
+
80
+ function _entryKey(payload) {
81
+ return String(payload.accountUuid || payload.accountId || '');
82
+ }
83
+
84
+ function _error(message, code, extra) {
85
+ return Object.assign(new Error(message), { code, ...(extra || {}) });
86
+ }
87
+
88
+ /**
89
+ * Prove the exact profile slot belongs to the requested immutable identity and
90
+ * lives under the machine profiles root. The broker already resolved it, but a
91
+ * compromised/buggy broker must not be able to point the worker at another
92
+ * account's directory.
93
+ */
94
+ function _assertProfileOwnership(profileDir, payload) {
95
+ if (!profileDir || typeof profileDir !== 'string') {
96
+ throw _error('missing profileDir', 'WORKER_NO_PROFILE');
97
+ }
98
+ if (!_isContained(PROFILES_DIR, profileDir)) {
99
+ throw _error('profileDir is outside the machine profile root', 'PROFILE_CONTAINMENT_FAILED');
100
+ }
101
+ const marker = readIdentityMarker(profileDir);
102
+ if (!marker) {
103
+ throw _error('profile identity marker is missing or invalid', 'PROFILE_MARKER_MISSING');
104
+ }
105
+ for (const k of ['serverUuid', 'tenantUuid', 'accountUuid', 'deviceUuid']) {
106
+ if (payload[k] && String(payload[k]) !== String(marker[k])) {
107
+ throw _error('profile identity mismatch: ' + k, 'PROFILE_IDENTITY_MISMATCH', { stage: 'profile' });
108
+ }
109
+ }
110
+ return marker;
111
+ }
112
+
113
+ function _launch(payload, profileDir, proxyOption, args) {
114
+ const { chromium } = require('playwright-core');
115
+ // One shared launch-options builder: keeps the extension subsystem available
116
+ // on branded Chrome (Chrome Web Store), forwards the per-session proxy and
117
+ // captures a NetLog only when explicitly enabled. No profile is modified.
118
+ const launchOptions = browserLaunch.buildChromiumLaunchOptions({
119
+ chromePath: chromePath || payload.chromePath,
120
+ headless: payload.headless === true,
121
+ args,
122
+ proxy: proxyOption,
123
+ captureNetlog: true,
124
+ });
125
+ return chromium.launchPersistentContext(profileDir, launchOptions);
126
+ }
127
+
128
+ async function _pageFor(entry) {
129
+ if (entry.page && !(typeof entry.page.isClosed === 'function' && entry.page.isClosed())) return entry.page;
130
+ const pages = entry.context.pages();
131
+ entry.page = pages[0] || await entry.context.newPage();
132
+ return entry.page;
133
+ }
134
+
135
+ async function _verify(entry, timeoutMs) {
136
+ const page = await _pageFor(entry);
137
+ const verified = await authState.verifyXAuth(page, entry.context, {
138
+ expectedUsername: entry.expectedUsername,
139
+ timeoutMs: timeoutMs == null ? 8000 : timeoutMs,
140
+ });
141
+ entry.lastAuth = verified;
142
+ return verified;
143
+ }
55
144
 
56
145
  async function startSession(payload) {
57
- const accountKey = String(payload.accountUuid || payload.accountId || '');
58
- if (!accountKey) throw Object.assign(new Error('missing account identity'), { code: 'WORKER_NO_ACCOUNT' });
146
+ const accountKey = _entryKey(payload);
147
+ if (!accountKey) throw _error('missing account identity', 'WORKER_NO_ACCOUNT');
59
148
  if (contexts.has(accountKey)) {
60
- return { alreadyRunning: true, accountKey };
149
+ const existing = contexts.get(accountKey);
150
+ const verified = await _verify(existing, 1500);
151
+ return {
152
+ started: true,
153
+ alreadyRunning: true,
154
+ accountKey,
155
+ profileDir: existing.profileDir,
156
+ browserReady: true,
157
+ visible: true,
158
+ ...authState.authSummary(verified),
159
+ };
61
160
  }
62
161
  const profileDir = payload.profileDir;
63
- if (!profileDir) throw Object.assign(new Error('missing profileDir'), { code: 'WORKER_NO_PROFILE' });
162
+ _assertProfileOwnership(profileDir, payload);
163
+ if (!fs.existsSync(profileDir)) fs.mkdirSync(profileDir, { recursive: true });
64
164
 
65
165
  // Local profile lock (agent-local), in addition to the broker's server lease.
66
166
  const lock = sessionRegistry.acquireLocalLock({
@@ -69,12 +169,16 @@ function buildWorkerHandler(opts) {
69
169
  profilePath: profileDir,
70
170
  });
71
171
  if (!lock.acquired) {
72
- throw Object.assign(new Error('local profile lock refused: ' + (lock.code || 'LOCAL_SESSION_EXISTS')), { code: lock.code || 'LOCAL_SESSION_EXISTS' });
172
+ throw _error('local profile lock refused: ' + (lock.code || 'LOCAL_SESSION_EXISTS'), lock.code || 'LOCAL_SESSION_EXISTS');
73
173
  }
74
174
 
75
175
  const sessionsRoot = path.join(getMachineRoot(), 'state', 'sessions');
76
176
  const runtimeDirs = bi.createSessionRuntimeDirs(sessionsRoot, accountKey);
77
177
 
178
+ const releaseLock = () => {
179
+ try { sessionRegistry.releaseLocalLock({ accountUuid: payload.accountUuid, accountId: payload.accountId || accountKey }); } catch { /* safe */ }
180
+ };
181
+
78
182
  const requireProxy = payload.requireProxy === true;
79
183
  // The broker may hand us EITHER an already-parsed proxy identity OR a raw
80
184
  // connection string. Both are normalized here through the ONE canonical
@@ -86,42 +190,46 @@ function buildWorkerHandler(opts) {
86
190
  let proxyOption = null;
87
191
  if (requireProxy) {
88
192
  if (!coerced.ok) {
89
- sessionRegistry.releaseLocalLock({ accountUuid: payload.accountUuid, accountId: payload.accountId });
90
- throw Object.assign(
91
- new Error(`proxy binding failed: ${coerced.detail}`),
92
- {
93
- code: coerced.code || 'PROXY_UNAVAILABLE',
94
- stage: 'proxy_binding',
95
- accountId: payload.accountId || null,
96
- accountUuid: payload.accountUuid || null,
97
- proxyId: payload.proxyId != null ? payload.proxyId : null,
98
- proxy: bi.maskProxyForLog(payload.proxy),
99
- },
100
- );
193
+ releaseLock();
194
+ throw _error(`proxy binding failed: ${coerced.detail}`, coerced.code || 'PROXY_UNAVAILABLE', {
195
+ stage: 'proxy_binding',
196
+ accountId: payload.accountId || null,
197
+ accountUuid: payload.accountUuid || null,
198
+ proxyId: payload.proxyId != null ? payload.proxyId : null,
199
+ proxy: bi.maskProxyForLog(payload.proxy),
200
+ });
101
201
  }
102
202
  proxy = coerced.identity;
203
+ // Proxy parity: the broker computes a credential-free fingerprint from the
204
+ // CENTRAL assignment. A mismatch means the assignment changed between the
205
+ // broker's decision and this launch — refuse before any origin traffic.
206
+ if (payload.proxyFingerprint) {
207
+ const fp = bi.proxyIdentityFingerprint(proxy);
208
+ if (fp !== payload.proxyFingerprint) {
209
+ releaseLock();
210
+ throw _error('proxy binding changed before launch', 'PROXY_BINDING_CHANGED', {
211
+ stage: 'proxy_binding', proxyId: payload.proxyId != null ? payload.proxyId : null, proxy: bi.maskProxyForLog(proxy),
212
+ });
213
+ }
214
+ }
103
215
  const bind = bi.buildProxyLaunchBinding(proxy, { allowInlineCredentials: process.env.XKWDSTORE_INLINE_PROXY_CREDENTIALS === 'true' });
104
216
  if (!bind.ok) {
105
- sessionRegistry.releaseLocalLock({ accountUuid: payload.accountUuid, accountId: payload.accountId });
106
- throw Object.assign(
107
- new Error(`proxy binding failed: ${bind.code}`),
108
- {
109
- code: bind.code || 'PROXY_UNAVAILABLE',
110
- stage: 'proxy_binding',
111
- accountId: payload.accountId || null,
112
- accountUuid: payload.accountUuid || null,
113
- proxyId: payload.proxyId != null ? payload.proxyId : null,
114
- proxy: bi.maskProxyForLog(proxy),
115
- },
116
- );
217
+ releaseLock();
218
+ throw _error(`proxy binding failed: ${bind.code}`, bind.code || 'PROXY_UNAVAILABLE', {
219
+ stage: 'proxy_binding',
220
+ accountId: payload.accountId || null,
221
+ accountUuid: payload.accountUuid || null,
222
+ proxyId: payload.proxyId != null ? payload.proxyId : null,
223
+ proxy: bi.maskProxyForLog(proxy),
224
+ });
117
225
  }
118
226
  proxyOption = bind.proxyOption;
119
227
  if (!proxyOption) {
120
- sessionRegistry.releaseLocalLock({ accountUuid: payload.accountUuid, accountId: payload.accountId });
121
- throw Object.assign(
122
- new Error('proxy binding failed: a proxy is required but the binding produced no proxy option'),
123
- { code: 'PROXY_UNAVAILABLE', stage: 'proxy_binding', accountId: payload.accountId || null, accountUuid: payload.accountUuid || null, proxyId: payload.proxyId != null ? payload.proxyId : null, proxy: bi.maskProxyForLog(proxy) },
124
- );
228
+ releaseLock();
229
+ throw _error('proxy binding failed: a proxy is required but the binding produced no proxy option', 'PROXY_UNAVAILABLE', {
230
+ stage: 'proxy_binding', accountId: payload.accountId || null, accountUuid: payload.accountUuid || null,
231
+ proxyId: payload.proxyId != null ? payload.proxyId : null, proxy: bi.maskProxyForLog(proxy),
232
+ });
125
233
  }
126
234
  }
127
235
 
@@ -132,23 +240,56 @@ function buildWorkerHandler(opts) {
132
240
  baseArgs: ['--no-first-run', '--no-default-browser-check', '--start-maximized'],
133
241
  });
134
242
 
135
- const { chromium } = require('playwright-core');
136
- const launchOptions = {
137
- executablePath: chromePath || payload.chromePath,
138
- headless: payload.headless === true,
139
- args,
140
- noDefaultViewport: true,
141
- };
142
- if (proxyOption) launchOptions.proxy = proxyOption;
243
+ // ── Proxy egress verification BEFORE any authentication traffic ──────────
244
+ // A proxy that accepts TCP but does not tunnel (or rejects credentials) must
245
+ // never be allowed to reach X with the stored cookies. This mirrors the
246
+ // direct runtime's fail-closed verification; a transport failure stays
247
+ // distinct from a cookie/logout outcome.
248
+ if (requireProxy && proxy) {
249
+ let iso;
250
+ try {
251
+ iso = await require('./proxyEgress').verifyProxyIsolation(
252
+ { server: proxy.server, username: proxy.username, password: proxy.password },
253
+ {},
254
+ );
255
+ } catch {
256
+ iso = { ok: false, code: 'PROXY_EGRESS_UNREACHABLE' };
257
+ }
258
+ if (!iso || !iso.ok) {
259
+ releaseLock();
260
+ try { bi.cleanupSessionRuntimeDirs(sessionsRoot, accountKey); } catch { /* safe */ }
261
+ const rawCode = String((iso && iso.code) || 'PROXY_UNREACHABLE');
262
+ const reason = String((iso && iso.reason) || '');
263
+ const code = rawCode === 'PROXY_EGRESS_UNREACHABLE'
264
+ ? (/407|auth/i.test(reason) ? 'PROXY_AUTH_FAILED'
265
+ : /refused connect|ECONNREFUSED/i.test(reason) ? 'PROXY_TCP_REFUSED'
266
+ : /timeout|timed out/i.test(reason) ? 'PROXY_CONNECT_TIMEOUT'
267
+ : /tls/i.test(reason) ? 'PROXY_TLS_FAILED'
268
+ : /ENOTFOUND|getaddrinfo/i.test(reason) ? 'PROXY_DNS_FAILED'
269
+ : 'PROXY_UNREACHABLE')
270
+ : rawCode;
271
+ throw _error('proxy egress verification failed', code, {
272
+ stage: 'proxy_egress',
273
+ accountId: payload.accountId || null,
274
+ accountUuid: payload.accountUuid || null,
275
+ proxyId: payload.proxyId != null ? payload.proxyId : null,
276
+ proxy: bi.maskProxyForLog(proxy),
277
+ reason: 'proxy_egress_failed',
278
+ });
279
+ }
280
+ }
143
281
 
144
282
  let context;
145
283
  try {
146
- context = await chromium.launchPersistentContext(profileDir, launchOptions);
284
+ context = await _launch(payload, profileDir, proxyOption, args);
147
285
  } catch (err) {
148
- sessionRegistry.releaseLocalLock({ accountUuid: payload.accountUuid, accountId: payload.accountId });
149
- throw Object.assign(new Error('launch failed: ' + err.message), { code: 'WORKER_LAUNCH_FAILED' });
286
+ releaseLock();
287
+ try { bi.cleanupSessionRuntimeDirs(sessionsRoot, accountKey); } catch { /* safe */ }
288
+ throw _error('launch failed: ' + authState.classifyNavigationError(err).reason, 'WORKER_LAUNCH_FAILED', {
289
+ stage: 'launch', accountId: payload.accountId || null, accountUuid: payload.accountUuid || null,
290
+ });
150
291
  }
151
- contexts.set(accountKey, { context, runtimeDirs, sessionsRoot, profileDir, accountUuid: payload.accountUuid, accountId: payload.accountId });
292
+
152
293
  // Record the real browser PID so crash recovery can prove ownership of the
153
294
  // exact process (never "any chrome.exe"). Resolved by exact profile dir.
154
295
  let browserPid = null;
@@ -156,71 +297,380 @@ function buildWorkerHandler(opts) {
156
297
  if (browserPid) {
157
298
  sessionRegistry.markRunning({ accountUuid: payload.accountUuid || null, accountId: payload.accountId || accountKey, browserPid });
158
299
  }
300
+
301
+ const entry = {
302
+ context,
303
+ page: null,
304
+ runtimeDirs,
305
+ sessionsRoot,
306
+ profileDir,
307
+ accountUuid: payload.accountUuid || null,
308
+ accountId: payload.accountId || accountKey,
309
+ expectedUsername: payload.expectedUsername || payload.username || null,
310
+ proxyFingerprint: proxy ? bi.proxyIdentityFingerprint(proxy) : null,
311
+ browserPid,
312
+ lastAuth: null,
313
+ // 2.1.5 containment: bounded navigation + stalled-tab watchdog.
314
+ navGuard: null,
315
+ connectivityEvents: [],
316
+ };
317
+ contexts.set(accountKey, entry);
318
+
319
+ // ── 2.1.5 navigation guard ────────────────────────────────────────────────
320
+ // A proxy that accepts TCP but never answers CONNECT leaves the tab on
321
+ // about:blank with a permanent spinner. The guard bounds every navigation and
322
+ // replaces a stalled tab with a diagnostic page so a failed request can never
323
+ // stay pending indefinitely.
324
+ try {
325
+ entry.navGuard = connectivity.installNavigationGuard(context, {
326
+ accountLabel: entry.accountUuid || entry.accountId || null,
327
+ onEvent: (event, detail) => {
328
+ try {
329
+ entry.connectivityEvents.push({ at: new Date().toISOString(), event, ...detail });
330
+ if (entry.connectivityEvents.length > 25) entry.connectivityEvents.shift();
331
+ } catch { /* never break the session */ }
332
+ },
333
+ });
334
+ } catch { /* containment is best effort; launch safety is unaffected */ }
335
+
159
336
  context.on('close', () => {
160
- const entry = contexts.get(accountKey);
161
- if (entry) {
162
- try { bi.cleanupSessionRuntimeDirs(entry.sessionsRoot, accountKey); } catch { }
163
- sessionRegistry.releaseLocalLock({ accountUuid: entry.accountUuid, accountId: entry.accountId });
164
- contexts.delete(accountKey);
165
- }
337
+ const current = contexts.get(accountKey);
338
+ if (current !== entry) return;
339
+ try { if (entry.navGuard) entry.navGuard.stop(); } catch { /* safe */ }
340
+ try { bi.cleanupSessionRuntimeDirs(entry.sessionsRoot, accountKey); } catch { /* safe */ }
341
+ try { sessionRegistry.releaseLocalLock({ accountUuid: entry.accountUuid, accountId: entry.accountId }); } catch { /* safe */ }
342
+ contexts.delete(accountKey);
166
343
  });
167
- return { started: true, accountKey, profileDir, visible: true };
344
+
345
+ // ── Canonical startup: verify BEFORE writing cookies ──────────────────────
346
+ // Never overwrite a newer authenticated profile with stale imported cookies.
347
+ let restored;
348
+ try {
349
+ const page = await _pageFor(entry);
350
+ restored = await authState.restoreAndVerify({
351
+ page,
352
+ context,
353
+ cookies: Array.isArray(payload.cookies) ? payload.cookies : null,
354
+ url: payload.url || null,
355
+ expectedUsername: entry.expectedUsername,
356
+ applyCookies,
357
+ navigationTimeoutMs: Number.isFinite(payload.navigationTimeoutMs) ? payload.navigationTimeoutMs : 45000,
358
+ verifyTimeoutMs: Number.isFinite(payload.verifyTimeoutMs) ? payload.verifyTimeoutMs : 8000,
359
+ });
360
+ entry.lastAuth = restored;
361
+ // A startup navigation that never completed must not leave the visible tab
362
+ // on about:blank: paint the actionable diagnostic page for the operator.
363
+ if (restored && restored.navigationOk === false) {
364
+ const failure = connectivity.classifyNavigationFailure(
365
+ Object.assign(new Error(restored.reason || 'navigation failed'), { code: restored.code }),
366
+ { url: payload.url || 'https://x.com/home', proxyActive: requireProxy, dnsPinned: requireProxy && !!proxy },
367
+ );
368
+ try {
369
+ await connectivity.paintNavigationFailure(page, {
370
+ ...failure,
371
+ url: payload.url || 'https://x.com/home',
372
+ accountLabel: entry.accountUuid || entry.accountId,
373
+ });
374
+ } catch { /* containment is best effort */ }
375
+ }
376
+ } catch (err) {
377
+ restored = {
378
+ authState: authState.AUTH_STATE.UNKNOWN,
379
+ reason: 'startup_verification_failed',
380
+ stage: 'verify',
381
+ browserReady: true,
382
+ };
383
+ entry.lastAuth = restored;
384
+ }
385
+
386
+ return {
387
+ started: true,
388
+ accountKey,
389
+ profileDir,
390
+ visible: true,
391
+ browserReady: true,
392
+ authState: restored.authState,
393
+ reason: restored.reason || null,
394
+ stage: restored.stage || null,
395
+ handle: restored.handle || null,
396
+ url: restored.url || null,
397
+ cookieState: restored.cookieState || null,
398
+ cookieApplied: restored.cookieApplied || 0,
399
+ cookieRejected: restored.cookieRejected || 0,
400
+ };
168
401
  }
169
402
 
170
403
  async function stopSession(payload) {
171
- const accountKey = String(payload.accountUuid || payload.accountId || '');
404
+ const accountKey = _entryKey(payload);
172
405
  const entry = contexts.get(accountKey);
173
- if (!entry) return { stopped: false, reason: 'not running' };
174
- try { await entry.context.close(); } catch { }
175
- try { bi.cleanupSessionRuntimeDirs(entry.sessionsRoot, accountKey); } catch { }
176
- sessionRegistry.releaseLocalLock({ accountUuid: entry.accountUuid, accountId: entry.accountId });
406
+ if (!entry) return { stopped: false, running: false, reason: 'not_running' };
407
+ // Await the REAL close, bounded. A stop is never reported while Chromium is
408
+ // still flushing its persistent profile.
409
+ let closed = false;
410
+ try {
411
+ if (typeof entry.context.isClosed === 'function' && entry.context.isClosed()) {
412
+ closed = true;
413
+ } else {
414
+ await Promise.race([
415
+ entry.context.close(),
416
+ new Promise((_, reject) => setTimeout(() => reject(Object.assign(new Error('browser close timed out'), { code: 'WORKER_STOP_UNVERIFIED' })), 20000)),
417
+ ]);
418
+ closed = typeof entry.context.isClosed === 'function' ? entry.context.isClosed() : true;
419
+ }
420
+ } catch (err) {
421
+ throw _error('browser close could not be verified', 'WORKER_STOP_UNVERIFIED', { stage: 'stop', accountId: entry.accountId, accountUuid: entry.accountUuid });
422
+ }
423
+ if (!closed) {
424
+ throw _error('browser close could not be verified', 'WORKER_STOP_UNVERIFIED', { stage: 'stop', accountId: entry.accountId, accountUuid: entry.accountUuid });
425
+ }
426
+ try { bi.cleanupSessionRuntimeDirs(entry.sessionsRoot, accountKey); } catch { /* safe */ }
427
+ try { sessionRegistry.releaseLocalLock({ accountUuid: entry.accountUuid, accountId: entry.accountId }); } catch { /* safe */ }
177
428
  contexts.delete(accountKey);
178
- return { stopped: true, accountKey };
429
+ return { stopped: true, running: false, accountKey };
179
430
  }
180
431
 
181
- return async function handler(command, payload) {
432
+ async function _requireEntry(payload) {
433
+ const accountKey = _entryKey(payload);
434
+ const entry = contexts.get(accountKey);
435
+ if (!entry) throw _error('Session not found', 'SESSION_NOT_FOUND', { accountId: payload.accountId || null, accountUuid: payload.accountUuid || null });
436
+ return entry;
437
+ }
438
+
439
+ /** Block authenticated actions before side effects when auth is unverified. */
440
+ async function _requireAuthenticated(entry) {
441
+ const verified = await _verify(entry, 2500);
442
+ const s = verified.authState;
443
+ const definiteFailure = s === authState.AUTH_STATE.SIGNED_OUT
444
+ || s === authState.AUTH_STATE.WRONG_ACCOUNT
445
+ || s === authState.AUTH_STATE.CHALLENGE_REQUIRED;
446
+ const observedUnknown = s === authState.AUTH_STATE.UNKNOWN
447
+ && verified.reason !== 'no_browser_signal';
448
+ if (definiteFailure || observedUnknown) {
449
+ return { ok: false, verified };
450
+ }
451
+ return { ok: true, verified };
452
+ }
453
+
454
+ const handler = async function handler(command, payload) {
182
455
  switch (command) {
183
456
  case 'startSession': return startSession(payload);
457
+
184
458
  case 'stopSession': return stopSession(payload);
459
+
185
460
  case 'getStatus': {
186
- const accountKey = String(payload.accountUuid || payload.accountId || '');
461
+ const accountKey = _entryKey(payload);
187
462
  const entry = contexts.get(accountKey);
188
- return { running: !!entry, accountKey, contexts: contexts.size };
463
+ if (!entry) {
464
+ return {
465
+ running: false, browserReady: false, accountKey,
466
+ authState: authState.AUTH_STATE.UNKNOWN, reason: 'no_browser', stage: 'status',
467
+ loggedIn: false, contexts: contexts.size,
468
+ };
469
+ }
470
+ const last = entry.lastAuth || {};
471
+ const pageUrl = (() => { try { return entry.page && !entry.page.isClosed() ? entry.page.url() : null; } catch { return null; } })();
472
+ return {
473
+ running: true, browserReady: true, accountKey, contexts: contexts.size,
474
+ authState: last.authState || authState.AUTH_STATE.UNKNOWN,
475
+ reason: last.reason || null,
476
+ stage: last.stage || 'status',
477
+ handle: last.handle || null,
478
+ loggedIn: last.authState === authState.AUTH_STATE.AUTHENTICATED,
479
+ url: pageUrl,
480
+ // 2.1.5 diagnostics: a tab sitting on about:blank is never "fine".
481
+ pageStalled: pageUrl === 'about:blank',
482
+ browser: browserLaunch.describeBrowser(chromePath),
483
+ connectivity: {
484
+ guard: entry.navGuard ? entry.navGuard.options : null,
485
+ stalledPainted: entry.navGuard ? entry.navGuard.stats.painted : 0,
486
+ recentEvents: entry.connectivityEvents.slice(-5),
487
+ },
488
+ };
489
+ }
490
+
491
+ case 'checkAuth':
492
+ case 'refreshSession': {
493
+ const entry = await _requireEntry(payload);
494
+ const page = await _pageFor(entry);
495
+ if (command === 'refreshSession') {
496
+ // Bounded reload: a stalled refresh must not leave the visible tab on
497
+ // about:blank with a spinner.
498
+ let current = '';
499
+ try { current = page.url(); } catch { current = ''; }
500
+ const target = authState.isAuthorizedXUrl(current) ? current : 'https://x.com/home';
501
+ const nav = await connectivity.navigateBounded(page, target, {
502
+ timeoutMs: 30000,
503
+ proxyActive: !!entry.proxyFingerprint,
504
+ dnsPinned: !!entry.proxyFingerprint,
505
+ accountLabel: entry.accountUuid || entry.accountId,
506
+ });
507
+ if (!nav.ok) {
508
+ return {
509
+ success: false,
510
+ code: nav.code,
511
+ stage: nav.stage,
512
+ reason: nav.reason,
513
+ error: nav.message,
514
+ painted: nav.painted === true,
515
+ browserReady: true,
516
+ ...authState.authSummary(entry.lastAuth),
517
+ };
518
+ }
519
+ }
520
+ const verified = await _verify(entry, 8000);
521
+ return { success: true, browserReady: true, ...authState.authSummary(verified), handle: verified.handle || null, url: verified.url || null };
189
522
  }
523
+
190
524
  case 'focus': {
191
- const accountKey = String(payload.accountUuid || payload.accountId || '');
192
- const entry = contexts.get(accountKey);
193
- if (!entry) return { focused: false };
194
- const pages = entry.context.pages();
195
- if (pages[0]) { try { await pages[0].bringToFront(); } catch { } }
525
+ const entry = await _requireEntry(payload);
526
+ const page = await _pageFor(entry);
527
+ try { await page.bringToFront(); } catch { /* best effort */ }
196
528
  return { focused: true };
197
529
  }
530
+
531
+ case 'navigate': {
532
+ const entry = await _requireEntry(payload);
533
+ const url = payload.url;
534
+ if (!authState.isAuthorizedXUrl(url)) {
535
+ throw _error('navigation target is not an authorized X origin', 'NAVIGATION_TARGET_REFUSED', { stage: 'navigation' });
536
+ }
537
+ const page = await _pageFor(entry);
538
+ const nav = await connectivity.navigateBounded(page, url, {
539
+ timeoutMs: 45000,
540
+ proxyActive: !!entry.proxyFingerprint,
541
+ dnsPinned: !!entry.proxyFingerprint,
542
+ accountLabel: entry.accountUuid || entry.accountId,
543
+ });
544
+ if (!nav.ok) {
545
+ return {
546
+ success: false,
547
+ code: nav.code,
548
+ stage: nav.stage,
549
+ reason: nav.reason,
550
+ error: nav.message,
551
+ painted: nav.painted === true,
552
+ };
553
+ }
554
+ return { success: true };
555
+ }
556
+
557
+ case 'type':
558
+ case 'paste': {
559
+ const entry = await _requireEntry(payload);
560
+ const page = await _pageFor(entry);
561
+ await page.locator(payload.selector).fill(payload.text);
562
+ return { success: true };
563
+ }
564
+
565
+ case 'press': {
566
+ const entry = await _requireEntry(payload);
567
+ const page = await _pageFor(entry);
568
+ await page.keyboard.press(payload.key);
569
+ return { success: true };
570
+ }
571
+
572
+ case 'click': {
573
+ const entry = await _requireEntry(payload);
574
+ const page = await _pageFor(entry);
575
+ await page.locator(payload.selector).click();
576
+ return { success: true };
577
+ }
578
+
579
+ case 'runAction': {
580
+ const entry = await _requireEntry(payload);
581
+ const action = payload.action;
582
+ if (!AUTH_EXEMPT_ACTIONS.has(action)) {
583
+ const gate = await _requireAuthenticated(entry);
584
+ if (!gate.ok) {
585
+ const a = gate.verified.authState;
586
+ const code = a === authState.AUTH_STATE.WRONG_ACCOUNT ? 'WRONG_ACCOUNT'
587
+ : a === authState.AUTH_STATE.CHALLENGE_REQUIRED ? 'CHALLENGE_REQUIRED'
588
+ : 'AUTH_UNVERIFIED';
589
+ return {
590
+ success: false,
591
+ code,
592
+ error: 'The X session is not verified as signed in; the action was not started.',
593
+ failureStage: 'pre_action',
594
+ browserReady: true,
595
+ ...authState.authSummary(gate.verified),
596
+ };
597
+ }
598
+ }
599
+ const page = await _pageFor(entry);
600
+ const { runAction } = require('./actions');
601
+ // Preserve the top-level action result contract (no re-wrapping).
602
+ return await runAction(page, action, payload.payload || payload.args || {});
603
+ }
604
+
198
605
  case 'closeAll': {
606
+ const results = [];
199
607
  for (const [key, entry] of Array.from(contexts.entries())) {
200
- try { await entry.context.close(); } catch { }
201
- try { bi.cleanupSessionRuntimeDirs(entry.sessionsRoot, key); } catch { }
202
- sessionRegistry.releaseLocalLock({ accountUuid: entry.accountUuid, accountId: entry.accountId });
608
+ try {
609
+ await Promise.race([
610
+ entry.context.close(),
611
+ new Promise((_, reject) => setTimeout(() => reject(new Error('timeout')), 15000)),
612
+ ]);
613
+ results.push({ accountKey: key, stopped: true });
614
+ } catch {
615
+ results.push({ accountKey: key, stopped: false });
616
+ continue;
617
+ }
618
+ try { bi.cleanupSessionRuntimeDirs(entry.sessionsRoot, key); } catch { /* safe */ }
619
+ try { sessionRegistry.releaseLocalLock({ accountUuid: entry.accountUuid, accountId: entry.accountId }); } catch { /* safe */ }
203
620
  contexts.delete(key);
204
621
  }
205
- return { closed: true };
622
+ return { closed: results.every((r) => r.stopped), results };
206
623
  }
624
+
207
625
  case 'recoverOrphans': {
208
626
  const mod = require('./sessionHandler');
209
627
  return mod.recoverOrphanedSessions();
210
628
  }
629
+
211
630
  case 'proxy-test': {
212
631
  // No browser: reuse the hardened device-side executor.
213
632
  const mod = require('./sessionHandler');
214
633
  return mod._proxyTest(payload);
215
634
  }
635
+
636
+ case 'connectivity-test': {
637
+ // No browser: per-endpoint DNS/TCP/TLS/HTTP diagnostic, through the
638
+ // configured proxy when one is supplied (never a silent direct bypass).
639
+ const mod = require('./sessionHandler');
640
+ return mod._connectivityTest(payload);
641
+ }
642
+
216
643
  case 'shutdown': {
217
- setImmediate(() => process.exit(0));
218
- return { shuttingDown: true };
644
+ // Await verified close of every owned browser BEFORE the process exits so
645
+ // Chromium flushes its persistent profile. Bounded: a wedged browser must
646
+ // not hang broker shutdown forever.
647
+ const results = [];
648
+ for (const [key, entry] of Array.from(contexts.entries())) {
649
+ try {
650
+ await Promise.race([
651
+ entry.context.close(),
652
+ new Promise((_, reject) => setTimeout(() => reject(new Error('timeout')), 15000)),
653
+ ]);
654
+ results.push({ accountKey: key, stopped: true });
655
+ } catch {
656
+ results.push({ accountKey: key, stopped: false });
657
+ }
658
+ try { bi.cleanupSessionRuntimeDirs(entry.sessionsRoot, key); } catch { /* safe */ }
659
+ try { sessionRegistry.releaseLocalLock({ accountUuid: entry.accountUuid, accountId: entry.accountId }); } catch { /* safe */ }
660
+ contexts.delete(key);
661
+ }
662
+ const allClosed = results.every((r) => r.stopped);
663
+ setImmediate(() => process.exit(allClosed ? 0 : 1));
664
+ return { shuttingDown: true, closed: allClosed, results };
219
665
  }
666
+
220
667
  default:
221
- throw Object.assign(new Error('unknown command ' + command), { code: 'UNKNOWN_COMMAND' });
668
+ throw _error('unknown command ' + command, 'UNKNOWN_COMMAND');
222
669
  }
223
670
  };
671
+
672
+ handler.hasContext = (accountKey) => contexts.has(String(accountKey));
673
+ return handler;
224
674
  }
225
675
 
226
676
  async function main() {
@@ -250,4 +700,4 @@ if (require.main === module) {
250
700
  main();
251
701
  }
252
702
 
253
- module.exports = { buildWorkerHandler, parseArgs };
703
+ module.exports = { buildWorkerHandler, parseArgs, AUTH_EXEMPT_ACTIONS };