@liqi0816/chrome-devtools-mcp-rebrowser 1.0.2 → 1.0.4

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/README.md CHANGED
@@ -18,7 +18,6 @@ Code is MIT. What license applies to human-AI conversation transcripts is an ope
18
18
 
19
19
  - **Node.js** ≥ 20.19.0 LTS
20
20
  - **Chrome** running with remote debugging enabled (go to `chrome://inspect/#remote-debugging`)
21
- - **Git** installed (provides `patch.exe` on Windows, needed for applying patches)
22
21
 
23
22
  ### Usage via `npx` (recommended)
24
23
 
@@ -83,7 +82,7 @@ Then configure the MCP server to use the local entry point:
83
82
 
84
83
  ## How It Works
85
84
 
86
- `chrome-devtools-mcp` is Google's official MCP server for Chrome DevTools. It bundles its own copy of Puppeteer (v24.39.1) internally. This project intercepts its `puppeteer.connect()` and `puppeteer.launch()` calls and redirects them through a separately installed, rebrowser-patched version of `puppeteer-core`.
85
+ `chrome-devtools-mcp` is Google's official MCP server for Chrome DevTools. It bundles its own copy of Puppeteer internally. This project intercepts its `puppeteer.connect()` and `puppeteer.launch()` calls and redirects them through a separately installed, rebrowser-patched version of `puppeteer-core`.
87
86
 
88
87
  ### Architecture
89
88
 
@@ -91,10 +90,10 @@ Then configure the MCP server to use the local entry point:
91
90
  launch.mjs (entry point)
92
91
  │
93
92
  ├─ Imports patched puppeteer-core (node_modules/puppeteer-core)
94
- │ └─ puppeteer-core@24.39.1 + rebrowser-patches applied
93
+ │ └─ puppeteer-core@25.18.1 + rebrowser-patches applied
95
94
  │
96
95
  ├─ Imports bundled puppeteer from chrome-devtools-mcp
97
- │ └─ node_modules/chrome-devtools-mcp/build/src/third_party/index.js
96
+ │ └─ node_modules/chrome-devtools-mcp/out/Default/gen/src/third_party/browser.js
98
97
  │
99
98
  ├─ Monkey-patches bundled puppeteer's connect()/launch() methods
100
99
  │ to redirect through the patched puppeteer-core
@@ -103,11 +102,14 @@ launch.mjs (entry point)
103
102
 
104
103
  postinstall.mjs (runs after npm install)
105
104
  │
106
- ├─ Applies rebrowser-patches to puppeteer-core (with --fuzz=10)
105
+ ├─ Applies rebrowser-patches to puppeteer-core (with --fuzz=10), using
106
+ │ the closest patch set rebrowser-patches ships + local per-file
107
+ │ overrides from patches/puppeteer-core/<version>/lib.patch
107
108
  │
108
- └─ Applies DevToolsConnectionAdapter.js patch to chrome-devtools-mcp
109
+ └─ Injects a Runtime.enable guard into the DevToolsConnectionAdapter
110
+ bundled in chrome-devtools-mcp's third_party/browser.js
109
111
 
110
- DevToolsConnectionAdapter.js (patched)
112
+ DevToolsConnectionAdapter (patched, inside third_party/browser.js)
111
113
  │
112
114
  └─ Blocks Runtime.enable calls from DevTools Universe models
113
115
  to prevent CDP detection via the separate CDP session
@@ -115,9 +117,19 @@ DevToolsConnectionAdapter.js (patched)
115
117
 
116
118
  ### Why the Monkey-Patching?
117
119
 
