Skip to main content

vector_core/community/
inbound.rs

1//! Inbound processing: turn a verified, opened Community message into a `Message`
2//! in `STATE` under its channel chat (→ app state). Pure conversion
3//! (`build_message`) is separated from the STATE mutation (`ingest_message`) so the
4//! conversion is unit-testable without any global state.
5
6use nostr_sdk::prelude::{Event, PublicKey};
7use nostr_sdk::prelude::ToBech32;
8
9use super::envelope::{open_message_multi, OpenedMessage};
10use super::Channel;
11use crate::state::ChatState;
12use crate::stored_event::event_kind;
13use crate::types::Message;
14
15/// Convert a verified [`OpenedMessage`] into a STATE `Message` via the SHARED content parser.
16///
17/// A Concord 3300 normalizes to a text rumor and runs through `rumor::process_rumor` — the exact same
18/// path a NIP-17 DM text message takes — so content, reply ref, emoji, ms (incl. the future-clamp),
19/// and author-by-conversation-type are parsed in ONE place for every transport. The only Concord-
20/// specific layering is attachments: Concord carries NIP-92 `imeta` (multi-file + caption), already
21/// parsed in `open_message`, so they're set on top of the shared text result.
22/// Build a normalized `(RumorEvent, RumorContext)` from an opened Concord inner so it can run through
23/// the SHARED `rumor::process_rumor`. `kind` is the canonical content kind the sub-kind maps to
24/// (3300→14, 3301→reaction, 3302→edit, 3305→deletion). The binding/banlist/authority checks already
25/// happened at the transport layer; this is purely the bridge to the shared content parser.
26fn concord_rumor(
27    opened: &OpenedMessage,
28    kind: nostr_sdk::prelude::Kind,
29    my_pubkey: &PublicKey,
30) -> (crate::rumor::RumorEvent, crate::rumor::RumorContext) {
31    use crate::rumor::{ConversationType, RumorContext, RumorEvent};
32    (
33        RumorEvent {
34            id: opened.message_id,
35            kind,
36            content: opened.content.clone(),
37            tags: opened.tags.clone(),
38            created_at: opened.created_at,
39            pubkey: opened.author,
40        },
41        RumorContext {
42            sender: opened.author,
43            is_mine: opened.author == *my_pubkey,
44            conversation_id: opened.channel_id.to_hex(),
45            conversation_type: ConversationType::Community,
46        },
47    )
48}
49
50pub fn build_message(opened: &OpenedMessage, my_pubkey: &PublicKey) -> Message {
51    use crate::rumor::{process_rumor, RumorProcessingResult};
52    let (rumor, ctx) = concord_rumor(opened, nostr_sdk::prelude::Kind::PrivateDirectMessage, my_pubkey);
53    let mut msg = match process_rumor(rumor, ctx, &crate::db::get_download_dir()) {
54        Ok(RumorProcessingResult::TextMessage(m)) => m,
55        // A 3300 is always a caption/text message, so this never fires — but never drop a message on
56        // a parser quirk: fall back to the minimal direct fields.
57        _ => Message {
58            id: opened.message_id.to_hex(),
59            content: opened.content.clone(),
60            at: opened.ms.unwrap_or_else(|| opened.created_at.as_secs().saturating_mul(1000)),
61            mine: opened.author == *my_pubkey,
62            npub: opened.author.to_bech32().ok(),
63            ..Default::default()
64        },
65    };
66    // Transport-specific: Concord attachments are NIP-92 imeta (already parsed). Link the outer wire
67    // id for the shared dedup. The shared parser already set content/reply/emoji/ms/npub.
68    msg.attachments = opened.attachments.clone();
69    // Drop any blob URL a foreign client (e.g. Armada) also inlined into the caption.
70    msg.content = super::attachments::strip_attachment_urls(&msg.content, &msg.attachments);
71    msg.wrapper_event_id = Some(opened.wrapper_id.to_hex());
72    msg
73}
74
75/// Ingest a verified Community message into STATE under its channel chat, creating
76/// the chat (as `ChatType::Community`) if absent. Returns the added `Message` (so the
77/// caller can persist + emit it), or `None` if it was a duplicate (dedup on the inner
78/// message id).
79pub fn ingest_message(
80    state: &mut ChatState,
81    opened: &OpenedMessage,
82    my_pubkey: &PublicKey,
83) -> Option<Message> {
84    let chat_id = opened.channel_id.to_hex();
85    let msg = build_message(opened, my_pubkey);
86    // DB-level dedup: an inner id already in the events table is KNOWN — don't re-ingest into
87    // STATE or re-emit it. A boot/catch-up sweep re-fetches the whole channel page, but in-memory
88    // STATE only holds the per-chat hydration window, so it can't dedup the tail on its own. Without
89    // this, replayed sends (incl. our own) resurface as "new", re-firing reads/notifications. Mirrors
90    // the DM pipeline: outer dedup (wrapper-id cache) + inner dedup (events table). Known events live
91    // in the DB and load from there.
92    if crate::db::events::event_exists(&msg.id).unwrap_or(false) {
93        return None;
94    }
95    state.ensure_community_chat(&chat_id);
96    if state.add_message_to_chat(&chat_id, &msg) {
97        Some(msg)
98    } else {
99        None
100    }
101}
102
103/// The result of processing an inbound wire event: a brand-new message (3300), an update to
104/// an existing message (a reaction 3301 / edit 3302 applied to its target), or a tombstone
105/// (a delete 3305 that removed its target). New/Updated surface as a UI `message_new` /
106/// `message_update`; Removed surfaces as a `message_removed`.
107pub enum IncomingEvent {
108    NewMessage(Message),
109    /// An existing message changed (reaction or edit). `message` is the live-updated view for the
110    /// UI. `edit_event` is `Some` only for edits: the `MESSAGE_EDIT` StoredEvent the caller persists
111    /// (event-sourced, folded on reload like DM edits) instead of overwriting the row. Reactions
112    /// leave it `None` and the caller re-saves the message row (which carries the new reaction).
113    Updated { target_id: String, message: Message, edit_event: Option<Box<crate::stored_event::StoredEvent>> },
114    Removed { target_id: String },
115    /// A reaction was revoked by its author (a 3305 tombstone whose target is a reaction id).
116    /// The caller drops the reaction's kind-7 row and re-emits `message` so chips refresh live.
117    /// Distinct from `Removed` (whole message) and `Updated` (re-saves the row, which is additive
118    /// and so can't express a removal). `message_id` is the parent for the UI update.
119    ReactionRemoved { message_id: String, reaction_id: String, message: Message },
120    /// A join/leave presence announcement (kind 3306). `npub` is the announcing member; the
121    /// caller persists + surfaces it as a `MemberJoined`/`MemberLeft` system event. `event_id`
122    /// is the inner id (dedup key). `created_at` is the inner's authenticated timestamp (secs) so a
123    /// HISTORICALLY-synced join/leave lands at the right place in the timeline, not at ingest-time
124    /// "now". `invited_by`/`invited_label` carry attribution on an invite-join (who/which-link
125    /// brought them) — `None` for a plain join/leave. Not a message.
126    Presence { npub: String, joined: bool, event_id: String, created_at: u64, invited_by: Option<String>, invited_label: Option<String> },
127    /// A cooperative kick (3309) targeting THE LOCAL USER, authorized (signer held `KICK` + outranked
128    /// us). The caller performs the self-removal teardown (wipe local chat data, RETAIN the held
129    /// epoch keys). A kick of ANOTHER member surfaces as `Presence { joined: false }`
130    /// instead, so it falls out of the observed member list without a dedicated arm.
131    Kicked { community_id: String },
132    /// A voluntary leave-presence (3306, content "leave") whose inner author IS the local npub — i.e. a
133    /// leave I (or another of my devices) published. route to the same self-removal teardown as
134    /// `Kicked`/ban so a leave on device A tears the community down on device B too. Safe because the
135    /// presence inner is real-npub-signed (only my own devices can author a leave for my npub). The
136    /// teardown is idempotent, so the publishing device tearing down on its own echoed leave is a no-op.
137    SelfLeft { community_id: String },
138    /// A WebXDC realtime peer signal (3310): a member advertising their Iroh node for a Mini App
139    /// session (`node_addr` = Some) or announcing they stopped playing (`node_addr` = None). The
140    /// caller persists it (kind-30078 row keyed by `topic_id`, the DM-parity shape) and — when a
141    /// realtime channel for the topic is live — feeds the peer to the gossip layer. Not a message.
142    WebxdcPeer {
143        npub: String,
144        topic_id: String,
145        /// Base32 iroh node address — `Some` for an advertisement, `None` for peer-left.
146        node_addr: Option<String>,
147        event_id: String,
148        created_at: u64,
149    },
150    /// A typing indicator (3311): a member is composing in this channel. Ephemeral — never persisted
151    /// or folded; the caller feeds it to the live typing tracker and emits `typing-update`. `until` is
152    /// the unix-secs the typer should stop being shown as active (receiver-computed, ~30s out).
153    Typing { npub: String, until: u64 },
154}
155
156/// Open a single incoming wire event against `channel`, verify the binding, and apply
157/// it to STATE by sub-kind: a message is ingested, a reaction/edit is applied to its
158/// target. Events that fail to open (wrong key, splice, forged sig, bad version) or that
159/// dedup/target-miss are dropped (returns `None`). This is the per-event handler the
160/// real-time subscription routes each arriving 3300/3301/3302 event through.
161pub fn process_incoming(
162    state: &mut ChatState,
163    event: &Event,
164    channel: &Channel,
165    my_pubkey: &PublicKey,
166) -> Option<IncomingEvent> {
167    // Outer-event dedup, shared with DMs via the cross-transport ledger: a wire event we've already
168    // processed is either recorded as some inner's `wrapper_event_id` (row-creating sub-kinds) or in
169    // the `processed_wrappers` ledger (non-row sub-kinds). Skip it BEFORE decryption — the same role
170    // the wrapper-id cache plays for gift-wraps. The per-inner-id check in ingest_message is the
171    // backstop for the same inner re-published under a fresh wire event.
172    let outer_bytes = event.id.to_bytes();
173    if crate::db::events::wrapper_event_exists(&event.id.to_hex()).unwrap_or(false)
174        || crate::db::wrappers::processed_wrapper_exists(&outer_bytes)
175    {
176        return None;
177    }
178    // binary seal: a dissolved community DROPS every subsequent event — control or message, any author
179    // (owner included), any claimed time. NO timestamp comparison: the seal is the flag, not a time.
180    // Already-persisted events stay (no retroactive purge); this only stops NEW events from landing.
181    // CARVE-OUT: own-message DELETIONS (3305) always pass — data ownership means anyone can scrub their own
182    // content from a dead community, and a delete only removes the author's OWN message (it can't inject, so
183    // it doesn't reopen the backdating attack the seal exists to stop). `apply_delete` restricts a dissolved
184    // community's deletes to SELF-deletes (moderation-hides are blocked).
185    if channel.dissolved && event.kind.as_u16() != event_kind::COMMUNITY_DELETE {
186        return None;
187    }
188    // Select the decryption key by the event's epoch pseudonym across ALL held epochs (post-rekey
189    // catch-up), so a message posted under an older epoch still opens. Falls back to the head epoch for
190    // send-built/test channels (read_epoch_keys).
191    let opened = match open_message_multi(event, &channel.id, &channel.read_epoch_keys()) {
192        Ok(o) => o,
193        Err(e) => {
194            crate::log_debug!("[community] inbound drop {}: {}", event.id.to_hex(), e);
195            return None;
196        }
197    };
198    // Banlist (the "anti-memberlist"): drop EVERY event kind from a banned author — message,
199    // reaction, edit, delete, presence — so a banned member vanishes entirely, presence and all.
200    if channel.banned.contains(&opened.author) {
201        crate::log_debug!("[community] dropped event from banned author {}", opened.author.to_hex());
202        return None;
203    }
204    let outcome = match opened.kind {
205        k if k == event_kind::COMMUNITY_MESSAGE => {
206            ingest_message(state, &opened, my_pubkey).map(IncomingEvent::NewMessage)
207        }
208        k if k == event_kind::COMMUNITY_REACTION => apply_reaction(state, &opened, my_pubkey),
209        k if k == event_kind::COMMUNITY_EDIT => apply_edit(state, &opened, my_pubkey),
210        k if k == event_kind::COMMUNITY_DELETE => apply_delete(state, &opened, channel, my_pubkey),
211        k if k == event_kind::COMMUNITY_PRESENCE => apply_presence(&opened, channel, my_pubkey),
212        k if k == event_kind::COMMUNITY_KICK => apply_kick(&opened, channel, my_pubkey),
213        k if k == event_kind::COMMUNITY_WEBXDC => apply_webxdc(&opened, my_pubkey),
214        k if k == event_kind::COMMUNITY_TYPING => apply_typing(&opened, my_pubkey),
215        _ => None,
216    };
217    // Record the outer id in the shared ledger for NON-message sub-kinds, which have no inner row to
218    // carry a `wrapper_event_id` (messages are covered atomically by that column on save). These are
219    // idempotent on replay, so recording at process time is safe. Gives every sub-kind the same
220    // pre-decryption skip on a re-fetch that messages already get. Typing is exempt — it's a frequent,
221    // realtime-only ephemeral signal; recording every keystroke ping would bloat the ledger for no gain.
222    if let Some(ref evt) = outcome {
223        if !matches!(evt, IncomingEvent::NewMessage(_) | IncomingEvent::Typing { .. }) {
224            let _ = crate::db::wrappers::save_processed_wrapper(
225                &outer_bytes, event.created_at.as_secs(), crate::db::wrappers::TRANSPORT_CONCORD,
226            );
227        }
228    }
229    outcome
230}
231
232/// Interpret a presence announcement (3306). The inner author is the member; content "leave"
233/// marks a departure, anything else (e.g. "join") an arrival. No STATE mutation here — the
234/// caller turns this into a persisted system event (which is where dedup-by-id happens).
235fn apply_presence(opened: &OpenedMessage, channel: &Channel, my_pubkey: &PublicKey) -> Option<IncomingEvent> {
236    // Content is "leave", plain "join", or an attributed-join JSON `{"by":"<npub>","l":"<label>"}`.
237    let joined = opened.content != "leave";
238    // voluntary-leave self-teardown: a leave whose inner author is MY npub means I (or another of my
239    // devices) left → route to the same self-removal teardown as a kick/ban, so the leave propagates to
240    // every device that syncs it. Safe because the inner is real-npub-signed (only my devices author it).
241    if !joined && opened.author == *my_pubkey {
242        if let Ok(Some(cid)) = crate::db::community::community_id_for_channel(&channel.id.to_hex()) {
243            // Only a leave NEWER than the current join is a real teardown. A leave OLDER than the join is
244            // a historical leave from a PRIOR membership cycle (re-accepting an invite writes a fresh,
245            // later join time) — it must NOT tear down the re-join (mirrors apply_kick's staleness gate),
246            // but it SHOULD still surface as a "left" system event so my own join/leave history matches
247            // what other members see. So: fresh leave → SelfLeft (teardown); stale leave → fall through to
248            // the normal Presence emission below (a MemberLeft history line). saturating_mul: the inner
249            // created_at isn't relay-clamped.
250            let cid_bytes = crate::community::CommunityId(crate::simd::hex::hex_to_bytes_32(&cid));
251            let join_ms = crate::db::community::community_created_at_ms(&cid_bytes).unwrap_or(0);
252            if opened.created_at.as_secs().saturating_mul(1000) > join_ms {
253                return Some(IncomingEvent::SelfLeft { community_id: cid });
254            }
255            crate::log_debug!("[community] self-leave predates this join — rendering as history, not teardown");
256        }
257    }
258    let (invited_by, invited_label) = if joined {
259        serde_json::from_str::<serde_json::Value>(&opened.content)
260            .ok()
261            .map(|v| {
262                // `by` is attacker-controlled (the joiner builds their own presence), so VALIDATE it is a
263                // real pubkey before surfacing — else a hostile join could inject arbitrary text into the
264                // member list as a fake "inviter". Drop a non-pubkey. Bound the free-text label too.
265                let by = v.get("by").and_then(|b| b.as_str())
266                    .filter(|s| PublicKey::parse(s).is_ok())
267                    .map(str::to_string);
268                let label = v.get("l").and_then(|l| l.as_str())
269                    .map(|s| s.chars().take(48).collect::<String>())
270                    .filter(|s| !s.is_empty());
271                (by, label)
272            })
273            .unwrap_or((None, None))
274    } else {
275        (None, None)
276    };
277    Some(IncomingEvent::Presence {
278        npub: opened.author.to_bech32().ok()?,
279        joined,
280        event_id: opened.message_id.to_hex(),
281        created_at: clamp_inner_secs(opened.created_at.as_secs()),
282        invited_by,
283        invited_label,
284    })
285}
286
287/// Clamp an author-controlled inner timestamp before it becomes a persisted
288/// sort key — a forged far-future stamp would otherwise pin the event at the
289/// timeline edge forever (mirrors the webxdc handlers' clamp).
290fn clamp_inner_secs(secs: u64) -> u64 {
291    let now = std::time::SystemTime::now()
292        .duration_since(std::time::UNIX_EPOCH)
293        .map(|d| d.as_secs())
294        .unwrap_or(0);
295    secs.min(now + 300)
296}
297
298/// Interpret a WebXDC peer signal (3310). JSON content: `{"op":"ad","topic":...,"addr":...}` for an
299/// advertisement, `{"op":"left","topic":...}` for a departure. The inner author is the player (real-npub
300/// signed, so a member can't forge another's presence). Own-device echoes are dropped — the local
301/// realtime layer already tracks itself. Both fields are author-controlled: the topic must be a
302/// 52-char base32 TopicId and the addr is size-bounded (the realtime layer's decode is the final word).
303fn apply_webxdc(opened: &OpenedMessage, my_pubkey: &PublicKey) -> Option<IncomingEvent> {
304    if opened.author == *my_pubkey {
305        return None;
306    }
307    let (topic_id, node_addr) = crate::webxdc::parse_peer_signal(&opened.content)?;
308    Some(IncomingEvent::WebxdcPeer {
309        npub: opened.author.to_bech32().ok()?,
310        topic_id,
311        node_addr,
312        event_id: opened.message_id.to_hex(),
313        created_at: opened.created_at.as_secs(),
314    })
315}
316
317/// Interpret a typing indicator (3311). Content is "typing"; the inner author is the typer (real-npub
318/// signed). Own-device echoes are dropped. `until` is computed receiver-side (now + 30s) rather than
319/// trusting the sender's clock — typing is realtime, so a fixed local window is both simpler and immune
320/// to a forged far-future timestamp pinning a phantom typer.
321fn apply_typing(opened: &OpenedMessage, my_pubkey: &PublicKey) -> Option<IncomingEvent> {
322    if opened.author == *my_pubkey {
323        return None;
324    }
325    if opened.content != "typing" {
326        return None;
327    }
328    let now = std::time::SystemTime::now()
329        .duration_since(std::time::UNIX_EPOCH)
330        .map(|d| d.as_secs())
331        .unwrap_or(0);
332    Some(IncomingEvent::Typing {
333        npub: opened.author.to_bech32().ok()?,
334        until: now + 30,
335    })
336}
337
338/// Apply an inbound cooperative kick (3309). The kicker's REAL npub is the inner author; `content` is the
339/// target member's hex pubkey. Honored only when the kicker (a) cites a grant we've SYNCED
340/// (`actor_authority_pinned`) AND (b) holds `KICK` + strictly outranks the target in the
341/// floor-protected roster (`can_act_on_member`; the owner is never a valid target there, so owner-
342/// protection falls out with no hardcoded carve-out, and a self-kick is refused since you don't strictly
343/// outrank yourself). NOT a
344/// rekey and NOT persisted: a kick of THE LOCAL USER yields `Kicked` (the caller tears down locally); a
345/// kick of another member reuses `Presence { joined: false }` so they drop out of the observed member
346/// list. An unauthorized or uncited kick is dropped. Per, only a kick NEWER than this account's join
347/// is obeyed, so re-accepting an invite cleanly overrides a stale kick replayed from channel history.
348fn apply_kick(opened: &OpenedMessage, channel: &Channel, my_pubkey: &PublicKey) -> Option<IncomingEvent> {
349    use crate::community::roles::Permissions;
350    let target = PublicKey::parse(opened.content.trim()).ok()?;
351    let target_hex = target.to_hex();
352    let kicker_hex = opened.author.to_hex();
353    let owner_hex = channel.protected.first().map(|pk| pk.to_hex());
354    let pinned = actor_authority_pinned(channel, owner_hex.as_deref(), &kicker_hex, opened.citation.as_ref());
355    if !(pinned && channel.roster.can_act_on_member(&kicker_hex, owner_hex.as_deref(), &target_hex, Permissions::KICK)) {
356        crate::log_debug!("[community] dropped kick: {kicker_hex} not authorized to kick {target_hex}");
357        return None;
358    }
359    let cid_hex = crate::db::community::community_id_for_channel(&channel.id.to_hex()).ok().flatten()?;
360    // "obey the latest kick newer than my current join": ignore any kick older than this account's
361    // join (the community row's first-save time, in ms). The inner's non-randomized `created_at` is
362    // seconds, so scale to ms. A kick tears the row down, so re-accepting an invite writes a fresh, later
363    // join time → a stale kick from before the re-join is cleanly overridden, no kicklist to maintain.
364    let cid = crate::community::CommunityId(crate::simd::hex::hex_to_bytes_32(&cid_hex));
365    let join_ms = crate::db::community::community_created_at_ms(&cid).unwrap_or(0);
366    // saturating: the inner `created_at` is NOT relay-clamped (it rides inside the ciphertext), so a
367    // hostile (already-authorized) kicker could set it near u64::MAX and overflow the ms scale.
368    if opened.created_at.as_secs().saturating_mul(1000) <= join_ms {
369        crate::log_debug!("[community] dropped stale kick of {target_hex} (predates this join)");
370        return None;
371    }
372    if target == *my_pubkey {
373        return Some(IncomingEvent::Kicked { community_id: cid_hex });
374    }
375    // Kicked someone else → reflect it in the observed member list as a leave (no dedicated arm).
376    Some(IncomingEvent::Presence {
377        npub: target.to_bech32().ok()?,
378        joined: false,
379        event_id: opened.message_id.to_hex(),
380        created_at: clamp_inner_secs(opened.created_at.as_secs()),
381        invited_by: None,
382        invited_label: None,
383    })
384}
385
386/// Does this wire event authenticate against the channel's keys — now (open +
387/// MAC) or on a prior sight (dedup ledgers)? The outer `created_at` is
388/// otherwise unauthenticated relay input: sync cursors must only ever advance
389/// over events that pass this, or one junk event stamped far-future/past at
390/// the channel's cleartext pseudonym wedges the session's fetch floor/ceiling.
391/// Ledger hits skip decryption, so steady-state re-syncs stay cheap.
392///
393/// CAVEAT: the ledger half is keyed by event id, NOT channel-scoped — a relay
394/// replaying channel A's real events into channel B's page authenticates here.
395/// Cursor skew from that is bounded by genuinely-authored (signature-pinned)
396/// times, roughly equivalent to the relay's existing withholding power; do not
397/// repurpose this as a channel-membership check.
398pub fn event_authenticates(event: &Event, channel: &Channel) -> bool {
399    if crate::db::events::wrapper_event_exists(&event.id.to_hex()).unwrap_or(false)
400        || crate::db::wrappers::processed_wrapper_exists(&event.id.to_bytes())
401    {
402        return true;
403    }
404    open_message_multi(event, &channel.id, &channel.read_epoch_keys()).is_ok()
405}
406
407/// Process a fetched batch of raw channel events (backfill / cold-start) in a SAFE order:
408/// messages (3300) first so a reaction/edit (3301/3302) finds its target already in STATE
409/// before its reference applies — relay return order is arbitrary, and a control event whose
410/// target hasn't been ingested yet is silently dropped. Each event goes through
411/// [`process_incoming`] (open + verify + dedup), so undecryptable/forged/duplicate events
412/// yield nothing. Returns the applied events in processing order for the caller to persist + emit.
413///
414/// KNOWN LIMITATION (cross-page): the two-pass ordering only covers targets WITHIN this batch.
415/// A reaction/edit on one page whose target message lives on an older, not-yet-fetched page is
416/// dropped and not re-applied when that page later arrives (the older page won't re-contain the
417/// reaction). Acceptable while history is shallow; when deep scroll-backfill matures this wants a
418/// pending-control buffer keyed by target id (re-drained on target ingest), mirroring the DM
419/// `PENDING_EVENTS` path.
420pub fn process_channel_batch(
421    state: &mut ChatState,
422    events: &[Event],
423    channel: &Channel,
424    my_pubkey: &PublicKey,
425) -> Vec<IncomingEvent> {
426    let mut out = Vec::new();
427    // Pass 1: messages; Pass 2: control events (reactions/edits). The outer kind mirrors the
428    // inner kind (seal enforces it), so it's a reliable partition key without decrypting.
429    for want_message in [true, false] {
430        for ev in events {
431            let is_message = ev.kind.as_u16() == event_kind::COMMUNITY_MESSAGE;
432            if is_message != want_message {
433                continue;
434            }
435            if let Some(evt) = process_incoming(state, ev, channel, my_pubkey) {
436                out.push(evt);
437            }
438        }
439    }
440    out
441}
442
443/// Apply an inbound reaction (3301) to its target message. The reaction is PARSED by the shared
444/// `process_rumor` (3301→kind 7: target, emoji, NIP-30 image); only the STATE apply (dedup on the
445/// reaction's inner id, so local + relay echoes collapse) is Concord-side.
446fn apply_reaction(state: &mut ChatState, opened: &OpenedMessage, my_pubkey: &PublicKey) -> Option<IncomingEvent> {
447    use crate::rumor::{process_rumor, RumorProcessingResult};
448    let (rumor, ctx) = concord_rumor(opened, nostr_sdk::prelude::Kind::Reaction, my_pubkey);
449    let reaction = match process_rumor(rumor, ctx, &crate::db::get_download_dir()) {
450        Ok(RumorProcessingResult::Reaction(r)) => r,
451        _ => return None,
452    };
453    let target_id = reaction.reference_id.clone();
454    // Cross-channel guard: a reaction may only land on a target resident in the SAME channel it was
455    // sealed under. The reaction's binding triad authenticates its own channel/epoch but says nothing
456    // about where its target lives, so without this a member holding one channel's key could inject
457    // reactions onto another channel's messages. (Community channel chats are keyed by channel-id hex.)
458    let expected_chat = opened.channel_id.to_hex();
459    if !matches!(state.find_message(&target_id), Some((chat, _)) if chat.id == expected_chat) {
460        return None;
461    }
462    let (_chat_id, was_added) = state.add_reaction_to_message(&target_id, reaction)?;
463    if !was_added {
464        return None;
465    }
466    let (_chat, message) = state.find_message(&target_id)?;
467    Some(IncomingEvent::Updated { target_id, message, edit_event: None })
468}
469
470/// Apply an inbound edit (3302) to its target message. PARSED by the shared `process_rumor`
471/// (3302→edit: target, new content, edited_at via the shared ms resolver). The author-scoped gate
472/// (only the original author may edit their own message) + the canonical edit applier are Concord-side.
473fn apply_edit(state: &mut ChatState, opened: &OpenedMessage, my_pubkey: &PublicKey) -> Option<IncomingEvent> {
474    use crate::rumor::{process_rumor, RumorProcessingResult};
475    let (rumor, ctx) = concord_rumor(opened, nostr_sdk::prelude::Kind::from(event_kind::MESSAGE_EDIT), my_pubkey);
476    let (target_id, new_content, edited_at, emoji_tags, edit_event) = match process_rumor(rumor, ctx, &crate::db::get_download_dir()) {
477        Ok(RumorProcessingResult::Edit { message_id, new_content, edited_at, emoji_tags, event }) => (message_id, new_content, edited_at, emoji_tags, event),
478        _ => return None,
479    };
480    // Author-scoped: you can't edit someone else's message (not a parser concern — needs the resident
481    // target's author).
482    let editor_npub = opened.author.to_bech32().ok()?;
483    let target_author = state.find_message(&target_id).and_then(|(_, m)| m.npub)?;
484    if target_author != editor_npub {
485        crate::log_debug!("[community] dropped edit from non-author of {}", target_id);
486        return None;
487    }
488    // The canonical edit applier seeds history with the original ONCE, dedups by `edited_at` (a
489    // relay-replayed edit is a no-op, not history corruption), sorts, and swaps the content.
490    let (_chat_id, message) = state.update_message(&target_id, |m| {
491        m.apply_edit(new_content.clone(), edited_at, emoji_tags.clone());
492    })?;
493    // Persist the edit as a folded MESSAGE_EDIT event (caller sets chat_id), mirroring DMs —
494    // no row overwrite, no JSON snapshot.
495    Some(IncomingEvent::Updated { target_id, message, edit_event: Some(Box::new(edit_event)) })
496}
497
498/// version-pinned authority for a directed authority action (moderation-hide 3305, kick 3309):
499/// does the actor's cited grant prove authority we've actually SYNCED? The owner is supreme (cites
500/// nothing). A non-owner must cite the grant that authorizes them, and we must hold that grant in our
501/// persisted heads at ≥ the cited version (with the cited hash at the tip) — else fail closed (don't
502/// honor an action claiming authority we can't confirm). This is the COMPLETENESS half only; the actual
503/// permission + outrank is the SEPARATE `can_act_on_member` check against the floor-protected roster (so
504/// a since-demoted actor is refused there: refuse-superseded). The block-until-synced FETCH escalation
505/// isn't possible in this sync inbound path; an action citing a version we haven't synced is dropped and
506/// re-evaluated on the next roster sync (the documented sync-path limit).
507fn actor_authority_pinned(
508    channel: &Channel,
509    owner_hex: Option<&str>,
510    actor_hex: &str,
511    citation: Option<&super::edition::AuthorityCitation>,
512) -> bool {
513    if owner_hex == Some(actor_hex) {
514        return true; // owner is supreme and cites nothing
515    }
516    if citation.is_none() {
517        return false; // a non-owner authority action MUST carry a citation
518    }
519    let Ok(Some(cid)) = crate::db::community::community_id_for_channel(&channel.id.to_hex()) else {
520        return false; // can't resolve the community → can't confirm the cited grant → fail closed
521    };
522    let cid_bytes = crate::simd::hex::hex_to_bytes_32(&cid);
523    let actor_bytes = crate::simd::hex::hex_to_bytes_32(actor_hex);
524    let grant_hex = crate::simd::hex::bytes_to_hex_32(&super::derive::grant_locator(
525        &crate::community::CommunityId(cid_bytes),
526        &actor_bytes,
527    ));
528    let head: Vec<super::roster::EntityHead> = crate::db::community::get_edition_head(&cid, &grant_hex)
529        .ok()
530        .flatten()
531        .map(|(version, self_hash)| super::roster::EntityHead { entity_hex: grant_hex.clone(), version, self_hash, inner_id: [0u8; 32], citation: None })
532        .into_iter()
533        .collect();
534    super::roster::authority_citation_satisfied(&head, owner_hex, actor_hex, &grant_hex, citation)
535}
536
537fn apply_delete(state: &mut ChatState, opened: &OpenedMessage, channel: &Channel, my_pubkey: &PublicKey) -> Option<IncomingEvent> {
538    use crate::community::roles::Permissions;
539    use crate::rumor::{process_rumor, RumorProcessingResult};
540    // Target PARSED by the shared deletion parser (3305→kind 5; rejects an ambiguous multi-`e` target).
541    // The author-delete vs moderation-hide AUTHORITY decision below stays Concord-side — it reads the
542    // synced roster, which the parser knows nothing about, and never mutates consensus.
543    let (rumor, ctx) = concord_rumor(opened, nostr_sdk::prelude::Kind::EventDeletion, my_pubkey);
544    let target_id = match process_rumor(rumor, ctx, &crate::db::get_download_dir()) {
545        Ok(RumorProcessingResult::DeletionRequest { target_event_id }) => target_event_id,
546        _ => return None,
547    };
548    let deleter = opened.author;
549    let deleter_hex = deleter.to_hex();
550
551    // A 3305 may target a REACTION rather than a message (both are event ids). Reactions are
552    // author-revocable only in v1 (no moderation-strip): the deleter must be the reactor. Handled
553    // before the message path so a reaction id never falls through to message-removal logic.
554    if let Some((_chat_id, message_id, author_npub, _is_comm)) = state.find_reaction(&target_id) {
555        let reactor_ok = PublicKey::parse(&author_npub).map(|pk| pk == deleter).unwrap_or(false);
556        if !reactor_ok {
557            crate::log_debug!("[community] dropped reaction-revoke: {deleter_hex} is not the reactor of {target_id}");
558            return None;
559        }
560        return state
561            .remove_reaction_from_message(&message_id, &target_id)
562            .map(|(_cid, message)| IncomingEvent::ReactionRemoved {
563                message_id,
564                reaction_id: target_id,
565                message,
566            });
567    }
568
569    let owner_hex = channel.protected.first().map(|pk| pk.to_hex());
570    // pinned authority for a moderation-hide: the deleter's cited grant must be one we've synced
571    // (fail closed otherwise). Orthogonal to the outrank below; self-deletes don't consult it.
572    let pinned = actor_authority_pinned(channel, owner_hex.as_deref(), &deleter_hex, opened.citation.as_ref());
573
574    // Resolve the target's author from the resident copy (needed for both the self-delete check and the
575    // hide outrank check). If the target isn't resident (an older page), we can't resolve the author.
576    let target_author = state
577        .find_message(&target_id)
578        .and_then(|(_, m)| m.npub.clone())
579        .and_then(|n| PublicKey::parse(&n).ok());
580
581    if let Some(author) = target_author {
582        // Self-delete: the message's own author removes it.
583        if author == deleter {
584            return state.remove_message(&target_id).map(|_| IncomingEvent::Removed { target_id });
585        }
586        // Moderation-hide: deleter must (a) cite an authorizing grant we've synced (`pinned`) AND
587        // (b) hold MANAGE_MESSAGES + outrank the target's author. The owner is never a valid target of
588        // `can_act_on_member` (so owner-protection falls out — no hardcoded carve-out), and a
589        // peer/superior can't be hidden either. Blocked once dissolved: a dead community accepts no
590        // new authority actions — only SELF-deletes (handled above) survive the seal.
591        if pinned && !channel.dissolved && channel.roster.can_act_on_member(&deleter_hex, owner_hex.as_deref(), &author.to_hex(), Permissions::MANAGE_MESSAGES) {
592            return state.remove_message(&target_id).map(|_| IncomingEvent::Removed { target_id });
593        }
594        crate::log_debug!("[community] dropped delete: {deleter_hex} not authorized to remove {target_id}");
595        return None;
596    }
597
598    // Target not resident in memory. If it's still in the DB (just paged out of the window), authorize
599    // against its REAL author — owner-protection and the outrank both apply exactly as for a resident
600    // target, so an admin can't tombstone the owner's (or a peer's) paged-out message.
601    if let Ok(Some(author_npub)) = crate::db::events::event_author(&target_id) {
602        if let Ok(author) = PublicKey::parse(&author_npub) {
603            // Dissolved gate mirrors the resident path: the seal blocks
604            // moderation-hides over paged-out targets too — only self-deletes
605            // survive in a dead community.
606            let ok = author == deleter
607                || (pinned
608                    && !channel.dissolved
609                    && channel.roster.can_act_on_member(&deleter_hex, owner_hex.as_deref(), &author.to_hex(), Permissions::MANAGE_MESSAGES));
610            if ok {
611                return Some(IncomingEvent::Removed { target_id });
612            }
613            crate::log_debug!("[community] dropped out-of-window delete: {deleter_hex} not authorized over {target_id}");
614            return None;
615        }
616    }
617
618    // Author unknown (in neither STATE nor DB — a hide racing ahead of its target). There's nothing to
619    // remove and no real author to authorize against yet, so DON'T act and DON'T let this record in the
620    // dedup ledger (returning None keeps `process_incoming` from recording the outer id). The hide stays
621    // un-deduped and RE-APPLIES on a later sync once the target is resident — the resident path then
622    // authorizes against the real author. (A speculative `Removed` here would be a no-op emit AND, via the
623    // ledger, dedup the hide forever → the message would never get hidden once it arrived: bypass.)
624    // Mirrors reaction/edit, which also return None on an absent target.
625    None
626}
627
628/// Route an incoming wire event by its `z` pseudonym tag to the matching channel in
629/// `routes`, then open + ingest it. Returns the added `Message`, or `None` if the
630/// event carries no `z` tag, names a pseudonym we don't route, or fails to open/dedup.
631/// Pure over the passed `state` + `routes`, so the routing is unit-testable without
632/// the live subscription loop.
633pub fn route_incoming(
634    state: &mut ChatState,
635    event: &Event,
636    routes: &std::collections::HashMap<String, Channel>,
637    my_pubkey: &PublicKey,
638) -> Option<IncomingEvent> {
639    let pseudonym = event.tags.iter().find_map(|t| {
640        let s = t.as_slice();
641        (s.len() >= 2 && s[0] == "z").then(|| s[1].clone())
642    })?;
643    let channel = routes.get(&pseudonym)?;
644    process_incoming(state, event, channel, my_pubkey)
645}
646
647#[cfg(test)]
648mod tests {
649    use nostr_sdk::prelude::FinalizeEvent;
650    use super::*;
651    use crate::community::derive::channel_pseudonym;
652    use std::collections::HashMap;
653    use crate::community::envelope::{build_inner_full, build_inner_typed, open_message, seal_message, seal_with_signed_inner};
654    use crate::community::edition::AuthorityCitation;
655    use crate::community::{Channel, ChannelId, ChannelKey, Epoch};
656    use crate::state::ChatState;
657    use nostr_sdk::prelude::{Keys, Tag};
658
659    /// A DB-backed community owned by `owner` with `admin` granted the Admin role (MANAGE_MESSAGES,
660    /// position 1) and the admin's grant head recorded at v1 — so `apply_delete` can resolve the
661    /// community (`community_id_for_channel`) and verify a moderation hide's pinned authority against the
662    /// persisted grant head. Returns the reloaded channel (carrying the denormalized roster + protected
663    /// owner) and a valid citation pinning the admin's v1 grant. Holds the DB test guard for the test.
664    fn db_roster_channel(
665        owner: &Keys,
666        admin: &PublicKey,
667    ) -> (tempfile::TempDir, std::sync::MutexGuard<'static, ()>, Channel, AuthorityCitation) {
668        use crate::community::roles::{CommunityRoles, MemberGrant, Role};
669        use nostr_sdk::prelude::ToBech32;
670        let guard = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
671        crate::db::close_database();
672        let tmp = tempfile::tempdir().unwrap();
673        let account = owner.public_key().to_bech32().unwrap();
674        std::fs::create_dir_all(tmp.path().join(&account)).unwrap();
675        crate::db::set_app_data_dir(tmp.path().to_path_buf());
676        crate::db::set_current_account(account.clone()).unwrap();
677        crate::db::init_database(&account).unwrap();
678        crate::state::MY_SECRET_KEY.store_from_keys(owner, &[]);
679        crate::state::set_my_public_key(owner.public_key());
680
681        let mut community = crate::community::Community::create("HQ", "general", vec!["r".into()]);
682        let cid = community.id.to_hex();
683        community.owner_attestation = Some(
684            crate::community::owner::build_owner_attestation_unsigned(owner.public_key(), &cid)
685                .finalize(owner)
686                .unwrap()
687                .as_json(),
688        );
689        crate::db::community::save_community(&community).unwrap();
690
691        // Grant the admin MANAGE_MESSAGES (Admin role) and cache it so the reloaded channel's roster
692        // ranks them; record their grant head at v1 so the citation below verifies.
693        let role = Role::admin("a".repeat(64));
694        let roster = CommunityRoles {
695            grants: vec![MemberGrant { member: admin.to_hex(), role_ids: vec![role.role_id.clone()] }],
696            roles: vec![role],
697        };
698        crate::db::community::set_community_roles(&cid, &roster, 0).unwrap();
699        let entity_id = crate::community::derive::grant_locator(&community.id, &admin.to_bytes());
700        let entity_hex = crate::simd::hex::bytes_to_hex_32(&entity_id);
701        let hash = [0x5Au8; 32];
702        crate::db::community::set_edition_head(&cid, &entity_hex, 1, &hash).unwrap();
703
704        let reloaded = crate::db::community::load_community(&community.id).unwrap().unwrap();
705        let channel = reloaded.channels[0].clone();
706        (tmp, guard, channel, AuthorityCitation { entity_id, version: 1, edition_hash: hash })
707    }
708
709    /// Seal a 3305 moderation hide of `target` as `author`, optionally carrying a `vac` citation.
710    fn seal_hide(channel: &Channel, author: &Keys, target: &str, ms: u64, citation: Option<&AuthorityCitation>) -> Event {
711        let extra: Vec<Tag> = citation.iter().map(|c| c.to_tag()).collect();
712        let inner = build_inner_full(
713            author.public_key(), &channel.id, channel.epoch, event_kind::COMMUNITY_DELETE, "", ms, Some(target), &[], &extra,
714        )
715        .finalize(author)
716        .unwrap();
717        seal_with_signed_inner(&Keys::generate(), &inner, &channel.key, &channel.id, channel.epoch).unwrap()
718    }
719
720    /// Ingest a message authored by `author` into `channel`, returning its inner id.
721    fn ingest_msg_in(state: &mut ChatState, channel: &Channel, author: &Keys, content: &str, ms: u64, viewer: &Keys) -> String {
722        let outer = seal_message(author, &channel.key, &channel.id, channel.epoch, content, ms).unwrap();
723        match process_incoming(state, &outer, channel, &viewer.public_key()) {
724            Some(IncomingEvent::NewMessage(m)) => m.id,
725            _ => panic!("expected a new message"),
726        }
727    }
728
729    fn opened_from(author: &Keys, content: &str, ms: u64) -> OpenedMessage {
730        let key = ChannelKey([0x33u8; 32]);
731        let chan = ChannelId([0x44u8; 32]);
732        let outer = seal_message(author, &key, &chan, Epoch(0), content, ms).unwrap();
733        open_message(&outer, &key, &chan, Epoch(0)).unwrap()
734    }
735
736    fn test_channel() -> Channel {
737        Channel { id: ChannelId([0x44u8; 32]), key: ChannelKey([0x33u8; 32]), epoch: Epoch(0), name: "t".into(), banned: Vec::new(), protected: Vec::new(), roster: Default::default(), epoch_keys: Vec::new(), dissolved: false }
738    }
739
740    /// Seal a typed control event (reaction/edit) referencing `target`, as `author`.
741    fn seal_typed(author: &Keys, kind: u16, content: &str, ms: u64, target: &str) -> Event {
742        let c = test_channel();
743        let inner = build_inner_typed(author.public_key(), &c.id, c.epoch, kind, content, ms, Some(target), &[])
744            .finalize(author)
745            .unwrap();
746        seal_with_signed_inner(&Keys::generate(), &inner, &c.key, &c.id, c.epoch).unwrap()
747    }
748
749    fn ingest_msg(state: &mut ChatState, author: &Keys, content: &str, ms: u64, viewer: &Keys) -> String {
750        let c = test_channel();
751        let outer = seal_message(author, &c.key, &c.id, c.epoch, content, ms).unwrap();
752        match process_incoming(state, &outer, &c, &viewer.public_key()) {
753            Some(IncomingEvent::NewMessage(m)) => m.id,
754            _ => panic!("expected a new message"),
755        }
756    }
757
758    #[test]
759    fn inbound_reaction_applies_to_target_and_dedups() {
760        use crate::stored_event::event_kind;
761        let mut state = ChatState::new();
762        let alice = Keys::generate();
763        let bob = Keys::generate();
764        let target = ingest_msg(&mut state, &alice, "hi", 1, &bob);
765
766        let react = seal_typed(&bob, event_kind::COMMUNITY_REACTION, "🔥", 2, &target);
767        match process_incoming(&mut state, &react, &test_channel(), &bob.public_key()) {
768            Some(IncomingEvent::Updated { target_id, message, edit_event: None }) => {
769                assert_eq!(target_id, target);
770                assert!(message.reactions.iter().any(|r| r.emoji == "🔥"), "reaction applied to target");
771            }
772            _ => panic!("expected a reaction update"),
773        }
774        // The exact same reaction event again → deduped (no second update).
775        assert!(process_incoming(&mut state, &react, &test_channel(), &bob.public_key()).is_none());
776    }
777
778    #[test]
779    fn bot_routing_tag_rides_the_v1_inner_into_addressed_bots() {
780        use nostr_sdk::prelude::ToBech32;
781        use crate::community::envelope::{build_inner_full, seal_with_signed_inner};
782        let mut state = ChatState::new();
783        let alice = Keys::generate();
784        let bot = Keys::generate();
785        let c = test_channel();
786
787        // A picker send: the `bot` routing tag rides the inner verbatim.
788        let inner = build_inner_full(
789            alice.public_key(),
790            &c.id,
791            c.epoch,
792            crate::stored_event::event_kind::COMMUNITY_MESSAGE,
793            "/roll 20",
794            5,
795            None,
796            &[],
797            &[crate::bot_interface::bot_tag(&bot.public_key())],
798        )
799        .finalize(&alice)
800        .unwrap();
801        let outer = seal_with_signed_inner(&Keys::generate(), &inner, &c.key, &c.id, c.epoch).unwrap();
802
803        // The real open + ingest path lifts the tag into `addressed_bots` —
804        // the field SDK bots consult to skip commands picked for another bot.
805        let opened = open_message(&outer, &c.key, &c.id, c.epoch).unwrap();
806        let msg = build_message(&opened, &alice.public_key());
807        assert_eq!(msg.addressed_bots, vec![bot.public_key().to_bech32().unwrap()]);
808
809        match process_incoming(&mut state, &outer, &c, &alice.public_key()) {
810            Some(IncomingEvent::NewMessage(m)) => {
811                assert_eq!(m.addressed_bots.len(), 1, "ingest keeps the routing tag");
812            }
813            _ => panic!("expected a new message"),
814        }
815    }
816
817    #[test]
818    fn reaction_cross_channel_is_rejected() {
819        // A member holding one channel's key must not be able to seal a reaction under THAT channel
820        // that lands on a message resident in ANOTHER channel.
821        use crate::stored_event::event_kind;
822        use crate::community::envelope::{build_inner_typed, seal_with_signed_inner};
823        let mut state = ChatState::new();
824        let alice = Keys::generate();
825        let bob = Keys::generate();
826        let chan_a = test_channel();
827        let chan_b = Channel {
828            id: ChannelId([0x55u8; 32]), key: ChannelKey([0x66u8; 32]), epoch: Epoch(0),
829            name: "b".into(), banned: Vec::new(), protected: Vec::new(),
830            roster: Default::default(), epoch_keys: Vec::new(), dissolved: false,
831        };
832        // Target message lives in channel A.
833        let target = ingest_msg_in(&mut state, &chan_a, &alice, "hi", 1, &bob);
834        // Bob seals a reaction under channel B that points at A's message.
835        let inner = build_inner_typed(
836            bob.public_key(), &chan_b.id, chan_b.epoch, event_kind::COMMUNITY_REACTION, "🔥", 2, Some(&target), &[],
837        ).finalize(&bob).unwrap();
838        let outer = seal_with_signed_inner(&Keys::generate(), &inner, &chan_b.key, &chan_b.id, chan_b.epoch).unwrap();
839        // Opened under channel B, but the target is in A → rejected, nothing applied.
840        assert!(
841            process_incoming(&mut state, &outer, &chan_b, &bob.public_key()).is_none(),
842            "a reaction sealed under another channel must not apply to this channel's message"
843        );
844        let (_c, msg) = state.find_message(&target).unwrap();
845        assert!(msg.reactions.is_empty(), "cross-channel reaction must not be applied");
846    }
847
848    #[test]
849    fn inbound_message_carries_multi_attachments() {
850        use crate::stored_event::event_kind;
851        use crate::community::attachments::attachment_to_imeta;
852        use crate::community::envelope::build_inner_full;
853        use crate::types::Attachment;
854        let mut state = ChatState::new();
855        let alice = Keys::generate();
856        let bob = Keys::generate();
857        let c = test_channel();
858
859        let mk = |n: &str, ext: &str| Attachment {
860            id: "x".into(), key: "0".repeat(64), nonce: format!("{:0<24}", crate::simd::hex::bytes_to_hex_string(n.as_bytes())),
861            extension: ext.into(), name: n.into(), url: format!("https://b/{n}"),
862            path: String::new(), size: 9, img_meta: None, downloading: false, downloaded: false,
863            webxdc_topic: None, group_id: None, original_hash: Some("a".repeat(64)),
864            fallback_urls: Vec::new(),
865        };
866        let imetas = vec![attachment_to_imeta(&mk("a.png", "png")), attachment_to_imeta(&mk("b.txt", "txt"))];
867        let inner = build_inner_full(
868            alice.public_key(), &c.id, c.epoch, event_kind::COMMUNITY_MESSAGE,
869            "caption", 5, None, &[], &imetas,
870        ).finalize(&alice).unwrap();
871        let outer = seal_with_signed_inner(&Keys::generate(), &inner, &c.key, &c.id, c.epoch).unwrap();
872
873        match process_incoming(&mut state, &outer, &c, &bob.public_key()) {
874            Some(IncomingEvent::NewMessage(m)) => {
875                assert_eq!(m.content, "caption", "caption + attachments coexist in one event");
876                assert_eq!(m.attachments.len(), 2);
877                assert_eq!(m.attachments[0].name, "a.png");
878                assert_eq!(m.attachments[1].name, "b.txt");
879                assert!(m.attachments.iter().all(|a| a.group_id.is_none()));
880            }
881            _ => panic!("expected new message with attachments"),
882        }
883    }
884
885    #[test]
886    fn inbound_edit_only_honored_from_original_author() {
887        use crate::stored_event::event_kind;
888        let mut state = ChatState::new();
889        let alice = Keys::generate();
890        let target = ingest_msg(&mut state, &alice, "original", 1, &alice);
891
892        // Author edits her own message → applied.
893        let edit = seal_typed(&alice, event_kind::COMMUNITY_EDIT, "edited!", 2, &target);
894        match process_incoming(&mut state, &edit, &test_channel(), &alice.public_key()) {
895            Some(IncomingEvent::Updated { message, edit_event, .. }) => {
896                assert_eq!(message.content, "edited!");
897                assert!(message.edited);
898                // Event-sourced: the edit rides a foldable MESSAGE_EDIT event, not a row overwrite.
899                let ev = edit_event.expect("edit surfaces a MESSAGE_EDIT event to persist");
900                assert_eq!(ev.kind, event_kind::MESSAGE_EDIT);
901                assert_eq!(ev.reference_id.as_deref(), Some(target.as_str()));
902                assert_eq!(ev.content, "edited!");
903            }
904            _ => panic!("expected an edit update"),
905        }
906
907        // A different author trying to edit alice's message → dropped, content unchanged.
908        let mallory = Keys::generate();
909        let hijack = seal_typed(&mallory, event_kind::COMMUNITY_EDIT, "hijacked", 3, &target);
910        assert!(process_incoming(&mut state, &hijack, &test_channel(), &alice.public_key()).is_none());
911        assert_eq!(state.find_message(&target).unwrap().1.content, "edited!");
912    }
913
914    #[test]
915    fn cooperative_delete_only_honored_from_original_author() {
916        use crate::stored_event::event_kind;
917        let mut state = ChatState::new();
918        let alice = Keys::generate();
919        let mallory = Keys::generate();
920        let target = ingest_msg(&mut state, &alice, "secret", 1, &alice);
921
922        // Someone else's delete of alice's message → dropped, message survives.
923        let hijack = seal_typed(&mallory, event_kind::COMMUNITY_DELETE, "", 2, &target);
924        assert!(process_incoming(&mut state, &hijack, &test_channel(), &alice.public_key()).is_none());
925        assert!(state.find_message(&target).is_some(), "non-author delete must not remove");
926
927        // Author's own delete (signed by a FRESH key, no retained message key needed) → removed.
928        let del = seal_typed(&alice, event_kind::COMMUNITY_DELETE, "", 3, &target);
929        match process_incoming(&mut state, &del, &test_channel(), &alice.public_key()) {
930            Some(IncomingEvent::Removed { target_id }) => assert_eq!(target_id, target),
931            _ => panic!("expected a removal"),
932        }
933        assert!(state.find_message(&target).is_none(), "message gone after author delete");
934
935        // Replaying the delete (or one arriving for an already-gone target) → silent no-op.
936        let replay = seal_typed(&alice, event_kind::COMMUNITY_DELETE, "", 4, &target);
937        assert!(process_incoming(&mut state, &replay, &test_channel(), &alice.public_key()).is_none());
938    }
939
940    #[test]
941    fn dissolved_community_still_honors_an_own_message_delete() {
942        use crate::stored_event::event_kind;
943        let mut state = ChatState::new();
944        let alice = Keys::generate();
945        let target = ingest_msg(&mut state, &alice, "alice's own message", 1, &alice);
946        let mut ch = test_channel();
947        ch.dissolved = true;
948        // carve-out (data ownership): the binary seal blocks all NEW content, but a member can always
949        // scrub their OWN past message even from a dead community — a 3305 self-delete passes the seal.
950        let del = seal_typed(&alice, event_kind::COMMUNITY_DELETE, "", 2, &target);
951        match process_incoming(&mut state, &del, &ch, &alice.public_key()) {
952            Some(IncomingEvent::Removed { target_id }) => assert_eq!(target_id, target),
953            _ => panic!("a self-delete must be honored in a dissolved community"),
954        }
955        assert!(state.find_message(&target).is_none(), "own message scrubbed from the dead community");
956    }
957
958    #[test]
959    fn admin_moderation_hide_removes_any_message() {
960        let owner = Keys::generate();
961        let admin = Keys::generate(); // granted MANAGE_MESSAGES in the roster
962        let (_tmp, _guard, c, cite) = db_roster_channel(&owner, &admin.public_key());
963        let alice = Keys::generate(); // author of the target
964        let mallory = Keys::generate(); // unprivileged member
965        let mut state = ChatState::new();
966        let target = ingest_msg_in(&mut state, &c, &alice, "spicy take", 1, &alice);
967
968        // A member with no MANAGE_MESSAGES role (and no citation to offer) cannot hide someone else's.
969        let hijack = seal_hide(&c, &mallory, &target, 2, None);
970        assert!(process_incoming(&mut state, &hijack, &c, &alice.public_key()).is_none());
971        assert!(state.find_message(&target).is_some(), "unprivileged hide rejected");
972
973        // The admin (hide signed by their REAL npub, citing their synced grant) hides a member's message.
974        let hide = seal_hide(&c, &admin, &target, 3, Some(&cite));
975        match process_incoming(&mut state, &hide, &c, &alice.public_key()) {
976            Some(IncomingEvent::Removed { target_id }) => assert_eq!(target_id, target),
977            _ => panic!("expected admin moderation-hide to remove the message"),
978        }
979        assert!(state.find_message(&target).is_none(), "admin hide removed the message");
980    }
981
982    #[test]
983    fn admin_hide_without_a_citation_is_dropped() {
984        // a non-owner moderation hide MUST cite the grant that authorizes them. An admin who holds
985        // MANAGE_MESSAGES but ships an UNCITED hide is dropped (fail closed — we never act on authority
986        // that isn't pinned to a synced grant version).
987        let owner = Keys::generate();
988        let admin = Keys::generate();
989        let (_tmp, _guard, c, _cite) = db_roster_channel(&owner, &admin.public_key());
990        let alice = Keys::generate();
991        let mut state = ChatState::new();
992        let target = ingest_msg_in(&mut state, &c, &alice, "spicy take", 1, &alice);
993
994        let hide = seal_hide(&c, &admin, &target, 2, None); // no citation
995        assert!(process_incoming(&mut state, &hide, &c, &alice.public_key()).is_none());
996        assert!(state.find_message(&target).is_some(), "an uncited admin hide is dropped");
997    }
998
999    #[test]
1000    fn hide_citing_an_unsynced_grant_version_is_dropped() {
1001        // The sync-floor: an admin who cites a grant version we have NOT synced (ahead of our persisted
1002        // head) is dropped — we can't confirm the authority, so we don't act (block-until-synced degrades
1003        // to drop in the sync inbound path; it re-evaluates once the grant syncs).
1004        let owner = Keys::generate();
1005        let admin = Keys::generate();
1006        let (_tmp, _guard, c, cite) = db_roster_channel(&owner, &admin.public_key());
1007        let alice = Keys::generate();
1008        let mut state = ChatState::new();
1009        let target = ingest_msg_in(&mut state, &c, &alice, "spicy take", 1, &alice);
1010
1011        // Our held head for the admin's grant is v1; the hide cites a future v2 nobody has yet.
1012        let ahead = AuthorityCitation { version: 2, ..cite };
1013        let hide = seal_hide(&c, &admin, &target, 2, Some(&ahead));
1014        assert!(process_incoming(&mut state, &hide, &c, &alice.public_key()).is_none());
1015        assert!(state.find_message(&target).is_some(), "a hide citing an unsynced version is dropped");
1016    }
1017
1018    #[test]
1019    fn hide_with_a_forged_citation_hash_is_dropped() {
1020        // fork guard: an admin citing their real grant entity + version but the WRONG hash is dropped.
1021        let owner = Keys::generate();
1022        let admin = Keys::generate();
1023        let (_tmp, _guard, c, cite) = db_roster_channel(&owner, &admin.public_key());
1024        let alice = Keys::generate();
1025        let mut state = ChatState::new();
1026        let target = ingest_msg_in(&mut state, &c, &alice, "spicy take", 1, &alice);
1027
1028        let forged = AuthorityCitation { edition_hash: [0xEE; 32], ..cite };
1029        let hide = seal_hide(&c, &admin, &target, 2, Some(&forged));
1030        assert!(process_incoming(&mut state, &hide, &c, &alice.public_key()).is_none());
1031        assert!(state.find_message(&target).is_some(), "a forged-hash citation is dropped");
1032    }
1033
1034    #[test]
1035    fn protected_owner_cannot_be_moderation_hidden_but_others_can() {
1036        let owner = Keys::generate(); // protected, implicit position 0
1037        let admin = Keys::generate(); // granted MANAGE_MESSAGES
1038        let (_tmp, _guard, c, cite) = db_roster_channel(&owner, &admin.public_key());
1039        let mut state = ChatState::new();
1040
1041        // An admin-signed hide targeting the OWNER's message is dropped — the owner outranks every admin.
1042        let owners_msg = ingest_msg_in(&mut state, &c, &owner, "owner speaks", 1, &owner);
1043        let hide_owner = seal_hide(&c, &admin, &owners_msg, 2, Some(&cite));
1044        assert!(process_incoming(&mut state, &hide_owner, &c, &owner.public_key()).is_none());
1045        assert!(state.find_message(&owners_msg).is_some(), "owner's message is protected");
1046
1047        // A non-protected member's message CAN be moderation-hidden by the same admin.
1048        let member = Keys::generate();
1049        let members_msg = ingest_msg_in(&mut state, &c, &member, "member speaks", 3, &owner);
1050        let hide_member = seal_hide(&c, &admin, &members_msg, 4, Some(&cite));
1051        match process_incoming(&mut state, &hide_member, &c, &owner.public_key()) {
1052            Some(IncomingEvent::Removed { target_id }) => assert_eq!(target_id, members_msg),
1053            _ => panic!("a non-protected member's message should be hideable"),
1054        }
1055    }
1056
1057    #[test]
1058    fn admin_hide_of_absent_target_defers_until_resident() {
1059        // A hide for a target resident in NEITHER STATE nor DB (racing ahead of its message) returns None
1060        // — there's nothing to remove and no real author to outrank yet. Critically it must NOT emit a
1061        // speculative Removed: that emit is a no-op (delete_event on an absent id does nothing) AND, via
1062        // the cross-transport dedup ledger, would dedup the hide forever, so the message would never get
1063        // hidden once it finally arrived (a moderation bypass). Returning None keeps the hide
1064        // un-deduped so it RE-APPLIES on a later sync once the target pages in (resident path authorizes
1065        // against the real author). Mirrors reaction/edit on an absent target.
1066        let owner = Keys::generate();
1067        let admin = Keys::generate();
1068        let (_tmp, _guard, c, cite) = db_roster_channel(&owner, &admin.public_key());
1069        let mut state = ChatState::new();
1070        let absent_target = "f".repeat(64); // never ingested into STATE or DB
1071
1072        let hide = seal_hide(&c, &admin, &absent_target, 1, Some(&cite));
1073        assert!(
1074            process_incoming(&mut state, &hide, &c, &Keys::generate().public_key()).is_none(),
1075            "a hide of an absent target defers (None) rather than falsely tombstoning + self-deduping",
1076        );
1077
1078        // A NON-privileged hide of an out-of-window message stays a no-op (no MANAGE_MESSAGES grant).
1079        let mallory = Keys::generate();
1080        let hijack = seal_hide(&c, &mallory, &absent_target, 2, None);
1081        assert!(process_incoming(&mut state, &hijack, &c, &mallory.public_key()).is_none());
1082
1083        // And a PRIVILEGED admin (holds MANAGE_MESSAGES) who ships an UNCITED hide of the unknown target
1084        // is ALSO dropped — the author-unknown branch is gated on `pinned`, not the permission bit alone.
1085        let uncited = seal_hide(&c, &admin, &absent_target, 3, None);
1086        assert!(
1087            process_incoming(&mut state, &uncited, &c, &Keys::generate().public_key()).is_none(),
1088            "an admin's uncited hide of an unknown target is dropped (pinned gates the author-unknown path)"
1089        );
1090    }
1091
1092    #[tokio::test]
1093    async fn out_of_window_hide_authorizes_against_db_author() {
1094        use crate::types::Message;
1095        // A paged-out target (in the DB, not resident in memory) is authorized against its REAL author:
1096        // an admin can hide a regular member's paged-out message, but NOT the owner's (owner-protection
1097        // holds even when the message is out of the in-memory window).
1098        use nostr_sdk::prelude::ToBech32;
1099        let owner = Keys::generate();
1100        let admin = Keys::generate(); // granted MANAGE_MESSAGES
1101        let member = Keys::generate();
1102        let (_tmp, _guard, c, cite) = db_roster_channel(&owner, &admin.public_key());
1103
1104        // Persist two messages to the DB only — a fresh ChatState holds neither.
1105        let owner_msg = "a".repeat(64);
1106        let member_msg = "b".repeat(64);
1107        let mk = |id: &str, author: &Keys, at: u64| {
1108            let mut m = Message::default();
1109            m.id = id.to_string();
1110            m.npub = Some(author.public_key().to_bech32().unwrap());
1111            m.at = at;
1112            m
1113        };
1114        crate::db::events::save_message("chatoow", &mk(&owner_msg, &owner, 1)).await.unwrap();
1115        crate::db::events::save_message("chatoow", &mk(&member_msg, &member, 2)).await.unwrap();
1116
1117        let mut state = ChatState::new();
1118        // Admin hide of the OWNER's paged-out message → dropped (owner is supreme, never a target).
1119        let hide_owner = seal_hide(&c, &admin, &owner_msg, 3, Some(&cite));
1120        assert!(
1121            process_incoming(&mut state, &hide_owner, &c, &member.public_key()).is_none(),
1122            "owner's paged-out message must not be hideable by an admin"
1123        );
1124        // Admin hide of a regular member's paged-out message → Removed (tombstoned).
1125        let hide_member = seal_hide(&c, &admin, &member_msg, 4, Some(&cite));
1126        match process_incoming(&mut state, &hide_member, &c, &owner.public_key()) {
1127            Some(IncomingEvent::Removed { target_id }) => assert_eq!(target_id, member_msg),
1128            _ => panic!("admin should hide a member's paged-out message"),
1129        }
1130
1131        // Dissolved seal covers paged-out targets too: an admin moderation-hide of a
1132        // member's DB-only message is dropped in a dead community, while the author's
1133        // own self-delete of their paged-out message still passes (data ownership).
1134        let member_msg2 = "c".repeat(64);
1135        crate::db::events::save_message("chatoow", &mk(&member_msg2, &member, 5)).await.unwrap();
1136        let mut sealed = c.clone();
1137        sealed.dissolved = true;
1138        let hide_sealed = seal_hide(&sealed, &admin, &member_msg2, 6, Some(&cite));
1139        assert!(
1140            process_incoming(&mut state, &hide_sealed, &sealed, &owner.public_key()).is_none(),
1141            "a dissolved community accepts no moderation-hide, resident or paged-out"
1142        );
1143        let self_del = seal_hide(&sealed, &member, &member_msg2, 7, None);
1144        match process_incoming(&mut state, &self_del, &sealed, &owner.public_key()) {
1145            Some(IncomingEvent::Removed { target_id }) => assert_eq!(target_id, member_msg2),
1146            _ => panic!("a self-delete of a paged-out message must survive the dissolved seal"),
1147        }
1148        crate::db::close_database();
1149    }
1150
1151    /// Seal a 3309 cooperative kick of `target_hex` as `author`, optionally carrying a `vac` citation.
1152    fn seal_kick(channel: &Channel, author: &Keys, target_hex: &str, ms: u64, citation: Option<&AuthorityCitation>) -> Event {
1153        let extra: Vec<Tag> = citation.iter().map(|c| c.to_tag()).collect();
1154        let inner = build_inner_full(
1155            author.public_key(), &channel.id, channel.epoch, event_kind::COMMUNITY_KICK, target_hex, ms, None, &[], &extra,
1156        )
1157        .finalize(author)
1158        .unwrap();
1159        seal_with_signed_inner(&Keys::generate(), &inner, &channel.key, &channel.id, channel.epoch).unwrap()
1160    }
1161
1162    /// A kick inner timestamp safely AFTER `db_roster_channel`'s community save, so the join-time
1163    /// guard honors it. `build_inner_full` derives `created_at = ms / 1000`, so we add a 5s margin.
1164    fn post_join_ms() -> u64 {
1165        let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_secs();
1166        (now + 5) * 1000
1167    }
1168
1169    #[test]
1170    fn cited_admin_kick_of_local_user_yields_self_removal() {
1171        let owner = Keys::generate();
1172        let admin = Keys::generate();
1173        let member = Keys::generate();
1174        let (_tmp, _g, channel, cite) = db_roster_channel(&owner, &admin.public_key());
1175        let mut state = ChatState::new();
1176        // Admin kicks `member`; the LOCAL viewer is `member` → Kicked (the caller tears down locally).
1177        let kick = seal_kick(&channel, &admin, &member.public_key().to_hex(), post_join_ms(), Some(&cite));
1178        match process_incoming(&mut state, &kick, &channel, &member.public_key()) {
1179            Some(IncomingEvent::Kicked { community_id }) => assert!(!community_id.is_empty()),
1180            _ => panic!("expected Kicked"),
1181        }
1182        crate::db::close_database();
1183    }
1184
1185    #[test]
1186    fn cited_admin_kick_of_other_member_is_a_leave() {
1187        use nostr_sdk::prelude::ToBech32;
1188        let owner = Keys::generate();
1189        let admin = Keys::generate();
1190        let member = Keys::generate();
1191        let (_tmp, _g, channel, cite) = db_roster_channel(&owner, &admin.public_key());
1192        let mut state = ChatState::new();
1193        // Admin kicks `member`; the LOCAL viewer is the owner → reflected as a leave Presence so `member`
1194        // drops out of the observed member list (no dedicated arm).
1195        let kick = seal_kick(&channel, &admin, &member.public_key().to_hex(), post_join_ms(), Some(&cite));
1196        match process_incoming(&mut state, &kick, &channel, &owner.public_key()) {
1197            Some(IncomingEvent::Presence { npub, joined, .. }) => {
1198                assert!(!joined);
1199                assert_eq!(npub, member.public_key().to_bech32().unwrap());
1200            }
1201            _ => panic!("expected leave Presence"),
1202        }
1203        crate::db::close_database();
1204    }
1205
1206    #[test]
1207    fn uncited_kick_is_dropped() {
1208        let owner = Keys::generate();
1209        let admin = Keys::generate();
1210        let member = Keys::generate();
1211        let (_tmp, _g, channel, _cite) = db_roster_channel(&owner, &admin.public_key());
1212        let mut state = ChatState::new();
1213        let kick = seal_kick(&channel, &admin, &member.public_key().to_hex(), 1, None);
1214        assert!(process_incoming(&mut state, &kick, &channel, &member.public_key()).is_none(),
1215            "a non-owner kick without a citation is dropped");
1216        crate::db::close_database();
1217    }
1218
1219    #[test]
1220    fn unprivileged_kick_is_dropped() {
1221        let owner = Keys::generate();
1222        let admin = Keys::generate();
1223        let mallory = Keys::generate();
1224        let member = Keys::generate();
1225        let (_tmp, _g, channel, cite) = db_roster_channel(&owner, &admin.public_key());
1226        let mut state = ChatState::new();
1227        // Mallory holds no grant; even replaying the admin's citation, mallory's own grant locator has no
1228        // synced head AND the roster doesn't rank them with KICK → dropped (double-gated).
1229        let kick = seal_kick(&channel, &mallory, &member.public_key().to_hex(), 1, Some(&cite));
1230        assert!(process_incoming(&mut state, &kick, &channel, &member.public_key()).is_none(),
1231            "a kick from an unranked actor is dropped");
1232        crate::db::close_database();
1233    }
1234
1235    #[test]
1236    fn kick_of_owner_is_dropped() {
1237        let owner = Keys::generate();
1238        let admin = Keys::generate();
1239        let (_tmp, _g, channel, cite) = db_roster_channel(&owner, &admin.public_key());
1240        let mut state = ChatState::new();
1241        // The owner is never a valid target of an authority action (owner-protection, no hardcoded carve-out).
1242        let kick = seal_kick(&channel, &admin, &owner.public_key().to_hex(), post_join_ms(), Some(&cite));
1243        assert!(process_incoming(&mut state, &kick, &channel, &owner.public_key()).is_none(),
1244            "an admin cannot kick the owner");
1245        crate::db::close_database();
1246    }
1247
1248    #[test]
1249    fn stale_kick_predating_join_is_dropped() {
1250        let owner = Keys::generate();
1251        let admin = Keys::generate();
1252        let member = Keys::generate();
1253        let (_tmp, _g, channel, cite) = db_roster_channel(&owner, &admin.public_key());
1254        let mut state = ChatState::new();
1255        // A fully-authorized kick whose inner timestamp PREDATES this account's join (ms=1 → created_at 0)
1256        // is ignored, so a re-accepted invite isn't undone by a stale kick replayed from history.
1257        let kick = seal_kick(&channel, &admin, &member.public_key().to_hex(), 1, Some(&cite));
1258        assert!(process_incoming(&mut state, &kick, &channel, &member.public_key()).is_none(),
1259            "a kick older than the current join is dropped");
1260        crate::db::close_database();
1261    }
1262
1263    #[test]
1264    fn webxdc_signals_parse_ad_and_left_and_reject_garbage() {
1265        use crate::stored_event::event_kind;
1266        use nostr_sdk::prelude::ToBech32;
1267        let mut state = ChatState::new();
1268        let alice = Keys::generate();
1269        let c = test_channel();
1270        let viewer = Keys::generate();
1271        let mk = |content: &str, ms: u64| {
1272            let inner = build_inner_typed(alice.public_key(), &c.id, c.epoch, event_kind::COMMUNITY_WEBXDC, content, ms, None, &[])
1273                .finalize(&alice).unwrap();
1274            seal_with_signed_inner(&Keys::generate(), &inner, &c.key, &c.id, c.epoch).unwrap()
1275        };
1276        let topic = crate::webxdc::mint_topic_id("game-hash", "sender");
1277
1278        // Advertisement: topic + addr surface, author attributed.
1279        let ad = serde_json::json!({ "op": "ad", "topic": topic, "addr": "BASE32NODEADDR" }).to_string();
1280        match process_incoming(&mut state, &mk(&ad, 1), &c, &viewer.public_key()) {
1281            Some(IncomingEvent::WebxdcPeer { npub, topic_id, node_addr, .. }) => {
1282                assert_eq!(npub, alice.public_key().to_bech32().unwrap(), "player is the inner author");
1283                assert_eq!(topic_id, topic);
1284                assert_eq!(node_addr.as_deref(), Some("BASE32NODEADDR"));
1285            }
1286            _ => panic!("expected a webxdc advertisement"),
1287        }
1288
1289        // Peer-left: no addr.
1290        let left = serde_json::json!({ "op": "left", "topic": topic }).to_string();
1291        match process_incoming(&mut state, &mk(&left, 2), &c, &viewer.public_key()) {
1292            Some(IncomingEvent::WebxdcPeer { node_addr, .. }) => {
1293                assert!(node_addr.is_none(), "peer-left carries no addr");
1294            }
1295            _ => panic!("expected a webxdc peer-left"),
1296        }
1297
1298        // Own echo is dropped — the local realtime layer already tracks itself.
1299        assert!(
1300            process_incoming(&mut state, &mk(&ad, 3), &c, &alice.public_key()).is_none(),
1301            "own webxdc signal must be ignored"
1302        );
1303
1304        // Garbage: malformed topic (author-controlled), unknown op, ad missing addr, non-JSON.
1305        let bad_topic = serde_json::json!({ "op": "ad", "topic": "../../etc", "addr": "X" }).to_string();
1306        assert!(process_incoming(&mut state, &mk(&bad_topic, 4), &c, &viewer.public_key()).is_none());
1307        let bad_op = serde_json::json!({ "op": "explode", "topic": topic }).to_string();
1308        assert!(process_incoming(&mut state, &mk(&bad_op, 5), &c, &viewer.public_key()).is_none());
1309        let no_addr = serde_json::json!({ "op": "ad", "topic": topic }).to_string();
1310        assert!(process_incoming(&mut state, &mk(&no_addr, 6), &c, &viewer.public_key()).is_none());
1311        assert!(process_incoming(&mut state, &mk("not json", 7), &c, &viewer.public_key()).is_none());
1312    }
1313
1314    #[test]
1315    fn typing_indicator_parses_drops_own_echo_and_rejects_garbage() {
1316        use crate::stored_event::event_kind;
1317        use nostr_sdk::prelude::ToBech32;
1318        let mut state = ChatState::new();
1319        let alice = Keys::generate();
1320        let c = test_channel();
1321        let viewer = Keys::generate();
1322        let mk = |content: &str, ms: u64| {
1323            let inner = build_inner_typed(alice.public_key(), &c.id, c.epoch, event_kind::COMMUNITY_TYPING, content, ms, None, &[])
1324                .finalize(&alice).unwrap();
1325            seal_with_signed_inner(&Keys::generate(), &inner, &c.key, &c.id, c.epoch).unwrap()
1326        };
1327        let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_secs();
1328
1329        // A "typing" signal from another member surfaces, attributed to the inner author, with a
1330        // receiver-computed near-future `until` (not the sender's clock).
1331        match process_incoming(&mut state, &mk("typing", 1), &c, &viewer.public_key()) {
1332            Some(IncomingEvent::Typing { npub, until }) => {
1333                assert_eq!(npub, alice.public_key().to_bech32().unwrap(), "typer is the inner author");
1334                assert!(until >= now && until <= now + 31, "until is receiver-computed (~now + 30s)");
1335            }
1336            _ => panic!("expected a typing indicator"),
1337        }
1338
1339        // Own echo is dropped — we never show ourselves typing.
1340        assert!(
1341            process_incoming(&mut state, &mk("typing", 2), &c, &alice.public_key()).is_none(),
1342            "own typing signal must be ignored"
1343        );
1344
1345        // Wrong content (a 3311 carrying anything but "typing") is rejected.
1346        assert!(process_incoming(&mut state, &mk("nope", 3), &c, &viewer.public_key()).is_none());
1347    }
1348
1349    #[test]
1350    fn presence_announcements_parse_join_and_leave() {
1351        use crate::stored_event::event_kind;
1352        let mut state = ChatState::new();
1353        let alice = Keys::generate();
1354        let c = test_channel();
1355        let viewer = Keys::generate();
1356        let mk = |content: &str, ms: u64| {
1357            let inner = build_inner_typed(alice.public_key(), &c.id, c.epoch, event_kind::COMMUNITY_PRESENCE, content, ms, None, &[])
1358                .finalize(&alice).unwrap();
1359            seal_with_signed_inner(&Keys::generate(), &inner, &c.key, &c.id, c.epoch).unwrap()
1360        };
1361        match process_incoming(&mut state, &mk("join", 1), &c, &viewer.public_key()) {
1362            Some(IncomingEvent::Presence { npub, joined, .. }) => {
1363                assert!(joined, "content 'join' → joined");
1364                assert_eq!(npub, alice.public_key().to_bech32().unwrap(), "announcer is the inner author");
1365            }
1366            _ => panic!("expected a join presence"),
1367        }
1368        match process_incoming(&mut state, &mk("leave", 2), &c, &viewer.public_key()) {
1369            Some(IncomingEvent::Presence { joined, invited_by, .. }) => {
1370                assert!(!joined, "content 'leave' → not joined");
1371                assert!(invited_by.is_none(), "a plain leave carries no attribution");
1372            }
1373            _ => panic!("expected a leave presence"),
1374        }
1375        // attributed join: content is `{"by":"<npub>","l":"<label>"}` → invited_by/label surface
1376        // (only when `by` is a REAL pubkey — a forged non-npub is dropped).
1377        let jean = Keys::generate().public_key().to_bech32().unwrap();
1378        let attributed = serde_json::json!({ "by": jean, "l": "Reddit" }).to_string();
1379        match process_incoming(&mut state, &mk(&attributed, 3), &c, &viewer.public_key()) {
1380            Some(IncomingEvent::Presence { joined, invited_by, invited_label, .. }) => {
1381                assert!(joined, "an attributed-join JSON is still a join");
1382                assert_eq!(invited_by.as_deref(), Some(jean.as_str()), "valid inviter npub surfaced");
1383                assert_eq!(invited_label.as_deref(), Some("Reddit"), "link label surfaced");
1384            }
1385            _ => panic!("expected an attributed join presence"),
1386        }
1387        // A forged non-pubkey `by` is dropped (no arbitrary text leaks into attribution).
1388        let forged = serde_json::json!({ "by": "haha not an npub", "l": "x" }).to_string();
1389        match process_incoming(&mut state, &mk(&forged, 4), &c, &viewer.public_key()) {
1390            Some(IncomingEvent::Presence { invited_by, .. }) => assert!(invited_by.is_none(), "forged inviter dropped"),
1391            _ => panic!("expected a join presence"),
1392        }
1393    }
1394
1395    #[test]
1396    fn leave_presence_authored_by_local_npub_yields_self_left() {
1397        use crate::stored_event::event_kind;
1398        // a leave-presence whose inner author IS the local npub is a self-removal → SelfLeft, so the
1399        // leave propagates to every device. A DB-backed channel is needed (community_id resolution).
1400        let owner = Keys::generate();
1401        let admin = Keys::generate();
1402        let (_tmp, _g, channel, _cite) = db_roster_channel(&owner, &admin.public_key());
1403        let mut state = ChatState::new();
1404        // A FRESH self-leave (newer than the join) is the teardown case — build it after the
1405        // community's recorded join time so the staleness gate treats it as a real SelfLeft.
1406        let cid = crate::db::community::community_id_for_channel(&channel.id.to_hex()).unwrap().unwrap();
1407        let cid_bytes = crate::community::CommunityId(crate::simd::hex::hex_to_bytes_32(&cid));
1408        let leave_ms = crate::db::community::community_created_at_ms(&cid_bytes).unwrap_or(0) + 10_000;
1409        let leave = {
1410            let inner = build_inner_typed(owner.public_key(), &channel.id, channel.epoch, event_kind::COMMUNITY_PRESENCE, "leave", leave_ms, None, &[])
1411                .finalize(&owner).unwrap();
1412            seal_with_signed_inner(&Keys::generate(), &inner, &channel.key, &channel.id, channel.epoch).unwrap()
1413        };
1414        match process_incoming(&mut state, &leave, &channel, &owner.public_key()) {
1415            Some(IncomingEvent::SelfLeft { community_id }) => assert!(!community_id.is_empty()),
1416            _ => panic!("expected SelfLeft"),
1417        }
1418        crate::db::close_database();
1419    }
1420
1421    #[test]
1422    fn leave_presence_authored_by_another_npub_stays_a_plain_leave() {
1423        use crate::stored_event::event_kind;
1424        use nostr_sdk::prelude::ToBech32;
1425        // A leave by SOMEONE ELSE is just a member-list departure, NOT a self-removal.
1426        let owner = Keys::generate();
1427        let admin = Keys::generate();
1428        let other = Keys::generate();
1429        let (_tmp, _g, channel, _cite) = db_roster_channel(&owner, &admin.public_key());
1430        let mut state = ChatState::new();
1431        let leave = {
1432            let inner = build_inner_typed(other.public_key(), &channel.id, channel.epoch, event_kind::COMMUNITY_PRESENCE, "leave", 2, None, &[])
1433                .finalize(&other).unwrap();
1434            seal_with_signed_inner(&Keys::generate(), &inner, &channel.key, &channel.id, channel.epoch).unwrap()
1435        };
1436        // LOCAL viewer is the owner; the leave is `other`'s → plain Presence{joined:false}.
1437        match process_incoming(&mut state, &leave, &channel, &owner.public_key()) {
1438            Some(IncomingEvent::Presence { npub, joined, .. }) => {
1439                assert!(!joined);
1440                assert_eq!(npub, other.public_key().to_bech32().unwrap());
1441            }
1442            _ => panic!("expected plain leave Presence"),
1443        }
1444        crate::db::close_database();
1445    }
1446
1447    #[test]
1448    fn self_delete_still_applies_after_keep_keys_teardown() {
1449        // after a self-removal teardown that RETAINS the epoch keys, a 3305 self-delete of one's own
1450        // past message still works — the channel is reconstructed from the retained key and the delete opens.
1451        let owner = Keys::generate();
1452        let admin = Keys::generate();
1453        let (_tmp, _g, channel, _cite) = db_roster_channel(&owner, &admin.public_key());
1454        let cid = crate::db::community::community_id_for_channel(&channel.id.to_hex()).unwrap().unwrap();
1455        let chan_hex = channel.id.to_hex();
1456        let epoch = channel.epoch.0;
1457
1458        // The local user posts a message under the channel's current epoch.
1459        let mut state = ChatState::new();
1460        let target = ingest_msg_in(&mut state, &channel, &owner, "mine", 1, &owner);
1461
1462        // Self-removal teardown that retains keys, then reconstruct the channel from the RETAINED key.
1463        crate::db::community::delete_community_retain_keys(&cid).unwrap();
1464        let retained = crate::db::community::held_epoch_key(&cid, &chan_hex, epoch).unwrap()
1465            .expect("epoch key retained after keep-keys teardown");
1466        let mut rebuilt = channel.clone();
1467        rebuilt.key = ChannelKey(retained);
1468        rebuilt.epoch = Epoch(epoch);
1469
1470        // A 3305 self-delete authored by the local user opens under the retained key and removes the message.
1471        let del = seal_hide(&rebuilt, &owner, &target, 2, None);
1472        match process_incoming(&mut state, &del, &rebuilt, &owner.public_key()) {
1473            Some(IncomingEvent::Removed { target_id }) => assert_eq!(target_id, target),
1474            _ => panic!("expected the self-delete to apply under the retained key"),
1475        }
1476        crate::db::close_database();
1477    }
1478
1479    #[test]
1480    fn banned_author_events_are_dropped_including_presence() {
1481        use crate::stored_event::event_kind;
1482        let mut state = ChatState::new();
1483        let alice = Keys::generate(); // will be banned
1484        let bob = Keys::generate();
1485        let mut c = test_channel();
1486        c.banned = vec![alice.public_key()];
1487
1488        // A banned author's message is dropped before any STATE mutation.
1489        let spam = seal_message(&alice, &c.key, &c.id, c.epoch, "spam", 1).unwrap();
1490        assert!(process_incoming(&mut state, &spam, &c, &bob.public_key()).is_none(), "banned message dropped");
1491
1492        // A banned author's PRESENCE is dropped too (the anti-memberlist must hide them entirely).
1493        let pres_inner = build_inner_typed(alice.public_key(), &c.id, c.epoch, event_kind::COMMUNITY_PRESENCE, "join", 2, None, &[])
1494            .finalize(&alice).unwrap();
1495        let pres = seal_with_signed_inner(&Keys::generate(), &pres_inner, &c.key, &c.id, c.epoch).unwrap();
1496        assert!(process_incoming(&mut state, &pres, &c, &bob.public_key()).is_none(), "banned presence dropped");
1497
1498        // A non-banned author is unaffected.
1499        let ok = seal_message(&bob, &c.key, &c.id, c.epoch, "hi", 3).unwrap();
1500        assert!(matches!(process_incoming(&mut state, &ok, &c, &bob.public_key()), Some(IncomingEvent::NewMessage(_))), "non-banned applied");
1501    }
1502
1503    #[test]
1504    fn cooperative_delete_applies_after_message_in_batch_order() {
1505        use crate::stored_event::event_kind;
1506        let mut state = ChatState::new();
1507        let alice = Keys::generate();
1508        let c = test_channel();
1509
1510        // A 3300 message and its author's 3305 delete, fed as ONE batch with the delete listed
1511        // first — process_channel_batch must ingest the message (pass 1) before the delete
1512        // (pass 2), so the tombstone lands on a present target.
1513        let msg_outer = seal_message(&alice, &c.key, &c.id, c.epoch, "bye", 1).unwrap();
1514        let opened = open_message(&msg_outer, &c.key, &c.id, c.epoch).unwrap();
1515        let inner_id = opened.message_id.to_hex();
1516        let del_outer = seal_typed(&alice, event_kind::COMMUNITY_DELETE, "", 2, &inner_id);
1517
1518        let applied = process_channel_batch(&mut state, &[del_outer, msg_outer], &c, &alice.public_key());
1519        assert!(applied.iter().any(|e| matches!(e, IncomingEvent::NewMessage(_))));
1520        assert!(applied.iter().any(|e| matches!(e, IncomingEvent::Removed { .. })));
1521        assert!(state.find_message(&inner_id).is_none(), "delete applied despite arriving first");
1522    }
1523
1524    #[test]
1525    fn build_message_sets_mine_and_author() {
1526        let me = Keys::generate();
1527        let opened = opened_from(&me, "hello", 4242);
1528        let msg = build_message(&opened, &me.public_key());
1529        assert_eq!(msg.content, "hello");
1530        assert_eq!(msg.at, 4242);
1531        assert!(msg.mine, "author == me → mine");
1532        assert_eq!(msg.npub, me.public_key().to_bech32().ok());
1533        assert_eq!(msg.id, opened.message_id.to_hex());
1534
1535        // A message from someone else is not mine.
1536        let other_view = build_message(&opened, &Keys::generate().public_key());
1537        assert!(!other_view.mine);
1538    }
1539
1540    #[test]
1541    fn ingest_creates_community_chat_and_adds_message() {
1542        let mut state = ChatState::new();
1543        let alice = Keys::generate();
1544        let opened = opened_from(&alice, "gm", 1);
1545
1546        assert!(ingest_message(&mut state, &opened, &alice.public_key()).is_some());
1547        // A Community chat now exists, keyed by the channel id, typed Community.
1548        let chat = state.chats.iter().find(|c| c.id == opened.channel_id.to_hex()).expect("chat");
1549        assert!(chat.is_community(), "channel chat must be ChatType::Community");
1550    }
1551
1552    #[test]
1553    fn process_incoming_ingests_valid_drops_foreign() {
1554        let mut state = ChatState::new();
1555        let alice = Keys::generate();
1556        let key = ChannelKey([0x33u8; 32]);
1557        let chan = ChannelId([0x44u8; 32]);
1558        let channel = Channel { id: chan, key: key.clone(), epoch: Epoch(0), name: "g".into(), banned: Vec::new(), protected: Vec::new(), roster: Default::default(), epoch_keys: Vec::new(), dissolved: false };
1559
1560        // A valid event for this channel lands.
1561        let outer = seal_message(&alice, &key, &chan, Epoch(0), "real", 1).unwrap();
1562        assert!(process_incoming(&mut state, &outer, &channel, &alice.public_key()).is_some());
1563        assert!(state.chats.iter().any(|c| c.is_community()));
1564
1565        // An event for a DIFFERENT channel (wrong key) is dropped, no chat created.
1566        let other_key = ChannelKey([0x99u8; 32]);
1567        let other_chan = ChannelId([0xaau8; 32]);
1568        let foreign = seal_message(&alice, &other_key, &other_chan, Epoch(0), "nope", 1).unwrap();
1569        assert!(process_incoming(&mut state, &foreign, &channel, &alice.public_key()).is_none());
1570        assert_eq!(state.chats.iter().filter(|c| c.is_community()).count(), 1);
1571    }
1572
1573    #[test]
1574    fn ingest_dedups_on_message_id() {
1575        let mut state = ChatState::new();
1576        let alice = Keys::generate();
1577        let opened = opened_from(&alice, "once", 1);
1578
1579        assert!(ingest_message(&mut state, &opened, &alice.public_key()).is_some(), "first add");
1580        assert!(ingest_message(&mut state, &opened, &alice.public_key()).is_none(), "duplicate not re-added");
1581        // Still exactly one Community chat.
1582        assert_eq!(state.chats.iter().filter(|c| c.is_community()).count(), 1);
1583    }
1584
1585    #[test]
1586    fn dedup_keys_on_inner_id_across_distinct_outer_events() {
1587        // The real invariant: a re-broadcast of the SAME inner message (same
1588        // inner id) wrapped in a DIFFERENT outer event must dedup. Sealing twice with
1589        // identical params yields the same inner event (created_at is derived from
1590        // ms, so it's deterministic) but distinct outer events (fresh ephemeral key +
1591        // nonce). The second must NOT add a second message.
1592        let mut state = ChatState::new();
1593        let alice = Keys::generate();
1594        let key = ChannelKey([0x33u8; 32]);
1595        let chan = ChannelId([0x44u8; 32]);
1596        let channel = Channel { id: chan, key: key.clone(), epoch: Epoch(0), name: "g".into(), banned: Vec::new(), protected: Vec::new(), roster: Default::default(), epoch_keys: Vec::new(), dissolved: false };
1597
1598        let outer_a = seal_message(&alice, &key, &chan, Epoch(0), "dup", 7).unwrap();
1599        let outer_b = seal_message(&alice, &key, &chan, Epoch(0), "dup", 7).unwrap();
1600        assert_ne!(outer_a.id, outer_b.id, "distinct outer events (fresh ephemeral + nonce)");
1601
1602        assert!(process_incoming(&mut state, &outer_a, &channel, &alice.public_key()).is_some());
1603        assert!(
1604            process_incoming(&mut state, &outer_b, &channel, &alice.public_key()).is_none(),
1605            "same inner message id must dedup despite a different outer event"
1606        );
1607    }
1608
1609    #[test]
1610    fn route_incoming_routes_by_pseudonym() {
1611        let mut state = ChatState::new();
1612        let alice = Keys::generate();
1613        let key = ChannelKey([0x33u8; 32]);
1614        let chan = ChannelId([0x44u8; 32]);
1615        let channel = Channel { id: chan, key: key.clone(), epoch: Epoch(0), name: "g".into(), banned: Vec::new(), protected: Vec::new(), roster: Default::default(), epoch_keys: Vec::new(), dissolved: false };
1616
1617        // Routing table keyed by the channel's epoch pseudonym.
1618        let mut routes = HashMap::new();
1619        routes.insert(channel_pseudonym(&key, &chan, Epoch(0)).to_hex(), channel.clone());
1620
1621        // An event tagged with that pseudonym routes + lands.
1622        let outer = seal_message(&alice, &key, &chan, Epoch(0), "routed", 1).unwrap();
1623        assert!(route_incoming(&mut state, &outer, &routes, &alice.public_key()).is_some());
1624
1625        // An event for an UNROUTED pseudonym (different channel) is ignored.
1626        let other_key = ChannelKey([0x55u8; 32]);
1627        let other_chan = ChannelId([0x66u8; 32]);
1628        let unrouted = seal_message(&alice, &other_key, &other_chan, Epoch(0), "x", 1).unwrap();
1629        assert!(route_incoming(&mut state, &unrouted, &routes, &alice.public_key()).is_none());
1630    }
1631
1632    #[test]
1633    fn ms_none_falls_back_to_created_at() {
1634        // Directly construct an OpenedMessage with no ms tag → `at` = created_at*1000.
1635        use nostr_sdk::prelude::{EventId, Timestamp, Tags};
1636        let author = Keys::generate();
1637        let opened = OpenedMessage {
1638            message_id: EventId::from_byte_array([0u8; 32]),
1639            author: author.public_key(),
1640            content: "no ms".into(),
1641            channel_id: ChannelId([1u8; 32]),
1642            epoch: Epoch(0),
1643            ms: None,
1644            created_at: Timestamp::from_secs(1500),
1645            kind: 3300,
1646            attachments: vec![],
1647            citation: None,
1648            wrapper_id: EventId::from_byte_array([0u8; 32]),
1649            tags: Tags::new(),
1650        };
1651        assert_eq!(build_message(&opened, &author.public_key()).at, 1_500_000);
1652    }
1653}