Functional Weave
Code in Rust

auth.totp

Authenticator-app two-factor codes (TOTP RFC 6238, HOTP RFC 4226): secret, QR URI, codes, verify with window and drift.

1.0.0 · published 2026-10-10 by charlie · Anterra

Pinned by 80 tests, run in TypeScript, Python and Rust.totpSecret 8 · totpUri 11 · hotpCode 20 · totpCode 19 · verifyTotp 22

What it does

Two-factor sign-in with an authenticator app (Google Authenticator, Microsoft Authenticator, 1Password, Authy): TOTP from RFC 6238, which is HOTP from RFC 4226 counted in time steps. Everything is pure: the random bytes and the time come from the caller.

## Setting it up for a user

The functions

A group: 5 functions that work together, each in its own file, each pinned by its own tests in TypeScript, Python and Rust. A project can install only the ones it calls.

  1. totp_secret (randomBytes: int[]) -> string
  2. totp_uri (issuer: string, account: string, secret: string, settings: TotpSettings) -> string
  3. hotp_code (secret: string, counter: int, digits: int, algorithm: TotpAlgorithm) -> string
  4. totp_code (secret: string, now: int, settings: TotpSettings) -> string
  5. verify_totp (secret: string, code: string, now: int, settings: TotpSettings, window: int, drift: int, lastUsedStep: int?) -> TotpCheck

The types it declares, generated into your project

// TotpAlgorithm is a string in Rust, one of: "SHA1", "SHA256".
// Parameters take it as &str and results hold it as String.

/// How codes are made. Authenticator apps expect SHA1, 6 digits, 30 seconds.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TotpSettings {
    pub algorithm: String,
    /// 6, 7 or 8
    pub digits: i64,
    /// seconds per step, 1 or more; 30 is the default everywhere
    pub period: i64,
}

// TotpReason is a string in Rust, one of: "wrong_code", "malformed_code", "replayed".
// Parameters take it as &str and results hold it as String.

/// Whether a code was accepted, and what to store if it was.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TotpCheck {
    pub valid: bool,
    /// the time step that matched; store it as lastUsedStep
    pub step: Option<i64>,
    /// matched step minus expected step; store it to centre the next window
    pub drift: Option<i64>,
    /// why not, when not valid
    pub reason: Option<String>,
}

Once installed, your code imports each one from the group's module.

totp_secret throws on bad input 8 tests

pub fn totp_secret(random_bytes: &[i64]) -> String
random_bytesint[]at least 16 bytes from a secure random source, read by the caller; 20 is usual
returnsstringthe secret as unpadded base32, to store (encrypted) and to show in the QR code

For example

  • totp_secret(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19) → AAAQEAYEAUDAOCAJBIFQYDIOB4IBCEQT 20 random bytes, the usual size, are 32 characters
  • totp_secret(255, 254, 253, 252, 251, 250, 249, 248, 247, 246, 245, 244, 243, 242, 241, 240) → 777P37H37L47R57W6X2PH4XR6A 16 bytes, the least accepted (RFC 4226 R6: 128 bits)
  • totp_secret(49, 50, 51, 52, 53, 54, 55, 56, 57, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 48) → GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ the RFC 4226 test secret
fune!(auth.totp@^1);  // then call totp_secret(…)
impl/rust/totp_secret.rs · 31 lines · open · 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::encoding_base32_base32_encode::base32_encode;

/// A new secret from the caller's random bytes, as unpadded base32. A pure
/// function cannot read randomness itself.
///
/// # Panics
/// Panics on a value outside 0-255, or fewer than 16 bytes.
pub fn totp_secret(random_bytes: &[i64]) -> String {
    if random_bytes.iter().any(|b| !(0..=255).contains(b)) {
        panic!("randomBytes must be a list of integers from 0 to 255");
    }
    if random_bytes.len() < 16 {
        panic!("randomBytes must hold at least 16 bytes (128 bits)");
    }
    base32_encode(random_bytes, false)
}

pub fn fune_vector(args: &[Value]) -> Value {
    let bytes: Vec<i64> = match &args[0] {
        Value::Arr(items) => items
            .iter()
            .map(|item| match item {
                Value::Int(i) => *i,
                _ => panic!("randomBytes must be a list of integers from 0 to 255"),
            })
            .collect(),
        _ => panic!("randomBytes must be a list of integers from 0 to 255"),
    };
    Value::str(&totp_secret(&bytes))
}

