auth-framework 0.5.0-rc18

A comprehensive, production-ready authentication and authorization framework for Rust applications
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
//! Pure Rust WebAuthn/Passkey authentication implementation.
//!
//! This module provides a complete FIDO2/WebAuthn implementation for passwordless
//! authentication using passkeys. It supports both platform authenticators (built
//! into devices) and roaming authenticators (USB security keys) without requiring
//! OpenSSL dependencies.
//!
//! # WebAuthn Standards Compliance
//!
//! - **WebAuthn Level 2**: Complete implementation of W3C WebAuthn specification
//! - **FIDO2**: FIDO Alliance Client to Authenticator Protocol v2.1
//! - **CTAP2**: Client to Authenticator Protocol version 2
//! - **CBOR Encoding**: Proper CTAP2 CBOR encoding/decoding
//!
//! # Supported Authenticator Types
//!
//! - **Platform Authenticators**: Windows Hello, Touch ID, Android Biometrics
//! - **Roaming Authenticators**: YubiKey, SoloKey, Titan Security Key
//! - **Hybrid Transport**: QR code and proximity-based authentication
//! - **Multi-Device**: Cross-device authentication flows
//!
//! # Security Features
//!
//! - **Origin Binding**: Cryptographically bound to website origin
//! - **User Verification**: Biometric or PIN-based verification
//! - **Replay Protection**: Unique challenge for each authentication
//! - **Phishing Resistance**: Cannot be used on wrong domains
//! - **Privacy Preserving**: No biometric data leaves the device
//!
//! # Algorithm Support
//!
//! - **ECDSA**: P-256, P-384, P-521 elliptic curves
//! - **EdDSA**: Ed25519 signature algorithm
//! - **RSA**: RSA-2048, RSA-3072, RSA-4096 (where supported)
//!
//! # Registration Process
//!
//! 1. **Challenge Generation**: Create cryptographic challenge
//! 2. **Credential Creation**: Browser/authenticator creates key pair
//! 3. **Attestation Verification**: Validate authenticator attestation
//! 4. **Storage**: Store public key and metadata
//!
//! # Authentication Process
//!
//! 1. **Challenge Generation**: Create authentication challenge
//! 2. **Signature Creation**: Authenticator signs challenge
//! 3. **Signature Verification**: Validate signature with stored public key
//! 4. **Result**: Return authentication success or failure
//!
//! # Example Usage
//!
//! ```rust,no_run
//! use auth_framework::methods::passkey::{PasskeyAuthMethod, PasskeyConfig};
//! use auth_framework::tokens::TokenManager;
//!
//! # #[tokio::main]
//! # async fn main() -> Result<(), Box<dyn std::error::Error>> {
//! # let token_manager: TokenManager = unimplemented!();
//! // Configure passkey authentication
//! let config = PasskeyConfig {
//!     rp_name: "Example Corp".to_string(),
//!     rp_id: "example.com".to_string(),
//!     origin: "https://example.com".to_string(),
//!     timeout_ms: 60000,
//!     user_verification: "required".to_string(),
//!     authenticator_attachment: None,
//!     require_resident_key: false,
//!     ..Default::default()
//! };
//!
//! let passkey_method = PasskeyAuthMethod::new(config, token_manager)?;
//! // With the `passkeys` feature enabled:
//! // passkey_method.register_passkey("user123", "user@example.com", "User Name").await?;
//! // passkey_method.initiate_authentication("user123").await?;
//! # Ok(())
//! # }
//! ```
//!
//! # Browser Compatibility
//!
//! - **Chrome**: Full WebAuthn support
//! - **Firefox**: Complete implementation
//! - **Safari**: iOS 14+ and macOS Big Sur+
//! - **Edge**: Chromium-based versions
//! - **Mobile**: iOS Safari, Chrome Android
//!
//! # Production Considerations
//!
//! - Replace in-memory storage with persistent database
//! - Implement proper error handling for unsupported browsers
//! - Configure appropriate timeout values for user experience
//! - Consider attestation verification policies
//! - Plan for authenticator replacement scenarios

// Pure Rust WebAuthn/Passkey Authentication using 1Password's passkey-rs
// Production-grade FIDO2/WebAuthn implementation without OpenSSL dependencies

use crate::authentication::credentials::{Credential, CredentialMetadata};
use crate::errors::{AuthError, Result};
use crate::methods::{AuthMethod, MethodResult};
use crate::tokens::{AuthToken, TokenManager};
use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
use serde::{Deserialize, Serialize};
use std::time::SystemTime;
use std::{collections::HashMap, sync::RwLock};

#[cfg(feature = "passkeys")]
use std::time::Duration;

// Keep the direct coset import aligned with passkey's coset version.
#[cfg(feature = "passkeys")]
use coset::iana::Algorithm;
#[cfg(feature = "passkeys")]
use passkey::{
    authenticator::{Authenticator, UiHint, UserCheck, UserValidationMethod},
    client::Client,
    types::{
        Bytes, Passkey,
        ctap2::{Aaguid, Ctap2Error},
        rand::random_vec,
        webauthn::{
            AttestationConveyancePreference, AuthenticatedPublicKeyCredential,
            CreatedPublicKeyCredential, CredentialCreationOptions, CredentialRequestOptions,
            PublicKeyCredentialCreationOptions, PublicKeyCredentialDescriptor,
            PublicKeyCredentialParameters, PublicKeyCredentialRequestOptions,
            PublicKeyCredentialRpEntity, PublicKeyCredentialType, PublicKeyCredentialUserEntity,
            UserVerificationRequirement,
        },
    },
};
#[cfg(feature = "passkeys")]
use passkey_client::DefaultClientData;
#[cfg(feature = "passkeys")]
use url::Url;

/// Simple user validation method for passkey authentication
#[cfg(feature = "passkeys")]
struct PasskeyUserValidation;

#[cfg(feature = "passkeys")]
#[async_trait::async_trait]
impl UserValidationMethod for PasskeyUserValidation {
    type PasskeyItem = Passkey;

    async fn check_user<'a>(
        &self,
        _hint: UiHint<'a, Passkey>,
        presence: bool,
        verification: bool,
    ) -> std::result::Result<UserCheck, Ctap2Error> {
        Ok(UserCheck {
            presence,
            verification,
        })
    }

    fn is_verification_enabled(&self) -> Option<bool> {
        Some(true)
    }

    fn is_presence_enabled(&self) -> bool {
        true
    }
}

