@rezkam/browser-tools 1.1.2 → 2.0.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,13 @@
1
1
  # @rezkam/browser-tools
2
2
 
3
+ ## 2.0.0
4
+
5
+ ### Major Changes
6
+
7
+ - 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.
8
+
9
+ 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.
10
+
3
11
  ## 1.1.2
4
12
 
5
13
  ### 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,6 +72,7 @@ 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
77
  | Page control | `nav`, `eval`, `screenshot` | Navigate the active tab or a new background tab, run page JavaScript, and capture PNG screenshots |
77
78
  | DOM inspection | `pick` | Select one or more visible elements and return tag, id, class, text, HTML, and parent information |
@@ -97,15 +98,43 @@ 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
+
109
138
  ### Shared tabs
110
139
 
111
140
  `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.
@@ -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.0.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,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
+ "./extensions.mjs": "./scripts/extensions.mjs",
25
26
  "./tab-broker.mjs": "./scripts/tab-broker.mjs",
26
27
  "./package.json": "./package.json"
27
28
  },
@@ -42,7 +43,7 @@
42
43
  "validate": "npm test && npm run test:e2e"
43
44
  },
44
45
  "dependencies": {
45
- "puppeteer-core": "^24.42.0",
46
+ "puppeteer-core": "npm:rebrowser-puppeteer-core@25.16.0",
46
47
  "ws": "^8.22.0"
47
48
  },
48
49
  "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,
@@ -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/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
  }