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