totp_uri throws on bad input 11 tests

pub fn totp_uri(issuer: &str, account: &str, secret: &str, settings: &TotpSettings) -> String
issuerstringyour app's name, shown in the authenticator; no colon
accountstringthe user's email or username; no colon
secretstringthe base32 secret from totpSecret
settingsTotpSettingsthe algorithm, digits and period; SHA1, 6 and 30 for every authenticator app
returnsstringthe otpauth://totp/ URI to put in a QR code

For example

  • totp_uri(Acme, ada@example.com, JBSWY3DPEHPK3PXP, algorithm SHA1, digits 6, period 30) → otpauth://totp/Acme:ada%40example.com?secret=JBSWY3DPEHPK3PXP&issuer=Acme&algorithm=SHA1&digits=6&period=30 the usual QR code: SHA1, 6 digits, 30 seconds
  • totp_uri(Acme Corp, ada lovelace@example.com, GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, algorithm SHA1, digits 6, period 30) → otpauth://totp/Acme%20Corp:ada%20lovelace%40example.com?secret=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ&issuer=Acme%20Corp&algorithm=SHA1&digits=6&period=30 spaces and an at sign are percent-encoded in the label and the issuer
  • totp_uri(Acme, ada, gezdgnbvgy3tqojqgezdgnbvgy3tqojq, algorithm SHA1, digits 6, period 30) → otpauth://totp/Acme:ada?secret=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ&issuer=Acme&algorithm=SHA1&digits=6&period=30 a lower-case, padded secret is written back canonical
fune!(auth.totp@^1);  // then call totp_uri(…)
impl/rust/totp_uri.rs · 58 lines · open · 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]),
    ))
}

hotp_code throws on bad input 20 tests

pub fn hotp_code(secret: &str, counter: i64, digits: i64, algorithm: &str) -> String
secretstringthe base32 secret
counterintthe moving factor, 0 to 2^53 - 1
digitsint6, 7 or 8
algorithmTotpAlgorithm
returnsstringthe code, zero-padded to digits

For example

  • hotp_code(GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 0, 6, SHA1) → 755224 RFC 4226 Appendix D: counter 0
  • hotp_code(GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 1, 6, SHA1) → 287082 RFC 4226 Appendix D: counter 1
  • hotp_code(GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 2, 6, SHA1) → 359152 RFC 4226 Appendix D: counter 2
fune!(auth.totp@^1);  // then call hotp_code(…)
impl/rust/hotp_code.rs · 97 lines · open · 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::crypto_hmac_sha1::hmac_sha1;  ← from crypto.hmac-sha1 ^1.0.0 · built alongside by fune
use super::crypto_hmac_sha256::hmac_sha256;  ← from crypto.hmac-sha256 ^1.0.0 · built alongside by fune
use super::encoding_base32_base32_decode::base32_decode;

const MAX_SAFE: i64 = 9007199254740991;

/// Whole number from 0 to 2^53 - 1: the range all three languages agree on.
pub fn is_totp_whole(value: i64) -> bool {
    (0..=MAX_SAFE).contains(&value)
}

pub fn check_totp_digits(digits: i64) {
    if !(6..=8).contains(&digits) {
        panic!("digits must be 6, 7 or 8");
    }
}

pub fn check_totp_algorithm(algorithm: &str) {
    if algorithm != "SHA1" && algorithm != "SHA256" {
        panic!("algorithm must be SHA1 or SHA256");
    }
}

pub fn check_totp_settings(settings: &TotpSettings) {
    check_totp_algorithm(&settings.algorithm);
    check_totp_digits(settings.digits);
    if !is_totp_whole(settings.period) || settings.period < 1 {
        panic!("period must be a whole number of seconds, 1 or more");
    }
}

/// The secret's bytes. Old Google Authenticator secrets are 80 bits, so 10
/// bytes is the least accepted; new ones from totp_secret are 16 or more.
pub fn totp_secret_key(secret: &str) -> Vec<i64> {
    let key = base32_decode(secret);
    if key.len() < 10 {
        panic!("secret must decode to at least 10 bytes");
    }
    key
}

