keep-core 0.7.5

Core library for Keep - sovereign key management for Nostr and Bitcoin
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
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
// SPDX-FileCopyrightText: (C) 2026 PrivKey LLC
// SPDX-License-Identifier: MIT

#![deny(unsafe_code)]

//! Sovereign key management for Nostr and Bitcoin.
//!
//! This crate provides encrypted key storage with the following features:
//!
//! - **Encrypted storage** using Redb with XChaCha20-Poly1305
//! - **Key derivation** using Argon2id with configurable parameters
//! - **Nostr keypair management** with nsec/npub support
//! - **FROST threshold signatures** for distributed key management
//! - **Hidden volumes** for plausible deniability
//!
//! # Example
//!
//! ```no_run
//! use std::path::Path;
//! use keep_core::Keep;
//!
//! // Create a new Keep
//! let mut keep = Keep::create(Path::new("/tmp/my-keep"), "password")?;
//!
//! // Generate a new key
//! let pubkey = keep.generate_key("my-key")?;
//!
//! // Lock when done
//! keep.lock();
//! # Ok::<(), keep_core::error::KeepError>(())
//! ```

#![deny(missing_docs)]

/// Tamper-evident audit logging with hash chain integrity.
pub mod audit;
/// Pluggable storage backends.
pub mod backend;
/// Portable encrypted vault backup and restore.
pub mod backup;
/// Cryptographic primitives for encryption, key derivation, and hashing.
pub mod crypto;
/// Shared text-level helpers for output descriptor strings.
pub mod descriptor;
/// Display formatting helpers for truncation and timestamps.
pub mod display;
/// Multi-source entropy mixing for defense-in-depth randomness.
pub mod entropy;
/// Error types and result aliases.
pub mod error;
/// FROST threshold signature implementation.
pub mod frost;
/// BIP-32 unhardened child-key primitives for FROST group keys (#487).
pub mod frost_bip32;
/// Hidden volume storage for plausible deniability.
pub mod hidden;
/// In-memory keyring for unlocked keys.
pub mod keyring;
/// Key types and Nostr keypair operations.
pub mod keys;
pub mod migration;

/// BIP-39 mnemonic generation and validation.
pub mod mnemonic;
/// NIP-06 key derivation from mnemonic seed phrase.
pub mod nip06;
/// Threshold-OPRF unlock primitive (frost-gate v2). Opt-in via the `oprf` feature.
#[cfg(feature = "oprf")]
pub mod oprf;
pub(crate) mod rate_limit;
/// Relay configuration for FROST shares.
pub mod relay;
mod rotation;
/// Arbitrary-secret records (passwords, API tokens, notes) stored in the vault.
pub mod secret;
/// Persistent encrypted storage backend.
pub mod storage;
/// Ephemeral time-limited secret vault.
pub mod vault;
/// Wallet descriptor types for FROST group spending policies.
pub mod wallet;

use std::path::{Path, PathBuf};

use tracing::debug;
use zeroize::Zeroizing;

use crate::audit::{
    AuditEntry, AuditEventType, AuditLog, RetentionPolicy, SigningAuditEntry, SigningAuditLog,
};
use crate::crypto::{Argon2Params, SecretKey};
use crate::error::{KeepError, Result};
use crate::frost::{ShareExport, SharePackage, StoredShare, ThresholdConfig, TrustedDealer};
use crate::keyring::Keyring;
use crate::keys::{KeyRecord, KeyType, NostrKeypair};
pub use crate::relay::{PeerPolicyEntry, RelayConfig, GLOBAL_RELAY_KEY};
pub use crate::storage::ProxyConfig;
use crate::storage::Storage;
pub use crate::storage::{ReplicatedApply, StatePublisher};
pub use crate::wallet::{DeviceRegistration, WalletDescriptor};

/// The main Keep type for encrypted key management.
pub struct Keep {
    storage: Storage,
    keyring: Keyring,
    audit: Option<AuditLog>,
    signing_audit: Option<SigningAuditLog>,
}

impl Keep {
    /// Install the keep-state replication sink on the underlying storage (keep-web wires this to a
    /// publisher that ships each vault-state change to the state relay). See [`StatePublisher`].
    pub fn set_state_publisher(&self, publisher: std::sync::Arc<dyn StatePublisher>) {
        self.storage.set_state_publisher(publisher);
    }

    /// Apply a record replicated from a peer into storage (the standby consumer side). Delegates to
    /// [`Storage::apply_replicated_record`]; never echoes back to the relay.
    pub fn apply_replicated_record(
        &self,
        table: &str,
        record_id: &str,
        encrypted: &[u8],
        created_at: u64,
        now: u64,
    ) -> Result<ReplicatedApply> {
        self.storage
            .apply_replicated_record(table, record_id, encrypted, created_at, now)
    }

    /// Apply a replicated delete (tombstone) from a peer. `now` is local wall-clock, used to reject an
    /// implausibly future-dated event (see [`Storage::apply_replicated_delete`]).
    pub fn apply_replicated_delete(
        &self,
        table: &str,
        record_id: &str,
        created_at: u64,
        now: u64,
    ) -> Result<ReplicatedApply> {
        self.storage
            .apply_replicated_delete(table, record_id, created_at, now)
    }

    /// The persisted rollback high-water-mark for one replicated record's d-tag (`None` if never
    /// applied), for seeding the publisher's per-d-tag floor. See [`Storage::state_version`].
    pub fn state_version(&self, table: &str, record_id: &str) -> Result<Option<u64>> {
        self.storage.state_version(table, record_id)
    }

    /// Snapshot all replicable records for the keep-state publisher to replay at startup, so records
    /// written before the replication hook was installed still reach a fresh standby. See
    /// [`Storage::snapshot_replicable_records`].
    pub fn snapshot_replicable_records(&self) -> Result<Vec<(&'static str, String, Vec<u8>)>> {
        self.storage.snapshot_replicable_records()
    }

    /// Create a new Keep with the given password.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use std::path::Path;
    /// use keep_core::Keep;
    ///
    /// let keep = Keep::create(Path::new("/tmp/my-keep"), "password")?;
    /// assert!(keep.is_unlocked());
    /// # Ok::<(), keep_core::error::KeepError>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`KeepError::AlreadyExists`] if a Keep already exists at the path.
    pub fn create(path: &Path, password: &str) -> Result<Self> {
        Self::create_with_params(path, password, Argon2Params::DEFAULT)
    }

    /// Create a new Keep with custom Argon2 parameters.
    pub fn create_with_params(path: &Path, password: &str, params: Argon2Params) -> Result<Self> {
        let storage = Storage::create(path, password, params)?;
        Ok(Self {
            storage,
            keyring: Keyring::new(),
            audit: None,
            signing_audit: None,
        })
    }

    /// Like [`Self::create_with_params`] but seeds a shared record-encryption key, so every node in a
    /// cluster shares one vault key (keep-state replication) and a standby decrypts what the active
    /// shipped. Each node still wraps the key under its own password+salt.
    pub fn create_with_shared_data_key(
        path: &Path,
        password: &str,
        params: Argon2Params,
        data_key: Zeroizing<[u8; crypto::KEY_SIZE]>,
    ) -> Result<Self> {
        let storage = Storage::create_with_shared_data_key(path, password, params, data_key)?;
        Ok(Self {
            storage,
            keyring: Keyring::new(),
            audit: None,
            signing_audit: None,
        })
    }

    /// Open an existing Keep.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use std::path::Path;
    /// use keep_core::Keep;
    ///
    /// let mut keep = Keep::open(Path::new("~/.keep"))?;
    /// keep.unlock("password")?;
    /// # Ok::<(), keep_core::error::KeepError>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`KeepError::NotFound`] if no Keep exists at the path.
    pub fn open(path: &Path) -> Result<Self> {
        let storage = Storage::open(path)?;
        Ok(Self {
            storage,
            keyring: Keyring::new(),
            audit: None,
            signing_audit: None,
        })
    }

    /// Unlock with the given password.
    ///
    /// # Errors
    ///
    /// Returns [`KeepError::InvalidPassword`] if the password is incorrect.
    /// Returns [`KeepError::RateLimited`] after too many failed attempts.
    pub fn unlock(&mut self, password: &str) -> Result<()> {
        self.storage.unlock(password)?;

        let data_key = self.get_data_key()?;
        self.audit = Some(AuditLog::open(self.storage.path(), &data_key)?);
        self.signing_audit = Some(SigningAuditLog::open(self.storage.path(), &data_key)?);

        // Flush any rate-limit trip events queued by prior failed unlocks
        // before recording this success, so the audit chain reflects the
        // chronological order: lock-out events first, then the successful
        // unlock that observed and cleared them. The drain consumes the trip
        // file before the audit writes, so emission is best-effort: a failed
        // audit write loses that event at-most-once with no retry.
        let trips = self.storage.drain_pending_trips();
        for trip in trips {
            let trip_ts = i64::try_from(trip.timestamp).unwrap_or(i64::MAX);
            let reason = format!(
                "rate limit threshold reached after {} failed attempts",
                trip.failed_attempts
            );
            self.audit_event(AuditEventType::RateLimitTripped, |mut e| {
                e.timestamp = trip_ts;
                e.with_success(false).with_reason(&reason)
            });
        }

        self.audit_event(AuditEventType::VaultUnlock, |e| e);
        debug!("loading keys to keyring");
        self.load_keys_to_keyring()
    }

    /// Verify a password without changing the unlock state.
    pub fn verify_password(&self, password: &str) -> Result<()> {
        self.storage.verify_password(password)
    }

    /// Read-only pre-flight check of whether `password` is this vault's password,
    /// WITHOUT touching the rate limiter, audit log, keyring, or unlock state.
    /// `Ok(true)` = matches, `Ok(false)` = wrong password, `Err` = could not check.
    /// Unlike [`Self::verify_password`] it does not record a rate-limit attempt and
    /// is not blocked by an active backoff, so a pre-flight check cannot self-inflict
    /// a lockout nor be silently skipped. Because it does not rate-limit, use it only
    /// on local, operator-driven paths (e.g. the duress-provision anti-brick guard),
    /// never as a remote or automated unlock oracle.
    pub fn password_matches(&self, password: &str) -> Result<bool> {
        self.storage.password_matches(password)
    }

    /// Lock and clear all keys from memory.
    pub fn lock(&mut self) {
        self.audit_event(AuditEventType::VaultLock, |e| e);
        self.keyring.clear();
        self.audit = None;
        self.signing_audit = None;
        self.storage.lock();
    }

    /// Returns true if unlocked.
    pub fn is_unlocked(&self) -> bool {
        self.storage.is_unlocked()
    }

    /// The vault's Argon2id parameters (from the header, readable before unlock).
    /// Non-secret; used to reproduce an unlock's KDF cost without unlocking.
    pub fn argon2_params(&self) -> crate::crypto::Argon2Params {
        self.storage.argon2_params()
    }

