teter-common 26.11.7

Shared types and protocol definitions for teter
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
//! Shared types and protocol definitions for teter.
//!
//! This crate defines the wire protocol used between all three components:
//! frontend, relay, and backend. Messages are JSON-encoded and framed by
//! WebSocket text frames.

pub mod account;
pub mod command;
pub mod error;

pub use error::{ProtocolError, ProtocolResult};

use serde::{Deserialize, Serialize};
use std::str::FromStr;
use uuid::Uuid;

/// Unique identifier for a teter session.
pub type SessionId = Uuid;

/// A message sent between frontend, relay, and backend.
///
/// All messages carry a `type` field that identifies the variant,
/// an optional `session` ID for session-scoped messages, and
/// a type-specific `payload`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Message {
    /// Message type identifier (e.g. "input", "output", "resize").
    #[serde(rename = "type", deserialize_with = "message_type_from_str")]
    pub msg_type: MessageType,

    /// Session ID, present on session-scoped messages.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub session: Option<SessionId>,

    /// The channel inside the session a message belongs to, for a backend
    /// that carries several of its machine's sessions in one relay session:
    /// an opaque ID ([`valid_channel`]), never a session's name. The relay
    /// sets it on what a frontend sends (the channel it joined), and sends
    /// the backend's output on a channel only to the frontends that joined
    /// it. Left out for the session as a whole.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub channel: Option<String>,

    /// Type-specific payload data.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub payload: Option<MessagePayload>,
}

/// All message type identifiers known to the protocol.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum MessageType {
    /// Backend registers a new session with the relay.
    SessionCreate,
    /// Frontend requests to join an existing session.
    SessionJoin,
    /// Relay confirms a frontend or backend has been attached to a session.
    SessionJoined,
    /// Either side detaches from a session.
    SessionLeft,
    /// Relay reports an error during session lifecycle.
    SessionError,
    /// Keyboard/mouse input from frontend to backend.
    Input,
    /// Terminal output from backend to frontend.
    Output,
    /// Terminal size change notification.
    Resize,
    /// Keep-alive heartbeat (either direction).
    Ping,
    /// Heartbeat response.
    Pong,
    /// First message on a connection: carries the token (`AuthToken` payload).
    Auth,
    /// Backend reattaches to its session after a dropped connection.
    SessionResume,
    /// Relay tells frontends their session's backend dropped.
    BackendAway,
    /// Relay tells frontends their session's backend is back.
    BackendBack,
    /// Relay tells the backend a frontend joined and waits for its replay.
    FrontendJoined,
    /// Backend sends a joining frontend the recent output, before live output.
    Replay,
    /// A registered machine's first message on `/backend`: which machine it
    /// is (`MachineId` payload), to be challenged (#86).
    MachineHello,
    /// The relay's challenge to a machine (`Challenge` payload): fresh bytes
    /// for it to sign.
    Challenge,
    /// A machine's answer to the challenge (`Signature` payload): its
    /// signature, by the key it registered.
    MachineProof,
    /// A registered machine stores one of its sessions on the relay (#87):
    /// on the message's channel, its name and key sealed to the account
    /// (`Record` payload).
    SessionRecord,
    /// A registered machine's session on the message's channel ended: its
    /// record goes.
    SessionRecordGone,
    /// A registered machine's link says which of its sessions run (#134,
    /// `RecordsKept` payload), once each relay session has told them all:
    /// the records its relay sessions (this one and those it held before)
    /// keep of any other go.
    SessionRecordsKept,
}

impl FromStr for MessageType {
    type Err = ProtocolError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "session_create" => Ok(Self::SessionCreate),
            "session_join" => Ok(Self::SessionJoin),
            "session_joined" => Ok(Self::SessionJoined),
            "session_left" => Ok(Self::SessionLeft),
            "session_error" => Ok(Self::SessionError),
            "input" => Ok(Self::Input),
            "output" => Ok(Self::Output),
            "resize" => Ok(Self::Resize),
            "ping" => Ok(Self::Ping),
            "pong" => Ok(Self::Pong),
            "auth" => Ok(Self::Auth),
            "session_resume" => Ok(Self::SessionResume),
            "backend_away" => Ok(Self::BackendAway),
            "backend_back" => Ok(Self::BackendBack),
            "frontend_joined" => Ok(Self::FrontendJoined),
            "replay" => Ok(Self::Replay),
            "machine_hello" => Ok(Self::MachineHello),
            "challenge" => Ok(Self::Challenge),
            "machine_proof" => Ok(Self::MachineProof),
            "session_record" => Ok(Self::SessionRecord),
            "session_record_gone" => Ok(Self::SessionRecordGone),
            "session_records_kept" => Ok(Self::SessionRecordsKept),
            other => Err(ProtocolError::UnknownType(other.to_string())),
        }
    }
}

impl MessageType {
    /// Convert a message type to its wire string identifier.
    pub fn to_str(&self) -> &'static str {
        match self {
            Self::SessionCreate => "session_create",
            Self::SessionJoin => "session_join",
            Self::SessionJoined => "session_joined",
            Self::SessionLeft => "session_left",
            Self::SessionError => "session_error",
            Self::Input => "input",
            Self::Output => "output",
            Self::Resize => "resize",
            Self::Ping => "ping",
            Self::Pong => "pong",
            Self::Auth => "auth",
            Self::SessionResume => "session_resume",
            Self::BackendAway => "backend_away",
            Self::BackendBack => "backend_back",
            Self::FrontendJoined => "frontend_joined",
            Self::Replay => "replay",
            Self::MachineHello => "machine_hello",
            Self::Challenge => "challenge",
            Self::MachineProof => "machine_proof",
            Self::SessionRecord => "session_record",
            Self::SessionRecordGone => "session_record_gone",
            Self::SessionRecordsKept => "session_records_kept",
        }
    }

    /// Whether this message carries terminal I/O data.
    pub fn is_io(&self) -> bool {
        matches!(self, Self::Input | Self::Output)
    }

    /// Whether this message requires a session ID.
    pub fn requires_session(&self) -> bool {
        !matches!(
            self,
            Self::Ping
                | Self::Pong
                | Self::Auth
                | Self::SessionCreate // creates a new session, no ID yet
                | Self::SessionError // may come before any session exists
                | Self::MachineHello // authentication, before any session
                | Self::Challenge
                | Self::MachineProof
        )
    }
}

