Skip to content

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

feat(webauthn): add signCount to virtual credentials (#43041)

Dmitry Gozmanec17ddf9cd2f
diff --git a/docs/src/api/class-browsercontext.md b/docs/src/api/class-browsercontext.md
index 5528616186..b18de7eea9 100644
--- a/docs/src/api/class-browsercontext.md
+++ b/docs/src/api/class-browsercontext.md
@@ -1590,7 +1590,7 @@ OPFS is currently not supported in ephemeral WebKit contexts.
- `credentials` ?<boolean>
Set to `true` to include the context's virtual WebAuthn [`property: BrowserContext.credentials`] (passkeys) in the storage
-state snapshot. The captured credentials carry their private keys, so they can be re-seeded into a later context via the
+state snapshot. The captured credentials carry their private keys and signature counters, so they can be re-seeded into a later context via the
[`option: Browser.newContext.storageState`] option or [`method: BrowserContext.setStorageState`].
Note that restoring the storage state that contains credentials will automatically install the virtual WebAuthn authenticator (see [`method: Credentials.install`]), and prevent all real authenticators from working in this context.
diff --git a/docs/src/api/class-credentials.md b/docs/src/api/class-credentials.md
index abcec7ffc0..9e8ca76eff 100644
--- a/docs/src/api/class-credentials.md
+++ b/docs/src/api/class-credentials.md
@@ -200,7 +200,8 @@ context.credentials().create(credential.rpId, new Credentials.CreateOptions()
.setId(credential.id)
.setUserHandle(credential.userHandle)
.setPrivateKey(credential.privateKey)
- .setPublicKey(credential.publicKey));
+ .setPublicKey(credential.publicKey)
+ .setSignCount(credential.signCount));
context.credentials().install();
Page page = context.newPage();
@@ -219,6 +220,7 @@ await context.credentials.create(
user_handle=credential["userHandle"],
private_key=credential["privateKey"],
public_key=credential["publicKey"],
+ sign_count=credential["signCount"],
)
await context.credentials.install()
@@ -238,6 +240,7 @@ context.credentials.create(
user_handle=credential["userHandle"],
private_key=credential["privateKey"],
public_key=credential["publicKey"],
+ sign_count=credential["signCount"],
)
context.credentials.install()
@@ -257,6 +260,7 @@ await context.Credentials.CreateAsync(credential.RpId, new()
UserHandle = credential.UserHandle,
PrivateKey = credential.PrivateKey,
PublicKey = credential.PublicKey,
+ SignCount = credential.SignCount,
});
await context.Credentials.InstallAsync();
@@ -278,6 +282,8 @@ See [authentication guide](../auth.md) for examples of using saving and restorin
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.
+- The signature counter of a fresh credential starts at `0` and is incremented by one on every
+ successful `navigator.credentials.get()` assertion. Pass [`option: Credentials.create.signCount`] to seed a different value.
## async method: Credentials.install
* since: v1.61
@@ -300,6 +306,7 @@ page will never see those credentials.
- `userHandle` <[string]> Base64url-encoded user handle.
- `privateKey` <[string]> Base64url-encoded PKCS#8 (DER) private key.
- `publicKey` <[string]> Base64url-encoded SPKI (DER) public key.
+ - `signCount` <[int]> Signature counter, the value reported to the relying party in the most recent assertion.
Seeds a virtual WebAuthn credential and returns it.
@@ -308,7 +315,8 @@ seeded credential is discoverable (resident), so the page can resolve it from bo
username-then-passkey and usernameless passkey flows. The returned object carries the private and public keys, so it can be persisted to disk and re-seeded in a later test.
To **import a known credential**, supply all four of [`option: Credentials.create.id`], [`option: Credentials.create.userHandle`], [`option: Credentials.create.privateKey`] and
-[`option: Credentials.create.publicKey`] together.
+[`option: Credentials.create.publicKey`] together. Pass [`option: Credentials.create.signCount`] as well to continue from the
+signature counter the relying party has already seen.
Call [`method: Credentials.install`] before navigating to a page that uses WebAuthn.
@@ -342,6 +350,13 @@ Base64url-encoded PKCS#8 (DER) private key. Auto-generated if omitted.
Base64url-encoded SPKI (DER) public key. Auto-generated if omitted.
+### option: Credentials.create.signCount
+* since: v1.64
+- `signCount` <[int]>
+
+Initial value of the [signature counter](https://www.w3.org/TR/webauthn-2/#signature-counter). The counter is incremented by one on
+every successful `navigator.credentials.get()` assertion, so the first assertion reports `signCount + 1`. Defaults to `0`.
+
## async method: Credentials.delete
* since: v1.61
@@ -364,12 +379,13 @@ Base64url-encoded credential id.
- `userHandle` <[string]>
- `privateKey` <[string]>
- `publicKey` <[string]>
+ - `signCount` <[int]>
Returns every credential currently held by the authenticator, optionally filtered by [`option: Credentials.get.rpId`] or
[`option: Credentials.get.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 private and public keys, so a passkey the app just
+Each returned credential includes its private and public keys and the current signature counter, 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
diff --git a/packages/playwright-client/types/types.d.ts b/packages/playwright-client/types/types.d.ts
index 7813b47719..b6cb56d11a 100644
--- a/packages/playwright-client/types/types.d.ts
+++ b/packages/playwright-client/types/types.d.ts
@@ -10728,8 +10728,8 @@ export interface BrowserContext {
/**
* Set to `true` to include the context's virtual WebAuthn
* [browserContext.credentials](https://playwright.dev/docs/api/class-browsercontext#browser-context-credentials)
- * (passkeys) in the storage state snapshot. The captured credentials carry their private keys, so they can be
- * re-seeded into a later context via the
+ * (passkeys) in the storage state snapshot. The captured credentials carry their private keys and signature counters,
+ * so they can be re-seeded into a later context via the
* [`storageState`](https://playwright.dev/docs/api/class-browser#browser-new-context-option-storage-state) option or
* [browserContext.setStorageState(storageState)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-storage-state).
* Note that restoring the storage state that contains credentials will automatically install the virtual WebAuthn
@@ -21128,6 +21128,8 @@ export interface Credentials {
* [`userHandle`](https://playwright.dev/docs/api/class-credentials#credentials-create-option-user-handle),
* [`privateKey`](https://playwright.dev/docs/api/class-credentials#credentials-create-option-private-key) and
* [`publicKey`](https://playwright.dev/docs/api/class-credentials#credentials-create-option-public-key) together.
+ * Pass [`signCount`](https://playwright.dev/docs/api/class-credentials#credentials-create-option-sign-count) as well
+ * to continue from the signature counter the relying party has already seen.
*
* Call [credentials.install()](https://playwright.dev/docs/api/class-credentials#credentials-install) before
* navigating to a page that uses WebAuthn.
@@ -21150,6 +21152,13 @@ export interface Credentials {
*/
publicKey?: string;
+ /**
+ * Initial value of the [signature counter](https://www.w3.org/TR/webauthn-2/#signature-counter). The counter is
+ * incremented by one on every successful `navigator.credentials.get()` assertion, so the first assertion reports
+ * `signCount + 1`. Defaults to `0`.
+ */
+ signCount?: number;
+
/**
* Base64url-encoded user handle. Auto-generated if omitted.
*/
@@ -21179,6 +21188,11 @@ export interface Credentials {
* Base64url-encoded SPKI (DER) public key.
*/
publicKey: string;
+
+ /**
+ * Signature counter, the value reported to the relying party in the most recent assertion.
+ */
+ signCount: number;
}>;
/**
@@ -21197,8 +21211,8 @@ export interface Credentials {
* [credentials.create(rpId[, 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 private and public keys, so a passkey the app just registered can be saved
- * and re-seeded into a later test with
+ * Each returned credential includes its private and public keys and the current signature counter, so a passkey the
+ * app just registered can be saved and re-seeded into a later test with
* [credentials.create(rpId[, options])](https://playwright.dev/docs/api/class-credentials#credentials-create) — see
* the second example in the class overview.
* @param options
@@ -21223,6 +21237,8 @@ export interface Credentials {
privateKey: string;
publicKey: string;
+
+ signCount: number;
}>>;
/**
diff --git a/packages/playwright-core/src/client/channels.d.ts b/packages/playwright-core/src/client/channels.d.ts
index 6b2d26cf7e..16e4ab0a86 100644
--- a/packages/playwright-core/src/client/channels.d.ts
+++ b/packages/playwright-core/src/client/channels.d.ts
@@ -15,8 +15,8 @@
*/
// This file is generated by generate_channels.js, do not edit manually.
-import type { Binary, Channel, AndroidWebView, AndroidSelector, AndroidElementInfo, APIResponse, Metadata, ClientSideCallMetadata, SDKLanguage, WaitInfo, HttpCredentials, SetNetworkCookie, NetworkCookie, ResourceTiming, SecurityDetails, RequestSizes, RemoteAddr, ExpectedTextValue, SelectorEngine, FormField, LifecycleEvent, ConsoleMessagesFilter, RecorderSource, IndexedDBDatabase, OPFSEntry, SetOriginStorage, OriginStorage, RecordHarOptions, SerializedValue, SerializedArgument, SerializedError, StackFrame, VirtualCredential, Point, Rect, URLPattern, NameValue } from '@protocol/structs';
-export type { Binary, Channel, AndroidWebView, AndroidSelector, AndroidElementInfo, APIResponse, Metadata, ClientSideCallMetadata, SDKLanguage, WaitInfo, HttpCredentials, SetNetworkCookie, NetworkCookie, ResourceTiming, SecurityDetails, RequestSizes, RemoteAddr, ExpectedTextValue, SelectorEngine, FormField, LifecycleEvent, ConsoleMessagesFilter, RecorderSource, IndexedDBDatabase, OPFSEntry, SetOriginStorage, OriginStorage, RecordHarOptions, SerializedValue, SerializedArgument, SerializedError, StackFrame, VirtualCredential, Point, Rect, URLPattern, NameValue } from '@protocol/structs';
+import type { Binary, Channel, AndroidWebView, AndroidSelector, AndroidElementInfo, APIResponse, Metadata, ClientSideCallMetadata, SDKLanguage, WaitInfo, HttpCredentials, SetNetworkCookie, NetworkCookie, ResourceTiming, SecurityDetails, RequestSizes, RemoteAddr, ExpectedTextValue, SelectorEngine, FormField, LifecycleEvent, ConsoleMessagesFilter, RecorderSource, IndexedDBDatabase, OPFSEntry, SetOriginStorage, OriginStorage, RecordHarOptions, SerializedValue, SerializedArgument, SerializedError, StackFrame, VirtualCredential, SetVirtualCredential, Point, Rect, URLPattern, NameValue } from '@protocol/structs';
+export type { Binary, Channel, AndroidWebView, AndroidSelector, AndroidElementInfo, APIResponse, Metadata, ClientSideCallMetadata, SDKLanguage, WaitInfo, HttpCredentials, SetNetworkCookie, NetworkCookie, ResourceTiming, SecurityDetails, RequestSizes, RemoteAddr, ExpectedTextValue, SelectorEngine, FormField, LifecycleEvent, ConsoleMessagesFilter, RecorderSource, IndexedDBDatabase, OPFSEntry, SetOriginStorage, OriginStorage, RecordHarOptions, SerializedValue, SerializedArgument, SerializedError, StackFrame, VirtualCredential, SetVirtualCredential, Point, Rect, URLPattern, NameValue } from '@protocol/structs';
export type TimeoutOptions = { signal: AbortSignal | undefined, timeout: number };
@@ -918,7 +918,7 @@ export type BrowserNewContextParams = {
storageState?: {
cookies?: SetNetworkCookie[],
origins?: SetOriginStorage[],
- credentials?: VirtualCredential[],
+ credentials?: SetVirtualCredential[],
},
};
export type BrowserNewContextOptions = {
@@ -995,7 +995,7 @@ export type BrowserNewContextOptions = {
storageState?: {
cookies?: SetNetworkCookie[],
origins?: SetOriginStorage[],
- credentials?: VirtualCredential[],
+ credentials?: SetVirtualCredential[],
},
};
export type BrowserNewContextResult = {
@@ -1075,7 +1075,7 @@ export type BrowserNewContextForReuseParams = {
storageState?: {
cookies?: SetNetworkCookie[],
origins?: SetOriginStorage[],
- credentials?: VirtualCredential[],
+ credentials?: SetVirtualCredential[],
},
};
export type BrowserNewContextForReuseOptions = {
@@ -1152,7 +1152,7 @@ export type BrowserNewContextForReuseOptions = {
storageState?: {
cookies?: SetNetworkCookie[],
origins?: SetOriginStorage[],
- credentials?: VirtualCredential[],
+ credentials?: SetVirtualCredential[],
},
};
export type BrowserNewContextForReuseResult = {
@@ -1566,14 +1566,14 @@ export type BrowserContextSetStorageStateParams = {
storageState?: {
cookies?: SetNetworkCookie[],
origins?: SetOriginStorage[],
- credentials?: VirtualCredential[],
+ credentials?: SetVirtualCredential[],
},
};
export type BrowserContextSetStorageStateOptions = {
storageState?: {
cookies?: SetNetworkCookie[],
origins?: SetOriginStorage[],
- credentials?: VirtualCredential[],
+ credentials?: SetVirtualCredential[],
},
};
export type BrowserContextSetStorageStateResult = void;
@@ -1719,12 +1719,14 @@ export type BrowserContextCredentialsCreateParams = {
userHandle?: string,
privateKey?: string,
publicKey?: string,
+ signCount?: number,
};
export type BrowserContextCredentialsCreateOptions = {
id?: string,
userHandle?: string,
privateKey?: string,
publicKey?: string,
+ signCount?: number,
};
export type BrowserContextCredentialsCreateResult = {
credential: VirtualCredential,
diff --git a/packages/playwright-core/src/server/channels.d.ts b/packages/playwright-core/src/server/channels.d.ts
index f16e3626df..465b517b0a 100644
--- a/packages/playwright-core/src/server/channels.d.ts
+++ b/packages/playwright-core/src/server/channels.d.ts
@@ -18,8 +18,8 @@
import type { Progress } from './progress';
-import type { Binary, Channel, AndroidWebView, AndroidSelector, AndroidElementInfo, APIResponse, Metadata, ClientSideCallMetadata, SDKLanguage, WaitInfo, HttpCredentials, SetNetworkCookie, NetworkCookie, ResourceTiming, SecurityDetails, RequestSizes, RemoteAddr, ExpectedTextValue, SelectorEngine, FormField, LifecycleEvent, ConsoleMessagesFilter, RecorderSource, IndexedDBDatabase, OPFSEntry, SetOriginStorage, OriginStorage, RecordHarOptions, SerializedValue, SerializedArgument, SerializedError, StackFrame, VirtualCredential, Point, Rect, URLPattern, NameValue } from '@protocol/structs';
-export type { Binary, Channel, AndroidWebView, AndroidSelector, AndroidElementInfo, APIResponse, Metadata, ClientSideCallMetadata, SDKLanguage, WaitInfo, HttpCredentials, SetNetworkCookie, NetworkCookie, ResourceTiming, SecurityDetails, RequestSizes, RemoteAddr, ExpectedTextValue, SelectorEngine, FormField, LifecycleEvent, ConsoleMessagesFilter, RecorderSource, IndexedDBDatabase, OPFSEntry, SetOriginStorage, OriginStorage, RecordHarOptions, SerializedValue, SerializedArgument, SerializedError, StackFrame, VirtualCredential, Point, Rect, URLPattern, NameValue } from '@protocol/structs';
+import type { Binary, Channel, AndroidWebView, AndroidSelector, AndroidElementInfo, APIResponse, Metadata, ClientSideCallMetadata, SDKLanguage, WaitInfo, HttpCredentials, SetNetworkCookie, NetworkCookie, ResourceTiming, SecurityDetails, RequestSizes, RemoteAddr, ExpectedTextValue, SelectorEngine, FormField, LifecycleEvent, ConsoleMessagesFilter, RecorderSource, IndexedDBDatabase, OPFSEntry, SetOriginStorage, OriginStorage, RecordHarOptions, SerializedValue, SerializedArgument, SerializedError, StackFrame, VirtualCredential, SetVirtualCredential, Point, Rect, URLPattern, NameValue } from '@protocol/structs';
+export type { Binary, Channel, AndroidWebView, AndroidSelector, AndroidElementInfo, APIResponse, Metadata, ClientSideCallMetadata, SDKLanguage, WaitInfo, HttpCredentials, SetNetworkCookie, NetworkCookie, ResourceTiming, SecurityDetails, RequestSizes, RemoteAddr, ExpectedTextValue, SelectorEngine, FormField, LifecycleEvent, ConsoleMessagesFilter, RecorderSource, IndexedDBDatabase, OPFSEntry, SetOriginStorage, OriginStorage, RecordHarOptions, SerializedValue, SerializedArgument, SerializedError, StackFrame, VirtualCredential, SetVirtualCredential, Point, Rect, URLPattern, NameValue } from '@protocol/structs';
// ----------- Initializer Traits -----------
export type InitializerTraits<T> =
@@ -919,7 +919,7 @@ export type BrowserNewContextParams = {
storageState?: {
cookies?: SetNetworkCookie[],
origins?: SetOriginStorage[],
- credentials?: VirtualCredential[],
+ credentials?: SetVirtualCredential[],
},
};
export type BrowserNewContextOptions = {
@@ -996,7 +996,7 @@ export type BrowserNewContextOptions = {
storageState?: {
cookies?: SetNetworkCookie[],
origins?: SetOriginStorage[],
- credentials?: VirtualCredential[],
+ credentials?: SetVirtualCredential[],
},
};
export type BrowserNewContextResult = {
@@ -1076,7 +1076,7 @@ export type BrowserNewContextForReuseParams = {
storageState?: {
cookies?: SetNetworkCookie[],
origins?: SetOriginStorage[],
- credentials?: VirtualCredential[],
+ credentials?: SetVirtualCredential[],
},
};
export type BrowserNewContextForReuseOptions = {
@@ -1153,7 +1153,7 @@ export type BrowserNewContextForReuseOptions = {
storageState?: {
cookies?: SetNetworkCookie[],
origins?: SetOriginStorage[],
- credentials?: VirtualCredential[],
+ credentials?: SetVirtualCredential[],
},
};
export type BrowserNewContextForReuseResult = {
@@ -1567,14 +1567,14 @@ export type BrowserContextSetStorageStateParams = {
storageState?: {
cookies?: SetNetworkCookie[],
origins?: SetOriginStorage[],
- credentials?: VirtualCredential[],
+ credentials?: SetVirtualCredential[],
},
};
export type BrowserContextSetStorageStateOptions = {
storageState?: {
cookies?: SetNetworkCookie[],
origins?: SetOriginStorage[],
- credentials?: VirtualCredential[],
+ credentials?: SetVirtualCredential[],
},
};
export type BrowserContextSetStorageStateResult = void;
@@ -1720,12 +1720,14 @@ export type BrowserContextCredentialsCreateParams = {
userHandle?: string,
privateKey?: string,
publicKey?: string,
+ signCount?: number,
};
export type BrowserContextCredentialsCreateOptions = {
id?: string,
userHandle?: string,
privateKey?: string,
publicKey?: string,
+ signCount?: number,
};
export type BrowserContextCredentialsCreateResult = {
credential: VirtualCredential,
diff --git a/packages/playwright-core/src/server/credentials.ts b/packages/playwright-core/src/server/credentials.ts
index b41bf29e37..26ff3e521f 100644
--- a/packages/playwright-core/src/server/credentials.ts
+++ b/packages/playwright-core/src/server/credentials.ts
@@ -32,10 +32,10 @@ export type VirtualCredential = {
userHandle: string; // base64url
privateKey: string; // base64url(DER PKCS#8)
publicKey: string; // base64url(DER SPKI)
+ signCount: number;
};
type CredentialRecord = VirtualCredential & {
- signCount: number;
isResident: boolean;
};
@@ -55,7 +55,11 @@ export class Credentials {
userHandle?: string,
privateKey?: string,
publicKey?: string,
+ signCount?: number,
}): Promise<VirtualCredential> {
+ const signCount = options.signCount ?? 0;
+ if (signCount < 0 || signCount > 0xffffffff)
+ throw new Error(`signCount must be between 0 and 4294967295, got ${signCount}`);
let privateKey = options.privateKey;
let publicKey = options.publicKey;
if (!privateKey || !publicKey) {
@@ -69,7 +73,7 @@ export class Credentials {
userHandle: options.userHandle || randomBase64Url(16),
privateKey,
publicKey,
- signCount: 0,
+ signCount,
isResident: true,
};
this._registry.set(record.id, record);
@@ -227,7 +231,7 @@ export class Credentials {
}
function toPublic(r: CredentialRecord): VirtualCredential {
- return { id: r.id, rpId: r.rpId, userHandle: r.userHandle, privateKey: r.privateKey, publicKey: r.publicKey };
+ return { id: r.id, rpId: r.rpId, userHandle: r.userHandle, privateKey: r.privateKey, publicKey: r.publicKey, signCount: r.signCount };
}
function randomBase64Url(bytes: number): string {
diff --git a/packages/playwright-core/types/types.d.ts b/packages/playwright-core/types/types.d.ts
index 7813b47719..b6cb56d11a 100644
--- a/packages/playwright-core/types/types.d.ts
+++ b/packages/playwright-core/types/types.d.ts
@@ -10728,8 +10728,8 @@ export interface BrowserContext {
/**
* Set to `true` to include the context's virtual WebAuthn
* [browserContext.credentials](https://playwright.dev/docs/api/class-browsercontext#browser-context-credentials)
- * (passkeys) in the storage state snapshot. The captured credentials carry their private keys, so they can be
- * re-seeded into a later context via the
+ * (passkeys) in the storage state snapshot. The captured credentials carry their private keys and signature counters,
+ * so they can be re-seeded into a later context via the
* [`storageState`](https://playwright.dev/docs/api/class-browser#browser-new-context-option-storage-state) option or
* [browserContext.setStorageState(storageState)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-storage-state).
* Note that restoring the storage state that contains credentials will automatically install the virtual WebAuthn
@@ -21128,6 +21128,8 @@ export interface Credentials {
* [`userHandle`](https://playwright.dev/docs/api/class-credentials#credentials-create-option-user-handle),
* [`privateKey`](https://playwright.dev/docs/api/class-credentials#credentials-create-option-private-key) and
* [`publicKey`](https://playwright.dev/docs/api/class-credentials#credentials-create-option-public-key) together.
+ * Pass [`signCount`](https://playwright.dev/docs/api/class-credentials#credentials-create-option-sign-count) as well
+ * to continue from the signature counter the relying party has already seen.
*
* Call [credentials.install()](https://playwright.dev/docs/api/class-credentials#credentials-install) before
* navigating to a page that uses WebAuthn.
@@ -21150,6 +21152,13 @@ export interface Credentials {
*/
publicKey?: string;
+ /**
+ * Initial value of the [signature counter](https://www.w3.org/TR/webauthn-2/#signature-counter). The counter is
+ * incremented by one on every successful `navigator.credentials.get()` assertion, so the first assertion reports
+ * `signCount + 1`. Defaults to `0`.
+ */
+ signCount?: number;
+
/**
* Base64url-encoded user handle. Auto-generated if omitted.
*/
@@ -21179,6 +21188,11 @@ export interface Credentials {
* Base64url-encoded SPKI (DER) public key.
*/
publicKey: string;
+
+ /**
+ * Signature counter, the value reported to the relying party in the most recent assertion.
+ */
+ signCount: number;
}>;
/**
@@ -21197,8 +21211,8 @@ export interface Credentials {
* [credentials.create(rpId[, 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 private and public keys, so a passkey the app just registered can be saved
- * and re-seeded into a later test with
+ * Each returned credential includes its private and public keys and the current signature counter, so a passkey the
+ * app just registered can be saved and re-seeded into a later test with
* [credentials.create(rpId[, options])](https://playwright.dev/docs/api/class-credentials#credentials-create) — see
* the second example in the class overview.
* @param options
@@ -21223,6 +21237,8 @@ export interface Credentials {
privateKey: string;
publicKey: string;
+
+ signCount: number;
}>>;
/**
diff --git a/packages/protocol/spec/browser.yml b/packages/protocol/spec/browser.yml
index 2e7a4e5ecb..ec5544fd35 100644
--- a/packages/protocol/spec/browser.yml
+++ b/packages/protocol/spec/browser.yml
@@ -78,7 +78,7 @@ Browser:
items: SetOriginStorage
credentials:
type: array?
- items: VirtualCredential
+ items: SetVirtualCredential
returns:
context: BrowserContext
@@ -104,7 +104,7 @@ Browser:
items: SetOriginStorage
credentials:
type: array?
- items: VirtualCredential
+ items: SetVirtualCredential
returns:
context: BrowserContext
diff --git a/packages/protocol/spec/browserContext.yml b/packages/protocol/spec/browserContext.yml
index dc86cf29b1..306f757a92 100644
--- a/packages/protocol/spec/browserContext.yml
+++ b/packages/protocol/spec/browserContext.yml
@@ -207,7 +207,7 @@ BrowserContext:
items: SetOriginStorage
credentials:
type: array?
- items: VirtualCredential
+ items: SetVirtualCredential
pause:
title: Pause
@@ -336,6 +336,7 @@ BrowserContext:
userHandle: string?
privateKey: string?
publicKey: string?
+ signCount: int?
returns:
credential: VirtualCredential
diff --git a/packages/protocol/spec/structs.yml b/packages/protocol/spec/structs.yml
index 7176692771..ab50541f51 100644
--- a/packages/protocol/spec/structs.yml
+++ b/packages/protocol/spec/structs.yml
@@ -28,6 +28,17 @@ VirtualCredential:
userHandle: string
privateKey: string
publicKey: string
+ signCount: int
+
+SetVirtualCredential:
+ type: object
+ properties:
+ id: string
+ rpId: string
+ userHandle: string
+ privateKey: string
+ publicKey: string
+ signCount: int?
Point:
type: object
diff --git a/packages/protocol/src/structs.d.ts b/packages/protocol/src/structs.d.ts
index fbbc33f679..666ca94d64 100644
--- a/packages/protocol/src/structs.d.ts
+++ b/packages/protocol/src/structs.d.ts
@@ -331,6 +331,16 @@ export type VirtualCredential = {
userHandle: string,
privateKey: string,
publicKey: string,
+ signCount: number,
+};
+
+export type SetVirtualCredential = {
+ id: string,
+ rpId: string,
+ userHandle: string,
+ privateKey: string,
+ publicKey: string,
+ signCount?: number,
};
export type Point = {
diff --git a/packages/protocol/src/validator.ts b/packages/protocol/src/validator.ts
index 8df2d2e6e0..36c1583bec 100644
--- a/packages/protocol/src/validator.ts
+++ b/packages/protocol/src/validator.ts
@@ -508,7 +508,7 @@ scheme.BrowserNewContextParams = tObject({
storageState: tOptional(tObject({
cookies: tOptional(tArray(tType('SetNetworkCookie'))),
origins: tOptional(tArray(tType('SetOriginStorage'))),
- credentials: tOptional(tArray(tType('VirtualCredential'))),
+ credentials: tOptional(tArray(tType('SetVirtualCredential'))),
})),
});
scheme.BrowserNewContextResult = tObject({
@@ -588,7 +588,7 @@ scheme.BrowserNewContextForReuseParams = tObject({
storageState: tOptional(tObject({
cookies: tOptional(tArray(tType('SetNetworkCookie'))),
origins: tOptional(tArray(tType('SetOriginStorage'))),
- credentials: tOptional(tArray(tType('VirtualCredential'))),
+ credentials: tOptional(tArray(tType('SetVirtualCredential'))),
})),
});
scheme.BrowserNewContextForReuseResult = tObject({
@@ -863,7 +863,7 @@ scheme.BrowserContextSetStorageStateParams = tObject({
storageState: tOptional(tObject({
cookies: tOptional(tArray(tType('SetNetworkCookie'))),
origins: tOptional(tArray(tType('SetOriginStorage'))),
- credentials: tOptional(tArray(tType('VirtualCredential'))),
+ credentials: tOptional(tArray(tType('SetVirtualCredential'))),
})),
});
scheme.BrowserContextSetStorageStateResult = tOptional(tObject({}));
@@ -954,6 +954,7 @@ scheme.BrowserContextCredentialsCreateParams = tObject({
userHandle: tOptional(tString),
privateKey: tOptional(tString),
publicKey: tOptional(tString),
+ signCount: tOptional(tInt),
});
scheme.BrowserContextCredentialsCreateResult = tObject({
credential: tType('VirtualCredential'),
@@ -3106,6 +3107,15 @@ scheme.VirtualCredential = tObject({
userHandle: tString,
privateKey: tString,
publicKey: tString,
+ signCount: tInt,
+});
+scheme.SetVirtualCredential = tObject({
+ id: tString,
+ rpId: tString,
+ userHandle: tString,
+ privateKey: tString,
+ publicKey: tString,
+ signCount: tOptional(tInt),
});
scheme.Point = tObject({
x: tFloat,
diff --git a/tests/library/browsercontext-webauthn.spec.ts b/tests/library/browsercontext-webauthn.spec.ts
index 40ae4498c1..b43325e94b 100644
--- a/tests/library/browsercontext-webauthn.spec.ts
+++ b/tests/library/browsercontext-webauthn.spec.ts
@@ -16,6 +16,20 @@
import { browserTest as it, expect } from '../config/browserTest';
+import type { Page } from 'playwright-core';
+
+// Runs an assertion ceremony with a discoverable credential, returns the signature counter from the authenticator data.
+async function assertAndGetSignCount(page: Page, rpId: string) {
+ return await page.evaluate(async ({ rpId }) => {
+ const challenge = crypto.getRandomValues(new Uint8Array(32));
+ const cred = await navigator.credentials.get({
+ publicKey: { challenge, rpId, userVerification: 'preferred' },
+ }) as PublicKeyCredential;
+ const resp = cred.response as AuthenticatorAssertionResponse;
+ return new DataView(resp.authenticatorData).getUint32(33);
+ }, { rpId });
+}
+
it('should not intercept navigator.credentials without install()', async ({ contextFactory, server }) => {
const context = await contextFactory();
// Seed a credential, but do not install the interceptor.
@@ -197,3 +211,65 @@ it('should reuse a page-created credential via the storageState option', async (
expect(gotId).toBe(createdId);
});
+
+it('should seed and report signCount', async ({ contextFactory, server }) => {
+ const context = await contextFactory();
+ const fresh = await context.credentials.create('fresh.example.com');
+ expect(fresh.signCount).toBe(0);
+
+ const seeded = await context.credentials.create(server.HOSTNAME, { signCount: 41 });
+ expect(seeded.signCount).toBe(41);
+ await context.credentials.install();
+ const page = await context.newPage();
+ await page.goto(server.EMPTY_PAGE);
+
+ // Each assertion increments the counter and reports the new value to the page.
+ expect(await assertAndGetSignCount(page, server.HOSTNAME)).toBe(42);
+ expect(await assertAndGetSignCount(page, server.HOSTNAME)).toBe(43);
+ expect(await context.credentials.get({ id: seeded.id })).toEqual([{ ...seeded, signCount: 43 }]);
+ expect(await context.credentials.get({ id: fresh.id })).toEqual([fresh]);
+
+ // A captured credential continues from the same counter in another context.
+ const [captured] = await context.credentials.get({ id: seeded.id });
+ const context2 = await contextFactory();
+ await context2.credentials.create(captured.rpId, captured);
+ await context2.credentials.install();
+ const page2 = await context2.newPage();
+ await page2.goto(server.EMPTY_PAGE);
+ expect(await assertAndGetSignCount(page2, server.HOSTNAME)).toBe(44);
+});
+
+it('should reject invalid signCount', async ({ contextFactory }) => {
+ const context = await contextFactory();
+ const error = await context.credentials.create('example.com', { signCount: -1 }).catch(e => e);
+ expect(error.message).toContain('signCount must be between 0 and 4294967295, got -1');
+ expect(await context.credentials.get()).toEqual([]);
+});
+
+it('should preserve signCount via the storageState option', async ({ contextFactory, server }) => {
+ const setupContext = await contextFactory();
+ await setupContext.credentials.create(server.HOSTNAME);
+ await setupContext.credentials.install();
+ const setupPage = await setupContext.newPage();
+ await setupPage.goto(server.EMPTY_PAGE);
+ expect(await assertAndGetSignCount(setupPage, server.HOSTNAME)).toBe(1);
+
+ const storageState = await setupContext.storageState({ credentials: true });
+ const [captured] = await setupContext.credentials.get();
+ expect(captured.signCount).toBe(1);
+ expect(storageState).toEqual({ cookies: [], origins: [], credentials: [captured] });
+
+ const context = await contextFactory({ storageState });
+ const page = await context.newPage();
+ await page.goto(server.EMPTY_PAGE);
+ expect(await assertAndGetSignCount(page, server.HOSTNAME)).toBe(2);
+
+ // Storage state saved by older versions has no signCount, the counter starts from zero.
+ const legacyCredential: Partial<typeof captured> = { ...captured };
+ delete legacyCredential.signCount;
+ const legacyStorageState = { ...storageState, credentials: [legacyCredential] };
+ const legacyContext = await contextFactory({ storageState: legacyStorageState });
+ const legacyPage = await legacyContext.newPage();
+ await legacyPage.goto(server.EMPTY_PAGE);
+ expect(await assertAndGetSignCount(legacyPage, server.HOSTNAME)).toBe(1);
+});