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
// SPDX-FileCopyrightText: © 2026 PrivKey LLC
// SPDX-License-Identifier: MIT

//! Tamper-evident audit logging with hash chain integrity.
use std::fs::{File, OpenOptions};
use std::io::{BufRead, BufReader, Write};
#[cfg(unix)]
use std::os::unix::fs::OpenOptionsExt;
use std::path::{Path, PathBuf};

use base64::{engine::general_purpose::STANDARD, Engine};
use serde::{Deserialize, Serialize};
use subtle::ConstantTimeEq;

use crate::crypto::{self, SecretKey};
use crate::error::{Result, StorageError};

fn hash_optional_str(data: &mut Vec<u8>, value: Option<&str>) {
    match value {
        Some(s) => {
            data.push(1);
            let len = u32::try_from(s.len()).expect("string too long for hash");
            data.extend_from_slice(&len.to_le_bytes());
            data.extend_from_slice(s.as_bytes());
        }
        None => data.push(0),
    }
}

/// Type of audit event.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[repr(u8)]
pub enum AuditEventType {
    /// Key generated.
    KeyGenerate = 0,
    /// Key imported.
    KeyImport = 1,
    /// Key exported.
    KeyExport = 2,
    /// Key deleted.
    KeyDelete = 3,
    /// Signing succeeded.
    Sign = 4,
    /// Signing failed.
    SignFailed = 5,
    /// FROST key generated.
    FrostGenerate = 6,
    /// Key split into FROST shares.
    FrostSplit = 7,
    /// FROST signing succeeded.
    FrostSign = 8,
    /// FROST signing failed.
    FrostSignFailed = 9,
    /// FROST session started.
    FrostSessionStart = 10,
    /// FROST session completed.
    FrostSessionComplete = 11,
    /// FROST session failed.
    FrostSessionFailed = 12,
    /// FROST share imported.
    FrostShareImport = 13,
    /// FROST share exported.
    FrostShareExport = 14,
    /// FROST share deleted.
    FrostShareDelete = 15,
    /// Authentication failed.
    AuthFailed = 16,
    /// Vault unlocked.
    VaultUnlock = 17,
    /// Vault locked.
    VaultLock = 18,
    /// FROST shares refreshed.
    FrostShareRefresh = 19,
    /// Rate limiter tripped on a failed unlock attempt. Recorded at unlock
    /// time on the NEXT successful unlock, since the data key needed to
    /// encrypt audit entries is not available while the vault is locked.
    RateLimitTripped = 20,
    /// Vault password rotated successfully.
    PasswordRotate = 21,
    /// Vault password rotation attempted but rejected (wrong old password,
    /// invalid new password, or mid-rotation failure). Recorded only when
    /// the vault was unlocked at attempt time; failed attempts on a locked
    /// vault cannot be persisted because the audit log needs the data key.
    PasswordRotateFailed = 22,
    /// Data encryption key rotated successfully.
    DataKeyRotate = 23,
    /// Data-key rotation attempted but rejected (wrong password or mid-
    /// rotation failure). Same locked-vault caveat as `PasswordRotateFailed`.
    DataKeyRotateFailed = 24,
    /// Arbitrary secret (password, API token, note) created or overwritten.
    SecretCreate = 25,
    /// Arbitrary secret deleted.
    SecretDelete = 26,
    /// Threshold-sealed secret value revealed via an OPRF quorum unseal. The most
    /// sensitive read in the store (it hands out the plaintext), audited like
    /// `KeyExport`.
    SecretReveal = 27,
}

impl std::fmt::Display for AuditEventType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::KeyGenerate => write!(f, "key_generate"),
            Self::KeyImport => write!(f, "key_import"),
            Self::KeyExport => write!(f, "key_export"),
            Self::KeyDelete => write!(f, "key_delete"),
            Self::Sign => write!(f, "sign"),
            Self::SignFailed => write!(f, "sign_failed"),
            Self::FrostGenerate => write!(f, "frost_generate"),
            Self::FrostSplit => write!(f, "frost_split"),
            Self::FrostSign => write!(f, "frost_sign"),
            Self::FrostSignFailed => write!(f, "frost_sign_failed"),
            Self::FrostSessionStart => write!(f, "frost_session_start"),
            Self::FrostSessionComplete => write!(f, "frost_session_complete"),
            Self::FrostSessionFailed => write!(f, "frost_session_failed"),
            Self::FrostShareImport => write!(f, "frost_share_import"),
            Self::FrostShareExport => write!(f, "frost_share_export"),
            Self::FrostShareDelete => write!(f, "frost_share_delete"),
            Self::AuthFailed => write!(f, "auth_failed"),
            Self::VaultUnlock => write!(f, "vault_unlock"),
            Self::VaultLock => write!(f, "vault_lock"),
            Self::FrostShareRefresh => write!(f, "frost_share_refresh"),
            Self::RateLimitTripped => write!(f, "rate_limit_tripped"),
            Self::PasswordRotate => write!(f, "password_rotate"),
            Self::PasswordRotateFailed => write!(f, "password_rotate_failed"),
            Self::DataKeyRotate => write!(f, "data_key_rotate"),
            Self::DataKeyRotateFailed => write!(f, "data_key_rotate_failed"),
            Self::SecretCreate => write!(f, "secret_create"),
            Self::SecretDelete => write!(f, "secret_delete"),
            Self::SecretReveal => write!(f, "secret_reveal"),
        }
    }
}

