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

chadtmiller.com/hud

A remote MCP server that shows atproto records as interactive UI inside MCP Apps hosts

0
0
1057 lines · 42.7 KB Raw History
//! Who an account is and where its records live. A handle resolves to a
//! DID by its `_atproto` TXT record, asked of public DNS, or failing that
//! its `https://<handle>/.well-known/atproto-did`; a DID to its document
//! from the PLC directory (`did:plc`) or its host (`did:web`); the document
//! names the PDS. A handle counts only both ways: it resolves to the DID,
//! and the DID's document claims it back (`alsoKnownAs` holding
//! `at://<handle>`). A handle asked for that fails that gives way to the
//! document's own handle, if that one verifies both ways; with neither, the
//! account is shown by its DID. Answers are kept an hour, and answers that
//! there is none (no document, a handle naming no DID) five minutes; no
//! answer at all (none in time, a server that cannot answer now) is not
//! kept, so the next to ask asks again (`net`).
//!
//! Sign-in's handle fields suggest accounts as a person types
//! (`place.hud.searchActors`): the typeahead service's (`TYPEAHEAD`)
//! answer, asked through the outbound client, kept as it says only where
//! it is well formed. Those handles are the service's word, not verified.

use crate::Hud;
use crate::cache::{Ttl, Weigh};
use crate::net::{DNS_WAIT, Fetched, did_of_txt};
use atproto::syntax::{is_did, is_handle};
use futures::StreamExt;
use serde_json::{Map, Value};
use std::sync::Arc;
use std::time::Duration;
use url::Url;

/// How long an answer is kept.
const KEEP: Duration = Duration::from_secs(3600);
/// How long an answer that there is none is kept.
const KEEP_FAILED: Duration = Duration::from_secs(300);
/// How long a DID document's fetch has.
const DOC_WAIT: Duration = Duration::from_secs(5);
/// The most of a DID document read.
const DOC_MAX: usize = 256 * 1024;
/// The most of a `/.well-known/atproto-did` read.
const WELL_KNOWN_MAX: usize = 8 * 1024;
/// The most DIDs whose handles a result's drawing (`Fields`) looks up.
const HANDLES_MAX: usize = 50;
/// How long the handles of a result have, together.
const HANDLES_WAIT: Duration = Duration::from_secs(4);
/// The typeahead service sign-in's suggestions come from: an index of
/// accounts across atproto by handle and name, as knotless's sign-in asks
/// it; no auth.
pub const TYPEAHEAD: &str = "https://typeahead.waow.tech/xrpc/tech.waow.typeahead.searchActors";
static TYPEAHEAD_URL: std::sync::LazyLock<Url> =
    std::sync::LazyLock::new(|| Url::parse(TYPEAHEAD).expect("the typeahead service's URL"));
/// How long the typeahead service has to answer.
const TYPEAHEAD_WAIT: Duration = Duration::from_secs(3);
/// The most of its answer read.
const TYPEAHEAD_MAX: usize = 256 * 1024;
/// The most of a suggested account's name kept, in bytes, as
/// `place.hud.searchActors#actor` bounds it.
const DISPLAY_NAME_MAX: usize = 640;

/// An account, resolved.
#[derive(Clone, Debug)]
pub struct Identity {
    pub did: String,
    /// Its handle, if verified both ways.
    pub handle: Option<String>,
    /// Its PDS's URL, checked, with no trailing `/`.
    pub pds: String,
}

impl Identity {
    /// How the account is named to a person: its handle, else its DID.
    pub fn name(&self) -> &str {
        self.handle.as_deref().unwrap_or(&self.did)
    }
}

/// Whether a DID document claims `handle` (`at://<handle>` in its
/// `alsoKnownAs`, case aside).
fn claims(doc: &Value, handle: &str) -> bool {
    doc.get("alsoKnownAs")
        .and_then(Value::as_array)
        .into_iter()
        .flatten()
        .filter_map(Value::as_str)
        .filter_map(|a| a.strip_prefix("at://"))
        .any(|h| h.eq_ignore_ascii_case(handle))
}

/// The first line of a `/.well-known/atproto-did` body, if it is a DID.
fn did_of_body(body: &[u8]) -> Option<String> {
    let line = body.split(|&b| b == b'\n').next()?;
    let line = std::str::from_utf8(line).ok()?.trim();
    is_did(line).then(|| line.to_string())
}

/// The DID a `com.atproto.identity.resolveHandle` answer names, if any.
fn did_of_resolved(body: &[u8]) -> Option<String> {
    let answer: Value = serde_json::from_slice(body).ok()?;
    let did = answer["did"].as_str()?;
    is_did(did).then(|| did.to_string())
}

/// What a lookup over the network had: an answer, the thing or why there
/// is none; or no answer at all, and why.
enum Asked<V> {
    Answer(Result<V, String>),
    NoAnswer(String),
}

/// Keep in `cache` what a lookup of `key` had: the thing an hour, an
/// answer that there is none five minutes, no answer not at all, so that
/// it neither answers the next to ask nor takes the place of an answer
/// another caller had meanwhile. And say it.
fn keep<V: Clone + Weigh>(
    cache: &Ttl<String, Result<V, String>>,
    key: &str,
    asked: Asked<V>,
) -> Result<V, String> {
    match asked {
        Asked::Answer(answer) => {
            let ttl = if answer.is_ok() { KEEP } else { KEEP_FAILED };
            cache.put(key.to_string(), answer.clone(), ttl);
            answer
        }
        Asked::NoAnswer(why) => Err(why),
    }
}

