chadtmiller.com/group-host
atmosphere group host
0
0
A group publishes a website, served sandboxed at its handle
crates/atproto/src/drisl.rs+8−0
| @@ -258,6 +258,14 @@ impl Value { | ||
} | ||
} | ||
| ||
/// The bytes this is, if it is bytes. | ||
pub fn into_bytes(self) -> Option<Vec<u8>> { | ||
match self { | ||
Value::Bytes(bytes) => Some(bytes), | ||
_ => None, | ||
} | ||
} | ||
| ||
/// The value a record's JSON holds, as atproto writes it: an object | ||
/// of `$link` alone a link, of `$bytes` alone bytes, a number with a | ||
/// fraction refused. | ||
crates/atproto/tests/drisl.rs+2−0
| @@ -129,6 +129,8 @@ fn says_whether_a_value_is_a_map() { | ||
Some(Default::default()) | ||
); | ||
assert_eq!(Value::Null.into_map(), None); | ||
assert_eq!(Value::Bytes(vec![1]).into_bytes(), Some(vec![1])); | ||
assert_eq!(Value::Null.into_bytes(), None); | ||
} | ||
| ||
#[test] | ||
crates/group-host/src/lexicons.rs+16−5
| @@ -5,15 +5,17 @@ | ||
//! of one of our own collections an app writes as a group before it is | ||
//! kept ([`check_record`]). | ||
| ||
use crate::Host; | ||
use crate::api::invalid; | ||
use crate::xrpc::XrpcError; | ||
use atproto::lexicon::Lexicons; | ||
use axum::body::Body; | ||
use axum::extract::{Query, Request}; | ||
use axum::extract::{Query, Request, State}; | ||
use axum::http::{Method, StatusCode}; | ||
use axum::middleware::Next; | ||
use axum::response::{IntoResponse, Response}; | ||
use serde_json::Value; | ||
use std::sync::Arc; | ||
use std::sync::OnceLock; | ||
| ||
macro_rules! lexicon { | ||
| @@ -51,6 +53,7 @@ pub const FILES: &[&str] = &[ | ||
lexicon!("fyi/opensocial/declineInvite"), | ||
lexicon!("fyi/opensocial/defs"), | ||
lexicon!("fyi/opensocial/deleteGroup"), | ||
lexicon!("fyi/opensocial/deleteSite"), | ||
lexicon!("fyi/opensocial/deleteSpace"), | ||
lexicon!("fyi/opensocial/denyJoinRequest"), | ||
lexicon!("fyi/opensocial/finishAccountMove"), | ||
| @@ -97,6 +100,7 @@ pub const FILES: &[&str] = &[ | ||
lexicon!("fyi/opensocial/permissions"), | ||
lexicon!("fyi/opensocial/profile"), | ||
lexicon!("fyi/opensocial/provisionGroup"), | ||
lexicon!("fyi/opensocial/putSite"), | ||
lexicon!("fyi/opensocial/removeRecoveryKey"), | ||
lexicon!("fyi/opensocial/requestJoin"), | ||
lexicon!("fyi/opensocial/resolveSubject"), | ||
| @@ -105,6 +109,7 @@ pub const FILES: &[&str] = &[ | ||
lexicon!("fyi/opensocial/revokeGroupToken"), | ||
lexicon!("fyi/opensocial/role"), | ||
lexicon!("fyi/opensocial/rule"), | ||
lexicon!("fyi/opensocial/site"), | ||
lexicon!("fyi/opensocial/space"), | ||
lexicon!("fyi/opensocial/startAccountMove"), | ||
lexicon!("fyi/opensocial/updateGroupHandle"), | ||
| @@ -141,8 +146,10 @@ fn refuse(err: XrpcError) -> Response { | ||
| ||
/// Refuses a call to a `fyi.opensocial.*` method whose parameters or JSON | ||
/// input are not what its lexicon describes, as `InvalidRequest` saying | ||
/// where and what; any other request passes as it came. | ||
pub async fn check(request: Request, next: Next) -> Response { | ||
/// where and what, or whose input is larger than it takes, as | ||
/// `PayloadTooLarge`: [`INPUT_AT_MOST`], but for `putSite`, which carries | ||
/// a whole site, `BLOB_UPLOAD_LIMIT`. Any other request passes as it came. | ||
pub async fn check(State(host): State<Arc<Host>>, request: Request, next: Next) -> Response { | ||
let path = request.uri().path(); | ||
let ours = path | ||
.strip_prefix("/xrpc/") | ||
| @@ -169,8 +176,12 @@ pub async fn check(request: Request, next: Next) -> Response { | ||
return next.run(request).await; | ||
} | ||
let (parts, body) = request.into_parts(); | ||
let Ok(bytes) = axum::body::to_bytes(body, INPUT_AT_MOST).await else { | ||
let said = format!("an input of {INPUT_AT_MOST} bytes at most, read whole"); | ||
let most = match nsid.as_str() { | ||
"fyi.opensocial.putSite" => host.config.blob_upload_limit as usize, | ||
_ => INPUT_AT_MOST, | ||
}; | ||
let Ok(bytes) = axum::body::to_bytes(body, most).await else { | ||
let said = format!("an input of {most} bytes at most, read whole"); | ||
return refuse(XrpcError::new( | ||
StatusCode::PAYLOAD_TOO_LARGE, | ||
"PayloadTooLarge", | ||
crates/group-host/src/lib.rs+17−1
| @@ -49,6 +49,7 @@ pub mod recovery; | ||
pub mod repo; | ||
pub mod scopes; | ||
pub mod secrets; | ||
pub mod sites; | ||
pub mod space; | ||
pub mod space_api; | ||
pub mod store; | ||
| @@ -129,6 +130,9 @@ pub fn client() -> reqwest::Client { | ||
| ||
/// The host's routes. | ||
pub fn router(host: Arc<Host>) -> Router { | ||
// A site is published whole, its files in one body: as large as one | ||
// upload may be, as the lexicons' check reads it. | ||
let site_limit = usize::try_from(host.config.blob_upload_limit).unwrap_or(usize::MAX); | ||
Router::new() | ||
.route("/xrpc/_health", get(health)) | ||
.route( | ||
| @@ -431,10 +435,22 @@ pub fn router(host: Arc<Host>) -> Router { | ||
.route("/console/logout", post(console_login::logout)) | ||
.merge(token_routes()) | ||
.merge(oauth_routes()) | ||
.route( | ||
"/xrpc/fyi.opensocial.putSite", | ||
post(sites::put_site).layer(axum::extract::DefaultBodyLimit::max(site_limit)), | ||
) | ||
.route("/xrpc/fyi.opensocial.deleteSite", post(sites::delete_site)) | ||
.route("/.well-known/did.json", get(api::did_json)) | ||
.route("/.well-known/atproto-did", get(api::atproto_did)) | ||
.route("/xrpc/{nsid}", get(not_implemented).post(not_implemented)) | ||
.layer(axum::middleware::from_fn(lexicons::check)) | ||
.layer(axum::middleware::from_fn_with_state( | ||
host.clone(), | ||
lexicons::check, | ||
)) | ||
.layer(axum::middleware::from_fn_with_state( | ||
host.clone(), | ||
sites::serve, | ||
)) | ||
.with_state(host) | ||
} | ||
| ||
crates/group-host/src/sites.rsnew+498−0
498 lines changed: not loaded until asked for.
crates/group-host/src/token_writes.rs+2−0
| @@ -257,6 +257,7 @@ impl Host { | ||
// A role may publish what it may write as the group in a space, as | ||
// it may write it there. | ||
let publishable = self.publishable(&acting.grant.group, &roles)?; | ||
let configures = actions_for(&grants, &roles).contains("group.configure"); | ||
for w in writes { | ||
let (collection, _) = w.path(); | ||
if !acting.permissions.repo(collection, action(w)) { | ||
| @@ -267,6 +268,7 @@ impl Host { | ||
return Err(no_longer(collection)); | ||
} | ||
self.declaration(&acting.grant.group, w)?; | ||
self.site_write(configures, w)?; | ||
} | ||
checked(writes) | ||
} | ||
crates/group-host/tests/sites.rsnew+436−0
436 lines changed: not loaded until asked for.
crates/group-host-mcp/src/lib.rs+17−0
| @@ -52,6 +52,8 @@ const LEXICONS: &[(&str, &str)] = &[ | ||
lexicon!("applyLabel"), | ||
lexicon!("negateLabel"), | ||
lexicon!("resolveSubject"), | ||
lexicon!("putSite"), | ||
lexicon!("deleteSite"), | ||
lexicon!("profile"), | ||
lexicon!("rule"), | ||
lexicon!("role"), | ||
| @@ -358,6 +360,21 @@ const TOOLS: &[(&str, &[&str], &str, Made)] = &[ | ||
them away, or with none given drops its grant.", | ||
Made::Grant, | ||
), | ||
( | ||
"site_publish", | ||
&[], | ||
"Publishes the group's website, whole, at its handle (`https://<handle>/`): every file \ | ||
of it, each as text or as bytes, in place of the site there; a file the group holds \ | ||
already is used again. Its pages run sandboxed, each in an origin of its own, with no \ | ||
cookies or storage; a page reads live data from the host's public methods.", | ||
Made::Method("putSite", None), | ||
), | ||
( | ||
"site_delete", | ||
&[], | ||
"Takes the group's website down.", | ||
Made::Method("deleteSite", None), | ||
), | ||
( | ||
"member_list", | ||
&[], | ||
crates/group-host-mcp/tests/protocol.rs+2−0
| @@ -37,6 +37,8 @@ fn names_each_tool_for_its_command() { | ||
"role_set", | ||
"role_delete", | ||
"role_grant", | ||
"site_publish", | ||
"site_delete", | ||
"member_list", | ||
"member_assign", | ||
"member_eject", | ||
crates/opensocial/src/lib.rs+50−0
| @@ -49,6 +49,11 @@ role | ||
delete a role nobody holds or is granted | ||
role grant <group> <role> [--scopes <scope,…>] [--assignable <role,…>] [--undo] | ||
add to what a role may do, or with --undo take it away | ||
site | ||
site publish <group> <dir> [--fallback <path>] [--not-found <path>] | ||
publish the files under <dir> as the group's website, at its | ||
handle, in place of the one there | ||
site delete <group> take the group's website down | ||
member | ||
member list <group> [--q <text>] [--limit <n>] [--cursor <cursor>] | ||
who is in the group, and their roles, a page at a time | ||
| @@ -586,6 +591,20 @@ pub async fn run(args: &[String], env: &Env) -> Result<String> { | ||
let [account] = a.take()?; | ||
import(&signed_in(env).await?, &host, env, account, &a).await | ||
} | ||
["site", "publish", rest @ ..] => { | ||
let a = parse(rest, &["fallback", "not-found"])?; | ||
let [group, dir] = a.take()?; | ||
let mut given = json!({"files": site_files(std::path::Path::new(dir))?}); | ||
for (flag, name) in [("fallback", "fallback"), ("not-found", "not_found")] { | ||
if let Some(path) = a.flags.get(flag) { | ||
given[name] = json!(path); | ||
} | ||
} | ||
let tools = group_host_mcp::tools(); | ||
let tool = tools.iter().find(|t| t.name == "site_publish"); | ||
let tool = tool.expect("site_publish is a tool"); | ||
command(&signed_in(env).await?, &host, tool, group, given).await | ||
} | ||
[group, action, rest @ ..] => { | ||
let name = format!("{group}_{action}").replace('-', "_"); | ||
let tools = group_host_mcp::tools(); | ||
| @@ -599,6 +618,37 @@ pub async fn run(args: &[String], env: &Env) -> Result<String> { | ||
} | ||
} | ||
| ||
/// The files under `dir`, for `putSite`: each at its path under it, as | ||
/// text if it is UTF-8, else as bytes. Those whose names start with a dot | ||
/// are left out, as the files of tools are. | ||
pub fn site_files(dir: &std::path::Path) -> Result<Vec<Value>> { | ||
let mut out = Vec::new(); | ||
let mut waiting = vec![(dir.to_path_buf(), String::new())]; | ||
while let Some((at, under)) = waiting.pop() { | ||
let entries = | ||
std::fs::read_dir(&at).with_context(|| format!("reading {}", at.display()))?; | ||
for entry in entries { | ||
let entry = entry?; | ||
let name = entry.file_name().to_string_lossy().into_owned(); | ||
if name.starts_with('.') { | ||
continue; | ||
} | ||
let path = format!("{under}{name}"); | ||
if std::fs::metadata(entry.path())?.is_dir() { | ||
waiting.push((entry.path(), format!("{path}/"))); | ||
continue; | ||
} | ||
let bytes = std::fs::read(entry.path())?; | ||
out.push(match String::from_utf8(bytes) { | ||
Ok(text) => json!({"path": path, "text": text}), | ||
Err(e) => json!({"path": path, "bytes": atproto::drisl::Value::Bytes(e.into_bytes()).to_json()}), | ||
}); | ||
} | ||
} | ||
out.sort_by(|a, b| a["path"].as_str().cmp(&b["path"].as_str())); | ||
Ok(out) | ||
} | ||
| ||
/// A tool's command, as `me`, in `group`: what it answers, as JSON; or | ||
/// for `group show`, as lines. | ||
async fn command( | ||
crates/opensocial/tests/commands.rs+62−0
| @@ -794,3 +794,65 @@ fn reads_its_environment() { | ||
assert!(env.handle.is_none() && env.seed_invite.is_empty()); | ||
assert_eq!(did_web("https://groups.example/"), "did:web:groups.example"); | ||
} | ||
| ||
#[tokio::test] | ||
async fn publishes_a_folder_as_the_groups_site_and_takes_it_down() { | ||
let h = host().await; | ||
let alice = env(&h, 0); | ||
let group = "riders.groups.test"; | ||
ok(&alice, &["group", "create", group]).await; | ||
let did = h.host.store.account(group).unwrap().unwrap().did; | ||
let dir = tempfile::tempdir().unwrap(); | ||
std::fs::create_dir(dir.path().join("rides")).unwrap(); | ||
std::fs::create_dir(dir.path().join(".git")).unwrap(); | ||
std::fs::write(dir.path().join("index.html"), "<h1>Riders</h1>").unwrap(); | ||
std::fs::write(dir.path().join("rides/index.html"), "<h1>Rides</h1>").unwrap(); | ||
std::fs::write(dir.path().join("logo.png"), [0x89, b'P', b'N', b'G', 0xff]).unwrap(); | ||
std::fs::write(dir.path().join(".env"), "SECRET=1").unwrap(); | ||
std::fs::write(dir.path().join(".git/HEAD"), "ref").unwrap(); | ||
let folder = dir.path().to_str().unwrap(); | ||
| ||
let args = [ | ||
"site", | ||
"publish", | ||
group, | ||
folder, | ||
"--not-found", | ||
"index.html", | ||
"--fallback", | ||
"rides/index.html", | ||
]; | ||
let made = said(&ok(&alice, &args).await); | ||
assert_eq!(made["uploaded"], 3, "{made}"); | ||
assert_eq!(made["url"], format!("http://{group}/")); | ||
let record = h | ||
.host | ||
.store | ||
.record(&did, "fyi.opensocial.site", "self") | ||
.unwrap() | ||
.unwrap(); | ||
let site = atproto::drisl::decode(&record.value).unwrap().to_json(); | ||
let paths: Vec<&str> = site["files"] | ||
.as_array() | ||
.unwrap() | ||
.iter() | ||
.map(|f| f["path"].as_str().unwrap()) | ||
.collect(); | ||
assert_eq!(paths, ["index.html", "logo.png", "rides/index.html"]); | ||
assert_eq!( | ||
(site["notFound"].as_str(), site["fallback"].as_str()), | ||
(Some("index.html"), Some("rides/index.html")) | ||
); | ||
| ||
let missing = fails(&alice, &["site", "publish", group, "/no/such/folder"]).await; | ||
assert!(missing.contains("reading /no/such/folder"), "{missing}"); | ||
| ||
ok(&alice, &["site", "delete", group]).await; | ||
assert!( | ||
h.host | ||
.store | ||
.record(&did, "fyi.opensocial.site", "self") | ||
.unwrap() | ||
.is_none() | ||
); | ||
} | ||
docs/design/README.md+3−0
| @@ -31,6 +31,7 @@ accounts on their own PDSes, anywhere on the network. | ||
| --- | --- | | ||
| The group's identity | its DID document, in the PLC directory, changed with the host's rotation key and any recovery keys ([recovery](recovery.md)) | | ||
| Its public records and files | its repo here | | ||
| Its website | a record in its repo here, served at its handle ([sites](sites.md)) | | ||
| Its profile, rules and labeler | its `meta` space, in the group's repo there | | ||
| Its roles, permissions, memberships and spaces | its `members` space, in the group's repo there | | ||
| What members write in its spaces | each member's own repo in the space, on their own PDS | | ||
| @@ -58,6 +59,8 @@ accounts on their own PDSes, anywhere on the network. | ||
- [Signing in](signing-in.md): people, apps and MCP clients, and what a | ||
token may do. | ||
- [Moderation](moderation.md): labels, the queue, and reports. | ||
- [Sites](sites.md): a group's website, published whole and served | ||
sandboxed at its handle. | ||
- [MCP](mcp.md): connecting an AI app to a group, and its tools. | ||
- [Recovery](recovery.md): keys that let a group's stewards hold its | ||
identity. | ||