~ 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
775 lines · 28.7 KB Raw History
//! Sign-in. HUD plays two OAuth roles, chained: the authorization server of
//! its own MCP endpoint, whose clients are MCP hosts (`issuer`), and a
//! confidential atproto OAuth client of each account's own server
//! (`client`). A host sends a person to `/oauth/authorize`; they name their
//! account; HUD signs them in at their PDS (PAR, PKCE, DPoP,
//! `private_key_jwt`), keeps that session, and gives the host a code for
//! tokens of HUD's own, opaque, good for `/mcp` alone. A call with one is
//! the account's: writes, and queries through its PDS.
//!
//! The workspace's page signs in the same way, by `POST /workspace/signin`
//! with the handle, with no MCP client and no page of HUD's: back from the
//! PDS, its session is a web session, named by a cookie HUD gives the
//! browser (30 days), good for the workspace's API alone, never as a
//! bearer token on `/mcp`. A web session and an MCP session of one account
//! are two sessions. HUD's own app, naming its account as a login hint,
//! goes straight on to the account's server too; asking for a new account
//! (`prompt=create`), or the workspace's `{"create": true}`, goes on to
//! the sign-up PDS's (`client::Hud::sign_up`).
//!
//! Kept on disk under `<HUD_DATA_DIR>/oauth/`, each file mode 0600, written
//! whole and renamed into place (`store`): `client-key.json`, HUD's ES256
//! signing key as a private JWK, made on first start; `sessions/<sha256 of
//! its id>.json`, each session, with its atproto tokens and DPoP key and the
//! SHA-256 of its MCP tokens or its cookie (never those); `clients/<id>.json`,
//! the clients registered dynamically. In memory: the index of those
//! hashes to sessions, built from the sessions at start; requests waiting
//! for their sign-in and HUD's codes, ten minutes at most; the client
//! metadata documents fetched, an hour. Tokens are never logged.

pub mod client;
pub mod issuer;
pub(crate) mod store;

#[cfg(test)]
mod tests;

use crate::Hud;
use crate::tools::Refusal;
use atproto::jose;
use atproto::keys::{Curve, Keypair};
use issuer::{Client, Code, Request};
use serde_json::{Value, json};
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::{Arc, Mutex, MutexGuard};
use std::time::{SystemTime, UNIX_EPOCH};
use store::{Kind, Session};

/// How long an MCP access token is good for.
pub const ACCESS_LIFE: u64 = 3600;
/// How long an MCP refresh token is good for, from its rotation.
pub const REFRESH_LIFE: u64 = 30 * 86_400;
/// The one scope HUD's own tokens carry.
pub const SCOPE: &str = "hud";
/// Where HUD's iOS app is sent back to: a private-use URI of its bundle
/// identifier (RFC 8252 §7.1). An app on hudkit (Android) names its own,
/// `<application ID>:/oauth/callback` (`issuer::app_redirect_uri`).
pub const APP_REDIRECT: &str = "place.hud.app:/oauth/callback";
/// How long a web session's cookie is good for.
pub const WEB_LIFE: u64 = 30 * 86_400;
/// The name of a web session's cookie.
pub const COOKIE: &str = "hud_session";
/// How long a request waits for its sign-in, at HUD and at the PDS.
const PENDING_LIFE: u64 = 600;
/// How long a code HUD gave waits for its exchange.
const CODE_LIFE: u64 = 300;
/// How long a spent code is remembered, to end its session if used again.
const SPENT_LIFE: u64 = 3600;
/// The most requests, sign-ins in progress and codes kept at once.
const PENDING_MAX: usize = 10_000;
/// What the workspace's methods answer a call refused for want of scope
/// from someone who signed in before HUD asked for what it asks now.
pub const SIGN_IN_AGAIN: &str =
    "HUD asks for more now than when you signed in: sign in again to allow this";

/// How long a sign-in that asked for a permission set holds it as its
/// server last resolved it, at most: a server keeps a set it resolved up
/// to a day (as atproto's permission sets allow), and some expand it once,
/// as the sign-in is approved (pds.js, zds). A sign-in older than this
/// that is refused for want of scope signs in again, for the set as it is
/// now (`Hud::scope_refused`).
pub const SET_FRESH: u64 = 86_400;

