#![expect(unsafe_code, reason = "Objective-C messages to LocalAuthentication")]
use std::sync::Arc;
use block2::RcBlock;
use cranpose_services::{
DeviceAuthAvailability, DeviceAuthOutcome, DeviceAuthRequest, DeviceAuthenticator,
finish_device_auth, set_platform_device_authenticator,
};
use dispatch2::DispatchQueue;
use objc2::runtime::Bool;
use objc2_foundation::{NSError, NSString};
use objc2_local_authentication::{LAContext, LAErrorDomain, LAPolicy};
use super::device_auth_codes::{PASSCODE_NOT_SET, outcome};
pub(crate) fn register() {
set_platform_device_authenticator(Some(Arc::new(AppleDeviceAuth)));
}
struct AppleDeviceAuth;
fn local_code(error: &NSError) -> Option<isize> {
let domain = unsafe { LAErrorDomain };
(&*error.domain() == domain).then(|| error.code())
}
impl DeviceAuthenticator for AppleDeviceAuth {
fn availability(&self) -> DeviceAuthAvailability {
let context = unsafe { LAContext::new() };
if let Err(error) =
unsafe { context.canEvaluatePolicy_error(LAPolicy::DeviceOwnerAuthentication) }
{
return if local_code(&error) == Some(PASSCODE_NOT_SET) {
DeviceAuthAvailability::NoScreenLock
} else {
DeviceAuthAvailability::Unsupported
};
}
let biometric = unsafe {
context.canEvaluatePolicy_error(LAPolicy::DeviceOwnerAuthenticationWithBiometrics)
};
if biometric.is_ok() {
DeviceAuthAvailability::Biometric
} else {
DeviceAuthAvailability::Credential
}
}
fn authenticate(&self, request: DeviceAuthRequest, reason: &str) {
let context = unsafe { LAContext::new() };
let reason = NSString::from_str(reason);
let held = context.clone();
let reply = RcBlock::new(move |unlocked: Bool, error: *mut NSError| {
let outcome = if unlocked.as_bool() {
DeviceAuthOutcome::Unlocked
} else {
outcome(unsafe { error.as_ref() }.and_then(local_code))
};
DispatchQueue::main().exec_async(move || finish_device_auth(request, outcome));
let _ = &held;
});
unsafe {
context.evaluatePolicy_localizedReason_reply(
LAPolicy::DeviceOwnerAuthentication,
&reason,
&reply,
);
}
}
}