Skip to main content

spoolframe_protocol/
federation.rs

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