teter-core 26.11.6

What teter's clients share without I/O: end-to-end encryption, account crypto, signed commands
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
//! End-to-end encryption between backend and frontend: the relay forwards
//! terminal data it cannot read. See `docs/architecture.md`, "End-to-end
//! encryption", for the design.
//!
//! The backend makes a [`Secret`] and prints it; the user gives it to the
//! frontend, and it never goes to the relay. Both derive [`Keys`] from it and
//! the session ID, one key per direction. A [`Sealer`] seals what one side
//! sends, an [`Opener`] opens what the other side sent and refuses anything
//! forged, altered, or seen before.

use std::collections::HashMap;
use std::fmt;

use chacha20poly1305::aead::{Aead, KeyInit, Payload};
use chacha20poly1305::{XChaCha20Poly1305, XNonce};
use hkdf::Hkdf;
use sha2::Sha256;
use teter_common::SessionId;
use zeroize::Zeroizing;

/// The version byte that starts every sealed message.
const VERSION: u8 = 1;
/// Bound into every message, so nothing sealed here passes for anything else.
const CONTEXT: &[u8] = b"teter-e2e-v1";
const SENDER_LEN: usize = 16;
const SEQ_LEN: usize = 8;
const HEADER_LEN: usize = 1 + SENDER_LEN + SEQ_LEN;
const TAG_LEN: usize = 16;
/// Senders an [`Opener`] takes; past that, a new sender is refused. A sender
/// is never forgotten, or the relay could replay what it had sent: a
/// session's frontends, every run of each, must stay under this.
const MAX_SENDERS: usize = 4096;

/// The session's shared secret: 32 random bytes, printed by the backend as
/// 64 hex digits. Never logged: its `Debug` hides it.
#[derive(Clone, PartialEq, Eq)]
pub struct Secret(Zeroizing<[u8; 32]>);

impl Secret {
    /// A new random secret.
    pub fn generate() -> std::io::Result<Self> {
        let mut bytes = Zeroizing::new([0u8; 32]);
        getrandom::fill(bytes.as_mut()).map_err(std::io::Error::other)?;
        Ok(Self(bytes))
    }

    /// The secret from its 64 hex digits (either case; whitespace and
    /// dashes are ignored, so a secret copied in groups, or read as a line,
    /// still reads).
    #[expect(
        clippy::indexing_slicing,
        reason = "fixed-size buffers: the header's length is checked before it is cut, and hex digits come in pairs of a 64-digit secret"
    )]
    pub fn parse(text: &str) -> Result<Self, InvalidSecret> {
        // Its room reserved at once: growing would leave copies behind.
        let mut digits = Zeroizing::new(Vec::with_capacity(text.len()));
        digits.extend(
            text.bytes()
                .filter(|b| !b.is_ascii_whitespace() && *b != b'-'),
        );
        if digits.len() != 64 {
            return Err(InvalidSecret);
        }
        let mut bytes = Zeroizing::new([0u8; 32]);
        for (byte, pair) in bytes.iter_mut().zip(digits.chunks(2)) {
            // `* 16 +` rather than `<< 4 |`: the same byte, but `|` mutated
            // to `^` gives the same byte too, so no test could catch it.
            *byte = hex_value(pair[0])? * 16 + hex_value(pair[1])?;
        }
        Ok(Self(bytes))
    }

    /// The secret as 64 lowercase hex digits, to print for the user. Named
    /// so that showing it is never an accident.
    #[expect(
        clippy::indexing_slicing,
        reason = "fixed-size buffers: the header's length is checked before it is cut, and hex digits come in pairs of a 64-digit secret"
    )]
    pub fn reveal(&self) -> Zeroizing<String> {
        let mut text = Zeroizing::new(String::with_capacity(64));
        for byte in self.0.iter() {
            text.push(char::from(HEX[usize::from(byte >> 4)]));
            text.push(char::from(HEX[usize::from(byte & 0xf)]));
        }
        text
    }
}

