Skip to main content

fastauth_plugin_two_factor/
endpoints.rs

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