/// Seconds since 1970.
pub fn now() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map_or(0, |d| d.as_secs())
}

/// What a hash of one of HUD's tokens names.
#[derive(Clone, Debug, PartialEq)]
enum Kept {
    /// A session's current access token, until it expires.
    Access { sid: String, exp: u64 },
    /// A session's current refresh token.
    Refresh { sid: String },
    /// A refresh token rotated out: used again, it ends its session.
    Replaced { sid: String },
    /// A web session's cookie, until it expires.
    Web { sid: String, exp: u64 },
}

/// Whom a sign-in is for: an MCP client's authorization request, or the
/// workspace's page.
#[derive(Clone, Debug)]
pub(crate) enum Asker {
    Mcp(Request),
    Web { created: u64 },
}

impl Asker {
    fn created(&self) -> u64 {
        match self {
            Asker::Mcp(r) => r.created,
            Asker::Web { created } => *created,
        }
    }
}

/// A sign-in in progress at an account's PDS, by its `state`.
pub(crate) struct Flow {
    pub asker: Asker,
    /// The PKCE verifier sent with the code's exchange.
    pub verifier: String,
    /// The session's DPoP key, from PAR on.
    pub dpop: Keypair,
    pub server: client::Server,
    /// The account named: the token's `sub` must be it. None for a new
    /// account ("Create one"), whose `sub` is whichever was made.
    pub did: Option<String>,
    /// The last DPoP nonce its server gave.
    pub nonce: Option<String>,
    /// The scope its request asked for: with permission sets, or what the
    /// views do where its server refused them.
    pub asked: String,
    pub created: u64,
}

/// A session kept, with who it is, which never changes, to name it without
/// waiting for its lock.
struct Live {
    did: String,
    handle: Option<String>,
    cell: Arc<tokio::sync::Mutex<Session>>,
}

/// What sign-in keeps in memory, under one lock held briefly.
#[derive(Default)]
struct State {
    sessions: HashMap<String, Live>,
    /// HUD's tokens and cookies by their SHA-256.
    tokens: HashMap<String, Kept>,
    /// Sign-ins waiting for their account to be named, by id.
    requests: HashMap<String, Asker>,
    /// Sign-ins in progress at accounts' PDSes, by `state`.
    flows: HashMap<String, Flow>,
    /// Codes HUD gave, by their SHA-256.
    codes: HashMap<String, Code>,
    /// Codes exchanged, by their SHA-256: the session each made, and until
    /// when it is remembered.
    spent: HashMap<String, (String, u64)>,
    /// Client metadata documents fetched, and until when each is kept.
    documents: HashMap<String, (Client, u64)>,
    /// Clients registered dynamically, by id.
    registered: HashMap<String, Client>,
}

/// Sign-in's state: HUD's client key, and the sessions and the rest.
pub struct Auth {
    /// HUD's origin: the MCP issuer, and the atproto client's.
    pub origin: String,
    /// The atproto scope of what the views do (`Config::oauth_scope`).
    pub scope: String,
    /// What is asked first, with permission sets (`Config::oauth_include`).
    pub include: Option<String>,
    /// The name and logo accounts' servers show for HUD as their client.
    pub client: crate::config::Client,
    dir: PathBuf,
    key: Keypair,
    kid: String,
    state: Mutex<State>,
}

/// A signed-in account, as a call made with its MCP token is made.
#[derive(Clone)]
pub struct Account {
    pub did: String,
    pub handle: Option<String>,
    session: Arc<tokio::sync::Mutex<Session>>,
}

impl std::fmt::Debug for Account {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Account({})", self.did)
    }
}

impl Account {
    /// `_meta.viewer`: who the call was made as.
    pub fn viewer(&self) -> Value {
        json!({ "did": self.did, "handle": self.handle })
    }
}

