Skip to main content

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