Skip to main content

waratah_notebook/
token.rs

1//! Startup-minted jupyter auth token (v1 security stub).
2
3use std::hash::BuildHasher as _;
4use std::time::{SystemTime, UNIX_EPOCH};
5
6/// Mint a hex token (64 chars from `/dev/urandom`, 32 from the fallback).
7///
8/// Primary source is 32 bytes of `/dev/urandom`. If that is unreadable —
9/// very unusual on the Linux hosts this dev tool targets — fall back to two
10/// differently-seeded `RandomState` hashes over distinct nano-time samples.
11/// That fallback is not cryptographic, but this token is a loopback dev
12/// stub; the auth iteration replaces it (ARCH.md §9 notebooks).
13pub fn mint_token() -> String {
14    if let Ok(bytes) = read_urandom(32) {
15        return hex(&bytes);
16    }
17    let mut out = String::with_capacity(32);
18    for seed in 0..2u128 {
19        let mut hasher = std::collections::hash_map::RandomState::new().build_hasher();
20        let nanos = SystemTime::now()
21            .duration_since(UNIX_EPOCH)
22            .map(|d| d.as_nanos())
23            .unwrap_or(0);
24        hasher.write_u128(nanos ^ ((std::process::id() as u128) << 64) ^ seed);
25        use std::hash::Hasher as _;
26        out.push_str(&format!("{:016x}", hasher.finish()));
27    }
28    out
29}
30
31fn read_urandom(len: usize) -> std::io::Result<Vec<u8>> {
32    use std::io::Read as _;
33    let mut file = std::fs::File::open("/dev/urandom")?;
34    let mut bytes = vec![0u8; len];
35    file.read_exact(&mut bytes)?;
36    Ok(bytes)
37}
38
39fn hex(bytes: &[u8]) -> String {
40    bytes.iter().map(|b| format!("{b:02x}")).collect()
41}
42
43#[cfg(test)]
44mod tests {
45    use super::*;
46
47    #[test]
48    fn tokens_are_long_hex_and_distinct() {
49        let a = mint_token();
50        let b = mint_token();
51        assert_eq!(a.len(), 64);
52        assert!(a.chars().all(|c| c.is_ascii_hexdigit()));
53        assert_ne!(a, b);
54    }
55}