aerovault 0.6.2

Military-grade encrypted vault format and CLI: AES-256-GCM-SIV, Argon2id, AES-KW, HMAC-SHA512, plus detached Reed-Solomon .aerocorrect error-correction sidecars
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
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
//! High-level vault operations.
//!
//! This module provides the public API for creating, opening, and manipulating
//! AeroVault v2 containers. All mutations use atomic writes (temp + fsync + rename)
//! to prevent data corruption on crash or power loss.

use std::fs::{File, OpenOptions};
use std::io::{BufReader, BufWriter, Read, Write};
use std::path::{Path, PathBuf};

use rand::RngCore;
use secrecy::{ExposeSecret, SecretString, SecretVec};
use zeroize::Zeroize;

use crate::constants::*;
use crate::crypto;
use crate::error::{CryptoError, Error, FormatError};
use crate::format::*;

/// Minimum allowed chunk size (4 KiB).
const MIN_CHUNK_SIZE: u32 = 4 * 1024;

/// Maximum allowed chunk size (16 MiB).
const MAX_CHUNK_SIZE: u32 = 16 * 1024 * 1024;

/// Options for creating a new vault.
pub struct CreateOptions {
    path: PathBuf,
    password: SecretString,
    mode: EncryptionMode,
    chunk_size: u32,
    version: u8,
}

impl CreateOptions {
    /// Create new vault options with the given path and password.
    pub fn new(path: impl Into<PathBuf>, password: impl Into<String>) -> Self {
        Self {
            path: path.into(),
            password: SecretString::from(password.into()),
            mode: EncryptionMode::Standard,
            chunk_size: DEFAULT_CHUNK_SIZE,
            version: VERSION,
        }
    }

    /// Select the on-disk container version to write.
    ///
    /// Defaults to the current [`VERSION`] (v3, file-id-bound chunk AAD).
    /// Pass [`LEGACY_VERSION`] (v2, chunk-index-only AAD) to write a legacy
    /// container, e.g. for migration tooling or backward-compat round-trip
    /// tests. Any other value is rejected at [`Vault::create`]. Readers accept
    /// both versions regardless of which one was written.
    pub fn with_version(mut self, version: u8) -> Self {
        self.version = version;
        self
    }

    /// Set the encryption mode.
    pub fn with_mode(mut self, mode: EncryptionMode) -> Self {
        self.mode = mode;
        self
    }

    /// Set a custom chunk size.
    ///
    /// Must be between 4 KiB and 16 MiB. Returns an error at vault creation
    /// if the value is out of range.
    pub fn with_chunk_size(mut self, size: u32) -> Self {
        self.chunk_size = size;
        self
    }
}

/// Decrypted entry information returned by listing operations.
#[derive(Debug, Clone)]
pub struct EntryInfo {
    /// Decrypted filename (may contain `/` for nested paths).
    pub name: String,
    /// Original file size in bytes.
    pub size: u64,
    /// Whether this is a directory entry.
    pub is_dir: bool,
    /// Last modification timestamp (ISO 8601).
    pub modified: String,
}

/// An unlocked AeroVault v2 container.
///
/// Created via [`Vault::create`] or [`Vault::open`]. Holds decrypted keys
/// in memory — drop the vault when done to zeroize secrets.
pub struct Vault {
    path: PathBuf,
    header: VaultHeader,
    master_key: SecretVec<u8>,
    mac_key: SecretVec<u8>,
}

impl Vault {
    /// Create a new empty vault at the specified path.
    ///
    /// # Errors
    ///
    /// Returns an error if the password is too short (< 8 chars), the chunk
    /// size is out of range, or the file cannot be written.
    pub fn create(opts: CreateOptions) -> crate::Result<Self> {
        if opts.password.expose_secret().len() < MIN_PASSWORD_LENGTH {
            return Err(crate::Error::PasswordPolicy(format!(
                "password must be at least {MIN_PASSWORD_LENGTH} characters"
            )));
        }

        if opts.chunk_size < MIN_CHUNK_SIZE || opts.chunk_size > MAX_CHUNK_SIZE {
            return Err(FormatError::InvalidChunkSize(opts.chunk_size).into());
        }

        if opts.version != VERSION && opts.version != LEGACY_VERSION {
            return Err(FormatError::UnsupportedVersion(opts.version).into());
        }

        // Generate random salt
        let mut salt = [0u8; SALT_SIZE];
        rand::rngs::OsRng.fill_bytes(&mut salt);

        // Derive base KEK from password
        let base_kek = crypto::derive_key(&opts.password, &salt)?;
        let (kek_master, kek_mac) = crypto::derive_kek_pair(base_kek.expose_secret());

        // Generate random master and MAC keys
        let mut master_key_raw = [0u8; KEY_SIZE];
        let mut mac_key_raw = [0u8; KEY_SIZE];
        rand::rngs::OsRng.fill_bytes(&mut master_key_raw);
        rand::rngs::OsRng.fill_bytes(&mut mac_key_raw);

        // Wrap keys
        let wrapped_master = crypto::wrap_key(&kek_master, &master_key_raw)?;
        let wrapped_mac = crypto::wrap_key(&kek_mac, &mac_key_raw)?;

        // kek_master and kek_mac are Zeroizing — auto-dropped

        // Build header
        let flags = HeaderFlags {
            cascade_mode: opts.mode == EncryptionMode::Cascade,
        };

        let mut header = VaultHeader {
            magic: *MAGIC,
            version: opts.version,
            flags,
            salt,
            wrapped_master_key: wrapped_master,
            wrapped_mac_key: wrapped_mac,
            chunk_size: opts.chunk_size,
            reserved: [0u8; 320],
            header_mac: [0u8; MAC_SIZE],
        };
        header.header_mac = header.compute_mac(&mac_key_raw);

        // Create empty manifest
        let now = chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string();
        let manifest = VaultManifest {
            created: now.clone(),
            modified: now,
            description: None,
            entries: Vec::new(),
        };

        let manifest_json =
            serde_json::to_string(&manifest).map_err(|e| crate::Error::Manifest(e.to_string()))?;
        let encrypted_manifest = crypto::encrypt_filename(&master_key_raw, &manifest_json)?;
        let manifest_bytes = encrypted_manifest.as_bytes();

        // Write vault file atomically via temp + fsync + rename
        let tmp_path = format!("{}.create.tmp", opts.path.display());
        let file = File::create(&tmp_path)?;
        let mut writer = BufWriter::new(file);

        writer.write_all(&header.to_bytes())?;
        writer.write_all(&(manifest_bytes.len() as u32).to_le_bytes())?;
        writer.write_all(manifest_bytes)?;
        writer.flush()?;
        writer.get_ref().sync_all()?;
        drop(writer);

        atomic_rename(&tmp_path, &opts.path)?;

        let master_key = SecretVec::new(master_key_raw.to_vec());
        let mac_key = SecretVec::new(mac_key_raw.to_vec());

        master_key_raw.zeroize();
        mac_key_raw.zeroize();

        Ok(Self {
            path: opts.path,
            header,
            master_key,
            mac_key,
        })
    }

    /// Open an existing vault with the given password.
    ///
    /// Verifies the header MAC before unwrapping the master key.
    ///
    /// # Errors
    ///
    /// Returns [`CryptoError::KeyUnwrap`] if the password is wrong, or
    /// [`CryptoError::HeaderMacMismatch`] if the header has been tampered with.
    pub fn open(path: impl Into<PathBuf>, password: impl Into<String>) -> crate::Result<Self> {
        let path = path.into();
        let pwd = SecretString::from(password.into());

        let file = File::open(&path)?;
        let mut reader = BufReader::new(file);

        // Read header
        let mut header_buf = [0u8; HEADER_SIZE];
        reader.read_exact(&mut header_buf)?;
        let header = VaultHeader::from_bytes(&header_buf)?;

        // Derive keys
        let base_kek = crypto::derive_key(&pwd, &header.salt)?;
        let (kek_master, kek_mac) = crypto::derive_kek_pair(base_kek.expose_secret());

        // Unwrap MAC key first, verify header MAC, then unwrap master key
        let mac_key = crypto::unwrap_key(&kek_mac, &header.wrapped_mac_key)?;
        header.verify_mac(mac_key.expose_secret())?;
        let master_key = crypto::unwrap_key(&kek_master, &header.wrapped_master_key)?;

        // kek_master and kek_mac are Zeroizing — auto-dropped

        Ok(Self {
            path,
            header,
            master_key,
            mac_key,
        })
    }

    /// Check if a file is an AeroVault v2 container (reads only the first 11 bytes).
    pub fn is_vault(path: impl AsRef<Path>) -> bool {
        let Ok(file) = File::open(path.as_ref()) else {
            return false;
        };
        let mut buf = [0u8; 11];
        let mut reader = BufReader::new(file);
        if reader.read_exact(&mut buf).is_err() {
            return false;
        }
        &buf[..10] == MAGIC && (buf[10] == VERSION || buf[10] == LEGACY_VERSION)
    }

