Skip to main content

spoolframe_protocol/
pairing.rs

1//! Pairing a device with a portable identity:
2//! the link a device shows as a QR code, and the frames the identity's
3//! phone and the device then exchange over a direct Iroh connection on
4//! [`PAIR_ALPN`]. No Spoolframe server takes part.
5//!
6//! A TV has no camera, so the QR code goes one way, device to phone:
7//!
8//! `spoolframe://pair?e=<endpoint id>&c=<code>&n=<name>&a=<ip:port>&r=<relay url>`
9//!
10//! - `e`, the device's `EndpointId` as 64 hex digits, and `c`, the
11//!   one-time [`PairingCode`] as 43 base64url characters (no padding),
12//!   are required. The phone dials `e` and nothing else, and Iroh's TLS
13//!   proves the key, so the phone pairs with the device that showed the
14//!   code or with nothing.
15//! - `n` is the device's name, for "Pairing with …" while the phone
16//!   dials; cut to [`MAX_NAME`] characters.
17//! - `a` (repeated, at most [`MAX_ADDRS`]) and `r` (repeated, at most
18//!   [`MAX_RELAYS`]) are where the device may be reached. Hints: the key
19//!   is still proved whatever path is taken.
20//!
21//! Values are percent-encoded as in an invite link ([`crate::invite`]).
22//! A parameter this build does not know is ignored; a second `e` or `c`
23//! is not (the link is refused), nor is one that cannot be read.
24//!
25//! Then, on one bidirectional stream, each frame a [`crate::codec`] frame
26//! (big-endian `u32` length, CBOR) of at most [`MAX_FRAME`] bytes:
27//!
28//! 1. phone → device: [`PhoneFrame::Hello`], the code, the identity
29//!    the phone wants this device to act as, and its name;
30//! 2. device → phone: [`DeviceFrame::Key`], the device's key for that
31//!    identity and its name, or [`DeviceFrame::Refused`];
32//! 3. phone → device: [`PhoneFrame::Credential`], the root's credential
33//!    for that key, the identity's newest state and the servers it signs
34//!    in to, or [`PhoneFrame::Declined`];
35//! 4. device → phone: [`DeviceFrame::Done`], or [`DeviceFrame::Refused`].
36
37use std::fmt;
38use std::net::SocketAddr;
39
40use base64::Engine;
41use base64::engine::general_purpose::URL_SAFE_NO_PAD;
42use serde::{Deserialize, Serialize};
43
44use crate::invite::{decode, encode, is_relay_url};
45use crate::portable::{
46    DevicePublicKey, PortableIdentityState, PortableUserId, UserDeviceCredential,
47};
48
49/// The ALPN of pairing, version 1. A device accepts it only while it
50/// shows a pairing code; at any other time a connection on it fails its
51/// handshake.
52pub const PAIR_ALPN: &[u8] = b"spoolframe/pair/1";
53
54/// Bytes in a [`PairingCode`]: 256 bits, out of reach of guessing within
55/// its five minutes whatever the rate.
56pub const CODE_LEN: usize = 32;
57
58/// How long a code is good for, from when the device shows it.
59pub const CODE_TTL_SECS: u64 = 5 * 60;
60
61/// The longest link read, in bytes. A link this build writes fits with
62/// every hint at its limit, the name in characters of three bytes each;
63/// a usual one (a LAN address or two, a short name) is under 250, a QR
64/// code of version 10 or so.
65pub const MAX_LINK: usize = 1024;
66
67/// The most `a` hints a link is written or read with.
68pub const MAX_ADDRS: usize = 8;
69
70/// The most `r` hints a link is written or read with.
71pub const MAX_RELAYS: usize = 2;
72
73/// The most characters of the device's name a link carries.
74pub const MAX_NAME: usize = 32;
75
76/// The largest pairing frame either side reads: room for an identity
77/// state at its limit of revoked keys, 1024 of about 90 bytes each.
78pub const MAX_FRAME: u32 = 256 << 10;
79
80const LINK_PREFIX: &str = "spoolframe://pair?";
81
82/// A one-time pairing code: 32 random bytes the device made, shown only in
83/// its QR code. Compared in constant time; [`fmt::Debug`] does not show
84/// it.
85#[derive(Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
86#[serde(transparent)]
87pub struct PairingCode(#[serde(with = "serde_bytes")] [u8; CODE_LEN]);
88
89impl PairingCode {
90    pub fn from_bytes(bytes: [u8; CODE_LEN]) -> Self {
91        Self(bytes)
92    }
93
94    pub fn as_bytes(&self) -> &[u8; CODE_LEN] {
95        &self.0
96    }
97
98    /// Whether `other` is this code, in time that does not depend on
99    /// where they differ: every byte is looked at, whatever the first.
100    pub fn matches(&self, other: &PairingCode) -> bool {
101        let diff = self
102            .0
103            .iter()
104            .zip(other.0.iter())
105            .fold(0u8, |acc, (a, b)| acc | (a ^ b));
106        std::hint::black_box(diff) == 0
107    }
108
109    /// The code as the link writes it: base64url, no padding.
110    pub fn to_text(&self) -> String {
111        URL_SAFE_NO_PAD.encode(self.0)
112    }
113
114    /// The code `text` writes, as [`Self::to_text`] gives it; `None` if
115    /// it is not one.
116    pub fn from_text(text: &str) -> Option<Self> {
117        if text.len() != 43 {
118            return None;
119        }
120        let bytes = URL_SAFE_NO_PAD.decode(text).ok()?;
121        Some(Self(bytes.try_into().ok()?))
122    }
123}
124
125impl fmt::Debug for PairingCode {
126    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
127        f.write_str("PairingCode(<redacted>)")
128    }
129}
130
131/// What a pairing link holds.
132#[derive(Clone, PartialEq, Eq)]
133pub struct PairingLink {
134    /// The device's `EndpointId`.
135    pub endpoint: [u8; 32],
136    pub code: PairingCode,
137    /// What the device calls itself.
138    pub name: String,
139    /// Addresses it may be reached at.
140    pub addrs: Vec<SocketAddr>,
141    /// The URLs of relays it may be reached through.
142    pub relays: Vec<String>,
143}
144
145impl fmt::Debug for PairingLink {
146    // The code pairs: keep it out of logs.
147    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
148        f.debug_struct("PairingLink")
149            .field("endpoint", &hex(&self.endpoint))
150            .field("name", &self.name)
151            .field("addrs", &self.addrs)
152            .field("relays", &self.relays)
153            .finish_non_exhaustive()
154    }
155}
156
157impl PairingLink {
158    /// The link: what the QR code carries. The name is cut to
159    /// [`MAX_NAME`] characters, the hints to their limits, so what is
160    /// written reads back the same.
161    pub fn link(&self) -> String {
162        let mut link = format!(
163            "{LINK_PREFIX}e={}&c={}",
164            hex(&self.endpoint),
165            self.code.to_text()
166        );
167        let mut add = |key: &str, value: &str| {
168            link.push('&');
169            link.push_str(key);
170            link.push('=');
171            link.push_str(&encode(value));
172        };
173        add("n", &cut(&self.name));
174        for addr in self.addrs.iter().take(MAX_ADDRS) {
175            add("a", &addr.to_string());
176        }
177        for relay in self.relays.iter().take(MAX_RELAYS) {
178            add("r", relay);
179        }
180        link
181    }
182}
183
184/// Why a text is not a pairing link.
185#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
186pub enum LinkError {
187    #[error("not a Spoolframe pairing code")]
188    NotALink,
189    #[error("the pairing code is longer than any device shows")]
190    TooLong,
191    #[error("the pairing code is damaged: {0}")]
192    Damaged(&'static str),
193}
194
195/// The pairing link `text` holds.
196pub fn parse_link(text: &str) -> Result<PairingLink, LinkError> {
197    let text = text.trim();
198    if text.len() > MAX_LINK {
199        return Err(LinkError::TooLong);
200    }
201    let query = text.strip_prefix(LINK_PREFIX).ok_or(LinkError::NotALink)?;
202    let mut endpoint = None;
203    let mut code = None;
204    let mut name = String::new();
205    let mut addrs = Vec::new();
206    let mut relays = Vec::new();
207    for pair in query.split('&').filter(|p| !p.is_empty()) {
208        let (key, raw) = pair.split_once('=').unwrap_or((pair, ""));
209        match key {
210            "e" => {
211                if endpoint.is_some() {
212                    return Err(LinkError::Damaged("two endpoints"));
213                }
214                endpoint = Some(unhex(raw).ok_or(LinkError::Damaged("not an endpoint id"))?);
215            }
216            "c" => {
217                if code.is_some() {
218                    return Err(LinkError::Damaged("two codes"));
219                }
220                code = Some(PairingCode::from_text(raw).ok_or(LinkError::Damaged("not a code"))?);
221            }
222            "n" => name = cut(&decode(raw).ok_or(LinkError::Damaged("the name"))?),
223            "a" if addrs.len() < MAX_ADDRS => {
224                if let Some(addr) = decode(raw).and_then(|a| a.parse().ok()) {
225                    addrs.push(addr);
226                }
227            }
228            "r" if relays.len() < MAX_RELAYS => {
229                if let Some(relay) = decode(raw).filter(|r| is_relay_url(r)) {
230                    relays.push(relay);
231                }
232            }
233            // A parameter a newer device added, or a hint past the limit.
234            _ => {}
235        }
236    }
237    Ok(PairingLink {
238        endpoint: endpoint.ok_or(LinkError::Damaged("no endpoint id"))?,
239        code: code.ok_or(LinkError::Damaged("no code"))?,
240        name,
241        addrs,
242        relays,
243    })
244}
245
246/// What the phone sends.
247#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
248#[serde(tag = "type", rename_all = "snake_case")]
249pub enum PhoneFrame {
250    /// The code from the QR code, and the identity the device is to act
251    /// as. First, and only once.
252    Hello {
253        code: PairingCode,
254        identity: PortableUserId,
255        /// What the identity's person calls it ("Steve"), for the device
256        /// to show before they authorize: "Check this matches Steve's
257        /// phone". Cut to [`MAX_NAME`] characters ([`cut_name`]). Left
258        /// out by a phone before it was added, and by one that sends no
259        /// name: `None`.
260        #[serde(default, skip_serializing_if = "Option::is_none")]
261        name: Option<String>,
262        /// What the phone calls itself ("Steve's iPhone"), its device
263        /// name, cut as `name` is. Left out by a phone before it was
264        /// added: `None`.
265        #[serde(default, skip_serializing_if = "Option::is_none")]
266        phone_name: Option<String>,
267    },
268    /// The root's credential for the key [`DeviceFrame::Key`] gave, the
269    /// identity's newest state if the phone has one, and the servers the
270    /// identity signs in to, for the device to save and sign in
271    /// to.
272    Credential {
273        credential: Box<UserDeviceCredential>,
274        state: Option<Box<PortableIdentityState>>,
275        servers: Vec<PairedServer>,
276    },
277    /// The person on the phone said no.
278    Declined,
279}
280
281/// The most servers a [`PhoneFrame::Credential`] carries; a device reads
282/// no more.
283pub const MAX_PAIRED_SERVERS: usize = 16;
284
285/// A server the paired identity signs in to, as the phone has it saved:
286/// enough for the device to pin and reach it. The phone vouches
287/// for it as the invite that brought it there did; the device dials the
288/// key and nothing else, and Iroh proves it.
289#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
290pub struct PairedServer {
291    /// Its `EndpointId`, 64 hex digits.
292    pub endpoint_id: String,
293    /// The server id pinned with the key.
294    pub server_id: String,
295    pub name: String,
296    /// Where it may be reached, at most [`MAX_ADDRS`]: hints. As text,
297    /// as `ServerAddresses` sends them.
298    #[serde(with = "crate::messages::socket_addrs_as_text")]
299    pub addrs: Vec<SocketAddr>,
300    /// Its relays' URLs, at most [`MAX_RELAYS`]: hints.
301    pub relays: Vec<String>,
302}
303
304impl PairedServer {
305    /// This server held to what a device keeps of one: `None` if its key
306    /// is not one; its name cut, and its hints to their limits, a relay
307    /// that is not a relay's URL left out.
308    pub fn within_bounds(mut self) -> Option<Self> {
309        let key = &self.endpoint_id;
310        if key.len() != 64 || !key.bytes().all(|b| b.is_ascii_hexdigit()) {
311            return None;
312        }
313        self.endpoint_id = key.to_ascii_lowercase();
314        if self.server_id.is_empty() || self.server_id.len() > 128 {
315            return None;
316        }
317        crate::messages::cut(&mut self.name);
318        self.addrs.truncate(MAX_ADDRS);
319        self.relays.retain(|r| is_relay_url(r));
320        self.relays.truncate(MAX_RELAYS);
321        Some(self)
322    }
323}
324
325/// What the device sends.
326#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
327#[serde(tag = "type", rename_all = "snake_case")]
328pub enum DeviceFrame {
329    /// The device's key for the identity [`PhoneFrame::Hello`] named, and
330    /// what the device calls itself.
331    Key {
332        device_key: DevicePublicKey,
333        name: String,
334    },
335    /// The credential is installed.
336    Done,
337    /// The pairing is over, refused for `reason`.
338    Refused { reason: Refusal },
339}
340
341/// Why a device refused a pairing. The device's pairing ends with each
342/// of them: it shows a new code to try again.
343#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, thiserror::Error)]
344#[serde(rename_all = "snake_case")]
345pub enum Refusal {
346    /// The device does not take portable sign-ins (its policy is off).
347    #[error("this device does not allow sign-ins from other people's accounts")]
348    NotAllowed,
349    /// The code is not the one shown.
350    #[error("the pairing code does not match")]
351    WrongCode,
352    /// The code was shown more than [`CODE_TTL_SECS`] ago.
353    #[error("the pairing code has expired")]
354    Expired,
355    /// The credential does not hold, is for another identity or key, or
356    /// the state revokes the key.
357    #[error("the device did not accept the credential")]
358    CredentialRefused,
359    /// Something else went wrong on the device: its storage, most likely.
360    #[error("the device could not finish pairing")]
361    Failed,
362    /// The person at the device turned the pairing down, or left it
363    /// unanswered. A phone before this reads it as unknown, and ends as
364    /// for a frame it cannot read.
365    #[error("the pairing was turned down on the device")]
366    Rejected,
367    /// A reason this build does not know, from a newer device.
368    #[serde(other)]
369    #[error("the device refused the pairing")]
370    Unknown,
371}
372
373fn cut(name: &str) -> String {
374    name.chars().take(MAX_NAME).collect()
375}
376
377/// `name` as a pairing carries a name: cut to [`MAX_NAME`] characters.
378pub fn cut_name(name: &str) -> String {
379    cut(name)
380}
381
382fn hex(bytes: &[u8; 32]) -> String {
383    bytes.iter().map(|b| format!("{b:02x}")).collect()
384}
385
386fn unhex(text: &str) -> Option<[u8; 32]> {
387    if text.len() != 64 || !text.is_ascii() {
388        return None;
389    }
390    let mut bytes = [0u8; 32];
391    for (i, byte) in bytes.iter_mut().enumerate() {
392        *byte = u8::from_str_radix(&text[2 * i..2 * i + 2], 16).ok()?;
393    }
394    Some(bytes)
395}
396
397/// Characters in a [`RelayCode`]: 10 of Crockford's base32, 50 bits.
398/// Typed by a person, so short; guessed only at the rate the server lets
399/// a stranger try, against a code that lives [`RELAY_TTL_SECS`].
400pub const RELAY_CODE_LEN: usize = 10;
401
402/// How long a server holds a relayed pairing, from its offer.
403pub const RELAY_TTL_SECS: u64 = 5 * 60;
404
405/// Crockford's base32 alphabet: no I, L, O or U.
406const CROCKFORD: &[u8; 32] = b"0123456789ABCDEFGHJKMNPQRSTVWXYZ";
407
408/// The short code a device shows beside its QR code, for a root terminal
409/// with no camera to pair it through a server both reach: 10
410/// characters of Crockford's base32, written in two groups of five.
411#[derive(Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
412#[serde(try_from = "String", into = "String")]
413pub struct RelayCode(String);
414
415impl RelayCode {
416    /// The code `bytes` make: each of the first 10 taken mod 32.
417    pub fn from_random(bytes: [u8; RELAY_CODE_LEN]) -> Self {
418        Self(
419            bytes
420                .iter()
421                .map(|b| CROCKFORD[usize::from(b % 32)] as char)
422                .collect(),
423        )
424    }
425
426    /// The code a person typed: case, spaces and dashes ignored; I and L
427    /// read as 1, O as 0, as Crockford's base32 reads them. `None` if it
428    /// is not 10 such characters.
429    pub fn parse(text: &str) -> Option<Self> {
430        let code: String = text
431            .chars()
432            .filter(|c| !c.is_whitespace() && *c != '-')
433            .map(|c| match c.to_ascii_uppercase() {
434                'I' | 'L' => '1',
435                'O' => '0',
436                c => c,
437            })
438            .collect();
439        (code.len() == RELAY_CODE_LEN && code.bytes().all(|b| CROCKFORD.contains(&b)))
440            .then_some(Self(code))
441    }
442
443    /// As a person reads it: `ABCDE-FGHJK`.
444    pub fn display(&self) -> String {
445        format!("{}-{}", &self.0[..5], &self.0[5..])
446    }
447
448    pub fn as_str(&self) -> &str {
449        &self.0
450    }
451}
452
453impl fmt::Debug for RelayCode {
454    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
455        f.write_str("RelayCode(<redacted>)")
456    }
457}
458
459impl TryFrom<String> for RelayCode {
460    type Error = &'static str;
461
462    fn try_from(text: String) -> Result<Self, Self::Error> {
463        Self::parse(&text).ok_or("a relay code is 10 characters of Crockford's base32")
464    }
465}
466
467impl From<RelayCode> for String {
468    fn from(code: RelayCode) -> Self {
469        code.0
470    }
471}
472
473/// A device's pairing request, held on a server under a [`RelayCode`]
474/// for a root terminal to fetch: the key the root is to vouch for
475/// and the device's name. Public data: whoever has the code may read it.
476#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
477pub struct PairingOffer {
478    pub code: RelayCode,
479    /// The device's key for the identity it is to act as.
480    pub device_key: DevicePublicKey,
481    /// Cut to [`MAX_NAME`] characters.
482    pub name: String,
483}
484
485/// The root terminal's answer to a [`PairingOffer`]: what
486/// [`PhoneFrame::Credential`] carries on a direct pairing. The server only
487/// carries it: the device checks the credential names its own key and
488/// shows whose identity it is before it keeps it.
489#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
490pub struct PairingAnswer {
491    pub credential: Box<UserDeviceCredential>,
492    pub state: Option<Box<PortableIdentityState>>,
493    /// At most [`MAX_PAIRED_SERVERS`].
494    pub servers: Vec<PairedServer>,
495}
496
497#[cfg(test)]
498mod tests {
499    use super::*;
500
501    fn sample() -> PairingLink {
502        PairingLink {
503            endpoint: [0xab; 32],
504            code: PairingCode::from_bytes([7; 32]),
505            name: "Living room TV & co".into(),
506            addrs: vec![
507                "192.168.1.20:51234".parse().unwrap(),
508                "[fe80::1]:51234".parse().unwrap(),
509            ],
510            relays: vec!["https://relay.example.org/".into()],
511        }
512    }
513
514    #[test]
515    fn a_link_reads_back_as_written() {
516        let link = sample();
517        let text = link.link();
518        assert!(text.starts_with("spoolframe://pair?e=abab"), "{text}");
519        assert_eq!(parse_link(&text).unwrap(), link);
520    }
521
522    #[test]
523    fn a_link_at_every_limit_fits() {
524        let link = PairingLink {
525            name: "名".repeat(200),
526            addrs: (0..20)
527                .map(|n| {
528                    format!("[fd12:3456:789a:1:2:3:4:{n:x}]:65535")
529                        .parse()
530                        .unwrap()
531                })
532                .collect(),
533            relays: (0..5)
534                .map(|n| format!("https://relay-{n}.some-long-domain-name.example.org/"))
535                .collect(),
536            ..sample()
537        };
538        let text = link.link();
539        assert!(text.len() <= MAX_LINK, "{} bytes", text.len());
540        let read = parse_link(&text).unwrap();
541        assert_eq!(read.name.chars().count(), MAX_NAME);
542        assert_eq!(
543            (read.addrs.len(), read.relays.len()),
544            (MAX_ADDRS, MAX_RELAYS)
545        );
546    }
547
548    #[test]
549    fn what_is_not_a_link_is_refused() {
550        let good = sample().link();
551        assert_eq!(parse_link("https://example.org"), Err(LinkError::NotALink));
552        assert_eq!(
553            parse_link(&good.replace("spoolframe://pair?", "spoolframe://invite?")),
554            Err(LinkError::NotALink)
555        );
556        assert_eq!(
557            parse_link(&format!("{good}&x={}", "y".repeat(MAX_LINK))),
558            Err(LinkError::TooLong)
559        );
560        let code = PairingCode::from_bytes([7; 32]).to_text();
561        for (damaged, why) in [
562            (good.replace(&code, ""), "not a code"),
563            (good.replace(&code, &code[..42]), "not a code"),
564            (good.replace(&format!("c={code}"), "x=1"), "no code"),
565            (good.replace("e=abab", "e=zzab"), "not an endpoint id"),
566            (
567                good.replace(&format!("e={}", "ab".repeat(32)), ""),
568                "no endpoint id",
569            ),
570            (format!("{good}&c={code}"), "two codes"),
571            (format!("{good}&e={}", "cd".repeat(32)), "two endpoints"),
572            (format!("{good}&n=%ZZ"), "the name"),
573        ] {
574            assert_eq!(
575                parse_link(&damaged),
576                Err(LinkError::Damaged(why)),
577                "{damaged}"
578            );
579        }
580    }
581
582    #[test]
583    fn unknown_parameters_and_unreadable_hints_are_ignored() {
584        let text = format!(
585            "{}&v=2&a=not-an-address&r=ftp%3A%2F%2Fnope",
586            sample().link()
587        );
588        assert_eq!(parse_link(&text).unwrap(), sample());
589    }
590
591    #[test]
592    fn the_code_is_kept_out_of_debug() {
593        let link = sample();
594        let shown = format!("{link:?} {:?}", link.code);
595        assert!(!shown.contains(&link.code.to_text()), "{shown}");
596        assert!(!shown.contains("7, 7"), "{shown}");
597    }
598
599    #[test]
600    fn codes_match_only_themselves() {
601        let code = PairingCode::from_bytes([7; 32]);
602        assert!(code.matches(&PairingCode::from_bytes([7; 32])));
603        let mut last = [7; 32];
604        last[31] = 8;
605        assert!(!code.matches(&PairingCode::from_bytes(last)));
606        let mut first = [7; 32];
607        first[0] = 0;
608        assert!(!code.matches(&PairingCode::from_bytes(first)));
609    }
610
611    /// Damaged links, from a fixed seed: none panics, and what reads as a
612    /// link writes back to one that reads the same.
613    #[test]
614    fn mangled_links_never_panic_and_what_reads_round_trips() {
615        let base = sample().link().into_bytes();
616        let mut state = 0x9e37_79b9_7f4a_7c15u64;
617        let mut next = move || {
618            state ^= state << 13;
619            state ^= state >> 7;
620            state ^= state << 17;
621            state
622        };
623        for _ in 0..20_000 {
624            let mut bytes = base.clone();
625            for _ in 0..(next() % 6 + 1) {
626                let at = (next() as usize) % bytes.len();
627                match next() % 3 {
628                    0 => bytes[at] = next() as u8,
629                    1 => {
630                        bytes.remove(at);
631                    }
632                    _ => bytes.insert(at, b"&=%:[]"[(next() % 6) as usize]),
633                }
634                if bytes.is_empty() {
635                    break;
636                }
637            }
638            let Ok(text) = std::str::from_utf8(&bytes) else {
639                continue;
640            };
641            if let Ok(link) = parse_link(text) {
642                assert_eq!(parse_link(&link.link()), Ok(link));
643            }
644        }
645    }
646
647    /// The guest's name rides the hello; a hello without it, as a phone
648    /// before it sent, still reads, with no name.
649    #[test]
650    fn a_hello_carries_the_guest_s_name_or_none() {
651        let identity = PortableUserId::from_bytes(
652            ed25519_dalek::SigningKey::from_bytes(&[7; 32])
653                .verifying_key()
654                .to_bytes(),
655        )
656        .unwrap();
657        let hello = PhoneFrame::Hello {
658            code: PairingCode::from_bytes([7; 32]),
659            identity,
660            name: Some("Steve".into()),
661            phone_name: Some("Steve's iPhone".into()),
662        };
663        let read: PhoneFrame =
664            crate::codec::decode(&crate::codec::encode(&hello).unwrap()).unwrap();
665        assert_eq!(read, hello);
666        assert_eq!(serde_json::to_value(&hello).unwrap()["name"], "Steve");
667        let cbor = crate::codec::encode(&hello).unwrap();
668        let mut value: ciborium::Value = ciborium::from_reader(cbor.as_slice()).unwrap();
669        let ciborium::Value::Map(fields) = &mut value else {
670            panic!("a map");
671        };
672        fields.retain(|(k, _)| !matches!(k.as_text(), Some("name" | "phone_name")));
673        let old: PhoneFrame = crate::codec::decode(&crate::codec::encode(&value).unwrap()).unwrap();
674        assert!(
675            matches!(
676                old,
677                PhoneFrame::Hello {
678                    name: None,
679                    phone_name: None,
680                    ..
681                }
682            ),
683            "{old:?}"
684        );
685    }
686
687    /// A rejection on the device is its own reason on the wire, and a
688    /// reason a newer device adds reads as unknown.
689    #[test]
690    fn a_rejection_is_its_own_reason() {
691        let rejected = DeviceFrame::Refused {
692            reason: Refusal::Rejected,
693        };
694        assert_eq!(
695            serde_json::to_string(&rejected).unwrap(),
696            r#"{"type":"refused","reason":"rejected"}"#
697        );
698        let read: DeviceFrame =
699            crate::codec::decode(&crate::codec::encode(&rejected).unwrap()).unwrap();
700        assert_eq!(read, rejected);
701        let newer: Refusal = serde_json::from_str(r#""too_tired""#).unwrap();
702        assert_eq!(newer, Refusal::Unknown);
703    }
704
705    #[test]
706    fn frames_are_tagged_by_type() {
707        let declined = crate::codec::encode(&PhoneFrame::Declined).unwrap();
708        let read: PhoneFrame = crate::codec::decode(&declined).unwrap();
709        assert_eq!(read, PhoneFrame::Declined);
710        let refused = DeviceFrame::Refused {
711            reason: Refusal::NotAllowed,
712        };
713        let json = serde_json::to_string(&refused).unwrap();
714        assert_eq!(json, r#"{"type":"refused","reason":"not_allowed"}"#);
715    }
716
717    /// A credential frame for user 7's device 9, with `servers`.
718    fn credential_frame(servers: Vec<PairedServer>) -> PhoneFrame {
719        use ed25519_dalek::{Signer, SigningKey};
720        let root = SigningKey::from_bytes(&[7; 32]);
721        let device = SigningKey::from_bytes(&[9; 32]);
722        let credential = UserDeviceCredential::new(
723            PortableUserId::from_bytes(root.verifying_key().to_bytes()).unwrap(),
724            DevicePublicKey::from_bytes(device.verifying_key().to_bytes()).unwrap(),
725            1,
726            1_791_504_000,
727            1_791_504_000 + 3600,
728            |m| root.sign(m),
729        );
730        PhoneFrame::Credential {
731            credential: Box::new(credential),
732            state: None,
733            servers,
734        }
735    }
736
737    fn home() -> PairedServer {
738        PairedServer {
739            endpoint_id: "ab".repeat(32),
740            server_id: "q7k3mpa9trdwf2h".into(),
741            name: "Home Media".into(),
742            addrs: vec![
743                "192.168.1.10:7420".parse().unwrap(),
744                "[2001:db8::1]:7420".parse().unwrap(),
745            ],
746            relays: vec!["https://relay.example.org/".into()],
747        }
748    }
749
750    /// P7-06: the servers ride the credential frame, their addresses as
751    /// text (a tagged frame cannot carry serde's own form through CBOR).
752    #[test]
753    fn a_credential_frame_carries_its_servers() {
754        let frame = credential_frame(vec![home()]);
755        let read: PhoneFrame =
756            crate::codec::decode(&crate::codec::encode(&frame).unwrap()).unwrap();
757        assert_eq!(read, frame);
758        let json = serde_json::to_value(&frame).unwrap();
759        assert_eq!(json["servers"][0]["addrs"][1], "[2001:db8::1]:7420");
760    }
761
762    /// A credential frame without its servers, as a phone before P7-06
763    /// sent it, is refused: an empty list is sent as one.
764    #[test]
765    fn a_credential_frame_without_servers_is_refused() {
766        let mut json = serde_json::to_value(credential_frame(vec![home()])).unwrap();
767        json.as_object_mut().unwrap().remove("servers");
768        let error = serde_json::from_value::<PhoneFrame>(json).unwrap_err();
769        assert!(
770            error.to_string().contains("missing field `servers`"),
771            "{error}"
772        );
773    }
774
775    #[test]
776    fn a_paired_server_is_held_to_bounds() {
777        assert_eq!(home().within_bounds(), Some(home()));
778        let loud = PairedServer {
779            endpoint_id: "AB".repeat(32),
780            name: "x".repeat(500),
781            addrs: (0..20)
782                .map(|n| format!("10.0.0.{n}:7420").parse().unwrap())
783                .collect(),
784            relays: vec![
785                "ftp://nope".into(),
786                "https://a.example/".into(),
787                "https://b.example/".into(),
788                "https://c.example/".into(),
789            ],
790            ..home()
791        };
792        let held = loud.within_bounds().unwrap();
793        assert_eq!(held.endpoint_id, "ab".repeat(32));
794        assert_eq!(held.name.chars().count(), crate::MAX_HELLO_TEXT);
795        assert_eq!(held.addrs.len(), MAX_ADDRS);
796        assert_eq!(held.relays, ["https://a.example/", "https://b.example/"]);
797        for bad in [
798            PairedServer {
799                endpoint_id: "not a key".into(),
800                ..home()
801            },
802            PairedServer {
803                server_id: String::new(),
804                ..home()
805            },
806        ] {
807            assert_eq!(bad.within_bounds(), None);
808        }
809    }
810}