Skip to main content

vector_core/community/
invite.rs

1//! Targeted invites (GROUP_PROTOCOL.md).
2//!
3//! An invite bundle is the key material a new member needs to join: the server-root
4//! key, the granted channels' keys + ids + epochs + names, the relay set (the 
5//! bootstrap), the owner attestation, and the Community id/name. It is delivered to the
6//! invitee's npub over a NIP-17 gift-wrapped DM (the carrier; see the service/command
7//! layer). `accept_invite` reconstructs a member-view Community (keyless — authority is
8//! the owner-rooted roster, not a held key).
9//!
10//! Byte fields are hex strings so the bundle is plain JSON inside the DM rumor.
11
12use serde::{Deserialize, Serialize};
13
14use super::{Channel, ChannelId, ChannelKey, Community, CommunityId, Epoch, ServerRootKey};
15use crate::stored_event::event_kind;
16use nostr_sdk::prelude::{EventBuilder, Kind, PublicKey, UnsignedEvent};
17
18/// A granted channel inside an invite bundle.
19#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
20pub struct InviteChannel {
21    pub id: String,
22    pub key: String,
23    pub epoch: u64,
24    pub name: String,
25}
26
27/// Everything a new member needs to join a Community.
28#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
29pub struct CommunityInvite {
30    pub community_id: String,
31    pub name: String,
32    pub server_root_key: String,
33    /// The server-root's current epoch, so a joiner adopts the right base read clock. `default`
34    /// keeps older bundles parseable (they predate rotation, so epoch 0 is correct for them).
35    #[serde(default)]
36    pub server_root_epoch: u64,
37    pub relays: Vec<String>,
38    pub channels: Vec<InviteChannel>,
39    /// Owner attestation (signed event JSON) so the joiner learns + verifies who the owner
40    /// is. `serde(default)` keeps older bundles (pre-feature) parseable.
41    #[serde(default)]
42    pub owner_attestation: Option<String>,
43}
44
45/// Hard caps on a received bundle. A bundle arrives over an unauthenticated gift wrap
46/// from an arbitrary sender, so a hostile one can declare an unbounded channel/relay
47/// list to force mass allocation + per-channel DB writes + relay connections. Reject
48/// anything past a sane MVP ceiling before allocating.
49const MAX_INVITE_CHANNELS: usize = 256;
50
51impl CommunityInvite {
52    pub fn to_json(&self) -> Result<String, String> {
53        serde_json::to_string(self).map_err(|e| e.to_string())
54    }
55    pub fn from_json(json: &str) -> Result<Self, String> {
56        let mut inv: Self = serde_json::from_str(json).map_err(|e| e.to_string())?;
57        // Truncate-on-read: an inbound bundle is unauthenticated, so enforce the relay cap as it
58        // enters rather than trusting (or rejecting on) the sender's count.
59        inv.relays = super::cap_relays(inv.relays);
60        Ok(inv)
61    }
62
63    /// Reject a bundle whose channel count exceeds the MVP ceiling (DoS guard for inbound,
64    /// attacker-controlled bundles). Relays are capped by truncation (`cap_relays`), not rejection,
65    /// so a >5 or legacy bundle degrades to the cap rather than failing the whole join.
66    pub fn validate(&self) -> Result<(), String> {
67        if self.channels.len() > MAX_INVITE_CHANNELS {
68            return Err(format!("invite declares too many channels ({})", self.channels.len()));
69        }
70        Ok(())
71    }
72}
73
74/// Decode a 64-char hex string to 32 bytes, rejecting malformed input (never silently zero-fills —
75/// a corrupt invite must error, not fabricate keys). Public input → SIMD-validated decode.
76fn hex32(hex: &str) -> Result<[u8; 32], String> {
77    crate::simd::hex::hex_to_bytes_32_checked(hex)
78        .ok_or_else(|| format!("invalid or wrong-length 64-char hex ({} chars)", hex.len()))
79}
80
81/// Build an invite bundle granting ALL of a Community's channels (the MVP grants the
82/// full channel set; per-channel/role-scoped grants are a later feature). Only the
83/// management *pubkey* is included — never the secret, so an invited member can't
84/// write metadata.
85pub fn build_invite(community: &Community) -> CommunityInvite {
86    CommunityInvite {
87        community_id: community.id.to_hex(),
88        name: community.name.clone(),
89        server_root_key: crate::simd::hex::bytes_to_hex_32(community.server_root_key.as_bytes()),
90        server_root_epoch: community.server_root_epoch.0,
91        relays: super::cap_relays(community.relays.clone()),
92        channels: community
93            .channels
94            .iter()
95            .map(|c| InviteChannel {
96                id: c.id.to_hex(),
97                key: crate::simd::hex::bytes_to_hex_32(c.key.as_bytes()),
98                epoch: c.epoch.0,
99                name: c.name.clone(),
100            })
101            .collect(),
102        owner_attestation: community.owner_attestation.clone(),
103    }
104}
105
106/// Reconstruct a **member-view** Community from an invite bundle: full read/post access via the
107/// granted channel keys (keyless — write authority is the member's npub roster rank, not a held
108/// key).
109pub fn accept_invite(invite: &CommunityInvite) -> Result<Community, String> {
110    invite.validate()?;
111    let id = CommunityId(hex32(&invite.community_id)?);
112    let server_root_key = ServerRootKey(hex32(&invite.server_root_key)?);
113
114    // Keep the owner attestation ONLY if it verifies against this community's id (keyless — the
115    // community_id is the sole binding; a bundle can't smuggle a bogus owner claim).
116    let owner_attestation = invite.owner_attestation.as_ref().and_then(|att| {
117        super::owner::verify_owner_attestation(att, &invite.community_id)
118            .map(|_| att.clone())
119    });
120
121    let mut channels = Vec::with_capacity(invite.channels.len());
122    for ic in &invite.channels {
123        channels.push(Channel {
124            id: ChannelId(hex32(&ic.id)?),
125            key: ChannelKey(hex32(&ic.key)?),
126            epoch: Epoch(ic.epoch),
127            name: ic.name.clone(),
128            // A fresh joiner starts with no local banlist; it arrives with the metadata fetch.
129            banned: Vec::new(),
130            protected: Vec::new(), roster: Default::default(),
131            // Only the current key is conveyed on join; the archive fills as rekeys are caught up.
132            epoch_keys: Vec::new(),
133            dissolved: false,
134        });
135    }
136
137    Ok(Community {
138        id,
139        server_root_key,
140        server_root_epoch: Epoch(invite.server_root_epoch),
141        name: invite.name.clone(),
142        // The private bundle conveys join material only; display metadata
143        // (description/icon/banner) arrives when the member syncs the GroupRoot, or via
144        // a public-invite preview. Left None here.
145        description: None,
146        icon: None,
147        banner: None,
148        relays: super::cap_relays(invite.relays.clone()),
149        channels,
150        owner_attestation,
151        // A fresh join starts alive; the first control fold detects + seals if a tombstone is present.
152        dissolved: false,
153    })
154}
155
156/// Build the gift-wrap rumor that carries an invite to an invitee (carrier). The
157/// rumor is an unsigned NIP-59 inner event (kind 3304) whose content is the bundle
158/// JSON; the caller gift-wraps it to the invitee's npub over NIP-17 (reusing Vector's
159/// existing private-DM path). `my_pubkey` is the rumor author — irrelevant to the
160/// bundle's trust (the owner attestation inside it anchors authority), it just
161/// satisfies NIP-01 serialization.
162pub fn build_invite_rumor(community: &Community, my_pubkey: PublicKey) -> Result<UnsignedEvent, String> {
163    let json = build_invite(community).to_json()?;
164    Ok(EventBuilder::new(Kind::Custom(event_kind::COMMUNITY_INVITE_BUNDLE), json).build(my_pubkey))
165}
166
167/// Parse an inbound rumor as a Community invite. Returns `None` unless the rumor is an
168/// invite (kind 3304) carrying a well-formed bundle — a non-invite DM or corrupt
169/// content yields `None`, never an error, so the inbound dispatcher can fall through.
170pub fn parse_invite_rumor(kind: Kind, content: &str) -> Option<CommunityInvite> {
171    if kind != Kind::Custom(event_kind::COMMUNITY_INVITE_BUNDLE) {
172        return None;
173    }
174    CommunityInvite::from_json(content).ok()
175}
176
177#[cfg(test)]
178mod tests {
179    use super::*;
180    use crate::community::envelope::{open_message, seal_message};
181    use nostr_sdk::prelude::Keys;
182
183    #[test]
184    fn relay_cap_truncates_dedups_and_holds_at_every_boundary() {
185        // 7 entries, 2 of them duplicates → dedup to 6 distinct, truncate to 5.
186        let many: Vec<String> = vec![
187            "wss://a".into(), "wss://b".into(), "wss://a".into(), "wss://c".into(),
188            "wss://d".into(), "wss://e".into(), "wss://f".into(),
189        ];
190        let capped = super::super::cap_relays(many.clone());
191        assert_eq!(capped, vec!["wss://a", "wss://b", "wss://c", "wss://d", "wss://e"]);
192
193        // Mint honors the cap.
194        let owner = Community::create("HQ", "general", many.clone());
195        assert!(owner.relays.len() <= super::super::MAX_COMMUNITY_RELAYS);
196
197        // A hostile bundle declaring >5 relays parses (truncate-on-read), not rejects,
198        // and the accepted member view is capped too.
199        let mut bundle = build_invite(&owner);
200        bundle.relays = many; // force an over-cap bundle past build_invite
201        let json = bundle.to_json().unwrap();
202        let parsed = CommunityInvite::from_json(&json).unwrap();
203        assert!(parsed.relays.len() <= super::super::MAX_COMMUNITY_RELAYS);
204        let member = accept_invite(&parsed).unwrap();
205        assert!(member.relays.len() <= super::super::MAX_COMMUNITY_RELAYS);
206    }
207
208    #[test]
209    fn invite_round_trips_to_member_view() {
210        let owner = Community::create("HQ", "general", vec!["wss://r1".into(), "wss://r2".into()]);
211        let json = build_invite(&owner).to_json().unwrap();
212        let invite = CommunityInvite::from_json(&json).unwrap();
213        let member = accept_invite(&invite).unwrap();
214
215        // Same Community identity + read material (keyless — the bundle conveys read material only).
216        assert_eq!(member.id, owner.id);
217        assert_eq!(member.name, "HQ");
218        assert_eq!(member.relays, owner.relays);
219        assert_eq!(member.server_root_key.as_bytes(), owner.server_root_key.as_bytes());
220        assert_eq!(member.channels.len(), 1);
221        assert_eq!(member.channels[0].id, owner.channels[0].id);
222        assert_eq!(member.channels[0].key.as_bytes(), owner.channels[0].key.as_bytes());
223        assert_eq!(member.channels[0].name, "general");
224    }
225
226    #[test]
227    fn invited_member_can_read_owner_messages() {
228        // The killer property: the keys conveyed by the invite actually WORK. Owner
229        // seals a message under the channel key; the invited member, reconstructed
230        // purely from the bundle, opens it and recovers the author.
231        let owner = Community::create("HQ", "general", vec![]);
232        let owner_author = Keys::generate();
233        let chan = &owner.channels[0];
234        let sealed =
235            seal_message(&owner_author, &chan.key, &chan.id, chan.epoch, "welcome!", 1).unwrap();
236
237        let invite = CommunityInvite::from_json(&build_invite(&owner).to_json().unwrap()).unwrap();
238        let member = accept_invite(&invite).unwrap();
239        let mc = &member.channels[0];
240        let opened = open_message(&sealed, &mc.key, &mc.id, mc.epoch).unwrap();
241        assert_eq!(opened.content, "welcome!");
242        assert_eq!(opened.author, owner_author.public_key());
243    }
244
245    #[test]
246    fn malformed_invite_errors() {
247        let owner = Community::create("HQ", "general", vec![]);
248        let mut invite = build_invite(&owner);
249        invite.server_root_key = "zz".into(); // too short + non-hex
250        assert!(accept_invite(&invite).is_err());
251    }
252
253    #[test]
254    fn accept_rejects_a_bundle_exceeding_the_caps() {
255        // DoS guard: an attacker-controlled bundle declaring a huge channel list is rejected
256        // before any allocation/connection. Relays are CAPPED by truncation (cap_relays) rather
257        // than rejected, so a >5 relay bundle still joins — just at ≤5 relays.
258        let owner = Community::create("HQ", "general", vec![]);
259        let mut over_relays = build_invite(&owner);
260        over_relays.relays = (0..100).map(|i| format!("wss://r{i}")).collect();
261        let member = accept_invite(&over_relays).expect("over-relay bundle truncates, not rejects");
262        assert!(member.relays.len() <= super::super::MAX_COMMUNITY_RELAYS, "relays truncated to cap");
263
264        let mut over_channels = build_invite(&owner);
265        over_channels.channels = (0..500)
266            .map(|i| InviteChannel { id: "aa".repeat(32), key: "bb".repeat(32), epoch: 0, name: format!("c{i}") })
267            .collect();
268        assert!(accept_invite(&over_channels).is_err(), "too many channels → rejected");
269    }
270
271    #[test]
272    fn accept_rejects_malformed_community_id() {
273        // A corrupt id must error, never silently zero-fill into a fabricated community.
274        let owner = Community::create("HQ", "general", vec![]);
275        let mut bad = build_invite(&owner);
276        bad.community_id = "not-64-hex".into();
277        assert!(accept_invite(&bad).is_err());
278    }
279
280    #[test]
281    fn accept_drops_a_bogus_owner_attestation_but_still_joins() {
282        // The bundle can carry an owner_attestation; an unverifiable one is DROPPED (no spoofed crown),
283        // but the join still succeeds — graceful, no panic, no false owner.
284        let owner = Community::create("HQ", "general", vec![]);
285        let mut inv = build_invite(&owner);
286        inv.owner_attestation = Some("not even an event".to_string());
287        let member = accept_invite(&inv).unwrap();
288        assert!(member.owner_attestation.is_none(), "an unverifiable attestation is dropped, not trusted");
289    }
290
291    #[test]
292    fn accept_an_empty_channel_bundle_is_graceful() {
293        let owner = Community::create("HQ", "general", vec![]);
294        let mut inv = build_invite(&owner);
295        inv.channels.clear();
296        let member = accept_invite(&inv).unwrap();
297        assert!(member.channels.is_empty(), "a 0-channel bundle accepts without panic");
298    }
299
300    #[test]
301    fn bundle_carries_read_keys() {
302        // The invite conveys the read keys (server-root + channel) a member needs to read/post.
303        let owner = Community::create("HQ", "general", vec![]);
304        let json = build_invite(&owner).to_json().unwrap();
305        assert!(json.contains(&crate::simd::hex::bytes_to_hex_32(owner.server_root_key.as_bytes())));
306        assert!(json.contains(&crate::simd::hex::bytes_to_hex_32(owner.channels[0].key.as_bytes())));
307    }
308
309    #[test]
310    fn invite_rumor_round_trips() {
311        let owner = Community::create("HQ", "general", vec!["wss://r1".into()]);
312        let author = Keys::generate();
313        let rumor = build_invite_rumor(&owner, author.public_key()).unwrap();
314
315        assert_eq!(rumor.kind, Kind::Custom(event_kind::COMMUNITY_INVITE_BUNDLE));
316        let parsed = parse_invite_rumor(rumor.kind, &rumor.content).expect("parses");
317        let member = accept_invite(&parsed).unwrap();
318        assert_eq!(member.id, owner.id);
319        assert_eq!(member.channels[0].key.as_bytes(), owner.channels[0].key.as_bytes());
320    }
321
322    #[test]
323    fn parse_invite_rumor_rejects_wrong_kind() {
324        // A normal text DM (kind 14) must never parse as an invite, even if its content
325        // happened to be valid bundle JSON.
326        let owner = Community::create("HQ", "general", vec![]);
327        let json = build_invite(&owner).to_json().unwrap();
328        assert!(parse_invite_rumor(Kind::Custom(14), &json).is_none());
329        // Right kind but garbage content → None, not panic.
330        assert!(parse_invite_rumor(Kind::Custom(event_kind::COMMUNITY_INVITE_BUNDLE), "not json").is_none());
331    }
332
333    #[tokio::test]
334    async fn full_carrier_chain_invitee_reads_owner_message() {
335        // End-to-end (sans the gift-wrap transport, which is src-tauri): owner builds an
336        // invite rumor → invitee parses it → accepts → opens a real channel message the
337        // owner sealed. Proves the rumor faithfully conveys working keys.
338        use crate::community::transport::memory::MemoryRelay;
339        use crate::community::send::{fetch_channel_messages, publish_message};
340
341        let owner = Community::create("HQ", "general", vec!["r1".into()]);
342        let author = Keys::generate();
343        let rumor = build_invite_rumor(&owner, author.public_key()).unwrap();
344
345        // The invitee only ever sees the rumor content.
346        let invite = parse_invite_rumor(rumor.kind, &rumor.content).expect("invite");
347        let member = accept_invite(&invite).unwrap();
348
349        // Owner posts a message; the member (reconstructed from the bundle) reads it.
350        let relay = MemoryRelay::new();
351        let owner_author = Keys::generate();
352        publish_message(&relay, &owner, &owner.channels[0], &owner_author, "welcome aboard", 1)
353            .await
354            .unwrap();
355
356        let msgs = fetch_channel_messages(&relay, &member, &member.channels[0]).await.unwrap();
357        assert_eq!(msgs.len(), 1);
358        assert_eq!(msgs[0].content, "welcome aboard");
359        assert_eq!(msgs[0].author, owner_author.public_key());
360    }
361}