/// Type-specific payload for a [`Message`].
///
/// Externally tagged on the wire: an object with one key, the variant name,
/// e.g. `{"Resize":{"columns":80,"rows":24}}`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum MessagePayload {
    /// Keyboard/mouse input data, sealed end to end (bytes, a JSON array of
    /// numbers). `paste` marks input inside a bracketed paste, sealed as
    /// such: left out when false.
    InputData {
        /// The sealed input.
        data: Vec<u8>,
        /// Whether it is inside a bracketed paste.
        #[serde(default, skip_serializing_if = "std::ops::Not::not")]
        paste: bool,
    },
    /// Terminal stdout/stderr output, sealed end to end (bytes, a JSON array
    /// of numbers).
    OutputData {
        /// The sealed output.
        data: Vec<u8>,
    },
    /// Terminal resize dimensions, in clear. Backend and frontend send a
    /// size sealed, as `Sealed`, instead.
    Resize {
        /// Width in columns.
        columns: u16,
        /// Height in rows.
        rows: u16,
    },
    /// Sealed end to end, carried by `resize`: the relay forwards it, and
    /// cannot read it (bytes, a JSON array of numbers).
    Sealed {
        /// The sealed bytes.
        data: Vec<u8>,
    },
    /// Token for authentication, carried by `auth`.
    AuthToken {
        /// The token.
        token: String,
        /// The relay protocol the client speaks ([`PROTOCOL`]; 1 from a
        /// client older than the field, #95).
        #[serde(default = "first_protocol")]
        protocol: u16,
    },
    /// Session ID and frontend token, carried by `session_joined`. To the
    /// backend that created or resumed the session it also carries the
    /// resume secret, which frontends never see.
    SessionCreated {
        /// The session's ID.
        session_id: SessionId,
        /// The token a frontend joins with.
        frontend_token: String,
        /// The resume secret, to the backend only.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        resume_secret: Option<String>,
        /// The relay protocol the relay speaks (#95; 1 from a relay older
        /// than the field), for the client to check.
        #[serde(default = "first_protocol")]
        protocol: u16,
    },
    /// The session's resume secret, carried by `session_resume`.
    ResumeSecret {
        /// The secret.
        secret: String,
    },
    /// What the backend does, carried by `session_create`: with `replay`,
    /// it answers each `frontend_joined` with a `replay`.
    SessionOptions {
        /// Whether the backend answers each joining frontend with a replay.
        replay: bool,
    },
    /// Which frontend joined, carried by `frontend_joined`. The number is
    /// the relay's, only meaningful within the session.
    Frontend {
        /// The relay's number for the frontend.
        frontend: u64,
        /// Lines of the session's history the frontend asked for with its
        /// join (#92): the replay holds them; 0 for none.
        #[serde(default)]
        history: u32,
        /// The rows of its terminal, which the history is pushed up by
        /// (#92); 0 for the session's.
        #[serde(default)]
        rows: u16,
        /// Whether it takes the history the session kept on disk before a
        /// restart, sealed to the account (#93).
        #[serde(default, skip_serializing_if = "is_false")]
        sealed_history: bool,
    },
    /// What a frontend asks with its join, carried by `session_join` (#92):
    /// lines of the session's history before its screen (0 for none, as a
    /// frontend older than this asks; a frontend joining again asks none).
    JoinOptions {
        /// Lines of history.
        history: u32,
        /// The rows of the frontend's terminal: the history is pushed up by
        /// as many, so all of it lands in the scrollback; 0 (or absent) for
        /// the session's.
        #[serde(default)]
        rows: u16,
        /// Whether it takes the history the session kept on disk before a
        /// restart, sealed to the account (#93): a device that holds the
        /// account's keys.
        #[serde(default, skip_serializing_if = "is_false")]
        sealed_history: bool,
    },
    /// The recent output for one joining frontend, carried by `replay`,
    /// sealed end to end (bytes, a JSON array of numbers).
    ReplayData {
        /// The frontend it is for.
        frontend: u64,
        /// The sealed recent output.
        data: Vec<u8>,
    },
    /// Which registered machine says hello, carried by `machine_hello`.
    MachineId {
        /// The machine's ID, as the relay gave it at registration.
        machine: String,
        /// The relay protocol the machine's link speaks ([`PROTOCOL`]).
        #[serde(default = "first_protocol")]
        protocol: u16,
    },
    /// Bytes for a machine to sign, carried by `challenge`.
    Challenge {
        /// The challenge.
        nonce: Vec<u8>,
        /// The relay protocol the relay speaks (#95).
        #[serde(default = "first_protocol")]
        protocol: u16,
        /// The machine's account's key rotations, oldest first (#89): the
        /// machine follows those signed from the keys it pinned.
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        rotations: Vec<crate::account::KeyRotation>,
    },
    /// A machine's signature of its challenge, carried by `machine_proof`.
    Signature {
        /// The Ed25519 signature.
        signature: Vec<u8>,
    },
    /// A session's name and key, sealed to the account, carried by
    /// `session_record`.
    Record {
        /// The session's name, sealed to the account.
        sealed_name: Vec<u8>,
        /// The session's end-to-end secret, sealed to the account for its
        /// channel.
        sealed_key: Vec<u8>,
        /// The machine's signature of the record (#133,
        /// `account::record_bytes`).
        #[serde(default)]
        signature: Vec<u8>,
    },
    /// The channels of the sessions a machine runs, carried by
    /// `session_records_kept` (#134).
    RecordsKept {
        /// The channels that run.
        channels: Vec<String>,
        /// The relay sessions the link held before this one: their records
        /// of sessions not running go too.
        #[serde(default)]
        previous: Vec<SessionId>,
    },
    /// Error reason from the relay.
    ErrorReason {
        /// The reason.
        reason: String,
    },
}

