Skip to main content

vector_core/community/
attachments.rs

1//! Community message attachments (NIP-92 `imeta`).
2//!
3//! Unlike NIP-17 DMs (one media item per event), a Community message event carries its
4//! caption in `content` plus one `imeta` tag per attachment — so a single message can
5//! mix text and N files. Each `imeta` holds the per-file AES-GCM key+nonce (the NIP-17
6//! attachment technique: fresh random key per file), so the Blossom ciphertext is only
7//! decryptable by members who can open the event.
8
9use std::path::Path;
10use nostr_sdk::prelude::*;
11use crate::types::{Attachment, ImageMetadata};
12
13const IMETA: &str = "imeta";
14
15/// Encode an [`Attachment`] as a NIP-92 `imeta` tag with Vector's encryption fields.
16/// Entries are space-delimited `key value` strings (NIP-92 form); a value may contain
17/// spaces (e.g. a filename) since only the first space delimits key from value.
18pub fn attachment_to_imeta(att: &Attachment) -> Tag {
19    let mut fields: Vec<String> = Vec::with_capacity(10);
20    fields.push(format!("url {}", att.url));
21    fields.push(format!("m {}", crate::crypto::mime_from_extension(&att.extension)));
22    fields.push("encryption-algorithm aes-gcm".to_string());
23    fields.push(format!("decryption-key {}", att.key));
24    fields.push(format!("decryption-nonce {}", att.nonce));
25    if att.size > 0 {
26        fields.push(format!("size {}", att.size));
27    }
28    if let Some(h) = att.original_hash.as_deref().filter(|h| !h.is_empty()) {
29        fields.push(format!("ox {}", h));
30    }
31    if !att.name.is_empty() {
32        fields.push(format!("name {}", att.name));
33    }
34    if let Some(meta) = &att.img_meta {
35        if !meta.thumbhash.is_empty() {
36            fields.push(format!("thumb {}", meta.thumbhash));
37        }
38        fields.push(format!("dim {}x{}", meta.width, meta.height));
39    }
40    // Mini Apps: the send-time-minted realtime topic rides the imeta so every
41    // member joins the same gossip topic (see `crate::webxdc::mint_topic_id`).
42    if let Some(topic) = att.webxdc_topic.as_deref().filter(|t| !t.is_empty()) {
43        fields.push(format!("webxdc-topic {}", topic));
44    }
45    Tag::custom(TagKind::Custom(IMETA.into()), fields)
46}
47
48/// Read a single `key value` field from an `imeta` tag's entries (value is everything
49/// after the first space, so spaces in the value are preserved).
50fn field<'a>(entries: &'a [String], key: &str) -> Option<&'a str> {
51    entries.iter().find_map(|e| {
52        e.strip_prefix(key)
53            .and_then(|rest| rest.strip_prefix(' '))
54    })
55}
56
57/// Parse a single `imeta` tag into an [`Attachment`]. `None` if the tag isn't an `imeta`
58/// or is missing the required url / decryption fields. `download_dir` computes the
59/// (not-yet-downloaded) local target path, mirroring the DM file-attachment path.
60pub fn attachment_from_imeta(tag: &Tag, download_dir: &Path) -> Option<Attachment> {
61    let entries = tag.as_slice();
62    if entries.first().map(String::as_str) != Some(IMETA) {
63        return None;
64    }
65    let body = &entries[1..];
66
67    let url = field(body, "url")?.to_string();
68    if url.is_empty() {
69        return None;
70    }
71    let key = field(body, "decryption-key")?.to_string();
72    let nonce = field(body, "decryption-nonce")?.to_string();
73
74    let mime = field(body, "m").unwrap_or("application/octet-stream");
75    let name = field(body, "name").map(crate::crypto::sanitize_filename).unwrap_or_default();
76    // Prefer the filename's extension (accurate for .toml/.rs/etc. that MIME maps to
77    // octet-stream); fall back to the MIME-derived extension.
78    let extension = name
79        .rsplit('.')
80        .next()
81        .filter(|e| !e.is_empty() && *e != name)
82        .map(|e| e.to_lowercase())
83        .unwrap_or_else(|| crate::crypto::extension_from_mime(mime));
84
85    let size = field(body, "size").and_then(|s| s.parse::<u64>().ok()).unwrap_or(0);
86    let original_hash = field(body, "ox").map(|s| s.to_string()).filter(|s| !s.is_empty());
87
88    let img_meta = {
89        let thumb = field(body, "thumb").map(|s| s.to_string());
90        let dim = field(body, "dim").and_then(|s| {
91            let (w, h) = s.split_once('x')?;
92            Some((w.parse::<u32>().ok()?, h.parse::<u32>().ok()?))
93        });
94        match (thumb, dim) {
95            (Some(thumbhash), Some((width, height))) => Some(ImageMetadata { thumbhash, width, height }),
96            _ => None,
97        }
98    };
99
100    // Local path keyed on the original hash (dedup across messages) when present, else
101    // the nonce (unique per send). The basis is author-controlled, so require it to be a
102    // bounded hex string before joining it into a filesystem path — a hostile member can't
103    // smuggle `../` traversal into the persisted `path` (defense-in-depth: `open_attachment`
104    // also re-checks the path is inside the download dir).
105    let basis = original_hash.clone().unwrap_or_else(|| nonce.clone());
106    if basis.is_empty() || basis.len() > 128 || !basis.bytes().all(|b| b.is_ascii_hexdigit()) {
107        return None;
108    }
109    let path = download_dir.join(format!("{}.{}", basis, extension));
110    let downloaded = path.exists();
111
112    // Bounded sanity on the author-controlled topic: base32 alphabet only, 32-byte
113    // payload (52 chars). Anything else is dropped, not propagated to the realtime layer.
114    let webxdc_topic = field(body, "webxdc-topic")
115        .filter(|t| t.len() == 52 && t.bytes().all(|b| b.is_ascii_uppercase() || (b'2'..=b'7').contains(&b)))
116        .map(|t| t.to_string());
117
118    Some(Attachment {
119        id: basis,
120        key,
121        nonce,
122        extension,
123        name,
124        url,
125        path: path.to_string_lossy().to_string(),
126        size,
127        img_meta,
128        downloading: false,
129        downloaded,
130        webxdc_topic,
131        group_id: None, // Community attachments use explicit key/nonce (NIP-17 technique).
132        original_hash,
133        scheme_version: None,
134        mls_filename: None,
135    })
136}
137
138/// Parse every `imeta` tag on an event into attachments, order preserved.
139/// Capped: a max-size event can carry ~1700 imeta tags, each becoming a
140/// persisted + in-STATE Attachment — bound the per-message amplification.
141pub fn attachments_from_tags<'a>(
142    tags: impl Iterator<Item = &'a Tag>,
143    download_dir: &Path,
144) -> Vec<Attachment> {
145    const MAX_ATTACHMENTS_PER_MESSAGE: usize = 32;
146    tags.filter_map(|t| attachment_from_imeta(t, download_dir))
147        .take(MAX_ATTACHMENTS_PER_MESSAGE)
148        .collect()
149}
150
151#[cfg(test)]
152mod tests {
153    use super::*;
154
155    fn sample(name: &str, ext: &str, with_img: bool) -> Attachment {
156        Attachment {
157            id: "h".into(),
158            key: "0".repeat(64),  // 32-byte key
159            nonce: "1".repeat(32), // 16-byte (0xChat-compatible) nonce
160            extension: ext.into(),
161            name: name.into(),
162            url: "https://blossom.example/abc".into(),
163            path: String::new(),
164            size: 4096,
165            img_meta: with_img.then(|| ImageMetadata { thumbhash: "TH".into(), width: 800, height: 600 }),
166            downloading: false,
167            downloaded: false,
168            webxdc_topic: None,
169            group_id: None,
170            original_hash: Some("a".repeat(64)),
171            scheme_version: None,
172            mls_filename: None,
173        }
174    }
175
176    #[test]
177    fn imeta_round_trip_preserves_crypto_and_meta() {
178        let dir = std::env::temp_dir();
179        let att = sample("my report.png", "png", true);
180        let tag = attachment_to_imeta(&att);
181        let back = attachment_from_imeta(&tag, &dir).expect("parses");
182        assert_eq!(back.url, att.url);
183        assert_eq!(back.key, att.key);
184        assert_eq!(back.nonce, att.nonce);
185        assert_eq!(back.size, att.size);
186        assert_eq!(back.original_hash, att.original_hash);
187        assert_eq!(back.name, "my report.png"); // space in filename survives
188        assert_eq!(back.extension, "png");
189        assert_eq!(back.group_id, None);
190        let m = back.img_meta.expect("img meta");
191        assert_eq!((m.width, m.height), (800, 600));
192        assert_eq!(m.thumbhash, "TH");
193    }
194
195    #[test]
196    fn spoiler_and_renamed_filenames_survive_imeta() {
197        // Spoiler is detected receiver-side by a `SPOILER_` prefix on the attachment NAME,
198        // so the name (incl. that prefix, and spaces) must round-trip through imeta intact —
199        // this is what gives Community attachments spoiler/rename parity with DMs.
200        let dir = std::env::temp_dir();
201        let spoiler = attachment_from_imeta(&attachment_to_imeta(&sample("SPOILER_big reveal.png", "png", true)), &dir).unwrap();
202        assert_eq!(spoiler.name, "SPOILER_big reveal.png");
203        assert!(spoiler.name.to_uppercase().starts_with("SPOILER_"), "spoiler prefix preserved");
204        assert_eq!(spoiler.extension, "png");
205
206        let renamed = attachment_from_imeta(&attachment_to_imeta(&sample("Quarterly Report (final).pdf", "pdf", false)), &dir).unwrap();
207        assert_eq!(renamed.name, "Quarterly Report (final).pdf");
208        assert_eq!(renamed.extension, "pdf");
209    }
210
211    #[test]
212    fn field_key_match_requires_a_following_space_no_prefix_bleed() {
213        // `field(_, "m")` must NOT match a longer key like "mime ..." (shared prefix). The
214        // "key + ' '" requirement guards this; lock it so future imeta fields can't collide.
215        let entries = vec!["mime image/png".to_string(), "m image/jpeg".to_string()];
216        assert_eq!(field(&entries, "m"), Some("image/jpeg"));
217        assert_eq!(field(&entries, "mime"), Some("image/png"));
218        assert_eq!(field(&["decryption-key-x abc".to_string()], "decryption-key"), None);
219        // A key present with no value (no following space) yields None, not a panic.
220        assert_eq!(field(&["url".to_string()], "url"), None);
221    }
222
223    #[test]
224    fn multiple_imeta_tags_parse_in_order() {
225        let dir = std::env::temp_dir();
226        let tags = vec![
227            Tag::custom(TagKind::Custom("z".into()), ["pseudonym"]),
228            attachment_to_imeta(&sample("a.png", "png", false)),
229            Tag::custom(TagKind::Custom("ms".into()), ["12"]),
230            attachment_to_imeta(&sample("b.pdf", "pdf", false)),
231        ];
232        let atts = attachments_from_tags(tags.iter(), &dir);
233        assert_eq!(atts.len(), 2);
234        assert_eq!(atts[0].name, "a.png");
235        assert_eq!(atts[1].name, "b.pdf");
236        assert_eq!(atts[1].extension, "pdf");
237    }
238
239    #[test]
240    fn non_imeta_and_incomplete_tags_are_skipped() {
241        let dir = std::env::temp_dir();
242        let not_imeta = Tag::custom(TagKind::Custom("e".into()), ["abc"]);
243        assert!(attachment_from_imeta(&not_imeta, &dir).is_none());
244        // imeta missing decryption fields → None.
245        let bad = Tag::custom(TagKind::Custom("imeta".into()), ["url https://x/y"]);
246        assert!(attachment_from_imeta(&bad, &dir).is_none());
247    }
248
249    #[test]
250    fn imeta_crypto_params_actually_decrypt_the_ciphertext() {
251        // End-to-end attachment crypto: encrypt a plaintext with the real params, carry the
252        // key/nonce via imeta, parse them back out, and confirm they decrypt the ciphertext.
253        // This is the receiver's download path in miniature (minus the Blossom fetch).
254        let dir = std::env::temp_dir();
255        let plaintext = b"the quick brown fox jumps over 13 lazy dogs".to_vec();
256        let params = crate::crypto::generate_encryption_params();
257        let ciphertext = crate::crypto::encrypt_data(&plaintext, &params).unwrap();
258
259        let att = Attachment {
260            id: "x".into(),
261            key: params.key.clone(),
262            nonce: params.nonce.clone(),
263            extension: "txt".into(),
264            name: "note.txt".into(),
265            url: "https://blossom.example/blob".into(),
266            path: String::new(),
267            size: ciphertext.len() as u64,
268            img_meta: None,
269            downloading: false,
270            downloaded: false,
271            webxdc_topic: None,
272            group_id: None,
273            original_hash: Some("c".repeat(64)),
274            scheme_version: None,
275            mls_filename: None,
276        };
277        let parsed = attachment_from_imeta(&attachment_to_imeta(&att), &dir).expect("parses");
278        // The parsed key/nonce (straight off the imeta) must decrypt the ciphertext.
279        let decrypted = crate::crypto::decrypt_data(&ciphertext, &parsed.key, &parsed.nonce)
280            .expect("decrypts with imeta-carried params");
281        assert_eq!(decrypted, plaintext, "round-trip plaintext matches");
282    }
283
284    #[test]
285    fn hostile_path_basis_is_rejected() {
286        // A channel member authors the imeta, so the path basis (`ox`, else `nonce`) is
287        // attacker-controlled. A non-hex / traversal basis must be refused, never joined
288        // into a filesystem path.
289        let dir = std::path::Path::new("/tmp/vector-test-dl");
290        let traversal = Tag::custom(TagKind::Custom("imeta".into()), [
291            "url https://x/y",
292            "decryption-key 00",
293            "decryption-nonce 11",
294            "ox ../../../../etc/passwd",
295        ]);
296        assert!(attachment_from_imeta(&traversal, dir).is_none(), "traversal ox rejected");
297
298        // Falls back to nonce when ox absent — a non-hex nonce is likewise rejected.
299        let bad_nonce = Tag::custom(TagKind::Custom("imeta".into()), [
300            "url https://x/y",
301            "decryption-key 00",
302            "decryption-nonce ../evil",
303        ]);
304        assert!(attachment_from_imeta(&bad_nonce, dir).is_none(), "traversal nonce rejected");
305
306        // A legitimate hex basis still parses.
307        let good = Tag::custom(TagKind::Custom("imeta".into()), [
308            "url https://x/y".to_string(),
309            "decryption-key 00".to_string(),
310            "decryption-nonce 11".to_string(),
311            format!("ox {}", "a".repeat(64)),
312        ]);
313        assert!(attachment_from_imeta(&good, dir).is_some(), "hex ox accepted");
314    }
315
316    #[test]
317    fn webxdc_topic_round_trips_imeta_and_garbage_is_dropped() {
318        let dir = std::env::temp_dir();
319        let topic = crate::webxdc::mint_topic_id("hash", "sender");
320        let mut att = sample("game.xdc", "xdc", false);
321        att.webxdc_topic = Some(topic.clone());
322        let back = attachment_from_imeta(&attachment_to_imeta(&att), &dir).expect("parses");
323        assert_eq!(back.webxdc_topic.as_deref(), Some(topic.as_str()));
324
325        // Author-controlled: wrong-length / off-alphabet topics are dropped, not propagated.
326        for bad in ["short", &"A".repeat(53), &"a".repeat(52), &format!("{}!", "A".repeat(51))] {
327            let mut att = sample("game.xdc", "xdc", false);
328            att.webxdc_topic = Some(bad.to_string());
329            let back = attachment_from_imeta(&attachment_to_imeta(&att), &dir).expect("parses");
330            assert_eq!(back.webxdc_topic, None, "bad topic {:?} must be dropped", bad);
331        }
332    }
333
334    #[test]
335    fn malformed_imeta_does_not_panic_and_drops_gracefully() {
336        let dir = std::env::temp_dir();
337        // Garbage entries, duplicate keys, value-less keys, weird spacing — must not panic.
338        let junk = Tag::custom(TagKind::Custom("imeta".into()), [
339            "url",                 // no value
340            "decryption-key",      // no value
341            "random noise here",
342            "  ",
343            "url https://x/legit", // a later valid url
344        ]);
345        // Missing decryption-key/nonce → None (not a panic).
346        assert!(attachment_from_imeta(&junk, &dir).is_none());
347
348        // Empty imeta (just the tag name) → None.
349        let empty = Tag::custom(TagKind::Custom("imeta".into()), Vec::<String>::new());
350        assert!(attachment_from_imeta(&empty, &dir).is_none());
351    }
352}