impl fmt::Debug for Secret {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("Secret(..)")
    }
}

const HEX: &[u8; 16] = b"0123456789abcdef";

fn hex_value(digit: u8) -> Result<u8, InvalidSecret> {
    match digit {
        b'0'..=b'9' => Ok(digit - b'0'),
        b'a'..=b'f' => Ok(digit - b'a' + 10),
        b'A'..=b'F' => Ok(digit - b'A' + 10),
        _ => Err(InvalidSecret),
    }
}

/// A secret that is not 64 hex digits.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InvalidSecret;

impl fmt::Display for InvalidSecret {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("the secret is not 64 hex digits")
    }
}

impl std::error::Error for InvalidSecret {}

/// Which way a message goes: each way has its own key.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Direction {
    /// Frontend to backend: `input` and `resize`.
    ToBackend,
    /// Backend to frontend: `output`, and `replay`, which reaches the
    /// frontend as `output`.
    ToFrontend,
}

/// What a sealed message holds, bound into it: a relay cannot pass one kind
/// off as another.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Kind {
    /// Keyboard and mouse input.
    Input,
    /// A terminal size.
    Resize,
    /// Terminal output.
    Output,
    /// Input inside a bracketed paste.
    Paste,
    /// A replay with the history a session kept on disk before it started
    /// again (#93), for a frontend that asked for it
    /// ([`crate::history::encode_replay`]).
    History,
}

impl Kind {
    fn byte(self) -> u8 {
        match self {
            Self::Input => 1,
            Self::Resize => 2,
            Self::Output => 3,
            Self::Paste => 4,
            Self::History => 5,
        }
    }
}

/// The session's two keys, derived from the secret and the session ID.
pub struct Keys {
    session: SessionId,
    to_backend: Zeroizing<[u8; 32]>,
    to_frontend: Zeroizing<[u8; 32]>,
}

impl Keys {
    /// HKDF-SHA256 over the secret, salted with the session ID, one key per
    /// direction: the keys of a session carried alone in its relay session.
    pub fn derive(secret: &Secret, session: SessionId) -> Self {
        Self::derive_with(secret, session, None)
    }

    /// [`Keys::derive`], for one channel of a relay session that carries
    /// several (`channel`, the session's opaque channel ID): the channel is
    /// in the HKDF info, so a message moved to another channel, or to the
    /// session as a whole, does not open, even under the same secret.
    pub fn derive_on(secret: &Secret, session: SessionId, channel: &str) -> Self {
        Self::derive_with(secret, session, Some(channel))
    }

    #[expect(
        clippy::expect_used,
        reason = "fixed-size slices of a header whose length was checked, and an AEAD key of the length the cipher takes"
    )]
    fn derive_with(secret: &Secret, session: SessionId, channel: Option<&str>) -> Self {
        let hkdf = Hkdf::<Sha256>::new(Some(session.as_bytes()), secret.0.as_ref());
        let key = |direction: &[u8]| {
            let mut info = direction.to_vec();
            if let Some(channel) = channel {
                info.extend_from_slice(b" on channel ");
                info.extend_from_slice(channel.as_bytes());
            }
            let mut key = Zeroizing::new([0u8; 32]);
            hkdf.expand(&info, key.as_mut())
                .expect("32 bytes is a valid HKDF-SHA256 length");
            key
        };
        Self {
            session,
            to_backend: key(b"teter-e2e-v1 frontend to backend"),
            to_frontend: key(b"teter-e2e-v1 backend to frontend"),
        }
    }

    fn cipher(&self, direction: Direction) -> XChaCha20Poly1305 {
        let key = match direction {
            Direction::ToBackend => &self.to_backend,
            Direction::ToFrontend => &self.to_frontend,
        };
        XChaCha20Poly1305::new(key.as_ref().into())
    }

    /// A sealer for what this side sends `direction`.
    pub fn sealer(&self, direction: Direction) -> std::io::Result<Sealer> {
        let mut sender = [0u8; SENDER_LEN];
        getrandom::fill(&mut sender).map_err(std::io::Error::other)?;
        Ok(Sealer {
            cipher: self.cipher(direction),
            session: self.session,
            sender,
            next: 0,
        })
    }

    /// An opener for what the other side sends `direction`.
    pub fn opener(&self, direction: Direction) -> Opener {
        Opener {
            cipher: self.cipher(direction),
            session: self.session,
            last: HashMap::new(),
            refused: std::collections::HashSet::new(),
            newly_refused: false,
        }
    }
}

