passless-rs 0.17.0

FIDO2 security token emulator
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
#[cfg(feature = "agent")]
use crate::agent::interaction::{AgentInteractionManager, action_from_info};
use crate::credential_backup::{
    BACKUP_COMMIT_SUBCOMMAND, BACKUP_PREPARE_SUBCOMMAND, BackupError, CMD_PASSLESS_BACKUP,
    CMD_PASSLESS_RESTORE, backup_commit_auth_data, backup_prepare_auth_data, bundle_token,
    decrypt_credential, encrypt_credential, restore_auth_data,
};
use crate::notification::{show_user_presence_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,
    BuiltInUvState, Credential, CredentialBackupState, CredentialKeyProvider, CredentialRef,
    CtapCommand, Error as SoftFido2Error, PinState, Result, SoftwareCredentialKeyProvider,
    StatusCode, UpResult, UvResult,
};

use std::collections::HashMap;
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;

pub 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. We clamp the uv_retries value to the configured maximum during
/// persistence as a safety measure to ensure the configured limit is always respected.
///
/// 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,
    #[cfg(feature = "agent")]
    interaction_manager: Option<Arc<AgentInteractionManager>>,
    #[cfg(feature = "agent")]
    isolated_mode: bool,
}

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,
            #[cfg(feature = "agent")]
            interaction_manager: None,
            #[cfg(feature = "agent")]
            isolated_mode: false,
        }
    }

    #[cfg(feature = "agent")]
    pub fn with_interaction_manager(
        storage: Arc<Mutex<S>>,
        pin_storage: Option<Arc<Mutex<P>>>,
        security_config: SecurityConfig,
        pin_config: PinConfig,
        interaction_manager: Arc<AgentInteractionManager>,
        isolated_mode: bool,
    ) -> Self {
        Self {
            storage,
            pin_storage,
            security_config,
            pin_config,
            interaction_manager: Some(interaction_manager),
            isolated_mode,
        }
    }
}

impl<S: CredentialStorage, P: PinStorage> AuthenticatorCallbacks for PasslessCallbacks<S, P> {
    fn request_up(&self, info: &str, user: Option<&str>, rp: &str) -> Result<UpResult> {
        #[cfg(feature = "agent")]
        {
            if let Some(ref manager) = self.interaction_manager {
                let action = action_from_info(info);
                let generation = 0;
                match manager.try_consume_up(rp, action, generation) {
                    Some(result) => {
                        debug!("Agent interaction override for UP: {:?}", result);
                        return Ok(result);
                    }
                    None => {
                        if manager.has_active_token() {
                            debug!(
                                "Agent interaction token active, auto-approving UP for rp={}",
                                rp
                            );
                            return Ok(UpResult::Accepted);
                        }
                    }
                }
                if self.isolated_mode {
                    debug!("Isolated mode: auto-approving UP for rp={}", rp);
                    return Ok(UpResult::Accepted);
                }
            }
        }

        // 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_user_presence_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(feature = "agent")]
        {
            if let Some(ref manager) = self.interaction_manager {
                let action = action_from_info(info);
                let generation = 0;
                match manager.try_consume_uv(rp, action, generation) {
                    Some(result) => {
                        debug!("Agent interaction override for UV: {:?}", result);
                        return Ok(result);
                    }
                    None => {
                        if manager.has_active_token() {
                            debug!(
                                "Agent interaction token active, auto-approving UV for rp={}",
                                rp
                            );
                            return Ok(UvResult::AcceptedWithUp);
                        }
                    }
                }
                if self.isolated_mode {
                    debug!("Isolated mode: auto-approving UV for rp={}", rp);
                    return Ok(UvResult::AcceptedWithUp);
                }
            }
        }

        #[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(soft_fido2::Error::DoesNotExist) => {
                debug!("Credential not found");
                Ok(None)
            }
            Err(e) => {
                error!("Storage error reading credential: {:?}", e);
                Err(e)
            }
        }
    }

    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>> {
        if let Err(e) = crate::storage::ValidatedRpId::try_from(rp_id) {
            warn!(
                "Rejected list_credentials for invalid RP ID '{}': {}",
                rp_id, e
            );
            return Err(soft_fido2::Error::Other);
        }

        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 found: {}", count);
        Ok(count)
    }

    fn get_timestamp_ms(&self) -> u64 {
        let start = SystemTime::now();
        let since_the_epoch = start.duration_since(UNIX_EPOCH).unwrap_or_default();
        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(())
        }
    }
}

#[derive(Debug, Clone, Copy)]
struct BuiltInUvPolicy;

