1use crate::tags::TagsExt;
28use std::path::Path;
29use nostr_sdk::prelude::*;
30use crate::types::{Message, Attachment, ImageMetadata, Reaction, is_renderable_reaction};
31use crate::stored_event::{StoredEvent, StoredEventBuilder, event_kind};
32use crate::crypto::{extension_from_mime, sanitize_filename};
33
34#[derive(Debug, Clone)]
36pub struct RumorEvent {
37 pub id: EventId,
38 pub kind: Kind,
39 pub content: String,
40 pub tags: Tags,
41 pub created_at: Timestamp,
42 pub pubkey: PublicKey,
43}
44
45#[derive(Debug, Clone)]
50pub struct RumorContext {
51 pub sender: PublicKey,
53 pub is_mine: bool,
55 pub conversation_id: String,
57 pub conversation_type: ConversationType,
59}
60
61#[derive(Debug, Clone, PartialEq)]
64pub enum ConversationType {
65 DirectMessage,
67 Community,
69}
70
71impl RumorContext {
72 pub fn author_npub(&self, author: &PublicKey) -> Option<String> {
75 match self.conversation_type {
76 ConversationType::Community => author.to_bech32().ok(),
77 ConversationType::DirectMessage => None,
78 }
79 }
80}
81
82#[derive(Debug, Clone)]
88pub enum RumorProcessingResult {
89 TextMessage(Message),
91 FileAttachment(Message),
93 Reaction(Reaction),
95 TypingIndicator {
97 profile_id: String,
98 until: u64,
99 },
100 LeaveRequest {
102 event_id: String,
104 member_pubkey: String,
106 },
107 WebxdcPeerAdvertisement {
109 event_id: String,
110 topic_id: String,
111 node_addr: String,
112 sender_npub: String,
113 created_at: u64,
114 },
115 WebxdcPeerLeft {
117 event_id: String,
118 topic_id: String,
119 sender_npub: String,
120 created_at: u64,
121 },
122 CallSignal {
124 event_id: String,
125 call_id: String,
126 signal: String,
127 node_addr: Option<String>,
128 sender_npub: String,
129 created_at: u64,
130 video: Option<String>,
132 media: Option<String>,
134 },
135 UnknownEvent(StoredEvent),
138 PivxPayment {
140 gift_code: String,
142 amount_piv: f64,
144 address: Option<String>,
146 message_id: String,
148 event: StoredEvent,
150 },
151 WallpaperChanged {
156 sender_npub: String,
158 created_at: u64,
160 url: String,
162 decryption_key: String,
164 decryption_nonce: String,
166 plaintext_hash: Option<String>,
168 mime: Option<String>,
170 blur: Option<u8>,
172 dim: Option<u8>,
174 event_id: String,
176 },
177 Ignored,
179 DeletionRequest {
184 target_event_id: String,
186 },
187 Edit {
189 message_id: String,
191 new_content: String,
193 edited_at: u64,
195 emoji_tags: Vec<crate::types::EmojiTag>,
197 text_spans: Vec<crate::text_spans::TextSpan>,
199 event: StoredEvent,
201 },
202}
203
204pub fn process_rumor(
221 rumor: RumorEvent,
222 context: RumorContext,
223 download_dir: &Path,
224) -> Result<RumorProcessingResult, String> {
225 if rumor.kind != Kind::EventDeletion && already_expired(extract_nip40_expiration(&rumor)) {
228 return Ok(RumorProcessingResult::Ignored);
229 }
230 match rumor.kind {
231 Kind::PrivateDirectMessage => {
233 process_text_message(rumor, context, download_dir)
234 }
235 k if k.as_u16() == 15 => {
237 process_file_attachment(rumor, context, download_dir)
238 }
239 k if k.as_u16() == event_kind::MESSAGE_EDIT => {
241 process_edit_event(rumor, context)
242 }
243 Kind::Reaction => {
245 process_reaction(rumor, context)
246 }
247 Kind::ApplicationSpecificData => {
249 process_app_specific(rumor, context)
250 }
251 Kind::EventDeletion => {
258 process_deletion(rumor, context)
259 }
260 _ => {
262 process_unknown_event(rumor, context)
263 }
264 }
265}
266
267fn process_unknown_event(
272 rumor: RumorEvent,
273 context: RumorContext,
274) -> Result<RumorProcessingResult, String> {
275 let tags: Vec<Vec<String>> = rumor.tags.iter()
277 .map(|tag| {
278 tag.as_slice().iter().map(|s| s.to_string()).collect()
279 })
280 .collect();
281
282 let reference_id = rumor.tags
284 .find_kind("e")
285 .and_then(|tag| tag.content())
286 .map(|s| s.to_string());
287
288 let event = StoredEventBuilder::new()
289 .id(rumor.id.to_hex())
290 .kind(rumor.kind.as_u16())
291 .content(rumor.content)
292 .tags(tags)
293 .reference_id(reference_id)
294 .created_at(rumor.created_at.as_secs())
295 .mine(context.is_mine)
296 .npub(rumor.pubkey.to_bech32().ok())
297 .build();
298
299 Ok(RumorProcessingResult::UnknownEvent(event))
300}
301
302fn process_text_message(
307 rumor: RumorEvent,
308 context: RumorContext,
309 download_dir: &Path,
310) -> Result<RumorProcessingResult, String> {
311 let replied_to = extract_reply_reference(&rumor);
313
314 let ms_timestamp = extract_millisecond_timestamp(&rumor);
316
317 let emoji_tags = crate::types::EmojiTag::extract_from_tags(rumor.tags.iter());
318 let addressed_bots = crate::bot_interface::addressed_bots(rumor.tags.iter());
319 let npub = context.author_npub(&rumor.pubkey);
321
322 let expiration = extract_nip40_expiration(&rumor);
324 let attachments = crate::community::attachments::attachments_from_tags(rumor.tags.iter(), download_dir);
332 let content = crate::community::attachments::strip_attachment_urls(&rumor.content, &attachments);
335 let text_spans = if content == rumor.content {
337 crate::text_spans::from_tags(rumor.tags.iter(), &content)
338 } else {
339 Vec::new()
340 };
341
342 let msg = Message {
343 expiration,
344 id: rumor.id.to_hex(),
345 content,
346 replied_to,
347 replied_to_content: None, replied_to_npub: None,
349 replied_to_has_attachment: None,
350 replied_to_attachment_extension: None,
351 replied_to_emoji_tags: None,
352 preview_metadata: None,
353 at: ms_timestamp,
354 attachments,
355 reactions: Vec::new(),
356 mine: context.is_mine,
357 pending: false,
358 failed: false,
359 npub,
360 wrapper_event_id: None, edited: false,
362 edit_history: None,
363 emoji_tags,
364 addressed_bots,
365 text_spans,
366 role_mentions: crate::community::mentions::from_tags(rumor.tags.iter()),
367 writer: false,
368 unauthorized: false,
369 };
370
371 Ok(RumorProcessingResult::TextMessage(msg))
372}
373
374pub fn extract_hash_from_blossom_url(url: &str) -> Option<String> {
378 let path = url.split('/').next_back()?;
379 let hash_part = path.split('.').next()?;
380 if hash_part.len() == 64 && hash_part.chars().all(|c| c.is_ascii_hexdigit()) {
381 Some(hash_part.to_string())
382 } else {
383 None
384 }
385}
386
387fn process_file_attachment(
395 rumor: RumorEvent,
396 context: RumorContext,
397 download_dir: &Path,
398) -> Result<RumorProcessingResult, String> {
399 let decryption_key = rumor.tags
404 .find_kind("decryption-key")
405 .and_then(|tag| tag.content())
406 .unwrap_or_default()
407 .to_string();
408
409 let decryption_nonce = if decryption_key.is_empty() {
410 String::new()
411 } else {
412 rumor.tags
413 .find_kind("decryption-nonce")
414 .and_then(|tag| tag.content())
415 .ok_or("Missing decryption-nonce tag")?
416 .to_string()
417 };
418
419 let original_file_hash = rumor.tags
421 .find_kind("ox")
422 .and_then(|tag| tag.content())
423 .map(|s| s.to_string());
424
425 let content_url = rumor.content.clone();
427
428 const EMPTY_FILE_HASH: &str = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
430 if content_url.contains(EMPTY_FILE_HASH) {
431 eprintln!("Skipping attachment with empty file hash in URL: {}", content_url);
432 return Err("Attachment contains empty file hash - skipping".to_string());
433 }
434
435 let img_meta: Option<ImageMetadata> = {
437 let thumbhash_opt = rumor.tags
442 .find_kind("thumbhash")
443 .or_else(|| rumor.tags.find_kind("thumb"))
444 .and_then(|tag| tag.content())
445 .map(|s| s.to_string());
446
447 let dimensions_opt = rumor.tags
448 .find_kind("dim")
449 .and_then(|tag| tag.content())
450 .and_then(|s| {
451 let parts: Vec<&str> = s.split('x').collect();
452 if parts.len() == 2 {
453 let width = parts[0].parse::<u32>().ok()?;
454 let height = parts[1].parse::<u32>().ok()?;
455 Some((width, height))
456 } else {
457 None
458 }
459 });
460
461 match (thumbhash_opt, dimensions_opt) {
462 (Some(thumbhash), Some((width, height))) => {
463 Some(ImageMetadata {
464 thumbhash,
465 width,
466 height,
467 })
468 },
469 _ => None
470 }
471 };
472
473 let mime_type = rumor.tags
475 .find_kind("file-type")
476 .and_then(|tag| tag.content())
477 .ok_or("Missing file-type tag")?;
478 let mime_extension = extension_from_mime(mime_type);
479
480 let file_name = rumor.tags
482 .find_kind("name")
483 .and_then(|tag| tag.content())
484 .map(sanitize_filename)
485 .unwrap_or_default();
486
487 let extension = if !file_name.is_empty() {
490 file_name.rsplit('.').next()
491 .filter(|e| !e.is_empty() && *e != file_name)
492 .map(|e| e.to_lowercase())
493 .unwrap_or(mime_extension)
494 } else {
495 mime_extension
496 };
497
498 let reported_size = rumor.tags
500 .find_kind("size")
501 .and_then(|tag| tag.content())
502 .and_then(|s| s.parse::<u64>().ok())
503 .unwrap_or(0);
504
505 let valid_path_basis =
512 |s: &str| !s.is_empty() && s.len() <= 128 && s.bytes().all(|b| b.is_ascii_hexdigit());
513 let original_file_hash = original_file_hash.filter(|h| valid_path_basis(h));
514 if !decryption_key.is_empty() && !valid_path_basis(&decryption_nonce) {
517 return Err("Invalid decryption-nonce tag".to_string());
518 }
519 let file_hash = crate::crypto::attachment_identity_basis(
520 original_file_hash.as_deref(),
521 &decryption_nonce,
522 &content_url,
523 );
524 let hash_file_path = download_dir.join(format!("{}.{}", file_hash, extension));
525 let downloaded = false;
530 let file_path = hash_file_path.to_string_lossy().to_string();
531
532 let replied_to = extract_reply_reference(&rumor);
534
535 let ms_timestamp = extract_millisecond_timestamp(&rumor);
537
538 let webxdc_topic = rumor.tags
542 .find_kind("webxdc-topic")
543 .and_then(|tag| tag.content())
544 .filter(|t| t.len() == 52 && t.bytes().all(|b| b.is_ascii_uppercase() || (b'2'..=b'7').contains(&b)))
545 .map(|s| s.to_string());
546
547 let mut fallback_urls: Vec<String> = Vec::new();
551 for tag in rumor.tags.iter() {
552 let parts = tag.as_slice();
553 if parts.first().map(String::as_str) != Some("fallback") {
554 continue;
555 }
556 let Some(u) = parts.get(1) else { continue };
557 if !u.starts_with("https://")
558 || u.contains(char::is_whitespace)
559 || *u == content_url
560 || fallback_urls.contains(u)
561 {
562 continue;
563 }
564 fallback_urls.push(u.clone());
565 if fallback_urls.len() >= 4 {
566 break;
567 }
568 }
569
570 let attachment = Attachment {
572 id: file_hash.clone(),
573 key: decryption_key,
574 nonce: decryption_nonce,
575 extension: extension.to_string(),
576 name: file_name,
577 url: content_url,
578 path: file_path,
579 size: reported_size,
580 img_meta,
581 downloading: false,
582 downloaded,
583 verified: false, resident: false,
584 webxdc_topic,
585 group_id: None, original_hash: original_file_hash, fallback_urls,
588 };
589
590 let emoji_tags = crate::types::EmojiTag::extract_from_tags(rumor.tags.iter());
591 let npub = context.author_npub(&rumor.pubkey);
593
594 let expiration = extract_nip40_expiration(&rumor);
596 let msg = Message {
597 expiration,
598 id: rumor.id.to_hex(),
599 content: String::new(),
600 replied_to,
601 replied_to_content: None, replied_to_npub: None,
603 replied_to_has_attachment: None,
604 replied_to_attachment_extension: None,
605 replied_to_emoji_tags: None,
606 preview_metadata: None,
607 at: ms_timestamp,
608 attachments: vec![attachment],
609 reactions: Vec::new(),
610 mine: context.is_mine,
611 pending: false,
612 failed: false,
613 npub,
614 wrapper_event_id: None, edited: false,
616 edit_history: None,
617 emoji_tags,
618 addressed_bots: crate::bot_interface::addressed_bots(rumor.tags.iter()),
619 text_spans: Vec::new(),
620 role_mentions: Vec::new(),
621 writer: false,
622 unauthorized: false,
623 };
624
625 Ok(RumorProcessingResult::FileAttachment(msg))
626}
627
628fn unique_event_ref(rumor: &RumorEvent) -> Option<String> {
638 let mut matches = rumor.tags.iter().filter(|t| t.kind() == "e");
639 let first = matches.next()?;
640 if matches.next().is_some() {
641 return None;
642 }
643 first.content().map(|s| s.to_string())
644}
645
646fn extract_nip40_expiration(rumor: &RumorEvent) -> Option<u64> {
649 rumor.tags.iter().find_map(|tag| {
650 let s = tag.as_slice();
651 if s.len() >= 2 && s[0] == "expiration" {
652 s[1].parse::<u64>().ok()
653 } else {
654 None
655 }
656 })
657}
658
659pub(crate) fn already_expired(expiration: Option<u64>) -> bool {
661 match expiration {
662 Some(exp) => exp <= crate::clock::now_secs(),
663 None => false,
664 }
665}
666
667fn process_deletion(
668 rumor: RumorEvent,
669 _context: RumorContext,
670) -> Result<RumorProcessingResult, String> {
671 let target_event_id = unique_event_ref(&rumor)
672 .ok_or("Deletion target tag missing or ambiguous")?;
673 Ok(RumorProcessingResult::DeletionRequest { target_event_id })
674}
675
676fn process_reaction(
680 rumor: RumorEvent,
681 _context: RumorContext,
682) -> Result<RumorProcessingResult, String> {
683 let reference_id = unique_event_ref(&rumor)
684 .ok_or("Reaction reference tag missing or ambiguous")?;
685
686 if !is_renderable_reaction(&rumor.content) {
689 return Ok(RumorProcessingResult::Ignored);
690 }
691
692 let emoji_url = if rumor.content.starts_with(':') && rumor.content.ends_with(':')
695 && rumor.content.len() >= 3
696 {
697 let sc = &rumor.content[1..rumor.content.len() - 1];
698 rumor.tags.iter().find_map(|tag| {
699 let parts: Vec<&str> = tag.as_slice().iter().map(|s| s.as_str()).collect();
700 if parts.len() >= 3 && parts[0] == "emoji" && parts[1] == sc {
701 Some(parts[2].to_string())
702 } else {
703 None
704 }
705 })
706 } else {
707 None
708 };
709
710 let reaction = Reaction {
711 id: rumor.id.to_hex(),
712 reference_id,
713 author_id: rumor.pubkey.to_bech32().unwrap_or_else(|_| rumor.pubkey.to_hex()),
714 emoji: rumor.content,
715 emoji_url,
716 };
717
718 Ok(RumorProcessingResult::Reaction(reaction))
719}
720
721fn process_edit_event(
725 rumor: RumorEvent,
726 context: RumorContext,
727) -> Result<RumorProcessingResult, String> {
728 let message_id = unique_event_ref(&rumor)
729 .ok_or("Edit reference tag missing or ambiguous")?;
730
731 let edited_at = extract_millisecond_timestamp(&rumor);
732
733 let emoji_tags = crate::types::EmojiTag::extract_from_tags(rumor.tags.iter());
736 let text_spans = crate::text_spans::from_tags(rumor.tags.iter(), &rumor.content);
737
738 let tags: Vec<Vec<String>> = rumor.tags.iter()
739 .map(|tag| {
740 tag.as_slice().iter().map(|s| s.to_string()).collect()
741 })
742 .collect();
743
744 let event = StoredEventBuilder::new()
745 .id(rumor.id.to_hex())
746 .kind(event_kind::MESSAGE_EDIT)
747 .content(rumor.content.clone())
748 .tags(tags)
749 .reference_id(Some(message_id.clone()))
750 .created_at(rumor.created_at.as_secs())
751 .mine(context.is_mine)
752 .npub(rumor.pubkey.to_bech32().ok())
753 .build();
754
755 Ok(RumorProcessingResult::Edit {
756 message_id,
757 new_content: rumor.content,
758 edited_at,
759 emoji_tags,
760 text_spans,
761 event,
762 })
763}
764
765fn process_app_specific(
767 rumor: RumorEvent,
768 context: RumorContext,
769) -> Result<RumorProcessingResult, String> {
770 if is_typing_indicator(&rumor) {
772 let expiry_tag = rumor.tags
773 .find_kind("expiration")
774 .ok_or("Typing indicator missing expiration tag")?;
775
776 let expiry_timestamp: u64 = expiry_tag.content()
777 .ok_or("Expiration tag has no content")?
778 .parse()
779 .map_err(|_| "Invalid expiration timestamp")?;
780
781 let current_timestamp = crate::clock::now_secs();
782
783 if expiry_timestamp <= current_timestamp || expiry_timestamp > current_timestamp + 30 {
784 return Ok(RumorProcessingResult::Ignored);
785 }
786
787 let profile_id = rumor.pubkey.to_bech32()
788 .map_err(|e| format!("Failed to convert pubkey to bech32: {}", e))?;
789
790 return Ok(RumorProcessingResult::TypingIndicator {
791 profile_id,
792 until: expiry_timestamp,
793 });
794 }
795
796 if is_leave_request(&rumor) {
798 let member_pubkey = rumor.pubkey.to_bech32()
799 .map_err(|e| format!("Failed to convert pubkey to bech32: {}", e))?;
800
801 return Ok(RumorProcessingResult::LeaveRequest {
802 event_id: rumor.id.to_hex(),
803 member_pubkey,
804 });
805 }
806
807 if is_pivx_payment(&rumor) {
809 let gift_code = rumor.tags
810 .find_kind("gift-code")
811 .and_then(|tag| tag.content())
812 .ok_or("PIVX payment missing gift-code tag")?
813 .to_string();
814
815 let amount_str = rumor.tags
816 .find_kind("amount")
817 .and_then(|tag| tag.content())
818 .unwrap_or("0");
819 let amount_piv = amount_str.parse::<u64>().unwrap_or(0) as f64 / 100_000_000.0;
820
821 let address = rumor.tags
822 .find_kind("address")
823 .and_then(|tag| tag.content())
824 .map(|s| s.to_string());
825
826 let message_id = rumor.id.to_hex();
827
828 let tags: Vec<Vec<String>> = rumor.tags.iter()
829 .map(|tag| tag.as_slice().iter().map(|s| s.to_string()).collect())
830 .collect();
831
832 let event = StoredEventBuilder::new()
833 .id(&message_id)
834 .kind(event_kind::APPLICATION_SPECIFIC)
835 .chat_id(0) .content(&rumor.content)
837 .tags(tags)
838 .created_at(rumor.created_at.as_secs())
839 .mine(context.is_mine)
840 .npub(Some(rumor.pubkey.to_bech32().unwrap_or_default()))
841 .build();
842
843 return Ok(RumorProcessingResult::PivxPayment {
844 gift_code,
845 amount_piv,
846 address,
847 message_id,
848 event,
849 });
850 }
851
852 if is_wallpaper_change(&rumor) {
856 let url = rumor.tags
861 .find_kind("url")
862 .and_then(|tag| tag.content())
863 .unwrap_or_default()
864 .to_string();
865 let decryption_key = rumor.tags
866 .find_kind("decryption-key")
867 .and_then(|tag| tag.content())
868 .unwrap_or_default()
869 .to_string();
870 let decryption_nonce = rumor.tags
871 .find_kind("decryption-nonce")
872 .and_then(|tag| tag.content())
873 .unwrap_or_default()
874 .to_string();
875 let plaintext_hash = rumor.tags
876 .find_kind("x")
877 .and_then(|tag| tag.content())
878 .map(|s| s.to_string());
879 let mime = rumor.tags
880 .find_kind("m")
881 .and_then(|tag| tag.content())
882 .map(|s| s.to_string());
883 let blur = rumor.tags
884 .find_kind("blur")
885 .and_then(|tag| tag.content())
886 .and_then(|s| s.parse::<u32>().ok())
887 .map(|n| n.min(30) as u8);
888 let dim = rumor.tags
889 .find_kind("dim")
890 .and_then(|tag| tag.content())
891 .and_then(|s| s.parse::<u32>().ok())
892 .map(|n| n.min(100) as u8);
893
894 return Ok(RumorProcessingResult::WallpaperChanged {
895 sender_npub: rumor.pubkey.to_bech32().unwrap_or_default(),
896 created_at: rumor.created_at.as_secs(),
897 url,
898 decryption_key,
899 decryption_nonce,
900 plaintext_hash,
901 mime,
902 blur,
903 dim,
904 event_id: rumor.id.to_hex(),
905 });
906 }
907
908 if is_webxdc_peer_advertisement(&rumor) {
910 log_info!("[WEBXDC] Found peer advertisement rumor, is_mine={}, sender={}",
911 context.is_mine,
912 rumor.pubkey.to_bech32().unwrap_or_else(|_| "unknown".to_string()));
913
914 if context.is_mine {
915 log_info!("[WEBXDC] Ignoring our own peer advertisement");
916 return Ok(RumorProcessingResult::Ignored);
917 }
918
919 log_info!("[WEBXDC] Detected peer advertisement in rumor from another device");
920
921 let topic_id = rumor.tags
922 .find_kind("webxdc-topic")
923 .and_then(|tag| tag.content())
924 .ok_or("Peer advertisement missing webxdc-topic tag")?
925 .to_string();
926
927 let node_addr = rumor.tags
928 .find_kind("webxdc-node-addr")
929 .and_then(|tag| tag.content())
930 .ok_or("Peer advertisement missing webxdc-node-addr tag")?
931 .to_string();
932
933 let sender_npub = rumor.pubkey.to_bech32().unwrap_or_default();
934 return Ok(RumorProcessingResult::WebxdcPeerAdvertisement {
935 event_id: rumor.id.to_hex(),
936 topic_id,
937 node_addr,
938 sender_npub,
939 created_at: rumor.created_at.as_secs(),
940 });
941 }
942
943 if is_webxdc_peer_left(&rumor) {
945 if context.is_mine {
946 return Ok(RumorProcessingResult::Ignored);
947 }
948
949 log_info!("[WEBXDC] Detected peer-left signal from another device");
950
951 let topic_id = rumor.tags
952 .find_kind("webxdc-topic")
953 .and_then(|tag| tag.content())
954 .ok_or("Peer-left missing webxdc-topic tag")?
955 .to_string();
956
957 let sender_npub = rumor.pubkey.to_bech32().unwrap_or_default();
958 return Ok(RumorProcessingResult::WebxdcPeerLeft {
959 event_id: rumor.id.to_hex(),
960 topic_id,
961 sender_npub,
962 created_at: rumor.created_at.as_secs(),
963 });
964 }
965
966 if is_call_signal(&rumor) {
967 if context.is_mine {
969 return Ok(RumorProcessingResult::Ignored);
970 }
971 let tag = |kind: &str| rumor.tags.find_kind(kind).and_then(|t| t.content()).map(|s| s.to_string());
972 let call_id = tag("call-id").ok_or("Call signal missing call-id tag")?;
973 if call_id.is_empty() || call_id.len() > 64 || !call_id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-') {
975 return Err("Call signal carries a malformed call-id".to_string());
976 }
977 let signal = tag("call-signal").ok_or("Call signal missing call-signal tag")?;
978 let sender_npub = rumor.pubkey.to_bech32().unwrap_or_default();
979 return Ok(RumorProcessingResult::CallSignal {
980 event_id: rumor.id.to_hex(),
981 call_id,
982 signal,
983 node_addr: tag("call-node-addr"),
984 sender_npub,
985 created_at: rumor.created_at.as_secs(),
986 video: tag("call-video"),
987 media: tag("call-media"),
988 });
989 }
990
991 Ok(RumorProcessingResult::Ignored)
993}
994
995fn is_call_signal(rumor: &RumorEvent) -> bool {
997 rumor.tags
998 .find_kind("d")
999 .and_then(|tag| tag.content())
1000 .map(|content| content == "vector-call")
1001 .unwrap_or(false)
1002 && rumor.tags.find_kind("call-id").is_some()
1003 && rumor.tags.find_kind("call-signal").is_some()
1004}
1005
1006fn is_webxdc_peer_advertisement(rumor: &RumorEvent) -> bool {
1008 rumor.content == "peer-advertisement"
1009 && rumor.tags.find_kind("webxdc-topic").is_some()
1010 && rumor.tags.find_kind("webxdc-node-addr").is_some()
1011}
1012
1013fn is_webxdc_peer_left(rumor: &RumorEvent) -> bool {
1015 rumor.content == "peer-left"
1016 && rumor.tags.find_kind("webxdc-topic").is_some()
1017}
1018
1019fn is_pivx_payment(rumor: &RumorEvent) -> bool {
1021 rumor.tags
1022 .find_kind("d")
1023 .and_then(|tag| tag.content())
1024 .map(|content| content == "pivx-payment")
1025 .unwrap_or(false)
1026 && rumor.tags.find_kind("gift-code").is_some()
1027}
1028
1029fn extract_millisecond_timestamp(rumor: &RumorEvent) -> u64 {
1038 let ms_tag = rumor.tags
1039 .find_kind("ms")
1040 .and_then(|t| t.content());
1041 resolve_message_timestamp(rumor.created_at.as_secs(), ms_tag)
1042}
1043
1044pub fn resolve_message_timestamp(created_at_secs: u64, ms_tag: Option<&str>) -> u64 {
1055 const FUTURE_GRACE_MS: u64 = 5 * 60 * 1000;
1056 let base = created_at_secs.saturating_mul(1000);
1057 let at = match ms_tag.and_then(|s| s.parse::<u64>().ok()) {
1058 Some(offset) if offset <= 999 => base.saturating_add(offset),
1059 _ => base,
1060 };
1061 let now_ms = crate::clock::now_ms();
1062 if at > now_ms.saturating_add(FUTURE_GRACE_MS) { now_ms } else { at }
1063}
1064
1065fn extract_reply_reference(rumor: &RumorEvent) -> String {
1070 match rumor.tags.find_kind("e") {
1071 Some(tag) if tag.as_slice().get(3).is_some_and(|s| s == "reply") => {
1073 tag.content().unwrap_or("").to_string()
1074 }
1075 _ => String::new(),
1076 }
1077}
1078
1079fn is_typing_indicator(rumor: &RumorEvent) -> bool {
1081 let has_vector_tag = rumor.tags
1082 .find_kind("d")
1083 .and_then(|tag| tag.content())
1084 .map(|content| content == "vector")
1085 .unwrap_or(false);
1086
1087 let is_typing_content = rumor.content == "typing";
1088
1089 has_vector_tag && is_typing_content
1090}
1091
1092fn is_wallpaper_change(rumor: &RumorEvent) -> bool {
1094 rumor.tags
1095 .find_kind("d")
1096 .and_then(|tag| tag.content())
1097 .map(|content| content == "vector-wallpaper")
1098 .unwrap_or(false)
1099}
1100
1101fn is_leave_request(rumor: &RumorEvent) -> bool {
1103 let has_vector_tag = rumor.tags
1104 .find_kind("d")
1105 .and_then(|tag| tag.content())
1106 .map(|content| content == "vector")
1107 .unwrap_or(false);
1108
1109 let is_leave_content = rumor.content == "leave";
1110
1111 has_vector_tag && is_leave_content
1112}
1113
1114#[cfg(test)]
1115mod tests {
1116 use super::*;
1117
1118 #[test]
1122 fn ms_resolver_applies_offset_enforces_sub_second_and_clamps_future() {
1123 assert_eq!(resolve_message_timestamp(1500, Some("242")), 1_500_242);
1125 assert_eq!(resolve_message_timestamp(1500, None), 1_500_000);
1127 assert_eq!(resolve_message_timestamp(1500, Some("4242")), 1_500_000);
1129 assert_eq!(resolve_message_timestamp(1500, Some("nope")), 1_500_000);
1130 let now = web_time::SystemTime::now()
1132 .duration_since(web_time::UNIX_EPOCH).unwrap().as_secs();
1133 let clamped = resolve_message_timestamp(253_402_300_800, Some("5"));
1134 assert!(clamped <= (now + 3600) * 1000, "implausible-future ms must clamp to ~now");
1135 }
1136
1137 #[test]
1141 fn ambiguous_target_is_rejected_for_reaction_edit_delete() {
1142 let keys = test_keypair();
1143 let two_e = || tags(vec![
1144 Tag::custom("e", ["aa".repeat(32)]),
1145 Tag::custom("e", ["bb".repeat(32)]),
1146 ]);
1147 assert!(process_rumor(make_rumor(&keys, Kind::Reaction, "🔥", two_e()), dm_context(&keys), &temp_dir()).is_err());
1148 assert!(process_rumor(make_rumor(&keys, Kind::EventDeletion, "", two_e()), dm_context(&keys), &temp_dir()).is_err());
1149 assert!(process_rumor(make_rumor(&keys, Kind::from(event_kind::MESSAGE_EDIT), "edited", two_e()), dm_context(&keys), &temp_dir()).is_err());
1150 let one_e = tags(vec![Tag::custom("e", ["aa".repeat(32)])]);
1151 assert!(process_rumor(make_rumor(&keys, Kind::Reaction, "🔥", one_e), dm_context(&keys), &temp_dir()).is_ok());
1152 }
1153
1154 fn test_keypair() -> Keys {
1155 Keys::generate()
1156 }
1157
1158 fn tags(items: Vec<Tag>) -> Tags {
1160 let mut t = Tags::new();
1161 for item in items {
1162 t.push(item);
1163 }
1164 t
1165 }
1166
1167 fn custom_tag(key: &str, values: &[&str]) -> Tag {
1169 let owned: Vec<String> = values.iter().map(|s| s.to_string()).collect();
1170 Tag::custom(key.to_string(), owned)
1171 }
1172
1173 fn make_rumor(keys: &Keys, kind: Kind, content: &str, t: Tags) -> RumorEvent {
1174 RumorEvent {
1175 id: EventId::from_byte_array([0u8; 32]),
1176 kind,
1177 content: content.to_string(),
1178 tags: t,
1179 created_at: Timestamp::from_secs(1700000000),
1180 pubkey: keys.public_key(),
1181 }
1182 }
1183
1184 fn dm_context(keys: &Keys) -> RumorContext {
1185 RumorContext {
1186 sender: keys.public_key(),
1187 is_mine: false,
1188 conversation_id: "npub1test".to_string(),
1189 conversation_type: ConversationType::DirectMessage,
1190 }
1191 }
1192
1193 fn temp_dir() -> std::path::PathBuf {
1194 std::env::temp_dir().join("vector-rumor-test")
1195 }
1196
1197 #[test]
1202 fn test_text_message_dm() {
1203 let keys = test_keypair();
1204 let rumor = make_rumor(&keys, Kind::PrivateDirectMessage, "Hello world!", Tags::new());
1205 let ctx = dm_context(&keys);
1206 let result = process_rumor(rumor, ctx, &temp_dir()).unwrap();
1207
1208 match result {
1209 RumorProcessingResult::TextMessage(msg) => {
1210 assert_eq!(msg.content, "Hello world!");
1211 assert!(!msg.mine);
1212 assert!(msg.npub.is_none());
1213 assert!(msg.attachments.is_empty());
1214 }
1215 _ => panic!("Expected TextMessage"),
1216 }
1217 }
1218
1219 #[test]
1220 fn dm_colour_tags_reach_the_message_and_its_edit() {
1221 let keys = test_keypair();
1222 let tags = Tags::from_list(vec![
1223 Tag::custom("color", ["0", "5", "rainbow"]),
1224 Tag::custom("color", ["0", "99", "rainbow"]),
1225 Tag::custom("color", ["6", "11", "solid", "#f472b6", "extra"]),
1226 ]);
1227 let rumor = make_rumor(&keys, Kind::PrivateDirectMessage, "hello world", tags);
1228 match process_rumor(rumor, dm_context(&keys), &temp_dir()).unwrap() {
1229 RumorProcessingResult::TextMessage(msg) => {
1230 assert_eq!(msg.text_spans.len(), 1, "out-of-range and unknown-argument tags are dropped");
1231 assert!(matches!(&msg.text_spans[0], crate::text_spans::TextSpan::Color(c) if (c.from, c.to) == (0, 5)));
1232 }
1233 _ => panic!("Expected TextMessage"),
1234 }
1235
1236 let edit_tags = Tags::from_list(vec![
1237 Tag::event(EventId::from_hex(&"ab".repeat(32)).unwrap()),
1238 Tag::custom("color", ["0", "3", "solid", "#60a5fa"]),
1239 ]);
1240 let edit = make_rumor(&keys, Kind::from(event_kind::MESSAGE_EDIT), "bye", edit_tags);
1241 match process_rumor(edit, dm_context(&keys), &temp_dir()).unwrap() {
1242 RumorProcessingResult::Edit { text_spans, .. } => assert_eq!(text_spans.len(), 1),
1243 _ => panic!("Expected Edit"),
1244 }
1245 }
1246
1247 #[test]
1248 fn role_tags_reach_the_message() {
1249 let keys = test_keypair();
1250 let tags = Tags::from_list(vec![Tag::custom("role", ["ab".repeat(32)]), Tag::custom("role", ["not-a-role"])]);
1251 let rumor = make_rumor(&keys, Kind::PrivateDirectMessage, "@Raid Team go", tags);
1252 match process_rumor(rumor, dm_context(&keys), &temp_dir()).unwrap() {
1253 RumorProcessingResult::TextMessage(msg) => assert_eq!(msg.role_mentions, vec!["ab".repeat(32)]),
1254 _ => panic!("Expected TextMessage"),
1255 }
1256 }
1257
1258 #[test]
1259 fn colour_is_dropped_when_a_stripped_link_shifts_the_text() {
1260 let keys = test_keypair();
1261 let url = "https://blossom.example/abc.png";
1262 let tags = Tags::from_list(vec![
1263 Tag::custom("imeta", vec![format!("url {url}"), "m image/png".to_string()]),
1264 Tag::custom("color", ["0", "2", "rainbow"]),
1265 ]);
1266 let rumor = make_rumor(&keys, Kind::PrivateDirectMessage, &format!("{url} hi"), tags);
1267 match process_rumor(rumor, dm_context(&keys), &temp_dir()).unwrap() {
1268 RumorProcessingResult::TextMessage(msg) => assert!(msg.text_spans.is_empty()),
1269 _ => panic!("Expected TextMessage"),
1270 }
1271 }
1272
1273 #[test]
1274 fn a_kind_14_imeta_attachment_is_a_file_not_a_link() {
1275 let keys = test_keypair();
1282 let url = "https://blossom.ditto.pub/80f94026dc4fc97f59d131d0f6ce9af1951602f720a9957d6d7189fc1aa4ffcf.m4a";
1283 let imeta = Tag::custom(
1284 "imeta",
1285 vec![
1286 format!("url {url}"),
1287 "m audio/mp4".to_string(),
1288 "waveform 2 100 83 100 2 100 100 100".to_string(),
1289 "duration 58".to_string(),
1290 "encryption-algorithm aes-gcm".to_string(),
1291 "decryption-key 6989b3b663e29897cbb8bbaeda93d7f02d54c5551be9b4fda7aa7cd788a4b7f0".to_string(),
1292 "decryption-nonce d45c254d936ce9e9108e8d7a4e88834c".to_string(),
1293 "ox 5276b12eaa5019742abe86508d0a1ce6ee704603dc384048d0f00fa80b8d7eb8".to_string(),
1294 ],
1295 );
1296 let rumor = make_rumor(&keys, Kind::PrivateDirectMessage, url, Tags::from_list(vec![imeta]));
1297 let result = process_rumor(rumor, dm_context(&keys), &temp_dir()).unwrap();
1298
1299 match result {
1300 RumorProcessingResult::TextMessage(msg) => {
1301 assert_eq!(msg.attachments.len(), 1, "the imeta becomes a real attachment");
1302 let att = &msg.attachments[0];
1303 assert_eq!(att.url, url);
1304 assert_eq!(att.extension, "m4a", "extension resolves from the audio/mp4 mime");
1305 assert_eq!(att.key, "6989b3b663e29897cbb8bbaeda93d7f02d54c5551be9b4fda7aa7cd788a4b7f0");
1306 assert_eq!(att.nonce, "d45c254d936ce9e9108e8d7a4e88834c");
1307 assert_eq!(
1308 att.original_hash.as_deref(),
1309 Some("5276b12eaa5019742abe86508d0a1ce6ee704603dc384048d0f00fa80b8d7eb8"),
1310 "ox is the dedup identity"
1311 );
1312 assert!(!att.downloaded, "arrival never claims the bytes are held");
1313 assert!(msg.content.is_empty(), "the URL renders as the file, not also as a link");
1314 }
1315 _ => panic!("Expected TextMessage carrying an attachment"),
1316 }
1317 }
1318
1319 #[test]
1320 fn a_kind_14_caption_survives_beside_its_attachment() {
1321 let keys = test_keypair();
1323 let url = "https://blossom.example/abc.png";
1324 let imeta = Tag::custom(
1325 "imeta",
1326 vec![format!("url {url}"), "m image/png".to_string()],
1327 );
1328 let rumor = make_rumor(
1329 &keys,
1330 Kind::PrivateDirectMessage,
1331 &format!("look at this\n{url}"),
1332 Tags::from_list(vec![imeta]),
1333 );
1334 match process_rumor(rumor, dm_context(&keys), &temp_dir()).unwrap() {
1335 RumorProcessingResult::TextMessage(msg) => {
1336 assert_eq!(msg.content, "look at this");
1337 assert_eq!(msg.attachments.len(), 1);
1338 assert!(msg.attachments[0].key.is_empty());
1340 }
1341 _ => panic!("Expected TextMessage"),
1342 }
1343 }
1344
1345 #[test]
1346 fn test_text_message_mine() {
1347 let keys = test_keypair();
1348 let rumor = make_rumor(&keys, Kind::PrivateDirectMessage, "My own message", Tags::new());
1349 let ctx = RumorContext {
1350 sender: keys.public_key(),
1351 is_mine: true,
1352 conversation_id: "npub1test".to_string(),
1353 conversation_type: ConversationType::DirectMessage,
1354 };
1355 let result = process_rumor(rumor, ctx, &temp_dir()).unwrap();
1356
1357 match result {
1358 RumorProcessingResult::TextMessage(msg) => {
1359 assert!(msg.mine);
1360 }
1361 _ => panic!("Expected TextMessage"),
1362 }
1363 }
1364
1365 #[test]
1366 fn test_text_message_with_reply() {
1367 let keys = test_keypair();
1368 let t = tags(vec![
1369 Tag::custom("e", ["abc123def456".to_string(), String::new(), "reply".to_string()]),
1370 ]);
1371 let rumor = make_rumor(&keys, Kind::PrivateDirectMessage, "Reply text", t);
1372 let ctx = dm_context(&keys);
1373 let result = process_rumor(rumor, ctx, &temp_dir()).unwrap();
1374
1375 match result {
1376 RumorProcessingResult::TextMessage(msg) => {
1377 assert_eq!(msg.replied_to, "abc123def456");
1378 }
1379 _ => panic!("Expected TextMessage"),
1380 }
1381 }
1382
1383 #[test]
1384 fn test_text_message_with_ms_timestamp() {
1385 let keys = test_keypair();
1386 let t = tags(vec![custom_tag("ms", &["456"])]);
1387 let rumor = make_rumor(&keys, Kind::PrivateDirectMessage, "Precise time", t);
1388 let ctx = dm_context(&keys);
1389 let result = process_rumor(rumor, ctx, &temp_dir()).unwrap();
1390
1391 match result {
1392 RumorProcessingResult::TextMessage(msg) => {
1393 assert_eq!(msg.at, 1700000000 * 1000 + 456);
1394 }
1395 _ => panic!("Expected TextMessage"),
1396 }
1397 }
1398
1399 #[test]
1404 fn test_reaction() {
1405 let keys = test_keypair();
1406 let t = tags(vec![custom_tag("e", &["target_msg_id_hex"])]);
1407 let rumor = make_rumor(&keys, Kind::Reaction, "👍", t);
1408 let ctx = dm_context(&keys);
1409 let result = process_rumor(rumor, ctx, &temp_dir()).unwrap();
1410
1411 match result {
1412 RumorProcessingResult::Reaction(reaction) => {
1413 assert_eq!(reaction.emoji, "👍");
1414 assert_eq!(reaction.reference_id, "target_msg_id_hex");
1415 }
1416 _ => panic!("Expected Reaction"),
1417 }
1418 }
1419
1420 #[test]
1421 fn test_reaction_missing_e_tag() {
1422 let keys = test_keypair();
1423 let rumor = make_rumor(&keys, Kind::Reaction, "👍", Tags::new());
1424 let ctx = dm_context(&keys);
1425 let result = process_rumor(rumor, ctx, &temp_dir());
1426 assert!(result.is_err());
1427 }
1428
1429 #[test]
1430 fn junk_reaction_content_is_dropped_clean_ones_kept() {
1431 for ok in ["👍", "+", "-", "", "👨\u{200d}👩\u{200d}👧\u{200d}👦", ":thugamy:"] {
1433 assert!(is_renderable_reaction(ok), "{ok:?} should be renderable");
1434 }
1435 for junk in [
1437 ":thugamy:https://image.nostr.build/ccc22.png",
1438 "https://example.com/x.png",
1439 "lorem ipsum dolor",
1440 ] {
1441 assert!(!is_renderable_reaction(junk), "{junk:?} should be dropped");
1442 }
1443 assert!(!is_renderable_reaction(&"x".repeat(64)));
1444
1445 let keys = test_keypair();
1447 let t = tags(vec![custom_tag("e", &["target"])]);
1448 let rumor = make_rumor(&keys, Kind::Reaction, ":thugamy:https://image.nostr.build/ccc22.png", t);
1449 let result = process_rumor(rumor, dm_context(&keys), &temp_dir()).unwrap();
1450 assert!(matches!(result, RumorProcessingResult::Ignored), "junk reaction should be Ignored");
1451 }
1452
1453 #[test]
1458 fn test_edit_event() {
1459 let keys = test_keypair();
1460 let t = tags(vec![custom_tag("e", &["original_msg_id"])]);
1461 let rumor = make_rumor(&keys, Kind::from_u16(16), "Edited content", t);
1462 let ctx = dm_context(&keys);
1463 let result = process_rumor(rumor, ctx, &temp_dir()).unwrap();
1464
1465 match result {
1466 RumorProcessingResult::Edit { message_id, new_content, event, .. } => {
1467 assert_eq!(message_id, "original_msg_id");
1468 assert_eq!(new_content, "Edited content");
1469 assert_eq!(event.kind, event_kind::MESSAGE_EDIT);
1470 }
1471 _ => panic!("Expected Edit"),
1472 }
1473 }
1474
1475 #[test]
1480 fn test_typing_indicator_valid() {
1481 let keys = test_keypair();
1482 let future_ts = web_time::SystemTime::now()
1483 .duration_since(web_time::UNIX_EPOCH).unwrap()
1484 .as_secs() + 10;
1485 let t = tags(vec![
1486 Tag::identifier("vector"),
1487 Tag::expiration(Timestamp::from_secs(future_ts)),
1488 ]);
1489 let rumor = make_rumor(&keys, Kind::ApplicationSpecificData, "typing", t);
1490 let ctx = dm_context(&keys);
1491 let result = process_rumor(rumor, ctx, &temp_dir()).unwrap();
1492
1493 match result {
1494 RumorProcessingResult::TypingIndicator { until, .. } => {
1495 assert_eq!(until, future_ts);
1496 }
1497 _ => panic!("Expected TypingIndicator"),
1498 }
1499 }
1500
1501 #[test]
1502 fn test_typing_indicator_expired() {
1503 let keys = test_keypair();
1504 let t = tags(vec![
1505 Tag::identifier("vector"),
1506 Tag::expiration(Timestamp::from_secs(1000000000)),
1507 ]);
1508 let rumor = make_rumor(&keys, Kind::ApplicationSpecificData, "typing", t);
1509 let ctx = dm_context(&keys);
1510 let result = process_rumor(rumor, ctx, &temp_dir()).unwrap();
1511
1512 assert!(matches!(result, RumorProcessingResult::Ignored));
1513 }
1514
1515 #[test]
1516 fn a_file_without_decryption_tags_is_a_plaintext_reference_not_a_drop() {
1517 let keys = test_keypair();
1521 let ox_hash = "deadbeef".repeat(8);
1522 let t = tags(vec![
1523 custom_tag("ox", &[&ox_hash]),
1524 custom_tag("file-type", &["application/x-webxdc"]),
1525 custom_tag("name", &["game.xdc"]),
1526 ]);
1527 let rumor = make_rumor(&keys, Kind::from_u16(15), "https://blossom.example/deadbeef.xdc", t);
1528 let result = process_rumor(rumor, dm_context(&keys), &temp_dir()).unwrap();
1529 match result {
1530 RumorProcessingResult::FileAttachment(msg) => {
1531 let att = &msg.attachments[0];
1532 assert!(att.key.is_empty());
1533 assert!(att.nonce.is_empty());
1534 assert_eq!(att.id, ox_hash, "identity must be the plaintext hash claim");
1535 assert!(!att.downloaded, "a reference is a claim, never resident content");
1536 }
1537 other => panic!("expected FileAttachment, got {other:?}"),
1538 }
1539 }
1540
1541 #[test]
1542 fn a_key_without_a_nonce_is_still_malformed() {
1543 let keys = test_keypair();
1546 let t = tags(vec![
1547 custom_tag("decryption-key", &["aabbccdd"]),
1548 custom_tag("ox", &[&"deadbeef".repeat(8)]),
1549 custom_tag("file-type", &["image/jpeg"]),
1550 ]);
1551 let rumor = make_rumor(&keys, Kind::from_u16(15), "https://blossom.example/deadbeef.jpg", t);
1552 assert!(process_rumor(rumor, dm_context(&keys), &temp_dir()).is_err());
1553 }
1554
1555 #[test]
1560 fn test_expired_text_message_is_dropped_on_receipt() {
1561 let keys = test_keypair();
1562 let t = tags(vec![Tag::expiration(Timestamp::from_secs(1000000000))]);
1563 let rumor = make_rumor(&keys, Kind::PrivateDirectMessage, "too late", t);
1564 let ctx = dm_context(&keys);
1565 let result = process_rumor(rumor, ctx, &temp_dir()).unwrap();
1566 assert!(matches!(result, RumorProcessingResult::Ignored));
1567 }
1568
1569 #[test]
1570 fn test_expired_file_message_is_dropped_on_receipt() {
1571 let keys = test_keypair();
1572 let ox_hash = "deadbeef".repeat(8);
1573 let t = tags(vec![
1574 custom_tag("decryption-key", &["aabbccdd"]),
1575 custom_tag("decryption-nonce", &["11223344"]),
1576 custom_tag("ox", &[&ox_hash]),
1577 custom_tag("file-type", &["image/jpeg"]),
1578 Tag::expiration(Timestamp::from_secs(1000000000)),
1579 ]);
1580 let rumor = make_rumor(&keys, Kind::from_u16(15), "https://blossom.example/deadbeef.jpg", t);
1581 let ctx = dm_context(&keys);
1582 let result = process_rumor(rumor, ctx, &temp_dir()).unwrap();
1583 assert!(matches!(result, RumorProcessingResult::Ignored));
1584 }
1585
1586 #[test]
1587 fn an_expired_reaction_or_edit_is_dropped_but_an_expired_delete_still_applies() {
1588 let keys = test_keypair();
1589 let target = || Tag::custom("e", ["aa".repeat(32)]);
1590 let expired = || Tag::expiration(Timestamp::from_secs(1000000000));
1591
1592 let reaction = make_rumor(&keys, Kind::Reaction, "🔥", tags(vec![target(), expired()]));
1593 assert!(matches!(process_rumor(reaction, dm_context(&keys), &temp_dir()).unwrap(), RumorProcessingResult::Ignored));
1594 let edit = make_rumor(&keys, Kind::from(event_kind::MESSAGE_EDIT), "edited", tags(vec![target(), expired()]));
1595 assert!(matches!(process_rumor(edit, dm_context(&keys), &temp_dir()).unwrap(), RumorProcessingResult::Ignored));
1596
1597 let delete = make_rumor(&keys, Kind::EventDeletion, "", tags(vec![target(), expired()]));
1598 assert!(matches!(
1599 process_rumor(delete, dm_context(&keys), &temp_dir()).unwrap(),
1600 RumorProcessingResult::DeletionRequest { .. }
1601 ));
1602 }
1603
1604 #[test]
1605 fn test_future_expiration_still_processes() {
1606 let keys = test_keypair();
1607 let future_ts = web_time::SystemTime::now()
1608 .duration_since(web_time::UNIX_EPOCH).unwrap()
1609 .as_secs() + 600;
1610 let t = tags(vec![Tag::expiration(Timestamp::from_secs(future_ts))]);
1611 let rumor = make_rumor(&keys, Kind::PrivateDirectMessage, "still alive", t);
1612 let ctx = dm_context(&keys);
1613 let result = process_rumor(rumor, ctx, &temp_dir()).unwrap();
1614 match result {
1615 RumorProcessingResult::TextMessage(msg) => {
1616 assert_eq!(msg.expiration, Some(future_ts));
1617 }
1618 _ => panic!("Expected TextMessage"),
1619 }
1620 }
1621
1622 #[test]
1627 fn test_leave_request() {
1628 let keys = test_keypair();
1629 let t = tags(vec![Tag::identifier("vector")]);
1630 let rumor = make_rumor(&keys, Kind::ApplicationSpecificData, "leave", t);
1631 let ctx = dm_context(&keys);
1632 let result = process_rumor(rumor, ctx, &temp_dir()).unwrap();
1633
1634 match result {
1635 RumorProcessingResult::LeaveRequest { member_pubkey, .. } => {
1636 assert!(!member_pubkey.is_empty());
1637 assert!(member_pubkey.starts_with("npub1"));
1638 }
1639 _ => panic!("Expected LeaveRequest"),
1640 }
1641 }
1642
1643 #[test]
1648 fn test_pivx_payment() {
1649 let keys = test_keypair();
1650 let t = tags(vec![
1651 Tag::identifier("pivx-payment"),
1652 custom_tag("gift-code", &["ABC12"]),
1653 custom_tag("amount", &["100000000"]),
1654 custom_tag("address", &["DTest123"]),
1655 ]);
1656 let rumor = make_rumor(&keys, Kind::ApplicationSpecificData, "pivx-payment", t);
1657 let ctx = dm_context(&keys);
1658 let result = process_rumor(rumor, ctx, &temp_dir()).unwrap();
1659
1660 match result {
1661 RumorProcessingResult::PivxPayment { gift_code, amount_piv, address, .. } => {
1662 assert_eq!(gift_code, "ABC12");
1663 assert!((amount_piv - 1.0).abs() < f64::EPSILON);
1664 assert_eq!(address, Some("DTest123".to_string()));
1665 }
1666 _ => panic!("Expected PivxPayment"),
1667 }
1668 }
1669
1670 #[test]
1675 fn test_webxdc_peer_advertisement() {
1676 let keys = test_keypair();
1677 let t = tags(vec![
1678 custom_tag("webxdc-topic", &["topic123"]),
1679 custom_tag("webxdc-node-addr", &["addr456"]),
1680 ]);
1681 let rumor = make_rumor(&keys, Kind::ApplicationSpecificData, "peer-advertisement", t);
1682 let ctx = dm_context(&keys);
1683 let result = process_rumor(rumor, ctx, &temp_dir()).unwrap();
1684
1685 match result {
1686 RumorProcessingResult::WebxdcPeerAdvertisement { topic_id, node_addr, .. } => {
1687 assert_eq!(topic_id, "topic123");
1688 assert_eq!(node_addr, "addr456");
1689 }
1690 _ => panic!("Expected WebxdcPeerAdvertisement"),
1691 }
1692 }
1693
1694 #[test]
1695 fn test_webxdc_peer_advertisement_own_ignored() {
1696 let keys = test_keypair();
1697 let t = tags(vec![
1698 custom_tag("webxdc-topic", &["topic123"]),
1699 custom_tag("webxdc-node-addr", &["addr456"]),
1700 ]);
1701 let rumor = make_rumor(&keys, Kind::ApplicationSpecificData, "peer-advertisement", t);
1702 let ctx = RumorContext {
1703 sender: keys.public_key(),
1704 is_mine: true,
1705 conversation_id: "npub1test".to_string(),
1706 conversation_type: ConversationType::DirectMessage,
1707 };
1708 let result = process_rumor(rumor, ctx, &temp_dir()).unwrap();
1709 assert!(matches!(result, RumorProcessingResult::Ignored));
1710 }
1711
1712 #[test]
1713 fn test_webxdc_peer_left() {
1714 let keys = test_keypair();
1715 let t = tags(vec![custom_tag("webxdc-topic", &["topic123"])]);
1716 let rumor = make_rumor(&keys, Kind::ApplicationSpecificData, "peer-left", t);
1717 let ctx = dm_context(&keys);
1718 let result = process_rumor(rumor, ctx, &temp_dir()).unwrap();
1719
1720 match result {
1721 RumorProcessingResult::WebxdcPeerLeft { topic_id, .. } => {
1722 assert_eq!(topic_id, "topic123");
1723 }
1724 _ => panic!("Expected WebxdcPeerLeft"),
1725 }
1726 }
1727
1728 #[test]
1733 fn test_unknown_kind() {
1734 let keys = test_keypair();
1735 let rumor = make_rumor(&keys, Kind::from_u16(65535), "Mystery event", Tags::new());
1736 let ctx = dm_context(&keys);
1737 let result = process_rumor(rumor, ctx, &temp_dir()).unwrap();
1738
1739 match result {
1740 RumorProcessingResult::UnknownEvent(event) => {
1741 assert_eq!(event.kind, 65535);
1742 assert_eq!(event.content, "Mystery event");
1743 }
1744 _ => panic!("Expected UnknownEvent"),
1745 }
1746 }
1747
1748 #[test]
1753 fn test_file_attachment() {
1754 let keys = test_keypair();
1755 let ox_hash = "deadbeef".repeat(8); let t = tags(vec![
1757 custom_tag("decryption-key", &["aabbccdd"]),
1758 custom_tag("decryption-nonce", &["11223344"]),
1759 custom_tag("ox", &[&ox_hash]),
1760 custom_tag("file-type", &["image/jpeg"]),
1761 custom_tag("name", &["photo.jpg"]),
1762 custom_tag("size", &["12345"]),
1763 ]);
1764 let rumor = make_rumor(&keys, Kind::from_u16(15), "https://blossom.example/deadbeef.jpg", t);
1765 let ctx = dm_context(&keys);
1766 let dir = temp_dir();
1767 let result = process_rumor(rumor, ctx, &dir).unwrap();
1768
1769 match result {
1770 RumorProcessingResult::FileAttachment(msg) => {
1771 assert_eq!(msg.attachments.len(), 1);
1772 let att = &msg.attachments[0];
1773 assert_eq!(att.key, "aabbccdd");
1774 assert_eq!(att.nonce, "11223344");
1775 assert_eq!(att.extension, "jpg");
1776 assert_eq!(att.name, "photo.jpg");
1777 assert_eq!(att.size, 12345);
1778 assert!(!att.downloaded);
1779 }
1780 _ => panic!("Expected FileAttachment"),
1781 }
1782 }
1783
1784 #[test]
1785 fn test_file_attachment_fallback_mirrors() {
1786 let keys = test_keypair();
1787 let ox_hash = "deadbeef".repeat(8);
1788 let t = tags(vec![
1789 custom_tag("decryption-key", &["aabbccdd"]),
1790 custom_tag("decryption-nonce", &["11223344"]),
1791 custom_tag("ox", &[&ox_hash]),
1792 custom_tag("file-type", &["image/jpeg"]),
1793 custom_tag("fallback", &["https://mirror-one.example/deadbeef.jpg"]),
1794 custom_tag("fallback", &["https://blossom.example/deadbeef.jpg"]),
1797 custom_tag("fallback", &["http://insecure.example/deadbeef.jpg"]),
1798 custom_tag("fallback", &["https://sneaky.example/a b.jpg"]),
1799 custom_tag("fallback", &["https://mirror-one.example/deadbeef.jpg"]),
1800 custom_tag("fallback", &["https://mirror-two.example/deadbeef.jpg"]),
1801 ]);
1802 let rumor = make_rumor(&keys, Kind::from_u16(15), "https://blossom.example/deadbeef.jpg", t);
1803 let ctx = dm_context(&keys);
1804 let result = process_rumor(rumor, ctx, &temp_dir()).unwrap();
1805
1806 match result {
1807 RumorProcessingResult::FileAttachment(msg) => {
1808 let att = &msg.attachments[0];
1809 assert_eq!(att.fallback_urls, vec![
1810 "https://mirror-one.example/deadbeef.jpg".to_string(),
1811 "https://mirror-two.example/deadbeef.jpg".to_string(),
1812 ]);
1813 }
1814 _ => panic!("Expected FileAttachment"),
1815 }
1816 }
1817
1818 #[test]
1819 fn test_file_attachment_hostile_path_basis_rejected() {
1820 let keys = test_keypair();
1821 let dir = temp_dir();
1822 let ctx = || dm_context(&keys);
1823
1824 let t = tags(vec![
1828 custom_tag("decryption-key", &["aabbccdd"]),
1829 custom_tag("decryption-nonce", &["11223344"]),
1830 custom_tag("ox", &["../../../etc/passwd"]),
1831 custom_tag("file-type", &["image/jpeg"]),
1832 custom_tag("name", &["x.jpg"]),
1833 ]);
1834 let rumor = make_rumor(&keys, Kind::from_u16(15), "https://blossom.example/x.jpg", t);
1835 let expected_id = crate::crypto::attachment_identity_basis(None, "11223344", "https://blossom.example/x.jpg");
1836 match process_rumor(rumor, ctx(), &dir).unwrap() {
1837 RumorProcessingResult::FileAttachment(msg) => {
1838 let att = &msg.attachments[0];
1839 assert!(!att.path.contains(".."), "traversal basis must not reach the path: {}", att.path);
1840 assert_eq!(att.id, expected_id, "id falls back to the nonce+url digest");
1841 }
1842 _ => panic!("Expected FileAttachment"),
1843 }
1844
1845 let t = tags(vec![
1847 custom_tag("decryption-key", &["aabbccdd"]),
1848 custom_tag("decryption-nonce", &["../../../etc/cron.d/evil"]),
1849 custom_tag("file-type", &["image/jpeg"]),
1850 ]);
1851 let rumor = make_rumor(&keys, Kind::from_u16(15), "https://blossom.example/y.jpg", t);
1852 assert!(process_rumor(rumor, ctx(), &dir).is_err());
1853 }
1854
1855 #[test]
1856 fn test_file_attachment_empty_hash_rejected() {
1857 let keys = test_keypair();
1858 let t = tags(vec![
1859 custom_tag("decryption-key", &["aabbccdd"]),
1860 custom_tag("decryption-nonce", &["11223344"]),
1861 custom_tag("file-type", &["image/jpeg"]),
1862 ]);
1863 let empty_hash = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
1864 let rumor = make_rumor(&keys, Kind::from_u16(15), &format!("https://blossom.example/{}", empty_hash), t);
1865 let ctx = dm_context(&keys);
1866 let result = process_rumor(rumor, ctx, &temp_dir());
1867 assert!(result.is_err());
1868 }
1869
1870 #[test]
1871 fn test_file_attachment_with_image_meta() {
1872 let keys = test_keypair();
1873 let ox_hash = "a".repeat(64);
1874 let t = tags(vec![
1875 custom_tag("decryption-key", &["aabbccdd"]),
1876 custom_tag("decryption-nonce", &["11223344"]),
1877 custom_tag("ox", &[&ox_hash]),
1878 custom_tag("file-type", &["image/png"]),
1879 custom_tag("thumbhash", &["base64data"]),
1880 custom_tag("dim", &["1920x1080"]),
1881 custom_tag("size", &["5000"]),
1882 ]);
1883 let rumor = make_rumor(&keys, Kind::from_u16(15), "https://blossom.example/aaa.png", t);
1884 let ctx = dm_context(&keys);
1885 let result = process_rumor(rumor, ctx, &temp_dir()).unwrap();
1886
1887 match result {
1888 RumorProcessingResult::FileAttachment(msg) => {
1889 let att = &msg.attachments[0];
1890 let meta = att.img_meta.as_ref().unwrap();
1891 assert_eq!(meta.width, 1920);
1892 assert_eq!(meta.height, 1080);
1893 assert_eq!(meta.thumbhash, "base64data");
1894 }
1895 _ => panic!("Expected FileAttachment"),
1896 }
1897 }
1898
1899 #[test]
1905 fn test_file_attachment_thumb_tag_is_read() {
1906 let keys = test_keypair();
1907 let ox_hash = "b".repeat(64);
1908 let t = tags(vec![
1909 custom_tag("decryption-key", &["aabbccdd"]),
1910 custom_tag("decryption-nonce", &["11223344"]),
1911 custom_tag("ox", &[&ox_hash]),
1912 custom_tag("file-type", &["image/png"]),
1913 custom_tag("thumb", &["realwiretag"]),
1914 custom_tag("dim", &["800x600"]),
1915 custom_tag("size", &["5000"]),
1916 ]);
1917 let rumor = make_rumor(&keys, Kind::from_u16(15), "https://blossom.example/bbb.png", t);
1918 let ctx = dm_context(&keys);
1919 let result = process_rumor(rumor, ctx, &temp_dir()).unwrap();
1920
1921 match result {
1922 RumorProcessingResult::FileAttachment(msg) => {
1923 let meta = msg.attachments[0].img_meta.as_ref()
1924 .expect("img_meta must be populated from the `thumb` tag");
1925 assert_eq!(meta.thumbhash, "realwiretag");
1926 assert_eq!(meta.width, 800);
1927 assert_eq!(meta.height, 600);
1928 }
1929 _ => panic!("Expected FileAttachment"),
1930 }
1931 }
1932
1933 #[test]
1938 fn test_extract_hash_from_blossom_url() {
1939 let hash = "a".repeat(64);
1940 let url = format!("https://blossom.example/{}.jpg", hash);
1941 assert_eq!(extract_hash_from_blossom_url(&url), Some(hash));
1942
1943 assert_eq!(extract_hash_from_blossom_url("https://example.com/short"), None);
1944 assert_eq!(extract_hash_from_blossom_url("https://example.com/not-hex-at-all-but-exactly-sixty-four-characters-long-string-here!"), None);
1945 }
1946
1947 #[test]
1948 fn test_unknown_app_specific_ignored() {
1949 let keys = test_keypair();
1950 let t = tags(vec![Tag::identifier("some-other-app")]);
1951 let rumor = make_rumor(&keys, Kind::ApplicationSpecificData, "unknown-content", t);
1952 let ctx = dm_context(&keys);
1953 let result = process_rumor(rumor, ctx, &temp_dir()).unwrap();
1954 assert!(matches!(result, RumorProcessingResult::Ignored));
1955 }
1956}