Skip to main content

adk_website/onboarding/
setup.rs

1//! The setup code (spec 3.5 §7.17, A-I20): a freshly started site cannot be claimed without
2//! it. The code pairs the owner's device through the kernel's pairing; until then the site
3//! serves a holding page and accepts no onboarding input.
4
5use adk_core::{AdkError, ErrorCategory, ErrorComponent, Result};
6use adk_kernel::pairing::{
7    ClaimedDevice, DeviceKind, DeviceRecord, DeviceScope, IssueCode, IssuedCode, Pairing,
8};
9use tokio::sync::Mutex;
10
11/// The approval group the owner's device answers decisions in.
12const OWNER_GROUP: &str = "owner";
13
14/// The setup-code gate of a fresh deployment (spec 3.5 §7.17, A-I20).
15///
16/// # Example
17///
18/// ```rust
19/// use std::sync::Arc;
20/// use adk_kernel::pairing::{InMemoryDeviceStore, Pairing};
21/// use adk_website::onboarding::SetupGate;
22///
23/// # #[tokio::main(flavor = "current_thread")]
24/// # async fn main() {
25/// let gate = SetupGate::new(Pairing::new(Arc::new(InMemoryDeviceStore::new())), "owner");
26/// assert!(gate.admit(None).await.is_err(), "no input before pairing");
27/// let issued = gate.issue().await.unwrap();
28/// let claimed = gate.claim(&issued.code, "Amina's phone").await.unwrap();
29/// assert_eq!(gate.admit(Some(&claimed.token)).await.unwrap().owner, "owner");
30/// # }
31/// ```
32pub struct SetupGate {
33    pairing: Pairing,
34    owner: String,
35    paired: Mutex<Option<String>>,
36}
37
38impl std::fmt::Debug for SetupGate {
39    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
40        f.debug_struct("SetupGate").field("owner", &self.owner).finish_non_exhaustive()
41    }
42}
43
44fn unpaired(reason: &str) -> AdkError {
45    AdkError::new(
46        ErrorComponent::Server,
47        ErrorCategory::Unauthorized,
48        "website.setup.unpaired",
49        format!(
50            "{reason}: this site accepts no onboarding input until its setup code pairs the \
51             owner's device; the code is in the site's logs (spec 3.5 A-I20)"
52        ),
53    )
54}
55
56impl SetupGate {
57    /// The gate over the kernel's `pairing`; the device it pairs acts as `owner`.
58    pub fn new(pairing: Pairing, owner: impl Into<String>) -> Self {
59        Self { pairing, owner: owner.into(), paired: Mutex::new(None) }
60    }
61
62    /// Issues the setup code and writes it to the logs, where the host shows it (spec 3.5
63    /// §7.17): a pairing code for a phone that reads, decides and stops.
64    ///
65    /// # Errors
66    ///
67    /// Returns the pairing store's error.
68    pub async fn issue(&self) -> Result<IssuedCode> {
69        let issued = self
70            .pairing
71            .issue(
72                IssueCode::new(self.owner.clone(), [OWNER_GROUP])
73                    .with_scopes(DeviceScope::ALL)
74                    .with_kind(DeviceKind::Phone)
75                    .with_name("Owner's device"),
76            )
77            .await
78            .map_err(|error| AdkError::config(error.to_string()))?;
79        tracing::info!(
80            setup.code = %issued.code,
81            setup.expires_at = %issued.expires_at,
82            "website setup code: enter it on the device that will own this site"
83        );
84        Ok(issued)
85    }
86
87    /// Claims the setup code from the owner's device; the device's token is returned once.
88    ///
89    /// # Errors
90    ///
91    /// `Unauthorized` for an unknown, used or expired code.
92    pub async fn claim(&self, code: &str, device: &str) -> Result<ClaimedDevice> {
93        let claimed = self
94            .pairing
95            .claim(code, Some(device))
96            .await
97            .map_err(|error| unpaired(&error.to_string()))?;
98        *self.paired.lock().await = Some(claimed.device.id.clone());
99        Ok(claimed)
100    }
101
102    /// Admits one piece of onboarding input from the device holding `token` (A-I20).
103    ///
104    /// # Errors
105    ///
106    /// `Unauthorized` without a token, or for a token the kernel's pairing does not
107    /// authenticate.
108    pub async fn admit(&self, token: Option<&str>) -> Result<DeviceRecord> {
109        let Some(token) = token else {
110            return Err(unpaired("no device token"));
111        };
112        self.pairing.authenticate(token).await.map_err(|error| unpaired(&error.to_string()))
113    }
114
115    /// Whether the owner's device has paired.
116    pub async fn paired(&self) -> bool {
117        self.paired.lock().await.is_some()
118    }
119}
120
121/// The page a fresh site serves until onboarding launches it (spec 3.5 §7.17).
122///
123/// # Example
124///
125/// ```rust
126/// assert!(adk_website::onboarding::holding_page("Juniper Bakery").contains("Juniper Bakery"));
127/// ```
128pub fn holding_page(site_name: &str) -> String {
129    let name = site_name
130        .replace('&', "&amp;")
131        .replace('<', "&lt;")
132        .replace('>', "&gt;")
133        .replace('"', "&quot;");
134    format!(
135        "<!doctype html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<meta name=\"viewport\" \
136         content=\"width=device-width, initial-scale=1\">\n<title>{name}</title>\n</head>\n<body>\n\
137         <main>\n<h1>{name}</h1>\n<p>This site is being set up. Please come back soon.</p>\n</main>\n\
138         </body>\n</html>\n"
139    )
140}