adk_website/onboarding/
setup.rs1use adk_core::{AdkError, ErrorCategory, ErrorComponent, Result};
6use adk_kernel::pairing::{
7 ClaimedDevice, DeviceKind, DeviceRecord, DeviceScope, IssueCode, IssuedCode, Pairing,
8};
9use tokio::sync::Mutex;
10
11const OWNER_GROUP: &str = "owner";
13
14pub 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 pub fn new(pairing: Pairing, owner: impl Into<String>) -> Self {
59 Self { pairing, owner: owner.into(), paired: Mutex::new(None) }
60 }
61
62 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 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 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 pub async fn paired(&self) -> bool {
117 self.paired.lock().await.is_some()
118 }
119}
120
121pub fn holding_page(site_name: &str) -> String {
129 let name = site_name
130 .replace('&', "&")
131 .replace('<', "<")
132 .replace('>', ">")
133 .replace('"', """);
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}