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