/// A single audit log entry with hash chain linkage.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuditEntry {
    /// Unix timestamp.
    pub timestamp: i64,
    /// Event type.
    pub event_type: AuditEventType,
    /// Public key involved.
    pub pubkey: Option<String>,
    /// Key type (e.g. "nostr").
    pub key_type: Option<String>,
    /// Hash of the signed message.
    pub message_hash: Option<String>,
    /// FROST group public key.
    pub group_pubkey: Option<String>,
    /// FROST participant identifiers.
    pub participants: Option<Vec<u16>>,
    /// FROST threshold.
    pub threshold: Option<u16>,
    /// Whether the operation succeeded.
    pub success: bool,
    /// Failure reason.
    pub reason: Option<String>,
    /// Previous entry hash.
    pub prev_hash: [u8; 32],
    /// This entry's hash.
    pub hash: [u8; 32],
}

impl AuditEntry {
    /// Create a new entry with the given event type and previous hash.
    pub fn new(event_type: AuditEventType, prev_hash: [u8; 32]) -> Self {
        Self {
            timestamp: chrono::Utc::now().timestamp(),
            event_type,
            pubkey: None,
            key_type: None,
            message_hash: None,
            group_pubkey: None,
            participants: None,
            threshold: None,
            success: true,
            reason: None,
            prev_hash,
            hash: [0u8; 32],
        }
    }

    /// Set the public key.
    pub fn with_pubkey(mut self, pubkey: &[u8; 32]) -> Self {
        self.pubkey = Some(hex::encode(pubkey));
        self
    }

    /// Set the key type.
    pub fn with_key_type(mut self, key_type: &str) -> Self {
        self.key_type = Some(key_type.to_string());
        self
    }

    /// Set the message hash.
    pub fn with_message_hash(mut self, message: &[u8]) -> Self {
        self.message_hash = Some(hex::encode(crypto::blake2b_256(message)));
        self
    }

    /// Set the FROST group public key.
    pub fn with_group(mut self, group_pubkey: &[u8; 32]) -> Self {
        self.group_pubkey = Some(hex::encode(group_pubkey));
        self
    }

    /// Set the FROST participant identifiers.
    pub fn with_participants(mut self, participants: Vec<u16>) -> Self {
        self.participants = Some(participants);
        self
    }

    /// Set the FROST threshold.
    pub fn with_threshold(mut self, threshold: u16) -> Self {
        self.threshold = Some(threshold);
        self
    }

    /// Set whether the operation succeeded.
    pub fn with_success(mut self, success: bool) -> Self {
        self.success = success;
        self
    }

    /// Set the failure reason.
    pub fn with_reason(mut self, reason: &str) -> Self {
        self.reason = Some(reason.to_string());
        self
    }

    /// Compute and set this entry's hash.
    pub fn finalize(mut self) -> Self {
        self.hash = self.compute_hash();
        self
    }

    fn compute_hash(&self) -> [u8; 32] {
        let mut data = Vec::new();
        data.extend_from_slice(&self.timestamp.to_le_bytes());
        data.extend_from_slice(&(self.event_type as u8).to_le_bytes());
        hash_optional_str(&mut data, self.pubkey.as_deref());
        hash_optional_str(&mut data, self.key_type.as_deref());
        hash_optional_str(&mut data, self.message_hash.as_deref());
        hash_optional_str(&mut data, self.group_pubkey.as_deref());
        if let Some(ref p) = self.participants {
            data.push(1);
            let len = u32::try_from(p.len()).expect("participants too long for hash");
            data.extend_from_slice(&len.to_le_bytes());
            for id in p {
                data.extend_from_slice(&id.to_le_bytes());
            }
        } else {
            data.push(0);
        }
        if let Some(t) = self.threshold {
            data.push(1);
            data.extend_from_slice(&t.to_le_bytes());
        } else {
            data.push(0);
        }
        data.push(self.success as u8);
        hash_optional_str(&mut data, self.reason.as_deref());
        data.extend_from_slice(&self.prev_hash);
        crypto::blake2b_256(&data)
    }

    /// Verify this entry's hash chain linkage.
    pub fn verify(&self, prev_hash: &[u8; 32]) -> bool {
        let prev_hash_match = self.prev_hash.ct_eq(prev_hash);
        let hash_match = self.hash.ct_eq(&self.compute_hash());
        (prev_hash_match & hash_match).into()
    }
}

/// Automatic retention policy.
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub struct RetentionPolicy {
    /// Maximum number of entries to keep.
    pub max_entries: Option<usize>,
    /// Maximum age of entries in days.
    pub max_age_days: Option<u32>,
}

impl Default for RetentionPolicy {
    fn default() -> Self {
        Self {
            max_entries: Some(10000),
            max_age_days: Some(365),
        }
    }
}

/// Encrypted audit log with hash chain integrity.
pub struct AuditLog {
    path: PathBuf,
    last_hash: [u8; 32],
    retention: RetentionPolicy,
}

