passless-rs 0.13.0

FIDO2 security token emulator
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
use crate::notification::show_verification_notification;
use crate::pin_storage::PinStorage;
use crate::storage::{CredentialFilter, CredentialStorage};
use crate::util::bytes_to_hex;

use passless_core::config::{PinConfig, PinEnforcement, SecurityConfig};

use soft_fido2::{
    Authenticator, AuthenticatorCallbacks, AuthenticatorConfig, AuthenticatorOptions, Credential,
    CredentialRef, CtapCommand, Error as SoftFido2Error, PinState, Result, StatusCode, UpResult,
    UvResult,
};

use std::sync::{Arc, LazyLock, Mutex};
use std::time::{SystemTime, UNIX_EPOCH};

use log::{debug, error, info, warn};

static VERSION: LazyLock<u32> = LazyLock::new(|| {
    let major = env!("CARGO_PKG_VERSION_MAJOR").parse().unwrap_or(0);
    let minor = env!("CARGO_PKG_VERSION_MINOR").parse().unwrap_or(0);
    let patch = env!("CARGO_PKG_VERSION_PATCH").parse().unwrap_or(0);

    (major << 16) | (minor << 8) | patch
});

/// Passless vendor command for resetting built-in UV retries without deleting credentials.
pub const CMD_PASSLESS_RESET_UV_RETRIES: u8 = 0x42;

const RESET_UV_RETRIES_SUBCOMMAND: u8 = 0x01;

fn error_status_byte(error: SoftFido2Error) -> u8 {
    match error {
        SoftFido2Error::CtapError(code) => code,
        error => StatusCode::from(error) as u8,
    }
}

/// Classification of UV retry count transitions for diagnostic logging
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum UvRetryTransition {
    Initialized,
    NoChange,
    NormalChange,
    Low,
    Exhausted,
    Recovered,
}

/// Wrapper to adapt passless PinStorage to soft-fido2 PinStorageCallbacks
///
/// This wrapper intercepts PIN state load/save operations to enforce the configured
/// max_uv_retries limit. Since soft-fido2 hardcodes MAX_UV_RETRIES=3 internally,
/// we clamp the uv_retries value to the configured maximum during persistence.
///
/// It also tracks UV retry transitions to emit actionable warnings when retries
/// approach or reach exhaustion, independent of the storage backend.
struct PinStorageWrapper<P: PinStorage> {
    storage: Arc<Mutex<P>>,
    max_uv_retries: u8,
    last_uv_retries: Mutex<Option<u8>>,
}

impl<P: PinStorage> PinStorageWrapper<P> {
    fn clamp_uv_retries(&self, state: &mut PinState) {
        if state.uv_retries > self.max_uv_retries {
            state.uv_retries = self.max_uv_retries;
        }
    }

    fn classify_uv_transition(old: Option<u8>, new: u8) -> UvRetryTransition {
        match old {
            None => UvRetryTransition::Initialized,
            Some(prev) if prev == new => UvRetryTransition::NoChange,
            Some(prev) if new == 0 && prev > 0 => UvRetryTransition::Exhausted,
            Some(prev) if new == 1 && prev > 1 => UvRetryTransition::Low,
            Some(prev) if new > prev && prev == 0 => UvRetryTransition::Recovered,
            Some(_) => UvRetryTransition::NormalChange,
        }
    }

    fn log_uv_retry_transition(&self, old: Option<u8>, new: u8) {
        match Self::classify_uv_transition(old, new) {
            UvRetryTransition::Initialized => {
                debug!("UV retries initialized: {} remaining", new);
            }
            UvRetryTransition::NoChange => {}
            UvRetryTransition::Exhausted => {
                error!(
                    "UV retries exhausted; built-in user verification is blocked. \
                     Run `passless client pin uv-reset` to restore UV retries"
                );
            }
            UvRetryTransition::Low => {
                warn!(
                    "UV retry limit is almost exhausted: 1 attempt remaining. \
                     Run `passless client pin uv-reset` to restore UV retries"
                );
            }
            UvRetryTransition::Recovered => {
                info!("UV retries restored from 0 to {} (reset/recovery)", new);
            }
            UvRetryTransition::NormalChange => {
                debug!(
                    "UV retries changed: {} -> {} remaining",
                    old.unwrap_or(0),
                    new
                );
            }
        }
    }
}

