~ 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
1375 lines · 51.6 KB Raw History
//! HUD as the authorization server of its MCP endpoint, as MCP's
//! authorization spec has one and Monolith's MCP issuer is
//! (`spec/OAUTH-MCP.md` there): its clients, public ones named by a client
//! ID metadata document (an `https://` `client_id`, fetched and kept an
//! hour) or registered dynamically (RFC 7591, kept on disk); the
//! authorization request, checked in order and kept for the sign-in page,
//! or, HUD's own app's naming its account as a login hint, sent straight on
//! to that account's server; the token endpoint, its code grant (PKCE and
//! the resource) and its refresh grant, rotating, a replaced refresh token
//! used again ending its session; revocation. Its tokens are opaque, 32
//! random bytes, kept as their SHA-256 alone.

use super::client::SignIn;
use super::store::{Mcp, Session};
use super::{
    ACCESS_LIFE, Asker, Auth, CODE_LIFE, Kept, PENDING_LIFE, PENDING_MAX, REFRESH_LIFE, SCOPE,
    SPENT_LIFE, index, now,
};
use crate::Hud;
use crate::net::{Failure, Fetched};
use atproto::jose;
use serde_json::{Map, Value, json};
use std::collections::HashMap;
use std::time::Duration;
use url::{Host, Url};

/// How long a client's metadata document has to answer.
const DOCUMENT_WAIT: Duration = Duration::from_secs(10);
/// The most of a client metadata document read.
const DOCUMENT_MAX: usize = 64 * 1024;
/// How long a client metadata document is kept.
const DOCUMENT_KEEP: u64 = 3600;
/// The most clients registered dynamically.
const CLIENTS_MAX: usize = 10_000;
/// The most redirect URIs a registered client may name.
const REDIRECTS_MAX: usize = 10;
/// The longest a redirect URI, a `state` or a client's name may be.
const URI_MAX: usize = 2048;
const STATE_MAX: usize = 1024;
const NAME_MAX: usize = 100;

/// An MCP client: a public one, as all HUD takes are.
#[derive(Clone, Debug, PartialEq)]
pub struct Client {
    pub id: String,
    /// Its `client_name`, one line.
    pub name: Option<String>,
    pub redirect_uris: Vec<String>,
    /// Whether its grant types include `refresh_token`: it is given refresh
    /// tokens, and may use them.
    pub refresh: bool,
}

impl Client {
    /// As a registered client is kept.
    pub fn to_json(&self) -> Value {
        let grants: &[&str] = if self.refresh {
            &["authorization_code", "refresh_token"]
        } else {
            &["authorization_code"]
        };
        json!({
            "client_id": self.id,
            "client_name": self.name,
            "redirect_uris": self.redirect_uris,
            "grant_types": grants,
            "response_types": ["code"],
            "token_endpoint_auth_method": "none",
        })
    }

    pub fn from_json(v: &Value) -> Option<Client> {
        Some(Client {
            id: v.get("client_id")?.as_str()?.to_string(),
            name: v
                .get("client_name")
                .and_then(Value::as_str)
                .map(str::to_string),
            redirect_uris: strings(v.get("redirect_uris"))?,
            refresh: strings(v.get("grant_types"))?
                .iter()
                .any(|g| g == "refresh_token"),
        })
    }

    /// What the sign-in page calls it: its name, else its document's host,
    /// else its id.
    pub fn shown(&self) -> String {
        if let Some(n) = &self.name {
            return n.clone();
        }
        Url::parse(&self.id)
            .ok()
            .and_then(|u| u.host_str().map(str::to_string))
            .unwrap_or_else(|| self.id.clone())
    }
}

/// An authorization request waiting for its account.
#[derive(Clone, Debug)]
pub struct Request {
    pub client_id: String,
    /// What the sign-in page calls the client.
    pub client_name: String,
    pub redirect_uri: String,
    pub state: Option<String>,
    /// PKCE, S256.
    pub challenge: String,
    pub login_hint: Option<String>,
    /// Whether it asks for a new account (`prompt=create`).
    pub create: bool,
    /// Whether its client names the account itself, so it goes straight on
    /// to the account's server (`straight_on`).
    pub straight: bool,
    /// Whether the client is given a refresh token.
    pub refresh: bool,
    pub created: u64,
}

impl Request {
    /// The client's redirect URI with `pairs`, `iss` and its `state` added.
    pub fn back(&self, origin: &str, pairs: &[(&str, &str)]) -> String {
        let mut all: Vec<(&str, &str)> = pairs.to_vec();
        all.push(("iss", origin));
        if let Some(s) = &self.state {
            all.push(("state", s));
        }
        with_query(&self.redirect_uri, &all)
    }
}

/// What the sign-in page shows of a request waiting.
#[derive(Clone, Debug, PartialEq)]
pub struct Pending {
    /// Its id, the form's hidden field.
    pub id: String,
    /// The client, by name; for the workspace, HUD.
    pub client: String,
    pub login_hint: Option<String>,
    /// Whether its client names the account itself (`straight_on`): HUD's
    /// own app (`Auth::app_client_id`), or a web client of an app whose
    /// file draws its own sign-in screen. With a login hint, or asking for
    /// a new account, it goes straight on to the account's server, or the
    /// sign-up PDS's, no page shown.
    pub straight: bool,
    /// Whether it asks for a new account (`prompt=create`).
    pub create: bool,
}

/// A code HUD gave, waiting for its exchange: the session it starts.
pub(crate) struct Code {
    pub client_id: String,
    pub redirect_uri: String,
    pub challenge: String,
    pub session: Session,
    pub refresh: bool,
    pub created: u64,
}

/// An OAuth error answer: its status, `error` and `error_description`.
#[derive(Clone, Debug, PartialEq)]
pub struct Refused {
    pub status: u16,
    pub error: &'static str,
    pub description: String,
}

fn refused(status: u16, error: &'static str, description: impl Into<String>) -> Refused {
    Refused {
        status,
        error,
        description: description.into(),
    }
}

impl Refused {
    pub fn to_json(&self) -> Value {
        json!({ "error": self.error, "error_description": self.description })
    }
}

