ferrocrypt 0.3.0-rc.5

Recipient-oriented file and directory encryption: passphrase (Argon2id) and X25519 public-key recipients, XChaCha20-Poly1305 STREAM payloads, HKDF-SHA3-256 / HMAC-SHA3-256 key derivation and authentication.
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
//! Public façade for FerroCrypt's encrypt / decrypt / keygen API.
//!
//! `api.rs` translates stable public types ([`Encryptor`], [`Decryptor`],
//! [`PublicKey`], [`PrivateKey`]) into internal protocol-level calls. It
//! does not derive keys, build headers, compute MACs, or fire progress
//! events directly; that work lives in [`crate::protocol`] and the
//! supporting modules. The module boundary is enforced by visibility:
//! `api.rs` is the only module that surfaces public-API types beyond
//! the helpers re-exported from [`crate`].
//!
//! ## Recipient model
//!
//! - `Encryptor::with_passphrase` — exactly one `argon2id` recipient
//!   (`MixingPolicy::Exclusive`).
//! - `Encryptor::with_public_key` / `with_public_keys` — one or more
//!   `x25519` recipients (`MixingPolicy::PublicKeyMixable`). Empty
//!   lists reject as [`CryptoError::EmptyRecipientList`]; lists that
//!   mix incompatible scheme policies (impossible today, where every
//!   [`PublicKey`] is X25519) reject as
//!   [`CryptoError::IncompatibleRecipients`].
//!
//! ## Decryptor type-safety
//!
//! [`Decryptor::open`] inspects the file's recipient list without
//! cryptographic work and returns a typed variant: [`Decryptor::Passphrase`]
//! for files sealed with a passphrase, [`Decryptor::PrivateKey`] for files
//! sealed to public keys. Each variant's `decrypt` method accepts only the
//! credentials that variant can use, so a mismatched-credential call — for
//! example, passing a [`PrivateKey`] to a passphrase-sealed file — is a compile
//! error rather than a runtime "no supported recipient" failure.

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

use crate::passphrase::Passphrase;

use crate::archive::{self, ArchiveLimits, IncompleteOutputPolicy};
use crate::container::HeaderReadLimits;
use crate::crypto::kdf::{KdfLimit, KdfParams};
use crate::error::sanitize_path_for_display;
use crate::format;
use crate::fs::paths;
use crate::key::limits::KeyReadLimits;
use crate::key::private::PrivateKey;
use crate::key::public::PublicKey;
use crate::protocol;
use crate::recipient;
use crate::recipient::policy::NativeRecipientType;
use crate::{
    AuthenticatedRecipientMode, CryptoError, DecryptOutcome, ENCRYPTED_EXTENSION, EncryptOutcome,
    KeyGenOutcome, ProgressEvent, UnauthenticatedRecipientMode,
};

// ─── Encryptor ─────────────────────────────────────────────────────────────

/// Builder-style entry point for encryption.
///
/// Pick the recipient kind via the constructor — passphrase
/// ([`Encryptor::with_passphrase`]) or one or more public keys
/// ([`Encryptor::with_public_key`], [`Encryptor::with_public_keys`]).
/// Then optionally set an explicit output path
/// ([`Encryptor::save_as`]) or override archive resource caps
/// ([`Encryptor::archive_limits`]). Finalize with
/// [`Encryptor::write`], which streams plaintext through the FCA
/// archive layer + XChaCha20-Poly1305 STREAM-BE32 directly to disk.
///
/// # Examples
///
/// Passphrase:
///
/// ```no_run
/// use ferrocrypt::{Encryptor, Passphrase};
/// let pass = Passphrase::new("correct horse battery staple");
/// let outcome = Encryptor::with_passphrase(pass)
///     .write("./payload", "./out", |ev| eprintln!("{ev}"))?;
/// println!("Encrypted to {}", outcome.output_path.display());
/// # Ok::<(), ferrocrypt::CryptoError>(())
/// ```
///
/// Single public-key recipient:
///
/// ```no_run
/// use ferrocrypt::{Encryptor, PublicKey};
/// let pk = PublicKey::from_key_file("./keys/public.key")?;
/// let outcome = Encryptor::with_public_key(pk)
///     .write("./payload", "./out", |ev| eprintln!("{ev}"))?;
/// # Ok::<(), ferrocrypt::CryptoError>(())
/// ```
///
/// Multiple public-key recipients:
///
/// ```no_run
/// use ferrocrypt::{Encryptor, PublicKey};
/// let alice = PublicKey::from_key_file("./alice/public.key")?;
/// let bob = PublicKey::from_key_file("./bob/public.key")?;
/// let outcome = Encryptor::with_public_keys([alice, bob])?
///     .write("./payload", "./out", |ev| eprintln!("{ev}"))?;
/// # Ok::<(), ferrocrypt::CryptoError>(())
/// ```
#[derive(Debug)]
#[non_exhaustive]
pub struct Encryptor {
    state: EncryptorState,
    save_as: Option<PathBuf>,
    archive_limits: Option<ArchiveLimits>,
    kdf_params: Option<KdfParams>,
    header_read_limits: Option<HeaderReadLimits>,
    kdf_limit: Option<KdfLimit>,
}

#[derive(Debug)]
enum EncryptorState {
    Passphrase(Passphrase),
    Recipients(Vec<PublicKey>),
}

/// Collects `public_keys` into a `Vec`, stopping as soon as it yields more
/// recipients than `FORMAT.md` §3.2 can encode.
///
/// The caller's own recipient-count policy is not applied here, because
/// [`Encryptor::header_read_limits`] can still raise or tighten it after
/// construction; [`Encryptor::write`] is where that check belongs. What this
/// bounds is the ceiling no configuration can lift: a list above
/// [`HeaderReadLimits::RECIPIENT_COUNT_STRUCTURAL_MAX`] could never produce a
/// writable file, so reading all of it is wasted memory and time.
///
/// At most one item beyond the ceiling is ever pulled — enough to know the
/// ceiling was passed — so an iterator of any length, including one with no
/// end, returns here after a bounded amount of work. The reported count is
/// therefore where collection stopped, not the length of the supplied
/// iterator, which is deliberately never established.
fn collect_recipients_within_structural_max(
    public_keys: impl IntoIterator<Item = PublicKey>,
) -> Result<Vec<PublicKey>, CryptoError> {
    let ceiling = HeaderReadLimits::RECIPIENT_COUNT_STRUCTURAL_MAX;
    let iter = public_keys.into_iter();
    // The lower size hint comes from the caller's iterator and is not
    // trustworthy, so it only ever shrinks the reservation.
    let mut collected = Vec::with_capacity(iter.size_hint().0.min(usize::from(ceiling)));
    for public_key in iter {
        if collected.len() == usize::from(ceiling) {
            return Err(CryptoError::RecipientCountCapExceeded {
                count: ceiling.saturating_add(1),
                local_cap: ceiling,
            });
        }
        collected.push(public_key);
    }
    Ok(collected)
}

impl Encryptor {
    /// Configures passphrase encryption.
    ///
    /// The resulting `.fcr` contains exactly one native `argon2id`
    /// recipient. The passphrase is checked against the fixed bound
    /// of 1 to 4,096 bytes when [`Encryptor::write`] runs;
    /// constructing this builder is infallible.
    pub fn with_passphrase(passphrase: Passphrase) -> Self {
        Self {
            state: EncryptorState::Passphrase(passphrase),
            save_as: None,
            archive_limits: None,
            kdf_params: None,
            header_read_limits: None,
            kdf_limit: None,
        }
    }

    /// Configures encryption to one public-key recipient.
    ///
    /// This is a convenience wrapper around [`Encryptor::with_public_keys`]
    /// for the common single-recipient case. As with that constructor,
    /// public-key encryption does not authenticate the sender.
    pub fn with_public_key(public_key: PublicKey) -> Self {
        Self {
            state: EncryptorState::Recipients(vec![public_key]),
            save_as: None,
            archive_limits: None,
            kdf_params: None,
            header_read_limits: None,
            kdf_limit: None,
        }
    }