/// What the two ways a handle names its DID had together, each its DID,
/// none, or why it had no answer: a DID if either named one, else no
/// answer if either had none, else none.
fn either(
    a: Result<Option<String>, String>,
    b: Result<Option<String>, String>,
) -> Result<Option<String>, String> {
    match (a, b) {
        (Ok(Some(did)), _) | (_, Ok(Some(did))) => Ok(Some(did)),
        (Err(why), _) | (_, Err(why)) => Err(why),
        _ => Ok(None),
    }
}

/// Why a DID's document cannot be read.
fn unreadable(did: &str, why: &str) -> String {
    format!("{did}'s DID document cannot be read: {why}")
}

/// What a DID's directory or host answered: its document, or why there is
/// none.
fn doc_of(did: &str, got: &Fetched) -> Result<Value, String> {
    match got.status {
        200 => {}
        404 | 410 => return Err(format!("No DID document for {did}")),
        s => return Err(unreadable(did, &format!("answered {s}"))),
    }
    let doc: Value =
        serde_json::from_slice(&got.body).map_err(|_| unreadable(did, "it is not JSON"))?;
    if doc.get("id").and_then(Value::as_str) != Some(did) {
        return Err(unreadable(did, "it is another DID's"));
    }
    Ok(doc)
}

/// The accounts a typeahead answer (`{actors: [{did, handle, displayName?,
/// avatar?}]}`) names, at most `limit`: each with a DID, and a handle that
/// is one and not `handle.invalid`; its name cut to `DISPLAY_NAME_MAX`
/// bytes; its avatar only if an https URL. None for any other answer.
fn typeahead_actors(body: &Value, limit: usize) -> Vec<Value> {
    let actors = body.get("actors").and_then(Value::as_array);
    actors
        .into_iter()
        .flatten()
        .filter_map(|a| {
            let did = a.get("did").and_then(Value::as_str).filter(|d| is_did(d))?;
            let handle = a
                .get("handle")
                .and_then(Value::as_str)
                .filter(|h| is_handle(h) && !h.eq_ignore_ascii_case("handle.invalid"))?;
            let mut actor = Map::new();
            actor.insert("did".into(), did.into());
            actor.insert("handle".into(), handle.to_ascii_lowercase().into());
            if let Some(name) = a.get("displayName").and_then(Value::as_str) {
                let mut end = name.len().min(DISPLAY_NAME_MAX);
                while !name.is_char_boundary(end) {
                    end -= 1;
                }
                if end > 0 {
                    actor.insert("displayName".into(), name[..end].into());
                }
            }
            let avatar = a
                .get("avatar")
                .and_then(Value::as_str)
                .filter(|u| Url::parse(u).is_ok_and(|u| u.scheme() == "https"));
            if let Some(avatar) = avatar {
                actor.insert("avatar".into(), avatar.into());
            }
            Some(Value::Object(actor))
        })
        .take(limit)
        .collect()
}

impl Hud {
    /// An account named by a handle (with or without a leading `@`) or a
    /// DID, resolved to its DID, verified handle and PDS.
    pub async fn resolve_actor(&self, actor: &str) -> Result<Identity, String> {
        let actor = actor.trim();
        let actor = actor.strip_prefix('@').unwrap_or(actor);
        if is_did(actor) {
            let doc = self.did_doc(actor).await?;
            let pds = self.pds_of(actor, &doc)?;
            let handle = self.verified_handle(actor, &doc).await;
            return Ok(Identity {
                did: actor.to_string(),
                handle,
                pds,
            });
        }
        if !is_handle(actor) {
            return Err(format!("Not a handle or DID: {actor}"));
        }
        let handle = actor.to_ascii_lowercase();
        let did = self.handle_did(&handle).await?;
        let doc = self.did_doc(&did).await?;
        let pds = self.pds_of(&did, &doc)?;
        // The handle asked for counts if the document claims it back; one
        // that only points at the DID (why.bsky.team, whose document names
        // why.bsky.world) does not, and the document's own handle stands in
        // when that one verifies both ways.
        let handle = match claims(&doc, &handle) {
            true => Some(handle),
            false => self.verified_handle(&did, &doc).await,
        };
        Ok(Identity { handle, did, pds })
    }

    /// The PDS of a DID, from its document.
    pub async fn pds(&self, did: &str) -> Result<String, String> {
        let doc = self.did_doc(did).await?;
        self.pds_of(did, &doc)
    }

    /// Accounts matching `q`, what is typed of a handle or name (a leading
    /// `@` aside), best first, at most `limit`, as the typeahead service
    /// (`TYPEAHEAD`) finds them: none for under two letters, or when it
    /// cannot say.
    pub async fn search_actors(&self, q: &str, limit: usize) -> Vec<Value> {
        self.search_actors_at(q, limit, &TYPEAHEAD_URL).await
    }

    /// `search_actors`, asking the typeahead service at `service`.
    async fn search_actors_at(&self, q: &str, limit: usize, service: &Url) -> Vec<Value> {
        let q = q.trim();
        let q = q.strip_prefix('@').unwrap_or(q);
        if q.chars().count() < 2 {
            return Vec::new();
        }
        let mut url = service.clone();
        url.query_pairs_mut()
            .append_pair("q", q)
            .append_pair("limit", &limit.to_string());
        let got = match self
            .net
            .fetch_json(&url, TYPEAHEAD_WAIT, TYPEAHEAD_MAX)
            .await
        {
            Ok(got) if got.status == 200 => got,
            Ok(got) => {
                tracing::info!(status = got.status, "typeahead refused");
                return Vec::new();
            }
            Err(e) => {
                tracing::info!(why = %e, "typeahead unreachable");
                return Vec::new();
            }
        };
        serde_json::from_slice::<Value>(&got.body)
            .map(|body| typeahead_actors(&body, limit))
            .unwrap_or_default()
    }

