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