qualia-bioauth 0.1.0

Auth-bound key storage: wrapping a 32-byte key behind platform user authentication (Android BiometricPrompt, Windows Hello).
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
// Copyright (C) 2026 Qualia2FA contributors
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License as published by the Free
// Software Foundation; either version 3 of the License, or (at your option) any
// later version.
//
// This library is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
// details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this library; if not, see <https://www.gnu.org/licenses/>.

//! Windows backend: a Windows Hello credential whose `hmac-secret` output is the
//! wrapping key.
//!
//! # Why not CNG's `NCRYPT_UI_POLICY`
//!
//! A CNG key can be created with `NCRYPT_UI_PROTECT_KEY_FLAG`, and the Key Storage
//! Provider will refuse to finalize or use it without a "strong key" prompt. That
//! prompt is the CryptUI password/PIN protector, not Windows Hello, and the KSP caches
//! it for the process. Using it would ask the user to invent a second password and
//! would not use the Hello credential the user already has. This backend therefore
//! uses the Win32 WebAuthn API instead.
//!
//! # How the key is bound to Hello
//!
//! 1. `WebAuthNAuthenticatorMakeCredential` creates a platform credential with the
//!    PRF switch (`bEnablePrf`) and confirms that the platform reports it enabled.
//! 2. For every wrap and unwrap, `WebAuthNAuthenticatorGetAssertion` is called with
//!    `WEBAUTHN_AUTHENTICATOR_HMAC_SECRET_VALUES_FLAG` and a 32-byte salt. The OS shows
//!    the Hello prompt, and only a successful gesture releases the 32-byte
//!    `hmac-secret`, which is the key that encrypts the master key.
//! 3. The credential id and the salt are stored in the payload, so the same Hello
//!    gesture reproduces the same secret after a restart. Both also enter the AEAD's
//!    AAD.
//!
//! The process never sees a key the platform would release without a gesture: if the
//! user cancels, the assertion fails and there is nothing to decrypt with. This is the
//! line the TODO draws between L3 and a `UserConsentVerifier` callback.
//!
//! # Availability
//!
//! `WebAuthNIsUserVerifyingPlatformAuthenticatorAvailable` reports a platform
//! **capability**, not whether this user has enrolled Hello. If it returns true and the
//! API version exposes the salt values, [`AuthBoundKeyStore::availability`] reports
//! [`Availability::Available`] and the first [`AuthBoundKeyStore::create`] makes the
//! real attempt. A `NotSupportedError` from that call is reported as
//! [`Error::Unavailable`] with a reason the user interface can show; it never falls
//! back to a software key.
//!
//! `hardware_backed` is reported as `false`: the Win32 WebAuthn API does not say
//! whether the platform authenticator is TPM-backed, and this crate does not guess.
//!
//! # Reading the PRF flag
//!
//! The attestation's `bPrfEnabled` field is **not** trusted. On Windows 11 23H2 (WebAuthn
//! API version 7) the credential is created with the `hmac-secret` extension requested but
//! `bPrfEnabled` stays zero; a build that fills the field is not guaranteed either. The
//! first `GetAssertion` is the ground truth: it either returns the 32-byte secret or it
//! does not. When it fails with a permanent refusal the store remembers that and reports
//! [`Error::Unavailable`] on later calls; the password path is unaffected. A browser demo
//! succeeding on the same machine is a reason to test the assertion, not to trust the
//! attestation flag.

mod payload;

use crate::format::AuthBlob;
use crate::key::{MASTER_KEY_LEN, MasterKey};
use crate::traits::{AuthBoundKeyStore, Availability, Backend};
use crate::{Error, Result};
use chacha20poly1305::aead::{Aead, KeyInit, Payload as AeadPayload};
use chacha20poly1305::{Key, XChaCha20Poly1305, XNonce};
use std::sync::{Mutex, PoisonError};
use windows_sys::Win32::Foundation::HWND;
use windows_sys::Win32::Networking::WindowsWebServices::{
    WEBAUTHN_ASSERTION, WEBAUTHN_ATTESTATION_CONVEYANCE_PREFERENCE_NONE,
    WEBAUTHN_AUTHENTICATOR_ATTACHMENT_PLATFORM, WEBAUTHN_AUTHENTICATOR_GET_ASSERTION_OPTIONS,
    WEBAUTHN_AUTHENTICATOR_HMAC_SECRET_VALUES_FLAG, WEBAUTHN_AUTHENTICATOR_MAKE_CREDENTIAL_OPTIONS,
    WEBAUTHN_CLIENT_DATA, WEBAUTHN_COSE_CREDENTIAL_PARAMETER, WEBAUTHN_COSE_CREDENTIAL_PARAMETERS,
    WEBAUTHN_CREDENTIAL, WEBAUTHN_CREDENTIAL_ATTESTATION, WEBAUTHN_CREDENTIAL_TYPE_PUBLIC_KEY,
    WEBAUTHN_CREDENTIALS, WEBAUTHN_EXTENSION, WEBAUTHN_EXTENSIONS,
    WEBAUTHN_EXTENSIONS_IDENTIFIER_HMAC_SECRET, WEBAUTHN_HMAC_SECRET_SALT,
    WEBAUTHN_HMAC_SECRET_SALT_VALUES, WEBAUTHN_RP_ENTITY_INFORMATION,
    WEBAUTHN_USER_ENTITY_INFORMATION, WEBAUTHN_USER_VERIFICATION_REQUIREMENT_REQUIRED,
    WebAuthNAuthenticatorGetAssertion, WebAuthNAuthenticatorMakeCredential,
    WebAuthNDeletePlatformCredential, WebAuthNFreeAssertion, WebAuthNFreeCredentialAttestation,
    WebAuthNGetApiVersionNumber, WebAuthNIsUserVerifyingPlatformAuthenticatorAvailable,
};
use windows_sys::Win32::Security::Cryptography::{
    BCRYPT_USE_SYSTEM_PREFERRED_RNG, BCryptGenRandom,
};
use windows_sys::Win32::UI::WindowsAndMessaging::{GetDesktopWindow, GetForegroundWindow};
use zeroize::Zeroize;

