keyroost 0.12.0

Desktop GUI for managing hardware security keys: FIDO2, OATH, OpenPGP, PIV, and Token2 programmable TOTP tokens.
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
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
//! Token2 on-device OTP (TOTP/HOTP) pane for the desktop GUI.
//!
//! This mirrors the OATH pane's structure: a per-selection state struct, a set
//! of `spawn_job`-driven operations that do blocking device I/O off the UI
//! thread, and a `cap_otp` render function. It drives [`keyroost_transport::
//! Token2OtpSession`], which auto-selects USB-HID or CCID/NFC (and can be forced
//! to either).
//!
//! Kept in its own file to avoid growing `main.rs`; the `impl App` blocks here
//! extend the same `App` type via Rust's multi-file inherent-impl support.

use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};

use keyroost_transport::{OtpTransportError, Token2OtpSession};

use crate::ui::theme::{self, BtnKind, Palette};
use crate::{now_secs_f64, wipe, App};

/// Which transport the OTP pane should use. Mirrors the CLI `--transport` flag.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum OtpTransportSel {
    #[default]
    Auto,
    Hid,
    Ccid,
}

impl OtpTransportSel {
    fn label(self) -> &'static str {
        match self {
            OtpTransportSel::Auto => "Auto",
            OtpTransportSel::Hid => "USB-HID",
            OtpTransportSel::Ccid => "CCID/NFC",
        }
    }
}

/// The concrete endpoint the OTP pane opens, resolved from the user's transport
/// choice and the *selected* device's actual interfaces. Binding to a specific
/// HID path / reader name (never "first match") keeps every OTP op on the key
/// the user picked when several are plugged in. GUI-local; see the assembler
/// note if Section E exposes an identical `keyroost_transport::OtpTarget`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum OtpTarget {
    HidPath(PathBuf),
    Reader(String),
    /// An `Auto` pick on a key exposing both interfaces: open USB-HID first
    /// and fall back to the SAME device's PC/SC reader when the HID open (or
    /// its applet probe) fails. Restores the pre-KEY-003 resilience — some
    /// firmware answers the HID GET_INFO probe with a malformed status word
    /// while its CCID side works (#82) — without reopening the first-match
    /// hole: both endpoints came from the one resolved, selected device.
    HidThenReader(PathBuf, String),
}

impl OtpTarget {
    /// Open a Token2 OTP session bound to exactly this endpoint (or endpoint
    /// pair — see [`OtpTarget::HidThenReader`]).
    fn open(&self) -> Result<Token2OtpSession, OtpTransportError> {
        // Honor KEYROOST_OTP_DEBUG so a stuck/empty list can be traced from the
        // GUI (matches the KEYROOST_CTAP_DEBUG convention; the CLI has --debug).
        let debug = std::env::var_os("KEYROOST_OTP_DEBUG").is_some();
        match self {
            OtpTarget::HidPath(p) => Token2OtpSession::open_hid_path(p, debug),
            OtpTarget::Reader(r) => Token2OtpSession::open_pcsc_reader(r, debug),
            OtpTarget::HidThenReader(p, r) => match Token2OtpSession::open_hid_path(p, debug) {
                Ok(s) => Ok(s),
                Err(hid_err) => Token2OtpSession::open_pcsc_reader(r, debug).map_err(|ccid_err| {
                    OtpTransportError::TransportUnavailable(format!(
                        "USB-HID failed ({hid_err}); the same key's smart-card \
                         fallback also failed ({ccid_err})"
                    ))
                }),
            },
        }
    }
}

/// Decide which endpoint to open for `sel`, given the selected device's resolved
/// USB-HID path and PC/SC reader name. Fails closed (`Err`) when the choice is
/// unsatisfiable — an explicit HID/CCID pick with no matching interface, or an
/// `Auto` pick on a device that resolved to neither — so the pane surfaces an
/// error instead of silently opening the first key on the bus. Pure + testable.
fn otp_target_for(
    sel: OtpTransportSel,
    hid_path: Option<&Path>,
    reader: Option<&str>,
) -> Result<OtpTarget, String> {
    match sel {
        OtpTransportSel::Hid => hid_path
            .map(|p| OtpTarget::HidPath(p.to_path_buf()))
            .ok_or_else(|| {
                "the selected key has no USB-HID interface; switch the transport to CCID/NFC"
                    .to_string()
            }),
        OtpTransportSel::Ccid => {
            reader
                .map(|r| OtpTarget::Reader(r.to_string()))
                .ok_or_else(|| {
                    "the selected key has no PC/SC reader; switch the transport to USB-HID"
                        .to_string()
                })
        }
        // Auto prefers USB-HID (the old detect_debug probe order tried HID
        // first) but keeps the same device's reader as an open-time fallback
        // when both exist — some firmware botches the HID applet probe while
        // its CCID side works (#82). A key with only a reader naturally
        // resolves to CCID/NFC.
        OtpTransportSel::Auto => match (hid_path, reader) {
            (Some(p), Some(r)) => Ok(OtpTarget::HidThenReader(p.to_path_buf(), r.to_string())),
            (Some(p), None) => Ok(OtpTarget::HidPath(p.to_path_buf())),
            (None, Some(r)) => Ok(OtpTarget::Reader(r.to_string())),
            (None, None) => Err("the selected key exposes no OTP-capable interface".to_string()),
        },
    }
}

/// One row in the OTP list: the stored entry plus the live code (when the
/// device returned one — TOTP without a button requirement).
pub struct OtpRow {
    pub app_name: String,
    pub account_name: String,
    pub type_str: &'static str,
    pub algo_str: &'static str,
    pub button_required: bool,
    pub code: Option<String>,
    /// TOTP time-step in seconds (e.g. 30 or 60), straight from the entry
    /// record's `timestep` field. Meaningful only for TOTP entries.
    pub period: u16,
}

impl OtpRow {
    /// Display label `app:account`, or just `account` when the app name is empty.
    fn label(&self) -> String {
        if self.app_name.is_empty() {
            self.account_name.clone()
        } else {
            format!("{}:{}", self.app_name, self.account_name)
        }
    }
}

/// "Add OTP entry" dialog state.
pub struct OtpAddDialog {
    pub open: bool,
    pub app_name: String,
    pub account_name: String,
    /// Base32 secret, entered masked.
    pub secret: String,
    /// True = TOTP, false = HOTP.
    pub totp: bool,
    /// True = SHA256, false = SHA1.
    pub sha256: bool,
    pub digits: u8,
    pub period: u16,
    pub require_touch: bool,
}

impl Default for OtpAddDialog {
    fn default() -> Self {
        OtpAddDialog {
            open: false,
            app_name: String::new(),
            account_name: String::new(),
            secret: String::new(),
            totp: true,
            sha256: false,
            digits: 6,
            period: 30,
            require_touch: false,
        }
    }
}

// Wipe the typed seed on drop (the form is replaced wholesale after submit).
impl Drop for OtpAddDialog {
    fn drop(&mut self) {
        wipe(&mut self.secret);
    }
}

/// Dialog state for configuring the HOTP-on-touch keystroke slot: the key types
/// a fresh HOTP code as keyboard input when touched outside any session.
pub struct ButtonHotpDialog {
    pub open: bool,
    /// Base32 secret, entered masked.
    pub secret: String,
    /// 6 or 8.
    pub digits: u8,
    /// Append an Enter keystroke after the code.
    pub send_enter: bool,
    /// Require a 2-second long touch (else a short tap triggers it).
    pub long_touch: bool,
    /// Type digits using the numeric-keypad scancodes.
    pub numpad: bool,
}

impl Default for ButtonHotpDialog {
    fn default() -> Self {
        ButtonHotpDialog {
            open: false,
            secret: String::new(),
            digits: 6,
            send_enter: true,
            long_touch: false,
            numpad: false,
        }
    }
}

impl Drop for ButtonHotpDialog {
    fn drop(&mut self) {
        wipe(&mut self.secret);
    }
}

/// Current enabled-state of the key's three USB interfaces, read from the device
/// config. Used to show the keyboard-HID toggle and to keep at least two
/// interfaces enabled when changing one.
#[derive(Clone, Copy)]
pub struct IfaceState {
    pub fido: bool,
    pub keyboard: bool,
    pub ccid: bool,
}

/// Current state of the HOTP-on-button keystroke slot, read from the device
/// config. Lets the UI show whether a seed is provisioned and edit the typing
/// options without re-entering the seed.
#[derive(Clone, Copy)]
pub struct ButtonHotpStatus {
    /// A seed is provisioned in the button-HOTP slot (config bit 8).
    pub configured: bool,
    /// The slot types Enter after the code.
    pub send_enter: bool,
    /// Long-press is required to emit the code.
    pub long_touch: bool,
    /// Codes are typed using the numeric keypad layout.
    pub numpad: bool,
}

impl IfaceState {
    fn enabled_count(&self) -> usize {
        [self.fido, self.keyboard, self.ccid]
            .iter()
            .filter(|x| **x)
            .count()
    }
}

/// Pending keyboard-HID toggle awaiting a typed-phrase confirmation.
pub struct KbdToggle {
    /// The state keyboard-HID will be set to.
    pub enable: bool,
    /// What the user has typed; must match the required phrase to proceed.
    pub typed: String,
}

/// Which OTP-PIN management action a [`PinDialog`] performs.
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum PinDialogKind {
    /// Set a PIN on a currently-unprotected key.
    Set,
    /// Change the PIN (needs the current PIN + a new one).
    Change,
    /// Remove the PIN (needs the current PIN).
    Remove,
}

/// A modal for setting / changing / removing the OTP PIN. `current`/`new` are
/// masked inputs; which are shown depends on `kind`. Wiped on drop.
#[derive(Default)]
pub struct PinDialog {
    pub kind_set: bool,
    pub kind_remove: bool,
    pub current: String,
    pub new: String,
    pub confirm: String,
}

impl Drop for PinDialog {
    fn drop(&mut self) {
        use zeroize::Zeroize;
        self.current.zeroize();
        self.new.zeroize();
        self.confirm.zeroize();
    }
}

impl PinDialog {
    fn for_kind(kind: PinDialogKind) -> Self {
        PinDialog {
            kind_set: kind == PinDialogKind::Set,
            kind_remove: kind == PinDialogKind::Remove,
            current: String::new(),
            new: String::new(),
            confirm: String::new(),
        }
    }
    fn kind(&self) -> PinDialogKind {
        if self.kind_set {
            PinDialogKind::Set
        } else if self.kind_remove {
            PinDialogKind::Remove
        } else {
            PinDialogKind::Change
        }
    }
}

/// Result of a successful OTP-pane load: the entry rows plus the device facts the
/// pane shows (transport label, serial, touch-HOTP availability, interface state).
struct OtpLoad {
    rows: Vec<OtpRow>,
    active: &'static str,
    serial: Option<String>,
    touch_ok: Option<bool>,
    touch_why: Option<&'static str>,
    /// Whether the key MODEL supports HOTP-on-touch at all (distinct from the
    /// keyboard interface merely being disabled). `None` if config unreadable.
    hotp_supported: Option<bool>,
    /// Whether the key MODEL has the on-device OTP function. `None` when the
    /// config couldn't be read (or was too short to say); see [`totp_capability`].
    totp_supported: Option<bool>,
    iface: Option<IfaceState>,
    button_hotp_status: Option<ButtonHotpStatus>,
    /// What the key itself said about its OTP PIN during this read: `Some(true)`
    /// a PIN is set, `Some(false)` the feature is present and unset, `None` the
    /// key does not offer the feature at all.
    pin_set: Option<bool>,
    /// Cached FpEnable from the same flag read: fingerprint protection enabled.
    fp_enabled: Option<bool>,
}

