Chrome DevTools for coding agents
feat: add configure_webauthn tool for virtual authenticators (#3276)
Mankhong Gardenada7963246c0
diff --git a/docs/configuration.md b/docs/configuration.mdindex e2abca07..712cb60f 100644--- a/docs/configuration.md+++ b/docs/configuration.md@@ -59,6 +59,11 @@ The Chrome DevTools MCP server supports the following configuration option:- **Type:** boolean- **Default:** `false`+- **`--categoryWebauthn`/ `--category-webauthn`**+ Set to true to include a tool that manages virtual WebAuthn authenticators, for testing passkey and security key flows.+ - **Type:** boolean+ - **Default:** `false`+- **`--autoConnect`/ `--auto-connect`**If specified, automatically connects to a browser (Chrome 144+) running locally from the user data directory identified by the channel param (default channel is stable). Requires the remote debugging server to be started in the Chrome instance via chrome://inspect/#remote-debugging.- **Type:** booleandiff --git a/docs/tool-reference.md b/docs/tool-reference.mdindex 55891167..a18967cd 100644--- a/docs/tool-reference.md+++ b/docs/tool-reference.md@@ -72,6 +72,8 @@- [`install_pwa`](#install_pwa)- [`launch_pwa`](#launch_pwa)- [`uninstall_pwa`](#uninstall_pwa)+- **[WebAuthn](#webauthn)** (1 tools)+ - [`configure_webauthn`](#configure_webauthn)## Input automation@@ -859,3 +861,23 @@ third-party developer tools with additional functionality. (requires flag: --cat- **manifestId** (string) **(required)**: The manifest ID of the web app: the resolved `id` member of its manifest. If `id` is omitted, it defaults to the resolved `start_url` (e.g. "https://example.com/"). See https://w3c.github.io/manifest/#id-member.---++## WebAuthn++> NOTE: The WebAuthn category is not active by default. Use the '--categoryWebauthn' flag.++### `configure_webauthn`++**Description:** Adds a virtual WebAuthn authenticator to the page. Call this before the page calls navigator.credentials. It answers navigator.credentials.create() and get() and is removed when the page closes. Omitted parameters keep their current values. Changing protocol, transport, hasResidentKey or hasUserVerification replaces the authenticator and deletes its credentials. enabled=false ignores other parameters and removes all authenticators on the page. (requires flag: --categoryWebauthn=true)++**Parameters:**++- **enabled** (boolean) **(required)**: Set to false to remove all virtual authenticators from the page.+- **pageId** (number) **(required)**: Targets a specific page by ID.+- **hasResidentKey** (boolean) _(optional)_: Whether the authenticator can store discoverable credentials (passkeys). Default: true. u2f does not support it, so it is false for u2f.+- **hasUserVerification** (boolean) _(optional)_: Whether the authenticator supports user verification (PIN or biometrics). Default: true. u2f does not support it, so it is false for u2f.+- **isUserVerified** (boolean) _(optional)_: Whether user verification succeeds. Set to false to test a failed verification. Default: true.+- **protocol** (enum: "ctap2", "u2f") _(optional)_: The authenticator protocol. Default: ctap2.+- **transport** (enum: "internal", "usb", "nfc", "ble", "hybrid") _(optional)_: "internal" is a platform authenticator such as Touch ID or Windows Hello; the others are roaming security keys. Default: internal.++---diff --git a/src/McpPage.ts b/src/McpPage.tsindex 4d74d91d..0e1cabde 100644--- a/src/McpPage.ts+++ b/src/McpPage.ts@@ -44,6 +44,8 @@ import type {MatchedStyles,Response,ScreenRecorderData,+ WebAuthnAuthenticatorConfig,+ WebAuthnAuthenticatorState,} from './tools/ToolDefinition.js';import type {EmulationSettings,@@ -53,6 +55,7 @@ import type {PrefersReducedMotion,TextSnapshotNode,} from './types.js';+import {getErrorMessage} from './utils/errorHandling.js';import {logger} from './utils/logger.js';import {getNetworkMultiplierFromString,@@ -61,6 +64,31 @@ import {type DialogAction,} from './utils/WaitForHelper.js';+const WEBAUTHN_PROTOCOLS = {+ ctap2: DevTools.Protocol.WebAuthn.AuthenticatorProtocol.Ctap2,+ u2f: DevTools.Protocol.WebAuthn.AuthenticatorProtocol.U2f,+};++const WEBAUTHN_TRANSPORTS = {+ internal: DevTools.Protocol.WebAuthn.AuthenticatorTransport.Internal,+ usb: DevTools.Protocol.WebAuthn.AuthenticatorTransport.Usb,+ nfc: DevTools.Protocol.WebAuthn.AuthenticatorTransport.Nfc,+ ble: DevTools.Protocol.WebAuthn.AuthenticatorTransport.Ble,+ hybrid: DevTools.Protocol.WebAuthn.AuthenticatorTransport.Hybrid,+};++interface WebAuthnAuthenticator {+ id: DevTools.Protocol.WebAuthn.AuthenticatorId;+ options: Omit<WebAuthnAuthenticatorState, 'credentials'>;+}++const WEBAUTHN_CREATION_OPTIONS = [+ 'protocol',+ 'transport',+ 'hasResidentKey',+ 'hasUserVerification',+] as const;+export function replaceHtmlElementsWithUids(schema: JSONSchema7Definition,): void {@@ -173,6 +201,8 @@ export class McpPage implements ContextPage {// MetadataisolatedContextName?: string;#devtoolsUniverse?: TargetUniverse;+ #webAuthnEnabled = false;+ #webAuthnAuthenticator?: WebAuthnAuthenticator;// Dialog#dialog?: Dialog;@@ -401,6 +431,134 @@ export class McpPage implements ContextPage {return this.#devtoolsUniverse;}+ getWebAuthnAuthenticator():+ Omit<WebAuthnAuthenticatorState, 'credentials'> | undefined {+ return (+ this.#webAuthnAuthenticator && {+ ...this.#webAuthnAuthenticator.options,+ }+ );+ }++ async configureWebAuthn(+ config: WebAuthnAuthenticatorConfig,+ ): Promise<WebAuthnAuthenticatorState | undefined> {+ const model = this.devtoolsUniverse?.target.model(+ DevTools.WebAuthnModel.WebAuthnModel,+ );+ if (!model) {+ throw new Error(`WebAuthn is not available for page ${this.id}.`);+ }+ const options = config.enabled+ ? this.#resolveWebAuthnOptions(config)+ : undefined;+ try {+ return await this.#applyWebAuthnConfig(model, options);+ } catch (error) {+ const orphan = this.#webAuthnAuthenticator;+ this.#webAuthnEnabled = false;+ this.#webAuthnAuthenticator = undefined;+ if (orphan) {+ try {+ await model.removeAuthenticator(orphan.id);+ } catch {+ // Already gone, e.g. another client disabled the environment.+ }+ }+ throw new Error(+ `Failed to configure WebAuthn for page ${this.id}: ${getErrorMessage(error)}`,+ {cause: error},+ );+ }+ }++ #resolveWebAuthnOptions(+ config: WebAuthnAuthenticatorConfig,+ ): WebAuthnAuthenticator['options'] {+ const current = this.#webAuthnAuthenticator?.options;+ const protocol = config.protocol ?? current?.protocol ?? 'ctap2';+ const transport = config.transport ?? current?.transport ?? 'internal';+ const isUserVerified =+ config.isUserVerified ?? current?.isUserVerified ?? true;+ if (protocol === 'u2f') {+ if (config.hasResidentKey || config.hasUserVerification) {+ throw new Error(+ `protocol 'u2f' does not support hasResidentKey or hasUserVerification. Set them to false or omit them.`,+ );+ }+ return {+ protocol,+ transport,+ hasResidentKey: false,+ hasUserVerification: false,+ isUserVerified,+ };+ }+ return {+ protocol,+ transport,+ hasResidentKey: config.hasResidentKey ?? current?.hasResidentKey ?? true,+ hasUserVerification:+ config.hasUserVerification ?? current?.hasUserVerification ?? true,+ isUserVerified,+ };+ }++ async #applyWebAuthnConfig(+ model: DevTools.WebAuthnModel.WebAuthnModel,+ options: WebAuthnAuthenticator['options'] | undefined,+ ): Promise<WebAuthnAuthenticatorState | undefined> {+ if (!options) {+ this.#webAuthnAuthenticator = undefined;+ this.#webAuthnEnabled = false;+ await model.setVirtualAuthEnvEnabled(false);+ return undefined;+ }+ if (!this.#webAuthnEnabled) {+ await model.setVirtualAuthEnvEnabled(true, false);+ this.#webAuthnEnabled = true;+ }++ const current = this.#webAuthnAuthenticator;+ let authenticator = current;+ if (+ !authenticator ||+ WEBAUTHN_CREATION_OPTIONS.some(+ key => options[key] !== authenticator?.options[key],+ )+ ) {+ if (authenticator) {+ await model.removeAuthenticator(authenticator.id);+ this.#webAuthnAuthenticator = undefined;+ }+ const id = await model.addAuthenticator({+ ...options,+ protocol: WEBAUTHN_PROTOCOLS[options.protocol],+ transport: WEBAUTHN_TRANSPORTS[options.transport],+ automaticPresenceSimulation: true,+ });+ authenticator = {id, options};+ this.#webAuthnAuthenticator = authenticator;+ } else if (+ options.isUserVerified !== authenticator.options.isUserVerified+ ) {+ await model.setUserVerified(authenticator.id, options.isUserVerified);+ authenticator.options.isUserVerified = options.isUserVerified;+ }++ const credentials = await model.getCredentials(authenticator.id);+ return {+ ...authenticator.options,+ credentials: credentials.map(credential => ({+ credentialId: credential.credentialId,+ rpId: credential.rpId,+ isResidentCredential: credential.isResidentCredential,+ userName: credential.userName,+ signCount: credential.signCount,+ })),+ };+ }+getDialog(): Dialog | undefined {if (this.#dialog?.handled) {this.#dialog = undefined;@@ -729,6 +887,7 @@ export class McpPage implements ContextPage {this.#consoleCollector?.dispose();const devtoolsUniverse = this.#devtoolsUniverse;this.#devtoolsUniverse = undefined;+ this.#webAuthnAuthenticator = undefined;devtoolsUniverse?.universe.dispose();void devtoolsUniverse?.session.detach().catch(e => {logger?.('Failed to detach DevTools session', e);diff --git a/src/McpResponse.ts b/src/McpResponse.tsindex 4a380b00..63f95081 100644--- a/src/McpResponse.ts+++ b/src/McpResponse.ts@@ -31,6 +31,7 @@ import {import {IssueFormatter} from './formatters/IssueFormatter.js';import {NetworkFormatter} from './formatters/NetworkFormatter.js';import {SnapshotFormatter} from './formatters/SnapshotFormatter.js';+import {WebAuthnFormatter} from './formatters/WebAuthnFormatter.js';import type {HeapSnapshotAggregateData,HeapSnapshotClassDiff,@@ -64,6 +65,7 @@ import type {MatchedStyles,Response,SnapshotParams,+ WebAuthnAuthenticatorState,} from './tools/ToolDefinition.js';import {type InsightName,@@ -156,6 +158,7 @@ export class McpResponse implements Response {#attachedWaitForResult?: WaitForEventsResult;#reconnectNotice = false;#devToolsComments?: CD4ACommentThread[];+ #webAuthnFormatter?: WebAuthnFormatter;get #deviceScope(): DevTools.CrUXManager.DeviceScope {return this.#page?.viewport?.isMobile ? 'PHONE' : 'DESKTOP';@@ -300,6 +303,12 @@ export class McpResponse implements Response {this.#attachedConsoleMessageId = msgid;}+ attachWebAuthnAuthenticator(+ authenticator: WebAuthnAuthenticatorState | undefined,+ ): void {+ this.#webAuthnFormatter = new WebAuthnFormatter(authenticator);+ }+attachTraceSummary(result: TraceResult): void {this.#attachedTraceSummary = result;}@@ -940,6 +949,7 @@ export class McpResponse implements Response {comments?: StructuredCommentThread[];commentsSnapshotRegenerated?: 'standard' | 'verbose';matchedStyles?: object;+ webauthnAuthenticator?: WebAuthnAuthenticatorState | null;errorMessage?: string;navigatedToUrl?: string;geolocation?: {latitude: number; longitude: number};@@ -1142,7 +1152,7 @@ Call ${handleDialog(this.#config.resolved).name} to handle it before continuing.targetInfos.get(mcpPage.targetId),);parts.push(- `${page.text}${context.isPageSelected(mcpPage) ? ' [selected]' : ''}${contextLabel}`,+ `${page.text}${context.isPageSelected(mcpPage) ? ' [selected]' : ''}${contextLabel}${formatWebAuthnLabel(mcpPage)}`,);structuredPages.push(page.structured);}@@ -1165,7 +1175,7 @@ Call ${handleDialog(this.#config.resolved).name} to handle it before continuing.targetInfos.get(mcpPage.targetId),);response.push(- `${page.text}${context.isPageSelected(mcpPage) ? ' [selected]' : ''}${contextLabel}`,+ `${page.text}${context.isPageSelected(mcpPage) ? ' [selected]' : ''}${contextLabel}${formatWebAuthnLabel(mcpPage)}`,);structuredExtensionPages.push(page.structured);}@@ -1740,6 +1750,16 @@ Call ${handleDialog(this.#config.resolved).name} to handle it before continuing.}}+ if (this.#webAuthnFormatter) {+ structuredContent.webauthnAuthenticator =+ this.#webAuthnFormatter.toJSON();+ response.push(+ compactEncode+ ? compactEncode(structuredContent.webauthnAuthenticator)+ : this.#webAuthnFormatter.toString(),+ );+ }+if (this.#cssStylesData) {const resolveUid = (backendNodeId: number): string | undefined =>this.#page?.textSnapshot?.resolveCdpElementId(backendNodeId);@@ -1888,6 +1908,18 @@ function formatPage(structured: createStructuredPage(mcpPage, context, title),};}+function getWebAuthnLabel(mcpPage: McpPage): string | undefined {+ const authenticator = mcpPage.getWebAuthnAuthenticator();+ return authenticator+ ? `${authenticator.protocol}/${authenticator.transport}`+ : undefined;+}++function formatWebAuthnLabel(mcpPage: McpPage): string {+ const label = getWebAuthnLabel(mcpPage);+ return label ? ` webauthn=${label}` : '';+}+function createStructuredPage(mcpPage: McpPage,context: McpContext,@@ -1898,6 +1930,7 @@ function createStructuredPage(title: string;selected: boolean;isolatedContext?: string;+ webauthn?: string;} {const isolatedContextName = mcpPage.isolatedContextName;const title = truncateTitle(rawTitle);@@ -1907,6 +1940,7 @@ function createStructuredPage(title: string;selected: boolean;isolatedContext?: string;+ webauthn?: string;} = {id: mcpPage.id,url: mcpPage.url(),@@ -1916,5 +1950,9 @@ function createStructuredPage(if (isolatedContextName) {entry.isolatedContext = isolatedContextName;}+ const webAuthnLabel = getWebAuthnLabel(mcpPage);+ if (webAuthnLabel) {+ entry.webauthn = webAuthnLabel;+ }return entry;}diff --git a/src/config/category-options.ts b/src/config/category-options.tsindex d227a59f..3aaf4e58 100644--- a/src/config/category-options.ts+++ b/src/config/category-options.ts@@ -120,6 +120,11 @@ const categoryOverrides: Record<'Set to true to include tools for automating Progressive Web Apps (install, launch, uninstall, and OS state). This feature is only supported with a pipe connection; autoConnect, browserUrl, and wsEndpoint are not supported.',offByDefault: true,},+ [ToolCategory.WEBAUTHN]: {+ describe:+ 'Set to true to include a tool that manages virtual WebAuthn authenticators, for testing passkey and security key flows.',+ offByDefault: true,+ },};function createOption(category: ToolCategory): CategoryOption {diff --git a/src/config/cli-options.ts b/src/config/cli-options.tsindex d8177a60..ecf71112 100644--- a/src/config/cli-options.ts+++ b/src/config/cli-options.ts@@ -250,6 +250,69 @@ export const commands: Commands = {},},},+ configure_webauthn: {+ description:+ 'Adds a virtual WebAuthn authenticator to the page. Call this before the page calls navigator.credentials. It answers navigator.credentials.create() and get() and is removed when the page closes. Omitted parameters keep their current values. Changing protocol, transport, hasResidentKey or hasUserVerification replaces the authenticator and deletes its credentials. enabled=false ignores other parameters and removes all authenticators on the page. (requires flag: --categoryWebauthn=true)',+ category: 'WebAuthn',+ args: {+ pageId: {+ name: 'pageId',+ type: 'number',+ description: 'Targets a specific page by ID.',+ required: true,+ positional: true,+ },+ enabled: {+ name: 'enabled',+ type: 'boolean',+ description:+ 'Set to false to remove all virtual authenticators from the page.',+ required: true,+ positional: true,+ },+ protocol: {+ name: 'protocol',+ type: 'string',+ description: 'The authenticator protocol. Default: ctap2.',+ required: false,+ positional: false,+ enum: ['ctap2', 'u2f'],+ },+ transport: {+ name: 'transport',+ type: 'string',+ description:+ '"internal" is a platform authenticator such as Touch ID or Windows Hello; the others are roaming security keys. Default: internal.',+ required: false,+ positional: false,+ enum: ['internal', 'usb', 'nfc', 'ble', 'hybrid'],+ },+ hasResidentKey: {+ name: 'hasResidentKey',+ type: 'boolean',+ description:+ 'Whether the authenticator can store discoverable credentials (passkeys). Default: true. u2f does not support it, so it is false for u2f.',+ required: false,+ positional: false,+ },+ hasUserVerification: {+ name: 'hasUserVerification',+ type: 'boolean',+ description:+ 'Whether the authenticator supports user verification (PIN or biometrics). Default: true. u2f does not support it, so it is false for u2f.',+ required: false,+ positional: false,+ },+ isUserVerified: {+ name: 'isUserVerified',+ type: 'boolean',+ description:+ 'Whether user verification succeeds. Set to false to test a failed verification. Default: true.',+ required: false,+ positional: false,+ },+ },+ },drag: {description: 'Drag an element onto another element',category: 'Input automation',diff --git a/src/formatters/WebAuthnFormatter.ts b/src/formatters/WebAuthnFormatter.tsnew file mode 100644index 00000000..e26ac390--- /dev/null+++ b/src/formatters/WebAuthnFormatter.ts@@ -0,0 +1,66 @@+/**+ * @license+ * Copyright 2026 Google LLC+ * SPDX-License-Identifier: Apache-2.0+ */++import type {WebAuthnAuthenticatorState} from '../tools/ToolDefinition.js';++function formatAuthenticator(+ authenticator: WebAuthnAuthenticatorState,+): string {+ const lines = [+ '## Virtual authenticator',+ `protocol=${authenticator.protocol}, transport=${authenticator.transport}, hasResidentKey=${authenticator.hasResidentKey}, hasUserVerification=${authenticator.hasUserVerification}, isUserVerified=${authenticator.isUserVerified}`,+ ];+ if (!authenticator.credentials.length) {+ lines.push('No credentials.');+ return lines.join('\n');+ }+ lines.push('### Credentials');+ for (const credential of authenticator.credentials) {+ const fields = [+ `credentialId=${credential.credentialId}`,+ `rpId=${credential.rpId ?? 'unknown'}`,+ `discoverable=${credential.isResidentCredential}`,+ `signCount=${credential.signCount}`,+ ];+ if (credential.userName) {+ fields.push(`userName=${credential.userName}`);+ }+ lines.push(`- ${fields.join(', ')}`);+ }+ return lines.join('\n');+}++export class WebAuthnFormatter {+ readonly #authenticator: WebAuthnAuthenticatorState | undefined;++ constructor(authenticator: WebAuthnAuthenticatorState | undefined) {+ this.#authenticator = authenticator;+ }++ toJSON(): WebAuthnAuthenticatorState | null {+ if (!this.#authenticator) {+ return null;+ }+ return {+ ...this.#authenticator,+ credentials: this.#authenticator.credentials.map(credential => ({+ ...credential,+ // Match PublicKeyCredential.id, which the page sees as base64url.+ credentialId: Buffer.from(credential.credentialId, 'base64').toString(+ 'base64url',+ ),+ })),+ };+ }++ toString(): string {+ const authenticator = this.toJSON();+ if (!authenticator) {+ return 'No virtual authenticator on this page.';+ }+ return formatAuthenticator(authenticator);+ }+}diff --git a/src/telemetry/flag_usage_metrics.json b/src/telemetry/flag_usage_metrics.jsonindex 7a325357..e180ea4b 100644--- a/src/telemetry/flag_usage_metrics.json+++ b/src/telemetry/flag_usage_metrics.json@@ -482,5 +482,13 @@{"name": "max_navigation_saved_present","flagType": "boolean"+ },+ {+ "name": "category_webauthn_present",+ "flagType": "boolean"+ },+ {+ "name": "category_webauthn",+ "flagType": "boolean"}]diff --git a/src/telemetry/tool_call_metrics.json b/src/telemetry/tool_call_metrics.jsonindex 923fe069..7a936753 100644--- a/src/telemetry/tool_call_metrics.json+++ b/src/telemetry/tool_call_metrics.json@@ -1363,5 +1363,38 @@"argType": "number"}]+ },+ {+ "name": "configure_webauthn",+ "args": [+ {+ "name": "page_id",+ "argType": "number"+ },+ {+ "name": "enabled",+ "argType": "boolean"+ },+ {+ "name": "protocol",+ "argType": "string"+ },+ {+ "name": "transport",+ "argType": "string"+ },+ {+ "name": "has_resident_key",+ "argType": "boolean"+ },+ {+ "name": "has_user_verification",+ "argType": "boolean"+ },+ {+ "name": "is_user_verified",+ "argType": "boolean"+ }+ ]}]diff --git a/src/tools/ToolDefinition.ts b/src/tools/ToolDefinition.tsindex 19c6674f..227f8be2 100644--- a/src/tools/ToolDefinition.ts+++ b/src/tools/ToolDefinition.ts@@ -310,6 +310,9 @@ export interface Response {options?: {requestFilePath?: string; responseFilePath?: string},): void;attachConsoleMessage(msgid: number): void;+ attachWebAuthnAuthenticator(+ authenticator: WebAuthnAuthenticatorState | undefined,+ ): void;// Allows re-using DevTools data queried by some tools.attachDevToolsData(data: DevToolsData): void;setTabId(tabId: string): void;@@ -465,6 +468,33 @@ export type BrowserlessContext = Readonly<{export type MatchedStyles = DevTools.CSSMatchedStyles.CSSMatchedStyles;+export type WebAuthnProtocol = 'ctap2' | 'u2f';+export type WebAuthnTransport = 'internal' | 'usb' | 'nfc' | 'ble' | 'hybrid';++export interface WebAuthnAuthenticatorConfig {+ enabled: boolean;+ protocol?: WebAuthnProtocol;+ transport?: WebAuthnTransport;+ hasResidentKey?: boolean;+ hasUserVerification?: boolean;+ isUserVerified?: boolean;+}++export interface WebAuthnAuthenticatorState {+ protocol: WebAuthnProtocol;+ transport: WebAuthnTransport;+ hasResidentKey: boolean;+ hasUserVerification: boolean;+ isUserVerified: boolean;+ credentials: Array<{+ credentialId: string;+ rpId?: string;+ isResidentCredential: boolean;+ userName?: string;+ signCount: number;+ }>;+}+/*** Only add methods used by tools/*.*/@@ -477,6 +507,9 @@ export type ContextPage = Readonly<{getAXNodeByUid(uid: string): TextSnapshotNode | undefined;getElementByUid(uid: string): Promise<ElementHandle<Element>>;getMatchedStylesForUid(uid: string): Promise<MatchedStyles>;+ configureWebAuthn(+ config: WebAuthnAuthenticatorConfig,+ ): Promise<WebAuthnAuthenticatorState | undefined>;/*** Returns a reqid for a cdpRequestId.diff --git a/src/tools/categories.ts b/src/tools/categories.tsindex 2c28a8e7..c60ae2c3 100644--- a/src/tools/categories.ts+++ b/src/tools/categories.ts@@ -16,6 +16,7 @@ export enum ToolCategory {MEMORY = 'memory',WEBMCP = 'experimentalWebmcp',PWA = 'pwa',+ WEBAUTHN = 'webauthn',}export const labels: Record<ToolCategory, string> = {@@ -30,4 +31,5 @@ export const labels: Record<ToolCategory, string> = {[ToolCategory.MEMORY]: 'Memory',[ToolCategory.WEBMCP]: 'WebMCP',[ToolCategory.PWA]: 'Progressive Web Apps',+ [ToolCategory.WEBAUTHN]: 'WebAuthn',};diff --git a/src/tools/tools.ts b/src/tools/tools.tsindex 1fa14267..9bd86ee9 100644--- a/src/tools/tools.ts+++ b/src/tools/tools.ts@@ -26,6 +26,7 @@ import * as slimTools from './slim/tools.js';import * as snapshotTools from './snapshot.js';import * as thirdPartyDeveloperTools from './thirdPartyDeveloper.js';import type {AnyToolDefinition} from './ToolDefinition.js';+import * as webauthnTools from './webauthn.js';import * as webmcpTools from './webmcp.js';export const createTools = (args: ParsedArguments): AnyToolDefinition[] => {@@ -48,6 +49,7 @@ export const createTools = (args: ParsedArguments): AnyToolDefinition[] => {...Object.values(slimTools),...Object.values(snapshotTools),...Object.values(thirdPartyDeveloperTools),+ ...Object.values(webauthnTools),...Object.values(webmcpTools),];diff --git a/src/tools/webauthn.ts b/src/tools/webauthn.tsnew file mode 100644index 00000000..ce752b9e--- /dev/null+++ b/src/tools/webauthn.ts@@ -0,0 +1,66 @@+/**+ * @license+ * Copyright 2026 Google LLC+ * SPDX-License-Identifier: Apache-2.0+ */++import {zod} from '../third_party/index.js';++import {ToolCategory} from './categories.js';+import {definePageTool, type PageToolFactory} from './ToolDefinition.js';++export const configureWebAuthn: PageToolFactory = definePageTool(() => ({+ name: 'configure_webauthn',+ description:+ 'Adds a virtual WebAuthn authenticator to the page. Call this before the page calls navigator.credentials. ' ++ 'It answers navigator.credentials.create() and get() and is removed when the page closes. ' ++ 'Omitted parameters keep their current values. Changing protocol, transport, hasResidentKey or hasUserVerification replaces the authenticator and deletes its credentials. ' ++ 'enabled=false ignores other parameters and removes all authenticators on the page.',+ annotations: {+ category: ToolCategory.WEBAUTHN,+ readOnlyHint: false,+ },+ schema: {+ enabled: zod+ .boolean()+ .describe(+ 'Set to false to remove all virtual authenticators from the page.',+ ),+ protocol: zod+ .enum(['ctap2', 'u2f'])+ .optional()+ .describe('The authenticator protocol. Default: ctap2.'),+ transport: zod+ .enum(['internal', 'usb', 'nfc', 'ble', 'hybrid'])+ .optional()+ .describe(+ '"internal" is a platform authenticator such as Touch ID or Windows Hello; the others are roaming security keys. Default: internal.',+ ),+ hasResidentKey: zod+ .boolean()+ .optional()+ .describe(+ 'Whether the authenticator can store discoverable credentials (passkeys). Default: true. u2f does not support it, so it is false for u2f.',+ ),+ hasUserVerification: zod+ .boolean()+ .optional()+ .describe(+ 'Whether the authenticator supports user verification (PIN or biometrics). Default: true. u2f does not support it, so it is false for u2f.',+ ),+ isUserVerified: zod+ .boolean()+ .optional()+ .describe(+ 'Whether user verification succeeds. Set to false to test a failed verification. Default: true.',+ ),+ },+ blockedByDialog: false,+ concurrency: 'page',+ verifyFilesSchema: {},+ handler: async (request, response) => {+ response.attachWebAuthnAuthenticator(+ await request.page.configureWebAuthn(request.params),+ );+ },+}));diff --git a/tests/McpPage.test.ts b/tests/McpPage.test.tsindex 67867d82..b8a7b8ef 100644--- a/tests/McpPage.test.ts+++ b/tests/McpPage.test.ts@@ -29,6 +29,9 @@ import {createMockPuppeteerPage,createMockPuppeteerTarget,createMockServerConfig,+ createMockAuthenticatorId,+ createMockTargetUniverse,+ createMockWebAuthnModel,createMockWebMCPTool,} from './mocks.js';import {serverHooks} from './server.js';@@ -2290,4 +2293,351 @@ describe('McpPage', () => {assert.doesNotThrow(() => mcpPage.throwIfDialogOpen());});});++ describe('configureWebAuthn()', () => {+ const DEFAULT_OPTIONS = {+ protocol: DevTools.Protocol.WebAuthn.AuthenticatorProtocol.Ctap2,+ transport: DevTools.Protocol.WebAuthn.AuthenticatorTransport.Internal,+ hasResidentKey: true,+ hasUserVerification: true,+ isUserVerified: true,+ automaticPresenceSimulation: true,+ };+ const CDP_ERROR = 'Could not find a virtual authenticator matching the ID';++ async function createWebAuthnPage() {+ const pptrPage = createMockPuppeteerPage();+ pptrPage.emulateFocusedPage.resolves();+ const mcpPage = new McpPage(+ createMockPuppeteerTarget({page: pptrPage}),+ 1,+ {config: createMockServerConfig(), locatorClass: Locator},+ );+ const model = createMockWebAuthnModel();+ let universe: TargetUniverse | undefined =+ createMockTargetUniverse(model);+ sinon.stub(mcpPage, 'devtoolsUniverse').get(() => universe);+ await mcpPage.init();+ return {+ mcpPage,+ model,+ detachUniverse: () => {+ universe = undefined;+ },+ };+ }++ async function assertFailsWithCdpError(+ promise: Promise<unknown>,+ ): Promise<void> {+ await assert.rejects(promise, {+ message: `Failed to configure WebAuthn for page 1: ${CDP_ERROR}`,+ });+ }++ it('creates an authenticator with defaults', async () => {+ const {mcpPage, model} = await createWebAuthnPage();+ model.addAuthenticator.resolves(createMockAuthenticatorId('auth-1'));++ const result = await mcpPage.configureWebAuthn({enabled: true});++ sinon.assert.calledOnceWithExactly(+ model.setVirtualAuthEnvEnabled,+ true,+ false,+ );+ sinon.assert.calledOnceWithExactly(+ model.addAuthenticator,+ DEFAULT_OPTIONS,+ );+ sinon.assert.calledOnceWithExactly(+ model.getCredentials,+ createMockAuthenticatorId('auth-1'),+ );+ assert.deepStrictEqual(result, {+ protocol: 'ctap2',+ transport: 'internal',+ hasResidentKey: true,+ hasUserVerification: true,+ isUserVerified: true,+ credentials: [],+ });+ assert.deepStrictEqual(mcpPage.getWebAuthnAuthenticator(), {+ protocol: 'ctap2',+ transport: 'internal',+ hasResidentKey: true,+ hasUserVerification: true,+ isUserVerified: true,+ });+ });++ it('updates isUserVerified in place and keeps omitted options', async () => {+ const {mcpPage, model} = await createWebAuthnPage();+ model.addAuthenticator.resolves(createMockAuthenticatorId('auth-1'));+ await mcpPage.configureWebAuthn({enabled: true, transport: 'usb'});++ const result = await mcpPage.configureWebAuthn({+ enabled: true,+ isUserVerified: false,+ });++ sinon.assert.calledOnceWithExactly(+ model.setVirtualAuthEnvEnabled,+ true,+ false,+ );+ sinon.assert.calledOnceWithExactly(model.addAuthenticator, {+ ...DEFAULT_OPTIONS,+ transport: DevTools.Protocol.WebAuthn.AuthenticatorTransport.Usb,+ });+ sinon.assert.notCalled(model.removeAuthenticator);+ sinon.assert.calledOnceWithExactly(+ model.setUserVerified,+ createMockAuthenticatorId('auth-1'),+ false,+ );+ assert.strictEqual(result?.transport, 'usb');+ assert.strictEqual(result.isUserVerified, false);+ });++ it('replaces the authenticator and keeps isUserVerified when a creation option changes', async () => {+ const {mcpPage, model} = await createWebAuthnPage();+ model.addAuthenticator+ .onFirstCall()+ .resolves(createMockAuthenticatorId('auth-1'));+ model.addAuthenticator+ .onSecondCall()+ .resolves(createMockAuthenticatorId('auth-2'));+ await mcpPage.configureWebAuthn({enabled: true, isUserVerified: false});++ const result = await mcpPage.configureWebAuthn({+ enabled: true,+ transport: 'nfc',+ });++ sinon.assert.calledOnceWithExactly(+ model.removeAuthenticator,+ createMockAuthenticatorId('auth-1'),+ );+ sinon.assert.calledWithExactly(model.addAuthenticator.secondCall, {+ ...DEFAULT_OPTIONS,+ transport: DevTools.Protocol.WebAuthn.AuthenticatorTransport.Nfc,+ isUserVerified: false,+ });+ sinon.assert.notCalled(model.setUserVerified);+ sinon.assert.calledWithExactly(+ model.getCredentials.secondCall,+ createMockAuthenticatorId('auth-2'),+ );+ assert.strictEqual(result?.transport, 'nfc');+ });++ it('creates a u2f authenticator without resident keys or user verification after a ctap2 one', async () => {+ const {mcpPage, model} = await createWebAuthnPage();+ model.addAuthenticator+ .onFirstCall()+ .resolves(createMockAuthenticatorId('auth-1'));+ model.addAuthenticator+ .onSecondCall()+ .resolves(createMockAuthenticatorId('auth-2'));+ await mcpPage.configureWebAuthn({enabled: true});++ const result = await mcpPage.configureWebAuthn({+ enabled: true,+ protocol: 'u2f',+ });++ sinon.assert.calledWithExactly(model.addAuthenticator.secondCall, {+ ...DEFAULT_OPTIONS,+ protocol: DevTools.Protocol.WebAuthn.AuthenticatorProtocol.U2f,+ hasResidentKey: false,+ hasUserVerification: false,+ });+ assert.strictEqual(result?.hasResidentKey, false);+ assert.strictEqual(result.hasUserVerification, false);+ });++ it('rejects hasResidentKey or hasUserVerification for u2f before calling CDP', async () => {+ const {mcpPage, model} = await createWebAuthnPage();+ model.addAuthenticator.resolves(createMockAuthenticatorId('auth-1'));+ await mcpPage.configureWebAuthn({enabled: true});+ const before = mcpPage.getWebAuthnAuthenticator();++ for (const option of ['hasResidentKey', 'hasUserVerification']) {+ await assert.rejects(+ mcpPage.configureWebAuthn({+ enabled: true,+ protocol: 'u2f',+ [option]: true,+ }),+ {+ message:+ "protocol 'u2f' does not support hasResidentKey or hasUserVerification. Set them to false or omit them.",+ },+ );+ }++ sinon.assert.calledOnce(model.addAuthenticator);+ sinon.assert.notCalled(model.removeAuthenticator);+ assert.deepStrictEqual(mcpPage.getWebAuthnAuthenticator(), before);+ });++ it('disables the virtual authenticator environment', async () => {+ const {mcpPage, model} = await createWebAuthnPage();+ model.addAuthenticator.resolves(createMockAuthenticatorId('auth-1'));+ await mcpPage.configureWebAuthn({enabled: true});++ assert.strictEqual(+ await mcpPage.configureWebAuthn({enabled: false}),+ undefined,+ );++ sinon.assert.calledWithExactly(+ model.setVirtualAuthEnvEnabled.secondCall,+ false,+ );+ sinon.assert.notCalled(model.removeAuthenticator);+ assert.strictEqual(mcpPage.getWebAuthnAuthenticator(), undefined);+ });++ it('disables the virtual authenticator environment that another client enabled', async () => {+ const {mcpPage, model} = await createWebAuthnPage();++ await mcpPage.configureWebAuthn({enabled: false});++ sinon.assert.calledOnceWithExactly(model.setVirtualAuthEnvEnabled, false);+ sinon.assert.notCalled(model.addAuthenticator);+ });++ it('lists stored credentials', async () => {+ const {mcpPage, model} = await createWebAuthnPage();+ model.addAuthenticator.resolves(createMockAuthenticatorId('auth-1'));+ model.getCredentials.resolves([+ {+ credentialId: 'Y3JlZA==',+ isResidentCredential: true,+ rpId: 'example.com',+ privateKey: 'a2V5',+ userHandle: 'dXNlcg==',+ signCount: 2,+ userName: 'alice',+ },+ ]);++ const result = await mcpPage.configureWebAuthn({enabled: true});++ assert.deepStrictEqual(result?.credentials, [+ {+ credentialId: 'Y3JlZA==',+ rpId: 'example.com',+ isResidentCredential: true,+ userName: 'alice',+ signCount: 2,+ },+ ]);+ });++ it('throws when the page has no WebAuthn model', async () => {+ const {mcpPage, detachUniverse} = await createWebAuthnPage();+ detachUniverse();++ await assert.rejects(mcpPage.configureWebAuthn({enabled: true}), {+ message: 'WebAuthn is not available for page 1.',+ });+ });++ it('throws the CDP error when enabling the environment fails', async () => {+ const {mcpPage, model} = await createWebAuthnPage();+ model.setVirtualAuthEnvEnabled.rejects(new Error(CDP_ERROR));++ await assertFailsWithCdpError(mcpPage.configureWebAuthn({enabled: true}));++ sinon.assert.notCalled(model.addAuthenticator);+ assert.strictEqual(mcpPage.getWebAuthnAuthenticator(), undefined);+ });++ it('throws the CDP error when adding the authenticator fails', async () => {+ const {mcpPage, model} = await createWebAuthnPage();+ model.addAuthenticator.rejects(new Error(CDP_ERROR));++ await assertFailsWithCdpError(mcpPage.configureWebAuthn({enabled: true}));++ sinon.assert.notCalled(model.getCredentials);+ assert.strictEqual(mcpPage.getWebAuthnAuthenticator(), undefined);+ });++ it('throws the CDP error when removing the replaced authenticator fails', async () => {+ const {mcpPage, model} = await createWebAuthnPage();+ model.addAuthenticator.resolves(createMockAuthenticatorId('auth-1'));+ await mcpPage.configureWebAuthn({enabled: true});+ model.removeAuthenticator.rejects(new Error(CDP_ERROR));++ await assertFailsWithCdpError(+ mcpPage.configureWebAuthn({enabled: true, transport: 'usb'}),+ );++ sinon.assert.calledOnce(model.addAuthenticator);+ assert.strictEqual(mcpPage.getWebAuthnAuthenticator(), undefined);+ });++ it('throws the CDP error when disabling the environment fails', async () => {+ const {mcpPage, model} = await createWebAuthnPage();+ model.setVirtualAuthEnvEnabled+ .withArgs(false)+ .rejects(new Error(CDP_ERROR));++ await assertFailsWithCdpError(+ mcpPage.configureWebAuthn({enabled: false}),+ );+ });++ it('throws the CDP error and removes the authenticator when setting isUserVerified fails', async () => {+ const {mcpPage, model} = await createWebAuthnPage();+ model.addAuthenticator.resolves(createMockAuthenticatorId('auth-1'));+ await mcpPage.configureWebAuthn({enabled: true});+ model.setUserVerified.rejects(new Error(CDP_ERROR));++ await assertFailsWithCdpError(+ mcpPage.configureWebAuthn({enabled: true, isUserVerified: false}),+ );++ sinon.assert.calledOnceWithExactly(+ model.removeAuthenticator,+ createMockAuthenticatorId('auth-1'),+ );+ assert.strictEqual(mcpPage.getWebAuthnAuthenticator(), undefined);+ });++ it('creates a new authenticator on the call after reading credentials fails', async () => {+ const {mcpPage, model} = await createWebAuthnPage();+ model.addAuthenticator+ .onFirstCall()+ .resolves(createMockAuthenticatorId('auth-1'));+ model.addAuthenticator+ .onSecondCall()+ .resolves(createMockAuthenticatorId('auth-2'));+ model.getCredentials.onFirstCall().rejects(new Error(CDP_ERROR));+ await assertFailsWithCdpError(mcpPage.configureWebAuthn({enabled: true}));++ await mcpPage.configureWebAuthn({enabled: true});++ sinon.assert.calledOnceWithExactly(+ model.removeAuthenticator,+ createMockAuthenticatorId('auth-1'),+ );+ sinon.assert.calledWithExactly(+ model.setVirtualAuthEnvEnabled.secondCall,+ true,+ false,+ );+ sinon.assert.calledWithExactly(+ model.addAuthenticator.secondCall,+ DEFAULT_OPTIONS,+ );+ sinon.assert.calledWithExactly(+ model.getCredentials.secondCall,+ createMockAuthenticatorId('auth-2'),+ );+ });+ });});diff --git a/tests/formatters/WebAuthnFormatter.test.js.snapshot b/tests/formatters/WebAuthnFormatter.test.js.snapshotnew file mode 100644index 00000000..1fa33b91--- /dev/null+++ b/tests/formatters/WebAuthnFormatter.test.js.snapshot@@ -0,0 +1,56 @@+exports[`WebAuthnFormatter > formats an authenticator with credentials toJSON 1`] = `+{+ "protocol": "ctap2",+ "transport": "usb",+ "hasResidentKey": true,+ "hasUserVerification": true,+ "isUserVerified": true,+ "credentials": [+ {+ "credentialId": "Bq4IsoJ-lZuj_w",+ "rpId": "example.com",+ "isResidentCredential": true,+ "userName": "alice",+ "signCount": 0+ },+ {+ "credentialId": "b3RoZXI",+ "isResidentCredential": false,+ "signCount": 3+ }+ ]+}+`;++exports[`WebAuthnFormatter > formats an authenticator with credentials toString 1`] = `+## Virtual authenticator+protocol=ctap2, transport=usb, hasResidentKey=true, hasUserVerification=true, isUserVerified=true+### Credentials+- credentialId=Bq4IsoJ-lZuj_w, rpId=example.com, discoverable=true, signCount=0, userName=alice+- credentialId=b3RoZXI, rpId=unknown, discoverable=false, signCount=3+`;++exports[`WebAuthnFormatter > formats an authenticator without credentials toJSON 1`] = `+{+ "protocol": "u2f",+ "transport": "nfc",+ "hasResidentKey": false,+ "hasUserVerification": false,+ "isUserVerified": false,+ "credentials": []+}+`;++exports[`WebAuthnFormatter > formats an authenticator without credentials toString 1`] = `+## Virtual authenticator+protocol=u2f, transport=nfc, hasResidentKey=false, hasUserVerification=false, isUserVerified=false+No credentials.+`;++exports[`WebAuthnFormatter > formats no authenticator toJSON 1`] = `+null+`;++exports[`WebAuthnFormatter > formats no authenticator toString 1`] = `+No virtual authenticator on this page.+`;diff --git a/tests/formatters/WebAuthnFormatter.test.ts b/tests/formatters/WebAuthnFormatter.test.tsnew file mode 100644index 00000000..2464ed13--- /dev/null+++ b/tests/formatters/WebAuthnFormatter.test.ts@@ -0,0 +1,83 @@+/**+ * @license+ * Copyright 2026 Google LLC+ * SPDX-License-Identifier: Apache-2.0+ */++import assert from 'node:assert';+import {describe, it} from 'node:test';++import {WebAuthnFormatter} from '../../src/formatters/WebAuthnFormatter.js';++describe('WebAuthnFormatter', () => {+ function formatterTest(label: string, setup: () => WebAuthnFormatter) {+ it(label + ' toString', t => {+ t.assert.snapshot(setup().toString());+ });+ it(label + ' toJSON', t => {+ t.assert.snapshot(JSON.stringify(setup().toJSON(), null, 2));+ });+ }++ formatterTest('formats no authenticator', () => {+ return new WebAuthnFormatter(undefined);+ });++ formatterTest('formats an authenticator without credentials', () => {+ return new WebAuthnFormatter({+ protocol: 'u2f',+ transport: 'nfc',+ hasResidentKey: false,+ hasUserVerification: false,+ isUserVerified: false,+ credentials: [],+ });+ });++ formatterTest('formats an authenticator with credentials', () => {+ return new WebAuthnFormatter({+ protocol: 'ctap2',+ transport: 'usb',+ hasResidentKey: true,+ hasUserVerification: true,+ isUserVerified: true,+ credentials: [+ {+ credentialId: 'Bq4IsoJ+lZuj/w==',+ rpId: 'example.com',+ isResidentCredential: true,+ userName: 'alice',+ signCount: 0,+ },+ {+ credentialId: 'b3RoZXI=',+ isResidentCredential: false,+ signCount: 3,+ },+ ],+ });+ });++ it('prints credential IDs as base64url without padding', () => {+ const formatter = new WebAuthnFormatter({+ protocol: 'ctap2',+ transport: 'internal',+ hasResidentKey: true,+ hasUserVerification: true,+ isUserVerified: true,+ credentials: [+ {+ credentialId: 'Bq4IsoJ+lZuj/w==',+ isResidentCredential: true,+ signCount: 1,+ },+ ],+ });++ assert.strictEqual(+ formatter.toJSON()?.credentials[0]?.credentialId,+ 'Bq4IsoJ-lZuj_w',+ );+ assert.match(formatter.toString(), /credentialId=Bq4IsoJ-lZuj_w,/);+ });+});diff --git a/tests/mocks.ts b/tests/mocks.tsindex f97bd523..3ae1ca65 100644--- a/tests/mocks.ts+++ b/tests/mocks.ts@@ -29,6 +29,7 @@ import sinon from 'sinon';import type {ParsedArguments} from '../src/config/mcp-options.js';import {ServerConfig} from '../src/config/ServerConfig.js';+import type {TargetUniverse} from '../src/devtools/DevtoolsUtils.js';import {McpContext} from '../src/McpContext.js';import {McpPage} from '../src/McpPage.js';import {McpResponse} from '../src/McpResponse.js';@@ -472,6 +473,7 @@ export function createMockMcpPage(});page.getWebMcpTools.returns([]);page.discoverThirdPartyDeveloperTools.resolves([]);+ page.getWebAuthnAuthenticator.returns(undefined);Object.defineProperty(page, 'pptrPage', {value: pptrPage,writable: true,@@ -578,6 +580,40 @@ export function createMockMcpContext(return context;}+export function createMockWebAuthnModel(): sinon.SinonStubbedInstance<DevTools.WebAuthnModel.WebAuthnModel> {+ const model = sinon.createStubInstance(DevTools.WebAuthnModel.WebAuthnModel);+ model.setVirtualAuthEnvEnabled.resolves();+ model.getCredentials.resolves([]);+ return model;+}++function isAuthenticatorId(+ id: unknown,+): id is DevTools.Protocol.WebAuthn.AuthenticatorId {+ return typeof id === 'string';+}++export function createMockAuthenticatorId(+ id: string,+): DevTools.Protocol.WebAuthn.AuthenticatorId {+ if (!isAuthenticatorId(id)) {+ throw new Error(`Invalid authenticator id: ${id}`);+ }+ return id;+}++export function createMockTargetUniverse(+ model: NonNullable<ReturnType<DevTools.Target['model']>>,+): TargetUniverse {+ const target = sinon.createStubInstance(DevTools.Target);+ target.model.returns(model);+ return {+ target,+ universe: sinon.createStubInstance(DevTools.Foundation.Universe.Universe),+ session: createMockCDPSession(),+ };+}+export function createMockMcpResponse(): MockMcpResponse {return sinon.createStubInstance(McpResponse);}diff --git a/tests/tools/webauthn.test.ts b/tests/tools/webauthn.test.tsnew file mode 100644index 00000000..0d637738--- /dev/null+++ b/tests/tools/webauthn.test.ts@@ -0,0 +1,175 @@+/**+ * @license+ * Copyright 2026 Google LLC+ * SPDX-License-Identifier: Apache-2.0+ */++import assert from 'node:assert';+import {describe, it} from 'node:test';++import sinon from 'sinon';++import type {McpContext} from '../../src/McpContext.js';+import type {McpResponse} from '../../src/McpResponse.js';+import type {+ WebAuthnAuthenticatorConfig,+ WebAuthnAuthenticatorState,+} from '../../src/tools/ToolDefinition.js';+import {configureWebAuthn} from '../../src/tools/webauthn.js';+import {createHandlerMocks} from '../mocks.js';+import {serverHooks} from '../server.js';+import {html, withMcpContext} from '../utils.js';++declare global {+ interface Window {+ register(): Promise<string>;+ signIn(): Promise<string>;+ }+}++describe('configure_webauthn', () => {+ it('applies the parameters and attaches the result', async () => {+ const {page, context, response, args} = createHandlerMocks();+ const state: WebAuthnAuthenticatorState = {+ protocol: 'ctap2',+ transport: 'usb',+ hasResidentKey: true,+ hasUserVerification: true,+ isUserVerified: false,+ credentials: [],+ };+ page.configureWebAuthn.resolves(state);+ const params: WebAuthnAuthenticatorConfig = {+ enabled: true,+ transport: 'usb',+ isUserVerified: false,+ };++ await configureWebAuthn(args).handler(+ {params: {...params}, page},+ response,+ context,+ );++ sinon.assert.calledOnceWithExactly(page.configureWebAuthn, params);+ sinon.assert.calledOnceWithExactly(+ response.attachWebAuthnAuthenticator,+ state,+ );+ });+});++const PASSKEY_PAGE = html`<script>+ window.register = async () => {+ const credential = await navigator.credentials.create({+ publicKey: {+ challenge: new Uint8Array(32),+ timeout: 5000,+ rp: {name: 'Test'},+ user: {+ id: new Uint8Array([1, 2, 3, 4]),+ name: '[email protected]',+ displayName: 'Alice',+ },+ pubKeyCredParams: [{type: 'public-key', alg: -7}],+ authenticatorSelection: {+ residentKey: 'required',+ userVerification: 'required',+ },+ },+ });+ return credential.id;+ };+ window.signIn = async () => {+ try {+ const credential = await navigator.credentials.get({+ publicKey: {+ challenge: new Uint8Array(32),+ timeout: 5000,+ userVerification: 'required',+ },+ });+ return credential.id;+ } catch (error) {+ return error.name;+ }+ };+</script>`;++// WebAuthn rejects IP addresses as relying party ids.+function localhostRoute(url: string): string {+ return url.replace('//127.0.0.1:', '//localhost:');+}++async function configure(+ context: McpContext,+ response: McpResponse,+ args: Parameters<typeof configureWebAuthn>[0],+ params: WebAuthnAuthenticatorConfig,+): Promise<string> {+ await configureWebAuthn(args).handler(+ {params: {...params}, page: context.getSelectedMcpPage()},+ response,+ context,+ );+ const {content} = await response.handle(context);+ const text = content.find(item => item.type === 'text');+ assert.ok(text?.type === 'text');+ return text.text;+}++describe('configure_webauthn in a browser', () => {+ const server = serverHooks();++ it('registers and signs in with a passkey, fails user verification, then drops the passkey on a transport change', async () => {+ server.addHtmlRoute('/passkey.html', PASSKEY_PAGE);+ await withMcpContext(async (response, context, args) => {+ const page = context.getSelectedMcpPage().pptrPage;+ await page.goto(localhostRoute(server.getRoute('/passkey.html')));+ assert.match(+ await configure(context, response, args, {enabled: true}),+ /protocol=ctap2, transport=internal[^\n]*\nNo credentials\./,+ );++ response.setIncludePages(true);+ const {content} = await response.handle(context);+ assert.ok(+ JSON.stringify(content).includes('[selected] webauthn=ctap2/internal'),+ );+ response.setIncludePages(false);++ const credentialId = await page.evaluate(() => window.register());+ assert.strictEqual(+ await page.evaluate(() => window.signIn()),+ credentialId,+ );++ const text = await configure(context, response, args, {+ enabled: true,+ isUserVerified: false,+ });+ assert.match(text, /isUserVerified=false/);+ assert.ok(text.includes(`credentialId=${credentialId},`));+ assert.match(text, /rpId=localhost, discoverable=true/);+ assert.match(text, /userName=alice@example\.com/);+ assert.doesNotMatch(text, /privateKey/);+ assert.strictEqual(+ await page.evaluate(() => window.signIn()),+ 'NotAllowedError',+ );++ assert.match(+ await configure(context, response, args, {+ enabled: true,+ transport: 'usb',+ }),+ /transport=usb[^\n]*\nNo credentials\./,+ );++ assert.match(+ await configure(context, response, args, {enabled: false}),+ /No virtual authenticator on this page\./,+ );+ });+ });+});