/// Relying-party identifier used for the credential.
///
/// A reserved `.invalid` domain: it never resolves, so a credential created for it
/// cannot be confused with a website's credential, and the WebAuthn API does not need
/// the origin to be reachable.
const RP_ID: &str = "qualia-bioauth.invalid";

/// Human-readable relying-party name shown by the platform.
const RP_NAME: &str = "Qualia2FA";

/// Origin written into the client data.
const ORIGIN: &str = "https://qualia-bioauth.invalid";

/// COSE identifier of ECDSA with SHA-256 (`-7`); windows-sys does not export it.
const COSE_ES256: i32 = -7;

/// Hash algorithm name the API expects alongside the client data.
const HASH_ALGORITHM: &str = "SHA-256";

/// How long the platform may wait for the Hello gesture.
const TIMEOUT_MS: u32 = 60_000;

/// The earliest WebAuthn API version that exposes the HMAC-secret salt values.
const MIN_API_VERSION: u32 = 7;

/// `NTE_USER_CANCELLED`: the user dismissed the Hello prompt.
const NTE_USER_CANCELLED: i32 = 0x8009_0036_u32 as i32;

/// `ERROR_CANCELLED`: some paths report a cancelled dialog as a Win32 error.
const ERROR_CANCELLED: i32 = 0x8007_04C7_u32 as i32;

/// `NTE_AUTHENTICATION_IGNORED`: the gesture did not verify the user.
const NTE_AUTHENTICATION_IGNORED: i32 = 0x8009_0031_u32 as i32;

/// `NTE_NOT_SUPPORTED`: the platform authenticator cannot perform this operation.
const NTE_NOT_SUPPORTED: i32 = 0x8009_0029_u32 as i32;

/// `NTE_DEVICE_NOT_READY`: no usable authenticator is enrolled.
const NTE_DEVICE_NOT_READY: i32 = 0x8009_0030_u32 as i32;

/// `NTE_NOT_FOUND`: the credential has already been deleted.
const NTE_NOT_FOUND: i32 = 0x8009_0011_u32 as i32;

/// `WEBAUTHN_AUTHENTICATOR_MAKE_CREDENTIAL_OPTIONS`, version 9.
///
/// Windows 11 25H2 exposes WebAuthn API 9. The version 7 struct that
/// `windows-sys 0.61` ships is rejected by that runtime with
/// `NTE_INVALID_PARAMETER` (`0x80090027`) for a platform credential. The v7 prefix is
/// kept byte-for-byte; the fields after `pbJsonExt` are the v8/v9 additions from
/// `webauthn.h`.
#[allow(non_snake_case, clippy::missing_docs_in_private_items)]
#[repr(C)]
struct MakeCredentialOptionsV9 {
    dwVersion: u32,
    dwTimeoutMilliseconds: u32,
    CredentialList: WEBAUTHN_CREDENTIALS,
    Extensions: WEBAUTHN_EXTENSIONS,
    dwAuthenticatorAttachment: u32,
    bRequireResidentKey: i32,
    dwUserVerificationRequirement: u32,
    dwAttestationConveyancePreference: u32,
    dwFlags: u32,
    pCancellationId: *mut core::ffi::c_void,
    pExcludeCredentialList: *mut core::ffi::c_void,
    dwEnterpriseAttestation: u32,
    dwLargeBlobSupport: u32,
    bPreferResidentKey: i32,
    bBrowserInPrivateMode: i32,
    bEnablePrf: i32,
    pLinkedDevice: *mut core::ffi::c_void,
    cbJsonExt: u32,
    pbJsonExt: *mut u8,
    pPRFGlobalEval: *mut WEBAUTHN_HMAC_SECRET_SALT,
    cCredentialHints: u32,
    ppwszCredentialHints: *mut *const u16,
    bThirdPartyPayment: i32,
    pwszRemoteWebOrigin: *const u16,
    cbPublicKeyCredentialCreationOptionsJSON: u32,
    pbPublicKeyCredentialCreationOptionsJSON: *mut u8,
    cbAuthenticatorId: u32,
    pbAuthenticatorId: *mut u8,
}

/// `WEBAUTHN_AUTHENTICATOR_GET_ASSERTION_OPTIONS`, version 9.
#[allow(non_snake_case, clippy::missing_docs_in_private_items)]
#[repr(C)]
struct GetAssertionOptionsV9 {
    dwVersion: u32,
    dwTimeoutMilliseconds: u32,
    CredentialList: WEBAUTHN_CREDENTIALS,
    Extensions: WEBAUTHN_EXTENSIONS,
    dwAuthenticatorAttachment: u32,
    dwUserVerificationRequirement: u32,
    dwFlags: u32,
    pwszU2fAppId: *const u16,
    pbU2fAppId: *mut i32,
    pCancellationId: *mut core::ffi::c_void,
    pAllowCredentialList: *mut core::ffi::c_void,
    dwCredLargeBlobOperation: u32,
    cbCredLargeBlob: u32,
    pbCredLargeBlob: *mut u8,
    pHmacSecretSaltValues: *mut WEBAUTHN_HMAC_SECRET_SALT_VALUES,
    bBrowserInPrivateMode: i32,
    pLinkedDevice: *mut core::ffi::c_void,
    bAutoFill: i32,
    cbJsonExt: u32,
    pbJsonExt: *mut u8,
    cCredentialHints: u32,
    ppwszCredentialHints: *mut *const u16,
    pwszRemoteWebOrigin: *const u16,
    cbPublicKeyCredentialRequestOptionsJSON: u32,
    pbPublicKeyCredentialRequestOptionsJSON: *mut u8,
    cbAuthenticatorId: u32,
    pbAuthenticatorId: *mut u8,
}

