@liqi0816/chrome-devtools-mcp-rebrowser 1.0.3 → 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
@@ -90,10 +90,10 @@ Then configure the MCP server to use the local entry point:
90
90
  launch.mjs (entry point)
91
91
  │
92
92
  ├─ Imports patched puppeteer-core (node_modules/puppeteer-core)
93
- │ └─ puppeteer-core@24.40.0 + rebrowser-patches applied
93
+ │ └─ puppeteer-core@25.18.1 + rebrowser-patches applied
94
94
  │
95
95
  ├─ Imports bundled puppeteer from chrome-devtools-mcp
96
- │ └─ 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
97
97
  │
98
98
  ├─ Monkey-patches bundled puppeteer's connect()/launch() methods
99
99
  │ to redirect through the patched puppeteer-core
@@ -102,11 +102,14 @@ launch.mjs (entry point)
102
102
 
103
103
  postinstall.mjs (runs after npm install)
104
104
  │
105
- ├─ 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
106
108
  │
107
- └─ 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
108
111
 
109
- DevToolsConnectionAdapter.js (patched)
112
+ DevToolsConnectionAdapter (patched, inside third_party/browser.js)
110
113
  │
111
114
  └─ Blocks Runtime.enable calls from DevTools Universe models
112
115
  to prevent CDP detection via the separate CDP session
@@ -114,16 +117,18 @@ DevToolsConnectionAdapter.js (patched)
114
117
 
115
118
  ### Why the Monkey-Patching?
116
119
 
