fastauth_plugin_passkey/lib.rs
1//! Passkeys for [fastauth](https://github.com/lassejlv/fastauth): WebAuthn registration and
2//! sign-in, built on [webauthn-rs](https://docs.rs/webauthn-rs). The routes and JSON match
3//! Better Auth's passkey plugin, so its `passkeyClient` works unchanged.
4//!
5//! ```
6//! use fastauth_core::prelude::*;
7//! use fastauth_plugin_passkey::{Passkey, PasskeyExt};
8//!
9//! let auth: Auth<MemoryAdapter, (), plugins![Passkey]> = FastAuth::builder()
10//! .secret(Secret::from_base64(&Secret::generate()))
11//! .base_url("https://acme.dk")
12//! .database(MemoryAdapter::new())
13//! .email_password(EmailPassword::default())
14//! .plugin(Passkey::new().rp_name("Acme"))
15//! .build()?;
16//! let _passkeys = auth.passkey();
17//! # Ok::<(), BuildError>(())
18//! ```
19//!
20//! Without the plugin registered, `auth.passkey()` doesn't compile:
21//!
22//! ```compile_fail
23//! use fastauth_core::prelude::*;
24//! use fastauth_plugin_passkey::PasskeyExt;
25//!
26//! let auth: Auth<MemoryAdapter> = FastAuth::builder()
27//! .secret(Secret::from_bytes(vec![1u8; 32]))
28//! .base_url("https://acme.dk")
29//! .database(MemoryAdapter::new())
30//! .build()
31//! .unwrap();
32//! let _passkeys = auth.passkey();
33//! ```
34//!
35//! A signed-in user adds a passkey with `generate-register-options` then
36//! `verify-registration`; with [`Passkey::sign_up`], a signed-out visitor does the same and
37//! the passkey creates their user. Anyone signs in with `generate-authenticate-options` then
38//! `verify-authentication`. Each `generate-*` call stores its challenge server-side for five
39//! minutes, in the `verification` table, and names it in a signed `{prefix}.passkey` cookie;
40//! the matching `verify-*` call consumes it, so each challenge works once. Signing in runs the
41//! other plugins' sign-in gates with method `"passkey"`, and checks and advances the
42//! credential's signature counter. A user claimed by proof of their email
43//! ([`Internal::claim_user`](fastauth_core::internal::Internal::claim_user)) loses the
44//! passkeys registered before the proof, inside the claim's transaction.
45
46mod ceremony;
47mod endpoints;
48mod error;
49mod model;
50
51use std::future::Future;
52use std::pin::Pin;
53
54use fastauth_core::config::CoreConfig;
55use fastauth_core::plugin_prelude::*;
56use fastauth_core::{ApiResponse, routes::Status};
57
58pub use endpoints::{
59 DeletePasskey, DeletePasskeyInput, GenerateAuthenticateOptions, GenerateRegisterOptions,
60 GenerateRegisterOptionsInput, ListUserPasskeys, PasskeyView, RegisterOutput, SignInOutput,
61 UpdatePasskey, UpdatePasskeyInput, UpdatePasskeyOutput, VerifyAuthentication,
62 VerifyAuthenticationInput, VerifyRegistration, VerifyRegistrationInput,
63};
64pub use error::PasskeyError;
65pub use model::PasskeyRow;
66pub use webauthn_rs;
67
68/// The passkey plugin: `.plugin(Passkey::new())`.
69///
70/// The relying party defaults to the app: its ID is `base_url`'s host, its name the app name,
71/// and ceremonies may come from `base_url`'s origin or any exact (wildcard-free) trusted
72/// origin. Passkeys always require user verification (a PIN or biometric), as webauthn-rs
73/// does for passkeys.
74#[derive(Clone, Default)]
75pub struct Passkey {
76 rp_id: Option<String>,
77 rp_name: Option<String>,
78 origins: Vec<String>,
79 sign_up: Option<SignUpResolver>,
80}
81
82type SignUpResolver = Arc<
83 dyn Fn(PasskeySignUp) -> Pin<Box<dyn Future<Output = Result<PasskeyUser, AuthError>> + Send>>
84 + Send
85 + Sync,
86>;
87
88impl std::fmt::Debug for Passkey {
89 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
90 f.debug_struct("Passkey")
91 .field("rp_id", &self.rp_id)
92 .field("rp_name", &self.rp_name)
93 .field("origins", &self.origins)
94 .field("sign_up", &self.sign_up.is_some())
95 .finish()
96 }
97}
98
99/// A signed-out registration asking for a user: what [`Passkey::sign_up`]'s resolver gets.
100#[derive(Clone, Debug, Default)]
101#[non_exhaustive]
102pub struct PasskeySignUp {
103 /// The `context` query parameter of `generate-register-options` (Better Auth's
104 /// `addPasskey({ context })`), as the client sent it. Anything the app chooses, such as
105 /// a signed token from its own sign-up form. Untrusted input.
106 pub context: Option<String>,
107 /// The `name` query parameter: the account name the authenticator will show.
108 pub name: Option<String>,
109}
110
111/// The user a passkey-first registration creates.
112#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
113pub struct PasskeyUser {
114 /// Must be a valid email no user has yet; `verify-registration` answers
115 /// `422 USER_ALREADY_EXISTS_USE_ANOTHER_EMAIL` when it's taken by then.
116 pub email: String,
117 pub name: String,
118 /// Whether the app has proven the email belongs to this visitor (default `false`).
119 /// An unverified user is claimed by whoever later proves the email with a magic link,
120 /// an email code or a social account, and that deletes this passkey.
121 pub email_verified: bool,
122}
123
124impl Passkey {
125 pub fn new() -> Self {
126 Self::default()
127 }
128
129 /// The relying party ID passkeys are bound to: a domain, e.g. `acme.dk` to share
130 /// passkeys between `acme.dk` and `app.acme.dk`. Default: `base_url`'s host.
131 pub fn rp_id(mut self, rp_id: impl Into<String>) -> Self {
132 self.rp_id = Some(rp_id.into());
133 self
134 }
135
136 /// The name authenticators show for the site. Default: the app name.
137 pub fn rp_name(mut self, rp_name: impl Into<String>) -> Self {
138 self.rp_name = Some(rp_name.into());
139 self
140 }
141
142 /// An origin ceremonies may come from, e.g. `https://app.acme.dk`. Call it once per
143 /// origin. Setting any replaces the default (`base_url` plus exact trusted origins).
144 pub fn origin(mut self, origin: impl Into<String>) -> Self {
145 self.origins.push(origin.into());
146 self
147 }
148
149 /// Passkey-first sign-up, off by default: a signed-out visitor may register a passkey,
150 /// and registering it creates their user. `resolve` runs in
151 /// `generate-register-options` and decides who that user is, typically from the
152 /// `context` the client passed; an error it returns is the route's answer. The user is
153 /// only created once `verify-registration` has checked the attestation, and with
154 /// `createSession: true` it signs in through the sign-in gates (method `"passkey"`).
155 ///
156 /// Better Auth's `registration: { requireSession: false, resolveUser }`. Signed-in
157 /// users still register as before: a fresh session that may mint credentials.
158 ///
159 /// ```
160 /// use fastauth_core::prelude::*;
161 /// use fastauth_plugin_passkey::{Passkey, PasskeyUser};
162 ///
163 /// let passkey = Passkey::new().sign_up(|request| async move {
164 /// let email = request.context.ok_or_else(|| {
165 /// AuthError::bad_request("INVALID_CONTEXT", "pass the email as context")
166 /// })?;
167 /// Ok(PasskeyUser { name: request.name.unwrap_or_default(), email, ..PasskeyUser::default() })
168 /// });
169 /// ```
170 pub fn sign_up<F, Fut>(mut self, resolve: F) -> Self
171 where
172 F: Fn(PasskeySignUp) -> Fut + Send + Sync + 'static,
173 Fut: Future<Output = Result<PasskeyUser, AuthError>> + Send + 'static,
174 {
175 self.sign_up = Some(Arc::new(move |request| Box::pin(resolve(request))));
176 self
177 }
178
179 /// The relying party for this app's configuration.
180 fn relying_party(&self, config: &CoreConfig) -> Result<webauthn_rs::Webauthn, AuthError> {
181 ceremony::relying_party(
182 self.rp_id.as_deref(),
183 self.rp_name.as_deref(),
184 &self.origins,
185 config,
186 )
187 }
188}
189
190impl Plugin for Passkey {
191 const ID: &'static str = "passkey";
192 type Requires = ();
193 type UserFields = ();
194 type SessionFields = ();
195
196 fn schema(&self, schema: &mut SchemaBuilder) {
197 schema.model::<PasskeyRow>();
198 }
199
200 fn init<D: Adapter>(self: &Arc<Self>, app: &mut PluginBuilder<'_, D>) {
201 app.endpoint(GenerateRegisterOptions(self.clone()))
202 .endpoint(VerifyRegistration(self.clone()))
203 .endpoint(GenerateAuthenticateOptions(self.clone()))
204 .endpoint(VerifyAuthentication(self.clone()))
205 .endpoint(ListUserPasskeys)
206 .endpoint(DeletePasskey)
207 .endpoint(UpdatePasskey)
208 .errors::<PasskeyError>()
209 .on_claim(|claim| {
210 Box::pin(async move {
211 claim
212 .db()
213 .delete::<PasskeyRow>(PasskeyRow::USER_ID.eq(claim.user_id()))
214 .await?;
215 Ok(())
216 })
217 });
218 }
219}
220
221/// Emitted when a user registers a passkey.
222#[derive(Clone, Debug, PartialEq, Eq)]
223pub struct PasskeyAdded {
224 pub user_id: Id,
225 pub passkey_id: Id,
226}
227
228/// Emitted when a user deletes one of their passkeys.
229#[derive(Clone, Debug, PartialEq, Eq)]
230pub struct PasskeyDeleted {
231 pub user_id: Id,
232 pub passkey_id: Id,
233}
234
235impl Event for PasskeyAdded {}
236impl Event for PasskeyDeleted {}
237
238/// `auth.passkey()`: the server API. Only compiles on an `Auth` with `Passkey` registered.
239pub trait PasskeyExt: AuthInstance + Sized {
240 fn passkey<I>(&self) -> PasskeyApi<'_, Self>
241 where
242 Self: HasPlugin<Passkey, I>,
243 {
244 PasskeyApi { auth: self }
245 }
246}
247
248impl<A: AuthInstance> PasskeyExt for A {}
249
250/// Manages a user's passkeys without HTTP. `headers` are the request's: their cookies carry
251/// the session. Registering and signing in need a browser, so they go over HTTP.
252pub struct PasskeyApi<'a, A> {
253 auth: &'a A,
254}
255
256impl<A: AuthInstance> PasskeyApi<'_, A> {
257 /// `GET /passkey/list-user-passkeys`.
258 pub async fn list(&self, headers: &HeaderMap) -> Result<Vec<PasskeyView>, AuthError> {
259 Ok(self
260 .auth
261 .api()
262 .headers(headers)
263 .call(&ListUserPasskeys, Empty {})
264 .await?
265 .data)
266 }
267
268 /// `POST /passkey/update-passkey`: renames one of the user's passkeys.
269 pub async fn update(
270 &self,
271 headers: &HeaderMap,
272 input: UpdatePasskeyInput,
273 ) -> Result<ApiResponse<UpdatePasskeyOutput>, AuthError> {
274 self.auth
275 .api()
276 .headers(headers)
277 .call(&UpdatePasskey, input)
278 .await
279 }
280
281 /// `POST /passkey/delete-passkey`.
282 pub async fn delete(
283 &self,
284 headers: &HeaderMap,
285 input: DeletePasskeyInput,
286 ) -> Result<ApiResponse<Status>, AuthError> {
287 self.auth
288 .api()
289 .headers(headers)
290 .call(&DeletePasskey, input)
291 .await
292 }
293}