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

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.
Files changed (3) hide show
  1. package/README.md +3 -2
  2. package/package.json +4 -3
  3. package/postinstall.mjs +115 -133
package/README.md CHANGED
@@ -2,6 +2,8 @@
2
2
 
3
3
  This project wraps [chrome-devtools-mcp](https://github.com/ChromeDevTools/chrome-devtools-mcp) with [rebrowser-patches](https://github.com/rebrowser/rebrowser-patches) to make AI agents undetectable by anti-bot systems like Cloudflare and DataDome.
4
4
 
5
+ ![negative bot detection result](./are-you-a-bot.webp)
6
+
5
7
  ## šŸ¤– AI
6
8
 
7
9
  Yes, I used AI. I also committed the full conversations as the real design documents (`.ai-conversations/` - private submodule, ask me for access).
@@ -32,7 +34,7 @@ No cloning or manual setup needed. Just configure your MCP client:
32
34
  "command": "npx",
33
35
  "args": [
34
36
  "-y",
35
- "chrome-devtools-mcp-rebrowser@latest",
37
+ "@liqi0816/chrome-devtools-mcp-rebrowser@latest",
36
38
  "--auto-connect",
37
39
  "--performance-crux=false",
38
40
  "--usage-statistics=false",
@@ -185,7 +187,6 @@ This is an acceptable tradeoff since `Runtime.enable` is the primary CDP detecti
185
187
  - Check that `DevToolsActivePort` file exists in Chrome's user data directory
186
188
 
187
189
  ### Patch fails with "FAILED" hunks
188
- - The `es5-iife` hunk failure is expected and harmless
189
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
190
191
 
191
192
  ### "emulateFocusedPage is not a function" (or similar)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@liqi0816/chrome-devtools-mcp-rebrowser",
3
- "version": "1.0.0",
3
+ "version": "1.0.2",
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",
@@ -24,7 +24,7 @@
24
24
  "type": "module",
25
25
  "main": "launch.mjs",
26
26
  "bin": {
27
- "chrome-devtools-mcp-rebrowser": "./launch.mjs"
27
+ "chrome-devtools-mcp-rebrowser": "launch.mjs"
28
28
  },
29
29
  "files": [
30
30
  "launch.mjs",
@@ -39,7 +39,8 @@
39
39
  },
40
40
  "dependencies": {
41
41
  "chrome-devtools-mcp": "^0.20.3",
42
- "puppeteer-core": "^24.39.1",
42
+ "diff": "^8.0.4",
43
+ "puppeteer-core": "^24.40.0",
43
44
  "rebrowser-patches": "^1.0.19"
44
45
  },
45
46
  "publishConfig": {
package/postinstall.mjs CHANGED
@@ -5,120 +5,129 @@
5
5
  * DevToolsConnectionAdapter patch so that `npx chrome-devtools-mcp-rebrowser`
6
6
  * works out of the box with zero manual setup.
7
7
  *
8
+ * Uses the pure-JS `diff` (jsdiff) library to apply unified patches,
9
+ * eliminating platform-specific differences between macOS/Linux/Windows
10
+ * `patch` binaries.
11
+ *
8
12
  * Runs after `npm install` (via package.json "postinstall" script).
9
13
  */
10
14
 
11
- import { execFile as execFileCb } from 'node:child_process';
12
- import { promisify } from 'node:util';
13
15
  import { createRequire } from 'node:module';
14
16
  import { dirname, join, resolve } from 'node:path';
15
- import { readFile, writeFile, unlink, mkdtemp } from 'node:fs/promises';
16
- import { tmpdir } from 'node:os';
17
+ import { mkdir, readFile, writeFile } from 'node:fs/promises';
18
+ import { parsePatch, applyPatch } from 'diff';
17
19
 
18
- const execFile = promisify(execFileCb);
19
20
  const require = createRequire(import.meta.url);
20
21
 
21
22
  // ---------------------------------------------------------------------------
22
23
  // Helpers
23
24
  // ---------------------------------------------------------------------------
24
25
 
25
- /** Resolve the directory of an installed package by its main/package.json */
26
+ /**
27
+ * Resolve the directory of an installed package by its main/package.json.
28
+ * @param {string} packageName
29
+ */
26
30
  function pkgDir(packageName) {
27
- const entry = require.resolve(`${packageName}/package.json`);
28
- return dirname(entry);
31
+ return dirname(require.resolve(`${packageName}/package.json`));
29
32
  }
30
33
 
31
- /** Find `patch` executable — on Windows try Git's bundled copy too */
32
- async function findPatch() {
33
- for (const base of [
34
- '',
35
- 'C:\\Program Files\\Git\\usr\\bin',
36
- 'C:\\Program Files (x86)\\Git\\usr\\bin',
37
- ]) {
38
- const cmd = join(base, 'patch');
39
- try {
40
- await execFile(cmd, ['--version']);
41
- return cmd;
42
- } catch {
43
- // not found, try next
44
- }
45
- }
46
- console.error(
47
- '✘ Could not find the `patch` command.\n' +
48
- ' On Linux/macOS it is usually pre-installed.\n' +
49
- ' On Windows, install Git for Windows — it bundles patch.exe in\n' +
50
- ' C:\\Program Files\\Git\\usr\\bin\\patch.exe\n' +
51
- ' and make sure it is on your PATH.',
52
- );
53
- throw new Error('Could not find `patch` executable');
34
+ /**
35
+ * Fuzzy line comparator for jsdiff's applyPatch.
36
+ *
37
+ * jsdiff has a hard constraint: context lines immediately adjacent to an
38
+ * insertion must match *exactly* (regardless of fuzzFactor). This fails when
39
+ * an upstream update adds parameters: `newPage()` → `newPage(options)`.
40
+ *
41
+ * This compareLine requires everything outside parentheses to match exactly,
42
+ * and inside parentheses one side must be a substring of the other — so
43
+ * `f()` matches `f(options)` but `f(a)` does NOT match `f(completely_different)`.
44
+ *
45
+ * This is safe because jsdiff keeps the file's original content for context
46
+ * lines — the comparator only affects *where* the hunk is placed.
47
+ *
48
+ * @param {number} _lineNumber — 1-based line number in the target file
49
+ * @param {string} line — line from the target file
50
+ * @param {'+' | '-' | ' '} _operation — hunk operation (unused)
51
+ * @param {string} patchContent — expected line from the patch
52
+ */
53
+ function fuzzyCompareLine(_lineNumber, line, _operation, patchContent) {
54
+ if (line === patchContent) return true;
55
+ if (line == null || patchContent == null) return false;
56
+
57
+ const openL = line.indexOf('('), closeL = line.lastIndexOf(')');
58
+ const openP = patchContent.indexOf('('), closeP = patchContent.lastIndexOf(')');
59
+ if (openL < 0 || closeL < 0 || openP < 0 || closeP < 0) return false;
60
+
61
+ // Everything outside the parens must match exactly
62
+ if (line.slice(0, openL) !== patchContent.slice(0, openP)) return false;
63
+ if (line.slice(closeL + 1) !== patchContent.slice(closeP + 1)) return false;
64
+
65
+ // Inside: one must be a substring of the other
66
+ const innerL = line.slice(openL + 1, closeL);
67
+ const innerP = patchContent.slice(openP + 1, closeP);
68
+ return innerL.includes(innerP) || innerP.includes(innerL);
54
69
  }
55
70
 
56
71
  /**
57
- * Strip hunks that target paths matching `filterRe` from a unified diff.
58
- * Returns the filtered patch as a string.
72
+ * Apply a single-file patch with fuzzing.
73
+ * Returns the patched string, or false if it cannot be applied.
74
+ * @param {string} source — original file content
75
+ * @param {import('diff').StructuredPatch} filePatch — parsed single-file patch
76
+ * @param {number} [maxFuzz=10] — maximum fuzz factor (number of context lines that can mismatch)
59
77
  */
60
- function stripHunksFromPatch(patchContent, filterRe) {
61
- const lines = patchContent.split('\n');
62
- const kept = [];
63
- let skipping = false;
64
-
65
- for (const line of lines) {
66
- // Each file section starts with "--- a/..."
67
- if (line.startsWith('--- a/')) {
68
- const path = line.slice('--- a/'.length);
69
- skipping = filterRe.test(path);
70
- }
71
- if (!skipping) kept.push(line);
72
- }
73
- return kept.join('\n');
78
+ function applyWithFuzz(source, filePatch, maxFuzz = 10) {
79
+ // Try with exact context lines first (jsdiff internally tries 0..maxFuzz errors)
80
+ const exact = applyPatch(source, filePatch, { fuzzFactor: maxFuzz });
81
+ if (exact !== false) return exact;
82
+ // Fallback: fuzzy context for changed function signatures (e.g. newPage() → newPage(options))
83
+ return applyPatch(source, filePatch, { fuzzFactor: maxFuzz, compareLine: fuzzyCompareLine });
74
84
  }
75
85
 
76
86
  /**
77
- * Apply a patch file to a target directory.
78
- *
79
- * Captures stdout/stderr so we can distinguish "already applied" from real
80
- * failures. With `--forward`, GNU patch exits 1 both when every hunk was
81
- * previously applied *and* when some hunks genuinely fail. We tell the two
82
- * apart by checking the output for FAILED hunks.
87
+ * Apply a multi-file unified patch to a target directory.
88
+ * Handles new files (/dev/null → b/path) and skips already-patched files.
89
+ * @param {string} targetDir — absolute path to the package root
90
+ * @param {string} patchContent — raw unified diff string
91
+ * @param {object} [options]
92
+ * @param {number} [options.maxFuzz] — maximum fuzz factor passed to applyWithFuzz
93
+ * @param {(fp: import('diff').StructuredPatch) => boolean} [options.filter] — predicate to select file patches
94
+ * @returns {Promise<{applied: number, skipped: number, failed: string[]}>}
83
95
  */
84
- async function applyPatch(patchBin, targetDir, patchFile, { fuzz } = {}) {
85
- const args = [
86
- '--batch',
87
- '-p1',
88
- `--input=${patchFile}`,
89
- '--verbose',
90
- '--no-backup-if-mismatch',
91
- '--reject-file=-',
92
- '--forward',
93
- ];
94
- if (fuzz != null) args.push(`--fuzz=${fuzz}`);
95
-
96
- try {
97
- const { stdout, stderr } = await execFile(patchBin, args, { cwd: targetDir });
98
- process.stdout.write(stdout);
99
- process.stderr.write(stderr);
100
- console.log(`āœ” Patch applied successfully in ${targetDir}`);
101
- } catch (err) {
102
- // execFile rejects for any non-zero exit code.
103
- process.stdout.write(err.stdout);
104
- process.stderr.write(err.stderr);
105
-
106
- // Check whether every hunk was "Reversed (or previously applied)".
107
- // If so (and there are zero FAILED hunks), this is a genuine
108
- // "already applied" situation.
109
- const hasFailedHunks = /FAILED/i.test(err.stdout);
110
- const hasReversed = /Reversed \(or previously applied\) patch detected/i.test(err.stdout);
111
-
112
- if (hasReversed && !hasFailedHunks) {
113
- console.log(`āœ” Patch already applied in ${targetDir} (skipped)`);
114
- return;
96
+ async function applyMultiPatch(targetDir, patchContent, { maxFuzz , filter } = {}) {
97
+ let filePatches = parsePatch(patchContent);
98
+ if (filter) filePatches = filePatches.filter(filter);
99
+
100
+ const stats = { applied: 0, skipped: 0, failed: [] };
101
+
102
+ for (const fp of filePatches) {
103
+ // New file: oldFileName is "/dev/null", use newFileName ("b/path/to/file")
104
+ // Existing file: oldFileName is "a/path/to/file"
105
+ const isNewFile = fp.oldFileName === '/dev/null';
106
+ const rel = isNewFile ? fp.newFileName.slice(2) : fp.oldFileName.slice(2);
107
+
108
+ // For new files, check if already created by a previous run
109
+ let src;
110
+ try { src = await readFile(join(targetDir, rel), 'utf8'); }
111
+ catch (e) {
112
+ if (e.code === 'ENOENT' && isNewFile) src = '';
113
+ else throw e;
115
114
  }
116
115
 
117
- // Any other non-zero exit is a real error.
118
- throw new Error(
119
- `✘ Patch failed in ${targetDir} (exit code ${err.code ?? err.status ?? '?'})`,
120
- );
116
+ // Check if patch content is already present (idempotent)
117
+ const added = fp.hunks.flatMap(h => h.lines.filter(l => l[0] === '+').map(l => l.slice(1).trim())).filter(Boolean);
118
+ if (added.length > 0 && added.every(l => src.includes(l))) { stats.skipped++; continue; }
119
+
120
+ const result = applyWithFuzz(src, fp, maxFuzz);
121
+ if (result !== false) {
122
+ const dest = join(targetDir, rel);
123
+ if (isNewFile) await mkdir(dirname(dest), { recursive: true });
124
+ await writeFile(dest, result);
125
+ stats.applied++;
126
+ } else {
127
+ stats.failed.push(rel);
128
+ }
121
129
  }
130
+ return stats;
122
131
  }
123
132
 
124
133
  // ---------------------------------------------------------------------------
@@ -128,11 +137,6 @@ async function applyPatch(patchBin, targetDir, patchFile, { fuzz } = {}) {
128
137
  async function main() {
129
138
  console.log('\nšŸ”§ chrome-devtools-mcp-rebrowser: postinstall\n');
130
139
 
131
- // 1. Locate patch executable
132
- const patchBin = await findPatch();
133
- console.log(`Using patch: ${patchBin}\n`);
134
-
135
- // 2. Resolve package directories
136
140
  const puppeteerCoreDir = pkgDir('puppeteer-core');
137
141
  const rebrowserPatchesDir = pkgDir('rebrowser-patches');
138
142
  const chromeDevtoolsMcpDir = pkgDir('chrome-devtools-mcp');
@@ -140,48 +144,26 @@ async function main() {
140
144
  dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Z]:)/i, '$1')),
141
145
  );
142
146
 
143
- console.log(`puppeteer-core: ${puppeteerCoreDir}`);
144
- console.log(`rebrowser-patches: ${rebrowserPatchesDir}`);
145
- console.log(`chrome-devtools-mcp: ${chromeDevtoolsMcpDir}`);
146
- console.log(`own package: ${ownDir}\n`);
147
-
148
- // 3. Apply rebrowser-patches to puppeteer-core (with fuzz for version tolerance)
149
- // The upstream patch includes hunks for lib/es5-iife/ which is a bundled
150
- // build that doesn't exist in every puppeteer-core release and doesn't
151
- // affect Node-side behaviour. We strip those hunks so they can't cause
152
- // spurious failures.
153
- const rebrowserPatchFile = join(
154
- rebrowserPatchesDir,
155
- 'patches',
156
- 'puppeteer-core',
157
- 'lib.patch',
147
+ // 1. Apply rebrowser-patches to puppeteer-core
148
+ console.log('--- Applying rebrowser-patches to puppeteer-core ---');
149
+ const rebrowserPatch = await readFile(
150
+ join(rebrowserPatchesDir, 'patches', 'puppeteer-core', 'lib.patch'), 'utf8',
158
151
  );
159
-
160
- const rawPatch = await readFile(rebrowserPatchFile, 'utf8');
161
- const filteredPatch = stripHunksFromPatch(rawPatch, /^lib\/es5-iife\//);
162
-
163
- // Write the filtered patch to a temp file
164
- const tmpDir = await mkdtemp(join(tmpdir(), 'rebrowser-'));
165
- const filteredPatchFile = join(tmpDir, 'lib-no-es5-iife.patch');
166
- await writeFile(filteredPatchFile, filteredPatch);
167
-
168
- try {
169
- console.log('--- Applying rebrowser-patches to puppeteer-core (es5-iife stripped) ---');
170
- await applyPatch(patchBin, puppeteerCoreDir, filteredPatchFile, { fuzz: 10 });
171
- } finally {
172
- // Clean up temp file
173
- await unlink(filteredPatchFile).catch(() => {});
174
- }
175
-
176
- // 4. Apply DevToolsConnectionAdapter patch to chrome-devtools-mcp
177
- const adapterPatchFile = join(
178
- ownDir,
179
- 'patches',
180
- 'chrome-devtools-mcp',
181
- 'DevToolsConnectionAdapter.js.patch',
152
+ const r1 = await applyMultiPatch(puppeteerCoreDir, rebrowserPatch, {
153
+ maxFuzz: 10,
154
+ filter: ({ oldFileName }) => !oldFileName.startsWith('a/lib/es5-iife')
155
+ });
156
+ console.log(` āœ” ${r1.applied} applied, ${r1.skipped} skipped`);
157
+ if (r1.failed.length) throw new Error(`✘ Failed: ${r1.failed.join(', ')}`);
158
+
159
+ // 2. Apply DevToolsConnectionAdapter patch to chrome-devtools-mcp
160
+ console.log('--- Applying DevToolsConnectionAdapter patch ---');
161
+ const adapterPatch = await readFile(
162
+ join(ownDir, 'patches', 'chrome-devtools-mcp', 'DevToolsConnectionAdapter.js.patch'), 'utf8',
182
163
  );
183
- console.log('\n--- Applying DevToolsConnectionAdapter patch to chrome-devtools-mcp ---');
184
- await applyPatch(patchBin, chromeDevtoolsMcpDir, adapterPatchFile);
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(', ')}`);
185
167
 
186
168
  console.log('\nāœ… All patches applied. Ready to use!\n');
187
169
  }