Skip to main content

weirdnet_contacts/
link.rs

1//! Contact links: add someone from a link or a QR code.
2use crate::id::{IdError, UserId};
3
4const SCHEME: &str = "weirdnet-contact://";
5
6/// A link to an identity: who they are, a name to suggest, and addresses to try. Shown as text
7/// or a QR code; opening it adds the identity as a contact.
8#[derive(Clone, Debug, PartialEq, Eq)]
9pub struct ContactLink {
10    /// The identity.
11    pub user: UserId,
12    /// A name to suggest (the person's display name).
13    pub name: String,
14    /// Addresses to dial first, as multiaddr text (may be empty: ask a relay).
15    pub addrs: Vec<String>,
16}
17
18/// Why a link did not parse.
19#[derive(Debug, thiserror::Error)]
20pub enum LinkError {
21    /// Not a `weirdnet-contact://` link.
22    #[error("not a contact link")]
23    Scheme,
24    /// The identity part is not a peer id.
25    #[error(transparent)]
26    Id(#[from] IdError),
27    /// A bad percent escape.
28    #[error("bad escape in the link")]
29    Escape,
30}
31
32fn enc(s: &str, out: &mut String) {
33    for b in s.bytes() {
34        if b.is_ascii_alphanumeric() || b"-._~/".contains(&b) {
35            out.push(b as char);
36        } else {
37            out.push_str(&format!("%{b:02X}"));
38        }
39    }
40}
41
42fn dec(s: &str) -> Result<String, LinkError> {
43    let b = s.as_bytes();
44    let mut out = Vec::with_capacity(b.len());
45    let mut i = 0;
46    while i < b.len() {
47        if b[i] == b'%' {
48            let h = s.get(i + 1..i + 3).ok_or(LinkError::Escape)?;
49            out.push(u8::from_str_radix(h, 16).map_err(|_| LinkError::Escape)?);
50            i += 3;
51        } else {
52            out.push(b[i]);
53            i += 1;
54        }
55    }
56    String::from_utf8(out).map_err(|_| LinkError::Escape)
57}
58
59impl ContactLink {
60    /// The link as text: `weirdnet-contact://<peer id>?name=...&addr=...`.
61    pub fn to_uri(&self) -> String {
62        let mut s = format!("{SCHEME}{}", self.user);
63        let mut sep = '?';
64        if !self.name.is_empty() {
65            s.push(sep);
66            s.push_str("name=");
67            enc(&self.name, &mut s);
68            sep = '&';
69        }
70        for a in &self.addrs {
71            s.push(sep);
72            s.push_str("addr=");
73            enc(a, &mut s);
74            sep = '&';
75        }
76        s
77    }
78
79    /// Parse a link.
80    pub fn parse(s: &str) -> Result<ContactLink, LinkError> {
81        let rest = s.trim().strip_prefix(SCHEME).ok_or(LinkError::Scheme)?;
82        let (id, query) = rest.split_once('?').unwrap_or((rest, ""));
83        let user = UserId::parse(id)?;
84        let (mut name, mut addrs) = (String::new(), Vec::new());
85        for kv in query.split('&').filter(|p| !p.is_empty()) {
86            match kv.split_once('=') {
87                Some(("name", v)) => name = dec(v)?,
88                Some(("addr", v)) => addrs.push(dec(v)?),
89                _ => {}
90            }
91        }
92        Ok(ContactLink { user, name, addrs })
93    }
94}
95
96#[cfg(test)]
97mod tests {
98    use super::*;
99    use weirdnet_net::Keypair;
100
101    #[test]
102    fn links_round_trip_with_odd_characters() {
103        let user = UserId::of_keypair(&Keypair::generate_ed25519());
104        let l = ContactLink {
105            user,
106            name: "Ana & Ben: 100% ünï".into(),
107            addrs: vec!["/dns4/relay.example.com/tcp/4747".into(), "/ip4/10.0.0.1/tcp/1".into()],
108        };
109        let uri = l.to_uri();
110        assert!(uri.starts_with("weirdnet-contact://12D3"), "{uri}");
111        assert_eq!(ContactLink::parse(&uri).unwrap(), l);
112    }
113
114    #[test]
115    fn bad_links_are_refused() {
116        assert!(matches!(ContactLink::parse("https://x"), Err(LinkError::Scheme)));
117        assert!(matches!(ContactLink::parse("weirdnet-contact://nope"), Err(LinkError::Id(_))));
118        let user = UserId::of_keypair(&Keypair::generate_ed25519());
119        assert!(matches!(ContactLink::parse(&format!("weirdnet-contact://{user}?name=%zz")), Err(LinkError::Escape)));
120        assert_eq!(ContactLink::parse(&format!("weirdnet-contact://{user}")).unwrap().name, "");
121    }
122}