chadtmiller.com/group-host
atmosphere group host
0
0
A group's pictures and who sees its profile, set in the console
crates/group-host/src/blobs.rs+112−2
| @@ -3,15 +3,30 @@ | ||
//! references it makes it permanent, and one that drops the last reference | ||
//! deletes it. Temporary blobs no record took within a day are swept. Only | ||
//! a blob a record references is served. | ||
//! | ||
//! An image of an account's is also served for a page to draw, at | ||
//! `/img/{did}/{cid}`, to whoever may see a record that holds it: anyone, | ||
//! for a record in its public repo or in the profile of a group listed on | ||
//! the network; for one in a space, whoever that space lets read, as the | ||
//! console's session says. Served as an image and nothing more, and kept | ||
//! for good, as a CID names its bytes. | ||
| ||
use crate::Host; | ||
use crate::store::Blob; | ||
use crate::authority::Access; | ||
use crate::group::meta_space; | ||
use crate::rbac::NS; | ||
use crate::store::{Blob, Store}; | ||
use crate::time::now_millis; | ||
use crate::xrpc::XrpcError; | ||
use anyhow::Result; | ||
use atproto::Cid; | ||
use axum::http::StatusCode; | ||
use axum::extract::{Path, State}; | ||
use axum::http::{HeaderMap, StatusCode, header}; | ||
use axum::response::{IntoResponse, Response}; | ||
use rusqlite::OptionalExtension; | ||
use serde_json::{Value, json}; | ||
use std::path::PathBuf; | ||
use std::sync::Arc; | ||
| ||
/// How long an upload waits for a record to reference it. | ||
pub const TEMPORARY_FOR: i64 = 24 * 60 * 60 * 1000; | ||
| @@ -130,3 +145,98 @@ fn collect(value: &Value, found: &mut Vec<Cid>) { | ||
_ => {} | ||
} | ||
} | ||
| ||
/// The kinds of image a page may be given. | ||
const IMAGES: [&str; 5] = [ | ||
"image/png", | ||
"image/jpeg", | ||
"image/webp", | ||
"image/gif", | ||
"image/avif", | ||
]; | ||
| ||
impl Store { | ||
/// Whether a record in `did`'s public repo holds the blob `cid`. | ||
pub fn held_publicly(&self, did: &str, cid: &Cid) -> anyhow::Result<bool> { | ||
let sql = "SELECT 1 FROM record_blob WHERE did = ?1 AND cid = ?2 LIMIT 1"; | ||
let found = self | ||
.conn() | ||
.query_row(sql, [did, &cid.to_string()], |_| Ok(())); | ||
Ok(found.optional()?.is_some()) | ||
} | ||
| ||
/// The spaces in which a record of `did`'s holds the blob `cid`. | ||
pub fn holding_spaces(&self, did: &str, cid: &Cid) -> anyhow::Result<Vec<String>> { | ||
let conn = self.conn(); | ||
let sql = "SELECT DISTINCT space FROM space_record_blob WHERE did = ?1 AND cid = ?2"; | ||
let mut q = conn.prepare(sql)?; | ||
let rows = q.query_map([did, &cid.to_string()], |r| r.get(0)); | ||
let rows = rows?; | ||
Ok(rows.collect::<rusqlite::Result<_>>()?) | ||
} | ||
} | ||
| ||
impl Host { | ||
/// Whether `who` (none, for someone not signed in) may see `did`'s blob | ||
/// `cid`: a record holding it is one they may read. | ||
pub fn may_see(&self, did: &str, cid: &Cid, who: Option<&str>) -> Result<bool> { | ||
if self.store.deactivation(did)?.is_some() { | ||
return Ok(false); | ||
} | ||
if self.store.held_publicly(did, cid)? { | ||
return Ok(true); | ||
} | ||
// A listed group's profile is anyone's to see, as listGroups shows it. | ||
let listed = self | ||
.store | ||
.record(did, &format!("{NS}.declaration"), "self")? | ||
.is_some(); | ||
for space in self.store.holding_spaces(did, cid)? { | ||
if listed && space == meta_space(did) { | ||
return Ok(true); | ||
} | ||
let hosted = self.store.space(&space)?; | ||
let may = hosted.map(|h| self.may(&space, &h, who, Access::Read)); | ||
if may.transpose()?.unwrap_or(false) { | ||
return Ok(true); | ||
} | ||
} | ||
Ok(false) | ||
} | ||
} | ||
| ||
/// An image of `did`'s, `cid`, for whoever may see it: nothing for anyone | ||
/// else, or for a blob that is not an image. | ||
pub async fn image( | ||
State(host): State<Arc<Host>>, | ||
Path((did, cid)): Path<(String, String)>, | ||
headers: HeaderMap, | ||
) -> Response { | ||
let gone = || StatusCode::NOT_FOUND.into_response(); | ||
let Ok(cid) = Cid::parse(&cid) else { | ||
return gone(); | ||
}; | ||
let who = host.console_caller(&headers).ok().flatten(); | ||
if !host.may_see(&did, &cid, who.as_deref()).unwrap_or(false) { | ||
return gone(); | ||
} | ||
let read = host.read_blob(&did, &cid).ok().flatten(); | ||
let Some((blob, bytes)) = read.filter(|(b, _)| IMAGES.contains(&b.mime_type.as_str())) else { | ||
return gone(); | ||
}; | ||
let headers = [ | ||
(header::CONTENT_TYPE, blob.mime_type), | ||
(header::X_CONTENT_TYPE_OPTIONS, "nosniff".into()), | ||
( | ||
header::CONTENT_SECURITY_POLICY, | ||
"default-src 'none'; sandbox".into(), | ||
), | ||
// Whoever else may see it, a CID's bytes never change: kept in a | ||
// browser, not in a cache between. | ||
( | ||
header::CACHE_CONTROL, | ||
"private, max-age=31536000, immutable".into(), | ||
), | ||
]; | ||
(headers, bytes).into_response() | ||
} | ||
crates/group-host/src/console_login.rs+1−1
| @@ -196,7 +196,7 @@ impl Host { | ||
} | ||
| ||
/// A session cookie's value, naming `did`, signed `now`. | ||
pub(crate) fn session_cookie(&self, did: &str, now: i64) -> String { | ||
pub fn session_cookie(&self, did: &str, now: i64) -> String { | ||
let claims = jose::b64(json!({"did": did, "iat": now, "exp": now + LASTS}).to_string()); | ||
format!( | ||
"{claims}.{}", | ||
crates/group-host/src/lib.rs+1−0
| @@ -442,6 +442,7 @@ pub fn router(host: Arc<Host>) -> Router { | ||
"/console/client-metadata.json", | ||
get(console_login::client_metadata), | ||
) | ||
.route("/img/{did}/{cid}", get(blobs::image)) | ||
.route("/console/login", get(console_login::login)) | ||
.route("/console/move/login", get(account_move::login)) | ||
.route( | ||
crates/group-host/tests/group_config.rs+102−0
| @@ -358,3 +358,105 @@ async fn an_admin_keeps_the_rules() { | ||
); | ||
} | ||
} | ||
| ||
/// An image of `did`'s, `cid`, as a page asks for it, as `who` if anyone: | ||
/// its status, its headers, and its bytes. | ||
async fn image( | ||
h: &common::Running, | ||
did: &str, | ||
cid: &str, | ||
who: Option<&Authority>, | ||
) -> (u16, reqwest::header::HeaderMap, Vec<u8>) { | ||
let mut req = h.http.get(format!("{}/img/{did}/{cid}", h.url)); | ||
if let Some(who) = who { | ||
let now = std::time::SystemTime::now() | ||
.duration_since(std::time::UNIX_EPOCH) | ||
.unwrap() | ||
.as_millis() as i64; | ||
let cookie = h.host.session_cookie(&who.did, now); | ||
req = req.header( | ||
"cookie", | ||
format!("{}={cookie}", group_host::console_login::COOKIE), | ||
); | ||
} | ||
let res = req.send().await.unwrap(); | ||
let status = res.status().as_u16(); | ||
let headers = res.headers().clone(); | ||
(status, headers, res.bytes().await.unwrap().to_vec()) | ||
} | ||
| ||
/// A record holding `blob`, of a collection of its own. | ||
fn holding(rkey: &str, blob: &Json) -> Write { | ||
Write::Create { | ||
collection: "com.example.photo".into(), | ||
rkey: rkey.into(), | ||
value: json!({"$type": "com.example.photo", "image": blob, "createdAt": "2026-11-04T00:00:00Z"}), | ||
} | ||
} | ||
| ||
#[tokio::test] | ||
async fn shows_an_image_to_whoever_may_see_a_record_that_holds_it() { | ||
let (h, did, [alice, bob, carol]) = group().await; | ||
let cid = |b: &Json| b["ref"]["$link"].as_str().unwrap().to_string(); | ||
| ||
// The avatar of a group listed on the network: anyone's to see, as an | ||
// image and nothing more, kept for good. | ||
let (_, up) = upload(&h, &alice, &did, b"face".to_vec(), "image/png").await; | ||
let avatar = up["blob"].clone(); | ||
let body = json!({"group": did, "displayName": "Riders", "avatar": avatar}); | ||
assert_eq!(call(&h, &alice, "updateProfile", body).await.0, 200); | ||
let (status, headers, bytes) = image(&h, &did, &cid(&avatar), None).await; | ||
assert_eq!((status, bytes.as_slice()), (200, &b"face"[..])); | ||
assert_eq!(headers["content-type"], "image/png"); | ||
assert_eq!(headers["x-content-type-options"], "nosniff"); | ||
assert_eq!( | ||
headers["content-security-policy"], | ||
"default-src 'none'; sandbox" | ||
); | ||
assert_eq!( | ||
headers["cache-control"], | ||
"private, max-age=31536000, immutable" | ||
); | ||
| ||
// Unlisted, its profile is its readers' alone: a member's, not a | ||
// stranger's, nor anyone's not signed in. | ||
let meta = meta_space(&did); | ||
let hide = json!({"group": did, "space": meta, "readableBy": [{"role": "member"}]}); | ||
assert_eq!(call(&h, &alice, "updateSpace", hide).await.0, 200); | ||
assert_eq!(image(&h, &did, &cid(&avatar), None).await.0, 404); | ||
assert_eq!(image(&h, &did, &cid(&avatar), Some(&carol)).await.0, 404); | ||
assert_eq!(image(&h, &did, &cid(&avatar), Some(&bob)).await.0, 200); | ||
| ||
// In its public repo: anyone's. | ||
let (_, up) = upload(&h, &alice, &did, b"ride".to_vec(), "image/jpeg").await; | ||
let photo = up["blob"].clone(); | ||
h.host.write(&did, &[holding("ride", &photo)]).unwrap(); | ||
assert_eq!(image(&h, &did, &cid(&photo), None).await.0, 200); | ||
| ||
// A file that is no image is not served as one, wherever it is held. | ||
let text = h.host.upload_blob(&did, b"words", "text/plain").unwrap(); | ||
h.host.write(&did, &[holding("words", &text)]).unwrap(); | ||
assert_eq!(image(&h, &did, &cid(&text), None).await.0, 404); | ||
| ||
// Nothing of its held by no record, and no CID at all. | ||
let loose = h.host.upload_blob(&did, b"loose", "image/png").unwrap(); | ||
assert_eq!(image(&h, &did, &cid(&loose), None).await.0, 404); | ||
assert_eq!(image(&h, &did, "not-a-cid", None).await.0, 404); | ||
| ||
// In a space of another's, which this host does not govern: no one's. | ||
let elsewhere = "at://did:plc:elsewhere/space/com.example.forum/main"; | ||
let (_, up) = upload(&h, &alice, &did, b"away".to_vec(), "image/png").await; | ||
let away = up["blob"].clone(); | ||
h.host | ||
.space_write(&did, elsewhere, &[holding("away", &away)]) | ||
.await | ||
.unwrap(); | ||
assert_eq!(image(&h, &did, &cid(&away), Some(&bob)).await.0, 404); | ||
| ||
// Switched off, it shows nothing. | ||
h.host | ||
.store | ||
.deactivate(&did, 0, &alice.did, &[], &[]) | ||
.unwrap(); | ||
assert_eq!(image(&h, &did, &cid(&photo), None).await.0, 404); | ||
} | ||
docs/design/groups.md+14−0
| @@ -78,6 +78,20 @@ so the host writes them for a caller holding `group.configure`: | ||
- `uploadImage` keeps an image (1 MB at most) as the group's blob, for | ||
the profile to reference: a blob in anyone else's repo would not | ||
resolve for it. | ||
| ||
Any image of a group's is served for a page to draw at | ||
`/img/{did}/{cid}` (`blobs.rs`), to whoever may see a record that holds | ||
it: anyone, for a record in its public repo, or in its profile while it is | ||
declared (as `listGroups` shows that profile to anyone); for a record in a | ||
space, whoever that space lets read, as the console's session cookie says. | ||
Only a PNG, JPEG, WebP, GIF or AVIF is served, as an image and nothing | ||
more (`nosniff`, and a sandbox for any document), and kept in the browser | ||
for good, as a CID names its bytes. A group switched off shows none. | ||
| ||
The console's settings set its pictures, and who sees its profile: | ||
anyone, when it is declared too, or its members alone. The host still | ||
lists every group of its own (`listGroups`), a hidden one by its handle | ||
alone. | ||
- `putRule` makes or changes a rule. A rule keeps its key when changed, | ||
so a label citing it still does; a new one goes last unless it says | ||
where. `deleteRule` takes one away; a label citing it keeps the URI. | ||
docs/reference/config.md+6−2
| @@ -22,8 +22,12 @@ and refuses to start on a value that does not read, saying which. | ||
| ||
It stops on SIGTERM or ctrl-c, answering the requests under way first. | ||
| ||
The console reads one: `GROUP_HOST`, the host it asks (default | ||
`http://127.0.0.1:2600`). | ||
The console reads `GROUP_HOST`, the host it asks (default | ||
`http://127.0.0.1:2600`), and, built (`node build`), what SvelteKit's | ||
Node adapter reads: `ORIGIN`, the address people reach it at, and | ||
`BODY_SIZE_LIMIT`, the most a request it hands on may carry (by default | ||
512K): set it to at least `BLOB_UPLOAD_LIMIT`, or an upload larger than | ||
that is refused before the host sees it. | ||
| ||
The `opensocial` command reads its own: `OPENSOCIAL_AS` and | ||
`OPENSOCIAL_PASSWORD` (who it signs in as), `PDS_URL` (where), | ||
harness/e2e/flows.spec.mjs+44−0
| @@ -123,6 +123,50 @@ test("changing a group's profile", async () => { | ||
await expect(page.getByText('Walks on Sundays.')).toBeVisible() | ||
}) | ||
| ||
// A one-pixel PNG. | ||
const PIXEL = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==', 'base64') | ||
| ||
test("giving a group a picture, and taking it away", async () => { | ||
await page.goto(url('/g/hikers.groups.test/settings')) | ||
await page.getByLabel('Avatar').setInputFiles({ name: 'face.png', mimeType: 'image/png', buffer: PIXEL }) | ||
await page.getByRole('button', { name: 'Upload the avatar' }).click() | ||
// Drawn on its page, from the host, as the image it is: one pixel wide. | ||
await page.goto(url('/g/hikers.groups.test')) | ||
const avatar = page.locator('.identity img.av') | ||
await expect(avatar).toBeVisible() | ||
await expect.poll(() => avatar.evaluate((img) => img.naturalWidth)).toBe(1) | ||
await page.goto(url('/g/hikers.groups.test/settings')) | ||
await page.getByRole('button', { name: 'Take the avatar away' }).click() | ||
await page.goto(url('/g/hikers.groups.test')) | ||
await expect(page.locator('.identity img.av')).toHaveCount(0) | ||
}) | ||
| ||
test("hiding a group's profile, and showing it again", async () => { | ||
// The host lists every group of its own; a hidden one by its handle alone. | ||
const listed = async () => { | ||
const { groups } = await fetch(`${world.host}/xrpc/fyi.opensocial.listGroups`).then((r) => r.json()) | ||
return groups.find((g) => g.handle === 'hikers.groups.test')?.displayName !== undefined | ||
} | ||
expect(await listed()).toBe(true) | ||
await page.goto(url('/g/hikers.groups.test/settings')) | ||
// Saved, and the page opened afresh as the host has it: not reloaded, | ||
// which would send the form's post again. | ||
const settings = url('/g/hikers.groups.test/settings') | ||
const save = async (label) => { | ||
await page.goto(settings) | ||
await page.getByLabel(label).check() | ||
const saved = page.waitForResponse((r) => r.request().method() === 'POST' && r.url().includes('/visibility')) | ||
await page.getByRole('button', { name: 'Save who sees it' }).click() | ||
await saved | ||
await page.goto(settings) | ||
await expect(page.getByLabel(label)).toBeChecked() | ||
} | ||
await save('Its members alone: to others, just its handle') | ||
await expect.poll(listed).toBe(false) | ||
await save('Anyone, and found on the network') | ||
await expect.poll(listed).toBe(true) | ||
}) | ||
| ||
test('adding a rule, and taking it away', async () => { | ||
await page.goto(url('/g/hikers.groups.test/settings')) | ||
await page.getByRole('textbox', { name: 'Rule' }).fill('Leave no trace') | ||
harness/world.mjs+2−1
| @@ -91,7 +91,8 @@ export async function start({ accounts, front, pdsEnv = {} }) { | ||
const web = spawn('node', ['build'], { | ||
cwd: join(root, 'web'), | ||
stdio: ['ignore', 'inherit', 'inherit'], | ||
env: { ...process.env, PORT: String(consolePort), HOST: '127.0.0.1', GROUP_HOST: `http://127.0.0.1:${hostPort}`, ORIGIN: base }, | ||
// A body as large as the host takes, past the Node adapter's 512K. | ||
env: { ...process.env, PORT: String(consolePort), HOST: '127.0.0.1', GROUP_HOST: `http://127.0.0.1:${hostPort}`, ORIGIN: base, BODY_SIZE_LIMIT: '64M' }, | ||
}) | ||
children.push(web) | ||
await up(`http://127.0.0.1:${consolePort}/`) | ||
lexicons/fyi/opensocial/defs.json+4−4
| @@ -217,7 +217,7 @@ | ||
}, | ||
"avatar": { | ||
"type": "string", | ||
"description": "CID of the avatar blob; the host serves it at /img/{did}/avatar." | ||
"description": "CID of the avatar blob; the host serves it at /img/{did}/{cid}, to whoever may see the profile." | ||
}, | ||
"rules": { | ||
"type": "array", | ||
| @@ -232,7 +232,7 @@ | ||
}, | ||
"banner": { | ||
"type": "string", | ||
"description": "CID of the banner blob; the host serves it at /img/{did}/banner." | ||
"description": "CID of the banner blob; the host serves it at /img/{did}/{cid}, to whoever may see the profile." | ||
}, | ||
"createdAt": { | ||
"type": "string", | ||
| @@ -319,7 +319,7 @@ | ||
}, | ||
"avatar": { | ||
"type": "string", | ||
"description": "CID of the avatar blob; the host serves it at /img/{did}/avatar." | ||
"description": "CID of the avatar blob; the host serves it at /img/{did}/{cid}, to whoever may see the profile." | ||
}, | ||
"deactivated": { | ||
"type": "boolean", | ||
| @@ -327,7 +327,7 @@ | ||
}, | ||
"banner": { | ||
"type": "string", | ||
"description": "CID of the banner blob; the host serves it at /img/{did}/banner." | ||
"description": "CID of the banner blob; the host serves it at /img/{did}/{cid}, to whoever may see the profile." | ||
}, | ||
"rules": { | ||
"type": "array", | ||
web/src/lib/organisms/GroupList.svelte+3−2
| @@ -1,12 +1,13 @@ | ||
<script lang="ts"> | ||
import Empty from '#lib/molecules/Empty.svelte'; | ||
import GroupRow from '#lib/molecules/GroupRow.svelte'; | ||
import { image } from '#lib/images.ts'; | ||
/** The groups a host runs, or what it says when it runs none. */ | ||
let { groups }: { groups: { did: string; handle: string; displayName?: string }[] } = $props(); | ||
let { groups }: { groups: { did: string; handle: string; displayName?: string; avatar?: string }[] } = $props(); | ||
</script> | ||
| ||
{#if groups.length} | ||
<div>{#each groups as g (g.did)}<GroupRow name={g.displayName ?? g.handle} handle={g.handle} />{/each}</div> | ||
<div>{#each groups as g (g.did)}<GroupRow name={g.displayName ?? g.handle} handle={g.handle} avatar={image(g.did, g.avatar)} />{/each}</div> | ||
{:else} | ||
<Empty title="No groups here yet">A group started on this host shows here once its profile is public.</Empty> | ||
{/if} | ||