/// What a machine signs to answer a challenge: this prefix, the challenge,
/// then its ID. The prefix keeps the signature from meaning anything else.
pub fn machine_proof_message(nonce: &[u8], machine: &str) -> Vec<u8> {
    let mut message = b"teter-machine-auth-v1 ".to_vec();
    message.extend_from_slice(nonce);
    message.extend_from_slice(machine.as_bytes());
    message
}

// --- Session-ending reasons ---

/// The `session_error` reason when the session's backend left: the session
/// is gone.
pub const BACKEND_LEFT: &str = "the backend left the session";

/// The `session_error` reason when a frontend's message finds its session
/// already removed: the session is gone.
pub const SESSION_GONE: &str = "the session is gone";

/// Whether a `session_error` reason says the session itself ended, as
/// opposed to an error about one connection or one message.
pub fn ends_the_session(reason: &str) -> bool {
    reason == BACKEND_LEFT || reason == SESSION_GONE
}

/// The longest channel ID, in bytes.
pub const MAX_CHANNEL: usize = 64;

/// Whether `channel` can be a channel ID: 1 to [`MAX_CHANNEL`] ASCII letters
/// or digits. Opaque: a backend picks it (a random ID per session), and it
/// never holds a session's name.
pub fn valid_channel(channel: &str) -> bool {
    !channel.is_empty()
        && channel.len() <= MAX_CHANNEL
        && channel.bytes().all(|b| b.is_ascii_alphanumeric())
}

impl Message {
    /// This message, on `channel`.
    #[must_use]
    pub fn on_channel(self, channel: Option<String>) -> Self {
        Self { channel, ..self }
    }
}

// --- Serialization helpers ---

/// The relay protocol this build speaks (#95): the version of the messages
/// between clients (backends, frontends) and the relay. A change a peer of
/// the version before cannot follow raises it.
pub const PROTOCOL: u16 = 3;

/// The oldest relay protocol a relay of this build accepts from a client.
pub const MIN_PROTOCOL: u16 = 2;

/// For serde: a flag left out when unset.
#[expect(
    clippy::trivially_copy_pass_by_ref,
    reason = "serde passes a reference"
)]
fn is_false(value: &bool) -> bool {
    !*value
}

/// What a client older than the protocol field speaks.
const fn first_protocol() -> u16 {
    1
}

/// Whether a client of this build works with a relay that speaks
/// `relay`: a relay serves its version and the one before, so one older than
/// this client is not.
///
/// # Errors
///
/// The refusal, naming both and what to upgrade.
pub fn check_relay_protocol(relay: u16) -> Result<(), String> {
    if relay < PROTOCOL {
        Err(format!(
            "the relay speaks relay protocol {relay}, older than this teter's {PROTOCOL}: upgrade \
             the relay"
        ))
    } else {
        Ok(())
    }
}

/// The relay protocol a first message `json` carries, read loosely before
/// the message is decoded (#95): a newer client's message may not decode
/// here, and it still says what to upgrade.
pub fn protocol_of(json: &str) -> Option<u16> {
    let value: serde_json::Value = serde_json::from_str(json).ok()?;
    let payload = value.get("payload")?.as_object()?;
    payload
        .values()
        .find_map(|inner| inner.get("protocol")?.as_u64())
        .and_then(|protocol| u16::try_from(protocol).ok())
}

/// Whether a relay that accepts `min..=max` serves a client of protocol
/// `client`; the refusal names both and what to upgrade.
///
/// # Errors
///
/// The refusal, for a client outside the range.
pub fn check_protocol(client: u16, min: u16, max: u16) -> Result<(), String> {
    if client > max {
        Err(format!(
            "this teter speaks relay protocol {client}, newer than the relay's {max}: upgrade the \
             relay"
        ))
    } else if client < min {
        Err(format!(
            "this teter speaks relay protocol {client}, older than the relay accepts ({min} to \
             {max}): upgrade teter"
        ))
    } else {
        Ok(())
    }
}

/// Serialize a [`Message`] to a JSON string.
pub fn serialize_message(msg: &Message) -> ProtocolResult<String> {
    serde_json::to_string(msg).map_err(ProtocolError::Serialization)
}