    /// Read vault header information without a password.
    ///
    /// Returns basic metadata (version, encryption mode, chunk size) that is
    /// stored unencrypted in the header. Useful for UI display before unlock.
    pub fn peek(path: impl AsRef<Path>) -> crate::Result<PeekInfo> {
        let file = File::open(path.as_ref())?;
        let mut reader = BufReader::new(file);
        let mut header_buf = [0u8; HEADER_SIZE];
        reader.read_exact(&mut header_buf)?;
        let header = VaultHeader::from_bytes(&header_buf)?;

        let mode = if header.flags.cascade_mode {
            EncryptionMode::Cascade
        } else {
            EncryptionMode::Standard
        };

        Ok(PeekInfo {
            version: header.version,
            mode,
            chunk_size: header.chunk_size,
        })
    }

    /// Get the vault file path.
    pub fn path(&self) -> &Path {
        &self.path
    }

    /// Get the encryption mode.
    pub fn mode(&self) -> EncryptionMode {
        if self.header.flags.cascade_mode {
            EncryptionMode::Cascade
        } else {
            EncryptionMode::Standard
        }
    }

    /// Get the chunk size.
    pub fn chunk_size(&self) -> u32 {
        self.header.chunk_size
    }

    /// Return security information about the vault.
    pub fn security_info(&self) -> SecurityInfo {
        SecurityInfo {
            version: self.header.version,
            mode: self.mode(),
            chunk_size: self.header.chunk_size,
            argon2_m_cost_kib: ARGON2_M_COST,
            argon2_t_cost: ARGON2_T_COST,
            argon2_p_cost: ARGON2_P_COST,
        }
    }

    /// List all entries in the vault with decrypted filenames.
    pub fn list(&self) -> crate::Result<Vec<EntryInfo>> {
        let manifest = self.read_manifest()?;
        let mut entries = Vec::with_capacity(manifest.entries.len());

        for entry in &manifest.entries {
            let name =
                crypto::decrypt_filename(self.master_key.expose_secret(), &entry.encrypted_name)?;
            entries.push(EntryInfo {
                name,
                size: entry.size,
                is_dir: entry.is_dir,
                modified: entry.modified.clone(),
            });
        }

        Ok(entries)
    }

    /// Add files from disk into the vault.
    ///
    /// Files are encrypted in chunks and appended to the data section.
    /// Duplicate filenames are silently skipped.
    pub fn add_files(&self, file_paths: &[impl AsRef<Path>]) -> crate::Result<u32> {
        self.add_files_to_dir(file_paths, "")
    }

    /// Add files to a specific directory inside the vault.
    ///
    /// The `target_dir` must already exist (or be empty for root).
    pub fn add_files_to_dir(
        &self,
        file_paths: &[impl AsRef<Path>],
        target_dir: &str,
    ) -> crate::Result<u32> {
        let target_dir = target_dir.trim().trim_matches('/');
        if target_dir.contains("..") {
            return Err(crate::Error::InvalidPath(
                "directory path cannot contain '..'".into(),
            ));
        }

        let cascade_mode = self.header.flags.cascade_mode;
        let chunk_size = self.header.chunk_size as usize;
        let bind_chunks = self.header.version >= VERSION;

        // Read current vault state
        let file = File::open(&self.path)?;
        let mut reader = BufReader::new(file);

        let mut header_buf = [0u8; HEADER_SIZE];
        reader.read_exact(&mut header_buf)?;

        let (_manifest_len, manifest_encrypted) = crypto::read_manifest_bounded(&mut reader)?;
        let manifest_str =
            std::str::from_utf8(&manifest_encrypted).map_err(|_| CryptoError::ManifestEncoding)?;
        let manifest_json =
            crypto::decrypt_filename(self.master_key.expose_secret(), manifest_str)?;

        let mut manifest: VaultManifest = serde_json::from_str(&manifest_json)
            .map_err(|e| crate::Error::Manifest(e.to_string()))?;

        // Verify target directory exists (if non-empty)
        if !target_dir.is_empty() {
            let target_encrypted =
                crypto::encrypt_filename(self.master_key.expose_secret(), target_dir)?;
            let dir_exists = manifest
                .entries
                .iter()
                .any(|e| e.encrypted_name == target_encrypted && e.is_dir);
            if !dir_exists {
                return Err(crate::Error::EntryNotFound(format!(
                    "target directory '{target_dir}'"
                )));
            }
        }

        // Read existing data
        let mut existing_data = Vec::new();
        reader.read_to_end(&mut existing_data)?;

        let chacha_key = if cascade_mode {
            crypto::derive_chacha_key(self.master_key.expose_secret())
        } else {
            zeroize::Zeroizing::new([0u8; KEY_SIZE])
        };

        let mut data_offset = existing_data.len() as u64;
        let mut new_data = Vec::new();
        let mut added_count = 0u32;

        for file_path in file_paths {
            let file_path = file_path.as_ref();
            let source = File::open(file_path)?;
            let metadata = source.metadata()?;

            let filename = file_path
                .file_name()
                .and_then(|n| n.to_str())
                .ok_or_else(|| crate::Error::InvalidPath(format!("{}", file_path.display())))?;

            let vault_name = if target_dir.is_empty() {
                filename.to_string()
            } else {
                format!("{target_dir}/{filename}")
            };

            // Check for duplicate
            let encrypted_name =
                crypto::encrypt_filename(self.master_key.expose_secret(), &vault_name)?;
            if manifest
                .entries
                .iter()
                .any(|e| e.encrypted_name == encrypted_name)
            {
                continue;
            }

            let mut source_reader = BufReader::new(source);
            let mut chunk_count = 0u32;
            let chunk_total = if metadata.len() == 0 {
                0
            } else {
                metadata
                    .len()
                    .div_ceil(chunk_size as u64)
                    .try_into()
                    .map_err(|_| crate::Error::Manifest("chunk count overflow".into()))?
            };
            let file_id = if bind_chunks {
                let mut id = [0u8; 16];
                rand::rngs::OsRng.fill_bytes(&mut id);
                Some(id)
            } else {
                None
            };
            let entry_offset = data_offset;

            loop {
                let mut chunk = vec![0u8; chunk_size];
                let bytes_read = source_reader.read(&mut chunk)?;
                if bytes_read == 0 {
                    break;
                }
                chunk.truncate(bytes_read);

                let encrypted_chunk = if cascade_mode {
                    crypto::encrypt_chunk_cascade_bound(
                        self.master_key.expose_secret(),
                        &chacha_key,
                        &chunk,
                        chunk_count,
                        file_id.as_ref(),
                        chunk_total,
                    )?
                } else {
                    crypto::encrypt_chunk_bound(
                        self.master_key.expose_secret(),
                        &chunk,
                        chunk_count,
                        file_id.as_ref(),
                        chunk_total,
                    )?
                };

                let chunk_len = encrypted_chunk.len() as u32;
                new_data.extend_from_slice(&chunk_len.to_le_bytes());
                new_data.extend_from_slice(&encrypted_chunk);

                data_offset += 4 + encrypted_chunk.len() as u64;
                chunk_count = chunk_count
                    .checked_add(1)
                    .ok_or_else(|| crate::Error::Manifest("chunk count overflow".into()))?;

                chunk.zeroize();
            }

            // The v3+ chunk AAD binds `chunk_total`, derived from the pre-stream
            // `metadata.len()`. Extraction rebuilds the AAD from the manifest's
            // stored `chunk_count` (the actual number of chunks streamed). If the
            // source changed size between the stat and the read, the two diverge
            // and every chunk would fail AAD verification on extract: a silently
            // unrecoverable entry. Fail the add instead of persisting it. (Legacy
            // v2 binds only the chunk index, so the mismatch is harmless there.)
            if bind_chunks && chunk_count != chunk_total {
                return Err(crate::Error::Manifest(format!(
                    "source changed size during add (bound {chunk_total} chunks, streamed {chunk_count}); aborting to avoid an unrecoverable entry"
                )));
            }

            let modified = metadata
                .modified()
                .map(|t| {
                    let datetime: chrono::DateTime<chrono::Utc> = t.into();
                    datetime.format("%Y-%m-%dT%H:%M:%SZ").to_string()
                })
                .unwrap_or_else(|_| chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string());

            manifest.entries.push(ManifestEntry {
                encrypted_name,
                name: String::new(),
                size: metadata.len(),
                offset: entry_offset,
                chunk_count,
                file_id,
                is_dir: false,
                modified,
            });

            added_count += 1;
        }

        if added_count > 0 {
            manifest.modified = chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string();
            self.write_vault_atomic(&header_buf, &manifest, &existing_data, &new_data)?;
        }

        // chacha_key is Zeroizing — auto-dropped
        Ok(added_count)
    }