impl<P: PinStorage + 'static> soft_fido2::PinStorageCallbacks for PinStorageWrapper<P> {
    fn load_pin_state(&self) -> std::result::Result<PinState, soft_fido2::StatusCode> {
        let storage = self
            .storage
            .lock()
            .map_err(|_| soft_fido2::StatusCode::Other)?;
        let mut state = storage.load_pin_state()?;
        self.clamp_uv_retries(&mut state);
        let mut last = self
            .last_uv_retries
            .lock()
            .map_err(|_| soft_fido2::StatusCode::Other)?;
        *last = Some(state.uv_retries);
        Ok(state)
    }

    fn save_pin_state(&self, state: &PinState) -> std::result::Result<(), soft_fido2::StatusCode> {
        let storage = self
            .storage
            .lock()
            .map_err(|_| soft_fido2::StatusCode::Other)?;
        let mut clamped_state = state.clone();
        self.clamp_uv_retries(&mut clamped_state);
        storage.save_pin_state(&clamped_state)?;
        let old = {
            let mut last = self
                .last_uv_retries
                .lock()
                .map_err(|_| soft_fido2::StatusCode::Other)?;
            let old = *last;
            *last = Some(clamped_state.uv_retries);
            old
        };
        self.log_uv_retry_transition(old, clamped_state.uv_retries);
        Ok(())
    }
}

/// Passless authenticator callbacks implementation
pub struct PasslessCallbacks<S: CredentialStorage, P: PinStorage> {
    storage: Arc<Mutex<S>>,
    pin_storage: Option<Arc<Mutex<P>>>,
    security_config: SecurityConfig,
    pin_config: PinConfig,
}

impl<S: CredentialStorage, P: PinStorage> PasslessCallbacks<S, P> {
    pub fn new(
        storage: Arc<Mutex<S>>,
        pin_storage: Option<Arc<Mutex<P>>>,
        security_config: SecurityConfig,
        pin_config: PinConfig,
    ) -> Self {
        Self {
            storage,
            pin_storage,
            security_config,
            pin_config,
        }
    }
}

impl<S: CredentialStorage, P: PinStorage> AuthenticatorCallbacks for PasslessCallbacks<S, P> {
    fn request_up(&self, info: &str, user: Option<&str>, rp: &str) -> Result<UpResult> {
        // Check for E2E test mode (only available in debug builds)
        #[cfg(debug_assertions)]
        {
            if std::env::var("PASSLESS_E2E_AUTO_ACCEPT_UV").is_ok() {
                info!("E2E test mode: Auto-accepting user verification");
                return Ok(UpResult::Accepted);
            }
        }

        let is_registration = info.to_lowercase().contains("registration")
            && !info.to_lowercase().contains("credential excluded");

        let should_verify = if is_registration {
            self.security_config.user_verification_registration
        } else {
            self.security_config.user_verification_authentication
        };

        let storage = match self.storage.lock() {
            Ok(s) => s,
            Err(_) => {
                error!("Failed to acquire storage lock during user verification request");
                return Err(soft_fido2::Error::Other);
            }
        };

        if storage.disable_user_verification() && !is_registration && !should_verify {
            debug!("User verification handled by backend (e.g., GPG): {}", info);
            return Ok(UpResult::Accepted);
        }

        if !should_verify {
            debug!(
                "User verification disabled for {}: {}",
                if is_registration {
                    "registration"
                } else {
                    "authentication"
                },
                info
            );
            return Ok(UpResult::Accepted);
        }

        match show_verification_notification(
            info,
            Some(rp),
            user,
            self.security_config.notification_timeout,
        ) {
            Ok(crate::notification::NotificationResult::Accepted) => Ok(UpResult::Accepted),
            Ok(crate::notification::NotificationResult::Denied) => Ok(UpResult::Denied),
            Err(e) => {
                error!("Failed to show notification: {}", e);
                Err(soft_fido2::Error::Other)
            }
        }
    }