    /// Configures encryption to one or more public-key recipients.
    ///
    /// Each recipient entry wraps the same per-file `file_key`
    /// independently, so any listed recipient can decrypt the resulting
    /// `.fcr` with their matching private key.
    ///
    /// # Security
    ///
    /// Public-key encryption controls who can decrypt the file, not who
    /// created it. Anyone with a recipient's public key can produce a file
    /// for that recipient. Use a separate signing layer if recipients must
    /// verify sender identity.
    ///
    /// # Default-decrypt round-trip
    ///
    /// By default the writer caps `public_keys.len()` at the same
    /// [`HeaderReadLimits::RECIPIENT_COUNT_DEFAULT`] (64) the reader
    /// applies via [`HeaderReadLimits::default`], so a default-configured
    /// [`Decryptor::open`] can read every file the default
    /// `Encryptor` produces. Lists above the default reject with
    /// [`CryptoError::RecipientCountCapExceeded`] at
    /// [`Encryptor::write`] time. To produce a file with more
    /// recipients, the caller must opt in via
    /// [`Encryptor::header_read_limits`] with a raised
    /// recipient-count limit; the receiving decryptor must be opened
    /// via [`Decryptor::open_with_limits`] with matching limits. Past
    /// roughly 750 X25519 recipients the aggregate header-MAC budget
    /// binds before the count does: the same [`HeaderReadLimits`] must
    /// then also raise
    /// [`HeaderReadLimits::max_header_mac_work_bytes`], on both sides,
    /// or [`Encryptor::write`] refuses with
    /// [`CryptoError::HeaderMacWorkCapExceeded`].
    ///
    /// # Errors
    ///
    /// Returns [`CryptoError::EmptyRecipientList`] if the iterator is empty,
    /// and [`CryptoError::RecipientCountCapExceeded`] if it yields more than
    /// [`HeaderReadLimits::RECIPIENT_COUNT_STRUCTURAL_MAX`] recipients — the
    /// ceiling `FORMAT.md` §3.2 imposes, which no configuration can raise.
    /// Collection stops one item past that ceiling, so an iterator far longer
    /// than it — or one with no end at all — is rejected having held no more
    /// recipients than the ceiling allows. The reported count is where
    /// collection stopped rather than the iterator's length, which is never
    /// established. The default recipient-count cap is a separate,
    /// caller-configurable check that runs at [`Encryptor::write`].
    ///
    /// All public keys in the current implementation are X25519 recipients;
    /// future key kinds may add additional mixing-policy checks.
    pub fn with_public_keys(
        public_keys: impl IntoIterator<Item = PublicKey>,
    ) -> Result<Self, CryptoError> {
        let public_keys = collect_recipients_within_structural_max(public_keys)?;
        if public_keys.is_empty() {
            return Err(CryptoError::EmptyRecipientList);
        }
        // Today PublicKey is always X25519 (PublicKeyMixable). When future
        // PublicKey variants carry different mixing policies, the check
        // expands here; protocol::encrypt re-checks as defense-in-depth.
        Ok(Self {
            state: EncryptorState::Recipients(public_keys),
            save_as: None,
            archive_limits: None,
            kdf_params: None,
            header_read_limits: None,
            kdf_limit: None,
        })
    }

    /// Sets the encrypted output file path.
    ///
    /// When set, this path is used instead of the default
    /// `{output_dir}/{stem}.fcr` destination chosen by [`Encryptor::write`].
    pub fn save_as(mut self, path: impl AsRef<Path>) -> Self {
        self.save_as = Some(path.as_ref().to_path_buf());
        self
    }

    /// Overrides the default archive resource caps applied during
    /// the writer-side preflight. Useful for callers operating on
    /// trusted trees that legitimately exceed the defaults.
    ///
    /// # Default-decrypt round-trip
    ///
    /// Raising `archive_limits` above [`ArchiveLimits::default`] can
    /// produce a `.fcr` whose archive payload exceeds what a
    /// default-configured [`PassphraseDecryptor`] /
    /// [`PrivateKeyDecryptor`] will extract. The receiving decryptor
    /// must be configured via
    /// [`PassphraseDecryptor::archive_limits`] /
    /// [`PrivateKeyDecryptor::archive_limits`] with limits that match
    /// (or exceed) the file's actual content. Lowering
    /// `archive_limits` only tightens what the encrypt-side preflight
    /// accepts and never breaks default round-trip.
    pub fn archive_limits(mut self, limits: ArchiveLimits) -> Self {
        self.archive_limits = Some(limits);
        self
    }

    /// Overrides the Argon2id parameters used by the passphrase recipient
    /// (`Encryptor::with_passphrase`). Has no effect on public-key
    /// (`Encryptor::with_public_key` / `with_public_keys`) flows, which use
    /// X25519 ECDH and never run Argon2id during encryption.
    ///
    /// If unset, the writer uses [`KdfParams::default`] (1 GiB memory,
    /// time_cost 4, parallelism 4). A `params.mem_cost` below the 19 MiB
    /// production memory floor rejects at [`Encryptor::write`] time with
    /// [`CryptoError::KdfBelowWriteFloor`], so a caller cannot seal a `.fcr`
    /// with weak Argon2id memory; the floor is hard and has no override.
    ///
    /// # Default-decrypt round-trip
    ///
    /// `kdf_params` is also checked at [`Encryptor::write`] time against
    /// the writer's [`KdfLimit`] policy. By default, memory is capped at
    /// 1 GiB and combined work at the writer's own budget, while time cost
    /// and lanes are capped at the format maximum, so [`KdfParams::default`]
    /// is accepted. A value above the effective policy rejects with the
    /// matching typed cap error. To write a `.fcr` with memory above 1 GiB or
    /// more total work than [`KdfParams::default`], or to use a deliberately
    /// tightened policy, configure [`Encryptor::kdf_limit`] and set a
    /// compatible [`PassphraseDecryptor::kdf_limit`] on the receiving decryptor
    /// before calling [`PassphraseDecryptor::decrypt`].
    pub fn kdf_params(mut self, params: KdfParams) -> Self {
        self.kdf_params = Some(params);
        self
    }

    /// Sets the writer-side header limits.
    ///
    /// By default the writer caps the header shape at the same
    /// [`HeaderReadLimits`] values the default reader uses, so a default
    /// [`Decryptor::open`] can read every file the default `Encryptor`
    /// produces. This builder raises or tightens those writer-side caps;
    /// the receiving decryptor must be opened via
    /// [`Decryptor::open_with_limits`] with limits that are at least as
    /// permissive. Past roughly 750 X25519 recipients the aggregate
    /// header-MAC budget binds before the recipient count does; see
    /// [`Encryptor::with_public_keys`].
    ///
    /// All four axes are checked before encryption work begins:
    /// `recipient_count`, canonical native recipient `body_len`, the exact
    /// `header_len` that the writer will emit (`ext_len = 0` for current
    /// writers), and the aggregate header-MAC work those two imply.
    /// Tightening any axis below the emitted header shape rejects at
    /// [`Encryptor::write`] time with the same typed cap error the reader
    /// would later return.
    pub fn header_read_limits(mut self, limits: HeaderReadLimits) -> Self {
        self.header_read_limits = Some(limits);
        self
    }

    /// Sets the writer-side KDF resource policy for passphrase encryption.
    ///
    /// The policy caps Argon2id memory cost, time cost, lane count, and
    /// combined work before any encryption work begins. The default policy
    /// accepts [`KdfParams::default`], which sits exactly at the default work
    /// budget, and rejects memory above 1 GiB unless the caller opts into a
    /// higher memory cap. Time cost and lanes default to the format maximum,
    /// so they only reject when the caller tightens them.
    ///
    /// Use this builder together with [`Encryptor::kdf_params`] to raise the
    /// memory or work ceiling, or to tighten any dimension. Raising memory does
    /// not raise the work budget, so parameters above
    /// [`KdfParams::default`]'s work need [`KdfLimit::max_work`] as well. The
    /// receiving passphrase decryptor must be configured via
    /// [`PassphraseDecryptor::kdf_limit`] with a policy that accepts the same
    /// parameters.
    ///
    /// Has no effect on public-key (`Encryptor::with_public_key` /
    /// `with_public_keys`) flows, which never run Argon2id during
    /// encryption.
    pub fn kdf_limit(mut self, limit: KdfLimit) -> Self {
        self.kdf_limit = Some(limit);
        self
    }

