Functional Weave
Code in Python

auth.recovery-codes@1.0.0

impl/rust/consume_recovery_code.rs

2,773 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_recovery_codes_hash_recovery_code::hash_recovery_code;  ← hashRecoveryCode, another function of this group · built into the same file, even by a slim install
use super::auth_recovery_codes_normalise_recovery_code::normalise_recovery_code;  ← normaliseRecoveryCode, 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
use super::encoding_hex_hex_decode::hex_decode;

fn is_hash(h: &str) -> bool {
    h.len() == 64 && h.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
}

/// One recovery-code attempt as a pure state change: the stored hashes in,
/// whether the code matched and the hashes to store from now on out. Every
/// stored hash is compared in constant time, with no early exit.
///
/// # Panics
/// Panics when a stored hash is not 64 lowercase hex characters.
pub fn consume_recovery_code(code: &str, hashes: &[String]) -> RecoveryCheck {
    if hashes.iter().any(|h| !is_hash(h)) {
        panic!("hashes must be a list of 64 lowercase hex characters each");
    }
    if normalise_recovery_code(code).is_none() {
        return RecoveryCheck { valid: false, index: None, remaining: hashes.to_vec() };
    }
    let attempt = hex_decode(&hash_recovery_code(code));
    let mut index: Option<usize> = None;
    for (i, h) in hashes.iter().enumerate() {
        let same = constant_time_equal(&attempt, &hex_decode(h));
        if same && index.is_none() {
            index = Some(i);
        }
    }
    match index {
        None => RecoveryCheck { valid: false, index: None, remaining: hashes.to_vec() },
        Some(found) => RecoveryCheck {
            valid: true,
            index: Some(found as i64),
            remaining: hashes
                .iter()
                .enumerate()
                .filter(|(i, _)| *i != found)
                .map(|(_, h)| h.clone())
                .collect(),
        },
    }
}

pub fn recovery_check_to_value(check: &RecoveryCheck) -> Value {
    Value::obj(vec![
        ("valid", Value::Bool(check.valid)),
        ("index", match check.index {
            Some(i) => Value::Int(i),
            None => Value::Null,
        }),
        ("remaining", Value::Arr(check.remaining.iter().map(|h| Value::str(h)).collect())),
    ])
}

pub fn fune_vector(args: &[Value]) -> Value {
    let code = match &args[0] {
        Value::Str(s) => s.clone(),
        _ => panic!("code must be a string"),
    };
    let hashes: Vec<String> = match &args[1] {
        Value::Arr(items) => items
            .iter()
            .map(|item| match item {
                Value::Str(s) => s.clone(),
                _ => panic!("hashes must be a list of 64 lowercase hex characters each"),
            })
            .collect(),
        _ => panic!("hashes must be a list of 64 lowercase hex characters each"),
    };
    recovery_check_to_value(&consume_recovery_code(&code, &hashes))
}