Skip to main content

spoolframe_protocol/
federation.rs

1//! Server-to-server federation on `spoolframe/federation/1` (P8-01,
2//! ARCHITECTURE §26–§28): pairing two servers, and replicating what one
3//! shares with the other ([`SyncLibrary`] and the rest, P8-02).
4//!
5//! Experimental ([`crate::experimental::FEDERATION`]): a server serves the
6//! ALPN only while its `experimental { federation = true; }` is on, and
7//! closes it at once otherwise. These messages may change without
8//! [`PROTOCOL_VERSION`] or the client protocol's version moving.
9//!
10//! A server's identity is its endpoint key, which the QUIC handshake
11//! proves. Its [`crate::ServerId`] is a label with no key, which outlives
12//! a rotated key: the server that is dialled pins the pair (endpoint id,
13//! server id). Nothing here is signed; arriving on the connection is the
14//! proof.
15//!
16//! One request per bidirectional stream, as [`crate::codec`] frames it: a
17//! [`PeerRequest`], answered by a [`PeerReply`]. The first is always
18//! [`PeerRequest::Hello`]. An endpoint the server does not know reaches
19//! only `Hello` and [`PeerRequest::RedeemPairing`]; anything else resets
20//! the stream with [`reset::NOT_ALLOWED`] and is counted against it as a
21//! wrong guess at an invite code. A known server id from a new key is
22//! held until an admin confirms the key ([`Standing::KeyHeld`]), and
23//! reaches only `Hello`. Only a live pair reaches replication's requests.
24
25mod assertion;
26mod media;
27mod replication;
28mod subtitles;
29
30pub use assertion::*;
31pub use media::*;
32pub use replication::*;
33pub use subtitles::*;
34
35use std::fmt;
36
37use serde::{Deserialize, Serialize};
38
39/// The version of `spoolframe/federation/1`'s messages this build speaks:
40/// the ALPN versions itself (P8-01, 2026-10-22), apart from the client
41/// protocol's [`crate::PROTOCOL_VERSION`].
42pub const PROTOCOL_VERSION: u32 = 1;
43
44/// The least time between two syncs a pair's [`PeerRequest::SharesChanged`]
45/// sets off: a pair that sends notices without end makes the receiver
46/// sync it at most this often.
47pub const SHARES_CHANGED_EVERY: std::time::Duration = std::time::Duration::from_secs(30);
48
49/// The longest request frame a server reads on this ALPN. A pairing is a
50/// code, a name and some address hints.
51pub const MAX_REQUEST: u32 = 16 << 10;
52
53/// The most address hints, and the most relays, a redemption carries; the
54/// rest are left out, as an invite link's are ([`crate::invite::MAX_HINTS`]).
55pub const MAX_HINTS: usize = crate::invite::MAX_HINTS;
56
57/// Stream reset codes on this ALPN.
58pub mod reset {
59    /// The request is not one this peer may make now: a stranger's
60    /// anything but `Hello` and a redemption, a held key's anything but
61    /// `Hello`, or any request before `Hello`.
62    pub const NOT_ALLOWED: u32 = 1;
63    /// The request did not arrive in time, or did not decode.
64    pub const BAD_REQUEST: u32 = 2;
65    /// The connection has as many streams open as it may: wait for one
66    /// to end, and ask again.
67    pub const BUSY: u32 = 3;
68    /// The asker took none of the reply within its own wait for it: the
69    /// reply is given up on, and what was not read is lost.
70    pub const STALLED: u32 = 4;
71}
72
73/// The first request on every connection: who the dialling server says it
74/// is. Its endpoint is proved by the connection; its server id is checked
75/// against the pin for that endpoint.
76#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
77pub struct PeerHello {
78    /// [`PROTOCOL_VERSION`] of the dialling server.
79    pub protocol_version: u32,
80    /// Its [`crate::ServerId`], as written.
81    pub server_id: String,
82    /// What it calls itself (`name`): shown to the other's admins. Cut to
83    /// [`crate::MAX_HELLO_TEXT`] characters.
84    pub name: String,
85}
86
87impl PeerHello {
88    /// This `PeerHello` with its name cut to [`crate::MAX_HELLO_TEXT`]
89    /// characters: what a server keeps of it.
90    pub fn within_bounds(mut self) -> Self {
91        self.name = server_name(self.name);
92        self
93    }
94}
95
96/// Whether `request` names a paired server's item, library or image
97/// anywhere, in any field (a `fed:` id, P8-02): what a server refuses from
98/// a client that did not name the experimental `federation` feature, at
99/// one boundary rather than in each request's handler (L1). A
100/// [`crate::Request`], or a resource's request, as an image's is
101/// (F8-11). Text that only starts like one, a search's or a name, is not
102/// an id.
103pub fn names_federated<T: Serialize + ?Sized>(request: &T) -> bool {
104    fn names(value: &ciborium::Value) -> bool {
105        match value {
106            ciborium::Value::Text(text) => federated_id(text),
107            ciborium::Value::Array(values) => values.iter().any(names),
108            ciborium::Value::Map(entries) => entries.iter().any(|(k, v)| names(k) || names(v)),
109            ciborium::Value::Tag(_, value) => names(value),
110            _ => false,
111        }
112    }
113    ciborium::Value::serialized(request).is_ok_and(|value| names(&value))
114}
115
116/// Whether `text` is a `fed:` id of an item, a library or an image.
117pub fn federated_id(text: &str) -> bool {
118    use spoolframe_types::{ArtworkId, LibraryId, MediaId};
119    text.starts_with("fed:")
120        && (text
121            .parse::<MediaId>()
122            .is_ok_and(|id| id.remote().is_some())
123            || text
124                .parse::<LibraryId>()
125                .is_ok_and(|id| id.remote().is_some())
126            || text
127                .parse::<ArtworkId>()
128                .is_ok_and(|id| id.remote().is_some()))
129}
130
131/// A server's `name` cut to [`crate::MAX_HELLO_TEXT`] characters, as a
132/// [`PeerHello`]'s is: what a server keeps of another's name, from
133/// wherever it came. Control characters go first (M8-03): the name is
134/// logged, and a newline in it would forge a line of the log.
135pub fn server_name(mut name: String) -> String {
136    name.retain(|c| !c.is_control());
137    crate::messages::cut(&mut name);
138    name
139}
140
141/// The answer to [`PeerHello`]: the server dialled, and what the dialling
142/// one is to it.
143#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
144pub struct PeerInfo {
145    /// [`PROTOCOL_VERSION`] of the server dialled.
146    pub protocol_version: u32,
147    pub server_id: String,
148    pub name: String,
149    pub standing: Standing,
150}
151
152/// What the dialling server is to the one it dialled.
153#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
154#[serde(rename_all = "snake_case")]
155pub enum Standing {
156    /// No pair: it may redeem a pairing invite, and nothing else.
157    Stranger,
158    /// Paired: this endpoint and server id are pinned.
159    Paired,
160    /// Its server id is paired with another key. The new key waits for
161    /// the other's admin to confirm it, and reaches only `Hello` until
162    /// then.
163    KeyHeld,
164    /// A standing this build does not know.
165    #[serde(other)]
166    Unknown,
167}
168
169/// Pair with the server dialled by redeeming its `federation` invite.
170#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
171pub struct RedeemPairing {
172    /// The invite's code, as its link carries it; any case, dashes or
173    /// spaces are taken.
174    pub code: String,
175    /// Addresses the dialling server may be reached at, as `ip:port`, so
176    /// the other can dial it back (to say it unpaired). Hints: at most
177    /// [`MAX_HINTS`] are kept, and one that does not read is left out.
178    #[serde(default)]
179    pub addrs: Vec<String>,
180    /// URLs of relays it may be reached through; hints, as `addrs`.
181    #[serde(default)]
182    pub relays: Vec<String>,
183}
184
185impl fmt::Debug for RedeemPairing {
186    // The code pairs a server until it is used up: keep it out of logs.
187    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
188        f.debug_struct("RedeemPairing")
189            .field("code", &"<redacted>")
190            .field("addrs", &self.addrs)
191            .field("relays", &self.relays)
192            .finish()
193    }
194}
195
196/// The pair is made: the dialled server pinned the dialling one, and
197/// says who it is so the other can write its own row.
198#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
199pub struct Paired {
200    pub server_id: String,
201    pub name: String,
202}
203
204/// Why no pair was made, or a peer was turned away.
205#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
206#[serde(tag = "type", rename_all = "snake_case")]
207pub enum PairingRefused {
208    /// No invite has this code, or it was revoked: counted as a wrong
209    /// guess.
210    InviteInvalid,
211    InviteExpired,
212    /// Every use it had is used.
213    InviteExhausted,
214    /// The code is a live invite's of another kind (an account's, a
215    /// portable user's).
216    WrongInviteKind,
217    /// Too many wrong codes, or too many strangers asking: try again in
218    /// `retry_after_secs`.
219    RateLimited {
220        retry_after_secs: u64,
221    },
222    /// This endpoint, or this server id, is paired already.
223    AlreadyPaired,
224    /// This endpoint is paired under another server id: refused every
225    /// time, and the connection is closed with
226    /// [`crate::close::SERVER_ID_CHANGED`].
227    ServerIdChanged,
228    /// The hello's server id is the dialled server's own: a server never
229    /// pairs with itself, or with one that copied its id.
230    SameServerId,
231    /// A new key for a paired server id that is not held: its admin
232    /// rejected it within the day, or as many new keys as are held for
233    /// that server wait already.
234    KeyRefused,
235    /// The other server holds this one's new key until its admin
236    /// confirms it: what a server tells its own admin (`PairServer`),
237    /// never sent on the ALPN, where the standing says it.
238    KeyHeld,
239    /// A reason this build does not know.
240    #[serde(other)]
241    Unknown,
242}
243
244impl PairingRefused {
245    /// Its name on the wire, the `type` tag: what the admin API's
246    /// `PAIRING_REFUSED` carries as `data.reason`, and the web UI matches.
247    pub fn name(self) -> &'static str {
248        match self {
249            PairingRefused::InviteInvalid => "invite_invalid",
250            PairingRefused::InviteExpired => "invite_expired",
251            PairingRefused::InviteExhausted => "invite_exhausted",
252            PairingRefused::WrongInviteKind => "wrong_invite_kind",
253            PairingRefused::RateLimited { .. } => "rate_limited",
254            PairingRefused::AlreadyPaired => "already_paired",
255            PairingRefused::ServerIdChanged => "server_id_changed",
256            PairingRefused::SameServerId => "same_server_id",
257            PairingRefused::KeyRefused => "key_refused",
258            PairingRefused::KeyHeld => "key_held",
259            PairingRefused::Unknown => "unknown",
260        }
261    }
262}
263
264impl fmt::Display for PairingRefused {
265    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
266        match self {
267            PairingRefused::InviteInvalid => f.write_str("that invite code is not valid"),
268            PairingRefused::InviteExpired => f.write_str("the invite has expired"),
269            PairingRefused::InviteExhausted => f.write_str("the invite has been used up"),
270            PairingRefused::WrongInviteKind => {
271                f.write_str("that invite is not one to pair a server with")
272            }
273            PairingRefused::RateLimited { retry_after_secs } => {
274                write!(f, "too many attempts; try again in {retry_after_secs} s")
275            }
276            PairingRefused::AlreadyPaired => f.write_str("the servers are paired already"),
277            PairingRefused::ServerIdChanged => {
278                f.write_str("this server is paired under another server id")
279            }
280            PairingRefused::SameServerId => f.write_str("that server id is this server's own"),
281            PairingRefused::KeyRefused => {
282                f.write_str("that new key for a paired server is not held for its admin")
283            }
284            PairingRefused::KeyHeld => f.write_str(
285                "the other server holds this server's new key until its admin confirms it",
286            ),
287            PairingRefused::Unknown => f.write_str("refused for a reason this build does not know"),
288        }
289    }
290}
291
292/// The server sending it no longer pairs with the one it is sent to:
293/// that one revokes its own row too. Best effort: a server that is not
294/// told keeps its row until its admin revokes it.
295#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
296pub struct Unpaired {}
297
298/// An admin's `PairServer` (client protocol, P8-01): the other server's
299/// `federation` invite link, with its code.
300#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
301pub struct PairServer {
302    pub link: String,
303}
304
305impl fmt::Debug for PairServer {
306    // The link carries the code: keep it out of logs.
307    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
308        f.write_str("PairServer { link: <redacted> }")
309    }
310}
311
312/// The most libraries one `ShareLibraries` names; the rest are left out.
313pub const MAX_SHARED: usize = 64;
314
315/// An admin's `ShareLibraries` (client protocol, P8-03): share libraries
316/// of this server with a paired one, as the QR flow offers once the pair
317/// is made. Every user of the paired server may browse and watch them.
318#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
319pub struct ShareLibraries {
320    /// The paired server's [`crate::ServerId`], as `ServerPaired` gave it.
321    pub server_id: String,
322    /// At most [`MAX_SHARED`]; the rest are left out.
323    pub libraries: Vec<spoolframe_types::LibraryId>,
324}
325
326impl ShareLibraries {
327    /// This request with at most [`MAX_SHARED`] libraries: what a server
328    /// reads of it.
329    pub fn within_bounds(mut self) -> Self {
330        self.libraries.truncate(MAX_SHARED);
331        self
332    }
333}
334
335/// A server paired by `PairServer` (client protocol, P8-01), as the app
336/// shows it.
337#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
338pub struct PeerServer {
339    /// What it calls itself.
340    pub name: String,
341    pub server_id: String,
342    /// Its `EndpointId`, hex: the key pinned.
343    pub endpoint_id: String,
344    /// The key's fingerprint, as the other server's admin sees it.
345    pub fingerprint: String,
346}
347
348/// A request on `spoolframe/federation/1`.
349#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
350#[serde(tag = "type", rename_all = "snake_case")]
351pub enum PeerRequest {
352    /// The first request on every connection: `Info`.
353    Hello(PeerHello),
354    /// A stranger's only other request: `Paired`, or `Refused`.
355    RedeemPairing(RedeemPairing),
356    /// A paired server unpaired: `Done`, then the connection is closed
357    /// with [`crate::close::UNPAIRED`].
358    Unpaired(Unpaired),
359    /// A pair's: the libraries shared with it now (P8-02): `Libraries`.
360    Libraries,
361    /// A pair's: what the sender shares with the server it is sent to
362    /// changed (a grant added or revoked), so that one syncs the sender
363    /// soon rather than at its next interval. It carries nothing: the
364    /// receiver asks `Libraries` and `Sync` as ever, at most once per
365    /// [`SHARES_CHANGED_EVERY`] per pair, a notice within it waiting
366    /// for its end and coalesced with any others. `Done`. Sent best
367    /// effort, on the connection the sender holds to the pair: a pair
368    /// not connected is not told, and syncs on connecting. A server that
369    /// does not know it resets the stream `NOT_ALLOWED`, which changes
370    /// nothing.
371    SharesChanged,
372    /// A pair's: one shared library's changes (P8-02): `Page`s on the
373    /// same stream, the last with `more: false`; `NotShared` for a
374    /// library that is not shared with it, `Unavailable` when it cannot
375    /// be walked now.
376    Sync(SyncLibrary),
377    /// A pair's: one image of an item in a library shared with it
378    /// (P8-02): `Artwork`, `NotShared` or `NotFound`, written as a reply
379    /// ([`crate::codec::write_reply`]), not a frame.
380    Artwork(ArtworkFetch),
381    /// A pair's: it vouches for one of its users, who wants an item of
382    /// this server's (P8-03): `Token`, or `AssertionRefused`.
383    AssertUser(AssertUser),
384    /// A pair's: one of its users searches subtitles for an item of this
385    /// server's (P8-07): `SubtitleResults`, or `Failed`.
386    SearchSubtitles(SubtitleSearchAsk),
387    /// A pair's: one of its users downloads a result (P8-07), counted
388    /// under the pair: `SubtitleDownloaded`, or `Failed`.
389    DownloadSubtitle(SubtitleDownloadAsk),
390    /// A pair's: one of its users removes a downloaded subtitle (P8-07):
391    /// `Done`, or `Failed`.
392    RemoveSubtitleDownload(SubtitleRemovalAsk),
393    /// A request this build does not know: not allowed.
394    #[serde(other)]
395    Unknown,
396}
397
398/// The answer to a [`PeerRequest`].
399#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
400#[serde(tag = "type", rename_all = "snake_case")]
401pub enum PeerReply {
402    Info(PeerInfo),
403    Paired(Paired),
404    Refused {
405        reason: PairingRefused,
406    },
407    Done,
408    /// The libraries shared with the pair, at most
409    /// [`MAX_SHARED_LIBRARIES`].
410    Libraries {
411        libraries: Vec<SharedLibrary>,
412    },
413    /// A page of a [`SyncLibrary`]'s answer.
414    Page(SyncPage),
415    /// An image: at most [`MAX_ARTWORK_BYTES`].
416    Artwork {
417        /// Its media type, as `image/jpeg`.
418        content_type: String,
419        #[serde(with = "serde_bytes")]
420        bytes: Vec<u8>,
421    },
422    /// The library, or the item the image is of, is not shared with the
423    /// pair (now, or any more): a cache of it goes.
424    NotShared,
425    /// Shared, but the item or image is not there now.
426    NotFound,
427    /// The sharing server cannot answer now (its catalog is down): the
428    /// asker keeps what it has and asks again later.
429    Unavailable,
430    /// The token for an [`AssertUser`] (P8-03).
431    Token(TokenGranted),
432    /// No token for an [`AssertUser`], and why.
433    AssertionRefused {
434        reason: AssertionRefused,
435    },
436    /// A subtitle search's results (P8-07).
437    SubtitleResults {
438        search: spoolframe_types::SubtitleSearch,
439    },
440    /// A subtitle downloaded (P8-07).
441    SubtitleDownloaded {
442        downloaded: spoolframe_types::SubtitleDownloaded,
443    },
444    /// A subtitle ask refused (P8-07), as the client protocol would refuse
445    /// it: SB passes it on to its device as it is.
446    Failed {
447        error: crate::Error,
448    },
449    /// A reply this build does not know.
450    #[serde(other)]
451    Unknown,
452}
453
454#[cfg(test)]
455mod tests {
456    use super::*;
457    use crate::codec;
458
459    fn round_trip<T>(value: T)
460    where
461        T: Serialize + serde::de::DeserializeOwned + PartialEq + fmt::Debug,
462    {
463        let bytes = codec::encode(&value).unwrap();
464        assert_eq!(codec::decode::<T>(&bytes).unwrap(), value);
465    }
466
467    /// A request naming a paired server's item anywhere names one; a
468    /// search for text that only starts like an id does not.
469    #[test]
470    fn a_fed_id_is_found_in_any_field_of_a_request() {
471        let alien: spoolframe_types::MediaId = "fed:movie:mzxw6ytbojtg633c:plex:1".parse().unwrap();
472        assert!(names_federated(&crate::Request::Item { id: alien.clone() }));
473        assert!(names_federated(&crate::Request::UpdateWatchProgress {
474            id: alien,
475            position_ms: 0,
476        }));
477        assert!(!names_federated(&crate::Request::Item {
478            id: "plex:movie:1".parse().unwrap(),
479        }));
480        assert!(!names_federated(&crate::Request::SetServerRow {
481            server_id: "fed:nothing".into(),
482            shown: true,
483        }));
484    }
485
486    fn hello() -> PeerHello {
487        PeerHello {
488            protocol_version: PROTOCOL_VERSION,
489            server_id: "mzxw6ytbojtg633c".into(),
490            name: "Bob's server".into(),
491        }
492    }
493
494    #[test]
495    fn every_request_goes_both_ways() {
496        round_trip(PeerRequest::Hello(hello()));
497        round_trip(PeerRequest::RedeemPairing(RedeemPairing {
498            code: "QW7K-2MFP-XR4T".into(),
499            addrs: vec!["203.0.113.7:7420".into()],
500            relays: vec!["https://relay.example.org".into()],
501        }));
502        round_trip(PeerRequest::Unpaired(Unpaired {}));
503    }
504
505    fn item() -> RemoteItem {
506        RemoteItem {
507            id: "plex:track:33".into(),
508            kind: RemoteKind::Track,
509            title: "Digital Love".into(),
510            parent: Some("plex:album:31".into()),
511            grandparent: Some("plex:artist:30".into()),
512            parent_title: Some("Discovery".into()),
513            grandparent_title: Some("Daft Punk".into()),
514            index: Some(3),
515            parent_index: Some(1),
516            year: Some(2001),
517            date: Some("2001-03-12".into()),
518            summary: None,
519            content_rating: None,
520            duration_ms: Some(301_000),
521            count: Some(14),
522            genres: vec!["Electronic".into()],
523            artwork: vec![RemoteArtwork {
524                id: "plex:/library/metadata/31/thumb/9".into(),
525                kind: RemoteArtworkKind::Poster,
526            }],
527            external_ids: vec!["mbid://5e4b7b2c".into()],
528            sort_title: None,
529            released: None,
530            added_at: None,
531            rating_tenths: None,
532            audience_rating_tenths: None,
533            size: None,
534            resolution: None,
535            dynamic_range: None,
536            hash: String::new(),
537        }
538        .hashed()
539    }
540
541    /// P8-02's requests and replies, through CBOR and back.
542    #[test]
543    fn replication_goes_both_ways() {
544        round_trip(PeerRequest::Libraries);
545        round_trip(PeerRequest::SharesChanged);
546        round_trip(PeerRequest::Sync(SyncLibrary {
547            library: "plex:2".into(),
548            since: None,
549        }));
550        round_trip(PeerRequest::Sync(SyncLibrary {
551            library: "plex:2".into(),
552            since: Some("0192f1c4".into()),
553        }));
554        round_trip(PeerRequest::Artwork(ArtworkFetch {
555            id: "plex:/library/metadata/31/thumb/9".into(),
556        }));
557        round_trip(PeerReply::Libraries {
558            libraries: vec![SharedLibrary {
559                id: "plex:2".into(),
560                title: "Music".into(),
561                kind: RemoteLibraryKind::Music,
562            }],
563        });
564        for mode in [SyncMode::Changes, SyncMode::Snapshot] {
565            round_trip(PeerReply::Page(SyncPage {
566                mode,
567                cursor: "0192f1c4".into(),
568                items: vec![item()],
569                removed: vec!["plex:track:32".into()],
570                more: true,
571            }));
572        }
573        round_trip(PeerReply::Artwork {
574            content_type: "image/png".into(),
575            bytes: vec![0x89, b'P', b'N', b'G'],
576        });
577        round_trip(PeerReply::NotShared);
578        round_trip(PeerReply::NotFound);
579        round_trip(PeerReply::Unavailable);
580    }
581
582    /// The hash is of the content: it moves when the item does, not when
583    /// the hash field itself is set.
584    #[test]
585    fn an_item_s_hash_follows_its_content() {
586        let a = item();
587        assert_eq!(a.digest(), a.hash);
588        assert_eq!(a.clone().hashed(), a);
589        let renamed = RemoteItem {
590            title: "Something About Us".into(),
591            ..a.clone()
592        };
593        assert_ne!(renamed.digest(), a.hash);
594    }
595
596    /// What a library is sorted and filtered by is sent only when there
597    /// is some: an item without it encodes with the fields it had before
598    /// them, so its hash is as an older server makes it and nothing is
599    /// sent again for them alone; one with them crosses whole.
600    #[test]
601    fn the_browse_facts_are_sent_only_when_known() {
602        let bytes = crate::codec::encode(&item()).unwrap();
603        let value: ciborium::Value = ciborium::from_reader(bytes.as_slice()).unwrap();
604        let keys: Vec<String> = value
605            .as_map()
606            .unwrap()
607            .iter()
608            .filter_map(|(k, _)| k.as_text().map(str::to_owned))
609            .collect();
610        assert_eq!(
611            keys,
612            [
613                "id",
614                "kind",
615                "title",
616                "parent",
617                "grandparent",
618                "parent_title",
619                "grandparent_title",
620                "index",
621                "parent_index",
622                "year",
623                "date",
624                "summary",
625                "content_rating",
626                "duration_ms",
627                "count",
628                "genres",
629                "artwork",
630                "external_ids",
631                "hash",
632            ]
633        );
634        let known = RemoteItem {
635            sort_title: Some("Something".into()),
636            released: Some("2001-03-12".into()),
637            added_at: Some(1_700_000_000),
638            rating_tenths: Some(87),
639            audience_rating_tenths: Some(91),
640            size: Some(30 << 30),
641            resolution: Some(spoolframe_types::Resolution::FullHd),
642            dynamic_range: Some(spoolframe_types::DynamicRange::DolbyVision),
643            ..item()
644        }
645        .hashed();
646        assert_ne!(known.hash, item().hash);
647        round_trip(PeerReply::Page(SyncPage {
648            mode: SyncMode::Snapshot,
649            cursor: "c".into(),
650            items: vec![known],
651            removed: Vec::new(),
652            more: false,
653        }));
654    }
655
656    /// A page past the bounds is cut to them as it is read: items,
657    /// removed ids, and each item's lists and texts.
658    #[test]
659    fn a_page_is_cut_to_its_bounds() {
660        let long = RemoteItem {
661            title: "x".repeat(MAX_ITEM_TEXT + 10),
662            summary: Some("y".repeat(MAX_ITEM_SUMMARY + 10)),
663            genres: vec!["g".into(); MAX_ITEM_GENRES + 1],
664            artwork: vec![item().artwork[0].clone(); MAX_ITEM_ARTWORK + 1],
665            external_ids: vec!["tmdb://1".into(); MAX_ITEM_EXTERNAL_IDS + 1],
666            ..item()
667        };
668        let page = SyncPage {
669            mode: SyncMode::Snapshot,
670            cursor: "c".into(),
671            items: vec![long; MAX_PAGE_ITEMS + 1],
672            removed: vec!["plex:movie:1".into(); MAX_PAGE_REMOVED + 1],
673            more: false,
674        }
675        .within_bounds();
676        assert_eq!(page.items.len(), MAX_PAGE_ITEMS);
677        assert_eq!(page.removed.len(), MAX_PAGE_REMOVED);
678        let item = &page.items[0];
679        assert_eq!(item.title.chars().count(), MAX_ITEM_TEXT);
680        assert_eq!(
681            item.summary.as_ref().unwrap().chars().count(),
682            MAX_ITEM_SUMMARY
683        );
684        assert_eq!(item.genres.len(), MAX_ITEM_GENRES);
685        assert_eq!(item.artwork.len(), MAX_ITEM_ARTWORK);
686        assert_eq!(item.external_ids.len(), MAX_ITEM_EXTERNAL_IDS);
687        let listed = libraries_within_bounds(vec![
688            SharedLibrary {
689                id: "plex:1".into(),
690                title: "Movies".into(),
691                kind: RemoteLibraryKind::Movies,
692            };
693            MAX_SHARED_LIBRARIES + 1
694        ]);
695        assert_eq!(listed.len(), MAX_SHARED_LIBRARIES);
696    }
697
698    /// What a newer sharing server adds reads as `Unknown`, item by item,
699    /// never failing the page: an item kind, an artwork role, a library
700    /// kind, a sync mode.
701    #[test]
702    fn what_a_newer_server_replicates_reads_as_unknown() {
703        let decode = |value: serde_json::Value| codec::encode(&value).unwrap();
704        let page = serde_json::json!({
705            "type": "page",
706            "mode": "patch",
707            "cursor": "c",
708            "items": [{
709                "id": "plex:clip:1",
710                "kind": "clip",
711                "title": "Trailer",
712                "artwork": [{ "id": "a", "kind": "banner" }],
713                "hash": "h",
714                "rating": 7,
715            }],
716            "more": false,
717        });
718        let PeerReply::Page(page) = codec::decode::<PeerReply>(&decode(page)).unwrap() else {
719            panic!("not a page");
720        };
721        assert_eq!(page.mode, SyncMode::Unknown);
722        assert_eq!(page.items[0].kind, RemoteKind::Unknown);
723        assert_eq!(page.items[0].artwork[0].kind, RemoteArtworkKind::Unknown);
724        let libraries = serde_json::json!({
725            "type": "libraries",
726            "libraries": [{ "id": "plex:4", "title": "Photos", "kind": "photos" }],
727        });
728        let PeerReply::Libraries { libraries } =
729            codec::decode::<PeerReply>(&decode(libraries)).unwrap()
730        else {
731            panic!("not libraries");
732        };
733        assert_eq!(libraries[0].kind, RemoteLibraryKind::Unknown);
734    }
735
736    #[test]
737    fn every_reply_goes_both_ways() {
738        for standing in [Standing::Stranger, Standing::Paired, Standing::KeyHeld] {
739            round_trip(PeerReply::Info(PeerInfo {
740                protocol_version: PROTOCOL_VERSION,
741                server_id: "mzxw6ytbojtg633c".into(),
742                name: "Alice's server".into(),
743                standing,
744            }));
745        }
746        round_trip(PeerReply::Paired(Paired {
747            server_id: "mzxw6ytbojtg633c".into(),
748            name: "Alice's server".into(),
749        }));
750        for reason in [
751            PairingRefused::InviteInvalid,
752            PairingRefused::InviteExpired,
753            PairingRefused::InviteExhausted,
754            PairingRefused::WrongInviteKind,
755            PairingRefused::RateLimited {
756                retry_after_secs: 30,
757            },
758            PairingRefused::AlreadyPaired,
759            PairingRefused::ServerIdChanged,
760            PairingRefused::SameServerId,
761            PairingRefused::KeyRefused,
762            PairingRefused::KeyHeld,
763        ] {
764            round_trip(PeerReply::Refused { reason });
765        }
766        round_trip(PeerReply::Done);
767    }
768
769    /// `name()` is the serde tag, for every reason.
770    #[test]
771    fn a_refusal_s_name_is_its_tag() {
772        for reason in [
773            PairingRefused::InviteInvalid,
774            PairingRefused::InviteExpired,
775            PairingRefused::InviteExhausted,
776            PairingRefused::WrongInviteKind,
777            PairingRefused::RateLimited {
778                retry_after_secs: 30,
779            },
780            PairingRefused::AlreadyPaired,
781            PairingRefused::ServerIdChanged,
782            PairingRefused::SameServerId,
783            PairingRefused::KeyRefused,
784            PairingRefused::KeyHeld,
785            PairingRefused::Unknown,
786        ] {
787            let json = serde_json::to_value(reason).unwrap();
788            assert_eq!(json["type"], reason.name(), "{reason:?}");
789        }
790    }
791
792    /// What a newer server adds reads as `Unknown`, never as a decode
793    /// failure: a request (which the server then does not allow), a
794    /// reply, a standing and a refusal.
795    #[test]
796    fn what_a_newer_server_sends_reads_as_unknown() {
797        let decode = |value: serde_json::Value| codec::encode(&value).unwrap();
798        assert_eq!(
799            codec::decode::<PeerRequest>(&decode(serde_json::json!({ "type": "share_library" })))
800                .unwrap(),
801            PeerRequest::Unknown
802        );
803        assert_eq!(
804            codec::decode::<PeerReply>(&decode(serde_json::json!({ "type": "catalog" }))).unwrap(),
805            PeerReply::Unknown
806        );
807        let info = serde_json::json!({
808            "type": "info",
809            "protocol_version": 2,
810            "server_id": "mzxw6ytbojtg633c",
811            "name": "Alice's server",
812            "standing": "neighbour",
813            "libraries": 3,
814        });
815        let PeerReply::Info(info) = codec::decode::<PeerReply>(&decode(info)).unwrap() else {
816            panic!("not info");
817        };
818        assert_eq!(info.standing, Standing::Unknown);
819        let refused = serde_json::json!({ "type": "refused", "reason": { "type": "busy" } });
820        assert_eq!(
821            codec::decode::<PeerReply>(&decode(refused)).unwrap(),
822            PeerReply::Refused {
823                reason: PairingRefused::Unknown
824            }
825        );
826    }
827
828    /// A grant's notice is a tag and nothing else: what an older server
829    /// reads as a request it does not know, and refuses.
830    #[test]
831    fn a_notice_of_shares_changed_is_its_tag_alone() {
832        let wire = codec::encode(&serde_json::json!({ "type": "shares_changed" })).unwrap();
833        assert_eq!(
834            codec::decode::<PeerRequest>(&wire).unwrap(),
835            PeerRequest::SharesChanged
836        );
837        assert_eq!(codec::encode(&PeerRequest::SharesChanged).unwrap(), wire);
838    }
839
840    /// A redemption from a server that sends no hints reads as one with
841    /// none.
842    #[test]
843    fn a_redemption_without_hints_has_none() {
844        let sent = serde_json::json!({ "type": "redeem_pairing", "code": "QW7K2MFPXR4T" });
845        let PeerRequest::RedeemPairing(redeem) =
846            codec::decode(&codec::encode(&sent).unwrap()).unwrap()
847        else {
848            panic!("not a redemption");
849        };
850        assert!(redeem.addrs.is_empty() && redeem.relays.is_empty());
851    }
852
853    /// The client protocol's request and reply (P8-01).
854    #[test]
855    fn pairing_from_an_app_goes_both_ways_and_keeps_the_link_out_of_debug() {
856        use crate::{Error, Reply, Request, Response};
857        let request = Request::PairServer(PairServer {
858            link: "spoolframe://invite?server=x&kind=federation&cap=QW7K-2MFP-XR4T".into(),
859        });
860        round_trip(request.clone());
861        assert!(!format!("{request:?}").contains("QW7K"));
862        round_trip(Response::Ok(Reply::ServerPaired {
863            server: PeerServer {
864                name: "Alice's server".into(),
865                server_id: "mzxw6ytbojtg633c".into(),
866                endpoint_id: "ab".repeat(32),
867                fingerprint: "PGJA-BHZ1-F68M-DFSE".into(),
868            },
869        }));
870        round_trip(Response::Err(Error::PairingRefused {
871            reason: PairingRefused::AlreadyPaired,
872        }));
873    }
874
875    /// The client protocol's share request and reply (P8-03), and its
876    /// bound.
877    #[test]
878    fn sharing_from_an_app_goes_both_ways_and_is_bounded() {
879        use crate::{Reply, Request, Response};
880        let library: spoolframe_types::LibraryId = "plex:1".parse().unwrap();
881        let share = ShareLibraries {
882            server_id: "mzxw6ytbojtg633c".into(),
883            libraries: vec![library.clone(); MAX_SHARED + 3],
884        };
885        round_trip(Request::ShareLibraries(share.clone()));
886        round_trip(Response::Ok(Reply::LibrariesShared {
887            libraries: vec![library],
888        }));
889        assert_eq!(share.within_bounds().libraries.len(), MAX_SHARED);
890    }
891
892    /// P8-02's client exposure: a library's server, Home's server rows
893    /// and items no longer available, the row setting and the event. What
894    /// is empty is left out, so a reply to an app that does not name the
895    /// feature reads as before.
896    #[test]
897    fn client_exposure_goes_both_ways_and_is_left_out_when_empty() {
898        use crate::{Event, HomeScreen, Reply, Request, Response, ServerRow};
899        use spoolframe_types::{Library, LibraryKind, LibraryServer};
900        let server = LibraryServer {
901            server_id: "mzxw6ytbojtg633c".into(),
902            name: "Alice's server".into(),
903            online: false,
904        };
905        let shared = Library {
906            id: "fed:mzxw6ytbojtg633c:plex:1".parse().unwrap(),
907            title: "Movies".into(),
908            kind: LibraryKind::Movies,
909            server: Some(server.clone()),
910        };
911        round_trip(Response::Ok(Reply::Libraries {
912            libraries: vec![shared],
913        }));
914        round_trip(Response::Ok(Reply::Home(HomeScreen {
915            unavailable: vec!["fed:movie:mzxw6ytbojtg633c:plex:1".parse().unwrap()],
916            servers: vec![ServerRow {
917                server,
918                shown: false,
919                items: Vec::new(),
920            }],
921            ..HomeScreen::default()
922        })));
923        round_trip(Request::SetServerRow {
924            server_id: "mzxw6ytbojtg633c".into(),
925            shown: true,
926        });
927        round_trip(Event::LibrariesChanged);
928        // P8-03: progress by item, and history's items no longer available.
929        let alien: spoolframe_types::MediaId = "fed:movie:mzxw6ytbojtg633c:plex:1".parse().unwrap();
930        round_trip(Request::UpdateWatchProgress {
931            id: alien.clone(),
932            position_ms: 2_400_000,
933        });
934        round_trip(Response::Ok(Reply::Items {
935            items: Vec::new(),
936            total: 1,
937            unavailable: vec![alien],
938        }));
939        let items = serde_json::to_value(Reply::Items {
940            items: Vec::new(),
941            total: 0,
942            unavailable: Vec::new(),
943        })
944        .unwrap();
945        assert!(items.get("unavailable").is_none(), "{items}");
946        let own = Library {
947            id: "plex:1".parse().unwrap(),
948            title: "Movies".into(),
949            kind: LibraryKind::Movies,
950            server: None,
951        };
952        let json = serde_json::to_value(&own).unwrap();
953        assert!(json.get("server").is_none(), "{json}");
954        let home = serde_json::to_value(HomeScreen::default()).unwrap();
955        assert!(home.get("servers").is_none() && home.get("unavailable").is_none());
956        assert_eq!(serde_json::from_value::<Library>(json).unwrap(), own);
957    }
958
959    #[test]
960    fn the_code_stays_out_of_debug_output() {
961        let redeem = RedeemPairing {
962            code: "QW7K-2MFP-XR4T".into(),
963            addrs: Vec::new(),
964            relays: Vec::new(),
965        };
966        assert!(!format!("{redeem:?}").contains("QW7K"));
967    }
968
969    /// P8-03's assertion and its answers, through CBOR and back; a scope
970    /// left out is a play, a newer one reads as unknown, and the token
971    /// stays out of debug output.
972    #[test]
973    fn an_assertion_goes_both_ways() {
974        let assertion = AssertUser {
975            user: "0192f1c4-5b6e-7a3d-9c41-2e8f7b6a5d4c".into(),
976            display_name: "Bob".into(),
977            client_endpoint: "ab".repeat(32),
978            item: "plex:movie:1".into(),
979            scope: TokenScope::Play,
980            preferences: None,
981            download: None,
982        };
983        round_trip(PeerRequest::AssertUser(assertion.clone()));
984        // P8-04: the user's track preferences go with it when SB has them.
985        let mut preferences = spoolframe_types::TrackPreferences::default();
986        preferences.audio.languages = vec!["fra".into()];
987        round_trip(PeerRequest::AssertUser(AssertUser {
988            preferences: Some(preferences),
989            ..assertion.clone()
990        }));
991        let granted = TokenGranted {
992            token: "f00d".repeat(16),
993            scope: TokenScope::Play,
994            expires_at: 1_791_000_300,
995        };
996        assert!(!format!("{granted:?}").contains("f00d"));
997        round_trip(PeerReply::Token(granted));
998        for reason in [
999            AssertionRefused::NotShared,
1000            AssertionRefused::InvalidUser,
1001            AssertionRefused::InvalidDevice,
1002            AssertionRefused::InvalidScope,
1003            AssertionRefused::Unavailable,
1004        ] {
1005            round_trip(PeerReply::AssertionRefused { reason });
1006        }
1007        let decode = |value: serde_json::Value| codec::encode(&value).unwrap();
1008        let sent = serde_json::json!({
1009            "type": "assert_user",
1010            "user": assertion.user,
1011            "display_name": "Bob",
1012            "client_endpoint": assertion.client_endpoint,
1013            "item": "plex:movie:1",
1014        });
1015        assert_eq!(
1016            codec::decode::<PeerRequest>(&decode(sent)).unwrap(),
1017            PeerRequest::AssertUser(assertion.clone())
1018        );
1019        let later = serde_json::json!({
1020            "type": "assert_user",
1021            "user": assertion.user,
1022            "display_name": "Bob",
1023            "client_endpoint": assertion.client_endpoint,
1024            "item": "plex:movie:1",
1025            "scope": "subtitles",
1026        });
1027        let PeerRequest::AssertUser(later) = codec::decode(&decode(later)).unwrap() else {
1028            panic!("not an assertion");
1029        };
1030        assert_eq!(later.scope, TokenScope::Unknown);
1031        let long = AssertUser {
1032            display_name: "x".repeat(500),
1033            ..assertion
1034        };
1035        assert_eq!(
1036            long.within_bounds().display_name.chars().count(),
1037            crate::MAX_HELLO_TEXT
1038        );
1039    }
1040
1041    /// P8-07: a download token's assertion, its grant, and the device a
1042    /// download is planned for, through CBOR and back; what an older
1043    /// server sends reads as before.
1044    #[test]
1045    fn a_download_token_and_its_device_go_both_ways() {
1046        use crate::{Reply, Request, Response};
1047        round_trip(PeerRequest::AssertUser(AssertUser {
1048            user: "0192f1c4-5b6e-7a3d-9c41-2e8f7b6a5d4c".into(),
1049            display_name: "Bob".into(),
1050            client_endpoint: "ab".repeat(32),
1051            item: "plex:movie:1".into(),
1052            scope: TokenScope::Download,
1053            preferences: None,
1054            download: Some("ab".repeat(16)),
1055        }));
1056        let alien: spoolframe_types::MediaId = "fed:movie:mzxw6ytbojtg633c:plex:1".parse().unwrap();
1057        round_trip(Request::RemoteGrant {
1058            id: alien.clone(),
1059            download: Some("cd".repeat(16)),
1060        });
1061        round_trip(Response::Ok(Reply::RemoteGranted(RemoteGranted {
1062            token: "f00d".repeat(16),
1063            item: "plex:movie:1".parse().unwrap(),
1064            endpoint_id: "ab".repeat(32),
1065            expires_at: 1_791_000_300,
1066            download: Some("ab".repeat(16)),
1067        })));
1068        round_trip(Request::PrepareDownload {
1069            id: alien.clone(),
1070            source: crate::downloads::DownloadSource::Original,
1071            tracks: crate::downloads::DownloadTracks::All,
1072            device: Some(crate::downloads::DownloadDevice {
1073                platform: spoolframe_types::Platform::Ios,
1074                capabilities: None,
1075            }),
1076        });
1077        round_trip(crate::downloads::DownloadState::Failed {
1078            reason: "gone".into(),
1079            cause: crate::downloads::DownloadFailure::NoLongerAvailable,
1080        });
1081        let older = serde_json::json!({ "type": "remote_grant", "id": alien.to_string() });
1082        assert_eq!(
1083            codec::decode::<Request>(&codec::encode(&older).unwrap()).unwrap(),
1084            Request::RemoteGrant {
1085                id: alien,
1086                download: None
1087            }
1088        );
1089    }
1090
1091    /// M8-03: a name with a newline in it would forge a log line.
1092    #[test]
1093    fn a_name_keeps_no_control_character() {
1094        let forged = PeerHello {
1095            name: "Bob\n2026-10-23T00:00:00Z ERROR forged\u{1b}[0m".into(),
1096            ..hello()
1097        };
1098        assert_eq!(
1099            forged.within_bounds().name,
1100            "Bob2026-10-23T00:00:00Z ERROR forged[0m"
1101        );
1102    }
1103
1104    #[test]
1105    fn a_long_name_is_cut_as_a_device_s_is() {
1106        let long = PeerHello {
1107            name: "x".repeat(500),
1108            ..hello()
1109        };
1110        assert_eq!(
1111            long.within_bounds().name.chars().count(),
1112            crate::MAX_HELLO_TEXT
1113        );
1114    }
1115
1116    /// P8-07's subtitle asks and their replies, through CBOR and back; an
1117    /// ask without the user's choices reads as the defaults.
1118    #[test]
1119    fn subtitle_asks_go_both_ways() {
1120        let subtitles = spoolframe_types::SubtitlePreferences {
1121            sdh: spoolframe_types::SdhPreference::Prefer,
1122            ..Default::default()
1123        };
1124        round_trip(PeerRequest::SearchSubtitles(SubtitleSearchAsk {
1125            user: "0192f1c4-0000-7000-8000-000000000001".into(),
1126            subtitles,
1127            item: "plex:1".into(),
1128            language: Some("pt-BR".into()),
1129        }));
1130        round_trip(PeerRequest::DownloadSubtitle(SubtitleDownloadAsk {
1131            user: "0192f1c4-0000-7000-8000-000000000001".into(),
1132            item: "plex:1".into(),
1133            result: "opensubtitles:101".into(),
1134        }));
1135        round_trip(PeerRequest::RemoveSubtitleDownload(SubtitleRemovalAsk {
1136            user: "0192f1c4-0000-7000-8000-000000000001".into(),
1137            item: "plex:1".into(),
1138            download: "d1".into(),
1139        }));
1140        round_trip(PeerReply::SubtitleResults {
1141            search: spoolframe_types::SubtitleSearch {
1142                languages: vec!["en".into()],
1143                results: Vec::new(),
1144                sources: Vec::new(),
1145            },
1146        });
1147        round_trip(PeerReply::Failed {
1148            error: crate::Error::QuotaExhausted {
1149                whose: spoolframe_types::QuotaOf::User,
1150                resets_at: Some(1_893_456_000),
1151                site: None,
1152            },
1153        });
1154
1155        #[derive(Serialize)]
1156        struct Bare<'a> {
1157            user: &'a str,
1158            item: &'a str,
1159        }
1160        let bytes = codec::encode(&Bare {
1161            user: "u",
1162            item: "plex:1",
1163        })
1164        .unwrap();
1165        let read: SubtitleSearchAsk = codec::decode(&bytes).unwrap();
1166        assert_eq!(read.subtitles, Default::default());
1167        assert_eq!(read.language, None);
1168    }
1169}