Skip to main content

vector_core/community/
mod.rs

1//! Vector Communities, on the Concord v2 (CORD) protocol in [`v2`], plus the pieces
2//! every layer shares: ids, epochs, images, transport, roles and moderation.
3
4pub mod attachments;
5pub mod cache;
6pub mod cipher;
7pub mod mentions;
8pub mod message_delete;
9pub mod policy;
10pub mod moderation;
11pub mod edition;
12pub mod version;
13pub mod raid;
14pub mod rank;
15pub mod roles;
16pub(crate) mod plane_neg;
17pub mod transport;
18pub mod v2;
19
20use rand::RngCore;
21use serde::{Deserialize, Serialize};
22use zeroize::{Zeroize, ZeroizeOnDrop};
23
24/// How fresh an inner send time must be to surface as a REALTIME event (ms).
25/// Generous against sender clock skew and relay push latency; tiny against the
26/// hours-to-months staleness of a relay-to-relay backfill replay.
27pub const REALTIME_FRESH_WINDOW_MS: u64 = 300_000;
28
29/// Whether an inner send time is fresh enough to surface as REALTIME. The live
30/// subscriptions are limit-0 (never history), but a relay backfilling from a
31/// peer ACCEPTS old events as new writes and pushes them to matching live subs
32/// — without this gate a month-old join or mention surfaces as if it just
33/// happened (bots welcome long-gone joiners, answer stale mentions). Gates only
34/// the "new" surfaces (`is_new`, bot events, pings); folding and persistence
35/// are NEVER gated on freshness.
36pub fn is_realtime_fresh(at_ms: u64) -> bool {
37    at_ms.saturating_add(REALTIME_FRESH_WINDOW_MS) >= crate::clock::now_ms()
38}
39
40/// Route an inbound Community event, live or a slow relay's straggler.
41pub async fn dispatch_inbound(
42    event: nostr_sdk::prelude::Event,
43    handler: std::sync::Arc<dyn crate::InboundEventHandler>,
44) {
45    v2::realtime::dispatch_event(event, handler).await;
46}
47
48/// A Community's stable identity = a random 32-byte opaque id (NOT a
49/// timestamp-encoding snowflake, which would leak creation time).
50#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
51pub struct CommunityId(pub [u8; 32]);
52
53impl CommunityId {
54    /// Lowercase hex — the addressable-event `d`-tag form.
55    pub fn to_hex(&self) -> String {
56        crate::simd::hex::bytes_to_hex_32(&self.0)
57    }
58}
59
60/// A Channel's stable identity within a Community. Same opaque-random rule as
61/// [`CommunityId`]; doubles as the addressable metadata `d`-tag.
62#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
63pub struct ChannelId(pub [u8; 32]);
64
65impl ChannelId {
66    /// Lowercase hex, the form used in the inner channel-binding tag.
67    pub fn to_hex(&self) -> String {
68        crate::simd::hex::bytes_to_hex_32(&self.0)
69    }
70}
71
72/// The epoch counter — the read-access clock ("two clocks"). Bumps only on a
73/// rekey; stamped explicitly even when it is 0, so multi-channel and rotation stay
74/// additive (forward-compat hook #1).
75#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
76pub struct Epoch(pub u64);
77
78/// A 32-byte symmetric channel secret — the raw NIP-44 v2 `ConversationKey`
79/// material. Zeroized on drop; never logged.
80#[derive(Clone, Zeroize, ZeroizeOnDrop)]
81pub struct ChannelKey(pub [u8; 32]);
82
83impl ChannelKey {
84    pub fn as_bytes(&self) -> &[u8; 32] {
85        &self.0
86    }
87}
88
89// Deliberately no Debug: a channel secret must never reach a log line.
90impl core::fmt::Debug for ChannelKey {
91    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
92        f.write_str("ChannelKey(<redacted>)")
93    }
94}
95
96/// The all-zero hex scope id for server-root-scoped epoch keys (`RekeyScope::ServerRoot`
97/// uses the all-zero `id32` sentinel). A `ChannelId` is random-32, so it can never collide with
98/// this — letting one `community_epoch_keys` table hold both channel keys and the base/server-root
99/// key keyed by `(scope_id, epoch)`.
100pub const SERVER_ROOT_SCOPE_HEX: &str =
101    "0000000000000000000000000000000000000000000000000000000000000000";
102
103/// The epoch-key-archive scope for a v2 `control_root` (CORD-02 §2): non-hex on
104/// purpose, so it collides with neither a channel id nor the root sentinel.
105/// Reserves the pair beside the root at mint (retry idempotency) and archives
106/// the secret per epoch.
107pub const CONTROL_ROOT_SCOPE: &str = "control-root";
108
109/// The epoch-key-archive scope for each epoch's Control Plane address, kept so the Audit Log can
110/// read an epoch back after a Refounding has moved the plane on. Non-hex, like the above.
111pub const CONTROL_PK_SCOPE: &str = "control-pk";
112
113/// The bytes behind an id written exactly as [`CommunityId::to_hex`] writes one, so a
114/// byte-keyed cache answers only for strings it would have matched character for character.
115pub(crate) fn id32_from_hex(hex: &str) -> Option<[u8; 32]> {
116    crate::simd::hex::hex_to_bytes_32_checked(hex).filter(|_| !hex.bytes().any(|b| b.is_ascii_uppercase()))
117}
118
119/// 32 cryptographically-random bytes (OsRng).
120pub(crate) fn random_32() -> [u8; 32] {
121    let mut b = [0u8; 32];
122    rand::rngs::OsRng.fill_bytes(&mut b);
123    b
124}
125
126/// A reference to an encrypted image blob (community logo/banner), using the same
127/// technique as NIP-17 file attachments: a fresh random AES-GCM key+nonce encrypts the
128/// image, the ciphertext is uploaded to Blossom, and this reference travels inside
129/// ServerRoot-sealed metadata. So possession of the server-root key (every member) gates
130/// the image, and there is no key reuse across images.
131#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
132pub struct CommunityImage {
133    /// Blossom URL of the encrypted blob.
134    pub url: String,
135    /// Hex AES-GCM key (per-image, random).
136    pub key: String,
137    /// Hex AES-GCM nonce.
138    pub nonce: String,
139    /// SHA-256 of the plaintext image (integrity check + local cache key).
140    pub hash: String,
141    /// File extension hint (e.g. "png", "jpg").
142    #[serde(default)]
143    pub ext: String,
144}
145
146/// Community icons and banners are raster only, sent and shown, like custom emoji.
147pub const SVG_REFUSED: &str = "SVG isn't supported for community icons or banners";
148
149/// Reads an image pointer field so a malformed one from another client drops alone, rather
150/// than failing the whole metadata document and taking the name and description with it.
151pub(crate) fn lenient_image<'de, D, T>(d: D) -> Result<Option<T>, D::Error>
152where
153    D: serde::Deserializer<'de>,
154    T: serde::de::DeserializeOwned,
155{
156    let value = Option::<serde_json::Value>::deserialize(d)?;
157    Ok(value.and_then(|v| serde_json::from_value(v).ok()))
158}
159
160/// Protocol cap on a Community's relay set (§ transport). More relays are needless and
161/// amplify resource + metadata-exposure cost; 5 gives redundancy without centralisation.
162/// Enforced by truncate-on-read at every Community/CommunityInvite construction boundary, so a
163/// hostile or legacy bundle degrades to ≤5 distinct relays rather than being honored or rejected.
164pub const MAX_COMMUNITY_RELAYS: usize = 5;
165
166/// Dedupe (order-preserving) + truncate a relay set to [`MAX_COMMUNITY_RELAYS`]. Dedup first so the
167/// cap means "up to 5 DISTINCT relays" — a bundle padding one relay 5× can't waste the budget.
168/// Whether an older page asked from `before_secs` reached the channel's start: the relays
169/// answered, brought nothing this device lacked, left no cursor to go on from, and nothing held
170/// lies below the cursor. Relays serve the cursor's own second again, so a page of only held
171/// messages can still be the end.
172pub fn reached_history_start(channel_id: &str, before_secs: Option<u64>, count: &crate::BackfillCount) -> bool {
173    reached_start(count, before_secs, |b| crate::db::events::newest_message_before(channel_id, b).is_some())
174}
175
176/// Whether this account holds the key a channel's history began under. A member who joined
177/// after a rotation holds only the epochs since: what came before sits on the relays sealed
178/// under keys it never received, so the oldest message it can read is not the channel's first.
179pub fn holds_history_from_start(channel_id: &str) -> bool {
180    let Ok(Some(cid)) = crate::db::community::community_id_for_channel(channel_id) else { return true };
181    let id = CommunityId(crate::simd::hex::hex_to_bytes_32(&cid));
182    let Ok(Some(community)) = crate::db::community::load_community_v2(&id) else { return true };
183    let ch = ChannelId(crate::simd::hex::hex_to_bytes_32(channel_id));
184    let Some(channel) = community.channel(&ch) else { return true };
185    let scope = if channel.private { channel_id } else { SERVER_ROOT_SCOPE_HEX };
186    let current = (channel.private && channel.key.is_some()).then_some(channel.epoch.0);
187    let oldest = crate::db::community::held_epoch_keys(&cid, scope).unwrap_or_default().into_iter().map(|(e, _)| e.0).chain(current).min();
188    oldest.is_none_or(|e| e == 0)
189}
190
191fn reached_start(count: &crate::BackfillCount, before_secs: Option<u64>, held_below: impl Fn(u64) -> bool) -> bool {
192    if count.unreachable || count.next_before.is_some() || count.new_messages > 0 {
193        return false;
194    }
195    count.fetched == 0 || before_secs.is_some_and(|b| !held_below(b))
196}
197
198#[cfg(test)]
199mod start_tests {
200    use super::reached_start;
201    use crate::BackfillCount;
202
203    #[test]
204    fn a_page_of_only_the_cursors_own_second_is_the_start() {
205        let held_boundary = BackfillCount { fetched: 3, new_messages: 0, next_before: None, unreachable: false };
206        assert!(reached_start(&held_boundary, Some(1000), |_| false), "nothing older held or served");
207        assert!(!reached_start(&held_boundary, Some(1000), |_| true), "held history below: a page that met it, not the start");
208    }
209
210    #[test]
211    fn silence_is_never_the_start() {
212        let silent = BackfillCount { unreachable: true, ..Default::default() };
213        assert!(!reached_start(&silent, Some(1000), |_| false));
214        let answered_empty = BackfillCount::default();
215        assert!(reached_start(&answered_empty, Some(1000), |_| false));
216    }
217
218    #[test]
219    fn more_to_walk_or_new_rows_is_not_the_start() {
220        assert!(!reached_start(&BackfillCount { fetched: 50, new_messages: 0, next_before: Some(900), unreachable: false }, Some(1000), |_| false));
221        assert!(!reached_start(&BackfillCount { fetched: 50, new_messages: 4, next_before: None, unreachable: false }, Some(1000), |_| false));
222    }
223}
224
225/// An invite's creator as an npub: Joins name it in hex, older ones in bech32.
226pub fn inviter_npub(creator: &str) -> Option<String> {
227    use nostr_sdk::prelude::{PublicKey, ToBech32};
228    PublicKey::parse(creator).ok().and_then(|pk| pk.to_bech32().ok())
229}
230
231pub fn cap_relays(relays: Vec<String>) -> Vec<String> {
232    let mut seen = std::collections::HashSet::new();
233    let mut out = Vec::with_capacity(relays.len().min(MAX_COMMUNITY_RELAYS));
234    for r in relays {
235        if out.len() >= MAX_COMMUNITY_RELAYS {
236            break;
237        }
238        if seen.insert(r.clone()) {
239            out.push(r);
240        }
241    }
242    out
243}
244
245#[cfg(test)]
246mod freshness_tests {
247    use super::*;
248
249    // The realtime gate: a just-sent event is fresh; a relay-backfill replay
250    // (hours to months old) and far-future junk are not "new" surfaces.
251    #[test]
252    fn realtime_freshness_window() {
253        let now_ms = crate::clock::now_ms();
254        assert!(is_realtime_fresh(now_ms), "just-sent is fresh");
255        assert!(is_realtime_fresh(now_ms - REALTIME_FRESH_WINDOW_MS / 2), "modest delay is fresh");
256        assert!(!is_realtime_fresh(now_ms - 3_600_000), "an hour-old replay is not");
257        assert!(!is_realtime_fresh(now_ms.saturating_sub(30 * 24 * 3_600_000)), "a month-old replay is not");
258        assert!(is_realtime_fresh(now_ms + 60_000), "sender clock slightly ahead still fresh");
259    }
260}