1use fastauth_core::crypto::base64url;
4use fastauth_core::plugin_prelude::*;
5use fastauth_core::routes::{Status, normalize_email};
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, PasskeySignUp, PasskeyUser};
20
21#[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
58async 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
72async 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
97async fn registering_session<D: Adapter>(
101 ctx: &Ctx<D, MaybeAuthenticated>,
102) -> Result<Option<SessionView>, AuthError> {
103 match ctx.session() {
104 None => Ok(None),
105 Some(session) if session.ephemeral || !ctx.config().is_fresh(&session.session) => {
106 Err(AuthError::not_fresh())
107 }
108 Some(_) => ctx.sensitive_session().await.map(Some),
109 }
110}
111
112enum Registrant {
114 User(UserView),
116 SignUp(PasskeyUser),
118}
119
120#[derive(Debug, Default, Deserialize)]
122#[serde(rename_all = "camelCase")]
123pub struct GenerateRegisterOptionsInput {
124 #[serde(default)]
127 pub authenticator_attachment: Option<AuthenticatorAttachment>,
128 #[serde(default)]
130 pub name: Option<String>,
131 #[serde(default)]
134 pub context: Option<String>,
135}
136
137pub struct GenerateRegisterOptions(pub(crate) Arc<Passkey>);
144
145impl<D: Adapter> Endpoint<D> for GenerateRegisterOptions {
146 const METHOD: Method = Method::GET;
147 const PATH: &'static str = "/passkey/generate-register-options";
148 type Access = MaybeAuthenticated;
149 type Input = GenerateRegisterOptionsInput;
150 type Output = PublicKeyCredentialCreationOptions;
151
152 async fn call(
153 &self,
154 ctx: Ctx<D, MaybeAuthenticated>,
155 input: GenerateRegisterOptionsInput,
156 ) -> Result<PublicKeyCredentialCreationOptions, AuthError> {
157 let (account, exclude, pending) = match registering_session(&ctx).await? {
158 Some(session) => {
159 let user = session.user;
160 let exclude = user_passkeys(&ctx, &user.id)
161 .await?
162 .iter()
163 .map(|row| {
164 Ok(PublicKeyCredentialDescriptor {
165 type_: "public-key".into(),
166 id: ceremony::credential_id(row)?,
167 transports: ceremony::transports(row.transports.as_deref()),
168 })
169 })
170 .collect::<Result<Vec<_>, AuthError>>()?;
171 let account = if user.email.is_empty() {
172 user.id.to_string()
173 } else {
174 user.email.clone()
175 };
176 (account, exclude, Registrant::User(user.clone()))
177 }
178 None => {
179 let resolve = self.0.sign_up.as_ref().ok_or(AuthError::unauthorized())?;
180 let user = resolve(PasskeySignUp {
181 context: input.context,
182 name: input.name.clone(),
183 })
184 .await?;
185 let user = PasskeyUser {
186 email: normalize_email(&user.email)?,
187 ..user
188 };
189 (user.email.clone(), Vec::new(), Registrant::SignUp(user))
190 }
191 };
192 let rp = self.0.relying_party(ctx.config())?;
193 let user_name = input.name.as_deref().filter(|n| !n.is_empty());
194 let (mut options, state) = rp
195 .start_passkey_registration(
196 Uuid::new_v4(),
197 user_name.unwrap_or(&account),
198 &account,
199 Some(exclude.iter().map(|d| d.id.clone()).collect()),
200 )
201 .map_err(AuthError::internal)?;
202 let options = &mut options.public_key;
203 options.exclude_credentials = Some(exclude);
204 if let Some(selection) = &mut options.authenticator_selection {
205 selection.resident_key = Some(ResidentKeyRequirement::Preferred);
206 selection.require_resident_key = false;
207 selection.authenticator_attachment = input.authenticator_attachment;
208 }
209 let challenge = match pending {
210 Registrant::SignUp(user) => Challenge::SignUp { user, state },
211 Registrant::User(user) => Challenge::Registration {
212 user_id: user.id.to_string(),
213 state,
214 },
215 };
216 store_challenge(&ctx, &challenge).await?;
217 Ok(options.clone())
218 }
219}
220
221#[derive(Debug, Deserialize)]
223#[serde(rename_all = "camelCase")]
224pub struct VerifyRegistrationInput {
225 pub response: Json,
227 #[serde(default)]
229 pub name: Option<String>,
230 #[serde(default)]
232 pub create_session: Option<bool>,
233}
234
235#[derive(Debug, Serialize)]
238pub struct RegisterOutput {
239 #[serde(flatten)]
240 pub passkey: PasskeyView,
241 #[serde(skip_serializing_if = "Option::is_none")]
242 pub session: Option<Map<String, Json>>,
243 #[serde(skip_serializing_if = "Option::is_none")]
244 pub user: Option<Map<String, Json>>,
245 #[serde(flatten)]
246 pub challenge: Option<Map<String, Json>>,
247}
248
249pub struct VerifyRegistration(pub(crate) Arc<Passkey>);
254
255impl<D: Adapter> Endpoint<D> for VerifyRegistration {
256 const METHOD: Method = Method::POST;
257 const PATH: &'static str = "/passkey/verify-registration";
258 type Access = MaybeAuthenticated;
259 type Input = VerifyRegistrationInput;
260 type Output = RegisterOutput;
261
262 async fn call(
263 &self,
264 ctx: Ctx<D, MaybeAuthenticated>,
265 input: VerifyRegistrationInput,
266 ) -> Result<RegisterOutput, AuthError> {
267 let session = registering_session(&ctx).await?;
268 if session.is_none() && self.0.sign_up.is_none() {
269 return Err(AuthError::unauthorized());
270 }
271 let rp = self.0.relying_party(ctx.config())?;
272 let (registrant, state) = match (take_challenge(&ctx).await?, session) {
273 (Challenge::Registration { user_id, state }, Some(session)) => {
274 if Id::from(user_id) != session.user.id {
275 return Err(PasskeyError::NotAllowed.into());
276 }
277 (Registrant::User(session.user), state)
278 }
279 (Challenge::SignUp { user, state }, None) => (Registrant::SignUp(user), state),
280 (Challenge::Registration { .. }, None) => return Err(AuthError::unauthorized()),
281 (Challenge::SignUp { .. }, Some(_)) => return Err(PasskeyError::NotAllowed.into()),
282 (Challenge::Authentication { .. }, _) => {
283 return Err(PasskeyError::ChallengeNotFound.into());
284 }
285 };
286 let failed = PasskeyError::FailedToVerifyRegistration;
287 let transports = input.response["response"]["transports"]
288 .as_array()
289 .map(|t| {
290 t.iter()
291 .filter_map(Json::as_str)
292 .collect::<Vec<_>>()
293 .join(",")
294 })
295 .unwrap_or_default();
296 let response: RegisterPublicKeyCredential =
297 serde_json::from_value(input.response).map_err(|_| failed)?;
298 let passkey = rp
299 .finish_passkey_registration(&response, &state)
300 .map_err(|_| failed)?;
301 let attested = ceremony::attested(&response.response.attestation_object).ok_or(failed)?;
302 let credential = Credential::from(passkey);
303 let credential_id = base64url(&credential.cred_id);
304 if ctx
305 .db()
306 .find::<PasskeyRow>(PasskeyRow::CREDENTIAL_ID.eq(&credential_id))
307 .one()
308 .await?
309 .is_some()
310 {
311 return Err(failed.into());
312 }
313 let (user, new_user) = match registrant {
314 Registrant::User(user) => (user, false),
315 Registrant::SignUp(user) => {
316 let user = ctx
317 .internal()
318 .create_user(
319 NewUser {
320 email: user.email,
321 name: user.name,
322 email_verified: user.email_verified,
323 ..NewUser::default()
324 },
325 None,
326 )
327 .await?;
328 (user, true)
329 }
330 };
331 let user_id = user.id.clone();
332 let row = PasskeyRow {
333 id: ctx.new_id()?,
334 name: input
335 .name
336 .map(|n| n.trim().to_owned())
337 .filter(|n| !n.is_empty()),
338 public_key: attested.public_key,
339 user_id: user_id.clone(),
340 credential_id,
341 counter: i64::from(credential.counter),
342 device_type: if credential.backup_eligible {
343 MULTI_DEVICE
344 } else {
345 SINGLE_DEVICE
346 }
347 .into(),
348 backed_up: credential.backup_state,
349 transports: Some(transports),
350 created_at: ctx.now(),
351 aaguid: Some(attested.aaguid),
352 };
353 let stored = match ctx.internal().lock_user_unless_claimed(&user).await {
354 Ok(tx) => match ctx.db_on(&tx).insert(&row).await {
355 Ok(_) => tx.commit().await.map_err(AuthError::from),
356 Err(err) => Err(err.into()),
357 },
358 Err(err) => Err(err),
359 };
360 if let Err(err) = stored {
361 if new_user {
362 ctx.db().delete::<User>(User::ID.eq(&user_id)).await?;
363 }
364 return Err(err);
365 }
366 ctx.emit(PasskeyAdded {
367 user_id: user_id.clone(),
368 passkey_id: row.id.clone(),
369 });
370 let (session, challenge) = match (input.create_session == Some(true), new_user) {
371 (false, _) => (None, None),
372 (true, false) => (
373 Some(
374 ctx.internal()
375 .create_session_unless_claimed(&user, true)
376 .await?,
377 ),
378 None,
379 ),
380 (true, true) => match ctx.internal().sign_in(user, Passkey::ID, true).await? {
381 SignInResult::SignedIn(session) => (Some(*session), None),
382 SignInResult::Challenge(body) => (None, body.as_object().cloned()),
383 },
384 };
385 Ok(RegisterOutput {
386 passkey: row.into(),
387 user: session.as_ref().map(|s| s.user.to_json()),
388 session: session.map(|s| s.to_json()),
389 challenge,
390 })
391 }
392}
393
394pub struct GenerateAuthenticateOptions(pub(crate) Arc<Passkey>);
398
399impl<D: Adapter> Endpoint<D> for GenerateAuthenticateOptions {
400 const METHOD: Method = Method::GET;
401 const PATH: &'static str = "/passkey/generate-authenticate-options";
402 type Access = MaybeAuthenticated;
403 type Input = Empty;
404 type Output = PublicKeyCredentialRequestOptions;
405
406 async fn call(
407 &self,
408 ctx: Ctx<D, MaybeAuthenticated>,
409 _: Empty,
410 ) -> Result<PublicKeyCredentialRequestOptions, AuthError> {
411 let rp = self.0.relying_party(ctx.config())?;
412 let (options, state) = rp
413 .start_discoverable_authentication()
414 .map_err(AuthError::internal)?;
415 let mut options = options.public_key;
416 if let Some(session) = ctx.session() {
417 options.allow_credentials = user_passkeys(&ctx, &session.user.id)
418 .await?
419 .iter()
420 .map(|row| {
421 Ok(AllowCredentials {
422 type_: "public-key".into(),
423 id: ceremony::credential_id(row)?,
424 transports: ceremony::transports(row.transports.as_deref()),
425 })
426 })
427 .collect::<Result<_, AuthError>>()?;
428 }
429 store_challenge(&ctx, &Challenge::Authentication { state }).await?;
430 Ok(options)
431 }
432}
433
434#[derive(Debug, Deserialize)]
436pub struct VerifyAuthenticationInput {
437 pub response: Json,
439}
440
441#[derive(Debug, Serialize)]
443#[serde(untagged)]
444pub enum SignInOutput {
445 SignedIn {
447 session: Map<String, Json>,
448 user: Map<String, Json>,
449 },
450 Challenge(Json),
452}
453
454pub struct VerifyAuthentication(pub(crate) Arc<Passkey>);
459
460impl<D: Adapter> Endpoint<D> for VerifyAuthentication {
461 const METHOD: Method = Method::POST;
462 const PATH: &'static str = "/passkey/verify-authentication";
463 type Access = Public;
464 type Input = VerifyAuthenticationInput;
465 type Output = SignInOutput;
466
467 async fn call(
468 &self,
469 ctx: Ctx<D, Public>,
470 input: VerifyAuthenticationInput,
471 ) -> Result<SignInOutput, AuthError> {
472 let rp = self.0.relying_party(ctx.config())?;
473 let Challenge::Authentication { state } = take_challenge(&ctx).await? else {
474 return Err(PasskeyError::ChallengeNotFound.into());
475 };
476 let response: PublicKeyCredential =
477 serde_json::from_value(input.response).map_err(|_| PasskeyError::InvalidAssertion)?;
478 let row = ctx
479 .db()
480 .find::<PasskeyRow>(PasskeyRow::CREDENTIAL_ID.eq(base64url(&response.raw_id)))
481 .one()
482 .await?
483 .ok_or(PasskeyError::UnknownCredential)?;
484 let credential = ceremony::credential(&row)?;
485 let result = rp
486 .finish_discoverable_authentication_v2(&response, state, &credential)
487 .map_err(|err| match err {
488 WebauthnError::AuthenticationFailure => PasskeyError::AuthenticationFailed,
489 _ => PasskeyError::InvalidAssertion,
490 })?;
491 let user = ctx
494 .internal()
495 .find_user_by_id(&row.user_id)
496 .await?
497 .ok_or_else(|| AuthError::internal("a passkey's user is gone"))?;
498 let counter = i64::from(result.counter().max(credential.counter));
499 let advanced = ctx
500 .db()
501 .update::<PasskeyRow>(
502 PasskeyRow::ID
503 .eq(&row.id)
504 .and(PasskeyRow::COUNTER.eq(row.counter)),
505 )
506 .set(PasskeyRow::COUNTER, counter)
507 .set(PasskeyRow::BACKED_UP, result.backup_state())
508 .exec()
509 .await?;
510 if advanced == 0 {
511 return Err(PasskeyError::InvalidAssertion.into());
512 }
513 Ok(
514 match ctx.internal().sign_in(user, Passkey::ID, true).await? {
515 SignInResult::SignedIn(session) => SignInOutput::SignedIn {
516 session: session.to_json(),
517 user: session.user.to_json(),
518 },
519 SignInResult::Challenge(body) => SignInOutput::Challenge(body),
520 },
521 )
522 }
523}
524
525pub struct ListUserPasskeys;
527
528impl<D: Adapter> Endpoint<D> for ListUserPasskeys {
529 const METHOD: Method = Method::GET;
530 const PATH: &'static str = "/passkey/list-user-passkeys";
531 type Access = Authenticated;
532 type Input = Empty;
533 type Output = Vec<PasskeyView>;
534
535 async fn call(
536 &self,
537 ctx: Ctx<D, Authenticated>,
538 _: Empty,
539 ) -> Result<Vec<PasskeyView>, AuthError> {
540 let rows = user_passkeys(&ctx, &ctx.session().user.id).await?;
541 Ok(rows.into_iter().map(PasskeyView::from).collect())
542 }
543}
544
545async fn own_passkey<D: Adapter>(
548 ctx: &Ctx<D, Authenticated>,
549 id: &str,
550 not_yours: AuthError,
551) -> Result<PasskeyRow, AuthError> {
552 let row = ctx
553 .db()
554 .find::<PasskeyRow>(PasskeyRow::ID.eq(Id::from(id)))
555 .one()
556 .await?
557 .ok_or(PasskeyError::PasskeyNotFound)?;
558 if row.user_id != ctx.sensitive_session().await?.user.id {
559 return Err(not_yours);
560 }
561 Ok(row)
562}
563
564#[derive(Debug, Deserialize)]
566pub struct DeletePasskeyInput {
567 pub id: String,
568}
569
570pub struct DeletePasskey;
572
573impl<D: Adapter> Endpoint<D> for DeletePasskey {
574 const METHOD: Method = Method::POST;
575 const PATH: &'static str = "/passkey/delete-passkey";
576 type Access = Authenticated;
577 type Input = DeletePasskeyInput;
578 type Output = Status;
579
580 async fn call(
581 &self,
582 ctx: Ctx<D, Authenticated>,
583 input: DeletePasskeyInput,
584 ) -> Result<Status, AuthError> {
585 let not_yours = AuthError::new(
586 StatusCode::UNAUTHORIZED,
587 codes::UNAUTHORIZED,
588 "Unauthorized",
589 );
590 let row = own_passkey(&ctx, &input.id, not_yours).await?;
591 ctx.db()
592 .delete::<PasskeyRow>(PasskeyRow::ID.eq(&row.id))
593 .await?;
594 ctx.emit(PasskeyDeleted {
595 user_id: row.user_id,
596 passkey_id: row.id,
597 });
598 Ok(Status { status: true })
599 }
600}
601
602#[derive(Debug, Deserialize)]
604pub struct UpdatePasskeyInput {
605 pub id: String,
606 pub name: String,
608}
609
610#[derive(Debug, Serialize)]
611pub struct UpdatePasskeyOutput {
612 pub passkey: PasskeyView,
613}
614
615pub struct UpdatePasskey;
617
618impl<D: Adapter> Endpoint<D> for UpdatePasskey {
619 const METHOD: Method = Method::POST;
620 const PATH: &'static str = "/passkey/update-passkey";
621 type Access = Authenticated;
622 type Input = UpdatePasskeyInput;
623 type Output = UpdatePasskeyOutput;
624
625 async fn call(
626 &self,
627 ctx: Ctx<D, Authenticated>,
628 input: UpdatePasskeyInput,
629 ) -> Result<UpdatePasskeyOutput, AuthError> {
630 let name = input.name.trim();
631 if name.is_empty() {
632 return Err(AuthError::bad_request(
633 codes::INVALID_BODY,
634 "name must not be empty",
635 ));
636 }
637 let mut row = own_passkey(&ctx, &input.id, PasskeyError::NotAllowed.into()).await?;
638 ctx.db()
639 .update::<PasskeyRow>(PasskeyRow::ID.eq(&row.id))
640 .set(PasskeyRow::NAME, Some(name.to_owned()))
641 .exec()
642 .await?;
643 row.name = Some(name.to_owned());
644 Ok(UpdatePasskeyOutput {
645 passkey: row.into(),
646 })
647 }
648}