1use nostr_sdk::prelude::PublicKey;
12use nostr_sdk::prelude::ToBech32;
13
14use super::super::attachments::attachments_from_tags;
15use super::chat::{self, ChatEvent};
16use super::community::CommunityV2;
17use super::guestbook::{self, GuestbookEntry};
18use super::stream;
19use crate::event_handler::InboundEventHandler;
20use crate::state::ChatState;
21use crate::types::{EmojiTag, Message, Reaction};
22
23pub fn chat_message_to_message(
28 opened: &stream::OpenedStream,
29 reply_to: &Option<chat::ReplyRef>,
30 emoji: &[(String, String)],
31 my_pubkey: &PublicKey,
32) -> Message {
33 let (replied_to, replied_to_npub) = match reply_to {
34 Some(r) => (
35 crate::simd::hex::bytes_to_hex_32(&r.id),
36 r.author.and_then(|a| a.to_bech32().ok()),
37 ),
38 None => (String::new(), None),
39 };
40 let attachments = attachments_from_tags(opened.rumor.tags.iter(), &crate::db::get_download_dir());
41 Message {
42 id: opened.rumor_id.to_hex(),
43 content: super::super::attachments::strip_attachment_urls(&opened.rumor.content, &attachments),
45 replied_to,
46 replied_to_npub,
47 at: opened.at_ms,
48 mine: opened.author == *my_pubkey,
49 npub: opened.author.to_bech32().ok(),
50 attachments,
51 emoji_tags: emoji
52 .iter()
53 .map(|(shortcode, url)| EmojiTag { shortcode: shortcode.clone(), url: url.clone() })
54 .collect(),
55 addressed_bots: crate::bot_interface::addressed_bots(opened.rumor.tags.iter()),
56 wrapper_event_id: Some(opened.wrapper_id.to_hex()),
57 expiration: chat::message_expiration(&opened.rumor),
59 ..Default::default()
60 }
61}
62
63fn author_is_banned_here(channel_id: &str, author: &PublicKey) -> bool {
67 let Ok(Some(cid_hex)) = crate::db::community::community_id_for_channel(channel_id) else {
68 return false;
69 };
70 crate::db::community::is_author_banned(&cid_hex, author)
71}
72
73fn moderation_delete_authorized(
78 channel_id: &str,
79 deleter: &PublicKey,
80 author: &PublicKey,
81 tags: &nostr_sdk::prelude::Tags,
82) -> bool {
83 let Ok(Some(cid_hex)) = crate::db::community::community_id_for_channel(channel_id) else {
84 return false;
85 };
86 if crate::db::community::get_community_dissolved(&cid_hex).unwrap_or(false) {
87 return false;
88 }
89 let Some(owner_hex) = crate::community::moderation::owner_hex(&cid_hex) else {
90 return false; };
92 let deleter_hex = deleter.to_hex();
93 let citation = crate::community::edition::AuthorityCitation::from_tags(tags);
94 if !super::service::citation_is_synced(&cid_hex, &owner_hex, &deleter_hex, citation.as_ref()) {
95 return false;
96 }
97 let roster = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
98 crate::community::moderation::can_hide(Some(&owner_hex), &roster, &deleter_hex, &author.to_hex())
99}
100
101pub enum ChatPersist {
106 New(Message),
108 Updated { message: Message, edit_event: Option<Box<crate::stored_event::StoredEvent>> },
112 Removed(String),
114 ReactionRemoved { reaction_id: String, message: Message },
118}
119
120pub fn apply_chat_to_state(state: &mut ChatState, event: &ChatEvent, channel_id: &str, my_pubkey: &PublicKey) -> Option<ChatPersist> {
127 if author_is_banned_here(channel_id, &event.opened().author) {
134 return None;
135 }
136 match event {
137 ChatEvent::Message { opened, reply_to, emoji } => {
138 let msg = chat_message_to_message(opened, reply_to, emoji, my_pubkey);
139 if crate::db::events::event_exists(&msg.id).unwrap_or(false) {
142 return None;
143 }
144 state.ensure_community_chat(channel_id);
145 state.add_message_to_chat(channel_id, &msg);
149 Some(ChatPersist::New(msg))
150 }
151 ChatEvent::Reaction { opened, target, emoji, emoji_url, .. } => {
152 let target_id = crate::simd::hex::bytes_to_hex_32(target);
153 if !matches!(state.find_message(&target_id), Some((chat, _)) if chat.id == channel_id) {
157 return None;
158 }
159 let reaction = Reaction {
160 id: opened.rumor_id.to_hex(),
161 reference_id: target_id.clone(),
162 author_id: opened.author.to_bech32().unwrap_or_else(|_| opened.author.to_hex()),
166 emoji: emoji.clone(),
167 emoji_url: emoji_url.clone(),
168 };
169 let (_c, added) = state.add_reaction_to_message(&target_id, reaction)?;
170 added.then(|| state.find_message(&target_id).map(|(_c, m)| ChatPersist::Updated { message: m, edit_event: None }))?
171 }
172 ChatEvent::Edit { opened, target, new_content } => {
173 if crate::db::events::event_exists(&opened.rumor_id.to_hex()).unwrap_or(false) {
178 return None;
179 }
180 let target_id = crate::simd::hex::bytes_to_hex_32(target);
181 let editor_npub = opened.author.to_bech32().ok()?;
183 if !matches!(state.find_message(&target_id), Some((chat, m)) if chat.id == channel_id && m.npub.as_deref() == Some(editor_npub.as_str())) {
184 return None;
185 }
186 let edited_at = opened.at_ms;
189 let (_c, message) = state.update_message(&target_id, |m| m.apply_edit(new_content.clone(), edited_at, Vec::new()))?;
190 let edit_event = crate::stored_event::StoredEventBuilder::new()
192 .id(opened.rumor_id.to_hex())
193 .kind(crate::stored_event::event_kind::MESSAGE_EDIT)
194 .content(new_content.clone())
195 .reference_id(Some(target_id.clone()))
196 .created_at(edited_at / 1000)
197 .mine(opened.author == *my_pubkey)
198 .npub(opened.author.to_bech32().ok())
199 .build();
200 Some(ChatPersist::Updated { message, edit_event: Some(Box::new(edit_event)) })
201 }
202 ChatEvent::Delete { opened, target, .. } => {
203 let target_id = crate::simd::hex::bytes_to_hex_32(target);
204 if let Some((_chat, message_id, author_npub, _)) = state.find_reaction(&target_id) {
209 let reactor_ok = PublicKey::parse(&author_npub).map(|pk| pk == opened.author).unwrap_or(false);
210 if !reactor_ok {
211 return None;
212 }
213 return state
214 .remove_reaction_from_message(&message_id, &target_id)
215 .map(|(_cid, message)| ChatPersist::ReactionRemoved { reaction_id: target_id, message });
216 }
217 let resident = state.find_message(&target_id).and_then(|(_, m)| m.npub.clone());
223 let author_npub = match resident {
224 Some(n) => Some(n),
225 None => crate::db::events::event_author(&target_id).ok().flatten(),
226 };
227 let author = author_npub.as_deref().and_then(|n| PublicKey::parse(n).ok())?;
228 let authorized = author == opened.author
229 || moderation_delete_authorized(channel_id, &opened.author, &author, &opened.rumor.tags);
230 if !authorized {
231 return None;
232 }
233 let _ = state.remove_message(&target_id);
236 Some(ChatPersist::Removed(target_id))
237 }
238 ChatEvent::Typing { .. } | ChatEvent::Webxdc { .. } => None,
239 }
240}
241
242pub async fn persist_chat_event(
248 event: &ChatEvent,
249 channel_id: &str,
250 my_pubkey: &PublicKey,
251 session: &crate::state::SessionGuard,
252) -> Option<ChatPersist> {
253 let outcome = {
254 let mut st = crate::state::STATE.lock().await;
255 if !session.is_valid() {
257 return None;
258 }
259 apply_chat_to_state(&mut st, event, channel_id, my_pubkey)
260 }?;
261 let outcome = match outcome {
265 ChatPersist::New(mut m) => {
266 if !m.replied_to.is_empty() {
267 let _ = crate::db::events::populate_reply_context(&mut m).await;
268 }
269 ChatPersist::New(m)
270 }
271 o => o,
272 };
273 if !session.is_valid() {
275 return None;
276 }
277 persist_chat(channel_id, &outcome).await;
278 Some(outcome)
279}
280
281pub async fn persist_chat(channel_id: &str, outcome: &ChatPersist) {
285 match outcome {
286 ChatPersist::New(m) => {
287 let _ = crate::db::events::save_message(channel_id, m).await;
288 }
289 ChatPersist::Updated { message, edit_event } => match edit_event {
292 Some(ev) => {
293 let mut ev = (**ev).clone();
294 if let Ok(cid) = crate::db::id_cache::get_or_create_chat_id(channel_id) {
297 ev.chat_id = cid;
298 }
299 let _ = crate::db::events::save_event(&ev).await;
300 }
301 None => {
302 let _ = crate::db::events::save_message(channel_id, message).await;
303 }
304 },
305 ChatPersist::Removed(id) => {
306 let _ = crate::db::events::delete_event(id).await;
307 }
308 ChatPersist::ReactionRemoved { reaction_id, message } => {
309 let _ = crate::db::events::delete_event(reaction_id).await;
310 let _ = crate::db::events::save_message(channel_id, message).await;
311 }
312 }
313}
314
315#[derive(Debug, Clone)]
317pub enum DispatchedV2 {
318 Chat { channel_id: String, event: Box<ChatEvent> },
324 Typing { channel_id: String, npub: String },
326 Presence { npub: String, joined: bool },
328 Kick { target: PublicKey },
332 Control { community_id: String },
337 Rekey { community_id: String },
341 Dissolved { community_id: String },
344 Ignored,
347 NotOurs,
349}
350
351pub fn dispatch_wrap(
357 wrap: &nostr_sdk::prelude::Event,
358 community: &CommunityV2,
359 my_pubkey: &PublicKey,
360 handler: &dyn InboundEventHandler,
361) -> DispatchedV2 {
362 for ch in &community.channels {
364 if ch.private && ch.key.is_none() {
367 continue;
368 }
369 let (secret, epoch) = community.channel_secret(ch);
370 let group = super::derive::channel_group_key(&secret, &ch.id, epoch);
371 if wrap.pubkey != group.pk() {
372 continue;
373 }
374 let Ok(event) = chat::open_chat_event(wrap, &group, &ch.id, epoch) else {
375 return DispatchedV2::NotOurs;
376 };
377 let channel_id = crate::simd::hex::bytes_to_hex_32(&ch.id.0);
378 return dispatch_chat_event(event, &channel_id, my_pubkey, handler);
379 }
380
381 let gb = super::derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch);
383 if wrap.pubkey == gb.pk() {
384 if let Ok(opened) = stream::open_wrap(wrap, &gb) {
385 if let Ok(ev) = guestbook::parse_guestbook_event(&opened) {
386 return dispatch_guestbook(&ev, community, handler);
387 }
388 }
389 return DispatchedV2::Ignored;
390 }
391
392 if wrap.pubkey == super::realtime::control_author(community) {
396 return DispatchedV2::Control { community_id: crate::simd::hex::bytes_to_hex_32(&community.id().0) };
397 }
398
399 if super::realtime::rekey_authors(community).iter().any(|p| *p == wrap.pubkey) {
404 return DispatchedV2::Rekey { community_id: crate::simd::hex::bytes_to_hex_32(&community.id().0) };
405 }
406
407 if wrap.pubkey == super::derive::dissolved_group_key(community.id()).pk() {
410 if super::dissolution::verify_dissolved(wrap, &community.identity) {
411 return DispatchedV2::Dissolved { community_id: crate::simd::hex::bytes_to_hex_32(&community.id().0) };
412 }
413 return DispatchedV2::Ignored;
414 }
415
416 DispatchedV2::NotOurs
417}
418
419fn dispatch_chat_event(event: ChatEvent, channel_id: &str, my_pubkey: &PublicKey, handler: &dyn InboundEventHandler) -> DispatchedV2 {
420 match event {
421 ChatEvent::Typing { opened } => {
425 if author_is_banned_here(channel_id, &opened.author) {
426 return DispatchedV2::Ignored;
427 }
428 let npub = opened.author.to_bech32().unwrap_or_default();
429 let until = opened.at_ms / 1000 + 30;
430 handler.on_community_typing(channel_id, &npub, until);
431 DispatchedV2::Typing { channel_id: channel_id.to_string(), npub }
432 }
433 ChatEvent::Webxdc { opened } => {
437 if opened.author == *my_pubkey || author_is_banned_here(channel_id, &opened.author) {
438 return DispatchedV2::Ignored;
439 }
440 let Some((topic_id, node_addr)) = crate::webxdc::parse_peer_signal(&opened.rumor.content) else {
441 return DispatchedV2::Ignored;
442 };
443 let npub = opened.author.to_bech32().unwrap_or_default();
444 handler.on_community_webxdc(
445 channel_id,
446 &npub,
447 &topic_id,
448 node_addr.as_deref(),
449 &opened.rumor_id.to_hex(),
450 opened.at_ms / 1000,
451 );
452 DispatchedV2::Ignored
453 }
454 event => DispatchedV2::Chat { channel_id: channel_id.to_string(), event: Box::new(event) },
457 }
458}
459
460fn dispatch_guestbook(ev: &guestbook::GuestbookEvent, community: &CommunityV2, handler: &dyn InboundEventHandler) -> DispatchedV2 {
461 let suppressed = match &ev.entry {
469 GuestbookEntry::Join { member, .. } | GuestbookEntry::Leave { member, .. } => {
470 let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
471 crate::db::community::is_author_banned(&cid_hex, member)
472 }
473 _ => false,
474 };
475 let event_id = crate::simd::hex::bytes_to_hex_32(&ev.rumor_id);
479 let chat_id = community
482 .primary_channel()
483 .map(|c| crate::simd::hex::bytes_to_hex_32(&c.id.0))
484 .unwrap_or_default();
485 match &ev.entry {
486 GuestbookEntry::Join { member, at_ms, invited_by } => {
487 let npub = member.to_bech32().unwrap_or_default();
488 let (by, label) = match invited_by {
489 Some((c, l)) => (Some(c.as_str()), Some(l.as_str())),
490 None => (None, None),
491 };
492 if !suppressed {
493 handler.on_community_presence(&chat_id, &npub, true, &event_id, at_ms / 1000, by, label);
494 }
495 DispatchedV2::Presence { npub: npub.clone(), joined: true }
496 }
497 GuestbookEntry::Leave { member, at_ms } => {
498 let npub = member.to_bech32().unwrap_or_default();
499 if !suppressed {
500 handler.on_community_presence(&chat_id, &npub, false, &event_id, at_ms / 1000, None, None);
501 }
502 DispatchedV2::Presence { npub: npub.clone(), joined: false }
503 }
504 GuestbookEntry::Kick { target, .. } => DispatchedV2::Kick { target: *target },
507 GuestbookEntry::Snapshot { .. } => DispatchedV2::Ignored,
508 }
509}
510
511#[cfg(test)]
512mod tests {
513 use super::*;
514 use super::super::service;
515 use crate::community::transport::memory::MemoryRelay;
516 use crate::community::transport::Transport;
517 use nostr_sdk::prelude::Keys;
518 use std::sync::Mutex;
519
520 #[derive(Default)]
522 struct Recorder {
523 messages: Mutex<Vec<(String, Message)>>,
524 updates: Mutex<Vec<(String, String)>>,
525 removed: Mutex<Vec<(String, String)>>,
526 presence: Mutex<Vec<(String, bool)>>,
527 }
528 impl InboundEventHandler for Recorder {
529 fn on_community_message(&self, chat_id: &str, msg: &Message, _is_new: bool) {
530 self.messages.lock().unwrap().push((chat_id.to_string(), msg.clone()));
531 }
532 fn on_community_update(&self, chat_id: &str, target: &str, _msg: &Message) {
533 self.updates.lock().unwrap().push((chat_id.to_string(), target.to_string()));
534 }
535 fn on_community_removed(&self, chat_id: &str, target: &str) {
536 self.removed.lock().unwrap().push((chat_id.to_string(), target.to_string()));
537 }
538 fn on_community_presence(&self, _c: &str, npub: &str, joined: bool, _e: &str, _a: u64, _b: Option<&str>, _l: Option<&str>) {
539 self.presence.lock().unwrap().push((npub.to_string(), joined));
540 }
541 }
542
543 fn init() -> (tempfile::TempDir, std::sync::MutexGuard<'static, ()>, Keys) {
544 let guard = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
545 crate::db::close_database();
546 crate::db::clear_id_caches();
547 let tmp = tempfile::tempdir().unwrap();
548 static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(90_000);
549 let n = N.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
550 const B: &[u8] = b"qpzry9x8gf2tvdw0s3jn54khce6mua7l";
551 let mut acct = String::from("npub1");
552 let mut v = n as usize;
553 for _ in 0..58 {
554 acct.push(B[v % 32] as char);
555 v = v / 32 + 7;
556 }
557 std::fs::create_dir_all(tmp.path().join(&acct)).unwrap();
558 crate::db::set_app_data_dir(tmp.path().to_path_buf());
559 crate::db::set_current_account(acct.clone()).unwrap();
560 crate::db::init_database(&acct).unwrap();
561 let _ = crate::state::take_nostr_client();
562 let me = Keys::generate();
563 crate::state::MY_SECRET_KEY.store_from_keys(&me, &[]);
564 crate::state::set_my_public_key(me.public_key());
565 (tmp, guard, me)
566 }
567
568 #[tokio::test]
569 async fn a_received_message_wrap_opens_then_fires_from_the_persist_outcome() {
570 use nostr_sdk::prelude::Timestamp;
571 let (_tmp, _guard, me) = init();
572 let relay = MemoryRelay::new();
573 let community = service::create_community(&relay, "In", vec!["wss://r".into()], None).await.unwrap();
574 let general = community.channels[0].id;
575 let cid = crate::simd::hex::bytes_to_hex_32(&general.0);
576
577 let member = Keys::generate();
580 let group = super::super::derive::channel_group_key(&community.community_root, &general, community.root_epoch);
581 let rumor = chat::build_message_rumor(member.public_key(), &general, community.root_epoch, "ping", None, &[], vec![], 5_000);
582 let (wrap, _) = chat::seal_chat_rumor(&rumor, &group, &member, Timestamp::from_secs(5), false).unwrap();
583
584 let rec = Recorder::default();
587 let dispatched = dispatch_wrap(&wrap, &community, &me.public_key(), &rec);
588 assert!(rec.messages.lock().unwrap().is_empty(), "no optimistic message callback");
589 let DispatchedV2::Chat { channel_id, event } = dispatched else {
590 panic!("a chat wrap dispatches as Chat");
591 };
592 assert_eq!(channel_id, cid);
593
594 let session = crate::state::SessionGuard::capture();
595 let outcome = persist_chat_event(&event, &channel_id, &me.public_key(), &session).await;
596 let Some(ChatPersist::New(msg)) = outcome else {
597 panic!("the first delivery persists as New");
598 };
599 assert_eq!(msg.content, "ping");
600 assert!(!msg.mine, "authored by the other member");
601
602 let (rewrap, _) = chat::seal_chat_rumor(&rumor, &group, &member, Timestamp::from_secs(6), false).unwrap();
605 assert_ne!(rewrap.id, wrap.id, "a re-wrap is a distinct outer event");
606 let DispatchedV2::Chat { event: dup, .. } = dispatch_wrap(&rewrap, &community, &me.public_key(), &rec) else {
607 panic!("the re-wrap still opens");
608 };
609 assert!(
610 persist_chat_event(&dup, &channel_id, &me.public_key(), &session).await.is_none(),
611 "a re-wrapped duplicate yields no outcome (nothing re-fires)"
612 );
613 }
614
615 #[tokio::test]
616 async fn a_guestbook_join_wrap_fires_presence() {
617 let (_tmp, _guard, me) = init();
618 let relay = MemoryRelay::new();
619 let community = service::create_community(&relay, "GB", vec!["wss://r".into()], None).await.unwrap();
621 let gb = super::super::derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch);
622 let q = crate::community::transport::Query { kinds: vec![stream::KIND_WRAP], authors: vec![gb.pk_hex()], ..Default::default() };
623 let wraps = relay.fetch(&q, &community.relays).await.unwrap();
624
625 let rec = Recorder::default();
626 for w in &wraps {
627 dispatch_wrap(w, &community, &me.public_key(), &rec);
628 }
629 let pres = rec.presence.lock().unwrap();
630 assert_eq!(pres.len(), 1, "the owner's genesis Join fires one presence");
631 assert!(pres[0].1, "it's a join");
632 assert_eq!(pres[0].0, me.public_key().to_bech32().unwrap());
633 }
634
635 #[tokio::test]
636 async fn v2_chat_events_persist_into_the_shared_store() {
637 let (_tmp, _guard, me) = init();
638 let relay = MemoryRelay::new();
639 let community = service::create_community(&relay, "Persist", vec!["wss://r".into()], None).await.unwrap();
640 let general = community.channels[0].id;
641 let cid = crate::simd::hex::bytes_to_hex_32(&general.0);
642 let group = super::super::derive::channel_group_key(&community.community_root, &general, community.root_epoch);
643 let me_hex = me.public_key().to_hex();
644
645 let msg_id = service::send_message(&relay, &community, &general, "persist me").await.unwrap();
646 service::send_reaction(&relay, &community, &general, &msg_id, &me_hex, super::super::kind::MESSAGE, "🔥", None).await.unwrap();
647
648 assert!(crate::db::events::event_exists(&msg_id).unwrap(), "the send echo persisted the message row");
651 let reacted = {
652 let st = crate::state::STATE.lock().await;
653 st.find_message(&msg_id).map(|(_, m)| m.reactions.iter().any(|r| r.emoji == "🔥")).unwrap_or(false)
654 };
655 assert!(reacted, "the send echo aggregated the reaction onto the stored message");
656
657 let q = crate::community::transport::Query { kinds: vec![stream::KIND_WRAP], authors: vec![group.pk_hex()], ..Default::default() };
660 let wraps = relay.fetch(&q, &community.relays).await.unwrap();
661 let mut events: Vec<ChatEvent> = wraps.iter().filter_map(|w| chat::open_chat_event(w, &group, &general, community.root_epoch).ok()).collect();
662 events.sort_by_key(|e| e.opened().at_ms);
663 assert!(!events.is_empty());
664 for ev in &events {
665 let outcome = {
666 let mut st = crate::state::STATE.lock().await;
667 apply_chat_to_state(&mut st, ev, &cid, &me.public_key())
668 };
669 assert!(outcome.is_none(), "the relay echo of an already-echoed send dedups");
670 }
671 }
672
673 #[tokio::test]
674 async fn a_v2_edit_persists_as_a_folded_edit_event() {
675 let (_tmp, _guard, me) = init();
676 let relay = MemoryRelay::new();
677 let community = service::create_community(&relay, "Edit", vec!["wss://r".into()], None).await.unwrap();
678 let general = community.channels[0].id;
679 let cid = crate::simd::hex::bytes_to_hex_32(&general.0);
680 let group = super::super::derive::channel_group_key(&community.community_root, &general, community.root_epoch);
681
682 let msg_id = service::send_message(&relay, &community, &general, "original").await.unwrap();
683 service::send_edit(&relay, &community, &general, &msg_id, "edited!").await.unwrap();
684
685 let q = crate::community::transport::Query { kinds: vec![stream::KIND_WRAP], authors: vec![group.pk_hex()], ..Default::default() };
687 let wraps = relay.fetch(&q, &community.relays).await.unwrap();
688 let mut events: Vec<ChatEvent> = wraps.iter().filter_map(|w| chat::open_chat_event(w, &group, &general, community.root_epoch).ok()).collect();
689 events.sort_by_key(|e| (!matches!(e, ChatEvent::Message { .. }), e.opened().at_ms));
690 for ev in &events {
691 let outcome = {
692 let mut st = crate::state::STATE.lock().await;
693 apply_chat_to_state(&mut st, ev, &cid, &me.public_key())
694 };
695 if let Some(o) = outcome {
696 persist_chat(&cid, &o).await;
697 }
698 }
699
700 let content = {
701 let st = crate::state::STATE.lock().await;
702 st.find_message(&msg_id).map(|(_, m)| m.content)
703 };
704 assert_eq!(content.as_deref(), Some("edited!"), "the edit applied to the stored message");
705 let edit_id = events.iter().find_map(|e| matches!(e, ChatEvent::Edit { .. }).then(|| e.opened().rumor_id.to_hex())).unwrap();
706 assert!(crate::db::events::event_exists(&edit_id).unwrap(), "the MESSAGE_EDIT event is persisted (folds on reload)");
707 }
708
709 #[tokio::test]
710 async fn a_reaction_after_a_rekey_aggregates_onto_a_prior_epoch_message() {
711 use nostr_sdk::prelude::Timestamp;
717 let (_tmp, _guard, me) = init();
718 let relay = MemoryRelay::new();
719 let community = service::create_community(&relay, "Rekeyed", vec!["wss://r".into()], None).await.unwrap();
720 let general = community.channels[0].id;
721 let cid = crate::simd::hex::bytes_to_hex_32(&general.0);
722 let session = crate::state::SessionGuard::capture();
723
724 let member = Keys::generate();
726 let g0 = super::super::derive::channel_group_key(&community.community_root, &general, community.root_epoch);
727 let msg = chat::build_message_rumor(member.public_key(), &general, community.root_epoch, "before the rekey", None, &[], vec![], 5_000);
728 let msg_id = msg.id.unwrap().to_hex();
729 let (mw, _) = chat::seal_chat_rumor(&msg, &g0, &member, Timestamp::from_secs(5), false).unwrap();
730 let ev = chat::open_chat_event(&mw, &g0, &general, community.root_epoch).unwrap();
731 assert!(matches!(persist_chat_event(&ev, &cid, &me.public_key(), &session).await, Some(ChatPersist::New(_))));
732
733 let next = crate::community::Epoch(community.root_epoch.0 + 1);
736 let g1 = super::super::derive::channel_group_key(&community.community_root, &general, next);
737 let reaction = chat::build_reaction_rumor(member.public_key(), &general, next, &msg_id, &member.public_key().to_hex(), super::super::kind::MESSAGE, "🎉", None, 6_000);
738 let (rw, _) = chat::seal_chat_rumor(&reaction, &g1, &member, Timestamp::from_secs(6), false).unwrap();
739 let rev = chat::open_chat_event(&rw, &g1, &general, next).unwrap();
740 let outcome = persist_chat_event(&rev, &cid, &me.public_key(), &session).await;
741 assert!(matches!(outcome, Some(ChatPersist::Updated { .. })), "the cross-epoch reaction updates the target");
742
743 let reaction_author = {
744 let st = crate::state::STATE.lock().await;
745 st.find_message(&msg_id)
746 .and_then(|(_, m)| m.reactions.iter().find(|r| r.emoji == "🎉").map(|r| r.author_id.clone()))
747 };
748 let author = reaction_author.expect("the epoch-1 reaction aggregated onto the epoch-0 message");
749 assert_eq!(author, member.public_key().to_bech32().unwrap(), "reaction author is stored as bech32");
752 }
753
754 #[tokio::test]
755 async fn an_un_react_removes_the_reaction_for_receivers_and_only_for_its_reactor() {
756 use nostr_sdk::prelude::Timestamp;
757 let (_tmp, _guard, me) = init();
758 let relay = MemoryRelay::new();
759 let community = service::create_community(&relay, "UnReact", vec!["wss://r".into()], None).await.unwrap();
760 let general = community.channels[0].id;
761 let cid = crate::simd::hex::bytes_to_hex_32(&general.0);
762 let session = crate::state::SessionGuard::capture();
763 let (secret, epoch) = community.channel_secret(&community.channels[0]);
764 let group = super::super::derive::channel_group_key(&secret, &general, epoch);
765
766 let member = Keys::generate();
768 let msg = chat::build_message_rumor(member.public_key(), &general, epoch, "react to me", None, &[], vec![], 5_000);
769 let msg_id = msg.id.unwrap().to_hex();
770 let (mw, _) = chat::seal_chat_rumor(&msg, &group, &member, Timestamp::from_secs(5), false).unwrap();
771 let ev = chat::open_chat_event(&mw, &group, &general, epoch).unwrap();
772 assert!(matches!(persist_chat_event(&ev, &cid, &me.public_key(), &session).await, Some(ChatPersist::New(_))));
773
774 let reaction = chat::build_reaction_rumor(member.public_key(), &general, epoch, &msg_id, &member.public_key().to_hex(), super::super::kind::MESSAGE, "🔥", None, 6_000);
775 let reaction_id = reaction.id.unwrap().to_hex();
776 let (rw, _) = chat::seal_chat_rumor(&reaction, &group, &member, Timestamp::from_secs(6), false).unwrap();
777 let rev = chat::open_chat_event(&rw, &group, &general, epoch).unwrap();
778 assert!(matches!(persist_chat_event(&rev, &cid, &me.public_key(), &session).await, Some(ChatPersist::Updated { .. })));
779
780 let outsider = Keys::generate();
782 let forged = chat::build_delete_rumor(outsider.public_key(), &general, epoch, &reaction_id, super::super::kind::MESSAGE, 7_000, None);
783 let (fw, _) = chat::seal_chat_rumor(&forged, &group, &outsider, Timestamp::from_secs(7), false).unwrap();
784 let fev = chat::open_chat_event(&fw, &group, &general, epoch).unwrap();
785 assert!(persist_chat_event(&fev, &cid, &me.public_key(), &session).await.is_none(), "only the reactor revokes their reaction");
786
787 let revoke = chat::build_delete_rumor(member.public_key(), &general, epoch, &reaction_id, super::super::kind::MESSAGE, 8_000, None);
790 let (vw, _) = chat::seal_chat_rumor(&revoke, &group, &member, Timestamp::from_secs(8), false).unwrap();
791 let vev = chat::open_chat_event(&vw, &group, &general, epoch).unwrap();
792 assert!(matches!(persist_chat_event(&vev, &cid, &me.public_key(), &session).await, Some(ChatPersist::ReactionRemoved { .. })));
793 let (has_reaction, parent_alive) = {
794 let st = crate::state::STATE.lock().await;
795 (
796 st.find_reaction(&reaction_id).is_some(),
797 st.find_message(&msg_id).is_some(),
798 )
799 };
800 assert!(!has_reaction, "the chip is gone from STATE");
801 assert!(parent_alive, "the parent message survives an un-react");
802 assert!(!crate::db::events::event_exists(&reaction_id).unwrap(), "the kind-7 row is deleted");
803 }
804
805 #[tokio::test]
806 async fn a_guestbook_join_fires_presence_with_its_real_rumor_id() {
807 use nostr_sdk::prelude::Timestamp;
808 use std::sync::Mutex as StdMutex;
809 let (_tmp, _guard, me) = init();
810 let relay = MemoryRelay::new();
811 let community = service::create_community(&relay, "Pres", vec!["wss://r".into()], None).await.unwrap();
812
813 #[derive(Default)]
814 struct Capture(StdMutex<Vec<(String, bool, String)>>);
815 impl InboundEventHandler for Capture {
816 fn on_community_presence(&self, _chat_id: &str, npub: &str, joined: bool, event_id: &str, _at: u64, _by: Option<&str>, _label: Option<&str>) {
817 self.0.lock().unwrap().push((npub.into(), joined, event_id.into()));
818 }
819 }
820
821 let member = Keys::generate();
822 let gb = super::super::derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch);
823 let rumor = guestbook::build_join_rumor(member.public_key(), None, 5_000);
824 let (wrap, _) = super::super::guestbook::seal_guestbook_rumor(&rumor, &gb, &member, Timestamp::from_secs(5)).unwrap();
825 let expected_id = rumor.id.unwrap().to_hex();
826
827 let cap = Capture::default();
828 let out = dispatch_wrap(&wrap, &community, &me.public_key(), &cap);
829 assert!(matches!(out, DispatchedV2::Presence { joined: true, .. }));
830 let seen = cap.0.lock().unwrap().clone();
831 assert_eq!(seen.len(), 1);
832 assert_eq!(seen[0].0, member.public_key().to_bech32().unwrap());
833 assert_eq!(seen[0].2, expected_id, "presence carries the join's own rumor id");
836 }
837
838 #[tokio::test]
839 async fn a_guestbook_kick_dispatches_its_target_and_raises_no_presence_line() {
840 use nostr_sdk::prelude::Timestamp;
843 use std::sync::Mutex as StdMutex;
844 let (_tmp, _guard, me) = init();
845 let relay = MemoryRelay::new();
846 let community = service::create_community(&relay, "Kicks", vec!["wss://r".into()], None).await.unwrap();
847
848 #[derive(Default)]
849 struct Capture(StdMutex<usize>);
850 impl InboundEventHandler for Capture {
851 fn on_community_presence(&self, _c: &str, _n: &str, _j: bool, _e: &str, _a: u64, _b: Option<&str>, _l: Option<&str>) {
852 *self.0.lock().unwrap() += 1;
853 }
854 }
855
856 let target = Keys::generate();
857 let gb = super::super::derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch);
858 let rumor = guestbook::build_kick_rumor(me.public_key(), target.public_key(), None, 5_000);
859 let (wrap, _) = super::super::guestbook::seal_guestbook_rumor(&rumor, &gb, &me, Timestamp::from_secs(5)).unwrap();
860
861 let cap = Capture::default();
862 let out = dispatch_wrap(&wrap, &community, &me.public_key(), &cap);
863 match out {
864 DispatchedV2::Kick { target: t } => assert_eq!(t, target.public_key(), "the kick names its target"),
865 other => panic!("a Kick must reach the store, got {other:?}"),
866 }
867 assert_eq!(*cap.0.lock().unwrap(), 0, "a kick raises no presence line");
869 }
870
871 #[tokio::test]
872 async fn a_webxdc_peer_ad_fires_the_shared_handler_and_own_echo_drops() {
873 use nostr_sdk::prelude::Timestamp;
874 use std::sync::Mutex as StdMutex;
875 let (_tmp, _guard, me) = init();
876 let relay = MemoryRelay::new();
877 let community = service::create_community(&relay, "XDC", vec!["wss://r".into()], None).await.unwrap();
878 let general = community.channels[0].id;
879
880 #[derive(Default)]
881 struct Capture(StdMutex<Vec<(String, String, Option<String>)>>);
882 impl InboundEventHandler for Capture {
883 fn on_community_webxdc(&self, _chat_id: &str, npub: &str, topic_id: &str, node_addr: Option<&str>, _event_id: &str, _created_at: u64) {
884 self.0.lock().unwrap().push((npub.into(), topic_id.into(), node_addr.map(String::from)));
885 }
886 }
887
888 let topic = "B".repeat(52);
889 let content = crate::webxdc::peer_signal_content(&topic, Some("iroh:node/xyz"));
890 let (secret, epoch) = community.channel_secret(&community.channels[0]);
891 let group = super::super::derive::channel_group_key(&secret, &general, epoch);
892
893 let peer = Keys::generate();
895 let rumor = chat::build_webxdc_rumor(peer.public_key(), &general, epoch, &content, vec![], 5_000);
896 let (wrap, _) = chat::seal_chat_rumor(&rumor, &group, &peer, Timestamp::from_secs(5), false).unwrap();
897 let cap = Capture::default();
898 let out = dispatch_wrap(&wrap, &community, &me.public_key(), &cap);
899 assert!(matches!(out, DispatchedV2::Ignored), "fired inline, nothing to persist v2-side");
900 let seen = cap.0.lock().unwrap().clone();
901 assert_eq!(seen.len(), 1);
902 assert_eq!(seen[0].0, peer.public_key().to_bech32().unwrap());
903 assert_eq!(seen[0].1, topic);
904 assert_eq!(seen[0].2.as_deref(), Some("iroh:node/xyz"));
905
906 let own = chat::build_webxdc_rumor(me.public_key(), &general, epoch, &content, vec![], 6_000);
908 let (own_wrap, _) = chat::seal_chat_rumor(&own, &group, &me, Timestamp::from_secs(6), false).unwrap();
909 let cap2 = Capture::default();
910 dispatch_wrap(&own_wrap, &community, &me.public_key(), &cap2);
911 assert!(cap2.0.lock().unwrap().is_empty(), "own-device echo drops");
912 }
913
914 #[tokio::test]
915 async fn a_v2_message_with_an_imeta_attachment_surfaces_as_an_attachment() {
916 use nostr_sdk::prelude::Timestamp;
917 let (_tmp, _guard, me) = init();
918 let relay = MemoryRelay::new();
919 let community = service::create_community(&relay, "Files", vec!["wss://r".into()], None).await.unwrap();
920 let general = community.channels[0].id;
921 let cid = crate::simd::hex::bytes_to_hex_32(&general.0);
922 let group = super::super::derive::channel_group_key(&community.community_root, &general, community.root_epoch);
923 let session = crate::state::SessionGuard::capture();
924
925 let attachment = crate::types::Attachment {
928 id: "a".repeat(64),
929 key: "0".repeat(64),
930 nonce: "1".repeat(32),
931 extension: "png".into(),
932 name: "photo.png".into(),
933 url: "https://blossom.example/abc".into(),
934 path: String::new(),
935 size: 4096,
936 img_meta: None,
937 downloading: false,
938 downloaded: false,
939 webxdc_topic: None,
940 group_id: None,
941 original_hash: Some("b".repeat(64)),
942 fallback_urls: Vec::new(),
943 };
944 let imeta = crate::community::attachments::attachment_to_imeta(&attachment);
945 let member = Keys::generate();
946 let rumor = chat::build_message_rumor(member.public_key(), &general, community.root_epoch, "here's a file", None, &[], vec![imeta], 5_000);
947 let (wrap, _) = chat::seal_chat_rumor(&rumor, &group, &member, Timestamp::from_secs(5), false).unwrap();
948 let ev = chat::open_chat_event(&wrap, &group, &general, community.root_epoch).unwrap();
949
950 let outcome = persist_chat_event(&ev, &cid, &me.public_key(), &session).await;
951 let Some(ChatPersist::New(msg)) = outcome else {
952 panic!("the file message persists as new");
953 };
954 assert_eq!(msg.attachments.len(), 1, "the imeta tag parsed into one attachment");
955 let att = &msg.attachments[0];
956 assert!(att.url.contains("blossom.example"), "attachment url carried through: {}", att.url);
957 assert_eq!(att.extension, "png", "extension carried through");
958 }
959
960 #[tokio::test]
961 async fn a_banned_members_every_chat_event_is_dropped_on_sight() {
962 use nostr_sdk::prelude::Timestamp;
966 let (_tmp, _guard, me) = init();
967 let relay = MemoryRelay::new();
968 let community = service::create_community(&relay, "BanGate", vec!["wss://r".into()], None).await.unwrap();
969 let general = community.channels[0].id;
970 let cid = crate::simd::hex::bytes_to_hex_32(&general.0);
971 let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
972 let group = super::super::derive::channel_group_key(&community.community_root, &general, community.root_epoch);
973 let session = crate::state::SessionGuard::capture();
974 let rogue = Keys::generate();
975
976 let m1 = chat::build_message_rumor(rogue.public_key(), &general, community.root_epoch, "pre-ban", None, &[], vec![], 5_000);
978 let m1_id = m1.id.unwrap().to_hex();
979 let (w1, _) = chat::seal_chat_rumor(&m1, &group, &rogue, Timestamp::from_secs(5), false).unwrap();
980 let ev = chat::open_chat_event(&w1, &group, &general, community.root_epoch).unwrap();
981 assert!(matches!(persist_chat_event(&ev, &cid, &me.public_key(), &session).await, Some(ChatPersist::New(_))));
982
983 crate::db::community::set_community_banlist(&cid_hex, &[rogue.public_key().to_hex()], 1_000).unwrap();
985
986 let m2 = chat::build_message_rumor(rogue.public_key(), &general, community.root_epoch, "post-ban", None, &[], vec![], 6_000);
988 let (w2, _) = chat::seal_chat_rumor(&m2, &group, &rogue, Timestamp::from_secs(6), false).unwrap();
989 let ev = chat::open_chat_event(&w2, &group, &general, community.root_epoch).unwrap();
990 assert!(persist_chat_event(&ev, &cid, &me.public_key(), &session).await.is_none(), "a banned message is dropped");
991
992 let edit = chat::build_edit_rumor(rogue.public_key(), &general, community.root_epoch, &m1_id, "rewritten", 7_000);
993 let (we, _) = chat::seal_chat_rumor(&edit, &group, &rogue, Timestamp::from_secs(7), false).unwrap();
994 let ev = chat::open_chat_event(&we, &group, &general, community.root_epoch).unwrap();
995 assert!(persist_chat_event(&ev, &cid, &me.public_key(), &session).await.is_none(), "a banned edit is dropped");
996
997 let del = chat::build_delete_rumor(rogue.public_key(), &general, community.root_epoch, &m1_id, super::super::kind::MESSAGE, 8_000, None);
998 let (wd, _) = chat::seal_chat_rumor(&del, &group, &rogue, Timestamp::from_secs(8), false).unwrap();
999 let ev = chat::open_chat_event(&wd, &group, &general, community.root_epoch).unwrap();
1000 assert!(persist_chat_event(&ev, &cid, &me.public_key(), &session).await.is_none(), "a banned delete is dropped");
1001 assert!(
1002 crate::state::STATE.lock().await.find_message(&m1_id).is_some(),
1003 "their pre-ban message survives their own post-ban delete"
1004 );
1005
1006 let rec = Recorder::default();
1008 let typ = chat::build_typing_rumor(rogue.public_key(), &general, community.root_epoch, 9_000);
1009 let (wt, _) = chat::seal_chat_rumor(&typ, &group, &rogue, Timestamp::from_secs(9), true).unwrap();
1010 assert!(matches!(dispatch_wrap(&wt, &community, &me.public_key(), &rec), DispatchedV2::Ignored));
1011 let gb = super::super::derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch);
1016 let join = guestbook::build_join_rumor(rogue.public_key(), None, 10_000);
1017 let (wj, _) = guestbook::seal_guestbook_rumor(&join, &gb, &rogue, Timestamp::from_secs(10)).unwrap();
1018 assert!(matches!(dispatch_wrap(&wj, &community, &me.public_key(), &rec), DispatchedV2::Presence { joined: true, .. }));
1019 assert!(rec.presence.lock().unwrap().is_empty(), "no presence callback for a banned join");
1020
1021 let innocent = Keys::generate();
1023 let m3 = chat::build_message_rumor(innocent.public_key(), &general, community.root_epoch, "innocent", None, &[], vec![], 11_000);
1024 let (w3, _) = chat::seal_chat_rumor(&m3, &group, &innocent, Timestamp::from_secs(11), false).unwrap();
1025 let ev = chat::open_chat_event(&w3, &group, &general, community.root_epoch).unwrap();
1026 assert!(matches!(persist_chat_event(&ev, &cid, &me.public_key(), &session).await, Some(ChatPersist::New(_))));
1027 }
1028
1029 #[tokio::test]
1030 async fn an_armada_threaded_reply_persists_and_fires_as_an_inline_reply() {
1031 use nostr_sdk::prelude::Timestamp;
1032 let (_tmp, _guard, me) = init();
1033 let relay = MemoryRelay::new();
1034 let community = service::create_community(&relay, "Thread", vec!["wss://r".into()], None).await.unwrap();
1035 let general = community.channels[0].id;
1036 let cid = crate::simd::hex::bytes_to_hex_32(&general.0);
1037 let group = super::super::derive::channel_group_key(&community.community_root, &general, community.root_epoch);
1038 let session = crate::state::SessionGuard::capture();
1039
1040 let member = Keys::generate();
1043 let root = chat::build_message_rumor(member.public_key(), &general, community.root_epoch, "thread root", None, &[], vec![], 5_000);
1044 let root_id = root.id.unwrap().to_hex();
1045 let (rw, _) = chat::seal_chat_rumor(&root, &group, &member, Timestamp::from_secs(5), false).unwrap();
1046 let reply = chat::build_comment_rumor(
1047 member.public_key(),
1048 &general,
1049 community.root_epoch,
1050 "thread reply",
1051 &root_id,
1052 super::super::kind::MESSAGE,
1053 &member.public_key().to_hex(),
1054 None,
1055 &[],
1056 6_000,
1057 );
1058 let reply_id = reply.id.unwrap().to_hex();
1059 let (tw, _) = chat::seal_chat_rumor(&reply, &group, &member, Timestamp::from_secs(6), false).unwrap();
1060
1061 for w in [&rw, &tw] {
1062 let ev = chat::open_chat_event(w, &group, &general, community.root_epoch).unwrap();
1063 let outcome = persist_chat_event(&ev, &cid, &me.public_key(), &session).await;
1064 assert!(matches!(outcome, Some(ChatPersist::New(_))), "both persist as new messages");
1065 }
1066 let held = {
1069 let st = crate::state::STATE.lock().await;
1070 st.find_message(&reply_id).map(|(_, m)| m)
1071 }
1072 .expect("the threaded reply is resident");
1073 assert_eq!(held.replied_to, root_id, "the immediate parent is the reply context");
1074 assert_eq!(held.content, "thread reply");
1075
1076 let del = chat::build_delete_rumor(member.public_key(), &general, community.root_epoch, &reply_id, super::super::kind::COMMENT, 7_000, None);
1078 let (dw, _) = chat::seal_chat_rumor(&del, &group, &member, Timestamp::from_secs(7), false).unwrap();
1079 let ev = chat::open_chat_event(&dw, &group, &general, community.root_epoch).unwrap();
1080 let outcome = persist_chat_event(&ev, &cid, &me.public_key(), &session).await;
1081 assert!(matches!(outcome, Some(ChatPersist::Removed(id)) if id == reply_id), "the author's delete removes their thread reply");
1082 }
1083
1084 #[tokio::test]
1085 async fn an_edit_replay_never_refires() {
1086 use nostr_sdk::prelude::Timestamp;
1087 let (_tmp, _guard, me) = init();
1088 let relay = MemoryRelay::new();
1089 let community = service::create_community(&relay, "EditReplay", vec!["wss://r".into()], None).await.unwrap();
1090 let general = community.channels[0].id;
1091 let cid = crate::simd::hex::bytes_to_hex_32(&general.0);
1092 let group = super::super::derive::channel_group_key(&community.community_root, &general, community.root_epoch);
1093 let session = crate::state::SessionGuard::capture();
1094
1095 let member = Keys::generate();
1097 let msg = chat::build_message_rumor(member.public_key(), &general, community.root_epoch, "v1 text", None, &[], vec![], 5_000);
1098 let msg_id = msg.id.unwrap().to_hex();
1099 let (mw, _) = chat::seal_chat_rumor(&msg, &group, &member, Timestamp::from_secs(5), false).unwrap();
1100 let edit = chat::build_edit_rumor(member.public_key(), &general, community.root_epoch, &msg_id, "v2 text", 6_000);
1101 let (ew, _) = chat::seal_chat_rumor(&edit, &group, &member, Timestamp::from_secs(6), false).unwrap();
1102 for w in [&mw, &ew] {
1103 if let Ok(ev) = chat::open_chat_event(w, &group, &general, community.root_epoch) {
1104 let _ = persist_chat_event(&ev, &cid, &me.public_key(), &session).await;
1105 }
1106 }
1107
1108 let (replay, _) = chat::seal_chat_rumor(&edit, &group, &member, Timestamp::from_secs(7), false).unwrap();
1111 assert_ne!(replay.id, ew.id, "a re-wrap is a distinct outer event");
1112 let ev = chat::open_chat_event(&replay, &group, &general, community.root_epoch).unwrap();
1113 assert!(
1114 persist_chat_event(&ev, &cid, &me.public_key(), &session).await.is_none(),
1115 "a replayed edit yields no outcome (no handler re-fire)"
1116 );
1117 }
1118
1119 #[tokio::test]
1120 async fn a_forged_edit_from_a_non_author_is_ignored() {
1121 use nostr_sdk::prelude::Timestamp;
1125 let (_tmp, _guard, me) = init();
1126 let relay = MemoryRelay::new();
1127 let community = service::create_community(&relay, "EditGuard", vec!["wss://r".into()], None).await.unwrap();
1128 let general = community.channels[0].id;
1129 let cid = crate::simd::hex::bytes_to_hex_32(&general.0);
1130 let group = super::super::derive::channel_group_key(&community.community_root, &general, community.root_epoch);
1131 let session = crate::state::SessionGuard::capture();
1132
1133 let author = Keys::generate();
1135 let msg = chat::build_message_rumor(author.public_key(), &general, community.root_epoch, "original", None, &[], vec![], 5_000);
1136 let msg_id = msg.id.unwrap().to_hex();
1137 let (mw, _) = chat::seal_chat_rumor(&msg, &group, &author, Timestamp::from_secs(5), false).unwrap();
1138 let ev = chat::open_chat_event(&mw, &group, &general, community.root_epoch).unwrap();
1139 persist_chat_event(&ev, &cid, &me.public_key(), &session).await;
1140
1141 let stranger = Keys::generate();
1143 let edit = chat::build_edit_rumor(stranger.public_key(), &general, community.root_epoch, &msg_id, "TAMPERED", 6_000);
1144 let (ew, _) = chat::seal_chat_rumor(&edit, &group, &stranger, Timestamp::from_secs(6), false).unwrap();
1145 let ev = chat::open_chat_event(&ew, &group, &general, community.root_epoch).unwrap();
1146 assert!(persist_chat_event(&ev, &cid, &me.public_key(), &session).await.is_none(), "a forged edit yields no outcome");
1147
1148 let content = {
1149 let st = crate::state::STATE.lock().await;
1150 st.find_message(&msg_id).map(|(_, m)| m.content)
1151 };
1152 assert_eq!(content.as_deref(), Some("original"), "the message content is unchanged by the forged edit");
1153 }
1154
1155 #[tokio::test]
1156 async fn a_reaction_cannot_be_injected_across_channels() {
1157 use nostr_sdk::prelude::Timestamp;
1163 let (_tmp, _guard, me) = init();
1164 let relay = MemoryRelay::new();
1165 let mut community = service::create_community(&relay, "TwoChan", vec!["wss://r".into()], None).await.unwrap();
1166 let chan_a = community.channels[0].id;
1167 let chan_b = service::create_public_channel(&relay, &community, "b").await.unwrap();
1168 community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
1169 let a_hex = crate::simd::hex::bytes_to_hex_32(&chan_a.0);
1170 let session = crate::state::SessionGuard::capture();
1171
1172 let author = Keys::generate();
1174 let gb = super::super::derive::channel_group_key(&community.community_root, &chan_b, community.root_epoch);
1175 let msg = chat::build_message_rumor(author.public_key(), &chan_b, community.root_epoch, "in B", None, &[], vec![], 5_000);
1176 let msg_id = msg.id.unwrap().to_hex();
1177 let (mw, _) = chat::seal_chat_rumor(&msg, &gb, &author, Timestamp::from_secs(5), false).unwrap();
1178 let bev = chat::open_chat_event(&mw, &gb, &chan_b, community.root_epoch).unwrap();
1179 persist_chat_event(&bev, &crate::simd::hex::bytes_to_hex_32(&chan_b.0), &me.public_key(), &session).await;
1180
1181 let ga = super::super::derive::channel_group_key(&community.community_root, &chan_a, community.root_epoch);
1183 let reaction = chat::build_reaction_rumor(author.public_key(), &chan_a, community.root_epoch, &msg_id, &author.public_key().to_hex(), super::super::kind::MESSAGE, "💥", None, 6_000);
1184 let (rw, _) = chat::seal_chat_rumor(&reaction, &ga, &author, Timestamp::from_secs(6), false).unwrap();
1185 let aev = chat::open_chat_event(&rw, &ga, &chan_a, community.root_epoch).unwrap();
1186 let outcome = persist_chat_event(&aev, &a_hex, &me.public_key(), &session).await;
1188 assert!(outcome.is_none(), "a cross-channel reaction is dropped");
1189 let reacted = {
1190 let st = crate::state::STATE.lock().await;
1191 st.find_message(&msg_id).map(|(_, m)| !m.reactions.is_empty()).unwrap_or(false)
1192 };
1193 assert!(!reacted, "the channel-B message gained no reaction from the channel-A injection");
1194 }
1195
1196 #[tokio::test]
1197 async fn a_forged_delete_from_a_non_author_is_ignored() {
1198 use nostr_sdk::prelude::Timestamp;
1199 let (_tmp, _guard, me) = init();
1200 let relay = MemoryRelay::new();
1201 let community = service::create_community(&relay, "Forge", vec!["wss://r".into()], None).await.unwrap();
1202 let general = community.channels[0].id;
1203 let cid = crate::simd::hex::bytes_to_hex_32(&general.0);
1204 let group = super::super::derive::channel_group_key(&community.community_root, &general, community.root_epoch);
1205
1206 let msg_id = service::send_message(&relay, &community, &general, "mine").await.unwrap();
1208 let q = crate::community::transport::Query { kinds: vec![stream::KIND_WRAP], authors: vec![group.pk_hex()], ..Default::default() };
1209 let wraps = relay.fetch(&q, &community.relays).await.unwrap();
1210 for w in &wraps {
1211 if let Ok(ev) = chat::open_chat_event(w, &group, &general, community.root_epoch) {
1212 let mut st = crate::state::STATE.lock().await;
1213 apply_chat_to_state(&mut st, &ev, &cid, &me.public_key());
1214 }
1215 }
1216
1217 let stranger = nostr_sdk::prelude::Keys::generate();
1219 let del = chat::build_delete_rumor(stranger.public_key(), &general, community.root_epoch, &msg_id, super::super::kind::MESSAGE, 9_000, None);
1220 let (wrap, _) = chat::seal_chat_rumor(&del, &group, &stranger, Timestamp::from_secs(9), false).unwrap();
1221 let event = chat::open_chat_event(&wrap, &group, &general, community.root_epoch).unwrap();
1222
1223 let outcome = {
1224 let mut st = crate::state::STATE.lock().await;
1225 apply_chat_to_state(&mut st, &event, &cid, &me.public_key())
1226 };
1227 assert!(outcome.is_none(), "a forged delete from a non-author yields no removal");
1228 let survives = {
1229 let st = crate::state::STATE.lock().await;
1230 st.find_message(&msg_id).is_some()
1231 };
1232 assert!(survives, "the message survives the forged delete (live view + DB stay consistent)");
1233 }
1234
1235 struct ModerationBed {
1239 community: super::super::community::CommunityV2,
1240 general: crate::community::ChannelId,
1241 chat_id: String,
1242 group: super::super::derive::GroupKey,
1243 admin: Keys,
1244 admin_citation: crate::community::edition::AuthorityCitation,
1245 }
1246
1247 async fn moderation_bed(relay: &MemoryRelay, name: &str) -> ModerationBed {
1248 let community = service::create_community(relay, name, vec!["wss://r".into()], None).await.unwrap();
1249 let general = community.channels[0].id;
1250 let chat_id = crate::simd::hex::bytes_to_hex_32(&general.0);
1251 let group = super::super::derive::channel_group_key(&community.community_root, &general, community.root_epoch);
1252 let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
1253
1254 let admin = Keys::generate();
1255 service::grant_admin(relay, &community, &admin.public_key()).await.unwrap();
1256
1257 let view = service::fetch_authority(relay, &community).await;
1260 crate::db::community::set_community_roles(&cid_hex, &view.roles, 1_000).unwrap();
1261
1262 let entity_id = super::super::derive::grant_locator(community.id(), &admin.public_key().to_bytes());
1264 let entity_hex = crate::simd::hex::bytes_to_hex_32(&entity_id);
1265 let (version, edition_hash) = crate::db::community::get_edition_head(&cid_hex, &entity_hex)
1266 .unwrap()
1267 .expect("the owner's own grant publish stores its head");
1268 let admin_citation = crate::community::edition::AuthorityCitation { entity_id, version, edition_hash };
1269
1270 ModerationBed { community, general, chat_id, group, admin, admin_citation }
1271 }
1272
1273 async fn post_as(bed: &ModerationBed, author: &Keys, body: &str, at: u64, me: &PublicKey) -> String {
1275 use nostr_sdk::prelude::Timestamp;
1276 let rumor = chat::build_message_rumor(author.public_key(), &bed.general, bed.community.root_epoch, body, None, &[], vec![], at);
1277 let (wrap, _) = chat::seal_chat_rumor(&rumor, &bed.group, author, Timestamp::from_secs(at / 1000), false).unwrap();
1278 let event = chat::open_chat_event(&wrap, &bed.group, &bed.general, bed.community.root_epoch).unwrap();
1279 let id = rumor.id.unwrap().to_hex();
1280 let mut st = crate::state::STATE.lock().await;
1281 apply_chat_to_state(&mut st, &event, &bed.chat_id, me);
1282 id
1283 }
1284
1285 async fn delete_as(
1287 bed: &ModerationBed,
1288 actor: &Keys,
1289 target: &str,
1290 citation: Option<&crate::community::edition::AuthorityCitation>,
1291 at: u64,
1292 me: &PublicKey,
1293 ) -> Option<ChatPersist> {
1294 use nostr_sdk::prelude::Timestamp;
1295 let del = chat::build_delete_rumor(actor.public_key(), &bed.general, bed.community.root_epoch, target, super::super::kind::MESSAGE, at, citation);
1296 let (wrap, _) = chat::seal_chat_rumor(&del, &bed.group, actor, Timestamp::from_secs(at / 1000), false).unwrap();
1297 let event = chat::open_chat_event(&wrap, &bed.group, &bed.general, bed.community.root_epoch).unwrap();
1298 let mut st = crate::state::STATE.lock().await;
1299 apply_chat_to_state(&mut st, &event, &bed.chat_id, me)
1300 }
1301
1302 #[tokio::test]
1303 async fn an_admins_moderation_delete_removes_a_members_message() {
1304 let (_tmp, _guard, me) = init();
1305 let relay = MemoryRelay::new();
1306 let bed = moderation_bed(&relay, "Mod").await;
1307 let member = Keys::generate();
1308
1309 let victim = post_as(&bed, &member, "spam", 1_000, &me.public_key()).await;
1310 let outcome = delete_as(&bed, &bed.admin, &victim, Some(&bed.admin_citation), 2_000, &me.public_key()).await;
1311
1312 assert!(matches!(outcome, Some(ChatPersist::Removed(ref id)) if *id == victim), "MANAGE_MESSAGES + outrank removes it");
1313 assert!(crate::state::STATE.lock().await.find_message(&victim).is_none());
1314 }
1315
1316 #[tokio::test]
1317 async fn an_admin_cannot_moderation_delete_the_owners_message() {
1318 let (_tmp, _guard, me) = init();
1322 let relay = MemoryRelay::new();
1323 let bed = moderation_bed(&relay, "Sacred").await;
1324
1325 let owners_message = post_as(&bed, &me, "the owner speaks", 1_000, &me.public_key()).await;
1326 let outcome = delete_as(&bed, &bed.admin, &owners_message, Some(&bed.admin_citation), 2_000, &me.public_key()).await;
1327
1328 assert!(outcome.is_none(), "an admin never outranks the owner");
1329 assert!(crate::state::STATE.lock().await.find_message(&owners_message).is_some());
1330 }
1331
1332 #[tokio::test]
1333 async fn a_moderation_delete_without_a_synced_citation_is_refused() {
1334 let (_tmp, _guard, me) = init();
1337 let relay = MemoryRelay::new();
1338 let bed = moderation_bed(&relay, "Uncited").await;
1339 let member = Keys::generate();
1340
1341 let victim = post_as(&bed, &member, "spam", 1_000, &me.public_key()).await;
1342 assert!(delete_as(&bed, &bed.admin, &victim, None, 2_000, &me.public_key()).await.is_none());
1343 assert!(crate::state::STATE.lock().await.find_message(&victim).is_some());
1344
1345 assert!(delete_as(&bed, &bed.admin, &victim, Some(&bed.admin_citation), 3_000, &me.public_key()).await.is_some());
1348 }
1349
1350 #[tokio::test]
1351 async fn a_roleless_member_cannot_moderation_delete_anyone() {
1352 let (_tmp, _guard, me) = init();
1353 let relay = MemoryRelay::new();
1354 let bed = moderation_bed(&relay, "Roleless").await;
1355 let (member, rando) = (Keys::generate(), Keys::generate());
1356
1357 let victim = post_as(&bed, &member, "hello", 1_000, &me.public_key()).await;
1358 let outcome = delete_as(&bed, &rando, &victim, Some(&bed.admin_citation), 2_000, &me.public_key()).await;
1361
1362 assert!(outcome.is_none(), "no MANAGE_MESSAGES, no removal");
1363 assert!(crate::state::STATE.lock().await.find_message(&victim).is_some());
1364 }
1365
1366 #[tokio::test]
1367 async fn a_member_still_deletes_their_own_message_uncited() {
1368 let (_tmp, _guard, me) = init();
1370 let relay = MemoryRelay::new();
1371 let bed = moderation_bed(&relay, "Self").await;
1372 let member = Keys::generate();
1373
1374 let mine = post_as(&bed, &member, "oops", 1_000, &me.public_key()).await;
1375 let outcome = delete_as(&bed, &member, &mine, None, 2_000, &me.public_key()).await;
1376
1377 assert!(matches!(outcome, Some(ChatPersist::Removed(ref id)) if *id == mine));
1378 }
1379
1380 #[tokio::test]
1381 async fn a_foreign_wrap_is_not_ours() {
1382 let (_tmp, _guard, me) = init();
1383 let relay = MemoryRelay::new();
1384 let community = service::create_community(&relay, "X", vec!["wss://r".into()], None).await.unwrap();
1385
1386 let stranger = super::super::derive::channel_group_key(&[0x99u8; 32], &community.channels[0].id, community.root_epoch);
1389 let rumor = chat::build_message_rumor(me.public_key(), &community.channels[0].id, community.root_epoch, "not yours", None, &[], vec![], 1_000);
1390 let (wrap, _) = chat::seal_chat_rumor(&rumor, &stranger, &me, nostr_sdk::prelude::Timestamp::from_secs(1), false).unwrap();
1391
1392 let rec = Recorder::default();
1393 assert!(matches!(dispatch_wrap(&wrap, &community, &me.public_key(), &rec), DispatchedV2::NotOurs));
1394 assert!(rec.messages.lock().unwrap().is_empty());
1395 }
1396}