    /// Encrypts `input` and writes the resulting `.fcr` file.
    ///
    /// `input` may be a regular file or a directory. Directory inputs are
    /// encoded as a FerroCrypt Archive (FCA) payload before payload encryption.
    /// The default destination is `{output_dir}/{stem}.fcr`; use
    /// [`Encryptor::save_as`] to supply an explicit output file path.
    ///
    /// # Errors
    ///
    /// Returns [`CryptoError::InputPath`] if `input` does not exist, and
    /// [`CryptoError::InvalidInput`] for an unusable input path, an output
    /// conflict, an unsupported archive entry, an empty or too-long
    /// passphrase, or a source file or directory that was replaced or removed
    /// while it was being read. It is also returned when, after the commit,
    /// the output path no longer leads to the file just written. A source
    /// name the FCA path grammar refuses returns
    /// [`CryptoError::UnsafeArchivePath`]. Caps and key-derivation settings
    /// each report their own variant, never `InvalidInput`: an
    /// [`ArchiveLimits`] cap returns the matching `Archive*CapExceeded`, a
    /// [`HeaderReadLimits`] cap returns the `*CapExceeded` variant for the axis
    /// it bounds, and Argon2id parameters return
    /// [`CryptoError::InvalidKdfParams`] outside the `FORMAT.md` §2.2 bounds,
    /// [`CryptoError::KdfBelowWriteFloor`] below the writer's memory floor, or
    /// the matching `Kdf*CapExceeded` above a [`KdfLimit`]. Returns
    /// [`CryptoError::Io`] for filesystem failures, including a committed
    /// output whose path could not be confirmed or that carries more than one
    /// filesystem name. These post-commit conditions can leave the complete
    /// encrypted file under its final, temporary, or moved name, and an error
    /// returned after the commit says in its message that the output is
    /// complete. Returns authentication or internal crypto errors if key
    /// wrapping or payload streaming fails.
    pub fn write(
        self,
        input: impl AsRef<Path>,
        output_dir: impl AsRef<Path>,
        on_event: impl Fn(&ProgressEvent),
    ) -> Result<EncryptOutcome, CryptoError> {
        let input = input.as_ref();
        let output_dir = output_dir.as_ref();
        let archive_limits = self.archive_limits.unwrap_or_default();
        let header_read_limits = self.header_read_limits.unwrap_or_default();
        let kdf_limit = self.kdf_limit.unwrap_or_default();
        // Resolved once: the value the preflight validates below is by
        // construction the value serialized into the recipient body.
        let kdf_params = self.kdf_params.unwrap_or_default();
        let save_as = self.save_as.as_deref();

        // Check the fixed passphrase byte-length bound before filesystem
        // work. A value outside the bound is a caller error, and reporting it
        // first avoids unnecessary syscalls.
        if let EncryptorState::Passphrase(p) = &self.state {
            validate_passphrase(p)?;
        }

        // Writer caps mirror reader defaults via the same `enforce_*`
        // helpers the reader uses, so default-encrypt and default-
        // decrypt cannot drift. Checked here so a misconfiguration
        // fails before recipient key files are read;
        // `protocol::encrypt` re-enforces the same gates for any
        // other caller.
        match &self.state {
            EncryptorState::Recipients(rs) => {
                protocol::preflight_header_write_limits(
                    header_read_limits,
                    rs.len(),
                    NativeRecipientType::X25519,
                    protocol::WRITE_EXT_BYTES,
                )?;
            }
            EncryptorState::Passphrase(_) => {
                protocol::preflight_header_write_limits(
                    header_read_limits,
                    1,
                    NativeRecipientType::Argon2id,
                    protocol::WRITE_EXT_BYTES,
                )?;
                kdf_params.validate_for_write(Some(&kdf_limit))?;
            }
        }

        archive::validate_encrypt_input(input)?;

        let output_path = match self.state {
            EncryptorState::Passphrase(passphrase) => {
                // The passphrase moves into the recipient, which
                // `protocol::encrypt` drops once the body is wrapped, so it
                // is gone before the payload is streamed.
                let recipient = recipient::argon2id::PassphraseRecipient {
                    passphrase,
                    kdf_params,
                    kdf_limit,
                };
                protocol::encrypt(
                    vec![recipient],
                    archive_limits,
                    header_read_limits,
                    input,
                    output_dir,
                    save_as,
                    &on_event,
                )?
            }
            EncryptorState::Recipients(public_keys) => {
                // Collect the 32-byte material into a local Vec that owns the
                // bytes; X25519Recipient borrows from it for the lifetime of
                // this match arm.
                let public_key_bytes_vec: Vec<[u8; 32]> = public_keys
                    .iter()
                    .map(|pk| pk.to_x25519_bytes())
                    .collect::<Result<_, _>>()?;
                let recipients: Vec<recipient::x25519::X25519Recipient> = public_key_bytes_vec
                    .iter()
                    .map(|bytes| recipient::x25519::X25519Recipient {
                        recipient_public_key_bytes: bytes,
                    })
                    .collect();
                protocol::encrypt(
                    recipients,
                    archive_limits,
                    header_read_limits,
                    input,
                    output_dir,
                    save_as,
                    &on_event,
                )?
            }
        };

        Ok(EncryptOutcome { output_path })
    }
}

// ─── Decryptor ─────────────────────────────────────────────────────────────

/// Type-safe entry point for decryption.
///
/// [`Decryptor::open`] reads the `.fcr` header without cryptographic work and
/// returns the variant that matches the file's recipient kind. Each variant
/// takes only the credentials it can use:
///
/// - [`Decryptor::Passphrase`] takes a passphrase.
/// - [`Decryptor::PrivateKey`] takes a [`PrivateKey`], which carries its
///   own unlock passphrase.
///
/// A mismatched-credential call — e.g. trying to decrypt a passphrase-sealed
/// file with a [`PrivateKey`] — is therefore a compile error. The runtime
/// [`CryptoError::DecryptorModeMismatch`] is left for the one case types
/// cannot cover: the file at the path changed recipient mode after
/// [`Decryptor::open`] classified it.
#[derive(Debug)]
#[non_exhaustive]
pub enum Decryptor {
    /// File is sealed with a passphrase. Decrypt via
    /// [`PassphraseDecryptor::decrypt`].
    Passphrase(PassphraseDecryptor),
    /// File is sealed to one or more public-key recipients. Decrypt
    /// via [`PrivateKeyDecryptor::decrypt`].
    PrivateKey(PrivateKeyDecryptor),
}

impl Decryptor {
    /// Probes the `.fcr` header (cheap structural read; no recipient
    /// unwrap, no MAC, no payload bytes touched) and returns the
    /// matching variant.
    ///
    /// The returned value holds the path, not the opened file: each `decrypt`
    /// reads the header again from that path. The classification is therefore
    /// a routing hint about a path, not a verdict about a file — if the path
    /// stops naming the file probed here, `decrypt` refuses a changed
    /// recipient mode with [`CryptoError::DecryptorModeMismatch`] and
    /// otherwise processes whatever is there now, under the same acceptance
    /// order. Within one `decrypt` call the file is opened once and kept open.
    ///
    /// # Errors
    ///
    /// Returns [`CryptoError::InputPath`] if `input` does not exist and
    /// [`CryptoError::InvalidInput`] if `input` is a directory. An input
    /// shorter than the 12-byte `.fcr` prefix returns
    /// [`CryptoError::InvalidFormat`] with
    /// [`FormatDefect::Truncated`](crate::FormatDefect::Truncated) whatever its
    /// bytes, because `FORMAT.md` §3.1 checks the length of the prefix before
    /// its magic. An input of at least 12 bytes that does not open with the
    /// FerroCrypt magic returns
    /// [`FormatDefect::BadMagic`](crate::FormatDefect::BadMagic). Malformed
    /// headers, unsupported versions, unknown critical recipients, and illegal
    /// recipient mixes return their corresponding `CryptoError` or
    /// [`FormatDefect`](crate::FormatDefect) variants. A passphrase recipient
    /// whose stored Argon2id parameters are outside the bounds `FORMAT.md` §2.2
    /// permits returns [`CryptoError::InvalidKdfParams`]. A header shape, or an
    /// aggregate header-MAC work total, above [`HeaderReadLimits::default`]
    /// returns the matching `*CapExceeded` variant; use
    /// [`Decryptor::open_with_limits`] to raise the caps.
    pub fn open(input: impl AsRef<Path>) -> Result<Self, CryptoError> {
        Self::open_inner(input.as_ref(), None)
    }

    /// Same as [`Decryptor::open`] but uses the supplied
    /// [`HeaderReadLimits`] for the structural header read instead of
    /// the conservative defaults.
    ///
    /// Callers handling files whose recipient strings, recipient
    /// counts, or header lengths legitimately exceed the defaults
    /// (for example, forward-compatible files with larger future recipient
    /// bodies) should construct a `HeaderReadLimits` via the builder
    /// methods and pass it here. The same limits are stashed on the
    /// returned variant so the second header read inside
    /// [`PassphraseDecryptor::decrypt`] / [`PrivateKeyDecryptor::decrypt`]
    /// uses them too — callers do not need to set them twice.
    ///
    /// # Errors
    ///
    /// Returns the same errors as [`Decryptor::open`], but applies the supplied
    /// [`HeaderReadLimits`] during structural header parsing.
    pub fn open_with_limits(
        input: impl AsRef<Path>,
        header_read_limits: HeaderReadLimits,
    ) -> Result<Self, CryptoError> {
        Self::open_inner(input.as_ref(), Some(header_read_limits))
    }