    /// Create a directory inside the vault.
    ///
    /// Intermediate directories are created automatically (like `mkdir -p`).
    pub fn create_directory(&self, dir_name: &str) -> crate::Result<u32> {
        let dir_name = dir_name.trim().trim_matches('/');
        if dir_name.is_empty() {
            return Err(crate::Error::InvalidPath(
                "directory name cannot be empty".into(),
            ));
        }
        if dir_name.contains("..") {
            return Err(crate::Error::InvalidPath(
                "directory name cannot contain '..'".into(),
            ));
        }
        if dir_name.len() > 4096 {
            return Err(crate::Error::InvalidPath("directory name too long".into()));
        }

        let file = File::open(&self.path)?;
        let mut reader = BufReader::new(file);

        let mut header_buf = [0u8; HEADER_SIZE];
        reader.read_exact(&mut header_buf)?;

        let (_manifest_len, manifest_encrypted) = crypto::read_manifest_bounded(&mut reader)?;
        let manifest_str =
            std::str::from_utf8(&manifest_encrypted).map_err(|_| CryptoError::ManifestEncoding)?;
        let manifest_json =
            crypto::decrypt_filename(self.master_key.expose_secret(), manifest_str)?;

        let mut manifest: VaultManifest = serde_json::from_str(&manifest_json)
            .map_err(|e| crate::Error::Manifest(e.to_string()))?;

        let mut existing_data = Vec::new();
        reader.read_to_end(&mut existing_data)?;

        // Collect directories to create (including intermediates)
        let mut dirs_to_create = Vec::new();
        let parts: Vec<&str> = dir_name.split('/').collect();
        for i in 1..=parts.len() {
            let partial = parts[..i].join("/");
            let encrypted = crypto::encrypt_filename(self.master_key.expose_secret(), &partial)?;
            if !manifest
                .entries
                .iter()
                .any(|e| e.encrypted_name == encrypted)
            {
                dirs_to_create.push((partial, encrypted));
            }
        }

        if dirs_to_create.is_empty() {
            return Ok(0);
        }

        let now = chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string();
        for (_, encrypted_name) in &dirs_to_create {
            manifest.entries.push(ManifestEntry {
                encrypted_name: encrypted_name.clone(),
                name: String::new(),
                size: 0,
                offset: 0,
                chunk_count: 0,
                file_id: None,
                is_dir: true,
                modified: now.clone(),
            });
        }

        manifest.modified = now;
        let created = dirs_to_create.len() as u32;
        self.write_vault_atomic(&header_buf, &manifest, &existing_data, &[])?;

        Ok(created)
    }

    /// Extract a single entry to the specified output directory.
    ///
    /// Returns the full path of the extracted file. Validates that the output
    /// path stays within `output_dir` to prevent path traversal attacks.
    pub fn extract(
        &self,
        entry_name: &str,
        output_dir: impl AsRef<Path>,
    ) -> crate::Result<PathBuf> {
        let output_dir = output_dir.as_ref();

        // Validate entry name against path traversal
        validate_entry_name(entry_name)?;

        let manifest = self.read_manifest()?;

        // Find matching entry
        let entry = manifest
            .entries
            .iter()
            .find(|e| {
                crypto::decrypt_filename(self.master_key.expose_secret(), &e.encrypted_name)
                    .map(|name| name == entry_name)
                    .unwrap_or(false)
            })
            .ok_or_else(|| crate::Error::EntryNotFound(entry_name.to_string()))?;

        if entry.is_dir {
            let dir_path = output_dir.join(entry_name);
            validate_output_path(&dir_path, output_dir)?;
            std::fs::create_dir_all(&dir_path)?;
            return Ok(dir_path);
        }

        let cascade_mode = self.header.flags.cascade_mode;

        let chacha_key = if cascade_mode {
            crypto::derive_chacha_key(self.master_key.expose_secret())
        } else {
            zeroize::Zeroizing::new([0u8; KEY_SIZE])
        };

        // Open vault and seek to data section
        let file = File::open(&self.path)?;
        let mut reader = BufReader::new(file);

        // Skip header
        let mut skip_buf = [0u8; HEADER_SIZE];
        reader.read_exact(&mut skip_buf)?;

        // Skip manifest
        let (manifest_len, _manifest_data) = crypto::read_manifest_bounded(&mut reader)?;
        let data_start = HEADER_SIZE as u64 + 4 + manifest_len as u64;
        let vault_len = std::fs::metadata(&self.path)?.len();

        // Skip to entry offset
        let mut skipped = 0u64;
        while skipped < entry.offset {
            let to_skip = std::cmp::min(entry.offset - skipped, 8192) as usize;
            let mut skip = vec![0u8; to_skip];
            reader.read_exact(&mut skip)?;
            skipped += to_skip as u64;
        }

        // Determine safe output path
        let filename = Path::new(entry_name)
            .file_name()
            .and_then(|n| n.to_str())
            .ok_or_else(|| {
                crate::Error::InvalidPath(format!("invalid entry name: {entry_name}"))
            })?;
        let dest_path = output_dir.join(filename);
        validate_output_path(&dest_path, output_dir)?;

        if let Some(parent) = dest_path.parent() {
            std::fs::create_dir_all(parent)?;
        }

        let out_file = open_new_output_file(&dest_path, output_dir)?;
        let mut writer = BufWriter::new(out_file);

        // Read and decrypt chunks
        let mut entry_bytes_consumed = 0u64;
        for chunk_idx in 0..entry.chunk_count {
            let mut len_buf = [0u8; 4];
            reader.read_exact(&mut len_buf)?;
            let chunk_len = u32::from_le_bytes(len_buf) as usize;
            let bytes_remaining =
                vault_len.saturating_sub(data_start + entry.offset + entry_bytes_consumed + 4);
            validate_encrypted_chunk_len(
                chunk_len,
                bytes_remaining,
                self.header.chunk_size,
                cascade_mode,
            )?;
            entry_bytes_consumed += 4 + chunk_len as u64;

            let mut encrypted_chunk = vec![0u8; chunk_len];
            reader.read_exact(&mut encrypted_chunk)?;

            let mut plaintext = if cascade_mode {
                crypto::decrypt_chunk_cascade_bound(
                    self.master_key.expose_secret(),
                    &chacha_key,
                    &encrypted_chunk,
                    chunk_idx,
                    entry.file_id.as_ref(),
                    entry.chunk_count,
                )?
            } else {
                crypto::decrypt_chunk_bound(
                    self.master_key.expose_secret(),
                    &encrypted_chunk,
                    chunk_idx,
                    entry.file_id.as_ref(),
                    entry.chunk_count,
                )?
            };

            writer.write_all(&plaintext)?;
            plaintext.zeroize();
            encrypted_chunk.zeroize();
        }

        writer.flush()?;
        // chacha_key is Zeroizing — auto-dropped

        Ok(dest_path)
    }

    /// Extract all entries to the specified output directory.
    ///
    /// Returns the number of entries extracted.
    pub fn extract_all(&self, output_dir: impl AsRef<Path>) -> crate::Result<u32> {
        let entries = self.list()?;
        let mut count = 0u32;
        for entry in &entries {
            self.extract(&entry.name, output_dir.as_ref())?;
            count += 1;
        }
        Ok(count)
    }

    /// Delete an entry from the vault manifest.
    ///
    /// The encrypted data remains in the file but becomes orphaned.
    /// Use [`Vault::compact`] (future) to reclaim space.
    pub fn delete_entry(&self, entry_name: &str) -> crate::Result<()> {
        let file = File::open(&self.path)?;
        let mut reader = BufReader::new(file);

        let mut header_buf = [0u8; HEADER_SIZE];
        reader.read_exact(&mut header_buf)?;

        let (_manifest_len, manifest_encrypted) = crypto::read_manifest_bounded(&mut reader)?;
        let manifest_str =
            std::str::from_utf8(&manifest_encrypted).map_err(|_| CryptoError::ManifestEncoding)?;
        let manifest_json =
            crypto::decrypt_filename(self.master_key.expose_secret(), manifest_str)?;

        let mut manifest: VaultManifest = serde_json::from_str(&manifest_json)
            .map_err(|e| crate::Error::Manifest(e.to_string()))?;

        let mut data_section = Vec::new();
        reader.read_to_end(&mut data_section)?;

        // Find and remove entry
        let mut found = false;
        manifest.entries.retain(|entry| {
            match crypto::decrypt_filename(self.master_key.expose_secret(), &entry.encrypted_name) {
                Ok(name) if name == entry_name => {
                    found = true;
                    false
                }
                _ => true,
            }
        });

        if !found {
            return Err(crate::Error::EntryNotFound(entry_name.to_string()));
        }

        manifest.modified = chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string();
        self.write_vault_atomic(&header_buf, &manifest, &data_section, &[])?;
        Ok(())
    }

