Skip to main content

agent_storage/family_invitation/
invitation_token.rs

1//! Invitation typeRaw bearer token
2
3use super::InvitationStorageError;
4use sha2::{Digest, Sha256};
5
6/// Raw bearer token. Its Debug implementation deliberately never reveals it.
7#[derive(Clone, PartialEq, Eq)]
8pub struct InvitationToken(String);
9
10impl InvitationToken {
11    pub(crate) fn generate() -> Self {
12        // Two independent UUIDv4 values provide 244 bits of CSPRNG-backed entropy.
13        Self(format!(
14            "{}{}",
15            uuid::Uuid::new_v4().simple(),
16            uuid::Uuid::new_v4().simple()
17        ))
18    }
19
20    pub(crate) fn hash(&self) -> String {
21        use std::fmt::Write as _;
22
23        let digest = Sha256::digest(self.0.as_bytes());
24        let mut hash = String::with_capacity(digest.len() * 2);
25        for byte in digest.iter() {
26            // Writing to a String is infallible.
27            write!(&mut hash, "{byte:02x}").expect("writing to String cannot fail");
28        }
29        hash
30    }
31
32    /// Parse a token received from an untrusted transport. Tokens are fixed-length
33    /// lowercase/uppercase hexadecimal strings; malformed values are rejected
34    /// before any identity provisioning takes place.
35    pub fn parse(value: &str) -> Result<Self, InvitationStorageError> {
36        if value.len() != 64 || !value.bytes().all(|byte| byte.is_ascii_hexdigit()) {
37            return Err(InvitationStorageError::NotFound);
38        }
39        Ok(Self(value.to_ascii_lowercase()))
40    }
41
42    pub fn expose(&self) -> &str {
43        &self.0
44    }
45}
46
47impl std::fmt::Debug for InvitationToken {
48    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
49        f.write_str("InvitationToken([REDACTED])")
50    }
51}