项目文件夹

文件
Natasha Gorshunova 02b4492ca6 feat: support allowedUrlPattern & blockedUrlPattern Options (#2037)
## Support for Network Blocklists and Allowlists
(`--blocked-url-pattern` & `--allowed-url-pattern` arguments)

This PR adds support for CLI options to restrict network access in the
browser session via URL patterns.

### Key Features & How It Works

- **Pattern Matching:** Utilizes the [URLPattern
Standard](https://urlpattern.spec.whatwg.org/) for pattern matching.
- **Target Detachment:** Silently detaches from targets (pages/tabs)
whose URLs match blocked patterns (or do not match allowed patterns)
upon connection.
- **Runtime Blocking:** Prevents navigations and blocks runtime requests
(such as fetch/XHR and subresources) if they violate the pattern rules.
- **Mutual Exclusivity:** `--blocked-url-pattern` and
`--allowed-url-pattern` conflict with each other and cannot be
configured simultaneously.
- **Browser Requirements:**
  - **`--allowed-url-pattern`**: Requires **Chrome 149+**.
- **`--blocked-url-pattern`**: Works on Chrome versions older than 149,
but **Chrome 149+ is highly recommended**.

### Important Limitations & Side Effects

- **Network Emulation/Throttling Conflict:** Network throttling is
disabled when a network blocklist/allowlist is configured, to avoid
conflicting with Puppeteer's underlying blocking mechanisms.
- Using the `emulate` tool to modify `networkConditions` (e.g. setting
to `Offline`) will throw an error: *`Network throttling is not supported
when network blocking (allowlist/blocklist) is configured.`*
- Other emulation settings (e.g., `cpuThrottlingRate`, `geolocation`,
`viewport`) are unaffected and remain fully functional.

---

### Configuration Examples

#### 1. Blocking specific domains or endpoints (Blocklist)
Add the `--blocked-url-pattern` options to the `args` list in your MCP
settings file:

```json
{
  "mcpServers": {
    "chrome-devtools": {
      "command": "npx",
      "args": [
        "chrome-devtools-mcp@latest",
        "--blocked-url-pattern=*://*.blocked-example.com/*",
        "--blocked-url-pattern=*://*.another-blocked-example.com/*"
      ]
    }
  }
}
```

#### 2. Restricting access to authorized domains (Allowlist)
Add the `--allowed-url-pattern` options to restrict the browser to
permitted hosts (requires Chrome 149+):

```json
{
  "mcpServers": {
    "chrome-devtools": {
      "command": "npx",
      "args": [
        "chrome-devtools-mcp@latest",
        "--allowed-url-pattern=https://*.allowed-example.com/*",
        "--allowed-url-pattern=https://*.another-allowed-example.com/*"
      ]
    }
  }
}
```

---------

Co-authored-by: Natallia Harshunova <nharshunova@chromium.org>
Co-authored-by: Alex Rudenko <alexrudenko@chromium.org>
2026-06-08 09:20:00 +00:00

284 行
7.9 KiB
TypeScript

/**
* @license
* Copyright 2026 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import assert from 'node:assert/strict';
import {describe, it} from 'node:test';
import {emulate} from '../src/tools/emulation.js';
import {lighthouseAudit} from '../src/tools/lighthouse.js';
import {navigatePage} from '../src/tools/pages.js';
import {evaluateScript} from '../src/tools/script.js';
import {serverHooks} from './server.js';
import {withMcpContext} from './utils.js';
describe('Network Blocking Integration', () => {
const server = serverHooks();
it('blocks URLs in blocklist', async () => {
server.addHtmlRoute('/allowed.html', '<html><body>Allowed</body></html>');
server.addHtmlRoute('/blocked.html', '<html><body>Blocked</body></html>');
const blockedUrlPattern = [server.getRoute('/blocked.html')];
await withMcpContext(
async (response, context) => {
const allowedUrl = server.getRoute('/allowed.html');
await navigatePage().handler(
{
params: {url: allowedUrl},
page: context.getSelectedMcpPage(),
},
response,
context,
);
assert.strictEqual(
response.responseLines[0],
`Successfully navigated to ${allowedUrl}.`,
);
response.resetResponseLineForTesting();
await evaluateScript().handler(
{
params: {function: String(() => document.body.textContent)},
},
response,
context,
);
assert.strictEqual(
JSON.parse(response.responseLines.at(2)!),
'Allowed',
);
const blockedUrl = server.getRoute('/blocked.html');
response.resetResponseLineForTesting();
await evaluateScript().handler(
{
params: {
function: `async () => {
try {
await fetch("${blockedUrl}");
return 'SUCCESS';
} catch (err) {
return err instanceof Error ? err.message : String(err);
}
}`,
},
},
response,
context,
);
assert.strictEqual(
JSON.parse(response.responseLines.at(2)!),
'Failed to fetch',
);
},
{
blockedUrlPattern,
},
);
});
it('blocks URLs not in allowlist', async () => {
server.addHtmlRoute('/allowed.html', '<html><body>Allowed</body></html>');
server.addHtmlRoute('/blocked.html', '<html><body>Blocked</body></html>');
const allowedUrlPattern = [server.getRoute('/allowed.html')];
await withMcpContext(
async (response, context) => {
const allowedUrl = server.getRoute('/allowed.html');
await navigatePage().handler(
{
params: {url: allowedUrl},
page: context.getSelectedMcpPage(),
},
response,
context,
);
assert.strictEqual(
response.responseLines[0],
`Successfully navigated to ${allowedUrl}.`,
);
response.resetResponseLineForTesting();
await evaluateScript().handler(
{
params: {function: String(() => document.body.textContent)},
},
response,
context,
);
assert.strictEqual(
JSON.parse(response.responseLines.at(2)!),
'Allowed',
);
const blockedUrl = server.getRoute('/blocked.html');
response.resetResponseLineForTesting();
await evaluateScript().handler(
{
params: {
function: `async () => {
try {
await fetch("${blockedUrl}");
return 'SUCCESS';
} catch (err) {
return err instanceof Error ? err.message : String(err);
}
}`,
},
},
response,
context,
);
assert.strictEqual(
JSON.parse(response.responseLines.at(2)!),
'Failed to fetch',
);
},
{
allowedUrlPattern,
},
);
});
it('respects blocklist after Lighthouse audits', async () => {
server.addHtmlRoute('/allowed.html', '<html><body>Allowed</body></html>');
server.addHtmlRoute('/blocked.html', '<html><body>Blocked</body></html>');
const blockedUrlPattern = [server.getRoute('/blocked.html')];
await withMcpContext(
async (response, context) => {
const allowedUrl = server.getRoute('/allowed.html');
await navigatePage().handler(
{
params: {url: allowedUrl},
page: context.getSelectedMcpPage(),
},
response,
context,
);
assert.strictEqual(
response.responseLines[0],
`Successfully navigated to ${allowedUrl}.`,
);
const blockedUrl = server.getRoute('/blocked.html');
// Verifies fetch is blocked before Lighthouse audit
response.resetResponseLineForTesting();
await evaluateScript().handler(
{
params: {
function: `async () => {
try {
await fetch("${blockedUrl}");
return 'SUCCESS';
} catch (err) {
return err instanceof Error ? err.message : String(err);
}
}`,
},
},
response,
context,
);
assert.strictEqual(
JSON.parse(response.responseLines.at(2)!),
'Failed to fetch',
'Fetch should be blocked before audit',
);
await lighthouseAudit.handler(
{
params: {
mode: 'navigation',
device: 'desktop',
},
page: context.getSelectedMcpPage(),
},
response,
context,
);
assert.equal(
response.attachedLighthouseResult?.summary.mode,
'navigation',
);
// 2. Verify fetch remains blocked AFTER Lighthouse audit
response.resetResponseLineForTesting();
await evaluateScript().handler(
{
params: {
function: `async () => {
try {
await fetch("${blockedUrl}");
return 'SUCCESS';
} catch (err) {
return err instanceof Error ? err.message : String(err);
}
}`,
},
},
response,
context,
);
assert.strictEqual(
JSON.parse(response.responseLines.at(2)!),
'Failed to fetch',
'Fetch should still be blocked after audit',
);
},
{
blockedUrlPattern,
},
);
});
it('throws error when trying to emulate network conditions while blocklist is configured', async () => {
const blockedUrlPattern = ['*://*/*'];
await withMcpContext(
async (response, context) => {
// Attempting to emulate network conditions should throw an error.
await assert.rejects(async () => {
await emulate.handler(
{
params: {
networkConditions: 'Offline',
},
page: context.getSelectedMcpPage(),
},
response,
context,
);
}, /Network throttling is not supported when network blocking \(allowlist\/blocklist\) is configured\./);
// Attempting to emulate CPU rate or other things should succeed without errors.
await emulate.handler(
{
params: {
cpuThrottlingRate: 2,
},
page: context.getSelectedMcpPage(),
},
response,
context,
);
assert.strictEqual(
response.responseLines[0],
'Emulation configured successfully',
);
},
{
blockedUrlPattern,
},
);
});
});