/// How a refused authorization request is answered.
#[derive(Debug, PartialEq)]
pub enum NotAuthorized {
    /// An error page: the request names no client, or no redirect URI of
    /// its client, so nothing can be sent back.
    Page(String),
    /// A redirect back to the client, carrying `error`.
    Redirect(String),
}

/// How `GET /oauth/authorize` goes on with a request it took.
#[derive(Debug, PartialEq)]
pub enum Authorized {
    /// The sign-in page.
    Page(Pending),
    /// On to the account's server's authorization page.
    Server(String),
}

/// A request's parameters, each given once: else which was given twice.
pub fn params(pairs: &[(String, String)]) -> Result<HashMap<String, String>, String> {
    let mut out = HashMap::new();
    for (k, v) in pairs {
        if out.insert(k.clone(), v.clone()).is_some() {
            return Err(format!("Parameter {k} is given more than once"));
        }
    }
    Ok(out)
}

/// `url` with `pairs` added to its query.
pub fn with_query(url: &str, pairs: &[(&str, &str)]) -> String {
    match Url::parse(url) {
        Ok(mut u) => {
            u.query_pairs_mut().extend_pairs(pairs);
            u.to_string()
        }
        Err(_) => url.to_string(),
    }
}

/// A JSON array of strings, as strings.
fn strings(v: Option<&Value>) -> Option<Vec<String>> {
    v?.as_array()?
        .iter()
        .map(|s| s.as_str().map(str::to_string))
        .collect()
}

/// An `http:` URL on `127.0.0.1`, `[::1]` or `localhost`, as the URL
/// standard writes each host.
fn loopback(u: &Url) -> bool {
    u.scheme() == "http" && matches!(u.host_str(), Some("127.0.0.1" | "[::1]" | "localhost"))
}

/// Whether a request sent back to `redirect` goes straight on to the
/// account's server, never showing HUD's page: where it is sent back to a
/// web client of an app whose file draws its own sign-in screen
/// (`domains`, the apps with a `signIn`), at that domain or one under it,
/// over https, or, where HUD may reach private addresses (a HUD for
/// development), on a loopback host. The page names the client so no
/// client rides the consent an account's server remembers; a code sent
/// back there reaches that app's own server alone, which drew the page
/// that asked for the account.
pub(crate) fn straight_on(redirect: &str, domains: &[String], allow_private: bool) -> bool {
    Url::parse(redirect).is_ok_and(|u| {
        let host = u.host_str().unwrap_or_default();
        let ours = domains
            .iter()
            .any(|d| host == d || host.ends_with(&format!(".{d}")));
        let web = u.scheme() == "https" && ours;
        !domains.is_empty() && (web || (allow_private && loopback(&u)))
    })
}

/// Whether a redirect URI is of a form a client may name: an `https:` URL;
/// an `http:` one on a loopback host; and, where `private_use`, a
/// private-use URI (RFC 8252 §7.1: a scheme of dotted labels, a colon, one
/// `/` and a path); none with a user, password or fragment.
fn redirect_form(uri: &str, private_use: bool) -> bool {
    let Ok(u) = Url::parse(uri) else { return false };
    if uri.len() > URI_MAX
        || !u.username().is_empty()
        || u.password().is_some()
        || u.fragment().is_some()
    {
        return false;
    }
    match u.scheme() {
        "https" => u.host().is_some(),
        "http" => loopback(&u),
        scheme => {
            let rest = &uri[scheme.len() + 1..];
            private_use
                && scheme.split('.').count() >= 2
                && scheme.split('.').all(|l| !l.is_empty())
                && rest.starts_with('/')
                && !rest.starts_with("//")
        }
    }
}

/// The redirect URI a request gets: the one given, if it matches one of
/// the client's, or its only one if none is given.
pub fn redirect_uri(mine: &[String], given: Option<&str>) -> Option<String> {
    match given {
        None => match mine {
            [only] => Some(only.clone()),
            _ => None,
        },
        Some(g) => mine.iter().any(|m| matches(m, g)).then(|| g.to_string()),
    }
}

/// Whether a redirect URI given matches one of the client's: equal, or
/// both on the same loopback host, the client's with no port, and equal but
/// for the port (RFC 8252 §7.3).
fn matches(mine: &str, given: &str) -> bool {
    if mine == given {
        return true;
    }
    let (Ok(m), Ok(mut g)) = (Url::parse(mine), Url::parse(given)) else {
        return false;
    };
    loopback(&m)
        && loopback(&g)
        && m.port().is_none()
        && g.set_port(None).is_ok()
        && m.as_str() == g.as_str()
}

/// The redirect URI a request of HUD's own app client gets: the one given
/// where it is a private-use URI whose path is `/oauth/callback` and no
/// more (each app on hudkit is sent back to its own application ID's
/// scheme, as `social.grain:/oauth/callback`, so two on one Android device
/// never both claim it), else `APP_REDIRECT` where none is given. Any app
/// may claim any scheme, so the scheme proves nothing of the app: PKCE
/// binds the code to the request, as with `APP_REDIRECT`.
pub(crate) fn app_redirect_uri(given: Option<&str>) -> Option<String> {
    let Some(g) = given else {
        return Some(super::APP_REDIRECT.to_string());
    };
    let ok = redirect_form(g, true)
        && Url::parse(g).is_ok_and(|u| {
            u.path() == "/oauth/callback" && u.query().is_none() && u.host().is_none()
        });
    ok.then(|| g.to_string())
}

/// A client ID that is a metadata document's URL, as one may be: `https`,
/// a domain name of two labels or more (not `localhost`, nor `.local`), no
/// port, user, password or fragment, a path that is not `/` and does not
/// end in `/`, written as the URL standard writes it.
fn document_url(id: &str) -> Option<Url> {
    let u = Url::parse(id).ok()?;
    let Some(Host::Domain(host)) = u.host() else {
        return None;
    };
    let ok = u.scheme() == "https"
        && u.as_str() == id
        && u.username().is_empty()
        && u.password().is_none()
        && u.fragment().is_none()
        && u.port().is_none()
        && u.path() != "/"
        && !u.path().ends_with('/')
        && host.contains('.')
        && !host.ends_with(".local")
        && !host.ends_with(".localhost");
    ok.then_some(u)
}

/// A client's name as shown: one line, at most 100 characters.
fn name_of(v: Option<&Value>) -> Option<String> {
    let n = v?.as_str()?.trim();
    (!n.is_empty() && !n.contains(char::is_control)).then(|| n.chars().take(NAME_MAX).collect())
}