/// A Windows auth-bound store backed by a Windows Hello credential.
///
/// The credential id is kept in memory after [`AuthBoundKeyStore::create`]. A store
/// that was just opened has no id yet, so [`AuthBoundKeyStore::wrap`] creates the
/// credential on its first call and [`AuthBoundKeyStore::delete`] can only remove a
/// credential created in this process. Use [`WindowsKeyStore::delete_blob`] to remove
/// the credential recorded in a persisted blob.
pub struct WindowsKeyStore {
    /// Credential id created in this process, if any.
    credential: Mutex<Option<Vec<u8>>>,
    /// A reason discovered by a failed attempt, reported by later `availability` calls.
    ///
    /// The WebAuthn capability check cannot see whether the platform authenticator
    /// actually enables PRF; only a creation attempt can. Remembering the answer keeps
    /// the user interface from offering a path that was just proved unusable.
    unavailable: Mutex<Option<&'static str>>,
    /// Serializes platform prompts: two Hello dialogs at once confuse the user and the
    /// authenticator.
    operation: Mutex<()>,
}

impl WindowsKeyStore {
    /// Creates an empty store.
    ///
    /// Nothing is created and no prompt is shown; [`AuthBoundKeyStore::availability`]
    /// reports what this machine supports.
    #[must_use]
    pub fn new() -> Self {
        Self {
            credential: Mutex::new(None),
            unavailable: Mutex::new(None),
            operation: Mutex::new(()),
        }
    }

    /// Deletes the credential recorded in `blob`, without unwrapping it.
    ///
    /// This is what "turn biometric unlock off" needs after a restart: the store no
    /// longer remembers the credential id, but the blob still names it.
    ///
    /// # Errors
    ///
    /// - a malformed blob or one written by another backend: the usual format errors
    /// - a platform failure while deleting: [`Error::Platform`]
    pub fn delete_blob(&self, blob: &[u8]) -> Result<()> {
        let blob = AuthBlob::parse(blob)?;
        blob.expect_backend(Backend::WindowsWebAuthn)?;
        let payload = payload::Payload::parse(blob.wrapped())?;

        let _operation = self
            .operation
            .lock()
            .unwrap_or_else(PoisonError::into_inner);
        delete_credential(payload.credential_id())?;

        let mut current = self
            .credential
            .lock()
            .unwrap_or_else(PoisonError::into_inner);
        if current.as_deref() == Some(payload.credential_id()) {
            *current = None;
        }
        Ok(())
    }

    /// Returns the current credential id, creating one if needed.
    fn ensure_credential(&self) -> Result<Vec<u8>> {
        if let Some(reason) = self.unavailable_reason() {
            return Err(Error::Unavailable { reason });
        }
        if let Some(credential) = self
            .credential
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .clone()
        {
            return Ok(credential);
        }

        let credential = match make_credential(foreground_window()) {
            Ok(credential) => credential,
            Err(Error::Unavailable { reason }) => {
                self.remember_unavailable(reason);
                return Err(Error::Unavailable { reason });
            }
            Err(error) => return Err(error),
        };
        *self
            .credential
            .lock()
            .unwrap_or_else(PoisonError::into_inner) = Some(credential.clone());
        Ok(credential)
    }

    /// The reason a previous attempt found this backend unusable, if any.
    fn unavailable_reason(&self) -> Option<&'static str> {
        *self
            .unavailable
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
    }

    /// Remembers that this backend cannot work on this machine.
    fn remember_unavailable(&self, reason: &'static str) {
        *self
            .unavailable
            .lock()
            .unwrap_or_else(PoisonError::into_inner) = Some(reason);
    }

    /// Asks the platform for the `hmac-secret`, remembering a permanent refusal.
    ///
    /// The attestation's PRF flag is **not** trusted: on some Windows builds the credential
    /// is created with the extension enabled but `bPrfEnabled` is left at zero. The assertion
    /// is the ground truth — it either returns the secret or it does not.
    fn hmac_secret(
        &self,
        credential_id: &[u8],
        salt: &[u8; payload::SALT_LEN],
    ) -> Result<[u8; 32]> {
        match get_hmac_secret(foreground_window(), credential_id, salt) {
            Ok(secret) => Ok(secret),
            Err(Error::Unavailable { reason }) => {
                self.remember_unavailable(reason);
                Err(Error::Unavailable { reason })
            }
            Err(error) => Err(error),
        }
    }

    /// A copy of the current credential id, if any.
    fn current_credential(&self) -> Option<Vec<u8>> {
        self.credential
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .clone()
    }
}

impl Default for WindowsKeyStore {
    fn default() -> Self {
        Self::new()
    }
}

impl core::fmt::Debug for WindowsKeyStore {
    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        formatter
            .debug_struct("WindowsKeyStore")
            .field("has_credential", &self.current_credential().is_some())
            .finish_non_exhaustive()
    }
}

impl AuthBoundKeyStore for WindowsKeyStore {
    fn availability(&self) -> Availability {
        if let Some(reason) = self.unavailable_reason() {
            return Availability::Unavailable { reason };
        }
        availability()
    }

