tauri-plugin-biometry 0.2.8

A Tauri v2 plugin for biometric authentication (Touch ID, Face ID, fingerprint) on Android, macOS, iOS and Windows.
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
use serde::de::DeserializeOwned;
use tauri::{plugin::PluginApi, AppHandle, Runtime};

use crate::error::{ErrorResponse, PluginInvokeError};
use crate::models::*;

use windows::{
    core::*,
    Security::Credentials::UI::{
        UserConsentVerificationResult, UserConsentVerifier, UserConsentVerifierAvailability,
    },
    Security::Credentials::{
        KeyCredentialCreationOption, KeyCredentialManager, KeyCredentialRetrievalResult,
        KeyCredentialStatus, PasswordCredential, PasswordVault,
    },
    Security::Cryptography::Core::{
        CryptographicEngine, HashAlgorithmNames, HashAlgorithmProvider, SymmetricAlgorithmNames,
        SymmetricKeyAlgorithmProvider,
    },
    Security::Cryptography::{BinaryStringEncoding, CryptographicBuffer},
    Win32::UI::WindowsAndMessaging::{
        BringWindowToTop, FindWindowW, IsIconic, SetForegroundWindow, ShowWindow, SW_RESTORE,
    },
};

pub fn init<R: Runtime, C: DeserializeOwned>(
    app: &AppHandle<R>,
    _api: PluginApi<R, C>,
) -> crate::Result<Biometry<R>> {
    Ok(Biometry(app.clone()))
}

#[inline]
fn to_wide(s: &str) -> Vec<u16> {
    use std::os::windows::ffi::OsStrExt;
    std::ffi::OsStr::new(s)
        .encode_wide()
        .chain(std::iter::once(0))
        .collect()
}

/// Try to find and foreground the Windows Hello credential dialog.
fn try_focus_hello_dialog_once() -> bool {
    // Common class name for the PIN/Hello dialog host
    let cls = to_wide("Credential Dialog Xaml Host");
    unsafe {
        let hwnd = FindWindowW(
            windows::core::PCWSTR(cls.as_ptr()),
            windows::core::PCWSTR::null(),
        );
        if let Ok(hwnd) = hwnd {
            if IsIconic(hwnd).as_bool() {
                let _ = ShowWindow(hwnd, SW_RESTORE);
            }
            let _ = BringWindowToTop(hwnd);
            let _ = SetForegroundWindow(hwnd);
            return true;
        }
    }
    false
}

/// Focus the Hello dialog by retrying a few times in a helper thread.
fn nudge_hello_dialog_focus_async(retries: u32, delay_ms: u64) {
    std::thread::spawn(move || {
        // Small initial delay gives the dialog time to appear
        std::thread::sleep(std::time::Duration::from_millis(delay_ms));
        for _ in 0..retries {
            if try_focus_hello_dialog_once() {
                break;
            }
            std::thread::sleep(std::time::Duration::from_millis(delay_ms));
        }
    });
}

/// Create or open a Windows Hello credential
fn get_credential(domain: &str, create_if_missing: bool) -> Result<KeyCredentialRetrievalResult> {
    let credential_name = HSTRING::from(domain);

    // Focus the Hello dialog
    nudge_hello_dialog_focus_async(5, 250);

    if create_if_missing {
        KeyCredentialManager::RequestCreateAsync(
            &credential_name,
            KeyCredentialCreationOption::ReplaceExisting,
        )?
        .get()
    } else {
        KeyCredentialManager::OpenAsync(&credential_name)?.get()
    }
}