    /// Generate a new Nostr keypair and store it.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use std::path::Path;
    /// # use keep_core::Keep;
    /// # let mut keep = Keep::create(Path::new("/tmp/k"), "pw")?;
    /// let pubkey = keep.generate_key("my-nostr-key")?;
    /// println!("Created key: {}", hex::encode(pubkey));
    /// # Ok::<(), keep_core::error::KeepError>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`KeepError::Locked`] if the Keep is not unlocked.
    pub fn generate_key(&mut self, name: &str) -> Result<[u8; 32]> {
        if !self.is_unlocked() {
            return Err(KeepError::Locked);
        }

        let keypair = NostrKeypair::generate()?;
        let pubkey = *keypair.public_bytes();

        let data_key = self.get_data_key()?;
        let encrypted = crypto::encrypt(keypair.secret_bytes(), &data_key)?;

        let record = KeyRecord::new(
            pubkey,
            KeyType::Nostr,
            name.to_string(),
            encrypted.to_bytes(),
        );

        self.storage.store_key(&record)?;

        self.keyring.load_key(
            pubkey,
            *keypair.secret_bytes(),
            KeyType::Nostr,
            name.to_string(),
        )?;

        self.audit_event(AuditEventType::KeyGenerate, |e| {
            e.with_pubkey(&pubkey).with_key_type("nostr")
        });

        Ok(pubkey)
    }

    /// Import an nsec and store it.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use std::path::Path;
    /// # use keep_core::Keep;
    /// # let mut keep = Keep::create(Path::new("/tmp/k"), "pw")?;
    /// let nsec = "nsec1...";
    /// let pubkey = keep.import_nsec(nsec, "imported-key")?;
    /// # Ok::<(), keep_core::error::KeepError>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`KeepError::Locked`] if the Keep is not unlocked.
    /// Returns [`KeepError::InvalidNsec`] if the nsec format is invalid.
    /// Returns [`KeepError::KeyAlreadyExists`] if the key is already stored.
    pub fn import_nsec(&mut self, nsec: &str, name: &str) -> Result<[u8; 32]> {
        if !self.is_unlocked() {
            return Err(KeepError::Locked);
        }

        let name = name.trim();
        if name.is_empty() {
            return Err(KeepError::InvalidInput("name cannot be empty".into()));
        }
        if name.chars().count() > 64 {
            return Err(KeepError::InvalidInput(
                "name must be 64 characters or fewer".into(),
            ));
        }

        let keypair = NostrKeypair::from_nsec(nsec)?;
        let pubkey = *keypair.public_bytes();

        if self.keyring.get(&pubkey).is_some() {
            return Err(KeepError::KeyAlreadyExists(keypair.to_npub()));
        }

        let data_key = self.get_data_key()?;
        let encrypted = crypto::encrypt(keypair.secret_bytes(), &data_key)?;

        let record = KeyRecord::new(
            pubkey,
            KeyType::Nostr,
            name.to_string(),
            encrypted.to_bytes(),
        );

        self.storage.store_key(&record)?;

        self.keyring.load_key(
            pubkey,
            *keypair.secret_bytes(),
            KeyType::Nostr,
            name.to_string(),
        )?;

        self.audit_event(AuditEventType::KeyImport, |e| {
            e.with_pubkey(&pubkey).with_key_type("nostr")
        });

        Ok(pubkey)
    }

    /// Import a Nostr key from raw secret bytes.
    pub fn import_secret_bytes(&mut self, secret: &mut [u8; 32], name: &str) -> Result<[u8; 32]> {
        if !self.is_unlocked() {
            return Err(KeepError::Locked);
        }

        let name = name.trim();
        if name.is_empty() {
            return Err(KeepError::InvalidInput("name cannot be empty".into()));
        }
        if name.chars().count() > 64 {
            return Err(KeepError::InvalidInput(
                "name must be 64 characters or fewer".into(),
            ));
        }

        let keypair = NostrKeypair::from_secret_bytes(secret)?;
        let pubkey = *keypair.public_bytes();

        if self.keyring.get(&pubkey).is_some() {
            return Err(KeepError::KeyAlreadyExists(keypair.to_npub()));
        }

        let data_key = self.get_data_key()?;
        let encrypted = crypto::encrypt(keypair.secret_bytes(), &data_key)?;

        let record = KeyRecord::new(
            pubkey,
            KeyType::Nostr,
            name.to_string(),
            encrypted.to_bytes(),
        );

        self.storage.store_key(&record)?;

        self.keyring.load_key(
            pubkey,
            *keypair.secret_bytes(),
            KeyType::Nostr,
            name.to_string(),
        )?;

        self.audit_event(AuditEventType::KeyImport, |e| {
            e.with_pubkey(&pubkey).with_key_type("nostr")
        });

        Ok(pubkey)
    }

    /// The primary key slot, if set.
    pub fn get_primary_key(&self) -> Option<&keyring::KeySlot> {
        self.keyring.get_primary()
    }

    /// List all stored key records.
    pub fn list_keys(&self) -> Result<Vec<KeyRecord>> {
        self.storage.list_keys()
    }

    /// Store (insert or overwrite by id) an arbitrary-secret record (password,
    /// API token, note). The whole record, including its plaintext value and
    /// title, is encrypted under the vault data key at rest. See
    /// [`storage::Storage::store_secret`]. Records a `SecretCreate` audit event
    /// (tagged with the non-sensitive random id, never the name or value) so
    /// secret mutations leave a forensic trail like every other sensitive op.
    pub fn store_secret(&mut self, record: &crate::secret::SecretRecord) -> Result<()> {
        self.storage.store_secret(record)?;
        self.audit_event(AuditEventType::SecretCreate, |e| e.with_pubkey(&record.id));
        Ok(())
    }

    /// Load a secret record by its 32-byte id.
    pub fn load_secret(&self, id: &[u8; 32]) -> Result<crate::secret::SecretRecord> {
        self.storage.load_secret(id)
    }

    /// List all stored secret records.
    pub fn list_secrets(&self) -> Result<Vec<crate::secret::SecretRecord>> {
        self.storage.list_secrets()
    }

    /// Delete a secret record by its 32-byte id. Records a `SecretDelete` audit
    /// event tagged with the id.
    pub fn delete_secret(&mut self, id: &[u8; 32]) -> Result<()> {
        self.storage.delete_secret(id)?;
        self.audit_event(AuditEventType::SecretDelete, |e| e.with_pubkey(id));
        Ok(())
    }

    /// Restore a secret WITHOUT emitting an audit event, for the backup-restore
    /// path only. Restore re-establishes the source vault's audit log verbatim
    /// (see `VaultBackup::audit_entries`), so re-auditing each restored row would
    /// double-count. Mirrors `restore_key_record`.
    pub fn restore_secret(&self, record: &crate::secret::SecretRecord) -> Result<()> {
        self.storage.store_secret(record)
    }

    /// Store a secret whose value can only be revealed with a t-of-n OPRF quorum.
    ///
    /// Takes a caller-minted `record` (via [`crate::secret::SecretRecord::new`])
    /// carrying the plaintext in `record.value`. The caller must mint the record
    /// FIRST so it knows the id, then derive `oprf_key` from the quorum for that id
    /// (`oprf_id = hex(record.id)`, `epoch`) BEFORE calling this: the seal records
    /// `oprf_id`, and a reveal re-derives the key for the same id, so a key derived
    /// for any other id would seal a value no quorum could ever reopen.
    ///
    /// `oprf_key` is the quorum-derived key ([`crate::oprf::derive_luks_key`]
    /// output); `epoch` its OPRF rotation counter. The value is sealed under a fresh
    /// per-secret DEK wrapped by `oprf_key`, so a single device that never assembles
    /// the quorum cannot decrypt it even with the vault unlocked. The record's
    /// name/kind stay readable with the vault data key. Returns the stored record
    /// (its `value` now the DEK-ciphertext). Records a `SecretCreate` audit event.
    pub fn store_sealed_secret(
        &mut self,
        mut record: crate::secret::SecretRecord,
        oprf_key: &crate::crypto::SecretKey,
        epoch: u32,
    ) -> Result<crate::secret::SecretRecord> {
        let oprf_id = hex::encode(record.id);
        // Take the plaintext out of the record and seal it; `record.value` becomes
        // the DEK-ciphertext. The lifted plaintext is zeroized when this scope ends.
        let plaintext = zeroize::Zeroizing::new(std::mem::take(&mut record.value));
        let (value_ciphertext, seal) =
            crate::secret::seal_value(&plaintext, oprf_key, oprf_id, epoch)?;
        record.value = value_ciphertext;
        self.storage.store_sealed_secret(&record, &seal)?;
        self.audit_event(AuditEventType::SecretCreate, |e| e.with_pubkey(&record.id));
        Ok(record)
    }

    /// Load the threshold seal for a secret id, or `None` if the secret is an
    /// ordinary plaintext-value secret. The seal carries the OPRF params
    /// (`oprf_id`, `epoch`) the quorum needs to re-derive the unwrapping key.
    pub fn load_secret_seal(&self, id: &[u8; 32]) -> Result<Option<crate::secret::ThresholdSeal>> {
        self.storage.load_secret_seal(id)
    }

    /// Reveal a threshold-sealed secret's plaintext value given the OPRF-quorum
    /// -derived key. Errors if the secret is not sealed, or if `oprf_key` is wrong
    /// (a single-device caller that never assembled the quorum cannot derive it).
    ///
    /// Records a `SecretReveal` audit event (tagged with the id) only on a
    /// successful unseal: revealing a quorum-gated plaintext is the most sensitive
    /// read in the store, audited like `KeyExport`. A wrong-key attempt leaves no
    /// entry (it never yields the value).
    pub fn reveal_sealed_secret(
        &mut self,
        id: &[u8; 32],
        oprf_key: &crate::crypto::SecretKey,
    ) -> Result<zeroize::Zeroizing<Vec<u8>>> {
        let record = self.storage.load_secret(id)?;
        let seal = self
            .storage
            .load_secret_seal(id)?
            .ok_or_else(|| KeepError::invalid_input("secret is not threshold-sealed"))?;
        let plaintext = crate::secret::unseal_value(&record.value, &seal, oprf_key)?;
        self.audit_event(AuditEventType::SecretReveal, |e| e.with_pubkey(id));
        Ok(plaintext)
    }

    /// Restore a threshold-sealed secret (record + seal) WITHOUT emitting an audit
    /// event, for the backup-restore path only. Mirrors [`Self::restore_secret`].
    pub fn restore_sealed_secret(
        &self,
        record: &crate::secret::SecretRecord,
        seal: &crate::secret::ThresholdSeal,
    ) -> Result<()> {
        self.storage.store_sealed_secret(record, seal)
    }

    /// Export a stored nsec key as NIP-49 ncryptsec.
    pub fn export_ncryptsec(&mut self, pubkey: &[u8; 32], password: &str) -> Result<String> {
        if !self.is_unlocked() {
            return Err(KeepError::Locked);
        }

        let slot = self
            .keyring
            .get(pubkey)
            .ok_or_else(|| KeepError::KeyNotFound(hex::encode(pubkey)))?;

        if slot.key_type != KeyType::Nostr {
            return Err(KeepError::InvalidInput("not a Nostr key".into()));
        }

        let result = keys::nip49::encrypt(slot.expose_secret(), password, None)?;
        self.audit_event(AuditEventType::KeyExport, |e| e.with_pubkey(pubkey));
        Ok(result)
    }

    /// Delete a key.
    pub fn delete_key(&mut self, pubkey: &[u8; 32]) -> Result<()> {
        let id = crypto::blake2b_256(pubkey);
        self.storage.delete_key(&id)?;
        self.keyring.remove(pubkey)?;
        self.audit_event(AuditEventType::KeyDelete, |e| e.with_pubkey(pubkey));
        Ok(())
    }