/// RFC 4226 section 5.3: HMAC of the 8-byte big-endian counter, then dynamic
/// truncation.
pub fn hotp_from_key(key: &[i64], counter: i64, digits: i64, algorithm: &str) -> String {
    let message: Vec<i64> = (counter as u64).to_be_bytes().iter().map(|b| *b as i64).collect();
    let mac = if algorithm == "SHA1" { hmac_sha1(key, &message) } else { hmac_sha256(key, &message) };
    let offset = (mac[mac.len() - 1] & 15) as usize;
    let binary = ((mac[offset] & 127) << 24) | (mac[offset + 1] << 16) | (mac[offset + 2] << 8) | mac[offset + 3];
    let modulus = 10i64.pow(digits as u32);
    format!("{:0width$}", binary % modulus, width = digits as usize)
}

/// The RFC 4226 HOTP code for one counter value.
///
/// # Panics
/// Panics on a counter outside 0 to 2^53 - 1, digits other than 6-8, an
/// unknown algorithm, or a secret that is not base32 of at least 10 bytes.
pub fn hotp_code(secret: &str, counter: i64, digits: i64, algorithm: &str) -> String {
    if !is_totp_whole(counter) {
        panic!("counter must be a whole number from 0 to 2^53 - 1");
    }
    check_totp_digits(digits);
    check_totp_algorithm(algorithm);
    hotp_from_key(&totp_secret_key(secret), counter, digits, algorithm)
}

pub fn totp_text_arg(value: &Value, message: &str) -> String {
    match value {
        Value::Str(s) => s.clone(),
        _ => panic!("{}", message),
    }
}

pub fn totp_int_arg(value: &Value, message: &str) -> i64 {
    match value {
        Value::Int(i) => *i,
        _ => panic!("{}", message),
    }
}

pub fn totp_settings_from_value(value: &Value) -> TotpSettings {
    TotpSettings {
        algorithm: totp_text_arg(value.get("algorithm"), "algorithm must be SHA1 or SHA256"),
        digits: totp_int_arg(value.get("digits"), "digits must be 6, 7 or 8"),
        period: totp_int_arg(value.get("period"), "period must be a whole number of seconds, 1 or more"),
    }
}

pub fn fune_vector(args: &[Value]) -> Value {
    Value::str(&hotp_code(
        &totp_text_arg(&args[0], "base32 text must be a string"),
        totp_int_arg(&args[1], "counter must be a whole number from 0 to 2^53 - 1"),
        totp_int_arg(&args[2], "digits must be 6, 7 or 8"),
        &totp_text_arg(&args[3], "algorithm must be SHA1 or SHA256"),
    ))
}

totp_code throws on bad input 19 tests

pub fn totp_code(secret: &str, now: i64, settings: &TotpSettings) -> String
secretstringthe base32 secret
nowintthe current time in Unix seconds, read by the caller
settingsTotpSettings
returnsstringthe code for the time step now falls in

For example

  • totp_code(GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 59, algorithm SHA1, digits 8, period 30) → 94287082 RFC 6238 Appendix B: SHA1 at 59
  • totp_code(GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZA, 59, algorithm SHA256, digits 8, period 30) → 46119246 RFC 6238 Appendix B: SHA256 at 59
  • totp_code(GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 1,111,111,109, algorithm SHA1, digits 8, period 30) → 07081804 RFC 6238 Appendix B: SHA1 at 1111111109
fune!(auth.totp@^1);  // then call totp_code(…)
impl/rust/totp_code.rs · 31 lines · open · 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]),
    ))
}

verify_totp throws on bad input 22 tests

pub fn verify_totp(secret: &str, code: &str, now: i64, settings: &TotpSettings, window: i64, drift: i64, last_used_step: Option<i64>) -> TotpCheck
secretstringthe base32 secret
codestringwhat the user typed; spaces are ignored
nowintthe current time in Unix seconds, read by the caller
settingsTotpSettings
windowintsteps accepted either side of the expected one, 0 to 10; 1 is usual
driftintthe user's known clock drift in steps, from an earlier check; 0 when none
last_used_stepint?the step of the last code this user signed in with, or null; that step and earlier ones are refused
returnsTotpCheckvalid with the step and drift to store, or not valid with the reason