/// 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 = (),
    K: CredentialKeyProvider = SoftwareCredentialKeyProvider,
> {
    /// The underlying soft_fido2 authenticator
    pub authenticator: Authenticator<PasslessCallbacks<S, P>, K>,
    /// Storage backend (injected dependency)
    pub storage: Arc<Mutex<S>>,
    /// Dynamic built-in UV policy; absent for agent authenticators.
    built_in_uv_policy: Option<BuiltInUvPolicy>,
    /// Maximum UV retries (configured value)
    max_uv_retries: u8,
    /// Runtime feature gate for credential export/import.
    credential_backup_enabled: bool,
    /// False for TPM and other non-exportable key providers.
    credential_backup_supported: bool,
    /// Prepared bundles awaiting durable client-side persistence confirmation.
    pending_backups: HashMap<Vec<u8>, [u8; 32]>,
    /// PIN storage for checking whether a PIN is configured
    pin_storage: Option<Arc<Mutex<P>>>,
}

impl<S: CredentialStorage + 'static> AuthenticatorService<S, (), SoftwareCredentialKeyProvider> {
    /// 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_shared_storage(
            Arc::new(Mutex::new(storage)),
            None,
            security_config,
            pin_config,
        )
    }
}

impl<S: CredentialStorage + 'static, P: PinStorage + 'static>
    AuthenticatorService<S, P, SoftwareCredentialKeyProvider>
{
    fn build_authenticator(
        storage: Arc<Mutex<S>>,
        pin_storage: Option<Arc<Mutex<P>>>,
        security_config: SecurityConfig,
        pin_config: PinConfig,
    ) -> Result<Authenticator<PasslessCallbacks<S, P>>> {
        #[cfg(feature = "agent")]
        {
            Self::build_authenticator_with_interaction(
                storage,
                pin_storage,
                security_config,
                pin_config,
                None,
            )
        }
        #[cfg(not(feature = "agent"))]
        {
            let options = AuthenticatorOptions {
                rk: true,
                up: true,
                uv: Some(true),
                plat: true,
                client_pin: Some(true),
                pin_uv_auth_token: Some(true),
                cred_mgmt: Some(true),
                bio_enroll: None,
                large_blobs: None,
                ep: None,
                always_uv: Some(security_config.always_uv),
                make_cred_uv_not_required: Some(true),
            };

            let config = AuthenticatorConfig::builder()
                .aaguid([
                    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)
                .default_credential_backup_state(if security_config.enable_credential_backup {
                    CredentialBackupState::Eligible
                } else {
                    CredentialBackupState::NotEligible
                })
                .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(),
            );

            let authenticator = 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)
            }?;

            Ok(authenticator)
        }
    }

    #[cfg(feature = "agent")]
    fn build_authenticator_with_interaction(
        storage: Arc<Mutex<S>>,
        pin_storage: Option<Arc<Mutex<P>>>,
        security_config: SecurityConfig,
        pin_config: PinConfig,
        interaction_manager: Option<Arc<AgentInteractionManager>>,
    ) -> Result<Authenticator<PasslessCallbacks<S, P>>> {
        Self::build_authenticator_with_interaction_and_options(
            storage,
            pin_storage,
            security_config,
            pin_config,
            interaction_manager,
            true,
        )
    }

    #[cfg(feature = "agent")]
    fn build_authenticator_with_interaction_and_options(
        storage: Arc<Mutex<S>>,
        pin_storage: Option<Arc<Mutex<P>>>,
        security_config: SecurityConfig,
        pin_config: PinConfig,
        interaction_manager: Option<Arc<AgentInteractionManager>>,
        use_agent_options: bool,
    ) -> Result<Authenticator<PasslessCallbacks<S, P>>> {
        let is_agent = use_agent_options;

        let options = if is_agent {
            AuthenticatorOptions {
                rk: true,
                up: true,
                uv: Some(false),
                plat: true,
                client_pin: Some(true),
                pin_uv_auth_token: Some(true),
                cred_mgmt: Some(true),
                bio_enroll: None,
                large_blobs: None,
                ep: None,
                always_uv: Some(true),
                make_cred_uv_not_required: Some(false),
            }
        } else {
            AuthenticatorOptions {
                rk: true,
                up: true,
                uv: Some(true),
                plat: true,
                client_pin: Some(true),
                pin_uv_auth_token: Some(true),
                cred_mgmt: Some(true),
                bio_enroll: None,
                large_blobs: None,
                ep: None,
                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)
            .default_credential_backup_state(CredentialBackupState::NotEligible)
            .algorithms(vec![-7])
            .max_pin_retries(pin_config.max_retries)
            .auto_lock_timeout(pin_config.auto_lock_timeout)
            .build();

        let callbacks = match interaction_manager {
            Some(ref mgr) => PasslessCallbacks::with_interaction_manager(
                storage,
                pin_storage.clone(),
                security_config,
                pin_config.clone(),
                mgr.clone(),
                use_agent_options,
            ),
            None => PasslessCallbacks::new(
                storage,
                pin_storage.clone(),
                security_config,
                pin_config.clone(),
            ),
        };

        let authenticator = 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)?
        };

        Ok(authenticator)
    }

    /// 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));
        Self::with_shared_storage(storage, pin_storage, security_config, pin_config)
    }

    /// Create a new authenticator service with shared (Arc-wrapped) storage
    ///
    /// This constructor accepts pre-wrapped `Arc<Mutex<S>>` and `Option<Arc<Mutex<P>>>`,
    /// allowing callers (such as `AgentStorageBundle`) to share ownership of the storage
    /// without moving it. Each call creates an independent `AuthenticatorService` that
    /// references the same underlying storage.
    pub fn with_shared_storage(
        storage: Arc<Mutex<S>>,
        pin_storage: Option<Arc<Mutex<P>>>,
        security_config: SecurityConfig,
        pin_config: PinConfig,
    ) -> Result<Self> {
        let authenticator = Self::build_authenticator(
            storage.clone(),
            pin_storage.clone(),
            security_config.clone(),
            pin_config.clone(),
        )?;

        let mut service = Self {
            authenticator,
            storage,
            built_in_uv_policy: Some(BuiltInUvPolicy),
            max_uv_retries: pin_config.max_uv_retries,
            credential_backup_enabled: security_config.enable_credential_backup,
            credential_backup_supported: true,
            pending_backups: HashMap::new(),
            pin_storage,
        };
        service.refresh_built_in_uv_state()?;
        Ok(service)
    }

    /// Create a new authenticator service with shared storage and an agent interaction manager
    ///
    /// The interaction manager allows agent ceremony code to install a one-shot token
    /// that overrides UP/UV prompts. When a matching token is present, callbacks consume
    /// it once and return the pre-decided result. Without a token, the human notification
    /// path is used. Token bytes are never serialized or logged.
    #[cfg(feature = "agent")]
    #[allow(dead_code)]
    pub fn with_shared_storage_and_interaction(
        storage: Arc<Mutex<S>>,
        pin_storage: Option<Arc<Mutex<P>>>,
        security_config: SecurityConfig,
        pin_config: PinConfig,
        interaction_manager: Arc<AgentInteractionManager>,
    ) -> Result<Self> {
        let authenticator = Self::build_authenticator_with_interaction(
            storage.clone(),
            pin_storage.clone(),
            security_config.clone(),
            pin_config.clone(),
            Some(interaction_manager),
        )?;

        Ok(Self {
            authenticator,
            storage,
            built_in_uv_policy: None,
            max_uv_retries: pin_config.max_uv_retries,
            credential_backup_enabled: security_config.enable_credential_backup,
            credential_backup_supported: true,
            pending_backups: HashMap::new(),
            pin_storage,
        })
    }
}

