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
// 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.

//! CTAP2 protocol session and PIN/UV management.
//!
//! Provides [`Ctap2Session`](crate::ctap2::Ctap2Session), which wraps a
//! [`CtapSession`](crate::ctap::CtapSession) and implements CTAP2-specific
//! command framing and response parsing.
//!
//! Also provides [`ClientPin`](crate::ctap2::ClientPin) for PIN/UV token
//! operations, and [`PinProtocol`](crate::ctap2::PinProtocol) (V1/V2) for
//! the underlying cryptographic operations.
//!
//! # Example
//!
//! ```no_run
//! use yubikit::ctap::CtapSession;
//! use yubikit::ctap2::Ctap2Session;
//! use yubikit::platform::hidapi::{HidFidoConnection, list_fido_devices};
//!
//! let devices = list_fido_devices()?;
//! let dev = devices.first().expect("no FIDO device found");
//! let conn = HidFidoConnection::open(dev)?;
//! let ctap = CtapSession::new_fido(conn).map_err(|(e, _)| e)?;
//! let mut session = Ctap2Session::new(ctap).map_err(|(e, _)| e)?;
//!
//! println!("Authenticator: {:?}", session.get_info()?.versions);
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```

mod bio_enrollment;
mod client_pin;
mod config;
mod credential_management;
mod large_blobs;
mod pin_protocol;
mod session;
/// CTAP2 data types for credentials, attestations, and authenticator responses.
pub mod types;

use std::collections::BTreeMap;

use hkdf::Hkdf;
use sha2::Sha256;

use crate::cbor::{self, Value};
use crate::ctap::CtapError;

/// Re-export core WebAuthn credential types used throughout CTAP2 operations.
pub use crate::webauthn::{
    PublicKeyCredentialDescriptor, PublicKeyCredentialParameters, PublicKeyCredentialUserEntity,
};
/// Re-export fingerprint bio enrollment management.
pub use bio_enrollment::BioEnrollment;
/// Re-export PIN/UV token management and permission flags.
pub use client_pin::{ClientPin, Ctap2Pin, Permissions};
/// Re-export authenticator configuration management.
pub use config::Config;
/// Re-export resident credential management operations.
pub use credential_management::CredentialManagement;
/// Re-export large-blob array read/write operations.
pub use large_blobs::LargeBlobs;
/// Re-export COSE key representation and PIN protocol versions.
pub use pin_protocol::{CoseKey, PinProtocol};
/// Re-export the CTAP2 session for authenticator communication.
pub use session::Ctap2Session;
/// Re-export commonly used CTAP2 response and credential data types.
pub use types::{
    AssertionResponse, AttestationResponse, AuthenticatorOptions, CredentialInfo,
    EnrollSampleResult, FingerprintSensorInfo, FingerprintTemplate, PublicKeyCredentialRpEntity,
    RpInfo,
};

// ---------------------------------------------------------------------------
// CTAP2 command bytes
// ---------------------------------------------------------------------------

/// CTAP2 authenticator command identifiers.
#[allow(dead_code)]
pub(crate) mod ctap2_cmd {
    /// `authenticatorMakeCredential` (0x01).
    pub const MAKE_CREDENTIAL: u8 = 0x01;
    /// `authenticatorGetAssertion` (0x02).
    pub const GET_ASSERTION: u8 = 0x02;
    /// `authenticatorGetInfo` (0x04).
    pub const GET_INFO: u8 = 0x04;
    /// `authenticatorClientPIN` (0x06).
    pub const CLIENT_PIN: u8 = 0x06;
    /// `authenticatorReset` (0x07).
    pub const RESET: u8 = 0x07;
    /// `authenticatorGetNextAssertion` (0x08).
    pub const GET_NEXT_ASSERTION: u8 = 0x08;
    /// `authenticatorBioEnrollment` (0x09).
    pub const BIO_ENROLLMENT: u8 = 0x09;
    /// `authenticatorCredentialManagement` (0x0A).
    pub const CREDENTIAL_MGMT: u8 = 0x0A;
    /// `authenticatorSelection` (0x0B).
    pub const SELECTION: u8 = 0x0B;
    /// `authenticatorLargeBlobs` (0x0C).
    pub const LARGE_BLOBS: u8 = 0x0C;
    /// `authenticatorConfig` (0x0D).
    pub const CONFIG: u8 = 0x0D;
    /// Vendor prototype `authenticatorBioEnrollment` (0x40).
    pub const BIO_ENROLLMENT_PRE: u8 = 0x40;
    /// Vendor prototype `authenticatorCredentialManagement` (0x41).
    pub const CREDENTIAL_MGMT_PRE: u8 = 0x41;
}

/// Build a CBOR map with sequential integer keys (1, 2, 3, ...) from positional args.
///
/// `None` entries are skipped (their key position is still consumed).
pub(crate) fn build_args_map(args: &[Option<Value>]) -> Vec<u8> {
    let mut params: Vec<(Value, Value)> = Vec::new();
    for (i, arg) in args.iter().enumerate() {
        if let Some(val) = arg {
            params.push((Value::Int((i + 1) as i64), val.clone()));
        }
    }
    cbor::encode(&Value::Map(params))
}

// ---------------------------------------------------------------------------
// CTAP2 status codes
// ---------------------------------------------------------------------------

/// CTAP2 error status codes returned by the authenticator.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum CtapStatus {
    /// The command completed successfully.
    Success = 0x00,
    /// The command is not a valid CTAP2 command.
    InvalidCommand = 0x01,
    /// One or more command parameters are invalid.
    InvalidParameter = 0x02,
    /// The encoded command length is invalid.
    InvalidLength = 0x03,
    /// The command sequence number is out of order.
    InvalidSeq = 0x04,
    /// The command timed out waiting for a response.
    Timeout = 0x05,
    /// The authenticator channel is busy processing another request.
    ChannelBusy = 0x06,
    /// A software lock is required before the command can proceed.
    LockRequired = 0x0A,
    /// The logical channel is invalid.
    InvalidChannel = 0x0B,
    /// The CBOR value has an unexpected type.
    CborUnexpectedType = 0x11,
    /// The CBOR encoding could not be parsed.
    InvalidCbor = 0x12,
    /// A required parameter is missing.
    MissingParameter = 0x14,
    /// An internal limit was exceeded (e.g. map size, array length).
    LimitExceeded = 0x15,
    /// The fingerprint database is full.
    FpDatabaseFull = 0x17,
    /// The large-blob storage is full.
    LargeBlobStorageFull = 0x18,
    /// The credential was excluded per the exclude list.
    CredentialExcluded = 0x19,
    /// The authenticator is still processing the request.
    Processing = 0x21,
    /// The credential is invalid or unrecognized.
    InvalidCredential = 0x22,
    /// A user action (touch) is pending.
    UserActionPending = 0x23,
    /// An operation is already in progress.
    OperationPending = 0x24,
    /// No operations are pending.
    NoOperations = 0x25,
    /// The requested algorithm is not supported.
    UnsupportedAlgorithm = 0x26,
    /// The operation was denied by policy.
    OperationDenied = 0x27,
    /// Internal key storage is full.
    KeyStoreFull = 0x28,
    /// The requested option is not supported.
    UnsupportedOption = 0x2B,
    /// The option value is invalid.
    InvalidOption = 0x2C,
    /// The operation was cancelled by a keepalive cancel request.
    KeepaliveCancel = 0x2D,
    /// No matching credentials were found.
    NoCredentials = 0x2E,
    /// The user did not complete the required action in time.
    UserActionTimeout = 0x2F,
    /// The operation is not allowed in the current state.
    NotAllowed = 0x30,
    /// The PIN is invalid.
    PinInvalid = 0x31,
    /// The PIN has been blocked due to too many failed attempts.
    PinBlocked = 0x32,
    /// The PIN authentication parameter (pinUvAuthParam) is invalid.
    PinAuthInvalid = 0x33,
    /// PIN authentication is blocked until the next power cycle.
    PinAuthBlocked = 0x34,
    /// No PIN has been set on the authenticator.
    PinNotSet = 0x35,
    /// A PIN/UV auth token is required but not provided.
    PuatRequired = 0x36,
    /// The new PIN violates the authenticator's PIN policy.
    PinPolicyViolation = 0x37,
    /// The PIN/UV auth token has expired.
    PinTokenExpired = 0x38,
    /// The serialized request is too large for the authenticator.
    RequestTooLarge = 0x39,
    /// The action timed out.
    ActionTimeout = 0x3A,
    /// User presence is required.
    UpRequired = 0x3B,
    /// Built-in user verification is blocked.
    UvBlocked = 0x3C,
    /// An integrity check failed.
    IntegrityFailure = 0x3D,
    /// The subcommand is invalid.
    InvalidSubcommand = 0x3E,
    /// Built-in user verification attempt was invalid.
    UvInvalid = 0x3F,
    /// The PIN/UV token does not have the required permission.
    UnauthorizedPermission = 0x40,
    /// An unrecognized or vendor-specific error code.
    Other = 0x7F,
}

impl CtapStatus {
    /// Convert a raw status byte into a `CtapStatus`.
    pub fn from_byte(b: u8) -> Self {
        match b {
            0x00 => Self::Success,
            0x01 => Self::InvalidCommand,
            0x02 => Self::InvalidParameter,
            0x03 => Self::InvalidLength,
            0x04 => Self::InvalidSeq,
            0x05 => Self::Timeout,
            0x06 => Self::ChannelBusy,
            0x0A => Self::LockRequired,
            0x0B => Self::InvalidChannel,
            0x11 => Self::CborUnexpectedType,
            0x12 => Self::InvalidCbor,
            0x14 => Self::MissingParameter,
            0x15 => Self::LimitExceeded,
            0x17 => Self::FpDatabaseFull,
            0x18 => Self::LargeBlobStorageFull,
            0x19 => Self::CredentialExcluded,
            0x21 => Self::Processing,
            0x22 => Self::InvalidCredential,
            0x23 => Self::UserActionPending,
            0x24 => Self::OperationPending,
            0x25 => Self::NoOperations,
            0x26 => Self::UnsupportedAlgorithm,
            0x27 => Self::OperationDenied,
            0x28 => Self::KeyStoreFull,
            0x2B => Self::UnsupportedOption,
            0x2C => Self::InvalidOption,
            0x2D => Self::KeepaliveCancel,
            0x2E => Self::NoCredentials,
            0x2F => Self::UserActionTimeout,
            0x30 => Self::NotAllowed,
            0x31 => Self::PinInvalid,
            0x32 => Self::PinBlocked,
            0x33 => Self::PinAuthInvalid,
            0x34 => Self::PinAuthBlocked,
            0x35 => Self::PinNotSet,
            0x36 => Self::PuatRequired,
            0x37 => Self::PinPolicyViolation,
            0x38 => Self::PinTokenExpired,
            0x39 => Self::RequestTooLarge,
            0x3A => Self::ActionTimeout,
            0x3B => Self::UpRequired,
            0x3C => Self::UvBlocked,
            0x3D => Self::IntegrityFailure,
            0x3E => Self::InvalidSubcommand,
            0x3F => Self::UvInvalid,
            0x40 => Self::UnauthorizedPermission,
            _ => Self::Other,
        }
    }
}

impl std::fmt::Display for CtapStatus {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{self:?} (0x{:02X})", *self as u8)
    }
}

// ---------------------------------------------------------------------------
// Ctap2Error
// ---------------------------------------------------------------------------

/// Error type for [`Ctap2Session`] CTAP2 protocol operations.
#[derive(Debug)]
pub enum Ctap2Error<E: std::error::Error + Send + Sync + 'static> {
    /// The authenticator returned a non-success status code.
    StatusError(CtapStatus),
    /// The underlying transport or session returned an error.
    Transport(CtapError<E>),
    /// The response from the authenticator was malformed.
    InvalidResponse(String),
}

impl<E: std::error::Error + Send + Sync + 'static> std::fmt::Display for Ctap2Error<E> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::StatusError(status) => write!(f, "CTAP2 error: {status}"),
            Self::Transport(e) => write!(f, "{e}"),
            Self::InvalidResponse(msg) => write!(f, "Invalid CTAP2 response: {msg}"),
        }
    }
}

impl<E: std::error::Error + Send + Sync + 'static> std::error::Error for Ctap2Error<E> {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Transport(e) => Some(e),
            _ => None,
        }
    }
}

impl<E: std::error::Error + Send + Sync + 'static> From<CtapError<E>> for Ctap2Error<E> {
    fn from(e: CtapError<E>) -> Self {
        Self::Transport(e)
    }
}

// ---------------------------------------------------------------------------
// Aaguid
// ---------------------------------------------------------------------------

/// 16-byte Authenticator Attestation GUID.
#[derive(Clone, Default, PartialEq, Eq, Hash)]
pub struct Aaguid([u8; 16]);

impl Aaguid {
    /// The all-zeros AAGUID, indicating no attestation identity.
    pub const NONE: Aaguid = Aaguid([0u8; 16]);

    /// Create an `Aaguid` from a 16-byte array.
    pub fn new(data: [u8; 16]) -> Self {
        Self(data)
    }

    /// Create an `Aaguid` from a byte slice, returning `None` if not exactly 16 bytes.
    pub fn from_slice(data: &[u8]) -> Option<Self> {
        data.try_into().ok().map(Self)
    }

    /// Return the underlying 16-byte array.
    pub fn as_bytes(&self) -> &[u8; 16] {
        &self.0
    }

    /// Whether this is the all-zeros (absent) AAGUID.
    pub fn is_none(&self) -> bool {
        self.0 == [0u8; 16]
    }
}

impl std::fmt::Debug for Aaguid {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        // Format as UUID: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
        let b = &self.0;
        write!(
            f,
            "{:02x}{:02x}{:02x}{:02x}-{:02x}{:02x}-{:02x}{:02x}-{:02x}{:02x}-{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}",
            b[0],
            b[1],
            b[2],
            b[3],
            b[4],
            b[5],
            b[6],
            b[7],
            b[8],
            b[9],
            b[10],
            b[11],
            b[12],
            b[13],
            b[14],
            b[15],
        )
    }
}

impl std::fmt::Display for Aaguid {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        std::fmt::Debug::fmt(self, f)
    }
}

// ---------------------------------------------------------------------------
// Info (authenticatorGetInfo response)
// ---------------------------------------------------------------------------

/// Parsed response from the authenticatorGetInfo command (§6.4).
///
/// All fields correspond to the integer-keyed CBOR map returned by the
/// authenticator. Optional/defaulted fields follow the CTAP 2.3 spec defaults.
#[derive(Debug, Clone, Default)]
pub struct Info {
    /// 0x01: List of supported protocol versions (e.g. "FIDO_2_0", "FIDO_2_1").
    pub versions: Vec<String>,
    /// 0x02: List of supported extensions.
    pub extensions: Vec<String>,
    /// 0x03: The AAGUID of the authenticator.
    pub aaguid: Aaguid,
    /// 0x04: Map of supported options and their values.
    pub options: BTreeMap<String, bool>,
    /// 0x05: Maximum message size supported by the authenticator (default 1024).
    pub max_msg_size: usize,
    /// 0x06: List of supported PIN/UV auth protocol versions.
    pub pin_uv_protocols: Vec<u32>,
    /// 0x07: Maximum number of credentials in a credential ID list.
    pub max_creds_in_list: Option<usize>,
    /// 0x08: Maximum credential ID length in bytes.
    pub max_cred_id_length: Option<usize>,
    /// 0x09: List of supported transports.
    pub transports: Vec<String>,
    /// 0x0A: List of supported algorithms for credential generation.
    pub algorithms: Vec<PublicKeyCredentialParameters>,
    /// 0x0B: Maximum size of the serialized large-blob array.
    pub max_large_blob: Option<usize>,
    /// 0x0C: Whether the authenticator requires a PIN change.
    pub force_pin_change: bool,
    /// 0x0D: Current minimum PIN length in Unicode code points (default 4).
    pub min_pin_length: usize,
    /// 0x0E: Firmware version of the authenticator.
    pub firmware_version: Option<u64>,
    /// 0x0F: Maximum credBlob length in bytes.
    pub max_cred_blob_length: Option<usize>,
    /// 0x10: Maximum number of RP IDs for setMinPINLength.
    pub max_rpids_for_min_pin: Option<usize>,
    /// 0x11: Preferred number of platform UV attempts before falling back.
    pub preferred_platform_uv_attempts: Option<usize>,
    /// 0x12: Bit field of supported UV modalities.
    pub uv_modality: Option<u32>,
    /// 0x13: Map of certification type to certification level.
    pub certifications: BTreeMap<String, Value>,
    /// 0x14: Estimated number of additional discoverable credentials that can be stored.
    pub remaining_disc_creds: Option<u32>,
    /// 0x15: List of vendor prototype config command identifiers.
    pub vendor_prototype_config_commands: Vec<u32>,
    /// 0x16: List of supported attestation formats (default ["packed"]).
    pub attestation_formats: Vec<String>,
    /// 0x17: Number of UV attempts since last PIN entry.
    pub uv_count_since_pin: Option<u32>,
    /// 0x18: Whether reset requires a long (10 second) touch.
    pub long_touch_for_reset: bool,
    /// 0x19: Encrypted device identifier (opaque, regenerated each getInfo call).
    pub enc_identifier: Option<Vec<u8>>,
    /// 0x1A: List of transports that must be used for reset.
    pub transports_for_reset: Vec<String>,
    /// 0x1B: Whether the authenticator enforces a PIN complexity policy beyond minPINLength.
    pub pin_complexity_policy: Option<bool>,
    /// 0x1C: URL with more information about the enforced PIN complexity policy.
    pub pin_complexity_policy_url: Option<Vec<u8>>,
    /// 0x1D: Maximum PIN length in Unicode code points (default 63 if absent).
    pub max_pin_length: Option<usize>,
    /// 0x1E: Encrypted credential store state (opaque, regenerated each getInfo call).
    pub enc_cred_store_state: Option<Vec<u8>>,
    /// 0x1F: List of supported authenticatorConfig subcommand values.
    pub config_commands: Vec<u32>,
}

impl Info {
    /// Parse an `Info` from a CBOR map with integer keys.
    pub fn from_cbor_map(map: &[(Value, Value)]) -> Self {
        let get = |key: i64| -> Option<&Value> {
            map.iter()
                .find(|(k, _)| matches!(k, Value::Int(n) if *n == key))
                .map(|(_, v)| v)
        };

        let get_strings = |key: i64| -> Vec<String> {
            get(key)
                .and_then(|v| v.as_array())
                .map(|arr| {
                    arr.iter()
                        .filter_map(|v| v.as_text().map(|s| s.to_string()))
                        .collect()
                })
                .unwrap_or_default()
        };

        let get_uint =
            |key: i64| -> Option<u64> { get(key).and_then(|v| v.as_int()).map(|n| n as u64) };

        let get_bool = |key: i64| -> Option<bool> { get(key).and_then(|v| v.as_bool()) };

        let get_uint_vec = |key: i64| -> Vec<u32> {
            get(key)
                .and_then(|v| v.as_array())
                .map(|arr| {
                    arr.iter()
                        .filter_map(|v| v.as_int().map(|n| n as u32))
                        .collect()
                })
                .unwrap_or_default()
        };

        let get_string_map = |key: i64| -> BTreeMap<String, Value> {
            get(key)
                .and_then(|v| v.as_map())
                .map(|entries| {
                    entries
                        .iter()
                        .filter_map(|(k, v)| k.as_text().map(|s| (s.to_string(), v.clone())))
                        .collect()
                })
                .unwrap_or_default()
        };

        let aaguid = get(0x03)
            .and_then(|v| v.as_bytes())
            .and_then(Aaguid::from_slice)
            .unwrap_or(Aaguid::NONE);

        let options = get(0x04)
            .and_then(|v| v.as_map())
            .map(|entries| {
                entries
                    .iter()
                    .filter_map(|(k, v)| {
                        k.as_text()
                            .and_then(|key| v.as_bool().map(|val| (key.to_string(), val)))
                    })
                    .collect()
            })
            .unwrap_or_default();

        let algorithms = get(0x0A)
            .and_then(|v| v.as_array())
            .map(|arr| {
                arr.iter()
                    .filter_map(PublicKeyCredentialParameters::from_cbor)
                    .collect()
            })
            .unwrap_or_default();

        let attestation_formats = {
            let fmts = get_strings(0x16);
            if fmts.is_empty() {
                vec!["packed".to_string()]
            } else {
                fmts
            }
        };

        Info {
            versions: get_strings(0x01),
            extensions: get_strings(0x02),
            aaguid,
            options,
            max_msg_size: get_uint(0x05).unwrap_or(1024) as usize,
            pin_uv_protocols: get_uint_vec(0x06),
            max_creds_in_list: get_uint(0x07).map(|n| n as usize),
            max_cred_id_length: get_uint(0x08).map(|n| n as usize),
            transports: get_strings(0x09),
            algorithms,
            max_large_blob: get_uint(0x0B).map(|n| n as usize),
            force_pin_change: get_bool(0x0C).unwrap_or(false),
            min_pin_length: get_uint(0x0D).unwrap_or(4) as usize,
            firmware_version: get_uint(0x0E),
            max_cred_blob_length: get_uint(0x0F).map(|n| n as usize),
            max_rpids_for_min_pin: get_uint(0x10).map(|n| n as usize),
            preferred_platform_uv_attempts: get_uint(0x11).map(|n| n as usize),
            uv_modality: get_uint(0x12).map(|n| n as u32),
            certifications: get_string_map(0x13),
            remaining_disc_creds: get_uint(0x14).map(|n| n as u32),
            vendor_prototype_config_commands: get_uint_vec(0x15),
            attestation_formats,
            uv_count_since_pin: get_uint(0x17).map(|n| n as u32),
            long_touch_for_reset: get_bool(0x18).unwrap_or(false),
            enc_identifier: get(0x19).and_then(|v| v.as_bytes()).map(|b| b.to_vec()),
            transports_for_reset: get_strings(0x1A),
            pin_complexity_policy: get_bool(0x1B),
            pin_complexity_policy_url: get(0x1C).and_then(|v| v.as_bytes()).map(|b| b.to_vec()),
            max_pin_length: get_uint(0x1D).map(|n| n as usize),
            enc_cred_store_state: get(0x1E).and_then(|v| v.as_bytes()).map(|b| b.to_vec()),
            config_commands: get_uint_vec(0x1F),
        }
    }

    /// Decrypt the encrypted device identifier using a persistent PIN/UV auth token.
    ///
    /// The identifier is encrypted by the authenticator and changes with each
    /// `getInfo` call, but decrypts to a stable value using the same persistent
    /// token. Returns `None` if the authenticator did not provide an encrypted
    /// identifier.
    pub fn get_identifier(&self, pin_token: &[u8]) -> Option<Vec<u8>> {
        self.decrypt_field(self.enc_identifier.as_deref(), b"encIdentifier", pin_token)
    }

    /// Decrypt the encrypted credential store state using a persistent PIN/UV auth token.
    ///
    /// The state value changes when credentials are added or removed, allowing
    /// the client to detect changes without re-enumerating. Returns `None` if
    /// the authenticator did not provide an encrypted credential store state.
    pub fn get_cred_store_state(&self, pin_token: &[u8]) -> Option<Vec<u8>> {
        self.decrypt_field(
            self.enc_cred_store_state.as_deref(),
            b"encCredStoreState",
            pin_token,
        )
    }

    /// Decrypt an encrypted Info field using HKDF-SHA256 + AES-256-CBC.
    fn decrypt_field(
        &self,
        encrypted: Option<&[u8]>,
        info_label: &[u8],
        pin_token: &[u8],
    ) -> Option<Vec<u8>> {
        let encrypted = encrypted?;
        if encrypted.len() < 16 {
            return None;
        }

        let salt = [0u8; 32];
        let hk = Hkdf::<Sha256>::new(Some(&salt), pin_token);
        let mut key = [0u8; 16];
        hk.expand(info_label, &mut key).ok()?;

        let (iv, ct) = encrypted.split_at(16);
        use aes::Aes128;
        use cbc::Decryptor as CbcDecryptor;
        use cipher::{BlockDecryptMut, KeyIvInit};
        let dec = CbcDecryptor::<Aes128>::new((&key).into(), iv.into());
        dec.decrypt_padded_vec_mut::<cipher::block_padding::NoPadding>(ct)
            .ok()
    }
}

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

    /// Build a minimal GetInfo CBOR map for testing.
    fn minimal_info_map() -> Value {
        Value::Map(vec![
            (
                Value::Int(0x01),
                Value::Array(vec![
                    Value::Text("FIDO_2_0".into()),
                    Value::Text("FIDO_2_1".into()),
                ]),
            ),
            (
                Value::Int(0x02),
                Value::Array(vec![Value::Text("hmac-secret".into())]),
            ),
            (Value::Int(0x03), Value::Bytes(vec![0xAA; 16])),
            (
                Value::Int(0x04),
                Value::Map(vec![
                    (Value::Text("rk".into()), Value::Bool(true)),
                    (Value::Text("up".into()), Value::Bool(true)),
                    (Value::Text("plat".into()), Value::Bool(false)),
                ]),
            ),
            (Value::Int(0x05), Value::Int(2048)),
            (
                Value::Int(0x06),
                Value::Array(vec![Value::Int(2), Value::Int(1)]),
            ),
            (Value::Int(0x07), Value::Int(8)),
            (Value::Int(0x08), Value::Int(128)),
            (
                Value::Int(0x0A),
                Value::Array(vec![Value::Map(vec![
                    (Value::Text("alg".into()), Value::Int(-7)),
                    (Value::Text("type".into()), Value::Text("public-key".into())),
                ])]),
            ),
            (Value::Int(0x0D), Value::Int(6)),
            (Value::Int(0x0E), Value::Int(328965)),
            (Value::Int(0x14), Value::Int(25)),
        ])
    }

    #[test]
    fn test_info_from_cbor_map() {
        let map = minimal_info_map();
        let entries = map.as_map().unwrap();
        let info = Info::from_cbor_map(entries);

        assert_eq!(info.versions, vec!["FIDO_2_0", "FIDO_2_1"]);
        assert_eq!(info.extensions, vec!["hmac-secret"]);
        assert_eq!(info.aaguid, Aaguid::new([0xAA; 16]));
        assert_eq!(info.options.get("rk"), Some(&true));
        assert_eq!(info.options.get("plat"), Some(&false));
        assert_eq!(info.max_msg_size, 2048);
        assert_eq!(info.pin_uv_protocols, vec![2, 1]);
        assert_eq!(info.max_creds_in_list, Some(8));
        assert_eq!(info.max_cred_id_length, Some(128));
        assert_eq!(info.algorithms.len(), 1);
        assert_eq!(info.algorithms[0].alg, -7);
        assert_eq!(
            info.algorithms[0].type_,
            crate::webauthn::PublicKeyCredentialType::PublicKey
        );
        assert_eq!(info.min_pin_length, 6);
        assert_eq!(info.firmware_version, Some(328965));
        assert_eq!(info.remaining_disc_creds, Some(25));
        // Defaults
        assert!(!info.force_pin_change);
        assert!(!info.long_touch_for_reset);
        assert_eq!(info.attestation_formats, vec!["packed"]);
    }

    #[test]
    fn test_info_defaults() {
        let info = Info::from_cbor_map(&[
            (
                Value::Int(0x01),
                Value::Array(vec![Value::Text("U2F_V2".into())]),
            ),
            (Value::Int(0x03), Value::Bytes(vec![0; 16])),
        ]);

        assert_eq!(info.versions, vec!["U2F_V2"]);
        assert_eq!(info.aaguid, Aaguid::NONE);
        assert_eq!(info.max_msg_size, 1024);
        assert_eq!(info.min_pin_length, 4);
        assert!(info.extensions.is_empty());
        assert!(info.options.is_empty());
        assert!(info.pin_uv_protocols.is_empty());
        assert_eq!(info.max_creds_in_list, None);
        assert_eq!(info.firmware_version, None);
    }

    #[test]
    fn test_aaguid_display() {
        let aaguid = Aaguid::new([
            0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54,
            0x32, 0x10,
        ]);
        assert_eq!(format!("{aaguid}"), "01234567-89ab-cdef-fedc-ba9876543210");
    }
}