/// Deserialize a [`Message`] from a JSON string.
///
/// When decoding fails, the error says where:
/// [`ProtocolError::Deserialization`] for text that is not a JSON object or
/// whose `type` is not a string, [`ProtocolError::MissingType`] for a missing
/// or empty `type`, [`ProtocolError::UnknownType`], [`ProtocolError::InvalidSession`] or
/// [`ProtocolError::InvalidPayload`]. A message without the session its type
/// requires gives [`ProtocolError::MissingSession`].
pub fn deserialize_message(json: &str) -> ProtocolResult<Message> {
    // serde's derive also takes a struct as a JSON array; the protocol does not.
    if !json.trim_start().starts_with('{') {
        return Err(ProtocolError::Deserialization(
            <serde_json::Error as serde::de::Error>::custom("a message is a JSON object"),
        ));
    }
    let msg: Message = serde_json::from_str(json).map_err(|e| classify_decode_error(json, e))?;

    if msg.msg_type.requires_session() && msg.session.is_none() {
        return Err(ProtocolError::MissingSession);
    }
    if msg
        .channel
        .as_deref()
        .is_some_and(|channel| !valid_channel(channel))
    {
        return Err(ProtocolError::InvalidChannel);
    }

    Ok(msg)
}

/// Read `type` only from a JSON string, never from serde's other enum forms
/// (such as `{"ping": null}`).
fn message_type_from_str<'de, D>(deserializer: D) -> Result<MessageType, D::Error>
where
    D: serde::Deserializer<'de>,
{
    let name = std::borrow::Cow::<'de, str>::deserialize(deserializer)?;
    name.parse().map_err(serde::de::Error::custom)
}

/// Find which part of a message failed to decode. Runs only on the error
/// path, so valid messages are decoded once, straight into [`Message`].
/// The original error, which carries the position, is kept as the source.
fn classify_decode_error(json: &str, err: serde_json::Error) -> ProtocolError {
    let Ok(serde_json::Value::Object(fields)) = serde_json::from_str(json) else {
        return ProtocolError::Deserialization(err);
    };
    let type_ = match fields.get("type") {
        None => return ProtocolError::MissingType,
        Some(serde_json::Value::String(t)) if t.is_empty() => return ProtocolError::MissingType,
        Some(serde_json::Value::String(t)) => t,
        Some(_) => return ProtocolError::Deserialization(err),
    };
    if let Err(unknown) = type_.parse::<MessageType>() {
        return unknown;
    }
    if let Some(session) = fields.get("session")
        && serde_json::from_value::<Option<SessionId>>(session.clone()).is_err()
    {
        return ProtocolError::InvalidSession { source: err };
    }
    if let Some(payload) = fields.get("payload")
        && serde_json::from_value::<Option<MessagePayload>>(payload.clone()).is_err()
    {
        return ProtocolError::InvalidPayload {
            type_: type_.clone(),
            source: err,
        };
    }
    ProtocolError::Deserialization(err)
}

// --- Builders ---

impl Message {
    /// Create a new session creation message.
    pub fn session_create() -> Self {
        Self {
            msg_type: MessageType::SessionCreate,
            session: None,
            channel: None,
            payload: None,
        }
    }

    /// Create a session creation message from a backend that replays recent
    /// output to joining frontends.
    pub fn session_create_replaying() -> Self {
        Self {
            msg_type: MessageType::SessionCreate,
            session: None,
            channel: None,
            payload: Some(MessagePayload::SessionOptions { replay: true }),
        }
    }

    /// Create a new session join message.
    pub fn session_join(session: SessionId) -> Self {
        Self {
            msg_type: MessageType::SessionJoin,
            session: Some(session),
            channel: None,
            payload: None,
        }
    }

    /// Create a session join that asks for `history` lines of the session's
    /// history before its screen (#92), for a terminal of `rows` rows; with
    /// none asked, a plain join.
    pub fn session_join_with_history(session: SessionId, history: u32, rows: u16) -> Self {
        Self::session_join_with_options(session, history, rows, false)
    }

    /// As [`Self::session_join_with_history`], also taking the history the
    /// session kept on disk before a restart, sealed to the account, with
    /// `sealed_history` (#93).
    pub fn session_join_with_options(
        session: SessionId,
        history: u32,
        rows: u16,
        sealed_history: bool,
    ) -> Self {
        if history == 0 && !sealed_history {
            return Self::session_join(session);
        }
        Self {
            payload: Some(MessagePayload::JoinOptions {
                history,
                rows,
                sealed_history,
            }),
            ..Self::session_join(session)
        }
    }

    /// Create a session joined confirmation, as a frontend gets it.
    pub fn session_joined(session: SessionId, frontend_token: String) -> Self {
        Self {
            msg_type: MessageType::SessionJoined,
            session: Some(session),
            channel: None,
            payload: Some(MessagePayload::SessionCreated {
                session_id: session,
                frontend_token,
                resume_secret: None,
                protocol: PROTOCOL,
            }),
        }
    }

    /// Create a session joined confirmation for the backend that created or
    /// resumed the session, with its resume secret.
    pub fn session_created(
        session: SessionId,
        frontend_token: String,
        resume_secret: String,
    ) -> Self {
        Self {
            msg_type: MessageType::SessionJoined,
            session: Some(session),
            channel: None,
            payload: Some(MessagePayload::SessionCreated {
                session_id: session,
                frontend_token,
                resume_secret: Some(resume_secret),
                protocol: PROTOCOL,
            }),
        }
    }

    /// Create a session resume request.
    pub fn session_resume(session: SessionId, secret: String) -> Self {
        Self {
            msg_type: MessageType::SessionResume,
            session: Some(session),
            channel: None,
            payload: Some(MessagePayload::ResumeSecret { secret }),
        }
    }

    /// Create a notice to the backend that a frontend joined.
    pub fn frontend_joined(session: SessionId, frontend: u64, history: u32, rows: u16) -> Self {
        Self::frontend_joined_with(session, frontend, history, rows, false)
    }

