Skip to main content

spoolframe_protocol/
federation.rs

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