@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.
@@ -1,377 +1,377 @@
1
- 'use strict';
2
-
3
- /**
4
- * Broker <-> interactive Browser Worker bridge (TW-manager Agent 2.1.0).
5
- *
6
- * ARCHITECTURE
7
- * ------------
8
- * Two distinct processes/roles:
9
- *
10
- * BROKER (machine-wide, silent, one per machine)
11
- * - owns device identity + the device private key
12
- * - owns the server WebSocket connection
13
- * - owns leases + the machine-local session registry
14
- * - holds the machine-wide named mutex
15
- * - NEVER launches Chromium
16
- *
17
- * BROWSER WORKER (per interactive desktop session)
18
- * - runs INSIDE the active interactive Windows session
19
- * - launches and drives Chromium for one account session
20
- * - receives ONLY typed browser commands from the broker
21
- * - CANNOT read the device private key
22
- * - CANNOT enroll/register a device
23
- *
24
- * TRANSPORT
25
- * ---------
26
- * A loopback-only TCP channel on 127.0.0.1 with an ephemeral port chosen by the
27
- * broker. It is NEVER bound to 0.0.0.0/LAN/Tailscale/public interfaces.
28
- *
29
- * SECURITY
30
- * --------
31
- * - The broker generates a 256-bit one-time channel token per worker; the
32
- * worker must present it on the first frame or the socket is destroyed.
33
- * - Every message is a typed, bounded JSON frame with a strict command
34
- * allowlist. There is NO arbitrary command execution: the worker only
35
- * understands the browser command types below.
36
- * - The channel carries no device credential and no proxy secret; the proxy
37
- * binding for a session is passed as a typed descriptor, and the worker
38
- * never logs it.
39
- * - Messages are size-bounded; a peer that exceeds the bound is disconnected.
40
- *
41
- * This module is dependency-free (node:net only).
42
- */
43
-
44
- const os = require('os');
45
- const net = require('net');
46
- const crypto = require('crypto');
47
-
48
- // The ONLY command types a worker will execute. Anything else is refused.
49
- const WORKER_COMMANDS = Object.freeze(new Set([
50
- 'startSession',
51
- 'stopSession',
52
- 'refreshSession',
53
- 'getStatus',
54
- 'checkAuth',
55
- 'navigate',
56
- 'type',
57
- 'paste',
58
- 'press',
59
- 'click',
60
- 'runAction',
61
- 'focus',
62
- 'closeAll',
63
- 'recoverOrphans',
64
- 'proxy-test',
65
- 'connectivity-test',
66
- 'shutdown',
67
- ]));
68
-
69
- const MAX_FRAME_BYTES = 256 * 1024;
70
- const CHANNEL_TOKEN_BYTES = 32;
71
-
72
- class BridgeError extends Error {
73
- constructor(message, code) {
74
- super(message);
75
- this.code = code || 'BRIDGE_ERROR';
76
- this.name = 'BridgeError';
77
- }
78
- }
79
-
80
- /** True when a socket address is loopback-only. */
81
- function isLoopback(address) {
82
- if (!address) return false;
83
- return address === '127.0.0.1'
84
- || address === '::1'
85
- || address === '::ffff:127.0.0.1'
86
- || address.startsWith('127.');
87
- }
88
-
89
- function newChannelToken() {
90
- return crypto.randomBytes(CHANNEL_TOKEN_BYTES).toString('base64url');
91
- }
92
-
93
- /**
94
- * Open the broker side of the bridge: a loopback-only listener that accepts ONE
95
- * worker connection, authenticated by the channel token.
96
- *
97
- * @param {object} opts
98
- * @param {string} opts.token — the one-time channel token the worker must present
99
- * @param {function} opts.onCommand — async (command, payload) => result
100
- * @returns {Promise<{port:number, close:function, waitForWorker:function, send:function}>}
101
- */
102
- function openBrokerChannel(opts) {
103
- const token = opts.token || newChannelToken();
104
-
105
- let workerSocket = null;
106
- let authed = false;
107
- // Result buffer keyed by command id, so `send()` + `takeResult(id)` / `call()`
108
- // can be used. Bounded so a runaway peer cannot grow memory.
109
- const results = new Map();
110
- const order = [];
111
- const waiters = new Map();
112
-
113
- function _storeResult(id, r) {
114
- if (id == null) return;
115
- results.set(id, r);
116
- order.push(id);
117
- while (order.length > 200) { results.delete(order.shift()); }
118
- const w = waiters.get(id);
119
- if (w) { waiters.delete(id); try { w(r); } catch { } }
120
- }
121
-
122
- const server = net.createServer((socket) => {
123
- // Reject any non-loopback peer outright (defense in depth: we bind loopback,
124
- // so this can only fire if something unusual happens).
125
- if (!isLoopback(socket.remoteAddress)) { socket.destroy(); return; }
126
- if (workerSocket && !workerSocket.destroyed) { socket.destroy(); return; } // one worker per channel
127
- workerSocket = socket;
128
- authed = false;
129
- let buffer = Buffer.alloc(0);
130
-
131
- const handleLine = (line) => {
132
- let msg;
133
- try { msg = JSON.parse(line); } catch { socket.destroy(); return; }
134
- if (!msg || typeof msg !== 'object') { socket.destroy(); return; }
135
- if (!authed) {
136
- if (msg.type !== 'auth' || msg.token !== token) { socket.destroy(); return; } // token single-use
137
- authed = true;
138
- socket.write(JSON.stringify({ type: 'auth-ok' }) + '\n');
139
- return;
140
- }
141
- if (msg.type === 'result') { _storeResult(msg.id, msg); return; }
142
- if (msg.type === 'event') { const f = eventListeners.get(msg.event); if (f) { try { f(msg.data); } catch { } } return; }
143
- };
144
-
145
- socket.on('data', (chunk) => {
146
- buffer = Buffer.concat([buffer, chunk]);
147
- if (buffer.length > MAX_FRAME_BYTES) { socket.destroy(); return; }
148
- let nl;
149
- while ((nl = buffer.indexOf(0x0a)) !== -1) {
150
- const line = buffer.slice(0, nl).toString('utf8');
151
- buffer = buffer.slice(nl + 1);
152
- handleLine(line);
153
- }
154
- });
155
- socket.on('error', () => { });
156
- socket.on('close', () => { if (workerSocket === socket) { workerSocket = null; authed = false; } });
157
- });
158
-
159
- const eventListeners = new Map();
160
-
161
- return new Promise((resolve, reject) => {
162
- server.once('error', reject);
163
- // 127.0.0.1 ONLY — never 0.0.0.0, never a LAN/Tailscale address.
164
- server.listen(0, '127.0.0.1', () => {
165
- const port = server.address().port;
166
- resolve({
167
- port,
168
- token,
169
- get connected() { return !!(workerSocket && !workerSocket.destroyed && authed); },
170
- on(event, fn) { eventListeners.set(event, fn); },
171
- takeResult(id) { const r = results.get(id); if (r) { results.delete(id); } return r || null; },
172
- /** Send a typed command; returns the command id. */
173
- send(command, payload) {
174
- if (!WORKER_COMMANDS.has(command)) throw new BridgeError('unknown command: ' + command, 'UNKNOWN_COMMAND');
175
- if (!workerSocket || !authed || workerSocket.destroyed) throw new BridgeError('no authenticated worker', 'NO_WORKER');
176
- const id = crypto.randomUUID();
177
- workerSocket.write(JSON.stringify({ type: 'command', id, command, payload: payload || {} }) + '\n');
178
- return id;
179
- },
180
- /** Send and await the typed result (bounded). */
181
- call(command, payload, timeoutMs = 120000) {
182
- return new Promise((res, rej) => {
183
- let id;
184
- try { id = this.send(command, payload); } catch (e) { rej(e); return; }
185
- const timer = setTimeout(() => { waiters.delete(id); rej(new BridgeError('worker call timed out: ' + command, 'WORKER_TIMEOUT')); }, timeoutMs);
186
- const _reject = (r) => rej(Object.assign(
187
- new Error(r.detail || r.error || 'worker error'),
188
- {
189
- code: r.error,
190
- stage: r.stage || null,
191
- accountId: r.accountId,
192
- accountUuid: r.accountUuid,
193
- proxyId: r.proxyId,
194
- proxy: r.proxy || null,
195
- // Safe auth classification raised by the worker (never secrets).
196
- authState: r.authState || null,
197
- reason: r.reason || null,
198
- failureStage: r.failureStage || null,
199
- },
200
- ));
201
- waiters.set(id, (r) => { clearTimeout(timer); if (r.ok) res(r.result); else _reject(r); });
202
- if (results.has(id)) { const r = results.get(id); results.delete(id); waiters.delete(id); clearTimeout(timer); if (r.ok) res(r.result); else _reject(r); }
203
- });
204
- },
205
- close() { try { if (workerSocket) workerSocket.destroy(); } catch { } try { server.close(); } catch { } },
206
- /** Tear down the CURRENT worker connection (session change / disposal). */
207
- dropWorker() {
208
- try { if (workerSocket) workerSocket.destroy(); } catch { }
209
- workerSocket = null;
210
- authed = false;
211
- },
212
- });
213
- });
214
- });
215
- }
216
-
217
- /**
218
- * Open the worker side of the bridge: connect to the broker's loopback port,
219
- * authenticate with the one-time token, and dispatch typed commands to a local
220
- * handler. Any non-loopback/unknown broker is refused.
221
- *
222
- * @param {object} opts
223
- * @param {number} opts.port
224
- * @param {string} opts.token
225
- * @param {function} opts.handler — async (command, payload) => result
226
- * @returns {Promise<{close:function, on:function}>}
227
- */
228
- function openWorkerChannel(opts) {
229
- const { port, token, handler } = opts;
230
- if (typeof handler !== 'function') throw new BridgeError('handler is required', 'BRIDGE_NO_HANDLER');
231
- return new Promise((resolve, reject) => {
232
- const socket = net.connect({ host: '127.0.0.1', port }, () => {
233
- socket.write(JSON.stringify({ type: 'auth', token }) + '\n');
234
- });
235
- let authOk = false;
236
- let buffer = Buffer.alloc(0);
237
- const listeners = new Map();
238
-
239
- socket.on('error', (err) => { if (!authOk) reject(new BridgeError('worker channel error: ' + err.message, 'BRIDGE_CONNECT_FAILED')); });
240
- socket.on('close', () => { const f = listeners.get('close'); if (f) f(); });
241
- socket.on('data', (chunk) => {
242
- buffer = Buffer.concat([buffer, chunk]);
243
- if (buffer.length > MAX_FRAME_BYTES) { socket.destroy(); return; }
244
- let nl;
245
- while ((nl = buffer.indexOf(0x0a)) !== -1) {
246
- const line = buffer.slice(0, nl).toString('utf8');
247
- buffer = buffer.slice(nl + 1);
248
- let msg; try { msg = JSON.parse(line); } catch { socket.destroy(); return; }
249
- if (!authOk) {
250
- if (msg.type === 'auth-ok') { authOk = true; resolve({ close: () => socket.destroy(), on: (ev, fn) => listeners.set(ev, fn) }); }
251
- else socket.destroy();
252
- continue;
253
- }
254
- if (msg.type !== 'command') continue;
255
- Promise.resolve()
256
- .then(() => handler(msg.command, msg.payload || {}))
257
- .then((result) => { if (!socket.destroyed) socket.write(JSON.stringify({ type: 'result', id: msg.id, ok: true, result: result == null ? null : result }) + '\n'); })
258
- .catch((err) => {
259
- if (socket.destroyed) return;
260
- // Forward a SAFE diagnostic subset so the broker can name the failing
261
- // stage and the account/proxy involved. `proxy` is already masked
262
- // (scheme://host:port) by the worker; no credential crosses here.
263
- socket.write(JSON.stringify({
264
- type: 'result',
265
- id: msg.id,
266
- ok: false,
267
- error: (err && err.code) || 'WORKER_ERROR',
268
- detail: String((err && err.message) || err).slice(0, 300),
269
- stage: (err && err.stage) || null,
270
- accountId: (err && err.accountId != null) ? err.accountId : null,
271
- accountUuid: (err && err.accountUuid) || null,
272
- proxyId: (err && err.proxyId != null) ? err.proxyId : null,
273
- proxy: (err && err.proxy) || null,
274
- // Safe auth classification: lets the broker separate "browser
275
- // opened" from "session verified" without leaking page content.
276
- authState: (err && err.authState) || null,
277
- reason: (err && err.reason) || null,
278
- failureStage: (err && err.failureStage) || null,
279
- }) + '\n');
280
- });
281
- }
282
- });
283
- });
284
- }
285
-
286
- // ── Process identity (Agent-owned browser PID) ───────────────────────────────
287
-
288
- /**
289
- * Resolve the top-level Chrome PID that owns EXACTLY this profile directory.
290
- *
291
- * Ownership is proven by the real process command line `--user-data-dir=<exact
292
- * profileDir>`, never "any chrome.exe" or "newest Chrome". Returns null when it
293
- * cannot be resolved (fail-safe: a null PID is never treated as owned).
294
- *
295
- * Used to record the browser PID in the Agent-local session registry so crash
296
- * recovery can identify an AGENT-OWNED orphan and never touch unrelated Chrome.
297
- *
298
- * @param {string} profileDir
299
- * @param {object} [opts] — { platform, exec } injection for deterministic tests
300
- * @returns {number|null}
301
- */
302
- function resolveChromePidForProfile(profileDir, opts = {}) {
303
- const platform = opts.platform || os.platform();
304
- if (platform !== 'win32' || !profileDir) return null;
305
- const cp = require('child_process');
306
- const path = require('path');
307
- const root = process.env.SystemRoot || process.env.WINDIR || 'C:\\Windows';
308
- const psExe = path.join(root, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');
309
- const run = opts.exec || ((exe, args, o) => cp.spawnSync(exe, args, o));
310
- const script = [
311
- "$ErrorActionPreference='SilentlyContinue';",
312
- "$procs = Get-CimInstance Win32_Process -Filter \"Name='chrome.exe'\";",
313
- "$t = ($env:OC_TARGET_PROFILE);",
314
- "$out = @(); foreach ($p in $procs) { if ($p.CommandLine -and ($p.CommandLine -like ('*' + $t + '*'))) { $out += [pscustomobject]@{ pid = $p.ProcessId; ppid = $p.ParentProcessId } } };",
315
- "ConvertTo-Json -Compress @($out)",
316
- ].join(' ');
317
- let r;
318
- try {
319
- r = run(psExe, ['-NoProfile', '-NonInteractive', '-Command', script], {
320
- encoding: 'utf8', windowsHide: true, timeout: 8000,
321
- env: { ...process.env, OC_TARGET_PROFILE: profileDir },
322
- });
323
- } catch { return null; }
324
- let rows;
325
- try { rows = JSON.parse((r.stdout || '').trim() || '[]'); } catch { return null; }
326
- if (!Array.isArray(rows)) rows = rows ? [rows] : [];
327
- if (rows.length === 0) return null;
328
- // The profile owner is the process whose parent is NOT in this set (the
329
- // top-level browser). Fall back to the smallest PID for determinism.
330
- const pids = new Set(rows.map((x) => x.pid));
331
- const roots = rows.filter((x) => !pids.has(x.ppid));
332
- const pick = (roots.length ? roots : rows).sort((a, b) => a.pid - b.pid)[0];
333
- return pick && Number.isFinite(pick.pid) ? pick.pid : null;
334
- }
335
-
336
- /** The typed command allowlist (exported for tests + documentation). */
337
- function workerCommandTypes() { return Array.from(WORKER_COMMANDS); }
338
-
339
- /**
340
- * Decide whether the broker must REPLACE its connected worker before routing a
341
- * job. A worker is SESSION-BOUND: it is only valid for the Windows session it was
342
- * launched into. The broker is global and long-lived; a worker is disposable.
343
- *
344
- * Truth table (the fast-user-switch invariant):
345
- * not connected -> replace (spawn one)
346
- * active session unknown (<0) -> keep (never spawn into an unknown session)
347
- * worker session unknown (<0) -> replace (do not trust an unbound worker)
348
- * workerSession !== activeSession -> replace (MISMATCH: e.g. 2 vs 1)
349
- * workerSession === activeSession -> keep (normal case)
350
- *
351
- * This is a PURE function so the mismatch case is unit-tested without desktops.
352
- *
353
- * @param {{connected:boolean, workerSession:number, activeSession:number}} o
354
- * @returns {boolean} true = tear down the current worker and launch a fresh one
355
- */
356
- function shouldReplaceWorker(o = {}) {
357
- const connected = o.connected === true;
358
- const workerSession = Number(o.workerSession);
359
- const activeSession = Number(o.activeSession);
360
- if (!connected) return true;
361
- if (!Number.isFinite(activeSession) || activeSession < 0) return false;
362
- if (!Number.isFinite(workerSession) || workerSession < 0) return true;
363
- return workerSession !== activeSession;
364
- }
365
-
366
- module.exports = {
367
- WORKER_COMMANDS,
368
- MAX_FRAME_BYTES,
369
- BridgeError,
370
- isLoopback,
371
- newChannelToken,
372
- openBrokerChannel,
373
- openWorkerChannel,
374
- workerCommandTypes,
375
- resolveChromePidForProfile,
376
- shouldReplaceWorker,
377
- };
1
+ 'use strict';
2
+
3
+ /**
4
+ * Broker <-> interactive Browser Worker bridge (TW-manager Agent 2.1.0).
5
+ *
6
+ * ARCHITECTURE
7
+ * ------------
8
+ * Two distinct processes/roles:
9
+ *
10
+ * BROKER (machine-wide, silent, one per machine)
11
+ * - owns device identity + the device private key
12
+ * - owns the server WebSocket connection
13
+ * - owns leases + the machine-local session registry
14
+ * - holds the machine-wide named mutex
15
+ * - NEVER launches Chromium
16
+ *
17
+ * BROWSER WORKER (per interactive desktop session)
18
+ * - runs INSIDE the active interactive Windows session
19
+ * - launches and drives Chromium for one account session
20
+ * - receives ONLY typed browser commands from the broker
21
+ * - CANNOT read the device private key
22
+ * - CANNOT enroll/register a device
23
+ *
24
+ * TRANSPORT
25
+ * ---------
26
+ * A loopback-only TCP channel on 127.0.0.1 with an ephemeral port chosen by the
27
+ * broker. It is NEVER bound to 0.0.0.0/LAN/Tailscale/public interfaces.
28
+ *
29
+ * SECURITY
30
+ * --------
31
+ * - The broker generates a 256-bit one-time channel token per worker; the
32
+ * worker must present it on the first frame or the socket is destroyed.
33
+ * - Every message is a typed, bounded JSON frame with a strict command
34
+ * allowlist. There is NO arbitrary command execution: the worker only
35
+ * understands the browser command types below.
36
+ * - The channel carries no device credential and no proxy secret; the proxy
37
+ * binding for a session is passed as a typed descriptor, and the worker
38
+ * never logs it.
39
+ * - Messages are size-bounded; a peer that exceeds the bound is disconnected.
40
+ *
41
+ * This module is dependency-free (node:net only).
42
+ */
43
+
44
+ const os = require('os');
45
+ const net = require('net');
46
+ const crypto = require('crypto');
47
+
48
+ // The ONLY command types a worker will execute. Anything else is refused.
49
+ const WORKER_COMMANDS = Object.freeze(new Set([
50
+ 'startSession',
51
+ 'stopSession',
52
+ 'refreshSession',
53
+ 'getStatus',
54
+ 'checkAuth',
55
+ 'navigate',
56
+ 'type',
57
+ 'paste',
58
+ 'press',
59
+ 'click',
60
+ 'runAction',
61
+ 'focus',
62
+ 'closeAll',
63
+ 'recoverOrphans',
64
+ 'proxy-test',
65
+ 'connectivity-test',
66
+ 'shutdown',
67
+ ]));
68
+
69
+ const MAX_FRAME_BYTES = 256 * 1024;
70
+ const CHANNEL_TOKEN_BYTES = 32;
71
+
72
+ class BridgeError extends Error {
73
+ constructor(message, code) {
74
+ super(message);
75
+ this.code = code || 'BRIDGE_ERROR';
76
+ this.name = 'BridgeError';
77
+ }
78
+ }
79
+
80
+ /** True when a socket address is loopback-only. */
81
+ function isLoopback(address) {
82
+ if (!address) return false;
83
+ return address === '127.0.0.1'
84
+ || address === '::1'
85
+ || address === '::ffff:127.0.0.1'
86
+ || address.startsWith('127.');
87
+ }
88
+
89
+ function newChannelToken() {
90
+ return crypto.randomBytes(CHANNEL_TOKEN_BYTES).toString('base64url');
91
+ }
92
+
93
+ /**
94
+ * Open the broker side of the bridge: a loopback-only listener that accepts ONE
95
+ * worker connection, authenticated by the channel token.
96
+ *
97
+ * @param {object} opts
98
+ * @param {string} opts.token — the one-time channel token the worker must present
99
+ * @param {function} opts.onCommand — async (command, payload) => result
100
+ * @returns {Promise<{port:number, close:function, waitForWorker:function, send:function}>}
101
+ */
102
+ function openBrokerChannel(opts) {
103
+ const token = opts.token || newChannelToken();
104
+
105
+ let workerSocket = null;
106
+ let authed = false;
107
+ // Result buffer keyed by command id, so `send()` + `takeResult(id)` / `call()`
108
+ // can be used. Bounded so a runaway peer cannot grow memory.
109
+ const results = new Map();
110
+ const order = [];
111
+ const waiters = new Map();
112
+
113
+ function _storeResult(id, r) {
114
+ if (id == null) return;
115
+ results.set(id, r);
116
+ order.push(id);
117
+ while (order.length > 200) { results.delete(order.shift()); }
118
+ const w = waiters.get(id);
119
+ if (w) { waiters.delete(id); try { w(r); } catch { } }
120
+ }
121
+
122
+ const server = net.createServer((socket) => {
123
+ // Reject any non-loopback peer outright (defense in depth: we bind loopback,
124
+ // so this can only fire if something unusual happens).
125
+ if (!isLoopback(socket.remoteAddress)) { socket.destroy(); return; }
126
+ if (workerSocket && !workerSocket.destroyed) { socket.destroy(); return; } // one worker per channel
127
+ workerSocket = socket;
128
+ authed = false;
129
+ let buffer = Buffer.alloc(0);
130
+
131
+ const handleLine = (line) => {
132
+ let msg;
133
+ try { msg = JSON.parse(line); } catch { socket.destroy(); return; }
134
+ if (!msg || typeof msg !== 'object') { socket.destroy(); return; }
135
+ if (!authed) {
136
+ if (msg.type !== 'auth' || msg.token !== token) { socket.destroy(); return; } // token single-use
137
+ authed = true;
138
+ socket.write(JSON.stringify({ type: 'auth-ok' }) + '\n');
139
+ return;
140
+ }
141
+ if (msg.type === 'result') { _storeResult(msg.id, msg); return; }
142
+ if (msg.type === 'event') { const f = eventListeners.get(msg.event); if (f) { try { f(msg.data); } catch { } } return; }
143
+ };
144
+
145
+ socket.on('data', (chunk) => {
146
+ buffer = Buffer.concat([buffer, chunk]);
147
+ if (buffer.length > MAX_FRAME_BYTES) { socket.destroy(); return; }
148
+ let nl;
149
+ while ((nl = buffer.indexOf(0x0a)) !== -1) {
150
+ const line = buffer.slice(0, nl).toString('utf8');
151
+ buffer = buffer.slice(nl + 1);
152
+ handleLine(line);
153
+ }
154
+ });
155
+ socket.on('error', () => { });
156
+ socket.on('close', () => { if (workerSocket === socket) { workerSocket = null; authed = false; } });
157
+ });
158
+
159
+ const eventListeners = new Map();
160
+
161
+ return new Promise((resolve, reject) => {
162
+ server.once('error', reject);
163
+ // 127.0.0.1 ONLY — never 0.0.0.0, never a LAN/Tailscale address.
164
+ server.listen(0, '127.0.0.1', () => {
165
+ const port = server.address().port;
166
+ resolve({
167
+ port,
168
+ token,
169
+ get connected() { return !!(workerSocket && !workerSocket.destroyed && authed); },
170
+ on(event, fn) { eventListeners.set(event, fn); },
171
+ takeResult(id) { const r = results.get(id); if (r) { results.delete(id); } return r || null; },
172
+ /** Send a typed command; returns the command id. */
173
+ send(command, payload) {
174
+ if (!WORKER_COMMANDS.has(command)) throw new BridgeError('unknown command: ' + command, 'UNKNOWN_COMMAND');
175
+ if (!workerSocket || !authed || workerSocket.destroyed) throw new BridgeError('no authenticated worker', 'NO_WORKER');
176
+ const id = crypto.randomUUID();
177
+ workerSocket.write(JSON.stringify({ type: 'command', id, command, payload: payload || {} }) + '\n');
178
+ return id;
179
+ },
180
+ /** Send and await the typed result (bounded). */
181
+ call(command, payload, timeoutMs = 120000) {
182
+ return new Promise((res, rej) => {
183
+ let id;
184
+ try { id = this.send(command, payload); } catch (e) { rej(e); return; }
185
+ const timer = setTimeout(() => { waiters.delete(id); rej(new BridgeError('worker call timed out: ' + command, 'WORKER_TIMEOUT')); }, timeoutMs);
186
+ const _reject = (r) => rej(Object.assign(
187
+ new Error(r.detail || r.error || 'worker error'),
188
+ {
189
+ code: r.error,
190
+ stage: r.stage || null,
191
+ accountId: r.accountId,
192
+ accountUuid: r.accountUuid,
193
+ proxyId: r.proxyId,
194
+ proxy: r.proxy || null,
195
+ // Safe auth classification raised by the worker (never secrets).
196
+ authState: r.authState || null,
197
+ reason: r.reason || null,
198
+ failureStage: r.failureStage || null,
199
+ },
200
+ ));
201
+ waiters.set(id, (r) => { clearTimeout(timer); if (r.ok) res(r.result); else _reject(r); });
202
+ if (results.has(id)) { const r = results.get(id); results.delete(id); waiters.delete(id); clearTimeout(timer); if (r.ok) res(r.result); else _reject(r); }
203
+ });
204
+ },
205
+ close() { try { if (workerSocket) workerSocket.destroy(); } catch { } try { server.close(); } catch { } },
206
+ /** Tear down the CURRENT worker connection (session change / disposal). */
207
+ dropWorker() {
208
+ try { if (workerSocket) workerSocket.destroy(); } catch { }
209
+ workerSocket = null;
210
+ authed = false;
211
+ },
212
+ });
213
+ });
214
+ });
215
+ }
216
+
217
+ /**
218
+ * Open the worker side of the bridge: connect to the broker's loopback port,
219
+ * authenticate with the one-time token, and dispatch typed commands to a local
220
+ * handler. Any non-loopback/unknown broker is refused.
221
+ *
222
+ * @param {object} opts
223
+ * @param {number} opts.port
224
+ * @param {string} opts.token
225
+ * @param {function} opts.handler — async (command, payload) => result
226
+ * @returns {Promise<{close:function, on:function}>}
227
+ */
228
+ function openWorkerChannel(opts) {
229
+ const { port, token, handler } = opts;
230
+ if (typeof handler !== 'function') throw new BridgeError('handler is required', 'BRIDGE_NO_HANDLER');
231
+ return new Promise((resolve, reject) => {
232
+ const socket = net.connect({ host: '127.0.0.1', port }, () => {
233
+ socket.write(JSON.stringify({ type: 'auth', token }) + '\n');
234
+ });
235
+ let authOk = false;
236
+ let buffer = Buffer.alloc(0);
237
+ const listeners = new Map();
238
+
239
+ socket.on('error', (err) => { if (!authOk) reject(new BridgeError('worker channel error: ' + err.message, 'BRIDGE_CONNECT_FAILED')); });
240
+ socket.on('close', () => { const f = listeners.get('close'); if (f) f(); });
241
+ socket.on('data', (chunk) => {
242
+ buffer = Buffer.concat([buffer, chunk]);
243
+ if (buffer.length > MAX_FRAME_BYTES) { socket.destroy(); return; }
244
+ let nl;
245
+ while ((nl = buffer.indexOf(0x0a)) !== -1) {
246
+ const line = buffer.slice(0, nl).toString('utf8');
247
+ buffer = buffer.slice(nl + 1);
248
+ let msg; try { msg = JSON.parse(line); } catch { socket.destroy(); return; }
249
+ if (!authOk) {
250
+ if (msg.type === 'auth-ok') { authOk = true; resolve({ close: () => socket.destroy(), on: (ev, fn) => listeners.set(ev, fn) }); }
251
+ else socket.destroy();
252
+ continue;
253
+ }
254
+ if (msg.type !== 'command') continue;
255
+ Promise.resolve()
256
+ .then(() => handler(msg.command, msg.payload || {}))
257
+ .then((result) => { if (!socket.destroyed) socket.write(JSON.stringify({ type: 'result', id: msg.id, ok: true, result: result == null ? null : result }) + '\n'); })
258
+ .catch((err) => {
259
+ if (socket.destroyed) return;
260
+ // Forward a SAFE diagnostic subset so the broker can name the failing
261
+ // stage and the account/proxy involved. `proxy` is already masked
262
+ // (scheme://host:port) by the worker; no credential crosses here.
263
+ socket.write(JSON.stringify({
264
+ type: 'result',
265
+ id: msg.id,
266
+ ok: false,
267
+ error: (err && err.code) || 'WORKER_ERROR',
268
+ detail: String((err && err.message) || err).slice(0, 300),
269
+ stage: (err && err.stage) || null,
270
+ accountId: (err && err.accountId != null) ? err.accountId : null,
271
+ accountUuid: (err && err.accountUuid) || null,
272
+ proxyId: (err && err.proxyId != null) ? err.proxyId : null,
273
+ proxy: (err && err.proxy) || null,
274
+ // Safe auth classification: lets the broker separate "browser
275
+ // opened" from "session verified" without leaking page content.
276
+ authState: (err && err.authState) || null,
277
+ reason: (err && err.reason) || null,
278
+ failureStage: (err && err.failureStage) || null,
279
+ }) + '\n');
280
+ });
281
+ }
282
+ });
283
+ });
284
+ }
285
+
286
+ // ── Process identity (Agent-owned browser PID) ───────────────────────────────
287
+
288
+ /**
289
+ * Resolve the top-level Chrome PID that owns EXACTLY this profile directory.
290
+ *
291
+ * Ownership is proven by the real process command line `--user-data-dir=<exact
292
+ * profileDir>`, never "any chrome.exe" or "newest Chrome". Returns null when it
293
+ * cannot be resolved (fail-safe: a null PID is never treated as owned).
294
+ *
295
+ * Used to record the browser PID in the Agent-local session registry so crash
296
+ * recovery can identify an AGENT-OWNED orphan and never touch unrelated Chrome.
297
+ *
298
+ * @param {string} profileDir
299
+ * @param {object} [opts] — { platform, exec } injection for deterministic tests
300
+ * @returns {number|null}
301
+ */
302
+ function resolveChromePidForProfile(profileDir, opts = {}) {
303
+ const platform = opts.platform || os.platform();
304
+ if (platform !== 'win32' || !profileDir) return null;
305
+ const cp = require('child_process');
306
+ const path = require('path');
307
+ const root = process.env.SystemRoot || process.env.WINDIR || 'C:\\Windows';
308
+ const psExe = path.join(root, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');
309
+ const run = opts.exec || ((exe, args, o) => cp.spawnSync(exe, args, o));
310
+ const script = [
311
+ "$ErrorActionPreference='SilentlyContinue';",
312
+ "$procs = Get-CimInstance Win32_Process -Filter \"Name='chrome.exe'\";",
313
+ "$t = ($env:OC_TARGET_PROFILE);",
314
+ "$out = @(); foreach ($p in $procs) { if ($p.CommandLine -and ($p.CommandLine -like ('*' + $t + '*'))) { $out += [pscustomobject]@{ pid = $p.ProcessId; ppid = $p.ParentProcessId } } };",
315
+ "ConvertTo-Json -Compress @($out)",
316
+ ].join(' ');
317
+ let r;
318
+ try {
319
+ r = run(psExe, ['-NoProfile', '-NonInteractive', '-Command', script], {
320
+ encoding: 'utf8', windowsHide: true, timeout: 8000,
321
+ env: { ...process.env, OC_TARGET_PROFILE: profileDir },
322
+ });
323
+ } catch { return null; }
324
+ let rows;
325
+ try { rows = JSON.parse((r.stdout || '').trim() || '[]'); } catch { return null; }
326
+ if (!Array.isArray(rows)) rows = rows ? [rows] : [];
327
+ if (rows.length === 0) return null;
328
+ // The profile owner is the process whose parent is NOT in this set (the
329
+ // top-level browser). Fall back to the smallest PID for determinism.
330
+ const pids = new Set(rows.map((x) => x.pid));
331
+ const roots = rows.filter((x) => !pids.has(x.ppid));
332
+ const pick = (roots.length ? roots : rows).sort((a, b) => a.pid - b.pid)[0];
333
+ return pick && Number.isFinite(pick.pid) ? pick.pid : null;
334
+ }
335
+
336
+ /** The typed command allowlist (exported for tests + documentation). */
337
+ function workerCommandTypes() { return Array.from(WORKER_COMMANDS); }
338
+
339
+ /**
340
+ * Decide whether the broker must REPLACE its connected worker before routing a
341
+ * job. A worker is SESSION-BOUND: it is only valid for the Windows session it was
342
+ * launched into. The broker is global and long-lived; a worker is disposable.
343
+ *
344
+ * Truth table (the fast-user-switch invariant):
345
+ * not connected -> replace (spawn one)
346
+ * active session unknown (<0) -> keep (never spawn into an unknown session)
347
+ * worker session unknown (<0) -> replace (do not trust an unbound worker)
348
+ * workerSession !== activeSession -> replace (MISMATCH: e.g. 2 vs 1)
349
+ * workerSession === activeSession -> keep (normal case)
350
+ *
351
+ * This is a PURE function so the mismatch case is unit-tested without desktops.
352
+ *
353
+ * @param {{connected:boolean, workerSession:number, activeSession:number}} o
354
+ * @returns {boolean} true = tear down the current worker and launch a fresh one
355
+ */
356
+ function shouldReplaceWorker(o = {}) {
357
+ const connected = o.connected === true;
358
+ const workerSession = Number(o.workerSession);
359
+ const activeSession = Number(o.activeSession);
360
+ if (!connected) return true;
361
+ if (!Number.isFinite(activeSession) || activeSession < 0) return false;
362
+ if (!Number.isFinite(workerSession) || workerSession < 0) return true;
363
+ return workerSession !== activeSession;
364
+ }
365
+
366
+ module.exports = {
367
+ WORKER_COMMANDS,
368
+ MAX_FRAME_BYTES,
369
+ BridgeError,
370
+ isLoopback,
371
+ newChannelToken,
372
+ openBrokerChannel,
373
+ openWorkerChannel,
374
+ workerCommandTypes,
375
+ resolveChromePidForProfile,
376
+ shouldReplaceWorker,
377
+ };