    fn open_inner(
        input: &Path,
        header_read_limits: Option<HeaderReadLimits>,
    ) -> Result<Self, CryptoError> {
        let Some(file) = open_header_input(input)? else {
            return Err(CryptoError::InvalidInput(format!(
                "Cannot decrypt a directory: {}",
                sanitize_path_for_display(input)
            )));
        };
        // Read the header as decryption does, with no magic shortcut, so a
        // file that is not a FerroCrypt file is reported in the `FORMAT.md`
        // §3.1 order: the length of the prefix before its magic.
        let mode =
            protocol::DecryptSession::from_file(file, header_read_limits.unwrap_or_default())?
                .mode();
        let input = input.to_path_buf();
        match mode {
            UnauthenticatedRecipientMode::Passphrase => Ok(Self::Passphrase(PassphraseDecryptor {
                input,
                kdf_limit: None,
                archive_limits: None,
                header_read_limits,
                incomplete_output_policy: None,
            })),
            UnauthenticatedRecipientMode::PublicKey => Ok(Self::PrivateKey(PrivateKeyDecryptor {
                input,
                kdf_limit: None,
                key_read_limits: None,
                archive_limits: None,
                header_read_limits,
                incomplete_output_policy: None,
            })),
        }
    }
}

/// Decryptor for passphrase-sealed `.fcr` files. Returned from
/// [`Decryptor::open`] when the file's recipient list classifies as
/// [`UnauthenticatedRecipientMode::Passphrase`].
#[derive(Debug)]
#[non_exhaustive]
pub struct PassphraseDecryptor {
    input: PathBuf,
    kdf_limit: Option<KdfLimit>,
    archive_limits: Option<ArchiveLimits>,
    header_read_limits: Option<HeaderReadLimits>,
    incomplete_output_policy: Option<IncompleteOutputPolicy>,
}

impl PassphraseDecryptor {
    /// Sets the reader-side KDF resource policy for this decrypt.
    ///
    /// The policy caps Argon2id memory cost, time cost, lane count, and
    /// combined work accepted from the file header, before any derivation work
    /// begins. If unset, the decrypt path applies [`KdfLimit::default`], a
    /// desktop-sized budget of 1 GiB and the writer's own work budget,
    /// matching what this library writes.
    ///
    /// A service that decrypts untrusted files unattended should set a
    /// smaller limit and bound how many decrypts run at once: the header
    /// chooses the Argon2id cost, and the derivation runs before the file
    /// is authenticated, so every concurrent call can hold the full budget.
    pub fn kdf_limit(mut self, limit: KdfLimit) -> Self {
        self.kdf_limit = Some(limit);
        self
    }

    /// Overrides the default archive resource caps applied during
    /// extraction. Must match (or exceed) the limits the writer used —
    /// a file produced with [`Encryptor::archive_limits`] above the
    /// default cannot be decrypted under [`ArchiveLimits::default`].
    pub fn archive_limits(mut self, limits: ArchiveLimits) -> Self {
        self.archive_limits = Some(limits);
        self
    }

    /// Overrides the header-read caps applied while parsing the
    /// `.fcr` header during decrypt. The same limits used at
    /// [`Decryptor::open`] / [`Decryptor::open_with_limits`] are
    /// carried into the variant; this builder lets callers tighten or
    /// loosen them between open and decrypt for advanced flows.
    pub fn header_read_limits(mut self, limits: HeaderReadLimits) -> Self {
        self.header_read_limits = Some(limits);
        self
    }

    /// Sets the policy that governs the `.incomplete` working tree
    /// when this decrypt fails.
    ///
    /// Defaults to [`IncompleteOutputPolicy::DeleteOnError`], which
    /// removes this run's `.incomplete` plaintext while the output is
    /// still treated as staged, and reports in the returned error a
    /// removal that failed or could not be confirmed. It does not remove
    /// a complete output confirmed before a later filesystem namespace
    /// error. Pass
    /// [`IncompleteOutputPolicy::RetainOnError`] for backup-recovery or
    /// forensic flows where partial output is more useful than no output. See
    /// that variant for the truncation-prefix caveat callers must understand
    /// before acting on a retained partial.
    pub fn incomplete_output_policy(mut self, policy: IncompleteOutputPolicy) -> Self {
        self.incomplete_output_policy = Some(policy);
        self
    }

    /// Decrypts this passphrase-sealed `.fcr` into `output_dir`.
    ///
    /// The passphrase is checked against the fixed bound of 1 to
    /// 4,096 bytes, then used to unwrap the file's `argon2id` recipient. The
    /// recovered candidate file key is accepted only after the header MAC
    /// verifies. On success, the decrypted file or directory is promoted
    /// into `output_dir` and returned in [`DecryptOutcome::output_path`].
    ///
    /// # Errors
    ///
    /// Returns [`CryptoError::InvalidInput`] for an empty or too-long
    /// passphrase or an output conflict. Caps report their own variants, never
    /// `InvalidInput`: an [`ArchiveLimits`] cap returns the matching
    /// `Archive*CapExceeded`, and stored Argon2id costs above a [`KdfLimit`]
    /// return [`CryptoError::KdfResourceCapExceeded`],
    /// [`CryptoError::KdfTimeCostCapExceeded`],
    /// [`CryptoError::KdfLanesCapExceeded`], or
    /// [`CryptoError::KdfWorkCapExceeded`]. An archived path the FCA grammar
    /// refuses returns [`CryptoError::UnsafeArchivePath`], and a manifest whose
    /// tree shape is illegal returns [`CryptoError::InvalidArchiveTree`].
    /// Returns [`CryptoError::DecryptorModeMismatch`] if the file at the path
    /// is no longer passphrase-sealed: the header is read again here, so a
    /// path whose contents changed since [`Decryptor::open`] is refused rather
    /// than decrypted.
    /// Returns [`CryptoError::InvalidFormat`] if the encrypted container or
    /// authenticated payload stream is structurally malformed. Returns
    /// authentication errors such as [`CryptoError::RecipientUnwrapFailed`],
    /// [`CryptoError::HeaderTampered`], [`CryptoError::PayloadTampered`], or
    /// [`CryptoError::PayloadTruncated`] when credentials are wrong or the file
    /// is modified. Returns [`CryptoError::InputPath`] if the encrypted file
    /// no longer exists, and [`CryptoError::Io`] for other filesystem
    /// failures. Checks that run after the complete plaintext output is
    /// committed can still fail the call, with [`CryptoError::InvalidInput`]
    /// or [`CryptoError::Io`]. In that case [`IncompleteOutputPolicy`] does
    /// not remove the confirmed output, and the error message says that the
    /// output is complete, unless the check found the output's final name
    /// missing or holding another entry, which is reported as a replacement.
    pub fn decrypt(
        self,
        passphrase: Passphrase,
        output_dir: impl AsRef<Path>,
        on_event: impl Fn(&ProgressEvent),
    ) -> Result<DecryptOutcome, CryptoError> {
        validate_passphrase(&passphrase)?;
        // Hand the passphrase to the credential so the protocol layer can
        // scrub it once the recipient slot loop is done, rather than holding
        // it here for the whole payload extraction.
        let credential = recipient::argon2id::PassphraseCredential {
            passphrase,
            kdf_limit: self.kdf_limit.as_ref(),
        };
        let archive_limits = self.archive_limits.unwrap_or_default();
        let header_read_limits = self.header_read_limits.unwrap_or_default();
        let incomplete_output_policy = self.incomplete_output_policy.unwrap_or_default();
        // No early progress event here. `protocol::decrypt` parses the
        // header structurally before any KDF runs; if the file is
        // malformed or mode-mismatched, no event should fire. The
        // `DerivingPassphraseWrapKey` event fires from inside
        // `argon2id::unwrap` once the slot loop reaches a structurally
        // valid `argon2id` body whose `kdf_params` are within the
        // resource cap — i.e. immediately before Argon2id actually runs.
        let output_path = protocol::decrypt(
            credential,
            &self.input,
            output_dir.as_ref(),
            archive_limits,
            header_read_limits,
            incomplete_output_policy,
            &on_event,
        )?;
        Ok(DecryptOutcome {
            output_path,
            recipient_mode: AuthenticatedRecipientMode::passphrase(),
        })
    }
}

/// Decryptor for public-key-sealed `.fcr` files. Returned from
/// [`Decryptor::open`] when the file's recipient list classifies as
/// [`UnauthenticatedRecipientMode::PublicKey`].
#[derive(Debug)]
#[non_exhaustive]
pub struct PrivateKeyDecryptor {
    input: PathBuf,
    kdf_limit: Option<KdfLimit>,
    key_read_limits: Option<KeyReadLimits>,
    archive_limits: Option<ArchiveLimits>,
    header_read_limits: Option<HeaderReadLimits>,
    incomplete_output_policy: Option<IncompleteOutputPolicy>,
}