    fn request_uv(&self, info: &str, user: Option<&str>, rp: &str) -> Result<UvResult> {
        #[cfg(debug_assertions)]
        {
            if std::env::var("PASSLESS_E2E_AUTO_ACCEPT_UV").is_ok() {
                info!("E2E test mode: Auto-accepting user verification");
                return Ok(UvResult::Accepted);
            }
        }

        let pin_set;
        let uv_retries;

        if let Some(pin_storage) = &self.pin_storage {
            let storage = pin_storage.lock().map_err(|_| soft_fido2::Error::Other)?;
            match storage.load_pin_state() {
                Ok(state) => {
                    pin_set = state.is_pin_set();
                    uv_retries = Some(state.uv_retries);
                }
                Err(e) => {
                    debug!("Failed to load PIN state for UV request: {:?}", e);
                    pin_set = false;
                    uv_retries = None;
                }
            }
        } else {
            pin_set = false;
            uv_retries = None;
        }

        if let Some(retries) = uv_retries {
            debug!(
                "UV request: pin_set={}, uv_retries={}, enforcement={}, always_uv={}",
                pin_set, retries, self.pin_config.enforcement, self.security_config.always_uv,
            );
            if retries == 0 {
                warn!(
                    "Built-in UV is blocked (0 retries remaining); \
                     falling back to notification-based verification because \
                     pin.enforcement={}",
                    self.pin_config.enforcement,
                );
            }
        }

        if pin_set {
            match self.pin_config.enforcement {
                PinEnforcement::Required => {
                    info!("PIN is set and enforcement=required, denying built-in UV to force PIN");
                    return Ok(UvResult::Denied);
                }
                PinEnforcement::Optional => {
                    if self.security_config.always_uv {
                        info!(
                            "PIN is set, always_uv=true, enforcement=optional, denying built-in UV"
                        );
                        return Ok(UvResult::Denied);
                    }
                    info!(
                        "PIN is set, always_uv=false, enforcement=optional, using notification fallback"
                    );
                }
                PinEnforcement::Never => {
                    info!("PIN is set but enforcement=never, using notification fallback");
                }
            }
        }

        match show_verification_notification(
            info,
            Some(rp),
            user,
            self.security_config.notification_timeout,
        ) {
            Ok(crate::notification::NotificationResult::Accepted) => {
                info!("User verification via notification: accepted");
                Ok(UvResult::AcceptedWithUp)
            }
            Ok(crate::notification::NotificationResult::Denied) => {
                warn!("User verification via notification: denied");
                Ok(UvResult::Denied)
            }
            Err(e) => {
                error!("Failed to show notification: {}", e);
                Err(soft_fido2::Error::Other)
            }
        }
    }

    fn write_credential(&self, credential: &CredentialRef) -> Result<()> {
        info!("Storing credential for RP: {}", credential.rp_id);
        debug!("Credential ID: {}", bytes_to_hex(credential.id));

        let mut storage = match self.storage.lock() {
            Ok(s) => s,
            Err(_) => {
                error!("Failed to acquire storage lock while writing credential");
                return Err(soft_fido2::Error::Other);
            }
        };

        storage.write(*credential)?;
        info!(
            "Credential persisted successfully for RP: {}",
            credential.rp_id
        );
        Ok(())
    }

    fn read_credential(&self, cred_id: &[u8]) -> Result<Option<Credential>> {
        debug!("Reading credential: id={}", bytes_to_hex(cred_id));

        let mut storage = match self.storage.lock() {
            Ok(s) => s,
            Err(_) => {
                error!("Failed to acquire storage lock while reading credential");
                return Err(soft_fido2::Error::Other);
            }
        };

        match storage.read(cred_id) {
            Ok(cred) => {
                debug!("Credential found");
                Ok(Some(cred))
            }
            Err(_) => {
                debug!("Credential not found");
                Ok(None)
            }
        }
    }

    fn delete_credential(&self, cred_id: &[u8]) -> Result<()> {
        info!("Removing credential ID: {}", bytes_to_hex(cred_id));

        let mut storage = match self.storage.lock() {
            Ok(s) => s,
            Err(_) => {
                error!("Failed to acquire storage lock while deleting credential");
                return Err(soft_fido2::Error::Other);
            }
        };

        storage.delete(cred_id)?;
        debug!("Credential removed");
        Ok(())
    }

