yubikit 1.0.0-beta.0

YubiKey management library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
// Copyright 2026 Yubico AB
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! High-level device enumeration for YubiKeys.
//!
//! This module provides a convenient API for discovering connected YubiKeys
//! and opening sessions with them.
//!
//! # Example
//!
//! ```no_run
//! use yubikit::platform::device::list_devices;
//! use yubikit::management::UsbInterface;
//!
//! let devices = list_devices(UsbInterface::CCID | UsbInterface::OTP | UsbInterface::FIDO).unwrap();
//! for dev in &devices {
//!     println!("{} (serial: {:?})", dev.name(), dev.info().serial);
//! }
//! ```

use crate::core::{Transport, set_override_version};
use crate::fido::FidoConnection;
use crate::management::{BoxedManagementError, Capability, DeviceInfo, FormFactor, UsbInterface};
use crate::otp::OtpConnection;
use crate::smartcard::{Aid, SmartCardConnection, SmartCardError, SmartCardProtocol};

// ---------------------------------------------------------------------------
// DeviceError
// ---------------------------------------------------------------------------

/// Errors that can occur during device enumeration or connection.
#[derive(Debug, thiserror::Error)]
pub enum DeviceError {
    /// A SmartCard protocol error.
    #[error("SmartCard error: {0}")]
    SmartCard(#[from] SmartCardError),
    /// A management session error.
    #[error("Management error: {0}")]
    Management(#[source] BoxedManagementError),
    /// A transport-level error (PC/SC, HID, or FIDO).
    #[error("Transport error: {0}")]
    Transport(#[source] Box<dyn std::error::Error + Send + Sync>),
    /// No YubiKey device was found.
    #[error("No YubiKey device found")]
    NoDeviceFound,
    /// The YubiKey is present, but its CCID reader cannot be accessed.
    #[error("YubiKey CCID reader is unavailable")]
    CcidUnavailable,
    /// The YubiKey is owned by another service client.
    #[error("YubiKey in use by another client")]
    InUse,
    /// The card is not a YubiKey.
    #[error("Not a YubiKey")]
    NotYubiKey,
    /// The operation was cancelled by the caller.
    #[error("Operation cancelled")]
    Cancelled,
    /// A different YubiKey was inserted or removed during reinsert.
    #[error("A different YubiKey was inserted/removed")]
    WrongDevice,
    /// The operation requires a disabled Cargo feature.
    #[error("Operation requires the '{0}' feature")]
    UnsupportedFeature(&'static str),
}

/// Status updates during a device reinsert operation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ReinsertStatus {
    /// The device should be removed (USB: unplug, NFC: remove from reader).
    Remove,
    /// The device has been removed and should be reinserted (USB: plug in, NFC: place on reader).
    Reinsert,
}

impl From<crate::fido::FidoError> for DeviceError {
    fn from(e: crate::fido::FidoError) -> Self {
        Self::Transport(Box::new(e))
    }
}

// ---------------------------------------------------------------------------
// Device trait
// ---------------------------------------------------------------------------

/// Abstract interface to a YubiKey device.
///
/// Provides access to device metadata and the ability to open connections.
/// Implemented by [`crate::platform::device::LocalYubiKeyDevice`] for local devices and can be implemented
/// by RPC proxy types for remote access.
pub trait YubiKeyDevice {
    /// Returns the [`DeviceInfo`] for this device.
    fn info(&self) -> &DeviceInfo;
    /// Returns the transport type (USB or NFC).
    fn transport(&self) -> Transport;
    /// Returns the product name derived from device info.
    fn name(&self) -> String;
    /// Returns the USB Product ID, if known.
    fn pid(&self) -> Option<u16> {
        None
    }
    /// Returns the PC/SC reader name, if this device has a smartcard reader.
    fn reader_name(&self) -> Option<&str> {
        None
    }
    /// Returns the USB interfaces available on this device.
    fn usb_interfaces(&self) -> UsbInterface;
    /// Open a SmartCard (CCID) connection, returning a trait object.
    fn open_smartcard(&self) -> Result<Box<dyn SmartCardConnection + Send>, DeviceError>;
    /// Open a FIDO HID (CTAP) connection, returning a trait object.
    fn open_fido(&self) -> Result<Box<dyn FidoConnection + Send>, DeviceError>;
    /// Open an OTP HID connection, returning a trait object.
    fn open_otp(&self) -> Result<Box<dyn OtpConnection + Send>, DeviceError>;
    /// Wait for the user to remove and reinsert this YubiKey.
    fn reinsert(
        &mut self,
        status_cb: &dyn Fn(ReinsertStatus),
        cancelled: &dyn Fn() -> bool,
    ) -> Result<(), DeviceError>;
    /// Clone this device into a boxed trait object.
    fn clone_box(&self) -> Box<dyn YubiKeyDevice>;
}

impl YubiKeyDevice for Box<dyn YubiKeyDevice> {
    fn info(&self) -> &DeviceInfo {
        (**self).info()
    }
    fn transport(&self) -> Transport {
        (**self).transport()
    }
    fn name(&self) -> String {
        (**self).name()
    }
    fn pid(&self) -> Option<u16> {
        (**self).pid()
    }
    fn reader_name(&self) -> Option<&str> {
        (**self).reader_name()
    }
    fn usb_interfaces(&self) -> UsbInterface {
        (**self).usb_interfaces()
    }
    fn open_smartcard(&self) -> Result<Box<dyn SmartCardConnection + Send>, DeviceError> {
        (**self).open_smartcard()
    }
    fn open_fido(&self) -> Result<Box<dyn FidoConnection + Send>, DeviceError> {
        (**self).open_fido()
    }
    fn open_otp(&self) -> Result<Box<dyn OtpConnection + Send>, DeviceError> {
        (**self).open_otp()
    }
    fn reinsert(
        &mut self,
        status_cb: &dyn Fn(ReinsertStatus),
        cancelled: &dyn Fn() -> bool,
    ) -> Result<(), DeviceError> {
        (**self).reinsert(status_cb, cancelled)
    }
    fn clone_box(&self) -> Box<dyn YubiKeyDevice> {
        (**self).clone_box()
    }
}

// ---------------------------------------------------------------------------
// Device naming
// ---------------------------------------------------------------------------

use crate::core::Version;
use crate::management::{DeviceConfig, ManagementSession, ReleaseType};
use crate::yubiotp::YubiOtpSession;

/// Check if a USB PID belongs to a Security Key (SKY).
pub(crate) fn is_sky_pid(pid: u16) -> bool {
    pid == 0x0120
}

/// Check if a USB PID belongs to a YubiKey Plus.
pub(crate) fn is_plus_pid(pid: u16) -> bool {
    pid == 0x0410
}

/// Check if a USB PID belongs to a YubiKey NEO.
pub(crate) fn is_neo_pid(pid: u16) -> bool {
    (0x0110..=0x0116).contains(&pid)
}

/// Get a basic device name from a USB Product ID.
///
/// Returns "Security Key" for SKY PIDs, "YubiKey NEO" for NEO PIDs,
/// or "YubiKey" for all other Yubico PIDs.
pub fn name_from_pid(pid: u16) -> &'static str {
    if is_sky_pid(pid) {
        "Security Key"
    } else if is_neo_pid(pid) {
        "YubiKey NEO"
    } else {
        "YubiKey"
    }
}

/// Derive USB interface flags from a Yubico USB Product ID.
pub fn usb_interfaces_from_pid(pid: u16) -> UsbInterface {
    match pid {
        // NEO PIDs
        0x0110 => UsbInterface::OTP,
        0x0111 => UsbInterface::OTP | UsbInterface::CCID,
        0x0112 => UsbInterface::CCID,
        0x0113 => UsbInterface::FIDO,
        0x0114 => UsbInterface::OTP | UsbInterface::FIDO,
        0x0115 => UsbInterface::FIDO | UsbInterface::CCID,
        0x0116 => UsbInterface::OTP | UsbInterface::FIDO | UsbInterface::CCID,
        // YK4+ PIDs
        0x0401 => UsbInterface::OTP,
        0x0402 => UsbInterface::FIDO,
        0x0403 => UsbInterface::OTP | UsbInterface::FIDO,
        0x0404 => UsbInterface::CCID,
        0x0405 => UsbInterface::OTP | UsbInterface::CCID,
        0x0406 => UsbInterface::FIDO | UsbInterface::CCID,
        0x0407 => UsbInterface::OTP | UsbInterface::FIDO | UsbInterface::CCID,
        // SKY
        0x0120 => UsbInterface::FIDO,
        // YK Plus
        0x0410 => UsbInterface::OTP | UsbInterface::FIDO,
        // YK Standard
        0x0010 => UsbInterface::OTP,
        _ => UsbInterface(0),
    }
}

/// Preview firmware version ranges.
const PREVIEW_RANGES: &[(Version, Version)] = &[
    (Version(5, 0, 0), Version(5, 1, 0)),
    (Version(5, 2, 0), Version(5, 2, 3)),
    (Version(5, 5, 0), Version(5, 5, 2)),
];

pub(crate) fn is_preview(version: Version) -> bool {
    PREVIEW_RANGES
        .iter()
        .any(|(start, end)| version >= *start && version < *end)
}

pub(crate) fn fido_only(cap: Capability) -> bool {
    let non_fido = Capability::OTP.0
        | Capability::OATH.0
        | Capability::PIV.0
        | Capability::OPENPGP.0
        | Capability::HSMAUTH.0;
    let fido = Capability::U2F.0 | Capability::FIDO2.0;
    (cap.0 & non_fido == 0) && (cap.0 & fido != 0)
}

/// Determine the product name of a YubiKey from its [`DeviceInfo`].
pub fn get_name(info: &DeviceInfo) -> String {
    if let Some(name) = &info.name {
        return name.clone();
    }

    let usb_supported = info
        .supported_capabilities
        .get(&Transport::Usb)
        .copied()
        .unwrap_or(Capability::NONE);

    let major = info.version.0;

    // SKY devices are handled separately — they never get "YubiKey Preview"
    // even on preview firmware, matching the Python behavior where key_type
    // is determined from PID before the preview check.
    if info.is_sky {
        if info.version >= Version(5, 1, 0) {
            return build_yk5_name(info, usb_supported);
        }
        if !usb_supported.contains(Capability::FIDO2) {
            return "FIDO U2F Security Key".to_string();
        }
        return "Security Key by Yubico".to_string();
    }

    // Pre-YK4 devices
    if major < 4 {
        return if major == 0 {
            format!("YubiKey ({})", info.version)
        } else if major == 3 {
            "YubiKey NEO".to_string()
        } else {
            "YubiKey".to_string()
        };
    }

    // YK4 era
    if major == 4 {
        if info.is_fips {
            return "YubiKey FIPS (4 Series)".to_string();
        }
        if usb_supported == Capability(Capability::OTP.0 | Capability::U2F.0) {
            return "YubiKey Edge".to_string();
        }
        return "YubiKey 4".to_string();
    }

    // Preview firmware (non-SKY only)
    if is_preview(info.version) {
        return "YubiKey Preview".to_string();
    }

    // YK5+ dynamic naming (5.1.0+)
    if info.version >= Version(5, 1, 0) {
        return build_yk5_name(info, usb_supported);
    }

    // Fallback for 5.0.x
    "YubiKey 5".to_string()
}

fn build_yk5_name(info: &DeviceInfo, usb_supported: Capability) -> String {
    let is_nano = matches!(
        info.form_factor,
        FormFactor::UsbANano | FormFactor::UsbCNano
    );
    let is_bio = info.form_factor.is_bio();
    let is_c = matches!(
        info.form_factor,
        FormFactor::UsbCKeychain | FormFactor::UsbCNano | FormFactor::UsbCBio
    );
    let has_nfc = info.supported_capabilities.contains_key(&Transport::Nfc);

    let mut parts: Vec<&str> = Vec::new();

    // Base name
    if info.is_sky {
        parts.push("Security Key");
    } else {
        parts.push("YubiKey");
        if !is_bio {
            parts.push("5");
        }
    }

    // Connector type
    if is_c {
        parts.push("C");
    } else if info.form_factor == FormFactor::UsbCLightning {
        parts.push("Ci");
    }

    // Form factor / transport suffix
    if is_nano {
        parts.push("Nano");
    } else if has_nfc {
        parts.push("NFC");
    } else if info.form_factor == FormFactor::UsbAKeychain {
        parts.push("A");
    } else if is_bio {
        parts.push("Bio");
    }

    // Edition suffix
    if info.is_fips {
        parts.push("FIPS");
    } else if is_bio {
        if fido_only(usb_supported) {
            parts.push("- FIDO Edition");
        } else if usb_supported.contains(Capability::PIV) {
            parts.push("- Multi-protocol Edition");
        }
    } else if info.is_sky && info.serial.is_some() {
        parts.push("- Enterprise Edition");
    } else if info.pin_complexity && !info.is_sky {
        parts.push("- Enhanced PIN");
    }

    parts.join(" ").replace("5 C", "5C").replace("5 A", "5A")
}

/// Synthesize device info based on PID and version
fn synthesize_info(pid: u16, version: Version, serial: Option<u32>) -> DeviceInfo {
    let mut supported = std::collections::HashMap::new();
    let mut enabled = std::collections::HashMap::new();
    let mut capabilities: Capability;

    if pid == 0x0010 {
        // YubiKey Standard (1-2)
        capabilities = Capability::OTP;
    } else if is_sky_pid(pid) {
        // SKY
        capabilities = Capability::U2F;
    } else if is_plus_pid(pid) {
        // YubiKey Plus
        capabilities = Capability::OTP | Capability::U2F;
    } else if is_neo_pid(pid) {
        // NEO
        capabilities = Capability::OTP | Capability::OATH | Capability::OPENPGP | Capability::PIV;
        if version >= Version(3, 3, 0) || usb_interfaces_from_pid(pid).contains(UsbInterface::FIDO)
        {
            capabilities |= Capability::U2F;
        }
        supported.insert(Transport::Nfc, capabilities);
        enabled.insert(Transport::Nfc, capabilities);
    } else {
        capabilities = Capability::NONE;
    }
    supported.insert(Transport::Usb, capabilities);
    enabled.insert(Transport::Usb, capabilities);

    DeviceInfo {
        config: DeviceConfig {
            enabled_capabilities: enabled,
            auto_eject_timeout: None,
            challenge_response_timeout: None,
            device_flags: None,
            nfc_restricted: None,
        },
        serial,
        version,
        form_factor: FormFactor::Unknown,
        supported_capabilities: supported,
        is_locked: false,
        is_fips: false,
        is_sky: pid == 0x0120,
        part_number: None,
        fips_capable: Capability::NONE,
        fips_approved: Capability::NONE,
        pin_complexity: false,
        reset_blocked: Capability::NONE,
        fps_version: None,
        stm_version: None,
        version_qualifier: crate::management::VersionQualifier::final_release(version),
        name: None,
    }
}

/// Read [`DeviceInfo`] from an open smart card connection.
///
/// Falls back to probing individual applets on older devices that lack
/// the management applet. Returns an error if the card is not a YubiKey
/// (no supported capabilities detected). Returns the connection for reuse.
pub fn read_info_ccid<C: SmartCardConnection + Send + 'static>(
    conn: C,
    pid: Option<u16>,
) -> Result<(DeviceInfo, C), DeviceError> {
    let mut session = match ManagementSession::new(conn) {
        Ok(s) => s,
        Err((e, conn)) => {
            log::debug!("Management session init failed ({e}), synthesizing info");
            // NEO and other old devices don't have the management applet.
            return synthesize_info_ccid(conn, pid, None);
        }
    };

    // Old devices (NEO, YubiKey 3/4.0) expose the management applet but don't
    // support reading DeviceInfo. Fall back to synthesizing it from the
    // version reported by the applet and the serial from the OTP applet.
    if session.version() < Version(4, 1, 0) {
        log::debug!("Device predates DeviceInfo support, synthesizing info");
        let version = session.version();
        let conn = session.into_connection();
        return synthesize_info_ccid(conn, pid, Some(version));
    }

    match session.read_device_info() {
        Ok(mut info) => {
            apply_device_info_fixups(&mut info);
            Ok((info, session.into_connection()))
        }
        Err(e) => Err(DeviceError::Management(e.erase())),
    }
}

/// Applets to scan (by AID) when synthesizing [`DeviceInfo`] for older keys
/// over CCID without a known PID.
const SCAN_APPLETS: &[(&[u8], Capability)] = &[
    (Aid::FIDO, Capability::U2F),
    (Aid::PIV, Capability::PIV),
    (Aid::OPENPGP, Capability::OPENPGP),
    (Aid::OATH, Capability::OATH),
];

/// Synthesize [`DeviceInfo`] for a legacy device over a SmartCard connection.
///
/// Attempts to read the version and serial from the OTP applet. If a version
/// is already known (e.g. from the management applet select response), it is
/// preferred over the OTP-reported version.
///
/// When `pid` is known, capabilities are derived from it. When `pid` is `None`
/// (e.g. a NEO seen over NFC, where no USB Product ID is available), the
/// supported applets are probed over CCID to determine the capabilities.
///
/// Returns [`DeviceError::NotYubiKey`] if the device exposes no capabilities.
fn synthesize_info_ccid<C: SmartCardConnection + Send + 'static>(
    conn: C,
    pid: Option<u16>,
    known_version: Option<Version>,
) -> Result<(DeviceInfo, C), DeviceError> {
    use std::collections::HashMap;

    let (version, serial, otp_present, conn) = match YubiOtpSession::new(conn) {
        Ok(mut otp_session) => {
            let version = known_version.unwrap_or_else(|| otp_session.version());
            let serial = otp_session.get_serial().ok();
            (version, serial, true, otp_session.into_connection())
        }
        Err((e, conn)) => {
            log::debug!("Couldn't open YubiOTP session: {e}");
            // Assume a minimum version if none is known.
            (known_version.unwrap_or(Version(3, 0, 0)), None, false, conn)
        }
    };

    // When the PID is known, capabilities are derived from it.
    if let Some(pid) = pid {
        return Ok((synthesize_info(pid, version, serial), conn));
    }

    // No PID (e.g. NEO over NFC): probe the applets present on the card to
    // determine the supported capabilities.
    let mut capabilities = if otp_present {
        Capability::OTP
    } else {
        Capability::NONE
    };

    let mut protocol = SmartCardProtocol::new(conn);
    for (aid, cap) in SCAN_APPLETS {
        match protocol.select(aid) {
            Ok(_) => {
                capabilities |= *cap;
                log::debug!("Found applet: capability {cap:?}");
            }
            Err(e) => log::debug!("Missing applet: capability {cap:?}: {e}"),
        }
    }
    let conn = protocol.into_connection();

    // Assume U2F on devices >= 3.3.0.
    if version >= Version(3, 3, 0) {
        capabilities |= Capability::U2F;
    }

    if capabilities == Capability::NONE {
        return Err(DeviceError::NotYubiKey);
    }

    let mut supported = HashMap::new();
    supported.insert(Transport::Usb, capabilities);
    supported.insert(Transport::Nfc, capabilities);
    let mut enabled = HashMap::new();
    enabled.insert(Transport::Usb, capabilities);
    enabled.insert(Transport::Nfc, capabilities);

    let info = DeviceInfo {
        config: DeviceConfig {
            enabled_capabilities: enabled,
            auto_eject_timeout: None,
            challenge_response_timeout: None,
            device_flags: None,
            nfc_restricted: None,
        },
        serial,
        version,
        form_factor: FormFactor::Unknown,
        supported_capabilities: supported,
        is_locked: false,
        is_fips: false,
        is_sky: false,
        part_number: None,
        fips_capable: Capability::NONE,
        fips_approved: Capability::NONE,
        pin_complexity: false,
        reset_blocked: Capability::NONE,
        fps_version: None,
        stm_version: None,
        version_qualifier: crate::management::VersionQualifier::final_release(version),
        name: None,
    };
    Ok((info, conn))
}

