Skip to main content

spoolframe_protocol/
invite.rs

1//! Invites (P6-01): the link that finds a server from anywhere, and the
2//! code in it that lets someone make their own account there.
3//!
4//! An invite is one string, shown as a QR code and pasted as it is:
5//!
6//! `spoolframe://invite?server=<endpoint id>&name=<name>&addr=<ip:port>&relay=<url>&exp=<unix seconds>&role=<consumer|admin>&cap=<code>`
7//!
8//! Sent as text it has an https form (PX-45), which Messages and Mail make
9//! tappable and the apps open as a universal link, with the same query
10//! after `#`: `https://spoolframe.app/i#server=…&cap=…`. A browser never
11//! sends a fragment, so the site never sees a code, an address or a
12//! server's key. A QR code stays `spoolframe://`: it is scanned in the
13//! same room and never needs the site. [`parse_link`] reads both.
14//!
15//! - `server`, the hex `EndpointId`, is the only parameter a link must
16//!   have. A client pins it as it is: the link came from the server's
17//!   admin, so there is nothing to trust on first use.
18//! - `name`, `addr` (repeated, one per address) and `relay` (repeated)
19//!   are hints for finding it. Iroh still proves the key whatever path is
20//!   taken.
21//! - `cap` is the invite's code, the capability that makes an account
22//!   (`RedeemInvite`). Without it the link only finds and saves the server.
23//! - `exp` and `role` are hints for the join form ("Joins as a consumer ·
24//!   expires Oct 14"). The server enforces its own when the code is
25//!   redeemed, and a link without them works the same.
26//! - `kind=portable-account` (P7-05): the code grants a portable identity
27//!   access (`RedeemPortableInvite`) rather than making an account. Absent,
28//!   it makes an account (`RedeemInvite`). A hint for which form to show:
29//!   the server answers the other request with `WrongInviteKind`.
30//! - `kind=federation` (P8-01, experimental): the code pairs another
31//!   server with this one; that server's admin redeems it
32//!   (`PairServer`, or the admin API's `federation_redeem`).
33//!
34//! Values are percent-encoded where they would break the link (`&`, `=`,
35//! `#`, `%`, `+`, spaces, anything outside ASCII); `:` and `/` stay as
36//! they are, so addresses and URLs read as themselves. A parameter this
37//! build does not know is ignored, as in the device sign-in link
38//! ([`crate::device_sign_in::parse_link`]), and so is a hint that cannot
39//! be read: a newer server may add both.
40//!
41//! The code is of the setup code's class: 12 characters from an alphabet
42//! with nothing to misread, about 59 bits, shown in groups of four
43//! (`QW7K-2MFP-XR4T`). People may type it with any case, dash or spacing;
44//! [`normalize_code`] takes all of them.
45
46use std::fmt;
47use std::net::SocketAddr;
48
49use spoolframe_types::Role;
50
51/// The characters an invite code is made of: no 0/O, 1/I/L or U.
52pub const CODE_ALPHABET: &[u8; 30] = b"ABCDEFGHJKMNPQRSTVWXYZ23456789";
53
54/// Characters in a code: 30^12, about 59 bits.
55pub const CODE_LEN: usize = 12;
56
57/// The most `addr` or `relay` hints a link is read with; any after them
58/// are left out, so a link cannot make a client keep or dial without
59/// end.
60pub const MAX_HINTS: usize = 32;
61/// The longest link read, in bytes (P6-07, glm E-4). A QR code holds a
62/// few hundred; a pasted link past this is not one a server wrote.
63pub const MAX_LINK: usize = 4096;
64
65const LINK_PREFIX: &str = "spoolframe://invite?";
66/// The https form's site, and the page whose fragment holds the invite.
67/// Permanent: every shipped app's associated domains name it, and every
68/// invite sent.
69const SHARE_HOST: &str = "spoolframe.app";
70const SHARE_PREFIX: &str = "https://spoolframe.app/i#";
71
72/// `input` as a code (`QW7K2MFPXR4T`), whatever case, dashes or spaces it
73/// was typed with; `None` if it cannot be one.
74pub fn normalize_code(input: &str) -> Option<String> {
75    let code: String = input
76        .chars()
77        .filter(|c| !matches!(c, '-' | ' '))
78        .map(|c| c.to_ascii_uppercase())
79        .collect();
80    (code.len() == CODE_LEN && code.bytes().all(|b| CODE_ALPHABET.contains(&b))).then_some(code)
81}
82
83/// `code` as shown: `QW7K-2MFP-XR4T`.
84pub fn display_code(code: &str) -> String {
85    let groups: Vec<&str> = (0..code.len())
86        .step_by(4)
87        .filter_map(|i| code.get(i..(i + 4).min(code.len())))
88        .collect();
89    groups.join("-")
90}
91
92/// What an invite link holds.
93#[derive(Clone, Default, PartialEq, Eq)]
94pub struct Invite {
95    /// The server's `EndpointId`, hex, lowercase.
96    pub server: String,
97    /// What the server calls itself, for the join form until it answers.
98    pub name: Option<String>,
99    /// Addresses it may be reached at.
100    pub addrs: Vec<SocketAddr>,
101    /// The URLs of relays it may be reached through.
102    pub relays: Vec<String>,
103    /// The pkarr relay it publishes where it is to (P6-05): a device
104    /// looks it up there by its key when no hint reaches it.
105    pub lookup: Option<String>,
106    /// The invite's code, normalized; `None` for a link that only finds
107    /// the server.
108    pub code: Option<String>,
109    /// When the code stops working, in Unix seconds: a hint.
110    pub expires_at: Option<u64>,
111    /// The role the account is made with: a hint.
112    pub role: Option<Role>,
113    /// What the code does: a hint.
114    pub kind: InviteLinkKind,
115}
116
117/// What an invite link's code does, as the link says (P7-05).
118#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
119pub enum InviteLinkKind {
120    /// Makes an account on the server (`RedeemInvite`): a link without
121    /// `kind`.
122    #[default]
123    CreateUser,
124    /// Grants a portable identity access (`RedeemPortableInvite`).
125    PortableAccount,
126    /// Pairs another server with this one (P8-01): redeemed by that
127    /// server, not a device.
128    Federation,
129}
130
131impl fmt::Debug for Invite {
132    // The code makes an account: keep it out of logs.
133    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
134        f.debug_struct("Invite")
135            .field("server", &self.server)
136            .field("name", &self.name)
137            .field("addrs", &self.addrs)
138            .field("relays", &self.relays)
139            .field("lookup", &self.lookup)
140            .field("code", &self.code.as_ref().map(|_| "<redacted>"))
141            .field("expires_at", &self.expires_at)
142            .field("role", &self.role)
143            .field("kind", &self.kind)
144            .finish()
145    }
146}
147
148impl Invite {
149    /// The `spoolframe://` link: what the QR code carries.
150    pub fn link(&self) -> String {
151        format!("{LINK_PREFIX}{}", self.query())
152    }
153
154    /// The https link (PX-45): what is sent as text and copied. The invite
155    /// is its fragment, never its path or query, so a browser that opens
156    /// it sends none of it to the site.
157    pub fn share_link(&self) -> String {
158        format!("{SHARE_PREFIX}{}", self.query())
159    }
160
161    /// The parameters both links carry.
162    fn query(&self) -> String {
163        let mut link = format!("server={}", self.server);
164        let mut add = |key: &str, value: &str| {
165            link.push('&');
166            link.push_str(key);
167            link.push('=');
168            link.push_str(&encode(value));
169        };
170        if let Some(name) = &self.name {
171            add("name", name);
172        }
173        for addr in &self.addrs {
174            add("addr", &addr.to_string());
175        }
176        for relay in &self.relays {
177            add("relay", relay);
178        }
179        if let Some(lookup) = &self.lookup {
180            add("lookup", lookup);
181        }
182        if let Some(at) = self.expires_at {
183            add("exp", &at.to_string());
184        }
185        if let Some(role) = self.role {
186            add("role", role.as_str());
187        }
188        match self.kind {
189            InviteLinkKind::CreateUser => {}
190            InviteLinkKind::PortableAccount => add("kind", "portable-account"),
191            InviteLinkKind::Federation => add("kind", "federation"),
192        }
193        if let Some(code) = &self.code {
194            add("cap", &display_code(code));
195        }
196        link
197    }
198}
199
200/// The invite `text` holds, in either form; `None` if it is not an
201/// invite link: another scheme or site, no `server`, a `server` that is
202/// not a key, or a `cap` that is not a code (a damaged link, not one
203/// without a code).
204pub fn parse_link(text: &str) -> Option<Invite> {
205    let text = text.trim();
206    if text.len() > MAX_LINK {
207        return None;
208    }
209    let query = text
210        .strip_prefix(LINK_PREFIX)
211        .or_else(|| share_query(text))?;
212    let mut server = None;
213    let mut invite = Invite::default();
214    for pair in query.split('&').filter(|p| !p.is_empty()) {
215        let (key, raw) = pair.split_once('=').unwrap_or((pair, ""));
216        // A value that does not decode is a hint that cannot be read.
217        let value = decode(raw);
218        match (key, value) {
219            ("server", Some(value)) if server.is_none() => server = Some(value),
220            ("server", None) => return None,
221            ("cap", Some(value)) => invite.code = Some(normalize_code(&value)?),
222            ("cap", None) => return None,
223            // Shown in the join form: cut as a device's name is (PX-10).
224            ("name", Some(mut value)) => {
225                crate::messages::cut(&mut value);
226                invite.name = Some(value);
227            }
228            ("addr", Some(value)) if invite.addrs.len() < MAX_HINTS => {
229                if let Ok(addr) = value.parse() {
230                    invite.addrs.push(addr);
231                }
232            }
233            ("relay", Some(value)) if invite.relays.len() < MAX_HINTS => {
234                if is_relay_url(&value) {
235                    invite.relays.push(value);
236                }
237            }
238            // An http(s) URL, as a relay's is.
239            ("lookup", Some(value)) if is_relay_url(&value) => invite.lookup = Some(value),
240            ("exp", Some(value)) => invite.expires_at = value.parse().ok(),
241            ("role", Some(value)) => {
242                invite.role = match value.as_str() {
243                    "consumer" => Some(Role::Consumer),
244                    "admin" => Some(Role::Admin),
245                    _ => None,
246                }
247            }
248            ("kind", Some(value)) if value == "portable-account" => {
249                invite.kind = InviteLinkKind::PortableAccount;
250            }
251            ("kind", Some(value)) if value == "federation" => {
252                invite.kind = InviteLinkKind::Federation;
253            }
254            // A parameter a newer server added, or a hint past the limit.
255            _ => {}
256        }
257    }
258    let server = server?;
259    if server.len() != 64 || !server.bytes().all(|b| b.is_ascii_hexdigit()) {
260        return None;
261    }
262    invite.server = server.to_ascii_lowercase();
263    Some(invite)
264}
265
266/// The fragment of `text` if it is the https form: `https`, the host
267/// `spoolframe.app` and nothing else in the authority (no user, port or
268/// trailing dot), the path `/i` or `/i/`, no query, then `#`. Scheme and
269/// host in any case, as URLs allow; the path as it is. Anything else is
270/// not an invite, so a link to another site never reads as one.
271fn share_query(text: &str) -> Option<&str> {
272    let scheme = text.get(..8)?;
273    if !scheme.eq_ignore_ascii_case("https://") {
274        return None;
275    }
276    let rest = &text[8..];
277    let end = rest.find(['/', '?', '#']).unwrap_or(rest.len());
278    if !rest[..end].eq_ignore_ascii_case(SHARE_HOST) {
279        return None;
280    }
281    let after = &rest[end..];
282    after
283        .strip_prefix("/i#")
284        .or_else(|| after.strip_prefix("/i/#"))
285}
286
287/// Whether `value` may be a relay's URL: `https://` or `http://` and a
288/// host, and nothing an opener could read another way. The SDK holds a
289/// server's pushed relays and lookup to it as well (P6-07, glm E-3).
290pub fn is_relay_url(value: &str) -> bool {
291    let rest = value
292        .strip_prefix("https://")
293        .or_else(|| value.strip_prefix("http://"));
294    rest.is_some_and(|rest| {
295        !rest.is_empty()
296            && !rest.starts_with('/')
297            && !value.chars().any(|c| c.is_whitespace() || c.is_control())
298    })
299}
300
301/// Whether `b` goes into a link as it is: letters, digits and what an
302/// address or a URL is written with, but none of what a query string
303/// gives a meaning to (`&`, `=`, `#`, `+`, `%`).
304fn plain(b: u8) -> bool {
305    b.is_ascii_alphanumeric() || b"-._~:/@[]!$'()*,;?".contains(&b)
306}
307
308/// `value` percent-encoded where it is not [`plain`], byte by byte of its
309/// UTF-8.
310pub(crate) fn encode(value: &str) -> String {
311    let mut out = String::with_capacity(value.len());
312    for b in value.bytes() {
313        if plain(b) {
314            out.push(b as char);
315        } else {
316            out.push_str(&format!("%{b:02X}"));
317        }
318    }
319    out
320}
321
322/// `raw` with its `%XX` escapes decoded; `None` if an escape is broken or
323/// the bytes are not UTF-8. `+` is itself, as [`encode`] never writes one
324/// for a space.
325pub(crate) fn decode(raw: &str) -> Option<String> {
326    let bytes = raw.as_bytes();
327    let mut out = Vec::with_capacity(bytes.len());
328    let mut i = 0;
329    while i < bytes.len() {
330        if bytes[i] == b'%' {
331            let hex = std::str::from_utf8(bytes.get(i + 1..i + 3)?).ok()?;
332            out.push(u8::from_str_radix(hex, 16).ok()?);
333            i += 3;
334        } else {
335            out.push(bytes[i]);
336            i += 1;
337        }
338    }
339    String::from_utf8(out).ok()
340}
341
342#[cfg(test)]
343mod tests {
344    use super::*;
345
346    /// P6-07, glm E-4: a pasted link past MAX_LINK is not read, and the
347    /// name shown from one is cut as a device's name is.
348    #[test]
349    fn a_link_too_long_is_not_read_and_a_long_name_is_cut() {
350        let key = "ab".repeat(32);
351        let name = "x".repeat(500);
352        let link = format!("{LINK_PREFIX}server={key}&name={name}");
353        let invite = parse_link(&link).unwrap();
354        assert_eq!(invite.name.unwrap().chars().count(), crate::MAX_HELLO_TEXT);
355        let padded = format!("{link}&pad={}", "y".repeat(MAX_LINK));
356        assert_eq!(parse_link(&padded), None);
357    }
358
359    const SERVER: &str = "3f9a1c7e5b2d8a04e6c1f7b39d52a8e0c4b6f1a2d3e5c7b9a1f0e2d4c6b8a0f1";
360
361    /// The design's invite (WebInviteResult).
362    fn invite() -> Invite {
363        Invite {
364            server: SERVER.into(),
365            name: Some("Home Media".into()),
366            addrs: vec!["203.0.113.24:41641".parse().unwrap()],
367            relays: vec!["https://relay.home-media.example".into()],
368            lookup: None,
369            code: Some("QW7K2MFPXR4T".into()),
370            expires_at: Some(1_792_003_200),
371            role: Some(Role::Consumer),
372            kind: InviteLinkKind::CreateUser,
373        }
374    }
375
376    #[test]
377    fn a_link_is_the_one_the_design_shows() {
378        assert_eq!(
379            invite().link(),
380            format!(
381                "spoolframe://invite?server={SERVER}&name=Home%20Media\
382                 &addr=203.0.113.24:41641&relay=https://relay.home-media.example\
383                 &exp=1792003200&role=consumer&cap=QW7K-2MFP-XR4T"
384            )
385        );
386    }
387
388    #[test]
389    fn a_link_reads_back() {
390        assert_eq!(parse_link(&invite().link()), Some(invite()));
391    }
392
393    #[test]
394    fn a_share_link_is_the_query_after_the_site_s_fragment() {
395        assert_eq!(
396            invite().share_link(),
397            format!(
398                "https://spoolframe.app/i#server={SERVER}&name=Home%20Media\
399                 &addr=203.0.113.24:41641&relay=https://relay.home-media.example\
400                 &exp=1792003200&role=consumer&cap=QW7K-2MFP-XR4T"
401            )
402        );
403    }
404
405    #[test]
406    fn a_share_link_reads_back_as_the_same_invite() {
407        assert_eq!(parse_link(&invite().share_link()), Some(invite()));
408        let only = Invite {
409            server: SERVER.into(),
410            ..Invite::default()
411        };
412        assert_eq!(parse_link(&only.share_link()), Some(only));
413    }
414
415    /// The code, the key and the hints are all in the fragment: a browser
416    /// asks the site for `/i` and nothing else.
417    #[test]
418    fn nothing_of_the_invite_is_in_the_share_link_s_path_or_query() {
419        let link = invite().share_link();
420        let (before, fragment) = link.split_once('#').unwrap();
421        assert_eq!(before, "https://spoolframe.app/i");
422        for part in ["QW7K", SERVER, "203.0.113.24", "Home"] {
423            assert!(fragment.contains(part), "{part} in {fragment}");
424        }
425        // Not even an escaped `#` could end the fragment early.
426        let odd = Invite {
427            name: Some("#cap=AAAA?x/y".into()),
428            ..invite()
429        };
430        let link = odd.share_link();
431        assert_eq!(link.matches('#').count(), 1, "{link}");
432        assert_eq!(parse_link(&link), Some(odd));
433    }
434
435    /// A link written before PX-45, as a QR code made then carries it.
436    #[test]
437    fn a_spoolframe_link_from_before_share_links_still_reads() {
438        let old = format!(
439            "spoolframe://invite?server={SERVER}&name=Home%20Media\
440             &addr=203.0.113.24:41641&relay=https://relay.home-media.example\
441             &exp=1792003200&role=consumer&cap=QW7K-2MFP-XR4T"
442        );
443        assert_eq!(parse_link(&old), Some(invite()));
444    }
445
446    #[test]
447    fn a_share_link_is_read_with_a_trailing_slash_and_in_any_case_of_host() {
448        let query = invite().link().replace(LINK_PREFIX, "");
449        for text in [
450            format!("https://spoolframe.app/i/#{query}"),
451            format!("HTTPS://SpoolFrame.App/i#{query}"),
452            format!("  https://spoolframe.app/i#{query}\n"),
453        ] {
454            assert_eq!(parse_link(&text), Some(invite()), "{text}");
455        }
456    }
457
458    #[test]
459    fn a_share_link_on_another_site_or_shape_is_not_an_invite() {
460        let query = invite().link().replace(LINK_PREFIX, "");
461        for text in [
462            // Another host, or one made to look like it.
463            format!("https://example.com/i#{query}"),
464            format!("https://spoolframe.app.example.com/i#{query}"),
465            format!("https://www.spoolframe.app/i#{query}"),
466            format!("https://spoolframe.app./i#{query}"),
467            format!("https://spoolframe.apps/i#{query}"),
468            format!("https://spoo1frame.app/i#{query}"),
469            format!("https://xn--spoolframe-xyz.app/i#{query}"),
470            // The userinfo trick, both ways round, and a port.
471            format!("https://spoolframe.app@example.com/i#{query}"),
472            format!("https://user@spoolframe.app/i#{query}"),
473            format!("https://spoolframe.app:443/i#{query}"),
474            // Not https.
475            format!("http://spoolframe.app/i#{query}"),
476            format!("spoolframe.app/i#{query}"),
477            format!("//spoolframe.app/i#{query}"),
478            // In the query, which a browser would send the site.
479            format!("https://spoolframe.app/i?{query}"),
480            format!("https://spoolframe.app/i?x=1#{query}"),
481            // Another path.
482            format!("https://spoolframe.app/I#{query}"),
483            format!("https://spoolframe.app/invite#{query}"),
484            format!("https://spoolframe.app/i/x#{query}"),
485            format!("https://spoolframe.app/#{query}"),
486            format!("https://spoolframe.app#{query}"),
487            // An empty fragment.
488            "https://spoolframe.app/i#".to_owned(),
489        ] {
490            assert_eq!(parse_link(&text), None, "{text}");
491        }
492    }
493
494    /// P7-05: a portable-account invite says so; one that does not is an
495    /// account's, as every link before it was.
496    #[test]
497    fn a_portable_account_link_says_its_kind_and_reads_back() {
498        let portable = Invite {
499            role: None,
500            kind: InviteLinkKind::PortableAccount,
501            ..invite()
502        };
503        let link = portable.link();
504        assert!(link.contains("&kind=portable-account&"), "{link}");
505        assert_eq!(parse_link(&link), Some(portable));
506        assert!(!invite().link().contains("kind="));
507        // A kind this build does not know is a hint it cannot read.
508        let other = invite().link().replace("&cap=", "&kind=household&cap=");
509        assert_eq!(parse_link(&other).unwrap().kind, InviteLinkKind::CreateUser);
510    }
511
512    /// P8-01: a server's pairing invite says so, with no role.
513    #[test]
514    fn a_federation_link_says_its_kind_and_reads_back() {
515        let federation = Invite {
516            role: None,
517            kind: InviteLinkKind::Federation,
518            ..invite()
519        };
520        let link = federation.link();
521        assert!(link.contains("&kind=federation&"), "{link}");
522        assert!(!link.contains("role="), "{link}");
523        assert_eq!(parse_link(&link), Some(federation.clone()));
524        assert_eq!(parse_link(&federation.share_link()), Some(federation));
525    }
526
527    #[test]
528    fn every_hint_reads_back_however_many_and_whatever_they_hold() {
529        let invite = Invite {
530            server: SERVER.into(),
531            name: Some("Anna & Bob's = 100% \"home\" #1 + café ✓".into()),
532            addrs: vec![
533                "192.168.1.10:7420".parse().unwrap(),
534                "[2001:db8::1]:7420".parse().unwrap(),
535                "203.0.113.7:7420".parse().unwrap(),
536            ],
537            relays: vec![
538                "https://relay.example.org/".into(),
539                "https://other.example.org:8443/path?a=1&b=2#x".into(),
540            ],
541            lookup: Some("https://dns.example.org/pkarr".into()),
542            code: None,
543            expires_at: None,
544            role: Some(Role::Admin),
545            kind: InviteLinkKind::PortableAccount,
546        };
547        assert_eq!(parse_link(&invite.link()), Some(invite));
548    }
549
550    #[test]
551    fn a_link_with_only_the_server_finds_it() {
552        let only = Invite {
553            server: SERVER.into(),
554            ..Invite::default()
555        };
556        assert_eq!(only.link(), format!("spoolframe://invite?server={SERVER}"));
557        assert_eq!(parse_link(&only.link()), Some(only));
558    }
559
560    #[test]
561    fn parameters_come_in_any_order_and_new_ones_are_ignored() {
562        let text = format!(
563            "spoolframe://invite?v=2&cap=qw7k 2mfp-xr4t&role=consumer&flavour=mint\
564             &exp=1792003200&relay=https://relay.home-media.example&addr=203.0.113.24:41641\
565             &name=Home%20Media&server={}",
566            SERVER.to_ascii_uppercase()
567        );
568        assert_eq!(parse_link(&text), Some(invite()));
569    }
570
571    #[test]
572    fn a_hint_that_cannot_be_read_is_left_out() {
573        let text = format!(
574            "spoolframe://invite?server={SERVER}&addr=nowhere&addr=10.0.0.2:7420\
575             &relay=ftp://relay.example.org&exp=soon&role=overlord&name=%zz"
576        );
577        assert_eq!(
578            parse_link(&text),
579            Some(Invite {
580                server: SERVER.into(),
581                addrs: vec!["10.0.0.2:7420".parse().unwrap()],
582                ..Invite::default()
583            })
584        );
585    }
586
587    #[test]
588    fn hints_past_the_limit_are_left_out() {
589        let addrs: String = (0..MAX_HINTS + 5)
590            .map(|i| format!("&addr=10.0.{}.{}:7420", i / 250, i % 250 + 1))
591            .collect();
592        let read = parse_link(&format!("spoolframe://invite?server={SERVER}{addrs}")).unwrap();
593        assert_eq!(read.addrs.len(), MAX_HINTS);
594    }
595
596    #[test]
597    fn anything_else_is_not_an_invite() {
598        for text in [
599            format!("https://example.com/invite?server={SERVER}"),
600            format!("spoolframe://approve?server={SERVER}&code=BCDFGHJK"),
601            "spoolframe://invite?name=Home".to_owned(),
602            "spoolframe://invite?server=abc".to_owned(),
603            format!("spoolframe://invite?server={SERVER}&cap=AAAA"),
604            format!("spoolframe://invite?server={SERVER}&cap=QW7K-2MFP-XR40"),
605        ] {
606            assert_eq!(parse_link(&text), None, "{text}");
607        }
608    }
609
610    #[test]
611    fn a_code_is_read_however_it_is_typed() {
612        for typed in [
613            "QW7K-2MFP-XR4T",
614            "qw7k2mfpxr4t",
615            "qw7k 2mfp xr4t",
616            " Qw7K-2mFp-xR4t ",
617        ] {
618            assert_eq!(
619                normalize_code(typed).as_deref(),
620                Some("QW7K2MFPXR4T"),
621                "{typed:?}"
622            );
623        }
624    }
625
626    #[test]
627    fn a_code_with_a_misreadable_character_or_the_wrong_length_is_not_one() {
628        for typed in ["QW7K-2MFP-XR4O", "QW7K-2MFP-XR4", "QW7K-2MFP-XR4TT", ""] {
629            assert_eq!(normalize_code(typed), None, "{typed:?}");
630        }
631    }
632
633    #[test]
634    fn a_code_shows_in_groups_of_four() {
635        assert_eq!(display_code("QW7K2MFPXR4T"), "QW7K-2MFP-XR4T");
636    }
637
638    #[test]
639    fn the_code_stays_out_of_debug_output() {
640        assert!(!format!("{:?}", invite()).contains("QW7K"));
641    }
642}