/// Per-selection state for the OTP pane.
#[derive(Default)]
pub struct OtpState {
    pub transport: OtpTransportSel,
    pub rows: Vec<OtpRow>,
    pub error: Option<String>,
    pub info: Option<String>,
    pub loaded: bool,
    pub add: OtpAddDialog,
    /// Dialog for the HOTP-on-touch keystroke slot.
    pub button_hotp: ButtonHotpDialog,
    pub confirm_delete: Option<(String, String)>,
    /// PIN entry buffer for a protected (R3.4+) key. Held only while unlocking.
    pub pin_input: String,
    /// Set when the last read reported the key is PIN-protected and no valid PIN
    /// has been entered yet — drives the unlock prompt instead of the list.
    pub pin_required: bool,
    /// The verified PIN for the current selection, reused across refreshes so the
    /// user isn't re-prompted every reload. Cleared when the device changes.
    pub pin: Option<zeroize::Zeroizing<String>>,
    /// Open PIN-management dialog (set / change / remove), if any.
    pub pin_dialog: Option<PinDialog>,
    /// Whether the key currently has an OTP PIN set (R3.4+). `None` until known.
    /// Drives which PIN menu items appear (Set vs Change/Remove/Lock).
    pub pin_set: Option<bool>,
    /// Whether fingerprint protection is enabled on the key (cached FpEnable).
    /// Drives the "Touch fingerprint" option on the unlock prompt and the
    /// enable/disable item in the "..." menu. `None` until known.
    pub fp_enabled: Option<bool>,
    /// Active transport label after a successful open (for the status line).
    pub active: Option<&'static str>,
    /// Device serial number (hex), read alongside the entry list when available.
    pub serial: Option<String>,
    /// Whether the key currently supports HOTP-on-touch (keyboard-HID enabled and
    /// the feature present). `None` until determined. Drives the Touch HOTP button.
    pub touch_hotp_ok: Option<bool>,
    /// Why touch-HOTP is unavailable, for the disabled-button tooltip.
    pub touch_hotp_why: Option<&'static str>,
    /// Whether the key MODEL supports HOTP-on-touch at all (distinct from the
    /// keyboard interface being toggled off). Gates the "Enable HID-HOTP" item.
    /// `None` until known.
    pub hotp_supported: Option<bool>,
    /// Whether the key was supplied WITH the on-device OTP function. `Some(false)`
    /// replaces the entry list and the add control with a plain explanation.
    /// `None` (unknown) leaves the pane exactly as it behaves today.
    pub totp_supported: Option<bool>,
    /// Current interface enabled-states (fido, keyboard-HID, ccid), read from the
    /// device config on load. `None` until known.
    pub iface: Option<IfaceState>,
    /// Pending keyboard-HID toggle confirmation: the target state and the typed
    /// confirmation phrase. `Some` while the confirm dialog is open.
    pub kbd_confirm: Option<KbdToggle>,
    /// Codes read on-demand for touch-required TOTP entries, keyed by
    /// `(app_name, account_name)`. Populated when the user presses "Read" and
    /// touches the key; shown in place of "touch to view" until the list reloads.
    pub touch_codes: std::collections::HashMap<(String, String), String>,
    /// Cached button-HOTP slot status from the device config: whether a seed is
    /// configured, and the current send-Enter / long-touch / numpad settings.
    /// `None` until read. Drives the "seed configured" indicator and the
    /// settings-only editor.
    pub button_hotp_status: Option<ButtonHotpStatus>,
}

impl Drop for OtpState {
    /// Scrub the PIN entry buffer when the pane state is torn down — which is
    /// what a device switch does (`self.otp = OtpState::default()`), so a PIN
    /// typed for one key must not survive into the next selection's memory.
    /// The `pin` field is `Zeroizing` and wipes itself; `pin_input` is a plain
    /// `String` because egui edits it in place, so it needs this.
    fn drop(&mut self) {
        wipe(&mut self.pin_input);
    }
}

fn unix_now() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0)
}

/// What the key's own config block says about the on-device OTP (TOTP) function.
///
/// Token2 keys are supplied in configurations that differ by which functions are
/// enabled, and the set is fixed at manufacture — a key made without on-device
/// OTP can't gain it later. The device advertises the function in the capability
/// bits of its config block, so the pane can say "this key doesn't have it"
/// instead of offering controls whose first command comes back as a protocol
/// error.
///
/// * `Some(true)`  — the key advertises the function.
/// * `Some(false)` — the key answered with a full config block and the bit is
///   clear: it was supplied without the on-device OTP function.
/// * `None` — we can't tell. Either no config was read, or the key answered with
///   a block too short to reach the capability byte. Callers must treat `None` as
///   "offer the feature anyway": hiding it because a read failed would be worse
///   than letting the attempt report its own error.
///
/// This only helps when the config read SUCCEEDS. A key whose config exchange
/// itself fails never yields a capability byte, and that failure is reported
/// unchanged.
fn totp_capability(info: Option<&keyroost_token2otp::DeviceInfo>) -> Option<bool> {
    let info = info?;
    // The capability bits live in byte 9. Some firmware answers READ_CONFIG with
    // only the leading interface-state byte(s); the parser zero-fills the rest,
    // which would read back as a confident "unsupported". Require a block long
    // enough to actually contain byte 9 before believing a clear bit.
    if info.raw_len < 10 {
        return None;
    }
    Some(info.totp_supported())
}

impl App {
    /// Resolve the OTP endpoint for the current selection + transport choice.
    /// `Err` when nothing is selected or the selection can't satisfy the pick.
    fn otp_target(&self) -> Result<OtpTarget, String> {
        let dev = self
            .selected_device()
            .ok_or_else(|| "no key selected".to_string())?;
        otp_target_for(
            self.otp.transport,
            dev.hid_path.as_deref(),
            dev.reader.as_deref(),
        )
    }

    /// Unlock the codes by a fingerprint touch (from the unlock prompt). Spawns a
    /// job that establishes the session, waits for the sensor touch, and reads
    /// the entries; on failure the prompt stays up with the error so the user can
    /// retry or use the PIN instead.
    pub(crate) fn unlock_otp_fingerprint(&mut self) {
        self.otp.error = None;
        let target = match self.otp_target() {
            Ok(t) => t,
            Err(e) => {
                self.otp.error = Some(e);
                return;
            }
        };
        let for_device = self.selected_device.clone();
        self.spawn_job("Touch the fingerprint sensor\u{2026}", move || {
            let result = (|| -> Result<Vec<OtpRow>, OtpTransportError> {
                let mut session = target.open()?;
                session.verify_fingerprint()?;
                let now = unix_now();
                let entries = session.enumerate(now)?;
                Ok(entries
                    .into_iter()
                    .map(|e| OtpRow {
                        app_name: e.app_name,
                        account_name: e.account_name,
                        type_str: keyroost_transport::otp_type_str(e.otp_type),
                        algo_str: otp_algo_str(e.algorithm),
                        button_required: e.button_required,
                        code: e.code,
                        period: e.timestep,
                    })
                    .collect())
            })();
            Box::new(move |app: &mut App| {
                if app.selected_device != for_device {
                    return;
                }
                match result {
                    Ok(rows) => {
                        app.otp.rows = rows;
                        app.otp.pin_required = false;
                        app.otp.loaded = true;
                        app.otp.error = None;
                    }
                    // Touch failed / wrong finger: keep the prompt up with the
                    // message; the user can retry the sensor or type the PIN.
                    Err(e) => {
                        app.otp.error = Some(e.to_string());
                        app.otp.pin_required = true;
                        app.otp.loaded = true;
                    }
                }
            })
        });
    }

