ferrocrypt 0.3.0-beta.1

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
//! 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 in v1, where every
//!   [`PublicKey`] is X25519) reject as
//!   [`CryptoError::IncompatibleRecipients`].
//!
//! ## Decryptor type-safety
//!
//! [`Decryptor::open`] inspects the file's recipient list (no crypto)
//! 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 actually use, so a mismatched-credential
//! call — e.g. passing a [`PrivateKey`] to a passphrase-sealed file — is
//! a compile error rather than a runtime "no supported recipient" failure.

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

use secrecy::{ExposeSecret as _, SecretString};

use crate::archive::{self, ArchiveLimits, IncompleteOutputPolicy};
use crate::container::{self, HeaderReadLimits};
use crate::crypto::kdf::{KdfLimit, KdfParams};
use crate::error::FormatDefect;
use crate::format;
use crate::fs::paths;
use crate::key::files::KeyFileKind;
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, secrecy::SecretString};
/// let pass = SecretString::from("correct horse battery staple".to_string());
/// 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(SecretString),
    Recipients(Vec<PublicKey>),
}

impl Encryptor {
    /// Configures passphrase encryption.
    ///
    /// The resulting `.fcr` contains exactly one native `argon2id`
    /// recipient. The passphrase is checked for non-emptiness when
    /// [`Encryptor::write`] runs; constructing this builder is
    /// infallible.
    pub fn with_passphrase(passphrase: SecretString) -> 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.
    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.
    ///
    /// # 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.
    ///
    /// # Errors
    ///
    /// Returns [`CryptoError::EmptyRecipientList`] if the iterator is empty.
    /// All public keys in the current v1 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: Vec<PublicKey> = public_keys.into_iter().collect();
        if public_keys.is_empty() {
            return Err(CryptoError::EmptyRecipientList);
        }
        // v1 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). Callers MUST NOT lower these
    /// parameters in production code paths — the override exists for
    /// callers with specific tuning needs (e.g. lower-spec embedded
    /// targets) and for in-tree tests via the workspace-internal
    /// `ferrocrypt-test-support` crate.
    ///
    /// # Default-decrypt round-trip
    ///
    /// `kdf_params.mem_cost` is checked at [`Encryptor::write`] time
    /// against the writer's [`KdfLimit`] ceiling (defaults to
    /// [`KdfLimit::default`] = 1 GiB, matching [`KdfParams::default`]).
    /// `params` whose `mem_cost` exceeds that ceiling reject with
    /// [`CryptoError::KdfResourceCapExceeded`]. To produce a `.fcr` with
    /// `mem_cost` above 1 GiB, the caller MUST opt in via
    /// [`Encryptor::kdf_limit`] with a matching [`KdfLimit`]; the
    /// decryptor MUST be configured the same way via
    /// [`PassphraseDecryptor::kdf_limit`] 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.
    ///
    /// All three axes are checked before encryption work begins:
    /// `recipient_count`, canonical native recipient `body_len`, and the
    /// exact v1 `header_len` that the writer will emit (`ext_len = 0` for
    /// current writers). 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 ceiling for accepted `kdf_params.mem_cost`.
    ///
    /// By default the writer requires
    /// `kdf_params.mem_cost <= KdfLimit::default().max_mem_cost_kib`
    /// (1 GiB) so a default [`PassphraseDecryptor`] can unwrap the
    /// produced `.fcr`. Use this builder together with
    /// [`Encryptor::kdf_params`] to raise the ceiling; the receiving
    /// passphrase decryptor MUST be configured via
    /// [`PassphraseDecryptor::kdf_limit`] with a matching
    /// [`KdfLimit`].
    ///
    /// 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::InvalidInput`] for invalid input paths, output
    /// conflicts, unsupported archive entries, empty passphrases, archive cap
    /// violations, or invalid KDF settings. Returns [`CryptoError::Io`] for
    /// filesystem failures. 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();
        let save_as = self.save_as.as_deref();

        // Cheap caller-supplied invariant first so an empty passphrase
        // surfaces before any filesystem syscall — fail fast on the
        // O(1) check before the kernel-side syscall.
        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. Adding a new cap = add one method on
        // the limit type; both sides pick it up.
        match &self.state {
            EncryptorState::Recipients(rs) => {
                preflight_header_write_limits(
                    header_read_limits,
                    rs.len(),
                    NativeRecipientType::X25519,
                )?;
            }
            EncryptorState::Passphrase(_) => {
                preflight_header_write_limits(
                    header_read_limits,
                    1,
                    NativeRecipientType::Argon2id,
                )?;
                let kdf_params = self.kdf_params.unwrap_or_default();
                kdf_params.validate_for_write(Some(&kdf_limit))?;
            }
        }