    /// Delete multiple entries from the vault manifest in a single pass.
    ///
    /// If `recursive` is true, deleting a directory also removes all entries
    /// under it (e.g., deleting "docs" also removes "docs/file.txt").
    /// Returns the number of entries removed.
    pub fn delete_entries(&self, names: &[&str], recursive: bool) -> crate::Result<u32> {
        let file = File::open(&self.path)?;
        let mut reader = BufReader::new(file);

        let mut header_buf = [0u8; HEADER_SIZE];
        reader.read_exact(&mut header_buf)?;

        let (_manifest_len, manifest_encrypted) = crypto::read_manifest_bounded(&mut reader)?;
        let manifest_str =
            std::str::from_utf8(&manifest_encrypted).map_err(|_| CryptoError::ManifestEncoding)?;
        let manifest_json =
            crypto::decrypt_filename(self.master_key.expose_secret(), manifest_str)?;

        let mut manifest: VaultManifest = serde_json::from_str(&manifest_json)
            .map_err(|e| crate::Error::Manifest(e.to_string()))?;

        let mut data_section = Vec::new();
        reader.read_to_end(&mut data_section)?;

        let original_count = manifest.entries.len();

        manifest.entries.retain(|entry| {
            let decrypted =
                crypto::decrypt_filename(self.master_key.expose_secret(), &entry.encrypted_name);
            match decrypted {
                Ok(name) => {
                    // Direct name match
                    if names.contains(&name.as_str()) {
                        return false;
                    }
                    // Recursive: remove children of deleted directories
                    if recursive {
                        for target in names {
                            if name.starts_with(&format!("{target}/")) {
                                return false;
                            }
                        }
                    }
                    true
                }
                Err(_) => true,
            }
        });

        let removed = (original_count - manifest.entries.len()) as u32;
        if removed > 0 {
            manifest.modified = chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string();
            self.write_vault_atomic(&header_buf, &manifest, &data_section, &[])?;
        }

        Ok(removed)
    }

    /// Move or rename an entry inside the vault.
    ///
    /// Supports both file and directory moves. When moving a directory, all
    /// descendant entries are moved as a single atomic manifest update.
    pub fn move_entry(&self, from: &str, to: &str) -> crate::Result<()> {
        let from = from.trim().trim_matches('/');
        let to = to.trim().trim_matches('/');

        if from.is_empty() || to.is_empty() {
            return Err(crate::Error::InvalidPath(
                "source and destination cannot be empty".into(),
            ));
        }

        validate_entry_name(from)?;
        validate_entry_name(to)?;

        if from == to {
            return Ok(());
        }

        if to.starts_with(&format!("{from}/")) {
            return Err(crate::Error::InvalidPath(
                "cannot move an entry into its own subtree".into(),
            ));
        }

        if from.len() > 4096 || to.len() > 4096 {
            return Err(crate::Error::InvalidPath("path too long".into()));
        }

        let file = File::open(&self.path)?;
        let mut reader = BufReader::new(file);

        let mut header_buf = [0u8; HEADER_SIZE];
        reader.read_exact(&mut header_buf)?;

        let (_manifest_len, manifest_encrypted) = crypto::read_manifest_bounded(&mut reader)?;
        let manifest_str =
            std::str::from_utf8(&manifest_encrypted).map_err(|_| CryptoError::ManifestEncoding)?;
        let manifest_json =
            crypto::decrypt_filename(self.master_key.expose_secret(), manifest_str)?;

        let mut manifest: VaultManifest = serde_json::from_str(&manifest_json)
            .map_err(|e| crate::Error::Manifest(e.to_string()))?;

        let mut data_section = Vec::new();
        reader.read_to_end(&mut data_section)?;

        let mut names: Vec<String> = Vec::with_capacity(manifest.entries.len());
        for entry in &manifest.entries {
            names.push(crypto::decrypt_filename(
                self.master_key.expose_secret(),
                &entry.encrypted_name,
            )?);
        }

        let src_index = names
            .iter()
            .position(|n| n == from)
            .ok_or_else(|| crate::Error::EntryNotFound(from.to_string()))?;
        let src_is_dir = manifest.entries[src_index].is_dir;

        let mut renames: Vec<(usize, String)> = Vec::new();
        for (idx, name) in names.iter().enumerate() {
            if src_is_dir {
                if name == from {
                    renames.push((idx, to.to_string()));
                } else if name.starts_with(&format!("{from}/")) {
                    renames.push((idx, format!("{to}{}", &name[from.len()..])));
                }
            } else if name == from {
                renames.push((idx, to.to_string()));
            }
        }

        if renames.is_empty() {
            return Err(crate::Error::EntryNotFound(from.to_string()));
        }

        // Build final entry map and validate uniqueness + parent directories.
        let mut final_map: std::collections::HashMap<String, bool> =
            std::collections::HashMap::new();
        for (idx, old_name) in names.iter().enumerate() {
            let resolved_name = renames
                .iter()
                .find(|(rename_idx, _)| *rename_idx == idx)
                .map(|(_, new_name)| new_name.as_str())
                .unwrap_or(old_name.as_str());

            if final_map
                .insert(resolved_name.to_string(), manifest.entries[idx].is_dir)
                .is_some()
            {
                return Err(crate::Error::Manifest(format!(
                    "target entry already exists: {resolved_name}"
                )));
            }
        }

        for name in final_map.keys() {
            if let Some((parent, _)) = name.rsplit_once('/') {
                if parent.is_empty() {
                    continue;
                }
                let parent_is_dir = final_map.get(parent).copied().unwrap_or(false);
                if !parent_is_dir {
                    return Err(crate::Error::EntryNotFound(format!(
                        "parent directory '{parent}'"
                    )));
                }
            }
        }

        let now = chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string();
        for (idx, new_name) in &renames {
            manifest.entries[*idx].encrypted_name =
                crypto::encrypt_filename(self.master_key.expose_secret(), new_name)?;
            manifest.entries[*idx].modified = now.clone();
        }

        manifest.modified = now;
        self.write_vault_atomic(&header_buf, &manifest, &data_section, &[])?;
        Ok(())
    }

    /// Rename an entry while keeping it in the same parent directory.
    pub fn rename_entry(&self, current_name: &str, new_name: &str) -> crate::Result<()> {
        let current_name = current_name.trim().trim_matches('/');
        let new_name = new_name.trim().trim_matches('/');

        if new_name.is_empty() {
            return Err(crate::Error::InvalidPath("new name cannot be empty".into()));
        }
        if new_name.contains('/') || new_name.contains('\\') || new_name.contains('\0') {
            return Err(crate::Error::InvalidPath(
                "new name must be a single path segment".into(),
            ));
        }
        if new_name == "." || new_name == ".." {
            return Err(crate::Error::InvalidPath("invalid new name".into()));
        }

        let target = if let Some((parent, _)) = current_name.rsplit_once('/') {
            format!("{parent}/{new_name}")
        } else {
            new_name.to_string()
        };

        self.move_entry(current_name, &target)
    }