For example

  • verify_totp(GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 050471, 1,111,111,111, algorithm SHA1, digits 6, period 30, 1, 0, —) → valid true, step 37,037,037, drift 0, reason — the current code is valid, no drift
  • verify_totp(GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 081804, 1,111,111,111, algorithm SHA1, digits 6, period 30, 1, 0, —) → valid true, step 37,037,036, drift -1, reason — the previous step's code inside a window of 1, drift -1
  • verify_totp(GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 266759, 1,111,111,111, algorithm SHA1, digits 6, period 30, 1, 0, —) → valid true, step 37,037,038, drift 1, reason — the next step's code, drift +1
fune!(auth.totp@^1);  // then call verify_totp(…)
impl/rust/verify_totp.rs · 112 lines · open · 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,
    ))
}

Install

fune build

With that line in your source, in a Rust project (language rust in fune.project), fune build resolves it and its 4 dependencies, pins them in fune.lock, downloads only the Rust package of each, and builds the code above into your project’s .fune/build, one readable file per capability with a header linking back here. A crate’s build.rs runs it before every compile. Or pin a range in fune.project and build in one step:

fune add auth.totp

That builds the whole group. To build only what you call, and whatever it uses inside the group:

fune add auth.totp --only totpSecret
Download for Rust auth.totp-1.0.0-rust.fune · 44,857 bytes sha256 dfe0f70e4b6045d8f0146110bf93ee831f8baa279ad6e1523473f93681b26d72

The manifest, vectors and README with only the Rust implementation. Install it without the registry with fune add ./auth.totp-1.0.0-rust.fune, or fetch it from a terminal with fune pull auth.totp@1.0.0:rust.

The whole function, every language, is one file too: auth.totp-1.0.0.fune, 62,297 bytes, sha256 92c28b8b0cdbe81f910af8b79eaf833d66b5aaf7d830e292e0668d19dfdf7e59. It installs into a project of any language.

Customise it in your app

The seams this capability offers. Put a marker directly above a function of your own and fune build wires it into the built code; the package on the registry is not changed, the built file’s header lists it under CUSTOMISED, and fune hooks lists every hook in the project. How hooks work.

before — your function gets the arguments and returns them, changed or not, or throws to refuse the call.

// fune: before auth.totp.totpSecret
// fune: before auth.totp.totpUri
// fune: before auth.totp.hotpCode
// fune: before auth.totp.totpCode
// fune: before auth.totp.verifyTotp

after — your function gets the result and the arguments, and returns the final result.

// fune: after auth.totp.totpSecret
// fune: after auth.totp.totpUri
// fune: after auth.totp.hotpCode
// fune: after auth.totp.totpCode
// fune: after auth.totp.verifyTotp

replace — inside this capability’s code only, calls to a dependency go to your function, with the same signature. Other capabilities that use it are unaffected; write in * to replace it everywhere.

// fune: replace crypto.constant-time-equal in auth.totp
// fune: replace crypto.hmac-sha1 in auth.totp
// fune: replace crypto.hmac-sha256 in auth.totp
// fune: replace encoding.base32 in auth.totp

step — your function runs at a numbered point inside a function’s body, receives the in-scope values it names as parameters, and may return replacements. List the points with fune show auth.totp --steps.

// fune: step auth.totp.<fn> after <n|label>

Tests

A version published now needs at least 8 tests for every function, and one that expects the error for each function that throws; the registry refuses it otherwise. fune verify --all runs each case in TypeScript, Python and Rust, and a project runs them again with fune verify. This page lists the cases; it does not run them. The exact JSON is vectors.json.

totpSecret 8 tests

CaseArgumentsExpected
20 random bytes, the usual size, are 32 characters 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 → AAAQEAYEAUDAOCAJBIFQYDIOB4IBCEQT
16 bytes, the least accepted (RFC 4226 R6: 128 bits) 255, 254, 253, 252, 251, 250, 249, 248, 247, 246, 245, 244, 243, 242, 241, 240 → 777P37H37L47R57W6X2PH4XR6A
the RFC 4226 test secret 49, 50, 51, 52, 53, 54, 55, 56, 57, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 48 → GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ
32 bytes need no padding character either way, 52 characters unpadded 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31 → AAAQEAYEAUDAOCAJBIFQYDIOB4IBCEQTCQKRMFYYDENBWHA5DYPQ
15 bytes are too few 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 → error: randomBytes must hold at least 16 bytes (128 bits)
no bytes at all → error: randomBytes must hold at least 16 bytes (128 bits)
a value above 255 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 300 → error: randomBytes must be a list of integers from 0 to 255
a fraction is not a byte 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 1.5 → error: randomBytes must be a list of integers from 0 to 255