/// Encrypt data using Windows Hello credential
fn encrypt_data(
    domain: &str,
    data: &[u8],
    credential_result: &KeyCredentialRetrievalResult,
) -> Result<String> {
    let status = credential_result.Status()?;
    if status != KeyCredentialStatus::Success {
        return Err(Error::from(HRESULT(-1)));
    }

    let credential = credential_result.Credential()?;
    let challenge_buffer = CryptographicBuffer::ConvertStringToBinary(
        &HSTRING::from(domain),
        BinaryStringEncoding::Utf8,
    )?;

    // Sign the challenge to get a unique key
    let signature = credential.RequestSignAsync(&challenge_buffer)?.get()?;
    let signature_result = signature.Result()?;

    // Use the signature to derive an encryption key
    let hash_provider = HashAlgorithmProvider::OpenAlgorithm(&HashAlgorithmNames::Sha256()?)?;
    let key_hash = hash_provider.HashData(&signature_result)?;

    // Create AES encryption provider
    let aes_provider =
        SymmetricKeyAlgorithmProvider::OpenAlgorithm(&SymmetricAlgorithmNames::AesCbcPkcs7()?)?;

    // Generate IV from domain hash
    let iv_data = CryptographicBuffer::ConvertStringToBinary(
        &HSTRING::from(format!("IV_{}", domain)),
        BinaryStringEncoding::Utf8,
    )?;
    let iv_hash = hash_provider.HashData(&iv_data)?;

    // Take first 16 bytes of IV hash for AES-128
    let mut iv_bytes: windows::core::Array<u8> = windows::core::Array::new();
    CryptographicBuffer::CopyToByteArray(&iv_hash, &mut iv_bytes)?;
    let iv_slice: Vec<u8> = iv_bytes.as_slice()[..16].to_vec();
    let iv = CryptographicBuffer::CreateFromByteArray(&iv_slice)?;

    // Create symmetric key
    let key = aes_provider.CreateSymmetricKey(&key_hash)?;

    // Encrypt the data
    let data_buffer = CryptographicBuffer::CreateFromByteArray(data)?;
    let encrypted_buffer = CryptographicEngine::Encrypt(&key, &data_buffer, Some(&iv))?;

    // Convert to base64 string
    Ok(CryptographicBuffer::EncodeToBase64String(&encrypted_buffer)?.to_string())
}

/// Decrypt data using Windows Hello credential
fn decrypt_data(
    domain: &str,
    encrypted_data: &str,
    credential_result: &KeyCredentialRetrievalResult,
) -> Result<Vec<u8>> {
    let status = credential_result.Status()?;
    if status != KeyCredentialStatus::Success {
        return Err(Error::from(HRESULT(-1)));
    }

    let credential = credential_result.Credential()?;
    let challenge_buffer = CryptographicBuffer::ConvertStringToBinary(
        &HSTRING::from(domain),
        BinaryStringEncoding::Utf8,
    )?;

    // Sign the challenge to get the same key
    let signature = credential.RequestSignAsync(&challenge_buffer)?.get()?;
    let signature_status = signature.Status()?;

    if signature_status != KeyCredentialStatus::Success {
        return Err(Error::from(HRESULT(-1)));
    }

    let signature_result = signature.Result()?;

    // Use the signature to derive the decryption key
    let hash_provider = HashAlgorithmProvider::OpenAlgorithm(&HashAlgorithmNames::Sha256()?)?;
    let key_hash = hash_provider.HashData(&signature_result)?;

    // Create AES decryption provider
    let aes_provider =
        SymmetricKeyAlgorithmProvider::OpenAlgorithm(&SymmetricAlgorithmNames::AesCbcPkcs7()?)?;

    // Generate IV from domain hash (same as encryption)
    let iv_data = CryptographicBuffer::ConvertStringToBinary(
        &HSTRING::from(format!("IV_{}", domain)),
        BinaryStringEncoding::Utf8,
    )?;
    let iv_hash = hash_provider.HashData(&iv_data)?;

    // Take first 16 bytes of IV hash for AES-128
    let mut iv_bytes: windows::core::Array<u8> = windows::core::Array::new();
    CryptographicBuffer::CopyToByteArray(&iv_hash, &mut iv_bytes)?;
    let iv_slice: Vec<u8> = iv_bytes.as_slice()[..16].to_vec();
    let iv = CryptographicBuffer::CreateFromByteArray(&iv_slice)?;

    // Create symmetric key
    let key = aes_provider.CreateSymmetricKey(&key_hash)?;

    // Decode from base64 and decrypt
    let encrypted_buffer =
        CryptographicBuffer::DecodeFromBase64String(&HSTRING::from(encrypted_data))?;
    let decrypted_buffer = CryptographicEngine::Decrypt(&key, &encrypted_buffer, Some(&iv))?;

    // Convert to bytes
    let mut decrypted_bytes: windows::core::Array<u8> = windows::core::Array::new();
    CryptographicBuffer::CopyToByteArray(&decrypted_buffer, &mut decrypted_bytes)?;

    Ok(decrypted_bytes.to_vec())
}

