vector-core 0.2.0

Core library for Vector — the single source of truth for all Vector clients, SDKs, and interfaces.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
pub mod guarded_key;
pub use guarded_key::GuardedKey;

mod signer;
pub use signer::GuardedSigner;

use argon2::Argon2;
use chacha20poly1305::{aead::Aead, ChaCha20Poly1305, KeyInit};
use zeroize::Zeroize;

/// Derive a 32-byte key from a password using Argon2id.
/// Parameters: 150MB memory, 10 iterations (matches src-tauri).
pub async fn hash_pass(password: &str) -> [u8; 32] {
    let password = password.to_string();
    tokio::task::spawn_blocking(move || {
        let salt = b"vectorvectovectvecvev";
        let mut output = [0u8; 32];

        let params = argon2::Params::new(
            150_000, // 150 MB
            10,      // iterations
            1,       // parallelism
            Some(32),
        ).unwrap();

        let argon2 = Argon2::new(argon2::Algorithm::Argon2id, argon2::Version::V0x13, params);
        argon2.hash_password_into(password.as_bytes(), salt, &mut output).unwrap();

        output
    }).await.unwrap()
}

/// Encrypt a string with the global ENCRYPTION_KEY (ChaCha20-Poly1305).
pub fn encrypt_with_key(plaintext: &str, key: &[u8; 32]) -> Result<String, String> {
    use chacha20poly1305::aead::OsRng;
    use chacha20poly1305::AeadCore;

    let cipher = ChaCha20Poly1305::new(key.into());
    let nonce = ChaCha20Poly1305::generate_nonce(&mut OsRng);

    let ciphertext = cipher.encrypt(&nonce, plaintext.as_bytes())
        .map_err(|e| format!("Encryption failed: {}", e))?;

    // Encode as hex: nonce + ciphertext
    let mut result = hex::encode(&nonce[..]);
    result.push_str(&hex::encode(&ciphertext));
    Ok(result)
}

/// Decrypt a hex-encoded ciphertext with a key.
pub fn decrypt_with_key(hex_data: &str, key: &[u8; 32]) -> Result<String, String> {
    if hex_data.len() < 24 {
        return Err("Ciphertext too short".to_string());
    }

    let nonce_hex = &hex_data[..24]; // 12 bytes = 24 hex chars
    let ciphertext_hex = &hex_data[24..];

    let nonce_bytes = hex::decode(nonce_hex)
        .map_err(|e| format!("Invalid nonce hex: {}", e))?;
    let ciphertext = hex::decode(ciphertext_hex)
        .map_err(|e| format!("Invalid ciphertext hex: {}", e))?;

    let nonce_arr: [u8; 12] = nonce_bytes.try_into()
        .map_err(|_| "Invalid nonce length".to_string())?;
    let nonce = chacha20poly1305::Nonce::from(nonce_arr);
    let cipher = ChaCha20Poly1305::new(key.into());

    let mut plaintext = cipher.decrypt(&nonce, ciphertext.as_ref())
        .map_err(|_| "Decryption failed (wrong key or corrupted data)".to_string())?;

    let result = String::from_utf8(plaintext.clone())
        .map_err(|_| "Decrypted data is not valid UTF-8".to_string())?;

    plaintext.zeroize();
    Ok(result)
}

/// Check if encryption is enabled in the database.
///
/// Delegates to `state::resolve_encryption_enabled_from_db` — the single
/// source of truth that handles the missing-row case consistently. The
/// previous implementation defaulted to `false` on missing rows, which
/// silently disagreed with `init_encryption_enabled` (defaulted to `true`)
/// and silently mis-routed login flows after an account swap.
pub fn is_encryption_enabled() -> bool {
    crate::state::resolve_encryption_enabled_from_db()
}

/// Simple hex encode/decode (for crypto module internal use).
mod hex {
    pub fn encode(bytes: &[u8]) -> String {
        // SIMD hex encode (NEON/SSE2, fast-pathing 32/16-byte). Identical lowercase output to the
        // old per-byte format! loop, but it runs on every encrypt (ciphertext + nonce).
        crate::simd::hex::bytes_to_hex_string(bytes)
    }

    pub fn decode(hex: &str) -> Result<Vec<u8>, String> {
        if hex.len() % 2 != 0 {
            return Err("Odd-length hex string".to_string());
        }
        // SIMD-validated decode (NEON/SSE2 in-register hex validation). Runs on every message read
        // (decrypt), so the recurring path stays fast; rejects non-hex like the old scalar loop.
        crate::simd::hex::hex_string_to_bytes_checked(hex)
            .ok_or_else(|| "Invalid hex character".to_string())
    }
}

// ============================================================================
// AES-256-GCM File Encryption (for NIP-96/Blossom attachments)
// ============================================================================

/// Parameters for AES-256-GCM file encryption (hex-encoded key + nonce).
#[derive(Debug)]
pub struct EncryptionParams {
    pub key: String,   // 32-byte key as hex
    pub nonce: String, // 16-byte nonce as hex (0xChat-compatible)
}

/// Generate random AES-256-GCM encryption parameters.
pub fn generate_encryption_params() -> EncryptionParams {
    use rand::Rng;
    let mut rng = rand::thread_rng();
    let mut key: [u8; 32] = rng.gen();
    let nonce: [u8; 16] = rng.gen();
    let params = EncryptionParams {
        key: hex::encode(&key),
        nonce: hex::encode(&nonce),
    };
    key.iter_mut().for_each(|b| *b = 0); // zeroize
    params
}

/// Encrypt data with AES-256-GCM using a 16-byte nonce (0xChat-compatible).
pub fn encrypt_data(data: &[u8], params: &EncryptionParams) -> Result<Vec<u8>, String> {
    use aes::Aes256;
    use aes::cipher::typenum::U16;
    use aes_gcm::{AesGcm, AeadInPlace, KeyInit as AesKeyInit};

    let key_bytes = hex::decode(&params.key).map_err(|e| format!("Invalid key: {}", e))?;
    let nonce_bytes = hex::decode(&params.nonce).map_err(|e| format!("Invalid nonce: {}", e))?;

    let cipher = AesGcm::<Aes256, U16>::new_from_slice(&key_bytes)
        .map_err(|_| "Invalid encryption key".to_string())?;

    let nonce_arr: [u8; 16] = nonce_bytes.try_into()
        .map_err(|_| "Invalid nonce length".to_string())?;
    let nonce = aes_gcm::Nonce::<U16>::from(nonce_arr);

    let mut buffer = data.to_vec();
    let tag = cipher.encrypt_in_place_detached(&nonce, &[], &mut buffer)
        .map_err(|_| "Encryption failed".to_string())?;

    buffer.extend_from_slice(&tag);
    Ok(buffer)
}