    fn create(&self) -> Result<()> {
        let _operation = self
            .operation
            .lock()
            .unwrap_or_else(PoisonError::into_inner);
        self.ensure_credential().map(|_| ())
    }

    fn wrap(&self, master: &MasterKey) -> Result<Vec<u8>> {
        let _operation = self
            .operation
            .lock()
            .unwrap_or_else(PoisonError::into_inner);
        let credential_id = self.ensure_credential()?;

        let mut salt = [0_u8; payload::SALT_LEN];
        random_bytes(&mut salt)?;
        let mut hmac_secret = self.hmac_secret(&credential_id, &salt)?;

        let mut nonce = [0_u8; payload::NONCE_LEN];
        random_bytes(&mut nonce)?;
        let aad = associated_data(&credential_id, &salt);

        let cipher = XChaCha20Poly1305::new(&Key::from(hmac_secret));
        let encrypted = cipher.encrypt(
            &XNonce::from(nonce),
            AeadPayload {
                msg: master.expose_secret(),
                aad: &aad,
            },
        );
        hmac_secret.zeroize();
        let ciphertext = encrypted.map_err(|_| Error::Platform {
            operation: "encrypt the master key",
            code: 0,
        })?;
        if ciphertext.len() != payload::CIPHERTEXT_LEN {
            return Err(Error::WrappedPayloadInvalid {
                reason: "the Windows ciphertext does not have the fixed length",
            });
        }
        let mut fixed = [0_u8; payload::CIPHERTEXT_LEN];
        fixed.copy_from_slice(&ciphertext);

        let payload = payload::Payload::new(credential_id, salt, nonce, fixed)?;
        let blob = AuthBlob::new(Backend::WindowsWebAuthn, payload.encode())?;
        Ok(blob.encode())
    }

    fn unwrap(&self, blob: &[u8]) -> Result<MasterKey> {
        let blob = AuthBlob::parse(blob)?;
        blob.expect_backend(Backend::WindowsWebAuthn)?;
        let payload = payload::Payload::parse(blob.wrapped())?;
        if let Some(reason) = self.unavailable_reason() {
            return Err(Error::Unavailable { reason });
        }

        let _operation = self
            .operation
            .lock()
            .unwrap_or_else(PoisonError::into_inner);
        let mut hmac_secret = self.hmac_secret(payload.credential_id(), payload.salt())?;

        let aad = associated_data(payload.credential_id(), payload.salt());
        let cipher = XChaCha20Poly1305::new(&Key::from(hmac_secret));
        let decrypted = cipher.decrypt(
            &XNonce::from(*payload.nonce()),
            AeadPayload {
                msg: payload.ciphertext(),
                aad: &aad,
            },
        );
        hmac_secret.zeroize();
        let mut plaintext = decrypted.map_err(|_| Error::AuthenticationFailed)?;

        let master = MasterKey::from_bytes(&plaintext);
        plaintext.zeroize();
        master
    }

    fn delete(&self) -> Result<()> {
        let _operation = self
            .operation
            .lock()
            .unwrap_or_else(PoisonError::into_inner);
        let current = self.current_credential();
        if let Some(credential) = current {
            delete_credential(&credential)?;
            let mut stored = self
                .credential
                .lock()
                .unwrap_or_else(PoisonError::into_inner);
            if stored.as_deref() == Some(credential.as_slice()) {
                *stored = None;
            }
        }
        Ok(())
    }

    fn delete_blob(&self, blob: &[u8]) -> Result<()> {
        WindowsKeyStore::delete_blob(self, blob)
    }
}

/// The WebAuthn API version this Windows build exposes.
///
/// Version 7 is the first one whose structures carry the HMAC-secret salt values; a
/// lower number means this backend cannot work at all. The number is public so that a
/// diagnostic run can report it next to the outcome.
#[must_use]
pub fn api_version() -> u32 {
    // SAFETY: no arguments and no preconditions.
    unsafe { WebAuthNGetApiVersionNumber() }
}

/// Reports what this machine supports.
fn availability() -> Availability {
    if api_version() < MIN_API_VERSION {
        return Availability::Unavailable {
            reason: "this Windows version does not expose the WebAuthn hmac-secret extension",
        };
    }

    let mut available: i32 = 0;
    // SAFETY: the API writes one BOOL to the pointer.
    let status = unsafe { WebAuthNIsUserVerifyingPlatformAuthenticatorAvailable(&mut available) };
    if status < 0 || available == 0 {
        return Availability::Unavailable {
            reason: "this machine has no user-verifying platform authenticator",
        };
    }

    Availability::Available {
        backend: Backend::WindowsWebAuthn,
        hardware_backed: false,
    }
}

/// Returns a non-null window a WebAuthn prompt can be parented to.
///
/// The foreground window is the natural choice, but it can be null (a process without a
/// foreground window, a terminal that owns none, a remote session). Passing null to
/// `WebAuthNAuthenticatorMakeCredential` is rejected with `NTE_INVALID_PARAMETER`
/// (`0x80090027`), which looks exactly like "PRF unsupported" and hides the real cause.
/// The desktop window always exists and the API accepts it, so it is the fallback.
fn foreground_window() -> HWND {
    // SAFETY: no arguments and no preconditions; null is a valid answer.
    let foreground = unsafe { GetForegroundWindow() };
    if !foreground.is_null() {
        return foreground;
    }
    // SAFETY: no arguments and no preconditions; the desktop window always exists.
    unsafe { GetDesktopWindow() }
}

