Skip to main content

weirdnet_device_link/
invite.rs

1//! The other direction: the **existing device** shows an invite as a QR code
2//! or link (`<scheme>invite/…`) and the **new device** scans it. The invite
3//! is only a meeting point: the new device answers it with its own signed
4//! [`Offer`](crate::Offer) link over `/weirdnet/link-invite/2`, and from there
5//! the link runs exactly as before: the existing device dials the offer,
6//! both screens show the same six-digit code, and nothing moves until the
7//! user confirms it on both. An invite holds no secret; whoever answers it
8//! still has to show the same code.
9use std::sync::{Arc, Mutex};
10
11use base64::Engine;
12use base64::engine::general_purpose::URL_SAFE_NO_PAD;
13use serde::{Deserialize, Serialize};
14use weirdnet_keys::random_bytes;
15use weirdnet_net::node::{Handler, NodeConfig};
16use weirdnet_net::profile::{Profile, WEIRDNET};
17use weirdnet_net::{Keypair, Multiaddr, PeerId, now_ms};
18
19use crate::compact::{Bytes, pack_addrs, unpack_addrs};
20use crate::net::listen_addrs;
21use crate::offer::{MAX_ADDRS, cbor, older_or_damaged, version_error};
22use crate::reach::{self, LinkNode};
23use crate::wire::LinkReply;
24use crate::{Error, OFFER_TTL_MS, Result, VERSION, decode_link};
25
26/// The invite's own stream id: offers are pushed here, not on `/weirdnet/link/2`.
27pub static INVITE_PROFILE: Profile = Profile { protocol: "/weirdnet/link-invite/2", thread: "weirdnet-link-invite", ..WEIRDNET };
28
29/// Longest invite text accepted.
30const MAX_INVITE: usize = 2048;
31
32/// What the existing device shows. On the wire (v2) it is a CBOR array: the
33/// peer id as bytes, addresses packed ([`crate::compact`]).
34#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
35#[serde(into = "InviteWire", try_from = "InviteWire")]
36pub struct Invite {
37    pub v: u8,
38    /// The listening node's peer id (a throwaway key).
39    pub peer: String,
40    /// Where it listens, without the `/p2p/` suffix.
41    pub addrs: Vec<String>,
42    /// 16 random bytes the answer must carry.
43    #[serde(with = "crate::bytes")]
44    pub token: Vec<u8>,
45    /// Unix ms after which the invite is dead.
46    pub expires_ms: i64,
47}
48
49#[derive(Serialize, Deserialize)]
50struct InviteWire(u8, Bytes, Vec<Bytes>, Bytes, i64);
51
52impl From<Invite> for InviteWire {
53    fn from(i: Invite) -> Self {
54        let peer = i.peer.parse::<PeerId>().map(|p| p.to_bytes()).unwrap_or_default();
55        InviteWire(i.v, Bytes(peer), pack_addrs(&i.addrs), Bytes(i.token), i.expires_ms)
56    }
57}
58
59impl TryFrom<InviteWire> for Invite {
60    type Error = &'static str;
61    fn try_from(InviteWire(v, peer, addrs, token, expires_ms): InviteWire) -> std::result::Result<Self, &'static str> {
62        let peer = PeerId::from_bytes(&peer.0).map_err(|_| "bad peer id")?.to_string();
63        Ok(Invite { v, peer, addrs: unpack_addrs(&addrs), token: token.0, expires_ms })
64    }
65}
66
67/// The new device's answer: its offer link.
68#[derive(Debug, Clone, Serialize, Deserialize)]
69pub enum InviteRequest {
70    Offer {
71        #[serde(with = "crate::bytes")]
72        token: Vec<u8>,
73        link: String,
74    },
75}
76
77/// `<scheme>invite/<base64url CBOR>`.
78pub fn encode_invite(scheme: &str, invite: &Invite) -> Result<String> {
79    Ok(format!("{scheme}invite/{}", URL_SAFE_NO_PAD.encode(cbor(invite)?)))
80}
81
82/// Reads an invite and checks its shape (expiry is the caller's, as for offers).
83pub fn decode_invite(scheme: &str, text: &str) -> Result<Invite> {
84    let text = text.trim();
85    if text.len() > MAX_INVITE {
86        return Err(Error::Invalid("the link is too long"));
87    }
88    let body = text.strip_prefix(&format!("{scheme}invite/")).ok_or(Error::Invalid("not a device invite"))?;
89    let blob = URL_SAFE_NO_PAD.decode(body).map_err(|_| Error::Invalid("the link is damaged"))?;
90    let invite: Invite = cbor4ii::serde::from_slice(&blob).map_err(|_| older_or_damaged(&blob))?;
91    if invite.v != VERSION {
92        return Err(version_error(invite.v));
93    }
94    if invite.token.len() != 16 || invite.addrs.is_empty() || invite.addrs.len() > MAX_ADDRS || invite.peer.parse::<PeerId>().is_err() {
95        return Err(Error::Invalid("the link is damaged"));
96    }
97    Ok(invite)
98}
99
100/// Whether `text` is an invite (rather than an offer) for `scheme`.
101pub fn is_invite(scheme: &str, text: &str) -> bool {
102    text.trim().starts_with(&format!("{scheme}invite/"))
103}
104
105struct Inbox {
106    scheme: String,
107    token: Vec<u8>,
108    expires_ms: i64,
109    offer: Mutex<Option<String>>,
110}
111
112impl Handler<InviteRequest, LinkReply> for Inbox {
113    fn request(&self, _from: &PeerId, req: InviteRequest) -> LinkReply {
114        let InviteRequest::Offer { token, link } = req;
115        if token != self.token {
116            return LinkReply::refused("not this invite");
117        }
118        if now_ms() > self.expires_ms {
119            return LinkReply::refused("this invite expired");
120        }
121        if decode_link(&self.scheme, &link).is_err() {
122            return LinkReply::refused("not a device link");
123        }
124        let mut offer = self.offer.lock().unwrap_or_else(|p| p.into_inner());
125        if offer.is_some() {
126            return LinkReply::refused("this invite was already answered");
127        }
128        *offer = Some(link);
129        LinkReply::Ok
130    }
131}
132
133/// The existing device, listening for an answer to its invite. Stops when
134/// dropped.
135pub struct InviteHost {
136    node: LinkNode<InviteRequest, LinkReply>,
137    inbox: Arc<Inbox>,
138    link: String,
139}
140
141impl InviteHost {
142    pub fn start(scheme: &str, cfg: NodeConfig) -> Result<Self> {
143        let token: [u8; 16] = random_bytes()?;
144        let expires_ms = now_ms() + OFFER_TTL_MS;
145        let inbox = Arc::new(Inbox { scheme: scheme.to_string(), token: token.to_vec(), expires_ms, offer: Mutex::new(None) });
146        let key = Keypair::generate_ed25519();
147        let peer = key.public().to_peer_id();
148        let node = reach::start(&INVITE_PROFILE, key, cfg, inbox.clone())?;
149        let addrs =
150            listen_addrs(&node.node, !node.relays.is_empty()).ok_or_else(|| Error::Net("network: could not listen for the other device".into()))?;
151        let invite = Invite { v: VERSION, peer: peer.to_string(), addrs, token: token.to_vec(), expires_ms };
152        let link = encode_invite(scheme, &invite)?;
153        Ok(InviteHost { node, inbox, link })
154    }
155
156    /// The text to show as a QR code and to copy.
157    pub fn link(&self) -> &str {
158        &self.link
159    }
160
161    pub fn expires_ms(&self) -> i64 {
162        self.inbox.expires_ms
163    }
164
165    pub fn expired(&self) -> bool {
166        now_ms() > self.inbox.expires_ms
167    }
168
169    /// The offer link the new device sent, once (then pair with it as if it
170    /// had been scanned).
171    pub fn take_offer(&self) -> Option<String> {
172        self.inbox.offer.lock().unwrap_or_else(|p| p.into_inner()).take()
173    }
174
175    /// The node's network status (connections, relay reservations).
176    pub fn net_status(&self) -> weirdnet_net::node::Status {
177        self.node.node.status()
178    }
179}
180
181impl Drop for InviteHost {
182    fn drop(&mut self) {
183        self.node.node.halt();
184    }
185}
186
187/// The new device: answer `invite` with its own `offer_link`.
188pub fn answer_invite(scheme: &str, invite: &str, offer_link: &str, cfg: NodeConfig) -> Result<()> {
189    let invite = decode_invite(scheme, invite)?;
190    if now_ms() > invite.expires_ms {
191        return Err(Error::Expired);
192    }
193    let peer: PeerId = invite.peer.parse().map_err(|_| Error::Invalid("the link is damaged"))?;
194    let addrs: Vec<Multiaddr> = invite.addrs.iter().filter_map(|a| format!("{a}/p2p/{peer}").parse().ok()).collect();
195    let node = reach::start::<InviteRequest, LinkReply>(&INVITE_PROFILE, Keypair::generate_ed25519(), cfg, Arc::new(NoAnswers))?;
196    let reply = node.node.request(peer, &addrs, InviteRequest::Offer { token: invite.token, link: offer_link.to_string() });
197    node.node.halt();
198    match reply? {
199        LinkReply::Ok => Ok(()),
200        LinkReply::Refused { reason } => Err(Error::Refused(reason)),
201    }
202}
203
204struct NoAnswers;
205
206impl Handler<InviteRequest, LinkReply> for NoAnswers {
207    fn request(&self, _from: &PeerId, _req: InviteRequest) -> LinkReply {
208        LinkReply::refused("this device is not inviting")
209    }
210}
211
212#[cfg(test)]
213mod tests {
214    use super::*;
215    use crate::{HostNode, HostStatus, Pairing};
216    use weirdnet_keys::Key32;
217
218    const SCHEME: &str = "weirdnet-morph://";
219
220    fn memory() -> NodeConfig {
221        NodeConfig { listen: vec!["/memory/0".parse().unwrap()], memory: true, ..Default::default() }
222    }
223
224    fn dial_only() -> NodeConfig {
225        NodeConfig { memory: true, ..Default::default() }
226    }
227
228    #[test]
229    fn an_invite_round_trips_and_rejects_damage() {
230        let invite = Invite {
231            v: VERSION,
232            peer: Keypair::generate_ed25519().public().to_peer_id().to_string(),
233            addrs: vec!["/ip4/192.168.1.2/udp/4001/quic-v1".into()],
234            token: vec![7; 16],
235            expires_ms: 1,
236        };
237        let text = encode_invite(SCHEME, &invite).unwrap();
238        assert!(is_invite(SCHEME, &text));
239        assert!(!is_invite(SCHEME, "weirdnet-morph://link/abc"));
240        assert_eq!(decode_invite(SCHEME, &text).unwrap(), invite);
241        assert!(decode_invite(SCHEME, &text[..text.len() - 4]).is_err());
242        assert!(decode_invite(SCHEME, "weirdnet-morph://link/abc").is_err());
243        assert!(decode_invite(SCHEME, &"x".repeat(5000)).is_err());
244    }
245
246    /// What a typical desktop listens on (LAN, Tailscale, Docker, IPv6, the
247    /// public relay's circuit), as libp2p reports it.
248    fn realistic_reachable(peer: &PeerId) -> Vec<String> {
249        let relay = crate::KNOWN_RELAYS[0];
250        [
251            "/ip4/10.0.0.2/tcp/41234".to_string(),
252            "/ip4/10.0.0.2/udp/41234/quic-v1".into(),
253            "/ip4/100.101.102.103/tcp/41234".into(),
254            "/ip4/100.101.102.103/udp/41234/quic-v1".into(),
255            "/ip4/172.17.0.1/tcp/41234".into(),
256            "/ip4/127.0.0.1/tcp/41234".into(),
257            "/ip6/fe80::1/tcp/41235".into(),
258            "/ip6/2600:1700:abcd:1234:5678:9abc:def0:1234/tcp/41235".into(),
259            format!("{relay}/p2p-circuit"),
260            format!("{relay}/p2p-circuit/p2p/{peer}"),
261        ]
262        .to_vec()
263    }
264
265    /// A phone has to read the code off a laptop screen: v1 made a version 18
266    /// QR; v2 is about 110 bytes of CBOR (version 9 at M).
267    #[test]
268    fn a_realistic_invite_is_small_and_a_low_qr_version() {
269        let key = Keypair::generate_ed25519();
270        let peer = key.public().to_peer_id();
271        let addrs = crate::offer_addrs(&realistic_reachable(&peer));
272        assert_eq!(addrs.len(), 4, "{addrs:?}");
273        assert_eq!(addrs[0], "/ip4/10.0.0.2/tcp/41234", "the LAN first");
274        assert_eq!(addrs[1], "/ip4/100.101.102.103/tcp/41234", "another host before another transport");
275        assert!(addrs.iter().all(|a| !a.contains("172.17.") && !a.contains("127.0.0.1") && !a.contains("fe80")));
276        let invite = Invite { v: VERSION, peer: peer.to_string(), addrs, token: vec![9; 16], expires_ms: now_ms() + OFFER_TTL_MS };
277        let raw = cbor(&invite).unwrap();
278        assert!(raw.len() < 120, "{} bytes", raw.len());
279        let text = encode_invite(SCHEME, &invite).unwrap();
280        let qr = qrcode::QrCode::with_error_correction_level(text.as_bytes(), qrcode::EcLevel::M).unwrap();
281        assert!(matches!(qr.version(), qrcode::Version::Normal(v) if v <= 9), "{:?} for {} chars", qr.version(), text.len());
282        println!("invite: {} bytes CBOR, {} chars, QR {:?} at M", raw.len(), text.len(), qr.version());
283        assert_eq!(decode_invite(SCHEME, &text).unwrap(), invite);
284    }
285
286    /// The built-in relay travels as one byte and the reader rebuilds its
287    /// full circuit (relay address and peer id) from its own list.
288    #[test]
289    fn the_known_relay_circuit_is_rebuilt_by_the_reader() {
290        let key = Keypair::generate_ed25519();
291        let circuit = format!("{}/p2p-circuit", crate::KNOWN_RELAYS[0]);
292        let invite =
293            Invite { v: VERSION, peer: key.public().to_peer_id().to_string(), addrs: vec![circuit.clone()], token: vec![1; 16], expires_ms: 5 };
294        let raw = cbor(&invite).unwrap();
295        assert!(!raw.windows(4).any(|w| w == b"dns4" || w == b"12D3"), "no relay text on the wire");
296        let read = decode_invite(SCHEME, &encode_invite(SCHEME, &invite).unwrap()).unwrap();
297        assert_eq!(read.addrs, vec![circuit]);
298    }
299
300    /// A v1 code (a CBOR map) says to update rather than "damaged".
301    #[test]
302    fn an_old_invite_says_update() {
303        #[derive(Serialize)]
304        struct V1 {
305            v: u8,
306            peer: String,
307        }
308        let blob = cbor(&V1 { v: 1, peer: "x".into() }).unwrap();
309        let text = format!("{SCHEME}invite/{}", URL_SAFE_NO_PAD.encode(blob));
310        let err = decode_invite(SCHEME, &text).unwrap_err().to_string();
311        assert!(err.contains("older version"), "{err}");
312    }
313
314    #[test]
315    fn the_new_device_scans_the_invite_and_the_identity_moves_after_both_confirm() {
316        // Existing device: shows the invite.
317        let existing = InviteHost::start(SCHEME, memory()).unwrap();
318        assert!(existing.take_offer().is_none());
319        // New device: scans it and answers with its own offer.
320        let new_device = HostNode::start(SCHEME, Keypair::generate_ed25519(), memory(), "Morph on desk").unwrap();
321        answer_invite(SCHEME, existing.link(), new_device.link(), dial_only()).unwrap();
322        // A second answer (anyone else's) is refused.
323        let other = HostNode::start(SCHEME, Keypair::generate_ed25519(), memory(), "intruder").unwrap();
324        assert!(matches!(answer_invite(SCHEME, existing.link(), other.link(), dial_only()), Err(Error::Refused(_))));
325        // Existing device: pairs with the offer it got, as if scanned.
326        let offer = existing.take_offer().unwrap();
327        assert!(existing.take_offer().is_none(), "taken once");
328        let mut pairing = Pairing::start(SCHEME, &offer, dial_only()).unwrap();
329        assert_eq!(pairing.device(), "Morph on desk");
330        let HostStatus::Paired { sas } = new_device.status() else { panic!("not paired") };
331        assert_eq!(sas, pairing.sas());
332        let seed = Key32::random().unwrap();
333        new_device.confirm();
334        pairing.send(&seed, "Work", "{}").unwrap();
335        assert_eq!(new_device.take().unwrap().seed, seed.0.to_vec());
336    }
337
338    #[test]
339    fn a_wrong_token_or_a_non_link_is_refused() {
340        let existing = InviteHost::start(SCHEME, memory()).unwrap();
341        let mut invite = decode_invite(SCHEME, existing.link()).unwrap();
342        invite.token = vec![0; 16];
343        let forged = encode_invite(SCHEME, &invite).unwrap();
344        let new_device = HostNode::start(SCHEME, Keypair::generate_ed25519(), memory(), "desk").unwrap();
345        assert!(matches!(answer_invite(SCHEME, &forged, new_device.link(), dial_only()), Err(Error::Refused(_))));
346        assert!(matches!(answer_invite(SCHEME, existing.link(), "hello", dial_only()), Err(Error::Refused(_))));
347        assert!(existing.take_offer().is_none());
348    }
349}