impl PrivateKeyDecryptor {
    /// Sets the reader-side KDF resource policy for unlocking `private.key`.
    ///
    /// The policy caps Argon2id memory cost, time cost, lane count, and
    /// combined work accepted from the key file's cleartext header, before any
    /// derivation work begins. If unset, the decrypt path applies
    /// [`KdfLimit::default`], a desktop-sized budget of 1 GiB and the writer's
    /// own work budget, matching what this library writes.
    ///
    /// A service that unlocks untrusted key files unattended should set a
    /// smaller limit and bound how many unlocks run at once: the key file's
    /// cleartext header chooses the Argon2id cost, and the derivation runs
    /// before the wrapped secret is authenticated.
    pub fn kdf_limit(mut self, limit: KdfLimit) -> Self {
        self.kdf_limit = Some(limit);
        self
    }

    /// Overrides the key-file caps applied while reading the supplied
    /// `private.key`.
    ///
    /// If unset, the decrypt path applies [`KeyReadLimits::default`].
    /// Raise [`KeyReadLimits::max_private_key_wrapped_secret_len`] for a
    /// key file whose wrapped secret legitimately exceeds the default. It is
    /// the only [`KeyReadLimits`] cap a `private.key` uses.
    pub fn key_read_limits(mut self, limits: KeyReadLimits) -> Self {
        self.key_read_limits = Some(limits);
        self
    }

    /// Overrides the default archive resource caps applied during
    /// extraction. Must match (or exceed) the limits the writer used —
    /// a file produced with [`Encryptor::archive_limits`] above the
    /// default cannot be decrypted under [`ArchiveLimits::default`].
    pub fn archive_limits(mut self, limits: ArchiveLimits) -> Self {
        self.archive_limits = Some(limits);
        self
    }

    /// Overrides the header-read caps applied while parsing the
    /// `.fcr` header during decrypt. The same limits used at
    /// [`Decryptor::open`] / [`Decryptor::open_with_limits`] are
    /// carried into the variant; this builder lets callers tighten or
    /// loosen them between open and decrypt for advanced flows.
    pub fn header_read_limits(mut self, limits: HeaderReadLimits) -> Self {
        self.header_read_limits = Some(limits);
        self
    }

    /// Sets the policy that governs the `.incomplete` working tree
    /// when this decrypt fails.
    ///
    /// Defaults to [`IncompleteOutputPolicy::DeleteOnError`], which
    /// removes this run's `.incomplete` plaintext while the output is
    /// still treated as staged, and reports in the returned error a
    /// removal that failed or could not be confirmed. It does not remove
    /// a complete output confirmed before a later filesystem namespace
    /// error. Pass
    /// [`IncompleteOutputPolicy::RetainOnError`] for backup-recovery or
    /// forensic flows where partial output is more useful than no output. See
    /// that variant for the truncation-prefix caveat callers must understand
    /// before acting on a retained partial.
    pub fn incomplete_output_policy(mut self, policy: IncompleteOutputPolicy) -> Self {
        self.incomplete_output_policy = Some(policy);
        self
    }

    /// Decrypts this public-key-recipient `.fcr` into `output_dir`.
    ///
    /// `private_key` must reference a FerroCrypt `private.key` file. The
    /// private key is unlocked with the passphrase bound by
    /// [`PrivateKey::from_key_file`], then the decryptor tries the supported
    /// `x25519` recipient slots until one yields a candidate file key that
    /// verifies the header MAC. On success, the decrypted file or directory
    /// is promoted into `output_dir` and returned in
    /// [`DecryptOutcome::output_path`].
    ///
    /// # Errors
    ///
    /// Returns [`CryptoError::InvalidInput`] for an empty or too-long
    /// private-key passphrase or an output conflict. An [`ArchiveLimits`] cap
    /// reports its own `Archive*CapExceeded` variant, never `InvalidInput`.
    /// An archived path the FCA grammar
    /// refuses returns [`CryptoError::UnsafeArchivePath`], and a manifest whose
    /// tree shape is illegal returns [`CryptoError::InvalidArchiveTree`].
    /// Returns [`CryptoError::DecryptorModeMismatch`] if the file at the path
    /// is no longer public-key-sealed: the header is read again here, so a
    /// path whose contents changed since [`Decryptor::open`] is refused rather
    /// than decrypted.
    /// Returns [`CryptoError::InvalidFormat`] if the private key, encrypted
    /// container, or authenticated payload stream is structurally malformed;
    /// returns [`CryptoError::KeyFileUnlockFailed`] if the private key is
    /// tampered or protected by a different passphrase.
    /// Returns [`CryptoError::KdfResourceCapExceeded`],
    /// [`CryptoError::KdfTimeCostCapExceeded`],
    /// [`CryptoError::KdfLanesCapExceeded`], or
    /// [`CryptoError::KdfWorkCapExceeded`] for `private.key` KDF costs above
    /// the [`KdfLimit`]. Returns [`CryptoError::UnsupportedKeyType`]
    /// if the private key wraps a key type this build does not support.
    /// Returns authentication errors such as
    /// [`CryptoError::RecipientUnwrapFailed`],
    /// [`CryptoError::HeaderMacFailedAfterUnwrap`],
    /// [`CryptoError::NoSupportedRecipient`], [`CryptoError::PayloadTampered`],
    /// or [`CryptoError::PayloadTruncated`]. `RecipientUnwrapFailed` means the
    /// private key matched no supported recipient slot, or a recipient body was
    /// modified; `NoSupportedRecipient` means the file contains no recipient
    /// type this build can process. Returns [`CryptoError::InputPath`] if the
    /// encrypted file or the private key file does not exist, and
    /// [`CryptoError::Io`] for other filesystem failures. Checks that run
    /// after the complete plaintext output is committed can still fail the
    /// call, with [`CryptoError::InvalidInput`] or [`CryptoError::Io`]. In
    /// that case [`IncompleteOutputPolicy`] does not remove the confirmed
    /// output, and the error message says that the output is complete, unless
    /// the check found the output's final name missing or holding another
    /// entry, which is reported as a replacement.
    pub fn decrypt(
        self,
        private_key: PrivateKey,
        output_dir: impl AsRef<Path>,
        on_event: impl Fn(&ProgressEvent),
    ) -> Result<DecryptOutcome, CryptoError> {
        let (key_file_path, private_key_passphrase) = private_key.into_key_file_parts();
        validate_passphrase(&private_key_passphrase)?;
        let archive_limits = self.archive_limits.unwrap_or_default();
        let header_read_limits = self.header_read_limits.unwrap_or_default();
        let incomplete_output_policy = self.incomplete_output_policy.unwrap_or_default();

        // Open and classify the encrypted file before unlocking the
        // private key, then retain that open file for decryption.
        // Structural errors must be reported before Argon2id starts.
        // Keeping one file open also prevents a path replacement during
        // the unlock from changing which bytes are decrypted.
        let session = protocol::DecryptSession::open(&self.input, header_read_limits)?;
        if session.mode() != UnauthenticatedRecipientMode::PublicKey {
            return Err(CryptoError::DecryptorModeMismatch {
                expected: UnauthenticatedRecipientMode::PublicKey,
                found: session.mode(),
            });
        }

        // No early progress event here. `open_x25519_private_key` first
        // applies the generic binary-shape, resource-cap, type-name
        // grammar, and passphrase-length gates. Only immediately before
        // Argon2id does `key::private::open_private_key` emit
        // `UnlockingPrivateKey`. Those pre-KDF failures and a concrete
        // public/private key-file mix-up therefore emit no event. Verdicts
        // that require authenticated bytes, including
        // `UnsupportedKeyType`, occur after the event.
        let private_key_bytes = recipient::native::x25519::open_x25519_private_key(
            &key_file_path,
            &private_key_passphrase,
            self.kdf_limit.as_ref(),
            self.key_read_limits.unwrap_or_default(),
            &on_event,
        )?;
        // The passphrase unlocks `private.key` and nothing else. Scrub it now
        // rather than carrying it through the payload phase below.
        drop(private_key_passphrase);

        let decryption_credential = recipient::x25519::X25519Credential { private_key_bytes };
        let output_path = protocol::decrypt_session(
            decryption_credential,
            session,
            output_dir.as_ref(),
            archive_limits,
            incomplete_output_policy,
            &on_event,
        )?;
        Ok(DecryptOutcome {
            output_path,
            recipient_mode: AuthenticatedRecipientMode::public_key(),
        })
    }
}

// ─── Private-key inspection ─────────────────────────────────────────────────

