Skip to main content

spoolframe_protocol/
phone_sign_in.rs

1//! Signing a TV in with a phone: the phone hands the TV the servers it
2//! signs in to and a sign-in it made for the TV on each, over a direct
3//! Iroh connection on [`SIGNIN_ALPN`].
4//!
5//! The TV shows the pairing link of [`crate::pairing`] as a QR code: the
6//! same link, the same one-time code. The phone dials the TV's key on
7//! [`SIGNIN_ALPN`] to sign it in to accounts, or on
8//! [`crate::pairing::PAIR_ALPN`] to put a guest's own identity on it;
9//! the code is taken by whichever comes first.
10//!
11//! On one bidirectional stream, each frame a [`crate::codec`] frame of
12//! at most [`MAX_FRAME`] bytes:
13//!
14//! 1. phone → TV: [`PhoneFrame::Hello`], the code and the phone's name;
15//! 2. TV → phone: [`TvFrame::Device`], what the TV is, or
16//!    [`TvFrame::Refused`];
17//! 3. phone → TV: [`PhoneFrame::Offers`], one [`Offer`] for each server
18//!    the person picked, at most [`MAX_OFFERS`], or
19//!    [`PhoneFrame::Declined`];
20//! 4. TV → phone: [`TvFrame::Done`], how each offer went, in the order
21//!    of the offers.
22//!
23//! Then the phone may send another [`PhoneFrame::Offers`] round, for
24//! servers it could not offer or the TV could not redeem, and the TV
25//! answers each with its own [`TvFrame::Done`], until the phone hangs
26//! up or sends [`PhoneFrame::Declined`], or for 2 minutes sends nothing.
27//! The person at the TV confirms the first round only. A TV before
28//! rounds hangs up after the first `Done`; a phone before them, the
29//! same.
30//!
31//! An offer's `request` is a device sign-in the phone's session made on
32//! that server for the TV's key (`OfferDeviceSignIn`). The TV redeems it
33//! with `AwaitDeviceSignIn` as if it had begun it itself; the server
34//! answers only the endpoint it was made for.
35//!
36//! Each enum has an `Unknown` variant, so a newer peer may add frames and
37//! outcomes: one read as `Unknown` ends the exchange, as one out of turn
38//! does.
39
40use serde::{Deserialize, Serialize};
41use spoolframe_types::Platform;
42
43use crate::pairing::{MAX_PAIRED_SERVERS, PairedServer, PairingCode};
44
45/// The ALPN of signing in with a phone, version 1. A TV accepts it only
46/// while it shows its code, whether or not it allows guests.
47pub const SIGNIN_ALPN: &[u8] = b"spoolframe/signin/1";
48
49/// The largest frame either side reads: [`MAX_OFFERS`] servers at their
50/// limits fit many times over.
51pub const MAX_FRAME: u32 = crate::pairing::MAX_FRAME;
52
53/// The most offers a [`PhoneFrame::Offers`] carries; a TV reads no more.
54pub const MAX_OFFERS: usize = MAX_PAIRED_SERVERS;
55
56/// The most characters of a reason a [`OfferOutcome::Failed`] carries.
57pub const MAX_REASON: usize = 200;
58
59/// What the phone sends.
60#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
61#[serde(tag = "type", rename_all = "snake_case")]
62pub enum PhoneFrame {
63    /// The code from the QR code, and what the phone calls itself
64    /// ("Andrey's iPhone", its device name, cut to
65    /// [`crate::pairing::MAX_NAME`] characters) for the TV to show. First,
66    /// and only once. `name` is left out by a phone before it was added.
67    Hello {
68        code: PairingCode,
69        #[serde(default, skip_serializing_if = "Option::is_none")]
70        name: Option<String>,
71    },
72    /// The sign-ins the phone made for the TV, one per server the person
73    /// picked.
74    Offers { offers: Vec<Offer> },
75    /// The person on the phone said no.
76    Declined,
77    /// A frame this build does not know.
78    #[serde(other)]
79    Unknown,
80}
81
82/// A server the phone signs the TV in to.
83#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
84pub struct Offer {
85    /// The server as the phone has it saved: the TV pins it, not
86    /// verified, as for a pairing's.
87    pub server: PairedServer,
88    /// The device sign-in made for the TV there (`DeviceSignInOffered`):
89    /// the TV's `AwaitDeviceSignIn` redeems it.
90    pub request: String,
91    /// Who the TV signs in as, for its screen: the profile's display name.
92    pub user_name: String,
93    /// The account's username there: what tells two accounts with one
94    /// display name apart, and a retry from another account. Left out by
95    /// a phone before it was added: the TV goes by `user_name` then.
96    #[serde(default, skip_serializing_if = "Option::is_none")]
97    pub username: Option<String>,
98}
99
100/// What the TV sends.
101#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
102#[serde(tag = "type", rename_all = "snake_case")]
103pub enum TvFrame {
104    /// What the TV is: "Sign in Living Room TV?". The phone makes its
105    /// offers for this.
106    Device {
107        name: String,
108        platform: Platform,
109        client_name: String,
110    },
111    /// How each offer went, in the order of the offers.
112    Done { results: Vec<OfferResult> },
113    /// The exchange is over, refused for `reason`.
114    Refused { reason: Refusal },
115    /// A frame this build does not know.
116    #[serde(other)]
117    Unknown,
118}
119
120/// How one offer went on the TV.
121#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
122pub struct OfferResult {
123    /// The offer's server: its endpoint id, as the offer named it.
124    pub server: String,
125    pub outcome: OfferOutcome,
126}
127
128/// Whether the TV is signed in to an offer's server.
129#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
130#[serde(tag = "type", rename_all = "snake_case")]
131pub enum OfferOutcome {
132    /// The TV holds a session there now.
133    SignedIn,
134    /// It is not: why, for the phone to show, cut to [`MAX_REASON`]
135    /// characters, and what kind of failure, for the phone to act on
136    /// ("Confirm it's you", "Try again later"). `kind` is left out by a
137    /// TV before it was added, and reads as [`FailureKind::Unknown`].
138    Failed {
139        reason: String,
140        #[serde(default, skip_serializing_if = "FailureKind::is_unknown")]
141        kind: FailureKind,
142    },
143    /// The person at the TV turned the sign-in down: nothing was
144    /// redeemed, and the grant runs out on its server unused.
145    Declined,
146    /// An outcome this build does not know.
147    #[serde(other)]
148    Unknown,
149}
150
151impl OfferOutcome {
152    /// A failure of `kind` for `reason`, cut to [`MAX_REASON`]
153    /// characters.
154    pub fn failed(kind: FailureKind, reason: &str) -> Self {
155        Self::Failed {
156            reason: reason.chars().take(MAX_REASON).collect(),
157            kind,
158        }
159    }
160}
161
162/// What kind of failure an offer's was on the TV: why its server did
163/// not sign it in.
164#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
165#[serde(rename_all = "snake_case")]
166pub enum FailureKind {
167    /// Too many sign-ins at once there, or too many waiting: the
168    /// server's `rate_limited`.
169    RateLimited,
170    /// The phone's session there must confirm it is them first.
171    RecentSignInRequired,
172    /// The phone's session there has ended (it expired, was revoked, or
173    /// an admin reset the password): sign in to that server again on
174    /// the phone first. Read as [`FailureKind::Unknown`] by a build
175    /// before it was added.
176    SessionEnded,
177    /// The account may not sign a device in there (a guest, or a role).
178    NotAllowed,
179    /// The server does not take phone sign-ins.
180    FeatureOff,
181    /// The TV could not reach the server, or it did not answer in time.
182    Unreachable,
183    /// The sign-in ran out on its server before the TV redeemed it.
184    Expired,
185    /// The server refused it otherwise: the reason is its message.
186    Refused,
187    /// A kind this build does not know, or none said (an older TV).
188    #[default]
189    #[serde(other)]
190    Unknown,
191}
192
193impl FailureKind {
194    pub fn is_unknown(&self) -> bool {
195        *self == FailureKind::Unknown
196    }
197}
198
199/// Why a TV refused a phone sign-in. The TV's code ends with each: it
200/// shows a new one to try again.
201#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, thiserror::Error)]
202#[serde(rename_all = "snake_case")]
203pub enum Refusal {
204    /// The code is not the one shown, or was used.
205    #[error("the sign-in code does not match")]
206    WrongCode,
207    /// The code was shown more than [`crate::pairing::CODE_TTL_SECS`] ago.
208    #[error("the sign-in code has expired")]
209    Expired,
210    /// Something else went wrong on the TV.
211    #[error("the TV could not finish signing in")]
212    Failed,
213    /// A reason this build does not know.
214    #[serde(other)]
215    #[error("the TV refused the sign-in")]
216    Unknown,
217}
218
219#[cfg(test)]
220mod tests {
221    use super::*;
222    use crate::codec::{decode, encode};
223
224    fn home() -> PairedServer {
225        PairedServer {
226            endpoint_id: "ab".repeat(32),
227            server_id: "q7k3mpa9trdwf2h".into(),
228            name: "Home Media".into(),
229            addrs: vec![
230                "192.168.1.10:7420".parse().unwrap(),
231                "[2001:db8::1]:7420".parse().unwrap(),
232            ],
233            relays: vec!["https://relay.example.org/".into()],
234        }
235    }
236
237    fn round_trip<T: Serialize + for<'de> Deserialize<'de> + PartialEq + std::fmt::Debug>(t: T) {
238        assert_eq!(decode::<T>(&encode(&t).unwrap()).unwrap(), t);
239    }
240
241    /// The names on the wire are promised to the apps.
242    #[test]
243    fn the_frames_wire_names_are_fixed() {
244        let offers = PhoneFrame::Offers {
245            offers: vec![Offer {
246                server: home(),
247                request: "r1".into(),
248                user_name: "Steve".into(),
249                username: Some("steve".into()),
250            }],
251        };
252        let json = serde_json::to_value(&offers).unwrap();
253        assert_eq!(json["type"], "offers");
254        assert_eq!(json["offers"][0]["request"], "r1");
255        assert_eq!(json["offers"][0]["user_name"], "Steve");
256        assert_eq!(json["offers"][0]["username"], "steve");
257        // From a phone before the username: none, and still read.
258        let mut old = json["offers"][0].clone();
259        old.as_object_mut().unwrap().remove("username");
260        let old: Offer = decode(&encode(&old).unwrap()).unwrap();
261        assert_eq!(old.username, None);
262        assert_eq!(
263            json["offers"][0]["server"]["addrs"][1],
264            "[2001:db8::1]:7420"
265        );
266        round_trip(offers);
267        round_trip(PhoneFrame::Hello {
268            code: PairingCode::from_bytes([7; 32]),
269            name: Some("Andrey's iPhone".into()),
270        });
271        // From a phone before the name: none.
272        let hello = PhoneFrame::Hello {
273            code: PairingCode::from_bytes([7; 32]),
274            name: None,
275        };
276        let json = serde_json::to_value(&hello).unwrap();
277        assert!(json.get("name").is_none(), "{json}");
278        round_trip(hello);
279        round_trip(PhoneFrame::Declined);
280
281        let device = TvFrame::Device {
282            name: "Living Room TV".into(),
283            platform: Platform::Tvos,
284            client_name: "spoolframe-tvos".into(),
285        };
286        assert_eq!(
287            serde_json::to_value(&device).unwrap(),
288            serde_json::json!({
289                "type": "device", "name": "Living Room TV", "platform": "tvos",
290                "client_name": "spoolframe-tvos",
291            })
292        );
293        round_trip(device);
294        let done = TvFrame::Done {
295            results: vec![
296                OfferResult {
297                    server: "ab".repeat(32),
298                    outcome: OfferOutcome::SignedIn,
299                },
300                OfferResult {
301                    server: "cd".repeat(32),
302                    outcome: OfferOutcome::failed(FailureKind::Unreachable, "unreachable"),
303                },
304            ],
305        };
306        let json = serde_json::to_value(&done).unwrap();
307        assert_eq!(
308            json["results"][0]["outcome"],
309            serde_json::json!({"type": "signed_in"})
310        );
311        assert_eq!(
312            json["results"][1]["outcome"],
313            serde_json::json!({"type": "failed", "reason": "unreachable", "kind": "unreachable"})
314        );
315        round_trip(done);
316        // From a TV before kinds: unknown, and the reason still read.
317        let old: OfferOutcome =
318            serde_json::from_value(serde_json::json!({"type": "failed", "reason": "no"})).unwrap();
319        assert_eq!(
320            old,
321            OfferOutcome::Failed {
322                reason: "no".into(),
323                kind: FailureKind::Unknown
324            }
325        );
326        // A kind a newer TV adds: unknown too.
327        let newer: OfferOutcome = decode(
328            &encode(&serde_json::json!({"type": "failed", "reason": "no", "kind": "on_fire"}))
329                .unwrap(),
330        )
331        .unwrap();
332        assert_eq!(
333            newer,
334            OfferOutcome::Failed {
335                reason: "no".into(),
336                kind: FailureKind::Unknown
337            }
338        );
339        for (kind, wire) in [
340            (FailureKind::RateLimited, "rate_limited"),
341            (FailureKind::RecentSignInRequired, "recent_sign_in_required"),
342            (FailureKind::SessionEnded, "session_ended"),
343            (FailureKind::NotAllowed, "not_allowed"),
344            (FailureKind::FeatureOff, "feature_off"),
345            (FailureKind::Unreachable, "unreachable"),
346            (FailureKind::Expired, "expired"),
347            (FailureKind::Refused, "refused"),
348        ] {
349            assert_eq!(serde_json::to_value(kind).unwrap(), wire);
350            round_trip(OfferOutcome::failed(kind, "why"));
351        }
352        let declined = OfferOutcome::Declined;
353        assert_eq!(
354            serde_json::to_value(&declined).unwrap(),
355            serde_json::json!({"type": "declined"})
356        );
357        round_trip(declined);
358        let refused = TvFrame::Refused {
359            reason: Refusal::WrongCode,
360        };
361        assert_eq!(
362            serde_json::to_string(&refused).unwrap(),
363            r#"{"type":"refused","reason":"wrong_code"}"#
364        );
365        round_trip(refused);
366    }
367
368    /// A newer peer's frame, outcome or reason reads as `Unknown`, through
369    /// CBOR as through JSON, rather than failing the read.
370    #[test]
371    fn what_a_newer_peer_adds_reads_as_unknown() {
372        let frame = serde_json::json!({"type": "teleport", "to": "mars"});
373        assert_eq!(
374            serde_json::from_value::<PhoneFrame>(frame.clone()).unwrap(),
375            PhoneFrame::Unknown
376        );
377        assert_eq!(
378            decode::<TvFrame>(&encode(&frame).unwrap()).unwrap(),
379            TvFrame::Unknown
380        );
381        let result = serde_json::json!({
382            "server": "ab".repeat(32),
383            "outcome": {"type": "postponed", "until": 5},
384        });
385        assert_eq!(
386            decode::<OfferResult>(&encode(&result).unwrap())
387                .unwrap()
388                .outcome,
389            OfferOutcome::Unknown
390        );
391        let refused = serde_json::json!({"type": "refused", "reason": "too_tired"});
392        assert_eq!(
393            decode::<TvFrame>(&encode(&refused).unwrap()).unwrap(),
394            TvFrame::Refused {
395                reason: Refusal::Unknown
396            }
397        );
398    }
399
400    #[test]
401    fn a_failure_s_reason_is_cut() {
402        let OfferOutcome::Failed { reason, .. } =
403            OfferOutcome::failed(FailureKind::Refused, &"é".repeat(500))
404        else {
405            panic!("a failure");
406        };
407        assert_eq!(reason.chars().count(), MAX_REASON);
408    }
409
410    /// Hello carries the code as pairing's does, and Debug keeps it out.
411    #[test]
412    fn the_hello_s_code_is_kept_out_of_debug() {
413        let hello = PhoneFrame::Hello {
414            code: PairingCode::from_bytes([7; 32]),
415            name: None,
416        };
417        let shown = format!("{hello:?}");
418        assert!(!shown.contains(&PairingCode::from_bytes([7; 32]).to_text()));
419        assert!(!shown.contains("7, 7"), "{shown}");
420    }
421}