/// A client metadata document fetched for `id`, held to MCP's rules, in
/// order: its own `client_id`; redirect URIs of the forms taken; a public
/// client; its grant and response types, if given, with the code's.
pub fn document_client(id: &str, doc: &Value) -> Result<Client, String> {
    let doc = doc.as_object().ok_or("its metadata is not a JSON object")?;
    if doc.get("client_id").and_then(Value::as_str) != Some(id) {
        return Err("its metadata's client_id is not its URL".into());
    }
    let redirect_uris = strings(doc.get("redirect_uris"))
        .filter(|r| !r.is_empty() && r.iter().all(|u| redirect_form(u, true)))
        .ok_or("its metadata's redirect_uris are not https, loopback or private-use URIs")?;
    if doc
        .get("token_endpoint_auth_method")
        .and_then(Value::as_str)
        != Some("none")
    {
        return Err("it is not a public client (token_endpoint_auth_method none)".into());
    }
    let listed = |k: &str, needed: &str| match doc.get(k) {
        None => Ok(None),
        v => strings(v)
            .filter(|l| l.iter().any(|t| t == needed))
            .map(Some)
            .ok_or(format!("its metadata's {k} lack {needed}")),
    };
    let grants = listed("grant_types", "authorization_code")?;
    listed("response_types", "code")?;
    Ok(Client {
        id: id.to_string(),
        name: name_of(doc.get("client_name")),
        redirect_uris,
        refresh: grants.is_some_and(|g| g.iter().any(|t| t == "refresh_token")),
    })
}

/// A dynamic registration's metadata (RFC 7591), checked: redirect URIs,
/// 1 to 10, https or loopback; a public client; grant types of the code's
/// and the refresh token's, by default the code's alone; the code's
/// response type; a name, one line. The client, less its id.
pub fn registration(body: &Value) -> Result<Client, Refused> {
    let bad = |why: &str| refused(400, "invalid_client_metadata", why);
    let o = body.as_object().ok_or_else(|| bad("Not a JSON object"))?;
    let redirect_uris = strings(o.get("redirect_uris"))
        .filter(|r| (1..=REDIRECTS_MAX).contains(&r.len()))
        .ok_or_else(|| bad("redirect_uris must be 1 to 10 URIs"))?;
    if !redirect_uris.iter().all(|u| redirect_form(u, false)) {
        return Err(refused(
            400,
            "invalid_redirect_uri",
            "Each redirect URI must be https, or http on a loopback host",
        ));
    }
    match o.get("token_endpoint_auth_method").map(Value::as_str) {
        None | Some(Some("none")) => {}
        _ => {
            return Err(bad(
                "Only public clients are registered: token_endpoint_auth_method none",
            ));
        }
    }
    let grants = match o.get("grant_types") {
        None => vec!["authorization_code".to_string()],
        v => strings(v)
            .filter(|g| {
                g.iter().any(|t| t == "authorization_code")
                    && g.iter()
                        .all(|t| matches!(t.as_str(), "authorization_code" | "refresh_token"))
            })
            .ok_or_else(|| bad("grant_types may be authorization_code and refresh_token"))?,
    };
    if let Some(r) = o.get("response_types")
        && strings(Some(r)).is_none_or(|r| r.is_empty() || r.iter().any(|t| t != "code"))
    {
        return Err(bad("response_types may be code alone"));
    }
    let name = match o.get("client_name") {
        None | Some(Value::Null) => None,
        v => Some(name_of(v).ok_or_else(|| bad("client_name must be one line of text"))?),
    };
    Ok(Client {
        id: String::new(),
        name,
        redirect_uris,
        refresh: grants.iter().any(|g| g == "refresh_token"),
    })
}

/// Whether `given` names the resource `<origin>/mcp`: equal to it, but for
/// its scheme and host, which may be in any case.
fn is_resource(origin: &str, given: &str) -> bool {
    let want = format!("{origin}/mcp");
    let (Some((ws, wrest)), Some((gs, grest))) = (want.split_once("://"), given.split_once("://"))
    else {
        return false;
    };
    let authority = |r: &str| r.find(['/', '?', '#']).unwrap_or(r.len());
    let (wa, wp) = wrest.split_at(authority(wrest));
    let (ga, gp) = grest.split_at(authority(grest));
    gs.eq_ignore_ascii_case(ws) && ga.eq_ignore_ascii_case(wa) && gp == wp
}

/// Whether a PKCE S256 challenge is of its form: 43 base64url characters.
fn is_challenge(c: &str) -> bool {
    c.len() == 43
        && c.bytes()
            .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
}

/// Give a session new MCP tokens: an access token, and a refresh token if
/// `refresh`. The tokens, to answer with once.
fn issue(s: &mut Session, refresh: bool, now: u64) -> (String, Option<String>) {
    let access = jose::random(32);
    s.mcp.access = jose::sha256(&access);
    s.mcp.access_exp = now + ACCESS_LIFE;
    let refresh = refresh.then(|| {
        let r = jose::random(32);
        s.mcp.refresh = Some(jose::sha256(&r));
        s.mcp.refresh_exp = now + REFRESH_LIFE;
        r
    });
    (access, refresh)
}

/// A token answer: the tokens, and the account's DID as `sub`.
fn answer(access: &str, refresh: Option<&str>, sub: &str) -> Value {
    let mut a = json!({
        "access_token": access,
        "token_type": "Bearer",
        "expires_in": ACCESS_LIFE,
        "scope": SCOPE,
        "sub": sub,
    });
    if let Some(r) = refresh {
        a["refresh_token"] = r.into();
    }
    a
}

impl Auth {
    /// A client's metadata document still kept.
    pub(super) fn kept_document(&self, id: &str) -> Option<Client> {
        let st = self.lock();
        st.documents
            .get(id)
            .filter(|(_, until)| *until > now())
            .map(|(c, _)| c.clone())
    }

    fn keep_document(&self, c: Client) {
        let mut st = self.lock();
        if st.documents.len() >= PENDING_MAX {
            let now = now();
            st.documents.retain(|_, (_, until)| *until > now);
        }
        if st.documents.len() < PENDING_MAX {
            st.documents
                .insert(c.id.clone(), (c, now() + DOCUMENT_KEEP));
        }
    }