/// Fills `out` with random bytes from the system CSPRNG.
fn random_bytes(out: &mut [u8]) -> Result<()> {
    // SAFETY: `out` is a valid writable buffer of the length passed in; a null
    // algorithm handle with the system-preferred-RNG flag is the documented form.
    let status = unsafe {
        BCryptGenRandom(
            std::ptr::null_mut(),
            out.as_mut_ptr(),
            out.len() as u32,
            BCRYPT_USE_SYSTEM_PREFERRED_RNG,
        )
    };
    if status < 0 {
        Err(Error::RandomnessUnavailable)
    } else {
        Ok(())
    }
}

/// The AAD that binds the credential id and the salt to the ciphertext.
fn associated_data(credential_id: &[u8], salt: &[u8; payload::SALT_LEN]) -> Vec<u8> {
    let mut aad =
        Vec::with_capacity(payload::AAD_PREFIX.len() + 2 + credential_id.len() + salt.len());
    aad.extend_from_slice(payload::AAD_PREFIX);
    aad.extend_from_slice(&(credential_id.len() as u16).to_be_bytes());
    aad.extend_from_slice(credential_id);
    aad.extend_from_slice(salt);
    aad
}

/// Creates a platform credential with the PRF/`hmac-secret` extension enabled.
fn make_credential(hwnd: HWND) -> Result<Vec<u8>> {
    let rp_id = wide(RP_ID);
    let rp_name = wide(RP_NAME);
    let user_name = wide("local");
    let user_display = wide("Qualia2FA");
    let hash_algorithm = wide(HASH_ALGORITHM);

    let relying_party = WEBAUTHN_RP_ENTITY_INFORMATION {
        dwVersion: 1,
        pwszId: rp_id.as_ptr(),
        pwszName: rp_name.as_ptr(),
        pwszIcon: std::ptr::null(),
    };

    let mut user_id = [0_u8; 16];
    random_bytes(&mut user_id)?;
    let user = WEBAUTHN_USER_ENTITY_INFORMATION {
        dwVersion: 1,
        cbId: user_id.len() as u32,
        pbId: user_id.as_mut_ptr(),
        pwszName: user_name.as_ptr(),
        pwszIcon: std::ptr::null(),
        pwszDisplayName: user_display.as_ptr(),
    };

    let mut parameters = [WEBAUTHN_COSE_CREDENTIAL_PARAMETER {
        dwVersion: 1,
        pwszCredentialType: WEBAUTHN_CREDENTIAL_TYPE_PUBLIC_KEY,
        lAlg: COSE_ES256,
    }];
    let parameter_list = WEBAUTHN_COSE_CREDENTIAL_PARAMETERS {
        cCredentialParameters: parameters.len() as u32,
        pCredentialParameters: parameters.as_mut_ptr(),
    };

    let mut challenge = [0_u8; 32];
    random_bytes(&mut challenge)?;
    let client_bytes = client_data("create", &challenge);
    let client = WEBAUTHN_CLIENT_DATA {
        dwVersion: 1,
        cbClientDataJSON: client_bytes.len() as u32,
        pbClientDataJSON: client_bytes.as_ptr().cast_mut(),
        pwszHashAlgId: hash_algorithm.as_ptr(),
    };

    let mut hmac_extension_value: i32 = 1;
    let mut hmac_extension = WEBAUTHN_EXTENSION {
        pwszExtensionIdentifier: WEBAUTHN_EXTENSIONS_IDENTIFIER_HMAC_SECRET,
        cbExtension: 4,
        pvExtension: (&mut hmac_extension_value as *mut i32).cast(),
    };
    let extensions = WEBAUTHN_EXTENSIONS {
        cExtensions: 1,
        pExtensions: &mut hmac_extension,
    };

    let mut attestation: *mut WEBAUTHN_CREDENTIAL_ATTESTATION = std::ptr::null_mut();
    // SAFETY: every pointer argument points at a live value for the duration of the
    // call; `attestation` is a valid out pointer. The API returns an owned object on
    // success, freed exactly once below.
    let status = if api_version() >= 9 {
        let options = MakeCredentialOptionsV9 {
            dwVersion: 9,
            dwTimeoutMilliseconds: TIMEOUT_MS,
            CredentialList: WEBAUTHN_CREDENTIALS {
                cCredentials: 0,
                pCredentials: std::ptr::null_mut(),
            },
            Extensions: extensions,
            dwAuthenticatorAttachment: WEBAUTHN_AUTHENTICATOR_ATTACHMENT_PLATFORM,
            bRequireResidentKey: 1,
            dwUserVerificationRequirement: WEBAUTHN_USER_VERIFICATION_REQUIREMENT_REQUIRED,
            dwAttestationConveyancePreference: WEBAUTHN_ATTESTATION_CONVEYANCE_PREFERENCE_NONE,
            dwFlags: 0,
            pCancellationId: std::ptr::null_mut(),
            pExcludeCredentialList: std::ptr::null_mut(),
            dwEnterpriseAttestation: 0,
            dwLargeBlobSupport: 0,
            bPreferResidentKey: 0,
            bBrowserInPrivateMode: 0,
            bEnablePrf: 1,
            pLinkedDevice: std::ptr::null_mut(),
            cbJsonExt: 0,
            pbJsonExt: std::ptr::null_mut(),
            pPRFGlobalEval: std::ptr::null_mut(),
            cCredentialHints: 0,
            ppwszCredentialHints: std::ptr::null_mut(),
            bThirdPartyPayment: 0,
            pwszRemoteWebOrigin: std::ptr::null(),
            cbPublicKeyCredentialCreationOptionsJSON: 0,
            pbPublicKeyCredentialCreationOptionsJSON: std::ptr::null_mut(),
            cbAuthenticatorId: 0,
            pbAuthenticatorId: std::ptr::null_mut(),
        };
        // SAFETY: every pointer points at a live value and the out pointer is valid; the
        // options are the v9 prefix-compatible layout the API reads by `dwVersion`.
        unsafe {
            WebAuthNAuthenticatorMakeCredential(
                hwnd,
                &relying_party,
                &user,
                &parameter_list,
                &client,
                (&options as *const MakeCredentialOptionsV9)
                    .cast::<WEBAUTHN_AUTHENTICATOR_MAKE_CREDENTIAL_OPTIONS>(),
                &mut attestation,
            )
        }
    } else {
        let options = WEBAUTHN_AUTHENTICATOR_MAKE_CREDENTIAL_OPTIONS {
            dwVersion: 7,
            dwTimeoutMilliseconds: TIMEOUT_MS,
            Extensions: extensions,
            dwAuthenticatorAttachment: WEBAUTHN_AUTHENTICATOR_ATTACHMENT_PLATFORM,
            bRequireResidentKey: 0,
            dwUserVerificationRequirement: WEBAUTHN_USER_VERIFICATION_REQUIREMENT_REQUIRED,
            dwAttestationConveyancePreference: WEBAUTHN_ATTESTATION_CONVEYANCE_PREFERENCE_NONE,
            bEnablePrf: 1,
            ..Default::default()
        };
        // SAFETY: every pointer points at a live value and the out pointer is valid.
        unsafe {
            WebAuthNAuthenticatorMakeCredential(
                hwnd,
                &relying_party,
                &user,
                &parameter_list,
                &client,
                &options,
                &mut attestation,
            )
        }
    };
    if status < 0 {
        return Err(map_status("WebAuthNAuthenticatorMakeCredential", status));
    }
    if attestation.is_null() {
        return Err(Error::Platform {
            operation: "WebAuthNAuthenticatorMakeCredential returned no attestation",
            code: 0,
        });
    }

    let credential_id = {
        // SAFETY: the API returned a valid, live attestation.
        let attestation = unsafe { &*attestation };
        if attestation.pbCredentialId.is_null() {
            Vec::new()
        } else {
            // SAFETY: the API reports a valid credential id and its length.
            unsafe {
                std::slice::from_raw_parts(
                    attestation.pbCredentialId,
                    attestation.cbCredentialId as usize,
                )
            }
            .to_vec()
        }
    };
    // SAFETY: the attestation is owned by this call and freed exactly once.
    unsafe { WebAuthNFreeCredentialAttestation(attestation) };

    if credential_id.is_empty() || credential_id.len() > payload::MAX_CREDENTIAL_ID_LEN {
        return Err(Error::WrappedPayloadInvalid {
            reason: "the platform returned an unusable credential id",
        });
    }
    Ok(credential_id)
}

