@xkwdstore/agent 2.0.7 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,280 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Agent-local session registry (2.1.0, Part E/F).
5
+ *
6
+ * WHY THIS EXISTS
7
+ * ---------------
8
+ * The server's durable lease is AUTHORITATIVE GLOBALLY, but it cannot see:
9
+ * - whether this machine already has a live Chromium for an account;
10
+ * - which PID owns a profile dir;
11
+ * - whether a previous agent process left an orphaned browser behind.
12
+ *
13
+ * This registry is the AGENT-LOCAL authority for those questions. It records
14
+ * only NON-SECRET metadata:
15
+ *
16
+ * accountUuid, accountId, leaseId, profilePath, browserPid,
17
+ * sessionKey, proxyIdentity (hash — NOT the proxy string/password),
18
+ * runtimeDir, startedAt, state, agentPid
19
+ *
20
+ * It deliberately never stores a lease TOKEN and never a proxy credential. The
21
+ * file is written atomically (temp + rename) so a crash cannot leave a torn
22
+ * registry, and it lives under the machine runtime dir so a restart of the agent
23
+ * can reconstruct what was running.
24
+ *
25
+ * TWO LOCKS, TWO PURPOSES (B2/E2)
26
+ * -------------------------------
27
+ * - SERVER LEASE = global authority (not touched by this module);
28
+ * - LOCAL PROFILE LOCK (this module) = protects against LOCAL duplicate
29
+ * launches/races: two agent instances, or a launch that races a live
30
+ * Chromium that still owns the profile dir.
31
+ *
32
+ * A stale local lock (owning PID gone) is released automatically; a SERVER
33
+ * durable lease is NEVER auto-cleared here (F2).
34
+ */
35
+
36
+ const fs = require('fs');
37
+ const os = require('os');
38
+ const path = require('path');
39
+
40
+ /** Terminal states are the ones that are safe to remove from the registry. */
41
+ const LIVE_STATES = Object.freeze(['starting', 'running', 'stopping']);
42
+
43
+ /**
44
+ * How long a `starting` entry (no browser PID yet) counts as live. Bounded so a
45
+ * launch that died mid-flight cannot permanently block the account locally; in
46
+ * production a real launch records the browser PID within seconds.
47
+ */
48
+ const START_WINDOW_MS = (() => {
49
+ const v = parseInt(process.env.XKWDSTORE_START_WINDOW_MS || '', 10);
50
+ return Number.isFinite(v) && v > 0 ? v : 120 * 1000;
51
+ })();
52
+
53
+ class SessionRegistryError extends Error {
54
+ constructor(message, code) {
55
+ super(message);
56
+ this.code = code || 'SESSION_REGISTRY_ERROR';
57
+ this.name = 'SessionRegistryError';
58
+ }
59
+ }
60
+
61
+ function defaultRegistryPath() {
62
+ const override = process.env.XKWDSTORE_SESSION_REGISTRY;
63
+ if (override && String(override).trim()) return path.resolve(String(override).trim());
64
+ // Resolve lazily so requiring this module never triggers machine I/O in tests.
65
+ const { getMachineRoot } = require('./deviceKeyStore');
66
+ return path.join(getMachineRoot(), 'runtime', 'sessions.json');
67
+ }
68
+
69
+ /** Stable per-account registry key (accountUuid preferred, else accountId). */
70
+ function sessionKey({ accountUuid, accountId } = {}) {
71
+ if (accountUuid && String(accountUuid).trim()) return String(accountUuid).trim();
72
+ return 'acct-' + String(accountId == null ? 'unknown' : accountId);
73
+ }
74
+
75
+ function _read(registryPath) {
76
+ try {
77
+ if (!fs.existsSync(registryPath)) return { version: 1, sessions: {} };
78
+ const parsed = JSON.parse(fs.readFileSync(registryPath, 'utf8'));
79
+ if (!parsed || typeof parsed !== 'object' || typeof parsed.sessions !== 'object' || parsed.sessions === null) {
80
+ return { version: 1, sessions: {} };
81
+ }
82
+ return { version: 1, sessions: parsed.sessions };
83
+ } catch {
84
+ // A torn/corrupt registry is not authoritative for a live browser — treat it
85
+ // as empty so a corrupted file cannot permanently block a profile. The
86
+ // SERVER lease still protects the account.
87
+ return { version: 1, sessions: {} };
88
+ }
89
+ }
90
+
91
+ function _write(registryPath, data) {
92
+ const dir = path.dirname(registryPath);
93
+ try { fs.mkdirSync(dir, { recursive: true, mode: 0o700 }); } catch { /* best-effort */ }
94
+ const tmp = path.join(dir, `.sessions.json.tmp.${process.pid}.${Date.now()}`);
95
+ const payload = JSON.stringify({ version: 1, updatedAt: new Date().toISOString(), sessions: data.sessions }, null, 2);
96
+ try {
97
+ fs.writeFileSync(tmp, payload, { encoding: 'utf8', mode: 0o600 });
98
+ fs.renameSync(tmp, registryPath);
99
+ } catch (e) {
100
+ try { if (fs.existsSync(tmp)) fs.unlinkSync(tmp); } catch { /* best-effort */ }
101
+ throw new SessionRegistryError('could not write the session registry: ' + ((e && e.message) || 'unknown'), 'SESSION_REGISTRY_WRITE_FAILED');
102
+ }
103
+ }
104
+
105
+ /** True when a PID is alive. */
106
+ function isProcessRunning(pid) {
107
+ if (!pid || typeof pid !== 'number') return false;
108
+ try { process.kill(pid, 0); return true; } catch { return false; }
109
+ }
110
+
111
+ /** True when the exact profile dir is held by a live browser PID recorded here. */
112
+ function _isEntryLive(entry) {
113
+ if (!entry) return false;
114
+ if (!LIVE_STATES.includes(entry.state)) return false;
115
+ if (isProcessRunning(entry.browserPid)) return true;
116
+ // No browser PID yet (still starting): live only while the OWNING AGENT is
117
+ // alive AND the entry is still within a short launch window. The window is
118
+ // bounded (START_WINDOW_MS) because a `starting` entry that never recorded a
119
+ // browser PID is a launch that failed/died — a stale one must not block the
120
+ // account locally on the next attempt.
121
+ if (!entry.browserPid && isProcessRunning(entry.agentPid)) {
122
+ const age = Date.now() - Date.parse(entry.startedAt || 0);
123
+ return Number.isFinite(age) && age < START_WINDOW_MS;
124
+ }
125
+ return false;
126
+ }
127
+
128
+ /**
129
+ * Acquire the AGENT-LOCAL profile lock for one session. Fails when a live agent
130
+ * session already owns the same profile dir (duplicate launch defense).
131
+ *
132
+ * @returns {{acquired:boolean, existing?:object, code?:string}}
133
+ */
134
+ function acquireLocalLock({ registryPath = defaultRegistryPath(), accountUuid, accountId, profilePath, leaseId, proxyIdentity, runtimeDir } = {}) {
135
+ const key = sessionKey({ accountUuid, accountId });
136
+ const data = _read(registryPath);
137
+
138
+ // Reap entries whose owning process is gone so a crash cannot permanently
139
+ // block a profile (F2). This does NOT touch the server lease.
140
+ let changed = false;
141
+ for (const [k, entry] of Object.entries(data.sessions)) {
142
+ if (!_isEntryLive(entry)) { delete data.sessions[k]; changed = true; }
143
+ }
144
+
145
+ const existing = data.sessions[key];
146
+ if (existing && _isEntryLive(existing)) {
147
+ if (changed) _write(registryPath, data);
148
+ return { acquired: false, code: 'LOCAL_SESSION_EXISTS', existing };
149
+ }
150
+
151
+ // Same-profile guard: another LIVE session (different account key) must not
152
+ // own this exact profile dir.
153
+ const normalizedTarget = profilePath ? path.resolve(profilePath).toLowerCase() : null;
154
+ if (normalizedTarget) {
155
+ for (const entry of Object.values(data.sessions)) {
156
+ if (!_isEntryLive(entry)) continue;
157
+ if (entry.profilePath && path.resolve(entry.profilePath).toLowerCase() === normalizedTarget) {
158
+ if (changed) _write(registryPath, data);
159
+ return { acquired: false, code: 'LOCAL_PROFILE_LOCKED', existing: entry };
160
+ }
161
+ }
162
+ }
163
+
164
+ data.sessions[key] = {
165
+ accountUuid: accountUuid || null,
166
+ accountId: accountId == null ? null : String(accountId),
167
+ leaseId: leaseId ? String(leaseId) : null,
168
+ profilePath: profilePath || null,
169
+ browserPid: null,
170
+ sessionKey: key,
171
+ proxyIdentity: proxyIdentity || null,
172
+ runtimeDir: runtimeDir || null,
173
+ startedAt: new Date().toISOString(),
174
+ state: 'starting',
175
+ agentPid: process.pid,
176
+ hostname: os.hostname(),
177
+ };
178
+ _write(registryPath, data);
179
+ return { acquired: true, entry: data.sessions[key] };
180
+ }
181
+
182
+ /** Record the browser PID + running state for an acquired session. */
183
+ function markRunning({ registryPath = defaultRegistryPath(), accountUuid, accountId, browserPid } = {}) {
184
+ const key = sessionKey({ accountUuid, accountId });
185
+ const data = _read(registryPath);
186
+ if (!data.sessions[key]) return false;
187
+ data.sessions[key].browserPid = browserPid || null;
188
+ data.sessions[key].state = 'running';
189
+ data.sessions[key].runningAt = new Date().toISOString();
190
+ _write(registryPath, data);
191
+ return true;
192
+ }
193
+
194
+ /** Release the local lock and remove the entry (verified-stop bookkeeping). */
195
+ function releaseLocalLock({ registryPath = defaultRegistryPath(), accountUuid, accountId } = {}) {
196
+ const key = sessionKey({ accountUuid, accountId });
197
+ const data = _read(registryPath);
198
+ if (!data.sessions[key]) return false;
199
+ delete data.sessions[key];
200
+ _write(registryPath, data);
201
+ return true;
202
+ }
203
+
204
+ /** Read the current registry (live + stale entries as recorded). */
205
+ function readRegistry(registryPath = defaultRegistryPath()) {
206
+ return _read(registryPath).sessions;
207
+ }
208
+
209
+ /** Live entries only (owning process still alive). */
210
+ function liveSessions(registryPath = defaultRegistryPath()) {
211
+ const data = _read(registryPath);
212
+ return Object.values(data.sessions).filter(_isEntryLive);
213
+ }
214
+
215
+ /**
216
+ * Crash recovery (F1): find entries recorded by THIS agent (matching device
217
+ * identity / machine) whose owning AGENT process is gone but whose BROWSER PID
218
+ * is still alive — these are agent-owned orphans that should be re-adopted or
219
+ * terminated. Never reports an unrelated user's Chrome: ownership requires a
220
+ * registry entry that this agent wrote.
221
+ *
222
+ * @returns {Array<object>} orphaned entries
223
+ */
224
+ function findOrphans(registryPath = defaultRegistryPath()) {
225
+ const data = _read(registryPath);
226
+ const orphans = [];
227
+ for (const entry of Object.values(data.sessions)) {
228
+ // Not the same machine/device → not ours.
229
+ if (entry.hostname && entry.hostname !== os.hostname()) continue;
230
+ const agentGone = !isProcessRunning(entry.agentPid);
231
+ const browserAlive = isProcessRunning(entry.browserPid);
232
+ if (agentGone && browserAlive) orphans.push(entry);
233
+ }
234
+ return orphans;
235
+ }
236
+
237
+ /**
238
+ * Classify whether a given browser PID is AGENT-OWNED. "Is chrome.exe" is not
239
+ * enough — only a PID that appears in OUR registry (or in the supplied
240
+ * agent-owned PID set) may ever be terminated. This is the guard behind
241
+ * "never kill unrelated user Chrome".
242
+ */
243
+ function isAgentOwnedPid(pid, { registryPath = defaultRegistryPath(), agentOwnedPids = null } = {}) {
244
+ if (!pid) return false;
245
+ if (agentOwnedPids && agentOwnedPids.has(pid)) return true;
246
+ const data = _read(registryPath);
247
+ return Object.values(data.sessions).some((e) => e.browserPid === pid);
248
+ }
249
+
250
+ /**
251
+ * Reap entries whose owning process is gone AND whose browser is gone, so the
252
+ * registry does not grow forever. Returns the number removed.
253
+ */
254
+ function reapDeadEntries(registryPath = defaultRegistryPath()) {
255
+ const data = _read(registryPath);
256
+ let removed = 0;
257
+ for (const [k, entry] of Object.entries(data.sessions)) {
258
+ const agentGone = !isProcessRunning(entry.agentPid);
259
+ const browserGone = !isProcessRunning(entry.browserPid);
260
+ if (agentGone && browserGone) { delete data.sessions[k]; removed += 1; }
261
+ }
262
+ if (removed > 0) _write(registryPath, data);
263
+ return removed;
264
+ }
265
+
266
+ module.exports = {
267
+ LIVE_STATES,
268
+ SessionRegistryError,
269
+ defaultRegistryPath,
270
+ sessionKey,
271
+ acquireLocalLock,
272
+ markRunning,
273
+ releaseLocalLock,
274
+ readRegistry,
275
+ liveSessions,
276
+ findOrphans,
277
+ isAgentOwnedPid,
278
+ reapDeadEntries,
279
+ isProcessRunning,
280
+ };
package/src/worker.js ADDED
@@ -0,0 +1,253 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Interactive Browser Worker entry point (TW-manager Agent 2.1.0).
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
+ * - understands ONLY typed browser commands (see brokerWorkerBridge)
12
+ * - NEVER reads the device private key
13
+ * - NEVER enrolls / registers the device
14
+ * - NEVER opens the server WebSocket
15
+ *
16
+ * The worker is deliberately small: all authority (identity, server connection,
17
+ * leases, policy) lives in the broker. The worker is a capability-limited
18
+ * executor so a compromised worker cannot impersonate the machine device.
19
+ *
20
+ * Usage (the broker passes these; an operator never runs this directly):
21
+ * node src/worker.js --port <n> --token <one-time> [--chrome <path>]
22
+ */
23
+
24
+ const path = require('path');
25
+ const os = require('os');
26
+
27
+ function parseArgs(argv) {
28
+ const out = {};
29
+ for (let i = 0; i < argv.length; i++) {
30
+ const a = argv[i];
31
+ if (a === '--port') out.port = parseInt(argv[++i], 10);
32
+ else if (a.startsWith('--port=')) out.port = parseInt(a.slice(7), 10);
33
+ else if (a === '--token') out.token = argv[++i];
34
+ else if (a.startsWith('--token=')) out.token = a.slice(8);
35
+ else if (a === '--chrome') out.chrome = argv[++i];
36
+ else if (a.startsWith('--chrome=')) out.chrome = a.slice(9);
37
+ }
38
+ return out;
39
+ }
40
+
41
+ /**
42
+ * Build the worker's command handler. The worker owns the browser lifecycle; the
43
+ * broker owns everything else. Each command is bound to an account+lease supplied
44
+ * by the broker as typed data (never a raw shell command).
45
+ */
46
+ function buildWorkerHandler(opts) {
47
+ const { chromePath } = opts;
48
+ // The real browser runtime: reuse the hardened session handler's primitives.
49
+ const bi = require('./browserIsolation');
50
+ const sessionRegistry = require('./sessionRegistry');
51
+ const { getMachineRoot } = require('./deviceKeyStore');
52
+
53
+ // Per-account live contexts owned by THIS worker process.
54
+ const contexts = new Map(); // accountKey -> { context, runtimeDirs, sessionsRoot, profileDir }
55
+
56
+ async function startSession(payload) {
57
+ const accountKey = String(payload.accountUuid || payload.accountId || '');
58
+ if (!accountKey) throw Object.assign(new Error('missing account identity'), { code: 'WORKER_NO_ACCOUNT' });
59
+ if (contexts.has(accountKey)) {
60
+ return { alreadyRunning: true, accountKey };
61
+ }
62
+ const profileDir = payload.profileDir;
63
+ if (!profileDir) throw Object.assign(new Error('missing profileDir'), { code: 'WORKER_NO_PROFILE' });
64
+
65
+ // Local profile lock (agent-local), in addition to the broker's server lease.
66
+ const lock = sessionRegistry.acquireLocalLock({
67
+ accountUuid: payload.accountUuid || null,
68
+ accountId: payload.accountId || accountKey,
69
+ profilePath: profileDir,
70
+ });
71
+ if (!lock.acquired) {
72
+ throw Object.assign(new Error('local profile lock refused: ' + (lock.code || 'LOCAL_SESSION_EXISTS')), { code: lock.code || 'LOCAL_SESSION_EXISTS' });
73
+ }
74
+
75
+ const sessionsRoot = path.join(getMachineRoot(), 'state', 'sessions');
76
+ const runtimeDirs = bi.createSessionRuntimeDirs(sessionsRoot, accountKey);
77
+
78
+ const requireProxy = payload.requireProxy === true;
79
+ // The broker may hand us EITHER an already-parsed proxy identity OR a raw
80
+ // connection string. Both are normalized here through the ONE canonical
81
+ // parser so a payload-shape change can never again surface as the opaque
82
+ // "proxy binding failed": every failure is classified with a typed code and
83
+ // a non-secret description.
84
+ const coerced = bi.coerceProxyIdentity(payload.proxy || null);
85
+ let proxy = null;
86
+ let proxyOption = null;
87
+ if (requireProxy) {
88
+ if (!coerced.ok) {
89
+ sessionRegistry.releaseLocalLock({ accountUuid: payload.accountUuid, accountId: payload.accountId });
90
+ throw Object.assign(
91
+ new Error(`proxy binding failed: ${coerced.detail}`),
92
+ {
93
+ code: coerced.code || 'PROXY_UNAVAILABLE',
94
+ stage: 'proxy_binding',
95
+ accountId: payload.accountId || null,
96
+ accountUuid: payload.accountUuid || null,
97
+ proxyId: payload.proxyId != null ? payload.proxyId : null,
98
+ proxy: bi.maskProxyForLog(payload.proxy),
99
+ },
100
+ );
101
+ }
102
+ proxy = coerced.identity;
103
+ const bind = bi.buildProxyLaunchBinding(proxy, { allowInlineCredentials: process.env.XKWDSTORE_INLINE_PROXY_CREDENTIALS === 'true' });
104
+ if (!bind.ok) {
105
+ sessionRegistry.releaseLocalLock({ accountUuid: payload.accountUuid, accountId: payload.accountId });
106
+ throw Object.assign(
107
+ new Error(`proxy binding failed: ${bind.code}`),
108
+ {
109
+ code: bind.code || 'PROXY_UNAVAILABLE',
110
+ stage: 'proxy_binding',
111
+ accountId: payload.accountId || null,
112
+ accountUuid: payload.accountUuid || null,
113
+ proxyId: payload.proxyId != null ? payload.proxyId : null,
114
+ proxy: bi.maskProxyForLog(proxy),
115
+ },
116
+ );
117
+ }
118
+ proxyOption = bind.proxyOption;
119
+ if (!proxyOption) {
120
+ sessionRegistry.releaseLocalLock({ accountUuid: payload.accountUuid, accountId: payload.accountId });
121
+ throw Object.assign(
122
+ new Error('proxy binding failed: a proxy is required but the binding produced no proxy option'),
123
+ { code: 'PROXY_UNAVAILABLE', stage: 'proxy_binding', accountId: payload.accountId || null, accountUuid: payload.accountUuid || null, proxyId: payload.proxyId != null ? payload.proxyId : null, proxy: bi.maskProxyForLog(proxy) },
124
+ );
125
+ }
126
+ }
127
+
128
+ const args = bi.buildLaunchArgs({
129
+ requireProxy,
130
+ proxyServerUrl: requireProxy && !proxyOption && proxy ? proxy.server : null,
131
+ proxyHostForDns: requireProxy && proxy ? proxy.host : null,
132
+ baseArgs: ['--no-first-run', '--no-default-browser-check', '--start-maximized'],
133
+ });
134
+
135
+ const { chromium } = require('playwright-core');
136
+ const launchOptions = {
137
+ executablePath: chromePath || payload.chromePath,
138
+ headless: payload.headless === true,
139
+ args,
140
+ noDefaultViewport: true,
141
+ };
142
+ if (proxyOption) launchOptions.proxy = proxyOption;
143
+
144
+ let context;
145
+ try {
146
+ context = await chromium.launchPersistentContext(profileDir, launchOptions);
147
+ } catch (err) {
148
+ sessionRegistry.releaseLocalLock({ accountUuid: payload.accountUuid, accountId: payload.accountId });
149
+ throw Object.assign(new Error('launch failed: ' + err.message), { code: 'WORKER_LAUNCH_FAILED' });
150
+ }
151
+ contexts.set(accountKey, { context, runtimeDirs, sessionsRoot, profileDir, accountUuid: payload.accountUuid, accountId: payload.accountId });
152
+ // Record the real browser PID so crash recovery can prove ownership of the
153
+ // exact process (never "any chrome.exe"). Resolved by exact profile dir.
154
+ let browserPid = null;
155
+ try { browserPid = require('./brokerWorkerBridge').resolveChromePidForProfile(profileDir); } catch { browserPid = null; }
156
+ if (browserPid) {
157
+ sessionRegistry.markRunning({ accountUuid: payload.accountUuid || null, accountId: payload.accountId || accountKey, browserPid });
158
+ }
159
+ context.on('close', () => {
160
+ const entry = contexts.get(accountKey);
161
+ if (entry) {
162
+ try { bi.cleanupSessionRuntimeDirs(entry.sessionsRoot, accountKey); } catch { }
163
+ sessionRegistry.releaseLocalLock({ accountUuid: entry.accountUuid, accountId: entry.accountId });
164
+ contexts.delete(accountKey);
165
+ }
166
+ });
167
+ return { started: true, accountKey, profileDir, visible: true };
168
+ }
169
+
170
+ async function stopSession(payload) {
171
+ const accountKey = String(payload.accountUuid || payload.accountId || '');
172
+ const entry = contexts.get(accountKey);
173
+ if (!entry) return { stopped: false, reason: 'not running' };
174
+ try { await entry.context.close(); } catch { }
175
+ try { bi.cleanupSessionRuntimeDirs(entry.sessionsRoot, accountKey); } catch { }
176
+ sessionRegistry.releaseLocalLock({ accountUuid: entry.accountUuid, accountId: entry.accountId });
177
+ contexts.delete(accountKey);
178
+ return { stopped: true, accountKey };
179
+ }
180
+
181
+ return async function handler(command, payload) {
182
+ switch (command) {
183
+ case 'startSession': return startSession(payload);
184
+ case 'stopSession': return stopSession(payload);
185
+ case 'getStatus': {
186
+ const accountKey = String(payload.accountUuid || payload.accountId || '');
187
+ const entry = contexts.get(accountKey);
188
+ return { running: !!entry, accountKey, contexts: contexts.size };
189
+ }
190
+ case 'focus': {
191
+ const accountKey = String(payload.accountUuid || payload.accountId || '');
192
+ const entry = contexts.get(accountKey);
193
+ if (!entry) return { focused: false };
194
+ const pages = entry.context.pages();
195
+ if (pages[0]) { try { await pages[0].bringToFront(); } catch { } }
196
+ return { focused: true };
197
+ }
198
+ case 'closeAll': {
199
+ for (const [key, entry] of Array.from(contexts.entries())) {
200
+ try { await entry.context.close(); } catch { }
201
+ try { bi.cleanupSessionRuntimeDirs(entry.sessionsRoot, key); } catch { }
202
+ sessionRegistry.releaseLocalLock({ accountUuid: entry.accountUuid, accountId: entry.accountId });
203
+ contexts.delete(key);
204
+ }
205
+ return { closed: true };
206
+ }
207
+ case 'recoverOrphans': {
208
+ const mod = require('./sessionHandler');
209
+ return mod.recoverOrphanedSessions();
210
+ }
211
+ case 'proxy-test': {
212
+ // No browser: reuse the hardened device-side executor.
213
+ const mod = require('./sessionHandler');
214
+ return mod._proxyTest(payload);
215
+ }
216
+ case 'shutdown': {
217
+ setImmediate(() => process.exit(0));
218
+ return { shuttingDown: true };
219
+ }
220
+ default:
221
+ throw Object.assign(new Error('unknown command ' + command), { code: 'UNKNOWN_COMMAND' });
222
+ }
223
+ };
224
+ }
225
+
226
+ async function main() {
227
+ const args = parseArgs(process.argv.slice(2));
228
+ if (!args.port || !args.token) {
229
+ console.error('worker: --port and --token are required (spawned by the broker)');
230
+ process.exit(2);
231
+ }
232
+ const { resolveChromeOrFail } = require('./chromeDetector');
233
+ let chromePath = args.chrome;
234
+ if (!chromePath) {
235
+ try { chromePath = resolveChromeOrFail().chromePath; } catch { chromePath = null; }
236
+ }
237
+ const bridge = require('./brokerWorkerBridge');
238
+ const handler = buildWorkerHandler({ chromePath });
239
+ try {
240
+ const conn = await bridge.openWorkerChannel({ port: args.port, token: args.token, handler });
241
+ // The worker stays alive until the broker closes the channel.
242
+ conn.on('close', () => process.exit(0));
243
+ } catch (e) {
244
+ console.error('worker: could not attach to broker: ' + ((e && e.message) || 'unknown'));
245
+ process.exit(3);
246
+ }
247
+ }
248
+
249
+ if (require.main === module) {
250
+ main();
251
+ }
252
+
253
+ module.exports = { buildWorkerHandler, parseArgs };