/// Operations on a [`PrivateKey`] that need the key-file unlock.
///
/// The unlock lives here rather than beside the type: `PrivateKey` is defined
/// in `key/private.rs`, which sits *below* `recipient/native/x25519.rs` in the
/// STRUCTURE.md §11 dependency graph, so reaching the X25519 reader from there
/// would make the two modules mutually dependent.
impl PrivateKey {
    /// Unlocks the private key and returns the public key that belongs to it.
    ///
    /// Consumes the value, because the unlock is the passphrase's only use and
    /// a `PrivateKey` is not reusable: build a fresh one for each operation, as
    /// with [`PrivateKeyDecryptor::decrypt`].
    ///
    /// The returned key is the `public_material` the file itself stores.
    /// `FORMAT.md` §8 requires a reader to reject a `private.key` whose stored
    /// public material is not `X25519(secret_material, basepoint)`, so the
    /// value is evidence about the pair rather than about one half of it. It
    /// carries this build's writer keypair suite, which every readable
    /// `private.key` belongs to (`FORMAT.md` §11.2).
    ///
    /// Use this to confirm which recipient a `private.key` decrypts for —
    /// comparing [`PublicKey::fingerprint`] against a fingerprint published out
    /// of band, or recovering the `fcr1…` recipient string from a key pair
    /// whose `public.key` was lost.
    ///
    /// Emits [`ProgressEvent::UnlockingPrivateKey`] at the Argon2id boundary,
    /// because the unlock runs the same key derivation a decrypt runs and takes
    /// the same time.
    ///
    /// Applies the library's default [`KdfLimit`] and [`KeyReadLimits`]. Use
    /// [`PrivateKey::into_public_key_with_limits`] for a key file sealed with
    /// [`KeyPairGenerator::kdf_limit`] above either default, which this method
    /// would otherwise refuse to open even though the matching decrypt
    /// succeeds.
    ///
    /// # Errors
    ///
    /// A key file whose stored parameters exceed either default surfaces the
    /// matching resource-cap error. Returns
    /// [`CryptoError::KeyFileUnlockFailed`] for a wrong passphrase or modified
    /// cleartext, which the AEAD cannot tell apart,
    /// [`CryptoError::UnsupportedKeyType`] for a key file that wraps a
    /// non-X25519 secret, [`CryptoError::InvalidInput`] for a passphrase
    /// outside the `FORMAT.md` §2.2 bound of 1 to 4,096 bytes,
    /// [`CryptoError::InputPath`] when the file does not exist and
    /// [`CryptoError::Io`] for any other filesystem failure, and the same
    /// structural and version errors as a decrypt that opens the same file.
    pub fn into_public_key(
        self,
        on_event: impl Fn(&ProgressEvent),
    ) -> Result<PublicKey, CryptoError> {
        self.into_public_key_with_limits(KdfLimit::default(), KeyReadLimits::default(), on_event)
    }

    /// Unlocks the private key under caller-chosen resource policy and returns
    /// the public key that belongs to it.
    ///
    /// Same operation and guarantees as [`PrivateKey::into_public_key`], with
    /// the two limits in place of its defaults. Pass the `kdf_limit` the key
    /// pair was generated under ([`KeyPairGenerator::kdf_limit`]), and a
    /// `key_read_limits` that admits the wrapped secret when it is larger than
    /// the default cap; that is the only [`KeyReadLimits`] cap a `private.key`
    /// uses. Limits that let [`PrivateKeyDecryptor`] open a key file also let
    /// this method open it.
    ///
    /// # Errors
    ///
    /// The same errors as [`PrivateKey::into_public_key`], measured against the
    /// supplied limits rather than the defaults.
    pub fn into_public_key_with_limits(
        self,
        kdf_limit: KdfLimit,
        key_read_limits: KeyReadLimits,
        on_event: impl Fn(&ProgressEvent),
    ) -> Result<PublicKey, CryptoError> {
        // The result is built with `PublicKey::from_x25519_bytes`, which tags
        // the value with this build's writer keypair suite, because raw bytes
        // carry no suite marker. That is only correct while every readable
        // `private.key` belongs to that suite: otherwise this method would
        // return an older-suite key tagged as the writer's, and
        // `to_recipient_string` would re-encode it under the wrong version
        // byte — the opposite of what a caller recovering a lost `public.key`
        // needs. Adding a `KeypairSuite` variant makes this match
        // non-exhaustive, which is the signal to thread the file's own suite
        // through the unlock instead of relying on there being one.
        const _: () = match crate::format::WRITER_KEYPAIR_SUITE {
            crate::format::KeypairSuite::V1 => (),
        };
        let (key_file_path, passphrase) = self.into_key_file_parts();
        // Same order as `PrivateKeyDecryptor::decrypt`: a passphrase outside
        // the fixed bound is a caller error, reported before the key file is
        // read, so both unlock routes answer it the same way.
        validate_passphrase(&passphrase)?;
        let opened = recipient::native::x25519::open_x25519_key_file(
            &key_file_path,
            &passphrase,
            Some(&kdf_limit),
            key_read_limits,
            &on_event,
        )?;
        // Both secrets have had their last use by this point: the unlock is the
        // passphrase's, and this operation never needs the key file's own
        // secret. Drop them here rather than at the end of the function.
        drop(passphrase);
        drop(opened.secret);
        PublicKey::from_x25519_bytes(opened.public)
    }
}

// ─── Key generation ─────────────────────────────────────────────────────────

/// Builder for X25519 key-pair generation.
///
/// Mirrors the [`Encryptor`] builder pattern: pick the passphrase at
/// construction, optionally override the Argon2id parameters used to
/// seal the resulting `private.key`, then call [`KeyPairGenerator::write`]
/// with the destination directory.
///
/// The free function [`generate_key_pair`] is a thin convenience wrapper
/// around this builder for callers that do not need to override KDF
/// parameters.
#[derive(Debug)]
#[non_exhaustive]
pub struct KeyPairGenerator {
    passphrase: Passphrase,
    kdf_params: Option<KdfParams>,
    kdf_limit: Option<KdfLimit>,
}

impl KeyPairGenerator {
    /// Constructs a key-pair generator with the passphrase that will be
    /// used to seal the resulting `private.key`. The passphrase is
    /// checked against the fixed bound of 1 to 4,096 bytes when
    /// [`KeyPairGenerator::write`] runs; constructing this builder is
    /// infallible.
    pub fn with_passphrase(passphrase: Passphrase) -> Self {
        Self {
            passphrase,
            kdf_params: None,
            kdf_limit: None,
        }
    }

    /// Overrides the Argon2id parameters used to seal `private.key`.
    /// If unset, the generator uses [`KdfParams::default`] (1 GiB memory,
    /// time_cost 4, parallelism 4).
    ///
    /// Same production memory floor as [`Encryptor::kdf_params`]: a
    /// `params.mem_cost` below the 19 MiB production memory floor rejects
    /// at [`KeyPairGenerator::write`] time with
    /// [`CryptoError::KdfBelowWriteFloor`], so a caller cannot seal a
    /// `private.key` with weak Argon2id memory; the floor is hard and has
    /// no override.
    ///
    /// # Default-decrypt round-trip
    ///
    /// `kdf_params` is also checked at [`KeyPairGenerator::write`] time
    /// against the writer's [`KdfLimit`] policy. By default, memory is capped
    /// at 1 GiB and combined work at the writer's own budget, while time cost
    /// and lanes are capped at the format maximum, so [`KdfParams::default`]
    /// is accepted. A value above the effective policy rejects with the
    /// matching typed cap error. To write a `private.key` with memory above
    /// 1 GiB or more total work than [`KdfParams::default`], or to use a
    /// deliberately tightened policy, configure
    /// [`KeyPairGenerator::kdf_limit`] and configure the unlocking
    /// [`PrivateKeyDecryptor`] with a compatible
    /// [`PrivateKeyDecryptor::kdf_limit`].
    pub fn kdf_params(mut self, params: KdfParams) -> Self {
        self.kdf_params = Some(params);
        self
    }

    /// Sets the writer-side KDF resource policy for sealing `private.key`.
    ///
    /// The policy caps Argon2id memory cost, time cost, lane count, and
    /// combined work before key generation begins. The default policy accepts
    /// [`KdfParams::default`], which sits exactly at the default work budget,
    /// and rejects memory above 1 GiB unless the caller opts into a higher
    /// memory cap. Time cost and lanes default to the format maximum, so
    /// they only reject when the caller tightens them.
    ///
    /// Use this builder together with [`KeyPairGenerator::kdf_params`] to raise
    /// the memory or work ceiling, or to tighten any dimension. Raising memory
    /// does not raise the work budget, so parameters above
    /// [`KdfParams::default`]'s work need [`KdfLimit::max_work`] as well. The
    /// receiving [`PrivateKeyDecryptor`] must be configured via
    /// [`PrivateKeyDecryptor::kdf_limit`] with a policy that accepts the same
    /// parameters.
    pub fn kdf_limit(mut self, limit: KdfLimit) -> Self {
        self.kdf_limit = Some(limit);
        self
    }

