Skip to main content

vector_core/crypto/
mod.rs

1pub mod guarded_key;
2pub use guarded_key::GuardedKey;
3
4mod signer;
5pub use signer::GuardedSigner;
6
7use argon2::Argon2;
8use chacha20poly1305::{aead::Aead, ChaCha20Poly1305, KeyInit};
9use zeroize::Zeroize;
10
11/// Derive a 32-byte key from a password using Argon2id.
12/// Parameters: 150MB memory, 10 iterations (matches src-tauri).
13pub async fn hash_pass(password: &str) -> [u8; 32] {
14    let password = password.to_string();
15    tokio::task::spawn_blocking(move || {
16        let salt = b"vectorvectovectvecvev";
17        let mut output = [0u8; 32];
18
19        let params = argon2::Params::new(
20            150_000, // 150 MB
21            10,      // iterations
22            1,       // parallelism
23            Some(32),
24        ).unwrap();
25
26        let argon2 = Argon2::new(argon2::Algorithm::Argon2id, argon2::Version::V0x13, params);
27        argon2.hash_password_into(password.as_bytes(), salt, &mut output).unwrap();
28
29        output
30    }).await.unwrap()
31}
32
33/// Encrypt a string with the global ENCRYPTION_KEY (ChaCha20-Poly1305).
34pub fn encrypt_with_key(plaintext: &str, key: &[u8; 32]) -> Result<String, String> {
35    use chacha20poly1305::aead::OsRng;
36    use chacha20poly1305::AeadCore;
37
38    let cipher = ChaCha20Poly1305::new(key.into());
39    let nonce = ChaCha20Poly1305::generate_nonce(&mut OsRng);
40
41    let ciphertext = cipher.encrypt(&nonce, plaintext.as_bytes())
42        .map_err(|e| format!("Encryption failed: {}", e))?;
43
44    // Encode as hex: nonce + ciphertext
45    let mut result = hex::encode(&nonce[..]);
46    result.push_str(&hex::encode(&ciphertext));
47    Ok(result)
48}
49
50/// Decrypt a hex-encoded ciphertext with a key.
51pub fn decrypt_with_key(hex_data: &str, key: &[u8; 32]) -> Result<String, String> {
52    if hex_data.len() < 24 {
53        return Err("Ciphertext too short".to_string());
54    }
55
56    let nonce_hex = &hex_data[..24]; // 12 bytes = 24 hex chars
57    let ciphertext_hex = &hex_data[24..];
58
59    let nonce_bytes = hex::decode(nonce_hex)
60        .map_err(|e| format!("Invalid nonce hex: {}", e))?;
61    let ciphertext = hex::decode(ciphertext_hex)
62        .map_err(|e| format!("Invalid ciphertext hex: {}", e))?;
63
64    let nonce_arr: [u8; 12] = nonce_bytes.try_into()
65        .map_err(|_| "Invalid nonce length".to_string())?;
66    let nonce = chacha20poly1305::Nonce::from(nonce_arr);
67    let cipher = ChaCha20Poly1305::new(key.into());
68
69    let mut plaintext = cipher.decrypt(&nonce, ciphertext.as_ref())
70        .map_err(|_| "Decryption failed (wrong key or corrupted data)".to_string())?;
71
72    let result = String::from_utf8(plaintext.clone())
73        .map_err(|_| "Decrypted data is not valid UTF-8".to_string())?;
74
75    plaintext.zeroize();
76    Ok(result)
77}
78
79/// Check if encryption is enabled in the database.
80///
81/// Delegates to `state::resolve_encryption_enabled_from_db` — the single
82/// source of truth that handles the missing-row case consistently. The
83/// previous implementation defaulted to `false` on missing rows, which
84/// silently disagreed with `init_encryption_enabled` (defaulted to `true`)
85/// and silently mis-routed login flows after an account swap.
86pub fn is_encryption_enabled() -> bool {
87    crate::state::resolve_encryption_enabled_from_db()
88}
89
90/// Simple hex encode/decode (for crypto module internal use).
91mod hex {
92    pub fn encode(bytes: &[u8]) -> String {
93        // SIMD hex encode (NEON/SSE2, fast-pathing 32/16-byte). Identical lowercase output to the
94        // old per-byte format! loop, but it runs on every encrypt (ciphertext + nonce).
95        crate::simd::hex::bytes_to_hex_string(bytes)
96    }
97
98    pub fn decode(hex: &str) -> Result<Vec<u8>, String> {
99        if hex.len() % 2 != 0 {
100            return Err("Odd-length hex string".to_string());
101        }
102        // SIMD-validated decode (NEON/SSE2 in-register hex validation). Runs on every message read
103        // (decrypt), so the recurring path stays fast; rejects non-hex like the old scalar loop.
104        crate::simd::hex::hex_string_to_bytes_checked(hex)
105            .ok_or_else(|| "Invalid hex character".to_string())
106    }
107}
108
109// ============================================================================
110// AES-256-GCM File Encryption (for NIP-96/Blossom attachments)
111// ============================================================================
112
113/// Parameters for AES-256-GCM file encryption (hex-encoded key + nonce).
114#[derive(Debug)]
115pub struct EncryptionParams {
116    pub key: String,   // 32-byte key as hex
117    pub nonce: String, // 16-byte nonce as hex (0xChat-compatible)
118}
119
120/// Generate random AES-256-GCM encryption parameters.
121pub fn generate_encryption_params() -> EncryptionParams {
122    use rand::Rng;
123    let mut rng = rand::thread_rng();
124    let mut key: [u8; 32] = rng.gen();
125    let nonce: [u8; 16] = rng.gen();
126    let params = EncryptionParams {
127        key: hex::encode(&key),
128        nonce: hex::encode(&nonce),
129    };
130    key.iter_mut().for_each(|b| *b = 0); // zeroize
131    params
132}
133
134/// Encrypt data with AES-256-GCM using a 16-byte nonce (0xChat-compatible).
135pub fn encrypt_data(data: &[u8], params: &EncryptionParams) -> Result<Vec<u8>, String> {
136    use aes::Aes256;
137    use aes::cipher::typenum::U16;
138    use aes_gcm::{AesGcm, AeadInPlace, KeyInit as AesKeyInit};
139
140    let key_bytes = hex::decode(&params.key).map_err(|e| format!("Invalid key: {}", e))?;
141    let nonce_bytes = hex::decode(&params.nonce).map_err(|e| format!("Invalid nonce: {}", e))?;
142
143    let cipher = AesGcm::<Aes256, U16>::new_from_slice(&key_bytes)
144        .map_err(|_| "Invalid encryption key".to_string())?;
145
146    let nonce_arr: [u8; 16] = nonce_bytes.try_into()
147        .map_err(|_| "Invalid nonce length".to_string())?;
148    let nonce = aes_gcm::Nonce::<U16>::from(nonce_arr);
149
150    let mut buffer = data.to_vec();
151    let tag = cipher.encrypt_in_place_detached(&nonce, &[], &mut buffer)
152        .map_err(|_| "Encryption failed".to_string())?;
153
154    buffer.extend_from_slice(&tag);
155    Ok(buffer)
156}
157
158/// Decrypt data with AES-256-GCM using a 16-byte nonce (0xChat-compatible).
159/// Input format: ciphertext || 16-byte auth tag.
160pub fn decrypt_data(encrypted_data: &[u8], key_hex: &str, nonce_hex: &str) -> Result<Vec<u8>, String> {
161    use aes::Aes256;
162    use aes::cipher::typenum::U16;
163    use aes_gcm::{AesGcm, AeadInPlace, KeyInit as AesKeyInit};
164
165    if encrypted_data.len() < 16 {
166        return Err(format!("Invalid Input: encrypted data too small ({} bytes, minimum 16 bytes required for authentication tag)", encrypted_data.len()));
167    }
168
169    let key_bytes = hex::decode(key_hex).map_err(|e| format!("Invalid key: {}", e))?;
170    let nonce_bytes = hex::decode(nonce_hex).map_err(|e| format!("Invalid nonce: {}", e))?;
171
172    let (ciphertext, tag_bytes) = encrypted_data.split_at(encrypted_data.len() - 16);
173
174    let cipher = AesGcm::<Aes256, U16>::new_from_slice(&key_bytes)
175        .map_err(|_| "Invalid decryption key".to_string())?;
176
177    let nonce_arr: [u8; 16] = nonce_bytes.try_into()
178        .map_err(|_| "Invalid nonce length".to_string())?;
179    let nonce = aes_gcm::Nonce::<U16>::from(nonce_arr);
180    let tag_arr: [u8; 16] = tag_bytes.try_into()
181        .map_err(|_| "Invalid tag length".to_string())?;
182    let tag = aes_gcm::Tag::<U16>::from(tag_arr);
183
184    let mut buffer = ciphertext.to_vec();
185    cipher.decrypt_in_place_detached(&nonce, &[], &mut buffer, &tag)
186        .map_err(|e| e.to_string())?;
187
188    Ok(buffer)
189}
190
191/// Calculate SHA-256 hash of data, returned as hex string.
192pub fn sha256_hex(data: &[u8]) -> String {
193    use sha2::{Sha256, Digest};
194    let mut hasher = Sha256::new();
195    hasher.update(data);
196    hex::encode(&hasher.finalize())
197}
198
199/// Identity basis for a RECEIVED attachment: the sender's `ox` (plaintext
200/// hash) when provided — it's what enables honest cross-message dedup — else
201/// a digest of nonce+url. Never the raw nonce: senders can and do reuse
202/// nonces, which cross-bound DIFFERENT files to one identity (the "new image
203/// renders as an old one" class). The upload URL is unique per ciphertext,
204/// so the digest is collision-resistant even against nonce reuse. Nothing
205/// honest ever writes a file under the digest name, so existence of one is
206/// never proof of download — reuse decisions stay with the content-verified
207/// download path.
208pub fn attachment_identity_basis(ox: Option<&str>, nonce: &str, url: &str) -> String {
209    match ox.filter(|h| !h.is_empty()) {
210        Some(h) => h.to_string(),
211        None => {
212            let mut buf = Vec::with_capacity(nonce.len() + 1 + url.len());
213            buf.extend_from_slice(nonce.as_bytes());
214            buf.push(0);
215            buf.extend_from_slice(url.as_bytes());
216            sha256_hex(&buf)
217        }
218    }
219}
220
221/// Get MIME type from file extension.
222pub fn mime_from_extension(ext: &str) -> &'static str {
223    match ext.to_lowercase().as_str() {
224        "png" => "image/png",
225        "jpg" | "jpeg" => "image/jpeg",
226        "gif" => "image/gif",
227        "webp" => "image/webp",
228        "svg" => "image/svg+xml",
229        "bmp" => "image/bmp",
230        "ico" => "image/x-icon",
231        "tiff" | "tif" => "image/tiff",
232        "dng" => "image/x-adobe-dng",
233        "cr2" => "image/x-canon-cr2",
234        "nef" => "image/x-nikon-nef",
235        "arw" => "image/x-sony-arw",
236        "mp4" => "video/mp4",
237        "webm" => "video/webm",
238        "mov" => "video/quicktime",
239        "avi" => "video/x-msvideo",
240        "mkv" => "video/x-matroska",
241        "flv" => "video/x-flv",
242        "wmv" => "video/x-ms-wmv",
243        "mpg" | "mpeg" => "video/mpeg",
244        "3gp" => "video/3gpp",
245        "ogv" => "video/ogg",
246        "ts" => "video/mp2t",
247        "mp3" => "audio/mpeg",
248        "ogg" => "audio/ogg",
249        "wav" => "audio/wav",
250        "flac" => "audio/flac",
251        "m4a" => "audio/mp4",
252        "aac" => "audio/aac",
253        "wma" => "audio/x-ms-wma",
254        "opus" => "audio/opus",
255        "pdf" => "application/pdf",
256        "doc" => "application/msword",
257        "docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
258        "xls" => "application/vnd.ms-excel",
259        "xlsx" => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
260        "ppt" => "application/vnd.ms-powerpoint",
261        "pptx" => "application/vnd.openxmlformats-officedocument.presentationml.presentation",
262        "odt" => "application/vnd.oasis.opendocument.text",
263        "ods" => "application/vnd.oasis.opendocument.spreadsheet",
264        "odp" => "application/vnd.oasis.opendocument.presentation",
265        "rtf" => "application/rtf",
266        "txt" => "text/plain",
267        "md" => "text/markdown",
268        "csv" => "text/csv",
269        "json" => "application/json",
270        "xml" => "application/xml",
271        "yaml" | "yml" => "application/x-yaml",
272        "toml" => "application/toml",
273        "sql" => "application/sql",
274        "zip" => "application/zip",
275        "rar" => "application/vnd.rar",
276        "7z" => "application/x-7z-compressed",
277        "tar" => "application/x-tar",
278        "gz" => "application/gzip",
279        "bz2" => "application/x-bzip2",
280        "xz" => "application/x-xz",
281        "iso" => "application/x-iso9660-image",
282        "dmg" => "application/x-apple-diskimage",
283        "apk" => "application/vnd.android.package-archive",
284        "jar" => "application/java-archive",
285        "xdc" => "application/vnd.webxdc+zip",
286        "obj" => "model/obj",
287        "gltf" => "model/gltf+json",
288        "glb" => "model/gltf-binary",
289        "stl" => "model/stl",
290        "dae" => "model/vnd.collada+xml",
291        "js" => "text/javascript",
292        "py" => "text/x-python",
293        "rs" => "text/x-rust",
294        "go" => "text/x-go",
295        "java" => "text/x-java",
296        "c" => "text/x-c",
297        "cpp" => "text/x-c++",
298        "cs" => "text/x-csharp",
299        "rb" => "text/x-ruby",
300        "php" => "text/x-php",
301        "swift" => "text/x-swift",
302        "html" | "htm" => "text/html",
303        "css" => "text/css",
304        "exe" => "application/x-msdownload",
305        "msi" => "application/x-msi",
306        "ttf" => "font/ttf",
307        "otf" => "font/otf",
308        "woff" => "font/woff",
309        "woff2" => "font/woff2",
310        _ => "application/octet-stream",
311    }
312}
313
314/// Convert a MIME type to a file extension.
315/// Falls back to using the MIME subtype when unknown.
316pub fn extension_from_mime(mime: &str) -> String {
317    match mime.trim().to_lowercase().as_str() {
318        // Images
319        "image/png" => "png",
320        "image/jpeg" | "image/jpg" => "jpg",
321        "image/gif" => "gif",
322        "image/webp" => "webp",
323        "image/svg+xml" => "svg",
324        "image/bmp" | "image/x-ms-bmp" => "bmp",
325        "image/x-icon" | "image/vnd.microsoft.icon" => "ico",
326        "image/tiff" => "tiff",
327        "image/x-adobe-dng" => "dng",
328        "image/x-canon-cr2" => "cr2",
329        "image/x-nikon-nef" => "nef",
330        "image/x-sony-arw" => "arw",
331        // Audio
332        "audio/wav" | "audio/x-wav" | "audio/wave" => "wav",
333        "audio/mp3" | "audio/mpeg" => "mp3",
334        "audio/flac" => "flac",
335        "audio/ogg" => "ogg",
336        "audio/mp4" => "m4a",
337        "audio/aac" | "audio/x-aac" => "aac",
338        "audio/x-ms-wma" => "wma",
339        "audio/opus" => "opus",
340        // Video
341        "video/mp4" => "mp4",
342        "video/webm" => "webm",
343        "video/quicktime" => "mov",
344        "video/x-msvideo" => "avi",
345        "video/x-matroska" => "mkv",
346        "video/x-flv" => "flv",
347        "video/x-ms-wmv" => "wmv",
348        "video/mpeg" => "mpg",
349        "video/3gpp" => "3gp",
350        "video/ogg" => "ogv",
351        "video/mp2t" => "ts",
352        // Documents
353        "application/pdf" => "pdf",
354        "application/msword" => "doc",
355        "application/vnd.openxmlformats-officedocument.wordprocessingml.document" => "docx",
356        "application/vnd.ms-excel" => "xls",
357        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" => "xlsx",
358        "application/vnd.ms-powerpoint" => "ppt",
359        "application/vnd.openxmlformats-officedocument.presentationml.presentation" => "pptx",
360        "application/vnd.oasis.opendocument.text" => "odt",
361        "application/vnd.oasis.opendocument.spreadsheet" => "ods",
362        "application/vnd.oasis.opendocument.presentation" => "odp",
363        "application/rtf" => "rtf",
364        // Text/Data
365        "text/plain" => "txt",
366        "text/markdown" => "md",
367        "text/csv" => "csv",
368        "application/json" => "json",
369        "application/xml" | "text/xml" => "xml",
370        "application/x-yaml" | "text/yaml" => "yaml",
371        "application/toml" => "toml",
372        "application/sql" => "sql",
373        // Archives
374        "application/zip" => "zip",
375        "application/x-rar-compressed" | "application/vnd.rar" => "rar",
376        "application/x-7z-compressed" => "7z",
377        "application/x-tar" => "tar",
378        "application/gzip" => "gz",
379        "application/x-bzip2" => "bz2",
380        "application/x-xz" => "xz",
381        "application/x-iso9660-image" => "iso",
382        "application/x-apple-diskimage" => "dmg",
383        "application/vnd.android.package-archive" => "apk",
384        "application/java-archive" => "jar",
385        "application/vnd.webxdc+zip" => "xdc",
386        // 3D
387        "model/obj" => "obj",
388        "model/gltf+json" => "gltf",
389        "model/gltf-binary" => "glb",
390        "model/stl" | "application/sla" => "stl",
391        "model/vnd.collada+xml" => "dae",
392        // Code
393        "text/javascript" | "application/javascript" => "js",
394        "text/typescript" | "application/typescript" => "ts",
395        "text/x-python" | "application/x-python" => "py",
396        "text/x-rust" => "rs",
397        "text/x-go" => "go",
398        "text/x-java" => "java",
399        "text/x-c" => "c",
400        "text/x-c++" => "cpp",
401        "text/x-csharp" => "cs",
402        "text/x-ruby" => "rb",
403        "text/x-php" => "php",
404        "text/x-swift" => "swift",
405        // Web
406        "text/html" => "html",
407        "text/css" => "css",
408        // Other
409        "application/x-msdownload" | "application/x-dosexec" => "exe",
410        "application/x-msi" => "msi",
411        "application/x-font-ttf" | "font/ttf" => "ttf",
412        "application/x-font-otf" | "font/otf" => "otf",
413        "font/woff" => "woff",
414        "font/woff2" => "woff2",
415        // Fallback: extract subtype
416        _ => {
417            let lower = mime.trim().to_lowercase();
418            return lower.split('/').nth(1).unwrap_or("bin").to_string();
419        }
420    }.to_string()
421}
422
423/// Sanitize a filename for safe filesystem use.
424/// Strips path traversal, dangerous characters, and truncates to 64-char stem.
425pub fn sanitize_filename(name: &str) -> String {
426    let base = name.rsplit('/').next().unwrap_or(name);
427    let base = base.rsplit('\\').next().unwrap_or(base);
428
429    let sanitized: String = base.chars().filter(|c| {
430        !matches!(c, '/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|' | '\0')
431    }).collect();
432
433    let sanitized = sanitized.trim_matches(|c: char| c == '.' || c == ' ');
434
435    if sanitized.is_empty() {
436        return String::new();
437    }
438
439    if let Some(dot_pos) = sanitized.rfind('.') {
440        let stem = &sanitized[..dot_pos];
441        let ext = &sanitized[dot_pos..];
442        if stem.len() > 64 {
443            let truncated = &stem[..stem.floor_char_boundary(64)];
444            return format!("{}{}", truncated, ext);
445        }
446    } else if sanitized.len() > 64 {
447        let truncated = &sanitized[..sanitized.floor_char_boundary(64)];
448        return truncated.to_string();
449    }
450
451    sanitized.to_string()
452}
453
454/// Resolve a unique filename in `dir`, appending `-1`, `-2`, etc. on collision.
455///
456/// If `dir/name` doesn't exist, returns it as-is. Otherwise increments a
457/// counter on the stem: `photo.jpg` → `photo-1.jpg` → `photo-2.jpg` ...
458pub fn resolve_unique_filename(dir: &std::path::Path, name: &str) -> std::path::PathBuf {
459    let candidate = dir.join(name);
460    if !candidate.exists() {
461        return candidate;
462    }
463
464    let stem = std::path::Path::new(name)
465        .file_stem()
466        .and_then(|s| s.to_str())
467        .unwrap_or(name);
468    let ext = std::path::Path::new(name)
469        .extension()
470        .and_then(|s| s.to_str())
471        .unwrap_or("");
472
473    let mut counter = 1u32;
474    loop {
475        let suffixed = if ext.is_empty() {
476            format!("{}-{}", stem, counter)
477        } else {
478            format!("{}-{}.{}", stem, counter, ext)
479        };
480        let candidate = dir.join(&suffixed);
481        if !candidate.exists() {
482            return candidate;
483        }
484        counter += 1;
485    }
486}
487
488/// Decrypt a DM file attachment and save to the download directory.
489///
490/// Uses AES-GCM decryption with the key/nonce from the attachment metadata.
491/// Saves with atomic write (temp file + rename). Returns (path, content_hash).
492/// If an identical file already exists (same name + size + hash), reuses it.
493pub fn decrypt_and_save_attachment(
494    encrypted_data: &[u8],
495    key: &str,
496    nonce: &str,
497    name: &str,
498    extension: &str,
499) -> Result<(std::path::PathBuf, String), String> {
500    let decrypted = decrypt_data(encrypted_data, key, nonce)?;
501    let file_hash = sha256_hex(&decrypted);
502
503    let dir = crate::db::get_download_dir();
504    std::fs::create_dir_all(&dir).map_err(|e| format!("Failed to create directory: {}", e))?;
505
506    let target_name = if name.is_empty() {
507        format!("{}.{}", file_hash, extension)
508    } else {
509        name.to_string()
510    };
511
512    // Content dedup: reuse if same name + size + hash
513    let candidate = dir.join(&target_name);
514    let already_exists = candidate.exists()
515        && std::fs::metadata(&candidate).map(|m| m.len() == decrypted.len() as u64).unwrap_or(false)
516        && std::fs::read(&candidate).map(|b| sha256_hex(&b) == file_hash).unwrap_or(false);
517
518    if already_exists {
519        return Ok((candidate, file_hash));
520    }
521
522    let file_path = resolve_unique_filename(&dir, &target_name);
523
524    // Atomic write: temp file then rename
525    let tmp_path = dir.join(format!(".{}.{}.tmp", file_hash, extension));
526    std::fs::write(&tmp_path, &decrypted).map_err(|e| format!("Failed to write file: {}", e))?;
527    std::fs::rename(&tmp_path, &file_path).map_err(|e| format!("Failed to rename file: {}", e))?;
528
529    Ok((file_path, file_hash))
530}
531
532/// Format bytes into human-readable format (KB, MB, GB).
533pub fn format_bytes(bytes: u64) -> String {
534    const KB: f64 = 1024.0;
535    const MB: f64 = KB * 1024.0;
536    const GB: f64 = MB * 1024.0;
537
538    if bytes < KB as u64 {
539        format!("{} B", bytes)
540    } else if bytes < MB as u64 {
541        format!("{:.1} KB", bytes as f64 / KB)
542    } else if bytes < GB as u64 {
543        format!("{:.1} MB", bytes as f64 / MB)
544    } else {
545        format!("{:.1} GB", bytes as f64 / GB)
546    }
547}
548
549/// Returns true if the provided MIME type is an image/*.
550pub fn is_image_mime(mime: &str) -> bool {
551    mime.trim().starts_with("image/")
552}
553
554/// Convert a file extension to a MIME type, with an optional restriction to image/* types.
555pub fn mime_from_extension_safe(extension: &str, image_only: bool) -> Result<String, String> {
556    let mime = mime_from_extension(extension).to_string();
557    if image_only && !is_image_mime(&mime) {
558        return Err(mime);
559    }
560    Ok(mime)
561}
562
563/// Detect MIME type from file magic bytes.
564/// Supports PNG, JPEG, GIF, WebP, TIFF, ICO, and SVG.
565/// Returns "application/octet-stream" for unrecognized formats.
566pub fn mime_from_magic_bytes(bytes: &[u8]) -> &'static str {
567    if bytes.len() < 4 {
568        return "application/octet-stream";
569    }
570    match bytes[0] {
571        0x89 if bytes[1..4] == [0x50, 0x4E, 0x47] => "image/png",
572        0xFF if bytes[1..3] == [0xD8, 0xFF] => "image/jpeg",
573        b'G' if bytes.len() >= 6 && (bytes[..6] == *b"GIF87a" || bytes[..6] == *b"GIF89a") => "image/gif",
574        b'R' if bytes.len() > 12 && bytes[..4] == *b"RIFF" && bytes[8..12] == *b"WEBP" => "image/webp",
575        0x49 if bytes[1..4] == [0x49, 0x2A, 0x00] => "image/tiff",
576        0x4D if bytes[1..4] == [0x4D, 0x00, 0x2A] => "image/tiff",
577        0x00 if bytes[1..4] == [0x00, 0x01, 0x00] => "image/x-icon",
578        b'<' if bytes.starts_with(b"<?xml") || bytes.starts_with(b"<svg") => "image/svg+xml",
579        _ => "application/octet-stream",
580    }
581}
582
583// ============================================================================
584// Conditional Encryption — maybe_encrypt / maybe_decrypt
585// ============================================================================
586
587use rand::Rng;
588use chacha20poly1305::Nonce;
589
590/// Check if a string looks like encrypted content (hex-encoded ChaCha20 output).
591/// Minimum (empty message): 12 + 0 + 16 = 28 bytes = 56 hex chars.
592#[inline]
593pub fn looks_encrypted(s: &str) -> bool {
594    if s.len() < 56 { return false; }
595    is_all_lowercase_hex(s.as_bytes())
596}
597
598/// NEON: check if all bytes are lowercase hex [0-9a-f].
599#[cfg(target_arch = "aarch64")]
600#[inline]
601fn is_all_lowercase_hex(bytes: &[u8]) -> bool {
602    use std::arch::aarch64::*;
603    unsafe {
604        let mut i = 0;
605        while i + 16 <= bytes.len() {
606            let chunk = vld1q_u8(bytes.as_ptr().add(i));
607            let is_digit = vandq_u8(vcgeq_u8(chunk, vdupq_n_u8(b'0')),
608                                    vcleq_u8(chunk, vdupq_n_u8(b'9')));
609            let is_af = vandq_u8(vcgeq_u8(chunk, vdupq_n_u8(b'a')),
610                                 vcleq_u8(chunk, vdupq_n_u8(b'f')));
611            if vminvq_u8(vorrq_u8(is_digit, is_af)) == 0 { return false; }
612            i += 16;
613        }
614        while i < bytes.len() {
615            let b = bytes[i];
616            if !matches!(b, b'0'..=b'9' | b'a'..=b'f') { return false; }
617            i += 1;
618        }
619    }
620    true
621}
622
623/// SSE2: check if all bytes are lowercase hex [0-9a-f].
624#[cfg(target_arch = "x86_64")]
625#[inline]
626fn is_all_lowercase_hex(bytes: &[u8]) -> bool {
627    use std::arch::x86_64::*;
628    unsafe {
629        let mut i = 0;
630        while i + 16 <= bytes.len() {
631            let chunk = _mm_loadu_si128(bytes.as_ptr().add(i) as *const __m128i);
632            let is_digit = _mm_cmpeq_epi8(
633                _mm_subs_epu8(_mm_sub_epi8(chunk, _mm_set1_epi8(b'0' as i8)), _mm_set1_epi8(9)),
634                _mm_setzero_si128());
635            let is_af = _mm_cmpeq_epi8(
636                _mm_subs_epu8(_mm_sub_epi8(chunk, _mm_set1_epi8(b'a' as i8)), _mm_set1_epi8(5)),
637                _mm_setzero_si128());
638            if _mm_movemask_epi8(_mm_or_si128(is_digit, is_af)) != 0xFFFF { return false; }
639            i += 16;
640        }
641        while i < bytes.len() {
642            let b = bytes[i];
643            if !matches!(b, b'0'..=b'9' | b'a'..=b'f') { return false; }
644            i += 1;
645        }
646    }
647    true
648}
649
650/// Scalar fallback for platforms without SIMD.
651#[cfg(not(any(target_arch = "aarch64", target_arch = "x86_64")))]
652#[inline]
653fn is_all_lowercase_hex(bytes: &[u8]) -> bool {
654    const IS_LOWER_HEX: [bool; 256] = {
655        let mut t = [false; 256];
656        t[b'0' as usize] = true; t[b'1' as usize] = true; t[b'2' as usize] = true;
657        t[b'3' as usize] = true; t[b'4' as usize] = true; t[b'5' as usize] = true;
658        t[b'6' as usize] = true; t[b'7' as usize] = true; t[b'8' as usize] = true;
659        t[b'9' as usize] = true; t[b'a' as usize] = true; t[b'b' as usize] = true;
660        t[b'c' as usize] = true; t[b'd' as usize] = true; t[b'e' as usize] = true;
661        t[b'f' as usize] = true;
662        t
663    };
664    bytes.iter().all(|&b| IS_LOWER_HEX[b as usize])
665}
666
667/// Encrypt a string using ENCRYPTION_KEY vault (ChaCha20-Poly1305).
668/// If `password` is Some, derives a key from it instead.
669pub async fn maybe_encrypt_inner(mut input: String, password: Option<String>) -> String {
670    let mut key: [u8; 32] = if password.is_none() {
671        crate::state::ENCRYPTION_KEY.get().expect("Encryption key must be set")
672    } else {
673        hash_pass(&password.unwrap()).await
674    };
675
676    let mut rng = rand::thread_rng();
677    let nonce_bytes: [u8; 12] = rng.gen();
678
679    let cipher = ChaCha20Poly1305::new_from_slice(&key)
680        .expect("Key should be valid");
681    let nonce: Nonce = nonce_bytes.into();
682
683    let ciphertext = cipher
684        .encrypt(&nonce, input.as_bytes())
685        .expect("Encryption should not fail");
686    input.zeroize();
687
688    let mut buffer = Vec::with_capacity(nonce_bytes.len() + ciphertext.len());
689    buffer.extend_from_slice(&nonce_bytes);
690    buffer.extend_from_slice(&ciphertext);
691
692    if !crate::state::ENCRYPTION_KEY.has_key() {
693        crate::state::ENCRYPTION_KEY.set(key, &[&crate::state::MY_SECRET_KEY]);
694    }
695
696    key.zeroize();
697
698    crate::simd::hex::bytes_to_hex_string(&buffer)
699}
700
701/// Decrypt a hex-encoded ChaCha20-Poly1305 ciphertext using ENCRYPTION_KEY vault.
702/// If `password` is Some, derives a key from it instead.
703pub async fn maybe_decrypt_inner(ciphertext: String, password: Option<String>) -> Result<String, ()> {
704    let has_password = password.is_some();
705
706    let mut key: [u8; 32] = if let Some(pass) = password {
707        hash_pass(&pass).await
708    } else {
709        match crate::state::ENCRYPTION_KEY.get() {
710            Some(k) => k,
711            None => return Err(()),
712        }
713    };
714
715    let encrypted_data = crate::simd::hex::hex_string_to_bytes(ciphertext.as_str());
716    if encrypted_data.len() < 12 {
717        key.zeroize();
718        return Err(());
719    }
720
721    let (nonce_bytes, actual_ciphertext) = encrypted_data.split_at(12);
722
723    let cipher = match ChaCha20Poly1305::new_from_slice(&key) {
724        Ok(c) => c,
725        Err(_) => { key.zeroize(); return Err(()) }
726    };
727
728    let nonce_arr: [u8; 12] = match nonce_bytes.try_into() {
729        Ok(n) => n,
730        Err(_) => { key.zeroize(); return Err(()) }
731    };
732    let nonce: Nonce = nonce_arr.into();
733    let plaintext = match cipher.decrypt(&nonce, actual_ciphertext) {
734        Ok(pt) => pt,
735        Err(_) => { key.zeroize(); return Err(()) }
736    };
737
738    if has_password && !crate::state::ENCRYPTION_KEY.has_key() {
739        crate::state::ENCRYPTION_KEY.set(key, &[&crate::state::MY_SECRET_KEY]);
740    }
741
742    key.zeroize();
743
744    // SAFETY: plaintext was originally valid UTF-8, authenticated decryption ensures integrity
745    unsafe { Ok(String::from_utf8_unchecked(plaintext)) }
746}
747
748/// Conditionally encrypt content based on encryption_enabled setting.
749pub async fn maybe_encrypt(input: String) -> String {
750    if crate::state::is_encryption_enabled_fast() {
751        maybe_encrypt_inner(input, None).await
752    } else {
753        input
754    }
755}
756
757/// Conditionally decrypt content. Handles crash recovery — if decryption fails
758/// on non-encrypted-looking content, returns it as-is.
759pub async fn maybe_decrypt(input: String) -> Result<String, ()> {
760    if crate::state::is_encryption_enabled_fast() {
761        match maybe_decrypt_inner(input.clone(), None).await {
762            Ok(decrypted) => Ok(decrypted),
763            Err(_) => {
764                if looks_encrypted(&input) { Err(()) } else { Ok(input) }
765            }
766        }
767    } else {
768        if looks_encrypted(&input) {
769            match maybe_decrypt_inner(input.clone(), None).await {
770                Ok(decrypted) => Ok(decrypted),
771                Err(_) => Ok(input),
772            }
773        } else {
774            Ok(input)
775        }
776    }
777}
778
779// ============================================================================
780// Synchronous at-rest helpers (Concord tables, sync DB code)
781// ============================================================================
782//
783// `maybe_encrypt`/`maybe_decrypt` are async (they may derive a key from a
784// password). The Concord DB layer is synchronous and only ever uses the live
785// ENCRYPTION_KEY vault, so these sync variants wrap the field-level primitives
786// against the vault + the enabled flag. Discriminators for the half-migrated
787// case: a key BLOB is 32 bytes raw vs 12+len+16 encrypted; a text field uses
788// `looks_encrypted` (>=56 lowercase-hex chars).
789
790/// ChaCha20-Poly1305 encrypt raw bytes with an explicit key → `nonce(12) || ct || tag(16)`.
791pub fn encrypt_blob_with_key(plaintext: &[u8], key: &[u8; 32]) -> Result<Vec<u8>, String> {
792    use rand::Rng;
793    let cipher = ChaCha20Poly1305::new_from_slice(key).map_err(|e| e.to_string())?;
794    let nonce_bytes: [u8; 12] = rand::thread_rng().gen();
795    let nonce = chacha20poly1305::Nonce::from(nonce_bytes);
796    let ct = cipher
797        .encrypt(&nonce, plaintext)
798        .map_err(|e| format!("blob encryption failed: {}", e))?;
799    let mut out = Vec::with_capacity(12 + ct.len());
800    out.extend_from_slice(&nonce_bytes);
801    out.extend_from_slice(&ct);
802    Ok(out)
803}
804
805/// ChaCha20-Poly1305 decrypt `nonce(12) || ct || tag(16)` with an explicit key.
806pub fn decrypt_blob_with_key(stored: &[u8], key: &[u8; 32]) -> Result<Vec<u8>, String> {
807    if stored.len() < 12 + 16 {
808        return Err("blob too short to be ciphertext".to_string());
809    }
810    let cipher = ChaCha20Poly1305::new_from_slice(key).map_err(|e| e.to_string())?;
811    let (nonce_bytes, ct) = stored.split_at(12);
812    let nonce_arr: [u8; 12] = nonce_bytes.try_into().map_err(|_| "bad nonce".to_string())?;
813    let nonce = chacha20poly1305::Nonce::from(nonce_arr);
814    cipher
815        .decrypt(&nonce, ct)
816        .map_err(|_| "blob decryption failed (wrong key or corrupted)".to_string())
817}
818
819/// Encrypt a secret key BLOB for at-rest storage. Off → unchanged. Enabled but
820/// the vault is empty → Err (never silently persists a secret in plaintext).
821pub fn maybe_encrypt_blob(plaintext: &[u8]) -> Result<Vec<u8>, String> {
822    if !crate::state::is_encryption_enabled_fast() {
823        return Ok(plaintext.to_vec());
824    }
825    let mut key = crate::state::ENCRYPTION_KEY
826        .get()
827        .ok_or_else(|| "encryption enabled but key vault is empty".to_string())?;
828    let out = encrypt_blob_with_key(plaintext, &key);
829    key.zeroize();
830    out
831}
832
833/// Decrypt a secret key BLOB. Tolerant of the half-migrated DB: a 32-byte value
834/// is a raw (not-yet-wrapped / encryption-off) key, and anything that fails to
835/// authenticate is returned as-is, so a mixed store always reads back correctly.
836pub fn maybe_decrypt_blob(stored: &[u8]) -> Vec<u8> {
837    // 32 bytes = a raw key (encryption off, or a row written before the at-rest pass).
838    if stored.len() == 32 {
839        return stored.to_vec();
840    }
841    match crate::state::ENCRYPTION_KEY.get() {
842        Some(mut key) => {
843            let out = decrypt_blob_with_key(stored, &key).unwrap_or_else(|_| stored.to_vec());
844            key.zeroize();
845            out
846        }
847        None => stored.to_vec(),
848    }
849}
850
851/// Encrypt a text field for at-rest storage. Off → unchanged. Enabled but the
852/// vault is empty → Err.
853pub fn maybe_encrypt_text(plaintext: &str) -> Result<String, String> {
854    if !crate::state::is_encryption_enabled_fast() {
855        return Ok(plaintext.to_string());
856    }
857    let mut key = crate::state::ENCRYPTION_KEY
858        .get()
859        .ok_or_else(|| "encryption enabled but key vault is empty".to_string())?;
860    let out = encrypt_with_key(plaintext, &key);
861    key.zeroize();
862    out
863}
864
865/// Decrypt a text field. A value that doesn't look encrypted (or can't be
866/// decrypted) is returned as-is — pre-migration rows and encryption-off rows.
867pub fn maybe_decrypt_text(stored: &str) -> String {
868    if !looks_encrypted(stored) {
869        return stored.to_string();
870    }
871    match crate::state::ENCRYPTION_KEY.get() {
872        Some(mut key) => {
873            let out = decrypt_with_key(stored, &key).unwrap_or_else(|_| stored.to_string());
874            key.zeroize();
875            out
876        }
877        None => stored.to_string(),
878    }
879}
880
881#[cfg(test)]
882mod at_rest_tests {
883    use super::*;
884
885    #[test]
886    fn blob_roundtrip_with_explicit_key() {
887        let key = [7u8; 32];
888        let secret = [0x42u8; 32];
889        let ct = encrypt_blob_with_key(&secret, &key).unwrap();
890        assert_eq!(ct.len(), 12 + 32 + 16, "nonce + ciphertext + tag");
891        assert_ne!(&ct[12..44], &secret[..], "ciphertext must not equal plaintext");
892        assert_eq!(decrypt_blob_with_key(&ct, &key).unwrap(), secret.to_vec());
893    }
894
895    #[test]
896    fn blob_wrong_key_fails() {
897        let ct = encrypt_blob_with_key(&[1u8; 32], &[7u8; 32]).unwrap();
898        assert!(decrypt_blob_with_key(&ct, &[9u8; 32]).is_err());
899    }
900
901    #[test]
902    fn encrypted_text_is_always_detected_as_encrypted() {
903        // Even the shortest fields ("[]", "{}", "") must exceed the looks_encrypted floor
904        // so they round-trip through maybe_decrypt_text.
905        let key = [3u8; 32];
906        for s in ["", "[]", "{}", "a"] {
907            let ct = encrypt_with_key(s, &key).unwrap();
908            assert!(looks_encrypted(&ct), "ciphertext for {:?} must look encrypted", s);
909            assert_eq!(decrypt_with_key(&ct, &key).unwrap(), s);
910        }
911    }
912}
913
914// ============================================================================
915// Image Metadata — thumbhash + dimensions for file attachments
916// ============================================================================
917
918/// Re-export SIMD nearest-neighbor downsample from simd::image.
919pub use crate::simd::image::nearest_neighbor_downsample_rgba;
920
921/// Generate a thumbhash from RGBA8 pixel data.
922///
923/// Downscales to fit within 100x100 (ThumbHash's max) using fast nearest-neighbor,
924/// then hashes. Returns the base91-encoded thumbhash string.
925pub fn generate_thumbhash_from_rgba(pixels: &[u8], width: u32, height: u32) -> Option<String> {
926    use fast_thumbhash::{rgba_to_thumb_hash, base91_encode};
927
928    const MAX_DIM: u32 = 100;
929
930    let (thumb_w, thumb_h) = if width <= MAX_DIM && height <= MAX_DIM {
931        (width, height)
932    } else if width > height {
933        (MAX_DIM, (MAX_DIM * height / width).max(1))
934    } else {
935        ((MAX_DIM * width / height).max(1), MAX_DIM)
936    };
937
938    let thumbnail = if thumb_w == width && thumb_h == height {
939        pixels.to_vec()
940    } else {
941        nearest_neighbor_downsample_rgba(pixels, width, height, thumb_w, thumb_h)
942    };
943
944    let hash = rgba_to_thumb_hash(thumb_w as usize, thumb_h as usize, &thumbnail);
945    Some(base91_encode(&hash))
946}
947
948/// Decode an image with allocation limits. A tiny file declaring 60000×60000
949/// would otherwise allocate ~14 GB before a single pixel decodes — every
950/// decode of bytes we didn't author must go through this.
951///
952/// Applies EXIF orientation to the pixels. Camera photos store their pixels in
953/// the sensor's native axis plus an orientation tag; `<img>` honours that tag,
954/// but our re-encode strips all metadata, so an un-baked decode would ship the
955/// sensor pixels with no tag and the receiver sees the photo rotated. Baking it
956/// in here keeps every downstream path (compress, thumbhash, dimensions) upright.
957pub fn decode_image_bounded(bytes: &[u8]) -> Result<image::DynamicImage, String> {
958    use image::ImageDecoder;
959    let mut reader = image::ImageReader::new(std::io::Cursor::new(bytes))
960        .with_guessed_format()
961        .map_err(|e| format!("image format: {e}"))?;
962    reader.limits(bounded_image_limits());
963    let mut decoder = reader.into_decoder().map_err(|e| format!("image decode: {e}"))?;
964    // Read the tag before consuming the decoder; formats without one report NoTransforms.
965    let orientation = decoder.orientation().map_err(|e| format!("image orientation: {e}"))?;
966    let mut img = image::DynamicImage::from_decoder(decoder)
967        .map_err(|e| format!("image decode: {e}"))?;
968    img.apply_orientation(orientation);
969    Ok(img)
970}
971
972/// Shared decode limits for [`decode_image_bounded`] and call sites that need
973/// their own `ImageReader` (fixed-format decodes).
974pub fn bounded_image_limits() -> image::Limits {
975    let mut limits = image::Limits::default();
976    limits.max_image_width = Some(16_384);
977    limits.max_image_height = Some(16_384);
978    limits.max_alloc = Some(256 * 1024 * 1024);
979    limits
980}
981
982/// Generate image metadata (thumbhash + dimensions) from raw file bytes.
983///
984/// Returns None if the bytes can't be decoded as an image.
985/// Used by `send_file_dm` to automatically include preview metadata for images.
986pub fn generate_image_metadata(file_bytes: &[u8]) -> Option<crate::types::ImageMetadata> {
987    let img = decode_image_bounded(file_bytes).ok()?;
988    let width = img.width();
989    let height = img.height();
990
991    let rgba = img.to_rgba8();
992    let thumbhash = generate_thumbhash_from_rgba(rgba.as_raw(), width, height)?;
993
994    Some(crate::types::ImageMetadata {
995        thumbhash,
996        width,
997        height,
998    })
999}
1000
1001#[cfg(test)]
1002mod tests {
1003    use super::*;
1004
1005    // ========================================================================
1006    // encrypt_with_key / decrypt_with_key roundtrip tests
1007    // ========================================================================
1008
1009    fn test_key() -> [u8; 32] {
1010        [0x42u8; 32]
1011    }
1012
1013    fn alt_key() -> [u8; 32] {
1014        [0x99u8; 32]
1015    }
1016
1017    #[test]
1018    fn encrypt_decrypt_roundtrip_simple() {
1019        let key = test_key();
1020        let plaintext = "hello world";
1021        let encrypted = encrypt_with_key(plaintext, &key).expect("encryption should succeed");
1022        let decrypted = decrypt_with_key(&encrypted, &key).expect("decryption should succeed");
1023        assert_eq!(decrypted, plaintext, "roundtrip should preserve plaintext");
1024    }
1025
1026    #[test]
1027    fn encrypt_decrypt_100_random_strings() {
1028        use rand::Rng;
1029        let key = test_key();
1030        let mut rng = rand::thread_rng();
1031        for i in 0..100 {
1032            let len = rng.gen_range(1..=200);
1033            let s: String = (0..len).map(|_| rng.gen_range(0x20u8..0x7f) as char).collect();
1034            let enc = encrypt_with_key(&s, &key)
1035                .unwrap_or_else(|e| panic!("encryption failed on iteration {}: {}", i, e));
1036            let dec = decrypt_with_key(&enc, &key)
1037                .unwrap_or_else(|e| panic!("decryption failed on iteration {}: {}", i, e));
1038            assert_eq!(dec, s, "roundtrip failed on iteration {}", i);
1039        }
1040    }
1041
1042    #[test]
1043    fn encrypt_decrypt_empty_string() {
1044        let key = test_key();
1045        let encrypted = encrypt_with_key("", &key).expect("encrypting empty string should succeed");
1046        let decrypted = decrypt_with_key(&encrypted, &key).expect("decrypting empty string should succeed");
1047        assert_eq!(decrypted, "", "empty string roundtrip should produce empty string");
1048    }
1049
1050    #[test]
1051    fn encrypt_decrypt_large_string() {
1052        let key = test_key();
1053        let plaintext = "A".repeat(10 * 1024); // 10 KB
1054        let encrypted = encrypt_with_key(&plaintext, &key).expect("encrypting 10KB should succeed");
1055        let decrypted = decrypt_with_key(&encrypted, &key).expect("decrypting 10KB should succeed");
1056        assert_eq!(decrypted, plaintext, "10KB roundtrip should preserve content");
1057    }
1058
1059    #[test]
1060    fn decrypt_with_wrong_key_fails() {
1061        let key = test_key();
1062        let wrong_key = alt_key();
1063        let encrypted = encrypt_with_key("secret data", &key).expect("encryption should succeed");
1064        let result = decrypt_with_key(&encrypted, &wrong_key);
1065        assert!(result.is_err(), "decryption with wrong key should fail");
1066    }
1067
1068    #[test]
1069    fn decrypt_corrupted_ciphertext_fails() {
1070        let key = test_key();
1071        let mut encrypted = encrypt_with_key("secret data", &key).expect("encryption should succeed");
1072        // Corrupt a byte in the ciphertext portion (past the 24-char nonce)
1073        let bytes: Vec<u8> = encrypted.bytes().collect();
1074        if bytes.len() > 30 {
1075            let mut chars: Vec<char> = encrypted.chars().collect();
1076            // Flip a hex digit in the ciphertext area
1077            chars[30] = if chars[30] == '0' { 'f' } else { '0' };
1078            encrypted = chars.into_iter().collect();
1079        }
1080        let result = decrypt_with_key(&encrypted, &key);
1081        assert!(result.is_err(), "decryption of corrupted ciphertext should fail");
1082    }
1083
1084    #[test]
1085    fn different_keys_produce_different_ciphertext() {
1086        let key1 = test_key();
1087        let key2 = alt_key();
1088        let plaintext = "same plaintext";
1089        let enc1 = encrypt_with_key(plaintext, &key1).expect("enc1 should succeed");
1090        let enc2 = encrypt_with_key(plaintext, &key2).expect("enc2 should succeed");
1091        // Ciphertexts after the nonce portion should differ (nonces differ too since random)
1092        assert_ne!(enc1, enc2, "different keys should produce different ciphertext");
1093    }
1094
1095    #[test]
1096    fn nonce_is_always_different() {
1097        let key = test_key();
1098        let plaintext = "same string encrypted twice";
1099        let enc1 = encrypt_with_key(plaintext, &key).expect("enc1 should succeed");
1100        let enc2 = encrypt_with_key(plaintext, &key).expect("enc2 should succeed");
1101        // The first 24 hex chars are the nonce
1102        let nonce1 = &enc1[..24];
1103        let nonce2 = &enc2[..24];
1104        assert_ne!(nonce1, nonce2, "nonces should differ between encryptions of the same plaintext");
1105    }
1106
1107    #[test]
1108    fn unicode_content_preserved() {
1109        let key = test_key();
1110        let plaintext = "Hello \u{1F600} \u{1F4A9} \u{1F30D} \u{00E9}\u{00E0}\u{00FC} \u{4E16}\u{754C} \u{0410}\u{0411}\u{0412}";
1111        let encrypted = encrypt_with_key(plaintext, &key).expect("encrypting unicode should succeed");
1112        let decrypted = decrypt_with_key(&encrypted, &key).expect("decrypting unicode should succeed");
1113        assert_eq!(decrypted, plaintext, "unicode content should be preserved through encrypt/decrypt");
1114    }
1115
1116    #[test]
1117    fn decrypt_too_short_ciphertext_fails() {
1118        let key = test_key();
1119        let result = decrypt_with_key("abcdef", &key);
1120        assert!(result.is_err(), "ciphertext shorter than 24 hex chars should fail");
1121        assert!(result.unwrap_err().contains("too short"), "error should mention too short");
1122    }
1123
1124    #[test]
1125    fn encrypt_output_is_hex_encoded() {
1126        let key = test_key();
1127        let encrypted = encrypt_with_key("test", &key).expect("encryption should succeed");
1128        assert!(encrypted.chars().all(|c| c.is_ascii_hexdigit()),
1129            "encrypted output should be entirely hex characters");
1130    }
1131
1132    #[test]
1133    fn encrypt_output_has_correct_structure() {
1134        let key = test_key();
1135        let encrypted = encrypt_with_key("test", &key).expect("encryption should succeed");
1136        // Must be at least 24 hex chars (nonce) + some ciphertext
1137        assert!(encrypted.len() > 24,
1138            "encrypted output should have nonce (24 hex chars) plus ciphertext");
1139        // Length should be even (hex pairs)
1140        assert_eq!(encrypted.len() % 2, 0,
1141            "encrypted output length should be even (hex pairs)");
1142    }
1143
1144    #[test]
1145    fn encrypt_decrypt_special_characters() {
1146        let key = test_key();
1147        let plaintext = r#"!@#$%^&*()_+-=[]{}|;':",.<>?/\`~"#;
1148        let encrypted = encrypt_with_key(plaintext, &key).expect("encrypting special chars should succeed");
1149        let decrypted = decrypt_with_key(&encrypted, &key).expect("decrypting special chars should succeed");
1150        assert_eq!(decrypted, plaintext, "special characters should survive roundtrip");
1151    }
1152
1153    #[test]
1154    fn encrypt_decrypt_newlines_and_whitespace() {
1155        let key = test_key();
1156        let plaintext = "line1\nline2\r\nline3\ttab\0null";
1157        let encrypted = encrypt_with_key(plaintext, &key).expect("encrypting whitespace should succeed");
1158        let decrypted = decrypt_with_key(&encrypted, &key).expect("decrypting whitespace should succeed");
1159        assert_eq!(decrypted, plaintext, "whitespace and control chars should survive roundtrip");
1160    }
1161
1162    #[test]
1163    fn decrypt_invalid_hex_in_nonce_fails() {
1164        let key = test_key();
1165        // 24 chars of invalid hex + some ciphertext
1166        let bad = "zzzzzzzzzzzzzzzzzzzzzzzz0000000000000000";
1167        let result = decrypt_with_key(bad, &key);
1168        assert!(result.is_err(), "invalid hex in nonce should fail");
1169    }
1170
1171    #[test]
1172    fn decrypt_invalid_hex_in_ciphertext_fails() {
1173        let key = test_key();
1174        // Valid nonce (24 hex chars) + invalid ciphertext hex
1175        let bad = "000000000000000000000000gggggggg";
1176        let result = decrypt_with_key(bad, &key);
1177        assert!(result.is_err(), "invalid hex in ciphertext should fail");
1178    }
1179
1180    // ========================================================================
1181    // hex module tests
1182    // ========================================================================
1183
1184    #[test]
1185    fn hex_encode_decode_roundtrip() {
1186        let data = vec![0x00, 0x01, 0xff, 0x80, 0x7f];
1187        let encoded = hex::encode(&data);
1188        let decoded = hex::decode(&encoded).expect("decode should succeed");
1189        assert_eq!(decoded, data, "hex encode/decode roundtrip should preserve bytes");
1190    }
1191
1192    #[test]
1193    fn hex_decode_odd_length_error() {
1194        let result = hex::decode("abc");
1195        assert!(result.is_err(), "odd-length hex string should fail");
1196        assert!(result.unwrap_err().contains("Odd-length"), "error should mention odd-length");
1197    }
1198
1199    #[test]
1200    fn hex_decode_invalid_hex_error() {
1201        let result = hex::decode("zzzz");
1202        assert!(result.is_err(), "invalid hex characters should fail");
1203    }
1204
1205    #[test]
1206    fn hex_encode_empty() {
1207        assert_eq!(hex::encode(&[]), "", "encoding empty bytes should produce empty string");
1208    }
1209
1210    #[test]
1211    fn hex_decode_empty() {
1212        let decoded = hex::decode("").expect("decoding empty string should succeed");
1213        assert!(decoded.is_empty(), "decoding empty string should produce empty vec");
1214    }
1215
1216    // ========================================================================
1217    // hash_pass tests
1218    // ========================================================================
1219
1220    #[tokio::test]
1221    async fn hash_pass_deterministic() {
1222        let key1 = hash_pass("my_password").await;
1223        let key2 = hash_pass("my_password").await;
1224        assert_eq!(key1, key2, "same password should always produce the same key");
1225    }
1226
1227    #[tokio::test]
1228    async fn hash_pass_different_passwords_different_keys() {
1229        let key1 = hash_pass("password_one").await;
1230        let key2 = hash_pass("password_two").await;
1231        assert_ne!(key1, key2, "different passwords should produce different keys");
1232    }
1233
1234    #[tokio::test]
1235    async fn hash_pass_output_is_32_bytes() {
1236        let key = hash_pass("test_password").await;
1237        assert_eq!(key.len(), 32, "hash_pass should produce exactly 32 bytes");
1238        // Ensure it is not all zeros (i.e. hashing actually happened)
1239        assert!(key.iter().any(|&b| b != 0), "hash output should not be all zeros");
1240    }
1241
1242    #[test]
1243    fn generate_thumbhash_from_bytes_basic() {
1244        // 2x2 red pixel image in RGBA
1245        let pixels: Vec<u8> = vec![
1246            255, 0, 0, 255,  255, 0, 0, 255,
1247            255, 0, 0, 255,  255, 0, 0, 255,
1248        ];
1249        let result = super::generate_thumbhash_from_rgba(&pixels, 2, 2);
1250        assert!(result.is_some());
1251        assert!(!result.unwrap().is_empty());
1252    }
1253
1254    #[test]
1255    fn generate_image_metadata_from_bytes() {
1256        // Create a 4x4 blue PNG in memory
1257        let img = image::RgbaImage::from_pixel(4, 4, image::Rgba([0, 0, 255, 255]));
1258        let mut buf = Vec::new();
1259        let mut cursor = std::io::Cursor::new(&mut buf);
1260        img.write_to(&mut cursor, image::ImageFormat::Png).unwrap();
1261
1262        let meta = super::generate_image_metadata(&buf);
1263        assert!(meta.is_some());
1264        let meta = meta.unwrap();
1265        assert_eq!(meta.width, 4);
1266        assert_eq!(meta.height, 4);
1267        assert!(!meta.thumbhash.is_empty());
1268    }
1269
1270    #[test]
1271    fn generate_image_metadata_non_image() {
1272        let text_bytes = b"this is not an image";
1273        let meta = super::generate_image_metadata(text_bytes);
1274        assert!(meta.is_none());
1275    }
1276}