/// Read [`DeviceInfo`] via OTP HID from an open connection.
///
/// Returns the connection for reuse. On error the connection is returned
/// when possible.
pub fn read_info_otp<T: OtpConnection + Send + 'static>(
    mut conn: T,
    pid: u16,
) -> Result<(DeviceInfo, T), (DeviceError, Option<T>)> {
    // Read the version directly from the connection
    let version = conn
        .otp_receive()
        .ok()
        .filter(|r| r.len() >= 4)
        .map(|r| Version::from_bytes(&r[1..4]))
        .unwrap_or(Version(0, 0, 0));

    // Older key, synthesize info
    if version != Version(0, 0, 1) && version < Version(4, 1, 0) {
        let (serial, conn) = match YubiOtpSession::new_otp(conn) {
            Ok(mut session) => {
                let serial = session.get_serial().ok();
                (serial, session.into_connection())
            }
            Err((e, conn)) => {
                log::debug!("Couldn't open YubiOTP session to read serial: {e}");
                (None, conn)
            }
        };
        return Ok((synthesize_info(pid, version, serial), conn));
    }

    let mut session = ManagementSession::new_otp(conn)
        .map_err(|(e, conn)| (DeviceError::Management(e.erase()), Some(conn)))?;
    match session.read_device_info() {
        Ok(mut info) => {
            apply_device_info_fixups(&mut info);
            Ok((info, session.into_connection()))
        }
        Err(e) => Err((
            DeviceError::Management(e.erase()),
            Some(session.into_connection()),
        )),
    }
}

