Skip to main content

adk_website/ui/
setup.rs

1//! Pairing the owner's device with the setup code (spec 3.5 §7.17, A-I20).
2//!
3//! A freshly started site cannot be claimed without its setup code, which the host prints to
4//! its logs. The code pairs one device through the kernel's pairing; from then on onboarding
5//! input is accepted only from that device's token. Until then the site serves its holding
6//! page and every onboarding input is refused.
7
8use adk_core::Result;
9use schemars::JsonSchema;
10use serde::{Deserialize, Serialize};
11
12use super::{WebsiteDesk, forbidden, invalid};
13
14/// What the setup screen shows (spec 3.5 §7.17).
15#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
16#[serde(rename_all = "camelCase")]
17pub struct SetupView {
18    /// The site's name.
19    pub site_name: String,
20    /// Whether this site asks for a setup code at all.
21    pub needed: bool,
22    /// Whether the owner's device has paired.
23    pub paired: bool,
24    /// Where the code is.
25    pub where_code: String,
26    /// What visitors see until the site is launched.
27    pub holding: String,
28}
29
30/// The device the setup code paired; its token is shown once (spec 3.5 A-I20).
31#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
32#[serde(rename_all = "camelCase")]
33pub struct ClaimedView {
34    /// The device's token: the page keeps it and sends it with every request.
35    pub token: String,
36    /// The device's name.
37    pub device: String,
38    /// When the pairing ends.
39    pub expires_at: chrono::DateTime<chrono::Utc>,
40}
41
42/// `POST …/setup/claim` body.
43#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
44#[serde(rename_all = "camelCase")]
45pub struct ClaimRequest {
46    /// The setup code from the host's logs.
47    pub code: String,
48    /// A name for this device, such as "Amina's laptop".
49    #[serde(default)]
50    pub device: Option<String>,
51}
52
53impl WebsiteDesk {
54    /// The setup screen (spec 3.5 §7.17).
55    pub async fn setup_view(&self) -> SetupView {
56        let paired = match &self.inner.setup {
57            Some(gate) => gate.paired().await,
58            None => true,
59        };
60        SetupView {
61            site_name: self.inner.name.clone(),
62            needed: self.inner.setup.is_some(),
63            paired,
64            where_code: "The setup code is in the site's logs: in the terminal where you started \
65                         it, or in your host's log viewer."
66                .into(),
67            holding: "This site is being set up. Please come back soon.".into(),
68        }
69    }
70
71    /// Claims the setup code from this device (spec 3.5 §7.17, A-I20): one code pairs one
72    /// device, once.
73    ///
74    /// # Errors
75    ///
76    /// `Unauthorized` for an unknown, used or expired code; `Forbidden` when the site needs no
77    /// setup code or a device has paired already.
78    pub async fn claim(&self, code: &str, device: Option<&str>) -> Result<ClaimedView> {
79        let gate = self.inner.setup.as_ref().ok_or_else(|| {
80            forbidden("website.setup.not_needed", "this site was set up without a setup code")
81        })?;
82        let code = code.trim();
83        if code.is_empty() {
84            return Err(invalid("website.setup.code_missing", "enter the setup code"));
85        }
86        let mut paired = self.inner.paired.lock().await;
87        if paired.is_some() || gate.paired().await {
88            return Err(forbidden(
89                "website.setup.already_paired",
90                "a device has already claimed this site; ask its owner to add you",
91            ));
92        }
93        let name =
94            device.map(str::trim).filter(|name| !name.is_empty()).unwrap_or("Owner's device");
95        let claimed = gate.claim(code, name).await?;
96        *paired = Some(claimed.device.id.clone());
97        drop(paired);
98        // The paired device is the only one onboarding admits, after a restart too (A-I20).
99        self.persist().await;
100        tracing::info!(website.site = %self.inner.site.id, device = %claimed.device.id, "website.setup.paired");
101        Ok(ClaimedView {
102            token: claimed.token,
103            device: claimed.device.name.clone(),
104            expires_at: claimed.device.expires_at,
105        })
106    }
107
108    /// Admits one piece of onboarding input carrying `token` (spec 3.5 A-I20): only the
109    /// device the setup code paired gets through. Returns the principal it acts as, the
110    /// device's owner. A desk built without a setup gate admits the authenticated `person`.
111    ///
112    /// # Errors
113    ///
114    /// `Unauthorized` before the code is claimed, without a token, or for another device's.
115    pub async fn admit(&self, person: &str, token: Option<&str>) -> Result<String> {
116        let Some(gate) = &self.inner.setup else { return Ok(person.to_string()) };
117        let record = gate.admit(token).await?;
118        let paired = self.inner.paired.lock().await.clone();
119        if paired.as_deref() != Some(record.id.as_str()) {
120            return Err(adk_core::AdkError::new(
121                adk_core::ErrorComponent::Server,
122                adk_core::ErrorCategory::Unauthorized,
123                "website.setup.unpaired",
124                "this device is not the one the setup code paired; onboarding input comes only \
125                 from the owner's paired device (spec 3.5 A-I20)",
126            ));
127        }
128        Ok(record.owner)
129    }
130}