    /// The keyring.
    pub fn keyring(&self) -> &Keyring {
        &self.keyring
    }

    /// Decrypted audit log entries for this vault, in chronological order.
    /// Returns an empty vec if the audit log file does not exist yet.
    ///
    /// # Errors
    /// Returns [`KeepError::Locked`] if the vault is not unlocked.
    pub fn read_audit_entries(&self) -> Result<Vec<AuditEntry>> {
        if !self.is_unlocked() {
            return Err(KeepError::Locked);
        }
        let data_key = self.get_data_key()?;
        let audit = AuditLog::open(self.storage.path(), &data_key)?;
        audit.read_all(&data_key)
    }

    /// Mutable access to the keyring.
    pub fn keyring_mut(&mut self) -> &mut Keyring {
        &mut self.keyring
    }

    /// Generate a new FROST key with the given threshold and total shares.
    pub fn frost_generate(
        &mut self,
        threshold: u16,
        total_shares: u16,
        name: &str,
    ) -> Result<Vec<SharePackage>> {
        if !self.is_unlocked() {
            return Err(KeepError::Locked);
        }

        let config = ThresholdConfig::new(threshold, total_shares)?;
        let dealer = TrustedDealer::new(config);
        let (shares, _) = dealer.generate(name)?;

        let data_key = self.get_data_key()?;
        for share in &shares {
            let stored = StoredShare::encrypt(share, &data_key)?;
            self.storage.store_share(&stored)?;
        }

        let group_pubkey = *shares[0].group_pubkey();
        let participants: Vec<u16> = (1..=total_shares).collect();
        self.audit_event(AuditEventType::FrostGenerate, |e| {
            e.with_group(&group_pubkey)
                .with_threshold(threshold)
                .with_participants(participants)
        });

        Ok(shares)
    }

    /// Split an existing key into FROST shares.
    pub fn frost_split(
        &mut self,
        key_name: &str,
        threshold: u16,
        total_shares: u16,
    ) -> Result<Vec<SharePackage>> {
        if !self.is_unlocked() {
            return Err(KeepError::Locked);
        }

        let slot = self
            .keyring
            .get_by_name(key_name)
            .ok_or_else(|| KeepError::KeyNotFound(key_name.to_string()))?;

        let secret = Zeroizing::new(*slot.expose_secret());

        let config = ThresholdConfig::new(threshold, total_shares)?;
        let dealer = TrustedDealer::new(config);
        let (shares, _) = dealer.split_existing(&secret, key_name)?;

        let data_key = self.get_data_key()?;
        for share in &shares {
            let stored = StoredShare::encrypt(share, &data_key)?;
            self.storage.store_share(&stored)?;
        }

        let group_pubkey = *shares[0].group_pubkey();
        let participants: Vec<u16> = (1..=total_shares).collect();
        self.audit_event(AuditEventType::FrostSplit, |e| {
            e.with_group(&group_pubkey)
                .with_threshold(threshold)
                .with_participants(participants)
        });

        Ok(shares)
    }

    /// List all stored FROST shares.
    pub fn frost_list_shares(&self) -> Result<Vec<StoredShare>> {
        self.storage.list_shares()
    }

    fn find_stored_share(
        &self,
        group_pubkey: &[u8; 32],
        identifier: u16,
        ciphersuite: Option<crate::frost::Ciphersuite>,
    ) -> Result<StoredShare> {
        let shares = self.storage.list_shares()?;
        shares
            .into_iter()
            .find(|s| {
                s.metadata.group_pubkey == *group_pubkey
                    && s.metadata.identifier == identifier
                    && ciphersuite.is_none_or(|cs| s.ciphersuite == cs)
            })
            .ok_or_else(|| KeepError::KeyNotFound(format!("No share {identifier} for group")))
    }

    /// Export a FROST share encrypted with a passphrase.
    pub fn frost_export_share(
        &mut self,
        group_pubkey: &[u8; 32],
        identifier: u16,
        passphrase: &str,
    ) -> Result<ShareExport> {
        if !self.is_unlocked() {
            return Err(KeepError::Locked);
        }

        let mut stored = self.find_stored_share(group_pubkey, identifier, None)?;
        let data_key = self.get_data_key()?;
        let share = stored.decrypt(&data_key)?;

        self.audit_event(AuditEventType::FrostShareExport, |e| {
            e.with_group(group_pubkey)
                .with_participants(vec![identifier])
        });

        let export =
            ShareExport::from_share_with_ciphersuite(&share, stored.ciphersuite, passphrase)?;

        // Exporting is the backup action: record it so the UI/clients can stop
        // nagging "not backed up". Best-effort; a storage error here must not
        // fail the export the caller already holds.
        if !stored.metadata.did_backup {
            stored.metadata.mark_backed_up();
            if let Err(e) = self.storage.store_share(&stored) {
                tracing::warn!(error = %e, "failed to persist did_backup after export");
            }
        }

        Ok(export)
    }

    /// Import a FROST share from an encrypted export.
    pub fn frost_import_share(
        &mut self,
        export: &ShareExport,
        passphrase: &str,
        name: &str,
    ) -> Result<()> {
        if !self.is_unlocked() {
            return Err(KeepError::Locked);
        }
        let name = name.trim();
        if name.is_empty() {
            return Err(KeepError::InvalidInput("name cannot be empty".into()));
        }
        if name.chars().count() > 64 {
            return Err(KeepError::InvalidInput(
                "name must be 64 characters or fewer".into(),
            ));
        }

        let share = export.to_share(passphrase, name)?;
        let data_key = self.get_data_key()?;
        let stored = StoredShare::encrypt_with_ciphersuite(&share, export.ciphersuite, &data_key)?;
        self.storage.store_share(&stored)?;

        let group = hex::decode(&export.group_pubkey)
            .ok()
            .and_then(|bytes| <[u8; 32]>::try_from(bytes.as_slice()).ok())
            .unwrap_or_else(|| crypto::blake2b_256(export.group_pubkey.as_bytes()));
        self.audit_event(AuditEventType::FrostShareImport, |e| {
            e.with_group(&group)
                .with_participants(vec![export.identifier])
        });

        Ok(())
    }

    /// Persist a share produced by [`frost::dkg::SoftwareDkgSession::finalize`]
    /// (#454). Wraps the finalized `KeyPackage` + `PublicKeyPackage` into a
    /// [`SharePackage`] with fresh metadata, encrypts under the vault's data
    /// key, stores it, and writes a `FrostShareImport` audit entry.
    pub fn frost_store_dkg_share(
        &mut self,
        result: &crate::frost::dkg::SoftwareDkgResult,
        threshold: u16,
        total_shares: u16,
        name: &str,
    ) -> Result<()> {
        if !self.is_unlocked() {
            return Err(KeepError::Locked);
        }
        let name = name.trim();
        if name.is_empty() {
            return Err(KeepError::InvalidInput("name cannot be empty".into()));
        }
        if name.chars().count() > 64 {
            return Err(KeepError::InvalidInput(
                "name must be 64 characters or fewer".into(),
            ));
        }

        let metadata = crate::frost::ShareMetadata::new(
            result.our_index,
            threshold,
            total_shares,
            result.group_pubkey,
            name.to_string(),
        );
        let share = crate::frost::SharePackage::new(
            metadata,
            &result.key_package,
            &result.public_key_package,
        )?;

        let data_key = self.get_data_key()?;
        let stored = StoredShare::encrypt(&share, &data_key)?;
        self.storage.store_share(&stored)?;

        self.audit_event(AuditEventType::FrostShareImport, |e| {
            e.with_group(&result.group_pubkey)
                .with_threshold(threshold)
                .with_participants(vec![result.our_index])
        });

        Ok(())
    }

    /// Refresh all FROST shares for a group, invalidating old shares.
    pub fn frost_refresh(&mut self, group_pubkey: &[u8; 32]) -> Result<Vec<frost::ShareMetadata>> {
        if !self.is_unlocked() {
            return Err(KeepError::Locked);
        }

        let data_key = self.get_data_key()?;
        let all_shares = self.storage.list_shares()?;
        let group_shares: Vec<_> = all_shares
            .into_iter()
            .filter(|s| {
                s.metadata.group_pubkey == *group_pubkey
                    && s.ciphersuite == crate::frost::Ciphersuite::Secp256k1Tr
            })
            .collect();

        if group_shares.is_empty() {
            return Err(KeepError::KeyNotFound("No shares for group".into()));
        }

        let threshold = group_shares[0].metadata.threshold;
        let total = group_shares[0].metadata.total_shares;

        let share_count: u16 = group_shares
            .len()
            .try_into()
            .map_err(|_| KeepError::Frost("Too many shares".into()))?;
        if share_count != total {
            return Err(KeepError::Frost(format!(
                "refresh requires the full set of {total} shares; only {share_count} available. \
                 A partial refresh would orphan the absent shares (#586)."
            )));
        }

        let decrypted: Vec<SharePackage> = group_shares
            .iter()
            .map(|s| s.decrypt(&data_key))
            .collect::<Result<_>>()?;

        let (refreshed, _) = frost::refresh_shares(&decrypted)?;

        let encrypted_shares: Vec<StoredShare> = refreshed
            .iter()
            .map(|share| StoredShare::encrypt(share, &data_key))
            .collect::<Result<_>>()?;

        self.storage.store_shares_atomic(&encrypted_shares)?;

        let metadata: Vec<_> = refreshed.iter().map(|s| s.metadata.clone()).collect();
        let participants: Vec<u16> = metadata.iter().map(|m| m.identifier).collect();
        self.audit_event(AuditEventType::FrostShareRefresh, |e| {
            e.with_group(group_pubkey)
                .with_threshold(threshold)
                .with_participants(participants)
        });

        Ok(metadata)
    }

    /// Delete a FROST share.
    pub fn frost_delete_share(&mut self, group_pubkey: &[u8; 32], identifier: u16) -> Result<()> {
        self.storage.delete_share(group_pubkey, identifier)?;
        self.audit_event(AuditEventType::FrostShareDelete, |e| {
            e.with_group(group_pubkey)
                .with_participants(vec![identifier])
        });
        Ok(())
    }

    /// Rename a stored FROST share (updates its display name only).
    pub fn frost_rename_share(
        &mut self,
        group_pubkey: &[u8; 32],
        identifier: u16,
        name: &str,
    ) -> Result<()> {
        if !self.is_unlocked() {
            return Err(KeepError::Locked);
        }
        let name = name.trim();
        if name.is_empty() {
            return Err(KeepError::InvalidInput(
                "share name must not be empty".into(),
            ));
        }
        if name.chars().count() > 64 {
            return Err(KeepError::InvalidInput(
                "share name must not exceed 64 characters".into(),
            ));
        }
        let mut stored = self.find_stored_share(group_pubkey, identifier, None)?;
        stored.metadata.name = name.to_string();
        self.storage.store_share(&stored)?;
        Ok(())
    }

    /// Get the hex-encoded group pubkey of the active share, if set.
    pub fn get_active_share_key(&self) -> Option<String> {
        std::fs::read_to_string(self.active_share_path())
            .ok()
            .map(|s| s.trim().to_string())
            .filter(|s| is_valid_hex_pubkey(s))
    }

