1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
//! WebAuthn virtual-authenticator credentials.
//!
//! Obtained via [`BrowserContext::credentials`](crate::protocol::BrowserContext::credentials).
//! Install a virtual authenticator, then register / list / delete passkeys
//! programmatically to drive `navigator.credentials.create()/get()` ceremonies
//! in tests without real hardware.
//!
//! ```no_run
//! # use playwright_rs::Playwright;
//! # async fn ex() -> playwright_rs::Result<()> {
//! # let pw = Playwright::launch().await?;
//! # let browser = pw.chromium().launch().await?;
//! # let context = browser.new_context().await?;
//! let creds = context.credentials();
//! creds.install().await?;
//! let cred = creds.create("example.com", None).await?;
//! assert_eq!(creds.get(None).await?.len(), 1);
//! creds.delete(&cred.id).await?;
//! # Ok(())
//! # }
//! ```
//!
//! See: <https://playwright.dev/docs/api/class-credentials>
use crate::error::Result;
use crate::server::channel::Channel;
use serde_json::json;
/// A virtual WebAuthn credential (passkey) held by the virtual authenticator.
#[derive(Debug, Clone, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct VirtualCredential {
/// Base64url credential ID.
pub id: String,
/// Relying-party (origin) ID the credential is scoped to.
pub rp_id: String,
/// Base64url user handle, if the credential has one.
#[serde(default)]
pub user_handle: String,
/// Base64url-encoded PKCS#8 private key.
#[serde(default)]
pub private_key: String,
/// Base64url-encoded public key.
#[serde(default)]
pub public_key: String,
}
/// Optional fields for [`Credentials::create`]. When omitted, the authenticator
/// generates them.
#[derive(Debug, Default, Clone)]
#[non_exhaustive]
pub struct CredentialsCreateOptions {
/// Explicit base64url credential ID.
pub id: Option<String>,
/// Base64url user handle to associate.
pub user_handle: Option<String>,
/// Base64url PKCS#8 private key to import.
pub private_key: Option<String>,
/// Base64url public key to import.
pub public_key: Option<String>,
}
impl CredentialsCreateOptions {
/// Set an explicit credential ID.
pub fn id(mut self, id: impl Into<String>) -> Self {
self.id = Some(id.into());
self
}
/// Set the user handle.
pub fn user_handle(mut self, user_handle: impl Into<String>) -> Self {
self.user_handle = Some(user_handle.into());
self
}
/// Import a specific private key (base64url PKCS#8).
pub fn private_key(mut self, private_key: impl Into<String>) -> Self {
self.private_key = Some(private_key.into());
self
}
/// Import a specific public key (base64url).
pub fn public_key(mut self, public_key: impl Into<String>) -> Self {
self.public_key = Some(public_key.into());
self
}
}
/// Filters for [`Credentials::get`]. With no filter set, all credentials are
/// returned.
#[derive(Debug, Default, Clone)]
#[non_exhaustive]
pub struct CredentialsGetOptions {
/// Only return credentials scoped to this relying-party ID.
pub rp_id: Option<String>,
/// Only return the credential with this ID.
pub id: Option<String>,
}
impl CredentialsGetOptions {
/// Filter by relying-party ID.
pub fn rp_id(mut self, rp_id: impl Into<String>) -> Self {
self.rp_id = Some(rp_id.into());
self
}
/// Filter by credential ID.
pub fn id(mut self, id: impl Into<String>) -> Self {
self.id = Some(id.into());
self
}
}
/// Manages the browser context's virtual WebAuthn authenticator.
///
/// See: <https://playwright.dev/docs/api/class-credentials>
#[derive(Clone)]
pub struct Credentials {
channel: Channel,
}
impl std::fmt::Debug for Credentials {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Credentials").finish_non_exhaustive()
}
}
impl Credentials {
pub(crate) fn new(channel: Channel) -> Self {
Self { channel }
}
/// Installs a virtual WebAuthn authenticator on the context. Call before
/// registering credentials or driving `navigator.credentials` ceremonies.
///
/// # Errors
///
/// Returns error if:
/// - The browser context has been closed
/// - Communication with the browser process fails
///
/// See: <https://playwright.dev/docs/api/class-credentials#credentials-install>
pub async fn install(&self) -> Result<()> {
self.channel
.send_no_result("credentialsInstall", json!({}))
.await
}
/// Registers a virtual credential scoped to `rp_id`, returning the created
/// credential (with any authenticator-generated fields filled in).
///
/// # Errors
///
/// Returns error if:
/// - The browser context has been closed
/// - Communication with the browser process fails
///
/// See: <https://playwright.dev/docs/api/class-credentials#credentials-create>
pub async fn create(
&self,
rp_id: &str,
options: impl Into<Option<CredentialsCreateOptions>>,
) -> Result<VirtualCredential> {
let options = options.into();
let mut params = json!({ "rpId": rp_id });
if let Some(o) = options {
if let Some(id) = o.id {
params["id"] = json!(id);
}
if let Some(uh) = o.user_handle {
params["userHandle"] = json!(uh);
}
if let Some(pk) = o.private_key {
params["privateKey"] = json!(pk);
}
if let Some(pk) = o.public_key {
params["publicKey"] = json!(pk);
}
}
#[derive(serde::Deserialize)]
struct R {
credential: VirtualCredential,
}
let r: R = self.channel.send("credentialsCreate", params).await?;
Ok(r.credential)
}
/// Lists virtual credentials, optionally filtered by relying-party or ID.
///
/// # Errors
///
/// Returns error if:
/// - The browser context has been closed
/// - Communication with the browser process fails
///
/// See: <https://playwright.dev/docs/api/class-credentials#credentials-get>
pub async fn get(
&self,
options: impl Into<Option<CredentialsGetOptions>>,
) -> Result<Vec<VirtualCredential>> {
let options = options.into();
let mut params = json!({});
if let Some(o) = options {
if let Some(rp_id) = o.rp_id {
params["rpId"] = json!(rp_id);
}
if let Some(id) = o.id {
params["id"] = json!(id);
}
}
#[derive(serde::Deserialize)]
struct R {
credentials: Vec<VirtualCredential>,
}
let r: R = self.channel.send("credentialsGet", params).await?;
Ok(r.credentials)
}
/// Deletes the credential with the given ID.
///
/// # Errors
///
/// Returns error if:
/// - The browser context has been closed
/// - Communication with the browser process fails
///
/// See: <https://playwright.dev/docs/api/class-credentials#credentials-delete>
pub async fn delete(&self, id: &str) -> Result<()> {
self.channel
.send_no_result("credentialsDelete", json!({ "id": id }))
.await
}
}