/// A session of an account's to call its PDS with where no request names
/// one, as for the canvases kept there: its account, a name for it that
/// another sign-in changes, its PDS, and the scope it was granted.
#[derive(Clone, Debug)]
pub(crate) struct Reach {
    pub account: Account,
    pub key: String,
    pub pds: String,
    pub scope: String,
}

impl Auth {
    /// Sign-in's state for the server at `origin`, under `data_dir`: its
    /// client key, made if there is none, and the sessions kept, those
    /// past their time deleted.
    pub fn open(origin: &str, scope: &str, data_dir: &std::path::Path) -> Result<Auth, String> {
        let dir = data_dir.join("oauth");
        let key_path = dir.join("client-key.json");
        let key = match std::fs::read(&key_path) {
            Ok(bytes) => serde_json::from_slice::<Value>(&bytes)
                .ok()
                .and_then(|jwk| store::key_from_jwk(&jwk))
                .ok_or_else(|| format!("{} is not a P-256 private JWK", key_path.display()))?,
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
                let key = Keypair::generate(Curve::P256);
                let kid = jose::thumbprint(&key.public());
                store::write_private(
                    &key_path,
                    store::key_to_jwk(&key, &kid).to_string().as_bytes(),
                )
                .map_err(|e| format!("keeping {}: {e}", key_path.display()))?;
                tracing::info!(kid, "made the OAuth client key");
                key
            }
            Err(e) => return Err(format!("reading {}: {e}", key_path.display())),
        };
        let kid = jose::thumbprint(&key.public());
        let auth = Auth {
            origin: origin.to_string(),
            scope: scope.to_string(),
            include: None,
            client: crate::config::Client::default(),
            dir,
            key,
            kid,
            state: Mutex::new(State::default()),
        };
        auth.load();
        Ok(auth)
    }

    fn lock(&self) -> MutexGuard<'_, State> {
        self.state
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
    }

    /// Read the sessions and registered clients kept on disk.
    fn load(&self) {
        let now = now();
        let mut st = self.lock();
        for path in json_files(&self.dir.join("sessions")) {
            let session = std::fs::read(&path)
                .ok()
                .and_then(|b| serde_json::from_slice::<Value>(&b).ok())
                .and_then(|v| Session::from_json(&v));
            match session {
                Some(s) if !past(&s, now) => index(&mut st, &s),
                Some(_) => {
                    let _ = std::fs::remove_file(&path);
                }
                None => tracing::warn!(path = %path.display(), "not a session; left as it is"),
            }
        }
        for path in json_files(&self.dir.join("clients")) {
            let client = std::fs::read(&path)
                .ok()
                .and_then(|b| serde_json::from_slice::<Value>(&b).ok())
                .and_then(|v| Client::from_json(&v));
            match client {
                Some(c) => {
                    st.registered.insert(c.id.clone(), c);
                }
                None => tracing::warn!(path = %path.display(), "not a client; left as it is"),
            }
        }
        let (sessions, clients) = (st.sessions.len(), st.registered.len());
        tracing::info!(sessions, clients, "sign-ins loaded");
    }

    /// HUD's atproto `client_id`: its client metadata's URL.
    pub fn client_id(&self) -> String {
        format!("{}/oauth/client-metadata.json", self.origin)
    }

    /// Where accounts' servers send people back.
    pub fn redirect_uri(&self) -> String {
        format!("{}/oauth/callback", self.origin)
    }

    /// The MCP endpoint: the resource HUD's tokens are for.
    pub fn resource(&self) -> String {
        format!("{}/mcp", self.origin)
    }

    /// `/.well-known/oauth-protected-resource[/mcp]`.
    pub fn protected_resource(&self) -> Value {
        json!({
            "resource": self.resource(),
            "authorization_servers": [self.origin],
            "scopes_supported": [SCOPE],
            "bearer_methods_supported": ["header"],
        })
    }

    /// `/.well-known/oauth-authorization-server`: HUD as the MCP endpoint's
    /// authorization server.
    pub fn authorization_server(&self) -> Value {
        let o = &self.origin;
        json!({
            "issuer": o,
            "authorization_endpoint": format!("{o}/oauth/authorize"),
            "token_endpoint": format!("{o}/oauth/token"),
            "revocation_endpoint": format!("{o}/oauth/revoke"),
            "registration_endpoint": format!("{o}/oauth/register"),
            "scopes_supported": [SCOPE],
            "response_types_supported": ["code"],
            "response_modes_supported": ["query"],
            "grant_types_supported": ["authorization_code", "refresh_token"],
            "code_challenge_methods_supported": ["S256"],
            "token_endpoint_auth_methods_supported": ["none"],
            "client_id_metadata_document_supported": true,
            "authorization_response_iss_parameter_supported": true,
            "protected_resources": [self.resource()],
        })
    }

    /// `/oauth/client-metadata.json`: HUD as an atproto OAuth client, a
    /// confidential one, under the name and logo it is configured with. Its
    /// scope is all HUD may ask for: with permission sets, and without, as
    /// it asks a server that refuses them.
    pub fn client_metadata(&self) -> Value {
        let mut scope: Vec<&str> = self.include.iter().flat_map(|i| i.split(' ')).collect();
        let direct = self.scope.split(' ').filter(|t| !scope.contains(t));
        scope.extend(direct.collect::<Vec<_>>());
        let mut doc = json!({
            "client_id": self.client_id(),
            "client_name": self.client.name,
            "client_uri": self.origin,
            "application_type": "web",
            "grant_types": ["authorization_code", "refresh_token"],
            "response_types": ["code"],
            "redirect_uris": [self.redirect_uri()],
            "scope": scope.join(" "),
            "token_endpoint_auth_method": "private_key_jwt",
            "token_endpoint_auth_signing_alg": "ES256",
            "jwks_uri": format!("{}/oauth/jwks.json", self.origin),
            "dpop_bound_access_tokens": true,
        });
        if let Some(logo) = &self.client.logo {
            doc["logo_uri"] = logo.as_str().into();
        }
        doc
    }

    /// `/oauth/jwks.json`: HUD's public client key.
    pub fn jwks(&self) -> Value {
        let mut jwk = jose::jwk(&self.key.public());
        jwk["kid"] = self.kid.clone().into();
        jwk["alg"] = "ES256".into();
        jwk["use"] = "sig".into();
        json!({ "keys": [jwk] })
    }

    /// The iOS app's MCP `client_id`: its metadata's URL, a document HUD
    /// serves itself (`app_client_metadata`), so the app needs no host of
    /// its own and no registration.
    pub fn app_client_id(&self) -> String {
        format!("{}/oauth/app-client.json", self.origin)
    }

    /// `/oauth/app-client.json`: HUD's apps as a public MCP client, sent
    /// back at a private-use redirect URI (RFC 8252 §7.1): iOS's
    /// `ASWebAuthenticationSession` catches `APP_REDIRECT`; an Android app
    /// names its own `<application ID>:/oauth/callback`, which the client's
    /// requests may (`issuer::app_redirect_uri`).
    pub fn app_client_metadata(&self) -> Value {
        json!({
            "client_id": self.app_client_id(),
            "client_name": "HUD for iOS",
            "client_uri": self.origin,
            "application_type": "native",
            "grant_types": ["authorization_code", "refresh_token"],
            "response_types": ["code"],
            "redirect_uris": [APP_REDIRECT],
            "token_endpoint_auth_method": "none",
        })
    }

    fn session_path(&self, sid: &str) -> PathBuf {
        self.dir
            .join("sessions")
            .join(format!("{}.json", jose::sha256(sid)))
    }

    /// Keep a session on disk: one live, its lock held by the caller, or not
    /// yet kept. A failure is logged: the session goes on in memory.
    pub(crate) fn save(&self, s: &Session) {
        let path = self.session_path(&s.id);
        if let Err(e) = store::write_private(&path, s.to_json().to_string().as_bytes()) {
            tracing::error!(did = s.did, error = %e, "could not keep a session");
        }
    }

    /// End a session whose lock the caller holds: forgotten in memory, and
    /// its file deleted.
    pub(crate) fn end_locked(&self, s: &mut Session) {
        s.ended = true;
        let _ = std::fs::remove_file(self.session_path(&s.id));
        let mut st = self.lock();
        st.sessions.remove(&s.id);
        st.tokens.retain(|_, k| kept_sid(k) != s.id);
        tracing::info!(did = s.did, "session ended");
    }

    /// End the session `sid`, if it is still kept.
    pub(crate) async fn end(&self, sid: &str) {
        let cell = self.lock().sessions.get(sid).map(|l| l.cell.clone());
        if let Some(cell) = cell {
            let mut s = cell.lock().await;
            if !s.ended {
                self.end_locked(&mut s);
            }
        }
    }

    /// The account an MCP access token is the current one of, unexpired;
    /// none for any other token.
    pub fn account(&self, token: &str) -> Option<Account> {
        let hash = jose::sha256(token);
        let st = self.lock();
        let Some(Kept::Access { sid, exp }) = st.tokens.get(&hash) else {
            return None;
        };
        if *exp <= now() {
            return None;
        }
        let live = st.sessions.get(sid)?;
        Some(Account {
            did: live.did.clone(),
            handle: live.handle.clone(),
            session: live.cell.clone(),
        })
    }

    /// The account a web session's cookie is the cookie of, unexpired; none
    /// for any other value.
    pub fn web_account(&self, cookie: &str) -> Option<Account> {
        let hash = jose::sha256(cookie);
        let st = self.lock();
        let Some(Kept::Web { sid, exp }) = st.tokens.get(&hash) else {
            return None;
        };
        if *exp <= now() {
            return None;
        }
        let live = st.sessions.get(sid)?;
        Some(Account {
            did: live.did.clone(),
            handle: live.handle.clone(),
            session: live.cell.clone(),
        })
    }

    /// Start a web session, signed in at its PDS: its cookie, to give the
    /// browser once.
    pub(crate) fn start_web(&self, mut s: Session) -> String {
        let cookie = jose::random(32);
        s.kind = Kind::Web;
        s.mcp.access = jose::sha256(&cookie);
        s.mcp.access_exp = now() + WEB_LIFE;
        self.save(&s);
        index(&mut self.lock(), &s);
        tracing::info!(did = s.did, "signed in on the web");
        cookie
    }

    /// A session for `did`, as if it had signed in at a PDS HUD never
    /// calls: a web session's cookie, or an MCP session's access token. For
    /// tests of what a session is used for, past its sign-in.
    #[cfg(any(test, feature = "testing"))]
    pub fn signed_in_offline(&self, did: &str, handle: Option<&str>, web: bool) -> String {
        self.signed_in_offline_at(did, handle, web, "https://pds.invalid")
    }

    /// As `signed_in_offline`, its PDS `pds`: for tests of what is sent
    /// there as the account, against a fake one.
    #[cfg(any(test, feature = "testing"))]
    pub fn signed_in_offline_at(
        &self,
        did: &str,
        handle: Option<&str>,
        web: bool,
        pds: &str,
    ) -> String {
        self.signed_in_offline_asking(did, handle, web, pds, &self.scope)
    }

    /// As `signed_in_offline_at`, signed in asking for `asked`: for tests
    /// of a sign-in made before HUD asked for what it asks now.
    #[cfg(any(test, feature = "testing"))]
    pub fn signed_in_offline_asking(
        &self,
        did: &str,
        handle: Option<&str>,
        web: bool,
        pds: &str,
        asked: &str,
    ) -> String {
        let s = Session {
            id: jose::random(32),
            did: did.to_string(),
            handle: handle.map(str::to_string),
            pds: pds.into(),
            issuer: pds.into(),
            token_endpoint: format!("{pds}/oauth/token"),
            revocation_endpoint: None,
            scope: asked.into(),
            asked: asked.into(),
            access_token: jose::random(16),
            refresh_token: None,
            expires_at: now() + 3600,
            dpop: Keypair::generate(Curve::P256),
            nonces: Default::default(),
            client_id: String::new(),
            kind: Kind::Mcp,
            mcp: issuer::unissued(),
            created_at: now(),
            ended: false,
        };
        if web {
            return self.start_web(s);
        }
        let mut s = s;
        let access = jose::random(32);
        s.mcp.access = jose::sha256(&access);
        s.mcp.access_exp = now() + ACCESS_LIFE;
        self.save(&s);
        index(&mut self.lock(), &s);
        access
    }

    /// As `signed_in_offline_at`, an MCP session of HUD's own app
    /// (`app_client_id`), its access token.
    #[cfg(any(test, feature = "testing"))]
    pub fn signed_in_offline_app(&self, did: &str, handle: Option<&str>, pds: &str) -> String {
        self.signed_in_offline_client(did, handle, pds, &self.app_client_id())
    }

    /// As `signed_in_offline_at`, an MCP session of the client
    /// `client_id`, its access token.
    #[cfg(any(test, feature = "testing"))]
    pub fn signed_in_offline_client(
        &self,
        did: &str,
        handle: Option<&str>,
        pds: &str,
        client_id: &str,
    ) -> String {
        let access = self.signed_in_offline_at(did, handle, false, pds);
        let account = self.account(&access).expect("just signed in");
        account
            .session
            .try_lock()
            .expect("held by no one yet")
            .client_id = client_id.to_string();
        access
    }

    /// Whether an account's session is one of HUD's own app's, rather than
    /// another MCP client's.
    pub async fn from_app(&self, account: &Account) -> bool {
        account.session.lock().await.client_id == self.app_client_id()
    }

    /// The operator's web app's MCP `client_id`: its metadata document at
    /// HUD's own origin, `/client-metadata.json`, which only that app
    /// answers (`HUD_WEB`, as `@hud/shell` serves it), HUD answering
    /// nothing there itself.
    pub fn web_client_id(&self) -> String {
        format!("{}/client-metadata.json", self.origin)
    }

    /// Whether an account's session is the operator's own: a workspace
    /// page's (its cookie), HUD's own app's, or the operator's web app's
    /// (`web_client_id`), rather than another MCP client's.
    pub async fn from_own_client(&self, account: &Account) -> bool {
        let s = account.session.lock().await;
        let own = [self.app_client_id(), self.web_client_id()];
        s.kind == Kind::Web || own.contains(&s.client_id)
    }

    /// Prune what has expired, and end the sessions past their time.
    pub async fn sweep(&self) {
        let now = now();
        let cells: Vec<Arc<tokio::sync::Mutex<Session>>> = {
            let mut st = self.lock();
            st.requests.retain(|_, r| r.created() + PENDING_LIFE > now);
            st.flows.retain(|_, f| f.created + PENDING_LIFE > now);
            st.codes.retain(|_, c| c.created + CODE_LIFE > now);
            st.spent.retain(|_, (_, until)| *until > now);
            st.documents.retain(|_, (_, until)| *until > now);
            st.sessions.values().map(|l| l.cell.clone()).collect()
        };
        for cell in cells {
            let mut s = cell.lock().await;
            if !s.ended && past(&s, now) {
                self.end_locked(&mut s);
            }
        }
    }

    /// The newest live session of `did` whose granted scope `fits`, else
    /// its newest; none if it has none.
    pub(crate) async fn reach(&self, did: &str, fits: impl Fn(&str) -> bool) -> Option<Reach> {
        let lives: Vec<(String, Option<String>, Arc<tokio::sync::Mutex<Session>>)> = self
            .lock()
            .sessions
            .iter()
            .filter(|(_, l)| l.did == did)
            .map(|(sid, l)| (sid.clone(), l.handle.clone(), l.cell.clone()))
            .collect();
        let now = now();
        let mut best: Option<((bool, u64), Reach)> = None;
        for (sid, handle, cell) in lives {
            let s = cell.lock().await;
            if s.ended || past(&s, now) {
                continue;
            }
            let rank = (fits(&s.scope), s.created_at);
            if best.as_ref().is_none_or(|(r, _)| rank > *r) {
                let reach = Reach {
                    account: Account {
                        did: did.to_string(),
                        handle,
                        session: cell.clone(),
                    },
                    key: jose::sha256(&sid),
                    pds: s.pds.clone(),
                    scope: s.scope.clone(),
                };
                best = Some((rank, reach));
            }
        }
        best.map(|(_, r)| r)
    }
}

