@xkwdstore/agent 2.1.5 → 2.1.7

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,703 +1,707 @@
1
- 'use strict';
2
-
3
- /**
4
- * Interactive Browser Worker entry point (TW-manager Agent 2.1.x).
5
- *
6
- * Runs INSIDE an interactive Windows desktop session. It is spawned by the
7
- * machine-wide Broker and connects back over a loopback-only, token-authenticated
8
- * channel. It:
9
- *
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
14
- * - understands ONLY typed browser commands (see brokerWorkerBridge)
15
- * - NEVER reads the device private key
16
- * - NEVER enrolls / registers the device
17
- * - NEVER opens the server WebSocket
18
- *
19
- * The worker is deliberately small: all authority (identity, server connection,
20
- * leases, policy) lives in the broker. The worker is a capability-limited
21
- * executor so a compromised worker cannot impersonate the machine device.
22
- *
23
- * Usage (the broker passes these; an operator never runs this directly):
24
- * node src/worker.js --port <n> --token <one-time> [--chrome <path>]
25
- */
26
-
27
- const path = require('path');
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
- ]);
36
-
37
- function parseArgs(argv) {
38
- const out = {};
39
- for (let i = 0; i < argv.length; i++) {
40
- const a = argv[i];
41
- if (a === '--port') out.port = parseInt(argv[++i], 10);
42
- else if (a.startsWith('--port=')) out.port = parseInt(a.slice(7), 10);
43
- else if (a === '--token') out.token = argv[++i];
44
- else if (a.startsWith('--token=')) out.token = a.slice(8);
45
- else if (a === '--chrome') out.chrome = argv[++i];
46
- else if (a.startsWith('--chrome=')) out.chrome = a.slice(9);
47
- }
48
- return out;
49
- }
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
-
60
- /**
61
- * Build the worker's command handler. The worker owns the browser lifecycle; the
62
- * broker owns everything else. Each command is bound to an account+lease supplied
63
- * by the broker as typed data (never a raw shell command).
64
- */
65
- function buildWorkerHandler(opts) {
66
- const { chromePath } = opts;
67
- // The real browser runtime: reuse the hardened session handler's primitives.
68
- const bi = require('./browserIsolation');
69
- const sessionRegistry = require('./sessionRegistry');
70
- const { getMachineRoot, PROFILES_DIR } = require('./deviceKeyStore');
71
- const { readIdentityMarker } = require('./profilePath');
72
- const { applyCookies } = require('./cookieInjection');
73
- const authState = require('./sessionAuth');
74
-
75
- // Per-account live contexts owned by THIS worker process.
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
- }
144
-
145
- async function startSession(payload) {
146
- const accountKey = _entryKey(payload);
147
- if (!accountKey) throw _error('missing account identity', 'WORKER_NO_ACCOUNT');
148
- if (contexts.has(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
- };
160
- }
161
- const profileDir = payload.profileDir;
162
- _assertProfileOwnership(profileDir, payload);
163
- if (!fs.existsSync(profileDir)) fs.mkdirSync(profileDir, { recursive: true });
164
-
165
- // Local profile lock (agent-local), in addition to the broker's server lease.
166
- const lock = sessionRegistry.acquireLocalLock({
167
- accountUuid: payload.accountUuid || null,
168
- accountId: payload.accountId || accountKey,
169
- profilePath: profileDir,
170
- });
171
- if (!lock.acquired) {
172
- throw _error('local profile lock refused: ' + (lock.code || 'LOCAL_SESSION_EXISTS'), lock.code || 'LOCAL_SESSION_EXISTS');
173
- }
174
-
175
- const sessionsRoot = path.join(getMachineRoot(), 'state', 'sessions');
176
- const runtimeDirs = bi.createSessionRuntimeDirs(sessionsRoot, accountKey);
177
-
178
- const releaseLock = () => {
179
- try { sessionRegistry.releaseLocalLock({ accountUuid: payload.accountUuid, accountId: payload.accountId || accountKey }); } catch { /* safe */ }
180
- };
181
-
182
- const requireProxy = payload.requireProxy === true;
183
- // The broker may hand us EITHER an already-parsed proxy identity OR a raw
184
- // connection string. Both are normalized here through the ONE canonical
185
- // parser so a payload-shape change can never again surface as the opaque
186
- // "proxy binding failed": every failure is classified with a typed code and
187
- // a non-secret description.
188
- const coerced = bi.coerceProxyIdentity(payload.proxy || null);
189
- let proxy = null;
190
- let proxyOption = null;
191
- if (requireProxy) {
192
- if (!coerced.ok) {
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
- });
201
- }
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
- }
215
- const bind = bi.buildProxyLaunchBinding(proxy, { allowInlineCredentials: process.env.XKWDSTORE_INLINE_PROXY_CREDENTIALS === 'true' });
216
- if (!bind.ok) {
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
- });
225
- }
226
- proxyOption = bind.proxyOption;
227
- if (!proxyOption) {
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
- });
233
- }
234
- }
235
-
236
- const args = bi.buildLaunchArgs({
237
- requireProxy,
238
- proxyServerUrl: requireProxy && !proxyOption && proxy ? proxy.server : null,
239
- proxyHostForDns: requireProxy && proxy ? proxy.host : null,
240
- baseArgs: ['--no-first-run', '--no-default-browser-check', '--start-maximized'],
241
- });
242
-
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
- }
281
-
282
- let context;
283
- try {
284
- context = await _launch(payload, profileDir, proxyOption, args);
285
- } catch (err) {
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
- });
291
- }
292
-
293
- // Record the real browser PID so crash recovery can prove ownership of the
294
- // exact process (never "any chrome.exe"). Resolved by exact profile dir.
295
- let browserPid = null;
296
- try { browserPid = require('./brokerWorkerBridge').resolveChromePidForProfile(profileDir); } catch { browserPid = null; }
297
- if (browserPid) {
298
- sessionRegistry.markRunning({ accountUuid: payload.accountUuid || null, accountId: payload.accountId || accountKey, browserPid });
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
-
336
- context.on('close', () => {
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);
343
- });
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
- };
401
- }
402
-
403
- async function stopSession(payload) {
404
- const accountKey = _entryKey(payload);
405
- const entry = contexts.get(accountKey);
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 */ }
428
- contexts.delete(accountKey);
429
- return { stopped: true, running: false, accountKey };
430
- }
431
-
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) {
455
- switch (command) {
456
- case 'startSession': return startSession(payload);
457
-
458
- case 'stopSession': return stopSession(payload);
459
-
460
- case 'getStatus': {
461
- const accountKey = _entryKey(payload);
462
- const entry = contexts.get(accountKey);
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 };
522
- }
523
-
524
- case 'focus': {
525
- const entry = await _requireEntry(payload);
526
- const page = await _pageFor(entry);
527
- try { await page.bringToFront(); } catch { /* best effort */ }
528
- return { focused: true };
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
-
605
- case 'closeAll': {
606
- const results = [];
607
- for (const [key, entry] of Array.from(contexts.entries())) {
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 */ }
620
- contexts.delete(key);
621
- }
622
- return { closed: results.every((r) => r.stopped), results };
623
- }
624
-
625
- case 'recoverOrphans': {
626
- const mod = require('./sessionHandler');
627
- return mod.recoverOrphanedSessions();
628
- }
629
-
630
- case 'proxy-test': {
631
- // No browser: reuse the hardened device-side executor.
632
- const mod = require('./sessionHandler');
633
- return mod._proxyTest(payload);
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
-
643
- case 'shutdown': {
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 };
665
- }
666
-
667
- default:
668
- throw _error('unknown command ' + command, 'UNKNOWN_COMMAND');
669
- }
670
- };
671
-
672
- handler.hasContext = (accountKey) => contexts.has(String(accountKey));
673
- return handler;
674
- }
675
-
676
- async function main() {
677
- const args = parseArgs(process.argv.slice(2));
678
- if (!args.port || !args.token) {
679
- console.error('worker: --port and --token are required (spawned by the broker)');
680
- process.exit(2);
681
- }
682
- const { resolveChromeOrFail } = require('./chromeDetector');
683
- let chromePath = args.chrome;
684
- if (!chromePath) {
685
- try { chromePath = resolveChromeOrFail().chromePath; } catch { chromePath = null; }
686
- }
687
- const bridge = require('./brokerWorkerBridge');
688
- const handler = buildWorkerHandler({ chromePath });
689
- try {
690
- const conn = await bridge.openWorkerChannel({ port: args.port, token: args.token, handler });
691
- // The worker stays alive until the broker closes the channel.
692
- conn.on('close', () => process.exit(0));
693
- } catch (e) {
694
- console.error('worker: could not attach to broker: ' + ((e && e.message) || 'unknown'));
695
- process.exit(3);
696
- }
697
- }
698
-
699
- if (require.main === module) {
700
- main();
701
- }
702
-
703
- module.exports = { buildWorkerHandler, parseArgs, AUTH_EXEMPT_ACTIONS };
1
+ 'use strict';
2
+
3
+ /**
4
+ * Interactive Browser Worker entry point (TW-manager Agent 2.1.x).
5
+ *
6
+ * Runs INSIDE an interactive Windows desktop session. It is spawned by the
7
+ * machine-wide Broker and connects back over a loopback-only, token-authenticated
8
+ * channel. It:
9
+ *
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
14
+ * - understands ONLY typed browser commands (see brokerWorkerBridge)
15
+ * - NEVER reads the device private key
16
+ * - NEVER enrolls / registers the device
17
+ * - NEVER opens the server WebSocket
18
+ *
19
+ * The worker is deliberately small: all authority (identity, server connection,
20
+ * leases, policy) lives in the broker. The worker is a capability-limited
21
+ * executor so a compromised worker cannot impersonate the machine device.
22
+ *
23
+ * Usage (the broker passes these; an operator never runs this directly):
24
+ * node src/worker.js --port <n> --token <one-time> [--chrome <path>]
25
+ */
26
+
27
+ const path = require('path');
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
+ ]);
36
+
37
+ function parseArgs(argv) {
38
+ const out = {};
39
+ for (let i = 0; i < argv.length; i++) {
40
+ const a = argv[i];
41
+ if (a === '--port') out.port = parseInt(argv[++i], 10);
42
+ else if (a.startsWith('--port=')) out.port = parseInt(a.slice(7), 10);
43
+ else if (a === '--token') out.token = argv[++i];
44
+ else if (a.startsWith('--token=')) out.token = a.slice(8);
45
+ else if (a === '--chrome') out.chrome = argv[++i];
46
+ else if (a.startsWith('--chrome=')) out.chrome = a.slice(9);
47
+ }
48
+ return out;
49
+ }
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
+
60
+ /**
61
+ * Build the worker's command handler. The worker owns the browser lifecycle; the
62
+ * broker owns everything else. Each command is bound to an account+lease supplied
63
+ * by the broker as typed data (never a raw shell command).
64
+ */
65
+ function buildWorkerHandler(opts) {
66
+ const { chromePath } = opts;
67
+ // The real browser runtime: reuse the hardened session handler's primitives.
68
+ const bi = require('./browserIsolation');
69
+ const sessionRegistry = require('./sessionRegistry');
70
+ const { getMachineRoot, PROFILES_DIR } = require('./deviceKeyStore');
71
+ const { readIdentityMarker } = require('./profilePath');
72
+ const { applyCookies } = require('./cookieInjection');
73
+ const authState = require('./sessionAuth');
74
+
75
+ // Per-account live contexts owned by THIS worker process.
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
+ }
144
+
145
+ async function startSession(payload) {
146
+ const accountKey = _entryKey(payload);
147
+ if (!accountKey) throw _error('missing account identity', 'WORKER_NO_ACCOUNT');
148
+ if (contexts.has(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
+ };
160
+ }
161
+ const profileDir = payload.profileDir;
162
+ _assertProfileOwnership(profileDir, payload);
163
+ if (!fs.existsSync(profileDir)) fs.mkdirSync(profileDir, { recursive: true });
164
+
165
+ // Local profile lock (agent-local), in addition to the broker's server lease.
166
+ const lock = sessionRegistry.acquireLocalLock({
167
+ accountUuid: payload.accountUuid || null,
168
+ accountId: payload.accountId || accountKey,
169
+ profilePath: profileDir,
170
+ });
171
+ if (!lock.acquired) {
172
+ throw _error('local profile lock refused: ' + (lock.code || 'LOCAL_SESSION_EXISTS'), lock.code || 'LOCAL_SESSION_EXISTS');
173
+ }
174
+
175
+ const sessionsRoot = path.join(getMachineRoot(), 'state', 'sessions');
176
+ const runtimeDirs = bi.createSessionRuntimeDirs(sessionsRoot, accountKey);
177
+
178
+ const releaseLock = () => {
179
+ try { sessionRegistry.releaseLocalLock({ accountUuid: payload.accountUuid, accountId: payload.accountId || accountKey }); } catch { /* safe */ }
180
+ };
181
+
182
+ const requireProxy = payload.requireProxy === true;
183
+ // The broker may hand us EITHER an already-parsed proxy identity OR a raw
184
+ // connection string. Both are normalized here through the ONE canonical
185
+ // parser so a payload-shape change can never again surface as the opaque
186
+ // "proxy binding failed": every failure is classified with a typed code and
187
+ // a non-secret description.
188
+ const coerced = bi.coerceProxyIdentity(payload.proxy || null);
189
+ let proxy = null;
190
+ let proxyOption = null;
191
+ if (requireProxy) {
192
+ if (!coerced.ok) {
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
+ });
201
+ }
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
+ }
215
+ const bind = bi.buildProxyLaunchBinding(proxy, { allowInlineCredentials: process.env.XKWDSTORE_INLINE_PROXY_CREDENTIALS === 'true' });
216
+ if (!bind.ok) {
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
+ });
225
+ }
226
+ proxyOption = bind.proxyOption;
227
+ if (!proxyOption) {
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
+ });
233
+ }
234
+ }
235
+
236
+ const args = bi.buildLaunchArgs({
237
+ requireProxy,
238
+ proxyServerUrl: requireProxy && !proxyOption && proxy ? proxy.server : null,
239
+ proxyHostForDns: requireProxy && proxy ? proxy.host : null,
240
+ // A credential-bearing proxy goes through Playwright's authenticated-proxy
241
+ // path, whose HTTP/2 negotiation stalls on Google properties. Pin HTTP/1.1
242
+ // for that case only (see buildLaunchArgs JSDoc).
243
+ proxyAuthenticated: Boolean(proxy && proxy.username !== undefined && proxy.username !== ''),
244
+ baseArgs: ['--no-first-run', '--no-default-browser-check', '--start-maximized'],
245
+ });
246
+
247
+ // ── Proxy egress verification BEFORE any authentication traffic ──────────
248
+ // A proxy that accepts TCP but does not tunnel (or rejects credentials) must
249
+ // never be allowed to reach X with the stored cookies. This mirrors the
250
+ // direct runtime's fail-closed verification; a transport failure stays
251
+ // distinct from a cookie/logout outcome.
252
+ if (requireProxy && proxy) {
253
+ let iso;
254
+ try {
255
+ iso = await require('./proxyEgress').verifyProxyIsolation(
256
+ { server: proxy.server, username: proxy.username, password: proxy.password },
257
+ {},
258
+ );
259
+ } catch {
260
+ iso = { ok: false, code: 'PROXY_EGRESS_UNREACHABLE' };
261
+ }
262
+ if (!iso || !iso.ok) {
263
+ releaseLock();
264
+ try { bi.cleanupSessionRuntimeDirs(sessionsRoot, accountKey); } catch { /* safe */ }
265
+ const rawCode = String((iso && iso.code) || 'PROXY_UNREACHABLE');
266
+ const reason = String((iso && iso.reason) || '');
267
+ const code = rawCode === 'PROXY_EGRESS_UNREACHABLE'
268
+ ? (/407|auth/i.test(reason) ? 'PROXY_AUTH_FAILED'
269
+ : /refused connect|ECONNREFUSED/i.test(reason) ? 'PROXY_TCP_REFUSED'
270
+ : /timeout|timed out/i.test(reason) ? 'PROXY_CONNECT_TIMEOUT'
271
+ : /tls/i.test(reason) ? 'PROXY_TLS_FAILED'
272
+ : /ENOTFOUND|getaddrinfo/i.test(reason) ? 'PROXY_DNS_FAILED'
273
+ : 'PROXY_UNREACHABLE')
274
+ : rawCode;
275
+ throw _error('proxy egress verification failed', code, {
276
+ stage: 'proxy_egress',
277
+ accountId: payload.accountId || null,
278
+ accountUuid: payload.accountUuid || null,
279
+ proxyId: payload.proxyId != null ? payload.proxyId : null,
280
+ proxy: bi.maskProxyForLog(proxy),
281
+ reason: 'proxy_egress_failed',
282
+ });
283
+ }
284
+ }
285
+
286
+ let context;
287
+ try {
288
+ context = await _launch(payload, profileDir, proxyOption, args);
289
+ } catch (err) {
290
+ releaseLock();
291
+ try { bi.cleanupSessionRuntimeDirs(sessionsRoot, accountKey); } catch { /* safe */ }
292
+ throw _error('launch failed: ' + authState.classifyNavigationError(err).reason, 'WORKER_LAUNCH_FAILED', {
293
+ stage: 'launch', accountId: payload.accountId || null, accountUuid: payload.accountUuid || null,
294
+ });
295
+ }
296
+
297
+ // Record the real browser PID so crash recovery can prove ownership of the
298
+ // exact process (never "any chrome.exe"). Resolved by exact profile dir.
299
+ let browserPid = null;
300
+ try { browserPid = require('./brokerWorkerBridge').resolveChromePidForProfile(profileDir); } catch { browserPid = null; }
301
+ if (browserPid) {
302
+ sessionRegistry.markRunning({ accountUuid: payload.accountUuid || null, accountId: payload.accountId || accountKey, browserPid });
303
+ }
304
+
305
+ const entry = {
306
+ context,
307
+ page: null,
308
+ runtimeDirs,
309
+ sessionsRoot,
310
+ profileDir,
311
+ accountUuid: payload.accountUuid || null,
312
+ accountId: payload.accountId || accountKey,
313
+ expectedUsername: payload.expectedUsername || payload.username || null,
314
+ proxyFingerprint: proxy ? bi.proxyIdentityFingerprint(proxy) : null,
315
+ browserPid,
316
+ lastAuth: null,
317
+ // 2.1.5 containment: bounded navigation + stalled-tab watchdog.
318
+ navGuard: null,
319
+ connectivityEvents: [],
320
+ };
321
+ contexts.set(accountKey, entry);
322
+
323
+ // ── 2.1.5 navigation guard ────────────────────────────────────────────────
324
+ // A proxy that accepts TCP but never answers CONNECT leaves the tab on
325
+ // about:blank with a permanent spinner. The guard bounds every navigation and
326
+ // replaces a stalled tab with a diagnostic page so a failed request can never
327
+ // stay pending indefinitely.
328
+ try {
329
+ entry.navGuard = connectivity.installNavigationGuard(context, {
330
+ accountLabel: entry.accountUuid || entry.accountId || null,
331
+ onEvent: (event, detail) => {
332
+ try {
333
+ entry.connectivityEvents.push({ at: new Date().toISOString(), event, ...detail });
334
+ if (entry.connectivityEvents.length > 25) entry.connectivityEvents.shift();
335
+ } catch { /* never break the session */ }
336
+ },
337
+ });
338
+ } catch { /* containment is best effort; launch safety is unaffected */ }
339
+
340
+ context.on('close', () => {
341
+ const current = contexts.get(accountKey);
342
+ if (current !== entry) return;
343
+ try { if (entry.navGuard) entry.navGuard.stop(); } catch { /* safe */ }
344
+ try { bi.cleanupSessionRuntimeDirs(entry.sessionsRoot, accountKey); } catch { /* safe */ }
345
+ try { sessionRegistry.releaseLocalLock({ accountUuid: entry.accountUuid, accountId: entry.accountId }); } catch { /* safe */ }
346
+ contexts.delete(accountKey);
347
+ });
348
+
349
+ // ── Canonical startup: verify BEFORE writing cookies ──────────────────────
350
+ // Never overwrite a newer authenticated profile with stale imported cookies.
351
+ let restored;
352
+ try {
353
+ const page = await _pageFor(entry);
354
+ restored = await authState.restoreAndVerify({
355
+ page,
356
+ context,
357
+ cookies: Array.isArray(payload.cookies) ? payload.cookies : null,
358
+ url: payload.url || null,
359
+ expectedUsername: entry.expectedUsername,
360
+ applyCookies,
361
+ navigationTimeoutMs: Number.isFinite(payload.navigationTimeoutMs) ? payload.navigationTimeoutMs : 45000,
362
+ verifyTimeoutMs: Number.isFinite(payload.verifyTimeoutMs) ? payload.verifyTimeoutMs : 8000,
363
+ });
364
+ entry.lastAuth = restored;
365
+ // A startup navigation that never completed must not leave the visible tab
366
+ // on about:blank: paint the actionable diagnostic page for the operator.
367
+ if (restored && restored.navigationOk === false) {
368
+ const failure = connectivity.classifyNavigationFailure(
369
+ Object.assign(new Error(restored.reason || 'navigation failed'), { code: restored.code }),
370
+ { url: payload.url || 'https://x.com/home', proxyActive: requireProxy, dnsPinned: requireProxy && !!proxy },
371
+ );
372
+ try {
373
+ await connectivity.paintNavigationFailure(page, {
374
+ ...failure,
375
+ url: payload.url || 'https://x.com/home',
376
+ accountLabel: entry.accountUuid || entry.accountId,
377
+ });
378
+ } catch { /* containment is best effort */ }
379
+ }
380
+ } catch (err) {
381
+ restored = {
382
+ authState: authState.AUTH_STATE.UNKNOWN,
383
+ reason: 'startup_verification_failed',
384
+ stage: 'verify',
385
+ browserReady: true,
386
+ };
387
+ entry.lastAuth = restored;
388
+ }
389
+
390
+ return {
391
+ started: true,
392
+ accountKey,
393
+ profileDir,
394
+ visible: true,
395
+ browserReady: true,
396
+ authState: restored.authState,
397
+ reason: restored.reason || null,
398
+ stage: restored.stage || null,
399
+ handle: restored.handle || null,
400
+ url: restored.url || null,
401
+ cookieState: restored.cookieState || null,
402
+ cookieApplied: restored.cookieApplied || 0,
403
+ cookieRejected: restored.cookieRejected || 0,
404
+ };
405
+ }
406
+
407
+ async function stopSession(payload) {
408
+ const accountKey = _entryKey(payload);
409
+ const entry = contexts.get(accountKey);
410
+ if (!entry) return { stopped: false, running: false, reason: 'not_running' };
411
+ // Await the REAL close, bounded. A stop is never reported while Chromium is
412
+ // still flushing its persistent profile.
413
+ let closed = false;
414
+ try {
415
+ if (typeof entry.context.isClosed === 'function' && entry.context.isClosed()) {
416
+ closed = true;
417
+ } else {
418
+ await Promise.race([
419
+ entry.context.close(),
420
+ new Promise((_, reject) => setTimeout(() => reject(Object.assign(new Error('browser close timed out'), { code: 'WORKER_STOP_UNVERIFIED' })), 20000)),
421
+ ]);
422
+ closed = typeof entry.context.isClosed === 'function' ? entry.context.isClosed() : true;
423
+ }
424
+ } catch (err) {
425
+ throw _error('browser close could not be verified', 'WORKER_STOP_UNVERIFIED', { stage: 'stop', accountId: entry.accountId, accountUuid: entry.accountUuid });
426
+ }
427
+ if (!closed) {
428
+ throw _error('browser close could not be verified', 'WORKER_STOP_UNVERIFIED', { stage: 'stop', accountId: entry.accountId, accountUuid: entry.accountUuid });
429
+ }
430
+ try { bi.cleanupSessionRuntimeDirs(entry.sessionsRoot, accountKey); } catch { /* safe */ }
431
+ try { sessionRegistry.releaseLocalLock({ accountUuid: entry.accountUuid, accountId: entry.accountId }); } catch { /* safe */ }
432
+ contexts.delete(accountKey);
433
+ return { stopped: true, running: false, accountKey };
434
+ }
435
+
436
+ async function _requireEntry(payload) {
437
+ const accountKey = _entryKey(payload);
438
+ const entry = contexts.get(accountKey);
439
+ if (!entry) throw _error('Session not found', 'SESSION_NOT_FOUND', { accountId: payload.accountId || null, accountUuid: payload.accountUuid || null });
440
+ return entry;
441
+ }
442
+
443
+ /** Block authenticated actions before side effects when auth is unverified. */
444
+ async function _requireAuthenticated(entry) {
445
+ const verified = await _verify(entry, 2500);
446
+ const s = verified.authState;
447
+ const definiteFailure = s === authState.AUTH_STATE.SIGNED_OUT
448
+ || s === authState.AUTH_STATE.WRONG_ACCOUNT
449
+ || s === authState.AUTH_STATE.CHALLENGE_REQUIRED;
450
+ const observedUnknown = s === authState.AUTH_STATE.UNKNOWN
451
+ && verified.reason !== 'no_browser_signal';
452
+ if (definiteFailure || observedUnknown) {
453
+ return { ok: false, verified };
454
+ }
455
+ return { ok: true, verified };
456
+ }
457
+
458
+ const handler = async function handler(command, payload) {
459
+ switch (command) {
460
+ case 'startSession': return startSession(payload);
461
+
462
+ case 'stopSession': return stopSession(payload);
463
+
464
+ case 'getStatus': {
465
+ const accountKey = _entryKey(payload);
466
+ const entry = contexts.get(accountKey);
467
+ if (!entry) {
468
+ return {
469
+ running: false, browserReady: false, accountKey,
470
+ authState: authState.AUTH_STATE.UNKNOWN, reason: 'no_browser', stage: 'status',
471
+ loggedIn: false, contexts: contexts.size,
472
+ };
473
+ }
474
+ const last = entry.lastAuth || {};
475
+ const pageUrl = (() => { try { return entry.page && !entry.page.isClosed() ? entry.page.url() : null; } catch { return null; } })();
476
+ return {
477
+ running: true, browserReady: true, accountKey, contexts: contexts.size,
478
+ authState: last.authState || authState.AUTH_STATE.UNKNOWN,
479
+ reason: last.reason || null,
480
+ stage: last.stage || 'status',
481
+ handle: last.handle || null,
482
+ loggedIn: last.authState === authState.AUTH_STATE.AUTHENTICATED,
483
+ url: pageUrl,
484
+ // 2.1.5 diagnostics: a tab sitting on about:blank is never "fine".
485
+ pageStalled: pageUrl === 'about:blank',
486
+ browser: browserLaunch.describeBrowser(chromePath),
487
+ connectivity: {
488
+ guard: entry.navGuard ? entry.navGuard.options : null,
489
+ stalledPainted: entry.navGuard ? entry.navGuard.stats.painted : 0,
490
+ recentEvents: entry.connectivityEvents.slice(-5),
491
+ },
492
+ };
493
+ }
494
+
495
+ case 'checkAuth':
496
+ case 'refreshSession': {
497
+ const entry = await _requireEntry(payload);
498
+ const page = await _pageFor(entry);
499
+ if (command === 'refreshSession') {
500
+ // Bounded reload: a stalled refresh must not leave the visible tab on
501
+ // about:blank with a spinner.
502
+ let current = '';
503
+ try { current = page.url(); } catch { current = ''; }
504
+ const target = authState.isAuthorizedXUrl(current) ? current : 'https://x.com/home';
505
+ const nav = await connectivity.navigateBounded(page, target, {
506
+ timeoutMs: 30000,
507
+ proxyActive: !!entry.proxyFingerprint,
508
+ dnsPinned: !!entry.proxyFingerprint,
509
+ accountLabel: entry.accountUuid || entry.accountId,
510
+ });
511
+ if (!nav.ok) {
512
+ return {
513
+ success: false,
514
+ code: nav.code,
515
+ stage: nav.stage,
516
+ reason: nav.reason,
517
+ error: nav.message,
518
+ painted: nav.painted === true,
519
+ browserReady: true,
520
+ ...authState.authSummary(entry.lastAuth),
521
+ };
522
+ }
523
+ }
524
+ const verified = await _verify(entry, 8000);
525
+ return { success: true, browserReady: true, ...authState.authSummary(verified), handle: verified.handle || null, url: verified.url || null };
526
+ }
527
+
528
+ case 'focus': {
529
+ const entry = await _requireEntry(payload);
530
+ const page = await _pageFor(entry);
531
+ try { await page.bringToFront(); } catch { /* best effort */ }
532
+ return { focused: true };
533
+ }
534
+
535
+ case 'navigate': {
536
+ const entry = await _requireEntry(payload);
537
+ const url = payload.url;
538
+ if (!authState.isAuthorizedXUrl(url)) {
539
+ throw _error('navigation target is not an authorized X origin', 'NAVIGATION_TARGET_REFUSED', { stage: 'navigation' });
540
+ }
541
+ const page = await _pageFor(entry);
542
+ const nav = await connectivity.navigateBounded(page, url, {
543
+ timeoutMs: 45000,
544
+ proxyActive: !!entry.proxyFingerprint,
545
+ dnsPinned: !!entry.proxyFingerprint,
546
+ accountLabel: entry.accountUuid || entry.accountId,
547
+ });
548
+ if (!nav.ok) {
549
+ return {
550
+ success: false,
551
+ code: nav.code,
552
+ stage: nav.stage,
553
+ reason: nav.reason,
554
+ error: nav.message,
555
+ painted: nav.painted === true,
556
+ };
557
+ }
558
+ return { success: true };
559
+ }
560
+
561
+ case 'type':
562
+ case 'paste': {
563
+ const entry = await _requireEntry(payload);
564
+ const page = await _pageFor(entry);
565
+ await page.locator(payload.selector).fill(payload.text);
566
+ return { success: true };
567
+ }
568
+
569
+ case 'press': {
570
+ const entry = await _requireEntry(payload);
571
+ const page = await _pageFor(entry);
572
+ await page.keyboard.press(payload.key);
573
+ return { success: true };
574
+ }
575
+
576
+ case 'click': {
577
+ const entry = await _requireEntry(payload);
578
+ const page = await _pageFor(entry);
579
+ await page.locator(payload.selector).click();
580
+ return { success: true };
581
+ }
582
+
583
+ case 'runAction': {
584
+ const entry = await _requireEntry(payload);
585
+ const action = payload.action;
586
+ if (!AUTH_EXEMPT_ACTIONS.has(action)) {
587
+ const gate = await _requireAuthenticated(entry);
588
+ if (!gate.ok) {
589
+ const a = gate.verified.authState;
590
+ const code = a === authState.AUTH_STATE.WRONG_ACCOUNT ? 'WRONG_ACCOUNT'
591
+ : a === authState.AUTH_STATE.CHALLENGE_REQUIRED ? 'CHALLENGE_REQUIRED'
592
+ : 'AUTH_UNVERIFIED';
593
+ return {
594
+ success: false,
595
+ code,
596
+ error: 'The X session is not verified as signed in; the action was not started.',
597
+ failureStage: 'pre_action',
598
+ browserReady: true,
599
+ ...authState.authSummary(gate.verified),
600
+ };
601
+ }
602
+ }
603
+ const page = await _pageFor(entry);
604
+ const { runAction } = require('./actions');
605
+ // Preserve the top-level action result contract (no re-wrapping).
606
+ return await runAction(page, action, payload.payload || payload.args || {});
607
+ }
608
+
609
+ case 'closeAll': {
610
+ const results = [];
611
+ for (const [key, entry] of Array.from(contexts.entries())) {
612
+ try {
613
+ await Promise.race([
614
+ entry.context.close(),
615
+ new Promise((_, reject) => setTimeout(() => reject(new Error('timeout')), 15000)),
616
+ ]);
617
+ results.push({ accountKey: key, stopped: true });
618
+ } catch {
619
+ results.push({ accountKey: key, stopped: false });
620
+ continue;
621
+ }
622
+ try { bi.cleanupSessionRuntimeDirs(entry.sessionsRoot, key); } catch { /* safe */ }
623
+ try { sessionRegistry.releaseLocalLock({ accountUuid: entry.accountUuid, accountId: entry.accountId }); } catch { /* safe */ }
624
+ contexts.delete(key);
625
+ }
626
+ return { closed: results.every((r) => r.stopped), results };
627
+ }
628
+
629
+ case 'recoverOrphans': {
630
+ const mod = require('./sessionHandler');
631
+ return mod.recoverOrphanedSessions();
632
+ }
633
+
634
+ case 'proxy-test': {
635
+ // No browser: reuse the hardened device-side executor.
636
+ const mod = require('./sessionHandler');
637
+ return mod._proxyTest(payload);
638
+ }
639
+
640
+ case 'connectivity-test': {
641
+ // No browser: per-endpoint DNS/TCP/TLS/HTTP diagnostic, through the
642
+ // configured proxy when one is supplied (never a silent direct bypass).
643
+ const mod = require('./sessionHandler');
644
+ return mod._connectivityTest(payload);
645
+ }
646
+
647
+ case 'shutdown': {
648
+ // Await verified close of every owned browser BEFORE the process exits so
649
+ // Chromium flushes its persistent profile. Bounded: a wedged browser must
650
+ // not hang broker shutdown forever.
651
+ const results = [];
652
+ for (const [key, entry] of Array.from(contexts.entries())) {
653
+ try {
654
+ await Promise.race([
655
+ entry.context.close(),
656
+ new Promise((_, reject) => setTimeout(() => reject(new Error('timeout')), 15000)),
657
+ ]);
658
+ results.push({ accountKey: key, stopped: true });
659
+ } catch {
660
+ results.push({ accountKey: key, stopped: false });
661
+ }
662
+ try { bi.cleanupSessionRuntimeDirs(entry.sessionsRoot, key); } catch { /* safe */ }
663
+ try { sessionRegistry.releaseLocalLock({ accountUuid: entry.accountUuid, accountId: entry.accountId }); } catch { /* safe */ }
664
+ contexts.delete(key);
665
+ }
666
+ const allClosed = results.every((r) => r.stopped);
667
+ setImmediate(() => process.exit(allClosed ? 0 : 1));
668
+ return { shuttingDown: true, closed: allClosed, results };
669
+ }
670
+
671
+ default:
672
+ throw _error('unknown command ' + command, 'UNKNOWN_COMMAND');
673
+ }
674
+ };
675
+
676
+ handler.hasContext = (accountKey) => contexts.has(String(accountKey));
677
+ return handler;
678
+ }
679
+
680
+ async function main() {
681
+ const args = parseArgs(process.argv.slice(2));
682
+ if (!args.port || !args.token) {
683
+ console.error('worker: --port and --token are required (spawned by the broker)');
684
+ process.exit(2);
685
+ }
686
+ const { resolveChromeOrFail } = require('./chromeDetector');
687
+ let chromePath = args.chrome;
688
+ if (!chromePath) {
689
+ try { chromePath = resolveChromeOrFail().chromePath; } catch { chromePath = null; }
690
+ }
691
+ const bridge = require('./brokerWorkerBridge');
692
+ const handler = buildWorkerHandler({ chromePath });
693
+ try {
694
+ const conn = await bridge.openWorkerChannel({ port: args.port, token: args.token, handler });
695
+ // The worker stays alive until the broker closes the channel.
696
+ conn.on('close', () => process.exit(0));
697
+ } catch (e) {
698
+ console.error('worker: could not attach to broker: ' + ((e && e.message) || 'unknown'));
699
+ process.exit(3);
700
+ }
701
+ }
702
+
703
+ if (require.main === module) {
704
+ main();
705
+ }
706
+
707
+ module.exports = { buildWorkerHandler, parseArgs, AUTH_EXEMPT_ACTIONS };