/// Runs one assertion and returns the 32-byte `hmac-secret`.
fn get_hmac_secret(
    hwnd: HWND,
    credential_id: &[u8],
    salt: &[u8; payload::SALT_LEN],
) -> Result<[u8; 32]> {
    let hash_algorithm = wide(HASH_ALGORITHM);

    let mut challenge = [0_u8; 32];
    random_bytes(&mut challenge)?;
    let client_bytes = client_data("get", &challenge);
    let client = WEBAUTHN_CLIENT_DATA {
        dwVersion: 1,
        cbClientDataJSON: client_bytes.len() as u32,
        pbClientDataJSON: client_bytes.as_ptr().cast_mut(),
        pwszHashAlgId: hash_algorithm.as_ptr(),
    };

    let mut salt_bytes = *salt;
    let mut hmac_salt = WEBAUTHN_HMAC_SECRET_SALT {
        cbFirst: payload::SALT_LEN as u32,
        pbFirst: salt_bytes.as_mut_ptr(),
        cbSecond: 0,
        pbSecond: std::ptr::null_mut(),
    };
    let mut salt_values = WEBAUTHN_HMAC_SECRET_SALT_VALUES {
        pGlobalHmacSalt: &mut hmac_salt,
        cCredWithHmacSecretSaltList: 0,
        pCredWithHmacSecretSaltList: std::ptr::null_mut(),
    };

    let mut credential_id_bytes = credential_id.to_vec();
    let mut credential = WEBAUTHN_CREDENTIAL {
        dwVersion: 1,
        cbId: credential_id_bytes.len() as u32,
        pbId: credential_id_bytes.as_mut_ptr(),
        pwszCredentialType: WEBAUTHN_CREDENTIAL_TYPE_PUBLIC_KEY,
    };

    let rp_id = wide(RP_ID);
    let mut assertion: *mut WEBAUTHN_ASSERTION = std::ptr::null_mut();
    // SAFETY: every pointer argument points at a live value for the duration of the
    // call; `assertion` is a valid out pointer. The API returns an owned object on
    // success, freed exactly once below.
    let status = if api_version() >= 9 {
        let options = GetAssertionOptionsV9 {
            dwVersion: 9,
            dwTimeoutMilliseconds: TIMEOUT_MS,
            CredentialList: WEBAUTHN_CREDENTIALS {
                cCredentials: 1,
                pCredentials: &mut credential,
            },
            Extensions: WEBAUTHN_EXTENSIONS {
                cExtensions: 0,
                pExtensions: std::ptr::null_mut(),
            },
            dwAuthenticatorAttachment: 0,
            dwUserVerificationRequirement: WEBAUTHN_USER_VERIFICATION_REQUIREMENT_REQUIRED,
            dwFlags: WEBAUTHN_AUTHENTICATOR_HMAC_SECRET_VALUES_FLAG,
            pwszU2fAppId: std::ptr::null(),
            pbU2fAppId: std::ptr::null_mut(),
            pCancellationId: std::ptr::null_mut(),
            pAllowCredentialList: std::ptr::null_mut(),
            dwCredLargeBlobOperation: 0,
            cbCredLargeBlob: 0,
            pbCredLargeBlob: std::ptr::null_mut(),
            pHmacSecretSaltValues: &mut salt_values,
            bBrowserInPrivateMode: 0,
            pLinkedDevice: std::ptr::null_mut(),
            bAutoFill: 0,
            cbJsonExt: 0,
            pbJsonExt: std::ptr::null_mut(),
            cCredentialHints: 0,
            ppwszCredentialHints: std::ptr::null_mut(),
            pwszRemoteWebOrigin: std::ptr::null(),
            cbPublicKeyCredentialRequestOptionsJSON: 0,
            pbPublicKeyCredentialRequestOptionsJSON: std::ptr::null_mut(),
            cbAuthenticatorId: 0,
            pbAuthenticatorId: std::ptr::null_mut(),
        };
        // SAFETY: every pointer points at a live value and the out pointer is valid; the
        // options are the v9 prefix-compatible layout the API reads by `dwVersion`.
        unsafe {
            WebAuthNAuthenticatorGetAssertion(
                hwnd,
                rp_id.as_ptr(),
                &client,
                (&options as *const GetAssertionOptionsV9)
                    .cast::<WEBAUTHN_AUTHENTICATOR_GET_ASSERTION_OPTIONS>(),
                &mut assertion,
            )
        }
    } else {
        let options = WEBAUTHN_AUTHENTICATOR_GET_ASSERTION_OPTIONS {
            dwVersion: 7,
            dwTimeoutMilliseconds: TIMEOUT_MS,
            CredentialList: WEBAUTHN_CREDENTIALS {
                cCredentials: 1,
                pCredentials: &mut credential,
            },
            dwUserVerificationRequirement: WEBAUTHN_USER_VERIFICATION_REQUIREMENT_REQUIRED,
            dwFlags: WEBAUTHN_AUTHENTICATOR_HMAC_SECRET_VALUES_FLAG,
            pHmacSecretSaltValues: &mut salt_values,
            ..Default::default()
        };
        // SAFETY: every pointer points at a live value and the out pointer is valid.
        unsafe {
            WebAuthNAuthenticatorGetAssertion(
                hwnd,
                rp_id.as_ptr(),
                &client,
                &options,
                &mut assertion,
            )
        }
    };
    if status < 0 {
        return Err(map_status("WebAuthNAuthenticatorGetAssertion", status));
    }
    if assertion.is_null() {
        return Err(Error::Platform {
            operation: "WebAuthNAuthenticatorGetAssertion returned no assertion",
            code: 0,
        });
    }

    let secret = {
        // SAFETY: the API returned a valid, live assertion.
        let assertion = unsafe { &*assertion };
        let salt = assertion.pHmacSecret;
        if salt.is_null() {
            None
        } else {
            // SAFETY: the API returned a live HMAC-secret structure.
            let salt = unsafe { &*salt };
            if salt.cbFirst != MASTER_KEY_LEN as u32 || salt.pbFirst.is_null() {
                None
            } else {
                let mut out = [0_u8; MASTER_KEY_LEN];
                // SAFETY: the API reported 32 live bytes at a non-null pointer.
                unsafe {
                    std::ptr::copy_nonoverlapping(salt.pbFirst, out.as_mut_ptr(), MASTER_KEY_LEN)
                };
                Some(out)
            }
        }
    };
    // SAFETY: the assertion is owned by this call and freed exactly once. The secret
    // was copied out above.
    unsafe { WebAuthNFreeAssertion(assertion) };

    secret.ok_or(Error::Unavailable {
        reason: "the platform assertion did not include a 32-byte hmac-secret",
    })
}

