Skip to content

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

docs(credentials): clarify scenarios, defaults and setUserVerified (#41192)

Dmitry Gozman41b00f189d70
diff --git a/docs/src/api/class-credentials.md b/docs/src/api/class-credentials.md
index 59af7a54d3..ff869db9cd 100644
--- a/docs/src/api/class-credentials.md
+++ b/docs/src/api/class-credentials.md
@@ -1,23 +1,79 @@
# 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.
+`Credentials` is a virtual WebAuthn authenticator scoped to a [BrowserContext]. It lets tests
+register passkeys and answer `navigator.credentials.create()` / `navigator.credentials.get()`
+ceremonies in the page, without a real authenticator or hardware security key.
-Implemented in userland via an injected script, so it works across Chromium, Firefox and WebKit.
+There are two common ways to use it:
-**Usage**
+- **Seed a known credential.** The passkey already exists — for example, your backend provisioned
+ it for a test user. Import it with [`method: Credentials.create`] so the app under test can sign
+ in right away. See the first example below.
+- **Capture a credential, then reuse it.** Let the app register a passkey once in a setup test,
+ read it back with [`method: Credentials.get`], and seed it into later tests — the same way
+ [`method: BrowserContext.storageState`] reuses signed-in state. See the second example below.
+
+**Usage: seed a known credential**
```js
const context = await browser.newContext();
+
+// A passkey your backend already provisioned for a test user.
+await context.credentials.create({
+ rpId: 'example.com',
+ id: knownCredentialId, // base64url
+ userHandle: knownUserHandle, // base64url
+ privateKey: knownPrivateKey, // base64url PKCS#8 (DER)
+ publicKey: knownPublicKey, // base64url SPKI (DER)
+});
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.
+// The page's navigator.credentials.get() is answered with the seeded passkey.
```
+**Usage: capture a passkey, then reuse it**
+
+```js
+// setup test: let the app register a passkey, then save it.
+const context = await browser.newContext();
+await context.credentials.install();
+
+const page = await context.newPage();
+await page.goto('https://example.com/register');
+await page.getByRole('button', { name: 'Create a passkey' }).click();
+
+// Read back the passkey the page registered — it includes the private key.
+const [credential] = await context.credentials.get({ rpId: 'example.com' });
+fs.writeFileSync('playwright/.auth/passkey.json', JSON.stringify(credential));
+```
+
+```js
+// later test: seed the captured passkey so the app starts already enrolled.
+const credential = JSON.parse(fs.readFileSync('playwright/.auth/passkey.json', 'utf8'));
+const context = await browser.newContext();
+await context.credentials.create(credential);
+await context.credentials.install();
+
+const page = await context.newPage();
+await page.goto('https://example.com/login');
+// navigator.credentials.get() resolves the captured passkey — already signed in.
+```
+
+**Defaults**
+
+- The authenticator presents itself as a **platform** authenticator (`authenticatorAttachment` is
+ `'platform'`), and `PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()` resolves
+ to `true` in the page.
+- Seeded credentials are **discoverable** (resident), so both username-then-passkey and
+ usernameless passkey flows resolve them.
+- Fresh keys are ECDSA P-256 (COSE algorithm `-7`). An omitted `id` or `userHandle` is
+ filled with 16 random bytes.
+- User verification is **on** by default — every assertion and attestation reports the user as
+ verified. Toggle this with [`method: Credentials.setUserVerified`].
+
## async method: Credentials.install
* since: v1.61
@@ -27,7 +83,7 @@ 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
+[`method: Credentials.create`] without `install()` populates the authenticator, but the
page will never see those credentials.
## async method: Credentials.create
@@ -40,11 +96,17 @@ page will never see those credentials.
- `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.
+Seeds a virtual WebAuthn credential and returns it.
+
+With only `rpId`, generates a fresh **ECDSA P-256** keypair, credential id and user handle. The
+seeded credential is discoverable (resident), so the page can resolve it from both
+username-then-passkey and usernameless passkey flows. The returned object carries the `privateKey` and `publicKey`, so
+it can be persisted to disk and re-seeded in a later test.
+
+To **import a known credential**, 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
@@ -58,7 +120,9 @@ page that uses WebAuthn.
## async method: Credentials.delete
* since: v1.61
-Removes a previously seeded credential.
+Removes a credential from the authenticator by its id. Works for any credential currently held —
+both those seeded with [`method: Credentials.create`] and those the page registered itself by
+calling `navigator.credentials.create()`.
### param: Credentials.delete.id
* since: v1.61
@@ -76,7 +140,12 @@ Base64url-encoded credential id.
- `privateKey` <[string]>
- `publicKey` <[string]>
-Returns seeded credentials, optionally filtered by `rpId` or `id`.
+Returns every credential currently held by the authenticator, optionally filtered by `rpId` or
+`id`. This includes both credentials seeded with [`method: Credentials.create`] and credentials
+the page registered itself by calling `navigator.credentials.create()`.
+
+Each returned credential includes its `privateKey` and `publicKey`, so a passkey the app just
+registered can be saved and re-seeded into a later test with [`method: Credentials.create`] — see the second example in the class overview.
### option: Credentials.get.rpId
* since: v1.61
@@ -93,11 +162,37 @@ 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.
+Controls whether the virtual authenticator reports the user as **verified**. This is a
+context-wide setting (default `true`) that toggles the user-verified (UV) flag in the
+`authenticatorData` of every subsequent `navigator.credentials.create()` and
+`navigator.credentials.get()` ceremony.
+
+When set to `false`, ceremonies still **succeed**, but the resulting assertion/attestation reports
+that user verification was *not* performed — the user-present (UP) flag stays set. It does **not**
+simulate a cancelled or denied prompt, and it does not reject the call. Use it to test how your
+relying party or app handles an assertion that lacks user verification, for example requiring
+step-up authentication.
+
+**Usage**
+
+```js
+await context.credentials.install();
+await context.credentials.create({ rpId: 'example.com' });
+
+// Report assertions as NOT user-verified, e.g. a presence-only tap.
+await context.credentials.setUserVerified(false);
+
+const page = await context.newPage();
+await page.goto('https://example.com/login');
+// Assert the app requires step-up auth or rejects the unverified sign-in.
+
+// Restore verified assertions for later steps.
+await context.credentials.setUserVerified(true);
+```
### param: Credentials.setUserVerified.value
* since: v1.61
- `value` <[boolean]>
-`true` to auto-approve user verification (default), `false` to refuse.
+`true` to report assertions and attestations as user-verified (default), `false` to report them as
+not user-verified.
diff --git a/docs/src/auth.md b/docs/src/auth.md
index 51145a79e8..36da17f117 100644
--- a/docs/src/auth.md
+++ b/docs/src/auth.md
@@ -397,6 +397,75 @@ export const test = baseTest.extend<{}, { workerStorageState: string }>({
});
```
+### Passkeys (WebAuthn)
+* langs: js
+
+**When to use**
+- Your app signs users in with passkeys (WebAuthn), and you want tests to start already enrolled.
+
+**Details**
+
+[`property: BrowserContext.credentials`] is a virtual WebAuthn authenticator. Unlike cookie or local storage state, a passkey is seeded **imperatively** with [`method: Credentials.create`] and [`method: Credentials.install`], so it lives in a [`context` fixture override](./test-fixtures.md#overriding-fixtures) rather than in the `storageState` config option.
+
+If your backend already provisioned a passkey for the test user, seed it directly — no setup project required:
+
+```js title="playwright/fixtures.ts"
+import { test as baseTest } from '@playwright/test';
+export * from '@playwright/test';
+
+export const test = baseTest.extend({
+ context: async ({ context }, use) => {
+ // A passkey your backend provisioned for the test user.
+ await context.credentials.create({
+ rpId: 'example.com',
+ id: process.env.PASSKEY_ID,
+ userHandle: process.env.PASSKEY_USER_HANDLE,
+ privateKey: process.env.PASSKEY_PRIVATE_KEY,
+ publicKey: process.env.PASSKEY_PUBLIC_KEY,
+ });
+ await context.credentials.install();
+ await use(context);
+ },
+});
+```
+
+Otherwise, let the app register a passkey once in a [setup project](#basic-shared-account-in-all-tests), capture it with [`method: Credentials.get`], and save it to disk:
+
+```js title="tests/passkey.setup.ts"
+import { test as setup } from '@playwright/test';
+import fs from 'fs';
+
+setup('enroll passkey', async ({ context, page }) => {
+ await context.credentials.install();
+ await page.goto('https://example.com/register');
+ // The app calls navigator.credentials.create() to register the passkey.
+ await page.getByRole('button', { name: 'Create a passkey' }).click();
+
+ // Read back the registered passkey, including its private key, and save it.
+ const [credential] = await context.credentials.get({ rpId: 'example.com' });
+ fs.writeFileSync('playwright/.auth/passkey.json', JSON.stringify(credential));
+});
+```
+
+Then seed the captured passkey into every test's context:
+
+```js title="playwright/fixtures.ts"
+import { test as baseTest } from '@playwright/test';
+import fs from 'fs';
+export * from '@playwright/test';
+
+export const test = baseTest.extend({
+ context: async ({ context }, use) => {
+ const credential = JSON.parse(fs.readFileSync('playwright/.auth/passkey.json', 'utf8'));
+ await context.credentials.create(credential);
+ await context.credentials.install();
+ await use(context);
+ },
+});
+```
+
+Declare the `setup` project as a [dependency](./test-projects.md#dependencies) of your testing projects, just like in the [basic flow](#basic-shared-account-in-all-tests). The saved `passkey.json` contains a private key, so keep it under `playwright/.auth` and out of source control (see [Core concepts](#core-concepts)).
+
### Multiple signed in roles
* langs: js
diff --git a/packages/playwright-client/types/types.d.ts b/packages/playwright-client/types/types.d.ts
index c80d5655a3..81a22d53e3 100644
--- a/packages/playwright-client/types/types.d.ts
+++ b/packages/playwright-client/types/types.d.ts
@@ -19419,32 +19419,76 @@ 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.
+ * `Credentials` is a virtual WebAuthn authenticator scoped to a
+ * [BrowserContext](https://playwright.dev/docs/api/class-browsercontext). It lets tests register passkeys and answer
+ * `navigator.credentials.create()` / `navigator.credentials.get()` ceremonies in the page, without a real
+ * authenticator or hardware security key.
*
- * Implemented in userland via an injected script, so it works across Chromium, Firefox and WebKit.
+ * There are two common ways to use it:
*
- * **Usage**
+ * **Usage: seed a known credential**
*
* ```js
* const context = await browser.newContext();
+ *
+ * // A passkey your backend already provisioned for a test user.
+ * await context.credentials.create({
+ * rpId: 'example.com',
+ * id: knownCredentialId, // base64url
+ * userHandle: knownUserHandle, // base64url
+ * privateKey: knownPrivateKey, // base64url PKCS#8 (DER)
+ * publicKey: knownPublicKey, // base64url SPKI (DER)
+ * });
* 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.
+ * // The page's navigator.credentials.get() is answered with the seeded passkey.
+ * ```
+ *
+ * **Usage: capture a passkey, then reuse it**
+ *
+ * ```js
+ * // setup test: let the app register a passkey, then save it.
+ * const context = await browser.newContext();
+ * await context.credentials.install();
+ *
+ * const page = await context.newPage();
+ * await page.goto('https://example.com/register');
+ * await page.getByRole('button', { name: 'Create a passkey' }).click();
+ *
+ * // Read back the passkey the page registered — it includes the private key.
+ * const [credential] = await context.credentials.get({ rpId: 'example.com' });
+ * fs.writeFileSync('playwright/.auth/passkey.json', JSON.stringify(credential));
* ```
*
+ * ```js
+ * // later test: seed the captured passkey so the app starts already enrolled.
+ * const credential = JSON.parse(fs.readFileSync('playwright/.auth/passkey.json', 'utf8'));
+ * const context = await browser.newContext();
+ * await context.credentials.create(credential);
+ * await context.credentials.install();
+ *
+ * const page = await context.newPage();
+ * await page.goto('https://example.com/login');
+ * // navigator.credentials.get() resolves the captured passkey — already signed in.
+ * ```
+ *
+ * **Defaults**
*/
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.
+ * Seeds a virtual WebAuthn credential and returns it.
+ *
+ * With only `rpId`, generates a fresh **ECDSA P-256** keypair, credential id and user handle. The seeded credential
+ * is discoverable (resident), so the page can resolve it from both username-then-passkey and usernameless passkey
+ * flows. The returned object carries the `privateKey` and `publicKey`, so it can be persisted to disk and re-seeded
+ * in a later test.
+ *
+ * To **import a known credential**, 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: {
@@ -19500,13 +19544,23 @@ export interface Credentials {
}>;
/**
- * Removes a previously seeded credential.
+ * Removes a credential from the authenticator by its id. Works for any credential currently held — both those seeded
+ * with [credentials.create(options)](https://playwright.dev/docs/api/class-credentials#credentials-create) and those
+ * the page registered itself by calling `navigator.credentials.create()`.
* @param id Base64url-encoded credential id.
*/
delete(id: string): Promise<void>;
/**
- * Returns seeded credentials, optionally filtered by `rpId` or `id`.
+ * Returns every credential currently held by the authenticator, optionally filtered by `rpId` or `id`. This includes
+ * both credentials seeded with
+ * [credentials.create(options)](https://playwright.dev/docs/api/class-credentials#credentials-create) and credentials
+ * the page registered itself by calling `navigator.credentials.create()`.
+ *
+ * Each returned credential includes its `privateKey` and `publicKey`, so a passkey the app just registered can be
+ * saved and re-seeded into a later test with
+ * [credentials.create(options)](https://playwright.dev/docs/api/class-credentials#credentials-create) — see the
+ * second example in the class overview.
* @param options
*/
get(options?: {
@@ -19539,14 +19593,39 @@ export interface 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()` populates the authenticator, 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.
+ * Controls whether the virtual authenticator reports the user as **verified**. This is a context-wide setting
+ * (default `true`) that toggles the user-verified (UV) flag in the `authenticatorData` of every subsequent
+ * `navigator.credentials.create()` and `navigator.credentials.get()` ceremony.
+ *
+ * When set to `false`, ceremonies still **succeed**, but the resulting assertion/attestation reports that user
+ * verification was *not* performed — the user-present (UP) flag stays set. It does **not** simulate a cancelled or
+ * denied prompt, and it does not reject the call. Use it to test how your relying party or app handles an assertion
+ * that lacks user verification, for example requiring step-up authentication.
+ *
+ * **Usage**
+ *
+ * ```js
+ * await context.credentials.install();
+ * await context.credentials.create({ rpId: 'example.com' });
+ *
+ * // Report assertions as NOT user-verified, e.g. a presence-only tap.
+ * await context.credentials.setUserVerified(false);
+ *
+ * const page = await context.newPage();
+ * await page.goto('https://example.com/login');
+ * // Assert the app requires step-up auth or rejects the unverified sign-in.
+ *
+ * // Restore verified assertions for later steps.
+ * await context.credentials.setUserVerified(true);
+ * ```
+ *
+ * @param value `true` to report assertions and attestations as user-verified (default), `false` to report them as not
+ * user-verified.
*/
setUserVerified(value: boolean): Promise<void>;
}
diff --git a/packages/playwright-core/types/types.d.ts b/packages/playwright-core/types/types.d.ts
index c80d5655a3..81a22d53e3 100644
--- a/packages/playwright-core/types/types.d.ts
+++ b/packages/playwright-core/types/types.d.ts
@@ -19419,32 +19419,76 @@ 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.
+ * `Credentials` is a virtual WebAuthn authenticator scoped to a
+ * [BrowserContext](https://playwright.dev/docs/api/class-browsercontext). It lets tests register passkeys and answer
+ * `navigator.credentials.create()` / `navigator.credentials.get()` ceremonies in the page, without a real
+ * authenticator or hardware security key.
*
- * Implemented in userland via an injected script, so it works across Chromium, Firefox and WebKit.
+ * There are two common ways to use it:
*
- * **Usage**
+ * **Usage: seed a known credential**
*
* ```js
* const context = await browser.newContext();
+ *
+ * // A passkey your backend already provisioned for a test user.
+ * await context.credentials.create({
+ * rpId: 'example.com',
+ * id: knownCredentialId, // base64url
+ * userHandle: knownUserHandle, // base64url
+ * privateKey: knownPrivateKey, // base64url PKCS#8 (DER)
+ * publicKey: knownPublicKey, // base64url SPKI (DER)
+ * });
* 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.
+ * // The page's navigator.credentials.get() is answered with the seeded passkey.
+ * ```
+ *
+ * **Usage: capture a passkey, then reuse it**
+ *
+ * ```js
+ * // setup test: let the app register a passkey, then save it.
+ * const context = await browser.newContext();
+ * await context.credentials.install();
+ *
+ * const page = await context.newPage();
+ * await page.goto('https://example.com/register');
+ * await page.getByRole('button', { name: 'Create a passkey' }).click();
+ *
+ * // Read back the passkey the page registered — it includes the private key.
+ * const [credential] = await context.credentials.get({ rpId: 'example.com' });
+ * fs.writeFileSync('playwright/.auth/passkey.json', JSON.stringify(credential));
* ```
*
+ * ```js
+ * // later test: seed the captured passkey so the app starts already enrolled.
+ * const credential = JSON.parse(fs.readFileSync('playwright/.auth/passkey.json', 'utf8'));
+ * const context = await browser.newContext();
+ * await context.credentials.create(credential);
+ * await context.credentials.install();
+ *
+ * const page = await context.newPage();
+ * await page.goto('https://example.com/login');
+ * // navigator.credentials.get() resolves the captured passkey — already signed in.
+ * ```
+ *
+ * **Defaults**
*/
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.
+ * Seeds a virtual WebAuthn credential and returns it.
+ *
+ * With only `rpId`, generates a fresh **ECDSA P-256** keypair, credential id and user handle. The seeded credential
+ * is discoverable (resident), so the page can resolve it from both username-then-passkey and usernameless passkey
+ * flows. The returned object carries the `privateKey` and `publicKey`, so it can be persisted to disk and re-seeded
+ * in a later test.
+ *
+ * To **import a known credential**, 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: {
@@ -19500,13 +19544,23 @@ export interface Credentials {
}>;
/**
- * Removes a previously seeded credential.
+ * Removes a credential from the authenticator by its id. Works for any credential currently held — both those seeded
+ * with [credentials.create(options)](https://playwright.dev/docs/api/class-credentials#credentials-create) and those
+ * the page registered itself by calling `navigator.credentials.create()`.
* @param id Base64url-encoded credential id.
*/
delete(id: string): Promise<void>;
/**
- * Returns seeded credentials, optionally filtered by `rpId` or `id`.
+ * Returns every credential currently held by the authenticator, optionally filtered by `rpId` or `id`. This includes
+ * both credentials seeded with
+ * [credentials.create(options)](https://playwright.dev/docs/api/class-credentials#credentials-create) and credentials
+ * the page registered itself by calling `navigator.credentials.create()`.
+ *
+ * Each returned credential includes its `privateKey` and `publicKey`, so a passkey the app just registered can be
+ * saved and re-seeded into a later test with
+ * [credentials.create(options)](https://playwright.dev/docs/api/class-credentials#credentials-create) — see the
+ * second example in the class overview.
* @param options
*/
get(options?: {
@@ -19539,14 +19593,39 @@ export interface 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()` populates the authenticator, 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.
+ * Controls whether the virtual authenticator reports the user as **verified**. This is a context-wide setting
+ * (default `true`) that toggles the user-verified (UV) flag in the `authenticatorData` of every subsequent
+ * `navigator.credentials.create()` and `navigator.credentials.get()` ceremony.
+ *
+ * When set to `false`, ceremonies still **succeed**, but the resulting assertion/attestation reports that user
+ * verification was *not* performed — the user-present (UP) flag stays set. It does **not** simulate a cancelled or
+ * denied prompt, and it does not reject the call. Use it to test how your relying party or app handles an assertion
+ * that lacks user verification, for example requiring step-up authentication.
+ *
+ * **Usage**
+ *
+ * ```js
+ * await context.credentials.install();
+ * await context.credentials.create({ rpId: 'example.com' });
+ *
+ * // Report assertions as NOT user-verified, e.g. a presence-only tap.
+ * await context.credentials.setUserVerified(false);
+ *
+ * const page = await context.newPage();
+ * await page.goto('https://example.com/login');
+ * // Assert the app requires step-up auth or rejects the unverified sign-in.
+ *
+ * // Restore verified assertions for later steps.
+ * await context.credentials.setUserVerified(true);
+ * ```
+ *
+ * @param value `true` to report assertions and attestations as user-verified (default), `false` to report them as not
+ * user-verified.
*/
setUserVerified(value: boolean): Promise<void>;
}
diff --git a/tests/library/browsercontext-webauthn.spec.ts b/tests/library/browsercontext-webauthn.spec.ts
index f4295c83ae..2b5ed6eff2 100644
--- a/tests/library/browsercontext-webauthn.spec.ts
+++ b/tests/library/browsercontext-webauthn.spec.ts
@@ -18,27 +18,6 @@ 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.
@@ -50,10 +29,51 @@ it('should not intercept navigator.credentials without install()', async ({ cont
expect(intercepted).toBe(false);
});
-it('should authenticate with a seeded credential', async ({ contextFactory, server }) => {
+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 seed a known credential and authenticate', async ({ contextFactory, server }) => {
+ // This is the easiest way to create credentials. In practice, this
+ // probably comes from environment.
+ const source = await contextFactory();
+ const known = await source.credentials.create({ rpId: server.HOSTNAME });
+
+ // A fresh context imports the known credential and signs in with it.
+ const context = await contextFactory();
+ await context.credentials.create(known);
+ await context.credentials.install();
const page = await context.newPage();
await page.goto(server.EMPTY_PAGE);
@@ -86,55 +106,21 @@ it('should authenticate with a seeded credential', async ({ contextFactory, serv
hasSignature: resp.signature.byteLength > 0,
authDataFlags: new Uint8Array(resp.authenticatorData)[32],
};
- }, { rpId: server.HOSTNAME, credentialId: seeded.id });
+ }, { rpId: server.HOSTNAME, credentialId: known.id });
- expect(result.id).toBe(seeded.id);
+ expect(result.id).toBe(known.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);
+ // After the credential is deleted, the page can no longer authenticate with it.
+ await context.credentials.delete(known.id);
+ expect(await context.credentials.get()).toHaveLength(0);
- const flagsByte = await page.evaluate(async ({ rpId, credentialId }) => {
+ const error = await page.evaluate(async ({ rpId, credentialId }) => {
const b64UrlToBytes = (s: string) => {
let str = s.replace(/-/g, '+').replace(/_/g, '/');
while (str.length % 4)
@@ -145,42 +131,64 @@ it('should toggle user-verified flag', async ({ contextFactory, server }) => {
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 }) => {
+ const challenge = crypto.getRandomValues(new Uint8Array(32));
try {
await navigator.credentials.get({
publicKey: {
- challenge: new Uint8Array(32),
+ challenge,
rpId,
- allowCredentials: [{ type: 'public-key', id: new Uint8Array([9, 9, 9, 9]) }],
+ allowCredentials: [{ type: 'public-key', id: b64UrlToBytes(credentialId) }],
},
});
return 'no-error';
} catch (e) {
return (e as DOMException).name;
}
+ }, { rpId: server.HOSTNAME, credentialId: known.id });
+ expect(error).toBe('NotAllowedError');
+});
+
+it('should capture a page-created credential and reuse it in another context', async ({ contextFactory, server }) => {
+ // Setup context: the app registers a passkey via navigator.credentials.create().
+ const setupContext = await contextFactory();
+ await setupContext.credentials.install();
+ const setupPage = await setupContext.newPage();
+ await setupPage.goto(server.EMPTY_PAGE);
+
+ const createdId = await setupPage.evaluate(async ({ rpId }) => {
+ const challenge = crypto.getRandomValues(new Uint8Array(32));
+ const created = await navigator.credentials.create({
+ publicKey: {
+ challenge,
+ 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;
+ return created.id;
}, { rpId: server.HOSTNAME });
- expect(error).toBe('NotAllowedError');
+ const [captured] = await setupContext.credentials.get({ rpId: server.HOSTNAME });
+ expect(captured.id).toBe(createdId);
+ expect(captured.privateKey).toMatch(/^[A-Za-z0-9_-]+$/);
+ expect(captured.publicKey).toMatch(/^[A-Za-z0-9_-]+$/);
+
+ // Reuse the captured passkey in a fresh context and sign in with it.
+ const context = await contextFactory();
+ await context.credentials.create(captured);
+ await context.credentials.install();
+ const page = await context.newPage();
+ await page.goto(server.EMPTY_PAGE);
+
+ const gotId = await page.evaluate(async ({ rpId }) => {
+ const challenge = crypto.getRandomValues(new Uint8Array(32));
+ // No allowCredentials — relies on the re-seeded credential being discoverable.
+ const cred = await navigator.credentials.get({
+ publicKey: { challenge, rpId, userVerification: 'preferred' },
+ }) as PublicKeyCredential;
+ return cred.id;
+ }, { rpId: server.HOSTNAME });
+
+ expect(gotId).toBe(createdId);
});