Skip to main content

adk_surface/mobile/
mod.rs

1//! The phone (spec 3.3 §5.4, §8.2; feature `mobile`): the web home installed on a phone,
2//! woken by push from the person's own kernel, approving high-risk calls after "Confirm it's
3//! you".
4//!
5//! [`router`] serves the phone's routes under `/surface`, relative to the `/api` prefix, beside
6//! [`web::router`](crate::web::router) and [`web::devices_router`](crate::web::devices_router)
7//! over the same engine. Their wire types are in [`web`](crate::web), so the API document is
8//! the same in every `web` build.
9//!
10//! | Route (under `/api`) | Who | Answer |
11//! |---|---|---|
12//! | `GET /surface/phone` | A phone, the web home | [`PhoneInfo`](crate::web::PhoneInfo) |
13//! | `PUT`, `DELETE /surface/phone/push` | A phone | Subscribes to wake-ups, or stops them |
14//! | `POST /surface/phone/push/received` | A phone | Acknowledges a wake-up |
15//! | `GET /surface/phone/push/deliveries` | The operator | [`DeliveriesResponse`](crate::web::DeliveriesResponse) |
16//! | `POST /surface/phone/passkey/options`, `POST /surface/phone/passkey` | A phone within 10 minutes of pairing, the web home | Sets up the passkey |
17//! | `DELETE /surface/phone/passkey/{id}` | The web home | Removes a computer passkey |
18//! | `POST /surface/decisions/{id}/confirm/options` | A phone, the web home | [`ConfirmOptions`](crate::web::ConfirmOptions), bound to one answer |
19//! | `POST /surface/decisions/{id}/confirm` | A phone, the web home | The answer, decided with presence |
20//! | `POST /surface/phone/qr` | The operator | The pairing link's QR code, as SVG |
21//! | `GET /surface/phone/devices` | The operator | [`PhoneDevicesResponse`](crate::web::PhoneDevicesResponse) |
22//!
23//! A paired device whose kind is not `phone` gets `403 surface.not_here` on every one of them.
24//! Without a home URL they answer `400 surface.phone.needs_home_url`.
25//!
26//! **Wake-ups carry nothing** (§11 S-I5): every push body is `{"v":1,"id":"…"}`, and the
27//! service worker shows the fixed words "A decision is waiting" / "Open the app to see it".
28//! A wake-up waits through quiet time; when quiet time ends each phone whose person has a
29//! waiting decision gets one. [`PushDoorbell`] hears about each decision; [`Phone::start_push`]
30//! sends.
31
32mod doorbell;
33mod error;
34mod passkey;
35mod push;
36mod qr;
37mod quiet;
38mod routes;
39mod store;
40#[cfg(test)]
41mod tests;
42mod vapid;
43mod webauthn;
44
45use std::sync::Arc;
46use std::time::Duration;
47
48use adk_core::audit_log::AuditTrail;
49use adk_core::{ApprovalService, Clock, SystemClock};
50use adk_kernel::QuietHours;
51use adk_kernel::pairing::Pairing;
52use axum::http::Uri;
53use tokio::task::JoinHandle;
54
55pub use doorbell::PushDoorbell;
56pub use error::MobileError;
57pub use push::PushAllowlist;
58pub use routes::router;
59pub use vapid::PushKey;
60
61use crate::engine::SurfaceEngine;
62use passkey::{PasskeyVerifier, Passkeys, RelyingParty};
63use push::{Deliveries, PushSender};
64use quiet::{KernelQuiet, QuietTime, Windows};
65use store::Attachments;
66use vapid::Vapid;
67use webauthn::WebauthnVerifier;
68
69/// The audit action of a wake-up held, sent or dropped (spec 3.3 §11).
70pub const SURFACE_AUDIT_NOTIFY: &str = "surface.notify";
71/// The audit action of a phone's push subscription, made or removed.
72pub const SURFACE_AUDIT_PHONE_PUSH: &str = "surface.phone.push";
73/// The audit action of a passkey set up or removed.
74pub const SURFACE_AUDIT_PHONE_PASSKEY: &str = "surface.phone.passkey";
75
76/// How often the push task looks whether quiet time has ended.
77const QUIET_POLL: Duration = Duration::from_secs(60);
78/// The first wait before a failed push is sent again.
79const PUSH_BACKOFF: Duration = Duration::from_secs(2);
80
81/// The home's public URL, and the passkeys' relying party it gives.
82#[derive(Debug, Clone)]
83pub(crate) struct Home {
84    pub(crate) url: String,
85    pub(crate) rp: RelyingParty,
86}
87
88impl Home {
89    /// `url` must be https, or http on `localhost` for tests: WebAuthn needs a secure context
90    /// and refuses IP addresses.
91    fn parse(url: &str) -> Result<Self, MobileError> {
92        let url = url.trim_end_matches('/').to_string();
93        let invalid = |reason: &str| {
94            MobileError::Surface(crate::error::SurfaceError::Invalid(format!(
95                "the home URL {url} {reason}: give the https URL people open the home at"
96            )))
97        };
98        let uri: Uri = url.parse().map_err(|_| invalid("is not a URL"))?;
99        let (Some(scheme), Some(authority)) = (uri.scheme_str(), uri.authority()) else {
100            return Err(invalid("is not an absolute URL"));
101        };
102        let host = authority.host().to_ascii_lowercase();
103        if host.starts_with('[') || host.parse::<std::net::IpAddr>().is_ok() {
104            return Err(invalid("is an IP address, which passkeys refuse"));
105        }
106        if scheme != "https" && !(scheme == "http" && host == "localhost") {
107            return Err(invalid("is not https"));
108        }
109        let origin = format!("{scheme}://{}", authority.as_str().to_ascii_lowercase());
110        Ok(Self { url, rp: RelyingParty { id: host, origin } })
111    }
112}
113
114/// The phone's parts (spec 3.3 §5.4): build it with [`Phone::builder`], serve it with
115/// [`router`], and start its wake-ups with [`Phone::start_push`].
116///
117/// # Example
118///
119/// ```rust
120/// use std::sync::Arc;
121/// use adk_core::{InMemoryApprovalStore, StoreApprovalService};
122/// use adk_kernel::pairing::{InMemoryDeviceStore, Pairing};
123/// use adk_session::InMemorySessionService;
124/// use adk_surface::mobile::{Phone, PushDoorbell, PushKey};
125/// use adk_surface::{LocalSource, SurfaceEngine};
126///
127/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
128/// let doorbell = Arc::new(PushDoorbell::new());
129/// let approvals = Arc::new(
130///     StoreApprovalService::new(Arc::new(InMemoryApprovalStore::new())).with_notifier(doorbell.clone()),
131/// );
132/// let source = LocalSource::builder("adk-rust")
133///     .sessions(Arc::new(InMemorySessionService::new()))
134///     .approvals(approvals.clone())
135///     .build()?;
136/// let engine = SurfaceEngine::builder(Arc::new(source)).stops_need("operator").build();
137/// let pairing = Pairing::new(Arc::new(InMemoryDeviceStore::new()));
138/// let phone = Phone::builder(engine, pairing)
139///     .home_url("https://home.example.ts.net")
140///     .push_key(PushKey::generate()?)
141///     .doorbell(doorbell)
142///     .approvals(approvals)
143///     .build()?;
144/// let routes = adk_surface::mobile::router(phone.clone());
145/// # let _ = routes;
146/// # Ok(())
147/// # }
148/// ```
149#[derive(Clone)]
150pub struct Phone {
151    pub(crate) inner: Arc<Inner>,
152}
153
154impl std::fmt::Debug for Phone {
155    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
156        f.debug_struct("Phone")
157            .field("home", &self.inner.home.as_ref().map(|home| &home.url))
158            .finish_non_exhaustive()
159    }
160}
161
162pub(crate) struct Inner {
163    pub(crate) engine: SurfaceEngine,
164    pub(crate) pairing: Pairing,
165    pub(crate) home: Option<Home>,
166    pub(crate) store: Attachments,
167    pub(crate) sender: PushSender,
168    pub(crate) quiet: Arc<dyn QuietTime>,
169    pub(crate) approvals: Option<Arc<dyn ApprovalService>>,
170    pub(crate) audit: Option<AuditTrail>,
171    pub(crate) clock: Arc<dyn Clock>,
172    pub(crate) deliveries: Arc<Deliveries>,
173    pub(crate) passkeys: Passkeys,
174    pub(crate) doorbell: Arc<PushDoorbell>,
175    pub(crate) operator: String,
176    pub(crate) poll: Duration,
177}
178
179impl Phone {
180    /// A builder over `engine` and the kernel's `pairing`.
181    pub fn builder(engine: SurfaceEngine, pairing: Pairing) -> PhoneBuilder {
182        PhoneBuilder {
183            engine,
184            pairing,
185            home_url: None,
186            push_key: None,
187            contact: None,
188            allowlist: PushAllowlist::default(),
189            quiet: Vec::new(),
190            approvals: None,
191            audit: None,
192            clock: Arc::new(SystemClock),
193            doorbell: None,
194            operator: "operator".to_string(),
195            poll: QUIET_POLL,
196            backoff: PUSH_BACKOFF,
197            kernel: None,
198        }
199    }
200
201    /// The doorbell to add to the approval service.
202    pub fn doorbell(&self) -> Arc<PushDoorbell> {
203        Arc::clone(&self.inner.doorbell)
204    }
205
206    /// The home's public URL, when it has one.
207    pub fn home_url(&self) -> Option<&str> {
208        self.inner.home.as_ref().map(|home| home.url.as_str())
209    }
210
211    /// Starts sending wake-ups (spec 3.3 §5.4): one for each decision the doorbell hears about,
212    /// held through quiet time; one per phone at the start and when quiet time ends. The task
213    /// stops when it is aborted or the doorbell is dropped.
214    ///
215    /// # Errors
216    ///
217    /// Returns [`MobileError::NeedsHomeUrl`] without a home URL, and an invalid-input error
218    /// without an approval service to read waiting decisions from.
219    pub fn start_push(&self) -> Result<JoinHandle<()>, MobileError> {
220        let inner = &self.inner;
221        if inner.home.is_none() {
222            return Err(MobileError::NeedsHomeUrl);
223        }
224        let Some(approvals) = inner.approvals.clone() else {
225            return Err(MobileError::Surface(crate::error::SurfaceError::Invalid(
226                "wake-ups read the waiting decisions: build the phone with .approvals(service)"
227                    .into(),
228            )));
229        };
230        let ringer = doorbell::Ringer {
231            pairing: inner.pairing.clone(),
232            store: inner.store.clone(),
233            sender: inner.sender.clone(),
234            quiet: Arc::clone(&inner.quiet),
235            approvals,
236            audit: inner.audit.clone(),
237            clock: Arc::clone(&inner.clock),
238            deliveries: Arc::clone(&inner.deliveries),
239            poll: inner.poll,
240        };
241        Ok(tokio::spawn(ringer.run(inner.doorbell.receiver())))
242    }
243}
244
245/// Builds a [`Phone`].
246pub struct PhoneBuilder {
247    engine: SurfaceEngine,
248    pairing: Pairing,
249    home_url: Option<String>,
250    push_key: Option<PushKey>,
251    contact: Option<String>,
252    allowlist: PushAllowlist,
253    quiet: Vec<QuietHours>,
254    approvals: Option<Arc<dyn ApprovalService>>,
255    audit: Option<AuditTrail>,
256    clock: Arc<dyn Clock>,
257    doorbell: Option<Arc<PushDoorbell>>,
258    operator: String,
259    poll: Duration,
260    backoff: Duration,
261    kernel: Option<adk_kernel::Kernel>,
262}
263
264impl std::fmt::Debug for PhoneBuilder {
265    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
266        f.debug_struct("PhoneBuilder").field("home_url", &self.home_url).finish_non_exhaustive()
267    }
268}
269
270impl PhoneBuilder {
271    /// The https URL people open the home at, such as `https://home.example.ts.net`: the
272    /// passkeys' relying party and the pairing links' base. Without it the phone's routes
273    /// answer `400 surface.phone.needs_home_url`.
274    #[must_use]
275    pub fn home_url(mut self, url: impl Into<String>) -> Self {
276        self.home_url = Some(url.into());
277        self
278    }
279
280    /// The push key; without one a key is made for this process only, and phones subscribe
281    /// again after a restart.
282    #[must_use]
283    pub fn push_key(mut self, key: PushKey) -> Self {
284        self.push_key = Some(key);
285        self
286    }
287
288    /// The contact push services see (`mailto:` or an https URL); the home URL by default.
289    #[must_use]
290    pub fn contact(mut self, contact: impl Into<String>) -> Self {
291        self.contact = Some(contact.into());
292        self
293    }
294
295    /// The push services a phone may subscribe through; the browsers' own by default.
296    #[must_use]
297    pub fn push_allowlist(mut self, allowlist: PushAllowlist) -> Self {
298        self.allowlist = allowlist;
299        self
300    }
301
302    /// A quiet time wake-ups wait through, for a phone served without a kernel; may be given
303    /// more than once. [`kernel`](Self::kernel) replaces it.
304    #[must_use]
305    pub fn quiet_hours(mut self, quiet: QuietHours) -> Self {
306        self.quiet.push(quiet);
307        self
308    }
309
310    /// The kernel whose quiet time wake-ups wait through (spec 3.3 §5.4, §10 K3): the area of
311    /// the decision's run, the default area otherwise, as the person changed it while the
312    /// kernel runs.
313    #[must_use]
314    pub fn kernel(mut self, kernel: adk_kernel::Kernel) -> Self {
315        self.kernel = Some(kernel);
316        self
317    }
318
319    /// The approval service whose waiting decisions wake the phones.
320    #[must_use]
321    pub fn approvals(mut self, approvals: Arc<dyn ApprovalService>) -> Self {
322        self.approvals = Some(approvals);
323        self
324    }
325
326    /// Where `surface.notify`, `surface.phone.push` and `surface.phone.passkey` are recorded.
327    #[must_use]
328    pub fn audit(mut self, trail: AuditTrail) -> Self {
329        self.audit = Some(trail);
330        self
331    }
332
333    /// The clock; the system's by default.
334    #[must_use]
335    pub fn clock(mut self, clock: Arc<dyn Clock>) -> Self {
336        self.clock = clock;
337        self
338    }
339
340    /// The doorbell added to the approval service; a new one by default.
341    #[must_use]
342    pub fn doorbell(mut self, doorbell: Arc<PushDoorbell>) -> Self {
343        self.doorbell = Some(doorbell);
344        self
345    }
346
347    /// The group of the operator, who reads deliveries, draws pairing QR codes and lists the
348    /// phones; `operator` by default.
349    #[must_use]
350    pub fn operator_group(mut self, group: impl Into<String>) -> Self {
351        self.operator = group.into();
352        self
353    }
354
355    /// How often the push task looks whether quiet time has ended; a minute by default.
356    #[must_use]
357    pub fn quiet_poll(mut self, every: Duration) -> Self {
358        self.poll = every.max(Duration::from_millis(10));
359        self
360    }
361
362    /// The first wait before a failed push is sent again; two seconds by default.
363    #[must_use]
364    pub fn push_backoff(mut self, wait: Duration) -> Self {
365        self.backoff = wait;
366        self
367    }
368
369    /// The phone.
370    ///
371    /// # Errors
372    ///
373    /// Returns an invalid-input error when the home URL is not https (or http on
374    /// `localhost`) or is an IP address, [`MobileError::PasskeyRefused`] when its host cannot
375    /// hold passkeys, [`MobileError::PushKey`] when no key can be made, and
376    /// [`MobileError::Source`] (`surface.phone.push_client`) when the push client cannot be
377    /// built.
378    pub fn build(self) -> Result<Phone, MobileError> {
379        let home = self.home_url.as_deref().map(Home::parse).transpose()?;
380        let verifier = home
381            .as_ref()
382            .map(|home| WebauthnVerifier::new(&home.rp))
383            .transpose()?
384            .map(|verifier| Arc::new(verifier) as Arc<dyn PasskeyVerifier>);
385        let key = match self.push_key {
386            Some(key) => key,
387            None => {
388                if home.is_some() {
389                    tracing::warn!("no push key given; phones subscribe again after a restart");
390                }
391                PushKey::generate()?
392            }
393        };
394        let contact = self
395            .contact
396            .or_else(|| home.as_ref().map(|home| home.url.clone()))
397            .unwrap_or_else(|| "https://adk-rust.com".to_string());
398        let vapid = Vapid::new(key, contact, Arc::clone(&self.clock));
399        // In the kernel's device store, shared by replicas and cleared with the device.
400        let store = Attachments::new(self.pairing.store().clone());
401        let quiet: Arc<dyn QuietTime> = match self.kernel {
402            Some(kernel) => Arc::new(KernelQuiet(kernel)),
403            None => Arc::new(Windows(self.quiet)),
404        };
405        Ok(Phone {
406            inner: Arc::new(Inner {
407                engine: self.engine,
408                pairing: self.pairing,
409                home,
410                passkeys: Passkeys::new(verifier, store.clone()),
411                store,
412                sender: PushSender::new(vapid, self.allowlist.clone(), self.backoff)?,
413                quiet,
414                approvals: self.approvals,
415                audit: self.audit,
416                clock: self.clock,
417                deliveries: Arc::default(),
418                doorbell: self.doorbell.unwrap_or_default(),
419                operator: self.operator,
420                poll: self.poll,
421            }),
422        })
423    }
424}