    /// A client of the metadata document fetched for `id`, its answer
    /// checked: its own, JSON, a document of MCP's rules. Kept an hour.
    pub(super) fn fetched_document(
        &self,
        id: &str,
        got: Result<Fetched, Failure>,
    ) -> Result<Client, String> {
        let got = got.map_err(|why| format!("its metadata could not be read: {why}"))?;
        if got.redirected || got.status != 200 {
            return Err(format!(
                "its metadata could not be read (answered {}{})",
                got.status,
                if got.redirected { ", redirected" } else { "" }
            ));
        }
        let json_type = got
            .header("content-type")
            .and_then(|t| t.split(';').next())
            .is_some_and(|t| t.trim().eq_ignore_ascii_case("application/json"));
        if !json_type {
            return Err("its metadata is not application/json".into());
        }
        let doc: Value = serde_json::from_slice(&got.body)
            .map_err(|_| "its metadata is not JSON".to_string())?;
        let c = document_client(id, &doc)?;
        self.keep_document(c.clone());
        Ok(c)
    }

    /// Keep a sign-in waiting for its account to be named; its id.
    pub(crate) fn keep_request(&self, r: Asker) -> Result<String, String> {
        let mut st = self.lock();
        let now = now();
        st.requests.retain(|_, r| r.created() + PENDING_LIFE > now);
        if st.requests.len() >= PENDING_MAX {
            return Err("Too many sign-ins are waiting; try again in a few minutes".into());
        }
        let id = jose::random(16);
        st.requests.insert(id.clone(), r);
        Ok(id)
    }

    /// A request waiting, as its sign-in page shows it.
    pub fn pending(&self, id: &str) -> Option<Pending> {
        let st = self.lock();
        let r = st
            .requests
            .get(id)
            .filter(|r| r.created() + PENDING_LIFE > now())?;
        Some(match r {
            Asker::Mcp(r) => Pending {
                id: id.to_string(),
                client: r.client_name.clone(),
                login_hint: r.login_hint.clone(),
                straight: r.straight,
                create: r.create,
            },
            Asker::Web { .. } => Pending {
                id: id.to_string(),
                client: self.client.name.clone(),
                login_hint: None,
                straight: false,
                create: false,
            },
        })
    }

    /// A request waiting, taken for its sign-in at the PDS.
    pub(crate) fn take_request(&self, id: &str) -> Option<Asker> {
        self.lock()
            .requests
            .remove(id)
            .filter(|r| r.created() + PENDING_LIFE > now())
    }

    /// A request waiting whose sign-in failed, taken and sent back to its
    /// client saying why (`access_denied`), for a client that drew its own
    /// sign-in screen to show it there; none where it is gone.
    pub(crate) fn sent_back(&self, id: &str, why: &str) -> Option<String> {
        let Some(Asker::Mcp(r)) = self.take_request(id) else {
            return None;
        };
        let refused = [("error", "access_denied"), ("error_description", why)];
        Some(r.back(&self.origin, &refused))
    }

    /// Keep a code for a session signed in; the code.
    pub(crate) fn give_code(&self, request: &Request, session: Session) -> Result<String, String> {
        let mut st = self.lock();
        let now = now();
        st.codes.retain(|_, c| c.created + CODE_LIFE > now);
        if st.codes.len() >= PENDING_MAX {
            return Err("Too many sign-ins are waiting".into());
        }
        let code = jose::random(32);
        st.codes.insert(
            jose::sha256(&code),
            Code {
                client_id: request.client_id.clone(),
                redirect_uri: request.redirect_uri.clone(),
                challenge: request.challenge.clone(),
                session,
                refresh: request.refresh,
                created: now,
            },
        );
        Ok(code)
    }

    /// A client registered dynamically, kept on disk; its registration
    /// answer.
    pub fn register(&self, mut c: Client) -> Result<Value, Refused> {
        let mut st = self.lock();
        if st.registered.len() >= CLIENTS_MAX {
            return Err(refused(
                503,
                "temporarily_unavailable",
                "No more clients are registered here",
            ));
        }
        c.id = jose::random(16);
        let path = self.dir.join("clients").join(format!("{}.json", c.id));
        super::store::write_private(&path, c.to_json().to_string().as_bytes()).map_err(|e| {
            tracing::error!(error = %e, "could not keep a client");
            refused(500, "server_error", "The client could not be kept")
        })?;
        let mut out = c.to_json();
        out["client_id_issued_at"] = now().into();
        if c.name.is_none()
            && let Some(o) = out.as_object_mut()
        {
            o.remove("client_name");
        }
        tracing::info!(client = c.id, "client registered");
        st.registered.insert(c.id.clone(), c);
        Ok(out)
    }

    /// The code grant: the code, not spent, its client's, its redirect
    /// URI's, its PKCE verifier's; starts its session. A code used again
    /// ends the session it made.
    async fn code_grant(
        &self,
        client: &Client,
        p: &HashMap<String, String>,
    ) -> Result<Value, Refused> {
        let bad = |why: &str| refused(400, "invalid_grant", why);
        let hash = jose::sha256(&p["code"]);
        let now = now();
        let (code, spent) = {
            let mut st = self.lock();
            let code = st.codes.remove(&hash);
            let spent = st.spent.get(&hash).map(|(sid, _)| sid.clone());
            (code, spent)
        };
        let Some(code) = code.filter(|c| c.created + CODE_LIFE > now) else {
            if let Some(sid) = spent {
                self.end(&sid).await;
            }
            return Err(bad("The code is not one HUD gave, or was used, or expired"));
        };
        if code.client_id != client.id {
            return Err(bad("The code was given to another client"));
        }
        if code.redirect_uri != p["redirect_uri"] {
            return Err(bad("redirect_uri is not the request's"));
        }
        if jose::sha256(&p["code_verifier"]) != code.challenge {
            return Err(bad("code_verifier does not match the code_challenge"));
        }
        let mut s = code.session;
        let (access, refresh) = issue(&mut s, code.refresh && client.refresh, now);
        self.save(&s);
        {
            let mut st = self.lock();
            index(&mut st, &s);
            st.spent.insert(hash, (s.id.clone(), now + SPENT_LIFE));
        }
        tracing::info!(did = s.did, client = client.id, "signed in");
        Ok(answer(&access, refresh.as_deref(), &s.did))
    }

