@rezkam/browser-tools 0.2.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,1450 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { spawn, spawnSync } from 'node:child_process';
3
+ import {
4
+ accessSync,
5
+ chmodSync,
6
+ constants as fsConstants,
7
+ existsSync,
8
+ mkdirSync,
9
+ readdirSync,
10
+ readFileSync,
11
+ rmSync,
12
+ statSync,
13
+ writeFileSync,
14
+ } from 'node:fs';
15
+ import { homedir, tmpdir } from 'node:os';
16
+ import { delimiter, dirname, join } from 'node:path';
17
+ import puppeteer from 'puppeteer-core';
18
+
19
+ export const DEFAULT_PORT = 9222;
20
+ export const CONNECT_PROBE_TIMEOUT_MS = 3000;
21
+ export const CHROME_READY_TIMEOUT_MS = 15000;
22
+ export const CHROME_READY_PROBE_TIMEOUT_MS = 250;
23
+ export const DEFAULT_CHROME_BIN = '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome';
24
+ export const DEFAULT_CHROME_SRC = join(homedir(), 'Library', 'Application Support', 'Google', 'Chrome');
25
+ export const DEFAULT_CACHE_DIR = join(homedir(), '.cache', 'pi-browser-tools');
26
+ export const DEFAULT_ARTIFACT_DIR = tmpdir();
27
+
28
+ // Legacy path constants are retained for older scripts that imported the pre-config Browser Tools API.
29
+ // New runtime code should use browserToolsRuntimeConfig() and path helpers so env and private config overrides are honored.
30
+ export const CHROME_BIN = DEFAULT_CHROME_BIN;
31
+ export const CHROME_SRC = DEFAULT_CHROME_SRC;
32
+ export const CACHE_DIR = DEFAULT_CACHE_DIR;
33
+ export const PROFILE_DST = join(CACHE_DIR, 'chrome-data');
34
+ export const FRESH_PROFILE_DIR = join(CACHE_DIR, 'chrome-fresh');
35
+ export const PROFILE_SYNC_STATE_FILE = join(CACHE_DIR, 'chrome-profile-sync.json');
36
+ export const OWNER_TOKEN_ENV = 'BROWSER_TOOLS_OWNER_TOKEN';
37
+ export const OWNER_ID_ENV = 'BROWSER_TOOLS_OWNER_ID';
38
+ export const OWNER_TOKEN_HASH_ALGORITHM = 'sha256';
39
+ export const PORT_LOCK_STALE_MS = 30000;
40
+
41
+ export function agentConfigRoot() {
42
+ return process.env.AGENT_CONFIG_DIR || join(homedir(), '.agents');
43
+ }
44
+
45
+ export function browserToolsConfigDir() {
46
+ return process.env.BROWSER_TOOLS_CONFIG_DIR || join(agentConfigRoot(), 'browser-tools');
47
+ }
48
+
49
+ function resolveBrowserToolsConfigDir(configDir = browserToolsConfigDir()) {
50
+ return configDir || browserToolsConfigDir();
51
+ }
52
+
53
+ export function browserToolsConfigFile(configDir = browserToolsConfigDir()) {
54
+ return join(resolveBrowserToolsConfigDir(configDir), 'config.json');
55
+ }
56
+
57
+ // Compatibility alias for the earlier Chrome profiles config file name.
58
+ export function browserToolsProfilesConfigFile(configDir = browserToolsConfigDir()) {
59
+ return browserToolsConfigFile(configDir);
60
+ }
61
+
62
+ export function expandHomePath(value) {
63
+ if (!value || typeof value !== 'string') return value;
64
+ if (value === '~') return homedir();
65
+ if (value.startsWith('~/')) return join(homedir(), value.slice(2));
66
+ return value;
67
+ }
68
+
69
+ export function browserToolsRuntimeConfig({ configDir = browserToolsConfigDir() } = {}) {
70
+ const effectiveConfigDir = resolveBrowserToolsConfigDir(configDir);
71
+ const config = safeReadJson(browserToolsConfigFile(effectiveConfigDir)) || {};
72
+ return {
73
+ configDir: effectiveConfigDir,
74
+ configFile: browserToolsConfigFile(effectiveConfigDir),
75
+ chromeBin: expandHomePath(process.env.BROWSER_TOOLS_CHROME_BIN || config.browser?.chromeBin || config.chromeBin || DEFAULT_CHROME_BIN),
76
+ chromeSourceDir: expandHomePath(process.env.BROWSER_TOOLS_CHROME_SOURCE_DIR || config.directories?.chromeSourceDir || config.sourceDir || DEFAULT_CHROME_SRC),
77
+ cacheDir: expandHomePath(process.env.BROWSER_TOOLS_CACHE_DIR || config.directories?.cacheDir || DEFAULT_CACHE_DIR),
78
+ artifactDir: expandHomePath(process.env.BROWSER_TOOLS_ARTIFACT_DIR || config.directories?.artifactDir || DEFAULT_ARTIFACT_DIR),
79
+ };
80
+ }
81
+
82
+ export function browserToolsChromeBin(options = {}) {
83
+ return browserToolsRuntimeConfig(options).chromeBin;
84
+ }
85
+
86
+ export function browserToolsChromeSourceDir(options = {}) {
87
+ return browserToolsRuntimeConfig(options).chromeSourceDir;
88
+ }
89
+
90
+ export function browserToolsCacheDir(options = {}) {
91
+ return browserToolsRuntimeConfig(options).cacheDir;
92
+ }
93
+
94
+ export function browserToolsArtifactDir(options = {}) {
95
+ return browserToolsRuntimeConfig(options).artifactDir;
96
+ }
97
+
98
+ export function profileDataDirForPort(port = DEFAULT_PORT) {
99
+ return join(browserToolsCacheDir(), `chrome-data-${normalizePort(port)}`);
100
+ }
101
+
102
+ export function freshProfileDirForPort(port = DEFAULT_PORT) {
103
+ return join(browserToolsCacheDir(), `chrome-fresh-${normalizePort(port)}`);
104
+ }
105
+
106
+ export function profileSyncStateFileForPort(port = DEFAULT_PORT) {
107
+ return join(browserToolsCacheDir(), `chrome-profile-sync-${normalizePort(port)}.json`);
108
+ }
109
+
110
+ const PROFILE_SYNC_ITEMS = [
111
+ { path: 'Cookies', type: 'file' },
112
+ { path: 'Cookies-journal', type: 'file' },
113
+ { path: 'Network/Cookies', type: 'file' },
114
+ { path: 'Network/Cookies-journal', type: 'file' },
115
+ { path: 'Network/Network Persistent State', type: 'file' },
116
+ { path: 'Account Web Data', type: 'file' },
117
+ { path: 'Account Web Data-journal', type: 'file' },
118
+ { path: 'Web Data', type: 'file' },
119
+ { path: 'Web Data-journal', type: 'file' },
120
+ { path: 'Safe Browsing Cookies', type: 'file' },
121
+ { path: 'Safe Browsing Cookies-journal', type: 'file' },
122
+ { path: 'Preferences', type: 'file' },
123
+ { path: 'Secure Preferences', type: 'file' },
124
+ { path: 'Local Storage', type: 'dir' },
125
+ { path: 'Session Storage', type: 'dir' },
126
+ { path: 'Storage', type: 'dir' },
127
+ { path: 'TransportSecurity', type: 'file' },
128
+ { path: 'Trust Tokens', type: 'file' },
129
+ { path: 'Extension Cookies', type: 'file' },
130
+ { path: 'Extension Cookies-journal', type: 'file' },
131
+ { path: 'Extensions', type: 'dir' },
132
+ { path: 'Extension State', type: 'dir' },
133
+ { path: 'Extension Rules', type: 'dir' },
134
+ { path: 'Extension Scripts', type: 'dir' },
135
+ { path: 'DNR Extension Rules', type: 'dir' },
136
+ { path: 'Local Extension Settings', type: 'dir' },
137
+ { path: 'Managed Extension Settings', type: 'dir' },
138
+ { path: 'Sync Extension Settings', type: 'dir' },
139
+ ];
140
+
141
+ export function sleep(ms) {
142
+ return new Promise((resolve) => setTimeout(resolve, ms));
143
+ }
144
+
145
+ export function ensureCacheDir(cacheDir = browserToolsCacheDir()) {
146
+ mkdirSync(cacheDir, { recursive: true, mode: 0o700 });
147
+ try {
148
+ chmodSync(cacheDir, 0o700);
149
+ } catch {
150
+ // Best effort. Existing permissions should not block browser use.
151
+ }
152
+ }
153
+
154
+ function writePrivateFile(file, content) {
155
+ writeFileSync(file, content, { mode: 0o600 });
156
+ try {
157
+ chmodSync(file, 0o600);
158
+ } catch {
159
+ // Best effort. The owner token is not written in plain text, but state still belongs to one local agent.
160
+ }
161
+ }
162
+
163
+ export function optionValue(args, name, fallback = null) {
164
+ const i = args.indexOf(name);
165
+ if (i === -1) return fallback;
166
+ const value = args[i + 1];
167
+ if (value === undefined || value.startsWith('--')) return true;
168
+ return value;
169
+ }
170
+
171
+ export function requiredOptionValue(args, name, fallback = null) {
172
+ const i = args.indexOf(name);
173
+ if (i === -1) return fallback;
174
+ const value = args[i + 1];
175
+ if (value === undefined || value.startsWith('--')) throw new Error(`Missing value after ${name}`);
176
+ return value;
177
+ }
178
+
179
+ export function parsePositiveIntegerOption(args, name, fallback) {
180
+ const value = optionValue(args, name, fallback);
181
+ if (value === fallback) return fallback;
182
+ if (value === true) throw new Error(`Missing ${name} value: expected a positive integer`);
183
+
184
+ const normalized = String(value).trim();
185
+ if (!/^[1-9]\d*$/.test(normalized)) {
186
+ throw new Error(`Invalid ${name} value: expected a positive integer, got "${value}"`);
187
+ }
188
+
189
+ return Number.parseInt(normalized, 10);
190
+ }
191
+
192
+ export function hasFlag(args, name) {
193
+ return args.includes(name);
194
+ }
195
+
196
+ export function normalizePort(value = DEFAULT_PORT) {
197
+ const port = Number.parseInt(String(value ?? DEFAULT_PORT), 10);
198
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
199
+ throw new Error(`Invalid --port value: ${value}`);
200
+ }
201
+ return port;
202
+ }
203
+
204
+ export function parsePort(args, fallback = DEFAULT_PORT) {
205
+ return normalizePort(requiredOptionValue(args, '--port', fallback));
206
+ }
207
+
208
+ function normalizeOwnerValue(value) {
209
+ if (value === undefined || value === null || value === true) return null;
210
+ const normalized = String(value).trim();
211
+ return normalized || null;
212
+ }
213
+
214
+ export function generateOwnerToken() {
215
+ return randomUUID();
216
+ }
217
+
218
+ export function ownerTokenHash(ownerToken) {
219
+ const token = normalizeOwnerValue(ownerToken);
220
+ if (!token) throw new Error('Missing browser owner token');
221
+ return createHash(OWNER_TOKEN_HASH_ALGORITHM).update(token, 'utf8').digest('hex');
222
+ }
223
+
224
+ export function parseOwnerToken(args, fallback = process.env[OWNER_TOKEN_ENV] || null) {
225
+ return normalizeOwnerValue(requiredOptionValue(args, '--owner-token', fallback));
226
+ }
227
+
228
+ export function parseOwnerId(args, fallback = process.env[OWNER_ID_ENV] || null) {
229
+ if (args.includes('--owner-id')) return normalizeOwnerValue(requiredOptionValue(args, '--owner-id', fallback));
230
+ return normalizeOwnerValue(requiredOptionValue(args, '--agent-id', fallback));
231
+ }
232
+
233
+ export function stripBrowserSessionArgs(args, { stripPort = true, stripPositionalPort = false } = {}) {
234
+ const stripped = [];
235
+ const optionsWithValues = new Set(['--owner-token', '--owner-id', '--agent-id']);
236
+ if (stripPort) optionsWithValues.add('--port');
237
+
238
+ for (let i = 0; i < args.length; i += 1) {
239
+ const arg = args[i];
240
+ if (optionsWithValues.has(arg)) {
241
+ const next = args[i + 1];
242
+ if (next !== undefined && !next.startsWith('--')) i += 1;
243
+ continue;
244
+ }
245
+ if (stripPositionalPort && /^\d{4,5}$/.test(arg)) continue;
246
+ stripped.push(arg);
247
+ }
248
+
249
+ return stripped;
250
+ }
251
+
252
+ function buildOwnerState({ ownerToken, ownerId = null }) {
253
+ return {
254
+ ownerId: normalizeOwnerValue(ownerId),
255
+ ownerTokenHash: ownerTokenHash(ownerToken),
256
+ ownerTokenHashAlgorithm: OWNER_TOKEN_HASH_ALGORITHM,
257
+ };
258
+ }
259
+
260
+ export function managedBrowserOwnershipSafety({ state, ownerToken }) {
261
+ if (!state || state.managedBy !== 'browser-tools') {
262
+ return { ok: false, reason: 'missing-managed-state' };
263
+ }
264
+ if (!state.ownerTokenHash) {
265
+ return { ok: false, reason: 'missing-state-owner-token', ownerId: state.ownerId || null };
266
+ }
267
+ const token = normalizeOwnerValue(ownerToken);
268
+ if (!token) {
269
+ return { ok: false, reason: 'missing-owner-token', ownerId: state.ownerId || null };
270
+ }
271
+ if (ownerTokenHash(token) !== state.ownerTokenHash) {
272
+ return { ok: false, reason: 'owner-token-mismatch', ownerId: state.ownerId || null };
273
+ }
274
+ return { ok: true, ownerId: state.ownerId || null };
275
+ }
276
+
277
+ export function pidFileForPort(port) {
278
+ return join(browserToolsCacheDir(), `chrome-${normalizePort(port)}.pid`);
279
+ }
280
+
281
+ export function stateFileForPort(port) {
282
+ return join(browserToolsCacheDir(), `chrome-${normalizePort(port)}.json`);
283
+ }
284
+
285
+ export function portLockDirForPort(port) {
286
+ return join(browserToolsCacheDir(), `chrome-${normalizePort(port)}.lock`);
287
+ }
288
+
289
+ export function chromePaths(port = DEFAULT_PORT) {
290
+ const runtime = browserToolsRuntimeConfig();
291
+ return {
292
+ chromeBin: runtime.chromeBin,
293
+ chromeSourceDir: runtime.chromeSourceDir,
294
+ cacheDir: runtime.cacheDir,
295
+ artifactDir: runtime.artifactDir,
296
+ configDir: runtime.configDir,
297
+ configFile: runtime.configFile,
298
+ profileDataDir: profileDataDirForPort(port),
299
+ freshProfileDir: freshProfileDirForPort(port),
300
+ pidFile: pidFileForPort(port),
301
+ stateFile: stateFileForPort(port),
302
+ };
303
+ }
304
+
305
+ export async function browserWSEndpoint(port = DEFAULT_PORT, timeoutMs = CONNECT_PROBE_TIMEOUT_MS) {
306
+ const normalizedPort = normalizePort(port);
307
+ const controller = new AbortController();
308
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
309
+ try {
310
+ const res = await fetch(`http://localhost:${normalizedPort}/json/version`, { signal: controller.signal });
311
+ if (!res.ok) return null;
312
+ const data = await res.json();
313
+ return data.webSocketDebuggerUrl ?? null;
314
+ } catch {
315
+ return null;
316
+ } finally {
317
+ clearTimeout(timer);
318
+ }
319
+ }
320
+
321
+ export async function waitForChromeReady(
322
+ port = DEFAULT_PORT,
323
+ { timeoutMs = CHROME_READY_TIMEOUT_MS, intervalMs = 250, probeTimeoutMs = CHROME_READY_PROBE_TIMEOUT_MS } = {},
324
+ ) {
325
+ const deadline = Date.now() + timeoutMs;
326
+ while (Date.now() < deadline) {
327
+ const remainingMs = Math.max(1, deadline - Date.now());
328
+ if (await browserWSEndpoint(port, Math.min(probeTimeoutMs, remainingMs))) return true;
329
+ const sleepMs = Math.min(intervalMs, Math.max(0, deadline - Date.now()));
330
+ if (sleepMs > 0) await sleep(sleepMs);
331
+ }
332
+ return false;
333
+ }
334
+
335
+ export function profileCopyReady(profileName, profileDataDir = profileDataDirForPort()) {
336
+ if (!profileName) return false;
337
+ const profileDir = join(profileDataDir, profileName);
338
+ return existsSync(profileDataDir) &&
339
+ existsSync(join(profileDataDir, 'Local State')) &&
340
+ existsSync(profileDir) &&
341
+ profileAuthStateReady(profileDir);
342
+ }
343
+
344
+ export function profileAuthStateReady(profileDir) {
345
+ return existsSync(join(profileDir, 'Cookies')) ||
346
+ existsSync(join(profileDir, 'Network', 'Cookies')) ||
347
+ existsSync(join(profileDir, 'Local Storage'));
348
+ }
349
+
350
+ export function readProfileSyncState(port = null) {
351
+ const stateFile = port === null ? profileSyncStateFileForPort(DEFAULT_PORT) : profileSyncStateFileForPort(port);
352
+ // This is a generated per-port cache file, not user config. A truncated or corrupt one should be
353
+ // treated as a cache miss (forcing a fresh sync), never abort a launch, so swallow parse errors.
354
+ try {
355
+ return safeReadJson(stateFile);
356
+ } catch {
357
+ return null;
358
+ }
359
+ }
360
+
361
+ export function readManagedStateForPort(port = DEFAULT_PORT) {
362
+ return readManagedState(stateFileForPort(port));
363
+ }
364
+
365
+ export function cleanupStaleManagedStateForPort(port = DEFAULT_PORT) {
366
+ const normalizedPort = normalizePort(port);
367
+ const paths = chromePaths(normalizedPort);
368
+ if (!existsSync(paths.pidFile) && !existsSync(paths.stateFile)) return false;
369
+
370
+ if (!existsSync(paths.pidFile) || !existsSync(paths.stateFile)) {
371
+ rmSync(paths.pidFile, { force: true });
372
+ rmSync(paths.stateFile, { force: true });
373
+ return true;
374
+ }
375
+
376
+ const pid = Number.parseInt(readFileSync(paths.pidFile, 'utf-8').trim(), 10);
377
+ if (!Number.isInteger(pid) || !processExists(pid)) {
378
+ rmSync(paths.pidFile, { force: true });
379
+ rmSync(paths.stateFile, { force: true });
380
+ return true;
381
+ }
382
+
383
+ return false;
384
+ }
385
+
386
+ export function acquirePortLock(port = DEFAULT_PORT, { ownerId = null, staleMs = PORT_LOCK_STALE_MS } = {}) {
387
+ const normalizedPort = normalizePort(port);
388
+ ensureCacheDir();
389
+ const lockDir = portLockDirForPort(normalizedPort);
390
+
391
+ for (let attempt = 0; attempt < 2; attempt += 1) {
392
+ try {
393
+ mkdirSync(lockDir, { mode: 0o700 });
394
+ writePrivateFile(join(lockDir, 'lock.json'), JSON.stringify({
395
+ pid: process.pid,
396
+ port: normalizedPort,
397
+ ownerId: normalizeOwnerValue(ownerId),
398
+ createdAt: new Date().toISOString(),
399
+ }, null, 2));
400
+ return {
401
+ port: normalizedPort,
402
+ lockDir,
403
+ release() {
404
+ rmSync(lockDir, { recursive: true, force: true });
405
+ },
406
+ };
407
+ } catch (e) {
408
+ if (e.code !== 'EEXIST') throw e;
409
+ // A start that crashed mid-write can leave a partial or corrupt lock.json. Treat an unreadable
410
+ // lock as having no metadata rather than throwing, so the age-based staleness check below can
411
+ // still recover the port (and a fresh, possibly mid-write lock is left alone until it ages out).
412
+ let lockState = null;
413
+ try {
414
+ lockState = safeReadJson(join(lockDir, 'lock.json'));
415
+ } catch {
416
+ lockState = null;
417
+ }
418
+ let stale = false;
419
+ if (lockState?.pid && !processExists(Number(lockState.pid))) stale = true;
420
+ try {
421
+ const ageMs = Date.now() - statSync(lockDir).mtimeMs;
422
+ if (ageMs > staleMs) stale = true;
423
+ } catch {
424
+ stale = true;
425
+ }
426
+ if (!stale) return null;
427
+ rmSync(lockDir, { recursive: true, force: true });
428
+ }
429
+ }
430
+
431
+ return null;
432
+ }
433
+
434
+ export function managedBrowserSafetyForPort(port = DEFAULT_PORT) {
435
+ const normalizedPort = normalizePort(port);
436
+ const paths = chromePaths(normalizedPort);
437
+ if (!existsSync(paths.stateFile) || !existsSync(paths.pidFile)) {
438
+ return { ok: false, reason: 'missing-managed-state' };
439
+ }
440
+
441
+ const pid = Number.parseInt(readFileSync(paths.pidFile, 'utf-8').trim(), 10);
442
+ if (!Number.isInteger(pid)) return { ok: false, reason: 'invalid-managed-pid' };
443
+ return verifyManagedChromeProcess({ pid, port: normalizedPort, state: readManagedState(paths.stateFile) });
444
+ }
445
+
446
+ export function validateProfileName(profileName) {
447
+ if (!profileName || typeof profileName !== 'string') throw new Error('Missing Chrome profile folder name');
448
+ if (profileName.includes('/') || profileName.includes('\\') || profileName === '.' || profileName === '..') {
449
+ throw new Error(`Invalid Chrome profile folder name: ${profileName}`);
450
+ }
451
+ return profileName;
452
+ }
453
+
454
+ function safeReadJson(file) {
455
+ try {
456
+ return JSON.parse(readFileSync(file, 'utf-8'));
457
+ } catch (error) {
458
+ if (error?.code === 'ENOENT') return null;
459
+ if (error instanceof SyntaxError) {
460
+ throw new Error(`Failed to parse JSON file ${file}: ${error.message}`, { cause: error });
461
+ }
462
+ throw new Error(`Failed to read JSON file ${file}: ${error.message}`, { cause: error });
463
+ }
464
+ }
465
+
466
+ function profileEntry(folder, info = {}) {
467
+ return {
468
+ folder,
469
+ name: info.name || folder,
470
+ account: info.user_name || null,
471
+ gaiaName: info.gaia_name || null,
472
+ lastUsed: Boolean(info.active_time),
473
+ lastActive: false,
474
+ };
475
+ }
476
+
477
+ export function discoverChromeProfiles({ sourceDir = browserToolsChromeSourceDir() } = {}) {
478
+ const localState = safeReadJson(join(sourceDir, 'Local State'));
479
+ const infoCache = localState?.profile?.info_cache || {};
480
+ const lastActiveProfiles = new Set(localState?.profile?.last_active_profiles || []);
481
+ const profiles = Object.entries(infoCache)
482
+ .map(([folder, info]) => ({ ...profileEntry(folder, info), lastActive: lastActiveProfiles.has(folder) }))
483
+ .sort((a, b) => a.folder.localeCompare(b.folder, undefined, { numeric: true }));
484
+
485
+ if (profiles.length) return profiles;
486
+ if (!existsSync(sourceDir)) return [];
487
+
488
+ return readdirSync(sourceDir, { withFileTypes: true })
489
+ .filter((entry) => entry.isDirectory())
490
+ .map((entry) => entry.name)
491
+ .filter((folder) => folder === 'Default' || /^Profile \d+$/.test(folder))
492
+ .filter((folder) => existsSync(join(sourceDir, folder, 'Preferences')))
493
+ .sort((a, b) => a.localeCompare(b, undefined, { numeric: true }))
494
+ .map((folder) => profileEntry(folder));
495
+ }
496
+
497
+ function buildAliases(profiles) {
498
+ const aliasCandidates = new Map();
499
+ for (const profile of profiles) {
500
+ for (const alias of [profile.folder, profile.name, profile.account, profile.gaiaName].filter(Boolean)) {
501
+ const key = String(alias).trim();
502
+ if (!key) continue;
503
+ if (!aliasCandidates.has(key)) aliasCandidates.set(key, new Set());
504
+ aliasCandidates.get(key).add(profile.folder);
505
+ }
506
+ }
507
+
508
+ const aliases = {};
509
+ for (const [alias, folders] of aliasCandidates.entries()) {
510
+ if (folders.size === 1) aliases[alias] = [...folders][0];
511
+ }
512
+ return aliases;
513
+ }
514
+
515
+ export function buildBrowserToolsConfig({ sourceDir = browserToolsChromeSourceDir(), existing = null } = {}) {
516
+ const profiles = discoverChromeProfiles({ sourceDir });
517
+ const existingDirectories = existing?.directories || {};
518
+ const existingBrowser = existing?.browser || {};
519
+ return {
520
+ version: 1,
521
+ generatedAt: new Date().toISOString(),
522
+ sourceDir,
523
+ directories: {
524
+ chromeSourceDir: existingDirectories.chromeSourceDir || sourceDir,
525
+ cacheDir: existingDirectories.cacheDir || browserToolsCacheDir(),
526
+ artifactDir: existingDirectories.artifactDir || browserToolsArtifactDir(),
527
+ },
528
+ browser: {
529
+ chromeBin: existingBrowser.chromeBin || browserToolsChromeBin(),
530
+ },
531
+ profiles: Object.fromEntries(profiles.map((profile) => [profile.folder, profile])),
532
+ aliases: buildAliases(profiles),
533
+ taskProfiles: existing?.taskProfiles || {},
534
+ };
535
+ }
536
+
537
+ // Compatibility wrappers for the earlier Chrome profiles config API.
538
+ // Keep them as direct aliases to the Browser Tools config layer.
539
+ export function buildChromeProfilesConfig(options = {}) {
540
+ return buildBrowserToolsConfig(options);
541
+ }
542
+
543
+ export function readBrowserToolsConfig({ configDir = browserToolsConfigDir() } = {}) {
544
+ return safeReadJson(browserToolsConfigFile(resolveBrowserToolsConfigDir(configDir)));
545
+ }
546
+
547
+ export function readChromeProfilesConfig(options = {}) {
548
+ return readBrowserToolsConfig(options);
549
+ }
550
+
551
+ export function writeBrowserToolsConfig(config, { configDir = browserToolsConfigDir() } = {}) {
552
+ const effectiveConfigDir = resolveBrowserToolsConfigDir(configDir);
553
+ mkdirSync(effectiveConfigDir, { recursive: true });
554
+ writePrivateFile(browserToolsConfigFile(effectiveConfigDir), `${JSON.stringify(config, null, 2)}\n`);
555
+ return config;
556
+ }
557
+
558
+ export function writeChromeProfilesConfig(config, options = {}) {
559
+ return writeBrowserToolsConfig(config, options);
560
+ }
561
+
562
+ export function ensureBrowserToolsConfig({ configDir = browserToolsConfigDir(), sourceDir = undefined, refresh = false } = {}) {
563
+ const effectiveConfigDir = resolveBrowserToolsConfigDir(configDir);
564
+ const existing = readBrowserToolsConfig({ configDir: effectiveConfigDir });
565
+ if (!refresh && existing?.version === 1 && existing.profiles && existing.aliases && existing.taskProfiles && existing.directories && existing.browser) return existing;
566
+ const effectiveSourceDir = sourceDir ?? browserToolsChromeSourceDir({ configDir: effectiveConfigDir });
567
+ return writeBrowserToolsConfig(buildBrowserToolsConfig({ sourceDir: effectiveSourceDir, existing }), { configDir: effectiveConfigDir });
568
+ }
569
+
570
+ export function ensureChromeProfilesConfig(options = {}) {
571
+ return ensureBrowserToolsConfig(options);
572
+ }
573
+
574
+ export function activeChromeProfiles(options = {}) {
575
+ const config = ensureBrowserToolsConfig(options);
576
+ return Object.values(config.profiles || {}).filter((profile) => profile.lastActive);
577
+ }
578
+
579
+ export function resolveChromeProfileReference(profileRef, { configDir = browserToolsConfigDir(), sourceDir = undefined, refresh = false } = {}) {
580
+ validateProfileName(profileRef);
581
+ const config = ensureBrowserToolsConfig({ configDir, sourceDir, refresh });
582
+ const profiles = config.profiles || {};
583
+ const aliases = config.aliases || {};
584
+ if (profiles[profileRef]) return validateProfileName(profileRef);
585
+ if (aliases[profileRef]) return validateProfileName(aliases[profileRef]);
586
+
587
+ const wanted = profileRef.toLowerCase();
588
+ const matches = Object.values(profiles).filter((profile) => [
589
+ profile.folder,
590
+ profile.name,
591
+ profile.account,
592
+ profile.gaiaName,
593
+ ].filter(Boolean).some((value) => String(value).toLowerCase() === wanted));
594
+
595
+ const folders = [...new Set(matches.map((profile) => profile.folder))];
596
+ if (folders.length === 1) return validateProfileName(folders[0]);
597
+ if (folders.length > 1) throw new Error(`Ambiguous Chrome profile reference: ${profileRef}. Use the Chrome profile folder name.`);
598
+
599
+ return validateProfileName(profileRef);
600
+ }
601
+
602
+ export function setTaskProfiles(taskName, profileRefs, { configDir = browserToolsConfigDir(), sourceDir = undefined } = {}) {
603
+ if (!taskName || typeof taskName !== 'string') throw new Error('Missing task name');
604
+ const profiles = profileRefs.map((profileRef) => resolveChromeProfileReference(profileRef, { configDir, sourceDir }));
605
+ if (!profiles.length) throw new Error('At least one --profile is required');
606
+ const config = ensureBrowserToolsConfig({ configDir, sourceDir });
607
+ config.taskProfiles = config.taskProfiles || {};
608
+ config.taskProfiles[taskName] = {
609
+ profiles,
610
+ defaultProfile: profiles[0],
611
+ updatedAt: new Date().toISOString(),
612
+ };
613
+ writeBrowserToolsConfig(config, { configDir });
614
+ return config.taskProfiles[taskName];
615
+ }
616
+
617
+ export function taskProfileConfig(taskName, { configDir = browserToolsConfigDir(), sourceDir = undefined } = {}) {
618
+ if (!taskName) return null;
619
+ const config = ensureBrowserToolsConfig({ configDir, sourceDir });
620
+ return config.taskProfiles?.[taskName] || null;
621
+ }
622
+
623
+ export function resolveTaskProfile(taskName, options = {}) {
624
+ const entry = taskProfileConfig(taskName, options);
625
+ return entry?.defaultProfile || entry?.profiles?.[0] || null;
626
+ }
627
+
628
+ export function resolveStartProfileName({
629
+ profileName = null,
630
+ taskName = null,
631
+ defaultProfileName = null,
632
+ configDir = browserToolsConfigDir(),
633
+ sourceDir = undefined,
634
+ refresh = false,
635
+ } = {}) {
636
+ const taskProfileName = !profileName && taskName ? resolveTaskProfile(taskName, { configDir, sourceDir }) : null;
637
+ const requestedProfileName = profileName || taskProfileName || defaultProfileName || null;
638
+ const resolvedProfileName = requestedProfileName ? resolveChromeProfileReference(requestedProfileName, { configDir, sourceDir, refresh }) : null;
639
+ return {
640
+ requestedProfileName,
641
+ resolvedProfileName,
642
+ source: profileName ? 'explicit' : (taskProfileName ? 'task' : (defaultProfileName ? 'default' : 'fresh')),
643
+ };
644
+ }
645
+
646
+ export function profileSyncItems() {
647
+ return PROFILE_SYNC_ITEMS.map((item) => ({ ...item }));
648
+ }
649
+
650
+ export function profileSyncRsyncCommands(profileName, { sourceDir = browserToolsChromeSourceDir(), destDir = profileDataDirForPort(), checkExists = false } = {}) {
651
+ const safeProfileName = validateProfileName(profileName);
652
+ const sourceProfileDir = join(sourceDir, safeProfileName);
653
+ const destProfileDir = join(destDir, safeProfileName);
654
+ const commands = [];
655
+
656
+ if (checkExists) {
657
+ let sourceProfileStat = null;
658
+ try {
659
+ sourceProfileStat = statSync(sourceProfileDir);
660
+ } catch {
661
+ throw new Error(`Chrome profile folder not found: ${sourceProfileDir}`);
662
+ }
663
+ if (!sourceProfileStat.isDirectory()) {
664
+ throw new Error(`Chrome profile folder is not a directory: ${sourceProfileDir}`);
665
+ }
666
+ }
667
+
668
+ const localStateSource = join(sourceDir, 'Local State');
669
+ if (!checkExists || existsSync(localStateSource)) {
670
+ commands.push({ args: ['-a', localStateSource, `${destDir}/`], dest: destDir, item: 'Local State' });
671
+ }
672
+
673
+ for (const item of PROFILE_SYNC_ITEMS) {
674
+ const sourcePath = join(sourceProfileDir, item.path);
675
+ if (checkExists && !existsSync(sourcePath)) continue;
676
+
677
+ const destPath = join(destProfileDir, item.path);
678
+ if (item.type === 'dir') {
679
+ commands.push({ args: ['-a', '--delete', `${sourcePath}/`, `${destPath}/`], dest: destPath, item: item.path });
680
+ } else {
681
+ commands.push({ args: ['-a', sourcePath, `${dirname(destPath)}/`], dest: dirname(destPath), item: item.path });
682
+ }
683
+ }
684
+
685
+ return commands;
686
+ }
687
+
688
+ export function syncChromeProfile(profileName, { force = false, port = DEFAULT_PORT, sourceDir = browserToolsChromeSourceDir(), destDir = profileDataDirForPort(port), includeGoogle = false } = {}) {
689
+ if (!profileName) return { status: 'skipped', profileDir: null };
690
+ validateProfileName(profileName);
691
+ ensureCacheDir();
692
+
693
+ // Reuse a cached copy only when its Google-inclusion matches the request, so switching the flag
694
+ // (or an older copy that predates it) forces a fresh sync instead of leaving the wrong identity in.
695
+ // A copy whose Google strip did not fully succeed is never reused, so the strip is retried (and its
696
+ // warning re-shown) instead of silently serving a clone that still carries the Google session.
697
+ const cachedState = readProfileSyncState(port);
698
+ const cachedMatches = cachedState
699
+ && typeof cachedState.includeGoogle === 'boolean'
700
+ && cachedState.includeGoogle === includeGoogle
701
+ && (includeGoogle || cachedState.googleStripOk === true);
702
+ if (!force && cachedMatches && profileCopyReady(profileName, destDir)) {
703
+ removeChromeProfileLocks(destDir);
704
+ return { status: 'cached', profileDir: destDir, state: cachedState };
705
+ }
706
+
707
+ const commands = profileSyncRsyncCommands(profileName, { sourceDir, destDir, checkExists: true });
708
+
709
+ rmSync(destDir, { recursive: true, force: true });
710
+ mkdirSync(destDir, { recursive: true });
711
+ const results = [];
712
+ const copiedItems = [];
713
+ for (const command of commands) {
714
+ mkdirSync(command.dest, { recursive: true });
715
+ const result = spawnSync('rsync', command.args, { stdio: 'inherit' });
716
+ if (result.error) throw result.error;
717
+ if (result.signal) throw new Error(`rsync failed for ${command.item}: terminated by signal ${result.signal}`);
718
+ if (result.status !== 0) throw new Error(`rsync failed for ${command.item}: exit status ${result.status}`);
719
+ results.push(result);
720
+ copiedItems.push(command.item);
721
+ }
722
+
723
+ removeChromeProfileLocks(destDir);
724
+ // Default: remove the Google session from the clone so a live copy cannot fork the source profile's
725
+ // rotating Google session token and log the source Chrome out. Opt back in with includeGoogle.
726
+ const googleStrip = includeGoogle ? null : stripGoogleIdentityFromProfileCopy(join(destDir, profileName));
727
+ const googleStripOk = includeGoogle ? true : !(googleStrip?.errors?.length);
728
+ // A default start that could not strip Google would launch a clone still carrying the source Google
729
+ // session, which is exactly the logout risk this excludes. Fail loudly instead of launching it.
730
+ if (!includeGoogle && !googleStripOk) {
731
+ rmSync(destDir, { recursive: true, force: true });
732
+ const detail = googleStrip.errors.map((entry) => entry.error).join('; ');
733
+ throw new Error(
734
+ `Could not strip the Google identity from the clone (${detail}). Refusing to launch, because the source Google session would be at risk. Ensure sqlite3 is available, or pass --include-google if you intend to use Google.`,
735
+ );
736
+ }
737
+ const rsyncStatuses = results.map((result) => result.status);
738
+ const state = {
739
+ profileName,
740
+ profileDir: destDir,
741
+ sourceDir,
742
+ syncedAt: new Date().toISOString(),
743
+ rsyncStatus: rsyncStatuses.length ? Math.max(...rsyncStatuses) : 0,
744
+ rsyncStatuses,
745
+ copiedItems,
746
+ includeGoogle,
747
+ googleStrip,
748
+ googleStripOk,
749
+ syncScope: includeGoogle ? 'auth-minimal' : 'auth-minimal-no-google',
750
+ };
751
+ writePrivateFile(profileSyncStateFileForPort(port), JSON.stringify(state, null, 2));
752
+ return { status: 'synced', profileDir: destDir, state };
753
+ }
754
+
755
+ // Registrable domains for Google account services and Google-owned properties whose cookies carry,
756
+ // share, or can re-establish the Google session. Account services (Gmail, Drive, Docs, Photos, Play,
757
+ // Cloud, Gemini, and so on) are all subdomains of google.com, so they are covered by that entry.
758
+ // Add new Google services here to keep the default exclusion comprehensive.
759
+ export const GOOGLE_IDENTITY_DOMAINS = [
760
+ 'google.com', 'google.dev', 'youtube.com', 'youtu.be', 'ytimg.com', 'googlevideo.com',
761
+ 'googleusercontent.com', 'gstatic.com', 'googleapis.com',
762
+ 'gmail.com', 'googlemail.com', 'blogger.com', 'blogspot.com',
763
+ 'doubleclick.net', 'google-analytics.com', 'googletagmanager.com',
764
+ 'googlesyndication.com', 'googleadservices.com',
765
+ 'withgoogle.com', 'google.org', 'android.com', 'goo.gl',
766
+ ];
767
+
768
+ // SQL that removes Google-ecosystem cookies from a copied Cookies database. host_key is stored in
769
+ // plain text, so this needs no decryption. Each domain matches as an exact host or a leading-dot
770
+ // suffix, and the Google country-search patterns require a leading dot, so lookalikes such as
771
+ // notgoogle.com or notgoogle.se can never match.
772
+ export function googleCookieDeleteSql() {
773
+ const clauses = [];
774
+ for (const domain of GOOGLE_IDENTITY_DOMAINS) {
775
+ const escaped = domain.replace(/'/g, "''");
776
+ clauses.push(`host_key='${escaped}'`);
777
+ clauses.push(`host_key LIKE '%.${escaped}'`);
778
+ }
779
+ // Google country search domains (.google.se, .google.co.uk, .google.com.au).
780
+ clauses.push("host_key LIKE '%.google.__'");
781
+ clauses.push("host_key LIKE '%.google.co.__'");
782
+ clauses.push("host_key LIKE '%.google.com.__'");
783
+ // The .google gTLD is owned entirely by Google (for example blog.google, codeassist.google).
784
+ clauses.push("host_key LIKE '%.google'");
785
+ return `DELETE FROM cookies WHERE ${clauses.join(' OR ')};`;
786
+ }
787
+
788
+ // Remove the Google session from a copied profile so a live clone cannot reconcile with Google and
789
+ // fork the source profile's rotating session token (which logs the source Chrome out). Deletes Google
790
+ // cookies from the copied Cookies databases and clears the Google OAuth refresh token from Web Data.
791
+ // Best effort and non-decrypting: it only touches plain-text columns of the copied databases.
792
+ export function stripGoogleIdentityFromProfileCopy(profileDir, { sqlite3Bin = 'sqlite3' } = {}) {
793
+ const result = { cookieDbs: [], webDataCleared: false, errors: [] };
794
+ const runSql = (db, sql) => {
795
+ const r = spawnSync(sqlite3Bin, [db, sql], { encoding: 'utf-8' });
796
+ if (r.error) return r.error.message;
797
+ if (r.status !== 0) return (r.stderr || `sqlite3 exited ${r.status}`).trim();
798
+ return null;
799
+ };
800
+ for (const rel of ['Cookies', join('Network', 'Cookies')]) {
801
+ const db = join(profileDir, rel);
802
+ if (!existsSync(db)) continue;
803
+ const error = runSql(db, googleCookieDeleteSql());
804
+ if (error) result.errors.push({ db, error });
805
+ else result.cookieDbs.push(db);
806
+ }
807
+ const webData = join(profileDir, 'Web Data');
808
+ if (existsSync(webData)) {
809
+ // token_service holds the account OAuth refresh token; dropping it stops the clone re-minting a session.
810
+ const error = runSql(webData, 'DELETE FROM token_service;');
811
+ if (error && !/no such table/i.test(error)) result.errors.push({ db: webData, error });
812
+ else result.webDataCleared = true;
813
+ }
814
+ return result;
815
+ }
816
+
817
+ export function removeChromeProfileLocks(profileDir) {
818
+ if (!existsSync(profileDir)) return;
819
+ const lockNames = new Set(['SingletonLock', 'SingletonSocket', 'SingletonCookie']);
820
+ const stack = [profileDir];
821
+
822
+ while (stack.length) {
823
+ const current = stack.pop();
824
+ let entries;
825
+ try {
826
+ entries = readdirSync(current, { withFileTypes: true });
827
+ } catch {
828
+ continue;
829
+ }
830
+
831
+ for (const entry of entries) {
832
+ const entryPath = join(current, entry.name);
833
+ if (lockNames.has(entry.name)) {
834
+ rmSync(entryPath, { force: true });
835
+ continue;
836
+ }
837
+ if (entry.isDirectory()) stack.push(entryPath);
838
+ }
839
+ }
840
+ }
841
+
842
+ export function chromeLaunchArgs({ port = DEFAULT_PORT, profileName = null, managedToken = null, userDataDir = null, headless = false, userAgent = null } = {}) {
843
+ const normalizedPort = normalizePort(port);
844
+ const launchUserDataDir = userDataDir || (profileName ? profileDataDirForPort(normalizedPort) : freshProfileDirForPort(normalizedPort));
845
+ const args = [
846
+ `--remote-debugging-port=${normalizedPort}`,
847
+ `--user-data-dir=${launchUserDataDir}`,
848
+ '--no-first-run',
849
+ '--no-default-browser-check',
850
+ '--disable-sync',
851
+ ];
852
+ // New headless runs the full browser (extensions and the copied profile still load) without opening
853
+ // a window. Old --headless is a separate lightweight engine that ignores extensions, so keep =new.
854
+ if (headless) args.push('--headless=new');
855
+ // A headless launch otherwise advertises a "HeadlessChrome" User-Agent. When the copied profile is
856
+ // signed in to Google, that headless fingerprint trips Google's session-theft protection and logs the
857
+ // source profile out, while a windowed launch (normal Chrome UA) does not. Present the normal UA so a
858
+ // headless clone matches a windowed one. Applied browser-wide so account reconcile requests use it too.
859
+ if (userAgent) args.push(`--user-agent=${userAgent}`);
860
+ if (managedToken) args.push(`--pi-browser-tools-managed=${managedToken}`);
861
+ if (profileName) args.push(`--profile-directory=${profileName}`);
862
+ return args;
863
+ }
864
+
865
+ export function detectChromeMajorVersion(chromeBin = browserToolsChromeBin()) {
866
+ try {
867
+ const result = spawnSync(chromeBin, ['--version'], { encoding: 'utf-8' });
868
+ if (result.status !== 0 || !result.stdout) return null;
869
+ const match = result.stdout.match(/(\d+)\.\d+\.\d+\.\d+/);
870
+ return match ? Number.parseInt(match[1], 10) : null;
871
+ } catch {
872
+ return null;
873
+ }
874
+ }
875
+
876
+ // Build the normal reduced Chrome User-Agent for a major version. Chrome freezes the platform token,
877
+ // so this matches what a windowed macOS Chrome sends. It carries no machine-specific data.
878
+ export function chromeUserAgentForMajor(major) {
879
+ if (!Number.isInteger(major) || major < 1) return null;
880
+ return `Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/${major}.0.0.0 Safari/537.36`;
881
+ }
882
+
883
+ export function headlessUserAgent(chromeBin = browserToolsChromeBin()) {
884
+ return chromeUserAgentForMajor(detectChromeMajorVersion(chromeBin));
885
+ }
886
+
887
+ export function managedBrowserForUserDataDir(userDataDir) {
888
+ const result = spawnSync('ps', ['-axo', 'pid=,command='], { encoding: 'utf-8' });
889
+ if (result.error || result.status !== 0) return null;
890
+ const chromeBin = browserToolsChromeBin();
891
+
892
+ for (const line of result.stdout.split('\n')) {
893
+ const trimmed = line.trim();
894
+ if (!trimmed) continue;
895
+ const match = trimmed.match(/^(\d+)\s+(.*)$/);
896
+ if (!match) continue;
897
+ const pid = Number.parseInt(match[1], 10);
898
+ const command = match[2];
899
+ if (!command.includes(chromeBin)) continue;
900
+ if (!command.includes(`--user-data-dir=${userDataDir}`)) continue;
901
+ if (!command.includes('--pi-browser-tools-managed=')) continue;
902
+ const portMatch = command.match(/--remote-debugging-port=(\d+)/);
903
+ if (!portMatch) continue;
904
+ return { pid, port: normalizePort(portMatch[1]), command };
905
+ }
906
+
907
+ return null;
908
+ }
909
+
910
+ function chromeBinCandidates(chromeBin) {
911
+ if (String(chromeBin).includes('/')) return [chromeBin];
912
+ const pathDirs = (process.env.PATH || '').split(delimiter).filter(Boolean);
913
+ return pathDirs.length ? pathDirs.map((dir) => join(dir, chromeBin)) : [chromeBin];
914
+ }
915
+
916
+ function assertChromeBinaryLaunchable(chromeBin) {
917
+ const candidates = chromeBinCandidates(chromeBin);
918
+ let exists = false;
919
+ for (const candidate of candidates) {
920
+ try {
921
+ const stat = statSync(candidate);
922
+ exists = true;
923
+ if (!stat.isFile()) continue;
924
+ accessSync(candidate, fsConstants.X_OK);
925
+ return;
926
+ } catch {
927
+ // Try the next PATH candidate or report a single actionable error below.
928
+ }
929
+ }
930
+
931
+ const problem = exists ? 'Chrome binary is not executable' : 'Chrome binary not found';
932
+ throw new Error(`${problem}: ${chromeBin}. Set BROWSER_TOOLS_CHROME_BIN or browser.chromeBin in Browser Tools config.`);
933
+ }
934
+
935
+ export function launchChrome({ port = DEFAULT_PORT, profileName = null, userDataDir = null, ownerToken = null, ownerId = null, headless = false, includeGoogle = false } = {}) {
936
+ ensureCacheDir();
937
+ const normalizedPort = normalizePort(port);
938
+ const launchUserDataDir = userDataDir || (profileName ? profileDataDirForPort(normalizedPort) : freshProfileDirForPort(normalizedPort));
939
+ const managedToken = randomUUID();
940
+ const effectiveOwnerToken = normalizeOwnerValue(ownerToken) || generateOwnerToken();
941
+ const chromeBin = browserToolsChromeBin();
942
+ const userAgent = headless ? headlessUserAgent(chromeBin) : null;
943
+ const args = chromeLaunchArgs({ port: normalizedPort, profileName, managedToken, userDataDir: launchUserDataDir, headless, userAgent });
944
+ assertChromeBinaryLaunchable(chromeBin);
945
+ const pidFile = pidFileForPort(normalizedPort);
946
+ const stateFile = stateFileForPort(normalizedPort);
947
+ const proc = spawn(chromeBin, args, {
948
+ detached: true,
949
+ stdio: 'ignore',
950
+ });
951
+ proc.once('error', (error) => {
952
+ rmSync(pidFile, { force: true });
953
+ rmSync(stateFile, { force: true });
954
+ console.error(`[browser-control] Chrome spawn failed: ${error.message}`);
955
+ });
956
+ if (!Number.isInteger(proc.pid)) {
957
+ throw new Error(`Chrome failed to start: no child process PID for ${chromeBin}`);
958
+ }
959
+ writePrivateFile(pidFile, String(proc.pid));
960
+ writePrivateFile(stateFile, JSON.stringify({
961
+ managedBy: 'browser-tools',
962
+ pid: proc.pid,
963
+ port: normalizedPort,
964
+ profileName: profileName || null,
965
+ userDataDir: launchUserDataDir,
966
+ headless: Boolean(headless),
967
+ includeGoogle: Boolean(includeGoogle),
968
+ managedToken,
969
+ ...buildOwnerState({ ownerToken: effectiveOwnerToken, ownerId }),
970
+ args,
971
+ startedAt: new Date().toISOString(),
972
+ }, null, 2));
973
+ proc.unref();
974
+ return proc;
975
+ }
976
+
977
+ export async function findAvailablePort(startPort = DEFAULT_PORT, { maxAttempts = 100 } = {}) {
978
+ let port = normalizePort(startPort);
979
+ for (let attempt = 0; attempt < maxAttempts; attempt++) {
980
+ if (existsSync(portLockDirForPort(port))) {
981
+ port = normalizePort(port + 1);
982
+ continue;
983
+ }
984
+ cleanupStaleManagedStateForPort(port);
985
+ if (
986
+ !(await browserWSEndpoint(port)) &&
987
+ !existsSync(stateFileForPort(port)) &&
988
+ !existsSync(pidFileForPort(port))
989
+ ) return port;
990
+ port = normalizePort(port + 1);
991
+ }
992
+ throw new Error(`No available Chrome debug port found starting at ${startPort}`);
993
+ }
994
+
995
+ export async function startChrome({
996
+ port = DEFAULT_PORT,
997
+ profileName = null,
998
+ taskName = null,
999
+ defaultProfileName = null,
1000
+ forceProfileSync = false,
1001
+ autoAllocatePort = false,
1002
+ ownerToken = null,
1003
+ ownerId = null,
1004
+ headless = false,
1005
+ includeGoogle = false,
1006
+ } = {}) {
1007
+ let normalizedPort = normalizePort(port);
1008
+ const providedOwnerToken = normalizeOwnerValue(ownerToken);
1009
+ const effectiveOwnerToken = providedOwnerToken || generateOwnerToken();
1010
+ const normalizedOwnerId = normalizeOwnerValue(ownerId);
1011
+ const { requestedProfileName, resolvedProfileName } = resolveStartProfileName({ profileName, taskName, defaultProfileName });
1012
+ ensureCacheDir();
1013
+
1014
+ while (true) {
1015
+ const portLock = acquirePortLock(normalizedPort, { ownerId: normalizedOwnerId });
1016
+ if (!portLock) {
1017
+ if (!autoAllocatePort) throw new Error(`Port :${normalizedPort} is locked by another Browser Tools start operation. Use a different --port or retry.`);
1018
+ normalizedPort = await findAvailablePort(normalizedPort + 1);
1019
+ continue;
1020
+ }
1021
+
1022
+ try {
1023
+ cleanupStaleManagedStateForPort(normalizedPort);
1024
+
1025
+ if (await browserWSEndpoint(normalizedPort)) {
1026
+ const safety = managedBrowserSafetyForPort(normalizedPort);
1027
+ if (!autoAllocatePort) {
1028
+ if (!safety.ok) {
1029
+ throw new Error(
1030
+ `Chrome DevTools is already listening on :${normalizedPort}, but it is not a Browser Tools managed browser (${safety.reason}). Use a different --port or stop that browser manually.`,
1031
+ );
1032
+ }
1033
+ const state = readManagedStateForPort(normalizedPort);
1034
+ const ownership = managedBrowserOwnershipSafety({ state, ownerToken: providedOwnerToken });
1035
+ if (!ownership.ok) {
1036
+ throw new Error(
1037
+ `Chrome DevTools on :${normalizedPort} is owned by another Browser Tools agent (${ownership.reason}). Use a different --port or provide the correct --owner-token.`,
1038
+ );
1039
+ }
1040
+ // Never reuse across a different Google mode: a default (stripped) start must not adopt a
1041
+ // Google-included browser (logout risk), and a Google workflow must not adopt a stripped one.
1042
+ if (Boolean(state?.includeGoogle) !== includeGoogle) {
1043
+ throw new Error(
1044
+ `Chrome on :${normalizedPort} is running with Google ${state?.includeGoogle ? 'included' : 'excluded'}, but this start requested Google ${includeGoogle ? 'included' : 'excluded'}. Stop it with scripts/stop.mjs --clean and start again.`,
1045
+ );
1046
+ }
1047
+ return {
1048
+ status: 'reused',
1049
+ port: normalizedPort,
1050
+ headless: Boolean(state?.headless),
1051
+ includeGoogle: Boolean(state?.includeGoogle),
1052
+ ownerToken: effectiveOwnerToken,
1053
+ ownerId: ownership.ownerId,
1054
+ ownerTokenGenerated: false,
1055
+ };
1056
+ }
1057
+ normalizedPort = await findAvailablePort(normalizedPort + 1);
1058
+ continue;
1059
+ }
1060
+
1061
+ const paths = chromePaths(normalizedPort);
1062
+ if (existsSync(paths.pidFile) || existsSync(paths.stateFile)) {
1063
+ const safety = managedBrowserSafetyForPort(normalizedPort);
1064
+ if (!autoAllocatePort) {
1065
+ throw new Error(
1066
+ `Browser Tools state already exists for :${normalizedPort}, but CDP is not responding (${safety.reason}). Use the owning token with scripts/stop.mjs --port ${normalizedPort} or choose a different --port.`,
1067
+ );
1068
+ }
1069
+ normalizedPort = await findAvailablePort(normalizedPort + 1);
1070
+ continue;
1071
+ }
1072
+
1073
+ const userDataDir = resolvedProfileName ? profileDataDirForPort(normalizedPort) : freshProfileDirForPort(normalizedPort);
1074
+ const existingManagedBrowser = managedBrowserForUserDataDir(userDataDir);
1075
+ if (existingManagedBrowser) {
1076
+ if (existingManagedBrowser.port === normalizedPort) {
1077
+ throw new Error(
1078
+ `Managed Chrome PID ${existingManagedBrowser.pid} owns :${normalizedPort}, but CDP is not responding. Run scripts/stop.mjs --port ${normalizedPort} with the owner token and retry.`,
1079
+ );
1080
+ }
1081
+ throw new Error(
1082
+ `Profile data dir is already in use by managed Chrome PID ${existingManagedBrowser.pid} on :${existingManagedBrowser.port}. Use --port ${existingManagedBrowser.port} with the owner token or stop it first.`,
1083
+ );
1084
+ }
1085
+
1086
+ // Sweep clones left behind by browsers that are no longer running, keeping this port's copy
1087
+ // so an in-progress reuse is never deleted. Best-effort: cleanup must not block a launch.
1088
+ try {
1089
+ pruneChromeClones({ keepPorts: [normalizedPort] });
1090
+ } catch {
1091
+ // Ignore cleanup failures.
1092
+ }
1093
+
1094
+ let profileSync = null;
1095
+ if (resolvedProfileName) {
1096
+ const cachedState = readProfileSyncState(normalizedPort);
1097
+ const googleMatches = cachedState && typeof cachedState.includeGoogle === 'boolean' && cachedState.includeGoogle === includeGoogle;
1098
+ const willSync = forceProfileSync || !profileCopyReady(resolvedProfileName, userDataDir) || !googleMatches;
1099
+ if (willSync) console.error(`⟳ Syncing Chrome profile auth state${includeGoogle ? ' (including Google)' : ' (Google identity excluded)'}...`);
1100
+ profileSync = syncChromeProfile(resolvedProfileName, { force: forceProfileSync, port: normalizedPort, destDir: userDataDir, includeGoogle });
1101
+ if (profileSync.status === 'cached') {
1102
+ console.error(`✓ Using cached profile copy at ${userDataDir} (use --sync to refresh; if a logged-in site appears logged out, stop with --clean and restart with --sync)`);
1103
+ } else if (profileSync.status === 'synced') {
1104
+ console.error(`✓ Profile synced to ${userDataDir}`);
1105
+ if (!includeGoogle) {
1106
+ // A failed strip aborts the sync above, so reaching here means the strip succeeded.
1107
+ console.error('✓ Google identity excluded from the clone (source Google session protected; pass --include-google for Google workflows)');
1108
+ }
1109
+ }
1110
+ }
1111
+ const proc = launchChrome({
1112
+ port: normalizedPort,
1113
+ profileName: resolvedProfileName,
1114
+ userDataDir,
1115
+ ownerToken: effectiveOwnerToken,
1116
+ ownerId: normalizedOwnerId,
1117
+ headless,
1118
+ includeGoogle,
1119
+ });
1120
+ const ready = await waitForChromeReady(normalizedPort, { timeoutMs: CHROME_READY_TIMEOUT_MS });
1121
+ if (!ready) {
1122
+ stopChrome({ port: normalizedPort, ownerToken: effectiveOwnerToken, ignorePortLock: true });
1123
+ throw new Error(`Failed to connect to Chrome after ${Math.round(CHROME_READY_TIMEOUT_MS / 1000)}s`);
1124
+ }
1125
+ return {
1126
+ status: 'started',
1127
+ port: normalizedPort,
1128
+ pid: proc.pid,
1129
+ profileName: resolvedProfileName,
1130
+ requestedProfileName,
1131
+ taskName,
1132
+ profileSync,
1133
+ headless: Boolean(headless),
1134
+ includeGoogle: Boolean(includeGoogle),
1135
+ ownerToken: effectiveOwnerToken,
1136
+ ownerId: normalizedOwnerId,
1137
+ ownerTokenGenerated: !providedOwnerToken,
1138
+ };
1139
+ } finally {
1140
+ portLock.release();
1141
+ }
1142
+ }
1143
+ }
1144
+
1145
+ export function stopChrome({ port = DEFAULT_PORT, clean = false, dryRun = false, ownerToken = null, ignorePortLock = false } = {}) {
1146
+ const normalizedPort = normalizePort(port);
1147
+ const paths = chromePaths(normalizedPort);
1148
+
1149
+ if (!ignorePortLock && existsSync(portLockDirForPort(normalizedPort))) {
1150
+ return { status: 'locked', port: normalizedPort, cleaned: false, reason: 'port-start-lock-present' };
1151
+ }
1152
+
1153
+ const hasPidFile = existsSync(paths.pidFile);
1154
+ const hasStateFile = existsSync(paths.stateFile);
1155
+ if (!hasPidFile && !hasStateFile) {
1156
+ return { status: 'missing', port: normalizedPort, cleaned: false };
1157
+ }
1158
+ if (!hasPidFile || !hasStateFile) {
1159
+ rmSync(paths.pidFile, { force: true });
1160
+ rmSync(paths.stateFile, { force: true });
1161
+ return { status: 'not-managed', port: normalizedPort, cleaned: false, reason: 'incomplete-managed-state' };
1162
+ }
1163
+
1164
+ const pid = Number.parseInt(readFileSync(paths.pidFile, 'utf-8').trim(), 10);
1165
+ const state = readManagedState(paths.stateFile);
1166
+ const safety = verifyManagedChromeProcess({ pid, port: normalizedPort, state });
1167
+ if (!safety.ok && safety.reason === 'process-not-found') {
1168
+ rmSync(paths.pidFile, { force: true });
1169
+ rmSync(paths.stateFile, { force: true });
1170
+ let cleaned = false;
1171
+ if (clean && isBrowserToolsUserDataDir(state?.userDataDir)) {
1172
+ rmSync(state.userDataDir, { recursive: true, force: true });
1173
+ rmSync(profileSyncStateFileForPort(normalizedPort), { force: true });
1174
+ cleaned = true;
1175
+ }
1176
+ return { status: 'already-gone', port: normalizedPort, pid, cleaned };
1177
+ }
1178
+
1179
+ const ownership = managedBrowserOwnershipSafety({ state, ownerToken });
1180
+ if (!ownership.ok) {
1181
+ return {
1182
+ status: 'not-owned',
1183
+ port: normalizedPort,
1184
+ pid,
1185
+ cleaned: false,
1186
+ reason: ownership.reason,
1187
+ ownerId: ownership.ownerId,
1188
+ command: safety.command,
1189
+ };
1190
+ }
1191
+
1192
+ if (!safety.ok) {
1193
+ rmSync(paths.pidFile, { force: true });
1194
+ rmSync(paths.stateFile, { force: true });
1195
+ return {
1196
+ status: 'not-managed',
1197
+ port: normalizedPort,
1198
+ pid,
1199
+ cleaned: false,
1200
+ reason: safety.reason,
1201
+ command: safety.command,
1202
+ };
1203
+ }
1204
+
1205
+ if (dryRun) {
1206
+ return { status: 'would-stop', port: normalizedPort, pid, cleaned: false, command: safety.command, ownerId: ownership.ownerId };
1207
+ }
1208
+
1209
+ let status = 'stopped';
1210
+ let error = null;
1211
+
1212
+ try {
1213
+ process.kill(pid, 'SIGTERM');
1214
+ if (!waitForProcessExit(pid, 2000)) {
1215
+ const killSafety = verifyManagedChromeProcess({ pid, port: normalizedPort, state });
1216
+ if (killSafety.ok) {
1217
+ process.kill(pid, 'SIGKILL');
1218
+ waitForProcessExit(pid, 1000);
1219
+ status = 'killed';
1220
+ } else {
1221
+ status = 'failed';
1222
+ error = new Error(`Refusing SIGKILL after failed safety recheck: ${killSafety.reason}`);
1223
+ }
1224
+ }
1225
+ } catch (e) {
1226
+ if (e.code === 'ESRCH') status = 'already-gone';
1227
+ else {
1228
+ status = 'failed';
1229
+ error = e;
1230
+ }
1231
+ }
1232
+
1233
+ rmSync(paths.pidFile, { force: true });
1234
+ rmSync(paths.stateFile, { force: true });
1235
+ let cleaned = false;
1236
+ if (clean && isBrowserToolsUserDataDir(state?.userDataDir)) {
1237
+ rmSync(state.userDataDir, { recursive: true, force: true });
1238
+ rmSync(profileSyncStateFileForPort(normalizedPort), { force: true });
1239
+ cleaned = true;
1240
+ }
1241
+
1242
+ return { status, port: normalizedPort, pid, cleaned, error };
1243
+ }
1244
+
1245
+ // Sweep cached profile clones that are not currently in use by a running managed Chrome.
1246
+ // Removes the clone data dir plus its per-port sync-state and lifecycle files. A clone whose
1247
+ // user-data-dir is still owned by a live managed Chrome is kept. Never touches non-clone cache
1248
+ // entries (for example ai-chat data), because every path comes from the per-port helpers.
1249
+ export function pruneChromeClones({ dryRun = false, keepPorts = [] } = {}) {
1250
+ const cacheDir = browserToolsCacheDir();
1251
+ const keep = new Set(keepPorts.map((value) => Number.parseInt(value, 10)));
1252
+ const removed = [];
1253
+ const kept = [];
1254
+ let entries;
1255
+ try {
1256
+ entries = readdirSync(cacheDir, { withFileTypes: true });
1257
+ } catch {
1258
+ return { removed, kept, dryRun, cacheDir };
1259
+ }
1260
+
1261
+ const ports = new Set();
1262
+ for (const entry of entries) {
1263
+ let match = entry.name.match(/^chrome-(?:data|fresh)-(\d+)$/);
1264
+ if (match && entry.isDirectory()) { ports.add(Number.parseInt(match[1], 10)); continue; }
1265
+ match = entry.name.match(/^chrome-profile-sync-(\d+)\.json$/);
1266
+ if (match && entry.isFile()) { ports.add(Number.parseInt(match[1], 10)); continue; }
1267
+ match = entry.name.match(/^chrome-(\d+)\.(?:pid|json)$/);
1268
+ if (match && entry.isFile()) ports.add(Number.parseInt(match[1], 10));
1269
+ }
1270
+
1271
+ for (const port of [...ports].sort((a, b) => a - b)) {
1272
+ if (keep.has(port)) {
1273
+ kept.push({ port, reason: 'kept-port' });
1274
+ continue;
1275
+ }
1276
+ // A concurrent start holds a port lock between profile sync and process spawn, so it has no
1277
+ // running process yet. Skip locked ports so we never delete another start's just-synced clone.
1278
+ if (existsSync(portLockDirForPort(port))) {
1279
+ kept.push({ port, reason: 'start-locked' });
1280
+ continue;
1281
+ }
1282
+ const dataDir = profileDataDirForPort(port);
1283
+ const freshDir = freshProfileDirForPort(port);
1284
+ // Both a stale profiled clone and a live fresh clone can share a port, so check each candidate
1285
+ // dir for a live owner. Removing either dir while one is in use would corrupt a running browser.
1286
+ const runningData = existsSync(dataDir) ? managedBrowserForUserDataDir(dataDir) : null;
1287
+ const runningFresh = existsSync(freshDir) ? managedBrowserForUserDataDir(freshDir) : null;
1288
+ const running = runningData || runningFresh;
1289
+ if (running) {
1290
+ kept.push({ port, reason: 'running', pid: running.pid, dir: runningData ? dataDir : freshDir });
1291
+ continue;
1292
+ }
1293
+ const targets = [dataDir, freshDir, pidFileForPort(port), stateFileForPort(port), profileSyncStateFileForPort(port)]
1294
+ .filter((path) => existsSync(path));
1295
+ if (!targets.length) continue;
1296
+ if (!dryRun) for (const path of targets) rmSync(path, { recursive: true, force: true });
1297
+ removed.push({ port, paths: targets });
1298
+ }
1299
+
1300
+ return { removed, kept, dryRun, cacheDir };
1301
+ }
1302
+
1303
+ function readManagedState(stateFile) {
1304
+ // Generated lifecycle state, not user config. A crash-truncated file must read as null so stop and
1305
+ // stale-state cleanup can remove it and recover the port, rather than aborting on a parse error.
1306
+ try {
1307
+ return safeReadJson(stateFile);
1308
+ } catch {
1309
+ return null;
1310
+ }
1311
+ }
1312
+
1313
+ function commandForPid(pid) {
1314
+ const result = spawnSync('ps', ['-p', String(pid), '-o', 'command='], { encoding: 'utf-8' });
1315
+ if (result.error || result.status !== 0) return null;
1316
+ const command = result.stdout.trim();
1317
+ return command || null;
1318
+ }
1319
+
1320
+ function processExists(pid) {
1321
+ try {
1322
+ process.kill(pid, 0);
1323
+ return true;
1324
+ } catch (e) {
1325
+ return e.code !== 'ESRCH';
1326
+ }
1327
+ }
1328
+
1329
+ function sleepSync(ms) {
1330
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
1331
+ }
1332
+
1333
+ function waitForProcessExit(pid, timeoutMs) {
1334
+ const deadline = Date.now() + timeoutMs;
1335
+ while (Date.now() < deadline) {
1336
+ if (!processExists(pid)) return true;
1337
+ sleepSync(100);
1338
+ }
1339
+ return !processExists(pid);
1340
+ }
1341
+
1342
+ function verifyManagedChromeProcess({ pid, port, state }) {
1343
+ const command = commandForPid(pid);
1344
+ if (!command) return { ok: false, reason: 'process-not-found' };
1345
+ return managedChromeCommandSafety({ pid, port, state, command });
1346
+ }
1347
+
1348
+ export function isBrowserToolsUserDataDir(userDataDir) {
1349
+ if (!userDataDir || typeof userDataDir !== 'string') return false;
1350
+ const cacheDir = browserToolsCacheDir();
1351
+ return userDataDir === PROFILE_DST ||
1352
+ userDataDir === FRESH_PROFILE_DIR ||
1353
+ userDataDir === profileDataDirForPort(DEFAULT_PORT) ||
1354
+ userDataDir === freshProfileDirForPort(DEFAULT_PORT) ||
1355
+ userDataDir.startsWith(`${cacheDir}/chrome-data-`) ||
1356
+ userDataDir.startsWith(`${cacheDir}/chrome-fresh-`);
1357
+ }
1358
+
1359
+ export function managedChromeCommandSafety({ pid, port, state, command }) {
1360
+ if (!state || state.managedBy !== 'browser-tools') {
1361
+ return { ok: false, reason: 'missing-managed-state', command };
1362
+ }
1363
+ if (Number(state.pid) !== Number(pid) || Number(state.port) !== Number(port)) {
1364
+ return { ok: false, reason: 'state-mismatch', command };
1365
+ }
1366
+ if (!state.managedToken) {
1367
+ return { ok: false, reason: 'missing-managed-token', command };
1368
+ }
1369
+ if (!isBrowserToolsUserDataDir(state.userDataDir)) {
1370
+ return { ok: false, reason: 'state-user-data-dir-mismatch', command };
1371
+ }
1372
+
1373
+ const expectedDebugPort = `--remote-debugging-port=${port}`;
1374
+ const expectedToken = `--pi-browser-tools-managed=${state.managedToken}`;
1375
+ const expectedUserDataDir = `--user-data-dir=${state.userDataDir}`;
1376
+ const expectedArgs = Array.isArray(state.args) ? state.args : [];
1377
+ const isChrome = command.includes('Google Chrome') || command.includes(browserToolsChromeBin()) || command.includes(CHROME_BIN);
1378
+
1379
+ if (!isChrome) return { ok: false, reason: 'not-chrome-process', command };
1380
+ if (!command.includes(expectedDebugPort)) return { ok: false, reason: 'debug-port-mismatch', command };
1381
+ if (!command.includes(expectedUserDataDir)) return { ok: false, reason: 'user-data-dir-mismatch', command };
1382
+ if (!command.includes(expectedToken)) return { ok: false, reason: 'managed-token-mismatch', command };
1383
+ if (!expectedArgs.includes(expectedDebugPort)) return { ok: false, reason: 'state-debug-port-missing', command };
1384
+ if (!expectedArgs.includes(expectedUserDataDir)) return { ok: false, reason: 'state-user-data-dir-missing', command };
1385
+ if (!expectedArgs.includes(expectedToken)) return { ok: false, reason: 'state-managed-token-missing', command };
1386
+
1387
+ return { ok: true, command };
1388
+ }
1389
+
1390
+ export async function connectBrowser(port = DEFAULT_PORT, options = {}) {
1391
+ const normalizedPort = normalizePort(port);
1392
+ const { ownerToken = parseOwnerToken(process.argv.slice(2)), ...puppeteerOptions } = options;
1393
+ const safety = managedBrowserSafetyForPort(normalizedPort);
1394
+ if (!safety.ok) {
1395
+ throw new Error(`Refusing to connect to unmanaged Chrome on :${normalizedPort}: ${safety.reason}`);
1396
+ }
1397
+ const state = readManagedStateForPort(normalizedPort);
1398
+ const ownership = managedBrowserOwnershipSafety({ state, ownerToken });
1399
+ if (!ownership.ok) {
1400
+ throw new Error(`Refusing to connect to Browser Tools Chrome on :${normalizedPort}: ${ownership.reason}`);
1401
+ }
1402
+ return puppeteer.connect({
1403
+ browserURL: `http://localhost:${normalizedPort}`,
1404
+ defaultViewport: null,
1405
+ ...puppeteerOptions,
1406
+ });
1407
+ }
1408
+
1409
+ export async function withBrowser(port, callback, options = {}) {
1410
+ const browser = await connectBrowser(port, options);
1411
+ try {
1412
+ return await callback(browser);
1413
+ } finally {
1414
+ browser.disconnect();
1415
+ }
1416
+ }
1417
+
1418
+ export async function activePage(browser) {
1419
+ const pages = await browser.pages();
1420
+ const page = pages.at(-1);
1421
+ if (!page) throw new Error('No active tab found');
1422
+ return page;
1423
+ }
1424
+
1425
+ export async function dedicatedPage(browser, urlMatcher, createUrl = null) {
1426
+ const pages = await browser.pages();
1427
+ let page = pages.find((candidate) => urlMatcher(candidate.url()));
1428
+ if (!page) {
1429
+ page = await browser.newPage({ background: true });
1430
+ if (createUrl) await page.goto(createUrl, { waitUntil: 'domcontentloaded', timeout: 15000 }).catch(() => {});
1431
+ }
1432
+ return page;
1433
+ }
1434
+
1435
+ export function timestampedTmpPath(prefix, extension) {
1436
+ const safePrefix = prefix.replace(/[^a-zA-Z0-9._-]/g, '-');
1437
+ const safeExtension = extension.replace(/^\./, '');
1438
+ const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
1439
+ const artifactDir = browserToolsArtifactDir();
1440
+ mkdirSync(artifactDir, { recursive: true });
1441
+ return join(artifactDir, `${safePrefix}-${timestamp}.${safeExtension}`);
1442
+ }
1443
+
1444
+ export function fileExists(path) {
1445
+ try {
1446
+ return existsSync(path) && statSync(path).isFile();
1447
+ } catch {
1448
+ return false;
1449
+ }
1450
+ }