Skip to main content

weirdnet_device_link/
session.rs

1//! Both sides of a link, without the network: key agreement, SAS, the sealed
2//! transfer and the offer's single-use rules.
3use std::sync::Mutex;
4
5use sha2::{Digest, Sha256};
6use weirdnet_keys::exchange::{ExchangeSecret, derive};
7use weirdnet_keys::{Key32, open, random_bytes, seal};
8use weirdnet_net::profile::WEIRDNET;
9use weirdnet_net::user::{NodeCert, decode_public, user_id};
10use weirdnet_net::{Keypair, PeerId};
11use zeroize::Zeroizing;
12
13use crate::offer::{Offer, VerifiedOffer, cbor, encode_link};
14use crate::wire::{CREDENTIAL_VERSION, Credential, LinkReply, LinkRequest, MAX_BUNDLE, Received, Transfer};
15use crate::{Error, MAX_ATTEMPTS, OFFER_TTL_MS, Result, VERSION};
16
17const TRANSCRIPT_DOMAIN: &[u8] = b"weirdnet-device-link/v1";
18const KEY_INFO: &[u8] = b"weirdnet-device-link/v1/key";
19const SAS_INFO: &[u8] = b"weirdnet-device-link/v1/sas";
20const TRANSFER_AAD: &[u8] = b"weirdnet-device-link/v1/transfer\n";
21const CREDENTIAL_AAD: &[u8] = b"weirdnet-device-link/v1/credential\n";
22
23fn transcript(offer: &[u8], eph_existing: &[u8; 32]) -> [u8; 32] {
24    let mut h = Sha256::new();
25    h.update(TRANSCRIPT_DOMAIN);
26    h.update(offer);
27    h.update(eph_existing);
28    h.finalize().into()
29}
30
31/// The session key and the 6-digit code both screens show.
32fn session_keys(shared: &[u8; 32], transcript: &[u8; 32]) -> Result<(Key32, String)> {
33    let (key, sas) = derive(shared, transcript, KEY_INFO, SAS_INFO)?;
34    Ok((key, format!("{:06}", u64::from_be_bytes(sas) % 1_000_000)))
35}
36
37fn aad(transcript: &[u8; 32]) -> Vec<u8> {
38    [TRANSFER_AAD, transcript.as_slice()].concat()
39}
40
41fn credential_aad(transcript: &[u8; 32]) -> Vec<u8> {
42    [CREDENTIAL_AAD, transcript.as_slice()].concat()
43}
44
45/// The 32-byte seed's Ed25519 user key.
46pub(crate) fn user_key(seed: &[u8]) -> Result<Keypair> {
47    let mut bytes = Zeroizing::new([0u8; 32]);
48    if seed.len() != 32 {
49        return Err(Error::Invalid("the identity did not check out"));
50    }
51    bytes.copy_from_slice(seed);
52    Keypair::ed25519_from_bytes(bytes.as_mut()).map_err(|_| Error::Invalid("the identity did not check out"))
53}
54
55/// What the new device's screen shows.
56#[derive(Debug, Clone, PartialEq, Eq)]
57pub enum HostStatus {
58    /// Showing the code; nobody has scanned it yet.
59    Waiting,
60    /// Paired: compare this code with the other device.
61    Paired {
62        sas: String,
63    },
64    /// The identity arrived (after the other device confirmed the code).
65    Received {
66        sas: String,
67    },
68    /// Taken into this device; the offer is spent.
69    Done,
70    Cancelled,
71    Expired,
72    Failed(&'static str),
73}
74
75struct Paired {
76    peer: PeerId,
77    key: Key32,
78    transcript: [u8; 32],
79    sas: String,
80}
81
82struct HostInner {
83    attempts: u32,
84    paired: Option<Paired>,
85    received: Option<Received>,
86    confirmed: bool,
87    end: Option<HostStatus>,
88}
89
90/// The new device's side: owns the ephemeral secret behind the offer.
91pub struct Host {
92    secret: ExchangeSecret,
93    offer: VerifiedOffer,
94    link: String,
95    inner: Mutex<HostInner>,
96}
97
98impl std::fmt::Debug for Host {
99    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
100        f.debug_struct("Host").field("peer", &self.offer.peer()).finish_non_exhaustive()
101    }
102}
103
104impl Host {
105    /// A fresh offer for `node_key` at `addrs`, valid for [`OFFER_TTL_MS`].
106    pub fn new(scheme: &str, node_key: &Keypair, addrs: Vec<String>, hint: &str, now_ms: i64) -> Result<Self> {
107        let secret = ExchangeSecret::generate();
108        let nonce: [u8; 16] = random_bytes()?;
109        let mut hint = hint.to_string();
110        while hint.len() > crate::offer::MAX_HINT {
111            hint.pop();
112        }
113        let offer = Offer {
114            v: VERSION,
115            node: node_key.public().encode_protobuf(),
116            eph: secret.public().to_vec(),
117            nonce: nonce.to_vec(),
118            addrs,
119            expires_ms: now_ms + OFFER_TTL_MS,
120            hint,
121        };
122        let (link, offer) = encode_link(scheme, &offer, node_key)?;
123        let inner = HostInner { attempts: 0, paired: None, received: None, confirmed: false, end: None };
124        Ok(Host { secret, offer, link, inner: Mutex::new(inner) })
125    }
126
127    /// The link text (what the QR code encodes).
128    pub fn link(&self) -> &str {
129        &self.link
130    }
131
132    pub fn expires_ms(&self) -> i64 {
133        self.offer.offer.expires_ms
134    }
135
136    fn lock(&self) -> std::sync::MutexGuard<'_, HostInner> {
137        self.inner.lock().unwrap_or_else(|p| p.into_inner())
138    }
139
140    pub fn status(&self, now_ms: i64) -> HostStatus {
141        let mut s = self.lock();
142        self.expire(&mut s, now_ms);
143        if let Some(end) = &s.end {
144            return end.clone();
145        }
146        match (&s.paired, &s.received) {
147            (Some(p), Some(_)) => HostStatus::Received { sas: p.sas.clone() },
148            (Some(p), None) => HostStatus::Paired { sas: p.sas.clone() },
149            _ => HostStatus::Waiting,
150        }
151    }
152
153    fn expire(&self, s: &mut HostInner, now_ms: i64) {
154        // An identity that already arrived stays takeable; the offer only had to
155        // be alive for the pairing and the transfer.
156        if s.end.is_none() && s.received.is_none() && self.offer.expired(now_ms) {
157            s.end = Some(HostStatus::Expired);
158            s.paired = None;
159        }
160    }
161
162    /// Answers a request from `from` (the peer id Noise authenticated).
163    pub fn handle(&self, from: &PeerId, req: LinkRequest, now_ms: i64) -> LinkReply {
164        let mut s = self.lock();
165        self.expire(&mut s, now_ms);
166        if let Some(end) = &s.end {
167            return LinkReply::refused(match end {
168                HostStatus::Expired => "the code expired",
169                HostStatus::Done => "the code was already used",
170                _ => "the code is no longer valid",
171            });
172        }
173        let nonce = match &req {
174            LinkRequest::Hello { nonce, .. }
175            | LinkRequest::Transfer { nonce, .. }
176            | LinkRequest::Credential { nonce, .. }
177            | LinkRequest::Cancel { nonce } => nonce,
178        };
179        if *nonce != self.offer.offer.nonce {
180            return LinkReply::refused("unknown code");
181        }
182        match req {
183            LinkRequest::Hello { eph, .. } => {
184                if s.received.is_some() {
185                    return LinkReply::refused("the code was already used");
186                }
187                s.attempts += 1;
188                if s.attempts > MAX_ATTEMPTS {
189                    s.end = Some(HostStatus::Failed("too many pairing attempts"));
190                    s.paired = None;
191                    return LinkReply::refused("too many pairing attempts");
192                }
193                let Ok(eph) = <[u8; 32]>::try_from(eph.as_slice()) else {
194                    return LinkReply::refused("bad key");
195                };
196                let Some(shared) = self.secret.agree(&eph) else {
197                    return LinkReply::refused("bad key");
198                };
199                let transcript = transcript(&self.offer.bytes, &eph);
200                match session_keys(&shared, &transcript) {
201                    Ok((key, sas)) => {
202                        s.paired = Some(Paired { peer: *from, key, transcript, sas });
203                        s.confirmed = false;
204                        LinkReply::Ok
205                    }
206                    Err(_) => LinkReply::refused("bad key"),
207                }
208            }
209            LinkRequest::Transfer { sealed, .. } => {
210                let Some(p) = s.paired.as_ref().filter(|p| p.peer == *from) else {
211                    return LinkReply::refused("not paired");
212                };
213                if s.received.is_some() {
214                    return LinkReply::refused("the code was already used");
215                }
216                let transfer = open(&p.key, &sealed, &aad(&p.transcript))
217                    .map_err(|_| Error::Invalid("could not open"))
218                    .and_then(|plain| cbor4ii::serde::from_slice::<Transfer>(&plain).map_err(|_| Error::Invalid("could not read")));
219                let transfer = match transfer {
220                    Ok(t) => t,
221                    Err(_) => return LinkReply::refused("could not open the transfer"),
222                };
223                if let Err(reason) = self.check(&transfer) {
224                    s.end = Some(HostStatus::Failed(reason));
225                    s.paired = None;
226                    return LinkReply::refused(reason);
227                }
228                s.received = Some(Received::Full(transfer));
229                LinkReply::Ok
230            }
231            LinkRequest::Credential { sealed, .. } => {
232                let Some(p) = s.paired.as_ref().filter(|p| p.peer == *from) else {
233                    return LinkReply::refused("not paired");
234                };
235                if s.received.is_some() {
236                    return LinkReply::refused("the code was already used");
237                }
238                let cred = open(&p.key, &sealed, &credential_aad(&p.transcript))
239                    .map_err(|_| Error::Invalid("could not open"))
240                    .and_then(|plain| cbor4ii::serde::from_slice::<Credential>(&plain).map_err(|_| Error::Invalid("could not read")));
241                let cred = match cred {
242                    Ok(c) => c,
243                    Err(_) => return LinkReply::refused("could not open the credential"),
244                };
245                if let Err(reason) = self.check_credential(&cred) {
246                    s.end = Some(HostStatus::Failed(reason));
247                    s.paired = None;
248                    return LinkReply::refused(reason);
249                }
250                s.received = Some(Received::Service(cred));
251                LinkReply::Ok
252            }
253            LinkRequest::Cancel { .. } => {
254                if s.paired.as_ref().is_some_and(|p| p.peer == *from) {
255                    s.end = Some(HostStatus::Cancelled);
256                    s.paired = None;
257                    s.received = None;
258                    LinkReply::Ok
259                } else {
260                    LinkReply::refused("not paired")
261                }
262            }
263        }
264    }
265
266    fn check(&self, t: &Transfer) -> std::result::Result<(), &'static str> {
267        const BAD: &str = "the identity did not check out";
268        if t.v != VERSION {
269            return Err("the other device runs a newer version");
270        }
271        let user = user_key(&t.seed).map_err(|_| BAD)?;
272        let user_public = user.public();
273        if user_id(&user_public) != t.user_id || t.node_cert.peer_id != self.offer.peer().to_string() {
274            return Err(BAD);
275        }
276        if !WEIRDNET.verify_cert(&user_public, &t.node_cert) || !t.node_cert.active() {
277            return Err(BAD);
278        }
279        Ok(())
280    }
281
282    fn check_credential(&self, c: &Credential) -> std::result::Result<(), &'static str> {
283        const BAD: &str = "the credential did not check out";
284        if c.v != CREDENTIAL_VERSION {
285            return Err("the other device runs a newer version");
286        }
287        if c.bundle.len() > MAX_BUNDLE {
288            return Err(BAD);
289        }
290        let key = decode_public(&c.user_key).map_err(|_| BAD)?;
291        if user_id(&key) != c.user_id || c.node_cert.peer_id != self.offer.peer().to_string() || c.node_cert.user_id != c.user_id {
292            return Err(BAD);
293        }
294        if !WEIRDNET.verify_cert(&key, &c.node_cert) || !c.node_cert.active() {
295            return Err(BAD);
296        }
297        Ok(())
298    }
299
300    /// The user tapped "Matches" on this device.
301    pub fn confirm(&self) {
302        let mut s = self.lock();
303        if s.paired.is_some() {
304            s.confirmed = true;
305        }
306    }
307
308    /// The identity, once it arrived and the user confirmed the code here. Spends
309    /// the offer; later calls fail.
310    pub fn take(&self) -> Result<Transfer> {
311        if matches!(self.lock().received, Some(Received::Service(_))) {
312            return Err(Error::Invalid("a service link arrived; take it with take_any"));
313        }
314        match self.take_any()? {
315            Received::Full(t) => Ok(t),
316            Received::Service(_) => Err(Error::Invalid("a service link arrived; take it with take_any")),
317        }
318    }
319
320    /// What arrived (a full link's [`Transfer`] or a service link's [`Credential`]),
321    /// once the user confirmed the code here. Spends the offer; later calls fail.
322    pub fn take_any(&self) -> Result<Received> {
323        let mut s = self.lock();
324        if !s.confirmed {
325            return Err(Error::Invalid("confirm the code first"));
326        }
327        let t = s.received.take().ok_or(Error::Invalid("nothing has arrived yet"))?;
328        s.paired = None;
329        s.end = Some(HostStatus::Done);
330        Ok(t)
331    }
332
333    /// The user said the codes differ, or closed the screen.
334    pub fn cancel(&self) {
335        let mut s = self.lock();
336        if s.end.is_none() {
337            s.end = Some(HostStatus::Cancelled);
338        }
339        s.paired = None;
340        s.received = None;
341    }
342}
343
344/// The existing device's side of one pairing.
345pub struct Sender {
346    offer: VerifiedOffer,
347    eph: [u8; 32],
348    key: Key32,
349    transcript: [u8; 32],
350    sas: String,
351}
352
353impl std::fmt::Debug for Sender {
354    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
355        f.debug_struct("Sender").field("peer", &self.offer.peer()).finish_non_exhaustive()
356    }
357}
358
359impl Sender {
360    /// Starts pairing with a scanned offer; send the returned Hello.
361    pub fn start(offer: VerifiedOffer, now_ms: i64) -> Result<(Self, LinkRequest)> {
362        if offer.expired(now_ms) {
363            return Err(Error::Expired);
364        }
365        let secret = ExchangeSecret::generate();
366        let eph = secret.public();
367        let shared = secret.agree(&offer.eph()).ok_or(Error::Invalid("the link is damaged"))?;
368        let transcript = transcript(&offer.bytes, &eph);
369        let (key, sas) = session_keys(&shared, &transcript)?;
370        let hello = LinkRequest::Hello { nonce: offer.offer.nonce.clone(), eph: eph.to_vec() };
371        Ok((Sender { offer, eph, key, transcript, sas }, hello))
372    }
373
374    pub fn sas(&self) -> &str {
375        &self.sas
376    }
377
378    pub fn offer(&self) -> &VerifiedOffer {
379        &self.offer
380    }
381
382    /// Our ephemeral public key (tests).
383    pub fn eph(&self) -> [u8; 32] {
384        self.eph
385    }
386
387    /// The sealed transfer request; only after the user confirmed the SAS.
388    pub fn transfer(&self, t: &Transfer) -> Result<LinkRequest> {
389        let plain = Zeroizing::new(cbor(t)?);
390        let sealed = seal(&self.key, &plain, &aad(&self.transcript))?;
391        Ok(LinkRequest::Transfer { nonce: self.offer.offer.nonce.clone(), sealed })
392    }
393
394    /// The sealed credential request of a service link; only after the user confirmed the SAS.
395    pub fn credential(&self, c: &Credential) -> Result<LinkRequest> {
396        let plain = Zeroizing::new(cbor(c)?);
397        let sealed = seal(&self.key, &plain, &credential_aad(&self.transcript))?;
398        Ok(LinkRequest::Credential { nonce: self.offer.offer.nonce.clone(), sealed })
399    }
400
401    pub fn cancel(&self) -> LinkRequest {
402        LinkRequest::Cancel { nonce: self.offer.offer.nonce.clone() }
403    }
404}
405
406/// A service link's credential for the new device in `offer`: the user's public key, a
407/// node certificate for it signed by `user` (the user keypair, which stays here), the
408/// sync types and `bundle` (for example `weirdnet_sync::LinkBundle` bytes). No seed.
409pub fn make_credential(
410    user: &Keypair,
411    profile_name: &str,
412    settings: &str,
413    sync: &[String],
414    bundle: &[u8],
415    offer: &VerifiedOffer,
416    now_ms: i64,
417) -> Result<Credential> {
418    if bundle.len() > MAX_BUNDLE {
419        return Err(Error::Invalid("the sync bundle is too large"));
420    }
421    let uid = user_id(&user.public());
422    let node_cert: NodeCert = WEIRDNET.certify(user, &uid, &offer.peer().to_string(), &offer.offer.hint, now_ms)?;
423    Ok(Credential {
424        v: CREDENTIAL_VERSION,
425        user_key: user.public().encode_protobuf(),
426        user_id: uid,
427        profile_name: profile_name.to_string(),
428        settings: settings.to_string(),
429        node_cert,
430        sync: sync.to_vec(),
431        bundle: bundle.to_vec(),
432    })
433}
434
435/// A transfer for the new device in `offer`: the seed, and a node certificate
436/// for it signed by the user key.
437pub fn make_transfer(seed: &Key32, profile_name: &str, settings: &str, offer: &VerifiedOffer, now_ms: i64) -> Result<Transfer> {
438    make_transfer_with(seed, profile_name, settings, &[], offer, now_ms)
439}
440
441/// [`make_transfer`], filling the types the user opted in to sync.
442pub fn make_transfer_with(seed: &Key32, profile_name: &str, settings: &str, sync: &[String], offer: &VerifiedOffer, now_ms: i64) -> Result<Transfer> {
443    let user = user_key(&seed.0)?;
444    let uid = user_id(&user.public());
445    let node_cert = WEIRDNET.certify(&user, &uid, &offer.peer().to_string(), &offer.offer.hint, now_ms)?;
446    Ok(Transfer {
447        v: VERSION,
448        seed: seed.0.to_vec(),
449        user_id: uid,
450        profile_name: profile_name.to_string(),
451        settings: settings.to_string(),
452        node_cert,
453        sync: sync.to_vec(),
454    })
455}
456
457#[cfg(test)]
458mod tests {
459    use super::*;
460
461    const SCHEME: &str = "weirdnet-morph://";
462
463    fn new_host(now: i64) -> (Host, Keypair) {
464        let node = Keypair::generate_ed25519();
465        let host = Host::new(SCHEME, &node, vec!["/ip4/192.168.1.5/tcp/4747".into()], "Morph on desk", now).unwrap();
466        (host, node)
467    }
468
469    fn scan(host: &Host, now: i64) -> (Sender, LinkRequest) {
470        Sender::start(crate::decode_link(SCHEME, host.link()).unwrap(), now).unwrap()
471    }
472
473    #[test]
474    fn both_sides_show_the_same_code_and_the_identity_moves() {
475        let (host, _) = new_host(0);
476        let phone = Keypair::generate_ed25519().public().to_peer_id();
477        assert_eq!(host.status(1), HostStatus::Waiting);
478        let (sender, hello) = scan(&host, 1);
479        assert_eq!(host.handle(&phone, hello, 2), LinkReply::Ok);
480        let HostStatus::Paired { sas } = host.status(3) else { panic!("not paired") };
481        assert_eq!(sas, sender.sas());
482        assert_eq!(sas.len(), 6);
483
484        let seed = Key32::random().unwrap();
485        let t = make_transfer(&seed, "Work", "{}", sender.offer(), 4).unwrap();
486        let uid = t.user_id.clone();
487        assert!(host.take().is_err(), "nothing yet");
488        assert_eq!(host.handle(&phone, sender.transfer(&t).unwrap(), 5), LinkReply::Ok);
489        assert!(matches!(host.status(6), HostStatus::Received { .. }));
490        assert!(host.take().is_err(), "not confirmed here yet");
491        host.confirm();
492        let got = host.take().unwrap();
493        assert_eq!(got.seed, seed.0.to_vec());
494        assert_eq!(got.user_id, uid);
495        assert_eq!(got.profile_name, "Work");
496        assert_eq!(host.status(7), HostStatus::Done);
497        // Single use.
498        assert!(host.take().is_err());
499        let (again, hello) = scan(&host, 8);
500        assert!(matches!(host.handle(&phone, hello, 9), LinkReply::Refused { .. }));
501        assert!(matches!(host.handle(&phone, again.transfer(&t).unwrap(), 9), LinkReply::Refused { .. }));
502    }
503
504    #[test]
505    fn a_service_credential_moves_without_a_seed() {
506        let (host, node) = new_host(0);
507        let phone = Keypair::generate_ed25519().public().to_peer_id();
508        let (sender, hello) = scan(&host, 1);
509        assert_eq!(host.handle(&phone, hello, 2), LinkReply::Ok);
510        let user = Keypair::generate_ed25519();
511        let c = make_credential(&user, "Work", "{}", &["ymir.pool".into()], b"bundle bytes", sender.offer(), 3).unwrap();
512        assert!(!format!("{c:?}").contains("bundle"), "Debug hides the bundle");
513        // Sealed for a credential: it does not open as a transfer, nor the other way round.
514        let LinkRequest::Credential { nonce, sealed } = sender.credential(&c).unwrap() else { panic!() };
515        assert!(matches!(host.handle(&phone, LinkRequest::Transfer { nonce: nonce.clone(), sealed: sealed.clone() }, 4), LinkReply::Refused { .. }));
516        assert_eq!(host.handle(&phone, LinkRequest::Credential { nonce, sealed }, 4), LinkReply::Ok);
517        host.confirm();
518        assert!(host.take().is_err(), "take() is for full links only");
519        let Received::Service(got) = host.take_any().unwrap() else { panic!("expected a service link") };
520        assert_eq!(got.bundle, b"bundle bytes");
521        assert_eq!(got.user_key, user.public().encode_protobuf());
522        assert_eq!(got.node_cert.peer_id, node.public().to_peer_id().to_string());
523        assert!(WEIRDNET.verify_cert(&user.public(), &got.node_cert));
524        assert_eq!(host.status(5), HostStatus::Done);
525    }
526
527    #[test]
528    fn a_credential_for_another_node_or_user_is_refused() {
529        let (host, _) = new_host(0);
530        let phone = Keypair::generate_ed25519().public().to_peer_id();
531        let (sender, hello) = scan(&host, 1);
532        host.handle(&phone, hello, 1);
533        let user = Keypair::generate_ed25519();
534        let mut c = make_credential(&user, "Work", "{}", &[], b"", sender.offer(), 1).unwrap();
535        c.user_key = Keypair::generate_ed25519().public().encode_protobuf();
536        assert!(matches!(host.handle(&phone, sender.credential(&c).unwrap(), 2), LinkReply::Refused { .. }));
537        assert!(matches!(host.status(3), HostStatus::Failed(_)));
538        assert!(make_credential(&user, "Work", "{}", &[], &vec![0; MAX_BUNDLE + 1], sender.offer(), 1).is_err());
539    }
540
541    #[test]
542    fn a_transfer_from_another_peer_or_key_is_refused() {
543        let (host, _) = new_host(0);
544        let phone = Keypair::generate_ed25519().public().to_peer_id();
545        let thief = Keypair::generate_ed25519().public().to_peer_id();
546        let (sender, hello) = scan(&host, 1);
547        host.handle(&phone, hello, 1);
548        let seed = Key32::random().unwrap();
549        let t = make_transfer(&seed, "Work", "{}", sender.offer(), 1).unwrap();
550        assert!(matches!(host.handle(&thief, sender.transfer(&t).unwrap(), 2), LinkReply::Refused { .. }));
551        // A second scanner re-pairs; the first sender's key no longer opens.
552        let (other, hello) = scan(&host, 2);
553        assert_ne!(other.sas(), sender.sas());
554        host.handle(&thief, hello, 2);
555        assert!(matches!(host.handle(&thief, sender.transfer(&t).unwrap(), 3), LinkReply::Refused { .. }));
556    }
557
558    #[test]
559    fn a_certificate_for_another_node_or_user_is_refused() {
560        let (host, _) = new_host(0);
561        let phone = Keypair::generate_ed25519().public().to_peer_id();
562        let (sender, hello) = scan(&host, 1);
563        host.handle(&phone, hello, 1);
564        let seed = Key32::random().unwrap();
565        let mut t = make_transfer(&seed, "Work", "{}", sender.offer(), 1).unwrap();
566        t.user_id = "someone-else".into();
567        assert!(matches!(host.handle(&phone, sender.transfer(&t).unwrap(), 2), LinkReply::Refused { .. }));
568        assert_eq!(host.status(3), HostStatus::Failed("the identity did not check out"));
569    }
570
571    #[test]
572    fn three_attempts_then_the_code_dies() {
573        let (host, _) = new_host(0);
574        let phone = Keypair::generate_ed25519().public().to_peer_id();
575        for _ in 0..MAX_ATTEMPTS {
576            let (_, hello) = scan(&host, 1);
577            assert_eq!(host.handle(&phone, hello, 1), LinkReply::Ok);
578        }
579        let (_, hello) = scan(&host, 1);
580        assert!(matches!(host.handle(&phone, hello, 1), LinkReply::Refused { .. }));
581        assert_eq!(host.status(1), HostStatus::Failed("too many pairing attempts"));
582    }
583
584    #[test]
585    fn codes_expire_and_cancel() {
586        let (host, _) = new_host(0);
587        let link = crate::decode_link(SCHEME, host.link()).unwrap();
588        assert!(matches!(Sender::start(link, OFFER_TTL_MS + 1), Err(Error::Expired)));
589        let phone = Keypair::generate_ed25519().public().to_peer_id();
590        let (_, hello) = scan(&host, 1);
591        assert!(matches!(host.handle(&phone, hello, OFFER_TTL_MS + 1), LinkReply::Refused { .. }));
592        assert_eq!(host.status(OFFER_TTL_MS + 1), HostStatus::Expired);
593
594        let (host, _) = new_host(0);
595        let (sender, hello) = scan(&host, 1);
596        host.handle(&phone, hello, 1);
597        assert_eq!(host.handle(&phone, sender.cancel(), 2), LinkReply::Ok);
598        assert_eq!(host.status(2), HostStatus::Cancelled);
599        let (host, _) = new_host(0);
600        host.cancel();
601        assert_eq!(host.status(1), HostStatus::Cancelled);
602    }
603
604    #[test]
605    fn transfers_do_not_show_the_seed() {
606        let (host, _) = new_host(0);
607        let (sender, _) = scan(&host, 1);
608        let t = make_transfer(&Key32([9; 32]), "Work", "{}", sender.offer(), 1).unwrap();
609        assert!(!format!("{t:?}").contains("9, 9"));
610        assert!(!format!("{host:?} {sender:?}").contains("secret"));
611    }
612}