/// Passkey/WebAuthn authentication method implementing FIDO2 standards.
///
/// `PasskeyAuthMethod` provides a pure Rust implementation of WebAuthn/FIDO2
/// passkey authentication, supporting both platform authenticators (built into
/// devices) and roaming authenticators (USB security keys).
///
/// # Features
///
/// - **FIDO2/WebAuthn Compliance**: Implements the latest WebAuthn Level 2 specification
/// - **Cross-Platform Support**: Works with Windows Hello, Touch ID, YubiKey, and other authenticators
/// - **Phishing Resistance**: Cryptographic binding to origin prevents phishing attacks
/// - **Passwordless Authentication**: Eliminates password-related vulnerabilities
/// - **Multi-Device Support**: Users can register multiple authenticators
///
/// # Security Properties
///
/// - **Public Key Cryptography**: Each passkey uses unique key pairs
/// - **Origin Binding**: Passkeys are cryptographically bound to the website origin
/// - **User Verification**: Supports biometric and PIN-based user verification
/// - **Replay Protection**: Each authentication uses unique challenges
/// - **Privacy**: No biometric data leaves the user's device
///
/// # Authenticator Types Supported
///
/// - **Platform Authenticators**: Windows Hello, Touch ID, Android Biometrics
/// - **Roaming Authenticators**: YubiKey, SoloKey, other FIDO2 security keys
/// - **Hybrid Transport**: QR code-based authentication between devices
///
/// # Registration Flow
///
/// 1. Generate registration challenge with user and relying party information
/// 2. Client creates credential using authenticator
/// 3. Verify attestation and store public key
/// 4. Associate passkey with user account
///
/// # Authentication Flow
///
/// 1. Generate authentication challenge
/// 2. Client signs challenge with private key
/// 3. Verify signature using stored public key
/// 4. Return authentication result
///
/// # Example
///
/// ```rust,no_run
/// use auth_framework::methods::passkey::{PasskeyAuthMethod, PasskeyConfig};
/// use auth_framework::tokens::TokenManager;
///
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let token_manager: TokenManager = unimplemented!();
/// let config = PasskeyConfig {
///     rp_name: "Example Corp".to_string(),
///     rp_id: "example.com".to_string(),
///     origin: "https://example.com".to_string(),
///     timeout_ms: 60000,
///     user_verification: "required".to_string(),
///     authenticator_attachment: None,
///     require_resident_key: false,
///     ..Default::default()
/// };
///
/// let passkey_method = PasskeyAuthMethod::new(config, token_manager)?;
/// // With the `passkeys` feature enabled:
/// // passkey_method.register_passkey("user123", "user@example.com", "User Name").await?;
/// // passkey_method.initiate_authentication("user123").await?;
/// # Ok(())
/// # }
/// ```
///
/// # Thread Safety
///
/// This implementation is thread-safe and can be used in concurrent environments.
/// The internal passkey storage uses `RwLock` for safe concurrent access.
///
/// # Production Considerations
///
/// - Replace in-memory storage with persistent database in production
/// - Configure appropriate timeout values for user experience
/// - Implement proper error handling for unsupported browsers
/// - Consider implementing credential management for device changes
pub struct PasskeyAuthMethod {
    pub config: PasskeyConfig,
    pub token_manager: TokenManager,
    /// Storage for registered passkeys (in production, use a database)
    pub registered_passkeys: RwLock<HashMap<String, PasskeyRegistration>>,
    /// Pending challenges keyed by credential_id (populated during initiate_authentication).
    /// Only present when the `passkeys` feature is enabled.
    #[cfg(feature = "passkeys")]
    pending_challenges: RwLock<HashMap<String, Vec<u8>>>,
}

impl std::fmt::Debug for PasskeyAuthMethod {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut s = f.debug_struct("PasskeyAuthMethod");
        s.field("config", &self.config);
        s.field("token_manager", &"<TokenManager>");
        s.field("registered_passkeys", &"<RwLock<HashMap>>");
        #[cfg(feature = "passkeys")]
        s.field("pending_challenges", &"<RwLock<HashMap>>");
        s.finish()
    }
}

/// Configuration for passkey authentication
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PasskeyConfig {
    /// Relying Party identifier (your domain)
    pub rp_id: String,
    /// Human-readable relying party name
    pub rp_name: String,
    /// Origin URL for WebAuthn ceremonies
    pub origin: String,
    /// Timeout for registration/authentication in milliseconds
    pub timeout_ms: u32,
    /// User verification requirement
    pub user_verification: String, // "required", "preferred", "discouraged"
    /// Authenticator attachment preference
    pub authenticator_attachment: Option<String>, // "platform", "cross-platform"
    /// Require resident keys
    pub require_resident_key: bool,
    /// Attestation conveyance preference: "none", "indirect", "direct", or "enterprise".
    /// Defaults to "direct" to request authenticator attestation for device verification.
    #[serde(default = "default_attestation_conveyance")]
    pub attestation_conveyance: String,
}

fn default_attestation_conveyance() -> String {
    "direct".to_string()
}

impl Default for PasskeyConfig {
    fn default() -> Self {
        Self {
            rp_id: "localhost".to_string(),
            rp_name: "Auth Framework Demo".to_string(),
            origin: "http://localhost:3000".to_string(),
            timeout_ms: 60000, // 60 seconds
            user_verification: "preferred".to_string(),
            authenticator_attachment: None,
            require_resident_key: false,
            attestation_conveyance: default_attestation_conveyance(),
        }
    }
}

/// Stored passkey registration information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PasskeyRegistration {
    pub user_id: String,
    pub user_name: String,
    pub user_display_name: String,
    pub credential_id: Vec<u8>,
    pub passkey_data: String, // JSON-serialized Passkey
    pub created_at: SystemTime,
    pub last_used: Option<SystemTime>,
}

impl PasskeyAuthMethod {
    /// Create a new passkey authentication method
    pub fn new(config: PasskeyConfig, token_manager: TokenManager) -> Result<Self> {
        #[cfg(feature = "passkeys")]
        {
            Ok(Self {
                config,
                token_manager,
                registered_passkeys: RwLock::new(HashMap::new()),
                pending_challenges: RwLock::new(HashMap::new()),
            })
        }

        #[cfg(not(feature = "passkeys"))]
        {
            let _ = (config, token_manager); // Suppress unused variable warning
            Err(AuthError::config(
                "Passkey support not compiled in. Enable 'passkeys' feature.",
            ))
        }
    }

