Skip to main content

vector_core/community/v2/
invite.rs

1//! CORD-05 Invites — how members are handed the keys that make them members.
2//!
3//! Two delivery lanes share one payload, the [`CommunityInvite`] **bundle**:
4//!   - **Public link** — the bundle rides relays as an addressable event
5//!     ([`kind::INVITE_BUNDLE`], empty `d`) authored by a throwaway per-link
6//!     keypair, encrypted under a key nobody on the network holds (derived off
7//!     the link's 16-byte unlock token). The link is `(naddr, #fragment)`: the
8//!     naddr is a bare public locator, the fragment carries the token + bootstrap
9//!     relays and never reaches a server. Only the *creator* (holder of the
10//!     link_signer secret, synced in their [`InviteList`]) can refresh or
11//!     tombstone the coordinate, so a link-holder can join but never squat or
12//!     kill the link (§2).
13//!   - **Direct invite** — when the invitee is a known npub the machinery drops
14//!     away: the bundle giftwraps straight to them as a STANDARD NIP-59 wrap
15//!     ([`build_direct_invite`], §6), not the reversed stream wrap of CORD-01.
16//!
17//! The inviter's identity is irrelevant to trust: the `community_id`
18//! self-certifies the owner (CORD-02 A.4), so no bundle can smuggle a false
19//! owner or a fake key for a real Community. Every bundle passes [`CommunityInvite::validate`]
20//! before it is trusted, whichever lane carried it.
21
22use crate::event_ext::FinalizeUnsignedWithId;
23use crate::event_ext::FinalizeOnClock;
24#[cfg(test)]
25use nostr_sdk::prelude::FinalizeEvent;
26use nostr_sdk::prelude::nip44::{
27    self,
28    v2::ConversationKey,
29};
30use nostr_sdk::prelude::{
31    Event, EventBuilder, FromBech32, Keys, Kind, PublicKey, Tag, Timestamp, ToBech32,
32};
33use serde::{Deserialize, Serialize};
34
35use super::super::{cap_relays, CommunityId};
36use super::control::ImageRef;
37use super::derive::{verify_community_id, TOKEN_LEN};
38use super::{kind, vsk};
39
40/// Hostile-bundle bound: a bundle is attacker-crafted input reached by following
41/// a link, so reject one carrying more Channels than a Community could sanely
42/// hold before allocating on its claims (CORD-05 §1).
43pub const MAX_BUNDLE_CHANNELS: usize = 256;
44
45/// Sanity ceiling on a bundle's `root_epoch` / channel epochs. Not a commitment
46/// (epochs aren't owner-signed), just a bound so attacker-set values can't push a
47/// later `epoch + 1` toward overflow. `2^40` is astronomically above any real
48/// rotation count.
49pub const MAX_BUNDLE_EPOCH: u64 = 1 << 40;
50
51/// A link's `label` caps at a name's 64 bytes (CORD-05 §1): a joiner echoes it into
52/// their Join, so an unbounded one would make that Join unpublishable.
53pub const MAX_LABEL_BYTES: usize = 64;
54
55/// A sealed rumor's envelope around its content: id, pubkey, a 10-digit `created_at`,
56/// the kind and empty tags.
57const DIRECT_RUMOR_ENVELOPE: usize = 256;
58
59/// The event a bundle rides, which sets its room.
60#[derive(Debug, Clone, Copy, PartialEq, Eq)]
61pub enum BundleLane {
62    /// One NIP-44 layer: the link's kind 33301.
63    Link,
64    /// A sealed rumor: the Direct Invite's kind 3313.
65    Direct,
66}
67
68/// A label as a writer may mint it: trimmed, cut to the cap on a char boundary, absent if empty.
69pub fn clamp_label(label: Option<String>) -> Option<String> {
70    let label = label?;
71    let label = label.trim();
72    let mut end = label.len().min(MAX_LABEL_BYTES);
73    while !label.is_char_boundary(end) {
74        end -= 1;
75    }
76    let label = label[..end].trim_end();
77    (!label.is_empty()).then(|| label.to_string())
78}
79
80/// The fragment format byte, which also selects the relay-dictionary generation
81/// (CORD-05 §3). Bumping it re-labels the dictionary universe.
82pub const FRAGMENT_VERSION: u8 = 4;
83
84/// The fragment carries at most this many bootstrap relays — it only needs to
85/// *find* the bundle, which then carries the authoritative set (CORD-05 §3).
86pub const MAX_BOOTSTRAP_RELAYS: usize = 3;
87
88/// `flags` bit 0: the stock set is in use, so zero relay bytes follow.
89const FLAG_STOCK_SET: u8 = 0x01;
90
91/// The stock relay dictionary, generation 4 — four primaries every client knows,
92/// referenced by a single byte (id = index + 1). Both Vector and Soapbox ship it
93/// identically, so an invite minted by either opens in the other. Append-only:
94/// growing it is a new generation, editing an entry re-labels existing links.
95const RELAY_DICT: [&str; 4] = [
96    "wss://jskitty.com/nostr",       // id 1 (Vector)
97    "wss://asia.vectorapp.io/nostr", // id 2 (Vector)
98    "wss://relay.ditto.pub",         // id 3 (Soapbox)
99    "wss://relay.dreamith.to",       // id 4 (Soapbox)
100];
101
102// ── Errors ───────────────────────────────────────────────────────────────────
103
104/// Errors from the invite layer.
105#[derive(Debug)]
106pub enum InviteError {
107    Json(String),
108    /// A hex field wasn't 32 valid bytes.
109    BadHex(&'static str),
110    /// More Channels than [`MAX_BUNDLE_CHANNELS`].
111    TooManyChannels(usize),
112    /// `(owner, owner_salt)` fail to reproduce `community_id` (CORD-02 A.4).
113    OwnerMismatch,
114    /// A malformed invite fragment (base64, truncation, trailing bytes, caps).
115    BadFragment(&'static str),
116    /// A fragment version this client won't decode (legacy or future).
117    BadVersion(u8),
118    /// A link/naddr that isn't a recognizable invite coordinate.
119    BadLink(&'static str),
120    /// A bundle event failed a wire gate: wrong kind, wrong author, bad
121    /// signature, or an unknown/missing `vsk` marker.
122    BadEvent(&'static str),
123    /// NIP-44 / NIP-19 / signing failure.
124    Crypto(String),
125}
126
127impl std::fmt::Display for InviteError {
128    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
129        match self {
130            InviteError::Json(e) => write!(f, "json: {e}"),
131            InviteError::BadHex(field) => write!(f, "field {field} is not 32-byte hex"),
132            InviteError::TooManyChannels(n) => write!(f, "bundle carries {n} channels (cap {MAX_BUNDLE_CHANNELS})"),
133            InviteError::OwnerMismatch => write!(f, "bundle owner does not reproduce its community_id"),
134            InviteError::BadFragment(why) => write!(f, "bad invite fragment: {why}"),
135            InviteError::BadVersion(v) => write!(f, "unsupported invite fragment version {v}"),
136            InviteError::BadLink(why) => write!(f, "bad invite link: {why}"),
137            InviteError::BadEvent(why) => write!(f, "bad invite bundle event: {why}"),
138            InviteError::Crypto(e) => write!(f, "crypto: {e}"),
139        }
140    }
141}
142
143impl std::error::Error for InviteError {}
144
145// ── 1. The Bundle ─────────────────────────────────────────────────────────────
146
147/// One granted Channel inside a bundle (CORD-05 §1). Public Channels derive from
148/// the `community_root`; a private Channel's independent `key` travels here.
149#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
150pub struct ChannelGrant {
151    /// Channel id (32-byte hex).
152    pub id: String,
153    /// Channel key (32-byte hex).
154    pub key: String,
155    pub epoch: u64,
156    pub name: String,
157}
158
159/// The `CommunityInvite` bundle (CORD-05 §1). Field names are wire-frozen and
160/// shared with Soapbox/Armada; a rename is a silent cross-client join failure.
161#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
162pub struct CommunityInvite {
163    /// `sha256("concord/community" || owner || owner_salt)` — self-certifies the owner.
164    pub community_id: String,
165    /// Owner x-only pubkey (32-byte hex).
166    pub owner: String,
167    /// Owner salt (32-byte hex).
168    pub owner_salt: String,
169    /// The base access key (32-byte hex) at `root_epoch`.
170    pub community_root: String,
171    pub root_epoch: u64,
172    /// The Control Plane's signer pubkey at `root_epoch` (CORD-02 §5):
173    /// subscribe, verify, read — never write. Absent = a legacy, pre-split
174    /// Community (fold Control at the legacy address instead, CORD-06 §3).
175    /// Taken on trust — it derives from a secret the joiner never holds, so
176    /// nothing in the bundle can prove it; a wrong one is eclipse-class
177    /// self-harm by the inviter, never forged authority (CORD-05 §1).
178    #[serde(skip_serializing_if = "Option::is_none")]
179    pub control_pk: Option<String>,
180    /// ABSENT, not empty, when the bundle vends no channel keys — armada omits it
181    /// (and re-fills it defensively on read). A required Vec here rejects the whole
182    /// bundle, which is a JOIN failure, not just a stale read.
183    #[serde(default)]
184    pub channels: Vec<ChannelGrant>,
185    #[serde(default)]
186    pub relays: Vec<String>,
187    /// Preview name so a parked invite renders; the Control fold is the authority.
188    pub name: String,
189    #[serde(skip_serializing_if = "Option::is_none")]
190    pub icon: Option<ImageRef>,
191    /// Optional, unix **ms**: past it the preview still renders, joining refuses.
192    #[serde(skip_serializing_if = "Option::is_none")]
193    pub expires_at: Option<u64>,
194    /// Optional attribution, echoed in the joiner's Guestbook Join (CORD-05 §1).
195    #[serde(skip_serializing_if = "Option::is_none")]
196    pub creator_npub: Option<String>,
197    #[serde(skip_serializing_if = "Option::is_none")]
198    pub label: Option<String>,
199    /// Unknown fields round-trip verbatim (CORD-02 §6) — carries other clients'
200    /// bundle extensions (`held_roots`, `refounder`, …) through untouched.
201    #[serde(flatten)]
202    pub extra: serde_json::Map<String, serde_json::Value>,
203}
204
205impl CommunityInvite {
206    /// Parse + bound + validate a decrypted bundle, whichever lane carried it:
207    /// truncate `relays` to the Community cap, reject an over-count of Channels
208    /// before trusting it, and verify the owner commitment.
209    pub fn from_bundle_json(json: &str) -> Result<Self, InviteError> {
210        let mut bundle: CommunityInvite = serde_json::from_str(json).map_err(|e| InviteError::Json(e.to_string()))?;
211        if bundle.channels.len() > MAX_BUNDLE_CHANNELS {
212            return Err(InviteError::TooManyChannels(bundle.channels.len()));
213        }
214        bundle.relays = cap_relays(std::mem::take(&mut bundle.relays));
215        bundle.validate()?;
216        Ok(bundle)
217    }
218
219    /// The self-certifying owner check (CORD-02 A.4) plus the Channel bound — a
220    /// mismatching bundle is refused, so even a compromised creator can't smuggle
221    /// a false owner or a fake key for a real Community.
222    pub fn validate(&self) -> Result<(), InviteError> {
223        if self.channels.len() > MAX_BUNDLE_CHANNELS {
224            return Err(InviteError::TooManyChannels(self.channels.len()));
225        }
226        // Epochs aren't covered by the community_id commitment, so an attacker can
227        // set them freely. Bound them well below `u64::MAX` (no real community
228        // rotates a trillion times) so a downstream `epoch + 1` can't be pushed near
229        // overflow and a crafted bundle can't derive nonsense addresses.
230        if self.root_epoch > MAX_BUNDLE_EPOCH || self.channels.iter().any(|c| c.epoch > MAX_BUNDLE_EPOCH) {
231            return Err(InviteError::BadFragment("epoch out of range"));
232        }
233        let owner = hex32(&self.owner, "owner")?;
234        let salt = hex32(&self.owner_salt, "owner_salt")?;
235        let cid = hex32(&self.community_id, "community_id")?;
236        if !verify_community_id(&CommunityId(cid), &owner, &salt) {
237            return Err(InviteError::OwnerMismatch);
238        }
239        Ok(())
240    }
241
242    /// Whether the invite's shelf life has run out (`expires_at` is unix ms).
243    /// Deliberately NOT checked at parse: a parked invite still renders past
244    /// expiry, only joining refuses (CORD-05 §1).
245    pub fn expired(&self, now_ms: u64) -> bool {
246        self.expires_at.is_some_and(|e| now_ms > e)
247    }
248
249    /// The attribution a joiner echoes into their Join: a 64-hex creator and a label within
250    /// the cap, anything else echoed as absent (CORD-05 §1).
251    pub fn attribution(&self) -> (Option<&str>, Option<&str>) {
252        let creator = self.creator_npub.as_deref().filter(|c| c.len() == 64 && c.bytes().all(|b| b.is_ascii_hexdigit()));
253        let label = self.label.as_deref().filter(|l| l.len() <= MAX_LABEL_BYTES);
254        (creator, label)
255    }
256
257    /// Whether this bundle's event fits a relay on `lane`.
258    pub fn fits(&self, lane: BundleLane) -> bool {
259        let Ok(json) = serde_json::to_string(self) else { return false };
260        match lane {
261            BundleLane::Link => crate::event_size::layer_fits(json.len()),
262            BundleLane::Direct => {
263                let escaped = serde_json::to_string(&json).map_or(usize::MAX, |s| s.len());
264                escaped + DIRECT_RUMOR_ENVELOPE <= crate::event_size::MAX_SEALED_RUMOR_BYTES
265            }
266        }
267    }
268
269    /// Shed public Channel grants, last first, until the bundle fits `lane`. A joiner derives
270    /// a public Channel from the root and folds it from Control, so only a private Channel's
271    /// key must ride the bundle; one that still won't fit is refused when it is sent.
272    pub fn fit(&mut self, lane: BundleLane) {
273        while !self.fits(lane) {
274            let Some(i) = self.channels.iter().rposition(|c| c.key == self.community_root) else { return };
275            self.channels.remove(i);
276        }
277    }
278}
279
280// ── 2. The bundle event (kind 33301) ──────────────────────────────────────────
281
282/// A fetched bundle coordinate resolves to one of these (CORD-05 §2).
283#[derive(Debug)]
284pub enum BundleState {
285    /// Boxed: the bundle dwarfs the empty `Revoked` variant.
286    Live(Box<CommunityInvite>),
287    /// The link was retired: a fetcher finds the grave instead of keys.
288    Revoked,
289}
290
291/// Build the addressable bundle event `(33301, link_signer, d="")`, marked live.
292/// The content is the §1 bundle NIP-44-encrypted under `bundle_key` (derived off
293/// the link's token — [`super::derive::invite_bundle_key`]), so relays store it
294/// but can never open it.
295pub fn build_bundle_event(
296    link_signer: &Keys,
297    bundle: &CommunityInvite,
298    bundle_key: &[u8; 32],
299) -> Result<Event, InviteError> {
300    let json = serde_json::to_string(bundle).map_err(|e| InviteError::Json(e.to_string()))?;
301    let content = seal_bundle(bundle_key, &json)?;
302    EventBuilder::new(Kind::Custom(kind::INVITE_BUNDLE), content)
303        .tags([d_empty(), vsk_tag(vsk::INVITE_LIVE)])
304        .finalize_on_clock(link_signer)
305        .map_err(|e| InviteError::Crypto(e.to_string()))
306}
307
308/// Re-post the coordinate as a revocation tombstone (CORD-05 §2) — signer-signed,
309/// so only the creator, and exactly as durable as the bundle it replaces (unlike
310/// a best-effort relay deletion).
311pub fn build_revocation(link_signer: &Keys) -> Result<Event, InviteError> {
312    EventBuilder::new(Kind::Custom(kind::INVITE_BUNDLE), "")
313        .tags([d_empty(), vsk_tag(vsk::INVITE_REVOKED)])
314        .finalize_on_clock(link_signer)
315        .map_err(|e| InviteError::Crypto(e.to_string()))
316}
317
318/// Verify + open a fetched bundle event. The primary anti-squat guard is the
319/// FETCH itself — the coordinate `(33301, link_signer, "")` means a different
320/// author is a different coordinate, so a squatter's spam never matches the
321/// filter — and this re-checks `event.pubkey == expected_signer` as a
322/// belt-and-suspenders against a relay handing back a foreign event. Gates on
323/// the signature, the `vsk` marker, decrypt, and [`CommunityInvite::validate`].
324pub fn parse_bundle_event(
325    event: &Event,
326    expected_signer: &PublicKey,
327    bundle_key: &[u8; 32],
328) -> Result<BundleState, InviteError> {
329    if event.kind.as_u16() != kind::INVITE_BUNDLE {
330        return Err(InviteError::BadEvent("wrong kind"));
331    }
332    if event.pubkey != *expected_signer {
333        return Err(InviteError::BadEvent("author is not the link signer"));
334    }
335    // The coordinate is `(33301, link_signer, "")`. The fetch filters on the author alone (relays
336    // handle an empty `#d` filter inconsistently), so pin the empty `d` here instead.
337    if !first_tag(event, "d").unwrap_or_default().is_empty() {
338        return Err(InviteError::BadEvent("bundle is not at the link's coordinate"));
339    }
340    event.verify().map_err(|_| InviteError::BadEvent("signature invalid"))?;
341
342    match first_tag(event, "vsk").as_deref() {
343        Some(v) if v == vsk::INVITE_REVOKED => return Ok(BundleState::Revoked),
344        Some(v) if v == vsk::INVITE_LIVE => {}
345        _ => return Err(InviteError::BadEvent("unknown or missing bundle marker")),
346    }
347
348    let json = open_bundle(bundle_key, &event.content)?;
349    Ok(BundleState::Live(Box::new(CommunityInvite::from_bundle_json(&json)?)))
350}
351
352// ── 3. The link (naddr + fragment codec) ──────────────────────────────────────
353
354const INVITE_PATH: &str = "/invite/";
355
356/// A parsed invite link: the bundle coordinate's author plus the fragment secrets.
357#[derive(Debug, Clone)]
358pub struct ParsedInviteLink {
359    /// The link signer's pubkey — the bundle coordinate's author.
360    pub link_signer: PublicKey,
361    pub token: [u8; TOKEN_LEN],
362    pub bootstrap_relays: Vec<String>,
363    /// The bare naddr as it appeared in the link.
364    pub naddr: String,
365}
366
367/// The stock relay set (dictionary ids 1..=4, in order) — selected by one flag
368/// so the common invite carries zero relay bytes.
369pub fn stock_relays() -> Vec<String> {
370    RELAY_DICT.iter().map(|s| s.to_string()).collect()
371}
372
373/// Encode the fragment `[version=4][flags][relays?][token:16]` as base64url with
374/// no padding. The stock set costs zero relay bytes (and is exempt from the
375/// 3-relay cap, which applies to explicit entries only); otherwise each relay is
376/// a dictionary-id byte, a `wss://`-implied literal (`0,len,host`), or a verbatim
377/// literal (`255,len,url`) for `ws://` and exotic schemes.
378pub fn encode_fragment(token: &[u8; TOKEN_LEN], relays: &[String]) -> Result<String, InviteError> {
379    let is_stock = relays.len() == RELAY_DICT.len() && relays.iter().zip(RELAY_DICT.iter()).all(|(r, d)| r == d);
380
381    let mut bytes = Vec::with_capacity(2 + TOKEN_LEN + relays.len() * 8);
382    bytes.push(FRAGMENT_VERSION);
383    if is_stock {
384        bytes.push(FLAG_STOCK_SET);
385    } else {
386        bytes.push(0x00);
387        let bounded = &relays[..relays.len().min(MAX_BOOTSTRAP_RELAYS)];
388        bytes.push(bounded.len() as u8);
389        for relay in bounded {
390            if let Some(id) = dict_id(relay) {
391                bytes.push(id);
392            } else if let Some(host) = relay.strip_prefix("wss://") {
393                if host.len() > u8::MAX as usize {
394                    return Err(InviteError::BadFragment("relay host too long"));
395                }
396                bytes.extend_from_slice(&[0x00, host.len() as u8]);
397                bytes.extend_from_slice(host.as_bytes());
398            } else {
399                if relay.len() > u8::MAX as usize {
400                    return Err(InviteError::BadFragment("relay url too long"));
401                }
402                bytes.extend_from_slice(&[0xff, relay.len() as u8]);
403                bytes.extend_from_slice(relay.as_bytes());
404            }
405        }
406    }
407    bytes.extend_from_slice(token);
408    Ok(crate::simd::base64::URL_SAFE_NO_PAD.encode_to_string(&bytes))
409}
410
411/// Decode a fragment into its token + bootstrap relays. Strict on framing: a
412/// wrong version (legacy OR future), a bad count, or any trailing byte after the
413/// token is fatal; an unknown dictionary id is skipped, not fatal, so the
414/// dictionary can grow without breaking older readers.
415pub fn decode_fragment(fragment: &str) -> Result<([u8; TOKEN_LEN], Vec<String>), InviteError> {
416    let bytes = crate::simd::base64::URL_SAFE_NO_PAD
417        .decode_to_vec(fragment.trim().as_bytes())
418        .map_err(|_| InviteError::BadFragment("not base64url"))?;
419
420    if bytes.len() < 2 {
421        return Err(InviteError::BadFragment("truncated"));
422    }
423    let version = bytes[0];
424    // Reject BOTH lower (legacy, wrong dictionary) and higher (unknown format)
425    // versions rather than decode against a dictionary we can't trust.
426    if version != FRAGMENT_VERSION {
427        return Err(InviteError::BadVersion(version));
428    }
429    let flags = bytes[1];
430    let mut o = 2usize;
431
432    let mut relays = Vec::new();
433    if flags & FLAG_STOCK_SET != 0 {
434        relays = stock_relays();
435    } else {
436        let count = *bytes.get(o).ok_or(InviteError::BadFragment("truncated"))? as usize;
437        o += 1;
438        if count > MAX_BOOTSTRAP_RELAYS {
439            return Err(InviteError::BadFragment("too many bootstrap relays"));
440        }
441        for _ in 0..count {
442            let lead = *bytes.get(o).ok_or(InviteError::BadFragment("truncated"))?;
443            o += 1;
444            if (1..=254).contains(&lead) {
445                if let Some(url) = dict_url(lead) {
446                    relays.push(url.to_string());
447                }
448                // Unknown dictionary id: skip, non-fatal (the dictionary grows).
449            } else {
450                let len = *bytes.get(o).ok_or(InviteError::BadFragment("truncated"))? as usize;
451                o += 1;
452                let end = o.checked_add(len).ok_or(InviteError::BadFragment("truncated"))?;
453                let raw = bytes.get(o..end).ok_or(InviteError::BadFragment("truncated"))?;
454                let text = std::str::from_utf8(raw).map_err(|_| InviteError::BadFragment("relay not utf8"))?;
455                relays.push(if lead == 255 { text.to_string() } else { format!("wss://{text}") });
456                o = end;
457            }
458        }
459    }
460
461    let end = o.checked_add(TOKEN_LEN).ok_or(InviteError::BadFragment("truncated"))?;
462    let raw = bytes.get(o..end).ok_or(InviteError::BadFragment("truncated"))?;
463    let mut token = [0u8; TOKEN_LEN];
464    token.copy_from_slice(raw);
465    if end != bytes.len() {
466        return Err(InviteError::BadFragment("trailing bytes"));
467    }
468    Ok((token, relays))
469}
470
471/// Build the bare naddr for a link signer's bundle coordinate `(33301, pk, "")` —
472/// no identifier bytes, no relay entries (relays travel in the fragment), keeping
473/// it as short as an naddr gets.
474pub fn bundle_naddr(link_signer: &PublicKey) -> Result<String, InviteError> {
475    let coord = nostr_sdk::prelude::nip01::Coordinate {
476        kind: Kind::Custom(kind::INVITE_BUNDLE),
477        public_key: *link_signer,
478        identifier: String::new(),
479    };
480    let n19 = nostr_sdk::prelude::nip19::Nip19Coordinate { coordinate: coord, relays: Vec::new() };
481    nostr_sdk::prelude::nip19::Nip19::Coordinate(n19)
482        .to_bech32()
483        .map_err(|e| InviteError::Crypto(e.to_string()))
484}
485
486/// Build a shareable invite URL on `base` — the base is interchangeable (any
487/// deeplink domain works), only the naddr and fragment are protocol (CORD-05 §2).
488pub fn build_invite_url(
489    base: &str,
490    link_signer: &PublicKey,
491    token: &[u8; TOKEN_LEN],
492    relays: &[String],
493) -> Result<String, InviteError> {
494    let naddr = bundle_naddr(link_signer)?;
495    let fragment = encode_fragment(token, relays)?;
496    Ok(format!("{}{INVITE_PATH}{naddr}#{fragment}", base.trim_end_matches('/')))
497}
498
499/// Parse a full URL (`…/invite/<naddr>#<fragment>`) or the domain-agnostic bare
500/// form (`<naddr>#<fragment>`) into its coordinate author + fragment secrets.
501pub fn parse_invite_link(input: &str) -> Result<ParsedInviteLink, InviteError> {
502    let (locator, fragment) = input.trim().split_once('#').ok_or(InviteError::BadLink("no fragment"))?;
503    if fragment.is_empty() {
504        return Err(InviteError::BadLink("empty fragment"));
505    }
506    // A full URL carries the naddr after `/invite/`; the bare form IS the naddr.
507    let naddr = match locator.find(INVITE_PATH) {
508        Some(i) => locator[i + INVITE_PATH.len()..].trim_end_matches('/'),
509        None => locator.trim_start_matches("nostr:"),
510    };
511    let link_signer = signer_from_naddr(naddr)?;
512    let (token, bootstrap_relays) = decode_fragment(fragment)?;
513    Ok(ParsedInviteLink { link_signer, token, bootstrap_relays, naddr: naddr.to_string() })
514}
515
516// ── 4. The Invite List (kind 13303) ───────────────────────────────────────────
517
518/// One minted link in a creator's private [`InviteList`] (CORD-05 §4). The
519/// `token` is the unlock secret AND the merge key; `signer_sk` is what refreshing
520/// or retiring the bundle needs.
521#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
522pub struct InviteEntry {
523    pub token: String,
524    pub signer_sk: String,
525    pub community_id: String,
526    pub url: String,
527    #[serde(skip_serializing_if = "Option::is_none")]
528    pub label: Option<String>,
529    pub created_at: u64,
530    #[serde(skip_serializing_if = "Option::is_none")]
531    pub expires_at: Option<u64>,
532    /// The root epoch this link was minted at. The severance discriminator: a
533    /// containment condemns every entry below its epoch, deterministically on
534    /// every device — no clock comparison can disagree with itself the way two
535    /// devices' clocks can. `None` (a pre-field or old-client mint) reads as 0,
536    /// so an unstamped link is condemned by any containment: fail toward the
537    /// closed door.
538    #[serde(default, skip_serializing_if = "Option::is_none")]
539    pub epoch: Option<u64>,
540    #[serde(flatten)]
541    pub extra: serde_json::Map<String, serde_json::Value>,
542}
543
544/// A retired link: a tombstone always beats an entry, terminally (CORD-05 §4).
545#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
546pub struct InviteTombstone {
547    pub token: String,
548    pub community_id: String,
549    /// The retired link's expiry, as its entry carried it: past it the link admits no one,
550    /// so the tombstone can go.
551    #[serde(default, skip_serializing_if = "Option::is_none")]
552    pub expires_at: Option<u64>,
553    #[serde(flatten)]
554    pub extra: serde_json::Map<String, serde_json::Value>,
555}
556
557/// An Invite List `expires_at` as unix ms. The list carries seconds, like `created_at`
558/// (CORD-05 §4); a value past the year 5000 in seconds is an older Vector's milliseconds.
559fn list_expiry_ms(v: u64) -> u64 {
560    if v >= 100_000_000_000 { v } else { v.saturating_mul(1000) }
561}
562
563impl InviteEntry {
564    /// When this link stops admitting anyone, in unix ms.
565    pub fn expires_at_ms(&self) -> Option<u64> {
566        self.expires_at.map(list_expiry_ms)
567    }
568}
569
570impl InviteTombstone {
571    /// The tombstone that retires `entry`.
572    pub fn of(entry: &InviteEntry) -> Self {
573        InviteTombstone { token: entry.token.clone(), community_id: entry.community_id.clone(), expires_at: entry.expires_at, extra: Default::default() }
574    }
575}
576
577/// A creator's Invite List — the kind-13303 replaceable, NIP-44-encrypted to
578/// self. Two clients can serve one npub, so the round-trip discipline applies.
579#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
580pub struct InviteList {
581    #[serde(default)]
582    pub entries: Vec<InviteEntry>,
583    #[serde(default)]
584    pub tombstones: Vec<InviteTombstone>,
585    #[serde(flatten)]
586    pub extra: serde_json::Map<String, serde_json::Value>,
587}
588
589impl InviteList {
590    /// Forget the links that can no longer admit anyone, entries and tombstones past their
591    /// expiry: one a stale device brings back is as dead as a retired one (CORD-05 §4).
592    pub fn prune_expired(&mut self, now_ms: u64) {
593        self.entries.retain(|e| e.expires_at_ms().is_none_or(|x| now_ms <= x));
594        self.tombstones.retain(|t| t.expires_at.map(list_expiry_ms).is_none_or(|x| now_ms <= x));
595    }
596
597    /// Whether the list, encrypted to self, fits one event.
598    pub fn fits(&self) -> bool {
599        serde_json::to_string(self).is_ok_and(|json| crate::event_size::layer_fits(json.len()))
600    }
601}
602
603/// Merge two Invite Lists without coordination (CORD-05 §4): the token is the
604/// merge key, an entry is immutable once minted (first-seen wins), tombstones
605/// union, and a tombstone always beats an entry — terminally, so a stale device
606/// can never resurrect a revoked link.
607pub fn merge_invite_lists(a: InviteList, b: InviteList) -> InviteList {
608    use std::collections::BTreeMap;
609
610    let mut entries: BTreeMap<String, InviteEntry> = BTreeMap::new();
611    for e in a.entries.into_iter().chain(b.entries) {
612        entries.entry(e.token.clone()).or_insert(e);
613    }
614    let mut tombstones: BTreeMap<String, InviteTombstone> = BTreeMap::new();
615    for t in a.tombstones.into_iter().chain(b.tombstones) {
616        tombstones.entry(t.token.clone()).or_insert(t);
617    }
618    for token in tombstones.keys() {
619        entries.remove(token);
620    }
621    let mut extra = a.extra;
622    extra.extend(b.extra);
623    InviteList {
624        entries: entries.into_values().collect(),
625        tombstones: tombstones.into_values().collect(),
626        extra,
627    }
628}
629
630/// Build the creator's kind-13303 Invite List event (CORD-05 §4): the document
631/// NIP-44-encrypted to SELF and signed by the creator's real key. Replaceable, one
632/// per creator. On READ the caller MERGES into the local mirror, never replaces.
633pub fn build_invite_list_event(my_keys: &Keys, list: &InviteList) -> Result<Event, InviteError> {
634    use nostr_sdk::prelude::nip44::{encrypt, Version};
635    let json = serde_json::to_string(list).map_err(|e| InviteError::Json(e.to_string()))?;
636    let content = encrypt(my_keys.secret_key(), &my_keys.public_key(), json.as_bytes(), Version::V2).map_err(|e| InviteError::Crypto(e.to_string()))?;
637    EventBuilder::new(Kind::Custom(kind::INVITE_LIST), content)
638        .finalize_on_clock(my_keys)
639        .map_err(|e| InviteError::Crypto(e.to_string()))
640}
641
642/// Decrypt + parse a kind-13303 event with the creator's own keys. A decrypt/parse
643/// failure MUST be treated as "no news" by the caller — never a clobber of a
644/// populated local list.
645pub fn parse_invite_list_event(event: &Event, my_keys: &Keys) -> Result<InviteList, InviteError> {
646    use nostr_sdk::prelude::nip44::decrypt;
647    if event.kind.as_u16() != kind::INVITE_LIST {
648        return Err(InviteError::BadEvent("not a kind-13303 invite list"));
649    }
650    let json = decrypt(my_keys.secret_key(), &my_keys.public_key(), &event.content).map_err(|e| InviteError::Crypto(e.to_string()))?;
651    serde_json::from_str(&json).map_err(|e| InviteError::Json(e.to_string()))
652}
653
654// ── 5. The Registry (vsk 8) ───────────────────────────────────────────────────
655
656/// Build the vsk-8 Registry entity content (CORD-05 §5): a JSON array of the
657/// creator's live link COORDINATES (link_signer pubkey hex) — never tokens,
658/// URLs, or signing secrets, so members see that links exist without gaining the
659/// ability to use one. The edition wrapping reuses the Control plane
660/// ([`super::control`]); this is only the content shape.
661pub fn build_registry_content(signers: &[PublicKey]) -> String {
662    let hexes: Vec<String> = signers.iter().map(|p| p.to_hex()).collect();
663    serde_json::to_string(&hexes).expect("Vec<String> always serializes")
664}
665
666/// Parse a Registry entity's content back into the link-signer coordinates.
667pub fn parse_registry_content(content: &str) -> Result<Vec<PublicKey>, InviteError> {
668    let hexes: Vec<String> = serde_json::from_str(content).map_err(|e| InviteError::Json(e.to_string()))?;
669    hexes
670        .iter()
671        .map(|h| PublicKey::from_hex(h).map_err(|_| InviteError::BadHex("registry signer")))
672        .collect()
673}
674
675// ── 6. Direct Invites (kind 3313) ─────────────────────────────────────────────
676
677/// Build a Direct Invite (CORD-05 §6): the §1 bundle handed to a known npub as a
678/// STANDARD NIP-59 giftwrap — ephemeral wrap author, the recipient in the `p`
679/// tag, a kind-13 seal signed by the inviter's REAL key (whose verified npub is
680/// what proves who invited), NOT the reversed stream wrap of CORD-01. The wrap
681/// carries the outer `["k","3313"]` index hint (the deliberate exception to the
682/// no-outer-tags rule) plus an optional NIP-40 `expiration` matching the bundle's
683/// `expires_at` (ms → seconds). NIP-59 tweaks the wrap and seal timestamps into
684/// the past.
685pub fn build_direct_invite(
686    inviter_keys: &Keys,
687    recipient: &PublicKey,
688    bundle: &CommunityInvite,
689) -> Result<Event, InviteError> {
690    let json = serde_json::to_string(bundle).map_err(|e| InviteError::Json(e.to_string()))?;
691
692    // The unsigned kind-3313 rumor, authored (claimed) by the inviter.
693    let mut rumor = EventBuilder::new(Kind::Custom(kind::DIRECT_INVITE), json)
694        .custom_created_at(crate::clock::timestamp())
695        .finalize_unsigned_with_id(inviter_keys.public_key());
696    rumor.ensure_id();
697
698    let seal_content = nip44::encrypt(inviter_keys.secret_key(), recipient, rumor.as_json(), nip44::Version::default())
699        .map_err(|e| InviteError::Crypto(e.to_string()))?;
700    let seal = EventBuilder::new(Kind::Seal, seal_content)
701        .custom_created_at(crate::sending::tweaked_timestamp())
702        .finalize_on_clock(inviter_keys)
703        .map_err(|e| InviteError::Crypto(e.to_string()))?;
704
705    let ephemeral = Keys::generate();
706    let wrap_content = nip44::encrypt(ephemeral.secret_key(), recipient, seal.as_json(), nip44::Version::default())
707        .map_err(|e| InviteError::Crypto(e.to_string()))?;
708    let mut tags = vec![
709        Tag::public_key(*recipient),
710        Tag::custom("k", [kind::DIRECT_INVITE.to_string()]),
711    ];
712    if let Some(ms) = bundle.expires_at {
713        tags.push(Tag::custom("expiration", [(ms / 1000).to_string()]));
714    }
715    EventBuilder::new(Kind::GiftWrap, wrap_content)
716        .tags(tags)
717        .custom_created_at(crate::sending::tweaked_timestamp())
718        .finalize_on_clock(&ephemeral)
719        .map_err(|e| InviteError::Crypto(e.to_string()))
720}
721
722/// Unwrap a Direct Invite giftwrap addressed to the recipient, returning the
723/// verified inviter + the validated bundle. Peels wrap → seal → rumor and MUST
724/// Schnorr-verify the kind-13 seal (its npub is the only proof of who invited),
725/// then binds `rumor.pubkey == seal.pubkey` (anti-spoof) and gates on the rumor
726/// kind (the outer `k` tag was only ever a hint). Nothing joins on unwrap —
727/// consent is the caller's concern (CORD-05 §6).
728pub fn unwrap_direct_invite(wrap: &Event, recipient_keys: &Keys) -> Result<(PublicKey, CommunityInvite), InviteError> {
729    if wrap.kind != Kind::GiftWrap {
730        return Err(InviteError::BadEvent("not a gift wrap"));
731    }
732    let seal_json = nip44::decrypt(recipient_keys.secret_key(), &wrap.pubkey, &wrap.content)
733        .map_err(|e| InviteError::Crypto(e.to_string()))?;
734    let seal = crate::event_json::event(&seal_json).map_err(|e| InviteError::Json(e.to_string()))?;
735    if seal.kind != Kind::Seal {
736        return Err(InviteError::BadEvent("inner is not a seal"));
737    }
738    seal.verify().map_err(|_| InviteError::BadEvent("seal signature invalid"))?;
739
740    let rumor_json = nip44::decrypt(recipient_keys.secret_key(), &seal.pubkey, &seal.content)
741        .map_err(|e| InviteError::Crypto(e.to_string()))?;
742    let rumor = crate::event_json::unsigned(&rumor_json).map_err(|e| InviteError::Json(e.to_string()))?;
743    if rumor.kind.as_u16() != kind::DIRECT_INVITE {
744        return Err(InviteError::BadEvent("rumor is not a direct invite"));
745    }
746    if rumor.pubkey != seal.pubkey {
747        return Err(InviteError::BadEvent("rumor author does not match the seal signer"));
748    }
749    let bundle = CommunityInvite::from_bundle_json(&rumor.content)?;
750    Ok((seal.pubkey, bundle))
751}
752
753// ── Signer-driven twins (bunker / NIP-55): identical wire, identity ops via VectorSigner ──
754
755/// [`build_invite_list_event`] via a [`VectorSigner`](crate::signer::VectorSigner). Self-encrypts to `my_pk` and
756/// signs the 13303 through the signer. `my_pk` must equal `my_public_key()`.
757pub async fn build_invite_list_event_signed<S: crate::signer::VectorSigner + ?Sized>(
758    signer: &S,
759    my_pk: PublicKey,
760    list: &InviteList,
761) -> Result<Event, InviteError> {
762    build_invite_list_event_at(signer, my_pk, list, crate::clock::timestamp().as_secs()).await
763}
764
765/// [`build_invite_list_event_signed`] dated `at_secs`: a replaceable list must outdate every copy
766/// its writer read.
767pub async fn build_invite_list_event_at<S: crate::signer::VectorSigner + ?Sized>(
768    signer: &S,
769    my_pk: PublicKey,
770    list: &InviteList,
771    at_secs: u64,
772) -> Result<Event, InviteError> {
773    let json = serde_json::to_string(list).map_err(|e| InviteError::Json(e.to_string()))?;
774    let content = signer.nip44_encrypt_async(&my_pk, &json).await.map_err(|e| InviteError::Crypto(e.to_string()))?;
775    let unsigned = EventBuilder::new(Kind::Custom(kind::INVITE_LIST), content).custom_created_at(Timestamp::from_secs(at_secs)).finalize_unsigned_with_id(my_pk);
776    signer.sign_event_async(unsigned).await.map_err(|e| InviteError::Crypto(e.to_string()))
777}
778
779/// [`parse_invite_list_event`] via a [`VectorSigner`](crate::signer::VectorSigner) (self-decrypt to `my_pk`).
780pub async fn parse_invite_list_event_signed<S: crate::signer::VectorSigner + ?Sized>(
781    signer: &S,
782    my_pk: PublicKey,
783    event: &Event,
784) -> Result<InviteList, InviteError> {
785    if event.kind.as_u16() != kind::INVITE_LIST {
786        return Err(InviteError::BadEvent("not a kind-13303 invite list"));
787    }
788    let json = signer.nip44_decrypt_async(&my_pk, &event.content).await.map_err(|e| InviteError::Crypto(e.to_string()))?;
789    serde_json::from_str(&json).map_err(|e| InviteError::Json(e.to_string()))
790}
791
792/// [`build_direct_invite`] via a [`VectorSigner`](crate::signer::VectorSigner): the kind-13 seal's NIP-44 (inviter
793/// → recipient) and signature go through the signer; the ephemeral wrap stays local.
794pub async fn build_direct_invite_signed<S: crate::signer::VectorSigner + ?Sized>(
795    signer: &S,
796    inviter_pk: PublicKey,
797    recipient: &PublicKey,
798    bundle: &CommunityInvite,
799) -> Result<Event, InviteError> {
800    let json = serde_json::to_string(bundle).map_err(|e| InviteError::Json(e.to_string()))?;
801    let mut rumor = EventBuilder::new(Kind::Custom(kind::DIRECT_INVITE), json)
802        .custom_created_at(crate::clock::timestamp())
803        .finalize_unsigned_with_id(inviter_pk);
804    rumor.ensure_id();
805    let rumor_json = rumor.as_json();
806    let seal_content = signer.nip44_encrypt_async(recipient, &rumor_json).await.map_err(|e| InviteError::Crypto(e.to_string()))?;
807    let seal_unsigned = EventBuilder::new(Kind::Seal, seal_content)
808        .custom_created_at(crate::sending::tweaked_timestamp())
809        .finalize_unsigned_with_id(inviter_pk);
810    let seal = signer.sign_event_async(seal_unsigned).await.map_err(|e| InviteError::Crypto(e.to_string()))?;
811    let ephemeral = Keys::generate();
812    let wrap_content = nip44::encrypt(ephemeral.secret_key(), recipient, seal.as_json(), nip44::Version::default())
813        .map_err(|e| InviteError::Crypto(e.to_string()))?;
814    let mut tags = vec![
815        Tag::public_key(*recipient),
816        Tag::custom("k", [kind::DIRECT_INVITE.to_string()]),
817    ];
818    if let Some(ms) = bundle.expires_at {
819        tags.push(Tag::custom("expiration", [(ms / 1000).to_string()]));
820    }
821    EventBuilder::new(Kind::GiftWrap, wrap_content)
822        .tags(tags)
823        .custom_created_at(crate::sending::tweaked_timestamp())
824        .finalize_on_clock(&ephemeral)
825        .map_err(|e| InviteError::Crypto(e.to_string()))
826}
827
828/// [`unwrap_direct_invite`] via a [`VectorSigner`](crate::signer::VectorSigner): both giftwrap peels decrypt
829/// through the signer. Same seal-verify + author-bind gates as the local path.
830pub async fn unwrap_direct_invite_signed<S: crate::signer::VectorSigner + ?Sized>(
831    signer: &S,
832    wrap: &Event,
833) -> Result<(PublicKey, CommunityInvite), InviteError> {
834    if wrap.kind != Kind::GiftWrap {
835        return Err(InviteError::BadEvent("not a gift wrap"));
836    }
837    let seal_json = signer.nip44_decrypt_async(&wrap.pubkey, &wrap.content).await.map_err(|e| InviteError::Crypto(e.to_string()))?;
838    let seal = crate::event_json::event(&seal_json).map_err(|e| InviteError::Json(e.to_string()))?;
839    if seal.kind != Kind::Seal {
840        return Err(InviteError::BadEvent("inner is not a seal"));
841    }
842    seal.verify().map_err(|_| InviteError::BadEvent("seal signature invalid"))?;
843    let rumor_json = signer.nip44_decrypt_async(&seal.pubkey, &seal.content).await.map_err(|e| InviteError::Crypto(e.to_string()))?;
844    let rumor = crate::event_json::unsigned(&rumor_json).map_err(|e| InviteError::Json(e.to_string()))?;
845    if rumor.kind.as_u16() != kind::DIRECT_INVITE {
846        return Err(InviteError::BadEvent("rumor is not a direct invite"));
847    }
848    if rumor.pubkey != seal.pubkey {
849        return Err(InviteError::BadEvent("rumor author does not match the seal signer"));
850    }
851    let bundle = CommunityInvite::from_bundle_json(&rumor.content)?;
852    Ok((seal.pubkey, bundle))
853}
854
855// ── helpers ────────────────────────────────────────────────────────────────────
856
857fn hex32(s: &str, field: &'static str) -> Result<[u8; 32], InviteError> {
858    crate::simd::hex::hex_to_bytes_32_checked(s).ok_or(InviteError::BadHex(field))
859}
860
861fn dict_id(url: &str) -> Option<u8> {
862    RELAY_DICT.iter().position(|u| *u == url).map(|i| (i + 1) as u8)
863}
864
865fn dict_url(id: u8) -> Option<&'static str> {
866    RELAY_DICT.get((id as usize).checked_sub(1)?).copied()
867}
868
869fn d_empty() -> Tag {
870    Tag::custom("d", [""])
871}
872
873fn vsk_tag(value: &str) -> Tag {
874    Tag::custom("vsk", [value])
875}
876
877fn first_tag(event: &Event, name: &str) -> Option<String> {
878    event.tags.iter().find_map(|t| {
879        let s = t.as_slice();
880        (s.len() >= 2 && s[0] == name).then(|| s[1].clone())
881    })
882}
883
884/// The NIP-44 bundle ciphertext under `bundle_key` used directly as the
885/// conversation key (CORD-05 §2 — not an ECDH pair). Standard-base64 payload so
886/// it interoperates with nostr-tools' `nip44.encrypt(json, bundle_key)`.
887pub(crate) fn seal_bundle(bundle_key: &[u8; 32], json: &str) -> Result<String, InviteError> {
888    let ck = ConversationKey::new(*bundle_key);
889    let ct = crate::community::cipher::encrypt_with_random_nonce(&ck, json.as_bytes()).map_err(|e| InviteError::Crypto(e.to_string()))?;
890    Ok(crate::simd::base64::STANDARD.encode_to_string(&ct))
891}
892
893fn open_bundle(bundle_key: &[u8; 32], content: &str) -> Result<String, InviteError> {
894    let ck = ConversationKey::new(*bundle_key);
895    let ct = crate::simd::base64::STANDARD
896        .decode_to_vec(content.as_bytes())
897        .map_err(|e| InviteError::Crypto(e.to_string()))?;
898    let pt = crate::crypto::nip44::decrypt(&ck, ct).map_err(|e| InviteError::Crypto(e.to_string()))?;
899    String::from_utf8(pt).map_err(|e| InviteError::Crypto(e.to_string()))
900}
901
902fn signer_from_naddr(naddr: &str) -> Result<PublicKey, InviteError> {
903    let trimmed = naddr.trim().trim_start_matches("nostr:");
904    let n19 = nostr_sdk::prelude::nip19::Nip19::from_bech32(trimmed).map_err(|_| InviteError::BadLink("invalid naddr"))?;
905    match n19 {
906        nostr_sdk::prelude::nip19::Nip19::Coordinate(c)
907            if c.coordinate.kind.as_u16() == kind::INVITE_BUNDLE && c.coordinate.identifier.is_empty() =>
908        {
909            Ok(c.coordinate.public_key)
910        }
911        _ => Err(InviteError::BadLink("naddr is not an invite-bundle coordinate")),
912    }
913}
914
915/// Default invite URL base. The path is irrelevant to the protocol (the fragment is read
916/// client-side and never sent to the server); only the fragment matters.
917pub const INVITE_URL_BASE: &str = "https://vectorapp.io/invite";
918
919/// How long a Direct Invite stays valid. A bundle hands out live key material for a
920/// community that keeps evolving (rotations, renames, bans), so an invite that never
921/// expires is both stale key material and clutter in the recipient's list. The sender
922/// stamps NIP-40 on the rumor AND (mirrored by the send path) on the outer gift wrap, so
923/// relays drop it on schedule; recipients enforce it themselves too, since relay support
924/// for NIP-40 is optional.
925pub const DIRECT_INVITE_EXPIRY_SECS: u64 = 24 * 60 * 60;
926
927/// Read a NIP-40 `expiration` tag (unix seconds) off an invite rumor's tags. `None` =
928/// no expiry declared (a pre-expiry sender), which callers treat as permanent.
929pub fn expiration_secs(tags: &nostr_sdk::prelude::Tags) -> Option<u64> {
930    tags.iter()
931        .find(|t| t.as_slice().first().map(|k| k.as_str() == "expiration").unwrap_or(false))
932        .and_then(|t| t.as_slice().get(1))
933        .and_then(|v| v.parse::<u64>().ok())
934}
935
936/// The non-secret community details shown before joining (no member count — the protocol
937/// hides membership, so any count would be a fiction).
938#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
939pub struct PublicInvitePreview {
940    pub name: String,
941    #[serde(default, skip_serializing_if = "Option::is_none")]
942    pub description: Option<String>,
943    /// Logo (encrypted blob ref). The per-image key rides here; the joiner also receives
944    /// the server-root key via `join`, so this exposes nothing they aren't already given.
945    #[serde(default, skip_serializing_if = "Option::is_none")]
946    pub icon: Option<crate::community::CommunityImage>,
947}
948
949/// A short, human-typable label for an unlabeled invite link. Crockford-ish base32 (no 0/1/I/O)
950/// so it's unambiguous to read and share aloud; 6 chars ≈ 1B combinations (collision-improbable).
951/// Every link gets a label: the one provided, else a random 6-char handle. A stable label makes
952/// the link identifiable in the UI and keys per-link join attribution off (creator, label), so it
953/// must be unique among THIS creator's links in the community (else two links share a join bucket).
954pub(crate) fn resolve_invite_label(community_id: &str, label: Option<String>) -> Result<String, String> {
955    let existing = crate::db::community::list_public_invites(community_id).unwrap_or_default();
956    let label_taken = |cand: &str| {
957        existing.iter().any(|r| r.label.as_deref().map(|e| e.eq_ignore_ascii_case(cand)).unwrap_or(false))
958    };
959    match label {
960        Some(l) if !l.trim().is_empty() => {
961            let l = l.trim().to_string();
962            if label_taken(&l) {
963                return Err(format!("You already have an invite link labeled \u{201c}{l}\u{201d}. Pick a different label."));
964            }
965            Ok(l)
966        }
967        // Random handle — regenerate on the (astronomically unlikely) collision.
968        _ => {
969            let mut l = generate_invite_label();
970            while label_taken(&l) {
971                l = generate_invite_label();
972            }
973            Ok(l)
974        }
975    }
976}
977
978fn generate_invite_label() -> String {
979    use rand::Rng;
980    const ALPHABET: &[u8] = b"ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
981    let mut rng = rand::thread_rng();
982    (0..6).map(|_| ALPHABET[rng.gen_range(0..ALPHABET.len())] as char).collect()
983}
984
985#[cfg(test)]
986mod tests {
987    use super::super::control::CommunityIdentity;
988    use super::super::derive::invite_bundle_key;
989    use super::*;
990    use crate::community::{random_32, MAX_COMMUNITY_RELAYS};
991
992    fn hex(bytes: &[u8; 32]) -> String {
993        crate::simd::hex::bytes_to_hex_32(bytes)
994    }
995
996    #[test]
997    fn a_bundle_vending_no_channel_keys_omits_the_field_entirely() {
998        // armada omits `channels` when the bundle carries no keys, and re-fills it
999        // on read. Required here, a public-community invite fails to parse at all —
1000        // a JOIN failure, not merely a stale read. Optional fields stay absent too.
1001        let json = r#"{
1002          "community_id":"aa","owner":"bb","owner_salt":"cc",
1003          "community_root":"dd","root_epoch":0,"name":"Public Room"
1004        }"#;
1005        let inv: CommunityInvite = serde_json::from_str(json).expect("absent `channels`/`relays` must parse");
1006        assert!(inv.channels.is_empty());
1007        assert!(inv.relays.is_empty());
1008        assert_eq!(inv.icon, None, "absent optionals are None, not an error");
1009        assert_eq!(inv.expires_at, None);
1010        assert_eq!(inv.name, "Public Room");
1011    }
1012
1013    /// A valid owner + bundle whose (owner, salt) reproduce its community_id.
1014    fn valid_bundle() -> (Keys, CommunityInvite) {
1015        let owner = Keys::generate();
1016        let id = CommunityIdentity::mint(&owner.public_key());
1017        let bundle = CommunityInvite {
1018            community_id: hex(&id.community_id.0),
1019            owner: hex(&id.owner_xonly),
1020            owner_salt: hex(&id.owner_salt),
1021            community_root: hex(&random_32()),
1022            root_epoch: 0,
1023            control_pk: None,
1024            channels: vec![],
1025            relays: vec!["wss://a.example".into(), "wss://b.example".into()],
1026            name: "Test community".into(),
1027            icon: None,
1028            expires_at: None,
1029            creator_npub: None,
1030            label: None,
1031            extra: Default::default(),
1032        };
1033        (owner, bundle)
1034    }
1035
1036    fn token16() -> [u8; TOKEN_LEN] {
1037        std::array::from_fn(|i| i as u8) // 00,01,..,0f
1038    }
1039
1040    // ── Bundle validate() ──────────────────────────────────────────────────────
1041
1042    #[test]
1043    fn validate_accepts_a_correct_owner_salt_id_triple() {
1044        let (_owner, bundle) = valid_bundle();
1045        assert!(bundle.validate().is_ok());
1046    }
1047
1048    #[test]
1049    fn validate_rejects_a_forged_owner() {
1050        let (_owner, mut bundle) = valid_bundle();
1051        // Attacker key over the REAL community id → second-preimage, must fail.
1052        let attacker = Keys::generate();
1053        bundle.owner = hex(&attacker.public_key().to_bytes());
1054        assert!(matches!(bundle.validate(), Err(InviteError::OwnerMismatch)));
1055    }
1056
1057    /// The widest bundle a Community can mint: every optional field set, names of quotes
1058    /// (escaped once per layer), and every Channel granted.
1059    fn widest_bundle(private: usize) -> CommunityInvite {
1060        let (_owner, mut b) = valid_bundle();
1061        let quotes = "\"".repeat(64);
1062        b.control_pk = Some(hex(&random_32()));
1063        b.relays = (0..MAX_COMMUNITY_RELAYS).map(|i| format!("wss://{i}{}.example", "r".repeat(240))).collect();
1064        b.name = quotes.clone();
1065        b.icon = Some(ImageRef { url: format!("https://{}.example/{}", "b".repeat(60), "f".repeat(64)), key: hex(&random_32()), nonce: "ab".repeat(12), hash: hex(&random_32()), extra: Default::default() });
1066        b.expires_at = Some(u64::MAX / 2);
1067        b.creator_npub = Some(hex(&random_32()));
1068        b.label = Some(quotes.clone());
1069        b.channels = (0..MAX_BUNDLE_CHANNELS)
1070            .map(|i| ChannelGrant {
1071                id: hex(&random_32()),
1072                key: if i < private { hex(&random_32()) } else { b.community_root.clone() },
1073                epoch: MAX_BUNDLE_EPOCH,
1074                name: quotes.clone(),
1075            })
1076            .collect();
1077        b
1078    }
1079
1080    #[test]
1081    fn a_full_bundle_sheds_public_grants_until_its_event_fits() {
1082        let private = 40;
1083        let mut link = widest_bundle(private);
1084        assert!(!link.fits(BundleLane::Link), "the test must start over the ceiling");
1085        link.fit(BundleLane::Link);
1086        assert!(link.channels.len() < MAX_BUNDLE_CHANNELS);
1087        assert_eq!(link.channels.iter().filter(|c| c.key != link.community_root).count(), private, "every private key still rides");
1088        let event = build_bundle_event(&Keys::generate(), &link, &invite_bundle_key(&token16())).unwrap();
1089        assert!(crate::event_size::check(&event).is_ok(), "link bundle is {} bytes", event.as_json().len());
1090
1091        let mut direct = widest_bundle(private);
1092        direct.fit(BundleLane::Direct);
1093        assert_eq!(direct.channels.iter().filter(|c| c.key != direct.community_root).count(), private);
1094        let wrap = build_direct_invite(&Keys::generate(), &Keys::generate().public_key(), &direct).unwrap();
1095        assert!(crate::event_size::check(&wrap).is_ok(), "direct invite is {} bytes", wrap.as_json().len());
1096
1097        // A bundle that already fits is left whole.
1098        let (_owner, mut small) = valid_bundle();
1099        small.channels = widest_bundle(0).channels.into_iter().take(3).collect();
1100        let before = small.clone();
1101        small.fit(BundleLane::Direct);
1102        assert_eq!(small, before);
1103    }
1104
1105    #[test]
1106    fn the_label_is_capped_when_minted_and_when_echoed() {
1107        assert_eq!(clamp_label(Some("  Reddit  ".into())).as_deref(), Some("Reddit"));
1108        assert_eq!(clamp_label(Some("   ".into())), None);
1109        let long = clamp_label(Some("é".repeat(40))).unwrap();
1110        assert!(long.len() <= MAX_LABEL_BYTES && long.chars().all(|c| c == 'é'), "cut on a char boundary");
1111
1112        let (_owner, mut b) = valid_bundle();
1113        b.creator_npub = Some(hex(&random_32()));
1114        b.label = Some("Conf 2026".into());
1115        assert_eq!(b.attribution(), (b.creator_npub.as_deref(), Some("Conf 2026")));
1116        b.label = Some("x".repeat(30_000));
1117        b.creator_npub = Some("not a key".into());
1118        assert_eq!(b.attribution(), (None, None), "a hostile bundle's attribution is echoed as absent");
1119    }
1120
1121    #[test]
1122    fn the_invite_list_forgets_expired_links_and_measures_itself() {
1123        let entry = |i: usize, expires_at: Option<u64>| InviteEntry {
1124            token: format!("{i:0>32}"),
1125            signer_sk: hex(&random_32()),
1126            community_id: hex(&random_32()),
1127            url: format!("https://vectorapp.io/invite/naddr1{}#{}", "q".repeat(120), "z".repeat(60)),
1128            label: Some("\"".repeat(64)),
1129            created_at: 1_800_000_000,
1130            expires_at,
1131            epoch: Some(MAX_BUNDLE_EPOCH),
1132            extra: Default::default(),
1133        };
1134        let mut list = InviteList::default();
1135        list.entries.push(entry(1, Some(1_000)));
1136        list.entries.push(entry(2, Some(5_000)));
1137        list.entries.push(entry(3, None));
1138        list.tombstones.push(InviteTombstone::of(&entry(4, Some(1_000))));
1139        list.tombstones.push(InviteTombstone::of(&entry(5, None)));
1140        list.prune_expired(2_000_000);
1141        assert_eq!(list.entries.iter().map(|e| e.token.clone()).collect::<Vec<_>>(), vec![entry(2, None).token, entry(3, None).token]);
1142        assert_eq!(list.tombstones.len(), 1, "an expired link's tombstone goes, a lasting one stays");
1143
1144        // The list carries seconds, as Armada writes it; an older Vector wrote milliseconds.
1145        assert_eq!(entry(0, Some(1_722_400_000)).expires_at_ms(), Some(1_722_400_000_000));
1146        assert_eq!(entry(0, Some(1_722_400_000_000)).expires_at_ms(), Some(1_722_400_000_000));
1147
1148        let mut i = 10;
1149        while list.fits() {
1150            list.entries.push(entry(i, None));
1151            i += 1;
1152        }
1153        list.entries.pop();
1154        assert!(list.entries.len() > 50, "a full list still holds dozens of links, held {}", list.entries.len());
1155        let me = Keys::generate();
1156        let event = build_invite_list_event(&me, &list).unwrap();
1157        assert!(crate::event_size::check(&event).is_ok(), "a full invite list is {} bytes", event.as_json().len());
1158    }
1159
1160    #[test]
1161    fn from_json_rejects_over_the_channel_cap() {
1162        let (_owner, mut bundle) = valid_bundle();
1163        bundle.channels = (0..MAX_BUNDLE_CHANNELS + 1)
1164            .map(|_| ChannelGrant { id: hex(&random_32()), key: hex(&random_32()), epoch: 0, name: "x".into() })
1165            .collect();
1166        let json = serde_json::to_string(&bundle).unwrap();
1167        assert!(matches!(
1168            CommunityInvite::from_bundle_json(&json),
1169            Err(InviteError::TooManyChannels(n)) if n == MAX_BUNDLE_CHANNELS + 1
1170        ));
1171    }
1172
1173    #[test]
1174    fn from_json_truncates_relays_to_the_community_cap() {
1175        let (_owner, mut bundle) = valid_bundle();
1176        bundle.relays = (0..MAX_COMMUNITY_RELAYS + 3).map(|i| format!("wss://r{i}.example")).collect();
1177        let json = serde_json::to_string(&bundle).unwrap();
1178        let parsed = CommunityInvite::from_bundle_json(&json).unwrap();
1179        assert_eq!(parsed.relays.len(), MAX_COMMUNITY_RELAYS);
1180    }
1181
1182    #[test]
1183    fn unknown_bundle_fields_round_trip() {
1184        // Other clients' extensions (held_roots, refounder, future) survive a
1185        // parse → serialize cycle untouched (CORD-02 §6).
1186        let (_owner, bundle) = valid_bundle();
1187        let mut value = serde_json::to_value(&bundle).unwrap();
1188        let obj = value.as_object_mut().unwrap();
1189        obj.insert("held_roots".into(), serde_json::json!([{ "epoch": 2, "key": "ab" }]));
1190        obj.insert("refounder".into(), serde_json::json!("deadbeef"));
1191        obj.insert("future_field".into(), serde_json::json!({ "deep": [1, 2] }));
1192        let json = serde_json::to_string(&value).unwrap();
1193
1194        let parsed = CommunityInvite::from_bundle_json(&json).unwrap();
1195        let out: serde_json::Value = serde_json::from_str(&serde_json::to_string(&parsed).unwrap()).unwrap();
1196        assert_eq!(out["held_roots"][0]["epoch"], 2);
1197        assert_eq!(out["refounder"], "deadbeef");
1198        assert_eq!(out["future_field"]["deep"][1], 2);
1199    }
1200
1201    #[test]
1202    fn expiry_is_a_join_gate_not_a_render_gate() {
1203        let (_owner, mut bundle) = valid_bundle();
1204        bundle.expires_at = Some(1_000_000);
1205        assert!(!bundle.expired(999_999));
1206        assert!(bundle.expired(1_000_001));
1207    }
1208
1209    // ── Fragment codec GOLDEN VECTORS (hand-computed base64url) ──────────────────
1210
1211    #[test]
1212    fn fragment_golden_stock_set() {
1213        // [0x04 version][0x01 stock flag][token 00..0f] = 18 bytes → base64url:
1214        //   04 01 00 | 01 02 03 | 04 05 06 | 07 08 09 | 0a 0b 0c | 0d 0e 0f
1215        //   B A E A    A Q I D    B A U G    B w g J    C g s M    D Q 4 P
1216        let token = token16();
1217        let frag = encode_fragment(&token, &stock_relays()).unwrap();
1218        assert_eq!(frag, "BAEAAQIDBAUGBwgJCgsMDQ4P");
1219        let (t, relays) = decode_fragment(&frag).unwrap();
1220        assert_eq!(t, token);
1221        assert_eq!(relays, stock_relays());
1222    }
1223
1224    #[test]
1225    fn fragment_golden_dictionary_id_mix() {
1226        // [04][00 flags][02 count][02 dict-id][04 dict-id][token] = 21 bytes:
1227        //   04 00 02 | 02 04 00 | 01 02 03 | 04 05 06 | 07 08 09 | 0a 0b 0c | 0d 0e 0f
1228        //   B A A C    A g Q A    A Q I D    B A U G    B w g J    C g s M    D Q 4 P
1229        let token = token16();
1230        let relays = vec![RELAY_DICT[1].to_string(), RELAY_DICT[3].to_string()];
1231        let frag = encode_fragment(&token, &relays).unwrap();
1232        assert_eq!(frag, "BAACAgQAAQIDBAUGBwgJCgsMDQ4P");
1233        let (t, out) = decode_fragment(&frag).unwrap();
1234        assert_eq!(t, token);
1235        assert_eq!(out, relays);
1236    }
1237
1238    #[test]
1239    fn fragment_golden_wss_implied_literal() {
1240        // [04][00][01 count][00 lead=wss-implied][03 len]["x.y"=78 2e 79][token] = 24 bytes:
1241        //   04 00 01 | 00 03 78 | 2e 79 00 | 01 02 03 | 04 05 06 | 07 08 09 | 0a 0b 0c | 0d 0e 0f
1242        //   B A A B    A A N 4    L n k A    A Q I D    B A U G    B w g J    C g s M    D Q 4 P
1243        let token = token16();
1244        let relays = vec!["wss://x.y".to_string()];
1245        let frag = encode_fragment(&token, &relays).unwrap();
1246        assert_eq!(frag, "BAABAAN4LnkAAQIDBAUGBwgJCgsMDQ4P");
1247        let (t, out) = decode_fragment(&frag).unwrap();
1248        assert_eq!(t, token);
1249        assert_eq!(out, relays);
1250    }
1251
1252    #[test]
1253    fn fragment_golden_verbatim_literal() {
1254        // [04][00][01][ff lead=verbatim][06 len]["ws://h"=77 73 3a 2f 2f 68][token] = 27 bytes:
1255        //   04 00 01 | ff 06 77 | 73 3a 2f | 2f 68 00 | 01 02 03 | 04 05 06 | 07 08 09 | 0a 0b 0c | 0d 0e 0f
1256        //   B A A B    _ w Z 3    c z o v    L 2 g A    A Q I D    B A U G    B w g J    C g s M    D Q 4 P
1257        let token = token16();
1258        let relays = vec!["ws://h".to_string()];
1259        let frag = encode_fragment(&token, &relays).unwrap();
1260        assert_eq!(frag, "BAAB_wZ3czovL2gAAQIDBAUGBwgJCgsMDQ4P");
1261        let (t, out) = decode_fragment(&frag).unwrap();
1262        assert_eq!(t, token);
1263        assert_eq!(out, relays);
1264    }
1265
1266    #[test]
1267    fn fragment_rejects_wrong_version_both_directions() {
1268        let token = token16();
1269        for bad in [3u8, 5u8] {
1270            let mut bytes = vec![bad, FLAG_STOCK_SET];
1271            bytes.extend_from_slice(&token);
1272            let frag = crate::simd::base64::URL_SAFE_NO_PAD.encode_to_string(&bytes);
1273            assert!(matches!(decode_fragment(&frag), Err(InviteError::BadVersion(v)) if v == bad));
1274        }
1275    }
1276
1277    #[test]
1278    fn fragment_rejects_trailing_bytes() {
1279        let token = token16();
1280        let mut bytes = vec![FRAGMENT_VERSION, FLAG_STOCK_SET];
1281        bytes.extend_from_slice(&token);
1282        bytes.push(0xff); // one byte past the token
1283        let frag = crate::simd::base64::URL_SAFE_NO_PAD.encode_to_string(&bytes);
1284        assert!(matches!(decode_fragment(&frag), Err(InviteError::BadFragment("trailing bytes"))));
1285    }
1286
1287    #[test]
1288    fn fragment_rejects_count_over_three() {
1289        let token = token16();
1290        let mut bytes = vec![FRAGMENT_VERSION, 0x00, 0x04]; // count 4 > cap
1291        bytes.extend_from_slice(&[1, 2, 3, 4]);
1292        bytes.extend_from_slice(&token);
1293        let frag = crate::simd::base64::URL_SAFE_NO_PAD.encode_to_string(&bytes);
1294        assert!(matches!(decode_fragment(&frag), Err(InviteError::BadFragment("too many bootstrap relays"))));
1295    }
1296
1297    #[test]
1298    fn fragment_skips_an_unknown_dictionary_id() {
1299        let token = token16();
1300        // count 1, dict id 200 (unknown gen-4 id) → skipped, not fatal.
1301        let mut bytes = vec![FRAGMENT_VERSION, 0x00, 0x01, 200];
1302        bytes.extend_from_slice(&token);
1303        let frag = crate::simd::base64::URL_SAFE_NO_PAD.encode_to_string(&bytes);
1304        let (t, relays) = decode_fragment(&frag).unwrap();
1305        assert_eq!(t, token);
1306        assert!(relays.is_empty());
1307    }
1308
1309    #[test]
1310    fn fragment_caps_bootstrap_relays_at_three() {
1311        let token = token16();
1312        let relays: Vec<String> = (0..4).map(|i| format!("wss://r{i}.example")).collect();
1313        let (_t, out) = decode_fragment(&encode_fragment(&token, &relays).unwrap()).unwrap();
1314        assert_eq!(out.len(), MAX_BOOTSTRAP_RELAYS);
1315    }
1316
1317    // ── 33301 bundle event ──────────────────────────────────────────────────────
1318
1319    #[test]
1320    fn bundle_event_round_trips_live() {
1321        let (_owner, bundle) = valid_bundle();
1322        let link = Keys::generate();
1323        let token = random_32();
1324        let key = invite_bundle_key(&token[..TOKEN_LEN].try_into().unwrap());
1325        let event = build_bundle_event(&link, &bundle, &key).unwrap();
1326        assert_eq!(event.pubkey, link.public_key());
1327
1328        match parse_bundle_event(&event, &link.public_key(), &key).unwrap() {
1329            BundleState::Live(b) => {
1330                assert_eq!(b.community_id, bundle.community_id);
1331                assert_eq!(b.name, "Test community");
1332            }
1333            BundleState::Revoked => panic!("expected Live"),
1334        }
1335    }
1336
1337    #[test]
1338    fn revocation_reads_as_revoked() {
1339        let link = Keys::generate();
1340        let tomb = build_revocation(&link).unwrap();
1341        let key = invite_bundle_key(&[0u8; TOKEN_LEN]);
1342        assert!(matches!(parse_bundle_event(&tomb, &link.public_key(), &key), Ok(BundleState::Revoked)));
1343    }
1344
1345    #[test]
1346    fn bundle_event_wrong_key_fails() {
1347        let (_owner, bundle) = valid_bundle();
1348        let link = Keys::generate();
1349        let key = invite_bundle_key(&[7u8; TOKEN_LEN]);
1350        let event = build_bundle_event(&link, &bundle, &key).unwrap();
1351        let wrong = invite_bundle_key(&[8u8; TOKEN_LEN]);
1352        assert!(parse_bundle_event(&event, &link.public_key(), &wrong).is_err());
1353    }
1354
1355    #[test]
1356    fn bundle_event_from_a_different_author_is_rejected() {
1357        // The coordinate is the anti-squat guard; the author re-check catches a
1358        // relay handing back a squatter's event at the same d.
1359        let (_owner, bundle) = valid_bundle();
1360        let real = Keys::generate();
1361        let squatter = Keys::generate();
1362        let key = invite_bundle_key(&[3u8; TOKEN_LEN]);
1363        let event = build_bundle_event(&squatter, &bundle, &key).unwrap();
1364        assert!(matches!(
1365            parse_bundle_event(&event, &real.public_key(), &key),
1366            Err(InviteError::BadEvent("author is not the link signer"))
1367        ));
1368    }
1369
1370    /// The fetch filters on the author alone (an empty `#d` filter is answered inconsistently by
1371    /// relays), so the empty `d` MUST be pinned here — otherwise the same signer's event at any
1372    /// other `d` would be accepted as the bundle.
1373    #[test]
1374    fn bundle_event_at_a_non_empty_d_is_rejected() {
1375        let (_owner, bundle) = valid_bundle();
1376        let link = Keys::generate();
1377        let key = invite_bundle_key(&[9u8; TOKEN_LEN]);
1378        let json = serde_json::to_string(&bundle).unwrap();
1379        let content = seal_bundle(&key, &json).unwrap();
1380        let event = EventBuilder::new(Kind::Custom(kind::INVITE_BUNDLE), content)
1381            .tags([Tag::identifier("elsewhere"), vsk_tag(vsk::INVITE_LIVE)])
1382            .finalize(&link)
1383            .unwrap();
1384        assert!(matches!(
1385            parse_bundle_event(&event, &link.public_key(), &key),
1386            Err(InviteError::BadEvent("bundle is not at the link's coordinate"))
1387        ));
1388    }
1389
1390    #[test]
1391    fn bundle_event_with_a_tampered_signature_is_rejected() {
1392        let (_owner, bundle) = valid_bundle();
1393        let link = Keys::generate();
1394        let other = Keys::generate();
1395        let key = invite_bundle_key(&[4u8; TOKEN_LEN]);
1396        let event = build_bundle_event(&link, &bundle, &key).unwrap();
1397        // Swap the author to `other` (its signature no longer matches the id).
1398        let mut json: serde_json::Value = serde_json::from_str(&event.as_json()).unwrap();
1399        json["pubkey"] = serde_json::Value::String(other.public_key().to_hex());
1400        let Ok(forged) = Event::from_json(json.to_string()) else { return };
1401        assert!(matches!(
1402            parse_bundle_event(&forged, &other.public_key(), &key),
1403            Err(InviteError::BadEvent("signature invalid"))
1404        ));
1405    }
1406
1407    // ── Invite List merge ───────────────────────────────────────────────────────
1408
1409    fn entry(token: &str, community: &str) -> InviteEntry {
1410        InviteEntry {
1411            token: token.into(),
1412            signer_sk: "bb".repeat(32),
1413            community_id: community.into(),
1414            url: "https://x/invite/naddr1xyz#frag".into(),
1415            label: None,
1416            created_at: 1000,
1417            expires_at: None,
1418            epoch: None,
1419            extra: Default::default(),
1420        }
1421    }
1422
1423    #[test]
1424    fn invite_list_merge_entries_immutable_tombstone_wins_terminally() {
1425        let e = entry(&"aa".repeat(16), &"cc".repeat(32));
1426        let a = merge_invite_lists(InviteList::default(), InviteList { entries: vec![e.clone()], ..Default::default() });
1427        assert_eq!(a.entries.len(), 1);
1428
1429        // Re-merging a mutated entry under the same token can't change it.
1430        let mut mutated = e.clone();
1431        mutated.label = Some("changed".into());
1432        let still = merge_invite_lists(a.clone(), InviteList { entries: vec![mutated], ..Default::default() });
1433        assert_eq!(still.entries[0].label, None);
1434
1435        // Tombstone beats the entry.
1436        let tomb = InviteTombstone::of(&e);
1437        let b = merge_invite_lists(a, InviteList { tombstones: vec![tomb], ..Default::default() });
1438        assert!(b.entries.is_empty());
1439        assert_eq!(b.tombstones.len(), 1);
1440
1441        // A stale device re-merging the entry can't resurrect the revoked link.
1442        let c = merge_invite_lists(b, InviteList { entries: vec![e], ..Default::default() });
1443        assert!(c.entries.is_empty());
1444    }
1445
1446    #[test]
1447    fn invite_list_tombstones_union() {
1448        let t1 = InviteTombstone { token: "11".repeat(16), community_id: "aa".repeat(32), expires_at: None, extra: Default::default() };
1449        let t2 = InviteTombstone { token: "22".repeat(16), community_id: "bb".repeat(32), expires_at: None, extra: Default::default() };
1450        let merged = merge_invite_lists(
1451            InviteList { tombstones: vec![t1], ..Default::default() },
1452            InviteList { tombstones: vec![t2], ..Default::default() },
1453        );
1454        assert_eq!(merged.tombstones.len(), 2);
1455    }
1456
1457    #[test]
1458    fn invite_list_unknown_fields_round_trip() {
1459        let wire = r#"{"entries":[],"tombstones":[],"schema":"future","note":{"x":1}}"#;
1460        let list: InviteList = serde_json::from_str(wire).unwrap();
1461        let out: serde_json::Value = serde_json::from_str(&serde_json::to_string(&list).unwrap()).unwrap();
1462        assert_eq!(out["schema"], "future");
1463        assert_eq!(out["note"]["x"], 1);
1464    }
1465
1466    // ── Direct invite ───────────────────────────────────────────────────────────
1467
1468    #[test]
1469    fn direct_invite_round_trips_to_inviter_and_bundle() {
1470        let inviter = Keys::generate();
1471        let recipient = Keys::generate();
1472        let (_owner, bundle) = valid_bundle();
1473
1474        let wrap = build_direct_invite(&inviter, &recipient.public_key(), &bundle).unwrap();
1475        assert_eq!(wrap.kind, Kind::GiftWrap);
1476        assert_ne!(wrap.pubkey, inviter.public_key(), "wrap author is ephemeral");
1477        assert!(wrap.tags.iter().any(|t| {
1478            let s = t.as_slice();
1479            s.len() >= 2 && s[0] == "k" && s[1] == kind::DIRECT_INVITE.to_string()
1480        }));
1481
1482        let (sender, out) = unwrap_direct_invite(&wrap, &recipient).unwrap();
1483        assert_eq!(sender, inviter.public_key());
1484        assert_eq!(out.community_id, bundle.community_id);
1485        assert_eq!(out.name, "Test community");
1486    }
1487
1488    #[test]
1489    fn direct_invite_rejects_a_seal_claiming_a_false_inviter() {
1490        // The verify Armada skips: a seal whose pubkey was swapped to Y but signed
1491        // by X has an invalid signature — the Schnorr check must catch it.
1492        let inviter = Keys::generate();
1493        let claimed = Keys::generate();
1494        let recipient = Keys::generate();
1495        let (_owner, bundle) = valid_bundle();
1496
1497        // Build a normal invite, then rebuild the seal with a swapped pubkey.
1498        let wrap = build_direct_invite(&inviter, &recipient.public_key(), &bundle).unwrap();
1499        let seal_json = nip44::decrypt(recipient.secret_key(), &wrap.pubkey, &wrap.content).unwrap();
1500        let mut seal_val: serde_json::Value = serde_json::from_str(&seal_json).unwrap();
1501        seal_val["pubkey"] = serde_json::Value::String(claimed.public_key().to_hex());
1502        // Re-wrap the forged seal to the recipient under a fresh ephemeral key.
1503        let ephemeral = Keys::generate();
1504        let wrap_ct =
1505            nip44::encrypt(ephemeral.secret_key(), &recipient.public_key(), seal_val.to_string(), nip44::Version::default())
1506                .unwrap();
1507        let forged = EventBuilder::new(Kind::GiftWrap, wrap_ct)
1508            .tags([Tag::public_key(recipient.public_key())])
1509            .finalize(&ephemeral)
1510            .unwrap();
1511        assert!(unwrap_direct_invite(&forged, &recipient).is_err());
1512    }
1513
1514    #[test]
1515    fn direct_invite_rejects_a_non_invite_rumor_kind() {
1516        let inviter = Keys::generate();
1517        let recipient = Keys::generate();
1518        let (_owner, bundle) = valid_bundle();
1519        let json = serde_json::to_string(&bundle).unwrap();
1520
1521        // Hand-build the shape with a kind-9 rumor instead of 3313.
1522        let mut rumor = EventBuilder::new(Kind::Custom(9), json)
1523            .custom_created_at(Timestamp::now())
1524            .finalize_unsigned_with_id(inviter.public_key());
1525        rumor.ensure_id();
1526        let seal_ct =
1527            nip44::encrypt(inviter.secret_key(), &recipient.public_key(), rumor.as_json(), nip44::Version::default()).unwrap();
1528        let seal = EventBuilder::new(Kind::Seal, seal_ct).finalize(&inviter).unwrap();
1529        let ephemeral = Keys::generate();
1530        let wrap_ct =
1531            nip44::encrypt(ephemeral.secret_key(), &recipient.public_key(), seal.as_json(), nip44::Version::default()).unwrap();
1532        let wrap = EventBuilder::new(Kind::GiftWrap, wrap_ct)
1533            .tags([Tag::public_key(recipient.public_key())])
1534            .finalize(&ephemeral)
1535            .unwrap();
1536        assert!(matches!(
1537            unwrap_direct_invite(&wrap, &recipient),
1538            Err(InviteError::BadEvent("rumor is not a direct invite"))
1539        ));
1540    }
1541
1542    #[test]
1543    fn direct_invite_stamps_nip40_expiration_in_seconds() {
1544        let inviter = Keys::generate();
1545        let recipient = Keys::generate();
1546        let (_owner, mut bundle) = valid_bundle();
1547        let expires_ms = 1_735_689_600_000u64;
1548        bundle.expires_at = Some(expires_ms);
1549
1550        let wrap = build_direct_invite(&inviter, &recipient.public_key(), &bundle).unwrap();
1551        let exp = wrap.tags.iter().find_map(|t| {
1552            let s = t.as_slice();
1553            (s.len() >= 2 && s[0] == "expiration").then(|| s[1].clone())
1554        });
1555        assert_eq!(exp, Some((expires_ms / 1000).to_string()));
1556    }
1557
1558    #[test]
1559    fn direct_invite_rejects_a_forged_owner_bundle() {
1560        let inviter = Keys::generate();
1561        let recipient = Keys::generate();
1562        let (_owner, mut bundle) = valid_bundle();
1563        bundle.owner = hex(&Keys::generate().public_key().to_bytes()); // forged
1564        let wrap = build_direct_invite(&inviter, &recipient.public_key(), &bundle).unwrap();
1565        assert!(matches!(unwrap_direct_invite(&wrap, &recipient), Err(InviteError::OwnerMismatch)));
1566    }
1567
1568    // ── Links ───────────────────────────────────────────────────────────────────
1569
1570    #[test]
1571    fn invite_link_round_trips_full_url_and_bare_form() {
1572        let link = Keys::generate();
1573        let token = token16();
1574        let relays = vec!["wss://a.example".to_string()];
1575        let url = build_invite_url("https://vectorapp.io", &link.public_key(), &token, &relays).unwrap();
1576        assert!(url.contains("/invite/naddr1"));
1577
1578        let parsed = parse_invite_link(&url).unwrap();
1579        assert_eq!(parsed.link_signer, link.public_key());
1580        assert_eq!(parsed.token, token);
1581        assert_eq!(parsed.bootstrap_relays, relays);
1582
1583        let bare = format!("{}#{}", parsed.naddr, url.split('#').nth(1).unwrap());
1584        assert_eq!(parse_invite_link(&bare).unwrap().link_signer, link.public_key());
1585    }
1586
1587    #[test]
1588    fn invite_link_rejects_non_invites() {
1589        assert!(parse_invite_link("hello world").is_err());
1590        assert!(parse_invite_link("wss://relay.example.com").is_err());
1591        assert!(parse_invite_link("https://x/invite/#frag").is_err());
1592    }
1593
1594    #[test]
1595    fn v2_parser_rejects_a_v1_style_url_no_cross_protocol_confusion() {
1596        // A legacy-format `…/invite#<base64url>` URL (no naddr segment in the
1597        // path) must never parse: the v2 parser fails at the naddr step.
1598        let v1_url = "https://vectorapp.io/invite#AmR1bW15djFmcmFnbWVudA";
1599        assert!(parse_invite_link(v1_url).is_err(), "v2 must reject a v1-format invite URL");
1600        // With a trailing slash it is likewise not a valid v2 naddr.
1601        assert!(parse_invite_link("https://vectorapp.io/invite/#AmR1bW15").is_err());
1602        // Sanity: a real v2 link still parses (bare naddr#fragment form).
1603        let token = [0x07u8; TOKEN_LEN];
1604        let signer = Keys::generate();
1605        let naddr = bundle_naddr(&signer.public_key()).unwrap();
1606        let frag = encode_fragment(&token, &[]).unwrap();
1607        assert!(parse_invite_link(&format!("{naddr}#{frag}")).is_ok());
1608    }
1609
1610    // ── Registry ────────────────────────────────────────────────────────────────
1611
1612    #[test]
1613    fn registry_content_round_trips_and_leaks_no_secrets() {
1614        let a = Keys::generate();
1615        let b = Keys::generate();
1616        let content = build_registry_content(&[a.public_key(), b.public_key()]);
1617
1618        // Coordinates only: exactly the two pubkey hexes, nothing else.
1619        let arr: Vec<String> = serde_json::from_str(&content).unwrap();
1620        assert_eq!(arr, vec![a.public_key().to_hex(), b.public_key().to_hex()]);
1621        // No token / url / secret ever rides the member-facing Registry.
1622        assert!(!content.contains("invite"));
1623        assert!(!content.contains("token"));
1624        assert!(!content.contains("://"));
1625
1626        let back = parse_registry_content(&content).unwrap();
1627        assert_eq!(back, vec![a.public_key(), b.public_key()]);
1628    }
1629}