impl AuditLog {
    /// Open or create an audit log at the given path.
    pub fn open(path: &Path, data_key: &SecretKey) -> Result<Self> {
        let audit_path = path.join("audit.log");
        let last_hash = if audit_path.exists() {
            Self::read_last_hash(&audit_path, data_key)?
        } else {
            [0u8; 32]
        };

        Ok(Self {
            path: audit_path,
            last_hash,
            retention: RetentionPolicy::default(),
        })
    }

    /// Set the retention policy.
    pub fn set_retention(&mut self, policy: RetentionPolicy) {
        self.retention = policy;
    }

    /// Log an audit entry.
    pub fn log(&mut self, mut entry: AuditEntry, data_key: &SecretKey) -> Result<()> {
        entry.prev_hash = self.last_hash;
        entry.hash = entry.compute_hash();

        let serialized = serde_json::to_vec(&entry)
            .map_err(|e| StorageError::serialization(format!("audit entry: {e}")))?;

        let encrypted = crypto::encrypt(&serialized, data_key)?;
        let line = format!("{}\n", STANDARD.encode(encrypted.to_bytes()));

        let mut opts = OpenOptions::new();
        opts.create(true).append(true);
        #[cfg(unix)]
        opts.mode(0o600);
        let mut file = opts.open(&self.path)?;
        file.write_all(line.as_bytes())?;
        file.sync_all()?;

        self.last_hash = entry.hash;
        Ok(())
    }

    /// Read all entries.
    pub fn read_all(&self, data_key: &SecretKey) -> Result<Vec<AuditEntry>> {
        if !self.path.exists() {
            return Ok(Vec::new());
        }
        Self::read_entries(&self.path, data_key)
    }

    /// Verify the hash chain integrity.
    pub fn verify_chain(&self, data_key: &SecretKey) -> Result<bool> {
        let entries = self.read_all(data_key)?;
        let mut prev_hash = [0u8; 32];

        for entry in entries {
            if !entry.verify(&prev_hash) {
                return Ok(false);
            }
            prev_hash = entry.hash;
        }

        Ok(true)
    }

    /// Apply the retention policy, returning the number of entries removed.
    pub fn apply_retention(&mut self, data_key: &SecretKey) -> Result<usize> {
        let entries = self.read_all(data_key)?;
        let original_count = entries.len();
        let now = chrono::Utc::now().timestamp();
        let max_age_secs = self.retention.max_age_days.map(|d| i64::from(d) * 86400);

        let mut filtered: Vec<_> = entries
            .into_iter()
            .filter(|e| max_age_secs.is_none_or(|max| now.saturating_sub(e.timestamp) <= max))
            .collect();

        if let Some(max) = self.retention.max_entries {
            if filtered.len() > max {
                filtered = filtered.split_off(filtered.len() - max);
            }
        }

        let removed = original_count - filtered.len();
        if removed > 0 {
            self.rewrite(&filtered, data_key)?;
        }

        Ok(removed)
    }

    /// Export the log as JSON.
    pub fn export(&self, data_key: &SecretKey) -> Result<String> {
        let entries = self.read_all(data_key)?;
        serde_json::to_string_pretty(&entries)
            .map_err(|e| StorageError::serialization(format!("export audit log: {e}")).into())
    }

    fn read_last_hash(path: &Path, data_key: &SecretKey) -> Result<[u8; 32]> {
        let entries = Self::read_entries(path, data_key)?;
        Ok(entries.last().map_or([0u8; 32], |e| e.hash))
    }

    fn read_entries(path: &Path, data_key: &SecretKey) -> Result<Vec<AuditEntry>> {
        const MAX_ENTRIES: usize = 100_000;

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

        for (line_num, line) in reader.lines().enumerate() {
            if entries.len() >= MAX_ENTRIES {
                return Err(StorageError::io(format!(
                    "audit log exceeds maximum of {MAX_ENTRIES} entries"
                ))
                .into());
            }
            let line = line?;
            if line.is_empty() {
                continue;
            }
            let entry = Self::decrypt_line(&line, data_key).map_err(|e| {
                StorageError::corrupted(format!("audit log at line {}: {}", line_num + 1, e))
            })?;
            entries.push(entry);
        }

        Ok(entries)
    }

    fn decrypt_line(line: &str, data_key: &SecretKey) -> Result<AuditEntry> {
        let bytes = STANDARD
            .decode(line)
            .map_err(|e| StorageError::invalid_format(format!("audit line: {e}")))?;

        let encrypted = crypto::EncryptedData::from_bytes(&bytes)?;
        let decrypted = crypto::decrypt(&encrypted, data_key)?;

        serde_json::from_slice(&decrypted.as_slice()?)
            .map_err(|e| StorageError::invalid_format(format!("audit entry: {e}")).into())
    }

    fn rewrite(&mut self, entries: &[AuditEntry], data_key: &SecretKey) -> Result<()> {
        let temp_path = self.path.with_extension("log.tmp");
        let backup_path = self.path.with_extension("log.bak");

        let final_hash = match self.write_entries_to_temp(&temp_path, entries, data_key) {
            Ok(hash) => hash,
            Err(e) => {
                let _ = std::fs::remove_file(&temp_path);
                return Err(e);
            }
        };

        if self.path.exists() {
            if let Err(e) = std::fs::rename(&self.path, &backup_path) {
                let _ = std::fs::remove_file(&temp_path);
                return Err(StorageError::io(format!("backup existing audit log: {e}")).into());
            }
        }

        if let Err(e) = std::fs::rename(&temp_path, &self.path) {
            if backup_path.exists() {
                let _ = std::fs::rename(&backup_path, &self.path);
            }
            let _ = std::fs::remove_file(&temp_path);
            return Err(StorageError::io(format!("replace audit log: {e}")).into());
        }

        let _ = std::fs::remove_file(&backup_path);
        self.last_hash = final_hash;
        Ok(())
    }

