1mod hotp;
21mod recovery;
22mod secret;
23
24#[cfg(doctest)]
25#[doc = include_str!("../README.md")]
26struct ReadmeDoctests;
27
28use std::fmt::Write as _;
29use std::time::{SystemTime, UNIX_EPOCH};
30
31use laravel::axum::extract::FromRequestParts;
32use laravel::axum::http::request::Parts;
33use laravel::config::cache::StoreConfig;
34use laravel::config::{Config, Env, Section};
35use laravel::container::Container;
36use laravel::context::Context;
37use laravel::foundation::ServiceProvider;
38use laravel::rate_limit::{self, Limit, Quota, TooManyAttempts};
39use qrcode::QrCode;
40use qrcode::render::svg;
41use subtle::{Choice, ConditionallySelectable, ConstantTimeEq};
42
43pub use crate::recovery::RecoveryCodes;
44pub use crate::secret::{MIN_SECRET_BYTES, MIN_STORED_SECRET_BYTES, Secret};
45
46#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
48pub enum Algorithm {
49 #[default]
51 Sha1,
52 Sha256,
54 Sha512,
56}
57
58impl std::str::FromStr for Algorithm {
59 type Err = Error;
60
61 fn from_str(name: &str) -> Result<Self, Error> {
63 match name.to_ascii_uppercase().as_str() {
64 "SHA1" => Ok(Self::Sha1),
65 "SHA256" => Ok(Self::Sha256),
66 "SHA512" => Ok(Self::Sha512),
67 _ => Err(Error::InvalidConfig("the algorithm must be SHA1, SHA256 or SHA512")),
68 }
69 }
70}
71
72impl Algorithm {
73 #[must_use]
75 pub fn as_str(self) -> &'static str {
76 match self {
77 Self::Sha1 => "SHA1",
78 Self::Sha256 => "SHA256",
79 Self::Sha512 => "SHA512",
80 }
81 }
82}
83
84#[derive(Clone, Debug, PartialEq, Eq, Section)]
99pub struct TwoFactorConfig {
100 #[env("TWO_FACTOR_ISSUER")]
102 pub issuer: Option<String>,
103 #[env("TWO_FACTOR_DIGITS", default = 6)]
105 pub digits: u32,
106 #[env("TWO_FACTOR_PERIOD", default = 30)]
108 pub period: u64,
109 #[env("TWO_FACTOR_WINDOW", default = 1)]
111 pub window: u64,
112 #[env("TWO_FACTOR_ALGORITHM", default = Algorithm::Sha1)]
114 pub algorithm: Algorithm,
115 #[env("TWO_FACTOR_SECRET_BYTES", default = 20)]
117 pub secret_bytes: usize,
118 #[env("TWO_FACTOR_CACHE_STORE")]
121 pub cache_store: Option<String>,
122}
123
124impl TwoFactorConfig {
125 pub fn validate(&self) -> Result<(), Error> {
133 if self.issuer.as_deref().is_some_and(|issuer| issuer.contains(':')) {
134 return Err(Error::InvalidConfig("the issuer can't contain a colon"));
135 }
136 if !(6..=8).contains(&self.digits) {
137 return Err(Error::InvalidConfig("digits must be 6, 7 or 8"));
138 }
139 if !(1..=MAX_PERIOD).contains(&self.period) {
140 return Err(Error::InvalidConfig("the period must be 1 to 86400 seconds"));
141 }
142 if self.window > 10 {
143 return Err(Error::InvalidConfig("the window must be 10 periods or fewer"));
144 }
145 if self.secret_bytes < MIN_SECRET_BYTES {
146 return Err(Error::SecretTooShort);
147 }
148
149 Ok(())
150 }
151}
152
153pub const MAX_PERIOD: u64 = 86_400;
155
156pub const ATTEMPTS_PER_MINUTE: u32 = 5;
158
159#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
161#[non_exhaustive]
162pub enum Error {
163 #[error("the two-factor secret is too short: a new one needs 16 bytes, an existing one 10 (16 base32 characters)")]
166 SecretTooShort,
167 #[error(
170 "a two-factor secret must be base32: the letters A to Z and digits 2 to 7, as many as whole bytes encode to"
171 )]
172 InvalidSecret,
173 #[error("the operating system couldn't provide random bytes")]
175 Random,
176 #[error("invalid two-factor config: {0}")]
178 InvalidConfig(&'static str),
179 #[error("the two-factor URL is too long for a QR code")]
181 QrCode,
182 #[error("the two-factor account name can't contain a colon")]
184 InvalidAccount,
185}
186
187#[derive(Clone, Debug, Default)]
192pub struct TwoFactor {
193 config: TwoFactorConfig,
194}
195
196impl TwoFactor {
197 pub fn new(config: TwoFactorConfig) -> Result<Self, Error> {
203 config.validate()?;
204
205 Ok(Self { config })
206 }
207
208 pub fn from_app() -> Result<Self, Error> {
214 let Some(config) = Context::current().map(|_| laravel::config()) else {
215 return Ok(Self::default());
216 };
217
218 Self::new(effective_config(&config))
219 }
220
221 #[must_use]
223 pub fn config(&self) -> &TwoFactorConfig {
224 &self.config
225 }
226
227 pub fn generate_secret(&self) -> Result<Secret, Error> {
233 Secret::generate(self.config.secret_bytes)
234 }
235
236 pub fn url(&self, secret: &Secret, account: &str) -> Result<String, Error> {
243 if account.contains(':') {
244 return Err(Error::InvalidAccount);
245 }
246
247 let label = match &self.config.issuer {
248 Some(issuer) => format!("{}:{}", encode(issuer), encode(account)),
249 None => encode(account),
250 };
251 let mut url = format!("otpauth://totp/{label}?secret={}", secret.to_base32());
252
253 if let Some(issuer) = &self.config.issuer {
254 let _ = write!(url, "&issuer={}", encode(issuer));
255 }
256
257 let _ = write!(
258 url,
259 "&algorithm={}&digits={}&period={}",
260 self.config.algorithm.as_str(),
261 self.config.digits,
262 self.config.period
263 );
264
265 Ok(url)
266 }
267
268 pub fn qr_code_svg(&self, secret: &Secret, account: &str) -> Result<String, Error> {
275 let code = QrCode::new(self.url(secret, account)?).map_err(|_| Error::QrCode)?;
276
277 Ok(code
278 .render::<svg::Color<'_>>()
279 .min_dimensions(192, 192)
280 .dark_color(svg::Color("#000000"))
281 .light_color(svg::Color("#ffffff"))
282 .build())
283 }
284
285 #[must_use]
287 pub fn code(&self, secret: &Secret) -> String {
288 self.code_at(secret, now())
289 }
290
291 #[must_use]
293 pub fn code_at(&self, secret: &Secret, time: u64) -> String {
294 hotp::code(secret, self.step(time), &self.config)
295 }
296
297 #[must_use]
300 pub fn verify(&self, secret: &Secret, code: &str) -> bool {
301 self.verify_at(secret, code, now()).is_some()
302 }
303
304 #[must_use]
307 pub fn verify_at(&self, secret: &Secret, code: &str, time: u64) -> Option<u64> {
308 let code: String = code.chars().filter(|c| !c.is_whitespace() && *c != '-').collect();
309 if code.len() != self.config.digits as usize || !code.bytes().all(|byte| byte.is_ascii_digit()) {
310 return None;
311 }
312
313 let current = self.step(time);
314 let first = current.saturating_sub(self.config.window);
315 let last = current.saturating_add(self.config.window);
316
317 let mut found = Choice::from(0);
319 let mut matched = 0;
320
321 for step in first..=last {
322 let equal = hotp::code(secret, step, &self.config).as_bytes().ct_eq(code.as_bytes());
323 matched.conditional_assign(&step, equal);
324 found |= equal;
325 }
326
327 bool::from(found).then_some(matched)
328 }
329
330 pub async fn attempt(&self, key: &str) -> laravel::Result<Result<Quota, TooManyAttempts>> {
342 let config = laravel::config();
343 check_store(&config, &config.cache.default)?;
344
345 rate_limit::attempt(
346 &format!("two-factor:{key}:attempts"),
347 Limit::per_minute(ATTEMPTS_PER_MINUTE),
348 )
349 .await
350 }
351
352 pub async fn verify_once(&self, secret: &Secret, code: &str, key: &str) -> laravel::Result<bool> {
367 let config = laravel::config();
368 let name = self.config.cache_store.as_deref().unwrap_or(&config.cache.default);
369 check_store(&config, name)?;
370 let cache = laravel::cache::store(name)?;
371
372 let time = now();
373 let Some(step) = self.verify_at(secret, code, time) else {
374 return Ok(false);
375 };
376 let first = self.step(time).saturating_sub(self.config.window);
377
378 let seconds = self.config.period * (2 * self.config.window + 1);
379 let ttl = laravel::time::ToSpan::seconds(i64::try_from(seconds).unwrap_or(i64::MAX));
380
381 for earlier in first..step {
384 cache
385 .add(&format!("two-factor:{key}:step:{earlier}"), true, ttl)
386 .await?;
387 }
388
389 if !cache.add(&format!("two-factor:{key}:step:{step}"), true, ttl).await? {
390 return Ok(false);
391 }
392
393 let current = self.step(now());
395
396 Ok(current.saturating_sub(self.config.window) <= step && step <= current.saturating_add(self.config.window))
397 }
398
399 fn step(&self, time: u64) -> u64 {
400 time / self.config.period
401 }
402}
403
404impl<S: Send + Sync> FromRequestParts<S> for TwoFactor {
406 type Rejection = laravel::Error;
407
408 async fn from_request_parts(_parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
409 Ok(Self::from_app()?)
410 }
411}
412
413#[derive(Clone, Copy, Debug, Default)]
428pub struct TwoFactorServiceProvider;
429
430impl ServiceProvider for TwoFactorServiceProvider {
431 fn config(&self, config: &mut Config, env: &Env) {
432 config.discover(env!("CARGO_CRATE_NAME"), env);
433 }
434
435 async fn boot(&self, app: &Container) -> laravel::Result<()> {
437 let config = app.config();
438 let two_factor = effective_config(config);
439 two_factor.validate()?;
440
441 check_store(config, &config.cache.default)?;
442
443 if let Some(name) = &two_factor.cache_store {
444 if !config.cache.stores.contains_key(name) {
445 return Err(laravel::Error::msg(format!(
446 "two-factor's cache store `{name}` isn't defined"
447 )));
448 }
449 check_store(config, name)?;
450 }
451
452 Ok(())
453 }
454}
455
456fn check_store(config: &Config, name: &str) -> laravel::Result<()> {
459 match config.cache.stores.get(name) {
460 Some(StoreConfig::Discard) => Err(laravel::Error::msg(format!(
461 "two-factor needs a cache store that keeps values, and `{name}` is a discard store"
462 ))),
463 Some(StoreConfig::Failover(_)) => Err(laravel::Error::msg(format!(
464 "two-factor needs one cache store it can trust, and `{name}` is a failover store; \
465 use one of its stores instead"
466 ))),
467 _ => Ok(()),
468 }
469}
470
471fn effective_config(config: &Config) -> TwoFactorConfig {
473 let mut two_factor = config.get::<TwoFactorConfig>().cloned().unwrap_or_default();
474
475 if two_factor.issuer.is_none() && !config.app.name.is_empty() {
476 two_factor.issuer = Some(config.app.name.clone());
477 }
478
479 two_factor
480}
481
482fn now() -> u64 {
484 match Context::current() {
485 Some(_) => u64::try_from(laravel::now().timestamp().as_second()).unwrap_or(0),
486 None => SystemTime::now()
487 .duration_since(UNIX_EPOCH)
488 .map_or(0, |since| since.as_secs()),
489 }
490}
491
492fn encode(text: &str) -> String {
494 let mut encoded = String::with_capacity(text.len());
495
496 for byte in text.bytes() {
497 if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~') {
498 encoded.push(char::from(byte));
499 } else {
500 let _ = write!(encoded, "%{byte:02X}");
501 }
502 }
503
504 encoded
505}