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        /// What the answering server calls itself now, as its
417        /// [`PeerInfo`]'s `name`: so a pair learns of a rename at its next
418        /// sync, without dialling again. Absent from a server before
419        /// 0.16.3.
420        #[serde(default, skip_serializing_if = "Option::is_none")]
421        name: Option<String>,
422    },
423    /// A page of a [`SyncLibrary`]'s answer.
424    Page(SyncPage),
425    /// An image: at most [`MAX_ARTWORK_BYTES`].
426    Artwork {
427        /// Its media type, as `image/jpeg`.
428        content_type: String,
429        #[serde(with = "serde_bytes")]
430        bytes: Vec<u8>,
431    },
432    /// The library, or the item the image is of, is not shared with the
433    /// pair (now, or any more): a cache of it goes.
434    NotShared,
435    /// Shared, but the item or image is not there now.
436    NotFound,
437    /// The sharing server cannot answer now (its catalog is down): the
438    /// asker keeps what it has and asks again later.
439    Unavailable,
440    /// The token for an [`AssertUser`].
441    Token(TokenGranted),
442    /// No token for an [`AssertUser`], and why.
443    AssertionRefused {
444        reason: AssertionRefused,
445    },
446    /// A subtitle search's results.
447    SubtitleResults {
448        search: spoolframe_types::SubtitleSearch,
449    },
450    /// A subtitle downloaded.
451    SubtitleDownloaded {
452        downloaded: spoolframe_types::SubtitleDownloaded,
453    },
454    /// A subtitle ask refused, as the client protocol would refuse
455    /// it: the home server passes it on to its device as it is.
456    Failed {
457        error: crate::Error,
458    },
459    /// A reply this build does not know.
460    #[serde(other)]
461    Unknown,
462}
463
464#[cfg(test)]
465mod tests {
466    use super::*;
467    use crate::codec;
468
469    fn round_trip<T>(value: T)
470    where
471        T: Serialize + serde::de::DeserializeOwned + PartialEq + fmt::Debug,
472    {
473        let bytes = codec::encode(&value).unwrap();
474        assert_eq!(codec::decode::<T>(&bytes).unwrap(), value);
475    }
476
477    /// A request naming a paired server's item anywhere names one; a
478    /// search for text that only starts like an id does not.
479    #[test]
480    fn a_fed_id_is_found_in_any_field_of_a_request() {
481        let alien: spoolframe_types::MediaId = "fed:movie:mzxw6ytbojtg633c:plex:1".parse().unwrap();
482        assert!(names_federated(&crate::Request::Item { id: alien.clone() }));
483        assert!(names_federated(&crate::Request::UpdateWatchProgress {
484            id: alien,
485            position_ms: 0,
486        }));
487        assert!(!names_federated(&crate::Request::Item {
488            id: "plex:movie:1".parse().unwrap(),
489        }));
490        assert!(!names_federated(&crate::Request::SetServerRow {
491            server_id: "fed:nothing".into(),
492            shown: true,
493        }));
494    }
495
496    fn hello() -> PeerHello {
497        PeerHello {
498            protocol_version: PROTOCOL_VERSION,
499            server_id: "mzxw6ytbojtg633c".into(),
500            name: "Bob's server".into(),
501        }
502    }
503
504    #[test]
505    fn every_request_goes_both_ways() {
506        round_trip(PeerRequest::Hello(hello()));
507        round_trip(PeerRequest::RedeemPairing(RedeemPairing {
508            code: "QW7K-2MFP-XR4T".into(),
509            addrs: vec!["203.0.113.7:7420".into()],
510            relays: vec!["https://relay.example.org".into()],
511        }));
512        round_trip(PeerRequest::Unpaired(Unpaired {}));
513    }
514
515    fn item() -> RemoteItem {
516        RemoteItem {
517            id: "plex:track:33".into(),
518            kind: RemoteKind::Track,
519            title: "Digital Love".into(),
520            parent: Some("plex:album:31".into()),
521            grandparent: Some("plex:artist:30".into()),
522            parent_title: Some("Discovery".into()),
523            grandparent_title: Some("Daft Punk".into()),
524            index: Some(3),
525            parent_index: Some(1),
526            year: Some(2001),
527            date: Some("2001-03-12".into()),
528            summary: None,
529            content_rating: None,
530            duration_ms: Some(301_000),
531            count: Some(14),
532            genres: vec!["Electronic".into()],
533            artwork: vec![RemoteArtwork {
534                id: "plex:/library/metadata/31/thumb/9".into(),
535                kind: RemoteArtworkKind::Poster,
536            }],
537            external_ids: vec!["mbid://5e4b7b2c".into()],
538            sort_title: None,
539            released: None,
540            added_at: None,
541            rating_tenths: None,
542            audience_rating_tenths: None,
543            size: None,
544            resolution: None,
545            dynamic_range: None,
546            hash: String::new(),
547        }
548        .hashed()
549    }
550
551    /// P8-02's requests and replies, through CBOR and back.
552    #[test]
553    fn replication_goes_both_ways() {
554        round_trip(PeerRequest::Libraries);
555        round_trip(PeerRequest::SharesChanged);
556        round_trip(PeerRequest::Sync(SyncLibrary {
557            library: "plex:2".into(),
558            since: None,
559        }));
560        round_trip(PeerRequest::Sync(SyncLibrary {
561            library: "plex:2".into(),
562            since: Some("0192f1c4".into()),
563        }));
564        round_trip(PeerRequest::Artwork(ArtworkFetch {
565            id: "plex:/library/metadata/31/thumb/9".into(),
566        }));
567        round_trip(PeerReply::Libraries {
568            libraries: vec![SharedLibrary {
569                id: "plex:2".into(),
570                title: "Music".into(),
571                kind: RemoteLibraryKind::Music,
572            }],
573            name: Some("Bob's server".into()),
574        });
575        for mode in [SyncMode::Changes, SyncMode::Snapshot] {
576            round_trip(PeerReply::Page(SyncPage {
577                mode,
578                cursor: "0192f1c4".into(),
579                items: vec![item()],
580                removed: vec!["plex:track:32".into()],
581                more: true,
582            }));
583        }
584        round_trip(PeerReply::Artwork {
585            content_type: "image/png".into(),
586            bytes: vec![0x89, b'P', b'N', b'G'],
587        });
588        round_trip(PeerReply::NotShared);
589        round_trip(PeerReply::NotFound);
590        round_trip(PeerReply::Unavailable);
591    }
592
593    /// The hash is of the content: it moves when the item does, not when
594    /// the hash field itself is set.
595    #[test]
596    fn an_item_s_hash_follows_its_content() {
597        let a = item();
598        assert_eq!(a.digest(), a.hash);
599        assert_eq!(a.clone().hashed(), a);
600        let renamed = RemoteItem {
601            title: "Something About Us".into(),
602            ..a.clone()
603        };
604        assert_ne!(renamed.digest(), a.hash);
605    }
606
607    /// What a library is sorted and filtered by is sent only when there
608    /// is some: an item without it encodes with the fields it had before
609    /// them, so its hash is as an older server makes it and nothing is
610    /// sent again for them alone; one with them crosses whole.
611    #[test]
612    fn the_browse_facts_are_sent_only_when_known() {
613        let bytes = crate::codec::encode(&item()).unwrap();
614        let value: ciborium::Value = ciborium::from_reader(bytes.as_slice()).unwrap();
615        let keys: Vec<String> = value
616            .as_map()
617            .unwrap()
618            .iter()
619            .filter_map(|(k, _)| k.as_text().map(str::to_owned))
620            .collect();
621        assert_eq!(
622            keys,
623            [
624                "id",
625                "kind",
626                "title",
627                "parent",
628                "grandparent",
629                "parent_title",
630                "grandparent_title",
631                "index",
632                "parent_index",
633                "year",
634                "date",
635                "summary",
636                "content_rating",
637                "duration_ms",
638                "count",
639                "genres",
640                "artwork",
641                "external_ids",
642                "hash",
643            ]
644        );
645        let known = RemoteItem {
646            sort_title: Some("Something".into()),
647            released: Some("2001-03-12".into()),
648            added_at: Some(1_700_000_000),
649            rating_tenths: Some(87),
650            audience_rating_tenths: Some(91),
651            size: Some(30 << 30),
652            resolution: Some(spoolframe_types::Resolution::FullHd),
653            dynamic_range: Some(spoolframe_types::DynamicRange::DolbyVision),
654            ..item()
655        }
656        .hashed();
657        assert_ne!(known.hash, item().hash);
658        round_trip(PeerReply::Page(SyncPage {
659            mode: SyncMode::Snapshot,
660            cursor: "c".into(),
661            items: vec![known],
662            removed: Vec::new(),
663            more: false,
664        }));
665    }
666
667    /// A page past the bounds is cut to them as it is read: items,
668    /// removed ids, and each item's lists and texts.
669    #[test]
670    fn a_page_is_cut_to_its_bounds() {
671        let long = RemoteItem {
672            title: "x".repeat(MAX_ITEM_TEXT + 10),
673            summary: Some("y".repeat(MAX_ITEM_SUMMARY + 10)),
674            genres: vec!["g".into(); MAX_ITEM_GENRES + 1],
675            artwork: vec![item().artwork[0].clone(); MAX_ITEM_ARTWORK + 1],
676            external_ids: vec!["tmdb://1".into(); MAX_ITEM_EXTERNAL_IDS + 1],
677            ..item()
678        };
679        let page = SyncPage {
680            mode: SyncMode::Snapshot,
681            cursor: "c".into(),
682            items: vec![long; MAX_PAGE_ITEMS + 1],
683            removed: vec!["plex:movie:1".into(); MAX_PAGE_REMOVED + 1],
684            more: false,
685        }
686        .within_bounds();
687        assert_eq!(page.items.len(), MAX_PAGE_ITEMS);
688        assert_eq!(page.removed.len(), MAX_PAGE_REMOVED);
689        let item = &page.items[0];
690        assert_eq!(item.title.chars().count(), MAX_ITEM_TEXT);
691        assert_eq!(
692            item.summary.as_ref().unwrap().chars().count(),
693            MAX_ITEM_SUMMARY
694        );
695        assert_eq!(item.genres.len(), MAX_ITEM_GENRES);
696        assert_eq!(item.artwork.len(), MAX_ITEM_ARTWORK);
697        assert_eq!(item.external_ids.len(), MAX_ITEM_EXTERNAL_IDS);
698        let listed = libraries_within_bounds(vec![
699            SharedLibrary {
700                id: "plex:1".into(),
701                title: "Movies".into(),
702                kind: RemoteLibraryKind::Movies,
703            };
704            MAX_SHARED_LIBRARIES + 1
705        ]);
706        assert_eq!(listed.len(), MAX_SHARED_LIBRARIES);
707    }
708
709    /// What a newer sharing server adds reads as `Unknown`, item by item,
710    /// never failing the page: an item kind, an artwork role, a library
711    /// kind, a sync mode.
712    #[test]
713    fn what_a_newer_server_replicates_reads_as_unknown() {
714        let decode = |value: serde_json::Value| codec::encode(&value).unwrap();
715        let page = serde_json::json!({
716            "type": "page",
717            "mode": "patch",
718            "cursor": "c",
719            "items": [{
720                "id": "plex:clip:1",
721                "kind": "clip",
722                "title": "Trailer",
723                "artwork": [{ "id": "a", "kind": "banner" }],
724                "hash": "h",
725                "rating": 7,
726            }],
727            "more": false,
728        });
729        let PeerReply::Page(page) = codec::decode::<PeerReply>(&decode(page)).unwrap() else {
730            panic!("not a page");
731        };
732        assert_eq!(page.mode, SyncMode::Unknown);
733        assert_eq!(page.items[0].kind, RemoteKind::Unknown);
734        assert_eq!(page.items[0].artwork[0].kind, RemoteArtworkKind::Unknown);
735        let libraries = serde_json::json!({
736            "type": "libraries",
737            "libraries": [{ "id": "plex:4", "title": "Photos", "kind": "photos" }],
738        });
739        let PeerReply::Libraries { libraries, name } =
740            codec::decode::<PeerReply>(&decode(libraries)).unwrap()
741        else {
742            panic!("not libraries");
743        };
744        assert_eq!(libraries[0].kind, RemoteLibraryKind::Unknown);
745        assert_eq!(name, None);
746    }
747
748    #[test]
749    fn every_reply_goes_both_ways() {
750        for standing in [Standing::Stranger, Standing::Paired, Standing::KeyHeld] {
751            round_trip(PeerReply::Info(PeerInfo {
752                protocol_version: PROTOCOL_VERSION,
753                server_id: "mzxw6ytbojtg633c".into(),
754                name: "Alice's server".into(),
755                standing,
756            }));
757        }
758        round_trip(PeerReply::Paired(Paired {
759            server_id: "mzxw6ytbojtg633c".into(),
760            name: "Alice's server".into(),
761        }));
762        for reason in [
763            PairingRefused::InviteInvalid,
764            PairingRefused::InviteExpired,
765            PairingRefused::InviteExhausted,
766            PairingRefused::WrongInviteKind,
767            PairingRefused::RateLimited {
768                retry_after_secs: 30,
769            },
770            PairingRefused::AlreadyPaired,
771            PairingRefused::ServerIdChanged,
772            PairingRefused::SameServerId,
773            PairingRefused::KeyRefused,
774            PairingRefused::KeyHeld,
775        ] {
776            round_trip(PeerReply::Refused { reason });
777        }
778        round_trip(PeerReply::Done);
779    }
780
781    /// `name()` is the serde tag, for every reason.
782    #[test]
783    fn a_refusal_s_name_is_its_tag() {
784        for reason in [
785            PairingRefused::InviteInvalid,
786            PairingRefused::InviteExpired,
787            PairingRefused::InviteExhausted,
788            PairingRefused::WrongInviteKind,
789            PairingRefused::RateLimited {
790                retry_after_secs: 30,
791            },
792            PairingRefused::AlreadyPaired,
793            PairingRefused::ServerIdChanged,
794            PairingRefused::SameServerId,
795            PairingRefused::KeyRefused,
796            PairingRefused::KeyHeld,
797            PairingRefused::Unknown,
798        ] {
799            let json = serde_json::to_value(reason).unwrap();
800            assert_eq!(json["type"], reason.name(), "{reason:?}");
801        }
802    }
803
804    /// What a newer server adds reads as `Unknown`, never as a decode
805    /// failure: a request (which the server then does not allow), a
806    /// reply, a standing and a refusal.
807    #[test]
808    fn what_a_newer_server_sends_reads_as_unknown() {
809        let decode = |value: serde_json::Value| codec::encode(&value).unwrap();
810        assert_eq!(
811            codec::decode::<PeerRequest>(&decode(serde_json::json!({ "type": "share_library" })))
812                .unwrap(),
813            PeerRequest::Unknown
814        );
815        assert_eq!(
816            codec::decode::<PeerReply>(&decode(serde_json::json!({ "type": "catalog" }))).unwrap(),
817            PeerReply::Unknown
818        );
819        let info = serde_json::json!({
820            "type": "info",
821            "protocol_version": 2,
822            "server_id": "mzxw6ytbojtg633c",
823            "name": "Alice's server",
824            "standing": "neighbour",
825            "libraries": 3,
826        });
827        let PeerReply::Info(info) = codec::decode::<PeerReply>(&decode(info)).unwrap() else {
828            panic!("not info");
829        };
830        assert_eq!(info.standing, Standing::Unknown);
831        let refused = serde_json::json!({ "type": "refused", "reason": { "type": "busy" } });
832        assert_eq!(
833            codec::decode::<PeerReply>(&decode(refused)).unwrap(),
834            PeerReply::Refused {
835                reason: PairingRefused::Unknown
836            }
837        );
838    }
839
840    /// A grant's notice is a tag and nothing else: what an older server
841    /// reads as a request it does not know, and refuses.
842    #[test]
843    fn a_notice_of_shares_changed_is_its_tag_alone() {
844        let wire = codec::encode(&serde_json::json!({ "type": "shares_changed" })).unwrap();
845        assert_eq!(
846            codec::decode::<PeerRequest>(&wire).unwrap(),
847            PeerRequest::SharesChanged
848        );
849        assert_eq!(codec::encode(&PeerRequest::SharesChanged).unwrap(), wire);
850    }
851
852    /// A redemption from a server that sends no hints reads as one with
853    /// none.
854    #[test]
855    fn a_redemption_without_hints_has_none() {
856        let sent = serde_json::json!({ "type": "redeem_pairing", "code": "QW7K2MFPXR4T" });
857        let PeerRequest::RedeemPairing(redeem) =
858            codec::decode(&codec::encode(&sent).unwrap()).unwrap()
859        else {
860            panic!("not a redemption");
861        };
862        assert!(redeem.addrs.is_empty() && redeem.relays.is_empty());
863    }
864
865    /// The client protocol's request and reply (P8-01).
866    #[test]
867    fn pairing_from_an_app_goes_both_ways_and_keeps_the_link_out_of_debug() {
868        use crate::{Error, Reply, Request, Response};
869        let request = Request::PairServer(PairServer {
870            link: "spoolframe://invite?server=x&kind=federation&cap=QW7K-2MFP-XR4T".into(),
871        });
872        round_trip(request.clone());
873        assert!(!format!("{request:?}").contains("QW7K"));
874        round_trip(Response::Ok(Reply::ServerPaired {
875            server: PeerServer {
876                name: "Alice's server".into(),
877                server_id: "mzxw6ytbojtg633c".into(),
878                endpoint_id: "ab".repeat(32),
879                fingerprint: "PGJA-BHZ1-F68M-DFSE".into(),
880            },
881        }));
882        round_trip(Response::Err(Error::PairingRefused {
883            reason: PairingRefused::AlreadyPaired,
884        }));
885    }
886
887    /// The client protocol's share request and reply (P8-03), and its
888    /// bound.
889    #[test]
890    fn sharing_from_an_app_goes_both_ways_and_is_bounded() {
891        use crate::{Reply, Request, Response};
892        let library: spoolframe_types::LibraryId = "plex:1".parse().unwrap();
893        let share = ShareLibraries {
894            server_id: "mzxw6ytbojtg633c".into(),
895            libraries: vec![library.clone(); MAX_SHARED + 3],
896        };
897        round_trip(Request::ShareLibraries(share.clone()));
898        round_trip(Response::Ok(Reply::LibrariesShared {
899            libraries: vec![library],
900        }));
901        assert_eq!(share.within_bounds().libraries.len(), MAX_SHARED);
902    }
903
904    /// P8-02's client exposure: a library's server, Home's server rows
905    /// and items no longer available, the row setting and the event. What
906    /// is empty is left out, so a reply to an app that does not name the
907    /// feature reads as before.
908    #[test]
909    fn client_exposure_goes_both_ways_and_is_left_out_when_empty() {
910        use crate::{Event, HomeScreen, Reply, Request, Response, ServerRow};
911        use spoolframe_types::{Library, LibraryKind, LibraryServer};
912        let server = LibraryServer {
913            server_id: "mzxw6ytbojtg633c".into(),
914            name: "Alice's server".into(),
915            online: false,
916        };
917        let shared = Library {
918            id: "fed:mzxw6ytbojtg633c:plex:1".parse().unwrap(),
919            title: "Movies".into(),
920            kind: LibraryKind::Movies,
921            server: Some(server.clone()),
922        };
923        round_trip(Response::Ok(Reply::Libraries {
924            libraries: vec![shared],
925        }));
926        round_trip(Response::Ok(Reply::Home(HomeScreen {
927            unavailable: vec!["fed:movie:mzxw6ytbojtg633c:plex:1".parse().unwrap()],
928            servers: vec![ServerRow {
929                server,
930                shown: false,
931                items: Vec::new(),
932            }],
933            ..HomeScreen::default()
934        })));
935        round_trip(Request::SetServerRow {
936            server_id: "mzxw6ytbojtg633c".into(),
937            shown: true,
938        });
939        round_trip(Event::LibrariesChanged);
940        // P8-03: progress by item, and history's items no longer available.
941        let alien: spoolframe_types::MediaId = "fed:movie:mzxw6ytbojtg633c:plex:1".parse().unwrap();
942        round_trip(Request::UpdateWatchProgress {
943            id: alien.clone(),
944            position_ms: 2_400_000,
945        });
946        round_trip(Response::Ok(Reply::Items {
947            items: Vec::new(),
948            total: 1,
949            unavailable: vec![alien],
950        }));
951        let items = serde_json::to_value(Reply::Items {
952            items: Vec::new(),
953            total: 0,
954            unavailable: Vec::new(),
955        })
956        .unwrap();
957        assert!(items.get("unavailable").is_none(), "{items}");
958        let own = Library {
959            id: "plex:1".parse().unwrap(),
960            title: "Movies".into(),
961            kind: LibraryKind::Movies,
962            server: None,
963        };
964        let json = serde_json::to_value(&own).unwrap();
965        assert!(json.get("server").is_none(), "{json}");
966        let home = serde_json::to_value(HomeScreen::default()).unwrap();
967        assert!(home.get("servers").is_none() && home.get("unavailable").is_none());
968        assert_eq!(serde_json::from_value::<Library>(json).unwrap(), own);
969    }
970
971    #[test]
972    fn the_code_stays_out_of_debug_output() {
973        let redeem = RedeemPairing {
974            code: "QW7K-2MFP-XR4T".into(),
975            addrs: Vec::new(),
976            relays: Vec::new(),
977        };
978        assert!(!format!("{redeem:?}").contains("QW7K"));
979    }
980
981    /// P8-03's assertion and its answers, through CBOR and back; a scope
982    /// left out is a play, a newer one reads as unknown, and the token
983    /// stays out of debug output.
984    #[test]
985    fn an_assertion_goes_both_ways() {
986        let assertion = AssertUser {
987            user: "0192f1c4-5b6e-7a3d-9c41-2e8f7b6a5d4c".into(),
988            display_name: "Bob".into(),
989            client_endpoint: "ab".repeat(32),
990            item: "plex:movie:1".into(),
991            scope: TokenScope::Play,
992            preferences: None,
993            download: None,
994        };
995        round_trip(PeerRequest::AssertUser(assertion.clone()));
996        // P8-04: the user's track preferences go with it when SB has them.
997        let mut preferences = spoolframe_types::TrackPreferences::default();
998        preferences.audio.languages = vec!["fra".into()];
999        round_trip(PeerRequest::AssertUser(AssertUser {
1000            preferences: Some(preferences),
1001            ..assertion.clone()
1002        }));
1003        let granted = TokenGranted {
1004            token: "f00d".repeat(16),
1005            scope: TokenScope::Play,
1006            expires_at: 1_791_000_300,
1007        };
1008        assert!(!format!("{granted:?}").contains("f00d"));
1009        round_trip(PeerReply::Token(granted));
1010        for reason in [
1011            AssertionRefused::NotShared,
1012            AssertionRefused::InvalidUser,
1013            AssertionRefused::InvalidDevice,
1014            AssertionRefused::InvalidScope,
1015            AssertionRefused::Unavailable,
1016        ] {
1017            round_trip(PeerReply::AssertionRefused { reason });
1018        }
1019        let decode = |value: serde_json::Value| codec::encode(&value).unwrap();
1020        let sent = serde_json::json!({
1021            "type": "assert_user",
1022            "user": assertion.user,
1023            "display_name": "Bob",
1024            "client_endpoint": assertion.client_endpoint,
1025            "item": "plex:movie:1",
1026        });
1027        assert_eq!(
1028            codec::decode::<PeerRequest>(&decode(sent)).unwrap(),
1029            PeerRequest::AssertUser(assertion.clone())
1030        );
1031        let later = serde_json::json!({
1032            "type": "assert_user",
1033            "user": assertion.user,
1034            "display_name": "Bob",
1035            "client_endpoint": assertion.client_endpoint,
1036            "item": "plex:movie:1",
1037            "scope": "subtitles",
1038        });
1039        let PeerRequest::AssertUser(later) = codec::decode(&decode(later)).unwrap() else {
1040            panic!("not an assertion");
1041        };
1042        assert_eq!(later.scope, TokenScope::Unknown);
1043        let long = AssertUser {
1044            display_name: "x".repeat(500),
1045            ..assertion
1046        };
1047        assert_eq!(
1048            long.within_bounds().display_name.chars().count(),
1049            crate::MAX_HELLO_TEXT
1050        );
1051    }
1052
1053    /// P8-07: a download token's assertion, its grant, and the device a
1054    /// download is planned for, through CBOR and back; what an older
1055    /// server sends reads as before.
1056    #[test]
1057    fn a_download_token_and_its_device_go_both_ways() {
1058        use crate::{Reply, Request, Response};
1059        round_trip(PeerRequest::AssertUser(AssertUser {
1060            user: "0192f1c4-5b6e-7a3d-9c41-2e8f7b6a5d4c".into(),
1061            display_name: "Bob".into(),
1062            client_endpoint: "ab".repeat(32),
1063            item: "plex:movie:1".into(),
1064            scope: TokenScope::Download,
1065            preferences: None,
1066            download: Some("ab".repeat(16)),
1067        }));
1068        let alien: spoolframe_types::MediaId = "fed:movie:mzxw6ytbojtg633c:plex:1".parse().unwrap();
1069        round_trip(Request::RemoteGrant {
1070            id: alien.clone(),
1071            download: Some("cd".repeat(16)),
1072        });
1073        round_trip(Response::Ok(Reply::RemoteGranted(RemoteGranted {
1074            token: "f00d".repeat(16),
1075            item: "plex:movie:1".parse().unwrap(),
1076            endpoint_id: "ab".repeat(32),
1077            expires_at: 1_791_000_300,
1078            download: Some("ab".repeat(16)),
1079        })));
1080        round_trip(Request::PrepareDownload {
1081            id: alien.clone(),
1082            source: crate::downloads::DownloadSource::Original,
1083            tracks: crate::downloads::DownloadTracks::All,
1084            device: Some(crate::downloads::DownloadDevice {
1085                platform: spoolframe_types::Platform::Ios,
1086                capabilities: None,
1087            }),
1088        });
1089        round_trip(crate::downloads::DownloadState::Failed {
1090            reason: "gone".into(),
1091            cause: crate::downloads::DownloadFailure::NoLongerAvailable,
1092        });
1093        let older = serde_json::json!({ "type": "remote_grant", "id": alien.to_string() });
1094        assert_eq!(
1095            codec::decode::<Request>(&codec::encode(&older).unwrap()).unwrap(),
1096            Request::RemoteGrant {
1097                id: alien,
1098                download: None
1099            }
1100        );
1101    }
1102
1103    /// M8-03: a name with a newline in it would forge a log line.
1104    #[test]
1105    fn a_name_keeps_no_control_character() {
1106        let forged = PeerHello {
1107            name: "Bob\n2026-10-23T00:00:00Z ERROR forged\u{1b}[0m".into(),
1108            ..hello()
1109        };
1110        assert_eq!(
1111            forged.within_bounds().name,
1112            "Bob2026-10-23T00:00:00Z ERROR forged[0m"
1113        );
1114    }
1115
1116    #[test]
1117    fn a_long_name_is_cut_as_a_device_s_is() {
1118        let long = PeerHello {
1119            name: "x".repeat(500),
1120            ..hello()
1121        };
1122        assert_eq!(
1123            long.within_bounds().name.chars().count(),
1124            crate::MAX_HELLO_TEXT
1125        );
1126    }
1127
1128    /// P8-07's subtitle asks and their replies, through CBOR and back; an
1129    /// ask without the user's choices reads as the defaults.
1130    #[test]
1131    fn subtitle_asks_go_both_ways() {
1132        let subtitles = spoolframe_types::SubtitlePreferences {
1133            sdh: spoolframe_types::SdhPreference::Prefer,
1134            ..Default::default()
1135        };
1136        round_trip(PeerRequest::SearchSubtitles(SubtitleSearchAsk {
1137            user: "0192f1c4-0000-7000-8000-000000000001".into(),
1138            subtitles,
1139            item: "plex:1".into(),
1140            language: Some("pt-BR".into()),
1141        }));
1142        round_trip(PeerRequest::DownloadSubtitle(SubtitleDownloadAsk {
1143            user: "0192f1c4-0000-7000-8000-000000000001".into(),
1144            item: "plex:1".into(),
1145            result: "opensubtitles:101".into(),
1146        }));
1147        round_trip(PeerRequest::RemoveSubtitleDownload(SubtitleRemovalAsk {
1148            user: "0192f1c4-0000-7000-8000-000000000001".into(),
1149            item: "plex:1".into(),
1150            download: "d1".into(),
1151        }));
1152        round_trip(PeerReply::SubtitleResults {
1153            search: spoolframe_types::SubtitleSearch {
1154                languages: vec!["en".into()],
1155                results: Vec::new(),
1156                sources: Vec::new(),
1157            },
1158        });
1159        round_trip(PeerReply::Failed {
1160            error: crate::Error::QuotaExhausted {
1161                whose: spoolframe_types::QuotaOf::User,
1162                resets_at: Some(1_893_456_000),
1163                site: None,
1164            },
1165        });
1166
1167        #[derive(Serialize)]
1168        struct Bare<'a> {
1169            user: &'a str,
1170            item: &'a str,
1171        }
1172        let bytes = codec::encode(&Bare {
1173            user: "u",
1174            item: "plex:1",
1175        })
1176        .unwrap();
1177        let read: SubtitleSearchAsk = codec::decode(&bytes).unwrap();
1178        assert_eq!(read.subtitles, Default::default());
1179        assert_eq!(read.language, None);
1180    }
1181}