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`; anyone signs in with `generate-authenticate-options` then
37//! `verify-authentication`. Each `generate-*` call stores its challenge server-side for five
38//! minutes, in the `verification` table, and names it in a signed `{prefix}.passkey` cookie;
39//! the matching `verify-*` call consumes it, so each challenge works once. Signing in runs the
40//! other plugins' sign-in gates with method `"passkey"`, and checks and advances the
41//! credential's signature counter.
42
43mod ceremony;
44mod endpoints;
45mod error;
46mod model;
47
48use fastauth_core::config::CoreConfig;
49use fastauth_core::plugin_prelude::*;
50use fastauth_core::{ApiResponse, routes::Status};
51
52pub use endpoints::{
53    DeletePasskey, DeletePasskeyInput, GenerateAuthenticateOptions, GenerateRegisterOptions,
54    GenerateRegisterOptionsInput, ListUserPasskeys, PasskeyView, RegisterOutput, SignInOutput,
55    UpdatePasskey, UpdatePasskeyInput, UpdatePasskeyOutput, VerifyAuthentication,
56    VerifyAuthenticationInput, VerifyRegistration, VerifyRegistrationInput,
57};
58pub use error::PasskeyError;
59pub use model::PasskeyRow;
60pub use webauthn_rs;
61
62/// The passkey plugin: `.plugin(Passkey::new())`.
63///
64/// The relying party defaults to the app: its ID is `base_url`'s host, its name the app name,
65/// and ceremonies may come from `base_url`'s origin or any exact (wildcard-free) trusted
66/// origin. Passkeys always require user verification (a PIN or biometric), as webauthn-rs
67/// does for passkeys.
68#[derive(Clone, Debug, Default)]
69pub struct Passkey {
70    rp_id: Option<String>,
71    rp_name: Option<String>,
72    origins: Vec<String>,
73}
74
75impl Passkey {
76    pub fn new() -> Self {
77        Self::default()
78    }
79
80    /// The relying party ID passkeys are bound to: a domain, e.g. `acme.dk` to share
81    /// passkeys between `acme.dk` and `app.acme.dk`. Default: `base_url`'s host.
82    pub fn rp_id(mut self, rp_id: impl Into<String>) -> Self {
83        self.rp_id = Some(rp_id.into());
84        self
85    }
86
87    /// The name authenticators show for the site. Default: the app name.
88    pub fn rp_name(mut self, rp_name: impl Into<String>) -> Self {
89        self.rp_name = Some(rp_name.into());
90        self
91    }
92
93    /// An origin ceremonies may come from, e.g. `https://app.acme.dk`. Call it once per
94    /// origin. Setting any replaces the default (`base_url` plus exact trusted origins).
95    pub fn origin(mut self, origin: impl Into<String>) -> Self {
96        self.origins.push(origin.into());
97        self
98    }
99
100    /// The relying party for this app's configuration.
101    fn relying_party(&self, config: &CoreConfig) -> Result<webauthn_rs::Webauthn, AuthError> {
102        ceremony::relying_party(
103            self.rp_id.as_deref(),
104            self.rp_name.as_deref(),
105            &self.origins,
106            config,
107        )
108    }
109}
110
111impl Plugin for Passkey {
112    const ID: &'static str = "passkey";
113    type Requires = ();
114    type UserFields = ();
115    type SessionFields = ();
116
117    fn schema(&self, schema: &mut SchemaBuilder) {
118        schema.model::<PasskeyRow>();
119    }
120
121    fn init<D: Adapter>(self: &Arc<Self>, app: &mut PluginBuilder<'_, D>) {
122        app.endpoint(GenerateRegisterOptions(self.clone()))
123            .endpoint(VerifyRegistration(self.clone()))
124            .endpoint(GenerateAuthenticateOptions(self.clone()))
125            .endpoint(VerifyAuthentication(self.clone()))
126            .endpoint(ListUserPasskeys)
127            .endpoint(DeletePasskey)
128            .endpoint(UpdatePasskey)
129            .errors::<PasskeyError>();
130    }
131}
132
133/// Emitted when a user registers a passkey.
134#[derive(Clone, Debug, PartialEq, Eq)]
135pub struct PasskeyAdded {
136    pub user_id: Id,
137    pub passkey_id: Id,
138}
139
140/// Emitted when a user deletes one of their passkeys.
141#[derive(Clone, Debug, PartialEq, Eq)]
142pub struct PasskeyDeleted {
143    pub user_id: Id,
144    pub passkey_id: Id,
145}
146
147impl Event for PasskeyAdded {}
148impl Event for PasskeyDeleted {}
149
150/// `auth.passkey()`: the server API. Only compiles on an `Auth` with `Passkey` registered.
151pub trait PasskeyExt: AuthInstance + Sized {
152    fn passkey<I>(&self) -> PasskeyApi<'_, Self>
153    where
154        Self: HasPlugin<Passkey, I>,
155    {
156        PasskeyApi { auth: self }
157    }
158}
159
160impl<A: AuthInstance> PasskeyExt for A {}
161
162/// Manages a user's passkeys without HTTP. `headers` are the request's: their cookies carry
163/// the session. Registering and signing in need a browser, so they go over HTTP.
164pub struct PasskeyApi<'a, A> {
165    auth: &'a A,
166}
167
168impl<A: AuthInstance> PasskeyApi<'_, A> {
169    /// `GET /passkey/list-user-passkeys`.
170    pub async fn list(&self, headers: &HeaderMap) -> Result<Vec<PasskeyView>, AuthError> {
171        Ok(self
172            .auth
173            .api()
174            .headers(headers)
175            .call(&ListUserPasskeys, Empty {})
176            .await?
177            .data)
178    }
179
180    /// `POST /passkey/update-passkey`: renames one of the user's passkeys.
181    pub async fn update(
182        &self,
183        headers: &HeaderMap,
184        input: UpdatePasskeyInput,
185    ) -> Result<ApiResponse<UpdatePasskeyOutput>, AuthError> {
186        self.auth
187            .api()
188            .headers(headers)
189            .call(&UpdatePasskey, input)
190            .await
191    }
192
193    /// `POST /passkey/delete-passkey`.
194    pub async fn delete(
195        &self,
196        headers: &HeaderMap,
197        input: DeletePasskeyInput,
198    ) -> Result<ApiResponse<Status>, AuthError> {
199        self.auth
200            .api()
201            .headers(headers)
202            .call(&DeletePasskey, input)
203            .await
204    }
205}