totpUri 11 tests

CaseArgumentsExpected
the usual QR code: SHA1, 6 digits, 30 seconds Acme, ada@example.com, JBSWY3DPEHPK3PXP, algorithm SHA1, digits 6, period 30 → otpauth://totp/Acme:ada%40example.com?secret=JBSWY3DPEHPK3PXP&issuer=Acme&algorithm=SHA1&digits=6&period=30
spaces and an at sign are percent-encoded in the label and the issuer Acme Corp, ada lovelace@example.com, GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, algorithm SHA1, digits 6, period 30 → otpauth://totp/Acme%20Corp:ada%20lovelace%40example.com?secret=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ&issuer=Acme%20Corp&algorithm=SHA1&digits=6&period=30
a lower-case, padded secret is written back canonical Acme, ada, gezdgnbvgy3tqojqgezdgnbvgy3tqojq, algorithm SHA1, digits 6, period 30 → otpauth://totp/Acme:ada?secret=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ&issuer=Acme&algorithm=SHA1&digits=6&period=30
SHA256, 8 digits, 60 seconds Acme, ada, GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZA, algorithm SHA256, digits 8, period 60 → otpauth://totp/Acme:ada?secret=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZA&issuer=Acme&algorithm=SHA256&digits=8&period=60
non-ASCII text is percent-encoded as UTF-8 Café Ltd, zoë@example.com, GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, algorithm SHA1, digits 6, period 30 → otpauth://totp/Caf%C3%A9%20Ltd:zo%C3%AB%40example.com?secret=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ&issuer=Caf%C3%A9%20Ltd&algorithm=SHA1&digits=6&period=30
a colon in the issuer would break the label Acme:Corp, ada, GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, algorithm SHA1, digits 6, period 30 → error: issuer must not contain a colon
a colon in the account Acme, ada:1, GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, algorithm SHA1, digits 6, period 30 → error: account must not contain a colon
an empty issuer , ada, GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, algorithm SHA1, digits 6, period 30 → error: issuer must not be empty
an empty account Acme, , GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, algorithm SHA1, digits 6, period 30 → error: account must not be empty
a secret that is not base32 Acme, ada, JBSW Y3DP, algorithm SHA1, digits 6, period 30 → error: base32 text may only contain A-Z and 2-7
Show the other 1 test
CaseArgumentsExpected
5 digits is not a code length authenticators show Acme, ada, GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, algorithm SHA1, digits 5, period 30 → error: digits must be 6, 7 or 8

hotpCode 20 tests

CaseArgumentsExpected
RFC 4226 Appendix D: counter 0 GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 0, 6, SHA1 → 755224
RFC 4226 Appendix D: counter 1 GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 1, 6, SHA1 → 287082
RFC 4226 Appendix D: counter 2 GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 2, 6, SHA1 → 359152
RFC 4226 Appendix D: counter 3 GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 3, 6, SHA1 → 969429
RFC 4226 Appendix D: counter 4 GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 4, 6, SHA1 → 338314
RFC 4226 Appendix D: counter 5 GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 5, 6, SHA1 → 254676
RFC 4226 Appendix D: counter 6 GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 6, 6, SHA1 → 287922
RFC 4226 Appendix D: counter 7 GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 7, 6, SHA1 → 162583
RFC 4226 Appendix D: counter 8 GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 8, 6, SHA1 → 399871
RFC 4226 Appendix D: counter 9 GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 9, 6, SHA1 → 520489
Show the other 10 tests
CaseArgumentsExpected
8 digits at counter 0 (reference: Python hmac) GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 0, 8, SHA1 → 84755224
SHA256 at counter 1 (reference: Python hmac) GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZA, 1, 6, SHA256 → 119246
a counter above 2^32 uses all eight counter bytes (reference: Python hmac) GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 4,294,967,297, 6, SHA1 → 108930
the largest counter, 2^53 - 1 (reference: Python hmac) GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 9,007,199,254,740,991, 6, SHA1 → 891307
a negative counter GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, -1, 6, SHA1 → error: counter must be a whole number from 0 to 2^53 - 1
a fractional counter GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 1.5, 6, SHA1 → error: counter must be a whole number from 0 to 2^53 - 1
9 digits GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 0, 9, SHA1 → error: digits must be 6, 7 or 8
SHA512 is not offered GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 0, 6, SHA512 → error: algorithm must be SHA1 or SHA256
a secret under 80 bits AAAAAAAAAAAAAAA, 0, 6, SHA1 → error: secret must decode to at least 10 bytes
a secret with a trailing newline GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ , 0, 6, SHA1 → error: base32 text may only contain A-Z and 2-7