    /// List entries on the selected key over the chosen transport.
    pub(crate) fn load_otp_entries(&mut self) {
        self.otp.error = None;
        // Bind I/O to the *selected* device (KEY-003). Auto prefers this key's
        // USB-HID interface and falls back to its reader; an unresolved or
        // ambiguous selection fails closed here rather than opening another key.
        let target = match self.otp_target() {
            Ok(t) => t,
            Err(e) => {
                self.otp.error = Some(e);
                self.otp.loaded = true; // show the error, not a stuck "Reading…"
                return;
            }
        };
        if std::env::var_os("KEYROOST_OTP_DEBUG").is_some() {
            eprintln!(
                "[otp gui] target={target:?} (user_sel={})",
                self.otp.transport.label()
            );
        }
        let for_device = self.selected_device.clone();
        // Move the (already-verified) PIN, if any, into the read job so a
        // protected key's codes decrypt. `None` means "unprotected, or not yet
        // unlocked" — enumerate_pinned then reports PinRequired for a protected
        // key, which the completion handler turns into the unlock prompt.
        // Clone as `Zeroizing`, not `String`: this copy travels into a worker
        // thread and is dropped there, so a plain clone would leave the PIN in
        // that thread's heap with nothing left to wipe it.
        let pin: Option<zeroize::Zeroizing<String>> = self.otp.pin.clone();
        self.spawn_job("Reading OTP entries\u{2026}", move || {
            let result =
                (|| -> Result<OtpLoad, OtpTransportError> {
                    let mut session = target.open()?;
                    let active = if session.is_pcsc() {
                        "CCID/NFC"
                    } else {
                        "USB-HID"
                    };
                    // Over a PC/SC reader (NFC/contact) we still skip the
                    // best-effort serial read: `read_serial` selects the FIDO
                    // applet, a detour only needed for display, and a missing
                    // serial string degrades gracefully. The device-config read
                    // is no longer skipped — it drives the keyboard-HID toggle —
                    // but it runs only after enumeration; see below.
                    let pcsc = session.is_pcsc();
                    let serial = if pcsc {
                        None
                    } else {
                        session
                            .read_serial()
                            .ok()
                            .map(|sn| sn.iter().map(|b| format!("{b:02x}")).collect::<String>())
                    };
                    // Enumerate the codes FIRST. The list is the primary result
                    // and must never be held hostage by the config read below —
                    // some contact (T=0) readers stall on the Case-2 READ_CONFIG
                    // APDU, and the PC/SC transport sets no deadline of its own,
                    // so a stall lasts as long as the reader driver allows.
                    // Reading codes first means any config trouble can only cost
                    // the (secondary) interface toggle, never the codes.
                    let now = unix_now();
                    // Carries the config read across both arms below so a failed
                    // enumerate doesn't cost a second READ_CONFIG.
                    let mut dev_info: Option<keyroost_token2otp::DeviceInfo> = None;
                    let rows: Vec<OtpRow> = match session.enumerate_pinned(now, pin.as_ref().map(|p| p.as_str())) {
                        Ok(entries) => entries
                            .into_iter()
                            .map(|e| OtpRow {
                                app_name: e.app_name,
                                account_name: e.account_name,
                                type_str: keyroost_transport::otp_type_str(e.otp_type),
                                algo_str: otp_algo_str(e.algorithm),
                                button_required: e.button_required,
                                code: e.code,
                                period: e.timestep,
                            })
                            .collect(),
                        Err(e) => {
                            // Enumeration failed. Before showing a raw protocol
                            // error, ask the key whether it has the on-device OTP
                            // function at all: keys supplied without it answer the
                            // config read fine and simply advertise the function as
                            // absent, which deserves a plain explanation rather than
                            // a status word. Anything else (including a config read
                            // that fails in its own right) keeps the original error.
                            dev_info = session.read_device_info().ok();
                            if totp_capability(dev_info.as_ref()) != Some(false) {
                                return Err(e);
                            }
                            Vec::new()
                        }
                    };

                    // Now read the device config for the interface states (which
                    // drive the keyboard-HID / HID-HOTP toggle) and touch-HOTP
                    // hints. Best-effort: `.ok()` swallows a failure so a reader
                    // that can't answer leaves `dev_info` = None (toggle hidden),
                    // exactly as before — and because it runs AFTER enumerate, a
                    // stall or error here cannot affect the code list. (The load
                    // is delivered in one piece, so a stall still costs wall-clock
                    // time before anything renders — but the list arrives
                    // complete rather than empty.)
                    //
                    // Over the key's own CCID/NFC this returns the full 64-byte
                    // block (verified on hardware), so the toggle appears. Over a
                    // genuine T=0 contact reader it may stall; that costs the
                    // toggle and the wait, not the codes.
                    if dev_info.is_none() {
                        dev_info = session.read_device_info().ok();
                    }
                    let (touch_ok, touch_why): (Option<bool>, Option<&'static str>) =
                        match &dev_info {
                            Some(info) => {
                                if !info.button_hotp_supported() {
                                    (Some(false), Some("this key was supplied without the HOTP-on-touch function; keys aren't upgradable after purchase, so it can't be enabled here"))
                                } else if info.hotp_keystroke_disabled() {
                                    (Some(false), Some("the keyboard-HID interface is disabled on this key; enable it to use HOTP-on-touch"))
                                } else {
                                    (Some(true), None)
                                }
                            }
                            // Couldn't read config (older model / reader quirk):
                            // leave it permitted rather than wrongly blocking.
                            None => (None, None),
                        };
                    let iface = dev_info.as_ref().map(|info| IfaceState {
                        fido: !info.fido_disabled(),
                        keyboard: !info.hotp_keystroke_disabled(),
                        ccid: !info.ccid_disabled(),
                    });
                    // Model-level support, separate from the interface toggle so
                    // the UI can disable "Enable HID-HOTP" on keys that lack the
                    // feature entirely (vs merely having the interface off).
                    let hotp_supported = dev_info.as_ref().map(|i| i.button_hotp_supported());
                    let totp_supported = totp_capability(dev_info.as_ref());
                    let button_hotp_status = dev_info.as_ref().and_then(|info| {
                        // The seed bit lives in byte 1; over a short CCID stub
                        // (byte 0 only) we can't tell, so report unknown rather
                        // than a misleading "no seed configured".
                        if !info.has_config_byte() {
                            return None;
                        }
                        Some(ButtonHotpStatus {
                            configured: info.button_hotp_configured(),
                            send_enter: !info.hotp_suppresses_enter(),
                            long_touch: info.hotp_long_press(),
                            numpad: info.hotp_uses_numpad(),
                        })
                    });
                    // The flag read that `enumerate_pinned` already performed,
                    // read back off the same connection — no extra round trip,
                    // and it is the key's answer rather than an inference from
                    // whether we happened to hold a PIN.
                    let pin_set = session.pin_set_cached();
                    let fp_enabled = session.fp_enabled_cached();
                    Ok(OtpLoad {
                        rows,
                        active,
                        pin_set,
                        fp_enabled,
                        serial,
                        touch_ok,
                        touch_why,
                        hotp_supported,
                        totp_supported,
                        iface,
                        button_hotp_status,
                    })
                })();
            Box::new(move |app: &mut App| {
                if app.selected_device != for_device {
                    return; // user switched keys mid-read
                }
                match result {
                    Ok(load) => {
                        app.otp.rows = load.rows;
                        app.otp.loaded = true;
                        app.otp.active = Some(load.active);
                        app.otp.serial = load.serial;
                        app.otp.touch_hotp_ok = load.touch_ok;
                        app.otp.touch_hotp_why = load.touch_why;
                        app.otp.hotp_supported = load.hotp_supported;
                        app.otp.totp_supported = load.totp_supported;
                        app.otp.iface = load.iface;
                        app.otp.button_hotp_status = load.button_hotp_status;
                        // Codes read on touch are tied to the old time-window;
                        // drop them so the freshly-loaded list governs display.
                        app.otp.touch_codes.clear();
                        app.otp.error = None;
                        // A successful read means either the key isn't protected
                        // or the stored PIN worked — leave the prompt state off.
                        app.otp.pin_required = false;
                        // Straight from the device's flag read. Inferring it
                        // from `app.otp.pin.is_some()` got this wrong whenever
                        // the key's own window was already open: the read
                        // succeeded without a PIN, so the pane reported "no PIN"
                        // and hid Change / Remove / Lock on a protected key.
                        app.otp.pin_set = load.pin_set;
                        app.otp.fp_enabled = load.fp_enabled;
                    }
                    Err(e) => {
                        if std::env::var_os("KEYROOST_OTP_DEBUG").is_some() {
                            eprintln!("[otp gui] load error variant: {e:?}");
                        }
                        // A protected key with no (or a wrong) PIN: flip the pane
                        // into its unlock prompt rather than showing a raw error.
                        if matches!(e, keyroost_transport::OtpTransportError::PinRequired) {
                            app.otp.pin_required = true;
                            app.otp.pin_set = Some(true);
                            app.otp.rows.clear();
                            app.otp.loaded = true;
                            app.otp.error = None;
                        } else {
                            // A wrong PIN invalidates the stored one so the prompt
                            // reappears instead of silently failing every refresh.
                            if matches!(
                                e,
                                keyroost_transport::OtpTransportError::Applet(
                                    keyroost_token2otp::OtpError::PinInvalid
                                ) | keyroost_transport::OtpTransportError::Applet(
                                    keyroost_token2otp::OtpError::PinInvalidRetries(_)
                                )
                            ) {
                                app.otp.pin = None;
                                app.otp.pin_required = true;
                            }
                            app.otp.error = Some(e.to_string());
                            app.otp.loaded = true;
                        }
                    }
                }
            })
        });
    }

    /// Provision the entry described by the add-dialog fields.
    pub(crate) fn provision_otp(&mut self) {
        self.otp.error = None;
        let app_name = self.otp.add.app_name.trim().to_owned();
        let account_name = self.otp.add.account_name.trim().to_owned();
        if account_name.is_empty() {
            self.otp.error = Some("account name is required".into());
            return;
        }
        if self.otp.add.secret.trim().is_empty() {
            self.otp.error = Some("Enter a Base32 secret for this entry.".into());
            return;
        }
        let secret = zeroize::Zeroizing::new(self.otp.add.secret.clone());
        let totp = self.otp.add.totp;
        let sha256 = self.otp.add.sha256;
        let digits = self.otp.add.digits;
        let period = self.otp.add.period;
        let touch = self.otp.add.require_touch;
        let target = match self.otp_target() {
            Ok(t) => t,
            Err(e) => {
                self.otp.error = Some(e);
                return;
            }
        };
        let for_device = self.selected_device.clone();
        // Carry the verified PIN (if the key is protected and already unlocked)
        // so the write takes the session-key path the device requires.
        // Clone as `Zeroizing`, not `String`: this copy travels into a worker
        // thread and is dropped there, so a plain clone would leave the PIN in
        // that thread's heap with nothing left to wipe it.
        let pin: Option<zeroize::Zeroizing<String>> = self.otp.pin.clone();

        self.spawn_job("Adding OTP entry\u{2026}", move || {
            let result = (|| -> Result<(), String> {
                let seed = keyroost_token2otp::decode_base32_seed(secret.trim())
                    .map_err(|m| format!("invalid Base32 secret: {m}"))?;
                let mut session = target.open().map_err(|e| e.to_string())?;
                let entry = keyroost_token2otp::WriteEntry {
                    otp_type: if totp {
                        keyroost_token2otp::OtpType::Totp
                    } else {
                        keyroost_token2otp::OtpType::Hotp
                    },
                    algorithm: if sha256 {
                        keyroost_token2otp::Algorithm::Sha256
                    } else {
                        keyroost_token2otp::Algorithm::Sha1
                    },
                    timestep: period,
                    code_length: digits,
                    button_required: touch,
                    app_name: &app_name,
                    account_name: &account_name,
                    seed: &seed,
                };
                session
                    .write_entry_pinned(&entry, pin.as_ref().map(|p| p.as_str()))
                    .map_err(|e| e.to_string())
            })();
            Box::new(move |app: &mut App| {
                if app.selected_device != for_device {
                    return;
                }
                match result {
                    Ok(()) => {
                        app.otp.add = OtpAddDialog::default();
                        app.otp.info = Some("OTP entry added.".into());
                        app.load_otp_entries();
                    }
                    Err(e) => app.otp.error = Some(e.to_string()),
                }
            })
        });
    }

    /// Configure the HOTP-on-touch keystroke slot from the dialog fields.
    pub(crate) fn provision_button_hotp(&mut self) {
        self.otp.error = None;
        let digits = self.otp.button_hotp.digits;
        if digits != 6 && digits != 8 {
            self.otp.error = Some("button HOTP digits must be 6 or 8".into());
            return;
        }
        // An empty secret field means "don't change the seed" — just apply the
        // typing options (Send Enter / long touch / numeric keypad). This works
        // whether or not a seed is already configured: with a seed it edits the
        // options in place; without one it sets the options the device will use
        // once a seed is written. Either way the seed slot is left untouched.
        if self.otp.button_hotp.secret.trim().is_empty() {
            let send_enter = self.otp.button_hotp.send_enter;
            let long_touch = self.otp.button_hotp.long_touch;
            let numpad = self.otp.button_hotp.numpad;
            self.otp.button_hotp.open = false;
            self.apply_button_hotp_options(send_enter, long_touch, numpad);
            return;
        }
        let secret = zeroize::Zeroizing::new(self.otp.button_hotp.secret.clone());
        let send_enter = self.otp.button_hotp.send_enter;
        let long_touch = self.otp.button_hotp.long_touch;
        let numpad = self.otp.button_hotp.numpad;
        let target = match self.otp_target() {
            Ok(t) => t,
            Err(e) => {
                self.otp.error = Some(e);
                return;
            }
        };
        let for_device = self.selected_device.clone();

        self.spawn_job("Setting touch HOTP\u{2026}", move || {
            let result = (|| -> Result<(), String> {
                let seed = keyroost_token2otp::decode_base32_seed(secret.trim())
                    .map_err(|m| format!("invalid Base32 secret: {m}"))?;
                let mut session = target.open().map_err(|e| e.to_string())?;
                session
                    .set_button_hotp(digits, &seed, send_enter, long_touch, numpad)
                    .map_err(|e| e.to_string())
            })();
            Box::new(move |app: &mut App| {
                if app.selected_device != for_device {
                    return;
                }
                match result {
                    Ok(()) => {
                        app.otp.button_hotp = ButtonHotpDialog::default();
                        app.otp.info = Some("Touch HOTP configured.".into());
                        // Re-read the config so the "seed configured" status and
                        // the settings-only editor reflect the new slot.
                        app.load_otp_entries();
                    }
                    Err(e) => app.otp.error = Some(e.to_string()),
                }
            })
        });
    }

    /// Apply a keyboard-HID enable/disable, preserving the other two interfaces
    /// and never dropping below two enabled. Built from the cached `iface` state.
    pub(crate) fn apply_keyboard_toggle(&mut self, enable: bool) {
        self.otp.error = None;
        let Some(cur) = self.otp.iface else {
            self.otp.error = Some("interface state unknown; refresh first".into());
            return;
        };
        // Compute the resulting state and enforce the two-interface minimum.
        let next = IfaceState {
            fido: cur.fido,
            keyboard: enable,
            ccid: cur.ccid,
        };
        if next.enabled_count() < 2 {
            self.otp.error = Some(
                "at least two interfaces must stay enabled; enable another interface first".into(),
            );
            return;
        }
        // Build the SET_DEVICE_TYPE *disable* mask (set bit = disable).
        use keyroost_token2otp::{DEV_CCID, DEV_FIDO, DEV_KEYBOARD};
        let mut disable: u8 = 0;
        if !next.fido {
            disable |= DEV_FIDO;
        }
        if !next.keyboard {
            disable |= DEV_KEYBOARD;
        }
        if !next.ccid {
            disable |= DEV_CCID;
        }
        let target = match self.otp_target() {
            Ok(t) => t,
            Err(e) => {
                self.otp.error = Some(e);
                return;
            }
        };
        let for_device = self.selected_device.clone();
        self.spawn_job("Updating interfaces\u{2026}", move || {
            let result = (|| -> Result<(), String> {
                let mut session = target.open().map_err(|e| e.to_string())?;
                session.set_device_type(disable).map_err(|e| e.to_string())
            })();
            Box::new(move |app: &mut App| {
                if app.selected_device != for_device {
                    return;
                }
                match result {
                    Ok(()) => {
                        app.otp.info = Some(
                            "Interface updated. Re-plug the key for the change to take effect."
                                .into(),
                        );
                        // Reflect the change locally; a refresh re-reads from hardware.
                        app.otp.iface = Some(next);
                    }
                    Err(e) => app.otp.error = Some(e),
                }
            })
        });
    }

    /// Clear the HOTP-on-touch keystroke slot.
    pub(crate) fn delete_button_hotp_slot(&mut self) {
        self.otp.error = None;
        let target = match self.otp_target() {
            Ok(t) => t,
            Err(e) => {
                self.otp.error = Some(e);
                return;
            }
        };
        let for_device = self.selected_device.clone();
        self.spawn_job("Clearing touch HOTP\u{2026}", move || {
            let result = (|| -> Result<(), String> {
                let mut session = target.open().map_err(|e| e.to_string())?;
                session.delete_button_hotp().map_err(|e| e.to_string())
            })();
            Box::new(move |app: &mut App| {
                if app.selected_device != for_device {
                    return;
                }
                match result {
                    Ok(()) => {
                        app.otp.info = Some("Touch HOTP cleared.".into());
                        app.load_otp_entries();
                    }
                    Err(e) => app.otp.error = Some(e.to_string()),
                }
            })
        });
    }

    /// Delete the entry identified by `(app, account)`.
    pub(crate) fn delete_otp_entry(&mut self, app_name: String, account_name: String) {
        self.otp.error = None;
        let target = match self.otp_target() {
            Ok(t) => t,
            Err(e) => {
                self.otp.error = Some(e);
                return;
            }
        };
        let for_device = self.selected_device.clone();
        // Clone as `Zeroizing`, not `String`: this copy travels into a worker
        // thread and is dropped there, so a plain clone would leave the PIN in
        // that thread's heap with nothing left to wipe it.
        let pin: Option<zeroize::Zeroizing<String>> = self.otp.pin.clone();
        self.spawn_job("Deleting OTP entry\u{2026}", move || {
            let result = (|| -> Result<(), OtpTransportError> {
                let mut session = target.open()?;
                session.delete_entry_pinned(
                    &app_name,
                    &account_name,
                    pin.as_ref().map(|p| p.as_str()),
                )
            })();
            Box::new(move |app: &mut App| {
                if app.selected_device != for_device {
                    return;
                }
                match result {
                    Ok(()) => {
                        app.otp.info = Some("OTP entry deleted.".into());
                        app.load_otp_entries();
                    }
                    Err(e) => app.otp.error = Some(e.to_string()),
                }
            })
        });
    }

    /// Lock the OTP PIN window now, clearing the cached PIN so the next read
    /// re-prompts.
    pub(crate) fn lock_otp_pin(&mut self) {
        self.otp.error = None;
        let target = match self.otp_target() {
            Ok(t) => t,
            Err(e) => {
                self.otp.error = Some(e);
                return;
            }
        };
        let for_device = self.selected_device.clone();
        // Clone as `Zeroizing`, not `String`: this copy travels into a worker
        // thread and is dropped there, so a plain clone would leave the PIN in
        // that thread's heap with nothing left to wipe it.
        let pin: Option<zeroize::Zeroizing<String>> = self.otp.pin.clone();
        self.spawn_job("Locking OTP PIN\u{2026}", move || {
            let result = (|| -> Result<(), OtpTransportError> {
                let mut session = target.open()?;
                // Ask to close the window first. The window is device-side
                // state, and the lock form of VERIFY carries no PIN, so on a
                // key that accepts it bare this costs nothing. Verifying first
                // — as this did — spends one of a finite number of retries
                // every time the user presses Lock, and spends it on a cached
                // PIN that may since have been changed on another host.
                match session.lock_pin() {
                    // The one answer that means "there was no session to close
                    // this way": open one with the PIN we hold and lock again.
                    Err(OtpTransportError::Applet(
                        keyroost_token2otp::OtpError::PinConditionsNotSatisfied,
                    )) => {
                        if let Some(p) = pin.as_deref() {
                            session.verify_pin(p)?;
                            session.lock_pin()
                        } else {
                            Ok(())
                        }
                    }
                    other => other,
                }
            })();
            Box::new(move |app: &mut App| {
                if app.selected_device != for_device {
                    return;
                }
                app.otp.pin = None;
                app.otp.pin_required = true;
                app.otp.rows.clear();
                match result {
                    Ok(()) => app.otp.info = Some("OTP PIN locked.".into()),
                    Err(e) => app.otp.error = Some(e.to_string()),
                }
            })
        });
    }

    /// Enable or disable fingerprint protection for OTP. Uses the PIN already
    /// cached this session; if none is cached, routes through the unlock prompt
    /// first (the user enters the PIN, then retries the toggle).
    pub(crate) fn set_otp_fp_protection(&mut self, enable: bool) {
        let pin = match &self.otp.pin {
            Some(p) => p.to_string(),
            None => {
                self.otp.pin_required = true;
                self.otp.error =
                    Some("Enter the OTP PIN first, then use the Fingerprint menu.".into());
                return;
            }
        };
        self.otp.error = None;
        let target = match self.otp_target() {
            Ok(t) => t,
            Err(e) => {
                self.otp.error = Some(e);
                return;
            }
        };
        let for_device = self.selected_device.clone();
        self.spawn_job("Updating fingerprint protection\u{2026}", move || {
            let result = (|| -> Result<(), OtpTransportError> {
                let mut session = target.open()?;
                session.set_fp_protection(&pin, enable)
            })();
            Box::new(move |app: &mut App| {
                if app.selected_device != for_device {
                    return;
                }
                match result {
                    Ok(()) => {
                        app.otp.fp_enabled = Some(enable);
                        app.otp.info = Some(if enable {
                            "Fingerprint unlock enabled.".into()
                        } else {
                            "Fingerprint unlock disabled.".into()
                        });
                    }
                    Err(e) => app.otp.error = Some(e.to_string()),
                }
            })
        });
    }

    /// Apply a set / change / remove PIN action from the [`PinDialog`].
    pub(crate) fn apply_pin_dialog(&mut self, kind: PinDialogKind) {
        self.otp.error = None;
        let dlg = match &self.otp.pin_dialog {
            Some(d) => d,
            None => return,
        };
        // The dialog wipes its own fields on drop; these copies must too, or
        // the PIN outlives the modal in the worker thread's heap.
        let current = zeroize::Zeroizing::new(dlg.current.clone());
        let newpin = zeroize::Zeroizing::new(dlg.new.clone());
        let confirm = zeroize::Zeroizing::new(dlg.confirm.clone());

        // The only host-side gate is the one the host owns: the two typed
        // fields must agree, because only this dialog knows they were meant to.
        // Whether the key accepts the PIN is the key's call — it answers with a
        // status word, and that answer is what the user is shown.
        match kind {
            PinDialogKind::Set | PinDialogKind::Change => {
                if newpin != confirm {
                    self.otp.error = Some("New PIN and confirmation do not match.".into());
                    return;
                }
            }
            PinDialogKind::Remove => {}
        }

        let target = match self.otp_target() {
            Ok(t) => t,
            Err(e) => {
                self.otp.error = Some(e);
                return;
            }
        };
        let for_device = self.selected_device.clone();
        self.spawn_job("Updating OTP PIN\u{2026}", move || {
            let result = (|| -> Result<Option<zeroize::Zeroizing<String>>, OtpTransportError> {
                let mut session = target.open()?;
                match kind {
                    PinDialogKind::Set => {
                        session.set_pin(&newpin)?;
                        Ok(Some(newpin.clone()))
                    }
                    PinDialogKind::Change => {
                        session.change_pin(&current, &newpin)?;
                        Ok(Some(newpin.clone()))
                    }
                    PinDialogKind::Remove => {
                        session.remove_pin(&current)?;
                        Ok(None)
                    }
                }
            })();
            Box::new(move |app: &mut App| {
                if app.selected_device != for_device {
                    return;
                }
                match result {
                    Ok(new_pin) => {
                        app.otp.pin_dialog = None;
                        match kind {
                            PinDialogKind::Set => {
                                app.otp.pin = new_pin.clone();
                                app.otp.pin_set = Some(true);
                                app.otp.info = Some("OTP PIN set.".into());
                            }
                            PinDialogKind::Change => {
                                app.otp.pin = new_pin.clone();
                                app.otp.pin_set = Some(true);
                                app.otp.info = Some("OTP PIN changed.".into());
                            }
                            PinDialogKind::Remove => {
                                app.otp.pin = None;
                                app.otp.pin_set = Some(false);
                                app.otp.pin_required = false;
                                app.otp.info = Some("OTP PIN removed.".into());
                            }
                        }
                        app.load_otp_entries();
                    }
                    Err(e) => app.otp.error = Some(e.to_string()),
                }
            })
        });
    }

    /// Render the set / change / remove PIN modal when open.
    fn render_pin_dialog(&mut self, ui: &mut egui::Ui, p: &Palette) {
        let kind = match &self.otp.pin_dialog {
            Some(d) => d.kind(),
            None => return,
        };
        let mut submit = false;
        let mut cancel = false;
        theme::card_frame(p).show(ui, |ui| {
            let title = match kind {
                PinDialogKind::Set => "Set OTP PIN",
                PinDialogKind::Change => "Change OTP PIN",
                PinDialogKind::Remove => "Remove OTP PIN",
            };
            ui.label(
                egui::RichText::new(title)
                    .font(theme::f_sb(14.0))
                    .color(p.txt),
            );
            ui.add_space(8.0);
            if let Some(dlg) = &mut self.otp.pin_dialog {
                if matches!(kind, PinDialogKind::Change | PinDialogKind::Remove) {
                    ui.label(
                        egui::RichText::new("Current PIN")
                            .font(theme::f_reg(12.0))
                            .color(p.txt2),
                    );
                    ui.add(
                        egui::TextEdit::singleline(&mut dlg.current)
                            .password(true)
                            .desired_width(220.0),
                    );
                    ui.add_space(6.0);
                }
                if matches!(kind, PinDialogKind::Set | PinDialogKind::Change) {
                    ui.label(
                        egui::RichText::new("New PIN")
                            .font(theme::f_reg(12.0))
                            .color(p.txt2),
                    );
                    ui.add(
                        egui::TextEdit::singleline(&mut dlg.new)
                            .password(true)
                            .desired_width(220.0),
                    );
                    ui.add_space(6.0);
                    ui.label(
                        egui::RichText::new("Confirm new PIN")
                            .font(theme::f_reg(12.0))
                            .color(p.txt2),
                    );
                    ui.add(
                        egui::TextEdit::singleline(&mut dlg.confirm)
                            .password(true)
                            .desired_width(220.0),
                    );
                }
            }
            ui.add_space(6.0);
            // Advice, not a rule: the key decides what it accepts and says so.
            ui.label(
                egui::RichText::new(
                    "Keys typically want 6+ digits (no trivial sequences), or \
                     10+ characters if the PIN isn't all digits.",
                )
                .font(theme::f_reg(11.0))
                .color(p.txt3),
            );
            if matches!(kind, PinDialogKind::Set | PinDialogKind::Change) {
                ui.add_space(4.0);
                ui.label(
                    egui::RichText::new(
                        "There is no PIN reset. Wrong attempts count down a retry \
                         counter, and once it reaches zero the only way back is to \
                         erase every OTP entry on this key.",
                    )
                    .font(theme::f_reg(11.0))
                    .color(p.warn),
                );
            }
            ui.add_space(10.0);
            ui.horizontal(|ui| {
                let action = match kind {
                    PinDialogKind::Set => "Set PIN",
                    PinDialogKind::Change => "Change PIN",
                    PinDialogKind::Remove => "Remove PIN",
                };
                if theme::button(ui, p, BtnKind::Primary, action).clicked() {
                    submit = true;
                }
                if theme::button(ui, p, BtnKind::Default, "Cancel").clicked() {
                    cancel = true;
                }
            });
        });
        if cancel {
            self.otp.pin_dialog = None;
        } else if submit {
            self.apply_pin_dialog(kind);
        }
    }

    /// the button-prompt). The returned code is stashed in `touch_codes` and
    /// shown in place of "touch to view" until the next list reload.
    pub(crate) fn read_touch_otp_entry(&mut self, app_name: String, account_name: String) {
        self.otp.error = None;
        let target = match self.otp_target() {
            Ok(t) => t,
            Err(e) => {
                self.otp.error = Some(e);
                return;
            }
        };
        let for_device = self.selected_device.clone();
        let key = (app_name.clone(), account_name.clone());
        self.spawn_job("Reading code \u{2014} touch your key\u{2026}", move || {
            let result = (|| -> Result<Option<String>, String> {
                let mut session = target.open().map_err(|e| e.to_string())?;
                let now = unix_now();
                let entry = session
                    .read_entry(now, &app_name, &account_name)
                    .map_err(|e| e.to_string())?;
                Ok(entry.code)
            })();
            Box::new(move |app: &mut App| {
                if app.selected_device != for_device {
                    return;
                }
                match result {
                    Ok(Some(code)) => {
                        app.otp.touch_codes.insert(key, code);
                    }
                    Ok(None) => {
                        app.otp.error = Some("the key did not return a code".into());
                    }
                    Err(e) => app.otp.error = Some(e),
                }
            })
        });
    }

    /// Apply the HOTP-on-button typing options (send-Enter, long-touch, numpad)
    /// to the already-provisioned slot, without re-sending the seed.
    pub(crate) fn apply_button_hotp_options(
        &mut self,
        send_enter: bool,
        long_touch: bool,
        numpad: bool,
    ) {
        self.otp.error = None;
        let target = match self.otp_target() {
            Ok(t) => t,
            Err(e) => {
                self.otp.error = Some(e);
                return;
            }
        };
        let for_device = self.selected_device.clone();
        self.spawn_job("Updating touch HOTP options\u{2026}", move || {
            let result = (|| -> Result<(), String> {
                let mut session = target.open().map_err(|e| e.to_string())?;
                session
                    .set_button_hotp_options(send_enter, long_touch, numpad)
                    .map_err(|e| e.to_string())
            })();
            Box::new(move |app: &mut App| {
                if app.selected_device != for_device {
                    return;
                }
                match result {
                    Ok(()) => {
                        app.otp.info = Some("Touch HOTP options updated.".into());
                        if let Some(st) = app.otp.button_hotp_status.as_mut() {
                            st.send_enter = send_enter;
                            st.long_touch = long_touch;
                            st.numpad = numpad;
                        }
                    }
                    Err(e) => app.otp.error = Some(e),
                }
            })
        });
    }

    /// Erase every entry on the key.
    pub(crate) fn erase_all_otp(&mut self) {
        self.otp.error = None;
        let target = match self.otp_target() {
            Ok(t) => t,
            Err(e) => {
                self.otp.error = Some(e);
                return;
            }
        };
        let for_device = self.selected_device.clone();
        self.spawn_job(
            "Erasing all OTP entries \u{2014} touch your key\u{2026}",
            move || {
                let result = (|| -> Result<(), OtpTransportError> {
                    let mut session = target.open()?;
                    session.erase_all()
                })();
                Box::new(move |app: &mut App| {
                    if app.selected_device != for_device {
                        return;
                    }
                    match result {
                        Ok(()) => {
                            app.otp.info = Some("All OTP entries erased.".into());
                            app.load_otp_entries();
                        }
                        Err(e) => app.otp.error = Some(e.to_string()),
                    }
                })
            },
        );
    }

    /// Render the OTP tab.
    pub(crate) fn cap_otp(&mut self, ui: &mut egui::Ui, p: &Palette) {
        // Auto-read once per selection (a hard error won't auto-retry).
        if !self.otp_tried && !self.busy() && self.otp.error.is_none() {
            self.otp_tried = true;
            self.load_otp_entries();
        }

        ui.horizontal(|ui| {
            ui.label(
                egui::RichText::new("On-device OTP")
                    .font(theme::f_sb(14.5))
                    .color(p.txt),
            );
            ui.add_space(6.0);
            self.help_dot(ui, p, "otp");
            ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                // Secondary actions live in an overflow menu so the header row
                // doesn't crowd: HID-HOTP configure, the interface toggle, and the
                // transport selector. Rendered first so that, in this
                // right-to-left layout, it sits at the far right edge. Actions are
                // accumulated as locals and applied after the menu closure to keep
                // `self` borrows simple.
                let mut open_touch = false;
                let mut kbd_target: Option<bool> = None;
                let mut new_transport: Option<OtpTransportSel> = None;
                let mut pin_dialog_open: Option<PinDialogKind> = None;
                let mut pin_lock = false;
                let mut fp_toggle: Option<bool> = None;

                let menu_btn =
                    theme::button(ui, p, BtnKind::Default, "...").on_hover_text("More actions");
                let menu_id = ui.make_persistent_id("otp_more_menu");
                egui::Popup::menu(&menu_btn)
                    .id(menu_id)
                    .close_behavior(egui::PopupCloseBehavior::CloseOnClick)
                    .show(|ui| {
                        ui.set_min_width(180.0);

                        // Transport selector.
                        ui.label(
                            egui::RichText::new("Transport")
                                .font(theme::f_reg(11.0))
                                .color(p.txt3),
                        );
                        for sel in [
                            OtpTransportSel::Auto,
                            OtpTransportSel::Hid,
                            OtpTransportSel::Ccid,
                        ] {
                            if ui
                                .selectable_label(self.otp.transport == sel, sel.label())
                                .clicked()
                            {
                                new_transport = Some(sel);
                            }
                        }
                        ui.separator();

                        // Configure HID-HOTP — disabled (with reason) when the
                        // keyboard interface is off or unsupported.
                        let touch_blocked = self.otp.touch_hotp_ok == Some(false);
                        ui.add_enabled_ui(!touch_blocked, |ui| {
                            let r = ui.selectable_label(false, "Configure HID-HOTP\u{2026}");
                            let r = match self.otp.touch_hotp_why {
                                Some(why) if touch_blocked => r.on_disabled_hover_text(why),
                                _ => r,
                            };
                            if r.clicked() {
                                open_touch = true;
                            }
                        });

                        // Enable/Disable the keyboard-HID interface.
                        if let Some(iface) = self.otp.iface {
                            let (label, target) = if iface.keyboard {
                                ("Disable HID-HOTP", false)
                            } else {
                                ("Enable HID-HOTP", true)
                            };
                            let would_underflow = !target && {
                                let after = IfaceState {
                                    keyboard: false,
                                    ..iface
                                };
                                after.enabled_count() < 2
                            };
                            // Enabling the keyboard interface is pointless on a
                            // model that doesn't have the HOTP-on-touch feature,
                            // so block it (the interface toggle only makes sense
                            // for keys that actually support it).
                            let unsupported = target && self.otp.hotp_supported == Some(false);
                            let blocked = would_underflow || unsupported;
                            ui.add_enabled_ui(!blocked, |ui| {
                                let r = ui.selectable_label(false, label);
                                let r = if unsupported {
                                    r.on_disabled_hover_text(
                                        "this key was supplied without the HOTP-on-touch \
                                         function; keys aren't upgradable after purchase, so \
                                         it can't be enabled here",
                                    )
                                } else if would_underflow {
                                    r.on_disabled_hover_text(
                                        "at least two interfaces must stay enabled",
                                    )
                                } else {
                                    r
                                };
                                if r.clicked() {
                                    kbd_target = Some(target);
                                }
                            });
                        }

                        // --- OTP PIN (R3.4+ privacy protection) ---
                        ui.separator();
                        ui.label(
                            egui::RichText::new("OTP PIN")
                                .font(theme::f_reg(11.0))
                                .color(p.txt3),
                        );
                        match self.otp.pin_set {
                            Some(false) => {
                                if ui.selectable_label(false, "Set PIN\u{2026}").clicked() {
                                    pin_dialog_open = Some(PinDialogKind::Set);
                                }
                            }
                            Some(true) => {
                                if ui.selectable_label(false, "Change PIN\u{2026}").clicked() {
                                    pin_dialog_open = Some(PinDialogKind::Change);
                                }
                                if ui.selectable_label(false, "Remove PIN\u{2026}").clicked() {
                                    pin_dialog_open = Some(PinDialogKind::Remove);
                                }
                                // Lock is only meaningful once unlocked this session.
                                ui.add_enabled_ui(self.otp.pin.is_some(), |ui| {
                                    if ui.selectable_label(false, "Lock now").clicked() {
                                        pin_lock = true;
                                    }
                                });
                            }
                            None => {
                                ui.add_enabled_ui(false, |ui| {
                                    let _ = ui.selectable_label(false, "No PIN feature reported");
                                });
                            }
                        }

                        // Fingerprint protection (only meaningful once a PIN is
                        // set, since enabling/disabling it authenticates with the
                        // PIN). Requires an enrolled fingerprint on the key; the
                        // device rejects enabling otherwise, surfaced as an error.
                        if self.otp.pin_set == Some(true) {
                            ui.separator();
                            ui.label(
                                egui::RichText::new("Fingerprint")
                                    .font(theme::f_reg(11.0))
                                    .color(p.txt3),
                            );
                            // Some(false) -> offer Enable; Some(true) -> offer
                            // Disable; None (unknown) -> no toggle item.
                            let toggle = match self.otp.fp_enabled {
                                Some(false) => Some((true, "Enable fingerprint unlock\u{2026}")),
                                Some(true) => Some((false, "Disable fingerprint unlock\u{2026}")),
                                None => None,
                            };
                            if let Some((target, label)) = toggle {
                                if ui.selectable_label(false, label).clicked() {
                                    fp_toggle = Some(target);
                                }
                            }
                        }
                    });

                // Apply menu selections after the closure.
                if let Some(sel) = new_transport {
                    self.otp.transport = sel;
                    self.otp.active = None;
                    self.otp.serial = None;
                    self.load_otp_entries();
                }
                if open_touch {
                    let mut dlg = ButtonHotpDialog::default();
                    dlg.open = true;
                    if let Some(st) = self.otp.button_hotp_status {
                        dlg.send_enter = st.send_enter;
                        dlg.long_touch = st.long_touch;
                        dlg.numpad = st.numpad;
                    }
                    self.otp.button_hotp = dlg;
                    // A reopened dialog must default to masked, regardless of a
                    // reveal toggle left set from a prior entry.
                    self.secret_reveal.insert("otp-buttonhotp-secret", false);
                }
                if let Some(target) = kbd_target {
                    self.otp.kbd_confirm = Some(KbdToggle {
                        enable: target,
                        typed: String::new(),
                    });
                }
                if let Some(kind) = pin_dialog_open {
                    self.otp.pin_dialog = Some(PinDialog::for_kind(kind));
                }
                if pin_lock {
                    self.lock_otp_pin();
                }
                if let Some(enable) = fp_toggle {
                    self.set_otp_fp_protection(enable);
                }

                // Primary actions, to the left of the overflow menu (added after
                // it so they sit left of it in this right-to-left layout).
                // "+ Add entry" is dropped entirely on a key that told us it has
                // no on-device OTP function — there is nothing to add it to.
                // Refresh stays, so the read can be retried.
                ui.add_space(6.0);
                if self.otp.totp_supported != Some(false)
                    && theme::button(ui, p, BtnKind::Primary, "+ Add entry").clicked()
                {
                    // OtpAddDialog has a Drop impl (wipes the typed seed), so
                    // `..Default` struct-update isn't allowed; build via default()
                    // then flip `open`.
                    let mut dlg = OtpAddDialog::default();
                    dlg.open = true;
                    self.otp.add = dlg;
                    // A reopened dialog must default to masked, regardless of a
                    // reveal toggle left set from a prior entry.
                    self.secret_reveal.insert("otp-add-secret", false);
                }
                ui.add_space(6.0);
                if theme::button(ui, p, BtnKind::Default, "Refresh").clicked() {
                    self.otp.active = None;
                    self.otp.serial = None;
                    self.load_otp_entries();
                }
            });
        });
        // Transport + serial on their own line, so neither collides with the
        // controls on the header row.
        if self.otp.active.is_some() || self.otp.serial.is_some() {
            let mut bits: Vec<String> = Vec::new();
            if let Some(active) = self.otp.active {
                bits.push(format!("via {active}"));
            }
            if let Some(serial) = &self.otp.serial {
                bits.push(format!("S/N {serial}"));
            }
            ui.label(
                egui::RichText::new(bits.join("  \u{00b7}  "))
                    .font(theme::f_reg(11.5))
                    .color(p.txt3),
            );
        }
        ui.add_space(12.0);