impl fmt::Debug for Keys {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Keys")
            .field("session", &self.session)
            .finish_non_exhaustive()
    }
}

/// The associated data of a message: what it is bound to besides its
/// header.
fn associated(session: SessionId, kind: Kind, header: &[u8]) -> Vec<u8> {
    let mut aad = Vec::with_capacity(CONTEXT.len() + 16 + 1 + header.len());
    aad.extend_from_slice(CONTEXT);
    aad.extend_from_slice(session.as_bytes());
    aad.push(kind.byte());
    aad.extend_from_slice(header);
    aad
}

/// Who sealed a message: the random ID of one sealer.
pub type SenderId = [u8; SENDER_LEN];

/// Seals what one side sends one way. Each message gets the next number;
/// with the sender's random ID, it makes the nonce, which is so never used
/// twice with the key.
pub struct Sealer {
    cipher: XChaCha20Poly1305,
    session: SessionId,
    sender: [u8; SENDER_LEN],
    next: u64,
}

impl Sealer {
    /// `plaintext` sealed as `kind`: version, sender, number, then the
    /// ciphertext with its tag.
    #[expect(
        clippy::expect_used,
        reason = "fixed-size slices of a header whose length was checked, and an AEAD key of the length the cipher takes"
    )]
    pub fn seal(&mut self, kind: Kind, plaintext: &[u8]) -> Vec<u8> {
        let seq = self.next;
        self.next = seq.checked_add(1).expect("2^64 messages from one sender");
        let mut header = [0u8; HEADER_LEN];
        header[0] = VERSION;
        header[1..1 + SENDER_LEN].copy_from_slice(&self.sender);
        header[1 + SENDER_LEN..].copy_from_slice(&seq.to_be_bytes());
        let nonce = XNonce::from_slice(&header[1..]);
        let aad = associated(self.session, kind, &header);
        let sealed = self
            .cipher
            .encrypt(
                nonce,
                Payload {
                    msg: plaintext,
                    aad: &aad,
                },
            )
            .expect("XChaCha20-Poly1305 seals any length a message can have");
        let mut out = Vec::with_capacity(HEADER_LEN + sealed.len());
        out.extend_from_slice(&header);
        out.extend_from_slice(&sealed);
        out
    }
}

impl fmt::Debug for Sealer {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Sealer")
            .field("session", &self.session)
            .finish_non_exhaustive()
    }
}

/// Why a sealed message was refused.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OpenError {
    /// Too short, or of an unknown version.
    Malformed,
    /// It does not open with the key: sealed with another secret or for
    /// another session, altered, or of another kind.
    Forged,
    /// Its number is not past the last one from its sender: seen before, or
    /// older than one already opened.
    Replayed,
    /// From a new sender, past the senders an opener takes.
    TooManySenders,
}

impl fmt::Display for OpenError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::Malformed => "a sealed message is malformed",
            Self::Forged => "a sealed message does not open: another secret, or altered",
            Self::Replayed => "a sealed message was seen before",
            Self::TooManySenders => "too many senders in this session",
        })
    }
}

impl std::error::Error for OpenError {}