    /// The refresh grant: the session's current refresh token, its
    /// client's, unexpired; both tokens replaced. A replaced one, or another
    /// client's, ends the session.
    async fn refresh_grant(&self, client: &Client, token: &str) -> Result<Value, Refused> {
        let bad = |why: &str| refused(400, "invalid_grant", why);
        let hash = jose::sha256(token);
        // A token and its session are kept and forgotten together, under
        // one lock.
        let kept = {
            let st = self.lock();
            st.tokens.get(&hash).cloned().map(|k| {
                let cell = st.sessions.get(super::kept_sid(&k)).map(|l| l.cell.clone());
                (k, cell)
            })
        };
        let cell = match kept {
            Some((Kept::Refresh { .. }, Some(cell))) => cell,
            Some((Kept::Replaced { sid }, _)) => {
                self.end(&sid).await;
                return Err(bad("The refresh token was replaced; its session is ended"));
            }
            _ => return Err(bad("The refresh token is not one HUD gave, or expired")),
        };
        let mut s = cell.lock().await;
        let now = now();
        if s.ended {
            return Err(bad("The session is ended"));
        }
        if s.mcp.refresh.as_deref() != Some(&hash) {
            self.end_locked(&mut s);
            return Err(bad("The refresh token was replaced; its session is ended"));
        }
        if s.client_id != client.id {
            self.end_locked(&mut s);
            return Err(bad("The refresh token is another client's"));
        }
        if s.mcp.refresh_exp <= now {
            self.end_locked(&mut s);
            return Err(bad("The refresh token expired"));
        }
        s.mcp.replace(hash);
        let (access, refresh) = issue(&mut s, true, now);
        self.save(&s);
        index(&mut self.lock(), &s);
        Ok(answer(&access, refresh.as_deref(), &s.did))
    }
}

/// A new session's MCP part, filled when its code is exchanged.
pub(crate) fn unissued() -> Mcp {
    Mcp {
        access: String::new(),
        access_exp: 0,
        refresh: None,
        refresh_exp: 0,
        replaced: Vec::new(),
    }
}

impl Hud {
    /// An MCP client: HUD's own iOS app, whose document HUD serves and so
    /// reads without fetching itself; its metadata document, fetched or
    /// kept, for another `https://` client ID; else one registered here.
    pub async fn mcp_client(&self, id: &str) -> Result<Client, String> {
        let auth = self.auth()?;
        if !id.starts_with("https://") {
            return auth
                .lock()
                .registered
                .get(id)
                .cloned()
                .ok_or_else(|| "it is not a client registered here".into());
        }
        if id == auth.app_client_id() {
            return document_client(id, &auth.app_client_metadata());
        }
        if let Some(c) = auth.kept_document(id) {
            return Ok(c);
        }
        let url = document_url(id).ok_or("it is not a client metadata document's URL")?;
        let got = self.net.fetch_json(&url, DOCUMENT_WAIT, DOCUMENT_MAX).await;
        auth.fetched_document(id, got)
    }

    /// `GET /oauth/authorize`: the request checked in order (its client,
    /// its redirect URI; then, sent back to the client, its response type,
    /// PKCE, resource, scope, login hint and state), and kept for the
    /// sign-in page.
    pub async fn authorize(&self, query: &[(String, String)]) -> Result<Pending, NotAuthorized> {
        let auth = self.auth().map_err(NotAuthorized::Page)?;
        let p = params(query).map_err(NotAuthorized::Page)?;
        let text = |k: &str| p.get(k).map(String::as_str).filter(|v| !v.is_empty());
        // 1. Its client.
        let client_id =
            text("client_id").ok_or_else(|| NotAuthorized::Page("client_id is required".into()))?;
        let client = self
            .mcp_client(client_id)
            .await
            .map_err(|why| NotAuthorized::Page(format!("Invalid client_id: {why}")))?;
        // 2. Its redirect URI.
        let redirect_uri = if client.id == auth.app_client_id() {
            app_redirect_uri(text("redirect_uri"))
        } else {
            redirect_uri(&client.redirect_uris, text("redirect_uri"))
        }
        .ok_or_else(|| NotAuthorized::Page("redirect_uri is not one of the client's".into()))?;
        // Past those, a refusal goes back to the client.
        let state = text("state").filter(|s| s.len() <= STATE_MAX);
        let domains = crate::view::views().sign_ins();
        let straight = client.id == auth.app_client_id()
            || straight_on(&redirect_uri, domains, self.config.allow_private);
        let mut request = Request {
            client_id: client.id.clone(),
            client_name: client.shown(),
            redirect_uri,
            state: state.map(str::to_string),
            challenge: String::new(),
            login_hint: None,
            create: false,
            straight,
            refresh: client.refresh,
            created: now(),
        };
        let refuse = |error: &str, why: &str| {
            NotAuthorized::Redirect(request.back(
                &auth.origin,
                &[("error", error), ("error_description", why)],
            ))
        };
        if text("state").is_some_and(|s| s.len() > STATE_MAX) {
            return Err(refuse("invalid_request", "state is too long"));
        }
        // 3-6.
        if text("response_type") != Some("code") {
            return Err(refuse(
                "unsupported_response_type",
                "Only the code response type is supported",
            ));
        }
        let Some(challenge) = text("code_challenge")
            .filter(|c| is_challenge(c))
            .filter(|_| text("code_challenge_method") == Some("S256"))
        else {
            return Err(refuse(
                "invalid_request",
                "code_challenge is required, with code_challenge_method S256",
            ));
        };
        if !text("resource").is_some_and(|r| is_resource(&auth.origin, r)) {
            return Err(refuse(
                "invalid_target",
                "resource must be this server's MCP endpoint",
            ));
        }
        if !matches!(p.get("scope").map(|s| s.trim()), None | Some("" | SCOPE)) {
            return Err(refuse("invalid_scope", "The one scope offered is hud"));
        }
        let hint = text("login_hint").map(|h| h.trim().trim_start_matches('@').to_lowercase());
        if hint
            .as_deref()
            .is_some_and(|h| !atproto::syntax::is_handle(h) && !atproto::syntax::is_did(h))
        {
            return Err(refuse(
                "invalid_request",
                "login_hint is neither a handle nor a DID",
            ));
        }
        request.challenge = challenge.to_string();
        request.login_hint = hint;
        request.create = text("prompt").is_some_and(|p| p.split(' ').any(|v| v == "create"));
        let shown = request.client_name.clone();
        let login_hint = request.login_hint.clone();
        let (create, straight) = (request.create, request.straight);
        let id = auth
            .keep_request(Asker::Mcp(request))
            .map_err(NotAuthorized::Page)?;
        Ok(Pending {
            id,
            client: shown,
            login_hint,
            straight,
            create,
        })
    }

