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 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
221pub 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
314pub fn extension_from_mime(mime: &str) -> String {
317 match mime.trim().to_lowercase().as_str() {
318 "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/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/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 "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/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 "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 "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 "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 "text/html" => "html",
407 "text/css" => "css",
408 "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 _ => {
417 let lower = mime.trim().to_lowercase();
418 return lower.split('/').nth(1).unwrap_or("bin").to_string();
419 }
420 }.to_string()
421}
422
423pub 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
454pub 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
488pub 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 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 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
532pub 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
549pub fn is_image_mime(mime: &str) -> bool {
551 mime.trim().starts_with("image/")
552}
553
554pub 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
563pub 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
583use rand::Rng;
588use chacha20poly1305::Nonce;
589
590#[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#[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#[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#[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
667pub 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
701pub 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 unsafe { Ok(String::from_utf8_unchecked(plaintext)) }
746}
747
748pub 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
757pub 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
779pub 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
805pub 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
819pub 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
833pub fn maybe_decrypt_blob(stored: &[u8]) -> Vec<u8> {
837 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
851pub 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
865pub 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 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
914pub use crate::simd::image::nearest_neighbor_downsample_rgba;
920
921pub 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
948pub fn decode_image_bounded(bytes: &[u8]) -> Result<image::DynamicImage, String> {
952 let mut reader = image::ImageReader::new(std::io::Cursor::new(bytes))
953 .with_guessed_format()
954 .map_err(|e| format!("image format: {e}"))?;
955 reader.limits(bounded_image_limits());
956 reader.decode().map_err(|e| format!("image decode: {e}"))
957}
958
959pub fn bounded_image_limits() -> image::Limits {
962 let mut limits = image::Limits::default();
963 limits.max_image_width = Some(16_384);
964 limits.max_image_height = Some(16_384);
965 limits.max_alloc = Some(256 * 1024 * 1024);
966 limits
967}
968
969pub fn generate_image_metadata(file_bytes: &[u8]) -> Option<crate::types::ImageMetadata> {
974 let img = decode_image_bounded(file_bytes).ok()?;
975 let width = img.width();
976 let height = img.height();
977
978 let rgba = img.to_rgba8();
979 let thumbhash = generate_thumbhash_from_rgba(rgba.as_raw(), width, height)?;
980
981 Some(crate::types::ImageMetadata {
982 thumbhash,
983 width,
984 height,
985 })
986}
987
988#[cfg(test)]
989mod tests {
990 use super::*;
991
992 fn test_key() -> [u8; 32] {
997 [0x42u8; 32]
998 }
999
1000 fn alt_key() -> [u8; 32] {
1001 [0x99u8; 32]
1002 }
1003
1004 #[test]
1005 fn encrypt_decrypt_roundtrip_simple() {
1006 let key = test_key();
1007 let plaintext = "hello world";
1008 let encrypted = encrypt_with_key(plaintext, &key).expect("encryption should succeed");
1009 let decrypted = decrypt_with_key(&encrypted, &key).expect("decryption should succeed");
1010 assert_eq!(decrypted, plaintext, "roundtrip should preserve plaintext");
1011 }
1012
1013 #[test]
1014 fn encrypt_decrypt_100_random_strings() {
1015 use rand::Rng;
1016 let key = test_key();
1017 let mut rng = rand::thread_rng();
1018 for i in 0..100 {
1019 let len = rng.gen_range(1..=200);
1020 let s: String = (0..len).map(|_| rng.gen_range(0x20u8..0x7f) as char).collect();
1021 let enc = encrypt_with_key(&s, &key)
1022 .unwrap_or_else(|e| panic!("encryption failed on iteration {}: {}", i, e));
1023 let dec = decrypt_with_key(&enc, &key)
1024 .unwrap_or_else(|e| panic!("decryption failed on iteration {}: {}", i, e));
1025 assert_eq!(dec, s, "roundtrip failed on iteration {}", i);
1026 }
1027 }
1028
1029 #[test]
1030 fn encrypt_decrypt_empty_string() {
1031 let key = test_key();
1032 let encrypted = encrypt_with_key("", &key).expect("encrypting empty string should succeed");
1033 let decrypted = decrypt_with_key(&encrypted, &key).expect("decrypting empty string should succeed");
1034 assert_eq!(decrypted, "", "empty string roundtrip should produce empty string");
1035 }
1036
1037 #[test]
1038 fn encrypt_decrypt_large_string() {
1039 let key = test_key();
1040 let plaintext = "A".repeat(10 * 1024); let encrypted = encrypt_with_key(&plaintext, &key).expect("encrypting 10KB should succeed");
1042 let decrypted = decrypt_with_key(&encrypted, &key).expect("decrypting 10KB should succeed");
1043 assert_eq!(decrypted, plaintext, "10KB roundtrip should preserve content");
1044 }
1045
1046 #[test]
1047 fn decrypt_with_wrong_key_fails() {
1048 let key = test_key();
1049 let wrong_key = alt_key();
1050 let encrypted = encrypt_with_key("secret data", &key).expect("encryption should succeed");
1051 let result = decrypt_with_key(&encrypted, &wrong_key);
1052 assert!(result.is_err(), "decryption with wrong key should fail");
1053 }
1054
1055 #[test]
1056 fn decrypt_corrupted_ciphertext_fails() {
1057 let key = test_key();
1058 let mut encrypted = encrypt_with_key("secret data", &key).expect("encryption should succeed");
1059 let bytes: Vec<u8> = encrypted.bytes().collect();
1061 if bytes.len() > 30 {
1062 let mut chars: Vec<char> = encrypted.chars().collect();
1063 chars[30] = if chars[30] == '0' { 'f' } else { '0' };
1065 encrypted = chars.into_iter().collect();
1066 }
1067 let result = decrypt_with_key(&encrypted, &key);
1068 assert!(result.is_err(), "decryption of corrupted ciphertext should fail");
1069 }
1070
1071 #[test]
1072 fn different_keys_produce_different_ciphertext() {
1073 let key1 = test_key();
1074 let key2 = alt_key();
1075 let plaintext = "same plaintext";
1076 let enc1 = encrypt_with_key(plaintext, &key1).expect("enc1 should succeed");
1077 let enc2 = encrypt_with_key(plaintext, &key2).expect("enc2 should succeed");
1078 assert_ne!(enc1, enc2, "different keys should produce different ciphertext");
1080 }
1081
1082 #[test]
1083 fn nonce_is_always_different() {
1084 let key = test_key();
1085 let plaintext = "same string encrypted twice";
1086 let enc1 = encrypt_with_key(plaintext, &key).expect("enc1 should succeed");
1087 let enc2 = encrypt_with_key(plaintext, &key).expect("enc2 should succeed");
1088 let nonce1 = &enc1[..24];
1090 let nonce2 = &enc2[..24];
1091 assert_ne!(nonce1, nonce2, "nonces should differ between encryptions of the same plaintext");
1092 }
1093
1094 #[test]
1095 fn unicode_content_preserved() {
1096 let key = test_key();
1097 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}";
1098 let encrypted = encrypt_with_key(plaintext, &key).expect("encrypting unicode should succeed");
1099 let decrypted = decrypt_with_key(&encrypted, &key).expect("decrypting unicode should succeed");
1100 assert_eq!(decrypted, plaintext, "unicode content should be preserved through encrypt/decrypt");
1101 }
1102
1103 #[test]
1104 fn decrypt_too_short_ciphertext_fails() {
1105 let key = test_key();
1106 let result = decrypt_with_key("abcdef", &key);
1107 assert!(result.is_err(), "ciphertext shorter than 24 hex chars should fail");
1108 assert!(result.unwrap_err().contains("too short"), "error should mention too short");
1109 }
1110
1111 #[test]
1112 fn encrypt_output_is_hex_encoded() {
1113 let key = test_key();
1114 let encrypted = encrypt_with_key("test", &key).expect("encryption should succeed");
1115 assert!(encrypted.chars().all(|c| c.is_ascii_hexdigit()),
1116 "encrypted output should be entirely hex characters");
1117 }
1118
1119 #[test]
1120 fn encrypt_output_has_correct_structure() {
1121 let key = test_key();
1122 let encrypted = encrypt_with_key("test", &key).expect("encryption should succeed");
1123 assert!(encrypted.len() > 24,
1125 "encrypted output should have nonce (24 hex chars) plus ciphertext");
1126 assert_eq!(encrypted.len() % 2, 0,
1128 "encrypted output length should be even (hex pairs)");
1129 }
1130
1131 #[test]
1132 fn encrypt_decrypt_special_characters() {
1133 let key = test_key();
1134 let plaintext = r#"!@#$%^&*()_+-=[]{}|;':",.<>?/\`~"#;
1135 let encrypted = encrypt_with_key(plaintext, &key).expect("encrypting special chars should succeed");
1136 let decrypted = decrypt_with_key(&encrypted, &key).expect("decrypting special chars should succeed");
1137 assert_eq!(decrypted, plaintext, "special characters should survive roundtrip");
1138 }
1139
1140 #[test]
1141 fn encrypt_decrypt_newlines_and_whitespace() {
1142 let key = test_key();
1143 let plaintext = "line1\nline2\r\nline3\ttab\0null";
1144 let encrypted = encrypt_with_key(plaintext, &key).expect("encrypting whitespace should succeed");
1145 let decrypted = decrypt_with_key(&encrypted, &key).expect("decrypting whitespace should succeed");
1146 assert_eq!(decrypted, plaintext, "whitespace and control chars should survive roundtrip");
1147 }
1148
1149 #[test]
1150 fn decrypt_invalid_hex_in_nonce_fails() {
1151 let key = test_key();
1152 let bad = "zzzzzzzzzzzzzzzzzzzzzzzz0000000000000000";
1154 let result = decrypt_with_key(bad, &key);
1155 assert!(result.is_err(), "invalid hex in nonce should fail");
1156 }
1157
1158 #[test]
1159 fn decrypt_invalid_hex_in_ciphertext_fails() {
1160 let key = test_key();
1161 let bad = "000000000000000000000000gggggggg";
1163 let result = decrypt_with_key(bad, &key);
1164 assert!(result.is_err(), "invalid hex in ciphertext should fail");
1165 }
1166
1167 #[test]
1172 fn hex_encode_decode_roundtrip() {
1173 let data = vec![0x00, 0x01, 0xff, 0x80, 0x7f];
1174 let encoded = hex::encode(&data);
1175 let decoded = hex::decode(&encoded).expect("decode should succeed");
1176 assert_eq!(decoded, data, "hex encode/decode roundtrip should preserve bytes");
1177 }
1178
1179 #[test]
1180 fn hex_decode_odd_length_error() {
1181 let result = hex::decode("abc");
1182 assert!(result.is_err(), "odd-length hex string should fail");
1183 assert!(result.unwrap_err().contains("Odd-length"), "error should mention odd-length");
1184 }
1185
1186 #[test]
1187 fn hex_decode_invalid_hex_error() {
1188 let result = hex::decode("zzzz");
1189 assert!(result.is_err(), "invalid hex characters should fail");
1190 }
1191
1192 #[test]
1193 fn hex_encode_empty() {
1194 assert_eq!(hex::encode(&[]), "", "encoding empty bytes should produce empty string");
1195 }
1196
1197 #[test]
1198 fn hex_decode_empty() {
1199 let decoded = hex::decode("").expect("decoding empty string should succeed");
1200 assert!(decoded.is_empty(), "decoding empty string should produce empty vec");
1201 }
1202
1203 #[tokio::test]
1208 async fn hash_pass_deterministic() {
1209 let key1 = hash_pass("my_password").await;
1210 let key2 = hash_pass("my_password").await;
1211 assert_eq!(key1, key2, "same password should always produce the same key");
1212 }
1213
1214 #[tokio::test]
1215 async fn hash_pass_different_passwords_different_keys() {
1216 let key1 = hash_pass("password_one").await;
1217 let key2 = hash_pass("password_two").await;
1218 assert_ne!(key1, key2, "different passwords should produce different keys");
1219 }
1220
1221 #[tokio::test]
1222 async fn hash_pass_output_is_32_bytes() {
1223 let key = hash_pass("test_password").await;
1224 assert_eq!(key.len(), 32, "hash_pass should produce exactly 32 bytes");
1225 assert!(key.iter().any(|&b| b != 0), "hash output should not be all zeros");
1227 }
1228
1229 #[test]
1230 fn generate_thumbhash_from_bytes_basic() {
1231 let pixels: Vec<u8> = vec![
1233 255, 0, 0, 255, 255, 0, 0, 255,
1234 255, 0, 0, 255, 255, 0, 0, 255,
1235 ];
1236 let result = super::generate_thumbhash_from_rgba(&pixels, 2, 2);
1237 assert!(result.is_some());
1238 assert!(!result.unwrap().is_empty());
1239 }
1240
1241 #[test]
1242 fn generate_image_metadata_from_bytes() {
1243 let img = image::RgbaImage::from_pixel(4, 4, image::Rgba([0, 0, 255, 255]));
1245 let mut buf = Vec::new();
1246 let mut cursor = std::io::Cursor::new(&mut buf);
1247 img.write_to(&mut cursor, image::ImageFormat::Png).unwrap();
1248
1249 let meta = super::generate_image_metadata(&buf);
1250 assert!(meta.is_some());
1251 let meta = meta.unwrap();
1252 assert_eq!(meta.width, 4);
1253 assert_eq!(meta.height, 4);
1254 assert!(!meta.thumbhash.is_empty());
1255 }
1256
1257 #[test]
1258 fn generate_image_metadata_non_image() {
1259 let text_bytes = b"this is not an image";
1260 let meta = super::generate_image_metadata(text_bytes);
1261 assert!(meta.is_none());
1262 }
1263}