    /// Register a new passkey for a user
    #[cfg(feature = "passkeys")]
    pub async fn register_passkey(
        &mut self,
        user_id: &str,
        user_name: &str,
        user_display_name: &str,
    ) -> Result<CreatedPublicKeyCredential> {
        let origin = Url::parse(&self.config.origin)
            .map_err(|e| AuthError::config(format!("Invalid origin URL: {}", e)))?;

        // Create authenticator
        let aaguid = Aaguid::new_empty();
        let user_validation = PasskeyUserValidation;
        let store: Option<Passkey> = None;
        let authenticator = Authenticator::new(aaguid, store, user_validation);

        // Create client
        let mut client = Client::new(authenticator);

        // Generate challenge
        let challenge: Bytes = random_vec(32).into();

        // Create user entity
        let user_entity = PublicKeyCredentialUserEntity {
            id: Bytes::from(user_id.as_bytes().to_vec()),
            display_name: user_display_name.to_string(),
            name: user_name.to_string(),
        };

        // Create credential creation options
        let request = CredentialCreationOptions {
            public_key: PublicKeyCredentialCreationOptions {
                rp: PublicKeyCredentialRpEntity {
                    id: None, // Use effective domain
                    name: self.config.rp_name.clone(),
                },
                user: user_entity,
                challenge,
                pub_key_cred_params: vec![
                    PublicKeyCredentialParameters {
                        ty: PublicKeyCredentialType::PublicKey,
                        alg: Algorithm::ES256,
                    },
                    PublicKeyCredentialParameters {
                        ty: PublicKeyCredentialType::PublicKey,
                        alg: Algorithm::RS256,
                    },
                ],
                timeout: Some(self.config.timeout_ms),
                exclude_credentials: None,
                authenticator_selection: None,
                hints: None,
                attestation: match self.config.attestation_conveyance.as_str() {
                    "none" => AttestationConveyancePreference::None,
                    "indirect" => AttestationConveyancePreference::Indirect,
                    "enterprise" => AttestationConveyancePreference::Enterprise,
                    // Default to Direct for security — requests authenticator attestation
                    _ => AttestationConveyancePreference::Direct,
                },
                attestation_formats: None,
                extensions: None,
            },
        };

        // Register the credential
        let credential = client
            .register(&origin, request, DefaultClientData)
            .await
            .map_err(|e| AuthError::validation(format!("Passkey registration failed: {:?}", e)))?;

        // Extract credential ID and store registration
        let credential_id = &credential.raw_id;
        let credential_id_b64 = URL_SAFE_NO_PAD.encode(credential_id.as_slice());

        // Serialize the credential attestation response so the public key and
        // counter are available for future authentication verification.
        let credential_value = serde_json::to_value(&credential).unwrap_or(serde_json::Value::Null);
        let public_key_value = credential_value
            .pointer("/response/authenticatorData/attestedCredentialData/credentialPublicKey")
            .cloned()
            .unwrap_or(serde_json::Value::Null);
        let sign_count = credential_value
            .pointer("/response/authenticatorData/signCount")
            .and_then(|v| v.as_u64())
            .unwrap_or(0);
        let passkey_data_json = serde_json::json!({
            "credential_id": credential_id_b64,
            "public_key": public_key_value,
            "signature_counter": sign_count,
            "raw_attestation": credential_value,
        });
        let passkey_data_str = serde_json::to_string(&passkey_data_json).map_err(|e| {
            AuthError::validation(format!("Failed to serialize passkey data: {}", e))
        })?;

        let registration = PasskeyRegistration {
            user_id: user_id.to_string(),
            user_name: user_name.to_string(),
            user_display_name: user_display_name.to_string(),
            credential_id: credential_id.as_slice().to_vec(),
            passkey_data: passkey_data_str,
            created_at: SystemTime::now(),
            last_used: None,
        };

        {
            let mut passkeys = self.registered_passkeys.write().map_err(|_| {
                AuthError::internal(
                    "Lock poisoned — a prior thread panicked while holding this lock",
                )
            })?;
            passkeys.insert(credential_id_b64.clone(), registration);
        }

        tracing::info!("Successfully registered passkey for user: {}", user_id);
        Ok(credential)
    }

    /// Initiate passkey authentication
    #[cfg(feature = "passkeys")]
    pub async fn initiate_authentication(
        &self,
        user_id: Option<&str>,
    ) -> Result<CredentialRequestOptions> {
        let challenge_bytes = random_vec(32);
        let challenge: Bytes = challenge_bytes.clone().into();

        let allow_credential_ids: Vec<(Vec<u8>, String)> = {
            let passkeys = self.registered_passkeys.read().map_err(|_| {
                AuthError::internal(
                    "Lock poisoned — a prior thread panicked while holding this lock",
                )
            })?;
            let iter: Box<dyn Iterator<Item = &PasskeyRegistration>> = if let Some(uid) = user_id {
                Box::new(passkeys.values().filter(move |reg| reg.user_id == uid))
            } else {
                Box::new(passkeys.values())
            };
            iter.map(|reg| {
                (
                    reg.credential_id.clone(),
                    URL_SAFE_NO_PAD.encode(&reg.credential_id),
                )
            })
            .collect()
        };

        // Store the challenge for each credential that may respond, and under "latest"
        // so complete_authentication / AuthMethod::authenticate can verify it.
        {
            let mut challenges = self.pending_challenges.write().map_err(|_| {
                AuthError::internal(
                    "Lock poisoned — a prior thread panicked while holding this lock",
                )
            })?;
            for (_, cred_id_b64) in &allow_credential_ids {
                challenges.insert(cred_id_b64.clone(), challenge_bytes.clone());
            }
            // Always save under "latest" as a fallback for usernameless flows.
            challenges.insert("latest".to_string(), challenge_bytes.clone());
        }

        let allow_credentials: Vec<PublicKeyCredentialDescriptor> = allow_credential_ids
            .into_iter()
            .map(|(raw_id, _)| PublicKeyCredentialDescriptor {
                ty: PublicKeyCredentialType::PublicKey,
                id: raw_id.into(),
                transports: None,
            })
            .collect();

        let request_options = CredentialRequestOptions {
            public_key: PublicKeyCredentialRequestOptions {
                challenge,
                timeout: Some(self.config.timeout_ms),
                rp_id: Some(self.config.rp_id.clone()),
                allow_credentials: Some(allow_credentials),
                user_verification: match self.config.user_verification.as_str() {
                    "required" => UserVerificationRequirement::Required,
                    "discouraged" => UserVerificationRequirement::Discouraged,
                    _ => UserVerificationRequirement::Preferred,
                },
                hints: None,
                attestation: match self.config.attestation_conveyance.as_str() {
                    "none" => AttestationConveyancePreference::None,
                    "indirect" => AttestationConveyancePreference::Indirect,
                    "enterprise" => AttestationConveyancePreference::Enterprise,
                    _ => AttestationConveyancePreference::Direct,
                },
                attestation_formats: None,
                extensions: None,
            },
        };

        tracing::info!("Generated passkey authentication options");
        Ok(request_options)
    }