/// Decrypt data with AES-256-GCM using a 16-byte nonce (0xChat-compatible).
/// Input format: ciphertext || 16-byte auth tag.
pub fn decrypt_data(encrypted_data: &[u8], key_hex: &str, nonce_hex: &str) -> Result<Vec<u8>, String> {
    use aes::Aes256;
    use aes::cipher::typenum::U16;
    use aes_gcm::{AesGcm, AeadInPlace, KeyInit as AesKeyInit};

    if encrypted_data.len() < 16 {
        return Err(format!("Invalid Input: encrypted data too small ({} bytes, minimum 16 bytes required for authentication tag)", encrypted_data.len()));
    }

    let key_bytes = hex::decode(key_hex).map_err(|e| format!("Invalid key: {}", e))?;
    let nonce_bytes = hex::decode(nonce_hex).map_err(|e| format!("Invalid nonce: {}", e))?;

    let (ciphertext, tag_bytes) = encrypted_data.split_at(encrypted_data.len() - 16);

    let cipher = AesGcm::<Aes256, U16>::new_from_slice(&key_bytes)
        .map_err(|_| "Invalid decryption key".to_string())?;

    let nonce_arr: [u8; 16] = nonce_bytes.try_into()
        .map_err(|_| "Invalid nonce length".to_string())?;
    let nonce = aes_gcm::Nonce::<U16>::from(nonce_arr);
    let tag_arr: [u8; 16] = tag_bytes.try_into()
        .map_err(|_| "Invalid tag length".to_string())?;
    let tag = aes_gcm::Tag::<U16>::from(tag_arr);

    let mut buffer = ciphertext.to_vec();
    cipher.decrypt_in_place_detached(&nonce, &[], &mut buffer, &tag)
        .map_err(|e| e.to_string())?;

    Ok(buffer)
}

/// Calculate SHA-256 hash of data, returned as hex string.
pub fn sha256_hex(data: &[u8]) -> String {
    use sha2::{Sha256, Digest};
    let mut hasher = Sha256::new();
    hasher.update(data);
    hex::encode(&hasher.finalize())
}

/// Identity basis for a RECEIVED attachment: the sender's `ox` (plaintext
/// hash) when provided — it's what enables honest cross-message dedup — else
/// a digest of nonce+url. Never the raw nonce: senders can and do reuse
/// nonces, which cross-bound DIFFERENT files to one identity (the "new image
/// renders as an old one" class). The upload URL is unique per ciphertext,
/// so the digest is collision-resistant even against nonce reuse. Nothing
/// honest ever writes a file under the digest name, so existence of one is
/// never proof of download — reuse decisions stay with the content-verified
/// download path.
pub fn attachment_identity_basis(ox: Option<&str>, nonce: &str, url: &str) -> String {
    match ox.filter(|h| !h.is_empty()) {
        Some(h) => h.to_string(),
        None => {
            let mut buf = Vec::with_capacity(nonce.len() + 1 + url.len());
            buf.extend_from_slice(nonce.as_bytes());
            buf.push(0);
            buf.extend_from_slice(url.as_bytes());
            sha256_hex(&buf)
        }
    }
}

/// Get MIME type from file extension.
pub fn mime_from_extension(ext: &str) -> &'static str {
    match ext.to_lowercase().as_str() {
        "png" => "image/png",
        "jpg" | "jpeg" => "image/jpeg",
        "gif" => "image/gif",
        "webp" => "image/webp",
        "svg" => "image/svg+xml",
        "bmp" => "image/bmp",
        "ico" => "image/x-icon",
        "tiff" | "tif" => "image/tiff",
        "dng" => "image/x-adobe-dng",
        "cr2" => "image/x-canon-cr2",
        "nef" => "image/x-nikon-nef",
        "arw" => "image/x-sony-arw",
        "mp4" => "video/mp4",
        "webm" => "video/webm",
        "mov" => "video/quicktime",
        "avi" => "video/x-msvideo",
        "mkv" => "video/x-matroska",
        "flv" => "video/x-flv",
        "wmv" => "video/x-ms-wmv",
        "mpg" | "mpeg" => "video/mpeg",
        "3gp" => "video/3gpp",
        "ogv" => "video/ogg",
        "ts" => "video/mp2t",
        "mp3" => "audio/mpeg",
        "ogg" => "audio/ogg",
        "wav" => "audio/wav",
        "flac" => "audio/flac",
        "m4a" => "audio/mp4",
        "aac" => "audio/aac",
        "wma" => "audio/x-ms-wma",
        "opus" => "audio/opus",
        "pdf" => "application/pdf",
        "doc" => "application/msword",
        "docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
        "xls" => "application/vnd.ms-excel",
        "xlsx" => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        "ppt" => "application/vnd.ms-powerpoint",
        "pptx" => "application/vnd.openxmlformats-officedocument.presentationml.presentation",
        "odt" => "application/vnd.oasis.opendocument.text",
        "ods" => "application/vnd.oasis.opendocument.spreadsheet",
        "odp" => "application/vnd.oasis.opendocument.presentation",
        "rtf" => "application/rtf",
        "txt" => "text/plain",
        "md" => "text/markdown",
        "csv" => "text/csv",
        "json" => "application/json",
        "xml" => "application/xml",
        "yaml" | "yml" => "application/x-yaml",
        "toml" => "application/toml",
        "sql" => "application/sql",
        "zip" => "application/zip",
        "rar" => "application/vnd.rar",
        "7z" => "application/x-7z-compressed",
        "tar" => "application/x-tar",
        "gz" => "application/gzip",
        "bz2" => "application/x-bzip2",
        "xz" => "application/x-xz",
        "iso" => "application/x-iso9660-image",
        "dmg" => "application/x-apple-diskimage",
        "apk" => "application/vnd.android.package-archive",
        "jar" => "application/java-archive",
        "xdc" => "application/vnd.webxdc+zip",
        "obj" => "model/obj",
        "gltf" => "model/gltf+json",
        "glb" => "model/gltf-binary",
        "stl" => "model/stl",
        "dae" => "model/vnd.collada+xml",
        "js" => "text/javascript",
        "py" => "text/x-python",
        "rs" => "text/x-rust",
        "go" => "text/x-go",
        "java" => "text/x-java",
        "c" => "text/x-c",
        "cpp" => "text/x-c++",
        "cs" => "text/x-csharp",
        "rb" => "text/x-ruby",
        "php" => "text/x-php",
        "swift" => "text/x-swift",
        "html" | "htm" => "text/html",
        "css" => "text/css",
        "exe" => "application/x-msdownload",
        "msi" => "application/x-msi",
        "ttf" => "font/ttf",
        "otf" => "font/otf",
        "woff" => "font/woff",
        "woff2" => "font/woff2",
        _ => "application/octet-stream",
    }
}

