1use fastauth_core::crypto::{Keys, base64url, ct_eq, random_bytes};
4use fastauth_core::mail::{AuthEmail, PluginEmail};
5use fastauth_core::plugin_prelude::*;
6use fastauth_core::routes::Status;
7use serde_json::{Map, json};
8
9use crate::model::{TwoFactorRow, TwoFactorUser};
10use crate::{TwoFactor, TwoFactorDisabled, TwoFactorEnabled, TwoFactorError, totp};
11
12const PENDING_COOKIE: &str = "two_factor";
13const TRUST_COOKIE: &str = "trust_device";
14const SESSION_CACHE_COOKIE: &str = "session_data";
15const OTP_TTL: Duration = Duration::minutes(15);
16const OTP_ATTEMPTS: u32 = 5;
17const BACKUP_CODE_ALPHABET: &[u8] =
18 b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
19
20#[derive(Debug, Deserialize)]
22pub struct PasswordInput {
23 pub password: String,
24}
25
26#[derive(Debug, Deserialize)]
28pub struct EnableInput {
29 pub password: String,
30 #[serde(default)]
32 pub issuer: Option<String>,
33}
34
35#[derive(Debug, Serialize)]
36#[serde(rename_all = "camelCase")]
37pub struct EnableOutput {
38 pub method: &'static str,
40 #[serde(rename = "totpURI")]
41 pub totp_uri: String,
42 pub backup_codes: Vec<String>,
44}
45
46#[derive(Debug, Serialize)]
47pub struct TotpUriOutput {
48 #[serde(rename = "totpURI")]
49 pub totp_uri: String,
50}
51
52#[derive(Debug, Deserialize)]
54#[serde(rename_all = "camelCase")]
55pub struct VerifyInput {
56 pub code: String,
57 pub trust_device: Option<bool>,
59}
60
61#[derive(Debug, Serialize)]
63#[serde(untagged)]
64pub enum VerifyOutput {
65 Verified {
67 token: String,
68 user: Map<String, serde_json::Value>,
69 },
70 Challenge(serde_json::Value),
73}
74
75#[derive(Debug, Serialize)]
76#[serde(rename_all = "camelCase")]
77pub struct BackupCodesOutput {
78 pub status: bool,
79 pub backup_codes: Vec<String>,
80}
81
82pub struct Enable(pub(crate) Arc<TwoFactor>);
86
87impl<D: Adapter> Endpoint<D> for Enable {
88 const METHOD: Method = Method::POST;
89 const PATH: &'static str = "/two-factor/enable";
90 type Access = Authenticated;
91 type Input = EnableInput;
92 type Output = EnableOutput;
93
94 async fn call(
95 &self,
96 ctx: Ctx<D, Authenticated>,
97 input: EnableInput,
98 ) -> Result<EnableOutput, AuthError> {
99 let user = &ctx.session().user;
100 check_password(&ctx, &user.id, &input.password).await?;
101 let secret = random_bytes::<20>();
102 let backup_codes = new_backup_codes(self.0.backup_codes);
103 ctx.db()
104 .delete::<TwoFactorRow>(TwoFactorRow::USER_ID.eq(&user.id))
105 .await?;
106 ctx.db()
107 .insert(&TwoFactorRow {
108 id: ctx.new_id()?,
109 user_id: user.id.clone(),
110 secret: ctx.keys().encrypt(&secret),
111 backup_codes: seal_codes(ctx.keys(), &backup_codes),
112 last_used_step: None,
113 })
114 .await?;
115 if self.0.skip_verification_on_enable {
116 set_enabled(&ctx, &user.id, true).await?;
117 }
118 let totp_uri = self.0.totp_uri(
119 &ctx.config().app_name,
120 input.issuer.as_deref(),
121 &user.email,
122 &secret,
123 );
124 Ok(EnableOutput {
125 method: "totp",
126 totp_uri,
127 backup_codes,
128 })
129 }
130}
131
132pub struct Disable;
134
135impl<D: Adapter> Endpoint<D> for Disable {
136 const METHOD: Method = Method::POST;
137 const PATH: &'static str = "/two-factor/disable";
138 type Access = Authenticated;
139 type Input = PasswordInput;
140 type Output = Status;
141
142 async fn call(
143 &self,
144 ctx: Ctx<D, Authenticated>,
145 input: PasswordInput,
146 ) -> Result<Status, AuthError> {
147 let user_id = &ctx.session().user.id;
148 check_password(&ctx, user_id, &input.password).await?;
149 ctx.db()
150 .delete::<TwoFactorRow>(TwoFactorRow::USER_ID.eq(user_id))
151 .await?;
152 set_enabled(&ctx, user_id, false).await?;
153 Ok(Status { status: true })
154 }
155}
156
157pub struct GetTotpUri(pub(crate) Arc<TwoFactor>);
159
160impl<D: Adapter> Endpoint<D> for GetTotpUri {
161 const METHOD: Method = Method::POST;
162 const PATH: &'static str = "/two-factor/get-totp-uri";
163 type Access = Authenticated;
164 type Input = PasswordInput;
165 type Output = TotpUriOutput;
166
167 async fn call(
168 &self,
169 ctx: Ctx<D, Authenticated>,
170 input: PasswordInput,
171 ) -> Result<TotpUriOutput, AuthError> {
172 let user = &ctx.session().user;
173 check_password(&ctx, &user.id, &input.password).await?;
174 let row = find_row(&ctx, &user.id)
175 .await?
176 .ok_or(TwoFactorError::TotpNotEnabled)?;
177 let secret = open_secret(ctx.keys(), &row)?;
178 Ok(TotpUriOutput {
179 totp_uri: self
180 .0
181 .totp_uri(&ctx.config().app_name, None, &user.email, &secret),
182 })
183 }
184}
185
186pub struct VerifyTotp(pub(crate) Arc<TwoFactor>);
189
190impl<D: Adapter> Endpoint<D> for VerifyTotp {
191 const METHOD: Method = Method::POST;
192 const PATH: &'static str = "/two-factor/verify-totp";
193 type Access = MaybeAuthenticated;
194 type Input = VerifyInput;
195 type Output = VerifyOutput;
196
197 async fn call(
198 &self,
199 ctx: Ctx<D, MaybeAuthenticated>,
200 input: VerifyInput,
201 ) -> Result<VerifyOutput, AuthError> {
202 let plugin = &self.0;
203 let mut subject = subject(&ctx).await?;
204 let user_id = subject.user().id.clone();
205 let row = find_row(&ctx, &user_id)
206 .await?
207 .ok_or(TwoFactorError::TotpNotEnabled)?;
208 let secret = open_secret(ctx.keys(), &row)?;
209 let now_step = ctx.now().unix_timestamp().max(0) as u64 / u64::from(plugin.period);
210 let step = totp::matching_step(&secret, input.code.trim(), now_step, plugin.digits)
211 .ok_or(TwoFactorError::InvalidCode)? as i64;
212 let unused = TwoFactorRow::LAST_USED_STEP
213 .is_null()
214 .or(TwoFactorRow::LAST_USED_STEP.lt(step));
215 let claimed = ctx
216 .db()
217 .update::<TwoFactorRow>(TwoFactorRow::ID.eq(&row.id).and(unused))
218 .set(TwoFactorRow::LAST_USED_STEP, step)
219 .exec()
220 .await?;
221 if claimed == 0 {
222 return Err(TwoFactorError::InvalidCode.into());
223 }
224 if let Subject::Session(session) = &mut subject
225 && !is_enabled(&session.user)?
226 {
227 set_enabled(&ctx, &user_id, true).await?;
228 session.user = ctx
229 .internal()
230 .find_user_by_id(&user_id)
231 .await?
232 .ok_or_else(|| AuthError::internal("user deleted while enabling two-factor"))?;
233 }
234 finish(plugin, &ctx, subject, input.trust_device).await
235 }
236}
237
238pub struct SendOtp;
240
241impl<D: Adapter> Endpoint<D> for SendOtp {
242 const METHOD: Method = Method::POST;
243 const PATH: &'static str = "/two-factor/send-otp";
244 type Access = MaybeAuthenticated;
245 type Input = Empty;
246 type Output = Status;
247
248 async fn call(&self, ctx: Ctx<D, MaybeAuthenticated>, _: Empty) -> Result<Status, AuthError> {
249 let subject = subject(&ctx).await?;
250 let user = subject.user();
251 let code = random_string(6, b"0123456789");
252 let internal = ctx.internal();
253 internal
254 .store_verification_value(&otp_identifier(&user.id), &code, OTP_TTL, None)
255 .await?;
256 let app_name = &ctx.config().app_name;
257 internal
258 .send_email(AuthEmail::Plugin(PluginEmail {
259 kind: "two-factor-otp",
260 to: user.email.clone(),
261 subject: format!("Your {app_name} verification code"),
262 text: format!(
263 "Your verification code is {code}. It expires in {} minutes.",
264 OTP_TTL.whole_minutes()
265 ),
266 url: None,
267 code: Some(code),
268 }))
269 .await?;
270 Ok(Status { status: true })
271 }
272}
273
274pub struct VerifyOtp(pub(crate) Arc<TwoFactor>);
276
277impl<D: Adapter> Endpoint<D> for VerifyOtp {
278 const METHOD: Method = Method::POST;
279 const PATH: &'static str = "/two-factor/verify-otp";
280 type Access = MaybeAuthenticated;
281 type Input = VerifyInput;
282 type Output = VerifyOutput;
283
284 async fn call(
285 &self,
286 ctx: Ctx<D, MaybeAuthenticated>,
287 input: VerifyInput,
288 ) -> Result<VerifyOutput, AuthError> {
289 let subject = subject(&ctx).await?;
290 let identifier = otp_identifier(&subject.user().id);
291 let Some(stored) = ctx
292 .db()
293 .find::<Verification>(Verification::IDENTIFIER.eq(&identifier))
294 .one()
295 .await?
296 else {
297 return Err(TwoFactorError::InvalidCode.into());
298 };
299 let burn = Verification::ID.eq(&stored.id);
300 if stored.expires_at <= ctx.now() {
301 ctx.db().delete::<Verification>(burn).await?;
302 return Err(TwoFactorError::OtpHasExpired.into());
303 }
304 if ctx
305 .internal()
306 .consume_verification_value(&identifier, input.code.trim())
307 .await?
308 .is_some()
309 {
310 return finish(&self.0, &ctx, subject, input.trust_device).await;
311 }
312 let attempts = stored
313 .data
314 .as_deref()
315 .and_then(|d| d.parse::<u32>().ok())
316 .unwrap_or(0)
317 + 1;
318 if attempts >= OTP_ATTEMPTS {
319 ctx.db().delete::<Verification>(burn).await?;
320 return Err(TwoFactorError::TooManyAttempts.into());
321 }
322 ctx.db()
323 .update::<Verification>(burn)
324 .set_raw("data", Value::Text(attempts.to_string()))
325 .exec()
326 .await?;
327 Err(TwoFactorError::InvalidCode.into())
328 }
329}
330
331pub struct GenerateBackupCodes(pub(crate) Arc<TwoFactor>);
333
334impl<D: Adapter> Endpoint<D> for GenerateBackupCodes {
335 const METHOD: Method = Method::POST;
336 const PATH: &'static str = "/two-factor/generate-backup-codes";
337 type Access = Authenticated;
338 type Input = PasswordInput;
339 type Output = BackupCodesOutput;
340
341 async fn call(
342 &self,
343 ctx: Ctx<D, Authenticated>,
344 input: PasswordInput,
345 ) -> Result<BackupCodesOutput, AuthError> {
346 let user = &ctx.session().user;
347 check_password(&ctx, &user.id, &input.password).await?;
348 let enabled = is_enabled(user)?;
349 let row = find_row(&ctx, &user.id)
350 .await?
351 .filter(|_| enabled)
352 .ok_or(TwoFactorError::TwoFactorNotEnabled)?;
353 let backup_codes = new_backup_codes(self.0.backup_codes);
354 ctx.db()
355 .update::<TwoFactorRow>(TwoFactorRow::ID.eq(&row.id))
356 .set(
357 TwoFactorRow::BACKUP_CODES,
358 seal_codes(ctx.keys(), &backup_codes),
359 )
360 .exec()
361 .await?;
362 Ok(BackupCodesOutput {
363 status: true,
364 backup_codes,
365 })
366 }
367}
368
369pub struct VerifyBackupCode(pub(crate) Arc<TwoFactor>);
371
372impl<D: Adapter> Endpoint<D> for VerifyBackupCode {
373 const METHOD: Method = Method::POST;
374 const PATH: &'static str = "/two-factor/verify-backup-code";
375 type Access = MaybeAuthenticated;
376 type Input = VerifyInput;
377 type Output = VerifyOutput;
378
379 async fn call(
380 &self,
381 ctx: Ctx<D, MaybeAuthenticated>,
382 input: VerifyInput,
383 ) -> Result<VerifyOutput, AuthError> {
384 let subject = subject(&ctx).await?;
385 let row = find_row(&ctx, &subject.user().id)
386 .await?
387 .ok_or(TwoFactorError::TwoFactorNotEnabled)?;
388 let mut hashes = open_hashes(ctx.keys(), &row)?;
389 let given = hash_code(input.code.trim());
390 let Some(index) = hashes
391 .iter()
392 .position(|h| ct_eq(h.as_bytes(), given.as_bytes()))
393 else {
394 return Err(TwoFactorError::InvalidBackupCode.into());
395 };
396 hashes.remove(index);
397 let sealed = seal_hashes(ctx.keys(), &hashes);
398 let claimed = ctx
399 .db()
400 .update::<TwoFactorRow>(
401 TwoFactorRow::ID
402 .eq(&row.id)
403 .and(TwoFactorRow::BACKUP_CODES.eq(row.backup_codes.clone())),
404 )
405 .set(TwoFactorRow::BACKUP_CODES, sealed)
406 .exec()
407 .await?;
408 if claimed == 0 {
409 return Err(TwoFactorError::InvalidBackupCode.into());
410 }
411 finish(&self.0, &ctx, subject, input.trust_device).await
412 }
413}
414
415pub(crate) async fn gate<D: Adapter>(
417 plugin: &TwoFactor,
418 ctx: HookCtx<D>,
419 attempt: SignInAttempt,
420) -> Result<Gate, AuthError> {
421 if !is_enabled(&attempt.user)? || is_trusted(&ctx, &attempt.user.id).await? {
422 return Ok(Gate::Allow);
423 }
424 let remember_me = if attempt.remember_me { "1" } else { "0" };
425 write_payload(
426 &ctx,
427 PENDING_COOKIE,
428 "pending",
429 [attempt.user.id.as_str(), remember_me, &attempt.method],
430 plugin.two_factor_cookie_max_age,
431 );
432 let methods: &[&str] = if ctx.internal().can_send_email() {
433 &["totp", "otp"]
434 } else {
435 &["totp"]
436 };
437 Ok(Gate::Challenge(json!({
438 "twoFactorRedirect": true,
439 "twoFactorMethods": methods,
440 })))
441}
442
443enum Subject {
445 Pending {
448 user: UserView,
449 remember_me: bool,
450 method: String,
451 },
452 Session(Box<SessionView>),
454}
455
456impl Subject {
457 fn user(&self) -> &UserView {
458 match self {
459 Subject::Pending { user, .. } => user,
460 Subject::Session(session) => &session.user,
461 }
462 }
463}
464
465async fn subject<D: Adapter>(ctx: &Ctx<D, MaybeAuthenticated>) -> Result<Subject, AuthError> {
467 if let Some([user_id, remember_me, method]) = read_payload(ctx, PENDING_COOKIE, "pending")
468 && let Some(user) = ctx.internal().find_user_by_id(&Id::from(user_id)).await?
469 {
470 return Ok(Subject::Pending {
471 user,
472 remember_me: remember_me == "1",
473 method,
474 });
475 }
476 ctx.session()
477 .map(|s| Subject::Session(Box::new(s.clone())))
478 .ok_or_else(|| TwoFactorError::InvalidTwoFactorCookie.into())
479}
480
481async fn finish<D: Adapter>(
484 plugin: &TwoFactor,
485 ctx: &Ctx<D, MaybeAuthenticated>,
486 subject: Subject,
487 trust_device: Option<bool>,
488) -> Result<VerifyOutput, AuthError> {
489 let session = match subject {
490 Subject::Pending {
491 user,
492 remember_me,
493 method,
494 } => {
495 ctx.delete_cookie(PENDING_COOKIE);
496 match ctx
497 .internal()
498 .complete_sign_in(TwoFactor::ID, user, method, remember_me)
499 .await?
500 {
501 SignInResult::SignedIn(session) => *session,
502 SignInResult::Challenge(body) => return Ok(VerifyOutput::Challenge(body)),
503 }
504 }
505 Subject::Session(session) => *session,
506 };
507 if trust_device == Some(true)
508 && let Some(row) = find_row(ctx, &session.user.id).await?
509 {
510 write_payload(
511 ctx,
512 TRUST_COOKIE,
513 "trust",
514 [session.user.id.as_str(), row.id.as_str()],
515 plugin.trust_device_for,
516 );
517 }
518 let user = session.user.to_json();
519 Ok(VerifyOutput::Verified {
520 token: session.token.unwrap_or_default(),
521 user,
522 })
523}
524
525async fn is_trusted<D: Adapter, A>(ctx: &Ctx<D, A>, user_id: &Id) -> Result<bool, AuthError> {
528 let Some([trusted_user, row_id]) = read_payload(ctx, TRUST_COOKIE, "trust") else {
529 return Ok(false);
530 };
531 if trusted_user != user_id.as_str() {
532 return Ok(false);
533 }
534 Ok(find_row(ctx, user_id)
535 .await?
536 .is_some_and(|row| row.id.as_str() == row_id))
537}
538
539fn write_payload<D: Adapter, A, const N: usize>(
541 ctx: &Ctx<D, A>,
542 cookie: &str,
543 kind: &str,
544 fields: [&str; N],
545 max_age: Duration,
546) {
547 let expires = (ctx.now() + max_age).unix_timestamp();
548 let value = format!("{kind}|{}|{expires}", fields.join("|"));
549 ctx.set_signed_cookie(cookie, &value, Some(max_age));
550}
551
552fn read_payload<D: Adapter, A, const N: usize>(
555 ctx: &Ctx<D, A>,
556 cookie: &str,
557 kind: &str,
558) -> Option<[String; N]> {
559 let value = ctx.signed_cookie(cookie)?;
560 let parts: Vec<&str> = value.split('|').collect();
561 let [found, fields @ .., expires] = &parts[..] else {
562 return None;
563 };
564 let expires: i64 = expires.parse().ok()?;
565 if *found != kind || expires <= ctx.now().unix_timestamp() {
566 return None;
567 }
568 fields
569 .iter()
570 .map(|field| (*field).to_owned())
571 .collect::<Vec<_>>()
572 .try_into()
573 .ok()
574}
575
576async fn check_password<D: Adapter, A>(
577 ctx: &Ctx<D, A>,
578 user_id: &Id,
579 password: &str,
580) -> Result<(), AuthError> {
581 let Some(hash) = ctx
582 .internal()
583 .credential_account(user_id)
584 .await?
585 .and_then(|a| a.password_hash)
586 else {
587 return Err(AuthError::bad_request(
588 codes::CREDENTIAL_ACCOUNT_NOT_FOUND,
589 "this user has no password",
590 ));
591 };
592 if !ctx
593 .passwords()
594 .verify(password, &hash)
595 .await
596 .map_err(AuthError::internal)?
597 {
598 return Err(AuthError::bad_request(
599 codes::INVALID_PASSWORD,
600 "invalid password",
601 ));
602 }
603 Ok(())
604}
605
606fn is_enabled(user: &UserView) -> Result<bool, AuthError> {
607 Ok(user
608 .fields::<TwoFactorUser>()
609 .map_err(AuthError::internal)?
610 .two_factor_enabled)
611}
612
613async fn set_enabled<D: Adapter, A>(
615 ctx: &Ctx<D, A>,
616 user_id: &Id,
617 enabled: bool,
618) -> Result<(), AuthError> {
619 ctx.db()
620 .update::<User>(User::ID.eq(user_id))
621 .set(TwoFactorUser::TWO_FACTOR_ENABLED, enabled)
622 .exec()
623 .await?;
624 ctx.delete_cookie(SESSION_CACHE_COOKIE);
625 let user_id = user_id.clone();
626 if enabled {
627 ctx.emit(TwoFactorEnabled { user_id });
628 } else {
629 ctx.emit(TwoFactorDisabled { user_id });
630 }
631 Ok(())
632}
633
634async fn find_row<D: Adapter, A>(
635 ctx: &Ctx<D, A>,
636 user_id: &Id,
637) -> Result<Option<TwoFactorRow>, AuthError> {
638 Ok(ctx
639 .db()
640 .find::<TwoFactorRow>(TwoFactorRow::USER_ID.eq(user_id))
641 .one()
642 .await?)
643}
644
645fn open_secret(keys: &Keys, row: &TwoFactorRow) -> Result<Vec<u8>, AuthError> {
646 keys.decrypt(&row.secret)
647 .ok_or_else(|| AuthError::internal("two-factor secret does not decrypt"))
648}
649
650fn otp_identifier(user_id: &Id) -> String {
651 format!("two-factor-otp:{user_id}")
652}
653
654fn new_backup_codes(count: usize) -> Vec<String> {
656 (0..count)
657 .map(|_| {
658 let code = random_string(10, BACKUP_CODE_ALPHABET);
659 format!("{}-{}", &code[..5], &code[5..])
660 })
661 .collect()
662}
663
664fn hash_code(code: &str) -> String {
665 base64url(Hash::sha256(code).as_bytes())
666}
667
668fn seal_codes(keys: &Keys, codes: &[String]) -> Vec<u8> {
670 let hashes: Vec<String> = codes.iter().map(|c| hash_code(c)).collect();
671 seal_hashes(keys, &hashes)
672}
673
674fn seal_hashes(keys: &Keys, hashes: &[String]) -> Vec<u8> {
675 keys.encrypt(&serde_json::to_vec(hashes).expect("a list of strings serializes"))
676}
677
678fn open_hashes(keys: &Keys, row: &TwoFactorRow) -> Result<Vec<String>, AuthError> {
679 keys.decrypt(&row.backup_codes)
680 .and_then(|json| serde_json::from_slice(&json).ok())
681 .ok_or_else(|| AuthError::internal("two-factor backup codes do not decrypt"))
682}