//! Talking to the hub's API: joining, pairing, and finding out which vaults this device should have. use anyhow::{Context, Result, bail}; use base64::Engine; use serde::de::DeserializeOwned; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; use std::time::Duration; /// This device's link to a hub, stored in the config file. #[derive(Debug, Clone, Serialize, Deserialize)] pub struct HubLink { pub url: String, pub device_id: String, pub key: String, } /// What `join` and `login` hand back. #[derive(Debug, Deserialize)] pub struct Welcome { pub person: String, pub device_id: String, pub key: String, } #[derive(Debug, Clone, Deserialize)] pub struct Me { pub person: String, pub owner: bool, pub device_label: String, pub vaults: Vec, /// Vaults this device must leave (access ended). #[serde(default)] pub leaving: Vec, /// Someone asked this device to share now (Nudge). #[serde(default)] pub nudge: bool, } /// One vault's health, as a device reports it to the hub: counts only, never content. #[derive(Debug, Serialize)] pub struct VaultHealth { pub vault_id: i64, pub last_synced: Option, pub waiting: usize, pub held_secrets: usize, pub holding: bool, } /// A vault this device has to hand over and leave (A6). #[derive(Debug, Clone, Deserialize)] pub struct Departure { pub id: i64, pub vault_id: i64, pub vault: String, pub delete_files: bool, /// A manager chose "delete without saving". pub without_saving: bool, } /// A departure as a manager sees it. #[derive(Debug, Deserialize)] pub struct Handover { pub id: i64, pub vault: String, pub person: String, pub device: String, /// waiting (device hasn't reported in), received (to review), kept, discarded, done, skipped pub state: String, pub at: i64, } #[derive(Debug, Clone, Deserialize)] pub struct HubVault { pub id: i64, pub name: String, pub role: String, pub git_url: String, } #[derive(Debug, Deserialize)] pub struct Member { pub person: String, pub role: String, pub devices: Vec, } #[derive(Debug, Deserialize)] pub struct LogEntry { pub at: i64, pub actor: String, pub action: String, pub detail: String, } fn agent() -> ureq::Agent { ureq::Agent::config_builder() .http_status_as_error(false) .timeout_global(Some(Duration::from_secs(30))) .user_agent(crate::remote::user_agent()) .build() .into() } fn base(url: &str) -> String { url.trim_end_matches('/').to_string() } fn finish(res: Result, ureq::Error>, url: &str) -> Result { let mut res = res.map_err(|e| anyhow::anyhow!("can't reach the hub at {url}: {e}"))?; let status = res.status(); let body: Value = res.body_mut().read_json().unwrap_or(Value::Null); if !status.is_success() { let msg = body.get("error").and_then(Value::as_str).unwrap_or("unexpected answer"); bail!("the hub said: {msg}"); } serde_json::from_value(body).context("the hub's answer didn't make sense") } /// Accepts an invite link (`https://hub/join/`), creating the person's account and this device. pub fn join(link: &str, label: &str) -> Result<(String, Welcome)> { let (url, token) = link.rsplit_once("/join/").context("that doesn't look like an invite link")?; let url = base(url); let res = agent().post(format!("{url}/api/join")).send_json(json!({"token": token, "device_label": label})); Ok((url.clone(), finish(res, &url)?)) } /// Signs this device in with a pairing code from another of the person's devices. pub fn login(url: &str, code: &str, label: &str) -> Result { let url = base(url); let res = agent().post(format!("{url}/api/login")).send_json(json!({"code": code, "device_label": label})); finish(res, &url) } impl HubLink { fn auth(&self) -> String { let raw = format!("{}:{}", self.device_id, self.key); format!("Basic {}", base64::engine::general_purpose::STANDARD.encode(raw)) } fn get(&self, path: &str) -> Result { let res = agent().get(format!("{}{path}", self.url)).header("Authorization", self.auth()).call(); finish(res, &self.url) } fn post(&self, path: &str, body: Value) -> Result { let res = agent().post(format!("{}{path}", self.url)).header("Authorization", self.auth()).send_json(body); finish(res, &self.url) } pub fn me(&self) -> Result { self.get("/api/me") } /// A short code another of this person's devices can log in with. pub fn pair(&self) -> Result { let v: Value = self.post("/api/pair", json!({}))?; Ok(v["code"].as_str().unwrap_or_default().to_string()) } pub fn set_label(&self, label: &str) -> Result<()> { let _: Value = self.post("/api/device/label", json!({ "label": label }))?; Ok(()) } pub fn create_vault(&self, name: &str) -> Result { self.post("/api/vaults", json!({ "name": name })) } /// One-time link for `person` with the given (vault, role) grants. pub fn invite(&self, person: &str, grants: &[(String, String)]) -> Result { let grants: Vec = grants.iter().map(|(v, r)| json!({"vault": v, "role": r})).collect(); let v: Value = self.post("/api/invites", json!({"person": person, "grants": grants}))?; Ok(v["link"].as_str().unwrap_or_default().to_string()) } pub fn grant(&self, person: &str, vault: &str, role: &str) -> Result<()> { let _: Value = self.post("/api/grants", json!({"person": person, "vault": vault, "role": role}))?; Ok(()) } pub fn members(&self, vault: &str) -> Result> { self.post("/api/members", json!({ "vault": vault })) } pub fn log(&self, count: usize) -> Result> { self.get(&format!("/api/log?count={count}")) } pub fn not_a_secret(&self, vault_id: i64, fingerprint: &str) -> Result<()> { let _: Value = self.post("/api/not-secrets", json!({"vault_id": vault_id, "fingerprint": fingerprint}))?; Ok(()) } } impl HubLink { /// A one-time link (2 minutes) that opens the canvas signed in as this device's person. pub fn web_link(&self) -> Result { let v: Value = self.post("/api/web/link", json!({}))?; Ok(v["url"].as_str().unwrap_or_default().to_string()) } pub fn report(&self, vaults: &[VaultHealth]) -> Result<()> { let _: Value = self.post("/api/report", json!({ "vaults": vaults }))?; Ok(()) } pub fn remove(&self, person: &str, vault: &str, without_saving: bool) -> Result { let v: Value = self.post("/api/remove", json!({"person": person, "vault": vault, "without_saving": without_saving}))?; Ok(v["devices"].as_u64().unwrap_or(0) as usize) } pub fn remove_device(&self, label: &str, person: Option<&str>) -> Result<()> { let _: Value = self.post("/api/device/remove", json!({"label": label, "person": person}))?; Ok(()) } pub fn team_remove(&self, person: &str) -> Result<()> { let _: Value = self.post("/api/team/remove", json!({ "person": person }))?; Ok(()) } /// Re-enables a removed person; returns a one-time sign-in link. pub fn team_restore(&self, person: &str) -> Result { let v: Value = self.post("/api/team/restore", json!({ "person": person }))?; Ok(v["link"].as_str().unwrap_or_default().to_string()) } pub fn handovers(&self) -> Result> { self.get("/api/handovers") } /// Changed files in a received handover, as "added/changed/removed path". pub fn handover_show(&self, id: i64) -> Result> { self.post("/api/handovers/show", json!({ "id": id })) } /// keep, discard or skip. pub fn handover_decide(&self, id: i64, decision: &str) -> Result { let v: Value = self.post("/api/handovers/decide", json!({"id": id, "decision": decision}))?; Ok(v["message"].as_str().unwrap_or_default().to_string()) } /// Deletes a vault (team owner); returns how many devices will hand over and remove their copy. pub fn delete_vault(&self, vault: &str) -> Result { let v: Value = self.post("/api/vaults/delete", json!({ "vault": vault }))?; Ok(v["devices"].as_u64().unwrap_or(0) as usize) } pub fn vault_setting(&self, vault: &str, delete_from_devices: bool) -> Result<()> { let _: Value = self.post("/api/vaults/settings", json!({"vault": vault, "delete_from_devices": delete_from_devices}))?; Ok(()) } /// Tells the hub this device has handed over (`head`, if anything) and is leaving. pub fn departure_done(&self, id: i64, head: Option) -> Result<()> { let _: Value = self.post("/api/departures/done", json!({"id": id, "head": head}))?; Ok(()) } } /// Is `role` allowed to share changes? pub fn can_edit(role: &str) -> bool { role == "edit" || role == "manage" }