        archive::validate_encrypt_input(input)?;

        let output_path = match self.state {
            EncryptorState::Passphrase(passphrase) => {
                let recipient = recipient::argon2id::PassphraseRecipient {
                    passphrase: &passphrase,
                    kdf_params: self.kdf_params.unwrap_or_default(),
                };
                protocol::encrypt(
                    std::slice::from_ref(&recipient),
                    archive_limits,
                    input,
                    output_dir,
                    save_as,
                    &on_event,
                )?
            }
            EncryptorState::Recipients(public_keys) => {
                // Resolve each PublicKey to its 32-byte material once.
                // The local Vec 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_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,
                    input,
                    output_dir,
                    save_as,
                    &on_event,
                )?
            }
        };

        Ok(EncryptOutcome { output_path })
    }
}

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

/// Type-safe entry point for decryption.
///
/// [`Decryptor::open`] reads the `.fcr` header (no crypto) 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`] plus its unlock
///   passphrase.
///
/// A mismatched-credential call — e.g. trying to decrypt a passphrase-sealed
/// file with a [`PrivateKey`] — is therefore a compile error rather than a
/// runtime [`CryptoError::DecryptorModeMismatch`] failure.
#[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.
    ///
    /// # Errors
    ///
    /// Returns [`CryptoError::InputPath`] if `input` does not exist and
    /// [`CryptoError::InvalidInput`] if `input` is a directory. Files that do
    /// not contain a FerroCrypt header return [`CryptoError::InvalidFormat`]
    /// with [`FormatDefect::BadMagic`]. Malformed headers, unsupported
    /// versions, unknown critical recipients, and illegal recipient mixes return
    /// their corresponding `CryptoError` or [`FormatDefect`] variants.
    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
    /// (e.g. forward-compatibility with future fat-recipient native
    /// types) 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 input = input.to_path_buf();
        validate_input_path(&input)?;
        if input.is_dir() {
            return Err(CryptoError::InvalidInput(format!(
                "Cannot decrypt a directory: {}",
                input.display()
            )));
        }
        let mode =
            probe_recipient_mode_with_limits(&input, header_read_limits.unwrap_or_default())?
                .ok_or(CryptoError::InvalidFormat(FormatDefect::BadMagic))?;
        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,
                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 maximum Argon2id memory cost accepted from the file header.
    ///
    /// If unset, the decrypt path applies [`KdfLimit::default`].
    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`]: a failed
    /// decrypt leaves no plaintext residue under `output_dir`. Pass
    /// [`IncompleteOutputPolicy::RetainOnError`] for backup-recovery
    /// or forensic flows where partial output is more useful than no
    /// output. See [`IncompleteOutputPolicy::RetainOnError`] for the
    /// truncation-prefix caveat callers MUST acknowledge 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 for non-emptiness, 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 passphrase, archive
    /// cap violations, output conflicts, or unsafe archived paths. Returns
    /// [`CryptoError::KdfResourceCapExceeded`] for rejected KDF costs.
    /// 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::Io`] for filesystem failures.
    pub fn decrypt(
        self,
        passphrase: SecretString,
        output_dir: impl AsRef<Path>,
        on_event: impl Fn(&ProgressEvent),
    ) -> Result<DecryptOutcome, CryptoError> {
        validate_passphrase(&passphrase)?;
        let credential = recipient::argon2id::PassphraseCredential {
            passphrase: &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>,
    archive_limits: Option<ArchiveLimits>,
    header_read_limits: Option<HeaderReadLimits>,
    incomplete_output_policy: Option<IncompleteOutputPolicy>,
}

impl PrivateKeyDecryptor {
    /// Sets the maximum Argon2id memory cost accepted when unlocking
    /// `private.key`.
    ///
    /// If unset, the decrypt path applies [`KdfLimit::default`].
    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`]: a failed
    /// decrypt leaves no plaintext residue under `output_dir`. Pass
    /// [`IncompleteOutputPolicy::RetainOnError`] for backup-recovery
    /// or forensic flows where partial output is more useful than no
    /// output. See [`IncompleteOutputPolicy::RetainOnError`] for the
    /// truncation-prefix caveat callers MUST acknowledge 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 `private_key_passphrase`, 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 `private_key_passphrase`,
    /// archive cap violations, output conflicts, or unsafe archived paths.
    /// Returns [`CryptoError::InvalidFormat`] or
    /// [`CryptoError::KeyFileUnlockFailed`] if the private key is malformed,
    /// the wrong kind, tampered, or protected by a different passphrase.
    /// Returns [`CryptoError::KdfResourceCapExceeded`] for rejected
    /// `private.key` KDF costs. Returns authentication errors such as
    /// [`CryptoError::RecipientUnwrapFailed`],
    /// [`CryptoError::HeaderMacFailedAfterUnwrap`],
    /// [`CryptoError::NoSupportedRecipient`], [`CryptoError::PayloadTampered`],
    /// or [`CryptoError::PayloadTruncated`] when no recipient unlocks the file
    /// or the file is modified. Returns [`CryptoError::Io`] for filesystem
    /// failures.
    pub fn decrypt(
        self,
        private_key: PrivateKey,
        private_key_passphrase: SecretString,
        output_dir: impl AsRef<Path>,
        on_event: impl Fn(&ProgressEvent),
    ) -> Result<DecryptOutcome, CryptoError> {
        validate_passphrase(&private_key_passphrase)?;
        // No early progress event here. `open_x25519_private_key` reads
        // and structurally validates `private.key` first; only when it
        // is about to run Argon2id does it emit
        // `UnlockingPrivateKey` from inside
        // `key::private::open_private_key`. A malformed or wrong-type
        // key file is rejected with no event fired.
        let private_key_bytes = recipient::native::x25519::open_x25519_private_key(
            private_key.key_file_path(),
            &private_key_passphrase,
            self.kdf_limit.as_ref(),
            &on_event,
        )?;
        let decryption_credential = recipient::x25519::X25519Credential { private_key_bytes };
        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();
        let output_path = protocol::decrypt(
            &decryption_credential,
            &self.input,
            output_dir.as_ref(),
            archive_limits,
            header_read_limits,
            incomplete_output_policy,
            &on_event,
        )?;
        Ok(DecryptOutcome {
            output_path,
            recipient_mode: AuthenticatedRecipientMode::public_key(),
        })
    }
}

// ─── 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: SecretString,
    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 for non-emptiness when [`KeyPairGenerator::write`] runs;
    /// constructing this builder is infallible.
    pub fn with_passphrase(passphrase: SecretString) -> 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 misuse caveat as [`Encryptor::kdf_params`]: callers MUST NOT
    /// lower these parameters in production code paths. The override
    /// exists for callers with specific tuning needs (e.g. lower-spec
    /// embedded targets) and for in-tree tests via the workspace-internal
    /// `ferrocrypt-test-support` crate.
    ///
    /// # Default-decrypt round-trip
    ///
    /// `kdf_params.mem_cost` is checked at [`KeyPairGenerator::write`]
    /// time against the writer's [`KdfLimit`] ceiling (defaults to
    /// [`KdfLimit::default`] = 1 GiB, matching [`KdfParams::default`]).
    /// `params` whose `mem_cost` exceeds that ceiling reject with
    /// [`CryptoError::KdfResourceCapExceeded`]. To produce a
    /// `private.key` with `mem_cost` above 1 GiB, the caller MUST opt
    /// in via [`KeyPairGenerator::kdf_limit`] with a matching
    /// [`KdfLimit`]; the unlocking
    /// [`PrivateKeyDecryptor`] MUST also be configured the same way via
    /// [`PrivateKeyDecryptor::kdf_limit`].
    pub fn kdf_params(mut self, params: KdfParams) -> Self {
        self.kdf_params = Some(params);
        self
    }

    /// Sets the writer-side ceiling for accepted `kdf_params.mem_cost`.
    ///
    /// By default the generator requires
    /// `kdf_params.mem_cost <= KdfLimit::default().max_mem_cost_kib`
    /// (1 GiB) so a default [`PrivateKeyDecryptor`] can unlock the
    /// produced `private.key`. Use this builder together with
    /// [`KeyPairGenerator::kdf_params`] to raise the ceiling; the
    /// receiving [`PrivateKeyDecryptor`] MUST be configured via
    /// [`PrivateKeyDecryptor::kdf_limit`] with a matching [`KdfLimit`].
    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`.
    ///
    /// # Errors
    ///
    /// Returns [`CryptoError::InvalidInput`] if the passphrase is empty, KDF
    /// parameters are outside the accepted writer policy, or either key file
    /// already exists. Returns [`CryptoError::Io`] for filesystem failures.
    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();
        // Writer caps mirror reader defaults via the same structural +
        // resource KDF validation the reader uses, so a `private.key`
        // produced here is unlocked by a default
        // `PrivateKeyDecryptor::decrypt`. To go above default, the
        // caller raises both sides explicitly.
        kdf_params.validate_for_write(Some(&kdf_limit))?;
        let (private_key_path, public_key_path, fingerprint) = protocol::generate_key_pair(
            &self.passphrase,
            &kdf_params,
            output_dir.as_ref(),
            &on_event,
        )?;
        Ok(KeyGenOutcome {
            private_key_path,
            public_key_path,
            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, secrecy::SecretString};
/// let pass = SecretString::from("protect-my-key".to_string());
/// 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: SecretString,
    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). No KDF, no private-key operation,
/// no credential prompt, no header-MAC verification, no payload decryption.
/// Capped allocation.
///
/// 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, the file is empty, or the
/// first 4 bytes are not the FerroCrypt magic. These cases mean "this isn't
/// a FerroCrypt file at all" — callers route to plaintext encrypt.
///
/// 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 (bad version / kind / flags, oversized
/// `header_len`, malformed recipient entries, etc.). The probe therefore
/// enforces the same structural invariants the decrypt path would, so
/// bit-rotten or attacker-tampered files surface their specific diagnostic
/// at probe time.
///
/// Returns typed recipient-classification errors when the recipient list is
/// structurally valid but cannot be classified: unknown critical recipients,
/// illegal passphrase mixing, or no supported native recipient.
///
/// # Errors
///
/// Returns [`CryptoError::Io`] if the file cannot be opened or read. Returns
/// [`CryptoError::InvalidFormat`] when the magic matches but the prefix,
/// header, recipient entries, or recipient mixing policy are malformed or
/// unsupported. Returns cap-exceeded variants when the declared header shape
/// 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
/// (forward-compatibility with future fat-recipient native types). All
/// other behavior — directory short-circuit, magic-byte fast path,
/// typed-error surface, "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, Seek, SeekFrom};
    let path = file_path.as_ref();

    // Short-circuit directories up-front so the behavior is uniform across
    // platforms. Without this pre-check, Unix lets us open a directory and
    // only fails at `read()` with `IsADirectory`, while Windows' `CreateFile`
    // refuses to open directories outright (requires `FILE_FLAG_BACKUP_SEMANTICS`)
    // and surfaces as `ERROR_ACCESS_DENIED` — indistinguishable from a real
    // permission error. One explicit check, one answer, on every platform.
    if path.is_dir() {
        return Ok(None);
    }

    let mut file = fs::File::open(path)?;

    // 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,
            // Defensive: on Unix, a TOCTOU race could swap the pre-checked
            // path for a directory between `is_dir()` and `File::open()`.
            // Keep the runtime handler so the race is still classified
            // correctly instead of surfacing as a generic I/O error.
            Err(e) if e.kind() == std::io::ErrorKind::IsADirectory => return Ok(None),
            Err(e) => return Err(CryptoError::Io(e)),
        }
    }
    if filled < magic_buf.len() || magic_buf != format::MAGIC {
        return Ok(None);
    }

    // Magic matched. Rewind the same handle and run the structural
    // reader against the full prefix + header. Using `seek` instead
    // of dropping and re-opening avoids both an extra syscall and a
    // TOCTOU window where the path could be swapped between checks.
    file.seek(SeekFrom::Start(0))?;
    let parsed = container::read_encrypted_header(&mut file, limits)?;

    // Structural classification only. `classify_recipient_mode`
    // does not verify the header MAC or run any recipient unwrap.
    let mode = recipient::classify_recipient_mode(&parsed.recipient_entries)?;
    Ok(Some(mode))
}

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

