@rezkam/browser-tools 1.0.4 → 1.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,18 @@
1
1
  # @rezkam/browser-tools
2
2
 
3
+ ## 1.1.1
4
+
5
+ ### Patch Changes
6
+
7
+ - 0ba174d: Fixed tab allocation, retry and shutdown races with locally owned lifecycle states. Capture failures now release their listeners without waiting for stalled body reads, GIF finalization runs once, and terminal lease messages cannot grant an empty tab. Failed disposal can retry or recover capacity after verified browser exit without overwriting a replacement browser.
8
+
9
+ ## 1.1.0
10
+
11
+ ### Minor Changes
12
+
13
+ - 0fcffe1: Support native Linux Chrome/Chromium discovery, profile locations, headless diagnostics and platform-correct user agents while retaining Puppeteer and owner-protected lifecycle contracts. Verify fixed-port endpoints against launch arguments, read Linux process identity through procfs, and add Linux/macOS browser smoke CI.
14
+ - e7a80e3: Add `browser-tools serve`, a tab broker that runs one lean Chrome for every client on a machine and hands out at most `--max-tabs` tabs at a time (default 4), each in its own browser context and taken back after `--tab-seconds` (default 120). A lease is an open HTTP request, so a client that exits gives its tab back. With `--proxy-server`, every request goes through the proxy, loopback and WebRTC included. The broker logs Chrome's memory by process type and every lease as JSON lines. `leaseTab` and `serveTabs` are exported from `@rezkam/browser-tools/tab-broker.mjs`, and `connectLeasedTab` connects to a leased tab.
15
+
3
16
  ## 1.0.4
4
17
 
5
18
  ### Patch Changes
package/README.md CHANGED
@@ -34,12 +34,24 @@ Commands can also run without a global install:
34
34
  npx @rezkam/browser-tools <command>
35
35
  ```
36
36
 
37
- Browser Tools requires macOS, Google Chrome, and Node.js 20 or newer. GIF recording and review additionally require `ffmpeg` and `ffprobe`:
37
+ Browser Tools requires macOS or Linux, installed Google Chrome or Chromium, and Node.js 20 or newer. GIF recording and review additionally require `ffmpeg` and `ffprobe`:
38
38
 
39
39
  ```bash
40
40
  brew install ffmpeg
41
41
  ```
42
42
 
43
+ ## Linux
44
+
45
+ Linux discovers executable Chrome/Chromium launchers on PATH and common distro locations, including the normal snap launcher. Explicit `BROWSER_TOOLS_CHROME_BIN` or `browser.chromeBin` config wins; no browser or OS packages are installed automatically. Use `browser-tools start --headless` without a display; headed mode needs a working X11 or Wayland session. Chromium sandboxing stays enabled. Root, containers, or restrictive AppArmor/user-namespace policies may need operator setup, never an automatic `--no-sandbox` fallback.
46
+
47
+ Profile discovery follows the selected browser family/channel under `${XDG_CONFIG_HOME:-~/.config}` (`google-chrome`, `google-chrome-beta`, `google-chrome-unstable`, or `chromium`); snap Chromium uses `~/snap/chromium/common/chromium`. Override with `BROWSER_TOOLS_CHROME_SOURCE_DIR` or `directories.chromeSourceDir`. `browser-tools config profiles` enumerates Local State into private local config.
48
+
49
+ Profile copying requires `rsync` and `sqlite3` (for default Google identity exclusion). Close the source browser before copying for a consistent snapshot; copying a live SQLite database is not an atomic backup. Copies stay private and source locks are never removed. Run as the same OS user, browser family, and unlocked desktop secret-store session: copied cookies may not decrypt without the original Libsecret/KWallet keyring or D-Bus session. Browser Tools never switches to basic password storage or promises portable logins. Extensions depend on Chromium build/policy and are not guaranteed merely because their files were copied.
50
+
51
+ Snap confinement may deny the default cache or artifact paths. Set `BROWSER_TOOLS_CACHE_DIR` and `BROWSER_TOOLS_ARTIFACT_DIR` to private locations permitted by the installed snap; do not bypass confinement by automatically invoking internal snap executables. Snap launcher discovery is supported, but distro-specific confinement/refresh/keyring behavior requires host validation. Flatpak, Windows, encrypted login migration across users/hosts, and extension execution are not covered by the native compatibility guarantee.
52
+
53
+ Local verification covers sandboxed Linux ARM64 Chromium navigation, eval, screenshots, ownership rejection, fixed-port endpoint identity and cleanup. CI runs unit/contracts and fresh-browser smoke on Linux and macOS (direct executable on hosted macOS); native NSWorkspace routing has a fixture contract, not a real desktop Dock/keychain validation. Real keyrings, headed Linux, snap confinement, and extensions require separate environment-specific verification. Puppeteer API and CLI contracts are retained; no Patchright migration is included.
54
+
43
55
  ## Quick start
44
56
 
45
57
  ```bash
@@ -67,6 +79,7 @@ Use `--profile "<profile or alias>"` when an existing login is needed, `--sync`
67
79
  | Visual recording | `record-gif`, `review-gif` | Record an interaction with pre-roll and post-roll frames, then create a contact sheet and metadata report |
68
80
  | HTTP capture | `record-har`, `extract-har` | Capture filtered active-tab traffic and derive a compact, non-executable request recipe |
69
81
  | Chrome DevTools Protocol | `record-cdp`, `cdp` | Record selected raw protocol events or send one guarded direct method call |