    /// As [`Self::frontend_joined`], saying whether the frontend takes the
    /// history kept on disk, sealed to the account (#93).
    pub fn frontend_joined_with(
        session: SessionId,
        frontend: u64,
        history: u32,
        rows: u16,
        sealed_history: bool,
    ) -> Self {
        Self {
            msg_type: MessageType::FrontendJoined,
            session: Some(session),
            channel: None,
            payload: Some(MessagePayload::Frontend {
                frontend,
                history,
                rows,
                sealed_history,
            }),
        }
    }

    /// Create a replay of recent output for a joining frontend.
    pub fn replay(session: SessionId, frontend: u64, data: Vec<u8>) -> Self {
        Self {
            msg_type: MessageType::Replay,
            session: Some(session),
            channel: None,
            payload: Some(MessagePayload::ReplayData { frontend, data }),
        }
    }

    /// Create a notice that the session's backend dropped.
    pub fn backend_away(session: SessionId) -> Self {
        Self {
            msg_type: MessageType::BackendAway,
            session: Some(session),
            channel: None,
            payload: None,
        }
    }

    /// Create a notice that the session's backend is back.
    pub fn backend_back(session: SessionId) -> Self {
        Self {
            msg_type: MessageType::BackendBack,
            session: Some(session),
            channel: None,
            payload: None,
        }
    }

    /// Create a session left message.
    pub fn session_left(session: SessionId) -> Self {
        Self {
            msg_type: MessageType::SessionLeft,
            session: Some(session),
            channel: None,
            payload: None,
        }
    }

    /// Create a session error message; `session` is `None` for an error that
    /// comes before the connection has a session (a failed `auth`, say).
    pub fn session_error(session: Option<SessionId>, reason: String) -> Self {
        Self {
            msg_type: MessageType::SessionError,
            session,
            channel: None,
            payload: Some(MessagePayload::ErrorReason { reason }),
        }
    }

    /// Create an input (keyboard/mouse) message.
    pub fn input(session: SessionId, data: Vec<u8>) -> Self {
        Self {
            msg_type: MessageType::Input,
            session: Some(session),
            channel: None,
            payload: Some(MessagePayload::InputData { data, paste: false }),
        }
    }

    /// Create an input message for bytes inside a bracketed paste.
    pub fn paste_input(session: SessionId, data: Vec<u8>) -> Self {
        Self {
            msg_type: MessageType::Input,
            session: Some(session),
            channel: None,
            payload: Some(MessagePayload::InputData { data, paste: true }),
        }
    }

    /// Create an output (terminal) message.
    pub fn output(session: SessionId, data: Vec<u8>) -> Self {
        Self {
            msg_type: MessageType::Output,
            session: Some(session),
            channel: None,
            payload: Some(MessagePayload::OutputData { data }),
        }
    }

    /// Create a resize message carrying a sealed size.
    pub fn sealed_resize(session: SessionId, data: Vec<u8>) -> Self {
        Self {
            msg_type: MessageType::Resize,
            session: Some(session),
            channel: None,
            payload: Some(MessagePayload::Sealed { data }),
        }
    }

    /// Create a resize message with the size in clear.
    pub fn resize(session: SessionId, columns: u16, rows: u16) -> Self {
        Self {
            msg_type: MessageType::Resize,
            session: Some(session),
            channel: None,
            payload: Some(MessagePayload::Resize { columns, rows }),
        }
    }

    /// Create an authentication message carrying `token`.
    pub fn auth(token: String) -> Self {
        Self {
            msg_type: MessageType::Auth,
            session: None,
            channel: None,
            payload: Some(MessagePayload::AuthToken {
                token,
                protocol: PROTOCOL,
            }),
        }
    }

    /// Create a ping (keep-alive) message.
    pub fn ping() -> Self {
        Self {
            msg_type: MessageType::Ping,
            session: None,
            channel: None,
            payload: None,
        }
    }

    /// Create a pong (heartbeat response) message.
    pub fn pong() -> Self {
        Self {
            msg_type: MessageType::Pong,
            session: None,
            channel: None,
            payload: None,
        }
    }
}

/// An authenticated connection role on the relay.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Role {
    /// Backend service running on a home machine.
    Backend,
    /// Terminal emulator client (laptop, phone, web).
    Frontend,
}

impl FromStr for Role {
    type Err = ProtocolError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "backend" => Ok(Self::Backend),
            "frontend" => Ok(Self::Frontend),
            other => Err(ProtocolError::UnknownType(other.to_string())),
        }
    }
}