totpCode 19 tests

CaseArgumentsExpected
RFC 6238 Appendix B: SHA1 at 59 GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 59, algorithm SHA1, digits 8, period 30 → 94287082
RFC 6238 Appendix B: SHA256 at 59 GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZA, 59, algorithm SHA256, digits 8, period 30 → 46119246
RFC 6238 Appendix B: SHA1 at 1111111109 GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 1,111,111,109, algorithm SHA1, digits 8, period 30 → 07081804
RFC 6238 Appendix B: SHA256 at 1111111109 GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZA, 1,111,111,109, algorithm SHA256, digits 8, period 30 → 68084774
RFC 6238 Appendix B: SHA1 at 1111111111 GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 1,111,111,111, algorithm SHA1, digits 8, period 30 → 14050471
RFC 6238 Appendix B: SHA256 at 1111111111 GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZA, 1,111,111,111, algorithm SHA256, digits 8, period 30 → 67062674
RFC 6238 Appendix B: SHA1 at 1234567890 GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 1,234,567,890, algorithm SHA1, digits 8, period 30 → 89005924
RFC 6238 Appendix B: SHA256 at 1234567890 GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZA, 1,234,567,890, algorithm SHA256, digits 8, period 30 → 91819424
RFC 6238 Appendix B: SHA1 at 2000000000 GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 2,000,000,000, algorithm SHA1, digits 8, period 30 → 69279037
RFC 6238 Appendix B: SHA256 at 2000000000 GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZA, 2,000,000,000, algorithm SHA256, digits 8, period 30 → 90698825
Show the other 9 tests
CaseArgumentsExpected
RFC 6238 Appendix B: SHA1 at 20000000000 GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 20,000,000,000, algorithm SHA1, digits 8, period 30 → 65353130
RFC 6238 Appendix B: SHA256 at 20000000000 GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZA, 20,000,000,000, algorithm SHA256, digits 8, period 30 → 77737706
6 digits, the last second of a step (59 is still step 1) GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 59, algorithm SHA1, digits 6, period 30 → 287082
the first second of the next step GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 60, algorithm SHA1, digits 6, period 30 → 359152
time zero is step zero GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 0, algorithm SHA1, digits 6, period 30 → 755224
a 60-second period halves the step (reference: Python hmac) GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 1,111,111,111, algorithm SHA1, digits 6, period 60 → 360094
a time before 1970 GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, -1, algorithm SHA1, digits 6, period 30 → error: now must be a whole number of seconds from 0 to 2^53 - 1
a period of 0 GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 59, algorithm SHA1, digits 6, period 0 → error: period must be a whole number of seconds, 1 or more
a fractional time GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 59.5, algorithm SHA1, digits 6, period 30 → error: now must be a whole number of seconds from 0 to 2^53 - 1

verifyTotp 22 tests

