Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions packages/extension/src/ui/connect.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
11 changes: 10 additions & 1 deletion packages/playwright-core/src/tools/backend/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -53,6 +53,7 @@ export type ContextConfig = {
outputMaxSize?: number;
saveSession?: boolean;
secrets?: Record<string, string>;
redactUrlParams?: string[];
sharedBrowserContext?: boolean;
snapshot?: {
mode?: 'full' | 'none';
Expand Down Expand Up @@ -132,6 +133,7 @@ export class Context {
private _disposables: Disposable[] = [];

private _webmcpToolsSignature = '';
private _redactUrlParamsRegex: RegExp | undefined;

private _runningToolName: string | undefined;
private _pendingUnhandledRejections: unknown[] = [];
Expand All @@ -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);
}
Expand Down Expand Up @@ -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;
}
}
Expand Down
8 changes: 8 additions & 0 deletions packages/playwright-core/src/tools/mcp/config.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 instead
Expand Down
3 changes: 3 additions & 0 deletions packages/playwright-core/src/tools/mcp/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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>;
Expand Down Expand Up @@ -388,6 +389,7 @@ function configFromCLIOptions(cliOptions: CLIOptions): Config & { configFile?: s
codegen: 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,
Expand Down Expand Up @@ -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);
Expand Down
1 change: 1 addition & 0 deletions packages/playwright-core/src/tools/mcp/program.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.')
Expand Down
25 changes: 25 additions & 0 deletions tests/extension/extension.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -494,6 +494,31 @@ test(`bypass connection dialog with token`, async ({ browserWithExtension, start
await 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 }) => {
Expand Down
25 changes: 25 additions & 0 deletions tests/mcp/secrets.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)`,
});
});