use sha2::{Digest as _, Sha256};
use crate::error::{KernelError, Result};
const ALPHABET: &[u8; 32] = b"0123456789ABCDEFGHJKMNPQRSTVWXYZ";
pub(crate) const TOKEN_PREFIX: &str = "adkd_";
pub(crate) fn random_bytes(len: usize) -> Result<Vec<u8>> {
let mut bytes = vec![0u8; len];
getrandom::fill(&mut bytes).map_err(|error| KernelError::Config {
reason: format!("the system random number generator failed: {error}"),
})?;
Ok(bytes)
}
pub(crate) fn hex(bytes: &[u8]) -> String {
bytes.iter().map(|byte| format!("{byte:02x}")).collect()
}
pub(crate) fn digest(text: &str) -> String {
hex(&Sha256::digest(text.as_bytes()))
}
pub(crate) fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
a.len() == b.len() && a.iter().zip(b).fold(0u8, |diff, (x, y)| diff | (x ^ y)) == 0
}
const CODE_CHARS: usize = 12;
pub(crate) fn new_code() -> Result<String> {
let bytes = random_bytes(8)?;
let bits = bytes.iter().fold(0u64, |bits, byte| (bits << 8) | u64::from(*byte));
let mut code = String::with_capacity(CODE_CHARS + 2);
for index in 0..CODE_CHARS {
if index > 0 && index.is_multiple_of(4) {
code.push('-');
}
let shift = 5 * (CODE_CHARS - 1 - index);
code.push(char::from(ALPHABET[((bits >> shift) & 0x1f) as usize]));
}
Ok(code)
}
pub(crate) fn normalize_code(code: &str) -> String {
code.chars()
.filter(|c| !matches!(c, '-' | ' ' | '_' | '.'))
.map(|c| match c.to_ascii_uppercase() {
'O' => '0',
'I' | 'L' => '1',
other => other,
})
.collect()
}
pub(crate) fn code_hash(code: &str) -> String {
digest(&normalize_code(code))
}
pub(crate) fn new_device_id() -> Result<String> {
Ok(hex(&random_bytes(8)?))
}
pub(crate) fn new_token(id: &str) -> Result<(String, String)> {
let secret = hex(&random_bytes(32)?);
let hash = digest(&secret);
Ok((format!("{TOKEN_PREFIX}{id}_{secret}"), hash))
}
pub(crate) fn parse_token(token: &str) -> Option<(&str, &str)> {
let rest = token.trim().strip_prefix(TOKEN_PREFIX)?;
let (id, secret) = rest.split_once('_')?;
(!id.is_empty() && !secret.is_empty()).then_some((id, secret))
}
pub(crate) fn clean_name(text: &str, max: usize) -> String {
text.chars().filter(|c| !c.is_control()).take(max).collect::<String>().trim().to_string()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn codes_are_twelve_crockford_characters() {
let mut seen = std::collections::BTreeSet::new();
for _ in 0..200 {
let code = new_code().unwrap();
assert_eq!(code.len(), 14, "{code}");
assert_eq!((&code[4..5], &code[9..10]), ("-", "-"), "{code}");
assert!(code.chars().filter(|c| *c != '-').all(|c| ALPHABET.contains(&(c as u8))));
seen.insert(code);
}
assert_eq!(seen.len(), 200, "codes repeat");
}
#[test]
fn a_code_carries_sixty_bits() {
let bits = CODE_CHARS * 5;
assert!(bits >= 60, "{bits} bits");
let firsts: std::collections::BTreeSet<char> =
(0..400).map(|_| new_code().unwrap().chars().next().unwrap()).collect();
assert!(firsts.len() > 16, "{firsts:?}");
}
#[test]
fn typed_codes_hash_as_shown() {
assert_eq!(code_hash("ab1d-o2l5"), code_hash("AB1D0215"));
assert_eq!(code_hash("AB1D 0215"), code_hash("ab1d-0215"));
assert_ne!(code_hash("AB1D-0215"), code_hash("AB1D-0216"));
}
#[test]
fn tokens_parse_and_hash() {
let id = new_device_id().unwrap();
let (token, hash) = new_token(&id).unwrap();
let (parsed, secret) = parse_token(&token).unwrap();
assert_eq!(parsed, id);
assert!(constant_time_eq(digest(secret).as_bytes(), hash.as_bytes()));
assert_eq!(parse_token("Bearer-xyz"), None);
assert_eq!(parse_token("adkd_"), None);
assert_eq!(parse_token("adkd_abc_"), None);
}
#[test]
fn names_lose_control_characters() {
assert_eq!(clean_name("Ana's\u{1b}[31m phone\n", 64), "Ana's[31m phone");
assert_eq!(clean_name("abcdef", 3), "abc");
}
}