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:
2026-10-29 07:56:41 +07:00
parent 4025726083
commit 193cb06f85
27 changed files with 3574 additions and 39 deletions

View File

@@ -1,2 +1,4 @@
target/ target/
.git/ .git/
web/node_modules/
web/dist/

54
Cargo.lock generated
View File

@@ -971,11 +971,13 @@ dependencies = [
"getrandom 0.4.3", "getrandom 0.4.3",
"lune-core", "lune-core",
"rusqlite", "rusqlite",
"rust-embed",
"serde", "serde",
"serde_json", "serde_json",
"sha2", "sha2",
"tempfile", "tempfile",
"tokio", "tokio",
"ureq",
] ]
[[package]] [[package]]
@@ -1006,6 +1008,16 @@ version = "0.3.17"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a"
[[package]]
name = "mime_guess"
version = "2.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f7c44f8e672c00fe5308fa235f821cb4198414e1c77935c1ab6948d3fd78550e"
dependencies = [
"mime",
"unicase",
]
[[package]] [[package]]
name = "miniz_oxide" name = "miniz_oxide"
version = "0.9.1" version = "0.9.1"
@@ -1302,6 +1314,42 @@ dependencies = [
"sqlite-wasm-rs", "sqlite-wasm-rs",
] ]
[[package]]
name = "rust-embed"
version = "8.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "19afa5b4b6a611de00bd1bdae6ae6f39084c9399f0679c3f52d8469cf335cc23"
dependencies = [
"rust-embed-impl",
"rust-embed-utils",
"walkdir",
]
[[package]]
name = "rust-embed-impl"
version = "8.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e0d8afda6374eac59e066abee06d265247ebbaf3006cf878e2879e8356e34053"
dependencies = [
"mime_guess",
"proc-macro2",
"quote",
"rust-embed-utils",
"syn 2.0.119",
"walkdir",
]
[[package]]
name = "rust-embed-utils"
version = "8.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0d84e8ba78bd384263e5922f084cbe1b081c3b7e69add59c8fb097b879ba968a"
dependencies = [
"mime_guess",
"sha2",
"walkdir",
]
[[package]] [[package]]
name = "rustix" name = "rustix"
version = "1.1.6" version = "1.1.6"
@@ -1768,6 +1816,12 @@ version = "1.20.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
[[package]]
name = "unicase"
version = "2.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "357cc3acc6a036009fd6c973ed009037c732d60d0b4f6c673e9041497482a28f"
[[package]] [[package]]
name = "unicode-ident" name = "unicode-ident"
version = "1.0.27" version = "1.0.27"

View File

@@ -1,7 +1,15 @@
# Lune hub: one container, data on /data. # Lune hub: one container, data on /data. The web canvas is built first and embedded in the binary.
FROM node:22-bookworm-slim AS web
WORKDIR /web
COPY web/package.json web/package-lock.json ./
RUN npm ci --no-audit --no-fund
COPY web/ ./
RUN npm run build
FROM rust:1.99-bookworm AS build FROM rust:1.99-bookworm AS build
WORKDIR /src WORKDIR /src
COPY . . COPY . .
COPY --from=web /web/dist ./web/dist
RUN cargo build --release -p lunehub RUN cargo build --release -p lunehub
FROM debian:bookworm-slim FROM debian:bookworm-slim

View File