/// Access to the biometry APIs.
pub struct Biometry<R: Runtime>(AppHandle<R>);

impl<R: Runtime> Biometry<R> {
    pub fn status(&self) -> crate::Result<Status> {
        let availability = UserConsentVerifier::CheckAvailabilityAsync()
            .and_then(|async_op| async_op.get())
            .map_err(|e| {
                crate::Error::PluginInvoke(PluginInvokeError::InvokeRejected(ErrorResponse {
                    code: Some("internalError".to_string()),
                    message: Some(format!("Failed to check biometry availability: {:?}", e)),
                    data: (),
                }))
            })?;

        let (is_available, biometry_type, error, error_code) = match availability {
            UserConsentVerifierAvailability::Available => (true, BiometryType::Auto, None, None),
            UserConsentVerifierAvailability::DeviceNotPresent => (
                false,
                BiometryType::None,
                Some("No biometric device found".to_string()),
                Some("biometryNotAvailable".to_string()),
            ),
            UserConsentVerifierAvailability::NotConfiguredForUser => (
                false,
                BiometryType::None,
                Some("Biometric authentication not configured".to_string()),
                Some("biometryNotEnrolled".to_string()),
            ),
            UserConsentVerifierAvailability::DisabledByPolicy => (
                false,
                BiometryType::None,
                Some("Biometric authentication disabled by policy".to_string()),
                Some("biometryNotAvailable".to_string()),
            ),
            UserConsentVerifierAvailability::DeviceBusy => (
                false,
                BiometryType::None,
                Some("Biometric device is busy".to_string()),
                Some("systemCancel".to_string()),
            ),
            _ => (
                false,
                BiometryType::None,
                Some("Unknown availability status".to_string()),
                Some("biometryNotAvailable".to_string()),
            ),
        };

        Ok(Status {
            is_available,
            biometry_type,
            error,
            error_code,
        })
    }

