From a46d3e2e3ab5bfcdfe6b162112b6de0cdfe43f36 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Tue, 27 Oct 2026 04:04:41 +0000 Subject: [PATCH] Report non-scriptable pages with one shared result (AGE-259) chrome://, DevTools, view-source, the Chrome Web Store, extension pages, and the PDF viewer now return access "metadata-only" and the wording "metadata only, can't read or act", so agents stop treating those pages as scriptable. An http(s) PDF can still load and is reported after. Co-authored-by: werbel.ted --- CHANGELOG.md | 11 + browser-tools-mcp/src/connector/connector.ts | 66 +++- browser-tools-mcp/src/gates/capability.ts | 27 +- browser-tools-mcp/src/mcp/client.ts | 17 +- browser-tools-mcp/src/mcp/server.ts | 36 +- browser-tools-mcp/src/mcp/tool-invoke.ts | 4 + browser-tools-mcp/src/restricted-page.ts | 263 +++++++++++++++ .../test/integration/connector-flow.test.ts | 25 +- .../integration/connector-security.test.ts | 7 +- .../test/integration/restricted-page.test.ts | 307 ++++++++++++++++++ .../test/unit/capability-gates.test.ts | 48 ++- .../test/unit/restricted-page.test.ts | 104 ++++++ 12 files changed, 897 insertions(+), 18 deletions(-) create mode 100644 browser-tools-mcp/src/restricted-page.ts create mode 100644 browser-tools-mcp/test/integration/restricted-page.test.ts create mode 100644 browser-tools-mcp/test/unit/restricted-page.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index cb2a07b0..76353c59 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,16 @@ # Changelog +## Unreleased + +- **Non-scriptable pages are reported the same way everywhere.** `chrome://`, + DevTools, `view-source:`, the Chrome Web Store, extension pages, and the + built-in PDF viewer come back as metadata only (`access: "metadata-only"`, + "metadata only, can't read or act"). Navigation to those pages is refused. + An http(s) PDF can still load, and is then reported as not scriptable. Page + info and the tab list carry the same fields. Screenshot, storage, console, + network, and audits on those pages return that result instead of an empty + success. + ## 2.0.5 The `browser-tools` CLI. The packages published to npm as 2.0.4 were diff --git a/browser-tools-mcp/src/connector/connector.ts b/browser-tools-mcp/src/connector/connector.ts index 6044f38e..b161fdbf 100644 --- a/browser-tools-mcp/src/connector/connector.ts +++ b/browser-tools-mcp/src/connector/connector.ts @@ -65,6 +65,13 @@ import { type CapabilityAction, type GatePolicy, } from "../gates/capability.js"; +import { + loadsWithoutScripting, + restrictedPage, + restrictedPageFields, + restrictedPageFromExtensionError, + RestrictedPageError, +} from "../restricted-page.js"; export const SERVER_SIGNATURE = "mcp-browser-connector-24x7"; export const SERVER_VERSION = "2.0.0"; @@ -167,6 +174,12 @@ export interface TabView { isCurrent: boolean; consoleCount: number; networkCount: number; + /** Set when this tab cannot be scripted. Same fields as navigation errors. */ + access?: "metadata-only"; + message?: string; + scriptable?: false; + kind?: string; + detail?: string; } export interface ExportResult { @@ -508,11 +521,13 @@ export async function createConnector(config: ConnectorConfig = {}): Promise { const current = currentTabId !== null ? tabs.get(String(currentTabId)) : undefined; const page = store.getCurrentPage(); + const url = current?.url || page.url; res.json({ - url: current?.url || page.url, + url, tabId: currentTabId ?? page.tabId, extensionConnected: telemetryConnected(), connectedTabs: tabs.size, + ...restrictedPageFields(url), }); }); @@ -838,9 +853,16 @@ export async function createConnector(config: ConnectorConfig = {}): Promise { const { allTabs, tabId: requested, ...rest } = query; const scoped = scope(allTabs, requested); + if (scoped.tabId !== null) assertScriptable(scoped.url); const result = store.queryConsole( scoped.tabId === null ? rest : { ...rest, tabId: scoped.tabId } ); @@ -872,6 +895,7 @@ export async function createConnector(config: ConnectorConfig = {}): Promise { const { allTabs, tabId: requested, ...rest } = query; const scoped = scope(allTabs, requested); + if (scoped.tabId !== null) assertScriptable(scoped.url); const result = store.queryNetwork( scoped.tabId === null ? rest : { ...rest, tabId: scoped.tabId } ); @@ -882,6 +906,7 @@ export async function createConnector(config: ConnectorConfig = {}): Promise { const scoped = scope(options.allTabs, options.tabId); + if (scoped.tabId !== null) assertScriptable(scoped.url); return { tabId: scoped.tabId, url: scoped.url, @@ -893,6 +918,7 @@ export async function createConnector(config: ConnectorConfig = {}): Promise { const scoped = scope(options.allTabs, options.tabId); + if (scoped.tabId !== null) assertScriptable(scoped.url); return { tabId: scoped.tabId, url: scoped.url, @@ -944,6 +970,7 @@ export async function createConnector(config: ConnectorConfig = {}): Promise { - await requestFromExtension(connectionForTab(options.tabId), "refresh-tab"); + const connection = connectionForTab(options.tabId); + assertScriptable(connection.tabId !== null ? tabUrl(connection.tabId) : store.getCurrentPage().url); + await requestFromExtension(connection, "refresh-tab"); } function parseHttpUrl(raw: string): URL { @@ -1211,7 +1242,12 @@ export async function createConnector(config: ConnectorConfig = {}): Promise { - const requestedUrl = parseHttpUrl(options.url.trim()).href; + const rawUrl = options.url.trim(); + const blocked = restrictedPage(rawUrl); + if (blocked && !loadsWithoutScripting(rawUrl)) { + throw new RestrictedPageError(blocked); + } + const requestedUrl = parseHttpUrl(rawUrl).href; const tabId = resolveTabId(options.tabId); if (tabId === null) { throw new ExtensionRequestError( @@ -1234,11 +1270,21 @@ export async function createConnector(config: ConnectorConfig = {}): Promise> { - const response = await requestFromExtension(connectionForTab(options.tabId), "get-storage", { + const connection = connectionForTab(options.tabId); + assertScriptable(connection.tabId !== null ? tabUrl(connection.tabId) : store.getCurrentPage().url); + const response = await requestFromExtension(connection, "get-storage", { kinds, }); const storage = response["storage"]; @@ -1283,6 +1331,8 @@ export async function createConnector(config: ConnectorConfig = {}): Promise tab.isCurrent); const page = this.#connector.store.getCurrentPage(); + const url = current?.url || page.url; return { - url: current?.url || page.url, + url, tabId: this.#connector.getCurrentTabId() ?? page.tabId, extensionConnected: this.#connector.hasExtension(), connectedTabs: tabs.length, + ...restrictedPageFields(url), }; } @@ -235,6 +248,8 @@ export class HttpConnectorClient implements ConnectorClient { const payload = text ? (JSON.parse(text) as Record) : {}; if (!response.ok) { + const restricted = restrictedPageErrorFromPayload(payload); + if (restricted) throw restricted; const message = typeof payload["error"] === "string" ? payload["error"] : `Request failed (${response.status})`; throw new Error(message); diff --git a/browser-tools-mcp/src/mcp/server.ts b/browser-tools-mcp/src/mcp/server.ts index 674c0979..35ac4ee2 100644 --- a/browser-tools-mcp/src/mcp/server.ts +++ b/browser-tools-mcp/src/mcp/server.ts @@ -14,6 +14,12 @@ import { import { resolveEnabledTools } from "../connector/api-policy.js"; import { createLogger } from "../util/logger.js"; import { AUDIT_CATEGORIES, type AuditCategory } from "../lighthouse/types.js"; +import { + RESTRICTED_PAGE_KINDS, + RESTRICTED_PAGE_MESSAGE, + RestrictedPageError, + restrictedPageToolText, +} from "../restricted-page.js"; const log = createLogger("mcp"); @@ -70,11 +76,28 @@ function ok(structured: Record, extraContent: ToolContent[] = [ } function fail(error: unknown): ToolResult { + if (error instanceof RestrictedPageError) { + log.warn("Tool call failed:", error.message); + // Text carries the JSON. structuredContent is omitted: clients validate it + // against the success output schema and would reject this shape. + return { content: [{ type: "text", text: restrictedPageToolText(error) }], isError: true }; + } const message = error instanceof Error ? error.message : String(error); log.warn("Tool call failed:", message); return { content: [{ type: "text", text: message }], isError: true }; } +const restrictedPageOutput = { + access: z + .literal("metadata-only") + .optional() + .describe(`Set when this page cannot be scripted. The message is "${RESTRICTED_PAGE_MESSAGE}".`), + message: z.string().optional().describe("Shared wording for a page that cannot be scripted"), + scriptable: z.literal(false).optional().describe("False when the page cannot be read or acted on"), + kind: z.enum(RESTRICTED_PAGE_KINDS).optional(), + detail: z.string().optional().describe("Which kind of page cannot be scripted"), +}; + /** Offers the complete history whenever a read had to be cut short. */ function truncationLinks(result: { truncated: boolean; tabId: unknown }): ToolContent[] { if (!result.truncated) return []; @@ -251,7 +274,9 @@ const TOOLS: ToolDefinition[] = [ description: "Every browser tab that currently has DevTools open, with the tabId you can pass to any other tool. " + "Call this when a result reported otherTabs above 0, or when the user mentions a page other than the one you have been reading. " + - "The tab marked isCurrent is the one every other tool uses when you do not pass tabId.", + "The tab marked isCurrent is the one every other tool uses when you do not pass tabId. " + + "A tab on chrome://, DevTools, view-source, the Chrome Web Store, an extension page, or the PDF viewer " + + `is metadata only (access "metadata-only", "${RESTRICTED_PAGE_MESSAGE}") and cannot be scripted.`, outputSchema: { tabs: z.array(z.record(z.string(), z.unknown())), currentTabId: z.union([z.number(), z.string()]).nullable(), @@ -447,7 +472,8 @@ const TOOLS: ToolDefinition[] = [ { title: "Get current page", description: - "Which page the browser is currently on. Call this before reading telemetry so you know what the logs describe. If connectedTabs is above 1, call listBrowserTabs before assuming this is the page the user means.", + "Which page the browser is currently on. Call this before reading telemetry so you know what the logs describe. If connectedTabs is above 1, call listBrowserTabs before assuming this is the page the user means. " + + `When the page cannot be scripted, access is "metadata-only" and message is "${RESTRICTED_PAGE_MESSAGE}".`, outputSchema: { url: z.string(), tabId: z.union([z.number(), z.string()]).nullable(), @@ -456,6 +482,7 @@ const TOOLS: ToolDefinition[] = [ .number() .int() .describe("How many tabs have DevTools open. Above 1 means other pages exist."), + ...restrictedPageOutput, }, annotations: { title: "Get current page", @@ -604,7 +631,10 @@ const TOOLS: ToolDefinition[] = [ description: "Loads a URL in the chosen browser tab without focusing it or attaching the debugger. " + "Uses the tabId from listBrowserTabs. Requires the extension service worker, the popup " + - "switch, and --allow-input on browser-tools-mcp (browser-tools CLI: --allow-actions).", + "switch, and --allow-input on browser-tools-mcp (browser-tools CLI: --allow-actions). " + + "chrome://, DevTools, view-source, the Chrome Web Store, and extension pages are refused. " + + "An http(s) PDF may load, then the tool fails because the viewer cannot be scripted. " + + `The error text is JSON with access "metadata-only" and message "${RESTRICTED_PAGE_MESSAGE}".`, inputSchema: { url: z.string().describe("http(s) URL to load in the tab"), tabId: tabIdInput, diff --git a/browser-tools-mcp/src/mcp/tool-invoke.ts b/browser-tools-mcp/src/mcp/tool-invoke.ts index 6227347e..8d46ffc0 100644 --- a/browser-tools-mcp/src/mcp/tool-invoke.ts +++ b/browser-tools-mcp/src/mcp/tool-invoke.ts @@ -7,6 +7,7 @@ import { screenshotUri, } from "./resources.js"; import type { AuditCategory } from "../lighthouse/types.js"; +import { RestrictedPageError, restrictedPageToolText } from "../restricted-page.js"; export type ToolContent = | { type: "text"; text: string } @@ -42,6 +43,9 @@ function ok(structured: Record, extraContent: ToolContent[] = [ } function fail(error: unknown): ToolResult { + if (error instanceof RestrictedPageError) { + return { content: [{ type: "text", text: restrictedPageToolText(error) }], isError: true }; + } const message = error instanceof Error ? error.message : String(error); return { content: [{ type: "text", text: message }], isError: true }; } diff --git a/browser-tools-mcp/src/restricted-page.ts b/browser-tools-mcp/src/restricted-page.ts new file mode 100644 index 00000000..587d4212 --- /dev/null +++ b/browser-tools-mcp/src/restricted-page.ts @@ -0,0 +1,263 @@ +/** + * Pages an extension cannot script. + * + * Tab lists, page info, and navigation all use this shape so agents see the + * same fields everywhere (AGE-259, and AGE-584's tab list and background + * navigate). `message` is the shared wording: metadata only, the page cannot + * be read or acted on. + */ + +export const RESTRICTED_PAGE_ACCESS = "metadata-only" as const; + +export const RESTRICTED_PAGE_MESSAGE = "metadata only, can't read or act"; + +/** Chromium's built-in PDF viewer extension. Stable across Chrome releases. */ +export const CHROMIUM_PDF_VIEWER_ID = "mhjfbmdgcfjbbpaeojofohoefgiehjai"; + +export const RESTRICTED_PAGE_KINDS = [ + "chrome", + "devtools", + "view-source", + "web-store", + "pdf", + "extension", + "browser", +] as const; + +export type RestrictedPageKind = (typeof RESTRICTED_PAGE_KINDS)[number]; + +export interface RestrictedPageReport { + access: typeof RESTRICTED_PAGE_ACCESS; + message: typeof RESTRICTED_PAGE_MESSAGE; + scriptable: false; + kind: RestrictedPageKind; + /** The page that cannot be scripted. */ + url: string; + /** Which kind of page this is, in one sentence. */ + detail: string; +} + +/** Fields spread onto a tab or page record. Omitted entirely for a normal page. */ +export type RestrictedPageFields = + | { + access: typeof RESTRICTED_PAGE_ACCESS; + message: typeof RESTRICTED_PAGE_MESSAGE; + scriptable: false; + kind: RestrictedPageKind; + detail: string; + } + | Record; + +const DETAILS: Record = { + chrome: "Browser pages such as chrome:// cannot be scripted.", + devtools: "DevTools pages cannot be scripted.", + "view-source": "view-source: pages cannot be scripted.", + "web-store": "The Chrome Web Store cannot be scripted.", + pdf: "The built-in PDF viewer cannot be scripted.", + extension: "Extension pages cannot be scripted.", + browser: "This browser page cannot be scripted.", +}; + +const SCHEMES: Record = { + "chrome:": "chrome", + "chrome-untrusted:": "chrome", + "chrome-search:": "chrome", + "chrome-error:": "chrome", + "devtools:": "devtools", + "view-source:": "view-source", + "edge:": "browser", + "brave:": "browser", + "arc:": "browser", + "opera:": "browser", + "vivaldi:": "browser", + "browser:": "browser", + "about:": "browser", + "chrome-extension:": "extension", + "moz-extension:": "extension", + "safari-web-extension:": "extension", + "edge-extension:": "extension", + "data:": "browser", + "blob:": "browser", + "javascript:": "browser", +}; + +const KIND_SET = new Set(RESTRICTED_PAGE_KINDS); + +function isPdfPath(pathname: string): boolean { + return /\.pdf$/i.test(pathname.replace(/\/+$/, "")); +} + +function isWebStore(parsed: URL): boolean { + if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return false; + const host = parsed.hostname.replace(/\.$/, "").toLowerCase(); + if (host === "chromewebstore.google.com") return true; + if (host !== "chrome.google.com") return false; + const path = parsed.pathname.toLowerCase().replace(/\/+$/, ""); + return path === "/webstore" || path.startsWith("/webstore/"); +} + +function detailFor(kind: RestrictedPageKind, parsed: URL): string { + if (parsed.protocol === "chrome-error:") return "Chrome's error page cannot be scripted."; + return DETAILS[kind]; +} + +function report(kind: RestrictedPageKind, parsed: URL): RestrictedPageReport { + return { + access: RESTRICTED_PAGE_ACCESS, + message: RESTRICTED_PAGE_MESSAGE, + scriptable: false, + kind, + url: parsed.href, + detail: detailFor(kind, parsed), + }; +} + +/** + * Classifies a URL the extension cannot script, or null when it can (or the + * value is not a URL). about:blank is left alone: extensions can script it. + */ +export function restrictedPage(url: string | null | undefined): RestrictedPageReport | null { + if (url == null || url.trim() === "") return null; + let parsed: URL; + try { + parsed = new URL(url.trim()); + } catch { + return null; + } + + if (parsed.protocol === "about:" && parsed.pathname === "blank") return null; + + if ( + parsed.protocol === "chrome-extension:" && + parsed.hostname.toLowerCase() === CHROMIUM_PDF_VIEWER_ID + ) { + return report("pdf", parsed); + } + + const byScheme = SCHEMES[parsed.protocol]; + if (byScheme) return report(byScheme, parsed); + if (isWebStore(parsed)) return report("web-store", parsed); + if (isPdfPath(parsed.pathname)) return report("pdf", parsed); + return null; +} + +export function restrictedPageFields(url: string | null | undefined): RestrictedPageFields { + const found = restrictedPage(url); + if (!found) return {}; + return { + access: found.access, + message: found.message, + scriptable: false, + kind: found.kind, + detail: found.detail, + }; +} + +/** + * An http(s) PDF can still be opened in the tab. The viewer cannot be + * scripted, which is reported after the load. Every other restricted URL is + * refused before navigation. + */ +export function loadsWithoutScripting(url: string | null | undefined): boolean { + const found = restrictedPage(url); + if (!found || found.kind !== "pdf") return false; + try { + const protocol = new URL(url!.trim()).protocol; + return protocol === "http:" || protocol === "https:"; + } catch { + return false; + } +} + +const URL_IN_TEXT = + /(?:^|[\s"'`(])((?:[a-z][a-z0-9+.-]*:\/\/|view-source:)[^\s"'`<>)]*)/gi; + +/** Turns a Chrome refusal that names one of these pages into the shared report. */ +export function restrictedPageFromExtensionError(message: string): RestrictedPageReport | null { + for (const match of message.matchAll(URL_IN_TEXT)) { + const found = restrictedPage(match[1]); + if (found) return found; + } + if (/extensions gallery cannot be scripted/i.test(message)) { + return restrictedPage("https://chrome.google.com/webstore"); + } + return null; +} + +export interface RestrictedPageErrorOptions { + /** The tab already moved to this URL. */ + navigated?: boolean; + tabId?: number | string; + requestedUrl?: string; + wasDiscarded?: boolean; +} + +export class RestrictedPageError extends Error { + readonly report: RestrictedPageReport; + readonly navigated: boolean; + readonly tabId?: number | string; + readonly requestedUrl?: string; + readonly wasDiscarded?: boolean; + + constructor(found: RestrictedPageReport, options: RestrictedPageErrorOptions = {}) { + const landed = options.navigated === true; + super( + landed + ? `The tab is on ${found.url}, but it is ${found.message}. ${found.detail}` + : `${found.message}. ${found.detail}` + ); + this.name = "RestrictedPageError"; + this.report = found; + this.navigated = landed; + if (options.tabId !== undefined) this.tabId = options.tabId; + if (options.requestedUrl) this.requestedUrl = options.requestedUrl; + if (options.wasDiscarded !== undefined) this.wasDiscarded = options.wasDiscarded; + } + + /** The fields agents and the local API share. */ + toJSON(): Record { + return { + access: this.report.access, + message: this.report.message, + scriptable: false, + kind: this.report.kind, + url: this.report.url, + detail: this.report.detail, + navigated: this.navigated, + ...(this.tabId !== undefined ? { tabId: this.tabId } : {}), + ...(this.requestedUrl ? { requestedUrl: this.requestedUrl } : {}), + ...(this.navigated ? { finalUrl: this.report.url } : {}), + ...(this.wasDiscarded !== undefined ? { wasDiscarded: this.wasDiscarded } : {}), + }; + } +} + +export function restrictedPageErrorFromPayload( + payload: Record +): RestrictedPageError | null { + if (payload["code"] !== "RESTRICTED_PAGE") return null; + const kind = payload["kind"]; + const url = payload["url"]; + if (typeof kind !== "string" || !KIND_SET.has(kind) || typeof url !== "string") return null; + const found = restrictedPage(url); + const report: RestrictedPageReport = found ?? { + access: RESTRICTED_PAGE_ACCESS, + message: RESTRICTED_PAGE_MESSAGE, + scriptable: false, + kind: kind as RestrictedPageKind, + url, + detail: typeof payload["detail"] === "string" ? payload["detail"] : DETAILS[kind as RestrictedPageKind], + }; + const tabId = payload["tabId"]; + return new RestrictedPageError(report, { + navigated: payload["navigated"] === true, + ...(typeof tabId === "number" || typeof tabId === "string" ? { tabId } : {}), + ...(typeof payload["requestedUrl"] === "string" ? { requestedUrl: payload["requestedUrl"] } : {}), + ...(typeof payload["wasDiscarded"] === "boolean" ? { wasDiscarded: payload["wasDiscarded"] } : {}), + }); +} + +/** Tool text: the sentence, then the shared JSON object. */ +export function restrictedPageToolText(error: RestrictedPageError): string { + return `${error.message}\n${JSON.stringify(error.toJSON(), null, 2)}`; +} diff --git a/browser-tools-mcp/test/integration/connector-flow.test.ts b/browser-tools-mcp/test/integration/connector-flow.test.ts index c2b76553..a16a7fde 100644 --- a/browser-tools-mcp/test/integration/connector-flow.test.ts +++ b/browser-tools-mcp/test/integration/connector-flow.test.ts @@ -247,7 +247,7 @@ describe("screenshots", () => { it("surfaces an extension-side capture failure", async () => { extension = await connectExtension({ - onScreenshot: () => ({ ok: false, error: "Cannot capture devtools:// URL" }), + onScreenshot: () => ({ ok: false, error: "The tab was closed" }), }); const res = await request(connector.app) @@ -256,7 +256,28 @@ describe("screenshots", () => { .send({}); expect(res.status).toBe(502); - expect(res.body.error).toContain("devtools://"); + expect(res.body.error).toContain("tab was closed"); + }); + + it("reports a devtools capture failure as a page that cannot be scripted", async () => { + extension = await connectExtension({ + onScreenshot: () => ({ ok: false, error: "Cannot capture devtools:// URL" }), + }); + + const res = await request(connector.app) + .post("/api/screenshot") + .set("Authorization", auth()) + .send({}); + + expect(res.status).toBe(422); + expect(res.body).toMatchObject({ + code: "RESTRICTED_PAGE", + access: "metadata-only", + message: "metadata only, can't read or act", + scriptable: false, + kind: "devtools", + }); + expect(res.body.url).toContain("devtools://"); }); it("times out instead of hanging when the extension never answers", async () => { diff --git a/browser-tools-mcp/test/integration/connector-security.test.ts b/browser-tools-mcp/test/integration/connector-security.test.ts index cfe6d43c..8550974e 100644 --- a/browser-tools-mcp/test/integration/connector-security.test.ts +++ b/browser-tools-mcp/test/integration/connector-security.test.ts @@ -657,7 +657,12 @@ describe("audit destination policy", () => { .set("Authorization", `Bearer ${guarded.token}`) .send({ tabId: 11 }); expect(own.status).toBe(422); - expect(own.body.error).toMatch(/navigate to an http\(s\) page first/); + expect(own.body).toMatchObject({ + code: "RESTRICTED_PAGE", + access: "metadata-only", + message: "metadata only, can't read or act", + scriptable: false, + }); } finally { await ext.close(); } diff --git a/browser-tools-mcp/test/integration/restricted-page.test.ts b/browser-tools-mcp/test/integration/restricted-page.test.ts new file mode 100644 index 00000000..8d02b733 --- /dev/null +++ b/browser-tools-mcp/test/integration/restricted-page.test.ts @@ -0,0 +1,307 @@ +import { afterEach, describe, expect, it } from "vitest"; +import os from "node:os"; +import path from "node:path"; +import request from "supertest"; +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js"; + +import { createConnector, type Connector } from "../../src/connector/connector"; +import { HttpConnectorClient, InProcessConnectorClient } from "../../src/mcp/client"; +import { createMcpServer } from "../../src/mcp/server"; +import { invokeTool } from "../../src/mcp/tool-invoke"; +import { RESTRICTED_PAGE_MESSAGE, RestrictedPageError } from "../../src/restricted-page"; +import { FakeExtension } from "../helpers/fake-extension"; + +function payloadOf(result: { content: Array<{ type: string; text?: string }>; isError?: boolean }) { + expect(result.isError).toBe(true); + const text = result.content.find((part) => part.type === "text")?.text ?? ""; + expect(text).toContain(RESTRICTED_PAGE_MESSAGE); + return JSON.parse(text.slice(text.indexOf("{"))) as Record; +} + +describe("restricted page navigation", () => { + let connector: Connector | undefined; + let devtools: FakeExtension | undefined; + let worker: FakeExtension | undefined; + + afterEach(async () => { + await devtools?.close(); + await worker?.close(); + await connector?.close(); + devtools = undefined; + worker = undefined; + }); + + async function start(allowInput = true) { + const screenshotDir = path.join(os.tmpdir(), `bt-restricted-${Date.now()}`); + connector = await createConnector({ port: 0, screenshotDir, allowInput }); + return connector; + } + + it("refuses chrome://, DevTools, view-source, the Web Store, and extension pages before navigating", async () => { + const current = await start(); + const urls = [ + ["chrome://settings", "chrome"], + ["devtools://devtools/", "devtools"], + ["view-source:https://example.com/", "view-source"], + ["https://chromewebstore.google.com/detail/foo", "web-store"], + ["https://chrome.google.com/webstore/category/extensions", "web-store"], + ["chrome-extension://abcdefghijklmnopabcdefghijklmnop/panel.html", "extension"], + ["edge://settings", "browser"], + ] as const; + + for (const [url, kind] of urls) { + await expect(current.navigateTab({ url, tabId: 1 }), url).rejects.toBeInstanceOf(RestrictedPageError); + try { + await current.navigateTab({ url, tabId: 1 }); + } catch (error) { + expect(error).toBeInstanceOf(RestrictedPageError); + expect((error as RestrictedPageError).toJSON()).toMatchObject({ + access: "metadata-only", + message: RESTRICTED_PAGE_MESSAGE, + scriptable: false, + kind, + navigated: false, + }); + } + } + }); + + it("returns the same JSON from the local API and the HTTP client", async () => { + const current = await start(); + const response = await request(current.app) + .post("/api/navigate") + .set("Authorization", `Bearer ${current.token}`) + .send({ url: "chrome://extensions" }); + + expect(response.status).toBe(422); + expect(response.body).toMatchObject({ + code: "RESTRICTED_PAGE", + access: "metadata-only", + message: RESTRICTED_PAGE_MESSAGE, + scriptable: false, + kind: "chrome", + navigated: false, + }); + + const http = new HttpConnectorClient({ + baseUrl: `http://127.0.0.1:${current.port}`, + token: current.token, + }); + await expect(http.navigate({ url: "view-source:http://localhost/" })).rejects.toMatchObject({ + name: "RestrictedPageError", + report: { kind: "view-source", message: RESTRICTED_PAGE_MESSAGE }, + }); + }); + + it("loads an http PDF and then reports that the viewer cannot be scripted", async () => { + const current = await start(); + devtools = new FakeExtension({ port: current.port, tabId: 7 }); + let probePopup = false; + worker = new FakeExtension({ + port: current.port, + role: "worker", + onCapabilityProbe: () => ({ + popupEnabled: probePopup, + panelEnabled: false, + liveUrl: "http://127.0.0.1:3000/", + excludeOrigins: [], + }), + onNavigate: async (msg) => ({ ok: true, finalUrl: msg.url, wasDiscarded: true }), + }); + await devtools.connect(); + await worker.connect(); + worker.send({ type: "capability-state", popupEnabled: true }); + probePopup = true; + await expect.poll(async () => + (await current.checkCapability("navigate", { + tabId: 7, + destinationUrl: "http://127.0.0.1:3000/guide.pdf", + })).allowed + ).toBe(true); + + await expect( + current.navigateTab({ tabId: 7, url: "http://127.0.0.1:3000/guide.pdf" }) + ).rejects.toMatchObject({ + navigated: true, + report: { kind: "pdf", message: RESTRICTED_PAGE_MESSAGE, scriptable: false }, + tabId: 7, + requestedUrl: "http://127.0.0.1:3000/guide.pdf", + }); + expect(worker.received.some((message) => message.type === "navigate-tab")).toBe(true); + }); + + it("can leave a chrome:// tab for an allowed http page", async () => { + const current = await start(); + devtools = new FakeExtension({ port: current.port, tabId: 4 }); + let probePopup = false; + worker = new FakeExtension({ + port: current.port, + role: "worker", + onCapabilityProbe: () => ({ + popupEnabled: probePopup, + panelEnabled: false, + liveUrl: "chrome://settings/", + excludeOrigins: [], + }), + onNavigate: async (msg) => ({ ok: true, finalUrl: msg.url, wasDiscarded: false }), + }); + await devtools.connect(); + await worker.connect(); + worker.send({ type: "capability-state", popupEnabled: true }); + probePopup = true; + await expect.poll(async () => + (await current.checkCapability("navigate", { + tabId: 4, + destinationUrl: "http://127.0.0.1:3000/next", + })).allowed + ).toBe(true); + + const result = await current.navigateTab({ tabId: 4, url: "http://127.0.0.1:3000/next" }); + expect(result.finalUrl).toBe("http://127.0.0.1:3000/next"); + }); + + it("reports a redirect onto an error page or the PDF viewer", async () => { + const current = await start(); + devtools = new FakeExtension({ port: current.port, tabId: 9 }); + let probePopup = false; + worker = new FakeExtension({ + port: current.port, + role: "worker", + onCapabilityProbe: () => ({ + popupEnabled: probePopup, + panelEnabled: false, + liveUrl: "http://127.0.0.1:3000/", + excludeOrigins: [], + }), + onNavigate: () => ({ + ok: true, + finalUrl: "chrome-error://chromewebdata/", + wasDiscarded: false, + }), + }); + await devtools.connect(); + await worker.connect(); + worker.send({ type: "capability-state", popupEnabled: true }); + probePopup = true; + await expect.poll(async () => + (await current.checkCapability("navigate", { + tabId: 9, + destinationUrl: "http://127.0.0.1:9/", + })).allowed + ).toBe(true); + + await expect(current.navigateTab({ tabId: 9, url: "http://127.0.0.1:9/" })).rejects.toMatchObject({ + navigated: true, + report: { kind: "chrome", url: "chrome-error://chromewebdata/" }, + }); + }); +}); + +describe("restricted pages through MCP tools", () => { + let connector: Connector; + let extension: FakeExtension | undefined; + let client: Client; + let closeServer: () => Promise; + + afterEach(async () => { + await closeServer?.(); + await extension?.close(); + await connector?.close(); + }); + + async function start(options: { onScreenshot?: (msg: unknown) => unknown } = {}) { + const screenshotDir = path.join(os.tmpdir(), `bt-restricted-mcp-${Date.now()}`); + connector = await createConnector({ port: 0, screenshotDir, allowInput: true, requestTimeoutMs: 3_000 }); + const { server } = createMcpServer({ client: new InProcessConnectorClient(connector) }); + const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); + client = new Client({ name: "test-client", version: "1.0.0" }); + await Promise.all([server.connect(serverTransport), client.connect(clientTransport)]); + closeServer = async () => { + await client.close(); + await server.close(); + }; + extension = new FakeExtension({ port: connector.port, tabId: 3, ...options }); + await extension.connect(); + await extension.waitForWelcome(); + } + + it("annotates page info and the tab list, and fails reads with the shared JSON", async () => { + await start(); + extension!.send({ type: "page", url: "chrome://settings/" }); + + await expect + .poll(async () => { + const page = await client.callTool({ name: "getPageInfo", arguments: {} }); + return (page.structuredContent as { url?: string } | undefined)?.url; + }) + .toBe("chrome://settings/"); + + const page = await client.callTool({ name: "getPageInfo", arguments: {} }); + expect(page.isError).toBeFalsy(); + expect(page.structuredContent).toMatchObject({ + url: "chrome://settings/", + access: "metadata-only", + message: RESTRICTED_PAGE_MESSAGE, + scriptable: false, + kind: "chrome", + }); + + const tabs = await client.callTool({ name: "listBrowserTabs", arguments: {} }); + const listed = (tabs.structuredContent as { tabs: Array> }).tabs[0]; + expect(listed).toMatchObject({ + access: "metadata-only", + message: RESTRICTED_PAGE_MESSAGE, + kind: "chrome", + }); + + const logs = await client.callTool({ name: "getConsoleLogs", arguments: {} }); + expect(payloadOf(logs)).toMatchObject({ + kind: "chrome", + scriptable: false, + message: RESTRICTED_PAGE_MESSAGE, + }); + + const shot = await client.callTool({ name: "takeScreenshot", arguments: {} }); + expect(payloadOf(shot).kind).toBe("chrome"); + expect(extension!.received.some((message) => message.type === "capture-screenshot")).toBe(false); + + const audit = await client.callTool({ + name: "runSEOAudit", + arguments: { url: "devtools://devtools/" }, + }); + expect(payloadOf(audit).kind).toBe("devtools"); + }); + + it("turns Chrome's devtools capture error into the shared report", async () => { + await start({ + onScreenshot: () => ({ ok: false, error: 'Cannot access contents of url "devtools://devtools/"' }), + }); + extension!.send({ type: "page", url: "https://example.com/" }); + + await expect + .poll(async () => { + const page = await client.callTool({ name: "getPageInfo", arguments: {} }); + return (page.structuredContent as { url?: string } | undefined)?.url; + }) + .toBe("https://example.com/"); + + const shot = await client.callTool({ name: "takeScreenshot", arguments: {} }); + expect(payloadOf(shot)).toMatchObject({ kind: "devtools", scriptable: false }); + }); + + it("refuses navigateBrowser with the same JSON the CLI prints", async () => { + await start(); + const viaMcp = await client.callTool({ + name: "navigateBrowser", + arguments: { url: "chrome://settings", tabId: 3 }, + }); + expect(payloadOf(viaMcp)).toMatchObject({ kind: "chrome", navigated: false }); + + const viaCli = await invokeTool("navigateBrowser", new InProcessConnectorClient(connector), { + url: "https://chrome.google.com/webstore/detail/foo", + tabId: 3, + }); + expect(payloadOf(viaCli)).toMatchObject({ kind: "web-store", navigated: false }); + }); +}); diff --git a/browser-tools-mcp/test/unit/capability-gates.test.ts b/browser-tools-mcp/test/unit/capability-gates.test.ts index d354111c..1a501b33 100644 --- a/browser-tools-mcp/test/unit/capability-gates.test.ts +++ b/browser-tools-mcp/test/unit/capability-gates.test.ts @@ -268,10 +268,10 @@ describe("origin allowlist", () => { } }); - it("refuses a non-http URL and a URL that carries credentials", () => { + it("refuses a non-scriptable page and a URL that carries credentials", () => { expect(decideCapability("readTab", { ...open, liveUrl: "chrome://settings" })).toEqual({ allowed: false, - reason: GateReason.urlNotAllowed, + reason: GateReason.restricted, }); expect(decideCapability("click", { ...open, liveUrl: "http://user:pass@localhost:3000/" })).toEqual({ allowed: false, @@ -279,6 +279,50 @@ describe("origin allowlist", () => { }); }); + it("lets navigation leave a restricted page and still refuses acting on one", () => { + expect( + decideCapability("navigate", { + ...open, + liveUrl: "chrome://settings", + destinationUrl: "http://localhost:3000/next", + }) + ).toEqual({ allowed: true, reason: GateReason.allowed }); + + expect( + decideCapability("navigate", { + ...open, + liveUrl: "http://localhost:3000/", + destinationUrl: "devtools://devtools/", + }) + ).toEqual({ allowed: false, reason: GateReason.restricted }); + + expect( + decideCapability("navigate", { + ...open, + liveUrl: "chrome://newtab/", + destinationUrl: "https://chromewebstore.google.com/detail/ext", + }) + ).toEqual({ allowed: false, reason: GateReason.restricted }); + + expect( + decideCapability("navigate", { + ...open, + liveUrl: "http://localhost:3000/", + destinationUrl: "http://localhost:3000/manual.pdf", + }).allowed + ).toBe(true); + + expect(decideCapability("softClick", { ...open, liveUrl: "http://localhost:3000/manual.pdf" })).toEqual({ + allowed: false, + reason: GateReason.restricted, + }); + expect( + decideCapability("readTab", { ...open, liveUrl: "https://chrome.google.com/webstore/detail/ext" }) + ).toEqual({ allowed: false, reason: GateReason.restricted }); + expect(tabListed("chrome://extensions/", policy())).toBe(true); + expect(tabListed("about:blank", policy())).toBe(true); + }); + it("drops excluded origins from a tab listing and leaves the list empty by default", () => { const exclude = policy({ excludeOrigins: ["https://excluded.example"] }); expect(tabListed("https://excluded.example/inbox", exclude)).toBe(false); diff --git a/browser-tools-mcp/test/unit/restricted-page.test.ts b/browser-tools-mcp/test/unit/restricted-page.test.ts new file mode 100644 index 00000000..b3f2098b --- /dev/null +++ b/browser-tools-mcp/test/unit/restricted-page.test.ts @@ -0,0 +1,104 @@ +import { describe, expect, it } from "vitest"; +import { + CHROMIUM_PDF_VIEWER_ID, + loadsWithoutScripting, + RESTRICTED_PAGE_MESSAGE, + restrictedPage, + restrictedPageFields, + restrictedPageFromExtensionError, + RestrictedPageError, +} from "../../src/restricted-page"; + +describe("restrictedPage", () => { + it("classifies the pages an extension cannot script", () => { + const cases: Array<[string, string]> = [ + ["chrome://settings", "chrome"], + ["chrome://settings/", "chrome"], + ["chrome-untrusted://new-tab-page", "chrome"], + ["chrome-error://chromewebdata/", "chrome"], + ["devtools://devtools/bundled/inspector.html", "devtools"], + ["view-source:https://example.com/", "view-source"], + ["https://chromewebstore.google.com/detail/foo", "web-store"], + ["https://chrome.google.com/webstore/detail/foo/bar", "web-store"], + ["https://chrome.google.com/webstore", "web-store"], + ["http://localhost:3000/files/report.PDF?download=1", "pdf"], + ["https://example.com/file.pdf#page=2", "pdf"], + ["http://localhost:3000/path.pdf/", "pdf"], + [`chrome-extension://${CHROMIUM_PDF_VIEWER_ID}/index.html`, "pdf"], + ["chrome-extension://abcdefghijklmnopabcdefghijklmnop/panel.html", "extension"], + ["edge://settings", "browser"], + ["brave://flags", "browser"], + ["about:config", "browser"], + ["moz-extension://12345678-1234-1234-1234-123456789abc/page.html", "extension"], + ]; + + for (const [url, kind] of cases) { + const found = restrictedPage(url); + expect(found, url).toMatchObject({ + access: "metadata-only", + message: RESTRICTED_PAGE_MESSAGE, + scriptable: false, + kind, + }); + expect(found?.detail, url).toBeTruthy(); + } + + expect(restrictedPage("chrome-error://chromewebdata/")?.detail).toContain("error page"); + }); + + it("leaves ordinary pages and about:blank alone", () => { + for (const url of [ + "https://example.com/", + "http://localhost:3000/app", + "https://chrome.google.com/search", + "https://www.google.com/webstore", + "https://example.com/report.pdf.bak", + "https://example.com/pdf/viewer", + "about:blank", + "", + "not a url", + ]) { + expect(restrictedPage(url), url).toBeNull(); + expect(restrictedPageFields(url), url).toEqual({}); + } + }); + + it("only treats an http(s) PDF as a page that can still be opened", () => { + expect(loadsWithoutScripting("http://127.0.0.1:3000/a.pdf")).toBe(true); + expect(loadsWithoutScripting("https://example.com/a.pdf")).toBe(true); + expect(loadsWithoutScripting("chrome://settings")).toBe(false); + expect(loadsWithoutScripting(`chrome-extension://${CHROMIUM_PDF_VIEWER_ID}/index.html`)).toBe(false); + expect(loadsWithoutScripting("file:///tmp/a.pdf")).toBe(false); + }); + + it("reads Chrome's own refusal text back into the same report", () => { + expect( + restrictedPageFromExtensionError('Cannot access contents of url "devtools://devtools/"')?.kind + ).toBe("devtools"); + expect(restrictedPageFromExtensionError("Cannot access a chrome:// URL")?.kind).toBe("chrome"); + expect( + restrictedPageFromExtensionError("The extensions gallery cannot be scripted.")?.kind + ).toBe("web-store"); + expect(restrictedPageFromExtensionError("The tab was closed")).toBeNull(); + }); + + it("puts the shared wording on the error agents see", () => { + const error = new RestrictedPageError(restrictedPage("chrome://settings")!, { + navigated: true, + tabId: 7, + requestedUrl: "http://localhost:3000/", + wasDiscarded: false, + }); + expect(error.message).toContain(RESTRICTED_PAGE_MESSAGE); + expect(error.toJSON()).toMatchObject({ + access: "metadata-only", + message: RESTRICTED_PAGE_MESSAGE, + scriptable: false, + kind: "chrome", + navigated: true, + tabId: 7, + requestedUrl: "http://localhost:3000/", + finalUrl: "chrome://settings", + }); + }); +});