Skip to main content

vector_core/
rumor.rs

1//! Rumor Processing Module
2//!
3//! Unified processing for the inner decrypted events of NIP-17 DMs. "Rumors" are
4//! the inner events; only the gift-wrap unwrapping happens before this.
5//!
6//! ## Architecture
7//!
8//! ```text
9//! Event → Protocol Handler (unwrap) → RumorEvent
10//!                                       ↓
11//!                             process_rumor() [SHARED]
12//!                                       ↓
13//!                             RumorProcessingResult
14//!                                       ↓
15//!                     Storage Handler (protocol-specific)
16//!                                       ↓
17//!                             Emit to UI [SHARED]
18//! ```
19//!
20//! ## Supported Rumor Types
21//!
22//! - **Text Messages**: `Kind::PrivateDirectMessage` - Plain text with optional replies
23//! - **File Attachments**: `Kind::from_u16(15)` - Encrypted files with metadata
24//! - **Reactions**: `Kind::Reaction` - Emoji reactions to messages
25//! - **Typing Indicators**: `Kind::ApplicationSpecificData` - Real-time typing status
26
27use 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/// Decrypted NIP-17 rumor event representation.
35#[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/// Context for processing a rumor
46///
47/// Provides the necessary context to process a rumor correctly,
48/// including who sent it and what conversation it belongs to.
49#[derive(Debug, Clone)]
50pub struct RumorContext {
51    /// The sender's public key
52    pub sender: PublicKey,
53    /// Whether this rumor is from ourselves
54    pub is_mine: bool,
55    /// The conversation ID (npub for DMs)
56    pub conversation_id: String,
57    /// The type of conversation
58    pub conversation_type: ConversationType,
59}
60
61/// Type of conversation — the transport-specific dimension the shared parser keys off (e.g. who the
62/// author is). `conversation_id` carries the address: an npub for a DM, a channel id for a Community.
63#[derive(Debug, Clone, PartialEq)]
64pub enum ConversationType {
65    /// Direct message (NIP-17) — 1:1, so the author is implied by the chat.
66    DirectMessage,
67    /// Concord community channel — a group, so each message records its real author.
68    Community,
69}
70
71impl RumorContext {
72    /// The author npub to stamp on a parsed message. A DM is 1:1 so the author is implied by the
73    /// chat (`None`); a Community message records its real author so the group can attribute it.
74    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/// Result of processing a rumor
83///
84/// Represents the different types of events that can result from
85/// processing a rumor. The caller is responsible for storing these
86/// results appropriately based on the conversation type.
87#[derive(Debug, Clone)]
88pub enum RumorProcessingResult {
89    /// A text message (with optional reply reference)
90    TextMessage(Message),
91    /// A file attachment message
92    FileAttachment(Message),
93    /// An emoji reaction to a message
94    Reaction(Reaction),
95    /// A typing indicator update
96    TypingIndicator {
97        profile_id: String,
98        until: u64,
99    },
100    /// A leave request from a group member (admin should auto-remove them)
101    LeaveRequest {
102        /// The event ID of the leave request (for deduplication)
103        event_id: String,
104        /// The pubkey of the member requesting to leave (npub)
105        member_pubkey: String,
106    },
107    /// A WebXDC peer advertisement for realtime channels
108    WebxdcPeerAdvertisement {
109        event_id: String,
110        topic_id: String,
111        node_addr: String,
112        sender_npub: String,
113        created_at: u64,
114    },
115    /// A WebXDC peer left signal (peer closed their Mini App)
116    WebxdcPeerLeft {
117        event_id: String,
118        topic_id: String,
119        sender_npub: String,
120        created_at: u64,
121    },
122    /// Call signalling (offer, answer, reject, hangup, busy) between two devices
123    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        /// Codecs the sender decodes, comma separated; absent from peers without video.
131        video: Option<String>,
132        /// "audio" or "video": what kind of call the offer is for.
133        media: Option<String>,
134    },
135    /// Unknown event type - stored for future compatibility
136    /// The frontend will render this as "Unknown Event" placeholder
137    UnknownEvent(StoredEvent),
138    /// A PIVX payment promo code sent in chat
139    PivxPayment {
140        /// The promo code (5-char Base58)
141        gift_code: String,
142        /// Amount in PIV
143        amount_piv: f64,
144        /// The PIVX address for balance checking (optional for older events)
145        address: Option<String>,
146        /// The message ID for this payment event
147        message_id: String,
148        /// The stored event for persistence
149        event: StoredEvent,
150    },
151    /// A per-DM wallpaper change. The encrypted Blossom file is referenced
152    /// by URL + decryption key in the tags; the caller is responsible for
153    /// the timestamp comparison (latest-write-wins against
154    /// `chat.wallpaper_ts`) and the download + decrypt step.
155    WallpaperChanged {
156        /// Sender's npub (whoever set the wallpaper).
157        sender_npub: String,
158        /// Rumor `created_at` (Unix seconds) — drives latest-write-wins.
159        created_at: u64,
160        /// Encrypted file URL on Blossom.
161        url: String,
162        /// Hex-encoded AES key.
163        decryption_key: String,
164        /// Hex-encoded AES nonce.
165        decryption_nonce: String,
166        /// Optional plaintext SHA-256 (for caller integrity check).
167        plaintext_hash: Option<String>,
168        /// Optional MIME hint (e.g. "image/png") — informs cache extension.
169        mime: Option<String>,
170        /// Blur (px, 0..=30). `None` falls back to the receiver's default.
171        blur: Option<u8>,
172        /// Brightness percent (0..=100). `None` falls back to default.
173        dim: Option<u8>,
174        /// The rumor ID, used as the system-event row id.
175        event_id: String,
176    },
177    /// Event was ignored (invalid, expired, or should not be stored)
178    Ignored,
179    /// A NIP-09 deletion request — sender asks live clients to drop a
180    /// previously-received message from local storage. Cooperative
181    /// delete-for-everyone signal that pairs with Vector's gift-wrap
182    /// nuke at the relay layer (see `vector_core::deletion`).
183    DeletionRequest {
184        /// Hex id of the rumor being deleted (target's `["e", ...]` tag).
185        target_event_id: String,
186    },
187    /// A message edit event
188    Edit {
189        /// The ID of the message being edited
190        message_id: String,
191        /// The new content
192        new_content: String,
193        /// Timestamp of the edit (milliseconds)
194        edited_at: u64,
195        /// NIP-30 custom-emoji tags resolved from the new content
196        emoji_tags: Vec<crate::types::EmojiTag>,
197        /// Coloured runs of the new content
198        text_spans: Vec<crate::text_spans::TextSpan>,
199        /// The stored event for persistence
200        event: StoredEvent,
201    },
202}
203
204/// Main rumor processor - protocol agnostic
205///
206/// This is the single entry point for processing all rumor types.
207/// It handles text messages, file attachments, reactions, and typing indicators
208/// in a unified way, regardless of the underlying protocol.
209///
210/// # Arguments
211///
212/// * `rumor` - The rumor event to process
213/// * `context` - Context about the rumor (sender, conversation, etc.)
214/// * `download_dir` - Directory for file attachment paths
215///
216/// # Returns
217///
218/// A `RumorProcessingResult` indicating what type of event was processed,
219/// or an error if processing failed.
220pub fn process_rumor(
221    rumor: RumorEvent,
222    context: RumorContext,
223    download_dir: &Path,
224) -> Result<RumorProcessingResult, String> {
225    // NIP-40: an event arriving already expired is dropped on receipt. Never a delete:
226    // refusing an expired tombstone would bring back what it erased.
227    if rumor.kind != Kind::EventDeletion && already_expired(extract_nip40_expiration(&rumor)) {
228        return Ok(RumorProcessingResult::Ignored);
229    }
230    match rumor.kind {
231        // Text messages — Kind 14 (NIP-17 DM chat message).
232        Kind::PrivateDirectMessage => {
233            process_text_message(rumor, context, download_dir)
234        }
235        // File attachments
236        k if k.as_u16() == 15 => {
237            process_file_attachment(rumor, context, download_dir)
238        }
239        // Message edits
240        k if k.as_u16() == event_kind::MESSAGE_EDIT => {
241            process_edit_event(rumor, context)
242        }
243        // Emoji reactions
244        Kind::Reaction => {
245            process_reaction(rumor, context)
246        }
247        // Application-specific data (typing indicators, etc.)
248        Kind::ApplicationSpecificData => {
249            process_app_specific(rumor, context)
250        }
251        // NIP-09 cooperative deletion (Layer 2 of Vector's delete flow).
252        // The relay-layer wrap nuke happens via the retained ephemeral
253        // key in `vector_core::deletion`; this rumor tells live clients
254        // that already decrypted the original to drop it from local
255        // storage. Authorization (sender == original author) is
256        // verified at commit time, not parse time.
257        Kind::EventDeletion => {
258            process_deletion(rumor, context)
259        }
260        // Unknown or unsupported kind - store for future compatibility
261        _ => {
262            process_unknown_event(rumor, context)
263        }
264    }
265}
266
267/// Process an unknown event type
268///
269/// Creates a StoredEvent for unknown kinds so they can be stored
270/// and potentially displayed/processed in future versions.
271fn process_unknown_event(
272    rumor: RumorEvent,
273    context: RumorContext,
274) -> Result<RumorProcessingResult, String> {
275    // Convert tags to Vec<Vec<String>> format
276    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    // Extract reference_id from e-tag if present
283    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
302/// Process a text message rumor
303///
304/// Extracts text content, reply references, millisecond-precision timestamps,
305/// and any NIP-92 `imeta` attachments riding the message.
306fn process_text_message(
307    rumor: RumorEvent,
308    context: RumorContext,
309    download_dir: &Path,
310) -> Result<RumorProcessingResult, String> {
311    // Extract reply reference if present
312    let replied_to = extract_reply_reference(&rumor);
313
314    // Extract millisecond-precision timestamp
315    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    // DM → None (1:1, implied by chat); Community → the real author.
320    let npub = context.author_npub(&rumor.pubkey);
321
322    // Create the message
323    let expiration = extract_nip40_expiration(&rumor);
324    // NIP-92 `imeta` on a kind-14: how other clients (Armada) send a file in a
325    // DM, where Vector uses kind 15 with top-level decryption tags. Both are
326    // valid NIP-17; without this the file arrives as a bare URL in the text.
327    // The imeta's own fields carry the AES-GCM key/nonce when the sender
328    // encrypted it, so the existing download path serves either kind. A
329    // community message overwrites both fields from its transport-parsed
330    // attachments, so this cannot double-add there.
331    let attachments = crate::community::attachments::attachments_from_tags(rumor.tags.iter(), download_dir);
332    // The URL usually IS the whole content on such a message; rendering the
333    // attachment AND the raw link would show the file twice.
334    let content = crate::community::attachments::strip_attachment_urls(&rumor.content, &attachments);
335    // Spans count chars of the content as sent; a stripped link would shift them.
336    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, // Populated by get_message_views
348        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, // Set by caller after processing
361        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
374/// Extract SHA256 hash from a Blossom URL
375///
376/// Blossom URLs typically follow the format: `https://server.com/<sha256hash>[.ext]`
377pub 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
387/// Process a file attachment rumor
388///
389/// Handles encrypted file metadata including:
390/// - Decryption keys and nonces
391/// - Original file hashes (for deduplication)
392/// - Image metadata (thumbhash, dimensions)
393/// - File extensions and mime types
394fn process_file_attachment(
395    rumor: RumorEvent,
396    context: RumorContext,
397    download_dir: &Path,
398) -> Result<RumorProcessingResult, String> {
399    // Extract decryption parameters. Absent/empty key = a PUBLIC plaintext
400    // blob shared by reference (e.g. a store app) — download + hash-verify,
401    // no decrypt. NIP-17 marks these tags optional; requiring them dropped
402    // such messages outright. A key WITHOUT a nonce is still malformed.
403    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    // Extract original file hash (ox tag) if present
420    let original_file_hash = rumor.tags
421        .find_kind("ox")
422        .and_then(|tag| tag.content())
423        .map(|s| s.to_string());
424
425    // Extract content storage URL
426    let content_url = rumor.content.clone();
427
428    // Skip attachments with empty file hash - these are corrupted uploads
429    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    // Extract image metadata if provided
436    let img_meta: Option<ImageMetadata> = {
437        // Read BOTH tag names: current senders emit `thumbhash` (see sending.rs),
438        // while older ones emit `thumb`. The two must never diverge or img_meta
439        // silently drops and the image renders as a generic file box with no
440        // preview — the bug this belt-and-braces read exists to prevent.
441        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    // Figure out the file extension: prefer the name tag's extension, fall back to MIME-derived
474    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    // Extract filename from name tag (used for extension override and display name)
481    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    // Use the extension from the original filename when available (more accurate than MIME for
488    // uncommon types like .sh, .toml, .rs, etc. which all map to application/octet-stream)
489    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    // Grab the reported file size
499    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    // Determine identity, file path and download status via the shared basis
506    // rules (ox for dedup when present, else a nonce+url digest — see
507    // `attachment_identity_basis`). The basis is author-controlled and
508    // becomes an on-disk filename — require bounded plain hex before joining
509    // it into a path, mirroring the Community parser, so a crafted tag can't
510    // smuggle `../` traversal into `path`.
511    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    // A plaintext reference (empty key forces empty nonce above) skips this:
515    // its basis is the ox claim or a digest of the url, both safe hex.
516    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    // Arrival never claims downloaded: an ox-named file proves nothing about
526    // content (the download path re-verifies by hash before reuse), and the
527    // honest pipeline never writes digest-named files at all — a file found
528    // under one could only be a foreign plant.
529    let downloaded = false;
530    let file_path = hash_file_path.to_string_lossy().to_string();
531
532    // Extract reply reference if present
533    let replied_to = extract_reply_reference(&rumor);
534
535    // Extract millisecond-precision timestamp
536    let ms_timestamp = extract_millisecond_timestamp(&rumor);
537
538    // Extract webxdc-topic for Mini Apps (realtime channel isolation).
539    // Bounded sanity (mirrors the Community parser): base32 alphabet only,
540    // 32-byte payload (52 chars); anything else is dropped, not propagated.
541    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    // NIP-17 `fallback` mirrors: the same ciphertext on other hosts, tried in
548    // order when the primary URL dies. Sender-controlled data — https-only,
549    // deduped against the primary and each other, capped.
550    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    // Create the attachment
571    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,       // Kind 15 attachments use explicit key/nonce
586        original_hash: original_file_hash, // ox tag value (original file hash)
587        fallback_urls,
588    };
589
590    let emoji_tags = crate::types::EmojiTag::extract_from_tags(rumor.tags.iter());
591    // DM → None (1:1, implied by chat); Community → the real author.
592    let npub = context.author_npub(&rumor.pubkey);
593
594    // Create the message with attachment
595    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, // Populated by get_message_views
602        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, // Set by caller after processing
615        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
628/// Process a NIP-09 deletion rumor (Layer 2 cooperative hide).
629///
630/// Extracts the target event id from the `["e", ...]` tag. Authorization
631/// (sender pubkey == original message author) is verified at commit
632/// time so callers can short-circuit without an extra DB hit at parse.
633/// The single `e`-tag target id, or `None` if absent OR ambiguous (multiple `e` tags). A reaction,
634/// edit, and deletion each act on ONE specific message, so a first-of-many match could route to the
635/// wrong target — reject ambiguity for every transport (shared hardening; honest senders emit exactly
636/// one `e` tag). This mirrors Concord's `unique_tag` discipline and extends it to DMs.
637fn 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
646/// Parse the NIP-40 `["expiration", <unix secs>]` tag off an inbound rumor.
647/// Present on Self-Destruct Timer messages; drives the local countdown + purge.
648fn 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
659/// NIP-40: true when the tag's expiry already lies in the past at receipt.
660pub(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
676/// Process a reaction rumor
677///
678/// Extracts emoji reactions to messages.
679fn 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    // Unrenderable / junk content: record the wrapper (Ignored) so it isn't
687    // re-synced, but store nothing — as if the reaction never arrived.
688    if !is_renderable_reaction(&rumor.content) {
689        return Ok(RumorProcessingResult::Ignored);
690    }
691
692    // NIP-30: pull the first `["emoji", shortcode, url]` tag whose
693    // shortcode matches the reaction content (`:shortcode:` form).
694    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
721/// Process a message edit rumor
722///
723/// Extracts the edited content and references the original message.
724fn 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    // NIP-30 custom-emoji tags ride the edit so a `:shortcode:` introduced (or
734    // kept) by the edit renders as its image rather than literal text.
735    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
765/// Process application-specific data (typing indicators, etc.)
766fn process_app_specific(
767    rumor: RumorEvent,
768    context: RumorContext,
769) -> Result<RumorProcessingResult, String> {
770    // Check if this is a typing indicator
771    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    // Check if this is a leave request
797    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    // Check if this is a PIVX payment
808    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) // Will be set by caller
836            .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    // Check if this is a wallpaper change. Tags carry the encrypted file
853    // ref; the caller decides whether this beats the chat's current
854    // `wallpaper_ts` and runs the download+decrypt step.
855    if is_wallpaper_change(&rumor) {
856        // A wallpaper rumor with no `url` is a removal tombstone — the sender
857        // cleared their wallpaper. The url/key/nonce are absent in that case,
858        // so they're optional here; the apply step treats an empty url as
859        // "revert to default theme".
860        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    // Check if this is a WebXDC peer advertisement
909    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    // Check if this is a WebXDC peer-left signal
944    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        // Our own signals echo back from our other devices; the caller's session already knows.
968        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        // Every reply repeats the caller's id, so only a short token is taken.
974        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    // Unknown application-specific data
992    Ok(RumorProcessingResult::Ignored)
993}
994
995/// Check if a rumor is a call signal
996fn 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
1006/// Check if a rumor is a WebXDC peer advertisement
1007fn 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
1013/// Check if a rumor is a WebXDC peer-left signal
1014fn is_webxdc_peer_left(rumor: &RumorEvent) -> bool {
1015    rumor.content == "peer-left"
1016        && rumor.tags.find_kind("webxdc-topic").is_some()
1017}
1018
1019/// Check if a rumor is a PIVX payment
1020fn 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
1029// ============================================================================
1030// Helper Functions
1031// ============================================================================
1032
1033/// Extract millisecond-precision timestamp from rumor
1034///
1035/// Combines the rumor's created_at (seconds) with a custom "ms" tag
1036/// to provide millisecond precision for accurate message ordering.
1037fn 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
1044/// Resolve a message's ordering timestamp (epoch ms) from its second-resolution `created_at` and an
1045/// optional `ms` sub-second offset tag. ONE implementation for every transport — DMs and Concord share
1046/// the exact ms convention AND the anti-abuse clamp.
1047///
1048/// - The `ms` tag is a 0..=999 sub-second offset (senders decompose `created_at = ms/1000`,
1049///   `tag = ms%1000`); an out-of-range or unparseable tag is ignored, falling back to whole seconds.
1050/// - The inner event escapes relay far-future clamping (DM rumors and Concord inners are both
1051///   encrypted and never published bare), so a hostile sender could stamp `created_at` year-9999 to
1052///   pin a message to the top forever. Clamp an implausible-future result back to receipt time; a few
1053///   minutes' grace absorbs clock skew, and a message inside it waits for its time ([`crate::early`]).
1054pub 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
1065/// Extract reply reference from rumor tags
1066///
1067/// Looks for an "e" tag with the "reply" marker to identify
1068/// which message this rumor is replying to.
1069fn extract_reply_reference(rumor: &RumorEvent) -> String {
1070    match rumor.tags.find_kind("e") {
1071        // Marker sits at index 3 of the raw tag (`["e", id, relay, "reply"]`).
1072        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
1079/// Check if rumor is a typing indicator
1080fn 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
1092/// Check if rumor is a wallpaper-change application-data event.
1093fn 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
1101/// Check if rumor is a leave request
1102fn 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    /// One ms resolver for every transport: sub-second offset convention + future-clamp.
1119    /// Without the clamp a year-9999 `created_at` would pin a message to the top forever — the shared
1120    /// resolver enforces it for DMs too.
1121    #[test]
1122    fn ms_resolver_applies_offset_enforces_sub_second_and_clamps_future() {
1123        // created_at seconds + a valid 0..=999 offset.
1124        assert_eq!(resolve_message_timestamp(1500, Some("242")), 1_500_242);
1125        // No tag → whole-second resolution.
1126        assert_eq!(resolve_message_timestamp(1500, None), 1_500_000);
1127        // Out-of-range offset (>999) or junk is ignored, never added.
1128        assert_eq!(resolve_message_timestamp(1500, Some("4242")), 1_500_000);
1129        assert_eq!(resolve_message_timestamp(1500, Some("nope")), 1_500_000);
1130        // Far-future created_at (year ~9999) is clamped back to ~now — can't dominate ordering.
1131        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    /// The dup-`e` target reject moved from Concord's `open_message` into the SHARED parser, so it now
1138    /// guards BOTH transports: a reaction/edit/delete naming TWO targets is ambiguous and rejected
1139    /// (a single, unambiguous target parses fine).
1140    #[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    /// Build a Tags collection from Tag items
1159    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    /// Create a custom tag (e.g., ["ms", "456"])
1168    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    // ========================================================================
1198    // Text Message Tests
1199    // ========================================================================
1200
1201    #[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        // Armada sends a DM file as a kind-14 whose content IS the URL, with a
1276        // NIP-92 `imeta` carrying the encryption params — where Vector uses
1277        // kind 15 with top-level tags. Both are valid NIP-17. Tag bytes below
1278        // are copied verbatim from a real Armada voice message, extra fields
1279        // (waveform/duration/encryption-algorithm) included, so an unknown
1280        // field can never quietly break the parse.
1281        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        // Only the URL is stripped: a caption sent alongside the file stays.
1322        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                // Unencrypted foreign media: no key/nonce, and that is allowed.
1339                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    // ========================================================================
1400    // Reaction Tests
1401    // ========================================================================
1402
1403    #[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        // Renderable glyphs / shortcodes survive.
1432        for ok in ["👍", "+", "-", "", "👨\u{200d}👩\u{200d}👧\u{200d}👦", ":thugamy:"] {
1433            assert!(is_renderable_reaction(ok), "{ok:?} should be renderable");
1434        }
1435        // Junk (a shortcode+URL, a bare URL, prose, anything long) is dropped.
1436        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        // End-to-end: the reported junk reaction resolves to Ignored, not Reaction.
1446        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    // ========================================================================
1454    // Edit Tests
1455    // ========================================================================
1456
1457    #[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    // ========================================================================
1476    // Typing Indicator Tests
1477    // ========================================================================
1478
1479    #[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        // Smart-forward Tier 2: a public blob (e.g. a store app) shared by
1518        // reference carries url + ox + size and NO decryption tags. NIP-17
1519        // marks the tags optional; this used to error out the whole message.
1520        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        // The leniency is for ABSENT crypto, not broken crypto: a key that
1544        // cannot decrypt anything must not demote the file to plaintext.
1545        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    // ========================================================================
1556    // NIP-40 receipt-drop tests
1557    // ========================================================================
1558
1559    #[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    // ========================================================================
1623    // Leave Request Tests
1624    // ========================================================================
1625
1626    #[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    // ========================================================================
1644    // PIVX Payment Tests
1645    // ========================================================================
1646
1647    #[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    // ========================================================================
1671    // WebXDC Tests
1672    // ========================================================================
1673
1674    #[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    // ========================================================================
1729    // Unknown Event Tests
1730    // ========================================================================
1731
1732    #[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    // ========================================================================
1749    // File Attachment Tests
1750    // ========================================================================
1751
1752    #[test]
1753    fn test_file_attachment() {
1754        let keys = test_keypair();
1755        let ox_hash = "deadbeef".repeat(8); // 64 hex chars
1756        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            // Junk a sender could stuff in: primary dup, plain http,
1795            // whitespace smuggle, mirror dup.
1796            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        // Traversal via ox: non-hex basis is ignored → the identity falls back
1825        // to the nonce+url digest (always clean hex) and never leaves the
1826        // download dir.
1827        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        // Traversal via the nonce (no ox): hard reject, nothing to fall back to.
1846        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    /// Guards the send/receive tag-name contract: the sender emits the
1900    /// thumbhash under `thumb` (sending.rs), so the receiver MUST read it from
1901    /// `thumb`. These had diverged (`thumb` vs `thumbhash`), silently dropping
1902    /// img_meta on every received image. The test above uses the `thumbhash`
1903    /// alias; this one uses the real wire tag.
1904    #[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    // ========================================================================
1934    // Helper Function Tests
1935    // ========================================================================
1936
1937    #[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}