/// Deletes one platform credential.
fn delete_credential(credential_id: &[u8]) -> Result<()> {
    // SAFETY: the pointer and length describe a live credential id.
    let status = unsafe {
        WebAuthNDeletePlatformCredential(credential_id.len() as u32, credential_id.as_ptr())
    };
    if status < 0 && status != NTE_NOT_FOUND {
        return Err(map_status("WebAuthNDeletePlatformCredential", status));
    }
    Ok(())
}

/// Maps a WebAuthn HRESULT to the crate's error.
///
/// `NTE_INVALID_PARAMETER` is deliberately **not** folded into `Unavailable`: on a machine
/// where the request shape is the problem, the HRESULT is the only thing that says so. It
/// becomes a `Platform` error with the code, which the diagnostic prints in full.
fn map_status(operation: &'static str, status: i32) -> Error {
    match status {
        NTE_USER_CANCELLED | ERROR_CANCELLED | NTE_AUTHENTICATION_IGNORED => {
            Error::AuthenticationFailed
        }
        NTE_NOT_SUPPORTED => Error::Unavailable {
            reason: "the platform authenticator does not support the hmac-secret extension",
        },
        NTE_DEVICE_NOT_READY => Error::Unavailable {
            reason: "Windows Hello is not ready for this user; enroll Hello or unlock the session",
        },
        _ => Error::Platform {
            operation,
            code: status,
        },
    }
}

/// Encodes a string as NUL-terminated UTF-16.
fn wide(text: &str) -> Vec<u16> {
    text.encode_utf16().chain(std::iter::once(0)).collect()
}

/// Builds the WebAuthn client-data JSON.
fn client_data(kind: &str, challenge: &[u8]) -> Vec<u8> {
    format!(
        "{{\"type\":\"webauthn.{kind}\",\"challenge\":\"{}\",\"origin\":\"{ORIGIN}\"}}",
        base64url(challenge)
    )
    .into_bytes()
}