    pub fn authenticate(&self, reason: String, _options: AuthOptions) -> crate::Result<()> {
        let result = UserConsentVerifier::RequestVerificationAsync(&HSTRING::from(reason))
            .and_then(|async_op| {
                nudge_hello_dialog_focus_async(5, 250);
                async_op.get()
            })
            .map_err(|e| {
                crate::Error::PluginInvoke(PluginInvokeError::InvokeRejected(ErrorResponse {
                    code: Some("internalError".to_string()),
                    message: Some(format!("Failed to request user verification: {:?}", e)),
                    data: (),
                }))
            })?;

        match result {
            UserConsentVerificationResult::Verified => Ok(()),
            UserConsentVerificationResult::DeviceBusy => Err(crate::Error::PluginInvoke(
                PluginInvokeError::InvokeRejected(ErrorResponse {
                    code: Some("systemCancel".to_string()),
                    message: Some("Device is busy".to_string()),
                    data: (),
                }),
            )),
            UserConsentVerificationResult::DeviceNotPresent => Err(crate::Error::PluginInvoke(
                PluginInvokeError::InvokeRejected(ErrorResponse {
                    code: Some("biometryNotAvailable".to_string()),
                    message: Some("No biometric device found".to_string()),
                    data: (),
                }),
            )),
            UserConsentVerificationResult::DisabledByPolicy => Err(crate::Error::PluginInvoke(
                PluginInvokeError::InvokeRejected(ErrorResponse {
                    code: Some("biometryNotAvailable".to_string()),
                    message: Some("Biometric authentication is disabled by policy".to_string()),
                    data: (),
                }),
            )),
            UserConsentVerificationResult::NotConfiguredForUser => Err(crate::Error::PluginInvoke(
                PluginInvokeError::InvokeRejected(ErrorResponse {
                    code: Some("biometryNotEnrolled".to_string()),
                    message: Some(
                        "Biometric authentication is not configured for the user".to_string(),
                    ),
                    data: (),
                }),
            )),
            UserConsentVerificationResult::Canceled => Err(crate::Error::PluginInvoke(
                PluginInvokeError::InvokeRejected(ErrorResponse {
                    code: Some("userCancel".to_string()),
                    message: Some("Authentication was canceled by the user".to_string()),
                    data: (),
                }),
            )),
            UserConsentVerificationResult::RetriesExhausted => Err(crate::Error::PluginInvoke(
                PluginInvokeError::InvokeRejected(ErrorResponse {
                    code: Some("biometryLockout".to_string()),
                    message: Some("Too many failed authentication attempts".to_string()),
                    data: (),
                }),
            )),
            _ => Err(crate::Error::PluginInvoke(
                PluginInvokeError::InvokeRejected(ErrorResponse {
                    code: Some("authenticationFailed".to_string()),
                    message: Some("Authentication failed".to_string()),
                    data: (),
                }),
            )),
        }
    }

    pub fn has_data(&self, options: DataOptions) -> crate::Result<bool> {
        let domain = options.domain;
        let name = options.name;

        if domain.is_empty() || name.is_empty() {
            return Ok(false);
        }

        // Try to open the credential (without creating)
        let credential_result = match get_credential(&domain, false) {
            Ok(result) => result,
            Err(_) => return Ok(false),
        };

        let status = credential_result.Status().map_err(|_| {
            crate::Error::PluginInvoke(PluginInvokeError::InvokeRejected(ErrorResponse {
                code: Some("internalError".to_string()),
                message: Some("Failed to check credential status".to_string()),
                data: (),
            }))
        })?;

        if status != KeyCredentialStatus::Success {
            return Ok(false);
        }

        // Check if there's data in the PasswordVault
        let vault = PasswordVault::new().map_err(|_| {
            crate::Error::PluginInvoke(PluginInvokeError::InvokeRejected(ErrorResponse {
                code: Some("internalError".to_string()),
                message: Some("Failed to access password vault".to_string()),
                data: (),
            }))
        })?;

        let resource = HSTRING::from(&domain);
        let username = HSTRING::from(&name);

        // Try to retrieve the credential without the password
        match vault.Retrieve(&resource, &username) {
            Ok(_) => Ok(true),
            Err(_) => Ok(false),
        }
    }