    /// The PDS a DID's document names, if it is a URL the server may fetch.
    fn pds_of(&self, did: &str, doc: &Value) -> Result<String, String> {
        let endpoint = atproto::did::pds(doc).ok_or_else(|| format!("{did} names no PDS"))?;
        let url = Url::parse(&endpoint).map_err(|_| format!("{did} names no usable PDS"))?;
        let plain = url.username().is_empty()
            && url.password().is_none()
            && url.query().is_none()
            && url.fragment().is_none();
        if !plain {
            return Err(format!("{did} names no usable PDS"));
        }
        crate::net::check_url(&url, self.net.allow_private())
            .map_err(|why| format!("{did}'s PDS cannot be used: {why}"))?;
        Ok(url.as_str().trim_end_matches('/').to_string())
    }

    /// The handle a DID's document claims, if it resolves back to the DID.
    async fn verified_handle(&self, did: &str, doc: &Value) -> Option<String> {
        let handle = atproto::did::handle(doc)?.to_ascii_lowercase();
        if !is_handle(&handle) || handle == "handle.invalid" {
            return None;
        }
        (self.handle_did(&handle).await.ok()? == did).then_some(handle)
    }

    /// The DID a (lowercased) handle resolves to: its DNS record's when it
    /// has one, else its `/.well-known/atproto-did`'s, both asked at once;
    /// or, with `HUD_HANDLE_RESOLVER`, what that service answers alone.
    pub async fn handle_did(&self, handle: &str) -> Result<String, String> {
        if let Some(kept) = self.handles.get(&handle.to_string()) {
            return kept;
        }
        let found = match &self.config.handle_resolver {
            Some(service) => self.handle_by_service(service, handle).await,
            // A DID in DNS answers at once; otherwise both answers count,
            // in whichever order they come.
            None => {
                let dns = async {
                    match self.handle_by_dns(handle).await {
                        Ok(Some(did)) => Err(did),
                        d => Ok(d),
                    }
                };
                let https = async { Ok(self.handle_by_https(handle).await) };
                match tokio::try_join!(dns, https) {
                    Err(did) => Ok(Some(did)),
                    Ok((d, h)) => either(d, h),
                }
            }
        };
        let asked = match found {
            Ok(did) => Asked::Answer(
                did.ok_or_else(|| format!("The handle {handle} does not resolve to a DID")),
            ),
            Err(why) => {
                Asked::NoAnswer(format!("The handle {handle} could not be resolved: {why}"))
            }
        };
        keep(&self.handles, handle, asked)
    }

    /// The DID a service's `com.atproto.identity.resolveHandle` names for
    /// a handle, if any; or why it had no answer.
    async fn handle_by_service(
        &self,
        service: &str,
        handle: &str,
    ) -> Result<Option<String>, String> {
        let Ok(mut url) = Url::parse(&format!(
            "{service}/xrpc/com.atproto.identity.resolveHandle"
        )) else {
            return Err(format!("{service} is not a URL"));
        };
        url.query_pairs_mut().append_pair("handle", handle);
        self.did_at(&url, service, did_of_resolved).await
    }

    /// The DID a handle's `_atproto` TXT record names, if any; or why DNS
    /// had no answer.
    async fn handle_by_dns(&self, handle: &str) -> Result<Option<String>, String> {
        let records = self.net.txt(&format!("_atproto.{handle}")).await?;
        Ok(did_of_txt(&records))
    }

    /// The DID a handle's `/.well-known/atproto-did` names, if any; or why
    /// its host had no answer.
    async fn handle_by_https(&self, handle: &str) -> Result<Option<String>, String> {
        let Ok(url) = Url::parse(&format!("https://{handle}/.well-known/atproto-did")) else {
            return Ok(None);
        };
        self.did_at(&url, handle, did_of_body).await
    }

    /// The DID `url` names, `did_of` its answer's body if it is a `200`'s;
    /// none if it answered otherwise, or was refused on an answer; or why
    /// `who` had no answer.
    async fn did_at(
        &self,
        url: &Url,
        who: &str,
        did_of: fn(&[u8]) -> Option<String>,
    ) -> Result<Option<String>, String> {
        match self.net.fetch(url, DNS_WAIT, WELL_KNOWN_MAX).await {
            Ok(got) if got.unavailable() => Err(format!("{who} answered {}", got.status)),
            Ok(got) => Ok((got.status == 200).then(|| did_of(&got.body)).flatten()),
            Err(f) if f.answered => Ok(None),
            Err(f) => Err(f.why),
        }
    }

    /// A DID's document: `did:plc` from the PLC directory, `did:web` from
    /// its host's `/.well-known/did.json`. Its `id` must be the DID.
    pub async fn did_doc(&self, did: &str) -> Result<Arc<Value>, String> {
        if let Some(kept) = self.docs.get(&did.to_string()) {
            return kept;
        }
        self.fresh_did_doc(did).await
    }

