1use std::path::Path;
10use nostr_sdk::prelude::*;
11use crate::types::{Attachment, ImageMetadata};
12
13const IMETA: &str = "imeta";
14
15pub 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 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
48fn 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
57pub 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 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 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 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, original_hash,
133 scheme_version: None,
134 mls_filename: None,
135 })
136}
137
138pub 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), nonce: "1".repeat(32), 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"); 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 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 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 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(¬_imeta, &dir).is_none());
244 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 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, ¶ms).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 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 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 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 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 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 let junk = Tag::custom(TagKind::Custom("imeta".into()), [
339 "url", "decryption-key", "random noise here",
342 " ",
343 "url https://x/legit", ]);
345 assert!(attachment_from_imeta(&junk, &dir).is_none());
347
348 let empty = Tag::custom(TagKind::Custom("imeta".into()), Vec::<String>::new());
350 assert!(attachment_from_imeta(&empty, &dir).is_none());
351 }
352}