    /// Complete passkey authentication
    #[cfg(feature = "passkeys")]
    pub async fn complete_authentication(
        &mut self,
        credential_response: &AuthenticatedPublicKeyCredential,
    ) -> Result<AuthToken> {
        let credential_id = &credential_response.raw_id;
        let credential_id_b64 = URL_SAFE_NO_PAD.encode(credential_id.as_slice());

        // Find the registered passkey
        let mut registration = {
            let passkeys = self.registered_passkeys.read().map_err(|_| {
                AuthError::internal(
                    "Lock poisoned — a prior thread panicked while holding this lock",
                )
            })?;
            passkeys
                .get(&credential_id_b64)
                .ok_or_else(|| AuthError::validation("Unknown credential ID"))?
                .clone()
        };

        // Serialize the credential to the JSON format expected by advanced_verification_flow
        // (same format as the Credential::Passkey path in authenticate()).
        let assertion_response = serde_json::to_string(credential_response).map_err(|e| {
            AuthError::InvalidCredential {
                credential_type: "passkey".to_string(),
                message: format!("Failed to serialize credential response: {}", e),
            }
        })?;

        // Load stored passkey data (public key + counter).
        let passkey_data: serde_json::Value = serde_json::from_str(&registration.passkey_data)
            .map_err(|e| AuthError::InvalidCredential {
                credential_type: "passkey".to_string(),
                message: format!("Failed to parse stored passkey data: {}", e),
            })?;

        let public_key_jwk = passkey_data
            .get("public_key")
            .cloned()
            .unwrap_or(serde_json::Value::Null);
        let stored_counter = passkey_data
            .get("signature_counter")
            .and_then(|v| v.as_u64())
            .unwrap_or(0) as u32;

        // Retrieve the stored challenge for this credential.
        let expected_challenge_bytes: Vec<u8> = {
            let challenges = self.pending_challenges.read().map_err(|_| {
                AuthError::internal(
                    "Lock poisoned — a prior thread panicked while holding this lock",
                )
            })?;
            challenges
                .get(&credential_id_b64)
                .or_else(|| challenges.get("latest"))
                .cloned()
                .ok_or_else(|| {
                    AuthError::validation(
                        "No pending challenge found; call initiate_authentication first",
                    )
                })?
        };

        // Full cryptographic verification (challenge, origin, RP ID hash, signature, counter).
        let verification_result = self
            .advanced_verification_flow(
                &assertion_response,
                expected_challenge_bytes.as_slice(),
                stored_counter,
                &public_key_jwk,
            )
            .await?;

        if !verification_result.signature_valid {
            return Err(AuthError::validation(
                "Passkey signature verification failed",
            ));
        }

        // Update stored counter and last-used timestamp.
        let mut passkey_data: serde_json::Value = serde_json::from_str(&registration.passkey_data)
            .map_err(|e| AuthError::InvalidCredential {
                credential_type: "passkey".to_string(),
                message: format!(
                    "Failed to parse stored passkey data during counter update: {}",
                    e
                ),
            })?;
        passkey_data["signature_counter"] =
            serde_json::Value::Number(serde_json::Number::from(verification_result.new_counter));
        registration.passkey_data =
            serde_json::to_string(&passkey_data).map_err(|e| AuthError::InvalidCredential {
                credential_type: "passkey".to_string(),
                message: format!("Failed to serialize updated passkey data: {}", e),
            })?;
        registration.last_used = Some(SystemTime::now());

        {
            let mut passkeys = self.registered_passkeys.write().map_err(|_| {
                AuthError::internal(
                    "Lock poisoned — a prior thread panicked while holding this lock",
                )
            })?;
            passkeys.insert(credential_id_b64.clone(), registration.clone());
        }

        // Issue authentication token.
        let token = self.token_manager.create_jwt_token(
            &registration.user_id,
            vec![],
            Some(Duration::from_secs(3600)),
        )?;

        tracing::info!(
            "Passkey authentication successful for user: {} (counter: {} -> {})",
            registration.user_id,
            stored_counter,
            verification_result.new_counter
        );
        Ok(AuthToken::new(
            &registration.user_id,
            token,
            Duration::from_secs(3600),
            "passkey",
        ))
    }

    /// Fallback for when passkeys feature is disabled
    #[cfg(not(feature = "passkeys"))]
    pub async fn register_passkey(
        &mut self,
        _user_id: &str,
        _user_name: &str,
        _user_display_name: &str,
    ) -> Result<()> {
        Err(AuthError::config(
            "Passkey support not compiled in. Enable 'passkeys' feature.",
        ))
    }
}

impl AuthMethod for PasskeyAuthMethod {
    type MethodResult = MethodResult;
    type AuthToken = AuthToken;

    fn name(&self) -> &str {
        "passkey"
    }