/// Convert a MIME type to a file extension.
/// Falls back to using the MIME subtype when unknown.
pub fn extension_from_mime(mime: &str) -> String {
    match mime.trim().to_lowercase().as_str() {
        // Images
        "image/png" => "png",
        "image/jpeg" | "image/jpg" => "jpg",
        "image/gif" => "gif",
        "image/webp" => "webp",
        "image/svg+xml" => "svg",
        "image/bmp" | "image/x-ms-bmp" => "bmp",
        "image/x-icon" | "image/vnd.microsoft.icon" => "ico",
        "image/tiff" => "tiff",
        "image/x-adobe-dng" => "dng",
        "image/x-canon-cr2" => "cr2",
        "image/x-nikon-nef" => "nef",
        "image/x-sony-arw" => "arw",
        // Audio
        "audio/wav" | "audio/x-wav" | "audio/wave" => "wav",
        "audio/mp3" | "audio/mpeg" => "mp3",
        "audio/flac" => "flac",
        "audio/ogg" => "ogg",
        "audio/mp4" => "m4a",
        "audio/aac" | "audio/x-aac" => "aac",
        "audio/x-ms-wma" => "wma",
        "audio/opus" => "opus",
        // Video
        "video/mp4" => "mp4",
        "video/webm" => "webm",
        "video/quicktime" => "mov",
        "video/x-msvideo" => "avi",
        "video/x-matroska" => "mkv",
        "video/x-flv" => "flv",
        "video/x-ms-wmv" => "wmv",
        "video/mpeg" => "mpg",
        "video/3gpp" => "3gp",
        "video/ogg" => "ogv",
        "video/mp2t" => "ts",
        // Documents
        "application/pdf" => "pdf",
        "application/msword" => "doc",
        "application/vnd.openxmlformats-officedocument.wordprocessingml.document" => "docx",
        "application/vnd.ms-excel" => "xls",
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" => "xlsx",
        "application/vnd.ms-powerpoint" => "ppt",
        "application/vnd.openxmlformats-officedocument.presentationml.presentation" => "pptx",
        "application/vnd.oasis.opendocument.text" => "odt",
        "application/vnd.oasis.opendocument.spreadsheet" => "ods",
        "application/vnd.oasis.opendocument.presentation" => "odp",
        "application/rtf" => "rtf",
        // Text/Data
        "text/plain" => "txt",
        "text/markdown" => "md",
        "text/csv" => "csv",
        "application/json" => "json",
        "application/xml" | "text/xml" => "xml",
        "application/x-yaml" | "text/yaml" => "yaml",
        "application/toml" => "toml",
        "application/sql" => "sql",
        // Archives
        "application/zip" => "zip",
        "application/x-rar-compressed" | "application/vnd.rar" => "rar",
        "application/x-7z-compressed" => "7z",
        "application/x-tar" => "tar",
        "application/gzip" => "gz",
        "application/x-bzip2" => "bz2",
        "application/x-xz" => "xz",
        "application/x-iso9660-image" => "iso",
        "application/x-apple-diskimage" => "dmg",
        "application/vnd.android.package-archive" => "apk",
        "application/java-archive" => "jar",
        "application/vnd.webxdc+zip" => "xdc",
        // 3D
        "model/obj" => "obj",
        "model/gltf+json" => "gltf",
        "model/gltf-binary" => "glb",
        "model/stl" | "application/sla" => "stl",
        "model/vnd.collada+xml" => "dae",
        // Code
        "text/javascript" | "application/javascript" => "js",
        "text/typescript" | "application/typescript" => "ts",
        "text/x-python" | "application/x-python" => "py",
        "text/x-rust" => "rs",
        "text/x-go" => "go",
        "text/x-java" => "java",
        "text/x-c" => "c",
        "text/x-c++" => "cpp",
        "text/x-csharp" => "cs",
        "text/x-ruby" => "rb",
        "text/x-php" => "php",
        "text/x-swift" => "swift",
        // Web
        "text/html" => "html",
        "text/css" => "css",
        // Other
        "application/x-msdownload" | "application/x-dosexec" => "exe",
        "application/x-msi" => "msi",
        "application/x-font-ttf" | "font/ttf" => "ttf",
        "application/x-font-otf" | "font/otf" => "otf",
        "font/woff" => "woff",
        "font/woff2" => "woff2",
        // Fallback: extract subtype
        _ => {
            let lower = mime.trim().to_lowercase();
            return lower.split('/').nth(1).unwrap_or("bin").to_string();
        }
    }.to_string()
}

/// Sanitize a filename for safe filesystem use.
/// Strips path traversal, dangerous characters, and truncates to 64-char stem.
pub fn sanitize_filename(name: &str) -> String {
    let base = name.rsplit('/').next().unwrap_or(name);
    let base = base.rsplit('\\').next().unwrap_or(base);

    let sanitized: String = base.chars().filter(|c| {
        !matches!(c, '/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|' | '\0')
    }).collect();

    let sanitized = sanitized.trim_matches(|c: char| c == '.' || c == ' ');

    if sanitized.is_empty() {
        return String::new();
    }

    if let Some(dot_pos) = sanitized.rfind('.') {
        let stem = &sanitized[..dot_pos];
        let ext = &sanitized[dot_pos..];
        if stem.len() > 64 {
            let truncated = &stem[..stem.floor_char_boundary(64)];
            return format!("{}{}", truncated, ext);
        }
    } else if sanitized.len() > 64 {
        let truncated = &sanitized[..sanitized.floor_char_boundary(64)];
        return truncated.to_string();
    }

    sanitized.to_string()
}

/// Resolve a unique filename in `dir`, appending `-1`, `-2`, etc. on collision.
///
/// If `dir/name` doesn't exist, returns it as-is. Otherwise increments a
/// counter on the stem: `photo.jpg` → `photo-1.jpg` → `photo-2.jpg` ...
pub fn resolve_unique_filename(dir: &std::path::Path, name: &str) -> std::path::PathBuf {
    let candidate = dir.join(name);
    if !candidate.exists() {
        return candidate;
    }

    let stem = std::path::Path::new(name)
        .file_stem()
        .and_then(|s| s.to_str())
        .unwrap_or(name);
    let ext = std::path::Path::new(name)
        .extension()
        .and_then(|s| s.to_str())
        .unwrap_or("");

    let mut counter = 1u32;
    loop {
        let suffixed = if ext.is_empty() {
            format!("{}-{}", stem, counter)
        } else {
            format!("{}-{}.{}", stem, counter, ext)
        };
        let candidate = dir.join(&suffixed);
        if !candidate.exists() {
            return candidate;
        }
        counter += 1;
    }
}

