vector_core/event_handler.rs
1//! Event handler — gift wrap receive, unwrap, process, commit pipeline.
2//!
3//! Two-phase architecture:
4//! - **Phase 1** (`prepare_event`): Parallel-safe — dedup, unwrap, process_rumor
5//! - **Phase 2** (`commit_prepared_event`): Sequential — save DB, update STATE, emit
6//!
7//! Platform-specific behavior (notifications) handled by `InboundEventHandler` trait.
8
9use nostr_sdk::prelude::*;
10
11use crate::rumor::{RumorProcessingResult, RumorEvent, RumorContext, ConversationType, process_rumor};
12use crate::types::Message;
13use crate::state::WRAPPER_ID_CACHE;
14
15/// Platform-specific callbacks for inbound event processing.
16///
17/// Same pattern as SendCallback/ProfileSyncHandler — trait with default no-ops.
18/// Platforms implement only the hooks they need.
19pub trait InboundEventHandler: Send + Sync {
20 /// A DM text message was received and committed to STATE + DB.
21 fn on_dm_received(&self, _chat_id: &str, _msg: &Message, _is_new: bool) {}
22
23 /// A DM file attachment was received and committed to STATE + DB.
24 fn on_file_received(&self, _chat_id: &str, _msg: &Message, _is_new: bool) {}
25
26 /// A reaction was received and applied to a message.
27 fn on_reaction_received(&self, _chat_id: &str, _msg: &Message) {}
28
29 /// A previously-stored message was deleted by its sender (Layer 2
30 /// cooperative hide via NIP-09 over NIP-17). Frontend drops the row.
31 fn on_message_deleted(&self, _chat_id: &str, _message_id: &str) {}
32
33 /// A Community invite was received over a gift wrap and the local user was
34 /// joined (member-view Community persisted). Platform refreshes the Community
35 /// subscription so messages start flowing, and surfaces the new Community in the UI.
36 fn on_community_invite(&self, _community_id: &str) {}
37
38 // --- Community realtime (Concord channel events; `chat_id` is the channel id hex) ---
39
40 /// A new Community channel message was received, ingested into STATE, and persisted.
41 fn on_community_message(&self, _chat_id: &str, _msg: &Message, _is_new: bool) {}
42
43 /// A reaction or edit was applied to an existing Community message. `target_id` is the
44 /// affected message; `msg` is the live-updated view.
45 fn on_community_update(&self, _chat_id: &str, _target_id: &str, _msg: &Message) {}
46
47 /// A Community message was removed (cooperative delete / moderation tombstone).
48 fn on_community_removed(&self, _chat_id: &str, _target_id: &str) {}
49
50 /// A join/leave presence announcement. `created_at` is the authenticated inner timestamp;
51 /// `invited_by`/`invited_label` carry invite attribution when present.
52 #[allow(clippy::too_many_arguments)]
53 fn on_community_presence(
54 &self,
55 _chat_id: &str,
56 _npub: &str,
57 _joined: bool,
58 _event_id: &str,
59 _created_at: u64,
60 _invited_by: Option<&str>,
61 _invited_label: Option<&str>,
62 ) {}
63
64 /// A Community typing indicator (ephemeral). `until` is the unix-secs the typer stops being active.
65 fn on_community_typing(&self, _chat_id: &str, _npub: &str, _until: u64) {}
66
67 /// A WebXDC realtime peer signal. `node_addr` = `Some` advertises an Iroh node, `None` = peer-left.
68 #[allow(clippy::too_many_arguments)]
69 fn on_community_webxdc(
70 &self,
71 _chat_id: &str,
72 _npub: &str,
73 _topic_id: &str,
74 _node_addr: Option<&str>,
75 _event_id: &str,
76 _created_at: u64,
77 ) {}
78
79 /// The local user was removed from a Community (kick / ban / a leave authored on another device).
80 /// Local data is torn down (epoch keys retained); the platform surfaces it + refreshes subs.
81 fn on_community_self_removed(&self, _community_id: &str) {}
82
83 /// A Private channel is now readable — its key arrived, by rekey delivery or
84 /// by a grant's key vend. `channel_id` is the 32-byte hex id.
85 ///
86 /// The inverse of the silent-mute failure: a bot granted access can act the
87 /// moment it can actually read, rather than polling for a channel it has no
88 /// way to know it is waiting on.
89 fn on_channel_keyed(&self, _community_id: &str, _channel_id: &str) {}
90
91 /// A Community's control plane was refreshed in realtime (banlist/roles/metadata/mode change,
92 /// or a re-founding followed). The platform re-reads display state.
93 fn on_community_refreshed(&self, _community_id: &str) {}
94
95 /// A Community was DISSOLVED by its owner (CORD-02 §9): sealed read-only, held keys still open
96 /// history but nothing new is honored. The platform surfaces the grave.
97 fn on_community_dissolved(&self, _community_id: &str) {}
98
99 /// Bulk-sync persist intercept: return `true` to take ownership of persisting a committed
100 /// DM/file message — the commit then SKIPS its per-message save AND its wrapper-ledger
101 /// write (`wrapper` = the gift-wrap's `(id_bytes, created_at)`; the owner MUST commit it
102 /// in the same transaction as the message row, or the message loses crash/drop
103 /// recoverability). Streaming sync loops (see [`BatchingPersist`]) buffer here and drain
104 /// many messages into one transaction. Default `false` keeps the per-message save.
105 fn buffer_persist(&self, _chat_id: &str, _msg: &Message, _wrapper: Option<([u8; 32], u64)>) -> bool { false }
106}
107
108/// No-op handler for CLI/tests.
109pub struct NoOpEventHandler;
110impl InboundEventHandler for NoOpEventHandler {}
111
112/// One deferred DM persist: the message, its chat, and its gift-wrap ledger entry — the
113/// ledger row commits in the same flush transaction as the message row (see
114/// `save_messages_batch_multi`), so a lost batch leaves the wrapper unledgered.
115struct BufferedDm {
116 chat_id: String,
117 msg: Message,
118 wrapper: Option<([u8; 32], u64)>,
119}
120
121/// Wraps any handler for a bulk-sync drain loop: every callback delegates to the inner
122/// handler, but committed messages BUFFER here instead of saving one transaction each —
123/// the loop calls [`BatchingPersist::flush`] periodically and at stream end to land them
124/// in batched transactions (`save_messages_batch_multi`).
125///
126/// Deferral is recoverable because the wrapper ledger (the negentropy fingerprint set)
127/// rides the flush transaction: a message lost to a crash, a stale-session drop, or a
128/// failed flush leaves its wrapper unledgered, so the next reconciliation re-delivers it.
129pub struct BatchingPersist<'a> {
130 inner: &'a dyn InboundEventHandler,
131 buf: std::sync::Mutex<Vec<BufferedDm>>,
132}
133
134impl<'a> BatchingPersist<'a> {
135 pub fn new(inner: &'a dyn InboundEventHandler) -> Self {
136 Self { inner, buf: std::sync::Mutex::new(Vec::new()) }
137 }
138
139 /// How many messages are waiting — the loop's flush-threshold probe.
140 pub fn buffered(&self) -> usize {
141 self.buf.lock().map(|b| b.len()).unwrap_or(0)
142 }
143
144 /// Drain the buffer into batched transactions (grouped by chat, arrival order kept).
145 /// On a stale session the drained messages are DROPPED, never written into the next
146 /// account's DB — their wrappers stay unledgered, so negentropy re-delivers them when
147 /// the original account returns.
148 pub async fn flush(&self, session: &crate::state::SessionGuard) -> usize {
149 self.try_flush(session).await.unwrap_or(0)
150 }
151
152 /// [`Self::flush`], but a persist failure is distinguishable from "nothing
153 /// to write" — callers that gate follow-on effects on the ledger actually
154 /// holding the batch (reconcile-cursor births) need the difference: an
155 /// advance over an unledgered batch skips those events forever.
156 pub async fn try_flush(&self, session: &crate::state::SessionGuard) -> Result<usize, String> {
157 let mut drained: Vec<BufferedDm> = match self.buf.lock() {
158 Ok(mut b) => b.drain(..).collect(),
159 Err(_) => return Ok(0),
160 };
161 if drained.is_empty() || !session.is_valid() {
162 return Ok(0);
163 }
164 // A deletion may have landed (live subscription or this stream) while an entry sat
165 // buffered: its delete_event no-ops on the not-yet-written row, so persisting the
166 // buffered copy would resurrect a deleted message. Keyed on the POSITIVE deletion
167 // tombstone, never STATE absence — the LRU evicts old messages from STATE, and
168 // archive-synced history is exactly that tail (an evicted message must still
169 // persist). A dropped entry's wrapper stays unledgered and re-delivers next sync,
170 // where the DB dedup sees the (still-deleted) state cleanly.
171 drained.retain(|e| !crate::state::was_message_deleted(&e.msg.id));
172 if drained.is_empty() {
173 return Ok(0);
174 }
175 // Group by chat preserving first-seen chat order + per-chat arrival order.
176 let mut groups: Vec<(String, Vec<(&Message, Option<([u8; 32], u64)>)>)> = Vec::new();
177 for e in &drained {
178 match groups.iter_mut().find(|(c, _)| c == &e.chat_id) {
179 Some((_, v)) => v.push((&e.msg, e.wrapper)),
180 None => groups.push((e.chat_id.clone(), vec![(&e.msg, e.wrapper)])),
181 }
182 }
183 match crate::db::events::save_messages_batch_multi(&groups, Some(session)).await {
184 Ok(n) => Ok(n),
185 Err(e) => {
186 crate::log_warn!("[Sync] batched persist failed ({} msgs): {}", drained.len(), e);
187 Err(e)
188 }
189 }
190 }
191}
192
193impl InboundEventHandler for BatchingPersist<'_> {
194 fn buffer_persist(&self, chat_id: &str, msg: &Message, wrapper: Option<([u8; 32], u64)>) -> bool {
195 match self.buf.lock() {
196 Ok(mut b) => {
197 b.push(BufferedDm { chat_id: chat_id.to_string(), msg: msg.clone(), wrapper });
198 true
199 }
200 // Poisoned lock: fall back to the commit's own per-message save.
201 Err(_) => false,
202 }
203 }
204
205 fn on_dm_received(&self, chat_id: &str, msg: &Message, is_new: bool) {
206 self.inner.on_dm_received(chat_id, msg, is_new)
207 }
208 fn on_file_received(&self, chat_id: &str, msg: &Message, is_new: bool) {
209 self.inner.on_file_received(chat_id, msg, is_new)
210 }
211 fn on_reaction_received(&self, chat_id: &str, msg: &Message) {
212 self.inner.on_reaction_received(chat_id, msg)
213 }
214 fn on_message_deleted(&self, chat_id: &str, message_id: &str) {
215 // The deletion's delete_event no-ops when the target is still buffered here —
216 // purge it (unledgered wrapper → re-delivers → dedups against the deleted state)
217 // so the flush can't resurrect a deleted message.
218 if let Ok(mut b) = self.buf.lock() {
219 b.retain(|e| e.msg.id != message_id);
220 }
221 self.inner.on_message_deleted(chat_id, message_id)
222 }
223 fn on_community_invite(&self, community_id: &str) {
224 self.inner.on_community_invite(community_id)
225 }
226 fn on_community_message(&self, chat_id: &str, msg: &Message, is_new: bool) {
227 self.inner.on_community_message(chat_id, msg, is_new)
228 }
229 fn on_community_update(&self, chat_id: &str, target_id: &str, msg: &Message) {
230 self.inner.on_community_update(chat_id, target_id, msg)
231 }
232 fn on_community_removed(&self, chat_id: &str, target_id: &str) {
233 self.inner.on_community_removed(chat_id, target_id)
234 }
235 fn on_community_presence(
236 &self,
237 chat_id: &str,
238 npub: &str,
239 joined: bool,
240 event_id: &str,
241 created_at: u64,
242 invited_by: Option<&str>,
243 invited_label: Option<&str>,
244 ) {
245 self.inner.on_community_presence(chat_id, npub, joined, event_id, created_at, invited_by, invited_label)
246 }
247 fn on_community_typing(&self, chat_id: &str, npub: &str, until: u64) {
248 self.inner.on_community_typing(chat_id, npub, until)
249 }
250 fn on_community_webxdc(
251 &self,
252 chat_id: &str,
253 npub: &str,
254 topic_id: &str,
255 node_addr: Option<&str>,
256 event_id: &str,
257 created_at: u64,
258 ) {
259 self.inner.on_community_webxdc(chat_id, npub, topic_id, node_addr, event_id, created_at)
260 }
261 fn on_community_self_removed(&self, community_id: &str) {
262 self.inner.on_community_self_removed(community_id)
263 }
264 fn on_community_refreshed(&self, community_id: &str) {
265 self.inner.on_community_refreshed(community_id)
266 }
267 fn on_community_dissolved(&self, community_id: &str) {
268 self.inner.on_community_dissolved(community_id)
269 }
270}
271
272/// Result of Phase 1 (prepare_event) — everything needed for sequential commit.
273pub enum PreparedEvent {
274 /// Fully processed DM rumor — ready for state commit.
275 Processed {
276 result: RumorProcessingResult,
277 contact: String,
278 sender: PublicKey,
279 is_mine: bool,
280 wrapper_event_id: String,
281 wrapper_event_id_bytes: [u8; 32],
282 wrapper_created_at: u64,
283 /// Time spent on ECDH + ChaCha20Poly1305 decryption (nanoseconds)
284 unwrap_ns: u64,
285 /// Time spent on rumor parsing (nanoseconds)
286 parse_ns: u64,
287 },
288 /// Community invite bundle (kind 3304) — parked for explicit user consent.
289 CommunityInvite {
290 invite: crate::community::invite::CommunityInvite,
291 /// Inviter's npub (bech32) — shown in the pending-invite UI.
292 inviter: String,
293 is_mine: bool,
294 wrapper_event_id_bytes: [u8; 32],
295 wrapper_created_at: u64,
296 /// Inner rumor `created_at` (seconds) — the real send time. Unlike the outer
297 /// wrapper, which NIP-59 backdates up to 2 days, this is honest; the tombstone
298 /// supersession test needs it so a re-invite isn't misread as older than a decline.
299 rumor_created_at: u64,
300 /// Sender-declared NIP-40 expiry (unix secs); 0 = none, so permanent.
301 expires_at: u64,
302 },
303 /// Concord v2 Direct Invite (inner kind 3313) — parked for explicit consent.
304 /// Carries the raw bundle JSON (parked verbatim; the accept path re-parses it).
305 CommunityInviteV2 {
306 bundle_json: String,
307 community_id: String,
308 /// Inviter's npub (hex) — the proven seal signer.
309 inviter: String,
310 is_mine: bool,
311 wrapper_event_id_bytes: [u8; 32],
312 wrapper_created_at: u64,
313 /// Inner rumor `created_at` (seconds) — the real send time (see the v1 variant).
314 rumor_created_at: u64,
315 /// Sender-declared NIP-40 expiry (unix secs); 0 = none, so permanent.
316 expires_at: u64,
317 },
318 /// Duplicate event — just persist wrapper for negentropy.
319 DedupSkip {
320 wrapper_id_bytes: [u8; 32],
321 wrapper_created_at: u64,
322 },
323 /// Error during unwrap/processing — persist wrapper for negentropy.
324 ErrorSkip {
325 wrapper_id_bytes: [u8; 32],
326 wrapper_created_at: u64,
327 },
328}
329
330/// Phase 1: Prepare an event for commit (parallel-safe, no state mutation).
331///
332/// Performs dedup check, gift wrap decryption, and rumor parsing.
333/// Safe to call from multiple tokio tasks concurrently.
334pub async fn prepare_event(
335 event: Event,
336 _client: &Client,
337 my_public_key: PublicKey,
338) -> PreparedEvent {
339 let wrapper_created_at = event.created_at.as_secs();
340 let wrapper_event_id_bytes: [u8; 32] = event.id.to_bytes();
341 let wrapper_event_id = event.id.to_hex();
342
343 // Dedup: in-memory cache first, then DB fallback
344 {
345 let cache = WRAPPER_ID_CACHE.lock().await;
346 if cache.contains(&wrapper_event_id_bytes) {
347 return PreparedEvent::DedupSkip { wrapper_id_bytes: wrapper_event_id_bytes, wrapper_created_at };
348 }
349 }
350
351 if let Ok(true) = crate::db::events::wrapper_event_exists(&wrapper_event_id) {
352 return PreparedEvent::DedupSkip { wrapper_id_bytes: wrapper_event_id_bytes, wrapper_created_at };
353 }
354
355 // Unwrap gift wrap (CPU-bound ECDH + ChaCha20Poly1305)
356 let unwrap_start = std::time::Instant::now();
357 let signer = match crate::signer::active_signer() {
358 Ok(s) => s,
359 Err(_) => return PreparedEvent::ErrorSkip {
360 wrapper_id_bytes: wrapper_event_id_bytes, wrapper_created_at,
361 },
362 };
363 let (rumor, sender) = match UnwrappedGift::from_gift_wrap_async(&signer, &event).await {
364 Ok(UnwrappedGift { rumor, sender }) => (rumor, sender),
365 Err(_) => return PreparedEvent::ErrorSkip {
366 wrapper_id_bytes: wrapper_event_id_bytes, wrapper_created_at,
367 },
368 };
369
370 let unwrap_ns = unwrap_start.elapsed().as_nanos() as u64;
371
372 // Inner rumor send time (seconds). The outer wrapper's `created_at` is NIP-59
373 // backdated up to 2 days, so it can't order an invite against a decline tombstone.
374 let rumor_created_at = rumor.created_at.as_secs();
375
376 let is_mine = sender == my_public_key;
377 let contact = if is_mine {
378 rumor.tags.public_keys().next()
379 .and_then(|pk| pk.to_bech32().ok())
380 .unwrap_or_else(|| sender.to_bech32().unwrap_or_default())
381 } else {
382 sender.to_bech32().unwrap_or_default()
383 };
384
385 // Skip NIP-17 group messages (multiple p-tags) — Vector DMs are 1:1
386 if rumor.tags.public_keys().count() > 1 {
387 return PreparedEvent::ErrorSkip {
388 wrapper_id_bytes: wrapper_event_id_bytes, wrapper_created_at,
389 };
390 }
391
392 // Community invite (carrier) — a join, not a chat message. Recognized before
393 // process_rumor so it never lands as an UnknownEvent in the DM thread.
394 if rumor.kind == Kind::Custom(crate::stored_event::event_kind::COMMUNITY_INVITE_BUNDLE) {
395 return match crate::community::invite::parse_invite_rumor(rumor.kind, &rumor.content) {
396 Some(invite) => PreparedEvent::CommunityInvite {
397 invite, inviter: contact.clone(), is_mine, wrapper_event_id_bytes, wrapper_created_at, rumor_created_at,
398 expires_at: crate::community::invite::expiration_secs(&rumor.tags).unwrap_or(0),
399 },
400 None => PreparedEvent::ErrorSkip { wrapper_id_bytes: wrapper_event_id_bytes, wrapper_created_at },
401 };
402 }
403
404 // Concord v2 Direct Invite (inner kind 3313) — the v2 join carrier. `from_bundle_json`
405 // validates the owner commitment + bounds; we park the canonical re-serialized bundle.
406 if rumor.kind == Kind::Custom(crate::community::v2::kind::DIRECT_INVITE) {
407 return match crate::community::v2::invite::CommunityInvite::from_bundle_json(&rumor.content)
408 .ok()
409 .and_then(|b| serde_json::to_string(&b).ok().map(|j| (b.community_id, j)))
410 {
411 Some((community_id, bundle_json)) => PreparedEvent::CommunityInviteV2 {
412 community_id,
413 bundle_json,
414 inviter: contact.clone(), // the seal signer's npub (bech32), like the v1 arm
415 is_mine,
416 wrapper_event_id_bytes,
417 wrapper_created_at,
418 rumor_created_at,
419 expires_at: crate::community::invite::expiration_secs(&rumor.tags).unwrap_or(0),
420 },
421 None => PreparedEvent::ErrorSkip { wrapper_id_bytes: wrapper_event_id_bytes, wrapper_created_at },
422 };
423 }
424
425 // Build RumorEvent for processing
426 let Some(rumor_id) = rumor.id else {
427 return PreparedEvent::ErrorSkip {
428 wrapper_id_bytes: wrapper_event_id_bytes, wrapper_created_at,
429 };
430 };
431
432 let rumor_event = RumorEvent {
433 id: rumor_id,
434 kind: rumor.kind,
435 content: rumor.content,
436 tags: rumor.tags,
437 created_at: rumor.created_at,
438 pubkey: rumor.pubkey,
439 };
440 let rumor_context = RumorContext {
441 sender,
442 is_mine,
443 conversation_id: contact.clone(),
444 conversation_type: ConversationType::DirectMessage,
445 };
446
447 let parse_start = std::time::Instant::now();
448 let download_dir = crate::db::get_download_dir();
449 match process_rumor(rumor_event, rumor_context, &download_dir) {
450 Ok(result) => {
451 let parse_ns = parse_start.elapsed().as_nanos() as u64;
452 PreparedEvent::Processed {
453 result, contact, sender, is_mine,
454 wrapper_event_id, wrapper_event_id_bytes, wrapper_created_at,
455 unwrap_ns, parse_ns,
456 }
457 }
458 Err(e) => {
459 log_warn!("[EventHandler] Failed to process rumor: {}", e);
460 PreparedEvent::ErrorSkip {
461 wrapper_id_bytes: wrapper_event_id_bytes, wrapper_created_at,
462 }
463 }
464 }
465}
466
467// ============================================================================
468// Phase 2: Commit — sequential state mutation, DB save, emit
469// ============================================================================
470
471/// Phase 2: commit a prepared event (sequential — not parallel-safe).
472/// Saves to DB, updates STATE, emits to frontend, calls handler hooks.
473/// Returns true if a new displayable message was committed.
474///
475/// Session-safety: captures the generation at the first line. If a swap
476/// occurred between `prepare_event()` and here (e.g. long-running
477/// negentropy fetch queued events for commit), bail before any STATE /
478/// DB write. Centralized so individual spawn sites (sync.rs fetch_messages,
479/// archive task, sync_dms, subscription_handler) don't have to wrap.
480/// Direct Invites live 24 hours BY DESIGN, and the RECIPIENT enforces it: a
481/// sender that omits the NIP-40 tag (older clients, other implementations)
482/// must not mint a permanent invite, and an archive sync that resurrects a
483/// months-old wrap must not park a ghost (a re-founded community's stale
484/// invite has no held id for the exists-guard to match). The sender's
485/// declared deadline is honored when EARLIER; the rumor-age lifetime is the
486/// ceiling either way. One hour of slack absorbs sender clock skew.
487pub const DIRECT_INVITE_LIFETIME_SECS: u64 = 24 * 3600 + 3600;
488
489/// Park the Private-Channel keys a CATCH-UP bundle carries that we don't hold.
490///
491/// This is delivery, never authority: nothing is adopted here. The bundle's
492/// self-certification is checked (a forged community binding never parks), the
493/// keys are stashed, and [`judge_channel_key_vend`] rules on them against our own
494/// fold after the next control follow. A vend that races its Grant therefore
495/// parks quietly instead of being dropped, which is what makes an admin's grant
496/// actually reach a member who is already in the community.
497///
498/// `inviter` is the seal author's npub (bech32) — recorded so the judge can
499/// require an entitled vendor.
500fn park_catch_up_channel_keys(
501 community_id: &str,
502 bundle_json: &str,
503 inviter: &str,
504 session: &crate::state::SessionGuard,
505) {
506 use crate::community::v2::invite::CommunityInvite;
507 let Ok(bundle) = CommunityInvite::from_bundle_json(bundle_json) else { return };
508 // (1) Self-cert: the bundle cannot claim to be this community while naming a
509 // different owner. Cheap, and it keeps garbage out of the park table.
510 let (Some(cid), Some(owner), Some(salt)) = (
511 crate::simd::hex::hex_to_bytes_32_checked(&bundle.community_id),
512 crate::simd::hex::hex_to_bytes_32_checked(&bundle.owner),
513 crate::simd::hex::hex_to_bytes_32_checked(&bundle.owner_salt),
514 ) else {
515 return;
516 };
517 if !crate::community::v2::derive::verify_community_id(&crate::community::CommunityId(cid), &owner, &salt) {
518 log_warn!("[community] catch-up bundle failed self-certification — dropped");
519 return;
520 }
521 let Ok(sender) = PublicKey::parse(inviter) else { return };
522 let sender_hex = sender.to_hex();
523 // The commit path's guard was captured before an await; re-check before the
524 // writes below or a swap mid-commit parks account A's channel key into
525 // account B's database.
526 if !session.is_valid() {
527 return;
528 }
529 let held = crate::db::community::load_community_v2(&crate::community::CommunityId(cid)).ok().flatten();
530 let mut parked_any = false;
531 for grant in &bundle.channels {
532 let Some(chan) = crate::simd::hex::hex_to_bytes_32_checked(&grant.id) else { continue };
533 let Some(key) = crate::simd::hex::hex_to_bytes_32_checked(&grant.key) else { continue };
534 // Only park what we LACK: a key at or below the held epoch is already
535 // superseded, and a public channel's "key" is just the root.
536 if let Some(c) = held.as_ref().and_then(|h| h.channel(&crate::community::ChannelId(chan))) {
537 if !c.private || (c.key.is_some() && grant.epoch <= c.epoch.0) {
538 continue;
539 }
540 }
541 if let Err(e) = crate::db::community::park_channel_key(community_id, &grant.id, grant.epoch, &key, &sender_hex) {
542 log_warn!("[community] parking a vended channel key failed: {e}");
543 continue;
544 }
545 parked_any = true;
546 }
547 // Judge it now rather than whenever the next edition happens by. A vend that
548 // lands AFTER its Grant folded changes no control state, so without a nudge
549 // there is nothing left to trigger the re-judge.
550 if parked_any {
551 crate::community::v2::realtime::enqueue_follow(&crate::community::CommunityId(cid));
552 }
553}
554
555fn expired_invite(expires_at: u64, rumor_created_at: u64) -> bool {
556 let now = nostr_sdk::prelude::Timestamp::now().as_secs();
557 if expires_at != 0 && expires_at <= now {
558 return true;
559 }
560 rumor_created_at.saturating_add(DIRECT_INVITE_LIFETIME_SECS) <= now
561}
562
563#[cfg(test)]
564mod invite_expiry_tests {
565 use super::*;
566
567 fn now() -> u64 {
568 nostr_sdk::prelude::Timestamp::now().as_secs()
569 }
570
571 #[test]
572 fn declared_deadline_is_honored() {
573 assert!(expired_invite(now() - 10, now()));
574 assert!(!expired_invite(now() + 3600, now()));
575 }
576
577 #[test]
578 fn tagless_invites_die_at_the_recipient_lifetime() {
579 // Fresh, no tag: parks.
580 assert!(!expired_invite(0, now() - 3600));
581 // A day-and-slack old, no tag: never parks — the class the archive
582 // recovery resurrected (months-old invite to a re-founded community).
583 assert!(expired_invite(0, now() - DIRECT_INVITE_LIFETIME_SECS));
584 assert!(expired_invite(0, now() - 90 * 24 * 3600));
585 }
586
587 #[test]
588 fn lifetime_caps_a_generous_declared_deadline() {
589 // Sender promised a week — the recipient's 24h ceiling still wins.
590 assert!(expired_invite(now() + 7 * 24 * 3600, now() - DIRECT_INVITE_LIFETIME_SECS));
591 }
592}
593
594pub async fn commit_prepared_event(
595 prepared: PreparedEvent,
596 is_new: bool,
597 handler: &dyn InboundEventHandler,
598) -> bool {
599 let session = crate::state::SessionGuard::capture();
600 if !session.is_valid() {
601 return false;
602 }
603 match prepared {
604 PreparedEvent::Processed { result, contact, sender, is_mine, wrapper_event_id, wrapper_event_id_bytes, wrapper_created_at, .. } => {
605 // Cache wrapper for session dedup
606 {
607 let mut cache = WRAPPER_ID_CACHE.lock().await;
608 cache.insert(wrapper_event_id_bytes);
609 }
610
611 // Blocked check — drop content from blocked contacts (wrapper still ledgered so
612 // the dropped content never re-syncs)
613 if !is_mine {
614 let blocked = {
615 let state = crate::state::STATE.lock().await;
616 state.get_profile(&contact).map_or(false, |p| p.flags.is_blocked())
617 };
618 if blocked {
619 let _ = crate::db::wrappers::save_processed_wrapper(&wrapper_event_id_bytes, wrapper_created_at, crate::db::wrappers::TRANSPORT_NIP17);
620 return false;
621 }
622 }
623
624 // Persist for cross-session dedup + negentropy — EXCEPT message rumors: the
625 // ledger IS the negentropy fingerprint set, and a batching handler may defer the
626 // message's save, so its wrapper must never be ledgered before its row lands (a
627 // ledgered-but-unpersisted message reads as "have" and is never re-delivered).
628 // Message wrappers ledger inside commit_dm_message / the batch-flush transaction.
629 if !matches!(result, RumorProcessingResult::TextMessage(_) | RumorProcessingResult::FileAttachment(_)) {
630 let _ = crate::db::wrappers::save_processed_wrapper(&wrapper_event_id_bytes, wrapper_created_at, crate::db::wrappers::TRANSPORT_NIP17);
631 }
632
633 match result {
634 RumorProcessingResult::TextMessage(mut msg) => {
635 msg.wrapper_event_id = Some(wrapper_event_id.clone());
636 commit_dm_message(msg, &contact, is_mine, is_new, &wrapper_event_id, wrapper_event_id_bytes, wrapper_created_at, handler, false).await
637 }
638 RumorProcessingResult::FileAttachment(mut msg) => {
639 msg.wrapper_event_id = Some(wrapper_event_id.clone());
640 // If the sender's client (e.g. 0xChat) didn't ship `size` in
641 // the imeta tag, probe the URL via Content-Length so the
642 // frontend's auto-download gate has accurate metadata to
643 // decide on.
644 //
645 // Skip for self-echoes (is_mine): we just uploaded these
646 // files, the local Attachment.size is authoritative, and
647 // probing our own blossom URL right after upload is a
648 // correlation-fingerprint privacy regression.
649 //
650 // Each probe is bounded by a 3s outer timeout so a slow or
651 // dead server can't stall the inbound rumor pipeline. If
652 // the probe times out, we ship size=0 and the frontend
653 // falls back to a manual "Click to Download" affordance.
654 if !is_mine {
655 for att in &mut msg.attachments {
656 if att.size == 0
657 && (att.url.starts_with("https://") || att.url.starts_with("http://"))
658 {
659 if let Ok(Some(size)) = tokio::time::timeout(
660 std::time::Duration::from_secs(3),
661 crate::net::get_remote_file_size(&att.url),
662 ).await {
663 att.size = size;
664 }
665 }
666 }
667 }
668 commit_dm_message(msg, &contact, is_mine, is_new, &wrapper_event_id, wrapper_event_id_bytes, wrapper_created_at, handler, true).await
669 }
670 RumorProcessingResult::Reaction(reaction) => {
671 commit_reaction(reaction, &contact, is_mine, &wrapper_event_id, handler).await
672 }
673 RumorProcessingResult::Edit { message_id, new_content, edited_at, emoji_tags, mut event } => {
674 commit_edit(&mut event, &contact, &message_id, &new_content, edited_at, emoji_tags, &wrapper_event_id).await
675 }
676 RumorProcessingResult::TypingIndicator { profile_id, until } => {
677 let active_typers = {
678 let mut state = crate::state::STATE.lock().await;
679 state.update_typing_and_get_active(&contact, &profile_id, until)
680 };
681 crate::traits::emit_event("typing-update", &serde_json::json!({
682 "conversation_id": contact,
683 "typers": active_typers,
684 }));
685 false
686 }
687 RumorProcessingResult::PivxPayment { gift_code, amount_piv, address, message_id, mut event } => {
688 if crate::db::events::event_exists(&event.id).unwrap_or(false) {
689 return false;
690 }
691 event.wrapper_event_id = Some(wrapper_event_id.clone());
692 let ts = event.created_at;
693 let _ = crate::db::events::save_pivx_payment_event(&contact, event).await;
694 crate::traits::emit_event("pivx_payment_received", &serde_json::json!({
695 "conversation_id": contact,
696 "gift_code": gift_code, "amount_piv": amount_piv,
697 "address": address, "message_id": message_id,
698 "sender": sender.to_hex(), "is_mine": is_mine,
699 "at": ts * 1000,
700 }));
701 true
702 }
703 RumorProcessingResult::UnknownEvent(mut event) => {
704 event.wrapper_event_id = Some(wrapper_event_id.clone());
705 // Store unknown events for forward compatibility
706 if let Ok(chat_id) = crate::db::id_cache::get_or_create_chat_id(&contact) {
707 event.chat_id = chat_id;
708 }
709 let _ = crate::db::events::save_event(&event).await;
710 false
711 }
712 RumorProcessingResult::LeaveRequest { .. } => false,
713 RumorProcessingResult::WebxdcPeerAdvertisement { .. } |
714 RumorProcessingResult::WebxdcPeerLeft { .. } => {
715 // WebXDC is platform-specific — handled by src-tauri directly
716 false
717 }
718 RumorProcessingResult::WallpaperChanged {
719 sender_npub, created_at, url, decryption_key, decryption_nonce,
720 plaintext_hash, mime, blur, dim, event_id,
721 } => {
722 let _ = crate::wallpaper::apply_received_wallpaper(
723 &contact, &sender_npub, created_at, &url,
724 &decryption_key, &decryption_nonce,
725 plaintext_hash.as_deref(), mime.as_deref(),
726 blur, dim,
727 &event_id,
728 ).await;
729 // System event is saved inside apply_received_wallpaper.
730 // Return true so the caller treats this as a stored event.
731 true
732 }
733 RumorProcessingResult::DeletionRequest { target_event_id } => {
734 // A deletion targets a message OR a reaction (both event ids,
735 // never colliding). Try the message path; if it's not a known
736 // message, treat it as a reaction revocation.
737 if commit_deletion(&target_event_id, &contact, &sender, handler).await {
738 true
739 } else {
740 commit_reaction_deletion(&target_event_id, &sender).await
741 }
742 }
743 RumorProcessingResult::Ignored => false,
744 }
745 }
746 PreparedEvent::CommunityInvite { invite, inviter, is_mine, wrapper_event_id_bytes, wrapper_created_at, rumor_created_at, expires_at } => {
747 // Negentropy bookkeeping regardless of outcome (the outer wrapper id is
748 // attacker-controlled, so it can't be the join-idempotency key — see below).
749 {
750 let mut cache = WRAPPER_ID_CACHE.lock().await;
751 cache.insert(wrapper_event_id_bytes);
752 }
753 let _ = crate::db::wrappers::save_processed_wrapper(&wrapper_event_id_bytes, wrapper_created_at, crate::db::wrappers::TRANSPORT_NIP17);
754
755 // Never park our own echoed invite.
756 if is_mine {
757 return false;
758 }
759
760 // Past the sender's deadline OR past the recipient-enforced 24h
761 // lifetime (a catch-up sync of a stale wrap, a relay that ignores
762 // expiry, a sender that never set the tag): never park it.
763 if expired_invite(expires_at, rumor_created_at) {
764 return false;
765 }
766
767 // Cap-check before touching the DB (a hostile bundle can declare an
768 // unbounded channel/relay list).
769 if let Err(e) = invite.validate() {
770 log_warn!("[community] invite rejected: {}", e);
771 return false;
772 }
773
774 // Idempotency on the INNER identity (community_id), NOT the wrapper id: a
775 // replayed bundle re-wrapped under fresh ephemeral keys must not re-notify
776 // or churn. If we already hold this Community, or already have it parked,
777 // drop silently.
778 let community_id = invite.community_id.clone();
779 // PUBLIC input: a signature-valid invite can still carry a malformed id, so decode through
780 // the SIMD-validated path (rejects non-hex / wrong length in-register).
781 let already_held = crate::community::CommunityId(
782 match crate::simd::hex::hex_to_bytes_32_checked(&community_id) {
783 Some(b) => b,
784 None => { log_warn!("[community] invite has malformed id"); return false; }
785 },
786 );
787 if crate::db::community::community_exists(&already_held).unwrap_or(false) {
788 return false;
789 }
790 if crate::db::community::pending_invite_exists(&community_id).unwrap_or(false) {
791 return false;
792 }
793
794 // Supersession: a decline/leave tombstone suppresses any invite no newer than the
795 // decision (so the un-deletable 3304 can't re-nag, and a sibling's decline propagated via
796 // the synced list silences this device too). A STRICTLY-newer invite falls through and
797 // parks — a deliberate re-invite resurfaces. Ordered on the inner rumor time, not the
798 // NIP-59-backdated wrapper (which would make a fresh re-invite look older than the decline).
799 if crate::community::list::tombstone_suppresses(&community_id, rumor_created_at) {
800 return false;
801 }
802
803 // Park for explicit consent — do NOT join, subscribe, or dial the bundle's
804 // relays here. The user accepts via the command layer.
805 let bundle_json = match invite.to_json() {
806 Ok(j) => j,
807 Err(e) => { log_warn!("[community] invite re-serialize failed: {}", e); return false; }
808 };
809 match crate::db::community::save_pending_invite(&community_id, &bundle_json, &inviter, expires_at as i64) {
810 Ok(true) => {
811 handler.on_community_invite(&community_id);
812 // Warm the community's first page in the background so a subsequent Accept opens
813 // populated instead of paying the join sync. RAM-only + best-effort; promotion on
814 // Join re-validates freshness. SessionGuard'd so a mid-flight swap is a no-op.
815 let invite_warm = invite.clone();
816 let bg = crate::state::SessionGuard::capture();
817 tokio::spawn(async move {
818 if !bg.is_valid() {
819 return;
820 }
821 crate::community::service::preload_community(&invite_warm).await;
822 });
823 }
824 Ok(false) => {} // raced — already parked
825 Err(e) => log_warn!("[community] invite park failed: {}", e),
826 }
827 false
828 }
829 PreparedEvent::CommunityInviteV2 { bundle_json, community_id, inviter, is_mine, wrapper_event_id_bytes, wrapper_created_at, rumor_created_at, expires_at } => {
830 {
831 let mut cache = WRAPPER_ID_CACHE.lock().await;
832 cache.insert(wrapper_event_id_bytes);
833 }
834 let _ = crate::db::wrappers::save_processed_wrapper(&wrapper_event_id_bytes, wrapper_created_at, crate::db::wrappers::TRANSPORT_NIP17);
835
836 // Never park our own echoed invite.
837 if is_mine {
838 return false;
839 }
840 // Past the sender's deadline or the 24h lifetime — see the v1 arm.
841 if expired_invite(expires_at, rumor_created_at) {
842 return false;
843 }
844 // Idempotency on the INNER community_id (already validated hex), not the
845 // attacker-controlled wrapper id: already held, or already parked → drop.
846 let held = match crate::simd::hex::hex_to_bytes_32_checked(&community_id) {
847 Some(b) => crate::community::CommunityId(b),
848 None => return false,
849 };
850 // Already a member? Then this is not an invitation but a CATCH-UP: a
851 // grant's Private-Channel key vend (CORD-03 "delivered on grant"), or
852 // an admin healing us forward. Park the keys we lack for the judge to
853 // rule on after the next control fold — dropping it here is why a
854 // granted member (or bot) stayed silently keyless.
855 if crate::db::community::community_exists(&held).unwrap_or(false) {
856 park_catch_up_channel_keys(&community_id, &bundle_json, &inviter, &session);
857 return false;
858 }
859 if crate::db::community::pending_invite_exists(&community_id).unwrap_or(false) {
860 return false;
861 }
862 // Supersession: a decline/leave tombstone (protocol-agnostic, keyed on
863 // community_id) suppresses a re-wrapped invite no newer than the decision,
864 // so a declined/left community can't be re-nagged by a fresh ephemeral wrap.
865 // Ordered on the inner rumor time, not the NIP-59-backdated wrapper.
866 if crate::community::list::tombstone_suppresses(&community_id, rumor_created_at) {
867 return false;
868 }
869 // Park for explicit consent — do NOT join/subscribe here. Accept via the command layer.
870 match crate::db::community::save_pending_invite(&community_id, &bundle_json, &inviter, expires_at as i64) {
871 Ok(true) => handler.on_community_invite(&community_id),
872 Ok(false) => {} // raced — already parked
873 Err(e) => log_warn!("[community] v2 invite park failed: {}", e),
874 }
875 false
876 }
877 PreparedEvent::DedupSkip { wrapper_id_bytes, wrapper_created_at } => {
878 // Persist wrapper timestamp for negentropy backfill (skip no-op writes).
879 // Guarded: a cache-hit skip can name a wrapper whose message is still sitting in
880 // a batch buffer (deferred ledger) — inserting it here would mark the message
881 // "have" before its row exists. Only touch the ledger when the wrapper is
882 // already ledgered (timestamp backfill) or its row is verifiably persisted
883 // (legacy pre-ledger events, whose wrapper lives only on the events row).
884 if wrapper_created_at > 0 {
885 if crate::db::wrappers::processed_wrapper_exists(&wrapper_id_bytes) {
886 let _ = crate::db::wrappers::update_wrapper_timestamp(&wrapper_id_bytes, wrapper_created_at);
887 } else {
888 let wrapper_hex = crate::simd::hex::bytes_to_hex_32(&wrapper_id_bytes);
889 if crate::db::events::wrapper_event_exists(&wrapper_hex).unwrap_or(false) {
890 let _ = crate::db::wrappers::save_processed_wrapper(&wrapper_id_bytes, wrapper_created_at, crate::db::wrappers::TRANSPORT_NIP17);
891 }
892 }
893 }
894 false
895 }
896 PreparedEvent::ErrorSkip { wrapper_id_bytes, wrapper_created_at } => {
897 let _ = crate::db::wrappers::save_processed_wrapper(&wrapper_id_bytes, wrapper_created_at, crate::db::wrappers::TRANSPORT_NIP17);
898 false
899 }
900 }
901}
902
903/// Commit a DM text or file message (shared logic for both).
904///
905/// Owns this message's wrapper-ledger write (`processed_wrappers` = the negentropy
906/// fingerprint set): the wrapper is ledgered only once the message row is durably handled —
907/// immediately after a successful save, inside the batch-flush transaction when a handler
908/// defers, or right away when the message is a known duplicate. An unledgered wrapper is
909/// re-delivered by the next reconciliation, which is what makes a dropped batch recoverable.
910#[allow(clippy::too_many_arguments)]
911async fn commit_dm_message(
912 mut msg: Message,
913 contact: &str,
914 _is_mine: bool,
915 is_new: bool,
916 wrapper_event_id: &str,
917 wrapper_event_id_bytes: [u8; 32],
918 wrapper_created_at: u64,
919 handler: &dyn InboundEventHandler,
920 is_file: bool,
921) -> bool {
922 let ledger_wrapper = || {
923 let _ = crate::db::wrappers::save_processed_wrapper(
924 &wrapper_event_id_bytes, wrapper_created_at, crate::db::wrappers::TRANSPORT_NIP17,
925 );
926 };
927 // Dedup: check if message already in DB
928 if let Ok(true) = crate::db::events::message_exists_in_db(&msg.id) {
929 // Already in DB — try to backfill wrapper_event_id
930 if let Ok(updated) = crate::db::events::update_wrapper_event_id(&msg.id, wrapper_event_id) {
931 if !updated {
932 let mut cache = WRAPPER_ID_CACHE.lock().await;
933 cache.insert(wrapper_event_id_bytes);
934 }
935 }
936 ledger_wrapper();
937 return false;
938 }
939
940 // Populate reply context
941 if !msg.replied_to.is_empty() {
942 let _ = crate::db::events::populate_reply_context(&mut msg).await;
943 }
944
945 // Add to STATE (+ clear typing indicator for file senders)
946 let added = {
947 let mut state = crate::state::STATE.lock().await;
948 let added = state.add_message_to_participant(contact, &msg);
949 if is_file && added {
950 state.update_typing_and_get_active(contact, contact, 0);
951 }
952 added
953 };
954
955 if added {
956 // Emit to frontend
957 crate::traits::emit_event("message_new", &serde_json::json!({
958 "message": &msg,
959 "chat_id": contact
960 }));
961
962 // Platform callback (notifications, badge, etc.)
963 if is_file {
964 handler.on_file_received(contact, &msg, is_new);
965 } else {
966 handler.on_dm_received(contact, &msg, is_new);
967 }
968
969 // Save to DB — unless a bulk-sync handler owns batched persistence (the handler then
970 // also owns the wrapper-ledger write, inside its flush transaction). On the immediate
971 // path the wrapper ledgers only after a successful save: a failed save left unledgered
972 // re-delivers on the next reconciliation instead of being lost.
973 if !handler.buffer_persist(contact, &msg, Some((wrapper_event_id_bytes, wrapper_created_at))) {
974 if crate::db::events::save_message(contact, &msg).await.is_ok() {
975 ledger_wrapper();
976 }
977 }
978 } else {
979 // STATE-level duplicate: a same-session twin owns the row; this wrapper carried
980 // nothing new, so ledger it now (parity with the old eager ledger).
981 ledger_wrapper();
982 }
983
984 added
985}
986
987/// Commit a reaction event.
988async fn commit_reaction(
989 reaction: crate::types::Reaction,
990 contact: &str,
991 is_mine: bool,
992 wrapper_event_id: &str,
993 handler: &dyn InboundEventHandler,
994) -> bool {
995 // Add to STATE
996 let msg_for_emit = {
997 let mut state = crate::state::STATE.lock().await;
998 if let Some((chat_id, was_added)) = state.add_reaction_to_message(&reaction.reference_id, reaction.clone()) {
999 if was_added {
1000 state.find_message(&reaction.reference_id)
1001 .map(|(_, msg)| (chat_id, msg))
1002 } else { None }
1003 } else { None }
1004 };
1005
1006 if let Some((chat_id, mut msg)) = msg_for_emit {
1007 crate::traits::emit_message_update(&chat_id, &reaction.reference_id, &mut msg).await;
1008 let _ = crate::db::events::save_message(&chat_id, &msg).await;
1009 handler.on_reaction_received(&chat_id, &msg);
1010 }
1011
1012 // Always save reaction event with wrapper for dedup
1013 if let Ok(chat_id) = crate::db::id_cache::get_chat_id_by_identifier(contact) {
1014 let _ = crate::db::events::save_reaction_event(
1015 &reaction, chat_id, None, is_mine, Some(wrapper_event_id.to_string())
1016 ).await;
1017 }
1018
1019 true
1020}
1021
1022/// Commit a message edit.
1023async fn commit_edit(
1024 event: &mut crate::stored_event::StoredEvent,
1025 contact: &str,
1026 message_id: &str,
1027 new_content: &str,
1028 edited_at: u64,
1029 emoji_tags: Vec<crate::types::EmojiTag>,
1030 wrapper_event_id: &str,
1031) -> bool {
1032 if crate::db::events::event_exists(&event.id).unwrap_or(false) {
1033 return false;
1034 }
1035 if let Ok(chat_id) = crate::db::id_cache::get_chat_id_by_identifier(contact) {
1036 event.chat_id = chat_id;
1037 }
1038 event.wrapper_event_id = Some(wrapper_event_id.to_string());
1039 let _ = crate::db::events::save_event(event).await;
1040
1041 let msg_for_emit = {
1042 let mut state = crate::state::STATE.lock().await;
1043 state.update_message_in_chat(contact, message_id, |msg| {
1044 msg.apply_edit(new_content.to_string(), edited_at, emoji_tags.clone());
1045 })
1046 };
1047 if let Some(mut msg) = msg_for_emit {
1048 crate::traits::emit_message_update(contact, message_id, &mut msg).await;
1049 }
1050 true
1051}
1052
1053/// Commit a NIP-09 cooperative deletion request.
1054///
1055/// Authorization: only the original message's author can delete it
1056/// (matches NIP-09's `event.pubkey == deletion.pubkey` rule applied to
1057/// the inner rumor). For DMs, that means either the sender is `MY` (we
1058/// deleted from another device) or the sender is the chat counterpart
1059/// who originally sent that message. Anyone else's deletion is silently
1060/// ignored.
1061///
1062/// On success: drops the message from in-memory STATE, removes the row
1063/// from the events table, and emits `message_removed` so the frontend
1064/// can fade the row out — same code path as failed-message cleanup.
1065async fn commit_deletion(
1066 target_event_id: &str,
1067 contact: &str,
1068 sender: &PublicKey,
1069 handler: &dyn InboundEventHandler,
1070) -> bool {
1071 // Look up the original. If not present locally there's nothing to
1072 // delete — the deletion notice arrived before the original (rare),
1073 // or we never had it. Either way, no-op.
1074 //
1075 // KNOWN LIMITATION: late-binding deletions are not handled. If
1076 // the deletion arrives BEFORE the original (cold sync, out-of-order
1077 // relay delivery), we drop the deletion silently here, and when the
1078 // original arrives later it shows up unhidden. A future enhancement
1079 // would persist a `pending_deletions` table keyed by target id and
1080 // apply queued deletions when the target is committed in
1081 // commit_dm_message. The common case (deletion arrives after the
1082 // original) works correctly today.
1083 //
1084 // For DM rumors the `npub` field is intentionally empty: the chat
1085 // is between two parties, so the author is implicit from `mine`
1086 // (me if true, chat counterpart if false). We derive the original
1087 // author from that, since the rumor pubkey isn't stored.
1088 let (mine, chat_id) = {
1089 let state = crate::state::STATE.lock().await;
1090 match state.find_message(target_event_id) {
1091 Some((chat, msg)) => (msg.mine, chat.id.clone()),
1092 None => return false,
1093 }
1094 };
1095
1096 // Authorization: deletion sender must match the original author.
1097 // For DMs:
1098 // - mine == true: original author == us (MY_PUBLIC_KEY).
1099 // Authorized if the deletion sender is also us
1100 // (i.e. came in via our own self-wrap from
1101 // another device, multi-device sync).
1102 // - mine == false: original author == chat counterpart. Chat id
1103 // for a DM is the counterpart's npub, so we
1104 // parse it and compare against the deletion
1105 // sender.
1106 let authorized = if mine {
1107 match crate::state::my_public_key() {
1108 Some(my_pk) => *sender == my_pk,
1109 None => false,
1110 }
1111 } else {
1112 match nostr_sdk::prelude::PublicKey::from_bech32(&chat_id) {
1113 Ok(counterpart) => sender == &counterpart,
1114 Err(_) => false, // chat id wasn't an npub (shouldn't happen for DMs)
1115 }
1116 };
1117 if !authorized {
1118 eprintln!(
1119 "[NIP-17 cooperative-delete] unauthorized: sender {} not the author of target {} (mine={}, chat={})",
1120 sender.to_hex(), target_event_id, mine, chat_id
1121 );
1122 return false;
1123 }
1124
1125 // Drop from in-memory state.
1126 let removed = {
1127 let mut state = crate::state::STATE.lock().await;
1128 state.remove_message(target_event_id)
1129 };
1130 let removed_msg = match removed {
1131 Some((_chat_id, msg)) => msg,
1132 None => return false,
1133 };
1134 // Tombstone BEFORE the row delete: the target may sit unflushed in a sync batch buffer
1135 // (delete_event below would no-op) — the flush consults this and drops it.
1136 crate::state::note_message_deleted(target_event_id);
1137
1138 // Nuke any cached attachment files for this message — sender asked
1139 // for the message to disappear, and a downloaded file the receiver
1140 // never moved out of Vector's cache should go with it.
1141 //
1142 // Refcount filter: drop attachments still referenced by sibling
1143 // messages so we don't yank a cached file from messages that
1144 // still need it (Vector dedupes by SHA-256, so the same file
1145 // can back multiple messages). User-managed paths are also left
1146 // alone (canonicalize + starts_with check).
1147 let unique = crate::deletion::filter_unreferenced_attachments(
1148 target_event_id,
1149 removed_msg.attachments,
1150 ).await;
1151 crate::deletion::delete_cached_attachment_files_pub(&unique);
1152
1153 // Drop from the events table.
1154 if let Err(e) = crate::db::events::delete_event(target_event_id).await {
1155 eprintln!(
1156 "[NIP-17 cooperative-delete] DB delete failed for {}: {}",
1157 target_event_id, e
1158 );
1159 }
1160
1161 // Tell the frontend to fade the row out. Reuses the existing
1162 // message_removed event handled in main.js, so no new wiring.
1163 crate::traits::emit_event(
1164 "message_removed",
1165 &serde_json::json!({
1166 "id": target_event_id,
1167 "chat_id": &chat_id,
1168 "reason": "deleted-by-sender",
1169 }),
1170 );
1171
1172 handler.on_message_deleted(&chat_id, target_event_id);
1173 let _ = contact;
1174 true
1175}
1176
1177/// Apply a cooperative reaction revocation (NIP-09 k=7) from the reaction's
1178/// author. Removes the reaction from its parent message and drops the kind-7
1179/// row, then live-refreshes the parent's chips. Returns false if we don't hold
1180/// the reaction or the sender isn't its author.
1181async fn commit_reaction_deletion(target_reaction_id: &str, sender: &PublicKey) -> bool {
1182 let found = {
1183 let state = crate::state::STATE.lock().await;
1184 state.find_reaction(target_reaction_id)
1185 };
1186 let (chat_id, message_id, author_npub, _is_community) = match found {
1187 Some(v) => v,
1188 None => return false,
1189 };
1190
1191 // Authorization: only the reaction's own author may revoke it.
1192 let authorized = nostr_sdk::prelude::PublicKey::parse(&author_npub)
1193 .map(|pk| pk == *sender)
1194 .unwrap_or(false);
1195 if !authorized {
1196 eprintln!(
1197 "[reaction-delete] unauthorized: sender {} is not the author of reaction {}",
1198 sender.to_hex(), target_reaction_id
1199 );
1200 return false;
1201 }
1202
1203 let updated = {
1204 let mut state = crate::state::STATE.lock().await;
1205 state.remove_reaction_from_message(&message_id, target_reaction_id)
1206 };
1207 let mut message = match updated {
1208 Some((_cid, msg)) => msg,
1209 None => return false,
1210 };
1211
1212 // save_message is additive for reactions, so the kind-7 row must be
1213 // dropped explicitly or it resurrects on reload.
1214 if let Err(e) = crate::db::events::delete_event(target_reaction_id).await {
1215 eprintln!("[reaction-delete] DB delete failed for {}: {}", target_reaction_id, e);
1216 }
1217
1218 crate::traits::emit_message_update(&chat_id, &message_id, &mut message).await;
1219 true
1220}
1221
1222// ============================================================================
1223// Convenience: single-call event processing
1224// ============================================================================
1225
1226/// Process a single event through the full pipeline (prepare + commit).
1227///
1228/// Gets client and public key from globals. For callers that manage their
1229/// own notification loop but want the full vector-core processing pipeline.
1230pub async fn process_event(
1231 event: Event,
1232 is_new: bool,
1233 handler: &dyn InboundEventHandler,
1234) -> std::result::Result<bool, String> {
1235 let client = crate::state::nostr_client()
1236 .ok_or_else(|| "Nostr client not initialized".to_string())?;
1237 let my_pk = crate::state::my_public_key()
1238 .ok_or_else(|| "Public key not initialized".to_string())?;
1239 let prepared = prepare_event(event, &client, my_pk).await;
1240 Ok(commit_prepared_event(prepared, is_new, handler).await)
1241}