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    // Mirrors of the same ciphertext (NIP-92 `fallback` convention).
46    for fb in &att.fallback_urls {
47        fields.push(format!("fallback {}", fb));
48    }
49    Tag::custom(IMETA, fields)
50}
51
52/// Read a single `key value` field from an `imeta` tag's entries (value is everything
53/// after the first space, so spaces in the value are preserved).
54fn field<'a>(entries: &'a [String], key: &str) -> Option<&'a str> {
55    entries.iter().find_map(|e| {
56        e.strip_prefix(key)
57            .and_then(|rest| rest.strip_prefix(' '))
58    })
59}
60
61/// Every value of a repeatable `key value` field, in tag order.
62fn fields_all<'a>(entries: &'a [String], key: &str) -> impl Iterator<Item = &'a str> + 'a {
63    let key = key.to_string();
64    entries.iter().filter_map(move |e| {
65        e.strip_prefix(key.as_str())
66            .and_then(|rest| rest.strip_prefix(' '))
67    })
68}
69
70/// Parse a single `imeta` tag into an [`Attachment`]. `None` if the tag isn't an `imeta`
71/// or is missing the required url / decryption fields. `download_dir` computes the
72/// (not-yet-downloaded) local target path, mirroring the DM file-attachment path.
73pub fn attachment_from_imeta(tag: &Tag, download_dir: &Path) -> Option<Attachment> {
74    let entries = tag.as_slice();
75    if entries.first().map(String::as_str) != Some(IMETA) {
76        return None;
77    }
78    let body = &entries[1..];
79
80    let url = field(body, "url")?.to_string();
81    if url.is_empty() {
82        return None;
83    }
84    // Foreign NIP-92 media is UNENCRYPTED — the decryption params are Vector's own
85    // extension and simply absent. Empty key+nonce marks a plaintext attachment;
86    // the download path then skips AES-GCM and saves the bytes verbatim.
87    let key = field(body, "decryption-key").unwrap_or("").to_string();
88    let nonce = field(body, "decryption-nonce").unwrap_or("").to_string();
89    // Half-specified encryption (exactly one of the pair present) is malformed.
90    if key.is_empty() != nonce.is_empty() {
91        return None;
92    }
93    let encrypted = !key.is_empty();
94
95    let mime = field(body, "m").unwrap_or("application/octet-stream");
96    let name = field(body, "name").map(crate::crypto::sanitize_filename).unwrap_or_default();
97    // Prefer the filename's extension (accurate for .toml/.rs/etc. that MIME maps to
98    // octet-stream); fall back to the MIME-derived extension.
99    let extension = name
100        .rsplit('.')
101        .next()
102        .filter(|e| !e.is_empty() && *e != name)
103        .map(|e| e.to_lowercase())
104        .unwrap_or_else(|| crate::crypto::extension_from_mime(mime));
105
106    let size = field(body, "size").and_then(|s| s.parse::<u64>().ok()).unwrap_or(0);
107    // Vector stamps the plaintext sha256 as `ox`; NIP-92 uses `x`. Either serves
108    // as the dedup / identity basis (content-addressed, so best for foreign media).
109    let original_hash = field(body, "ox").or_else(|| field(body, "x"))
110        .map(|s| s.to_string()).filter(|s| !s.is_empty());
111
112    let img_meta = {
113        let thumb = field(body, "thumb").map(|s| s.to_string());
114        let dim = field(body, "dim").and_then(|s| {
115            let (w, h) = s.split_once('x')?;
116            Some((w.parse::<u32>().ok()?, h.parse::<u32>().ok()?))
117        });
118        match (thumb, dim) {
119            (Some(thumbhash), Some((width, height))) => Some(ImageMetadata { thumbhash, width, height }),
120            _ => None,
121        }
122    };
123
124    // An ENCRYPTED nonce is author-controlled, feeds the identity digest, and must
125    // be hex for decryption — reject garbage. A plaintext attachment has no nonce;
126    // its identity falls back to the content hash (`ox`/`x`) or `sha256(url)`.
127    if encrypted && (nonce.len() > 128 || !nonce.bytes().all(|b| b.is_ascii_hexdigit())) {
128        return None;
129    }
130
131    // Identity + local path via the shared basis rules (ox for dedup when
132    // present, else a nonce+url digest — see `attachment_identity_basis`).
133    // The ox basis is author-controlled, so require bounded hex before
134    // joining it into a filesystem path — a hostile member can't smuggle
135    // `../` traversal into the persisted `path` (defense-in-depth:
136    // `open_attachment` also re-checks the path is inside the download dir).
137    let basis = crate::crypto::attachment_identity_basis(original_hash.as_deref(), &nonce, &url);
138    if basis.is_empty() || basis.len() > 128 || !basis.bytes().all(|b| b.is_ascii_hexdigit()) {
139        return None;
140    }
141    let path = download_dir.join(format!("{}.{}", basis, extension));
142    // Arrival never claims downloaded: an ox-named file proves nothing about
143    // content (the download path re-verifies by hash before reuse), and the
144    // honest pipeline never writes digest-named files at all — a file found
145    // under one could only be a foreign plant.
146    let downloaded = false;
147
148    // Bounded sanity on the author-controlled topic: base32 alphabet only, 32-byte
149    // payload (52 chars). Anything else is dropped, not propagated to the realtime layer.
150    let webxdc_topic = field(body, "webxdc-topic")
151        .filter(|t| t.len() == 52 && t.bytes().all(|b| b.is_ascii_uppercase() || (b'2'..=b'7').contains(&b)))
152        .map(|t| t.to_string());
153
154    // `fallback` mirrors: same ciphertext on other hosts. Author-controlled —
155    // https-only, deduped against the primary and each other, capped.
156    let mut fallback_urls: Vec<String> = Vec::new();
157    for fb in fields_all(body, "fallback") {
158        if !fb.starts_with("https://")
159            || fb.contains(char::is_whitespace)
160            || fb == url
161            || fallback_urls.iter().any(|f| f == fb)
162        {
163            continue;
164        }
165        fallback_urls.push(fb.to_string());
166        if fallback_urls.len() >= 4 {
167            break;
168        }
169    }
170
171    Some(Attachment {
172        id: basis,
173        key,
174        nonce,
175        extension,
176        name,
177        url,
178        path: path.to_string_lossy().to_string(),
179        size,
180        img_meta,
181        downloading: false,
182        downloaded,
183        verified: false, resident: false,
184        webxdc_topic,
185        group_id: None, // Community attachments use explicit key/nonce (NIP-17 technique).
186        original_hash,
187        fallback_urls,
188    })
189}
190
191/// Parse every `imeta` tag on an event into attachments, order preserved.
192/// Capped: a max-size event can carry ~1700 imeta tags, each becoming a
193/// persisted + in-STATE Attachment — bound the per-message amplification.
194pub fn attachments_from_tags<'a>(
195    tags: impl Iterator<Item = &'a Tag>,
196    download_dir: &Path,
197) -> Vec<Attachment> {
198    const MAX_ATTACHMENTS_PER_MESSAGE: usize = 32;
199    tags.filter_map(|t| attachment_from_imeta(t, download_dir))
200        .take(MAX_ATTACHMENTS_PER_MESSAGE)
201        .collect()
202}
203
204/// Strip attachment blob URLs that some clients (e.g. Armada) inline into the
205/// message content IN ADDITION to the `imeta` tag. Vector renders the file from
206/// the imeta, so the inline copy is pure redundancy: it wastes storage and makes
207/// the frontend try to web-preview a raw (often encrypted) blob URL — which can't
208/// decode, so it just errors. Display-only: the wire event and message id are
209/// untouched (we never re-sign), so this can't affect dedup or authority.
210pub fn strip_attachment_urls(content: &str, attachments: &[Attachment]) -> String {
211    if content.is_empty() || attachments.is_empty() {
212        return content.to_string();
213    }
214    let mut out = content.to_string();
215    for att in attachments {
216        if !att.url.is_empty() {
217            out = out.replace(&att.url, "");
218        }
219    }
220    if out == content {
221        return content.to_string(); // nothing matched — leave it byte-identical
222    }
223    // Removing a URL that sat on its own line leaves dangling whitespace / a
224    // trailing blank line — tidy per-line trailing space and trim the ends,
225    // keeping the surviving caption's own newlines.
226    out.lines()
227        .map(str::trim_end)
228        .collect::<Vec<_>>()
229        .join("\n")
230        .trim()
231        .to_string()
232}
233
234#[cfg(test)]
235mod tests {
236    use super::*;
237
238    fn sample(name: &str, ext: &str, with_img: bool) -> Attachment {
239        Attachment {
240            id: "h".into(),
241            key: "0".repeat(64),  // 32-byte key
242            nonce: "1".repeat(32), // 16-byte (0xChat-compatible) nonce
243            extension: ext.into(),
244            name: name.into(),
245            url: "https://blossom.example/abc".into(),
246            path: String::new(),
247            size: 4096,
248            img_meta: with_img.then(|| ImageMetadata { thumbhash: "TH".into(), width: 800, height: 600 }),
249            downloading: false,
250            downloaded: false, verified: false, resident: false,
251            webxdc_topic: None,
252            group_id: None,
253            original_hash: Some("a".repeat(64)),
254            fallback_urls: Vec::new(),
255        }
256    }
257
258    #[test]
259    fn imeta_fallback_mirrors_roundtrip() {
260        let dir = std::env::temp_dir();
261        let mut att = sample("pic.png", "png", false);
262        att.fallback_urls = vec![
263            "https://mirror-one.example/abc".to_string(),
264            "https://mirror-two.example/abc".to_string(),
265        ];
266        let parsed = attachment_from_imeta(&attachment_to_imeta(&att), &dir).unwrap();
267        assert_eq!(parsed.fallback_urls, att.fallback_urls);
268    }
269
270    #[test]
271    fn imeta_fallback_filters_junk() {
272        // Author-controlled entries: primary dups, non-https schemes and
273        // repeated mirrors are dropped, not propagated.
274        let dir = std::env::temp_dir();
275        let att = sample("pic.png", "png", false);
276        let mut entries: Vec<String> = attachment_to_imeta(&att).as_slice()[1..].to_vec();
277        entries.push(format!("fallback {}", att.url));
278        entries.push("fallback http://insecure.example/abc".to_string());
279        entries.push("fallback https://sneaky.example/a b".to_string());
280        entries.push("fallback https://mirror.example/abc".to_string());
281        entries.push("fallback https://mirror.example/abc".to_string());
282        let parsed = attachment_from_imeta(&Tag::custom(IMETA, entries), &dir).unwrap();
283        assert_eq!(parsed.fallback_urls, vec!["https://mirror.example/abc".to_string()]);
284    }
285
286    #[test]
287    fn strip_attachment_urls_removes_inlined_blob_url() {
288        let att = sample("pic.jpeg", "jpeg", false); // url = https://blossom.example/abc
289        // Trailing URL on its own line (the Armada shape) → caption survives clean.
290        assert_eq!(
291            strip_attachment_urls("Check this out\nhttps://blossom.example/abc", &[att.clone()]),
292            "Check this out"
293        );
294        // Content that is ONLY the URL collapses to empty.
295        assert_eq!(strip_attachment_urls("https://blossom.example/abc", &[att.clone()]), "");
296        // A caption that doesn't contain the URL is returned byte-identical.
297        assert_eq!(strip_attachment_urls("just a caption", &[att.clone()]), "just a caption");
298        // No attachments → untouched.
299        assert_eq!(strip_attachment_urls("hello", &[]), "hello");
300    }
301
302    #[test]
303    fn nonce_reuse_yields_distinct_identities() {
304        // Two DIFFERENT uploads sharing a (reused) nonce and lacking ox must
305        // not share an identity or an on-disk path — that cross-binding is
306        // exactly how a new image rendered as an older one.
307        let dir = std::env::temp_dir();
308        let mut a = sample("", "png", false);
309        a.original_hash = None;
310        let mut b = sample("", "png", false);
311        b.original_hash = None;
312        b.url = "https://blossom.example/DIFFERENT".into();
313
314        let pa = attachment_from_imeta(&attachment_to_imeta(&a), &dir).unwrap();
315        let pb = attachment_from_imeta(&attachment_to_imeta(&b), &dir).unwrap();
316        assert_eq!(pa.nonce, pb.nonce, "precondition: shared nonce");
317        assert_ne!(pa.id, pb.id, "identity must differ per upload");
318        assert_ne!(pa.path, pb.path, "on-disk target must differ per upload");
319    }
320
321    #[test]
322    fn ox_identity_never_claims_downloaded_on_arrival() {
323        // A file existing at {ox}.{ext} proves nothing about content (ox is
324        // the sender's CLAIM); arrival must not bind to it. The download path
325        // re-verifies by hash before any reuse.
326        let dir = tempfile::tempdir().unwrap();
327        let att = sample("", "png", false);
328        let ox = att.original_hash.clone().unwrap();
329        std::fs::write(dir.path().join(format!("{}.png", ox)), b"some other image").unwrap();
330
331        let parsed = attachment_from_imeta(&attachment_to_imeta(&att), dir.path()).unwrap();
332        assert_eq!(parsed.id, ox, "ox stays the dedup identity");
333        assert!(!parsed.downloaded, "existence of an ox-named file is not proof of download");
334    }
335
336    #[test]
337    fn digest_identity_never_trusts_planted_files() {
338        // The honest pipeline never writes files under the digest name, so a
339        // file found there could only be a foreign plant (e.g. an attachment
340        // saved under an attacker-chosen 64-hex filename). Arrival must not
341        // bind to it.
342        let dir = tempfile::tempdir().unwrap();
343        let mut att = sample("", "png", false);
344        att.original_hash = None;
345        let digest = crate::crypto::attachment_identity_basis(None, &att.nonce, &att.url);
346        std::fs::write(dir.path().join(format!("{}.png", digest)), b"planted content").unwrap();
347
348        let parsed = attachment_from_imeta(&attachment_to_imeta(&att), dir.path()).unwrap();
349        assert_eq!(parsed.id, digest);
350        assert!(!parsed.downloaded, "a digest-named file is never proof of download");
351    }
352
353    #[test]
354    fn imeta_round_trip_preserves_crypto_and_meta() {
355        let dir = std::env::temp_dir();
356        let att = sample("my report.png", "png", true);
357        let tag = attachment_to_imeta(&att);
358        let back = attachment_from_imeta(&tag, &dir).expect("parses");
359        assert_eq!(back.url, att.url);
360        assert_eq!(back.key, att.key);
361        assert_eq!(back.nonce, att.nonce);
362        assert_eq!(back.size, att.size);
363        assert_eq!(back.original_hash, att.original_hash);
364        assert_eq!(back.name, "my report.png"); // space in filename survives
365        assert_eq!(back.extension, "png");
366        assert_eq!(back.group_id, None);
367        let m = back.img_meta.expect("img meta");
368        assert_eq!((m.width, m.height), (800, 600));
369        assert_eq!(m.thumbhash, "TH");
370    }
371
372    #[test]
373    fn spoiler_and_renamed_filenames_survive_imeta() {
374        // Spoiler is detected receiver-side by a `SPOILER_` prefix on the attachment NAME,
375        // so the name (incl. that prefix, and spaces) must round-trip through imeta intact —
376        // this is what gives Community attachments spoiler/rename parity with DMs.
377        let dir = std::env::temp_dir();
378        let spoiler = attachment_from_imeta(&attachment_to_imeta(&sample("SPOILER_big reveal.png", "png", true)), &dir).unwrap();
379        assert_eq!(spoiler.name, "SPOILER_big reveal.png");
380        assert!(spoiler.name.to_uppercase().starts_with("SPOILER_"), "spoiler prefix preserved");
381        assert_eq!(spoiler.extension, "png");
382
383        let renamed = attachment_from_imeta(&attachment_to_imeta(&sample("Quarterly Report (final).pdf", "pdf", false)), &dir).unwrap();
384        assert_eq!(renamed.name, "Quarterly Report (final).pdf");
385        assert_eq!(renamed.extension, "pdf");
386    }
387
388    #[test]
389    fn field_key_match_requires_a_following_space_no_prefix_bleed() {
390        // `field(_, "m")` must NOT match a longer key like "mime ..." (shared prefix). The
391        // "key + ' '" requirement guards this; lock it so future imeta fields can't collide.
392        let entries = vec!["mime image/png".to_string(), "m image/jpeg".to_string()];
393        assert_eq!(field(&entries, "m"), Some("image/jpeg"));
394        assert_eq!(field(&entries, "mime"), Some("image/png"));
395        assert_eq!(field(&["decryption-key-x abc".to_string()], "decryption-key"), None);
396        // A key present with no value (no following space) yields None, not a panic.
397        assert_eq!(field(&["url".to_string()], "url"), None);
398    }
399
400    #[test]
401    fn multiple_imeta_tags_parse_in_order() {
402        let dir = std::env::temp_dir();
403        let tags = vec![
404            Tag::custom("z", ["pseudonym"]),
405            attachment_to_imeta(&sample("a.png", "png", false)),
406            Tag::custom("ms", ["12"]),
407            attachment_to_imeta(&sample("b.pdf", "pdf", false)),
408        ];
409        let atts = attachments_from_tags(tags.iter(), &dir);
410        assert_eq!(atts.len(), 2);
411        assert_eq!(atts[0].name, "a.png");
412        assert_eq!(atts[1].name, "b.pdf");
413        assert_eq!(atts[1].extension, "pdf");
414    }
415
416    #[test]
417    fn non_imeta_and_incomplete_tags_are_skipped() {
418        let dir = std::env::temp_dir();
419        let not_imeta = Tag::custom("e", ["abc"]);
420        assert!(attachment_from_imeta(&not_imeta, &dir).is_none());
421        // No `url` at all → None (NIP-92 requires a url).
422        let no_url = Tag::custom("imeta", ["m image/png"]);
423        assert!(attachment_from_imeta(&no_url, &dir).is_none());
424        // A url-only imeta is valid now — an unencrypted (plaintext) attachment.
425        let plain = Tag::custom("imeta", ["url https://x/y"]);
426        assert!(attachment_from_imeta(&plain, &dir).is_some(), "url-only imeta = plaintext attachment");
427    }
428
429    #[test]
430    fn imeta_crypto_params_actually_decrypt_the_ciphertext() {
431        // End-to-end attachment crypto: encrypt a plaintext with the real params, carry the
432        // key/nonce via imeta, parse them back out, and confirm they decrypt the ciphertext.
433        // This is the receiver's download path in miniature (minus the Blossom fetch).
434        let dir = std::env::temp_dir();
435        let plaintext = b"the quick brown fox jumps over 13 lazy dogs".to_vec();
436        let params = crate::crypto::generate_encryption_params();
437        let ciphertext = crate::crypto::encrypt_data(&plaintext, &params).unwrap();
438
439        let att = Attachment {
440            id: "x".into(),
441            key: params.key.clone(),
442            nonce: params.nonce.clone(),
443            extension: "txt".into(),
444            name: "note.txt".into(),
445            url: "https://blossom.example/blob".into(),
446            path: String::new(),
447            size: ciphertext.len() as u64,
448            img_meta: None,
449            downloading: false,
450            downloaded: false, verified: false, resident: false,
451            webxdc_topic: None,
452            group_id: None,
453            original_hash: Some("c".repeat(64)),
454            fallback_urls: Vec::new(),
455        };
456        let parsed = attachment_from_imeta(&attachment_to_imeta(&att), &dir).expect("parses");
457        // The parsed key/nonce (straight off the imeta) must decrypt the ciphertext.
458        let decrypted = crate::crypto::decrypt_data(&ciphertext, &parsed.key, &parsed.nonce)
459            .expect("decrypts with imeta-carried params");
460        assert_eq!(decrypted, plaintext, "round-trip plaintext matches");
461    }
462
463    #[test]
464    fn hostile_path_basis_is_rejected() {
465        // A channel member authors the imeta, so the path basis (`ox`, else `nonce`) is
466        // attacker-controlled. A non-hex / traversal basis must be refused, never joined
467        // into a filesystem path.
468        let dir = std::path::Path::new("/tmp/vector-test-dl");
469        let traversal = Tag::custom("imeta", [
470            "url https://x/y",
471            "decryption-key 00",
472            "decryption-nonce 11",
473            "ox ../../../../etc/passwd",
474        ]);
475        assert!(attachment_from_imeta(&traversal, dir).is_none(), "traversal ox rejected");
476
477        // Falls back to nonce when ox absent — a non-hex nonce is likewise rejected.
478        let bad_nonce = Tag::custom("imeta", [
479            "url https://x/y",
480            "decryption-key 00",
481            "decryption-nonce ../evil",
482        ]);
483        assert!(attachment_from_imeta(&bad_nonce, dir).is_none(), "traversal nonce rejected");
484
485        // A legitimate hex basis still parses.
486        let good = Tag::custom("imeta", [
487            "url https://x/y".to_string(),
488            "decryption-key 00".to_string(),
489            "decryption-nonce 11".to_string(),
490            format!("ox {}", "a".repeat(64)),
491        ]);
492        assert!(attachment_from_imeta(&good, dir).is_some(), "hex ox accepted");
493    }
494
495    #[test]
496    fn unencrypted_nip92_imeta_parses_as_plaintext() {
497        let dir = std::env::temp_dir();
498        // A foreign client's plain NIP-92 imeta: url + m + dim + `x` (sha256), and
499        // NO decryption params. It must parse (empty key/nonce = plaintext) so we can
500        // best-effort render it, identity keyed by the `x` content hash.
501        let x = "b".repeat(64);
502        let tag = Tag::custom("imeta", [
503            "url https://blossom.ditto.pub/abc.png".to_string(),
504            "m image/png".to_string(),
505            "dim 640x480".to_string(),
506            format!("x {x}"),
507        ]);
508        let att = attachment_from_imeta(&tag, &dir).expect("unencrypted imeta parses");
509        assert!(att.key.is_empty() && att.nonce.is_empty(), "plaintext: no keys");
510        assert_eq!(att.url, "https://blossom.ditto.pub/abc.png");
511        assert_eq!(att.id, x, "identity is the NIP-92 `x` content hash");
512        assert_eq!(att.extension, "png");
513
514        // Half-specified encryption (key without a nonce) is still refused.
515        let half = Tag::custom("imeta", ["url https://x/y", "decryption-key 00"]);
516        assert!(attachment_from_imeta(&half, &dir).is_none(), "key without nonce dropped");
517    }
518
519    #[test]
520    fn webxdc_topic_round_trips_imeta_and_garbage_is_dropped() {
521        let dir = std::env::temp_dir();
522        let topic = crate::webxdc::mint_topic_id("hash", "sender");
523        let mut att = sample("game.xdc", "xdc", false);
524        att.webxdc_topic = Some(topic.clone());
525        let back = attachment_from_imeta(&attachment_to_imeta(&att), &dir).expect("parses");
526        assert_eq!(back.webxdc_topic.as_deref(), Some(topic.as_str()));
527
528        // Author-controlled: wrong-length / off-alphabet topics are dropped, not propagated.
529        for bad in ["short", &"A".repeat(53), &"a".repeat(52), &format!("{}!", "A".repeat(51))] {
530            let mut att = sample("game.xdc", "xdc", false);
531            att.webxdc_topic = Some(bad.to_string());
532            let back = attachment_from_imeta(&attachment_to_imeta(&att), &dir).expect("parses");
533            assert_eq!(back.webxdc_topic, None, "bad topic {:?} must be dropped", bad);
534        }
535    }
536
537    #[test]
538    fn malformed_imeta_does_not_panic_and_drops_gracefully() {
539        let dir = std::env::temp_dir();
540        // Garbage entries, duplicate keys, value-less keys, weird spacing — must not panic.
541        let junk = Tag::custom("imeta", [
542            "url",                 // no value (skipped: `field` needs `key<space>`)
543            "decryption-key",      // no value
544            "random noise here",
545            "  ",
546            "url https://x/legit", // a later valid url
547        ]);
548        // The valid url is recovered (no decryption fields → plaintext); no panic.
549        let att = attachment_from_imeta(&junk, &dir).expect("recovers the valid url as plaintext");
550        assert_eq!(att.url, "https://x/legit");
551        assert!(att.key.is_empty() && att.nonce.is_empty());
552
553        // No url anywhere → None (not a panic).
554        let no_url = Tag::custom("imeta", ["m image/png", "random"]);
555        assert!(attachment_from_imeta(&no_url, &dir).is_none());
556
557        // Empty imeta (just the tag name) → None.
558        let empty = Tag::custom("imeta", Vec::<String>::new());
559        assert!(attachment_from_imeta(&empty, &dir).is_none());
560    }
561}