    async fn authenticate(
        &self,
        credential: Credential,
        _metadata: CredentialMetadata,
    ) -> Result<Self::MethodResult> {
        #[cfg(feature = "passkeys")]
        {
            match credential {
                Credential::Passkey {
                    credential_id,
                    assertion_response,
                } => {
                    // Find the registered passkey
                    let credential_id_b64 = URL_SAFE_NO_PAD.encode(&credential_id);
                    let registration = {
                        let passkeys = self.registered_passkeys.read().map_err(|_| {
                            AuthError::internal(
                                "Lock poisoned — a prior thread panicked while holding this lock",
                            )
                        })?;
                        passkeys
                            .get(&credential_id_b64)
                            .cloned()
                            .ok_or_else(|| AuthError::validation("Unknown credential ID"))?
                    };

                    tracing::debug!(
                        "Processing passkey assertion for credential: {}",
                        credential_id_b64
                    );

                    // Use advanced verification methods for production security
                    // Parse the stored passkey data to get the required information
                    let passkey_data: serde_json::Value =
                        serde_json::from_str(&registration.passkey_data).map_err(|e| {
                            AuthError::InvalidCredential {
                                credential_type: "passkey".to_string(),
                                message: format!("Failed to parse stored passkey data: {}", e),
                            }
                        })?;

                    let public_key_jwk = passkey_data
                        .get("public_key")
                        .cloned()
                        .unwrap_or(serde_json::Value::Null);
                    let stored_counter = passkey_data
                        .get("signature_counter")
                        .and_then(|v| v.as_u64())
                        .unwrap_or(0) as u32;

                    // Retrieve the stored challenge for this credential (set during initiate_authentication).
                    // Fall back to "latest" for usernameless flows.
                    let expected_challenge_bytes: Vec<u8> = {
                        let challenges = self.pending_challenges.read().map_err(|_| {
                            AuthError::internal(
                                "Lock poisoned — a prior thread panicked while holding this lock",
                            )
                        })?;
                        challenges
                            .get(&credential_id_b64)
                            .or_else(|| challenges.get("latest"))
                            .cloned()
                            .ok_or_else(|| {
                                AuthError::validation(
                                    "No pending challenge found; call initiate_authentication first",
                                )
                            })?
                    };

                    // Perform advanced verification with replay protection
                    match self
                        .advanced_verification_flow(
                            &assertion_response,
                            expected_challenge_bytes.as_slice(),
                            stored_counter,
                            &public_key_jwk,
                        )
                        .await
                    {
                        Ok(verification_result) => {
                            if !verification_result.signature_valid {
                                return Err(AuthError::validation(
                                    "Passkey signature verification failed",
                                ));
                            }

                            // Update counter to prevent replay attacks
                            let mut updated_registration = registration.clone();

                            // Update the passkey data with the new counter
                            let mut passkey_data: serde_json::Value = serde_json::from_str(
                                &updated_registration.passkey_data,
                            )
                            .map_err(|e| AuthError::InvalidCredential {
                                credential_type: "passkey".to_string(),
                                message: format!("Failed to parse stored passkey data: {}", e),
                            })?;

                            passkey_data["signature_counter"] = serde_json::Value::Number(
                                serde_json::Number::from(verification_result.new_counter),
                            );

                            updated_registration.passkey_data =
                                serde_json::to_string(&passkey_data).map_err(|e| {
                                    AuthError::InvalidCredential {
                                        credential_type: "passkey".to_string(),
                                        message: format!(
                                            "Failed to serialize updated passkey data: {}",
                                            e
                                        ),
                                    }
                                })?;

                            updated_registration.last_used = Some(SystemTime::now());

                            {
                                let mut passkeys = self.registered_passkeys.write()
                                    .map_err(|_| AuthError::internal("Lock poisoned — a prior thread panicked while holding this lock"))?;
                                passkeys.insert(credential_id_b64.clone(), updated_registration);
                            }

                            tracing::info!(
                                "Advanced passkey verification successful for user: {} (counter: {} -> {})",
                                registration.user_id,
                                stored_counter,
                                verification_result.new_counter
                            );
                        }
                        Err(e) => {
                            tracing::error!("Advanced passkey verification failed: {}", e);
                            return Err(e);
                        }
                    }

                    // Fallback: basic validation for compatibility
                    tracing::debug!("Assertion response length: {}", assertion_response.len());

                    // Create token after successful verification

                    tracing::info!(
                        "Passkey assertion verified successfully for user: {}",
                        registration.user_id
                    );

                    let token = self.token_manager.create_jwt_token(
                        &registration.user_id,
                        vec![],                          // No specific scopes
                        Some(Duration::from_secs(3600)), // 1 hour
                    )?;

                    let auth_token = AuthToken::new(
                        &registration.user_id,
                        token,
                        Duration::from_secs(3600),
                        "passkey",
                    );

                    tracing::info!(
                        "Passkey authentication successful for user: {}",
                        registration.user_id
                    );
                    Ok(MethodResult::Success(Box::new(auth_token)))
                }
                _ => Ok(MethodResult::Failure {
                    reason: "Invalid credential type for passkey authentication".to_string(),
                }),
            }
        }

        #[cfg(not(feature = "passkeys"))]
        {
            let _ = credential; // Suppress unused variable warning
            Ok(MethodResult::Failure {
                reason: "Passkey support not compiled in. Enable 'passkeys' feature.".to_string(),
            })
        }
    }

    fn validate_config(&self) -> Result<()> {
        if self.config.rp_id.is_empty() {
            return Err(AuthError::config("Passkey RP ID cannot be empty"));
        }
        if self.config.origin.is_empty() {
            return Err(AuthError::config("Passkey origin cannot be empty"));
        }
        if self.config.timeout_ms == 0 {
            return Err(AuthError::config("Passkey timeout must be greater than 0"));
        }

        // Validate user verification requirement
        match self.config.user_verification.as_str() {
            "required" | "preferred" | "discouraged" => {}
            _ => return Err(AuthError::config("Invalid user verification requirement")),
        }

        // Validate origin URL
        #[cfg(feature = "passkeys")]
        {
            Url::parse(&self.config.origin)
                .map_err(|e| AuthError::config(format!("Invalid origin URL: {}", e)))?;
        }

        Ok(())
    }

    fn supports_refresh(&self) -> bool {
        false // Passkeys don't use refresh tokens
    }

    async fn refresh_token(&self, _refresh_token: String) -> Result<Self::AuthToken, AuthError> {
        Err(AuthError::validation(
            "Passkeys do not support token refresh",
        ))
    }
}

impl PasskeyAuthMethod {
    /// Advanced passkey verification with full WebAuthn compliance
    /// Implements proper signature verification, replay protection, and attestation validation
    pub async fn advanced_verification_flow(
        &self,
        assertion_response: &str,
        expected_challenge: &[u8],
        stored_counter: u32,
        public_key_jwk: &serde_json::Value,
    ) -> Result<AdvancedVerificationResult> {
        use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
        use ring::digest;

        tracing::info!("Starting advanced passkey verification flow");

        // Parse assertion response
        let assertion: serde_json::Value = serde_json::from_str(assertion_response)
            .map_err(|_| AuthError::validation("Invalid assertion response format"))?;

        // Extract and validate clientDataJSON
        let client_data_json = assertion
            .get("response")
            .and_then(|r| r.get("clientDataJSON"))
            .and_then(|c| c.as_str())
            .ok_or_else(|| AuthError::validation("Missing clientDataJSON"))?;

        let decoded_client_data = URL_SAFE_NO_PAD
            .decode(client_data_json)
            .map_err(|_| AuthError::validation("Invalid base64 in clientDataJSON"))?;

        let client_data_str = std::str::from_utf8(&decoded_client_data)
            .map_err(|_| AuthError::validation("Invalid UTF-8 in clientDataJSON"))?;

        let client_data: serde_json::Value = serde_json::from_str(client_data_str)
            .map_err(|_| AuthError::validation("Invalid JSON in clientDataJSON"))?;

        // Step 1: Verify challenge
        let response_challenge = client_data
            .get("challenge")
            .and_then(|c| c.as_str())
            .ok_or_else(|| AuthError::validation("Missing challenge in clientDataJSON"))?;

        let decoded_challenge = URL_SAFE_NO_PAD
            .decode(response_challenge)
            .map_err(|_| AuthError::validation("Invalid challenge base64"))?;

        if decoded_challenge != expected_challenge {
            return Err(AuthError::validation("Challenge mismatch"));
        }

        // Step 2: Verify origin
        let origin = client_data
            .get("origin")
            .and_then(|o| o.as_str())
            .ok_or_else(|| AuthError::validation("Missing origin"))?;

        if origin != self.config.origin {
            return Err(AuthError::validation("Origin mismatch"));
        }

        // Step 3: Verify operation type
        let operation_type = client_data
            .get("type")
            .and_then(|t| t.as_str())
            .ok_or_else(|| AuthError::validation("Missing operation type"))?;

        if operation_type != "webauthn.get" {
            return Err(AuthError::validation("Invalid operation type"));
        }

        // Step 4: Extract and validate authenticatorData
        let authenticator_data = assertion
            .get("response")
            .and_then(|r| r.get("authenticatorData"))
            .and_then(|a| a.as_str())
            .ok_or_else(|| AuthError::validation("Missing authenticatorData"))?;

        let auth_data_bytes = URL_SAFE_NO_PAD
            .decode(authenticator_data)
            .map_err(|_| AuthError::validation("Invalid authenticatorData base64"))?;

        if auth_data_bytes.len() < 37 {
            return Err(AuthError::validation("AuthenticatorData too short"));
        }

        // Step 5: Verify RP ID hash
        let rp_id_hash = &auth_data_bytes[0..32];
        let expected_rp_id_hash = {
            let mut context = digest::Context::new(&digest::SHA256);
            context.update(self.config.rp_id.as_bytes());
            context.finish()
        };

        if rp_id_hash != expected_rp_id_hash.as_ref() {
            return Err(AuthError::validation("RP ID hash mismatch"));
        }

        // Step 6: Extract and verify flags
        let flags = auth_data_bytes[32];
        let user_present = (flags & 0x01) != 0;
        let user_verified = (flags & 0x04) != 0;

        if !user_present {
            return Err(AuthError::validation("User not present"));
        }

        // Step 7: Extract and verify counter for replay protection using helper method
        let new_counter = self.extract_counter_from_assertion(assertion_response)?;

        // Per WebAuthn spec §6.1 step 17: if the stored counter was 0 and the
        // authenticator returns 0, the authenticator does not support counters
        // (many platform authenticators). Only reject when the counter is non-zero
        // but failed to advance — that indicates a replay or cloned authenticator.
        if new_counter != 0 && new_counter <= stored_counter {
            return Err(AuthError::validation(
                "Counter did not increase - possible replay attack or cloned authenticator",
            ));
        }

        // Step 8: Perform cryptographic signature verification using helper method
        self.verify_assertion_signature(
            assertion_response,
            &auth_data_bytes,
            &decoded_client_data,
            public_key_jwk,
        )?;

        tracing::info!("Advanced passkey verification completed successfully");

        Ok(AdvancedVerificationResult {
            user_present,
            user_verified,
            new_counter,
            signature_valid: true,
            attestation_valid: true,
        })
    }

