Functional Weave
Code in Rust

auth.totp@1.0.0

impl/rust/verify_totp.rs

3,976 bytes · the Rust implementation · view raw

Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.

use super::funejson::Value;  ← the fune runtime: the JSON value the test vectors use; fune build keeps it only where a signature takes one
use super::auth_totp_hotp_code::{
    check_totp_settings, hotp_from_key, totp_int_arg, totp_secret_key, totp_settings_from_value, totp_text_arg,
};
use super::auth_totp_totp_code::check_totp_now;  ← totpCode, another function of this group · built into the same file, even by a slim install
use super::crypto_constant_time_equal::constant_time_equal;  ← from crypto.constant-time-equal ^1.0.0 · built alongside by fune

fn ascii(text: &str) -> Vec<i64> {
    text.bytes().map(|b| b as i64).collect()
}

/// Checks a typed code against the steps around now (centred on the user's
/// known drift), closest first, earlier first on a tie. Every step in the
/// window is compared in constant time. A step at or before last_used_step
/// is refused as replayed.
///
/// # Panics
/// Panics on a bad now, settings, window (0-10), drift (-1000 to 1000) or
/// secret.
pub fn verify_totp(
    secret: &str,
    code: &str,
    now: i64,
    settings: &TotpSettings,
    window: i64,
    drift: i64,
    last_used_step: Option<i64>,
) -> TotpCheck {
    check_totp_now(now);
    check_totp_settings(settings);
    if !(0..=10).contains(&window) {
        panic!("window must be a whole number from 0 to 10");
    }
    if !(-1000..=1000).contains(&drift) {
        panic!("drift must be a whole number from -1000 to 1000");
    }
    let key = totp_secret_key(secret);
    let typed: String = code.chars().filter(|c| *c != ' ').collect();
    if typed.len() as i64 != settings.digits || !typed.bytes().all(|b| b.is_ascii_digit()) {
        return TotpCheck { valid: false, step: None, drift: None, reason: Some("malformed_code".to_string()) };
    }
    let expected = now / settings.period;
    let centre = expected + drift;
    let typed_bytes = ascii(&typed);
    let mut accepted: Option<i64> = None;
    let mut replayed = false;
    for distance in 0..=window {
        let steps = if distance == 0 { vec![centre] } else { vec![centre - distance, centre + distance] };
        for step in steps {
            if step < 0 {
                continue;
            }
            let made = hotp_from_key(&key, step, settings.digits, &settings.algorithm);
            if !constant_time_equal(&ascii(&made), &typed_bytes) {
                continue;
            }
            match last_used_step {
                Some(last) if step <= last => replayed = true,
                _ => {
                    if accepted.is_none() {
                        accepted = Some(step);
                    }
                }
            }
        }
    }
    match accepted {
        Some(step) => TotpCheck { valid: true, step: Some(step), drift: Some(step - expected), reason: None },
        None => TotpCheck {
            valid: false,
            step: None,
            drift: None,
            reason: Some(if replayed { "replayed" } else { "wrong_code" }.to_string()),
        },
    }
}

pub fn totp_check_to_value(check: &TotpCheck) -> Value {
    let int_or_null = |v: Option<i64>| match v {
        Some(i) => Value::Int(i),
        None => Value::Null,
    };
    Value::obj(vec![
        ("valid", Value::Bool(check.valid)),
        ("step", int_or_null(check.step)),
        ("drift", int_or_null(check.drift)),
        (
            "reason",
            match &check.reason {
                Some(r) => Value::str(r),
                None => Value::Null,
            },
        ),
    ])
}

pub fn fune_vector(args: &[Value]) -> Value {
    let last_used_step = match &args[6] {
        Value::Null => None,
        Value::Int(i) => Some(*i),
        _ => panic!("lastUsedStep must be a whole number or null"),
    };
    totp_check_to_value(&verify_totp(
        &totp_text_arg(&args[0], "base32 text must be a string"),
        &totp_text_arg(&args[1], "code must be text"),
        totp_int_arg(&args[2], "now must be a whole number of seconds from 0 to 2^53 - 1"),
        &totp_settings_from_value(&args[3]),
        totp_int_arg(&args[4], "window must be a whole number from 0 to 10"),
        totp_int_arg(&args[5], "drift must be a whole number from -1000 to 1000"),
        last_used_step,
    ))
}