Functional Weave
Code in TypeScript

auth.email-token@1.0.0

impl/rust/hash_email_token.rs

1,402 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::crypto_sha256::sha256;  ← from crypto.sha256 ^1.0.0 · built alongside by fune
use super::encoding_hex_hex_encode::hex_encode;
use super::encoding_utf8_utf8_encode::utf8_encode;

/// Refuses a purpose that is not 1 to 40 characters of a-z, 0-9 and -.
pub fn check_email_token_purpose(purpose: &str) {
    let ok = !purpose.is_empty()
        && purpose.len() <= 40
        && purpose.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-');
    if !ok {
        panic!("purpose must be 1 to 40 characters of a-z, 0-9 and -");
    }
}

/// The stored key for a token: the hex SHA-256 of the purpose, ":" and the
/// token, so a token issued for one purpose never matches another.
///
/// # Panics
/// Panics on a malformed purpose or an empty token.
pub fn hash_email_token(token: &str, purpose: &str) -> String {
    check_email_token_purpose(purpose);
    if token.is_empty() {
        panic!("token must be a non-empty string");
    }
    hex_encode(&sha256(&utf8_encode(&format!("{}:{}", purpose, token))))
}

pub fn fune_vector(args: &[Value]) -> Value {
    let token = match &args[0] {
        Value::Str(s) => s.clone(),
        _ => panic!("token must be a non-empty string"),
    };
    let purpose = match &args[1] {
        Value::Str(s) => s.clone(),
        _ => panic!("purpose must be 1 to 40 characters of a-z, 0-9 and -"),
    };
    Value::Str(hash_email_token(&token, &purpose))
}