/// Opens what the other side sends one way. It keeps the last number from
/// each sender and takes only later ones: the relay can drop or delay
/// messages, never replay or reorder them unnoticed.
pub struct Opener {
    cipher: XChaCha20Poly1305,
    session: SessionId,
    last: HashMap<[u8; SENDER_LEN], u64>,
    /// New senders refused, past the senders it takes, up to a bound.
    refused: std::collections::HashSet<[u8; SENDER_LEN]>,
    /// Whether a sender was refused for the first time since last asked.
    newly_refused: bool,
}

impl Opener {
    /// The plaintext of `sealed`, a message of `kind`.
    pub fn open(&mut self, kind: Kind, sealed: &[u8]) -> Result<Zeroizing<Vec<u8>>, OpenError> {
        self.open_from(kind, sealed).map(|(plaintext, _)| plaintext)
    }

    /// The plaintext of `sealed`, a message of `kind`, and who sent it.
    #[expect(
        clippy::indexing_slicing,
        clippy::expect_used,
        clippy::map_err_ignore,
        reason = "fixed-size buffers: the header's length is checked before it is cut, and hex digits come in pairs of a 64-digit secret; fixed-size slices of a header whose length was checked, and an AEAD key of the length the cipher takes; AEAD failure carries no cause on purpose: a forgery and a corruption must look alike"
    )]
    pub fn open_from(
        &mut self,
        kind: Kind,
        sealed: &[u8],
    ) -> Result<(Zeroizing<Vec<u8>>, SenderId), OpenError> {
        if sealed.len() < HEADER_LEN + TAG_LEN || sealed[0] != VERSION {
            return Err(OpenError::Malformed);
        }
        let (header, body) = sealed.split_at(HEADER_LEN);
        let sender: [u8; SENDER_LEN] = header[1..1 + SENDER_LEN].try_into().expect("16 bytes");
        let seq = u64::from_be_bytes(header[1 + SENDER_LEN..].try_into().expect("8 bytes"));
        if self.last.get(&sender).is_some_and(|&last| seq <= last) {
            return Err(OpenError::Replayed);
        }
        let aad = associated(self.session, kind, header);
        let plaintext = self
            .cipher
            .decrypt(
                XNonce::from_slice(&header[1..]),
                Payload {
                    msg: body,
                    aad: &aad,
                },
            )
            .map_err(|_| OpenError::Forged)?;
        // Only once it opened: a forgery moves nothing.
        if !self.last.contains_key(&sender) && self.last.len() >= MAX_SENDERS {
            if self.refused.len() < MAX_SENDERS && self.refused.insert(sender) {
                self.newly_refused = true;
            }
            return Err(OpenError::TooManySenders);
        }
        self.last.insert(sender, seq);
        Ok((Zeroizing::new(plaintext), sender))
    }
}

impl Opener {
    /// Whether a sender has been refused for the first time since this was
    /// last asked: each refused sender counts once.
    pub fn take_newly_refused(&mut self) -> bool {
        std::mem::take(&mut self.newly_refused)
    }
}

impl fmt::Debug for Opener {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Opener")
            .field("session", &self.session)
            .finish_non_exhaustive()
    }
}

/// A terminal size as the plaintext of a sealed `resize`: columns, then
/// rows, big-endian.
pub fn encode_size(columns: u16, rows: u16) -> [u8; 4] {
    let [c0, c1] = columns.to_be_bytes();
    let [r0, r1] = rows.to_be_bytes();
    [c0, c1, r0, r1]
}

