Skip to main content

vector_core/community/v2/
inbound.rs

1//! v2 inbound bridge — turns opened v2 events into the protocol-agnostic
2//! [`InboundEventHandler`] callbacks the rest of Vector (and the SDK's
3//! `on_message`) already consumes. The handler is the seam: v1 and v2 both feed
4//! it, so a bot receives v2 messages with no SDK change.
5//!
6//! Dispatch is by which plane a kind-1059 wrap opens under. A received wrap is
7//! tried against each held channel's Chat-Plane key (author match, no trial
8//! decrypt), then the Guestbook plane; a control-plane fold is a heavier
9//! separate path (metadata/roster), handled by the service refresh, not here.
10
11use nostr_sdk::prelude::PublicKey;
12use nostr_sdk::prelude::ToBech32;
13
14use super::super::attachments::attachments_from_tags;
15use super::chat::{self, ChatEvent};
16use super::community::CommunityV2;
17use super::guestbook::{self, GuestbookEntry};
18use super::stream;
19use crate::event_handler::InboundEventHandler;
20use crate::state::ChatState;
21use crate::types::{EmojiTag, Message, Reaction};
22
23/// Build a protocol-agnostic [`Message`] from an opened v2 chat Message event.
24/// Mirrors v1's `build_message` field-for-field (id = the rumor id, ms time,
25/// `mine`, npub, imeta attachments, NIP-30 emoji, the reply reference), so the
26/// frontend/SDK renderers treat a v2 message identically to a v1 or DM one.
27pub fn chat_message_to_message(
28    opened: &stream::OpenedStream,
29    reply_to: &Option<chat::ReplyRef>,
30    emoji: &[(String, String)],
31    my_pubkey: &PublicKey,
32) -> Message {
33    let (replied_to, replied_to_npub) = match reply_to {
34        Some(r) => (
35            crate::simd::hex::bytes_to_hex_32(&r.id),
36            r.author.and_then(|a| a.to_bech32().ok()),
37        ),
38        None => (String::new(), None),
39    };
40    let attachments = attachments_from_tags(opened.rumor.tags.iter(), &crate::db::get_download_dir());
41    Message {
42        id: opened.rumor_id.to_hex(),
43        // Drop any blob URL a foreign client (e.g. Armada) also inlined into the caption.
44        content: super::super::attachments::strip_attachment_urls(&opened.rumor.content, &attachments),
45        replied_to,
46        replied_to_npub,
47        at: opened.at_ms,
48        mine: opened.author == *my_pubkey,
49        npub: opened.author.to_bech32().ok(),
50        attachments,
51        emoji_tags: emoji
52            .iter()
53            .map(|(shortcode, url)| EmojiTag { shortcode: shortcode.clone(), url: url.clone() })
54            .collect(),
55        addressed_bots: crate::bot_interface::addressed_bots(opened.rumor.tags.iter()),
56        wrapper_event_id: Some(opened.wrapper_id.to_hex()),
57        // Self-Destruct Timer: the sender's NIP-40 expiry drives our local purge.
58        expiration: chat::message_expiration(&opened.rumor),
59        ..Default::default()
60    }
61}
62
63/// Whether `author` sits on the banlist of the community owning `channel_id`
64/// (fail-open on a lookup error: availability must never hide honest traffic —
65/// the ban re-applies on the next fold).
66fn author_is_banned_here(channel_id: &str, author: &PublicKey) -> bool {
67    let Ok(Some(cid_hex)) = crate::db::community::community_id_for_channel(channel_id) else {
68        return false;
69    };
70    crate::db::community::is_author_banned(&cid_hex, author)
71}
72
73/// May `deleter` remove a message authored by `author` in this channel? The
74/// deleter needs `MANAGE_MESSAGES`, a strict outrank, and a synced citation.
75/// Blocked once dissolved: a dead community honors no new authority action, only
76/// the self-deletes its seal deliberately leaves open (CORD-02 §9).
77fn moderation_delete_authorized(
78    channel_id: &str,
79    deleter: &PublicKey,
80    author: &PublicKey,
81    tags: &nostr_sdk::prelude::Tags,
82) -> bool {
83    let Ok(Some(cid_hex)) = crate::db::community::community_id_for_channel(channel_id) else {
84        return false;
85    };
86    if crate::db::community::get_community_dissolved(&cid_hex).unwrap_or(false) {
87        return false;
88    }
89    let Some(owner_hex) = crate::community::moderation::owner_hex(&cid_hex) else {
90        return false; // no provable owner → no provable authority chain
91    };
92    let deleter_hex = deleter.to_hex();
93    let citation = crate::community::edition::AuthorityCitation::from_tags(tags);
94    if !super::service::citation_is_synced(&cid_hex, &owner_hex, &deleter_hex, citation.as_ref()) {
95        return false;
96    }
97    let roster = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
98    crate::community::moderation::can_hide(Some(&owner_hex), &roster, &deleter_hex, &author.to_hex())
99}
100
101/// What applying a v2 chat event to STATE yielded — the caller persists it (async)
102/// once the STATE lock is dropped. Mirrors v1's `IncomingEvent` for the chat sub-kinds:
103/// a message row is saved fresh or re-saved (a landed reaction rides the row), a delete
104/// drops it. Persistence is the caller's so the apply step stays sync + lock-scoped.
105pub enum ChatPersist {
106    /// A brand-new message — save its row.
107    New(Message),
108    /// A message changed: a reaction landed (`edit_event` None → re-save the row, which
109    /// carries reactions) or an edit applied (`edit_event` Some → save the folded
110    /// MESSAGE_EDIT event, event-sourced like v1 + DMs, never a row overwrite).
111    Updated { message: Message, edit_event: Option<Box<crate::stored_event::StoredEvent>> },
112    /// A message removed by its author — drop its row.
113    Removed(String),
114    /// A reaction revoked by its reactor — drop the kind-7 row (save is
115    /// additive; a lingering row would resurrect the chip on the next load)
116    /// and re-save the parent so its embedded reactions refresh.
117    ReactionRemoved { reaction_id: String, message: Message },
118}
119
120/// Apply an opened v2 [`ChatEvent`] to STATE (dedup + aggregate onto the SHARED
121/// [`ChatState`]), mirroring v1's `ingest_message`/`apply_reaction`/`apply_delete`. Sync:
122/// the DB dedup read + STATE mutation run under the caller's lock; the caller then does the
123/// async DB persist on the returned [`ChatPersist`] (see [`persist_chat`]). Returns `None`
124/// for a duplicate, a non-persisted kind (typing/webxdc), an edit (increment 2), or an
125/// aggregate whose target isn't resident in this channel.
126pub fn apply_chat_to_state(state: &mut ChatState, event: &ChatEvent, channel_id: &str, my_pubkey: &PublicKey) -> Option<ChatPersist> {
127    // CORD-04 §4: a banned npub VANISHES — every chat event they author (message,
128    // reaction, edit, delete) is dropped at fold time. Severance (the rekey) only
129    // cuts their READ of new epochs; they still hold old epoch keys and can post
130    // to old planes forever — refusing to fold them is what makes the ban hold.
131    // The persisted banlist can never name the owner (the authority fold refuses
132    // a ban whose target is position 0), so no owner exemption is needed here.
133    if author_is_banned_here(channel_id, &event.opened().author) {
134        return None;
135    }
136    match event {
137        ChatEvent::Message { opened, reply_to, emoji } => {
138            let msg = chat_message_to_message(opened, reply_to, emoji, my_pubkey);
139            // DB dedup: a known inner id is already stored — don't re-ingest/re-emit (a
140            // catch-up sweep re-fetches the whole page; in-memory STATE holds only a window).
141            if crate::db::events::event_exists(&msg.id).unwrap_or(false) {
142                return None;
143            }
144            state.ensure_community_chat(channel_id);
145            // Persist regardless of the STATE-add result: `event_exists` already proved
146            // it's not in the DB, so a `false` here means only that another writer put it
147            // in STATE first — the row must still be saved, or it's lost until re-fetch.
148            state.add_message_to_chat(channel_id, &msg);
149            Some(ChatPersist::New(msg))
150        }
151        ChatEvent::Reaction { opened, target, emoji, emoji_url, .. } => {
152            let target_id = crate::simd::hex::bytes_to_hex_32(target);
153            // Cross-channel guard: a reaction lands only on a target resident in the SAME
154            // channel it was sealed under (its binding authenticates its own channel, never
155            // the target's) — else a member could inject reactions across channels.
156            if !matches!(state.find_message(&target_id), Some((chat, _)) if chat.id == channel_id) {
157                return None;
158            }
159            let reaction = Reaction {
160                id: opened.rumor_id.to_hex(),
161                reference_id: target_id.clone(),
162                // npub, not hex: the frontend's whole reaction contract (profile
163                // name resolve + the own-reaction highlight vs strPubkey) keys on
164                // bech32 — exactly what v1 stores.
165                author_id: opened.author.to_bech32().unwrap_or_else(|_| opened.author.to_hex()),
166                emoji: emoji.clone(),
167                emoji_url: emoji_url.clone(),
168            };
169            let (_c, added) = state.add_reaction_to_message(&target_id, reaction)?;
170            added.then(|| state.find_message(&target_id).map(|(_c, m)| ChatPersist::Updated { message: m, edit_event: None }))?
171        }
172        ChatEvent::Edit { opened, target, new_content } => {
173            // Dedup by the edit's own rumor id (its MESSAGE_EDIT row below): the
174            // in-message `apply_edit` dedups silently, so without this a re-wrapped
175            // duplicate would still return Updated and re-fire the handler — the
176            // replay hole the persist-gated callbacks exist to close.
177            if crate::db::events::event_exists(&opened.rumor_id.to_hex()).unwrap_or(false) {
178                return None;
179            }
180            let target_id = crate::simd::hex::bytes_to_hex_32(target);
181            // Author-scoped + same-channel: only the original author edits their own message.
182            let editor_npub = opened.author.to_bech32().ok()?;
183            if !matches!(state.find_message(&target_id), Some((chat, m)) if chat.id == channel_id && m.npub.as_deref() == Some(editor_npub.as_str())) {
184                return None;
185            }
186            // Apply to STATE via the shared canonical applier (seeds history with the
187            // original once, dedups by `edited_at`, swaps content) — reused from v1/DMs.
188            let edited_at = opened.at_ms;
189            let (_c, message) = state.update_message(&target_id, |m| m.apply_edit(new_content.clone(), edited_at, Vec::new()))?;
190            // Persist as a folded MESSAGE_EDIT event (chat_id set at save time), matching v1.
191            let edit_event = crate::stored_event::StoredEventBuilder::new()
192                .id(opened.rumor_id.to_hex())
193                .kind(crate::stored_event::event_kind::MESSAGE_EDIT)
194                .content(new_content.clone())
195                .reference_id(Some(target_id.clone()))
196                .created_at(edited_at / 1000)
197                .mine(opened.author == *my_pubkey)
198                .npub(opened.author.to_bech32().ok())
199                .build();
200            Some(ChatPersist::Updated { message, edit_event: Some(Box::new(edit_event)) })
201        }
202        ChatEvent::Delete { opened, target, .. } => {
203            let target_id = crate::simd::hex::bytes_to_hex_32(target);
204            // A delete may target a REACTION (an un-react) rather than a message.
205            // Reactions are author-revocable only: the deleter must be the
206            // reactor. Checked before the message path so a reaction id never
207            // falls through to message-removal logic (v1's exact rule).
208            if let Some((_chat, message_id, author_npub, _)) = state.find_reaction(&target_id) {
209                let reactor_ok = PublicKey::parse(&author_npub).map(|pk| pk == opened.author).unwrap_or(false);
210                if !reactor_ok {
211                    return None;
212                }
213                return state
214                    .remove_reaction_from_message(&message_id, &target_id)
215                    .map(|(_cid, message)| ChatPersist::ReactionRemoved { reaction_id: target_id, message });
216            }
217            // A delete removes its author's OWN message, or someone else's under
218            // MANAGE_MESSAGES. Resolve the target's author from the resident copy, then
219            // the DB for a paged-out row — residency is a cache detail, and authorizing
220            // only what's in the window would let a moderator's hide of an older message
221            // land on some peers and not others.
222            let resident = state.find_message(&target_id).and_then(|(_, m)| m.npub.clone());
223            let author_npub = match resident {
224                Some(n) => Some(n),
225                None => crate::db::events::event_author(&target_id).ok().flatten(),
226            };
227            let author = author_npub.as_deref().and_then(|n| PublicKey::parse(n).ok())?;
228            let authorized = author == opened.author
229                || moderation_delete_authorized(channel_id, &opened.author, &author, &opened.rumor.tags);
230            if !authorized {
231                return None;
232            }
233            // A paged-out target isn't in STATE to remove; the caller's persist step
234            // drops the stored row either way.
235            let _ = state.remove_message(&target_id);
236            Some(ChatPersist::Removed(target_id))
237        }
238        ChatEvent::Typing { .. } | ChatEvent::Webxdc { .. } => None,
239    }
240}
241
242/// Apply an already-opened chat event to STATE + the shared store — the LIVE
243/// counterpart of [`crate::VectorCore::v2_backfill_channel`]'s catch-up persistence.
244/// The dispatcher opened the wrap (so nothing decrypts twice); the returned outcome
245/// is what the caller's callbacks fire from — a duplicate, a non-resident target,
246/// or a forged edit/delete yields `None` and nothing re-fires.
247pub async fn persist_chat_event(
248    event: &ChatEvent,
249    channel_id: &str,
250    my_pubkey: &PublicKey,
251    session: &crate::state::SessionGuard,
252) -> Option<ChatPersist> {
253    let outcome = {
254        let mut st = crate::state::STATE.lock().await;
255        // A swap can land on the lock await: only mutate THIS account's STATE.
256        if !session.is_valid() {
257            return None;
258        }
259        apply_chat_to_state(&mut st, event, channel_id, my_pubkey)
260    }?;
261    // Resolve a reply's preview (content/npub) from the DB before persist + emit
262    // (v1 parity): the parent is often persisted but outside the in-memory window,
263    // and without this the live render shows a reply with no context.
264    let outcome = match outcome {
265        ChatPersist::New(mut m) => {
266            if !m.replied_to.is_empty() {
267                let _ = crate::db::events::populate_reply_context(&mut m).await;
268            }
269            ChatPersist::New(m)
270        }
271        o => o,
272    };
273    // …and only persist to THIS account's DB (the save straddles an await).
274    if !session.is_valid() {
275        return None;
276    }
277    persist_chat(channel_id, &outcome).await;
278    // §7 pin duties: a deleted pinned message wants the omitting edition, an
279    // edited one a refreshed proof bundle. Fired only from a PERSISTED outcome
280    // (the dedup/authorization gates above already passed); non-curators no-op.
281    match (&outcome, event) {
282        (ChatPersist::Removed(target), _) => {
283            super::service::spawn_pin_duty(channel_id, target, None);
284        }
285        (ChatPersist::Updated { .. }, ChatEvent::Edit { opened, target, .. }) => {
286            let target_hex = crate::simd::hex::bytes_to_hex_32(target);
287            super::service::spawn_pin_duty(channel_id, &target_hex, Some(opened.clone()));
288        }
289        _ => {}
290    }
291    Some(outcome)
292}
293
294/// Persist an [`apply_chat_to_state`] outcome to the shared events DB — async, run by the
295/// caller AFTER the STATE lock drops (a message row carries its reactions, so a reaction
296/// re-saves the row; a delete drops it).
297pub async fn persist_chat(channel_id: &str, outcome: &ChatPersist) {
298    match outcome {
299        ChatPersist::New(m) => {
300            let _ = crate::db::events::save_message(channel_id, m).await;
301        }
302        // An edit is event-sourced: save the MESSAGE_EDIT row (folded on reload), never a
303        // row overwrite. A reaction rides the message row, so re-save it.
304        ChatPersist::Updated { message, edit_event } => match edit_event {
305            Some(ev) => {
306                let mut ev = (**ev).clone();
307                // get-or-CREATE: a lookup-only id would leave a fresh channel's edit at
308                // chat_id 0 (orphaned, dropped on the reload fold).
309                if let Ok(cid) = crate::db::id_cache::get_or_create_chat_id(channel_id) {
310                    ev.chat_id = cid;
311                }
312                let _ = crate::db::events::save_event(&ev).await;
313            }
314            None => {
315                let _ = crate::db::events::save_message(channel_id, message).await;
316            }
317        },
318        ChatPersist::Removed(id) => {
319            let _ = crate::db::events::delete_event(id).await;
320        }
321        ChatPersist::ReactionRemoved { reaction_id, message } => {
322            let _ = crate::db::events::delete_event(reaction_id).await;
323            let _ = crate::db::events::save_message(channel_id, message).await;
324        }
325    }
326}
327
328/// The typed outcome of dispatching one v2 wrap.
329#[derive(Debug, Clone)]
330pub enum DispatchedV2 {
331    /// An OPENED chat event (message/reaction/edit/delete) on `channel_id` (hex),
332    /// NOT yet applied. The realtime layer runs it through [`persist_chat_event`]
333    /// and fires the matching callback from the outcome — so a re-wrapped
334    /// duplicate (any keyholder can re-wrap a signed seal into a fresh 1059) or a
335    /// forged edit/delete never re-fires a handler, exactly v1's model.
336    Chat { channel_id: String, event: Box<ChatEvent> },
337    /// A typing indicator from `npub` on `channel_id`.
338    Typing { channel_id: String, npub: String },
339    /// A Guestbook join/leave for `npub`.
340    Presence { npub: String, joined: bool },
341    /// A Guestbook Kick naming `target`. Returned unjudged: the store keeps the
342    /// raw rumor and the memberlist fold is what applies KICK authority, so the
343    /// realtime layer ingests it and re-folds rather than trusting the wrap.
344    Kick { target: PublicKey },
345    /// A wrap on this community's Control Plane — its metadata/channel set may
346    /// have changed. Recognized here (address match) but NOT folded: the fold
347    /// needs the whole edition chain, so the realtime layer re-fetches + re-folds
348    /// + re-subscribes. `community_id` is hex.
349    Control { community_id: String },
350    /// A wrap on one of this community's next-epoch rekey planes — a rotation is in
351    /// flight. Recognized by address; the realtime layer runs the stateful catch-up
352    /// ([`super::service::follow_rekeys`]) across every scope. `community_id` is hex.
353    Rekey { community_id: String },
354    /// A verified owner-signed tombstone at the dissolved plane (CORD-02 §9): the
355    /// community is dead. The realtime layer seals it read-only. `community_id` is hex.
356    Dissolved { community_id: String },
357    /// The wrap opened on a v2 plane but carries nothing the handler renders
358    /// (e.g. a WebXDC signal, or a kick we don't surface in the first cut).
359    Ignored,
360    /// Not a v2 plane of this community — try elsewhere / drop.
361    NotOurs,
362}
363
364/// Dispatch a received kind-1059 wrap for `community`: route it to the plane it
365/// opens under. Chat events are returned OPENED (the realtime layer persists,
366/// then fires callbacks from the outcome); only the non-persisted kinds (typing,
367/// guestbook presence) fire their callback inline here. Purely in-memory — so
368/// this stays offline-testable.
369pub fn dispatch_wrap(
370    wrap: &nostr_sdk::prelude::Event,
371    community: &CommunityV2,
372    my_pubkey: &PublicKey,
373    handler: &dyn InboundEventHandler,
374) -> DispatchedV2 {
375    // 1. Chat planes: try each held channel by its group key (author match).
376    for ch in &community.channels {
377        // A keyless private channel is UNREADABLE — never address it at the root plane
378        // (channel_secret falls back to the root, which would be a private→public leak).
379        if ch.private && ch.key.is_none() {
380            continue;
381        }
382        let (secret, epoch) = community.channel_secret(ch);
383        let group = super::derive::channel_group_key(&secret, &ch.id, epoch);
384        if wrap.pubkey != group.pk() {
385            continue;
386        }
387        let Ok(event) = chat::open_chat_event(wrap, &group, &ch.id, epoch) else {
388            return DispatchedV2::NotOurs;
389        };
390        let channel_id = crate::simd::hex::bytes_to_hex_32(&ch.id.0);
391        return dispatch_chat_event(event, &channel_id, my_pubkey, handler);
392    }
393
394    // 2. Guestbook plane: join/leave presence.
395    let gb = super::derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch);
396    if wrap.pubkey == gb.pk() {
397        if let Ok(opened) = stream::open_wrap(wrap, &gb) {
398            if let Ok(ev) = guestbook::parse_guestbook_event(&opened) {
399                return dispatch_guestbook(&ev, community, handler);
400            }
401        }
402        return DispatchedV2::Ignored;
403    }
404
405    // 3. Control plane: a metadata/channel edition. Recognized by address only —
406    // the fold needs the whole chain, which the realtime layer re-fetches. Shares
407    // one address helper with the subscription so the two can't drift.
408    if wrap.pubkey == super::realtime::control_author(community) {
409        return DispatchedV2::Control { community_id: crate::simd::hex::bytes_to_hex_32(&community.id().0) };
410    }
411
412    // 4. Rekey planes: a rotation in flight (base or a private channel), addressed
413    // at the next epoch. Same author-set the subscription rides — one source of
414    // truth ([`super::realtime::rekey_authors`]) so recognition and subscription
415    // can't drift.
416    if super::realtime::rekey_authors(community).iter().any(|p| *p == wrap.pubkey) {
417        return DispatchedV2::Rekey { community_id: crate::simd::hex::bytes_to_hex_32(&community.id().0) };
418    }
419
420    // 5. Dissolved plane: the terminal tombstone (CORD-02 §9). Honor ONLY a valid
421    // owner seal — a foreign event at this public address is noise.
422    if wrap.pubkey == super::derive::dissolved_group_key(community.id()).pk() {
423        if super::dissolution::verify_dissolved(wrap, &community.identity) {
424            return DispatchedV2::Dissolved { community_id: crate::simd::hex::bytes_to_hex_32(&community.id().0) };
425        }
426        return DispatchedV2::Ignored;
427    }
428
429    DispatchedV2::NotOurs
430}
431
432fn dispatch_chat_event(event: ChatEvent, channel_id: &str, my_pubkey: &PublicKey, handler: &dyn InboundEventHandler) -> DispatchedV2 {
433    match event {
434        // Typing is ephemeral (never persisted) — fired inline, so it carries its
435        // own CORD-04 banned-author drop (the persisted kinds get theirs in
436        // `apply_chat_to_state`).
437        ChatEvent::Typing { opened } => {
438            if author_is_banned_here(channel_id, &opened.author) {
439                return DispatchedV2::Ignored;
440            }
441            let npub = opened.author.to_bech32().unwrap_or_default();
442            let until = opened.at_ms / 1000 + 30;
443            handler.on_community_typing(channel_id, &npub, until);
444            DispatchedV2::Typing { channel_id: channel_id.to_string(), npub }
445        }
446        // A WebXDC peer signal fires the same handler surface v1 uses — the shared
447        // tail (30078 persist + recency gate + Iroh wiring + the lobby emit) does
448        // the rest. Own-device echoes drop: the local realtime layer tracks itself.
449        ChatEvent::Webxdc { opened } => {
450            if opened.author == *my_pubkey || author_is_banned_here(channel_id, &opened.author) {
451                return DispatchedV2::Ignored;
452            }
453            let Some((topic_id, node_addr)) = crate::webxdc::parse_peer_signal(&opened.rumor.content) else {
454                return DispatchedV2::Ignored;
455            };
456            let npub = opened.author.to_bech32().unwrap_or_default();
457            handler.on_community_webxdc(
458                channel_id,
459                &npub,
460                &topic_id,
461                node_addr.as_deref(),
462                &opened.rumor_id.to_hex(),
463                opened.at_ms / 1000,
464            );
465            DispatchedV2::Ignored
466        }
467        // Message/Reaction/Edit/Delete all persist first; their callbacks fire from
468        // the outcome (dedup + author checks), never optimistically.
469        event => DispatchedV2::Chat { channel_id: channel_id.to_string(), event: Box::new(event) },
470    }
471}
472
473fn dispatch_guestbook(ev: &guestbook::GuestbookEvent, community: &CommunityV2, handler: &dyn InboundEventHandler) -> DispatchedV2 {
474    // CORD-04 §4 is a RENDER/FOLD rule, not a storage rule: a banned npub's
475    // presence draws no line, but the event still reaches the store, because the
476    // fold subtracts the banlist REVERSIBLY. Dropping it here instead is
477    // destructive: an invite legally races an unban ("any keyholder can whisper
478    // keys"), so a Join can arrive seconds before the unban edition — eaten at
479    // the store, the member stays invisible after the unban with nothing left to
480    // re-fold.
481    let suppressed = match &ev.entry {
482        GuestbookEntry::Join { member, .. } | GuestbookEntry::Leave { member, .. } => {
483            let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
484            crate::db::community::is_author_banned(&cid_hex, member)
485        }
486        _ => false,
487    };
488    // The REAL rumor id keys the presence line: `save_system_event_at` dedups by
489    // it, so every distinct join/leave inserts exactly once no matter how many
490    // paths (live replay, reconnect, catch-up) deliver it.
491    let event_id = crate::simd::hex::bytes_to_hex_32(&ev.rumor_id);
492    // Presence is announced against the community's SURFACED row (the primary
493    // channel — the one chat the list shows). A community with NO channels has no
494    // row to announce against, and `unwrap_or_default()` invented one: a blank
495    // conversation id, which a UNIQUE identifier then collapsed into a single
496    // unopenable chat shared by every such community. None = don't announce; the
497    // dispatch still reports the presence so the memberlist bookkeeping runs, and
498    // the guestbook re-folds the line once a channel exists.
499    let chat_id = community
500        .primary_channel()
501        .map(|c| crate::simd::hex::bytes_to_hex_32(&c.id.0));
502    match &ev.entry {
503        GuestbookEntry::Join { member, at_ms, invited_by } => {
504            let npub = member.to_bech32().unwrap_or_default();
505            let (by, label) = match invited_by {
506                Some((c, l)) => (Some(c.as_str()), Some(l.as_str())),
507                None => (None, None),
508            };
509            if let (false, Some(chat)) = (suppressed, chat_id.as_deref()) {
510                handler.on_community_presence(chat, &npub, true, &event_id, at_ms / 1000, by, label);
511            }
512            DispatchedV2::Presence { npub: npub.clone(), joined: true }
513        }
514        GuestbookEntry::Leave { member, at_ms } => {
515            let npub = member.to_bech32().unwrap_or_default();
516            if let (false, Some(chat)) = (suppressed, chat_id.as_deref()) {
517                handler.on_community_presence(chat, &npub, false, &event_id, at_ms / 1000, None, None);
518            }
519            DispatchedV2::Presence { npub: npub.clone(), joined: false }
520        }
521        // A Kick shapes the memberlist, not the feed — so no presence line, but it
522        // MUST reach the store or the target never leaves anyone's roster.
523        GuestbookEntry::Kick { target, .. } => DispatchedV2::Kick { target: *target },
524        GuestbookEntry::Snapshot { .. } => DispatchedV2::Ignored,
525    }
526}
527
528#[cfg(test)]
529mod tests {
530    use super::*;
531    use super::super::service;
532    use crate::community::transport::memory::MemoryRelay;
533    use crate::community::transport::Transport;
534    use nostr_sdk::prelude::Keys;
535    use std::sync::Mutex;
536
537    /// A handler that records every callback it receives.
538    #[derive(Default)]
539    struct Recorder {
540        messages: Mutex<Vec<(String, Message)>>,
541        updates: Mutex<Vec<(String, String)>>,
542        removed: Mutex<Vec<(String, String)>>,
543        presence: Mutex<Vec<(String, bool)>>,
544    }
545    impl InboundEventHandler for Recorder {
546        fn on_community_message(&self, chat_id: &str, msg: &Message, _is_new: bool) {
547            self.messages.lock().unwrap().push((chat_id.to_string(), msg.clone()));
548        }
549        fn on_community_update(&self, chat_id: &str, target: &str, _msg: &Message) {
550            self.updates.lock().unwrap().push((chat_id.to_string(), target.to_string()));
551        }
552        fn on_community_removed(&self, chat_id: &str, target: &str) {
553            self.removed.lock().unwrap().push((chat_id.to_string(), target.to_string()));
554        }
555        fn on_community_presence(&self, _c: &str, npub: &str, joined: bool, _e: &str, _a: u64, _b: Option<&str>, _l: Option<&str>) {
556            self.presence.lock().unwrap().push((npub.to_string(), joined));
557        }
558    }
559
560    fn init() -> (tempfile::TempDir, std::sync::MutexGuard<'static, ()>, Keys) {
561        let guard = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
562        crate::db::close_database();
563        crate::db::clear_id_caches();
564        let tmp = tempfile::tempdir().unwrap();
565        static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(90_000);
566        let n = N.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
567        const B: &[u8] = b"qpzry9x8gf2tvdw0s3jn54khce6mua7l";
568        let mut acct = String::from("npub1");
569        let mut v = n as usize;
570        for _ in 0..58 {
571            acct.push(B[v % 32] as char);
572            v = v / 32 + 7;
573        }
574        std::fs::create_dir_all(tmp.path().join(&acct)).unwrap();
575        crate::db::set_app_data_dir(tmp.path().to_path_buf());
576        crate::db::set_current_account(acct.clone()).unwrap();
577        crate::db::init_database(&acct).unwrap();
578        let _ = crate::state::take_nostr_client();
579        let me = Keys::generate();
580        crate::state::MY_SECRET_KEY.store_from_keys(&me, &[]);
581        crate::state::set_my_public_key(me.public_key());
582        (tmp, guard, me)
583    }
584
585    #[tokio::test]
586    async fn a_received_message_wrap_opens_then_fires_from_the_persist_outcome() {
587        use nostr_sdk::prelude::Timestamp;
588        let (_tmp, _guard, me) = init();
589        let relay = MemoryRelay::new();
590        let community = service::create_community(&relay, "In", vec!["wss://r".into()], None).await.unwrap();
591        let general = community.channels[0].id;
592        let cid = crate::simd::hex::bytes_to_hex_32(&general.0);
593
594        // ANOTHER member (holds the root) posts — the incoming case, so no local
595        // send echo pre-persisted it.
596        let member = Keys::generate();
597        let group = super::super::derive::channel_group_key(&community.community_root, &general, community.root_epoch);
598        let rumor = chat::build_message_rumor(member.public_key(), &general, community.root_epoch, "ping", None, &[], vec![], 5_000);
599        let (wrap, _) = chat::seal_chat_rumor(&rumor, &group, &member, Timestamp::from_secs(5), false).unwrap();
600
601        // Dispatch OPENS the event but fires no message callback — that belongs to
602        // the persist outcome (dedup + author checks), v1's model.
603        let rec = Recorder::default();
604        let dispatched = dispatch_wrap(&wrap, &community, &me.public_key(), &rec);
605        assert!(rec.messages.lock().unwrap().is_empty(), "no optimistic message callback");
606        let DispatchedV2::Chat { channel_id, event } = dispatched else {
607            panic!("a chat wrap dispatches as Chat");
608        };
609        assert_eq!(channel_id, cid);
610
611        let session = crate::state::SessionGuard::capture();
612        let outcome = persist_chat_event(&event, &channel_id, &me.public_key(), &session).await;
613        let Some(ChatPersist::New(msg)) = outcome else {
614            panic!("the first delivery persists as New");
615        };
616        assert_eq!(msg.content, "ping");
617        assert!(!msg.mine, "authored by the other member");
618
619        // A RE-WRAP of the same signed rumor (any keyholder can mint one) is a
620        // fresh outer event, but the persist dedups on the inner id — no re-fire.
621        let (rewrap, _) = chat::seal_chat_rumor(&rumor, &group, &member, Timestamp::from_secs(6), false).unwrap();
622        assert_ne!(rewrap.id, wrap.id, "a re-wrap is a distinct outer event");
623        let DispatchedV2::Chat { event: dup, .. } = dispatch_wrap(&rewrap, &community, &me.public_key(), &rec) else {
624            panic!("the re-wrap still opens");
625        };
626        assert!(
627            persist_chat_event(&dup, &channel_id, &me.public_key(), &session).await.is_none(),
628            "a re-wrapped duplicate yields no outcome (nothing re-fires)"
629        );
630    }
631
632    #[tokio::test]
633    async fn a_guestbook_join_wrap_fires_presence() {
634        let (_tmp, _guard, me) = init();
635        let relay = MemoryRelay::new();
636        // create_community publishes the owner's genesis Join to the guestbook.
637        let community = service::create_community(&relay, "GB", vec!["wss://r".into()], None).await.unwrap();
638        let gb = super::super::derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch);
639        let q = crate::community::transport::Query { kinds: vec![stream::KIND_WRAP], authors: vec![gb.pk_hex()], ..Default::default() };
640        let wraps = relay.fetch(&q, &community.relays).await.unwrap();
641
642        let rec = Recorder::default();
643        for w in &wraps {
644            dispatch_wrap(w, &community, &me.public_key(), &rec);
645        }
646        let pres = rec.presence.lock().unwrap();
647        assert_eq!(pres.len(), 1, "the owner's genesis Join fires one presence");
648        assert!(pres[0].1, "it's a join");
649        assert_eq!(pres[0].0, me.public_key().to_bech32().unwrap());
650    }
651
652    #[tokio::test]
653    async fn v2_chat_events_persist_into_the_shared_store() {
654        let (_tmp, _guard, me) = init();
655        let relay = MemoryRelay::new();
656        let community = service::create_community(&relay, "Persist", vec!["wss://r".into()], None).await.unwrap();
657        let general = community.channels[0].id;
658        let cid = crate::simd::hex::bytes_to_hex_32(&general.0);
659        let group = super::super::derive::channel_group_key(&community.community_root, &general, community.root_epoch);
660        let me_hex = me.public_key().to_hex();
661
662        let msg_id = service::send_message(&relay, &community, &general, "persist me").await.unwrap();
663        service::send_reaction(&relay, &community, &general, &msg_id, &me_hex, super::super::kind::MESSAGE, "🔥", None).await.unwrap();
664
665        // The SEND ECHO persisted both immediately — send-then-read works with no
666        // listen loop (the INT-W3 contract).
667        assert!(crate::db::events::event_exists(&msg_id).unwrap(), "the send echo persisted the message row");
668        let reacted = {
669            let st = crate::state::STATE.lock().await;
670            st.find_message(&msg_id).map(|(_, m)| m.reactions.iter().any(|r| r.emoji == "🔥")).unwrap_or(false)
671        };
672        assert!(reacted, "the send echo aggregated the reaction onto the stored message");
673
674        // The relay's copies of our own sends then arrive — every one dedups
675        // against the echoed rows (no double rows, no re-fires).
676        let q = crate::community::transport::Query { kinds: vec![stream::KIND_WRAP], authors: vec![group.pk_hex()], ..Default::default() };
677        let wraps = relay.fetch(&q, &community.relays).await.unwrap();
678        let mut events: Vec<ChatEvent> = wraps.iter().filter_map(|w| chat::open_chat_event(w, &group, &general, community.root_epoch).ok()).collect();
679        events.sort_by_key(|e| e.opened().at_ms);
680        assert!(!events.is_empty());
681        for ev in &events {
682            let outcome = {
683                let mut st = crate::state::STATE.lock().await;
684                apply_chat_to_state(&mut st, ev, &cid, &me.public_key())
685            };
686            assert!(outcome.is_none(), "the relay echo of an already-echoed send dedups");
687        }
688    }
689
690    #[tokio::test]
691    async fn a_v2_edit_persists_as_a_folded_edit_event() {
692        let (_tmp, _guard, me) = init();
693        let relay = MemoryRelay::new();
694        let community = service::create_community(&relay, "Edit", vec!["wss://r".into()], None).await.unwrap();
695        let general = community.channels[0].id;
696        let cid = crate::simd::hex::bytes_to_hex_32(&general.0);
697        let group = super::super::derive::channel_group_key(&community.community_root, &general, community.root_epoch);
698
699        let msg_id = service::send_message(&relay, &community, &general, "original").await.unwrap();
700        service::send_edit(&relay, &community, &general, &msg_id, "edited!").await.unwrap();
701
702        // Apply messages BEFORE their edits (a target must be resident to edit).
703        let q = crate::community::transport::Query { kinds: vec![stream::KIND_WRAP], authors: vec![group.pk_hex()], ..Default::default() };
704        let wraps = relay.fetch(&q, &community.relays).await.unwrap();
705        let mut events: Vec<ChatEvent> = wraps.iter().filter_map(|w| chat::open_chat_event(w, &group, &general, community.root_epoch).ok()).collect();
706        events.sort_by_key(|e| (!matches!(e, ChatEvent::Message { .. }), e.opened().at_ms));
707        for ev in &events {
708            let outcome = {
709                let mut st = crate::state::STATE.lock().await;
710                apply_chat_to_state(&mut st, ev, &cid, &me.public_key())
711            };
712            if let Some(o) = outcome {
713                persist_chat(&cid, &o).await;
714            }
715        }
716
717        let content = {
718            let st = crate::state::STATE.lock().await;
719            st.find_message(&msg_id).map(|(_, m)| m.content)
720        };
721        assert_eq!(content.as_deref(), Some("edited!"), "the edit applied to the stored message");
722        let edit_id = events.iter().find_map(|e| matches!(e, ChatEvent::Edit { .. }).then(|| e.opened().rumor_id.to_hex())).unwrap();
723        assert!(crate::db::events::event_exists(&edit_id).unwrap(), "the MESSAGE_EDIT event is persisted (folds on reload)");
724    }
725
726    #[tokio::test]
727    async fn a_reaction_after_a_rekey_aggregates_onto_a_prior_epoch_message() {
728        // Sync stability across a rekey: a message written at epoch 0 and a reaction
729        // to it written at epoch 1 (its wrap sealed + bound under the NEW epoch key)
730        // must still aggregate — STATE keys by rumor id, not epoch, so a reaction to
731        // pre-refound history lands. The reaction's OWN binding is epoch 1; the
732        // target's is epoch 0.
733        use nostr_sdk::prelude::Timestamp;
734        let (_tmp, _guard, me) = init();
735        let relay = MemoryRelay::new();
736        let community = service::create_community(&relay, "Rekeyed", vec!["wss://r".into()], None).await.unwrap();
737        let general = community.channels[0].id;
738        let cid = crate::simd::hex::bytes_to_hex_32(&general.0);
739        let session = crate::state::SessionGuard::capture();
740
741        // Epoch-0 message, opened under the epoch-0 public key, persisted.
742        let member = Keys::generate();
743        let g0 = super::super::derive::channel_group_key(&community.community_root, &general, community.root_epoch);
744        let msg = chat::build_message_rumor(member.public_key(), &general, community.root_epoch, "before the rekey", None, &[], vec![], 5_000);
745        let msg_id = msg.id.unwrap().to_hex();
746        let (mw, _) = chat::seal_chat_rumor(&msg, &g0, &member, Timestamp::from_secs(5), false).unwrap();
747        let ev = chat::open_chat_event(&mw, &g0, &general, community.root_epoch).unwrap();
748        assert!(matches!(persist_chat_event(&ev, &cid, &me.public_key(), &session).await, Some(ChatPersist::New(_))));
749
750        // Epoch-1 reaction (same root, next epoch → a distinct channel key) to that
751        // epoch-0 message, opened under the epoch-1 key.
752        let next = crate::community::Epoch(community.root_epoch.0 + 1);
753        let g1 = super::super::derive::channel_group_key(&community.community_root, &general, next);
754        let reaction = chat::build_reaction_rumor(member.public_key(), &general, next, &msg_id, &member.public_key().to_hex(), super::super::kind::MESSAGE, "🎉", None, 6_000);
755        let (rw, _) = chat::seal_chat_rumor(&reaction, &g1, &member, Timestamp::from_secs(6), false).unwrap();
756        let rev = chat::open_chat_event(&rw, &g1, &general, next).unwrap();
757        let outcome = persist_chat_event(&rev, &cid, &me.public_key(), &session).await;
758        assert!(matches!(outcome, Some(ChatPersist::Updated { .. })), "the cross-epoch reaction updates the target");
759
760        let reaction_author = {
761            let st = crate::state::STATE.lock().await;
762            st.find_message(&msg_id)
763                .and_then(|(_, m)| m.reactions.iter().find(|r| r.emoji == "🎉").map(|r| r.author_id.clone()))
764        };
765        let author = reaction_author.expect("the epoch-1 reaction aggregated onto the epoch-0 message");
766        // npub, never hex: the frontend resolves the reactor's profile and detects
767        // "my reaction" by comparing against the user's npub.
768        assert_eq!(author, member.public_key().to_bech32().unwrap(), "reaction author is stored as bech32");
769    }
770
771    #[tokio::test]
772    async fn an_un_react_removes_the_reaction_for_receivers_and_only_for_its_reactor() {
773        use nostr_sdk::prelude::Timestamp;
774        let (_tmp, _guard, me) = init();
775        let relay = MemoryRelay::new();
776        let community = service::create_community(&relay, "UnReact", vec!["wss://r".into()], None).await.unwrap();
777        let general = community.channels[0].id;
778        let cid = crate::simd::hex::bytes_to_hex_32(&general.0);
779        let session = crate::state::SessionGuard::capture();
780        let (secret, epoch) = community.channel_secret(&community.channels[0]);
781        let group = super::super::derive::channel_group_key(&secret, &general, epoch);
782
783        // A message, then the member's reaction to it.
784        let member = Keys::generate();
785        let msg = chat::build_message_rumor(member.public_key(), &general, epoch, "react to me", None, &[], vec![], 5_000);
786        let msg_id = msg.id.unwrap().to_hex();
787        let (mw, _) = chat::seal_chat_rumor(&msg, &group, &member, Timestamp::from_secs(5), false).unwrap();
788        let ev = chat::open_chat_event(&mw, &group, &general, epoch).unwrap();
789        assert!(matches!(persist_chat_event(&ev, &cid, &me.public_key(), &session).await, Some(ChatPersist::New(_))));
790
791        let reaction = chat::build_reaction_rumor(member.public_key(), &general, epoch, &msg_id, &member.public_key().to_hex(), super::super::kind::MESSAGE, "🔥", None, 6_000);
792        let reaction_id = reaction.id.unwrap().to_hex();
793        let (rw, _) = chat::seal_chat_rumor(&reaction, &group, &member, Timestamp::from_secs(6), false).unwrap();
794        let rev = chat::open_chat_event(&rw, &group, &general, epoch).unwrap();
795        assert!(matches!(persist_chat_event(&rev, &cid, &me.public_key(), &session).await, Some(ChatPersist::Updated { .. })));
796
797        // A NON-reactor's delete targeting the reaction is dropped outright.
798        let outsider = Keys::generate();
799        let forged = chat::build_delete_rumor(outsider.public_key(), &general, epoch, &reaction_id, super::super::kind::MESSAGE, 7_000, None);
800        let (fw, _) = chat::seal_chat_rumor(&forged, &group, &outsider, Timestamp::from_secs(7), false).unwrap();
801        let fev = chat::open_chat_event(&fw, &group, &general, epoch).unwrap();
802        assert!(persist_chat_event(&fev, &cid, &me.public_key(), &session).await.is_none(), "only the reactor revokes their reaction");
803
804        // The REACTOR's delete removes it: STATE chip gone, kind-7 row gone
805        // (a lingering row would resurrect the chip on the next load), parent intact.
806        let revoke = chat::build_delete_rumor(member.public_key(), &general, epoch, &reaction_id, super::super::kind::MESSAGE, 8_000, None);
807        let (vw, _) = chat::seal_chat_rumor(&revoke, &group, &member, Timestamp::from_secs(8), false).unwrap();
808        let vev = chat::open_chat_event(&vw, &group, &general, epoch).unwrap();
809        assert!(matches!(persist_chat_event(&vev, &cid, &me.public_key(), &session).await, Some(ChatPersist::ReactionRemoved { .. })));
810        let (has_reaction, parent_alive) = {
811            let st = crate::state::STATE.lock().await;
812            (
813                st.find_reaction(&reaction_id).is_some(),
814                st.find_message(&msg_id).is_some(),
815            )
816        };
817        assert!(!has_reaction, "the chip is gone from STATE");
818        assert!(parent_alive, "the parent message survives an un-react");
819        assert!(!crate::db::events::event_exists(&reaction_id).unwrap(), "the kind-7 row is deleted");
820    }
821
822    #[tokio::test]
823    async fn a_guestbook_join_fires_presence_with_its_real_rumor_id() {
824        use nostr_sdk::prelude::Timestamp;
825        use std::sync::Mutex as StdMutex;
826        let (_tmp, _guard, me) = init();
827        let relay = MemoryRelay::new();
828        let community = service::create_community(&relay, "Pres", vec!["wss://r".into()], None).await.unwrap();
829
830        #[derive(Default)]
831        struct Capture(StdMutex<Vec<(String, bool, String)>>);
832        impl InboundEventHandler for Capture {
833            fn on_community_presence(&self, _chat_id: &str, npub: &str, joined: bool, event_id: &str, _at: u64, _by: Option<&str>, _label: Option<&str>) {
834                self.0.lock().unwrap().push((npub.into(), joined, event_id.into()));
835            }
836        }
837
838        let member = Keys::generate();
839        let gb = super::super::derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch);
840        let rumor = guestbook::build_join_rumor(member.public_key(), None, 5_000);
841        let (wrap, _) = super::super::guestbook::seal_guestbook_rumor(&rumor, &gb, &member, Timestamp::from_secs(5)).unwrap();
842        let expected_id = rumor.id.unwrap().to_hex();
843
844        let cap = Capture::default();
845        let out = dispatch_wrap(&wrap, &community, &me.public_key(), &cap);
846        assert!(matches!(out, DispatchedV2::Presence { joined: true, .. }));
847        let seen = cap.0.lock().unwrap().clone();
848        assert_eq!(seen.len(), 1);
849        assert_eq!(seen[0].0, member.public_key().to_bech32().unwrap());
850        // The REAL rumor id keys the line — an empty id would collapse every
851        // distinct join into one dedup slot (first wins, the rest vanish).
852        assert_eq!(seen[0].2, expected_id, "presence carries the join's own rumor id");
853    }
854
855    #[tokio::test]
856    async fn a_guestbook_kick_dispatches_its_target_and_raises_no_presence_line() {
857        // Routing regression: a Kick used to fall to `Ignored`, so realtime dropped it
858        // and the target never left anyone's memberlist (nor their own community).
859        use nostr_sdk::prelude::Timestamp;
860        use std::sync::Mutex as StdMutex;
861        let (_tmp, _guard, me) = init();
862        let relay = MemoryRelay::new();
863        let community = service::create_community(&relay, "Kicks", vec!["wss://r".into()], None).await.unwrap();
864
865        #[derive(Default)]
866        struct Capture(StdMutex<usize>);
867        impl InboundEventHandler for Capture {
868            fn on_community_presence(&self, _c: &str, _n: &str, _j: bool, _e: &str, _a: u64, _b: Option<&str>, _l: Option<&str>) {
869                *self.0.lock().unwrap() += 1;
870            }
871        }
872
873        let target = Keys::generate();
874        let gb = super::super::derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch);
875        let rumor = guestbook::build_kick_rumor(me.public_key(), target.public_key(), None, 5_000);
876        let (wrap, _) = super::super::guestbook::seal_guestbook_rumor(&rumor, &gb, &me, Timestamp::from_secs(5)).unwrap();
877
878        let cap = Capture::default();
879        let out = dispatch_wrap(&wrap, &community, &me.public_key(), &cap);
880        match out {
881            DispatchedV2::Kick { target: t } => assert_eq!(t, target.public_key(), "the kick names its target"),
882            other => panic!("a Kick must reach the store, got {other:?}"),
883        }
884        // A kick shapes the memberlist, not the feed.
885        assert_eq!(*cap.0.lock().unwrap(), 0, "a kick raises no presence line");
886    }
887
888    #[tokio::test]
889    async fn a_webxdc_peer_ad_fires_the_shared_handler_and_own_echo_drops() {
890        use nostr_sdk::prelude::Timestamp;
891        use std::sync::Mutex as StdMutex;
892        let (_tmp, _guard, me) = init();
893        let relay = MemoryRelay::new();
894        let community = service::create_community(&relay, "XDC", vec!["wss://r".into()], None).await.unwrap();
895        let general = community.channels[0].id;
896
897        #[derive(Default)]
898        struct Capture(StdMutex<Vec<(String, String, Option<String>)>>);
899        impl InboundEventHandler for Capture {
900            fn on_community_webxdc(&self, _chat_id: &str, npub: &str, topic_id: &str, node_addr: Option<&str>, _event_id: &str, _created_at: u64) {
901                self.0.lock().unwrap().push((npub.into(), topic_id.into(), node_addr.map(String::from)));
902            }
903        }
904
905        let topic = "B".repeat(52);
906        let content = crate::webxdc::peer_signal_content(&topic, Some("iroh:node/xyz"));
907        let (secret, epoch) = community.channel_secret(&community.channels[0]);
908        let group = super::super::derive::channel_group_key(&secret, &general, epoch);
909
910        // A PEER's ad fires the shared v1 handler surface.
911        let peer = Keys::generate();
912        let rumor = chat::build_webxdc_rumor(peer.public_key(), &general, epoch, &content, vec![], 5_000);
913        let (wrap, _) = chat::seal_chat_rumor(&rumor, &group, &peer, Timestamp::from_secs(5), false).unwrap();
914        let cap = Capture::default();
915        let out = dispatch_wrap(&wrap, &community, &me.public_key(), &cap);
916        assert!(matches!(out, DispatchedV2::Ignored), "fired inline, nothing to persist v2-side");
917        let seen = cap.0.lock().unwrap().clone();
918        assert_eq!(seen.len(), 1);
919        assert_eq!(seen[0].0, peer.public_key().to_bech32().unwrap());
920        assert_eq!(seen[0].1, topic);
921        assert_eq!(seen[0].2.as_deref(), Some("iroh:node/xyz"));
922
923        // Our OWN echo never re-fires — the local realtime layer tracks itself.
924        let own = chat::build_webxdc_rumor(me.public_key(), &general, epoch, &content, vec![], 6_000);
925        let (own_wrap, _) = chat::seal_chat_rumor(&own, &group, &me, Timestamp::from_secs(6), false).unwrap();
926        let cap2 = Capture::default();
927        dispatch_wrap(&own_wrap, &community, &me.public_key(), &cap2);
928        assert!(cap2.0.lock().unwrap().is_empty(), "own-device echo drops");
929    }
930
931    #[tokio::test]
932    async fn a_v2_message_with_an_imeta_attachment_surfaces_as_an_attachment() {
933        use nostr_sdk::prelude::Timestamp;
934        let (_tmp, _guard, me) = init();
935        let relay = MemoryRelay::new();
936        let community = service::create_community(&relay, "Files", vec!["wss://r".into()], None).await.unwrap();
937        let general = community.channels[0].id;
938        let cid = crate::simd::hex::bytes_to_hex_32(&general.0);
939        let group = super::super::derive::channel_group_key(&community.community_root, &general, community.root_epoch);
940        let session = crate::state::SessionGuard::capture();
941
942        // Build a valid NIP-92 imeta tag via the same encoder the v2 file pipeline
943        // uses, so the round-trip mirrors production exactly.
944        let attachment = crate::types::Attachment {
945            id: "a".repeat(64),
946            key: "0".repeat(64),
947            nonce: "1".repeat(32),
948            extension: "png".into(),
949            name: "photo.png".into(),
950            url: "https://blossom.example/abc".into(),
951            path: String::new(),
952            size: 4096,
953            img_meta: None,
954            downloading: false,
955            downloaded: false,
956            webxdc_topic: None,
957            group_id: None,
958            original_hash: Some("b".repeat(64)),
959            fallback_urls: Vec::new(),
960        };
961        let imeta = crate::community::attachments::attachment_to_imeta(&attachment);
962        let member = Keys::generate();
963        let rumor = chat::build_message_rumor(member.public_key(), &general, community.root_epoch, "here's a file", None, &[], vec![imeta], 5_000);
964        let (wrap, _) = chat::seal_chat_rumor(&rumor, &group, &member, Timestamp::from_secs(5), false).unwrap();
965        let ev = chat::open_chat_event(&wrap, &group, &general, community.root_epoch).unwrap();
966
967        let outcome = persist_chat_event(&ev, &cid, &me.public_key(), &session).await;
968        let Some(ChatPersist::New(msg)) = outcome else {
969            panic!("the file message persists as new");
970        };
971        assert_eq!(msg.attachments.len(), 1, "the imeta tag parsed into one attachment");
972        let att = &msg.attachments[0];
973        assert!(att.url.contains("blossom.example"), "attachment url carried through: {}", att.url);
974        assert_eq!(att.extension, "png", "extension carried through");
975    }
976
977    #[tokio::test]
978    async fn a_banned_members_every_chat_event_is_dropped_on_sight() {
979        // CORD-04 §4: a banned npub vanishes — message, reaction, edit, delete,
980        // typing, and presence alike. Severance only cuts their READ; this fold
981        // gate is what makes the ban hold against old-epoch keys they still have.
982        use nostr_sdk::prelude::Timestamp;
983        let (_tmp, _guard, me) = init();
984        let relay = MemoryRelay::new();
985        let community = service::create_community(&relay, "BanGate", vec!["wss://r".into()], None).await.unwrap();
986        let general = community.channels[0].id;
987        let cid = crate::simd::hex::bytes_to_hex_32(&general.0);
988        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
989        let group = super::super::derive::channel_group_key(&community.community_root, &general, community.root_epoch);
990        let session = crate::state::SessionGuard::capture();
991        let rogue = Keys::generate();
992
993        // Pre-ban: the rogue's message folds like anyone's.
994        let m1 = chat::build_message_rumor(rogue.public_key(), &general, community.root_epoch, "pre-ban", None, &[], vec![], 5_000);
995        let m1_id = m1.id.unwrap().to_hex();
996        let (w1, _) = chat::seal_chat_rumor(&m1, &group, &rogue, Timestamp::from_secs(5), false).unwrap();
997        let ev = chat::open_chat_event(&w1, &group, &general, community.root_epoch).unwrap();
998        assert!(matches!(persist_chat_event(&ev, &cid, &me.public_key(), &session).await, Some(ChatPersist::New(_))));
999
1000        // The ban lands (the fold's persisted banlist).
1001        crate::db::community::set_community_banlist(&cid_hex, &[rogue.public_key().to_hex()], 1_000).unwrap();
1002
1003        // Post-ban: every kind they author drops.
1004        let m2 = chat::build_message_rumor(rogue.public_key(), &general, community.root_epoch, "post-ban", None, &[], vec![], 6_000);
1005        let (w2, _) = chat::seal_chat_rumor(&m2, &group, &rogue, Timestamp::from_secs(6), false).unwrap();
1006        let ev = chat::open_chat_event(&w2, &group, &general, community.root_epoch).unwrap();
1007        assert!(persist_chat_event(&ev, &cid, &me.public_key(), &session).await.is_none(), "a banned message is dropped");
1008
1009        let edit = chat::build_edit_rumor(rogue.public_key(), &general, community.root_epoch, &m1_id, "rewritten", 7_000);
1010        let (we, _) = chat::seal_chat_rumor(&edit, &group, &rogue, Timestamp::from_secs(7), false).unwrap();
1011        let ev = chat::open_chat_event(&we, &group, &general, community.root_epoch).unwrap();
1012        assert!(persist_chat_event(&ev, &cid, &me.public_key(), &session).await.is_none(), "a banned edit is dropped");
1013
1014        let del = chat::build_delete_rumor(rogue.public_key(), &general, community.root_epoch, &m1_id, super::super::kind::MESSAGE, 8_000, None);
1015        let (wd, _) = chat::seal_chat_rumor(&del, &group, &rogue, Timestamp::from_secs(8), false).unwrap();
1016        let ev = chat::open_chat_event(&wd, &group, &general, community.root_epoch).unwrap();
1017        assert!(persist_chat_event(&ev, &cid, &me.public_key(), &session).await.is_none(), "a banned delete is dropped");
1018        assert!(
1019            crate::state::STATE.lock().await.find_message(&m1_id).is_some(),
1020            "their pre-ban message survives their own post-ban delete"
1021        );
1022
1023        // Typing + presence fire inline — the dispatcher's own gate covers them.
1024        let rec = Recorder::default();
1025        let typ = chat::build_typing_rumor(rogue.public_key(), &general, community.root_epoch, 9_000);
1026        let (wt, _) = chat::seal_chat_rumor(&typ, &group, &rogue, Timestamp::from_secs(9), true).unwrap();
1027        assert!(matches!(dispatch_wrap(&wt, &community, &me.public_key(), &rec), DispatchedV2::Ignored));
1028        // A banned member's Join draws no presence line but still dispatches for
1029        // STORAGE: the fold subtracts the banlist reversibly, so an unban can
1030        // resurrect a Join that legally raced the ban window — a store-side drop
1031        // would eat it forever.
1032        let gb = super::super::derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch);
1033        let join = guestbook::build_join_rumor(rogue.public_key(), None, 10_000);
1034        let (wj, _) = guestbook::seal_guestbook_rumor(&join, &gb, &rogue, Timestamp::from_secs(10)).unwrap();
1035        assert!(matches!(dispatch_wrap(&wj, &community, &me.public_key(), &rec), DispatchedV2::Presence { joined: true, .. }));
1036        assert!(rec.presence.lock().unwrap().is_empty(), "no presence callback for a banned join");
1037
1038        // An innocent author still folds normally.
1039        let innocent = Keys::generate();
1040        let m3 = chat::build_message_rumor(innocent.public_key(), &general, community.root_epoch, "innocent", None, &[], vec![], 11_000);
1041        let (w3, _) = chat::seal_chat_rumor(&m3, &group, &innocent, Timestamp::from_secs(11), false).unwrap();
1042        let ev = chat::open_chat_event(&w3, &group, &general, community.root_epoch).unwrap();
1043        assert!(matches!(persist_chat_event(&ev, &cid, &me.public_key(), &session).await, Some(ChatPersist::New(_))));
1044    }
1045
1046    #[tokio::test]
1047    async fn an_armada_threaded_reply_persists_and_fires_as_an_inline_reply() {
1048        use nostr_sdk::prelude::Timestamp;
1049        let (_tmp, _guard, me) = init();
1050        let relay = MemoryRelay::new();
1051        let community = service::create_community(&relay, "Thread", vec!["wss://r".into()], None).await.unwrap();
1052        let general = community.channels[0].id;
1053        let cid = crate::simd::hex::bytes_to_hex_32(&general.0);
1054        let group = super::super::derive::channel_group_key(&community.community_root, &general, community.root_epoch);
1055        let session = crate::state::SessionGuard::capture();
1056
1057        // A member posts a root message, then a kind-1111 threaded reply to it
1058        // (the shape Armada sends).
1059        let member = Keys::generate();
1060        let root = chat::build_message_rumor(member.public_key(), &general, community.root_epoch, "thread root", None, &[], vec![], 5_000);
1061        let root_id = root.id.unwrap().to_hex();
1062        let (rw, _) = chat::seal_chat_rumor(&root, &group, &member, Timestamp::from_secs(5), false).unwrap();
1063        let reply = chat::build_comment_rumor(
1064            member.public_key(),
1065            &general,
1066            community.root_epoch,
1067            "thread reply",
1068            &root_id,
1069            super::super::kind::MESSAGE,
1070            &member.public_key().to_hex(),
1071            None,
1072            &[],
1073            6_000,
1074        );
1075        let reply_id = reply.id.unwrap().to_hex();
1076        let (tw, _) = chat::seal_chat_rumor(&reply, &group, &member, Timestamp::from_secs(6), false).unwrap();
1077
1078        for w in [&rw, &tw] {
1079            let ev = chat::open_chat_event(w, &group, &general, community.root_epoch).unwrap();
1080            let outcome = persist_chat_event(&ev, &cid, &me.public_key(), &session).await;
1081            assert!(matches!(outcome, Some(ChatPersist::New(_))), "both persist as new messages");
1082        }
1083        // The reply row carries its parent as inline reply context, resolved
1084        // from the persisted root (v1's reply-preview parity).
1085        let held = {
1086            let st = crate::state::STATE.lock().await;
1087            st.find_message(&reply_id).map(|(_, m)| m)
1088        }
1089        .expect("the threaded reply is resident");
1090        assert_eq!(held.replied_to, root_id, "the immediate parent is the reply context");
1091        assert_eq!(held.content, "thread reply");
1092
1093        // Its author deletes it — target kind 1111 (the delete e/k grammar).
1094        let del = chat::build_delete_rumor(member.public_key(), &general, community.root_epoch, &reply_id, super::super::kind::COMMENT, 7_000, None);
1095        let (dw, _) = chat::seal_chat_rumor(&del, &group, &member, Timestamp::from_secs(7), false).unwrap();
1096        let ev = chat::open_chat_event(&dw, &group, &general, community.root_epoch).unwrap();
1097        let outcome = persist_chat_event(&ev, &cid, &me.public_key(), &session).await;
1098        assert!(matches!(outcome, Some(ChatPersist::Removed(id)) if id == reply_id), "the author's delete removes their thread reply");
1099    }
1100
1101    #[tokio::test]
1102    async fn an_edit_replay_never_refires() {
1103        use nostr_sdk::prelude::Timestamp;
1104        let (_tmp, _guard, me) = init();
1105        let relay = MemoryRelay::new();
1106        let community = service::create_community(&relay, "EditReplay", vec!["wss://r".into()], None).await.unwrap();
1107        let general = community.channels[0].id;
1108        let cid = crate::simd::hex::bytes_to_hex_32(&general.0);
1109        let group = super::super::derive::channel_group_key(&community.community_root, &general, community.root_epoch);
1110        let session = crate::state::SessionGuard::capture();
1111
1112        // Another member posts, then edits their own message.
1113        let member = Keys::generate();
1114        let msg = chat::build_message_rumor(member.public_key(), &general, community.root_epoch, "v1 text", None, &[], vec![], 5_000);
1115        let msg_id = msg.id.unwrap().to_hex();
1116        let (mw, _) = chat::seal_chat_rumor(&msg, &group, &member, Timestamp::from_secs(5), false).unwrap();
1117        let edit = chat::build_edit_rumor(member.public_key(), &general, community.root_epoch, &msg_id, "v2 text", 6_000);
1118        let (ew, _) = chat::seal_chat_rumor(&edit, &group, &member, Timestamp::from_secs(6), false).unwrap();
1119        for w in [&mw, &ew] {
1120            if let Ok(ev) = chat::open_chat_event(w, &group, &general, community.root_epoch) {
1121                let _ = persist_chat_event(&ev, &cid, &me.public_key(), &session).await;
1122            }
1123        }
1124
1125        // A RE-WRAP of the same signed EDIT (fresh outer id) must not re-fire: the
1126        // MESSAGE_EDIT row dedups it, exactly like the other three chat kinds.
1127        let (replay, _) = chat::seal_chat_rumor(&edit, &group, &member, Timestamp::from_secs(7), false).unwrap();
1128        assert_ne!(replay.id, ew.id, "a re-wrap is a distinct outer event");
1129        let ev = chat::open_chat_event(&replay, &group, &general, community.root_epoch).unwrap();
1130        assert!(
1131            persist_chat_event(&ev, &cid, &me.public_key(), &session).await.is_none(),
1132            "a replayed edit yields no outcome (no handler re-fire)"
1133        );
1134    }
1135
1136    #[tokio::test]
1137    async fn a_forged_edit_from_a_non_author_is_ignored() {
1138        // Author-scoping on edits (the counterpart to the forged-delete guard): a
1139        // member (holds the channel key) forges an EDIT of someone else's message.
1140        // It must not rewrite the content.
1141        use nostr_sdk::prelude::Timestamp;
1142        let (_tmp, _guard, me) = init();
1143        let relay = MemoryRelay::new();
1144        let community = service::create_community(&relay, "EditGuard", vec!["wss://r".into()], None).await.unwrap();
1145        let general = community.channels[0].id;
1146        let cid = crate::simd::hex::bytes_to_hex_32(&general.0);
1147        let group = super::super::derive::channel_group_key(&community.community_root, &general, community.root_epoch);
1148        let session = crate::state::SessionGuard::capture();
1149
1150        // The real author posts a message.
1151        let author = Keys::generate();
1152        let msg = chat::build_message_rumor(author.public_key(), &general, community.root_epoch, "original", None, &[], vec![], 5_000);
1153        let msg_id = msg.id.unwrap().to_hex();
1154        let (mw, _) = chat::seal_chat_rumor(&msg, &group, &author, Timestamp::from_secs(5), false).unwrap();
1155        let ev = chat::open_chat_event(&mw, &group, &general, community.root_epoch).unwrap();
1156        persist_chat_event(&ev, &cid, &me.public_key(), &session).await;
1157
1158        // A stranger (member, holds the key) forges an edit of the author's message.
1159        let stranger = Keys::generate();
1160        let edit = chat::build_edit_rumor(stranger.public_key(), &general, community.root_epoch, &msg_id, "TAMPERED", 6_000);
1161        let (ew, _) = chat::seal_chat_rumor(&edit, &group, &stranger, Timestamp::from_secs(6), false).unwrap();
1162        let ev = chat::open_chat_event(&ew, &group, &general, community.root_epoch).unwrap();
1163        assert!(persist_chat_event(&ev, &cid, &me.public_key(), &session).await.is_none(), "a forged edit yields no outcome");
1164
1165        let content = {
1166            let st = crate::state::STATE.lock().await;
1167            st.find_message(&msg_id).map(|(_, m)| m.content)
1168        };
1169        assert_eq!(content.as_deref(), Some("original"), "the message content is unchanged by the forged edit");
1170    }
1171
1172    #[tokio::test]
1173    async fn a_reaction_cannot_be_injected_across_channels() {
1174        // A member holds BOTH channels' keys, so they can seal a valid reaction in
1175        // channel A whose target is a message resident in channel B. The
1176        // cross-channel guard (a reaction lands only on a same-channel target) must
1177        // drop it — else reactions could be injected onto messages in channels the
1178        // reaction was never sealed under.
1179        use nostr_sdk::prelude::Timestamp;
1180        let (_tmp, _guard, me) = init();
1181        let relay = MemoryRelay::new();
1182        let mut community = service::create_community(&relay, "TwoChan", vec!["wss://r".into()], None).await.unwrap();
1183        let chan_a = community.channels[0].id;
1184        let chan_b = service::create_public_channel(&relay, &community, "b").await.unwrap();
1185        community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
1186        let a_hex = crate::simd::hex::bytes_to_hex_32(&chan_a.0);
1187        let session = crate::state::SessionGuard::capture();
1188
1189        // A message lives in channel B.
1190        let author = Keys::generate();
1191        let gb = super::super::derive::channel_group_key(&community.community_root, &chan_b, community.root_epoch);
1192        let msg = chat::build_message_rumor(author.public_key(), &chan_b, community.root_epoch, "in B", None, &[], vec![], 5_000);
1193        let msg_id = msg.id.unwrap().to_hex();
1194        let (mw, _) = chat::seal_chat_rumor(&msg, &gb, &author, Timestamp::from_secs(5), false).unwrap();
1195        let bev = chat::open_chat_event(&mw, &gb, &chan_b, community.root_epoch).unwrap();
1196        persist_chat_event(&bev, &crate::simd::hex::bytes_to_hex_32(&chan_b.0), &me.public_key(), &session).await;
1197
1198        // A reaction sealed in channel A, targeting the channel-B message.
1199        let ga = super::super::derive::channel_group_key(&community.community_root, &chan_a, community.root_epoch);
1200        let reaction = chat::build_reaction_rumor(author.public_key(), &chan_a, community.root_epoch, &msg_id, &author.public_key().to_hex(), super::super::kind::MESSAGE, "💥", None, 6_000);
1201        let (rw, _) = chat::seal_chat_rumor(&reaction, &ga, &author, Timestamp::from_secs(6), false).unwrap();
1202        let aev = chat::open_chat_event(&rw, &ga, &chan_a, community.root_epoch).unwrap();
1203        // Applied under channel A (where it was sealed) — the target is in B.
1204        let outcome = persist_chat_event(&aev, &a_hex, &me.public_key(), &session).await;
1205        assert!(outcome.is_none(), "a cross-channel reaction is dropped");
1206        let reacted = {
1207            let st = crate::state::STATE.lock().await;
1208            st.find_message(&msg_id).map(|(_, m)| !m.reactions.is_empty()).unwrap_or(false)
1209        };
1210        assert!(!reacted, "the channel-B message gained no reaction from the channel-A injection");
1211    }
1212
1213    #[tokio::test]
1214    async fn a_forged_delete_from_a_non_author_is_ignored() {
1215        use nostr_sdk::prelude::Timestamp;
1216        let (_tmp, _guard, me) = init();
1217        let relay = MemoryRelay::new();
1218        let community = service::create_community(&relay, "Forge", vec!["wss://r".into()], None).await.unwrap();
1219        let general = community.channels[0].id;
1220        let cid = crate::simd::hex::bytes_to_hex_32(&general.0);
1221        let group = super::super::derive::channel_group_key(&community.community_root, &general, community.root_epoch);
1222
1223        // `me` posts a message and it's persisted into STATE.
1224        let msg_id = service::send_message(&relay, &community, &general, "mine").await.unwrap();
1225        let q = crate::community::transport::Query { kinds: vec![stream::KIND_WRAP], authors: vec![group.pk_hex()], ..Default::default() };
1226        let wraps = relay.fetch(&q, &community.relays).await.unwrap();
1227        for w in &wraps {
1228            if let Ok(ev) = chat::open_chat_event(w, &group, &general, community.root_epoch) {
1229                let mut st = crate::state::STATE.lock().await;
1230                apply_chat_to_state(&mut st, &ev, &cid, &me.public_key());
1231            }
1232        }
1233
1234        // A STRANGER (a member, so holds the channel key) forges a delete of `me`'s message.
1235        let stranger = nostr_sdk::prelude::Keys::generate();
1236        let del = chat::build_delete_rumor(stranger.public_key(), &general, community.root_epoch, &msg_id, super::super::kind::MESSAGE, 9_000, None);
1237        let (wrap, _) = chat::seal_chat_rumor(&del, &group, &stranger, Timestamp::from_secs(9), false).unwrap();
1238        let event = chat::open_chat_event(&wrap, &group, &general, community.root_epoch).unwrap();
1239
1240        let outcome = {
1241            let mut st = crate::state::STATE.lock().await;
1242            apply_chat_to_state(&mut st, &event, &cid, &me.public_key())
1243        };
1244        assert!(outcome.is_none(), "a forged delete from a non-author yields no removal");
1245        let survives = {
1246            let st = crate::state::STATE.lock().await;
1247            st.find_message(&msg_id).is_some()
1248        };
1249        assert!(survives, "the message survives the forged delete (live view + DB stay consistent)");
1250    }
1251
1252    /// Owner + a granted admin + two posted messages, with the roster and the
1253    /// admin's Grant head persisted the way `follow_control` leaves them. Returns
1254    /// the pieces a moderation-delete test needs to seal one and judge it.
1255    struct ModerationBed {
1256        community: super::super::community::CommunityV2,
1257        general: crate::community::ChannelId,
1258        chat_id: String,
1259        group: super::super::derive::GroupKey,
1260        admin: Keys,
1261        admin_citation: crate::community::edition::AuthorityCitation,
1262    }
1263
1264    async fn moderation_bed(relay: &MemoryRelay, name: &str) -> ModerationBed {
1265        let community = service::create_community(relay, name, vec!["wss://r".into()], None).await.unwrap();
1266        let general = community.channels[0].id;
1267        let chat_id = crate::simd::hex::bytes_to_hex_32(&general.0);
1268        let group = super::super::derive::channel_group_key(&community.community_root, &general, community.root_epoch);
1269        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
1270
1271        let admin = Keys::generate();
1272        service::grant_admin(relay, &community, &admin.public_key()).await.unwrap();
1273
1274        // What `follow_control` persists after folding: the authorized roster, so
1275        // the receive path resolves ranks without a fetch.
1276        let view = service::fetch_authority(relay, &community).await;
1277        crate::db::community::set_community_roles(&cid_hex, &view.roles, 1_000).unwrap();
1278
1279        // The admin's `vac`: the Grant edition the owner just published for them.
1280        let entity_id = super::super::derive::grant_locator(community.id(), &admin.public_key().to_bytes());
1281        let entity_hex = crate::simd::hex::bytes_to_hex_32(&entity_id);
1282        let (version, edition_hash) = crate::db::community::get_edition_head(&cid_hex, &entity_hex)
1283            .unwrap()
1284            .expect("the owner's own grant publish stores its head");
1285        let admin_citation = crate::community::edition::AuthorityCitation { entity_id, version, edition_hash };
1286
1287        ModerationBed { community, general, chat_id, group, admin, admin_citation }
1288    }
1289
1290    /// Seal `author`'s message onto the chat plane and apply it, returning its rumor id.
1291    async fn post_as(bed: &ModerationBed, author: &Keys, body: &str, at: u64, me: &PublicKey) -> String {
1292        use nostr_sdk::prelude::Timestamp;
1293        let rumor = chat::build_message_rumor(author.public_key(), &bed.general, bed.community.root_epoch, body, None, &[], vec![], at);
1294        let (wrap, _) = chat::seal_chat_rumor(&rumor, &bed.group, author, Timestamp::from_secs(at / 1000), false).unwrap();
1295        let event = chat::open_chat_event(&wrap, &bed.group, &bed.general, bed.community.root_epoch).unwrap();
1296        let id = rumor.id.unwrap().to_hex();
1297        let mut st = crate::state::STATE.lock().await;
1298        apply_chat_to_state(&mut st, &event, &bed.chat_id, me);
1299        id
1300    }
1301
1302    /// Seal `actor`'s kind-5 against `target` and run it through the receive path.
1303    async fn delete_as(
1304        bed: &ModerationBed,
1305        actor: &Keys,
1306        target: &str,
1307        citation: Option<&crate::community::edition::AuthorityCitation>,
1308        at: u64,
1309        me: &PublicKey,
1310    ) -> Option<ChatPersist> {
1311        use nostr_sdk::prelude::Timestamp;
1312        let del = chat::build_delete_rumor(actor.public_key(), &bed.general, bed.community.root_epoch, target, super::super::kind::MESSAGE, at, citation);
1313        let (wrap, _) = chat::seal_chat_rumor(&del, &bed.group, actor, Timestamp::from_secs(at / 1000), false).unwrap();
1314        let event = chat::open_chat_event(&wrap, &bed.group, &bed.general, bed.community.root_epoch).unwrap();
1315        let mut st = crate::state::STATE.lock().await;
1316        apply_chat_to_state(&mut st, &event, &bed.chat_id, me)
1317    }
1318
1319    #[tokio::test]
1320    async fn an_admins_moderation_delete_removes_a_members_message() {
1321        let (_tmp, _guard, me) = init();
1322        let relay = MemoryRelay::new();
1323        let bed = moderation_bed(&relay, "Mod").await;
1324        let member = Keys::generate();
1325
1326        let victim = post_as(&bed, &member, "spam", 1_000, &me.public_key()).await;
1327        let outcome = delete_as(&bed, &bed.admin, &victim, Some(&bed.admin_citation), 2_000, &me.public_key()).await;
1328
1329        assert!(matches!(outcome, Some(ChatPersist::Removed(ref id)) if *id == victim), "MANAGE_MESSAGES + outrank removes it");
1330        assert!(crate::state::STATE.lock().await.find_message(&victim).is_none());
1331    }
1332
1333    #[tokio::test]
1334    async fn an_admin_cannot_moderation_delete_the_owners_message() {
1335        // The owner is position 0, supreme and never a valid target. This holds
1336        // only while the owner RESOLVES — an owner who needs no Role ranks last
1337        // without one.
1338        let (_tmp, _guard, me) = init();
1339        let relay = MemoryRelay::new();
1340        let bed = moderation_bed(&relay, "Sacred").await;
1341
1342        let owners_message = post_as(&bed, &me, "the owner speaks", 1_000, &me.public_key()).await;
1343        let outcome = delete_as(&bed, &bed.admin, &owners_message, Some(&bed.admin_citation), 2_000, &me.public_key()).await;
1344
1345        assert!(outcome.is_none(), "an admin never outranks the owner");
1346        assert!(crate::state::STATE.lock().await.find_message(&owners_message).is_some());
1347    }
1348
1349    #[tokio::test]
1350    async fn a_moderation_delete_without_a_synced_citation_is_refused() {
1351        // CORD-04 §5: a non-owner must name the Grant it acts under, and we must
1352        // hold it. Uncited, the actor's rank is unprovable — fail closed.
1353        let (_tmp, _guard, me) = init();
1354        let relay = MemoryRelay::new();
1355        let bed = moderation_bed(&relay, "Uncited").await;
1356        let member = Keys::generate();
1357
1358        let victim = post_as(&bed, &member, "spam", 1_000, &me.public_key()).await;
1359        assert!(delete_as(&bed, &bed.admin, &victim, None, 2_000, &me.public_key()).await.is_none());
1360        assert!(crate::state::STATE.lock().await.find_message(&victim).is_some());
1361
1362        // The same delete WITH its citation lands — proving the refusal above was
1363        // the citation and not the rank.
1364        assert!(delete_as(&bed, &bed.admin, &victim, Some(&bed.admin_citation), 3_000, &me.public_key()).await.is_some());
1365    }
1366
1367    #[tokio::test]
1368    async fn a_roleless_member_cannot_moderation_delete_anyone() {
1369        let (_tmp, _guard, me) = init();
1370        let relay = MemoryRelay::new();
1371        let bed = moderation_bed(&relay, "Roleless").await;
1372        let (member, rando) = (Keys::generate(), Keys::generate());
1373
1374        let victim = post_as(&bed, &member, "hello", 1_000, &me.public_key()).await;
1375        // A citation is no substitute for a grant: cite the ADMIN's entity while
1376        // holding nothing, and the roster check still refuses.
1377        let outcome = delete_as(&bed, &rando, &victim, Some(&bed.admin_citation), 2_000, &me.public_key()).await;
1378
1379        assert!(outcome.is_none(), "no MANAGE_MESSAGES, no removal");
1380        assert!(crate::state::STATE.lock().await.find_message(&victim).is_some());
1381    }
1382
1383    #[tokio::test]
1384    async fn a_member_still_deletes_their_own_message_uncited() {
1385        // The self-delete path must not acquire a citation requirement.
1386        let (_tmp, _guard, me) = init();
1387        let relay = MemoryRelay::new();
1388        let bed = moderation_bed(&relay, "Self").await;
1389        let member = Keys::generate();
1390
1391        let mine = post_as(&bed, &member, "oops", 1_000, &me.public_key()).await;
1392        let outcome = delete_as(&bed, &member, &mine, None, 2_000, &me.public_key()).await;
1393
1394        assert!(matches!(outcome, Some(ChatPersist::Removed(ref id)) if *id == mine));
1395    }
1396
1397    #[tokio::test]
1398    async fn a_foreign_wrap_is_not_ours() {
1399        let (_tmp, _guard, me) = init();
1400        let relay = MemoryRelay::new();
1401        let community = service::create_community(&relay, "X", vec!["wss://r".into()], None).await.unwrap();
1402
1403        // A wrap from an unrelated stream key (e.g. a DM giftwrap, or another
1404        // community) must not match any plane.
1405        let stranger = super::super::derive::channel_group_key(&[0x99u8; 32], &community.channels[0].id, community.root_epoch);
1406        let rumor = chat::build_message_rumor(me.public_key(), &community.channels[0].id, community.root_epoch, "not yours", None, &[], vec![], 1_000);
1407        let (wrap, _) = chat::seal_chat_rumor(&rumor, &stranger, &me, nostr_sdk::prelude::Timestamp::from_secs(1), false).unwrap();
1408
1409        let rec = Recorder::default();
1410        assert!(matches!(dispatch_wrap(&wrap, &community, &me.public_key(), &rec), DispatchedV2::NotOurs));
1411        assert!(rec.messages.lock().unwrap().is_empty());
1412    }
1413}