chadtmiller.com/group-host
atmosphere group host
0
0
A group's site shows the group to whoever signs in on it
crates/group-host/src/config.rs+14−0
| @@ -64,6 +64,15 @@ pub struct Config { | ||
/// How many of the lines it logs at info and below it keeps to read | ||
/// back, `LOGS_KEEP`; any line is kept 30 days at most. | ||
pub logs_keep: u64, | ||
/// Where the built page that holds a site visitor's session is, | ||
/// `SITE_SHELL_DIR`: its `shell.js`, served at `/_os/shell.js` on a | ||
/// group's address. A site that asks for live data has none to run | ||
/// without it. | ||
pub site_shell: Option<std::path::PathBuf>, | ||
/// Where that page looks up a handle typed to sign in, | ||
/// `SITE_HANDLE_RESOLVER`: a service answering | ||
/// `com.atproto.identity.resolveHandle`. Bluesky's unless set. | ||
pub site_handle_resolver: String, | ||
} | ||
| ||
/// The service that finds anyone on the network by what is typed. | ||
| @@ -157,6 +166,9 @@ impl Config { | ||
.with_context(|| format!("LOGS_KEEP is no number of lines: {n}"))?, | ||
None => crate::logs::KEEP, | ||
}; | ||
let site_shell = var("SITE_SHELL_DIR").map(std::path::PathBuf::from); | ||
let site_handle_resolver = | ||
var("SITE_HANDLE_RESOLVER").unwrap_or_else(|| "https://bsky.social".into()); | ||
Ok(Config { | ||
port, | ||
public_url, | ||
| @@ -176,6 +188,8 @@ impl Config { | ||
signup_pds, | ||
host_admins, | ||
logs_keep, | ||
site_shell, | ||
site_handle_resolver, | ||
}) | ||
} | ||
| ||
crates/group-host/src/lib.rs+1−0
| @@ -53,6 +53,7 @@ pub mod recovery; | ||
pub mod repo; | ||
pub mod scopes; | ||
pub mod secrets; | ||
pub mod site_head; | ||
pub mod sites; | ||
pub mod space; | ||
pub mod space_api; | ||
crates/group-host/src/site_head.rsnew+141−0
| @@ -0,0 +1,141 @@ | ||
//! What a link to a page of a group's site previews as, when the host | ||
//! serves the page around it (a site that asks for live data): the page's | ||
//! own `<title>`, and the `<meta>` tags apps read for a preview, written | ||
//! again into the host's page. A crawler reads that page and runs nothing, | ||
//! so without them every link would preview as the bare address. | ||
//! | ||
//! Only what a preview needs is taken, and each is written afresh, its | ||
//! text escaped: nothing of a site's markup reaches the host's page as | ||
//! markup. | ||
| ||
/// How much of a page is read for its head. | ||
const HEAD_AT_MOST: usize = 64 * 1024; | ||
/// How many `<meta>` tags are taken. | ||
const METAS_AT_MOST: usize = 32; | ||
| ||
/// The title and preview tags of the page `html`, as tags for the host's | ||
/// page: its `<title>`, or `fallback` if it has none. | ||
pub fn preview(html: &str, fallback: &str) -> String { | ||
let head = head(html); | ||
let lower = head.to_ascii_lowercase(); | ||
let title = title(head, &lower).unwrap_or(fallback); | ||
let mut out = format!("<title>{}</title>", escape(title)); | ||
for (key, name, content) in metas(head, &lower).take(METAS_AT_MOST) { | ||
out.push_str(&format!( | ||
"<meta {key}=\"{}\" content=\"{}\">", | ||
escape(name), | ||
escape(content) | ||
)); | ||
} | ||
out | ||
} | ||
| ||
/// The page up to its body, at most [`HEAD_AT_MOST`] bytes of it. | ||
fn head(html: &str) -> &str { | ||
let mut end = html.len().min(HEAD_AT_MOST); | ||
while !html.is_char_boundary(end) { | ||
end -= 1; | ||
} | ||
let html = &html[..end]; | ||
let lower = html.to_ascii_lowercase(); | ||
let body = ["</head", "<body"] | ||
.iter() | ||
.filter_map(|t| lower.find(t)) | ||
.min(); | ||
&html[..body.unwrap_or(html.len())] | ||
} | ||
| ||
/// The text of the page's `<title>`, trimmed, if it has any. | ||
fn title<'a>(head: &'a str, lower: &str) -> Option<&'a str> { | ||
let open = lower.find("<title")?; | ||
let start = open + lower[open..].find('>')? + 1; | ||
let end = start + lower[start..].find("</title")?; | ||
Some(head[start..end].trim()).filter(|t| !t.is_empty()) | ||
} | ||
| ||
/// Each `<meta>` a preview is read from, as `name` or `property`, what it | ||
/// names, and its content. | ||
fn metas<'a>( | ||
head: &'a str, | ||
lower: &'a str, | ||
) -> impl Iterator<Item = (&'static str, &'a str, &'a str)> { | ||
let starts = lower | ||
.match_indices("<meta") | ||
.map(|(at, _)| at + "<meta".len()); | ||
starts | ||
.filter(|&at| lower[at..].starts_with(|c: char| c.is_ascii_whitespace() || c == '/')) | ||
.filter_map(|at| { | ||
let attrs = attributes(&head[at..]); | ||
let found = |key: &str| { | ||
attrs | ||
.iter() | ||
.find(|(k, _)| k.eq_ignore_ascii_case(key)) | ||
.map(|&(_, v)| v) | ||
}; | ||
let content = found("content")?; | ||
match (found("name"), found("property")) { | ||
(Some(name), _) if previews_name(name) => Some(("name", name, content)), | ||
(_, Some(property)) if previews_property(property) => { | ||
Some(("property", property, content)) | ||
} | ||
_ => None, | ||
} | ||
}) | ||
} | ||
| ||
/// A `<meta name>` a preview is read from. | ||
fn previews_name(name: &str) -> bool { | ||
let name = name.to_ascii_lowercase(); | ||
["description", "theme-color"].contains(&name.as_str()) || name.starts_with("twitter:") | ||
} | ||
| ||
/// A `<meta property>` a preview is read from: Open Graph's. | ||
fn previews_property(property: &str) -> bool { | ||
property.to_ascii_lowercase().starts_with("og:") | ||
} | ||
| ||
/// The attributes of the tag `tag` begins, up to the `>` that ends it, as | ||
/// HTML reads them: a name, and a value quoted either way, or unquoted, or | ||
/// none. | ||
fn attributes(tag: &str) -> Vec<(&str, &str)> { | ||
let mut found = Vec::new(); | ||
let mut rest = tag; | ||
loop { | ||
rest = rest.trim_start_matches(|c: char| c.is_ascii_whitespace() || c == '/'); | ||
if rest.is_empty() || rest.starts_with('>') { | ||
return found; | ||
} | ||
let name_end = rest | ||
.find(|c: char| c.is_ascii_whitespace() || "=>/".contains(c)) | ||
.unwrap_or(rest.len()); | ||
let name = &rest[..name_end]; | ||
rest = rest[name_end..].trim_start(); | ||
let Some(after) = rest.strip_prefix('=') else { | ||
found.push((name, "")); | ||
continue; | ||
}; | ||
let after = after.trim_start(); | ||
let (value, left) = match after.chars().next() { | ||
Some(q @ ('"' | '\'')) => match after[1..].find(q) { | ||
Some(end) => (&after[1..1 + end], &after[2 + end..]), | ||
None => return found, | ||
}, | ||
_ => { | ||
let end = after | ||
.find(|c: char| c.is_ascii_whitespace() || c == '>') | ||
.unwrap_or(after.len()); | ||
(&after[..end], &after[end..]) | ||
} | ||
}; | ||
found.push((name, value)); | ||
rest = left; | ||
} | ||
} | ||
| ||
/// `text` as it may stand in an attribute's double quotes or a title: an | ||
/// entity the page wrote stays as written, but nothing can end either. | ||
fn escape(text: &str) -> String { | ||
text.replace('"', """) | ||
.replace('<', "<") | ||
.replace('>', ">") | ||
} | ||
crates/group-host/src/site_kit.jsnew+94−0
| @@ -0,0 +1,94 @@ | ||
// `os`: what a page of a group's site asks the page the host serves | ||
// around it, which holds the visitor's session. Each ask is a message to | ||
// it, answered by one naming the same id; a read nobody may make now is | ||
// refused with `locked` and a reason, "sign in" or "not for you". | ||
// | ||
// <os-sign-in> is a button for signing in and out, in the page's own | ||
// markup, so the page's own CSS styles it: "Sign in" while nobody is, | ||
// then the visitor's handle and "Sign out". | ||
(() => { | ||
let seq = 0; | ||
const pending = new Map(); | ||
const watching = new Set(); | ||
addEventListener('message', (e) => { | ||
const m = e.data; | ||
if (e.source !== parent || !m || m.os !== 1) return; | ||
if (m.type === 'changed') return watching.forEach((fn) => fn(m.me)); | ||
if (m.type !== 'reply') return; | ||
const waiting = pending.get(m.id); | ||
if (!waiting) return; | ||
pending.delete(m.id); | ||
if (!('error' in m)) return waiting.resolve(m.value); | ||
const error = new Error(m.error); | ||
error.locked = !!m.locked; | ||
error.reason = m.reason; | ||
waiting.reject(error); | ||
}); | ||
const ask = (type, body = {}) => | ||
new Promise((resolve, reject) => { | ||
const id = ++seq; | ||
pending.set(id, { resolve, reject }); | ||
parent.postMessage({ os: 1, type, id, ...body }, '*'); | ||
}); | ||
const tell = (type, body = {}) => parent.postMessage({ os: 1, type, ...body }, '*'); | ||
const os = { | ||
/** The group whose site this is: `{did, handle}`. */ | ||
group: () => ask('group'), | ||
/** Who is looking: `{signedIn, did, handle}`. */ | ||
me: () => ask('me'), | ||
/** One of the host's methods the site reads, as whoever is looking. */ | ||
call: (method, params = {}) => ask('call', { method, params }), | ||
/** | ||
* Opens the host's sign-in dialog, its handle filled in with `hint` if | ||
* given, for the visitor to confirm. Signed in, the page loads again. | ||
*/ | ||
signIn: ({ hint } = {}) => tell('signIn', hint ? { hint: String(hint) } : {}), | ||
/** Signs the visitor out; `onChange` hears of it. */ | ||
signOut: () => tell('signOut'), | ||
/** Calls `fn` with who is looking, whenever that changes in place. */ | ||
onChange: (fn) => { | ||
watching.add(fn); | ||
return () => watching.delete(fn); | ||
} | ||
}; | ||
window.os = os; | ||
| ||
// Where this page is and what it is called, for the page around it to | ||
// show in the address bar and the tab: as it loads, and as a page that | ||
// routes in the browser moves. | ||
const at = () => | ||
tell('at', { path: location.pathname + location.search + location.hash, title: document.title }); | ||
for (const name of ['pushState', 'replaceState']) { | ||
const was = history[name].bind(history); | ||
history[name] = (...args) => (was(...args), at()); | ||
} | ||
addEventListener('popstate', at); | ||
addEventListener('hashchange', at); | ||
at(); | ||
| ||
class SignIn extends HTMLElement { | ||
connectedCallback() { | ||
this.stop = os.onChange((me) => this.draw(me)); | ||
os.me().then((me) => this.draw(me)); | ||
} | ||
disconnectedCallback() { | ||
this.stop?.(); | ||
} | ||
draw(me) { | ||
const button = document.createElement('button'); | ||
button.type = 'button'; | ||
if (!me.signedIn) { | ||
button.textContent = 'Sign in'; | ||
button.onclick = () => os.signIn({ hint: this.getAttribute('hint') ?? undefined }); | ||
return this.replaceChildren(button); | ||
} | ||
const who = document.createElement('span'); | ||
who.className = 'handle'; | ||
who.textContent = `@${me.handle ?? me.did}`; | ||
button.textContent = 'Sign out'; | ||
button.onclick = () => os.signOut(); | ||
this.replaceChildren(who, ' ', button); | ||
} | ||
} | ||
customElements.define('os-sign-in', SignIn); | ||
})(); | ||
crates/group-host/src/sites.rs+219−13
| @@ -22,12 +22,13 @@ use crate::api::invalid; | ||
use crate::group_api::{group_of, signed_in}; | ||
use crate::rbac::NS; | ||
use crate::repo::{Asked, Write, record_cid}; | ||
use crate::site_head; | ||
use crate::time::{iso, now_millis}; | ||
use crate::xrpc::XrpcError; | ||
use atproto::drisl; | ||
use axum::Json; | ||
use axum::extract::{Request, State}; | ||
use axum::http::{HeaderMap, HeaderValue, Method, StatusCode, header}; | ||
use axum::http::{HeaderMap, HeaderName, HeaderValue, Method, StatusCode, header}; | ||
use axum::middleware::Next; | ||
use axum::response::{IntoResponse, Response}; | ||
use serde_json::{Value, json}; | ||
| @@ -70,7 +71,7 @@ fn blob_of(file: &Value) -> Option<atproto::Cid> { | ||
} | ||
| ||
/// Refuses a site the host would not serve: one whose paths [`paths`] | ||
/// refuses, or a file naming no blob. | ||
/// refuses, a file naming no blob, or a read that is none of [`READS`]. | ||
pub fn check(site: &Value) -> Result<(), XrpcError> { | ||
paths(site)?; | ||
for file in site["files"].as_array().into_iter().flatten() { | ||
| @@ -79,7 +80,34 @@ pub fn check(site: &Value) -> Result<(), XrpcError> { | ||
return Err(refused(format!("{path} names no blob"))); | ||
} | ||
} | ||
Ok(()) | ||
reads(site) | ||
} | ||
| ||
/// The host's methods a site's pages may ask, as whoever is looking and | ||
/// signed in, through the page the host serves around them: reads alone. | ||
pub const READS: &[&str] = &[ | ||
"fyi.opensocial.getGroup", | ||
"fyi.opensocial.listMembers", | ||
"fyi.opensocial.listSpaceRecords", | ||
"fyi.opensocial.getSpaceBlob", | ||
"fyi.opensocial.getActor", | ||
"fyi.opensocial.getViewer", | ||
]; | ||
| ||
/// The methods a site's `reads` name. | ||
fn reads_of(site: &Value) -> Vec<&str> { | ||
let all = site["reads"].as_array().into_iter().flatten(); | ||
all.filter_map(|r| r["method"].as_str()).collect() | ||
} | ||
| ||
/// Refuses a site whose `reads` name a method that is none of [`READS`]. | ||
fn reads(site: &Value) -> Result<(), XrpcError> { | ||
match reads_of(site).into_iter().find(|m| !READS.contains(m)) { | ||
Some(method) => Err(refused(format!( | ||
"{method} is none of the methods a site's pages may ask" | ||
))), | ||
None => Ok(()), | ||
} | ||
} | ||
| ||
/// Refuses a site's paths: a file at a path no file may be at, or at one | ||
| @@ -251,8 +279,15 @@ impl Host { | ||
Ok(read.map(|(_, bytes)| (kind.to_string(), bytes, etag))) | ||
} | ||
| ||
/// The answer of `did`'s site, `handle`, to `asking`. | ||
fn site_answer(&self, did: &str, handle: &str, asking: &Asking) -> Result<Response, XrpcError> { | ||
/// The answer of `did`'s site, `handle`, to `asking`, its own folders | ||
/// redirected under `under`. | ||
fn site_answer( | ||
&self, | ||
did: &str, | ||
handle: &str, | ||
asking: &Asking, | ||
under: &str, | ||
) -> Result<Response, XrpcError> { | ||
if self.active(did).is_err() { | ||
return Ok(plain(StatusCode::NOT_FOUND, "no site here")); | ||
} | ||
| @@ -281,7 +316,7 @@ impl Host { | ||
.is_some() | ||
{ | ||
return Ok(moved( | ||
&format!("/{}/", encoded(path)), | ||
&format!("{under}/{}/", encoded(path)), | ||
StatusCode::MOVED_PERMANENTLY, | ||
)); | ||
} | ||
| @@ -301,6 +336,38 @@ impl Host { | ||
} | ||
Ok(plain(StatusCode::NOT_FOUND, "no such page")) | ||
} | ||
| ||
/// `did`'s site as its record has it, while the group is on. | ||
fn live_site(&self, did: &str) -> Option<Value> { | ||
self.active(did).ok()?; | ||
let record = self.store.record(did, SITE, "self").ok().flatten()?; | ||
let site = drisl::decode(&record.value).expect("a record the host wrote"); | ||
Some(site.to_json()) | ||
} | ||
| ||
/// The page of `did`'s `site` the frame shows at `path`, and the status | ||
/// it is served with: the file there or the folder's `index.html`, else | ||
/// its `fallback`, else, not found, its `notFound`. Only HTML is read. | ||
fn page_at(&self, did: &str, site: &Value, path: &str) -> (StatusCode, Option<String>) { | ||
let tried = match path.is_empty() || path.ends_with('/') { | ||
true => vec![format!("{path}index.html")], | ||
false => vec![path.to_string(), format!("{path}/index.html")], | ||
}; | ||
let fallback = site["fallback"].as_str().map(String::from); | ||
let found = |paths: Vec<String>| { | ||
let file = paths | ||
.iter() | ||
.find_map(|p| self.site_file(did, site, p).ok().flatten()); | ||
let html = file.filter(|(kind, ..)| kind.starts_with("text/html")); | ||
html.and_then(|(_, bytes, _)| String::from_utf8(bytes).ok()) | ||
}; | ||
let shown = tried.into_iter().chain(fallback).collect::<Vec<_>>(); | ||
if let Some(html) = found(shown) { | ||
return (StatusCode::OK, Some(html)); | ||
} | ||
let missing = site["notFound"].as_str().map(String::from); | ||
(StatusCode::NOT_FOUND, found(missing.into_iter().collect())) | ||
} | ||
} | ||
| ||
/// A file of a site's, or that the browser holds it already. | ||
| @@ -330,8 +397,11 @@ pub async fn serve(State(host): State<Arc<Host>>, req: Request, next: Next) -> R | ||
.get(header::HOST) | ||
.and_then(|h| h.to_str().ok()); | ||
let group = named.and_then(|n| host.site_of(n)); | ||
let (Some((did, handle)), false) = (group, req.uri().path().starts_with("/.well-known/")) | ||
else { | ||
// The host's own paths there: its `/.well-known/`, and its methods, | ||
// which the page around a site asks (a handle being typed, say). | ||
let path = req.uri().path(); | ||
let ours = path.starts_with("/.well-known/") || path.starts_with("/xrpc/"); | ||
let (Some((did, handle)), false) = (group, ours) else { | ||
return next.run(req).await; | ||
}; | ||
if ![Method::GET, Method::HEAD].contains(req.method()) { | ||
| @@ -356,8 +426,143 @@ pub async fn serve(State(host): State<Arc<Host>>, req: Request, next: Next) -> R | ||
held: text(header::IF_NONE_MATCH).map(String::from), | ||
path, | ||
}; | ||
let answer = host.site_answer(&did, &handle, &asking); | ||
sandboxed(answer.unwrap_or_else(IntoResponse::into_response)) | ||
// The name the browser asked, as a proxy in front says it if it says, | ||
// else as the request does: the site's OAuth client is named for it. | ||
let asked = text(HeaderName::from_static("x-forwarded-host")); | ||
match host.live_site(&did).filter(|s| !reads_of(s).is_empty()) { | ||
Some(site) => { | ||
let origin = format!("https://{}", asked.or(named).unwrap_or_default()); | ||
live(&host, &did, &handle, &site, &origin, asking) | ||
} | ||
None => sandboxed( | ||
host.site_answer(&did, &handle, &asking, "") | ||
.unwrap_or_else(IntoResponse::into_response), | ||
), | ||
} | ||
} | ||
| ||
/// The script a site's page runs to ask the page around it, `os`. | ||
const KIT: &str = include_str!("site_kit.js"); | ||
| ||
/// What the page around a site's pages allows itself: its own script, and | ||
/// calls to any PDS its visitor signs in at. | ||
const SHELL_POLICY: &str = "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; \ | ||
connect-src *; img-src * data:; frame-src 'self'; frame-ancestors 'none'; base-uri 'none'; \ | ||
form-action 'none'"; | ||
| ||
/// The answer of a site that asks for live data, as the browser at | ||
/// `origin` asked it: its files under `/_site/`, sandboxed; its OAuth | ||
/// client document, named for `origin`; the `os` script and the page's | ||
/// own; and at every other page, the page the host serves around them, | ||
/// holding the visitor's session. | ||
fn live( | ||
host: &Host, | ||
did: &str, | ||
handle: &str, | ||
site: &Value, | ||
origin: &str, | ||
mut asking: Asking, | ||
) -> Response { | ||
let reads = reads_of(site); | ||
match asking.path.as_str() { | ||
"client-metadata.json" => client_metadata(host, handle, origin, &reads), | ||
"_os/kit.js" => script(KIT.as_bytes().to_vec()), | ||
"_os/shell.js" => { | ||
let built = host.config.site_shell.as_ref().map(|d| d.join("shell.js")); | ||
match built.map(std::fs::read) { | ||
Some(Ok(bytes)) => script(bytes), | ||
_ => plain(StatusCode::NOT_FOUND, "no page to run a site in here"), | ||
} | ||
} | ||
path if path.starts_with("_site/") => { | ||
asking.path = path["_site/".len()..].to_string(); | ||
let answer = host.site_answer(did, handle, &asking, "/_site"); | ||
sandboxed(answer.unwrap_or_else(IntoResponse::into_response)) | ||
} | ||
_ if asking.page => shell(host, did, handle, site, &asking.path), | ||
_ => { | ||
let answer = host.site_answer(did, handle, &asking, ""); | ||
sandboxed(answer.unwrap_or_else(IntoResponse::into_response)) | ||
} | ||
} | ||
} | ||
| ||
fn script(bytes: Vec<u8>) -> Response { | ||
let kind = [(header::CONTENT_TYPE, "text/javascript; charset=utf-8")]; | ||
(StatusCode::OK, kind, bytes).into_response() | ||
} | ||
| ||
/// The site's OAuth client document, at its address `origin`: `atproto`, | ||
/// and leave to ask each of `reads`, and `getViewer`, of the host. | ||
fn client_metadata(host: &Host, handle: &str, origin: &str, reads: &[&str]) -> Response { | ||
let aud = format!("{}#opensocial", host.config.service_did); | ||
let aud = reqwest::Url::parse_with_params("https://x/", &[("aud", aud)]) | ||
.expect("a URL") | ||
.query() | ||
.unwrap_or_default() | ||
.to_string(); | ||
let mut scope = vec!["atproto".to_string()]; | ||
let viewer = "fyi.opensocial.getViewer"; | ||
for method in reads.iter().chain([&viewer]).collect::<BTreeSet<_>>() { | ||
scope.push(format!("rpc:{method}?{aud}")); | ||
} | ||
let doc = json!({ | ||
"client_id": format!("{origin}/client-metadata.json"), | ||
"client_name": handle, | ||
"client_uri": origin, | ||
"redirect_uris": [format!("{origin}/_os/callback")], | ||
"scope": scope.join(" "), | ||
"grant_types": ["authorization_code", "refresh_token"], | ||
"response_types": ["code"], | ||
"application_type": "web", | ||
"token_endpoint_auth_method": "none", | ||
"dpop_bound_access_tokens": true, | ||
}); | ||
let mut res = Json(doc).into_response(); | ||
res.headers_mut().insert( | ||
header::ACCESS_CONTROL_ALLOW_ORIGIN, | ||
HeaderValue::from_static("*"), | ||
); | ||
res | ||
} | ||
| ||
/// The page around a site's pages at `path`: the group's page there in a | ||
/// sandboxed frame, and what the host's script needs to sign its visitor | ||
/// in and ask `reads` as them. | ||
fn shell(host: &Host, did: &str, handle: &str, site: &Value, path: &str) -> Response { | ||
let reads = reads_of(site); | ||
let (status, html) = host.page_at(did, site, path); | ||
let head = site_head::preview(html.as_deref().unwrap_or_default(), handle); | ||
let config = json!({ | ||
"group": did, | ||
"handle": handle, | ||
"reads": reads, | ||
"aud": format!("{}#opensocial", host.config.service_did), | ||
"handleResolver": host.config.site_handle_resolver, | ||
"plc": host.config.plc_url, | ||
"signUpAt": host.config.signup_pds, | ||
"console": host.config.console_url, | ||
"allowHttp": host.config.public_url.starts_with("http://"), | ||
}); | ||
// In a script element, `<` is the one thing that could end it early. | ||
let config = config.to_string().replace('<', "\\u003c"); | ||
let frame = format!("/_site/{}", encoded(path)); | ||
let page = format!( | ||
"<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\">\ | ||
<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\ | ||
{head}</head><body>\ | ||
<iframe id=\"os-page\" title=\"{handle}\" data-src=\"{frame}\" \ | ||
sandbox=\"allow-scripts allow-forms allow-popups allow-popups-to-escape-sandbox\"></iframe>\ | ||
<script type=\"application/json\" id=\"os-config\">{config}</script>\ | ||
<script type=\"module\" src=\"/_os/shell.js\"></script></body></html>" | ||
); | ||
let headers = [ | ||
(header::CONTENT_TYPE, "text/html; charset=utf-8"), | ||
(header::CONTENT_SECURITY_POLICY, SHELL_POLICY), | ||
(header::CACHE_CONTROL, "no-cache"), | ||
(header::X_CONTENT_TYPE_OPTIONS, "nosniff"), | ||
]; | ||
(status, headers, page).into_response() | ||
} | ||
| ||
type Answer = Result<Json<Value>, XrpcError>; | ||
| @@ -418,11 +623,12 @@ pub async fn put_site( | ||
let group = configuring(&host, &headers, &body, "putSite").await?; | ||
host.active(&group)?; | ||
let mut site = json!({"$type": SITE, "files": [], "createdAt": iso(now_millis())}); | ||
for key in ["fallback", "notFound"] { | ||
if let Some(path) = body.get(key) { | ||
site[key] = path.clone(); | ||
for key in ["fallback", "notFound", "reads"] { | ||
if let Some(given) = body.get(key) { | ||
site[key] = given.clone(); | ||
} | ||
} | ||
reads(&site)?; | ||
let given = body["files"].as_array().expect("its lexicon requires it"); | ||
let names: Vec<Value> = given.iter().map(|f| json!({"path": f["path"]})).collect(); | ||
paths(&json!({"files": names, "fallback": site["fallback"], "notFound": site["notFound"]}))?; | ||
crates/group-host/tests/sites.rs+238−0
| @@ -457,3 +457,241 @@ async fn a_site_is_larger_than_another_methods_input() { | ||
let made = call(&h, &alice, "putSite", json!({"group": did, "files": files})).await; | ||
assert_eq!(made.0, 200, "{}", made.1); | ||
} | ||
| ||
/// The page around a live site's pages, as the host writes it: its head, | ||
/// and the settings its script reads. | ||
fn shell_of(page: &Page) -> (&str, Json) { | ||
let head = page.body.split("</head>").next().unwrap(); | ||
let config = page.body.split("id=\"os-config\">").nth(1).unwrap(); | ||
let config = config.split("</script>").next().unwrap(); | ||
(head, serde_json::from_str(config).unwrap()) | ||
} | ||
| ||
#[tokio::test] | ||
async fn a_site_that_reads_is_served_in_the_page_that_holds_its_visitors_session() { | ||
let built = tempfile::tempdir().unwrap(); | ||
std::fs::write(built.path().join("shell.js"), "// the shell").unwrap(); | ||
let dir = built.path().to_str().unwrap(); | ||
let vars = [ | ||
("SITE_SHELL_DIR", dir), | ||
("SITE_HANDLE_RESOLVER", "https://pds.test"), | ||
]; | ||
let h = start(&vars, false).await; | ||
let (did, [alice, ..]) = group(&h).await; | ||
let front = "<html><head><title> Riders & friends </title>\ | ||
<meta property=\"og:image\" content=\"/card.png\"></head><body>live</body></html>"; | ||
let files = json!([ | ||
{"path": "index.html", "text": front}, | ||
{"path": "rides/index.html", "text": "<h1>Rides</h1>"}, | ||
{"path": "card.png", "bytes": {"$bytes": "iVBORw0KGgo"}}, | ||
{"path": "404.html", "text": "<title>Lost</title>"}, | ||
]); | ||
let reads = | ||
json!([{"method": format!("{NS}.getGroup")}, {"method": format!("{NS}.listMembers")}]); | ||
let body = json!({"group": did, "files": files, "notFound": "404.html", "reads": reads}); | ||
let made = call(&h, &alice, "putSite", body.clone()).await; | ||
assert_eq!(made.0, 200, "{}", made.1); | ||
| ||
// A page is the host's, around the site's own in a sandboxed frame. | ||
let shell = page(&h, "/").await; | ||
assert_eq!(shell.status, 200); | ||
assert!( | ||
shell | ||
.header("content-security-policy") | ||
.contains("frame-ancestors 'none'") | ||
); | ||
assert_eq!(shell.header("cache-control"), "no-cache"); | ||
assert!( | ||
shell.body.contains("data-src=\"/_site/\""), | ||
"{}", | ||
shell.body | ||
); | ||
let (head, config) = shell_of(&shell); | ||
assert!( | ||
head.contains("<title>Riders & friends</title>"), | ||
"{head}" | ||
); | ||
assert!(head.contains("<meta property=\"og:image\" content=\"/card.png\">")); | ||
assert_eq!(config["group"], did); | ||
assert_eq!( | ||
config["reads"], | ||
json!([format!("{NS}.getGroup"), format!("{NS}.listMembers")]) | ||
); | ||
assert_eq!(config["handleResolver"], "https://pds.test"); | ||
// A page the site has no file for is missing there too, its preview | ||
// the notFound page's; a site with neither, the group's handle. | ||
let lost = page(&h, "/rides/42").await; | ||
assert_eq!(lost.status, 404); | ||
assert!(shell_of(&lost).0.contains("<title>Lost</title>")); | ||
assert!(lost.body.contains("data-src=\"/_site/rides/42\"")); | ||
assert_eq!(page(&h, "/rides").await.status, 200); | ||
| ||
// The site's own files, sandboxed, under /_site/; its folders too. | ||
let framed = page(&h, "/_site/").await; | ||
assert_eq!( | ||
(framed.status, framed.header("content-security-policy")), | ||
(200, SANDBOX) | ||
); | ||
assert!(framed.body.contains("live")); | ||
let folder = page(&h, "/_site/rides").await; | ||
assert_eq!( | ||
(folder.status, folder.header("location")), | ||
(301, "/_site/rides/") | ||
); | ||
// A file that is no page, at its own path, as the frame's links ask. | ||
let image = page(&h, "/card.png").await; | ||
assert_eq!( | ||
(image.status, image.header("content-type")), | ||
(200, "image/png") | ||
); | ||
| ||
// The scripts: the kit a page loads, and the host's own page's. | ||
let kit = page(&h, "/_os/kit.js").await; | ||
assert_eq!(kit.header("content-type"), "text/javascript; charset=utf-8"); | ||
assert!(kit.body.contains("customElements.define('os-sign-in'")); | ||
assert_eq!(page(&h, "/_os/shell.js").await.body, "// the shell"); | ||
| ||
// Its OAuth client: at the address, asking only for what it reads. | ||
let client = page(&h, "/client-metadata.json").await; | ||
let doc: Json = serde_json::from_str(&client.body).unwrap(); | ||
let origin = format!("https://{RIDERS}"); | ||
assert_eq!(doc["client_id"], format!("{origin}/client-metadata.json")); | ||
assert_eq!( | ||
doc["redirect_uris"], | ||
json!([format!("{origin}/_os/callback")]) | ||
); | ||
let scope = doc["scope"] | ||
.as_str() | ||
.unwrap() | ||
.split(' ') | ||
.collect::<Vec<_>>(); | ||
let aud = "aud=did%3Aweb%3Ahost.test%23opensocial"; | ||
let rpc = |m: &str| format!("rpc:{NS}.{m}?{aud}"); | ||
let wanted = [ | ||
"atproto".into(), | ||
rpc("getGroup"), | ||
rpc("getViewer"), | ||
rpc("listMembers"), | ||
]; | ||
assert_eq!(scope, wanted); | ||
// Behind a proxy, it is named for the name the browser asked. | ||
let proxied = [("x-forwarded-host", "riders.example:8443")]; | ||
let client = ask(&h, "GET", RIDERS, "/client-metadata.json", &proxied).await; | ||
let doc: Json = serde_json::from_str(&client.body).unwrap(); | ||
let callback = json!(["https://riders.example:8443/_os/callback"]); | ||
assert_eq!(doc["redirect_uris"], callback); | ||
| ||
// The host's methods answer there, for the page around the site. | ||
let health = page(&h, "/xrpc/_health").await; | ||
assert_eq!( | ||
(health.status, health.header("content-security-policy")), | ||
(200, "") | ||
); | ||
| ||
// Published without reads, it is its files alone again. | ||
let mut plain = body; | ||
plain.as_object_mut().unwrap().remove("reads"); | ||
assert_eq!(call(&h, &alice, "putSite", plain).await.0, 200); | ||
let front = page(&h, "/").await; | ||
assert_eq!( | ||
(front.status, front.header("content-security-policy")), | ||
(200, SANDBOX) | ||
); | ||
assert!(front.body.contains("live")); | ||
} | ||
| ||
#[tokio::test] | ||
async fn a_site_reads_only_what_the_host_lets_a_page_read() { | ||
let h = start(&[], false).await; | ||
let (did, [alice, ..]) = group(&h).await; | ||
let files = json!([{"path": "index.html", "text": "<p>hi</p>"}]); | ||
let reads = json!([{"method": format!("{NS}.createGroup")}]); | ||
let said = call( | ||
&h, | ||
&alice, | ||
"putSite", | ||
json!({"group": did, "files": files, "reads": reads}), | ||
) | ||
.await; | ||
assert_eq!(error(&said), (400, "InvalidSite")); | ||
let message = said.1["message"].as_str().unwrap(); | ||
assert!( | ||
message.contains("createGroup is none of the methods"), | ||
"{message}" | ||
); | ||
| ||
// Without a built page to hold a session, a page of the site still | ||
// loads, and says what it lacks. | ||
let reads = json!([{"method": format!("{NS}.getGroup")}]); | ||
let said = call( | ||
&h, | ||
&alice, | ||
"putSite", | ||
json!({"group": did, "files": files, "reads": reads}), | ||
) | ||
.await; | ||
assert_eq!(said.0, 200, "{}", said.1); | ||
let shell = page(&h, "/_os/shell.js").await; | ||
assert_eq!( | ||
(shell.status, shell.body.as_str()), | ||
(404, "no page to run a site in here") | ||
); | ||
// A site with no page anywhere for a path, its preview the handle's. | ||
let lost = page(&h, "/nowhere").await; | ||
assert_eq!(lost.status, 404); | ||
assert!( | ||
shell_of(&lost) | ||
.0 | ||
.contains(&format!("<title>{RIDERS}</title>")) | ||
); | ||
} | ||
| ||
#[test] | ||
fn a_page_previews_as_its_own_head_says_and_never_as_markup() { | ||
let preview = |html: &str| group_host::site_head::preview(html, "riders.test"); | ||
// The title, trimmed; none, or an empty one, is the fallback's. | ||
assert_eq!(preview("<TITLE> Rides </TITLE>"), "<title>Rides</title>"); | ||
assert_eq!(preview("<p>no head</p>"), "<title>riders.test</title>"); | ||
assert_eq!(preview("<title> </title>"), "<title>riders.test</title>"); | ||
assert_eq!(preview("<title>never closed"), "<title>riders.test</title>"); | ||
| ||
// The tags a preview is read from, however their attributes are | ||
// written; nothing else, and nothing after the head. | ||
let head = r##"<title>R</title> | ||
<meta name="description" content='Rides, "all paces"'> | ||
<META PROPERTY=og:title CONTENT=Riders /> | ||
<meta name="twitter:card" content="summary" defer> | ||
<meta name=theme-color content="#0a0"> | ||
<meta name="robots" content="noindex"> | ||
<meta property="fb:app_id" content="1"> | ||
<meta http-equiv="refresh" content="0;url=https://elsewhere.test"> | ||
<meta charset="utf-8"> | ||
<metadata name="description" content="no tag"> | ||
<meta name="description" content="unclosed> | ||
</head><body><meta name="description" content="in the body">"##; | ||
assert_eq!( | ||
preview(head), | ||
"<title>R</title>\ | ||
<meta name=\"description\" content=\"Rides, "all paces"\">\ | ||
<meta property=\"og:title\" content=\"Riders\">\ | ||
<meta name=\"twitter:card\" content=\"summary\">\ | ||
<meta name=\"theme-color\" content=\"#0a0\">" | ||
); | ||
| ||
// What a page wrote can't end the host's tags or open one of its own; | ||
// an entity it wrote stays as written. | ||
let sly = "<title>1 < 2 & \"q\" > 0</title>\ | ||
<meta property='og:x\"><script>' content=\"a\">"; | ||
assert_eq!( | ||
preview(sly), | ||
"<title>1 < 2 & "q" > 0</title>\ | ||
<meta property=\"og:x"><script>\" content=\"a\">" | ||
); | ||
| ||
// Only so much of a page is read, at a character's edge, and only so | ||
// many tags taken from it. | ||
let long = format!("a{}<title>late</title>", "é".repeat(40_000)); | ||
assert_eq!(preview(&long), "<title>riders.test</title>"); | ||
let many = "<meta name=description content=x>".repeat(40); | ||
assert_eq!(preview(&many).matches("<meta").count(), 32); | ||
} | ||
crates/group-host-mcp/src/lib.rs+3−1
| @@ -393,7 +393,9 @@ const TOOLS: &[(&str, &[&str], &str, Made)] = &[ | ||
"Publishes the group's website, whole, at its address (`https://<address>/`): 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.", | ||
cookies or storage. A site that names `reads`, methods of the host's such as \ | ||
fyi.opensocial.listMembers, is served in a page of the host's that signs its visitor in, \ | ||
and its pages ask those as whoever is looking, with `os.call` from `/_os/kit.js`.", | ||
Made::Method("putSite", None), | ||
), | ||
( | ||
crates/opensocial/src/lib.rs+13−3
| @@ -58,9 +58,10 @@ role | ||
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>] | ||
site publish <group> <dir> [--fallback <path>] [--not-found <path>] [--reads <methods>] | ||
publish the files under <dir> as the group's website, at its | ||
address, in place of the one there | ||
address, in place of the one there; with --reads, the host's | ||
methods its pages may ask as whoever signs in on it | ||
site delete <group> take the group's website down | ||
member | ||
member list <group> [--q <text>] [--limit <n>] [--cursor <cursor>] | ||
| @@ -672,7 +673,7 @@ pub async fn run(args: &[String], env: &Env) -> Result<String> { | ||
Ok(stats_lines(&said)) | ||
} | ||
["site", "publish", rest @ ..] => { | ||
let a = parse(rest, &["fallback", "not-found"])?; | ||
let a = parse(rest, &["fallback", "not-found", "reads"])?; | ||
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")] { | ||
| @@ -680,6 +681,15 @@ pub async fn run(args: &[String], env: &Env) -> Result<String> { | ||
given[name] = json!(path); | ||
} | ||
} | ||
// Each method by its NSID, or its name alone, as one of ours. | ||
if let Some(reads) = a.flags.get("reads") { | ||
let methods = reads.split(',').map(str::trim).filter(|r| !r.is_empty()); | ||
let named = |r: &str| match r.contains('.') { | ||
true => r.to_string(), | ||
false => m(r), | ||
}; | ||
given["reads"] = methods.map(|r| json!({"method": named(r)})).collect(); | ||
} | ||
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"); | ||
crates/opensocial/tests/commands.rs+17−0
| @@ -922,6 +922,23 @@ async fn publishes_a_folder_as_the_groups_site_and_takes_it_down() { | ||
(Some("index.html"), Some("rides/index.html")) | ||
); | ||
| ||
// Reads by name, as one of the host's, or by NSID. | ||
let args = [ | ||
"site", | ||
"publish", | ||
group, | ||
folder, | ||
"--reads", | ||
"getGroup, fyi.opensocial.listMembers", | ||
]; | ||
ok(&alice, &args).await; | ||
let record = h.host.store.record(&did, "fyi.opensocial.site", "self"); | ||
let site = atproto::drisl::decode(&record.unwrap().unwrap().value).unwrap(); | ||
let reads = &site.to_json()["reads"]; | ||
let wanted = | ||
json!([{"method": "fyi.opensocial.getGroup"}, {"method": "fyi.opensocial.listMembers"}]); | ||
assert_eq!(reads, &wanted); | ||
| ||
let missing = fails(&alice, &["site", "publish", group, "/no/such/folder"]).await; | ||
assert!(missing.contains("reading /no/such/folder"), "{missing}"); | ||
| ||
docs/design/README.md+2−1
| @@ -62,7 +62,8 @@ accounts on their own PDSes, anywhere on the network. | ||
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 address. | ||
sandboxed at its address, and the live data a visitor sees once | ||
signed in on it. | ||
- [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. | ||