    /// Copy an entry (file or directory) inside the vault.
    ///
    /// The copied entries reuse the existing encrypted data chunk references;
    /// only manifest metadata is duplicated and re-encrypted names are written.
    pub fn copy_entry(&self, from: &str, to: &str) -> crate::Result<()> {
        let from = from.trim().trim_matches('/');
        let to = to.trim().trim_matches('/');

        if from.is_empty() || to.is_empty() {
            return Err(crate::Error::InvalidPath(
                "source and destination cannot be empty".into(),
            ));
        }

        validate_entry_name(from)?;
        validate_entry_name(to)?;

        if from == to {
            return Err(crate::Error::Manifest("target entry already exists".into()));
        }

        if to.starts_with(&format!("{from}/")) {
            return Err(crate::Error::InvalidPath(
                "cannot copy an entry into its own subtree".into(),
            ));
        }

        if from.len() > 4096 || to.len() > 4096 {
            return Err(crate::Error::InvalidPath("path too long".into()));
        }

        let file = File::open(&self.path)?;
        let mut reader = BufReader::new(file);

        let mut header_buf = [0u8; HEADER_SIZE];
        reader.read_exact(&mut header_buf)?;

        let (_manifest_len, manifest_encrypted) = crypto::read_manifest_bounded(&mut reader)?;
        let manifest_str =
            std::str::from_utf8(&manifest_encrypted).map_err(|_| CryptoError::ManifestEncoding)?;
        let manifest_json =
            crypto::decrypt_filename(self.master_key.expose_secret(), manifest_str)?;

        let mut manifest: VaultManifest = serde_json::from_str(&manifest_json)
            .map_err(|e| crate::Error::Manifest(e.to_string()))?;

        let mut data_section = Vec::new();
        reader.read_to_end(&mut data_section)?;

        let mut names: Vec<String> = Vec::with_capacity(manifest.entries.len());
        for entry in &manifest.entries {
            names.push(crypto::decrypt_filename(
                self.master_key.expose_secret(),
                &entry.encrypted_name,
            )?);
        }

        let src_index = names
            .iter()
            .position(|n| n == from)
            .ok_or_else(|| crate::Error::EntryNotFound(from.to_string()))?;
        let src_is_dir = manifest.entries[src_index].is_dir;

        let mut copies: Vec<(usize, String)> = Vec::new();
        for (idx, name) in names.iter().enumerate() {
            if src_is_dir {
                if name == from {
                    copies.push((idx, to.to_string()));
                } else if name.starts_with(&format!("{from}/")) {
                    copies.push((idx, format!("{to}{}", &name[from.len()..])));
                }
            } else if name == from {
                copies.push((idx, to.to_string()));
            }
        }

        if copies.is_empty() {
            return Err(crate::Error::EntryNotFound(from.to_string()));
        }

        let mut final_map: std::collections::HashMap<String, bool> =
            std::collections::HashMap::new();
        for (idx, name) in names.iter().enumerate() {
            final_map.insert(name.to_string(), manifest.entries[idx].is_dir);
        }
        for (src_idx, copied_name) in &copies {
            if final_map
                .insert(copied_name.clone(), manifest.entries[*src_idx].is_dir)
                .is_some()
            {
                return Err(crate::Error::Manifest(format!(
                    "target entry already exists: {copied_name}"
                )));
            }
        }

        for name in final_map.keys() {
            if let Some((parent, _)) = name.rsplit_once('/') {
                if parent.is_empty() {
                    continue;
                }
                let parent_is_dir = final_map.get(parent).copied().unwrap_or(false);
                if !parent_is_dir {
                    return Err(crate::Error::EntryNotFound(format!(
                        "parent directory '{parent}'"
                    )));
                }
            }
        }

        let now = chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string();
        let mut new_entries: Vec<ManifestEntry> = Vec::with_capacity(copies.len());
        for (src_idx, copied_name) in copies {
            let mut cloned = manifest.entries[src_idx].clone();
            cloned.encrypted_name =
                crypto::encrypt_filename(self.master_key.expose_secret(), &copied_name)?;
            cloned.modified = now.clone();
            new_entries.push(cloned);
        }

        manifest.entries.extend(new_entries);
        manifest.modified = now;
        self.write_vault_atomic(&header_buf, &manifest, &data_section, &[])?;
        Ok(())
    }

    /// Compact the vault by removing orphaned data from deleted entries.
    ///
    /// Reads all surviving entries, decrypts and re-encrypts their chunks with
    /// fresh nonces, and writes a new vault file. Uses atomic temp+rename.
    ///
    /// Returns a [`CompactResult`] with size savings information.
    pub fn compact(&self) -> crate::Result<CompactResult> {
        use std::io::Seek;

        let original_size = std::fs::metadata(&self.path)?.len();

        // Read header + manifest
        let file = File::open(&self.path)?;
        let mut reader = BufReader::new(file);

        let mut header_buf = [0u8; HEADER_SIZE];
        reader.read_exact(&mut header_buf)?;

        let (manifest_len, manifest_encrypted) = crypto::read_manifest_bounded(&mut reader)?;
        let manifest_str =
            std::str::from_utf8(&manifest_encrypted).map_err(|_| CryptoError::ManifestEncoding)?;
        let manifest_json =
            crypto::decrypt_filename(self.master_key.expose_secret(), manifest_str)?;

        let mut manifest: VaultManifest = serde_json::from_str(&manifest_json)
            .map_err(|e| crate::Error::Manifest(e.to_string()))?;

        let data_start = HEADER_SIZE as u64 + 4 + manifest_len as u64;
        let cascade_mode = self.header.flags.cascade_mode;
        let file_count = manifest.entries.len();
        drop(reader);

        let chacha_key = if cascade_mode {
            crypto::derive_chacha_key(self.master_key.expose_secret())
        } else {
            zeroize::Zeroizing::new([0u8; KEY_SIZE])
        };

        // Re-open for seek-based reads
        let orig_file = File::open(&self.path)?;
        let mut orig_reader = BufReader::new(orig_file);

        let mut compacted_data: Vec<u8> = Vec::new();
        let mut new_data_offset: u64 = 0;

        for entry in &mut manifest.entries {
            if entry.is_dir || entry.chunk_count == 0 {
                entry.offset = 0;
                continue;
            }

            let entry_new_offset = new_data_offset;
            orig_reader.seek(std::io::SeekFrom::Start(data_start + entry.offset))?;

            let mut entry_bytes_consumed = 0u64;
            for chunk_idx in 0..entry.chunk_count {
                let mut len_buf = [0u8; 4];
                orig_reader.read_exact(&mut len_buf)?;
                let encrypted_chunk_len = u32::from_le_bytes(len_buf) as usize;
                let bytes_remaining = original_size
                    .saturating_sub(data_start + entry.offset + entry_bytes_consumed + 4);
                validate_encrypted_chunk_len(
                    encrypted_chunk_len,
                    bytes_remaining,
                    self.header.chunk_size,
                    cascade_mode,
                )?;
                entry_bytes_consumed += 4 + encrypted_chunk_len as u64;

                let mut encrypted_chunk = vec![0u8; encrypted_chunk_len];
                orig_reader.read_exact(&mut encrypted_chunk)?;

                let mut plaintext = if cascade_mode {
                    crypto::decrypt_chunk_cascade_bound(
                        self.master_key.expose_secret(),
                        &chacha_key,
                        &encrypted_chunk,
                        chunk_idx,
                        entry.file_id.as_ref(),
                        entry.chunk_count,
                    )?
                } else {
                    crypto::decrypt_chunk_bound(
                        self.master_key.expose_secret(),
                        &encrypted_chunk,
                        chunk_idx,
                        entry.file_id.as_ref(),
                        entry.chunk_count,
                    )?
                };

                encrypted_chunk.zeroize();

                let new_encrypted = if cascade_mode {
                    crypto::encrypt_chunk_cascade_bound(
                        self.master_key.expose_secret(),
                        &chacha_key,
                        &plaintext,
                        chunk_idx,
                        entry.file_id.as_ref(),
                        entry.chunk_count,
                    )?
                } else {
                    crypto::encrypt_chunk_bound(
                        self.master_key.expose_secret(),
                        &plaintext,
                        chunk_idx,
                        entry.file_id.as_ref(),
                        entry.chunk_count,
                    )?
                };

                plaintext.zeroize();

                let new_chunk_len = new_encrypted.len() as u32;
                compacted_data.extend_from_slice(&new_chunk_len.to_le_bytes());
                compacted_data.extend_from_slice(&new_encrypted);

                new_data_offset += 4 + new_encrypted.len() as u64;
            }

            entry.offset = entry_new_offset;
        }
        drop(orig_reader);

        manifest.modified = chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string();

        // Write compacted vault
        let manifest_json =
            serde_json::to_string(&manifest).map_err(|e| crate::Error::Manifest(e.to_string()))?;
        let encrypted_manifest =
            crypto::encrypt_filename(self.master_key.expose_secret(), &manifest_json)?;
        let manifest_bytes = encrypted_manifest.as_bytes();

        let tmp_path = format!("{}.compact.tmp", self.path.display());
        let tmp_file = File::create(&tmp_path)?;
        let mut writer = BufWriter::new(tmp_file);

        writer.write_all(&header_buf)?;
        writer.write_all(&(manifest_bytes.len() as u32).to_le_bytes())?;
        writer.write_all(manifest_bytes)?;
        writer.write_all(&compacted_data)?;
        writer.flush()?;
        writer.get_ref().sync_all()?;
        drop(writer);

        atomic_rename(&tmp_path, &self.path)?;

        let compacted_size = std::fs::metadata(&self.path)?.len();

        Ok(CompactResult {
            original_size,
            compacted_size,
            saved_bytes: original_size.saturating_sub(compacted_size),
            file_count,
        })
    }

