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 if nonce.is_empty() || nonce.len() > 128 || !nonce.bytes().all(|b| b.is_ascii_hexdigit()) {
103 return None;
104 }
105
106 let basis = crate::crypto::attachment_identity_basis(original_hash.as_deref(), &nonce, &url);
113 if basis.is_empty() || basis.len() > 128 || !basis.bytes().all(|b| b.is_ascii_hexdigit()) {
114 return None;
115 }
116 let path = download_dir.join(format!("{}.{}", basis, extension));
117 let downloaded = false;
122
123 let webxdc_topic = field(body, "webxdc-topic")
126 .filter(|t| t.len() == 52 && t.bytes().all(|b| b.is_ascii_uppercase() || (b'2'..=b'7').contains(&b)))
127 .map(|t| t.to_string());
128
129 Some(Attachment {
130 id: basis,
131 key,
132 nonce,
133 extension,
134 name,
135 url,
136 path: path.to_string_lossy().to_string(),
137 size,
138 img_meta,
139 downloading: false,
140 downloaded,
141 webxdc_topic,
142 group_id: None, original_hash,
144 scheme_version: None,
145 mls_filename: None,
146 })
147}
148
149pub fn attachments_from_tags<'a>(
153 tags: impl Iterator<Item = &'a Tag>,
154 download_dir: &Path,
155) -> Vec<Attachment> {
156 const MAX_ATTACHMENTS_PER_MESSAGE: usize = 32;
157 tags.filter_map(|t| attachment_from_imeta(t, download_dir))
158 .take(MAX_ATTACHMENTS_PER_MESSAGE)
159 .collect()
160}
161
162#[cfg(test)]
163mod tests {
164 use super::*;
165
166 fn sample(name: &str, ext: &str, with_img: bool) -> Attachment {
167 Attachment {
168 id: "h".into(),
169 key: "0".repeat(64), nonce: "1".repeat(32), extension: ext.into(),
172 name: name.into(),
173 url: "https://blossom.example/abc".into(),
174 path: String::new(),
175 size: 4096,
176 img_meta: with_img.then(|| ImageMetadata { thumbhash: "TH".into(), width: 800, height: 600 }),
177 downloading: false,
178 downloaded: false,
179 webxdc_topic: None,
180 group_id: None,
181 original_hash: Some("a".repeat(64)),
182 scheme_version: None,
183 mls_filename: None,
184 }
185 }
186
187 #[test]
188 fn nonce_reuse_yields_distinct_identities() {
189 let dir = std::env::temp_dir();
193 let mut a = sample("", "png", false);
194 a.original_hash = None;
195 let mut b = sample("", "png", false);
196 b.original_hash = None;
197 b.url = "https://blossom.example/DIFFERENT".into();
198
199 let pa = attachment_from_imeta(&attachment_to_imeta(&a), &dir).unwrap();
200 let pb = attachment_from_imeta(&attachment_to_imeta(&b), &dir).unwrap();
201 assert_eq!(pa.nonce, pb.nonce, "precondition: shared nonce");
202 assert_ne!(pa.id, pb.id, "identity must differ per upload");
203 assert_ne!(pa.path, pb.path, "on-disk target must differ per upload");
204 }
205
206 #[test]
207 fn ox_identity_never_claims_downloaded_on_arrival() {
208 let dir = tempfile::tempdir().unwrap();
212 let att = sample("", "png", false);
213 let ox = att.original_hash.clone().unwrap();
214 std::fs::write(dir.path().join(format!("{}.png", ox)), b"some other image").unwrap();
215
216 let parsed = attachment_from_imeta(&attachment_to_imeta(&att), dir.path()).unwrap();
217 assert_eq!(parsed.id, ox, "ox stays the dedup identity");
218 assert!(!parsed.downloaded, "existence of an ox-named file is not proof of download");
219 }
220
221 #[test]
222 fn digest_identity_never_trusts_planted_files() {
223 let dir = tempfile::tempdir().unwrap();
228 let mut att = sample("", "png", false);
229 att.original_hash = None;
230 let digest = crate::crypto::attachment_identity_basis(None, &att.nonce, &att.url);
231 std::fs::write(dir.path().join(format!("{}.png", digest)), b"planted content").unwrap();
232
233 let parsed = attachment_from_imeta(&attachment_to_imeta(&att), dir.path()).unwrap();
234 assert_eq!(parsed.id, digest);
235 assert!(!parsed.downloaded, "a digest-named file is never proof of download");
236 }
237
238 #[test]
239 fn imeta_round_trip_preserves_crypto_and_meta() {
240 let dir = std::env::temp_dir();
241 let att = sample("my report.png", "png", true);
242 let tag = attachment_to_imeta(&att);
243 let back = attachment_from_imeta(&tag, &dir).expect("parses");
244 assert_eq!(back.url, att.url);
245 assert_eq!(back.key, att.key);
246 assert_eq!(back.nonce, att.nonce);
247 assert_eq!(back.size, att.size);
248 assert_eq!(back.original_hash, att.original_hash);
249 assert_eq!(back.name, "my report.png"); assert_eq!(back.extension, "png");
251 assert_eq!(back.group_id, None);
252 let m = back.img_meta.expect("img meta");
253 assert_eq!((m.width, m.height), (800, 600));
254 assert_eq!(m.thumbhash, "TH");
255 }
256
257 #[test]
258 fn spoiler_and_renamed_filenames_survive_imeta() {
259 let dir = std::env::temp_dir();
263 let spoiler = attachment_from_imeta(&attachment_to_imeta(&sample("SPOILER_big reveal.png", "png", true)), &dir).unwrap();
264 assert_eq!(spoiler.name, "SPOILER_big reveal.png");
265 assert!(spoiler.name.to_uppercase().starts_with("SPOILER_"), "spoiler prefix preserved");
266 assert_eq!(spoiler.extension, "png");
267
268 let renamed = attachment_from_imeta(&attachment_to_imeta(&sample("Quarterly Report (final).pdf", "pdf", false)), &dir).unwrap();
269 assert_eq!(renamed.name, "Quarterly Report (final).pdf");
270 assert_eq!(renamed.extension, "pdf");
271 }
272
273 #[test]
274 fn field_key_match_requires_a_following_space_no_prefix_bleed() {
275 let entries = vec!["mime image/png".to_string(), "m image/jpeg".to_string()];
278 assert_eq!(field(&entries, "m"), Some("image/jpeg"));
279 assert_eq!(field(&entries, "mime"), Some("image/png"));
280 assert_eq!(field(&["decryption-key-x abc".to_string()], "decryption-key"), None);
281 assert_eq!(field(&["url".to_string()], "url"), None);
283 }
284
285 #[test]
286 fn multiple_imeta_tags_parse_in_order() {
287 let dir = std::env::temp_dir();
288 let tags = vec![
289 Tag::custom(TagKind::Custom("z".into()), ["pseudonym"]),
290 attachment_to_imeta(&sample("a.png", "png", false)),
291 Tag::custom(TagKind::Custom("ms".into()), ["12"]),
292 attachment_to_imeta(&sample("b.pdf", "pdf", false)),
293 ];
294 let atts = attachments_from_tags(tags.iter(), &dir);
295 assert_eq!(atts.len(), 2);
296 assert_eq!(atts[0].name, "a.png");
297 assert_eq!(atts[1].name, "b.pdf");
298 assert_eq!(atts[1].extension, "pdf");
299 }
300
301 #[test]
302 fn non_imeta_and_incomplete_tags_are_skipped() {
303 let dir = std::env::temp_dir();
304 let not_imeta = Tag::custom(TagKind::Custom("e".into()), ["abc"]);
305 assert!(attachment_from_imeta(¬_imeta, &dir).is_none());
306 let bad = Tag::custom(TagKind::Custom("imeta".into()), ["url https://x/y"]);
308 assert!(attachment_from_imeta(&bad, &dir).is_none());
309 }
310
311 #[test]
312 fn imeta_crypto_params_actually_decrypt_the_ciphertext() {
313 let dir = std::env::temp_dir();
317 let plaintext = b"the quick brown fox jumps over 13 lazy dogs".to_vec();
318 let params = crate::crypto::generate_encryption_params();
319 let ciphertext = crate::crypto::encrypt_data(&plaintext, ¶ms).unwrap();
320
321 let att = Attachment {
322 id: "x".into(),
323 key: params.key.clone(),
324 nonce: params.nonce.clone(),
325 extension: "txt".into(),
326 name: "note.txt".into(),
327 url: "https://blossom.example/blob".into(),
328 path: String::new(),
329 size: ciphertext.len() as u64,
330 img_meta: None,
331 downloading: false,
332 downloaded: false,
333 webxdc_topic: None,
334 group_id: None,
335 original_hash: Some("c".repeat(64)),
336 scheme_version: None,
337 mls_filename: None,
338 };
339 let parsed = attachment_from_imeta(&attachment_to_imeta(&att), &dir).expect("parses");
340 let decrypted = crate::crypto::decrypt_data(&ciphertext, &parsed.key, &parsed.nonce)
342 .expect("decrypts with imeta-carried params");
343 assert_eq!(decrypted, plaintext, "round-trip plaintext matches");
344 }
345
346 #[test]
347 fn hostile_path_basis_is_rejected() {
348 let dir = std::path::Path::new("/tmp/vector-test-dl");
352 let traversal = Tag::custom(TagKind::Custom("imeta".into()), [
353 "url https://x/y",
354 "decryption-key 00",
355 "decryption-nonce 11",
356 "ox ../../../../etc/passwd",
357 ]);
358 assert!(attachment_from_imeta(&traversal, dir).is_none(), "traversal ox rejected");
359
360 let bad_nonce = Tag::custom(TagKind::Custom("imeta".into()), [
362 "url https://x/y",
363 "decryption-key 00",
364 "decryption-nonce ../evil",
365 ]);
366 assert!(attachment_from_imeta(&bad_nonce, dir).is_none(), "traversal nonce rejected");
367
368 let good = Tag::custom(TagKind::Custom("imeta".into()), [
370 "url https://x/y".to_string(),
371 "decryption-key 00".to_string(),
372 "decryption-nonce 11".to_string(),
373 format!("ox {}", "a".repeat(64)),
374 ]);
375 assert!(attachment_from_imeta(&good, dir).is_some(), "hex ox accepted");
376 }
377
378 #[test]
379 fn webxdc_topic_round_trips_imeta_and_garbage_is_dropped() {
380 let dir = std::env::temp_dir();
381 let topic = crate::webxdc::mint_topic_id("hash", "sender");
382 let mut att = sample("game.xdc", "xdc", false);
383 att.webxdc_topic = Some(topic.clone());
384 let back = attachment_from_imeta(&attachment_to_imeta(&att), &dir).expect("parses");
385 assert_eq!(back.webxdc_topic.as_deref(), Some(topic.as_str()));
386
387 for bad in ["short", &"A".repeat(53), &"a".repeat(52), &format!("{}!", "A".repeat(51))] {
389 let mut att = sample("game.xdc", "xdc", false);
390 att.webxdc_topic = Some(bad.to_string());
391 let back = attachment_from_imeta(&attachment_to_imeta(&att), &dir).expect("parses");
392 assert_eq!(back.webxdc_topic, None, "bad topic {:?} must be dropped", bad);
393 }
394 }
395
396 #[test]
397 fn malformed_imeta_does_not_panic_and_drops_gracefully() {
398 let dir = std::env::temp_dir();
399 let junk = Tag::custom(TagKind::Custom("imeta".into()), [
401 "url", "decryption-key", "random noise here",
404 " ",
405 "url https://x/legit", ]);
407 assert!(attachment_from_imeta(&junk, &dir).is_none());
409
410 let empty = Tag::custom(TagKind::Custom("imeta".into()), Vec::<String>::new());
412 assert!(attachment_from_imeta(&empty, &dir).is_none());
413 }
414}