/// Whether a session is past its time: its refresh token expired, or with
/// none, its access token.
fn past(s: &Session, now: u64) -> bool {
    match s.mcp.refresh {
        Some(_) => s.mcp.refresh_exp <= now,
        None => s.mcp.access_exp <= now,
    }
}

/// The session a token's entry names.
fn kept_sid(k: &Kept) -> &str {
    match k {
        Kept::Access { sid, .. }
        | Kept::Refresh { sid }
        | Kept::Replaced { sid }
        | Kept::Web { sid, .. } => sid,
    }
}

/// Put a session and its tokens in the index, in place of what was there:
/// an MCP session's tokens, or a web session's cookie.
fn index(st: &mut State, s: &Session) {
    st.tokens.retain(|_, k| kept_sid(k) != s.id);
    let sid = || s.id.clone();
    match s.kind {
        Kind::Web => {
            st.tokens.insert(
                s.mcp.access.clone(),
                Kept::Web {
                    sid: sid(),
                    exp: s.mcp.access_exp,
                },
            );
        }
        Kind::Mcp => {
            st.tokens.insert(
                s.mcp.access.clone(),
                Kept::Access {
                    sid: sid(),
                    exp: s.mcp.access_exp,
                },
            );
            if let Some(r) = &s.mcp.refresh {
                st.tokens.insert(r.clone(), Kept::Refresh { sid: sid() });
            }
            for r in &s.mcp.replaced {
                st.tokens.insert(r.clone(), Kept::Replaced { sid: sid() });
            }
        }
    }
    st.sessions.entry(s.id.clone()).or_insert_with(|| Live {
        did: s.did.clone(),
        handle: s.handle.clone(),
        cell: Arc::new(tokio::sync::Mutex::new(s.clone())),
    });
}