impl Role {
    /// Convert a role to its wire string identifier.
    pub fn to_str(&self) -> &'static str {
        match self {
            Self::Backend => "backend",
            Self::Frontend => "frontend",
        }
    }

    /// Parse a role from a string identifier, returning `None` for unknown values.
    pub fn parse_opt(s: &str) -> Option<Self> {
        s.parse().ok()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn roundtrip(msg: &Message) -> String {
        let json = serialize_message(msg).unwrap();
        let restored = deserialize_message(&json).unwrap();
        assert_eq!(*msg, restored);
        json
    }

    #[test]
    fn test_session_create_roundtrip() {
        let msg = Message::session_create();
        roundtrip(&msg);
    }

    #[test]
    fn test_session_join_roundtrip() {
        let sid = SessionId::new_v4();
        let msg = Message::session_join(sid);
        roundtrip(&msg);
    }

    #[test]
    fn test_session_joined_roundtrip() {
        let sid = SessionId::new_v4();
        let token = "test-token-123".to_string();
        let msg = Message::session_joined(sid, token.clone());
        roundtrip(&msg);

        if let Some(MessagePayload::SessionCreated {
            session_id,
            frontend_token,
            resume_secret,
            ..
        }) = &msg.payload
        {
            assert_eq!(*session_id, sid);
            assert_eq!(*frontend_token, token);
            assert_eq!(*resume_secret, None);
        } else {
            panic!("expected SessionCreated payload");
        }
        // A frontend's copy carries no resume secret on the wire.
        assert!(!serialize_message(&msg).unwrap().contains("resume_secret"));
    }

    #[test]
    fn test_replay_messages_roundtrip() {
        let sid = SessionId::new_v4();
        let create = Message::session_create_replaying();
        let json = roundtrip(&create);
        assert!(
            json.contains(r#"{"SessionOptions":{"replay":true}}"#),
            "{json}"
        );
        let joined = Message::frontend_joined(sid, 7, 0, 0);
        let json = roundtrip(&joined);
        assert!(json.contains(r#""type":"frontend_joined""#), "{json}");
        assert!(
            json.contains(r#"{"Frontend":{"frontend":7,"history":0,"rows":0}}"#),
            "{json}"
        );
        // A relay older than the field sends none: no history.
        let old = deserialize_message(
            r#"{"type":"frontend_joined","session":"7011b901-812b-4f0b-83bb-da42e6148c81","payload":{"Frontend":{"frontend":7}}}"#,
        )
        .unwrap();
        assert!(matches!(
            old.payload,
            Some(MessagePayload::Frontend {
                frontend: 7,
                history: 0,
                rows: 0,
                sealed_history: false
            })
        ));
        let replay = Message::replay(sid, 7, b"hi".to_vec());
        let json = roundtrip(&replay);
        assert!(
            json.contains(r#"{"ReplayData":{"frontend":7,"data":[104,105]}}"#),
            "{json}"
        );
        for (name, ty) in [
            ("frontend_joined", MessageType::FrontendJoined),
            ("replay", MessageType::Replay),
        ] {
            assert_eq!(name.parse::<MessageType>().unwrap(), ty);
            assert_eq!(ty.to_str(), name);
            assert!(ty.requires_session());
        }
    }

    #[test]
    fn test_resume_messages_roundtrip() {
        let sid = SessionId::new_v4();
        let created = Message::session_created(sid, "tok".into(), "sec".into());
        let json = roundtrip(&created);
        assert!(json.contains(r#""resume_secret":"sec""#), "{json}");
        let resume = Message::session_resume(sid, "sec".into());
        let json = roundtrip(&resume);
        assert!(json.contains(r#""type":"session_resume""#), "{json}");
        assert!(
            json.contains(r#"{"ResumeSecret":{"secret":"sec"}}"#),
            "{json}"
        );
        for msg in [Message::backend_away(sid), Message::backend_back(sid)] {
            let json = roundtrip(&msg);
            assert_eq!(deserialize_message(&json).unwrap(), msg);
        }
        for (name, ty) in [
            ("session_resume", MessageType::SessionResume),
            ("backend_away", MessageType::BackendAway),
            ("backend_back", MessageType::BackendBack),
        ] {
            assert_eq!(name.parse::<MessageType>().unwrap(), ty);
            assert_eq!(ty.to_str(), name);
            assert!(ty.requires_session());
        }
    }

    #[test]
    fn test_session_left_roundtrip() {
        let sid = SessionId::new_v4();
        let msg = Message::session_left(sid);
        roundtrip(&msg);
    }

    #[test]
    fn test_session_error_roundtrip() {
        let sid = SessionId::new_v4();
        let msg = Message::session_error(Some(sid), "connection lost".to_string());
        roundtrip(&msg);
    }

    #[test]
    fn test_input_roundtrip() {
        let sid = SessionId::new_v4();
        let data = vec![0x1b, 0x5b, 0x41]; // ESC [ A (up arrow)
        let msg = Message::input(sid, data.clone());
        roundtrip(&msg);

        if let Some(MessagePayload::InputData { data: received, .. }) = &msg.payload {
            assert_eq!(*received, data);
        } else {
            panic!("expected InputData payload");
        }
    }

    #[test]
    fn test_output_roundtrip() {
        let sid = SessionId::new_v4();
        let data = b"Hello, teter!\n".to_vec();
        let msg = Message::output(sid, data.clone());
        roundtrip(&msg);

        if let Some(MessagePayload::OutputData { data: received }) = &msg.payload {
            assert_eq!(*received, data);
        } else {
            panic!("expected OutputData payload");
        }
    }

    #[test]
    fn test_resize_roundtrip() {
        let sid = SessionId::new_v4();
        let msg = Message::resize(sid, 120, 40);
        roundtrip(&msg);

        if let Some(MessagePayload::Resize { columns, rows }) = &msg.payload {
            assert_eq!(*columns, 120);
            assert_eq!(*rows, 40);
        } else {
            panic!("expected Resize payload");
        }
    }

    #[test]
    fn paste_input_is_marked_and_plain_input_leaves_the_mark_out() {
        let sid = SessionId::new_v4();
        let paste = Message::paste_input(sid, vec![1, 2]);
        roundtrip(&paste);
        let json = serialize_message(&paste).unwrap();
        assert!(
            json.contains(r#"{"InputData":{"data":[1,2],"paste":true}}"#),
            "{json}"
        );
        let plain = Message::input(sid, vec![1, 2]);
        let json = serialize_message(&plain).unwrap();
        assert!(json.contains(r#"{"InputData":{"data":[1,2]}}"#), "{json}");
        // A message without the mark reads as not paste.
        let read = deserialize_message(&json).unwrap();
        assert_eq!(
            read.payload,
            Some(MessagePayload::InputData {
                data: vec![1, 2],
                paste: false
            })
        );
    }

    #[test]
    fn a_sealed_resize_roundtrips() {
        let sid = SessionId::new_v4();
        let msg = Message::sealed_resize(sid, vec![1, 2, 255]);
        roundtrip(&msg);
        assert_eq!(msg.msg_type, MessageType::Resize);
        assert_eq!(msg.session, Some(sid));
        assert_eq!(
            msg.payload,
            Some(MessagePayload::Sealed {
                data: vec![1, 2, 255]
            })
        );
        let json = serialize_message(&msg).unwrap();
        assert!(
            json.contains(r#""payload":{"Sealed":{"data":[1,2,255]}}"#),
            "{json}"
        );
    }

    #[test]
    fn test_ping_roundtrip() {
        let msg = Message::ping();
        roundtrip(&msg);
    }

    #[test]
    fn test_pong_roundtrip() {
        let msg = Message::pong();
        roundtrip(&msg);
    }

    #[test]
    fn test_message_type_from_str() {
        assert_eq!(MessageType::from_str("input").unwrap(), MessageType::Input);
        assert_eq!(
            MessageType::from_str("session_create").unwrap(),
            MessageType::SessionCreate
        );
        assert!(MessageType::from_str("unknown_type").is_err());
    }

    #[test]
    fn test_message_type_to_str() {
        assert_eq!(MessageType::Input.to_str(), "input");
        assert_eq!(MessageType::Output.to_str(), "output");
        assert_eq!(MessageType::Resize.to_str(), "resize");
        assert_eq!(MessageType::Ping.to_str(), "ping");
    }

    #[test]
    fn test_requires_session() {
        assert!(!MessageType::Ping.requires_session());
        assert!(!MessageType::Pong.requires_session());
        assert!(MessageType::Input.requires_session());
        assert!(MessageType::Output.requires_session());
        assert!(!MessageType::Auth.requires_session());
        assert!(!MessageType::SessionError.requires_session());
        assert!(MessageType::SessionJoin.requires_session());
    }

    #[test]
    fn the_protocol_is_read_from_a_first_message_that_does_not_decode() {
        assert_eq!(
            protocol_of(r#"{"type":"auth","payload":{"AuthToken":{"protocol":7}}}"#),
            Some(7)
        );
        assert_eq!(protocol_of(r#"{"type":"ping"}"#), None);
        assert_eq!(protocol_of("not json"), None);
        assert!(check_relay_protocol(PROTOCOL).is_ok());
    }

    #[test]
    fn protocols_outside_the_range_say_what_to_upgrade() {
        assert_eq!(check_protocol(2, 1, 2), Ok(()));
        assert!(
            check_protocol(3, 1, 2)
                .unwrap_err()
                .contains("upgrade the relay")
        );
        assert!(
            check_protocol(0, 1, 2)
                .unwrap_err()
                .contains("upgrade teter")
        );
    }

    #[test]
    fn test_auth_roundtrip() {
        let json = roundtrip(&Message::auth("secret".to_string()));
        assert_eq!(
            json,
            r#"{"type":"auth","payload":{"AuthToken":{"token":"secret","protocol":3}}}"#
        );
        // A client older than the field speaks protocol 1 (#95).
        let old = deserialize_message(r#"{"type":"auth","payload":{"AuthToken":{"token":"t"}}}"#)
            .unwrap();
        assert_eq!(
            old.payload,
            Some(MessagePayload::AuthToken {
                token: "t".to_owned(),
                protocol: 1
            })
        );
        assert_eq!("auth".parse::<MessageType>().unwrap(), MessageType::Auth);
        assert_eq!(MessageType::Auth.to_str(), "auth");
    }

    #[test]
    fn test_session_error_without_session_roundtrip() {
        let json = roundtrip(&Message::session_error(
            None,
            "authentication failed".to_string(),
        ));
        assert!(!json.contains("session\""), "{json}");
    }

    #[test]
    fn test_missing_session_rejected() {
        // A message without a session field that requires one should fail.
        let json = r#"{"type":"input"}"#;
        assert!(matches!(
            deserialize_message(json),
            Err(ProtocolError::MissingSession)
        ));
    }

    #[test]
    fn test_missing_type_rejected() {
        let json = r#"{"session":"00000000-0000-0000-0000-000000000000"}"#;
        assert!(deserialize_message(json).is_err());
    }

    const SID: &str = "00000000-0000-0000-0000-000000000000";

    fn invalid_payload_type(json: &str) -> String {
        match deserialize_message(json) {
            Err(ProtocolError::InvalidPayload { type_, .. }) => type_,
            other => panic!("expected InvalidPayload, got {other:?}"),
        }
    }

    #[test]
    fn test_invalid_payload_names_the_type() {
        let json = format!(
            r#"{{"type":"resize","session":"{SID}","payload":{{"Resize":{{"columns":"wide","rows":24}}}}}}"#
        );
        assert_eq!(invalid_payload_type(&json), "resize");
    }

    #[test]
    fn test_invalid_payload_type_with_whitespace() {
        let json = format!(
            r#"{{ "session" : "{SID}", "payload" : {{ "InputData" : {{ "data" : "x" }} }}, "type" : "input" }}"#
        );
        assert_eq!(invalid_payload_type(&json), "input");
    }

    #[test]
    fn test_not_a_message_gives_deserialization_error() {
        for json in [
            "[1, 2]".to_string(),
            "not json".to_string(),
            format!(r#"{{"type":5,"session":"{SID}"}}"#),
        ] {
            let err = deserialize_message(&json).unwrap_err();
            assert!(
                matches!(err, ProtocolError::Deserialization(_)),
                "{json}: {err:?}"
            );
            assert!(err.to_string().starts_with("failed to decode"), "{err}");
        }
    }

    #[test]
    fn test_missing_or_empty_type_gives_missing_type() {
        for json in [
            format!(r#"{{"session":"{SID}"}}"#),
            format!(r#"{{"type":"","session":"{SID}"}}"#),
        ] {
            assert!(
                matches!(deserialize_message(&json), Err(ProtocolError::MissingType)),
                "{json}"
            );
        }
    }

    #[test]
    fn test_unknown_type_gives_unknown_type() {
        let json = format!(r#"{{"type":"bogus","session":"{SID}"}}"#);
        assert!(matches!(
            deserialize_message(&json),
            Err(ProtocolError::UnknownType(t)) if t == "bogus"
        ));
    }

    #[test]
    fn test_bad_session_names_the_session() {
        for json in [
            r#"{"type":"input","session":"not-a-uuid","payload":{"InputData":{"data":[1]}}}"#,
            r#"{"type":"input","session":5,"payload":{"InputData":{"data":[1]}}}"#,
        ] {
            let err = deserialize_message(json).unwrap_err();
            assert!(
                matches!(err, ProtocolError::InvalidSession { .. }),
                "{json}: {err:?}"
            );
            assert!(err.to_string().contains("session"), "{err}");
        }
    }

    #[test]
    fn test_non_canonical_forms_are_rejected() {
        for json in [
            r#"["ping"]"#,
            r#"["input","00000000-0000-0000-0000-000000000000"]"#,
            r#"["ping",null,null]"#,
            r#"{"type":{"ping":null}}"#,
        ] {
            assert!(
                matches!(
                    deserialize_message(json),
                    Err(ProtocolError::Deserialization(_))
                ),
                "{json}"
            );
        }
    }

    #[test]
    fn test_decode_error_keeps_position() {
        let json = format!(
            r#"{{"type":"resize","session":"{SID}","payload":{{"Resize":{{"columns":"wide","rows":24}}}}}}"#
        );
        match deserialize_message(&json) {
            Err(ProtocolError::InvalidPayload { source, .. }) => {
                assert_eq!(source.line(), 1);
                assert!(source.column() > 0);
            }
            other => panic!("expected InvalidPayload, got {other:?}"),
        }
    }

    #[test]
    fn test_null_fields_are_absent() {
        let json = r#"{"type":"ping","session":null,"payload":null}"#;
        assert_eq!(deserialize_message(json).unwrap(), Message::ping());
    }

    #[test]
    fn test_only_the_session_ending_reasons_end_the_session() {
        assert!(ends_the_session(BACKEND_LEFT));
        assert!(ends_the_session(SESSION_GONE));
        assert!(!ends_the_session("silent past the heartbeat timeout"));
        assert!(!ends_the_session(""));
    }

    #[test]
    fn test_io_flag() {
        assert!(MessageType::Input.is_io());
        assert!(MessageType::Output.is_io());
        assert!(!MessageType::Resize.is_io());
        assert!(!MessageType::Ping.is_io());
    }

    #[test]
    fn test_role_to_from_str() {
        assert_eq!(Role::Backend.to_str(), "backend");
        assert_eq!(Role::Frontend.to_str(), "frontend");
        assert_eq!(Role::parse_opt("backend"), Some(Role::Backend));
        assert_eq!(Role::parse_opt("frontend"), Some(Role::Frontend));
        assert_eq!(Role::parse_opt("unknown"), None);
    }

    #[test]
    fn test_role_from_str_trait() {
        assert_eq!("backend".parse::<Role>().unwrap(), Role::Backend);
        assert_eq!("frontend".parse::<Role>().unwrap(), Role::Frontend);
        assert!("unknown".parse::<Role>().is_err());
    }

    #[test]
    fn test_auth_token_roundtrip() {
        let msg = Message {
            msg_type: MessageType::SessionCreate,
            session: None,
            channel: None,
            payload: Some(MessagePayload::AuthToken {
                token: "backend-secret-token".to_string(),
                protocol: PROTOCOL,
            }),
        };
        roundtrip(&msg);
    }

    #[test]
    fn test_error_reason_roundtrip() {
        let sid = SessionId::new_v4();
        let msg = Message {
            msg_type: MessageType::SessionError,
            session: Some(sid),
            channel: None,
            payload: Some(MessagePayload::ErrorReason {
                reason: "relay overload".to_string(),
            }),
        };
        roundtrip(&msg);
    }

    #[test]
    fn test_session_id_generation() {
        let id1 = SessionId::new_v4();
        let id2 = SessionId::new_v4();
        assert_ne!(id1, id2);
    }

    #[test]
    fn a_channel_travels_and_one_that_is_not_an_opaque_id_is_refused() {
        let msg = Message::output(SessionId::nil(), vec![1]).on_channel(Some("a1B2".into()));
        let json = serialize_message(&msg).unwrap();
        assert!(json.contains(r#""channel":"a1B2""#), "{json}");
        assert_eq!(deserialize_message(&json).unwrap(), msg);
        // Left out when there is none.
        let plain = serialize_message(&Message::output(SessionId::nil(), vec![1])).unwrap();
        assert!(!plain.contains("channel"), "{plain}");
        for bad in ["", "my session", "a/b", &"x".repeat(MAX_CHANNEL + 1)] {
            let json = serialize_message(
                &Message::session_join(SessionId::nil()).on_channel(Some(bad.to_owned())),
            )
            .unwrap();
            assert!(
                matches!(
                    deserialize_message(&json),
                    Err(ProtocolError::InvalidChannel)
                ),
                "{bad:?}"
            );
        }
        assert!(valid_channel(&"f".repeat(MAX_CHANNEL)));
    }
}