/// Decrypt a DM file attachment and save to the download directory.
///
/// Uses AES-GCM decryption with the key/nonce from the attachment metadata.
/// Saves with atomic write (temp file + rename). Returns (path, content_hash).
/// If an identical file already exists (same name + size + hash), reuses it.
pub fn decrypt_and_save_attachment(
    encrypted_data: &[u8],
    key: &str,
    nonce: &str,
    name: &str,
    extension: &str,
) -> Result<(std::path::PathBuf, String), String> {
    let decrypted = decrypt_data(encrypted_data, key, nonce)?;
    let file_hash = sha256_hex(&decrypted);

    let dir = crate::db::get_download_dir();
    std::fs::create_dir_all(&dir).map_err(|e| format!("Failed to create directory: {}", e))?;

    let target_name = if name.is_empty() {
        format!("{}.{}", file_hash, extension)
    } else {
        name.to_string()
    };

    // Content dedup: reuse if same name + size + hash
    let candidate = dir.join(&target_name);
    let already_exists = candidate.exists()
        && std::fs::metadata(&candidate).map(|m| m.len() == decrypted.len() as u64).unwrap_or(false)
        && std::fs::read(&candidate).map(|b| sha256_hex(&b) == file_hash).unwrap_or(false);

    if already_exists {
        return Ok((candidate, file_hash));
    }

    let file_path = resolve_unique_filename(&dir, &target_name);

    // Atomic write: temp file then rename
    let tmp_path = dir.join(format!(".{}.{}.tmp", file_hash, extension));
    std::fs::write(&tmp_path, &decrypted).map_err(|e| format!("Failed to write file: {}", e))?;
    std::fs::rename(&tmp_path, &file_path).map_err(|e| format!("Failed to rename file: {}", e))?;

    Ok((file_path, file_hash))
}

/// Format bytes into human-readable format (KB, MB, GB).
pub fn format_bytes(bytes: u64) -> String {
    const KB: f64 = 1024.0;
    const MB: f64 = KB * 1024.0;
    const GB: f64 = MB * 1024.0;

    if bytes < KB as u64 {
        format!("{} B", bytes)
    } else if bytes < MB as u64 {
        format!("{:.1} KB", bytes as f64 / KB)
    } else if bytes < GB as u64 {
        format!("{:.1} MB", bytes as f64 / MB)
    } else {
        format!("{:.1} GB", bytes as f64 / GB)
    }
}

/// Returns true if the provided MIME type is an image/*.
pub fn is_image_mime(mime: &str) -> bool {
    mime.trim().starts_with("image/")
}

/// Convert a file extension to a MIME type, with an optional restriction to image/* types.
pub fn mime_from_extension_safe(extension: &str, image_only: bool) -> Result<String, String> {
    let mime = mime_from_extension(extension).to_string();
    if image_only && !is_image_mime(&mime) {
        return Err(mime);
    }
    Ok(mime)
}

/// Detect MIME type from file magic bytes.
/// Supports PNG, JPEG, GIF, WebP, TIFF, ICO, and SVG.
/// Returns "application/octet-stream" for unrecognized formats.
pub fn mime_from_magic_bytes(bytes: &[u8]) -> &'static str {
    if bytes.len() < 4 {
        return "application/octet-stream";
    }
    match bytes[0] {
        0x89 if bytes[1..4] == [0x50, 0x4E, 0x47] => "image/png",
        0xFF if bytes[1..3] == [0xD8, 0xFF] => "image/jpeg",
        b'G' if bytes.len() >= 6 && (bytes[..6] == *b"GIF87a" || bytes[..6] == *b"GIF89a") => "image/gif",
        b'R' if bytes.len() > 12 && bytes[..4] == *b"RIFF" && bytes[8..12] == *b"WEBP" => "image/webp",
        0x49 if bytes[1..4] == [0x49, 0x2A, 0x00] => "image/tiff",
        0x4D if bytes[1..4] == [0x4D, 0x00, 0x2A] => "image/tiff",
        0x00 if bytes[1..4] == [0x00, 0x01, 0x00] => "image/x-icon",
        b'<' if bytes.starts_with(b"<?xml") || bytes.starts_with(b"<svg") => "image/svg+xml",
        _ => "application/octet-stream",
    }
}

// ============================================================================
// Conditional Encryption — maybe_encrypt / maybe_decrypt
// ============================================================================

use rand::Rng;
use chacha20poly1305::Nonce;

/// Check if a string looks like encrypted content (hex-encoded ChaCha20 output).
/// Minimum (empty message): 12 + 0 + 16 = 28 bytes = 56 hex chars.
#[inline]
pub fn looks_encrypted(s: &str) -> bool {
    if s.len() < 56 { return false; }
    is_all_lowercase_hex(s.as_bytes())
}

/// NEON: check if all bytes are lowercase hex [0-9a-f].
#[cfg(target_arch = "aarch64")]
#[inline]
fn is_all_lowercase_hex(bytes: &[u8]) -> bool {
    use std::arch::aarch64::*;
    unsafe {
        let mut i = 0;
        while i + 16 <= bytes.len() {
            let chunk = vld1q_u8(bytes.as_ptr().add(i));
            let is_digit = vandq_u8(vcgeq_u8(chunk, vdupq_n_u8(b'0')),
                                    vcleq_u8(chunk, vdupq_n_u8(b'9')));
            let is_af = vandq_u8(vcgeq_u8(chunk, vdupq_n_u8(b'a')),
                                 vcleq_u8(chunk, vdupq_n_u8(b'f')));
            if vminvq_u8(vorrq_u8(is_digit, is_af)) == 0 { return false; }
            i += 16;
        }
        while i < bytes.len() {
            let b = bytes[i];
            if !matches!(b, b'0'..=b'9' | b'a'..=b'f') { return false; }
            i += 1;
        }
    }
    true
}