/// Returns the default encrypted filename for a given input path.
///
/// For example, a regular file named `secrets.txt` maps to `secrets.fcr`; a
/// directory named `secrets` maps to `secrets.fcr`.
///
/// # Errors
///
/// Returns [`CryptoError::InvalidInput`] if the path has no usable file name or
/// contains a non-UTF-8 file name.
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.
///
/// Checks the cleartext v1 structure: magic bytes, version, key-file kind,
/// flags, length fields, X25519 type name, X25519 public-material length, and
/// total file size. This does **not** attempt to decrypt the key and does not
/// require a passphrase. If the caller accidentally points this at a text
/// `public.key`, [`FormatDefect::WrongKeyFileType`] is returned instead of a
/// generic key-file parse error.
///
/// # Errors
///
/// Returns [`CryptoError::Io`] if the file cannot be read. Returns
/// [`CryptoError::InvalidFormat`] or [`CryptoError::UnsupportedVersion`] if the
/// file is not a v1 private key, is malformed, or is a public key.
pub fn validate_private_key_file(key_file: impl AsRef<Path>) -> Result<(), CryptoError> {
    let data = paths::read_file_capped(
        key_file.as_ref(),
        crate::key::private::PRIVATE_KEY_FILE_READ_CAP_BYTES,
        || CryptoError::InvalidFormat(FormatDefect::MalformedPrivateKey),
    )?;
    if matches!(KeyFileKind::classify(&data), KeyFileKind::Public) {
        return Err(CryptoError::InvalidFormat(FormatDefect::WrongKeyFileType));
    }
    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`] is
/// returned instead of a UTF-8 decode error.
///
/// Companion to [`validate_private_key_file`].
///
/// # Errors
///
/// Returns [`CryptoError::Io`] if the file cannot be read. Returns
/// [`CryptoError::InvalidFormat`], [`CryptoError::InvalidInput`], or
/// [`CryptoError::RecipientStringCapExceeded`] if the text file or recipient
/// string is malformed, unsupported, too large for local policy, or is a private
/// key.
pub fn validate_public_key_file(key_file: impl AsRef<Path>) -> Result<(), CryptoError> {
    PublicKey::from_key_file(key_file).validate()
}

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

/// Enforces the exact `.fcr` header shape a v1 writer will emit against
/// the caller-supplied [`HeaderReadLimits`]. Mirrors the reader-side cap
/// checks in `container::read_encrypted_header`, but runs before any KDF,
/// ECDH, or output-file work.
///
/// Takes a [`NativeRecipientType`] rather than a `(type_name, body_len)`
/// pair so the type-name / body-length pair is bound by the registry
/// (impossible for a caller to mix `argon2id`'s name with `x25519`'s
/// body length), and so adding a future native recipient updates the
/// preflight automatically through the registry's accessors.
fn preflight_header_write_limits(
    limits: HeaderReadLimits,
    recipient_count: usize,
    native: NativeRecipientType,
) -> Result<(), CryptoError> {
    let type_name = native.type_name();
    let body_len = native.body_len();

    // `RECIPIENT_COUNT_MAX = 4096` fits u16; saturating cast keeps the
    // cap diagnostic honest in the theoretical case of an in-memory
    // list above u16::MAX, while still surfacing the cap-exceeded
    // variant before later structural checks.
    let count_u16: u16 = u16::try_from(recipient_count).unwrap_or(u16::MAX);
    limits.enforce_recipient_count(count_u16)?;

    // body_len is bounded by the canonical native `BODY_LENGTH` (≤ 116
    // in v1), so the saturating cast cannot fire today. Defensive
    // fallback for a hypothetical future plugin recipient with a body
    // above `u32::MAX`: `enforce_recipient_body_len` rejects against
    // the per-entry cap (≤ `BODY_LEN_STRUCTURAL_MAX = 16 MiB`), so
    // `u32::MAX` always trips the cap.
    let body_len_u32: u32 = u32::try_from(body_len).unwrap_or(u32::MAX);
    limits.enforce_recipient_body_len(body_len_u32)?;

    // Compute the exact `header_len` the writer will emit
    // (`header_fixed + recipient_count * per_entry`, with `ext_len = 0`
    // for v1 writers) and check it against the cap. All checked
    // arithmetic funnels into one shared overflow error.
    let overflow_err = || CryptoError::HeaderLenCapExceeded {
        header_len: u32::MAX,
        local_cap: limits.max_header_len,
    };
    let per_entry = (recipient::entry::ENTRY_HEADER_SIZE as u64)
        .checked_add(type_name.len() as u64)
        .and_then(|v| v.checked_add(body_len as u64))
        .ok_or_else(overflow_err)?;
    let total_entries = (recipient_count as u64)
        .checked_mul(per_entry)
        .ok_or_else(overflow_err)?;
    let header_len_u64 = (format::HEADER_FIXED_SIZE as u64)
        .checked_add(total_entries)
        .ok_or_else(overflow_err)?;
    let header_len = u32::try_from(header_len_u64).unwrap_or(u32::MAX);
    limits.enforce_header_len(header_len)?;

    Ok(())
}

/// Rejects empty passphrases. Shared by every API entry point that
/// takes a passphrase so the CLI, desktop, and library callers see the
/// same error class.
pub(crate) fn validate_passphrase(passphrase: &SecretString) -> Result<(), CryptoError> {
    if passphrase.expose_secret().is_empty() {
        return Err(CryptoError::InvalidInput(
            "Passphrase must not be empty".to_string(),
        ));
    }
    Ok(())
}

/// Rejects non-existent input paths early with a typed error
/// ([`CryptoError::InputPath`]) instead of letting the first I/O syscall
/// surface a less informative `Io(NotFound)`.
pub(crate) fn validate_input_path(input_path: &Path) -> Result<(), CryptoError> {
    if !input_path.exists() {
        return Err(CryptoError::InputPath);
    }
    Ok(())
}