118
- - `chrome-devtools-mcp` bundles Puppeteer in a single rollup file (`third_party/index.js`), so you can't simply swap out `puppeteer-core` via `package.json`.
119
- - `rebrowser-puppeteer` (the drop-in replacement) is only available up to v24.8.1, but `chrome-devtools-mcp@0.20.3` requires Puppeteer v24.39.1 APIs (e.g., `page.emulateFocusedPage()`).
120
- - Solution: install `puppeteer-core@24.39.1` separately, apply `rebrowser-patches` to it, then redirect the bundled Puppeteer's calls through the patched version.
120
+ - `chrome-devtools-mcp` bundles Puppeteer in a single minified file (`third_party/browser.js`), so you can't simply swap out `puppeteer-core` via `package.json`.
121
+ - `rebrowser-puppeteer` (the drop-in replacement) is only available up to v24.8.1, but recent `chrome-devtools-mcp` releases require newer Puppeteer APIs (e.g., `page.emulateFocusedPage()` from v24.39+).
122
+ - Solution: install a compatible `puppeteer-core` separately, apply `rebrowser-patches` to it, then redirect the bundled Puppeteer's calls through the patched version.
123
+
124
+ ### Why `puppeteer-core` and `rebrowser-patches` are pinned to exact versions
125
+
126
+ You'll see `"puppeteer-core": "25.18.1"` and `"rebrowser-patches": "1.1.3"` (no caret) in `package.json`. This is deliberate — these two **must** move in lockstep:
127
+
128
+ `rebrowser-patches` is a set of **line-by-line unified diffs** against puppeteer-core's compiled output. Any upstream puppeteer-core release can add/remove lines near a hunk and make the patch stop applying — even patch-level releases. For example, `rebrowser-patches@1.0.19` was cut against puppeteer-core 24.40.x, and newer puppeteer-core (24.41+) adds fields to `IsolatedWorld.js` that break hunks (see [issue #4](https://github.com/liqi0816/chrome-devtools-mcp-rebrowser/issues/4)). Conversely, a newer `rebrowser-patches` release could target a different puppeteer-core line layout and stop applying to 24.40.0.
129
+
130
+ Since 1.1, `rebrowser-patches` ships one patch set per tested puppeteer-core version (`patches/puppeteer-core/<version>/lib.patch`); `postinstall.mjs` picks one with the same logic as rebrowser's own CLI (exact → newest same major.minor → newest overall). When the pinned puppeteer-core is newer than anything rebrowser has tested, files whose hunks no longer apply are re-anchored in this repo's `patches/puppeteer-core/<version>/lib.patch`, which replaces the upstream hunk for those files only. Currently puppeteer-core 25.18.1 uses rebrowser's 25.16.0 set plus local overrides for `cdp/WebWorker.js` and `cdp/utils.js`. The same file also carries one addition rebrowser doesn't have: a `cdp/Page.js` patch that restores console message collection (see [Console messages](#console-messages)).
131
+
132
+ Both pins are bumped together whenever a new `rebrowser-patches` release catches up to a newer puppeteer-core. The remaining dependencies (`chrome-devtools-mcp`, `diff`) still float on `^` ranges because their APIs are stable and the patches we apply use fuzzy matching.
121
133
 
122
134
  ## Flags
123
135
 
@@ -154,9 +166,9 @@ You can fine-tune the anti-detection patches:
154
166
 
155
167
  4. **Browser `_connection()` method** — Exposes the CDP connection for advanced use cases (not detectable by websites).
156
168
 
157
- ### DevToolsConnectionAdapter.js (applied to chrome-devtools-mcp)
169
+ ### DevToolsConnectionAdapter (applied to chrome-devtools-mcp)
158
170
 
159
- 5. **DevTools Universe `Runtime.Enable` leak** — Even with rebrowser-patches applied to puppeteer-core, `chrome-devtools-mcp` creates a *separate* CDP session per page via `page.createCDPSession()` in `DevtoolsUtils.js` and feeds it to a DevTools Universe. The Universe's RuntimeModel then calls `Runtime.enable` on that session — completely bypassing the patched puppeteer-core. We patch `DevToolsConnectionAdapter.js` to intercept and block `Runtime.enable` calls in the `send()` method, consistent with how rebrowser-patches handles it inside Puppeteer's FrameManager.
171
+ 5. **DevTools Universe `Runtime.Enable` leak** — Even with rebrowser-patches applied to puppeteer-core, `chrome-devtools-mcp` creates a *separate* CDP session per page via `page.createCDPSession()` in `McpPage.js` and feeds it to a DevTools Universe. The Universe's RuntimeModel then calls `Runtime.enable` on that session — completely bypassing the patched puppeteer-core. We patch the `DevToolsConnectionAdapter` class (bundled into `third_party/browser.js` since chrome-devtools-mcp 1.x) to intercept and block `Runtime.enable` calls in the `send()` method, consistent with how rebrowser-patches handles it inside Puppeteer's FrameManager.
160
172
 
161
173
  ### What the DevTools Universe CDP session is used for
162
174
 
@@ -173,12 +185,28 @@ You can fine-tune the anti-detection patches:
173
185
  Blocking `Runtime.enable` on the Universe session means the `RuntimeModel` won't receive execution context events, which degrades `getExceptionDetails()` (error cause chain resolution in `get_console_message`). However:
174
186
 
175
187
  - **Core MCP tools are unaffected** — `evaluate_script`, page snapshots, navigation, clicking, typing, screenshots all use Puppeteer APIs directly, not the Universe session.
176
- - **Console message collection is unaffected** — `PageCollector` listens on Puppeteer's own CDP session (`page._client()`), not the Universe session.
188
+ - **Console message collection is unaffected by this block** — `PageCollector` listens on Puppeteer's own CDP session (`page._client()`), not the Universe session. It is affected by rebrowser's fix inside puppeteer-core, though; see [Console messages](#console-messages).
177
189
  - **Stack traces from `DebuggerModel` still work** — `Debugger.enable` is not blocked, so source-map-aware stack traces continue to function.
178
190
  - **Only error cause chains degrade** — The recursive `.cause` lookup via `RuntimeModel.getExceptionDetails()` may fail silently, omitting cause details from console error output.
179
191
 
180
192
  This is an acceptable tradeoff since `Runtime.enable` is the primary CDP detection vector used by anti-bot systems.
181
193
 
194
+ ### Console messages
195
+
196
+ Puppeteer builds `page.on('console')` events from `Runtime.consoleAPICalled`, which Chrome only sends after `Runtime.enable`. rebrowser-patches suppresses `Runtime.enable` and does not replace that event source, so with the upstream patches alone `list_console_messages` never sees the page's `console.*` output.
197
+
198
+ This repo's `cdp/Page.js` patch enables the legacy `Console` CDP domain instead and converts its `Console.messageAdded` events into Puppeteer console messages. `Console` forwards the message text Chrome has already built and never serializes the logged arguments, which is the step the `Runtime.enable` leak depends on. Compared with unpatched `chrome-devtools-mcp`:
199
+
200
+ | | Unpatched | This project |
201
+ |---|---|---|
202
+ | `console.log/warn/error/debug` text and level | Yes | Yes |
203
+ | Arguments in `get_console_message` | Structured (`{"a":1}`) | Flattened into the text (`[object Object]`) |
204
+ | Stack trace of the `console.*` call | Yes | No |
205
+ | Uncaught exceptions | Yes | No — the `Console` domain does not report them |
206
+ | Console output from workers | Yes | No |
207
+
208
+ The `Console` domain is marked deprecated in the protocol, so a future Chrome may remove it. Setting `REBROWSER_PATCHES_RUNTIME_FIX_MODE=0` turns the rebrowser fix off and restores the full unpatched behavior (and the leak).
209
+
182
210
  ## Troubleshooting
183
211
 
184
212
  ### "Could not connect to Chrome"
@@ -187,20 +215,17 @@ This is an acceptable tradeoff since `Runtime.enable` is the primary CDP detecti
187
215
  - Check that `DevToolsActivePort` file exists in Chrome's user data directory
188
216
 
189
217
  ### Patch fails with "FAILED" hunks
190
- - If CJS/ESM hunks fail, the puppeteer-core version may have changed too much. Try adjusting the `--fuzz` value or manually applying the changes
218
+ - The installed `puppeteer-core` version drifted past what `rebrowser-patches` knows how to patch. `postinstall.mjs` prints the exact installed versions and a link to [issue #4](https://github.com/liqi0816/chrome-devtools-mcp-rebrowser/issues/4) when this happens. Re-run with `npx -y @liqi0816/chrome-devtools-mcp-rebrowser@latest` — the pinned `puppeteer-core` and `rebrowser-patches` in `package.json` should keep the install reproducible.
191
219
 
192
220
  ### "emulateFocusedPage is not a function" (or similar)
193
- - Version mismatch: ensure `puppeteer-core` in `package.json` matches the version in `chrome-devtools-mcp`'s `devDependencies` (currently `24.39.1`)
194
-
195
- ### Postinstall fails — "`patch` command not found"
196
- - On Linux/macOS: `patch` is usually pre-installed. If not: `sudo apt install patch` or `brew install gpatch`.
197
- - On Windows: Install [Git for Windows](https://gitforwindows.org/) — it bundles `patch.exe` at `C:\Program Files\Git\usr\bin\patch.exe`. Make sure it's on your PATH.
221
+ - Version mismatch: ensure `puppeteer-core` in `package.json` is a version whose API is supported by the bundled Puppeteer inside `chrome-devtools-mcp` (see the Version Compatibility table below).
198
222
 
199
223
  ## Version Compatibility
200
224
 
201
- | Package | Version |
202
- |---------|---------|
203
- | chrome-devtools-mcp | 0.20.3 |
204
- | puppeteer-core | 24.39.1 |
205
- | rebrowser-patches | 1.0.19 |
206
- | Node.js | ≥ 20.19.0 |
225
+ | Package | Version | Pinned? |
226
+ |---------|---------|---------|
227
+ | chrome-devtools-mcp | ^1.14.0 | floats (anchored regex patch) |
228
+ | puppeteer-core | 25.18.1 | **exact** ([why](#why-puppeteer-core-and-rebrowser-patches-are-pinned-to-exact-versions)) |
229
+ | rebrowser-patches | 1.1.3 | **exact** ([why](#why-puppeteer-core-and-rebrowser-patches-are-pinned-to-exact-versions)) |
230
+ | diff | ^9.0.0 | floats |
231
+ | Node.js | ≥ 20.19.0 | — |
package/launch.mjs CHANGED
@@ -8,7 +8,8 @@ const require = createRequire(import.meta.url);
8
8
  // ---------------------------------------------------------------------------
9
9
  // Step 1: Import the patched puppeteer-core
10
10
  // ---------------------------------------------------------------------------
11
- // This is puppeteer-core@24.39.1 with rebrowser-patches applied in-place.
11
+ // This is puppeteer-core (pinned in package.json — currently 25.18.1) with
12
+ // rebrowser-patches applied in-place by postinstall.mjs.
12
13
  // The patches disable Runtime.Enable (the primary CDP detection vector),
13
14
  // change sourceURL from pptr:... to app.js, and rename the utility world.
14
15
  import puppeteerCore from 'puppeteer-core';
@@ -18,7 +19,7 @@ import puppeteerCore from 'puppeteer-core';
18
19
  // ---------------------------------------------------------------------------
19
20
  // ESM modules are cached by resolved URL, so this gives us a reference to the
20
21
  // SAME puppeteer object that browser.js will use when it calls connect()/launch().
21
- import { puppeteer as bundledPuppeteer } from 'chrome-devtools-mcp/build/src/third_party/index.js';
22
+ import { puppeteer as bundledPuppeteer } from 'chrome-devtools-mcp/out/Default/gen/src/third_party/browser.js';
22
23
 
23
24
  bundledPuppeteer.connect = function connect() {
24
25
  process.stderr.write('[rebrowser-patch] Redirecting puppeteer.connect() through patched puppeteer-core\n');
@@ -35,5 +36,5 @@ bundledPuppeteer.launch = function launch() {
35
36
  // ---------------------------------------------------------------------------
36
37
  // This imports and runs chrome-devtools-mcp's main entry point. When it
37
38
  // eventually calls puppeteer.connect() or puppeteer.launch() via
38
- // browser.js → third_party/index.js, it will hit our patched methods above.
39
- await import('chrome-devtools-mcp/build/src/bin/chrome-devtools-mcp.js');
39
+ // BrowserManager.js → loadBrowser() → third_party/browser.js, it will hit our patched methods above.
40
+ await import('chrome-devtools-mcp/out/Default/gen/src/bin/chrome-devtools-mcp.js');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@liqi0816/chrome-devtools-mcp-rebrowser",
3
- "version": "1.0.2",
3
+ "version": "1.0.4",
4
4
  "description": "Chrome DevTools MCP server with rebrowser anti-detection patches — undetectable by Cloudflare, DataDome, and other anti-bot systems",
5
5
  "keywords": [
6
6
  "mcp",
@@ -20,7 +20,7 @@
20
20
  "url": "git+https://github.com/liqi0816/chrome-devtools-mcp-rebrowser.git"
21
21
  },
22
22
  "license": "MIT",
23
- "author": "LI, Qi <goodlq11@gmail.com>",
23
+ "author": "LI, Qi (https://github.com/liqi0816)",
24
24
  "type": "module",
25
25
  "main": "launch.mjs",
26
26
  "bin": {
@@ -35,13 +35,15 @@
35
35
  ],
36
36
  "scripts": {
37
37
  "postinstall": "node postinstall.mjs",
38
- "start": "node launch.mjs"
38
+ "start": "node launch.mjs",
39
+ "smoke-test": "node smoke-test.mjs",
40
+ "prepublishOnly": "npm run smoke-test"
39
41
  },
40
42
  "dependencies": {
41
- "chrome-devtools-mcp": "^0.20.3",
42
- "diff": "^8.0.4",
43
- "puppeteer-core": "^24.40.0",
44
- "rebrowser-patches": "^1.0.19"
43
+ "chrome-devtools-mcp": "^1.14.0",
44
+ "diff": "^9.0.0",
45
+ "puppeteer-core": "25.18.1",
46
+ "rebrowser-patches": "1.1.3"
45
47
  },
46
48
  "publishConfig": {
47
49
  "access": "public"
@@ -0,0 +1,121 @@
1
+ --- a/lib/puppeteer/cdp/WebWorker.js
2
+ +++ b/lib/puppeteer/cdp/WebWorker.js
3
+ @@ -92,6 +92,10 @@
4
+ this.#world = new IsolatedWorld(this, new TimeoutSettings(), MAIN_WORLD, logger);
5
+ this.#emitter = new EventEmitter(undefined, logger);
6
+ this.#client.once('Runtime.executionContextCreated', async (event) => {
7
+ + if (process.env['REBROWSER_PATCHES_RUNTIME_FIX_MODE'] !== '0') {
8
+ + // rebrowser-patches: ignore default logic
9
+ + return;
10
+ + }
11
+ this.#world.setContext(new ExecutionContext(client, event.context, this.#world, logger));
12
+ });
13
+ this.#client.once('Inspector.workerScriptLoaded', () => {
14
+ @@ -145,9 +149,24 @@
15
+ // registers a later Disconnected listener that stops forwarding, so the
16
+ // opposite order would drop those RequestFailed events.
17
+ this.#forwardNetworkEvents(netManager);
18
+ - this.#client.send('Runtime.enable').catch((err) => {
19
+ - return this.#logger?.(DEBUG_PREFIXES.error)?.(err);
20
+ - });
21
+ + if (process.env['REBROWSER_PATCHES_RUNTIME_FIX_MODE'] !== '0') {
22
+ + // @ts-ignore
23
+ + process.env['REBROWSER_PATCHES_DEBUG'] && console.log('[rebrowser-patches][WebWorker] initialize', this.#targetType, this.#id);
24
+ + // rebrowser-patches: manually create context
25
+ + const contextPayload = {
26
+ + id: -3,
27
+ + auxData: {
28
+ + frameId: this.#id,
29
+ + }
30
+ + };
31
+ + // @ts-ignore
32
+ + this.#world.setContext(new ExecutionContext(client, contextPayload, this.#world, this.#logger));
33
+ + }
34
+ + else {
35
+ + this.#client.send('Runtime.enable').catch((err) => {
36
+ + return this.#logger?.(DEBUG_PREFIXES.error)?.(err);
37
+ + });
38
+ + }
39
+ }
40
+ /**
41
+ * Network manager for workers that are not owned by a page (service and
42
+ --- a/lib/puppeteer/cdp/utils.js
43
+ +++ b/lib/puppeteer/cdp/utils.js
44
+ @@ -239,6 +239,9 @@
45
+ /**
46
+ * @internal
47
+ */
48
+ +// rebrowser-patches: without Runtime.enable, Chrome drops CDP bindings when the page navigates
49
+ +// (crbug.com/382473087). The binding is added again when the navigation commits, so a call made before that
50
+ +// waits for it instead of throwing. This function is serialized into the page: keep comments out of its body.
51
+ export function addPageBinding(type, name, prefix) {
52
+ // Depending on the frame loading state either Runtime.evaluate or
53
+ // Page.addScriptToEvaluateOnNewDocument might succeed. Let's check that we
54
+ @@ -259,7 +262,7 @@
55
+ const seq = (callPuppeteer.lastSeq ?? 0) + 1;
56
+ callPuppeteer.lastSeq = seq;
57
+ callPuppeteer.args.set(seq, args);
58
+ - callPuppeteer(JSON.stringify({
59
+ + const payload = JSON.stringify({
60
+ type,
61
+ name,
62
+ seq,
63
+ @@ -267,7 +270,26 @@
64
+ isTrivial: !args.some(value => {
65
+ return value instanceof Node;
66
+ }),
67
+ - }));
68
+ + });
69
+ + const send = (tries) => {
70
+ + // @ts-expect-error: In a different context.
71
+ + // Needs to be the same as CDP_BINDING_PREFIX.
72
+ + const cdpBinding = globalThis[prefix + name];
73
+ + if (typeof cdpBinding === 'function') {
74
+ + cdpBinding(payload);
75
+ + }
76
+ + else if (tries < 500) {
77
+ + setTimeout(() => {
78
+ + return send(tries + 1);
79
+ + }, 10);
80
+ + }
81
+ + else {
82
+ + callPuppeteer.callbacks
83
+ + .get(seq)
84
+ + ?.reject(new Error(`binding ${name} is not available`));
85
+ + }
86
+ + };
87
+ + send(0);
88
+ return new Promise((resolve, reject) => {
89
+ callPuppeteer.callbacks.set(seq, {
90
+ resolve(value) {
91
+ --- a/lib/puppeteer/cdp/Page.js
92
+ +++ b/lib/puppeteer/cdp/Page.js
93
+ @@ -302,6 +302,7 @@
94
+ clientEmitter.on('Inspector.targetCrashed', this.#onTargetCrashed.bind(this));
95
+ clientEmitter.on('Performance.metrics', this.#emitMetrics.bind(this));
96
+ clientEmitter.on('Log.entryAdded', this.#onLogEntryAdded.bind(this));
97
+ + clientEmitter.on('Console.messageAdded', this.#onConsoleMessageAdded.bind(this));
98
+ clientEmitter.on('Page.fileChooserOpened', this.#onFileChooser.bind(this));
99
+ }
100
+ #onDetachedFromTarget = (target) => {
101
+ @@ -353,6 +354,7 @@
102
+ this.#frameManager.initialize(this.#primaryTargetClient),
103
+ this.#primaryTargetClient.send('Performance.enable'),
104
+ this.#primaryTargetClient.send('Log.enable'),
105
+ + process.env['REBROWSER_PATCHES_RUNTIME_FIX_MODE'] !== '0' && this.#primaryTargetClient.send('Console.enable'),
106
+ this.#webmcp.initialize(),
107
+ ]);
108
+ }
109
+ @@ -514,6 +516,12 @@
110
+ #onTargetCrashed() {
111
+ this.emit("error" /* PageEvent.Error */, new Error('Page crashed!'));
112
+ }
113
+ + #onConsoleMessageAdded(event) {
114
+ + // rebrowser-patches: Runtime.consoleAPICalled needs Runtime.enable, so console.* output is
115
+ + // read from the legacy Console domain instead (text only, no argument handles).
116
+ + const { level, text, url, line, column } = event.message;
117
+ + this.#emitConsoleMessage(new ConsoleMessage(convertConsoleMessageLevel(level), text, [], [{ url, lineNumber: line === undefined ? undefined : line - 1, columnNumber: column === undefined ? undefined : column - 1 }], undefined, undefined, this.#primaryTarget._targetId, undefined));
118
+ + }
119
+ #onLogEntryAdded(event) {
120
+ const { level, text, args, source, url, lineNumber, stackTrace } = event.entry;
121
+ if (args) {
package/postinstall.mjs CHANGED
@@ -16,6 +16,10 @@ import { createRequire } from 'node:module';
16
16
  import { dirname, join, resolve } from 'node:path';
17
17
  import { mkdir, readFile, writeFile } from 'node:fs/promises';
18
18
  import { parsePatch, applyPatch } from 'diff';
19
+ // rebrowser-patches >= 1.1 ships one patch set per upstream version under
20
+ // patches/<package>/<version>/; reuse its own selection logic (exact match →
21
+ // newest same major.minor → newest overall) so we stay in sync with its CLI.
22
+ import { resolvePatchVersion } from 'rebrowser-patches/scripts/utils/index.js';
19
23
 
20
24
  const require = createRequire(import.meta.url);
21
25
 
@@ -87,14 +91,14 @@ function applyWithFuzz(source, filePatch, maxFuzz = 10) {
87
91
  * Apply a multi-file unified patch to a target directory.
88
92
  * Handles new files (/dev/null → b/path) and skips already-patched files.
89
93
  * @param {string} targetDir — absolute path to the package root
90
- * @param {string} patchContent — raw unified diff string
94
+ * @param {string | import('diff').StructuredPatch[]} patchContent — raw unified diff string, or already-parsed file patches
91
95
  * @param {object} [options]
92
96
  * @param {number} [options.maxFuzz] — maximum fuzz factor passed to applyWithFuzz
93
97
  * @param {(fp: import('diff').StructuredPatch) => boolean} [options.filter] — predicate to select file patches
94
98
  * @returns {Promise<{applied: number, skipped: number, failed: string[]}>}
95
99
  */
96
100
  async function applyMultiPatch(targetDir, patchContent, { maxFuzz , filter } = {}) {
97
- let filePatches = parsePatch(patchContent);
101
+ let filePatches = typeof patchContent === 'string' ? parsePatch(patchContent) : patchContent;
98
102
  if (filter) filePatches = filePatches.filter(filter);
99
103
 
100
104
  const stats = { applied: 0, skipped: 0, failed: [] };
@@ -134,36 +138,134 @@ async function applyMultiPatch(targetDir, patchContent, { maxFuzz , filter } = {
134
138
  // Main
135
139
  // ---------------------------------------------------------------------------
136
140
 
141
+ /**
142
+ * Read the installed version of a package, or 'unknown' if it can't be resolved.
143
+ * @param {string} packageName
144
+ */
145
+ function pkgVersion(packageName) {
146
+ try { return require(`${packageName}/package.json`).version; }
147
+ catch { return 'unknown'; }
148
+ }
149
+
150
+ /**
151
+ * Print a big, impossible-to-miss error block with diagnostic info and a link to
152
+ * the known-compatibility issue. Tuned specifically for issue #4: a
153
+ * `puppeteer-core` / `rebrowser-patches` version mismatch silently produces an
154
+ * unpatchable install. Both are now pinned exact in package.json, so this path
155
+ * should only fire if a user has overridden the pins or is running from a fork.
156
+ *
157
+ * @param {string} stage — human-readable stage name that failed
158
+ * @param {string[]} failed — list of patch target files that did not apply
159
+ * @param {Record<string, string>} versions — installed versions for context
160
+ */
161
+ function printPatchFailureReport(stage, failed, versions) {
162
+ const lines = [
163
+ '',
164
+ '━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━',
165
+ `✘ chrome-devtools-mcp-rebrowser postinstall: ${stage} FAILED`,
166
+ '━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━',
167
+ '',
168
+ 'The following patch targets could not be applied:',
169
+ ...failed.map(f => ` • ${f}`),
170
+ '',
171
+ 'Installed versions:',
172
+ ...Object.entries(versions).map(([k, v]) => ` • ${k}: ${v}`),
173
+ '',
174
+ 'This usually means one of the patched dependencies was upgraded past',
175
+ 'what rebrowser-patches knows how to handle. See:',
176
+ ' https://github.com/liqi0816/chrome-devtools-mcp-rebrowser/issues/4',
177
+ '',
178
+ 'Quickest workaround: pin the known-good versions locally, e.g.',
179
+ ' npx -y @liqi0816/chrome-devtools-mcp-rebrowser@1.0.4',
180
+ '(or whatever the latest published version is).',
181
+ '━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━',
182
+ '',
183
+ ];
184
+ console.error(lines.join('\n'));
185
+ }
186
+
137
187
  async function main() {
138
188
  console.log('\n🔧 chrome-devtools-mcp-rebrowser: postinstall\n');
139
189
 
140
190
  const puppeteerCoreDir = pkgDir('puppeteer-core');
141
- const rebrowserPatchesDir = pkgDir('rebrowser-patches');
142
191
  const chromeDevtoolsMcpDir = pkgDir('chrome-devtools-mcp');
143
192
  const ownDir = resolve(
144
193
  dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Z]:)/i, '$1')),
145
194
  );
146
195
 
196
+ const versions = {
197
+ 'puppeteer-core': pkgVersion('puppeteer-core'),
198
+ 'rebrowser-patches': pkgVersion('rebrowser-patches'),
199
+ 'chrome-devtools-mcp': pkgVersion('chrome-devtools-mcp'),
200
+ };
201
+ console.log('Installed:', Object.entries(versions).map(([k, v]) => `${k}@${v}`).join(', '));
202
+ console.log('');
203
+
147
204
  // 1. Apply rebrowser-patches to puppeteer-core
148
205
  console.log('--- Applying rebrowser-patches to puppeteer-core ---');
149
- const rebrowserPatch = await readFile(
150
- join(rebrowserPatchesDir, 'patches', 'puppeteer-core', 'lib.patch'), 'utf8',
151
- );
152
- const r1 = await applyMultiPatch(puppeteerCoreDir, rebrowserPatch, {
153
- maxFuzz: 10,
154
- filter: ({ oldFileName }) => !oldFileName.startsWith('a/lib/es5-iife')
155
- });
206
+ const resolved = resolvePatchVersion('puppeteer-core', versions['puppeteer-core'], 'lib');
207
+ if (!resolved) {
208
+ printPatchFailureReport('rebrowser-patches → puppeteer-core', ['(no lib.patch shipped for puppeteer-core)'], versions);
209
+ throw new Error('No rebrowser-patches lib.patch found for puppeteer-core');
210
+ }
211
+ console.log(` Using rebrowser patch set ${resolved.version}` +
212
+ (resolved.exact ? '' : ` (closest match; not tested upstream on ${versions['puppeteer-core']})`));
213
+ const rebrowserPatch = await readFile(resolved.path, 'utf8');
214
+
215
+ // Local per-file overrides for puppeteer-core versions newer than what
216
+ // rebrowser-patches has tested: patches/puppeteer-core/<version>/lib.patch.
217
+ // A file listed there replaces the upstream hunk for that same file.
218
+ let overridePatches = [];
219
+ try {
220
+ overridePatches = parsePatch(await readFile(
221
+ join(ownDir, 'patches', 'puppeteer-core', versions['puppeteer-core'], 'lib.patch'), 'utf8',
222
+ ));
223
+ console.log(` Local overrides: ${overridePatches.map(fp => fp.oldFileName.slice(2)).join(', ')}`);
224
+ } catch (e) {
225
+ if (e.code !== 'ENOENT') throw e;
226
+ }
227
+ const overridden = new Set(overridePatches.map(fp => fp.oldFileName));
228
+ const upstreamPatches = parsePatch(rebrowserPatch)
229
+ .filter(({ oldFileName }) => !oldFileName.startsWith('a/lib/es5-iife') && !overridden.has(oldFileName));
230
+
231
+ const r1 = await applyMultiPatch(puppeteerCoreDir, [...upstreamPatches, ...overridePatches], { maxFuzz: 10 });
156
232
  console.log(` ✔ ${r1.applied} applied, ${r1.skipped} skipped`);
157
- if (r1.failed.length) throw new Error(`✘ Failed: ${r1.failed.join(', ')}`);
233
+ if (r1.failed.length) {
234
+ printPatchFailureReport('rebrowser-patches → puppeteer-core', r1.failed, versions);
235
+ throw new Error(`Failed patches: ${r1.failed.join(', ')}`);
236
+ }
158
237
 
159
- // 2. Apply DevToolsConnectionAdapter patch to chrome-devtools-mcp
238
+ // 2. Block Runtime.enable in chrome-devtools-mcp's DevToolsConnectionAdapter.
239
+ // Since chrome-devtools-mcp 1.x the adapter is bundled (minified, on a single
240
+ // ~900 KB line) into third_party/browser.js, so a unified diff is impractical.
241
+ // Instead, anchor on the adapter's send() signature + its unique error string
242
+ // and inject the guard using whatever parameter names the minifier chose.
160
243
  console.log('--- Applying DevToolsConnectionAdapter patch ---');
161
- const adapterPatch = await readFile(
162
- join(ownDir, 'patches', 'chrome-devtools-mcp', 'DevToolsConnectionAdapter.js.patch'), 'utf8',
163
- );
164
- const r2 = await applyMultiPatch(chromeDevtoolsMcpDir, adapterPatch, { maxFuzz: 2 });
165
- console.log(` ✔ ${r2.applied} applied, ${r2.skipped} skipped`);
166
- if (r2.failed.length) throw new Error(`✘ Failed: ${r2.failed.join(', ')}`);
244
+ const adapterRel = join('out', 'Default', 'gen', 'src', 'third_party', 'browser.js');
245
+ const adapterPath = join(chromeDevtoolsMcpDir, adapterRel);
246
+ const adapterSrc = await readFile(adapterPath, 'utf8');
247
+ const MARKER = '/*rebrowser-patches:DevToolsConnectionAdapter*/';
248
+ if (adapterSrc.includes(MARKER)) {
249
+ console.log(' ✔ 0 applied, 1 skipped');
250
+ } else {
251
+ const anchor = /send\(([\w$]+),([\w$]+),([\w$]+)\)\{if\(\3===void 0\)throw new Error\("Attempting to send on the root session\. This must not happen"\);/g;
252
+ const matches = [...adapterSrc.matchAll(anchor)];
253
+ if (matches.length !== 1) {
254
+ printPatchFailureReport('DevToolsConnectionAdapter patch → chrome-devtools-mcp',
255
+ [`${adapterRel} (expected 1 anchor match, found ${matches.length})`], versions);
256
+ throw new Error(`Failed patches: ${adapterRel}`);
257
+ }
258
+ const [m, method, , sessionId] = matches[0];
259
+ // The DevTools Universe models call Runtime.enable on their own CDP session,
260
+ // which leaks as a detectable CDP marker. Suppress it here just like
261
+ // rebrowser-patches suppresses it inside Puppeteer's FrameManager.
262
+ const guard = `${MARKER}if(${method}==="Runtime.enable"&&process.env.REBROWSER_PATCHES_RUNTIME_FIX_MODE!=="0"){` +
263
+ `process.env.REBROWSER_PATCHES_DEBUG&&console.error("[rebrowser-patches][DevToolsConnection] Blocked Runtime.enable on session",${sessionId});` +
264
+ `return Promise.resolve({result:{}})}`;
265
+ const idx = matches[0].index + m.length;
266
+ await writeFile(adapterPath, adapterSrc.slice(0, idx) + guard + adapterSrc.slice(idx));
267
+ console.log(' ✔ 1 applied, 0 skipped');
268
+ }
167
269
 
168
270
  console.log('\n✅ All patches applied. Ready to use!\n');
169
271
  }
@@ -1,17 +0,0 @@
1
- --- a/build/src/DevToolsConnectionAdapter.js
2
- +++ b/build/src/DevToolsConnectionAdapter.js
3
- @@ -27,6 +27,14 @@
4
- if (!session) {
5
- throw new Error('Unknown session ' + sessionId);
6
- }
7
- + // rebrowser-patches: block Runtime.enable to prevent CDP detection.
8
- + // The DevTools Universe models call Runtime.enable on their own CDP session,
9
- + // which leaks as a detectable CDP marker. We suppress it here just like
10
- + // rebrowser-patches suppresses it inside Puppeteer's FrameManager.
11
- + if (method === 'Runtime.enable' && process.env['REBROWSER_PATCHES_RUNTIME_FIX_MODE'] !== '0') {
12
- + process.env['REBROWSER_PATCHES_DEBUG'] && console.error('[rebrowser-patches][DevToolsConnection] Blocked Runtime.enable on session', sessionId);
13
- + return Promise.resolve({ result: {} });
14
- + }
15
- // Rolled protocol version between puppeteer and DevTools doesn't necessarily match
16
- /* eslint-disable @typescript-eslint/no-explicit-any */
17
- return session