/// Base64url without padding.
fn base64url(bytes: &[u8]) -> String {
    const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
    let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
    for chunk in bytes.chunks(3) {
        let first = u32::from(chunk[0]);
        let second = chunk.get(1).copied().map_or(0, u32::from);
        let third = chunk.get(2).copied().map_or(0, u32::from);
        let triple = (first << 16) | (second << 8) | third;
        out.push(ALPHABET[(triple >> 18) as usize & 0x3F] as char);
        out.push(ALPHABET[(triple >> 12) as usize & 0x3F] as char);
        if chunk.len() > 1 {
            out.push(ALPHABET[(triple >> 6) as usize & 0x3F] as char);
        }
        if chunk.len() > 2 {
            out.push(ALPHABET[triple as usize & 0x3F] as char);
        }
    }
    out
}

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

    /// Availability is a truthful answer, never a panic.
    #[test]
    fn availability_is_reported() {
        let availability = availability();
        if availability.is_available() {
            assert_eq!(availability.backend(), Some(Backend::WindowsWebAuthn));
        } else {
            match availability {
                Availability::Unavailable { reason } => assert!(!reason.is_empty()),
                other => panic!("unexpected availability: {other:?}"),
            }
        }
    }

    /// The prompt parent is always non-null; a null parent is `NTE_INVALID_PARAMETER`.
    #[test]
    fn the_prompt_parent_is_never_null() {
        assert!(!foreground_window().is_null());
    }

    /// Deleting a store that holds nothing succeeds.
    #[test]
    fn delete_with_no_credential_is_ok() {
        let store = WindowsKeyStore::new();
        store.delete().expect("delete is idempotent");
    }

    /// A mock blob is rejected by the Windows backend before any platform call.
    #[test]
    fn mock_blob_is_rejected_as_the_wrong_backend() {
        let mock = MockKeyStore::new();
        let master = MasterKey::generate().expect("randomness");
        let blob = mock.wrap(&master).expect("wrap");

        let store = WindowsKeyStore::new();
        assert!(matches!(
            store.unwrap(&blob),
            Err(Error::WrongBackend {
                expected: Backend::WindowsWebAuthn,
                actual: Backend::Mock,
            })
        ));
        assert!(matches!(
            store.delete_blob(&blob),
            Err(Error::WrongBackend { .. })
        ));
    }

    /// The base64url encoder is unpadded and URL-safe.
    #[test]
    fn base64url_uses_the_url_safe_alphabet_without_padding() {
        assert_eq!(base64url(&[]), "");
        assert_eq!(base64url(&[0xFB_u8]), "-w");
        assert_eq!(base64url(&[0xFF_u8, 0xEF]), "_-8");
        assert_eq!(base64url(b"foobar"), "Zm9vYmFy");
    }

    /// The client-data JSON has the shape WebAuthn expects.
    #[test]
    fn client_data_has_the_expected_shape() {
        let json = String::from_utf8(client_data("get", &[0x11_u8; 4])).expect("utf-8");
        assert!(json.starts_with("{\"type\":\"webauthn.get\""));
        assert!(json.contains("\"challenge\":\"EREREQ\""));
        assert!(json.contains(ORIGIN));
    }

    /// A full round trip on a machine whose platform authenticator enables PRF.
    ///
    /// Ignored by default: it shows **three** Windows Hello prompts (create the
    /// credential, wrap, unwrap) and needs a real user to complete them. Run it
    /// deliberately on the acceptance machine:
    ///
    /// ```text
    /// cargo test --features mock -- --ignored --nocapture
    /// ```
    ///
    /// The output says which outcome happened:
    ///
    /// - `RESULT: roundtrip OK` — the platform released the `hmac-secret`, the wrapped
    ///   master key came back, and the credential was deleted;
    /// - `RESULT: PRF UNAVAILABLE: ...` — the platform created the credential but did
    ///   not enable the PRF extension. The test passes to show that the store fails
    ///   closed, but **this machine cannot run the Windows L3 path**.
    #[test]
    #[ignore = "requires an enrolled Windows Hello account and shows prompts"]
    fn hello_roundtrip() {
        // SAFETY: no arguments and no preconditions.
        let api_version = unsafe { WebAuthNGetApiVersionNumber() };
        let store = WindowsKeyStore::new();
        println!("WebAuthN API version: {api_version}");
        println!("availability: {:?}", store.availability());

        if !store.availability().is_available() {
            println!("RESULT: SKIPPED (no user-verifying platform authenticator)");
            return;
        }

        match store.create() {
            Ok(()) => println!("create: ok"),
            Err(Error::Unavailable { reason }) => {
                println!("RESULT: PRF UNAVAILABLE: {reason}");
                assert!(matches!(
                    store.availability(),
                    Availability::Unavailable { .. }
                ));
                return;
            }
            Err(error) => panic!("create failed: {error}"),
        }

        let master = MasterKey::generate().expect("randomness");
        let blob = match store.wrap(&master) {
            Ok(blob) => blob,
            Err(Error::Unavailable { reason }) => {
                println!("RESULT: PRF UNAVAILABLE: {reason}");
                assert!(matches!(
                    store.availability(),
                    Availability::Unavailable { .. }
                ));
                return;
            }
            Err(error) => panic!("wrap failed: {error}"),
        };
        println!("wrap: ok");
        let restored = store.unwrap(&blob).expect("unwrap (Hello prompt)");
        assert_eq!(restored, master);
        println!("unwrap: ok, the same master key came back");

        store.delete_blob(&blob).expect("delete the credential");
        assert!(
            store.unwrap(&blob).is_err(),
            "a deleted credential still unwraps"
        );
        println!("delete: ok, the old blob no longer unwraps");
        println!("RESULT: roundtrip OK");
    }
}