/// The size in a sealed `resize`'s plaintext, if it is one.
pub fn decode_size(plaintext: &[u8]) -> Option<(u16, u16)> {
    let [c0, c1, r0, r1] = plaintext.try_into().ok()?;
    Some((u16::from_be_bytes([c0, c1]), u16::from_be_bytes([r0, r1])))
}

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

    fn pair() -> (Keys, Keys) {
        let secret = Secret::generate().unwrap();
        let session = SessionId::new_v4();
        let backend = Keys::derive(&secret, session);
        let frontend = Keys::derive(&Secret::parse(&secret.reveal()).unwrap(), session);
        (backend, frontend)
    }

    #[test]
    fn a_secret_round_trips_through_its_text() {
        let secret = Secret::generate().unwrap();
        let text = secret.reveal();
        assert_eq!(text.len(), 64);
        assert!(text.bytes().all(|b| HEX.contains(&b)));
        assert_eq!(Secret::parse(&text).unwrap(), secret);
        // Upper case, and grouped with spaces or dashes.
        assert_eq!(Secret::parse(&text.to_uppercase()).unwrap(), secret);
        let grouped: String = text
            .as_bytes()
            .chunks(8)
            .map(|c| std::str::from_utf8(c).unwrap())
            .collect::<Vec<_>>()
            .join("-");
        assert_eq!(Secret::parse(&grouped).unwrap(), secret);
        // Read as a line, with its end.
        assert_eq!(Secret::parse(&format!(" {}\r\n", *text)).unwrap(), secret);
        assert_eq!(Secret::parse(&format!("{}\t", *text)).unwrap(), secret);
        assert_ne!(Secret::generate().unwrap(), secret);
    }

    #[test]
    fn a_secret_that_is_not_64_hex_digits_is_refused() {
        assert_eq!(Secret::parse(""), Err(InvalidSecret));
        assert_eq!(Secret::parse(&"a".repeat(63)), Err(InvalidSecret));
        assert_eq!(Secret::parse(&"a".repeat(65)), Err(InvalidSecret));
        assert_eq!(Secret::parse(&"g".repeat(64)), Err(InvalidSecret));
        assert_eq!(
            Secret::parse(&format!("{}G", "a".repeat(63))),
            Err(InvalidSecret)
        );
        // Each digit's value counts.
        let secret = Secret::parse(&format!("0f{}", "0".repeat(62))).unwrap();
        assert!(secret.reveal().starts_with("0f00"));
        let secret = Secret::parse(&format!("A9{}", "0".repeat(62))).unwrap();
        assert!(secret.reveal().starts_with("a900"));
    }

    #[test]
    fn nothing_secret_shows_in_debug() {
        let secret = Secret::parse(&"ab".repeat(32)).unwrap();
        assert_eq!(format!("{secret:?}"), "Secret(..)");
        let keys = Keys::derive(&secret, SessionId::nil());
        let shown = format!(
            "{keys:?} {:?} {:?}",
            keys.sealer(Direction::ToBackend).unwrap(),
            keys.opener(Direction::ToBackend)
        );
        assert!(!shown.contains("ab"), "{shown}");
        assert!(!shown.contains("171"), "{shown}");
        for name in ["Keys", "Sealer", "Opener"] {
            assert!(shown.contains(name), "{shown}");
        }
        // The errors say what went wrong.
        assert!(InvalidSecret.to_string().contains("64 hex digits"));
        assert!(OpenError::Forged.to_string().contains("another secret"));
        assert!(OpenError::Replayed.to_string().contains("seen before"));
        assert!(OpenError::Malformed.to_string().contains("malformed"));
        assert!(
            OpenError::TooManySenders
                .to_string()
                .contains("too many senders")
        );
    }

    #[test]
    fn what_one_side_seals_the_other_opens() {
        let (backend, frontend) = pair();
        let mut sealer = frontend.sealer(Direction::ToBackend).unwrap();
        let mut opener = backend.opener(Direction::ToBackend);
        let sealed = sealer.seal(Kind::Input, b"hunter2\r");
        assert_eq!(sealed.len(), HEADER_LEN + 8 + TAG_LEN);
        assert!(!sealed.windows(7).any(|w| w == b"hunter2"));
        assert_eq!(
            &opener.open(Kind::Input, &sealed).unwrap()[..],
            b"hunter2\r"
        );
        // And the other way, with the other key.
        let mut sealer = backend.sealer(Direction::ToFrontend).unwrap();
        let mut opener = frontend.opener(Direction::ToFrontend);
        let sealed = sealer.seal(Kind::Output, b"$ ");
        assert_eq!(&opener.open(Kind::Output, &sealed).unwrap()[..], b"$ ");
        // Empty plaintext seals too.
        let sealed = sealer.seal(Kind::Output, b"");
        assert_eq!(&opener.open(Kind::Output, &sealed).unwrap()[..], b"");
    }

    #[test]
    fn the_same_plaintext_never_seals_the_same() {
        let (backend, _) = pair();
        let mut sealer = backend.sealer(Direction::ToFrontend).unwrap();
        let a = sealer.seal(Kind::Output, b"same");
        let b = sealer.seal(Kind::Output, b"same");
        assert_ne!(a[HEADER_LEN..], b[HEADER_LEN..]);
        let mut other = backend.sealer(Direction::ToFrontend).unwrap();
        assert_ne!(
            a[1..1 + SENDER_LEN],
            other.seal(Kind::Output, b"same")[1..1 + SENDER_LEN]
        );
    }

    #[test]
    fn a_wrong_secret_another_session_or_direction_does_not_open() {
        let (backend, _) = pair();
        let mut sealer = backend.sealer(Direction::ToFrontend).unwrap();
        let sealed = sealer.seal(Kind::Output, b"screen");
        let other = Keys::derive(&Secret::generate().unwrap(), backend.session);
        assert_eq!(
            other
                .opener(Direction::ToFrontend)
                .open(Kind::Output, &sealed),
            Err(OpenError::Forged)
        );
        let secret = Secret::parse(&"11".repeat(32)).unwrap();
        let here = Keys::derive(&secret, SessionId::new_v4());
        let elsewhere = Keys::derive(&secret, SessionId::new_v4());
        let sealed = here
            .sealer(Direction::ToFrontend)
            .unwrap()
            .seal(Kind::Output, b"x");
        assert_eq!(
            elsewhere
                .opener(Direction::ToFrontend)
                .open(Kind::Output, &sealed),
            Err(OpenError::Forged)
        );
        // Sealed one way, opened as the other.
        assert_eq!(
            here.opener(Direction::ToBackend)
                .open(Kind::Output, &sealed),
            Err(OpenError::Forged)
        );
    }

    #[test]
    fn an_altered_message_or_one_of_another_kind_does_not_open() {
        let (backend, frontend) = pair();
        let mut sealer = frontend.sealer(Direction::ToBackend).unwrap();
        let mut opener = backend.opener(Direction::ToBackend);
        let sealed = sealer.seal(Kind::Input, b"ls\r");
        for at in 1..sealed.len() {
            let mut altered = sealed.clone();
            altered[at] ^= 1;
            assert!(opener.open(Kind::Input, &altered).is_err(), "byte {at}");
        }
        assert_eq!(opener.open(Kind::Resize, &sealed), Err(OpenError::Forged));
        // The original still opens: refusals moved nothing.
        assert!(opener.open(Kind::Input, &sealed).is_ok());
    }

    #[test]
    fn a_malformed_message_is_refused() {
        let (backend, _) = pair();
        let mut opener = backend.opener(Direction::ToBackend);
        assert_eq!(opener.open(Kind::Input, b""), Err(OpenError::Malformed));
        assert_eq!(
            opener.open(Kind::Input, &[VERSION; HEADER_LEN + TAG_LEN - 1]),
            Err(OpenError::Malformed)
        );
        let mut sealed = backend
            .sealer(Direction::ToBackend)
            .unwrap()
            .seal(Kind::Input, b"");
        assert_eq!(sealed.len(), HEADER_LEN + TAG_LEN);
        assert!(
            backend
                .opener(Direction::ToBackend)
                .open(Kind::Input, &sealed)
                .is_ok()
        );
        sealed[0] = 2;
        assert_eq!(opener.open(Kind::Input, &sealed), Err(OpenError::Malformed));
    }

    #[test]
    fn a_replayed_or_older_message_is_refused() {
        let (backend, frontend) = pair();
        let mut sealer = frontend.sealer(Direction::ToBackend).unwrap();
        let mut opener = backend.opener(Direction::ToBackend);
        let first = sealer.seal(Kind::Input, b"a");
        let second = sealer.seal(Kind::Input, b"b");
        let third = sealer.seal(Kind::Input, b"c");
        assert!(opener.open(Kind::Input, &second).is_ok());
        assert_eq!(opener.open(Kind::Input, &second), Err(OpenError::Replayed));
        // Older than one opened: refused; a gap is fine (dropped messages).
        assert_eq!(opener.open(Kind::Input, &first), Err(OpenError::Replayed));
        assert!(opener.open(Kind::Input, &third).is_ok());
        // Each sender has its own numbers.
        let mut another = frontend.sealer(Direction::ToBackend).unwrap();
        assert!(
            opener
                .open(Kind::Input, &another.seal(Kind::Input, b"d"))
                .is_ok()
        );
        assert!(
            opener
                .open(Kind::Resize, &sealer.seal(Kind::Resize, &encode_size(1, 2)))
                .is_ok()
        );
    }

    #[test]
    #[expect(
        clippy::let_underscore_must_use,
        reason = "the test checks what the opener records, not what open returns"
    )]
    fn a_new_sender_past_the_limit_is_refused_and_none_is_forgotten() {
        let (backend, frontend) = pair();
        let mut opener = backend.opener(Direction::ToBackend);
        let mut first = frontend.sealer(Direction::ToBackend).unwrap();
        let old = first.seal(Kind::Input, b"old");
        assert!(opener.open(Kind::Input, &old).is_ok());
        for _ in 1..MAX_SENDERS {
            let mut sender = frontend.sealer(Direction::ToBackend).unwrap();
            assert!(
                opener
                    .open(Kind::Input, &sender.seal(Kind::Input, b"x"))
                    .is_ok()
            );
        }
        assert_eq!(opener.last.len(), MAX_SENDERS);
        let mut newest = frontend.sealer(Direction::ToBackend).unwrap();
        assert!(!opener.take_newly_refused());
        assert_eq!(
            opener.open(Kind::Input, &newest.seal(Kind::Input, b"y")),
            Err(OpenError::TooManySenders)
        );
        assert!(opener.take_newly_refused());
        assert!(!opener.take_newly_refused(), "told once per ask");
        // The same sender again: not new.
        let _ = opener.open(Kind::Input, &newest.seal(Kind::Input, b"y2"));
        assert!(!opener.take_newly_refused());
        // Another new sender: new.
        let mut other = frontend.sealer(Direction::ToBackend).unwrap();
        let _ = opener.open(Kind::Input, &other.seal(Kind::Input, b"o"));
        assert!(opener.take_newly_refused());
        // The first sender is still known: its replay is refused, and its
        // next message opens.
        assert_eq!(opener.open(Kind::Input, &old), Err(OpenError::Replayed));
        assert!(
            opener
                .open(Kind::Input, &first.seal(Kind::Input, b"z"))
                .is_ok()
        );
        // A forgery from a new sender is a forgery, limit or not.
        let mut forged = newest.seal(Kind::Input, b"f");
        let last = forged.len() - 1;
        forged[last] ^= 1;
        assert_eq!(opener.open(Kind::Input, &forged), Err(OpenError::Forged));
        // Refused senders are told up to the bound, and none past it.
        while opener.refused.len() < MAX_SENDERS {
            let mut sender = frontend.sealer(Direction::ToBackend).unwrap();
            let _ = opener.open(Kind::Input, &sender.seal(Kind::Input, b"r"));
            assert!(opener.take_newly_refused());
        }
        let mut past = frontend.sealer(Direction::ToBackend).unwrap();
        assert_eq!(
            opener.open(Kind::Input, &past.seal(Kind::Input, b"p")),
            Err(OpenError::TooManySenders)
        );
        assert!(!opener.take_newly_refused(), "told past the bound");
        assert_eq!(opener.refused.len(), MAX_SENDERS);
    }

    #[test]
    fn paste_is_a_kind_of_its_own_and_the_sender_is_told() {
        let (backend, frontend) = pair();
        let mut sealer = frontend.sealer(Direction::ToBackend).unwrap();
        let mut opener = backend.opener(Direction::ToBackend);
        let pasted = sealer.seal(Kind::Paste, b"p");
        // Not input: a relay cannot pass typed input off as paste, or back.
        assert_eq!(opener.open(Kind::Input, &pasted), Err(OpenError::Forged));
        let (plaintext, sender) = opener.open_from(Kind::Paste, &pasted).unwrap();
        assert_eq!(&plaintext[..], b"p");
        assert_eq!(sender, sealer.sender);
        let typed = sealer.seal(Kind::Input, b"t");
        assert_eq!(opener.open(Kind::Paste, &typed), Err(OpenError::Forged));
        let (_, again) = opener.open_from(Kind::Input, &typed).unwrap();
        assert_eq!(again, sender);
    }

    #[test]
    fn a_size_round_trips() {
        assert_eq!(decode_size(&encode_size(80, 24)), Some((80, 24)));
        assert_eq!(
            decode_size(&encode_size(0x1234, 0xabcd)),
            Some((0x1234, 0xabcd))
        );
        assert_eq!(encode_size(0x1234, 0xabcd), [0x12, 0x34, 0xab, 0xcd]);
        assert_eq!(decode_size(&[1, 2, 3]), None);
        assert_eq!(decode_size(&[1, 2, 3, 4, 5]), None);
    }

    #[test]
    fn the_keys_follow_a_known_derivation() {
        // A fixed secret and session give fixed keys: the derivation is
        // part of the protocol, and must not change by accident. The values
        // come from an independent HKDF-SHA256 (Python's hmac and hashlib).
        let secret = Secret::parse(&"00".repeat(32)).unwrap();
        let keys = Keys::derive(&secret, SessionId::nil());
        let hex = |k: &[u8; 32]| k.iter().map(|b| format!("{b:02x}")).collect::<String>();
        let pinned = (hex(&keys.to_backend), hex(&keys.to_frontend));
        assert_ne!(pinned.0, pinned.1);
        assert_eq!(
            pinned,
            (
                String::from("026099e9d850ab7ef27762ea7e6c8590bb153abae1261881b66d32b2a24e9b42"),
                String::from("7b11817c258cfdc9b023206880109ea790e6ec441440e0dc413f9307d02dc870")
            )
        );
    }

    #[test]
    fn a_message_moved_to_another_channel_does_not_open() {
        let secret = Secret::generate().unwrap();
        let session = SessionId::new_v4();
        let on_a = Keys::derive_on(&secret, session, "aaaa");
        let mut sealer = on_a.sealer(Direction::ToFrontend).unwrap();
        let sealed = sealer.seal(Kind::Output, b"for channel a");
        // Its own channel opens it.
        let mut opener = on_a.opener(Direction::ToFrontend);
        assert_eq!(
            opener.open(Kind::Output, &sealed).unwrap().as_slice(),
            b"for channel a"
        );
        // Another channel, or the session as a whole, under the same secret,
        // does not.
        for keys in [
            Keys::derive_on(&secret, session, "bbbb"),
            Keys::derive(&secret, session),
        ] {
            assert!(
                keys.opener(Direction::ToFrontend)
                    .open(Kind::Output, &sealed)
                    .is_err()
            );
        }
        // And a channel-less message does not open on a channel.
        let plain = Keys::derive(&secret, session)
            .sealer(Direction::ToFrontend)
            .unwrap()
            .seal(Kind::Output, b"whole session");
        assert!(
            on_a.opener(Direction::ToFrontend)
                .open(Kind::Output, &plain)
                .is_err()
        );
    }
}