use crate::error::BaseError;
use sha2::Sha256;
#[async_trait::async_trait]
pub trait TotpVerifier: Send + Sync + 'static {
async fn verify(&self, secret: &str, code: &str) -> Result<(), BaseError>;
}
#[derive(Debug, Clone)]
pub struct TotpLiteVerifier {
pub window_seconds: u64,
pub tolerance: u64,
}
impl Default for TotpLiteVerifier {
fn default() -> Self {
Self {
window_seconds: 30,
tolerance: 1,
}
}
}
impl TotpLiteVerifier {
fn now_seconds() -> Result<u64, BaseError> {
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_err(|_| BaseError::ConfigError("系统时间早于 Unix 纪元".to_string()))?;
Ok(now.as_secs())
}
pub fn generate(&self, secret: &str, timestamp_secs: u64) -> String {
let decoded = base32_decode(secret);
totp_lite::totp_custom::<Sha256>(self.window_seconds, 6, &decoded, timestamp_secs)
}
fn code_matches(&self, secret: &str, code: &str, timestamp_secs: u64) -> bool {
let decoded = base32_decode(secret);
let current =
totp_lite::totp_custom::<Sha256>(self.window_seconds, 6, &decoded, timestamp_secs);
if constant_time_eq(current.as_bytes(), code.as_bytes()) {
return true;
}
for offset in 1..=self.tolerance {
let past = totp_lite::totp_custom::<Sha256>(
self.window_seconds,
6,
&decoded,
timestamp_secs.saturating_sub(self.window_seconds * offset),
);
let future = totp_lite::totp_custom::<Sha256>(
self.window_seconds,
6,
&decoded,
timestamp_secs.saturating_add(self.window_seconds * offset),
);
if constant_time_eq(past.as_bytes(), code.as_bytes())
|| constant_time_eq(future.as_bytes(), code.as_bytes())
{
return true;
}
}
false
}
}
#[async_trait::async_trait]
impl TotpVerifier for TotpLiteVerifier {
async fn verify(&self, secret: &str, code: &str) -> Result<(), BaseError> {
let now = Self::now_seconds()?;
if self.code_matches(secret, code, now) {
Ok(())
} else {
Err(BaseError::Unauthorized("TOTP 校验失败".to_string()))
}
}
}
fn base32_decode(input: &str) -> Vec<u8> {
const ALPHABET: &[u8; 32] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
let mut bits: u64 = 0;
let mut bit_count: u32 = 0;
let mut out = Vec::with_capacity(input.len() * 5 / 8);
for byte in input.bytes() {
if byte == b' ' || byte == b'\n' || byte == b'\r' || byte == b'\t' {
continue;
}
let Some(value) = ALPHABET
.iter()
.position(|&a| a == byte.to_ascii_uppercase())
else {
if byte == b'=' {
break;
}
continue;
};
bits = (bits << 5) | value as u64;
bit_count += 5;
if bit_count >= 8 {
bit_count -= 8;
out.push((bits >> bit_count) as u8);
bits &= (1 << bit_count) - 1;
}
}
out
}
fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
if a.len() != b.len() {
return false;
}
let mut diff = 0u8;
for (x, y) in a.iter().zip(b.iter()) {
diff |= x ^ y;
}
diff == 0
}
#[cfg(test)]
mod __tests__ {
use super::*;
#[test]
fn base32_round_trip() {
let decoded = base32_decode("MZXW6YTBOI======");
assert_eq!(decoded, b"foobar");
let decoded = base32_decode("mzxw6ytboi");
assert_eq!(decoded, b"foobar");
}
#[test]
fn totp_verify_accepts_current_and_neighbor_windows() {
let verifier = TotpLiteVerifier::default();
let secret = "JBSWY3DPEHPK3PXP";
let now = 1_700_000_000u64;
let code = verifier.generate(secret, now);
assert!(verifier.code_matches(secret, &code, now));
let past_code = verifier.generate(secret, now - 30);
assert!(verifier.code_matches(secret, &past_code, now));
let future_code = verifier.generate(secret, now + 30);
assert!(verifier.code_matches(secret, &future_code, now));
}
#[test]
fn totp_verify_rejects_wrong_code() {
let verifier = TotpLiteVerifier::default();
let secret = "JBSWY3DPEHPK3PXP";
let now = 1_700_000_000u64;
let code = verifier.generate(secret, now);
let wrong = if code == "000000" { "000001" } else { "000000" };
assert!(!verifier.code_matches(secret, wrong, now));
}
#[tokio::test]
async fn async_verify_rejects_unknown_secret() {
let verifier = TotpLiteVerifier::default();
let result = verifier.verify("AAAA", "123456").await;
assert!(matches!(result, Err(BaseError::Unauthorized(_))));
}
}