    fn list_credentials(&self, rp_id: &str, _user_id: Option<&[u8]>) -> Result<Vec<Credential>> {
        info!("Listing credentials for RP: {}", rp_id);

        let mut storage = match self.storage.lock() {
            Ok(s) => s,
            Err(e) => {
                error!(
                    "Failed to acquire storage lock while listing credentials: {}",
                    e
                );
                return Err(soft_fido2::Error::Other);
            }
        };

        let filter = CredentialFilter::ByRp(rp_id.to_string());

        let mut credentials = Vec::new();

        match storage.read_first(filter) {
            Ok(first_cred) => {
                info!(
                    "Found first credential for RP {}: id={}",
                    rp_id,
                    bytes_to_hex(&first_cred.id)
                );
                credentials.push(first_cred);

                while let Ok(cred) = storage.read_next() {
                    info!("Found additional credential: id={}", bytes_to_hex(&cred.id));
                    credentials.push(cred);
                }
            }
            Err(e) => {
                debug!("No credentials found for RP {}: {:?}", rp_id, e);
            }
        }

        info!(
            "Total credentials found for RP {}: {}",
            rp_id,
            credentials.len()
        );
        Ok(credentials)
    }

    fn enumerate_rps(&self) -> Result<Vec<(String, Option<String>, usize)>> {
        debug!("Enumerating relying parties");

        let mut storage = match self.storage.lock() {
            Ok(s) => s,
            Err(_) => {
                error!("Failed to acquire storage lock while enumerating RPs");
                return Err(soft_fido2::Error::Other);
            }
        };

        let filter = CredentialFilter::None;
        let mut all_credentials = Vec::new();

        if let Ok(first_cred) = storage.read_first(filter) {
            all_credentials.push(first_cred);

            while let Ok(cred) = storage.read_next() {
                all_credentials.push(cred);
            }
        }

        use std::collections::HashMap;
        let mut rp_map: HashMap<String, (Option<String>, usize)> = HashMap::new();

        for cred in all_credentials {
            let entry = rp_map
                .entry(cred.rp.id.clone())
                .or_insert((cred.rp.name.clone(), 0));
            entry.1 += 1;
        }

        let result: Vec<(String, Option<String>, usize)> = rp_map
            .into_iter()
            .map(|(rp_id, (rp_name, count))| (rp_id, rp_name, count))
            .collect();

        debug!("Found {} relying parties", result.len());
        Ok(result)
    }

    fn credential_count(&self) -> Result<usize> {
        debug!("Counting total credentials");

        let storage = match self.storage.lock() {
            Ok(s) => s,
            Err(_) => {
                error!("Failed to acquire storage lock while counting credentials");
                return Err(soft_fido2::Error::Other);
            }
        };

        let count = storage.count_credentials();
        debug!("Total credentials: {}", count);
        Ok(count)
    }

    fn get_timestamp_ms(&self) -> u64 {
        let start = SystemTime::now();
        let since_the_epoch = start
            .duration_since(UNIX_EPOCH)
            .expect("Time went backwards");
        since_the_epoch.as_millis() as u64
    }
}

impl<S: CredentialStorage, P: PinStorage> soft_fido2::PinStorageCallbacks
    for PasslessCallbacks<S, P>
{
    fn load_pin_state(&self) -> std::result::Result<PinState, soft_fido2::StatusCode> {
        if let Some(pin_storage) = &self.pin_storage {
            let storage = pin_storage
                .lock()
                .map_err(|_| soft_fido2::StatusCode::Other)?;
            storage.load_pin_state()
        } else {
            Ok(PinState::new())
        }
    }

    fn save_pin_state(&self, state: &PinState) -> std::result::Result<(), soft_fido2::StatusCode> {
        if let Some(pin_storage) = &self.pin_storage {
            let storage = pin_storage
                .lock()
                .map_err(|_| soft_fido2::StatusCode::Other)?;
            storage.save_pin_state(state)
        } else {
            Ok(())
        }
    }
}

/// Main authenticator service
///
/// This service orchestrates the FIDO2 authenticator:
/// - Storage is injected through the CredentialStorage trait
/// - Handles CTAP requests and generates responses
pub struct AuthenticatorService<S: CredentialStorage, P: PinStorage = ()> {
    /// The underlying soft_fido2 authenticator
    pub authenticator: Authenticator<PasslessCallbacks<S, P>>,
    /// Storage backend (injected dependency)
    pub storage: Arc<Mutex<S>>,
    /// Maximum UV retries (configured value, not soft-fido2's hardcoded 3)
    max_uv_retries: u8,
}

