chadtmiller.com/group-host
atmosphere group host
0
0
A group's links show their site's icon, kept as the group's own
crates/group-host/src/config.rs+6−0
| @@ -44,6 +44,10 @@ pub struct Config { | ||
/// `provisionGroup`, `PROVISIONING_CLIENTS`, comma-separated client | ||
/// ids, `*` for any: none unless set. | ||
pub provisioning_clients: Vec<String>, | ||
/// Where a link's site's icon is asked when an MCP client writes a link | ||
/// to a group's profile, `FAVICONS`: the link's address follows, | ||
/// encoded. Bluesky's favicon service unless set; empty asks nowhere. | ||
pub favicons: String, | ||
/// Where a handle being typed is looked for, `ACTOR_SEARCH`: `plc`, | ||
/// the handles in `PLC_URL`'s own export, or the URL of a service | ||
/// answering `tech.waow.typeahead.searchActors`. The typeahead service | ||
| @@ -134,6 +138,7 @@ impl Config { | ||
if reqwest::Url::parse(&console_url).is_err() { | ||
bail!("CONSOLE_URL is no URL: {console_url}"); | ||
} | ||
let favicons = var("FAVICONS").unwrap_or_else(|| group_host_mcp::FAVICONS.into()); | ||
let signup_pds = var("SIGNUP_PDS").unwrap_or_else(|| "https://bsky.social".into()); | ||
let signup_pds = signup_pds.trim_end_matches('/').to_string(); | ||
if reqwest::Url::parse(&signup_pds).is_err() { | ||
| @@ -153,6 +158,7 @@ impl Config { | ||
blob_upload_limit, | ||
console_url, | ||
provisioning_clients, | ||
favicons, | ||
actor_search, | ||
signup_pds, | ||
}) | ||
crates/group-host/src/group_config.rs+41−11
| @@ -23,6 +23,9 @@ type Answer = Result<Json<Value>, XrpcError>; | ||
/// The most bytes a profile's picture may be, as its lexicon has it. | ||
pub const IMAGE_AT_MOST: i64 = 2_000_000; | ||
| ||
/// The most bytes a link's icon may be, as its lexicon has it. | ||
pub const ICON_AT_MOST: i64 = 100_000; | ||
| ||
/// Where a group meets: the places `community.lexicon.location` has. | ||
const PLACES: [&str; 4] = [ | ||
"community.lexicon.location.address", | ||
| @@ -162,23 +165,49 @@ fn site(profile: &Value) -> Result<(), XrpcError> { | ||
impl Host { | ||
/// Refuses a picture a profile names at `key`, unless it is one of the | ||
/// group's own uploads, of a kind of image a page is given and no | ||
/// larger than a profile takes, with the type and size the host kept. | ||
/// larger than a profile takes. | ||
fn picture(&self, group: &str, profile: &Value, key: &str) -> Result<(), XrpcError> { | ||
let Some(asked) = profile.get(key) else { | ||
return Ok(()); | ||
}; | ||
let not_one = || { | ||
invalid(format!( | ||
"{key} is a PNG, JPEG or WebP image of at most {IMAGE_AT_MOST} bytes, as the group's uploadBlob answered it" | ||
)) | ||
}; | ||
let not_one = format!( | ||
"{key} is a PNG, JPEG or WebP image of at most {IMAGE_AT_MOST} bytes, as the group's uploadBlob answered it" | ||
); | ||
self.image(group, asked, &PROFILE_IMAGES, IMAGE_AT_MOST, ¬_one) | ||
} | ||
| ||
/// Refuses an icon a link names, unless it is one of the group's own | ||
/// uploads, a PNG no larger than a link takes. | ||
fn icons(&self, group: &str, profile: &Value) -> Result<(), XrpcError> { | ||
let not_one = format!( | ||
"a link's icon is a PNG image of at most {ICON_AT_MOST} bytes, as the group's uploadBlob answered it" | ||
); | ||
let links = profile["links"].as_array().into_iter().flatten(); | ||
for icon in links.filter_map(|link| link.get("icon")) { | ||
self.image(group, icon, &["image/png"], ICON_AT_MOST, ¬_one)?; | ||
} | ||
Ok(()) | ||
} | ||
| ||
/// Refuses the blob `asked`, unless it is one of the group's own | ||
/// uploads, of one of `kinds` and at most `at_most` bytes, with the | ||
/// type and size the host kept: `not_one` says why. | ||
fn image( | ||
&self, | ||
group: &str, | ||
asked: &Value, | ||
kinds: &[&str], | ||
at_most: i64, | ||
not_one: &str, | ||
) -> Result<(), XrpcError> { | ||
let not_one = || invalid(not_one.to_string()); | ||
let link = asked["ref"]["$link"].as_str().unwrap_or_default(); | ||
let cid = Cid::parse(link).map_err(|_| not_one())?; | ||
let kept = self.store.blob(group, &cid).map_err(XrpcError::internal)?; | ||
let kept = kept.ok_or_else(not_one)?; | ||
let image = PROFILE_IMAGES.contains(&kept.mime_type.as_str()); | ||
let image = kinds.contains(&kept.mime_type.as_str()); | ||
let as_kept = asked["mimeType"] == kept.mime_type && asked["size"] == kept.size; | ||
if !image || kept.size > IMAGE_AT_MOST || !as_kept { | ||
if !image || kept.size > at_most || !as_kept { | ||
return Err(not_one()); | ||
} | ||
Ok(()) | ||
| @@ -186,8 +215,8 @@ impl Host { | ||
| ||
/// Refuses a profile the group should not keep: one with no name, a | ||
/// join policy the host does not know, a place that is none, a site or | ||
/// link not on the web, words blank or listed twice, or a picture that is | ||
/// not one of its own. | ||
/// link not on the web, words blank or listed twice, or a picture or a | ||
/// link's icon that is not one of its own. | ||
fn profile(&self, group: &str, profile: &Value) -> Result<(), XrpcError> { | ||
if !said(&profile["displayName"]) { | ||
return Err(invalid("displayName is required")); | ||
| @@ -200,7 +229,8 @@ impl Host { | ||
words(profile, "topics", "topic")?; | ||
words(profile, "languages", "language")?; | ||
self.picture(group, profile, "avatar")?; | ||
self.picture(group, profile, "banner") | ||
self.picture(group, profile, "banner")?; | ||
self.icons(group, profile) | ||
} | ||
| ||
/// Refuses a write of the group's profile or one of its rules, in its | ||
crates/group-host/src/mcp.rs+22−0
| @@ -791,6 +791,17 @@ impl Host { | ||
let kept = self.group_record(&who.group, &uri, &collection, &rkey); | ||
let kept = kept.map_err(XrpcError::internal).map_err(said)?; | ||
let kept = kept.unwrap_or_default(); | ||
// Each new link's site's icon, kept as the group's own. | ||
let mut fields = fields; | ||
let favicons = &self.config.favicons; | ||
let wanted = group_host_mcp::iconless(&collection, &kept, &mut fields, favicons); | ||
for (at, asked) in wanted { | ||
let Some(png) = favicon(&self.http, &asked).await else { | ||
continue; | ||
}; | ||
let icon = self.upload_blob(&who.group, &png, "image/png"); | ||
group_host_mcp::iconed(&mut fields, at, icon.map_err(said)?); | ||
} | ||
let write = group_host_mcp::edited(&kept, space, collection, rkey, fields); | ||
Box::pin(self.carry_out(who, write)).await | ||
} | ||
| @@ -938,3 +949,14 @@ pub async fn revoke_connected_app( | ||
ended.map_err(XrpcError::internal)?; | ||
Ok(Json(json!({}))) | ||
} | ||
| ||
/// The icon the favicon service answers at `asked`: a PNG no larger than | ||
/// a link's icon may be, or none. | ||
async fn favicon(http: &reqwest::Client, asked: &str) -> Option<Vec<u8>> { | ||
let res = http.get(asked).send().await.ok()?; | ||
let kind = res.headers().get(header::CONTENT_TYPE).cloned(); | ||
let png = res.status().is_success() && kind.is_some_and(|k| k == "image/png"); | ||
let bytes = res.bytes().await.ok()?; | ||
let small = bytes.len() <= group_host_mcp::ICON_AT_MOST; | ||
(png && small).then(|| bytes.to_vec()) | ||
} | ||
crates/group-host/tests/common/mod.rs+29−0
| @@ -157,6 +157,35 @@ async fn last( | ||
.ok_or(StatusCode::NOT_FOUND) | ||
} | ||
| ||
/// The bytes the favicon service answers for a site whose name starts | ||
/// `chat.`. | ||
pub const FAVICON: &[u8] = b"\x89PNG a green dot"; | ||
| ||
/// A favicon service, as the host asks one: where it is, the link's | ||
/// address to follow. A site whose name starts `chat.` has `FAVICON`, one | ||
/// whose starts `big.` an icon larger than a link's may be, `gif.` one | ||
/// that is no PNG; any other none. | ||
pub async fn start_favicons() -> String { | ||
async fn icon( | ||
axum::extract::Query(q): axum::extract::Query<HashMap<String, String>>, | ||
) -> axum::response::Response { | ||
use axum::response::IntoResponse; | ||
let site = q.get("url").map(String::as_str).unwrap_or_default(); | ||
let site = site.trim_start_matches("https://"); | ||
let png = [(axum::http::header::CONTENT_TYPE, "image/png")]; | ||
match site.split('.').next() { | ||
Some("chat") => (png, FAVICON).into_response(), | ||
Some("big") => (png, vec![0; 100_001]).into_response(), | ||
Some("gif") => { | ||
([(axum::http::header::CONTENT_TYPE, "image/gif")], "GIF89a").into_response() | ||
} | ||
_ => StatusCode::NOT_FOUND.into_response(), | ||
} | ||
} | ||
let at = serve(Router::new().route("/favicon", get(icon))).await; | ||
format!("{at}/favicon?url=") | ||
} | ||
| ||
/// Serves `router` on a free port, answering its address. | ||
pub async fn serve(router: Router) -> String { | ||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); | ||
crates/group-host/tests/group_config.rs+8−1
| @@ -83,13 +83,15 @@ async fn an_admin_changes_the_profile() { | ||
assert_eq!(avatar["size"], 2_000_000); | ||
assert_eq!(avatar["mimeType"], "image/webp"); | ||
let banner = uploaded(&h, &app, &token, b"road".to_vec(), "image/jpeg").await; | ||
// As large as a link's icon may be. | ||
let icon = uploaded(&h, &app, &token, vec![8; 100_000], "image/png").await; | ||
let record = riders(json!({ | ||
"displayName": "Riders United", | ||
"description": "We ride.", | ||
"url": "https://riders.example", | ||
// As many links as a profile holds, a title as long as one may be. | ||
"links": [ | ||
{"url": "https://chat.riders.example", "title": "Our chat"}, | ||
{"url": "https://chat.riders.example", "title": "Our chat", "icon": icon}, | ||
{"url": "http://calendar.riders.example/rides"}, | ||
{"url": "https://a.example", "title": "x".repeat(64)}, | ||
{"url": "https://b.example", "title": "B"}, | ||
| @@ -150,6 +152,7 @@ async fn refuses_a_profile_it_should_not_keep() { | ||
let moving = uploaded(&h, &app, &token, b"GIF89a".to_vec(), "image/gif").await; | ||
let large = uploaded(&h, &app, &token, vec![0; 2_000_001], "image/png").await; | ||
let face = uploaded(&h, &app, &token, b"face".to_vec(), "image/webp").await; | ||
let wide = uploaded(&h, &app, &token, vec![0; 100_001], "image/png").await; | ||
// Its type and size are the upload's, whatever the record says. | ||
let mut retyped = face.clone(); | ||
retyped["mimeType"] = json!("image/png"); | ||
| @@ -182,6 +185,10 @@ async fn refuses_a_profile_it_should_not_keep() { | ||
riders(json!({"avatar": never})), | ||
riders(json!({"avatar": anothers})), | ||
riders(json!({"avatar": {"ref": "x"}})), | ||
// Icons that are not the group's own small PNGs, as it kept them. | ||
riders(json!({"links": [{"url": "https://riders.example", "icon": face}]})), | ||
riders(json!({"links": [{"url": "https://riders.example", "icon": wide}]})), | ||
riders(json!({"links": [{"url": "https://riders.example", "icon": anothers}]})), | ||
// Longer than the lexicon has them, or not of its format. | ||
riders(json!({"displayName": "x".repeat(65)})), | ||
riders(json!({"topics": [{"topic": "x".repeat(65)}]})), | ||
crates/group-host/tests/mcp.rs+22−1
| @@ -426,7 +426,8 @@ async fn acts_as_the_member_in_the_group_they_chose() { | ||
| ||
#[tokio::test] | ||
async fn writes_the_groups_profile_and_rules_as_the_group() { | ||
let h = start(&[], false).await; | ||
let favicons = common::start_favicons().await; | ||
let h = start(&[("FAVICONS", &favicons)], false).await; | ||
let [alice, ..] = people(&h).await; | ||
let group = start_group( | ||
&h, | ||
| @@ -459,6 +460,26 @@ async fn writes_the_groups_profile_and_rules_as_the_group() { | ||
assert!(got.get("isError").is_none(), "{got}"); | ||
want.as_object_mut().unwrap().remove("description"); | ||
assert_eq!(kept("profile", "self").unwrap(), want); | ||
// Its links, each new one with its site's icon, kept as the group's | ||
// own, where the site has a small PNG; written again, each keeps it. | ||
let links = json!([ | ||
{"url": "https://chat.riders.example", "title": "Our chat"}, | ||
{"url": "https://big.riders.example"}, | ||
{"url": "https://gif.riders.example"}, | ||
{"url": "https://riders.example"}, | ||
]); | ||
let got = tool(&h, access, "profile_set", json!({"links": links})).await; | ||
assert!(got.get("isError").is_none(), "{got}"); | ||
let written = kept("profile", "self").unwrap()["links"].clone(); | ||
let icon = &written[0]["icon"]; | ||
assert_eq!(icon["mimeType"], "image/png"); | ||
assert_eq!(icon["size"], common::FAVICON.len()); | ||
for at in 1..4 { | ||
assert_eq!(written[at].get("icon"), None, "{written}"); | ||
} | ||
let got = tool(&h, access, "profile_set", json!({"links": links})).await; | ||
assert!(got.get("isError").is_none(), "{got}"); | ||
assert_eq!(kept("profile", "self").unwrap()["links"], written); | ||
| ||
// A new rule, keyed by the clock; changed at its key; taken away. | ||
let got = tool( | ||
crates/group-host-mcp/src/lib.rs+72−1
| @@ -325,7 +325,7 @@ const TOOLS: &[(&str, &[&str], &str, Made)] = &[ | ||
"profile_set", | ||
&[], | ||
"Changes the group's profile as the group. Changes only the fields given, keeping the \ | ||
rest; a field given empty, or null, is taken away.", | ||
rest; a field given empty, or null, is taken away. A new link is given its site's icon.", | ||
Made::Edit("profile", META, "self"), | ||
), | ||
( | ||
| @@ -946,6 +946,77 @@ pub fn edited( | ||
} | ||
} | ||
| ||
/// Where a link's site's icon is asked unless another service is named: | ||
/// the link's address follows, encoded, and a PNG is answered. | ||
pub const FAVICONS: &str = "https://cardyb.bsky.app/v1/favicon?url="; | ||
| ||
/// The most bytes a link's icon may be, as its lexicon has it. | ||
pub const ICON_AT_MOST: usize = 100_000; | ||
| ||
/// The links of a profile `fields` gives, in the `collection` it is | ||
/// written to, that want their site's icon: each by where it is in the | ||
/// list, and the address its icon is asked at, of the favicon service at | ||
/// `favicons`. A link given with no icon, at an address the record `kept` | ||
/// has one for, is given that one instead, so a list written again keeps | ||
/// its icons. With no service, none are asked. | ||
pub fn iconless( | ||
collection: &str, | ||
kept: &Value, | ||
fields: &mut Map<String, Value>, | ||
favicons: &str, | ||
) -> Vec<(usize, String)> { | ||
if collection != format!("{NS}.profile") { | ||
return Vec::new(); | ||
} | ||
let had = kept["links"].as_array().into_iter().flatten(); | ||
let had: HashMap<&str, &Value> = had | ||
.filter_map(|l| Some((l["url"].as_str()?, l.get("icon")?))) | ||
.collect(); | ||
let mut wanted = Vec::new(); | ||
let links = fields.get_mut("links").and_then(Value::as_array_mut); | ||
for (at, link) in links.into_iter().flatten().enumerate() { | ||
let url = link["url"].as_str().unwrap_or_default().to_string(); | ||
if link.get("icon").is_some() || !link.is_object() { | ||
continue; | ||
} | ||
match had.get(url.as_str()) { | ||
Some(icon) => link["icon"] = (*icon).clone(), | ||
None if web(&url) && !favicons.is_empty() => { | ||
wanted.push((at, format!("{favicons}{}", encoded(&url)))) | ||
} | ||
None => {} | ||
} | ||
} | ||
wanted | ||
} | ||
| ||
/// `fields`' link at `at`, given the blob `icon`. | ||
pub fn iconed(fields: &mut Map<String, Value>, at: usize, icon: Value) { | ||
if let Some(link) = fields.get_mut("links").and_then(|l| l.get_mut(at)) { | ||
link["icon"] = icon; | ||
} | ||
} | ||
| ||
/// Whether `url` is an address on the web. | ||
fn web(url: &str) -> bool { | ||
url.starts_with("https://") || url.starts_with("http://") | ||
} | ||
| ||
/// `text` as it stands in a URL's query: each byte but a letter, a digit | ||
/// and `-._~` as `%` and its hex. | ||
fn encoded(text: &str) -> String { | ||
let mut out = String::new(); | ||
for b in text.bytes() { | ||
match b { | ||
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => { | ||
out.push(b as char) | ||
} | ||
_ => out.push_str(&format!("%{b:02X}")), | ||
} | ||
} | ||
out | ||
} | ||
| ||
fn error(id: &Value, code: i64, message: &str) -> Value { | ||
json!({"jsonrpc": "2.0", "id": id, "error": {"code": code, "message": message}}) | ||
} | ||
crates/group-host-mcp/tests/protocol.rs+50−1
| @@ -2,7 +2,8 @@ | ||
//! the server answers each message an MCP client sends. | ||
| ||
use group_host_mcp::{ | ||
Action, Key, PROTOCOL_VERSIONS, Plan, Tool, answer, camel, edited, plan, regrant, snake, tools, | ||
Action, FAVICONS, Key, PROTOCOL_VERSIONS, Plan, Tool, answer, camel, edited, iconed, iconless, | ||
plan, regrant, snake, tools, | ||
}; | ||
use serde_json::{Value, json}; | ||
| ||
| @@ -614,3 +615,51 @@ async fn refuses_what_is_not_a_request_it_knows() { | ||
-32602 | ||
); | ||
} | ||
| ||
#[test] | ||
fn asks_the_icon_of_each_new_link_once() { | ||
let profile = "fyi.opensocial.profile"; | ||
let icon = | ||
json!({"$type": "blob", "ref": {"$link": "bafkreia"}, "mimeType": "image/png", "size": 9}); | ||
let kept = json!({"links": [ | ||
{"url": "https://chat.example", "icon": icon}, | ||
{"url": "https://old.example"}, | ||
]}); | ||
let given = || { | ||
json!({"links": [ | ||
{"url": "https://chat.example", "title": "Our chat"}, | ||
{"url": "https://new.example/a b?c=d"}, | ||
{"url": "https://own.example", "icon": "its own"}, | ||
{"url": "ftp://files.example"}, | ||
"not a link", | ||
{"url": "https://old.example"}, | ||
]}) | ||
.as_object() | ||
.unwrap() | ||
.clone() | ||
}; | ||
// A link it had keeps its icon; one new to it, on the web, is asked | ||
// for, its address encoded; any other is left as given. | ||
let mut fields = given(); | ||
let wanted = iconless(profile, &kept, &mut fields, FAVICONS); | ||
let asked = format!("{FAVICONS}https%3A%2F%2Fnew.example%2Fa%20b%3Fc%3Dd"); | ||
let old = format!("{FAVICONS}https%3A%2F%2Fold.example"); | ||
assert_eq!(wanted, vec![(1, asked), (5, old)]); | ||
assert_eq!(fields["links"][0]["icon"], icon); | ||
assert_eq!(fields["links"][2]["icon"], "its own"); | ||
assert_eq!(fields["links"][3].get("icon"), None); | ||
// Given one, it holds it; at no link, nothing is. | ||
iconed(&mut fields, 1, json!("the icon")); | ||
iconed(&mut fields, 9, json!("nowhere")); | ||
assert_eq!(fields["links"][1]["icon"], "the icon"); | ||
assert_eq!(fields["links"].as_array().unwrap().len(), 6); | ||
// With no service, none is asked; nor of a record but a profile. | ||
assert_eq!(iconless(profile, &kept, &mut given(), ""), vec![]); | ||
let rule = "fyi.opensocial.rule"; | ||
assert_eq!(iconless(rule, &kept, &mut given(), FAVICONS), vec![]); | ||
// Nor of a profile with no links given. | ||
let mut none = json!({"description": "x"}).as_object().unwrap().clone(); | ||
assert_eq!(iconless(profile, &kept, &mut none, FAVICONS), vec![]); | ||
iconed(&mut none, 0, json!("nowhere")); | ||
assert_eq!(none.get("links"), None); | ||
} | ||
crates/opensocial/src/lib.rs+61−5
| @@ -124,6 +124,9 @@ pub struct Env { | ||
/// The password of an account `import` moves, at its own server, | ||
/// `OPENSOCIAL_IMPORT_PASSWORD`. | ||
pub import_password: Option<String>, | ||
/// Where a link's site's icon is asked, `FAVICONS`: the link's | ||
/// address follows, encoded. Empty asks nowhere. | ||
pub favicons: String, | ||
} | ||
| ||
/// The did:web a host at `url` is by default, as the host names itself. | ||
| @@ -150,6 +153,7 @@ impl Env { | ||
handle: var("OPENSOCIAL_AS"), | ||
password: var("OPENSOCIAL_PASSWORD"), | ||
import_password: var("OPENSOCIAL_IMPORT_PASSWORD"), | ||
favicons: var("FAVICONS").unwrap_or_else(|| group_host_mcp::FAVICONS.into()), | ||
seed_invite: invite | ||
.split(',') | ||
.map(str::trim) | ||
| @@ -160,11 +164,13 @@ impl Env { | ||
} | ||
} | ||
| ||
/// A host, by its address and DID. | ||
/// A host, by its address and DID; and where a link's site's icon is | ||
/// asked when a link is written to a group's profile there. | ||
#[derive(Debug, Clone)] | ||
pub struct Host { | ||
pub url: String, | ||
pub did: String, | ||
pub favicons: String, | ||
} | ||
| ||
/// A person signed in at their PDS. | ||
| @@ -406,13 +412,14 @@ impl<'a> GroupSession<'a> { | ||
token: Option<&str>, | ||
body: &Value, | ||
) -> Result<Value> { | ||
let mut res = self.post(nsid, authorization, token, body).await?; | ||
let json = Body::Json(body); | ||
let mut res = self.post(nsid, authorization, token, &json).await?; | ||
let stale = res | ||
.headers() | ||
.get("www-authenticate") | ||
.is_some_and(|v| v.to_str().unwrap_or_default().contains("use_dpop_nonce")); | ||
if stale { | ||
res = self.post(nsid, authorization, token, body).await?; | ||
res = self.post(nsid, authorization, token, &json).await?; | ||
} | ||
answer(res, nsid).await | ||
} | ||
| @@ -422,10 +429,16 @@ impl<'a> GroupSession<'a> { | ||
nsid: &str, | ||
authorization: &str, | ||
token: Option<&str>, | ||
body: &Value, | ||
body: &Body<'_>, | ||
) -> Result<reqwest::Response> { | ||
let url = format!("{}/xrpc/{nsid}", self.host.url); | ||
let asked = self.client.http.post(url).json(body); | ||
let asked = match body { | ||
Body::Json(body) => self.client.http.post(url).json(body), | ||
Body::Png(bytes) => { | ||
let asked = self.client.http.post(url).body(bytes.to_vec()); | ||
asked.header("content-type", "image/png") | ||
} | ||
}; | ||
let asked = asked.header("authorization", authorization); | ||
let sent = asked.header("dpop", self.proof(nsid, token)).send().await; | ||
let res = sent.context(format!("reaching {}", self.host.url))?; | ||
| @@ -441,6 +454,35 @@ impl<'a> GroupSession<'a> { | ||
let auth = format!("DPoP {}", self.token); | ||
self.send(nsid, &auth, Some(&self.token), body).await | ||
} | ||
| ||
/// `png` uploaded as the group's: the blob a record names it by. | ||
async fn upload(&self, png: &[u8]) -> Result<Value> { | ||
let nsid = "com.atproto.repo.uploadBlob"; | ||
let auth = format!("DPoP {}", self.token); | ||
let token = Some(self.token.as_str()); | ||
let res = self.post(nsid, &auth, token, &Body::Png(png)).await?; | ||
Ok(answer(res, nsid).await?["blob"].clone()) | ||
} | ||
} | ||
| ||
/// What a request to the host carries: JSON, or a PNG. | ||
enum Body<'a> { | ||
Json(&'a Value), | ||
Png(&'a [u8]), | ||
} | ||
| ||
/// How long a site's icon is waited for. | ||
const ICON_WAIT: std::time::Duration = std::time::Duration::from_secs(8); | ||
| ||
/// The icon the favicon service answers at `asked`: a PNG no larger than | ||
/// a link's icon may be, or none. | ||
async fn favicon(http: &reqwest::Client, asked: &str) -> Option<Vec<u8>> { | ||
let res = http.get(asked).timeout(ICON_WAIT).send().await.ok()?; | ||
let kind = res.headers().get("content-type").cloned(); | ||
let png = res.status().is_success() && kind.is_some_and(|k| k == "image/png"); | ||
let bytes = res.bytes().await.ok()?; | ||
let small = bytes.len() <= group_host_mcp::ICON_AT_MOST; | ||
(png && small).then(|| bytes.to_vec()) | ||
} | ||
| ||
/// The arguments after a command: its words, and its `--flag value`s. | ||
| @@ -558,6 +600,7 @@ pub async fn run(args: &[String], env: &Env) -> Result<String> { | ||
let host = Host { | ||
url: env.host.clone(), | ||
did: env.host_did.clone(), | ||
favicons: env.favicons.clone(), | ||
}; | ||
let words: Vec<&str> = args.iter().map(String::as_str).collect(); | ||
match words.as_slice() { | ||
| @@ -579,6 +622,7 @@ pub async fn run(args: &[String], env: &Env) -> Result<String> { | ||
let dest = Host { | ||
url: to.to_string(), | ||
did: did.unwrap_or_else(|| did_web(to)), | ||
favicons: env.favicons.clone(), | ||
}; | ||
migrate(&signed_in(env).await?, &host, &dest, group).await | ||
} | ||
| @@ -792,6 +836,18 @@ async fn carry_out(me: &Client, host: &Host, group: &str, plan: Plan) -> Result< | ||
let asked = [("group", group), ("space", &uri), ("uri", &record)]; | ||
let listed = me.query(host, &m("listSpaceRecords"), &asked).await?; | ||
let kept = listed["records"][0]["value"].clone(); | ||
// Each new link's site's icon, kept as the group's own. | ||
let mut fields = fields; | ||
let wanted = group_host_mcp::iconless(&collection, &kept, &mut fields, &host.favicons); | ||
if !wanted.is_empty() { | ||
let session = GroupSession::start(me, host, group, &uri).await?; | ||
for (at, asked) in wanted { | ||
let Some(png) = favicon(&me.http, &asked).await else { | ||
continue; | ||
}; | ||
group_host_mcp::iconed(&mut fields, at, session.upload(&png).await?); | ||
} | ||
} | ||
let write = group_host_mcp::edited(&kept, space, collection, rkey, fields); | ||
Box::pin(carry_out(me, host, group, write)).await | ||
} | ||
crates/opensocial/tests/commands.rs+40−0
| @@ -25,9 +25,35 @@ const INVITE: &str = "space:fyi.opensocial.invites?authority=*&collection=fyi.op | ||
struct Running { | ||
host: Arc<Host>, | ||
url: String, | ||
favicons: String, | ||
_data: TempDir, | ||
} | ||
| ||
/// The bytes the favicon service answers for a site whose name starts | ||
/// `chat.`. | ||
const FAVICON: &[u8] = b"\x89PNG a green dot"; | ||
| ||
/// A favicon service, as the command asks one: where it is, the link's | ||
/// address to follow. A site whose name starts `chat.` has `FAVICON`; | ||
/// any other none. | ||
async fn favicons() -> String { | ||
async fn icon( | ||
axum::extract::Query(q): axum::extract::Query<HashMap<String, String>>, | ||
) -> axum::response::Response { | ||
use axum::response::IntoResponse; | ||
let site = q.get("url").map(String::as_str).unwrap_or_default(); | ||
match site.starts_with("https://chat.") { | ||
true => ([("content-type", "image/png")], FAVICON).into_response(), | ||
false => axum::http::StatusCode::NOT_FOUND.into_response(), | ||
} | ||
} | ||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); | ||
let at = listener.local_addr().unwrap(); | ||
let router = axum::Router::new().route("/favicon", axum::routing::get(icon)); | ||
tokio::spawn(async move { axum::serve(listener, router).await.unwrap() }); | ||
format!("http://{at}/favicon?url=") | ||
} | ||
| ||
async fn host() -> Running { | ||
let n = net(); | ||
// By name, as the reference PDS takes a did:web of one, not of an | ||
| @@ -49,6 +75,7 @@ async fn host() -> Running { | ||
Running { | ||
host, | ||
url, | ||
favicons: favicons().await, | ||
_data: data, | ||
} | ||
} | ||
| @@ -63,6 +90,7 @@ fn env(h: &Running, who: usize) -> Env { | ||
("PDS_URL", n.pds.clone()), | ||
("OPENSOCIAL_AS", person.handle.clone()), | ||
("OPENSOCIAL_PASSWORD", person.password.clone()), | ||
("FAVICONS", h.favicons.clone()), | ||
( | ||
"OPENSOCIAL_SEED_INVITE", | ||
format!(" {} ,", n.accounts[1].handle), | ||
| @@ -336,6 +364,17 @@ async fn writes_the_groups_rules_roles_and_profile() { | ||
let written = kept(&meta, "profile", "self").unwrap(); | ||
assert_eq!(written.get("topics"), None); | ||
assert_eq!(written["description"], "Bikes"); | ||
// Its links, each new one with its site's icon where the site has | ||
// one, kept as the group's own; written again, each keeps it. | ||
let links = r#"[{"url": "https://chat.riders.example", "title": "Our chat"}, {"url": "https://riders.example"}]"#; | ||
let profile = ["profile", "set", group, "--links", links]; | ||
ok(&alice, &profile).await; | ||
let written = kept(&meta, "profile", "self").unwrap()["links"].clone(); | ||
assert_eq!(written[0]["icon"]["mimeType"], "image/png"); | ||
assert_eq!(written[0]["icon"]["size"], FAVICON.len()); | ||
assert_eq!(written[1].get("icon"), None); | ||
ok(&alice, &profile).await; | ||
assert_eq!(kept(&meta, "profile", "self").unwrap()["links"], written); | ||
| ||
// The queue; a label on an account, and taken back, in its history. | ||
let queue = said(&ok(&alice, &["mod", "list", group, "--status", "open"]).await); | ||
| @@ -405,6 +444,7 @@ async fn switches_a_group_off_and_on_and_deletes_it() { | ||
let at = HostAt { | ||
url: h.url.clone(), | ||
did: did_web(&h.url), | ||
favicons: String::new(), | ||
}; | ||
let key = Keypair::generate(Curve::K256).public().did_key(); | ||
let body = json!({"group": did, "key": key}); | ||