    pub fn get_data(&self, options: GetDataOptions) -> crate::Result<DataResponse> {
        let domain = options.domain.clone();
        let name = options.name.clone();

        if domain.is_empty() || name.is_empty() {
            return Err(crate::Error::PluginInvoke(
                PluginInvokeError::InvokeRejected(ErrorResponse {
                    code: Some("invalidInput".to_string()),
                    message: Some("Domain and name must not be empty".to_string()),
                    data: (),
                }),
            ));
        }

        // Try to open the credential (without creating)
        let credential_result = get_credential(&domain, false).map_err(|e| {
            crate::Error::PluginInvoke(PluginInvokeError::InvokeRejected(ErrorResponse {
                code: Some("credentialNotFound".to_string()),
                message: Some(format!("Failed to open credential: {:?}", e)),
                data: (),
            }))
        })?;

        let status = credential_result.Status().map_err(|e| {
            crate::Error::PluginInvoke(PluginInvokeError::InvokeRejected(ErrorResponse {
                code: Some("internalError".to_string()),
                message: Some(format!("Failed to check credential status: {:?}", e)),
                data: (),
            }))
        })?;

        if status != KeyCredentialStatus::Success {
            return Err(crate::Error::PluginInvoke(
                PluginInvokeError::InvokeRejected(ErrorResponse {
                    code: Some("credentialNotFound".to_string()),
                    message: Some("Credential not available".to_string()),
                    data: (),
                }),
            ));
        }

        // Access the PasswordVault
        let vault = PasswordVault::new().map_err(|e| {
            crate::Error::PluginInvoke(PluginInvokeError::InvokeRejected(ErrorResponse {
                code: Some("internalError".to_string()),
                message: Some(format!("Failed to access password vault: {:?}", e)),
                data: (),
            }))
        })?;

        let resource = HSTRING::from(&domain);
        let username = HSTRING::from(&name);

        // Retrieve the credential with password
        let credential = vault.Retrieve(&resource, &username).map_err(|e| {
            crate::Error::PluginInvoke(PluginInvokeError::InvokeRejected(ErrorResponse {
                code: Some("dataNotFound".to_string()),
                message: Some(format!("Failed to retrieve data: {:?}", e)),
                data: (),
            }))
        })?;

        // Get the password (encrypted data)
        credential.RetrievePassword().map_err(|e| {
            crate::Error::PluginInvoke(PluginInvokeError::InvokeRejected(ErrorResponse {
                code: Some("internalError".to_string()),
                message: Some(format!("Failed to retrieve password: {:?}", e)),
                data: (),
            }))
        })?;

        let encrypted_data = credential.Password().map_err(|e| {
            crate::Error::PluginInvoke(PluginInvokeError::InvokeRejected(ErrorResponse {
                code: Some("internalError".to_string()),
                message: Some(format!("Failed to get password: {:?}", e)),
                data: (),
            }))
        })?;

        // Decrypt the data
        let decrypted_data = decrypt_data(&domain, &encrypted_data.to_string(), &credential_result)
            .map_err(|e| {
                crate::Error::PluginInvoke(PluginInvokeError::InvokeRejected(ErrorResponse {
                    code: Some("decryptionFailed".to_string()),
                    message: Some(format!("Failed to decrypt data: {:?}", e)),
                    data: (),
                }))
            })?;

        // Convert decrypted bytes to string
        let data_string = String::from_utf8(decrypted_data).map_err(|e| {
            crate::Error::PluginInvoke(PluginInvokeError::InvokeRejected(ErrorResponse {
                code: Some("internalError".to_string()),
                message: Some(format!("Failed to convert data to string: {:?}", e)),
                data: (),
            }))
        })?;

        Ok(DataResponse {
            domain,
            name,
            data: data_string,
        })
    }

