Functional Weave
Code in TypeScript

auth.totp@1.0.0

impl/rust/totp_code.rs

1,072 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, is_totp_whole, totp_int_arg, totp_secret_key, totp_settings_from_value,
    totp_text_arg,
};

pub fn check_totp_now(now: i64) {
    if !is_totp_whole(now) {
        panic!("now must be a whole number of seconds from 0 to 2^53 - 1");
    }
}

/// The RFC 6238 code for the time step now falls in: HOTP at
/// floor(now / period).
///
/// # Panics
/// Panics on a negative or too large now, bad settings or a bad secret.
pub fn totp_code(secret: &str, now: i64, settings: &TotpSettings) -> String {
    check_totp_now(now);
    check_totp_settings(settings);
    let key = totp_secret_key(secret);
    hotp_from_key(&key, now / settings.period, settings.digits, &settings.algorithm)
}

pub fn fune_vector(args: &[Value]) -> Value {
    Value::str(&totp_code(
        &totp_text_arg(&args[0], "base32 text must be a string"),
        totp_int_arg(&args[1], "now must be a whole number of seconds from 0 to 2^53 - 1"),
        &totp_settings_from_value(&args[2]),
    ))
}