impl<S: CredentialStorage + 'static> AuthenticatorService<S, ()> {
    /// Create a new authenticator service without PIN storage
    #[allow(dead_code)]
    pub fn new(storage: S, security_config: SecurityConfig, pin_config: PinConfig) -> Result<Self> {
        Self::with_pin_storage(storage, None, security_config, pin_config)
    }
}

impl<S: CredentialStorage + 'static, P: PinStorage + 'static> AuthenticatorService<S, P> {
    fn build_authenticator(
        storage: Arc<Mutex<S>>,
        pin_storage: Option<Arc<Mutex<P>>>,
        security_config: SecurityConfig,
        pin_config: PinConfig,
    ) -> Result<Authenticator<PasslessCallbacks<S, P>>> {
        // Hardcoded authenticator options (FIDO2 spec compliant)
        // These are platform authenticator defaults and shouldn't need configuration
        let options = AuthenticatorOptions {
            rk: true,                      // Resident keys (passkeys)
            up: true,                      // User presence
            uv: Some(true),                // Notification-based user verification
            plat: true,                    // Platform authenticator
            client_pin: Some(true),        // Client PIN capability
            pin_uv_auth_token: Some(true), // PIN/UV auth token support
            cred_mgmt: Some(true),         // Credential management
            bio_enroll: None,              // No biometric enrollment
            large_blobs: None,             // No large blob storage
            ep: None,                      // Enterprise attestation not enabled
            always_uv: Some(security_config.always_uv),
            make_cred_uv_not_required: Some(true),
        };

        let config = AuthenticatorConfig::builder()
            .aaguid([
                // "fido.passless.rs"
                0x66, 0x69, 0x64, 0x6F, 0x2E, 0x70, 0x61, 0x73, 0x73, 0x6C, 0x65, 0x73, 0x73, 0x2E,
                0x72, 0x73,
            ])
            .options(options)
            .commands(vec![
                CtapCommand::MakeCredential,
                CtapCommand::GetAssertion,
                CtapCommand::GetInfo,
                CtapCommand::ClientPin,
                CtapCommand::GetNextAssertion,
                CtapCommand::Selection,
            ])
            .max_credentials(100)
            .extensions(vec!["credProtect".to_string()])
            .firmware_version(*VERSION)
            .constant_sign_count(security_config.constant_signature_counter)
            .algorithms(vec![-7])
            .max_pin_retries(pin_config.max_retries)
            .auto_lock_timeout(pin_config.auto_lock_timeout)
            .build();

        let callbacks = PasslessCallbacks::new(
            storage,
            pin_storage.clone(),
            security_config,
            pin_config.clone(),
        );

        if let Some(ps) = pin_storage {
            Authenticator::with_config_and_pin_storage(
                callbacks,
                config,
                PinStorageWrapper {
                    storage: ps,
                    max_uv_retries: pin_config.max_uv_retries,
                    last_uv_retries: Mutex::new(None),
                },
            )
        } else {
            Authenticator::with_config(callbacks, config)
        }
    }

    /// Create a new authenticator service with optional PIN storage
    pub fn with_pin_storage(
        storage: S,
        pin_storage: Option<Arc<Mutex<P>>>,
        security_config: SecurityConfig,
        pin_config: PinConfig,
    ) -> Result<Self> {
        let storage = Arc::new(Mutex::new(storage));
        let authenticator = Self::build_authenticator(
            storage.clone(),
            pin_storage.clone(),
            security_config.clone(),
            pin_config.clone(),
        )?;

        Ok(Self {
            authenticator,
            storage,
            max_uv_retries: pin_config.max_uv_retries,
        })
    }

    fn reset_uv_retries(&mut self) -> core::result::Result<(), StatusCode> {
        // Use the high-level reset API from soft-fido2
        self.authenticator
            .reset_uv_retries()
            .map_err(|_| StatusCode::Other)?;

        Ok(())
    }