    /// Generates the X25519 key pair and writes `private.key` +
    /// `public.key` into `output_dir`.
    ///
    /// Both files are written and synced before either receives its final
    /// name. `private.key` is committed first, and the output directory is
    /// flushed after each commit. This order prevents process interruption
    /// from leaving a usable `public.key` without its matching `private.key`.
    ///
    /// On filesystems that support directory flushing, the same guarantee
    /// covers power loss, and a successful return means the two files and
    /// their directory entries have reached stable storage. Other filesystems
    /// depend on their own ordering after power loss.
    ///
    /// # Errors
    ///
    /// Returns [`CryptoError::InvalidInput`] if the passphrase is empty or too
    /// long, KDF parameters are outside the accepted writer policy, or either
    /// key file already exists. It is also returned when, after a commit, a
    /// key file's path no longer leads to the file just written; committed key
    /// files are kept.
    ///
    /// Returns [`CryptoError::Io`] for filesystem failures, including a
    /// directory flush failure or a committed key file that carries more than
    /// one filesystem name. If the flush after committing
    /// `public.key` fails, the method makes a best-effort attempt to remove
    /// `public.key` but keeps `private.key`. Removing both without a successful
    /// directory flush could leave only the public key after power loss. A
    /// remaining `private.key` is safe to delete. An error returned after a
    /// commit can leave one or both complete key files for the caller to
    /// inspect; its message names each key file that is complete. If a
    /// removal cannot be confirmed — the key file was replaced during the
    /// operation, or it still had another name — the error message says so,
    /// and for a key file that had already been committed it first says that
    /// a complete key file was committed.
    pub fn write(
        self,
        output_dir: impl AsRef<Path>,
        on_event: impl Fn(&ProgressEvent),
    ) -> Result<KeyGenOutcome, CryptoError> {
        validate_passphrase(&self.passphrase)?;
        let kdf_params = self.kdf_params.unwrap_or_default();
        let kdf_limit = self.kdf_limit.unwrap_or_default();
        // Moved in, not borrowed: `protocol::generate_key_pair` scrubs it as
        // soon as `private.key` is sealed, before the files reach disk.
        let (private_key_path, public_key_path, recipient_string, fingerprint) =
            protocol::generate_key_pair(
                self.passphrase,
                &kdf_params,
                Some(&kdf_limit),
                output_dir.as_ref(),
                &on_event,
            )?;
        Ok(KeyGenOutcome {
            private_key_path,
            public_key_path,
            recipient_string,
            fingerprint,
        })
    }
}

/// Generates and stores an X25519 key pair for public-key
/// (recipient) encryption.
///
/// Writes `private.key` (passphrase-wrapped at rest) and `public.key`
/// (UTF-8 `fcr1…` recipient string) into `output_dir`. Returns the
/// final paths plus the SHA3-256 fingerprint of the public key.
///
/// Thin convenience wrapper around [`KeyPairGenerator`]. Callers that
/// need to override Argon2id parameters should use the builder directly:
/// `KeyPairGenerator::with_passphrase(pass).kdf_params(p).write(dir, ev)`.
///
/// # Errors
///
/// Returns the same errors as [`KeyPairGenerator::write`].
///
/// # Examples
///
/// ```no_run
/// use ferrocrypt::{generate_key_pair, Passphrase};
/// let pass = Passphrase::new("protect-my-key");
/// let outcome = generate_key_pair("./keys", pass, |ev| eprintln!("{ev}"))?;
/// println!("Fingerprint: {}", outcome.fingerprint);
/// # Ok::<(), ferrocrypt::CryptoError>(())
/// ```
pub fn generate_key_pair(
    output_dir: impl AsRef<Path>,
    passphrase: Passphrase,
    on_event: impl Fn(&ProgressEvent),
) -> Result<KeyGenOutcome, CryptoError> {
    KeyPairGenerator::with_passphrase(passphrase).write(output_dir, on_event)
}

// ─── Recipient-mode probe ───────────────────────────────────────────────────

/// Cheap structural probe of an `.fcr` file's recipient list. **Not a
/// security claim.**
///
/// Performs a single bounded header parse on one file handle (no path reopen
/// between magic check and header read). It does not run a KDF, perform a
/// private-key operation, prompt for credentials, verify the header MAC, or
/// decrypt payload bytes. Allocations are bounded by [`HeaderReadLimits`].
///
/// A positive result is **not** evidence that the file is authentic,
/// decryptable, untampered, or well-formed beyond the structural shape
/// required to classify it. A canonical header that would later fail
/// recipient unwrap or MAC verify still returns `Ok(Some(_))` here — those
/// checks require running the full decrypt. Use only for UI / routing hints;
/// for an authenticated mode value see [`AuthenticatedRecipientMode`] on
/// [`DecryptOutcome`].
///
/// Returns `Ok(None)` if the path is a directory or the file does not open with
/// the 4-byte FerroCrypt magic, an empty file or one shorter than the magic
/// included. These cases mean "this isn't a FerroCrypt file at all" — callers
/// route to plaintext encrypt. [`Decryptor::open`] refuses a file without the
/// magic: with [`FormatDefect::Truncated`](crate::FormatDefect::Truncated) when
/// it is shorter than the 12-byte `.fcr` prefix, and with
/// [`FormatDefect::BadMagic`](crate::FormatDefect::BadMagic) otherwise. It
/// refuses a directory with [`CryptoError::InvalidInput`].
///
/// Returns `Ok(Some(UnauthenticatedRecipientMode))` when the prefix matches
/// and the header parses and classifies cleanly. The mode is derived from
/// the recipient list: exactly one native `argon2id` recipient maps to
/// [`UnauthenticatedRecipientMode::Passphrase`], and one or more supported
/// `x25519` recipients with no `argon2id` recipient map to
/// [`UnauthenticatedRecipientMode::PublicKey`].
///
/// Returns [`CryptoError::InvalidFormat`] when the magic matches but the
/// prefix or header is malformed (wrong kind, reserved version byte or flags,
/// oversized `header_len`, malformed recipient entries, etc.), and
/// [`CryptoError::UnsupportedVersion`] for an outer-container version this
/// release does not read. The probe therefore enforces the same structural
/// invariants the decrypt path would, so corrupt or attacker-modified files
/// surface their specific diagnostic at probe time.
///
/// Returns typed recipient-classification errors when the recipient list is
/// structurally valid but cannot be classified:
/// [`CryptoError::UnknownCriticalRecipient`] for an unknown critical
/// recipient, [`CryptoError::IncompatibleRecipients`] for an illegal mix,
/// [`CryptoError::NoSupportedRecipient`] when no recipient is of a supported
/// type, and [`CryptoError::InvalidKdfParams`] for a passphrase recipient
/// whose stored Argon2id parameters are out of range.
///
/// # Errors
///
/// Returns [`CryptoError::InputPath`] if the file does not exist, and
/// [`CryptoError::Io`] for other open or read failures. Returns
/// [`CryptoError::InvalidInput`] if the path is not a regular file (for
/// example a FIFO or device node) — such inputs are refused without
/// blocking. Returns [`CryptoError::InvalidFormat`] when the magic matches
/// but the prefix, header, or recipient entries are malformed,
/// [`CryptoError::UnsupportedVersion`] for an outer-container version this
/// release does not read, [`CryptoError::UnknownCriticalRecipient`],
/// [`CryptoError::IncompatibleRecipients`], or
/// [`CryptoError::NoSupportedRecipient`] when the recipient list cannot be
/// classified, and [`CryptoError::InvalidKdfParams`] when a passphrase
/// recipient's stored Argon2id parameters are outside the bounds `FORMAT.md`
/// §2.2 permits. Returns cap-exceeded variants when the declared
/// header shape, or the aggregate header-MAC work its recipient list implies,
/// exceeds [`HeaderReadLimits::default`].
pub fn probe_recipient_mode(
    file_path: impl AsRef<Path>,
) -> Result<Option<UnauthenticatedRecipientMode>, CryptoError> {
    probe_recipient_mode_with_limits(file_path, HeaderReadLimits::default())
}

