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

A group's site moves to its own domain once that domain reaches the host

Merged chadtmiller.com asked to merge into main from chadtmiller.com/group-host:sites/own-domain
crates/group-host/src/config.rs+8−0
@@ -73,6 +73,12 @@ pub struct Config {
/// `SITE_HANDLE_RESOLVER`: a service answering
/// `com.atproto.identity.resolveHandle`. Bluesky's unless set.
pub site_handle_resolver: String,
/// Where the host asks a group's own domain whether it reaches this
/// host, before serving the group's site there, `SITE_CHECK_AT`: a URL
/// asked in the domain's place, with the domain as its `Host` (a proxy
/// in front that the host can't reach at its public addresses). Unset,
/// the domain itself, over https.
pub site_check_at: Option<String>,
}
/// The service that finds anyone on the network by what is typed.
@@ -169,6 +175,7 @@ impl Config {
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());
let site_check_at = var("SITE_CHECK_AT").map(|u| u.trim_end_matches('/').to_string());
Ok(Config {
port,
public_url,
@@ -190,6 +197,7 @@ impl Config {
logs_keep,
site_shell,
site_handle_resolver,
site_check_at,
})
}
crates/group-host/src/group_api.rs+7−2
@@ -165,13 +165,18 @@ fn rules(host: &Host, group: &str) -> Result<Vec<Value>, XrpcError> {
fn base(host: &Host, did: &str, handle: &str) -> Result<Value, XrpcError> {
let address = host.store.address(did).map_err(XrpcError::internal)?;
Ok(json!({
let mut view = json!({
"did": did,
"handle": handle,
"address": address,
"meta": meta_space(did),
"members": members_space(did),
}))
});
let domain = host.store.site_domain(did).map_err(XrpcError::internal)?;
if let Some(domain) = domain {
view["siteDomain"] = json!(domain);
}
Ok(view)
}
fn merge(into: &mut Value, from: Value) {
crates/group-host/src/group_handle.rs+5−0
@@ -14,6 +14,7 @@ use crate::group_api::{group_of, signed_in};
use crate::group_config::forbidden;
use crate::rbac::NS;
use crate::repo::identity;
use crate::time::now_millis;
use crate::xrpc::XrpcError;
use atproto::plc::Signed;
use atproto::syntax;
@@ -153,6 +154,10 @@ pub async fn update_group_handle(
.store
.set_handle(group, &handle, &[identity(group, &handle)]);
set.map_err(XrpcError::internal)?;
// The site was served at the old handle's domain, checked to reach
// here; the new one isn't, so the site goes back to the address.
let unsite = host.store.set_site_domain(group, None, now_millis());
unsite.map_err(XrpcError::internal)?;
host.announce();
Ok(Json(json!({ "handle": handle })))
}
crates/group-host/src/lexicons.rs+2−0
@@ -54,6 +54,7 @@ pub const FILES: &[&str] = &[
lexicon!("fyi/opensocial/deleteGroup"),
lexicon!("fyi/opensocial/deleteLabelDefinition"),
lexicon!("fyi/opensocial/deleteSite"),
lexicon!("fyi/opensocial/deleteSiteDomain"),
lexicon!("fyi/opensocial/deleteSpace"),
lexicon!("fyi/opensocial/denyJoinRequest"),
lexicon!("fyi/opensocial/finishAccountMove"),
@@ -102,6 +103,7 @@ pub const FILES: &[&str] = &[
lexicon!("fyi/opensocial/provisionGroup"),
lexicon!("fyi/opensocial/putLabelDefinition"),
lexicon!("fyi/opensocial/putSite"),
lexicon!("fyi/opensocial/putSiteDomain"),
lexicon!("fyi/opensocial/removeRecoveryKey"),
lexicon!("fyi/opensocial/requestJoin"),
lexicon!("fyi/opensocial/resolveSubject"),
crates/group-host/src/lib.rs+10−0
@@ -53,6 +53,7 @@ pub mod recovery;
pub mod repo;
pub mod scopes;
pub mod secrets;
pub mod site_domain;
pub mod site_head;
pub mod sites;
pub mod space;
@@ -472,6 +473,15 @@ pub(crate) fn routes(host: Arc<Host>) -> Router {
post(sites::put_site).layer(axum::extract::DefaultBodyLimit::max(site_limit)),
)
.route("/xrpc/fyi.opensocial.deleteSite", post(sites::delete_site))
.route(
"/xrpc/fyi.opensocial.putSiteDomain",
post(site_domain::put_site_domain),
)
.route(
"/xrpc/fyi.opensocial.deleteSiteDomain",
post(site_domain::delete_site_domain),
)
.route("/tls/ask", get(site_domain::tls_ask))
.route("/.well-known/did.json", get(api::did_json))
.route("/.well-known/atproto-did", get(api::atproto_did))
.route("/xrpc/{nsid}", get(not_implemented).post(not_implemented))
crates/group-host/src/site_domain.rsnew+127−0
@@ -0,0 +1,127 @@
//! A group's site at its own domain: the domain of its handle, once the
//! group takes one ([`crate::group_handle`]).
//!
//! The handle proves the group controls the domain, not that the domain's
//! web traffic reaches this host: its A record may still name an old site.
//! So the site moves there only when a steward switches it on, and only if
//! the domain answers as this host then. Once on, the domain serves the
//! site, `www.` under it and the address redirect to it, and the address
//! keeps the host's own paths. Switched off, or the handle changed, the
//! site is at its address alone again.
//!
//! A proxy in front issues the domain's certificate as it is first asked
//! for, asking [`tls_ask`] first, so nobody can point DNS at the host and
//! spend its certificate limits.
use crate::Host;
use crate::identity::LOOKUP;
use crate::sites::configuring;
use crate::time::now_millis;
use crate::xrpc::XrpcError;
use axum::Json;
use axum::extract::{Query, State};
use axum::http::{HeaderMap, StatusCode, header};
use serde_json::{Value, json};
use std::collections::HashMap;
use std::sync::Arc;
type Answer = Result<Json<Value>, XrpcError>;
fn bad(error: &'static str, message: String) -> XrpcError {
XrpcError::new(StatusCode::BAD_REQUEST, error, message)
}
impl Host {
/// The domain of `group`'s handle, when it is one of its own and not
/// its address here.
fn own_domain(&self, group: &str) -> Result<Option<String>, XrpcError> {
let account = self.store.account(group).map_err(XrpcError::internal)?;
let address = self.store.address(group).map_err(XrpcError::internal)?;
Ok(account
.map(|a| a.handle)
.filter(|h| Some(h) != address.as_ref()))
}
/// Whether `domain` answers as this host: its `describeServer` naming
/// this host's DID. Asked at the domain over https, or at
/// `SITE_CHECK_AT` with the domain as its `Host`.
async fn reaches(&self, domain: &str) -> bool {
let base = match &self.config.site_check_at {
Some(at) => at.clone(),
None => format!("https://{domain}"),
};
let url = format!("{base}/xrpc/com.atproto.server.describeServer");
let asked = self
.http
.get(url)
.header(header::HOST, domain)
.timeout(LOOKUP);
let Ok(answer) = asked.send().await else {
return false;
};
let said: Value = answer.json().await.unwrap_or_default();
said["did"] == self.config.service_did.as_str()
}
}
/// Serves the group's site at its handle's own domain, once that domain
/// reaches this host.
pub async fn put_site_domain(
State(host): State<Arc<Host>>,
headers: HeaderMap,
Json(body): Json<Value>,
) -> Answer {
let group = configuring(&host, &headers, &body, "putSiteDomain").await?;
host.active(&group)?;
let Some(domain) = host.own_domain(&group)? else {
let why = "the group's handle is its address: take a handle on a domain of its own first";
return Err(bad("NoOwnDomain", why.into()));
};
if !host.reaches(&domain).await {
let why = format!(
"{domain} doesn't reach this host yet: point its A and AAAA records at this host's addresses, then try again"
);
return Err(bad("NotReaching", why));
}
let set = host
.store
.set_site_domain(&group, Some(&domain), now_millis());
set.map_err(XrpcError::internal)?;
Ok(Json(json!({ "domain": domain })))
}
/// Serves the group's site at its address alone again.
pub async fn delete_site_domain(
State(host): State<Arc<Host>>,
headers: HeaderMap,
Json(body): Json<Value>,
) -> Answer {
let group = configuring(&host, &headers, &body, "deleteSiteDomain").await?;
let set = host.store.set_site_domain(&group, None, now_millis());
set.map_err(XrpcError::internal)?;
Ok(Json(json!({})))
}
/// Whether a proxy in front may get a certificate for `domain`: the own
/// domain of a group that is on, or `www.` under it, whether or not its
/// site is there yet, so that the host can check the domain reaches it.
pub async fn tls_ask(
State(host): State<Arc<Host>>,
Query(p): Query<HashMap<String, String>>,
) -> StatusCode {
let asked = p.get("domain").map(|d| d.to_ascii_lowercase());
let asked = asked.unwrap_or_default();
let domain = asked.strip_prefix("www.").unwrap_or(&asked);
let account = host.store.account(domain).ok().flatten();
let group = account.filter(|a| a.handle == domain).map(|a| a.did);
let ours = group.filter(|g| {
host.own_domain(g)
.ok()
.flatten()
.is_some_and(|d| d == domain)
});
match ours.filter(|g| host.active(g).is_ok()) {
Some(_) => StatusCode::OK,
None => StatusCode::NOT_FOUND,
}
}
crates/group-host/src/sites.rs+51−11
@@ -236,10 +236,20 @@ fn moved(to: &str, status: StatusCode) -> Response {
(status, [(header::LOCATION, to)]).into_response()
}
/// Where a request to a name finds a group's site.
enum SiteAt {
/// Here: the group, and its handle.
Here(String, String),
/// At this domain instead, the group's own.
There(String),
}
impl Host {
/// The group whose address a request to `name` names, and its handle,
/// unless `name` is the host's own.
fn site_of(&self, name: &str) -> Option<(String, String)> {
/// Where a request to `name` finds a group's site: the group whose
/// address or own domain it is, or the domain its site is served at
/// instead (from its address, or `www.` under that domain); nothing if
/// `name` is the host's own or no group's.
fn site_of(&self, name: &str) -> Option<SiteAt> {
let name = name
.split(':')
.next()
@@ -254,9 +264,22 @@ impl Host {
if name.is_empty() || name == own.split(':').next().unwrap_or_default() {
return None;
}
let did = self.store.addressed(&name).ok().flatten()?;
let account = self.store.account(&did).ok().flatten()?;
Some((account.did, account.handle))
let here = |did: String| {
let account = self.store.account(&did).ok().flatten()?;
Some(SiteAt::Here(account.did, account.handle))
};
if let Some(did) = self.store.addressed(&name).ok().flatten() {
return match self.store.site_domain(&did).ok().flatten() {
Some(domain) => Some(SiteAt::There(domain)),
None => here(did),
};
}
if let Some(did) = self.store.sited(&name).ok().flatten() {
return here(did);
}
let apex = name.strip_prefix("www.")?;
self.store.sited(apex).ok().flatten()?;
Some(SiteAt::There(apex.to_string()))
}
/// The file of `did`'s site at `path`: its type and bytes, and its ETag.
@@ -389,8 +412,9 @@ fn file(
(status, headers, [(header::CONTENT_TYPE, kind)], bytes).into_response()
}
/// Answers a request to a group's handle from its site, but for the
/// host's own paths under `/.well-known/`; passes on any other.
/// Answers a request to a group's address or own domain from its site,
/// but for the host's own paths under `/.well-known/` and `/xrpc/`, or
/// redirects it to where the site is; passes on any other.
pub async fn serve(State(host): State<Arc<Host>>, req: Request, next: Next) -> Response {
let named = req
.headers()
@@ -401,9 +425,17 @@ pub async fn serve(State(host): State<Arc<Host>>, req: Request, next: Next) -> R
// 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 {
let (Some(at), false) = (group, ours) else {
return next.run(req).await;
};
let (did, handle) = match at {
SiteAt::Here(did, handle) => (did, handle),
SiteAt::There(domain) => {
let asked = req.uri().path_and_query().map_or("/", |p| p.as_str());
let to = format!("https://{domain}{asked}");
return sandboxed(moved(&to, StatusCode::MOVED_PERMANENTLY));
}
};
if ![Method::GET, Method::HEAD].contains(req.method()) {
let mut res = plain(StatusCode::METHOD_NOT_ALLOWED, "a site is only read");
res.headers_mut()
@@ -568,7 +600,7 @@ fn shell(host: &Host, did: &str, handle: &str, site: &Value, path: &str) -> Resp
type Answer = Result<Json<Value>, XrpcError>;
/// The group a body names, once its caller of `lxm` may configure it.
async fn configuring(
pub(crate) async fn configuring(
host: &Host,
headers: &HeaderMap,
body: &Value,
@@ -659,10 +691,18 @@ pub async fn put_site(
.split("://")
.next()
.unwrap_or("https");
let domain = host
.store
.site_domain(&group)
.map_err(XrpcError::internal)?;
let url = match domain {
Some(domain) => format!("https://{domain}/"),
None => format!("{scheme}://{address}/"),
};
Ok(Json(json!({
"uri": format!("at://{group}/{SITE}/self"),
"cid": record_cid(SITE, &site)?.to_string(),
"url": format!("{scheme}://{address}/"),
"url": url,
"uploaded": uploaded,
})))
}
crates/group-host/src/store.rs+38−0
@@ -426,6 +426,15 @@ pub const MIGRATIONS: &[&str] = &[
// here were kept in milliseconds.
"
UPDATE account SET created_at = created_at / 1000 WHERE created_at > 100000000000;
",
// A group's site served at its handle's own domain, switched on by a
// steward once the domain reaches the host; only while the handle is it.
"
CREATE TABLE IF NOT EXISTS site_domain (
did TEXT PRIMARY KEY REFERENCES account (did),
domain TEXT NOT NULL UNIQUE,
at INTEGER NOT NULL
);
",
];
@@ -562,6 +571,7 @@ const FORGET_ACCOUNT: &[&str] = &[
"DELETE FROM index_record WHERE space IN (SELECT uri FROM space WHERE authority = ?1)",
"DELETE FROM index_repo WHERE space IN (SELECT uri FROM space WHERE authority = ?1)",
"DELETE FROM deactivation WHERE did = ?1",
"DELETE FROM site_domain WHERE did = ?1",
"DELETE FROM address WHERE did = ?1",
"DELETE FROM outbox WHERE repo = ?1",
"DELETE FROM space_recipient WHERE space IN (SELECT uri FROM space WHERE authority = ?1)",
@@ -1831,6 +1841,34 @@ impl Store {
Ok(found.optional()?)
}
/// The domain `did`'s site is served at, while its handle is still it.
pub fn site_domain(&self, did: &str) -> Result<Option<String>> {
let sql = "SELECT s.domain FROM site_domain s JOIN account a ON a.did = s.did AND a.handle = s.domain WHERE s.did = ?1";
let found = self.conn().query_row(sql, [did], |r| r.get(0));
Ok(found.optional()?)
}
/// The group whose site is served at `domain`.
pub fn sited(&self, domain: &str) -> Result<Option<String>> {
let sql = "SELECT a.did FROM site_domain s JOIN account a ON a.did = s.did AND a.handle = s.domain WHERE s.domain = lower(?1)";
let found = self.conn().query_row(sql, [domain], |r| r.get(0));
Ok(found.optional()?)
}
/// Serves `did`'s site at `domain` from `at`, or with none, at its
/// address alone.
pub fn set_site_domain(&self, did: &str, domain: Option<&str>, at: i64) -> Result<()> {
let conn = self.conn();
match domain {
Some(domain) => conn.execute(
"INSERT INTO site_domain (did, domain, at) VALUES (?1, ?2, ?3) ON CONFLICT (did) DO UPDATE SET domain = ?2, at = ?3",
params![did, domain, at],
)?,
None => conn.execute("DELETE FROM site_domain WHERE did = ?1", [did])?,
};
Ok(())
}
/// Gives `did` the handle `handle`, with `events`; refused if another
/// account has it.
pub fn set_handle(&self, did: &str, handle: &str, events: &[Event]) -> Result<()> {
crates/group-host/tests/common/mod.rs+10−0
@@ -263,6 +263,16 @@ pub async fn start_reachable(vars: &[(&str, &str)]) -> Running {
start_on(listener, &vars, false).await
}
/// A host given where it listens as `var` too, as for a domain that
/// reaches it (`SITE_CHECK_AT`).
pub async fn start_naming_itself(var: &str, vars: &[(&str, &str)]) -> Running {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let url = format!("http://{}", listener.local_addr().unwrap());
let mut vars = vars.to_vec();
vars.push((var, &url));
start_on(listener, &vars, false).await
}
/// A host reachable by name, at `http://localhost:<port>`, its `did:web`
/// of that name: for servers elsewhere that resolve its DID, as one
/// resolves `localhost` over http. It listens on every address, IPv6 and
crates/group-host/tests/sites.rs+98−1
@@ -7,7 +7,7 @@ use common::groups::*;
use common::members::{granting, keep};
use common::oauth::App;
use common::spaces::*;
use common::{Running, start};
use common::{Running, start, start_naming_itself};
use group_host::sites::{self, SANDBOX, SITE};
use serde_json::{Value as Json, json};
@@ -695,3 +695,100 @@ fn a_page_previews_as_its_own_head_says_and_never_as_markup() {
let many = "<meta name=description content=x>".repeat(40);
assert_eq!(preview(&many).matches("<meta").count(), 32);
}
/// Riders' handle on a domain of its own, as updateGroupHandle gives it.
const OWN: &str = "riders.example";
/// Whether a proxy in front may get a certificate for `domain`.
async fn certified(h: &Running, domain: &str) -> u16 {
let asked = reqwest::get(format!("{}/tls/ask?domain={domain}", h.url)).await;
asked.unwrap().status().as_u16()
}
#[tokio::test]
async fn a_site_moves_to_the_groups_own_domain_once_it_reaches_the_host() {
// A host whose groups' domains reach it, as the proxy in front would.
let h = start_naming_itself("SITE_CHECK_AT", &[]).await;
let (did, [alice, bob, ..]) = group(&h).await;
let site = json!({"group": did, "files": [{"path": "index.html", "text": "hi"}]});
assert_eq!(call(&h, &alice, "putSite", site.clone()).await.0, 200);
let body = json!({"group": did});
// Its handle its address, it has no domain of its own to move to.
let said = call(&h, &alice, "putSiteDomain", body.clone()).await;
assert_eq!(error(&said), (400, "NoOwnDomain"));
assert_eq!(certified(&h, RIDERS).await, 404);
h.host.store.set_handle(&did, OWN, &[]).unwrap();
// Certificates for its domain and www. under it, before it is switched
// on, so the host can check the domain reaches it; for no other.
assert_eq!(certified(&h, OWN).await, 200);
assert_eq!(certified(&h, "WWW.riders.example").await, 200);
assert_eq!(certified(&h, "elsewhere.example").await, 404);
// Until it is, the domain serves nothing of the site.
let there = ask(&h, "GET", OWN, "/", &[]).await;
assert_eq!(there.header("content-security-policy"), "");
let said = call(&h, &bob, "putSiteDomain", body.clone()).await;
assert_eq!(error(&said), (403, "Forbidden"));
let said = call(&h, &alice, "putSiteDomain", body.clone()).await;
assert_eq!(said, (200, json!({"domain": OWN})));
// The domain serves it, keeping the host's own paths; the address and
// www. send visitors there, path and query kept.
let there = ask(&h, "GET", OWN, "/", &[]).await;
assert_eq!((there.status, there.body.as_str()), (200, "hi"));
let from = page(&h, "/rides/?when=sat").await;
let to = "https://riders.example/rides/?when=sat";
assert_eq!((from.status, from.header("location")), (301, to));
assert_eq!(from.header("content-security-policy"), SANDBOX);
let www = ask(&h, "GET", "www.riders.example", "/a", &[]).await;
assert_eq!(
(www.status, www.header("location")),
(301, "https://riders.example/a")
);
let named = ask(&h, "GET", OWN, "/.well-known/atproto-did", &[]).await;
assert_eq!(named.body, did);
// The group and a publish say where it is.
let lxm = format!("{NS}.getGroup");
let (_, shown) = get(&h, &lxm, &format!("group={did}"), &[auth(&h, &alice, &lxm)]).await;
assert_eq!(shown["group"]["siteDomain"], OWN);
let made = call(&h, &alice, "putSite", site).await;
assert_eq!(made.1["url"], "https://riders.example/");
// Switched off, the site is at its address alone again.
assert_eq!(
call(&h, &alice, "deleteSiteDomain", body.clone()).await,
(200, json!({}))
);
assert_eq!(page(&h, "/").await.body, "hi");
let there = ask(&h, "GET", OWN, "/", &[]).await;
assert_eq!(there.header("content-security-policy"), "");
let (_, shown) = get(&h, &lxm, &format!("group={did}"), &[auth(&h, &alice, &lxm)]).await;
assert_eq!(shown["group"].get("siteDomain"), None);
// On again, a new handle ends it: the new domain was never checked.
call(&h, &alice, "putSiteDomain", body).await;
let lxm = format!("{NS}.updateGroupHandle");
let back = json!({"group": did, "handle": RIDERS});
assert_eq!(
post(&h, &lxm, &back, &[auth(&h, &alice, &lxm)]).await.0,
200
);
assert_eq!(page(&h, "/").await.body, "hi");
h.host.store.set_handle(&did, OWN, &[]).unwrap();
assert_eq!(page(&h, "/").await.body, "hi");
}
#[tokio::test]
async fn a_site_stays_at_its_address_while_its_domain_reaches_no_host() {
// Asked as itself, over https, a domain under .example never answers.
let h = start(&[], false).await;
let (did, [alice, ..]) = group(&h).await;
h.host.store.set_handle(&did, OWN, &[]).unwrap();
let said = call(&h, &alice, "putSiteDomain", json!({"group": did})).await;
assert_eq!(error(&said), (400, "NotReaching"));
let message = said.1["message"].as_str().unwrap();
assert!(
message.starts_with("riders.example doesn't reach this host yet"),
"{message}"
);
}
crates/group-host-mcp/src/lib.rs+12−0
crates/group-host-mcp/tests/protocol.rs+1−0
crates/opensocial/src/lib.rs+3−0
crates/opensocial/tests/commands.rs+6−0
docs/design/README.md+2−2
docs/design/sites.md+34−3
docs/reference/api.md+3−0
docs/reference/cli.md+1−0
docs/reference/config.md+1−0
docs/reference/mcp.md+1−0
docs/deploying.md+21−0
lexicons/fyi/opensocial/defs.json+8−0
lexicons/fyi/opensocial/deleteSiteDomain.jsonnew+32−0
lexicons/fyi/opensocial/putSiteDomain.jsonnew+47−0
web/src/lib/organisms/SiteDomain.sveltenew+68−0
web/src/lib/server/settings.ts+23−1
web/src/routes/g/[handle]/settings/site/+page.server.ts+13−3
web/src/routes/g/[handle]/settings/site/+page.svelte+15−2
web/src/routes/g/[handle]/+page.server.ts+1−1