    /// `GET /oauth/authorize`: the request checked and kept (`authorize`);
    /// then, for a client that names the account itself (`straight_on`:
    /// HUD's own app, or a web client of an app that draws its own sign-in
    /// screen) asking for a new account (`prompt=create`), straight on to
    /// the sign-up PDS's server, or naming its account as a login hint, to
    /// that account's; where that fails, sent back to the client saying why
    /// (`access_denied`), for it to show on its own screen; else the
    /// sign-in page. Any other client's always gets the page: it names the
    /// client, and skipping it would let any client ride the consent the
    /// account's server remembers.
    pub async fn begin_sign_in(
        &self,
        query: &[(String, String)],
    ) -> Result<Authorized, NotAuthorized> {
        let pending = self.authorize(query).await?;
        let went = if pending.straight && pending.create {
            self.sign_up(&pending.id).await
        } else if let Some(hint) = pending.login_hint.clone().filter(|_| pending.straight) {
            self.sign_in(&pending.id, &hint).await
        } else {
            return Ok(Authorized::Page(pending));
        };
        let expired =
            || NotAuthorized::Page("This sign-in has expired; start again from your app".into());
        match went {
            Ok(to) => Ok(Authorized::Server(to)),
            Err(SignIn::Failed(_, why)) => {
                let back = self
                    .auth()
                    .ok()
                    .and_then(|a| a.sent_back(&pending.id, &why));
                Err(back.map_or_else(expired, NotAuthorized::Redirect))
            }
            Err(SignIn::Expired) => Err(expired()),
        }
    }

    /// `POST /workspace/signin`: the workspace's sign-in as `login`, a
    /// handle or DID, sent on to its account's server: the URL of that
    /// server's authorization page; else why not, in words for a person.
    pub async fn web_sign_in(&self, login: &str) -> Result<String, String> {
        self.web_begin(Some(login)).await
    }

    /// `POST /workspace/signin`, `{"create": true}`: the workspace's
    /// "Create one", sent on to the sign-up PDS's server (`sign_up`): the
    /// URL of its page; else why not, in words for a person.
    pub async fn web_sign_up(&self) -> Result<String, String> {
        self.web_begin(None).await
    }

    /// The workspace's sign-in as `login`, or with none a new account's.
    async fn web_begin(&self, login: Option<&str>) -> Result<String, String> {
        let auth = self.auth()?;
        let id = auth.keep_request(Asker::Web { created: now() })?;
        let went = match login {
            Some(login) => self.sign_in(&id, login).await,
            None => self.sign_up(&id).await,
        };
        went.map_err(|e| {
            auth.take_request(&id);
            match e {
                SignIn::Failed(_, why) => why,
                SignIn::Expired => "This sign-in took too long; try again".into(),
            }
        })
    }

    /// `POST /workspace/signout`: the web session a cookie names ends, its
    /// atproto refresh token revoked at its server first where that has a
    /// revocation endpoint. Nothing for any other value.
    pub async fn sign_out(&self, cookie: &str) {
        let Ok(auth) = self.auth() else { return };
        let Some(account) = auth.web_account(cookie) else {
            return;
        };
        let mut s = account.session.lock().await;
        if s.ended {
            return;
        }
        self.revoke_at_server(auth, &mut s).await;
        auth.end_locked(&mut s);
    }

    /// Every session of `did` ends, web, MCP and app alike, each one's
    /// atproto refresh token revoked at its server first where that has a
    /// revocation endpoint, as `sign_out` does: how many ended.
    pub async fn sign_out_everywhere(&self, did: &str) -> usize {
        let Ok(auth) = self.auth() else { return 0 };
        let cells: Vec<_> = auth
            .lock()
            .sessions
            .values()
            .filter(|l| l.did == did)
            .map(|l| l.cell.clone())
            .collect();
        let mut ended = 0;
        for cell in cells {
            let mut s = cell.lock().await;
            if s.ended {
                continue;
            }
            self.revoke_at_server(auth, &mut s).await;
            auth.end_locked(&mut s);
            ended += 1;
        }
        tracing::info!(did, ended, "every session of an account ended");
        ended
    }

    /// `POST /oauth/token`: the code grant or the refresh grant, checked in
    /// order (the body; its client; the grant and its parameters; the
    /// resource, if given).
    pub async fn token(&self, pairs: &[(String, String)]) -> Result<Value, Refused> {
        let auth = self
            .auth()
            .map_err(|why| refused(400, "invalid_request", why))?;
        let p = params(pairs).map_err(|why| refused(400, "invalid_request", why))?;
        let filled = |k: &str| p.get(k).is_some_and(|v| !v.is_empty());
        if !filled("client_id") {
            return Err(refused(400, "invalid_request", "client_id is required"));
        }
        let client = self
            .mcp_client(&p["client_id"])
            .await
            .map_err(|_| refused(400, "invalid_client", "Invalid client_id"))?;
        let grant = p.get("grant_type").map(String::as_str);
        match grant {
            Some("authorization_code")
                if filled("code") && filled("redirect_uri") && filled("code_verifier") => {}
            Some("refresh_token") if filled("refresh_token") => {}
            None | Some("authorization_code" | "refresh_token") => {
                return Err(refused(
                    400,
                    "invalid_request",
                    "grant_type and its parameters are required",
                ));
            }
            Some(_) => {
                return Err(refused(
                    400,
                    "unsupported_grant_type",
                    "Unsupported grant_type",
                ));
            }
        }
        if p.get("resource")
            .is_some_and(|r| !is_resource(&auth.origin, r))
        {
            return Err(refused(
                400,
                "invalid_target",
                "resource must be this server's MCP endpoint",
            ));
        }
        if grant == Some("authorization_code") {
            return auth.code_grant(&client, &p).await;
        }
        if !client.refresh {
            return Err(refused(
                400,
                "unauthorized_client",
                "The client does not have the refresh_token grant",
            ));
        }
        auth.refresh_grant(&client, &p["refresh_token"]).await
    }

