use std::path::Path;
use nostr_sdk::prelude::*;
use crate::types::{Attachment, ImageMetadata};
const IMETA: &str = "imeta";
pub fn attachment_to_imeta(att: &Attachment) -> Tag {
let mut fields: Vec<String> = Vec::with_capacity(10);
fields.push(format!("url {}", att.url));
fields.push(format!("m {}", crate::crypto::mime_from_extension(&att.extension)));
fields.push("encryption-algorithm aes-gcm".to_string());
fields.push(format!("decryption-key {}", att.key));
fields.push(format!("decryption-nonce {}", att.nonce));
if att.size > 0 {
fields.push(format!("size {}", att.size));
}
if let Some(h) = att.original_hash.as_deref().filter(|h| !h.is_empty()) {
fields.push(format!("ox {}", h));
}
if !att.name.is_empty() {
fields.push(format!("name {}", att.name));
}
if let Some(meta) = &att.img_meta {
if !meta.thumbhash.is_empty() {
fields.push(format!("thumb {}", meta.thumbhash));
}
fields.push(format!("dim {}x{}", meta.width, meta.height));
}
if let Some(topic) = att.webxdc_topic.as_deref().filter(|t| !t.is_empty()) {
fields.push(format!("webxdc-topic {}", topic));
}
Tag::custom(TagKind::Custom(IMETA.into()), fields)
}
fn field<'a>(entries: &'a [String], key: &str) -> Option<&'a str> {
entries.iter().find_map(|e| {
e.strip_prefix(key)
.and_then(|rest| rest.strip_prefix(' '))
})
}
pub fn attachment_from_imeta(tag: &Tag, download_dir: &Path) -> Option<Attachment> {
let entries = tag.as_slice();
if entries.first().map(String::as_str) != Some(IMETA) {
return None;
}
let body = &entries[1..];
let url = field(body, "url")?.to_string();
if url.is_empty() {
return None;
}
let key = field(body, "decryption-key")?.to_string();
let nonce = field(body, "decryption-nonce")?.to_string();
let mime = field(body, "m").unwrap_or("application/octet-stream");
let name = field(body, "name").map(crate::crypto::sanitize_filename).unwrap_or_default();
let extension = name
.rsplit('.')
.next()
.filter(|e| !e.is_empty() && *e != name)
.map(|e| e.to_lowercase())
.unwrap_or_else(|| crate::crypto::extension_from_mime(mime));
let size = field(body, "size").and_then(|s| s.parse::<u64>().ok()).unwrap_or(0);
let original_hash = field(body, "ox").map(|s| s.to_string()).filter(|s| !s.is_empty());
let img_meta = {
let thumb = field(body, "thumb").map(|s| s.to_string());
let dim = field(body, "dim").and_then(|s| {
let (w, h) = s.split_once('x')?;
Some((w.parse::<u32>().ok()?, h.parse::<u32>().ok()?))
});
match (thumb, dim) {
(Some(thumbhash), Some((width, height))) => Some(ImageMetadata { thumbhash, width, height }),
_ => None,
}
};
if nonce.is_empty() || nonce.len() > 128 || !nonce.bytes().all(|b| b.is_ascii_hexdigit()) {
return None;
}
let basis = crate::crypto::attachment_identity_basis(original_hash.as_deref(), &nonce, &url);
if basis.is_empty() || basis.len() > 128 || !basis.bytes().all(|b| b.is_ascii_hexdigit()) {
return None;
}
let path = download_dir.join(format!("{}.{}", basis, extension));
let downloaded = false;
let webxdc_topic = field(body, "webxdc-topic")
.filter(|t| t.len() == 52 && t.bytes().all(|b| b.is_ascii_uppercase() || (b'2'..=b'7').contains(&b)))
.map(|t| t.to_string());
Some(Attachment {
id: basis,
key,
nonce,
extension,
name,
url,
path: path.to_string_lossy().to_string(),
size,
img_meta,
downloading: false,
downloaded,
webxdc_topic,
group_id: None, original_hash,
scheme_version: None,
mls_filename: None,
})
}
pub fn attachments_from_tags<'a>(
tags: impl Iterator<Item = &'a Tag>,
download_dir: &Path,
) -> Vec<Attachment> {
const MAX_ATTACHMENTS_PER_MESSAGE: usize = 32;
tags.filter_map(|t| attachment_from_imeta(t, download_dir))
.take(MAX_ATTACHMENTS_PER_MESSAGE)
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
fn sample(name: &str, ext: &str, with_img: bool) -> Attachment {
Attachment {
id: "h".into(),
key: "0".repeat(64), nonce: "1".repeat(32), extension: ext.into(),
name: name.into(),
url: "https://blossom.example/abc".into(),
path: String::new(),
size: 4096,
img_meta: with_img.then(|| ImageMetadata { thumbhash: "TH".into(), width: 800, height: 600 }),
downloading: false,
downloaded: false,
webxdc_topic: None,
group_id: None,
original_hash: Some("a".repeat(64)),
scheme_version: None,
mls_filename: None,
}
}
#[test]
fn nonce_reuse_yields_distinct_identities() {
let dir = std::env::temp_dir();
let mut a = sample("", "png", false);
a.original_hash = None;
let mut b = sample("", "png", false);
b.original_hash = None;
b.url = "https://blossom.example/DIFFERENT".into();
let pa = attachment_from_imeta(&attachment_to_imeta(&a), &dir).unwrap();
let pb = attachment_from_imeta(&attachment_to_imeta(&b), &dir).unwrap();
assert_eq!(pa.nonce, pb.nonce, "precondition: shared nonce");
assert_ne!(pa.id, pb.id, "identity must differ per upload");
assert_ne!(pa.path, pb.path, "on-disk target must differ per upload");
}
#[test]
fn ox_identity_never_claims_downloaded_on_arrival() {
let dir = tempfile::tempdir().unwrap();
let att = sample("", "png", false);
let ox = att.original_hash.clone().unwrap();
std::fs::write(dir.path().join(format!("{}.png", ox)), b"some other image").unwrap();
let parsed = attachment_from_imeta(&attachment_to_imeta(&att), dir.path()).unwrap();
assert_eq!(parsed.id, ox, "ox stays the dedup identity");
assert!(!parsed.downloaded, "existence of an ox-named file is not proof of download");
}
#[test]
fn digest_identity_never_trusts_planted_files() {
let dir = tempfile::tempdir().unwrap();
let mut att = sample("", "png", false);
att.original_hash = None;
let digest = crate::crypto::attachment_identity_basis(None, &att.nonce, &att.url);
std::fs::write(dir.path().join(format!("{}.png", digest)), b"planted content").unwrap();
let parsed = attachment_from_imeta(&attachment_to_imeta(&att), dir.path()).unwrap();
assert_eq!(parsed.id, digest);
assert!(!parsed.downloaded, "a digest-named file is never proof of download");
}
#[test]
fn imeta_round_trip_preserves_crypto_and_meta() {
let dir = std::env::temp_dir();
let att = sample("my report.png", "png", true);
let tag = attachment_to_imeta(&att);
let back = attachment_from_imeta(&tag, &dir).expect("parses");
assert_eq!(back.url, att.url);
assert_eq!(back.key, att.key);
assert_eq!(back.nonce, att.nonce);
assert_eq!(back.size, att.size);
assert_eq!(back.original_hash, att.original_hash);
assert_eq!(back.name, "my report.png"); assert_eq!(back.extension, "png");
assert_eq!(back.group_id, None);
let m = back.img_meta.expect("img meta");
assert_eq!((m.width, m.height), (800, 600));
assert_eq!(m.thumbhash, "TH");
}
#[test]
fn spoiler_and_renamed_filenames_survive_imeta() {
let dir = std::env::temp_dir();
let spoiler = attachment_from_imeta(&attachment_to_imeta(&sample("SPOILER_big reveal.png", "png", true)), &dir).unwrap();
assert_eq!(spoiler.name, "SPOILER_big reveal.png");
assert!(spoiler.name.to_uppercase().starts_with("SPOILER_"), "spoiler prefix preserved");
assert_eq!(spoiler.extension, "png");
let renamed = attachment_from_imeta(&attachment_to_imeta(&sample("Quarterly Report (final).pdf", "pdf", false)), &dir).unwrap();
assert_eq!(renamed.name, "Quarterly Report (final).pdf");
assert_eq!(renamed.extension, "pdf");
}
#[test]
fn field_key_match_requires_a_following_space_no_prefix_bleed() {
let entries = vec!["mime image/png".to_string(), "m image/jpeg".to_string()];
assert_eq!(field(&entries, "m"), Some("image/jpeg"));
assert_eq!(field(&entries, "mime"), Some("image/png"));
assert_eq!(field(&["decryption-key-x abc".to_string()], "decryption-key"), None);
assert_eq!(field(&["url".to_string()], "url"), None);
}
#[test]
fn multiple_imeta_tags_parse_in_order() {
let dir = std::env::temp_dir();
let tags = vec![
Tag::custom(TagKind::Custom("z".into()), ["pseudonym"]),
attachment_to_imeta(&sample("a.png", "png", false)),
Tag::custom(TagKind::Custom("ms".into()), ["12"]),
attachment_to_imeta(&sample("b.pdf", "pdf", false)),
];
let atts = attachments_from_tags(tags.iter(), &dir);
assert_eq!(atts.len(), 2);
assert_eq!(atts[0].name, "a.png");
assert_eq!(atts[1].name, "b.pdf");
assert_eq!(atts[1].extension, "pdf");
}
#[test]
fn non_imeta_and_incomplete_tags_are_skipped() {
let dir = std::env::temp_dir();
let not_imeta = Tag::custom(TagKind::Custom("e".into()), ["abc"]);
assert!(attachment_from_imeta(¬_imeta, &dir).is_none());
let bad = Tag::custom(TagKind::Custom("imeta".into()), ["url https://x/y"]);
assert!(attachment_from_imeta(&bad, &dir).is_none());
}
#[test]
fn imeta_crypto_params_actually_decrypt_the_ciphertext() {
let dir = std::env::temp_dir();
let plaintext = b"the quick brown fox jumps over 13 lazy dogs".to_vec();
let params = crate::crypto::generate_encryption_params();
let ciphertext = crate::crypto::encrypt_data(&plaintext, ¶ms).unwrap();
let att = Attachment {
id: "x".into(),
key: params.key.clone(),
nonce: params.nonce.clone(),
extension: "txt".into(),
name: "note.txt".into(),
url: "https://blossom.example/blob".into(),
path: String::new(),
size: ciphertext.len() as u64,
img_meta: None,
downloading: false,
downloaded: false,
webxdc_topic: None,
group_id: None,
original_hash: Some("c".repeat(64)),
scheme_version: None,
mls_filename: None,
};
let parsed = attachment_from_imeta(&attachment_to_imeta(&att), &dir).expect("parses");
let decrypted = crate::crypto::decrypt_data(&ciphertext, &parsed.key, &parsed.nonce)
.expect("decrypts with imeta-carried params");
assert_eq!(decrypted, plaintext, "round-trip plaintext matches");
}
#[test]
fn hostile_path_basis_is_rejected() {
let dir = std::path::Path::new("/tmp/vector-test-dl");
let traversal = Tag::custom(TagKind::Custom("imeta".into()), [
"url https://x/y",
"decryption-key 00",
"decryption-nonce 11",
"ox ../../../../etc/passwd",
]);
assert!(attachment_from_imeta(&traversal, dir).is_none(), "traversal ox rejected");
let bad_nonce = Tag::custom(TagKind::Custom("imeta".into()), [
"url https://x/y",
"decryption-key 00",
"decryption-nonce ../evil",
]);
assert!(attachment_from_imeta(&bad_nonce, dir).is_none(), "traversal nonce rejected");
let good = Tag::custom(TagKind::Custom("imeta".into()), [
"url https://x/y".to_string(),
"decryption-key 00".to_string(),
"decryption-nonce 11".to_string(),
format!("ox {}", "a".repeat(64)),
]);
assert!(attachment_from_imeta(&good, dir).is_some(), "hex ox accepted");
}
#[test]
fn webxdc_topic_round_trips_imeta_and_garbage_is_dropped() {
let dir = std::env::temp_dir();
let topic = crate::webxdc::mint_topic_id("hash", "sender");
let mut att = sample("game.xdc", "xdc", false);
att.webxdc_topic = Some(topic.clone());
let back = attachment_from_imeta(&attachment_to_imeta(&att), &dir).expect("parses");
assert_eq!(back.webxdc_topic.as_deref(), Some(topic.as_str()));
for bad in ["short", &"A".repeat(53), &"a".repeat(52), &format!("{}!", "A".repeat(51))] {
let mut att = sample("game.xdc", "xdc", false);
att.webxdc_topic = Some(bad.to_string());
let back = attachment_from_imeta(&attachment_to_imeta(&att), &dir).expect("parses");
assert_eq!(back.webxdc_topic, None, "bad topic {:?} must be dropped", bad);
}
}
#[test]
fn malformed_imeta_does_not_panic_and_drops_gracefully() {
let dir = std::env::temp_dir();
let junk = Tag::custom(TagKind::Custom("imeta".into()), [
"url", "decryption-key", "random noise here",
" ",
"url https://x/legit", ]);
assert!(attachment_from_imeta(&junk, &dir).is_none());
let empty = Tag::custom(TagKind::Custom("imeta".into()), Vec::<String>::new());
assert!(attachment_from_imeta(&empty, &dir).is_none());
}
}