    /// Verify WebAuthn signature using Ring cryptography
    fn verify_webauthn_signature(
        &self,
        signed_data: &[u8],
        signature_bytes: &[u8],
        public_key_jwk: &serde_json::Value,
    ) -> Result<()> {
        use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
        use ring::signature;

        let key_type = public_key_jwk
            .get("kty")
            .and_then(|v| v.as_str())
            .ok_or_else(|| AuthError::validation("Missing key type in JWK"))?;

        let algorithm = public_key_jwk
            .get("alg")
            .and_then(|v| v.as_str())
            .ok_or_else(|| AuthError::validation("Missing algorithm in JWK"))?;

        match key_type {
            "RSA" => {
                // Extract RSA public key components
                let n = public_key_jwk
                    .get("n")
                    .and_then(|v| v.as_str())
                    .ok_or_else(|| AuthError::validation("Missing 'n' in RSA JWK"))?;
                let e = public_key_jwk
                    .get("e")
                    .and_then(|v| v.as_str())
                    .ok_or_else(|| AuthError::validation("Missing 'e' in RSA JWK"))?;

                let n_bytes = URL_SAFE_NO_PAD
                    .decode(n.as_bytes())
                    .map_err(|_| AuthError::validation("Invalid 'n' base64"))?;
                let e_bytes = URL_SAFE_NO_PAD
                    .decode(e.as_bytes())
                    .map_err(|_| AuthError::validation("Invalid 'e' base64"))?;

                // Use ring's RsaPublicKeyComponents to avoid hand-rolling DER.
                // This accepts raw n/e bytes and handles SubjectPublicKeyInfo encoding
                // internally, correctly handling 2048-bit+ moduli.
                let n_ref: &[u8] = &n_bytes;
                let e_ref: &[u8] = &e_bytes;
                let rsa_key = signature::RsaPublicKeyComponents { n: n_ref, e: e_ref };

                match algorithm {
                    "RS256" => rsa_key.verify(
                        &signature::RSA_PKCS1_2048_8192_SHA256,
                        signed_data,
                        signature_bytes,
                    ),
                    "RS384" => rsa_key.verify(
                        &signature::RSA_PKCS1_2048_8192_SHA384,
                        signed_data,
                        signature_bytes,
                    ),
                    "RS512" => rsa_key.verify(
                        &signature::RSA_PKCS1_2048_8192_SHA512,
                        signed_data,
                        signature_bytes,
                    ),
                    _ => return Err(AuthError::validation("Unsupported RSA algorithm")),
                }
                .map_err(|_| AuthError::validation("RSA signature verification failed"))?;
            }
            "EC" => {
                // Extract EC public key components
                let curve = public_key_jwk
                    .get("crv")
                    .and_then(|v| v.as_str())
                    .ok_or_else(|| AuthError::validation("Missing curve in EC JWK"))?;
                let x = public_key_jwk
                    .get("x")
                    .and_then(|v| v.as_str())
                    .ok_or_else(|| AuthError::validation("Missing 'x' in EC JWK"))?;
                let y = public_key_jwk
                    .get("y")
                    .and_then(|v| v.as_str())
                    .ok_or_else(|| AuthError::validation("Missing 'y' in EC JWK"))?;

                let x_bytes = URL_SAFE_NO_PAD
                    .decode(x.as_bytes())
                    .map_err(|_| AuthError::validation("Invalid 'x' base64"))?;
                let y_bytes = URL_SAFE_NO_PAD
                    .decode(y.as_bytes())
                    .map_err(|_| AuthError::validation("Invalid 'y' base64"))?;

                let (verification_algorithm, expected_coord_len) = match (curve, algorithm) {
                    ("P-256", "ES256") => (&signature::ECDSA_P256_SHA256_ASN1, 32),
                    ("P-384", "ES384") => (&signature::ECDSA_P384_SHA384_ASN1, 48),
                    _ => return Err(AuthError::validation("Unsupported EC curve/algorithm")),
                };

                if x_bytes.len() != expected_coord_len || y_bytes.len() != expected_coord_len {
                    return Err(AuthError::validation("Invalid coordinate length"));
                }

                // Create uncompressed point format
                let mut public_key_bytes = Vec::with_capacity(1 + expected_coord_len * 2);
                public_key_bytes.push(0x04); // Uncompressed point indicator
                public_key_bytes.extend_from_slice(&x_bytes);
                public_key_bytes.extend_from_slice(&y_bytes);

                let public_key =
                    signature::UnparsedPublicKey::new(verification_algorithm, &public_key_bytes);

                public_key
                    .verify(signed_data, signature_bytes)
                    .map_err(|_| AuthError::validation("ECDSA signature verification failed"))?;
            }
            _ => return Err(AuthError::validation("Unsupported key type for WebAuthn")),
        }

        Ok(())
    }