117
- - `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`.
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`.
118
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+).
119
122
  - Solution: install a compatible `puppeteer-core` separately, apply `rebrowser-patches` to it, then redirect the bundled Puppeteer's calls through the patched version.
120
123
 
121
124
  ### Why `puppeteer-core` and `rebrowser-patches` are pinned to exact versions
122
125
 
123
- You'll see `"puppeteer-core": "24.40.0"` and `"rebrowser-patches": "1.0.19"` (no caret) in `package.json`. This is deliberate — these two **must** move in lockstep:
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:
124
127
 
125
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.
126
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
+
127
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.
128
133
 
129
134
  ## Flags
@@ -161,9 +166,9 @@ You can fine-tune the anti-detection patches:
161
166
 
162
167
  4. **Browser `_connection()` method** — Exposes the CDP connection for advanced use cases (not detectable by websites).
163
168
 
164
- ### DevToolsConnectionAdapter.js (applied to chrome-devtools-mcp)
169
+ ### DevToolsConnectionAdapter (applied to chrome-devtools-mcp)
165
170
 
166
- 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.
167
172
 
168
173
  ### What the DevTools Universe CDP session is used for
169
174
 
@@ -180,12 +185,28 @@ You can fine-tune the anti-detection patches:
180
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:
181
186
 
182
187
  - **Core MCP tools are unaffected** — `evaluate_script`, page snapshots, navigation, clicking, typing, screenshots all use Puppeteer APIs directly, not the Universe session.
183
- - **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).
184
189
  - **Stack traces from `DebuggerModel` still work** — `Debugger.enable` is not blocked, so source-map-aware stack traces continue to function.
185
190
  - **Only error cause chains degrade** — The recursive `.cause` lookup via `RuntimeModel.getExceptionDetails()` may fail silently, omitting cause details from console error output.
186
191
 
187
192
  This is an acceptable tradeoff since `Runtime.enable` is the primary CDP detection vector used by anti-bot systems.
188
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
+
189
210
  ## Troubleshooting
190
211
 
191
212
  ### "Could not connect to Chrome"
@@ -203,8 +224,8 @@ This is an acceptable tradeoff since `Runtime.enable` is the primary CDP detecti
203
224
 
204
225
  | Package | Version | Pinned? |
205
226
  |---------|---------|---------|
206
- | chrome-devtools-mcp | ^0.22.0 | floats (fuzzy patch) |
207
- | puppeteer-core | 24.40.0 | **exact** ([why](#why-puppeteer-core-and-rebrowser-patches-are-pinned-to-exact-versions)) |
208
- | rebrowser-patches | 1.0.19 | **exact** ([why](#why-puppeteer-core-and-rebrowser-patches-are-pinned-to-exact-versions)) |
209
- | diff | ^8.0.4 | floats |
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 |
210
231
  | Node.js | ≥ 20.19.0 | — |
package/launch.mjs CHANGED
@@ -8,7 +8,7 @@ const require = createRequire(import.meta.url);
8
8
  // ---------------------------------------------------------------------------
9
9
  // Step 1: Import the patched puppeteer-core
10
10
  // ---------------------------------------------------------------------------
11
- // This is puppeteer-core (pinned in package.json — currently 24.40.0) with
11
+ // This is puppeteer-core (pinned in package.json — currently 25.18.1) with
12
12
  // rebrowser-patches applied in-place by postinstall.mjs.
13
13
  // The patches disable Runtime.Enable (the primary CDP detection vector),
14
14
  // change sourceURL from pptr:... to app.js, and rename the utility world.
@@ -19,7 +19,7 @@ import puppeteerCore from 'puppeteer-core';
19
19
  // ---------------------------------------------------------------------------
20
20
  // ESM modules are cached by resolved URL, so this gives us a reference to the
21
21
  // SAME puppeteer object that browser.js will use when it calls connect()/launch().
22
- 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';
23
23
 
24
24
  bundledPuppeteer.connect = function connect() {
25
25
  process.stderr.write('[rebrowser-patch] Redirecting puppeteer.connect() through patched puppeteer-core\n');
@@ -36,5 +36,5 @@ bundledPuppeteer.launch = function launch() {
36
36
  // ---------------------------------------------------------------------------
37
37
  // This imports and runs chrome-devtools-mcp's main entry point. When it
38
38
  // eventually calls puppeteer.connect() or puppeteer.launch() via
39
- // browser.js → third_party/index.js, it will hit our patched methods above.
40
- 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.3",
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": {
@@ -40,10 +40,10 @@
40
40
  "prepublishOnly": "npm run smoke-test"
41
41
  },
42
42
  "dependencies": {
43
- "chrome-devtools-mcp": "^0.22.0",
44
- "diff": "^8.0.4",
45
- "puppeteer-core": "24.40.0",
46
- "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"
47
47
  },
48
48
  "publishConfig": {
49
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: [] };
@@ -172,7 +176,7 @@ function printPatchFailureReport(stage, failed, versions) {
172
176
  ' https://github.com/liqi0816/chrome-devtools-mcp-rebrowser/issues/4',
173
177
  '',
174
178
  'Quickest workaround: pin the known-good versions locally, e.g.',
175
- ' npx -y @liqi0816/chrome-devtools-mcp-rebrowser@1.0.3',
179
+ ' npx -y @liqi0816/chrome-devtools-mcp-rebrowser@1.0.4',
176
180
  '(or whatever the latest published version is).',
177
181
  '━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━',
178
182
  '',
@@ -184,7 +188,6 @@ async function main() {
184
188
  console.log('\n🔧 chrome-devtools-mcp-rebrowser: postinstall\n');
185
189
 
186
190
  const puppeteerCoreDir = pkgDir('puppeteer-core');
187
- const rebrowserPatchesDir = pkgDir('rebrowser-patches');
188
191
  const chromeDevtoolsMcpDir = pkgDir('chrome-devtools-mcp');
189
192
  const ownDir = resolve(
190
193
  dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Z]:)/i, '$1')),
@@ -200,29 +203,68 @@ async function main() {
200
203
 
201
204
  // 1. Apply rebrowser-patches to puppeteer-core
202
205
  console.log('--- Applying rebrowser-patches to puppeteer-core ---');
203
- const rebrowserPatch = await readFile(
204
- join(rebrowserPatchesDir, 'patches', 'puppeteer-core', 'lib.patch'), 'utf8',
205
- );
206
- const r1 = await applyMultiPatch(puppeteerCoreDir, rebrowserPatch, {
207
- maxFuzz: 10,
208
- filter: ({ oldFileName }) => !oldFileName.startsWith('a/lib/es5-iife')
209
- });
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 });
210
232
  console.log(` ✔ ${r1.applied} applied, ${r1.skipped} skipped`);
211
233
  if (r1.failed.length) {
212
234
  printPatchFailureReport('rebrowser-patches → puppeteer-core', r1.failed, versions);
213
235
  throw new Error(`Failed patches: ${r1.failed.join(', ')}`);
214
236
  }
215
237
 
216
- // 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.
217
243
  console.log('--- Applying DevToolsConnectionAdapter patch ---');
218
- const adapterPatch = await readFile(
219
- join(ownDir, 'patches', 'chrome-devtools-mcp', 'DevToolsConnectionAdapter.js.patch'), 'utf8',
220
- );
221
- const r2 = await applyMultiPatch(chromeDevtoolsMcpDir, adapterPatch, { maxFuzz: 2 });
222
- console.log(` ✔ ${r2.applied} applied, ${r2.skipped} skipped`);
223
- if (r2.failed.length) {
224
- printPatchFailureReport('DevToolsConnectionAdapter patch → chrome-devtools-mcp', r2.failed, versions);
225
- throw new Error(`Failed patches: ${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');
226
268
  }
227
269
 
228
270
  console.log('\n✅ All patches applied. Ready to use!\n');
@@ -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