Skip to main content

teter_common/
lib.rs

1//! Shared types and protocol definitions for teter.
2//!
3//! This crate defines the wire protocol used between all three components:
4//! frontend, relay, and backend. Messages are JSON-encoded and framed by
5//! WebSocket text frames.
6
7pub mod account;
8pub mod command;
9pub mod error;
10
11pub use error::{ProtocolError, ProtocolResult};
12
13use serde::{Deserialize, Serialize};
14use std::str::FromStr;
15use uuid::Uuid;
16
17/// Unique identifier for a teter session.
18pub type SessionId = Uuid;
19
20/// A message sent between frontend, relay, and backend.
21///
22/// All messages carry a `type` field that identifies the variant,
23/// an optional `session` ID for session-scoped messages, and
24/// a type-specific `payload`.
25#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
26pub struct Message {
27    /// Message type identifier (e.g. "input", "output", "resize").
28    #[serde(rename = "type", deserialize_with = "message_type_from_str")]
29    pub msg_type: MessageType,
30
31    /// Session ID, present on session-scoped messages.
32    #[serde(skip_serializing_if = "Option::is_none")]
33    pub session: Option<SessionId>,
34
35    /// The channel inside the session a message belongs to, for a backend
36    /// that carries several of its machine's sessions in one relay session:
37    /// an opaque ID ([`valid_channel`]), never a session's name. The relay
38    /// sets it on what a frontend sends (the channel it joined), and sends
39    /// the backend's output on a channel only to the frontends that joined
40    /// it. Left out for the session as a whole.
41    #[serde(default, skip_serializing_if = "Option::is_none")]
42    pub channel: Option<String>,
43
44    /// Type-specific payload data.
45    #[serde(skip_serializing_if = "Option::is_none")]
46    pub payload: Option<MessagePayload>,
47}
48
49/// All message type identifiers known to the protocol.
50#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
51#[serde(rename_all = "snake_case")]
52#[non_exhaustive]
53pub enum MessageType {
54    /// Backend registers a new session with the relay.
55    SessionCreate,
56    /// Frontend requests to join an existing session.
57    SessionJoin,
58    /// Relay confirms a frontend or backend has been attached to a session.
59    SessionJoined,
60    /// Either side detaches from a session.
61    SessionLeft,
62    /// Relay reports an error during session lifecycle.
63    SessionError,
64    /// Keyboard/mouse input from frontend to backend.
65    Input,
66    /// Terminal output from backend to frontend.
67    Output,
68    /// Terminal size change notification.
69    Resize,
70    /// Keep-alive heartbeat (either direction).
71    Ping,
72    /// Heartbeat response.
73    Pong,
74    /// First message on a connection: carries the token (`AuthToken` payload).
75    Auth,
76    /// Backend reattaches to its session after a dropped connection.
77    SessionResume,
78    /// Relay tells frontends their session's backend dropped.
79    BackendAway,
80    /// Relay tells frontends their session's backend is back.
81    BackendBack,
82    /// Relay tells the backend a frontend joined and waits for its replay.
83    FrontendJoined,
84    /// Backend sends a joining frontend the recent output, before live output.
85    Replay,
86    /// A registered machine's first message on `/backend`: which machine it
87    /// is (`MachineId` payload), to be challenged (#86).
88    MachineHello,
89    /// The relay's challenge to a machine (`Challenge` payload): fresh bytes
90    /// for it to sign.
91    Challenge,
92    /// A machine's answer to the challenge (`Signature` payload): its
93    /// signature, by the key it registered.
94    MachineProof,
95    /// A registered machine stores one of its sessions on the relay (#87):
96    /// on the message's channel, its name and key sealed to the account
97    /// (`Record` payload).
98    SessionRecord,
99    /// A registered machine's session on the message's channel ended: its
100    /// record goes.
101    SessionRecordGone,
102    /// A registered machine's link says which of its sessions run (#134,
103    /// `RecordsKept` payload), once each relay session has told them all:
104    /// the records its relay sessions (this one and those it held before)
105    /// keep of any other go.
106    SessionRecordsKept,
107}
108
109impl FromStr for MessageType {
110    type Err = ProtocolError;
111
112    fn from_str(s: &str) -> Result<Self, Self::Err> {
113        match s {
114            "session_create" => Ok(Self::SessionCreate),
115            "session_join" => Ok(Self::SessionJoin),
116            "session_joined" => Ok(Self::SessionJoined),
117            "session_left" => Ok(Self::SessionLeft),
118            "session_error" => Ok(Self::SessionError),
119            "input" => Ok(Self::Input),
120            "output" => Ok(Self::Output),
121            "resize" => Ok(Self::Resize),
122            "ping" => Ok(Self::Ping),
123            "pong" => Ok(Self::Pong),
124            "auth" => Ok(Self::Auth),
125            "session_resume" => Ok(Self::SessionResume),
126            "backend_away" => Ok(Self::BackendAway),
127            "backend_back" => Ok(Self::BackendBack),
128            "frontend_joined" => Ok(Self::FrontendJoined),
129            "replay" => Ok(Self::Replay),
130            "machine_hello" => Ok(Self::MachineHello),
131            "challenge" => Ok(Self::Challenge),
132            "machine_proof" => Ok(Self::MachineProof),
133            "session_record" => Ok(Self::SessionRecord),
134            "session_record_gone" => Ok(Self::SessionRecordGone),
135            "session_records_kept" => Ok(Self::SessionRecordsKept),
136            other => Err(ProtocolError::UnknownType(other.to_string())),
137        }
138    }
139}
140
141impl MessageType {
142    /// Convert a message type to its wire string identifier.
143    pub fn to_str(&self) -> &'static str {
144        match self {
145            Self::SessionCreate => "session_create",
146            Self::SessionJoin => "session_join",
147            Self::SessionJoined => "session_joined",
148            Self::SessionLeft => "session_left",
149            Self::SessionError => "session_error",
150            Self::Input => "input",
151            Self::Output => "output",
152            Self::Resize => "resize",
153            Self::Ping => "ping",
154            Self::Pong => "pong",
155            Self::Auth => "auth",
156            Self::SessionResume => "session_resume",
157            Self::BackendAway => "backend_away",
158            Self::BackendBack => "backend_back",
159            Self::FrontendJoined => "frontend_joined",
160            Self::Replay => "replay",
161            Self::MachineHello => "machine_hello",
162            Self::Challenge => "challenge",
163            Self::MachineProof => "machine_proof",
164            Self::SessionRecord => "session_record",
165            Self::SessionRecordGone => "session_record_gone",
166            Self::SessionRecordsKept => "session_records_kept",
167        }
168    }
169
170    /// Whether this message carries terminal I/O data.
171    pub fn is_io(&self) -> bool {
172        matches!(self, Self::Input | Self::Output)
173    }
174
175    /// Whether this message requires a session ID.
176    pub fn requires_session(&self) -> bool {
177        !matches!(
178            self,
179            Self::Ping
180                | Self::Pong
181                | Self::Auth
182                | Self::SessionCreate // creates a new session, no ID yet
183                | Self::SessionError // may come before any session exists
184                | Self::MachineHello // authentication, before any session
185                | Self::Challenge
186                | Self::MachineProof
187        )
188    }
189}
190
191/// Type-specific payload for a [`Message`].
192///
193/// Externally tagged on the wire: an object with one key, the variant name,
194/// e.g. `{"Resize":{"columns":80,"rows":24}}`.
195#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
196pub enum MessagePayload {
197    /// Keyboard/mouse input data, sealed end to end (bytes, a JSON array of
198    /// numbers). `paste` marks input inside a bracketed paste, sealed as
199    /// such: left out when false.
200    InputData {
201        /// The sealed input.
202        data: Vec<u8>,
203        /// Whether it is inside a bracketed paste.
204        #[serde(default, skip_serializing_if = "std::ops::Not::not")]
205        paste: bool,
206    },
207    /// Terminal stdout/stderr output, sealed end to end (bytes, a JSON array
208    /// of numbers).
209    OutputData {
210        /// The sealed output.
211        data: Vec<u8>,
212    },
213    /// Terminal resize dimensions, in clear. Backend and frontend send a
214    /// size sealed, as `Sealed`, instead.
215    Resize {
216        /// Width in columns.
217        columns: u16,
218        /// Height in rows.
219        rows: u16,
220    },
221    /// Sealed end to end, carried by `resize`: the relay forwards it, and
222    /// cannot read it (bytes, a JSON array of numbers).
223    Sealed {
224        /// The sealed bytes.
225        data: Vec<u8>,
226    },
227    /// Token for authentication, carried by `auth`.
228    AuthToken {
229        /// The token.
230        token: String,
231        /// The relay protocol the client speaks ([`PROTOCOL`]; 1 from a
232        /// client older than the field, #95).
233        #[serde(default = "first_protocol")]
234        protocol: u16,
235    },
236    /// Session ID and frontend token, carried by `session_joined`. To the
237    /// backend that created or resumed the session it also carries the
238    /// resume secret, which frontends never see.
239    SessionCreated {
240        /// The session's ID.
241        session_id: SessionId,
242        /// The token a frontend joins with.
243        frontend_token: String,
244        /// The resume secret, to the backend only.
245        #[serde(default, skip_serializing_if = "Option::is_none")]
246        resume_secret: Option<String>,
247        /// The relay protocol the relay speaks (#95; 1 from a relay older
248        /// than the field), for the client to check.
249        #[serde(default = "first_protocol")]
250        protocol: u16,
251    },
252    /// The session's resume secret, carried by `session_resume`.
253    ResumeSecret {
254        /// The secret.
255        secret: String,
256    },
257    /// What the backend does, carried by `session_create`: with `replay`,
258    /// it answers each `frontend_joined` with a `replay`.
259    SessionOptions {
260        /// Whether the backend answers each joining frontend with a replay.
261        replay: bool,
262    },
263    /// Which frontend joined, carried by `frontend_joined`. The number is
264    /// the relay's, only meaningful within the session.
265    Frontend {
266        /// The relay's number for the frontend.
267        frontend: u64,
268        /// Lines of the session's history the frontend asked for with its
269        /// join (#92): the replay holds them; 0 for none.
270        #[serde(default)]
271        history: u32,
272        /// The rows of its terminal, which the history is pushed up by
273        /// (#92); 0 for the session's.
274        #[serde(default)]
275        rows: u16,
276        /// Whether it takes the history the session kept on disk before a
277        /// restart, sealed to the account (#93).
278        #[serde(default, skip_serializing_if = "is_false")]
279        sealed_history: bool,
280    },
281    /// What a frontend asks with its join, carried by `session_join` (#92):
282    /// lines of the session's history before its screen (0 for none, as a
283    /// frontend older than this asks; a frontend joining again asks none).
284    JoinOptions {
285        /// Lines of history.
286        history: u32,
287        /// The rows of the frontend's terminal: the history is pushed up by
288        /// as many, so all of it lands in the scrollback; 0 (or absent) for
289        /// the session's.
290        #[serde(default)]
291        rows: u16,
292        /// Whether it takes the history the session kept on disk before a
293        /// restart, sealed to the account (#93): a device that holds the
294        /// account's keys.
295        #[serde(default, skip_serializing_if = "is_false")]
296        sealed_history: bool,
297    },
298    /// The recent output for one joining frontend, carried by `replay`,
299    /// sealed end to end (bytes, a JSON array of numbers).
300    ReplayData {
301        /// The frontend it is for.
302        frontend: u64,
303        /// The sealed recent output.
304        data: Vec<u8>,
305    },
306    /// Which registered machine says hello, carried by `machine_hello`.
307    MachineId {
308        /// The machine's ID, as the relay gave it at registration.
309        machine: String,
310        /// The relay protocol the machine's link speaks ([`PROTOCOL`]).
311        #[serde(default = "first_protocol")]
312        protocol: u16,
313    },
314    /// Bytes for a machine to sign, carried by `challenge`.
315    Challenge {
316        /// The challenge.
317        nonce: Vec<u8>,
318        /// The relay protocol the relay speaks (#95).
319        #[serde(default = "first_protocol")]
320        protocol: u16,
321        /// The machine's account's key rotations, oldest first (#89): the
322        /// machine follows those signed from the keys it pinned.
323        #[serde(default, skip_serializing_if = "Vec::is_empty")]
324        rotations: Vec<crate::account::KeyRotation>,
325    },
326    /// A machine's signature of its challenge, carried by `machine_proof`.
327    Signature {
328        /// The Ed25519 signature.
329        signature: Vec<u8>,
330    },
331    /// A session's name and key, sealed to the account, carried by
332    /// `session_record`.
333    Record {
334        /// The session's name, sealed to the account.
335        sealed_name: Vec<u8>,
336        /// The session's end-to-end secret, sealed to the account for its
337        /// channel.
338        sealed_key: Vec<u8>,
339        /// The machine's signature of the record (#133,
340        /// `account::record_bytes`).
341        #[serde(default)]
342        signature: Vec<u8>,
343    },
344    /// The channels of the sessions a machine runs, carried by
345    /// `session_records_kept` (#134).
346    RecordsKept {
347        /// The channels that run.
348        channels: Vec<String>,
349        /// The relay sessions the link held before this one: their records
350        /// of sessions not running go too.
351        #[serde(default)]
352        previous: Vec<SessionId>,
353    },
354    /// Error reason from the relay.
355    ErrorReason {
356        /// The reason.
357        reason: String,
358    },
359}
360
361/// What a machine signs to answer a challenge: this prefix, the challenge,
362/// then its ID. The prefix keeps the signature from meaning anything else.
363pub fn machine_proof_message(nonce: &[u8], machine: &str) -> Vec<u8> {
364    let mut message = b"teter-machine-auth-v1 ".to_vec();
365    message.extend_from_slice(nonce);
366    message.extend_from_slice(machine.as_bytes());
367    message
368}
369
370// --- Session-ending reasons ---
371
372/// The `session_error` reason when the session's backend left: the session
373/// is gone.
374pub const BACKEND_LEFT: &str = "the backend left the session";
375
376/// The `session_error` reason when a frontend's message finds its session
377/// already removed: the session is gone.
378pub const SESSION_GONE: &str = "the session is gone";
379
380/// Whether a `session_error` reason says the session itself ended, as
381/// opposed to an error about one connection or one message.
382pub fn ends_the_session(reason: &str) -> bool {
383    reason == BACKEND_LEFT || reason == SESSION_GONE
384}
385
386/// The longest channel ID, in bytes.
387pub const MAX_CHANNEL: usize = 64;
388
389/// Whether `channel` can be a channel ID: 1 to [`MAX_CHANNEL`] ASCII letters
390/// or digits. Opaque: a backend picks it (a random ID per session), and it
391/// never holds a session's name.
392pub fn valid_channel(channel: &str) -> bool {
393    !channel.is_empty()
394        && channel.len() <= MAX_CHANNEL
395        && channel.bytes().all(|b| b.is_ascii_alphanumeric())
396}
397
398impl Message {
399    /// This message, on `channel`.
400    #[must_use]
401    pub fn on_channel(self, channel: Option<String>) -> Self {
402        Self { channel, ..self }
403    }
404}
405
406// --- Serialization helpers ---
407
408/// The relay protocol this build speaks (#95): the version of the messages
409/// between clients (backends, frontends) and the relay. A change a peer of
410/// the version before cannot follow raises it.
411pub const PROTOCOL: u16 = 3;
412
413/// The oldest relay protocol a relay of this build accepts from a client.
414pub const MIN_PROTOCOL: u16 = 2;
415
416/// For serde: a flag left out when unset.
417#[expect(
418    clippy::trivially_copy_pass_by_ref,
419    reason = "serde passes a reference"
420)]
421fn is_false(value: &bool) -> bool {
422    !*value
423}
424
425/// What a client older than the protocol field speaks.
426const fn first_protocol() -> u16 {
427    1
428}
429
430/// Whether a client of this build works with a relay that speaks
431/// `relay`: a relay serves its version and the one before, so one older than
432/// this client is not.
433///
434/// # Errors
435///
436/// The refusal, naming both and what to upgrade.
437pub fn check_relay_protocol(relay: u16) -> Result<(), String> {
438    if relay < PROTOCOL {
439        Err(format!(
440            "the relay speaks relay protocol {relay}, older than this teter's {PROTOCOL}: upgrade \
441             the relay"
442        ))
443    } else {
444        Ok(())
445    }
446}
447
448/// The relay protocol a first message `json` carries, read loosely before
449/// the message is decoded (#95): a newer client's message may not decode
450/// here, and it still says what to upgrade.
451pub fn protocol_of(json: &str) -> Option<u16> {
452    let value: serde_json::Value = serde_json::from_str(json).ok()?;
453    let payload = value.get("payload")?.as_object()?;
454    payload
455        .values()
456        .find_map(|inner| inner.get("protocol")?.as_u64())
457        .and_then(|protocol| u16::try_from(protocol).ok())
458}
459
460/// Whether a relay that accepts `min..=max` serves a client of protocol
461/// `client`; the refusal names both and what to upgrade.
462///
463/// # Errors
464///
465/// The refusal, for a client outside the range.
466pub fn check_protocol(client: u16, min: u16, max: u16) -> Result<(), String> {
467    if client > max {
468        Err(format!(
469            "this teter speaks relay protocol {client}, newer than the relay's {max}: upgrade the \
470             relay"
471        ))
472    } else if client < min {
473        Err(format!(
474            "this teter speaks relay protocol {client}, older than the relay accepts ({min} to \
475             {max}): upgrade teter"
476        ))
477    } else {
478        Ok(())
479    }
480}
481
482/// Serialize a [`Message`] to a JSON string.
483pub fn serialize_message(msg: &Message) -> ProtocolResult<String> {
484    serde_json::to_string(msg).map_err(ProtocolError::Serialization)
485}
486
487/// Deserialize a [`Message`] from a JSON string.
488///
489/// When decoding fails, the error says where:
490/// [`ProtocolError::Deserialization`] for text that is not a JSON object or
491/// whose `type` is not a string, [`ProtocolError::MissingType`] for a missing
492/// or empty `type`, [`ProtocolError::UnknownType`], [`ProtocolError::InvalidSession`] or
493/// [`ProtocolError::InvalidPayload`]. A message without the session its type
494/// requires gives [`ProtocolError::MissingSession`].
495pub fn deserialize_message(json: &str) -> ProtocolResult<Message> {
496    // serde's derive also takes a struct as a JSON array; the protocol does not.
497    if !json.trim_start().starts_with('{') {
498        return Err(ProtocolError::Deserialization(
499            <serde_json::Error as serde::de::Error>::custom("a message is a JSON object"),
500        ));
501    }
502    let msg: Message = serde_json::from_str(json).map_err(|e| classify_decode_error(json, e))?;
503
504    if msg.msg_type.requires_session() && msg.session.is_none() {
505        return Err(ProtocolError::MissingSession);
506    }
507    if msg
508        .channel
509        .as_deref()
510        .is_some_and(|channel| !valid_channel(channel))
511    {
512        return Err(ProtocolError::InvalidChannel);
513    }
514
515    Ok(msg)
516}
517
518/// Read `type` only from a JSON string, never from serde's other enum forms
519/// (such as `{"ping": null}`).
520fn message_type_from_str<'de, D>(deserializer: D) -> Result<MessageType, D::Error>
521where
522    D: serde::Deserializer<'de>,
523{
524    let name = std::borrow::Cow::<'de, str>::deserialize(deserializer)?;
525    name.parse().map_err(serde::de::Error::custom)
526}
527
528/// Find which part of a message failed to decode. Runs only on the error
529/// path, so valid messages are decoded once, straight into [`Message`].
530/// The original error, which carries the position, is kept as the source.
531fn classify_decode_error(json: &str, err: serde_json::Error) -> ProtocolError {
532    let Ok(serde_json::Value::Object(fields)) = serde_json::from_str(json) else {
533        return ProtocolError::Deserialization(err);
534    };
535    let type_ = match fields.get("type") {
536        None => return ProtocolError::MissingType,
537        Some(serde_json::Value::String(t)) if t.is_empty() => return ProtocolError::MissingType,
538        Some(serde_json::Value::String(t)) => t,
539        Some(_) => return ProtocolError::Deserialization(err),
540    };
541    if let Err(unknown) = type_.parse::<MessageType>() {
542        return unknown;
543    }
544    if let Some(session) = fields.get("session")
545        && serde_json::from_value::<Option<SessionId>>(session.clone()).is_err()
546    {
547        return ProtocolError::InvalidSession { source: err };
548    }
549    if let Some(payload) = fields.get("payload")
550        && serde_json::from_value::<Option<MessagePayload>>(payload.clone()).is_err()
551    {
552        return ProtocolError::InvalidPayload {
553            type_: type_.clone(),
554            source: err,
555        };
556    }
557    ProtocolError::Deserialization(err)
558}
559
560// --- Builders ---
561
562impl Message {
563    /// Create a new session creation message.
564    pub fn session_create() -> Self {
565        Self {
566            msg_type: MessageType::SessionCreate,
567            session: None,
568            channel: None,
569            payload: None,
570        }
571    }
572
573    /// Create a session creation message from a backend that replays recent
574    /// output to joining frontends.
575    pub fn session_create_replaying() -> Self {
576        Self {
577            msg_type: MessageType::SessionCreate,
578            session: None,
579            channel: None,
580            payload: Some(MessagePayload::SessionOptions { replay: true }),
581        }
582    }
583
584    /// Create a new session join message.
585    pub fn session_join(session: SessionId) -> Self {
586        Self {
587            msg_type: MessageType::SessionJoin,
588            session: Some(session),
589            channel: None,
590            payload: None,
591        }
592    }
593
594    /// Create a session join that asks for `history` lines of the session's
595    /// history before its screen (#92), for a terminal of `rows` rows; with
596    /// none asked, a plain join.
597    pub fn session_join_with_history(session: SessionId, history: u32, rows: u16) -> Self {
598        Self::session_join_with_options(session, history, rows, false)
599    }
600
601    /// As [`Self::session_join_with_history`], also taking the history the
602    /// session kept on disk before a restart, sealed to the account, with
603    /// `sealed_history` (#93).
604    pub fn session_join_with_options(
605        session: SessionId,
606        history: u32,
607        rows: u16,
608        sealed_history: bool,
609    ) -> Self {
610        if history == 0 && !sealed_history {
611            return Self::session_join(session);
612        }
613        Self {
614            payload: Some(MessagePayload::JoinOptions {
615                history,
616                rows,
617                sealed_history,
618            }),
619            ..Self::session_join(session)
620        }
621    }
622
623    /// Create a session joined confirmation, as a frontend gets it.
624    pub fn session_joined(session: SessionId, frontend_token: String) -> Self {
625        Self {
626            msg_type: MessageType::SessionJoined,
627            session: Some(session),
628            channel: None,
629            payload: Some(MessagePayload::SessionCreated {
630                session_id: session,
631                frontend_token,
632                resume_secret: None,
633                protocol: PROTOCOL,
634            }),
635        }
636    }
637
638    /// Create a session joined confirmation for the backend that created or
639    /// resumed the session, with its resume secret.
640    pub fn session_created(
641        session: SessionId,
642        frontend_token: String,
643        resume_secret: String,
644    ) -> Self {
645        Self {
646            msg_type: MessageType::SessionJoined,
647            session: Some(session),
648            channel: None,
649            payload: Some(MessagePayload::SessionCreated {
650                session_id: session,
651                frontend_token,
652                resume_secret: Some(resume_secret),
653                protocol: PROTOCOL,
654            }),
655        }
656    }
657
658    /// Create a session resume request.
659    pub fn session_resume(session: SessionId, secret: String) -> Self {
660        Self {
661            msg_type: MessageType::SessionResume,
662            session: Some(session),
663            channel: None,
664            payload: Some(MessagePayload::ResumeSecret { secret }),
665        }
666    }
667
668    /// Create a notice to the backend that a frontend joined.
669    pub fn frontend_joined(session: SessionId, frontend: u64, history: u32, rows: u16) -> Self {
670        Self::frontend_joined_with(session, frontend, history, rows, false)
671    }
672
673    /// As [`Self::frontend_joined`], saying whether the frontend takes the
674    /// history kept on disk, sealed to the account (#93).
675    pub fn frontend_joined_with(
676        session: SessionId,
677        frontend: u64,
678        history: u32,
679        rows: u16,
680        sealed_history: bool,
681    ) -> Self {
682        Self {
683            msg_type: MessageType::FrontendJoined,
684            session: Some(session),
685            channel: None,
686            payload: Some(MessagePayload::Frontend {
687                frontend,
688                history,
689                rows,
690                sealed_history,
691            }),
692        }
693    }
694
695    /// Create a replay of recent output for a joining frontend.
696    pub fn replay(session: SessionId, frontend: u64, data: Vec<u8>) -> Self {
697        Self {
698            msg_type: MessageType::Replay,
699            session: Some(session),
700            channel: None,
701            payload: Some(MessagePayload::ReplayData { frontend, data }),
702        }
703    }
704
705    /// Create a notice that the session's backend dropped.
706    pub fn backend_away(session: SessionId) -> Self {
707        Self {
708            msg_type: MessageType::BackendAway,
709            session: Some(session),
710            channel: None,
711            payload: None,
712        }
713    }
714
715    /// Create a notice that the session's backend is back.
716    pub fn backend_back(session: SessionId) -> Self {
717        Self {
718            msg_type: MessageType::BackendBack,
719            session: Some(session),
720            channel: None,
721            payload: None,
722        }
723    }
724
725    /// Create a session left message.
726    pub fn session_left(session: SessionId) -> Self {
727        Self {
728            msg_type: MessageType::SessionLeft,
729            session: Some(session),
730            channel: None,
731            payload: None,
732        }
733    }
734
735    /// Create a session error message; `session` is `None` for an error that
736    /// comes before the connection has a session (a failed `auth`, say).
737    pub fn session_error(session: Option<SessionId>, reason: String) -> Self {
738        Self {
739            msg_type: MessageType::SessionError,
740            session,
741            channel: None,
742            payload: Some(MessagePayload::ErrorReason { reason }),
743        }
744    }
745
746    /// Create an input (keyboard/mouse) message.
747    pub fn input(session: SessionId, data: Vec<u8>) -> Self {
748        Self {
749            msg_type: MessageType::Input,
750            session: Some(session),
751            channel: None,
752            payload: Some(MessagePayload::InputData { data, paste: false }),
753        }
754    }
755
756    /// Create an input message for bytes inside a bracketed paste.
757    pub fn paste_input(session: SessionId, data: Vec<u8>) -> Self {
758        Self {
759            msg_type: MessageType::Input,
760            session: Some(session),
761            channel: None,
762            payload: Some(MessagePayload::InputData { data, paste: true }),
763        }
764    }
765
766    /// Create an output (terminal) message.
767    pub fn output(session: SessionId, data: Vec<u8>) -> Self {
768        Self {
769            msg_type: MessageType::Output,
770            session: Some(session),
771            channel: None,
772            payload: Some(MessagePayload::OutputData { data }),
773        }
774    }
775
776    /// Create a resize message carrying a sealed size.
777    pub fn sealed_resize(session: SessionId, data: Vec<u8>) -> Self {
778        Self {
779            msg_type: MessageType::Resize,
780            session: Some(session),
781            channel: None,
782            payload: Some(MessagePayload::Sealed { data }),
783        }
784    }
785
786    /// Create a resize message with the size in clear.
787    pub fn resize(session: SessionId, columns: u16, rows: u16) -> Self {
788        Self {
789            msg_type: MessageType::Resize,
790            session: Some(session),
791            channel: None,
792            payload: Some(MessagePayload::Resize { columns, rows }),
793        }
794    }
795
796    /// Create an authentication message carrying `token`.
797    pub fn auth(token: String) -> Self {
798        Self {
799            msg_type: MessageType::Auth,
800            session: None,
801            channel: None,
802            payload: Some(MessagePayload::AuthToken {
803                token,
804                protocol: PROTOCOL,
805            }),
806        }
807    }
808
809    /// Create a ping (keep-alive) message.
810    pub fn ping() -> Self {
811        Self {
812            msg_type: MessageType::Ping,
813            session: None,
814            channel: None,
815            payload: None,
816        }
817    }
818
819    /// Create a pong (heartbeat response) message.
820    pub fn pong() -> Self {
821        Self {
822            msg_type: MessageType::Pong,
823            session: None,
824            channel: None,
825            payload: None,
826        }
827    }
828}
829
830/// An authenticated connection role on the relay.
831#[derive(Debug, Clone, PartialEq, Eq)]
832pub enum Role {
833    /// Backend service running on a home machine.
834    Backend,
835    /// Terminal emulator client (laptop, phone, web).
836    Frontend,
837}
838
839impl FromStr for Role {
840    type Err = ProtocolError;
841
842    fn from_str(s: &str) -> Result<Self, Self::Err> {
843        match s {
844            "backend" => Ok(Self::Backend),
845            "frontend" => Ok(Self::Frontend),
846            other => Err(ProtocolError::UnknownType(other.to_string())),
847        }
848    }
849}
850
851impl Role {
852    /// Convert a role to its wire string identifier.
853    pub fn to_str(&self) -> &'static str {
854        match self {
855            Self::Backend => "backend",
856            Self::Frontend => "frontend",
857        }
858    }
859
860    /// Parse a role from a string identifier, returning `None` for unknown values.
861    pub fn parse_opt(s: &str) -> Option<Self> {
862        s.parse().ok()
863    }
864}
865
866#[cfg(test)]
867mod tests {
868    use super::*;
869
870    fn roundtrip(msg: &Message) -> String {
871        let json = serialize_message(msg).unwrap();
872        let restored = deserialize_message(&json).unwrap();
873        assert_eq!(*msg, restored);
874        json
875    }
876
877    #[test]
878    fn test_session_create_roundtrip() {
879        let msg = Message::session_create();
880        roundtrip(&msg);
881    }
882
883    #[test]
884    fn test_session_join_roundtrip() {
885        let sid = SessionId::new_v4();
886        let msg = Message::session_join(sid);
887        roundtrip(&msg);
888    }
889
890    #[test]
891    fn test_session_joined_roundtrip() {
892        let sid = SessionId::new_v4();
893        let token = "test-token-123".to_string();
894        let msg = Message::session_joined(sid, token.clone());
895        roundtrip(&msg);
896
897        if let Some(MessagePayload::SessionCreated {
898            session_id,
899            frontend_token,
900            resume_secret,
901            ..
902        }) = &msg.payload
903        {
904            assert_eq!(*session_id, sid);
905            assert_eq!(*frontend_token, token);
906            assert_eq!(*resume_secret, None);
907        } else {
908            panic!("expected SessionCreated payload");
909        }
910        // A frontend's copy carries no resume secret on the wire.
911        assert!(!serialize_message(&msg).unwrap().contains("resume_secret"));
912    }
913
914    #[test]
915    fn test_replay_messages_roundtrip() {
916        let sid = SessionId::new_v4();
917        let create = Message::session_create_replaying();
918        let json = roundtrip(&create);
919        assert!(
920            json.contains(r#"{"SessionOptions":{"replay":true}}"#),
921            "{json}"
922        );
923        let joined = Message::frontend_joined(sid, 7, 0, 0);
924        let json = roundtrip(&joined);
925        assert!(json.contains(r#""type":"frontend_joined""#), "{json}");
926        assert!(
927            json.contains(r#"{"Frontend":{"frontend":7,"history":0,"rows":0}}"#),
928            "{json}"
929        );
930        // A relay older than the field sends none: no history.
931        let old = deserialize_message(
932            r#"{"type":"frontend_joined","session":"7011b901-812b-4f0b-83bb-da42e6148c81","payload":{"Frontend":{"frontend":7}}}"#,
933        )
934        .unwrap();
935        assert!(matches!(
936            old.payload,
937            Some(MessagePayload::Frontend {
938                frontend: 7,
939                history: 0,
940                rows: 0,
941                sealed_history: false
942            })
943        ));
944        let replay = Message::replay(sid, 7, b"hi".to_vec());
945        let json = roundtrip(&replay);
946        assert!(
947            json.contains(r#"{"ReplayData":{"frontend":7,"data":[104,105]}}"#),
948            "{json}"
949        );
950        for (name, ty) in [
951            ("frontend_joined", MessageType::FrontendJoined),
952            ("replay", MessageType::Replay),
953        ] {
954            assert_eq!(name.parse::<MessageType>().unwrap(), ty);
955            assert_eq!(ty.to_str(), name);
956            assert!(ty.requires_session());
957        }
958    }
959
960    #[test]
961    fn test_resume_messages_roundtrip() {
962        let sid = SessionId::new_v4();
963        let created = Message::session_created(sid, "tok".into(), "sec".into());
964        let json = roundtrip(&created);
965        assert!(json.contains(r#""resume_secret":"sec""#), "{json}");
966        let resume = Message::session_resume(sid, "sec".into());
967        let json = roundtrip(&resume);
968        assert!(json.contains(r#""type":"session_resume""#), "{json}");
969        assert!(
970            json.contains(r#"{"ResumeSecret":{"secret":"sec"}}"#),
971            "{json}"
972        );
973        for msg in [Message::backend_away(sid), Message::backend_back(sid)] {
974            let json = roundtrip(&msg);
975            assert_eq!(deserialize_message(&json).unwrap(), msg);
976        }
977        for (name, ty) in [
978            ("session_resume", MessageType::SessionResume),
979            ("backend_away", MessageType::BackendAway),
980            ("backend_back", MessageType::BackendBack),
981        ] {
982            assert_eq!(name.parse::<MessageType>().unwrap(), ty);
983            assert_eq!(ty.to_str(), name);
984            assert!(ty.requires_session());
985        }
986    }
987
988    #[test]
989    fn test_session_left_roundtrip() {
990        let sid = SessionId::new_v4();
991        let msg = Message::session_left(sid);
992        roundtrip(&msg);
993    }
994
995    #[test]
996    fn test_session_error_roundtrip() {
997        let sid = SessionId::new_v4();
998        let msg = Message::session_error(Some(sid), "connection lost".to_string());
999        roundtrip(&msg);
1000    }
1001
1002    #[test]
1003    fn test_input_roundtrip() {
1004        let sid = SessionId::new_v4();
1005        let data = vec![0x1b, 0x5b, 0x41]; // ESC [ A (up arrow)
1006        let msg = Message::input(sid, data.clone());
1007        roundtrip(&msg);
1008
1009        if let Some(MessagePayload::InputData { data: received, .. }) = &msg.payload {
1010            assert_eq!(*received, data);
1011        } else {
1012            panic!("expected InputData payload");
1013        }
1014    }
1015
1016    #[test]
1017    fn test_output_roundtrip() {
1018        let sid = SessionId::new_v4();
1019        let data = b"Hello, teter!\n".to_vec();
1020        let msg = Message::output(sid, data.clone());
1021        roundtrip(&msg);
1022
1023        if let Some(MessagePayload::OutputData { data: received }) = &msg.payload {
1024            assert_eq!(*received, data);
1025        } else {
1026            panic!("expected OutputData payload");
1027        }
1028    }
1029
1030    #[test]
1031    fn test_resize_roundtrip() {
1032        let sid = SessionId::new_v4();
1033        let msg = Message::resize(sid, 120, 40);
1034        roundtrip(&msg);
1035
1036        if let Some(MessagePayload::Resize { columns, rows }) = &msg.payload {
1037            assert_eq!(*columns, 120);
1038            assert_eq!(*rows, 40);
1039        } else {
1040            panic!("expected Resize payload");
1041        }
1042    }
1043
1044    #[test]
1045    fn paste_input_is_marked_and_plain_input_leaves_the_mark_out() {
1046        let sid = SessionId::new_v4();
1047        let paste = Message::paste_input(sid, vec![1, 2]);
1048        roundtrip(&paste);
1049        let json = serialize_message(&paste).unwrap();
1050        assert!(
1051            json.contains(r#"{"InputData":{"data":[1,2],"paste":true}}"#),
1052            "{json}"
1053        );
1054        let plain = Message::input(sid, vec![1, 2]);
1055        let json = serialize_message(&plain).unwrap();
1056        assert!(json.contains(r#"{"InputData":{"data":[1,2]}}"#), "{json}");
1057        // A message without the mark reads as not paste.
1058        let read = deserialize_message(&json).unwrap();
1059        assert_eq!(
1060            read.payload,
1061            Some(MessagePayload::InputData {
1062                data: vec![1, 2],
1063                paste: false
1064            })
1065        );
1066    }
1067
1068    #[test]
1069    fn a_sealed_resize_roundtrips() {
1070        let sid = SessionId::new_v4();
1071        let msg = Message::sealed_resize(sid, vec![1, 2, 255]);
1072        roundtrip(&msg);
1073        assert_eq!(msg.msg_type, MessageType::Resize);
1074        assert_eq!(msg.session, Some(sid));
1075        assert_eq!(
1076            msg.payload,
1077            Some(MessagePayload::Sealed {
1078                data: vec![1, 2, 255]
1079            })
1080        );
1081        let json = serialize_message(&msg).unwrap();
1082        assert!(
1083            json.contains(r#""payload":{"Sealed":{"data":[1,2,255]}}"#),
1084            "{json}"
1085        );
1086    }
1087
1088    #[test]
1089    fn test_ping_roundtrip() {
1090        let msg = Message::ping();
1091        roundtrip(&msg);
1092    }
1093
1094    #[test]
1095    fn test_pong_roundtrip() {
1096        let msg = Message::pong();
1097        roundtrip(&msg);
1098    }
1099
1100    #[test]
1101    fn test_message_type_from_str() {
1102        assert_eq!(MessageType::from_str("input").unwrap(), MessageType::Input);
1103        assert_eq!(
1104            MessageType::from_str("session_create").unwrap(),
1105            MessageType::SessionCreate
1106        );
1107        assert!(MessageType::from_str("unknown_type").is_err());
1108    }
1109
1110    #[test]
1111    fn test_message_type_to_str() {
1112        assert_eq!(MessageType::Input.to_str(), "input");
1113        assert_eq!(MessageType::Output.to_str(), "output");
1114        assert_eq!(MessageType::Resize.to_str(), "resize");
1115        assert_eq!(MessageType::Ping.to_str(), "ping");
1116    }
1117
1118    #[test]
1119    fn test_requires_session() {
1120        assert!(!MessageType::Ping.requires_session());
1121        assert!(!MessageType::Pong.requires_session());
1122        assert!(MessageType::Input.requires_session());
1123        assert!(MessageType::Output.requires_session());
1124        assert!(!MessageType::Auth.requires_session());
1125        assert!(!MessageType::SessionError.requires_session());
1126        assert!(MessageType::SessionJoin.requires_session());
1127    }
1128
1129    #[test]
1130    fn the_protocol_is_read_from_a_first_message_that_does_not_decode() {
1131        assert_eq!(
1132            protocol_of(r#"{"type":"auth","payload":{"AuthToken":{"protocol":7}}}"#),
1133            Some(7)
1134        );
1135        assert_eq!(protocol_of(r#"{"type":"ping"}"#), None);
1136        assert_eq!(protocol_of("not json"), None);
1137        assert!(check_relay_protocol(PROTOCOL).is_ok());
1138    }
1139
1140    #[test]
1141    fn protocols_outside_the_range_say_what_to_upgrade() {
1142        assert_eq!(check_protocol(2, 1, 2), Ok(()));
1143        assert!(
1144            check_protocol(3, 1, 2)
1145                .unwrap_err()
1146                .contains("upgrade the relay")
1147        );
1148        assert!(
1149            check_protocol(0, 1, 2)
1150                .unwrap_err()
1151                .contains("upgrade teter")
1152        );
1153    }
1154
1155    #[test]
1156    fn test_auth_roundtrip() {
1157        let json = roundtrip(&Message::auth("secret".to_string()));
1158        assert_eq!(
1159            json,
1160            r#"{"type":"auth","payload":{"AuthToken":{"token":"secret","protocol":3}}}"#
1161        );
1162        // A client older than the field speaks protocol 1 (#95).
1163        let old = deserialize_message(r#"{"type":"auth","payload":{"AuthToken":{"token":"t"}}}"#)
1164            .unwrap();
1165        assert_eq!(
1166            old.payload,
1167            Some(MessagePayload::AuthToken {
1168                token: "t".to_owned(),
1169                protocol: 1
1170            })
1171        );
1172        assert_eq!("auth".parse::<MessageType>().unwrap(), MessageType::Auth);
1173        assert_eq!(MessageType::Auth.to_str(), "auth");
1174    }
1175
1176    #[test]
1177    fn test_session_error_without_session_roundtrip() {
1178        let json = roundtrip(&Message::session_error(
1179            None,
1180            "authentication failed".to_string(),
1181        ));
1182        assert!(!json.contains("session\""), "{json}");
1183    }
1184
1185    #[test]
1186    fn test_missing_session_rejected() {
1187        // A message without a session field that requires one should fail.
1188        let json = r#"{"type":"input"}"#;
1189        assert!(matches!(
1190            deserialize_message(json),
1191            Err(ProtocolError::MissingSession)
1192        ));
1193    }
1194
1195    #[test]
1196    fn test_missing_type_rejected() {
1197        let json = r#"{"session":"00000000-0000-0000-0000-000000000000"}"#;
1198        assert!(deserialize_message(json).is_err());
1199    }
1200
1201    const SID: &str = "00000000-0000-0000-0000-000000000000";
1202
1203    fn invalid_payload_type(json: &str) -> String {
1204        match deserialize_message(json) {
1205            Err(ProtocolError::InvalidPayload { type_, .. }) => type_,
1206            other => panic!("expected InvalidPayload, got {other:?}"),
1207        }
1208    }
1209
1210    #[test]
1211    fn test_invalid_payload_names_the_type() {
1212        let json = format!(
1213            r#"{{"type":"resize","session":"{SID}","payload":{{"Resize":{{"columns":"wide","rows":24}}}}}}"#
1214        );
1215        assert_eq!(invalid_payload_type(&json), "resize");
1216    }
1217
1218    #[test]
1219    fn test_invalid_payload_type_with_whitespace() {
1220        let json = format!(
1221            r#"{{ "session" : "{SID}", "payload" : {{ "InputData" : {{ "data" : "x" }} }}, "type" : "input" }}"#
1222        );
1223        assert_eq!(invalid_payload_type(&json), "input");
1224    }
1225
1226    #[test]
1227    fn test_not_a_message_gives_deserialization_error() {
1228        for json in [
1229            "[1, 2]".to_string(),
1230            "not json".to_string(),
1231            format!(r#"{{"type":5,"session":"{SID}"}}"#),
1232        ] {
1233            let err = deserialize_message(&json).unwrap_err();
1234            assert!(
1235                matches!(err, ProtocolError::Deserialization(_)),
1236                "{json}: {err:?}"
1237            );
1238            assert!(err.to_string().starts_with("failed to decode"), "{err}");
1239        }
1240    }
1241
1242    #[test]
1243    fn test_missing_or_empty_type_gives_missing_type() {
1244        for json in [
1245            format!(r#"{{"session":"{SID}"}}"#),
1246            format!(r#"{{"type":"","session":"{SID}"}}"#),
1247        ] {
1248            assert!(
1249                matches!(deserialize_message(&json), Err(ProtocolError::MissingType)),
1250                "{json}"
1251            );
1252        }
1253    }
1254
1255    #[test]
1256    fn test_unknown_type_gives_unknown_type() {
1257        let json = format!(r#"{{"type":"bogus","session":"{SID}"}}"#);
1258        assert!(matches!(
1259            deserialize_message(&json),
1260            Err(ProtocolError::UnknownType(t)) if t == "bogus"
1261        ));
1262    }
1263
1264    #[test]
1265    fn test_bad_session_names_the_session() {
1266        for json in [
1267            r#"{"type":"input","session":"not-a-uuid","payload":{"InputData":{"data":[1]}}}"#,
1268            r#"{"type":"input","session":5,"payload":{"InputData":{"data":[1]}}}"#,
1269        ] {
1270            let err = deserialize_message(json).unwrap_err();
1271            assert!(
1272                matches!(err, ProtocolError::InvalidSession { .. }),
1273                "{json}: {err:?}"
1274            );
1275            assert!(err.to_string().contains("session"), "{err}");
1276        }
1277    }
1278
1279    #[test]
1280    fn test_non_canonical_forms_are_rejected() {
1281        for json in [
1282            r#"["ping"]"#,
1283            r#"["input","00000000-0000-0000-0000-000000000000"]"#,
1284            r#"["ping",null,null]"#,
1285            r#"{"type":{"ping":null}}"#,
1286        ] {
1287            assert!(
1288                matches!(
1289                    deserialize_message(json),
1290                    Err(ProtocolError::Deserialization(_))
1291                ),
1292                "{json}"
1293            );
1294        }
1295    }
1296
1297    #[test]
1298    fn test_decode_error_keeps_position() {
1299        let json = format!(
1300            r#"{{"type":"resize","session":"{SID}","payload":{{"Resize":{{"columns":"wide","rows":24}}}}}}"#
1301        );
1302        match deserialize_message(&json) {
1303            Err(ProtocolError::InvalidPayload { source, .. }) => {
1304                assert_eq!(source.line(), 1);
1305                assert!(source.column() > 0);
1306            }
1307            other => panic!("expected InvalidPayload, got {other:?}"),
1308        }
1309    }
1310
1311    #[test]
1312    fn test_null_fields_are_absent() {
1313        let json = r#"{"type":"ping","session":null,"payload":null}"#;
1314        assert_eq!(deserialize_message(json).unwrap(), Message::ping());
1315    }
1316
1317    #[test]
1318    fn test_only_the_session_ending_reasons_end_the_session() {
1319        assert!(ends_the_session(BACKEND_LEFT));
1320        assert!(ends_the_session(SESSION_GONE));
1321        assert!(!ends_the_session("silent past the heartbeat timeout"));
1322        assert!(!ends_the_session(""));
1323    }
1324
1325    #[test]
1326    fn test_io_flag() {
1327        assert!(MessageType::Input.is_io());
1328        assert!(MessageType::Output.is_io());
1329        assert!(!MessageType::Resize.is_io());
1330        assert!(!MessageType::Ping.is_io());
1331    }
1332
1333    #[test]
1334    fn test_role_to_from_str() {
1335        assert_eq!(Role::Backend.to_str(), "backend");
1336        assert_eq!(Role::Frontend.to_str(), "frontend");
1337        assert_eq!(Role::parse_opt("backend"), Some(Role::Backend));
1338        assert_eq!(Role::parse_opt("frontend"), Some(Role::Frontend));
1339        assert_eq!(Role::parse_opt("unknown"), None);
1340    }
1341
1342    #[test]
1343    fn test_role_from_str_trait() {
1344        assert_eq!("backend".parse::<Role>().unwrap(), Role::Backend);
1345        assert_eq!("frontend".parse::<Role>().unwrap(), Role::Frontend);
1346        assert!("unknown".parse::<Role>().is_err());
1347    }
1348
1349    #[test]
1350    fn test_auth_token_roundtrip() {
1351        let msg = Message {
1352            msg_type: MessageType::SessionCreate,
1353            session: None,
1354            channel: None,
1355            payload: Some(MessagePayload::AuthToken {
1356                token: "backend-secret-token".to_string(),
1357                protocol: PROTOCOL,
1358            }),
1359        };
1360        roundtrip(&msg);
1361    }
1362
1363    #[test]
1364    fn test_error_reason_roundtrip() {
1365        let sid = SessionId::new_v4();
1366        let msg = Message {
1367            msg_type: MessageType::SessionError,
1368            session: Some(sid),
1369            channel: None,
1370            payload: Some(MessagePayload::ErrorReason {
1371                reason: "relay overload".to_string(),
1372            }),
1373        };
1374        roundtrip(&msg);
1375    }
1376
1377    #[test]
1378    fn test_session_id_generation() {
1379        let id1 = SessionId::new_v4();
1380        let id2 = SessionId::new_v4();
1381        assert_ne!(id1, id2);
1382    }
1383
1384    #[test]
1385    fn a_channel_travels_and_one_that_is_not_an_opaque_id_is_refused() {
1386        let msg = Message::output(SessionId::nil(), vec![1]).on_channel(Some("a1B2".into()));
1387        let json = serialize_message(&msg).unwrap();
1388        assert!(json.contains(r#""channel":"a1B2""#), "{json}");
1389        assert_eq!(deserialize_message(&json).unwrap(), msg);
1390        // Left out when there is none.
1391        let plain = serialize_message(&Message::output(SessionId::nil(), vec![1])).unwrap();
1392        assert!(!plain.contains("channel"), "{plain}");
1393        for bad in ["", "my session", "a/b", &"x".repeat(MAX_CHANNEL + 1)] {
1394            let json = serialize_message(
1395                &Message::session_join(SessionId::nil()).on_channel(Some(bad.to_owned())),
1396            )
1397            .unwrap();
1398            assert!(
1399                matches!(
1400                    deserialize_message(&json),
1401                    Err(ProtocolError::InvalidChannel)
1402                ),
1403                "{bad:?}"
1404            );
1405        }
1406        assert!(valid_channel(&"f".repeat(MAX_CHANNEL)));
1407    }
1408}