82
+ | Shared tabs | `serve` | Run one lean Chrome for every client on the machine and lease its tabs, a bounded number at a time, each for a bounded time |
70
83
 
71
84
  Run `browser-tools --help` for the command list. Commands with detailed option references, such as `record-har`, `record-cdp`, and `review-gif`, also support command-level `--help`.
72
85
 
@@ -93,6 +106,31 @@ import { runBrowserResource } from '@rezkam/browser-tools/resource-helper.mjs';
93
106
 
94
107
  The root package export and `@rezkam/browser-tools/browser-control.mjs` both expose the browser lifecycle and connection module. The resource helper export provides the shared lifecycle for generic extractors.
95
108
 
109
+ ### Shared tabs
110
+
111
+ `browser-tools serve` starts a tab broker and prints `{"url": ...}` once it listens. Chrome starts with the first lease, without extensions, component apps, a startup window or background networking.
112
+
113
+ ```js
114
+ import { connectLeasedTab } from '@rezkam/browser-tools';
115
+ import { leaseTab } from '@rezkam/browser-tools/tab-broker.mjs';
116
+
117
+ const lease = await leaseTab(brokerUrl, { client: 'quotes' });
118
+ const { browser, page } = await connectLeasedTab(lease);
119
+ try {
120
+ await page.goto('https://example.com/');
121
+ } finally {
122
+ await browser.disconnect();
123
+ lease.release();
124
+ }
125
+ ```
126
+
127
+ - At most `--max-tabs` tabs (default 4) are leased at once; later leases wait in order.
128
+ - Each tab has a browser context of its own, so tabs share no cookies or storage, and downloads are refused.
129
+ - A tab is taken back after `--tab-seconds` (default 120), and `lease.ended` then settles with `'expired'`. A client that exits gives its tab back, because a lease is an open HTTP request.
130
+ - With `--proxy-server`, every request goes through the proxy, loopback addresses and WebRTC included.
131
+ - `--until-stdin-closes` stops the broker, and its Chrome, when the parent holding its stdin goes away.
132
+ - On Linux the broker logs Chrome's memory every 15 seconds as a `browser_memory` JSON line on stderr (proportional set size by process type), and each finished lease as a `tab_lease` line with its wait, hold time and how it ended.
133
+
96
134
  ## Development
97
135
 
98
136
  ```bash
@@ -23,6 +23,7 @@
23
23
  * browser-tools scrape-page [--port <n>]
24
24
  * browser-tools extract-article [--chars <n>] [--port <n>]
25
25
  * browser-tools config profiles|active-profiles|task-profile ...
26
+ * browser-tools serve [--max-tabs <n>] [--tab-seconds <n>] [--headless] [--proxy-server <url>] [--until-stdin-closes]
26
27
  */
27
28
 
28
29
  import { spawnSync } from 'node:child_process';
@@ -49,6 +50,7 @@ const COMMANDS = {
49
50
  'scrape-page': 'scrape-page.mjs',
50
51
  'extract-article': 'extract-article.mjs',
51
52
  config: 'config.mjs',
53
+ serve: 'serve.mjs',
52
54
  };
53
55
 
54
56
  function printUsage() {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rezkam/browser-tools",
3
- "version": "1.0.4",
3
+ "version": "1.1.1",
4
4
  "description": "Sandboxed, owner-token-protected Chrome automation for AI agents: control pages, record and review GIFs, capture HAR and raw CDP events, send CDP calls, and manage Chrome profiles.",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",
@@ -22,6 +22,7 @@
22
22
  ".": "./scripts/browser-control.mjs",
23
23
  "./browser-control.mjs": "./scripts/browser-control.mjs",
24
24
  "./resource-helper.mjs": "./scripts/resource-helper.mjs",
25
+ "./tab-broker.mjs": "./scripts/tab-broker.mjs",
25
26
  "./package.json": "./package.json"
26
27
  },
27
28
  "files": [
@@ -41,7 +42,8 @@
41
42
  "validate": "npm test && npm run test:e2e"
42
43
  },
43
44
  "dependencies": {
44
- "puppeteer-core": "^24.42.0"
45
+ "puppeteer-core": "^24.42.0",
46
+ "ws": "^8.22.0"
45
47
  },
46
48
  "devDependencies": {
47
49
  "@changesets/cli": "^2.31.0"
@@ -17,14 +17,16 @@ import { homedir, tmpdir } from 'node:os';
17
17
  import { delimiter, dirname, join, resolve } from 'node:path';
18
18
  import { fileURLToPath } from 'node:url';
19
19
  import puppeteer from 'puppeteer-core';
20
+ import WebSocket from 'ws';
21
+ import { discoverChromeBinary, discoverChromeSourceDir, chromePlatformToken } from './browser-platform.mjs';
20
22
 
21
23
  export const DEFAULT_PORT = 9222;
22
24
  export const CONNECT_PROBE_TIMEOUT_MS = 3000;
23
25
  export const PORT_OCCUPANCY_PROBE_TIMEOUT_MS = 250;
24
26
  export const CHROME_READY_TIMEOUT_MS = 15000;
25
27
  export const CHROME_READY_PROBE_TIMEOUT_MS = 250;
26
- export const DEFAULT_CHROME_BIN = '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome';
27
- export const DEFAULT_CHROME_SRC = join(homedir(), 'Library', 'Application Support', 'Google', 'Chrome');
28
+ export const DEFAULT_CHROME_BIN = discoverChromeBinary() || (process.platform === 'linux' ? 'google-chrome' : '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome');
29
+ export const DEFAULT_CHROME_SRC = discoverChromeSourceDir({ chromeBin: DEFAULT_CHROME_BIN }) || join(homedir(), '.config', 'google-chrome');
28
30
  export const DEFAULT_CACHE_DIR = join(homedir(), '.cache', 'pi-browser-tools');
29
31
  export const DEFAULT_ARTIFACT_DIR = tmpdir();
30
32
 
@@ -84,11 +86,12 @@ export function expandHomePath(value) {
84
86
  export function browserToolsRuntimeConfig({ configDir = browserToolsConfigDir() } = {}) {
85
87
  const effectiveConfigDir = resolveBrowserToolsConfigDir(configDir);
86
88
  const config = safeReadJson(browserToolsConfigFile(effectiveConfigDir)) || {};
89
+ const chromeBin = expandHomePath(process.env.BROWSER_TOOLS_CHROME_BIN || config.browser?.chromeBin || config.chromeBin || discoverChromeBinary() || DEFAULT_CHROME_BIN);
87
90
  return {
88
91
  configDir: effectiveConfigDir,
89
92
  configFile: browserToolsConfigFile(effectiveConfigDir),
90
- chromeBin: expandHomePath(process.env.BROWSER_TOOLS_CHROME_BIN || config.browser?.chromeBin || config.chromeBin || DEFAULT_CHROME_BIN),
91
- chromeSourceDir: expandHomePath(process.env.BROWSER_TOOLS_CHROME_SOURCE_DIR || config.directories?.chromeSourceDir || config.sourceDir || DEFAULT_CHROME_SRC),
93
+ chromeBin,
94
+ chromeSourceDir: expandHomePath(process.env.BROWSER_TOOLS_CHROME_SOURCE_DIR || config.directories?.chromeSourceDir || config.sourceDir || discoverChromeSourceDir({ chromeBin }) || DEFAULT_CHROME_SRC),
92
95
  cacheDir: expandHomePath(process.env.BROWSER_TOOLS_CACHE_DIR || config.directories?.cacheDir || DEFAULT_CACHE_DIR),
93
96
  artifactDir: expandHomePath(process.env.BROWSER_TOOLS_ARTIFACT_DIR || config.directories?.artifactDir || DEFAULT_ARTIFACT_DIR),
94
97
  maxBrowsers: config.browser?.maxBrowsers ?? config.maxBrowsers ?? null,
@@ -379,7 +382,7 @@ export async function browserWSEndpoint(port = DEFAULT_PORT, timeoutMs = CONNECT
379
382
  const controller = new AbortController();
380
383
  const timer = setTimeout(() => controller.abort(), timeoutMs);
381
384
  try {
382
- const res = await fetch(`http://localhost:${normalizedPort}/json/version`, { signal: controller.signal });
385
+ const res = await fetch(`http://127.0.0.1:${normalizedPort}/json/version`, { signal: controller.signal });
383
386
  if (!res.ok) return null;