        if let Some(info) = &self.otp.info {
            ui.colored_label(p.ok, info);
            ui.add_space(6.0);
        }
        if let Some(err) = &self.otp.error {
            ui.colored_label(p.err, err);
            ui.add_space(6.0);
        }

        self.render_otp_add_form(ui, p);
        self.render_pin_dialog(ui, p);
        self.render_button_hotp_form(ui, p);
        self.render_keyboard_confirm(ui, p);
        self.render_otp_delete_confirm(ui, p);

        if !self.otp.loaded {
            ui.label(
                egui::RichText::new("Reading entries\u{2026}")
                    .font(theme::f_reg(13.0))
                    .color(p.txt3),
            );
            return;
        }
        // The key answered the config read and reported no on-device OTP
        // function. Say so plainly, in place of a list and an "Erase all" button
        // that could only produce a protocol error. This is the quiet case where
        // the key talks to us correctly and simply lacks the feature; a key whose
        // config exchange itself fails leaves this `None` and still shows the
        // transport error above.
        if self.otp.totp_supported == Some(false) {
            theme::card_frame(p).show(ui, |ui| {
                ui.label(
                    egui::RichText::new("This key does not have on-device OTP.")
                        .font(theme::f_sb(13.5))
                        .color(p.txt),
                );
                ui.add_space(4.0);
                ui.label(
                    egui::RichText::new(
                        "The key reports that it was supplied without the on-device OTP \
                         function, so it can't store TOTP or HOTP entries. Token2 keys \
                         aren't upgradable after purchase \u{2014} the functions a key has \
                         are fixed when it is made, and OTP is a separate product \
                         configuration. Your other features on this key are unaffected.",
                    )
                    .font(theme::f_reg(11.5))
                    .color(p.txt3),
                );
            });
            return;
        }
        // Protected (R3.4+) key with no valid PIN yet: show the unlock prompt
        // instead of the (empty) list. Entering the PIN and unlocking reloads
        // the entries via the stored PIN.
        if self.otp.pin_required {
            let mut do_unlock = false;
            let mut do_fp = false;
            let fp_on = self.otp.fp_enabled == Some(true);
            theme::card_frame(p).show(ui, |ui| {
                ui.label(
                    egui::RichText::new("This key's OTP codes are protected")
                        .font(theme::f_sb(13.5))
                        .color(p.txt),
                );
                ui.add_space(6.0);
                ui.label(
                    egui::RichText::new(if fp_on {
                        "Touch the fingerprint sensor, or enter the OTP PIN, to view codes."
                    } else {
                        "Enter the OTP PIN to view and manage codes."
                    })
                    .font(theme::f_reg(12.5))
                    .color(p.txt2),
                );
                ui.add_space(8.0);
                let resp = ui.add(
                    egui::TextEdit::singleline(&mut self.otp.pin_input)
                        .password(true)
                        .hint_text("OTP PIN")
                        .desired_width(220.0),
                );
                let entered = resp.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter));
                ui.add_space(8.0);
                ui.horizontal(|ui| {
                    if theme::button(ui, p, BtnKind::Primary, "Unlock").clicked() || entered {
                        do_unlock = true;
                    }
                    if fp_on
                        && theme::button(ui, p, BtnKind::Default, "Touch fingerprint").clicked()
                    {
                        do_fp = true;
                    }
                });
                if let Some(err) = &self.otp.error {
                    ui.add_space(6.0);
                    ui.label(
                        egui::RichText::new(err)
                            .font(theme::f_reg(12.0))
                            .color(p.err),
                    );
                }
            });
            if do_fp {
                self.unlock_otp_fingerprint();
            } else if do_unlock && !self.otp.pin_input.trim().is_empty() {
                self.otp.pin = Some(zeroize::Zeroizing::new(
                    self.otp.pin_input.trim().to_owned(),
                ));
                // `.clear()` only sets the length to zero — the PIN would stay
                // in the buffer verbatim. `wipe` is the helper the rest of the
                // GUI's secret fields use.
                wipe(&mut self.otp.pin_input);
                self.otp.pin_required = false;
                self.otp.error = None;
                self.load_otp_entries();
            }
            return;
        }

        if self.otp.rows.is_empty() && self.otp.error.is_none() {
            ui.label(
                egui::RichText::new("No OTP entries on this key.")
                    .font(theme::f_reg(13.0))
                    .color(p.txt3),
            );
            return;
        }

        let mut copy: Option<String> = None;
        let mut delete: Option<(String, String)> = None;
        let mut read_touch: Option<(String, String)> = None;
        // Snapshot on-demand-read codes so the row loop (which borrows
        // `self.otp.rows`) can look them up without also borrowing `self.otp`.
        let touch_codes = self.otp.touch_codes.clone();
        theme::card_frame(p).show(ui, |ui| {
            let n = self.otp.rows.len();
            for (i, row) in self.otp.rows.iter().enumerate() {
                ui.horizontal(|ui| {
                    ui.vertical(|ui| {
                        ui.label(
                            egui::RichText::new(row.label())
                                .font(theme::f_sb(13.5))
                                .color(p.txt),
                        );
                        let mut meta = format!("{}/{}", row.type_str, row.algo_str);
                        if row.button_required {
                            meta.push_str("  · touch");
                        }
                        ui.label(
                            egui::RichText::new(meta)
                                .font(theme::f_reg(11.0))
                                .color(p.txt3),
                        );
                    });
                    ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                        if theme::button(ui, p, BtnKind::Default, "Delete").clicked() {
                            delete = Some((row.app_name.clone(), row.account_name.clone()));
                        }
                        ui.add_space(8.0);
                        match &row.code {
                            Some(code) => {
                                if theme::button(ui, p, BtnKind::Default, "Copy").clicked() {
                                    copy = Some(code.clone());
                                }
                                ui.add_space(8.0);
                                let is_totp = row.type_str.eq_ignore_ascii_case("TOTP");
                                // TOTP codes are time-based: show the same live
                                // countdown ring + seconds the OATH pane uses, so
                                // the user can see how long the code stays valid.
                                // HOTP codes are counter-based and have no window.
                                // Use the entry's own time-step (30 or 60s, etc.);
                                // fall back to 30 if the record reported 0.
                                let period = if row.period == 0 {
                                    30
                                } else {
                                    row.period as u64
                                };
                                let totp = is_totp.then(|| theme::totp_window(period));
                                let code_color = match totp {
                                    Some((secs, _)) if secs <= 5 => p.warn,
                                    _ => p.txt,
                                };
                                ui.label(
                                    egui::RichText::new(code)
                                        .font(theme::f_mono(16.0))
                                        .color(code_color),
                                );
                                if let Some((secs, pct)) = totp {
                                    let ring_color = if secs <= 5 { p.warn } else { p.accent };
                                    ui.add_space(8.0);
                                    theme::ring(ui, pct, 18.0, ring_color, p.line);
                                    ui.add_space(6.0);
                                    ui.label(
                                        egui::RichText::new(format!("{secs}s"))
                                            .font(theme::f_reg(11.0))
                                            .color(p.txt3),
                                    );
                                }
                            }
                            None => {
                                let rkey = (row.app_name.clone(), row.account_name.clone());
                                if let Some(code) = touch_codes.get(&rkey) {
                                    // Already read on touch this session — show it
                                    // (TOTP touch entries still have a window, but
                                    // the device gives no countdown for them here).
                                    if theme::button(ui, p, BtnKind::Default, "Copy").clicked() {
                                        copy = Some(code.clone());
                                    }
                                    ui.add_space(8.0);
                                    ui.label(
                                        egui::RichText::new(code)
                                            .font(theme::f_mono(16.0))
                                            .color(p.txt),
                                    );
                                } else if row.button_required {
                                    if theme::button(ui, p, BtnKind::Default, "Read")
                                        .on_hover_text("Touch the key to read this code")
                                        .clicked()
                                    {
                                        read_touch = Some(rkey);
                                    }
                                } else {
                                    ui.label(
                                        egui::RichText::new("\u{2014}")
                                            .font(theme::f_reg(11.5))
                                            .color(p.txt3),
                                    );
                                }
                            }
                        }
                    });
                });
                if i + 1 < n {
                    ui.add_space(5.0);
                    let y = ui.cursor().top();
                    ui.painter().hline(
                        ui.max_rect().x_range(),
                        y,
                        egui::Stroke::new(1.0, p.line_soft),
                    );
                    ui.add_space(5.0);
                }
            }
        });

        ui.add_space(10.0);
        ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
            if theme::button(ui, p, BtnKind::Danger, "Erase all\u{2026}").clicked() {
                self.otp.confirm_delete = Some((String::new(), String::new())); // sentinel = erase-all
            }
        });

        if let Some(code) = copy {
            ui.ctx().copy_text(code.clone());
            self.clipboard_clear_at = Some((code, now_secs_f64() + 45.0));
        }
        if let Some((a, acct)) = delete {
            self.otp.confirm_delete = Some((a, acct));
        }
        if let Some((a, acct)) = read_touch {
            self.read_touch_otp_entry(a, acct);
        }
    }

    /// The add-entry form, shown inline when `add.open`.
    fn render_otp_add_form(&mut self, ui: &mut egui::Ui, p: &Palette) {
        if !self.otp.add.open {
            return;
        }
        let mut submit = false;
        let mut cancel = false;
        theme::card_frame(p).show(ui, |ui| {
            ui.label(
                egui::RichText::new("Add OTP entry")
                    .font(theme::f_sb(13.5))
                    .color(p.txt),
            );
            ui.add_space(8.0);
            egui::Grid::new("otp_add_grid")
                .num_columns(2)
                .spacing([10.0, 8.0])
                .show(ui, |ui| {
                    ui.label("Issuer / app");
                    ui.text_edit_singleline(&mut self.otp.add.app_name);
                    ui.end_row();

                    ui.label("Account");
                    ui.text_edit_singleline(&mut self.otp.add.account_name);
                    ui.end_row();

                    ui.label("Secret (Base32)");
                    {
                        let mut rev = self
                            .secret_reveal
                            .get("otp-add-secret")
                            .copied()
                            .unwrap_or(false);
                        crate::secret_edit(ui, p, &mut self.otp.add.secret, &mut rev, "", 260.0);
                        self.secret_reveal.insert("otp-add-secret", rev);
                    }
                    ui.end_row();

                    #[cfg(feature = "qr")]
                    {
                        ui.label("");
                        if crate::scan_qr_button(ui, p) {
                            self.otp_scan_qr();
                        }
                        ui.end_row();
                    }

                    ui.label("Type");
                    ui.horizontal(|ui| {
                        ui.selectable_value(&mut self.otp.add.totp, true, "TOTP");
                        ui.selectable_value(&mut self.otp.add.totp, false, "HOTP");
                    });
                    ui.end_row();

                    ui.label("Algorithm");
                    ui.horizontal(|ui| {
                        ui.selectable_value(&mut self.otp.add.sha256, false, "SHA1");
                        ui.selectable_value(&mut self.otp.add.sha256, true, "SHA256");
                    });
                    ui.end_row();

                    ui.label("Digits");
                    ui.add(egui::DragValue::new(&mut self.otp.add.digits).range(4..=10));
                    ui.end_row();

                    if self.otp.add.totp {
                        ui.label("Period (s)");
                        ui.add(egui::DragValue::new(&mut self.otp.add.period).range(1..=120));
                        ui.end_row();
                    }

                    ui.label("Require touch");
                    ui.checkbox(&mut self.otp.add.require_touch, "");
                    ui.end_row();
                });
            ui.add_space(10.0);
            ui.horizontal(|ui| {
                if theme::button(ui, p, BtnKind::Primary, "Add").clicked() {
                    submit = true;
                }
                ui.add_space(6.0);
                if theme::button(ui, p, BtnKind::Default, "Cancel").clicked() {
                    cancel = true;
                }
            });
        });
        ui.add_space(10.0);
        if submit {
            self.otp.add.open = false;
            self.provision_otp();
        } else if cancel {
            self.otp.add = OtpAddDialog::default();
        }
    }

    /// The touch-HOTP form, shown inline when `button_hotp.open`. Configures the
    /// single HOTP-on-touch keystroke slot.
    fn render_button_hotp_form(&mut self, ui: &mut egui::Ui, p: &Palette) {
        if !self.otp.button_hotp.open {
            return;
        }
        let mut submit = false;
        let mut clear = false;
        let mut cancel = false;
        theme::card_frame(p).show(ui, |ui| {
            ui.horizontal(|ui| {
                ui.label(
                    egui::RichText::new("HID-HOTP (keystroke)")
                        .font(theme::f_sb(13.5))
                        .color(p.txt),
                );
                ui.add_space(6.0);
                self.help_dot(ui, p, "touch-hotp");
            });
            ui.add_space(4.0);
            ui.label(
                egui::RichText::new(
                    "The key types a fresh HOTP code as keyboard input when you touch it \
                     outside any session. One slot per key.",
                )
                .font(theme::f_reg(11.5))
                .color(p.txt3),
            );
            ui.add_space(8.0);
            // Show whether a seed is already provisioned in the slot, read from
            // the device config on load.
            match self.otp.button_hotp_status {
                Some(st) if st.configured => {
                    theme::pill(ui, "Seed configured", p.ok, p.ok_soft());
                    ui.add_space(4.0);
                    ui.label(
                        egui::RichText::new(
                            "A seed is already set. Leave the secret blank and Save \
                             to change only the typing options; enter a new secret to \
                             replace the seed or change the digit length.",
                        )
                        .font(theme::f_reg(11.0))
                        .color(p.txt3),
                    );
                }
                Some(_) => {
                    theme::pill(ui, "No seed configured", p.txt3, p.line);
                }
                None => {
                    // Couldn't read the device config — most often because the
                    // full config block is only served over USB-HID, which
                    // Windows restricts for FIDO-class devices unless elevated.
                    // Don't claim "no seed"; say we can't tell.
                    theme::pill(ui, "Slot status unknown", p.txt3, p.line);
                    ui.add_space(4.0);
                    ui.label(
                        egui::RichText::new(
                            "Couldn't read the slot status from this key's config \
                             block. Provisioning still works; reload to retry.",
                        )
                        .font(theme::f_reg(11.0))
                        .color(p.txt3),
                    );
                }
            }
            ui.add_space(8.0);
            egui::Grid::new("button_hotp_grid")
                .num_columns(2)
                .spacing([10.0, 8.0])
                .show(ui, |ui| {
                    let configured = matches!(
                        self.otp.button_hotp_status,
                        Some(st) if st.configured
                    );
                    ui.label(if configured {
                        "New secret (Base32)"
                    } else {
                        "Secret (Base32)"
                    });
                    let bh_hint = if configured {
                        "leave blank to keep current seed"
                    } else {
                        ""
                    };
                    {
                        let mut rev = self
                            .secret_reveal
                            .get("otp-buttonhotp-secret")
                            .copied()
                            .unwrap_or(false);
                        crate::secret_edit(
                            ui,
                            p,
                            &mut self.otp.button_hotp.secret,
                            &mut rev,
                            bh_hint,
                            260.0,
                        );
                        self.secret_reveal.insert("otp-buttonhotp-secret", rev);
                    }
                    ui.end_row();

                    // Digit length is only settable as part of a seed write
                    // (spec §1.7); there's no standalone command for it. So it's
                    // only editable when a secret is being entered — with a blank
                    // secret (options-only Save) the existing length is kept.
                    let seed_present = !self.otp.button_hotp.secret.trim().is_empty();
                    ui.label("Digits");
                    ui.add_enabled_ui(seed_present, |ui| {
                        ui.horizontal(|ui| {
                            ui.selectable_value(&mut self.otp.button_hotp.digits, 6u8, "6");
                            ui.selectable_value(&mut self.otp.button_hotp.digits, 8u8, "8");
                        });
                    })
                    .response
                    .on_disabled_hover_text(
                        "Digit length can only change when you set a new secret \u{2014} \
                         the key has no command to change it on its own.",
                    );
                    ui.end_row();

                    ui.label("Send Enter");
                    ui.checkbox(&mut self.otp.button_hotp.send_enter, "");
                    ui.end_row();

                    ui.label("Long touch (2s)");
                    ui.checkbox(&mut self.otp.button_hotp.long_touch, "");
                    ui.end_row();

                    ui.label("Numeric keypad");
                    ui.checkbox(&mut self.otp.button_hotp.numpad, "");
                    ui.end_row();
                });
            ui.add_space(10.0);
            ui.horizontal(|ui| {
                if theme::button(ui, p, BtnKind::Primary, "Save").clicked() {
                    submit = true;
                }
                ui.add_space(6.0);
                if theme::button(ui, p, BtnKind::Default, "Cancel").clicked() {
                    cancel = true;
                }
                ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                    if theme::button(ui, p, BtnKind::Danger, "Clear slot").clicked() {
                        clear = true;
                    }
                });
            });
        });
        ui.add_space(10.0);
        if submit {
            self.otp.button_hotp.open = false;
            self.provision_button_hotp();
        } else if clear {
            self.otp.button_hotp.open = false;
            self.delete_button_hotp_slot();
        } else if cancel {
            self.otp.button_hotp = ButtonHotpDialog::default();
        }
    }

    /// Typed-phrase confirmation for the keyboard-HID enable/disable toggle.
    /// Mirrors the CLI's `interface` confirmation: this reconfigures the hardware,
    /// so the user must type an exact phrase before it applies.
    fn render_keyboard_confirm(&mut self, ui: &mut egui::Ui, p: &Palette) {
        let Some(tog) = self.otp.kbd_confirm.as_ref() else {
            return;
        };
        let enable = tog.enable;
        const PHRASE: &str = "change interface";
        let mut apply = false;
        let mut cancel = false;
        theme::card_frame(p).show(ui, |ui| {
            let title = if enable {
                "Enable HID-HOTP (keyboard interface)?"
            } else {
                "Disable HID-HOTP (keyboard interface)?"
            };
            ui.colored_label(p.err, title);
            ui.add_space(4.0);
            ui.label(
                egui::RichText::new(
                    "This reconfigures the key's USB interfaces. The change takes effect \
                     after you re-plug the key. Disabling an interface removes the matching \
                     features until you re-enable it; if you disable the interface you are \
                     connected over, you may lose access to the key.",
                )
                .font(theme::f_reg(11.5))
                .color(p.txt3),
            );
            ui.add_space(8.0);
            ui.label(
                egui::RichText::new(format!("Type \u{201c}{PHRASE}\u{201d} to confirm:"))
                    .font(theme::f_reg(12.0))
                    .color(p.txt2),
            );
            if let Some(t) = self.otp.kbd_confirm.as_mut() {
                ui.add(egui::TextEdit::singleline(&mut t.typed).desired_width(220.0));
            }
            ui.add_space(8.0);
            let matched = self
                .otp
                .kbd_confirm
                .as_ref()
                .is_some_and(|t| t.typed.trim() == PHRASE);
            ui.horizontal(|ui| {
                ui.add_enabled_ui(matched, |ui| {
                    if theme::button(ui, p, BtnKind::Danger, "Apply").clicked() {
                        apply = true;
                    }
                });
                ui.add_space(6.0);
                if theme::button(ui, p, BtnKind::Default, "Cancel").clicked() {
                    cancel = true;
                }
            });
        });
        ui.add_space(10.0);
        if apply {
            self.otp.kbd_confirm = None;
            self.apply_keyboard_toggle(enable);
        } else if cancel {
            self.otp.kbd_confirm = None;
        }
    }

    /// Confirmation dialog for delete / erase-all.
    fn render_otp_delete_confirm(&mut self, ui: &mut egui::Ui, p: &Palette) {
        let Some((app_name, account_name)) = self.otp.confirm_delete.clone() else {
            return;
        };
        let erase_all = app_name.is_empty() && account_name.is_empty();
        let mut confirm = false;
        let mut cancel = false;
        theme::card_frame(p).show(ui, |ui| {
            let msg = if erase_all {
                "Erase ALL OTP entries on this key? This cannot be undone.".to_string()
            } else if app_name.is_empty() {
                format!("Delete OTP entry \"{account_name}\"?")
            } else {
                format!("Delete OTP entry \"{app_name}:{account_name}\"?")
            };
            ui.colored_label(p.err, msg);
            if erase_all {
                ui.add_space(4.0);
                ui.label(
                    egui::RichText::new(
                        "After you confirm, touch the key's sensor to complete the erase \
                         — the device waits for a physical touch.",
                    )
                    .font(theme::f_reg(11.5))
                    .color(p.txt3),
                );
            }
            ui.add_space(8.0);
            ui.horizontal(|ui| {
                let label = if erase_all { "Erase all" } else { "Delete" };
                if theme::button(ui, p, BtnKind::Danger, label).clicked() {
                    confirm = true;
                }
                ui.add_space(6.0);
                if theme::button(ui, p, BtnKind::Default, "Cancel").clicked() {
                    cancel = true;
                }
            });
        });
        ui.add_space(10.0);
        if confirm {
            self.otp.confirm_delete = None;
            if erase_all {
                self.erase_all_otp();
            } else {
                self.delete_otp_entry(app_name, account_name);
            }
        } else if cancel {
            self.otp.confirm_delete = None;
        }
    }
}