/// SSE2: check if all bytes are lowercase hex [0-9a-f].
#[cfg(target_arch = "x86_64")]
#[inline]
fn is_all_lowercase_hex(bytes: &[u8]) -> bool {
    use std::arch::x86_64::*;
    unsafe {
        let mut i = 0;
        while i + 16 <= bytes.len() {
            let chunk = _mm_loadu_si128(bytes.as_ptr().add(i) as *const __m128i);
            let is_digit = _mm_cmpeq_epi8(
                _mm_subs_epu8(_mm_sub_epi8(chunk, _mm_set1_epi8(b'0' as i8)), _mm_set1_epi8(9)),
                _mm_setzero_si128());
            let is_af = _mm_cmpeq_epi8(
                _mm_subs_epu8(_mm_sub_epi8(chunk, _mm_set1_epi8(b'a' as i8)), _mm_set1_epi8(5)),
                _mm_setzero_si128());
            if _mm_movemask_epi8(_mm_or_si128(is_digit, is_af)) != 0xFFFF { return false; }
            i += 16;
        }
        while i < bytes.len() {
            let b = bytes[i];
            if !matches!(b, b'0'..=b'9' | b'a'..=b'f') { return false; }
            i += 1;
        }
    }
    true
}

/// Scalar fallback for platforms without SIMD.
#[cfg(not(any(target_arch = "aarch64", target_arch = "x86_64")))]
#[inline]
fn is_all_lowercase_hex(bytes: &[u8]) -> bool {
    const IS_LOWER_HEX: [bool; 256] = {
        let mut t = [false; 256];
        t[b'0' as usize] = true; t[b'1' as usize] = true; t[b'2' as usize] = true;
        t[b'3' as usize] = true; t[b'4' as usize] = true; t[b'5' as usize] = true;
        t[b'6' as usize] = true; t[b'7' as usize] = true; t[b'8' as usize] = true;
        t[b'9' as usize] = true; t[b'a' as usize] = true; t[b'b' as usize] = true;
        t[b'c' as usize] = true; t[b'd' as usize] = true; t[b'e' as usize] = true;
        t[b'f' as usize] = true;
        t
    };
    bytes.iter().all(|&b| IS_LOWER_HEX[b as usize])
}

/// Encrypt a string using ENCRYPTION_KEY vault (ChaCha20-Poly1305).
/// If `password` is Some, derives a key from it instead.
pub async fn maybe_encrypt_inner(mut input: String, password: Option<String>) -> String {
    let mut key: [u8; 32] = if password.is_none() {
        crate::state::ENCRYPTION_KEY.get().expect("Encryption key must be set")
    } else {
        hash_pass(&password.unwrap()).await
    };

    let mut rng = rand::thread_rng();
    let nonce_bytes: [u8; 12] = rng.gen();

    let cipher = ChaCha20Poly1305::new_from_slice(&key)
        .expect("Key should be valid");
    let nonce: Nonce = nonce_bytes.into();

    let ciphertext = cipher
        .encrypt(&nonce, input.as_bytes())
        .expect("Encryption should not fail");
    input.zeroize();

    let mut buffer = Vec::with_capacity(nonce_bytes.len() + ciphertext.len());
    buffer.extend_from_slice(&nonce_bytes);
    buffer.extend_from_slice(&ciphertext);

    if !crate::state::ENCRYPTION_KEY.has_key() {
        crate::state::ENCRYPTION_KEY.set(key, &[&crate::state::MY_SECRET_KEY]);
    }

    key.zeroize();

    crate::simd::hex::bytes_to_hex_string(&buffer)
}

/// Decrypt a hex-encoded ChaCha20-Poly1305 ciphertext using ENCRYPTION_KEY vault.
/// If `password` is Some, derives a key from it instead.
pub async fn maybe_decrypt_inner(ciphertext: String, password: Option<String>) -> Result<String, ()> {
    let has_password = password.is_some();

    let mut key: [u8; 32] = if let Some(pass) = password {
        hash_pass(&pass).await
    } else {
        match crate::state::ENCRYPTION_KEY.get() {
            Some(k) => k,
            None => return Err(()),
        }
    };

    let encrypted_data = crate::simd::hex::hex_string_to_bytes(ciphertext.as_str());
    if encrypted_data.len() < 12 {
        key.zeroize();
        return Err(());
    }

    let (nonce_bytes, actual_ciphertext) = encrypted_data.split_at(12);

    let cipher = match ChaCha20Poly1305::new_from_slice(&key) {
        Ok(c) => c,
        Err(_) => { key.zeroize(); return Err(()) }
    };

    let nonce_arr: [u8; 12] = match nonce_bytes.try_into() {
        Ok(n) => n,
        Err(_) => { key.zeroize(); return Err(()) }
    };
    let nonce: Nonce = nonce_arr.into();
    let plaintext = match cipher.decrypt(&nonce, actual_ciphertext) {
        Ok(pt) => pt,
        Err(_) => { key.zeroize(); return Err(()) }
    };

    if has_password && !crate::state::ENCRYPTION_KEY.has_key() {
        crate::state::ENCRYPTION_KEY.set(key, &[&crate::state::MY_SECRET_KEY]);
    }

    key.zeroize();

    // SAFETY: plaintext was originally valid UTF-8, authenticated decryption ensures integrity
    unsafe { Ok(String::from_utf8_unchecked(plaintext)) }
}

/// Conditionally encrypt content based on encryption_enabled setting.
pub async fn maybe_encrypt(input: String) -> String {
    if crate::state::is_encryption_enabled_fast() {
        maybe_encrypt_inner(input, None).await
    } else {
        input
    }
}

/// Conditionally decrypt content. Handles crash recovery — if decryption fails
/// on non-encrypted-looking content, returns it as-is.
pub async fn maybe_decrypt(input: String) -> Result<String, ()> {
    if crate::state::is_encryption_enabled_fast() {
        match maybe_decrypt_inner(input.clone(), None).await {
            Ok(decrypted) => Ok(decrypted),
            Err(_) => {
                if looks_encrypted(&input) { Err(()) } else { Ok(input) }
            }
        }
    } else {
        if looks_encrypted(&input) {
            match maybe_decrypt_inner(input.clone(), None).await {
                Ok(decrypted) => Ok(decrypted),
                Err(_) => Ok(input),
            }
        } else {
            Ok(input)
        }
    }
}

// ============================================================================
// Synchronous at-rest helpers (Concord tables, sync DB code)
// ============================================================================
//
// `maybe_encrypt`/`maybe_decrypt` are async (they may derive a key from a
// password). The Concord DB layer is synchronous and only ever uses the live
// ENCRYPTION_KEY vault, so these sync variants wrap the field-level primitives
// against the vault + the enabled flag. Discriminators for the half-migrated
// case: a key BLOB is 32 bytes raw vs 12+len+16 encrypted; a text field uses
// `looks_encrypted` (>=56 lowercase-hex chars).