CaseArgumentsExpected
the current code is valid, no drift GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 050471, 1,111,111,111, algorithm SHA1, digits 6, period 30, 1, 0, — → valid true, step 37,037,037, drift 0, reason —
the previous step's code inside a window of 1, drift -1 GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 081804, 1,111,111,111, algorithm SHA1, digits 6, period 30, 1, 0, — → valid true, step 37,037,036, drift -1, reason —
the next step's code, drift +1 GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 266759, 1,111,111,111, algorithm SHA1, digits 6, period 30, 1, 0, — → valid true, step 37,037,038, drift 1, reason —
two steps old is outside a window of 1 GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 731029, 1,111,111,111, algorithm SHA1, digits 6, period 30, 1, 0, — → valid false, step —, drift —, reason wrong_code
a stored drift of -2 centres the window: two steps old is now the middle GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 731029, 1,111,111,111, algorithm SHA1, digits 6, period 30, 0, -2, — → valid true, step 37,037,035, drift -2, reason —
window 0 accepts only the centre GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 266759, 1,111,111,111, algorithm SHA1, digits 6, period 30, 0, 0, — → valid false, step —, drift —, reason wrong_code
spaces in a typed code are ignored GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 050 471, 1,111,111,111, algorithm SHA1, digits 6, period 30, 1, 0, — → valid true, step 37,037,037, drift 0, reason —
the code already used at this step is replayed GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 050471, 1,111,111,111, algorithm SHA1, digits 6, period 30, 1, 0, 37,037,037 → valid false, step —, drift —, reason replayed
a later step than the last one used is fine GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 266759, 1,111,111,111, algorithm SHA1, digits 6, period 30, 1, 0, 37,037,037 → valid true, step 37,037,038, drift 1, reason —
an older code after a newer one was used is replayed GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 081804, 1,111,111,111, algorithm SHA1, digits 6, period 30, 1, 0, 37,037,037 → valid false, step —, drift —, reason replayed
Show the other 12 tests
CaseArgumentsExpected
five digits is malformed, not wrong GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 05047, 1,111,111,111, algorithm SHA1, digits 6, period 30, 1, 0, — → valid false, step —, drift —, reason malformed_code
letters are malformed GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 12a456, 1,111,111,111, algorithm SHA1, digits 6, period 30, 1, 0, — → valid false, step —, drift —, reason malformed_code
full-width digits are malformed GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 123456, 1,111,111,111, algorithm SHA1, digits 6, period 30, 1, 0, — → valid false, step —, drift —, reason malformed_code
a code that matches no step in the window GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 000000, 1,111,111,111, algorithm SHA1, digits 6, period 30, 1, 0, — → valid false, step —, drift —, reason wrong_code
at time zero the window never reaches a negative step GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 755224, 0, algorithm SHA1, digits 6, period 30, 1, 0, — → valid true, step 0, drift 0, reason —
RFC 6238 SHA256, 8 digits, at 2000000000 GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZA, 90698825, 2,000,000,000, algorithm SHA256, digits 8, period 30, 1, 0, — → valid true, step 66,666,666, drift 0, reason —
a window of 11 is too wide GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 050471, 1,111,111,111, algorithm SHA1, digits 6, period 30, 11, 0, — → error: window must be a whole number from 0 to 10
a negative window GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 050471, 1,111,111,111, algorithm SHA1, digits 6, period 30, -1, 0, — → error: window must be a whole number from 0 to 10
a drift beyond 1000 steps GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 050471, 1,111,111,111, algorithm SHA1, digits 6, period 30, 1, 1,001, — → error: drift must be a whole number from -1000 to 1000
a fractional last used step GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 050471, 1,111,111,111, algorithm SHA1, digits 6, period 30, 1, 0, 1.5 → error: lastUsedStep must be a whole number or null
the code as a number rather than text GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 123,456, 1,111,111,111, algorithm SHA1, digits 6, period 30, 1, 0, — → error: code must be text
a secret that is too short is an error, not a wrong code AAAAAAAA, 050471, 1,111,111,111, algorithm SHA1, digits 6, period 30, 1, 0, — → error: secret must decode to at least 10 bytes

Verification

Verified by the operator, not the sandbox 80 test vectors declared; none run by the registry.

Verified locally by the registry's operator, not by the sandbox. This version was published with FUNE_VERIFY_MODE=inline-dev (the operator's import of the first-party registry, or a development server): the server validated the package - its manifest, signatures, imports, safety lint and test rules - but the registry did not run its test vectors in its sandbox. The operator runs them with `fune verify --all` before importing.

Signed by the registry with key fw-9dc887227da47575 (ed25519), over its integrity and this report's digest. The full report · JSON

More from the author