    /// A DID's document fetched now, whatever is kept, and kept in its
    /// place if it was had: what a sign-in's account is checked against.
    pub async fn fresh_did_doc(&self, did: &str) -> Result<Arc<Value>, String> {
        let asked = self.fetch_doc(did).await;
        keep(&self.docs, did, asked)
    }

    /// A DID's document as its directory or host answers now.
    async fn fetch_doc(&self, did: &str) -> Asked<Arc<Value>> {
        let url = match self.doc_url(did) {
            Ok(url) => url,
            Err(why) => return Asked::Answer(Err(why)),
        };
        match self.net.fetch(&url, DOC_WAIT, DOC_MAX).await {
            Ok(got) if got.unavailable() => {
                Asked::NoAnswer(unreadable(did, &format!("answered {}", got.status)))
            }
            Ok(got) => Asked::Answer(doc_of(did, &got).map(Arc::new)),
            Err(f) if f.answered => Asked::Answer(Err(unreadable(did, &f.why))),
            Err(f) => Asked::NoAnswer(unreadable(did, &f.why)),
        }
    }

    /// Where a DID's document is read, if it is a DID atproto supports.
    fn doc_url(&self, did: &str) -> Result<Url, String> {
        let url = if did.starts_with("did:plc:") {
            format!("{}/{did}", self.config.plc_url)
        } else if let Some(host) = did.strip_prefix("did:web:") {
            // A host alone, as atproto allows: a port is written `%3A`.
            // localhost, where private addresses are allowed (a service
            // run beside HUD for tests), over http, as atproto's own
            // resolver reads it.
            let host = host.replace("%3A", ":").replace("%3a", ":");
            let (name, port) = host.split_once(':').unwrap_or((&host, "443"));
            let local = self.net.allow_private() && name == "localhost";
            if !(is_handle(name) || local) || port.parse::<u16>().is_err() {
                return Err(format!("{did} is not a did:web atproto supports"));
            }
            let scheme = if local { "http" } else { "https" };
            format!("{scheme}://{host}/.well-known/did.json")
        } else {
            return Err(format!("{did} is not a did:plc or did:web"));
        };
        Url::parse(&url).map_err(|_| format!("{did} is not a DID atproto supports"))
    }

    /// The verified handles of the DIDs among `values`' strings, at any
    /// depth: at most 50 of them, as many as resolve within a few seconds.
    pub async fn handles_of<'a>(&self, values: impl IntoIterator<Item = &'a Value>) -> Value {
        let mut dids = Vec::new();
        for v in values {
            collect_dids(v, &mut dids);
        }
        let mut lookups = futures::stream::iter(dids.into_iter().map(|did| async move {
            let doc = self.did_doc(&did).await.ok()?;
            let handle = self.verified_handle(&did, &doc).await?;
            Some((did, handle))
        }))
        .buffer_unordered(10);
        let deadline = tokio::time::Instant::now() + HANDLES_WAIT;
        let mut out = Map::new();
        while let Ok(Some(found)) = tokio::time::timeout_at(deadline, lookups.next()).await {
            if let Some((did, handle)) = found {
                out.insert(did, Value::String(handle));
            }
        }
        Value::Object(out)
    }
}

