use nostr_sdk::prelude::PublicKey;
use nostr_sdk::prelude::ToBech32;
use super::super::attachments::attachments_from_tags;
use super::chat::{self, ChatEvent};
use super::community::CommunityV2;
use super::guestbook::{self, GuestbookEntry};
use super::stream;
use crate::event_handler::InboundEventHandler;
use crate::state::ChatState;
use crate::types::{EmojiTag, Message, Reaction};
pub fn chat_message_to_message(
opened: &stream::OpenedStream,
reply_to: &Option<chat::ReplyRef>,
emoji: &[(String, String)],
my_pubkey: &PublicKey,
) -> Message {
let (replied_to, replied_to_npub) = match reply_to {
Some(r) => (
crate::simd::hex::bytes_to_hex_32(&r.id),
r.author.and_then(|a| a.to_bech32().ok()),
),
None => (String::new(), None),
};
let attachments = attachments_from_tags(opened.rumor.tags.iter(), &crate::db::get_download_dir());
let content = super::super::attachments::strip_attachment_urls(&opened.rumor.content, &attachments);
let text_spans = if content == opened.rumor.content {
crate::text_spans::from_tags(opened.rumor.tags.iter(), &content)
} else {
Vec::new()
};
Message {
id: opened.rumor_id.to_hex(),
content,
text_spans,
replied_to,
replied_to_npub,
at: opened.at_ms,
mine: opened.author == *my_pubkey,
npub: opened.author.to_bech32().ok(),
attachments,
emoji_tags: emoji
.iter()
.map(|(shortcode, url)| EmojiTag { shortcode: shortcode.clone(), url: url.clone() })
.collect(),
addressed_bots: crate::bot_interface::addressed_bots(opened.rumor.tags.iter()),
role_mentions: crate::community::mentions::from_tags(opened.rumor.tags.iter()),
writer: chat::carries_writer_epoch(&opened.rumor),
unauthorized: opened.held,
wrapper_event_id: Some(opened.wrapper_id.to_hex()),
expiration: chat::message_expiration(&opened.rumor),
..Default::default()
}
}
fn author_is_banned_here(channel_id: &str, community: Option<&[u8; 32]>, author: &PublicKey) -> bool {
let resolved;
let community = match community {
Some(c) => c,
None => {
let Some(Ok(Some(c))) =
crate::community::id32_from_hex(channel_id).map(|ch| crate::db::community::community_for_channel(&ch))
else {
return false;
};
resolved = c;
&resolved
}
};
crate::db::community::is_author_banned_in(community, author)
}
fn moderation_delete_authorized(
channel_id: &str,
deleter: &PublicKey,
author: &PublicKey,
tags: &nostr_sdk::prelude::Tags,
) -> bool {
let Ok(Some(cid_hex)) = crate::db::community::community_id_for_channel(channel_id) else {
return false;
};
if crate::db::community::get_community_dissolved(&cid_hex).unwrap_or(false) {
return false;
}
let Some(owner_hex) = crate::community::moderation::owner_hex(&cid_hex) else {
return false; };
let deleter_hex = deleter.to_hex();
let citation = crate::community::edition::AuthorityCitation::from_tags(tags);
if !super::service::citation_is_synced(&cid_hex, &owner_hex, &deleter_hex, citation.as_ref()) {
return false;
}
let roster = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
let private = crate::db::community::channel_is_private(channel_id).ok().flatten().unwrap_or(false);
crate::community::moderation::can_hide_in_channel(Some(&owner_hex), &roster, &deleter_hex, &author.to_hex(), channel_id, private)
}
fn note_moderation_delete(channel_id: &str, opened: &stream::OpenedStream, author: &PublicKey) {
let Some(id) = opened.rumor.id.map(|i| i.to_hex()) else { return };
let (channel, actor, author, at_ms) = (channel_id.to_string(), opened.author.to_hex(), author.to_hex(), opened.at_ms);
crate::db::spawn_bound(async move {
if let Ok(Some(cid)) = crate::db::community::community_id_for_channel(&channel) {
super::service::note_moderation_delete(&cid, &id, at_ms, &actor, &author, &channel);
}
});
}
pub enum ChatPersist {
New(Message),
Updated { message: Message, edit_event: Option<Box<crate::stored_event::StoredEvent>> },
Removed { id: String, moderated: bool },
ReactionRemoved { reaction_id: String, message: Message },
}
pub fn apply_chat_to_state(state: &mut ChatState, event: &ChatEvent, channel_id: &str, my_pubkey: &PublicKey) -> Option<ChatPersist> {
apply_chat_to_state_in(state, event, channel_id, None, my_pubkey, None)
}
pub(crate) fn apply_page_event_to_state(state: &mut ChatState, event: &ChatEvent, channel_id: &str, my_pubkey: &PublicKey, stored: &std::collections::HashSet<String>) -> Option<ChatPersist> {
apply_chat_to_state_in(state, event, channel_id, None, my_pubkey, Some(stored))
}
pub(crate) fn page_event_ids<'a>(events: impl IntoIterator<Item = &'a ChatEvent>) -> Vec<String> {
events
.into_iter()
.filter(|e| matches!(e, ChatEvent::Message { .. } | ChatEvent::Edit { .. }))
.map(|e| e.opened().rumor_id.to_hex())
.collect()
}
fn apply_chat_to_state_in(
state: &mut ChatState,
event: &ChatEvent,
channel_id: &str,
community: Option<&[u8; 32]>,
my_pubkey: &PublicKey,
stored: Option<&std::collections::HashSet<String>>,
) -> Option<ChatPersist> {
let is_stored = |id: &str| match stored {
Some(ids) => ids.contains(id),
None => crate::db::events::event_exists(id).unwrap_or(false),
};
if author_is_banned_here(channel_id, community, &event.opened().author) {
return None;
}
if !matches!(event, ChatEvent::Delete { .. })
&& crate::rumor::already_expired(chat::message_expiration(&event.opened().rumor))
{
return None;
}
match event {
ChatEvent::Message { opened, reply_to, emoji } => {
let msg = chat_message_to_message(opened, reply_to, emoji, my_pubkey);
if msg.mine && state.find_message(&msg.id).is_some_and(|(_, m)| m.failed) {
super::service::confirm_in(state, &msg.id);
}
if is_stored(&msg.id) || crate::state::was_message_deleted(&msg.id) {
return None;
}
state.ensure_community_chat(channel_id);
if !state.add_message_to_chat(channel_id, &msg) && stored.is_some() && crate::db::events::event_exists(&msg.id).unwrap_or(false) {
return None;
}
Some(ChatPersist::New(msg))
}
ChatEvent::Reaction { opened, target, emoji, emoji_url, .. } => {
if !crate::types::is_renderable_reaction(emoji) {
return None;
}
let target_id = crate::simd::hex::bytes_to_hex_32(target);
if !matches!(state.find_message(&target_id), Some((chat, _)) if chat.id == channel_id) {
return None;
}
let reaction = Reaction {
id: opened.rumor_id.to_hex(),
reference_id: target_id.clone(),
author_id: opened.author.to_bech32().unwrap_or_else(|_| opened.author.to_hex()),
emoji: emoji.clone(),
emoji_url: emoji_url.clone(),
};
let (_c, added) = state.add_reaction_to_message(&target_id, reaction)?;
added.then(|| state.find_message(&target_id).map(|(_c, m)| ChatPersist::Updated { message: m, edit_event: None }))?
}
ChatEvent::Edit { opened, target, new_content, emoji } => {
if is_stored(&opened.rumor_id.to_hex()) {
return None;
}
let target_id = crate::simd::hex::bytes_to_hex_32(target);
let editor_npub = opened.author.to_bech32().ok()?;
if !matches!(state.find_message(&target_id), Some((chat, m)) if chat.id == channel_id && m.npub.as_deref() == Some(editor_npub.as_str())) {
return None;
}
let edited_at = opened.at_ms;
let emoji_tags: Vec<crate::types::EmojiTag> = emoji
.iter()
.map(|(shortcode, url)| crate::types::EmojiTag { shortcode: shortcode.clone(), url: url.clone() })
.collect();
let text_spans = crate::text_spans::from_tags(opened.rumor.tags.iter(), new_content);
let (_c, message) = state.update_message_with(&target_id, |m, i| m.apply_edit(new_content.clone(), edited_at, emoji_tags.clone(), text_spans.clone(), i))?;
let edit_event = crate::stored_event::StoredEventBuilder::new()
.id(opened.rumor_id.to_hex())
.kind(crate::stored_event::event_kind::MESSAGE_EDIT)
.content(new_content.clone())
.tags(
emoji.iter().map(|(s, u)| vec!["emoji".to_string(), s.clone(), u.clone()])
.chain(text_spans.iter().map(|s| s.to_tag_parts()))
.chain((edited_at % 1000 > 0).then(|| vec!["ms".to_string(), (edited_at % 1000).to_string()]))
.chain(super::chat::carries_writer_epoch(&opened.rumor).then(|| vec!["writer".to_string()]))
.collect(),
)
.reference_id(Some(target_id.clone()))
.wrapper_event_id(Some(opened.wrapper_id.to_hex()))
.created_at(edited_at / 1000)
.mine(opened.author == *my_pubkey)
.npub(opened.author.to_bech32().ok())
.build();
Some(ChatPersist::Updated { message, edit_event: Some(Box::new(edit_event)) })
}
ChatEvent::Delete { opened, target, .. } => {
let target_id = crate::simd::hex::bytes_to_hex_32(target);
if let Some((_chat, message_id, author_npub, _)) = state.find_reaction(&target_id) {
let reactor_ok = PublicKey::parse(&author_npub).map(|pk| pk == opened.author).unwrap_or(false);
if !reactor_ok {
return None;
}
return state
.remove_reaction_from_message(&message_id, &target_id)
.map(|(_cid, message)| ChatPersist::ReactionRemoved { reaction_id: target_id, message });
}
let resident = state.find_message(&target_id).and_then(|(_, m)| m.npub.clone());
let author_npub = match resident {
Some(n) => Some(n),
None => crate::db::events::event_author(&target_id).ok().flatten(),
};
let author = author_npub.as_deref().and_then(|n| PublicKey::parse(n).ok())?;
let authorized = author == opened.author
|| moderation_delete_authorized(channel_id, &opened.author, &author, &opened.rumor.tags);
if !authorized {
return None;
}
if author != opened.author {
note_moderation_delete(channel_id, opened, &author);
}
let _ = state.remove_message(&target_id);
Some(ChatPersist::Removed { id: target_id, moderated: author != opened.author })
}
ChatEvent::Typing { .. } | ChatEvent::Webxdc { .. } | ChatEvent::VoicePresence { .. } | ChatEvent::VoiceDirective { .. } => None,
}
}
pub async fn hydrate_target(event: &ChatEvent, channel_id: &str) {
let msg_id = match event {
ChatEvent::Reaction { target, .. } | ChatEvent::Edit { target, .. } => crate::simd::hex::bytes_to_hex_32(target),
ChatEvent::Delete { target, .. } => {
let id = crate::simd::hex::bytes_to_hex_32(target);
if crate::state::STATE.lock().await.find_reaction(&id).is_some() {
return;
}
match crate::db::events::reaction_target(&id) {
Ok(Some(parent)) => parent,
_ => return,
}
}
_ => return,
};
if crate::state::STATE.lock().await.find_message(&msg_id).is_some() {
return;
}
if let Ok(Some((chat, msg))) = crate::db::events::get_message_by_id(&msg_id).await {
if chat == channel_id {
crate::state::STATE.lock().await.add_message_to_chat(channel_id, &msg);
}
}
}
pub async fn awaits_target(event: &ChatEvent) -> bool {
let target = match event {
ChatEvent::Reaction { target, .. } | ChatEvent::Edit { target, .. } | ChatEvent::Delete { target, .. } => {
crate::simd::hex::bytes_to_hex_32(target)
}
_ => return false,
};
let st = crate::state::STATE.lock().await;
st.find_message(&target).is_none() && st.find_reaction(&target).is_none()
}
pub async fn persist_chat_event(
event: &ChatEvent,
channel_id: &str,
my_pubkey: &PublicKey,
) -> Option<ChatPersist> {
persist_chat_event_in(event, channel_id, None, my_pubkey).await
}
pub(crate) async fn persist_routed_chat_event(
event: &ChatEvent,
channel_id: &str,
community: &[u8; 32],
my_pubkey: &PublicKey,
) -> Option<ChatPersist> {
persist_chat_event_in(event, channel_id, Some(community), my_pubkey).await
}
async fn persist_chat_event_in(
event: &ChatEvent,
channel_id: &str,
community: Option<&[u8; 32]>,
my_pubkey: &PublicKey,
) -> Option<ChatPersist> {
hydrate_target(event, channel_id).await;
let outcome = {
let mut st = crate::state::STATE.lock().await;
apply_chat_to_state_in(&mut st, event, channel_id, community, my_pubkey, None)
}?;
let outcome = match outcome {
ChatPersist::New(mut m) => {
if !m.replied_to.is_empty() {
let _ = crate::db::events::populate_reply_context(&mut m).await;
}
crate::db::attachments::verify_message_attachments(&mut m, Some(channel_id)).await;
ChatPersist::New(m)
}
o => o,
};
persist_chat(channel_id, &outcome).await;
match (&outcome, event) {
(ChatPersist::Removed { id: target, .. }, _) => {
super::service::spawn_pin_duty(channel_id, target, None);
}
(ChatPersist::Updated { .. }, ChatEvent::Edit { opened, target, .. }) => {
let target_hex = crate::simd::hex::bytes_to_hex_32(target);
super::service::spawn_pin_duty(channel_id, &target_hex, Some(opened.clone()));
}
_ => {}
}
Some(outcome)
}
pub async fn persist_chat(channel_id: &str, outcome: &ChatPersist) {
match outcome {
ChatPersist::New(m) => {
let _ = crate::db::events::save_message(channel_id, m).await;
}
ChatPersist::Updated { message, edit_event: None } => {
let _ = crate::db::events::save_new_reactions(channel_id, message).await;
}
ChatPersist::Updated { edit_event: Some(ev), .. } => save_edit_event(channel_id, ev).await,
ChatPersist::Removed { id, .. } => remove_message(id).await,
ChatPersist::ReactionRemoved { reaction_id, .. } => {
let _ = crate::db::events::delete_event(reaction_id).await;
}
}
}
pub async fn notify_chat_outcome(handler: &dyn InboundEventHandler, channel_id: &str, event: &ChatEvent, outcome: ChatPersist, live: bool) {
let by = || event.opened().author.to_bech32().unwrap_or_else(|_| event.opened().author.to_hex());
let at = event.opened().at_ms;
let news = || crate::news::is_news(at) && crate::news::first_telling(event.opened().rumor_id.as_bytes());
match outcome {
ChatPersist::New(message) => {
let fresh = match crate::news::listening_since() {
Some(_) => crate::news::is_news(message.at) && crate::news::first_telling_hex(&message.id),
None => live && crate::community::is_realtime_fresh(message.at),
};
handler.on_community_message(channel_id, &message, fresh);
}
ChatPersist::Updated { mut message, edit_event } => {
let _ = crate::db::events::populate_reply_context(&mut message).await;
handler.on_community_update(channel_id, &message.id, &message);
match (edit_event, event) {
_ if !news() => {}
(Some(_), _) => handler.on_message_edited(channel_id, &message, at),
(None, ChatEvent::Reaction { opened, .. }) => {
let id = opened.rumor_id.to_hex();
if let Some(reaction) = message.reactions.iter().find(|r| r.id == id) {
handler.on_reaction_added(channel_id, &message, reaction, at);
}
}
_ => {}
}
}
ChatPersist::ReactionRemoved { reaction_id, mut message } => {
let _ = crate::db::events::populate_reply_context(&mut message).await;
handler.on_community_update(channel_id, &message.id, &message);
if news() {
handler.on_reaction_removed(channel_id, &message, &reaction_id, &by(), at);
}
}
ChatPersist::Removed { id, moderated } => {
handler.on_community_removed(channel_id, &id);
if news() {
handler.on_message_removed(channel_id, &id, Some(&by()), moderated, at);
}
}
}
}
async fn remove_message(id: &str) {
crate::state::note_message_deleted(id);
if let Err(e) = crate::db::events::add_message_tombstone(id) {
crate::log_warn!("[v2 delete] tombstone write failed: {e}");
}
let _ = crate::db::events::delete_event(id).await;
}
pub async fn persist_chat_page(channel_id: &str, outcomes: &[ChatPersist], session: &std::sync::Arc<crate::db::Session>) {
let mut pending: Vec<&Message> = Vec::new();
let mut reacted: Vec<&Message> = Vec::new();
for outcome in outcomes {
if !session.is_live() {
return;
}
match outcome {
ChatPersist::New(m) => pending.push(m),
ChatPersist::Updated { message, edit_event: None } => reacted.push(message),
ChatPersist::Updated { edit_event: Some(ev), .. } => save_edit_event(channel_id, ev).await,
ChatPersist::Removed { id, .. } => {
flush_page(channel_id, &mut pending, &mut reacted, session).await;
remove_message(id).await;
}
ChatPersist::ReactionRemoved { reaction_id, .. } => {
flush_page(channel_id, &mut pending, &mut reacted, session).await;
let _ = crate::db::events::delete_event(reaction_id).await;
}
}
}
flush_page(channel_id, &mut pending, &mut reacted, session).await;
}
async fn flush_page<'a>(
channel_id: &str,
pending: &mut Vec<&'a Message>,
reacted: &mut Vec<&'a Message>,
session: &std::sync::Arc<crate::db::Session>,
) {
crate::db::events::flush_message_batch(channel_id, pending, session).await;
for message in reacted.drain(..) {
if session.is_live() {
let _ = crate::db::events::save_new_reactions(channel_id, message).await;
}
}
}
async fn save_edit_event(channel_id: &str, ev: &crate::stored_event::StoredEvent) {
let mut ev = ev.clone();
if let Ok(cid) = crate::db::id_cache::get_or_create_chat_id(channel_id) {
ev.chat_id = cid;
}
let _ = crate::db::events::save_event(&ev).await;
}
#[derive(Debug, Clone)]
pub enum DispatchedV2 {
Chat { channel_id: String, event: Box<ChatEvent> },
Typing { channel_id: String, npub: String },
VoicePresence { channel_id: String },
Presence { npub: String, joined: bool, event: Box<guestbook::GuestbookEvent> },
Kick { target: PublicKey, event: Box<guestbook::GuestbookEvent> },
Nickname(Box<guestbook::GuestbookEvent>),
Timeout(Box<guestbook::GuestbookEvent>),
Control { community_id: String },
Rekey { community_id: String },
Dissolved { community_id: String },
Held { channel_id: String, author: PublicKey, at_ms: u64, marked: Option<Box<ChatEvent>> },
Early { at_ms: u64 },
Ignored,
NotOurs,
}
pub fn dispatch_wrap(
wrap: &nostr_sdk::prelude::Event,
community: &CommunityV2,
my_pubkey: &PublicKey,
handler: &dyn InboundEventHandler,
) -> DispatchedV2 {
for ch in &community.channels {
if ch.private && ch.key.is_none() {
continue;
}
let (secret, epoch) = community.channel_secret(ch);
let group = super::derive::channel_group_key(&secret, &ch.id, epoch);
if wrap.pubkey != group.pk() {
continue;
}
let below_seal = |at_ms: u64| ch.writers.as_ref().and_then(|l| l.seal.as_ref()).is_some_and(|s| at_ms < s.until);
let wrapped_ms = wrap.created_at.as_secs().saturating_mul(1000);
if ch.writers.as_ref().is_some_and(|l| l.read_address_quiet(wrapped_ms)) || below_seal(wrapped_ms.saturating_add(999)) {
return DispatchedV2::Ignored;
}
let Ok(event) = chat::open_chat_event(wrap, &group, &ch.id, epoch) else {
return DispatchedV2::NotOurs;
};
if below_seal(event.opened().at_ms) {
return DispatchedV2::Ignored;
}
return dispatch_judged(event, community, ch, None, my_pubkey, handler);
}
for ch in &community.channels {
let Some(ledger) = ch.writers.as_ref() else { continue };
if ch.private && ch.key.is_none() {
continue;
}
let Some((wepoch, ..)) = ledger.writers().find(|(_, pk, _)| *pk == wrap.pubkey.to_bytes()) else { continue };
let (secret, epoch) = community.channel_secret(ch);
let group = super::derive::channel_group_key(&secret, &ch.id, epoch);
let Ok(event) = chat::open_writer_chat_event(wrap, &wrap.pubkey, wepoch, group.conv_key(), &ch.id, epoch) else {
return DispatchedV2::NotOurs;
};
return dispatch_judged(event, community, ch, Some(wepoch), my_pubkey, handler);
}
let gb = super::derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch);
if wrap.pubkey == gb.pk() {
if let Ok(opened) = stream::open_wrap(wrap, &gb) {
if let Ok(ev) = guestbook::parse_guestbook_event(&opened) {
return dispatch_guestbook(ev, community, handler);
}
}
return DispatchedV2::Ignored;
}
if wrap.pubkey == super::realtime::control_author(community) {
return DispatchedV2::Control { community_id: crate::simd::hex::bytes_to_hex_32(&community.id().0) };
}
if super::realtime::rekey_authors(community).contains(&wrap.pubkey) {
return DispatchedV2::Rekey { community_id: crate::simd::hex::bytes_to_hex_32(&community.id().0) };
}
if wrap.pubkey == super::derive::dissolved_group_key(community.id()).pk() {
if super::dissolution::verify_dissolved(wrap, &community.identity) {
return DispatchedV2::Dissolved { community_id: crate::simd::hex::bytes_to_hex_32(&community.id().0) };
}
return DispatchedV2::Ignored;
}
DispatchedV2::NotOurs
}
fn dispatch_judged(event: ChatEvent, community: &CommunityV2, ch: &super::community::ChannelV2, wepoch: Option<crate::community::Epoch>, my_pubkey: &PublicKey, handler: &dyn InboundEventHandler) -> DispatchedV2 {
let channel_id = crate::simd::hex::bytes_to_hex_32(&ch.id.0);
let (at_ms, author) = (event.opened().at_ms, event.opened().author);
if matches!(event, ChatEvent::Message { .. }) && crate::early::is_early(at_ms) {
return DispatchedV2::Early { at_ms };
}
if matches!(event, ChatEvent::VoicePresence { .. } | ChatEvent::VoiceDirective { .. }) && super::service::Judge::of(community, ch).is_some_and(|j| !j.admits(&event, wepoch)) {
return DispatchedV2::Ignored;
}
if let ChatEvent::VoicePresence { opened, heard } = event {
if author_is_banned_here(&channel_id, Some(&community.id().0), &opened.author) {
return DispatchedV2::Ignored;
}
let now = crate::clock::now_ms();
let noted = super::voice::note(&channel_id, opened.author, at_ms, heard, now);
if noted.reached {
super::service::reassert_voice_directives(community, &channel_id, &opened.author);
#[cfg(feature = "calls")]
crate::calls::voice::greet(&channel_id, &opened.author);
}
if !noted.changed {
return DispatchedV2::Ignored;
}
#[cfg(feature = "calls")]
crate::calls::voice::nudge(&channel_id);
handler.on_voice_presence(&channel_id);
return DispatchedV2::VoicePresence { channel_id };
}
if let ChatEvent::VoiceDirective { opened, target, directive, to } = event {
let cid = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let owner = community.owner().ok().map(|o| o.to_hex());
let actor = opened.author.to_hex();
let roles = crate::db::community::get_community_roles(&cid).unwrap_or_default();
let authorized = (owner.as_deref() == Some(actor.as_str()) && owner.as_deref() != Some(target.to_hex().as_str()))
|| roles.can_act_on_member(&actor, owner.as_deref(), &target.to_hex(), directive.permission());
if !authorized || author_is_banned_here(&channel_id, Some(&community.id().0), &opened.author) {
return DispatchedV2::Ignored;
}
let now = crate::clock::now_ms();
if !super::voice::directive_in_window(&channel_id, &target, at_ms, now) {
return DispatchedV2::Ignored;
}
if super::voice::apply_directive(&channel_id, &target, directive, at_ms, now) {
super::service::yield_voice_directive(&channel_id, &target, directive);
}
if let Some(id) = opened.rumor.id {
super::service::note_voice_directive(&cid, &id.to_hex(), at_ms, &actor, &target.to_hex(), &channel_id, directive, to.as_ref());
}
#[cfg(feature = "calls")]
crate::calls::voice::on_directive(&channel_id, &target, directive, to);
#[cfg(not(feature = "calls"))]
let _ = to;
handler.on_voice_presence(&channel_id);
return DispatchedV2::VoicePresence { channel_id };
}
match super::service::sort_arrival(super::service::Judge::of(community, ch).as_ref(), event, wepoch) {
super::service::Arrival::Stands(event) => dispatch_chat_event(event, &channel_id, &community.id().0, my_pubkey, handler),
super::service::Arrival::Held(marked) => DispatchedV2::Held { channel_id, author, at_ms, marked: marked.map(Box::new) },
super::service::Arrival::Dropped => DispatchedV2::Ignored,
}
}
fn dispatch_chat_event(
event: ChatEvent,
channel_id: &str,
community: &[u8; 32],
my_pubkey: &PublicKey,
handler: &dyn InboundEventHandler,
) -> DispatchedV2 {
match event {
ChatEvent::Typing { opened } => {
if opened.author == *my_pubkey || author_is_banned_here(channel_id, Some(community), &opened.author) {
return DispatchedV2::Ignored;
}
let npub = opened.author.to_bech32().unwrap_or_default();
let until = opened.at_ms / 1000 + 30;
handler.on_community_typing(channel_id, &npub, until);
DispatchedV2::Typing { channel_id: channel_id.to_string(), npub }
}
ChatEvent::Webxdc { opened } => {
if opened.author == *my_pubkey || author_is_banned_here(channel_id, Some(community), &opened.author) {
return DispatchedV2::Ignored;
}
let Some((topic_id, node_addr)) = crate::webxdc::parse_peer_signal(&opened.rumor.content) else {
return DispatchedV2::Ignored;
};
let npub = opened.author.to_bech32().unwrap_or_default();
handler.on_community_webxdc(
channel_id,
&npub,
&topic_id,
node_addr.as_deref(),
&opened.rumor_id.to_hex(),
opened.at_ms / 1000,
);
DispatchedV2::Ignored
}
event => DispatchedV2::Chat { channel_id: channel_id.to_string(), event: Box::new(event) },
}
}
fn dispatch_guestbook(ev: guestbook::GuestbookEvent, community: &CommunityV2, handler: &dyn InboundEventHandler) -> DispatchedV2 {
let suppressed = match &ev.entry {
GuestbookEntry::Join { member, .. } | GuestbookEntry::Leave { member, .. } => {
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
crate::db::community::is_author_banned(&cid_hex, member)
}
_ => false,
};
let event_id = crate::simd::hex::bytes_to_hex_32(&ev.rumor_id);
let chat_id = community
.primary_channel()
.map(|c| crate::simd::hex::bytes_to_hex_32(&c.id.0));
match &ev.entry {
GuestbookEntry::Join { member, at_ms, invited_by } => {
let npub = member.to_bech32().unwrap_or_default();
let (by, label) = match invited_by {
Some((c, l)) => (Some(c.as_str()), Some(l.as_str())),
None => (None, None),
};
if let (false, Some(chat)) = (suppressed, chat_id.as_deref()) {
if crate::news::first_telling(&ev.rumor_id) {
handler.on_community_presence(chat, &npub, true, &event_id, at_ms / 1000, by, label);
}
}
DispatchedV2::Presence { npub, joined: true, event: Box::new(ev) }
}
GuestbookEntry::Leave { member, at_ms } => {
let npub = member.to_bech32().unwrap_or_default();
if let (false, Some(chat)) = (suppressed, chat_id.as_deref()) {
if crate::news::first_telling(&ev.rumor_id) {
handler.on_community_presence(chat, &npub, false, &event_id, at_ms / 1000, None, None);
}
}
DispatchedV2::Presence { npub, joined: false, event: Box::new(ev) }
}
GuestbookEntry::Kick { target, .. } => DispatchedV2::Kick { target: *target, event: Box::new(ev) },
GuestbookEntry::Snapshot { .. } => DispatchedV2::Ignored,
GuestbookEntry::Nickname { .. } => DispatchedV2::Nickname(Box::new(ev)),
GuestbookEntry::Timeout { .. } => DispatchedV2::Timeout(Box::new(ev)),
}
}
pub async fn persist_webxdc_signal(
channel_hex: &str,
npub: &str,
topic_id: &str,
node_addr: Option<&str>,
event_id: &str,
created_at: u64,
) {
if crate::db::events::event_exists(event_id).unwrap_or(true) {
return;
}
let now_secs = crate::clock::now_secs();
let created_at = created_at.min(now_secs + 300);
let Ok(chat_id) = crate::db::id_cache::get_or_create_chat_id(channel_hex) else { return };
let mut tags = vec![
vec!["webxdc-topic".to_string(), topic_id.to_string()],
vec!["d".to_string(), "vector-webxdc-peer".to_string()],
];
if let Some(addr) = node_addr {
tags.push(vec!["webxdc-node-addr".to_string(), addr.to_string()]);
}
let event = crate::stored_event::StoredEvent {
id: event_id.to_string(),
kind: crate::stored_event::event_kind::APPLICATION_SPECIFIC,
chat_id,
user_id: None,
content: if node_addr.is_some() { "peer-advertisement" } else { "peer-left" }.to_string(),
tags,
reference_id: Some(topic_id.to_string()),
created_at,
received_at: crate::clock::now_ms(),
mine: false,
pending: false,
failed: false,
wrapper_event_id: None,
npub: Some(npub.to_string()),
preview_metadata: None,
};
if let Err(e) = crate::db::events::save_event(&event).await {
crate::log_warn!("[community] failed to persist webxdc peer signal: {e}");
}
}
#[cfg(test)]
mod tests {
use super::*;
use super::super::service;
use crate::community::transport::memory::MemoryRelay;
use crate::community::transport::Transport;
use nostr_sdk::prelude::Keys;
use std::sync::Mutex;
#[derive(Default)]
struct Recorder {
messages: Mutex<Vec<(String, Message)>>,
updates: Mutex<Vec<(String, String)>>,
removed: Mutex<Vec<(String, String)>>,
presence: Mutex<Vec<(String, bool)>>,
typing: Mutex<Vec<(String, String)>>,
}
impl InboundEventHandler for Recorder {
fn on_community_message(&self, chat_id: &str, msg: &Message, _is_new: bool) {
self.messages.lock().unwrap().push((chat_id.to_string(), msg.clone()));
}
fn on_community_update(&self, chat_id: &str, target: &str, _msg: &Message) {
self.updates.lock().unwrap().push((chat_id.to_string(), target.to_string()));
}
fn on_community_removed(&self, chat_id: &str, target: &str) {
self.removed.lock().unwrap().push((chat_id.to_string(), target.to_string()));
}
fn on_community_presence(&self, _c: &str, npub: &str, joined: bool, _e: &str, _a: u64, _b: Option<&str>, _l: Option<&str>) {
self.presence.lock().unwrap().push((npub.to_string(), joined));
}
fn on_community_typing(&self, chat_id: &str, npub: &str, _until: u64) {
self.typing.lock().unwrap().push((chat_id.to_string(), npub.to_string()));
}
}
fn init() -> (tempfile::TempDir, std::sync::MutexGuard<'static, ()>, Keys) {
let guard = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
crate::db::close_database();
crate::db::clear_id_caches();
let tmp = tempfile::tempdir().unwrap();
static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(90_000);
let n = N.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
const B: &[u8] = b"qpzry9x8gf2tvdw0s3jn54khce6mua7l";
let mut acct = String::from("npub1");
let mut v = n as usize;
for _ in 0..58 {
acct.push(B[v % 32] as char);
v = v / 32 + 7;
}
std::fs::create_dir_all(tmp.path().join(&acct)).unwrap();
crate::db::set_app_data_dir(crate::db::shared_test_data_dir().to_path_buf());
crate::db::set_current_account(acct.clone()).unwrap();
crate::db::init_database(&acct).unwrap();
let _ = crate::state::take_nostr_client();
let me = Keys::generate();
crate::state::MY_SECRET_KEY.store_from_keys(&me, &[]);
crate::state::set_my_public_key(me.public_key());
(tmp, guard, me)
}
#[tokio::test]
async fn a_restricted_channel_dispatches_its_writers_and_holds_the_rest() {
use super::super::writers::{writer_address, Ledger, Spell};
use crate::community::Epoch;
use nostr_sdk::prelude::Timestamp;
let (_tmp, _guard, me) = init();
let relay = MemoryRelay::new();
let mut community = service::create_community(&relay, "Live", vec!["wss://r".into()], None).await.unwrap();
let general = community.channels[0].id;
let epoch = community.root_epoch;
let read = super::super::derive::channel_group_key(&community.community_root, &general, epoch);
let (s1, s2) = ([0x11; 32], [0x22; 32]);
let w1 = super::super::derive::channel_writer_group_key(&s1, &general, Epoch(1));
let w2 = super::super::derive::channel_writer_group_key(&s2, &general, Epoch(2));
let ledger = Ledger::new(&general)
.appended(10_000, Spell::Writer { epoch: Epoch(1), pk: writer_address(&s1, &general, Epoch(1)), root: Epoch(0), by: [0x0b; 32], certifier: None })
.unwrap()
.appended(20_000, Spell::Writer { epoch: Epoch(2), pk: writer_address(&s2, &general, Epoch(2)), root: Epoch(0), by: [0x0b; 32], certifier: None })
.unwrap();
community.channels[0].writers = Some(ledger);
assert!(super::super::realtime::plane_authors(std::slice::from_ref(&community)).contains(&w2.pk()), "the live writer is subscribed");
let member = Keys::generate();
let post = |group: &super::super::derive::GroupKey, wepoch: Option<Epoch>, text: &str, at_ms: u64| {
let rumor = chat::build_message_rumor(member.public_key(), &general, epoch, text, None, &[], vec![], at_ms);
let rumor = match wepoch {
Some(w) => chat::with_writer_epoch(rumor, w),
None => rumor,
};
let split = super::super::derive::GroupKey::from_parts(group.keys().clone(), read.conv_key().clone());
chat::seal_chat_rumor(&rumor, &split, &member, Timestamp::from_secs(at_ms / 1000), false).unwrap().0
};
let rec = Recorder::default();
let chat = |wrap: &nostr_sdk::prelude::Event| matches!(dispatch_wrap(wrap, &community, &me.public_key(), &rec), DispatchedV2::Chat { .. });
assert!(chat(&post(&w2, Some(Epoch(2)), "live", 30_000)));
let as_message = |wrap: &nostr_sdk::prelude::Event| match dispatch_wrap(wrap, &community, &me.public_key(), &rec) {
DispatchedV2::Chat { event, .. } => match *event {
chat::ChatEvent::Message { opened, reply_to, emoji } => chat_message_to_message(&opened, &reply_to, &emoji, &me.public_key()),
_ => panic!("not a message"),
},
_ => panic!("not dispatched as chat"),
};
assert!(as_message(&post(&w2, Some(Epoch(2)), "signed by the key", 30_000)).writer);
assert!(!as_message(&post(&read, None, "said in the open", 5_000)).writer);
assert!(chat(&post(&w1, Some(Epoch(1)), "past", 15_000)), "a writer's past posts stay");
let held = |wrap: &nostr_sdk::prelude::Event| matches!(dispatch_wrap(wrap, &community, &me.public_key(), &rec), DispatchedV2::Held { marked: Some(ref e), .. } if e.opened().held);
assert!(held(&post(&w1, Some(Epoch(1)), "late", 25_000)), "held after its entry ends");
assert!(!chat(&post(&w2, Some(Epoch(1)), "spliced", 30_000)), "the epoch must be the address's");
assert!(!chat(&post(&w2, None, "untagged", 30_000)));
assert!(held(&post(&read, None, "flood", 30_000)), "held inside a writer window");
assert!(chat(&post(&read, None, "earlier", 5_000)), "before the window it was open");
assert!(!chat(&post(&read, Some(Epoch(2)), "dressed up", 5_000)), "a read-address post claims no writer epoch");
let reaction = chat::build_reaction_rumor(member.public_key(), &general, epoch, &crate::simd::hex::bytes_to_hex_32(&[0x33; 32]), &me.public_key().to_hex(), 9, "+", None, 30_000);
let (wrap, _) = chat::seal_chat_rumor(&reaction, &read, &member, Timestamp::from_secs(30), false).unwrap();
assert!(chat(&wrap), "reactions stay at the read address");
let typing = |group: &super::super::derive::GroupKey, wepoch: Option<Epoch>| {
let rumor = chat::build_typing_rumor(member.public_key(), &general, epoch, 30_000);
let rumor = match wepoch {
Some(w) => chat::with_writer_epoch(rumor, w),
None => rumor,
};
let split = super::super::derive::GroupKey::from_parts(group.keys().clone(), read.conv_key().clone());
chat::seal_chat_rumor(&rumor, &split, &member, Timestamp::from_secs(30), true).unwrap().0
};
assert!(matches!(dispatch_wrap(&typing(&read, None), &community, &me.public_key(), &rec), DispatchedV2::Ignored), "nobody shows as typing through the read address");
assert!(matches!(dispatch_wrap(&typing(&w2, Some(Epoch(2))), &community, &me.public_key(), &rec), DispatchedV2::Typing { .. }), "a writer does");
let presence = |endpoint: Option<[u8; 32]>, at_ms: u64| {
let rumor = chat::build_voice_presence_rumor(member.public_key(), &general, epoch, endpoint.as_ref().map(|e| (e, Some("https://relay.example./"))), crate::community::v2::voice::Showing { muted: true, ..Default::default() }, at_ms);
chat::seal_chat_rumor(&rumor, &read, &member, Timestamp::from_secs(at_ms / 1000), true).unwrap().0
};
let now = web_time::SystemTime::now().duration_since(web_time::UNIX_EPOCH).unwrap().as_millis() as u64;
let ch_hex = crate::simd::hex::bytes_to_hex_32(&general.0);
assert!(matches!(dispatch_wrap(&presence(Some([0x44; 32]), now), &community, &me.public_key(), &rec), DispatchedV2::VoicePresence { .. }), "a non-writer is in the call");
assert_eq!(super::super::voice::author_of(&ch_hex, &[0x44; 32], now), Some(member.public_key()), "the sealed presence binds its endpoint to them");
assert_eq!(super::super::voice::present(&ch_hex, now)[0].relay.as_deref(), Some("https://relay.example./"), "and names the relay it's reached through");
assert!(super::super::voice::present(&ch_hex, now)[0].muted && !super::super::voice::present(&ch_hex, now)[0].deafened, "and whether they're muted");
assert!(matches!(dispatch_wrap(&presence(None, now + 1), &community, &me.public_key(), &rec), DispatchedV2::VoicePresence { .. }));
assert!(super::super::voice::present(&ch_hex, now + 1).is_empty(), "and leaves it");
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
crate::db::community::set_community_banlist(&cid_hex, &[member.public_key().to_hex()], 1).unwrap();
assert!(matches!(dispatch_wrap(&presence(Some([0x45; 32]), now + 2), &community, &me.public_key(), &rec), DispatchedV2::Ignored), "a banned member is in no call");
crate::db::community::set_community_banlist(&cid_hex, &[], 2).unwrap();
let mut forged = post(&w2, Some(Epoch(2)), "forged", 30_000);
forged.sig = post(&w2, Some(Epoch(2)), "other", 30_001).sig;
assert!(!chat(&forged));
let reader = Keys::generate();
crate::state::MY_SECRET_KEY.store_from_keys(&reader, &[]);
crate::state::set_my_public_key(reader.public_key());
assert!(matches!(dispatch_wrap(&post(&w1, Some(Epoch(1)), "late again", 25_000), &community, &reader.public_key(), &rec), DispatchedV2::Held { marked: None, .. }));
assert!(matches!(dispatch_wrap(&post(&read, None, "flood again", 30_000), &community, &reader.public_key(), &rec), DispatchedV2::Held { marked: None, .. }));
assert!(matches!(dispatch_wrap(&post(&w1, Some(Epoch(1)), "past again", 15_000), &community, &reader.public_key(), &rec), DispatchedV2::Chat { .. }));
assert!(matches!(dispatch_wrap(&typing(&read, None), &community, &reader.public_key(), &rec), DispatchedV2::Ignored), "a signal of the moment is never held");
}
#[tokio::test]
async fn a_received_message_wrap_opens_then_fires_from_the_persist_outcome() {
use nostr_sdk::prelude::Timestamp;
let (_tmp, _guard, me) = init();
let relay = MemoryRelay::new();
let community = service::create_community(&relay, "In", vec!["wss://r".into()], None).await.unwrap();
let general = community.channels[0].id;
let cid = crate::simd::hex::bytes_to_hex_32(&general.0);
let member = Keys::generate();
let group = super::super::derive::channel_group_key(&community.community_root, &general, community.root_epoch);
let rumor = chat::build_message_rumor(member.public_key(), &general, community.root_epoch, "ping", None, &[], vec![], 5_000);
let (wrap, _) = chat::seal_chat_rumor(&rumor, &group, &member, Timestamp::from_secs(5), false).unwrap();
let rec = Recorder::default();
let dispatched = dispatch_wrap(&wrap, &community, &me.public_key(), &rec);
assert!(rec.messages.lock().unwrap().is_empty(), "no optimistic message callback");
let DispatchedV2::Chat { channel_id, event } = dispatched else {
panic!("a chat wrap dispatches as Chat");
};
assert_eq!(channel_id, cid);
let outcome = persist_chat_event(&event, &channel_id, &me.public_key()).await;
let Some(ChatPersist::New(msg)) = outcome else {
panic!("the first delivery persists as New");
};
assert_eq!(msg.content, "ping");
assert!(!msg.mine, "authored by the other member");
let (rewrap, _) = chat::seal_chat_rumor(&rumor, &group, &member, Timestamp::from_secs(6), false).unwrap();
assert_ne!(rewrap.id, wrap.id, "a re-wrap is a distinct outer event");
let DispatchedV2::Chat { event: dup, .. } = dispatch_wrap(&rewrap, &community, &me.public_key(), &rec) else {
panic!("the re-wrap still opens");
};
assert!(
persist_chat_event(&dup, &channel_id, &me.public_key()).await.is_none(),
"a re-wrapped duplicate yields no outcome (nothing re-fires)"
);
}
#[tokio::test]
async fn an_already_expired_message_is_refused_at_ingest() {
use nostr_sdk::prelude::{Tag, Timestamp};
let (_tmp, _guard, me) = init();
let relay = MemoryRelay::new();
let community = service::create_community(&relay, "Exp", vec!["wss://r".into()], None).await.unwrap();
let general = community.channels[0].id;
let member = Keys::generate();
let group = super::super::derive::channel_group_key(&community.community_root, &general, community.root_epoch);
let rec = Recorder::default();
let expired = vec![Tag::expiration(Timestamp::from_secs(1_000_000_000))];
let rumor = chat::build_message_rumor(member.public_key(), &general, community.root_epoch, "gone", None, &[], expired, 5_000);
let seal = stream::build_seal(&rumor, stream::SealForm::Encrypted, &group, &member).unwrap();
let (wrap, _) = stream::wrap_seal(&seal, &group, stream::KIND_WRAP, Timestamp::from_secs(5)).unwrap();
assert!(
!wrap.tags.iter().any(|t| t.as_slice().first().map(|k| k == "expiration").unwrap_or(false)),
"the outer wrap carries no expiration"
);
let DispatchedV2::Chat { channel_id, event } = dispatch_wrap(&wrap, &community, &me.public_key(), &rec) else {
panic!("a chat wrap dispatches as Chat");
};
let id = event.opened().rumor_id.to_hex();
assert!(
persist_chat_event(&event, &channel_id, &me.public_key()).await.is_none(),
"an expired message yields no outcome"
);
assert!(!crate::db::events::event_exists(&id).unwrap(), "never stored");
assert!(crate::state::STATE.lock().await.find_message(&id).is_none(), "never resident");
let later = vec![Tag::expiration(Timestamp::from_secs(4_000_000_000))];
let rumor = chat::build_message_rumor(member.public_key(), &general, community.root_epoch, "kept", None, &[], later, 6_000);
let (wrap, _) = chat::seal_chat_rumor(&rumor, &group, &member, Timestamp::from_secs(6), false).unwrap();
let DispatchedV2::Chat { channel_id, event } = dispatch_wrap(&wrap, &community, &me.public_key(), &rec) else {
panic!("a chat wrap dispatches as Chat");
};
let Some(ChatPersist::New(msg)) = persist_chat_event(&event, &channel_id, &me.public_key()).await else {
panic!("an unexpired message persists as New");
};
assert_eq!(msg.expiration, Some(4_000_000_000));
}
#[tokio::test]
async fn an_edit_expires_with_the_message_it_edits() {
use nostr_sdk::prelude::{Tag, Timestamp};
let (_tmp, _guard, _me) = init();
let relay = MemoryRelay::new();
let community = service::create_community(&relay, "EditExp", vec!["wss://r".into()], None).await.unwrap();
let general = community.channels[0].id;
let cid = crate::simd::hex::bytes_to_hex_32(&general.0);
let group = super::super::derive::channel_group_key(&community.community_root, &general, community.root_epoch);
async fn wire_expiry(
relay: &MemoryRelay,
community: &CommunityV2,
group: &super::super::derive::GroupKey,
edit_id: &str,
) -> (Option<u64>, Option<u64>) {
let general = community.channels[0].id;
let q = crate::community::transport::Query { kinds: vec![stream::KIND_WRAP], authors: vec![group.pk_hex()], ..Default::default() };
let wraps = relay.fetch(&q, &community.relays).await.unwrap();
wraps
.iter()
.find_map(|w| {
let ev = chat::open_chat_event(w, group, &general, community.root_epoch).ok()?;
(ev.opened().rumor_id.to_hex() == edit_id).then(|| {
let outer = w.tags.iter().find_map(|t| {
let s = t.as_slice();
(s.first().map(String::as_str) == Some("expiration")).then(|| s[1].parse::<u64>().unwrap())
});
(chat::message_expiration(&ev.opened().rumor), outer)
})
})
.expect("the edit is on the relay")
}
let exp = web_time::SystemTime::now().duration_since(web_time::UNIX_EPOCH).unwrap().as_secs() + 3_600;
let fleeting = service::send_chat_message(&relay, &community, &general, "fleeting", None, &[], vec![Tag::expiration(Timestamp::from_secs(exp))]).await.unwrap();
let edit = service::send_edit(&relay, &community, &general, &fleeting, "still fleeting", &[]).await.unwrap();
assert_eq!(wire_expiry(&relay, &community, &group, &edit).await, (Some(exp), Some(exp)), "the rumor and the wrap both carry the message's expiry");
let permanent = service::send_message(&relay, &community, &general, "forever").await.unwrap();
let edit = service::send_edit(&relay, &community, &general, &permanent, "still forever", &[]).await.unwrap();
assert_eq!(wire_expiry(&relay, &community, &group, &edit).await, (None, None), "a permanent message's edit is permanent");
crate::state::STATE.lock().await.remove_message(&fleeting);
assert_eq!(crate::self_destruct::edit_expiry(&fleeting).await, Ok(Some(exp)));
let lapsed = Message {
id: "ab".repeat(32), content: "gone".into(), at: 1_000, mine: true,
expiration: Some(1_000_000_000), ..Default::default()
};
crate::db::events::save_message(&cid, &lapsed).await.unwrap();
assert!(service::send_edit(&relay, &community, &general, &lapsed.id, "too late", &[]).await.is_err(), "an expired message can't be edited");
}
#[tokio::test]
async fn an_expired_reaction_or_edit_is_refused_but_an_expired_delete_still_lands() {
use nostr_sdk::prelude::{Tag, Timestamp, UnsignedEvent};
let (_tmp, _guard, me) = init();
let relay = MemoryRelay::new();
let community = service::create_community(&relay, "ExpAgg", vec!["wss://r".into()], None).await.unwrap();
let general = community.channels[0].id;
let epoch = community.root_epoch;
let cid = crate::simd::hex::bytes_to_hex_32(&general.0);
let group = super::super::derive::channel_group_key(&community.community_root, &general, epoch);
let member = Keys::generate();
let expired = |r: &UnsignedEvent| {
let mut tags: Vec<Tag> = r.tags.iter().cloned().collect();
tags.push(Tag::expiration(Timestamp::from_secs(1_000_000_000)));
stream::build_rumor_secs(r.kind.as_u16(), r.pubkey, &r.content, tags, r.created_at.as_secs())
};
let ingest = |rumor: UnsignedEvent, at: u64| {
let (wrap, _) = chat::seal_chat_rumor(&rumor, &group, &member, Timestamp::from_secs(at), false).unwrap();
chat::open_chat_event(&wrap, &group, &general, epoch).unwrap()
};
let msg = chat::build_message_rumor(member.public_key(), &general, epoch, "permanent", None, &[], vec![], 5_000);
let msg_id = msg.id.unwrap().to_hex();
assert!(matches!(persist_chat_event(&ingest(msg, 5), &cid, &me.public_key()).await, Some(ChatPersist::New(_))));
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);
assert!(persist_chat_event(&ingest(expired(&reaction), 6), &cid, &me.public_key()).await.is_none(), "an expired reaction is refused");
let edit = chat::build_edit_rumor(member.public_key(), &general, epoch, &msg_id, "rewritten", &[], None, 7_000);
assert!(persist_chat_event(&ingest(expired(&edit), 7), &cid, &me.public_key()).await.is_none(), "an expired edit is refused");
{
let st = crate::state::STATE.lock().await;
let (_, held) = st.find_message(&msg_id).expect("the message is resident");
assert!(held.reactions.is_empty(), "no reaction landed");
assert_eq!(held.content, "permanent", "no edit landed");
}
assert!(matches!(persist_chat_event(&ingest(reaction, 6), &cid, &me.public_key()).await, Some(ChatPersist::Updated { .. })));
let delete = chat::build_delete_rumor(member.public_key(), &general, epoch, &msg_id, super::super::kind::MESSAGE, 8_000, None);
let outcome = persist_chat_event(&ingest(expired(&delete), 8), &cid, &me.public_key()).await;
assert!(matches!(outcome, Some(ChatPersist::Removed { id, .. }) if id == msg_id), "an expired delete still erases");
}
#[tokio::test]
async fn a_reaction_edit_or_unreact_lands_on_a_message_paged_out_of_memory() {
use nostr_sdk::prelude::{Timestamp, UnsignedEvent};
let (_tmp, _guard, me) = init();
let relay = MemoryRelay::new();
let community = service::create_community(&relay, "PagedOut", vec!["wss://r".into()], None).await.unwrap();
let general = community.channels[0].id;
let epoch = community.root_epoch;
let cid = crate::simd::hex::bytes_to_hex_32(&general.0);
let group = super::super::derive::channel_group_key(&community.community_root, &general, epoch);
let member = Keys::generate();
let ingest = |rumor: UnsignedEvent, at: u64| {
let (wrap, _) = chat::seal_chat_rumor(&rumor, &group, &member, Timestamp::from_secs(at), false).unwrap();
chat::open_chat_event(&wrap, &group, &general, epoch).unwrap()
};
let page_out = || async {
let mut st = crate::state::STATE.lock().await;
st.chats.iter_mut().find(|c| c.id == cid).unwrap().messages.retain_newest(0);
};
let msg = chat::build_message_rumor(member.public_key(), &general, epoch, "hello", None, &[], vec![], 5_000);
let msg_id = msg.id.unwrap().to_hex();
assert!(matches!(persist_chat_event(&ingest(msg, 5), &cid, &me.public_key()).await, Some(ChatPersist::New(_))));
page_out().await;
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);
let reaction_id = reaction.id.unwrap().to_hex();
assert!(matches!(persist_chat_event(&ingest(reaction, 6), &cid, &me.public_key()).await, Some(ChatPersist::Updated { .. })), "the reaction lands");
page_out().await;
let edit = chat::build_edit_rumor(member.public_key(), &general, epoch, &msg_id, "rewritten", &[], None, 7_000);
assert!(matches!(persist_chat_event(&ingest(edit, 7), &cid, &me.public_key()).await, Some(ChatPersist::Updated { .. })), "the edit lands");
page_out().await;
let unreact = chat::build_delete_rumor(member.public_key(), &general, epoch, &reaction_id, super::super::kind::REACTION, 8_000, None);
assert!(matches!(persist_chat_event(&ingest(unreact, 8), &cid, &me.public_key()).await, Some(ChatPersist::ReactionRemoved { .. })), "the un-react lands");
let (_, stored) = crate::db::events::get_message_by_id(&msg_id).await.unwrap().unwrap();
assert_eq!(stored.content, "rewritten");
assert!(stored.reactions.is_empty());
}
#[tokio::test]
async fn reactions_on_an_edited_paged_out_message_keep_its_original_under_local_encryption() {
use nostr_sdk::prelude::{Timestamp, UnsignedEvent};
struct Vault;
impl Drop for Vault {
fn drop(&mut self) {
crate::state::ENCRYPTION_KEY.clear(&[]);
crate::state::set_encryption_enabled(false);
}
}
let (_tmp, _guard, me) = init();
let _vault = Vault;
crate::state::ENCRYPTION_KEY.set([0x5a; 32], &[]);
crate::state::set_encryption_enabled(true);
let relay = MemoryRelay::new();
let community = service::create_community(&relay, "Sealed", vec!["wss://r".into()], None).await.unwrap();
let general = community.channels[0].id;
let epoch = community.root_epoch;
let cid = crate::simd::hex::bytes_to_hex_32(&general.0);
let group = super::super::derive::channel_group_key(&community.community_root, &general, epoch);
let member = Keys::generate();
let ingest = |rumor: UnsignedEvent, at: u64| {
let (wrap, _) = chat::seal_chat_rumor(&rumor, &group, &member, Timestamp::from_secs(at), false).unwrap();
chat::open_chat_event(&wrap, &group, &general, epoch).unwrap()
};
let page_out = || async {
crate::state::STATE.lock().await.chats.iter_mut().find(|c| c.id == cid).unwrap().messages.retain_newest(0);
};
let stored_content = |id: &str| {
let conn = crate::db::get_db_connection_guard_static().unwrap();
conn.query_row("SELECT content FROM events WHERE id = ?1", [id], |r| r.get::<_, String>(0)).unwrap()
};
let msg = chat::build_message_rumor(member.public_key(), &general, epoch, "hello", None, &[], vec![], 5_000);
let msg_id = msg.id.unwrap().to_hex();
let react = |emoji: &str, at: u64| {
chat::build_reaction_rumor(member.public_key(), &general, epoch, &msg_id, &member.public_key().to_hex(), super::super::kind::MESSAGE, emoji, None, at)
};
assert!(matches!(persist_chat_event(&ingest(msg, 5), &cid, &me.public_key()).await, Some(ChatPersist::New(_))));
let written = stored_content(&msg_id);
let edit = chat::build_edit_rumor(member.public_key(), &general, epoch, &msg_id, "rewritten", &[], None, 6_000);
assert!(persist_chat_event(&ingest(edit, 6), &cid, &me.public_key()).await.is_some());
page_out().await;
let Some(ChatPersist::Updated { message, .. }) = persist_chat_event(&ingest(react("🔥", 7_000), 7), &cid, &me.public_key()).await else {
panic!("the reaction lands");
};
assert_eq!(message.content, "rewritten", "brought back as its text, not its sealed row");
page_out().await;
let second = react("🎉", 8_000);
let second_id = second.id.unwrap().to_hex();
let unreact = chat::build_delete_rumor(member.public_key(), &general, epoch, &second_id, super::super::kind::REACTION, 9_000, None);
let mut outcomes = Vec::new();
for (rumor, at) in [(second, 8), (unreact, 9)] {
let event = ingest(rumor, at);
hydrate_target(&event, &cid).await;
let mut st = crate::state::STATE.lock().await;
outcomes.extend(apply_chat_to_state(&mut st, &event, &cid, &me.public_key()));
}
assert_eq!(outcomes.len(), 2, "the page reacts and un-reacts");
persist_chat_page(&cid, &outcomes, &crate::db::current_session()).await;
assert_eq!(stored_content(&msg_id), written, "the original row is never rewritten");
assert_eq!(crate::crypto::maybe_decrypt_text(&written), "hello", "and was sealed once");
let (_, back) = crate::db::events::get_message_by_id(&msg_id).await.unwrap().unwrap();
assert_eq!(back.content, "rewritten");
assert_eq!(back.edit_history.as_ref().unwrap()[0].content, "hello");
assert_eq!(back.reactions.iter().map(|r| r.emoji.as_str()).collect::<Vec<_>>(), vec!["🔥"], "the revoked one is gone");
}
#[tokio::test]
async fn the_typed_hooks_name_what_happened() {
use nostr_sdk::prelude::{Timestamp, UnsignedEvent};
#[derive(Default)]
struct Typed(std::sync::Mutex<Vec<String>>);
impl InboundEventHandler for Typed {
fn on_reaction_added(&self, _c: &str, _m: &Message, r: &Reaction, at: u64) {
self.0.lock().unwrap().push(format!("react {} {}", r.emoji, at % 100_000));
}
fn on_reaction_removed(&self, _c: &str, _m: &Message, _id: &str, _by: &str, _at: u64) {
self.0.lock().unwrap().push("unreact".into());
}
fn on_message_edited(&self, _c: &str, m: &Message, _at: u64) {
self.0.lock().unwrap().push(format!("edit {}", m.content));
}
fn on_message_removed(&self, _c: &str, _id: &str, by: Option<&str>, moderated: bool, _at: u64) {
self.0.lock().unwrap().push(format!("removed {} {moderated}", &by.unwrap_or_default()[..5]));
}
}
let (_tmp, _guard, me) = init();
let relay = MemoryRelay::new();
let community = service::create_community(&relay, "Typed", vec!["wss://r".into()], None).await.unwrap();
let general = community.channels[0].id;
let epoch = community.root_epoch;
let cid = crate::simd::hex::bytes_to_hex_32(&general.0);
let group = super::super::derive::channel_group_key(&community.community_root, &general, epoch);
let member = Keys::generate();
let ingest = |rumor: UnsignedEvent, at: u64| {
let (wrap, _) = chat::seal_chat_rumor(&rumor, &group, &member, Timestamp::from_secs(at), false).unwrap();
chat::open_chat_event(&wrap, &group, &general, epoch).unwrap()
};
let t0 = crate::clock::now_ms() / 100_000 * 100_000 - 100_000;
let msg = chat::build_message_rumor(member.public_key(), &general, epoch, "hello", None, &[], vec![], t0 + 5_000);
let msg_id = msg.id.unwrap().to_hex();
let react = chat::build_reaction_rumor(member.public_key(), &general, epoch, &msg_id, &member.public_key().to_hex(), super::super::kind::MESSAGE, "🔥", None, t0 + 6_000);
let react_id = react.id.unwrap().to_hex();
let rumors = [
(msg, t0 + 5_000),
(react, t0 + 6_000),
(chat::build_edit_rumor(member.public_key(), &general, epoch, &msg_id, "rewritten", &[], None, t0 + 7_000), t0 + 7_000),
(chat::build_delete_rumor(member.public_key(), &general, epoch, &react_id, super::super::kind::REACTION, t0 + 8_000, None), t0 + 8_000),
(chat::build_delete_rumor(member.public_key(), &general, epoch, &msg_id, super::super::kind::MESSAGE, t0 + 9_000, None), t0 + 9_000),
];
let typed = Typed::default();
for (rumor, at) in rumors {
let event = ingest(rumor, at / 1000);
let outcome = persist_chat_event(&event, &cid, &me.public_key()).await.expect("each applies");
notify_chat_outcome(&typed, &cid, &event, outcome, false).await;
}
assert_eq!(*typed.0.lock().unwrap(), vec!["react 🔥 6000", "edit rewritten", "unreact", "removed npub1 false"]);
}
#[tokio::test]
async fn a_listener_hears_a_caught_up_message_once_and_never_history() {
use nostr_sdk::prelude::{Timestamp, UnsignedEvent};
#[derive(Default)]
struct Heard(std::sync::Mutex<Vec<(String, bool)>>);
impl InboundEventHandler for Heard {
fn on_community_message(&self, _c: &str, m: &Message, is_new: bool) {
self.0.lock().unwrap().push((m.content.clone(), is_new));
}
}
let (_tmp, _guard, me) = init();
let relay = MemoryRelay::new();
let community = service::create_community(&relay, "Gap", vec!["wss://r".into()], None).await.unwrap();
let general = community.channels[0].id;
let epoch = community.root_epoch;
let cid = crate::simd::hex::bytes_to_hex_32(&general.0);
let group = super::super::derive::channel_group_key(&community.community_root, &general, epoch);
let member = Keys::generate();
let fetched = |rumor: UnsignedEvent, at_ms: u64| {
let (wrap, _) = chat::seal_chat_rumor(&rumor, &group, &member, Timestamp::from_secs(at_ms / 1000), false).unwrap();
service::FetchedEvent { event: chat::open_chat_event(&wrap, &group, &general, epoch).unwrap(), epoch, wrap: Some(wrap) }
};
let now = crate::clock::now_ms();
let heard = std::sync::Arc::new(Heard::default());
let _listening = crate::news::listen_for_test(heard.clone(), now - 600_000);
let gap = chat::build_message_rumor(member.public_key(), &general, epoch, "sent during the gap", None, &[], vec![], now - 300_000);
let old = chat::build_message_rumor(member.public_key(), &general, epoch, "last week", None, &[], vec![], now - 7 * 86_400_000);
let page = vec![fetched(gap.clone(), now - 300_000), fetched(old, now - 7 * 86_400_000)];
crate::VectorCore::v2_ingest_chat_page(&cid, me.public_key(), crate::db::current_session(), page).await;
assert_eq!(*heard.0.lock().unwrap(), vec![("sent during the gap".to_string(), true)], "the catch-up delivers news, not history");
let again = fetched(gap, now - 300_000);
assert!(persist_chat_event(&again.event, &cid, &me.public_key()).await.is_none());
assert_eq!(heard.0.lock().unwrap().len(), 1);
let racing = chat::build_message_rumor(member.public_key(), &general, epoch, "caught twice", None, &[], vec![], now - 200_000);
let page = || vec![fetched(racing.clone(), now - 200_000)];
let session = crate::db::current_session();
tokio::join!(
crate::VectorCore::v2_ingest_chat_page(&cid, me.public_key(), session.clone(), page()),
crate::VectorCore::v2_ingest_chat_page(&cid, me.public_key(), session.clone(), page()),
);
let told = heard.0.lock().unwrap().iter().filter(|(text, news)| text == "caught twice" && *news).count();
assert_eq!(told, 1, "told once, whichever stored it");
}
#[tokio::test]
async fn a_deleted_message_stays_deleted_when_a_relay_serves_it_again() {
use nostr_sdk::prelude::{Timestamp, UnsignedEvent};
let (_tmp, _guard, me) = init();
let relay = MemoryRelay::new();
let community = service::create_community(&relay, "Gone", vec!["wss://r".into()], None).await.unwrap();
let general = community.channels[0].id;
let epoch = community.root_epoch;
let cid = crate::simd::hex::bytes_to_hex_32(&general.0);
let group = super::super::derive::channel_group_key(&community.community_root, &general, epoch);
let member = Keys::generate();
let ingest = |rumor: UnsignedEvent, at: u64| {
let (wrap, _) = chat::seal_chat_rumor(&rumor, &group, &member, Timestamp::from_secs(at), false).unwrap();
chat::open_chat_event(&wrap, &group, &general, epoch).unwrap()
};
let msg = chat::build_message_rumor(member.public_key(), &general, epoch, "regret", None, &[], vec![], 5_000);
let msg_id = msg.id.unwrap().to_hex();
let original = ingest(msg, 5);
assert!(matches!(persist_chat_event(&original, &cid, &me.public_key()).await, Some(ChatPersist::New(_))));
let delete = chat::build_delete_rumor(member.public_key(), &general, epoch, &msg_id, super::super::kind::MESSAGE, 6_000, None);
assert!(matches!(persist_chat_event(&ingest(delete, 6), &cid, &me.public_key()).await, Some(ChatPersist::Removed { .. })));
crate::state::clear_message_tombstones();
crate::state::seed_message_tombstones(crate::db::events::load_message_tombstones().unwrap());
assert!(persist_chat_event(&original, &cid, &me.public_key()).await.is_none(), "the original, served again, stays gone");
let page = [apply_chat_to_state(&mut *crate::state::STATE.lock().await, &original, &cid, &me.public_key())];
assert!(page[0].is_none(), "and a catch-up page refuses it too");
let at = crate::db::events::locate_message(&msg_id).unwrap();
assert_eq!((at.chat, at.deleted), (None, true), "a link to it reads as deleted");
}
#[tokio::test]
async fn a_guestbook_join_wrap_fires_presence() {
let (_tmp, _guard, me) = init();
let relay = MemoryRelay::new();
let community = service::create_community(&relay, "GB", vec!["wss://r".into()], None).await.unwrap();
let gb = super::super::derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch);
let q = crate::community::transport::Query { kinds: vec![stream::KIND_WRAP], authors: vec![gb.pk_hex()], ..Default::default() };
let wraps = relay.fetch(&q, &community.relays).await.unwrap();
let rec = Recorder::default();
for w in &wraps {
dispatch_wrap(w, &community, &me.public_key(), &rec);
}
let pres = rec.presence.lock().unwrap();
assert_eq!(pres.len(), 1, "the owner's genesis Join fires one presence");
assert!(pres[0].1, "it's a join");
assert_eq!(pres[0].0, me.public_key().to_bech32().unwrap());
}
#[tokio::test]
async fn v2_chat_events_persist_into_the_shared_store() {
let (_tmp, _guard, me) = init();
let relay = MemoryRelay::new();
let community = service::create_community(&relay, "Persist", vec!["wss://r".into()], None).await.unwrap();
let general = community.channels[0].id;
let cid = crate::simd::hex::bytes_to_hex_32(&general.0);
let group = super::super::derive::channel_group_key(&community.community_root, &general, community.root_epoch);
let me_hex = me.public_key().to_hex();
let msg_id = service::send_message(&relay, &community, &general, "persist me").await.unwrap();
service::send_reaction(&relay, &community, &general, &msg_id, &me_hex, super::super::kind::MESSAGE, "🔥", None).await.unwrap();
assert!(crate::db::events::event_exists(&msg_id).unwrap(), "the send echo persisted the message row");
let reacted = {
let st = crate::state::STATE.lock().await;
st.find_message(&msg_id).map(|(_, m)| m.reactions.iter().any(|r| r.emoji == "🔥")).unwrap_or(false)
};
assert!(reacted, "the send echo aggregated the reaction onto the stored message");
let q = crate::community::transport::Query { kinds: vec![stream::KIND_WRAP], authors: vec![group.pk_hex()], ..Default::default() };
let wraps = relay.fetch(&q, &community.relays).await.unwrap();
let mut events: Vec<ChatEvent> = wraps.iter().filter_map(|w| chat::open_chat_event(w, &group, &general, community.root_epoch).ok()).collect();
events.sort_by_key(|e| e.opened().at_ms);
assert!(!events.is_empty());
for ev in &events {
let outcome = {
let mut st = crate::state::STATE.lock().await;
apply_chat_to_state(&mut st, ev, &cid, &me.public_key())
};
assert!(outcome.is_none(), "the relay echo of an already-echoed send dedups");
}
}
#[tokio::test]
async fn a_v2_edit_persists_as_a_folded_edit_event() {
let (_tmp, _guard, me) = init();
let relay = MemoryRelay::new();
let community = service::create_community(&relay, "Edit", vec!["wss://r".into()], None).await.unwrap();
let general = community.channels[0].id;
let cid = crate::simd::hex::bytes_to_hex_32(&general.0);
let group = super::super::derive::channel_group_key(&community.community_root, &general, community.root_epoch);
let msg_id = service::send_message(&relay, &community, &general, "original").await.unwrap();
service::send_edit(&relay, &community, &general, &msg_id, "edited!", &[]).await.unwrap();
let q = crate::community::transport::Query { kinds: vec![stream::KIND_WRAP], authors: vec![group.pk_hex()], ..Default::default() };
let wraps = relay.fetch(&q, &community.relays).await.unwrap();
let mut events: Vec<ChatEvent> = wraps.iter().filter_map(|w| chat::open_chat_event(w, &group, &general, community.root_epoch).ok()).collect();
events.sort_by_key(|e| (!matches!(e, ChatEvent::Message { .. }), e.opened().at_ms));
for ev in &events {
let outcome = {
let mut st = crate::state::STATE.lock().await;
apply_chat_to_state(&mut st, ev, &cid, &me.public_key())
};
if let Some(o) = outcome {
persist_chat(&cid, &o).await;
}
}
let content = {
let st = crate::state::STATE.lock().await;
st.find_message(&msg_id).map(|(_, m)| m.content)
};
assert_eq!(content.as_deref(), Some("edited!"), "the edit applied to the stored message");
let edit_id = events.iter().find_map(|e| matches!(e, ChatEvent::Edit { .. }).then(|| e.opened().rumor_id.to_hex())).unwrap();
assert!(crate::db::events::event_exists(&edit_id).unwrap(), "the MESSAGE_EDIT event is persisted (folds on reload)");
}
#[tokio::test]
async fn colour_spans_travel_with_messages_and_edits() {
use crate::text_color::Effect;
use crate::text_spans::{extract, to_nostr_tags, TextSpan};
let (_tmp, _guard, me) = init();
let relay = MemoryRelay::new();
let community = service::create_community(&relay, "Colour", vec!["wss://r".into()], None).await.unwrap();
let general = community.channels[0].id;
let cid = crate::simd::hex::bytes_to_hex_32(&general.0);
let group = super::super::derive::channel_group_key(&community.community_root, &general, community.root_epoch);
let (plain, spans) = extract("hi <rainbow>everyone</rainbow> at <t:0:R>!");
let msg_id = service::send_chat_message(&relay, &community, &general, &plain, None, &[], to_nostr_tags(&spans).collect()).await.unwrap();
let (edited, edit_spans) = extract("<color pink>bye</color> all");
service::send_edit_tagged(&relay, &community, &general, &msg_id, &edited, &[], to_nostr_tags(&edit_spans).collect()).await.unwrap();
let q = crate::community::transport::Query { kinds: vec![stream::KIND_WRAP], authors: vec![group.pk_hex()], ..Default::default() };
let wraps = relay.fetch(&q, &community.relays).await.unwrap();
let mut events: Vec<ChatEvent> = wraps.iter().filter_map(|w| chat::open_chat_event(w, &group, &general, community.root_epoch).ok()).collect();
events.sort_by_key(|e| (!matches!(e, ChatEvent::Message { .. }), e.opened().at_ms));
let sent = events.iter().find(|e| matches!(e, ChatEvent::Message { .. })).unwrap().opened();
assert_eq!(sent.rumor.content, "hi everyone at 1970-01-01 00:00 UTC!", "the markup never reaches the wire");
let wire = crate::text_spans::from_tags(sent.rumor.tags.iter(), &sent.rumor.content);
assert_eq!(wire.len(), 2);
assert!(matches!(&wire[0], TextSpan::Color(c) if (c.from, c.to, c.effect) == (3, 11, Effect::Rainbow)));
assert!(matches!(&wire[1], TextSpan::Time(t) if (t.from, t.to, t.unix, t.style) == (15, 35, 0, 'R')));
let built = chat_message_to_message(sent, &None, &[], &me.public_key());
assert_eq!(built.text_spans, wire, "the inbound message carries the wire's spans");
for ev in &events {
let o = {
let mut st = crate::state::STATE.lock().await;
apply_chat_to_state(&mut st, ev, &cid, &me.public_key())
};
if let Some(o) = o { persist_chat(&cid, &o).await; }
}
let folded = crate::state::STATE.lock().await.find_message(&msg_id).map(|(_, m)| m).unwrap();
assert_eq!(folded.content, "bye all");
assert_eq!(folded.text_spans, edit_spans, "the edit's spans replace the original's");
let chat_db = crate::db::id_cache::get_chat_id_by_identifier(&cid).unwrap();
let reloaded = crate::db::events::get_message_views(chat_db, 50, 0).await.unwrap()
.into_iter().find(|m| m.id == msg_id).expect("reloaded");
assert_eq!(reloaded.content, "bye all");
assert_eq!(reloaded.text_spans, edit_spans, "the reload fold reads the edit's spans");
}
#[tokio::test]
async fn an_edit_carries_its_custom_emoji_to_peers_and_across_restart() {
let (_tmp, _guard, me) = init();
let relay = MemoryRelay::new();
let community = service::create_community(&relay, "EditEmoji", vec!["wss://r".into()], None).await.unwrap();
let general = community.channels[0].id;
let cid = crate::simd::hex::bytes_to_hex_32(&general.0);
let group = super::super::derive::channel_group_key(&community.community_root, &general, community.root_epoch);
let msg_id = service::send_message(&relay, &community, &general, "plain").await.unwrap();
service::send_edit(
&relay, &community, &general, &msg_id,
"now with :vectorlove:",
&[("vectorlove", "https://cdn.example/vectorlove.webp")],
).await.unwrap();
let q = crate::community::transport::Query { kinds: vec![stream::KIND_WRAP], authors: vec![group.pk_hex()], ..Default::default() };
let wraps = relay.fetch(&q, &community.relays).await.unwrap();
let mut events: Vec<ChatEvent> = wraps.iter().filter_map(|w| chat::open_chat_event(w, &group, &general, community.root_epoch).ok()).collect();
events.sort_by_key(|e| (!matches!(e, ChatEvent::Message { .. }), e.opened().at_ms));
let wire_emoji = events.iter().find_map(|e| match e {
ChatEvent::Edit { emoji, .. } => Some(emoji.clone()),
_ => None,
}).expect("the edit decodes");
assert_eq!(
wire_emoji,
vec![("vectorlove".to_string(), "https://cdn.example/vectorlove.webp".to_string())],
"the 3302 rumor carries the NIP-30 pair on the wire"
);
for ev in &events {
let outcome = {
let mut st = crate::state::STATE.lock().await;
apply_chat_to_state(&mut st, ev, &cid, &me.public_key())
};
if let Some(o) = outcome {
persist_chat(&cid, &o).await;
}
}
let folded = {
let st = crate::state::STATE.lock().await;
st.find_message(&msg_id).map(|(_, m)| m.emoji_tags.clone())
}.expect("message resident");
assert_eq!(folded.len(), 1, "the fold adopted the edit's emoji set");
assert_eq!(folded[0].shortcode, "vectorlove");
assert_eq!(folded[0].url, "https://cdn.example/vectorlove.webp");
let edit_id = events.iter().find_map(|e| matches!(e, ChatEvent::Edit { .. }).then(|| e.opened().rumor_id.to_hex())).unwrap();
let (_wrap, stored_tags) = crate::db::events::get_event_wrap_context(&edit_id)
.unwrap()
.expect("the MESSAGE_EDIT row is persisted");
let restored = crate::types::EmojiTag::extract_from_stored(&stored_tags);
assert_eq!(restored.len(), 1, "the MESSAGE_EDIT row carries the tags the reload fold reads");
assert_eq!(restored[0].shortcode, "vectorlove");
}
#[tokio::test]
async fn a_reaction_after_a_rekey_aggregates_onto_a_prior_epoch_message() {
use nostr_sdk::prelude::Timestamp;
let (_tmp, _guard, me) = init();
let relay = MemoryRelay::new();
let community = service::create_community(&relay, "Rekeyed", vec!["wss://r".into()], None).await.unwrap();
let general = community.channels[0].id;
let cid = crate::simd::hex::bytes_to_hex_32(&general.0);
let member = Keys::generate();
let g0 = super::super::derive::channel_group_key(&community.community_root, &general, community.root_epoch);
let msg = chat::build_message_rumor(member.public_key(), &general, community.root_epoch, "before the rekey", None, &[], vec![], 5_000);
let msg_id = msg.id.unwrap().to_hex();
let (mw, _) = chat::seal_chat_rumor(&msg, &g0, &member, Timestamp::from_secs(5), false).unwrap();
let ev = chat::open_chat_event(&mw, &g0, &general, community.root_epoch).unwrap();
assert!(matches!(persist_chat_event(&ev, &cid, &me.public_key()).await, Some(ChatPersist::New(_))));
let next = crate::community::Epoch(community.root_epoch.0 + 1);
let g1 = super::super::derive::channel_group_key(&community.community_root, &general, next);
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);
let (rw, _) = chat::seal_chat_rumor(&reaction, &g1, &member, Timestamp::from_secs(6), false).unwrap();
let rev = chat::open_chat_event(&rw, &g1, &general, next).unwrap();
let outcome = persist_chat_event(&rev, &cid, &me.public_key()).await;
assert!(matches!(outcome, Some(ChatPersist::Updated { .. })), "the cross-epoch reaction updates the target");
let reaction_author = {
let st = crate::state::STATE.lock().await;
st.find_message(&msg_id)
.and_then(|(_, m)| m.reactions.iter().find(|r| r.emoji == "🎉").map(|r| r.author_id.clone()))
};
let author = reaction_author.expect("the epoch-1 reaction aggregated onto the epoch-0 message");
assert_eq!(author, member.public_key().to_bech32().unwrap(), "reaction author is stored as bech32");
}
#[tokio::test]
async fn an_un_react_removes_the_reaction_for_receivers_and_only_for_its_reactor() {
use nostr_sdk::prelude::Timestamp;
let (_tmp, _guard, me) = init();
let relay = MemoryRelay::new();
let community = service::create_community(&relay, "UnReact", vec!["wss://r".into()], None).await.unwrap();
let general = community.channels[0].id;
let cid = crate::simd::hex::bytes_to_hex_32(&general.0);
let (secret, epoch) = community.channel_secret(&community.channels[0]);
let group = super::super::derive::channel_group_key(&secret, &general, epoch);
let member = Keys::generate();
let msg = chat::build_message_rumor(member.public_key(), &general, epoch, "react to me", None, &[], vec![], 5_000);
let msg_id = msg.id.unwrap().to_hex();
let (mw, _) = chat::seal_chat_rumor(&msg, &group, &member, Timestamp::from_secs(5), false).unwrap();
let ev = chat::open_chat_event(&mw, &group, &general, epoch).unwrap();
assert!(matches!(persist_chat_event(&ev, &cid, &me.public_key()).await, Some(ChatPersist::New(_))));
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);
let reaction_id = reaction.id.unwrap().to_hex();
let (rw, _) = chat::seal_chat_rumor(&reaction, &group, &member, Timestamp::from_secs(6), false).unwrap();
let rev = chat::open_chat_event(&rw, &group, &general, epoch).unwrap();
assert!(matches!(persist_chat_event(&rev, &cid, &me.public_key()).await, Some(ChatPersist::Updated { .. })));
let outsider = Keys::generate();
let forged = chat::build_delete_rumor(outsider.public_key(), &general, epoch, &reaction_id, super::super::kind::MESSAGE, 7_000, None);
let (fw, _) = chat::seal_chat_rumor(&forged, &group, &outsider, Timestamp::from_secs(7), false).unwrap();
let fev = chat::open_chat_event(&fw, &group, &general, epoch).unwrap();
assert!(persist_chat_event(&fev, &cid, &me.public_key()).await.is_none(), "only the reactor revokes their reaction");
let revoke = chat::build_delete_rumor(member.public_key(), &general, epoch, &reaction_id, super::super::kind::MESSAGE, 8_000, None);
let (vw, _) = chat::seal_chat_rumor(&revoke, &group, &member, Timestamp::from_secs(8), false).unwrap();
let vev = chat::open_chat_event(&vw, &group, &general, epoch).unwrap();
assert!(matches!(persist_chat_event(&vev, &cid, &me.public_key()).await, Some(ChatPersist::ReactionRemoved { .. })));
let (has_reaction, parent_alive) = {
let st = crate::state::STATE.lock().await;
(
st.find_reaction(&reaction_id).is_some(),
st.find_message(&msg_id).is_some(),
)
};
assert!(!has_reaction, "the chip is gone from STATE");
assert!(parent_alive, "the parent message survives an un-react");
assert!(!crate::db::events::event_exists(&reaction_id).unwrap(), "the kind-7 row is deleted");
}
#[tokio::test]
async fn a_guestbook_join_fires_presence_with_its_real_rumor_id() {
use nostr_sdk::prelude::Timestamp;
use std::sync::Mutex as StdMutex;
let (_tmp, _guard, me) = init();
let relay = MemoryRelay::new();
let community = service::create_community(&relay, "Pres", vec!["wss://r".into()], None).await.unwrap();
#[derive(Default)]
struct Capture(StdMutex<Vec<(String, bool, String)>>);
impl InboundEventHandler for Capture {
fn on_community_presence(&self, _chat_id: &str, npub: &str, joined: bool, event_id: &str, _at: u64, _by: Option<&str>, _label: Option<&str>) {
self.0.lock().unwrap().push((npub.into(), joined, event_id.into()));
}
}
let member = Keys::generate();
let gb = super::super::derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch);
let rumor = guestbook::build_join_rumor(member.public_key(), None, 5_000);
let (wrap, _) = super::super::guestbook::seal_guestbook_rumor(&rumor, &gb, &member, Timestamp::from_secs(5)).unwrap();
let expected_id = rumor.id.unwrap().to_hex();
let cap = Capture::default();
let out = dispatch_wrap(&wrap, &community, &me.public_key(), &cap);
assert!(matches!(out, DispatchedV2::Presence { joined: true, .. }));
let seen = cap.0.lock().unwrap().clone();
assert_eq!(seen.len(), 1);
assert_eq!(seen[0].0, member.public_key().to_bech32().unwrap());
assert_eq!(seen[0].2, expected_id, "presence carries the join's own rumor id");
}
#[tokio::test]
async fn a_guestbook_kick_dispatches_its_target_and_raises_no_presence_line() {
use nostr_sdk::prelude::Timestamp;
use std::sync::Mutex as StdMutex;
let (_tmp, _guard, me) = init();
let relay = MemoryRelay::new();
let community = service::create_community(&relay, "Kicks", vec!["wss://r".into()], None).await.unwrap();
#[derive(Default)]
struct Capture(StdMutex<usize>);
impl InboundEventHandler for Capture {
fn on_community_presence(&self, _c: &str, _n: &str, _j: bool, _e: &str, _a: u64, _b: Option<&str>, _l: Option<&str>) {
*self.0.lock().unwrap() += 1;
}
}
let target = Keys::generate();
let gb = super::super::derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch);
let rumor = guestbook::build_kick_rumor(me.public_key(), target.public_key(), None, 5_000);
let (wrap, _) = super::super::guestbook::seal_guestbook_rumor(&rumor, &gb, &me, Timestamp::from_secs(5)).unwrap();
let cap = Capture::default();
let out = dispatch_wrap(&wrap, &community, &me.public_key(), &cap);
match out {
DispatchedV2::Kick { target: t, .. } => assert_eq!(t, target.public_key(), "the kick names its target"),
other => panic!("a Kick must reach the store, got {other:?}"),
}
assert_eq!(*cap.0.lock().unwrap(), 0, "a kick raises no presence line");
}
#[tokio::test]
async fn a_webxdc_peer_ad_fires_the_shared_handler_and_own_echo_drops() {
use nostr_sdk::prelude::Timestamp;
use std::sync::Mutex as StdMutex;
let (_tmp, _guard, me) = init();
let relay = MemoryRelay::new();
let community = service::create_community(&relay, "XDC", vec!["wss://r".into()], None).await.unwrap();
let general = community.channels[0].id;
#[derive(Default)]
struct Capture(StdMutex<Vec<(String, String, Option<String>)>>);
impl InboundEventHandler for Capture {
fn on_community_webxdc(&self, _chat_id: &str, npub: &str, topic_id: &str, node_addr: Option<&str>, _event_id: &str, _created_at: u64) {
self.0.lock().unwrap().push((npub.into(), topic_id.into(), node_addr.map(String::from)));
}
}
let topic = "B".repeat(52);
let content = crate::webxdc::peer_signal_content(&topic, Some("iroh:node/xyz"));
let (secret, epoch) = community.channel_secret(&community.channels[0]);
let group = super::super::derive::channel_group_key(&secret, &general, epoch);
let peer = Keys::generate();
let rumor = chat::build_webxdc_rumor(peer.public_key(), &general, epoch, &content, vec![], 5_000);
let (wrap, _) = chat::seal_chat_rumor(&rumor, &group, &peer, Timestamp::from_secs(5), false).unwrap();
let cap = Capture::default();
let out = dispatch_wrap(&wrap, &community, &me.public_key(), &cap);
assert!(matches!(out, DispatchedV2::Ignored), "fired inline, nothing to persist v2-side");
let seen = cap.0.lock().unwrap().clone();
assert_eq!(seen.len(), 1);
assert_eq!(seen[0].0, peer.public_key().to_bech32().unwrap());
assert_eq!(seen[0].1, topic);
assert_eq!(seen[0].2.as_deref(), Some("iroh:node/xyz"));
let own = chat::build_webxdc_rumor(me.public_key(), &general, epoch, &content, vec![], 6_000);
let (own_wrap, _) = chat::seal_chat_rumor(&own, &group, &me, Timestamp::from_secs(6), false).unwrap();
let cap2 = Capture::default();
dispatch_wrap(&own_wrap, &community, &me.public_key(), &cap2);
assert!(cap2.0.lock().unwrap().is_empty(), "own-device echo drops");
}
#[tokio::test]
async fn a_v2_message_with_an_imeta_attachment_surfaces_as_an_attachment() {
use nostr_sdk::prelude::Timestamp;
let (_tmp, _guard, me) = init();
let relay = MemoryRelay::new();
let community = service::create_community(&relay, "Files", vec!["wss://r".into()], None).await.unwrap();
let general = community.channels[0].id;
let cid = crate::simd::hex::bytes_to_hex_32(&general.0);
let group = super::super::derive::channel_group_key(&community.community_root, &general, community.root_epoch);
let attachment = crate::types::Attachment {
id: "a".repeat(64),
key: "0".repeat(64),
nonce: "1".repeat(32),
extension: "png".into(),
name: "photo.png".into(),
url: "https://blossom.example/abc".into(),
path: String::new(),
size: 4096,
img_meta: None,
downloading: false,
downloaded: false, verified: false, resident: false,
webxdc_topic: None,
group_id: None,
original_hash: Some("b".repeat(64)),
fallback_urls: Vec::new(),
};
let imeta = crate::community::attachments::attachment_to_imeta(&attachment);
let member = Keys::generate();
let rumor = chat::build_message_rumor(member.public_key(), &general, community.root_epoch, "here's a file", None, &[], vec![imeta], 5_000);
let (wrap, _) = chat::seal_chat_rumor(&rumor, &group, &member, Timestamp::from_secs(5), false).unwrap();
let ev = chat::open_chat_event(&wrap, &group, &general, community.root_epoch).unwrap();
let outcome = persist_chat_event(&ev, &cid, &me.public_key()).await;
let Some(ChatPersist::New(msg)) = outcome else {
panic!("the file message persists as new");
};
assert_eq!(msg.attachments.len(), 1, "the imeta tag parsed into one attachment");
let att = &msg.attachments[0];
assert!(att.url.contains("blossom.example"), "attachment url carried through: {}", att.url);
assert_eq!(att.extension, "png", "extension carried through");
}
#[tokio::test]
async fn a_banned_members_every_chat_event_is_dropped_on_sight() {
use nostr_sdk::prelude::Timestamp;
let (_tmp, _guard, me) = init();
let relay = MemoryRelay::new();
let community = service::create_community(&relay, "BanGate", vec!["wss://r".into()], None).await.unwrap();
let general = community.channels[0].id;
let cid = crate::simd::hex::bytes_to_hex_32(&general.0);
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let group = super::super::derive::channel_group_key(&community.community_root, &general, community.root_epoch);
let rogue = Keys::generate();
let m1 = chat::build_message_rumor(rogue.public_key(), &general, community.root_epoch, "pre-ban", None, &[], vec![], 5_000);
let m1_id = m1.id.unwrap().to_hex();
let (w1, _) = chat::seal_chat_rumor(&m1, &group, &rogue, Timestamp::from_secs(5), false).unwrap();
let ev = chat::open_chat_event(&w1, &group, &general, community.root_epoch).unwrap();
assert!(matches!(persist_chat_event(&ev, &cid, &me.public_key()).await, Some(ChatPersist::New(_))));
crate::db::community::set_community_banlist(&cid_hex, &[rogue.public_key().to_hex()], 1_000).unwrap();
let m2 = chat::build_message_rumor(rogue.public_key(), &general, community.root_epoch, "post-ban", None, &[], vec![], 6_000);
let (w2, _) = chat::seal_chat_rumor(&m2, &group, &rogue, Timestamp::from_secs(6), false).unwrap();
let ev = chat::open_chat_event(&w2, &group, &general, community.root_epoch).unwrap();
assert!(persist_chat_event(&ev, &cid, &me.public_key()).await.is_none(), "a banned message is dropped");
let edit = chat::build_edit_rumor(rogue.public_key(), &general, community.root_epoch, &m1_id, "rewritten", &[], None, 7_000);
let (we, _) = chat::seal_chat_rumor(&edit, &group, &rogue, Timestamp::from_secs(7), false).unwrap();
let ev = chat::open_chat_event(&we, &group, &general, community.root_epoch).unwrap();
assert!(persist_chat_event(&ev, &cid, &me.public_key()).await.is_none(), "a banned edit is dropped");
let del = chat::build_delete_rumor(rogue.public_key(), &general, community.root_epoch, &m1_id, super::super::kind::MESSAGE, 8_000, None);
let (wd, _) = chat::seal_chat_rumor(&del, &group, &rogue, Timestamp::from_secs(8), false).unwrap();
let ev = chat::open_chat_event(&wd, &group, &general, community.root_epoch).unwrap();
assert!(persist_chat_event(&ev, &cid, &me.public_key()).await.is_none(), "a banned delete is dropped");
assert!(
crate::state::STATE.lock().await.find_message(&m1_id).is_some(),
"their pre-ban message survives their own post-ban delete"
);
let rec = Recorder::default();
let typ = chat::build_typing_rumor(rogue.public_key(), &general, community.root_epoch, 9_000);
let (wt, _) = chat::seal_chat_rumor(&typ, &group, &rogue, Timestamp::from_secs(9), true).unwrap();
assert!(matches!(dispatch_wrap(&wt, &community, &me.public_key(), &rec), DispatchedV2::Ignored));
let gb = super::super::derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch);
let join = guestbook::build_join_rumor(rogue.public_key(), None, 10_000);
let (wj, _) = guestbook::seal_guestbook_rumor(&join, &gb, &rogue, Timestamp::from_secs(10)).unwrap();
assert!(matches!(dispatch_wrap(&wj, &community, &me.public_key(), &rec), DispatchedV2::Presence { joined: true, .. }));
assert!(rec.presence.lock().unwrap().is_empty(), "no presence callback for a banned join");
let innocent = Keys::generate();
let m3 = chat::build_message_rumor(innocent.public_key(), &general, community.root_epoch, "innocent", None, &[], vec![], 11_000);
let (w3, _) = chat::seal_chat_rumor(&m3, &group, &innocent, Timestamp::from_secs(11), false).unwrap();
let ev = chat::open_chat_event(&w3, &group, &general, community.root_epoch).unwrap();
assert!(matches!(persist_chat_event(&ev, &cid, &me.public_key()).await, Some(ChatPersist::New(_))));
}
#[tokio::test]
async fn my_own_typing_from_another_client_never_paints_me_as_typing() {
use nostr_sdk::prelude::Timestamp;
let (_tmp, _guard, me) = init();
let relay = MemoryRelay::new();
let community = service::create_community(&relay, "Typing", vec!["wss://r".into()], None).await.unwrap();
let general = community.channels[0].id;
let cid = crate::simd::hex::bytes_to_hex_32(&general.0);
let group = super::super::derive::channel_group_key(&community.community_root, &general, community.root_epoch);
let rec = Recorder::default();
let mine = chat::build_typing_rumor(me.public_key(), &general, community.root_epoch, 5_000);
let (wm, _) = chat::seal_chat_rumor(&mine, &group, &me, Timestamp::from_secs(5), true).unwrap();
assert!(
matches!(dispatch_wrap(&wm, &community, &me.public_key(), &rec), DispatchedV2::Ignored),
"our own typing signal is not someone typing at us"
);
assert!(rec.typing.lock().unwrap().is_empty(), "no typing callback for our own signal");
let peer = Keys::generate();
let theirs = chat::build_typing_rumor(peer.public_key(), &general, community.root_epoch, 6_000);
let (wt, _) = chat::seal_chat_rumor(&theirs, &group, &peer, Timestamp::from_secs(6), true).unwrap();
assert!(matches!(dispatch_wrap(&wt, &community, &me.public_key(), &rec), DispatchedV2::Typing { .. }));
let got = rec.typing.lock().unwrap();
assert_eq!(got.len(), 1, "exactly the peer's signal fired");
assert_eq!(got[0].0, cid);
assert_eq!(got[0].1, peer.public_key().to_bech32().unwrap());
}
#[tokio::test]
async fn an_armada_threaded_reply_persists_and_fires_as_an_inline_reply() {
use nostr_sdk::prelude::Timestamp;
let (_tmp, _guard, me) = init();
let relay = MemoryRelay::new();
let community = service::create_community(&relay, "Thread", vec!["wss://r".into()], None).await.unwrap();
let general = community.channels[0].id;
let cid = crate::simd::hex::bytes_to_hex_32(&general.0);
let group = super::super::derive::channel_group_key(&community.community_root, &general, community.root_epoch);
let member = Keys::generate();
let root = chat::build_message_rumor(member.public_key(), &general, community.root_epoch, "thread root", None, &[], vec![], 5_000);
let root_id = root.id.unwrap().to_hex();
let (rw, _) = chat::seal_chat_rumor(&root, &group, &member, Timestamp::from_secs(5), false).unwrap();
let reply = chat::build_comment_rumor(
member.public_key(),
&general,
community.root_epoch,
"thread reply",
&root_id,
super::super::kind::MESSAGE,
&member.public_key().to_hex(),
None,
&[],
6_000,
);
let reply_id = reply.id.unwrap().to_hex();
let (tw, _) = chat::seal_chat_rumor(&reply, &group, &member, Timestamp::from_secs(6), false).unwrap();
for w in [&rw, &tw] {
let ev = chat::open_chat_event(w, &group, &general, community.root_epoch).unwrap();
let outcome = persist_chat_event(&ev, &cid, &me.public_key()).await;
assert!(matches!(outcome, Some(ChatPersist::New(_))), "both persist as new messages");
}
let held = {
let st = crate::state::STATE.lock().await;
st.find_message(&reply_id).map(|(_, m)| m)
}
.expect("the threaded reply is resident");
assert_eq!(held.replied_to, root_id, "the immediate parent is the reply context");
assert_eq!(held.content, "thread reply");
let del = chat::build_delete_rumor(member.public_key(), &general, community.root_epoch, &reply_id, super::super::kind::COMMENT, 7_000, None);
let (dw, _) = chat::seal_chat_rumor(&del, &group, &member, Timestamp::from_secs(7), false).unwrap();
let ev = chat::open_chat_event(&dw, &group, &general, community.root_epoch).unwrap();
let outcome = persist_chat_event(&ev, &cid, &me.public_key()).await;
assert!(matches!(outcome, Some(ChatPersist::Removed { id, .. }) if id == reply_id), "the author's delete removes their thread reply");
}
#[tokio::test]
async fn an_edit_replay_never_refires() {
use nostr_sdk::prelude::Timestamp;
let (_tmp, _guard, me) = init();
let relay = MemoryRelay::new();
let community = service::create_community(&relay, "EditReplay", vec!["wss://r".into()], None).await.unwrap();
let general = community.channels[0].id;
let cid = crate::simd::hex::bytes_to_hex_32(&general.0);
let group = super::super::derive::channel_group_key(&community.community_root, &general, community.root_epoch);
let member = Keys::generate();
let msg = chat::build_message_rumor(member.public_key(), &general, community.root_epoch, "v1 text", None, &[], vec![], 5_000);
let msg_id = msg.id.unwrap().to_hex();
let (mw, _) = chat::seal_chat_rumor(&msg, &group, &member, Timestamp::from_secs(5), false).unwrap();
let edit = chat::build_edit_rumor(member.public_key(), &general, community.root_epoch, &msg_id, "v2 text", &[], None, 6_000);
let (ew, _) = chat::seal_chat_rumor(&edit, &group, &member, Timestamp::from_secs(6), false).unwrap();
for w in [&mw, &ew] {
if let Ok(ev) = chat::open_chat_event(w, &group, &general, community.root_epoch) {
let _ = persist_chat_event(&ev, &cid, &me.public_key()).await;
}
}
let (replay, _) = chat::seal_chat_rumor(&edit, &group, &member, Timestamp::from_secs(7), false).unwrap();
assert_ne!(replay.id, ew.id, "a re-wrap is a distinct outer event");
let ev = chat::open_chat_event(&replay, &group, &general, community.root_epoch).unwrap();
assert!(
persist_chat_event(&ev, &cid, &me.public_key()).await.is_none(),
"a replayed edit yields no outcome (no handler re-fire)"
);
}
#[tokio::test]
async fn a_forged_edit_from_a_non_author_is_ignored() {
use nostr_sdk::prelude::Timestamp;
let (_tmp, _guard, me) = init();
let relay = MemoryRelay::new();
let community = service::create_community(&relay, "EditGuard", vec!["wss://r".into()], None).await.unwrap();
let general = community.channels[0].id;
let cid = crate::simd::hex::bytes_to_hex_32(&general.0);
let group = super::super::derive::channel_group_key(&community.community_root, &general, community.root_epoch);
let author = Keys::generate();
let msg = chat::build_message_rumor(author.public_key(), &general, community.root_epoch, "original", None, &[], vec![], 5_000);
let msg_id = msg.id.unwrap().to_hex();
let (mw, _) = chat::seal_chat_rumor(&msg, &group, &author, Timestamp::from_secs(5), false).unwrap();
let ev = chat::open_chat_event(&mw, &group, &general, community.root_epoch).unwrap();
persist_chat_event(&ev, &cid, &me.public_key()).await;
let stranger = Keys::generate();
let edit = chat::build_edit_rumor(stranger.public_key(), &general, community.root_epoch, &msg_id, "TAMPERED", &[], None, 6_000);
let (ew, _) = chat::seal_chat_rumor(&edit, &group, &stranger, Timestamp::from_secs(6), false).unwrap();
let ev = chat::open_chat_event(&ew, &group, &general, community.root_epoch).unwrap();
assert!(persist_chat_event(&ev, &cid, &me.public_key()).await.is_none(), "a forged edit yields no outcome");
let content = {
let st = crate::state::STATE.lock().await;
st.find_message(&msg_id).map(|(_, m)| m.content)
};
assert_eq!(content.as_deref(), Some("original"), "the message content is unchanged by the forged edit");
}
#[tokio::test]
async fn a_reaction_cannot_be_injected_across_channels() {
use nostr_sdk::prelude::Timestamp;
let (_tmp, _guard, me) = init();
let relay = MemoryRelay::new();
let mut community = service::create_community(&relay, "TwoChan", vec!["wss://r".into()], None).await.unwrap();
let chan_a = community.channels[0].id;
let chan_b = service::create_public_channel(&relay, &community, "b").await.unwrap();
community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
let a_hex = crate::simd::hex::bytes_to_hex_32(&chan_a.0);
let author = Keys::generate();
let gb = super::super::derive::channel_group_key(&community.community_root, &chan_b, community.root_epoch);
let msg = chat::build_message_rumor(author.public_key(), &chan_b, community.root_epoch, "in B", None, &[], vec![], 5_000);
let msg_id = msg.id.unwrap().to_hex();
let (mw, _) = chat::seal_chat_rumor(&msg, &gb, &author, Timestamp::from_secs(5), false).unwrap();
let bev = chat::open_chat_event(&mw, &gb, &chan_b, community.root_epoch).unwrap();
persist_chat_event(&bev, &crate::simd::hex::bytes_to_hex_32(&chan_b.0), &me.public_key()).await;
let ga = super::super::derive::channel_group_key(&community.community_root, &chan_a, community.root_epoch);
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);
let (rw, _) = chat::seal_chat_rumor(&reaction, &ga, &author, Timestamp::from_secs(6), false).unwrap();
let aev = chat::open_chat_event(&rw, &ga, &chan_a, community.root_epoch).unwrap();
let outcome = persist_chat_event(&aev, &a_hex, &me.public_key()).await;
assert!(outcome.is_none(), "a cross-channel reaction is dropped");
let reacted = {
let st = crate::state::STATE.lock().await;
st.find_message(&msg_id).map(|(_, m)| !m.reactions.is_empty()).unwrap_or(false)
};
assert!(!reacted, "the channel-B message gained no reaction from the channel-A injection");
}
#[tokio::test]
async fn a_reaction_with_junk_content_is_dropped_and_a_clean_one_lands() {
use nostr_sdk::prelude::Timestamp;
let (_tmp, _guard, me) = init();
let relay = MemoryRelay::new();
let community = service::create_community(&relay, "Junk", vec!["wss://r".into()], None).await.unwrap();
let general = community.channels[0].id;
let cid = crate::simd::hex::bytes_to_hex_32(&general.0);
let group = super::super::derive::channel_group_key(&community.community_root, &general, community.root_epoch);
let author = Keys::generate();
let msg = chat::build_message_rumor(author.public_key(), &general, community.root_epoch, "hi", None, &[], vec![], 5_000);
let msg_id = msg.id.unwrap().to_hex();
let (mw, _) = chat::seal_chat_rumor(&msg, &group, &author, Timestamp::from_secs(5), false).unwrap();
let ev = chat::open_chat_event(&mw, &group, &general, community.root_epoch).unwrap();
persist_chat_event(&ev, &cid, &me.public_key()).await;
let react = |content: &str, at: u64| {
let r = chat::build_reaction_rumor(author.public_key(), &general, community.root_epoch, &msg_id, &author.public_key().to_hex(), super::super::kind::MESSAGE, content, None, at);
let (w, _) = chat::seal_chat_rumor(&r, &group, &author, Timestamp::from_secs(at / 1000), false).unwrap();
chat::open_chat_event(&w, &group, &general, community.root_epoch).unwrap()
};
let junk = react(":catclap:https://i.nostr.build/lLMrw.gif", 6_000);
assert!(persist_chat_event(&junk, &cid, &me.public_key()).await.is_none(), "a shortcode+URL reaction is dropped");
let clean = react(":catclap:", 7_000);
assert!(persist_chat_event(&clean, &cid, &me.public_key()).await.is_some(), "a clean shortcode reaction lands");
let emojis: Vec<String> = {
let st = crate::state::STATE.lock().await;
st.find_message(&msg_id).map(|(_, m)| m.reactions.iter().map(|r| r.emoji.clone()).collect()).unwrap_or_default()
};
assert_eq!(emojis, vec![":catclap:".to_string()]);
}
#[tokio::test]
async fn a_forged_delete_from_a_non_author_is_ignored() {
use nostr_sdk::prelude::Timestamp;
let (_tmp, _guard, me) = init();
let relay = MemoryRelay::new();
let community = service::create_community(&relay, "Forge", vec!["wss://r".into()], None).await.unwrap();
let general = community.channels[0].id;
let cid = crate::simd::hex::bytes_to_hex_32(&general.0);
let group = super::super::derive::channel_group_key(&community.community_root, &general, community.root_epoch);
let msg_id = service::send_message(&relay, &community, &general, "mine").await.unwrap();
let q = crate::community::transport::Query { kinds: vec![stream::KIND_WRAP], authors: vec![group.pk_hex()], ..Default::default() };
let wraps = relay.fetch(&q, &community.relays).await.unwrap();
for w in &wraps {
if let Ok(ev) = chat::open_chat_event(w, &group, &general, community.root_epoch) {
let mut st = crate::state::STATE.lock().await;
apply_chat_to_state(&mut st, &ev, &cid, &me.public_key());
}
}
let stranger = nostr_sdk::prelude::Keys::generate();
let del = chat::build_delete_rumor(stranger.public_key(), &general, community.root_epoch, &msg_id, super::super::kind::MESSAGE, 9_000, None);
let (wrap, _) = chat::seal_chat_rumor(&del, &group, &stranger, Timestamp::from_secs(9), false).unwrap();
let event = chat::open_chat_event(&wrap, &group, &general, community.root_epoch).unwrap();
let outcome = {
let mut st = crate::state::STATE.lock().await;
apply_chat_to_state(&mut st, &event, &cid, &me.public_key())
};
assert!(outcome.is_none(), "a forged delete from a non-author yields no removal");
let survives = {
let st = crate::state::STATE.lock().await;
st.find_message(&msg_id).is_some()
};
assert!(survives, "the message survives the forged delete (live view + DB stay consistent)");
}
struct ModerationBed {
community: super::super::community::CommunityV2,
general: crate::community::ChannelId,
chat_id: String,
group: super::super::derive::GroupKey,
admin: Keys,
admin_citation: crate::community::edition::AuthorityCitation,
}
async fn moderation_bed(relay: &MemoryRelay, name: &str) -> ModerationBed {
let community = service::create_community(relay, name, vec!["wss://r".into()], None).await.unwrap();
let general = community.channels[0].id;
let chat_id = crate::simd::hex::bytes_to_hex_32(&general.0);
let group = super::super::derive::channel_group_key(&community.community_root, &general, community.root_epoch);
let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
let admin = Keys::generate();
service::grant_admin(relay, &community, &admin.public_key()).await.unwrap();
let view = service::fetch_authority(relay, &community).await;
crate::db::community::set_community_roles(&cid_hex, &view.roles, 1_000).unwrap();
let entity_id = super::super::derive::grant_locator(community.id(), &admin.public_key().to_bytes());
let entity_hex = crate::simd::hex::bytes_to_hex_32(&entity_id);
let (version, edition_hash) = crate::db::community::get_edition_head(&cid_hex, &entity_hex)
.unwrap()
.expect("the owner's own grant publish stores its head");
let admin_citation = crate::community::edition::AuthorityCitation { entity_id, version, edition_hash };
ModerationBed { community, general, chat_id, group, admin, admin_citation }
}
async fn post_as(bed: &ModerationBed, author: &Keys, body: &str, at: u64, me: &PublicKey) -> String {
use nostr_sdk::prelude::Timestamp;
let rumor = chat::build_message_rumor(author.public_key(), &bed.general, bed.community.root_epoch, body, None, &[], vec![], at);
let (wrap, _) = chat::seal_chat_rumor(&rumor, &bed.group, author, Timestamp::from_secs(at / 1000), false).unwrap();
let event = chat::open_chat_event(&wrap, &bed.group, &bed.general, bed.community.root_epoch).unwrap();
let id = rumor.id.unwrap().to_hex();
let mut st = crate::state::STATE.lock().await;
apply_chat_to_state(&mut st, &event, &bed.chat_id, me);
id
}
async fn delete_as(
bed: &ModerationBed,
actor: &Keys,
target: &str,
citation: Option<&crate::community::edition::AuthorityCitation>,
at: u64,
me: &PublicKey,
) -> Option<ChatPersist> {
use nostr_sdk::prelude::Timestamp;
let del = chat::build_delete_rumor(actor.public_key(), &bed.general, bed.community.root_epoch, target, super::super::kind::MESSAGE, at, citation);
let (wrap, _) = chat::seal_chat_rumor(&del, &bed.group, actor, Timestamp::from_secs(at / 1000), false).unwrap();
let event = chat::open_chat_event(&wrap, &bed.group, &bed.general, bed.community.root_epoch).unwrap();
let mut st = crate::state::STATE.lock().await;
apply_chat_to_state(&mut st, &event, &bed.chat_id, me)
}
#[tokio::test]
async fn an_admins_moderation_delete_removes_a_members_message() {
let (_tmp, _guard, me) = init();
let relay = MemoryRelay::new();
let bed = moderation_bed(&relay, "Mod").await;
let member = Keys::generate();
let victim = post_as(&bed, &member, "spam", 1_000, &me.public_key()).await;
let outcome = delete_as(&bed, &bed.admin, &victim, Some(&bed.admin_citation), 2_000, &me.public_key()).await;
assert!(matches!(outcome, Some(ChatPersist::Removed { ref id, moderated: true }) if *id == victim), "MANAGE_MESSAGES + outrank removes it, as a moderator");
assert!(crate::state::STATE.lock().await.find_message(&victim).is_none());
}
#[tokio::test]
async fn an_admin_cannot_moderation_delete_the_owners_message() {
let (_tmp, _guard, me) = init();
let relay = MemoryRelay::new();
let bed = moderation_bed(&relay, "Sacred").await;
let owners_message = post_as(&bed, &me, "the owner speaks", 1_000, &me.public_key()).await;
let outcome = delete_as(&bed, &bed.admin, &owners_message, Some(&bed.admin_citation), 2_000, &me.public_key()).await;
assert!(outcome.is_none(), "an admin never outranks the owner");
assert!(crate::state::STATE.lock().await.find_message(&owners_message).is_some());
}
#[tokio::test]
async fn a_moderation_delete_without_a_synced_citation_is_refused() {
let (_tmp, _guard, me) = init();
let relay = MemoryRelay::new();
let bed = moderation_bed(&relay, "Uncited").await;
let member = Keys::generate();
let victim = post_as(&bed, &member, "spam", 1_000, &me.public_key()).await;
assert!(delete_as(&bed, &bed.admin, &victim, None, 2_000, &me.public_key()).await.is_none());
assert!(crate::state::STATE.lock().await.find_message(&victim).is_some());
assert!(delete_as(&bed, &bed.admin, &victim, Some(&bed.admin_citation), 3_000, &me.public_key()).await.is_some());
}
#[tokio::test]
async fn a_roleless_member_cannot_moderation_delete_anyone() {
let (_tmp, _guard, me) = init();
let relay = MemoryRelay::new();
let bed = moderation_bed(&relay, "Roleless").await;
let (member, rando) = (Keys::generate(), Keys::generate());
let victim = post_as(&bed, &member, "hello", 1_000, &me.public_key()).await;
let outcome = delete_as(&bed, &rando, &victim, Some(&bed.admin_citation), 2_000, &me.public_key()).await;
assert!(outcome.is_none(), "no MANAGE_MESSAGES, no removal");
assert!(crate::state::STATE.lock().await.find_message(&victim).is_some());
}
#[tokio::test]
async fn a_member_still_deletes_their_own_message_uncited() {
let (_tmp, _guard, me) = init();
let relay = MemoryRelay::new();
let bed = moderation_bed(&relay, "Self").await;
let member = Keys::generate();
let mine = post_as(&bed, &member, "oops", 1_000, &me.public_key()).await;
let outcome = delete_as(&bed, &member, &mine, None, 2_000, &me.public_key()).await;
assert!(matches!(outcome, Some(ChatPersist::Removed { ref id, moderated: false }) if *id == mine));
}
#[tokio::test]
async fn a_foreign_wrap_is_not_ours() {
let (_tmp, _guard, me) = init();
let relay = MemoryRelay::new();
let community = service::create_community(&relay, "X", vec!["wss://r".into()], None).await.unwrap();
let stranger = super::super::derive::channel_group_key(&[0x99u8; 32], &community.channels[0].id, community.root_epoch);
let rumor = chat::build_message_rumor(me.public_key(), &community.channels[0].id, community.root_epoch, "not yours", None, &[], vec![], 1_000);
let (wrap, _) = chat::seal_chat_rumor(&rumor, &stranger, &me, nostr_sdk::prelude::Timestamp::from_secs(1), false).unwrap();
let rec = Recorder::default();
assert!(matches!(dispatch_wrap(&wrap, &community, &me.public_key(), &rec), DispatchedV2::NotOurs));
assert!(rec.messages.lock().unwrap().is_empty());
}
}