const secret = totpSecret([...crypto.getRandomValues(new Uint8Array(20))]);
const settings = { algorithm: "SHA1", digits: 6, period: 30 };
const uri = totpUri("Acme", user.email, secret, settings); // render as a QR code
// store the secret (encrypted at rest) as pending; confirm it with one
// verifyTotp before switching two-factor on, so a mis-scan never locks them out

`totpSecret` takes at least 16 random bytes (RFC 4226 R6 asks for 128 bits, recommends 160; 20 is what most services use) and returns unpadded base32, the form the otpauth:// URI and manual entry both use. `totpUri` writes the Google Authenticator Key Uri Format: `otpauth://totp/Acme:ada%40example.com?secret=...&issuer=Acme&algorithm=SHA1&digits=6&period=30`. The issuer and account are percent-encoded per RFC 3986 (unreserved characters kept, the rest as UTF-8 `%XX`), and a colon in either is refused because it would break the `Issuer:account` label.

**Use SHA1, 6 digits, 30 seconds** unless you control the authenticator: many apps ignore `algorithm`, `digits` and `period` and silently show the wrong codes. SHA1 here is HMAC-SHA1, which is still sound (see `crypto.sha1`). SHA256 is offered for authenticators that honour it; SHA-512 is not offered, because the registry has no SHA-512 yet.

## Checking a code

const check = verifyTotp(secret, typed, nowSeconds, settings, 1, user.totpDrift ?? 0, user.totpLastStep);
if (check.valid) save({ totpLastStep: check.step, totpDrift: check.drift });

- **Window.** Steps `drift - window` to `drift + window` around the expected step are accepted (`window` 0 to 10; 1 is RFC 6238's recommendation, which allows about 30 seconds of clock difference either way). They are tried closest first, the earlier step first on a tie, so the answer is deterministic. - **Drift.** `drift` in the result is how many steps the user's device is off. Store it and pass it next time to centre the window on that device's clock (RFC 6238 section 6), keeping the window small. - **Replay.** Pass the `step` of the user's last accepted code as `lastUsedStep`; a code for that step or an earlier one is refused with `replayed`, so a code seen over a shoulder or in a log cannot be used again (RFC 6238 section 5.2). Store the new `step` after every success. - **Typed input.** Spaces are removed first (`123 456`); anything that is not then exactly `digits` ASCII digits is `malformed_code`, not `wrong_code`. - Every step in the window is computed and compared with `crypto.constant-time-equal`, so timing does not say which step matched.

Rate-limit attempts (see `auth.login-throttle`): six digits are a million codes, and a window of 1 accepts three of them.

A secret must decode to at least 10 bytes (80 bits, the size older services issued) so existing secrets keep working; new ones are 16 or more. Base32 errors in a secret come straight from `encoding.base32`; strip spaces from a secret shown in groups before passing it.

`hotpCode` is the counter-based RFC 4226 code on its own, for hardware tokens or email/SMS codes keyed by a counter. Counters and times are 0 to 2^53 - 1, the range all three languages share.

## Vectors

RFC 4226 Appendix D (all ten counters) and RFC 6238 Appendix B (SHA1 and SHA256, all six times, 8 digits), with the test secrets `12345678901234567890` (base32 `GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ`) and `12345678901234567890123456789012`. Other expected codes were computed with Python's `hmac` module as an independent reference, and the URIs with `urllib.parse.quote`.

Sources: RFC 4226, HOTP (https://www.rfc-editor.org/rfc/rfc4226); RFC 6238, TOTP (https://www.rfc-editor.org/rfc/rfc6238); Key Uri Format (https://github.com/google/google-authenticator/wiki/Key-Uri-Format).

Files

PathBytes
README.md4,065
impl/python/hotp_code.py2,300
impl/python/totp_code.py669
impl/python/totp_secret.py784
impl/python/totp_uri.py1,548
impl/python/verify_totp.py2,453
impl/rust/hotp_code.rs3,554
impl/rust/totp_code.rs1,072
impl/rust/totp_secret.rs1,092
impl/rust/totp_uri.rs1,989
impl/rust/verify_totp.rs3,976
impl/typescript/hotp_code.ts2,891
impl/typescript/totp_code.ts686
impl/typescript/totp_secret.ts912
impl/typescript/totp_uri.ts1,494
impl/typescript/verify_totp.ts2,744
vectors.json17,978