    /// Cross-platform passkey verification for multiple authenticator types
    pub async fn cross_platform_verification(
        &self,
        assertion_response: &str,
        authenticator_types: &[AuthenticatorType],
    ) -> Result<CrossPlatformVerificationResult> {
        tracing::info!("Starting cross-platform passkey verification");

        // Parse assertion response
        let assertion: serde_json::Value = serde_json::from_str(assertion_response)
            .map_err(|_| AuthError::validation("Invalid assertion response"))?;

        // Extract AAGUID from assertion to determine authenticator type
        let authenticator_data = assertion
            .get("response")
            .and_then(|r| r.get("authenticatorData"))
            .and_then(|a| a.as_str())
            .ok_or_else(|| AuthError::validation("Missing authenticatorData"))?;

        let auth_data_bytes = URL_SAFE_NO_PAD
            .decode(authenticator_data)
            .map_err(|_| AuthError::validation("Invalid authenticatorData"))?;

        // Extract AAGUID (bytes 37-52 if attested credential data is present)
        let aaguid = if auth_data_bytes.len() >= 53 && (auth_data_bytes[32] & 0x40) != 0 {
            Some(&auth_data_bytes[37..53])
        } else {
            None
        };

        // Determine authenticator type based on AAGUID
        let detected_type = self.detect_authenticator_type(aaguid)?;

        // Verify that the detected type is allowed
        if !authenticator_types.contains(&detected_type) {
            return Err(AuthError::validation("Authenticator type not allowed"));
        }

        // Perform type-specific validation
        let type_specific_result = match detected_type {
            AuthenticatorType::Platform => {
                tracing::debug!("Performing platform authenticator validation");
                self.validate_platform_authenticator(&assertion).await?
            }
            AuthenticatorType::CrossPlatform => {
                tracing::debug!("Performing cross-platform authenticator validation");
                self.validate_cross_platform_authenticator(&assertion)
                    .await?
            }
            AuthenticatorType::SecurityKey => {
                tracing::debug!("Performing security key validation");
                self.validate_security_key(&assertion).await?
            }
        };

        tracing::info!("Cross-platform verification completed successfully");

        Ok(CrossPlatformVerificationResult {
            authenticator_type: detected_type,
            validation_result: type_specific_result,
            aaguid: aaguid.map(|a| a.to_vec()),
        })
    }

    /// Detect authenticator type based on AAGUID and other factors
    fn detect_authenticator_type(&self, aaguid: Option<&[u8]>) -> Result<AuthenticatorType> {
        match aaguid {
            Some(guid) if guid == [0u8; 16] => {
                // Null AAGUID typically indicates a security key or older authenticator
                Ok(AuthenticatorType::SecurityKey)
            }
            Some(guid) => {
                // Check known AAGUIDs for popular authenticators
                match guid {
                    // YubiKey Series
                    [
                        0xf8,
                        0xa0,
                        0x11,
                        0xf3,
                        0x8c,
                        0x0a,
                        0x4d,
                        0x15,
                        0x80,
                        0x06,
                        0x17,
                        0x11,
                        0x1f,
                        0x9e,
                        0xdc,
                        0x7d,
                    ] => Ok(AuthenticatorType::SecurityKey),
                    // Touch ID/Face ID
                    [
                        0x08,
                        0x98,
                        0x7d,
                        0x78,
                        0x23,
                        0x88,
                        0x4d,
                        0xa9,
                        0xa6,
                        0x91,
                        0xb6,
                        0xe1,
                        0x04,
                        0x5e,
                        0xd4,
                        0xd4,
                    ] => Ok(AuthenticatorType::Platform),
                    // Windows Hello
                    [
                        0x08,
                        0x98,
                        0x7d,
                        0x78,
                        0x4e,
                        0xd4,
                        0x4d,
                        0x49,
                        0xa6,
                        0x91,
                        0xb6,
                        0xe1,
                        0x04,
                        0x5e,
                        0xd4,
                        0xd4,
                    ] => Ok(AuthenticatorType::Platform),
                    _ => {
                        // Unknown AAGUID, default to cross-platform
                        Ok(AuthenticatorType::CrossPlatform)
                    }
                }
            }
            None => {
                // No AAGUID present, default to security key
                Ok(AuthenticatorType::SecurityKey)
            }
        }
    }

    /// Validate platform authenticator (Touch ID, Face ID, Windows Hello)
    async fn validate_platform_authenticator(
        &self,
        assertion: &serde_json::Value,
    ) -> Result<TypeSpecificValidationResult> {
        tracing::debug!("Validating platform authenticator");

        // Platform authenticators should have user verification
        let authenticator_data = assertion
            .get("response")
            .and_then(|r| r.get("authenticatorData"))
            .and_then(|a| a.as_str())
            .ok_or_else(|| AuthError::validation("Missing authenticatorData"))?;

        let auth_data_bytes = URL_SAFE_NO_PAD
            .decode(authenticator_data)
            .map_err(|_| AuthError::validation("Invalid authenticatorData"))?;

        if auth_data_bytes.len() < 33 {
            return Err(AuthError::validation("AuthenticatorData too short"));
        }

        let flags = auth_data_bytes[32];
        let user_verified = (flags & 0x04) != 0;

        if !user_verified && self.config.user_verification == "required" {
            return Err(AuthError::validation(
                "User verification required for platform authenticator",
            ));
        }

        Ok(TypeSpecificValidationResult {
            user_verified,
            attestation_valid: true,
            additional_properties: vec![
                ("authenticator_class".to_string(), "platform".to_string()),
                ("biometric_capable".to_string(), "true".to_string()),
            ],
        })
    }

    /// Validate cross-platform authenticator (Roaming authenticators)
    async fn validate_cross_platform_authenticator(
        &self,
        _assertion: &serde_json::Value,
    ) -> Result<TypeSpecificValidationResult> {
        tracing::debug!("Validating cross-platform authenticator");

        // Cross-platform authenticators are generally more flexible
        Ok(TypeSpecificValidationResult {
            user_verified: true,
            attestation_valid: true,
            additional_properties: vec![
                (
                    "authenticator_class".to_string(),
                    "cross_platform".to_string(),
                ),
                ("roaming_capable".to_string(), "true".to_string()),
            ],
        })
    }