/// ChaCha20-Poly1305 encrypt raw bytes with an explicit key → `nonce(12) || ct || tag(16)`.
pub fn encrypt_blob_with_key(plaintext: &[u8], key: &[u8; 32]) -> Result<Vec<u8>, String> {
    use rand::Rng;
    let cipher = ChaCha20Poly1305::new_from_slice(key).map_err(|e| e.to_string())?;
    let nonce_bytes: [u8; 12] = rand::thread_rng().gen();
    let nonce = chacha20poly1305::Nonce::from(nonce_bytes);
    let ct = cipher
        .encrypt(&nonce, plaintext)
        .map_err(|e| format!("blob encryption failed: {}", e))?;
    let mut out = Vec::with_capacity(12 + ct.len());
    out.extend_from_slice(&nonce_bytes);
    out.extend_from_slice(&ct);
    Ok(out)
}

/// ChaCha20-Poly1305 decrypt `nonce(12) || ct || tag(16)` with an explicit key.
pub fn decrypt_blob_with_key(stored: &[u8], key: &[u8; 32]) -> Result<Vec<u8>, String> {
    if stored.len() < 12 + 16 {
        return Err("blob too short to be ciphertext".to_string());
    }
    let cipher = ChaCha20Poly1305::new_from_slice(key).map_err(|e| e.to_string())?;
    let (nonce_bytes, ct) = stored.split_at(12);
    let nonce_arr: [u8; 12] = nonce_bytes.try_into().map_err(|_| "bad nonce".to_string())?;
    let nonce = chacha20poly1305::Nonce::from(nonce_arr);
    cipher
        .decrypt(&nonce, ct)
        .map_err(|_| "blob decryption failed (wrong key or corrupted)".to_string())
}

/// Encrypt a secret key BLOB for at-rest storage. Off → unchanged. Enabled but
/// the vault is empty → Err (never silently persists a secret in plaintext).
pub fn maybe_encrypt_blob(plaintext: &[u8]) -> Result<Vec<u8>, String> {
    if !crate::state::is_encryption_enabled_fast() {
        return Ok(plaintext.to_vec());
    }
    let mut key = crate::state::ENCRYPTION_KEY
        .get()
        .ok_or_else(|| "encryption enabled but key vault is empty".to_string())?;
    let out = encrypt_blob_with_key(plaintext, &key);
    key.zeroize();
    out
}

/// Decrypt a secret key BLOB. Tolerant of the half-migrated DB: a 32-byte value
/// is a raw (not-yet-wrapped / encryption-off) key, and anything that fails to
/// authenticate is returned as-is, so a mixed store always reads back correctly.
pub fn maybe_decrypt_blob(stored: &[u8]) -> Vec<u8> {
    // 32 bytes = a raw key (encryption off, or a row written before the at-rest pass).
    if stored.len() == 32 {
        return stored.to_vec();
    }
    match crate::state::ENCRYPTION_KEY.get() {
        Some(mut key) => {
            let out = decrypt_blob_with_key(stored, &key).unwrap_or_else(|_| stored.to_vec());
            key.zeroize();
            out
        }
        None => stored.to_vec(),
    }
}

/// Encrypt a text field for at-rest storage. Off → unchanged. Enabled but the
/// vault is empty → Err.
pub fn maybe_encrypt_text(plaintext: &str) -> Result<String, String> {
    if !crate::state::is_encryption_enabled_fast() {
        return Ok(plaintext.to_string());
    }
    let mut key = crate::state::ENCRYPTION_KEY
        .get()
        .ok_or_else(|| "encryption enabled but key vault is empty".to_string())?;
    let out = encrypt_with_key(plaintext, &key);
    key.zeroize();
    out
}

/// Decrypt a text field. A value that doesn't look encrypted (or can't be
/// decrypted) is returned as-is — pre-migration rows and encryption-off rows.
pub fn maybe_decrypt_text(stored: &str) -> String {
    if !looks_encrypted(stored) {
        return stored.to_string();
    }
    match crate::state::ENCRYPTION_KEY.get() {
        Some(mut key) => {
            let out = decrypt_with_key(stored, &key).unwrap_or_else(|_| stored.to_string());
            key.zeroize();
            out
        }
        None => stored.to_string(),
    }
}

#[cfg(test)]
mod at_rest_tests {
    use super::*;

    #[test]
    fn blob_roundtrip_with_explicit_key() {
        let key = [7u8; 32];
        let secret = [0x42u8; 32];
        let ct = encrypt_blob_with_key(&secret, &key).unwrap();
        assert_eq!(ct.len(), 12 + 32 + 16, "nonce + ciphertext + tag");
        assert_ne!(&ct[12..44], &secret[..], "ciphertext must not equal plaintext");
        assert_eq!(decrypt_blob_with_key(&ct, &key).unwrap(), secret.to_vec());
    }

    #[test]
    fn blob_wrong_key_fails() {
        let ct = encrypt_blob_with_key(&[1u8; 32], &[7u8; 32]).unwrap();
        assert!(decrypt_blob_with_key(&ct, &[9u8; 32]).is_err());
    }

    #[test]
    fn encrypted_text_is_always_detected_as_encrypted() {
        // Even the shortest fields ("[]", "{}", "") must exceed the looks_encrypted floor
        // so they round-trip through maybe_decrypt_text.
        let key = [3u8; 32];
        for s in ["", "[]", "{}", "a"] {
            let ct = encrypt_with_key(s, &key).unwrap();
            assert!(looks_encrypted(&ct), "ciphertext for {:?} must look encrypted", s);
            assert_eq!(decrypt_with_key(&ct, &key).unwrap(), s);
        }
    }
}

// ============================================================================
// Image Metadata — thumbhash + dimensions for file attachments
// ============================================================================

/// Re-export SIMD nearest-neighbor downsample from simd::image.
pub use crate::simd::image::nearest_neighbor_downsample_rgba;

/// Generate a thumbhash from RGBA8 pixel data.
///
/// Downscales to fit within 100x100 (ThumbHash's max) using fast nearest-neighbor,
/// then hashes. Returns the base91-encoded thumbhash string.
pub fn generate_thumbhash_from_rgba(pixels: &[u8], width: u32, height: u32) -> Option<String> {
    use fast_thumbhash::{rgba_to_thumb_hash, base91_encode};

    const MAX_DIM: u32 = 100;

    let (thumb_w, thumb_h) = if width <= MAX_DIM && height <= MAX_DIM {
        (width, height)
    } else if width > height {
        (MAX_DIM, (MAX_DIM * height / width).max(1))
    } else {
        ((MAX_DIM * width / height).max(1), MAX_DIM)
    };

    let thumbnail = if thumb_w == width && thumb_h == height {
        pixels.to_vec()
    } else {
        nearest_neighbor_downsample_rgba(pixels, width, height, thumb_w, thumb_h)
    };

    let hash = rgba_to_thumb_hash(thumb_w as usize, thumb_h as usize, &thumbnail);
    Some(base91_encode(&hash))
}

