Skip to main content

fastauth_plugin_passkey/
endpoints.rs

1//! The `/passkey/*` endpoints.
2
3use fastauth_core::crypto::base64url;
4use fastauth_core::plugin_prelude::*;
5use fastauth_core::routes::Status;
6use serde_json::{Map, Value as Json};
7use webauthn_rs::prelude::{
8    Credential, PublicKeyCredential, RegisterPublicKeyCredential, Uuid, WebauthnError,
9};
10use webauthn_rs_proto::{
11    AllowCredentials, AuthenticatorAttachment, PublicKeyCredentialCreationOptions,
12    PublicKeyCredentialDescriptor, PublicKeyCredentialRequestOptions, ResidentKeyRequirement,
13};
14
15use crate::ceremony::{
16    self, CHALLENGE_COOKIE, CHALLENGE_TTL, Challenge, IDENTIFIER, MULTI_DEVICE, SINGLE_DEVICE,
17};
18use crate::model::PasskeyRow;
19use crate::{Passkey, PasskeyAdded, PasskeyDeleted, PasskeyError};
20
21/// A passkey as clients see it: Better Auth's row, camelCase, `credentialID` included.
22#[derive(Clone, Debug, Serialize)]
23#[serde(rename_all = "camelCase")]
24pub struct PasskeyView {
25    pub id: Id,
26    pub name: Option<String>,
27    pub public_key: String,
28    pub user_id: Id,
29    #[serde(rename = "credentialID")]
30    pub credential_id: String,
31    pub counter: i64,
32    pub device_type: String,
33    pub backed_up: bool,
34    pub transports: Option<String>,
35    #[serde(with = "time::serde::rfc3339")]
36    pub created_at: OffsetDateTime,
37    pub aaguid: Option<String>,
38}
39
40impl From<PasskeyRow> for PasskeyView {
41    fn from(row: PasskeyRow) -> Self {
42        Self {
43            id: row.id,
44            name: row.name,
45            public_key: row.public_key,
46            user_id: row.user_id,
47            credential_id: row.credential_id,
48            counter: row.counter,
49            device_type: row.device_type,
50            backed_up: row.backed_up,
51            transports: row.transports,
52            created_at: row.created_at,
53            aaguid: row.aaguid,
54        }
55    }
56}
57
58/// Starts a ceremony: stores its state for `CHALLENGE_TTL` and names it in the signed cookie.
59async fn store_challenge<D: Adapter, A>(
60    ctx: &Ctx<D, A>,
61    challenge: &Challenge,
62) -> Result<(), AuthError> {
63    let data = serde_json::to_string(challenge).map_err(AuthError::internal)?;
64    let token = ctx
65        .internal()
66        .create_verification(IDENTIFIER, CHALLENGE_TTL, Some(data))
67        .await?;
68    ctx.set_signed_cookie(CHALLENGE_COOKIE, &token, Some(CHALLENGE_TTL));
69    Ok(())
70}
71
72/// Consumes the challenge the cookie names. Each one works once, whatever the outcome.
73async fn take_challenge<D: Adapter, A>(ctx: &Ctx<D, A>) -> Result<Challenge, AuthError> {
74    let token = ctx
75        .signed_cookie(CHALLENGE_COOKIE)
76        .ok_or(PasskeyError::ChallengeNotFound)?;
77    ctx.delete_cookie(CHALLENGE_COOKIE);
78    ctx.internal()
79        .consume_verification(&token)
80        .await?
81        .filter(|v| v.identifier == IDENTIFIER)
82        .and_then(|v| serde_json::from_str(v.data.as_deref()?).ok())
83        .ok_or_else(|| PasskeyError::ChallengeNotFound.into())
84}
85
86async fn user_passkeys<D: Adapter, A>(
87    ctx: &Ctx<D, A>,
88    user_id: &Id,
89) -> Result<Vec<PasskeyRow>, AuthError> {
90    Ok(ctx
91        .db()
92        .find::<PasskeyRow>(PasskeyRow::USER_ID.eq(user_id))
93        .all()
94        .await?)
95}
96
97/// Query of `/passkey/generate-register-options`.
98#[derive(Debug, Default, Deserialize)]
99#[serde(rename_all = "camelCase")]
100pub struct GenerateRegisterOptionsInput {
101    /// `platform` for this device's authenticator, `cross-platform` for a security key or
102    /// phone.
103    #[serde(default)]
104    pub authenticator_attachment: Option<AuthenticatorAttachment>,
105    /// The account name the authenticator shows. Default: the user's email.
106    #[serde(default)]
107    pub name: Option<String>,
108    /// Better Auth's passkey-first registration context. Accepted and ignored: fastauth
109    /// registers passkeys for signed-in users only.
110    #[serde(default)]
111    pub context: Option<String>,
112}
113
114/// `GET /passkey/generate-register-options`: the `PublicKeyCredentialCreationOptions` to
115/// pass to `navigator.credentials.create()`. Needs a fresh session. The user's passkeys are
116/// excluded, so an authenticator can't register twice.
117pub struct GenerateRegisterOptions(pub(crate) Arc<Passkey>);
118
119impl<D: Adapter> Endpoint<D> for GenerateRegisterOptions {
120    const METHOD: Method = Method::GET;
121    const PATH: &'static str = "/passkey/generate-register-options";
122    type Access = Fresh;
123    type Input = GenerateRegisterOptionsInput;
124    type Output = PublicKeyCredentialCreationOptions;
125
126    async fn call(
127        &self,
128        ctx: Ctx<D, Fresh>,
129        input: GenerateRegisterOptionsInput,
130    ) -> Result<PublicKeyCredentialCreationOptions, AuthError> {
131        let user = &ctx.session().user;
132        let rp = self.0.relying_party(ctx.config())?;
133        let existing = user_passkeys(&ctx, &user.id).await?;
134        let exclude = existing
135            .iter()
136            .map(|row| {
137                Ok(PublicKeyCredentialDescriptor {
138                    type_: "public-key".into(),
139                    id: ceremony::credential_id(row)?,
140                    transports: ceremony::transports(row.transports.as_deref()),
141                })
142            })
143            .collect::<Result<Vec<_>, AuthError>>()?;
144        let account = if user.email.is_empty() {
145            user.id.as_str()
146        } else {
147            &user.email
148        };
149        let user_name = input.name.as_deref().filter(|n| !n.is_empty());
150        let (mut options, state) = rp
151            .start_passkey_registration(
152                Uuid::new_v4(),
153                user_name.unwrap_or(account),
154                account,
155                Some(exclude.iter().map(|d| d.id.clone()).collect()),
156            )
157            .map_err(AuthError::internal)?;
158        let options = &mut options.public_key;
159        options.exclude_credentials = Some(exclude);
160        if let Some(selection) = &mut options.authenticator_selection {
161            selection.resident_key = Some(ResidentKeyRequirement::Preferred);
162            selection.require_resident_key = false;
163            selection.authenticator_attachment = input.authenticator_attachment;
164        }
165        store_challenge(
166            &ctx,
167            &Challenge::Registration {
168                user_id: user.id.to_string(),
169                state,
170            },
171        )
172        .await?;
173        Ok(options.clone())
174    }
175}
176
177/// Body of `/passkey/verify-registration`.
178#[derive(Debug, Deserialize)]
179#[serde(rename_all = "camelCase")]
180pub struct VerifyRegistrationInput {
181    /// The `navigator.credentials.create()` result as JSON (`RegistrationResponseJSON`).
182    pub response: Json,
183    /// A name for the passkey.
184    #[serde(default)]
185    pub name: Option<String>,
186    /// Also start a new session, as Better Auth does.
187    #[serde(default)]
188    pub create_session: Option<bool>,
189}
190
191/// The new passkey; with `createSession`, also the new session and the user.
192#[derive(Debug, Serialize)]
193pub struct RegisterOutput {
194    #[serde(flatten)]
195    pub passkey: PasskeyView,
196    #[serde(skip_serializing_if = "Option::is_none")]
197    pub session: Option<Map<String, Json>>,
198    #[serde(skip_serializing_if = "Option::is_none")]
199    pub user: Option<Map<String, Json>>,
200}
201
202/// `POST /passkey/verify-registration`: verifies the authenticator's attestation against the
203/// challenge from `generate-register-options` and stores the passkey. Needs a fresh session,
204/// the same user's.
205pub struct VerifyRegistration(pub(crate) Arc<Passkey>);
206
207impl<D: Adapter> Endpoint<D> for VerifyRegistration {
208    const METHOD: Method = Method::POST;
209    const PATH: &'static str = "/passkey/verify-registration";
210    type Access = Fresh;
211    type Input = VerifyRegistrationInput;
212    type Output = RegisterOutput;
213
214    async fn call(
215        &self,
216        ctx: Ctx<D, Fresh>,
217        input: VerifyRegistrationInput,
218    ) -> Result<RegisterOutput, AuthError> {
219        let rp = self.0.relying_party(ctx.config())?;
220        let Challenge::Registration { user_id, state } = take_challenge(&ctx).await? else {
221            return Err(PasskeyError::ChallengeNotFound.into());
222        };
223        let user_id = Id::from(user_id);
224        if user_id != ctx.session().user.id {
225            return Err(PasskeyError::NotAllowed.into());
226        }
227        let failed = PasskeyError::FailedToVerifyRegistration;
228        let transports = input.response["response"]["transports"]
229            .as_array()
230            .map(|t| {
231                t.iter()
232                    .filter_map(Json::as_str)
233                    .collect::<Vec<_>>()
234                    .join(",")
235            })
236            .unwrap_or_default();
237        let response: RegisterPublicKeyCredential =
238            serde_json::from_value(input.response).map_err(|_| failed)?;
239        let passkey = rp
240            .finish_passkey_registration(&response, &state)
241            .map_err(|_| failed)?;
242        let attested = ceremony::attested(&response.response.attestation_object).ok_or(failed)?;
243        let credential = Credential::from(passkey);
244        let credential_id = base64url(&credential.cred_id);
245        if ctx
246            .db()
247            .find::<PasskeyRow>(PasskeyRow::CREDENTIAL_ID.eq(&credential_id))
248            .one()
249            .await?
250            .is_some()
251        {
252            return Err(failed.into());
253        }
254        let row = PasskeyRow {
255            id: ctx.new_id()?,
256            name: input
257                .name
258                .map(|n| n.trim().to_owned())
259                .filter(|n| !n.is_empty()),
260            public_key: attested.public_key,
261            user_id: user_id.clone(),
262            credential_id,
263            counter: i64::from(credential.counter),
264            device_type: if credential.backup_eligible {
265                MULTI_DEVICE
266            } else {
267                SINGLE_DEVICE
268            }
269            .into(),
270            backed_up: credential.backup_state,
271            transports: Some(transports),
272            created_at: ctx.now(),
273            aaguid: Some(attested.aaguid),
274        };
275        ctx.db().insert(&row).await?;
276        ctx.emit(PasskeyAdded {
277            user_id: user_id.clone(),
278            passkey_id: row.id.clone(),
279        });
280        let (session, user) = if input.create_session == Some(true) {
281            let session = ctx.internal().create_session(&user_id, true).await?;
282            (Some(session.to_json()), Some(session.user.to_json()))
283        } else {
284            (None, None)
285        };
286        Ok(RegisterOutput {
287            passkey: row.into(),
288            session,
289            user,
290        })
291    }
292}
293
294/// `GET /passkey/generate-authenticate-options`: the `PublicKeyCredentialRequestOptions` to
295/// pass to `navigator.credentials.get()`. Signed out, any discoverable passkey for this site
296/// may answer; signed in, the options list the user's passkeys.
297pub struct GenerateAuthenticateOptions(pub(crate) Arc<Passkey>);
298
299impl<D: Adapter> Endpoint<D> for GenerateAuthenticateOptions {
300    const METHOD: Method = Method::GET;
301    const PATH: &'static str = "/passkey/generate-authenticate-options";
302    type Access = MaybeAuthenticated;
303    type Input = Empty;
304    type Output = PublicKeyCredentialRequestOptions;
305
306    async fn call(
307        &self,
308        ctx: Ctx<D, MaybeAuthenticated>,
309        _: Empty,
310    ) -> Result<PublicKeyCredentialRequestOptions, AuthError> {
311        let rp = self.0.relying_party(ctx.config())?;
312        let (options, state) = rp
313            .start_discoverable_authentication()
314            .map_err(AuthError::internal)?;
315        let mut options = options.public_key;
316        if let Some(session) = ctx.session() {
317            options.allow_credentials = user_passkeys(&ctx, &session.user.id)
318                .await?
319                .iter()
320                .map(|row| {
321                    Ok(AllowCredentials {
322                        type_: "public-key".into(),
323                        id: ceremony::credential_id(row)?,
324                        transports: ceremony::transports(row.transports.as_deref()),
325                    })
326                })
327                .collect::<Result<_, AuthError>>()?;
328        }
329        store_challenge(&ctx, &Challenge::Authentication { state }).await?;
330        Ok(options)
331    }
332}
333
334/// Body of `/passkey/verify-authentication`.
335#[derive(Debug, Deserialize)]
336pub struct VerifyAuthenticationInput {
337    /// The `navigator.credentials.get()` result as JSON (`AuthenticationResponseJSON`).
338    pub response: Json,
339}
340
341/// What a passkey sign-in answers.
342#[derive(Debug, Serialize)]
343#[serde(untagged)]
344pub enum SignInOutput {
345    /// Signed in: Better Auth's `{ session, user }`.
346    SignedIn {
347        session: Map<String, Json>,
348        user: Map<String, Json>,
349    },
350    /// A sign-in gate's answer, e.g. `{"twoFactorRedirect": true}`. No session exists yet.
351    Challenge(Json),
352}
353
354/// `POST /passkey/verify-authentication`: verifies the assertion against the challenge from
355/// `generate-authenticate-options` and the stored public key, checks and advances the
356/// signature counter, then signs the passkey's user in through the sign-in gates (method
357/// `"passkey"`).
358pub struct VerifyAuthentication(pub(crate) Arc<Passkey>);
359
360impl<D: Adapter> Endpoint<D> for VerifyAuthentication {
361    const METHOD: Method = Method::POST;
362    const PATH: &'static str = "/passkey/verify-authentication";
363    type Access = Public;
364    type Input = VerifyAuthenticationInput;
365    type Output = SignInOutput;
366
367    async fn call(
368        &self,
369        ctx: Ctx<D, Public>,
370        input: VerifyAuthenticationInput,
371    ) -> Result<SignInOutput, AuthError> {
372        let rp = self.0.relying_party(ctx.config())?;
373        let Challenge::Authentication { state } = take_challenge(&ctx).await? else {
374            return Err(PasskeyError::ChallengeNotFound.into());
375        };
376        let response: PublicKeyCredential =
377            serde_json::from_value(input.response).map_err(|_| PasskeyError::InvalidAssertion)?;
378        let row = ctx
379            .db()
380            .find::<PasskeyRow>(PasskeyRow::CREDENTIAL_ID.eq(base64url(&response.raw_id)))
381            .one()
382            .await?
383            .ok_or(PasskeyError::UnknownCredential)?;
384        let credential = ceremony::credential(&row)?;
385        let result = rp
386            .finish_discoverable_authentication_v2(&response, state, &credential)
387            .map_err(|err| match err {
388                WebauthnError::AuthenticationFailure => PasskeyError::AuthenticationFailed,
389                _ => PasskeyError::InvalidAssertion,
390            })?;
391        let counter = i64::from(result.counter().max(credential.counter));
392        let advanced = ctx
393            .db()
394            .update::<PasskeyRow>(
395                PasskeyRow::ID
396                    .eq(&row.id)
397                    .and(PasskeyRow::COUNTER.eq(row.counter)),
398            )
399            .set(PasskeyRow::COUNTER, counter)
400            .set(PasskeyRow::BACKED_UP, result.backup_state())
401            .exec()
402            .await?;
403        if advanced == 0 {
404            return Err(PasskeyError::InvalidAssertion.into());
405        }
406        let user = ctx
407            .internal()
408            .find_user_by_id(&row.user_id)
409            .await?
410            .ok_or_else(|| AuthError::internal("a passkey's user is gone"))?;
411        Ok(
412            match ctx.internal().sign_in(user, Passkey::ID, true).await? {
413                SignInResult::SignedIn(session) => SignInOutput::SignedIn {
414                    session: session.to_json(),
415                    user: session.user.to_json(),
416                },
417                SignInResult::Challenge(body) => SignInOutput::Challenge(body),
418            },
419        )
420    }
421}
422
423/// `GET /passkey/list-user-passkeys`: the signed-in user's passkeys.
424pub struct ListUserPasskeys;
425
426impl<D: Adapter> Endpoint<D> for ListUserPasskeys {
427    const METHOD: Method = Method::GET;
428    const PATH: &'static str = "/passkey/list-user-passkeys";
429    type Access = Authenticated;
430    type Input = Empty;
431    type Output = Vec<PasskeyView>;
432
433    async fn call(
434        &self,
435        ctx: Ctx<D, Authenticated>,
436        _: Empty,
437    ) -> Result<Vec<PasskeyView>, AuthError> {
438        let rows = user_passkeys(&ctx, &ctx.session().user.id).await?;
439        Ok(rows.into_iter().map(PasskeyView::from).collect())
440    }
441}
442
443/// The caller's passkey `id`: 404 `PASSKEY_NOT_FOUND` when there's none, 401 `not_yours`
444/// when it's someone else's, as Better Auth's ownership check answers.
445async fn own_passkey<D: Adapter>(
446    ctx: &Ctx<D, Authenticated>,
447    id: &str,
448    not_yours: AuthError,
449) -> Result<PasskeyRow, AuthError> {
450    let row = ctx
451        .db()
452        .find::<PasskeyRow>(PasskeyRow::ID.eq(Id::from(id)))
453        .one()
454        .await?
455        .ok_or(PasskeyError::PasskeyNotFound)?;
456    if row.user_id != ctx.session().user.id {
457        return Err(not_yours);
458    }
459    Ok(row)
460}
461
462/// Body of `/passkey/delete-passkey`.
463#[derive(Debug, Deserialize)]
464pub struct DeletePasskeyInput {
465    pub id: String,
466}
467
468/// `POST /passkey/delete-passkey`: deletes one of the signed-in user's passkeys.
469pub struct DeletePasskey;
470
471impl<D: Adapter> Endpoint<D> for DeletePasskey {
472    const METHOD: Method = Method::POST;
473    const PATH: &'static str = "/passkey/delete-passkey";
474    type Access = Authenticated;
475    type Input = DeletePasskeyInput;
476    type Output = Status;
477
478    async fn call(
479        &self,
480        ctx: Ctx<D, Authenticated>,
481        input: DeletePasskeyInput,
482    ) -> Result<Status, AuthError> {
483        let not_yours = AuthError::new(
484            StatusCode::UNAUTHORIZED,
485            codes::UNAUTHORIZED,
486            "Unauthorized",
487        );
488        let row = own_passkey(&ctx, &input.id, not_yours).await?;
489        ctx.db()
490            .delete::<PasskeyRow>(PasskeyRow::ID.eq(&row.id))
491            .await?;
492        ctx.emit(PasskeyDeleted {
493            user_id: row.user_id,
494            passkey_id: row.id,
495        });
496        Ok(Status { status: true })
497    }
498}
499
500/// Body of `/passkey/update-passkey`.
501#[derive(Debug, Deserialize)]
502pub struct UpdatePasskeyInput {
503    pub id: String,
504    /// The new name; trimmed, and not empty.
505    pub name: String,
506}
507
508#[derive(Debug, Serialize)]
509pub struct UpdatePasskeyOutput {
510    pub passkey: PasskeyView,
511}
512
513/// `POST /passkey/update-passkey`: renames one of the signed-in user's passkeys.
514pub struct UpdatePasskey;
515
516impl<D: Adapter> Endpoint<D> for UpdatePasskey {
517    const METHOD: Method = Method::POST;
518    const PATH: &'static str = "/passkey/update-passkey";
519    type Access = Authenticated;
520    type Input = UpdatePasskeyInput;
521    type Output = UpdatePasskeyOutput;
522
523    async fn call(
524        &self,
525        ctx: Ctx<D, Authenticated>,
526        input: UpdatePasskeyInput,
527    ) -> Result<UpdatePasskeyOutput, AuthError> {
528        let name = input.name.trim();
529        if name.is_empty() {
530            return Err(AuthError::bad_request(
531                codes::INVALID_BODY,
532                "name must not be empty",
533            ));
534        }
535        let mut row = own_passkey(&ctx, &input.id, PasskeyError::NotAllowed.into()).await?;
536        ctx.db()
537            .update::<PasskeyRow>(PasskeyRow::ID.eq(&row.id))
538            .set(PasskeyRow::NAME, Some(name.to_owned()))
539            .exec()
540            .await?;
541        row.name = Some(name.to_owned());
542        Ok(UpdatePasskeyOutput {
543            passkey: row.into(),
544        })
545    }
546}