    /// `POST /oauth/revoke` (RFC 7009): the session an MCP token is of
    /// ends, if it is the client's that names itself (a `client_id` left
    /// out names none), its atproto refresh token revoked at its server
    /// first where that has a revocation endpoint. Answered alike whatever
    /// the token.
    pub async fn revoke(&self, pairs: &[(String, String)]) -> Result<(), Refused> {
        let auth = self
            .auth()
            .map_err(|why| refused(400, "invalid_request", why))?;
        let p = params(pairs).map_err(|why| refused(400, "invalid_request", why))?;
        let Some(token) = p.get("token").filter(|t| !t.is_empty()) else {
            return Err(refused(400, "invalid_request", "token is required"));
        };
        if !p
            .get("token_type_hint")
            .is_none_or(|h| matches!(h.as_str(), "access_token" | "refresh_token"))
        {
            return Err(refused(
                400,
                "invalid_request",
                "token_type_hint must be access_token or refresh_token",
            ));
        }
        // A web session's cookie is not a token this endpoint takes.
        let kept = auth.lock().tokens.get(&jose::sha256(token)).cloned();
        let Some(sid) = kept
            .filter(|k| !matches!(k, Kept::Web { .. }))
            .map(|k| super::kept_sid(&k).to_string())
        else {
            return Ok(());
        };
        let cell = auth.lock().sessions.get(&sid).map(|l| l.cell.clone());
        let Some(cell) = cell else { return Ok(()) };
        let mut s = cell.lock().await;
        if s.ended
            || p.get("client_id")
                .is_some_and(|c| !c.is_empty() && *c != s.client_id)
        {
            return Ok(());
        }
        self.revoke_at_server(auth, &mut s).await;
        auth.end_locked(&mut s);
        Ok(())
    }

    /// `POST /oauth/register`: a client registered, kept on disk.
    pub fn register(&self, body: &[u8]) -> Result<Value, Refused> {
        let auth = self
            .auth()
            .map_err(|why| refused(400, "invalid_request", why))?;
        let body: Value = serde_json::from_slice(body)
            .map_err(|_| refused(400, "invalid_client_metadata", "Not JSON"))?;
        auth.register(registration(&body)?)
    }
}

/// The params of a form body, or of a JSON object's string fields.
pub fn body_params(
    content_type: Option<&str>,
    body: &[u8],
) -> Result<Vec<(String, String)>, Refused> {
    let kind = content_type
        .and_then(|t| t.split(';').next())
        .map(|t| t.trim().to_ascii_lowercase());
    match kind.as_deref() {
        Some("application/x-www-form-urlencoded") => Ok(url::form_urlencoded::parse(body)
            .map(|(k, v)| (k.into_owned(), v.into_owned()))
            .collect()),
        Some("application/json") => {
            let v: Map<String, Value> = serde_json::from_slice(body)
                .map_err(|_| refused(400, "invalid_request", "The body is not a JSON object"))?;
            Ok(v.into_iter()
                .filter_map(|(k, v)| Some((k, v.as_str()?.to_string())))
                .collect())
        }
        _ => Err(refused(
            400,
            "invalid_request",
            "The body must be a form or JSON",
        )),
    }
}

#[cfg(test)]
pub(crate) mod tests {
    use super::*;

    /// Straight on: sent back to an app's own domain, or one under it, over
    /// https; on a loopback host only where HUD reaches private addresses;
    /// never with no app drawing its own sign-in screen.
    #[test]
    fn straight_on_its_apps_domains() {
        let grain = ["grain.social".to_string()];
        for (redirect, private, straight) in [
            ("https://grain.social/auth/callback", false, true),
            ("https://next.grain.social/auth/callback", false, true),
            ("http://next.grain.social/auth/callback", false, false),
            ("https://notgrain.social/cb", false, false),
            ("https://grain.social.evil.test/cb", false, false),
            ("http://localhost:5173/auth/callback", true, true),
            ("http://localhost:5173/auth/callback", false, false),
            ("place.hud.app:/oauth/callback", true, false),
            ("not a url", true, false),
        ] {
            assert_eq!(
                straight_on(redirect, &grain, private),
                straight,
                "{redirect} {private}"
            );
        }
        assert!(!straight_on("https://grain.social/cb", &[], true));
        assert!(!straight_on("http://localhost/cb", &[], true));
    }

    #[test]
    fn redirect_uris_and_forms() {
        assert!(redirect_form(
            "https://claude.ai/api/mcp/auth_callback",
            true
        ));
        assert!(redirect_form("http://localhost/callback", false));
        assert!(redirect_form("http://127.0.0.1:3000/cb", false));
        assert!(redirect_form("com.example.app:/cb", true));
        assert!(!redirect_form("com.example.app:/cb", false));
        assert!(!redirect_form("com.example.app://cb", true));
        assert!(!redirect_form("http://example.com/cb", true));
        assert!(!redirect_form("https://u:p@example.com/cb", true));
        assert!(!redirect_form("https://example.com/cb#x", true));
        let mine = vec!["http://localhost/cb".to_string()];
        assert_eq!(
            redirect_uri(&mine, Some("http://localhost:5173/cb")).as_deref(),
            Some("http://localhost:5173/cb")
        );
        assert_eq!(
            redirect_uri(&mine, Some("http://localhost:5173/other")),
            None
        );
        assert_eq!(
            redirect_uri(&mine, None).as_deref(),
            Some("http://localhost/cb")
        );
        let two = vec!["https://a.example/cb".into(), "https://b.example/cb".into()];
        assert_eq!(redirect_uri(&two, None), None);
        for (given, ok) in [
            (None, Some(super::super::APP_REDIRECT)),
            (
                Some("place.hud.app:/oauth/callback"),
                Some("place.hud.app:/oauth/callback"),
            ),
            (
                Some("social.grain:/oauth/callback"),
                Some("social.grain:/oauth/callback"),
            ),
            (
                Some("social.grain.debug:/oauth/callback"),
                Some("social.grain.debug:/oauth/callback"),
            ),
            (Some("social.grain:/oauth/other"), None),
            (Some("social.grain:/oauth/callback?x=1"), None),
            (Some("social.grain://oauth/callback"), None),
            (Some("grain:/oauth/callback"), None),
            (Some("https://evil.example/oauth/callback"), None),
            (Some("http://localhost/oauth/callback"), None),
        ] {
            assert_eq!(app_redirect_uri(given).as_deref(), ok, "{given:?}");
        }
    }