impl<
    S: CredentialStorage + 'static,
    P: PinStorage + 'static,
    K: CredentialKeyProvider + Send + Sync + 'static,
> AuthenticatorService<S, P, K>
{
    #[cfg(feature = "tpm")]
    fn build_authenticator_with_key_provider(
        storage: Arc<Mutex<S>>,
        pin_storage: Option<Arc<Mutex<P>>>,
        security_config: SecurityConfig,
        pin_config: PinConfig,
        key_provider: K,
    ) -> Result<Authenticator<PasslessCallbacks<S, P>, K>> {
        #[cfg(feature = "agent")]
        {
            Self::build_authenticator_with_interaction_and_key_provider(
                storage,
                pin_storage,
                security_config,
                pin_config,
                None,
                key_provider,
            )
        }
        #[cfg(not(feature = "agent"))]
        {
            let options = AuthenticatorOptions {
                rk: true,
                up: true,
                uv: Some(true),
                plat: true,
                client_pin: Some(true),
                pin_uv_auth_token: Some(true),
                cred_mgmt: Some(true),
                bio_enroll: None,
                large_blobs: None,
                ep: None,
                always_uv: Some(security_config.always_uv),
                make_cred_uv_not_required: Some(true),
            };

            let config = AuthenticatorConfig::builder()
                .aaguid([
                    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)
                .default_credential_backup_state(if security_config.enable_credential_backup {
                    CredentialBackupState::Eligible
                } else {
                    CredentialBackupState::NotEligible
                })
                .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(),
            );

            let authenticator = if let Some(ps) = pin_storage {
                Authenticator::with_config_and_pin_storage_and_key_provider(
                    callbacks,
                    config,
                    PinStorageWrapper {
                        storage: ps,
                        max_uv_retries: pin_config.max_uv_retries,
                        last_uv_retries: Mutex::new(None),
                    },
                    key_provider,
                )
            } else {
                Authenticator::with_config_and_key_provider(callbacks, config, key_provider)
            }?;

            Ok(authenticator)
        }
    }

    #[cfg(all(feature = "tpm", feature = "agent"))]
    fn build_authenticator_with_interaction_and_key_provider(
        storage: Arc<Mutex<S>>,
        pin_storage: Option<Arc<Mutex<P>>>,
        security_config: SecurityConfig,
        pin_config: PinConfig,
        interaction_manager: Option<Arc<AgentInteractionManager>>,
        key_provider: K,
    ) -> Result<Authenticator<PasslessCallbacks<S, P>, K>> {
        let is_agent = interaction_manager.is_some();

        let options = if is_agent {
            AuthenticatorOptions {
                rk: true,
                up: true,
                uv: Some(false),
                plat: true,
                client_pin: Some(true),
                pin_uv_auth_token: Some(true),
                cred_mgmt: Some(true),
                bio_enroll: None,
                large_blobs: None,
                ep: None,
                always_uv: Some(true),
                make_cred_uv_not_required: Some(false),
            }
        } else {
            AuthenticatorOptions {
                rk: true,
                up: true,
                uv: Some(true),
                plat: true,
                client_pin: Some(true),
                pin_uv_auth_token: Some(true),
                cred_mgmt: Some(true),
                bio_enroll: None,
                large_blobs: None,
                ep: None,
                always_uv: Some(security_config.always_uv),
                make_cred_uv_not_required: Some(true),
            }
        };

        let config = AuthenticatorConfig::builder()
            .aaguid([
                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)
            .default_credential_backup_state(CredentialBackupState::NotEligible)
            .algorithms(vec![-7])
            .max_pin_retries(pin_config.max_retries)
            .auto_lock_timeout(pin_config.auto_lock_timeout)
            .build();

        let callbacks = match interaction_manager {
            Some(ref mgr) => PasslessCallbacks::with_interaction_manager(
                storage,
                pin_storage.clone(),
                security_config,
                pin_config.clone(),
                mgr.clone(),
                is_agent,
            ),
            None => PasslessCallbacks::new(
                storage,
                pin_storage.clone(),
                security_config,
                pin_config.clone(),
            ),
        };

        let authenticator = if let Some(ps) = pin_storage {
            Authenticator::with_config_and_pin_storage_and_key_provider(
                callbacks,
                config,
                PinStorageWrapper {
                    storage: ps,
                    max_uv_retries: pin_config.max_uv_retries,
                    last_uv_retries: Mutex::new(None),
                },
                key_provider,
            )?
        } else {
            Authenticator::with_config_and_key_provider(callbacks, config, key_provider)?
        };

        Ok(authenticator)
    }

    /// Create a new authenticator service with optional PIN storage and a custom key provider
    #[cfg(feature = "tpm")]
    pub fn with_pin_storage_and_key_provider(
        storage: S,
        pin_storage: Option<Arc<Mutex<P>>>,
        key_provider: K,
        security_config: SecurityConfig,
        pin_config: PinConfig,
    ) -> Result<Self> {
        let storage = Arc::new(Mutex::new(storage));
        Self::with_shared_storage_and_key_provider(
            storage,
            pin_storage,
            key_provider,
            security_config,
            pin_config,
        )
    }

    /// Create a new authenticator service with shared (Arc-wrapped) storage and a custom key provider
    #[cfg(feature = "tpm")]
    pub fn with_shared_storage_and_key_provider(
        storage: Arc<Mutex<S>>,
        pin_storage: Option<Arc<Mutex<P>>>,
        key_provider: K,
        security_config: SecurityConfig,
        pin_config: PinConfig,
    ) -> Result<Self> {
        let authenticator = Self::build_authenticator_with_key_provider(
            storage.clone(),
            pin_storage.clone(),
            security_config.clone(),
            pin_config.clone(),
            key_provider,
        )?;

        let mut service = Self {
            authenticator,
            storage,
            built_in_uv_policy: Some(BuiltInUvPolicy),
            max_uv_retries: pin_config.max_uv_retries,
            credential_backup_enabled: false,
            credential_backup_supported: false,
            pending_backups: HashMap::new(),
            pin_storage,
        };
        service.refresh_built_in_uv_state()?;
        Ok(service)
    }

    #[cfg(all(feature = "tpm", feature = "agent"))]
    pub fn with_shared_storage_and_key_provider_and_interaction(
        storage: Arc<Mutex<S>>,
        pin_storage: Option<Arc<Mutex<P>>>,
        key_provider: K,
        security_config: SecurityConfig,
        pin_config: PinConfig,
        interaction_manager: Arc<AgentInteractionManager>,
    ) -> Result<Self> {
        let authenticator = Self::build_authenticator_with_interaction_and_key_provider(
            storage.clone(),
            pin_storage.clone(),
            security_config.clone(),
            pin_config.clone(),
            Some(interaction_manager),
            key_provider,
        )?;

        Ok(Self {
            authenticator,
            storage,
            built_in_uv_policy: None,
            max_uv_retries: pin_config.max_uv_retries,
            credential_backup_enabled: false,
            credential_backup_supported: false,
            pending_backups: HashMap::new(),
            pin_storage,
        })
    }

    fn refresh_built_in_uv_state(&mut self) -> Result<()> {
        let Some(_policy) = self.built_in_uv_policy else {
            return Ok(());
        };

        let pin_configured = self
            .pin_storage
            .as_ref()
            .and_then(|ps| ps.lock().ok())
            .and_then(|ps| ps.load_pin_state().ok())
            .map(|state| state.pin_hash.is_some())
            .unwrap_or(false);

        let state = if pin_configured {
            BuiltInUvState::SupportedNotConfigured
        } else {
            BuiltInUvState::Configured
        };

        self.authenticator.set_built_in_uv_state(state)
    }

    fn reset_uv_retries(&mut self) -> core::result::Result<(), StatusCode> {
        self.authenticator
            .reset_uv_retries()
            .map_err(|_| StatusCode::Other)?;

        Ok(())
    }

    fn backup_error_status(error: BackupError) -> StatusCode {
        match error {
            BackupError::InvalidInput => StatusCode::InvalidParameter,
            BackupError::InvalidBundle => StatusCode::InvalidCredential,
            BackupError::UnsupportedCredential => StatusCode::UnsupportedOption,
            BackupError::CryptoUnavailable | BackupError::CryptoFailed => {
                StatusCode::IntegrityFailure
            }
            BackupError::TooLarge => StatusCode::RequestTooLarge,
        }
    }

    fn credential_ref(credential: &Credential) -> CredentialRef<'_> {
        CredentialRef {
            id: &credential.id,
            rp_id: &credential.rp.id,
            rp_name: credential.rp.name.as_deref(),
            user_id: &credential.user.id,
            user_name: credential.user.name.as_deref(),
            user_display_name: credential.user.display_name.as_deref(),
            sign_count: &credential.sign_count,
            alg: &credential.alg,
            key: &credential.key,
            created: &credential.created,
            discoverable: &credential.discoverable,
            cred_protect: credential.extensions.cred_protect.as_ref(),
            backup_state: &credential.backup_state,
            cred_random: credential.extensions.cred_random.as_ref(),
        }
    }

    fn verify_backup_authorization(
        &mut self,
        protocol: u8,
        param: &[u8],
        auth_data: &[u8],
    ) -> core::result::Result<(), u8> {
        self.authenticator
            .verify_credential_management_pin_uv_auth(protocol, param, auth_data)
            .map_err(error_status_byte)
    }

    fn handle_backup_command(&mut self, payload: &[u8], response: &mut Vec<u8>) {
        response.clear();
        if !self.credential_backup_enabled || !self.credential_backup_supported {
            response.push(StatusCode::UnsupportedOption as u8);
            return;
        }

        let parser = match soft_fido2_ctap::cbor::MapParser::from_bytes(payload) {
            Ok(parser) => parser,
            Err(status) => {
                response.push(status as u8);
                return;
            }
        };
        let subcommand: u8 = match parser.get(1) {
            Ok(value) => value,
            Err(status) => {
                response.push(status as u8);
                return;
            }
        };

        match subcommand {
            BACKUP_PREPARE_SUBCOMMAND => {
                let credential_id = match parser.get_bytes(2) {
                    Ok(value) => value,
                    Err(status) => {
                        response.push(status as u8);
                        return;
                    }
                };
                let recipient: String = match parser.get(3) {
                    Ok(value) => value,
                    Err(status) => {
                        response.push(status as u8);
                        return;
                    }
                };
                let protocol: u8 = match parser.get(4) {
                    Ok(value) => value,
                    Err(status) => {
                        response.push(status as u8);
                        return;
                    }
                };
                let param = match parser.get_bytes(5) {
                    Ok(value) => value,
                    Err(status) => {
                        response.push(status as u8);
                        return;
                    }
                };
                let auth_data = backup_prepare_auth_data(&credential_id, &recipient);
                if let Err(status) = self.verify_backup_authorization(protocol, &param, &auth_data)
                {
                    response.push(status);
                    return;
                }

                let mut credential = {
                    let mut storage = match self.storage.lock() {
                        Ok(storage) => storage,
                        Err(_) => {
                            response.push(StatusCode::Other as u8);
                            return;
                        }
                    };
                    match storage.read(&credential_id) {
                        Ok(credential) => credential,
                        Err(soft_fido2::Error::DoesNotExist) => {
                            response.push(StatusCode::NoCredentials as u8);
                            return;
                        }
                        Err(_) => {
                            response.push(StatusCode::Other as u8);
                            return;
                        }
                    }
                };
                credential.backup_state = CredentialBackupState::BackedUp;
                let bundle = match encrypt_credential(&credential, &recipient) {
                    Ok(bundle) => bundle,
                    Err(error) => {
                        response.push(Self::backup_error_status(error) as u8);
                        return;
                    }
                };
                let token = bundle_token(&bundle);
                self.pending_backups.insert(credential_id, token);

                match soft_fido2_ctap::cbor::MapBuilder::new()
                    .insert_bytes(1, &bundle)
                    .and_then(|builder| builder.insert_bytes(2, &token))
                    .and_then(|builder| builder.build())
                {
                    Ok(body) => {
                        response.push(StatusCode::Success as u8);
                        response.extend_from_slice(&body);
                    }
                    Err(_) => response.push(StatusCode::Other as u8),
                }
            }
            BACKUP_COMMIT_SUBCOMMAND => {
                let credential_id = match parser.get_bytes(2) {
                    Ok(value) => value,
                    Err(status) => {
                        response.push(status as u8);
                        return;
                    }
                };
                let token = match parser.get_bytes(3) {
                    Ok(value) => value,
                    Err(status) => {
                        response.push(status as u8);
                        return;
                    }
                };
                let protocol: u8 = match parser.get(4) {
                    Ok(value) => value,
                    Err(status) => {
                        response.push(status as u8);
                        return;
                    }
                };
                let param = match parser.get_bytes(5) {
                    Ok(value) => value,
                    Err(status) => {
                        response.push(status as u8);
                        return;
                    }
                };
                let auth_data = backup_commit_auth_data(&credential_id, &token);
                if let Err(status) = self.verify_backup_authorization(protocol, &param, &auth_data)
                {
                    response.push(status);
                    return;
                }
                if token.len() != 32
                    || self
                        .pending_backups
                        .get(&credential_id)
                        .map(|expected| expected.as_slice())
                        != Some(token.as_slice())
                {
                    response.push(StatusCode::IntegrityFailure as u8);
                    return;
                }

                let result = (|| -> Result<()> {
                    let mut storage = self.storage.lock().map_err(|_| soft_fido2::Error::Other)?;
                    let mut credential = storage.read(&credential_id)?;
                    credential.backup_state = CredentialBackupState::BackedUp;
                    storage.write(Self::credential_ref(&credential))
                })();
                match result {
                    Ok(()) => {
                        self.pending_backups.remove(&credential_id);
                        response.push(StatusCode::Success as u8);
                        response.push(0xa0);
                    }
                    Err(soft_fido2::Error::DoesNotExist) => {
                        response.push(StatusCode::NoCredentials as u8)
                    }
                    Err(_) => response.push(StatusCode::Other as u8),
                }
            }
            _ => response.push(StatusCode::InvalidSubcommand as u8),
        }
    }

    fn handle_restore_command(&mut self, payload: &[u8], response: &mut Vec<u8>) {
        response.clear();
        if !self.credential_backup_enabled || !self.credential_backup_supported {
            response.push(StatusCode::UnsupportedOption as u8);
            return;
        }

        let parser = match soft_fido2_ctap::cbor::MapParser::from_bytes(payload) {
            Ok(parser) => parser,
            Err(status) => {
                response.push(status as u8);
                return;
            }
        };
        let bundle = match parser.get_bytes(1) {
            Ok(value) => value,
            Err(status) => {
                response.push(status as u8);
                return;
            }
        };
        let replace: bool = parser.get(2).unwrap_or(false);
        let protocol: u8 = match parser.get(3) {
            Ok(value) => value,
            Err(status) => {
                response.push(status as u8);
                return;
            }
        };
        let param = match parser.get_bytes(4) {
            Ok(value) => value,
            Err(status) => {
                response.push(status as u8);
                return;
            }
        };
        let auth_data = restore_auth_data(&bundle, replace);
        if let Err(status) = self.verify_backup_authorization(protocol, &param, &auth_data) {
            response.push(status);
            return;
        }

        let mut credential = match decrypt_credential(&bundle) {
            Ok(credential) => credential,
            Err(error) => {
                response.push(Self::backup_error_status(error) as u8);
                return;
            }
        };
        credential.backup_state = CredentialBackupState::BackedUp;
        let credential_id = credential.id.clone();

        let result = (|| -> core::result::Result<(), StatusCode> {
            let mut storage = self.storage.lock().map_err(|_| StatusCode::Other)?;
            let existing = match storage.read(&credential_id) {
                Ok(existing) => Some(existing),
                Err(soft_fido2::Error::DoesNotExist) => None,
                Err(_) => return Err(StatusCode::Other),
            };
            if existing.is_some() && !replace {
                return Err(StatusCode::CredentialExcluded);
            }
            if existing.is_some() {
                storage
                    .delete(&credential_id)
                    .map_err(|_| StatusCode::Other)?;
            }
            if storage.write(Self::credential_ref(&credential)).is_err() {
                if let Some(previous) = existing {
                    let _ = storage.write(Self::credential_ref(&previous));
                }
                return Err(StatusCode::Other);
            }
            Ok(())
        })();

        match result {
            Ok(()) => match soft_fido2_ctap::cbor::MapBuilder::new()
                .insert_bytes(1, &credential_id)
                .and_then(|builder| builder.build())
            {
                Ok(body) => {
                    response.push(StatusCode::Success as u8);
                    response.extend_from_slice(&body);
                }
                Err(_) => response.push(StatusCode::Other as u8),
            },
            Err(status) => response.push(status as u8),
        }
    }

    /// Process a CTAP request and generate a response
    pub fn handle(&mut self, request: &[u8], response_buffer: &mut Vec<u8>) -> Result<()> {
        self.refresh_built_in_uv_state()?;

        if request.first() == Some(&CMD_PASSLESS_BACKUP) {
            self.handle_backup_command(&request[1..], response_buffer);
            return Ok(());
        }
        if request.first() == Some(&CMD_PASSLESS_RESTORE) {
            self.handle_restore_command(&request[1..], response_buffer);
            return Ok(());
        }
        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(());
            }

            // pinUvAuthProtocol (key 3) and pinUvAuthParam (key 4) are optional.
            // When a PIN is configured, the client MUST include them for authorization.
            // When no PIN is configured, the client may omit them, and we skip
            // verification (the command is already gated by local UHID access and
            // the existing passless client reset command works without PIN auth).
            if let (Ok(pin_uv_auth_protocol), Ok(pin_uv_auth_param)) =
                (parser.get::<u8>(3), parser.get_bytes(4))
            {
                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);
                    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 {
        match self.storage.lock() {
            Ok(storage) => format!("Credentials in storage: {}", storage.count_credentials()),
            Err(_) => "Failed to acquire storage lock".to_string(),
        }
    }

    /// Register a custom CTAP command handler
    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;

    use soft_fido2_ctap::SecPinHash;

    struct TestPinStorage {
        state: Mutex<PinState>,
    }

    impl TestPinStorage {
        fn new(state: PinState) -> Self {
            Self {
                state: Mutex::new(state),
            }
        }

        fn set_state(&self, state: PinState) {
            *self.state.lock().expect("test PIN storage lock") = state;
        }
    }

    impl PinStorage for TestPinStorage {
        fn load_pin_state(&self) -> core::result::Result<PinState, StatusCode> {
            self.state
                .lock()
                .map(|state| state.clone())
                .map_err(|_| StatusCode::Other)
        }

        fn save_pin_state(&self, state: &PinState) -> core::result::Result<(), StatusCode> {
            *self.state.lock().map_err(|_| StatusCode::Other)? = state.clone();
            Ok(())
        }
    }

    fn pin_state_with_pin() -> PinState {
        let mut state = PinState::new();
        state.pin_hash = Some(SecPinHash::new([0x42; 32]));
        state
    }

    fn get_info_uv(response: &[u8]) -> Option<bool> {
        assert_eq!(response.first(), Some(&0x00));
        let value: serde_cbor::Value =
            serde_cbor::from_slice(&response[1..]).expect("decode authenticatorGetInfo");
        let info = match value {
            serde_cbor::Value::Map(info) => info,
            other => panic!("expected GetInfo map, got {other:?}"),
        };
        let options = match info.get(&serde_cbor::Value::Integer(4)) {
            Some(serde_cbor::Value::Map(options)) => options,
            other => panic!("expected GetInfo options map, got {other:?}"),
        };
        match options.get(&serde_cbor::Value::Text("uv".to_string())) {
            Some(serde_cbor::Value::Bool(value)) => Some(*value),
            None => None,
            other => panic!("expected boolean uv option, got {other:?}"),
        }
    }

    #[test]
    fn test_get_info_tracks_runtime_pin_policy_without_consuming_uv_retries() {
        let temp_dir = tempfile::tempdir().expect("create temp directory");
        let credential_dir = temp_dir.path().join("credentials");
        std::fs::create_dir_all(&credential_dir).expect("create credential directory");
        let storage = LocalStorageAdapter::new(credential_dir).expect("create credential storage");

        let pin_state = PinState {
            uv_retries: 5,
            ..pin_state_with_pin()
        };
        let pin_storage = Arc::new(Mutex::new(TestPinStorage::new(pin_state)));

        let security_config = SecurityConfig {
            always_uv: true,
            ..Default::default()
        };
        let pin_config = PinConfig {
            enforcement: PinEnforcement::Optional,
            ..Default::default()
        };

        let mut service = AuthenticatorService::with_pin_storage(
            storage,
            Some(pin_storage.clone()),
            security_config,
            pin_config,
        )
        .expect("create authenticator service");

        assert_eq!(
            service
                .authenticator
                .built_in_uv_state()
                .expect("read built-in UV state"),
            BuiltInUvState::SupportedNotConfigured
        );

        let mut response = Vec::new();
        service
            .handle(&[0x04], &mut response)
            .expect("handle GetInfo with PIN");
        assert_eq!(get_info_uv(&response), Some(false));
        assert_eq!(
            pin_storage
                .lock()
                .expect("test PIN storage")
                .load_pin_state()
                .expect("load PIN state")
                .uv_retries,
            5
        );

        pin_storage
            .lock()
            .expect("test PIN storage")
            .set_state(PinState::new());
        service
            .handle(&[0x04], &mut response)
            .expect("handle GetInfo without PIN");
        assert_eq!(get_info_uv(&response), Some(true));
        assert_eq!(
            service
                .authenticator
                .built_in_uv_state()
                .expect("read built-in UV state"),
            BuiltInUvState::Configured
        );

        let mut pin_state = pin_state_with_pin();
        pin_state.uv_retries = 5;
        pin_storage
            .lock()
            .expect("test PIN storage")
            .set_state(pin_state);
        service
            .handle(&[0x04], &mut response)
            .expect("handle GetInfo after restoring PIN");
        assert_eq!(get_info_uv(&response), Some(false));
        assert_eq!(
            pin_storage
                .lock()
                .expect("test PIN storage")
                .load_pin_state()
                .expect("load PIN state")
                .uv_retries,
            5
        );
    }

    #[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,
            enable_credential_backup: 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);
    }

    #[cfg(feature = "agent")]
    #[test]
    fn test_delegated_pin_storage_arc_identity() {
        use crate::pin_storage::local::LocalPinStorage;

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

        let cred_temp = temp_dir.join("creds");
        std::fs::create_dir_all(&cred_temp).unwrap();
        let cred_storage: Arc<Mutex<Box<dyn CredentialStorage>>> = Arc::new(Mutex::new(Box::new(
            LocalStorageAdapter::new(cred_temp).unwrap(),
        )));

        let pin_storage: Arc<Mutex<Box<dyn crate::pin_storage::PinStorage>>> =
            Arc::new(Mutex::new(Box::new(LocalPinStorage::new(temp_dir.clone()))));

        let human_pin_storage_clone = pin_storage.clone();

        let security_config = SecurityConfig::default();
        let pin_config = PinConfig::default();
        let interaction_manager =
            Arc::new(crate::agent::interaction::AgentInteractionManager::new());

        let service = AuthenticatorService::with_shared_storage_and_interaction(
            cred_storage,
            Some(pin_storage.clone()),
            security_config,
            pin_config,
            interaction_manager,
        )
        .expect("Service creation should succeed");

        let _ = &service.authenticator;

        assert!(
            Arc::ptr_eq(&pin_storage, &human_pin_storage_clone),
            "delegated service must share the same Arc<Mutex<PinStorage>> as human"
        );

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