    fn write_entries_to_temp(
        &self,
        temp_path: &Path,
        entries: &[AuditEntry],
        data_key: &SecretKey,
    ) -> Result<[u8; 32]> {
        let mut opts = OpenOptions::new();
        opts.write(true).create(true).truncate(true);
        #[cfg(unix)]
        opts.mode(0o600);
        let mut file = opts.open(temp_path)?;

        let mut prev_hash = [0u8; 32];
        for entry in entries {
            let mut entry = entry.clone();
            entry.prev_hash = prev_hash;
            entry.hash = entry.compute_hash();

            let serialized = serde_json::to_vec(&entry)
                .map_err(|e| StorageError::serialization(e.to_string()))?;

            let encrypted = crypto::encrypt(&serialized, data_key)?;
            let line = format!("{}\n", STANDARD.encode(encrypted.to_bytes()));
            file.write_all(line.as_bytes())?;
            prev_hash = entry.hash;
        }

        file.sync_all()?;
        Ok(prev_hash)
    }

    /// Get the last entry's hash.
    pub fn last_hash(&self) -> [u8; 32] {
        self.last_hash
    }

    /// Re-encrypt the entire log with a new data key.
    pub fn reencrypt(&mut self, old_key: &SecretKey, new_key: &SecretKey) -> Result<()> {
        if !self.path.exists() {
            return Ok(());
        }
        let entries = Self::read_entries(&self.path, old_key)?;
        if entries.is_empty() {
            return Ok(());
        }
        self.rewrite(&entries, new_key)
    }
}

/// NIP-46 signing request type.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[repr(u8)]
pub enum SigningRequestType {
    /// Client connection.
    Connect = 0,
    /// Public key retrieval.
    GetPublicKey = 1,
    /// Event signing.
    SignEvent = 2,
    /// NIP-04 encryption.
    Nip04Encrypt = 3,
    /// NIP-04 decryption.
    Nip04Decrypt = 4,
    /// NIP-44 encryption.
    Nip44Encrypt = 5,
    /// NIP-44 decryption.
    Nip44Decrypt = 6,
    /// Client disconnection.
    Disconnect = 7,
    /// Kill switch toggled.
    KillSwitch = 8,
}

impl std::fmt::Display for SigningRequestType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Connect => write!(f, "connect"),
            Self::GetPublicKey => write!(f, "get_public_key"),
            Self::SignEvent => write!(f, "sign_event"),
            Self::Nip04Encrypt => write!(f, "nip04_encrypt"),
            Self::Nip04Decrypt => write!(f, "nip04_decrypt"),
            Self::Nip44Encrypt => write!(f, "nip44_encrypt"),
            Self::Nip44Decrypt => write!(f, "nip44_decrypt"),
            Self::Disconnect => write!(f, "disconnect"),
            Self::KillSwitch => write!(f, "kill_switch"),
        }
    }
}

/// Decision made on a signing request.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[repr(u8)]
pub enum SigningDecision {
    /// Approved.
    Approved = 0,
    /// Denied.
    Denied = 1,
}

impl std::fmt::Display for SigningDecision {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Approved => write!(f, "approved"),
            Self::Denied => write!(f, "denied"),
        }
    }
}

/// A single signing audit log entry with hash chain linkage.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SigningAuditEntry {
    /// Unix timestamp.
    pub timestamp: i64,
    /// Request type.
    pub request_type: SigningRequestType,
    /// Decision (approved/denied).
    pub decision: SigningDecision,
    /// Whether decided by policy (true) or user (false).
    pub was_automatic: bool,
    /// Hex public key of the requesting app.
    pub caller: String,
    /// Human-readable caller name.
    pub caller_name: Option<String>,
    /// Nostr event kind.
    pub event_kind: Option<u32>,
    /// Reason for the decision.
    pub reason: Option<String>,
    /// Previous entry hash.
    pub prev_hash: [u8; 32],
    /// This entry's hash.
    pub hash: [u8; 32],
}

impl SigningAuditEntry {
    /// Create a new signing audit entry.
    pub fn new(
        request_type: SigningRequestType,
        decision: SigningDecision,
        was_automatic: bool,
        caller: String,
        prev_hash: [u8; 32],
    ) -> Self {
        Self {
            timestamp: chrono::Utc::now().timestamp(),
            request_type,
            decision,
            was_automatic,
            caller,
            caller_name: None,
            event_kind: None,
            reason: None,
            prev_hash,
            hash: [0u8; 32],
        }
    }

    /// Set the caller name.
    pub fn with_caller_name(mut self, name: impl Into<String>) -> Self {
        self.caller_name = Some(name.into());
        self
    }

