use serde_json::Value;
use crate::{AuthError, Support};
pub fn support() -> Support {
imp::support()
}
pub fn platform_authenticator_available() -> impl std::future::Future<Output = bool> + Send {
let (tx, rx) = day_async::oneshot();
imp::available(Box::new(move |available| tx.send(available)));
async move { rx.await.unwrap_or(false) }
}
pub fn create(
options: &Value,
) -> impl std::future::Future<Output = Result<Value, AuthError>> + Send {
let request = check_creation_options(options);
let (tx, rx) = day_async::oneshot();
match request {
Ok(json) => imp::create(json, Box::new(move |answer| tx.send(answer))),
Err(e) => tx.send(Err(e)),
}
async move { rx.await.unwrap_or(Err(AuthError::Cancelled)) }
}
pub fn get(options: &Value) -> impl std::future::Future<Output = Result<Value, AuthError>> + Send {
let request = check_request_options(options);
let (tx, rx) = day_async::oneshot();
match request {
Ok(json) => imp::get(json, Box::new(move |answer| tx.send(answer))),
Err(e) => tx.send(Err(e)),
}
async move { rx.await.unwrap_or(Err(AuthError::Cancelled)) }
}
type OnDone = Box<dyn FnOnce(Result<Value, AuthError>) + Send>;
fn text(options: &Value, path: &[&str]) -> Option<String> {
let mut cur = options;
for key in path {
cur = cur.get(key)?;
}
cur.as_str().map(str::to_string)
}
fn check_creation_options(options: &Value) -> Result<String, AuthError> {
if !options.is_object() {
return Err(AuthError::InvalidRequest(
"the options must be a JSON object".into(),
));
}
for (path, what) in [
(&["rp", "id"][..], "rp.id"),
(&["rp", "name"][..], "rp.name"),
(&["user", "id"][..], "user.id"),
(&["user", "name"][..], "user.name"),
(&["challenge"][..], "challenge"),
] {
if text(options, path).unwrap_or_default().is_empty() {
return Err(AuthError::InvalidRequest(format!(
"the creation options need {what}"
)));
}
}
if options
.get("pubKeyCredParams")
.and_then(Value::as_array)
.is_none_or(std::vec::Vec::is_empty)
{
return Err(AuthError::InvalidRequest(
"the creation options need pubKeyCredParams".into(),
));
}
serde_json::to_string(options).map_err(|e| AuthError::InvalidRequest(e.to_string()))
}
fn check_request_options(options: &Value) -> Result<String, AuthError> {
if !options.is_object() {
return Err(AuthError::InvalidRequest(
"the options must be a JSON object".into(),
));
}
if text(options, &["challenge"]).unwrap_or_default().is_empty() {
return Err(AuthError::InvalidRequest(
"the request options need a challenge".into(),
));
}
serde_json::to_string(options).map_err(|e| AuthError::InvalidRequest(e.to_string()))
}
#[cfg(any(
target_os = "ios",
target_os = "macos",
target_os = "android",
target_arch = "wasm32"
))]
fn read_answer(answer: Result<String, day_bridge::Error>) -> Result<Value, AuthError> {
match answer {
Ok(text) => match text.as_str() {
"cancelled" => Err(AuthError::Cancelled),
"unsupported" => Err(AuthError::Unsupported),
"invalid_state" => Err(AuthError::Provider {
error: "invalid_state".into(),
description: Some(
"a passkey for this account already exists on this device".into(),
),
}),
"not_allowed" => Err(AuthError::Provider {
error: "not_allowed".into(),
description: Some("the authenticator refused the request".into()),
}),
other if other.starts_with("error:") => {
Err(AuthError::Platform(other[6..].to_string()))
}
json => serde_json::from_str(json)
.map_err(|e| AuthError::Platform(format!("credential JSON: {e}"))),
},
Err(e) => Err(AuthError::from(e)),
}
}
#[cfg(any(
target_os = "ios",
target_os = "macos",
target_os = "android",
target_arch = "wasm32"
))]
mod imp {
use super::*;
use crate::native::{
create_passkey_native_async, get_passkey_native_async, passkeys_available_native_async,
passkeys_available_native_support,
};
pub fn support() -> Support {
passkeys_available_native_support()
}
pub fn available(on_done: Box<dyn FnOnce(bool) + Send>) {
let _ = passkeys_available_native_async(move |answer| on_done(answer == Ok(1)));
}
#[expect(
clippy::needless_pass_by_value,
reason = "every platform's `imp` module has this signature"
)]
pub fn create(options_json: String, on_done: OnDone) {
let _ =
create_passkey_native_async(&options_json, move |answer| on_done(read_answer(answer)));
}
#[expect(
clippy::needless_pass_by_value,
reason = "every platform's `imp` module has this signature"
)]
pub fn get(options_json: String, on_done: OnDone) {
let _ = get_passkey_native_async(&options_json, move |answer| on_done(read_answer(answer)));
}
}
#[cfg(target_os = "windows")]
#[path = "passkeys_windows.rs"]
mod imp;
#[cfg(not(any(
target_os = "ios",
target_os = "macos",
target_os = "android",
target_os = "windows",
target_arch = "wasm32"
)))]
mod imp {
use super::*;
pub fn support() -> Support {
Support::Unsupported
}
pub fn available(on_done: Box<dyn FnOnce(bool) + Send>) {
on_done(false);
}
pub fn create(_options_json: String, on_done: OnDone) {
on_done(Err(AuthError::Unsupported));
}
pub fn get(_options_json: String, on_done: OnDone) {
on_done(Err(AuthError::Unsupported));
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn creation_options_are_checked_before_any_platform_call() {
let good = json!({
"rp": {"id": "example.com", "name": "Example"},
"user": {"id": "dXNlcg", "name": "alice", "displayName": "Alice"},
"challenge": "Y2hhbGxlbmdl",
"pubKeyCredParams": [{"type": "public-key", "alg": -7}]
});
assert!(check_creation_options(&good).is_ok());
let mut missing = good.clone();
missing["user"]["id"] = Value::Null;
std::assert_matches!(
check_creation_options(&missing),
Err(AuthError::InvalidRequest(_))
);
let mut no_params = good.clone();
no_params["pubKeyCredParams"] = json!([]);
std::assert_matches!(
check_creation_options(&no_params),
Err(AuthError::InvalidRequest(_))
);
std::assert_matches!(
check_creation_options(&json!("x")),
Err(AuthError::InvalidRequest(_))
);
}
#[test]
fn request_options_need_a_challenge() {
assert!(check_request_options(&json!({"challenge": "abc"})).is_ok());
std::assert_matches!(
check_request_options(&json!({"rpId": "x"})),
Err(AuthError::InvalidRequest(_))
);
}
#[test]
fn support_and_availability_agree() {
let s = support();
let (tx, rx) = std::sync::mpsc::channel();
imp::available(Box::new(move |a| {
let _ = tx.send(a);
}));
let available = rx.recv().unwrap_or(false);
if s == Support::Unsupported {
assert!(!available);
}
}
}