    /// Process a CTAP request and generate a response
    /// Ok(()) on success or an error
    pub fn handle(&mut self, request: &[u8], response_buffer: &mut Vec<u8>) -> Result<()> {
        if request.first() == Some(&CMD_PASSLESS_RESET_UV_RETRIES) {
            response_buffer.clear();

            let payload = &request[1..];
            let parser = match soft_fido2_ctap::cbor::MapParser::from_bytes(payload) {
                Ok(parser) => parser,
                Err(status) => {
                    response_buffer.push(status as u8);
                    return Ok(());
                }
            };

            let sub_command: u8 = match parser.get(1) {
                Ok(sub_command) => sub_command,
                Err(status) => {
                    response_buffer.push(status as u8);
                    return Ok(());
                }
            };

            if sub_command != RESET_UV_RETRIES_SUBCOMMAND {
                response_buffer.push(StatusCode::InvalidParameter as u8);
                return Ok(());
            }

            let pin_uv_auth_protocol: u8 = match parser.get(3) {
                Ok(protocol) => protocol,
                Err(status) => {
                    response_buffer.push(status as u8);
                    return Ok(());
                }
            };

            let pin_uv_auth_param: Vec<u8> = match parser.get_bytes(4) {
                Ok(param) => param,
                Err(status) => {
                    response_buffer.push(status as u8);
                    return Ok(());
                }
            };

            let auth_data = [CMD_PASSLESS_RESET_UV_RETRIES, RESET_UV_RETRIES_SUBCOMMAND];
            if let Err(error) = self.authenticator.verify_credential_management_pin_uv_auth(
                pin_uv_auth_protocol,
                &pin_uv_auth_param,
                &auth_data,
            ) {
                response_buffer.push(error_status_byte(error));
                return Ok(());
            }

            match self.reset_uv_retries() {
                Ok(()) => {
                    response_buffer.push(0x00);
                    // Include the restored UV retries count in the response
                    // Response format: CBOR map { 1: uv_retries_count }
                    // Use configured max_uv_retries, not soft-fido2's hardcoded value
                    if let Ok(cbor_data) = soft_fido2_ctap::cbor::MapBuilder::new()
                        .insert(1, self.max_uv_retries)
                        .and_then(|b| b.build())
                    {
                        response_buffer.extend_from_slice(&cbor_data);
                    } else {
                        response_buffer.push(0xa0);
                    }
                }
                Err(status) => response_buffer.push(status as u8),
            }
            return Ok(());
        }

        let result = self.authenticator.handle(request, response_buffer);
        if let Err(SoftFido2Error::CtapError(code)) = &result
            && *code == StatusCode::UvBlocked as u8
        {
            warn!(
                "CTAP request returned UV_BLOCKED (0x{:02x}); \
                 built-in user verification retries are exhausted. \
                 Run `passless client pin uv-reset` to restore",
                code
            );
        }
        result?;
        Ok(())
    }

    /// Get storage information
    pub fn storage_info(&self) -> String {
        let storage = self.storage.lock().unwrap();
        format!("Credentials in storage: {}", storage.count_credentials())
    }

