Skip to content

Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.

feat(credentials): add context.credentials WebAuthn virtual authenticator (#40849)

Pavel Feldman72bbd1d964a8
diff --git a/docs/src/api/class-browsercontext.md b/docs/src/api/class-browsercontext.md
index a00901d0c5..c5e504b484 100644
--- a/docs/src/api/class-browsercontext.md
+++ b/docs/src/api/class-browsercontext.md
@@ -74,6 +74,13 @@ This event is not emitted.
Playwright has ability to mock clock and passage of time.
+## property: BrowserContext.credentials
+* since: v1.61
+- type: <[Credentials]>
+
+Virtual WebAuthn authenticator for this context. Lets tests seed credentials and intercept
+`navigator.credentials.create()` / `navigator.credentials.get()` ceremonies.
+
## property: BrowserContext.debugger
* since: v1.59
- type: <[Debugger]>
diff --git a/docs/src/api/class-credentials.md b/docs/src/api/class-credentials.md
new file mode 100644
index 0000000000..59af7a54d3
--- /dev/null
+++ b/docs/src/api/class-credentials.md
@@ -0,0 +1,103 @@
+# class: Credentials
+* since: v1.61
+
+`Credentials` provides a virtual WebAuthn authenticator scoped to a [BrowserContext]. It lets tests
+seed credentials, intercept `navigator.credentials.create()` / `navigator.credentials.get()` calls
+in pages, and complete WebAuthn ceremonies without a real authenticator.
+
+Implemented in userland via an injected script, so it works across Chromium, Firefox and WebKit.
+
+**Usage**
+
+```js
+const context = await browser.newContext();
+await context.credentials.install();
+await context.credentials.create({ rpId: 'example.com' });
+const page = await context.newPage();
+await page.goto('https://example.com/login');
+// Page's navigator.credentials.get() will be answered using the seeded credential.
+```
+
+## async method: Credentials.install
+* since: v1.61
+
+Installs the virtual WebAuthn authenticator into the context, overriding
+`navigator.credentials.create()` and `navigator.credentials.get()` in all current
+and future pages. Call this before the page first touches `navigator.credentials`.
+
+Required: until `install()` is called, no interception is in place and the page sees
+the platform's native (or absent) WebAuthn behaviour. Seeding credentials with
+[`method: Credentials.create`] without `install()` populates the registry but the
+page will never see those credentials.
+
+## async method: Credentials.create
+* since: v1.61
+- returns: <[Object]>
+ * alias: VirtualCredential
+ - `id` <[string]> Base64url-encoded credential id.
+ - `rpId` <[string]> Relying party id.
+ - `userHandle` <[string]> Base64url-encoded user handle.
+ - `privateKey` <[string]> Base64url-encoded PKCS#8 (DER) private key.
+ - `publicKey` <[string]> Base64url-encoded SPKI (DER) public key.
+
+Seeds a virtual WebAuthn credential. With only `rpId`, generates a fresh ECDSA P-256 keypair,
+credential id and user handle. To import a pre-registered credential (e.g. authenticating as an
+existing test user the server already knows about), supply all four of `id`, `userHandle`,
+`privateKey` and `publicKey` together. Call [`method: Credentials.install`] before navigating to a
+page that uses WebAuthn.
+
+### param: Credentials.create.options
+* since: v1.61
+- `options` <[Object]>
+ - `rpId` <[string]> Relying party id (typically the site's effective domain).
+ - `id` ?<[string]> Base64url-encoded credential id. Auto-generated if omitted.
+ - `userHandle` ?<[string]> Base64url-encoded user handle. Auto-generated if omitted.
+ - `privateKey` ?<[string]> Base64url-encoded PKCS#8 (DER) private key. Auto-generated if omitted.
+ - `publicKey` ?<[string]> Base64url-encoded SPKI (DER) public key. Auto-generated if omitted.
+
+## async method: Credentials.delete
+* since: v1.61
+
+Removes a previously seeded credential.
+
+### param: Credentials.delete.id
+* since: v1.61
+- `id` <[string]>
+
+Base64url-encoded credential id.
+
+## async method: Credentials.get
+* since: v1.61
+- returns: <[Array]<[Object]>>
+ * alias: VirtualCredential
+ - `id` <[string]>
+ - `rpId` <[string]>
+ - `userHandle` <[string]>
+ - `privateKey` <[string]>
+ - `publicKey` <[string]>
+
+Returns seeded credentials, optionally filtered by `rpId` or `id`.
+
+### option: Credentials.get.rpId
+* since: v1.61
+- `rpId` <[string]>
+
+Only return credentials for this relying party id.
+
+### option: Credentials.get.id
+* since: v1.61
+- `id` <[string]>
+
+Only return the credential with this base64url-encoded id.
+
+## async method: Credentials.setUserVerified
+* since: v1.61
+
+Toggles whether the virtual authenticator auto-approves user-verification prompts. Useful for
+simulating a user denying biometric verification.
+
+### param: Credentials.setUserVerified.value
+* since: v1.61
+- `value` <[boolean]>
+
+`true` to auto-approve user verification (default), `false` to refuse.
diff --git a/examples/webauthn/register-and-login.mjs b/examples/webauthn/register-and-login.mjs
new file mode 100644
index 0000000000..23855358a3
--- /dev/null
+++ b/examples/webauthn/register-and-login.mjs
@@ -0,0 +1,20 @@
+import { chromium } from 'playwright';
+
+(async () => {
+ const browser = await chromium.launch({ headless: false, slowMo: 250 });
+ const context = await browser.newContext();
+ await context.credentials.install();
+ const page = await context.newPage();
+ await page.goto('https://webauthn.io/');
+ await page.locator('#input-email').fill(`pw-demo-${Date.now()}`);
+ await page.locator('#register-button').click();
+ await page.getByText(/success!.*try to authenticate/i).waitFor();
+
+ const seeded = await context.credentials.get();
+ console.log(` ✓ registered: id=${seeded[0].id.substring(0, 12)}… rpId=${seeded[0].rpId}`);
+
+ await page.locator('#login-button').click();
+ await page.getByText(/you're logged in/i).waitFor();
+ console.log(` ✓ authenticated`);
+ await browser.close();
+})();
diff --git a/examples/webauthn/seed-credential.mjs b/examples/webauthn/seed-credential.mjs
new file mode 100644
index 0000000000..b08d79d85e
--- /dev/null
+++ b/examples/webauthn/seed-credential.mjs
@@ -0,0 +1,39 @@
+// Demonstrates `context.credentials.create()` — seeding a pre-existing
+// credential into a fresh context.
+//
+// In a real test suite the keypair would live in a fixture file (saved once
+// after registering a stable test user). Here we synthesise it by registering
+// in context A, then importing into context B to authenticate without any
+// further UI interaction.
+
+import { chromium } from 'playwright';
+
+(async () => {
+ const browser = await chromium.launch({ headless: false, slowMo: 250 });
+ const username = `pw-demo-${Date.now()}`;
+
+ // Context A: register so webauthn.io stores the credential server-side.
+ const contextA = await browser.newContext();
+ await contextA.credentials.install();
+ const pageA = await contextA.newPage();
+ await pageA.goto('https://webauthn.io/');
+ await pageA.locator('#input-email').fill(username);
+ await pageA.locator('#register-button').click();
+ await pageA.getByText(/success!.*try to authenticate/i).waitFor();
+ const [registered] = await contextA.credentials.get();
+ await contextA.close();
+ console.log(` ✓ registered ${username}: id=${registered.id.substring(0, 12)}…`);
+
+ // Context B: seed the same credential. webauthn.io's home page issues a
+ // discoverable `navigator.credentials.get()` on load — the seeded credential
+ // satisfies it and the site logs us in with no clicks needed.
+ const contextB = await browser.newContext();
+ await contextB.credentials.install();
+ await contextB.credentials.create(registered);
+ const pageB = await contextB.newPage();
+ await pageB.goto('https://webauthn.io/');
+ await pageB.getByText(/you're logged in/i).waitFor();
+ console.log(` ✓ authenticated with seeded credential (no UI)`);
+
+ await browser.close();
+})();
diff --git a/examples/webauthn/user-verification.mjs b/examples/webauthn/user-verification.mjs
new file mode 100644
index 0000000000..eb681d8ec9
--- /dev/null
+++ b/examples/webauthn/user-verification.mjs
@@ -0,0 +1,41 @@
+// Demonstrates `context.credentials.setUserVerified()` — simulating a user
+// refusing biometric verification (e.g. a wrong fingerprint).
+//
+// We configure webauthn.io to require user verification, then flip the
+// authenticator's UV flag off and try to log in. The relying party sees
+// UV=0 in the assertion flags and rejects the login. Flipping UV back on
+// makes the next attempt succeed.
+
+import { chromium } from 'playwright';
+
+(async () => {
+ const browser = await chromium.launch({ headless: false, slowMo: 250 });
+ const context = await browser.newContext();
+ await context.credentials.install();
+ const page = await context.newPage();
+ await page.goto('https://webauthn.io/');
+
+ // Force the relying party to require user verification at both ends.
+ await page.locator('button:has-text("Advanced Settings")').click();
+ await page.locator('#optRegUserVerification').selectOption('required');
+ await page.locator('#optAuthUserVerification').selectOption('required');
+
+ await page.locator('#input-email').fill(`pw-demo-${Date.now()}`);
+ await page.locator('#register-button').click();
+ await page.getByText(/success!.*try to authenticate/i).waitFor();
+ console.log(` ✓ registered (UV=required)`);
+
+ // Simulate failed biometric — UV bit will be 0 in the next assertion.
+ await context.credentials.setUserVerified(false);
+ await page.locator('#login-button').click();
+ await page.getByText(/authentication failed/i).waitFor();
+ console.log(` ✓ login rejected: server got UV=0 but required UV=1`);
+
+ // Recovery: biometric succeeds, UV=1 in the assertion.
+ await context.credentials.setUserVerified(true);
+ await page.locator('#login-button').click();
+ await page.getByText(/you're logged in/i).waitFor();
+ console.log(` ✓ login succeeded after UV restored`);
+
+ await browser.close();
+})();
diff --git a/packages/injected/src/webAuthn.ts b/packages/injected/src/webAuthn.ts
new file mode 100644
index 0000000000..deb940ba32
--- /dev/null
+++ b/packages/injected/src/webAuthn.ts
@@ -0,0 +1,211 @@
+/**
+ * Copyright (c) Microsoft Corporation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+// Wire format passed through the page binding (JSON-only; binary is base64url).
+export type CreateRequest = {
+ type: 'create',
+ origin: string,
+ challenge: string,
+ rp: { id?: string, name: string },
+ user: { id: string, name: string, displayName: string },
+ pubKeyCredParams: { type: string, alg: number }[],
+ excludeCredentials?: { type: string, id: string }[],
+ userVerification?: string,
+ residentKey?: string,
+};
+
+export type GetRequest = {
+ type: 'get',
+ origin: string,
+ challenge: string,
+ rpId: string,
+ allowCredentials?: { type: string, id: string }[],
+ userVerification?: string,
+};
+
+export type CreateResponse = {
+ ok: true,
+ id: string,
+ clientDataJSON: string,
+ attestationObject: string,
+} | { ok: false, name: string, message: string };
+
+export type GetResponse = {
+ ok: true,
+ id: string,
+ clientDataJSON: string,
+ authenticatorData: string,
+ signature: string,
+ userHandle: string | null,
+} | { ok: false, name: string, message: string };
+
+type GlobalThis = typeof globalThis;
+
+export function inject(globalThis: GlobalThis) {
+ if ((globalThis as any).__pwWebAuthnInstalled)
+ return;
+ (globalThis as any).__pwWebAuthnInstalled = true;
+
+ const binding = (globalThis as any).__pwWebAuthnBinding as (payload: any) => Promise<any>;
+ if (!binding || !globalThis.navigator)
+ return;
+ if (!globalThis.navigator.credentials) {
+ Object.defineProperty(globalThis.navigator, 'credentials', {
+ value: { create: async () => null, get: async () => null },
+ writable: true,
+ configurable: true,
+ });
+ }
+
+ function toBase64Url(buf: ArrayBuffer | ArrayBufferView): string {
+ const bytes = buf instanceof ArrayBuffer ? new Uint8Array(buf) : new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
+ let s = '';
+ for (let i = 0; i < bytes.length; i++)
+ s += String.fromCharCode(bytes[i]);
+ return globalThis.btoa(s).replaceAll('+', '-').replaceAll('/', '_').replaceAll('=', '');
+ }
+
+ function fromBase64Url(s: string): ArrayBuffer {
+ let str = s.replaceAll('-', '+').replaceAll('_', '/');
+ while (str.length % 4)
+ str += '=';
+ const bin = globalThis.atob(str);
+ const out = new Uint8Array(bin.length);
+ for (let i = 0; i < bin.length; i++)
+ out[i] = bin.charCodeAt(i);
+ return out.buffer;
+ }
+
+ const PublicKeyCredentialCtor: any = (globalThis as any).PublicKeyCredential;
+ const AuthAttestationResponseCtor: any = (globalThis as any).AuthenticatorAttestationResponse;
+ const AuthAssertionResponseCtor: any = (globalThis as any).AuthenticatorAssertionResponse;
+
+ function defineReadonly(target: any, props: Record<string, any>) {
+ for (const k of Object.keys(props))
+ Object.defineProperty(target, k, { value: props[k], enumerable: true, configurable: true });
+ }
+
+ function makeAttestationResponse(clientDataJSON: ArrayBuffer, attestationObject: ArrayBuffer) {
+ const proto = AuthAttestationResponseCtor?.prototype || Object.prototype;
+ const r = Object.create(proto);
+ defineReadonly(r, { clientDataJSON, attestationObject });
+ r.getTransports = () => ['internal'];
+ r.getAuthenticatorData = () => {
+ // Extract authData from attestationObject (CBOR: { fmt, attStmt, authData }).
+ // For simplicity, return the whole attestationObject — callers rarely use this in tests.
+ return attestationObject;
+ };
+ r.getPublicKey = () => null;
+ r.getPublicKeyAlgorithm = () => -7;
+ return r;
+ }
+
+ function makeAssertionResponse(clientDataJSON: ArrayBuffer, authenticatorData: ArrayBuffer, signature: ArrayBuffer, userHandle: ArrayBuffer | null) {
+ const proto = AuthAssertionResponseCtor?.prototype || Object.prototype;
+ const r = Object.create(proto);
+ defineReadonly(r, { clientDataJSON, authenticatorData, signature, userHandle });
+ return r;
+ }
+
+ function makePublicKeyCredential(id: string, response: any) {
+ const proto = PublicKeyCredentialCtor?.prototype || Object.prototype;
+ const cred = Object.create(proto);
+ defineReadonly(cred, {
+ id,
+ rawId: fromBase64Url(id),
+ type: 'public-key',
+ authenticatorAttachment: 'platform',
+ response,
+ });
+ cred.getClientExtensionResults = () => ({});
+ cred.toJSON = () => ({ id, rawId: id, type: 'public-key', response: {} });
+ return cred;
+ }
+
+ function toBuf(x: ArrayBuffer | ArrayBufferView | undefined): ArrayBuffer {
+ if (!x)
+ return new ArrayBuffer(0);
+ if (x instanceof ArrayBuffer)
+ return x;
+ const v = x as ArrayBufferView;
+ const out = new Uint8Array(v.byteLength);
+ out.set(new Uint8Array(v.buffer as ArrayBuffer, v.byteOffset, v.byteLength));
+ return out.buffer;
+ }
+
+ function failure(name: string, message: string): never {
+ const Ctor: any = (globalThis as any).DOMException || Error;
+ throw new Ctor(message, name);
+ }
+
+ const origCreate = globalThis.navigator.credentials.create.bind(globalThis.navigator.credentials);
+ const origGet = globalThis.navigator.credentials.get.bind(globalThis.navigator.credentials);
+
+ globalThis.navigator.credentials.create = async function(options?: CredentialCreationOptions): Promise<Credential | null> {
+ if (!options || !(options as any).publicKey)
+ return origCreate(options);
+ const pk = (options as any).publicKey;
+ const req: CreateRequest = {
+ type: 'create',
+ origin: globalThis.location.origin,
+ challenge: toBase64Url(toBuf(pk.challenge)),
+ rp: { id: pk.rp?.id, name: pk.rp?.name || '' },
+ user: {
+ id: toBase64Url(toBuf(pk.user?.id)),
+ name: pk.user?.name || '',
+ displayName: pk.user?.displayName || '',
+ },
+ pubKeyCredParams: (pk.pubKeyCredParams || []).map((p: any) => ({ type: p.type, alg: p.alg })),
+ excludeCredentials: (pk.excludeCredentials || []).map((c: any) => ({ type: c.type, id: toBase64Url(toBuf(c.id)) })),
+ userVerification: pk.authenticatorSelection?.userVerification,
+ residentKey: pk.authenticatorSelection?.residentKey,
+ };
+ const result: CreateResponse = await binding(req);
+ if (!result.ok)
+ failure(result.name, result.message);
+ const resp = makeAttestationResponse(fromBase64Url(result.clientDataJSON), fromBase64Url(result.attestationObject));
+ return makePublicKeyCredential(result.id, resp);
+ };
+
+ globalThis.navigator.credentials.get = async function(options?: CredentialRequestOptions): Promise<Credential | null> {
+ if (!options || !(options as any).publicKey)
+ return origGet(options);
+ const pk = (options as any).publicKey;
+ const req: GetRequest = {
+ type: 'get',
+ origin: globalThis.location.origin,
+ challenge: toBase64Url(toBuf(pk.challenge)),
+ rpId: pk.rpId || new URL(globalThis.location.origin).hostname,
+ allowCredentials: (pk.allowCredentials || []).map((c: any) => ({ type: c.type, id: toBase64Url(toBuf(c.id)) })),
+ userVerification: pk.userVerification,
+ };
+ const result: GetResponse = await binding(req);
+ if (!result.ok)
+ failure(result.name, result.message);
+ const resp = makeAssertionResponse(
+ fromBase64Url(result.clientDataJSON),
+ fromBase64Url(result.authenticatorData),
+ fromBase64Url(result.signature),
+ result.userHandle ? fromBase64Url(result.userHandle) : null,
+ );
+ return makePublicKeyCredential(result.id, resp);
+ };
+
+ if (PublicKeyCredentialCtor) {
+ PublicKeyCredentialCtor.isUserVerifyingPlatformAuthenticatorAvailable = async () => true;
+ PublicKeyCredentialCtor.isConditionalMediationAvailable = async () => true;
+ }
+}
diff --git a/packages/isomorphic/protocolMetainfo.ts b/packages/isomorphic/protocolMetainfo.ts
index 5fa0617879..b0e779d1b0 100644
--- a/packages/isomorphic/protocolMetainfo.ts
+++ b/packages/isomorphic/protocolMetainfo.ts
@@ -107,6 +107,11 @@ export const methodMetainfo = new Map<string, MethodMetainfo>([
['BrowserContext.clockRunFor', { title: 'Run clock "{ticksNumber|ticksString}"', }],
['BrowserContext.clockSetFixedTime', { title: 'Set fixed time "{timeNumber|timeString}"', }],
['BrowserContext.clockSetSystemTime', { title: 'Set system time "{timeNumber|timeString}"', }],
+ ['BrowserContext.credentialsInstall', { title: 'Install virtual WebAuthn authenticator', }],
+ ['BrowserContext.credentialsCreate', { title: 'Create virtual credential for "{rpId}"', }],
+ ['BrowserContext.credentialsGet', { title: 'Get virtual credentials', }],
+ ['BrowserContext.credentialsDelete', { title: 'Delete virtual credential', }],
+ ['BrowserContext.credentialsSetUserVerified', { title: 'Set virtual authenticator user verified', }],
['BrowserType.launch', { title: 'Launch browser', }],
['BrowserType.launchPersistentContext', { title: 'Launch persistent context', }],
['BrowserType.connectOverCDP', { title: 'Connect over CDP', }],
diff --git a/packages/playwright-client/types/types.d.ts b/packages/playwright-client/types/types.d.ts
index 1b17367221..6939caf9d4 100644
--- a/packages/playwright-client/types/types.d.ts
+++ b/packages/playwright-client/types/types.d.ts
@@ -9907,6 +9907,12 @@ export interface BrowserContext {
*/
clock: Clock;
+ /**
+ * Virtual WebAuthn authenticator for this context. Lets tests seed credentials and intercept
+ * `navigator.credentials.create()` / `navigator.credentials.get()` ceremonies.
+ */
+ credentials: Credentials;
+
/**
* Debugger allows to pause and resume the execution.
*/
@@ -19241,6 +19247,139 @@ export interface Coverage {
}>>;
}
+/**
+ * `Credentials` provides a virtual WebAuthn authenticator scoped to a
+ * [BrowserContext](https://playwright.dev/docs/api/class-browsercontext). It lets tests seed credentials, intercept
+ * `navigator.credentials.create()` / `navigator.credentials.get()` calls in pages, and complete WebAuthn ceremonies
+ * without a real authenticator.
+ *
+ * Implemented in userland via an injected script, so it works across Chromium, Firefox and WebKit.
+ *
+ * **Usage**
+ *
+ * ```js
+ * const context = await browser.newContext();
+ * await context.credentials.install();
+ * await context.credentials.create({ rpId: 'example.com' });
+ * const page = await context.newPage();
+ * await page.goto('https://example.com/login');
+ * // Page's navigator.credentials.get() will be answered using the seeded credential.
+ * ```
+ *
+ */
+export interface Credentials {
+ /**
+ * Seeds a virtual WebAuthn credential. With only `rpId`, generates a fresh ECDSA P-256 keypair, credential id and
+ * user handle. To import a pre-registered credential (e.g. authenticating as an existing test user the server already
+ * knows about), supply all four of `id`, `userHandle`, `privateKey` and `publicKey` together. Call
+ * [credentials.install()](https://playwright.dev/docs/api/class-credentials#credentials-install) before navigating to
+ * a page that uses WebAuthn.
+ * @param options
+ */
+ create(options: {
+ /**
+ * Base64url-encoded credential id. Auto-generated if omitted.
+ */
+ id?: string;
+
+ /**
+ * Base64url-encoded PKCS#8 (DER) private key. Auto-generated if omitted.
+ */
+ privateKey?: string;
+
+ /**
+ * Base64url-encoded SPKI (DER) public key. Auto-generated if omitted.
+ */
+ publicKey?: string;
+
+ /**
+ * Relying party id (typically the site's effective domain).
+ */
+ rpId: string;
+
+ /**
+ * Base64url-encoded user handle. Auto-generated if omitted.
+ */
+ userHandle?: string;
+ }): Promise<{
+ /**
+ * Base64url-encoded credential id.
+ */
+ id: string;
+
+ /**
+ * Relying party id.
+ */
+ rpId: string;
+
+ /**
+ * Base64url-encoded user handle.
+ */
+ userHandle: string;
+
+ /**
+ * Base64url-encoded PKCS#8 (DER) private key.
+ */
+ privateKey: string;
+
+ /**
+ * Base64url-encoded SPKI (DER) public key.
+ */
+ publicKey: string;
+ }>;
+
+ /**
+ * Removes a previously seeded credential.
+ * @param id Base64url-encoded credential id.
+ */
+ delete(id: string): Promise<void>;
+
+ /**
+ * Returns seeded credentials, optionally filtered by `rpId` or `id`.
+ * @param options
+ */
+ get(options?: {
+ /**
+ * Only return the credential with this base64url-encoded id.
+ */
+ id?: string;
+
+ /**
+ * Only return credentials for this relying party id.
+ */
+ rpId?: string;
+ }): Promise<Array<{
+ id: string;
+
+ rpId: string;
+
+ userHandle: string;
+
+ privateKey: string;
+
+ publicKey: string;
+ }>>;
+
+ /**
+ * Installs the virtual WebAuthn authenticator into the context, overriding `navigator.credentials.create()` and
+ * `navigator.credentials.get()` in all current and future pages. Call this before the page first touches
+ * `navigator.credentials`.
+ *
+ * Required: until `install()` is called, no interception is in place and the page sees the platform's native (or
+ * absent) WebAuthn behaviour. Seeding credentials with
+ * [credentials.create(options)](https://playwright.dev/docs/api/class-credentials#credentials-create) without
+ * `install()` populates the registry but the page will never see those credentials.
+ */
+ install(): Promise<void>;
+
+ /**
+ * Toggles whether the virtual authenticator auto-approves user-verification prompts. Useful for simulating a user
+ * denying biometric verification.
+ * @param value `true` to auto-approve user verification (default), `false` to refuse.
+ */
+ setUserVerified(value: boolean): Promise<void>;
+}
+
/**
* API for controlling the Playwright debugger. The debugger allows pausing script execution and inspecting the page.
* Obtain the debugger instance via
diff --git a/packages/playwright-core/src/client/browserContext.ts b/packages/playwright-core/src/client/browserContext.ts
index fa903eea9e..31accbf0cb 100644
--- a/packages/playwright-core/src/client/browserContext.ts
+++ b/packages/playwright-core/src/client/browserContext.ts
@@ -25,6 +25,7 @@ import { ChannelOwner } from './channelOwner';
import { evaluationScript } from './clientHelper';
import { Clock } from './clock';
import { ConsoleMessage } from './consoleMessage';
+import { Credentials } from './credentials';
import { Debugger } from './debugger';
import { Dialog } from './dialog';
import { DisposableObject, DisposableStub } from './disposable';
@@ -73,6 +74,7 @@ export class BrowserContext extends ChannelOwner<channels.BrowserContextChannel>
readonly request: APIRequestContext;
readonly tracing: Tracing;
readonly clock: Clock;
+ readonly credentials: Credentials;
readonly _serviceWorkers = new Set<Worker>();
private _closingStatus: 'none' | 'closing' | 'closed' = 'none';
@@ -98,6 +100,7 @@ export class BrowserContext extends ChannelOwner<channels.BrowserContextChannel>
this.request = APIRequestContext.from(initializer.requestContext);
this.request._timeoutSettings = this._timeoutSettings;
this.clock = new Clock(this);
+ this.credentials = new Credentials(this);
this._channel.on('bindingCall', ({ binding }) => this._onBinding(BindingCall.from(binding)));
this._channel.on('close', () => this._onClose());
diff --git a/packages/playwright-core/src/client/credentials.ts b/packages/playwright-core/src/client/credentials.ts
new file mode 100644
index 0000000000..3d9db076d4
--- /dev/null
+++ b/packages/playwright-core/src/client/credentials.ts
@@ -0,0 +1,49 @@
+/**
+ * Copyright (c) Microsoft Corporation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { BrowserContext } from './browserContext';
+import type * as api from '../../types/types';
+import type * as channels from '@protocol/channels';
+
+export class Credentials implements api.Credentials {
+ private _browserContext: BrowserContext;
+
+ constructor(browserContext: BrowserContext) {
+ this._browserContext = browserContext;
+ }
+
+ async install(): Promise<void> {
+ await this._browserContext._channel.credentialsInstall({});
+ }
+
+ async create(options: channels.BrowserContextCredentialsCreateParams): Promise<channels.VirtualCredential> {
+ const { credential } = await this._browserContext._channel.credentialsCreate(options);
+ return credential;
+ }
+
+ async get(options: channels.BrowserContextCredentialsGetParams = {}): Promise<channels.VirtualCredential[]> {
+ const { credentials } = await this._browserContext._channel.credentialsGet(options);
+ return credentials;
+ }
+
+ async delete(id: string): Promise<void> {
+ await this._browserContext._channel.credentialsDelete({ id });
+ }
+
+ async setUserVerified(value: boolean): Promise<void> {
+ await this._browserContext._channel.credentialsSetUserVerified({ value });
+ }
+}
diff --git a/packages/playwright-core/src/protocol/validator.ts b/packages/playwright-core/src/protocol/validator.ts
index c2e1b77177..ccfddb497a 100644
--- a/packages/playwright-core/src/protocol/validator.ts
+++ b/packages/playwright-core/src/protocol/validator.ts
@@ -927,6 +927,33 @@ scheme.BrowserContextClockSetSystemTimeParams = tObject({
timeString: tOptional(tString),
});
scheme.BrowserContextClockSetSystemTimeResult = tOptional(tObject({}));
+scheme.BrowserContextCredentialsInstallParams = tOptional(tObject({}));
+scheme.BrowserContextCredentialsInstallResult = tOptional(tObject({}));
+scheme.BrowserContextCredentialsCreateParams = tObject({
+ rpId: tString,
+ id: tOptional(tString),
+ userHandle: tOptional(tString),
+ privateKey: tOptional(tString),
+ publicKey: tOptional(tString),
+});
+scheme.BrowserContextCredentialsCreateResult = tObject({
+ credential: tType('VirtualCredential'),
+});
+scheme.BrowserContextCredentialsGetParams = tObject({
+ rpId: tOptional(tString),
+ id: tOptional(tString),
+});
+scheme.BrowserContextCredentialsGetResult = tObject({
+ credentials: tArray(tType('VirtualCredential')),
+});
+scheme.BrowserContextCredentialsDeleteParams = tObject({
+ id: tString,
+});
+scheme.BrowserContextCredentialsDeleteResult = tOptional(tObject({}));
+scheme.BrowserContextCredentialsSetUserVerifiedParams = tObject({
+ value: tBoolean,
+});
+scheme.BrowserContextCredentialsSetUserVerifiedResult = tOptional(tObject({}));
scheme.BrowserTypeInitializer = tObject({
executablePath: tString,
name: tString,
@@ -3003,6 +3030,13 @@ scheme.StackFrame = tObject({
column: tInt,
function: tOptional(tString),
});
+scheme.VirtualCredential = tObject({
+ id: tString,
+ rpId: tString,
+ userHandle: tString,
+ privateKey: tString,
+ publicKey: tString,
+});
scheme.Point = tObject({
x: tFloat,
y: tFloat,
diff --git a/packages/playwright-core/src/server/browserContext.ts b/packages/playwright-core/src/server/browserContext.ts
index cf687c5683..1124acb9f9 100644
--- a/packages/playwright-core/src/server/browserContext.ts
+++ b/packages/playwright-core/src/server/browserContext.ts
@@ -20,6 +20,7 @@ import fs from 'fs';
import { rewriteErrorMessage } from '@isomorphic/stackTrace';
import { debugMode, isUnderTest } from '@utils/debug';
import { Clock } from './clock';
+import { Credentials } from './credentials';
import { Debugger } from './debugger';
import { DialogManager } from './dialog';
import { BrowserContextAPIRequestContext } from './fetch';
@@ -110,6 +111,7 @@ export abstract class BrowserContext<EM extends EventMap = EventMap> extends Sdk
private _debugger!: Debugger;
_closeReason: string | undefined;
readonly clock: Clock;
+ readonly credentials: Credentials;
_clientCertificatesProxy: ClientCertificatesProxy | undefined;
private _playwrightBindingExposed?: Promise<void>;
readonly dialogManager: DialogManager;
@@ -128,6 +130,7 @@ export abstract class BrowserContext<EM extends EventMap = EventMap> extends Sdk
this.fetchRequest = new BrowserContextAPIRequestContext(this);
this.tracing = new Tracing(this, browser.options.tracesDir);
this.clock = new Clock(this);
+ this.credentials = new Credentials(this);
this.dialogManager = new DialogManager(this.instrumentation);
}
@@ -238,6 +241,7 @@ export abstract class BrowserContext<EM extends EventMap = EventMap> extends Sdk
// Note: we only need to reset properties from the "paramsThatAllowContextReuse" list.
// All other properties force a new context.
await this.clock.uninstall(progress);
+ await this.credentials.dispose(progress);
await progress.race(this.setUserAgent(this._options.userAgent));
await progress.race(this.doUpdateDefaultEmulatedMedia());
await progress.race(this.doUpdateDefaultViewport());
diff --git a/packages/playwright-core/src/server/credentials.ts b/packages/playwright-core/src/server/credentials.ts
new file mode 100644
index 0000000000..43702a1997
--- /dev/null
+++ b/packages/playwright-core/src/server/credentials.ts
@@ -0,0 +1,291 @@
+/**
+ * Copyright (c) Microsoft Corporation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import crypto from 'crypto';
+
+import * as rawWebAuthnSource from '../generated/webAuthnSource';
+import { nullProgress } from './progress';
+
+import type { BrowserContext } from './browserContext';
+import type { InitScript } from './page';
+import type { Progress } from '@protocol/progress';
+
+const kBindingName = '__pwWebAuthnBinding';
+const kAuthenticatorAAGUID = Buffer.alloc(16); // All-zero AAGUID for the virtual authenticator.
+
+export type VirtualCredential = {
+ id: string; // base64url credentialId
+ rpId: string;
+ userHandle: string; // base64url
+ privateKey: string; // base64url(DER PKCS#8)
+ publicKey: string; // base64url(DER SPKI)
+};
+
+type CredentialRecord = VirtualCredential & {
+ signCount: number;
+ isResident: boolean;
+};
+
+export class Credentials {
+ private _browserContext: BrowserContext;
+ private _initScripts: InitScript[] = [];
+ private _installed = false;
+ private _registry = new Map<string, CredentialRecord>();
+ private _userVerified = true;
+
+ constructor(browserContext: BrowserContext) {
+ this._browserContext = browserContext;
+ }
+
+ async create(options: {
+ rpId: string,
+ id?: string,
+ userHandle?: string,
+ privateKey?: string,
+ publicKey?: string,
+ }): Promise<VirtualCredential> {
+ let privateKey = options.privateKey;
+ let publicKey = options.publicKey;
+ if (!privateKey || !publicKey) {
+ const pair = crypto.generateKeyPairSync('ec', { namedCurve: 'P-256' });
+ privateKey = bufToB64Url(pair.privateKey.export({ format: 'der', type: 'pkcs8' }) as Buffer);
+ publicKey = bufToB64Url(pair.publicKey.export({ format: 'der', type: 'spki' }) as Buffer);
+ }
+ const record: CredentialRecord = {
+ id: options.id || randomBase64Url(16),
+ rpId: options.rpId,
+ userHandle: options.userHandle || randomBase64Url(16),
+ privateKey,
+ publicKey,
+ signCount: 0,
+ isResident: true,
+ };
+ this._registry.set(record.id, record);
+ return toPublic(record);
+ }
+
+ async get(filter?: { rpId?: string, id?: string }): Promise<VirtualCredential[]> {
+ return [...this._registry.values()].filter(c => {
+ if (filter?.rpId && c.rpId !== filter.rpId)
+ return false;
+ if (filter?.id && c.id !== filter.id)
+ return false;
+ return true;
+ }).map(toPublic);
+ }
+
+ async delete(id: string): Promise<void> {
+ this._registry.delete(id);
+ }
+
+ setUserVerified(value: boolean) {
+ this._userVerified = value;
+ }
+
+ async dispose(progress: Progress) {
+ await progress.race(Promise.all(this._initScripts.map(s => s.dispose())));
+ this._initScripts = [];
+ this._installed = false;
+ this._registry.clear();
+ }
+
+ async install(progress: Progress) {
+ if (this._installed)
+ return;
+ this._installed = true;
+ await this._browserContext.exposeBinding(progress, kBindingName, async (_source, payload: any) => {
+ try {
+ if (payload?.type === 'create')
+ return await this._handleCreate(payload);
+ if (payload?.type === 'get')
+ return this._handleGet(payload);
+ } catch (e) {
+ return { ok: false, name: 'NotAllowedError', message: (e as Error).message };
+ }
+ return { ok: false, name: 'NotAllowedError', message: 'Unknown WebAuthn request' };
+ });
+ const script = `(() => {
+ const module = {};
+ ${rawWebAuthnSource.source}
+ module.exports.inject()(globalThis);
+ })();`;
+ const initScript = await this._browserContext.addInitScript(nullProgress, script);
+ this._initScripts.push(initScript);
+ await progress.race(this._browserContext.safeNonStallingEvaluateInAllFrames(script, 'main', { throwOnJSErrors: false }));
+ }
+
+ private async _handleCreate(req: any) {
+ const rpId = req.rp?.id || new URL(req.origin).hostname;
+ const userHandle = req.user.id; // base64url
+ // Check exclude list: if a credential matches, refuse.
+ if (req.excludeCredentials?.length) {
+ for (const desc of req.excludeCredentials) {
+ if (this._registry.has(desc.id))
+ return { ok: false, name: 'InvalidStateError', message: 'Credential excluded' };
+ }
+ }
+ const pair = crypto.generateKeyPairSync('ec', { namedCurve: 'P-256' });
+ const privateKey = bufToB64Url(pair.privateKey.export({ format: 'der', type: 'pkcs8' }) as Buffer);
+ const publicKey = bufToB64Url(pair.publicKey.export({ format: 'der', type: 'spki' }) as Buffer);
+ const credentialId = crypto.randomBytes(16);
+ const credentialIdB64 = bufToB64Url(credentialId);
+ const record: CredentialRecord = {
+ id: credentialIdB64,
+ rpId,
+ userHandle,
+ privateKey,
+ publicKey,
+ signCount: 0,
+ isResident: req.residentKey === 'required' || req.residentKey === 'preferred',
+ };
+ this._registry.set(credentialIdB64, record);
+
+ const clientDataJSON = Buffer.from(JSON.stringify({
+ type: 'webauthn.create',
+ challenge: req.challenge,
+ origin: req.origin,
+ crossOrigin: false,
+ }));
+ const rpIdHash = crypto.createHash('sha256').update(rpId).digest();
+ const flags = 0x01 | (this._userVerified ? 0x04 : 0) | 0x40; // UP | UV? | AT
+ const signCountBuf = u32ToBytes(record.signCount);
+ const cosePublicKey = encodeCoseEs256PublicKey(pair.publicKey);
+ const credIdLenBuf = Buffer.from([(credentialId.length >> 8) & 0xff, credentialId.length & 0xff]);
+ const attestedCredentialData = Buffer.concat([kAuthenticatorAAGUID, credIdLenBuf, credentialId, cosePublicKey]);
+ const authData = Buffer.concat([rpIdHash, Buffer.from([flags]), signCountBuf, attestedCredentialData]);
+ const attestationObject = encodeAttestationObjectNone(authData);
+ return {
+ ok: true,
+ id: credentialIdB64,
+ clientDataJSON: bufToB64Url(clientDataJSON),
+ attestationObject: bufToB64Url(attestationObject),
+ };
+ }
+
+ private _handleGet(req: any) {
+ const rpId = req.rpId || new URL(req.origin).hostname;
+ let candidate: CredentialRecord | undefined;
+ if (req.allowCredentials?.length) {
+ for (const desc of req.allowCredentials) {
+ const c = this._registry.get(desc.id);
+ if (c && c.rpId === rpId) {
+ candidate = c;
+ break;
+ }
+ }
+ } else {
+ // Resident credential lookup by rpId.
+ for (const c of this._registry.values()) {
+ if (c.rpId === rpId && c.isResident) {
+ candidate = c;
+ break;
+ }
+ }
+ }
+ if (!candidate)
+ return { ok: false, name: 'NotAllowedError', message: 'No matching credential' };
+
+ const clientDataJSON = Buffer.from(JSON.stringify({
+ type: 'webauthn.get',
+ challenge: req.challenge,
+ origin: req.origin,
+ crossOrigin: false,
+ }));
+ const rpIdHash = crypto.createHash('sha256').update(rpId).digest();
+ const flags = 0x01 | (this._userVerified ? 0x04 : 0); // UP | UV?
+ candidate.signCount += 1;
+ const signCountBuf = u32ToBytes(candidate.signCount);
+ const authData = Buffer.concat([rpIdHash, Buffer.from([flags]), signCountBuf]);
+ const clientDataHash = crypto.createHash('sha256').update(clientDataJSON).digest();
+ const toSign = Buffer.concat([authData, clientDataHash]);
+ const privateKey = crypto.createPrivateKey({ key: b64UrlToBuf(candidate.privateKey), format: 'der', type: 'pkcs8' });
+ const signature = crypto.sign('sha256', toSign, privateKey);
+ return {
+ ok: true,
+ id: candidate.id,
+ clientDataJSON: bufToB64Url(clientDataJSON),
+ authenticatorData: bufToB64Url(authData),
+ signature: bufToB64Url(signature),
+ userHandle: candidate.userHandle || null,
+ };
+ }
+}
+
+function toPublic(r: CredentialRecord): VirtualCredential {
+ return { id: r.id, rpId: r.rpId, userHandle: r.userHandle, privateKey: r.privateKey, publicKey: r.publicKey };
+}
+
+function randomBase64Url(bytes: number): string {
+ return bufToB64Url(crypto.randomBytes(bytes));
+}
+
+function bufToB64Url(b: Buffer): string {
+ return b.toString('base64').replaceAll('+', '-').replaceAll('/', '_').replaceAll('=', '');
+}
+
+function b64UrlToBuf(s: string): Buffer {
+ return Buffer.from(s, 'base64url');
+}
+
+function u32ToBytes(n: number): Buffer {
+ const b = Buffer.alloc(4);
+ b.writeUInt32BE(n >>> 0, 0);
+ return b;
+}
+
+// Minimal CBOR encoder — only the subset we need for COSE keys and the attestation object.
+function cborHead(major: number, value: number): Buffer {
+ const m = major << 5;
+ if (value < 24)
+ return Buffer.from([m | value]);
+ if (value < 0x100)
+ return Buffer.from([m | 24, value]);
+ if (value < 0x10000)
+ return Buffer.from([m | 25, (value >> 8) & 0xff, value & 0xff]);
+ return Buffer.from([m | 26, (value >>> 24) & 0xff, (value >> 16) & 0xff, (value >> 8) & 0xff, value & 0xff]);
+}
+
+function cborUint(v: number): Buffer { return cborHead(0, v); }
+function cborNint(v: number): Buffer { return cborHead(1, -1 - v); } // v must be negative
+function cborBytes(b: Buffer): Buffer { return Buffer.concat([cborHead(2, b.length), b]); }
+function cborText(s: string): Buffer {
+ const b = Buffer.from(s, 'utf8');
+ return Buffer.concat([cborHead(3, b.length), b]);
+}
+function cborMap(entries: [Buffer, Buffer][]): Buffer {
+ return Buffer.concat([cborHead(5, entries.length), ...entries.flatMap(([k, v]) => [k, v])]);
+}
+
+function encodeCoseEs256PublicKey(publicKey: crypto.KeyObject): Buffer {
+ const jwk = publicKey.export({ format: 'jwk' }) as { x: string, y: string };
+ const x = Buffer.from(jwk.x, 'base64url');
+ const y = Buffer.from(jwk.y, 'base64url');
+ return cborMap([
+ [cborUint(1), cborUint(2)], // kty = EC2
+ [cborUint(3), cborNint(-7)], // alg = ES256
+ [cborNint(-1), cborUint(1)], // crv = P-256
+ [cborNint(-2), cborBytes(x)],
+ [cborNint(-3), cborBytes(y)],
+ ]);
+}
+
+function encodeAttestationObjectNone(authData: Buffer): Buffer {
+ return cborMap([
+ [cborText('fmt'), cborText('none')],
+ [cborText('attStmt'), cborMap([])],
+ [cborText('authData'), cborBytes(authData)],
+ ]);
+}
diff --git a/packages/playwright-core/src/server/dispatchers/browserContextDispatcher.ts b/packages/playwright-core/src/server/dispatchers/browserContextDispatcher.ts
index 1c8f3f5894..e0763acdf7 100644
--- a/packages/playwright-core/src/server/dispatchers/browserContextDispatcher.ts
+++ b/packages/playwright-core/src/server/dispatchers/browserContextDispatcher.ts
@@ -404,6 +404,28 @@ export class BrowserContextDispatcher extends Dispatcher<BrowserContext, channel
await progress.race(this._context.clock.setSystemTime(params.timeString ?? params.timeNumber ?? 0));
}
+ async credentialsInstall(params: channels.BrowserContextCredentialsInstallParams, progress: Progress): Promise<channels.BrowserContextCredentialsInstallResult> {
+ await this._context.credentials.install(progress);
+ }
+
+ async credentialsCreate(params: channels.BrowserContextCredentialsCreateParams, progress: Progress): Promise<channels.BrowserContextCredentialsCreateResult> {
+ const credential = await progress.race(this._context.credentials.create(params));
+ return { credential };
+ }
+
+ async credentialsGet(params: channels.BrowserContextCredentialsGetParams, progress: Progress): Promise<channels.BrowserContextCredentialsGetResult> {
+ const credentials = await progress.race(this._context.credentials.get(params));
+ return { credentials };
+ }
+
+ async credentialsDelete(params: channels.BrowserContextCredentialsDeleteParams, progress: Progress): Promise<channels.BrowserContextCredentialsDeleteResult> {
+ await progress.race(this._context.credentials.delete(params.id));
+ }
+
+ async credentialsSetUserVerified(params: channels.BrowserContextCredentialsSetUserVerifiedParams, progress: Progress): Promise<channels.BrowserContextCredentialsSetUserVerifiedResult> {
+ this._context.credentials.setUserVerified(params.value);
+ }
+
async updateSubscription(params: channels.BrowserContextUpdateSubscriptionParams, progress: Progress): Promise<void> {
if (params.enabled)
this._subscriptions.add(params.event);
diff --git a/packages/playwright-core/types/types.d.ts b/packages/playwright-core/types/types.d.ts
index 1b17367221..6939caf9d4 100644
--- a/packages/playwright-core/types/types.d.ts
+++ b/packages/playwright-core/types/types.d.ts
@@ -9907,6 +9907,12 @@ export interface BrowserContext {
*/
clock: Clock;
+ /**
+ * Virtual WebAuthn authenticator for this context. Lets tests seed credentials and intercept
+ * `navigator.credentials.create()` / `navigator.credentials.get()` ceremonies.
+ */
+ credentials: Credentials;
+
/**
* Debugger allows to pause and resume the execution.
*/
@@ -19241,6 +19247,139 @@ export interface Coverage {
}>>;
}
+/**
+ * `Credentials` provides a virtual WebAuthn authenticator scoped to a
+ * [BrowserContext](https://playwright.dev/docs/api/class-browsercontext). It lets tests seed credentials, intercept
+ * `navigator.credentials.create()` / `navigator.credentials.get()` calls in pages, and complete WebAuthn ceremonies
+ * without a real authenticator.
+ *
+ * Implemented in userland via an injected script, so it works across Chromium, Firefox and WebKit.
+ *
+ * **Usage**
+ *
+ * ```js
+ * const context = await browser.newContext();
+ * await context.credentials.install();
+ * await context.credentials.create({ rpId: 'example.com' });
+ * const page = await context.newPage();
+ * await page.goto('https://example.com/login');
+ * // Page's navigator.credentials.get() will be answered using the seeded credential.
+ * ```
+ *
+ */
+export interface Credentials {
+ /**
+ * Seeds a virtual WebAuthn credential. With only `rpId`, generates a fresh ECDSA P-256 keypair, credential id and
+ * user handle. To import a pre-registered credential (e.g. authenticating as an existing test user the server already
+ * knows about), supply all four of `id`, `userHandle`, `privateKey` and `publicKey` together. Call
+ * [credentials.install()](https://playwright.dev/docs/api/class-credentials#credentials-install) before navigating to
+ * a page that uses WebAuthn.
+ * @param options
+ */
+ create(options: {
+ /**
+ * Base64url-encoded credential id. Auto-generated if omitted.
+ */
+ id?: string;
+
+ /**
+ * Base64url-encoded PKCS#8 (DER) private key. Auto-generated if omitted.
+ */
+ privateKey?: string;
+
+ /**
+ * Base64url-encoded SPKI (DER) public key. Auto-generated if omitted.
+ */
+ publicKey?: string;
+
+ /**
+ * Relying party id (typically the site's effective domain).
+ */
+ rpId: string;
+
+ /**
+ * Base64url-encoded user handle. Auto-generated if omitted.
+ */
+ userHandle?: string;
+ }): Promise<{
+ /**
+ * Base64url-encoded credential id.
+ */
+ id: string;
+
+ /**
+ * Relying party id.
+ */
+ rpId: string;
+
+ /**
+ * Base64url-encoded user handle.
+ */
+ userHandle: string;
+
+ /**
+ * Base64url-encoded PKCS#8 (DER) private key.
+ */
+ privateKey: string;
+
+ /**
+ * Base64url-encoded SPKI (DER) public key.
+ */
+ publicKey: string;
+ }>;
+
+ /**
+ * Removes a previously seeded credential.
+ * @param id Base64url-encoded credential id.
+ */
+ delete(id: string): Promise<void>;
+
+ /**
+ * Returns seeded credentials, optionally filtered by `rpId` or `id`.
+ * @param options
+ */
+ get(options?: {
+ /**
+ * Only return the credential with this base64url-encoded id.
+ */
+ id?: string;
+
+ /**
+ * Only return credentials for this relying party id.
+ */
+ rpId?: string;
+ }): Promise<Array<{
+ id: string;
+
+ rpId: string;
+
+ userHandle: string;
+
+ privateKey: string;
+
+ publicKey: string;
+ }>>;
+
+ /**
+ * Installs the virtual WebAuthn authenticator into the context, overriding `navigator.credentials.create()` and
+ * `navigator.credentials.get()` in all current and future pages. Call this before the page first touches
+ * `navigator.credentials`.
+ *
+ * Required: until `install()` is called, no interception is in place and the page sees the platform's native (or
+ * absent) WebAuthn behaviour. Seeding credentials with
+ * [credentials.create(options)](https://playwright.dev/docs/api/class-credentials#credentials-create) without
+ * `install()` populates the registry but the page will never see those credentials.
+ */
+ install(): Promise<void>;
+
+ /**
+ * Toggles whether the virtual authenticator auto-approves user-verification prompts. Useful for simulating a user
+ * denying biometric verification.
+ * @param value `true` to auto-approve user verification (default), `false` to refuse.
+ */
+ setUserVerified(value: boolean): Promise<void>;
+}
+
/**
* API for controlling the Playwright debugger. The debugger allows pausing script execution and inspecting the page.
* Obtain the debugger instance via
diff --git a/packages/protocol/spec/browserContext.yml b/packages/protocol/spec/browserContext.yml
index e215c5411d..5abdc57a15 100644
--- a/packages/protocol/spec/browserContext.yml
+++ b/packages/protocol/spec/browserContext.yml
@@ -314,6 +314,40 @@ BrowserContext:
timeNumber: float?
timeString: string?
+ credentialsInstall:
+ title: Install virtual WebAuthn authenticator
+
+ credentialsCreate:
+ title: Create virtual credential for "{rpId}"
+ parameters:
+ rpId: string
+ id: string?
+ userHandle: string?
+ privateKey: string?
+ publicKey: string?
+ returns:
+ credential: VirtualCredential
+
+ credentialsGet:
+ title: Get virtual credentials
+ parameters:
+ rpId: string?
+ id: string?
+ returns:
+ credentials:
+ type: array
+ items: VirtualCredential
+
+ credentialsDelete:
+ title: Delete virtual credential
+ parameters:
+ id: string
+
+ credentialsSetUserVerified:
+ title: Set virtual authenticator user verified
+ parameters:
+ value: boolean
+
events:
bindingCall:
diff --git a/packages/protocol/spec/structs.yml b/packages/protocol/spec/structs.yml
index 2f8bcb44b5..7176692771 100644
--- a/packages/protocol/spec/structs.yml
+++ b/packages/protocol/spec/structs.yml
@@ -20,6 +20,15 @@ StackFrame:
column: int
function: string?
+VirtualCredential:
+ type: object
+ properties:
+ id: string
+ rpId: string
+ userHandle: string
+ privateKey: string
+ publicKey: string
+
Point:
type: object
properties:
diff --git a/packages/protocol/src/channels.d.ts b/packages/protocol/src/channels.d.ts
index d3acc2cc95..6729812696 100644
--- a/packages/protocol/src/channels.d.ts
+++ b/packages/protocol/src/channels.d.ts
@@ -1353,6 +1353,11 @@ export interface BrowserContextChannel extends BrowserContextEventTarget, Channe
clockRunFor(params: BrowserContextClockRunForParams, progress?: Progress): Promise<BrowserContextClockRunForResult>;
clockSetFixedTime(params: BrowserContextClockSetFixedTimeParams, progress?: Progress): Promise<BrowserContextClockSetFixedTimeResult>;
clockSetSystemTime(params: BrowserContextClockSetSystemTimeParams, progress?: Progress): Promise<BrowserContextClockSetSystemTimeResult>;
+ credentialsInstall(params?: BrowserContextCredentialsInstallParams, progress?: Progress): Promise<BrowserContextCredentialsInstallResult>;
+ credentialsCreate(params: BrowserContextCredentialsCreateParams, progress?: Progress): Promise<BrowserContextCredentialsCreateResult>;
+ credentialsGet(params: BrowserContextCredentialsGetParams, progress?: Progress): Promise<BrowserContextCredentialsGetResult>;
+ credentialsDelete(params: BrowserContextCredentialsDeleteParams, progress?: Progress): Promise<BrowserContextCredentialsDeleteResult>;
+ credentialsSetUserVerified(params: BrowserContextCredentialsSetUserVerifiedParams, progress?: Progress): Promise<BrowserContextCredentialsSetUserVerifiedResult>;
}
export type BrowserContextBindingCallEvent = {
binding: BindingCallChannel,
@@ -1734,6 +1739,50 @@ export type BrowserContextClockSetSystemTimeOptions = {
timeString?: string,
};
export type BrowserContextClockSetSystemTimeResult = void;
+export type BrowserContextCredentialsInstallParams = {};
+export type BrowserContextCredentialsInstallOptions = {};
+export type BrowserContextCredentialsInstallResult = void;
+export type BrowserContextCredentialsCreateParams = {
+ rpId: string,
+ id?: string,
+ userHandle?: string,
+ privateKey?: string,
+ publicKey?: string,
+};
+export type BrowserContextCredentialsCreateOptions = {
+ id?: string,
+ userHandle?: string,
+ privateKey?: string,
+ publicKey?: string,
+};
+export type BrowserContextCredentialsCreateResult = {
+ credential: VirtualCredential,
+};
+export type BrowserContextCredentialsGetParams = {
+ rpId?: string,
+ id?: string,
+};
+export type BrowserContextCredentialsGetOptions = {
+ rpId?: string,
+ id?: string,
+};
+export type BrowserContextCredentialsGetResult = {
+ credentials: VirtualCredential[],
+};
+export type BrowserContextCredentialsDeleteParams = {
+ id: string,
+};
+export type BrowserContextCredentialsDeleteOptions = {
+
+};
+export type BrowserContextCredentialsDeleteResult = void;
+export type BrowserContextCredentialsSetUserVerifiedParams = {
+ value: boolean,
+};
+export type BrowserContextCredentialsSetUserVerifiedOptions = {
+
+};
+export type BrowserContextCredentialsSetUserVerifiedResult = void;
export interface BrowserContextEvents {
'bindingCall': BrowserContextBindingCallEvent;
@@ -5294,6 +5343,14 @@ export type StackFrame = {
function?: string,
};
+export type VirtualCredential = {
+ id: string,
+ rpId: string,
+ userHandle: string,
+ privateKey: string,
+ publicKey: string,
+};
+
export type Point = {
x: number,
y: number,
diff --git a/tests/library/browsercontext-webauthn.spec.ts b/tests/library/browsercontext-webauthn.spec.ts
new file mode 100644
index 0000000000..f4295c83ae
--- /dev/null
+++ b/tests/library/browsercontext-webauthn.spec.ts
@@ -0,0 +1,186 @@
+/**
+ * Copyright (c) Microsoft Corporation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { browserTest as it, expect } from '../config/browserTest';
+
+it.skip(({ mode }) => mode.startsWith('service'));
+
+// WebAuthn requires a secure context (HTTPS or localhost). The test server's default
+// `same_origin = 'localhost'` satisfies this for HTTP.
+
+it('should seed a credential @smoke', async ({ contextFactory, server }) => {
+ const context = await contextFactory();
+ const cred = await context.credentials.create({ rpId: server.HOSTNAME });
+ expect(cred.id).toBeTruthy();
+ expect(cred.rpId).toBe(server.HOSTNAME);
+ expect(cred.userHandle).toBeTruthy();
+ // base64url has no padding and no +/ chars
+ expect(cred.privateKey).toMatch(/^[A-Za-z0-9_-]+$/);
+ expect(cred.publicKey).toMatch(/^[A-Za-z0-9_-]+$/);
+
+ const all = await context.credentials.get();
+ expect(all).toHaveLength(1);
+ expect(all[0].id).toBe(cred.id);
+
+ await context.credentials.delete(cred.id);
+ expect(await context.credentials.get()).toHaveLength(0);
+});
+
+it('should not intercept navigator.credentials without install()', async ({ contextFactory, server }) => {
+ const context = await contextFactory();
+ // Seed a credential, but do not install the interceptor.
+ await context.credentials.create({ rpId: server.HOSTNAME });
+ const page = await context.newPage();
+ await page.goto(server.EMPTY_PAGE);
+
+ const intercepted = await page.evaluate(() => (globalThis as any).__pwWebAuthnInstalled === true);
+ expect(intercepted).toBe(false);
+});
+
+it('should authenticate with a seeded credential', async ({ contextFactory, server }) => {
+ const context = await contextFactory();
+ await context.credentials.install();
+ const seeded = await context.credentials.create({ rpId: server.HOSTNAME });
+ const page = await context.newPage();
+ await page.goto(server.EMPTY_PAGE);
+
+ const result = await page.evaluate(async ({ rpId, credentialId }) => {
+ const b64UrlToBytes = (s: string) => {
+ let str = s.replace(/-/g, '+').replace(/_/g, '/');
+ while (str.length % 4)
+ str += '=';
+ const bin = atob(str);
+ const u8 = new Uint8Array(bin.length);
+ for (let i = 0; i < bin.length; i++)
+ u8[i] = bin.charCodeAt(i);
+ return u8;
+ };
+ const challenge = crypto.getRandomValues(new Uint8Array(32));
+ const cred = await navigator.credentials.get({
+ publicKey: {
+ challenge,
+ rpId,
+ allowCredentials: [{ type: 'public-key', id: b64UrlToBytes(credentialId) }],
+ userVerification: 'preferred',
+ },
+ }) as PublicKeyCredential;
+ const resp = cred.response as AuthenticatorAssertionResponse;
+ return {
+ id: cred.id,
+ type: cred.type,
+ hasClientData: resp.clientDataJSON.byteLength > 0,
+ hasAuthData: resp.authenticatorData.byteLength > 0,
+ hasSignature: resp.signature.byteLength > 0,
+ authDataFlags: new Uint8Array(resp.authenticatorData)[32],
+ };
+ }, { rpId: server.HOSTNAME, credentialId: seeded.id });
+
+ expect(result.id).toBe(seeded.id);
+ expect(result.type).toBe('public-key');
+ expect(result.hasClientData).toBe(true);
+ expect(result.hasAuthData).toBe(true);
+ expect(result.hasSignature).toBe(true);
+ // UP (0x01) | UV (0x04) = 0x05
+ expect(result.authDataFlags & 0x05).toBe(0x05);
+});
+
+it('should round-trip create then get in the page', async ({ contextFactory, server }) => {
+ const context = await contextFactory();
+ await context.credentials.install();
+ const page = await context.newPage();
+ await page.goto(server.EMPTY_PAGE);
+
+ const result = await page.evaluate(async ({ rpId }) => {
+ const challenge1 = crypto.getRandomValues(new Uint8Array(32));
+ const created = await navigator.credentials.create({
+ publicKey: {
+ challenge: challenge1,
+ rp: { id: rpId, name: 'Test RP' },
+ user: { id: new Uint8Array([1, 2, 3, 4]), name: 'u', displayName: 'User' },
+ pubKeyCredParams: [{ type: 'public-key', alg: -7 }],
+ authenticatorSelection: { residentKey: 'required', userVerification: 'preferred' },
+ },
+ }) as PublicKeyCredential;
+ const challenge2 = crypto.getRandomValues(new Uint8Array(32));
+ const got = await navigator.credentials.get({
+ publicKey: { challenge: challenge2, rpId, userVerification: 'preferred' },
+ }) as PublicKeyCredential;
+ return { createdId: created.id, gotId: got.id };
+ }, { rpId: server.HOSTNAME });
+
+ expect(result.createdId).toBe(result.gotId);
+ const stored = await context.credentials.get();
+ expect(stored.map(c => c.id)).toContain(result.createdId);
+});
+
+it('should toggle user-verified flag', async ({ contextFactory, server }) => {
+ const context = await contextFactory();
+ await context.credentials.install();
+ const seeded = await context.credentials.create({ rpId: server.HOSTNAME });
+ await context.credentials.setUserVerified(false);
+ const page = await context.newPage();
+ await page.goto(server.EMPTY_PAGE);
+
+ const flagsByte = await page.evaluate(async ({ rpId, credentialId }) => {
+ const b64UrlToBytes = (s: string) => {
+ let str = s.replace(/-/g, '+').replace(/_/g, '/');
+ while (str.length % 4)
+ str += '=';
+ const bin = atob(str);
+ const u8 = new Uint8Array(bin.length);
+ for (let i = 0; i < bin.length; i++)
+ u8[i] = bin.charCodeAt(i);
+ return u8;
+ };
+ const cred = await navigator.credentials.get({
+ publicKey: {
+ challenge: new Uint8Array(32),
+ rpId,
+ allowCredentials: [{ type: 'public-key', id: b64UrlToBytes(credentialId) }],
+ },
+ }) as PublicKeyCredential;
+ const resp = cred.response as AuthenticatorAssertionResponse;
+ return new Uint8Array(resp.authenticatorData)[32];
+ }, { rpId: server.HOSTNAME, credentialId: seeded.id });
+
+ // UV bit (0x04) should be unset; UP bit (0x01) still set.
+ expect(flagsByte & 0x04).toBe(0);
+ expect(flagsByte & 0x01).toBe(0x01);
+});
+
+it('should reject when no credential matches', async ({ contextFactory, server }) => {
+ const context = await contextFactory();
+ await context.credentials.install();
+ const page = await context.newPage();
+ await page.goto(server.EMPTY_PAGE);
+
+ const error = await page.evaluate(async ({ rpId }) => {
+ try {
+ await navigator.credentials.get({
+ publicKey: {
+ challenge: new Uint8Array(32),
+ rpId,
+ allowCredentials: [{ type: 'public-key', id: new Uint8Array([9, 9, 9, 9]) }],
+ },
+ });
+ return 'no-error';
+ } catch (e) {
+ return (e as DOMException).name;
+ }
+ }, { rpId: server.HOSTNAME });
+
+ expect(error).toBe('NotAllowedError');
+});
diff --git a/utils/generate_injected.js b/utils/generate_injected.js
index 64a462f016..e661df9d5e 100644
--- a/utils/generate_injected.js
+++ b/utils/generate_injected.js
@@ -68,6 +68,12 @@ const injectedScripts = [
path.join(ROOT, 'packages', 'playwright-core', 'src', 'generated'),
true,
],
+ [
+ path.join(ROOT, 'packages', 'injected', 'src', 'webAuthn.ts'),
+ path.join(ROOT, 'packages', 'injected', 'lib'),
+ path.join(ROOT, 'packages', 'playwright-core', 'src', 'generated'),
+ true,
+ ],
[
path.join(ROOT, 'packages', 'playwright-ct-core', 'src', 'injected', 'index.ts'),
path.join(ROOT, 'packages', 'playwright-ct-core', 'lib', 'injected', 'packed'),