mod doorbell;
mod error;
mod passkey;
mod push;
mod qr;
mod quiet;
mod routes;
mod store;
#[cfg(test)]
mod tests;
mod vapid;
mod webauthn;
use std::sync::Arc;
use std::time::Duration;
use adk_core::audit_log::AuditTrail;
use adk_core::{ApprovalService, Clock, SystemClock};
use adk_kernel::QuietHours;
use adk_kernel::pairing::Pairing;
use axum::http::Uri;
use tokio::task::JoinHandle;
pub use doorbell::PushDoorbell;
pub use error::MobileError;
pub use push::PushAllowlist;
pub use routes::router;
pub use vapid::PushKey;
use crate::engine::SurfaceEngine;
use passkey::{PasskeyVerifier, Passkeys, RelyingParty};
use push::{Deliveries, PushSender};
use quiet::{KernelQuiet, QuietTime, Windows};
use store::Attachments;
use vapid::Vapid;
use webauthn::WebauthnVerifier;
pub const SURFACE_AUDIT_NOTIFY: &str = "surface.notify";
pub const SURFACE_AUDIT_PHONE_PUSH: &str = "surface.phone.push";
pub const SURFACE_AUDIT_PHONE_PASSKEY: &str = "surface.phone.passkey";
const QUIET_POLL: Duration = Duration::from_secs(60);
const PUSH_BACKOFF: Duration = Duration::from_secs(2);
#[derive(Debug, Clone)]
pub(crate) struct Home {
pub(crate) url: String,
pub(crate) rp: RelyingParty,
}
impl Home {
fn parse(url: &str) -> Result<Self, MobileError> {
let url = url.trim_end_matches('/').to_string();
let invalid = |reason: &str| {
MobileError::Surface(crate::error::SurfaceError::Invalid(format!(
"the home URL {url} {reason}: give the https URL people open the home at"
)))
};
let uri: Uri = url.parse().map_err(|_| invalid("is not a URL"))?;
let (Some(scheme), Some(authority)) = (uri.scheme_str(), uri.authority()) else {
return Err(invalid("is not an absolute URL"));
};
let host = authority.host().to_ascii_lowercase();
if host.starts_with('[') || host.parse::<std::net::IpAddr>().is_ok() {
return Err(invalid("is an IP address, which passkeys refuse"));
}
if scheme != "https" && !(scheme == "http" && host == "localhost") {
return Err(invalid("is not https"));
}
let origin = format!("{scheme}://{}", authority.as_str().to_ascii_lowercase());
Ok(Self { url, rp: RelyingParty { id: host, origin } })
}
}
#[derive(Clone)]
pub struct Phone {
pub(crate) inner: Arc<Inner>,
}
impl std::fmt::Debug for Phone {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Phone")
.field("home", &self.inner.home.as_ref().map(|home| &home.url))
.finish_non_exhaustive()
}
}
pub(crate) struct Inner {
pub(crate) engine: SurfaceEngine,
pub(crate) pairing: Pairing,
pub(crate) home: Option<Home>,
pub(crate) store: Attachments,
pub(crate) sender: PushSender,
pub(crate) quiet: Arc<dyn QuietTime>,
pub(crate) approvals: Option<Arc<dyn ApprovalService>>,
pub(crate) audit: Option<AuditTrail>,
pub(crate) clock: Arc<dyn Clock>,
pub(crate) deliveries: Arc<Deliveries>,
pub(crate) passkeys: Passkeys,
pub(crate) doorbell: Arc<PushDoorbell>,
pub(crate) operator: String,
pub(crate) poll: Duration,
}
impl Phone {
pub fn builder(engine: SurfaceEngine, pairing: Pairing) -> PhoneBuilder {
PhoneBuilder {
engine,
pairing,
home_url: None,
push_key: None,
contact: None,
allowlist: PushAllowlist::default(),
quiet: Vec::new(),
approvals: None,
audit: None,
clock: Arc::new(SystemClock),
doorbell: None,
operator: "operator".to_string(),
poll: QUIET_POLL,
backoff: PUSH_BACKOFF,
kernel: None,
}
}
pub fn doorbell(&self) -> Arc<PushDoorbell> {
Arc::clone(&self.inner.doorbell)
}
pub fn home_url(&self) -> Option<&str> {
self.inner.home.as_ref().map(|home| home.url.as_str())
}
pub fn start_push(&self) -> Result<JoinHandle<()>, MobileError> {
let inner = &self.inner;
if inner.home.is_none() {
return Err(MobileError::NeedsHomeUrl);
}
let Some(approvals) = inner.approvals.clone() else {
return Err(MobileError::Surface(crate::error::SurfaceError::Invalid(
"wake-ups read the waiting decisions: build the phone with .approvals(service)"
.into(),
)));
};
let ringer = doorbell::Ringer {
pairing: inner.pairing.clone(),
store: inner.store.clone(),
sender: inner.sender.clone(),
quiet: Arc::clone(&inner.quiet),
approvals,
audit: inner.audit.clone(),
clock: Arc::clone(&inner.clock),
deliveries: Arc::clone(&inner.deliveries),
poll: inner.poll,
};
Ok(tokio::spawn(ringer.run(inner.doorbell.receiver())))
}
}
pub struct PhoneBuilder {
engine: SurfaceEngine,
pairing: Pairing,
home_url: Option<String>,
push_key: Option<PushKey>,
contact: Option<String>,
allowlist: PushAllowlist,
quiet: Vec<QuietHours>,
approvals: Option<Arc<dyn ApprovalService>>,
audit: Option<AuditTrail>,
clock: Arc<dyn Clock>,
doorbell: Option<Arc<PushDoorbell>>,
operator: String,
poll: Duration,
backoff: Duration,
kernel: Option<adk_kernel::Kernel>,
}
impl std::fmt::Debug for PhoneBuilder {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("PhoneBuilder").field("home_url", &self.home_url).finish_non_exhaustive()
}
}
impl PhoneBuilder {
#[must_use]
pub fn home_url(mut self, url: impl Into<String>) -> Self {
self.home_url = Some(url.into());
self
}
#[must_use]
pub fn push_key(mut self, key: PushKey) -> Self {
self.push_key = Some(key);
self
}
#[must_use]
pub fn contact(mut self, contact: impl Into<String>) -> Self {
self.contact = Some(contact.into());
self
}
#[must_use]
pub fn push_allowlist(mut self, allowlist: PushAllowlist) -> Self {
self.allowlist = allowlist;
self
}
#[must_use]
pub fn quiet_hours(mut self, quiet: QuietHours) -> Self {
self.quiet.push(quiet);
self
}
#[must_use]
pub fn kernel(mut self, kernel: adk_kernel::Kernel) -> Self {
self.kernel = Some(kernel);
self
}
#[must_use]
pub fn approvals(mut self, approvals: Arc<dyn ApprovalService>) -> Self {
self.approvals = Some(approvals);
self
}
#[must_use]
pub fn audit(mut self, trail: AuditTrail) -> Self {
self.audit = Some(trail);
self
}
#[must_use]
pub fn clock(mut self, clock: Arc<dyn Clock>) -> Self {
self.clock = clock;
self
}
#[must_use]
pub fn doorbell(mut self, doorbell: Arc<PushDoorbell>) -> Self {
self.doorbell = Some(doorbell);
self
}
#[must_use]
pub fn operator_group(mut self, group: impl Into<String>) -> Self {
self.operator = group.into();
self
}
#[must_use]
pub fn quiet_poll(mut self, every: Duration) -> Self {
self.poll = every.max(Duration::from_millis(10));
self
}
#[must_use]
pub fn push_backoff(mut self, wait: Duration) -> Self {
self.backoff = wait;
self
}
pub fn build(self) -> Result<Phone, MobileError> {
let home = self.home_url.as_deref().map(Home::parse).transpose()?;
let verifier = home
.as_ref()
.map(|home| WebauthnVerifier::new(&home.rp))
.transpose()?
.map(|verifier| Arc::new(verifier) as Arc<dyn PasskeyVerifier>);
let key = match self.push_key {
Some(key) => key,
None => {
if home.is_some() {
tracing::warn!("no push key given; phones subscribe again after a restart");
}
PushKey::generate()?
}
};
let contact = self
.contact
.or_else(|| home.as_ref().map(|home| home.url.clone()))
.unwrap_or_else(|| "https://adk-rust.com".to_string());
let vapid = Vapid::new(key, contact, Arc::clone(&self.clock));
let store = Attachments::new(self.pairing.store().clone());
let quiet: Arc<dyn QuietTime> = match self.kernel {
Some(kernel) => Arc::new(KernelQuiet(kernel)),
None => Arc::new(Windows(self.quiet)),
};
Ok(Phone {
inner: Arc::new(Inner {
engine: self.engine,
pairing: self.pairing,
home,
passkeys: Passkeys::new(verifier, store.clone()),
store,
sender: PushSender::new(vapid, self.allowlist.clone(), self.backoff)?,
quiet,
approvals: self.approvals,
audit: self.audit,
clock: self.clock,
deliveries: Arc::default(),
doorbell: self.doorbell.unwrap_or_default(),
operator: self.operator,
poll: self.poll,
}),
})
}
}