@rezkam/browser-tools 1.1.1 → 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 +14 -0
- package/README.md +31 -2
- package/bin/browser-tools.mjs +2 -0
- package/package.json +4 -3
- package/scripts/browser-control.mjs +21 -7
- package/scripts/extensions.mjs +93 -0
- package/scripts/start.mjs +15 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,19 @@
|
|
|
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
|
+
|
|
11
|
+
## 1.1.2
|
|
12
|
+
|
|
13
|
+
### Patch Changes
|
|
14
|
+
|
|
15
|
+
- b8a738f: Headless launches no longer report automation or Chrome's default 800x600 screen. They disable the `AutomationControlled` Blink feature so `navigator.webdriver` is false, and present a 1920x1080 screen with a 1920x1040 window, so bot defenses that reject those headless signals treat the browser like a windowed one.
|
|
16
|
+
|
|
3
17
|
## 1.1.1
|
|
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
|
|
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.
|
package/bin/browser-tools.mjs
CHANGED
|
@@ -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": "
|
|
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": ">=
|
|
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": "
|
|
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 = [
|
|
@@ -1027,7 +1027,10 @@ export function chromeLaunchArgs({ port = DEFAULT_PORT, profileName = null, mana
|
|
|
1027
1027
|
];
|
|
1028
1028
|
// New headless runs the full browser (extensions and the copied profile still load) without opening
|
|
1029
1029
|
// a window. Old --headless is a separate lightweight engine that ignores extensions, so keep =new.
|
|
1030
|
-
|
|
1030
|
+
// Bot defenses reject navigator.webdriver and headless Chrome's default 800x600 screen, so a
|
|
1031
|
+
// headless launch hides the automation flag and reports a common desktop display.
|
|
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');
|
|
1031
1034
|
// A headless launch otherwise advertises a "HeadlessChrome" User-Agent. When the copied profile is
|
|
1032
1035
|
// signed in to Google, that headless fingerprint trips Google's session-theft protection and logs the
|
|
1033
1036
|
// source profile out, while a windowed launch (normal Chrome UA) does not. Present the normal UA so a
|
|
@@ -1516,6 +1519,7 @@ export function managedBrowserReuseDecision({
|
|
|
1516
1519
|
profileName = null,
|
|
1517
1520
|
headless = false,
|
|
1518
1521
|
forceProfileSync = false,
|
|
1522
|
+
extensionDebugging = false,
|
|
1519
1523
|
}) {
|
|
1520
1524
|
if (!safety?.ok) return { ok: false, reason: safety?.reason || 'missing-managed-state' };
|
|
1521
1525
|
const ownership = managedBrowserOwnershipSafety({ state, ownerToken });
|
|
@@ -1533,6 +1537,7 @@ export function managedBrowserReuseDecision({
|
|
|
1533
1537
|
if (profileName && (!state.profileSourceDir || resolve(state.profileSourceDir) !== resolve(browserToolsChromeSourceDir()))) return fail('profile-source-mismatch');
|
|
1534
1538
|
// Headless is fixed at launch, so a windowed request cannot be served by a headless browser.
|
|
1535
1539
|
if (Boolean(state?.headless) !== Boolean(headless)) return fail('headless-mismatch');
|
|
1540
|
+
if (Boolean(state?.extensionDebugging) !== Boolean(extensionDebugging)) return fail('extension-debugging-mismatch');
|
|
1536
1541
|
return { ok: true, ownerId: ownership.ownerId, state };
|
|
1537
1542
|
}
|
|
1538
1543
|
|
|
@@ -1545,6 +1550,7 @@ export function findReusableManagedBrowser({
|
|
|
1545
1550
|
profileName = null,
|
|
1546
1551
|
headless = false,
|
|
1547
1552
|
forceProfileSync = false,
|
|
1553
|
+
extensionDebugging = false,
|
|
1548
1554
|
processes = listManagedChromeProcesses(),
|
|
1549
1555
|
} = {}) {
|
|
1550
1556
|
if (!normalizeOwnerValue(ownerToken)) return null;
|
|
@@ -1553,7 +1559,7 @@ export function findReusableManagedBrowser({
|
|
|
1553
1559
|
const state = readManagedState(stateFileForPort(entry.port));
|
|
1554
1560
|
if (!state || Number(state.pid) !== Number(entry.pid)) continue;
|
|
1555
1561
|
const decision = managedBrowserReuseDecision({
|
|
1556
|
-
safety: { ok: true }, state, ownerToken, includeGoogle, profileName, headless, forceProfileSync,
|
|
1562
|
+
safety: { ok: true }, state, ownerToken, includeGoogle, profileName, headless, forceProfileSync, extensionDebugging,
|
|
1557
1563
|
});
|
|
1558
1564
|
if (decision.ok) return { ...entry, state };
|
|
1559
1565
|
}
|
|
@@ -1621,7 +1627,7 @@ function launchHeadlessChromeApp({ chromeBin, args }) {
|
|
|
1621
1627
|
return { pid };
|
|
1622
1628
|
}
|
|
1623
1629
|
|
|
1624
|
-
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 } = {}) {
|
|
1625
1631
|
ensureCacheDir();
|
|
1626
1632
|
const normalizedPort = normalizePort(port);
|
|
1627
1633
|
const launchUserDataDir = userDataDir || (profileName ? profileDataDirForPort(normalizedPort) : freshProfileDirForPort(normalizedPort));
|
|
@@ -1629,7 +1635,7 @@ export function launchChrome({ port = DEFAULT_PORT, profileName = null, userData
|
|
|
1629
1635
|
const effectiveOwnerToken = normalizeOwnerValue(ownerToken) || generateOwnerToken();
|
|
1630
1636
|
const chromeBin = browserToolsChromeBin();
|
|
1631
1637
|
const userAgent = headless ? headlessUserAgent(chromeBin) : null;
|
|
1632
|
-
const args = chromeLaunchArgs({ port: normalizedPort, profileName, managedToken, userDataDir: launchUserDataDir, headless, userAgent });
|
|
1638
|
+
const args = chromeLaunchArgs({ port: normalizedPort, profileName, managedToken, userDataDir: launchUserDataDir, headless, userAgent, extensionDebugging });
|
|
1633
1639
|
// A stale marker must not make a later launch appear to own a competing endpoint.
|
|
1634
1640
|
rmSync(join(launchUserDataDir, 'DevToolsActivePort'), { force: true });
|
|
1635
1641
|
assertChromeBinaryLaunchable(chromeBin);
|
|
@@ -1666,6 +1672,7 @@ export function launchChrome({ port = DEFAULT_PORT, profileName = null, userData
|
|
|
1666
1672
|
userDataDir: launchUserDataDir,
|
|
1667
1673
|
headless: Boolean(headless),
|
|
1668
1674
|
includeGoogle: Boolean(includeGoogle),
|
|
1675
|
+
extensionDebugging: Boolean(extensionDebugging),
|
|
1669
1676
|
managedToken,
|
|
1670
1677
|
...buildOwnerState({ ownerToken: effectiveOwnerToken, ownerId }),
|
|
1671
1678
|
// Who launched this browser, so a leaked one is attributable instead of anonymous.
|
|
@@ -1709,6 +1716,7 @@ export async function startChrome({
|
|
|
1709
1716
|
ownerId = null,
|
|
1710
1717
|
headless = false,
|
|
1711
1718
|
includeGoogle = false,
|
|
1719
|
+
extensionDebugging = false,
|
|
1712
1720
|
} = {}) {
|
|
1713
1721
|
let normalizedPort = normalizePort(port);
|
|
1714
1722
|
const providedOwnerToken = normalizeOwnerValue(ownerToken);
|
|
@@ -1749,7 +1757,7 @@ export async function startChrome({
|
|
|
1749
1757
|
if (providedOwnerToken) {
|
|
1750
1758
|
const candidates = autoAllocatePort ? liveBrowsers : liveBrowsers.filter((entry) => entry.port === normalizedPort);
|
|
1751
1759
|
const found = findReusableManagedBrowser({
|
|
1752
|
-
ownerToken: providedOwnerToken, includeGoogle, processes: candidates,
|
|
1760
|
+
ownerToken: providedOwnerToken, includeGoogle, extensionDebugging, processes: candidates,
|
|
1753
1761
|
profileName: resolvedProfileName, headless, forceProfileSync,
|
|
1754
1762
|
});
|
|
1755
1763
|
const foundEndpoint = found ? await browserWSEndpoint(found.port) : null;
|
|
@@ -1792,7 +1800,7 @@ export async function startChrome({
|
|
|
1792
1800
|
const safety = managedBrowserSafetyForPort(normalizedPort);
|
|
1793
1801
|
const state = readManagedStateForPort(normalizedPort);
|
|
1794
1802
|
const reuse = managedBrowserReuseDecision({
|
|
1795
|
-
safety, state, ownerToken: providedOwnerToken, includeGoogle,
|
|
1803
|
+
safety, state, ownerToken: providedOwnerToken, includeGoogle, extensionDebugging,
|
|
1796
1804
|
profileName: resolvedProfileName, headless, forceProfileSync,
|
|
1797
1805
|
});
|
|
1798
1806
|
// Reuse first, on both paths. An auto-allocated start used to skip this entirely and walk to
|
|
@@ -1834,6 +1842,9 @@ export async function startChrome({
|
|
|
1834
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.`,
|
|
1835
1843
|
);
|
|
1836
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
|
+
}
|
|
1837
1848
|
if (reuse.reason === 'sync-requested') {
|
|
1838
1849
|
throw new Error(
|
|
1839
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.`,
|
|
@@ -1918,6 +1929,7 @@ export async function startChrome({
|
|
|
1918
1929
|
serializedReuse = findReusableManagedBrowser({
|
|
1919
1930
|
ownerToken: providedOwnerToken,
|
|
1920
1931
|
includeGoogle,
|
|
1932
|
+
extensionDebugging,
|
|
1921
1933
|
profileName: resolvedProfileName,
|
|
1922
1934
|
headless,
|
|
1923
1935
|
forceProfileSync,
|
|
@@ -1939,6 +1951,7 @@ export async function startChrome({
|
|
|
1939
1951
|
ownerId: normalizedOwnerId,
|
|
1940
1952
|
headless,
|
|
1941
1953
|
includeGoogle,
|
|
1954
|
+
extensionDebugging,
|
|
1942
1955
|
});
|
|
1943
1956
|
}
|
|
1944
1957
|
} finally {
|
|
@@ -1957,6 +1970,7 @@ export async function startChrome({
|
|
|
1957
1970
|
state,
|
|
1958
1971
|
ownerToken: providedOwnerToken,
|
|
1959
1972
|
includeGoogle,
|
|
1973
|
+
extensionDebugging,
|
|
1960
1974
|
profileName: resolvedProfileName,
|
|
1961
1975
|
headless,
|
|
1962
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
|
|
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
|
}
|