/// The `.json` files of a directory; none if it cannot be read.
fn json_files(dir: &std::path::Path) -> Vec<PathBuf> {
    let Ok(entries) = std::fs::read_dir(dir) else {
        return Vec::new();
    };
    entries
        .filter_map(|e| e.ok().map(|e| e.path()))
        .filter(|p| p.extension().is_some_and(|x| x == "json"))
        .collect()
}

impl Hud {
    /// Sign-in's state, or why there is none.
    pub fn auth(&self) -> Result<&Auth, String> {
        self.oauth
            .as_ref()
            .ok_or_else(|| "Sign-in is off on this server".to_string())
    }

    /// Whether `account` signed in asking for less than HUD asks for now
    /// (`scope::behind`): signing in again grants the rest. A sign-in that
    /// asked for permission sets is held to what HUD asks with them; one
    /// that did not, to what the views do, as HUD asks a server that
    /// refuses sets.
    pub async fn behind(&self, account: &Account) -> bool {
        let Some(auth) = &self.oauth else {
            return false;
        };
        let then = account.session.lock().await.asked.clone();
        let now = match &auth.include {
            Some(include) if crate::scope::includes(&then) => include,
            _ => &auth.scope,
        };
        crate::scope::behind(&then, now)
    }

    /// What a PDS's refusal of a call as `account` for want of `scope`
    /// (`ScopeMissingError`) answers. Signed in before HUD asked for what
    /// it asks now, or with a permission set more than `SET_FRESH` ago,
    /// which a set grown since may grant, signing in again
    /// (`Refusal::SignIn`: an MCP host's 401 challenge; the workspace's
    /// methods say `SIGN_IN_AGAIN`, as their page and app offer it). Else
    /// the sign-in does not allow it, which signing in again would not
    /// change.
    pub async fn scope_refused(&self, account: &Account, scope: &str) -> Refusal {
        let stale = {
            let s = account.session.lock().await;
            crate::scope::includes(&s.asked) && s.created_at + SET_FRESH < now()
        };
        match stale || self.behind(account).await {
            true => Refusal::SignIn,
            false => Refusal::Error(format!("Your sign-in does not allow {scope}")),
        }
    }
}