Functional Weave
Code in Python

auth.recovery-codes@1.0.0

impl/rust/generate_recovery_codes.rs

2,379 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

/// Crockford's base32 alphabet, lower case: no i, l, o or u to misread.
pub const RECOVERY_ALPHABET: &str = "0123456789abcdefghjkmnpqrstvwxyz";

const BYTES_PER_CODE: usize = 10;

/// Recovery codes from the caller's random bytes, 10 bytes (80 bits) each,
/// as 16 Crockford base32 characters in four groups. Pass bytes from a
/// CSPRNG (getrandom), never a seeded generator.
///
/// # Panics
/// Panics on a byte outside 0-255, a count outside 1-50, or too few bytes.
pub fn generate_recovery_codes(entropy: &[i64], count: i64) -> Vec<String> {
    if entropy.iter().any(|b| !(0..=255).contains(b)) {
        panic!("entropy must be a list of integers from 0 to 255");
    }
    if !(1..=50).contains(&count) {
        panic!("count must be a whole number from 1 to 50");
    }
    let needed = count as usize * BYTES_PER_CODE;
    if entropy.len() < needed {
        panic!(
            "entropy must hold at least 10 bytes per code: {} needed, {} given",
            needed,
            entropy.len()
        );
    }
    let alphabet = RECOVERY_ALPHABET.as_bytes();
    let mut codes = Vec::with_capacity(count as usize);
    for c in 0..count as usize {
        let mut chars = String::with_capacity(16);
        let mut buffer: i64 = 0;
        let mut bits = 0;
        for i in 0..BYTES_PER_CODE {
            buffer = ((buffer << 8) | entropy[c * BYTES_PER_CODE + i]) & 0xffff;
            bits += 8;
            while bits >= 5 {
                bits -= 5;
                chars.push(alphabet[((buffer >> bits) & 31) as usize] as char);
            }
        }
        codes.push(format!("{}-{}-{}-{}", &chars[0..4], &chars[4..8], &chars[8..12], &chars[12..16]));
    }
    codes
}

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