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