@@ -88,8 +88,10 @@ enum Command {
#[arg(long)] #[arg(long)]
vaults_dir: Option<PathBuf>, vaults_dir: Option<PathBuf>,
}, },
/// Make a one-time code to add another of your devices /// Make a one-time code to add another of your devices (or sign in to the canvas on a phone)
Pair, Pair,
/// Open the team canvas in your browser, already signed in
Open,
/// Vaults on the hub /// Vaults on the hub
Vault { Vault {
#[command(subcommand)] #[command(subcommand)]
@@ -297,6 +299,13 @@ fn run_cli(cli: Cli) -> Result<()> {
Command::Join { link, name, vaults_dir } => team::join(&mut config, &link, &name, vaults_dir)?, Command::Join { link, name, vaults_dir } => team::join(&mut config, &link, &name, vaults_dir)?,
Command::Login { hub, code, name, vaults_dir } => team::login(&mut config, &hub, &code, &name, vaults_dir)?, Command::Login { hub, code, name, vaults_dir } => team::login(&mut config, &hub, &code, &name, vaults_dir)?,
Command::Pair => team::pair(&config)?, Command::Pair => team::pair(&config)?,
Command::Open => {
let url = team::link(&config)?.web_link()?;
let opener = if cfg!(target_os = "macos") { "open" } else { "xdg-open" };
if std::process::Command::new(opener).arg(&url).status().map(|s| !s.success()).unwrap_or(true) {
println!("Open this link in your browser (it works once, for 2 minutes):\n\n {url}");
}
}
Command::Vault { action: VaultCmd::New { name } } => team::vault_new(&mut config, &name)?, Command::Vault { action: VaultCmd::New { name } } => team::vault_new(&mut config, &name)?,
Command::Vault { action: VaultCmd::Upload { name, fresh } } => team::vault_upload(&mut config, &name, fresh)?, Command::Vault { action: VaultCmd::Upload { name, fresh } } => team::vault_upload(&mut config, &name, fresh)?,
Command::Invite { person, vaults } => team::invite(&config, &person, &vaults)?, Command::Invite { person, vaults } => team::invite(&config, &person, &vaults)?,

View File

@@ -48,7 +48,7 @@ pub fn login(config: &mut Config, url: &str, code: &str, label: &str, vaults_dir
pub fn pair(config: &Config) -> Result<()> { pub fn pair(config: &Config) -> Result<()> {
let h = link(config)?; let h = link(config)?;
let code = h.pair()?; let code = h.pair()?;
println!("On the new device (code works once, for 10 minutes):\n"); println!("On the new device (or type the code on the canvas sign-in page; works once, for 10 minutes):\n");
println!(" lunesync login --hub {} --code {code} --name <its label>", h.url); println!(" lunesync login --hub {} --code {code} --name <its label>", h.url);
Ok(()) Ok(())
} }

View File

@@ -180,6 +180,12 @@ impl HubLink {
} }
impl HubLink { 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<String> {
let v: Value = self.post("/api/web/link", json!({}))?;
Ok(v["url"].as_str().unwrap_or_default().to_string())
}
pub fn remove(&self, person: &str, vault: &str, without_saving: bool) -> Result<usize> { pub fn remove(&self, person: &str, vault: &str, without_saving: bool) -> Result<usize> {
let v: Value = self.post("/api/remove", json!({"person": person, "vault": vault, "without_saving": without_saving}))?; 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) Ok(v["devices"].as_u64().unwrap_or(0) as usize)

View File

@@ -153,47 +153,40 @@ Only the current milestone gets detailed below. The next one is detailed when th
--- ---
## 6. Milestone 4 — Access I can take back ## 6. Milestone 5 — Canvas for access
Milestones 1–3 (sync, safety checks, the hub with invites, pairing and roles) are built; their detail lives in the code and tests now. Milestones 1–4 (sync, safety checks, the hub, taking access back) are built; their detail lives in the code and tests now. The canvas follows Sen's clickable prototype (team canvas artboard) and the X decisions.
### Goal ### Goal
Taking access back is as clean as giving it. Removing someone from a vault collects their unshared work for a manager to review, then their copy disappears; their other vaults keep working. Removing someone from the team stops everything. A lost laptop can be removed on its own. All from the CLI. The hub serves a web canvas where access is managed by touch: drag a vault onto a person to grant, pull a ribbon until it snaps to revoke (with Undo), and every gesture has a button in the details panel. Invites and device labels live here too.
### What Sen does ### What Sen does
```bash ```bash
lunesync remove Alice --vault DevOps # Alice loses DevOps only (A5) lunesync open # opens the canvas in the browser, already signed in
lunesync remove Alice --vault DevOps --without-saving
lunesync device remove "Old laptop" # one device, e.g. lost; --person for someone else's (owner)
lunesync team remove Bob # owner only; asks to type the name (A8)
lunesync team restore Bob # re-enables the account; prints a one-time sign-in link
lunesync handovers # unshared work that came back, and devices still to report in
lunesync handover show|keep|discard 7
lunesync handover skip 7 # a device that will never come back: delete without saving
lunesync vault set DevOps --delete-from-devices off # A7, on by default
``` ```
Or on a phone / another browser: open the hub's address, type a code from `lunesync pair`.
On the canvas: drag DevOps onto Alice (she gets Edit; change the role in the panel), pull the dot on a ribbon until it pinches and snaps (Undo for 8 s), **Invite person** (name + vaults → a one-time link to copy), rename or remove a device in a person's panel, switch **Float** / **Dock**, create a vault (owner), turn "delete from their devices" on or off per vault.
### Behavior ### Behavior
- **Removing from a vault (A5, A6)**: the membership ends at once and the hub opens a *departure* for each of that person's devices. A device learns about it the next time it checks in (within ~30 s while running; offline devices on reconnect), then: - **Sign-in (decided, §8)**: no passwords. `lunesync open` makes a one-time sign-in link (2 minutes) from a signed-in device; or type a pairing code on the hub's sign-in page. The session cookie lasts 30 days (HttpOnly, SameSite=Strict, Secure on HTTPS); signing out, or removal from the team, ends it. The canvas acts as the person ("Sen (web)" in the access log), never as a device: it holds no vault content.
1. stops syncing that vault and saves anything unsaved; - **What you see**: the owner sees every vault and person; others see the vaults they're in. Everyone sees the team's people (to grant). Devices are visible to their owner, the team owner, and managers of a vault the person is in. Gestures only work on vaults you manage.
2. makes the folder read-only; - **Grant** = drop a vault on a person (Edit). Dropping on an invited person who hasn't joined yet adds it to their invite. No confirmation (X2).
3. sends everything not yet shared to the hub's **handover area** for that vault. Notes held by the secret check go along with the secret replaced by `[secret removed when leaving]` (P1: the secret itself is never sent or kept); - **Revoke** = pull a ribbon's dot until it snaps. The ribbon disappears and an 8 s Undo toast shows; the hub holds the removal until the window passes, so nothing reaches the person's devices before then. Then the M4 flow runs (handover, delete).
4. after the hub confirms receipt, deletes the folder — only if the app created it (marker in `.git/`, A9), never following links out. A folder the app adopted, or a vault with "delete from devices" off (A7), is left in place, read-only and no longer synced. - **Panels (X1, X3, X11)**: overview (vaults, people, recent activity for the owner), vault (members with role and Remove, Give access, the delete-from-devices setting), person (devices: rename, remove; vaults). Back navigation remembers where a panel was opened from. Bottom sheet on phones.
- A device that was removed can still do exactly one thing until its departures are done: hand over. It can't read or change the vault. - **Look**: X4–X8 as in the prototype — metaball ribbons with the goo filter, identity colors fading vault→person, focus with veils, Float (shared bobbing clock) and Dock, reduced motion respected. Status colors stay unused until M6.
- **Handovers** are reviewed by a manager: **keep** combines them into the vault (same-lines clashes keep both, labeled with the leaving device), **discard** drops them. If nothing was unshared, the departure just completes. `skip` = "Delete without saving" for a pending departure. - **Invite link in a browser** shows how to join (`lunesync join <link> --name …`) instead of an error.
- **Removing a device (A1)**: same flow for every vault on that device; afterwards its key stops working. - The hub serves the canvas itself (built into the binary); nothing else to deploy.
- **Remove from team (A8)**: owner only, asks for confirmation. Ends every membership (departures as above), removes every device, disables the account (restorable, keeps its name in history). Restore re-enables it with no vaults and a one-time sign-in link for a new device.
- Everything is in the access log (A10). Messages say plainly what can't be recalled (A11): copies made elsewhere stay where they are.
### Acceptance — Sen acts this out ### Acceptance — Sen acts this out
1. Alice has DevOps and Notes and edits DevOps while offline. Remove her from DevOps; when she reconnects her edit arrives as a handover, her DevOps folder disappears, Notes keeps syncing. 1. `lunesync open` → the canvas, signed in. A phone signs in with a code.
2. `handover show` lists her changes; `keep` brings them into DevOps on every device; another handover is discarded. 2. Drag a vault onto a teammate: the vault arrives on their devices. Change their role in the panel.
3. Remove Bob from the team: all his vaults leave his devices, his device can't do anything after, the access log shows each step. `team restore Bob` lets him back in with no vaults. 3. Pull a ribbon until it snaps, press Undo: nothing changed on their devices. Pull again and wait: the M4 removal runs.
4. Remove a device that's switched off: `handover skip`; when it's switched on later, its copy is deleted without anything being sent. 4. Invite a person with a vault; they join from the link; they appear on the canvas with their device.
5. A vault with "delete from devices" off: the person's copy stays, read-only, no longer synced. 5. Rename and remove a device from the panel; switch Float/Dock; everything works with buttons alone (keyboard).
### Out of scope for M4 ### Out of scope for M5
Undo window and gestures (M5, X2). Permanent account deletion (later admin action). Verifying removal in external tools (non-goal for v1). Freshness glow, Nudge, tidy and handover review, remove from team (M6). Desktop app (M7).
## 7. Open questions ## 7. Open questions
None open. None open.
@@ -204,3 +197,4 @@ Record here: date, what changed, why, which decision number. Example:
- 2026-10-28 — Secret detection (open question, P2): our own short list of ~20 high-confidence rules, not an embedded gitleaks-style set. Fewer false alarms, easy to read. (Sen) - 2026-10-28 — Secret detection (open question, P2): our own short list of ~20 high-confidence rules, not an embedded gitleaks-style set. Fewer false alarms, easy to read. (Sen)
- 2026-10-29 — Hub storage (open question): plain bare repos on the hub's volume served by the hub itself (device key + role check, then Git's own HTTP backend); no Gitea underneath. (Sen) - 2026-10-29 — Hub storage (open question): plain bare repos on the hub's volume served by the hub itself (device key + role check, then Git's own HTTP backend); no Gitea underneath. (Sen)
- 2026-10-29 — Web canvas sign-in (new): no passwords; a one-time link from `lunesync open` or a pairing code typed on the hub's sign-in page; 30-day session cookie. (Sen)

View File

@@ -11,6 +11,7 @@ chrono = "0.4.45"
getrandom = "0.4.3" getrandom = "0.4.3"
lune-core = { version = "0.1.0", path = "../core" } lune-core = { version = "0.1.0", path = "../core" }
rusqlite = { version = "0.41.0", features = ["bundled"] } rusqlite = { version = "0.41.0", features = ["bundled"] }
rust-embed = { version = "8.13.0", features = ["mime-guess"] }
serde = { version = "1.0.229", features = ["derive"] } serde = { version = "1.0.229", features = ["derive"] }
serde_json = "1.0.154" serde_json = "1.0.154"
sha2 = "0.11.1" sha2 = "0.11.1"
@@ -18,3 +19,4 @@ tokio = { version = "1.54.1", features = ["full"] }
[dev-dependencies] [dev-dependencies]
tempfile = "3.27.0" tempfile = "3.27.0"
ureq = "3.5.0"

13
hub/build.rs Normal file
View 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");
}

View File

@@ -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. /// 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> { 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 unknown = || ApiError(StatusCode::UNAUTHORIZED, "this device isn't signed in to the hub".into());
let (id, key) = credentials(headers).ok_or_else(unknown)?; if let Some((id, key)) = credentials(headers) {
let conn = hub.db.lock().unwrap(); let conn = hub.db.lock().unwrap();
db::caller(&conn, &id, &key)?.ok_or_else(unknown) 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. /// The signed-in device, if it still has normal access.

View File

@@ -62,6 +62,19 @@ CREATE TABLE IF NOT EXISTS departures (
created INTEGER NOT NULL, created INTEGER NOT NULL,
updated 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 ( CREATE TABLE IF NOT EXISTS log (
id INTEGER PRIMARY KEY, id INTEGER PRIMARY KEY,
at INTEGER NOT NULL, at INTEGER NOT NULL,
@@ -151,6 +164,27 @@ pub fn caller(conn: &Connection, device_id: &str, key: &str) -> Result<Option<Ca
.optional()?) .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. /// 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)> { pub fn new_device(conn: &Connection, account_id: i64, label: &str) -> Result<(String, String)> {
let id = format!("dev_{}", token(10).to_lowercase()); let id = format!("dev_{}", token(10).to_lowercase());

View File

@@ -34,6 +34,9 @@ pub struct RemoveReq {
vault: String, vault: String,
#[serde(default)] #[serde(default)]
without_saving: bool, 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. /// 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() { if db::role(&conn, account_id, vault_id)?.is_none() {
return Err(bad(format!("{person} isn't a member of {vault}"))); 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])?; if req.delay_seconds > 0 {
let n = db::depart(&conn, account_id, vault_id, None, req.without_saving)?; conn.execute(
let how = if req.without_saving { " without saving" } else { "" }; "INSERT INTO pending_removals (account_id, vault_id, without_saving, due, by_who) VALUES (?1, ?2, ?3, ?4, ?5)",
db::log(&conn, &caller.who(), "access removed", &format!("{person} from {vault}{how} ({})", devices_phrase(n)))?; 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 }))) 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)] #[derive(Deserialize)]
pub struct DeviceRemoveReq { pub struct DeviceRemoveReq {
#[serde(default)]
label: String, label: String,
person: Option<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. /// 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 { pub async fn remove_device(State(hub): State<Shared>, headers: HeaderMap, Json(req): Json<DeviceRemoveReq>) -> ApiResult {
let caller = authenticate(&hub, &headers)?; let caller = authenticate(&hub, &headers)?;
let conn = hub.db.lock().unwrap(); 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 { let (account_id, person) = match &req.person {
Some(p) if !p.eq_ignore_ascii_case(&caller.person) => { Some(p) if !p.eq_ignore_ascii_case(&caller.person) => {
if !caller.owner { 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 devices SET removed = 1 WHERE account_id = ?1", [account_id])?;
tx.execute("UPDATE accounts SET disabled = 1 WHERE 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 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 devices: Vec<String> = {
let mut stmt = tx.prepare("SELECT id FROM devices WHERE account_id = ?1")?; let mut stmt = tx.prepare("SELECT id FROM devices WHERE account_id = ?1")?;
stmt.query_map([account_id], |r| r.get(0))?.collect::<Result<_, _>>()? stmt.query_map([account_id], |r| r.get(0))?.collect::<Result<_, _>>()?

View File

@@ -5,6 +5,7 @@ mod db;
mod git; mod git;
mod hook; mod hook;
mod leave; mod leave;
mod web;
use anyhow::Result; use anyhow::Result;
use axum::Router; 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() }); 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() let app = Router::new()
.route("/api/join", post(api::join)) .route("/api/join", post(api::join))
.route("/api/login", post(api::login)) .route("/api/login", post(api::login))
@@ -84,8 +97,17 @@ async fn serve() -> Result<()> {
.route("/api/handovers", get(leave::handovers)) .route("/api/handovers", get(leave::handovers))
.route("/api/handovers/show", post(leave::handover_show)) .route("/api/handovers/show", post(leave::handover_show))
.route("/api/handovers/decide", post(leave::handover_decide)) .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("/git/{repo}/{*rest}", any(git::serve))
.route("/health", get(|| async { "ok" })) .route("/health", get(|| async { "ok" }))
.fallback(web::static_files)
.layer(DefaultBodyLimit::disable()) .layer(DefaultBodyLimit::disable())
.with_state(hub); .with_state(hub);
let listener = tokio::net::TcpListener::bind(&listen).await?; let listener = tokio::net::TcpListener::bind(&listen).await?;

284
hub/src/web.rs Normal file
View 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(),
}
}

View File

@@ -254,3 +254,60 @@ fn taking_access_back() {
assert!(log.iter().any(|a| a == action), "missing {action} in {log:?}"); 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);
}

2
web/.gitignore vendored Normal file
View File

@@ -0,0 +1,2 @@
node_modules/
dist/

14
web/index.html Normal file
View File

@@ -0,0 +1,14 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<title>Lune · Team canvas</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wght@12..96,600;12..96,700&family=Atkinson+Hyperlegible:wght@400;700&display=swap">
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

1742
web/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

22
web/package.json Normal file
View File

@@ -0,0 +1,22 @@
{
"name": "lune-canvas",
"private": true,
"version": "0.1.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"check": "tsc -b"
},
"dependencies": {
"react": "18.3.1",
"react-dom": "18.3.1"
},
"devDependencies": {
"@types/react": "18.3.12",
"@types/react-dom": "18.3.1",
"@vitejs/plugin-react": "4.3.4",
"typescript": "5.6.3",
"vite": "5.4.11"
}
}

791
web/src/Canvas.tsx Normal file
View File

@@ -0,0 +1,791 @@
// The team canvas (M5): vaults on the left, people on the right, ribbons for who can sync what.
// Grant = drag a vault onto a person; revoke = pull a ribbon's dot until it snaps (Undo for 8 s). Every gesture
// also has a button in the details panel (X3).
import { useEffect, useMemo, useRef, useState } from 'react';
import { api, type CanvasData, type LogEntry, type Member, type Person, type Role, type Vault } from './api';
import {
HANDLE_T, W, boardHeight, circle, easeBack, lerp, personColor, positions, ribbon, roundRect, vaultColor,
type Layout, type Pt,
} from './geometry';
const UNDO_SECONDS = 8;
const ROLES: Role[] = ['read', 'edit', 'manage'];
const roleName = (r: Role) => r.charAt(0).toUpperCase() + r.slice(1);
const plural = (n: number, word: string, many = word + 's') => `${n} ${n === 1 ? word : many}`;
const keyOf = (m: { vault: string; person: string }) => `${m.vault}|${m.person}`;
type Sel =
| { kind: 'overview'; back?: Sel }
| { kind: 'vault'; id: string; back?: Sel }
| { kind: 'person'; id: string; back?: Sel };
type Drag =
| { kind: 'grant'; v: string; start: Pt; p: Pt; moved: boolean }
| { kind: 'retract'; v: string; p: Pt }
| { kind: 'detach'; key: string; p: Pt }
| { kind: 'snap'; key: string; p: Pt };
type Toast = { text: string; undo?: () => void };
function store(key: string, value?: string): string | null {
try {
if (value !== undefined) localStorage.setItem(key, value);
return localStorage.getItem(key);
} catch {
return null;
}
}
const reducedMotion = () => window.matchMedia?.('(prefers-reduced-motion: reduce)').matches ?? false;
export function Canvas({ data, reload, onSignOut }: { data: CanvasData; reload: () => Promise<void>; onSignOut: () => void }) {
const [layout, setLayoutState] = useState<Layout>(store('lune.layout') === 'dock' ? 'dock' : 'float');
const [blend, setBlend] = useState<{ from: Layout; to: Layout; t: number } | null>(null);
const [sel, setSel] = useState<Sel | null>(null);
const [hover, setHover] = useState<{ kind: 'vault' | 'person'; id: string } | null>(null);
const [drag, setDrag] = useState<Drag | null>(null);
const [pinched, setPinched] = useState<{ key: string; p: Pt; t: number } | null>(null);
const [toast, setToast] = useState<Toast | null>(null);
const [sheet, setSheet] = useState<'invite' | 'vault' | null>(null);
const [onboarded, setOnboarded] = useState(store('lune.onboarded') === '1');
const [hidden, setHidden] = useState<Set<string>>(new Set());
const [extra, setExtra] = useState<Member[]>([]);
const [log, setLog] = useState<LogEntry[]>([]);
const svgRef = useRef<SVGSVGElement>(null);
const rafs = useRef<Record<string, number>>({});
const toastTimer = useRef<number>();
const hoverTimer = useRef<number>();
const lastFocus = useRef<{ kind: 'vault' | 'person'; id: string } | null>(null);
// Optimistic additions last until fresh data arrives; the hub stays the source of truth.
useEffect(() => setExtra([]), [data]);
useEffect(() => {
const t = window.setInterval(() => reload(), 10000);
return () => window.clearInterval(t);
}, [reload]);
useEffect(() => () => Object.values(rafs.current).forEach(cancelAnimationFrame), []);
// Float: every node bobs on one shared clock (X8).
useEffect(() => {
try {
document.getAnimations?.().forEach((a) => {
if ((a as CSSAnimation).animationName === 'bob' && a.startTime !== 0) a.startTime = 0;
});
} catch {
/* older browsers: unsynced bobbing is fine */
}
});
useEffect(() => {
if (sel?.kind === 'overview' && data.me.owner) api.log(8).then(setLog).catch(() => setLog([]));
}, [sel, data]);
const vaults = data.vaults;
const people = data.people;
const vault = (id: string) => vaults.find((v) => v.id === id)!;
const person = (id: string) => people.find((p) => p.id === id)!;
const pendingKeys = useMemo(() => new Set(data.pending.map(keyOf)), [data]);
const members = useMemo(
() =>
[...data.members, ...extra.filter((e) => !data.members.some((m) => keyOf(m) === keyOf(e)))].filter(
(m) => !hidden.has(keyOf(m)) && !pendingKeys.has(keyOf(m)),
),
[data, extra, hidden, pendingKeys],
);
const H = boardHeight(vaults.length, people.length);
const at = useMemo(
() => ({
float: positions(vaults.map((v) => v.id), people.map((p) => p.id), 'float', H),
dock: positions(vaults.map((v) => v.id), people.map((p) => p.id), 'dock', H),
}),
[vaults, people, H],
);
const pos = (id: string): Pt => {
if (!blend) return at[layout][id];
const a = at[blend.from][id], c = at[blend.to][id], t = easeBack(blend.t);
return { x: lerp(a.x, c.x, t), y: lerp(a.y, c.y, t) };
};
const ends = (m: { vault: string; person: string }) => {
const a = pos(m.vault), b = pos(m.person);
return { ax: a.x, ay: a.y, bx: b.x, by: b.y };
};
function anim(key: string, ms: number, step: (t: number) => void, done?: () => void) {
const t0 = performance.now();
cancelAnimationFrame(rafs.current[key]);
const tick = (now: number) => {
const t = Math.min(1, (now - t0) / ms);
step(t);
if (t < 1) rafs.current[key] = requestAnimationFrame(tick);
else done?.();
};
rafs.current[key] = requestAnimationFrame(tick);
}
function say(text: string, undo?: () => void) {
setToast({ text, undo });
window.clearTimeout(toastTimer.current);
toastTimer.current = window.setTimeout(() => setToast(null), undo ? UNDO_SECONDS * 1000 : 4200);
}
async function run(action: () => Promise<unknown>, ok?: string) {
try {
await action();
if (ok) say(ok);
} catch (e) {
say((e as Error).message);
} finally {
await reload();
}
}
// ---- What the gestures and buttons do ----
function grant(vId: string, pId: string) {
const v = vault(vId), p = person(pId);
if (members.some((m) => m.vault === vId && m.person === pId)) return say(`${p.name} already has ${v.name}.`);
setExtra((x) => [...x, { vault: vId, person: pId, role: 'edit' }]);
run(
() => (p.invited ? api.inviteGrant(p.name, v.name, 'edit') : api.grant(p.name, v.name, 'edit')),
p.invited ? `${v.name} is added to ${p.name}'s invite.` : `${p.name} can now sync ${v.name}. It arrives on their devices within a minute.`,
);
}
async function revoke(key: string) {
const [vId, pId] = key.split('|');
const v = vault(vId), p = person(pId);
setHidden((h) => new Set(h).add(key));
const unhide = () => setHidden((h) => { const n = new Set(h); n.delete(key); return n; });
if (p.invited) {
await run(() => api.inviteGrant(p.name, v.name, null, true), `${v.name} is off ${p.name}'s invite.`);
unhide();
return;
}
try {
const res = await api.remove(p.name, v.name, UNDO_SECONDS);
const copies = v.delete_from_devices ? 'then deleted from their devices' : 'then their copy stops updating';
say(`${p.name} removed from ${v.name}. Unshared work comes to you for review, ${copies}.`, async () => {
setToast(null);
await run(() => api.undoRemove(res.pending!), `${p.name} has ${v.name} again. Nothing changed on their devices.`);
unhide();
});
window.setTimeout(() => reload().then(unhide), (UNDO_SECONDS + 1.5) * 1000);
} catch (e) {
unhide();
say((e as Error).message);
}
}
function cycleRole(m: Member) {
const v = vault(m.vault), p = person(m.person);
const next = ROLES[(ROLES.indexOf(m.role) + 1) % ROLES.length];
run(() => (p.invited ? api.inviteGrant(p.name, v.name, next) : api.grant(p.name, v.name, next)), `${p.name} now has ${roleName(next)} on ${v.name}.`);
}
function setLayout(l: Layout) {
if (blend || l === layout) return;
store('lune.layout', l);
if (reducedMotion()) return setLayoutState(l);
const from = layout;
setBlend({ from, to: l, t: 0 });
anim('layout', 720, (t) => setBlend({ from, to: l, t }), () => { setLayoutState(l); setBlend(null); });
}
// ---- Pointer handling ----
const toSvg = (e: React.PointerEvent): Pt => {
const svg = svgRef.current;
if (!svg) return { x: 0, y: 0 };
const pt = svg.createSVGPoint();
pt.x = e.clientX;
pt.y = e.clientY;
const q = pt.matrixTransform(svg.getScreenCTM()!.inverse());
return { x: q.x, y: q.y };
};
const capture = (e: React.PointerEvent) => { try { svgRef.current?.setPointerCapture(e.pointerId); } catch { /* fine */ } };
const target = (p: Pt) => {
let best: string | null = null, bd = 1e9;
for (const pr of people) {
const q = pos(pr.id), d = Math.hypot(p.x - q.x, p.y - q.y);
if (d < bd) { bd = d; best = pr.id; }
}
return best && bd < 130 ? { id: best, dist: bd } : null;
};
function startGrant(vId: string, e: React.PointerEvent) {
if (sheet || drag || pinched) return;
e.preventDefault();
const p = toSvg(e);
capture(e);
setDrag({ kind: 'grant', v: vId, start: p, p, moved: false });
}
function startDetach(key: string, e: React.PointerEvent) {
if (sheet || drag || pinched) return;
e.preventDefault();
capture(e);
setDrag({ kind: 'detach', key, p: toSvg(e) });
}
function onMove(e: React.PointerEvent) {
if (!drag || (drag.kind !== 'grant' && drag.kind !== 'detach')) return;
const p = toSvg(e);
if (drag.kind === 'grant') setDrag({ ...drag, p, moved: drag.moved || Math.hypot(p.x - drag.start.x, p.y - drag.start.y) > 6 });
else setDrag({ ...drag, p });
}
function onUp() {
const d = drag;
if (!d) return;
if (d.kind === 'grant') {
if (!d.moved) { setDrag(null); setSel({ kind: 'vault', id: d.v }); return; }
const t = target(d.p);
if (t && t.dist < 75) { setDrag(null); grant(d.v, t.id); return; }
const a = pos(d.v), p0 = d.p;
setDrag({ kind: 'retract', v: d.v, p: p0 });
anim('drag', 260, (t) => { const k = 1 - Math.pow(1 - t, 3); setDrag({ kind: 'retract', v: d.v, p: { x: lerp(p0.x, a.x, k), y: lerp(p0.y, a.y, k) } }); }, () => setDrag(null));
} else if (d.kind === 'detach') {
const [vId, pId] = d.key.split('|');
const e = ends({ vault: vId, person: pId });
const h0 = { x: lerp(e.ax, e.bx, HANDLE_T), y: lerp(e.ay, e.by, HANDLE_T) };
if (Math.hypot(d.p.x - h0.x, d.p.y - h0.y) > 110) {
const key = d.key, P = d.p;
setDrag(null);
setPinched({ key, p: P, t: 0 });
anim('pinch', reducedMotion() ? 1 : 300, (t) => setPinched({ key, p: P, t }), () => { setPinched(null); revoke(key); });
} else {
const q0 = d.p;
setDrag({ kind: 'snap', key: d.key, p: q0 });
anim('drag', 240, (t) => { const k = 1 - Math.pow(1 - t, 3); setDrag({ kind: 'snap', key: d.key, p: { x: lerp(q0.x, h0.x, k), y: lerp(q0.y, h0.y, k) } }); }, () => setDrag(null));
}
}
}
// ---- Drawing ----
const bob = !blend && layout === 'float' && !reducedMotion() ? 'bob' : '';
const grantDrag = drag && drag.kind === 'grant' && drag.moved ? drag : null;
const tgt = grantDrag ? target(grantDrag.p) : null;
const hot = tgt && tgt.dist < 75 ? tgt.id : null;
const focus = !drag && hover ? hover : sel && (sel.kind === 'vault' || sel.kind === 'person') ? { kind: sel.kind, id: sel.id } : null;
if (focus) lastFocus.current = focus;
const relV = (vId: string) => !focus || (focus.kind === 'vault' ? focus.id === vId : members.some((m) => m.vault === vId && m.person === focus.id));
const relP = (pId: string) => !focus || (focus.kind === 'person' ? focus.id === pId : members.some((m) => m.person === pId && m.vault === focus.id));
const pct = (x: number, y: number): React.CSSProperties => ({ position: 'absolute', left: `${(x / W) * 100}%`, top: `${(y / H) * 100}%` });
const leave = () => { window.clearTimeout(hoverTimer.current); hoverTimer.current = window.setTimeout(() => setHover(null), 90); };
const enter = (kind: 'vault' | 'person', id: string) => { window.clearTimeout(hoverTimer.current); if (!drag) setHover({ kind, id }); };
const blobs: { d: string; fill: string; delay: string; op: number }[] = [];
const labels: { text: string; style: React.CSSProperties; inner: React.CSSProperties }[] = [];
const ribbons: { d: string; fill: string; op?: number; dim?: number }[] = [];
const handles: { key: string; x: number; y: number; dim: boolean }[] = [];
const grips: { x: number; y: number; r: number }[] = [];
const grads: { id: string; x1: number; y1: number; x2: number; y2: number; c1: string; c2: string }[] = [];
vaults.forEach((v, i) => {
const p = pos(v.id), delay = (i * 0.7).toFixed(1), vo = relV(v.id) ? 1 : 0.35;
blobs.push({ d: roundRect(p.x, p.y, 138, 70, 26), fill: vaultColor(v.id).fill, delay, op: focus && relV(v.id) ? 1 : 0 });
labels.push({
text: v.name,
style: { ...pct(p.x - 20, p.y), transform: 'translateY(-50%)', opacity: vo, transition: 'opacity .2s' },
inner: { display: 'inline-block', whiteSpace: 'nowrap', fontWeight: 700, fontSize: 'max(1.4cqw, 10px)', animationDelay: `${delay}s`, maxWidth: '8.2cqw', overflow: 'hidden', textOverflow: 'ellipsis' },
});
});
people.forEach((pr, i) => {
const p = pos(pr.id), delay = (0.35 + i * 0.6).toFixed(1), po = relP(pr.id) ? 1 : 0.35;
if (!pr.invited) blobs.push({ d: circle(p.x, p.y, 38), fill: personColor(pr.id).fill, delay, op: focus && relP(pr.id) ? 1 : 0 });
labels.push({ text: pr.name.charAt(0).toUpperCase(), style: { ...pct(p.x, p.y), transform: 'translate(-50%,-50%)', opacity: po }, inner: { display: 'inline-block', fontWeight: 700, fontSize: 'max(2cqw, 12px)', animationDelay: `${delay}s` } });
labels.push({
text: pr.invited ? `${pr.name} · invited` : pr.name,
style: { ...pct(p.x, p.y + 48), transform: 'translate(-50%,-50%)', opacity: po },
inner: { display: 'inline-block', whiteSpace: 'nowrap', fontSize: 'max(1.3cqw, 10px)', animationDelay: `${delay}s` },
});
});
for (const m of members) {
const key = keyOf(m), e = ends(m), gid = `g-${key.replace(/[^a-zA-Z0-9]/g, '-')}`, fill = `url(#${gid})`;
grads.push({ id: gid, x1: e.ax, y1: e.ay, x2: e.bx, y2: e.by, c1: vaultColor(m.vault).fill, c2: personColor(m.person).fill });
const dim = !!(focus && ((focus.kind === 'vault' && focus.id !== m.vault) || (focus.kind === 'person' && focus.id !== m.person)));
const h0 = { x: lerp(e.ax, e.bx, HANDLE_T), y: lerp(e.ay, e.by, HANDLE_T) };
if (pinched?.key === key) {
const P = pinched.p, shrink = 1 - pinched.t;
ribbons.push({ d: ribbon(e.ax, e.ay, lerp(e.ax, P.x, 0.45 * shrink), lerp(e.ay, P.y, 0.45 * shrink), 14, 3, 0.6), fill });
ribbons.push({ d: ribbon(e.bx, e.by, lerp(e.bx, P.x, 0.3 * shrink), lerp(e.by, P.y, 0.3 * shrink), 11, 4, 0.6), fill });
continue;
}
const active = drag && (drag.kind === 'detach' || drag.kind === 'snap') && drag.key === key ? drag.p : null;
if (active) {
const P = active, dist = Math.hypot(P.x - h0.x, P.y - h0.y), neck = dist < 110 ? 4 + 4 * (1 - dist / 110) : 0;
if (neck > 0.5) {
ribbons.push({ d: ribbon(e.ax, e.ay, P.x, P.y, 16, Math.max(4, neck * 0.8), neck), fill });
ribbons.push({ d: ribbon(P.x, P.y, e.bx, e.by, neck, Math.max(4, neck * 0.8), 11), fill });
grips.push({ x: P.x, y: P.y, r: 7 });
} else {
ribbons.push({ d: ribbon(e.ax, e.ay, lerp(e.ax, P.x, 0.45), lerp(e.ay, P.y, 0.45), 14, 3, 0.6), fill });
ribbons.push({ d: ribbon(e.bx, e.by, lerp(e.bx, P.x, 0.3), lerp(e.by, P.y, 0.3), 9, 3, 0.6), fill });
grips.push({ x: P.x, y: P.y, r: 5 });
}
} else {
ribbons.push({ d: ribbon(e.ax, e.ay, e.bx, e.by, 16, 4.5, 11), fill, dim: focus && !dim ? 1 : 0 });
const pr = person(m.person);
// You can't pull your own ribbon, nor the team owner's (they always keep access).
if (vault(m.vault).can_manage && !pr.owner && pr.id !== data.me.id) handles.push({ key, x: h0.x, y: h0.y, dim });
}
}
let ghost: { d: string; cx: number; cy: number; c2: string } | null = null;
if (drag && ((drag.kind === 'grant' && drag.moved) || drag.kind === 'retract')) {
const a = pos(drag.v);
let E = drag.p;
if (tgt) { const q = pos(tgt.id), k = Math.max(0, Math.min(1, 1 - tgt.dist / 130)) * 0.55; E = { x: lerp(E.x, q.x, k), y: lerp(E.y, q.y, k) }; }
const c2 = tgt ? personColor(tgt.id).fill : vaultColor(drag.v).fill;
grads.push({ id: 'g-ghost', x1: a.x, y1: a.y, x2: E.x, y2: E.y, c1: vaultColor(drag.v).fill, c2 });
ghost = { d: ribbon(a.x, a.y, E.x, E.y, 16, 4.5, 9), cx: E.x, cy: E.y, c2 };
}
let hint = '', hintHot = false;
if (grantDrag) {
hint = hot ? `Release to give ${person(hot).name} access to ${vault(grantDrag.v).name}.` : 'Drop on a person to give access.';
hintHot = !!hot;
}
if (drag?.kind === 'detach') {
const [vId, pId] = drag.key.split('|'), e = ends({ vault: vId, person: pId });
const far = Math.hypot(drag.p.x - lerp(e.ax, e.bx, HANDLE_T), drag.p.y - lerp(e.ay, e.by, HANDLE_T)) > 110;
hint = far ? `Release to remove ${person(pId).name} from ${vault(vId).name}.` : 'Pull further to remove access.';
hintHot = far;
}
const manages = vaults.some((v) => v.can_manage);
const back = sel?.back;
const backLabel = !back ? '' : back.kind === 'overview' ? 'Vaults & people' : back.kind === 'vault' ? vault(back.id)?.name : person(back.id)?.name;
const open = (s: Sel) => setSel({ ...s, back: sel ?? undefined });
const boardStyle: React.CSSProperties = { width: `min(100%, calc((100dvh - 160px) * ${W / H}))`, aspectRatio: `${W} / ${H}` };
return (
<div className={`root${sel ? ' open' : ''}`}>
<header className="topbar">
<div className="float-card" style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '10px 16px 10px 12px' }}>
<svg width="34" height="34" viewBox="0 0 34 34" aria-hidden="true"><circle cx="9" cy="17" r="7" fill="#6A4BD0" /><circle cx="27" cy="17" r="5" fill="#BBA8F2" /><path d="M9 12 C16 15 20 15 27 13 L27 21 C20 19 16 19 9 22 Z" fill="#BBA8F2" /></svg>
<div style={{ display: 'flex', flexDirection: 'column' }}>
<span className="disp" style={{ fontSize: 20, fontWeight: 700, lineHeight: 1.1 }}>Team canvas</span>
<span style={{ fontSize: 13, color: 'var(--muted)' }}>{plural(vaults.length, 'vault')} · {plural(people.filter((p) => !p.invited).length, 'person', 'people')}</span>
</div>
</div>
<div className="float-card" style={{ display: 'flex', flexWrap: 'wrap', alignItems: 'center', gap: 8, padding: 6 }}>
<button className="btn btn-small btn-ghost" onClick={() => setSel({ kind: 'overview' })}>Vaults &amp; people</button>
<div className="seg" role="group" aria-label="Layout">
<button className="btn btn-small" aria-pressed={(blend ? blend.to : layout) === 'float'} onClick={() => setLayout('float')}>Float</button>
<button className="btn btn-small" aria-pressed={(blend ? blend.to : layout) === 'dock'} onClick={() => setLayout('dock')}>Dock</button>
</div>
{manages && <button className="btn btn-small btn-primary" onClick={() => setSheet('invite')}>Invite person</button>}
</div>
</header>
<div className="stage" onPointerDown={(e) => { if (e.target === e.currentTarget && !drag) setSel(null); }}>
{vaults.length === 0 ? (
<div className="empty"><div>
<h2 className="disp" style={{ margin: 0 }}>No vaults yet</h2>
<p className="muted">{data.me.owner ? 'Create one here, or move an existing vault onto the hub with `lunesync vault upload`.' : 'When someone gives you a vault, it shows up here.'}</p>
{data.me.owner && <button className="btn btn-primary" onClick={() => setSheet('vault')}>New vault</button>}
</div></div>
) : (
<div className="board" style={boardStyle}>
<svg ref={svgRef} viewBox={`0 0 ${W} ${H}`} role="img" aria-label="Vaults on the left, people on the right. Ribbons show who can sync which vault." style={{ display: 'block', width: '100%', height: 'auto', touchAction: 'none', userSelect: 'none' }} onPointerMove={onMove} onPointerUp={onUp} onPointerCancel={onUp}>
<defs>
<filter id="goo" x="-10%" y="-10%" width="120%" height="120%" colorInterpolationFilters="sRGB">
<feGaussianBlur in="SourceGraphic" stdDeviation="5" />
<feColorMatrix mode="matrix" values="1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 20 -8" />
</filter>
{grads.map((g) => (
<linearGradient key={g.id} id={g.id} gradientUnits="userSpaceOnUse" x1={g.x1} y1={g.y1} x2={g.x2} y2={g.y2}>
<stop offset="0.15" stopColor={g.c1} /><stop offset="0.85" stopColor={g.c2} />
</linearGradient>
))}
</defs>
<rect x="0" y="0" width={W} height={H} fill="transparent" onPointerDown={() => { if (!drag) setSel(null); }} />
<text x="200" y="44" textAnchor="middle" style={{ fontSize: 12, letterSpacing: 2, fill: 'var(--muted)' }}>VAULTS</text>
<text x="770" y="44" textAnchor="middle" style={{ fontSize: 12, letterSpacing: 2, fill: 'var(--muted)' }}>PEOPLE</text>
{/* Ribbons and node halos melt together (X4); a focused node's set is redrawn bright on top (X7). */}
<g className="fade" opacity={focus ? 0.22 : 0.85} filter="url(#goo)">
{ribbons.map((r, i) => <path key={`r${i}`} d={r.d} fill={r.fill} />)}
{blobs.map((b, i) => <path key={`b${i}`} className={bob} style={{ animationDelay: `${b.delay}s` }} d={b.d} fill={b.fill} />)}
{ghost && <><path d={ghost.d} fill="url(#g-ghost)" /><circle cx={ghost.cx} cy={ghost.cy} r="14" fill={ghost.c2} /></>}
</g>
<g className="fade" opacity="0.85" filter="url(#goo)">
{ribbons.filter((r) => r.dim !== undefined).map((r, i) => <path key={`dr${i}`} className="fade" d={r.d} fill={r.fill} opacity={r.dim} />)}
{blobs.map((b, i) => <path key={`db${i}`} className={`fade ${bob}`} style={{ animationDelay: `${b.delay}s` }} d={b.d} fill={b.fill} opacity={b.op} />)}
</g>
{ghost && <circle cx={ghost.cx} cy={ghost.cy} r="8" fill="#6A4BD0" />}
{grips.map((g, i) => <circle key={`gr${i}`} cx={g.x} cy={g.y} r={g.r} fill="#6A4BD0" stroke="#FFFFFF" strokeWidth="2" />)}
{vaults.map((v, i) => {
const p = pos(v.id), c = vaultColor(v.id), on = sel?.kind === 'vault' && sel.id === v.id, veil = relV(v.id) ? 0 : 0.65;
return (
<g key={v.id} transform={`translate(${p.x.toFixed(1)},${p.y.toFixed(1)})`}>
<g className={bob} style={{ animationDelay: `${(i * 0.7).toFixed(1)}s` }}>
<g
data-vault={v.name}
onPointerDown={(e) => (v.can_manage ? startGrant(v.id, e) : undefined)}
onClick={() => { if (!v.can_manage) setSel({ kind: 'vault', id: v.id }); }}
onPointerEnter={() => enter('vault', v.id)} onPointerLeave={leave}
style={{ cursor: v.can_manage ? 'grab' : 'pointer' }}
>
<rect x="-62" y="-28" width="124" height="56" rx="18" fill={hot && grantDrag?.v === v.id ? c.fill : c.tint} stroke={c.stroke} strokeWidth={on ? 3 : 1.5} />
<path d="M-50 -9 h14 l4 4 h8 v14 h-26 z" fill="none" stroke={c.stroke} strokeWidth="1.8" strokeLinejoin="round" />
<rect className="fade" x="-64" y="-30" width="128" height="60" rx="20" fill="#F5F3FB" opacity={veil} pointerEvents="none" />
</g>
</g>
</g>
);
})}
{people.map((pr, i) => {
const p = pos(pr.id), c = personColor(pr.id), on = sel?.kind === 'person' && sel.id === pr.id;
const veil = relP(pr.id) ? 0 : 0.65, n = pr.devices.length;
const angles = n === 1 ? [18] : n === 2 ? [-30, 30] : pr.devices.map((_, j) => -40 + (j * 80) / Math.max(1, n - 1));
return (
<g key={pr.id} className="fade" transform={`translate(${p.x.toFixed(1)},${p.y.toFixed(1)})`}>
<g className={bob} style={{ animationDelay: `${(0.35 + i * 0.6).toFixed(1)}s` }}>
{pr.devices.map((d, j) => {
const a = (angles[j] * Math.PI) / 180, cx = Math.cos(a) * 52, cy = Math.sin(a) * 52;
return (
<g key={d.id} className="fade" opacity={veil ? 0.35 : 1}>
<line x1="0" y1="0" x2={cx} y2={cy} stroke="#E2DDF0" strokeWidth="1.5" />
<circle cx={cx} cy={cy} r="6.5" fill={c.ring} stroke="#FFFFFF" strokeWidth="2" />
</g>
);
})}
<g data-person={pr.name} onClick={() => { if (!drag) setSel({ kind: 'person', id: pr.id }); }} onPointerEnter={() => enter('person', pr.id)} onPointerLeave={leave} style={{ cursor: 'pointer' }}>
<circle r="30" fill={pr.id === hot ? c.fill : c.tint} stroke={c.ring} strokeWidth={pr.id === hot ? 6 : on ? 4.5 : 3} strokeDasharray={pr.invited ? '5 5' : 'none'} />
<circle className="fade" r="34" fill="#F5F3FB" opacity={veil} pointerEvents="none" />
</g>
</g>
</g>
);
})}
{handles.map((h) => (
<g key={h.key} data-ribbon={`${vault(h.key.split('|')[0]).name}|${person(h.key.split('|')[1]).name}`} transform={`translate(${h.x.toFixed(1)},${h.y.toFixed(1)})`} opacity={h.dim ? 0.15 : 1} onPointerDown={(e) => startDetach(h.key, e)} style={{ cursor: 'grab' }}>
<circle r="16" fill="transparent" />
<circle r="5.5" fill="#6A4BD0" stroke="#FFFFFF" strokeWidth="2" />
</g>
))}
</svg>
<div aria-hidden="true" style={{ position: 'absolute', inset: 0, pointerEvents: 'none' }}>
{labels.map((l, i) => <div key={i} style={l.style}><span className={bob} style={l.inner}>{l.text}</span></div>)}
{people.map((pr, i) => {
const p = pos(pr.id), n = pr.devices.length;
const angles = n === 1 ? [18] : n === 2 ? [-30, 30] : pr.devices.map((_, j) => -40 + (j * 80) / Math.max(1, n - 1));
return pr.devices.map((d, j) => {
const a = (angles[j] * Math.PI) / 180;
return (
<div key={d.id} style={{ ...pct(p.x + Math.cos(a) * 52 + 11, p.y + Math.sin(a) * 52), transform: 'translateY(-50%)', opacity: relP(pr.id) ? 1 : 0.35 }}>
<span className={bob} style={{ display: 'inline-block', whiteSpace: 'nowrap', fontSize: 'max(1.1cqw, 9px)', color: 'var(--muted)', animationDelay: `${(0.35 + i * 0.6).toFixed(1)}s` }}>{d.label}</span>
</div>
);
});
})}
{hot && grantDrag && (() => {
const q = pos(hot);
return <div style={{ ...pct(q.x, q.y - 64), transform: 'translate(-50%,-50%)' }}><span style={{ display: 'inline-block', background: 'var(--ink)', color: '#FFF', fontWeight: 700, fontSize: '1.3cqw', padding: '0.5em 1em', borderRadius: 999, whiteSpace: 'nowrap' }}>Give {person(hot).name} {vault(grantDrag.v).name}</span></div>;
})()}
</div>
</div>
)}
</div>
<div className="bottombar">{hint && <span className={`chipbar${hintHot ? ' hot' : ''}`}>{hint}</span>}</div>
{!onboarded && manages && vaults.length > 0 && (
<div className="coach" role="note" aria-label="Getting started">
<span className="disp" style={{ fontSize: 17, fontWeight: 700 }}>Two moves to know</span>
<div className="tip"><span className="tipn">1</span><span>Drag a vault onto a person to give them access.</span></div>
<div className="tip"><span className="tipn">2</span><span>Pull the dot on a ribbon until it snaps to take access back. You can undo.</span></div>
<span className="muted">Click any vault or person for details and buttons.</span>
<button className="btn btn-small btn-primary" style={{ alignSelf: 'flex-end' }} onClick={() => { store('lune.onboarded', '1'); setOnboarded(true); }}>Got it</button>
</div>
)}
{sel && (
<aside aria-label="Details" className="panel">
{back && <button className="backbtn" onClick={() => setSel(back)}>‹ {backLabel}</button>}
{sel.kind === 'overview' && <Overview data={data} members={members} log={log} open={open} close={() => setSel(null)} newVault={() => setSheet('vault')} signOut={onSignOut} />}
{sel.kind === 'vault' && vault(sel.id) && (
<VaultPanel v={vault(sel.id)} data={data} members={members} open={open} close={() => setSel(null)}
cycleRole={cycleRole} remove={(m) => revoke(keyOf(m))} grant={grant}
toggleDelete={(v) => run(() => api.vaultSetting(v.name, !v.delete_from_devices), v.delete_from_devices ? `Removed people keep a read-only copy of ${v.name}.` : `Removed people's copies of ${v.name} are deleted from their devices.`)} />
)}
{sel.kind === 'person' && person(sel.id) && (
<PersonPanel p={person(sel.id)} data={data} members={members} open={open} close={() => setSel(null)} run={run} />
)}
</aside>
)}
{sheet === 'invite' && <InviteDialog vaults={vaults.filter((v) => v.can_manage)} owner={data.me.owner} close={() => { setSheet(null); reload(); }} />}
{sheet === 'vault' && <NewVaultDialog close={() => setSheet(null)} create={(name) => { setSheet(null); run(() => api.createVault(name), `${name} is ready. Drag it onto people to share it.`); }} />}
<div className="toast-wrap" aria-live="polite">
{toast && (
<div className="toast">
<span style={{ padding: '2px 8px 2px 0' }}>{toast.text}</span>
{toast.undo && <button className="undo" onClick={toast.undo}>Undo</button>}
</div>
)}
</div>
</div>
);
}
function Avatar({ p }: { p: Person }) {
const c = personColor(p.id);
return <span className="avatar" style={{ background: c.tint, borderColor: c.ring, borderStyle: p.invited ? 'dashed' : 'solid' }}>{p.name.charAt(0).toUpperCase()}</span>;
}
function Swatch({ v }: { v: Vault }) {
const c = vaultColor(v.id);
return (
<span className="swatch" style={{ background: c.tint, borderColor: c.fill }}>
<svg width="16" height="14" viewBox="0 0 18 16" aria-hidden="true"><path d="M1 2.5 h6 l2 2 h8 v10 h-16 z" fill="none" stroke={c.stroke} strokeWidth="1.8" strokeLinejoin="round" /></svg>
</span>
);
}
function CloseButton({ close }: { close: () => void }) {
return <button className="btn btn-small" aria-label="Close details" onClick={close}>✕</button>;
}
function Overview({ data, members, log, open, close, newVault, signOut }: {
data: CanvasData; members: Member[]; log: LogEntry[]; open: (s: Sel) => void; close: () => void; newVault: () => void; signOut: () => void;
}) {
return (
<>
<div className="panel-head"><h2 className="disp">Vaults &amp; people</h2><CloseButton close={close} /></div>
<section className="ov-sec" aria-label="Vaults">
<div className="ov-head"><h3>Vaults</h3><span className="ov-count">{data.vaults.length}</span></div>
{data.vaults.map((v) => (
<button key={v.id} className="row" onClick={() => open({ kind: 'vault', id: v.id })}>
<Swatch v={v} />
<span style={{ display: 'flex', flexDirection: 'column', flex: 1, minWidth: 0 }}><b>{v.name}</b><span className="sub">{plural(members.filter((m) => m.vault === v.id).length, 'person', 'people')}</span></span>
<span aria-hidden="true" className="chev">›</span>
</button>
))}
{data.me.owner && <button className="btn btn-small" style={{ alignSelf: 'flex-start', marginTop: 6 }} onClick={newVault}>New vault</button>}
</section>
<section className="ov-sec" aria-label="People">
<div className="ov-head"><h3>People</h3><span className="ov-count">{data.people.length}</span></div>
{data.people.map((p) => (
<button key={p.id} className="row" onClick={() => open({ kind: 'person', id: p.id })}>
<Avatar p={p} />
<span style={{ display: 'flex', flexDirection: 'column', flex: 1, minWidth: 0 }}>
<b>{p.name}</b>
<span className="sub">{p.invited ? 'Invited, not joined yet' : p.owner ? 'Team owner' : plural(members.filter((m) => m.person === p.id).length, 'vault')}</span>
</span>
<span aria-hidden="true" className="chev">›</span>
</button>
))}
</section>
{data.me.owner && log.length > 0 && (
<section className="ov-sec" aria-label="Recent activity">
<div className="ov-head"><h3>Recent activity</h3></div>
<ol className="log">
{log.map((e, i) => (
<li key={i}><i /><span style={{ display: 'flex', flexDirection: 'column', gap: 2 }}><span>{e.actor} · {e.action}: {e.detail}</span><span className="muted">{new Date(e.at * 1000).toLocaleString()}</span></span></li>
))}
</ol>
</section>
)}
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8 }}>
<span className="muted">Signed in as {data.me.person}</span>
<button className="btn btn-small" onClick={signOut}>Sign out</button>
</div>
</>
);
}
function VaultPanel({ v, data, members, open, close, cycleRole, remove, grant, toggleDelete }: {
v: Vault; data: CanvasData; members: Member[]; open: (s: Sel) => void; close: () => void;
cycleRole: (m: Member) => void; remove: (m: Member) => void; grant: (v: string, p: string) => void; toggleDelete: (v: Vault) => void;
}) {
const inVault = members.filter((m) => m.vault === v.id);
const outside = data.people.filter((p) => !inVault.some((m) => m.person === p.id));
const mine = inVault.find((m) => m.person === data.me.id);
return (
<>
<div className="panel-head">
<div><span className="eyebrow">Vault · {plural(inVault.length, 'person', 'people')}</span><h2 className="disp">{v.name}</h2></div>
<CloseButton close={close} />
</div>
{!v.can_manage && mine && <div className="note">You have {roleName(mine.role)} access. People with Manage decide who else can sync it.</div>}
<div>
<h3>People with access</h3>
{inVault.map((m) => {
const p = data.people.find((x) => x.id === m.person)!;
// Your own row and the team owner's can't be changed here (no locking yourself out by accident).
const fixed = p.owner || p.id === data.me.id;
return (
<div key={m.person} className="member">
<Avatar p={p} />
<button className="namebtn" onClick={() => open({ kind: 'person', id: p.id })}>{p.name}{p.invited ? ' (invited)' : ''}</button>
{v.can_manage && !fixed ? (
<button className="btn btn-small" aria-label={`${p.name}'s role is ${roleName(m.role)}. Change role`} onClick={() => cycleRole(m)}>{roleName(m.role)}</button>
) : (
<span className="muted">{roleName(m.role)}</span>
)}
{v.can_manage && !fixed && (
<button className="btn btn-small btn-danger" aria-label={`Remove ${p.name} from ${v.name}`} onClick={() => remove(m)}>Remove</button>
)}
</div>
);
})}
</div>
{v.can_manage && outside.length > 0 && (
<div>
<h3>Give access</h3>
<div className="chips">{outside.map((p) => <button key={p.id} className="btn btn-small" onClick={() => grant(v.id, p.id)}>+ {p.name}</button>)}</div>
</div>
)}
{v.can_manage && (
<div style={{ borderTop: '1px solid #EEEAF6', paddingTop: 16, display: 'flex', flexDirection: 'column', gap: 6 }}>
<h3>When someone is removed</h3>
<label className="check">
<input type="checkbox" checked={v.delete_from_devices} onChange={() => toggleDelete(v)} />
<span>Delete this vault from their devices, after their unshared work is sent to you</span>
</label>
<p className="muted">Removing someone only affects this vault. Copies made elsewhere can't be recalled.</p>
</div>
)}
</>
);
}
function PersonPanel({ p, data, members, open, close, run }: {
p: Person; data: CanvasData; members: Member[]; open: (s: Sel) => void; close: () => void;
run: (action: () => Promise<unknown>, ok?: string) => Promise<void>;
}) {
const [renaming, setRenaming] = useState<{ id: string; value: string } | null>(null);
const theirs = members.filter((m) => m.person === p.id);
const canEditDevices = p.id === data.me.id || data.me.owner;
const eyebrow = p.invited ? 'Invited' : p.owner ? 'Team owner' : 'Team member';
return (
<>
<div className="panel-head">
<div><span className="eyebrow">{eyebrow}</span><h2 className="disp">{p.name}</h2></div>
<CloseButton close={close} />
</div>
{p.invited && <div className="note">{p.name} hasn't joined yet. Vaults you give them now arrive once they join with their invite link.</div>}
{!p.invited && (
<div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
<h3>Devices</h3>
{p.devices.length === 0 && <p className="muted">{canEditDevices ? 'No devices yet.' : "Only their vault managers see someone's devices."}</p>}
{p.devices.map((d) => (
<div key={d.id} className="device">
{renaming?.id === d.id ? (
<form className="device-head" onSubmit={(e) => { e.preventDefault(); const label = renaming.value.trim(); setRenaming(null); if (label && label !== d.label) run(() => api.renameDevice(d.id, label), `Renamed to ${label}. New history entries carry this name.`); }}>
<label htmlFor={`rename-${d.id}`} className="eyebrow" style={{ position: 'absolute', left: -9999 }}>Device name</label>
<input id={`rename-${d.id}`} className="field" value={renaming.value} onChange={(e) => setRenaming({ id: d.id, value: e.target.value })} autoFocus maxLength={40} />
<button className="btn btn-small btn-primary" type="submit">Save</button>
<button className="btn btn-small" type="button" onClick={() => setRenaming(null)}>Cancel</button>
</form>
) : (
<div className="device-head">
<i style={{ width: 12, height: 12, borderRadius: '50%', background: personColor(p.id).ring, display: 'inline-block', flex: 'none' }} />
<b style={{ flex: 1 }}>{d.label}</b>
</div>
)}
{canEditDevices && renaming?.id !== d.id && (
<div className="chips">
<button className="btn btn-small" onClick={() => setRenaming({ id: d.id, value: d.label })}>Rename</button>
<button className="btn btn-small btn-danger" aria-label={`Remove device ${d.label}`} onClick={() => run(() => api.removeDevice(d.id), `${d.label} is removed. It sends anything unshared, then deletes its vault copies and stops working.`)}>Remove device</button>
</div>
)}
</div>
))}
</div>
)}
<div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
<h3>Vaults</h3>
{theirs.length === 0 && <p className="muted">None yet. Drag a vault onto {p.name} to share it.</p>}
{theirs.map((m) => {
const v = data.vaults.find((x) => x.id === m.vault)!;
return (
<button key={m.vault} className="row" onClick={() => open({ kind: 'vault', id: v.id })}>
<Swatch v={v} /><b style={{ flex: 1 }}>{v.name}</b><span className="sub">{roleName(m.role)}</span>
</button>
);
})}
</div>
</>
);
}
function InviteDialog({ vaults, owner, close }: { vaults: Vault[]; owner: boolean; close: () => void }) {
const [name, setName] = useState('');
const [picked, setPicked] = useState<Set<string>>(new Set());
const [link, setLink] = useState('');
const [error, setError] = useState('');
const [copied, setCopied] = useState(false);
const create = async (e: React.FormEvent) => {
e.preventDefault();
try {
const grants = vaults.filter((v) => picked.has(v.id)).map((v) => ({ vault: v.name, role: 'edit' as Role }));
setLink((await api.invite(name.trim(), grants)).link);
setError('');
} catch (err) {
setError((err as Error).message);
}
};
const command = `lunesync join ${link} --name "<their device>"`;
return (
<div className="scrim" onPointerDown={(e) => { if (e.target === e.currentTarget) close(); }}>
<div className="dialog" role="dialog" aria-modal="true" aria-label="Invite a person">
<h2 className="disp">Invite a person</h2>
{!link ? (
<form onSubmit={create} style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
<label className="lbl" htmlFor="invite-name">Name</label>
<input id="invite-name" className="field" value={name} onChange={(e) => setName(e.target.value)} placeholder="Sari" autoFocus />
{vaults.length > 0 && (
<fieldset style={{ border: 0, padding: 0, margin: 0, display: 'flex', flexDirection: 'column', gap: 8 }}>
<legend className="lbl" style={{ fontSize: 14, fontWeight: 700, marginBottom: 6 }}>Vaults they get (Edit){owner ? ' — optional' : ''}</legend>
{vaults.map((v) => (
<label key={v.id} className="check">
<input type="checkbox" checked={picked.has(v.id)} onChange={() => setPicked((s) => { const n = new Set(s); if (n.has(v.id)) n.delete(v.id); else n.add(v.id); return n; })} />
<span>{v.name}</span>
</label>
))}
</fieldset>
)}
<p className="muted">You'll get a one-time link to send them. They join with the sync app and appear here; give them more vaults by dragging.</p>
{error && <p className="error" role="alert">{error}</p>}
<div className="actions">
<button className="btn" type="button" onClick={close}>Cancel</button>
<button className="btn btn-primary" type="submit" disabled={!name.trim() || (!owner && picked.size === 0)}>Create invite link</button>
</div>
</form>
) : (
<>
<p style={{ margin: 0, lineHeight: 1.5 }}>Send this to {name.trim()} over a channel you trust. It works once, for 7 days. They run:</p>
<pre className="cmd">{command}</pre>
<div className="actions">
<button className="btn" onClick={() => navigator.clipboard?.writeText(command).then(() => setCopied(true))}>{copied ? 'Copied' : 'Copy'}</button>
<button className="btn btn-primary" onClick={close}>Done</button>
</div>
</>
)}
</div>
</div>
);
}
function NewVaultDialog({ close, create }: { close: () => void; create: (name: string) => void }) {
const [name, setName] = useState('');
return (
<div className="scrim" onPointerDown={(e) => { if (e.target === e.currentTarget) close(); }}>
<form className="dialog" role="dialog" aria-modal="true" aria-label="New vault" onSubmit={(e) => { e.preventDefault(); if (name.trim()) create(name.trim()); }}>
<h2 className="disp">New vault</h2>
<label className="lbl" htmlFor="vault-name">Name</label>
<input id="vault-name" className="field" value={name} onChange={(e) => setName(e.target.value)} placeholder="DevOps" autoFocus />
<p className="muted">It starts empty and arrives on your devices within a minute. To move an existing vault here, use <code>lunesync vault upload</code>.</p>
<div className="actions">
<button className="btn" type="button" onClick={close}>Cancel</button>
<button className="btn btn-primary" type="submit" disabled={!name.trim()}>Create</button>
</div>
</form>
</div>
);
}

81
web/src/api.ts Normal file
View File

@@ -0,0 +1,81 @@
// Talking to the hub. The session cookie signs requests; X-Lune marks them as coming from the canvas.
export type Role = 'read' | 'edit' | 'manage';
export interface Vault {
id: string;
name: string;
can_manage: boolean;
delete_from_devices: boolean;
}
export interface Device {
id: string;
label: string;
}
export interface Person {
id: string;
name: string;
owner: boolean;
/** Invited but not joined yet. */
invited: boolean;
devices: Device[];
}
export interface Member {
vault: string;
person: string;
role: Role;
}
export interface CanvasData {
me: { id: string; person: string; owner: boolean };
vaults: Vault[];
people: Person[];
members: Member[];
/** Removals waiting out their Undo window. */
pending: { id: number; vault: string; person: string }[];
}
export interface LogEntry {
at: number;
actor: string;
action: string;
detail: string;
}
export class SignedOut extends Error {}
async function call<T>(method: string, path: string, body?: unknown): Promise<T> {
const res = await fetch(path, {
method,
credentials: 'same-origin',
headers: { 'X-Lune': '1', ...(body ? { 'Content-Type': 'application/json' } : {}) },
body: body ? JSON.stringify(body) : undefined,
});
const data = await res.json().catch(() => ({}));
if (res.status === 401) throw new SignedOut(data.error ?? 'please sign in');
if (!res.ok) throw new Error(data.error ?? 'something went wrong on the hub');
return data as T;
}
export const api = {
canvas: () => call<CanvasData>('GET', '/api/canvas'),
log: (count = 8) => call<LogEntry[]>('GET', `/api/log?count=${count}`),
signin: (code: string) => call<object>('POST', '/api/web/signin', { code }),
signout: () => call<object>('POST', '/api/web/signout'),
grant: (person: string, vault: string, role: Role) => call<object>('POST', '/api/grants', { person, vault, role }),
inviteGrant: (person: string, vault: string, role: Role | null, remove = false) =>
call<object>('POST', '/api/invites/grant', { person, vault, role, remove }),
remove: (person: string, vault: string, delaySeconds: number) =>
call<{ pending?: number }>('POST', '/api/remove', { person, vault, delay_seconds: delaySeconds }),
undoRemove: (pending: number) => call<object>('POST', '/api/remove/undo', { pending }),
invite: (person: string, grants: { vault: string; role: Role }[]) =>
call<{ link: string }>('POST', '/api/invites', { person, grants }),
createVault: (name: string) => call<object>('POST', '/api/vaults', { name }),
vaultSetting: (vault: string, deleteFromDevices: boolean) =>
call<object>('POST', '/api/vaults/settings', { vault, delete_from_devices: deleteFromDevices }),
renameDevice: (deviceId: string, label: string) => call<object>('POST', '/api/devices/rename', { device_id: deviceId, label }),
removeDevice: (deviceId: string) => call<object>('POST', '/api/device/remove', { device_id: deviceId }),
};

81
web/src/geometry.ts Normal file
View File

@@ -0,0 +1,81 @@
// Shapes and places on the canvas. Coordinates are in the board's viewBox: 1000 wide, height grows with the team.
export type Pt = { x: number; y: number };
export type Layout = 'float' | 'dock';
export const W = 1000;
/** How far along a ribbon (vault → person) its grab dot sits. */
export const HANDLE_T = 0.8;
export function boardHeight(nVaults: number, nPeople: number): number {
return Math.max(620, 140 + Math.max(nVaults, nPeople) * 120);
}
/** Where each vault (left) and person (right) sits. Float is a loose scatter, Dock a tidy column. */
export function positions(vaults: string[], people: string[], layout: Layout, h: number): Record<string, Pt> {
const out: Record<string, Pt> = {};
const jitter = [35, -40, 45, -25, 20, -35];
const column = (ids: string[], x: number) => {
const top = 120, bottom = h - 90, n = ids.length;
ids.forEach((id, i) => {
const y = n === 1 ? h / 2 : top + (i * (bottom - top)) / (n - 1);
out[id] = { x: layout === 'float' ? x + jitter[i % jitter.length] : x, y };
});
};
column(vaults, 200);
column(people, 770);
return out;
}
export const lerp = (a: number, b: number, t: number) => a + (b - a) * t;
export function easeBack(t: number) {
const c = 1.3;
return 1 + (c + 1) * Math.pow(t - 1, 3) + c * Math.pow(t - 1, 2);
}
/** A ribbon from (x1,y1) to (x2,y2): w1/w2 half-widths at the ends, wm at the waist. */
export function ribbon(x1: number, y1: number, x2: number, y2: number, w1: number, wm: number, w2: number): string {
const dx = x2 - x1, dy = y2 - y1, L = Math.max(1, Math.hypot(dx, dy));
const ux = dx / L, uy = dy / L, nx = -uy, ny = ux, k = L * 0.35;
const f = (x: number, y: number) => `${x.toFixed(1)} ${y.toFixed(1)}`;
return (
`M${f(x1 + nx * w1, y1 + ny * w1)} C${f(x1 + ux * k + nx * wm, y1 + uy * k + ny * wm)} ${f(x2 - ux * k + nx * wm, y2 - uy * k + ny * wm)} ${f(x2 + nx * w2, y2 + ny * w2)}` +
` L${f(x2 - nx * w2, y2 - ny * w2)} C${f(x2 - ux * k - nx * wm, y2 - uy * k - ny * wm)} ${f(x1 + ux * k - nx * wm, y1 + uy * k - ny * wm)} ${f(x1 - nx * w1, y1 - ny * w1)} Z`
);
}
export function roundRect(cx: number, cy: number, w: number, h: number, r: number): string {
const x = cx - w / 2, y = cy - h / 2;
return `M${x + r} ${y} h${w - 2 * r} a${r} ${r} 0 0 1 ${r} ${r} v${h - 2 * r} a${r} ${r} 0 0 1 ${-r} ${r} h${-(w - 2 * r)} a${r} ${r} 0 0 1 ${-r} ${-r} v${-(h - 2 * r)} a${r} ${r} 0 0 1 ${r} ${-r} Z`;
}
export function circle(cx: number, cy: number, r: number): string {
return `M${cx - r} ${cy} a${r} ${r} 0 1 0 ${2 * r} 0 a${r} ${r} 0 1 0 ${-2 * r} 0 Z`;
}
/** Identity colors (X5): no green, amber, grey or red — those mean status. */
const VAULT_COLORS = [
{ fill: '#9B85F0', tint: '#ECE6FD', stroke: '#6A4BD0' },
{ fill: '#6FB4EA', tint: '#E2F0FB', stroke: '#2B78B0' },
{ fill: '#EE97B4', tint: '#FCE8EF', stroke: '#B9476E' },
{ fill: '#8FA0F5', tint: '#E8ECFD', stroke: '#3F51B5' },
{ fill: '#C58AE8', tint: '#F5EAFC', stroke: '#8A3FB0' },
{ fill: '#7CC3E0', tint: '#E3F4FA', stroke: '#2A7FA0' },
];
const PERSON_COLORS = [
{ fill: '#B3A2F6', tint: '#F2EEFE', ring: '#6A4BD0' },
{ fill: '#F0A6CA', tint: '#FDEEF5', ring: '#B0457A' },
{ fill: '#86CCD8', tint: '#E7F6F8', ring: '#2A8296' },
{ fill: '#D4A2E4', tint: '#F8EEFB', ring: '#8E4AA8' },
{ fill: '#9DB4F2', tint: '#ECF1FD', ring: '#3D5BB8' },
{ fill: '#E9A6E0', tint: '#FBEDF8', ring: '#A2448F' },
];
function pick<T>(list: T[], id: string): T {
let h = 0;
for (const c of id) h = (h * 31 + c.charCodeAt(0)) >>> 0;
return list[h % list.length];
}
export const vaultColor = (id: string) => pick(VAULT_COLORS, id);
export const personColor = (id: string) => pick(PERSON_COLORS, id);

81
web/src/main.tsx Normal file
View File

@@ -0,0 +1,81 @@
import { StrictMode, useEffect, useState } from 'react';
import { createRoot } from 'react-dom/client';
import { api, SignedOut, type CanvasData } from './api';
import { Canvas } from './Canvas';
import './styles.css';
/** Sign in with a code from one of your devices (no passwords, §8). */
function SignIn({ onDone }: { onDone: () => void }) {
const expired = new URLSearchParams(location.search).has('expired');
const [code, setCode] = useState('');
const [error, setError] = useState(expired ? 'That sign-in link was used or expired. Run `lunesync open` again, or use a code.' : '');
const submit = async (e: React.FormEvent) => {
e.preventDefault();
try {
await api.signin(code);
history.replaceState(null, '', '/');
onDone();
} catch (err) {
setError((err as Error).message);
}
};
return (
<main className="page">
<form className="card" onSubmit={submit}>
<span className="eyebrow">Lune</span>
<h1 className="disp">Sign in to the team canvas</h1>
<label htmlFor="code">Code from one of your devices</label>
<input id="code" className="field code" value={code} onChange={(e) => setCode(e.target.value)} placeholder="K7QD-4MXA" autoComplete="one-time-code" autoFocus />
{error && <p className="error" role="alert">{error}</p>}
<button className="btn btn-primary" type="submit" disabled={!code.trim()}>Sign in</button>
<p className="muted">Get a code with <code>lunesync pair</code>, or run <code>lunesync open</code> on a device to skip this page.</p>
</form>
</main>
);
}
/** What an invite link shows in a browser: how to join with the app. */
function Join() {
const link = location.href;
return (
<main className="page">
<div className="card">
<span className="eyebrow">Lune · invite</span>
<h1 className="disp">You're invited to a team</h1>
<p>Install the sync app, then join from the device you'll use (this link works once):</p>
<pre className="cmd">lunesync join {link} --name "My laptop"</pre>
<p className="muted">Pick any name for the device; your team sees it next to your changes. Shared vaults arrive in <code>~/Vaults</code>.</p>
</div>
</main>
);
}
function App() {
const [data, setData] = useState<CanvasData | null>(null);
const [state, setState] = useState<'loading' | 'signin' | 'ready' | 'error'>('loading');
const [error, setError] = useState('');
const load = async () => {
try {
setData(await api.canvas());
setState('ready');
} catch (e) {
if (e instanceof SignedOut) setState('signin');
else {
setError((e as Error).message);
setState('error');
}
}
};
useEffect(() => {
if (!location.pathname.startsWith('/join/')) load();
}, []);
if (location.pathname.startsWith('/join/')) return <Join />;
if (state === 'signin') return <SignIn onDone={load} />;
if (state === 'error') return <main className="page"><div className="card"><p className="error">{error}</p><button className="btn" onClick={load}>Try again</button></div></main>;
if (!data) return <main className="page" aria-busy="true" />;
return <Canvas data={data} reload={load} onSignOut={async () => { await api.signout().catch(() => {}); setState('signin'); }} />;
}
createRoot(document.getElementById('root')!).render(<StrictMode><App /></StrictMode>);

129
web/src/styles.css Normal file
View File

@@ -0,0 +1,129 @@
/* The team canvas, after Sen's prototype: ink on lavender paper, display type for names, a calm purple accent.
Status colors (green/amber/grey/red) are reserved for M6 and not used here (X6). */
:root {
--paper: #F5F3FB;
--dots: #DCD5EE;
--surface: #FFFFFF;
--ink: #221E33;
--muted: #6A6480;
--line: #E2DDF0;
--line-strong: #D7D0EC;
--accent: #6A4BD0;
--accent-hover: #5A3CC0;
--accent-soft: #F1EDFB;
--accent-tint: #E8E1FB;
--focus: #9B84EA;
--danger-ink: #A52A2F;
--font-display: 'Bricolage Grotesque', 'Avenir Next', system-ui, sans-serif;
--font-body: 'Atkinson Hyperlegible', system-ui, -apple-system, sans-serif;
}
* { box-sizing: border-box; }
html, body { margin: 0; height: 100%; }
body { background: var(--paper); color: var(--ink); font-family: var(--font-body); font-size: 15px; }
code, pre { font-family: ui-monospace, Menlo, monospace; font-size: 0.9em; }
.disp { font-family: var(--font-display); }
.muted { color: var(--muted); font-size: 13px; line-height: 1.5; margin: 0; }
.eyebrow { font-size: 12px; letter-spacing: 1.5px; text-transform: uppercase; color: var(--muted); font-weight: 700; }
.error { color: var(--danger-ink); margin: 0; font-size: 14px; }
.btn { font: inherit; font-size: 14px; min-height: 40px; padding: 8px 14px; border-radius: 12px; border: 1px solid var(--line-strong); background: var(--surface); color: var(--ink); cursor: pointer; }
.btn:hover { background: var(--accent-soft); }
.btn:disabled { opacity: 0.55; cursor: default; }
.btn-primary { background: var(--accent); border-color: var(--accent); color: #FFFFFF; }
.btn-primary:hover { background: var(--accent-hover); }
.btn-danger { color: var(--danger-ink); border-color: #EBC5C7; }
.btn-danger:hover { background: #FBEDED; }
.btn-small { min-height: 32px; padding: 4px 10px; font-size: 13px; border-radius: 10px; }
.btn-ghost { border-color: transparent; background: transparent; }
button:focus-visible, input:focus-visible, a:focus-visible { outline: 3px solid var(--focus); outline-offset: 2px; }
.field { font: inherit; font-size: 15px; padding: 10px 12px; border-radius: 12px; border: 1px solid var(--line-strong); background: var(--surface); color: var(--ink); width: 100%; }
.field.code { font-family: var(--font-display); font-size: 24px; letter-spacing: 3px; text-transform: uppercase; }
/* Sign-in and join pages */
.page { min-height: 100%; display: flex; align-items: center; justify-content: center; padding: 24px 16px; }
.card { background: var(--surface); border: 1px solid var(--line); border-radius: 24px; padding: 28px; width: 100%; max-width: 460px; display: flex; flex-direction: column; gap: 14px; box-shadow: 0 16px 40px rgba(34, 30, 51, 0.08); }
.card h1 { margin: 0; font-size: 26px; line-height: 1.15; }
.card p { margin: 0; line-height: 1.5; }
.card label { font-weight: 700; font-size: 14px; }
.cmd { background: #1E1B2E; color: #EDE9F8; border-radius: 12px; padding: 12px 14px; margin: 0; overflow-x: auto; white-space: pre-wrap; word-break: break-all; }
/* Canvas */
.root { height: 100vh; height: 100dvh; overflow: hidden; position: relative; background-color: var(--paper); background-image: radial-gradient(var(--dots) 1.2px, transparent 1.4px); background-size: 24px 24px; }
.bob { animation: bob 4.6s ease-in-out infinite; }
@keyframes bob { 0%, 100% { transform: translateY(0); } 50% { transform: translateY(-4px); } }
.fade { transition: opacity 0.2s ease; }
.stage { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; padding: 88px 24px 84px; transition: padding 0.3s ease; }
.board { position: relative; container-type: inline-size; }
.open .stage { padding-right: 428px; }
.topbar { position: absolute; top: 0; left: 0; right: 0; display: flex; flex-wrap: wrap; justify-content: space-between; align-items: flex-start; gap: 10px; padding: 16px; pointer-events: none; z-index: 12; }
.topbar > * { pointer-events: auto; }
.float-card { background: rgba(255, 255, 255, 0.94); border: 1px solid var(--line); border-radius: 18px; box-shadow: 0 6px 20px rgba(34, 30, 51, 0.08); }
.seg { display: flex; padding: 4px; gap: 4px; background: var(--accent-soft); border-radius: 14px; }
.seg .btn { border-color: transparent; background: transparent; color: var(--muted); }
.seg .btn[aria-pressed='true'] { background: #FFFFFF; color: var(--ink); font-weight: 700; box-shadow: 0 1px 3px rgba(34, 30, 51, 0.12); }
.bottombar { position: absolute; left: 16px; right: 16px; bottom: 16px; display: flex; flex-wrap: wrap; justify-content: space-between; align-items: flex-end; gap: 8px; pointer-events: none; z-index: 11; transition: right 0.3s ease; }
.open .bottombar { right: 428px; }
.chipbar { background: rgba(255, 255, 255, 0.94); border: 1px solid var(--line); border-radius: 999px; padding: 8px 14px; font-size: 13px; color: var(--muted); }
.chipbar.hot { color: #4B2FB0; font-weight: 700; }
.empty { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; pointer-events: none; }
.empty > div { pointer-events: auto; text-align: center; max-width: 360px; display: flex; flex-direction: column; gap: 10px; align-items: center; }
.panel { position: absolute; top: 84px; right: 16px; bottom: 16px; width: 396px; max-width: calc(100% - 32px); overflow-y: auto; background: var(--surface); border: 1px solid var(--line); border-radius: 24px; padding: 20px; display: flex; flex-direction: column; gap: 20px; box-shadow: 0 16px 40px rgba(34, 30, 51, 0.14); z-index: 15; animation: slidein 0.25s ease-out; }
.panel h2 { margin: 0; font-size: 24px; }
.panel h3 { margin: 0 0 6px; font-size: 12px; letter-spacing: 1.5px; color: var(--muted); font-weight: 700; text-transform: uppercase; }
.panel-head { display: flex; justify-content: space-between; align-items: flex-start; gap: 12px; }
.panel-head > div { display: flex; flex-direction: column; gap: 2px; min-width: 0; }
.backbtn { font: inherit; font-size: 13px; font-weight: 700; background: none; border: 0; color: var(--accent); cursor: pointer; padding: 6px 8px; margin: -8px 0 -6px -8px; border-radius: 8px; align-self: flex-start; }
.backbtn:hover { background: var(--accent-soft); }
.ov-sec { background: #F8F6FC; border: 1px solid #ECE8F5; border-radius: 18px; padding: 12px; display: flex; flex-direction: column; gap: 2px; }
.ov-head { display: flex; align-items: center; justify-content: space-between; padding: 2px 6px 8px; }
.ov-count { font-size: 12px; color: var(--muted); background: #FFFFFF; border: 1px solid var(--line); border-radius: 999px; padding: 1px 9px; }
.row { font: inherit; display: flex; align-items: center; gap: 12px; width: 100%; background: transparent; border: 0; border-radius: 12px; padding: 8px 6px; cursor: pointer; text-align: left; color: var(--ink); }
.row:hover { background: #FFFFFF; }
.row .sub { font-size: 13px; color: var(--muted); }
.chev { color: #A39DB8; font-size: 20px; line-height: 1; flex: none; }
.member { display: flex; align-items: center; gap: 10px; padding: 6px 0; }
.namebtn { font: inherit; font-weight: 700; flex: 1; text-align: left; background: none; border: 0; padding: 4px 0; cursor: pointer; color: var(--ink); min-width: 0; overflow: hidden; text-overflow: ellipsis; }
.namebtn:hover { color: var(--accent); text-decoration: underline; }
.avatar { width: 34px; height: 34px; border-radius: 50%; border: 3px solid; display: flex; align-items: center; justify-content: center; font-weight: 700; flex: none; }
.swatch { width: 34px; height: 34px; border-radius: 11px; border: 2px solid; display: flex; align-items: center; justify-content: center; flex: none; }
.device { border: 1px solid var(--line); border-radius: 16px; padding: 12px; display: flex; flex-direction: column; gap: 8px; }
.device-head { display: flex; align-items: center; gap: 10px; }
.chips { display: flex; gap: 8px; flex-wrap: wrap; }
.note { background: var(--accent-soft); border: 1px solid var(--line-strong); border-radius: 16px; padding: 14px; display: flex; flex-direction: column; gap: 8px; font-size: 14px; line-height: 1.45; }
.check { display: flex; gap: 10px; align-items: flex-start; font-size: 14px; cursor: pointer; line-height: 1.45; }
.check input { width: 18px; height: 18px; margin: 1px 0 0; accent-color: var(--accent); flex: none; }
.log { list-style: none; margin: 0; padding: 0 6px; display: flex; flex-direction: column; }
.log li { display: grid; grid-template-columns: 12px minmax(0, 1fr); gap: 10px; padding: 7px 0; font-size: 14px; line-height: 1.4; }
.log li i { width: 8px; height: 8px; border-radius: 50%; background: #BBA8F2; margin-top: 6px; display: block; }
.coach { position: absolute; left: 16px; bottom: 68px; z-index: 13; width: 320px; max-width: calc(100% - 32px); background: #FFFFFF; border: 1px solid var(--line); border-radius: 20px; padding: 16px; box-shadow: 0 12px 32px rgba(34, 30, 51, 0.14); display: flex; flex-direction: column; gap: 10px; }
.tip { display: flex; gap: 10px; font-size: 14px; line-height: 1.45; }
.tipn { width: 22px; height: 22px; border-radius: 50%; background: var(--accent-tint); color: #4B2FB0; font-weight: 700; font-size: 12px; display: flex; align-items: center; justify-content: center; flex: none; }
.scrim { position: fixed; inset: 0; background: rgba(34, 30, 51, 0.38); display: flex; align-items: center; justify-content: center; padding: 16px; z-index: 20; }
.dialog { background: #FFFFFF; border-radius: 24px; padding: 24px; width: 100%; max-width: 460px; display: flex; flex-direction: column; gap: 14px; max-height: calc(100dvh - 32px); overflow-y: auto; }
.dialog h2 { margin: 0; font-size: 22px; }
.dialog label.lbl { font-size: 14px; font-weight: 700; }
.actions { display: flex; justify-content: flex-end; gap: 10px; flex-wrap: wrap; }
.toast-wrap { position: fixed; left: 50%; bottom: 20px; transform: translateX(-50%); z-index: 30; width: max-content; max-width: calc(100% - 32px); }
.toast { background: var(--ink); color: #FFFFFF; padding: 10px 10px 10px 18px; border-radius: 14px; font-size: 14px; line-height: 1.4; box-shadow: 0 8px 24px rgba(34, 30, 51, 0.25); display: flex; align-items: center; gap: 12px; }
.undo { font: inherit; font-size: 14px; font-weight: 700; background: none; border: 0; color: #C9B8FF; cursor: pointer; padding: 6px 8px; border-radius: 8px; }
.undo:hover { background: rgba(255, 255, 255, 0.1); }
@keyframes slidein { from { transform: translateX(24px); opacity: 0; } to { transform: none; opacity: 1; } }
@keyframes slideup { from { transform: translateY(24px); opacity: 0; } to { transform: none; opacity: 1; } }
@media (max-width: 720px) {
.stage { padding: 136px 8px 64px; }
.open .stage { padding-right: 8px; padding-bottom: 58vh; }
.panel { top: auto; left: 8px; right: 8px; bottom: 8px; width: auto; max-width: none; height: 56vh; animation-name: slideup; }
.open .bottombar { display: none; }
.coach { bottom: 16px; }
}
@media (prefers-reduced-motion: reduce) {
.bob { animation: none; }
.panel { animation: none; }
.stage, .bottombar, .fade { transition: none; }
}

16
web/tsconfig.json Normal file
View File

@@ -0,0 +1,16 @@
{
"compilerOptions": {
"target": "ES2020",
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"module": "ESNext",
"moduleResolution": "bundler",
"jsx": "react-jsx",
"strict": true,
"noEmit": true,
"skipLibCheck": true,
"isolatedModules": true,
"noUnusedLocals": true,
"noUnusedParameters": true
},
"include": ["src"]
}

1
web/tsconfig.tsbuildinfo Normal file
View File

@@ -0,0 +1 @@
{"root":["./src/canvas.tsx","./src/api.ts","./src/geometry.ts","./src/main.tsx"],"version":"5.6.3"}

8
web/vite.config.ts Normal file
View File

@@ -0,0 +1,8 @@
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
// `npm run dev` talks to a hub on :8080; `npm run build` output is embedded in the hub binary.
export default defineConfig({
plugins: [react()],
server: { proxy: { '/api': 'http://127.0.0.1:8080', '/signin/': 'http://127.0.0.1:8080' } },
});