Functional Weave
Code in TypeScript

auth.totp@1.0.0

impl/rust/totp_uri.rs

1,989 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, totp_secret_key, totp_settings_from_value, totp_text_arg};  ← hotpCode, another function of this group · built into the same file, even by a slim install
use super::encoding_base32_base32_encode::base32_encode;

/// RFC 3986 percent-encoding: everything but the unreserved characters, as
/// UTF-8 bytes.
fn percent_encode(text: &str) -> String {
    let mut out = String::with_capacity(text.len());
    for &b in text.as_bytes() {
        if b.is_ascii_alphanumeric() || b == b'-' || b == b'.' || b == b'_' || b == b'~' {
            out.push(b as char);
        } else {
            out.push_str(&format!("%{:02X}", b));
        }
    }
    out
}

fn check_label_part(value: &str, name: &str) {
    if value.is_empty() {
        panic!("{} must not be empty", name);
    }
    if value.contains(':') {
        panic!("{} must not contain a colon", name);
    }
}

/// The Key Uri Format authenticator apps scan from a QR code. The secret is
/// written back in canonical form (upper case, unpadded).
///
/// # Panics
/// Panics on an empty issuer or account, a colon in either, bad settings or
/// a bad secret.
pub fn totp_uri(issuer: &str, account: &str, secret: &str, settings: &TotpSettings) -> String {
    check_label_part(issuer, "issuer");
    check_label_part(account, "account");
    check_totp_settings(settings);
    let canonical = base32_encode(&totp_secret_key(secret), false);
    format!(
        "otpauth://totp/{}:{}?secret={}&issuer={}&algorithm={}&digits={}&period={}",
        percent_encode(issuer),
        percent_encode(account),
        canonical,
        percent_encode(issuer),
        settings.algorithm,
        settings.digits,
        settings.period
    )
}

pub fn fune_vector(args: &[Value]) -> Value {
    Value::str(&totp_uri(
        &totp_text_arg(&args[0], "issuer must be text"),
        &totp_text_arg(&args[1], "account must be text"),
        &totp_text_arg(&args[2], "base32 text must be a string"),
        &totp_settings_from_value(&args[3]),
    ))
}