use crate::id::{IdError, UserId};
const SCHEME: &str = "weirdnet-contact://";
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ContactLink {
pub user: UserId,
pub name: String,
pub addrs: Vec<String>,
}
#[derive(Debug, thiserror::Error)]
pub enum LinkError {
#[error("not a contact link")]
Scheme,
#[error(transparent)]
Id(#[from] IdError),
#[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 {
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
}
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, "");
}
}