    /// Set the active share by hex-encoded group pubkey. Pass `None` to clear.
    pub fn set_active_share_key(&self, key: Option<&str>) -> Result<()> {
        if !self.is_unlocked() {
            return Err(KeepError::Locked);
        }
        let path = self.active_share_path();
        match key {
            Some(k) => {
                if !is_valid_hex_pubkey(k) {
                    return Err(KeepError::InvalidInput(
                        "Group pubkey must be 64 hex characters".into(),
                    ));
                }
                let normalized = k.to_ascii_lowercase();
                write_restricted(&path, normalized.as_bytes())?;
            }
            None => {
                if let Err(e) = std::fs::remove_file(&path) {
                    if e.kind() != std::io::ErrorKind::NotFound {
                        return Err(e.into());
                    }
                }
            }
        }
        Ok(())
    }

    fn active_share_path(&self) -> PathBuf {
        self.storage.path.join("active_share")
    }

    /// Store a finalized wallet descriptor, associated with a FROST group.
    pub fn store_wallet_descriptor(&self, descriptor: &WalletDescriptor) -> Result<()> {
        if !self.is_unlocked() {
            return Err(KeepError::Locked);
        }
        self.storage.store_descriptor(descriptor)
    }

    /// Get the wallet descriptor for a FROST group.
    pub fn get_wallet_descriptor(
        &self,
        group_pubkey: &[u8; 32],
    ) -> Result<Option<WalletDescriptor>> {
        if !self.is_unlocked() {
            return Err(KeepError::Locked);
        }
        self.storage.get_descriptor(group_pubkey)
    }

    /// List the latest-version wallet descriptor for every group. Older
    /// descriptor versions are not returned; use
    /// [`list_all_wallet_descriptor_versions`] when every row is required
    /// (backup, rotation re-encryption verification, etc.).
    ///
    /// [`list_all_wallet_descriptor_versions`]: Self::list_all_wallet_descriptor_versions
    pub fn list_wallet_descriptors(&self) -> Result<Vec<WalletDescriptor>> {
        if !self.is_unlocked() {
            return Err(KeepError::Locked);
        }
        self.storage.list_descriptors()
    }

    /// List every persisted wallet descriptor row across all groups and
    /// versions. Used by backup and rotation paths that must round-trip every
    /// stored record.
    pub fn list_all_wallet_descriptor_versions(&self) -> Result<Vec<WalletDescriptor>> {
        if !self.is_unlocked() {
            return Err(KeepError::Locked);
        }
        self.storage.list_all_descriptor_versions()
    }

    /// Delete a wallet descriptor.
    pub fn delete_wallet_descriptor(&self, group_pubkey: &[u8; 32]) -> Result<()> {
        if !self.is_unlocked() {
            return Err(KeepError::Locked);
        }
        self.storage.delete_descriptor(group_pubkey)
    }

    /// Atomically insert or update a device registration on the descriptor for
    /// the given FROST group. Performs the load-modify-store under the
    /// storage's descriptor write lock so concurrent callers cannot drop each
    /// other's updates.
    pub fn upsert_device_registration(
        &self,
        group_pubkey: &[u8; 32],
        registration: DeviceRegistration,
    ) -> Result<()> {
        if !self.is_unlocked() {
            return Err(KeepError::Locked);
        }
        self.storage
            .upsert_device_registration(group_pubkey, registration)
    }

    /// Store a key health status record.
    pub fn store_health_status(&self, status: &wallet::KeyHealthStatus) -> Result<()> {
        if !self.is_unlocked() {
            return Err(KeepError::Locked);
        }
        self.storage.store_health_status(status)
    }

    /// Get a key health status record.
    pub fn get_health_status(
        &self,
        group_pubkey: &[u8; 32],
        share_index: u16,
    ) -> Result<Option<wallet::KeyHealthStatus>> {
        if !self.is_unlocked() {
            return Err(KeepError::Locked);
        }
        self.storage.get_health_status(group_pubkey, share_index)
    }

    /// List all key health status records.
    pub fn list_health_statuses(&self) -> Result<Vec<wallet::KeyHealthStatus>> {
        if !self.is_unlocked() {
            return Err(KeepError::Locked);
        }
        self.storage.list_health_statuses()
    }

    /// List health statuses that are stale (not checked within the threshold).
    pub fn list_stale_health_statuses(&self, now: u64) -> Result<Vec<wallet::KeyHealthStatus>> {
        if !self.is_unlocked() {
            return Err(KeepError::Locked);
        }
        let all = self.storage.list_health_statuses()?;
        Ok(all.into_iter().filter(|s| s.is_stale(now)).collect())
    }

    /// Store relay configuration for a FROST share.
    pub fn store_relay_config(&self, config: &RelayConfig) -> Result<()> {
        if !self.is_unlocked() {
            return Err(KeepError::Locked);
        }
        let normalized_config = config.clone().normalize()?;
        self.storage.store_relay_config(&normalized_config)
    }

    /// Get relay configuration for a FROST share.
    pub fn get_relay_config(&self, group_pubkey: &[u8; 32]) -> Result<Option<RelayConfig>> {
        if !self.is_unlocked() {
            return Err(KeepError::Locked);
        }
        self.storage.get_relay_config(group_pubkey)
    }

    /// Get relay configuration for a FROST share, returning defaults if none stored.
    pub fn get_relay_config_or_default(&self, group_pubkey: &[u8; 32]) -> Result<RelayConfig> {
        if !self.is_unlocked() {
            return Err(KeepError::Locked);
        }
        Ok(self
            .storage
            .get_relay_config(group_pubkey)?
            .unwrap_or_else(|| RelayConfig::with_defaults(*group_pubkey)))
    }

    /// List all stored relay configurations.
    pub fn list_relay_configs(&self) -> Result<Vec<RelayConfig>> {
        if !self.is_unlocked() {
            return Err(KeepError::Locked);
        }
        self.storage.list_relay_configs()
    }

    /// Delete relay configuration for a FROST share.
    pub fn delete_relay_config(&self, group_pubkey: &[u8; 32]) -> Result<()> {
        if !self.is_unlocked() {
            return Err(KeepError::Locked);
        }
        self.storage.delete_relay_config(group_pubkey)
    }

    /// Get the kill switch state from the vault.
    pub fn get_kill_switch(&self) -> Result<bool> {
        if !self.is_unlocked() {
            return Err(KeepError::Locked);
        }
        self.storage.get_kill_switch()
    }

    /// Set the kill switch state in the vault.
    pub fn set_kill_switch(&self, active: bool) -> Result<()> {
        if !self.is_unlocked() {
            return Err(KeepError::Locked);
        }
        self.storage.set_kill_switch(active)
    }

    /// Get the proxy configuration.
    pub fn get_proxy_config(&self) -> Result<ProxyConfig> {
        if !self.is_unlocked() {
            return Err(KeepError::Locked);
        }
        self.storage.get_proxy_config()
    }

    /// Set the proxy configuration.
    pub fn set_proxy_config(&self, config: &ProxyConfig) -> Result<()> {
        if !self.is_unlocked() {
            return Err(KeepError::Locked);
        }
        self.storage.set_proxy_config(config)
    }

    /// Get a FROST share by group public key.
    pub fn frost_get_share(&self, group_pubkey: &[u8; 32]) -> Result<frost::SharePackage> {
        if !self.is_unlocked() {
            return Err(KeepError::Locked);
        }

        let data_key = self.get_data_key()?;
        let shares = self.storage.list_shares()?;
        let stored = shares
            .iter()
            .find(|s| {
                s.metadata.group_pubkey == *group_pubkey
                    && s.ciphersuite == crate::frost::Ciphersuite::Secp256k1Tr
            })
            .ok_or_else(|| KeepError::KeyNotFound("No shares for group".into()))?;

        stored.decrypt(&data_key)
    }

    /// Get a FROST share by group public key and identifier index.
    pub fn frost_get_share_by_index(
        &self,
        group_pubkey: &[u8; 32],
        identifier: u16,
    ) -> Result<frost::SharePackage> {
        if !self.is_unlocked() {
            return Err(KeepError::Locked);
        }

        let stored = self.find_stored_share(group_pubkey, identifier, None)?;
        let data_key = self.get_data_key()?;
        stored.decrypt(&data_key)
    }

    /// Sign using local FROST shares. Requires threshold shares locally.
    pub fn frost_sign(&mut self, group_pubkey: &[u8; 32], message: &[u8]) -> Result<[u8; 64]> {
        if !self.is_unlocked() {
            return Err(KeepError::Locked);
        }

        let data_key = self.get_data_key()?;
        let shares = self.storage.list_shares()?;
        let our_shares: Vec<_> = shares
            .iter()
            .filter(|s| {
                s.metadata.group_pubkey == *group_pubkey
                    && s.ciphersuite == crate::frost::Ciphersuite::Secp256k1Tr
            })
            .collect();

        if our_shares.is_empty() {
            return Err(KeepError::KeyNotFound("No shares for group".into()));
        }

        let threshold = our_shares[0].metadata.threshold;

        if our_shares.len() < threshold as usize {
            self.audit_event(AuditEventType::FrostSignFailed, |e| {
                e.with_group(group_pubkey)
                    .with_message_hash(message)
                    .with_success(false)
                    .with_reason("Insufficient shares")
            });
            return Err(KeepError::Frost(format!(
                "Need {} shares to sign, only {} available",
                threshold,
                our_shares.len()
            )));
        }

        let mut decrypted_shares = Vec::new();
        for stored in our_shares.iter().take(threshold as usize) {
            decrypted_shares.push(stored.decrypt(&data_key)?);
        }

        match frost::sign_with_local_shares(&decrypted_shares, message) {
            Ok(sig) => {
                self.audit_event(AuditEventType::FrostSign, |e| {
                    e.with_group(group_pubkey)
                        .with_message_hash(message)
                        .with_threshold(threshold)
                });
                Ok(sig)
            }
            Err(e) => {
                self.audit_event(AuditEventType::FrostSignFailed, |e| {
                    e.with_group(group_pubkey)
                        .with_message_hash(message)
                        .with_success(false)
                });
                Err(e)
            }
        }
    }

    /// Generate a FROST-Ed25519 threshold key and store its shares.
    ///
    /// Shares are tagged with [`Ciphersuite::Ed25519`], which is bound into the
    /// at-rest AEAD AAD so they cannot be confused with secp256k1 shares.
    #[cfg(feature = "ed25519")]
    pub fn frost_generate_ed25519(
        &mut self,
        threshold: u16,
        total_shares: u16,
        name: &str,
    ) -> Result<Vec<SharePackage>> {
        if !self.is_unlocked() {
            return Err(KeepError::Locked);
        }

        let config = ThresholdConfig::new(threshold, total_shares)?;
        let dealer = crate::frost::ed25519::TrustedDealer::new(config);
        let (shares, _) = dealer.generate(name)?;

        let data_key = self.get_data_key()?;
        for share in &shares {
            let stored = StoredShare::encrypt_with_ciphersuite(
                share,
                crate::frost::Ciphersuite::Ed25519,
                &data_key,
            )?;
            self.storage.store_share(&stored)?;
        }

        let group_pubkey = *shares[0].group_pubkey();
        let participants: Vec<u16> = shares.iter().map(|s| s.metadata.identifier).collect();
        self.audit_event(AuditEventType::FrostGenerate, |e| {
            e.with_group(&group_pubkey)
                .with_threshold(threshold)
                .with_participants(participants)
        });

        Ok(shares)
    }

