Skip to main content

spoolframe_protocol/
device_sign_in.rs

1//! Signing a device in by approving it on another: the code a TV
2//! shows, and the link its QR code carries.
3//!
4//! The code is 8 letters from an alphabet without vowels (so it never
5//! spells a word), shown as two groups of four: `BCDF-GHJK`. 20^8 codes,
6//! a 5-minute life and rate-limited guessing put a guessed code out of
7//! reach. People type it with any case, dash or spacing; [`normalize`]
8//! takes all of them. The server makes codes; everyone reads them here.
9
10/// The letters a code is made of.
11pub const ALPHABET: &[u8; 20] = b"BCDFGHJKLMNPQRSTVWXZ";
12
13/// Letters in a code.
14pub const CODE_LEN: usize = 8;
15
16const LINK_PREFIX: &str = "spoolframe://approve?";
17
18/// `input` as a code (`BCDFGHJK`), whatever case, dashes or spaces it was
19/// typed with; `None` if it cannot be one.
20pub fn normalize(input: &str) -> Option<String> {
21    let code: String = input
22        .chars()
23        .filter(|c| !matches!(c, '-' | ' '))
24        .map(|c| c.to_ascii_uppercase())
25        .collect();
26    (code.len() == CODE_LEN && code.bytes().all(|b| ALPHABET.contains(&b))).then_some(code)
27}
28
29/// `code` as shown: `BCDF-GHJK`.
30pub fn display(code: &str) -> String {
31    match code.split_at_checked(CODE_LEN / 2) {
32        Some((a, b)) => format!("{a}-{b}"),
33        None => code.to_owned(),
34    }
35}
36
37/// What the device's QR code carries: the server to approve on (its hex
38/// `EndpointId`, so a phone that has not seen it can connect and pin it)
39/// and the code.
40pub fn link(server: &str, code: &str) -> String {
41    format!("{LINK_PREFIX}server={server}&code={code}")
42}
43
44/// The page of the web UI at `origin` (`https://media.example.org`) that
45/// approves `code`: what the QR code carries for a phone with a browser
46/// and no Spoolframe app.
47pub fn web_link(origin: &str, code: &str) -> String {
48    format!("{origin}/auth/device?code={code}")
49}
50
51/// A link a phone scanned or was opened with.
52#[derive(Debug, Clone, PartialEq, Eq)]
53pub struct Link {
54    /// Hex `EndpointId`.
55    pub server: String,
56    /// Normalized.
57    pub code: String,
58}
59
60/// The server and code of a [`link`]; `None` if `text` is not one.
61pub fn parse_link(text: &str) -> Option<Link> {
62    let query = text.trim().strip_prefix(LINK_PREFIX)?;
63    let (mut server, mut code) = (None, None);
64    for pair in query.split('&') {
65        match pair.split_once('=')? {
66            ("server", value) => server = Some(value),
67            ("code", value) => code = Some(value),
68            // A parameter a newer server added.
69            _ => {}
70        }
71    }
72    let server = server?;
73    if server.len() != 64 || !server.bytes().all(|b| b.is_ascii_hexdigit()) {
74        return None;
75    }
76    Some(Link {
77        server: server.to_ascii_lowercase(),
78        code: normalize(code?)?,
79    })
80}
81
82#[cfg(test)]
83mod tests {
84    use super::*;
85
86    const SERVER: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
87
88    #[test]
89    fn a_code_is_read_however_it_is_typed() {
90        for typed in ["BCDF-GHJK", "bcdfghjk", "bcdf ghjk", " BcDf-gHjK "] {
91            assert_eq!(normalize(typed).as_deref(), Some("BCDFGHJK"), "{typed:?}");
92        }
93    }
94
95    #[test]
96    fn a_code_with_a_vowel_or_the_wrong_length_is_not_one() {
97        for typed in ["BCDF-GHJA", "BCDFGHJ", "BCDFGHJKL", "", "BCDF-GHJ1"] {
98            assert_eq!(normalize(typed), None, "{typed:?}");
99        }
100    }
101
102    #[test]
103    fn a_code_shows_in_two_groups() {
104        assert_eq!(display("BCDFGHJK"), "BCDF-GHJK");
105    }
106
107    #[test]
108    fn a_link_reads_back() {
109        let text = link(SERVER, "BCDFGHJK");
110        assert_eq!(
111            text,
112            format!("spoolframe://approve?server={SERVER}&code=BCDFGHJK")
113        );
114        assert_eq!(
115            parse_link(&text),
116            Some(Link {
117                server: SERVER.into(),
118                code: "BCDFGHJK".into()
119            })
120        );
121    }
122
123    #[test]
124    fn a_web_link_is_the_approval_page_with_the_code() {
125        assert_eq!(
126            web_link("https://media.example.org", "BCDFGHJK"),
127            "https://media.example.org/auth/device?code=BCDFGHJK"
128        );
129    }
130
131    #[test]
132    fn a_link_takes_its_parameters_in_any_order_and_ignores_new_ones() {
133        let text = format!("spoolframe://approve?code=bcdf-ghjk&v=2&server={SERVER}");
134        assert_eq!(parse_link(&text).unwrap().code, "BCDFGHJK");
135    }
136
137    #[test]
138    fn anything_else_is_not_a_link() {
139        for text in [
140            "https://example.com/approve?server=x&code=BCDFGHJK".to_owned(),
141            format!("spoolframe://approve?server={SERVER}"),
142            "spoolframe://approve?server=abc&code=BCDFGHJK".to_owned(),
143            format!("spoolframe://approve?server={SERVER}&code=AAAA"),
144        ] {
145            assert_eq!(parse_link(&text), None, "{text}");
146        }
147    }
148}