/// SHA label for an OTP algorithm (the byte layer has only SHA1/SHA256).
fn otp_algo_str(a: keyroost_token2otp::Algorithm) -> &'static str {
    match a {
        keyroost_token2otp::Algorithm::Sha1 => "SHA1",
        keyroost_token2otp::Algorithm::Sha256 => "SHA256",
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::path::{Path, PathBuf};

    /// A config block of `len` bytes whose capability byte (9) is `ext`.
    fn config_block(len: usize, ext: u8) -> keyroost_token2otp::DeviceInfo {
        let mut raw = vec![0u8; len];
        if len > 9 {
            raw[9] = ext;
        }
        keyroost_token2otp::DeviceInfo::parse(&raw).expect("non-empty block parses")
    }

    #[test]
    fn a_full_config_block_decides_the_totp_gate_both_ways() {
        // Bit 1 of byte 9 is the advertised TOTP function.
        assert_eq!(totp_capability(Some(&config_block(10, 0x01))), Some(true));
        assert_eq!(totp_capability(Some(&config_block(10, 0x00))), Some(false));
        // Other capability bits must not be mistaken for it.
        assert_eq!(totp_capability(Some(&config_block(10, 0x1a))), Some(false));
        assert_eq!(totp_capability(Some(&config_block(64, 0x1b))), Some(true));
    }

    #[test]
    fn a_short_config_block_is_unknown_not_unsupported() {
        // Byte 9 is absent; the parser zero-fills it, which must NOT be read as
        // a key that lacks the function — that would hide the feature over any
        // transport whose firmware answers with a stub block.
        for len in 1..=9 {
            assert_eq!(totp_capability(Some(&config_block(len, 0))), None, "{len}");
        }
    }

    #[test]
    fn no_config_read_leaves_the_feature_offered() {
        // Hiding on a failed read would be worse than letting the attempt
        // report its own error, so an absent config means "unknown".
        assert_eq!(totp_capability(None), None);
    }

    #[test]
    fn auto_with_both_interfaces_keeps_the_reader_as_fallback() {
        // #82: some firmware answers the HID probe with a malformed status
        // word while its CCID side works fine. An Auto pick on a key with
        // both interfaces must carry the reader as a same-device fallback —
        // never silently bind to HID alone.
        let t = otp_target_for(
            OtpTransportSel::Auto,
            Some(Path::new("/dev/hidraw3")),
            Some("Acme CCID 00"),
        );
        assert_eq!(
            t,
            Ok(OtpTarget::HidThenReader(
                PathBuf::from("/dev/hidraw3"),
                "Acme CCID 00".into()
            ))
        );
    }

    #[test]
    fn auto_with_hid_only_is_a_plain_hid_target() {
        let t = otp_target_for(OtpTransportSel::Auto, Some(Path::new("/dev/hidraw3")), None);
        assert_eq!(t, Ok(OtpTarget::HidPath(PathBuf::from("/dev/hidraw3"))));
    }

    #[test]
    fn auto_falls_back_to_reader_when_no_hid() {
        let t = otp_target_for(OtpTransportSel::Auto, None, Some("Acme CCID 00"));
        assert_eq!(t, Ok(OtpTarget::Reader("Acme CCID 00".into())));
    }

    #[test]
    fn auto_errors_when_no_interface() {
        assert!(otp_target_for(OtpTransportSel::Auto, None, None).is_err());
    }

    #[test]
    fn hid_requires_a_hid_path() {
        assert_eq!(
            otp_target_for(
                OtpTransportSel::Hid,
                Some(Path::new("/dev/hidraw3")),
                Some("r")
            ),
            Ok(OtpTarget::HidPath(PathBuf::from("/dev/hidraw3")))
        );
        assert!(otp_target_for(OtpTransportSel::Hid, None, Some("r")).is_err());
    }

    #[test]
    fn ccid_requires_a_reader() {
        assert_eq!(
            otp_target_for(
                OtpTransportSel::Ccid,
                Some(Path::new("/dev/hidraw3")),
                Some("r")
            ),
            Ok(OtpTarget::Reader("r".into()))
        );
        assert!(
            otp_target_for(OtpTransportSel::Ccid, Some(Path::new("/dev/hidraw3")), None).is_err()
        );
    }
}