    /// Sign a message with a threshold of local FROST-Ed25519 shares.
    ///
    /// Returns a detached 64-byte Ed25519 signature over the raw message
    /// (RFC 8032), verifiable by [`Keep::frost_verify_ed25519`] and by any
    /// standard Ed25519 verifier against the group public key.
    #[cfg(feature = "ed25519")]
    pub fn frost_sign_ed25519(
        &mut self,
        group_pubkey: &[u8; 32],
        message: &[u8],
    ) -> Result<[u8; 64]> {
        if !self.is_unlocked() {
            return Err(KeepError::Locked);
        }

        let decrypted_shares = match self.frost_ed25519_decrypt_threshold_shares(group_pubkey) {
            Ok(shares) => shares,
            Err(e) => {
                self.audit_event(AuditEventType::FrostSignFailed, |ev| {
                    ev.with_group(group_pubkey)
                        .with_message_hash(message)
                        .with_success(false)
                        .with_reason("Insufficient shares")
                });
                return Err(e);
            }
        };
        let threshold = decrypted_shares[0].metadata.threshold;

        match crate::frost::ed25519::sign_with_local_shares(&decrypted_shares, message) {
            Ok(sig) => {
                self.audit_event(AuditEventType::FrostSign, |e| {
                    e.with_group(group_pubkey)
                        .with_message_hash(message)
                        .with_threshold(threshold)
                });
                Ok(sig)
            }
            Err(e) => {
                self.audit_event(AuditEventType::FrostSignFailed, |e| {
                    e.with_group(group_pubkey)
                        .with_message_hash(message)
                        .with_success(false)
                });
                Err(e)
            }
        }
    }

    /// Decrypt the threshold set of local Ed25519 shares for a group.
    ///
    /// Returns exactly `threshold` decrypted shares or a `KeyNotFound`/`Frost`
    /// error. Does not emit audit events; callers own audit semantics.
    #[cfg(feature = "ed25519")]
    fn frost_ed25519_decrypt_threshold_shares(
        &self,
        group_pubkey: &[u8; 32],
    ) -> Result<Vec<SharePackage>> {
        let data_key = self.get_data_key()?;
        let shares = self.storage.list_shares()?;
        let our_shares: Vec<_> = shares
            .iter()
            .filter(|s| {
                s.metadata.group_pubkey == *group_pubkey
                    && s.ciphersuite == crate::frost::Ciphersuite::Ed25519
            })
            .collect();

        if our_shares.is_empty() {
            return Err(KeepError::KeyNotFound("No Ed25519 shares for group".into()));
        }

        let threshold = our_shares[0].metadata.threshold;
        if our_shares.len() < threshold as usize {
            return Err(KeepError::Frost(format!(
                "Need {} shares to sign, only {} available",
                threshold,
                our_shares.len()
            )));
        }

        let mut decrypted_shares = Vec::with_capacity(threshold as usize);
        for stored in our_shares.iter().take(threshold as usize) {
            decrypted_shares.push(stored.decrypt(&data_key)?);
        }
        Ok(decrypted_shares)
    }

    /// Verify a detached Ed25519 signature against a group public key.
    #[cfg(feature = "ed25519")]
    pub fn frost_verify_ed25519(
        group_pubkey: &[u8; 32],
        message: &[u8],
        signature: &[u8; 64],
    ) -> Result<()> {
        crate::frost::ed25519::verify(group_pubkey, message, signature)
    }

    /// Sign `message` and produce a minisign-compatible detached signature.
    ///
    /// Runs two FROST-Ed25519 threshold signing sessions: one over the
    /// BLAKE2b-512 prehash of the message (the `"ED"` file signature) and one
    /// over `file_signature || trusted_comment` (the global signature). The
    /// result verifies with the standard `minisign -V` tool against the
    /// exported group public key.
    #[cfg(feature = "ed25519")]
    pub fn frost_sign_ed25519_minisign(
        &mut self,
        group_pubkey: &[u8; 32],
        message: &[u8],
        untrusted_comment: String,
        trusted_comment: String,
    ) -> Result<crate::frost::ed25519::minisign::MinisignSignature> {
        use crate::frost::ed25519::minisign;

        if !self.is_unlocked() {
            return Err(KeepError::Locked);
        }

        minisign::validate_comment("untrusted", &untrusted_comment)?;
        minisign::validate_comment("trusted", &trusted_comment)?;

        let decrypted_shares = match self.frost_ed25519_decrypt_threshold_shares(group_pubkey) {
            Ok(shares) => shares,
            Err(e) => {
                self.audit_event(AuditEventType::FrostSignFailed, |ev| {
                    ev.with_group(group_pubkey)
                        .with_message_hash(message)
                        .with_success(false)
                        .with_reason("Insufficient shares")
                });
                return Err(e);
            }
        };
        let threshold = decrypted_shares[0].metadata.threshold;

        // Two independent threshold sessions over the same decrypted share set:
        // fresh nonces per session keep each signature secure.
        let prehash = minisign::prehash(message);
        let sign_both = (|| {
            let signature =
                crate::frost::ed25519::sign_with_local_shares(&decrypted_shares, &prehash)?;
            let global_bytes = minisign::global_signed_bytes(&signature, &trusted_comment);
            let global_signature =
                crate::frost::ed25519::sign_with_local_shares(&decrypted_shares, &global_bytes)?;
            Ok::<_, KeepError>((signature, global_signature))
        })();

        let (signature, global_signature) = match sign_both {
            Ok(pair) => {
                self.audit_event(AuditEventType::FrostSign, |e| {
                    e.with_group(group_pubkey)
                        .with_message_hash(message)
                        .with_threshold(threshold)
                });
                pair
            }
            Err(e) => {
                self.audit_event(AuditEventType::FrostSignFailed, |ev| {
                    ev.with_group(group_pubkey)
                        .with_message_hash(message)
                        .with_success(false)
                });
                return Err(e);
            }
        };

        Ok(minisign::MinisignSignature {
            sig_alg: minisign::ALG_PREHASHED,
            key_id: minisign::key_id(group_pubkey),
            signature,
            global_signature,
            untrusted_comment,
            trusted_comment,
        })
    }

    /// Verify a minisign-compatible detached signature against a group public
    /// key, checking both the file signature and the global signature using
    /// minisign's semantics (key-id match, prehash for `"ED"`, RFC 8032 strict
    /// cofactorless verification via frost-ed25519).
    #[cfg(feature = "ed25519")]
    pub fn frost_verify_ed25519_minisign(
        group_pubkey: &[u8; 32],
        message: &[u8],
        sig: &crate::frost::ed25519::minisign::MinisignSignature,
    ) -> Result<()> {
        use crate::frost::ed25519::minisign;

        if sig.key_id != minisign::key_id(group_pubkey) {
            return Err(KeepError::InvalidInput(
                "signature key id does not match group public key".into(),
            ));
        }

        let signed_message = match sig.sig_alg {
            minisign::ALG_PREHASHED => minisign::prehash(message).to_vec(),
            minisign::ALG_LEGACY => message.to_vec(),
            _ => {
                return Err(KeepError::InvalidInput(
                    "unknown signature algorithm".into(),
                ))
            }
        };

        crate::frost::ed25519::verify(group_pubkey, &signed_message, &sig.signature)?;

        let global_bytes = minisign::global_signed_bytes(&sig.signature, &sig.trusted_comment);
        crate::frost::ed25519::verify(group_pubkey, &global_bytes, &sig.global_signature)
    }

    fn load_keys_to_keyring(&mut self) -> Result<()> {
        let data_key = self.get_data_key()?;
        let records = self.storage.list_keys()?;

        for record in records {
            let encrypted = crypto::EncryptedData::from_bytes(&record.encrypted_secret)?;
            let secret_bytes = crypto::decrypt(&encrypted, &data_key)?;

            let mut secret = Zeroizing::new([0u8; 32]);
            let decrypted = secret_bytes.as_slice()?;
            secret.copy_from_slice(&decrypted);

            self.keyring
                .load_key(record.pubkey, *secret, record.key_type, record.name)?;
        }

        Ok(())
    }

    fn get_data_key(&self) -> Result<SecretKey> {
        self.storage.data_key().cloned().ok_or(KeepError::Locked)
    }

    /// Rotate the vault password.
    ///
    /// Re-encrypts the data encryption key with a new password-derived key.
    /// The data encryption key itself is unchanged, so stored secrets remain intact.
    ///
    /// Closes #579 (every post-storage-rotation failure path now emits a
    /// failure audit entry before propagating) and #580 (the success path
    /// uses `audit_event_required`, so a silent audit-write failure is
    /// surfaced as `KeepError::AuditWriteFailed`).
    pub fn rotate_password(&mut self, old_password: &str, new_password: &str) -> Result<()> {
        let result = self.rotate_password_inner(old_password, new_password);
        match &result {
            Ok(()) => self.audit_event_required(AuditEventType::PasswordRotate, |e| e),
            Err(e) => {
                // Failed attempts are observable only when the vault was
                // unlocked before the call (audit log needs the data key).
                let reason = e.to_string();
                self.audit_event(AuditEventType::PasswordRotateFailed, |entry| {
                    entry.with_success(false).with_reason(&reason)
                });
                result
            }
        }
    }

    fn rotate_password_inner(&mut self, old_password: &str, new_password: &str) -> Result<()> {
        self.storage.rotate_password(old_password, new_password)?;
        self.keyring.clear();
        self.load_keys_to_keyring()?;
        Ok(())
    }

    /// Rotate the data encryption key.
    ///
    /// Generates a new data encryption key and re-encrypts all stored keys and shares.
    ///
    /// Closes #579 (a failure before the storage commit audits
    /// DataKeyRotateFailed) and #580 (success path uses `audit_event_required`).
    pub fn rotate_data_key(&mut self, password: &str) -> Result<()> {
        // A locked vault has no data key, so the failure entry cannot be
        // encrypted/recorded here; `audit_event` no-ops in that case.
        let old_data_key = self.get_data_key()?;

        // Pre-commit phase. `storage.rotate_data_key` rolls back internally on
        // failure, so the on-disk data key is unchanged and the audit chains
        // still match `old_data_key` == the current data key. The failure entry
        // therefore encrypts under the key matching the on-disk chain (#579).
        if let Err(e) = self.storage.rotate_data_key(password) {
            let reason = e.to_string();
            self.audit_event(AuditEventType::DataKeyRotateFailed, |entry| {
                entry.with_success(false).with_reason(&reason)
            });
            return Err(e);
        }

        // Post-commit phase. Storage has durably committed the new data key, so
        // the rotation has already succeeded on disk; the audit chains are still
        // under `old_data_key` until re-encrypted below. A failure here must NOT
        // emit a DataKeyRotateFailed entry: it would be encrypted under the new
        // key and appended to a chain still under the old key (corrupting it,
        // since `reencrypt` is atomic and leaves the file under the old key on
        // failure), and it would misreport a rotation that already committed.
        let new_data_key = self.get_data_key()?;
        if let Some(ref mut audit) = self.audit {
            audit.reencrypt(&old_data_key, &new_data_key)?;
        }
        if let Some(ref mut signing_audit) = self.signing_audit {
            signing_audit.reencrypt(&old_data_key, &new_data_key)?;
        }

        // Both chains are now under `new_data_key`, so record the success entry
        // before reloading the keyring (#580 fails closed). The rotation has
        // already committed; the keyring is in-memory and rebuilt on the next
        // unlock, so a reload failure must not leave the rotation unrecorded.
        self.audit_event_required(AuditEventType::DataKeyRotate, |e| e)?;

        self.keyring.clear();
        self.load_keys_to_keyring()
    }

