Skip to main content

zaun_community_protocol/client/member/
link.rs

1//! Invitation links (§8.6): `zaun://join/<base64url(InvitePayload)>`.
2
3use zeroize::Zeroizing;
4
5use crate::b64;
6use crate::client::{ExpectedHost, SessionConfig};
7use crate::command::object::InviteLink;
8use crate::encoding::{DecodeError, EncodeError, Reader, Writer};
9use crate::envelope::VersionRange;
10use crate::ids::{CommunityId, HostId, InviteSecret};
11use crate::signed::FORMAT_V1;
12
13/// The link scheme and path.
14pub const INVITE_LINK_PREFIX: &str = "zaun://join/";
15/// Largest `host_address` in bytes.
16const ADDRESS_BYTES: usize = 2_048;
17
18/// The canonical `InvitePayload` (§8.6). Unsigned: after connecting, the welcome must show a
19/// descriptor deriving `community_id`, a delegation naming `host_id`, and a host proof —
20/// which [`InvitePayload::session_config`] makes the session check.
21///
22/// `Debug` never shows the secret ([`InviteSecret`] is redacted); it is zeroized on drop.
23#[derive(Debug, Clone, PartialEq, Eq)]
24pub struct InvitePayload {
25    /// The community.
26    pub community_id: CommunityId,
27    /// The host to connect to.
28    pub host_id: HostId,
29    /// The host's SimpleX contact address, ≤ 2 048 bytes.
30    pub host_address: String,
31    /// The invitation secret.
32    pub invite_secret: InviteSecret,
33    /// Expiry, ms; none = never.
34    pub expires_at: Option<u64>,
35    /// Lowest protocol version of the community.
36    pub protocol_min: u16,
37    /// Highest protocol version of the community.
38    pub protocol_max: u16,
39}
40
41/// A link that is not a valid invitation. Carries no part of the input.
42#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
43pub enum LinkError {
44    /// Not `zaun://join/…`.
45    #[error("not a Zaun invitation link")]
46    Prefix,
47    /// Not strict base64url.
48    #[error("invitation link is not valid base64url")]
49    Encoding,
50    /// Not a canonical `InvitePayload`.
51    #[error("invitation payload is malformed")]
52    Payload,
53    /// The host address is empty or too long, or the version range is invalid.
54    #[error("invitation payload has an invalid field")]
55    Field,
56}
57
58impl From<DecodeError> for LinkError {
59    fn from(_: DecodeError) -> Self {
60        Self::Payload
61    }
62}
63
64impl From<EncodeError> for LinkError {
65    fn from(_: EncodeError) -> Self {
66        Self::Field
67    }
68}
69
70impl InvitePayload {
71    /// Parses a link strictly: prefix, canonical base64url, canonical payload, no trailing
72    /// bytes. Decoded bytes are zeroized.
73    ///
74    /// # Errors
75    /// [`LinkError`], which never echoes the input.
76    pub fn parse(link: &str) -> Result<Self, LinkError> {
77        let encoded = link
78            .strip_prefix(INVITE_LINK_PREFIX)
79            .ok_or(LinkError::Prefix)?;
80        let bytes = Zeroizing::new(b64::decode(encoded).map_err(|_| LinkError::Encoding)?);
81        let mut r = Reader::new(&bytes);
82        if r.u8()? != FORMAT_V1 {
83            return Err(LinkError::Payload);
84        }
85        let community_id = CommunityId::from_bytes(r.array()?);
86        let host_id = HostId::from_bytes(r.array()?);
87        let host_address = r.string(ADDRESS_BYTES)?.to_owned();
88        let secret = Zeroizing::new(r.array::<32>()?);
89        let payload = Self {
90            community_id,
91            host_id,
92            host_address,
93            invite_secret: InviteSecret::from_bytes(*secret),
94            expires_at: r.option(Reader::u64)?,
95            protocol_min: r.u16()?,
96            protocol_max: r.u16()?,
97        };
98        r.finish()?;
99        payload.check()?;
100        Ok(payload)
101    }
102
103    /// Formats the link. The intermediate bytes are zeroized; the returned link is redacted
104    /// in `Debug`.
105    ///
106    /// # Errors
107    /// [`LinkError::Field`] for an empty or oversized address or a bad version range.
108    pub fn to_link(&self) -> Result<InviteLink, LinkError> {
109        self.check()?;
110        let mut w = Writer::new();
111        w.u8(FORMAT_V1);
112        w.fixed(self.community_id.as_bytes());
113        w.fixed(self.host_id.as_bytes());
114        w.string(&self.host_address, ADDRESS_BYTES)?;
115        w.fixed(self.invite_secret.expose());
116        w.option(self.expires_at.as_ref(), |w, v| {
117            w.u64(*v);
118            Ok(())
119        })?;
120        w.u16(self.protocol_min);
121        w.u16(self.protocol_max);
122        let bytes = Zeroizing::new(w.into_bytes());
123        let encoded = Zeroizing::new(b64::encode(&bytes));
124        Ok(InviteLink::new(format!(
125            "{INVITE_LINK_PREFIX}{}",
126            encoded.as_str()
127        )))
128    }
129
130    fn check(&self) -> Result<(), LinkError> {
131        let address = (1..=ADDRESS_BYTES).contains(&self.host_address.len());
132        let versions = self.protocol_min >= 1 && self.protocol_max >= self.protocol_min;
133        if address && versions {
134            Ok(())
135        } else {
136            Err(LinkError::Field)
137        }
138    }
139
140    /// Whether the invitation has expired at `now_ms`.
141    #[must_use]
142    pub fn is_expired(&self, now_ms: u64) -> bool {
143        self.expires_at.is_some_and(|at| now_ms > at)
144    }
145
146    /// Whether the community's version range overlaps `ours`.
147    #[must_use]
148    pub const fn supports(&self, ours: VersionRange) -> bool {
149        self.protocol_min <= ours.max && ours.min <= self.protocol_max
150    }
151
152    /// A session configuration that pins the link's host and community (§8.6).
153    #[must_use]
154    pub fn session_config(&self) -> SessionConfig {
155        SessionConfig::new(ExpectedHost::Id(self.host_id), Some(self.community_id))
156    }
157}