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 },
256 Credential {
261 credential: Box<UserDeviceCredential>,
262 state: Option<Box<PortableIdentityState>>,
263 servers: Vec<PairedServer>,
264 },
265 Declined,
267}
268
269pub const MAX_PAIRED_SERVERS: usize = 16;
272
273#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
278pub struct PairedServer {
279 pub endpoint_id: String,
281 pub server_id: String,
283 pub name: String,
284 #[serde(with = "crate::messages::socket_addrs_as_text")]
287 pub addrs: Vec<SocketAddr>,
288 pub relays: Vec<String>,
290}
291
292impl PairedServer {
293 pub fn within_bounds(mut self) -> Option<Self> {
297 let key = &self.endpoint_id;
298 if key.len() != 64 || !key.bytes().all(|b| b.is_ascii_hexdigit()) {
299 return None;
300 }
301 self.endpoint_id = key.to_ascii_lowercase();
302 if self.server_id.is_empty() || self.server_id.len() > 128 {
303 return None;
304 }
305 crate::messages::cut(&mut self.name);
306 self.addrs.truncate(MAX_ADDRS);
307 self.relays.retain(|r| is_relay_url(r));
308 self.relays.truncate(MAX_RELAYS);
309 Some(self)
310 }
311}
312
313#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
315#[serde(tag = "type", rename_all = "snake_case")]
316pub enum DeviceFrame {
317 Key {
320 device_key: DevicePublicKey,
321 name: String,
322 },
323 Done,
325 Refused { reason: Refusal },
327}
328
329#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, thiserror::Error)]
332#[serde(rename_all = "snake_case")]
333pub enum Refusal {
334 #[error("this device does not allow sign-ins from other people's accounts")]
336 NotAllowed,
337 #[error("the pairing code does not match")]
339 WrongCode,
340 #[error("the pairing code has expired")]
342 Expired,
343 #[error("the device did not accept the credential")]
346 CredentialRefused,
347 #[error("the device could not finish pairing")]
349 Failed,
350}
351
352fn cut(name: &str) -> String {
353 name.chars().take(MAX_NAME).collect()
354}
355
356fn hex(bytes: &[u8; 32]) -> String {
357 bytes.iter().map(|b| format!("{b:02x}")).collect()
358}
359
360fn unhex(text: &str) -> Option<[u8; 32]> {
361 if text.len() != 64 || !text.is_ascii() {
362 return None;
363 }
364 let mut bytes = [0u8; 32];
365 for (i, byte) in bytes.iter_mut().enumerate() {
366 *byte = u8::from_str_radix(&text[2 * i..2 * i + 2], 16).ok()?;
367 }
368 Some(bytes)
369}
370
371pub const RELAY_CODE_LEN: usize = 10;
375
376pub const RELAY_TTL_SECS: u64 = 5 * 60;
378
379const CROCKFORD: &[u8; 32] = b"0123456789ABCDEFGHJKMNPQRSTVWXYZ";
381
382#[derive(Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
386#[serde(try_from = "String", into = "String")]
387pub struct RelayCode(String);
388
389impl RelayCode {
390 pub fn from_random(bytes: [u8; RELAY_CODE_LEN]) -> Self {
392 Self(
393 bytes
394 .iter()
395 .map(|b| CROCKFORD[usize::from(b % 32)] as char)
396 .collect(),
397 )
398 }
399
400 pub fn parse(text: &str) -> Option<Self> {
404 let code: String = text
405 .chars()
406 .filter(|c| !c.is_whitespace() && *c != '-')
407 .map(|c| match c.to_ascii_uppercase() {
408 'I' | 'L' => '1',
409 'O' => '0',
410 c => c,
411 })
412 .collect();
413 (code.len() == RELAY_CODE_LEN && code.bytes().all(|b| CROCKFORD.contains(&b)))
414 .then_some(Self(code))
415 }
416
417 pub fn display(&self) -> String {
419 format!("{}-{}", &self.0[..5], &self.0[5..])
420 }
421
422 pub fn as_str(&self) -> &str {
423 &self.0
424 }
425}
426
427impl fmt::Debug for RelayCode {
428 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
429 f.write_str("RelayCode(<redacted>)")
430 }
431}
432
433impl TryFrom<String> for RelayCode {
434 type Error = &'static str;
435
436 fn try_from(text: String) -> Result<Self, Self::Error> {
437 Self::parse(&text).ok_or("a relay code is 10 characters of Crockford's base32")
438 }
439}
440
441impl From<RelayCode> for String {
442 fn from(code: RelayCode) -> Self {
443 code.0
444 }
445}
446
447#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
451pub struct PairingOffer {
452 pub code: RelayCode,
453 pub device_key: DevicePublicKey,
455 pub name: String,
457}
458
459#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
464pub struct PairingAnswer {
465 pub credential: Box<UserDeviceCredential>,
466 pub state: Option<Box<PortableIdentityState>>,
467 pub servers: Vec<PairedServer>,
469}
470
471#[cfg(test)]
472mod tests {
473 use super::*;
474
475 fn sample() -> PairingLink {
476 PairingLink {
477 endpoint: [0xab; 32],
478 code: PairingCode::from_bytes([7; 32]),
479 name: "Living room TV & co".into(),
480 addrs: vec![
481 "192.168.1.20:51234".parse().unwrap(),
482 "[fe80::1]:51234".parse().unwrap(),
483 ],
484 relays: vec!["https://relay.example.org/".into()],
485 }
486 }
487
488 #[test]
489 fn a_link_reads_back_as_written() {
490 let link = sample();
491 let text = link.link();
492 assert!(text.starts_with("spoolframe://pair?e=abab"), "{text}");
493 assert_eq!(parse_link(&text).unwrap(), link);
494 }
495
496 #[test]
497 fn a_link_at_every_limit_fits() {
498 let link = PairingLink {
499 name: "名".repeat(200),
500 addrs: (0..20)
501 .map(|n| {
502 format!("[fd12:3456:789a:1:2:3:4:{n:x}]:65535")
503 .parse()
504 .unwrap()
505 })
506 .collect(),
507 relays: (0..5)
508 .map(|n| format!("https://relay-{n}.some-long-domain-name.example.org/"))
509 .collect(),
510 ..sample()
511 };
512 let text = link.link();
513 assert!(text.len() <= MAX_LINK, "{} bytes", text.len());
514 let read = parse_link(&text).unwrap();
515 assert_eq!(read.name.chars().count(), MAX_NAME);
516 assert_eq!(
517 (read.addrs.len(), read.relays.len()),
518 (MAX_ADDRS, MAX_RELAYS)
519 );
520 }
521
522 #[test]
523 fn what_is_not_a_link_is_refused() {
524 let good = sample().link();
525 assert_eq!(parse_link("https://example.org"), Err(LinkError::NotALink));
526 assert_eq!(
527 parse_link(&good.replace("spoolframe://pair?", "spoolframe://invite?")),
528 Err(LinkError::NotALink)
529 );
530 assert_eq!(
531 parse_link(&format!("{good}&x={}", "y".repeat(MAX_LINK))),
532 Err(LinkError::TooLong)
533 );
534 let code = PairingCode::from_bytes([7; 32]).to_text();
535 for (damaged, why) in [
536 (good.replace(&code, ""), "not a code"),
537 (good.replace(&code, &code[..42]), "not a code"),
538 (good.replace(&format!("c={code}"), "x=1"), "no code"),
539 (good.replace("e=abab", "e=zzab"), "not an endpoint id"),
540 (
541 good.replace(&format!("e={}", "ab".repeat(32)), ""),
542 "no endpoint id",
543 ),
544 (format!("{good}&c={code}"), "two codes"),
545 (format!("{good}&e={}", "cd".repeat(32)), "two endpoints"),
546 (format!("{good}&n=%ZZ"), "the name"),
547 ] {
548 assert_eq!(
549 parse_link(&damaged),
550 Err(LinkError::Damaged(why)),
551 "{damaged}"
552 );
553 }
554 }
555
556 #[test]
557 fn unknown_parameters_and_unreadable_hints_are_ignored() {
558 let text = format!(
559 "{}&v=2&a=not-an-address&r=ftp%3A%2F%2Fnope",
560 sample().link()
561 );
562 assert_eq!(parse_link(&text).unwrap(), sample());
563 }
564
565 #[test]
566 fn the_code_is_kept_out_of_debug() {
567 let link = sample();
568 let shown = format!("{link:?} {:?}", link.code);
569 assert!(!shown.contains(&link.code.to_text()), "{shown}");
570 assert!(!shown.contains("7, 7"), "{shown}");
571 }
572
573 #[test]
574 fn codes_match_only_themselves() {
575 let code = PairingCode::from_bytes([7; 32]);
576 assert!(code.matches(&PairingCode::from_bytes([7; 32])));
577 let mut last = [7; 32];
578 last[31] = 8;
579 assert!(!code.matches(&PairingCode::from_bytes(last)));
580 let mut first = [7; 32];
581 first[0] = 0;
582 assert!(!code.matches(&PairingCode::from_bytes(first)));
583 }
584
585 #[test]
588 fn mangled_links_never_panic_and_what_reads_round_trips() {
589 let base = sample().link().into_bytes();
590 let mut state = 0x9e37_79b9_7f4a_7c15u64;
591 let mut next = move || {
592 state ^= state << 13;
593 state ^= state >> 7;
594 state ^= state << 17;
595 state
596 };
597 for _ in 0..20_000 {
598 let mut bytes = base.clone();
599 for _ in 0..(next() % 6 + 1) {
600 let at = (next() as usize) % bytes.len();
601 match next() % 3 {
602 0 => bytes[at] = next() as u8,
603 1 => {
604 bytes.remove(at);
605 }
606 _ => bytes.insert(at, b"&=%:[]"[(next() % 6) as usize]),
607 }
608 if bytes.is_empty() {
609 break;
610 }
611 }
612 let Ok(text) = std::str::from_utf8(&bytes) else {
613 continue;
614 };
615 if let Ok(link) = parse_link(text) {
616 assert_eq!(parse_link(&link.link()), Ok(link));
617 }
618 }
619 }
620
621 #[test]
622 fn frames_are_tagged_by_type() {
623 let declined = crate::codec::encode(&PhoneFrame::Declined).unwrap();
624 let read: PhoneFrame = crate::codec::decode(&declined).unwrap();
625 assert_eq!(read, PhoneFrame::Declined);
626 let refused = DeviceFrame::Refused {
627 reason: Refusal::NotAllowed,
628 };
629 let json = serde_json::to_string(&refused).unwrap();
630 assert_eq!(json, r#"{"type":"refused","reason":"not_allowed"}"#);
631 }
632
633 fn credential_frame(servers: Vec<PairedServer>) -> PhoneFrame {
635 use ed25519_dalek::{Signer, SigningKey};
636 let root = SigningKey::from_bytes(&[7; 32]);
637 let device = SigningKey::from_bytes(&[9; 32]);
638 let credential = UserDeviceCredential::new(
639 PortableUserId::from_bytes(root.verifying_key().to_bytes()).unwrap(),
640 DevicePublicKey::from_bytes(device.verifying_key().to_bytes()).unwrap(),
641 1,
642 1_791_504_000,
643 1_791_504_000 + 3600,
644 |m| root.sign(m),
645 );
646 PhoneFrame::Credential {
647 credential: Box::new(credential),
648 state: None,
649 servers,
650 }
651 }
652
653 fn home() -> PairedServer {
654 PairedServer {
655 endpoint_id: "ab".repeat(32),
656 server_id: "q7k3mpa9trdwf2h".into(),
657 name: "Home Media".into(),
658 addrs: vec![
659 "192.168.1.10:7420".parse().unwrap(),
660 "[2001:db8::1]:7420".parse().unwrap(),
661 ],
662 relays: vec!["https://relay.example.org/".into()],
663 }
664 }
665
666 #[test]
669 fn a_credential_frame_carries_its_servers() {
670 let frame = credential_frame(vec![home()]);
671 let read: PhoneFrame =
672 crate::codec::decode(&crate::codec::encode(&frame).unwrap()).unwrap();
673 assert_eq!(read, frame);
674 let json = serde_json::to_value(&frame).unwrap();
675 assert_eq!(json["servers"][0]["addrs"][1], "[2001:db8::1]:7420");
676 }
677
678 #[test]
681 fn a_credential_frame_without_servers_is_refused() {
682 let mut json = serde_json::to_value(credential_frame(vec![home()])).unwrap();
683 json.as_object_mut().unwrap().remove("servers");
684 let error = serde_json::from_value::<PhoneFrame>(json).unwrap_err();
685 assert!(
686 error.to_string().contains("missing field `servers`"),
687 "{error}"
688 );
689 }
690
691 #[test]
692 fn a_paired_server_is_held_to_bounds() {
693 assert_eq!(home().within_bounds(), Some(home()));
694 let loud = PairedServer {
695 endpoint_id: "AB".repeat(32),
696 name: "x".repeat(500),
697 addrs: (0..20)
698 .map(|n| format!("10.0.0.{n}:7420").parse().unwrap())
699 .collect(),
700 relays: vec![
701 "ftp://nope".into(),
702 "https://a.example/".into(),
703 "https://b.example/".into(),
704 "https://c.example/".into(),
705 ],
706 ..home()
707 };
708 let held = loud.within_bounds().unwrap();
709 assert_eq!(held.endpoint_id, "ab".repeat(32));
710 assert_eq!(held.name.chars().count(), crate::MAX_HELLO_TEXT);
711 assert_eq!(held.addrs.len(), MAX_ADDRS);
712 assert_eq!(held.relays, ["https://a.example/", "https://b.example/"]);
713 for bad in [
714 PairedServer {
715 endpoint_id: "not a key".into(),
716 ..home()
717 },
718 PairedServer {
719 server_id: String::new(),
720 ..home()
721 },
722 ] {
723 assert_eq!(bad.within_bounds(), None);
724 }
725 }
726}