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