1use nostr_sdk::prelude::{Event, PublicKey};
7use nostr_sdk::ToBech32;
8
9use super::envelope::{open_message_multi, OpenedMessage};
10use super::Channel;
11use crate::state::ChatState;
12use crate::stored_event::event_kind;
13use crate::types::Message;
14
15fn concord_rumor(
27 opened: &OpenedMessage,
28 kind: nostr_sdk::Kind,
29 my_pubkey: &PublicKey,
30) -> (crate::rumor::RumorEvent, crate::rumor::RumorContext) {
31 use crate::rumor::{ConversationType, RumorContext, RumorEvent};
32 (
33 RumorEvent {
34 id: opened.message_id,
35 kind,
36 content: opened.content.clone(),
37 tags: opened.tags.clone(),
38 created_at: opened.created_at,
39 pubkey: opened.author,
40 },
41 RumorContext {
42 sender: opened.author,
43 is_mine: opened.author == *my_pubkey,
44 conversation_id: opened.channel_id.to_hex(),
45 conversation_type: ConversationType::Community,
46 },
47 )
48}
49
50pub fn build_message(opened: &OpenedMessage, my_pubkey: &PublicKey) -> Message {
51 use crate::rumor::{process_rumor, RumorProcessingResult};
52 let (rumor, ctx) = concord_rumor(opened, nostr_sdk::Kind::PrivateDirectMessage, my_pubkey);
53 let mut msg = match process_rumor(rumor, ctx, &crate::db::get_download_dir()) {
54 Ok(RumorProcessingResult::TextMessage(m)) => m,
55 _ => Message {
58 id: opened.message_id.to_hex(),
59 content: opened.content.clone(),
60 at: opened.ms.unwrap_or_else(|| opened.created_at.as_secs().saturating_mul(1000)),
61 mine: opened.author == *my_pubkey,
62 npub: opened.author.to_bech32().ok(),
63 ..Default::default()
64 },
65 };
66 msg.attachments = opened.attachments.clone();
69 msg.wrapper_event_id = Some(opened.wrapper_id.to_hex());
70 msg
71}
72
73pub fn ingest_message(
78 state: &mut ChatState,
79 opened: &OpenedMessage,
80 my_pubkey: &PublicKey,
81) -> Option<Message> {
82 let chat_id = opened.channel_id.to_hex();
83 let msg = build_message(opened, my_pubkey);
84 if crate::db::events::event_exists(&msg.id).unwrap_or(false) {
91 return None;
92 }
93 state.ensure_community_chat(&chat_id);
94 if state.add_message_to_chat(&chat_id, msg.clone()) {
95 Some(msg)
96 } else {
97 None
98 }
99}
100
101pub enum IncomingEvent {
106 NewMessage(Message),
107 Updated { target_id: String, message: Message, edit_event: Option<Box<crate::stored_event::StoredEvent>> },
112 Removed { target_id: String },
113 ReactionRemoved { message_id: String, reaction_id: String, message: Message },
118 Presence { npub: String, joined: bool, event_id: String, created_at: u64, invited_by: Option<String>, invited_label: Option<String> },
125 Kicked { community_id: String },
130 SelfLeft { community_id: String },
136 WebxdcPeer {
141 npub: String,
142 topic_id: String,
143 node_addr: Option<String>,
145 event_id: String,
146 created_at: u64,
147 },
148 Typing { npub: String, until: u64 },
152}
153
154pub fn process_incoming(
160 state: &mut ChatState,
161 event: &Event,
162 channel: &Channel,
163 my_pubkey: &PublicKey,
164) -> Option<IncomingEvent> {
165 let outer_bytes = event.id.to_bytes();
171 if crate::db::events::wrapper_event_exists(&event.id.to_hex()).unwrap_or(false)
172 || crate::db::wrappers::processed_wrapper_exists(&outer_bytes)
173 {
174 return None;
175 }
176 if channel.dissolved && event.kind.as_u16() != event_kind::COMMUNITY_DELETE {
184 return None;
185 }
186 let opened = match open_message_multi(event, &channel.id, &channel.read_epoch_keys()) {
190 Ok(o) => o,
191 Err(e) => {
192 crate::log_debug!("[community] inbound drop {}: {}", event.id.to_hex(), e);
193 return None;
194 }
195 };
196 if channel.banned.contains(&opened.author) {
199 crate::log_debug!("[community] dropped event from banned author {}", opened.author.to_hex());
200 return None;
201 }
202 let outcome = match opened.kind {
203 k if k == event_kind::COMMUNITY_MESSAGE => {
204 ingest_message(state, &opened, my_pubkey).map(IncomingEvent::NewMessage)
205 }
206 k if k == event_kind::COMMUNITY_REACTION => apply_reaction(state, &opened, my_pubkey),
207 k if k == event_kind::COMMUNITY_EDIT => apply_edit(state, &opened, my_pubkey),
208 k if k == event_kind::COMMUNITY_DELETE => apply_delete(state, &opened, channel, my_pubkey),
209 k if k == event_kind::COMMUNITY_PRESENCE => apply_presence(&opened, channel, my_pubkey),
210 k if k == event_kind::COMMUNITY_KICK => apply_kick(&opened, channel, my_pubkey),
211 k if k == event_kind::COMMUNITY_WEBXDC => apply_webxdc(&opened, my_pubkey),
212 k if k == event_kind::COMMUNITY_TYPING => apply_typing(&opened, my_pubkey),
213 _ => None,
214 };
215 if let Some(ref evt) = outcome {
221 if !matches!(evt, IncomingEvent::NewMessage(_) | IncomingEvent::Typing { .. }) {
222 let _ = crate::db::wrappers::save_processed_wrapper(
223 &outer_bytes, event.created_at.as_secs(), crate::db::wrappers::TRANSPORT_CONCORD,
224 );
225 }
226 }
227 outcome
228}
229
230fn apply_presence(opened: &OpenedMessage, channel: &Channel, my_pubkey: &PublicKey) -> Option<IncomingEvent> {
234 let joined = opened.content != "leave";
236 if !joined && opened.author == *my_pubkey {
240 if let Ok(Some(cid)) = crate::db::community::community_id_for_channel(&channel.id.to_hex()) {
241 let cid_bytes = crate::community::CommunityId(crate::simd::hex::hex_to_bytes_32(&cid));
249 let join_ms = crate::db::community::community_created_at_ms(&cid_bytes).unwrap_or(0);
250 if opened.created_at.as_secs().saturating_mul(1000) > join_ms {
251 return Some(IncomingEvent::SelfLeft { community_id: cid });
252 }
253 crate::log_debug!("[community] self-leave predates this join — rendering as history, not teardown");
254 }
255 }
256 let (invited_by, invited_label) = if joined {
257 serde_json::from_str::<serde_json::Value>(&opened.content)
258 .ok()
259 .map(|v| {
260 let by = v.get("by").and_then(|b| b.as_str())
264 .filter(|s| PublicKey::parse(s).is_ok())
265 .map(str::to_string);
266 let label = v.get("l").and_then(|l| l.as_str())
267 .map(|s| s.chars().take(48).collect::<String>())
268 .filter(|s| !s.is_empty());
269 (by, label)
270 })
271 .unwrap_or((None, None))
272 } else {
273 (None, None)
274 };
275 Some(IncomingEvent::Presence {
276 npub: opened.author.to_bech32().ok()?,
277 joined,
278 event_id: opened.message_id.to_hex(),
279 created_at: clamp_inner_secs(opened.created_at.as_secs()),
280 invited_by,
281 invited_label,
282 })
283}
284
285fn clamp_inner_secs(secs: u64) -> u64 {
289 let now = std::time::SystemTime::now()
290 .duration_since(std::time::UNIX_EPOCH)
291 .map(|d| d.as_secs())
292 .unwrap_or(0);
293 secs.min(now + 300)
294}
295
296fn apply_webxdc(opened: &OpenedMessage, my_pubkey: &PublicKey) -> Option<IncomingEvent> {
302 if opened.author == *my_pubkey {
303 return None;
304 }
305 let v: serde_json::Value = serde_json::from_str(&opened.content).ok()?;
306 let topic_id = v.get("topic").and_then(|t| t.as_str())
307 .filter(|t| t.len() == 52 && t.bytes().all(|b| b.is_ascii_uppercase() || (b'2'..=b'7').contains(&b)))?
308 .to_string();
309 let node_addr = match v.get("op").and_then(|o| o.as_str())? {
310 "ad" => Some(
311 v.get("addr").and_then(|a| a.as_str())
312 .filter(|a| !a.is_empty() && a.len() <= 2048)?
313 .to_string(),
314 ),
315 "left" => None,
316 _ => return None,
317 };
318 Some(IncomingEvent::WebxdcPeer {
319 npub: opened.author.to_bech32().ok()?,
320 topic_id,
321 node_addr,
322 event_id: opened.message_id.to_hex(),
323 created_at: opened.created_at.as_secs(),
324 })
325}
326
327fn apply_typing(opened: &OpenedMessage, my_pubkey: &PublicKey) -> Option<IncomingEvent> {
332 if opened.author == *my_pubkey {
333 return None;
334 }
335 if opened.content != "typing" {
336 return None;
337 }
338 let now = std::time::SystemTime::now()
339 .duration_since(std::time::UNIX_EPOCH)
340 .map(|d| d.as_secs())
341 .unwrap_or(0);
342 Some(IncomingEvent::Typing {
343 npub: opened.author.to_bech32().ok()?,
344 until: now + 30,
345 })
346}
347
348fn apply_kick(opened: &OpenedMessage, channel: &Channel, my_pubkey: &PublicKey) -> Option<IncomingEvent> {
359 use crate::community::roles::Permissions;
360 let target = PublicKey::parse(opened.content.trim()).ok()?;
361 let target_hex = target.to_hex();
362 let kicker_hex = opened.author.to_hex();
363 let owner_hex = channel.protected.first().map(|pk| pk.to_hex());
364 let pinned = actor_authority_pinned(channel, owner_hex.as_deref(), &kicker_hex, opened.citation.as_ref());
365 if !(pinned && channel.roster.can_act_on_member(&kicker_hex, owner_hex.as_deref(), &target_hex, Permissions::KICK)) {
366 crate::log_debug!("[community] dropped kick: {kicker_hex} not authorized to kick {target_hex}");
367 return None;
368 }
369 let cid_hex = crate::db::community::community_id_for_channel(&channel.id.to_hex()).ok().flatten()?;
370 let cid = crate::community::CommunityId(crate::simd::hex::hex_to_bytes_32(&cid_hex));
375 let join_ms = crate::db::community::community_created_at_ms(&cid).unwrap_or(0);
376 if opened.created_at.as_secs().saturating_mul(1000) <= join_ms {
379 crate::log_debug!("[community] dropped stale kick of {target_hex} (predates this join)");
380 return None;
381 }
382 if target == *my_pubkey {
383 return Some(IncomingEvent::Kicked { community_id: cid_hex });
384 }
385 Some(IncomingEvent::Presence {
387 npub: target.to_bech32().ok()?,
388 joined: false,
389 event_id: opened.message_id.to_hex(),
390 created_at: clamp_inner_secs(opened.created_at.as_secs()),
391 invited_by: None,
392 invited_label: None,
393 })
394}
395
396pub fn event_authenticates(event: &Event, channel: &Channel) -> bool {
409 if crate::db::events::wrapper_event_exists(&event.id.to_hex()).unwrap_or(false)
410 || crate::db::wrappers::processed_wrapper_exists(&event.id.to_bytes())
411 {
412 return true;
413 }
414 open_message_multi(event, &channel.id, &channel.read_epoch_keys()).is_ok()
415}
416
417pub fn process_channel_batch(
431 state: &mut ChatState,
432 events: &[Event],
433 channel: &Channel,
434 my_pubkey: &PublicKey,
435) -> Vec<IncomingEvent> {
436 let mut out = Vec::new();
437 for want_message in [true, false] {
440 for ev in events {
441 let is_message = ev.kind.as_u16() == event_kind::COMMUNITY_MESSAGE;
442 if is_message != want_message {
443 continue;
444 }
445 if let Some(evt) = process_incoming(state, ev, channel, my_pubkey) {
446 out.push(evt);
447 }
448 }
449 }
450 out
451}
452
453fn apply_reaction(state: &mut ChatState, opened: &OpenedMessage, my_pubkey: &PublicKey) -> Option<IncomingEvent> {
457 use crate::rumor::{process_rumor, RumorProcessingResult};
458 let (rumor, ctx) = concord_rumor(opened, nostr_sdk::Kind::Reaction, my_pubkey);
459 let reaction = match process_rumor(rumor, ctx, &crate::db::get_download_dir()) {
460 Ok(RumorProcessingResult::Reaction(r)) => r,
461 _ => return None,
462 };
463 let target_id = reaction.reference_id.clone();
464 let expected_chat = opened.channel_id.to_hex();
469 if !matches!(state.find_message(&target_id), Some((chat, _)) if chat.id == expected_chat) {
470 return None;
471 }
472 let (_chat_id, was_added) = state.add_reaction_to_message(&target_id, reaction)?;
473 if !was_added {
474 return None;
475 }
476 let (_chat, message) = state.find_message(&target_id)?;
477 Some(IncomingEvent::Updated { target_id, message, edit_event: None })
478}
479
480fn apply_edit(state: &mut ChatState, opened: &OpenedMessage, my_pubkey: &PublicKey) -> Option<IncomingEvent> {
484 use crate::rumor::{process_rumor, RumorProcessingResult};
485 let (rumor, ctx) = concord_rumor(opened, nostr_sdk::Kind::from(event_kind::MESSAGE_EDIT), my_pubkey);
486 let (target_id, new_content, edited_at, emoji_tags, edit_event) = match process_rumor(rumor, ctx, &crate::db::get_download_dir()) {
487 Ok(RumorProcessingResult::Edit { message_id, new_content, edited_at, emoji_tags, event }) => (message_id, new_content, edited_at, emoji_tags, event),
488 _ => return None,
489 };
490 let editor_npub = opened.author.to_bech32().ok()?;
493 let target_author = state.find_message(&target_id).and_then(|(_, m)| m.npub)?;
494 if target_author != editor_npub {
495 crate::log_debug!("[community] dropped edit from non-author of {}", target_id);
496 return None;
497 }
498 let (_chat_id, message) = state.update_message(&target_id, |m| {
501 m.apply_edit(new_content.clone(), edited_at, emoji_tags.clone());
502 })?;
503 Some(IncomingEvent::Updated { target_id, message, edit_event: Some(Box::new(edit_event)) })
506}
507
508fn actor_authority_pinned(
518 channel: &Channel,
519 owner_hex: Option<&str>,
520 actor_hex: &str,
521 citation: Option<&super::edition::AuthorityCitation>,
522) -> bool {
523 if owner_hex == Some(actor_hex) {
524 return true; }
526 if citation.is_none() {
527 return false; }
529 let Ok(Some(cid)) = crate::db::community::community_id_for_channel(&channel.id.to_hex()) else {
530 return false; };
532 let cid_bytes = crate::simd::hex::hex_to_bytes_32(&cid);
533 let actor_bytes = crate::simd::hex::hex_to_bytes_32(actor_hex);
534 let grant_hex = crate::simd::hex::bytes_to_hex_32(&super::derive::grant_locator(
535 &crate::community::CommunityId(cid_bytes),
536 &actor_bytes,
537 ));
538 let head: Vec<super::roster::EntityHead> = crate::db::community::get_edition_head(&cid, &grant_hex)
539 .ok()
540 .flatten()
541 .map(|(version, self_hash)| super::roster::EntityHead { entity_hex: grant_hex.clone(), version, self_hash, inner_id: [0u8; 32], citation: None })
542 .into_iter()
543 .collect();
544 super::roster::authority_citation_satisfied(&head, owner_hex, actor_hex, &grant_hex, citation)
545}
546
547fn apply_delete(state: &mut ChatState, opened: &OpenedMessage, channel: &Channel, my_pubkey: &PublicKey) -> Option<IncomingEvent> {
548 use crate::community::roles::Permissions;
549 use crate::rumor::{process_rumor, RumorProcessingResult};
550 let (rumor, ctx) = concord_rumor(opened, nostr_sdk::Kind::EventDeletion, my_pubkey);
554 let target_id = match process_rumor(rumor, ctx, &crate::db::get_download_dir()) {
555 Ok(RumorProcessingResult::DeletionRequest { target_event_id }) => target_event_id,
556 _ => return None,
557 };
558 let deleter = opened.author;
559 let deleter_hex = deleter.to_hex();
560
561 if let Some((_chat_id, message_id, author_npub, _is_comm)) = state.find_reaction(&target_id) {
565 let reactor_ok = PublicKey::parse(&author_npub).map(|pk| pk == deleter).unwrap_or(false);
566 if !reactor_ok {
567 crate::log_debug!("[community] dropped reaction-revoke: {deleter_hex} is not the reactor of {target_id}");
568 return None;
569 }
570 return state
571 .remove_reaction_from_message(&message_id, &target_id)
572 .map(|(_cid, message)| IncomingEvent::ReactionRemoved {
573 message_id,
574 reaction_id: target_id,
575 message,
576 });
577 }
578
579 let owner_hex = channel.protected.first().map(|pk| pk.to_hex());
580 let pinned = actor_authority_pinned(channel, owner_hex.as_deref(), &deleter_hex, opened.citation.as_ref());
583
584 let target_author = state
587 .find_message(&target_id)
588 .and_then(|(_, m)| m.npub.clone())
589 .and_then(|n| PublicKey::parse(&n).ok());
590
591 if let Some(author) = target_author {
592 if author == deleter {
594 return state.remove_message(&target_id).map(|_| IncomingEvent::Removed { target_id });
595 }
596 if pinned && !channel.dissolved && channel.roster.can_act_on_member(&deleter_hex, owner_hex.as_deref(), &author.to_hex(), Permissions::MANAGE_MESSAGES) {
602 return state.remove_message(&target_id).map(|_| IncomingEvent::Removed { target_id });
603 }
604 crate::log_debug!("[community] dropped delete: {deleter_hex} not authorized to remove {target_id}");
605 return None;
606 }
607
608 if let Ok(Some(author_npub)) = crate::db::events::event_author(&target_id) {
612 if let Ok(author) = PublicKey::parse(&author_npub) {
613 let ok = author == deleter
617 || (pinned
618 && !channel.dissolved
619 && channel.roster.can_act_on_member(&deleter_hex, owner_hex.as_deref(), &author.to_hex(), Permissions::MANAGE_MESSAGES));
620 if ok {
621 return Some(IncomingEvent::Removed { target_id });
622 }
623 crate::log_debug!("[community] dropped out-of-window delete: {deleter_hex} not authorized over {target_id}");
624 return None;
625 }
626 }
627
628 None
636}
637
638pub fn route_incoming(
644 state: &mut ChatState,
645 event: &Event,
646 routes: &std::collections::HashMap<String, Channel>,
647 my_pubkey: &PublicKey,
648) -> Option<IncomingEvent> {
649 let pseudonym = event.tags.iter().find_map(|t| {
650 let s = t.as_slice();
651 (s.len() >= 2 && s[0] == "z").then(|| s[1].clone())
652 })?;
653 let channel = routes.get(&pseudonym)?;
654 process_incoming(state, event, channel, my_pubkey)
655}
656
657#[cfg(test)]
658mod tests {
659 use super::*;
660 use crate::community::derive::channel_pseudonym;
661 use std::collections::HashMap;
662 use crate::community::envelope::{build_inner_full, build_inner_typed, open_message, seal_message, seal_with_signed_inner};
663 use crate::community::edition::AuthorityCitation;
664 use crate::community::{Channel, ChannelId, ChannelKey, Epoch};
665 use crate::state::ChatState;
666 use nostr_sdk::prelude::{Keys, Tag};
667
668 fn db_roster_channel(
674 owner: &Keys,
675 admin: &PublicKey,
676 ) -> (tempfile::TempDir, std::sync::MutexGuard<'static, ()>, Channel, AuthorityCitation) {
677 use crate::community::roles::{CommunityRoles, MemberGrant, Role};
678 use nostr_sdk::{JsonUtil, ToBech32};
679 let guard = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
680 crate::db::close_database();
681 let tmp = tempfile::tempdir().unwrap();
682 let account = owner.public_key().to_bech32().unwrap();
683 std::fs::create_dir_all(tmp.path().join(&account)).unwrap();
684 crate::db::set_app_data_dir(tmp.path().to_path_buf());
685 crate::db::set_current_account(account.clone()).unwrap();
686 crate::db::init_database(&account).unwrap();
687 crate::state::MY_SECRET_KEY.store_from_keys(owner, &[]);
688 crate::state::set_my_public_key(owner.public_key());
689
690 let mut community = crate::community::Community::create("HQ", "general", vec!["r".into()]);
691 let cid = community.id.to_hex();
692 community.owner_attestation = Some(
693 crate::community::owner::build_owner_attestation_unsigned(owner.public_key(), &cid)
694 .sign_with_keys(owner)
695 .unwrap()
696 .as_json(),
697 );
698 crate::db::community::save_community(&community).unwrap();
699
700 let role = Role::admin("a".repeat(64));
703 let roster = CommunityRoles {
704 grants: vec![MemberGrant { member: admin.to_hex(), role_ids: vec![role.role_id.clone()] }],
705 roles: vec![role],
706 };
707 crate::db::community::set_community_roles(&cid, &roster, 0).unwrap();
708 let entity_id = crate::community::derive::grant_locator(&community.id, &admin.to_bytes());
709 let entity_hex = crate::simd::hex::bytes_to_hex_32(&entity_id);
710 let hash = [0x5Au8; 32];
711 crate::db::community::set_edition_head(&cid, &entity_hex, 1, &hash).unwrap();
712
713 let reloaded = crate::db::community::load_community(&community.id).unwrap().unwrap();
714 let channel = reloaded.channels[0].clone();
715 (tmp, guard, channel, AuthorityCitation { entity_id, version: 1, edition_hash: hash })
716 }
717
718 fn seal_hide(channel: &Channel, author: &Keys, target: &str, ms: u64, citation: Option<&AuthorityCitation>) -> Event {
720 let extra: Vec<Tag> = citation.iter().map(|c| c.to_tag()).collect();
721 let inner = build_inner_full(
722 author.public_key(), &channel.id, channel.epoch, event_kind::COMMUNITY_DELETE, "", ms, Some(target), &[], &extra,
723 )
724 .sign_with_keys(author)
725 .unwrap();
726 seal_with_signed_inner(&Keys::generate(), &inner, &channel.key, &channel.id, channel.epoch).unwrap()
727 }
728
729 fn ingest_msg_in(state: &mut ChatState, channel: &Channel, author: &Keys, content: &str, ms: u64, viewer: &Keys) -> String {
731 let outer = seal_message(author, &channel.key, &channel.id, channel.epoch, content, ms).unwrap();
732 match process_incoming(state, &outer, channel, &viewer.public_key()) {
733 Some(IncomingEvent::NewMessage(m)) => m.id,
734 _ => panic!("expected a new message"),
735 }
736 }
737
738 fn opened_from(author: &Keys, content: &str, ms: u64) -> OpenedMessage {
739 let key = ChannelKey([0x33u8; 32]);
740 let chan = ChannelId([0x44u8; 32]);
741 let outer = seal_message(author, &key, &chan, Epoch(0), content, ms).unwrap();
742 open_message(&outer, &key, &chan, Epoch(0)).unwrap()
743 }
744
745 fn test_channel() -> Channel {
746 Channel { id: ChannelId([0x44u8; 32]), key: ChannelKey([0x33u8; 32]), epoch: Epoch(0), name: "t".into(), banned: Vec::new(), protected: Vec::new(), roster: Default::default(), epoch_keys: Vec::new(), dissolved: false }
747 }
748
749 fn seal_typed(author: &Keys, kind: u16, content: &str, ms: u64, target: &str) -> Event {
751 let c = test_channel();
752 let inner = build_inner_typed(author.public_key(), &c.id, c.epoch, kind, content, ms, Some(target), &[])
753 .sign_with_keys(author)
754 .unwrap();
755 seal_with_signed_inner(&Keys::generate(), &inner, &c.key, &c.id, c.epoch).unwrap()
756 }
757
758 fn ingest_msg(state: &mut ChatState, author: &Keys, content: &str, ms: u64, viewer: &Keys) -> String {
759 let c = test_channel();
760 let outer = seal_message(author, &c.key, &c.id, c.epoch, content, ms).unwrap();
761 match process_incoming(state, &outer, &c, &viewer.public_key()) {
762 Some(IncomingEvent::NewMessage(m)) => m.id,
763 _ => panic!("expected a new message"),
764 }
765 }
766
767 #[test]
768 fn inbound_reaction_applies_to_target_and_dedups() {
769 use crate::stored_event::event_kind;
770 let mut state = ChatState::new();
771 let alice = Keys::generate();
772 let bob = Keys::generate();
773 let target = ingest_msg(&mut state, &alice, "hi", 1, &bob);
774
775 let react = seal_typed(&bob, event_kind::COMMUNITY_REACTION, "🔥", 2, &target);
776 match process_incoming(&mut state, &react, &test_channel(), &bob.public_key()) {
777 Some(IncomingEvent::Updated { target_id, message, edit_event: None }) => {
778 assert_eq!(target_id, target);
779 assert!(message.reactions.iter().any(|r| r.emoji == "🔥"), "reaction applied to target");
780 }
781 _ => panic!("expected a reaction update"),
782 }
783 assert!(process_incoming(&mut state, &react, &test_channel(), &bob.public_key()).is_none());
785 }
786
787 #[test]
788 fn reaction_cross_channel_is_rejected() {
789 use crate::stored_event::event_kind;
792 use crate::community::envelope::{build_inner_typed, seal_with_signed_inner};
793 let mut state = ChatState::new();
794 let alice = Keys::generate();
795 let bob = Keys::generate();
796 let chan_a = test_channel();
797 let chan_b = Channel {
798 id: ChannelId([0x55u8; 32]), key: ChannelKey([0x66u8; 32]), epoch: Epoch(0),
799 name: "b".into(), banned: Vec::new(), protected: Vec::new(),
800 roster: Default::default(), epoch_keys: Vec::new(), dissolved: false,
801 };
802 let target = ingest_msg_in(&mut state, &chan_a, &alice, "hi", 1, &bob);
804 let inner = build_inner_typed(
806 bob.public_key(), &chan_b.id, chan_b.epoch, event_kind::COMMUNITY_REACTION, "🔥", 2, Some(&target), &[],
807 ).sign_with_keys(&bob).unwrap();
808 let outer = seal_with_signed_inner(&Keys::generate(), &inner, &chan_b.key, &chan_b.id, chan_b.epoch).unwrap();
809 assert!(
811 process_incoming(&mut state, &outer, &chan_b, &bob.public_key()).is_none(),
812 "a reaction sealed under another channel must not apply to this channel's message"
813 );
814 let (_c, msg) = state.find_message(&target).unwrap();
815 assert!(msg.reactions.is_empty(), "cross-channel reaction must not be applied");
816 }
817
818 #[test]
819 fn inbound_message_carries_multi_attachments() {
820 use crate::stored_event::event_kind;
821 use crate::community::attachments::attachment_to_imeta;
822 use crate::community::envelope::build_inner_full;
823 use crate::types::Attachment;
824 let mut state = ChatState::new();
825 let alice = Keys::generate();
826 let bob = Keys::generate();
827 let c = test_channel();
828
829 let mk = |n: &str, ext: &str| Attachment {
830 id: "x".into(), key: "0".repeat(64), nonce: format!("{:0<24}", crate::simd::hex::bytes_to_hex_string(n.as_bytes())),
831 extension: ext.into(), name: n.into(), url: format!("https://b/{n}"),
832 path: String::new(), size: 9, img_meta: None, downloading: false, downloaded: false,
833 webxdc_topic: None, group_id: None, original_hash: Some("a".repeat(64)),
834 scheme_version: None, mls_filename: None,
835 };
836 let imetas = vec![attachment_to_imeta(&mk("a.png", "png")), attachment_to_imeta(&mk("b.txt", "txt"))];
837 let inner = build_inner_full(
838 alice.public_key(), &c.id, c.epoch, event_kind::COMMUNITY_MESSAGE,
839 "caption", 5, None, &[], &imetas,
840 ).sign_with_keys(&alice).unwrap();
841 let outer = seal_with_signed_inner(&Keys::generate(), &inner, &c.key, &c.id, c.epoch).unwrap();
842
843 match process_incoming(&mut state, &outer, &c, &bob.public_key()) {
844 Some(IncomingEvent::NewMessage(m)) => {
845 assert_eq!(m.content, "caption", "caption + attachments coexist in one event");
846 assert_eq!(m.attachments.len(), 2);
847 assert_eq!(m.attachments[0].name, "a.png");
848 assert_eq!(m.attachments[1].name, "b.txt");
849 assert!(m.attachments.iter().all(|a| a.group_id.is_none()));
850 }
851 _ => panic!("expected new message with attachments"),
852 }
853 }
854
855 #[test]
856 fn inbound_edit_only_honored_from_original_author() {
857 use crate::stored_event::event_kind;
858 let mut state = ChatState::new();
859 let alice = Keys::generate();
860 let target = ingest_msg(&mut state, &alice, "original", 1, &alice);
861
862 let edit = seal_typed(&alice, event_kind::COMMUNITY_EDIT, "edited!", 2, &target);
864 match process_incoming(&mut state, &edit, &test_channel(), &alice.public_key()) {
865 Some(IncomingEvent::Updated { message, edit_event, .. }) => {
866 assert_eq!(message.content, "edited!");
867 assert!(message.edited);
868 let ev = edit_event.expect("edit surfaces a MESSAGE_EDIT event to persist");
870 assert_eq!(ev.kind, event_kind::MESSAGE_EDIT);
871 assert_eq!(ev.reference_id.as_deref(), Some(target.as_str()));
872 assert_eq!(ev.content, "edited!");
873 }
874 _ => panic!("expected an edit update"),
875 }
876
877 let mallory = Keys::generate();
879 let hijack = seal_typed(&mallory, event_kind::COMMUNITY_EDIT, "hijacked", 3, &target);
880 assert!(process_incoming(&mut state, &hijack, &test_channel(), &alice.public_key()).is_none());
881 assert_eq!(state.find_message(&target).unwrap().1.content, "edited!");
882 }
883
884 #[test]
885 fn cooperative_delete_only_honored_from_original_author() {
886 use crate::stored_event::event_kind;
887 let mut state = ChatState::new();
888 let alice = Keys::generate();
889 let mallory = Keys::generate();
890 let target = ingest_msg(&mut state, &alice, "secret", 1, &alice);
891
892 let hijack = seal_typed(&mallory, event_kind::COMMUNITY_DELETE, "", 2, &target);
894 assert!(process_incoming(&mut state, &hijack, &test_channel(), &alice.public_key()).is_none());
895 assert!(state.find_message(&target).is_some(), "non-author delete must not remove");
896
897 let del = seal_typed(&alice, event_kind::COMMUNITY_DELETE, "", 3, &target);
899 match process_incoming(&mut state, &del, &test_channel(), &alice.public_key()) {
900 Some(IncomingEvent::Removed { target_id }) => assert_eq!(target_id, target),
901 _ => panic!("expected a removal"),
902 }
903 assert!(state.find_message(&target).is_none(), "message gone after author delete");
904
905 let replay = seal_typed(&alice, event_kind::COMMUNITY_DELETE, "", 4, &target);
907 assert!(process_incoming(&mut state, &replay, &test_channel(), &alice.public_key()).is_none());
908 }
909
910 #[test]
911 fn dissolved_community_still_honors_an_own_message_delete() {
912 use crate::stored_event::event_kind;
913 let mut state = ChatState::new();
914 let alice = Keys::generate();
915 let target = ingest_msg(&mut state, &alice, "alice's own message", 1, &alice);
916 let mut ch = test_channel();
917 ch.dissolved = true;
918 let del = seal_typed(&alice, event_kind::COMMUNITY_DELETE, "", 2, &target);
921 match process_incoming(&mut state, &del, &ch, &alice.public_key()) {
922 Some(IncomingEvent::Removed { target_id }) => assert_eq!(target_id, target),
923 _ => panic!("a self-delete must be honored in a dissolved community"),
924 }
925 assert!(state.find_message(&target).is_none(), "own message scrubbed from the dead community");
926 }
927
928 #[test]
929 fn admin_moderation_hide_removes_any_message() {
930 let owner = Keys::generate();
931 let admin = Keys::generate(); let (_tmp, _guard, c, cite) = db_roster_channel(&owner, &admin.public_key());
933 let alice = Keys::generate(); let mallory = Keys::generate(); let mut state = ChatState::new();
936 let target = ingest_msg_in(&mut state, &c, &alice, "spicy take", 1, &alice);
937
938 let hijack = seal_hide(&c, &mallory, &target, 2, None);
940 assert!(process_incoming(&mut state, &hijack, &c, &alice.public_key()).is_none());
941 assert!(state.find_message(&target).is_some(), "unprivileged hide rejected");
942
943 let hide = seal_hide(&c, &admin, &target, 3, Some(&cite));
945 match process_incoming(&mut state, &hide, &c, &alice.public_key()) {
946 Some(IncomingEvent::Removed { target_id }) => assert_eq!(target_id, target),
947 _ => panic!("expected admin moderation-hide to remove the message"),
948 }
949 assert!(state.find_message(&target).is_none(), "admin hide removed the message");
950 }
951
952 #[test]
953 fn admin_hide_without_a_citation_is_dropped() {
954 let owner = Keys::generate();
958 let admin = Keys::generate();
959 let (_tmp, _guard, c, _cite) = db_roster_channel(&owner, &admin.public_key());
960 let alice = Keys::generate();
961 let mut state = ChatState::new();
962 let target = ingest_msg_in(&mut state, &c, &alice, "spicy take", 1, &alice);
963
964 let hide = seal_hide(&c, &admin, &target, 2, None); assert!(process_incoming(&mut state, &hide, &c, &alice.public_key()).is_none());
966 assert!(state.find_message(&target).is_some(), "an uncited admin hide is dropped");
967 }
968
969 #[test]
970 fn hide_citing_an_unsynced_grant_version_is_dropped() {
971 let owner = Keys::generate();
975 let admin = Keys::generate();
976 let (_tmp, _guard, c, cite) = db_roster_channel(&owner, &admin.public_key());
977 let alice = Keys::generate();
978 let mut state = ChatState::new();
979 let target = ingest_msg_in(&mut state, &c, &alice, "spicy take", 1, &alice);
980
981 let ahead = AuthorityCitation { version: 2, ..cite };
983 let hide = seal_hide(&c, &admin, &target, 2, Some(&ahead));
984 assert!(process_incoming(&mut state, &hide, &c, &alice.public_key()).is_none());
985 assert!(state.find_message(&target).is_some(), "a hide citing an unsynced version is dropped");
986 }
987
988 #[test]
989 fn hide_with_a_forged_citation_hash_is_dropped() {
990 let owner = Keys::generate();
992 let admin = Keys::generate();
993 let (_tmp, _guard, c, cite) = db_roster_channel(&owner, &admin.public_key());
994 let alice = Keys::generate();
995 let mut state = ChatState::new();
996 let target = ingest_msg_in(&mut state, &c, &alice, "spicy take", 1, &alice);
997
998 let forged = AuthorityCitation { edition_hash: [0xEE; 32], ..cite };
999 let hide = seal_hide(&c, &admin, &target, 2, Some(&forged));
1000 assert!(process_incoming(&mut state, &hide, &c, &alice.public_key()).is_none());
1001 assert!(state.find_message(&target).is_some(), "a forged-hash citation is dropped");
1002 }
1003
1004 #[test]
1005 fn protected_owner_cannot_be_moderation_hidden_but_others_can() {
1006 let owner = Keys::generate(); let admin = Keys::generate(); let (_tmp, _guard, c, cite) = db_roster_channel(&owner, &admin.public_key());
1009 let mut state = ChatState::new();
1010
1011 let owners_msg = ingest_msg_in(&mut state, &c, &owner, "owner speaks", 1, &owner);
1013 let hide_owner = seal_hide(&c, &admin, &owners_msg, 2, Some(&cite));
1014 assert!(process_incoming(&mut state, &hide_owner, &c, &owner.public_key()).is_none());
1015 assert!(state.find_message(&owners_msg).is_some(), "owner's message is protected");
1016
1017 let member = Keys::generate();
1019 let members_msg = ingest_msg_in(&mut state, &c, &member, "member speaks", 3, &owner);
1020 let hide_member = seal_hide(&c, &admin, &members_msg, 4, Some(&cite));
1021 match process_incoming(&mut state, &hide_member, &c, &owner.public_key()) {
1022 Some(IncomingEvent::Removed { target_id }) => assert_eq!(target_id, members_msg),
1023 _ => panic!("a non-protected member's message should be hideable"),
1024 }
1025 }
1026
1027 #[test]
1028 fn admin_hide_of_absent_target_defers_until_resident() {
1029 let owner = Keys::generate();
1037 let admin = Keys::generate();
1038 let (_tmp, _guard, c, cite) = db_roster_channel(&owner, &admin.public_key());
1039 let mut state = ChatState::new();
1040 let absent_target = "f".repeat(64); let hide = seal_hide(&c, &admin, &absent_target, 1, Some(&cite));
1043 assert!(
1044 process_incoming(&mut state, &hide, &c, &Keys::generate().public_key()).is_none(),
1045 "a hide of an absent target defers (None) rather than falsely tombstoning + self-deduping",
1046 );
1047
1048 let mallory = Keys::generate();
1050 let hijack = seal_hide(&c, &mallory, &absent_target, 2, None);
1051 assert!(process_incoming(&mut state, &hijack, &c, &mallory.public_key()).is_none());
1052
1053 let uncited = seal_hide(&c, &admin, &absent_target, 3, None);
1056 assert!(
1057 process_incoming(&mut state, &uncited, &c, &Keys::generate().public_key()).is_none(),
1058 "an admin's uncited hide of an unknown target is dropped (pinned gates the author-unknown path)"
1059 );
1060 }
1061
1062 #[tokio::test]
1063 async fn out_of_window_hide_authorizes_against_db_author() {
1064 use crate::types::Message;
1065 use nostr_sdk::ToBech32;
1069 let owner = Keys::generate();
1070 let admin = Keys::generate(); let member = Keys::generate();
1072 let (_tmp, _guard, c, cite) = db_roster_channel(&owner, &admin.public_key());
1073
1074 let owner_msg = "a".repeat(64);
1076 let member_msg = "b".repeat(64);
1077 let mk = |id: &str, author: &Keys, at: u64| {
1078 let mut m = Message::default();
1079 m.id = id.to_string();
1080 m.npub = Some(author.public_key().to_bech32().unwrap());
1081 m.at = at;
1082 m
1083 };
1084 crate::db::events::save_message("chatoow", &mk(&owner_msg, &owner, 1)).await.unwrap();
1085 crate::db::events::save_message("chatoow", &mk(&member_msg, &member, 2)).await.unwrap();
1086
1087 let mut state = ChatState::new();
1088 let hide_owner = seal_hide(&c, &admin, &owner_msg, 3, Some(&cite));
1090 assert!(
1091 process_incoming(&mut state, &hide_owner, &c, &member.public_key()).is_none(),
1092 "owner's paged-out message must not be hideable by an admin"
1093 );
1094 let hide_member = seal_hide(&c, &admin, &member_msg, 4, Some(&cite));
1096 match process_incoming(&mut state, &hide_member, &c, &owner.public_key()) {
1097 Some(IncomingEvent::Removed { target_id }) => assert_eq!(target_id, member_msg),
1098 _ => panic!("admin should hide a member's paged-out message"),
1099 }
1100
1101 let member_msg2 = "c".repeat(64);
1105 crate::db::events::save_message("chatoow", &mk(&member_msg2, &member, 5)).await.unwrap();
1106 let mut sealed = c.clone();
1107 sealed.dissolved = true;
1108 let hide_sealed = seal_hide(&sealed, &admin, &member_msg2, 6, Some(&cite));
1109 assert!(
1110 process_incoming(&mut state, &hide_sealed, &sealed, &owner.public_key()).is_none(),
1111 "a dissolved community accepts no moderation-hide, resident or paged-out"
1112 );
1113 let self_del = seal_hide(&sealed, &member, &member_msg2, 7, None);
1114 match process_incoming(&mut state, &self_del, &sealed, &owner.public_key()) {
1115 Some(IncomingEvent::Removed { target_id }) => assert_eq!(target_id, member_msg2),
1116 _ => panic!("a self-delete of a paged-out message must survive the dissolved seal"),
1117 }
1118 crate::db::close_database();
1119 }
1120
1121 fn seal_kick(channel: &Channel, author: &Keys, target_hex: &str, ms: u64, citation: Option<&AuthorityCitation>) -> Event {
1123 let extra: Vec<Tag> = citation.iter().map(|c| c.to_tag()).collect();
1124 let inner = build_inner_full(
1125 author.public_key(), &channel.id, channel.epoch, event_kind::COMMUNITY_KICK, target_hex, ms, None, &[], &extra,
1126 )
1127 .sign_with_keys(author)
1128 .unwrap();
1129 seal_with_signed_inner(&Keys::generate(), &inner, &channel.key, &channel.id, channel.epoch).unwrap()
1130 }
1131
1132 fn post_join_ms() -> u64 {
1135 let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_secs();
1136 (now + 5) * 1000
1137 }
1138
1139 #[test]
1140 fn cited_admin_kick_of_local_user_yields_self_removal() {
1141 let owner = Keys::generate();
1142 let admin = Keys::generate();
1143 let member = Keys::generate();
1144 let (_tmp, _g, channel, cite) = db_roster_channel(&owner, &admin.public_key());
1145 let mut state = ChatState::new();
1146 let kick = seal_kick(&channel, &admin, &member.public_key().to_hex(), post_join_ms(), Some(&cite));
1148 match process_incoming(&mut state, &kick, &channel, &member.public_key()) {
1149 Some(IncomingEvent::Kicked { community_id }) => assert!(!community_id.is_empty()),
1150 _ => panic!("expected Kicked"),
1151 }
1152 crate::db::close_database();
1153 }
1154
1155 #[test]
1156 fn cited_admin_kick_of_other_member_is_a_leave() {
1157 use nostr_sdk::ToBech32;
1158 let owner = Keys::generate();
1159 let admin = Keys::generate();
1160 let member = Keys::generate();
1161 let (_tmp, _g, channel, cite) = db_roster_channel(&owner, &admin.public_key());
1162 let mut state = ChatState::new();
1163 let kick = seal_kick(&channel, &admin, &member.public_key().to_hex(), post_join_ms(), Some(&cite));
1166 match process_incoming(&mut state, &kick, &channel, &owner.public_key()) {
1167 Some(IncomingEvent::Presence { npub, joined, .. }) => {
1168 assert!(!joined);
1169 assert_eq!(npub, member.public_key().to_bech32().unwrap());
1170 }
1171 _ => panic!("expected leave Presence"),
1172 }
1173 crate::db::close_database();
1174 }
1175
1176 #[test]
1177 fn uncited_kick_is_dropped() {
1178 let owner = Keys::generate();
1179 let admin = Keys::generate();
1180 let member = Keys::generate();
1181 let (_tmp, _g, channel, _cite) = db_roster_channel(&owner, &admin.public_key());
1182 let mut state = ChatState::new();
1183 let kick = seal_kick(&channel, &admin, &member.public_key().to_hex(), 1, None);
1184 assert!(process_incoming(&mut state, &kick, &channel, &member.public_key()).is_none(),
1185 "a non-owner kick without a citation is dropped");
1186 crate::db::close_database();
1187 }
1188
1189 #[test]
1190 fn unprivileged_kick_is_dropped() {
1191 let owner = Keys::generate();
1192 let admin = Keys::generate();
1193 let mallory = Keys::generate();
1194 let member = Keys::generate();
1195 let (_tmp, _g, channel, cite) = db_roster_channel(&owner, &admin.public_key());
1196 let mut state = ChatState::new();
1197 let kick = seal_kick(&channel, &mallory, &member.public_key().to_hex(), 1, Some(&cite));
1200 assert!(process_incoming(&mut state, &kick, &channel, &member.public_key()).is_none(),
1201 "a kick from an unranked actor is dropped");
1202 crate::db::close_database();
1203 }
1204
1205 #[test]
1206 fn kick_of_owner_is_dropped() {
1207 let owner = Keys::generate();
1208 let admin = Keys::generate();
1209 let (_tmp, _g, channel, cite) = db_roster_channel(&owner, &admin.public_key());
1210 let mut state = ChatState::new();
1211 let kick = seal_kick(&channel, &admin, &owner.public_key().to_hex(), post_join_ms(), Some(&cite));
1213 assert!(process_incoming(&mut state, &kick, &channel, &owner.public_key()).is_none(),
1214 "an admin cannot kick the owner");
1215 crate::db::close_database();
1216 }
1217
1218 #[test]
1219 fn stale_kick_predating_join_is_dropped() {
1220 let owner = Keys::generate();
1221 let admin = Keys::generate();
1222 let member = Keys::generate();
1223 let (_tmp, _g, channel, cite) = db_roster_channel(&owner, &admin.public_key());
1224 let mut state = ChatState::new();
1225 let kick = seal_kick(&channel, &admin, &member.public_key().to_hex(), 1, Some(&cite));
1228 assert!(process_incoming(&mut state, &kick, &channel, &member.public_key()).is_none(),
1229 "a kick older than the current join is dropped");
1230 crate::db::close_database();
1231 }
1232
1233 #[test]
1234 fn webxdc_signals_parse_ad_and_left_and_reject_garbage() {
1235 use crate::stored_event::event_kind;
1236 use nostr_sdk::ToBech32;
1237 let mut state = ChatState::new();
1238 let alice = Keys::generate();
1239 let c = test_channel();
1240 let viewer = Keys::generate();
1241 let mk = |content: &str, ms: u64| {
1242 let inner = build_inner_typed(alice.public_key(), &c.id, c.epoch, event_kind::COMMUNITY_WEBXDC, content, ms, None, &[])
1243 .sign_with_keys(&alice).unwrap();
1244 seal_with_signed_inner(&Keys::generate(), &inner, &c.key, &c.id, c.epoch).unwrap()
1245 };
1246 let topic = crate::webxdc::mint_topic_id("game-hash", "sender");
1247
1248 let ad = serde_json::json!({ "op": "ad", "topic": topic, "addr": "BASE32NODEADDR" }).to_string();
1250 match process_incoming(&mut state, &mk(&ad, 1), &c, &viewer.public_key()) {
1251 Some(IncomingEvent::WebxdcPeer { npub, topic_id, node_addr, .. }) => {
1252 assert_eq!(npub, alice.public_key().to_bech32().unwrap(), "player is the inner author");
1253 assert_eq!(topic_id, topic);
1254 assert_eq!(node_addr.as_deref(), Some("BASE32NODEADDR"));
1255 }
1256 _ => panic!("expected a webxdc advertisement"),
1257 }
1258
1259 let left = serde_json::json!({ "op": "left", "topic": topic }).to_string();
1261 match process_incoming(&mut state, &mk(&left, 2), &c, &viewer.public_key()) {
1262 Some(IncomingEvent::WebxdcPeer { node_addr, .. }) => {
1263 assert!(node_addr.is_none(), "peer-left carries no addr");
1264 }
1265 _ => panic!("expected a webxdc peer-left"),
1266 }
1267
1268 assert!(
1270 process_incoming(&mut state, &mk(&ad, 3), &c, &alice.public_key()).is_none(),
1271 "own webxdc signal must be ignored"
1272 );
1273
1274 let bad_topic = serde_json::json!({ "op": "ad", "topic": "../../etc", "addr": "X" }).to_string();
1276 assert!(process_incoming(&mut state, &mk(&bad_topic, 4), &c, &viewer.public_key()).is_none());
1277 let bad_op = serde_json::json!({ "op": "explode", "topic": topic }).to_string();
1278 assert!(process_incoming(&mut state, &mk(&bad_op, 5), &c, &viewer.public_key()).is_none());
1279 let no_addr = serde_json::json!({ "op": "ad", "topic": topic }).to_string();
1280 assert!(process_incoming(&mut state, &mk(&no_addr, 6), &c, &viewer.public_key()).is_none());
1281 assert!(process_incoming(&mut state, &mk("not json", 7), &c, &viewer.public_key()).is_none());
1282 }
1283
1284 #[test]
1285 fn typing_indicator_parses_drops_own_echo_and_rejects_garbage() {
1286 use crate::stored_event::event_kind;
1287 use nostr_sdk::ToBech32;
1288 let mut state = ChatState::new();
1289 let alice = Keys::generate();
1290 let c = test_channel();
1291 let viewer = Keys::generate();
1292 let mk = |content: &str, ms: u64| {
1293 let inner = build_inner_typed(alice.public_key(), &c.id, c.epoch, event_kind::COMMUNITY_TYPING, content, ms, None, &[])
1294 .sign_with_keys(&alice).unwrap();
1295 seal_with_signed_inner(&Keys::generate(), &inner, &c.key, &c.id, c.epoch).unwrap()
1296 };
1297 let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_secs();
1298
1299 match process_incoming(&mut state, &mk("typing", 1), &c, &viewer.public_key()) {
1302 Some(IncomingEvent::Typing { npub, until }) => {
1303 assert_eq!(npub, alice.public_key().to_bech32().unwrap(), "typer is the inner author");
1304 assert!(until >= now && until <= now + 31, "until is receiver-computed (~now + 30s)");
1305 }
1306 _ => panic!("expected a typing indicator"),
1307 }
1308
1309 assert!(
1311 process_incoming(&mut state, &mk("typing", 2), &c, &alice.public_key()).is_none(),
1312 "own typing signal must be ignored"
1313 );
1314
1315 assert!(process_incoming(&mut state, &mk("nope", 3), &c, &viewer.public_key()).is_none());
1317 }
1318
1319 #[test]
1320 fn presence_announcements_parse_join_and_leave() {
1321 use crate::stored_event::event_kind;
1322 let mut state = ChatState::new();
1323 let alice = Keys::generate();
1324 let c = test_channel();
1325 let viewer = Keys::generate();
1326 let mk = |content: &str, ms: u64| {
1327 let inner = build_inner_typed(alice.public_key(), &c.id, c.epoch, event_kind::COMMUNITY_PRESENCE, content, ms, None, &[])
1328 .sign_with_keys(&alice).unwrap();
1329 seal_with_signed_inner(&Keys::generate(), &inner, &c.key, &c.id, c.epoch).unwrap()
1330 };
1331 match process_incoming(&mut state, &mk("join", 1), &c, &viewer.public_key()) {
1332 Some(IncomingEvent::Presence { npub, joined, .. }) => {
1333 assert!(joined, "content 'join' → joined");
1334 assert_eq!(npub, alice.public_key().to_bech32().unwrap(), "announcer is the inner author");
1335 }
1336 _ => panic!("expected a join presence"),
1337 }
1338 match process_incoming(&mut state, &mk("leave", 2), &c, &viewer.public_key()) {
1339 Some(IncomingEvent::Presence { joined, invited_by, .. }) => {
1340 assert!(!joined, "content 'leave' → not joined");
1341 assert!(invited_by.is_none(), "a plain leave carries no attribution");
1342 }
1343 _ => panic!("expected a leave presence"),
1344 }
1345 let jean = Keys::generate().public_key().to_bech32().unwrap();
1348 let attributed = serde_json::json!({ "by": jean, "l": "Reddit" }).to_string();
1349 match process_incoming(&mut state, &mk(&attributed, 3), &c, &viewer.public_key()) {
1350 Some(IncomingEvent::Presence { joined, invited_by, invited_label, .. }) => {
1351 assert!(joined, "an attributed-join JSON is still a join");
1352 assert_eq!(invited_by.as_deref(), Some(jean.as_str()), "valid inviter npub surfaced");
1353 assert_eq!(invited_label.as_deref(), Some("Reddit"), "link label surfaced");
1354 }
1355 _ => panic!("expected an attributed join presence"),
1356 }
1357 let forged = serde_json::json!({ "by": "haha not an npub", "l": "x" }).to_string();
1359 match process_incoming(&mut state, &mk(&forged, 4), &c, &viewer.public_key()) {
1360 Some(IncomingEvent::Presence { invited_by, .. }) => assert!(invited_by.is_none(), "forged inviter dropped"),
1361 _ => panic!("expected a join presence"),
1362 }
1363 }
1364
1365 #[test]
1366 fn leave_presence_authored_by_local_npub_yields_self_left() {
1367 use crate::stored_event::event_kind;
1368 let owner = Keys::generate();
1371 let admin = Keys::generate();
1372 let (_tmp, _g, channel, _cite) = db_roster_channel(&owner, &admin.public_key());
1373 let mut state = ChatState::new();
1374 let cid = crate::db::community::community_id_for_channel(&channel.id.to_hex()).unwrap().unwrap();
1377 let cid_bytes = crate::community::CommunityId(crate::simd::hex::hex_to_bytes_32(&cid));
1378 let leave_ms = crate::db::community::community_created_at_ms(&cid_bytes).unwrap_or(0) + 10_000;
1379 let leave = {
1380 let inner = build_inner_typed(owner.public_key(), &channel.id, channel.epoch, event_kind::COMMUNITY_PRESENCE, "leave", leave_ms, None, &[])
1381 .sign_with_keys(&owner).unwrap();
1382 seal_with_signed_inner(&Keys::generate(), &inner, &channel.key, &channel.id, channel.epoch).unwrap()
1383 };
1384 match process_incoming(&mut state, &leave, &channel, &owner.public_key()) {
1385 Some(IncomingEvent::SelfLeft { community_id }) => assert!(!community_id.is_empty()),
1386 _ => panic!("expected SelfLeft"),
1387 }
1388 crate::db::close_database();
1389 }
1390
1391 #[test]
1392 fn leave_presence_authored_by_another_npub_stays_a_plain_leave() {
1393 use crate::stored_event::event_kind;
1394 use nostr_sdk::ToBech32;
1395 let owner = Keys::generate();
1397 let admin = Keys::generate();
1398 let other = Keys::generate();
1399 let (_tmp, _g, channel, _cite) = db_roster_channel(&owner, &admin.public_key());
1400 let mut state = ChatState::new();
1401 let leave = {
1402 let inner = build_inner_typed(other.public_key(), &channel.id, channel.epoch, event_kind::COMMUNITY_PRESENCE, "leave", 2, None, &[])
1403 .sign_with_keys(&other).unwrap();
1404 seal_with_signed_inner(&Keys::generate(), &inner, &channel.key, &channel.id, channel.epoch).unwrap()
1405 };
1406 match process_incoming(&mut state, &leave, &channel, &owner.public_key()) {
1408 Some(IncomingEvent::Presence { npub, joined, .. }) => {
1409 assert!(!joined);
1410 assert_eq!(npub, other.public_key().to_bech32().unwrap());
1411 }
1412 _ => panic!("expected plain leave Presence"),
1413 }
1414 crate::db::close_database();
1415 }
1416
1417 #[test]
1418 fn self_delete_still_applies_after_keep_keys_teardown() {
1419 let owner = Keys::generate();
1422 let admin = Keys::generate();
1423 let (_tmp, _g, channel, _cite) = db_roster_channel(&owner, &admin.public_key());
1424 let cid = crate::db::community::community_id_for_channel(&channel.id.to_hex()).unwrap().unwrap();
1425 let chan_hex = channel.id.to_hex();
1426 let epoch = channel.epoch.0;
1427
1428 let mut state = ChatState::new();
1430 let target = ingest_msg_in(&mut state, &channel, &owner, "mine", 1, &owner);
1431
1432 crate::db::community::delete_community_retain_keys(&cid).unwrap();
1434 let retained = crate::db::community::held_epoch_key(&cid, &chan_hex, epoch).unwrap()
1435 .expect("epoch key retained after keep-keys teardown");
1436 let mut rebuilt = channel.clone();
1437 rebuilt.key = ChannelKey(retained);
1438 rebuilt.epoch = Epoch(epoch);
1439
1440 let del = seal_hide(&rebuilt, &owner, &target, 2, None);
1442 match process_incoming(&mut state, &del, &rebuilt, &owner.public_key()) {
1443 Some(IncomingEvent::Removed { target_id }) => assert_eq!(target_id, target),
1444 _ => panic!("expected the self-delete to apply under the retained key"),
1445 }
1446 crate::db::close_database();
1447 }
1448
1449 #[test]
1450 fn banned_author_events_are_dropped_including_presence() {
1451 use crate::stored_event::event_kind;
1452 let mut state = ChatState::new();
1453 let alice = Keys::generate(); let bob = Keys::generate();
1455 let mut c = test_channel();
1456 c.banned = vec![alice.public_key()];
1457
1458 let spam = seal_message(&alice, &c.key, &c.id, c.epoch, "spam", 1).unwrap();
1460 assert!(process_incoming(&mut state, &spam, &c, &bob.public_key()).is_none(), "banned message dropped");
1461
1462 let pres_inner = build_inner_typed(alice.public_key(), &c.id, c.epoch, event_kind::COMMUNITY_PRESENCE, "join", 2, None, &[])
1464 .sign_with_keys(&alice).unwrap();
1465 let pres = seal_with_signed_inner(&Keys::generate(), &pres_inner, &c.key, &c.id, c.epoch).unwrap();
1466 assert!(process_incoming(&mut state, &pres, &c, &bob.public_key()).is_none(), "banned presence dropped");
1467
1468 let ok = seal_message(&bob, &c.key, &c.id, c.epoch, "hi", 3).unwrap();
1470 assert!(matches!(process_incoming(&mut state, &ok, &c, &bob.public_key()), Some(IncomingEvent::NewMessage(_))), "non-banned applied");
1471 }
1472
1473 #[test]
1474 fn cooperative_delete_applies_after_message_in_batch_order() {
1475 use crate::stored_event::event_kind;
1476 let mut state = ChatState::new();
1477 let alice = Keys::generate();
1478 let c = test_channel();
1479
1480 let msg_outer = seal_message(&alice, &c.key, &c.id, c.epoch, "bye", 1).unwrap();
1484 let opened = open_message(&msg_outer, &c.key, &c.id, c.epoch).unwrap();
1485 let inner_id = opened.message_id.to_hex();
1486 let del_outer = seal_typed(&alice, event_kind::COMMUNITY_DELETE, "", 2, &inner_id);
1487
1488 let applied = process_channel_batch(&mut state, &[del_outer, msg_outer], &c, &alice.public_key());
1489 assert!(applied.iter().any(|e| matches!(e, IncomingEvent::NewMessage(_))));
1490 assert!(applied.iter().any(|e| matches!(e, IncomingEvent::Removed { .. })));
1491 assert!(state.find_message(&inner_id).is_none(), "delete applied despite arriving first");
1492 }
1493
1494 #[test]
1495 fn build_message_sets_mine_and_author() {
1496 let me = Keys::generate();
1497 let opened = opened_from(&me, "hello", 4242);
1498 let msg = build_message(&opened, &me.public_key());
1499 assert_eq!(msg.content, "hello");
1500 assert_eq!(msg.at, 4242);
1501 assert!(msg.mine, "author == me → mine");
1502 assert_eq!(msg.npub, me.public_key().to_bech32().ok());
1503 assert_eq!(msg.id, opened.message_id.to_hex());
1504
1505 let other_view = build_message(&opened, &Keys::generate().public_key());
1507 assert!(!other_view.mine);
1508 }
1509
1510 #[test]
1511 fn ingest_creates_community_chat_and_adds_message() {
1512 let mut state = ChatState::new();
1513 let alice = Keys::generate();
1514 let opened = opened_from(&alice, "gm", 1);
1515
1516 assert!(ingest_message(&mut state, &opened, &alice.public_key()).is_some());
1517 let chat = state.chats.iter().find(|c| c.id == opened.channel_id.to_hex()).expect("chat");
1519 assert!(chat.is_community(), "channel chat must be ChatType::Community");
1520 }
1521
1522 #[test]
1523 fn process_incoming_ingests_valid_drops_foreign() {
1524 let mut state = ChatState::new();
1525 let alice = Keys::generate();
1526 let key = ChannelKey([0x33u8; 32]);
1527 let chan = ChannelId([0x44u8; 32]);
1528 let channel = Channel { id: chan, key: key.clone(), epoch: Epoch(0), name: "g".into(), banned: Vec::new(), protected: Vec::new(), roster: Default::default(), epoch_keys: Vec::new(), dissolved: false };
1529
1530 let outer = seal_message(&alice, &key, &chan, Epoch(0), "real", 1).unwrap();
1532 assert!(process_incoming(&mut state, &outer, &channel, &alice.public_key()).is_some());
1533 assert!(state.chats.iter().any(|c| c.is_community()));
1534
1535 let other_key = ChannelKey([0x99u8; 32]);
1537 let other_chan = ChannelId([0xaau8; 32]);
1538 let foreign = seal_message(&alice, &other_key, &other_chan, Epoch(0), "nope", 1).unwrap();
1539 assert!(process_incoming(&mut state, &foreign, &channel, &alice.public_key()).is_none());
1540 assert_eq!(state.chats.iter().filter(|c| c.is_community()).count(), 1);
1541 }
1542
1543 #[test]
1544 fn ingest_dedups_on_message_id() {
1545 let mut state = ChatState::new();
1546 let alice = Keys::generate();
1547 let opened = opened_from(&alice, "once", 1);
1548
1549 assert!(ingest_message(&mut state, &opened, &alice.public_key()).is_some(), "first add");
1550 assert!(ingest_message(&mut state, &opened, &alice.public_key()).is_none(), "duplicate not re-added");
1551 assert_eq!(state.chats.iter().filter(|c| c.is_community()).count(), 1);
1553 }
1554
1555 #[test]
1556 fn dedup_keys_on_inner_id_across_distinct_outer_events() {
1557 let mut state = ChatState::new();
1563 let alice = Keys::generate();
1564 let key = ChannelKey([0x33u8; 32]);
1565 let chan = ChannelId([0x44u8; 32]);
1566 let channel = Channel { id: chan, key: key.clone(), epoch: Epoch(0), name: "g".into(), banned: Vec::new(), protected: Vec::new(), roster: Default::default(), epoch_keys: Vec::new(), dissolved: false };
1567
1568 let outer_a = seal_message(&alice, &key, &chan, Epoch(0), "dup", 7).unwrap();
1569 let outer_b = seal_message(&alice, &key, &chan, Epoch(0), "dup", 7).unwrap();
1570 assert_ne!(outer_a.id, outer_b.id, "distinct outer events (fresh ephemeral + nonce)");
1571
1572 assert!(process_incoming(&mut state, &outer_a, &channel, &alice.public_key()).is_some());
1573 assert!(
1574 process_incoming(&mut state, &outer_b, &channel, &alice.public_key()).is_none(),
1575 "same inner message id must dedup despite a different outer event"
1576 );
1577 }
1578
1579 #[test]
1580 fn route_incoming_routes_by_pseudonym() {
1581 let mut state = ChatState::new();
1582 let alice = Keys::generate();
1583 let key = ChannelKey([0x33u8; 32]);
1584 let chan = ChannelId([0x44u8; 32]);
1585 let channel = Channel { id: chan, key: key.clone(), epoch: Epoch(0), name: "g".into(), banned: Vec::new(), protected: Vec::new(), roster: Default::default(), epoch_keys: Vec::new(), dissolved: false };
1586
1587 let mut routes = HashMap::new();
1589 routes.insert(channel_pseudonym(&key, &chan, Epoch(0)).to_hex(), channel.clone());
1590
1591 let outer = seal_message(&alice, &key, &chan, Epoch(0), "routed", 1).unwrap();
1593 assert!(route_incoming(&mut state, &outer, &routes, &alice.public_key()).is_some());
1594
1595 let other_key = ChannelKey([0x55u8; 32]);
1597 let other_chan = ChannelId([0x66u8; 32]);
1598 let unrouted = seal_message(&alice, &other_key, &other_chan, Epoch(0), "x", 1).unwrap();
1599 assert!(route_incoming(&mut state, &unrouted, &routes, &alice.public_key()).is_none());
1600 }
1601
1602 #[test]
1603 fn ms_none_falls_back_to_created_at() {
1604 use nostr_sdk::prelude::{EventId, Timestamp, Tags};
1606 let author = Keys::generate();
1607 let opened = OpenedMessage {
1608 message_id: EventId::all_zeros(),
1609 author: author.public_key(),
1610 content: "no ms".into(),
1611 channel_id: ChannelId([1u8; 32]),
1612 epoch: Epoch(0),
1613 ms: None,
1614 created_at: Timestamp::from_secs(1500),
1615 kind: 3300,
1616 attachments: vec![],
1617 citation: None,
1618 wrapper_id: EventId::all_zeros(),
1619 tags: Tags::new(),
1620 };
1621 assert_eq!(build_message(&opened, &author.public_key()).at, 1_500_000);
1622 }
1623}