384
387
  const data = await res.json();
385
388
  return data.webSocketDebuggerUrl ?? null;
@@ -400,10 +403,10 @@ export async function browserWSEndpoint(port = DEFAULT_PORT, timeoutMs = CONNECT
400
403
  function tcpListenerOnHost(port, host, timeoutMs) {
401
404
  return new Promise((resolvePromise) => {
402
405
  const socket = createConnection({ host, port });
403
- let settled = false;
406
+ let state = { phase: 'connecting' };
404
407
  const finish = (occupied) => {
405
- if (settled) return;
406
- settled = true;
408
+ if (state.phase === 'settled') return;
409
+ state = { phase: 'settled', occupied };
407
410
  socket.destroy();
408
411
  resolvePromise(occupied);
409
412
  };
@@ -437,6 +440,52 @@ export function devToolsActivePortMatches(userDataDir, endpoint) {
437
440
  }
438
441
  }
439
442
 
443
+ // Fixed-port Chromium need not write DevToolsActivePort. A loopback URL alone is
444
+ // not ownership proof: ask the endpoint for its actual browser launch arguments.
445
+ export async function launchedEndpointMatches({ port, endpoint, state, timeoutMs = 3000 }) {
446
+ let url;
447
+ try { url = new URL(endpoint); } catch { return false; }
448
+ if (url.hash || url.username || url.password || url.protocol !== 'ws:' || !['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname)
449
+ || Number(url.port) !== Number(port) || !url.pathname.startsWith('/devtools/browser/')) return false;
450
+ if (devToolsActivePortMatches(state?.userDataDir, endpoint)) return true;
451
+ if (!state?.managedToken || !state?.userDataDir) return false;
452
+ return new Promise((resolve) => {
453
+ let socket;
454
+ try { socket = new WebSocket(endpoint, { followRedirects: false, handshakeTimeout: timeoutMs, maxPayload: 1024 * 1024 }); }
455
+ catch { resolve(false); return; }
456
+ let probeState = { phase: 'connecting' };
457
+ const finish = (ok) => {
458
+ if (probeState.phase === 'settled') return;
459
+ probeState = { phase: 'settled', ok };
460
+ clearTimeout(timer);
461
+ socket.terminate();
462
+ resolve(ok);
463
+ };
464
+ const timer = setTimeout(() => finish(false), timeoutMs);
465
+ socket.on('error', () => finish(false));
466
+ socket.on('close', () => finish(false));
467
+ socket.on('open', () => {
468
+ if (probeState.phase !== 'connecting') return;
469
+ probeState = { phase: 'checking' };
470
+ socket.send(JSON.stringify({ id: 1, method: 'Browser.getBrowserCommandLine' }));
471
+ });
472
+ socket.on('message', (data) => {
473
+ if (probeState.phase !== 'checking') return;
474
+ try {
475
+ const message = JSON.parse(data.toString());
476
+ if (message.id !== 1) return;
477
+ const args = message.result?.arguments;
478
+ finish(Array.isArray(args) && [
479
+ '--enable-automation',
480
+ '--remote-debugging-port=' + port,
481
+ '--user-data-dir=' + state.userDataDir,
482
+ '--pi-browser-tools-managed=' + state.managedToken,
483
+ ].every(arg => args.includes(arg)));
484
+ } catch { finish(false); }
485
+ });
486
+ });
487
+ }
488
+
440
489
  export async function waitForChromeEndpoint(
441
490
  port = DEFAULT_PORT,
442
491
  { timeoutMs = CHROME_READY_TIMEOUT_MS, intervalMs = 250, probeTimeoutMs = CHROME_READY_PROBE_TIMEOUT_MS } = {},
@@ -821,6 +870,7 @@ export function syncChromeProfile(profileName, { force = false, port = DEFAULT_P
821
870
  const cachedMatches = cachedState
822
871
  && typeof cachedState.includeGoogle === 'boolean'
823
872
  && cachedState.includeGoogle === includeGoogle
873
+ && cachedState.sourceDir && resolve(cachedState.sourceDir) === resolve(sourceDir)
824
874
  && (includeGoogle || cachedState.googleStripOk === true);
825
875
  if (!force && cachedMatches && profileCopyReady(profileName, destDir)) {
826
876
  removeChromeProfileLocks(destDir);
@@ -830,11 +880,12 @@ export function syncChromeProfile(profileName, { force = false, port = DEFAULT_P
830
880
  const commands = profileSyncRsyncCommands(profileName, { sourceDir, destDir, checkExists: true });
831
881
 
832
882
  rmSync(destDir, { recursive: true, force: true });
833
- mkdirSync(destDir, { recursive: true });
883
+ mkdirSync(destDir, { recursive: true, mode: 0o700 });
884
+ chmodSync(destDir, 0o700);
834
885
  const results = [];
835
886
  const copiedItems = [];
836
887
  for (const command of commands) {
837
- mkdirSync(command.dest, { recursive: true });
888
+ mkdirSync(command.dest, { recursive: true, mode: 0o700 });
838
889
  const result = spawnSync('rsync', command.args, { stdio: 'inherit' });
839
890
  if (result.error) throw result.error;
840
891
  if (result.signal) throw new Error(`rsync failed for ${command.item}: terminated by signal ${result.signal}`);
@@ -968,6 +1019,8 @@ export function chromeLaunchArgs({ port = DEFAULT_PORT, profileName = null, mana
968
1019
  const args = [
969
1020
  `--remote-debugging-port=${normalizedPort}`,
970
1021
  `--user-data-dir=${launchUserDataDir}`,
1022
+ '--remote-debugging-address=127.0.0.1',
1023
+ '--enable-automation',
971
1024
  '--no-first-run',
972
1025
  '--no-default-browser-check',
973
1026
  '--disable-sync',
@@ -1000,7 +1053,7 @@ export function detectChromeMajorVersion(chromeBin = browserToolsChromeBin()) {
1000
1053
  // so this matches what a windowed macOS Chrome sends. It carries no machine-specific data.
1001
1054
  export function chromeUserAgentForMajor(major) {
1002
1055
  if (!Number.isInteger(major) || major < 1) return null;
1003
- 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`;
1056
+ return `Mozilla/5.0 (${chromePlatformToken()}) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/${major}.0.0.0 Safari/537.36`;
1004
1057
  }
1005
1058
 
1006
1059
  export function headlessUserAgent(chromeBin = browserToolsChromeBin()) {
@@ -1134,7 +1187,7 @@ export function managedBrowserIdentityMatches(expected, current) {
1134
1187
  export function verifyManagedChromePid(pid, { cacheDir = browserToolsCacheDir(), chromeBin = browserToolsChromeBin() } = {}) {
1135
1188
  const command = commandForPid(pid);
1136
1189
  if (!command) return null;
1137
- return managedChromeProcessFromCommand({ pid, command, cacheDir, chromeBin });
1190
+ return managedChromeProcessFromCommand({ pid, command: command.replaceAll('\0', ' ').trim(), cacheDir, chromeBin });
1138
1191
  }
1139
1192
 
1140
1193
  // The live inventory of managed browsers. This reads the process table rather than the lifecycle
@@ -1477,6 +1530,7 @@ export function managedBrowserReuseDecision({
1477
1530
  // Adopting a browser built from a different profile (or a fresh, signed-out clone) would run the
1478
1531
  // caller's automation against the wrong account.
1479
1532
  if ((state?.profileName || null) !== (profileName || null)) return fail('profile-mismatch');
1533
+ if (profileName && (!state.profileSourceDir || resolve(state.profileSourceDir) !== resolve(browserToolsChromeSourceDir()))) return fail('profile-source-mismatch');
1480
1534
  // Headless is fixed at launch, so a windowed request cannot be served by a headless browser.
1481
1535
  if (Boolean(state?.headless) !== Boolean(headless)) return fail('headless-mismatch');
1482
1536
  return { ok: true, ownerId: ownership.ownerId, state };
@@ -1579,6 +1633,11 @@ export function launchChrome({ port = DEFAULT_PORT, profileName = null, userData
1579
1633
  // A stale marker must not make a later launch appear to own a competing endpoint.
1580
1634
  rmSync(join(launchUserDataDir, 'DevToolsActivePort'), { force: true });
1581
1635
  assertChromeBinaryLaunchable(chromeBin);
1636
+ if (process.platform === 'linux' && !headless && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY) {
1637
+ throw new Error('No Linux display found. Pass --headless (API: headless: true), or provide a working DISPLAY/WAYLAND_DISPLAY.');
1638
+ }
1639
+ mkdirSync(launchUserDataDir, { recursive: true, mode: 0o700 });
1640
+ chmodSync(launchUserDataDir, 0o700);
1582
1641
  const pidFile = pidFileForPort(normalizedPort);
1583
1642
  const stateFile = stateFileForPort(normalizedPort);
1584
1643
  let proc = headless ? launchHeadlessChromeApp({ chromeBin, args }) : null;
@@ -1603,6 +1662,7 @@ export function launchChrome({ port = DEFAULT_PORT, profileName = null, userData
1603
1662
  pid: proc.pid,
1604
1663
  port: normalizedPort,
1605
1664
  profileName: profileName || null,
1665
+ profileSourceDir: profileName ? browserToolsChromeSourceDir() : null,
1606
1666
  userDataDir: launchUserDataDir,
1607
1667
  headless: Boolean(headless),
1608
1668
  includeGoogle: Boolean(includeGoogle),
@@ -1761,6 +1821,9 @@ export async function startChrome({
1761
1821
  }
1762
1822
  // A configuration mismatch is not an ownership problem: the caller owns this browser, it
1763
1823
  // was just built differently. Say so, rather than sending them to look for a token.
1824
+ if (reuse.reason === 'profile-source-mismatch') {
1825
+ throw new Error('Managed Chrome profile source differs or was not recorded by this version. Stop it with the owner token and --clean, then restart for the requested source profile.');
1826
+ }
1764
1827
  if (reuse.reason === 'profile-mismatch') {
1765
1828
  throw new Error(
1766
1829
  `Chrome on :${normalizedPort} was started with profile ${state?.profileName ? `"${state.profileName}"` : '(fresh, no profile)'}, but this start requested ${resolvedProfileName ? `"${resolvedProfileName}"` : '(fresh, no profile)'}. Reusing it would run against the wrong account. Stop it with scripts/stop.mjs --clean and start again, or pick a different --port.`,
@@ -1916,11 +1979,11 @@ export async function startChrome({
1916
1979
  const launchedEndpoint = await waitForChromeEndpoint(normalizedPort, { timeoutMs: CHROME_READY_TIMEOUT_MS });
1917
1980
  if (!launchedEndpoint) {
1918
1981
  stopChrome({ port: normalizedPort, ownerToken: effectiveOwnerToken, ignorePortLock: true });
1919
- throw new Error(`Failed to connect to Chrome after ${Math.round(CHROME_READY_TIMEOUT_MS / 1000)}s`);
1982
+ throw new Error(`Failed to connect to Chrome after ${Math.round(CHROME_READY_TIMEOUT_MS / 1000)}s. Check the executable, Linux sandbox/user-namespace policy, display (or --headless), and profile permissions. Snap confinement may require BROWSER_TOOLS_CACHE_DIR and BROWSER_TOOLS_ARTIFACT_DIR inside its accessible directories. Browser Tools never disables the sandbox automatically.`);
1920
1983
  }
1921
1984
  const launchedState = readManagedStateForPort(normalizedPort);
1922
1985
  const launchedSafety = managedBrowserSafetyForPort(normalizedPort);
1923
- if (!launchedSafety.ok || Number(launchedState?.pid) !== Number(proc?.pid) || !devToolsActivePortMatches(launchedState?.userDataDir, launchedEndpoint)) {
1986
+ if (!launchedSafety.ok || Number(launchedState?.pid) !== Number(proc?.pid) || !await launchedEndpointMatches({ port: normalizedPort, endpoint: launchedEndpoint, state: launchedState })) {
1924
1987
  stopChrome({ port: normalizedPort, ownerToken: effectiveOwnerToken, ignorePortLock: true });
1925
1988
  throw new Error(
1926
1989
  `Chrome reported ready on :${normalizedPort}, but the responding process was not verified as the managed launch (${launchedSafety.reason || 'pid-mismatch'}).`,
@@ -1987,7 +2050,7 @@ export function stopChrome({ port = DEFAULT_PORT, clean = false, dryRun = false,
1987
2050
  rmSync(paths.stateFile, { force: true });
1988
2051
  let cleaned = false;
1989
2052
  if (clean && isBrowserToolsUserDataDir(state?.userDataDir)) {
1990
- rmSync(state.userDataDir, { recursive: true, force: true });
2053
+ rmSync(state.userDataDir, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
1991
2054
  rmSync(profileSyncStateFileForPort(normalizedPort), { force: true });
1992
2055
  cleaned = true;
1993
2056
  }
@@ -2079,7 +2142,7 @@ export function stopChrome({ port = DEFAULT_PORT, clean = false, dryRun = false,
2079
2142
  rmSync(paths.stateFile, { force: true });
2080
2143
  let cleaned = false;
2081
2144
  if (clean && isBrowserToolsUserDataDir(state?.userDataDir)) {
2082
- rmSync(state.userDataDir, { recursive: true, force: true });
2145
+ rmSync(state.userDataDir, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
2083
2146
  rmSync(profileSyncStateFileForPort(normalizedPort), { force: true });
2084
2147
  cleaned = true;
2085
2148
  }
@@ -2165,6 +2228,19 @@ function readManagedState(stateFile) {
2165
2228
  }
2166
2229
 
2167
2230
  function commandForPid(pid) {
2231
+ if (process.platform === 'linux') {
2232
+ try {
2233
+ const command = readFileSync(`/proc/${pid}/cmdline`, 'utf8');
2234
+ // Chromium rewrites its process title into argv[0], leaving only trailing NULs.
2235
+ // Retain exact boundaries for ordinary argv; parse the rewritten title as ps does.
2236
+ if (command) return command.split('\0').filter(Boolean).length === 1 ? command.replaceAll('\0', '').trim() : command;
2237
+ if (!processExists(pid)) return null;
2238
+ throw new Error(`Cannot inspect live browser process ${pid}`);
2239
+ } catch (error) {
2240
+ if (error.code === 'ENOENT' || error.code === 'ESRCH') return null;
2241
+ throw error;
2242
+ }
2243
+ }
2168
2244
  const result = spawnSync('ps', ['-p', String(pid), '-o', 'command='], { encoding: 'utf-8' });
2169
2245
  if (result.error || result.status !== 0) return null;
2170
2246
  const command = result.stdout.trim();
@@ -2194,6 +2270,12 @@ function processStartIdentity(pid) {
2194
2270
  }
2195
2271
 
2196
2272
  function processIsZombie(pid) {
2273
+ if (process.platform === 'linux') {
2274
+ try {
2275
+ const stat = readFileSync(`/proc/${pid}/stat`, 'utf8');
2276
+ return stat.slice(stat.lastIndexOf(')') + 2).startsWith('Z');
2277
+ } catch { return false; }
2278
+ }
2197
2279
  const result = spawnSync('ps', ['-p', String(pid), '-o', 'state='], { encoding: 'utf-8' });
2198
2280
  if (result.error || result.status !== 0) return false;
2199
2281
  return result.stdout.trim().startsWith('Z');
@@ -2272,9 +2354,18 @@ export function managedChromeCommandSafety({ pid, port, state, command }) {
2272
2354
  const expectedToken = `--pi-browser-tools-managed=${state.managedToken}`;
2273
2355
  const expectedUserDataDir = `--user-data-dir=${state.userDataDir}`;
2274
2356
 
2275
- if (!command.includes(expectedDebugPort)) return { ok: false, reason: 'debug-port-mismatch', command };
2276
- if (!command.includes(expectedUserDataDir)) return { ok: false, reason: 'user-data-dir-mismatch', command };
2277
- if (!command.includes(expectedToken)) return { ok: false, reason: 'managed-token-mismatch', command };
2357
+ const argv = command.includes('\0') ? command.split('\0') : null;
2358
+ const hasArgument = (arg) => {
2359
+ if (argv) return argv.includes(arg);
2360
+ const start = command.indexOf(arg);
2361
+ if (start < 0) return false;
2362
+ const end = start + arg.length;
2363
+ return (start === 0 || /\s/.test(command[start - 1]))
2364
+ && (end === command.length || /\s/.test(command[end]));
2365
+ };
2366
+ if (!hasArgument(expectedDebugPort)) return { ok: false, reason: 'debug-port-mismatch', command };
2367
+ if (!hasArgument(expectedUserDataDir)) return { ok: false, reason: 'user-data-dir-mismatch', command };
2368
+ if (!hasArgument(expectedToken)) return { ok: false, reason: 'managed-token-mismatch', command };
2278
2369
 
2279
2370
  return { ok: true, command };
2280
2371
  }
@@ -2292,12 +2383,35 @@ export async function connectBrowser(port = DEFAULT_PORT, options = {}) {
2292
2383
  throw new Error(`Refusing to connect to Browser Tools Chrome on :${normalizedPort}: ${ownership.reason}`);
2293
2384
  }
2294
2385
  return puppeteer.connect({
2295
- browserURL: `http://localhost:${normalizedPort}`,
2386
+ browserURL: `http://127.0.0.1:${normalizedPort}`,
2296
2387
  defaultViewport: null,
2297
2388
  ...puppeteerOptions,
2298
2389
  });
2299
2390
  }
2300
2391
 
2392
+ /** Connects to a browser this process started itself, which needs no managed-browser ownership check. */
2393
+ export async function connectOwnBrowser(browserWSEndpoint, options = {}) {
2394
+ return puppeteer.connect({ browserWSEndpoint, defaultViewport: null, ...options });
2395
+ }
2396
+
2397
+ /** Connects to the one tab a tab broker leased (see tab-broker.mjs), seeing no other tab of the browser. */
2398
+ export async function connectLeasedTab({ cdpUrl, tabUrl }, options = {}) {
2399
+ if (typeof cdpUrl !== 'string' || !cdpUrl.startsWith('ws://')) throw new Error('cdpUrl must be a ws:// address');
2400
+ if (typeof tabUrl !== 'string' || !tabUrl.startsWith('about:blank#')) throw new Error('tabUrl must be a leased tab address');
2401
+ const browser = await puppeteer.connect({
2402
+ browserWSEndpoint: cdpUrl,
2403
+ defaultViewport: null,
2404
+ ...options,
2405
+ targetFilter: (target) => target.url() === tabUrl,
2406
+ });
2407
+ const [page] = await browser.pages();
2408
+ if (!page) {
2409
+ await browser.disconnect();
2410
+ throw new Error('The leased tab is gone');
2411
+ }
2412
+ return { browser, page };
2413
+ }
2414
+
2301
2415
  export async function withBrowser(port, callback, options = {}) {
2302
2416
  const browser = await connectBrowser(port, options);
2303
2417
  try {
@@ -0,0 +1,96 @@
1
+ import { accessSync, constants, readFileSync, realpathSync, statSync } from 'node:fs';
2
+ import { homedir } from 'node:os';
3
+ import { basename, isAbsolute, join } from 'node:path';
4
+
5
+ const MAC_CHROME = '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome';
6
+ const LINUX_NAMES = [
7
+ 'google-chrome', 'google-chrome-stable', 'google-chrome-beta',
8
+ 'google-chrome-unstable', 'chromium', 'chromium-browser',
9
+ ];
10
+ const LINUX_LOCATIONS = ['/usr/bin', '/usr/local/bin', '/opt/bin']
11
+ .flatMap((directory) => LINUX_NAMES.map((name) => join(directory, name))).concat([
12
+ // Use the supported snap launcher, never its internal binary.
13
+ '/snap/bin/chromium',
14
+ '/opt/google/chrome/chrome', '/opt/google/chrome-beta/chrome',
15
+ '/opt/google/chrome-unstable/chrome',
16
+ '/usr/lib/chromium/chromium', '/usr/lib64/chromium-browser/chromium-browser',
17
+ '/usr/lib/chromium-browser/chromium-browser', '/usr/lib64/chromium/chromium',
18
+ ]);
19
+
20
+ function executable(file) {
21
+ try {
22
+ accessSync(file, constants.X_OK);
23
+ return statSync(file).isFile();
24
+ } catch { return false; }
25
+ }
26
+
27
+ /** Read-only discovery: executable Linux launcher or null if absent.
28
+ * macOS preserves its historical default even when not installed.
29
+ * Explicit configuration/env overrides belong to the caller.
30
+ */
31
+ export function discoverChromeBinary({ platform = process.platform, env = process.env, home = homedir() } = {}) {
32
+ if (platform === 'darwin') return MAC_CHROME;
33
+ if (platform !== 'linux') return null;
34
+ void home; // Do not infer installations from arbitrary downloads/caches.
35
+ const directories = (env.PATH || '').split(':').filter(Boolean);
36
+ for (const name of LINUX_NAMES) {
37
+ for (const directory of directories) {
38
+ const candidate = join(directory, name);
39
+ if (executable(candidate)) return candidate;
40
+ }
41
+ }
42
+ return LINUX_LOCATIONS.find(executable) || null;
43
+ }
44
+
45
+ function directoryExists(directory) {
46
+ try { return statSync(directory).isDirectory(); } catch { return false; }
47
+ }
48
+
49
+ function snapChromium(binary, env = process.env) {
50
+ if (!binary.includes('/')) {
51
+ binary = (env.PATH || '').split(':').filter(Boolean).map(dir => join(dir, binary)).find(executable) || binary;
52
+ }
53
+ if (binary === '/snap/bin/chromium' || binary.includes('/snap/chromium/')) return true;
54
+ try {
55
+ const target = realpathSync(binary);
56
+ if (target === '/usr/bin/snap' || target.includes('/snap/chromium/')) return true;
57
+ // Ubuntu's chromium-browser compatibility launcher delegates to snap.
58
+ if (statSync(binary).size < 64 * 1024) {
59
+ return /(?:\/snap\/bin\/chromium|\bsnap\s+run\s+chromium\b)/.test(readFileSync(binary, 'utf8'));
60
+ }
61
+ } catch { /* Missing or unreadable launchers retain predictable defaults. */ }
62
+ return false;
63
+ }
64
+
65
+ /** User-data root for the selected browser family/channel; never creates it.
66
+ * Never substitutes another browser family's existing profile.
67
+ */
68
+ export function discoverChromeSourceDir({ chromeBin, platform = process.platform, env = process.env, home = homedir() } = {}) {
69
+ if (platform === 'darwin') return join(home, 'Library', 'Application Support', 'Google', 'Chrome');
70
+ if (platform !== 'linux') return null;
71
+ const binary = chromeBin || discoverChromeBinary({ platform, env, home }) || 'google-chrome';
72
+ const name = basename(binary).toLowerCase();
73
+ const configRoot = env.XDG_CONFIG_HOME && isAbsolute(env.XDG_CONFIG_HOME)
74
+ ? env.XDG_CONFIG_HOME : join(home, '.config');
75
+ if (name.includes('chromium') || binary.includes('/snap/chromium/')) {
76
+ const native = join(configRoot, 'chromium');
77
+ const snap = join(home, 'snap', 'chromium', 'common', 'chromium');
78
+ if (snapChromium(binary, env)) return snap;
79
+ // Distro launchers can delegate to snap; stay within the Chromium family.
80
+ return !directoryExists(native) && directoryExists(snap) ? snap : native;
81
+ }
82
+ const channel = /(?:google-chrome|chrome)[-/]beta(?:[/]|$)/.test(binary) ? '-beta'
83
+ : /(?:google-chrome|chrome)[-/](?:unstable|dev)(?:[/]|$)/.test(binary) ? '-unstable' : '';
84
+ return join(configRoot, 'google-chrome' + channel);
85
+ }
86
+
87
+ /** User-agent platform component, not a full User-Agent string. */
88
+ export function chromePlatformToken({ platform = process.platform, arch = process.arch } = {}) {
89
+ if (platform === 'darwin') return 'Macintosh; Intel Mac OS X 10_15_7';
90
+ if (platform === 'win32') return 'Windows NT 10.0; Win64; x64';
91
+ if (platform === 'linux') {
92
+ const machine = { x64: 'x86_64', arm64: 'aarch64', ia32: 'i686', arm: 'armv7l' }[arch] || arch;
93
+ return 'X11; Linux ' + machine;
94
+ }
95
+ return 'X11; ' + platform + ' ' + arch;
96
+ }
@@ -1,4 +1,5 @@
1
1
  import { hasFlag, parsePositiveIntegerOption, sleep } from './browser-control.mjs';
2
+ import { createRecordingLifecycle } from './recording-lifecycle.mjs';
2
3
  import {
3
4
  matchesPatterns,
4
5
  optionValues,
@@ -100,40 +101,58 @@ export async function runCdpEventCapture({
100
101
  writeEvent,
101
102
  onPhase = () => {},
102
103
  }) {
104
+ const lifecycle = createRecordingLifecycle('cdp');
103
105
  let eventCount = 0;
104
106
  const startedMonotonic = performance.now();
105
107
  const onAnyEvent = (method, params) => {
106
- if (eventCount >= options.maxEvents) return;
108
+ if (['completed', 'failed'].includes(lifecycle.phase) || eventCount >= options.maxEvents) return;
107
109
  if (typeof method !== 'string') return;
108
110
  if (!matchesPatterns(method, options.eventPatterns, options.excludedEventPatterns)) return;
109
- writeEvent({
110
- timestamp: new Date().toISOString(),
111
- elapsed_ms: Number((performance.now() - startedMonotonic).toFixed(3)),
112
- method,
113
- params: sanitizeCdpEvent(method, params, options),
114
- });
115
- eventCount += 1;
111
+ try {
112
+ writeEvent({
113
+ timestamp: new Date().toISOString(),
114
+ elapsed_ms: Number((performance.now() - startedMonotonic).toFixed(3)),
115
+ method,
116
+ params: sanitizeCdpEvent(method, params, options),
117
+ });
118
+ eventCount += 1;
119
+ } catch (error) {
120
+ lifecycle.transition('failed', { error });
121
+ }
116
122
  };
117
123
  session.on('*', onAnyEvent);
118
124
 
119
- for (const domain of options.domains) {
120
- if (options.skippedDomainEnables.includes(domain)) continue;
121
- try {
122
- await session.send(`${domain}.enable`);
123
- } catch (error) {
124
- throw new Error(`Could not enable CDP domain ${domain}: ${error.message}. Use --skip-enable ${domain} and --setup when the domain needs a different activation method.`);
125
+ const assertHealthy = () => {
126
+ if (lifecycle.phase === 'failed') throw lifecycle.snapshot().error;
127
+ };
128
+ try {
129
+ for (const domain of options.domains) {
130
+ if (options.skippedDomainEnables.includes(domain)) continue;
131
+ try {
132
+ await session.send(`${domain}.enable`);
133
+ } catch (error) {
134
+ throw new Error(`Could not enable CDP domain ${domain}: ${error.message}. Use --skip-enable ${domain} and --setup when the domain needs a different activation method.`);
135
+ }
125
136
  }
126
- }
127
- for (const command of options.setupCommands) {
128
- await session.send(command.method, command.params);
129
- }
130
- await onPhase('recording');
137
+ for (const command of options.setupCommands) await session.send(command.method, command.params);
138
+ assertHealthy();
139
+ lifecycle.transition('recording');
140
+ await onPhase('recording');
131
141
 
132
- const deadline = Date.now() + options.maxDurationSeconds * 1000;
133
- while (!shouldStop() && Date.now() < deadline && eventCount < options.maxEvents) await sleep(100);
134
- const reason = shouldStop() ? 'requested' : (eventCount >= options.maxEvents ? 'max-events' : 'max-duration');
135
- await onPhase('post-wait', reason);
136
- await sleep(options.postWaitMs);
137
- session.off('*', onAnyEvent);
138
- return { reason, eventCount };
142
+ const deadline = Date.now() + options.maxDurationSeconds * 1000;
143
+ while (lifecycle.phase === 'recording' && !shouldStop() && Date.now() < deadline && eventCount < options.maxEvents) await sleep(100);
144
+ assertHealthy();
145
+ const reason = shouldStop() ? 'requested' : (eventCount >= options.maxEvents ? 'max-events' : 'max-duration');
146
+ lifecycle.transition('post-wait', { reason });
147
+ await onPhase('post-wait', reason);
148
+ await sleep(options.postWaitMs);
149
+ assertHealthy();
150
+ lifecycle.transition('completed');
151
+ return { reason, eventCount };
152
+ } catch (error) {
153
+ if (lifecycle.phase !== 'failed') lifecycle.transition('failed', { error });
154
+ throw error;
155
+ } finally {
156
+ session.off('*', onAnyEvent);
157
+ }
139
158
  }