use super::funejson::Value; use super::auth_recovery_codes_hash_recovery_code::hash_recovery_code; use super::auth_recovery_codes_normalise_recovery_code::normalise_recovery_code; use super::crypto_constant_time_equal::constant_time_equal; 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 = 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 = 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)) }