    pub fn set_data(&self, options: SetDataOptions) -> crate::Result<()> {
        let domain = options.domain;
        let name = options.name;
        let data = options.data;

        if domain.is_empty() || name.is_empty() {
            return Err(crate::Error::PluginInvoke(
                PluginInvokeError::InvokeRejected(ErrorResponse {
                    code: Some("invalidInput".to_string()),
                    message: Some("Domain and name must not be empty".to_string()),
                    data: (),
                }),
            ));
        }

        // Create or replace the credential
        let credential_result = get_credential(&domain, true).map_err(|e| {
            crate::Error::PluginInvoke(PluginInvokeError::InvokeRejected(ErrorResponse {
                code: Some("credentialCreationFailed".to_string()),
                message: Some(format!("Failed to create credential: {:?}", e)),
                data: (),
            }))
        })?;

        let status = credential_result.Status().map_err(|e| {
            crate::Error::PluginInvoke(PluginInvokeError::InvokeRejected(ErrorResponse {
                code: Some("internalError".to_string()),
                message: Some(format!("Failed to check credential status: {:?}", e)),
                data: (),
            }))
        })?;

        if status != KeyCredentialStatus::Success {
            return Err(crate::Error::PluginInvoke(
                PluginInvokeError::InvokeRejected(ErrorResponse {
                    code: Some("credentialCreationFailed".to_string()),
                    message: Some("Failed to create credential".to_string()),
                    data: (),
                }),
            ));
        }

        // Encrypt the data
        let encrypted_data =
            encrypt_data(&domain, data.as_bytes(), &credential_result).map_err(|e| {
                crate::Error::PluginInvoke(PluginInvokeError::InvokeRejected(ErrorResponse {
                    code: Some("encryptionFailed".to_string()),
                    message: Some(format!("Failed to encrypt data: {:?}", e)),
                    data: (),
                }))
            })?;

        // Access the PasswordVault
        let vault = PasswordVault::new().map_err(|e| {
            crate::Error::PluginInvoke(PluginInvokeError::InvokeRejected(ErrorResponse {
                code: Some("internalError".to_string()),
                message: Some(format!("Failed to access password vault: {:?}", e)),
                data: (),
            }))
        })?;

        let resource = HSTRING::from(&domain);
        let username = HSTRING::from(&name);
        let password = HSTRING::from(&encrypted_data);

        // Try to remove existing credential if it exists
        if let Ok(existing) = vault.Retrieve(&resource, &username) {
            let _ = vault.Remove(&existing);
        }

        // Create new credential
        let credential = PasswordCredential::CreatePasswordCredential(
            &resource, &username, &password,
        )
        .map_err(|e| {
            crate::Error::PluginInvoke(PluginInvokeError::InvokeRejected(ErrorResponse {
                code: Some("internalError".to_string()),
                message: Some(format!("Failed to create password credential: {:?}", e)),
                data: (),
            }))
        })?;

        // Add to vault
        vault.Add(&credential).map_err(|e| {
            crate::Error::PluginInvoke(PluginInvokeError::InvokeRejected(ErrorResponse {
                code: Some("internalError".to_string()),
                message: Some(format!("Failed to store credential: {:?}", e)),
                data: (),
            }))
        })?;

        Ok(())
    }

    pub fn remove_data(&self, options: RemoveDataOptions) -> crate::Result<()> {
        let domain = options.domain;
        let name = options.name;

        if domain.is_empty() || name.is_empty() {
            return Err(crate::Error::PluginInvoke(
                PluginInvokeError::InvokeRejected(ErrorResponse {
                    code: Some("invalidInput".to_string()),
                    message: Some("Domain and name must not be empty".to_string()),
                    data: (),
                }),
            ));
        }

        // Access the PasswordVault
        let vault = PasswordVault::new().map_err(|e| {
            crate::Error::PluginInvoke(PluginInvokeError::InvokeRejected(ErrorResponse {
                code: Some("internalError".to_string()),
                message: Some(format!("Failed to access password vault: {:?}", e)),
                data: (),
            }))
        })?;

        let resource = HSTRING::from(&domain);
        let username = HSTRING::from(&name);

        // Try to retrieve and remove the credential
        match vault.Retrieve(&resource, &username) {
            Ok(credential) => {
                vault.Remove(&credential).map_err(|e| {
                    crate::Error::PluginInvoke(PluginInvokeError::InvokeRejected(ErrorResponse {
                        code: Some("internalError".to_string()),
                        message: Some(format!("Failed to remove credential: {:?}", e)),
                        data: (),
                    }))
                })?;
                Ok(())
            }
            Err(_) => {
                // Credential doesn't exist, which is fine for remove
                Ok(())
            }
        }
    }
}