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(Id),
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.id.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_id) => 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 let user_id = Id::from(user_id);
275 if user_id != session.user.id {
276 return Err(PasskeyError::NotAllowed.into());
277 }
278 (Registrant::User(user_id), state)
279 }
280 (Challenge::SignUp { user, state }, None) => (Registrant::SignUp(user), state),
281 (Challenge::Registration { .. }, None) => return Err(AuthError::unauthorized()),
282 (Challenge::SignUp { .. }, Some(_)) => return Err(PasskeyError::NotAllowed.into()),
283 (Challenge::Authentication { .. }, _) => {
284 return Err(PasskeyError::ChallengeNotFound.into());
285 }
286 };
287 let failed = PasskeyError::FailedToVerifyRegistration;
288 let transports = input.response["response"]["transports"]
289 .as_array()
290 .map(|t| {
291 t.iter()
292 .filter_map(Json::as_str)
293 .collect::<Vec<_>>()
294 .join(",")
295 })
296 .unwrap_or_default();
297 let response: RegisterPublicKeyCredential =
298 serde_json::from_value(input.response).map_err(|_| failed)?;
299 let passkey = rp
300 .finish_passkey_registration(&response, &state)
301 .map_err(|_| failed)?;
302 let attested = ceremony::attested(&response.response.attestation_object).ok_or(failed)?;
303 let credential = Credential::from(passkey);
304 let credential_id = base64url(&credential.cred_id);
305 if ctx
306 .db()
307 .find::<PasskeyRow>(PasskeyRow::CREDENTIAL_ID.eq(&credential_id))
308 .one()
309 .await?
310 .is_some()
311 {
312 return Err(failed.into());
313 }
314 let (user_id, new_user) = match registrant {
315 Registrant::User(user_id) => (user_id, None),
316 Registrant::SignUp(user) => {
317 let user = ctx
318 .internal()
319 .create_user(
320 NewUser {
321 email: user.email,
322 name: user.name,
323 email_verified: user.email_verified,
324 ..NewUser::default()
325 },
326 None,
327 )
328 .await?;
329 (user.id.clone(), Some(user))
330 }
331 };
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 if let Err(err) = ctx.db().insert(&row).await {
354 if new_user.is_some() {
355 ctx.db().delete::<User>(User::ID.eq(&user_id)).await?;
356 }
357 return Err(err.into());
358 }
359 ctx.emit(PasskeyAdded {
360 user_id: user_id.clone(),
361 passkey_id: row.id.clone(),
362 });
363 let (session, challenge) = match (input.create_session == Some(true), new_user) {
364 (false, _) => (None, None),
365 (true, None) => (
366 Some(ctx.internal().create_session(&user_id, true).await?),
367 None,
368 ),
369 (true, Some(user)) => match ctx.internal().sign_in(user, Passkey::ID, true).await? {
370 SignInResult::SignedIn(session) => (Some(*session), None),
371 SignInResult::Challenge(body) => (None, body.as_object().cloned()),
372 },
373 };
374 Ok(RegisterOutput {
375 passkey: row.into(),
376 user: session.as_ref().map(|s| s.user.to_json()),
377 session: session.map(|s| s.to_json()),
378 challenge,
379 })
380 }
381}
382
383pub struct GenerateAuthenticateOptions(pub(crate) Arc<Passkey>);
387
388impl<D: Adapter> Endpoint<D> for GenerateAuthenticateOptions {
389 const METHOD: Method = Method::GET;
390 const PATH: &'static str = "/passkey/generate-authenticate-options";
391 type Access = MaybeAuthenticated;
392 type Input = Empty;
393 type Output = PublicKeyCredentialRequestOptions;
394
395 async fn call(
396 &self,
397 ctx: Ctx<D, MaybeAuthenticated>,
398 _: Empty,
399 ) -> Result<PublicKeyCredentialRequestOptions, AuthError> {
400 let rp = self.0.relying_party(ctx.config())?;
401 let (options, state) = rp
402 .start_discoverable_authentication()
403 .map_err(AuthError::internal)?;
404 let mut options = options.public_key;
405 if let Some(session) = ctx.session() {
406 options.allow_credentials = user_passkeys(&ctx, &session.user.id)
407 .await?
408 .iter()
409 .map(|row| {
410 Ok(AllowCredentials {
411 type_: "public-key".into(),
412 id: ceremony::credential_id(row)?,
413 transports: ceremony::transports(row.transports.as_deref()),
414 })
415 })
416 .collect::<Result<_, AuthError>>()?;
417 }
418 store_challenge(&ctx, &Challenge::Authentication { state }).await?;
419 Ok(options)
420 }
421}
422
423#[derive(Debug, Deserialize)]
425pub struct VerifyAuthenticationInput {
426 pub response: Json,
428}
429
430#[derive(Debug, Serialize)]
432#[serde(untagged)]
433pub enum SignInOutput {
434 SignedIn {
436 session: Map<String, Json>,
437 user: Map<String, Json>,
438 },
439 Challenge(Json),
441}
442
443pub struct VerifyAuthentication(pub(crate) Arc<Passkey>);
448
449impl<D: Adapter> Endpoint<D> for VerifyAuthentication {
450 const METHOD: Method = Method::POST;
451 const PATH: &'static str = "/passkey/verify-authentication";
452 type Access = Public;
453 type Input = VerifyAuthenticationInput;
454 type Output = SignInOutput;
455
456 async fn call(
457 &self,
458 ctx: Ctx<D, Public>,
459 input: VerifyAuthenticationInput,
460 ) -> Result<SignInOutput, AuthError> {
461 let rp = self.0.relying_party(ctx.config())?;
462 let Challenge::Authentication { state } = take_challenge(&ctx).await? else {
463 return Err(PasskeyError::ChallengeNotFound.into());
464 };
465 let response: PublicKeyCredential =
466 serde_json::from_value(input.response).map_err(|_| PasskeyError::InvalidAssertion)?;
467 let row = ctx
468 .db()
469 .find::<PasskeyRow>(PasskeyRow::CREDENTIAL_ID.eq(base64url(&response.raw_id)))
470 .one()
471 .await?
472 .ok_or(PasskeyError::UnknownCredential)?;
473 let credential = ceremony::credential(&row)?;
474 let result = rp
475 .finish_discoverable_authentication_v2(&response, state, &credential)
476 .map_err(|err| match err {
477 WebauthnError::AuthenticationFailure => PasskeyError::AuthenticationFailed,
478 _ => PasskeyError::InvalidAssertion,
479 })?;
480 let counter = i64::from(result.counter().max(credential.counter));
481 let advanced = ctx
482 .db()
483 .update::<PasskeyRow>(
484 PasskeyRow::ID
485 .eq(&row.id)
486 .and(PasskeyRow::COUNTER.eq(row.counter)),
487 )
488 .set(PasskeyRow::COUNTER, counter)
489 .set(PasskeyRow::BACKED_UP, result.backup_state())
490 .exec()
491 .await?;
492 if advanced == 0 {
493 return Err(PasskeyError::InvalidAssertion.into());
494 }
495 let user = ctx
496 .internal()
497 .find_user_by_id(&row.user_id)
498 .await?
499 .ok_or_else(|| AuthError::internal("a passkey's user is gone"))?;
500 Ok(
501 match ctx.internal().sign_in(user, Passkey::ID, true).await? {
502 SignInResult::SignedIn(session) => SignInOutput::SignedIn {
503 session: session.to_json(),
504 user: session.user.to_json(),
505 },
506 SignInResult::Challenge(body) => SignInOutput::Challenge(body),
507 },
508 )
509 }
510}
511
512pub struct ListUserPasskeys;
514
515impl<D: Adapter> Endpoint<D> for ListUserPasskeys {
516 const METHOD: Method = Method::GET;
517 const PATH: &'static str = "/passkey/list-user-passkeys";
518 type Access = Authenticated;
519 type Input = Empty;
520 type Output = Vec<PasskeyView>;
521
522 async fn call(
523 &self,
524 ctx: Ctx<D, Authenticated>,
525 _: Empty,
526 ) -> Result<Vec<PasskeyView>, AuthError> {
527 let rows = user_passkeys(&ctx, &ctx.session().user.id).await?;
528 Ok(rows.into_iter().map(PasskeyView::from).collect())
529 }
530}
531
532async fn own_passkey<D: Adapter>(
535 ctx: &Ctx<D, Authenticated>,
536 id: &str,
537 not_yours: AuthError,
538) -> Result<PasskeyRow, AuthError> {
539 let row = ctx
540 .db()
541 .find::<PasskeyRow>(PasskeyRow::ID.eq(Id::from(id)))
542 .one()
543 .await?
544 .ok_or(PasskeyError::PasskeyNotFound)?;
545 if row.user_id != ctx.session().user.id {
546 return Err(not_yours);
547 }
548 Ok(row)
549}
550
551#[derive(Debug, Deserialize)]
553pub struct DeletePasskeyInput {
554 pub id: String,
555}
556
557pub struct DeletePasskey;
559
560impl<D: Adapter> Endpoint<D> for DeletePasskey {
561 const METHOD: Method = Method::POST;
562 const PATH: &'static str = "/passkey/delete-passkey";
563 type Access = Authenticated;
564 type Input = DeletePasskeyInput;
565 type Output = Status;
566
567 async fn call(
568 &self,
569 ctx: Ctx<D, Authenticated>,
570 input: DeletePasskeyInput,
571 ) -> Result<Status, AuthError> {
572 let not_yours = AuthError::new(
573 StatusCode::UNAUTHORIZED,
574 codes::UNAUTHORIZED,
575 "Unauthorized",
576 );
577 let row = own_passkey(&ctx, &input.id, not_yours).await?;
578 ctx.db()
579 .delete::<PasskeyRow>(PasskeyRow::ID.eq(&row.id))
580 .await?;
581 ctx.emit(PasskeyDeleted {
582 user_id: row.user_id,
583 passkey_id: row.id,
584 });
585 Ok(Status { status: true })
586 }
587}
588
589#[derive(Debug, Deserialize)]
591pub struct UpdatePasskeyInput {
592 pub id: String,
593 pub name: String,
595}
596
597#[derive(Debug, Serialize)]
598pub struct UpdatePasskeyOutput {
599 pub passkey: PasskeyView,
600}
601
602pub struct UpdatePasskey;
604
605impl<D: Adapter> Endpoint<D> for UpdatePasskey {
606 const METHOD: Method = Method::POST;
607 const PATH: &'static str = "/passkey/update-passkey";
608 type Access = Authenticated;
609 type Input = UpdatePasskeyInput;
610 type Output = UpdatePasskeyOutput;
611
612 async fn call(
613 &self,
614 ctx: Ctx<D, Authenticated>,
615 input: UpdatePasskeyInput,
616 ) -> Result<UpdatePasskeyOutput, AuthError> {
617 let name = input.name.trim();
618 if name.is_empty() {
619 return Err(AuthError::bad_request(
620 codes::INVALID_BODY,
621 "name must not be empty",
622 ));
623 }
624 let mut row = own_passkey(&ctx, &input.id, PasskeyError::NotAllowed.into()).await?;
625 ctx.db()
626 .update::<PasskeyRow>(PasskeyRow::ID.eq(&row.id))
627 .set(PasskeyRow::NAME, Some(name.to_owned()))
628 .exec()
629 .await?;
630 row.name = Some(name.to_owned());
631 Ok(UpdatePasskeyOutput {
632 passkey: row.into(),
633 })
634 }
635}