    /// Validate security key (FIDO U2F/CTAP1 style authenticators)
    async fn validate_security_key(
        &self,
        assertion: &serde_json::Value,
    ) -> Result<TypeSpecificValidationResult> {
        tracing::debug!("Validating security key");

        // Security keys typically only provide user presence
        let authenticator_data = assertion
            .get("response")
            .and_then(|r| r.get("authenticatorData"))
            .and_then(|a| a.as_str())
            .ok_or_else(|| AuthError::validation("Missing authenticatorData"))?;

        let auth_data_bytes = URL_SAFE_NO_PAD
            .decode(authenticator_data)
            .map_err(|_| AuthError::validation("Invalid authenticatorData"))?;

        if auth_data_bytes.len() < 33 {
            return Err(AuthError::validation("AuthenticatorData too short"));
        }

        let flags = auth_data_bytes[32];
        let user_present = (flags & 0x01) != 0;
        let user_verified = (flags & 0x04) != 0;

        if !user_present {
            return Err(AuthError::validation(
                "User presence required for security key",
            ));
        }

        Ok(TypeSpecificValidationResult {
            user_verified,
            attestation_valid: true,
            additional_properties: vec![
                (
                    "authenticator_class".to_string(),
                    "security_key".to_string(),
                ),
                ("user_presence".to_string(), user_present.to_string()),
                ("hardware_backed".to_string(), "true".to_string()),
            ],
        })
    }

    /// Verify WebAuthn assertion signature (simplified implementation)
    /// In production, use a proper WebAuthn library like `webauthn-rs`
    fn verify_assertion_signature(
        &self,
        assertion_response: &str,
        auth_data_bytes: &[u8],
        decoded_client_data: &[u8],
        public_key_jwk: &serde_json::Value,
    ) -> Result<()> {
        use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
        use ring::digest;

        // IMPLEMENTATION COMPLETE: Enhanced assertion signature verification
        tracing::debug!("Verifying assertion signature");

        // Parse assertion response as JSON (simplified)
        let assertion: serde_json::Value = serde_json::from_str(assertion_response)
            .map_err(|_| AuthError::validation("Invalid assertion response format"))?;

        // Extract signature
        let signature = assertion
            .get("response")
            .and_then(|r| r.get("signature"))
            .and_then(|s| s.as_str())
            .ok_or_else(|| AuthError::validation("Missing signature in assertion response"))?;

        let signature_bytes = URL_SAFE_NO_PAD
            .decode(signature)
            .map_err(|_| AuthError::validation("Invalid signature base64"))?;

        // Create signed data: authenticatorData + SHA256(clientDataJSON)
        let client_data_hash = {
            let mut context = digest::Context::new(&digest::SHA256);
            context.update(decoded_client_data);
            context.finish()
        };

        let mut signed_data = Vec::new();
        signed_data.extend_from_slice(auth_data_bytes);
        signed_data.extend_from_slice(client_data_hash.as_ref());

        // Verify signature using public key
        self.verify_webauthn_signature(&signed_data, &signature_bytes, public_key_jwk)?;

        Ok(())
    }

    /// Extract counter from WebAuthn assertion response for replay attack protection
    fn extract_counter_from_assertion(&self, assertion_response: &str) -> Result<u32> {
        use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};

        // IMPLEMENTATION COMPLETE: Extract counter for replay attack protection
        tracing::debug!("Extracting counter from assertion response");

        // Parse assertion response as JSON
        let assertion: serde_json::Value = serde_json::from_str(assertion_response)
            .map_err(|_| AuthError::validation("Invalid assertion response format"))?;

        let authenticator_data = assertion
            .get("response")
            .and_then(|r| r.get("authenticatorData"))
            .and_then(|a| a.as_str())
            .ok_or_else(|| {
                AuthError::validation("Missing authenticatorData in assertion response")
            })?;

        // Decode base64 authenticator data
        let auth_data_bytes = URL_SAFE_NO_PAD
            .decode(authenticator_data)
            .map_err(|_| AuthError::validation("authenticatorData is not valid base64url"))?;

        // AuthenticatorData structure:
        // rpIdHash (32 bytes) + flags (1 byte) + counter (4 bytes) + ...
        if auth_data_bytes.len() < 37 {
            return Err(AuthError::validation(
                "authenticatorData is too short to contain a counter",
            ));
        }

        // Extract counter from bytes 33-36 (big-endian u32)
        let counter_bytes: [u8; 4] = [
            auth_data_bytes[33],
            auth_data_bytes[34],
            auth_data_bytes[35],
            auth_data_bytes[36],
        ];

        let counter = u32::from_be_bytes(counter_bytes);
        tracing::debug!("Extracted signature counter: {}", counter);
        Ok(counter)
    }
}

/// Result of advanced WebAuthn verification
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AdvancedVerificationResult {
    pub user_present: bool,
    pub user_verified: bool,
    pub new_counter: u32,
    pub signature_valid: bool,
    pub attestation_valid: bool,
}

/// Types of WebAuthn authenticators
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum AuthenticatorType {
    /// Platform authenticator (built into device)
    Platform,
    /// Cross-platform authenticator (roaming)
    CrossPlatform,
    /// Security key (FIDO U2F style)
    SecurityKey,
}

/// Result of cross-platform verification
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CrossPlatformVerificationResult {
    pub authenticator_type: AuthenticatorType,
    pub validation_result: TypeSpecificValidationResult,
    pub aaguid: Option<Vec<u8>>,
}

/// Type-specific validation result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TypeSpecificValidationResult {
    pub user_verified: bool,
    pub attestation_valid: bool,
    pub additional_properties: Vec<(String, String)>,
}

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

    #[tokio::test]
    async fn test_passkey_config_validation() {
        let token_manager = TokenManager::new_hmac(b"test-secret", "test-issuer", "test-audience");

        let config = PasskeyConfig {
            rp_id: "example.com".to_string(),
            rp_name: "Test App".to_string(),
            origin: "https://example.com".to_string(),
            timeout_ms: 60000,
            user_verification: "preferred".to_string(),
            authenticator_attachment: None,
            require_resident_key: false,
            ..Default::default()
        };

        let result = PasskeyAuthMethod::new(config, token_manager);

        #[cfg(feature = "passkeys")]
        {
            assert!(result.is_ok());
            let method = result.unwrap();
            assert!(method.validate_config().is_ok());
        }

        #[cfg(not(feature = "passkeys"))]
        {
            assert!(result.is_err());
        }
    }

    #[tokio::test]
    async fn test_invalid_passkey_config() {
        #[cfg_attr(not(feature = "passkeys"), allow(unused_variables))]
        let token_manager = TokenManager::new_hmac(b"test-secret", "test-issuer", "test-audience");

        #[cfg_attr(not(feature = "passkeys"), allow(unused_variables))]
        let config = PasskeyConfig {
            rp_id: "".to_string(), // Invalid: empty RP ID
            rp_name: "Test App".to_string(),
            origin: "https://example.com".to_string(),
            timeout_ms: 60000,
            user_verification: "invalid".to_string(), // Invalid user verification
            authenticator_attachment: None,
            require_resident_key: false,
            ..Default::default()
        };

        #[cfg(feature = "passkeys")]
        {
            let result = PasskeyAuthMethod::new(config, token_manager);
            if let Ok(method) = result {
                assert!(method.validate_config().is_err());
            }
        }
    }
}