/// The distinct DIDs among a value's strings, up to `HANDLES_MAX`.
fn collect_dids(v: &Value, out: &mut Vec<String>) {
    if out.len() >= HANDLES_MAX {
        return;
    }
    match v {
        Value::String(s) if is_did(s) && !out.contains(s) => out.push(s.clone()),
        Value::Array(items) => items.iter().for_each(|i| collect_dids(i, out)),
        Value::Object(o) => o.values().for_each(|i| collect_dids(i, out)),
        _ => {}
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::tools::Refusal;
    use axum::Router;
    use axum::extract::{Path, State};
    use axum::http::StatusCode;
    use axum::response::{IntoResponse, Response};
    use serde_json::json;
    use std::sync::atomic::{AtomicUsize, Ordering::SeqCst};

    const APPVIEW: &str = "did:plc:aaaaaaaaaaaaaaaaaaaaaaaa";
    const GONE: &str = "did:plc:bbbbbbbbbbbbbbbbbbbbbbbb";

    /// The fake's state: how many times its directory was asked, how long
    /// its first answer waits, and its own URL.
    #[derive(Clone)]
    struct Directory {
        asked: Arc<AtomicUsize>,
        late: Duration,
        url: String,
    }

    /// A DID's document, as the fake directory answers: none for any DID
    /// but the AppView's; for the AppView's, a `503` first, sent `late`,
    /// as a cold or busy directory might, and after that its document.
    async fn document(State(d): State<Directory>, Path(did): Path<String>) -> Response {
        let n = d.asked.fetch_add(1, SeqCst);
        if did != APPVIEW {
            return StatusCode::NOT_FOUND.into_response();
        }
        if n == 0 {
            tokio::time::sleep(d.late).await;
            return StatusCode::SERVICE_UNAVAILABLE.into_response();
        }
        let service =
            json!({ "id": "#bsky_appview", "type": "BskyAppView", "serviceEndpoint": d.url });
        axum::Json(json!({ "id": did, "service": [service] })).into_response()
    }

    /// A server signed out whose PLC directory is the fake, on a loopback
    /// port, the AppView too; and how many times its directory was asked.
    async fn served(late: Duration) -> (Arc<Hud>, impl Fn() -> usize) {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let url = format!("http://{}", listener.local_addr().unwrap());
        let asked = Arc::new(AtomicUsize::new(0));
        let state = Directory {
            asked: asked.clone(),
            late,
            url: url.clone(),
        };
        let app = Router::new()
            .route(
                "/xrpc/app.bsky.feed.getFeed",
                axum::routing::get(|| async { axum::Json(json!({ "feed": [] })) }),
            )
            .route("/{did}", axum::routing::get(document))
            .with_state(state);
        tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
        let dir = std::env::temp_dir().join(format!("hud-identity-{}", atproto::jose::random(6)));
        let hud = Hud::new(crate::Config {
            port: 0,
            bind: "::".parse().unwrap(),
            public_origin: "https://hud.test".into(),
            cache_dir: dir.join("cache"),
            blob_cache_bytes: 0,
            cache_memory_bytes: 1 << 24,
            data_dir: dir,
            oauth: false,
            oauth_scope: crate::scope::asked(crate::view::views(), true, false),
            oauth_include: None,
            workspace: true,
            spaces: false,
            plc_url: url,
            handle_resolver: None,
            allow_private: true,
            backlinks: crate::backlinks::Backlinks::None,
            favicons: None,
            image_cdn: None,
            relay: None,
            sign_up_pds: crate::config::SIGN_UP_PDS.into(),
            client: Default::default(),
            operators: Vec::new(),
            logs: false,
            logs_keep: crate::logs::KEEP,
        })
        .unwrap();
        (hud, move || asked.load(SeqCst))
    }

    /// A call of the feed through the AppView, as the soak's first is.
    async fn feed(hud: &Hud) -> Result<(), Refusal> {
        feed_named(hud, "hot").await
    }

    /// A call of the feed `name` through the AppView.
    async fn feed_named(hud: &Hud, name: &str) -> Result<(), Refusal> {
        let args = json!({ "method": "app.bsky.feed.getFeed",
                           "params": { "feed": format!("at://{APPVIEW}/app.bsky.feed.generator/{name}") },
                           "service": format!("{APPVIEW}#bsky_appview") });
        hud.call_tool("query", Some(&args), None)
            .await
            .unwrap()
            .map(|_| ())
    }

    #[tokio::test]
    async fn no_answer_is_kept() {
        let (hud, asked) = served(Duration::ZERO).await;
        assert_eq!(
            feed(&hud).await,
            Err(Refusal::Error(format!(
                "{APPVIEW}'s DID document cannot be read: answered 503"
            )))
        );
        // The 503 said nothing of the document: the next call asks again,
        // and has it.
        assert_eq!(feed(&hud).await, Ok(()));
        assert_eq!(asked(), 2);
        // Had, it is kept.
        assert_eq!(feed(&hud).await, Ok(()));
        assert_eq!(asked(), 2);
        // An answer that there is none is kept as well.
        for _ in 0..2 {
            assert_eq!(
                hud.did_doc(GONE).await.unwrap_err(),
                format!("No DID document for {GONE}")
            );
        }
        assert_eq!(asked(), 3);
    }

    #[tokio::test]
    async fn first_callers_at_once_keep_no_failure() {
        // Four at once, each of its own feed (the same asked at once is
        // asked once), on a server just started: one meets the directory's
        // 503, last, after the others had the document.
        let (hud, asked) = served(Duration::from_millis(200)).await;
        let feeds = ["a", "b", "c", "d"].map(|name| feed_named(&hud, name));
        let first = futures::future::join_all(feeds).await;
        assert_eq!(first.iter().filter(|r| r.is_err()).count(), 1, "{first:?}");
        // Its failure took the place of no answer: every call after has
        // the document kept, asking nothing.
        let before = asked();
        for _ in 0..4 {
            assert_eq!(feed(&hud).await, Ok(()));
        }
        assert_eq!(asked(), before);
    }

    const ALICE: &str = "did:plc:alicealicealicealicealic";
    const WHY: &str = "did:plc:whywhywhywhywhywhywhywhy";
    const NOBODY: &str = "did:plc:nobodynobodynobodynobody";
    const LIAR: &str = "did:plc:liarliarliarliarliarliar";
    const ODD: &str = "did:plc:oddoddoddoddoddoddoddodd";

    /// A DID's document naming `handle` and the PDS `pds`, as text.
    fn doc(did: &str, handle: &str, pds: &str) -> String {
        let pds = json!({ "id": "#atproto_pds", "type": "AtprotoPersonalDataServer",
                          "serviceEndpoint": pds });
        json!({ "id": did, "alsoKnownAs": [format!("at://{handle}")], "service": [pds] })
            .to_string()
    }

    /// What the fake answers: each DID's document, as a status and a body,
    /// and each handle's DID, as its resolver answers it.
    type Answers = Arc<(Vec<(String, u16, String)>, Vec<(&'static str, u16, String)>)>;

    async fn directory(State(a): State<Answers>, Path(did): Path<String>) -> Response {
        match a.0.iter().find(|(d, _, _)| *d == did) {
            Some((_, status, body)) => {
                (StatusCode::from_u16(*status).unwrap(), body.clone()).into_response()
            }
            None => StatusCode::NOT_FOUND.into_response(),
        }
    }

    async fn resolve_handle(
        State(a): State<Answers>,
        axum::extract::Query(q): axum::extract::Query<std::collections::HashMap<String, String>>,
    ) -> Response {
        match a.1.iter().find(|(h, _, _)| *h == q["handle"]) {
            Some((_, status, body)) => {
                (StatusCode::from_u16(*status).unwrap(), body.clone()).into_response()
            }
            None => (StatusCode::BAD_REQUEST, r#"{"error":"InvalidRequest"}"#).into_response(),
        }
    }

    /// A host's own `did:web` document, of the host it is asked at.
    async fn own_doc(headers: axum::http::HeaderMap) -> Response {
        let host = headers["host"].to_str().unwrap().replace(':', "%3A");
        axum::Json(json!({ "id": format!("did:web:{host}") })).into_response()
    }

    /// A server signed out whose PLC directory and handle resolver are a
    /// fake on a loopback port, answering as `answers` say; its config
    /// changed by `with` (given the fake's URL); and the fake's URL.
    async fn world(
        docs: Vec<(String, u16, String)>,
        handles: Vec<(&'static str, u16, String)>,
        with: impl FnOnce(&mut crate::Config, &str),
    ) -> (Arc<Hud>, String) {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let url = format!("http://{}", listener.local_addr().unwrap());
        let app = Router::new()
            .route(
                "/xrpc/com.atproto.identity.resolveHandle",
                axum::routing::get(resolve_handle),
            )
            .route("/.well-known/did.json", axum::routing::get(own_doc))
            .route("/{did}", axum::routing::get(directory))
            .with_state(Arc::new((docs, handles)));
        tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
        let dir = std::env::temp_dir().join(format!("hud-identity-{}", atproto::jose::random(6)));
        let mut config = crate::Config {
            port: 0,
            bind: "::".parse().unwrap(),
            public_origin: "https://hud.test".into(),
            cache_dir: dir.join("cache"),
            blob_cache_bytes: 0,
            cache_memory_bytes: 1 << 24,
            data_dir: dir,
            oauth: false,
            oauth_scope: crate::scope::asked(crate::view::views(), true, false),
            oauth_include: None,
            workspace: true,
            sign_up_pds: crate::config::SIGN_UP_PDS.into(),
            client: Default::default(),
            operators: Vec::new(),
            logs: false,
            logs_keep: crate::logs::KEEP,
            spaces: false,
            plc_url: url.clone(),
            handle_resolver: Some(url.clone()),
            allow_private: true,
            backlinks: crate::backlinks::Backlinks::None,
            favicons: None,
            image_cdn: None,
            relay: None,
        };
        with(&mut config, &url);
        (Hud::new(config).unwrap(), url)
    }

    /// A handle's DID, as its resolver answers it.
    fn named(handle: &'static str, did: &str) -> (&'static str, u16, String) {
        (handle, 200, json!({ "did": did }).to_string())
    }

    #[tokio::test]
    async fn documents_refused_as_their_directory_answers() {
        let ok = |did: &str| (did.to_string(), 200, doc(did, "x.test", "https://pds.test"));
        let docs = vec![
            (ALICE.to_string(), 200, "<html>".to_string()),
            (WHY.to_string(), 418, String::new()),
            (
                LIAR.to_string(),
                200,
                doc(ALICE, "x.test", "https://pds.test"),
            ),
            (ODD.to_string(), 200, " ".repeat(DOC_MAX + 1)),
            ok(NOBODY),
        ];
        let (hud, url) = world(docs, Vec::new(), |_, _| {}).await;
        let err = |did: &'static str| {
            let hud = hud.clone();
            async move { hud.did_doc(did).await.unwrap_err() }
        };
        let unreadable =
            |did: &str, why: &str| format!("{did}'s DID document cannot be read: {why}");
        assert_eq!(err(ALICE).await, unreadable(ALICE, "it is not JSON"));
        assert_eq!(err(WHY).await, unreadable(WHY, "answered 418"));
        assert_eq!(err(LIAR).await, unreadable(LIAR, "it is another DID's"));
        // Refused on its answer, as too large: an answer, kept.
        assert_eq!(err(ODD).await, unreadable(ODD, "its answer is too large"));
        assert_eq!(hud.did_doc(NOBODY).await.unwrap()["id"], NOBODY);
        // DIDs atproto does not support, or no did:web host can serve.
        for (did, why) in [
            ("did:web:bad_host", "is not a did:web atproto supports"),
            (
                "did:web:localhost%3Aport",
                "is not a did:web atproto supports",
            ),
            (
                "did:key:z6MkhaXgBZDvotDkL5257faiztiGiC2QtKLGpbnnEGta2doK",
                "is not a did:plc or did:web",
            ),
        ] {
            assert_eq!(err(did).await, format!("{did} {why}"));
        }
        // A did:web of localhost, private addresses being allowed: read
        // over http.
        let port = url.rsplit(':').next().unwrap();
        let web: &'static str = format!("did:web:localhost%3A{port}").leak();
        assert_eq!(hud.did_doc(web).await.unwrap()["id"], web);
        // A directory that cannot be reached, or named by no URL.
        let (closed, _) = world(Vec::new(), Vec::new(), |c, _| {
            c.plc_url = "http://127.0.0.1:1".into()
        })
        .await;
        assert_eq!(
            closed.did_doc(ALICE).await.unwrap_err(),
            unreadable(ALICE, "could not connect")
        );
        let (nowhere, _) = world(Vec::new(), Vec::new(), |c, _| c.plc_url = "nowhere".into()).await;
        assert_eq!(
            nowhere.did_doc(ALICE).await.unwrap_err(),
            format!("{ALICE} is not a DID atproto supports")
        );
    }

    #[tokio::test]
    async fn the_pds_a_document_names_if_usable() {
        let with_pds = |did: &str, pds: &str| (did.to_string(), 200, doc(did, "x.test", pds));
        let docs = vec![
            (ALICE.to_string(), 200, json!({ "id": ALICE }).to_string()),
            with_pds(WHY, "not a url"),
            with_pds(LIAR, "https://user@pds.test"),
            with_pds(ODD, "ftp://pds.test"),
            with_pds(NOBODY, "http://127.0.0.1:9/"),
        ];
        let (hud, _) = world(docs, Vec::new(), |_, _| {}).await;
        assert_eq!(
            hud.pds(ALICE).await.unwrap_err(),
            format!("{ALICE} names no PDS")
        );
        assert_eq!(
            hud.pds(WHY).await.unwrap_err(),
            format!("{WHY} names no usable PDS")
        );
        assert_eq!(
            hud.pds(LIAR).await.unwrap_err(),
            format!("{LIAR} names no usable PDS")
        );
        assert_eq!(
            hud.pds(ODD).await.unwrap_err(),
            format!("{ODD}'s PDS cannot be used: ftp://pds.test is not https")
        );
        assert_eq!(hud.pds(NOBODY).await.unwrap(), "http://127.0.0.1:9");
    }

    #[tokio::test]
    async fn handles_count_only_both_ways() {
        let pds = "https://pds.test";
        let docs = vec![
            (ALICE.to_string(), 200, doc(ALICE, "Alice.Test", pds)),
            (WHY.to_string(), 200, doc(WHY, "why.world", pds)),
            (NOBODY.to_string(), 200, doc(NOBODY, "handle.invalid", pds)),
            (LIAR.to_string(), 200, doc(LIAR, "alice.test", pds)),
            (ODD.to_string(), 200, doc(ODD, "not a handle", pds)),
        ];
        let handles = vec![
            named("alice.test", ALICE),
            named("why.test", WHY),
            named("why.world", WHY),
            ("busy.test", 503, String::new()),
            ("huge.test", 200, " ".repeat(WELL_KNOWN_MAX + 1)),
            ("bad.test", 200, json!({ "did": "nope" }).to_string()),
        ];
        let (hud, url) = world(docs, handles, |_, _| {}).await;
        let who = |actor: &'static str| {
            let hud = hud.clone();
            async move {
                let i = hud.resolve_actor(actor).await.unwrap();
                (i.did, i.handle, i.pds)
            }
        };
        let handle = |h: &str| Some(h.to_string());
        // Claimed back by the document, case aside.
        assert_eq!(
            who("@Alice.Test").await,
            (ALICE.into(), handle("alice.test"), pds.into())
        );
        // Pointing at the DID alone: the document's own handle stands in.
        assert_eq!(
            who("why.test").await,
            (WHY.into(), handle("why.world"), pds.into())
        );
        // None that verifies: the account is shown by its DID.
        for did in [NOBODY, LIAR, ODD] {
            let i = hud.resolve_actor(did).await.unwrap();
            assert_eq!((i.handle.as_deref(), i.name()), (None, did));
        }
        let refused = |actor: &'static str| {
            let hud = hud.clone();
            async move { hud.resolve_actor(actor).await.unwrap_err() }
        };
        assert_eq!(
            refused("not a handle!").await,
            "Not a handle or DID: not a handle!"
        );
        for h in ["nobody.test", "huge.test", "bad.test"] {
            assert_eq!(
                refused(h).await,
                format!("The handle {h} does not resolve to a DID")
            );
        }
        assert_eq!(
            refused("busy.test").await,
            format!("The handle busy.test could not be resolved: {url} answered 503")
        );
        // The DIDs of a result named by their verified handles.
        let values = [json!({ "a": ALICE, "b": [NOBODY, GONE, "did:plc:"] })];
        assert_eq!(
            hud.handles_of(&values).await,
            json!({ ALICE: "alice.test" })
        );
    }

    #[tokio::test]
    async fn resolvers_that_cannot_answer() {
        let (closed, _) = world(Vec::new(), Vec::new(), |c, _| {
            c.handle_resolver = Some("http://127.0.0.1:1".into())
        })
        .await;
        assert_eq!(
            closed.handle_did("alice.test").await.unwrap_err(),
            "The handle alice.test could not be resolved: could not connect"
        );
        let (nowhere, _) = world(Vec::new(), Vec::new(), |c, _| {
            c.handle_resolver = Some("nowhere".into())
        })
        .await;
        assert_eq!(
            nowhere.handle_did("alice.test").await.unwrap_err(),
            "The handle alice.test could not be resolved: nowhere is not a URL"
        );
    }

    #[tokio::test]
    async fn handles_by_dns() {
        use crate::net::tests::{Reply, fake_net, txt};
        let (mut hud, _) = world(Vec::new(), Vec::new(), |c, _| c.handle_resolver = None).await;
        Arc::get_mut(&mut hud).unwrap().net = fake_net(false, |name, _| match name {
            "_atproto.dns.test" => Reply::Records(vec![txt(name, &format!("did={ALICE}"))]),
            _ => Reply::NoSuchName,
        })
        .await;
        // Its TXT record names it; its host has none, refused on DNS's answer.
        assert_eq!(hud.handle_did("dns.test").await.unwrap(), ALICE);
        assert_eq!(
            hud.handle_did("none.test").await.unwrap_err(),
            "The handle none.test does not resolve to a DID"
        );
        // A name no URL can hold has no well-known DID.
        assert!(
            hud.handle_did("a b")
                .await
                .unwrap_err()
                .starts_with("The handle a b "),
        );
    }

    #[test]
    fn either_way_of_naming() {
        let did = || Ok(Some("did:plc:a".to_string()));
        let none = || Ok(None);
        let silent = || Err("no answer".to_string());
        assert_eq!(either(silent(), did()), did());
        assert_eq!(either(did(), silent()), did());
        // One that had no answer says nothing: not that it names none.
        assert_eq!(either(none(), silent()), silent());
        assert_eq!(either(none(), none()), none());
    }

    #[test]
    fn dids_in_values_at_most_fifty() {
        let v: Vec<Value> = (0..60).map(|i| json!(format!("did:plc:{i:024}"))).collect();
        let mut out = Vec::new();
        collect_dids(&json!(v), &mut out);
        assert_eq!(out.len(), HANDLES_MAX);
    }

    #[test]
    fn claimed_handles() {
        let doc = json!({ "alsoKnownAs": ["at://Alice.Example.com", "https://x"] });
        assert!(claims(&doc, "alice.example.com"));
        assert!(!claims(&doc, "bob.example.com"));
        assert!(!claims(&json!({}), "alice.example.com"));
    }

    #[test]
    fn dids_in_values() {
        let v = json!({ "a": "did:plc:one", "b": ["did:web:x.com", "did:plc:one", "nope"],
                        "c": { "d": "at://did:plc:two/x.y.z/1" } });
        let mut out = Vec::new();
        collect_dids(&v, &mut out);
        out.sort();
        assert_eq!(out, ["did:plc:one", "did:web:x.com"]);
    }

    #[test]
    fn well_known_bodies() {
        assert_eq!(
            did_of_body(b"did:plc:abc\n").as_deref(),
            Some("did:plc:abc")
        );
        assert_eq!(did_of_body(b"<html>"), None);
    }

    #[test]
    fn typeahead_answers_kept_where_well_formed() {
        let long = "é".repeat(400);
        let body = json!({ "actors": [
            { "did": "did:plc:alice", "handle": "Alice.Test", "displayName": long,
              "avatar": "https://cdn.example/a.jpg" },
            { "did": "did:plc:gone", "handle": "handle.invalid" },
            { "did": "not a did", "handle": "bob.test" },
            { "did": "did:plc:carol", "handle": "not a handle" },
            { "did": "did:plc:dan", "handle": "dan.test", "avatar": "http://cdn.example/d.jpg" },
            { "did": "did:plc:erin", "handle": "erin.test", "avatar": "javascript:alert(1)" },
            "nothing",
            { "did": "did:plc:fred", "handle": "fred.test", "displayName": "€".repeat(300) },
            { "did": "did:plc:gail", "handle": "gail.test", "displayName": "" },
        ] });
        let got = typeahead_actors(&body, 6);
        let dids: Vec<&str> = got.iter().map(|a| a["did"].as_str().unwrap()).collect();
        assert_eq!(
            dids,
            [
                "did:plc:alice",
                "did:plc:dan",
                "did:plc:erin",
                "did:plc:fred",
                "did:plc:gail"
            ]
        );
        assert_eq!(got[0]["handle"], "alice.test");
        assert_eq!(got[0]["avatar"], "https://cdn.example/a.jpg");
        // Cut to 640 bytes, whole characters; none where it says nothing.
        assert_eq!(got[0]["displayName"].as_str().unwrap(), "é".repeat(320));
        assert_eq!(got[3]["displayName"].as_str().unwrap(), "€".repeat(213));
        assert!(got[4].get("displayName").is_none());
        assert!(got[1].get("avatar").is_none() && got[2].get("avatar").is_none());
        assert_eq!(typeahead_actors(&body, 1).len(), 1);
        assert!(typeahead_actors(&json!({ "actors": "x" }), 6).is_empty());
        assert!(typeahead_actors(&json!([]), 6).is_empty());
    }

    #[tokio::test]
    async fn typeahead_asked_as_typed() {
        use axum::extract::Query;
        use std::collections::HashMap;
        let app = Router::new().route(
            "/typeahead",
            axum::routing::get(|Query(q): Query<HashMap<String, String>>| async move {
                match q["q"].as_str() {
                    "busy" => (StatusCode::SERVICE_UNAVAILABLE, String::new()),
                    "junk" => (StatusCode::OK, "not json".to_string()),
                    asked => {
                        let name = format!("{asked} {}", q["limit"]);
                        let actor = json!({ "did": "did:plc:alice", "handle": "alice.test", "displayName": name });
                        (StatusCode::OK, json!({ "actors": [actor] }).to_string())
                    }
                }
            }),
        );
        let service = Url::parse(&format!("{}/typeahead", crate::tests::serve(app).await)).unwrap();
        let hud = crate::tests::hud_with("http://127.0.0.1:9", |_| {});
        // Asked as typed, a leading `@` aside.
        assert_eq!(
            hud.search_actors_at(" @al ", 3, &service).await,
            [json!({ "did": "did:plc:alice", "handle": "alice.test", "displayName": "al 3" })]
        );
        // None for under two letters, a refusal, an answer not JSON, or a
        // service that cannot be reached.
        for q in ["@a", "busy", "junk"] {
            assert!(hud.search_actors_at(q, 3, &service).await.is_empty(), "{q}");
        }
        let closed = crate::writes::tests::closed_port().await;
        let closed = Url::parse(&format!("http://127.0.0.1:{closed}/typeahead")).unwrap();
        assert!(hud.search_actors_at("al", 3, &closed).await.is_empty());
        assert!(hud.search_actors("a", 3).await.is_empty());
    }
}