@rezkam/browser-tools 1.1.2 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,19 @@
1
1
  # @rezkam/browser-tools
2
2
 
3
+ ## 2.1.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 924caa5: Add `--viewport <width>x<height> [--mobile] [--scale <n>]` to `screenshot`, `eval`, and `nav`, and `screenshot --selector <css>` for one element. A screen size sent with `cdp call` ended with that call, so later commands silently saw a desktop page; the size is now held for the command that asks for it, without reloading the tab, and `cdp call` says when an Emulation override will not last. `screenshot` reports the image size and fails when a viewport capture does not match the requested size, and element captures no longer wait forever on background tabs. Library code can use `capturePage` and `withViewport` from `@rezkam/browser-tools/viewport.mjs`.
8
+
9
+ ## 2.0.0
10
+
11
+ ### Major Changes
12
+
13
+ - 608f58d: Require Node.js 22.12 or newer for the pinned Rebrowser Puppeteer backend and add owner-protected unpacked extension loading and updates. Verify on load that a service worker of the loaded version activated, retain extension settings during updates, and keep extension-debugging permissions explicit at launch and during browser reuse.
14
+
15
+ Breaking: the Rebrowser backend does not send `Runtime.enable`, so `page.on('console')` and `page.on('pageerror')` no longer receive events on pages from `connectBrowser`, `withBrowser`, or `connectLeasedTab`. Pages can detect that call, so it stays off. Read page state with `page.evaluate` or report through `exposeFunction` instead.
16
+
3
17
  ## 1.1.2
4
18
 
5
19
  ### Patch Changes
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @rezkam/browser-tools
2
2
 
3
- Managed Chrome automation with isolated profiles and owner-protected sessions. Browser Tools can drive pages, inspect the DOM, capture visual and network evidence, and extract page content without connecting to or stopping your main Chrome.
3
+ Managed Chrome automation with isolated profiles and owner-protected sessions. Connections use the pinned Rebrowser Puppeteer backend to reduce library-specific automation signals; this does not guarantee undetectability or provider access. Browser Tools can drive pages, inspect the DOM, capture visual and network evidence, and extract page content without connecting to or stopping your main Chrome.
4
4
 
5
5
  This repository provides both the `browser-tools` skill and the `@rezkam/browser-tools` npm package. The skill uses the same CLI that the package installs.
6
6
 
@@ -34,7 +34,7 @@ Commands can also run without a global install:
34
34
  npx @rezkam/browser-tools <command>
35
35
  ```
36
36
 
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`:
37
+ Browser Tools requires macOS or Linux, installed Google Chrome or Chromium, and Node.js 22.12 or newer. GIF recording and review additionally require `ffmpeg` and `ffprobe`:
38
38
 
39
39
  ```bash
40
40
  brew install ffmpeg
@@ -72,8 +72,9 @@ Use `--profile "<profile or alias>"` when an existing login is needed, `--sync`
72
72
  | Area | Commands | What they do |
73
73
  | --- | --- | --- |
74
74
  | Browser lifecycle | `start`, `status`, `stop` | Launch, inspect, stop, clean, reap, and prune managed Chrome sessions |
75
+ | Extensions | `extensions load`, `extensions update` | Load trusted unpacked extensions or reload updated files while retaining identity and settings |
75
76
  | Profile configuration | `config` | Discover profiles, list active profiles, and manage task-to-profile mappings |
76
- | Page control | `nav`, `eval`, `screenshot` | Navigate the active tab or a new background tab, run page JavaScript, and capture PNG screenshots |
77
+ | Page control | `nav`, `eval`, `screenshot` | Navigate the active tab or a new background tab, run page JavaScript, and capture PNG screenshots of the viewport, the full page, or one element, optionally at a set screen size |
77
78
  | DOM inspection | `pick` | Select one or more visible elements and return tag, id, class, text, HTML, and parent information |
78
79
  | Page extraction | `scrape-page`, `extract-article` | Extract article-like links with timestamps or readable article text from the active tab |
79
80
  | Visual recording | `record-gif`, `review-gif` | Record an interaction with pre-roll and post-roll frames, then create a contact sheet and metadata report |
@@ -97,15 +98,61 @@ Browser Tools stores local configuration under `~/.agents/browser-tools` and man
97
98
 
98
99
  For detailed ownership rules, profile behavior, capture filters, and command options, see the repository's [SKILL.md](https://github.com/rezkam/browser-tools/blob/main/SKILL.md) and [Browser Control reference](https://github.com/rezkam/browser-tools/blob/main/references/browser-control.md).
99
100
 
101
+ ## Extensions
102
+
103
+ Load a trusted unpacked extension when starting a managed browser:
104
+
105
+ ```bash
106
+ browser-tools start --headless --extension /absolute/path/to/extension
107
+ # Repeat --extension to load multiple extensions.
108
+ ```
109
+
110
+ Startup verifies the manifest and, for service-worker extensions, that a worker of that version reached the activated state before reporting ready. A worker script that fails to evaluate is reported as a failed load or update. A failed initial load stops the newly created browser. Loading into an existing owned session instead requires that it was started with `--extension-debugging`:
111
+
112
+ ```bash
113
+ browser-tools extensions load /absolute/path/to/extension --port <reported-port>
114
+ # After replacing the trusted files in the same directory:
115
+ browser-tools extensions update /absolute/path/to/extension --port <reported-port>
116
+ ```
117
+
118
+ Both commands require the owner's token. Updates reload without uninstalling, retaining the extension ID and settings; use the same directory or a manifest with a stable key. Changing an extension's key changes its identity. Extension-debugging permissions are fixed at launch, explicit, and part of browser reuse checks. Do not load untrusted extensions: they can access site data in the managed profile.
119
+
120
+ Browser Tools does not download extensions or silently enable their online updaters. The caller owns trusted downloads, signature/digest validation, rule freshness and application-specific configuration. Applications should retain their existing verified download and configuration workflow and check the active network rules. A loaded worker alone does not prove provider rules are enabled.
121
+
100
122
  ## Programmatic use
101
123
 
102
124
  ```js