    #[test]
    fn documents_checked() {
        let id = "https://client.example/meta.json";
        let good = json!({ "client_id": id, "client_name": "Client\u{7}",
            "redirect_uris": ["https://client.example/cb"],
            "token_endpoint_auth_method": "none",
            "grant_types": ["authorization_code", "refresh_token"] });
        let c = document_client(id, &good).unwrap();
        assert!(c.refresh);
        assert_eq!(c.name, None, "a name with a control character is not shown");
        assert_eq!(c.shown(), "client.example");
        for (k, v) in [
            ("client_id", json!("https://client.example/other.json")),
            ("redirect_uris", json!([])),
            ("redirect_uris", json!(["http://client.example/cb"])),
            ("token_endpoint_auth_method", json!("private_key_jwt")),
            ("grant_types", json!(["refresh_token"])),
            ("response_types", json!(["token"])),
        ] {
            let mut bad = good.clone();
            bad[k] = v;
            assert!(document_client(id, &bad).is_err(), "{k}");
        }
        let mut no_method = good.clone();
        no_method
            .as_object_mut()
            .unwrap()
            .remove("token_endpoint_auth_method");
        assert!(document_client(id, &no_method).is_err());
        assert!(document_url(id).is_some());
        for bad in [
            "https://client.example/",
            "https://client.example:8443/m.json",
            "https://localhost/m.json",
            "https://1.2.3.4/m.json",
            "https://box.local/m.json",
            "http://client.example/m.json",
            "https://client.example/m.json#x",
            "https://client.example/a/../m.json",
        ] {
            assert!(document_url(bad).is_none(), "{bad}");
        }
    }

    #[test]
    fn registrations_checked() {
        let c = registration(&json!({ "redirect_uris": ["https://chatgpt.com/cb"],
            "client_name": "ChatGPT", "grant_types": ["authorization_code", "refresh_token"],
            "token_endpoint_auth_method": "none", "response_types": ["code"] }))
        .unwrap();
        assert!(c.refresh);
        assert_eq!(c.name.as_deref(), Some("ChatGPT"));
        // Left out, the grant types are the code's alone.
        let c = registration(&json!({ "redirect_uris": ["http://127.0.0.1/cb"] })).unwrap();
        assert!(!c.refresh);
        let err = |v: Value| registration(&v).unwrap_err().error;
        assert_eq!(
            err(json!({ "redirect_uris": ["http://evil.example/cb"] })),
            "invalid_redirect_uri"
        );
        assert_eq!(
            err(json!({ "redirect_uris": ["com.example.app:/cb"] })),
            "invalid_redirect_uri"
        );
        assert_eq!(err(json!({})), "invalid_client_metadata");
        assert_eq!(err(json!([])), "invalid_client_metadata");
        assert_eq!(
            err(json!({ "redirect_uris": ["https://a.example/cb"],
                        "token_endpoint_auth_method": "client_secret_basic" })),
            "invalid_client_metadata"
        );
        assert_eq!(
            err(json!({ "redirect_uris": ["https://a.example/cb"], "grant_types": ["implicit"] })),
            "invalid_client_metadata"
        );
        assert_eq!(
            err(json!({ "redirect_uris": ["https://a.example/cb"], "client_name": "a\nb" })),
            "invalid_client_metadata"
        );
        assert_eq!(
            err(json!({ "redirect_uris": ["https://a.example/cb"], "response_types": ["token"] })),
            "invalid_client_metadata"
        );
        // Loopback is 127.0.0.1, [::1] or localhost, as the URL standard
        // writes each, by any port.
        for uri in [
            "http://[::1]:8080/cb",
            "http://127.1/cb",
            "http://LOCALHOST/cb",
        ] {
            assert!(
                registration(&json!({ "redirect_uris": [uri] })).is_ok(),
                "{uri}"
            );
        }
        assert_eq!(
            err(json!({ "redirect_uris": ["http://[::2]/cb"] })),
            "invalid_redirect_uri"
        );
    }

    #[test]
    fn resources_and_params() {
        assert!(is_resource(
            "https://hud.example",
            "https://hud.example/mcp"
        ));
        assert!(is_resource(
            "https://hud.example",
            "HTTPS://HUD.Example/mcp"
        ));
        assert!(!is_resource(
            "https://hud.example",
            "https://hud.example/MCP"
        ));
        assert!(!is_resource("https://hud.example", "https://hud.example"));
        assert!(!is_resource(
            "https://hud.example",
            "https://other.example/mcp"
        ));
        assert!(!is_resource("https://hud.example", "hud.example/mcp"));
        let pairs = |p: &[(&str, &str)]| -> Vec<(String, String)> {
            p.iter()
                .map(|(k, v)| (k.to_string(), v.to_string()))
                .collect()
        };
        assert!(params(&pairs(&[("a", "1"), ("a", "2")])).is_err());
        assert_eq!(
            with_query("https://c.example/cb?x=1", &[("code", "c d")]),
            "https://c.example/cb?x=1&code=c+d"
        );
        assert_eq!(with_query("not a url", &[("code", "c")]), "not a url");
        assert_eq!(
            body_params(
                Some("application/json; charset=utf-8"),
                br#"{"a":"1","n":2}"#
            )
            .unwrap(),
            pairs(&[("a", "1")])
        );
        assert_eq!(
            body_params(Some("application/x-www-form-urlencoded"), b"a=1&b=%20").unwrap(),
            pairs(&[("a", "1"), ("b", " ")])
        );
        assert!(body_params(Some("text/plain"), b"").is_err());
        assert_eq!(
            body_params(Some("application/json"), b"[\"a\"]")
                .unwrap_err()
                .description,
            "The body is not a JSON object"
        );
    }
}