/// Read [`DeviceInfo`] via FIDO HID (CTAP) from an open connection.
///
/// Returns the connection for reuse. On error the connection is returned
/// when possible.
pub fn read_info_fido<C: FidoConnection + 'static>(
    conn: C,
    pid: u16,
) -> Result<(DeviceInfo, C), (DeviceError, Option<C>)> {
    let version = conn.device_version();

    // Older key, synthesize info
    if version != Version(0, 0, 1) && version < Version(4, 1, 0) {
        return Ok((synthesize_info(pid, version, None), conn));
    }

    let mut session = ManagementSession::new_fido(conn)
        .map_err(|(e, conn)| (DeviceError::Management(e.erase()), Some(conn)))?;
    match session.read_device_info() {
        Ok(mut info) => {
            apply_device_info_fixups(&mut info);
            Ok((info, session.into_connection()))
        }
        Err(e) => Err((
            DeviceError::Management(e.erase()),
            Some(session.into_connection()),
        )),
    }
}

/// Apply standard fixups for known device quirks.
fn apply_device_info_fixups(info: &mut DeviceInfo) {
    // Override version from version qualifier for non-final (dev) firmware
    if info.version_qualifier.release_type != ReleaseType::Final {
        log::debug!(
            "Overriding version {} with qualifier version {}",
            info.version,
            info.version_qualifier.version
        );
        info.version = info.version_qualifier.version;
        set_override_version(info.version);
    }

    // YK4-based FIPS (4.4.x)
    if info.version >= Version(4, 4, 0) && info.version < Version(4, 5, 0) {
        info.is_fips = true;
    }

    // Infer SKY for older firmware that doesn't set the flag.
    // Devices before 5.2.8 with no serial and FIDO-only capabilities are SKY.
    if !info.is_sky
        && info.serial.is_none()
        && info.version < Version(5, 2, 8)
        && info
            .supported_capabilities
            .get(&Transport::Usb)
            .is_some_and(|c| fido_only(*c))
    {
        info.is_sky = true;
    }

    // Fix NFC: set enabled if missing
    if info.has_transport(Transport::Nfc) {
        if !info
            .config
            .enabled_capabilities
            .contains_key(&Transport::Nfc)
            && let Some(&nfc_sup) = info.supported_capabilities.get(&Transport::Nfc)
        {
            info.config
                .enabled_capabilities
                .insert(Transport::Nfc, nfc_sup);
        }
        // Remove NFC for form factors known to not have NFC
        let remove_nfc = matches!(
            info.form_factor,
            FormFactor::UsbANano | FormFactor::UsbCNano | FormFactor::UsbCLightning
        ) || (info.form_factor == FormFactor::UsbCKeychain
            && info.version < Version(5, 2, 4));

        if remove_nfc {
            info.supported_capabilities.remove(&Transport::Nfc);
            info.config.enabled_capabilities.remove(&Transport::Nfc);
        }
    }

    // Fix USB: set enabled if missing (pre-YubiKey 5)
    if info.has_transport(Transport::Usb)
        && !info
            .config
            .enabled_capabilities
            .contains_key(&Transport::Usb)
        && let Some(&usb_sup) = info.supported_capabilities.get(&Transport::Usb)
    {
        info.config
            .enabled_capabilities
            .insert(Transport::Usb, usb_sup);
    }
}

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

    fn make_info(
        version: Version,
        form_factor: FormFactor,
        is_sky: bool,
        is_fips: bool,
        serial: Option<u32>,
        nfc: bool,
        usb_cap: Capability,
        pin_complexity: bool,
    ) -> DeviceInfo {
        let mut supported = HashMap::new();
        supported.insert(Transport::Usb, usb_cap);
        if nfc {
            supported.insert(Transport::Nfc, usb_cap);
        }
        DeviceInfo {
            config: DeviceConfig {
                enabled_capabilities: HashMap::new(),
                auto_eject_timeout: None,
                challenge_response_timeout: None,
                device_flags: None,
                nfc_restricted: None,
            },
            serial,
            version,
            form_factor,
            supported_capabilities: supported,
            is_locked: false,
            is_fips,
            is_sky,
            part_number: None,
            fips_capable: Capability::NONE,
            fips_approved: Capability::NONE,
            pin_complexity,
            reset_blocked: Capability::NONE,
            fps_version: None,
            stm_version: None,
            version_qualifier: crate::management::VersionQualifier::final_release(version),
            name: None,
        }
    }

    #[test]
    fn test_neo() {
        let info = make_info(
            Version(3, 5, 0),
            FormFactor::Unknown,
            false,
            false,
            Some(123),
            true,
            Capability(Capability::OTP.0 | Capability::OATH.0),
            false,
        );
        assert_eq!(get_name(&info), "YubiKey NEO");
    }

    #[test]
    fn test_yk4() {
        let info = make_info(
            Version(4, 3, 7),
            FormFactor::UsbAKeychain,
            false,
            false,
            Some(456),
            false,
            Capability(Capability::OTP.0 | Capability::PIV.0 | Capability::OATH.0),
            false,
        );
        assert_eq!(get_name(&info), "YubiKey 4");
    }

    #[test]
    fn test_yk4_fips() {
        let info = make_info(
            Version(4, 4, 5),
            FormFactor::UsbAKeychain,
            false,
            true,
            Some(789),
            false,
            Capability(Capability::OTP.0 | Capability::PIV.0),
            false,
        );
        assert_eq!(get_name(&info), "YubiKey FIPS (4 Series)");
    }

    #[test]
    fn test_yk5_nfc() {
        let info = make_info(
            Version(5, 2, 4),
            FormFactor::UsbAKeychain,
            false,
            false,
            Some(100),
            true,
            Capability(Capability::OTP.0 | Capability::PIV.0 | Capability::FIDO2.0),
            false,
        );
        assert_eq!(get_name(&info), "YubiKey 5 NFC");
    }

    #[test]
    fn test_yk5c_nano() {
        let info = make_info(
            Version(5, 4, 3),
            FormFactor::UsbCNano,
            false,
            false,
            Some(200),
            false,
            Capability(Capability::OTP.0 | Capability::PIV.0),
            false,
        );
        assert_eq!(get_name(&info), "YubiKey 5C Nano");
    }

    #[test]
    fn test_yk5ci() {
        let info = make_info(
            Version(5, 2, 4),
            FormFactor::UsbCLightning,
            false,
            false,
            Some(300),
            false,
            Capability(Capability::OTP.0 | Capability::PIV.0),
            false,
        );
        assert_eq!(get_name(&info), "YubiKey 5Ci");
    }

    #[test]
    fn test_security_key_nfc() {
        let info = make_info(
            Version(5, 2, 8),
            FormFactor::UsbAKeychain,
            true,
            false,
            None,
            true,
            Capability(Capability::U2F.0 | Capability::FIDO2.0),
            false,
        );
        assert_eq!(get_name(&info), "Security Key NFC");
    }

    #[test]
    fn test_bio_fido() {
        let info = make_info(
            Version(5, 5, 6),
            FormFactor::UsbABio,
            false,
            false,
            Some(400),
            false,
            Capability(Capability::U2F.0 | Capability::FIDO2.0),
            false,
        );
        assert_eq!(get_name(&info), "YubiKey Bio - FIDO Edition");
    }

    #[test]
    fn test_bio_multi_protocol() {
        let info = make_info(
            Version(5, 6, 0),
            FormFactor::UsbCBio,
            false,
            false,
            Some(500),
            false,
            Capability(Capability::PIV.0 | Capability::FIDO2.0),
            false,
        );
        assert_eq!(get_name(&info), "YubiKey C Bio - Multi-protocol Edition");
    }

    #[test]
    fn test_preview() {
        let info = make_info(
            Version(5, 0, 1),
            FormFactor::UsbAKeychain,
            false,
            false,
            Some(600),
            false,
            Capability(Capability::OTP.0 | Capability::PIV.0),
            false,
        );
        assert_eq!(get_name(&info), "YubiKey Preview");
    }

    #[test]
    fn test_sky_enterprise() {
        let info = make_info(
            Version(5, 4, 3),
            FormFactor::UsbAKeychain,
            true,
            false,
            Some(700),
            false,
            Capability(Capability::U2F.0 | Capability::FIDO2.0),
            false,
        );
        assert_eq!(get_name(&info), "Security Key A - Enterprise Edition");
    }

    #[test]
    fn test_sky_nfc_inferred() {
        let mut info = make_info(
            Version(5, 1, 2),
            FormFactor::UsbAKeychain,
            false,
            false,
            None,
            true,
            Capability(Capability::U2F.0 | Capability::FIDO2.0),
            false,
        );
        apply_device_info_fixups(&mut info);
        assert!(info.is_sky);
        assert_eq!(get_name(&info), "Security Key NFC");
    }

    #[test]
    fn test_sky_inference_not_applied_with_serial() {
        let mut info = make_info(
            Version(5, 1, 2),
            FormFactor::UsbAKeychain,
            false,
            false,
            Some(123),
            true,
            Capability(Capability::U2F.0 | Capability::FIDO2.0),
            false,
        );
        apply_device_info_fixups(&mut info);
        assert!(!info.is_sky);
    }

    #[test]
    fn test_yk5a() {
        let info = make_info(
            Version(5, 2, 4),
            FormFactor::UsbAKeychain,
            false,
            false,
            Some(800),
            false,
            Capability(Capability::OTP.0 | Capability::PIV.0),
            false,
        );
        assert_eq!(get_name(&info), "YubiKey 5A");
    }

    #[test]
    fn test_fido_only() {
        assert!(fido_only(Capability(
            Capability::U2F.0 | Capability::FIDO2.0
        )));
        assert!(fido_only(Capability::FIDO2));
        assert!(!fido_only(Capability(
            Capability::FIDO2.0 | Capability::PIV.0
        )));
        assert!(!fido_only(Capability::NONE));
    }

    #[test]
    fn test_is_preview() {
        assert!(is_preview(Version(5, 0, 0)));
        assert!(is_preview(Version(5, 0, 1)));
        assert!(!is_preview(Version(5, 1, 0)));
        assert!(is_preview(Version(5, 2, 0)));
        assert!(is_preview(Version(5, 2, 2)));
        assert!(!is_preview(Version(5, 2, 3)));
        assert!(is_preview(Version(5, 5, 0)));
        assert!(is_preview(Version(5, 5, 1)));
        assert!(!is_preview(Version(5, 5, 2)));
        assert!(!is_preview(Version(5, 4, 0)));
    }

    #[test]
    fn test_enhanced_pin() {
        let info = make_info(
            Version(5, 7, 0),
            FormFactor::UsbCKeychain,
            false,
            false,
            Some(900),
            false,
            Capability(Capability::OTP.0 | Capability::PIV.0),
            true,
        );
        assert_eq!(get_name(&info), "YubiKey 5C - Enhanced PIN");
    }

    #[test]
    fn test_sky_preview_firmware() {
        let mut info = make_info(
            Version(5, 0, 2),
            FormFactor::UsbAKeychain,
            false,
            false,
            None,
            false,
            Capability(Capability::U2F.0 | Capability::FIDO2.0),
            false,
        );
        apply_device_info_fixups(&mut info);
        assert!(info.is_sky);
        assert_eq!(get_name(&info), "Security Key by Yubico");
    }

    #[test]
    fn test_sky_u2f_only() {
        let info = make_info(
            Version(0, 0, 0),
            FormFactor::Unknown,
            true,
            false,
            None,
            false,
            Capability::U2F,
            false,
        );
        assert_eq!(get_name(&info), "FIDO U2F Security Key");
    }

    #[test]
    fn test_is_sky_pid() {
        assert!(is_sky_pid(0x0120));
        assert!(!is_sky_pid(0x0116));
        assert!(!is_sky_pid(0x0401));
    }
}