Milestone 5: canvas for access
The hub now serves a React canvas (web/, embedded at build time): grant by dragging a vault onto a person, revoke by pulling a ribbon until it snaps with an 8 s Undo the hub honours before anything reaches devices, invites (including vaults dropped on invitees), device rename and removal, Float/Dock, and panels with a button for every gesture. Sign-in without passwords (SPEC §8): `lunesync open` one-time link or a pairing code typed on the hub; 30-day HttpOnly session cookie plus an X-Lune header on every canvas request. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -11,6 +11,7 @@ chrono = "0.4.45"
|
||||
getrandom = "0.4.3"
|
||||
lune-core = { version = "0.1.0", path = "../core" }
|
||||
rusqlite = { version = "0.41.0", features = ["bundled"] }
|
||||
rust-embed = { version = "8.13.0", features = ["mime-guess"] }
|
||||
serde = { version = "1.0.229", features = ["derive"] }
|
||||
serde_json = "1.0.154"
|
||||
sha2 = "0.11.1"
|
||||
@@ -18,3 +19,4 @@ tokio = { version = "1.54.1", features = ["full"] }
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile = "3.27.0"
|
||||
ureq = "3.5.0"
|
||||
|
||||
13
hub/build.rs
Normal file
13
hub/build.rs
Normal file
@@ -0,0 +1,13 @@
|
||||
// The canvas is built from web/ (npm run build) and embedded. Without a build, embed a page that says so.
|
||||
fn main() {
|
||||
let dist = std::path::Path::new("../web/dist");
|
||||
if !dist.join("index.html").exists() {
|
||||
std::fs::create_dir_all(dist).unwrap();
|
||||
std::fs::write(
|
||||
dist.join("index.html"),
|
||||
"<!doctype html><title>Lune</title><p>The canvas isn't built yet: run <code>npm run build</code> in <code>web/</code>, then rebuild the hub.</p>",
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
println!("cargo:rerun-if-changed=../web/dist");
|
||||
}
|
||||
@@ -74,9 +74,20 @@ pub fn credentials(headers: &HeaderMap) -> Option<(String, String)> {
|
||||
/// The signed-in device, including one that was removed and may only hand over.
|
||||
pub fn authenticate_any(hub: &Hub, headers: &HeaderMap) -> Result<Caller, ApiError> {
|
||||
let unknown = || ApiError(StatusCode::UNAUTHORIZED, "this device isn't signed in to the hub".into());
|
||||
let (id, key) = credentials(headers).ok_or_else(unknown)?;
|
||||
let conn = hub.db.lock().unwrap();
|
||||
db::caller(&conn, &id, &key)?.ok_or_else(unknown)
|
||||
if let Some((id, key)) = credentials(headers) {
|
||||
let conn = hub.db.lock().unwrap();
|
||||
return db::caller(&conn, &id, &key)?.ok_or_else(unknown);
|
||||
}
|
||||
// The canvas: a session cookie, plus a header other sites can't send (no cross-site requests).
|
||||
if let Some(token) = crate::web::session_token(headers) {
|
||||
if headers.get("x-lune").is_none() {
|
||||
return Err(denied("requests from the canvas need the X-Lune header"));
|
||||
}
|
||||
let conn = hub.db.lock().unwrap();
|
||||
return db::web_caller(&conn, &token)?
|
||||
.ok_or_else(|| ApiError(StatusCode::UNAUTHORIZED, "please sign in again".into()));
|
||||
}
|
||||
Err(unknown())
|
||||
}
|
||||
|
||||
/// The signed-in device, if it still has normal access.
|
||||
|
||||
@@ -62,6 +62,19 @@ CREATE TABLE IF NOT EXISTS departures (
|
||||
created INTEGER NOT NULL,
|
||||
updated INTEGER NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS web_sessions (
|
||||
token_hash TEXT PRIMARY KEY,
|
||||
account_id INTEGER NOT NULL,
|
||||
expires INTEGER NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS pending_removals (
|
||||
id INTEGER PRIMARY KEY,
|
||||
account_id INTEGER NOT NULL,
|
||||
vault_id INTEGER NOT NULL,
|
||||
without_saving INTEGER NOT NULL,
|
||||
due INTEGER NOT NULL,
|
||||
by_who TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS log (
|
||||
id INTEGER PRIMARY KEY,
|
||||
at INTEGER NOT NULL,
|
||||
@@ -151,6 +164,27 @@ pub fn caller(conn: &Connection, device_id: &str, key: &str) -> Result<Option<Ca
|
||||
.optional()?)
|
||||
}
|
||||
|
||||
/// The person signed in to the canvas with this session token. Acts as the person, never as a device.
|
||||
pub fn web_caller(conn: &Connection, token: &str) -> Result<Option<Caller>> {
|
||||
Ok(conn
|
||||
.query_row(
|
||||
"SELECT a.id, a.name, a.owner, a.disabled = 0 FROM web_sessions s JOIN accounts a ON a.id = s.account_id
|
||||
WHERE s.token_hash = ?1 AND s.expires > ?2",
|
||||
params![hash(token), now()],
|
||||
|r| {
|
||||
Ok(Caller {
|
||||
device_id: String::new(),
|
||||
device_label: "web".into(),
|
||||
account_id: r.get(0)?,
|
||||
person: r.get(1)?,
|
||||
owner: r.get(2)?,
|
||||
active: r.get(3)?,
|
||||
})
|
||||
},
|
||||
)
|
||||
.optional()?)
|
||||
}
|
||||
|
||||
/// Creates a device for `account_id`; returns (device id, key). Only the key's hash is kept.
|
||||
pub fn new_device(conn: &Connection, account_id: i64, label: &str) -> Result<(String, String)> {
|
||||
let id = format!("dev_{}", token(10).to_lowercase());
|
||||
|
||||
@@ -34,6 +34,9 @@ pub struct RemoveReq {
|
||||
vault: String,
|
||||
#[serde(default)]
|
||||
without_saving: bool,
|
||||
/// The canvas's Undo window: hold the removal this long before anything reaches their devices (X2).
|
||||
#[serde(default)]
|
||||
delay_seconds: i64,
|
||||
}
|
||||
|
||||
/// Removes a person from one vault (A5). Their other vaults are untouched.
|
||||
@@ -51,23 +54,89 @@ pub async fn remove(State(hub): State<Shared>, headers: HeaderMap, Json(req): Js
|
||||
if db::role(&conn, account_id, vault_id)?.is_none() {
|
||||
return Err(bad(format!("{person} isn't a member of {vault}")));
|
||||
}
|
||||
conn.execute("DELETE FROM memberships WHERE account_id = ?1 AND vault_id = ?2", [account_id, vault_id])?;
|
||||
let n = db::depart(&conn, account_id, vault_id, None, req.without_saving)?;
|
||||
let how = if req.without_saving { " without saving" } else { "" };
|
||||
db::log(&conn, &caller.who(), "access removed", &format!("{person} from {vault}{how} ({})", devices_phrase(n)))?;
|
||||
if req.delay_seconds > 0 {
|
||||
conn.execute(
|
||||
"INSERT INTO pending_removals (account_id, vault_id, without_saving, due, by_who) VALUES (?1, ?2, ?3, ?4, ?5)",
|
||||
params![account_id, vault_id, req.without_saving, db::now() + req.delay_seconds.min(60), caller.who()],
|
||||
)?;
|
||||
return Ok(Json(json!({ "pending": conn.last_insert_rowid() })));
|
||||
}
|
||||
let n = apply_removal(&conn, &caller.who(), account_id, vault_id, req.without_saving)?;
|
||||
Ok(Json(json!({ "devices": n })))
|
||||
}
|
||||
|
||||
/// Ends a membership and opens departures for the person's devices (A6).
|
||||
pub fn apply_removal(conn: &Connection, who: &str, account_id: i64, vault_id: i64, without_saving: bool) -> Result<usize> {
|
||||
let person: String = conn.query_row("SELECT name FROM accounts WHERE id = ?1", [account_id], |r| r.get(0))?;
|
||||
let vault: String = conn.query_row("SELECT name FROM vaults WHERE id = ?1", [vault_id], |r| r.get(0))?;
|
||||
if conn.execute("DELETE FROM memberships WHERE account_id = ?1 AND vault_id = ?2", [account_id, vault_id])? == 0 {
|
||||
return Ok(0);
|
||||
}
|
||||
let n = db::depart(conn, account_id, vault_id, None, without_saving)?;
|
||||
let how = if without_saving { " without saving" } else { "" };
|
||||
db::log(conn, who, "access removed", &format!("{person} from {vault}{how} ({})", devices_phrase(n)))?;
|
||||
Ok(n)
|
||||
}
|
||||
|
||||
/// Applies removals whose Undo window has passed. Runs every second.
|
||||
pub fn apply_due_removals(conn: &Connection) -> Result<()> {
|
||||
let due: Vec<(i64, i64, i64, bool, String)> = {
|
||||
let mut stmt = conn.prepare("SELECT id, account_id, vault_id, without_saving, by_who FROM pending_removals WHERE due <= ?1")?;
|
||||
stmt.query_map([db::now()], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?, r.get(4)?)))?.collect::<Result<_, _>>()?
|
||||
};
|
||||
for (id, account_id, vault_id, without_saving, who) in due {
|
||||
conn.execute("DELETE FROM pending_removals WHERE id = ?1", [id])?;
|
||||
apply_removal(conn, &who, account_id, vault_id, without_saving)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct UndoReq {
|
||||
pending: i64,
|
||||
}
|
||||
|
||||
/// Undo within the window: the removal never happened, nothing reached their devices.
|
||||
pub async fn undo_remove(State(hub): State<Shared>, headers: HeaderMap, Json(req): Json<UndoReq>) -> ApiResult {
|
||||
let caller = authenticate(&hub, &headers)?;
|
||||
let conn = hub.db.lock().unwrap();
|
||||
let found: Option<i64> = conn
|
||||
.query_row("SELECT vault_id FROM pending_removals WHERE id = ?1", [req.pending], |r| r.get(0))
|
||||
.optional()?;
|
||||
let vault_id = found.ok_or_else(|| bad("too late to undo — the removal already went through"))?;
|
||||
if !can_manage(&conn, &caller, vault_id)? {
|
||||
return Err(denied("you need Manage on that vault"));
|
||||
}
|
||||
conn.execute("DELETE FROM pending_removals WHERE id = ?1", [req.pending])?;
|
||||
Ok(Json(json!({})))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct DeviceRemoveReq {
|
||||
#[serde(default)]
|
||||
label: String,
|
||||
person: Option<String>,
|
||||
/// The canvas names devices by id.
|
||||
device_id: Option<String>,
|
||||
}
|
||||
|
||||
/// Removes one device (A1): it hands over and leaves every vault, then its key stops working.
|
||||
pub async fn remove_device(State(hub): State<Shared>, headers: HeaderMap, Json(req): Json<DeviceRemoveReq>) -> ApiResult {
|
||||
let caller = authenticate(&hub, &headers)?;
|
||||
let conn = hub.db.lock().unwrap();
|
||||
let mut req = req;
|
||||
if let Some(id) = &req.device_id {
|
||||
let (label, person): (String, String) = conn
|
||||
.query_row(
|
||||
"SELECT d.label, a.name FROM devices d JOIN accounts a ON a.id = d.account_id WHERE d.id = ?1 AND d.removed = 0",
|
||||
[id],
|
||||
|r| Ok((r.get(0)?, r.get(1)?)),
|
||||
)
|
||||
.optional()?
|
||||
.ok_or_else(|| bad("no such device"))?;
|
||||
req.label = label;
|
||||
req.person = Some(person);
|
||||
}
|
||||
let (account_id, person) = match &req.person {
|
||||
Some(p) if !p.eq_ignore_ascii_case(&caller.person) => {
|
||||
if !caller.owner {
|
||||
@@ -133,6 +202,8 @@ pub async fn team_remove(State(hub): State<Shared>, headers: HeaderMap, Json(req
|
||||
tx.execute("UPDATE devices SET removed = 1 WHERE account_id = ?1", [account_id])?;
|
||||
tx.execute("UPDATE accounts SET disabled = 1 WHERE id = ?1", [account_id])?;
|
||||
tx.execute("DELETE FROM invites WHERE person = ?1 AND used IS NULL", [&person])?;
|
||||
tx.execute("DELETE FROM web_sessions WHERE account_id = ?1", [account_id])?;
|
||||
tx.execute("DELETE FROM pending_removals WHERE account_id = ?1", [account_id])?;
|
||||
let devices: Vec<String> = {
|
||||
let mut stmt = tx.prepare("SELECT id FROM devices WHERE account_id = ?1")?;
|
||||
stmt.query_map([account_id], |r| r.get(0))?.collect::<Result<_, _>>()?
|
||||
|
||||
@@ -5,6 +5,7 @@ mod db;
|
||||
mod git;
|
||||
mod hook;
|
||||
mod leave;
|
||||
mod web;
|
||||
|
||||
use anyhow::Result;
|
||||
use axum::Router;
|
||||
@@ -63,6 +64,18 @@ async fn serve() -> Result<()> {
|
||||
}
|
||||
|
||||
let hub = Arc::new(api::Hub { db: Mutex::new(conn), data, url: url.clone() });
|
||||
// Removals made on the canvas wait out their Undo window, then go through.
|
||||
let ticker = hub.clone();
|
||||
tokio::spawn(async move {
|
||||
let mut every = tokio::time::interval(std::time::Duration::from_secs(1));
|
||||
loop {
|
||||
every.tick().await;
|
||||
let conn = ticker.db.lock().unwrap();
|
||||
if let Err(e) = leave::apply_due_removals(&conn) {
|
||||
eprintln!("hub error: {e:#}");
|
||||
}
|
||||
}
|
||||
});
|
||||
let app = Router::new()
|
||||
.route("/api/join", post(api::join))
|
||||
.route("/api/login", post(api::login))
|
||||
@@ -84,8 +97,17 @@ async fn serve() -> Result<()> {
|
||||
.route("/api/handovers", get(leave::handovers))
|
||||
.route("/api/handovers/show", post(leave::handover_show))
|
||||
.route("/api/handovers/decide", post(leave::handover_decide))
|
||||
.route("/api/remove/undo", post(leave::undo_remove))
|
||||
.route("/api/web/signin", post(web::signin))
|
||||
.route("/api/web/link", post(web::link))
|
||||
.route("/api/web/signout", post(web::signout))
|
||||
.route("/api/canvas", get(web::canvas))
|
||||
.route("/api/invites/grant", post(web::invite_grant))
|
||||
.route("/api/devices/rename", post(web::rename_device))
|
||||
.route("/signin/{token}", get(web::signin_link))
|
||||
.route("/git/{repo}/{*rest}", any(git::serve))
|
||||
.route("/health", get(|| async { "ok" }))
|
||||
.fallback(web::static_files)
|
||||
.layer(DefaultBodyLimit::disable())
|
||||
.with_state(hub);
|
||||
let listener = tokio::net::TcpListener::bind(&listen).await?;
|
||||
|
||||
284
hub/src/web.rs
Normal file
284
hub/src/web.rs
Normal file
@@ -0,0 +1,284 @@
|
||||
//! The web canvas (M5): signing in without passwords, the canvas's state, and serving the app itself.
|
||||
|
||||
use crate::api::{ApiError, ApiResult, Shared, authenticate, bad, can_manage, denied};
|
||||
use crate::db;
|
||||
use axum::Json;
|
||||
use axum::extract::{Path, State};
|
||||
use axum::http::{HeaderMap, HeaderValue, StatusCode, Uri, header};
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use rusqlite::{Connection, OptionalExtension, params};
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
const SESSION_DAYS: i64 = 30;
|
||||
|
||||
#[derive(rust_embed::RustEmbed)]
|
||||
#[folder = "../web/dist"]
|
||||
struct Assets;
|
||||
|
||||
/// The session cookie's value, if the request carries one.
|
||||
pub fn session_token(headers: &HeaderMap) -> Option<String> {
|
||||
let cookies = headers.get(header::COOKIE)?.to_str().ok()?;
|
||||
cookies.split(';').find_map(|c| c.trim().strip_prefix("lune_session=").map(String::from))
|
||||
}
|
||||
|
||||
fn session_cookie(hub: &crate::api::Hub, token: &str, max_age: i64) -> HeaderValue {
|
||||
let secure = if hub.url.starts_with("https://") { "; Secure" } else { "" };
|
||||
HeaderValue::from_str(&format!("lune_session={token}; Path=/; HttpOnly; SameSite=Strict; Max-Age={max_age}{secure}")).unwrap()
|
||||
}
|
||||
|
||||
/// Starts a 30-day canvas session for `account_id` and returns the cookie to set.
|
||||
fn start_session(hub: &crate::api::Hub, conn: &Connection, account_id: i64, how: &str) -> Result<HeaderValue, ApiError> {
|
||||
let disabled: bool = conn.query_row("SELECT disabled FROM accounts WHERE id = ?1", [account_id], |r| r.get(0))?;
|
||||
if disabled {
|
||||
return Err(denied("this account was removed from the team"));
|
||||
}
|
||||
let token = db::token(40);
|
||||
conn.execute(
|
||||
"INSERT INTO web_sessions (token_hash, account_id, expires) VALUES (?1, ?2, ?3)",
|
||||
params![db::hash(&token), account_id, db::now() + SESSION_DAYS * 86400],
|
||||
)?;
|
||||
let person: String = conn.query_row("SELECT name FROM accounts WHERE id = ?1", [account_id], |r| r.get(0))?;
|
||||
db::log(conn, &format!("{person} (web)"), "signed in", how)?;
|
||||
Ok(session_cookie(hub, &token, SESSION_DAYS * 86400))
|
||||
}
|
||||
|
||||
/// Consumes a pairing code (or one-time sign-in token); returns its account.
|
||||
fn use_code(conn: &Connection, code: &str) -> Result<i64, ApiError> {
|
||||
let found: Option<(i64, i64, Option<i64>)> = conn
|
||||
.query_row(
|
||||
"SELECT account_id, expires, used FROM pair_codes WHERE code_hash = ?1",
|
||||
[db::hash(code)],
|
||||
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
|
||||
)
|
||||
.optional()?;
|
||||
match found {
|
||||
Some((a, expires, None)) if expires >= db::now() => {
|
||||
conn.execute("UPDATE pair_codes SET used = ?1 WHERE code_hash = ?2", params![db::now(), db::hash(code)])?;
|
||||
Ok(a)
|
||||
}
|
||||
Some((_, _, Some(_))) => Err(denied("that code was already used — make a new one with `lunesync pair`")),
|
||||
Some(_) => Err(denied("that code has expired — make a new one with `lunesync pair`")),
|
||||
None => Err(denied("that code isn't valid")),
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct SigninReq {
|
||||
code: String,
|
||||
}
|
||||
|
||||
/// Sign in by typing a pairing code from one of your devices.
|
||||
pub async fn signin(State(hub): State<Shared>, Json(req): Json<SigninReq>) -> Result<Response, ApiError> {
|
||||
let code: String = req.code.chars().filter(|c| c.is_ascii_alphanumeric()).collect::<String>().to_uppercase();
|
||||
let conn = hub.db.lock().unwrap();
|
||||
let account_id = use_code(&conn, &code)?;
|
||||
let cookie = start_session(&hub, &conn, account_id, "with a code")?;
|
||||
Ok(([(header::SET_COOKIE, cookie)], Json(json!({}))).into_response())
|
||||
}
|
||||
|
||||
/// `lunesync open`: a one-time link (2 minutes) that signs the browser in as this device's person.
|
||||
pub async fn link(State(hub): State<Shared>, headers: HeaderMap) -> ApiResult {
|
||||
let caller = authenticate(&hub, &headers)?;
|
||||
if caller.device_id.is_empty() {
|
||||
return Err(bad("open the canvas from a device"));
|
||||
}
|
||||
let token = db::token(40);
|
||||
let conn = hub.db.lock().unwrap();
|
||||
conn.execute(
|
||||
"INSERT INTO pair_codes (code_hash, account_id, expires) VALUES (?1, ?2, ?3)",
|
||||
params![db::hash(&token), caller.account_id, db::now() + 120],
|
||||
)?;
|
||||
Ok(Json(json!({ "url": format!("{}/signin/{token}", hub.url) })))
|
||||
}
|
||||
|
||||
/// Following the one-time link: set the session and go to the canvas.
|
||||
pub async fn signin_link(State(hub): State<Shared>, Path(token): Path<String>) -> Response {
|
||||
let conn = hub.db.lock().unwrap();
|
||||
let result = use_code(&conn, &token).and_then(|a| start_session(&hub, &conn, a, "from a device"));
|
||||
match result {
|
||||
Ok(cookie) => (StatusCode::SEE_OTHER, [(header::LOCATION, HeaderValue::from_static("/")), (header::SET_COOKIE, cookie)]).into_response(),
|
||||
Err(_) => (StatusCode::SEE_OTHER, [(header::LOCATION, HeaderValue::from_static("/signin?expired=1"))]).into_response(),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn signout(State(hub): State<Shared>, headers: HeaderMap) -> Response {
|
||||
if let Some(token) = session_token(&headers) {
|
||||
let conn = hub.db.lock().unwrap();
|
||||
let _ = conn.execute("DELETE FROM web_sessions WHERE token_hash = ?1", [db::hash(&token)]);
|
||||
}
|
||||
([(header::SET_COOKIE, session_cookie(&hub, "", 0))], Json(json!({}))).into_response()
|
||||
}
|
||||
|
||||
/// Everything the canvas shows, limited to what this person may see.
|
||||
pub async fn canvas(State(hub): State<Shared>, headers: HeaderMap) -> ApiResult {
|
||||
let caller = authenticate(&hub, &headers)?;
|
||||
let conn = hub.db.lock().unwrap();
|
||||
|
||||
let vault_rows: Vec<(i64, String, bool)> = {
|
||||
let sql = if caller.owner {
|
||||
"SELECT id, name, delete_from_devices FROM vaults ORDER BY created, id"
|
||||
} else {
|
||||
"SELECT v.id, v.name, v.delete_from_devices FROM vaults v JOIN memberships m ON m.vault_id = v.id
|
||||
WHERE m.account_id = ?1 ORDER BY v.created, v.id"
|
||||
};
|
||||
let mut stmt = conn.prepare(sql)?;
|
||||
let map = |r: &rusqlite::Row| Ok((r.get(0)?, r.get(1)?, r.get(2)?));
|
||||
if caller.owner { stmt.query_map([], map)?.collect::<Result<_, _>>()? } else { stmt.query_map([caller.account_id], map)?.collect::<Result<_, _>>()? }
|
||||
};
|
||||
let mut vaults = vec![];
|
||||
let mut managed = vec![];
|
||||
for (id, name, delete_files) in &vault_rows {
|
||||
let manage = can_manage(&conn, &caller, *id)?;
|
||||
if manage {
|
||||
managed.push(*id);
|
||||
}
|
||||
vaults.push(json!({ "id": format!("v{id}"), "name": name, "can_manage": manage, "delete_from_devices": delete_files }));
|
||||
}
|
||||
let visible: Vec<i64> = vault_rows.iter().map(|v| v.0).collect();
|
||||
|
||||
let mut members = vec![];
|
||||
{
|
||||
let mut stmt = conn.prepare("SELECT vault_id, account_id, role FROM memberships")?;
|
||||
let rows: Vec<(i64, i64, String)> = stmt.query_map([], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)))?.collect::<Result<_, _>>()?;
|
||||
for (v, a, role) in rows.into_iter().filter(|r| visible.contains(&r.0)) {
|
||||
members.push(json!({ "vault": format!("v{v}"), "person": format!("a{a}"), "role": role }));
|
||||
}
|
||||
}
|
||||
|
||||
let mut people = vec![];
|
||||
{
|
||||
let mut stmt = conn.prepare("SELECT id, name, owner FROM accounts WHERE disabled = 0 ORDER BY created, id")?;
|
||||
let rows: Vec<(i64, String, bool)> = stmt.query_map([], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)))?.collect::<Result<_, _>>()?;
|
||||
for (id, name, owner) in rows {
|
||||
// Devices: your own, the owner sees all, managers see their members' (blueprint J6).
|
||||
let shares_managed = members.iter().any(|m| {
|
||||
m["person"] == format!("a{id}") && managed.iter().any(|v| m["vault"] == format!("v{v}"))
|
||||
});
|
||||
let devices: Vec<Value> = if id == caller.account_id || caller.owner || shares_managed {
|
||||
let mut d = conn.prepare("SELECT id, label FROM devices WHERE account_id = ?1 AND removed = 0 ORDER BY created")?;
|
||||
d.query_map([id], |r| Ok(json!({ "id": r.get::<_, String>(0)?, "label": r.get::<_, String>(1)? })))?
|
||||
.collect::<Result<_, _>>()?
|
||||
} else {
|
||||
vec![]
|
||||
};
|
||||
people.push(json!({ "id": format!("a{id}"), "name": name, "owner": owner, "invited": false, "devices": devices }));
|
||||
}
|
||||
}
|
||||
|
||||
// People invited but not joined yet show up too, with the vaults their invite carries.
|
||||
{
|
||||
let mut stmt = conn.prepare(
|
||||
"SELECT person, grants FROM invites WHERE used IS NULL AND owner = 0 AND account_id IS NULL AND expires > ?1 ORDER BY rowid",
|
||||
)?;
|
||||
let rows: Vec<(String, String)> = stmt.query_map([db::now()], |r| Ok((r.get(0)?, r.get(1)?)))?.collect::<Result<_, _>>()?;
|
||||
for (person, grants) in rows {
|
||||
let grants: Vec<(i64, String)> = serde_json::from_str(&grants).unwrap_or_default();
|
||||
if !caller.owner && !grants.iter().any(|(v, _)| managed.contains(v)) {
|
||||
continue;
|
||||
}
|
||||
let key = format!("i:{person}");
|
||||
for (v, role) in grants.iter().filter(|(v, _)| visible.contains(v)) {
|
||||
members.push(json!({ "vault": format!("v{v}"), "person": key, "role": role }));
|
||||
}
|
||||
people.push(json!({ "id": key, "name": person, "owner": false, "invited": true, "devices": [] }));
|
||||
}
|
||||
}
|
||||
|
||||
let pending: Vec<Value> = {
|
||||
let mut stmt = conn.prepare("SELECT id, vault_id, account_id FROM pending_removals")?;
|
||||
let rows: Vec<(i64, i64, i64)> = stmt.query_map([], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)))?.collect::<Result<_, _>>()?;
|
||||
rows.into_iter()
|
||||
.filter(|r| visible.contains(&r.1))
|
||||
.map(|(id, v, a)| json!({ "id": id, "vault": format!("v{v}"), "person": format!("a{a}") }))
|
||||
.collect()
|
||||
};
|
||||
|
||||
Ok(Json(json!({
|
||||
"me": { "id": format!("a{}", caller.account_id), "person": caller.person, "owner": caller.owner },
|
||||
"vaults": vaults, "people": people, "members": members, "pending": pending
|
||||
})))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct InviteGrantReq {
|
||||
person: String,
|
||||
vault: String,
|
||||
role: Option<String>,
|
||||
#[serde(default)]
|
||||
remove: bool,
|
||||
}
|
||||
|
||||
/// Dropping a vault on someone invited but not joined yet: add it to (or take it off) their invite.
|
||||
pub async fn invite_grant(State(hub): State<Shared>, headers: HeaderMap, Json(req): Json<InviteGrantReq>) -> ApiResult {
|
||||
let caller = authenticate(&hub, &headers)?;
|
||||
let conn = hub.db.lock().unwrap();
|
||||
let (vault_id, vault) = db::vault_id(&conn, &req.vault)?.ok_or_else(|| bad(format!("no vault named {}", req.vault)))?;
|
||||
if !can_manage(&conn, &caller, vault_id)? {
|
||||
return Err(denied(format!("you need Manage on {vault} to give access to it")));
|
||||
}
|
||||
let (token_hash, grants): (String, String) = conn
|
||||
.query_row(
|
||||
"SELECT token_hash, grants FROM invites WHERE person = ?1 AND used IS NULL AND account_id IS NULL AND expires > ?2",
|
||||
params![req.person.trim(), db::now()],
|
||||
|r| Ok((r.get(0)?, r.get(1)?)),
|
||||
)
|
||||
.optional()?
|
||||
.ok_or_else(|| bad(format!("no open invite for {}", req.person.trim())))?;
|
||||
let mut grants: Vec<(i64, String)> = serde_json::from_str(&grants).unwrap_or_default();
|
||||
grants.retain(|(v, _)| *v != vault_id);
|
||||
let role = req.role.unwrap_or_else(|| "edit".into()).to_lowercase();
|
||||
if !["read", "edit", "manage"].contains(&role.as_str()) {
|
||||
return Err(bad("roles are read, edit or manage"));
|
||||
}
|
||||
if !req.remove {
|
||||
grants.push((vault_id, role.clone()));
|
||||
}
|
||||
conn.execute("UPDATE invites SET grants = ?1 WHERE token_hash = ?2", params![serde_json::to_string(&grants).unwrap(), token_hash])?;
|
||||
let what = if req.remove { format!("{vault} taken off") } else { format!("{vault}: {role}") };
|
||||
db::log(&conn, &caller.who(), "invite changed", &format!("for {} ({what})", req.person.trim()))?;
|
||||
Ok(Json(json!({})))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct RenameReq {
|
||||
device_id: String,
|
||||
label: String,
|
||||
}
|
||||
|
||||
/// Renames a device: your own, or anyone's for the team owner.
|
||||
pub async fn rename_device(State(hub): State<Shared>, headers: HeaderMap, Json(req): Json<RenameReq>) -> ApiResult {
|
||||
let caller = authenticate(&hub, &headers)?;
|
||||
let label = req.label.trim();
|
||||
if label.is_empty() || label.len() > 40 {
|
||||
return Err(bad("a device label needs 1–40 characters"));
|
||||
}
|
||||
let conn = hub.db.lock().unwrap();
|
||||
let (account_id, old): (i64, String) = conn
|
||||
.query_row("SELECT account_id, label FROM devices WHERE id = ?1 AND removed = 0", [&req.device_id], |r| Ok((r.get(0)?, r.get(1)?)))
|
||||
.optional()?
|
||||
.ok_or_else(|| bad("no such device"))?;
|
||||
if account_id != caller.account_id && !caller.owner {
|
||||
return Err(denied("you can only rename your own devices"));
|
||||
}
|
||||
conn.execute("UPDATE devices SET label = ?1 WHERE id = ?2", params![label, req.device_id])?;
|
||||
db::log(&conn, &caller.who(), "device renamed", &format!("{old} → {label}"))?;
|
||||
Ok(Json(json!({})))
|
||||
}
|
||||
|
||||
/// The canvas app: real files by path, everything else is the app's own page (it routes itself).
|
||||
pub async fn static_files(uri: Uri) -> Response {
|
||||
let path = uri.path().trim_start_matches('/');
|
||||
let file = Assets::get(path).map(|f| (path.to_string(), f)).or_else(|| Assets::get("index.html").map(|f| ("index.html".into(), f)));
|
||||
match file {
|
||||
Some((name, f)) => {
|
||||
let cache = if name.starts_with("assets/") { "public, max-age=31536000, immutable" } else { "no-cache" };
|
||||
(
|
||||
[(header::CONTENT_TYPE, f.metadata.mimetype().to_string()), (header::CACHE_CONTROL, cache.to_string())],
|
||||
f.data.into_owned(),
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
None => (StatusCode::NOT_FOUND, "the canvas wasn't built into this hub").into_response(),
|
||||
}
|
||||
}
|
||||
@@ -254,3 +254,60 @@ fn taking_access_back() {
|
||||
assert!(log.iter().any(|a| a == action), "missing {action} in {log:?}");
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Milestone 5: the canvas's sessions and the Undo window ----
|
||||
|
||||
#[test]
|
||||
fn canvas_session_and_undo_window() {
|
||||
let _turn = SERIAL.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let tmp = tempfile::TempDir::new().unwrap();
|
||||
let (_hub, url, owner_link) = start_hub(&tmp.path().join("data"));
|
||||
let (_, sen_w) = hub::join(&owner_link, "Codex").unwrap();
|
||||
let codex = as_device(&url, &sen_w);
|
||||
codex.create_vault("DevOps").unwrap();
|
||||
let link = codex.invite("Alice", &[("DevOps".into(), "edit".into())]).unwrap();
|
||||
hub::join(&link, "Alice laptop").unwrap();
|
||||
as_device(&url, &sen_w);
|
||||
|
||||
let agent: ureq::Agent = ureq::Agent::config_builder().http_status_as_error(false).build().into();
|
||||
// Sign in with a pairing code: the browser gets a session cookie.
|
||||
let res = agent.post(format!("{url}/api/web/signin")).send_json(serde_json::json!({ "code": codex.pair().unwrap() })).unwrap();
|
||||
assert_eq!(res.status(), 200);
|
||||
let cookie = res.headers().get("set-cookie").unwrap().to_str().unwrap().to_string();
|
||||
assert!(cookie.contains("HttpOnly") && cookie.contains("SameSite=Strict"), "{cookie}");
|
||||
let session = cookie.split(';').next().unwrap().to_string();
|
||||
|
||||
// Without the canvas header, a cookie alone gets nothing (no cross-site requests).
|
||||
let res = agent.get(format!("{url}/api/canvas")).header("Cookie", &session).call().unwrap();
|
||||
assert_eq!(res.status(), 403);
|
||||
let canvas = |agent: &ureq::Agent| -> serde_json::Value {
|
||||
agent.get(format!("{url}/api/canvas")).header("Cookie", &session).header("X-Lune", "1").call().unwrap().body_mut().read_json().unwrap()
|
||||
};
|
||||
let c = canvas(&agent);
|
||||
assert_eq!(c["me"]["person"], "Sen");
|
||||
assert_eq!(c["members"].as_array().unwrap().len(), 2);
|
||||
|
||||
let post = |path: &str, body: serde_json::Value| -> serde_json::Value {
|
||||
agent.post(format!("{url}{path}")).header("Cookie", &session).header("X-Lune", "1").send_json(body).unwrap().body_mut().read_json().unwrap()
|
||||
};
|
||||
let alice_has_devops = || codex.members("DevOps").unwrap().iter().any(|m| m.person == "Alice");
|
||||
|
||||
// Pull the ribbon, then Undo inside the window: nothing happened.
|
||||
let pending = post("/api/remove", serde_json::json!({"person": "Alice", "vault": "DevOps", "delay_seconds": 2}))["pending"].as_i64().unwrap();
|
||||
assert!(alice_has_devops(), "still a member during the Undo window");
|
||||
post("/api/remove/undo", serde_json::json!({ "pending": pending }));
|
||||
std::thread::sleep(std::time::Duration::from_millis(3500));
|
||||
assert!(alice_has_devops());
|
||||
|
||||
// Pull again and let the window pass: the removal goes through.
|
||||
post("/api/remove", serde_json::json!({"person": "Alice", "vault": "DevOps", "delay_seconds": 1}));
|
||||
std::thread::sleep(std::time::Duration::from_millis(3000));
|
||||
assert!(!alice_has_devops());
|
||||
let undo = post("/api/remove/undo", serde_json::json!({ "pending": pending }));
|
||||
assert!(undo["error"].as_str().unwrap().contains("too late"));
|
||||
|
||||
// Signing out ends the session.
|
||||
post("/api/web/signout", serde_json::json!({}));
|
||||
let res = agent.get(format!("{url}/api/canvas")).header("Cookie", &session).header("X-Lune", "1").call().unwrap();
|
||||
assert_eq!(res.status(), 401);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user