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
use objc2_core_foundation::{
    kCFCopyStringDictionaryKeyCallBacks, kCFTypeDictionaryValueCallBacks, CFBoolean, CFData,
    CFDictionary, CFDictionaryKeyCallBacks, CFDictionaryValueCallBacks, CFIndex, CFRetained,
    CFString, CFType,
};
use objc2_local_authentication::{LABiometryType, LAContext, LAError, LAPolicy};
use objc2_security::{
    errSecDuplicateItem, errSecInteractionNotAllowed, errSecItemNotFound, errSecSuccess,
    errSecUserCanceled, kSecAttrAccessControl, kSecAttrAccessibleWhenUnlockedThisDeviceOnly,
    kSecAttrAccount, kSecAttrService, kSecClass, kSecClassGenericPassword, kSecMatchLimit,
    kSecMatchLimitOne, kSecReturnData, kSecUseAuthenticationUI, kSecUseAuthenticationUIFail,
    kSecUseDataProtectionKeychain, kSecUseOperationPrompt, kSecValueData, SecAccessControl,
    SecAccessControlCreateFlags, SecItemAdd, SecItemCopyMatching, SecItemDelete, SecItemUpdate,
};
use serde::de::DeserializeOwned;
use std::ffi::c_void;
use tauri::{plugin::PluginApi, AppHandle, Runtime};

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

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

fn la_error_to_string(error: LAError) -> &'static str {
    match error {
        LAError::AppCancel => "appCancel",
        LAError::AuthenticationFailed => "authenticationFailed",
        LAError::InvalidContext => "invalidContext",
        LAError::NotInteractive => "notInteractive",
        LAError::PasscodeNotSet => "passcodeNotSet",
        LAError::SystemCancel => "systemCancel",
        LAError::UserCancel => "userCancel",
        LAError::UserFallback => "userFallback",
        LAError::BiometryLockout => "biometryLockout",
        LAError::BiometryNotAvailable => "biometryNotAvailable",
        LAError::BiometryNotEnrolled => "biometryNotEnrolled",
        _ => "unknown",
    }
}