103
125
  import { activePage, connectBrowser, startChrome, stopChrome, withBrowser } from '@rezkam/browser-tools';
104
126
  import { runBrowserResource } from '@rezkam/browser-tools/resource-helper.mjs';
127
+ import { loadManagedExtension } from '@rezkam/browser-tools/extensions.mjs';
105
128
  ```
106
129
 
130
+ For extensions, use `startChrome({ extensionDebugging: true, ...options })`, then `loadManagedExtension({ directory, port, ownerToken })`. Applications that already configure their extension may instead call `browser.installExtension(directory)` on an owned connection.
131
+
107
132
  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.
108
133
 
134
+ ### Console and page-error events
135
+
136
+ The Rebrowser backend does not send `Runtime.enable`, because pages can detect it. As a result `page.on('console')` and `page.on('pageerror')` receive nothing, without an error. Page evaluation, navigation, network events, and `exposeFunction` are unaffected. Browser Tools keeps that protection on and offers no way to turn it off. Read page state with `page.evaluate` instead, or have the page report through `exposeFunction`.
137
+
138
+ ### Screen size and screenshots
139
+
140
+ ```bash
141
+ browser-tools screenshot --viewport 375x667 --mobile --port <reported port>
142
+ browser-tools eval --viewport 375x667 --mobile 'innerWidth' --port <reported port>
143
+ ```
144
+
145
+ `--viewport <width>x<height> [--mobile] [--scale <n>]` works on `screenshot`, `eval`, and `nav`, and `screenshot --selector <css>` captures one element. The size lasts for that one command, because Chrome drops an emulated size when the CDP session that set it ends. For the same reason a size sent with `browser-tools cdp call Emulation.setDeviceMetricsOverride` is gone before the next command runs. `screenshot` reports the image size on stderr and fails when a viewport capture does not match the requested size.
146
+
147
+ ```js
148
+ import { capturePage, withViewport } from '@rezkam/browser-tools/viewport.mjs';
149
+
150
+ const viewport = { width: 375, height: 667, deviceScaleFactor: 2, mobile: true };
151
+ const png = await capturePage(page, { viewport, selector: 'table.results' });
152
+ ```
153
+
154
+ Use `capturePage` on managed tabs in place of Puppeteer's `elementHandle.screenshot()`, which never finishes on a background tab, and `page.screenshot()`, which ignores the scale of a size set on another session.
155
+
109
156
  ### Shared tabs
110
157
 
111
158
  `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.
@@ -10,9 +10,9 @@
10
10
  * browser-tools start [--task <task>] [--profile <name>] [--headless] [--sync] [--port <n>]
11
11
  * browser-tools status [--port <n>] [--json]
12
12
  * browser-tools stop [--clean] [--dry-run] [--prune]
13
- * browser-tools nav <url> [--new] [--port <n>]
14
- * browser-tools eval '<javascript>' [--port <n>]
15
- * browser-tools screenshot [--full] [--port <n>]
13
+ * browser-tools nav <url> [--new] [--viewport <w>x<h> [--mobile] [--scale <n>]] [--port <n>]
14
+ * browser-tools eval '<javascript>' [--viewport <w>x<h> [--mobile] [--scale <n>]] [--port <n>]
15
+ * browser-tools screenshot [--full | --selector <css>] [--viewport <w>x<h> [--mobile] [--scale <n>]] [--port <n>]
16
16
  * browser-tools record-gif start|status|stop [options]
17
17
  * browser-tools review-gif <meaningful.gif> [options]
18
18
  * browser-tools record-har start|status|stop [options]
@@ -22,6 +22,7 @@
22
22
  * browser-tools pick "<instruction>" [--port <n>]
23
23
  * browser-tools scrape-page [--port <n>]
24
24
  * browser-tools extract-article [--chars <n>] [--port <n>]
25
+ * browser-tools extensions load|update <trusted-unpacked-directory> [--port <n>]
25
26
  * browser-tools config profiles|active-profiles|task-profile ...
26
27
  * browser-tools serve [--max-tabs <n>] [--tab-seconds <n>] [--headless] [--proxy-server <url>] [--until-stdin-closes]
27
28
  */
@@ -49,6 +50,7 @@ const COMMANDS = {
49
50
  pick: 'pick.mjs',
50
51
  'scrape-page': 'scrape-page.mjs',
51
52
  'extract-article': 'extract-article.mjs',
53
+ extensions: 'extensions.mjs',
52
54
  config: 'config.mjs',
53
55
  serve: 'serve.mjs',
54
56
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rezkam/browser-tools",
3
- "version": "1.1.2",
3
+ "version": "2.1.0",
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",
@@ -13,7 +13,7 @@
13
13
  "url": "https://github.com/rezkam/browser-tools/issues"
14
14
  },
15
15
  "engines": {
16
- "node": ">=20"
16
+ "node": ">=22.12.0"
17
17
  },
18
18
  "bin": {
19
19
  "browser-tools": "./bin/browser-tools.mjs"
@@ -22,7 +22,9 @@
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
+ "./extensions.mjs": "./scripts/extensions.mjs",
25
26
  "./tab-broker.mjs": "./scripts/tab-broker.mjs",
27
+ "./viewport.mjs": "./scripts/viewport.mjs",
26
28
  "./package.json": "./package.json"
27
29
  },
28
30
  "files": [
@@ -42,7 +44,7 @@
42
44
  "validate": "npm test && npm run test:e2e"
43
45
  },
44
46
  "dependencies": {
45
- "puppeteer-core": "^24.42.0",
47
+ "puppeteer-core": "npm:rebrowser-puppeteer-core@25.16.0",
46
48
  "ws": "^8.22.0"
47
49
  },
48
50
  "devDependencies": {
@@ -1013,7 +1013,7 @@ export function removeChromeProfileLocks(profileDir) {
1013
1013
  }
1014
1014
  }
1015
1015
 
