@xkwdstore/agent 2.0.7 → 2.1.1

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.
@@ -0,0 +1,163 @@
1
+ // XKWDStore Agent 2.1.0 — interactive-session process launcher.
2
+ //
3
+ // WHY THIS EXISTS
4
+ // ---------------
5
+ // The machine broker runs as a Windows SERVICE in Session 0. Session 0 has no
6
+ // interactive desktop, so a Chromium window launched from the broker would be
7
+ // invisible/non-functional. The broker must launch its Browser Worker into the
8
+ // ACTIVE INTERACTIVE USER SESSION.
9
+ //
10
+ // This helper, run by the broker (LocalSystem), launches a process in the active
11
+ // console session using CreateProcessAsUser with the session's user token:
12
+ //
13
+ // WTSGetActiveConsoleSessionId -> WTSQueryUserToken ->
14
+ // DuplicateTokenEx -> CreateEnvironmentBlock -> CreateProcessAsUser
15
+ //
16
+ // It requires SeTcbPrivilege (LocalSystem has it). It launches EXACTLY the
17
+ // command it is given (node + worker.js + invite), never a shell, and passes no
18
+ // secret. The worker then authenticates to the broker over the loopback channel.
19
+ //
20
+ // The launched child inherits the USER's desktop (session), so Chromium appears
21
+ // on that user's screen.
22
+
23
+ using System;
24
+ using System.ComponentModel;
25
+ using System.Diagnostics;
26
+ using System.Runtime.InteropServices;
27
+
28
+ internal static class SessionLauncher
29
+ {
30
+ [DllImport("kernel32.dll")]
31
+ private static extern uint WTSGetActiveConsoleSessionId();
32
+
33
+ [DllImport("wtsapi32.dll", SetLastError = true)]
34
+ private static extern bool WTSQueryUserToken(uint sessionId, out IntPtr token);
35
+
36
+ [DllImport("advapi32.dll", SetLastError = true)]
37
+ private static extern bool DuplicateTokenEx(IntPtr existing, uint desiredAccess, IntPtr attrs,
38
+ int impersonationLevel, int tokenType, out IntPtr newToken);
39
+
40
+ [DllImport("userenv.dll", SetLastError = true)]
41
+ private static extern bool CreateEnvironmentBlock(out IntPtr env, IntPtr token, bool inherit);
42
+
43
+ [DllImport("userenv.dll", SetLastError = true)]
44
+ private static extern bool DestroyEnvironmentBlock(IntPtr env);
45
+
46
+ [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
47
+ private static extern bool CreateProcessAsUser(IntPtr token, string app, string cmdLine,
48
+ IntPtr procAttrs, IntPtr threadAttrs, bool inherit, uint flags, IntPtr env, string cwd,
49
+ ref STARTUPINFO si, out PROCESS_INFORMATION pi);
50
+
51
+ [DllImport("kernel32.dll", SetLastError = true)]
52
+ private static extern bool CloseHandle(IntPtr h);
53
+
54
+ [StructLayout(LayoutKind.Sequential)]
55
+ private struct SECURITY_ATTRIBUTES { public int nLength; public IntPtr lpSecurityDescriptor; public bool bInheritHandle; }
56
+
57
+ [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
58
+ private static extern IntPtr CreateFile(string name, uint access, uint share, ref SECURITY_ATTRIBUTES sa,
59
+ uint creation, uint flags, IntPtr template);
60
+
61
+ private const uint GENERIC_WRITE = 0x40000000;
62
+ private const uint FILE_SHARE_WRITE = 0x00000002;
63
+ private const uint FILE_SHARE_READ = 0x00000001;
64
+ private const uint CREATE_ALWAYS = 2;
65
+ private const uint FILE_ATTRIBUTE_NORMAL = 0x80;
66
+ private const int STARTF_USESTDHANDLES = 0x00000100;
67
+
68
+ private const uint TOKEN_ALL_ACCESS = 0xF01FF;
69
+ private const uint CREATE_UNICODE_ENVIRONMENT = 0x00000400;
70
+
71
+ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
72
+ private struct STARTUPINFO
73
+ {
74
+ public int cb;
75
+ public string lpReserved;
76
+ public string lpDesktop;
77
+ public string lpTitle;
78
+ public int dwX, dwY, dwXSize, dwYSize, dwXCountChars, dwYCountChars, dwFillAttribute, dwFlags;
79
+ public short wShowWindow, cbReserved2;
80
+ public IntPtr lpReserved2, hStdInput, hStdOutput, hStdError;
81
+ }
82
+
83
+ [StructLayout(LayoutKind.Sequential)]
84
+ private struct PROCESS_INFORMATION
85
+ {
86
+ public IntPtr hProcess, hThread;
87
+ public int dwProcessId, dwThreadId;
88
+ }
89
+
90
+ public static int Main(string[] args)
91
+ {
92
+ // Args: -Exe <node.exe> -Args "<worker args>" [-Cwd <dir>] [-Out <file>] [-Err <file>]
93
+ // -Query -> print the ACTIVE CONSOLE session id and exit (broker session check)
94
+ string exe = null, argLine = null, cwd = null, outFile = null, errFile = null;
95
+ bool query = false;
96
+ for (int i = 0; i < args.Length; i++)
97
+ {
98
+ switch (args[i])
99
+ {
100
+ case "-Exe": if (i + 1 < args.Length) exe = args[++i]; break;
101
+ case "-Args": if (i + 1 < args.Length) argLine = args[++i]; break;
102
+ case "-Cwd": if (i + 1 < args.Length) cwd = args[++i]; break;
103
+ case "-Out": if (i + 1 < args.Length) outFile = args[++i]; break;
104
+ case "-Err": if (i + 1 < args.Length) errFile = args[++i]; break;
105
+ case "-Query": query = true; break;
106
+ }
107
+ }
108
+ if (query)
109
+ {
110
+ uint qs = WTSGetActiveConsoleSessionId();
111
+ Console.WriteLine("SESSION=" + (qs == 0xFFFFFFFF ? "-1" : qs.ToString()));
112
+ return 0;
113
+ }
114
+ if (exe == null || argLine == null) { Console.Error.WriteLine("usage: -Exe <exe> -Args <args> [-Cwd <dir>] | -Query"); return 2; }
115
+
116
+ uint session = WTSGetActiveConsoleSessionId();
117
+ if (session == 0xFFFFFFFF) { Console.Error.WriteLine("no active console session"); return 3; }
118
+
119
+ IntPtr userToken;
120
+ if (!WTSQueryUserToken(session, out userToken)) { Console.Error.WriteLine("WTSQueryUserToken failed: " + new Win32Exception(Marshal.GetLastWin32Error()).Message); return 4; }
121
+
122
+ IntPtr dup;
123
+ if (!DuplicateTokenEx(userToken, TOKEN_ALL_ACCESS, IntPtr.Zero, 2 /*SecurityImpersonation*/, 1 /*Primary*/, out dup))
124
+ { Console.Error.WriteLine("DuplicateTokenEx failed: " + new Win32Exception(Marshal.GetLastWin32Error()).Message); return 5; }
125
+
126
+ IntPtr env = IntPtr.Zero;
127
+ CreateEnvironmentBlock(out env, dup, false);
128
+
129
+ var si = new STARTUPINFO();
130
+ si.cb = Marshal.SizeOf(si);
131
+ si.lpDesktop = "winsta0\\default";
132
+
133
+ // Redirect child stdio to files (a service-session launch has no console,
134
+ // so otherwise the worker's errors would be lost).
135
+ IntPtr outHandle = IntPtr.Zero, errHandle = IntPtr.Zero;
136
+ if (outFile != null || errFile != null)
137
+ {
138
+ var sa = new SECURITY_ATTRIBUTES();
139
+ sa.nLength = Marshal.SizeOf(sa);
140
+ sa.bInheritHandle = true;
141
+ outHandle = CreateFile(outFile ?? "NUL", GENERIC_WRITE, FILE_SHARE_WRITE | FILE_SHARE_READ, ref sa, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, IntPtr.Zero);
142
+ errHandle = CreateFile(errFile ?? (outFile ?? "NUL"), GENERIC_WRITE, FILE_SHARE_WRITE | FILE_SHARE_READ, ref sa, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, IntPtr.Zero);
143
+ si.dwFlags |= STARTF_USESTDHANDLES;
144
+ si.hStdOutput = outHandle;
145
+ si.hStdError = errHandle;
146
+ }
147
+
148
+ PROCESS_INFORMATION pi;
149
+ // Quote the executable path (it contains spaces); node parses argv itself
150
+ // when launched via CreateProcessAsUser without a shell.
151
+ string cmd = "\"" + exe + "\" " + argLine;
152
+ bool ok = CreateProcessAsUser(dup, exe, cmd, IntPtr.Zero, IntPtr.Zero,
153
+ (outHandle != IntPtr.Zero), CREATE_UNICODE_ENVIRONMENT, env, string.IsNullOrEmpty(cwd) ? null : cwd, ref si, out pi);
154
+ if (!ok) { Console.Error.WriteLine("CreateProcessAsUser failed: " + new Win32Exception(Marshal.GetLastWin32Error()).Message); return 6; }
155
+
156
+ Console.WriteLine("LAUNCHED pid=" + pi.dwProcessId + " session=" + session);
157
+ CloseHandle(pi.hThread); CloseHandle(pi.hProcess); CloseHandle(dup); CloseHandle(userToken);
158
+ if (outHandle != IntPtr.Zero) CloseHandle(outHandle);
159
+ if (errHandle != IntPtr.Zero) CloseHandle(errHandle);
160
+ if (env != IntPtr.Zero) DestroyEnvironmentBlock(env);
161
+ return 0;
162
+ }
163
+ }
@@ -0,0 +1,53 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Per-interactive-session worker launcher (TW-manager Agent 2.1.0).
5
+ *
6
+ * A Scheduled Task (AtLogOn, per user) runs this tiny helper. It does NOT carry
7
+ * any credential and cannot enroll. Its ONLY job is to ask the machine broker
8
+ * (over the local machine-state directory) for a one-time channel token, then
9
+ * start `worker.js` attached to THAT active desktop session.
10
+ *
11
+ * The broker writes a short-lived "worker invitation" file into
12
+ * `<machineRoot>\runtime\worker-invite.json` containing { port, token, expiresAt }.
13
+ * The invitation is:
14
+ * - written with 0o600 / restrictive ACL,
15
+ * - single-use (the broker regenerates the token per worker),
16
+ * - short-lived (expires in 60s),
17
+ * - worthless without the loopback channel (no network exposure).
18
+ *
19
+ * If the invitation is absent/expired (broker not up yet), the helper exits
20
+ * quietly; the broker will spawn a worker itself when it needs one.
21
+ */
22
+
23
+ const fs = require('fs');
24
+ const os = require('os');
25
+ const path = require('path');
26
+ const { spawn } = require('child_process');
27
+
28
+ function main() {
29
+ let machineState;
30
+ try { machineState = require('../machineState'); } catch { process.exit(0); }
31
+
32
+ const invitePath = path.join(machineState.paths.runtime, 'worker-invite.json');
33
+ let invite = null;
34
+ try { invite = JSON.parse(fs.readFileSync(invitePath, 'utf8')); } catch { invite = null; }
35
+ if (!invite || !invite.port || !invite.token) {
36
+ // No broker invitation (broker not running yet). Nothing to do.
37
+ process.exit(0);
38
+ }
39
+ if (invite.expiresAt && Date.parse(invite.expiresAt) < Date.now()) {
40
+ try { fs.unlinkSync(invitePath); } catch { }
41
+ process.exit(0);
42
+ }
43
+
44
+ const workerScript = path.join(__dirname, '..', 'src', 'worker.js');
45
+ const child = spawn(process.execPath, [workerScript, '--port', String(invite.port), '--token', String(invite.token)], {
46
+ stdio: 'ignore',
47
+ windowsHide: true,
48
+ });
49
+ child.unref();
50
+ process.exit(0);
51
+ }
52
+
53
+ main();
@@ -0,0 +1,352 @@
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
+ 'getStatus',
53
+ 'focus',
54
+ 'closeAll',
55
+ 'recoverOrphans',
56
+ 'proxy-test',
57
+ 'shutdown',
58
+ ]));
59
+
60
+ const MAX_FRAME_BYTES = 256 * 1024;
61
+ const CHANNEL_TOKEN_BYTES = 32;
62
+
63
+ class BridgeError extends Error {
64
+ constructor(message, code) {
65
+ super(message);
66
+ this.code = code || 'BRIDGE_ERROR';
67
+ this.name = 'BridgeError';
68
+ }
69
+ }
70
+
71
+ /** True when a socket address is loopback-only. */
72
+ function isLoopback(address) {
73
+ if (!address) return false;
74
+ return address === '127.0.0.1'
75
+ || address === '::1'
76
+ || address === '::ffff:127.0.0.1'
77
+ || address.startsWith('127.');
78
+ }
79
+
80
+ function newChannelToken() {
81
+ return crypto.randomBytes(CHANNEL_TOKEN_BYTES).toString('base64url');
82
+ }
83
+
84
+ /**
85
+ * Open the broker side of the bridge: a loopback-only listener that accepts ONE
86
+ * worker connection, authenticated by the channel token.
87
+ *
88
+ * @param {object} opts
89
+ * @param {string} opts.token — the one-time channel token the worker must present
90
+ * @param {function} opts.onCommand — async (command, payload) => result
91
+ * @returns {Promise<{port:number, close:function, waitForWorker:function, send:function}>}
92
+ */
93
+ function openBrokerChannel(opts) {
94
+ const token = opts.token || newChannelToken();
95
+
96
+ let workerSocket = null;
97
+ let authed = false;
98
+ // Result buffer keyed by command id, so `send()` + `takeResult(id)` / `call()`
99
+ // can be used. Bounded so a runaway peer cannot grow memory.
100
+ const results = new Map();
101
+ const order = [];
102
+ const waiters = new Map();
103
+
104
+ function _storeResult(id, r) {
105
+ if (id == null) return;
106
+ results.set(id, r);
107
+ order.push(id);
108
+ while (order.length > 200) { results.delete(order.shift()); }
109
+ const w = waiters.get(id);
110
+ if (w) { waiters.delete(id); try { w(r); } catch { } }
111
+ }
112
+
113
+ const server = net.createServer((socket) => {
114
+ // Reject any non-loopback peer outright (defense in depth: we bind loopback,
115
+ // so this can only fire if something unusual happens).
116
+ if (!isLoopback(socket.remoteAddress)) { socket.destroy(); return; }
117
+ if (workerSocket && !workerSocket.destroyed) { socket.destroy(); return; } // one worker per channel
118
+ workerSocket = socket;
119
+ authed = false;
120
+ let buffer = Buffer.alloc(0);
121
+
122
+ const handleLine = (line) => {
123
+ let msg;
124
+ try { msg = JSON.parse(line); } catch { socket.destroy(); return; }
125
+ if (!msg || typeof msg !== 'object') { socket.destroy(); return; }
126
+ if (!authed) {
127
+ if (msg.type !== 'auth' || msg.token !== token) { socket.destroy(); return; } // token single-use
128
+ authed = true;
129
+ socket.write(JSON.stringify({ type: 'auth-ok' }) + '\n');
130
+ return;
131
+ }
132
+ if (msg.type === 'result') { _storeResult(msg.id, msg); return; }
133
+ if (msg.type === 'event') { const f = eventListeners.get(msg.event); if (f) { try { f(msg.data); } catch { } } return; }
134
+ };
135
+
136
+ socket.on('data', (chunk) => {
137
+ buffer = Buffer.concat([buffer, chunk]);
138
+ if (buffer.length > MAX_FRAME_BYTES) { socket.destroy(); return; }
139
+ let nl;
140
+ while ((nl = buffer.indexOf(0x0a)) !== -1) {
141
+ const line = buffer.slice(0, nl).toString('utf8');
142
+ buffer = buffer.slice(nl + 1);
143
+ handleLine(line);
144
+ }
145
+ });
146
+ socket.on('error', () => { });
147
+ socket.on('close', () => { if (workerSocket === socket) { workerSocket = null; authed = false; } });
148
+ });
149
+
150
+ const eventListeners = new Map();
151
+
152
+ return new Promise((resolve, reject) => {
153
+ server.once('error', reject);
154
+ // 127.0.0.1 ONLY — never 0.0.0.0, never a LAN/Tailscale address.
155
+ server.listen(0, '127.0.0.1', () => {
156
+ const port = server.address().port;
157
+ resolve({
158
+ port,
159
+ token,
160
+ get connected() { return !!(workerSocket && !workerSocket.destroyed && authed); },
161
+ on(event, fn) { eventListeners.set(event, fn); },
162
+ takeResult(id) { const r = results.get(id); if (r) { results.delete(id); } return r || null; },
163
+ /** Send a typed command; returns the command id. */
164
+ send(command, payload) {
165
+ if (!WORKER_COMMANDS.has(command)) throw new BridgeError('unknown command: ' + command, 'UNKNOWN_COMMAND');
166
+ if (!workerSocket || !authed || workerSocket.destroyed) throw new BridgeError('no authenticated worker', 'NO_WORKER');
167
+ const id = crypto.randomUUID();
168
+ workerSocket.write(JSON.stringify({ type: 'command', id, command, payload: payload || {} }) + '\n');
169
+ return id;
170
+ },
171
+ /** Send and await the typed result (bounded). */
172
+ call(command, payload, timeoutMs = 120000) {
173
+ return new Promise((res, rej) => {
174
+ let id;
175
+ try { id = this.send(command, payload); } catch (e) { rej(e); return; }
176
+ const timer = setTimeout(() => { waiters.delete(id); rej(new BridgeError('worker call timed out: ' + command, 'WORKER_TIMEOUT')); }, timeoutMs);
177
+ const _reject = (r) => rej(Object.assign(
178
+ new Error(r.detail || r.error || 'worker error'),
179
+ { code: r.error, stage: r.stage || null, accountId: r.accountId, accountUuid: r.accountUuid, proxyId: r.proxyId, proxy: r.proxy || null },
180
+ ));
181
+ waiters.set(id, (r) => { clearTimeout(timer); if (r.ok) res(r.result); else _reject(r); });
182
+ 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); }
183
+ });
184
+ },
185
+ close() { try { if (workerSocket) workerSocket.destroy(); } catch { } try { server.close(); } catch { } },
186
+ /** Tear down the CURRENT worker connection (session change / disposal). */
187
+ dropWorker() {
188
+ try { if (workerSocket) workerSocket.destroy(); } catch { }
189
+ workerSocket = null;
190
+ authed = false;
191
+ },
192
+ });
193
+ });
194
+ });
195
+ }
196
+
197
+ /**
198
+ * Open the worker side of the bridge: connect to the broker's loopback port,
199
+ * authenticate with the one-time token, and dispatch typed commands to a local
200
+ * handler. Any non-loopback/unknown broker is refused.
201
+ *
202
+ * @param {object} opts
203
+ * @param {number} opts.port
204
+ * @param {string} opts.token
205
+ * @param {function} opts.handler — async (command, payload) => result
206
+ * @returns {Promise<{close:function, on:function}>}
207
+ */
208
+ function openWorkerChannel(opts) {
209
+ const { port, token, handler } = opts;
210
+ if (typeof handler !== 'function') throw new BridgeError('handler is required', 'BRIDGE_NO_HANDLER');
211
+ return new Promise((resolve, reject) => {
212
+ const socket = net.connect({ host: '127.0.0.1', port }, () => {
213
+ socket.write(JSON.stringify({ type: 'auth', token }) + '\n');
214
+ });
215
+ let authOk = false;
216
+ let buffer = Buffer.alloc(0);
217
+ const listeners = new Map();
218
+
219
+ socket.on('error', (err) => { if (!authOk) reject(new BridgeError('worker channel error: ' + err.message, 'BRIDGE_CONNECT_FAILED')); });
220
+ socket.on('close', () => { const f = listeners.get('close'); if (f) f(); });
221
+ socket.on('data', (chunk) => {
222
+ buffer = Buffer.concat([buffer, chunk]);
223
+ if (buffer.length > MAX_FRAME_BYTES) { socket.destroy(); return; }
224
+ let nl;
225
+ while ((nl = buffer.indexOf(0x0a)) !== -1) {
226
+ const line = buffer.slice(0, nl).toString('utf8');
227
+ buffer = buffer.slice(nl + 1);
228
+ let msg; try { msg = JSON.parse(line); } catch { socket.destroy(); return; }
229
+ if (!authOk) {
230
+ if (msg.type === 'auth-ok') { authOk = true; resolve({ close: () => socket.destroy(), on: (ev, fn) => listeners.set(ev, fn) }); }
231
+ else socket.destroy();
232
+ continue;
233
+ }
234
+ if (msg.type !== 'command') continue;
235
+ Promise.resolve()
236
+ .then(() => handler(msg.command, msg.payload || {}))
237
+ .then((result) => { if (!socket.destroyed) socket.write(JSON.stringify({ type: 'result', id: msg.id, ok: true, result: result == null ? null : result }) + '\n'); })
238
+ .catch((err) => {
239
+ if (socket.destroyed) return;
240
+ // Forward a SAFE diagnostic subset so the broker can name the failing
241
+ // stage and the account/proxy involved. `proxy` is already masked
242
+ // (scheme://host:port) by the worker; no credential crosses here.
243
+ socket.write(JSON.stringify({
244
+ type: 'result',
245
+ id: msg.id,
246
+ ok: false,
247
+ error: (err && err.code) || 'WORKER_ERROR',
248
+ detail: String((err && err.message) || err).slice(0, 300),
249
+ stage: (err && err.stage) || null,
250
+ accountId: (err && err.accountId != null) ? err.accountId : null,
251
+ accountUuid: (err && err.accountUuid) || null,
252
+ proxyId: (err && err.proxyId != null) ? err.proxyId : null,
253
+ proxy: (err && err.proxy) || null,
254
+ }) + '\n');
255
+ });
256
+ }
257
+ });
258
+ });
259
+ }
260
+
261
+ // ── Process identity (Agent-owned browser PID) ───────────────────────────────
262
+
263
+ /**
264
+ * Resolve the top-level Chrome PID that owns EXACTLY this profile directory.
265
+ *
266
+ * Ownership is proven by the real process command line `--user-data-dir=<exact
267
+ * profileDir>`, never "any chrome.exe" or "newest Chrome". Returns null when it
268
+ * cannot be resolved (fail-safe: a null PID is never treated as owned).
269
+ *
270
+ * Used to record the browser PID in the Agent-local session registry so crash
271
+ * recovery can identify an AGENT-OWNED orphan and never touch unrelated Chrome.
272
+ *
273
+ * @param {string} profileDir
274
+ * @param {object} [opts] — { platform, exec } injection for deterministic tests
275
+ * @returns {number|null}
276
+ */
277
+ function resolveChromePidForProfile(profileDir, opts = {}) {
278
+ const platform = opts.platform || os.platform();
279
+ if (platform !== 'win32' || !profileDir) return null;
280
+ const cp = require('child_process');
281
+ const path = require('path');
282
+ const root = process.env.SystemRoot || process.env.WINDIR || 'C:\\Windows';
283
+ const psExe = path.join(root, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');
284
+ const run = opts.exec || ((exe, args, o) => cp.spawnSync(exe, args, o));
285
+ const script = [
286
+ "$ErrorActionPreference='SilentlyContinue';",
287
+ "$procs = Get-CimInstance Win32_Process -Filter \"Name='chrome.exe'\";",
288
+ "$t = ($env:OC_TARGET_PROFILE);",
289
+ "$out = @(); foreach ($p in $procs) { if ($p.CommandLine -and ($p.CommandLine -like ('*' + $t + '*'))) { $out += [pscustomobject]@{ pid = $p.ProcessId; ppid = $p.ParentProcessId } } };",
290
+ "ConvertTo-Json -Compress @($out)",
291
+ ].join(' ');
292
+ let r;
293
+ try {
294
+ r = run(psExe, ['-NoProfile', '-NonInteractive', '-Command', script], {
295
+ encoding: 'utf8', windowsHide: true, timeout: 8000,
296
+ env: { ...process.env, OC_TARGET_PROFILE: profileDir },
297
+ });
298
+ } catch { return null; }
299
+ let rows;
300
+ try { rows = JSON.parse((r.stdout || '').trim() || '[]'); } catch { return null; }
301
+ if (!Array.isArray(rows)) rows = rows ? [rows] : [];
302
+ if (rows.length === 0) return null;
303
+ // The profile owner is the process whose parent is NOT in this set (the
304
+ // top-level browser). Fall back to the smallest PID for determinism.
305
+ const pids = new Set(rows.map((x) => x.pid));
306
+ const roots = rows.filter((x) => !pids.has(x.ppid));
307
+ const pick = (roots.length ? roots : rows).sort((a, b) => a.pid - b.pid)[0];
308
+ return pick && Number.isFinite(pick.pid) ? pick.pid : null;
309
+ }
310
+
311
+ /** The typed command allowlist (exported for tests + documentation). */
312
+ function workerCommandTypes() { return Array.from(WORKER_COMMANDS); }
313
+
314
+ /**
315
+ * Decide whether the broker must REPLACE its connected worker before routing a
316
+ * job. A worker is SESSION-BOUND: it is only valid for the Windows session it was
317
+ * launched into. The broker is global and long-lived; a worker is disposable.
318
+ *
319
+ * Truth table (the fast-user-switch invariant):
320
+ * not connected -> replace (spawn one)
321
+ * active session unknown (<0) -> keep (never spawn into an unknown session)
322
+ * worker session unknown (<0) -> replace (do not trust an unbound worker)
323
+ * workerSession !== activeSession -> replace (MISMATCH: e.g. 2 vs 1)
324
+ * workerSession === activeSession -> keep (normal case)
325
+ *
326
+ * This is a PURE function so the mismatch case is unit-tested without desktops.
327
+ *
328
+ * @param {{connected:boolean, workerSession:number, activeSession:number}} o
329
+ * @returns {boolean} true = tear down the current worker and launch a fresh one
330
+ */
331
+ function shouldReplaceWorker(o = {}) {
332
+ const connected = o.connected === true;
333
+ const workerSession = Number(o.workerSession);
334
+ const activeSession = Number(o.activeSession);
335
+ if (!connected) return true;
336
+ if (!Number.isFinite(activeSession) || activeSession < 0) return false;
337
+ if (!Number.isFinite(workerSession) || workerSession < 0) return true;
338
+ return workerSession !== activeSession;
339
+ }
340
+
341
+ module.exports = {
342
+ WORKER_COMMANDS,
343
+ MAX_FRAME_BYTES,
344
+ BridgeError,
345
+ isLoopback,
346
+ newChannelToken,
347
+ openBrokerChannel,
348
+ openWorkerChannel,
349
+ workerCommandTypes,
350
+ resolveChromePidForProfile,
351
+ shouldReplaceWorker,
352
+ };