    /// Set the event kind.
    pub fn with_event_kind(mut self, kind: u32) -> Self {
        self.event_kind = Some(kind);
        self
    }

    /// Set the reason.
    pub fn with_reason(mut self, reason: impl Into<String>) -> Self {
        self.reason = Some(reason.into());
        self
    }

    /// Compute and set this entry's hash.
    pub fn finalize(mut self) -> Self {
        self.hash = self.compute_hash();
        self
    }

    fn compute_hash(&self) -> [u8; 32] {
        let mut data = Vec::new();
        data.extend_from_slice(&self.timestamp.to_le_bytes());
        data.push(self.request_type as u8);
        data.push(self.decision as u8);
        data.push(self.was_automatic as u8);
        let caller_len = u32::try_from(self.caller.len()).expect("caller too long for hash");
        data.extend_from_slice(&caller_len.to_le_bytes());
        data.extend_from_slice(self.caller.as_bytes());
        hash_optional_str(&mut data, self.caller_name.as_deref());
        if let Some(kind) = self.event_kind {
            data.push(1);
            data.extend_from_slice(&kind.to_le_bytes());
        } else {
            data.push(0);
        }
        hash_optional_str(&mut data, self.reason.as_deref());
        data.extend_from_slice(&self.prev_hash);
        crypto::blake2b_256(&data)
    }

    /// Verify this entry's hash chain linkage.
    pub fn verify(&self, prev_hash: &[u8; 32]) -> bool {
        let prev_hash_match = self.prev_hash.ct_eq(prev_hash);
        let hash_match = self.hash.ct_eq(&self.compute_hash());
        (prev_hash_match & hash_match).into()
    }
}

/// Encrypted signing audit log with hash chain integrity.
pub struct SigningAuditLog {
    path: PathBuf,
    last_hash: [u8; 32],
    retention: RetentionPolicy,
}

impl SigningAuditLog {
    /// Open or create a signing audit log at the given path.
    pub fn open(path: &Path, data_key: &SecretKey) -> Result<Self> {
        let audit_path = path.join("signing_audit.log");
        let last_hash = if audit_path.exists() {
            Self::read_last_hash(&audit_path, data_key)?
        } else {
            [0u8; 32]
        };

        Ok(Self {
            path: audit_path,
            last_hash,
            retention: RetentionPolicy::default(),
        })
    }

    /// Set the retention policy.
    pub fn set_retention(&mut self, policy: RetentionPolicy) {
        self.retention = policy;
    }

    /// Apply the retention policy, returning the number of entries removed.
    pub fn apply_retention(&mut self, data_key: &SecretKey) -> Result<usize> {
        let entries = self.read_all(data_key)?;
        let original_count = entries.len();
        let now = chrono::Utc::now().timestamp();
        let max_age_secs = self.retention.max_age_days.map(|d| i64::from(d) * 86400);

        let mut filtered: Vec<_> = entries
            .into_iter()
            .filter(|e| max_age_secs.is_none_or(|max| now.saturating_sub(e.timestamp) <= max))
            .collect();

        if let Some(max) = self.retention.max_entries {
            if filtered.len() > max {
                filtered = filtered.split_off(filtered.len() - max);
            }
        }

        let removed = original_count - filtered.len();
        if removed > 0 {
            self.rewrite(&filtered, data_key)?;
        }

        Ok(removed)
    }

    /// Log a signing audit entry.
    pub fn log(&mut self, mut entry: SigningAuditEntry, data_key: &SecretKey) -> Result<()> {
        entry.prev_hash = self.last_hash;
        entry.hash = entry.compute_hash();

        let serialized = serde_json::to_vec(&entry)
            .map_err(|e| StorageError::serialization(format!("signing audit entry: {e}")))?;

        let encrypted = crypto::encrypt(&serialized, data_key)?;
        let line = format!("{}\n", STANDARD.encode(encrypted.to_bytes()));

        let mut opts = OpenOptions::new();
        opts.create(true).append(true);
        #[cfg(unix)]
        opts.mode(0o600);
        let mut file = opts.open(&self.path)?;
        file.write_all(line.as_bytes())?;
        file.sync_all()?;

        self.last_hash = entry.hash;
        Ok(())
    }

    /// Read all entries.
    pub fn read_all(&self, data_key: &SecretKey) -> Result<Vec<SigningAuditEntry>> {
        if !self.path.exists() {
            return Ok(Vec::new());
        }
        Self::read_entries(&self.path, data_key)
    }

    /// Read a page of entries (newest first), optionally filtered by caller.
    pub fn read_page(
        &self,
        data_key: &SecretKey,
        offset: usize,
        limit: usize,
        caller_filter: Option<&str>,
    ) -> Result<Vec<SigningAuditEntry>> {
        let all = self.read_all(data_key)?;
        let entries = all
            .into_iter()
            .rev()
            .filter(|e| caller_filter.is_none_or(|c| e.caller == c))
            .skip(offset)
            .take(limit)
            .collect();
        Ok(entries)
    }

