weirdnet-contacts 0.1.0

A contact book for Weirdnet apps: trusted and blocked identities, presence with privacy rules (base to everyone, detail to trusted contacts), signed text direct messages with delivery state and an offline queue, and contact links, served over weirdnet-service.
Documentation
//! Contact links: add someone from a link or a QR code.
use crate::id::{IdError, UserId};

const SCHEME: &str = "weirdnet-contact://";

/// A link to an identity: who they are, a name to suggest, and addresses to try. Shown as text
/// or a QR code; opening it adds the identity as a contact.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ContactLink {
    /// The identity.
    pub user: UserId,
    /// A name to suggest (the person's display name).
    pub name: String,
    /// Addresses to dial first, as multiaddr text (may be empty: ask a relay).
    pub addrs: Vec<String>,
}

/// Why a link did not parse.
#[derive(Debug, thiserror::Error)]
pub enum LinkError {
    /// Not a `weirdnet-contact://` link.
    #[error("not a contact link")]
    Scheme,
    /// The identity part is not a peer id.
    #[error(transparent)]
    Id(#[from] IdError),
    /// A bad percent escape.
    #[error("bad escape in the link")]
    Escape,
}

fn enc(s: &str, out: &mut String) {
    for b in s.bytes() {
        if b.is_ascii_alphanumeric() || b"-._~/".contains(&b) {
            out.push(b as char);
        } else {
            out.push_str(&format!("%{b:02X}"));
        }
    }
}

fn dec(s: &str) -> Result<String, LinkError> {
    let b = s.as_bytes();
    let mut out = Vec::with_capacity(b.len());
    let mut i = 0;
    while i < b.len() {
        if b[i] == b'%' {
            let h = s.get(i + 1..i + 3).ok_or(LinkError::Escape)?;
            out.push(u8::from_str_radix(h, 16).map_err(|_| LinkError::Escape)?);
            i += 3;
        } else {
            out.push(b[i]);
            i += 1;
        }
    }
    String::from_utf8(out).map_err(|_| LinkError::Escape)
}

impl ContactLink {
    /// The link as text: `weirdnet-contact://<peer id>?name=...&addr=...`.
    pub fn to_uri(&self) -> String {
        let mut s = format!("{SCHEME}{}", self.user);
        let mut sep = '?';
        if !self.name.is_empty() {
            s.push(sep);
            s.push_str("name=");
            enc(&self.name, &mut s);
            sep = '&';
        }
        for a in &self.addrs {
            s.push(sep);
            s.push_str("addr=");
            enc(a, &mut s);
            sep = '&';
        }
        s
    }

    /// Parse a link.
    pub fn parse(s: &str) -> Result<ContactLink, LinkError> {
        let rest = s.trim().strip_prefix(SCHEME).ok_or(LinkError::Scheme)?;
        let (id, query) = rest.split_once('?').unwrap_or((rest, ""));
        let user = UserId::parse(id)?;
        let (mut name, mut addrs) = (String::new(), Vec::new());
        for kv in query.split('&').filter(|p| !p.is_empty()) {
            match kv.split_once('=') {
                Some(("name", v)) => name = dec(v)?,
                Some(("addr", v)) => addrs.push(dec(v)?),
                _ => {}
            }
        }
        Ok(ContactLink { user, name, addrs })
    }
}

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

    #[test]
    fn links_round_trip_with_odd_characters() {
        let user = UserId::of_keypair(&Keypair::generate_ed25519());
        let l = ContactLink {
            user,
            name: "Ana & Ben: 100% ünï".into(),
            addrs: vec!["/dns4/relay.example.com/tcp/4747".into(), "/ip4/10.0.0.1/tcp/1".into()],
        };
        let uri = l.to_uri();
        assert!(uri.starts_with("weirdnet-contact://12D3"), "{uri}");
        assert_eq!(ContactLink::parse(&uri).unwrap(), l);
    }

    #[test]
    fn bad_links_are_refused() {
        assert!(matches!(ContactLink::parse("https://x"), Err(LinkError::Scheme)));
        assert!(matches!(ContactLink::parse("weirdnet-contact://nope"), Err(LinkError::Id(_))));
        let user = UserId::of_keypair(&Keypair::generate_ed25519());
        assert!(matches!(ContactLink::parse(&format!("weirdnet-contact://{user}?name=%zz")), Err(LinkError::Escape)));
        assert_eq!(ContactLink::parse(&format!("weirdnet-contact://{user}")).unwrap().name, "");
    }
}