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 match (&outcome, event) {
282 (ChatPersist::Removed(target), _) => {
283 super::service::spawn_pin_duty(channel_id, target, None);
284 }
285 (ChatPersist::Updated { .. }, ChatEvent::Edit { opened, target, .. }) => {
286 let target_hex = crate::simd::hex::bytes_to_hex_32(target);
287 super::service::spawn_pin_duty(channel_id, &target_hex, Some(opened.clone()));
288 }
289 _ => {}
290 }
291 Some(outcome)
292}
293
294pub async fn persist_chat(channel_id: &str, outcome: &ChatPersist) {
298 match outcome {
299 ChatPersist::New(m) => {
300 let _ = crate::db::events::save_message(channel_id, m).await;
301 }
302 ChatPersist::Updated { message, edit_event } => match edit_event {
305 Some(ev) => {
306 let mut ev = (**ev).clone();
307 if let Ok(cid) = crate::db::id_cache::get_or_create_chat_id(channel_id) {
310 ev.chat_id = cid;
311 }
312 let _ = crate::db::events::save_event(&ev).await;
313 }
314 None => {
315 let _ = crate::db::events::save_message(channel_id, message).await;
316 }
317 },
318 ChatPersist::Removed(id) => {
319 let _ = crate::db::events::delete_event(id).await;
320 }
321 ChatPersist::ReactionRemoved { reaction_id, message } => {
322 let _ = crate::db::events::delete_event(reaction_id).await;
323 let _ = crate::db::events::save_message(channel_id, message).await;
324 }
325 }
326}
327
328#[derive(Debug, Clone)]
330pub enum DispatchedV2 {
331 Chat { channel_id: String, event: Box<ChatEvent> },
337 Typing { channel_id: String, npub: String },
339 Presence { npub: String, joined: bool },
341 Kick { target: PublicKey },
345 Control { community_id: String },
350 Rekey { community_id: String },
354 Dissolved { community_id: String },
357 Ignored,
360 NotOurs,
362}
363
364pub fn dispatch_wrap(
370 wrap: &nostr_sdk::prelude::Event,
371 community: &CommunityV2,
372 my_pubkey: &PublicKey,
373 handler: &dyn InboundEventHandler,
374) -> DispatchedV2 {
375 for ch in &community.channels {
377 if ch.private && ch.key.is_none() {
380 continue;
381 }
382 let (secret, epoch) = community.channel_secret(ch);
383 let group = super::derive::channel_group_key(&secret, &ch.id, epoch);
384 if wrap.pubkey != group.pk() {
385 continue;
386 }
387 let Ok(event) = chat::open_chat_event(wrap, &group, &ch.id, epoch) else {
388 return DispatchedV2::NotOurs;
389 };
390 let channel_id = crate::simd::hex::bytes_to_hex_32(&ch.id.0);
391 return dispatch_chat_event(event, &channel_id, my_pubkey, handler);
392 }
393
394 let gb = super::derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch);
396 if wrap.pubkey == gb.pk() {
397 if let Ok(opened) = stream::open_wrap(wrap, &gb) {
398 if let Ok(ev) = guestbook::parse_guestbook_event(&opened) {
399 return dispatch_guestbook(&ev, community, handler);
400 }
401 }
402 return DispatchedV2::Ignored;
403 }
404
405 if wrap.pubkey == super::realtime::control_author(community) {
409 return DispatchedV2::Control { community_id: crate::simd::hex::bytes_to_hex_32(&community.id().0) };
410 }
411
412 if super::realtime::rekey_authors(community).iter().any(|p| *p == wrap.pubkey) {
417 return DispatchedV2::Rekey { community_id: crate::simd::hex::bytes_to_hex_32(&community.id().0) };
418 }
419
420 if wrap.pubkey == super::derive::dissolved_group_key(community.id()).pk() {
423 if super::dissolution::verify_dissolved(wrap, &community.identity) {
424 return DispatchedV2::Dissolved { community_id: crate::simd::hex::bytes_to_hex_32(&community.id().0) };
425 }
426 return DispatchedV2::Ignored;
427 }
428
429 DispatchedV2::NotOurs
430}
431
432fn dispatch_chat_event(event: ChatEvent, channel_id: &str, my_pubkey: &PublicKey, handler: &dyn InboundEventHandler) -> DispatchedV2 {
433 match event {
434 ChatEvent::Typing { opened } => {
438 if author_is_banned_here(channel_id, &opened.author) {
439 return DispatchedV2::Ignored;
440 }
441 let npub = opened.author.to_bech32().unwrap_or_default();
442 let until = opened.at_ms / 1000 + 30;
443 handler.on_community_typing(channel_id, &npub, until);
444 DispatchedV2::Typing { channel_id: channel_id.to_string(), npub }
445 }
446 ChatEvent::Webxdc { opened } => {
450 if opened.author == *my_pubkey || author_is_banned_here(channel_id, &opened.author) {
451 return DispatchedV2::Ignored;
452 }
453 let Some((topic_id, node_addr)) = crate::webxdc::parse_peer_signal(&opened.rumor.content) else {
454 return DispatchedV2::Ignored;
455 };
456 let npub = opened.author.to_bech32().unwrap_or_default();
457 handler.on_community_webxdc(
458 channel_id,
459 &npub,
460 &topic_id,
461 node_addr.as_deref(),
462 &opened.rumor_id.to_hex(),
463 opened.at_ms / 1000,
464 );
465 DispatchedV2::Ignored
466 }
467 event => DispatchedV2::Chat { channel_id: channel_id.to_string(), event: Box::new(event) },
470 }
471}
472
473fn dispatch_guestbook(ev: &guestbook::GuestbookEvent, community: &CommunityV2, handler: &dyn InboundEventHandler) -> DispatchedV2 {
474 let suppressed = match &ev.entry {
482 GuestbookEntry::Join { member, .. } | GuestbookEntry::Leave { member, .. } => {
483 let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
484 crate::db::community::is_author_banned(&cid_hex, member)
485 }
486 _ => false,
487 };
488 let event_id = crate::simd::hex::bytes_to_hex_32(&ev.rumor_id);
492 let chat_id = community
500 .primary_channel()
501 .map(|c| crate::simd::hex::bytes_to_hex_32(&c.id.0));
502 match &ev.entry {
503 GuestbookEntry::Join { member, at_ms, invited_by } => {
504 let npub = member.to_bech32().unwrap_or_default();
505 let (by, label) = match invited_by {
506 Some((c, l)) => (Some(c.as_str()), Some(l.as_str())),
507 None => (None, None),
508 };
509 if let (false, Some(chat)) = (suppressed, chat_id.as_deref()) {
510 handler.on_community_presence(chat, &npub, true, &event_id, at_ms / 1000, by, label);
511 }
512 DispatchedV2::Presence { npub: npub.clone(), joined: true }
513 }
514 GuestbookEntry::Leave { member, at_ms } => {
515 let npub = member.to_bech32().unwrap_or_default();
516 if let (false, Some(chat)) = (suppressed, chat_id.as_deref()) {
517 handler.on_community_presence(chat, &npub, false, &event_id, at_ms / 1000, None, None);
518 }
519 DispatchedV2::Presence { npub: npub.clone(), joined: false }
520 }
521 GuestbookEntry::Kick { target, .. } => DispatchedV2::Kick { target: *target },
524 GuestbookEntry::Snapshot { .. } => DispatchedV2::Ignored,
525 }
526}
527
528#[cfg(test)]
529mod tests {
530 use super::*;
531 use super::super::service;
532 use crate::community::transport::memory::MemoryRelay;
533 use crate::community::transport::Transport;
534 use nostr_sdk::prelude::Keys;
535 use std::sync::Mutex;
536
537 #[derive(Default)]
539 struct Recorder {
540 messages: Mutex<Vec<(String, Message)>>,
541 updates: Mutex<Vec<(String, String)>>,
542 removed: Mutex<Vec<(String, String)>>,
543 presence: Mutex<Vec<(String, bool)>>,
544 }
545 impl InboundEventHandler for Recorder {
546 fn on_community_message(&self, chat_id: &str, msg: &Message, _is_new: bool) {
547 self.messages.lock().unwrap().push((chat_id.to_string(), msg.clone()));
548 }
549 fn on_community_update(&self, chat_id: &str, target: &str, _msg: &Message) {
550 self.updates.lock().unwrap().push((chat_id.to_string(), target.to_string()));
551 }
552 fn on_community_removed(&self, chat_id: &str, target: &str) {
553 self.removed.lock().unwrap().push((chat_id.to_string(), target.to_string()));
554 }
555 fn on_community_presence(&self, _c: &str, npub: &str, joined: bool, _e: &str, _a: u64, _b: Option<&str>, _l: Option<&str>) {
556 self.presence.lock().unwrap().push((npub.to_string(), joined));
557 }
558 }
559
560 fn init() -> (tempfile::TempDir, std::sync::MutexGuard<'static, ()>, Keys) {
561 let guard = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
562 crate::db::close_database();
563 crate::db::clear_id_caches();
564 let tmp = tempfile::tempdir().unwrap();
565 static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(90_000);
566 let n = N.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
567 const B: &[u8] = b"qpzry9x8gf2tvdw0s3jn54khce6mua7l";
568 let mut acct = String::from("npub1");
569 let mut v = n as usize;
570 for _ in 0..58 {
571 acct.push(B[v % 32] as char);
572 v = v / 32 + 7;
573 }
574 std::fs::create_dir_all(tmp.path().join(&acct)).unwrap();
575 crate::db::set_app_data_dir(tmp.path().to_path_buf());
576 crate::db::set_current_account(acct.clone()).unwrap();
577 crate::db::init_database(&acct).unwrap();
578 let _ = crate::state::take_nostr_client();
579 let me = Keys::generate();
580 crate::state::MY_SECRET_KEY.store_from_keys(&me, &[]);
581 crate::state::set_my_public_key(me.public_key());
582 (tmp, guard, me)
583 }
584
585 #[tokio::test]
586 async fn a_received_message_wrap_opens_then_fires_from_the_persist_outcome() {
587 use nostr_sdk::prelude::Timestamp;
588 let (_tmp, _guard, me) = init();
589 let relay = MemoryRelay::new();
590 let community = service::create_community(&relay, "In", vec!["wss://r".into()], None).await.unwrap();
591 let general = community.channels[0].id;
592 let cid = crate::simd::hex::bytes_to_hex_32(&general.0);
593
594 let member = Keys::generate();
597 let group = super::super::derive::channel_group_key(&community.community_root, &general, community.root_epoch);
598 let rumor = chat::build_message_rumor(member.public_key(), &general, community.root_epoch, "ping", None, &[], vec![], 5_000);
599 let (wrap, _) = chat::seal_chat_rumor(&rumor, &group, &member, Timestamp::from_secs(5), false).unwrap();
600
601 let rec = Recorder::default();
604 let dispatched = dispatch_wrap(&wrap, &community, &me.public_key(), &rec);
605 assert!(rec.messages.lock().unwrap().is_empty(), "no optimistic message callback");
606 let DispatchedV2::Chat { channel_id, event } = dispatched else {
607 panic!("a chat wrap dispatches as Chat");
608 };
609 assert_eq!(channel_id, cid);
610
611 let session = crate::state::SessionGuard::capture();
612 let outcome = persist_chat_event(&event, &channel_id, &me.public_key(), &session).await;
613 let Some(ChatPersist::New(msg)) = outcome else {
614 panic!("the first delivery persists as New");
615 };
616 assert_eq!(msg.content, "ping");
617 assert!(!msg.mine, "authored by the other member");
618
619 let (rewrap, _) = chat::seal_chat_rumor(&rumor, &group, &member, Timestamp::from_secs(6), false).unwrap();
622 assert_ne!(rewrap.id, wrap.id, "a re-wrap is a distinct outer event");
623 let DispatchedV2::Chat { event: dup, .. } = dispatch_wrap(&rewrap, &community, &me.public_key(), &rec) else {
624 panic!("the re-wrap still opens");
625 };
626 assert!(
627 persist_chat_event(&dup, &channel_id, &me.public_key(), &session).await.is_none(),
628 "a re-wrapped duplicate yields no outcome (nothing re-fires)"
629 );
630 }
631
632 #[tokio::test]
633 async fn a_guestbook_join_wrap_fires_presence() {
634 let (_tmp, _guard, me) = init();
635 let relay = MemoryRelay::new();
636 let community = service::create_community(&relay, "GB", vec!["wss://r".into()], None).await.unwrap();
638 let gb = super::super::derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch);
639 let q = crate::community::transport::Query { kinds: vec![stream::KIND_WRAP], authors: vec![gb.pk_hex()], ..Default::default() };
640 let wraps = relay.fetch(&q, &community.relays).await.unwrap();
641
642 let rec = Recorder::default();
643 for w in &wraps {
644 dispatch_wrap(w, &community, &me.public_key(), &rec);
645 }
646 let pres = rec.presence.lock().unwrap();
647 assert_eq!(pres.len(), 1, "the owner's genesis Join fires one presence");
648 assert!(pres[0].1, "it's a join");
649 assert_eq!(pres[0].0, me.public_key().to_bech32().unwrap());
650 }
651
652 #[tokio::test]
653 async fn v2_chat_events_persist_into_the_shared_store() {
654 let (_tmp, _guard, me) = init();
655 let relay = MemoryRelay::new();
656 let community = service::create_community(&relay, "Persist", vec!["wss://r".into()], None).await.unwrap();
657 let general = community.channels[0].id;
658 let cid = crate::simd::hex::bytes_to_hex_32(&general.0);
659 let group = super::super::derive::channel_group_key(&community.community_root, &general, community.root_epoch);
660 let me_hex = me.public_key().to_hex();
661
662 let msg_id = service::send_message(&relay, &community, &general, "persist me").await.unwrap();
663 service::send_reaction(&relay, &community, &general, &msg_id, &me_hex, super::super::kind::MESSAGE, "🔥", None).await.unwrap();
664
665 assert!(crate::db::events::event_exists(&msg_id).unwrap(), "the send echo persisted the message row");
668 let reacted = {
669 let st = crate::state::STATE.lock().await;
670 st.find_message(&msg_id).map(|(_, m)| m.reactions.iter().any(|r| r.emoji == "🔥")).unwrap_or(false)
671 };
672 assert!(reacted, "the send echo aggregated the reaction onto the stored message");
673
674 let q = crate::community::transport::Query { kinds: vec![stream::KIND_WRAP], authors: vec![group.pk_hex()], ..Default::default() };
677 let wraps = relay.fetch(&q, &community.relays).await.unwrap();
678 let mut events: Vec<ChatEvent> = wraps.iter().filter_map(|w| chat::open_chat_event(w, &group, &general, community.root_epoch).ok()).collect();
679 events.sort_by_key(|e| e.opened().at_ms);
680 assert!(!events.is_empty());
681 for ev in &events {
682 let outcome = {
683 let mut st = crate::state::STATE.lock().await;
684 apply_chat_to_state(&mut st, ev, &cid, &me.public_key())
685 };
686 assert!(outcome.is_none(), "the relay echo of an already-echoed send dedups");
687 }
688 }
689
690 #[tokio::test]
691 async fn a_v2_edit_persists_as_a_folded_edit_event() {
692 let (_tmp, _guard, me) = init();
693 let relay = MemoryRelay::new();
694 let community = service::create_community(&relay, "Edit", vec!["wss://r".into()], None).await.unwrap();
695 let general = community.channels[0].id;
696 let cid = crate::simd::hex::bytes_to_hex_32(&general.0);
697 let group = super::super::derive::channel_group_key(&community.community_root, &general, community.root_epoch);
698
699 let msg_id = service::send_message(&relay, &community, &general, "original").await.unwrap();
700 service::send_edit(&relay, &community, &general, &msg_id, "edited!").await.unwrap();
701
702 let q = crate::community::transport::Query { kinds: vec![stream::KIND_WRAP], authors: vec![group.pk_hex()], ..Default::default() };
704 let wraps = relay.fetch(&q, &community.relays).await.unwrap();
705 let mut events: Vec<ChatEvent> = wraps.iter().filter_map(|w| chat::open_chat_event(w, &group, &general, community.root_epoch).ok()).collect();
706 events.sort_by_key(|e| (!matches!(e, ChatEvent::Message { .. }), e.opened().at_ms));
707 for ev in &events {
708 let outcome = {
709 let mut st = crate::state::STATE.lock().await;
710 apply_chat_to_state(&mut st, ev, &cid, &me.public_key())
711 };
712 if let Some(o) = outcome {
713 persist_chat(&cid, &o).await;
714 }
715 }
716
717 let content = {
718 let st = crate::state::STATE.lock().await;
719 st.find_message(&msg_id).map(|(_, m)| m.content)
720 };
721 assert_eq!(content.as_deref(), Some("edited!"), "the edit applied to the stored message");
722 let edit_id = events.iter().find_map(|e| matches!(e, ChatEvent::Edit { .. }).then(|| e.opened().rumor_id.to_hex())).unwrap();
723 assert!(crate::db::events::event_exists(&edit_id).unwrap(), "the MESSAGE_EDIT event is persisted (folds on reload)");
724 }
725
726 #[tokio::test]
727 async fn a_reaction_after_a_rekey_aggregates_onto_a_prior_epoch_message() {
728 use nostr_sdk::prelude::Timestamp;
734 let (_tmp, _guard, me) = init();
735 let relay = MemoryRelay::new();
736 let community = service::create_community(&relay, "Rekeyed", vec!["wss://r".into()], None).await.unwrap();
737 let general = community.channels[0].id;
738 let cid = crate::simd::hex::bytes_to_hex_32(&general.0);
739 let session = crate::state::SessionGuard::capture();
740
741 let member = Keys::generate();
743 let g0 = super::super::derive::channel_group_key(&community.community_root, &general, community.root_epoch);
744 let msg = chat::build_message_rumor(member.public_key(), &general, community.root_epoch, "before the rekey", None, &[], vec![], 5_000);
745 let msg_id = msg.id.unwrap().to_hex();
746 let (mw, _) = chat::seal_chat_rumor(&msg, &g0, &member, Timestamp::from_secs(5), false).unwrap();
747 let ev = chat::open_chat_event(&mw, &g0, &general, community.root_epoch).unwrap();
748 assert!(matches!(persist_chat_event(&ev, &cid, &me.public_key(), &session).await, Some(ChatPersist::New(_))));
749
750 let next = crate::community::Epoch(community.root_epoch.0 + 1);
753 let g1 = super::super::derive::channel_group_key(&community.community_root, &general, next);
754 let reaction = chat::build_reaction_rumor(member.public_key(), &general, next, &msg_id, &member.public_key().to_hex(), super::super::kind::MESSAGE, "🎉", None, 6_000);
755 let (rw, _) = chat::seal_chat_rumor(&reaction, &g1, &member, Timestamp::from_secs(6), false).unwrap();
756 let rev = chat::open_chat_event(&rw, &g1, &general, next).unwrap();
757 let outcome = persist_chat_event(&rev, &cid, &me.public_key(), &session).await;
758 assert!(matches!(outcome, Some(ChatPersist::Updated { .. })), "the cross-epoch reaction updates the target");
759
760 let reaction_author = {
761 let st = crate::state::STATE.lock().await;
762 st.find_message(&msg_id)
763 .and_then(|(_, m)| m.reactions.iter().find(|r| r.emoji == "🎉").map(|r| r.author_id.clone()))
764 };
765 let author = reaction_author.expect("the epoch-1 reaction aggregated onto the epoch-0 message");
766 assert_eq!(author, member.public_key().to_bech32().unwrap(), "reaction author is stored as bech32");
769 }
770
771 #[tokio::test]
772 async fn an_un_react_removes_the_reaction_for_receivers_and_only_for_its_reactor() {
773 use nostr_sdk::prelude::Timestamp;
774 let (_tmp, _guard, me) = init();
775 let relay = MemoryRelay::new();
776 let community = service::create_community(&relay, "UnReact", vec!["wss://r".into()], None).await.unwrap();
777 let general = community.channels[0].id;
778 let cid = crate::simd::hex::bytes_to_hex_32(&general.0);
779 let session = crate::state::SessionGuard::capture();
780 let (secret, epoch) = community.channel_secret(&community.channels[0]);
781 let group = super::super::derive::channel_group_key(&secret, &general, epoch);
782
783 let member = Keys::generate();
785 let msg = chat::build_message_rumor(member.public_key(), &general, epoch, "react to me", None, &[], vec![], 5_000);
786 let msg_id = msg.id.unwrap().to_hex();
787 let (mw, _) = chat::seal_chat_rumor(&msg, &group, &member, Timestamp::from_secs(5), false).unwrap();
788 let ev = chat::open_chat_event(&mw, &group, &general, epoch).unwrap();
789 assert!(matches!(persist_chat_event(&ev, &cid, &me.public_key(), &session).await, Some(ChatPersist::New(_))));
790
791 let reaction = chat::build_reaction_rumor(member.public_key(), &general, epoch, &msg_id, &member.public_key().to_hex(), super::super::kind::MESSAGE, "🔥", None, 6_000);
792 let reaction_id = reaction.id.unwrap().to_hex();
793 let (rw, _) = chat::seal_chat_rumor(&reaction, &group, &member, Timestamp::from_secs(6), false).unwrap();
794 let rev = chat::open_chat_event(&rw, &group, &general, epoch).unwrap();
795 assert!(matches!(persist_chat_event(&rev, &cid, &me.public_key(), &session).await, Some(ChatPersist::Updated { .. })));
796
797 let outsider = Keys::generate();
799 let forged = chat::build_delete_rumor(outsider.public_key(), &general, epoch, &reaction_id, super::super::kind::MESSAGE, 7_000, None);
800 let (fw, _) = chat::seal_chat_rumor(&forged, &group, &outsider, Timestamp::from_secs(7), false).unwrap();
801 let fev = chat::open_chat_event(&fw, &group, &general, epoch).unwrap();
802 assert!(persist_chat_event(&fev, &cid, &me.public_key(), &session).await.is_none(), "only the reactor revokes their reaction");
803
804 let revoke = chat::build_delete_rumor(member.public_key(), &general, epoch, &reaction_id, super::super::kind::MESSAGE, 8_000, None);
807 let (vw, _) = chat::seal_chat_rumor(&revoke, &group, &member, Timestamp::from_secs(8), false).unwrap();
808 let vev = chat::open_chat_event(&vw, &group, &general, epoch).unwrap();
809 assert!(matches!(persist_chat_event(&vev, &cid, &me.public_key(), &session).await, Some(ChatPersist::ReactionRemoved { .. })));
810 let (has_reaction, parent_alive) = {
811 let st = crate::state::STATE.lock().await;
812 (
813 st.find_reaction(&reaction_id).is_some(),
814 st.find_message(&msg_id).is_some(),
815 )
816 };
817 assert!(!has_reaction, "the chip is gone from STATE");
818 assert!(parent_alive, "the parent message survives an un-react");
819 assert!(!crate::db::events::event_exists(&reaction_id).unwrap(), "the kind-7 row is deleted");
820 }
821
822 #[tokio::test]
823 async fn a_guestbook_join_fires_presence_with_its_real_rumor_id() {
824 use nostr_sdk::prelude::Timestamp;
825 use std::sync::Mutex as StdMutex;
826 let (_tmp, _guard, me) = init();
827 let relay = MemoryRelay::new();
828 let community = service::create_community(&relay, "Pres", vec!["wss://r".into()], None).await.unwrap();
829
830 #[derive(Default)]
831 struct Capture(StdMutex<Vec<(String, bool, String)>>);
832 impl InboundEventHandler for Capture {
833 fn on_community_presence(&self, _chat_id: &str, npub: &str, joined: bool, event_id: &str, _at: u64, _by: Option<&str>, _label: Option<&str>) {
834 self.0.lock().unwrap().push((npub.into(), joined, event_id.into()));
835 }
836 }
837
838 let member = Keys::generate();
839 let gb = super::super::derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch);
840 let rumor = guestbook::build_join_rumor(member.public_key(), None, 5_000);
841 let (wrap, _) = super::super::guestbook::seal_guestbook_rumor(&rumor, &gb, &member, Timestamp::from_secs(5)).unwrap();
842 let expected_id = rumor.id.unwrap().to_hex();
843
844 let cap = Capture::default();
845 let out = dispatch_wrap(&wrap, &community, &me.public_key(), &cap);
846 assert!(matches!(out, DispatchedV2::Presence { joined: true, .. }));
847 let seen = cap.0.lock().unwrap().clone();
848 assert_eq!(seen.len(), 1);
849 assert_eq!(seen[0].0, member.public_key().to_bech32().unwrap());
850 assert_eq!(seen[0].2, expected_id, "presence carries the join's own rumor id");
853 }
854
855 #[tokio::test]
856 async fn a_guestbook_kick_dispatches_its_target_and_raises_no_presence_line() {
857 use nostr_sdk::prelude::Timestamp;
860 use std::sync::Mutex as StdMutex;
861 let (_tmp, _guard, me) = init();
862 let relay = MemoryRelay::new();
863 let community = service::create_community(&relay, "Kicks", vec!["wss://r".into()], None).await.unwrap();
864
865 #[derive(Default)]
866 struct Capture(StdMutex<usize>);
867 impl InboundEventHandler for Capture {
868 fn on_community_presence(&self, _c: &str, _n: &str, _j: bool, _e: &str, _a: u64, _b: Option<&str>, _l: Option<&str>) {
869 *self.0.lock().unwrap() += 1;
870 }
871 }
872
873 let target = Keys::generate();
874 let gb = super::super::derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch);
875 let rumor = guestbook::build_kick_rumor(me.public_key(), target.public_key(), None, 5_000);
876 let (wrap, _) = super::super::guestbook::seal_guestbook_rumor(&rumor, &gb, &me, Timestamp::from_secs(5)).unwrap();
877
878 let cap = Capture::default();
879 let out = dispatch_wrap(&wrap, &community, &me.public_key(), &cap);
880 match out {
881 DispatchedV2::Kick { target: t } => assert_eq!(t, target.public_key(), "the kick names its target"),
882 other => panic!("a Kick must reach the store, got {other:?}"),
883 }
884 assert_eq!(*cap.0.lock().unwrap(), 0, "a kick raises no presence line");
886 }
887
888 #[tokio::test]
889 async fn a_webxdc_peer_ad_fires_the_shared_handler_and_own_echo_drops() {
890 use nostr_sdk::prelude::Timestamp;
891 use std::sync::Mutex as StdMutex;
892 let (_tmp, _guard, me) = init();
893 let relay = MemoryRelay::new();
894 let community = service::create_community(&relay, "XDC", vec!["wss://r".into()], None).await.unwrap();
895 let general = community.channels[0].id;
896
897 #[derive(Default)]
898 struct Capture(StdMutex<Vec<(String, String, Option<String>)>>);
899 impl InboundEventHandler for Capture {
900 fn on_community_webxdc(&self, _chat_id: &str, npub: &str, topic_id: &str, node_addr: Option<&str>, _event_id: &str, _created_at: u64) {
901 self.0.lock().unwrap().push((npub.into(), topic_id.into(), node_addr.map(String::from)));
902 }
903 }
904
905 let topic = "B".repeat(52);
906 let content = crate::webxdc::peer_signal_content(&topic, Some("iroh:node/xyz"));
907 let (secret, epoch) = community.channel_secret(&community.channels[0]);
908 let group = super::super::derive::channel_group_key(&secret, &general, epoch);
909
910 let peer = Keys::generate();
912 let rumor = chat::build_webxdc_rumor(peer.public_key(), &general, epoch, &content, vec![], 5_000);
913 let (wrap, _) = chat::seal_chat_rumor(&rumor, &group, &peer, Timestamp::from_secs(5), false).unwrap();
914 let cap = Capture::default();
915 let out = dispatch_wrap(&wrap, &community, &me.public_key(), &cap);
916 assert!(matches!(out, DispatchedV2::Ignored), "fired inline, nothing to persist v2-side");
917 let seen = cap.0.lock().unwrap().clone();
918 assert_eq!(seen.len(), 1);
919 assert_eq!(seen[0].0, peer.public_key().to_bech32().unwrap());
920 assert_eq!(seen[0].1, topic);
921 assert_eq!(seen[0].2.as_deref(), Some("iroh:node/xyz"));
922
923 let own = chat::build_webxdc_rumor(me.public_key(), &general, epoch, &content, vec![], 6_000);
925 let (own_wrap, _) = chat::seal_chat_rumor(&own, &group, &me, Timestamp::from_secs(6), false).unwrap();
926 let cap2 = Capture::default();
927 dispatch_wrap(&own_wrap, &community, &me.public_key(), &cap2);
928 assert!(cap2.0.lock().unwrap().is_empty(), "own-device echo drops");
929 }
930
931 #[tokio::test]
932 async fn a_v2_message_with_an_imeta_attachment_surfaces_as_an_attachment() {
933 use nostr_sdk::prelude::Timestamp;
934 let (_tmp, _guard, me) = init();
935 let relay = MemoryRelay::new();
936 let community = service::create_community(&relay, "Files", vec!["wss://r".into()], None).await.unwrap();
937 let general = community.channels[0].id;
938 let cid = crate::simd::hex::bytes_to_hex_32(&general.0);
939 let group = super::super::derive::channel_group_key(&community.community_root, &general, community.root_epoch);
940 let session = crate::state::SessionGuard::capture();
941
942 let attachment = crate::types::Attachment {
945 id: "a".repeat(64),
946 key: "0".repeat(64),
947 nonce: "1".repeat(32),
948 extension: "png".into(),
949 name: "photo.png".into(),
950 url: "https://blossom.example/abc".into(),
951 path: String::new(),
952 size: 4096,
953 img_meta: None,
954 downloading: false,
955 downloaded: false,
956 webxdc_topic: None,
957 group_id: None,
958 original_hash: Some("b".repeat(64)),
959 fallback_urls: Vec::new(),
960 };
961 let imeta = crate::community::attachments::attachment_to_imeta(&attachment);
962 let member = Keys::generate();
963 let rumor = chat::build_message_rumor(member.public_key(), &general, community.root_epoch, "here's a file", None, &[], vec![imeta], 5_000);
964 let (wrap, _) = chat::seal_chat_rumor(&rumor, &group, &member, Timestamp::from_secs(5), false).unwrap();
965 let ev = chat::open_chat_event(&wrap, &group, &general, community.root_epoch).unwrap();
966
967 let outcome = persist_chat_event(&ev, &cid, &me.public_key(), &session).await;
968 let Some(ChatPersist::New(msg)) = outcome else {
969 panic!("the file message persists as new");
970 };
971 assert_eq!(msg.attachments.len(), 1, "the imeta tag parsed into one attachment");
972 let att = &msg.attachments[0];
973 assert!(att.url.contains("blossom.example"), "attachment url carried through: {}", att.url);
974 assert_eq!(att.extension, "png", "extension carried through");
975 }
976
977 #[tokio::test]
978 async fn a_banned_members_every_chat_event_is_dropped_on_sight() {
979 use nostr_sdk::prelude::Timestamp;
983 let (_tmp, _guard, me) = init();
984 let relay = MemoryRelay::new();
985 let community = service::create_community(&relay, "BanGate", vec!["wss://r".into()], None).await.unwrap();
986 let general = community.channels[0].id;
987 let cid = crate::simd::hex::bytes_to_hex_32(&general.0);
988 let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
989 let group = super::super::derive::channel_group_key(&community.community_root, &general, community.root_epoch);
990 let session = crate::state::SessionGuard::capture();
991 let rogue = Keys::generate();
992
993 let m1 = chat::build_message_rumor(rogue.public_key(), &general, community.root_epoch, "pre-ban", None, &[], vec![], 5_000);
995 let m1_id = m1.id.unwrap().to_hex();
996 let (w1, _) = chat::seal_chat_rumor(&m1, &group, &rogue, Timestamp::from_secs(5), false).unwrap();
997 let ev = chat::open_chat_event(&w1, &group, &general, community.root_epoch).unwrap();
998 assert!(matches!(persist_chat_event(&ev, &cid, &me.public_key(), &session).await, Some(ChatPersist::New(_))));
999
1000 crate::db::community::set_community_banlist(&cid_hex, &[rogue.public_key().to_hex()], 1_000).unwrap();
1002
1003 let m2 = chat::build_message_rumor(rogue.public_key(), &general, community.root_epoch, "post-ban", None, &[], vec![], 6_000);
1005 let (w2, _) = chat::seal_chat_rumor(&m2, &group, &rogue, Timestamp::from_secs(6), false).unwrap();
1006 let ev = chat::open_chat_event(&w2, &group, &general, community.root_epoch).unwrap();
1007 assert!(persist_chat_event(&ev, &cid, &me.public_key(), &session).await.is_none(), "a banned message is dropped");
1008
1009 let edit = chat::build_edit_rumor(rogue.public_key(), &general, community.root_epoch, &m1_id, "rewritten", 7_000);
1010 let (we, _) = chat::seal_chat_rumor(&edit, &group, &rogue, Timestamp::from_secs(7), false).unwrap();
1011 let ev = chat::open_chat_event(&we, &group, &general, community.root_epoch).unwrap();
1012 assert!(persist_chat_event(&ev, &cid, &me.public_key(), &session).await.is_none(), "a banned edit is dropped");
1013
1014 let del = chat::build_delete_rumor(rogue.public_key(), &general, community.root_epoch, &m1_id, super::super::kind::MESSAGE, 8_000, None);
1015 let (wd, _) = chat::seal_chat_rumor(&del, &group, &rogue, Timestamp::from_secs(8), false).unwrap();
1016 let ev = chat::open_chat_event(&wd, &group, &general, community.root_epoch).unwrap();
1017 assert!(persist_chat_event(&ev, &cid, &me.public_key(), &session).await.is_none(), "a banned delete is dropped");
1018 assert!(
1019 crate::state::STATE.lock().await.find_message(&m1_id).is_some(),
1020 "their pre-ban message survives their own post-ban delete"
1021 );
1022
1023 let rec = Recorder::default();
1025 let typ = chat::build_typing_rumor(rogue.public_key(), &general, community.root_epoch, 9_000);
1026 let (wt, _) = chat::seal_chat_rumor(&typ, &group, &rogue, Timestamp::from_secs(9), true).unwrap();
1027 assert!(matches!(dispatch_wrap(&wt, &community, &me.public_key(), &rec), DispatchedV2::Ignored));
1028 let gb = super::super::derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch);
1033 let join = guestbook::build_join_rumor(rogue.public_key(), None, 10_000);
1034 let (wj, _) = guestbook::seal_guestbook_rumor(&join, &gb, &rogue, Timestamp::from_secs(10)).unwrap();
1035 assert!(matches!(dispatch_wrap(&wj, &community, &me.public_key(), &rec), DispatchedV2::Presence { joined: true, .. }));
1036 assert!(rec.presence.lock().unwrap().is_empty(), "no presence callback for a banned join");
1037
1038 let innocent = Keys::generate();
1040 let m3 = chat::build_message_rumor(innocent.public_key(), &general, community.root_epoch, "innocent", None, &[], vec![], 11_000);
1041 let (w3, _) = chat::seal_chat_rumor(&m3, &group, &innocent, Timestamp::from_secs(11), false).unwrap();
1042 let ev = chat::open_chat_event(&w3, &group, &general, community.root_epoch).unwrap();
1043 assert!(matches!(persist_chat_event(&ev, &cid, &me.public_key(), &session).await, Some(ChatPersist::New(_))));
1044 }
1045
1046 #[tokio::test]
1047 async fn an_armada_threaded_reply_persists_and_fires_as_an_inline_reply() {
1048 use nostr_sdk::prelude::Timestamp;
1049 let (_tmp, _guard, me) = init();
1050 let relay = MemoryRelay::new();
1051 let community = service::create_community(&relay, "Thread", vec!["wss://r".into()], None).await.unwrap();
1052 let general = community.channels[0].id;
1053 let cid = crate::simd::hex::bytes_to_hex_32(&general.0);
1054 let group = super::super::derive::channel_group_key(&community.community_root, &general, community.root_epoch);
1055 let session = crate::state::SessionGuard::capture();
1056
1057 let member = Keys::generate();
1060 let root = chat::build_message_rumor(member.public_key(), &general, community.root_epoch, "thread root", None, &[], vec![], 5_000);
1061 let root_id = root.id.unwrap().to_hex();
1062 let (rw, _) = chat::seal_chat_rumor(&root, &group, &member, Timestamp::from_secs(5), false).unwrap();
1063 let reply = chat::build_comment_rumor(
1064 member.public_key(),
1065 &general,
1066 community.root_epoch,
1067 "thread reply",
1068 &root_id,
1069 super::super::kind::MESSAGE,
1070 &member.public_key().to_hex(),
1071 None,
1072 &[],
1073 6_000,
1074 );
1075 let reply_id = reply.id.unwrap().to_hex();
1076 let (tw, _) = chat::seal_chat_rumor(&reply, &group, &member, Timestamp::from_secs(6), false).unwrap();
1077
1078 for w in [&rw, &tw] {
1079 let ev = chat::open_chat_event(w, &group, &general, community.root_epoch).unwrap();
1080 let outcome = persist_chat_event(&ev, &cid, &me.public_key(), &session).await;
1081 assert!(matches!(outcome, Some(ChatPersist::New(_))), "both persist as new messages");
1082 }
1083 let held = {
1086 let st = crate::state::STATE.lock().await;
1087 st.find_message(&reply_id).map(|(_, m)| m)
1088 }
1089 .expect("the threaded reply is resident");
1090 assert_eq!(held.replied_to, root_id, "the immediate parent is the reply context");
1091 assert_eq!(held.content, "thread reply");
1092
1093 let del = chat::build_delete_rumor(member.public_key(), &general, community.root_epoch, &reply_id, super::super::kind::COMMENT, 7_000, None);
1095 let (dw, _) = chat::seal_chat_rumor(&del, &group, &member, Timestamp::from_secs(7), false).unwrap();
1096 let ev = chat::open_chat_event(&dw, &group, &general, community.root_epoch).unwrap();
1097 let outcome = persist_chat_event(&ev, &cid, &me.public_key(), &session).await;
1098 assert!(matches!(outcome, Some(ChatPersist::Removed(id)) if id == reply_id), "the author's delete removes their thread reply");
1099 }
1100
1101 #[tokio::test]
1102 async fn an_edit_replay_never_refires() {
1103 use nostr_sdk::prelude::Timestamp;
1104 let (_tmp, _guard, me) = init();
1105 let relay = MemoryRelay::new();
1106 let community = service::create_community(&relay, "EditReplay", vec!["wss://r".into()], None).await.unwrap();
1107 let general = community.channels[0].id;
1108 let cid = crate::simd::hex::bytes_to_hex_32(&general.0);
1109 let group = super::super::derive::channel_group_key(&community.community_root, &general, community.root_epoch);
1110 let session = crate::state::SessionGuard::capture();
1111
1112 let member = Keys::generate();
1114 let msg = chat::build_message_rumor(member.public_key(), &general, community.root_epoch, "v1 text", None, &[], vec![], 5_000);
1115 let msg_id = msg.id.unwrap().to_hex();
1116 let (mw, _) = chat::seal_chat_rumor(&msg, &group, &member, Timestamp::from_secs(5), false).unwrap();
1117 let edit = chat::build_edit_rumor(member.public_key(), &general, community.root_epoch, &msg_id, "v2 text", 6_000);
1118 let (ew, _) = chat::seal_chat_rumor(&edit, &group, &member, Timestamp::from_secs(6), false).unwrap();
1119 for w in [&mw, &ew] {
1120 if let Ok(ev) = chat::open_chat_event(w, &group, &general, community.root_epoch) {
1121 let _ = persist_chat_event(&ev, &cid, &me.public_key(), &session).await;
1122 }
1123 }
1124
1125 let (replay, _) = chat::seal_chat_rumor(&edit, &group, &member, Timestamp::from_secs(7), false).unwrap();
1128 assert_ne!(replay.id, ew.id, "a re-wrap is a distinct outer event");
1129 let ev = chat::open_chat_event(&replay, &group, &general, community.root_epoch).unwrap();
1130 assert!(
1131 persist_chat_event(&ev, &cid, &me.public_key(), &session).await.is_none(),
1132 "a replayed edit yields no outcome (no handler re-fire)"
1133 );
1134 }
1135
1136 #[tokio::test]
1137 async fn a_forged_edit_from_a_non_author_is_ignored() {
1138 use nostr_sdk::prelude::Timestamp;
1142 let (_tmp, _guard, me) = init();
1143 let relay = MemoryRelay::new();
1144 let community = service::create_community(&relay, "EditGuard", vec!["wss://r".into()], None).await.unwrap();
1145 let general = community.channels[0].id;
1146 let cid = crate::simd::hex::bytes_to_hex_32(&general.0);
1147 let group = super::super::derive::channel_group_key(&community.community_root, &general, community.root_epoch);
1148 let session = crate::state::SessionGuard::capture();
1149
1150 let author = Keys::generate();
1152 let msg = chat::build_message_rumor(author.public_key(), &general, community.root_epoch, "original", None, &[], vec![], 5_000);
1153 let msg_id = msg.id.unwrap().to_hex();
1154 let (mw, _) = chat::seal_chat_rumor(&msg, &group, &author, Timestamp::from_secs(5), false).unwrap();
1155 let ev = chat::open_chat_event(&mw, &group, &general, community.root_epoch).unwrap();
1156 persist_chat_event(&ev, &cid, &me.public_key(), &session).await;
1157
1158 let stranger = Keys::generate();
1160 let edit = chat::build_edit_rumor(stranger.public_key(), &general, community.root_epoch, &msg_id, "TAMPERED", 6_000);
1161 let (ew, _) = chat::seal_chat_rumor(&edit, &group, &stranger, Timestamp::from_secs(6), false).unwrap();
1162 let ev = chat::open_chat_event(&ew, &group, &general, community.root_epoch).unwrap();
1163 assert!(persist_chat_event(&ev, &cid, &me.public_key(), &session).await.is_none(), "a forged edit yields no outcome");
1164
1165 let content = {
1166 let st = crate::state::STATE.lock().await;
1167 st.find_message(&msg_id).map(|(_, m)| m.content)
1168 };
1169 assert_eq!(content.as_deref(), Some("original"), "the message content is unchanged by the forged edit");
1170 }
1171
1172 #[tokio::test]
1173 async fn a_reaction_cannot_be_injected_across_channels() {
1174 use nostr_sdk::prelude::Timestamp;
1180 let (_tmp, _guard, me) = init();
1181 let relay = MemoryRelay::new();
1182 let mut community = service::create_community(&relay, "TwoChan", vec!["wss://r".into()], None).await.unwrap();
1183 let chan_a = community.channels[0].id;
1184 let chan_b = service::create_public_channel(&relay, &community, "b").await.unwrap();
1185 community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
1186 let a_hex = crate::simd::hex::bytes_to_hex_32(&chan_a.0);
1187 let session = crate::state::SessionGuard::capture();
1188
1189 let author = Keys::generate();
1191 let gb = super::super::derive::channel_group_key(&community.community_root, &chan_b, community.root_epoch);
1192 let msg = chat::build_message_rumor(author.public_key(), &chan_b, community.root_epoch, "in B", None, &[], vec![], 5_000);
1193 let msg_id = msg.id.unwrap().to_hex();
1194 let (mw, _) = chat::seal_chat_rumor(&msg, &gb, &author, Timestamp::from_secs(5), false).unwrap();
1195 let bev = chat::open_chat_event(&mw, &gb, &chan_b, community.root_epoch).unwrap();
1196 persist_chat_event(&bev, &crate::simd::hex::bytes_to_hex_32(&chan_b.0), &me.public_key(), &session).await;
1197
1198 let ga = super::super::derive::channel_group_key(&community.community_root, &chan_a, community.root_epoch);
1200 let reaction = chat::build_reaction_rumor(author.public_key(), &chan_a, community.root_epoch, &msg_id, &author.public_key().to_hex(), super::super::kind::MESSAGE, "💥", None, 6_000);
1201 let (rw, _) = chat::seal_chat_rumor(&reaction, &ga, &author, Timestamp::from_secs(6), false).unwrap();
1202 let aev = chat::open_chat_event(&rw, &ga, &chan_a, community.root_epoch).unwrap();
1203 let outcome = persist_chat_event(&aev, &a_hex, &me.public_key(), &session).await;
1205 assert!(outcome.is_none(), "a cross-channel reaction is dropped");
1206 let reacted = {
1207 let st = crate::state::STATE.lock().await;
1208 st.find_message(&msg_id).map(|(_, m)| !m.reactions.is_empty()).unwrap_or(false)
1209 };
1210 assert!(!reacted, "the channel-B message gained no reaction from the channel-A injection");
1211 }
1212
1213 #[tokio::test]
1214 async fn a_forged_delete_from_a_non_author_is_ignored() {
1215 use nostr_sdk::prelude::Timestamp;
1216 let (_tmp, _guard, me) = init();
1217 let relay = MemoryRelay::new();
1218 let community = service::create_community(&relay, "Forge", vec!["wss://r".into()], None).await.unwrap();
1219 let general = community.channels[0].id;
1220 let cid = crate::simd::hex::bytes_to_hex_32(&general.0);
1221 let group = super::super::derive::channel_group_key(&community.community_root, &general, community.root_epoch);
1222
1223 let msg_id = service::send_message(&relay, &community, &general, "mine").await.unwrap();
1225 let q = crate::community::transport::Query { kinds: vec![stream::KIND_WRAP], authors: vec![group.pk_hex()], ..Default::default() };
1226 let wraps = relay.fetch(&q, &community.relays).await.unwrap();
1227 for w in &wraps {
1228 if let Ok(ev) = chat::open_chat_event(w, &group, &general, community.root_epoch) {
1229 let mut st = crate::state::STATE.lock().await;
1230 apply_chat_to_state(&mut st, &ev, &cid, &me.public_key());
1231 }
1232 }
1233
1234 let stranger = nostr_sdk::prelude::Keys::generate();
1236 let del = chat::build_delete_rumor(stranger.public_key(), &general, community.root_epoch, &msg_id, super::super::kind::MESSAGE, 9_000, None);
1237 let (wrap, _) = chat::seal_chat_rumor(&del, &group, &stranger, Timestamp::from_secs(9), false).unwrap();
1238 let event = chat::open_chat_event(&wrap, &group, &general, community.root_epoch).unwrap();
1239
1240 let outcome = {
1241 let mut st = crate::state::STATE.lock().await;
1242 apply_chat_to_state(&mut st, &event, &cid, &me.public_key())
1243 };
1244 assert!(outcome.is_none(), "a forged delete from a non-author yields no removal");
1245 let survives = {
1246 let st = crate::state::STATE.lock().await;
1247 st.find_message(&msg_id).is_some()
1248 };
1249 assert!(survives, "the message survives the forged delete (live view + DB stay consistent)");
1250 }
1251
1252 struct ModerationBed {
1256 community: super::super::community::CommunityV2,
1257 general: crate::community::ChannelId,
1258 chat_id: String,
1259 group: super::super::derive::GroupKey,
1260 admin: Keys,
1261 admin_citation: crate::community::edition::AuthorityCitation,
1262 }
1263
1264 async fn moderation_bed(relay: &MemoryRelay, name: &str) -> ModerationBed {
1265 let community = service::create_community(relay, name, vec!["wss://r".into()], None).await.unwrap();
1266 let general = community.channels[0].id;
1267 let chat_id = crate::simd::hex::bytes_to_hex_32(&general.0);
1268 let group = super::super::derive::channel_group_key(&community.community_root, &general, community.root_epoch);
1269 let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
1270
1271 let admin = Keys::generate();
1272 service::grant_admin(relay, &community, &admin.public_key()).await.unwrap();
1273
1274 let view = service::fetch_authority(relay, &community).await;
1277 crate::db::community::set_community_roles(&cid_hex, &view.roles, 1_000).unwrap();
1278
1279 let entity_id = super::super::derive::grant_locator(community.id(), &admin.public_key().to_bytes());
1281 let entity_hex = crate::simd::hex::bytes_to_hex_32(&entity_id);
1282 let (version, edition_hash) = crate::db::community::get_edition_head(&cid_hex, &entity_hex)
1283 .unwrap()
1284 .expect("the owner's own grant publish stores its head");
1285 let admin_citation = crate::community::edition::AuthorityCitation { entity_id, version, edition_hash };
1286
1287 ModerationBed { community, general, chat_id, group, admin, admin_citation }
1288 }
1289
1290 async fn post_as(bed: &ModerationBed, author: &Keys, body: &str, at: u64, me: &PublicKey) -> String {
1292 use nostr_sdk::prelude::Timestamp;
1293 let rumor = chat::build_message_rumor(author.public_key(), &bed.general, bed.community.root_epoch, body, None, &[], vec![], at);
1294 let (wrap, _) = chat::seal_chat_rumor(&rumor, &bed.group, author, Timestamp::from_secs(at / 1000), false).unwrap();
1295 let event = chat::open_chat_event(&wrap, &bed.group, &bed.general, bed.community.root_epoch).unwrap();
1296 let id = rumor.id.unwrap().to_hex();
1297 let mut st = crate::state::STATE.lock().await;
1298 apply_chat_to_state(&mut st, &event, &bed.chat_id, me);
1299 id
1300 }
1301
1302 async fn delete_as(
1304 bed: &ModerationBed,
1305 actor: &Keys,
1306 target: &str,
1307 citation: Option<&crate::community::edition::AuthorityCitation>,
1308 at: u64,
1309 me: &PublicKey,
1310 ) -> Option<ChatPersist> {
1311 use nostr_sdk::prelude::Timestamp;
1312 let del = chat::build_delete_rumor(actor.public_key(), &bed.general, bed.community.root_epoch, target, super::super::kind::MESSAGE, at, citation);
1313 let (wrap, _) = chat::seal_chat_rumor(&del, &bed.group, actor, Timestamp::from_secs(at / 1000), false).unwrap();
1314 let event = chat::open_chat_event(&wrap, &bed.group, &bed.general, bed.community.root_epoch).unwrap();
1315 let mut st = crate::state::STATE.lock().await;
1316 apply_chat_to_state(&mut st, &event, &bed.chat_id, me)
1317 }
1318
1319 #[tokio::test]
1320 async fn an_admins_moderation_delete_removes_a_members_message() {
1321 let (_tmp, _guard, me) = init();
1322 let relay = MemoryRelay::new();
1323 let bed = moderation_bed(&relay, "Mod").await;
1324 let member = Keys::generate();
1325
1326 let victim = post_as(&bed, &member, "spam", 1_000, &me.public_key()).await;
1327 let outcome = delete_as(&bed, &bed.admin, &victim, Some(&bed.admin_citation), 2_000, &me.public_key()).await;
1328
1329 assert!(matches!(outcome, Some(ChatPersist::Removed(ref id)) if *id == victim), "MANAGE_MESSAGES + outrank removes it");
1330 assert!(crate::state::STATE.lock().await.find_message(&victim).is_none());
1331 }
1332
1333 #[tokio::test]
1334 async fn an_admin_cannot_moderation_delete_the_owners_message() {
1335 let (_tmp, _guard, me) = init();
1339 let relay = MemoryRelay::new();
1340 let bed = moderation_bed(&relay, "Sacred").await;
1341
1342 let owners_message = post_as(&bed, &me, "the owner speaks", 1_000, &me.public_key()).await;
1343 let outcome = delete_as(&bed, &bed.admin, &owners_message, Some(&bed.admin_citation), 2_000, &me.public_key()).await;
1344
1345 assert!(outcome.is_none(), "an admin never outranks the owner");
1346 assert!(crate::state::STATE.lock().await.find_message(&owners_message).is_some());
1347 }
1348
1349 #[tokio::test]
1350 async fn a_moderation_delete_without_a_synced_citation_is_refused() {
1351 let (_tmp, _guard, me) = init();
1354 let relay = MemoryRelay::new();
1355 let bed = moderation_bed(&relay, "Uncited").await;
1356 let member = Keys::generate();
1357
1358 let victim = post_as(&bed, &member, "spam", 1_000, &me.public_key()).await;
1359 assert!(delete_as(&bed, &bed.admin, &victim, None, 2_000, &me.public_key()).await.is_none());
1360 assert!(crate::state::STATE.lock().await.find_message(&victim).is_some());
1361
1362 assert!(delete_as(&bed, &bed.admin, &victim, Some(&bed.admin_citation), 3_000, &me.public_key()).await.is_some());
1365 }
1366
1367 #[tokio::test]
1368 async fn a_roleless_member_cannot_moderation_delete_anyone() {
1369 let (_tmp, _guard, me) = init();
1370 let relay = MemoryRelay::new();
1371 let bed = moderation_bed(&relay, "Roleless").await;
1372 let (member, rando) = (Keys::generate(), Keys::generate());
1373
1374 let victim = post_as(&bed, &member, "hello", 1_000, &me.public_key()).await;
1375 let outcome = delete_as(&bed, &rando, &victim, Some(&bed.admin_citation), 2_000, &me.public_key()).await;
1378
1379 assert!(outcome.is_none(), "no MANAGE_MESSAGES, no removal");
1380 assert!(crate::state::STATE.lock().await.find_message(&victim).is_some());
1381 }
1382
1383 #[tokio::test]
1384 async fn a_member_still_deletes_their_own_message_uncited() {
1385 let (_tmp, _guard, me) = init();
1387 let relay = MemoryRelay::new();
1388 let bed = moderation_bed(&relay, "Self").await;
1389 let member = Keys::generate();
1390
1391 let mine = post_as(&bed, &member, "oops", 1_000, &me.public_key()).await;
1392 let outcome = delete_as(&bed, &member, &mine, None, 2_000, &me.public_key()).await;
1393
1394 assert!(matches!(outcome, Some(ChatPersist::Removed(ref id)) if *id == mine));
1395 }
1396
1397 #[tokio::test]
1398 async fn a_foreign_wrap_is_not_ours() {
1399 let (_tmp, _guard, me) = init();
1400 let relay = MemoryRelay::new();
1401 let community = service::create_community(&relay, "X", vec!["wss://r".into()], None).await.unwrap();
1402
1403 let stranger = super::super::derive::channel_group_key(&[0x99u8; 32], &community.channels[0].id, community.root_epoch);
1406 let rumor = chat::build_message_rumor(me.public_key(), &community.channels[0].id, community.root_epoch, "not yours", None, &[], vec![], 1_000);
1407 let (wrap, _) = chat::seal_chat_rumor(&rumor, &stranger, &me, nostr_sdk::prelude::Timestamp::from_secs(1), false).unwrap();
1408
1409 let rec = Recorder::default();
1410 assert!(matches!(dispatch_wrap(&wrap, &community, &me.public_key(), &rec), DispatchedV2::NotOurs));
1411 assert!(rec.messages.lock().unwrap().is_empty());
1412 }
1413}