/// Same as [`probe_recipient_mode`] but uses the supplied
/// [`HeaderReadLimits`] for the structural header read instead of the
/// conservative defaults.
///
/// Use this when probing files whose recipient strings, recipient counts,
/// or header lengths legitimately exceed the default local caps (for example,
/// forward-compatible files with larger future recipient bodies). All other
/// behavior — directory short-circuit, magic-byte fast path, typed-error
/// surface, and "not a security claim" semantics — is identical.
///
/// # Errors
///
/// Returns the same errors as [`probe_recipient_mode`], but applies the
/// supplied [`HeaderReadLimits`] instead of the default caps.
pub fn probe_recipient_mode_with_limits(
    file_path: impl AsRef<Path>,
    limits: HeaderReadLimits,
) -> Result<Option<UnauthenticatedRecipientMode>, CryptoError> {
    use std::io::Read;
    let path = file_path.as_ref();

    let Some(mut file) = open_header_input(path)? else {
        return Ok(None);
    };

    // Peek the 4-byte magic. Anything that doesn't claim to be a
    // FerroCrypt file (empty, too short, wrong magic) routes to
    // plaintext-encrypt as `Ok(None)`. Once magic matches, `Ok(None)`
    // is no longer reachable: a magic-claiming file must surface as
    // a valid header or a typed structural error.
    let mut magic_buf = [0u8; format::MAGIC_SIZE];
    let mut filled = 0;
    while filled < magic_buf.len() {
        match file.read(&mut magic_buf[filled..]) {
            Ok(0) => break,
            Ok(n) => filled += n,
            Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
            Err(e) => return Err(CryptoError::Io(e)),
        }
    }
    if filled < magic_buf.len() || magic_buf != format::MAGIC {
        return Ok(None);
    }

    // Magic matched. Run the structural reader on the same handle, which
    // `from_file` rewinds: re-opening the path would leave a window for it to
    // be swapped between the checks. Structural classification and resource
    // policy only — the same preflight the decrypt path runs, so this probe
    // cannot report a file the reader would then refuse under these limits.
    // No header MAC and no recipient unwrap happen here.
    let session = protocol::DecryptSession::from_file(file, limits)?;
    Ok(Some(session.mode()))
}

/// Opens `path` for a header read, or returns `None` when it names a
/// directory, so the probe and [`Decryptor::open`] treat directories alike on
/// every platform. Where a directory opens, as on Unix, the opened handle
/// decides, which leaves no window for the path to change. Where the open
/// refuses a directory with a permission error, as on Windows, a look at the
/// path tells that error apart from a real one.
///
/// [`paths::open_input_file`] refuses FIFOs, sockets, and device nodes
/// without blocking, so an attacker-placed FIFO cannot hold the caller inside
/// `open(2)`.
fn open_header_input(path: &Path) -> Result<Option<std::fs::File>, CryptoError> {
    let file = match paths::open_input_file(path) {
        Ok(file) => file,
        Err(CryptoError::Io(error))
            if error.kind() == std::io::ErrorKind::PermissionDenied && path.is_dir() =>
        {
            return Ok(None);
        }
        Err(error) => return Err(error),
    };
    if file.metadata().map_err(CryptoError::Io)?.is_dir() {
        return Ok(None);
    }
    Ok(Some(file))
}

// ─── Filename + key-file helpers ────────────────────────────────────────────

/// Returns the default encrypted filename for a given input path.
///
/// The path is inspected on the filesystem, because the rule differs by kind:
/// a directory keeps its whole name, so `my.photos` maps to `my.photos.fcr`,
/// while anything else — a regular file, or a path that does not exist — is
/// reduced to its stem, so `secrets.txt` maps to `secrets.fcr`. An input of
/// `.` or `..` takes the name of the directory it points at. The answer
/// therefore describes the path as it is now. [`Encryptor::write`] derives the
/// name itself and commits without overwriting, so a stale answer here cannot
/// cost the caller a file.
///
/// # Errors
///
/// Returns [`CryptoError::InvalidInput`] if the path has no usable file name or
/// contains a non-UTF-8 file name, and [`CryptoError::Io`] if the path cannot
/// be inspected.
pub fn default_encrypted_filename(input_path: impl AsRef<Path>) -> Result<String, CryptoError> {
    let base_name = paths::encryption_base_name(input_path)?;
    Ok(format!("{}.{}", base_name, ENCRYPTED_EXTENSION))
}

/// Validates that a file is a well-formed FerroCrypt `private.key` file.
///
/// A file that starts with `fcr1`, the start of every recipient string, is
/// refused first, as a `public.key`, with
/// [`FormatDefect::WrongKeyFileType`](crate::FormatDefect::WrongKeyFileType),
/// even when it is shorter than the fixed header. The cleartext structure is
/// then checked in this order: the size of the 90-byte fixed header, magic
/// bytes, key-file kind, version, flags, length fields, KDF parameters, total
/// file size, type name, and the X25519 public-material and wrapped-secret
/// lengths. A file whose size differs from what its header declares is
/// therefore malformed whatever its type name. This does **not** attempt to
/// decrypt the key and does not require a passphrase.
///
/// Companion to [`validate_public_key_file`]. Applies no resource caps of
/// its own: the verdict follows what `FORMAT.md` §8 allows, not what a
/// default reader would accept.
///
/// # Errors
///
/// Returns [`CryptoError::InputPath`] if the file does not exist, and
/// [`CryptoError::Io`] for other read failures. Returns
/// [`CryptoError::InvalidFormat`] or [`CryptoError::UnsupportedVersion`] if the
/// file is not a supported private key, is malformed, or is a public key, and
/// [`CryptoError::InvalidKdfParams`] if its stored KDF parameters are outside
/// the `FORMAT.md` §2.2 bounds. Returns [`CryptoError::UnsupportedKeyType`] for
/// a well-formed private key of a key type this build does not support.
pub fn validate_private_key_file(key_file: impl AsRef<Path>) -> Result<(), CryptoError> {
    // Validation applies no resource policy, so the read admits the largest
    // wrapped secret the format allows.
    let data = crate::key::files::read_private_key_bytes(
        key_file.as_ref(),
        KeyReadLimits::PRIVATE_KEY_WRAPPED_SECRET_LEN_STRUCTURAL_MAX,
    )?;
    recipient::native::x25519::validate_private_key_shape(&data)
}

/// Validates that a file is a well-formed FerroCrypt `public.key`
/// text file.
///
/// Checks the canonical `fcr1…` recipient string grammar, including Bech32
/// checksum, HRP, typed payload lengths, type name, key-material length, and
/// internal SHA3-256 checksum. Does **not** require a passphrase. If the caller
/// accidentally points this at a binary `private.key`,
/// [`FormatDefect::WrongKeyFileType`](crate::FormatDefect::WrongKeyFileType) is
/// returned instead of a UTF-8 decode error, unless the file is longer than
/// 20,001 bytes, the most a `public.key` can hold: `FORMAT.md` §7.1 checks the
/// size first, so such a file is reported as
/// [`FormatDefect::MalformedPublicKey`](crate::FormatDefect::MalformedPublicKey).
///
/// Companion to [`validate_private_key_file`]. Applies no resource caps
/// of its own: the verdict follows what `FORMAT.md` §7 allows, not what
/// a default reader would accept.
///
/// # Errors
///
/// Returns [`CryptoError::InputPath`] if the file does not exist, and
/// [`CryptoError::Io`] for other read failures. Returns
/// [`CryptoError::InvalidFormat`] if the text file or recipient string is
/// malformed, beyond the structural ceiling, or is a private key. Returns
/// [`CryptoError::UnsupportedVersion`] for a public key from an
/// unsupported keypair suite. Returns
/// [`CryptoError::UnsupportedKeyType`] for a valid public key of a
/// key type this build does not support.
pub fn validate_public_key_file(key_file: impl AsRef<Path>) -> Result<(), CryptoError> {
    // No resource policy of its own: this validates structure only, so the
    // recipient-string cap runs at its structural maximum.
    PublicKey::from_key_file_with_limits(key_file, KeyReadLimits::structural_max()).map(|_| ())
}

// ─── Internal validators ────────────────────────────────────────────────────

/// Enforces the `FORMAT.md` §2.2 passphrase byte-length bound (1 to
/// [`MAX_PASSPHRASE_LEN_BYTES`](crate::crypto::kdf::MAX_PASSPHRASE_LEN_BYTES),
/// inclusive) at the public boundary, so an out-of-bound passphrase is
/// rejected before any input or archive work. Shares
/// [`crate::crypto::kdf::check_passphrase_len`] with the pre-Argon2id
/// gates, so the boundary and the key-derivation paths cannot drift.
pub(crate) fn validate_passphrase(passphrase: &Passphrase) -> Result<(), CryptoError> {
    crate::crypto::kdf::check_passphrase_len(passphrase.expose())
}