Skip to main content

vector_core/transfer/
session.rs

1//! One side of a transfer as a pure state machine: messages in, messages and outcomes out. The
2//! network loop feeds it; the tests drive two or three of them by hand.
3//!
4//! The joiner commits to its SPAKE2 message before it sees the shower's, and the shower sends its
5//! own before it sees the joiner's, so a party that knows the code still can't steer the number
6//! the two screens show. Any third device in the room ends the session. The identity itself travels
7//! under SPAKE2's secret and an ML-KEM-1024 secret together: the receiver's encapsulation key rides
8//! in its sealed hello, and the sender encapsulates to it when the user approves.
9
10use nostr_sdk::prelude::{FromBech32, FromMnemonic, Keys, PublicKey, ToBech32};
11use serde::{Deserialize, Serialize};
12use zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing};
13
14use super::code::Code;
15use super::crypto::{commitment, kem_encapsulate, kem_public_ok, room, transcript, Dir, KemSeed, Pake, Sealed, SessionKeys};
16use super::wire::{DecodeError, Msg};
17
18#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize, Deserialize)]
19#[serde(rename_all = "lowercase")]
20pub enum Role {
21    /// Signed in, holds the key.
22    Sender,
23    /// Being set up.
24    Receiver,
25}
26
27#[derive(Clone, Copy, PartialEq, Eq, Debug)]
28pub enum Presentation {
29    /// Displays the code.
30    Shower,
31    /// Scanned or typed it.
32    Joiner,
33}
34
35/// The identity a sender hands over.
36#[derive(Clone, Serialize, Deserialize, Zeroize, ZeroizeOnDrop)]
37pub struct Bundle {
38    pub nsec: String,
39    #[serde(default, skip_serializing_if = "Option::is_none")]
40    pub seed: Option<String>,
41}
42
43impl Bundle {
44    /// The identity as stored on the sender. A seed that doesn't derive this key stays behind.
45    pub fn from_stored(nsec: &str, seed: Option<&str>) -> Self {
46        let pk = Keys::parse(nsec).ok().map(|k| k.public_key());
47        let seed = seed.filter(|s| pk.is_some() && Keys::from_mnemonic(*s, None).ok().map(|k| k.public_key()) == pk);
48        Self { nsec: nsec.to_string(), seed: seed.map(str::to_string) }
49    }
50
51    /// The key's public half, if the nsec parses and any seed derives the same key.
52    fn identity(&self) -> Option<PublicKey> {
53        let pk = Keys::parse(&self.nsec).ok()?.public_key();
54        match &self.seed {
55            Some(seed) => (Keys::from_mnemonic(seed.as_str(), None).ok()?.public_key() == pk).then_some(pk),
56            None => Some(pk),
57        }
58    }
59}
60
61#[derive(Clone, PartialEq, Eq, Debug)]
62pub enum Failure {
63    /// The two devices hold different codes.
64    WrongCode,
65    /// Another device used the code.
66    Contention,
67    /// Both devices are signed in, or neither is.
68    RoleClash(Role),
69    /// The other device speaks another version of the protocol.
70    Version,
71    /// The sender's user said no.
72    Denied,
73    /// The identity that arrived isn't the one the sender announced.
74    BadBundle,
75    /// The number was typed wrong too many times.
76    WrongNumber,
77    /// Out of order or malformed.
78    Protocol(&'static str),
79    /// The other device gave up.
80    PeerAborted(String),
81}
82
83pub enum Out {
84    Send(Msg),
85    /// The peer repeated itself: our last message was lost, send it again.
86    Resend,
87    /// The keys agree. `sas` is shown on the receiver and typed on the sender; `sender` is the
88    /// identity the sender announced, on the receiver.
89    Matched { sas: String, sender: Option<PublicKey> },
90    /// Receiver: the identity arrived and matches what was announced.
91    Received(Bundle),
92    /// Sender: the receiver has it.
93    Acked,
94    Failed(Failure),
95}
96
97impl std::fmt::Debug for Out {
98    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
99        match self {
100            Out::Send(m) => write!(f, "Send({})", m.kind()),
101            Out::Resend => write!(f, "Resend"),
102            Out::Matched { .. } => write!(f, "Matched"),
103            Out::Received(_) => write!(f, "Received"),
104            Out::Acked => write!(f, "Acked"),
105            Out::Failed(why) => write!(f, "Failed({why:?})"),
106        }
107    }
108}
109
110#[derive(Debug, PartialEq, Eq)]
111pub enum ApproveError {
112    NotReady,
113    WrongNumber { tries_left: u8 },
114    NotYours,
115}
116
117#[derive(Serialize, Deserialize)]
118struct Hello {
119    role: Role,
120    #[serde(default, skip_serializing_if = "Option::is_none")]
121    npub: Option<String>,
122    /// The receiver's ML-KEM-1024 encapsulation key, base64.
123    #[serde(default, skip_serializing_if = "Option::is_none")]
124    kem: Option<String>,
125    /// The sender's display name, for the new device's screen.
126    #[serde(default, skip_serializing_if = "Option::is_none")]
127    name: Option<String>,
128    /// The sender's avatar thumbnail, base64. Shown only after the receiver re-encodes it.
129    #[serde(default, skip_serializing_if = "Option::is_none")]
130    avatar: Option<String>,
131}
132
133#[derive(PartialEq, Eq, Debug)]
134enum Stage {
135    AwaitCommit,
136    AwaitPake,
137    AwaitReveal([u8; 32]),
138    AwaitHello,
139    Matched,
140    Sent,
141    Done,
142    Failed,
143}
144
145const SAS_TRIES: u8 = 3;
146
147pub struct Session {
148    role: Role,
149    presentation: Presentation,
150    me: PublicKey,
151    room: PublicKey,
152    identity: Option<PublicKey>,
153    peer: Option<PublicKey>,
154    pake: Option<Pake>,
155    my_pake: Vec<u8>,
156    keys: Option<SessionKeys>,
157    announced: Option<PublicKey>,
158    stage: Stage,
159    seen: Vec<&'static str>,
160    last: Option<Msg>,
161    sas_checked: bool,
162    sas_tries: u8,
163    /// Receiver: its ML-KEM key. Sender: none.
164    kem: Option<KemSeed>,
165    my_kem_public: Vec<u8>,
166    /// Sender: the receiver's encapsulation key, from its hello.
167    peer_kem_public: Vec<u8>,
168    /// The keys the bundle and its ack travel under, once the ML-KEM secret is in.
169    hybrid: Option<SessionKeys>,
170    /// Sender: its name and avatar thumbnail. Receiver: the sender's, from its hello.
171    face_name: Option<String>,
172    face_avatar: Option<Vec<u8>>,
173}
174
175impl Session {
176    /// `me` is this device's throwaway author. A sender passes the identity it will hand over.
177    pub fn new(role: Role, presentation: Presentation, code: &Code, me: PublicKey, identity: Option<PublicKey>) -> (Self, Vec<Out>) {
178        let pake = Pake::start(code);
179        let my_pake = pake.msg().to_vec();
180        let kem = (role == Role::Receiver).then(KemSeed::generate);
181        let my_kem_public = kem.as_ref().map(KemSeed::public_key).unwrap_or_default();
182        let mut s = Self {
183            role,
184            presentation,
185            me,
186            room: room(code.nameplate()),
187            identity: if role == Role::Sender { identity } else { None },
188            peer: None,
189            pake: Some(pake),
190            my_pake,
191            keys: None,
192            announced: None,
193            stage: if presentation == Presentation::Shower { Stage::AwaitCommit } else { Stage::AwaitPake },
194            seen: Vec::new(),
195            last: None,
196            sas_checked: false,
197            sas_tries: 0,
198            kem,
199            my_kem_public,
200            peer_kem_public: Vec::new(),
201            hybrid: None,
202            face_name: None,
203            face_avatar: None,
204        };
205        let out = match presentation {
206            Presentation::Joiner => vec![s.send(Msg::Commit(commitment(&s.my_pake)))],
207            Presentation::Shower => Vec::new(),
208        };
209        (s, out)
210    }
211
212    pub fn room(&self) -> PublicKey {
213        self.room
214    }
215
216    /// Sender: the name and avatar thumbnail its hello carries, set before the hello goes out.
217    pub fn set_face(&mut self, name: Option<String>, avatar: Option<Vec<u8>>) {
218        if self.role == Role::Sender {
219            self.face_name = name.map(|n| n.chars().take(64).collect());
220            self.face_avatar = avatar.filter(|a| a.len() <= super::avatar::MAX_BYTES);
221        }
222    }
223
224    /// Receiver: the name and avatar thumbnail the sender announced. Untrusted, for display only.
225    pub fn sender_face(&self) -> (Option<&str>, Option<&[u8]>) {
226        match self.role {
227            Role::Receiver => (self.face_name.as_deref(), self.face_avatar.as_deref()),
228            Role::Sender => (None, None),
229        }
230    }
231
232    /// The message to send again when the peer seems to have missed it.
233    pub fn last_sent(&self) -> Option<&Msg> {
234        self.last.as_ref()
235    }
236
237    /// Finished one way or the other: nothing more will be sent or accepted.
238    pub fn is_over(&self) -> bool {
239        matches!(self.stage, Stage::Done | Stage::Failed)
240    }
241
242    /// Keys agreed and nothing handed over yet: the approval window.
243    pub fn is_matched(&self) -> bool {
244        self.stage == Stage::Matched
245    }
246
247    /// Sender: the identity went out and the ack hasn't come back yet.
248    pub fn is_sent(&self) -> bool {
249        self.stage == Stage::Sent
250    }
251
252    /// The peer message our last one answered: only a repeat of that means ours was lost. Anything
253    /// else repeated is the peer retrying across our reply, and answering it would loop forever.
254    fn answers(&self) -> Option<&'static str> {
255        match self.last.as_ref()? {
256            Msg::Pake(_) => Some("commit"),
257            Msg::Reveal { .. } => Some("pake"),
258            Msg::Hello(_) => Some("reveal"),
259            Msg::Ack(_) => Some("bundle"),
260            _ => None,
261        }
262    }
263
264    fn send(&mut self, msg: Msg) -> Out {
265        if !matches!(msg, Msg::Abort(_)) {
266            self.last = Some(msg.clone());
267        }
268        Out::Send(msg)
269    }
270
271    fn fail(&mut self, failure: Failure) -> Vec<Out> {
272        self.stage = Stage::Failed;
273        vec![Out::Failed(failure)]
274    }
275
276    fn fail_loudly(&mut self, failure: Failure, reason: &str) -> Vec<Out> {
277        self.stage = Stage::Failed;
278        vec![Out::Send(Msg::Abort(reason.to_string())), Out::Failed(failure)]
279    }
280
281    fn my_dir(&self) -> Dir {
282        match self.presentation {
283            Presentation::Shower => Dir::ShowerToJoiner,
284            Presentation::Joiner => Dir::JoinerToShower,
285        }
286    }
287
288    fn peer_dir(&self) -> Dir {
289        match self.presentation {
290            Presentation::Shower => Dir::JoinerToShower,
291            Presentation::Joiner => Dir::ShowerToJoiner,
292        }
293    }
294
295    fn hello(&self) -> Zeroizing<Vec<u8>> {
296        let kem = (!self.my_kem_public.is_empty()).then(|| crate::simd::base64::STANDARD.encode_to_string(&self.my_kem_public));
297        let (name, avatar) = match self.role {
298            Role::Sender => (self.face_name.clone(), self.face_avatar.as_ref().map(|a| crate::simd::base64::STANDARD.encode_to_string(a))),
299            Role::Receiver => (None, None),
300        };
301        let hello = Hello { role: self.role, npub: self.identity.and_then(|pk| pk.to_bech32().ok()), kem, name, avatar };
302        Zeroizing::new(serde_json::to_vec(&hello).expect("plain struct"))
303    }
304
305    /// Open the peer's hello and settle who is who.
306    fn accept_hello(&mut self, sealed: &[u8]) -> Result<(), Vec<Out>> {
307        let keys = self.keys.as_ref().expect("keys before hello");
308        let Ok(plain) = keys.open(self.peer_dir(), Sealed::Hello, sealed) else {
309            return Err(self.fail_loudly(Failure::WrongCode, "code"));
310        };
311        let Ok(hello) = serde_json::from_slice::<Hello>(&plain) else {
312            return Err(self.fail_loudly(Failure::Protocol("malformed hello"), "protocol"));
313        };
314        if hello.role == self.role {
315            return Err(self.fail_loudly(Failure::RoleClash(self.role), "role"));
316        }
317        if hello.role == Role::Sender {
318            match hello.npub.as_deref().and_then(|n| PublicKey::from_bech32(n).ok()) {
319                Some(pk) => self.announced = Some(pk),
320                None => return Err(self.fail_loudly(Failure::Protocol("sender without identity"), "protocol")),
321            }
322            self.face_name = hello.name.map(|n| n.chars().take(64).collect());
323            self.face_avatar = hello
324                .avatar
325                .and_then(|a| crate::simd::base64::STANDARD.decode_to_vec(a).ok())
326                .filter(|a| a.len() <= super::avatar::MAX_BYTES);
327        } else {
328            let kem = hello.kem.as_deref().and_then(|k| crate::simd::base64::STANDARD.decode_to_vec(k).ok());
329            match kem.filter(|k| kem_public_ok(k)) {
330                Some(k) => self.peer_kem_public = k,
331                None => return Err(self.fail_loudly(Failure::Protocol("receiver without a post-quantum key"), "protocol")),
332            }
333        }
334        Ok(())
335    }
336
337    fn matched(&mut self) -> Out {
338        self.stage = Stage::Matched;
339        let sas = self.keys.as_ref().expect("matched with keys").sas();
340        Out::Matched { sas, sender: self.announced }
341    }
342
343    /// Waiting on the peer's next message, so the last one should be repeated until it comes.
344    pub fn awaiting_reply(&self) -> bool {
345        matches!(self.stage, Stage::AwaitPake | Stage::AwaitReveal(_) | Stage::AwaitHello | Stage::Sent)
346    }
347
348    pub fn on_message(&mut self, author: PublicKey, msg: Result<Msg, DecodeError>) -> Vec<Out> {
349        if author == self.me {
350            return Vec::new();
351        }
352        // A receiver that has the identity still answers a repeated bundle, or the sender never
353        // hears the ack.
354        if self.stage == Stage::Done && self.peer == Some(author) {
355            return match msg {
356                Ok(m) if self.answers() == Some(m.kind()) => vec![Out::Resend],
357                _ => Vec::new(),
358            };
359        }
360        if self.is_over() {
361            return Vec::new();
362        }
363        let msg = match msg {
364            Ok(msg) => msg,
365            Err(DecodeError::Version(_)) if self.peer.is_none_or(|p| p == author) => return self.fail(Failure::Version),
366            Err(_) if self.peer == Some(author) => return self.fail(Failure::Protocol("malformed message")),
367            Err(_) => return self.fail_loudly(Failure::Contention, "contention"),
368        };
369
370        match self.peer {
371            Some(peer) if peer != author => return self.fail_loudly(Failure::Contention, "contention"),
372            Some(_) => {}
373            None => {
374                let opens = matches!(
375                    (&self.stage, &msg),
376                    (Stage::AwaitCommit, Msg::Commit(_)) | (Stage::AwaitPake, Msg::Pake(_))
377                );
378                if !opens {
379                    return self.fail_loudly(Failure::Contention, "contention");
380                }
381                self.peer = Some(author);
382            }
383        }
384
385        if let Msg::Abort(reason) = msg {
386            return self.fail(Failure::PeerAborted(reason));
387        }
388        let kind = msg.kind();
389        if self.seen.contains(&kind) {
390            return if self.answers() == Some(kind) { vec![Out::Resend] } else { Vec::new() };
391        }
392        self.seen.push(kind);
393
394        match (std::mem::replace(&mut self.stage, Stage::Failed), msg) {
395            (Stage::AwaitCommit, Msg::Commit(h)) => {
396                self.stage = Stage::AwaitReveal(h);
397                vec![self.send(Msg::Pake(self.my_pake.clone()))]
398            }
399            (Stage::AwaitPake, Msg::Pake(theirs)) => {
400                let shared = match self.pake.take().expect("pake once").finish(&theirs) {
401                    Ok(k) => k,
402                    Err(why) => return self.fail_loudly(Failure::Protocol(why), "protocol"),
403                };
404                let t = transcript(&self.room, &author, &self.me, &theirs, &self.my_pake);
405                let keys = SessionKeys::derive(&shared, t);
406                let hello = keys.seal(self.my_dir(), Sealed::Hello, &self.hello());
407                self.keys = Some(keys);
408                self.stage = Stage::AwaitHello;
409                vec![self.send(Msg::Reveal { pake: self.my_pake.clone(), hello })]
410            }
411            (Stage::AwaitReveal(h), Msg::Reveal { pake: theirs, hello }) => {
412                if commitment(&theirs) != h {
413                    return self.fail_loudly(Failure::Protocol("commitment mismatch"), "protocol");
414                }
415                let shared = match self.pake.take().expect("pake once").finish(&theirs) {
416                    Ok(k) => k,
417                    Err(why) => return self.fail_loudly(Failure::Protocol(why), "protocol"),
418                };
419                let t = transcript(&self.room, &self.me, &author, &self.my_pake, &theirs);
420                self.keys = Some(SessionKeys::derive(&shared, t));
421                if let Err(out) = self.accept_hello(&hello) {
422                    return out;
423                }
424                let mine = self.keys.as_ref().expect("derived").seal(self.my_dir(), Sealed::Hello, &self.hello());
425                let send = self.send(Msg::Hello(mine));
426                vec![send, self.matched()]
427            }
428            (Stage::AwaitHello, Msg::Hello(sealed)) => {
429                if let Err(out) = self.accept_hello(&sealed) {
430                    return out;
431                }
432                vec![self.matched()]
433            }
434            (Stage::Matched, Msg::Bundle { kem, sealed }) if self.role == Role::Receiver => {
435                let keys = self.keys.as_ref().expect("matched with keys");
436                let Ok(shared) = self.kem.as_ref().expect("receiver has a kem key").decapsulate(&kem) else {
437                    return self.fail_loudly(Failure::Protocol("malformed kem ciphertext"), "protocol");
438                };
439                let hybrid = keys.hybrid(&self.my_kem_public, &kem, &shared);
440                let Ok(plain) = hybrid.open(self.peer_dir(), Sealed::Bundle, &sealed) else {
441                    return self.fail_loudly(Failure::Protocol("unreadable bundle"), "protocol");
442                };
443                let Ok(bundle) = serde_json::from_slice::<Bundle>(&plain) else {
444                    return self.fail_loudly(Failure::BadBundle, "bundle");
445                };
446                if bundle.identity().is_none() || bundle.identity() != self.announced {
447                    return self.fail_loudly(Failure::BadBundle, "bundle");
448                }
449                let ack = hybrid.seal(self.my_dir(), Sealed::Ack, b"");
450                self.hybrid = Some(hybrid);
451                self.stage = Stage::Done;
452                // The account is ready before the ack goes out: a slow publish mustn't hold up sign-in.
453                let send = self.send(Msg::Ack(ack));
454                vec![Out::Received(bundle), send]
455            }
456            (Stage::Matched, Msg::Deny(sealed)) if self.role == Role::Receiver => {
457                let keys = self.keys.as_ref().expect("matched with keys");
458                if keys.open(self.peer_dir(), Sealed::Deny, &sealed).is_err() {
459                    return self.fail(Failure::Protocol("unreadable deny"));
460                }
461                self.fail(Failure::Denied)
462            }
463            (Stage::Sent, Msg::Ack(sealed)) => {
464                let keys = self.hybrid.as_ref().expect("sent under hybrid keys");
465                if keys.open(self.peer_dir(), Sealed::Ack, &sealed).is_err() {
466                    return self.fail(Failure::Protocol("unreadable ack"));
467                }
468                self.stage = Stage::Done;
469                vec![Out::Acked]
470            }
471            (stage, _) => {
472                self.stage = stage;
473                self.fail_loudly(Failure::Protocol("unexpected message"), "protocol")
474            }
475        }
476    }
477
478    /// Sender: check the number the user typed from the new device. Three wrong tries end it.
479    pub fn check_number(&mut self, typed: &str) -> Result<(), ApproveError> {
480        if self.role != Role::Sender || self.stage != Stage::Matched {
481            return Err(ApproveError::NotReady);
482        }
483        if self.keys.as_ref().expect("matched with keys").sas_matches(typed) {
484            self.sas_checked = true;
485            return Ok(());
486        }
487        self.sas_tries += 1;
488        if self.sas_tries >= SAS_TRIES {
489            self.stage = Stage::Failed;
490        }
491        Err(ApproveError::WrongNumber { tries_left: SAS_TRIES.saturating_sub(self.sas_tries) })
492    }
493
494    /// Sender: hand the identity over. Once only, and only after the number checked out.
495    pub fn approve(&mut self, bundle: Bundle) -> Result<Vec<Out>, ApproveError> {
496        if self.role != Role::Sender || self.stage != Stage::Matched || !self.sas_checked {
497            return Err(ApproveError::NotReady);
498        }
499        if bundle.identity().is_none() || bundle.identity() != self.identity {
500            return Err(ApproveError::NotYours);
501        }
502        let (kem, shared) = kem_encapsulate(&self.peer_kem_public).map_err(|_| ApproveError::NotReady)?;
503        let hybrid = self.keys.as_ref().expect("matched with keys").hybrid(&self.peer_kem_public, &kem, &shared);
504        // Sized up front so serializing never reallocates and strands an unwiped copy of the key.
505        let mut plain = Zeroizing::new(Vec::with_capacity(1024));
506        serde_json::to_writer(&mut *plain, &bundle).expect("plain struct");
507        let sealed = hybrid.seal(self.my_dir(), Sealed::Bundle, &plain);
508        self.hybrid = Some(hybrid);
509        self.stage = Stage::Sent;
510        Ok(vec![self.send(Msg::Bundle { kem, sealed })])
511    }
512
513    /// Sender: the user said no.
514    pub fn deny(&mut self) -> Vec<Out> {
515        if self.role != Role::Sender || self.stage != Stage::Matched {
516            return Vec::new();
517        }
518        let sealed = self.keys.as_ref().expect("matched with keys").seal(self.my_dir(), Sealed::Deny, b"");
519        self.stage = Stage::Done;
520        vec![self.send(Msg::Deny(sealed))]
521    }
522
523    /// The host is giving up (cancel, timeout): tell the peer so it doesn't wait.
524    pub fn abort(&mut self, reason: &str) -> Vec<Out> {
525        if self.is_over() {
526            return Vec::new();
527        }
528        self.stage = Stage::Failed;
529        vec![Out::Send(Msg::Abort(reason.to_string()))]
530    }
531}
532
533#[cfg(test)]
534mod tests {
535    use super::*;
536
537    struct Device {
538        session: Session,
539        author: PublicKey,
540        outbox: Vec<Msg>,
541        events: Vec<Out>,
542    }
543
544    impl Device {
545        fn new(role: Role, presentation: Presentation, code: &str, identity: Option<&Keys>) -> Self {
546            let author = Keys::generate().public_key();
547            let (session, out) = Session::new(role, presentation, &Code::parse(code).unwrap(), author, identity.map(|k| k.public_key()));
548            let mut d = Self { session, author, outbox: Vec::new(), events: Vec::new() };
549            d.absorb(out);
550            d
551        }
552
553        fn absorb(&mut self, out: Vec<Out>) {
554            for o in out {
555                match o {
556                    Out::Send(m) => self.outbox.push(m),
557                    Out::Resend => {
558                        if let Some(m) = self.session.last_sent().cloned() {
559                            self.outbox.push(m);
560                        }
561                    }
562                    other => self.events.push(other),
563                }
564            }
565        }
566
567        fn take(&mut self) -> Vec<Msg> {
568            std::mem::take(&mut self.outbox)
569        }
570
571        fn hear(&mut self, from: PublicKey, msgs: Vec<Msg>) {
572            for m in msgs {
573                let encoded = m.encode();
574                let out = self.session.on_message(from, Msg::decode(&encoded));
575                self.absorb(out);
576            }
577        }
578
579        fn sas(&self) -> Option<String> {
580            self.events.iter().find_map(|e| match e {
581                Out::Matched { sas, .. } => Some(sas.clone()),
582                _ => None,
583            })
584        }
585
586        fn failure(&self) -> Option<Failure> {
587            self.events.iter().find_map(|e| match e {
588                Out::Failed(f) => Some(f.clone()),
589                _ => None,
590            })
591        }
592    }
593
594    /// Deliver everything both ways until nobody has anything left to say.
595    fn pump(a: &mut Device, b: &mut Device) {
596        for _ in 0..10 {
597            let (to_b, to_a) = (a.take(), b.take());
598            if to_b.is_empty() && to_a.is_empty() {
599                return;
600            }
601            b.hear(a.author, to_b);
602            a.hear(b.author, to_a);
603        }
604        panic!("the devices kept talking: a resend loop");
605    }
606
607    fn bundle_for(keys: &Keys, seed: Option<&str>) -> Bundle {
608        Bundle { nsec: keys.secret_key().to_bech32().unwrap(), seed: seed.map(str::to_string) }
609    }
610
611    const CODE: &str = "7-orbit-lemon-stage";
612
613    fn matched_pair(sender_shows: bool) -> (Device, Device, Keys) {
614        let identity = Keys::generate();
615        let (sp, rp) = if sender_shows { (Presentation::Shower, Presentation::Joiner) } else { (Presentation::Joiner, Presentation::Shower) };
616        let mut sender = Device::new(Role::Sender, sp, CODE, Some(&identity));
617        let mut receiver = Device::new(Role::Receiver, rp, CODE, None);
618        pump(&mut sender, &mut receiver);
619        (sender, receiver, identity)
620    }
621
622    #[test]
623    fn the_identity_moves_whichever_device_shows_the_code() {
624        for sender_shows in [true, false] {
625            let (mut sender, mut receiver, identity) = matched_pair(sender_shows);
626            let sas = receiver.sas().expect("receiver matched");
627            assert_eq!(sender.sas().as_deref(), Some(sas.as_str()));
628            assert!(receiver.events.iter().any(|e| matches!(e, Out::Matched { sender: Some(pk), .. } if *pk == identity.public_key())));
629
630            sender.session.check_number(&sas).unwrap();
631            let out = sender.session.approve(bundle_for(&identity, None)).unwrap();
632            sender.absorb(out);
633            pump(&mut sender, &mut receiver);
634
635            let received = receiver.events.iter().find_map(|e| match e { Out::Received(b) => Some(b.nsec.clone()), _ => None });
636            assert_eq!(received.as_deref(), Some(bundle_for(&identity, None).nsec.as_str()));
637            assert!(sender.events.iter().any(|e| matches!(e, Out::Acked)));
638            assert!(sender.session.is_over() && receiver.session.is_over());
639
640            // The ack was lost: the repeated bundle gets it again, and nothing else changes.
641            let bundle = sender.session.last_sent().cloned().unwrap();
642            receiver.hear(sender.author, vec![bundle]);
643            assert!(matches!(receiver.take().as_slice(), [Msg::Ack(_)]));
644            assert_eq!(receiver.events.iter().filter(|e| matches!(e, Out::Received(_))).count(), 1);
645        }
646    }
647
648    #[test]
649    fn the_senders_face_reaches_the_receiver_and_only_the_receiver() {
650        let identity = Keys::generate();
651        let mut sender = Device::new(Role::Sender, Presentation::Joiner, CODE, Some(&identity));
652        sender.session.set_face(Some("Kitty".repeat(20)), Some(vec![0xff, 0xd8, 0xff, 1, 2, 3]));
653        let mut receiver = Device::new(Role::Receiver, Presentation::Shower, CODE, None);
654        receiver.session.set_face(Some("ignored".into()), None);
655        pump(&mut sender, &mut receiver);
656        let (name, avatar) = receiver.session.sender_face();
657        assert_eq!(name.map(|n| n.chars().count()), Some(64), "names are capped");
658        assert_eq!(avatar, Some(&[0xff, 0xd8, 0xff, 1, 2, 3][..]));
659        assert_eq!(sender.session.sender_face(), (None, None));
660    }
661
662    #[test]
663    fn a_seed_travels_only_with_the_key_it_derives() {
664        let phrase = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about";
665        let from_seed = Keys::from_mnemonic(phrase, None).unwrap();
666        let mut sender = Device::new(Role::Sender, Presentation::Shower, CODE, Some(&from_seed));
667        let mut receiver = Device::new(Role::Receiver, Presentation::Joiner, CODE, None);
668        pump(&mut sender, &mut receiver);
669        sender.session.check_number(&receiver.sas().unwrap()).unwrap();
670        assert_eq!(sender.session.approve(bundle_for(&Keys::generate(), Some(phrase))).unwrap_err(), ApproveError::NotYours);
671        let stray = Bundle::from_stored(&bundle_for(&Keys::generate(), None).nsec, Some(phrase));
672        assert!(stray.seed.is_none(), "a seed for another key is left behind");
673        let out = sender.session.approve(bundle_for(&from_seed, Some(phrase))).unwrap();
674        sender.absorb(out);
675        pump(&mut sender, &mut receiver);
676        assert!(receiver.events.iter().any(|e| matches!(e, Out::Received(b) if b.seed.as_deref() == Some(phrase))));
677    }
678
679    #[test]
680    fn a_different_code_ends_both_sides() {
681        let mut shower = Device::new(Role::Receiver, Presentation::Shower, CODE, None);
682        let mut joiner = Device::new(Role::Sender, Presentation::Joiner, "7-orbit-lemon-stamp", Some(&Keys::generate()));
683        pump(&mut shower, &mut joiner);
684        assert_eq!(shower.failure(), Some(Failure::WrongCode));
685        assert!(matches!(joiner.failure(), Some(Failure::PeerAborted(_))));
686        assert!(shower.sas().is_none() && joiner.sas().is_none());
687    }
688
689    #[test]
690    fn a_third_device_in_the_room_ends_the_session() {
691        let identity = Keys::generate();
692        let mut shower = Device::new(Role::Sender, Presentation::Shower, CODE, Some(&identity));
693        let mut real = Device::new(Role::Receiver, Presentation::Joiner, CODE, None);
694        let mut intruder = Device::new(Role::Receiver, Presentation::Joiner, CODE, None);
695        shower.hear(intruder.author, intruder.take());
696        shower.hear(real.author, real.take());
697        assert_eq!(shower.failure(), Some(Failure::Contention));
698        shower.take();
699        assert_eq!(shower.session.check_number("000000"), Err(ApproveError::NotReady));
700
701        // After the keys agree, too.
702        let (mut sender, mut receiver, _) = matched_pair(true);
703        let late = Keys::generate().public_key();
704        sender.hear(late, vec![Msg::Commit([0; 32])]);
705        assert_eq!(sender.failure(), Some(Failure::Contention));
706        assert_eq!(sender.session.check_number(&receiver.sas().unwrap()), Err(ApproveError::NotReady));
707        receiver.hear(late, vec![Msg::Abort("x".into())]);
708        assert_eq!(receiver.failure(), Some(Failure::Contention));
709    }
710
711    #[test]
712    fn a_joiner_cannot_reveal_other_than_it_committed() {
713        let mut shower = Device::new(Role::Sender, Presentation::Shower, CODE, Some(&Keys::generate()));
714        let mut joiner = Device::new(Role::Receiver, Presentation::Joiner, CODE, None);
715        shower.hear(joiner.author, joiner.take());
716        joiner.hear(shower.author, shower.take());
717        let other = Pake::start(&Code::parse(CODE).unwrap());
718        let swapped: Vec<Msg> = joiner.take().into_iter().map(|m| match m {
719            Msg::Reveal { hello, .. } => Msg::Reveal { pake: other.msg().to_vec(), hello },
720            m => m,
721        }).collect();
722        shower.hear(joiner.author, swapped);
723        assert_eq!(shower.failure(), Some(Failure::Protocol("commitment mismatch")));
724    }
725
726    #[test]
727    fn the_showers_own_message_reflected_back_is_refused() {
728        let mut shower = Device::new(Role::Sender, Presentation::Shower, CODE, Some(&Keys::generate()));
729        let mallory = Keys::generate().public_key();
730        let own = shower.session.my_pake.clone();
731        shower.hear(mallory, vec![Msg::Commit(commitment(&own))]);
732        shower.take();
733        shower.hear(mallory, vec![Msg::Reveal { pake: own, hello: vec![0; 32] }]);
734        assert_eq!(shower.failure(), Some(Failure::Protocol("reflected pake message")));
735    }
736
737    #[test]
738    fn two_signed_in_devices_or_two_new_ones_clash() {
739        for role in [Role::Sender, Role::Receiver] {
740            let id = (role == Role::Sender).then(Keys::generate);
741            let mut a = Device::new(role, Presentation::Shower, CODE, id.as_ref());
742            let mut b = Device::new(role, Presentation::Joiner, CODE, id.as_ref());
743            pump(&mut a, &mut b);
744            assert_eq!(a.failure(), Some(Failure::RoleClash(role)));
745            assert!(a.sas().is_none() && b.sas().is_none());
746        }
747    }
748
749    #[test]
750    fn the_number_gates_approval_and_approval_happens_once() {
751        let (mut sender, receiver, identity) = matched_pair(false);
752        let sas = receiver.sas().unwrap();
753        assert_eq!(sender.session.approve(bundle_for(&identity, None)).unwrap_err(), ApproveError::NotReady, "no number yet");
754        assert_eq!(sender.session.check_number("000000x"), Err(ApproveError::WrongNumber { tries_left: 2 }));
755        sender.session.check_number(&sas).unwrap();
756        assert!(sender.session.approve(bundle_for(&identity, None)).is_ok());
757        assert_eq!(sender.session.approve(bundle_for(&identity, None)).unwrap_err(), ApproveError::NotReady, "once");
758        assert!(sender.session.deny().is_empty(), "no deny after a bundle");
759
760        let (mut sender, _, identity) = matched_pair(true);
761        for left in [2, 1, 0] {
762            assert_eq!(sender.session.check_number("not it"), Err(ApproveError::WrongNumber { tries_left: left }));
763        }
764        assert!(sender.session.is_over());
765        assert_eq!(sender.session.approve(bundle_for(&identity, None)).unwrap_err(), ApproveError::NotReady);
766    }
767
768    #[test]
769    fn a_denial_reaches_the_receiver_and_nothing_follows_it() {
770        let (mut sender, mut receiver, identity) = matched_pair(true);
771        let out = sender.session.deny();
772        sender.absorb(out);
773        pump(&mut sender, &mut receiver);
774        assert_eq!(receiver.failure(), Some(Failure::Denied));
775        assert!(sender.session.check_number(&receiver.sas().unwrap()).is_err());
776        assert!(sender.session.approve(bundle_for(&identity, None)).is_err());
777    }
778
779    /// A bundle sealed the way an honest sender would, but carrying `bundle`.
780    fn forge(sender: &Device, receiver: &Device, bundle: &Bundle) -> Msg {
781        let pk = &receiver.session.my_kem_public;
782        let (kem, shared) = kem_encapsulate(pk).unwrap();
783        let hybrid = sender.session.keys.as_ref().unwrap().hybrid(pk, &kem, &shared);
784        let sealed = hybrid.seal(sender.session.my_dir(), Sealed::Bundle, &serde_json::to_vec(bundle).unwrap());
785        Msg::Bundle { kem, sealed }
786    }
787
788    #[test]
789    fn a_bundle_for_another_identity_is_refused() {
790        let (sender, mut receiver, _) = matched_pair(true);
791        let forged = forge(&sender, &receiver, &bundle_for(&Keys::generate(), None));
792        receiver.hear(sender.author, vec![forged]);
793        assert_eq!(receiver.failure(), Some(Failure::BadBundle));
794        assert!(!receiver.events.iter().any(|e| matches!(e, Out::Received(_))));
795    }
796
797    #[test]
798    fn the_identity_needs_the_post_quantum_secret_as_well() {
799        let (mut sender, receiver, identity) = matched_pair(true);
800        sender.session.check_number(&receiver.sas().unwrap()).unwrap();
801        let out = sender.session.approve(bundle_for(&identity, None)).unwrap();
802        let Some(Out::Send(Msg::Bundle { kem, sealed })) = out.into_iter().next() else { panic!("a bundle") };
803        // Someone who later recovers SPAKE2's keys (a quantum computer replaying a recording) has
804        // the classical keys and the ciphertext, but not the receiver's ML-KEM secret.
805        let classical = sender.session.keys.as_ref().unwrap();
806        assert!(classical.open(Dir::ShowerToJoiner, Sealed::Bundle, &sealed).is_err());
807        let wrong_kem = KemSeed::generate().decapsulate(&kem).unwrap();
808        let guessed = classical.hybrid(&receiver.session.my_kem_public, &kem, &wrong_kem);
809        assert!(guessed.open(Dir::ShowerToJoiner, Sealed::Bundle, &sealed).is_err());
810    }
811
812    #[test]
813    fn a_bent_kem_ciphertext_delivers_nothing() {
814        let (mut sender, mut receiver, identity) = matched_pair(false);
815        sender.session.check_number(&receiver.sas().unwrap()).unwrap();
816        let out = sender.session.approve(bundle_for(&identity, None)).unwrap();
817        let Some(Out::Send(Msg::Bundle { mut kem, sealed })) = out.into_iter().next() else { panic!("a bundle") };
818        kem[100] ^= 0x40;
819        receiver.hear(sender.author, vec![Msg::Bundle { kem, sealed }]);
820        assert_eq!(receiver.failure(), Some(Failure::Protocol("unreadable bundle")));
821        assert!(!receiver.events.iter().any(|e| matches!(e, Out::Received(_))));
822    }
823
824    #[test]
825    fn a_receiver_without_a_sound_post_quantum_key_is_refused() {
826        // Missing, and present but outside the field FIPS 203 allows.
827        for bad in [Vec::new(), vec![0xff; super::super::crypto::KEM_PUBLIC_LEN]] {
828            let identity = Keys::generate();
829            let mut sender = Device::new(Role::Sender, Presentation::Shower, CODE, Some(&identity));
830            let mut receiver = Device::new(Role::Receiver, Presentation::Joiner, CODE, None);
831            receiver.session.my_kem_public = bad;
832            pump(&mut sender, &mut receiver);
833            assert_eq!(sender.failure(), Some(Failure::Protocol("receiver without a post-quantum key")));
834            assert!(sender.sas().is_none());
835        }
836    }
837
838    #[test]
839    fn a_repeated_message_asks_for_a_resend_rather_than_restarting() {
840        let mut shower = Device::new(Role::Receiver, Presentation::Shower, CODE, None);
841        let mut joiner = Device::new(Role::Sender, Presentation::Joiner, CODE, Some(&Keys::generate()));
842        let commit = joiner.take();
843        shower.hear(joiner.author, commit.clone());
844        let first = shower.take();
845        shower.hear(joiner.author, commit);
846        assert_eq!(shower.take(), first, "the same Pake again");
847        assert!(shower.failure().is_none());
848    }
849
850    #[test]
851    fn a_retransmit_that_crosses_a_reply_settles_instead_of_looping() {
852        // The joiner's timer repeats its Reveal while the shower's Hello is still in flight.
853        let mut shower = Device::new(Role::Receiver, Presentation::Shower, CODE, None);
854        let mut joiner = Device::new(Role::Sender, Presentation::Joiner, CODE, Some(&Keys::generate()));
855        shower.hear(joiner.author, joiner.take());
856        joiner.hear(shower.author, shower.take());
857        let reveal = joiner.take();
858        shower.hear(joiner.author, reveal.clone());
859        let hello = shower.take();
860        shower.hear(joiner.author, reveal);
861        let repeated_hello = shower.take();
862        assert_eq!(repeated_hello.len(), 1, "a lost Hello is sent again");
863        joiner.hear(shower.author, hello);
864        joiner.hear(shower.author, repeated_hello);
865        assert!(joiner.take().is_empty(), "the joiner doesn't answer a repeated Hello with a Reveal");
866        assert!(joiner.sas().is_some() && shower.sas().is_some());
867        pump(&mut shower, &mut joiner);
868    }
869
870    #[test]
871    fn a_sender_waiting_on_its_ack_ignores_stale_handshake_repeats() {
872        let (mut sender, receiver, identity) = matched_pair(false);
873        sender.session.check_number(&receiver.sas().unwrap()).unwrap();
874        let out = sender.session.approve(bundle_for(&identity, None)).unwrap();
875        sender.absorb(out);
876        sender.take();
877        // The receiver's earlier messages turn up again: none of them is answered with the bundle.
878        sender.hear(receiver.author, vec![Msg::Pake(vec![0x53; 33]), Msg::Hello(vec![1; 40])]);
879        assert!(sender.take().is_empty());
880        assert!(sender.failure().is_none() && sender.session.is_sent());
881    }
882
883    #[test]
884    fn another_protocol_version_says_so() {
885        let mut shower = Device::new(Role::Receiver, Presentation::Shower, CODE, None);
886        let out = shower.session.on_message(Keys::generate().public_key(), Msg::decode(r#"{"v":9,"t":"commit"}"#));
887        shower.absorb(out);
888        assert_eq!(shower.failure(), Some(Failure::Version));
889    }
890
891    #[test]
892    fn a_relay_that_splices_in_its_own_shower_cannot_complete() {
893        // An attacker who knows the code answers the joiner first, then the real shower answers
894        // too: the joiner sees two showers and stops, before any number is shown.
895        let mut joiner = Device::new(Role::Receiver, Presentation::Joiner, CODE, None);
896        let mut fake = Device::new(Role::Sender, Presentation::Shower, CODE, Some(&Keys::generate()));
897        let mut real = Device::new(Role::Sender, Presentation::Shower, CODE, Some(&Keys::generate()));
898        let commit = joiner.take();
899        fake.hear(joiner.author, commit.clone());
900        real.hear(joiner.author, commit);
901        joiner.hear(fake.author, fake.take());
902        joiner.hear(real.author, real.take());
903        assert_eq!(joiner.failure(), Some(Failure::Contention));
904        assert!(joiner.sas().is_none());
905    }
906}