Skip to main content

spoolframe_protocol/
invite.rs

1//! Invites: 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, 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`: 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` (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. 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: 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.
118#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
119#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
120pub enum InviteLinkKind {
121    /// Makes an account on the server (`RedeemInvite`): a link without
122    /// `kind`.
123    #[default]
124    CreateUser,
125    /// Grants a portable identity access (`RedeemPortableInvite`).
126    PortableAccount,
127    /// Pairs another server with this one: redeemed by that
128    /// server, not a device.
129    Federation,
130}
131
132impl fmt::Debug for Invite {
133    // The code makes an account: keep it out of logs.
134    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
135        f.debug_struct("Invite")
136            .field("server", &self.server)
137            .field("name", &self.name)
138            .field("addrs", &self.addrs)
139            .field("relays", &self.relays)
140            .field("lookup", &self.lookup)
141            .field("code", &self.code.as_ref().map(|_| "<redacted>"))
142            .field("expires_at", &self.expires_at)
143            .field("role", &self.role)
144            .field("kind", &self.kind)
145            .finish()
146    }
147}
148
149impl Invite {
150    /// The `spoolframe://` link: what the QR code carries.
151    pub fn link(&self) -> String {
152        format!("{LINK_PREFIX}{}", self.query())
153    }
154
155    /// The https link: what is sent as text and copied. The invite
156    /// is its fragment, never its path or query, so a browser that opens
157    /// it sends none of it to the site.
158    pub fn share_link(&self) -> String {
159        format!("{SHARE_PREFIX}{}", self.query())
160    }
161
162    /// The parameters both links carry.
163    fn query(&self) -> String {
164        let mut link = format!("server={}", self.server);
165        let mut add = |key: &str, value: &str| {
166            link.push('&');
167            link.push_str(key);
168            link.push('=');
169            link.push_str(&encode(value));
170        };
171        if let Some(name) = &self.name {
172            add("name", name);
173        }
174        for addr in &self.addrs {
175            add("addr", &addr.to_string());
176        }
177        for relay in &self.relays {
178            add("relay", relay);
179        }
180        if let Some(lookup) = &self.lookup {
181            add("lookup", lookup);
182        }
183        if let Some(at) = self.expires_at {
184            add("exp", &at.to_string());
185        }
186        if let Some(role) = self.role {
187            add("role", role.as_str());
188        }
189        match self.kind {
190            InviteLinkKind::CreateUser => {}
191            InviteLinkKind::PortableAccount => add("kind", "portable-account"),
192            InviteLinkKind::Federation => add("kind", "federation"),
193        }
194        if let Some(code) = &self.code {
195            add("cap", &display_code(code));
196        }
197        link
198    }
199}
200
201/// The invite `text` holds, in either form; `None` if it is not an
202/// invite link: another scheme or site, no `server`, a `server` that is
203/// not a key, or a `cap` that is not a code (a damaged link, not one
204/// without a code).
205pub fn parse_link(text: &str) -> Option<Invite> {
206    let text = text.trim();
207    if text.len() > MAX_LINK {
208        return None;
209    }
210    let query = text
211        .strip_prefix(LINK_PREFIX)
212        .or_else(|| share_query(text))?;
213    let mut server = None;
214    let mut invite = Invite::default();
215    for pair in query.split('&').filter(|p| !p.is_empty()) {
216        let (key, raw) = pair.split_once('=').unwrap_or((pair, ""));
217        // A value that does not decode is a hint that cannot be read.
218        let value = decode(raw);
219        match (key, value) {
220            ("server", Some(value)) if server.is_none() => server = Some(value),
221            ("server", None) => return None,
222            ("cap", Some(value)) => invite.code = Some(normalize_code(&value)?),
223            ("cap", None) => return None,
224            // Shown in the join form: cut as a device's name is.
225            ("name", Some(mut value)) => {
226                crate::messages::cut(&mut value);
227                invite.name = Some(value);
228            }
229            ("addr", Some(value)) if invite.addrs.len() < MAX_HINTS => {
230                if let Ok(addr) = value.parse() {
231                    invite.addrs.push(addr);
232                }
233            }
234            ("relay", Some(value)) if invite.relays.len() < MAX_HINTS => {
235                if is_relay_url(&value) {
236                    invite.relays.push(value);
237                }
238            }
239            // An http(s) URL, as a relay's is.
240            ("lookup", Some(value)) if is_relay_url(&value) => invite.lookup = Some(value),
241            ("exp", Some(value)) => invite.expires_at = value.parse().ok(),
242            ("role", Some(value)) => {
243                invite.role = match value.as_str() {
244                    "consumer" => Some(Role::Consumer),
245                    "admin" => Some(Role::Admin),
246                    _ => None,
247                }
248            }
249            ("kind", Some(value)) if value == "portable-account" => {
250                invite.kind = InviteLinkKind::PortableAccount;
251            }
252            ("kind", Some(value)) if value == "federation" => {
253                invite.kind = InviteLinkKind::Federation;
254            }
255            // A parameter a newer server added, or a hint past the limit.
256            _ => {}
257        }
258    }
259    let server = server?;
260    if server.len() != 64 || !server.bytes().all(|b| b.is_ascii_hexdigit()) {
261        return None;
262    }
263    invite.server = server.to_ascii_lowercase();
264    Some(invite)
265}
266
267/// The fragment of `text` if it is the https form: `https`, the host
268/// `spoolframe.app` and nothing else in the authority (no user, port or
269/// trailing dot), the path `/i` or `/i/`, no query, then `#`. Scheme and
270/// host in any case, as URLs allow; the path as it is. Anything else is
271/// not an invite, so a link to another site never reads as one.
272fn share_query(text: &str) -> Option<&str> {
273    let scheme = text.get(..8)?;
274    if !scheme.eq_ignore_ascii_case("https://") {
275        return None;
276    }
277    let rest = &text[8..];
278    let end = rest.find(['/', '?', '#']).unwrap_or(rest.len());
279    if !rest[..end].eq_ignore_ascii_case(SHARE_HOST) {
280        return None;
281    }
282    let after = &rest[end..];
283    after
284        .strip_prefix("/i#")
285        .or_else(|| after.strip_prefix("/i/#"))
286}
287
288/// Whether `value` may be a relay's URL: `https://` or `http://` and a
289/// host, and nothing an opener could read another way. The SDK holds a
290/// server's pushed relays and lookup to it as well.
291pub fn is_relay_url(value: &str) -> bool {
292    let rest = value
293        .strip_prefix("https://")
294        .or_else(|| value.strip_prefix("http://"));
295    rest.is_some_and(|rest| {
296        !rest.is_empty()
297            && !rest.starts_with('/')
298            && !value.chars().any(|c| c.is_whitespace() || c.is_control())
299    })
300}
301
302/// Whether `b` goes into a link as it is: letters, digits and what an
303/// address or a URL is written with, but none of what a query string
304/// gives a meaning to (`&`, `=`, `#`, `+`, `%`).
305fn plain(b: u8) -> bool {
306    b.is_ascii_alphanumeric() || b"-._~:/@[]!$'()*,;?".contains(&b)
307}
308
309/// `value` percent-encoded where it is not [`plain`], byte by byte of its
310/// UTF-8.
311pub(crate) fn encode(value: &str) -> String {
312    let mut out = String::with_capacity(value.len());
313    for b in value.bytes() {
314        if plain(b) {
315            out.push(b as char);
316        } else {
317            out.push_str(&format!("%{b:02X}"));
318        }
319    }
320    out
321}
322
323/// `raw` with its `%XX` escapes decoded; `None` if an escape is broken or
324/// the bytes are not UTF-8. `+` is itself, as [`encode`] never writes one
325/// for a space.
326pub(crate) fn decode(raw: &str) -> Option<String> {
327    let bytes = raw.as_bytes();
328    let mut out = Vec::with_capacity(bytes.len());
329    let mut i = 0;
330    while i < bytes.len() {
331        if bytes[i] == b'%' {
332            let hex = std::str::from_utf8(bytes.get(i + 1..i + 3)?).ok()?;
333            out.push(u8::from_str_radix(hex, 16).ok()?);
334            i += 3;
335        } else {
336            out.push(bytes[i]);
337            i += 1;
338        }
339    }
340    String::from_utf8(out).ok()
341}
342
343#[cfg(test)]
344mod tests {
345    use super::*;
346
347    /// P6-07, glm E-4: a pasted link past MAX_LINK is not read, and the
348    /// name shown from one is cut as a device's name is.
349    #[test]
350    fn a_link_too_long_is_not_read_and_a_long_name_is_cut() {
351        let key = "ab".repeat(32);
352        let name = "x".repeat(500);
353        let link = format!("{LINK_PREFIX}server={key}&name={name}");
354        let invite = parse_link(&link).unwrap();
355        assert_eq!(invite.name.unwrap().chars().count(), crate::MAX_HELLO_TEXT);
356        let padded = format!("{link}&pad={}", "y".repeat(MAX_LINK));
357        assert_eq!(parse_link(&padded), None);
358    }
359
360    const SERVER: &str = "3f9a1c7e5b2d8a04e6c1f7b39d52a8e0c4b6f1a2d3e5c7b9a1f0e2d4c6b8a0f1";
361
362    /// The design's invite (WebInviteResult).
363    fn invite() -> Invite {
364        Invite {
365            server: SERVER.into(),
366            name: Some("Home Media".into()),
367            addrs: vec!["203.0.113.24:41641".parse().unwrap()],
368            relays: vec!["https://relay.home-media.example".into()],
369            lookup: None,
370            code: Some("QW7K2MFPXR4T".into()),
371            expires_at: Some(1_792_003_200),
372            role: Some(Role::Consumer),
373            kind: InviteLinkKind::CreateUser,
374        }
375    }
376
377    #[test]
378    fn a_link_is_the_one_the_design_shows() {
379        assert_eq!(
380            invite().link(),
381            format!(
382                "spoolframe://invite?server={SERVER}&name=Home%20Media\
383                 &addr=203.0.113.24:41641&relay=https://relay.home-media.example\
384                 &exp=1792003200&role=consumer&cap=QW7K-2MFP-XR4T"
385            )
386        );
387    }
388
389    #[test]
390    fn a_link_reads_back() {
391        assert_eq!(parse_link(&invite().link()), Some(invite()));
392    }
393
394    #[test]
395    fn a_share_link_is_the_query_after_the_site_s_fragment() {
396        assert_eq!(
397            invite().share_link(),
398            format!(
399                "https://spoolframe.app/i#server={SERVER}&name=Home%20Media\
400                 &addr=203.0.113.24:41641&relay=https://relay.home-media.example\
401                 &exp=1792003200&role=consumer&cap=QW7K-2MFP-XR4T"
402            )
403        );
404    }
405
406    #[test]
407    fn a_share_link_reads_back_as_the_same_invite() {
408        assert_eq!(parse_link(&invite().share_link()), Some(invite()));
409        let only = Invite {
410            server: SERVER.into(),
411            ..Invite::default()
412        };
413        assert_eq!(parse_link(&only.share_link()), Some(only));
414    }
415
416    /// The code, the key and the hints are all in the fragment: a browser
417    /// asks the site for `/i` and nothing else.
418    #[test]
419    fn nothing_of_the_invite_is_in_the_share_link_s_path_or_query() {
420        let link = invite().share_link();
421        let (before, fragment) = link.split_once('#').unwrap();
422        assert_eq!(before, "https://spoolframe.app/i");
423        for part in ["QW7K", SERVER, "203.0.113.24", "Home"] {
424            assert!(fragment.contains(part), "{part} in {fragment}");
425        }
426        // Not even an escaped `#` could end the fragment early.
427        let odd = Invite {
428            name: Some("#cap=AAAA?x/y".into()),
429            ..invite()
430        };
431        let link = odd.share_link();
432        assert_eq!(link.matches('#').count(), 1, "{link}");
433        assert_eq!(parse_link(&link), Some(odd));
434    }
435
436    /// A link written before PX-45, as a QR code made then carries it.
437    #[test]
438    fn a_spoolframe_link_from_before_share_links_still_reads() {
439        let old = format!(
440            "spoolframe://invite?server={SERVER}&name=Home%20Media\
441             &addr=203.0.113.24:41641&relay=https://relay.home-media.example\
442             &exp=1792003200&role=consumer&cap=QW7K-2MFP-XR4T"
443        );
444        assert_eq!(parse_link(&old), Some(invite()));
445    }
446
447    #[test]
448    fn a_share_link_is_read_with_a_trailing_slash_and_in_any_case_of_host() {
449        let query = invite().link().replace(LINK_PREFIX, "");
450        for text in [
451            format!("https://spoolframe.app/i/#{query}"),
452            format!("HTTPS://SpoolFrame.App/i#{query}"),
453            format!("  https://spoolframe.app/i#{query}\n"),
454        ] {
455            assert_eq!(parse_link(&text), Some(invite()), "{text}");
456        }
457    }
458
459    #[test]
460    fn a_share_link_on_another_site_or_shape_is_not_an_invite() {
461        let query = invite().link().replace(LINK_PREFIX, "");
462        for text in [
463            // Another host, or one made to look like it.
464            format!("https://example.com/i#{query}"),
465            format!("https://spoolframe.app.example.com/i#{query}"),
466            format!("https://www.spoolframe.app/i#{query}"),
467            format!("https://spoolframe.app./i#{query}"),
468            format!("https://spoolframe.apps/i#{query}"),
469            format!("https://spoo1frame.app/i#{query}"),
470            format!("https://xn--spoolframe-xyz.app/i#{query}"),
471            // The userinfo trick, both ways round, and a port.
472            format!("https://spoolframe.app@example.com/i#{query}"),
473            format!("https://user@spoolframe.app/i#{query}"),
474            format!("https://spoolframe.app:443/i#{query}"),
475            // Not https.
476            format!("http://spoolframe.app/i#{query}"),
477            format!("spoolframe.app/i#{query}"),
478            format!("//spoolframe.app/i#{query}"),
479            // In the query, which a browser would send the site.
480            format!("https://spoolframe.app/i?{query}"),
481            format!("https://spoolframe.app/i?x=1#{query}"),
482            // Another path.
483            format!("https://spoolframe.app/I#{query}"),
484            format!("https://spoolframe.app/invite#{query}"),
485            format!("https://spoolframe.app/i/x#{query}"),
486            format!("https://spoolframe.app/#{query}"),
487            format!("https://spoolframe.app#{query}"),
488            // An empty fragment.
489            "https://spoolframe.app/i#".to_owned(),
490        ] {
491            assert_eq!(parse_link(&text), None, "{text}");
492        }
493    }
494
495    /// P7-05: a portable-account invite says so; one that does not is an
496    /// account's, as every link before it was.
497    #[test]
498    fn a_portable_account_link_says_its_kind_and_reads_back() {
499        let portable = Invite {
500            role: None,
501            kind: InviteLinkKind::PortableAccount,
502            ..invite()
503        };
504        let link = portable.link();
505        assert!(link.contains("&kind=portable-account&"), "{link}");
506        assert_eq!(parse_link(&link), Some(portable));
507        assert!(!invite().link().contains("kind="));
508        // A kind this build does not know is a hint it cannot read.
509        let other = invite().link().replace("&cap=", "&kind=household&cap=");
510        assert_eq!(parse_link(&other).unwrap().kind, InviteLinkKind::CreateUser);
511    }
512
513    /// P8-01: a server's pairing invite says so, with no role.
514    #[test]
515    fn a_federation_link_says_its_kind_and_reads_back() {
516        let federation = Invite {
517            role: None,
518            kind: InviteLinkKind::Federation,
519            ..invite()
520        };
521        let link = federation.link();
522        assert!(link.contains("&kind=federation&"), "{link}");
523        assert!(!link.contains("role="), "{link}");
524        assert_eq!(parse_link(&link), Some(federation.clone()));
525        assert_eq!(parse_link(&federation.share_link()), Some(federation));
526    }
527
528    #[test]
529    fn every_hint_reads_back_however_many_and_whatever_they_hold() {
530        let invite = Invite {
531            server: SERVER.into(),
532            name: Some("Anna & Bob's = 100% \"home\" #1 + café ✓".into()),
533            addrs: vec![
534                "192.168.1.10:7420".parse().unwrap(),
535                "[2001:db8::1]:7420".parse().unwrap(),
536                "203.0.113.7:7420".parse().unwrap(),
537            ],
538            relays: vec![
539                "https://relay.example.org/".into(),
540                "https://other.example.org:8443/path?a=1&b=2#x".into(),
541            ],
542            lookup: Some("https://dns.example.org/pkarr".into()),
543            code: None,
544            expires_at: None,
545            role: Some(Role::Admin),
546            kind: InviteLinkKind::PortableAccount,
547        };
548        assert_eq!(parse_link(&invite.link()), Some(invite));
549    }
550
551    #[test]
552    fn a_link_with_only_the_server_finds_it() {
553        let only = Invite {
554            server: SERVER.into(),
555            ..Invite::default()
556        };
557        assert_eq!(only.link(), format!("spoolframe://invite?server={SERVER}"));
558        assert_eq!(parse_link(&only.link()), Some(only));
559    }
560
561    #[test]
562    fn parameters_come_in_any_order_and_new_ones_are_ignored() {
563        let text = format!(
564            "spoolframe://invite?v=2&cap=qw7k 2mfp-xr4t&role=consumer&flavour=mint\
565             &exp=1792003200&relay=https://relay.home-media.example&addr=203.0.113.24:41641\
566             &name=Home%20Media&server={}",
567            SERVER.to_ascii_uppercase()
568        );
569        assert_eq!(parse_link(&text), Some(invite()));
570    }
571
572    #[test]
573    fn a_hint_that_cannot_be_read_is_left_out() {
574        let text = format!(
575            "spoolframe://invite?server={SERVER}&addr=nowhere&addr=10.0.0.2:7420\
576             &relay=ftp://relay.example.org&exp=soon&role=overlord&name=%zz"
577        );
578        assert_eq!(
579            parse_link(&text),
580            Some(Invite {
581                server: SERVER.into(),
582                addrs: vec!["10.0.0.2:7420".parse().unwrap()],
583                ..Invite::default()
584            })
585        );
586    }
587
588    #[test]
589    fn hints_past_the_limit_are_left_out() {
590        let addrs: String = (0..MAX_HINTS + 5)
591            .map(|i| format!("&addr=10.0.{}.{}:7420", i / 250, i % 250 + 1))
592            .collect();
593        let read = parse_link(&format!("spoolframe://invite?server={SERVER}{addrs}")).unwrap();
594        assert_eq!(read.addrs.len(), MAX_HINTS);
595    }
596
597    #[test]
598    fn anything_else_is_not_an_invite() {
599        for text in [
600            format!("https://example.com/invite?server={SERVER}"),
601            format!("spoolframe://approve?server={SERVER}&code=BCDFGHJK"),
602            "spoolframe://invite?name=Home".to_owned(),
603            "spoolframe://invite?server=abc".to_owned(),
604            format!("spoolframe://invite?server={SERVER}&cap=AAAA"),
605            format!("spoolframe://invite?server={SERVER}&cap=QW7K-2MFP-XR40"),
606        ] {
607            assert_eq!(parse_link(&text), None, "{text}");
608        }
609    }
610
611    #[test]
612    fn a_code_is_read_however_it_is_typed() {
613        for typed in [
614            "QW7K-2MFP-XR4T",
615            "qw7k2mfpxr4t",
616            "qw7k 2mfp xr4t",
617            " Qw7K-2mFp-xR4t ",
618        ] {
619            assert_eq!(
620                normalize_code(typed).as_deref(),
621                Some("QW7K2MFPXR4T"),
622                "{typed:?}"
623            );
624        }
625    }
626
627    #[test]
628    fn a_code_with_a_misreadable_character_or_the_wrong_length_is_not_one() {
629        for typed in ["QW7K-2MFP-XR4O", "QW7K-2MFP-XR4", "QW7K-2MFP-XR4TT", ""] {
630            assert_eq!(normalize_code(typed), None, "{typed:?}");
631        }
632    }
633
634    #[test]
635    fn a_code_shows_in_groups_of_four() {
636        assert_eq!(display_code("QW7K2MFPXR4T"), "QW7K-2MFP-XR4T");
637    }
638
639    #[test]
640    fn the_code_stays_out_of_debug_output() {
641        assert!(!format!("{:?}", invite()).contains("QW7K"));
642    }
643}