    /// Read a page and return metadata (distinct callers, total count) in a single pass.
    pub fn read_page_with_metadata(
        &self,
        data_key: &SecretKey,
        offset: usize,
        limit: usize,
        caller_filter: Option<&str>,
    ) -> Result<(Vec<SigningAuditEntry>, Vec<String>, usize)> {
        let all = self.read_all(data_key)?;
        let count = all.len();

        let mut seen = std::collections::HashSet::new();
        let mut callers = Vec::new();
        for entry in all.iter().rev() {
            if seen.insert(entry.caller.clone()) {
                callers.push(entry.caller.clone());
            }
        }

        let entries = all
            .into_iter()
            .rev()
            .filter(|e| caller_filter.is_none_or(|c| e.caller == c))
            .skip(offset)
            .take(limit)
            .collect();

        Ok((entries, callers, count))
    }

    /// Get distinct callers, most recently active first.
    pub fn distinct_callers(&self, data_key: &SecretKey) -> Result<Vec<String>> {
        let entries = self.read_all(data_key)?;
        let mut seen = std::collections::HashSet::new();
        let mut callers = Vec::new();
        for entry in entries.iter().rev() {
            if seen.insert(entry.caller.clone()) {
                callers.push(entry.caller.clone());
            }
        }
        Ok(callers)
    }

    /// Get the total number of entries.
    pub fn count(&self, data_key: &SecretKey) -> Result<usize> {
        Ok(self.read_all(data_key)?.len())
    }

    /// Verify the hash chain integrity and return the entry count.
    pub fn verify_chain(&self, data_key: &SecretKey) -> Result<(bool, usize)> {
        let entries = self.read_all(data_key)?;
        let count = entries.len();
        let mut prev_hash = [0u8; 32];

        for entry in entries {
            if !entry.verify(&prev_hash) {
                return Ok((false, count));
            }
            prev_hash = entry.hash;
        }

        Ok((true, count))
    }

    /// Get the last entry's hash.
    pub fn last_hash(&self) -> [u8; 32] {
        self.last_hash
    }

    /// Re-encrypt the entire log with a new data key.
    pub fn reencrypt(&mut self, old_key: &SecretKey, new_key: &SecretKey) -> Result<()> {
        if !self.path.exists() {
            return Ok(());
        }
        let entries = Self::read_entries(&self.path, old_key)?;
        if entries.is_empty() {
            return Ok(());
        }
        self.rewrite(&entries, new_key)
    }

    fn read_last_hash(path: &Path, data_key: &SecretKey) -> Result<[u8; 32]> {
        let entries = Self::read_entries(path, data_key)?;
        Ok(entries.last().map_or([0u8; 32], |e| e.hash))
    }

    fn read_entries(path: &Path, data_key: &SecretKey) -> Result<Vec<SigningAuditEntry>> {
        const MAX_ENTRIES: usize = 100_000;

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

        for (line_num, line) in reader.lines().enumerate() {
            if entries.len() >= MAX_ENTRIES {
                return Err(StorageError::io(format!(
                    "signing audit log exceeds maximum of {MAX_ENTRIES} entries"
                ))
                .into());
            }
            let line = line?;
            if line.is_empty() {
                continue;
            }
            let entry = Self::decrypt_line(&line, data_key).map_err(|e| {
                StorageError::corrupted(format!(
                    "signing audit log at line {}: {}",
                    line_num + 1,
                    e
                ))
            })?;
            entries.push(entry);
        }

        Ok(entries)
    }

    fn decrypt_line(line: &str, data_key: &SecretKey) -> Result<SigningAuditEntry> {
        let bytes = STANDARD
            .decode(line)
            .map_err(|e| StorageError::invalid_format(format!("signing audit line: {e}")))?;

        let encrypted = crypto::EncryptedData::from_bytes(&bytes)?;
        let decrypted = crypto::decrypt(&encrypted, data_key)?;

        serde_json::from_slice(&decrypted.as_slice()?)
            .map_err(|e| StorageError::invalid_format(format!("signing audit entry: {e}")).into())
    }

    fn rewrite(&mut self, entries: &[SigningAuditEntry], data_key: &SecretKey) -> Result<()> {
        let temp_path = self.path.with_extension("log.tmp");
        let backup_path = self.path.with_extension("log.bak");

        let final_hash = match self.write_entries_to_temp(&temp_path, entries, data_key) {
            Ok(hash) => hash,
            Err(e) => {
                let _ = std::fs::remove_file(&temp_path);
                return Err(e);
            }
        };

        if self.path.exists() {
            if let Err(e) = std::fs::rename(&self.path, &backup_path) {
                let _ = std::fs::remove_file(&temp_path);
                return Err(StorageError::io(format!("backup signing audit log: {e}")).into());
            }
        }

        if let Err(e) = std::fs::rename(&temp_path, &self.path) {
            if backup_path.exists() {
                let _ = std::fs::rename(&backup_path, &self.path);
            }
            let _ = std::fs::remove_file(&temp_path);
            return Err(StorageError::io(format!("replace signing audit log: {e}")).into());
        }

        let _ = std::fs::remove_file(&backup_path);
        self.last_hash = final_hash;
        Ok(())
    }