    /// Register a custom CTAP command handler
    ///
    /// This allows registering vendor-specific commands (0x40-0xFF range).
    /// Useful for compatibility with different authenticator variants.
    ///
    /// # Arguments
    ///
    /// * `command` - Command byte (0x40-0xFF vendor range)
    /// * `handler` - Handler function that processes the command
    pub fn register_custom_command<F>(&mut self, command: u8, handler: F)
    where
        F: Fn(&[u8]) -> core::result::Result<Vec<u8>, soft_fido2::StatusCode>
            + Send
            + Sync
            + 'static,
    {
        self.authenticator.register_custom_command(command, handler);
    }
}

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

    use crate::storage::LocalStorageAdapter;

    #[test]
    fn test_service_creation() {
        let temp_dir = std::env::temp_dir().join("test_passless");
        if let Err(e) = std::fs::create_dir_all(&temp_dir) {
            panic!("Failed to create temp directory: {}", e);
        }
        let storage = match LocalStorageAdapter::new(temp_dir.clone()) {
            Ok(s) => s,
            Err(e) => panic!("Failed to create local storage: {}", e),
        };

        let security_config = SecurityConfig {
            check_mlock: false,
            disable_core_dumps: false,
            constant_signature_counter: false,
            always_uv: true,
            user_verification_registration: true,
            user_verification_authentication: true,
            notification_timeout: 30,
        };

        let pin_config = PinConfig::default();

        let service = AuthenticatorService::new(storage, security_config, pin_config);
        assert!(service.is_ok(), "Service creation should succeed");

        // Cleanup
        let _ = std::fs::remove_dir_all(temp_dir);
    }

    #[test]
    fn test_reset_uv_retries_command_requires_authentication() {
        let temp_dir = std::env::temp_dir().join("test_passless_reset_uv_retries");
        let _ = std::fs::remove_dir_all(&temp_dir);
        std::fs::create_dir_all(&temp_dir).expect("Failed to create temp directory");

        let storage =
            LocalStorageAdapter::new(temp_dir.clone()).expect("Failed to create local storage");
        let mut service = AuthenticatorService::with_pin_storage(
            storage,
            None::<Arc<Mutex<()>>>,
            SecurityConfig::default(),
            PinConfig::default(),
        )
        .expect("Service creation should succeed");

        let mut response = Vec::new();
        service
            .handle(&[CMD_PASSLESS_RESET_UV_RETRIES], &mut response)
            .expect("UV retry reset command should be handled");

        assert_ne!(response, vec![0x00, 0xa0]);

        let _ = std::fs::remove_dir_all(temp_dir);
    }

    #[test]
    fn test_pin_storage_wrapper_clamps_on_save() {
        use crate::pin_storage::local::LocalPinStorage;
        use soft_fido2::PinStorageCallbacks;

        let temp_dir = std::env::temp_dir().join("test_passless_pin_wrapper_save");
        let _ = std::fs::remove_dir_all(&temp_dir);
        std::fs::create_dir_all(&temp_dir).expect("Failed to create temp directory");

        let pin_storage = LocalPinStorage::new(temp_dir.clone());
        let wrapper = PinStorageWrapper {
            storage: Arc::new(Mutex::new(pin_storage)),
            max_uv_retries: 5,
            last_uv_retries: Mutex::new(None),
        };

        let mut state = PinState::new();
        state.uv_retries = 10;

        // Save should clamp to max_uv_retries
        wrapper.save_pin_state(&state).expect("Save should succeed");

        // Load should return clamped value
        let loaded = wrapper.load_pin_state().expect("Load should succeed");
        assert_eq!(loaded.uv_retries, 5, "uv_retries should be clamped to max");

        let _ = std::fs::remove_dir_all(temp_dir);
    }

    #[test]
    fn test_pin_storage_wrapper_clamps_on_load() {
        use crate::pin_storage::local::LocalPinStorage;
        use soft_fido2::PinStorageCallbacks;

        let temp_dir = std::env::temp_dir().join("test_passless_pin_wrapper_load");
        let _ = std::fs::remove_dir_all(&temp_dir);
        std::fs::create_dir_all(&temp_dir).expect("Failed to create temp directory");

        let pin_storage = LocalPinStorage::new(temp_dir.clone());

        let wrapper_high = PinStorageWrapper {
            storage: Arc::new(Mutex::new(pin_storage)),
            max_uv_retries: 8,
            last_uv_retries: Mutex::new(None),
        };
        let mut state = PinState::new();
        state.uv_retries = 8;
        wrapper_high
            .save_pin_state(&state)
            .expect("Save should succeed");

        let pin_storage2 = LocalPinStorage::new(temp_dir.clone());
        let wrapper_low = PinStorageWrapper {
            storage: Arc::new(Mutex::new(pin_storage2)),
            max_uv_retries: 3,
            last_uv_retries: Mutex::new(None),
        };

        // Load should clamp to the lower max
        let loaded = wrapper_low.load_pin_state().expect("Load should succeed");
        assert_eq!(
            loaded.uv_retries, 3,
            "uv_retries should be clamped to lower max on load"
        );

        let _ = std::fs::remove_dir_all(temp_dir);
    }

    #[test]
    fn test_uv_retry_transition_classification() {
        assert_eq!(
            PinStorageWrapper::<()>::classify_uv_transition(None, 3),
            UvRetryTransition::Initialized,
        );
        assert_eq!(
            PinStorageWrapper::<()>::classify_uv_transition(Some(3), 2),
            UvRetryTransition::NormalChange,
        );
        assert_eq!(
            PinStorageWrapper::<()>::classify_uv_transition(Some(2), 1),
            UvRetryTransition::Low,
        );
        assert_eq!(
            PinStorageWrapper::<()>::classify_uv_transition(Some(1), 0),
            UvRetryTransition::Exhausted,
        );
        assert_eq!(
            PinStorageWrapper::<()>::classify_uv_transition(Some(0), 0),
            UvRetryTransition::NoChange,
        );
        assert_eq!(
            PinStorageWrapper::<()>::classify_uv_transition(Some(0), 8),
            UvRetryTransition::Recovered,
        );
        assert_eq!(
            PinStorageWrapper::<()>::classify_uv_transition(Some(5), 5),
            UvRetryTransition::NoChange,
        );
        assert_eq!(
            PinStorageWrapper::<()>::classify_uv_transition(Some(3), 1),
            UvRetryTransition::Low,
        );
        assert_eq!(
            PinStorageWrapper::<()>::classify_uv_transition(Some(2), 0),
            UvRetryTransition::Exhausted,
        );
    }

    #[test]
    fn test_pin_storage_wrapper_tracks_uv_retry_transitions() {
        use crate::pin_storage::local::LocalPinStorage;
        use soft_fido2::PinStorageCallbacks;

        let temp_dir = std::env::temp_dir().join("test_passless_uv_transitions");
        let _ = std::fs::remove_dir_all(&temp_dir);
        std::fs::create_dir_all(&temp_dir).expect("Failed to create temp directory");

        let pin_storage = LocalPinStorage::new(temp_dir.clone());
        let wrapper = PinStorageWrapper {
            storage: Arc::new(Mutex::new(pin_storage)),
            max_uv_retries: 8,
            last_uv_retries: Mutex::new(None),
        };

        let mut state = PinState::new();
        state.uv_retries = 3;
        wrapper.save_pin_state(&state).expect("Save should succeed");
        {
            let last = wrapper.last_uv_retries.lock().unwrap();
            assert_eq!(*last, Some(3));
        }

        state.uv_retries = 2;
        wrapper.save_pin_state(&state).expect("Save should succeed");
        {
            let last = wrapper.last_uv_retries.lock().unwrap();
            assert_eq!(*last, Some(2));
        }

        state.uv_retries = 1;
        wrapper.save_pin_state(&state).expect("Save should succeed");
        {
            let last = wrapper.last_uv_retries.lock().unwrap();
            assert_eq!(*last, Some(1));
        }

        state.uv_retries = 0;
        wrapper.save_pin_state(&state).expect("Save should succeed");
        {
            let last = wrapper.last_uv_retries.lock().unwrap();
            assert_eq!(*last, Some(0));
        }

        state.uv_retries = 0;
        wrapper.save_pin_state(&state).expect("Save should succeed");
        {
            let last = wrapper.last_uv_retries.lock().unwrap();
            assert_eq!(*last, Some(0));
        }

        state.uv_retries = 8;
        wrapper.save_pin_state(&state).expect("Save should succeed");
        {
            let last = wrapper.last_uv_retries.lock().unwrap();
            assert_eq!(*last, Some(8));
        }

        let _ = std::fs::remove_dir_all(temp_dir);
    }

    #[test]
    fn test_pin_storage_wrapper_load_initializes_last_uv_retries() {
        use crate::pin_storage::local::LocalPinStorage;
        use soft_fido2::PinStorageCallbacks;

        let temp_dir = std::env::temp_dir().join("test_passless_uv_load_init");
        let _ = std::fs::remove_dir_all(&temp_dir);
        std::fs::create_dir_all(&temp_dir).expect("Failed to create temp directory");

        let pin_storage = LocalPinStorage::new(temp_dir.clone());
        let wrapper = PinStorageWrapper {
            storage: Arc::new(Mutex::new(pin_storage)),
            max_uv_retries: 8,
            last_uv_retries: Mutex::new(None),
        };

        {
            let last = wrapper.last_uv_retries.lock().unwrap();
            assert_eq!(*last, None);
        }

        let _state = wrapper.load_pin_state().expect("Load should succeed");
        {
            let last = wrapper.last_uv_retries.lock().unwrap();
            assert!(last.is_some());
        }

        let _ = std::fs::remove_dir_all(temp_dir);
    }
}