/// Randomized coverage (proptest, dev-only) for the endpoint chooser: the
/// full contract, over arbitrary interface combinations — never panics,
/// never invents an endpoint, fails closed when the pick is unsatisfiable.
#[cfg(test)]
mod prop_tests {
    use super::*;
    use proptest::prelude::*;
    use std::path::{Path, PathBuf};

    fn any_sel() -> impl Strategy<Value = OtpTransportSel> {
        prop_oneof![
            Just(OtpTransportSel::Auto),
            Just(OtpTransportSel::Hid),
            Just(OtpTransportSel::Ccid),
        ]
    }

    proptest! {
        #[test]
        fn target_is_exactly_the_contracted_endpoint(
            sel in any_sel(),
            hid in proptest::option::of("[ -~]{1,16}"),
            reader in proptest::option::of("[ -~]{1,16}"),
        ) {
            let hid_path = hid.as_ref().map(PathBuf::from);
            let got = otp_target_for(sel, hid_path.as_deref(), reader.as_deref());
            // The contract, spelled out per selection: an explicit pick maps
            // to exactly that interface or fails; Auto prefers HID, falls
            // back to the reader, and errors only when neither exists.
            let expected = match sel {
                OtpTransportSel::Hid => hid_path.clone().map(OtpTarget::HidPath),
                OtpTransportSel::Ccid => reader.clone().map(OtpTarget::Reader),
                // Auto binds every interface the device offers: both → HID
                // first with the reader as same-device fallback (#82).
                OtpTransportSel::Auto => match (hid_path.clone(), reader.clone()) {
                    (Some(p), Some(r)) => Some(OtpTarget::HidThenReader(p, r)),
                    (Some(p), None) => Some(OtpTarget::HidPath(p)),
                    (None, Some(r)) => Some(OtpTarget::Reader(r)),
                    (None, None) => None,
                },
            };
            match expected {
                Some(t) => prop_assert_eq!(got, Ok(t)),
                None => prop_assert!(got.is_err(), "unsatisfiable pick must fail closed"),
            }
        }

        /// Whatever comes back Ok points at an interface the device really
        /// resolved — the chooser can never fabricate an endpoint (that would
        /// reopen the "first key on the bus" hole).
        #[test]
        fn ok_target_never_invents_an_endpoint(
            sel in any_sel(),
            hid in proptest::option::of("[ -~]{1,16}"),
            reader in proptest::option::of("[ -~]{1,16}"),
        ) {
            let hid_path = hid.as_ref().map(PathBuf::from);
            if let Ok(t) = otp_target_for(sel, hid_path.as_deref(), reader.as_deref()) {
                match t {
                    OtpTarget::HidPath(p) => {
                        prop_assert_eq!(Some(p.as_path()), hid_path.as_deref().map(Path::new));
                    }
                    OtpTarget::Reader(r) => prop_assert_eq!(Some(r.as_str()), reader.as_deref()),
                    OtpTarget::HidThenReader(p, r) => {
                        prop_assert_eq!(Some(p.as_path()), hid_path.as_deref().map(Path::new));
                        prop_assert_eq!(Some(r.as_str()), reader.as_deref());
                    }
                }
            }
        }
    }
}