    fn write_entries_to_temp(
        &self,
        temp_path: &Path,
        entries: &[SigningAuditEntry],
        data_key: &SecretKey,
    ) -> Result<[u8; 32]> {
        let mut opts = OpenOptions::new();
        opts.write(true).create(true).truncate(true);
        #[cfg(unix)]
        opts.mode(0o600);
        let mut file = opts.open(temp_path)?;

        let mut prev_hash = [0u8; 32];
        for entry in entries {
            let mut entry = entry.clone();
            entry.prev_hash = prev_hash;
            entry.hash = entry.compute_hash();

            let serialized = serde_json::to_vec(&entry)
                .map_err(|e| StorageError::serialization(e.to_string()))?;

            let encrypted = crypto::encrypt(&serialized, data_key)?;
            let line = format!("{}\n", STANDARD.encode(encrypted.to_bytes()));
            file.write_all(line.as_bytes())?;
            prev_hash = entry.hash;
        }

        file.sync_all()?;
        Ok(prev_hash)
    }
}

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

    fn test_key() -> SecretKey {
        SecretKey::generate().unwrap()
    }

    #[test]
    fn test_audit_entry_hash_chain() {
        let genesis = [0u8; 32];
        let entry1 = AuditEntry::new(AuditEventType::KeyGenerate, genesis)
            .with_pubkey(&[1u8; 32])
            .with_key_type("nostr")
            .finalize();

        assert!(entry1.verify(&genesis));

        let entry2 = AuditEntry::new(AuditEventType::Sign, entry1.hash)
            .with_pubkey(&[1u8; 32])
            .with_message_hash(b"test message")
            .finalize();

        assert!(entry2.verify(&entry1.hash));
        assert!(!entry2.verify(&genesis));
    }

    #[test]
    fn test_audit_log_persistence() {
        let dir = tempdir().unwrap();
        let key = test_key();

        {
            let mut log = AuditLog::open(dir.path(), &key).unwrap();
            let entry = AuditEntry::new(AuditEventType::KeyGenerate, log.last_hash())
                .with_pubkey(&[1u8; 32]);
            log.log(entry, &key).unwrap();
        }

        {
            let log = AuditLog::open(dir.path(), &key).unwrap();
            let entries = log.read_all(&key).unwrap();
            assert_eq!(entries.len(), 1);
            assert!(matches!(entries[0].event_type, AuditEventType::KeyGenerate));
        }
    }

    #[test]
    fn test_audit_chain_verification() {
        let dir = tempdir().unwrap();
        let key = test_key();
        let mut log = AuditLog::open(dir.path(), &key).unwrap();

        for i in 0..5 {
            let entry =
                AuditEntry::new(AuditEventType::Sign, log.last_hash()).with_pubkey(&[i as u8; 32]);
            log.log(entry, &key).unwrap();
        }

        assert!(log.verify_chain(&key).unwrap());
    }

    #[test]
    fn test_retention_policy() {
        let dir = tempdir().unwrap();
        let key = test_key();
        let mut log = AuditLog::open(dir.path(), &key).unwrap();
        log.set_retention(RetentionPolicy {
            max_entries: Some(3),
            max_age_days: None,
        });

        for i in 0..5 {
            let entry =
                AuditEntry::new(AuditEventType::Sign, log.last_hash()).with_pubkey(&[i as u8; 32]);
            log.log(entry, &key).unwrap();
        }

        let removed = log.apply_retention(&key).unwrap();
        assert_eq!(removed, 2);

        let entries = log.read_all(&key).unwrap();
        assert_eq!(entries.len(), 3);
    }

    #[test]
    fn verify_chain_returns_true_when_log_absent() {
        // A vault that has never recorded an entry has no audit.log on disk.
        // `verify_chain` must not error or return false in that case, or every
        // freshly-created vault would look "tampered" to `keep audit verify`.
        let dir = tempdir().unwrap();
        let key = test_key();
        let log = AuditLog::open(dir.path(), &key).unwrap();
        assert!(log.verify_chain(&key).unwrap());
        assert!(log.read_all(&key).unwrap().is_empty());
    }

    #[test]
    fn verify_chain_detects_ciphertext_tamper() {
        // The audit log's primary integrity guarantee: a byte flip in a
        // persisted entry must NOT pass verify_chain. The line-level
        // ciphertext check is what `keep audit verify` relies on to detect
        // post-hoc edits of the audit log.
        let dir = tempdir().unwrap();
        let key = test_key();
        let mut log = AuditLog::open(dir.path(), &key).unwrap();

        for i in 0..3 {
            let entry =
                AuditEntry::new(AuditEventType::Sign, log.last_hash()).with_pubkey(&[i as u8; 32]);
            log.log(entry, &key).unwrap();
        }
        assert!(log.verify_chain(&key).unwrap());

        // Flip a byte in the middle of the first persisted entry.
        let audit_path = dir.path().join("audit.log");
        let mut content = std::fs::read(&audit_path).unwrap();
        let first_newline = content.iter().position(|b| *b == b'\n').unwrap();
        // Pick a base64 alphabet character inside the first line so the byte
        // remains decode-valid but the underlying ciphertext is altered.
        let target = first_newline / 2;
        content[target] = if content[target] == b'A' { b'B' } else { b'A' };
        std::fs::write(&audit_path, &content).unwrap();

        // The tampered line must NOT verify cleanly. Either Ok(false) for a
        // hash-chain mismatch, or Err(Corrupted/InvalidFormat) for a failed
        // decrypt: both are acceptable failure modes that `keep audit verify`
        // surfaces to the operator as a tamper warning.
        match log.verify_chain(&key) {
            Ok(false) => {}
            Err(_) => {}
            Ok(true) => panic!("verify_chain accepted a tampered entry as valid"),
        }
    }

    #[test]
    fn apply_retention_by_age_drops_old_entries() {
        // The age-based retention path is what `keep audit retention --max-days`
        // exercises; nothing tested it end-to-end before.
        let dir = tempdir().unwrap();
        let key = test_key();
        let mut log = AuditLog::open(dir.path(), &key).unwrap();

        let now = chrono::Utc::now().timestamp();
        let old_ts = now - 60 * 86400; // 60 days ago.
        let recent_ts = now - 86400; // 1 day ago.

        let mut old_entry = AuditEntry::new(AuditEventType::Sign, log.last_hash());
        old_entry.timestamp = old_ts;
        log.log(old_entry, &key).unwrap();

        let mut recent_entry = AuditEntry::new(AuditEventType::Sign, log.last_hash());
        recent_entry.timestamp = recent_ts;
        log.log(recent_entry, &key).unwrap();

        log.set_retention(RetentionPolicy {
            max_entries: None,
            max_age_days: Some(30),
        });
        let removed = log.apply_retention(&key).unwrap();
        assert_eq!(removed, 1, "the 60-day-old entry must be pruned");

        let remaining = log.read_all(&key).unwrap();
        assert_eq!(remaining.len(), 1);
        assert_eq!(remaining[0].timestamp, recent_ts);
        assert!(
            log.verify_chain(&key).unwrap(),
            "retention rewrite must preserve a valid hash chain"
        );
    }

    #[test]
    fn test_signing_audit_hash_chain() {
        let genesis = [0u8; 32];
        let entry1 = SigningAuditEntry::new(
            SigningRequestType::SignEvent,
            SigningDecision::Approved,
            false,
            "abc123".into(),
            genesis,
        )
        .with_event_kind(1)
        .finalize();

        assert!(entry1.verify(&genesis));

        let entry2 = SigningAuditEntry::new(
            SigningRequestType::SignEvent,
            SigningDecision::Denied,
            true,
            "def456".into(),
            entry1.hash,
        )
        .with_event_kind(30023)
        .with_reason("rate limited")
        .finalize();

        assert!(entry2.verify(&entry1.hash));
        assert!(!entry2.verify(&genesis));
    }

    #[test]
    fn test_signing_audit_log_persistence() {
        let dir = tempdir().unwrap();
        let key = test_key();

        {
            let mut log = SigningAuditLog::open(dir.path(), &key).unwrap();
            let entry = SigningAuditEntry::new(
                SigningRequestType::Connect,
                SigningDecision::Approved,
                false,
                "app1".into(),
                log.last_hash(),
            )
            .with_caller_name("Test App");
            log.log(entry, &key).unwrap();
        }

        {
            let log = SigningAuditLog::open(dir.path(), &key).unwrap();
            let entries = log.read_all(&key).unwrap();
            assert_eq!(entries.len(), 1);
            assert_eq!(entries[0].request_type, SigningRequestType::Connect);
            assert_eq!(entries[0].caller_name, Some("Test App".into()));
        }
    }

    #[test]
    fn test_signing_audit_chain_verification() {
        let dir = tempdir().unwrap();
        let key = test_key();
        let mut log = SigningAuditLog::open(dir.path(), &key).unwrap();

        for i in 0..5 {
            let entry = SigningAuditEntry::new(
                SigningRequestType::SignEvent,
                SigningDecision::Approved,
                i % 2 == 0,
                format!("app{i}"),
                log.last_hash(),
            )
            .with_event_kind(1);
            log.log(entry, &key).unwrap();
        }

        assert!(log.verify_chain(&key).unwrap().0);
    }

    #[test]
    fn test_signing_audit_pagination() {
        let dir = tempdir().unwrap();
        let key = test_key();
        let mut log = SigningAuditLog::open(dir.path(), &key).unwrap();

        for i in 0..10 {
            let caller = if i % 3 == 0 { "app_a" } else { "app_b" };
            let entry = SigningAuditEntry::new(
                SigningRequestType::SignEvent,
                SigningDecision::Approved,
                false,
                caller.into(),
                log.last_hash(),
            );
            log.log(entry, &key).unwrap();
        }

        let page = log.read_page(&key, 0, 3, None).unwrap();
        assert_eq!(page.len(), 3);

        let page = log.read_page(&key, 3, 3, None).unwrap();
        assert_eq!(page.len(), 3);

        let filtered = log.read_page(&key, 0, 100, Some("app_a")).unwrap();
        assert_eq!(filtered.len(), 4);
    }

    #[test]
    fn test_signing_audit_distinct_callers() {
        let dir = tempdir().unwrap();
        let key = test_key();
        let mut log = SigningAuditLog::open(dir.path(), &key).unwrap();

        for caller in &["app_a", "app_b", "app_a", "app_c"] {
            let entry = SigningAuditEntry::new(
                SigningRequestType::SignEvent,
                SigningDecision::Approved,
                false,
                caller.to_string(),
                log.last_hash(),
            );
            log.log(entry, &key).unwrap();
        }

        let callers = log.distinct_callers(&key).unwrap();
        assert_eq!(callers.len(), 3);
    }
}