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
11pub 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, 10, 1, 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
33pub 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 let mut result = hex::encode(&nonce[..]);
46 result.push_str(&hex::encode(&ciphertext));
47 Ok(result)
48}
49
50pub 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]; 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
79pub fn is_encryption_enabled() -> bool {
87 crate::state::resolve_encryption_enabled_from_db()
88}
89
90mod hex {
92 pub fn encode(bytes: &[u8]) -> String {
93 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 crate::simd::hex::hex_string_to_bytes_checked(hex)
105 .ok_or_else(|| "Invalid hex character".to_string())
106 }
107}
108
109#[derive(Debug)]
115pub struct EncryptionParams {
116 pub key: String, pub nonce: String, }
119
120pub 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); params
132}
133
134pub 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(¶ms.key).map_err(|e| format!("Invalid key: {}", e))?;
141 let nonce_bytes = hex::decode(¶ms.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
158pub 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
191pub 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
199pub fn mime_from_extension(ext: &str) -> &'static str {
201 match ext.to_lowercase().as_str() {
202 "png" => "image/png",
203 "jpg" | "jpeg" => "image/jpeg",
204 "gif" => "image/gif",
205 "webp" => "image/webp",
206 "svg" => "image/svg+xml",
207 "bmp" => "image/bmp",
208 "ico" => "image/x-icon",
209 "tiff" | "tif" => "image/tiff",
210 "dng" => "image/x-adobe-dng",
211 "cr2" => "image/x-canon-cr2",
212 "nef" => "image/x-nikon-nef",
213 "arw" => "image/x-sony-arw",
214 "mp4" => "video/mp4",
215 "webm" => "video/webm",
216 "mov" => "video/quicktime",
217 "avi" => "video/x-msvideo",
218 "mkv" => "video/x-matroska",
219 "flv" => "video/x-flv",
220 "wmv" => "video/x-ms-wmv",
221 "mpg" | "mpeg" => "video/mpeg",
222 "3gp" => "video/3gpp",
223 "ogv" => "video/ogg",
224 "ts" => "video/mp2t",
225 "mp3" => "audio/mpeg",
226 "ogg" => "audio/ogg",
227 "wav" => "audio/wav",
228 "flac" => "audio/flac",
229 "m4a" => "audio/mp4",
230 "aac" => "audio/aac",
231 "wma" => "audio/x-ms-wma",
232 "opus" => "audio/opus",
233 "pdf" => "application/pdf",
234 "doc" => "application/msword",
235 "docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
236 "xls" => "application/vnd.ms-excel",
237 "xlsx" => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
238 "ppt" => "application/vnd.ms-powerpoint",
239 "pptx" => "application/vnd.openxmlformats-officedocument.presentationml.presentation",
240 "odt" => "application/vnd.oasis.opendocument.text",
241 "ods" => "application/vnd.oasis.opendocument.spreadsheet",
242 "odp" => "application/vnd.oasis.opendocument.presentation",
243 "rtf" => "application/rtf",
244 "txt" => "text/plain",
245 "md" => "text/markdown",
246 "csv" => "text/csv",
247 "json" => "application/json",
248 "xml" => "application/xml",
249 "yaml" | "yml" => "application/x-yaml",
250 "toml" => "application/toml",
251 "sql" => "application/sql",
252 "zip" => "application/zip",
253 "rar" => "application/vnd.rar",
254 "7z" => "application/x-7z-compressed",
255 "tar" => "application/x-tar",
256 "gz" => "application/gzip",
257 "bz2" => "application/x-bzip2",
258 "xz" => "application/x-xz",
259 "iso" => "application/x-iso9660-image",
260 "dmg" => "application/x-apple-diskimage",
261 "apk" => "application/vnd.android.package-archive",
262 "jar" => "application/java-archive",
263 "xdc" => "application/vnd.webxdc+zip",
264 "obj" => "model/obj",
265 "gltf" => "model/gltf+json",
266 "glb" => "model/gltf-binary",
267 "stl" => "model/stl",
268 "dae" => "model/vnd.collada+xml",
269 "js" => "text/javascript",
270 "py" => "text/x-python",
271 "rs" => "text/x-rust",
272 "go" => "text/x-go",
273 "java" => "text/x-java",
274 "c" => "text/x-c",
275 "cpp" => "text/x-c++",
276 "cs" => "text/x-csharp",
277 "rb" => "text/x-ruby",
278 "php" => "text/x-php",
279 "swift" => "text/x-swift",
280 "html" | "htm" => "text/html",
281 "css" => "text/css",
282 "exe" => "application/x-msdownload",
283 "msi" => "application/x-msi",
284 "ttf" => "font/ttf",
285 "otf" => "font/otf",
286 "woff" => "font/woff",
287 "woff2" => "font/woff2",
288 _ => "application/octet-stream",
289 }
290}
291
292pub fn extension_from_mime(mime: &str) -> String {
295 match mime.trim().to_lowercase().as_str() {
296 "image/png" => "png",
298 "image/jpeg" | "image/jpg" => "jpg",
299 "image/gif" => "gif",
300 "image/webp" => "webp",
301 "image/svg+xml" => "svg",
302 "image/bmp" | "image/x-ms-bmp" => "bmp",
303 "image/x-icon" | "image/vnd.microsoft.icon" => "ico",
304 "image/tiff" => "tiff",
305 "image/x-adobe-dng" => "dng",
306 "image/x-canon-cr2" => "cr2",
307 "image/x-nikon-nef" => "nef",
308 "image/x-sony-arw" => "arw",
309 "audio/wav" | "audio/x-wav" | "audio/wave" => "wav",
311 "audio/mp3" | "audio/mpeg" => "mp3",
312 "audio/flac" => "flac",
313 "audio/ogg" => "ogg",
314 "audio/mp4" => "m4a",
315 "audio/aac" | "audio/x-aac" => "aac",
316 "audio/x-ms-wma" => "wma",
317 "audio/opus" => "opus",
318 "video/mp4" => "mp4",
320 "video/webm" => "webm",
321 "video/quicktime" => "mov",
322 "video/x-msvideo" => "avi",
323 "video/x-matroska" => "mkv",
324 "video/x-flv" => "flv",
325 "video/x-ms-wmv" => "wmv",
326 "video/mpeg" => "mpg",
327 "video/3gpp" => "3gp",
328 "video/ogg" => "ogv",
329 "video/mp2t" => "ts",
330 "application/pdf" => "pdf",
332 "application/msword" => "doc",
333 "application/vnd.openxmlformats-officedocument.wordprocessingml.document" => "docx",
334 "application/vnd.ms-excel" => "xls",
335 "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" => "xlsx",
336 "application/vnd.ms-powerpoint" => "ppt",
337 "application/vnd.openxmlformats-officedocument.presentationml.presentation" => "pptx",
338 "application/vnd.oasis.opendocument.text" => "odt",
339 "application/vnd.oasis.opendocument.spreadsheet" => "ods",
340 "application/vnd.oasis.opendocument.presentation" => "odp",
341 "application/rtf" => "rtf",
342 "text/plain" => "txt",
344 "text/markdown" => "md",
345 "text/csv" => "csv",
346 "application/json" => "json",
347 "application/xml" | "text/xml" => "xml",
348 "application/x-yaml" | "text/yaml" => "yaml",
349 "application/toml" => "toml",
350 "application/sql" => "sql",
351 "application/zip" => "zip",
353 "application/x-rar-compressed" | "application/vnd.rar" => "rar",
354 "application/x-7z-compressed" => "7z",
355 "application/x-tar" => "tar",
356 "application/gzip" => "gz",
357 "application/x-bzip2" => "bz2",
358 "application/x-xz" => "xz",
359 "application/x-iso9660-image" => "iso",
360 "application/x-apple-diskimage" => "dmg",
361 "application/vnd.android.package-archive" => "apk",
362 "application/java-archive" => "jar",
363 "application/vnd.webxdc+zip" => "xdc",
364 "model/obj" => "obj",
366 "model/gltf+json" => "gltf",
367 "model/gltf-binary" => "glb",
368 "model/stl" | "application/sla" => "stl",
369 "model/vnd.collada+xml" => "dae",
370 "text/javascript" | "application/javascript" => "js",
372 "text/typescript" | "application/typescript" => "ts",
373 "text/x-python" | "application/x-python" => "py",
374 "text/x-rust" => "rs",
375 "text/x-go" => "go",
376 "text/x-java" => "java",
377 "text/x-c" => "c",
378 "text/x-c++" => "cpp",
379 "text/x-csharp" => "cs",
380 "text/x-ruby" => "rb",
381 "text/x-php" => "php",
382 "text/x-swift" => "swift",
383 "text/html" => "html",
385 "text/css" => "css",
386 "application/x-msdownload" | "application/x-dosexec" => "exe",
388 "application/x-msi" => "msi",
389 "application/x-font-ttf" | "font/ttf" => "ttf",
390 "application/x-font-otf" | "font/otf" => "otf",
391 "font/woff" => "woff",
392 "font/woff2" => "woff2",
393 _ => {
395 let lower = mime.trim().to_lowercase();
396 return lower.split('/').nth(1).unwrap_or("bin").to_string();
397 }
398 }.to_string()
399}
400
401pub fn sanitize_filename(name: &str) -> String {
404 let base = name.rsplit('/').next().unwrap_or(name);
405 let base = base.rsplit('\\').next().unwrap_or(base);
406
407 let sanitized: String = base.chars().filter(|c| {
408 !matches!(c, '/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|' | '\0')
409 }).collect();
410
411 let sanitized = sanitized.trim_matches(|c: char| c == '.' || c == ' ');
412
413 if sanitized.is_empty() {
414 return String::new();
415 }
416
417 if let Some(dot_pos) = sanitized.rfind('.') {
418 let stem = &sanitized[..dot_pos];
419 let ext = &sanitized[dot_pos..];
420 if stem.len() > 64 {
421 let truncated = &stem[..stem.floor_char_boundary(64)];
422 return format!("{}{}", truncated, ext);
423 }
424 } else if sanitized.len() > 64 {
425 let truncated = &sanitized[..sanitized.floor_char_boundary(64)];
426 return truncated.to_string();
427 }
428
429 sanitized.to_string()
430}
431
432pub fn resolve_unique_filename(dir: &std::path::Path, name: &str) -> std::path::PathBuf {
437 let candidate = dir.join(name);
438 if !candidate.exists() {
439 return candidate;
440 }
441
442 let stem = std::path::Path::new(name)
443 .file_stem()
444 .and_then(|s| s.to_str())
445 .unwrap_or(name);
446 let ext = std::path::Path::new(name)
447 .extension()
448 .and_then(|s| s.to_str())
449 .unwrap_or("");
450
451 let mut counter = 1u32;
452 loop {
453 let suffixed = if ext.is_empty() {
454 format!("{}-{}", stem, counter)
455 } else {
456 format!("{}-{}.{}", stem, counter, ext)
457 };
458 let candidate = dir.join(&suffixed);
459 if !candidate.exists() {
460 return candidate;
461 }
462 counter += 1;
463 }
464}
465
466pub fn decrypt_and_save_attachment(
472 encrypted_data: &[u8],
473 key: &str,
474 nonce: &str,
475 name: &str,
476 extension: &str,
477) -> Result<(std::path::PathBuf, String), String> {
478 let decrypted = decrypt_data(encrypted_data, key, nonce)?;
479 let file_hash = sha256_hex(&decrypted);
480
481 let dir = crate::db::get_download_dir();
482 std::fs::create_dir_all(&dir).map_err(|e| format!("Failed to create directory: {}", e))?;
483
484 let target_name = if name.is_empty() {
485 format!("{}.{}", file_hash, extension)
486 } else {
487 name.to_string()
488 };
489
490 let candidate = dir.join(&target_name);
492 let already_exists = candidate.exists()
493 && std::fs::metadata(&candidate).map(|m| m.len() == decrypted.len() as u64).unwrap_or(false)
494 && std::fs::read(&candidate).map(|b| sha256_hex(&b) == file_hash).unwrap_or(false);
495
496 if already_exists {
497 return Ok((candidate, file_hash));
498 }
499
500 let file_path = resolve_unique_filename(&dir, &target_name);
501
502 let tmp_path = dir.join(format!(".{}.{}.tmp", file_hash, extension));
504 std::fs::write(&tmp_path, &decrypted).map_err(|e| format!("Failed to write file: {}", e))?;
505 std::fs::rename(&tmp_path, &file_path).map_err(|e| format!("Failed to rename file: {}", e))?;
506
507 Ok((file_path, file_hash))
508}
509
510pub fn format_bytes(bytes: u64) -> String {
512 const KB: f64 = 1024.0;
513 const MB: f64 = KB * 1024.0;
514 const GB: f64 = MB * 1024.0;
515
516 if bytes < KB as u64 {
517 format!("{} B", bytes)
518 } else if bytes < MB as u64 {
519 format!("{:.1} KB", bytes as f64 / KB)
520 } else if bytes < GB as u64 {
521 format!("{:.1} MB", bytes as f64 / MB)
522 } else {
523 format!("{:.1} GB", bytes as f64 / GB)
524 }
525}
526
527pub fn is_image_mime(mime: &str) -> bool {
529 mime.trim().starts_with("image/")
530}
531
532pub fn mime_from_extension_safe(extension: &str, image_only: bool) -> Result<String, String> {
534 let mime = mime_from_extension(extension).to_string();
535 if image_only && !is_image_mime(&mime) {
536 return Err(mime);
537 }
538 Ok(mime)
539}
540
541pub fn mime_from_magic_bytes(bytes: &[u8]) -> &'static str {
545 if bytes.len() < 4 {
546 return "application/octet-stream";
547 }
548 match bytes[0] {
549 0x89 if bytes[1..4] == [0x50, 0x4E, 0x47] => "image/png",
550 0xFF if bytes[1..3] == [0xD8, 0xFF] => "image/jpeg",
551 b'G' if bytes.len() >= 6 && (bytes[..6] == *b"GIF87a" || bytes[..6] == *b"GIF89a") => "image/gif",
552 b'R' if bytes.len() > 12 && bytes[..4] == *b"RIFF" && bytes[8..12] == *b"WEBP" => "image/webp",
553 0x49 if bytes[1..4] == [0x49, 0x2A, 0x00] => "image/tiff",
554 0x4D if bytes[1..4] == [0x4D, 0x00, 0x2A] => "image/tiff",
555 0x00 if bytes[1..4] == [0x00, 0x01, 0x00] => "image/x-icon",
556 b'<' if bytes.starts_with(b"<?xml") || bytes.starts_with(b"<svg") => "image/svg+xml",
557 _ => "application/octet-stream",
558 }
559}
560
561use rand::Rng;
566use chacha20poly1305::Nonce;
567
568#[inline]
571pub fn looks_encrypted(s: &str) -> bool {
572 if s.len() < 56 { return false; }
573 is_all_lowercase_hex(s.as_bytes())
574}
575
576#[cfg(target_arch = "aarch64")]
578#[inline]
579fn is_all_lowercase_hex(bytes: &[u8]) -> bool {
580 use std::arch::aarch64::*;
581 unsafe {
582 let mut i = 0;
583 while i + 16 <= bytes.len() {
584 let chunk = vld1q_u8(bytes.as_ptr().add(i));
585 let is_digit = vandq_u8(vcgeq_u8(chunk, vdupq_n_u8(b'0')),
586 vcleq_u8(chunk, vdupq_n_u8(b'9')));
587 let is_af = vandq_u8(vcgeq_u8(chunk, vdupq_n_u8(b'a')),
588 vcleq_u8(chunk, vdupq_n_u8(b'f')));
589 if vminvq_u8(vorrq_u8(is_digit, is_af)) == 0 { return false; }
590 i += 16;
591 }
592 while i < bytes.len() {
593 let b = bytes[i];
594 if !matches!(b, b'0'..=b'9' | b'a'..=b'f') { return false; }
595 i += 1;
596 }
597 }
598 true
599}
600
601#[cfg(target_arch = "x86_64")]
603#[inline]
604fn is_all_lowercase_hex(bytes: &[u8]) -> bool {
605 use std::arch::x86_64::*;
606 unsafe {
607 let mut i = 0;
608 while i + 16 <= bytes.len() {
609 let chunk = _mm_loadu_si128(bytes.as_ptr().add(i) as *const __m128i);
610 let is_digit = _mm_cmpeq_epi8(
611 _mm_subs_epu8(_mm_sub_epi8(chunk, _mm_set1_epi8(b'0' as i8)), _mm_set1_epi8(9)),
612 _mm_setzero_si128());
613 let is_af = _mm_cmpeq_epi8(
614 _mm_subs_epu8(_mm_sub_epi8(chunk, _mm_set1_epi8(b'a' as i8)), _mm_set1_epi8(5)),
615 _mm_setzero_si128());
616 if _mm_movemask_epi8(_mm_or_si128(is_digit, is_af)) != 0xFFFF { return false; }
617 i += 16;
618 }
619 while i < bytes.len() {
620 let b = bytes[i];
621 if !matches!(b, b'0'..=b'9' | b'a'..=b'f') { return false; }
622 i += 1;
623 }
624 }
625 true
626}
627
628#[cfg(not(any(target_arch = "aarch64", target_arch = "x86_64")))]
630#[inline]
631fn is_all_lowercase_hex(bytes: &[u8]) -> bool {
632 const IS_LOWER_HEX: [bool; 256] = {
633 let mut t = [false; 256];
634 t[b'0' as usize] = true; t[b'1' as usize] = true; t[b'2' as usize] = true;
635 t[b'3' as usize] = true; t[b'4' as usize] = true; t[b'5' as usize] = true;
636 t[b'6' as usize] = true; t[b'7' as usize] = true; t[b'8' as usize] = true;
637 t[b'9' as usize] = true; t[b'a' as usize] = true; t[b'b' as usize] = true;
638 t[b'c' as usize] = true; t[b'd' as usize] = true; t[b'e' as usize] = true;
639 t[b'f' as usize] = true;
640 t
641 };
642 bytes.iter().all(|&b| IS_LOWER_HEX[b as usize])
643}
644
645pub async fn maybe_encrypt_inner(mut input: String, password: Option<String>) -> String {
648 let mut key: [u8; 32] = if password.is_none() {
649 crate::state::ENCRYPTION_KEY.get().expect("Encryption key must be set")
650 } else {
651 hash_pass(&password.unwrap()).await
652 };
653
654 let mut rng = rand::thread_rng();
655 let nonce_bytes: [u8; 12] = rng.gen();
656
657 let cipher = ChaCha20Poly1305::new_from_slice(&key)
658 .expect("Key should be valid");
659 let nonce: Nonce = nonce_bytes.into();
660
661 let ciphertext = cipher
662 .encrypt(&nonce, input.as_bytes())
663 .expect("Encryption should not fail");
664 input.zeroize();
665
666 let mut buffer = Vec::with_capacity(nonce_bytes.len() + ciphertext.len());
667 buffer.extend_from_slice(&nonce_bytes);
668 buffer.extend_from_slice(&ciphertext);
669
670 if !crate::state::ENCRYPTION_KEY.has_key() {
671 crate::state::ENCRYPTION_KEY.set(key, &[&crate::state::MY_SECRET_KEY]);
672 }
673
674 key.zeroize();
675
676 crate::simd::hex::bytes_to_hex_string(&buffer)
677}
678
679pub async fn maybe_decrypt_inner(ciphertext: String, password: Option<String>) -> Result<String, ()> {
682 let has_password = password.is_some();
683
684 let mut key: [u8; 32] = if let Some(pass) = password {
685 hash_pass(&pass).await
686 } else {
687 match crate::state::ENCRYPTION_KEY.get() {
688 Some(k) => k,
689 None => return Err(()),
690 }
691 };
692
693 let encrypted_data = crate::simd::hex::hex_string_to_bytes(ciphertext.as_str());
694 if encrypted_data.len() < 12 {
695 key.zeroize();
696 return Err(());
697 }
698
699 let (nonce_bytes, actual_ciphertext) = encrypted_data.split_at(12);
700
701 let cipher = match ChaCha20Poly1305::new_from_slice(&key) {
702 Ok(c) => c,
703 Err(_) => { key.zeroize(); return Err(()) }
704 };
705
706 let nonce_arr: [u8; 12] = match nonce_bytes.try_into() {
707 Ok(n) => n,
708 Err(_) => { key.zeroize(); return Err(()) }
709 };
710 let nonce: Nonce = nonce_arr.into();
711 let plaintext = match cipher.decrypt(&nonce, actual_ciphertext) {
712 Ok(pt) => pt,
713 Err(_) => { key.zeroize(); return Err(()) }
714 };
715
716 if has_password && !crate::state::ENCRYPTION_KEY.has_key() {
717 crate::state::ENCRYPTION_KEY.set(key, &[&crate::state::MY_SECRET_KEY]);
718 }
719
720 key.zeroize();
721
722 unsafe { Ok(String::from_utf8_unchecked(plaintext)) }
724}
725
726pub async fn maybe_encrypt(input: String) -> String {
728 if crate::state::is_encryption_enabled_fast() {
729 maybe_encrypt_inner(input, None).await
730 } else {
731 input
732 }
733}
734
735pub async fn maybe_decrypt(input: String) -> Result<String, ()> {
738 if crate::state::is_encryption_enabled_fast() {
739 match maybe_decrypt_inner(input.clone(), None).await {
740 Ok(decrypted) => Ok(decrypted),
741 Err(_) => {
742 if looks_encrypted(&input) { Err(()) } else { Ok(input) }
743 }
744 }
745 } else {
746 if looks_encrypted(&input) {
747 match maybe_decrypt_inner(input.clone(), None).await {
748 Ok(decrypted) => Ok(decrypted),
749 Err(_) => Ok(input),
750 }
751 } else {
752 Ok(input)
753 }
754 }
755}
756
757pub fn encrypt_blob_with_key(plaintext: &[u8], key: &[u8; 32]) -> Result<Vec<u8>, String> {
770 use rand::Rng;
771 let cipher = ChaCha20Poly1305::new_from_slice(key).map_err(|e| e.to_string())?;
772 let nonce_bytes: [u8; 12] = rand::thread_rng().gen();
773 let nonce = chacha20poly1305::Nonce::from(nonce_bytes);
774 let ct = cipher
775 .encrypt(&nonce, plaintext)
776 .map_err(|e| format!("blob encryption failed: {}", e))?;
777 let mut out = Vec::with_capacity(12 + ct.len());
778 out.extend_from_slice(&nonce_bytes);
779 out.extend_from_slice(&ct);
780 Ok(out)
781}
782
783pub fn decrypt_blob_with_key(stored: &[u8], key: &[u8; 32]) -> Result<Vec<u8>, String> {
785 if stored.len() < 12 + 16 {
786 return Err("blob too short to be ciphertext".to_string());
787 }
788 let cipher = ChaCha20Poly1305::new_from_slice(key).map_err(|e| e.to_string())?;
789 let (nonce_bytes, ct) = stored.split_at(12);
790 let nonce_arr: [u8; 12] = nonce_bytes.try_into().map_err(|_| "bad nonce".to_string())?;
791 let nonce = chacha20poly1305::Nonce::from(nonce_arr);
792 cipher
793 .decrypt(&nonce, ct)
794 .map_err(|_| "blob decryption failed (wrong key or corrupted)".to_string())
795}
796
797pub fn maybe_encrypt_blob(plaintext: &[u8]) -> Result<Vec<u8>, String> {
800 if !crate::state::is_encryption_enabled_fast() {
801 return Ok(plaintext.to_vec());
802 }
803 let mut key = crate::state::ENCRYPTION_KEY
804 .get()
805 .ok_or_else(|| "encryption enabled but key vault is empty".to_string())?;
806 let out = encrypt_blob_with_key(plaintext, &key);
807 key.zeroize();
808 out
809}
810
811pub fn maybe_decrypt_blob(stored: &[u8]) -> Vec<u8> {
815 if stored.len() == 32 {
817 return stored.to_vec();
818 }
819 match crate::state::ENCRYPTION_KEY.get() {
820 Some(mut key) => {
821 let out = decrypt_blob_with_key(stored, &key).unwrap_or_else(|_| stored.to_vec());
822 key.zeroize();
823 out
824 }
825 None => stored.to_vec(),
826 }
827}
828
829pub fn maybe_encrypt_text(plaintext: &str) -> Result<String, String> {
832 if !crate::state::is_encryption_enabled_fast() {
833 return Ok(plaintext.to_string());
834 }
835 let mut key = crate::state::ENCRYPTION_KEY
836 .get()
837 .ok_or_else(|| "encryption enabled but key vault is empty".to_string())?;
838 let out = encrypt_with_key(plaintext, &key);
839 key.zeroize();
840 out
841}
842
843pub fn maybe_decrypt_text(stored: &str) -> String {
846 if !looks_encrypted(stored) {
847 return stored.to_string();
848 }
849 match crate::state::ENCRYPTION_KEY.get() {
850 Some(mut key) => {
851 let out = decrypt_with_key(stored, &key).unwrap_or_else(|_| stored.to_string());
852 key.zeroize();
853 out
854 }
855 None => stored.to_string(),
856 }
857}
858
859#[cfg(test)]
860mod at_rest_tests {
861 use super::*;
862
863 #[test]
864 fn blob_roundtrip_with_explicit_key() {
865 let key = [7u8; 32];
866 let secret = [0x42u8; 32];
867 let ct = encrypt_blob_with_key(&secret, &key).unwrap();
868 assert_eq!(ct.len(), 12 + 32 + 16, "nonce + ciphertext + tag");
869 assert_ne!(&ct[12..44], &secret[..], "ciphertext must not equal plaintext");
870 assert_eq!(decrypt_blob_with_key(&ct, &key).unwrap(), secret.to_vec());
871 }
872
873 #[test]
874 fn blob_wrong_key_fails() {
875 let ct = encrypt_blob_with_key(&[1u8; 32], &[7u8; 32]).unwrap();
876 assert!(decrypt_blob_with_key(&ct, &[9u8; 32]).is_err());
877 }
878
879 #[test]
880 fn encrypted_text_is_always_detected_as_encrypted() {
881 let key = [3u8; 32];
884 for s in ["", "[]", "{}", "a"] {
885 let ct = encrypt_with_key(s, &key).unwrap();
886 assert!(looks_encrypted(&ct), "ciphertext for {:?} must look encrypted", s);
887 assert_eq!(decrypt_with_key(&ct, &key).unwrap(), s);
888 }
889 }
890}
891
892pub use crate::simd::image::nearest_neighbor_downsample_rgba;
898
899pub fn generate_thumbhash_from_rgba(pixels: &[u8], width: u32, height: u32) -> Option<String> {
904 use fast_thumbhash::{rgba_to_thumb_hash, base91_encode};
905
906 const MAX_DIM: u32 = 100;
907
908 let (thumb_w, thumb_h) = if width <= MAX_DIM && height <= MAX_DIM {
909 (width, height)
910 } else if width > height {
911 (MAX_DIM, (MAX_DIM * height / width).max(1))
912 } else {
913 ((MAX_DIM * width / height).max(1), MAX_DIM)
914 };
915
916 let thumbnail = if thumb_w == width && thumb_h == height {
917 pixels.to_vec()
918 } else {
919 nearest_neighbor_downsample_rgba(pixels, width, height, thumb_w, thumb_h)
920 };
921
922 let hash = rgba_to_thumb_hash(thumb_w as usize, thumb_h as usize, &thumbnail);
923 Some(base91_encode(&hash))
924}
925
926pub fn decode_image_bounded(bytes: &[u8]) -> Result<image::DynamicImage, String> {
930 let mut reader = image::ImageReader::new(std::io::Cursor::new(bytes))
931 .with_guessed_format()
932 .map_err(|e| format!("image format: {e}"))?;
933 reader.limits(bounded_image_limits());
934 reader.decode().map_err(|e| format!("image decode: {e}"))
935}
936
937pub fn bounded_image_limits() -> image::Limits {
940 let mut limits = image::Limits::default();
941 limits.max_image_width = Some(16_384);
942 limits.max_image_height = Some(16_384);
943 limits.max_alloc = Some(256 * 1024 * 1024);
944 limits
945}
946
947pub fn generate_image_metadata(file_bytes: &[u8]) -> Option<crate::types::ImageMetadata> {
952 let img = decode_image_bounded(file_bytes).ok()?;
953 let width = img.width();
954 let height = img.height();
955
956 let rgba = img.to_rgba8();
957 let thumbhash = generate_thumbhash_from_rgba(rgba.as_raw(), width, height)?;
958
959 Some(crate::types::ImageMetadata {
960 thumbhash,
961 width,
962 height,
963 })
964}
965
966#[cfg(test)]
967mod tests {
968 use super::*;
969
970 fn test_key() -> [u8; 32] {
975 [0x42u8; 32]
976 }
977
978 fn alt_key() -> [u8; 32] {
979 [0x99u8; 32]
980 }
981
982 #[test]
983 fn encrypt_decrypt_roundtrip_simple() {
984 let key = test_key();
985 let plaintext = "hello world";
986 let encrypted = encrypt_with_key(plaintext, &key).expect("encryption should succeed");
987 let decrypted = decrypt_with_key(&encrypted, &key).expect("decryption should succeed");
988 assert_eq!(decrypted, plaintext, "roundtrip should preserve plaintext");
989 }
990
991 #[test]
992 fn encrypt_decrypt_100_random_strings() {
993 use rand::Rng;
994 let key = test_key();
995 let mut rng = rand::thread_rng();
996 for i in 0..100 {
997 let len = rng.gen_range(1..=200);
998 let s: String = (0..len).map(|_| rng.gen_range(0x20u8..0x7f) as char).collect();
999 let enc = encrypt_with_key(&s, &key)
1000 .unwrap_or_else(|e| panic!("encryption failed on iteration {}: {}", i, e));
1001 let dec = decrypt_with_key(&enc, &key)
1002 .unwrap_or_else(|e| panic!("decryption failed on iteration {}: {}", i, e));
1003 assert_eq!(dec, s, "roundtrip failed on iteration {}", i);
1004 }
1005 }
1006
1007 #[test]
1008 fn encrypt_decrypt_empty_string() {
1009 let key = test_key();
1010 let encrypted = encrypt_with_key("", &key).expect("encrypting empty string should succeed");
1011 let decrypted = decrypt_with_key(&encrypted, &key).expect("decrypting empty string should succeed");
1012 assert_eq!(decrypted, "", "empty string roundtrip should produce empty string");
1013 }
1014
1015 #[test]
1016 fn encrypt_decrypt_large_string() {
1017 let key = test_key();
1018 let plaintext = "A".repeat(10 * 1024); let encrypted = encrypt_with_key(&plaintext, &key).expect("encrypting 10KB should succeed");
1020 let decrypted = decrypt_with_key(&encrypted, &key).expect("decrypting 10KB should succeed");
1021 assert_eq!(decrypted, plaintext, "10KB roundtrip should preserve content");
1022 }
1023
1024 #[test]
1025 fn decrypt_with_wrong_key_fails() {
1026 let key = test_key();
1027 let wrong_key = alt_key();
1028 let encrypted = encrypt_with_key("secret data", &key).expect("encryption should succeed");
1029 let result = decrypt_with_key(&encrypted, &wrong_key);
1030 assert!(result.is_err(), "decryption with wrong key should fail");
1031 }
1032
1033 #[test]
1034 fn decrypt_corrupted_ciphertext_fails() {
1035 let key = test_key();
1036 let mut encrypted = encrypt_with_key("secret data", &key).expect("encryption should succeed");
1037 let bytes: Vec<u8> = encrypted.bytes().collect();
1039 if bytes.len() > 30 {
1040 let mut chars: Vec<char> = encrypted.chars().collect();
1041 chars[30] = if chars[30] == '0' { 'f' } else { '0' };
1043 encrypted = chars.into_iter().collect();
1044 }
1045 let result = decrypt_with_key(&encrypted, &key);
1046 assert!(result.is_err(), "decryption of corrupted ciphertext should fail");
1047 }
1048
1049 #[test]
1050 fn different_keys_produce_different_ciphertext() {
1051 let key1 = test_key();
1052 let key2 = alt_key();
1053 let plaintext = "same plaintext";
1054 let enc1 = encrypt_with_key(plaintext, &key1).expect("enc1 should succeed");
1055 let enc2 = encrypt_with_key(plaintext, &key2).expect("enc2 should succeed");
1056 assert_ne!(enc1, enc2, "different keys should produce different ciphertext");
1058 }
1059
1060 #[test]
1061 fn nonce_is_always_different() {
1062 let key = test_key();
1063 let plaintext = "same string encrypted twice";
1064 let enc1 = encrypt_with_key(plaintext, &key).expect("enc1 should succeed");
1065 let enc2 = encrypt_with_key(plaintext, &key).expect("enc2 should succeed");
1066 let nonce1 = &enc1[..24];
1068 let nonce2 = &enc2[..24];
1069 assert_ne!(nonce1, nonce2, "nonces should differ between encryptions of the same plaintext");
1070 }
1071
1072 #[test]
1073 fn unicode_content_preserved() {
1074 let key = test_key();
1075 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}";
1076 let encrypted = encrypt_with_key(plaintext, &key).expect("encrypting unicode should succeed");
1077 let decrypted = decrypt_with_key(&encrypted, &key).expect("decrypting unicode should succeed");
1078 assert_eq!(decrypted, plaintext, "unicode content should be preserved through encrypt/decrypt");
1079 }
1080
1081 #[test]
1082 fn decrypt_too_short_ciphertext_fails() {
1083 let key = test_key();
1084 let result = decrypt_with_key("abcdef", &key);
1085 assert!(result.is_err(), "ciphertext shorter than 24 hex chars should fail");
1086 assert!(result.unwrap_err().contains("too short"), "error should mention too short");
1087 }
1088
1089 #[test]
1090 fn encrypt_output_is_hex_encoded() {
1091 let key = test_key();
1092 let encrypted = encrypt_with_key("test", &key).expect("encryption should succeed");
1093 assert!(encrypted.chars().all(|c| c.is_ascii_hexdigit()),
1094 "encrypted output should be entirely hex characters");
1095 }
1096
1097 #[test]
1098 fn encrypt_output_has_correct_structure() {
1099 let key = test_key();
1100 let encrypted = encrypt_with_key("test", &key).expect("encryption should succeed");
1101 assert!(encrypted.len() > 24,
1103 "encrypted output should have nonce (24 hex chars) plus ciphertext");
1104 assert_eq!(encrypted.len() % 2, 0,
1106 "encrypted output length should be even (hex pairs)");
1107 }
1108
1109 #[test]
1110 fn encrypt_decrypt_special_characters() {
1111 let key = test_key();
1112 let plaintext = r#"!@#$%^&*()_+-=[]{}|;':",.<>?/\`~"#;
1113 let encrypted = encrypt_with_key(plaintext, &key).expect("encrypting special chars should succeed");
1114 let decrypted = decrypt_with_key(&encrypted, &key).expect("decrypting special chars should succeed");
1115 assert_eq!(decrypted, plaintext, "special characters should survive roundtrip");
1116 }
1117
1118 #[test]
1119 fn encrypt_decrypt_newlines_and_whitespace() {
1120 let key = test_key();
1121 let plaintext = "line1\nline2\r\nline3\ttab\0null";
1122 let encrypted = encrypt_with_key(plaintext, &key).expect("encrypting whitespace should succeed");
1123 let decrypted = decrypt_with_key(&encrypted, &key).expect("decrypting whitespace should succeed");
1124 assert_eq!(decrypted, plaintext, "whitespace and control chars should survive roundtrip");
1125 }
1126
1127 #[test]
1128 fn decrypt_invalid_hex_in_nonce_fails() {
1129 let key = test_key();
1130 let bad = "zzzzzzzzzzzzzzzzzzzzzzzz0000000000000000";
1132 let result = decrypt_with_key(bad, &key);
1133 assert!(result.is_err(), "invalid hex in nonce should fail");
1134 }
1135
1136 #[test]
1137 fn decrypt_invalid_hex_in_ciphertext_fails() {
1138 let key = test_key();
1139 let bad = "000000000000000000000000gggggggg";
1141 let result = decrypt_with_key(bad, &key);
1142 assert!(result.is_err(), "invalid hex in ciphertext should fail");
1143 }
1144
1145 #[test]
1150 fn hex_encode_decode_roundtrip() {
1151 let data = vec![0x00, 0x01, 0xff, 0x80, 0x7f];
1152 let encoded = hex::encode(&data);
1153 let decoded = hex::decode(&encoded).expect("decode should succeed");
1154 assert_eq!(decoded, data, "hex encode/decode roundtrip should preserve bytes");
1155 }
1156
1157 #[test]
1158 fn hex_decode_odd_length_error() {
1159 let result = hex::decode("abc");
1160 assert!(result.is_err(), "odd-length hex string should fail");
1161 assert!(result.unwrap_err().contains("Odd-length"), "error should mention odd-length");
1162 }
1163
1164 #[test]
1165 fn hex_decode_invalid_hex_error() {
1166 let result = hex::decode("zzzz");
1167 assert!(result.is_err(), "invalid hex characters should fail");
1168 }
1169
1170 #[test]
1171 fn hex_encode_empty() {
1172 assert_eq!(hex::encode(&[]), "", "encoding empty bytes should produce empty string");
1173 }
1174
1175 #[test]
1176 fn hex_decode_empty() {
1177 let decoded = hex::decode("").expect("decoding empty string should succeed");
1178 assert!(decoded.is_empty(), "decoding empty string should produce empty vec");
1179 }
1180
1181 #[tokio::test]
1186 async fn hash_pass_deterministic() {
1187 let key1 = hash_pass("my_password").await;
1188 let key2 = hash_pass("my_password").await;
1189 assert_eq!(key1, key2, "same password should always produce the same key");
1190 }
1191
1192 #[tokio::test]
1193 async fn hash_pass_different_passwords_different_keys() {
1194 let key1 = hash_pass("password_one").await;
1195 let key2 = hash_pass("password_two").await;
1196 assert_ne!(key1, key2, "different passwords should produce different keys");
1197 }
1198
1199 #[tokio::test]
1200 async fn hash_pass_output_is_32_bytes() {
1201 let key = hash_pass("test_password").await;
1202 assert_eq!(key.len(), 32, "hash_pass should produce exactly 32 bytes");
1203 assert!(key.iter().any(|&b| b != 0), "hash output should not be all zeros");
1205 }
1206
1207 #[test]
1208 fn generate_thumbhash_from_bytes_basic() {
1209 let pixels: Vec<u8> = vec![
1211 255, 0, 0, 255, 255, 0, 0, 255,
1212 255, 0, 0, 255, 255, 0, 0, 255,
1213 ];
1214 let result = super::generate_thumbhash_from_rgba(&pixels, 2, 2);
1215 assert!(result.is_some());
1216 assert!(!result.unwrap().is_empty());
1217 }
1218
1219 #[test]
1220 fn generate_image_metadata_from_bytes() {
1221 let img = image::RgbaImage::from_pixel(4, 4, image::Rgba([0, 0, 255, 255]));
1223 let mut buf = Vec::new();
1224 let mut cursor = std::io::Cursor::new(&mut buf);
1225 img.write_to(&mut cursor, image::ImageFormat::Png).unwrap();
1226
1227 let meta = super::generate_image_metadata(&buf);
1228 assert!(meta.is_some());
1229 let meta = meta.unwrap();
1230 assert_eq!(meta.width, 4);
1231 assert_eq!(meta.height, 4);
1232 assert!(!meta.thumbhash.is_empty());
1233 }
1234
1235 #[test]
1236 fn generate_image_metadata_non_image() {
1237 let text_bytes = b"this is not an image";
1238 let meta = super::generate_image_metadata(text_bytes);
1239 assert!(meta.is_none());
1240 }
1241}