~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0

A host is named, given a logo and links to its operator's pages

Merged chadtmiller.com asked to merge into feature/branding from chadtmiller.com/group-host:branding/host
.changeset/host-branding.mdnew+7−0
@@ -0,0 +1,7 @@
---
default: minor
---
# A host's operator names it, and gives it a logo and links to their pages
`SERVICE_NAME`, `LOGO_URL`, `HOME_URL`, `PRIVACY_POLICY_URL`, `TERMS_OF_SERVICE_URL`, `SUPPORT_URL` and `CONTACT_EMAIL` say how the host shows itself. The console draws the name and logo in its header and its pages' titles, and links the operator's pages from its footer, reading them from the host by `org.atgrp.internal.getBrand`. The host serves its logo at `/img/host`, read as an app's logo is: only a PNG, JPEG, GIF or WebP image of at most 256 KiB. `describeServer` gives the privacy policy and terms of service as its `links`, and the email address as its `contact`. Unset, the console is Atmosphere Groups as before.
crates/group-host/src/api.rs+9−2
@@ -107,14 +107,21 @@ pub async fn check_address(State(host): State<Arc<Host>>, Query(p): Query<Params
Ok(Json(json!({ "address": address, "available": available })))
}
/// The host as a PDS describes itself: its DID, and the domain whose names
/// it gives its groups. Nobody signs up here: a group is made for someone.
/// The host as a PDS describes itself: its DID, the domain whose names it
/// gives its groups, and its operator's policies and address, as far as
/// set. Nobody signs up here: a group is made for someone.
pub async fn describe_server(State(host): State<Arc<Host>>) -> Json<Value> {
let b = &host.config.brand;
Json(json!({
"did": host.config.service_did,
"availableUserDomains": [host.config.handle_domain],
"inviteCodeRequired": true,
"blobUploadLimit": host.config.blob_upload_limit,
"links": crate::brand::set([
("privacyPolicy", &b.privacy_policy),
("termsOfService", &b.terms_of_service),
]),
"contact": crate::brand::set([("email", &b.contact_email)]),
}))
}
crates/group-host/src/apps.rs+37−15
@@ -130,18 +130,18 @@ impl Host {
/// whose metadata names no logo a page may show, or whose logo is no
/// image.
pub async fn logo(&self, id: &str, now: i64) -> Option<Logo> {
if let Some(kept) = self.logos.get(id, now) {
return kept;
}
let logo = self.read_logo(id, now).await;
tracing::info!(client = id, found = logo.is_some(), "read a logo");
self.logos.keep(id, now, logo.clone());
logo
kept(&self.logos, id, now, self.read_logo(id, now)).await
}
async fn read_logo(&self, id: &str, now: i64) -> Option<Logo> {
let view = self.client_view(id, now).await?;
let asked = self.guarded.get(view["logo"].as_str()?).ok()?;
self.read_image(view["logo"].as_str()?).await
}
/// The image at `url`, read as a logo is: from a public address, at
/// most [`LOGO_AT_MOST`] bytes, and only an image by its first bytes.
pub(crate) async fn read_image(&self, url: &str) -> Option<Logo> {
let asked = self.guarded.get(url).ok()?;
let res = asked.send().await.ok()?;
let res = res.error_for_status().ok()?;
let bytes = capped(res, LOGO_AT_MOST).await?;
@@ -153,13 +153,25 @@ impl Host {
}
}
/// The logo of the app `?id=` names, for a page to draw: nothing for one
/// the host does not serve.
pub async fn logo(State(host): State<Arc<Host>>, Query(p): Query<Params>) -> Response {
let id = p.get("id").map(String::as_str).unwrap_or_default();
let Some(logo) = host.logo(id, now_millis()).await else {
return StatusCode::NOT_FOUND.into_response();
};
/// The logo `logos` keeps under `key`, or else the one `read` reads, kept
/// for next time either way.
pub(crate) async fn kept(
logos: &Logos,
key: &str,
now: i64,
read: impl Future<Output = Option<Logo>>,
) -> Option<Logo> {
if let Some(kept) = logos.get(key, now) {
return kept;
}
let logo = read.await;
tracing::info!(of = key, found = logo.is_some(), "read a logo");
logos.keep(key, now, logo.clone());
logo
}
/// A logo as a page is to draw it: as an image, and nothing more.
pub(crate) fn served(logo: Logo) -> Response {
let headers = [
(header::CONTENT_TYPE, logo.kind),
(header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
@@ -171,3 +183,13 @@ pub async fn logo(State(host): State<Arc<Host>>, Query(p): Query<Params>) -> Res
];
(headers, logo.bytes).into_response()
}
/// The logo of the app `?id=` names, for a page to draw: nothing for one
/// the host does not serve.
pub async fn logo(State(host): State<Arc<Host>>, Query(p): Query<Params>) -> Response {
let id = p.get("id").map(String::as_str).unwrap_or_default();
match host.logo(id, now_millis()).await {
Some(logo) => served(logo),
None => StatusCode::NOT_FOUND.into_response(),
}
}
crates/group-host/src/brand.rsnew+53−0
@@ -0,0 +1,53 @@
//! How the host shows itself, as its operator names it (`config::Brand`):
//! its name, logo and pages, for the console to draw (`getBrand`), and its
//! logo served from here, at `/img/host`, read as an app's logo is
//! (`apps`), so that a reader's browser asks no other server for it.
use crate::Host;
use crate::apps::{Logo, kept, served};
use crate::time::now_millis;
use axum::Json;
use axum::extract::State;
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use serde_json::{Map, Value, json};
use std::sync::Arc;
/// The fields of `fields` that are set, as an object.
pub(crate) fn set<const N: usize>(fields: [(&str, &Option<String>); N]) -> Value {
let set = fields
.into_iter()
.filter_map(|(k, v)| Some((k.to_string(), json!(v.as_ref()?))));
Value::Object(set.collect::<Map<_, _>>())
}
/// How the host shows itself: its name and logo, and the links to its
/// operator's pages, each only when set.
pub async fn get_brand(State(host): State<Arc<Host>>) -> Json<Value> {
let b = &host.config.brand;
let mut brand = set([("name", &b.name), ("logo", &b.logo)]);
brand["links"] = set([
("home", &b.home),
("privacyPolicy", &b.privacy_policy),
("termsOfService", &b.terms_of_service),
("support", &b.support),
]);
Json(brand)
}
impl Host {
/// The host's logo, kept or read now: none when it names none, or
/// when what it names is no image.
pub async fn host_logo(&self, now: i64) -> Option<Logo> {
let url = self.config.brand.logo.as_deref()?;
kept(&self.host_logo, url, now, self.read_image(url)).await
}
}
/// The host's logo, for a page to draw: nothing when it has none.
pub async fn logo(State(host): State<Arc<Host>>) -> Response {
match host.host_logo(now_millis()).await {
Some(logo) => served(logo),
None => StatusCode::NOT_FOUND.into_response(),
}
}
crates/group-host/src/config.rs+64−0
@@ -84,6 +84,68 @@ pub struct Config {
/// Whether it limits how much one caller asks, `RATE_LIMITS`: `on`,
/// unless `off` (`limits`).
pub rate_limits: bool,
/// How it shows itself to people: its name, logo and pages.
pub brand: Brand,
}
/// How the host shows itself on its pages, as its operator names it: none
/// of it set, the console's own name, and no logo or links.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Brand {
/// Its name, `SERVICE_NAME`, at most [`NAME_AT_MOST`] characters.
pub name: Option<String>,
/// Its logo, `LOGO_URL`, which it serves at `/img/host`.
pub logo: Option<String>,
/// Its operator's home page, `HOME_URL`.
pub home: Option<String>,
/// Its privacy policy, `PRIVACY_POLICY_URL`.
pub privacy_policy: Option<String>,
/// Its terms of service, `TERMS_OF_SERVICE_URL`.
pub terms_of_service: Option<String>,
/// Where people get help, `SUPPORT_URL`.
pub support: Option<String>,
/// Where its operator is written to, `CONTACT_EMAIL`.
pub contact_email: Option<String>,
}
/// The most characters a host's name may be, as a page's header has room for.
pub const NAME_AT_MOST: usize = 40;
impl Brand {
/// The brand `var` names, each variable left empty as unset.
fn from(var: &impl Fn(&str) -> Option<String>) -> Result<Brand> {
let set = |name: &str| {
var(name)
.map(|v| v.trim().to_string())
.filter(|v| !v.is_empty())
};
let page = |name: &str| -> Result<Option<String>> {
let Some(url) = set(name) else {
return Ok(None);
};
match reqwest::Url::parse(&url) {
Ok(u) if ["https", "http"].contains(&u.scheme()) => Ok(Some(url)),
_ => bail!("{name} is no http or https URL: {url}"),
}
};
let name = set("SERVICE_NAME");
if let Some(n) = name.as_ref().filter(|n| n.chars().count() > NAME_AT_MOST) {
bail!("SERVICE_NAME is at most {NAME_AT_MOST} characters: {n}");
}
let contact_email = set("CONTACT_EMAIL");
if let Some(e) = contact_email.as_ref().filter(|e| !e.contains('@')) {
bail!("CONTACT_EMAIL is no email address: {e}");
}
Ok(Brand {
name,
logo: page("LOGO_URL")?,
home: page("HOME_URL")?,
privacy_policy: page("PRIVACY_POLICY_URL")?,
terms_of_service: page("TERMS_OF_SERVICE_URL")?,
support: page("SUPPORT_URL")?,
contact_email,
})
}
}
/// The service that finds anyone on the network by what is typed.
@@ -203,6 +265,7 @@ impl Config {
Some("off") => false,
Some(other) => bail!("RATE_LIMITS is on or off, not {other}"),
};
let brand = Brand::from(&var)?;
Ok(Config {
port,
public_url,
@@ -225,6 +288,7 @@ impl Config {
logs_keep,
domain_check_at,
rate_limits,
brand,
})
}
crates/group-host/src/lexicons.rs+1−0
@@ -79,6 +79,7 @@ pub const FILES: &[&str] = &[
lexicon!("org/atgrp/internal/getActorGroups"),
lexicon!("org/atgrp/internal/getActorInvites"),
lexicon!("org/atgrp/internal/getAuthorization"),
lexicon!("org/atgrp/internal/getBrand"),
lexicon!("org/atgrp/internal/getGroup"),
lexicon!("org/atgrp/internal/getGroupAuth"),
lexicon!("org/atgrp/internal/getJoinRequest"),
crates/group-host/src/lib.rs+6−0
@@ -14,6 +14,7 @@ pub mod authority;
pub mod authority_api;
pub mod authorization;
pub mod blobs;
pub mod brand;
pub mod config;
pub mod console_login;
pub mod firehose;
@@ -109,6 +110,8 @@ pub struct Host {
pub(crate) lexicons: permission_sets::Read,
/// Apps' logos, as read.
pub(crate) logos: apps::Logos,
/// Its own logo, as read.
pub(crate) host_logo: apps::Logos,
/// The lines it logged, kept for its operators.
pub logs: Arc<logs::Logs>,
/// How it is used, counted for its operators.
@@ -156,6 +159,7 @@ impl Host {
handles: Default::default(),
lexicons: Default::default(),
logos: Default::default(),
host_logo: Default::default(),
logs: Arc::new(logs),
stats,
limits,
@@ -383,6 +387,7 @@ pub(crate) fn routes(host: Arc<Host>) -> Router {
"/xrpc/org.atgrp.internal.getViewer",
get(actors::get_viewer),
)
.route("/xrpc/org.atgrp.internal.getBrand", get(brand::get_brand))
.route("/xrpc/org.atgrp.internal.getActor", get(actors::get_actor))
.route(
"/xrpc/org.atgrp.internal.getActorGroups",
@@ -480,6 +485,7 @@ pub(crate) fn routes(host: Arc<Host>) -> Router {
get(console_login::client_metadata),
)
.route("/img/app", get(apps::logo))
.route("/img/host", get(brand::logo))
.route("/img/{did}/{cid}", get(blobs::image))
.route("/console/login", get(console_login::login))
.route("/console/move/login", get(account_move::login))
crates/group-host/tests/brand.rsnew+129−0
@@ -0,0 +1,129 @@
//! How the host shows itself: its name, logo and pages as its operator
//! names them, for the console (`getBrand`) and as a PDS describes itself
//! (`describeServer`), and its logo served from here (`/img/host`).
mod common;
use axum::Router;
use axum::http::{StatusCode, header};
use axum::routing::get;
use common::{Running, serve, start, start_reachable};
use serde_json::json;
use std::sync::{Arc, Mutex};
const PNG: &[u8] = b"\x89PNG\r\n\x1a\n\0\0\0\rIHDR";
/// What `/img/host` answers: its status and bytes.
async fn host_logo(h: &Running) -> (u16, Vec<u8>) {
let res = h.http.get(format!("{}/img/host", h.url)).send().await;
let res = res.unwrap();
(res.status().as_u16(), res.bytes().await.unwrap().to_vec())
}
#[tokio::test]
async fn a_host_named_nothing_shows_the_consoles_own() {
let h = start(&[], false).await;
let (status, brand) = h.get("org.atgrp.internal.getBrand", "").await;
assert_eq!(status, 200, "{brand}");
assert_eq!(brand, json!({"links": {}}));
let (status, described) = h.get("com.atproto.server.describeServer", "").await;
assert_eq!(status, 200, "{described}");
assert_eq!(described["links"], json!({}));
assert_eq!(described["contact"], json!({}));
assert_eq!(host_logo(&h).await.0, 404);
}
#[tokio::test]
async fn a_host_shows_its_operators_name_logo_and_pages() {
// The operator's server, whose logo can change under it.
let logo = Arc::new(Mutex::new(PNG.to_vec()));
let served = logo.clone();
let router = Router::new()
.route(
"/logo.png",
get(move || {
let bytes = served.lock().unwrap().clone();
async move { bytes }
}),
)
.route(
"/logo.svg",
get(|| async { "<svg xmlns='http://www.w3.org/2000/svg'/>" }),
)
.route("/gone.png", get(|| async { StatusCode::NOT_FOUND }));
let site = serve(router).await;
let logo_url = format!("{site}/logo.png");
// A host on http, which reads others at any address, as a test's are.
let h = start_reachable(&[
("SERVICE_NAME", "Riverside Groups"),
("LOGO_URL", &logo_url),
("HOME_URL", "https://riverside.example"),
("PRIVACY_POLICY_URL", "https://riverside.example/privacy"),
("TERMS_OF_SERVICE_URL", "https://riverside.example/terms"),
("SUPPORT_URL", "https://riverside.example/help"),
("CONTACT_EMAIL", "hello@riverside.example"),
])
.await;
let (status, brand) = h.get("org.atgrp.internal.getBrand", "").await;
assert_eq!(status, 200, "{brand}");
assert_eq!(
brand,
json!({
"name": "Riverside Groups",
"logo": logo_url,
"links": {
"home": "https://riverside.example",
"privacyPolicy": "https://riverside.example/privacy",
"termsOfService": "https://riverside.example/terms",
"support": "https://riverside.example/help",
},
})
);
// As a PDS says it: its policies, and where its operator is written to.
let (_, described) = h.get("com.atproto.server.describeServer", "").await;
assert_eq!(
described["links"],
json!({
"privacyPolicy": "https://riverside.example/privacy",
"termsOfService": "https://riverside.example/terms",
})
);
assert_eq!(
described["contact"],
json!({"email": "hello@riverside.example"})
);
// Its logo, served from here as an image and nothing more.
let res = h.http.get(format!("{}/img/host", h.url)).send().await;
let res = res.unwrap();
assert_eq!(res.status(), 200);
for (name, value) in [
(header::CONTENT_TYPE, "image/png"),
(header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
(
header::CONTENT_SECURITY_POLICY,
"default-src 'none'; sandbox",
),
(header::CACHE_CONTROL, "private, max-age=600"),
] {
assert_eq!(res.headers()[&name], value, "{name}");
}
assert_eq!(res.bytes().await.unwrap(), PNG);
// Kept as read: a logo changed on its server shows once the kept one
// is old, not before.
*logo.lock().unwrap() = b"no image".to_vec();
assert_eq!(host_logo(&h).await, (200, PNG.to_vec()));
// A logo that is no image, or can't be read, is not served.
for path in ["logo.svg", "gone.png"] {
let url = format!("{site}/{path}");
let h = start_reachable(&[("LOGO_URL", &url)]).await;
assert_eq!(host_logo(&h).await.0, 404, "{path}");
}
// Nor is one at a private address, for a host on https.
let h = start(&[("LOGO_URL", &logo_url)], false).await;
assert_eq!(host_logo(&h).await.0, 404);
}
crates/group-host/tests/config.rs+52−1
@@ -1,6 +1,6 @@
//! The config the environment gives, and what it refuses.
use group_host::config::Config;
use group_host::config::{Brand, Config};
use std::collections::HashMap;
fn config(vars: &[(&str, &str)]) -> anyhow::Result<Config> {
@@ -183,3 +183,54 @@ fn rate_limits_are_on_unless_turned_off() {
let refused = config(&[("RATE_LIMITS", "maybe")]).unwrap_err();
assert_eq!(refused.to_string(), "RATE_LIMITS is on or off, not maybe");
}
#[test]
fn the_host_shows_itself_as_its_operator_names_it() {
// Nothing set, and nothing written but spaces, is the console's own.
assert_eq!(config(&[]).unwrap().brand, Brand::default());
let blank = config(&[("SERVICE_NAME", " "), ("LOGO_URL", "")]).unwrap();
assert_eq!(blank.brand, Brand::default());
let c = config(&[
("SERVICE_NAME", " Riverside Groups "),
("LOGO_URL", "https://riverside.example/logo.png"),
("HOME_URL", "https://riverside.example"),
("PRIVACY_POLICY_URL", "https://riverside.example/privacy"),
("TERMS_OF_SERVICE_URL", "https://riverside.example/terms"),
("SUPPORT_URL", "http://help.riverside.test"),
("CONTACT_EMAIL", "hello@riverside.example"),
])
.unwrap();
let some = |s: &str| Some(s.to_string());
assert_eq!(
c.brand,
Brand {
name: some("Riverside Groups"),
logo: some("https://riverside.example/logo.png"),
home: some("https://riverside.example"),
privacy_policy: some("https://riverside.example/privacy"),
terms_of_service: some("https://riverside.example/terms"),
support: some("http://help.riverside.test"),
contact_email: some("hello@riverside.example"),
}
);
let err = |vars: &[(&str, &str)]| config(vars).unwrap_err().to_string();
let long = "A name longer than any header has room for";
assert_eq!(
err(&[("SERVICE_NAME", long)]),
format!("SERVICE_NAME is at most 40 characters: {long}")
);
assert_eq!(
err(&[("LOGO_URL", "logo.png")]),
"LOGO_URL is no http or https URL: logo.png"
);
assert_eq!(
err(&[("SUPPORT_URL", "mailto:help@riverside.example")]),
"SUPPORT_URL is no http or https URL: mailto:help@riverside.example"
);
assert_eq!(
err(&[("CONTACT_EMAIL", "riverside.example")]),
"CONTACT_EMAIL is no email address: riverside.example"
);
}
deploy/docker-compose.yml+9−0
@@ -43,6 +43,15 @@ services:
HOST_ADMINS: ${GROUP_HOST_ADMINS:-}
LOGS_KEEP: ${GROUP_HOST_LOGS_KEEP:-500000}
RATE_LIMITS: ${GROUP_HOST_RATE_LIMITS:-on}
# How the host shows itself; empty, the console's own name and no
# logo or links.
SERVICE_NAME: ${GROUP_HOST_SERVICE_NAME:-}
LOGO_URL: ${GROUP_HOST_LOGO_URL:-}
HOME_URL: ${GROUP_HOST_HOME_URL:-}
PRIVACY_POLICY_URL: ${GROUP_HOST_PRIVACY_POLICY_URL:-}
TERMS_OF_SERVICE_URL: ${GROUP_HOST_TERMS_OF_SERVICE_URL:-}
SUPPORT_URL: ${GROUP_HOST_SUPPORT_URL:-}
CONTACT_EMAIL: ${GROUP_HOST_CONTACT_EMAIL:-}
volumes:
# The database, blobs and keys: back it up (docs/deploying.md).
# Owned by uid 1000, the node user the image runs as.
docs/reference/api.md+3−1
docs/reference/config.md+18−2
docs/deploying.md+1−0
lexicons/org/atgrp/internal/getBrand.jsonnew+64−0
web/messages/en.json+15−14
web/src/lib/atoms/Title.sveltenew+10−0
web/src/lib/organisms/SiteFooter.svelte+16−3
web/src/lib/organisms/SiteHeader.svelte+12−3
web/src/lib/brand.tsnew+24−0
web/src/routes/authorize/+page.svelte+2−1
web/src/routes/g/[handle]/moderation/+page.svelte+2−3
web/src/routes/g/[handle]/settings/apps/+page.svelte+2−4
web/src/routes/g/[handle]/settings/labels/+page.svelte+2−4
web/src/routes/g/[handle]/settings/recovery/+page.svelte+2−4
web/src/routes/g/[handle]/settings/roles/+page.svelte+2−4
web/src/routes/g/[handle]/settings/rules/+page.svelte+2−4
web/src/routes/g/[handle]/settings/+page.svelte+2−3
web/src/routes/g/[handle]/+page.svelte+2−1
web/src/routes/move/+page.svelte+2−1
web/src/routes/new/+page.svelte+2−1
web/src/routes/+error.svelte+2−1
web/src/routes/+layout.svelte+2−1
web/src/routes/+layout.ts+11−5
web/src/routes/+page.svelte+3−2
web/src/app.css+34−3
web/src/app.d.ts+8−1
web/src/tokens.css+2−0