1016
- export function chromeLaunchArgs({ port = DEFAULT_PORT, profileName = null, managedToken = null, userDataDir = null, headless = false, userAgent = null } = {}) {
1016
+ export function chromeLaunchArgs({ port = DEFAULT_PORT, profileName = null, managedToken = null, userDataDir = null, headless = false, userAgent = null, extensionDebugging = false } = {}) {
1017
1017
  const normalizedPort = normalizePort(port);
1018
1018
  const launchUserDataDir = userDataDir || (profileName ? profileDataDirForPort(normalizedPort) : freshProfileDirForPort(normalizedPort));
1019
1019
  const args = [
@@ -1030,6 +1030,7 @@ export function chromeLaunchArgs({ port = DEFAULT_PORT, profileName = null, mana
1030
1030
  // Bot defenses reject navigator.webdriver and headless Chrome's default 800x600 screen, so a
1031
1031
  // headless launch hides the automation flag and reports a common desktop display.
1032
1032
  if (headless) args.push('--headless=new', '--disable-blink-features=AutomationControlled', '--window-size=1920,1040', '--screen-info={1920x1080}');
1033
+ if (extensionDebugging) args.push('--enable-unsafe-extension-debugging');
1033
1034
  // A headless launch otherwise advertises a "HeadlessChrome" User-Agent. When the copied profile is
1034
1035
  // signed in to Google, that headless fingerprint trips Google's session-theft protection and logs the
1035
1036
  // source profile out, while a windowed launch (normal Chrome UA) does not. Present the normal UA so a
@@ -1518,6 +1519,7 @@ export function managedBrowserReuseDecision({
1518
1519
  profileName = null,
1519
1520
  headless = false,
1520
1521
  forceProfileSync = false,
1522
+ extensionDebugging = false,
1521
1523
  }) {
1522
1524
  if (!safety?.ok) return { ok: false, reason: safety?.reason || 'missing-managed-state' };
1523
1525
  const ownership = managedBrowserOwnershipSafety({ state, ownerToken });
@@ -1535,6 +1537,7 @@ export function managedBrowserReuseDecision({
1535
1537
  if (profileName && (!state.profileSourceDir || resolve(state.profileSourceDir) !== resolve(browserToolsChromeSourceDir()))) return fail('profile-source-mismatch');
1536
1538
  // Headless is fixed at launch, so a windowed request cannot be served by a headless browser.
1537
1539
  if (Boolean(state?.headless) !== Boolean(headless)) return fail('headless-mismatch');
1540
+ if (Boolean(state?.extensionDebugging) !== Boolean(extensionDebugging)) return fail('extension-debugging-mismatch');
1538
1541
  return { ok: true, ownerId: ownership.ownerId, state };
1539
1542
  }
1540
1543
 
@@ -1547,6 +1550,7 @@ export function findReusableManagedBrowser({
1547
1550
  profileName = null,
1548
1551
  headless = false,
1549
1552
  forceProfileSync = false,
1553
+ extensionDebugging = false,
1550
1554
  processes = listManagedChromeProcesses(),
1551
1555
  } = {}) {
1552
1556
  if (!normalizeOwnerValue(ownerToken)) return null;
@@ -1555,7 +1559,7 @@ export function findReusableManagedBrowser({
1555
1559
  const state = readManagedState(stateFileForPort(entry.port));
1556
1560
  if (!state || Number(state.pid) !== Number(entry.pid)) continue;
1557
1561
  const decision = managedBrowserReuseDecision({
1558
- safety: { ok: true }, state, ownerToken, includeGoogle, profileName, headless, forceProfileSync,
1562
+ safety: { ok: true }, state, ownerToken, includeGoogle, profileName, headless, forceProfileSync, extensionDebugging,
1559
1563
  });
1560
1564
  if (decision.ok) return { ...entry, state };
1561
1565
  }
@@ -1623,7 +1627,7 @@ function launchHeadlessChromeApp({ chromeBin, args }) {
1623
1627
  return { pid };
1624
1628
  }
1625
1629
 
1626
- export function launchChrome({ port = DEFAULT_PORT, profileName = null, userDataDir = null, ownerToken = null, ownerId = null, headless = false, includeGoogle = false } = {}) {
1630
+ export function launchChrome({ port = DEFAULT_PORT, profileName = null, userDataDir = null, ownerToken = null, ownerId = null, headless = false, includeGoogle = false, extensionDebugging = false } = {}) {
1627
1631
  ensureCacheDir();
1628
1632
  const normalizedPort = normalizePort(port);
1629
1633
  const launchUserDataDir = userDataDir || (profileName ? profileDataDirForPort(normalizedPort) : freshProfileDirForPort(normalizedPort));
@@ -1631,7 +1635,7 @@ export function launchChrome({ port = DEFAULT_PORT, profileName = null, userData
1631
1635
  const effectiveOwnerToken = normalizeOwnerValue(ownerToken) || generateOwnerToken();
1632
1636
  const chromeBin = browserToolsChromeBin();
1633
1637
  const userAgent = headless ? headlessUserAgent(chromeBin) : null;
1634
- const args = chromeLaunchArgs({ port: normalizedPort, profileName, managedToken, userDataDir: launchUserDataDir, headless, userAgent });
1638
+ const args = chromeLaunchArgs({ port: normalizedPort, profileName, managedToken, userDataDir: launchUserDataDir, headless, userAgent, extensionDebugging });
1635
1639
  // A stale marker must not make a later launch appear to own a competing endpoint.
1636
1640
  rmSync(join(launchUserDataDir, 'DevToolsActivePort'), { force: true });
1637
1641
  assertChromeBinaryLaunchable(chromeBin);
@@ -1668,6 +1672,7 @@ export function launchChrome({ port = DEFAULT_PORT, profileName = null, userData
1668
1672
  userDataDir: launchUserDataDir,
1669
1673
  headless: Boolean(headless),
1670
1674
  includeGoogle: Boolean(includeGoogle),
1675
+ extensionDebugging: Boolean(extensionDebugging),
1671
1676
  managedToken,
1672
1677
  ...buildOwnerState({ ownerToken: effectiveOwnerToken, ownerId }),
1673
1678
  // Who launched this browser, so a leaked one is attributable instead of anonymous.
@@ -1711,6 +1716,7 @@ export async function startChrome({
1711
1716
  ownerId = null,
1712
1717
  headless = false,
1713
1718
  includeGoogle = false,
1719
+ extensionDebugging = false,
1714
1720
  } = {}) {
1715
1721
  let normalizedPort = normalizePort(port);
1716
1722
  const providedOwnerToken = normalizeOwnerValue(ownerToken);
@@ -1751,7 +1757,7 @@ export async function startChrome({
1751
1757
  if (providedOwnerToken) {
1752
1758
  const candidates = autoAllocatePort ? liveBrowsers : liveBrowsers.filter((entry) => entry.port === normalizedPort);
1753
1759
  const found = findReusableManagedBrowser({
1754
- ownerToken: providedOwnerToken, includeGoogle, processes: candidates,
1760
+ ownerToken: providedOwnerToken, includeGoogle, extensionDebugging, processes: candidates,
1755
1761
  profileName: resolvedProfileName, headless, forceProfileSync,
1756
1762
  });
1757
1763
  const foundEndpoint = found ? await browserWSEndpoint(found.port) : null;
@@ -1794,7 +1800,7 @@ export async function startChrome({
1794
1800
  const safety = managedBrowserSafetyForPort(normalizedPort);
1795
1801
  const state = readManagedStateForPort(normalizedPort);
1796
1802
  const reuse = managedBrowserReuseDecision({
1797
- safety, state, ownerToken: providedOwnerToken, includeGoogle,
1803
+ safety, state, ownerToken: providedOwnerToken, includeGoogle, extensionDebugging,
1798
1804
  profileName: resolvedProfileName, headless, forceProfileSync,
1799
1805
  });
1800
1806
  // Reuse first, on both paths. An auto-allocated start used to skip this entirely and walk to
@@ -1836,6 +1842,9 @@ export async function startChrome({
1836
1842
  `Chrome on :${normalizedPort} is running ${state?.headless ? 'headless' : 'windowed'}, but this start requested ${headless ? 'headless' : 'windowed'}. Headless is fixed at launch: stop it with scripts/stop.mjs --clean and start again.`,
1837
1843
  );
1838
1844
  }
1845
+ if (reuse.reason === 'extension-debugging-mismatch') {
1846
+ throw new Error(`Chrome on :${normalizedPort} has different extension-debugging permissions. Stop it with the owner token and --clean, then restart with the requested extension settings.`);
1847
+ }
1839
1848
  if (reuse.reason === 'sync-requested') {
1840
1849
  throw new Error(
1841
1850
  `Chrome on :${normalizedPort} is already running, and --sync asks for a freshly copied profile. Stop it with scripts/stop.mjs --clean and start again with --sync.`,
@@ -1920,6 +1929,7 @@ export async function startChrome({
1920
1929
  serializedReuse = findReusableManagedBrowser({
1921
1930
  ownerToken: providedOwnerToken,
1922
1931
  includeGoogle,
1932
+ extensionDebugging,
1923
1933
  profileName: resolvedProfileName,
1924
1934
  headless,
1925
1935
  forceProfileSync,
@@ -1941,6 +1951,7 @@ export async function startChrome({
1941
1951
  ownerId: normalizedOwnerId,
1942
1952
  headless,
1943
1953
  includeGoogle,
1954
+ extensionDebugging,
1944
1955
  });
1945
1956
  }
1946
1957
  } finally {
@@ -1959,6 +1970,7 @@ export async function startChrome({
1959
1970
  state,
1960
1971
  ownerToken: providedOwnerToken,
1961
1972
  includeGoogle,
1973
+ extensionDebugging,
1962
1974
  profileName: resolvedProfileName,
1963
1975
  headless,
1964
1976
  forceProfileSync,
package/scripts/cdp.mjs CHANGED
@@ -22,6 +22,7 @@ import {
22
22
  validateCdpMethod,
23
23
  withPageCdpSession,
24
24
  } from './cdp-common.mjs';
25
+ import { SESSION_SCOPED_NOTE } from './viewport.mjs';
25
26
 
26
27
  const SCRIPT_FILE = fileURLToPath(import.meta.url);
27
28
 
@@ -36,7 +37,9 @@ Options:
36
37
  --owner-token <token> Prefer ${OWNER_TOKEN_ENV} instead
37
38
 
38
39
  Direct calls target the active tab and require its owner token. Methods that bypass
39
- managed-browser lifecycle safety are blocked. Prefer --params-file for sensitive input.`);
40
+ managed-browser lifecycle safety are blocked. Prefer --params-file for sensitive input.
41
+ Each call uses its own CDP session, so Emulation overrides end when the call returns.
42
+ For a screen size, use --viewport on screenshot, eval, or nav.`);
40
43
  }
41
44
 
42
45
  function parseParams(args) {
@@ -80,6 +83,7 @@ async function callMethod(args) {
80
83
  const result = await withPageCdpSession(port, ownerToken, ({ session }) => session.send(method, params));
81
84
  const output = sanitizeCdpCallResult(method, result, { redact: hasFlag(rest, '--redact') });
82
85
  console.log(JSON.stringify(output, null, 2));
86
+ if (/^Emulation\.set/.test(method)) console.error(SESSION_SCOPED_NOTE);
83
87
  }
84
88
 
85
89
  export async function main(args = process.argv.slice(2)) {
package/scripts/eval.mjs CHANGED
@@ -7,6 +7,7 @@
7
7
  * scripts/eval.mjs 'document.title'
8
8
  * scripts/eval.mjs 'await fetch("/api/data").then(r => r.json())'
9
9
  * scripts/eval.mjs --port 9223 'document.title'
10
+ * scripts/eval.mjs --viewport 375x667 --mobile 'innerWidth'
10
11
  * scripts/eval.mjs --owner-token "$BROWSER_TOOLS_OWNER_TOKEN" 'document.title'
11
12
  */
12
13
 
@@ -14,6 +15,7 @@ import { realpathSync } from 'node:fs';
14
15
  import { fileURLToPath } from 'node:url';
15
16
  import { format } from 'node:util';
16
17
  import { activePage, parseOwnerToken, parsePort, stripBrowserSessionArgs, withBrowser } from './browser-control.mjs';
18
+ import { parseViewport, stripViewportArgs, withViewport } from './viewport.mjs';
17
19
 
18
20
  if (isDirectExecution()) await main();
19
21
 
@@ -21,10 +23,17 @@ async function main() {
21
23
  const args = process.argv.slice(2);
22
24
  const port = parsePort(args);
23
25
  const ownerToken = parseOwnerToken(args);
24
- const code = stripBrowserSessionArgs(args).join(' ');
26
+ let viewport;
27
+ try {
28
+ viewport = parseViewport(args);
29
+ } catch (error) {
30
+ console.error(`✗ ${error.message}`);
31
+ process.exit(1);
32
+ }
33
+ const code = stripViewportArgs(stripBrowserSessionArgs(args)).join(' ');
25
34
 
26
35
  if (!code) {
27
- console.log("Usage: eval.js [--port <n>] '<javascript>'");
36
+ console.log("Usage: eval.js [--port <n>] [--viewport <width>x<height> [--mobile] [--scale <n>]] '<javascript>'");
28
37
  console.log(" ./eval.js 'document.title'");
29
38
  console.log(' ./eval.js \'document.querySelectorAll("a").length\'');
30
39
  process.exit(1);
@@ -32,10 +41,10 @@ async function main() {
32
41
 
33
42
  await withBrowser(port, async (browser) => {
34
43
  const page = await activePage(browser);
35
- const result = await page.evaluate((c) => {
44
+ const result = await withViewport(page, viewport, () => page.evaluate((c) => {
36
45
  const AsyncFunction = (async () => {}).constructor;
37
46
  return new AsyncFunction(`return (${c})`)();
38
- }, code);
47
+ }, code));
39
48
 
40
49
  printResult(result);
41
50
  }, { ownerToken });
@@ -0,0 +1,93 @@
1
+ #!/usr/bin/env node
2
+ import { readFileSync, realpathSync, statSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ import {
6
+ connectBrowser, expandHomePath, parseOwnerToken, parsePort, readManagedStateForPort,
7
+ } from './browser-control.mjs';
8
+
9
+ // Only load explicitly trusted local files. Downloads, archive validation and provider-specific
10
+ // configuration belong to the caller; an extension can access the browsing session's site data.
11
+ export function extensionDirectory(directory) {
12
+ if (typeof directory !== 'string' || !directory || directory.startsWith('--')) {
13
+ throw new Error('An unpacked extension directory is required');
14
+ }
15
+ const path = realpathSync(expandHomePath(directory));
16
+ if (!statSync(path).isDirectory()) throw new Error('Extension path must be a directory');
17
+ const manifest = JSON.parse(readFileSync(join(path, 'manifest.json'), 'utf8'));
18
+ if (![2, 3].includes(manifest.manifest_version) || typeof manifest.name !== 'string' || !manifest.name.trim()
19
+ || typeof manifest.version !== 'string' || !/^\d+(\.\d+){0,3}$/.test(manifest.version)) {
20
+ throw new Error('Invalid extension manifest');
21
+ }
22
+ return { path, manifest };
23
+ }
24
+
25
+ const WORKER_POLL_MS = 100;
26
+ const WORKER_PROBE_MS = 2000;
27
+
28
+ // The manifest version alone proves nothing about the worker: Chrome answers getManifest() in the
29
+ // short-lived global of a worker whose script failed to evaluate. Only a script that ran reaches
30
+ // "activated", so require both. Poll instead of waiting on target events, because a healthy worker
31
+ // can still be installing when its target appears and no later event would re-check it.
32
+ async function extensionWorkerStarted(browser, { id, version, timeout }) {
33
+ const deadline = Date.now() + timeout;
34
+ const probe = async (target) => {
35
+ const worker = await target.worker();
36
+ return worker.evaluate(
37
+ expected => chrome.runtime.getManifest().version === expected && self.serviceWorker?.state === 'activated',
38
+ version,
39
+ );
40
+ };
41
+ while (Date.now() < deadline) {
42
+ const targets = browser.targets().filter(target => target.type() === 'service_worker' && target.url().startsWith(`chrome-extension://${id}/`));
43
+ for (const target of targets) {
44
+ // A worker that is being torn down can leave an evaluation unanswered, so bound each probe.
45
+ let timer;
46
+ const expired = new Promise(resolve => { timer = setTimeout(resolve, WORKER_PROBE_MS, false); });
47
+ try {
48
+ if (await Promise.race([probe(target).catch(() => false), expired])) return true;
49
+ } finally {
50
+ clearTimeout(timer);
51
+ }
52
+ }
53
+ await new Promise(resolve => setTimeout(resolve, WORKER_POLL_MS));
54
+ }
55
+ return false;
56
+ }
57
+
58
+ export async function loadManagedExtension({ directory, port, ownerToken, timeout = 30000 }) {
59
+ const { path, manifest } = extensionDirectory(directory);
60
+ const browser = await connectBrowser(port, { ownerToken });
61
+ try {
62
+ if (!readManagedStateForPort(port)?.extensionDebugging) {
63
+ throw new Error('Extension loading requires a browser started with --extension-debugging or --extension');
64
+ }
65
+ // Chrome reloads an existing unpacked extension at the same path, retaining its ID and storage.
66
+ // Do not uninstall as part of an update: uninstalling destroys the extension settings.
67
+ const id = await browser.installExtension(path);
68
+ const workerVerified = Boolean(manifest.background?.service_worker);
69
+ if (workerVerified && !await extensionWorkerStarted(browser, { id, version: manifest.version, timeout })) {
70
+ throw new Error(`Extension ${manifest.name} ${manifest.version} was loaded, but its service worker did not start within ${timeout}ms. Check the worker script for errors, then update again.`);
71
+ }
72
+ return { id, name: manifest.name, version: manifest.version, directory: path, workerVerified };
73
+ } finally {
74
+ await browser.disconnect();
75
+ }
76
+ }
77
+
78
+ export async function main(args = process.argv.slice(2)) {
79
+ const [command, directory, ...options] = args;
80
+ if (!command || command === '--help' || command === '-h') {
81
+ console.error('Usage: browser-tools extensions load|update <trusted-unpacked-directory> --port <n> [--owner-token <token>]\nUpdate reloads the same directory without uninstalling, retaining extension identity and settings.\nRequires start --extension-debugging (or start --extension <directory>).');
82
+ return command ? 0 : 1;
83
+ }
84
+ if (!['load', 'update'].includes(command)) throw new Error(`Unknown extensions command: ${command}`);
85
+ const result = await loadManagedExtension({ directory, port: parsePort(options), ownerToken: parseOwnerToken(options) });
86
+ console.log(JSON.stringify(result, null, 2));
87
+ return 0;
88
+ }
89
+
90
+ if (process.argv[1] && realpathSync(process.argv[1]) === fileURLToPath(import.meta.url)) {
91
+ try { process.exitCode = await main(); }
92
+ catch (error) { console.error(`✗ ${error.message}`); process.exitCode = 1; }
93
+ }
package/scripts/nav.mjs CHANGED
@@ -6,19 +6,28 @@
6
6
  * scripts/nav.mjs https://example.com
7
7
  * scripts/nav.mjs https://example.com --new
8
8
  * scripts/nav.mjs https://example.com --port 9223
9
+ * scripts/nav.mjs https://example.com --viewport 375x667 --mobile
9
10
  * scripts/nav.mjs https://example.com --owner-token "$BROWSER_TOOLS_OWNER_TOKEN"
10
11
  */
11
12
 
12
13
  import { activePage, hasFlag, parseOwnerToken, parsePort, withBrowser } from './browser-control.mjs';
14
+ import { parseViewport, withViewport } from './viewport.mjs';
13
15
 
14
16
  const args = process.argv.slice(2);
15
17
  const url = args.find((a) => a.startsWith('http') || a.startsWith('file'));
16
18
  const newTab = hasFlag(args, '--new');
17
19
  const port = parsePort(args);
18
20
  const ownerToken = parseOwnerToken(args);
21
+ let viewport;
22
+ try {
23
+ viewport = parseViewport(args);
24
+ } catch (error) {
25
+ console.error(`✗ ${error.message}`);
26
+ process.exit(1);
27
+ }
19
28
 
20
29
  if (!url) {
21
- console.log('Usage: scripts/nav.mjs <url> [--new] [--port <n>]');
30
+ console.log('Usage: scripts/nav.mjs <url> [--new] [--port <n>] [--viewport <width>x<height> [--mobile] [--scale <n>]]');
22
31
  console.log(' scripts/nav.mjs https://example.com');
23
32
  console.log(' scripts/nav.mjs https://example.com --new');
24
33
  process.exit(1);
@@ -27,12 +36,12 @@ if (!url) {
27
36
  await withBrowser(port, async (browser) => {
28
37
  if (newTab) {
29
38
  const page = await browser.newPage({ background: true });
30
- await page.goto(url, { waitUntil: 'domcontentloaded' });
39
+ await withViewport(page, viewport, () => page.goto(url, { waitUntil: 'domcontentloaded' }));
31
40
  console.log(`✓ Opened new tab: ${url}`);
32
41
  return;
33
42
  }
34
43
 
35
44
  const page = await activePage(browser);
36
- await page.goto(url, { waitUntil: 'domcontentloaded' });
45
+ await withViewport(page, viewport, () => page.goto(url, { waitUntil: 'domcontentloaded' }));
37
46
  console.log(`✓ Navigated to: ${url}`);
38
47
  }, { ownerToken });
@@ -1,25 +1,40 @@
1
1
  #!/usr/bin/env node
2
2
  /**
3
- * Take a screenshot of the active tab's viewport.
3
+ * Take a screenshot of the active tab's viewport, full page, or one element.
4
4
  * Prints the file path so the agent can read it.
5
5
  *
6
6
  * Usage:
7
7
  * scripts/screenshot.mjs
8
8
  * scripts/screenshot.mjs --port 9223
9
9
  * scripts/screenshot.mjs --full
10
+ * scripts/screenshot.mjs --viewport 375x667 --mobile
11
+ * scripts/screenshot.mjs --viewport 375x667 --scale 2 --selector 'table.results'
10
12
  * scripts/screenshot.mjs --owner-token "$BROWSER_TOOLS_OWNER_TOKEN"
11
13
  */
12
14
 
13
- import { activePage, hasFlag, parseOwnerToken, parsePort, timestampedTmpPath, withBrowser } from './browser-control.mjs';
15
+ import { writeFileSync } from 'node:fs';
16
+ import { activePage, hasFlag, parseOwnerToken, parsePort, requiredOptionValue, timestampedTmpPath, withBrowser } from './browser-control.mjs';
17
+ import { capturePage, parseViewport, pngSize } from './viewport.mjs';
14
18
 
15
- const args = process.argv.slice(2);
16
- const port = parsePort(args);
17
- const ownerToken = parseOwnerToken(args);
18
- const fullPage = hasFlag(args, '--full');
19
+ try {
20
+ const args = process.argv.slice(2);
21
+ const port = parsePort(args);
22
+ const ownerToken = parseOwnerToken(args);
23
+ const fullPage = hasFlag(args, '--full');
24
+ const selector = requiredOptionValue(args, '--selector', null);
25
+ const viewport = parseViewport(args);
26
+ if (fullPage && selector) throw new Error('Use only one of --full or --selector');
19
27
 
20
- await withBrowser(port, async (browser) => {
21
- const page = await activePage(browser);
22
- const filepath = timestampedTmpPath('browser-screenshot', 'png');
23
- await page.screenshot({ path: filepath, fullPage });
24
- console.log(filepath);
25
- }, { ownerToken });
28
+ await withBrowser(port, async (browser) => {
29
+ const page = await activePage(browser);
30
+ const filepath = timestampedTmpPath('browser-screenshot', 'png');
31
+ const image = await capturePage(page, { viewport, fullPage, selector });
32
+ writeFileSync(filepath, image);
33
+ const { width, height } = pngSize(image);
34
+ console.error(`${width}x${height} px`);
35
+ console.log(filepath);
36
+ }, { ownerToken });
37
+ } catch (error) {
38
+ console.error(`✗ ${error.message}`);
39
+ process.exitCode = 1;
40
+ }
package/scripts/start.mjs CHANGED
@@ -13,7 +13,8 @@
13
13
  * BROWSER_TOOLS_OWNER_TOKEN="<owner token>" scripts/start.mjs
14
14
  */
15
15
 
16
- import { CLI_OWNER_ID, hasFlag, requiredOptionValue, parseOwnerId, parseOwnerToken, parsePort, startChrome } from './browser-control.mjs';
16
+ import { CLI_OWNER_ID, hasFlag, requiredOptionValue, parseOwnerId, parseOwnerToken, parsePort, startChrome, stopChrome } from './browser-control.mjs';
17
+ import { extensionDirectory, loadManagedExtension } from './extensions.mjs';
17
18
 
18
19
  const args = process.argv.slice(2);
19
20
  const profileName = requiredOptionValue(args, '--profile', null);
@@ -26,8 +27,18 @@ const port = parsePort(args);
26
27
  const ownerToken = parseOwnerToken(args);
27
28
  const ownerId = parseOwnerId(args) || CLI_OWNER_ID;
28
29
 
30
+ let result;
29
31
  try {
30
- const result = await startChrome({ port, profileName, taskName, forceProfileSync, autoAllocatePort: !explicitPort, ownerToken, ownerId, headless, includeGoogle });
32
+ const extensions = [];
33
+ for (let i = 0; i < args.length; i++) {
34
+ if (args[i] === '--extension') extensions.push(extensionDirectory(args[++i]).path);
35
+ }
36
+ const extensionDebugging = hasFlag(args, '--extension-debugging') || extensions.length > 0;
37
+ result = await startChrome({ port, profileName, taskName, forceProfileSync, autoAllocatePort: !explicitPort, ownerToken, ownerId, headless, includeGoogle, extensionDebugging });
38
+ for (const directory of extensions) {
39
+ const extension = await loadManagedExtension({ directory, port: result.port, ownerToken: result.ownerToken });
40
+ console.log(`✓ Extension ${extension.name} ${extension.version} loaded (${extension.id}; worker verified: ${extension.workerVerified})`);
41
+ }
31
42
  const mode = result.headless ? ' (headless)' : '';
32
43
  if (result.status === 'reused') {
33
44
  console.log(`✓ Chrome already running on :${result.port}${mode}; reusing owned instance`);
@@ -44,6 +55,8 @@ try {
44
55
  console.log(`Use with follow-up commands: --port ${result.port}`);
45
56
  }
46
57
  } catch (e) {
58
+ // A failed initial extension load must not leave a new browser behind. Do not stop a reused session.
59
+ if (result?.status === 'started') stopChrome({ port: result.port, ownerToken: result.ownerToken, clean: true });
47
60
  console.error(`✗ ${e.message}`);
48
61
  process.exit(1);
49
62
  }
@@ -0,0 +1,150 @@
1
+ /**
2
+ * Screen-size options shared by the commands that look at a page.
3
+ *
4
+ * Chrome keeps an emulated screen size only while the CDP session that set it stays attached, and
5
+ * every CLI command is its own session. So the size is applied inside the command that needs it,
6
+ * on a session held for exactly that long. Puppeteer's page.setViewport is avoided on purpose: it
7
+ * reloads the page whenever the mobile flag changes, which would throw away the state of the tab.
8
+ */
9
+
10
+ const VIEWPORT_OPTIONS_WITH_VALUES = new Set(['--viewport', '--scale']);
11
+ const VIEWPORT_FLAGS = new Set(['--mobile']);
12
+
13
+ // Accepts a Buffer or the Uint8Array that Puppeteer returns from screenshot().
14
+ export function pngSize(bytes) {
15
+ const buffer = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
16
+ if (buffer.length < 24 || buffer.toString('latin1', 1, 4) !== 'PNG') throw new Error('Not a PNG image');
17
+ return { width: buffer.readUInt32BE(16), height: buffer.readUInt32BE(20) };
18
+ }
19
+
20
+ function optionValue(args, name) {
21
+ const i = args.indexOf(name);
22
+ if (i === -1) return null;
23
+ const value = args[i + 1];
24
+ if (value === undefined || value.startsWith('--')) throw new Error(`Missing value after ${name}`);
25
+ return value;
26
+ }
27
+
28
+ export function parseViewport(args) {
29
+ const size = optionValue(args, '--viewport');
30
+ const scale = optionValue(args, '--scale');
31
+ const isMobile = args.includes('--mobile');
32
+ if (size === null) {
33
+ if (isMobile || scale !== null) throw new Error('--mobile and --scale need --viewport <width>x<height>');
34
+ return null;
35
+ }
36
+ const match = /^([1-9]\d{0,4})x([1-9]\d{0,4})$/.exec(size);
37
+ if (!match) throw new Error(`Invalid --viewport value: ${size}. Expected <width>x<height>, for example 375x667`);
38
+ const deviceScaleFactor = scale === null ? 1 : Number(scale);
39
+ if (!(deviceScaleFactor > 0 && deviceScaleFactor <= 8)) throw new Error(`Invalid --scale value: ${scale}. Expected a number from 0 (exclusive) to 8`);
40
+ return { width: Number(match[1]), height: Number(match[2]), deviceScaleFactor, mobile: isMobile };
41
+ }
42
+
43
+ export function stripViewportArgs(args) {
44
+ const stripped = [];
45
+ for (let i = 0; i < args.length; i += 1) {
46
+ if (VIEWPORT_OPTIONS_WITH_VALUES.has(args[i])) i += 1;
47
+ else if (!VIEWPORT_FLAGS.has(args[i])) stripped.push(args[i]);
48
+ }
49
+ return stripped;
50
+ }
51
+
52
+ const windowSize = page => page.evaluate(() => `${innerWidth}x${innerHeight}`);
53
+
54
+ // Chrome does not draw a hidden tab, and without a drawn frame the page keeps the size it was last
55
+ // given, so clearing the override is not enough there. Capturing one pixel makes Chrome draw.
56
+ async function restoreSize(page, session, original) {
57
+ for (let attempt = 0; attempt < 20; attempt += 1) {
58
+ if (await windowSize(page) === original) return;
59
+ await session.send('Page.captureScreenshot', { format: 'jpeg', quality: 1, clip: { x: 0, y: 0, width: 1, height: 1, scale: 1 } });
60
+ await new Promise(resolve => setTimeout(resolve, 50));
61
+ }
62
+ throw new Error(`The page did not return to its own size (${original}) after the screen size was cleared. It is still ${await windowSize(page)}`);
63
+ }
64
+
65
+ // Runs the callback with a CDP session that holds the requested size, or no size at all.
66
+ async function withSession(page, viewport, callback) {
67
+ const session = await page.createCDPSession();
68
+ let original = null;
69
+ let failed = true;
70
+ try {
71
+ if (viewport) {
72
+ original = await windowSize(page);
73
+ await session.send('Emulation.setDeviceMetricsOverride', viewport);
74
+ if (viewport.mobile) await session.send('Emulation.setTouchEmulationEnabled', { enabled: true });
75
+ }
76
+ const result = await callback(session);
77
+ failed = false;
78
+ return result;
79
+ } finally {
80
+ // Detaching drops the overrides, but not always before the next command looks at the page.
81
+ if (viewport?.mobile) await session.send('Emulation.setTouchEmulationEnabled', { enabled: false }).catch(() => {});
82
+ if (viewport) await session.send('Emulation.clearDeviceMetricsOverride').catch(() => {});
83
+ // A size that outlives its command is the silent failure this module exists to prevent, so it
84
+ // is an error. It must not replace the error of a command that already failed.
85
+ const restored = original === null ? null : await restoreSize(page, session, original).then(() => null, error => error);
86
+ await session.detach().catch(() => {});
87
+ if (restored && !failed) throw restored;
88
+ }
89
+ }
90
+
91
+ export async function withViewport(page, viewport, callback) {
92
+ if (!viewport) return callback();
93
+ return withSession(page, viewport, () => callback());
94
+ }
95
+
96
+ // Captures the viewport, the full page, or one element as PNG bytes, at the requested size.
97
+ //
98
+ // The capture is sent on the same session that holds the size. A capture sent on another session,
99
+ // which is what page.screenshot() does, honours the width but not the scale. The element is located
100
+ // by its position and captured beyond the viewport, because Puppeteer's element capture first waits
101
+ // for an IntersectionObserver that never fires on a background tab.
102
+ export async function capturePage(page, { viewport = null, fullPage = false, selector = null } = {}) {
103
+ if (fullPage && selector) throw new Error('Use only one of --full or --selector');
104
+ return withSession(page, viewport, async (session) => {
105
+ const layoutWidth = () => page.evaluate(() => innerWidth);
106
+ const before = viewport ? await layoutWidth() : null;
107
+ let clip = null;
108
+ if (selector) {
109
+ const box = await page.evaluate((query) => {
110
+ const node = document.querySelector(query);
111
+ if (!node) return null;
112
+ const rect = node.getBoundingClientRect();
113
+ return { x: rect.x + scrollX, y: rect.y + scrollY, width: rect.width, height: rect.height };
114
+ }, selector);
115
+ if (!box) throw new Error(`No element matches ${selector}`);
116
+ if (!(box.width > 0 && box.height > 0)) throw new Error(`Element ${selector} has no visible size`);
117
+ clip = { ...box, scale: 1 };
118
+ }
119
+ // A full-page capture has no clip: Chrome then captures the whole document, without the scrollbar gutter.
120
+ // Chrome drops the page's scrollbar for a capture beyond the viewport and does not bring it back.
121
+ // That is left alone: restoring it takes a resize the page can see.
122
+ const { data } = await session.send('Page.captureScreenshot', {
123
+ format: 'png', ...(clip ? { clip } : {}), captureBeyondViewport: Boolean(clip || fullPage),
124
+ });
125
+ const image = Buffer.from(data, 'base64');
126
+ // A capture at the wrong size looks plausible and misleads every measurement taken from it,
127
+ // so the requested size must still hold after the capture and must show in the image.
128
+ const after = viewport ? await layoutWidth() : null;
129
+ if (after !== before) throw new Error(`The page width changed from ${before} to ${after} px during the capture`);
130
+ const actual = pngSize(image);
131
+ const expected = expectedImageSize(viewport, { fullPage, selector });
132
+ if (expected && (actual.width !== expected.width || actual.height !== expected.height)) {
133
+ throw new Error(`Screenshot is ${actual.width}x${actual.height}, but --viewport asked for ${expected.width}x${expected.height}`);
134
+ }
135
+ return image;
136
+ });
137
+ }
138
+
139
+ // What the image must measure when the request fixes its size. A full-page or element capture is as
140
+ // large as its content, so only a plain viewport capture has a size to hold it to.
141
+ export function expectedImageSize(viewport, { fullPage = false, selector = null } = {}) {
142
+ if (!viewport || fullPage || selector) return null;
143
+ return {
144
+ width: Math.round(viewport.width * viewport.deviceScaleFactor),
145
+ height: Math.round(viewport.height * viewport.deviceScaleFactor),
146
+ };
147
+ }
148
+
149
+ export const SESSION_SCOPED_NOTE = 'Note: an Emulation override ends with this command, because Chrome drops it when the CDP session that set it detaches. '
150
+ + 'For a screen size, pass --viewport <width>x<height> [--mobile] [--scale <n>] to screenshot, eval, or nav instead.';