    /// Change the vault password.
    ///
    /// Re-wraps the master and MAC keys with a new KEK. The encrypted content
    /// remains unchanged — only the 512-byte header is modified.
    pub fn change_password(&mut self, new_password: impl Into<String>) -> crate::Result<()> {
        let new_pwd = SecretString::from(new_password.into());
        if new_pwd.expose_secret().len() < MIN_PASSWORD_LENGTH {
            return Err(crate::Error::PasswordPolicy(format!(
                "password must be at least {MIN_PASSWORD_LENGTH} characters"
            )));
        }

        let mut vault_data = std::fs::read(&self.path)?;

        if vault_data.len() < HEADER_SIZE {
            return Err(FormatError::TooSmall {
                actual: vault_data.len(),
                expected: HEADER_SIZE,
            }
            .into());
        }

        // Generate new salt
        let mut new_salt = [0u8; SALT_SIZE];
        rand::rngs::OsRng.fill_bytes(&mut new_salt);

        // Derive new KEKs
        let new_base_kek = crypto::derive_key(&new_pwd, &new_salt)?;
        let (new_kek_master, new_kek_mac) = crypto::derive_kek_pair(new_base_kek.expose_secret());

        // Re-wrap keys
        let new_wrapped_master =
            crypto::wrap_key(&new_kek_master, self.master_key.expose_secret())?;
        let new_wrapped_mac = crypto::wrap_key(&new_kek_mac, self.mac_key.expose_secret())?;

        // new_kek_master and new_kek_mac are Zeroizing — auto-dropped

        // Build new header
        let mut new_header = VaultHeader {
            magic: *MAGIC,
            version: VERSION,
            flags: self.header.flags,
            salt: new_salt,
            wrapped_master_key: new_wrapped_master,
            wrapped_mac_key: new_wrapped_mac,
            chunk_size: self.header.chunk_size,
            reserved: [0u8; 320],
            header_mac: [0u8; MAC_SIZE],
        };
        new_header.header_mac = new_header.compute_mac(self.mac_key.expose_secret());

        // Write new header into vault data
        let header_bytes = new_header.to_bytes();
        vault_data[..HEADER_SIZE].copy_from_slice(&header_bytes);

        // Atomic write with fsync
        atomic_write(&self.path, &vault_data, "chpw")?;

        self.header = new_header;
        vault_data.zeroize();

        Ok(())
    }

    // --- Internal Helpers ---

    /// Read and decrypt the vault manifest.
    fn read_manifest(&self) -> crate::Result<VaultManifest> {
        let file = File::open(&self.path)?;
        let mut reader = BufReader::new(file);

        let mut header_buf = [0u8; HEADER_SIZE];
        reader.read_exact(&mut header_buf)?;

        let (_manifest_len, manifest_encrypted) = crypto::read_manifest_bounded(&mut reader)?;
        let manifest_str =
            std::str::from_utf8(&manifest_encrypted).map_err(|_| CryptoError::ManifestEncoding)?;
        let manifest_json =
            crypto::decrypt_filename(self.master_key.expose_secret(), manifest_str)?;

        serde_json::from_str(&manifest_json).map_err(|e| crate::Error::Manifest(e.to_string()))
    }

    /// Write vault atomically: header + manifest + data_old + data_new.
    fn write_vault_atomic(
        &self,
        header_buf: &[u8; HEADER_SIZE],
        manifest: &VaultManifest,
        existing_data: &[u8],
        new_data: &[u8],
    ) -> crate::Result<()> {
        let manifest_json =
            serde_json::to_string(manifest).map_err(|e| crate::Error::Manifest(e.to_string()))?;
        let encrypted_manifest =
            crypto::encrypt_filename(self.master_key.expose_secret(), &manifest_json)?;
        let manifest_bytes = encrypted_manifest.as_bytes();

        let tmp_path = format!("{}.tmp", self.path.display());
        let file = File::create(&tmp_path)?;
        let mut writer = BufWriter::new(file);

        writer.write_all(header_buf)?;
        writer.write_all(&(manifest_bytes.len() as u32).to_le_bytes())?;
        writer.write_all(manifest_bytes)?;
        writer.write_all(existing_data)?;
        writer.write_all(new_data)?;
        writer.flush()?;
        writer.get_ref().sync_all()?;
        drop(writer);

        atomic_rename(&tmp_path, &self.path)?;
        Ok(())
    }
}

/// Header information available without a password.
#[derive(Debug, Clone)]
pub struct PeekInfo {
    /// Format version.
    pub version: u8,
    /// Encryption mode.
    pub mode: EncryptionMode,
    /// Chunk size in bytes.
    pub chunk_size: u32,
}

/// Result of a compact operation.
#[derive(Debug, Clone)]
pub struct CompactResult {
    /// Original vault file size in bytes.
    pub original_size: u64,
    /// Compacted vault file size in bytes.
    pub compacted_size: u64,
    /// Bytes saved.
    pub saved_bytes: u64,
    /// Number of entries in the vault.
    pub file_count: usize,
}

/// Security information about a vault.
#[derive(Debug, Clone)]
pub struct SecurityInfo {
    /// Format version.
    pub version: u8,
    /// Encryption mode.
    pub mode: EncryptionMode,
    /// Chunk size in bytes.
    pub chunk_size: u32,
    /// Argon2id memory cost in KiB.
    pub argon2_m_cost_kib: u32,
    /// Argon2id time cost.
    pub argon2_t_cost: u32,
    /// Argon2id parallelism.
    pub argon2_p_cost: u32,
}

impl std::fmt::Display for SecurityInfo {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mode_str = match self.mode {
            EncryptionMode::Standard => "AES-256-GCM-SIV",
            EncryptionMode::Cascade => "AES-256-GCM-SIV + ChaCha20-Poly1305",
        };
        write!(
            f,
            "Version: {}\n\
             Encryption: {}\n\
             Chunk size: {} bytes\n\
             KDF: Argon2id ({} MiB, t={}, p={})\n\
             Key wrapping: AES-256-KW (RFC 3394)\n\
             Filename encryption: AES-256-SIV\n\
             Header integrity: HMAC-SHA512",
            self.version,
            mode_str,
            self.chunk_size,
            self.argon2_m_cost_kib / 1024,
            self.argon2_t_cost,
            self.argon2_p_cost,
        )
    }
}

/// Validate that an entry name is safe (no path traversal, no absolute paths).
fn validate_entry_name(name: &str) -> crate::Result<()> {
    if name.contains("..") {
        return Err(crate::Error::InvalidPath(
            "entry name contains '..' (path traversal)".into(),
        ));
    }
    if name.starts_with('/') || name.starts_with('\\') {
        return Err(crate::Error::InvalidPath(
            "entry name is an absolute path".into(),
        ));
    }
    if name.contains('\0') {
        return Err(crate::Error::InvalidPath(
            "entry name contains null byte".into(),
        ));
    }
    Ok(())
}

/// Validate that a resolved output path stays within the output directory.
fn validate_output_path(path: &Path, output_dir: &Path) -> crate::Result<()> {
    // Canonicalize the output directory (it must exist)
    let canonical_dir = output_dir
        .canonicalize()
        .unwrap_or_else(|_| output_dir.to_path_buf());

    // For the file path, canonicalize the parent (which should exist after create_dir_all)
    // and append the filename
    let canonical_path = if let Some(parent) = path.parent() {
        let canon_parent = parent
            .canonicalize()
            .unwrap_or_else(|_| parent.to_path_buf());
        if let Some(filename) = path.file_name() {
            canon_parent.join(filename)
        } else {
            canon_parent
        }
    } else {
        path.to_path_buf()
    };

    if !canonical_path.starts_with(&canonical_dir) {
        return Err(crate::Error::InvalidPath(format!(
            "output path escapes target directory: {}",
            path.display()
        )));
    }
    Ok(())
}

fn validate_encrypted_chunk_len(
    chunk_len: usize,
    bytes_remaining: u64,
    header_chunk_size: u32,
    cascade_mode: bool,
) -> crate::Result<()> {
    let aead_overhead = NONCE_SIZE + TAG_SIZE;
    let max_len =
        header_chunk_size as usize + aead_overhead + if cascade_mode { aead_overhead } else { 0 };

    if chunk_len > max_len {
        return Err(Error::Format(FormatError::InvalidChunkSize(
            chunk_len as u32,
        )));
    }
    if chunk_len as u64 > bytes_remaining {
        return Err(Error::Format(FormatError::ManifestTruncated));
    }
    Ok(())
}

fn open_new_output_file(path: &Path, output_dir: &Path) -> crate::Result<File> {
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent)?;
    }
    validate_output_path(path, output_dir)?;

    let canonical_dir = output_dir.canonicalize()?;
    let canonical_parent = path
        .parent()
        .ok_or_else(|| Error::InvalidPath(format!("missing parent for {}", path.display())))?
        .canonicalize()?;
    if !canonical_parent.starts_with(&canonical_dir) {
        return Err(Error::InvalidPath(format!(
            "output path escapes target directory: {}",
            path.display()
        )));
    }

    let mut options = OpenOptions::new();
    options.write(true).create_new(true);

    #[cfg(unix)]
    {
        use std::os::unix::fs::{MetadataExt, OpenOptionsExt};
        options.custom_flags(libc::O_NOFOLLOW);
        let file = options.open(path)?;
        let fd_meta = file.metadata()?;
        let path_meta = std::fs::symlink_metadata(path)?;
        if !path_meta.file_type().is_file()
            || fd_meta.dev() != path_meta.dev()
            || fd_meta.ino() != path_meta.ino()
        {
            return Err(Error::InvalidPath(format!(
                "output path is not the newly-created regular file: {}",
                path.display()
            )));
        }
        let canonical_path = path.canonicalize()?;
        if !canonical_path.starts_with(&canonical_dir) {
            return Err(Error::InvalidPath(format!(
                "output path escapes target directory: {}",
                path.display()
            )));
        }
        Ok(file)
    }

    #[cfg(not(unix))]
    {
        let file = options.open(path)?;
        let canonical_path = path.canonicalize()?;
        if !canonical_path.starts_with(&canonical_dir) {
            return Err(Error::InvalidPath(format!(
                "output path escapes target directory: {}",
                path.display()
            )));
        }
        Ok(file)
    }
}

