chadtmiller.com/hud
A remote MCP server that shows atproto records as interactive UI inside MCP Apps hosts
place.hud.hudkit 0.6.0 Latest 5 packages
0
0
Sign in by handle on web and iOS, switch accounts, delete your data
crates/hud/src/main.rs+7−0
| @@ -78,6 +78,8 @@ Configuration, from the environment: | ||
HUD_RELAY the relay asked which repositories hold people's | ||
workspace themes, to browse everyone's; empty lists | ||
only an account's (https://bsky.network) | ||
HUD_SIGN_UP_PDS the PDS \"Create one\" makes a new account at, an | ||
origin (https://selfhosted.social) | ||
RUST_LOG log filter (info) | ||
"; | ||
| ||
| @@ -250,6 +252,10 @@ fn config() -> Result<Config, String> { | ||
return Err("HUD_RELAY is not valid text".into()); | ||
} | ||
}; | ||
let sign_up_pds = match var("HUD_SIGN_UP_PDS")? { | ||
Some(u) => origin("HUD_SIGN_UP_PDS", &u)?, | ||
None => hud_core::config::SIGN_UP_PDS.to_string(), | ||
}; | ||
Ok(Config { | ||
port, | ||
bind, | ||
| @@ -268,6 +274,7 @@ fn config() -> Result<Config, String> { | ||
favicons, | ||
image_cdn, | ||
relay, | ||
sign_up_pds, | ||
}) | ||
} | ||
| ||
crates/hud/tests/cli.rs+5−0
| @@ -268,6 +268,7 @@ fn serves_with_sign_in_and_spaces_and_stops_on_sigint() { | ||
("HUD_FAVICONS", " http://127.0.0.1:9/favicon?url= "), | ||
("HUD_IMAGE_CDN", "https://cdn.test/img/"), | ||
("HUD_RELAY", " "), | ||
("HUD_SIGN_UP_PDS", "https://pds.test"), | ||
], | ||
); | ||
assert!(server.said("canvases go in people's own spaces")); | ||
| @@ -403,6 +404,10 @@ fn refuses_configuration_it_cannot_use() { | ||
&[("HUD_RELAY", "ftp://relay.example")], | ||
r#"HUD_RELAY: "ftp://relay.example" is not an http or https URL, as https://bsky.network"#, | ||
), | ||
( | ||
&[("HUD_SIGN_UP_PDS", "https://pds.example/signup")], | ||
r#"HUD_SIGN_UP_PDS: "https://pds.example/signup" is not an http or https origin"#, | ||
), | ||
]; | ||
for (env, message) in cases { | ||
let said = refused(env); | ||
crates/hud-core/src/canvas/canonical.rs+1−0
| @@ -148,6 +148,7 @@ mod tests { | ||
data_dir: dir, | ||
oauth: false, | ||
oauth_scope: crate::scope::asked(false), | ||
sign_up_pds: crate::config::SIGN_UP_PDS.into(), | ||
spaces: false, | ||
plc_url: "http://127.0.0.1:9".into(), | ||
handle_resolver: None, | ||
crates/hud-core/src/canvas/engine.rs+272−26
| @@ -32,6 +32,16 @@ pub struct Who<'a> { | ||
pub handle: Option<&'a str>, | ||
} | ||
| ||
/// What a person has in the canvases: those they own, each its id, name | ||
/// and how many others are in it, invited ones too; how many of others' | ||
/// they are in; and how many invitations wait for them. | ||
#[derive(Debug, PartialEq)] | ||
pub struct Holding { | ||
pub owned: Vec<(String, String, usize)>, | ||
pub shared: usize, | ||
pub invited: usize, | ||
} | ||
| ||
/// Why something was not done. | ||
#[derive(Debug, PartialEq)] | ||
pub enum Refused { | ||
| @@ -961,6 +971,39 @@ impl Canvases { | ||
tid | ||
} | ||
}; | ||
let (events, kept) = self.keep_tiles(&info, tiles, &before, &gone).await; | ||
if let Err(e) = kept { | ||
tracing::error!(canvas = id, error = %e, "could not keep a canvas"); | ||
} | ||
let count = tiles.len(); | ||
let tile = match tiles.iter().find(|t| t.id == answer) { | ||
Some(t) => t.clone(), | ||
None => gone | ||
.into_iter() | ||
.find(|g| g.id == answer) | ||
.ok_or(Refused::NoTile(answer))?, | ||
}; | ||
drop(slot); | ||
self.dir() | ||
.await | ||
.canvases | ||
.get_mut(id) | ||
.into_iter() | ||
.for_each(|e| e.tiles = count); | ||
self.tell_tiles(id, events, &Cause::of(who, by)); | ||
Ok(tile) | ||
} | ||
| ||
/// A change to a canvas's tiles, its lock held, kept: `gone` taken | ||
/// off, and each tile whose place `before` does not hold as it now is | ||
/// changed, or added. Its events, and whether the store kept it. | ||
async fn keep_tiles( | ||
&self, | ||
info: &CanvasInfo, | ||
tiles: &[Tile], | ||
before: &HashMap<String, Placement>, | ||
gone: &[Tile], | ||
) -> (Vec<Event>, Result<(), String>) { | ||
let changed: Vec<&Tile> = tiles | ||
.iter() | ||
.filter(|t| before.get(&t.id) != Some(&placement(t))) | ||
| @@ -985,7 +1028,7 @@ impl Canvases { | ||
let kept = self | ||
.store | ||
.write(Change::Tiles { | ||
info: &info, | ||
info, | ||
tiles, | ||
changed, | ||
gone: gone | ||
| @@ -994,25 +1037,11 @@ impl Canvases { | ||
.collect(), | ||
}) | ||
.await; | ||
if let Err(e) = kept { | ||
tracing::error!(canvas = id, error = %e, "could not keep a canvas"); | ||
} | ||
let count = tiles.len(); | ||
let tile = match tiles.iter().find(|t| t.id == answer) { | ||
Some(t) => t.clone(), | ||
None => gone | ||
.into_iter() | ||
.find(|g| g.id == answer) | ||
.ok_or(Refused::NoTile(answer))?, | ||
}; | ||
drop(slot); | ||
self.dir() | ||
.await | ||
.canvases | ||
.get_mut(id) | ||
.into_iter() | ||
.for_each(|e| e.tiles = count); | ||
let cause = Cause::of(who, by); | ||
(events, kept) | ||
} | ||
| ||
/// Everyone in a canvas told of changes to its tiles, by `cause`. | ||
fn tell_tiles(&self, id: &str, events: Vec<Event>, cause: &Cause) { | ||
for event in events { | ||
self.hub.tell( | ||
id, | ||
| @@ -1023,7 +1052,6 @@ impl Canvases { | ||
}, | ||
); | ||
} | ||
Ok(tile) | ||
} | ||
| ||
/// Change a canvas's info, its lock held: `f` checks and changes it. | ||
| @@ -1133,22 +1161,39 @@ impl Canvases { | ||
/// Delete a canvas, its owner's alone: out of everyone's tabs. | ||
pub async fn delete(&self, who: Who<'_>, id: &str) -> Result<(), Refused> { | ||
let _ops = self.ops.lock().await; | ||
if let Err(e) = self.drop_canvas(who, id, false).await? { | ||
tracing::error!(canvas = id, error = %e, "could not delete a canvas"); | ||
} | ||
Ok(()) | ||
} | ||
| ||
/// Delete a canvas, `ops` held, as `delete` does: whether the store | ||
/// deleted it. Where it did not and `keep_failed`, the canvas stays as | ||
/// it was, everyone's tabs too, so asking again finds it to delete. | ||
async fn drop_canvas( | ||
&self, | ||
who: Who<'_>, | ||
id: &str, | ||
keep_failed: bool, | ||
) -> Result<Result<(), String>, Refused> { | ||
let (info, _) = self.seen(who.did, id).await?; | ||
Self::owner_only(&info, who.did, "deletes it")?; | ||
let open = self.open(id); | ||
{ | ||
let kept = { | ||
let _slot = open.tiles.lock().await; | ||
if let Err(e) = self.store.write(Change::Deleted(&info)).await { | ||
tracing::error!(canvas = id, error = %e, "could not delete a canvas"); | ||
let kept = self.store.write(Change::Deleted(&info)).await; | ||
if kept.is_err() && keep_failed { | ||
return Ok(kept); | ||
} | ||
let mut d = self.dir().await; | ||
d.canvases.remove(id); | ||
for m in &info.members { | ||
d.put_away(&m.did, id); | ||
} | ||
} | ||
kept | ||
}; | ||
self.told(&info, &info, &Cause::of(who, By::Person)).await; | ||
Ok(()) | ||
Ok(kept) | ||
} | ||
| ||
/// Invite someone (`did`, verified `handle`) to a canvas as an editor or | ||
| @@ -1415,6 +1460,134 @@ impl Canvases { | ||
self.tiles(who, id).await | ||
} | ||
| ||
/// What a person has in the canvases, theirs in spaces read first, as | ||
/// `forget` would delete it. | ||
pub async fn holding(&self, who: Who<'_>) -> Holding { | ||
self.place(who).await; | ||
let d = self.dir().await; | ||
let mut owned: Vec<&Entry> = Vec::new(); | ||
let (mut shared, mut invited) = (0, 0); | ||
for e in d.canvases.values() { | ||
match e.info.member(who.did) { | ||
Some(m) if m.role == Role::Owner => owned.push(e), | ||
Some(m) if m.joined => shared += 1, | ||
Some(_) => invited += 1, | ||
None => {} | ||
} | ||
} | ||
owned.sort_by(|a, b| { | ||
(&a.info.created_at, &a.info.id).cmp(&(&b.info.created_at, &b.info.id)) | ||
}); | ||
Holding { | ||
owned: owned | ||
.iter() | ||
.map(|e| { | ||
let others = e.info.members.iter().filter(|m| m.did != who.did).count(); | ||
(e.info.id.clone(), e.info.name.clone(), others) | ||
}) | ||
.collect(), | ||
shared, | ||
invited, | ||
} | ||
} | ||
| ||
/// Everything of a person's in the canvases deleted: each canvas they | ||
/// own, for everyone in it, as `delete` does; in each canvas of | ||
/// others, the tiles they made taken off, then they leave it (or | ||
/// decline it), as `remove` does; then their tabs, and what the store | ||
/// keeps of theirs past that (`Store::forget`). How many canvases, | ||
/// tiles and memberships went; else, all else done, what was not. | ||
pub async fn forget(&self, who: Who<'_>) -> Result<usize, String> { | ||
self.place(who).await; | ||
let (owned, others): (Vec<String>, Vec<String>) = { | ||
let d = self.dir().await; | ||
let (owned, others): (Vec<&Entry>, Vec<&Entry>) = d | ||
.canvases | ||
.values() | ||
.filter(|e| e.info.member(who.did).is_some()) | ||
.partition(|e| e.info.owner == who.did); | ||
let ids = |es: Vec<&Entry>| es.iter().map(|e| e.info.id.clone()).collect(); | ||
(ids(owned), ids(others)) | ||
}; | ||
let mut deleted = 0; | ||
let mut failed: Vec<String> = Vec::new(); | ||
for id in owned { | ||
let _ops = self.ops.lock().await; | ||
match self.drop_canvas(who, &id, true).await { | ||
Ok(Ok(())) => deleted += 1, | ||
Ok(Err(e)) => failed.push(format!("canvas {id}: {e}")), | ||
// Deleted meanwhile: nothing of it left. | ||
Err(_) => {} | ||
} | ||
} | ||
for id in others { | ||
// Their tiles first: once out, nothing of theirs there is found. | ||
match self.retract(who, &id).await { | ||
Ok(n) => deleted += n, | ||
Err(e) => { | ||
failed.push(format!("your tiles on canvas {id}: {e}")); | ||
continue; | ||
} | ||
} | ||
// Gone or left meanwhile: nothing to count. | ||
deleted += usize::from(self.remove(who, &id, who.did).await.is_ok()); | ||
} | ||
{ | ||
let mut d = self.dir().await; | ||
d.open.remove(who.did); | ||
d.current.remove(who.did); | ||
d.settled.remove(who.did); | ||
} | ||
if let Err(lines) = self.store.forget(who.did).await { | ||
failed.extend(lines); | ||
} | ||
self.nudge(who.did, None, None); | ||
let (did, failures) = (who.did, failed.len()); | ||
tracing::info!(did, deleted, failures, "a person's canvases deleted"); | ||
if failed.is_empty() { | ||
Ok(deleted) | ||
} else { | ||
Err(failed.join("; ")) | ||
} | ||
} | ||
| ||
/// Take off a canvas every tile `who` made there, whatever their role | ||
/// now, as removing each would: one change, everyone in it told. How | ||
/// many went. | ||
async fn retract(&self, who: Who<'_>, id: &str) -> Result<usize, String> { | ||
let open = self.open(id); | ||
let mut slot = open.tiles.lock().await; | ||
let Some(info) = self.info_of(id).await else { | ||
return Ok(0); | ||
}; | ||
let tiles = self.loaded(&mut slot, &info).await; | ||
let before: HashMap<String, Placement> = | ||
tiles.iter().map(|t| (t.id.clone(), placement(t))).collect(); | ||
let mine: Vec<String> = tiles | ||
.iter() | ||
.filter(|t| t.author == who.did) | ||
.map(|t| t.id.clone()) | ||
.collect(); | ||
if mine.is_empty() { | ||
return Ok(0); | ||
} | ||
let gone: Vec<Tile> = mine | ||
.iter() | ||
.filter_map(|tid| strip::remove(tiles, tid).ok()) | ||
.collect(); | ||
let (events, kept) = self.keep_tiles(&info, tiles, &before, &gone).await; | ||
let count = tiles.len(); | ||
drop(slot); | ||
self.dir() | ||
.await | ||
.canvases | ||
.get_mut(id) | ||
.into_iter() | ||
.for_each(|e| e.tiles = count); | ||
self.tell_tiles(id, events, &Cause::of(who, By::Person)); | ||
kept.map(|()| gone.len()) | ||
} | ||
| ||
/// A tile of a canvas, for a member. | ||
pub async fn tile(&self, who: Who<'_>, id: &str, tid: &str) -> Result<Tile, Refused> { | ||
self.tiles(who, id) | ||
| @@ -1949,6 +2122,10 @@ mod tests { | ||
self.files.retire_legacy(did) | ||
} | ||
| ||
fn forget<'a>(&'a self, did: &'a str) -> Fut<'a, Result<(), Vec<String>>> { | ||
self.files.forget(did) | ||
} | ||
| ||
fn person<'a>(&'a self, _did: &'a str) -> Fut<'a, Option<Vec<(CanvasInfo, usize)>>> { | ||
Box::pin(async { Some(Vec::new()) }) | ||
} | ||
| @@ -2010,6 +2187,75 @@ mod tests { | ||
std::fs::remove_dir_all(&d).unwrap(); | ||
} | ||
| ||
#[tokio::test] | ||
async fn a_persons_canvases_forgotten_past_failures() { | ||
let d = dir(); | ||
let (store, failing) = Faulty::new(d.clone()); | ||
let c = Canvases::new(Box::new(store)); | ||
// Hers, and Bob's, which she is in with a tile of hers. | ||
let mine = c.resolve(A, None).await.unwrap(); | ||
let bobs = c.create(B, "Bob's", By::Person).await.unwrap().id; | ||
c.invite(B, &bobs, A.did, A.handle, Role::Editor) | ||
.await | ||
.unwrap(); | ||
c.open_canvas(A, &bobs).await.unwrap(); | ||
c.apply(A, &bobs, add("describe_repo"), By::Person) | ||
.await | ||
.unwrap(); | ||
// And one she is invited to, with no tile of hers. | ||
let empty = c.create(B, "Empty", By::Person).await.unwrap().id; | ||
c.invite(B, &empty, A.did, A.handle, Role::Viewer) | ||
.await | ||
.unwrap(); | ||
// Its writes failing: what was not deleted, said. | ||
failing.store(true, Ordering::Relaxed); | ||
assert_eq!( | ||
c.forget(A).await, | ||
Err(format!( | ||
"canvas {mine}: the disk is full; your tiles on canvas {bobs}: the disk is full" | ||
)) | ||
); | ||
// Hers, not deleted, still there to delete. | ||
assert!(c.sees(A.did, &mine).await); | ||
// Asked again, writes kept: hers deleted, her tile goes from Bob's, | ||
// then she leaves it. | ||
failing.store(false, Ordering::Relaxed); | ||
assert_eq!(c.forget(A).await, Ok(3)); | ||
assert!(!c.sees(A.did, &mine).await); | ||
assert!(!d.join(format!("{mine}.json")).exists()); | ||
assert!(!c.sees(A.did, &bobs).await); | ||
assert!(c.tiles(B, &bobs).await.unwrap().is_empty()); | ||
std::fs::remove_dir_all(&d).unwrap(); | ||
} | ||
| ||
#[tokio::test] | ||
async fn canvases_gone_while_forgetting_waits_count_for_nothing() { | ||
let d = dir(); | ||
let c = Canvases::new(Box::new(FileStore::new(d.clone()))); | ||
let mine = c.resolve(A, None).await.unwrap(); | ||
let bobs = c.create(B, "Bob's", By::Person).await.unwrap().id; | ||
c.invite(B, &bobs, A.did, A.handle, Role::Editor) | ||
.await | ||
.unwrap(); | ||
c.open_canvas(A, &bobs).await.unwrap(); | ||
c.apply(A, &bobs, add("describe_repo"), By::Person) | ||
.await | ||
.unwrap(); | ||
// Each deleted while forgetting waits its turn at it. | ||
let ops = c.ops.lock().await; | ||
let open = c.open(&bobs); | ||
let slot = open.tiles.lock().await; | ||
let mut forgetting = std::pin::pin!(c.forget(A)); | ||
assert!(futures::poll!(forgetting.as_mut()).is_pending()); | ||
c.dir().await.canvases.remove(&mine); | ||
drop(ops); | ||
assert!(futures::poll!(forgetting.as_mut()).is_pending()); | ||
c.dir().await.canvases.remove(&bobs); | ||
drop(slot); | ||
assert_eq!(forgetting.await, Ok(0)); | ||
std::fs::remove_dir_all(&d).unwrap(); | ||
} | ||
| ||
#[tokio::test] | ||
async fn first_uses_at_once_make_one_canvas() { | ||
let d = dir(); | ||
crates/hud-core/src/canvas/mod.rs+1−1
| @@ -22,7 +22,7 @@ pub mod store; | ||
mod strip; | ||
mod tools; | ||
| ||
pub use engine::{Canvases, Cause, Notice, Refused, Watch, Who}; | ||
pub use engine::{Canvases, Cause, Holding, Notice, Refused, Watch, Who}; | ||
pub use tools::definitions; | ||
| ||
use crate::tools::is_me; | ||
crates/hud-core/src/canvas/space.rs+136−0
| @@ -791,6 +791,84 @@ impl Inner { | ||
.insert(uri.to_string()); | ||
} | ||
| ||
/// What is kept of a person's past their canvases deleted: their | ||
/// files (`FileStore::forget`), what memory holds of theirs, and every | ||
/// workspace space of theirs their sign-in reaches, each deleted, or | ||
/// failing that, as a grant without deleting spaces does, emptied of | ||
/// its records. Every failure, in a line each. | ||
async fn forget(&self, did: &str) -> Result<(), Vec<String>> { | ||
let mut failed = self.files.forget(did).await.err().unwrap_or_default(); | ||
{ | ||
let mut st = self.lock(); | ||
let theirs = | ||
|uri: &str| atproto::space::SpaceRef::parse(uri).is_ok_and(|s| s.authority == did); | ||
let ids: Vec<String> = st | ||
.kept | ||
.iter() | ||
.filter(|(_, k)| k.info.owner == did) | ||
.map(|(id, _)| id.clone()) | ||
.collect(); | ||
for id in &ids { | ||
st.kept.remove(id); | ||
st.waiting.retain(|(c, _), _| c != id); | ||
} | ||
st.left.retain(|_, uri| !theirs(uri)); | ||
st.doomed.remove(did); | ||
st.people.remove(did); | ||
} | ||
let hud = self.hud.upgrade(); | ||
let reach = match &hud { | ||
Some(hud) => self.reach(hud, did).await.filter(|r| grants(&r.scope)), | ||
None => None, | ||
}; | ||
if let (Some(hud), Some(r)) = (hud, reach) { | ||
let listed = match hud.spaces_alpha(&r.pds).await { | ||
Ok(false) => Ok(Vec::new()), | ||
Ok(true) => hud | ||
.spaces_of(&r.account, SPACE_TYPE) | ||
.await | ||
.map_err(|f| f.line()), | ||
Err(why) => Err(format!("your PDS could not be reached: {why}")), | ||
}; | ||
match listed { | ||
Err(why) => failed.push(format!("your workspace spaces were not listed: {why}")), | ||
Ok(listed) => { | ||
for uri in listed { | ||
let ours = atproto::space::SpaceRef::parse(&uri) | ||
.is_ok_and(|s| s.authority == did && s.kind == SPACE_TYPE); | ||
if !ours { | ||
continue; | ||
} | ||
if let Err(f) = Self::delete_whole(&hud, &r, &uri).await { | ||
failed.push(format!("{uri} was not deleted: {}", f.line())); | ||
} | ||
} | ||
} | ||
} | ||
} | ||
if failed.is_empty() { | ||
Ok(()) | ||
} else { | ||
Err(failed) | ||
} | ||
} | ||
| ||
/// Delete a space of `r`'s; failing that for want of permission, its | ||
/// records in it. | ||
async fn delete_whole(hud: &Hud, r: &Reach, uri: &str) -> Result<(), Failure> { | ||
match hud.delete_space(&r.account, uri).await { | ||
Err(f) if !f.transient() => { | ||
for rec in hud.space_records(&r.account, uri).await? { | ||
hud.delete_space_record(&r.account, uri, &rec.collection, &rec.rkey) | ||
.await?; | ||
} | ||
tracing::info!(space = uri, "a space emptied, as it was not deleted"); | ||
Ok(()) | ||
} | ||
done => done, | ||
} | ||
} | ||
| ||
/// Write a placed tile once its last such change is a second | ||
/// old, and again if it changes so while written. | ||
async fn settle_tile(self: Arc<Self>, key: (String, String)) { | ||
| @@ -949,6 +1027,10 @@ impl Store for SpaceStore { | ||
fn flush(&self) -> Fut<'_, ()> { | ||
Box::pin(self.inner.flush()) | ||
} | ||
| ||
fn forget<'a>(&'a self, did: &'a str) -> Fut<'a, Result<(), Vec<String>>> { | ||
Box::pin(self.inner.forget(did)) | ||
} | ||
} | ||
| ||
#[cfg(test)] | ||
| @@ -1241,6 +1323,7 @@ mod tests { | ||
data_dir: dir.join("data"), | ||
oauth: false, | ||
oauth_scope: crate::scope::asked(false), | ||
sign_up_pds: crate::config::SIGN_UP_PDS.into(), | ||
spaces: false, | ||
plc_url: "http://127.0.0.1:9".into(), | ||
handle_resolver: None, | ||
| @@ -1432,4 +1515,57 @@ mod tests { | ||
assert_eq!(store.inner.lock().people[ALICE].failures, 0); | ||
std::fs::remove_dir_all(&d).unwrap(); | ||
} | ||
| ||
#[tokio::test] | ||
async fn forgotten_from_memory_with_the_server_gone() { | ||
let d = dir(); | ||
let inner = serverless(&d); | ||
const BOB: &str = "did:plc:bob"; | ||
let bobs = "0000000000bb"; | ||
{ | ||
let mut st = inner.lock(); | ||
st.kept.insert(ID.into(), in_space()); | ||
let mut his = in_space(); | ||
his.info.owner = BOB.into(); | ||
st.kept.insert(bobs.into(), his); | ||
st.waiting | ||
.insert((ID.into(), "00000000000a".into()), Some(Instant::now())); | ||
st.waiting | ||
.insert((bobs.into(), "00000000000a".into()), Some(Instant::now())); | ||
let left = |did: &str, id: &str| space::uri(did, SPACE_TYPE, id); | ||
st.left | ||
.insert("0000000000cc".into(), left(ALICE, "0000000000cc")); | ||
st.left | ||
.insert("0000000000dd".into(), left(BOB, "0000000000dd")); | ||
st.doomed | ||
.entry(ALICE.into()) | ||
.or_default() | ||
.insert(in_space().uri); | ||
st.people.insert( | ||
ALICE.into(), | ||
Person { | ||
key: None, | ||
choice: Choice::Space, | ||
failures: 0, | ||
decided: Instant::now(), | ||
}, | ||
); | ||
} | ||
// Nothing of hers kept in memory after; Bob's as it was. | ||
assert_eq!(inner.forget(ALICE).await, Ok(())); | ||
let st = inner.lock(); | ||
let keys = |m: Vec<&String>| m.into_iter().cloned().collect::<Vec<_>>(); | ||
assert_eq!(keys(st.kept.keys().collect()), [bobs]); | ||
assert_eq!(keys(st.left.keys().collect()), ["0000000000dd"]); | ||
assert_eq!( | ||
st.waiting | ||
.keys() | ||
.map(|(c, _)| c.as_str()) | ||
.collect::<Vec<_>>(), | ||
[bobs] | ||
); | ||
assert!(st.doomed.is_empty() && st.people.is_empty()); | ||
drop(st); | ||
std::fs::remove_dir_all(&d).unwrap(); | ||
} | ||
} | ||
crates/hud-core/src/canvas/store.rs+68−1
| @@ -14,7 +14,9 @@ | ||
//! person's first canvas and kept aside as `<…>.json.moved`; so is a canvas | ||
//! moved into a space, `<id>.json.moved`. A canvas's tiles from before | ||
//! columns (`x`, `y`, `w`, `h`) are made columns as it is read | ||
//! (`super::migrated`), and written back at start. Each file mode 0600, | ||
//! (`super::migrated`), and written back at start. A person's whole | ||
//! deletion (`forget`) deletes their index, their canvas from before and | ||
//! every file of a canvas they own, put aside or not. Each file mode 0600, | ||
//! written whole. | ||
| ||
use super::{CanvasInfo, Tile, migrated}; | ||
| @@ -97,6 +99,12 @@ pub trait Store: Send + Sync { | ||
fn flush(&self) -> Fut<'_, ()> { | ||
Box::pin(async {}) | ||
} | ||
/// Delete what is kept of a person's past their canvases, once each | ||
/// was deleted or left: their index, their canvas from before there | ||
/// were many, any file of a canvas they own still kept (put aside | ||
/// too), and where spaces are on, every workspace space of theirs | ||
/// left. Every failure, in a line each. | ||
fn forget<'a>(&'a self, did: &'a str) -> Fut<'a, Result<(), Vec<String>>>; | ||
} | ||
| ||
/// Canvases in the server's own files. | ||
| @@ -303,6 +311,49 @@ impl Store for FileStore { | ||
} | ||
}) | ||
} | ||
| ||
fn forget<'a>(&'a self, did: &'a str) -> Fut<'a, Result<(), Vec<String>>> { | ||
Box::pin(async move { | ||
let mut paths = vec![self.index_path(did), self.legacy_path(did)]; | ||
paths.push(paths[1].with_extension("json.moved")); | ||
// A canvas of theirs kept, or put aside, which nothing else | ||
// deletes: one moved into a space, or whose deletion failed. | ||
for entry in std::fs::read_dir(&self.dir).into_iter().flatten().flatten() { | ||
let path = entry.path(); | ||
// A name that is not text is no canvas's: it matches no id. | ||
let name = entry.file_name(); | ||
let name = name.to_string_lossy(); | ||
let stem = name | ||
.strip_suffix(".json.moved") | ||
.or_else(|| name.strip_suffix(".json")); | ||
if !stem.is_some_and(|s| super::checked_id(s).is_ok_and(|id| id == s)) { | ||
continue; | ||
} | ||
let owner = std::fs::read(&path) | ||
.ok() | ||
.and_then(|b| serde_json::from_slice::<Value>(&b).ok()) | ||
.and_then(|v| CanvasInfo::from_json(&v)) | ||
.map(|info| info.owner); | ||
if owner.as_deref() == Some(did) { | ||
paths.push(path); | ||
} | ||
} | ||
let failed: Vec<String> = paths | ||
.iter() | ||
.filter_map(|path| match std::fs::remove_file(path) { | ||
Err(e) if e.kind() != std::io::ErrorKind::NotFound => { | ||
Some(format!("{}: {e}", path.display())) | ||
} | ||
_ => None, | ||
}) | ||
.collect(); | ||
if failed.is_empty() { | ||
Ok(()) | ||
} else { | ||
Err(failed) | ||
} | ||
}) | ||
} | ||
} | ||
| ||
#[cfg(test)] | ||
| @@ -342,6 +393,22 @@ mod tests { | ||
doc.to_string() | ||
} | ||
| ||
#[tokio::test] | ||
async fn forgetting_says_what_it_could_not_delete() { | ||
let d = dir(); | ||
let store = FileStore::new(d.clone()); | ||
// Where a person's index goes, a directory. | ||
let index = store.index_path(ALICE); | ||
std::fs::create_dir_all(index.join("x")).unwrap(); | ||
let why = store.forget(ALICE).await.unwrap_err(); | ||
assert_eq!(why.len(), 1, "{why:?}"); | ||
assert!( | ||
why[0].starts_with(&format!("{}: ", index.display())), | ||
"{why:?}" | ||
); | ||
std::fs::remove_dir_all(&d).unwrap(); | ||
} | ||
| ||
#[tokio::test] | ||
async fn what_cannot_be_read_or_written_is_left_as_it_is() { | ||
let d = dir(); | ||
crates/hud-core/src/canvas/tools.rs+1−0
| @@ -495,6 +495,7 @@ mod tests { | ||
favicons: None, | ||
image_cdn: None, | ||
relay: None, | ||
sign_up_pds: crate::config::SIGN_UP_PDS.into(), | ||
}) | ||
.unwrap() | ||
} | ||
crates/hud-core/src/oauth/tests/spaces.rs+118−1
| @@ -2,7 +2,8 @@ | ||
//! (`describeServer`'s `spacesAlpha`, `com.atproto.space.*` with a | ||
//! `space:` permission, listings page by page), and the canvases kept | ||
//! there (`canvas::space`) against it: where a person's canvases go and | ||
//! why, moving them in, writes, moves put off, failures, and deleting. | ||
//! why, moving them in, writes, moves put off, failures, deleting, and a | ||
//! person's whole deletion (`Canvases::forget`). | ||
| ||
use super::*; | ||
use crate::canvas::space::grants; | ||
| @@ -744,6 +745,122 @@ async fn failures_tried_again_then_back_to_files() { | ||
assert_eq!(f.lock().unwrap().spaces.writes.len(), asked); | ||
} | ||
| ||
#[tokio::test] | ||
async fn a_persons_canvases_and_spaces_forgotten() { | ||
let (h, f, base) = spaced().await; | ||
let (mine, _) = file_canvas(&h, "0000000000aa", "Mine", &[]); | ||
let (shared, _) = file_canvas(&h, "0000000000bb", "Ours", &[OTHER]); | ||
sign_in(&h, &f, &base).await; | ||
let fresh = h.canvases.create(ME, "Fresh", By::Person).await.unwrap(); | ||
assert_eq!(storages(&h).await[&fresh.id]["kind"], "space"); | ||
// A space of theirs no canvas is read from, left from before. | ||
let stray = space_of("0000000000cc"); | ||
f.lock().unwrap().spaces.held.insert( | ||
stray.clone(), | ||
BTreeMap::from([("place.hud.tile/000000000001".to_string(), json!({}))]), | ||
); | ||
let held = h.canvases.holding(ME).await; | ||
assert_eq!( | ||
held.owned, | ||
[ | ||
(mine.id.clone(), "Mine".to_string(), 0), | ||
(shared.id.clone(), "Ours".to_string(), 1), | ||
(fresh.id.clone(), "Fresh".to_string(), 0), | ||
] | ||
); | ||
// Its PDS failing: the canvases go, but their spaces do not, and it | ||
// says so. | ||
f.lock().unwrap().spaces.failing = 100; | ||
let why = h.canvases.forget(ME).await.unwrap_err(); | ||
assert!(why.contains("was not deleted"), "{why}"); | ||
// What is still in their spaces is read back, to be deleted again. | ||
let names: Vec<String> = h | ||
.canvases | ||
.holding(ME) | ||
.await | ||
.owned | ||
.into_iter() | ||
.map(|(_, name, _)| name) | ||
.collect(); | ||
assert_eq!(names, ["Mine", "Fresh"]); | ||
// Asked again: every workspace space of theirs deleted, and every | ||
// file of theirs. | ||
f.lock().unwrap().spaces.failing = 0; | ||
h.canvases.forget(ME).await.unwrap(); | ||
let w = f.lock().unwrap(); | ||
let left: Vec<&String> = w.spaces.held.keys().filter(|k| k.contains(TYPE)).collect(); | ||
assert!(left.is_empty(), "{left:?}"); | ||
assert_eq!(w.spaces.count(&format!("deleteSpace {stray}")), 1); | ||
drop(w); | ||
let dir = h.config.data_dir.join("canvas"); | ||
for file in [ | ||
"0000000000aa.json.moved".to_string(), | ||
"0000000000bb.json".to_string(), | ||
format!("by-did/{}.json", jose::sha256(DID)), | ||
] { | ||
assert!(!dir.join(&file).exists(), "{file}"); | ||
} | ||
} | ||
| ||
#[tokio::test] | ||
async fn a_persons_spaces_forgotten_as_their_pds_answers() { | ||
let (h, f, base) = spaced().await; | ||
sign_in(&h, &f, &base).await; | ||
let forget = async || h.canvases.forget(ME).await; | ||
// A grant that does not delete spaces: a space of theirs emptied of | ||
// its records instead. | ||
let stray = space_of("0000000000cc"); | ||
{ | ||
let mut w = f.lock().unwrap(); | ||
w.spaces.held.insert( | ||
stray.clone(), | ||
BTreeMap::from([("place.hud.tile/000000000001".to_string(), json!({}))]), | ||
); | ||
w.granted = Some(format!( | ||
"atproto transition:generic space:{TYPE}?authority=*&manage=create&manage=update" | ||
)); | ||
} | ||
forget().await.unwrap(); | ||
assert_eq!( | ||
f.lock().unwrap().spaces.held.get(&stray), | ||
Some(&BTreeMap::new()) | ||
); | ||
f.lock().unwrap().granted = None; | ||
// Spaces listed that are not theirs, or not workspaces: left alone. | ||
let others = [ | ||
format!("at://{OTHER}/space/{TYPE}/0000000000dd"), | ||
format!("at://{DID}/space/com.example.other/0000000000ee"), | ||
]; | ||
f.lock().unwrap().spaces.answer = Some(( | ||
"listSpaces".into(), | ||
json!({ "spaces": others.iter().map(|s| json!({ "space": s })).collect::<Vec<_>>() }), | ||
)); | ||
let asked = f.lock().unwrap().spaces.writes.len(); | ||
forget().await.unwrap(); | ||
assert_eq!(f.lock().unwrap().spaces.writes.len(), asked); | ||
f.lock().unwrap().spaces.answer = None; | ||
// Its spaces not listed, or its PDS not reached: said so. | ||
f.lock().unwrap().spaces.refuse = Some("Nope".into()); | ||
let why = forget().await.unwrap_err(); | ||
assert!( | ||
why.starts_with("your workspace spaces were not listed: "), | ||
"{why}" | ||
); | ||
f.lock().unwrap().spaces.refuse = None; | ||
f.lock().unwrap().spaces.describe = Some((500, String::new())); | ||
assert_eq!( | ||
forget().await.unwrap_err(), | ||
"your workspace spaces were not listed: your PDS could not be reached: describeServer answered 500" | ||
); | ||
// A PDS without spaces: none to delete. | ||
{ | ||
let mut w = f.lock().unwrap(); | ||
w.spaces.describe = None; | ||
w.spaces.alpha = false; | ||
} | ||
forget().await.unwrap(); | ||
} | ||
| ||
/// Every sign-in of the account ended. | ||
async fn sign_out(h: &Hud) { | ||
let auth = h.auth().unwrap(); | ||
crates/hud-core/src/oauth/client.rs+102−26
| @@ -13,8 +13,12 @@ | ||
//! `/oauth/callback`: the `state` and `iss` checked, the code exchanged, the | ||
//! token answer checked (DPoP-bound; its `sub` the account named) and its | ||
//! `sub` resolved again, fresh, its PDS's authorization server the one that | ||
//! answered. Every request to the server carries a DPoP proof, and is sent | ||
//! again once with the server's `DPoP-Nonce` when it asks for one. | ||
//! answered. "Create one" pushes its request to the sign-up PDS's | ||
//! authorization server instead (`Config::sign_up_pds`), with | ||
//! `prompt=create` and no login hint: no account is named, so its answer's | ||
//! `sub`, resolved, is the account. Every request to the server carries a | ||
//! DPoP proof, and is sent again once with the server's `DPoP-Nonce` when | ||
//! it asks for one. | ||
//! | ||
//! A call to the PDS as the account carries its access token as `DPoP` and | ||
//! a proof naming it (`ath`). The token is refreshed when it has expired, or | ||
| @@ -103,6 +107,22 @@ struct Snapshot { | ||
nonces: BTreeMap<String, String>, | ||
} | ||
| ||
/// What a request pushed asks for. | ||
enum Push<'a> { | ||
/// A sign-in as the account named: its DID, and the login hint. | ||
SignIn { did: String, login: &'a str }, | ||
/// A new account (`prompt=create`), at the sign-up PDS. | ||
SignUp, | ||
} | ||
| ||
/// A URL's host, as a person reads it. | ||
fn host_of(url: &str) -> String { | ||
Url::parse(url) | ||
.ok() | ||
.and_then(|u| u.host_str().map(str::to_string)) | ||
.unwrap_or_else(|| url.to_string()) | ||
} | ||
| ||
/// A URL's origin. | ||
pub(crate) fn origin_of(url: &str) -> String { | ||
Url::parse(url).map_or_else(|_| url.to_string(), |u| u.origin().ascii_serialization()) | ||
| @@ -392,32 +412,87 @@ impl Hud { | ||
.await | ||
.map_err(|_| format!("{login} does not resolve to an account"))?; | ||
let server = self.authorization_server(&who.pds).await?; | ||
self.push_to( | ||
auth, | ||
request_id, | ||
server, | ||
Push::SignIn { | ||
did: who.did, | ||
login: &login, | ||
}, | ||
) | ||
.await | ||
} | ||
| ||
/// "Create one": the request pushed to the authorization server of the | ||
/// sign-up PDS (`Config::sign_up_pds`) with `prompt=create` and no | ||
/// login hint, the account known only once its answer names it; the | ||
/// URL of that server's sign-up page. Else its page again, saying why, | ||
/// while its request still waits. | ||
pub async fn sign_up(&self, request_id: &str) -> Result<String, SignIn> { | ||
let Ok(auth) = self.auth() else { | ||
return Err(SignIn::Expired); | ||
}; | ||
if auth.pending(request_id).is_none() { | ||
return Err(SignIn::Expired); | ||
} | ||
let pds = &self.config.sign_up_pds; | ||
let why = match self.authorization_server(pds).await { | ||
Ok(server) => match self.push_to(auth, request_id, server, Push::SignUp).await { | ||
Ok(to) => return Ok(to), | ||
Err(why) => why, | ||
}, | ||
Err(why) => { | ||
tracing::warn!(pds, why, "sign-up PDS unusable"); | ||
format!( | ||
"Accounts can't be made at {} now; try again later", | ||
host_of(pds) | ||
) | ||
} | ||
}; | ||
let page = auth.pending(request_id).ok_or(SignIn::Expired)?; | ||
Err(SignIn::Failed(page, why)) | ||
} | ||
| ||
/// A sign-in's request pushed (PAR, PKCE, DPoP) to `server`, the | ||
/// request waiting taken and its flow kept: the URL of the server's | ||
/// authorization page, else why not. | ||
async fn push_to( | ||
&self, | ||
auth: &Auth, | ||
request_id: &str, | ||
server: Server, | ||
how: Push<'_>, | ||
) -> Result<String, String> { | ||
let state = jose::random(16); | ||
let verifier = jose::random(32); | ||
let dpop = Keypair::generate(Curve::P256); | ||
let mut nonce = None; | ||
let challenge = jose::sha256(&verifier); | ||
let redirect_uri = auth.redirect_uri(); | ||
let mut form = vec![ | ||
("response_type", "code"), | ||
("code_challenge", challenge.as_str()), | ||
("code_challenge_method", "S256"), | ||
("state", state.as_str()), | ||
("redirect_uri", redirect_uri.as_str()), | ||
("scope", auth.scope.as_str()), | ||
]; | ||
let (named, did) = match &how { | ||
Push::SignIn { did, login } => { | ||
form.push(("login_hint", *login)); | ||
("Your account's server".to_string(), Some(did.clone())) | ||
} | ||
Push::SignUp => { | ||
form.push(("prompt", "create")); | ||
(host_of(&self.config.sign_up_pds), None) | ||
} | ||
}; | ||
let pushed = self | ||
.as_post( | ||
auth, | ||
&server.issuer, | ||
&server.par, | ||
&dpop, | ||
&mut nonce, | ||
&[ | ||
("response_type", "code"), | ||
("code_challenge", &challenge), | ||
("code_challenge_method", "S256"), | ||
("state", &state), | ||
("redirect_uri", &redirect_uri), | ||
("scope", &auth.scope), | ||
("login_hint", &login), | ||
], | ||
) | ||
.as_post(auth, &server.issuer, &server.par, &dpop, &mut nonce, &form) | ||
.await; | ||
let (status, body) = | ||
pushed.map_err(|why| format!("Your account's server could not be reached: {why}"))?; | ||
pushed.map_err(|why| format!("{named} could not be reached: {why}"))?; | ||
let request_uri = body["request_uri"] | ||
.as_str() | ||
.filter(|_| (200..300).contains(&status)); | ||
| @@ -425,8 +500,8 @@ impl Hud { | ||
let error = safe_name(&body); | ||
tracing::warn!(status, error, issuer = server.issuer, "PAR refused"); | ||
return Err(match error { | ||
Some(e) => format!("Your account's server refused the sign-in: {e}"), | ||
None => format!("Your account's server refused the sign-in ({status})"), | ||
Some(e) => format!("{named} refused the sign-in: {e}"), | ||
None => format!("{named} refused the sign-in ({status})"), | ||
}); | ||
}; | ||
// Gone meanwhile, it is told as expired, whatever this says. | ||
| @@ -445,7 +520,7 @@ impl Hud { | ||
verifier, | ||
dpop, | ||
server, | ||
did: who.did, | ||
did, | ||
nonce, | ||
created: now(), | ||
}, | ||
| @@ -494,7 +569,7 @@ impl Hud { | ||
let session = match self.exchange(auth, &flow, code).await { | ||
Ok(s) => s, | ||
Err(why) => { | ||
tracing::warn!(did = flow.did, why, "sign-in refused"); | ||
tracing::warn!(did = flow.did.as_deref(), why, "sign-in refused"); | ||
return Ok(back("access_denied", &why)); | ||
} | ||
}; | ||
| @@ -537,11 +612,12 @@ impl Hud { | ||
}); | ||
} | ||
let t = tokens_of(&body).map_err(|why| format!("Your account's server's answer: {why}"))?; | ||
if t.sub != flow.did { | ||
if flow.did.as_ref().is_some_and(|did| t.sub != *did) { | ||
return Err("You signed in as another account than the one you named".into()); | ||
} | ||
// The account resolved again, fresh: its PDS's authorization server | ||
// must be the one that answered. | ||
// The account resolved again, fresh (or for the first time, one | ||
// just made): its PDS's authorization server must be the one that | ||
// answered. | ||
self.fresh_did_doc(&t.sub).await?; | ||
let who = self.resolve_actor(&t.sub).await?; | ||
let server = self.authorization_server(&who.pds).await?; | ||
crates/hud-core/src/oauth/issuer.rs+114−18
crates/hud-core/src/oauth/mod.rs+32−7
crates/hud-core/src/oauth/tests.rs+215−12
crates/hud-core/src/account.rsnew+83−0
crates/hud-core/src/config.rs+6−0
crates/hud-core/src/identity.rs+174−0
crates/hud-core/src/join.rs+1−0
crates/hud-core/src/lib.rs+4−1
crates/hud-core/src/theme.rs+121−3
crates/hud-core/src/tools.rs+1−0
crates/hud-core/src/writes.rs+1−0
crates/hud-server/atmo/anisota.jpgnew+0−0
A binary file, not shown.
crates/hud-server/atmo/beacon-bits.jpgnew+0−0
A binary file, not shown.
crates/hud-server/atmo/blacksky.jpgnew+0−0
A binary file, not shown.
crates/hud-server/atmo/blento.jpgnew+0−0
A binary file, not shown.
crates/hud-server/atmo/bluesky.jpgnew+0−0
A binary file, not shown.
crates/hud-server/atmo/eurosky.jpgnew+0−0
A binary file, not shown.
crates/hud-server/atmo/flashes.jpgnew+0−0
A binary file, not shown.
crates/hud-server/atmo/gander.jpgnew+0−0
A binary file, not shown.
crates/hud-server/atmo/germ.jpgnew+0−0
A binary file, not shown.
crates/hud-server/atmo/leaflet.jpgnew+0−0
A binary file, not shown.
crates/hud-server/atmo/northsky.jpgnew+0−0
A binary file, not shown.
crates/hud-server/atmo/offprint.jpgnew+0−0
A binary file, not shown.
crates/hud-server/atmo/pckt.jpgnew+0−0
A binary file, not shown.
crates/hud-server/atmo/plyr.jpgnew+0−0
A binary file, not shown.
crates/hud-server/atmo/popfeed.jpgnew+0−0
A binary file, not shown.
crates/hud-server/atmo/semble.jpgnew+0−0
A binary file, not shown.
crates/hud-server/atmo/skylight.jpgnew+0−0
A binary file, not shown.
crates/hud-server/atmo/spark.pngnew+0−0
A binary file, not shown.
crates/hud-server/atmo/stream-place.jpgnew+0−0
A binary file, not shown.
crates/hud-server/atmo/tangled.jpgnew+0−0
A binary file, not shown.
crates/hud-server/hero/workspace-dark.webpnew+0−0
A binary file, not shown.
crates/hud-server/hero/workspace-light.webpnew+0−0
A binary file, not shown.
crates/hud-server/hero/workspace-themes.webpnew+0−0
A binary file, not shown.
crates/hud-server/src/policies/guidelines.htmlnew+50−0
crates/hud-server/src/policies/privacy.htmlnew+120−0
crates/hud-server/src/policies/terms.htmlnew+98−0
crates/hud-server/src/xrpc/tests.rs+317−4
crates/hud-server/src/blob.rs+1−0
crates/hud-server/src/lib.rs+8−4
crates/hud-server/src/mcp.rs+1−0
crates/hud-server/src/oauth.rs+224−60
crates/hud-server/src/policies.rsnew+137−0
crates/hud-server/src/workspace.rs+817−111
928 lines changed: not loaded until asked for.
crates/hud-server/src/xrpc.rs+76−5
docs/running.md+5−2
docs/sign-in.md+13−3
docs/workspace-api.md+6−3
docs/workspace.md+25−2
harness/e2e/accounts.spec.mjsnew+115−0
harness/e2e/pages.mjs+8−6
harness/e2e/world.mjs+2−0
harness/look/hero.mjsnew+63−0
harness/look/record.mjs+51−7
harness/look/states.mjs+71−25
harness/look/tools.json+3750−0
A large diff, not shown.