1use 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
49pub const PAIR_ALPN: &[u8] = b"spoolframe/pair/1";
53
54pub const CODE_LEN: usize = 32;
57
58pub const CODE_TTL_SECS: u64 = 5 * 60;
60
61pub const MAX_LINK: usize = 1024;
66
67pub const MAX_ADDRS: usize = 8;
69
70pub const MAX_RELAYS: usize = 2;
72
73pub const MAX_NAME: usize = 32;
75
76pub const MAX_FRAME: u32 = 256 << 10;
79
80const LINK_PREFIX: &str = "spoolframe://pair?";
81
82#[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 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 pub fn to_text(&self) -> String {
111 URL_SAFE_NO_PAD.encode(self.0)
112 }
113
114 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#[derive(Clone, PartialEq, Eq)]
133pub struct PairingLink {
134 pub endpoint: [u8; 32],
136 pub code: PairingCode,
137 pub name: String,
139 pub addrs: Vec<SocketAddr>,
141 pub relays: Vec<String>,
143}
144
145impl fmt::Debug for PairingLink {
146 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 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#[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
195pub 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 _ => {}
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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
248#[serde(tag = "type", rename_all = "snake_case")]
249pub enum PhoneFrame {
250 Hello {
253 code: PairingCode,
254 identity: PortableUserId,
255 #[serde(default, skip_serializing_if = "Option::is_none")]
261 name: Option<String>,
262 #[serde(default, skip_serializing_if = "Option::is_none")]
266 phone_name: Option<String>,
267 },
268 Credential {
273 credential: Box<UserDeviceCredential>,
274 state: Option<Box<PortableIdentityState>>,
275 servers: Vec<PairedServer>,
276 },
277 Declined,
279}
280
281pub const MAX_PAIRED_SERVERS: usize = 16;
284
285#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
290pub struct PairedServer {
291 pub endpoint_id: String,
293 pub server_id: String,
295 pub name: String,
296 #[serde(with = "crate::messages::socket_addrs_as_text")]
299 pub addrs: Vec<SocketAddr>,
300 pub relays: Vec<String>,
302}
303
304impl PairedServer {
305 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
327#[serde(tag = "type", rename_all = "snake_case")]
328pub enum DeviceFrame {
329 Key {
332 device_key: DevicePublicKey,
333 name: String,
334 },
335 Done,
337 Refused { reason: Refusal },
339}
340
341#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, thiserror::Error)]
344#[serde(rename_all = "snake_case")]
345pub enum Refusal {
346 #[error("this device does not allow sign-ins from other people's accounts")]
348 NotAllowed,
349 #[error("the pairing code does not match")]
351 WrongCode,
352 #[error("the pairing code has expired")]
354 Expired,
355 #[error("the device did not accept the credential")]
358 CredentialRefused,
359 #[error("the device could not finish pairing")]
361 Failed,
362 #[error("the pairing was turned down on the device")]
366 Rejected,
367 #[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
377pub 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
397pub const RELAY_CODE_LEN: usize = 10;
401
402pub const RELAY_TTL_SECS: u64 = 5 * 60;
404
405const CROCKFORD: &[u8; 32] = b"0123456789ABCDEFGHJKMNPQRSTVWXYZ";
407
408#[derive(Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
412#[serde(try_from = "String", into = "String")]
413pub struct RelayCode(String);
414
415impl RelayCode {
416 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 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 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
477pub struct PairingOffer {
478 pub code: RelayCode,
479 pub device_key: DevicePublicKey,
481 pub name: String,
483}
484
485#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
490pub struct PairingAnswer {
491 pub credential: Box<UserDeviceCredential>,
492 pub state: Option<Box<PortableIdentityState>>,
493 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 #[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 #[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 #[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 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 #[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 #[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}