#[cfg(unix)]
fn fsync_parent_dir(path: &Path) -> crate::Result<()> {
    if let Some(parent) = path.parent() {
        let parent = if parent.as_os_str().is_empty() {
            Path::new(".")
        } else {
            parent
        };
        let dir = File::open(parent)?;
        dir.sync_all()?;
    }
    Ok(())
}

#[cfg(not(unix))]
fn fsync_parent_dir(_path: &Path) -> crate::Result<()> {
    Ok(())
}

/// Atomic rename: tmp -> final as the single visible commit point.
fn atomic_rename(tmp_path: &str, final_path: &Path) -> crate::Result<()> {
    #[cfg(windows)]
    if final_path.exists() {
        std::fs::remove_file(final_path)?;
    }

    std::fs::rename(tmp_path, final_path)?;
    fsync_parent_dir(final_path)?;
    Ok(())
}

/// Atomic write: write to temp file with fsync, then rename.
fn atomic_write(path: &Path, data: &[u8], suffix: &str) -> crate::Result<()> {
    let tmp_path = format!("{}.{suffix}.tmp", path.display());
    let file = File::create(&tmp_path)?;
    let mut writer = BufWriter::new(file);
    writer.write_all(data)?;
    writer.flush()?;
    writer.get_ref().sync_all()?;
    drop(writer);

    #[cfg(windows)]
    if path.exists() {
        std::fs::remove_file(path)?;
    }

    std::fs::rename(&tmp_path, path)?;
    fsync_parent_dir(path)?;
    Ok(())
}

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

    fn temp_vault_path() -> PathBuf {
        let mut path = std::env::temp_dir();
        path.push(format!(
            "aerovault-test-{}.aerovault",
            rand::random::<u64>()
        ));
        path
    }

    #[test]
    fn test_create_and_open() {
        let path = temp_vault_path();
        let opts = CreateOptions::new(&path, "test-password-123");
        let _vault = Vault::create(opts).unwrap();

        assert!(Vault::is_vault(&path));

        let vault = Vault::open(&path, "test-password-123").unwrap();
        let entries = vault.list().unwrap();
        assert!(entries.is_empty());

        std::fs::remove_file(&path).ok();
    }

    #[test]
    fn test_wrong_password() {
        let path = temp_vault_path();
        let opts = CreateOptions::new(&path, "correct-password");
        let _vault = Vault::create(opts).unwrap();

        let result = Vault::open(&path, "wrong-password");
        assert!(result.is_err());

        std::fs::remove_file(&path).ok();
    }

    #[test]
    fn test_password_too_short() {
        let path = temp_vault_path();
        let opts = CreateOptions::new(&path, "short");
        let result = Vault::create(opts);
        assert!(result.is_err());
        std::fs::remove_file(&path).ok();
    }

    #[test]
    fn test_chunk_size_validation() {
        let path = temp_vault_path();
        let opts = CreateOptions::new(&path, "test-password-123").with_chunk_size(1); // too small
        assert!(Vault::create(opts).is_err());

        let opts = CreateOptions::new(&path, "test-password-123").with_chunk_size(32 * 1024 * 1024); // too large
        assert!(Vault::create(opts).is_err());

        std::fs::remove_file(&path).ok();
    }

    #[test]
    fn test_add_and_extract() {
        let path = temp_vault_path();
        let opts = CreateOptions::new(&path, "test-password-123");
        let vault = Vault::create(opts).unwrap();

        // Create a test file
        let test_file = std::env::temp_dir().join("aerovault-test-input.txt");
        let mut f = File::create(&test_file).unwrap();
        f.write_all(b"Hello from AeroVault!").unwrap();

        // Add file
        let added = vault.add_files(&[&test_file]).unwrap();
        assert_eq!(added, 1);

        // List
        let entries = vault.list().unwrap();
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].name, "aerovault-test-input.txt");
        assert_eq!(entries[0].size, 21);
        assert!(!entries[0].is_dir);

        // Extract
        let out_dir = std::env::temp_dir().join("aerovault-test-output");
        std::fs::create_dir_all(&out_dir).ok();
        let extracted = vault.extract("aerovault-test-input.txt", &out_dir).unwrap();
        let content = std::fs::read_to_string(&extracted).unwrap();
        assert_eq!(content, "Hello from AeroVault!");

        // Cleanup
        std::fs::remove_file(&path).ok();
        std::fs::remove_file(&test_file).ok();
        std::fs::remove_dir_all(&out_dir).ok();
    }

    #[test]
    fn test_legacy_v2_roundtrip_and_version_dispatch() {
        // A v2 (LEGACY_VERSION) container must round-trip byte-identically with
        // the chunk-index-only AAD, and a default v3 container must round-trip
        // with the file-id-bound AAD. Both must reopen and extract correctly.
        // Locks the backward-compat read path against future refactors.
        let v2_path = temp_vault_path();
        let v3_path = temp_vault_path();

        // Multi-chunk payload (> one default chunk) to exercise chunk indexing.
        let input = std::env::temp_dir().join(format!(
            "aerovault-legacy-input-{}.bin",
            v2_path.file_stem().unwrap().to_string_lossy()
        ));
        let payload: Vec<u8> = (0..200_000u32).map(|i| (i % 251) as u8).collect();
        std::fs::write(&input, &payload).unwrap();
        let entry = input.file_name().unwrap().to_string_lossy().to_string();

        // --- v2 legacy container ---
        let v2 = Vault::create(
            CreateOptions::new(&v2_path, "legacy-password-123").with_version(LEGACY_VERSION),
        )
        .unwrap();
        v2.add_files(&[&input]).unwrap();
        assert_eq!(Vault::peek(&v2_path).unwrap().version, LEGACY_VERSION);

        let v2r = Vault::open(&v2_path, "legacy-password-123").unwrap();
        let out2 = std::env::temp_dir().join(format!("av-legacy-out-{}", std::process::id()));
        std::fs::create_dir_all(&out2).ok();
        let ex2 = v2r.extract(&entry, &out2).unwrap();
        assert_eq!(
            std::fs::read(&ex2).unwrap(),
            payload,
            "v2 legacy round-trip"
        );

        // --- v3 default container ---
        let v3 = Vault::create(CreateOptions::new(&v3_path, "modern-password-123")).unwrap();
        v3.add_files(&[&input]).unwrap();
        assert_eq!(Vault::peek(&v3_path).unwrap().version, VERSION);

        let v3r = Vault::open(&v3_path, "modern-password-123").unwrap();
        let out3 = std::env::temp_dir().join(format!("av-v3-out-{}", std::process::id()));
        std::fs::create_dir_all(&out3).ok();
        let ex3 = v3r.extract(&entry, &out3).unwrap();
        assert_eq!(std::fs::read(&ex3).unwrap(), payload, "v3 round-trip");

        // An unsupported version is rejected at create time.
        assert!(Vault::create(
            CreateOptions::new(temp_vault_path(), "x-password-123").with_version(9)
        )
        .is_err());

        std::fs::remove_file(&v2_path).ok();
        std::fs::remove_file(&v3_path).ok();
        std::fs::remove_file(&input).ok();
        std::fs::remove_dir_all(&out2).ok();
        std::fs::remove_dir_all(&out3).ok();
    }

    #[test]
    fn test_cascade_mode() {
        let path = temp_vault_path();
        let opts =
            CreateOptions::new(&path, "test-password-123").with_mode(EncryptionMode::Cascade);
        let vault = Vault::create(opts).unwrap();

        assert_eq!(vault.mode(), EncryptionMode::Cascade);

        let test_file = std::env::temp_dir().join("aerovault-cascade-input.txt");
        let mut f = File::create(&test_file).unwrap();
        f.write_all(b"Cascade mode test").unwrap();

        vault.add_files(&[&test_file]).unwrap();

        // Re-open and extract
        let vault2 = Vault::open(&path, "test-password-123").unwrap();
        let out_dir = std::env::temp_dir().join("aerovault-cascade-output");
        std::fs::create_dir_all(&out_dir).ok();
        let extracted = vault2
            .extract("aerovault-cascade-input.txt", &out_dir)
            .unwrap();
        let content = std::fs::read_to_string(&extracted).unwrap();
        assert_eq!(content, "Cascade mode test");

        std::fs::remove_file(&path).ok();
        std::fs::remove_file(&test_file).ok();
        std::fs::remove_dir_all(&out_dir).ok();
    }

    #[test]
    fn test_create_directory() {
        let path = temp_vault_path();
        let opts = CreateOptions::new(&path, "test-password-123");
        let vault = Vault::create(opts).unwrap();

        // Create nested directory
        let created = vault.create_directory("docs/notes").unwrap();
        assert_eq!(created, 2); // "docs" + "docs/notes"

        // Creating again should return 0
        let created = vault.create_directory("docs/notes").unwrap();
        assert_eq!(created, 0);

        let entries = vault.list().unwrap();
        assert_eq!(entries.len(), 2);
        assert!(entries.iter().all(|e| e.is_dir));

        std::fs::remove_file(&path).ok();
    }

    #[test]
    fn test_delete_entry() {
        let path = temp_vault_path();
        let opts = CreateOptions::new(&path, "test-password-123");
        let vault = Vault::create(opts).unwrap();

        let test_file = std::env::temp_dir().join("aerovault-delete-input.txt");
        let mut f = File::create(&test_file).unwrap();
        f.write_all(b"to be deleted").unwrap();

        vault.add_files(&[&test_file]).unwrap();
        assert_eq!(vault.list().unwrap().len(), 1);

        vault.delete_entry("aerovault-delete-input.txt").unwrap();
        assert_eq!(vault.list().unwrap().len(), 0);

        // Deleting again should fail
        assert!(vault.delete_entry("aerovault-delete-input.txt").is_err());

        std::fs::remove_file(&path).ok();
        std::fs::remove_file(&test_file).ok();
    }

    #[test]
    fn test_change_password() {
        let path = temp_vault_path();
        let opts = CreateOptions::new(&path, "old-password-123");
        let mut vault = Vault::create(opts).unwrap();

        let test_file = std::env::temp_dir().join("aerovault-chpw-input.txt");
        let mut f = File::create(&test_file).unwrap();
        f.write_all(b"password change test").unwrap();
        vault.add_files(&[&test_file]).unwrap();

        vault.change_password("new-password-456").unwrap();

        // Old password should fail
        assert!(Vault::open(&path, "old-password-123").is_err());

        // New password should work and data should be intact
        let vault2 = Vault::open(&path, "new-password-456").unwrap();
        let entries = vault2.list().unwrap();
        assert_eq!(entries.len(), 1);

        std::fs::remove_file(&path).ok();
        std::fs::remove_file(&test_file).ok();
    }

    #[test]
    fn test_is_vault_negative() {
        let path = std::env::temp_dir().join("not-a-vault.txt");
        std::fs::write(&path, b"just text").ok();
        assert!(!Vault::is_vault(&path));
        std::fs::remove_file(&path).ok();

        assert!(!Vault::is_vault("/nonexistent/path"));
    }

    #[test]
    fn test_security_info_display() {
        let path = temp_vault_path();
        let opts = CreateOptions::new(&path, "test-password-123");
        let vault = Vault::create(opts).unwrap();
        let info = vault.security_info();
        let display = format!("{info}");
        assert!(display.contains("AES-256-GCM-SIV"));
        assert!(display.contains("128 MiB"));
        std::fs::remove_file(&path).ok();
    }

    #[test]
    fn test_path_traversal_rejected() {
        assert!(validate_entry_name("../etc/passwd").is_err());
        assert!(validate_entry_name("/etc/passwd").is_err());
        assert!(validate_entry_name("foo\0bar").is_err());
        assert!(validate_entry_name("normal/file.txt").is_ok());
    }

    #[test]
    fn test_rename_entry() {
        let path = temp_vault_path();
        let opts = CreateOptions::new(&path, "test-password-123");
        let vault = Vault::create(opts).unwrap();

        let test_file = std::env::temp_dir().join("aerovault-rename-input.txt");
        std::fs::write(&test_file, b"rename me").unwrap();
        vault.add_files(&[&test_file]).unwrap();

        vault
            .rename_entry("aerovault-rename-input.txt", "renamed.txt")
            .unwrap();

        let entries = vault.list().unwrap();
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].name, "renamed.txt");

        let out_dir = std::env::temp_dir().join("aerovault-rename-output");
        std::fs::create_dir_all(&out_dir).ok();
        let extracted = vault.extract("renamed.txt", &out_dir).unwrap();
        assert!(extracted.ends_with("renamed.txt"));

        std::fs::remove_file(&path).ok();
        std::fs::remove_file(&test_file).ok();
        std::fs::remove_dir_all(&out_dir).ok();
    }

    #[test]
    fn test_move_directory_recursive() {
        let path = temp_vault_path();
        let opts = CreateOptions::new(&path, "test-password-123");
        let vault = Vault::create(opts).unwrap();

        vault.create_directory("docs/old").unwrap();

        let temp_dir = std::env::temp_dir();
        let test_file = temp_dir.join("aerovault-move-input.txt");
        std::fs::write(&test_file, b"move me").unwrap();
        vault.add_files_to_dir(&[&test_file], "docs/old").unwrap();

        vault.create_directory("archive").unwrap();
        vault.move_entry("docs/old", "archive/old").unwrap();

        let names: Vec<String> = vault.list().unwrap().into_iter().map(|e| e.name).collect();
        assert!(names.iter().any(|n| n == "archive/old"));
        assert!(names
            .iter()
            .any(|n| n == "archive/old/aerovault-move-input.txt"));
        assert!(!names.iter().any(|n| n == "docs/old"));

        let out_dir = temp_dir.join("aerovault-move-output");
        std::fs::create_dir_all(&out_dir).ok();
        let extracted = vault
            .extract("archive/old/aerovault-move-input.txt", &out_dir)
            .unwrap();
        let content = std::fs::read_to_string(extracted).unwrap();
        assert_eq!(content, "move me");

        std::fs::remove_file(&path).ok();
        std::fs::remove_file(&test_file).ok();
        std::fs::remove_dir_all(&out_dir).ok();
    }

    #[test]
    fn test_move_entry_rejects_self_subtree() {
        let path = temp_vault_path();
        let opts = CreateOptions::new(&path, "test-password-123");
        let vault = Vault::create(opts).unwrap();

        vault.create_directory("docs/old").unwrap();
        assert!(vault.move_entry("docs", "docs/archive").is_err());

        std::fs::remove_file(&path).ok();
    }

    #[test]
    fn test_copy_entry_file() {
        let path = temp_vault_path();
        let opts = CreateOptions::new(&path, "test-password-123");
        let vault = Vault::create(opts).unwrap();

        let test_file = std::env::temp_dir().join("aerovault-copy-input.txt");
        std::fs::write(&test_file, b"copy me").unwrap();
        vault.add_files(&[&test_file]).unwrap();

        vault
            .copy_entry("aerovault-copy-input.txt", "aerovault-copy-output.txt")
            .unwrap();

        let names: Vec<String> = vault.list().unwrap().into_iter().map(|e| e.name).collect();
        assert!(names.iter().any(|n| n == "aerovault-copy-input.txt"));
        assert!(names.iter().any(|n| n == "aerovault-copy-output.txt"));

        let out_dir = std::env::temp_dir().join("aerovault-copy-output-dir");
        std::fs::create_dir_all(&out_dir).ok();
        let extracted = vault
            .extract("aerovault-copy-output.txt", &out_dir)
            .unwrap();
        let content = std::fs::read_to_string(extracted).unwrap();
        assert_eq!(content, "copy me");

        std::fs::remove_file(&path).ok();
        std::fs::remove_file(&test_file).ok();
        std::fs::remove_dir_all(&out_dir).ok();
    }

    #[test]
    fn test_copy_entry_directory_recursive() {
        let path = temp_vault_path();
        let opts = CreateOptions::new(&path, "test-password-123");
        let vault = Vault::create(opts).unwrap();

        vault.create_directory("docs/original").unwrap();

        let test_file = std::env::temp_dir().join("aerovault-copy-tree-input.txt");
        std::fs::write(&test_file, b"tree copy").unwrap();
        vault
            .add_files_to_dir(&[&test_file], "docs/original")
            .unwrap();

        vault.create_directory("archive").unwrap();
        vault
            .copy_entry("docs/original", "archive/original-copy")
            .unwrap();

        let names: Vec<String> = vault.list().unwrap().into_iter().map(|e| e.name).collect();
        assert!(names.iter().any(|n| n == "docs/original"));
        assert!(names.iter().any(|n| n == "archive/original-copy"));
        assert!(names
            .iter()
            .any(|n| n == "archive/original-copy/aerovault-copy-tree-input.txt"));

        std::fs::remove_file(&path).ok();
        std::fs::remove_file(&test_file).ok();
    }

    #[test]
    fn test_copy_entry_rejects_self_subtree() {
        let path = temp_vault_path();
        let opts = CreateOptions::new(&path, "test-password-123");
        let vault = Vault::create(opts).unwrap();

        vault.create_directory("docs/original").unwrap();
        assert!(vault.copy_entry("docs", "docs/archive").is_err());

        std::fs::remove_file(&path).ok();
    }
}