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