    /// Returns the data encryption key used to encrypt stored secrets.
    ///
    /// # Errors
    /// Returns [`KeepError::Locked`] if [`unlock()`](Self::unlock) has not been called.
    ///
    /// Exposed for FROST/FrostSigner integration to decrypt stored shares.
    pub fn data_key(&self) -> Result<SecretKey> {
        self.get_data_key()
    }

    /// Store a pre-encrypted key record directly (for backup restore).
    pub(crate) fn restore_key_record(&self, record: &KeyRecord) -> Result<()> {
        self.get_data_key()?;
        self.storage.store_key(record)
    }

    /// Store a pre-encrypted share directly (for backup restore).
    pub(crate) fn restore_stored_share(&self, share: &StoredShare) -> Result<()> {
        self.get_data_key()?;
        self.storage.store_share(share)
    }

    fn audit_event<F>(&mut self, event_type: AuditEventType, builder: F)
    where
        F: FnOnce(AuditEntry) -> AuditEntry,
    {
        let data_key = match self.get_data_key() {
            Ok(k) => k,
            Err(_) => return,
        };
        if let Some(ref mut audit) = self.audit {
            let entry = builder(AuditEntry::new(event_type, audit.last_hash()));
            if let Err(e) = audit.log(entry, &data_key) {
                tracing::warn!("Failed to write audit log entry for {}: {}", event_type, e);
            }
        }
    }

    /// Audit-write that propagates failure to the caller. Used for
    /// security-critical events where a silent best-effort log (#580) is
    /// unacceptable: a successful return MUST mean the audit entry was
    /// persisted. Fails closed when the vault is locked or the audit log is
    /// unavailable.
    fn audit_event_required<F>(&mut self, event_type: AuditEventType, builder: F) -> Result<()>
    where
        F: FnOnce(AuditEntry) -> AuditEntry,
    {
        let data_key = self.get_data_key()?;
        let audit = self.audit.as_mut().ok_or_else(|| {
            KeepError::AuditWriteFailed(format!(
                "audit log not initialized; cannot record required event {event_type}"
            ))
        })?;
        let entry = builder(AuditEntry::new(event_type, audit.last_hash()));
        audit
            .log(entry, &data_key)
            .map_err(|e| KeepError::AuditWriteFailed(format!("{event_type}: {e}")))
    }

    /// Read all audit log entries.
    pub fn audit_read_all(&self) -> Result<Vec<AuditEntry>> {
        let (audit, data_key) = self.audit_with_key()?;
        audit.read_all(&data_key)
    }

    /// Verify the integrity of the audit log chain.
    pub fn audit_verify_chain(&self) -> Result<bool> {
        let (audit, data_key) = self.audit_with_key()?;
        audit.verify_chain(&data_key)
    }

    /// Export the audit log as JSON.
    pub fn audit_export(&self) -> Result<String> {
        let (audit, data_key) = self.audit_with_key()?;
        audit.export(&data_key)
    }

    fn audit_with_key(&self) -> Result<(&AuditLog, SecretKey)> {
        let audit = self.audit.as_ref().ok_or(KeepError::Locked)?;
        let data_key = self.get_data_key()?;
        Ok((audit, data_key))
    }

    /// Set the retention policy for the audit log.
    pub fn audit_set_retention(&mut self, policy: RetentionPolicy) {
        if let Some(ref mut audit) = self.audit {
            audit.set_retention(policy);
        }
    }

    /// Apply the retention policy and return the number of entries removed.
    pub fn audit_apply_retention(&mut self) -> Result<usize> {
        let data_key = self.get_data_key()?;
        let audit = self.audit.as_mut().ok_or(KeepError::Locked)?;
        audit.apply_retention(&data_key)
    }

    /// Log a signing audit entry.
    pub fn signing_audit_log(&mut self, entry: SigningAuditEntry) -> Result<()> {
        let data_key = self.get_data_key()?;
        let log = self.signing_audit.as_mut().ok_or(KeepError::Locked)?;
        log.log(entry, &data_key)
    }

    /// Get the last hash of the signing audit chain.
    pub fn signing_audit_last_hash(&self) -> Result<[u8; 32]> {
        let log = self.signing_audit.as_ref().ok_or(KeepError::Locked)?;
        Ok(log.last_hash())
    }

    /// Read a page of signing audit entries with metadata in a single decryption pass.
    pub fn signing_audit_read_page_with_metadata(
        &self,
        offset: usize,
        limit: usize,
        caller_filter: Option<&str>,
    ) -> Result<(Vec<SigningAuditEntry>, Vec<String>, usize)> {
        let (log, data_key) = self.signing_audit_with_key()?;
        log.read_page_with_metadata(&data_key, offset, limit, caller_filter)
    }

    /// Verify the integrity of the signing audit chain and return the entry count.
    pub fn signing_audit_verify_chain(&self) -> Result<(bool, usize)> {
        let (log, data_key) = self.signing_audit_with_key()?;
        log.verify_chain(&data_key)
    }

    fn signing_audit_with_key(&self) -> Result<(&SigningAuditLog, SecretKey)> {
        let log = self.signing_audit.as_ref().ok_or(KeepError::Locked)?;
        let data_key = self.get_data_key()?;
        Ok((log, data_key))
    }
}

fn is_valid_hex_pubkey(s: &str) -> bool {
    s.len() == 64 && s.chars().all(|c| c.is_ascii_hexdigit())
}

fn write_restricted(path: &Path, data: &[u8]) -> std::io::Result<()> {
    use std::io::Write;
    let mut opts = std::fs::OpenOptions::new();
    opts.write(true).create(true).truncate(true);
    #[cfg(unix)]
    {
        use std::os::unix::fs::OpenOptionsExt;
        opts.mode(0o600);
    }
    let mut file = opts.open(path)?;
    file.write_all(data)
}