/// 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 context = unsafe { LAContext::new() };

        let can_evaluate = unsafe {
            context.canEvaluatePolicy_error(LAPolicy::DeviceOwnerAuthenticationWithBiometrics)
        };

        let biometry_type = unsafe { context.biometryType() };

        let is_available = can_evaluate.is_ok();
        let mut error_reason: Option<String> = None;
        let mut error_code: Option<String> = None;

        if let Err(error) = can_evaluate {
            let ns_error = &*error;

            // Get error description
            let description = ns_error.localizedDescription();
            error_reason = Some(description.to_string());

            // Map error code to string representation
            let code = LAError(ns_error.code());
            error_code = Some(la_error_to_string(code).to_string());
        }

        // Map LABiometryType to our BiometryType enum
        let mapped_biometry_type = match biometry_type {
            LABiometryType::None => BiometryType::None,
            LABiometryType::TouchID => BiometryType::TouchID,
            LABiometryType::FaceID => BiometryType::FaceID,
            #[allow(unreachable_patterns)]
            _ => BiometryType::None,
        };

        Ok(Status {
            is_available,
            biometry_type: mapped_biometry_type,
            error: error_reason,
            error_code,
        })
    }

    pub fn authenticate(&self, reason: String, options: AuthOptions) -> crate::Result<()> {
        let context = unsafe { LAContext::new() };

        // Check if biometry is available or device credential is allowed
        let can_evaluate_biometry = unsafe {
            context.canEvaluatePolicy_error(LAPolicy::DeviceOwnerAuthenticationWithBiometrics)
        };

        let allow_device_credential = options.allow_device_credential.unwrap_or(false);

        if can_evaluate_biometry.is_err() && !allow_device_credential {
            // Biometry unavailable and fallback disabled
            if let Err(error) = can_evaluate_biometry {
                let ns_error = &*error;
                let description = ns_error.localizedDescription();
                let code = LAError(ns_error.code());
                let error_code = la_error_to_string(code);

                return Err(crate::Error::PluginInvoke(
                    PluginInvokeError::InvokeRejected(ErrorResponse {
                        code: Some(error_code.to_string()),
                        message: Some(description.to_string()),
                        data: (),
                    }),
                ));
            }
        }

        // Set localized titles if provided
        if let Some(fallback_title) = options.fallback_title {
            unsafe {
                let title_str = objc2_foundation::NSString::from_str(&fallback_title);
                context.setLocalizedFallbackTitle(Some(&title_str));
            }
        }

        if let Some(cancel_title) = options.cancel_title {
            unsafe {
                let title_str = objc2_foundation::NSString::from_str(&cancel_title);
                context.setLocalizedCancelTitle(Some(&title_str));
            }
        }

        // Set authentication reuse duration to 0 (no reuse)
        unsafe {
            context.setTouchIDAuthenticationAllowableReuseDuration(0.0);
        }

        // Determine which policy to use
        let policy = if allow_device_credential {
            LAPolicy::DeviceOwnerAuthentication
        } else {
            LAPolicy::DeviceOwnerAuthenticationWithBiometrics
        };

        // Create a channel to communicate between the callback and the main thread
        let (tx, rx) = std::sync::mpsc::channel();

        // Perform authentication
        unsafe {
            let reason_str = objc2_foundation::NSString::from_str(&reason);
            let tx_clone = tx.clone();

            context.evaluatePolicy_localizedReason_reply(
                policy,
                &reason_str,
                &block2::StackBlock::new(
                    move |success: objc2::runtime::Bool,
                          error_ptr: *mut objc2_foundation::NSError| {
                        if success.as_bool() {
                            let _ = tx_clone.send(Ok(()));
                        } else if !error_ptr.is_null() {
                            let error = &*error_ptr;
                            let description = error.localizedDescription().to_string();
                            let code = LAError(error.code());
                            let error_code = la_error_to_string(code);

                            let _ = tx_clone.send(Err(crate::Error::PluginInvoke(
                                PluginInvokeError::InvokeRejected(ErrorResponse {
                                    code: Some(error_code.to_string()),
                                    message: Some(description),
                                    data: (),
                                }),
                            )));
                        } else {
                            let _ = tx_clone.send(Err(crate::Error::PluginInvoke(
                                PluginInvokeError::InvokeRejected(ErrorResponse {
                                    code: Some("authenticationFailed".to_string()),
                                    message: Some("Unknown error".to_string()),
                                    data: (),
                                }),
                            )));
                        }
                    },
                ),
            );
        }

        // Wait for authentication result
        match rx.recv() {
            Ok(result) => result,
            Err(_) => Err(crate::Error::PluginInvoke(
                PluginInvokeError::InvokeRejected(ErrorResponse {
                    code: Some("authenticationFailed".to_string()),
                    message: Some("Failed to receive authentication result".to_string()),
                    data: (),
                }),
            )),
        }
    }

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

            // `kSecUseDataProtectionKeychain` opts every SecItem call in
            // this file into the modern data-protection keychain — the
            // only backend on macOS that honors `SecAccessControl`
            // (biometric gating). Without it `secd` falls back to the
            // legacy file keychain, generates an implicit
            // `kSecAttrAccess` from `kSecAttrAccessible`, and rejects
            // writes that also pass `kSecAttrAccessControl` with
            // errSecParam ("conflicting kSecAccess and
            // kSecAccessControl attributes"). The flag must be present
            // on EVERY call (add/copy/update/delete) so they all
            // address the same backend.
            let true_ref = CFBoolean::new(true).as_ref();
            let keys: [&CFType; 6] = [
                kSecClass.as_ref(),
                kSecMatchLimit.as_ref(),
                kSecUseAuthenticationUI.as_ref(),
                kSecAttrAccount.as_ref(),
                kSecAttrService.as_ref(),
                kSecUseDataProtectionKeychain.as_ref(),
            ];
            let values: [&CFType; 6] = [
                kSecClassGenericPassword.as_ref(),
                kSecMatchLimitOne.as_ref(),
                kSecUseAuthenticationUIFail.as_ref(),
                account_cf.as_ref(),
                service_cf.as_ref(),
                true_ref,
            ];

            let query = CFDictionary::new(
                None,
                keys.as_ptr() as *mut *const c_void,
                values.as_ptr() as *mut *const c_void,
                keys.len() as CFIndex,
                &kCFCopyStringDictionaryKeyCallBacks as *const CFDictionaryKeyCallBacks,
                &kCFTypeDictionaryValueCallBacks as *const CFDictionaryValueCallBacks,
            )
            .ok_or_else(|| {
                crate::Error::PluginInvoke(PluginInvokeError::InvokeRejected(ErrorResponse {
                    code: Some("internalError".to_string()),
                    message: Some("Failed to create CFDictionary for query".to_string()),
                    data: (),
                }))
            })?;

            let status = SecItemCopyMatching(&query, std::ptr::null_mut());

            if status == errSecSuccess || status == errSecInteractionNotAllowed {
                Ok(true)
            } else if status == errSecItemNotFound {
                Ok(false)
            } else {
                Err(crate::Error::PluginInvoke(
                    PluginInvokeError::InvokeRejected(ErrorResponse {
                        code: Some("keychainError".to_string()),
                        message: Some(format!("SecItemCopyMatching failed with status: {status}")),
                        data: (),
                    }),
                ))
            }
        }
    }

    pub fn get_data(&self, options: GetDataOptions) -> crate::Result<DataResponse> {
        unsafe {
            let cf_account: CFRetained<CFString> = CFString::from_str(&options.name);
            let cf_service: CFRetained<CFString> = CFString::from_str(&options.domain);
            let cf_reason: CFRetained<CFString> = CFString::from_str(&options.reason);

            let true_ref = CFBoolean::new(true).as_ref();
            let keys: [&CFType; 7] = [
                kSecClass.as_ref(),
                kSecAttrAccount.as_ref(),
                kSecAttrService.as_ref(),
                kSecReturnData.as_ref(),
                kSecMatchLimit.as_ref(),
                kSecUseOperationPrompt.as_ref(),
                kSecUseDataProtectionKeychain.as_ref(),
            ];
            let values: [&CFType; 7] = [
                kSecClassGenericPassword.as_ref(),
                cf_account.as_ref(),
                cf_service.as_ref(),
                true_ref,
                kSecMatchLimitOne.as_ref(),
                cf_reason.as_ref(),
                true_ref,
            ];

            let query = CFDictionary::new(
                None,
                keys.as_ptr() as *mut *const c_void,
                values.as_ptr() as *mut *const c_void,
                keys.len() as CFIndex,
                &kCFCopyStringDictionaryKeyCallBacks as *const CFDictionaryKeyCallBacks,
                &kCFTypeDictionaryValueCallBacks as *const CFDictionaryValueCallBacks,
            )
            .ok_or_else(|| {
                crate::Error::PluginInvoke(PluginInvokeError::InvokeRejected(ErrorResponse {
                    code: Some("internalError".to_string()),
                    message: Some("Failed to create CFDictionary for query".to_string()),
                    data: (),
                }))
            })?;

            let mut out: *const CFType = std::ptr::null();
            let status = SecItemCopyMatching(&query, &mut out);

            if status == errSecSuccess {
                if !out.is_null() {
                    let cf_data: &CFData = &*(out as *const CFData);
                    let bytes = cf_data.byte_ptr();
                    let data = std::slice::from_raw_parts(bytes, cf_data.len() as usize);
                    Ok(DataResponse {
                        domain: options.domain,
                        name: options.name,
                        data: String::from_utf8_lossy(data).to_string(),
                    })
                } else {
                    Err(crate::Error::PluginInvoke(
                        PluginInvokeError::InvokeRejected(ErrorResponse {
                            code: Some("dataError".to_string()),
                            message: Some("SecItemCopyMatching returned null data".to_string()),
                            data: (),
                        }),
                    ))
                }
            } else if status == errSecItemNotFound {
                return Err(crate::Error::PluginInvoke(
                    PluginInvokeError::InvokeRejected(ErrorResponse {
                        code: Some("itemNotFound".to_string()),
                        message: Some(format!("Error retrieving item from keychain: {status}")),
                        data: (),
                    }),
                ));
            } else if status == errSecUserCanceled {
                return Err(crate::Error::PluginInvoke(
                    PluginInvokeError::InvokeRejected(ErrorResponse {
                        code: Some("userCancel".to_string()),
                        message: Some("User canceled".to_string()),
                        data: (),
                    }),
                ));
            } else if status == errSecInteractionNotAllowed {
                return Err(crate::Error::PluginInvoke(
                    PluginInvokeError::InvokeRejected(ErrorResponse {
                        code: Some("authenticationRequired".to_string()),
                        message: Some(
                            "Authentication required but UI interaction is not allowed".to_string(),
                        ),
                        data: (),
                    }),
                ));
            } else {
                return Err(crate::Error::PluginInvoke(
                    PluginInvokeError::InvokeRejected(ErrorResponse {
                        code: Some("keychainError".to_string()),
                        message: Some(format!("Error retrieving item from keychain: {status}")),
                        data: (),
                    }),
                ));
            }
        }
    }

    pub fn set_data(&self, options: SetDataOptions) -> crate::Result<()> {
        unsafe {
            let cf_account: CFRetained<CFString> = CFString::from_str(&options.name);
            let cf_service: CFRetained<CFString> = CFString::from_str(&options.domain);
            let cf_value: CFRetained<CFData> = CFData::from_bytes(options.data.as_bytes());

            // Create SecAccessControl(userPresence)
            let ac_ref = SecAccessControl::with_flags(
                None,
                kSecAttrAccessibleWhenUnlockedThisDeviceOnly,
                SecAccessControlCreateFlags::UserPresence,
                std::ptr::null_mut(),
            )
            .ok_or_else(|| {
                crate::Error::PluginInvoke(PluginInvokeError::InvokeRejected(ErrorResponse {
                    code: Some("internalError".to_string()),
                    message: Some("Failed to create SecAccessControl".to_string()),
                    data: (),
                }))
            })?;

            // Attributes for SecItemAdd. The `SecAccessControl` built
            // above already encodes the accessibility class — passing
            // `kSecAttrAccessible` here in addition would conflict
            // (errSecParam, "kSecAccess and kSecAccessControl"). We
            // also opt into the data-protection keychain so
            // `kSecAttrAccessControl` is honored.
            let true_ref = CFBoolean::new(true).as_ref();
            let keys: [&CFType; 6] = [
                kSecClass.as_ref(),
                kSecAttrAccount.as_ref(),
                kSecAttrService.as_ref(),
                kSecValueData.as_ref(),
                kSecAttrAccessControl.as_ref(),
                kSecUseDataProtectionKeychain.as_ref(),
            ];
            let values: [&CFType; 6] = [
                kSecClassGenericPassword.as_ref(),
                cf_account.as_ref(),
                cf_service.as_ref(),
                cf_value.as_ref(),
                ac_ref.as_ref(),
                true_ref,
            ];

            let add_dict = CFDictionary::new(
                None,
                keys.as_ptr() as *mut *const c_void,
                values.as_ptr() as *mut *const c_void,
                keys.len() as CFIndex,
                &kCFCopyStringDictionaryKeyCallBacks as *const CFDictionaryKeyCallBacks,
                &kCFTypeDictionaryValueCallBacks as *const CFDictionaryValueCallBacks,
            )
            .ok_or_else(|| {
                crate::Error::PluginInvoke(PluginInvokeError::InvokeRejected(ErrorResponse {
                    code: Some("internalError".to_string()),
                    message: Some("Failed to create CFDictionary for add_dict".to_string()),
                    data: (),
                }))
            })?;

            let mut status = SecItemAdd(&add_dict, std::ptr::null_mut());
            if status == errSecDuplicateItem {
                // Query dict (class + account + service). Same backend
                // opt-in as the add — otherwise SecItemUpdate looks at
                // the legacy keychain and reports "not found" for an
                // item that lives in the data-protection backend.
                let q_keys: [&CFType; 4] = [
                    kSecClass.as_ref(),
                    kSecAttrAccount.as_ref(),
                    kSecAttrService.as_ref(),
                    kSecUseDataProtectionKeychain.as_ref(),
                ];
                let q_vals: [&CFType; 4] = [
                    kSecClassGenericPassword.as_ref(),
                    cf_account.as_ref(),
                    cf_service.as_ref(),
                    true_ref,
                ];

                let query = CFDictionary::new(
                    None,
                    q_keys.as_ptr() as *mut *const c_void,
                    q_vals.as_ptr() as *mut *const c_void,
                    q_keys.len() as CFIndex,
                    &kCFCopyStringDictionaryKeyCallBacks as *const CFDictionaryKeyCallBacks,
                    &kCFTypeDictionaryValueCallBacks as *const CFDictionaryValueCallBacks,
                )
                .ok_or_else(|| {
                    crate::Error::PluginInvoke(PluginInvokeError::InvokeRejected(ErrorResponse {
                        code: Some("internalError".to_string()),
                        message: Some("Failed to create CFDictionary for update query".to_string()),
                        data: (),
                    }))
                })?;

                // Update dict (value data + access control). Same
                // reasoning as the add path: `SecAccessControl` already
                // carries the accessibility class, so passing
                // `kSecAttrAccessible` separately collides with
                // `kSecAttrAccessControl`.
                let u_keys: [&CFType; 2] = [kSecValueData.as_ref(), kSecAttrAccessControl.as_ref()];
                let u_vals: [&CFType; 2] = [cf_value.as_ref(), ac_ref.as_ref()];

                let update_dict = CFDictionary::new(
                    None,
                    u_keys.as_ptr() as *mut *const c_void,
                    u_vals.as_ptr() as *mut *const c_void,
                    u_keys.len() as CFIndex,
                    &kCFCopyStringDictionaryKeyCallBacks as *const CFDictionaryKeyCallBacks,
                    &kCFTypeDictionaryValueCallBacks as *const CFDictionaryValueCallBacks,
                )
                .ok_or_else(|| {
                    crate::Error::PluginInvoke(PluginInvokeError::InvokeRejected(ErrorResponse {
                        code: Some("internalError".to_string()),
                        message: Some("Failed to create CFDictionary for update_dict".to_string()),
                        data: (),
                    }))
                })?;

                status = SecItemUpdate(&query, &update_dict);
            }

            if status == errSecSuccess {
                Ok(())
            } else {
                Err(crate::Error::PluginInvoke(
                    PluginInvokeError::InvokeRejected(ErrorResponse {
                        code: Some("keychainError".to_string()),
                        message: Some(format!("Error adding item to keychain: {status}")),
                        data: (),
                    }),
                ))
            }
        }
    }

    pub fn remove_data(&self, options: RemoveDataOptions) -> crate::Result<()> {
        unsafe {
            let cf_account: CFRetained<CFString> = CFString::from_str(&options.name);
            let cf_service: CFRetained<CFString> = CFString::from_str(&options.domain);

            // Build immutable CFDictionary with 4 key-value pairs. The
            // `kSecUseDataProtectionKeychain` flag matches the
            // backend the corresponding `set_data` writes into;
            // without it the delete targets the legacy keychain and
            // misses items stored under the modern backend.
            let true_ref = CFBoolean::new(true).as_ref();
            let keys: [&CFType; 4] = [
                kSecClass.as_ref(),
                kSecAttrAccount.as_ref(),
                kSecAttrService.as_ref(),
                kSecUseDataProtectionKeychain.as_ref(),
            ];
            let values: [&CFType; 4] = [
                kSecClassGenericPassword.as_ref(),
                cf_account.as_ref(),
                cf_service.as_ref(),
                true_ref,
            ];

            let query = CFDictionary::new(
                None,
                keys.as_ptr() as *mut *const c_void,
                values.as_ptr() as *mut *const c_void,
                keys.len() as CFIndex,
                &kCFCopyStringDictionaryKeyCallBacks as *const CFDictionaryKeyCallBacks,
                &kCFTypeDictionaryValueCallBacks as *const CFDictionaryValueCallBacks,
            )
            .ok_or_else(|| {
                crate::Error::PluginInvoke(PluginInvokeError::InvokeRejected(ErrorResponse {
                    code: Some("internalError".to_string()),
                    message: Some("Failed to create CFDictionary for delete query".to_string()),
                    data: (),
                }))
            })?;

            let status = SecItemDelete(&query);

            if status == errSecSuccess || status == errSecItemNotFound {
                Ok(())
            } else {
                Err(crate::Error::PluginInvoke(
                    PluginInvokeError::InvokeRejected(ErrorResponse {
                        code: Some("keychainError".to_string()),
                        message: Some(format!("Error deleting item from keychain: {status}")),
                        data: (),
                    }),
                ))
            }
        }
    }
}