Skip to main content

fastauth_plugin_two_factor/
lib.rs

1//! Two-factor authentication for [fastauth](https://github.com/lassejlv/fastauth): TOTP
2//! authenticator apps, one-time codes by email, backup codes and trusted devices. The routes
3//! and JSON match Better Auth's two-factor plugin, so its `twoFactorClient` works unchanged.
4//!
5//! ```
6//! use fastauth_core::prelude::*;
7//! use fastauth_plugin_two_factor::{TwoFactor, TwoFactorExt};
8//!
9//! let auth: Auth<MemoryAdapter, (), plugins![TwoFactor]> = FastAuth::builder()
10//!     .secret(Secret::from_bytes(vec![1u8; 32]))
11//!     .base_url("http://localhost:3000")
12//!     .database(MemoryAdapter::new())
13//!     .email_password(EmailPassword::default())
14//!     .plugin(TwoFactor::new().issuer("Acme"))
15//!     .build()?;
16//! let _two_factor = auth.two_factor();
17//! # Ok::<(), BuildError>(())
18//! ```
19//!
20//! Without the plugin registered, `auth.two_factor()` doesn't compile:
21//!
22//! ```compile_fail
23//! use fastauth_core::prelude::*;
24//! use fastauth_plugin_two_factor::TwoFactorExt;
25//!
26//! let auth: Auth<MemoryAdapter> = FastAuth::builder()
27//!     .secret(Secret::from_bytes(vec![1u8; 32]))
28//!     .base_url("http://localhost:3000")
29//!     .database(MemoryAdapter::new())
30//!     .email_password(EmailPassword::default())
31//!     .build()
32//!     .unwrap();
33//! let _two_factor = auth.two_factor();
34//! ```
35//!
36//! Signing in as a user with two-factor on answers
37//! `{ "twoFactorRedirect": true, "twoFactorMethods": ["totp", "otp"] }` (`"otp"` only with a
38//! mailer) and sets a
39//! signed `{prefix}.two_factor` cookie naming the pending user. One of `verify-totp`,
40//! `verify-otp` (after `send-otp`) or `verify-backup-code` then finishes the sign-in: the
41//! other plugins' sign-in gates still run, so one that denies (a ban) or challenges answers
42//! instead of a session.
43
44mod endpoints;
45mod error;
46mod model;
47pub mod totp;
48
49use fastauth_core::plugin_prelude::*;
50use fastauth_core::{ApiResponse, routes::Status};
51use percent_encoding::{AsciiSet, NON_ALPHANUMERIC, utf8_percent_encode};
52
53pub use endpoints::{
54    BackupCodesOutput, Disable, Enable, EnableInput, EnableOutput, GenerateBackupCodes, GetTotpUri,
55    PasswordInput, SendOtp, TotpUriOutput, VerifyBackupCode, VerifyInput, VerifyOtp, VerifyOutput,
56    VerifyTotp,
57};
58pub use error::TwoFactorError;
59pub use model::{TwoFactorRow, TwoFactorUser};
60
61const URI_COMPONENT: &AsciiSet = &NON_ALPHANUMERIC
62    .remove(b'-')
63    .remove(b'.')
64    .remove(b'_')
65    .remove(b'~');
66
67/// The two-factor plugin: `.plugin(TwoFactor::new().issuer("Acme"))`.
68#[derive(Clone, Debug)]
69pub struct TwoFactor {
70    issuer: Option<String>,
71    digits: u32,
72    period: u32,
73    backup_codes: usize,
74    skip_verification_on_enable: bool,
75    trust_device_for: Duration,
76    two_factor_cookie_max_age: Duration,
77}
78
79impl Default for TwoFactor {
80    fn default() -> Self {
81        Self {
82            issuer: None,
83            digits: 6,
84            period: 30,
85            backup_codes: 10,
86            skip_verification_on_enable: false,
87            trust_device_for: Duration::days(30),
88            two_factor_cookie_max_age: Duration::minutes(10),
89        }
90    }
91}
92
93impl TwoFactor {
94    pub fn new() -> Self {
95        Self::default()
96    }
97
98    /// The name authenticator apps show next to the account. Default: the app name.
99    pub fn issuer(mut self, issuer: impl Into<String>) -> Self {
100        self.issuer = Some(issuer.into());
101        self
102    }
103
104    /// Digits per TOTP code, 6 (the default) to 8.
105    pub fn digits(mut self, digits: u32) -> Self {
106        assert!((6..=8).contains(&digits), "TOTP codes have 6 to 8 digits");
107        self.digits = digits;
108        self
109    }
110
111    /// Seconds per TOTP code (default 30). Codes one period early or late are accepted.
112    pub fn period(mut self, seconds: u32) -> Self {
113        assert!(seconds > 0, "a TOTP period is at least one second");
114        self.period = seconds;
115        self
116    }
117
118    /// How many backup codes enabling or regenerating hands out (default 10).
119    pub fn backup_codes(mut self, count: usize) -> Self {
120        self.backup_codes = count;
121        self
122    }
123
124    /// Turn two-factor on at `/two-factor/enable` instead of after the first verified code.
125    pub fn skip_verification_on_enable(mut self, skip: bool) -> Self {
126        self.skip_verification_on_enable = skip;
127        self
128    }
129
130    /// How long `trustDevice: true` skips the challenge on that device (default 30 days).
131    pub fn trust_device_for(mut self, duration: Duration) -> Self {
132        self.trust_device_for = duration;
133        self
134    }
135
136    /// How long a challenged sign-in may take to verify (default 10 minutes).
137    pub fn two_factor_cookie_max_age(mut self, max_age: Duration) -> Self {
138        self.two_factor_cookie_max_age = max_age;
139        self
140    }
141
142    fn totp_uri(
143        &self,
144        app_name: &str,
145        issuer: Option<&str>,
146        account: &str,
147        secret: &[u8],
148    ) -> String {
149        let issuer = issuer.or(self.issuer.as_deref()).unwrap_or(app_name);
150        let issuer = utf8_percent_encode(issuer, URI_COMPONENT);
151        format!(
152            "otpauth://totp/{issuer}:{}?secret={}&issuer={issuer}&digits={}&period={}",
153            utf8_percent_encode(account, URI_COMPONENT),
154            totp::base32(secret),
155            self.digits,
156            self.period
157        )
158    }
159}
160
161impl Plugin for TwoFactor {
162    const ID: &'static str = "two-factor";
163    type Requires = ();
164    type UserFields = TwoFactorUser;
165    type SessionFields = ();
166
167    fn schema(&self, schema: &mut SchemaBuilder) {
168        schema.model::<TwoFactorRow>();
169    }
170
171    fn init<D: Adapter>(self: &Arc<Self>, app: &mut PluginBuilder<'_, D>) {
172        app.endpoint(Enable(self.clone()))
173            .endpoint(Disable)
174            .endpoint(GetTotpUri(self.clone()))
175            .endpoint(VerifyTotp(self.clone()))
176            .endpoint(SendOtp)
177            .endpoint(VerifyOtp(self.clone()))
178            .endpoint(GenerateBackupCodes(self.clone()))
179            .endpoint(VerifyBackupCode(self.clone()))
180            .rate_limit("/two-factor/verify-*", Limit::per(Duration::minutes(1), 5))
181            .errors::<TwoFactorError>();
182        let plugin = self.clone();
183        app.sign_in_gate(move |ctx, attempt| {
184            let plugin = plugin.clone();
185            async move { endpoints::gate(&plugin, ctx, attempt).await }
186        });
187    }
188}
189
190/// Emitted when a user's two-factor turns on.
191#[derive(Clone, Debug, PartialEq, Eq)]
192pub struct TwoFactorEnabled {
193    pub user_id: Id,
194}
195
196/// Emitted when a user turns two-factor off.
197#[derive(Clone, Debug, PartialEq, Eq)]
198pub struct TwoFactorDisabled {
199    pub user_id: Id,
200}
201
202impl Event for TwoFactorEnabled {}
203impl Event for TwoFactorDisabled {}
204
205/// `auth.two_factor()`: the server API. Only compiles on an `Auth` with `TwoFactor` registered.
206pub trait TwoFactorExt: AuthInstance + Sized {
207    fn two_factor<I>(&self) -> TwoFactorApi<'_, Self>
208    where
209        Self: HasPlugin<TwoFactor, I>,
210    {
211        TwoFactorApi {
212            auth: self,
213            plugin: self.plugin_arc().clone(),
214        }
215    }
216}
217
218impl<A: AuthInstance> TwoFactorExt for A {}
219
220/// Calls the two-factor endpoints without HTTP. `headers` are the request's: their cookies
221/// carry the session, or the pending sign-in for `verify_totp`.
222pub struct TwoFactorApi<'a, A> {
223    auth: &'a A,
224    plugin: Arc<TwoFactor>,
225}
226
227impl<A: AuthInstance> TwoFactorApi<'_, A> {
228    /// `POST /two-factor/enable`.
229    pub async fn enable(
230        &self,
231        headers: &HeaderMap,
232        input: EnableInput,
233    ) -> Result<ApiResponse<EnableOutput>, AuthError> {
234        self.auth
235            .api()
236            .headers(headers)
237            .call(&Enable(self.plugin.clone()), input)
238            .await
239    }
240
241    /// `POST /two-factor/disable`.
242    pub async fn disable(
243        &self,
244        headers: &HeaderMap,
245        input: PasswordInput,
246    ) -> Result<ApiResponse<Status>, AuthError> {
247        self.auth.api().headers(headers).call(&Disable, input).await
248    }
249
250    /// `POST /two-factor/verify-totp`. The response's cookies carry a new session when this
251    /// finishes a sign-in.
252    pub async fn verify_totp(
253        &self,
254        headers: &HeaderMap,
255        input: VerifyInput,
256    ) -> Result<ApiResponse<VerifyOutput>, AuthError> {
257        self.auth
258            .api()
259            .headers(headers)
260            .call(&VerifyTotp(self.plugin.clone()), input)
261            .await
262    }
263}