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