use adk_core::{AdkError, ErrorCategory, ErrorComponent, Result};
use adk_kernel::pairing::{
ClaimedDevice, DeviceKind, DeviceRecord, DeviceScope, IssueCode, IssuedCode, Pairing,
};
use tokio::sync::Mutex;
const OWNER_GROUP: &str = "owner";
pub struct SetupGate {
pairing: Pairing,
owner: String,
paired: Mutex<Option<String>>,
}
impl std::fmt::Debug for SetupGate {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("SetupGate").field("owner", &self.owner).finish_non_exhaustive()
}
}
fn unpaired(reason: &str) -> AdkError {
AdkError::new(
ErrorComponent::Server,
ErrorCategory::Unauthorized,
"website.setup.unpaired",
format!(
"{reason}: this site accepts no onboarding input until its setup code pairs the \
owner's device; the code is in the site's logs (spec 3.5 A-I20)"
),
)
}
impl SetupGate {
pub fn new(pairing: Pairing, owner: impl Into<String>) -> Self {
Self { pairing, owner: owner.into(), paired: Mutex::new(None) }
}
pub async fn issue(&self) -> Result<IssuedCode> {
let issued = self
.pairing
.issue(
IssueCode::new(self.owner.clone(), [OWNER_GROUP])
.with_scopes(DeviceScope::ALL)
.with_kind(DeviceKind::Phone)
.with_name("Owner's device"),
)
.await
.map_err(|error| AdkError::config(error.to_string()))?;
tracing::info!(
setup.code = %issued.code,
setup.expires_at = %issued.expires_at,
"website setup code: enter it on the device that will own this site"
);
Ok(issued)
}
pub async fn claim(&self, code: &str, device: &str) -> Result<ClaimedDevice> {
let claimed = self
.pairing
.claim(code, Some(device))
.await
.map_err(|error| unpaired(&error.to_string()))?;
*self.paired.lock().await = Some(claimed.device.id.clone());
Ok(claimed)
}
pub async fn admit(&self, token: Option<&str>) -> Result<DeviceRecord> {
let Some(token) = token else {
return Err(unpaired("no device token"));
};
self.pairing.authenticate(token).await.map_err(|error| unpaired(&error.to_string()))
}
pub async fn paired(&self) -> bool {
self.paired.lock().await.is_some()
}
}
pub fn holding_page(site_name: &str) -> String {
let name = site_name
.replace('&', "&")
.replace('<', "<")
.replace('>', ">")
.replace('"', """);
format!(
"<!doctype html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<meta name=\"viewport\" \
content=\"width=device-width, initial-scale=1\">\n<title>{name}</title>\n</head>\n<body>\n\
<main>\n<h1>{name}</h1>\n<p>This site is being set up. Please come back soon.</p>\n</main>\n\
</body>\n</html>\n"
)
}