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