Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.
TypeScript automationchromechromiume2e-testingelectronend-to-end-testingfirefoxjavascriptplaywrighttesttest-automationtestingtesting-toolswebwebkit
feat(mcp): redact url parameter values in tool responses (#43258)
Pavel Feldmanaf362f2b0a80
diff --git a/packages/extension/src/ui/connect.tsx b/packages/extension/src/ui/connect.tsxindex 2b7a54a4e4..1385ee1796 100644--- a/packages/extension/src/ui/connect.tsx+++ b/packages/extension/src/ui/connect.tsx@@ -95,6 +95,12 @@ const ConnectApp: React.FC = () => {const expectedToken = getOrCreateAuthToken();const token = params.get('token');+ // With the token bypass, this page becomes the connected tab; do not expose the token in its URL.+ if (token) {+ const url = new URL(window.location.href);+ url.searchParams.delete('token');+ window.history.replaceState(null, '', url);+ }if (token === expectedToken) {await handleConnectToTab();return;diff --git a/packages/playwright-core/src/tools/backend/context.ts b/packages/playwright-core/src/tools/backend/context.tsindex a4b3dccc5f..9a04e79042 100644--- a/packages/playwright-core/src/tools/backend/context.ts+++ b/packages/playwright-core/src/tools/backend/context.ts@@ -19,7 +19,7 @@ import os from 'os';import path from 'path';import debug from 'debug';-import { escapeWithQuotes } from '@isomorphic/stringUtils';+import { escapeRegExp, escapeWithQuotes } from '@isomorphic/stringUtils';import { disposeAll } from '@isomorphic/disposable';import { eventsHelper } from '@utils/eventsHelper';import { isPathInside, isSystemDirectory, isWritable, resolveSymlinks, sanitizeForFilePath } from '@utils/fileUtils';@@ -53,6 +53,7 @@ export type ContextConfig = {outputMaxSize?: number;saveSession?: boolean;secrets?: Record<string, string>;+ redactUrlParams?: string[];sharedBrowserContext?: boolean;snapshot?: {mode?: 'full' | 'none';@@ -132,6 +133,7 @@ export class Context {private _disposables: Disposable[] = [];private _webmcpToolsSignature = '';+ private _redactUrlParamsRegex: RegExp | undefined;private _runningToolName: string | undefined;private _pendingUnhandledRejections: unknown[] = [];@@ -149,6 +151,11 @@ export class Context {this._defaultBrowserContext = browserContext;if (this.config.testIdAttribute)playwright.selectors.setTestIdAttribute(this.config.testIdAttribute);+ const redactUrlParams = this.config.redactUrlParams?.filter(Boolean);+ // Matches `name=value` after `?`, `&` or `#`, so that both query and fragment parameters are covered.+ // The value ends where a URL would end inside markdown, YAML or JSON.+ if (redactUrlParams?.length)+ this._redactUrlParamsRegex = new RegExp(`([?&#](?:${redactUrlParams.map(escapeRegExp).join('|')})=)[^&#\\s"'<>()\\[\\]\`\\\\]+`, 'gi');testDebug('create context');process.on('unhandledRejection', this._onUnhandledRejection);}@@ -511,6 +518,8 @@ export class Context {continue;text = text.replaceAll(secretValue, `<secret>${secretName}</secret>`);}+ if (this._redactUrlParamsRegex)+ text = text.replace(this._redactUrlParamsRegex, '$1<redacted>');return text;}}diff --git a/packages/playwright-core/src/tools/mcp/config.d.ts b/packages/playwright-core/src/tools/mcp/config.d.tsindex 1971b09db6..76234b472c 100644--- a/packages/playwright-core/src/tools/mcp/config.d.ts+++ b/packages/playwright-core/src/tools/mcp/config.d.ts@@ -159,6 +159,14 @@ export type Config = {*/secrets?: Record<string, string>;+ /**+ * Names of URL query and fragment parameters, for example `access_token` or `code`, whose values+ * are replaced with `<redacted>` in the tool responses. Use it for session and grant values that+ * are minted at runtime and cannot be listed in `secrets`. Like `secrets`, it is a convenience+ * and not a security feature.+ */+ redactUrlParams?: string[];+/*** The directory for automatically named output files, for example a screenshot taken without an* explicit file name. Files with an explicit name are resolved against the workspace root insteaddiff --git a/packages/playwright-core/src/tools/mcp/config.ts b/packages/playwright-core/src/tools/mcp/config.tsindex 07dc1d3a83..8f9ecee16f 100644--- a/packages/playwright-core/src/tools/mcp/config.ts+++ b/packages/playwright-core/src/tools/mcp/config.ts@@ -69,6 +69,7 @@ export type CLIOptions = {profileDirName?: string;proxyBypass?: string;proxyServer?: string;+ redactUrlParams?: string[];remoteHeader?: Record<string, string>;saveSession?: boolean;secrets?: Record<string, string>;@@ -388,6 +389,7 @@ function configFromCLIOptions(cliOptions: CLIOptions): Config & { configFile?: scodegen: cliOptions.codegen,saveSession: cliOptions.saveSession,secrets: cliOptions.secrets,+ redactUrlParams: cliOptions.redactUrlParams,sharedBrowserContext: cliOptions.sharedBrowserContext,snapshot: cliOptions.snapshotMode || cliOptions.snapshotBoxes !== undefined ? { mode: cliOptions.snapshotMode, boxes: cliOptions.snapshotBoxes } : undefined,outputDir: cliOptions.outputDir,@@ -458,6 +460,7 @@ export function configFromEnv(env?: NodeJS.ProcessEnv): Config & { configFile?:options.port = numberParser(e.PLAYWRIGHT_MCP_PORT);options.proxyBypass = envToString(e.PLAYWRIGHT_MCP_PROXY_BYPASS);options.proxyServer = envToString(e.PLAYWRIGHT_MCP_PROXY_SERVER);+ options.redactUrlParams = commaSeparatedList(e.PLAYWRIGHT_MCP_REDACT_URL_PARAMS);options.remoteHeader = headerParser(envToString(e.PLAYWRIGHT_MCP_REMOTE_HEADERS));options.secrets = dotenvFileLoader(e.PLAYWRIGHT_MCP_SECRETS_FILE);options.storageState = envToString(e.PLAYWRIGHT_MCP_STORAGE_STATE);diff --git a/packages/playwright-core/src/tools/mcp/program.ts b/packages/playwright-core/src/tools/mcp/program.tsindex 86f448f4c5..f3be1a74a8 100644--- a/packages/playwright-core/src/tools/mcp/program.ts+++ b/packages/playwright-core/src/tools/mcp/program.ts@@ -69,6 +69,7 @@ export function decorateMCPCommand(command: Command) {.option('--profile-dir-name <name>', 'name of the profile directory in the user data dir to connect to with --extension, for example "Profile 1". Defaults to the last used profile that has the extension installed.').option('--proxy-bypass <bypass>', 'comma-separated domains to bypass proxy, for example ".com,chromium.org,.domain.com"').option('--proxy-server <proxy>', 'specify proxy server, for example "http://myproxy:3128", "http://user:password@myproxy:3128" or "socks5://myproxy:8080"')+ .option('--redact-url-params <names>', 'comma-separated list of URL query and fragment parameter names, for example "access_token,code", whose values are replaced with <redacted> in the tool responses.', commaSeparatedList).addOption(new ProgramOption('--remote-header <headers...>', 'headers to send with the remote endpoint connect request, multiple can be specified.').argParser(headerParser).hideHelp()).option('--sandbox', 'enable the sandbox for all process types that are normally not sandboxed.').option('--save-session', 'Whether to save the Playwright MCP session into the output directory.')diff --git a/tests/extension/extension.spec.ts b/tests/extension/extension.spec.tsindex 250ea9192c..eab3e1670a 100644--- a/tests/extension/extension.spec.ts+++ b/tests/extension/extension.spec.ts@@ -494,6 +494,31 @@ test(`bypass connection dialog with token`, async ({ browserWithExtension, startawait expect(page.locator('.client-info')).toContainText(`Connected to "${clientName}"`);});+test(`does not expose the token in the connect page url`, {+ annotation: { type: 'issue', description: 'https://github.com/microsoft/playwright-mcp/issues/1791' },+}, async ({ browserWithExtension, startClient }) => {+ const browserContext = await browserWithExtension.launch();+ const token = await readExtensionToken(browserContext);++ const { client } = await startClient({+ args: [`--extension`],+ env: {+ PLAYWRIGHT_MCP_EXTENSION_TOKEN: token,+ PWTEST_EXTENSION_USER_DATA_DIR: browserWithExtension.userDataDir,+ },+ });++ // With the token bypass, the connect page itself becomes the connected tab.+ const response = await client.callTool({+ name: 'browser_tabs',+ arguments: { action: 'list' },+ });+ expect(response).toHaveResponse({+ result: expect.stringContaining(`chrome-extension://${extensionId}/connect.html?`),+ });+ expect(JSON.stringify(response)).not.toContain(token);+});+test(`times out when the extension rejects the token`, {annotation: { type: 'issue', description: 'https://github.com/microsoft/playwright-mcp/issues/1732' },}, async ({ startExtensionClient, server }) => {diff --git a/tests/mcp/secrets.spec.ts b/tests/mcp/secrets.spec.tsindex 266c7f34ea..d865857ea2 100644--- a/tests/mcp/secrets.spec.ts+++ b/tests/mcp/secrets.spec.ts@@ -189,3 +189,28 @@ test('empty secret value is ignored', async ({ startClient, server }) => {snapshot: expect.stringContaining(`<secret>X-PASSWORD</secret>`),});});++test('redacts url parameter values', { annotation: { type: 'issue', description: 'https://github.com/microsoft/playwright-mcp/issues/1791' } }, async ({ startClient, server }) => {+ const { client } = await startClient({+ args: ['--redact-url-params=code,access_token'],+ });++ server.setRedirect('/login', '/app?code=abc123&state=s1#access_token=jwt.payload.sig&token_type=bearer');+ server.setContent('/app?code=abc123&state=s1', `<title>App</title><a href="/next?code=def456">Next</a>`, 'text/html');++ expect(await client.callTool({+ name: 'browser_navigate',+ arguments: { url: server.PREFIX + '/login' },+ })).toHaveResponse({+ page: `- Page URL: ${server.PREFIX}/app?code=<redacted>&state=s1#access_token=<redacted>&token_type=bearer+- Page Title: App`,+ snapshot: expect.stringContaining(`/url: /next?code=<redacted>`),+ });++ expect(await client.callTool({+ name: 'browser_tabs',+ arguments: { action: 'list' },+ })).toHaveResponse({+ result: `- 0: (current) [App](${server.PREFIX}/app?code=<redacted>&state=s1#access_token=<redacted>&token_type=bearer)`,+ });+});