Skip to main content

vector_core/community/
mod.rs

1//! Vector Community protocol (GROUP_PROTOCOL.md).
2//!
3//! A Community is the top-level container (Discord's "server", but Vector is
4//! serverless so the name reflects that); it holds Channels. This module is the
5//! cryptographic core: the frozen key-derivation convention and the message
6//! envelope. It is pure, network-free, and DB-free — the riskiest unknowns
7//! isolated for exhaustive unit testing before anything depends on them.
8
9pub mod attachments;
10pub mod cache;
11pub mod cipher;
12pub mod derive;
13pub mod envelope;
14pub mod inbound;
15pub mod invite;
16pub mod invite_list;
17pub mod list;
18pub mod metadata;
19pub mod moderation;
20pub mod edition;
21pub mod migration;
22pub mod owner;
23pub mod rekey;
24pub mod roster;
25pub mod version;
26pub mod public_invite;
27pub mod realtime;
28pub mod roles;
29pub mod send;
30pub mod service;
31pub mod transport;
32pub mod v2;
33
34use nostr_sdk::prelude::PublicKey;
35use rand::RngCore;
36use serde::{Deserialize, Serialize};
37use zeroize::{Zeroize, ZeroizeOnDrop};
38
39/// How fresh an inner send time must be to surface as a REALTIME event (ms).
40/// Generous against sender clock skew and relay push latency; tiny against the
41/// hours-to-months staleness of a relay-to-relay backfill replay.
42pub const REALTIME_FRESH_WINDOW_MS: u64 = 300_000;
43
44/// Whether an inner send time is fresh enough to surface as REALTIME. The live
45/// subscriptions are limit-0 (never history), but a relay backfilling from a
46/// peer ACCEPTS old events as new writes and pushes them to matching live subs
47/// — without this gate a month-old join or mention surfaces as if it just
48/// happened (bots welcome long-gone joiners, answer stale mentions). Gates only
49/// the "new" surfaces (`is_new`, bot events, pings); folding and persistence
50/// are NEVER gated on freshness.
51pub fn is_realtime_fresh(at_ms: u64) -> bool {
52    let now_ms = std::time::SystemTime::now()
53        .duration_since(std::time::UNIX_EPOCH)
54        .map(|d| d.as_millis() as u64)
55        .unwrap_or(0);
56    at_ms.saturating_add(REALTIME_FRESH_WINDOW_MS) >= now_ms
57}
58
59/// Which Concord protocol a community runs. Vector carries both for a migration
60/// window: v1 (the shipped `#z`-addressed stack) and v2 (the self-certifying-id
61/// CORD stack, `community::v2`). Persisted as the `communities.protocol` integer.
62#[derive(Debug, Clone, Copy, PartialEq, Eq)]
63pub enum ConcordProtocol {
64    V1,
65    V2,
66}
67
68impl ConcordProtocol {
69    pub fn as_i64(self) -> i64 {
70        match self {
71            ConcordProtocol::V1 => 1,
72            ConcordProtocol::V2 => 2,
73        }
74    }
75
76    /// Map the stored integer; anything unrecognized (or a legacy NULL read as 0)
77    /// falls back to v1, the pre-migration default.
78    pub fn from_i64(n: i64) -> ConcordProtocol {
79        match n {
80            2 => ConcordProtocol::V2,
81            _ => ConcordProtocol::V1,
82        }
83    }
84}
85
86/// A Community's stable identity = a random 32-byte opaque id (NOT a
87/// timestamp-encoding snowflake, which would leak creation time).
88#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
89pub struct CommunityId(pub [u8; 32]);
90
91impl CommunityId {
92    /// Lowercase hex — the addressable-event `d`-tag form.
93    pub fn to_hex(&self) -> String {
94        crate::simd::hex::bytes_to_hex_32(&self.0)
95    }
96}
97
98/// A Channel's stable identity within a Community. Same opaque-random rule as
99/// [`CommunityId`]; doubles as the addressable metadata `d`-tag.
100#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
101pub struct ChannelId(pub [u8; 32]);
102
103impl ChannelId {
104    /// Lowercase hex, the form used in the inner channel-binding tag.
105    pub fn to_hex(&self) -> String {
106        crate::simd::hex::bytes_to_hex_32(&self.0)
107    }
108}
109
110/// The epoch counter — the read-access clock ("two clocks"). Bumps only on a
111/// rekey; stamped explicitly even when it is 0, so multi-channel and rotation stay
112/// additive (forward-compat hook #1).
113#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
114pub struct Epoch(pub u64);
115
116/// A 32-byte symmetric channel secret — the raw NIP-44 v2 `ConversationKey`
117/// material. Zeroized on drop; never logged.
118#[derive(Clone, Zeroize, ZeroizeOnDrop)]
119pub struct ChannelKey(pub [u8; 32]);
120
121impl ChannelKey {
122    pub fn as_bytes(&self) -> &[u8; 32] {
123        &self.0
124    }
125}
126
127// Deliberately no Debug: a channel secret must never reach a log line.
128impl core::fmt::Debug for ChannelKey {
129    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
130        f.write_str("ChannelKey(<redacted>)")
131    }
132}
133
134/// Per-epoch pseudonym = the value carried in the relay-filterable `z` tag.
135/// Opaque 32 bytes; outsiders can't link it across epochs or to an identity.
136#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
137pub struct Pseudonym(pub [u8; 32]);
138
139impl Pseudonym {
140    pub fn to_hex(&self) -> String {
141        crate::simd::hex::bytes_to_hex_32(&self.0)
142    }
143}
144
145/// The server-root / `@everyone` key: always minted, always distinct from any
146/// channel key. Gates metadata + roster + roleless channels. Zeroized on drop.
147#[derive(Clone, Zeroize, ZeroizeOnDrop)]
148pub struct ServerRootKey(pub [u8; 32]);
149
150impl ServerRootKey {
151    pub fn as_bytes(&self) -> &[u8; 32] {
152        &self.0
153    }
154}
155
156impl core::fmt::Debug for ServerRootKey {
157    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
158        f.write_str("ServerRootKey(<redacted>)")
159    }
160}
161
162/// The all-zero hex scope id for server-root-scoped epoch keys (`RekeyScope::ServerRoot`
163/// uses the all-zero `id32` sentinel). A `ChannelId` is random-32, so it can never collide with
164/// this — letting one `community_epoch_keys` table hold both channel keys and the base/server-root
165/// key keyed by `(scope_id, epoch)`.
166pub const SERVER_ROOT_SCOPE_HEX: &str =
167    "0000000000000000000000000000000000000000000000000000000000000000";
168
169/// The epoch-key-archive scope for a v2 `control_root` (CORD-02 §2): non-hex on
170/// purpose, so it collides with neither a channel id nor the root sentinel.
171/// Reserves the pair beside the root at mint (retry idempotency) and archives
172/// the secret per epoch.
173pub const CONTROL_ROOT_SCOPE: &str = "control-root";
174
175/// 32 cryptographically-random bytes (OsRng).
176pub(crate) fn random_32() -> [u8; 32] {
177    let mut b = [0u8; 32];
178    rand::rngs::OsRng.fill_bytes(&mut b);
179    b
180}
181
182/// A reference to an encrypted image blob (community logo/banner), using the same
183/// technique as NIP-17 file attachments: a fresh random AES-GCM key+nonce encrypts the
184/// image, the ciphertext is uploaded to Blossom, and this reference travels inside
185/// ServerRoot-sealed metadata. So possession of the server-root key (every member) gates
186/// the image, and there is no key reuse across images.
187#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
188pub struct CommunityImage {
189    /// Blossom URL of the encrypted blob.
190    pub url: String,
191    /// Hex AES-GCM key (per-image, random).
192    pub key: String,
193    /// Hex AES-GCM nonce.
194    pub nonce: String,
195    /// SHA-256 of the plaintext image (integrity check + local cache key).
196    pub hash: String,
197    /// File extension hint (e.g. "png", "jpg").
198    #[serde(default)]
199    pub ext: String,
200}
201
202/// A Channel inside a Community: its own independent key, current epoch, and name.
203///
204/// MULTI-EPOCH READ: `key`/`epoch` are the channel's CURRENT (head) epoch (what SENDS use), while
205/// `epoch_keys` carries EVERY epoch key the member retains across rekeys. The read paths
206/// (`fetch_channel_*`, `open_message_multi`) query `"#z":[<pseudonym per held epoch>]` and select the
207/// decryption key by the wire event's `z` pseudonym tag — so messages a removed-from-the-future member
208/// posted under an older epoch aren't stranded after a catch-up across one or more rekeys. Non-ratcheted
209/// per-epoch keys make this random-access: any retained epoch's plane decrypts directly, no replay.
210#[derive(Debug, Clone)]
211pub struct Channel {
212    pub id: ChannelId,
213    pub key: ChannelKey,
214    pub epoch: Epoch,
215    pub name: String,
216    /// The owning Community's banlist (the "anti-memberlist"), denormalized onto each channel
217    /// so the inbound path (which holds a `&Channel`) can drop events from banned authors
218    /// without a separate lookup. Populated only by `db::load_community`; empty everywhere a
219    /// channel is built for sending or in tests. See [`crate::community::inbound`].
220    pub banned: Vec<PublicKey>,
221    /// The protected set — the proven owner only (implicit roster position 0), denormalized so the
222    /// inbound path enforces the invariant that the owner is NEVER effectively banned or hidden.
223    /// Admins are NOT in this set: the owner outranks them and may ban/hide them; everyone else is
224    /// ranked through the roster, not here. `db::load_community` filters the owner out of `banned`
225    /// and populates this; empty for send-built channels and tests.
226    pub protected: Vec<PublicKey>,
227    /// The Community's AUTHORIZED roster (roles + grants, post delegation check), denormalized so
228    /// the inbound delete path can verify a moderation-hide the keyless way — the hider's real npub must
229    /// hold `MANAGE_MESSAGES` and outrank the target's author, resolved against this roster.
230    /// `db::load_community` populates it from the cached authorized roster; empty for send-built channels
231    /// and tests (an empty roster authorizes only the owner, via `protected`).
232    pub roster: roles::CommunityRoles,
233    /// EVERY epoch key the member retains for this channel (`(epoch, key)`, from the multi-held archive),
234    /// so the read path can fetch + decrypt across rekeys. Populated only by `db::load_community`; empty
235    /// for send-built channels and tests, where reads fall back to the single head epoch (see
236    /// [`Self::read_epoch_keys`]).
237    pub epoch_keys: Vec<(Epoch, ChannelKey)>,
238    /// The owning Community's dissolution seal, denormalized onto each channel so the inbound path
239    /// (which holds a `&Channel`) drops EVERY subsequent event without a separate lookup — any kind, any
240    /// author, any time. Populated only by `db::load_community`; `false` for send-built channels + tests.
241    pub dissolved: bool,
242}
243
244impl Channel {
245    /// The `(epoch, key)` set the read path queries + decrypts against: every retained epoch when
246    /// loaded from the DB, else just the head (send-built channels / tests). Newest epoch first, so a
247    /// backward page walk and the per-event key lookup both see the current epoch before older ones.
248    pub fn read_epoch_keys(&self) -> Vec<(Epoch, ChannelKey)> {
249        let mut keys = if self.epoch_keys.is_empty() {
250            vec![(self.epoch, self.key.clone())]
251        } else {
252            self.epoch_keys.clone()
253        };
254        keys.sort_by(|a, b| b.0.0.cmp(&a.0.0));
255        keys
256    }
257}
258
259/// A Community (Discord's "server").
260///
261/// Keyless authority model: there is no shared signing key. READ access = key possession
262/// (`server_root_key` + the granted channel keys let any member read/post); WRITE authority = the
263/// member's npub rank in the owner-rooted roster, and the OWNER is derived by verifying the
264/// `owner_attestation` (see `service::is_proven_owner`). `ChannelKey`/`ServerRootKey` secrets are not
265/// serialized here; persistence is a separate, vault-backed concern.
266#[derive(Debug, Clone)]
267pub struct Community {
268    pub id: CommunityId,
269    /// @everyone base key — at `server_root_epoch`.
270    pub server_root_key: ServerRootKey,
271    /// The server-root's current epoch — the base/`@everyone` read clock. Bumps only on a
272    /// base rotation (a Private-community removal, or re-founding); stays 0 in a Public community and
273    /// at MVP. The per-epoch server-root pseudonym is derived from this, so it is the G1 seam the
274    /// control-plane fetch widens against once re-anchoring + multi-epoch fetch ship.
275    pub server_root_epoch: Epoch,
276    pub name: String,
277    /// Short description / topic (server-root-gated metadata; shown in invite previews).
278    pub description: Option<String>,
279    /// Logo (encrypted blob ref — see [`CommunityImage`]).
280    pub icon: Option<CommunityImage>,
281    /// Banner (encrypted blob ref).
282    pub banner: Option<CommunityImage>,
283    /// Preferred relay set for all of this Community's events.
284    pub relays: Vec<String>,
285    pub channels: Vec<Channel>,
286    /// The owner's identity attestation (a signed event JSON, see [`owner`]) binding this
287    /// community's id to the owner's npub. The proven owner is DERIVED by verifying it, never stored
288    /// as a bare claim. `None` until the creator signs it. Travels in the GroupRoot + invite bundle.
289    pub owner_attestation: Option<String>,
290    /// The owner-dissolution SEAL. `true` once a folded GroupDissolved tombstone was verified against
291    /// the proven owner — PERMANENT and irreversible (there is no un-dissolve; the way forward is a fresh
292    /// community). Once set, the control fold stops advancing and the inbound path drops every subsequent
293    /// event (any kind/author/time — the seal is this flag, NOT a timestamp). `false` for a live community.
294    pub dissolved: bool,
295}
296
297/// Protocol cap on a Community's relay set (§ transport). More relays are needless and
298/// amplify resource + metadata-exposure cost; 5 gives redundancy without centralisation.
299/// Enforced by truncate-on-read at every Community/CommunityInvite construction boundary, so a
300/// hostile or legacy bundle degrades to ≤5 distinct relays rather than being honored or rejected.
301pub const MAX_COMMUNITY_RELAYS: usize = 5;
302
303/// Dedupe (order-preserving) + truncate a relay set to [`MAX_COMMUNITY_RELAYS`]. Dedup first so the
304/// cap means "up to 5 DISTINCT relays" — a bundle padding one relay 5× can't waste the budget.
305pub fn cap_relays(relays: Vec<String>) -> Vec<String> {
306    let mut seen = std::collections::HashSet::new();
307    let mut out = Vec::with_capacity(relays.len().min(MAX_COMMUNITY_RELAYS));
308    for r in relays {
309        if out.len() >= MAX_COMMUNITY_RELAYS {
310            break;
311        }
312        if seen.insert(r.clone()) {
313            out.push(r);
314        }
315    }
316    out
317}
318
319impl Community {
320    /// Mint a brand-new Community with one default channel, owned by the creator.
321    /// All ids are random opaque 32-byte values (NOT timestamp snowflakes), and the
322    /// server-root + channel keys are independently generated (hook #3). The owner attestation
323    /// is signed separately by `service::create_community` (it needs the owner's identity signer).
324    pub fn create(
325        name: impl Into<String>,
326        default_channel_name: impl Into<String>,
327        relays: Vec<String>,
328    ) -> Self {
329        let channel = Channel {
330            id: ChannelId(random_32()),
331            key: ChannelKey(random_32()),
332            epoch: Epoch(0),
333            name: default_channel_name.into(),
334            banned: Vec::new(),
335            protected: Vec::new(), roster: Default::default(),
336            epoch_keys: Vec::new(),
337            dissolved: false,
338        };
339        Community {
340            id: CommunityId(random_32()),
341            server_root_key: ServerRootKey(random_32()),
342            server_root_epoch: Epoch(0),
343            name: name.into(),
344            description: None,
345            icon: None,
346            banner: None,
347            relays: cap_relays(relays),
348            channels: vec![channel],
349            // Signed asynchronously by `service::create_community` (needs the owner's identity
350            // signer); a freshly-minted in-memory Community has none yet.
351            owner_attestation: None,
352            dissolved: false,
353        }
354    }
355}
356
357#[cfg(test)]
358mod freshness_tests {
359    use super::*;
360
361    // The realtime gate: a just-sent event is fresh; a relay-backfill replay
362    // (hours to months old) and far-future junk are not "new" surfaces.
363    #[test]
364    fn realtime_freshness_window() {
365        let now_ms = std::time::SystemTime::now()
366            .duration_since(std::time::UNIX_EPOCH).unwrap().as_millis() as u64;
367        assert!(is_realtime_fresh(now_ms), "just-sent is fresh");
368        assert!(is_realtime_fresh(now_ms - REALTIME_FRESH_WINDOW_MS / 2), "modest delay is fresh");
369        assert!(!is_realtime_fresh(now_ms - 3_600_000), "an hour-old replay is not");
370        assert!(!is_realtime_fresh(now_ms.saturating_sub(30 * 24 * 3_600_000)), "a month-old replay is not");
371        assert!(is_realtime_fresh(now_ms + 60_000), "sender clock slightly ahead still fresh");
372    }
373}