/// Returns the default path to the Keep directory (~/.keep).
/// Override with the `KEEP_HOME` environment variable.
pub fn default_keep_path() -> Result<PathBuf> {
    match std::env::var("KEEP_HOME") {
        Ok(val) if !val.trim().is_empty() => {
            let path = PathBuf::from(&val);
            if path.is_absolute() {
                Ok(path)
            } else {
                Err(KeepError::InvalidInput(
                    "KEEP_HOME must be an absolute path".into(),
                ))
            }
        }
        _ => dirs::home_dir()
            .map(|p| p.join(".keep"))
            .ok_or(KeepError::HomeNotFound),
    }
}

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

    fn test_keep(path: &Path) -> Keep {
        Storage::create(path, "testpass", crypto::Argon2Params::TESTING).unwrap();
        let mut keep = Keep::open(path).unwrap();
        keep.unlock("testpass").unwrap();
        keep
    }

    #[test]
    fn rate_limit_trip_emits_audit_entry_on_next_unlock() {
        // The rate limiter trips after MAX_ATTEMPTS (5) failed unlocks. The
        // trip event must surface as a `RateLimitTripped` audit entry the
        // next time the operator successfully unlocks (#495).
        let dir = tempdir().unwrap();
        let path = dir.path().join("keep");

        Storage::create(&path, "right-password", crypto::Argon2Params::TESTING).unwrap();

        // Five failed attempts trips the limiter.
        for _ in 0..5 {
            let mut keep = Keep::open(&path).unwrap();
            let _ = keep.unlock("wrong-password");
        }

        // The sixth attempt would hit the back-off; wait it out by clearing
        // the active rate-limit counter (the trip event lives in a separate
        // file that record_success deliberately does NOT touch).
        crate::rate_limit::record_success(&path);

        let mut keep = Keep::open(&path).unwrap();
        keep.unlock("right-password").unwrap();

        let entries = keep.audit_read_all().unwrap();
        let trips: Vec<_> = entries
            .iter()
            .filter(|e| matches!(e.event_type, AuditEventType::RateLimitTripped))
            .collect();
        assert_eq!(trips.len(), 1, "expected one trip entry, got {trips:#?}");
        assert!(!trips[0].success, "trip entry must record success=false");
        assert!(
            trips[0]
                .reason
                .as_deref()
                .is_some_and(|r| r.contains("rate limit")),
            "trip entry must carry a descriptive reason, got {:?}",
            trips[0].reason
        );

        // Chronological order: RateLimitTripped precedes the VaultUnlock it
        // was discovered by, so the audit chain reflects the actual sequence
        // of lockout then recovery.
        let trip_idx = entries
            .iter()
            .position(|e| matches!(e.event_type, AuditEventType::RateLimitTripped))
            .unwrap();
        let unlock_idx = entries
            .iter()
            .rposition(|e| matches!(e.event_type, AuditEventType::VaultUnlock))
            .unwrap();
        assert!(trip_idx < unlock_idx);

        // Subsequent unlocks don't re-emit the same trip.
        keep.lock();
        let mut keep = Keep::open(&path).unwrap();
        keep.unlock("right-password").unwrap();
        let entries = keep.audit_read_all().unwrap();
        let trip_count = entries
            .iter()
            .filter(|e| matches!(e.event_type, AuditEventType::RateLimitTripped))
            .count();
        assert_eq!(
            trip_count, 1,
            "trip entry must not duplicate on later unlocks"
        );
    }

    #[test]
    fn test_keep_create_and_unlock() {
        let dir = tempdir().unwrap();
        let path = dir.path().join("keep");

        {
            let keep = Keep::create(&path, "password").unwrap();
            assert!(keep.is_unlocked());
        }

        {
            let mut keep = Keep::open(&path).unwrap();
            assert!(!keep.is_unlocked());
            keep.unlock("password").unwrap();
            assert!(keep.is_unlocked());
        }
    }

    #[test]
    fn test_keep_generate_key() {
        let dir = tempdir().unwrap();
        let path = dir.path().join("keep");

        let mut keep = test_keep(&path);
        let pubkey = keep.generate_key("test").unwrap();

        assert_eq!(keep.keyring().len(), 1);
        assert!(keep.keyring().get(&pubkey).is_some());
        assert!(keep.keyring().get_by_name("test").is_some());
    }

    #[test]
    fn test_keep_lock() {
        let dir = tempdir().unwrap();
        let path = dir.path().join("keep");

        let mut keep = test_keep(&path);
        keep.generate_key("test").unwrap();
        assert!(keep.is_unlocked());

        keep.lock();
        assert!(!keep.is_unlocked());
        assert_eq!(keep.keyring().len(), 0);
    }

    #[test]
    fn test_keep_primary_key() {
        let dir = tempdir().unwrap();
        let path = dir.path().join("keep");

        let mut keep = test_keep(&path);
        assert!(keep.get_primary_key().is_none());

        keep.generate_key("first").unwrap();
        let primary = keep.get_primary_key().unwrap();
        assert_eq!(primary.name, "first");
    }

    #[test]
    fn test_frost_generate_and_sign() {
        let dir = tempdir().unwrap();
        let path = dir.path().join("keep");

        let mut keep = test_keep(&path);

        let shares = keep.frost_generate(2, 3, "frost-test").unwrap();
        assert_eq!(shares.len(), 3);

        let group_pubkey = *shares[0].group_pubkey();

        let message = b"test message to sign with FROST";
        let signature = keep.frost_sign(&group_pubkey, message).unwrap();

        assert_eq!(signature.len(), 64);

        let stored_shares = keep.frost_list_shares().unwrap();
        assert_eq!(stored_shares.len(), 3);
    }

    #[test]
    fn test_frost_split_preserves_npub() {
        let dir = tempdir().unwrap();
        let path = dir.path().join("keep");

        let mut keep = test_keep(&path);

        let pubkey = keep.generate_key("to-split").unwrap();

        let shares = keep.frost_split("to-split", 2, 3).unwrap();
        assert_eq!(shares.len(), 3);

        let frost_pubkey = *shares[0].group_pubkey();
        assert_eq!(frost_pubkey, pubkey);

        let message = b"sign with split key";
        let signature = keep.frost_sign(&frost_pubkey, message).unwrap();
        assert_eq!(signature.len(), 64);
    }

    #[cfg(feature = "ed25519")]
    #[test]
    fn test_frost_ed25519_generate_sign_verify() {
        let dir = tempdir().unwrap();
        let path = dir.path().join("keep");
        let mut keep = test_keep(&path);

        let shares = keep.frost_generate_ed25519(2, 3, "release").unwrap();
        assert_eq!(shares.len(), 3);
        let group_pubkey = *shares[0].group_pubkey();

        let message = b"release artifact v1.0";
        let signature = keep.frost_sign_ed25519(&group_pubkey, message).unwrap();
        assert_eq!(signature.len(), 64);

        Keep::frost_verify_ed25519(&group_pubkey, message, &signature).unwrap();
        assert!(Keep::frost_verify_ed25519(&group_pubkey, b"tampered", &signature).is_err());

        // Shares persisted across reopen carry the Ed25519 ciphersuite tag and
        // still sign after the versioned-blob round-trip through storage.
        drop(keep);
        let mut keep = Keep::open(&path).unwrap();
        keep.unlock("testpass").unwrap();
        let sig2 = keep.frost_sign_ed25519(&group_pubkey, message).unwrap();
        Keep::frost_verify_ed25519(&group_pubkey, message, &sig2).unwrap();
    }

    #[cfg(feature = "ed25519")]
    #[test]
    fn test_frost_ed25519_export_import_sign() {
        let src_dir = tempdir().unwrap();
        let src_path = src_dir.path().join("keep");
        let mut src = test_keep(&src_path);

        let shares = src.frost_generate_ed25519(2, 3, "release").unwrap();
        let group_pubkey = *shares[0].group_pubkey();

        let exports: Vec<_> = shares
            .iter()
            .take(2)
            .map(|s| {
                let export = src
                    .frost_export_share(&group_pubkey, s.metadata.identifier, "transfer-pass")
                    .unwrap();
                assert_eq!(export.ciphersuite, crate::frost::Ciphersuite::Ed25519);
                export
            })
            .collect();

        let dst_dir = tempdir().unwrap();
        let dst_path = dst_dir.path().join("keep");
        let mut dst = test_keep(&dst_path);

        for (i, export) in exports.iter().enumerate() {
            dst.frost_import_share(export, "transfer-pass", &format!("imported-{i}"))
                .unwrap();
        }

        let message = b"exported then imported";
        let sig = dst.frost_sign_ed25519(&group_pubkey, message).unwrap();
        Keep::frost_verify_ed25519(&group_pubkey, message, &sig).unwrap();
    }

    #[cfg(feature = "ed25519")]
    #[test]
    fn test_frost_ed25519_data_key_rotation() {
        let dir = tempdir().unwrap();
        let path = dir.path().join("keep");
        let mut keep = test_keep(&path);

        let shares = keep.frost_generate_ed25519(2, 3, "release").unwrap();
        let group_pubkey = *shares[0].group_pubkey();

        // Rotation re-encrypts the inner key package under the ciphersuite AAD
        // and verifies it; an Ed25519 vault must rotate without failing.
        keep.rotate_data_key("testpass").unwrap();

        let message = b"after rotation";
        let sig = keep.frost_sign_ed25519(&group_pubkey, message).unwrap();
        Keep::frost_verify_ed25519(&group_pubkey, message, &sig).unwrap();
    }

    #[cfg(feature = "ed25519")]
    #[test]
    fn test_frost_ed25519_minisign_round_trip() {
        use crate::frost::ed25519::minisign::MinisignSignature;

        let dir = tempdir().unwrap();
        let path = dir.path().join("keep");
        let mut keep = test_keep(&path);

        let shares = keep.frost_generate_ed25519(2, 3, "release").unwrap();
        let group_pubkey = *shares[0].group_pubkey();

        let message = b"release artifact v2.0";
        let sig = keep
            .frost_sign_ed25519_minisign(
                &group_pubkey,
                message,
                "untrusted".into(),
                "trusted:abc".into(),
            )
            .unwrap();

        // Full struct verifies (file + global signatures).
        Keep::frost_verify_ed25519_minisign(&group_pubkey, message, &sig).unwrap();

        // Survives encode/parse round-trip.
        let encoded = sig.encode().unwrap();
        let parsed = MinisignSignature::parse(&encoded).unwrap();
        Keep::frost_verify_ed25519_minisign(&group_pubkey, message, &parsed).unwrap();

        // Tampered message rejected.
        assert!(Keep::frost_verify_ed25519_minisign(&group_pubkey, b"tampered", &parsed).is_err());

        // Tampered trusted comment breaks the global signature.
        let mut bad = MinisignSignature::parse(&encoded).unwrap();
        bad.trusted_comment = "trusted:evil".into();
        assert!(Keep::frost_verify_ed25519_minisign(&group_pubkey, message, &bad).is_err());

        // Wrong group public key fails the key-id check.
        let wrong = [0u8; 32];
        assert!(Keep::frost_verify_ed25519_minisign(&wrong, message, &parsed).is_err());
    }

    #[cfg(feature = "ed25519")]
    #[test]
    fn test_frost_ed25519_minisign_external_binary() {
        use crate::frost::ed25519::minisign::MinisignPublicKey;
        use std::process::Command;

        // Prefer the C minisign binary; fall back to rsign2 (rsign), which is
        // byte-format compatible with minisign. Skip if neither is installed.
        let verifier = if Command::new("minisign").arg("-v").output().is_ok() {
            "minisign"
        } else if Command::new("rsign").arg("--help").output().is_ok() {
            "rsign"
        } else {
            eprintln!("no minisign/rsign binary installed; skipping external cross-check");
            return;
        };

        let dir = tempdir().unwrap();
        let path = dir.path().join("keep");
        let mut keep = test_keep(&path);

        let shares = keep.frost_generate_ed25519(2, 3, "release").unwrap();
        let group_pubkey = *shares[0].group_pubkey();

        let data_path = dir.path().join("artifact.bin");
        std::fs::write(&data_path, b"external minisign cross-check payload").unwrap();
        let message = std::fs::read(&data_path).unwrap();

        let sig = keep
            .frost_sign_ed25519_minisign(
                &group_pubkey,
                &message,
                "keep test".into(),
                "timestamp:0\tfile:artifact.bin".into(),
            )
            .unwrap();
        let sig_path = dir.path().join("artifact.bin.minisig");
        std::fs::write(&sig_path, sig.encode().unwrap()).unwrap();

        let pk = MinisignPublicKey::from_group_pubkey(&group_pubkey, "keep test".into());
        let pk_path = dir.path().join("keep.pub");
        std::fs::write(&pk_path, pk.encode().unwrap()).unwrap();

        let output = match verifier {
            "minisign" => Command::new("minisign")
                .arg("-V")
                .arg("-p")
                .arg(&pk_path)
                .arg("-m")
                .arg(&data_path)
                .output()
                .expect("run minisign -V"),
            _ => Command::new("rsign")
                .arg("verify")
                .arg("-p")
                .arg(&pk_path)
                .arg("-x")
                .arg(&sig_path)
                .arg(&data_path)
                .output()
                .expect("run rsign verify"),
        };
        assert!(
            output.status.success(),
            "external verify ({verifier}) failed: {}{}",
            String::from_utf8_lossy(&output.stdout),
            String::from_utf8_lossy(&output.stderr),
        );
    }

    #[test]
    fn test_frost_insufficient_shares_fails() {
        use crate::frost::{SigningSession, ThresholdConfig, TrustedDealer};

        let config = ThresholdConfig::two_of_three();
        let dealer = TrustedDealer::new(config);
        let (shares, _) = dealer.generate("test").unwrap();

        let message = b"test".to_vec();
        let kp0 = shares[0].key_package().unwrap();

        let mut session = SigningSession::new(message, 2).unwrap();
        session.generate_commitment(&kp0).unwrap();

        assert_eq!(session.commitments_needed(), 1);
        assert!(!session.is_complete());
    }

    #[test]
    fn test_keep_rotate_password() {
        let dir = tempdir().unwrap();
        let path = dir.path().join("keep");

        {
            let mut keep = test_keep(&path);
            keep.generate_key("rotatetest").unwrap();
        }

        {
            let mut keep = Keep::open(&path).unwrap();
            keep.unlock("testpass").unwrap();
            keep.rotate_password("testpass", "newpass1").unwrap();
        }

        {
            let mut keep = Keep::open(&path).unwrap();
            assert!(keep.unlock("testpass").is_err());
        }

        {
            let mut keep = Keep::open(&path).unwrap();
            keep.unlock("newpass1").unwrap();
            assert!(keep.keyring().get_by_name("rotatetest").is_some());
        }
    }

    #[test]
    fn test_is_valid_hex_pubkey() {
        let valid = "a".repeat(64);
        assert!(is_valid_hex_pubkey(&valid));

        let mixed_hex = "0123456789abcdef".repeat(4);
        assert!(is_valid_hex_pubkey(&mixed_hex));

        // is_ascii_hexdigit accepts A-F; set_active_share_key normalizes
        // to lowercase before persisting.
        let upper = "A".repeat(64);
        assert!(is_valid_hex_pubkey(&upper));

        assert!(!is_valid_hex_pubkey(&"a".repeat(63)));
        assert!(!is_valid_hex_pubkey(&"a".repeat(65)));
        assert!(!is_valid_hex_pubkey(""));
        assert!(!is_valid_hex_pubkey(
            "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz"
        ));
    }

    #[test]
    fn test_keep_rotate_data_key() {
        let dir = tempdir().unwrap();
        let path = dir.path().join("keep");

        let pubkey;
        {
            let mut keep = test_keep(&path);
            pubkey = keep.generate_key("dektest").unwrap();
        }

        {
            let mut keep = Keep::open(&path).unwrap();
            keep.unlock("testpass").unwrap();
            keep.rotate_data_key("testpass").unwrap();
            assert!(keep.keyring().get(&pubkey).is_some());
        }

        {
            let mut keep = Keep::open(&path).unwrap();
            keep.unlock("testpass").unwrap();
            let slot = keep.keyring().get(&pubkey).unwrap();
            assert_eq!(slot.name, "dektest");
        }
    }

    // === #566: audit-log entries for rotation security operations ===

    /// `Keep::rotate_password` MUST emit a `PasswordRotate` audit entry on
    /// success. Without this, security-sensitive password rotations leave no
    /// observable trace for the operator or for post-incident review.
    #[test]
    fn rotate_password_emits_success_audit_entry() {
        let dir = tempdir().unwrap();
        let path = dir.path().join("keep");
        {
            let mut keep = test_keep(&path);
            keep.generate_key("audited").unwrap();
            keep.rotate_password("testpass", "newpass1").unwrap();
            let entries = keep.audit_read_all().unwrap();
            assert!(
                entries
                    .iter()
                    .any(|e| e.event_type == AuditEventType::PasswordRotate),
                "PasswordRotate entry missing from audit log: {:?}",
                entries.iter().map(|e| e.event_type).collect::<Vec<_>>()
            );
        }
        // Re-open with the NEW password to confirm the audit log survived the
        // header rotation and still chain-verifies.
        let mut keep = Keep::open(&path).unwrap();
        keep.unlock("newpass1").unwrap();
        keep.audit_verify_chain().unwrap();
        let entries = keep.audit_read_all().unwrap();
        assert!(entries
            .iter()
            .any(|e| e.event_type == AuditEventType::PasswordRotate));
    }

    /// `Keep::rotate_password` MUST emit a `PasswordRotateFailed` audit entry
    /// when the call is rejected, so failed attacker attempts are observable.
    /// Failed attempts on an already-locked vault cannot be recorded (data
    /// key unavailable); this test exercises the unlocked path and uses an
    /// invalid new password as the failure trigger because Storage's
    /// `rotate_password` short-circuits the wrong-old-password check when
    /// the vault is already unlocked (which is the path that admits audit
    /// writes), while `validate_new_password` is enforced unconditionally.
    #[test]
    fn rotate_password_emits_failure_audit_entry_when_unlocked() {
        let dir = tempdir().unwrap();
        let path = dir.path().join("keep");
        let mut keep = test_keep(&path);
        keep.generate_key("audited").unwrap();

        let pre = keep.audit_read_all().unwrap().len();

        // Empty new password: validate_new_password rejects.
        assert!(keep.rotate_password("testpass", "").is_err());
        let after_empty = keep.audit_read_all().unwrap();
        assert!(
            after_empty.len() > pre,
            "audit log should grow on empty-new-password rejection"
        );
        let failure = after_empty
            .iter()
            .find(|e| e.event_type == AuditEventType::PasswordRotateFailed)
            .expect("PasswordRotateFailed entry missing after empty-new-password rejection");
        assert!(
            !failure.success,
            "PasswordRotateFailed entry must be marked success=false"
        );
        assert!(
            failure.reason.is_some(),
            "PasswordRotateFailed entry must record a failure reason"
        );

        // Too-short new password: same rejection.
        let pre2 = keep.audit_read_all().unwrap().len();
        assert!(keep.rotate_password("testpass", "a").is_err());
        let entries = keep.audit_read_all().unwrap();
        assert!(
            entries.len() > pre2,
            "audit log should grow on too-short-new-password rejection"
        );
        // The original password still unlocks: failure paths don't corrupt
        // the header. Drop the first handle before reopening so the vault
        // file lock is released.
        drop(keep);
        let mut reopened = Keep::open(&path).unwrap();
        reopened.unlock("testpass").unwrap();
    }

    /// `Keep::rotate_data_key` MUST emit a `DataKeyRotate` audit entry on
    /// success. The entry's payload is encrypted under the NEW data key (the
    /// log gets re-encrypted as part of rotation); this test confirms the
    /// entry is readable after rotation and the chain still verifies.
    #[test]
    fn rotate_data_key_emits_success_audit_entry() {
        let dir = tempdir().unwrap();
        let path = dir.path().join("keep");
        {
            let mut keep = test_keep(&path);
            keep.generate_key("dek-audit").unwrap();
            keep.rotate_data_key("testpass").unwrap();
            let entries = keep.audit_read_all().unwrap();
            assert!(
                entries
                    .iter()
                    .any(|e| e.event_type == AuditEventType::DataKeyRotate),
                "DataKeyRotate entry missing from audit log: {:?}",
                entries.iter().map(|e| e.event_type).collect::<Vec<_>>()
            );
            // The audit log was re-encrypted under the new data key during
            // rotation; the chain over both pre- and post-rotation entries
            // must remain valid.
            keep.audit_verify_chain().unwrap();
        }
        // Confirm persistence: re-open and the entry is still there.
        let mut keep = Keep::open(&path).unwrap();
        keep.unlock("testpass").unwrap();
        let entries = keep.audit_read_all().unwrap();
        assert!(entries
            .iter()
            .any(|e| e.event_type == AuditEventType::DataKeyRotate));
    }

    // === #581 / #579 / #580: rotation hardening ===

    /// `Keep::rotate_password` MUST reject a wrong `old_password` even when the
    /// vault is already unlocked (#581). Without this, anyone with access to
    /// an unlocked Keep could re-wrap the data key without proving knowledge
    /// of the prior credential.
    #[test]
    fn rotate_password_rejects_wrong_old_password_when_already_unlocked() {
        let dir = tempdir().unwrap();
        let path = dir.path().join("keep");
        let mut keep = test_keep(&path);

        // Vault is unlocked. The rotation should still refuse without the
        // correct old password.
        let err = keep
            .rotate_password("NOT_THE_OLD_PASSWORD", "newpass1")
            .expect_err("wrong old password must be refused even when unlocked");
        let _ = err; // shape varies, pin only on error path

        // The original password still unlocks: failure paths do not corrupt
        // the header.
        drop(keep);
        let mut reopened = Keep::open(&path).unwrap();
        reopened.unlock("testpass").unwrap();
    }

    /// Same gap on `rotate_data_key`: wrong password rejected even when
    /// already unlocked (#581).
    #[test]
    fn rotate_data_key_rejects_wrong_password_when_already_unlocked() {
        let dir = tempdir().unwrap();
        let path = dir.path().join("keep");
        let mut keep = test_keep(&path);

        let err = keep
            .rotate_data_key("WRONG_PASSWORD")
            .expect_err("wrong password must be refused even when unlocked");
        let _ = err;

        drop(keep);
        let mut reopened = Keep::open(&path).unwrap();
        reopened.unlock("testpass").unwrap();
    }

    /// `Keep::rotate_password` MUST emit a `PasswordRotateFailed` audit entry
    /// when the wrong-old-password gate (#581) fires on an unlocked vault.
    /// Without this, an attacker's failed rotation attempts on a hijacked
    /// unlocked Keep would be unobservable.
    #[test]
    fn rotate_password_wrong_old_password_emits_failure_audit_entry() {
        let dir = tempdir().unwrap();
        let path = dir.path().join("keep");
        let mut keep = test_keep(&path);

        let pre = keep.audit_read_all().unwrap().len();
        assert!(keep
            .rotate_password("WRONG_OLD_PASSWORD", "newpass1")
            .is_err());
        let entries = keep.audit_read_all().unwrap();
        assert!(
            entries.len() > pre,
            "audit log must grow on a rejected rotation"
        );
        assert!(
            entries
                .iter()
                .any(|e| e.event_type == AuditEventType::PasswordRotateFailed),
            "PasswordRotateFailed entry missing after wrong-old-password rejection"
        );
    }

    #[test]
    fn test_default_keep_path_from_env() {
        let abs_path = if cfg!(windows) {
            "C:\\tmp\\my-keep"
        } else {
            "/tmp/my-keep"
        };
        temp_env::with_var("KEEP_HOME", Some(abs_path), || {
            let p = default_keep_path().unwrap();
            assert_eq!(p, PathBuf::from(abs_path));
        });
    }

    #[test]
    fn test_default_keep_path_relative_env_rejected() {
        temp_env::with_var("KEEP_HOME", Some("relative/path"), || {
            let result = default_keep_path();
            assert!(result.is_err());
        });
    }

    #[test]
    fn test_default_keep_path_empty_env_falls_back() {
        temp_env::with_var("KEEP_HOME", Some(""), || {
            let p = default_keep_path().unwrap();
            let expected = dirs::home_dir().unwrap().join(".keep");
            assert_eq!(p, expected);
        });
    }

    #[test]
    fn test_default_keep_path_blank_env_falls_back() {
        temp_env::with_var("KEEP_HOME", Some("   "), || {
            let p = default_keep_path().unwrap();
            let expected = dirs::home_dir().unwrap().join(".keep");
            assert_eq!(p, expected);
        });
    }

    /// Run a software DKG group in-process, persist every finalized share via
    /// `frost_store_dkg_share`, and confirm the shares reload with intact
    /// metadata and can be exported. Covers the finalize -> SharePackage ->
    /// encrypt -> store -> reload bridge that the DKG unit tests do not touch.
    #[test]
    fn test_frost_store_dkg_share_roundtrip() {
        use crate::frost::dkg::{SoftwareDkgSession, SoftwareRound1Wire, SoftwareRound2Wire};

        let (threshold, participants): (u16, u16) = (2, 3);

        let mut sessions: Vec<SoftwareDkgSession> = (1..=participants)
            .map(|idx| SoftwareDkgSession::init(threshold, participants, idx).unwrap())
            .collect();

        let round1_wires: Vec<SoftwareRound1Wire> =
            sessions.iter_mut().map(|s| s.round1().unwrap()).collect();
        for (i, session) in sessions.iter_mut().enumerate() {
            for (j, wire) in round1_wires.iter().enumerate() {
                if i != j {
                    session.round1_peer(wire).unwrap();
                }
            }
        }

        let mut per_session_round2: Vec<Vec<(u16, SoftwareRound2Wire)>> =
            sessions.iter_mut().map(|s| s.round2().unwrap()).collect();
        for (sender_i, wires) in per_session_round2.drain(..).enumerate() {
            for (recipient_index, wire) in wires {
                let recipient_i = (recipient_index - 1) as usize;
                assert_ne!(recipient_i, sender_i);
                sessions[recipient_i].receive_share(&wire).unwrap();
            }
        }

        let results: Vec<_> = sessions.iter_mut().map(|s| s.finalize().unwrap()).collect();
        let group_pubkey = results[0].group_pubkey;

        let dir = tempdir().unwrap();
        let path = dir.path().join("keep");
        let mut keep = test_keep(&path);

        for r in &results {
            keep.frost_store_dkg_share(r, threshold, participants, "dkg-group")
                .unwrap();
        }

        let shares = keep.frost_list_shares().unwrap();
        assert_eq!(shares.len(), participants as usize);
        for share in &shares {
            assert_eq!(share.metadata.group_pubkey, group_pubkey);
            assert_eq!(share.metadata.threshold, threshold);
            assert_eq!(share.metadata.total_shares, participants);
            assert_eq!(share.metadata.name, "dkg-group");
        }
        let indices: std::collections::BTreeSet<u16> =
            shares.iter().map(|s| s.metadata.identifier).collect();
        assert_eq!(indices, (1..=participants).collect());

        // A stored share decrypts and exports under a passphrase.
        let export = keep
            .frost_export_share(&group_pubkey, results[0].our_index, "export-pass")
            .unwrap();
        drop(export);

        // A locked vault refuses to store.
        keep.lock();
        assert!(matches!(
            keep.frost_store_dkg_share(&results[0], threshold, participants, "dkg-group"),
            Err(KeepError::Locked)
        ));
    }
}