Skip to main content

ibridge_core/
account.rs

1// SPDX-License-Identifier: Apache-2.0
2
3//! Account identifiers.
4
5use std::fmt;
6
7use crate::error::ParseError;
8
9/// A primary iCloud address (`@icloud.com`, `@me.com` or `@mac.com`).
10///
11/// Held in lowercase: Apple does not tell `Ada@icloud.com` from `ada@icloud.com`, so
12/// neither does an account lookup, a cache key or a keychain entry.
13#[derive(Clone, PartialEq, Eq, Hash, Debug)]
14pub struct AppleId(String);
15
16impl AppleId {
17    /// Returns the address in lowercase.
18    #[must_use]
19    pub fn as_str(&self) -> &str {
20        &self.0
21    }
22}
23
24impl TryFrom<&str> for AppleId {
25    type Error = ParseError;
26
27    fn try_from(value: &str) -> Result<Self, Self::Error> {
28        let Some((local, domain)) = value.rsplit_once('@') else {
29            return Err(ParseError::AppleId);
30        };
31        if !valid_local_part(local) {
32            return Err(ParseError::AppleId);
33        }
34        let domain = domain.to_ascii_lowercase();
35        if !matches!(domain.as_str(), "icloud.com" | "me.com" | "mac.com") {
36            return Err(ParseError::AppleId);
37        }
38        Ok(Self(format!("{}@{domain}", local.to_ascii_lowercase())))
39    }
40}
41
42/// ASCII local part: letters, digits and `. _ % + -`, no leading, trailing or doubled dot.
43fn valid_local_part(local: &str) -> bool {
44    let bytes = local.as_bytes();
45    if bytes.is_empty() || bytes.len() > 64 {
46        return false;
47    }
48    let (Some(first), Some(last)) = (bytes.first(), bytes.last()) else {
49        return false;
50    };
51    if *first == b'.' || *last == b'.' {
52        return false;
53    }
54    let mut prev_dot = false;
55    for &byte in bytes {
56        let ok = byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'%' | b'+' | b'-');
57        if !ok || (byte == b'.' && prev_dot) {
58            return false;
59        }
60        prev_dot = byte == b'.';
61    }
62    true
63}
64
65impl fmt::Display for AppleId {
66    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
67        f.write_str(self.as_str())
68    }
69}