Milestone 3: the hub
lunehub serves accounts, invites, pairing codes, memberships, devices and vaults as plain bare repos (SPEC §8), checks device key and role on every Git request, refuses secrets in a pre-receive hook (P3) and logs every access change. Ships as one container (Dockerfile, compose.yaml). lunesync gains join, login, pair, vault new/upload, invite, grant, members and hub log; `run` picks up new vaults and roles from the hub. Read members' edits stay local. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
159
core/src/hub.rs
Normal file
159
core/src/hub.rs
Normal file
@@ -0,0 +1,159 @@
|
||||
//! 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<HubVault>,
|
||||
}
|
||||
|
||||
#[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<String>,
|
||||
}
|
||||
|
||||
#[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)))
|
||||
.build()
|
||||
.into()
|
||||
}
|
||||
|
||||
fn base(url: &str) -> String {
|
||||
url.trim_end_matches('/').to_string()
|
||||
}
|
||||
|
||||
fn finish<T: DeserializeOwned>(res: Result<ureq::http::Response<ureq::Body>, ureq::Error>, url: &str) -> Result<T> {
|
||||
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/<token>`), 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<Welcome> {
|
||||
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<T: DeserializeOwned>(&self, path: &str) -> Result<T> {
|
||||
let res = agent().get(format!("{}{path}", self.url)).header("Authorization", self.auth()).call();
|
||||
finish(res, &self.url)
|
||||
}
|
||||
|
||||
fn post<T: DeserializeOwned>(&self, path: &str, body: Value) -> Result<T> {
|
||||
let res = agent().post(format!("{}{path}", self.url)).header("Authorization", self.auth()).send_json(body);
|
||||
finish(res, &self.url)
|
||||
}
|
||||
|
||||
pub fn me(&self) -> Result<Me> {
|
||||
self.get("/api/me")
|
||||
}
|
||||
|
||||
/// A short code another of this person's devices can log in with.
|
||||
pub fn pair(&self) -> Result<String> {
|
||||
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<HubVault> {
|
||||
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<String> {
|
||||
let grants: Vec<Value> = 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<Vec<Member>> {
|
||||
self.post("/api/members", json!({ "vault": vault }))
|
||||
}
|
||||
|
||||
pub fn log(&self, count: usize) -> Result<Vec<LogEntry>> {
|
||||
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(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Is `role` allowed to share changes?
|
||||
pub fn can_edit(role: &str) -> bool {
|
||||
role == "edit" || role == "manage"
|
||||
}
|
||||
Reference in New Issue
Block a user