/// Decode an image with allocation limits. A tiny file declaring 60000×60000
/// would otherwise allocate ~14 GB before a single pixel decodes — every
/// decode of bytes we didn't author must go through this.
pub fn decode_image_bounded(bytes: &[u8]) -> Result<image::DynamicImage, String> {
    let mut reader = image::ImageReader::new(std::io::Cursor::new(bytes))
        .with_guessed_format()
        .map_err(|e| format!("image format: {e}"))?;
    reader.limits(bounded_image_limits());
    reader.decode().map_err(|e| format!("image decode: {e}"))
}

/// Shared decode limits for [`decode_image_bounded`] and call sites that need
/// their own `ImageReader` (fixed-format decodes).
pub fn bounded_image_limits() -> image::Limits {
    let mut limits = image::Limits::default();
    limits.max_image_width = Some(16_384);
    limits.max_image_height = Some(16_384);
    limits.max_alloc = Some(256 * 1024 * 1024);
    limits
}

/// Generate image metadata (thumbhash + dimensions) from raw file bytes.
///
/// Returns None if the bytes can't be decoded as an image.
/// Used by `send_file_dm` to automatically include preview metadata for images.
pub fn generate_image_metadata(file_bytes: &[u8]) -> Option<crate::types::ImageMetadata> {
    let img = decode_image_bounded(file_bytes).ok()?;
    let width = img.width();
    let height = img.height();

    let rgba = img.to_rgba8();
    let thumbhash = generate_thumbhash_from_rgba(rgba.as_raw(), width, height)?;

    Some(crate::types::ImageMetadata {
        thumbhash,
        width,
        height,
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    // ========================================================================
    // encrypt_with_key / decrypt_with_key roundtrip tests
    // ========================================================================

    fn test_key() -> [u8; 32] {
        [0x42u8; 32]
    }

    fn alt_key() -> [u8; 32] {
        [0x99u8; 32]
    }

    #[test]
    fn encrypt_decrypt_roundtrip_simple() {
        let key = test_key();
        let plaintext = "hello world";
        let encrypted = encrypt_with_key(plaintext, &key).expect("encryption should succeed");
        let decrypted = decrypt_with_key(&encrypted, &key).expect("decryption should succeed");
        assert_eq!(decrypted, plaintext, "roundtrip should preserve plaintext");
    }

    #[test]
    fn encrypt_decrypt_100_random_strings() {
        use rand::Rng;
        let key = test_key();
        let mut rng = rand::thread_rng();
        for i in 0..100 {
            let len = rng.gen_range(1..=200);
            let s: String = (0..len).map(|_| rng.gen_range(0x20u8..0x7f) as char).collect();
            let enc = encrypt_with_key(&s, &key)
                .unwrap_or_else(|e| panic!("encryption failed on iteration {}: {}", i, e));
            let dec = decrypt_with_key(&enc, &key)
                .unwrap_or_else(|e| panic!("decryption failed on iteration {}: {}", i, e));
            assert_eq!(dec, s, "roundtrip failed on iteration {}", i);
        }
    }

    #[test]
    fn encrypt_decrypt_empty_string() {
        let key = test_key();
        let encrypted = encrypt_with_key("", &key).expect("encrypting empty string should succeed");
        let decrypted = decrypt_with_key(&encrypted, &key).expect("decrypting empty string should succeed");
        assert_eq!(decrypted, "", "empty string roundtrip should produce empty string");
    }

    #[test]
    fn encrypt_decrypt_large_string() {
        let key = test_key();
        let plaintext = "A".repeat(10 * 1024); // 10 KB
        let encrypted = encrypt_with_key(&plaintext, &key).expect("encrypting 10KB should succeed");
        let decrypted = decrypt_with_key(&encrypted, &key).expect("decrypting 10KB should succeed");
        assert_eq!(decrypted, plaintext, "10KB roundtrip should preserve content");
    }

    #[test]
    fn decrypt_with_wrong_key_fails() {
        let key = test_key();
        let wrong_key = alt_key();
        let encrypted = encrypt_with_key("secret data", &key).expect("encryption should succeed");
        let result = decrypt_with_key(&encrypted, &wrong_key);
        assert!(result.is_err(), "decryption with wrong key should fail");
    }

    #[test]
    fn decrypt_corrupted_ciphertext_fails() {
        let key = test_key();
        let mut encrypted = encrypt_with_key("secret data", &key).expect("encryption should succeed");
        // Corrupt a byte in the ciphertext portion (past the 24-char nonce)
        let bytes: Vec<u8> = encrypted.bytes().collect();
        if bytes.len() > 30 {
            let mut chars: Vec<char> = encrypted.chars().collect();
            // Flip a hex digit in the ciphertext area
            chars[30] = if chars[30] == '0' { 'f' } else { '0' };
            encrypted = chars.into_iter().collect();
        }
        let result = decrypt_with_key(&encrypted, &key);
        assert!(result.is_err(), "decryption of corrupted ciphertext should fail");
    }

    #[test]
    fn different_keys_produce_different_ciphertext() {
        let key1 = test_key();
        let key2 = alt_key();
        let plaintext = "same plaintext";
        let enc1 = encrypt_with_key(plaintext, &key1).expect("enc1 should succeed");
        let enc2 = encrypt_with_key(plaintext, &key2).expect("enc2 should succeed");
        // Ciphertexts after the nonce portion should differ (nonces differ too since random)
        assert_ne!(enc1, enc2, "different keys should produce different ciphertext");
    }

    #[test]
    fn nonce_is_always_different() {
        let key = test_key();
        let plaintext = "same string encrypted twice";
        let enc1 = encrypt_with_key(plaintext, &key).expect("enc1 should succeed");
        let enc2 = encrypt_with_key(plaintext, &key).expect("enc2 should succeed");
        // The first 24 hex chars are the nonce
        let nonce1 = &enc1[..24];
        let nonce2 = &enc2[..24];
        assert_ne!(nonce1, nonce2, "nonces should differ between encryptions of the same plaintext");
    }

    #[test]
    fn unicode_content_preserved() {
        let key = test_key();
        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}";
        let encrypted = encrypt_with_key(plaintext, &key).expect("encrypting unicode should succeed");
        let decrypted = decrypt_with_key(&encrypted, &key).expect("decrypting unicode should succeed");
        assert_eq!(decrypted, plaintext, "unicode content should be preserved through encrypt/decrypt");
    }

    #[test]
    fn decrypt_too_short_ciphertext_fails() {
        let key = test_key();
        let result = decrypt_with_key("abcdef", &key);
        assert!(result.is_err(), "ciphertext shorter than 24 hex chars should fail");
        assert!(result.unwrap_err().contains("too short"), "error should mention too short");
    }

    #[test]
    fn encrypt_output_is_hex_encoded() {
        let key = test_key();
        let encrypted = encrypt_with_key("test", &key).expect("encryption should succeed");
        assert!(encrypted.chars().all(|c| c.is_ascii_hexdigit()),
            "encrypted output should be entirely hex characters");
    }

    #[test]
    fn encrypt_output_has_correct_structure() {
        let key = test_key();
        let encrypted = encrypt_with_key("test", &key).expect("encryption should succeed");
        // Must be at least 24 hex chars (nonce) + some ciphertext
        assert!(encrypted.len() > 24,
            "encrypted output should have nonce (24 hex chars) plus ciphertext");
        // Length should be even (hex pairs)
        assert_eq!(encrypted.len() % 2, 0,
            "encrypted output length should be even (hex pairs)");
    }

    #[test]
    fn encrypt_decrypt_special_characters() {
        let key = test_key();
        let plaintext = r#"!@#$%^&*()_+-=[]{}|;':",.<>?/\`~"#;
        let encrypted = encrypt_with_key(plaintext, &key).expect("encrypting special chars should succeed");
        let decrypted = decrypt_with_key(&encrypted, &key).expect("decrypting special chars should succeed");
        assert_eq!(decrypted, plaintext, "special characters should survive roundtrip");
    }

    #[test]
    fn encrypt_decrypt_newlines_and_whitespace() {
        let key = test_key();
        let plaintext = "line1\nline2\r\nline3\ttab\0null";
        let encrypted = encrypt_with_key(plaintext, &key).expect("encrypting whitespace should succeed");
        let decrypted = decrypt_with_key(&encrypted, &key).expect("decrypting whitespace should succeed");
        assert_eq!(decrypted, plaintext, "whitespace and control chars should survive roundtrip");
    }

    #[test]
    fn decrypt_invalid_hex_in_nonce_fails() {
        let key = test_key();
        // 24 chars of invalid hex + some ciphertext
        let bad = "zzzzzzzzzzzzzzzzzzzzzzzz0000000000000000";
        let result = decrypt_with_key(bad, &key);
        assert!(result.is_err(), "invalid hex in nonce should fail");
    }

    #[test]
    fn decrypt_invalid_hex_in_ciphertext_fails() {
        let key = test_key();
        // Valid nonce (24 hex chars) + invalid ciphertext hex
        let bad = "000000000000000000000000gggggggg";
        let result = decrypt_with_key(bad, &key);
        assert!(result.is_err(), "invalid hex in ciphertext should fail");
    }

    // ========================================================================
    // hex module tests
    // ========================================================================

    #[test]
    fn hex_encode_decode_roundtrip() {
        let data = vec![0x00, 0x01, 0xff, 0x80, 0x7f];
        let encoded = hex::encode(&data);
        let decoded = hex::decode(&encoded).expect("decode should succeed");
        assert_eq!(decoded, data, "hex encode/decode roundtrip should preserve bytes");
    }

    #[test]
    fn hex_decode_odd_length_error() {
        let result = hex::decode("abc");
        assert!(result.is_err(), "odd-length hex string should fail");
        assert!(result.unwrap_err().contains("Odd-length"), "error should mention odd-length");
    }

    #[test]
    fn hex_decode_invalid_hex_error() {
        let result = hex::decode("zzzz");
        assert!(result.is_err(), "invalid hex characters should fail");
    }

    #[test]
    fn hex_encode_empty() {
        assert_eq!(hex::encode(&[]), "", "encoding empty bytes should produce empty string");
    }

    #[test]
    fn hex_decode_empty() {
        let decoded = hex::decode("").expect("decoding empty string should succeed");
        assert!(decoded.is_empty(), "decoding empty string should produce empty vec");
    }

    // ========================================================================
    // hash_pass tests
    // ========================================================================

    #[tokio::test]
    async fn hash_pass_deterministic() {
        let key1 = hash_pass("my_password").await;
        let key2 = hash_pass("my_password").await;
        assert_eq!(key1, key2, "same password should always produce the same key");
    }

    #[tokio::test]
    async fn hash_pass_different_passwords_different_keys() {
        let key1 = hash_pass("password_one").await;
        let key2 = hash_pass("password_two").await;
        assert_ne!(key1, key2, "different passwords should produce different keys");
    }

    #[tokio::test]
    async fn hash_pass_output_is_32_bytes() {
        let key = hash_pass("test_password").await;
        assert_eq!(key.len(), 32, "hash_pass should produce exactly 32 bytes");
        // Ensure it is not all zeros (i.e. hashing actually happened)
        assert!(key.iter().any(|&b| b != 0), "hash output should not be all zeros");
    }

    #[test]
    fn generate_thumbhash_from_bytes_basic() {
        // 2x2 red pixel image in RGBA
        let pixels: Vec<u8> = vec![
            255, 0, 0, 255,  255, 0, 0, 255,
            255, 0, 0, 255,  255, 0, 0, 255,
        ];
        let result = super::generate_thumbhash_from_rgba(&pixels, 2, 2);
        assert!(result.is_some());
        assert!(!result.unwrap().is_empty());
    }

    #[test]
    fn generate_image_metadata_from_bytes() {
        // Create a 4x4 blue PNG in memory
        let img = image::RgbaImage::from_pixel(4, 4, image::Rgba([0, 0, 255, 255]));
        let mut buf = Vec::new();
        let mut cursor = std::io::Cursor::new(&mut buf);
        img.write_to(&mut cursor, image::ImageFormat::Png).unwrap();

        let meta = super::generate_image_metadata(&buf);
        assert!(meta.is_some());
        let meta = meta.unwrap();
        assert_eq!(meta.width, 4);
        assert_eq!(meta.height, 4);
        assert!(!meta.thumbhash.is_empty());
    }

    #[test]
    fn generate_image_metadata_non_image() {
        let text_bytes = b"this is not an image";
        let meta = super::generate_image_metadata(text_bytes);
        assert!(meta.is_none());
    }
}