~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0
2366 lines · 85.4 KB Raw History
//! OAuth: the server as authorization server for its own accounts, as
//! `spec/OAUTH.md` says: its metadata, loopback clients, pushed
//! authorization requests, the authorization page and its API (`page`),
//! the pages' build, embedded and served (`assets`),
//! the token and revocation endpoints, DPoP (`dpop`), the check every
//! XRPC call with an OAuth access token makes of it (`access`), the
//! account's own routes listing and ending its sessions and devices
//! (`account`), and passkeys, which sign an account in on the page and
//! which those routes add, list and remove (`passkeys`).
//!
//! What it keeps, its requests, codes, sessions and the accounts signed in
//! on each device, is one `State` behind one lock: it is not any one
//! account's, as a request is no account's until it is approved. Each
//! change is an entry in `accounts.log` (`ENTRIES`), appended under that
//! lock so that the log has the changes in the order they were made, in one
//! frame with the single-use values (`replay`) the request spent; it is
//! answered once that frame is on disk, waited for with no lock held. Tokens,
//! nonces, device cookies and ephemeral tokens are sealed with a secret kept
//! in `PDS_DATA_DIR/oauth.key`, so the server checks them without keeping
//! them: a session keeps only the ids of its current tokens.
//!
//! A DPoP proof is spent in memory as soon as it passes (`dpop::Spent`), and
//! kept in the log only with what its request kept, once that passed its
//! token or grant; a refused request's proof is held in memory alone, and
//! writes nothing. PAR keeps at most so many requests pending (`Pending`),
//! and below the free-space floor (`low`) nothing that would keep anything
//! is taken.

pub(crate) mod account;
mod assets;
mod client;
mod clients;
mod dpop;
pub(crate) mod mcp;
mod page;
pub(crate) mod passkeys;
mod scope;
mod sets;
pub(crate) mod space_scope;
#[cfg(test)]
pub(crate) mod tests;

pub(crate) use clients::ClientFetch;

use crate::{Service, Shared, durable};
use axum::{
    Extension, Router,
    body::{Body, Bytes},
    extract::State as AxState,
    http::{HeaderMap, HeaderValue, Method, StatusCode, header},
    response::{IntoResponse, Response},
    routing::{any, get},
};
use base64::Engine;
use base64::engine::general_purpose::URL_SAFE_NO_PAD as B64;
use hmac::{Hmac, Mac};
use serde_json::{Value as Json, json};
use sha2::{Digest, Sha256};
use std::collections::HashMap;
use std::io::Write;
use std::path::Path;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Mutex, MutexGuard, PoisonError};

/// The kinds of `accounts.log` entry this module keeps.
pub(crate) const ENTRIES: &[&str] = &[
    "oauthRequest",
    "oauthLoad",
    "oauthApprove",
    "oauthEndRequest",
    "oauthSpendCode",
    "oauthSession",
    "oauthRefresh",
    "oauthEndSession",
    "oauthSignIn",
    "oauthSignOut",
    "oauthDeviceKey",
    "oauthDeviceEnd",
    "oauthForgetClients",
    "oauthPasskeyAdd",
    "oauthPasskeyUse",
    "oauthPasskeyRemove",
];

/// What a change of an account's ends of what OAuth keeps of it (`OAuth::end_for`).
#[derive(Clone, Copy, Debug, Default)]
pub(crate) struct Ends {
    /// Its sessions.
    pub sessions: bool,
    /// The requests approved for it whose codes were not yet exchanged.
    pub requests: bool,
    /// The clients it approved, for silent sign-in.
    pub clients: bool,
    /// Its sign-ins on every device.
    pub devices: bool,
    /// Its passkeys, and its link to add one.
    pub passkeys: bool,
    /// Everything, logging nothing: it was deleted.
    pub account: bool,
}

/// OAuth's entries, in order, without those of the accounts `gone`, which
/// were deleted: their sessions with their refreshes and ends, the requests
/// approved for them from start to end with their codes, and their sign-ins
/// and sign-outs. Replayed, they make what replaying all of them and
/// `forget_account` of each makes.
pub(crate) fn without_accounts(
    entries: Vec<Json>,
    gone: &std::collections::HashSet<String>,
) -> Vec<Json> {
    if gone.is_empty() {
        return entries;
    }
    let of_gone = |e: &Json| e["did"].as_str().is_some_and(|d| gone.contains(d));
    let text = |e: &Json, k: &str| e[k].as_str().unwrap_or_default().to_string();
    let (mut requests, mut codes, mut sids) = (
        std::collections::HashSet::new(),
        std::collections::HashSet::new(),
        std::collections::HashSet::new(),
    );
    for e in entries.iter().filter(|e| of_gone(e)) {
        match e["t"].as_str() {
            Some("oauthApprove") => {
                requests.insert(text(e, "id"));
                codes.insert(text(e, "code"));
            }
            Some("oauthSession") => {
                sids.insert(text(e, "sid"));
                codes.insert(text(e, "code"));
            }
            _ => {}
        }
    }
    entries
        .into_iter()
        .filter(|e| {
            let dropped = match e["t"].as_str() {
                Some("oauthRequest" | "oauthLoad" | "oauthApprove" | "oauthEndRequest") => {
                    requests.contains(e["id"].as_str().unwrap_or_default())
                }
                Some("oauthSpendCode") => codes.contains(e["code"].as_str().unwrap_or_default()),
                Some("oauthSession" | "oauthRefresh" | "oauthEndSession") => {
                    sids.contains(e["sid"].as_str().unwrap_or_default())
                }
                _ => false,
            };
            !dropped && !of_gone(e)
        })
        .collect()
}

/// The file in the data directory that holds the secret OAuth's tokens, nonces and cookies are sealed with.
const KEY_FILE: &str = "oauth.key";

/// How long a pushed request lasts, and an authorization page keeps it.
const REQUEST_LIFE: u64 = 300;
/// How long a code may be exchanged.
const CODE_LIFE: u64 = 300;
/// How long an access token works.
const ACCESS_LIFE: u64 = 900;
/// How long a session lasts from when it started.
const SESSION_LIFE: u64 = 14 * 24 * 60 * 60;
/// How long an ephemeral sign-in lasts.
const EPHEMERAL_LIFE: u64 = 15 * 60;
/// How long an account signed in on a device needs no new sign-in.
const LOGIN_LIFE: u64 = 7 * 24 * 60 * 60;
/// How long a client's `state`, and an exchanged code's challenge, are held.
const HELD_LIFE: u64 = 24 * 60 * 60;
/// How long a request is kept past its time, so that it is refused as past its time.
const KEEP_PAST: u64 = 60 * 60;
/// The namespace of the single-use values clients' `state`s are kept in.
const STATE_NS: &str = "state";
/// The most requests pending from one client address, and from all.
const PENDING_PER_ADDRESS: usize = 1000;
const PENDING_ALL: usize = 20000;
/// The longest body PAR, and the authorization page's API, read.
pub(crate) const BODY_MAX: usize = 102400;
/// The longest body the token and revocation endpoints read.
const OTHER_BODY_MAX: usize = 2 << 20;

const REQUEST_URI: &str = "urn:ietf:params:oauth:request_uri:";

/// The labels a session's access and refresh tokens are sealed for: an MCP
/// session's apart from an atproto one's, so that neither issuer, nor XRPC,
/// takes the other's (`spec/OAUTH-MCP.md`).
fn labels(mcp: bool) -> (&'static str, &'static str) {
    if mcp {
        ("mcp access", "mcp refresh")
    } else {
        ("access", "refresh")
    }
}

/// A pushed authorization request, as kept.
#[derive(Clone, Debug, PartialEq, Eq)]
struct Request {
    client_id: String,
    redirect_uri: String,
    /// The scopes kept of it, each once, in the order first given.
    scope: Vec<String>,
    state: String,
    code_challenge: String,
    login_hint: Option<String>,
    /// Kept as given for a confidential client, which may sign in
    /// silently; for a public one, `consent` or `create`.
    prompt: Option<String>,
    response_mode: String,
    ui_locales: Option<String>,
    /// The thumbprint of the client's DPoP key: `dpop_jkt`, or else the
    /// PAR's proof's; none for a PAR with neither, which the code grant then
    /// binds to its token request's key (`spec/OAUTH.md`, PAR step 4). Empty
    /// for an MCP issuer's request, which binds no key.
    jkt: Option<String>,
    expires: u64,
    /// The device it was loaded on.
    device: Option<String>,
    approval: Option<Approval>,
    /// The id of the key a confidential client authenticated with, which
    /// the request, and then its session, is bound to.
    client_key: Option<String>,
    /// The client address it was pushed from (`pending_key`), if kept.
    addr: Option<String>,
    /// The resource an MCP issuer's request is for (`spec/OAUTH-MCP.md`):
    /// set, it is the MCP issuer's, and has no DPoP key.
    resource: Option<String>,
}

impl Request {
    /// Whether it is the MCP issuer's.
    fn mcp(&self) -> bool {
        self.resource.is_some()
    }
}

/// The requests kept and pending, not yet approved, ended or past their
/// time, by the client address each came from (`pending_key`): at most
/// `per_address` from one, and `all` from all together. Kept with the
/// requests, as replayed, and past their time forgotten at each change.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct Pending {
    /// Each pending request's address and time.
    of: HashMap<String, (String, u64)>,
    /// How many are pending from each address.
    per: HashMap<String, usize>,
    /// The same requests, soonest past their time first.
    by_time: std::collections::BTreeSet<(u64, String)>,
    per_address: usize,
    all: usize,
}

impl Default for Pending {
    fn default() -> Pending {
        Pending::new(PENDING_PER_ADDRESS, PENDING_ALL)
    }
}

impl Pending {
    pub fn new(per_address: usize, all: usize) -> Pending {
        Pending {
            of: HashMap::new(),
            per: HashMap::new(),
            by_time: Default::default(),
            per_address,
            all,
        }
    }

    pub fn add(&mut self, id: &str, addr: &str, expires: u64) {
        self.remove(id);
        self.of.insert(id.to_string(), (addr.to_string(), expires));
        *self.per.entry(addr.to_string()).or_default() += 1;
        self.by_time.insert((expires, id.to_string()));
    }

    /// A pending request's new time.
    pub fn extend(&mut self, id: &str, expires: u64) {
        if let Some((_, t)) = self.of.get_mut(id) {
            self.by_time.remove(&(*t, id.to_string()));
            *t = expires;
            self.by_time.insert((expires, id.to_string()));
        }
    }

    /// A request no longer pending: approved, ended or forgotten.
    pub fn remove(&mut self, id: &str) {
        let Some((addr, t)) = self.of.remove(id) else {
            return;
        };
        self.by_time.remove(&(t, id.to_string()));
        if let Some(n) = self.per.get_mut(&addr) {
            *n -= 1;
            if *n == 0 {
                self.per.remove(&addr);
            }
        }
    }

    /// Forget the requests past their time at `now`.
    pub fn expire(&mut self, now: u64) {
        while let Some((t, id)) = self.by_time.first().cloned()
            && t <= now
        {
            self.remove(&id);
        }
    }

    /// Why one more request from `addr` may not be kept, if it may not.
    pub fn full(&self, addr: &str) -> Option<&'static str> {
        if self.per.get(addr).is_some_and(|n| *n >= self.per_address) {
            return Some("Too many pending authorization requests from this address");
        }
        (self.of.len() >= self.all).then_some("Too many pending authorization requests")
    }

    #[cfg(test)]
    pub fn len(&self) -> usize {
        self.of.len()
    }
}

/// The key a client address counts pending requests by: an IPv6 address by
/// its first 64 bits, an IPv4 address as it is, anything else (no address,
/// or what a proxy forwarded that is none) by a digest of it, so that each
/// is short.
fn pending_key(client: &str) -> String {
    match client
        .parse::<std::net::IpAddr>()
        .map(|ip| ip.to_canonical())
    {
        Ok(std::net::IpAddr::V4(a)) => a.to_string(),
        Ok(std::net::IpAddr::V6(a)) => {
            let s = a.segments();
            format!("{:x}:{:x}:{:x}:{:x}::/64", s[0], s[1], s[2], s[3])
        }
        Err(_) => format!("#{}", hex::encode(&Sha256::digest(client.as_bytes())[..16])),
    }
}

/// A request's approval, and its code.
#[derive(Clone, Debug, PartialEq, Eq)]
struct Approval {
    code: String,
    did: String,
    scope: Vec<String>,
    at: u64,
}

/// A session the token endpoint started.
#[derive(Clone, Debug, PartialEq, Eq)]
struct Session {
    did: String,
    client_id: String,
    jkt: String,
    /// Its scope as consented, `include:` tokens and all.
    scope: Vec<String>,
    /// Its scope expanded (`sets::expand`): what its tokens allow, and what
    /// its token answers say.
    granted: Vec<String>,
    started: u64,
    /// The code it was made from.
    code: String,
    /// The ids of its current tokens.
    access: String,
    access_exp: u64,
    refresh: String,
    /// The key a confidential client's session is bound to.
    client_key: Option<String>,
    /// Its last token answer.
    refreshed: u64,
    /// Whether it is the MCP issuer's (`spec/OAUTH-MCP.md`): no DPoP key,
    /// and tokens for the MCP endpoint alone.
    mcp: bool,
}

impl Session {
    /// When it ends: two weeks after it started, or for a confidential
    /// client 730 days after, or 90 days after its last token answer.
    fn end(&self) -> u64 {
        match self.client_key {
            Some(_) => (self.started + clients::CONFIDENTIAL_LIFE)
                .min(self.refreshed + clients::CONFIDENTIAL_IDLE),
            None => self.started + SESSION_LIFE,
        }
    }
}

/// Where an account signed in on a device from, as the sign-in's API call
/// came (`spec/OAUTH-ACCOUNT.md`, "_oauthDevices"): its `User-Agent`, its
/// first 256 characters, and its client address, each if it had one, or
/// none for a sign-in kept before they were.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
struct Whence {
    user_agent: Option<String>,
    address: Option<String>,
}

impl Whence {
    /// Of a request with these headers, from client address `client`
    /// (`crate::limits::client`, empty for none).
    fn of(headers: &HeaderMap, client: &str) -> Whence {
        Whence {
            user_agent: headers.get(header::USER_AGENT).map(|v| {
                String::from_utf8_lossy(v.as_bytes())
                    .chars()
                    .take(256)
                    .collect()
            }),
            address: Some(client.to_string()).filter(|c| !c.is_empty()),
        }
    }

    /// An `oauthSignIn` entry's, as kept: each field left out if it is not there.
    fn kept(e: &Json) -> Whence {
        let text = |k: &str| e[k].as_str().map(str::to_string);
        Whence {
            user_agent: text("userAgent"),
            address: text("ipAddress"),
        }
    }

    /// Its fields, into an `oauthSignIn` entry, or a device as
    /// `_oauthDevices` answers it, which name them alike.
    fn fill(&self, e: &mut Json) {
        if let Some(a) = &self.user_agent {
            e["userAgent"] = json!(a);
        }
        if let Some(a) = &self.address {
            e["ipAddress"] = json!(a);
        }
    }
}

/// Everything OAuth keeps.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(crate) struct State {
    requests: HashMap<String, Request>,
    /// Each approved request's code, and its request: spending a code ends its request.
    codes: HashMap<String, String>,
    sessions: HashMap<String, Session>,
    /// Each session's code, and the session.
    by_code: HashMap<String, String>,
    /// The accounts signed in on each device, with when.
    devices: HashMap<String, Vec<(String, u64)>>,
    /// Where each account signed in on each device signed in from, by
    /// device and account, for those signed in from somewhere kept.
    whence: HashMap<(String, String), Whence>,
    /// Each device's cookies' key since a sign-in last gave it new ones,
    /// and when: cookies of another key are old (`spec/OAUTH.md`, "Devices").
    device_keys: HashMap<String, (String, u64)>,
    /// The discoverable clients each account approved, with every scope
    /// token it approved each for: `approved[did][client_id]`.
    approved: HashMap<String, HashMap<String, Vec<String>>>,
    /// The requests pending, by client address.
    pending: Pending,
    /// The passkeys, and the accounts' user handles.
    passkeys: passkeys::Kept,
}

fn strings(v: &Json) -> Option<Vec<String>> {
    v.as_array()?
        .iter()
        .map(|s| s.as_str().map(str::to_string))
        .collect()
}

impl State {
    /// Make the change an entry says, as it is logged and as it is replayed;
    /// `is_account` says whether a DID is an account's.
    fn apply(&mut self, e: &Json, is_account: &dyn Fn(&str) -> bool) -> Result<(), String> {
        let text = |k: &str| {
            e[k].as_str()
                .map(str::to_string)
                .ok_or_else(|| format!("an entry with no {k}: {e}"))
        };
        let opt_text = |k: &str| e[k].as_str().map(str::to_string);
        let number = |k: &str| {
            e[k].as_u64()
                .ok_or_else(|| format!("an entry with no {k}: {e}"))
        };
        let list = |k: &str| strings(&e[k]).ok_or_else(|| format!("an entry with no {k}: {e}"));
        let account = |k: &str| {
            text(k).and_then(|d| {
                if is_account(&d) {
                    Ok(d)
                } else {
                    Err(format!("an entry of {d:?}, which no account has: {e}"))
                }
            })
        };
        match e["t"].as_str() {
            Some("oauthRequest") => {
                let id = text("id")?;
                if self.requests.contains_key(&id) {
                    return Err(format!("a second request {id}"));
                }
                let r = Request {
                    client_id: text("client")?,
                    redirect_uri: text("redirectUri")?,
                    scope: list("scope")?,
                    state: text("state")?,
                    code_challenge: text("codeChallenge")?,
                    login_hint: opt_text("loginHint"),
                    prompt: opt_text("prompt"),
                    response_mode: text("responseMode")?,
                    ui_locales: opt_text("uiLocales"),
                    jkt: opt_text("jkt"),
                    expires: number("expires")?,
                    device: None,
                    approval: None,
                    client_key: opt_text("clientKey"),
                    addr: opt_text("addr"),
                    resource: opt_text("resource"),
                };
                // A request kept before addresses were is counted as of no address.
                self.pending
                    .add(&id, r.addr.as_deref().unwrap_or_default(), r.expires);
                self.requests.insert(id, r);
            }
            Some("oauthLoad") => {
                let id = text("id")?;
                let r = self
                    .requests
                    .get_mut(&id)
                    .ok_or_else(|| format!("a load of request {id}, which is not kept"))?;
                r.device = Some(text("device")?);
                r.expires = number("expires")?;
                self.pending.extend(&id, r.expires);
            }
            Some("oauthApprove") => {
                let (id, code) = (text("id")?, text("code")?);
                let r = self
                    .requests
                    .get_mut(&id)
                    .ok_or_else(|| format!("an approval of request {id}, which is not kept"))?;
                if r.approval.is_some() || self.codes.contains_key(&code) {
                    return Err(format!("a second approval of request {id}"));
                }
                let did = account("did")?;
                let scope = list("scope")?;
                r.approval = Some(Approval {
                    code: code.clone(),
                    did: did.clone(),
                    scope: scope.clone(),
                    at: number("at")?,
                });
                self.codes.insert(code, id.clone());
                self.pending.remove(&id);
                // A discoverable client's approval is kept, for silent sign-in;
                // an MCP client's signs it in to nothing.
                if clients::discoverable(&r.client_id) && !r.mcp() {
                    let tokens = self
                        .approved
                        .entry(did)
                        .or_default()
                        .entry(r.client_id.clone())
                        .or_default();
                    for t in scope {
                        if !tokens.contains(&t) {
                            tokens.push(t);
                        }
                    }
                }
            }
            Some("oauthEndRequest") => {
                let id = text("id")?;
                let r = self
                    .requests
                    .remove(&id)
                    .ok_or_else(|| format!("the end of request {id}, which is not kept"))?;
                self.pending.remove(&id);
                if let Some(a) = r.approval {
                    self.codes.remove(&a.code);
                }
            }
            Some("oauthSpendCode") => {
                self.spend(&text("code")?)?;
            }
            Some("oauthSession") => {
                let (sid, code) = (text("sid")?, text("code")?);
                if self.sessions.contains_key(&sid) {
                    return Err(format!("a second session {sid}"));
                }
                let scope = list("scope")?;
                let s = Session {
                    did: account("did")?,
                    client_id: text("client")?,
                    jkt: text("jkt")?,
                    // A session kept before sets were served kept no expansion: it had nothing to expand.
                    granted: strings(&e["granted"]).unwrap_or_else(|| scope.clone()),
                    scope,
                    started: number("started")?,
                    code: code.clone(),
                    access: text("access")?,
                    access_exp: number("accessExp")?,
                    refresh: text("refresh")?,
                    client_key: opt_text("clientKey"),
                    refreshed: number("started")?,
                    mcp: e["mcp"].as_bool().unwrap_or(false),
                };
                self.spend(&code)?;
                self.by_code.insert(code, sid.clone());
                self.sessions.insert(sid, s);
            }
            Some("oauthRefresh") => {
                let sid = text("sid")?;
                let s = self
                    .sessions
                    .get_mut(&sid)
                    .ok_or_else(|| format!("a refresh of session {sid}, which is not kept"))?;
                s.access = text("access")?;
                s.access_exp = number("accessExp")?;
                s.refresh = text("refresh")?;
                if let Some(granted) = strings(&e["granted"]) {
                    s.granted = granted;
                }
                if let Some(at) = e["at"].as_u64() {
                    s.refreshed = at;
                }
            }
            Some("oauthEndSession") => {
                let sid = text("sid")?;
                let s = self
                    .sessions
                    .remove(&sid)
                    .ok_or_else(|| format!("the end of session {sid}, which is not kept"))?;
                self.by_code.remove(&s.code);
            }
            Some("oauthSignIn") => {
                let (device, did, at) = (text("device")?, account("did")?, number("at")?);
                let (whence, key) = (Whence::kept(e), (device.clone(), did.clone()));
                if whence == Whence::default() {
                    self.whence.remove(&key);
                } else {
                    self.whence.insert(key, whence);
                }
                let signed = self.devices.entry(device).or_default();
                signed.retain(|(d, _)| *d != did);
                signed.push((did, at));
            }
            Some("oauthSignOut") => {
                let (device, did) = (text("device")?, text("did")?);
                let signed = self
                    .devices
                    .get_mut(&device)
                    .filter(|s| s.iter().any(|(d, _)| *d == did));
                let signed = signed.ok_or_else(|| {
                    format!("a sign-out of {did} on device {device}, which it is not signed in on")
                })?;
                signed.retain(|(d, _)| *d != did);
                if signed.is_empty() {
                    self.devices.remove(&device);
                }
                self.whence.remove(&(device, did));
            }
            Some("oauthDeviceKey") => {
                let (device, key, at) = (text("device")?, text("key")?, number("at")?);
                self.device_keys.insert(device, (key, at));
            }
            Some("oauthDeviceEnd") => {
                let device = text("device")?;
                self.devices.remove(&device);
                self.device_keys.remove(&device);
                self.whence.retain(|(d, _), _| *d != device);
            }
            Some("oauthForgetClients") => {
                self.approved.remove(&text("did")?);
            }
            Some(t) if passkeys::ENTRIES.contains(&t) => {
                self.passkeys.apply(e, account("did")?)?;
            }
            t => return Err(format!("a log entry of no known type: {t:?}")),
        }
        Ok(())
    }

    /// Spend a code not yet spent, ending its request.
    fn spend(&mut self, code: &str) -> Result<(), String> {
        let id = self
            .codes
            .remove(code)
            .ok_or_else(|| format!("code {code} is not one to spend"))?;
        self.requests.remove(&id);
        self.pending.remove(&id);
        Ok(())
    }

    /// Forget what is past use at `now`: requests well past their time, and
    /// sessions past their end. Nothing is logged: replaying the log and
    /// forgetting the same gives the same.
    fn forget(&mut self, now: u64) {
        self.pending.expire(now);
        let codes = &mut self.codes;
        self.requests.retain(|_, r| {
            let keep = r.expires + KEEP_PAST > now
                || r.approval
                    .as_ref()
                    .is_some_and(|a| a.at + CODE_LIFE + KEEP_PAST > now);
            if !keep && let Some(a) = &r.approval {
                codes.remove(&a.code);
            }
            keep
        });
        let by_code = &mut self.by_code;
        self.sessions.retain(|_, s| {
            let keep = s.end() > now;
            if !keep {
                by_code.remove(&s.code);
            }
            keep
        });
    }

    /// Forget everything of an account that was deleted: its sessions, the
    /// requests approved for it, its sign-ins on every device, the clients
    /// it approved, and its passkeys and user handle. Nothing is logged:
    /// the deletion's own entry does this on replay, and a compacted log
    /// leaves out what it forgot (`without_accounts`).
    fn forget_account(&mut self, did: &str) {
        let codes = &mut self.codes;
        self.requests.retain(|_, r| {
            let theirs = r.approval.as_ref().is_some_and(|a| a.did == did);
            if theirs && let Some(a) = &r.approval {
                codes.remove(&a.code);
            }
            !theirs
        });
        let by_code = &mut self.by_code;
        self.sessions.retain(|_, s| {
            if s.did == did {
                by_code.remove(&s.code);
            }
            s.did != did
        });
        self.devices.retain(|_, signed| {
            signed.retain(|(d, _)| d != did);
            !signed.is_empty()
        });
        self.whence.retain(|(_, d), _| d != did);
        self.approved.remove(did);
        self.passkeys.forget_account(did);
    }

    fn signed_in(&self, device: &str) -> &[(String, u64)] {
        self.devices.get(device).map_or(&[], Vec::as_slice)
    }
}

type HmacSha256 = Hmac<Sha256>;

/// What OAuth keeps, and the secret it seals with.
pub(crate) struct OAuth {
    key: [u8; 32],
    /// Whether the secret is new, to write once the log shows nothing needs the old one.
    made: bool,
    /// The origin of `PDS_PUBLIC_URL`.
    pub issuer: String,
    state: Mutex<State>,
    /// When `State::forget` is next due.
    next_forget: AtomicU64,
    /// Discoverable clients' documents and JWKS, kept a while.
    clients: clients::Clients,
    /// DPoP proofs spent, held in memory (`dpop::Spent`).
    proofs: Mutex<dpop::Spent>,
    /// Permission sets resolved, held in memory (`sets`).
    sets: sets::Sets,
    /// Passkeys' links and challenges, held in memory (`passkeys::Held`):
    /// its lock is taken after `state`'s, never before.
    held: Mutex<passkeys::Held>,
}

fn new_id(bytes: usize) -> String {
    let b: Vec<u8> = (0..bytes).map(|_| rand::random::<u8>()).collect();
    B64.encode(b)
}

impl OAuth {
    /// The OAuth of the server whose data is in `dir`, with nothing kept yet,
    /// fetching clients' documents as `client_fetch` says, if given.
    pub fn open(
        dir: &Path,
        public_url: &str,
        client_fetch: Option<ClientFetch>,
    ) -> Result<OAuth, String> {
        let origin = url::Url::parse(public_url)
            .map_err(|e| format!("PDS_PUBLIC_URL: {e}"))?
            .origin();
        if !origin.is_tuple() {
            return Err("PDS_PUBLIC_URL has no origin".into());
        }
        let (key, made) = match std::fs::read(dir.join(KEY_FILE)) {
            Ok(bytes) => (
                bytes
                    .try_into()
                    .map_err(|_| format!("{KEY_FILE} is not 32 bytes"))?,
                false,
            ),
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => (rand::random(), true),
            Err(e) => return Err(format!("{KEY_FILE}: {e}")),
        };
        let clients = clients::Clients::new(client_fetch);
        let (state, proofs) = (Mutex::default(), Mutex::default());
        Ok(OAuth {
            key,
            made,
            issuer: origin.ascii_serialization(),
            state,
            next_forget: AtomicU64::new(0),
            clients,
            proofs,
            sets: sets::Sets::default(),
            held: Mutex::default(),
        })
    }

    /// Replay an entry of `accounts.log` of the kinds in `ENTRIES`.
    pub fn replay(&self, e: &Json, is_account: &dyn Fn(&str) -> bool) -> Result<(), String> {
        self.lock().apply(e, is_account)
    }

    /// An account was deleted, or its deletion replayed: forget what OAuth
    /// keeps of it.
    pub fn forget_account(&self, did: &str) {
        self.lock().forget_account(did);
    }

    /// Under OAuth's lock, end what `ends` says of account `did`, for a
    /// change of its (`spec/LIFECYCLE.md`, `spec/EMAIL.md`): `log` logs the
    /// change, given the entries that end them to log in its frame, and once
    /// it has, they are ended; with `ends.account`, everything of it is then
    /// forgotten, as its deletion's own entry does on replay. No change of
    /// OAuth's is made meanwhile. OAuth's lock is taken before the account's
    /// state's, which `log` may take, as everywhere: what holds OAuth's may
    /// read an account's state.
    pub fn end_for<T, E>(
        &self,
        did: &str,
        ends: Ends,
        log: impl FnOnce(Vec<Json>) -> Result<T, E>,
    ) -> Result<T, E> {
        let mut st = self.lock();
        let mut ended = Vec::new();
        if ends.requests {
            let mut ids: Vec<&String> = st
                .requests
                .iter()
                .filter(|(_, r)| r.approval.as_ref().is_some_and(|a| a.did == did))
                .map(|(id, _)| id)
                .collect();
            ids.sort();
            ended.extend(
                ids.into_iter()
                    .map(|id| json!({ "t": "oauthEndRequest", "id": id })),
            );
        }
        if ends.sessions {
            let mut sids: Vec<&String> = st
                .sessions
                .iter()
                .filter(|(_, s)| s.did == did)
                .map(|(sid, _)| sid)
                .collect();
            sids.sort();
            ended.extend(
                sids.into_iter()
                    .map(|sid| json!({ "t": "oauthEndSession", "sid": sid })),
            );
        }
        if ends.clients && st.approved.contains_key(did) {
            ended.push(json!({ "t": "oauthForgetClients", "did": did }));
        }
        if ends.devices {
            let mut devices: Vec<&String> = st
                .devices
                .iter()
                .filter(|(_, signed)| signed.iter().any(|(d, _)| d == did))
                .map(|(device, _)| device)
                .collect();
            devices.sort();
            ended.extend(
                devices
                    .into_iter()
                    .map(|device| json!({ "t": "oauthSignOut", "device": device, "did": did })),
            );
        }
        if ends.passkeys {
            ended.extend(st.passkeys.removals(did));
        }
        let out = log(ended.clone())?;
        for e in &ended {
            st.apply(e, &|_| true)
                .unwrap_or_else(|why| panic!("an OAuth change made under its lock: {why}"));
        }
        if ends.passkeys || ends.account {
            self.held().end_for(did);
        }
        if ends.account {
            st.forget_account(did);
        }
        Ok(out)
    }

    /// Once the log is replayed, at `now`: forget what is past use, and keep a
    /// new secret, unless what the log keeps was sealed with one now lost.
    pub fn recovered(&self, dir: &Path, now: u64) -> Result<(), String> {
        let mut st = self.lock();
        st.forget(now);
        if !self.made {
            return Ok(());
        }
        if !st.sessions.is_empty()
            || !st.requests.is_empty()
            || !st.devices.is_empty()
            || !st.device_keys.is_empty()
            || st.passkeys.any()
        {
            return Err(format!(
                "{KEY_FILE} is missing, and what OAuth gave out was sealed with it"
            ));
        }
        let (path, tmp) = (dir.join(KEY_FILE), dir.join(format!("{KEY_FILE}.tmp")));
        let made = (|| {
            let mut f = pds_store::open_private(
                &tmp,
                std::fs::OpenOptions::new()
                    .create(true)
                    .write(true)
                    .truncate(true),
            )?;
            f.write_all(&self.key)?;
            pds_store::sync_file(&f)?;
            std::fs::rename(&tmp, &path)?;
            pds_store::sync_dir(dir)
        })();
        made.map_err(|e| format!("{KEY_FILE}: {e}"))
    }

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

    /// An account's user handle (`spec/PASSKEYS.md`, "The relying party"):
    /// the HMAC-SHA-256 of its DID under a key kept as OAuth's secret is
    /// (one made from that secret for this alone), so the same whatever
    /// happens to the account, and kept nowhere.
    fn user_handle(&self, did: &str) -> [u8; 32] {
        let key = self.mac("passkey user handles", &[]);
        let mut m = HmacSha256::new_from_slice(&key).expect("HMAC takes a key of any length");
        m.update(did.as_bytes());
        m.finalize().into_bytes().into()
    }

    fn held(&self) -> MutexGuard<'_, passkeys::Held> {
        self.held.lock().unwrap_or_else(PoisonError::into_inner)
    }

    /// The MCP issuer (`spec/OAUTH-MCP.md`, "Names").
    pub fn mcp_issuer(&self) -> String {
        format!("{}/oauth/mcp", self.issuer)
    }

    /// The issuer of a request: the MCP issuer, or the atproto one.
    fn issuer_of(&self, r: &Request) -> String {
        if r.mcp() {
            self.mcp_issuer()
        } else {
            self.issuer.clone()
        }
    }

    /// The scope a code was approved with, if it is a code to exchange: what
    /// the code grant resolves the sets of before it takes the lock.
    fn approved_scope(&self, code: &str) -> Vec<String> {
        let st = self.lock();
        st.codes
            .get(code)
            .and_then(|id| st.requests.get(id)?.approval.as_ref())
            .map(|a| a.scope.clone())
            .unwrap_or_default()
    }

    /// The scope, as consented, of the session a refresh token is of: one
    /// sealed for `label`.
    fn session_scope(&self, label: &str, token: &str) -> Vec<String> {
        let Some((sid, _)) = self.token_of(label, token) else {
            return vec![];
        };
        self.lock()
            .sessions
            .get(&sid)
            .map(|s| s.scope.clone())
            .unwrap_or_default()
    }

    fn mac(&self, label: &str, data: &[u8]) -> [u8; 32] {
        let mut m = HmacSha256::new_from_slice(&self.key).expect("HMAC takes a key of any length");
        m.update(label.as_bytes());
        m.update(&[0]);
        m.update(data);
        m.finalize().into_bytes().into()
    }

    /// `payload`, sealed for `label`: base64url of it, `.`, and its MAC.
    fn seal(&self, label: &str, payload: &Json) -> String {
        let p = B64.encode(payload.to_string());
        let m = B64.encode(self.mac(label, p.as_bytes()));
        format!("{p}.{m}")
    }

    /// What `seal` sealed for `label`, if it did.
    fn unseal(&self, label: &str, sealed: &str) -> Option<Json> {
        let (p, m) = sealed.split_once('.')?;
        let mut mac =
            HmacSha256::new_from_slice(&self.key).expect("HMAC takes a key of any length");
        mac.update(label.as_bytes());
        mac.update(&[0]);
        mac.update(p.as_bytes());
        mac.verify_slice(&B64.decode(m).ok()?).ok()?;
        serde_json::from_slice(&B64.decode(p).ok()?).ok()
    }

    /// A token of `kind`, a label of `labels`, for a session: its id and the token's.
    fn token(&self, kind: &str, sid: &str, jti: &str) -> String {
        self.seal(kind, &json!({ "sid": sid, "jti": jti }))
    }

    /// The session and token id a token of `kind` names, if the server made it.
    fn token_of(&self, kind: &str, token: &str) -> Option<(String, String)> {
        let t = self.unseal(kind, token)?;
        Some((
            t["sid"].as_str()?.to_string(),
            t["jti"].as_str()?.to_string(),
        ))
    }

    /// Everything kept, to compare across restarts.
    #[cfg(test)]
    pub fn snapshot(&self) -> State {
        self.lock().clone()
    }

    /// Hold pending requests to these caps, as a test of them must.
    #[cfg(test)]
    pub fn cap_pending(&self, per_address: usize, all: usize) {
        let mut st = self.lock();
        (st.pending.per_address, st.pending.all) = (per_address, all);
    }

    /// How many requests are pending.
    #[cfg(test)]
    pub fn pending(&self) -> usize {
        self.lock().pending.len()
    }
}

/// A request's changes to what OAuth keeps: the single-use values it spent,
/// and the frame it is answered after.
struct Tx<'a> {
    svc: &'a Shared,
    spent: Vec<Json>,
    frame: u64,
    /// Whether a frame of it could not be written or synced: the request fails.
    failed: bool,
}

impl<'a> Tx<'a> {
    fn new(svc: &'a Shared) -> Self {
        Tx {
            svc,
            spent: Vec::new(),
            frame: 0,
            failed: false,
        }
    }

    /// Look at what is kept and change it, under its lock: `f` answers the
    /// entries to make and log (the single-use values it spent among them),
    /// which go in one frame with those spent before, and change what is
    /// kept only once that frame is written. A frame that cannot be written
    /// fails the request: nothing it would change changes, here or after.
    fn change<T>(&mut self, f: impl FnOnce(&State, u64) -> (Vec<Json>, T)) -> T {
        let (svc, now) = (self.svc, self.svc.sessions.now());
        let mut st = svc.oauth.lock();
        if svc.oauth.next_forget.load(Ordering::Relaxed) <= now {
            st.forget(now);
            svc.oauth.next_forget.store(now + 60, Ordering::Relaxed);
        }
        // Requests past their time are pending no longer, whenever the rest is forgotten.
        st.pending.expire(now);
        let (entries, out) = f(&st, now);
        // An account deleted since the request looked it up is no account
        // to log anything of: each account the entries name is loaded, if
        // it is one. A deletion is logged with the directory written,
        // which is read here until these entries are logged, so it is
        // logged wholly before them or wholly after.
        for did in entries.iter().filter_map(|e| e["did"].as_str()) {
            svc.by_did(did);
        }
        let directory = crate::read(&svc.directory);
        if entries.iter().any(|e| {
            e["did"]
                .as_str()
                .is_some_and(|d| !directory.by_did.contains_key(d))
        }) {
            self.failed = true;
        }
        if entries.is_empty() || self.failed {
            // What it answers may have been logged by another request.
            self.frame = self.frame.max(svc.log.written());
            return out;
        }
        let mut all = std::mem::take(&mut self.spent);
        all.extend(entries);
        match svc.log.append(&all) {
            Ok(n) => {
                for e in all
                    .iter()
                    .filter(|e| e["t"].as_str().is_some_and(|t| ENTRIES.contains(&t)))
                {
                    st.apply(e, &|_| true)
                        .unwrap_or_else(|why| panic!("an OAuth change made under its lock: {why}"));
                }
                self.frame = n;
            }
            Err(e) => self.fail(e),
        }
        out
    }

    fn fail(&mut self, e: std::io::Error) {
        crate::ops::failed("writing accounts.log failed", e);
        self.failed = true;
    }

    /// Log what is spent and not yet logged, and wait until all of it is on
    /// disk: false if any of it could not be, and the request is to fail.
    async fn done(mut self) -> bool {
        if !self.spent.is_empty() && !self.failed {
            match self.svc.log.append(&self.spent) {
                Ok(n) => {
                    self.frame = n;
                }
                Err(e) => self.fail(e),
            }
        }
        if self.frame > 0
            && !self.failed
            && durable(self.svc.log.clone(), self.frame).await.is_err()
        {
            self.failed = true;
        }
        !self.failed
    }
}

/// Run a request's handler to its end, even if its caller goes away: what it
/// logged is answered only once on disk, and must not be left half done.
async fn finish(f: impl Future<Output = Response> + Send + 'static) -> Response {
    crate::ops::spawn(f)
        .await
        .unwrap_or_else(|_| StatusCode::INTERNAL_SERVER_ERROR.into_response())
}

pub(crate) fn routes() -> Router<Shared> {
    Router::new()
        .route(
            "/.well-known/oauth-protected-resource",
            get(protected_resource),
        )
        .route(
            "/.well-known/oauth-authorization-server",
            any(authorization_server),
        )
        .route("/oauth/jwks", any(jwks))
        .route(
            "/oauth/par",
            any(|s, m, h, p, b| endpoint(s, m, h, p, b, Endpoint::Par)),
        )
        .route(
            "/oauth/token",
            any(|s, m, h, p, b| endpoint(s, m, h, p, b, Endpoint::Token)),
        )
        .route(
            "/oauth/revoke",
            any(|s, m, h, p, b| endpoint(s, m, h, p, b, Endpoint::Revoke)),
        )
        .route("/oauth/authorize", any(page::authorize))
        .route("/oauth/passkey", any(passkeys::passkey_page))
        .route("/oauth/assets/{name}", any(assets::asset))
        .route("/oauth/authorize/redirect", any(page::redirect))
        .route("/@atproto/oauth-provider/~api/{endpoint}", any(page::api))
        .route(
            "/.well-known/oauth-protected-resource/mcp",
            get(mcp::protected_resource),
        )
        .route(
            "/.well-known/oauth-authorization-server/oauth/mcp",
            any(mcp::authorization_server),
        )
        .route("/oauth/mcp/authorize", any(mcp::authorize))
        .route(
            "/oauth/mcp/token",
            any(|s, m, h, p, b| endpoint(s, m, h, p, b, Endpoint::McpToken)),
        )
        .route(
            "/oauth/mcp/revoke",
            any(|s, m, h, p, b| endpoint(s, m, h, p, b, Endpoint::McpRevoke)),
        )
}

fn set(r: &mut Response, name: &'static str, value: &str) {
    if let Ok(v) = HeaderValue::from_str(value) {
        r.headers_mut().insert(name, v);
    }
}

fn json_response(status: u16, body: &Json) -> Response {
    let status = StatusCode::from_u16(status).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
    (
        status,
        [(header::CONTENT_TYPE, "application/json")],
        body.to_string(),
    )
        .into_response()
}

/// The CORS headers of what browsers may call from any origin.
fn cors(mut r: Response) -> Response {
    for (k, v) in [
        ("access-control-allow-origin", "*"),
        ("access-control-allow-methods", "*"),
        ("access-control-allow-headers", "Content-Type,DPoP"),
        ("access-control-max-age", "86400"),
    ] {
        set(&mut r, k, v);
    }
    r
}

/// Answer `GET` with `doc`, and `OPTIONS` with the CORS headers.
fn document(method: &Method, doc: impl FnOnce() -> Json) -> Response {
    match *method {
        Method::GET | Method::HEAD => cors(json_response(200, &doc())),
        Method::OPTIONS => cors(StatusCode::OK.into_response()),
        _ => StatusCode::METHOD_NOT_ALLOWED.into_response(),
    }
}

async fn protected_resource(AxState(svc): AxState<Shared>) -> Response {
    let iss = &svc.oauth.issuer;
    let doc = json!({
        "resource": iss, "authorization_servers": [iss], "scopes_supported": [],
        "bearer_methods_supported": ["header"], "resource_documentation": "https://atproto.com",
    });
    let mut r = json_response(200, &doc);
    set(&mut r, "access-control-allow-origin", "*");
    r
}

async fn authorization_server(AxState(svc): AxState<Shared>, method: Method) -> Response {
    let iss = &svc.oauth.issuer;
    document(&method, || {
        json!({
            "issuer": iss,
            "authorization_endpoint": format!("{iss}/oauth/authorize"),
            "token_endpoint": format!("{iss}/oauth/token"),
            "revocation_endpoint": format!("{iss}/oauth/revoke"),
            "pushed_authorization_request_endpoint": format!("{iss}/oauth/par"),
            "jwks_uri": format!("{iss}/oauth/jwks"),
            "require_pushed_authorization_requests": true,
            "require_request_uri_registration": true,
            "request_uri_parameter_supported": true,
            "request_parameter_supported": false,
            "scopes_supported": SCOPES_SUPPORTED,
            "subject_types_supported": ["public"],
            "response_types_supported": ["code"],
            "response_modes_supported": ["query", "fragment", "form_post"],
            "grant_types_supported": ["authorization_code", "refresh_token"],
            "code_challenge_methods_supported": ["S256"],
            "ui_locales_supported": ["en-US"],
            "display_values_supported": ["page", "popup", "touch"],
            "authorization_response_iss_parameter_supported": true,
            "token_endpoint_auth_methods_supported": ["none", "private_key_jwt"],
            "token_endpoint_auth_signing_alg_values_supported": dpop::ALGS,
            "dpop_signing_alg_values_supported": dpop::ALGS,
            "protected_resources": [iss],
            "client_id_metadata_document_supported": true,
            "prompt_values_supported": ["none", "login", "consent", "select_account", "create"],
        })
    })
}

/// The scopes both issuers' metadata names.
const SCOPES_SUPPORTED: [&str; 4] = [
    "atproto",
    "transition:email",
    "transition:generic",
    "transition:chat.bsky",
];

async fn jwks(method: Method) -> Response {
    document(&method, || json!({ "keys": [] }))
}

/// An answer of the three endpoints: its status, its body, and the
/// `WWW-Authenticate` error it carries, if any.
struct Out {
    status: u16,
    body: Json,
    www: Option<(&'static str, String)>,
}

fn ok(status: u16, body: Json) -> Out {
    Out {
        status,
        body,
        www: None,
    }
}

fn refuse(status: u16, error: &str, description: impl Into<String>) -> Out {
    ok(
        status,
        json!({ "error": error, "error_description": description.into() }),
    )
}

/// A refusal that names the DPoP scheme's error in `WWW-Authenticate`.
fn refuse_dpop(error: &'static str, description: impl Into<String>) -> Out {
    let d = description.into();
    Out {
        status: 401,
        body: json!({ "error": error, "error_description": d }),
        www: Some((error, d)),
    }
}

/// A DPoP proof's refusal, as the three endpoints answer it.
fn refused_proof(r: dpop::Refusal) -> Out {
    match r {
        dpop::Refusal::Invalid(d) => refuse_dpop("invalid_dpop_proof", d),
        dpop::Refusal::Nonce(d) => refuse(400, "use_dpop_nonce", d),
    }
}

/// Whether the free space is below `PDS_MIN_FREE_BYTES`, as XRPC's writes
/// check it (`spec/OAUTH.md`, "Free space"): what would keep something is
/// then refused, changing nothing.
pub(super) fn low(svc: &Service) -> bool {
    svc.limits.disk.check().is_err()
}

/// The three endpoints' refusal below the free-space floor.
fn unavailable() -> Out {
    refuse(
        507,
        "temporarily_unavailable",
        "Not enough free space to store this",
    )
}

/// A request body of at most `max` bytes, by its `Content-Length` or as it
/// comes: Err(413) if it is longer, Err(400) if it could not be read.
pub(super) async fn read_body(headers: &HeaderMap, body: Body, max: usize) -> Result<Bytes, u16> {
    let declared = headers
        .get(header::CONTENT_LENGTH)
        .and_then(|v| v.to_str().ok())
        .and_then(|v| v.parse::<u64>().ok());
    if declared.is_some_and(|n| n > max as u64) {
        return Err(413);
    }
    match crate::limits::read_body(body, max).await {
        Some(b) if b.len() > max => Err(413),
        Some(b) => Ok(b),
        None => Err(400),
    }
}

/// What a change that checked a request's token or grant logs and answers:
/// below the free-space floor, anything it would keep is refused with
/// `507`, changing nothing; once the request passed (answered `2xx`,
/// keeping something), its DPoP proof is kept with it, and otherwise held
/// in memory alone (`spec/OAUTH.md`, "DPoP" step 5).
fn settle(
    svc: &Service,
    proof: &dpop::Proof,
    now: u64,
    low: bool,
    (mut entries, out): (Vec<Json>, Out),
) -> (Vec<Json>, Out) {
    if entries.is_empty() {
        return (entries, out);
    }
    if low {
        return (vec![], unavailable());
    }
    if out.status < 300 {
        let Some(kept) = dpop::keep(svc, proof, now) else {
            return (
                vec![],
                refuse_dpop("invalid_dpop_proof", "DPoP proof jti was used before"),
            );
        };
        entries.insert(0, kept);
    }
    (entries, out)
}

/// A `WWW-Authenticate` header of the DPoP scheme.
fn www_authenticate(error: &str, description: &str) -> String {
    let quoted = |s: &str| s.replace('\\', "\\\\").replace('"', "\\\"");
    format!(
        "DPoP algs=\"{}\", error=\"{}\", error_description=\"{}\"",
        dpop::ALGS.join(" "),
        quoted(error),
        quoted(description)
    )
}

#[derive(Clone, Copy)]
enum Endpoint {
    Par,
    Token,
    Revoke,
    /// The MCP issuer's (`spec/OAUTH-MCP.md`), which take no DPoP proof.
    McpToken,
    McpRevoke,
}

/// `/oauth/par`, `/oauth/token` and `/oauth/revoke`, and the MCP issuer's
/// token and revocation endpoints.
async fn endpoint(
    AxState(svc): AxState<Shared>,
    method: Method,
    headers: HeaderMap,
    peer: Option<Extension<crate::limits::Peer>>,
    body: Body,
    which: Endpoint,
) -> Response {
    if method == Method::OPTIONS {
        return cors(StatusCode::OK.into_response());
    }
    let client = crate::limits::client(
        &svc.config.trusted_proxies,
        &headers,
        peer.map(|Extension(p)| p.0),
    );
    finish(async move {
        let out = if method != Method::POST {
            let status = if matches!(which, Endpoint::Par) {
                405
            } else {
                404
            };
            refuse(status, "invalid_request", "Method not allowed")
        } else {
            let max = if matches!(which, Endpoint::Par) {
                BODY_MAX
            } else {
                OTHER_BODY_MAX
            };
            match read_body(&headers, body, max).await {
                Err(413) => refuse(413, "invalid_request", "Request body too large"),
                Err(status) => refuse(status, "invalid_request", "The body could not be read"),
                Ok(body) => {
                    let mut tx = Tx::new(&svc);
                    let out = match which {
                        Endpoint::Par => par(&svc, &mut tx, &headers, &body, &client).await,
                        Endpoint::Token => token(&svc, &mut tx, &headers, &body).await,
                        Endpoint::Revoke => revoke(&svc, &mut tx, &headers, &body).await,
                        Endpoint::McpToken => mcp::token(&svc, &mut tx, &headers, &body).await,
                        Endpoint::McpRevoke => mcp::revoke(&svc, &mut tx, &headers, &body),
                    };
                    // Below the free-space floor nothing is kept, a client's assertion neither.
                    if out.status == 507 {
                        tx.spent.clear();
                    }
                    if tx.done().await {
                        out
                    } else {
                        refuse(500, "server_error", "Internal server error")
                    }
                }
            }
        };
        let mut r = cors(json_response(out.status, &out.body));
        set(&mut r, "cache-control", "no-store");
        set(&mut r, "pragma", "no-cache");
        if matches!(which, Endpoint::McpToken | Endpoint::McpRevoke) {
            return r;
        }
        set(&mut r, "dpop-nonce", &svc.oauth.nonce(svc.sessions.now()));
        let expose = match out.www {
            Some((error, d)) => {
                set(&mut r, "www-authenticate", &www_authenticate(error, &d));
                "DPoP-Nonce, WWW-Authenticate"
            }
            None => "DPoP-Nonce",
        };
        set(&mut r, "access-control-expose-headers", expose);
        r
    })
    .await
}

/// A request body's parameters, as given.
struct Params(Vec<(String, Json)>);

/// A JSON object's members, with any given twice.
struct Pairs(Vec<(String, Json)>);

impl<'de> serde::Deserialize<'de> for Pairs {
    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Pairs, D::Error> {
        struct Visit;
        impl<'de> serde::de::Visitor<'de> for Visit {
            type Value = Pairs;
            fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
                f.write_str("a JSON object")
            }
            fn visit_map<A: serde::de::MapAccess<'de>>(self, mut m: A) -> Result<Pairs, A::Error> {
                let mut out = Vec::new();
                while let Some(kv) = m.next_entry::<String, Json>()? {
                    out.push(kv);
                }
                Ok(Pairs(out))
            }
        }
        d.deserialize_map(Visit)
    }
}

impl Params {
    /// A body as the three endpoints take it: a form or JSON, no parameter
    /// twice, and no `Content-Encoding` but `identity`, as none is decoded
    /// (`spec/OAUTH.md`, "Pushed authorization requests").
    fn of(headers: &HeaderMap, body: &[u8]) -> Result<Params, Out> {
        let encoded = headers.get_all(header::CONTENT_ENCODING).iter().any(|v| {
            v.to_str().map_or(true, |v| {
                v.split(',')
                    .any(|e| !e.trim().eq_ignore_ascii_case("identity"))
            })
        });
        if encoded {
            return Err(refuse(
                415,
                "invalid_request",
                "Unsupported Content-Encoding",
            ));
        }
        let essence = headers
            .get(header::CONTENT_TYPE)
            .and_then(|v| v.to_str().ok())
            .map(|v| {
                v.split(';')
                    .next()
                    .unwrap_or_default()
                    .trim()
                    .to_ascii_lowercase()
            });
        let pairs: Vec<(String, Json)> = match essence.as_deref() {
            Some("application/x-www-form-urlencoded") => url::form_urlencoded::parse(body)
                .map(|(k, v)| (k.into_owned(), Json::String(v.into_owned())))
                .collect(),
            Some("application/json") => match serde_json::from_slice::<Pairs>(body) {
                Ok(p) => p.0,
                Err(_) => return Err(refuse(400, "invalid_request", "Invalid JSON body")),
            },
            _ => return Err(refuse(415, "invalid_request", "Unsupported Content-Type")),
        };
        if let Some((k, _)) = pairs
            .iter()
            .enumerate()
            .find(|(i, (k, _))| pairs[..*i].iter().any(|(j, _)| j == k))
            .map(|(_, p)| p)
        {
            return Err(refuse(
                400,
                "invalid_request",
                format!("Parameter {k} is given more than once"),
            ));
        }
        Ok(Params(pairs))
    }

    fn get(&self, k: &str) -> Option<&Json> {
        self.0.iter().find(|(n, _)| n == k).map(|(_, v)| v)
    }

    /// A string parameter, if given: Err if it is not a string.
    fn text(&self, k: &str) -> Result<Option<&str>, ()> {
        match self.get(k) {
            None => Ok(None),
            Some(Json::String(s)) => Ok(Some(s)),
            Some(_) => Err(()),
        }
    }

    /// A string parameter that is there and not empty.
    fn filled(&self, k: &str) -> Option<&str> {
        self.text(k).ok().flatten().filter(|s| !s.is_empty())
    }
}

const RESPONSE_TYPES: &[&str] = &[
    "code",
    "token",
    "none",
    "code id_token token",
    "code id_token",
    "code token",
    "id_token token",
    "id_token",
];

/// Language tags as `fr-CA en`.
fn valid_locales(s: &str) -> bool {
    !s.is_empty() && s.split(' ').all(valid_locale)
}

/// A language tag as `en` or `fr-CA`.
fn valid_locale(t: &str) -> bool {
    let (lang, region) = t.split_once('-').map_or((t, None), |(l, r)| (l, Some(r)));
    (2..=3).contains(&lang.len())
        && lang.bytes().all(|b| b.is_ascii_lowercase())
        && region.is_none_or(|r| r.len() == 2 && r.bytes().all(|b| b.is_ascii_uppercase()))
}

/// Whether `s` has the form of a JWT: base64url JSON objects, then a signature.
fn jwt_form(s: &str) -> bool {
    let parts: Vec<&str> = s.split('.').collect();
    let object = |p: &str| {
        B64.decode(p)
            .ok()
            .and_then(|b| serde_json::from_slice::<Json>(&b).ok())
            .is_some_and(|j| j.is_object())
    };
    parts.len() == 3 && object(parts[0]) && object(parts[1]) && B64.decode(parts[2]).is_ok()
}

/// The forms of PAR's parameters (its check 3).
fn par_forms(p: &Params) -> Result<(), String> {
    let text = |k: &str| p.text(k).map_err(|_| format!("{k} must be a string"));
    let one_of = |k: &str, values: &[&str]| -> Result<(), String> {
        match text(k)? {
            Some(v) if !values.contains(&v) => Err(format!("{k} is not one of {values:?}")),
            _ => Ok(()),
        }
    };
    match text("response_type")? {
        Some(t) if RESPONSE_TYPES.contains(&t) => {}
        _ => return Err("response_type is missing or not a response type".into()),
    }
    if text("redirect_uri")?.is_some_and(|u| !client::redirect_form(u)) {
        return Err("redirect_uri is not a redirect URI".into());
    }
    // A missing scope is refused later, as one without `atproto`.
    if text("scope")?.is_some_and(|s| !scope::valid(s)) {
        return Err("scope is not a scope string".into());
    }
    one_of("code_challenge_method", &["S256", "plain"])?;
    one_of(
        "prompt",
        &["none", "login", "consent", "select_account", "create"],
    )?;
    one_of("response_mode", &["query", "fragment", "form_post"])?;
    one_of("display", &["page", "popup", "touch", "wap"])?;
    if text("ui_locales")?.is_some_and(|l| !valid_locales(l)) {
        return Err("ui_locales is not language tags".into());
    }
    let max_age = match p.get("max_age") {
        None => true,
        Some(Json::String(s)) => !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit()),
        Some(Json::Number(n)) => n.is_u64(),
        Some(_) => false,
    };
    if !max_age {
        return Err("max_age is not an integer, 0 or more".into());
    }
    if text("login_hint")?.is_some_and(str::is_empty) {
        return Err("login_hint is empty".into());
    }
    if text("id_token_hint")?.is_some_and(|t| !jwt_form(t)) {
        return Err("id_token_hint is not a JWT".into());
    }
    let claims = match p.get("claims") {
        None | Some(Json::Object(_)) => true,
        Some(Json::String(s)) => serde_json::from_str::<Json>(s).is_ok_and(|c| c.is_object()),
        Some(_) => false,
    };
    if !claims {
        return Err("claims is not a JSON object".into());
    }
    for k in ["state", "code_challenge", "nonce", "dpop_jkt"] {
        text(k)?;
    }
    Ok(())
}

/// The longest `client_id` PAR keeps: a loopback one naming a
/// `redirect_uri` of 2048 bytes and a `scope` of 4096, every byte of both
/// percent-encoded (spec/OAUTH.md, PAR step 17).
const CLIENT_ID_CAP: usize = "http://localhost/?redirect_uri=&scope=".len() + 3 * (2048 + 4096);

/// PAR's step 17: why a request is larger than the server keeps, if it is.
fn too_large(p: &Params) -> Option<&'static str> {
    let text = |k: &str| p.text(k).ok().flatten().unwrap_or_default();
    if text("client_id").len() > CLIENT_ID_CAP {
        return Some("client_id is too long");
    }
    if text("state").len() > 1024 {
        return Some("state is too long");
    }
    if text("code_challenge").chars().count() != 43 {
        return Some("code_challenge must be 43 characters");
    }
    if text("redirect_uri").len() > 2048 || text("login_hint").len() > 2048 {
        return Some("redirect_uri or login_hint is too long");
    }
    if text("scope").len() > 4096 {
        return Some("scope is too long");
    }
    if text("ui_locales").split(' ').count() > 16 {
        return Some("ui_locales has too many tags");
    }
    None
}

/// A client's `state` as the single-use value that keeps it: one string of
/// its `client_id` and `state`, whose SHA-256 is what is kept.
fn state_value(client_id: &str, state: &str) -> String {
    format!("{}:{client_id}{state}", client_id.len())
}

/// Whether a client gave `state` in the last 24 hours: as kept now, or as
/// older servers kept it, in a namespace of the client's own.
fn state_used(svc: &Service, client_id: &str, state: &str, now: u64) -> bool {
    svc.replay
        .holds(STATE_NS, &state_value(client_id, state), now)
        || svc.replay.holds(&format!("state {client_id}"), state, now)
}

/// `POST /oauth/par`, checked in the order `spec/OAUTH.md` gives, with a
/// discoverable client loaded and a confidential one authenticated as
/// `spec/OAUTH-CLIENTS.md` adds. `address` is the client address.
async fn par(
    svc: &Service,
    tx: &mut Tx<'_>,
    headers: &HeaderMap,
    body: &[u8],
    address: &str,
) -> Out {
    let p = match Params::of(headers, body) {
        Ok(p) => p,
        Err(out) => return out,
    };
    let bad = |d: &str| refuse(400, "invalid_request", d);
    let Some(client_id) = p.filled("client_id") else {
        return refuse(400, "invalid_client", "client_id is required");
    };
    if let Err(why) = par_forms(&p) {
        return bad(&why);
    }
    // 4. The proof, if the request carries one. A request with none is
    // taken, its key then bound at the token request (the code grant's step
    // 2), as the reference takes it. This departs from `atproto/oauth.md`,
    // which has clients send a proof at PAR; it is taken only because the
    // reference takes it and clients written against it rely on it, and is
    // a candidate to drop once they send proofs (`spec/OAUTH.md`, "Where
    // the reference departs from the specs").
    let proof = match dpop::check(svc, headers, "POST", "/oauth/par", None) {
        Ok(proof) => proof,
        Err(r) => return refused_proof(r),
    };
    let client = match clients::load(svc, client_id).await {
        Ok(c) => c,
        Err(e) => return refuse(400, e, "Invalid client_id"),
    };
    let client_key =
        match clients::authenticate(svc, client_id, client.keys.as_deref(), &p, &mut tx.spent) {
            Ok(k) => k,
            Err(r) => return r.out(),
        };
    let text = |k: &str| p.text(k).ok().flatten();
    // 6. `dpop_jkt` given with a proof is its key's; given without one, it
    // is kept as the request's key.
    let dpop_jkt = text("dpop_jkt");
    if let (Some(j), Some(proof)) = (dpop_jkt, &proof)
        && j != proof.jkt
    {
        return refuse_dpop("invalid_token", "dpop_jkt does not match the DPoP proof");
    }
    let jkt = dpop_jkt.or(proof.as_ref().map(|p| p.jkt.as_str()));
    if ["claims", "id_token_hint", "nonce"]
        .iter()
        .any(|k| p.get(k).is_some())
    {
        return bad("claims, id_token_hint and nonce are not supported");
    }
    if text("response_type") != Some("code") {
        return refuse(
            400,
            "unsupported_response_type",
            "Only the code response type is supported",
        );
    }
    let tokens = scope::tokens(text("scope").unwrap_or_default());
    let declared = scope::tokens(&client.scope);
    if let Some(t) = tokens.iter().find(|t| !declared.contains(t)) {
        return refuse(
            400,
            "invalid_scope",
            format!("Scope {t} is not declared by the client"),
        );
    }
    let Some(redirect_uri) = client.redirect_uri(text("redirect_uri")) else {
        return bad("redirect_uri is not one of the client's");
    };
    let Some(challenge) = p.filled("code_challenge") else {
        return bad("code_challenge is required");
    };
    if !tokens.contains(&"atproto") {
        return refuse(400, "invalid_scope", "The atproto scope is required");
    }
    if tokens.contains(&"openid") {
        return refuse(400, "invalid_scope", "OpenID is not supported");
    }
    if text("code_challenge_method") != Some("S256") {
        return bad("code_challenge_method must be S256");
    }
    let confidential = client.keys.is_some();
    if text("prompt") == Some("none") && !confidential {
        return bad("A public client may not sign in silently");
    }
    let login_hint = text("login_hint").map(str::to_lowercase);
    if login_hint
        .as_deref()
        .is_some_and(|h| !pds_repo::data::valid_handle(h) && !pds_repo::data::valid_did(h))
    {
        return bad("login_hint is neither a handle nor a DID");
    }
    // 15. Each set the scope includes resolves, and is a set.
    if let Err((nsid, why)) = svc.oauth.sets.resolve_all(svc, &scope::kept(&tokens)).await {
        let description = match why {
            sets::Unresolved::Fails(_) => format!("Permission set {nsid} could not be resolved"),
            sets::Unresolved::NotASet | sets::Unresolved::NotASpace => {
                format!("{nsid} is not a permission set")
            }
        };
        return refuse(400, "invalid_scope", description);
    }
    let Some(state) = text("state").filter(|s| !s.is_empty()) else {
        return bad("state is required");
    };
    if state_used(svc, client_id, state, svc.sessions.now()) {
        return bad("state was used before");
    }
    if let Some(why) = too_large(&p) {
        return bad(why);
    }
    let addr = pending_key(address);
    let id = format!("req-{}", hex::encode(rand::random::<[u8; 16]>()));
    let low = low(svc);
    tx.change(|st, now| {
        if let Some(why) = st.pending.full(&addr) {
            return (vec![], refuse(429, "invalid_request", why));
        }
        if low {
            return (vec![], unavailable());
        }
        // The state is claimed only now, so that a request refused leaves it
        // unspent; of two requests with one state, the second is refused here.
        let Some(held) = svc.replay.claim(STATE_NS, &state_value(client_id, state), now, now + HELD_LIFE) else { return (vec![], bad("state was used before")) };
        let entry = json!({
            "t": "oauthRequest", "id": id, "client": client_id, "redirectUri": redirect_uri, "scope": scope::kept(&tokens),
            "state": state, "codeChallenge": challenge, "loginHint": login_hint,
            "prompt": if confidential { text("prompt") } else if text("prompt") == Some("create") { Some("create") } else { Some("consent") },
            "responseMode": text("response_mode").unwrap_or("query"), "uiLocales": text("ui_locales"),
            "jkt": jkt, "expires": now + REQUEST_LIFE, "clientKey": client_key, "addr": addr,
        });
        let kept = (vec![held, entry], ok(201, json!({ "request_uri": format!("{REQUEST_URI}{id}"), "expires_in": REQUEST_LIFE })));
        match &proof {
            Some(proof) => settle(svc, proof, now, low, kept),
            // A request with no proof has none to keep.
            None => kept,
        }
    })
}

/// Whether a PKCE verifier is of its form: 43 to 128 of `A-Za-z0-9-._~`.
fn verifier_form(v: &str) -> bool {
    (43..=128).contains(&v.len())
        && v.bytes()
            .all(|b| b.is_ascii_alphanumeric() || b"-._~".contains(&b))
}

/// A new session's or refresh's tokens, as the token endpoint answers them:
/// an MCP session's sealed apart, for the `Bearer` scheme.
fn token_answer(svc: &Service, sid: &str, s: &Session, now: u64) -> Json {
    let (access, refresh) = labels(s.mcp);
    json!({
        "access_token": svc.oauth.token(access, sid, &s.access), "token_type": if s.mcp { "Bearer" } else { "DPoP" },
        "refresh_token": svc.oauth.token(refresh, sid, &s.refresh), "scope": s.granted.join(" "),
        "expires_in": s.access_exp.saturating_sub(now), "sub": s.did,
    })
}

/// `POST /oauth/token`, checked in the order `spec/OAUTH.md` gives, with
/// the client loaded and authenticated as `spec/OAUTH-CLIENTS.md` adds.
async fn token(svc: &Service, tx: &mut Tx<'_>, headers: &HeaderMap, body: &[u8]) -> Out {
    let p = match Params::of(headers, body) {
        Ok(p) => p,
        Err(out) => return out,
    };
    let grant = |d: &str| refuse(400, "invalid_grant", d);
    let Some(client_id) = p.filled("client_id") else {
        return grant("client_id is required");
    };
    let grant_type = p.filled("grant_type");
    let fields = match grant_type {
        Some("authorization_code") => {
            p.filled("code").is_some()
                && p.text("redirect_uri")
                    .ok()
                    .flatten()
                    .is_some_and(client::redirect_form)
                && p.text("code_verifier")
                    .is_ok_and(|v| v.is_none_or(verifier_form))
        }
        Some("refresh_token") => p.filled("refresh_token").is_some(),
        Some("password" | "client_credentials") => true,
        _ => false,
    };
    if !fields {
        return grant("Invalid grant_type or its parameters");
    }
    let proof = match dpop::check(svc, headers, "POST", "/oauth/token", None) {
        Ok(proof) => proof,
        Err(r) => return refused_proof(r),
    };
    let client = match clients::load(svc, client_id).await {
        Ok(c) => c,
        Err(e) => return refuse(400, e, "Invalid client_id"),
    };
    let Some(proof) = proof else {
        return refuse_dpop("invalid_dpop_proof", "DPoP proof required");
    };
    let key = match clients::authenticate(svc, client_id, client.keys.as_deref(), &p, &mut tx.spent)
    {
        Ok(k) => k,
        Err(r) => return r.out(),
    };
    let low = low(svc);
    match grant_type {
        Some("authorization_code") => {
            let (code, redirect_uri, verifier) = (
                p.filled("code").unwrap_or_default(),
                p.filled("redirect_uri").unwrap_or_default(),
                p.filled("code_verifier"),
            );
            // The sets and space declarations the code's scope names,
            // resolved again, with no lock held.
            let approved = svc.oauth.approved_scope(code);
            let sets = svc.oauth.sets.for_token(svc, &approved).await.ok();
            let mut out = tx.change(|st, now| {
                settle(
                    svc,
                    &proof,
                    now,
                    low,
                    exchange(
                        svc,
                        st,
                        now,
                        low,
                        client_id,
                        false,
                        &proof.jkt,
                        key.as_deref(),
                        code,
                        redirect_uri,
                        verifier,
                        sets.as_ref(),
                    ),
                )
            });
            // A client without the refresh grant is given no refresh token.
            if !client.refresh
                && let Some(body) = out.body.as_object_mut()
            {
                body.remove("refresh_token");
            }
            out
        }
        Some("refresh_token") if client.refresh => {
            let token = p.filled("refresh_token").unwrap_or_default();
            // The session's sets and declarations, resolved again, with no lock held.
            let consented = svc.oauth.session_scope("refresh", token);
            let sets = svc.oauth.sets.for_token(svc, &consented).await.ok();
            tx.change(|st, now| {
                settle(
                    svc,
                    &proof,
                    now,
                    low,
                    refresh(
                        svc,
                        st,
                        now,
                        client_id,
                        false,
                        &proof.jkt,
                        key.as_deref(),
                        token,
                        sets.as_ref(),
                    ),
                )
            })
        }
        _ => grant("Unsupported grant_type"),
    }
}

/// The code grant: entries to log, and the answer. `jkt` is the token
/// request's proof's key, which the session is bound to: the request's
/// key, where it kept one, must be it (`spec/OAUTH.md`, the code grant's
/// step 2). `key` is the client key the request was authenticated with, if
/// any; `mcp`, whether it is the MCP issuer's, which takes only its own
/// codes, and binds no DPoP key (`jkt` empty). Below the free-space floor
/// (`low`), a code that would be exchanged is refused before its challenge
/// is spent.
#[allow(clippy::too_many_arguments)]
fn exchange(
    svc: &Service,
    st: &State,
    now: u64,
    low: bool,
    client_id: &str,
    mcp: bool,
    jkt: &str,
    key: Option<&str>,
    code: &str,
    redirect_uri: &str,
    verifier: Option<&str>,
    sets: Option<&sets::Expansion>,
) -> (Vec<Json>, Out) {
    let refused = || refuse(400, "invalid_grant", "Invalid code");
    // A code the other issuer gave is none of this one's.
    let Some((r, a)) = st
        .codes
        .get(code)
        .and_then(|id| st.requests.get(id))
        .and_then(|r| Some((r, r.approval.as_ref()?)))
        .filter(|(r, _)| r.mcp() == mcp)
    else {
        // A code used twice ends what the first use made.
        let end = st
            .by_code
            .get(code)
            .filter(|sid| st.sessions.get(*sid).is_some_and(|s| s.mcp == mcp))
            .map(|sid| json!({ "t": "oauthEndSession", "sid": sid }));
        return (end.into_iter().collect(), refused());
    };
    let spend = || vec![json!({ "t": "oauthSpendCode", "code": code })];
    if now >= a.at + CODE_LIFE
        || r.client_id != client_id
        || r.jkt.as_deref().is_some_and(|k| k != jkt)
        || r.client_key.as_deref() != key
        || r.redirect_uri != redirect_uri
    {
        return (spend(), refused());
    }
    if verifier.is_none_or(|v| B64.encode(Sha256::digest(v.as_bytes())) != r.code_challenge) {
        return (spend(), refused());
    }
    // 6. Its account neither taken down nor deactivated now, whenever it was
    // approved (`spec/LIFECYCLE.md`): read under OAuth's lock, which a change
    // of the account's state takes before its own (`OAuth::end_for`).
    let up = svc.account(&a.did).is_some_and(|acct| {
        let state = crate::read(&acct.state);
        state.takedown.is_none() && !state.deactivated && !state.deleted
    });
    if !up {
        return (spend(), refused());
    }
    // The sets and space declarations its scope names, each resolved again
    // (`spec/OAUTH-PERMISSION-SETS.md`, `spec/OAUTH-SCOPES.md`).
    let Some(sets) = sets else {
        return (
            vec![],
            refuse(
                400,
                "invalid_request",
                "A permission set or space declaration could not be resolved",
            ),
        );
    };
    if low {
        return (vec![], unavailable());
    }
    let Some(held) = svc
        .replay
        .claim("pkce", &r.code_challenge, now, now + HELD_LIFE)
    else {
        return (spend(), refused());
    };
    let sid = new_id(16);
    let mut s = Session {
        did: a.did.clone(),
        client_id: client_id.to_string(),
        jkt: jkt.to_string(),
        scope: a.scope.clone(),
        granted: sets::expand(&a.scope, sets, &a.did),
        started: now,
        code: code.to_string(),
        access: new_id(12),
        access_exp: 0,
        refresh: new_id(12),
        client_key: r.client_key.clone(),
        refreshed: now,
        mcp,
    };
    s.access_exp = (now + ACCESS_LIFE).min(s.end());
    let mut entry = json!({
        "t": "oauthSession", "sid": sid, "did": s.did, "client": s.client_id, "jkt": s.jkt, "scope": s.scope, "granted": s.granted,
        "started": s.started, "code": s.code, "access": s.access, "accessExp": s.access_exp, "refresh": s.refresh,
        "clientKey": s.client_key,
    });
    if mcp {
        entry["mcp"] = json!(true);
    }
    (vec![held, entry], ok(200, token_answer(svc, &sid, &s, now)))
}

/// The refresh grant: entries to log, and the answer. `mcp` as `exchange`'s.
#[allow(clippy::too_many_arguments)]
fn refresh(
    svc: &Service,
    st: &State,
    now: u64,
    client_id: &str,
    mcp: bool,
    jkt: &str,
    key: Option<&str>,
    token: &str,
    sets: Option<&sets::Expansion>,
) -> (Vec<Json>, Out) {
    let refused = || refuse(400, "invalid_grant", "Invalid refresh token");
    let Some((sid, jti)) = svc.oauth.token_of(labels(mcp).1, token) else {
        return (vec![], refused());
    };
    let Some(s) = st.sessions.get(&sid).filter(|s| s.mcp == mcp) else {
        return (vec![], refused());
    };
    if s.refresh != jti
        || s.client_id != client_id
        || s.jkt != jkt
        || s.client_key.as_deref() != key
        || now >= s.end()
    {
        return (
            vec![json!({ "t": "oauthEndSession", "sid": sid })],
            refused(),
        );
    }
    let mut next = s.clone();
    next.access = new_id(12);
    next.refreshed = now;
    next.access_exp = (now + ACCESS_LIFE).min(next.end());
    next.refresh = new_id(12);
    // Expanded again from its sets and declarations as they are now; as it
    // was if one no longer resolves.
    if let Some(sets) = sets {
        next.granted = sets::expand(&next.scope, sets, &next.did);
    }
    let entry = json!({ "t": "oauthRefresh", "sid": sid, "access": next.access, "accessExp": next.access_exp, "refresh": next.refresh, "at": now, "granted": next.granted });
    (vec![entry], ok(200, token_answer(svc, &sid, &next, now)))
}

/// The session a token names, of any kind revocation takes: its current
/// access token, its refresh tokens current and replaced, and, of an
/// atproto session, its code; `mcp` as `exchange`'s.
fn session_of<'s>(
    svc: &Service,
    st: &'s State,
    token: &str,
    mcp: bool,
) -> Option<(String, &'s Session)> {
    let found = |sid: &str| {
        st.sessions
            .get(sid)
            .filter(|s| s.mcp == mcp)
            .map(|s| (sid.to_string(), s))
    };
    let (access, refresh) = labels(mcp);
    if let Some((sid, jti)) = svc.oauth.token_of(access, token) {
        return found(&sid).filter(|(_, s)| s.access == jti);
    }
    if let Some((sid, _)) = svc.oauth.token_of(refresh, token) {
        return found(&sid);
    }
    if mcp {
        return None;
    }
    found(st.by_code.get(token)?)
}

/// `POST /oauth/revoke` (RFC 7009). With a proof, the client is loaded and,
/// if confidential, authenticated: either refused, nothing changes. Its
/// proof is kept durably only if a token is revoked.
async fn revoke(svc: &Service, tx: &mut Tx<'_>, headers: &HeaderMap, body: &[u8]) -> Out {
    let p = match Params::of(headers, body) {
        Ok(p) => p,
        Err(out) => return out,
    };
    let hint = p.text("token_type_hint");
    if p.filled("client_id").is_none()
        || p.filled("token").is_none()
        || !hint.is_ok_and(|h| h.is_none_or(|h| ["access_token", "refresh_token"].contains(&h)))
    {
        return refuse(
            400,
            "invalid_request",
            "client_id and token are required, and token_type_hint must be a token type",
        );
    }
    let proof = match dpop::check(svc, headers, "POST", "/oauth/revoke", None) {
        Ok(proof) => proof,
        Err(r) => return refused_proof(r),
    };
    let Some(proof) = proof else {
        return ok(200, json!({}));
    };
    let (client_id, token) = (
        p.filled("client_id").unwrap_or_default(),
        p.filled("token").unwrap_or_default(),
    );
    let Ok(client) = clients::load(svc, client_id).await else {
        return ok(200, json!({}));
    };
    let Ok(key) = clients::authenticate(svc, client_id, client.keys.as_deref(), &p, &mut tx.spent)
    else {
        return ok(200, json!({}));
    };
    let low = low(svc);
    tx.change(|st, now| {
        let mine =
            |s: &Session| s.client_id == client_id && s.jkt == proof.jkt && s.client_key == key;
        let end = session_of(svc, st, token, false)
            .filter(|(_, s)| mine(s))
            .map(|(sid, _)| json!({ "t": "oauthEndSession", "sid": sid }));
        settle(
            svc,
            &proof,
            now,
            low,
            (end.into_iter().collect(), ok(200, json!({}))),
        )
    })
}

// ---- OAuth access tokens at XRPC --------------------------------------------
//
// What every method that takes a token asks of a call made with
// `Authorization: DPoP <access token>`; which methods do, and what they need
// of the session's scope, is `crate::scopes` (`spec/OAUTH-SCOPES.md`).

/// The session an XRPC call's OAuth access token is of, once the token and its proof pass.
pub(crate) struct Access {
    pub did: String,
    /// Its scope tokens, as kept and narrowed, its `include:` scopes expanded.
    pub scope: Vec<String>,
}

/// Check an XRPC call to `path` made with `Authorization: DPoP <token>`, in
/// the order `spec/OAUTH.md` gives under "OAuth tokens on XRPC": its proof,
/// then its token. A proof that passes is spent; once its token is found
/// good it is kept, and on disk before this answers, but below the
/// free-space floor it is held in memory alone, as it is for a call refused.
/// A refusal is the error to name, `invalid_dpop_proof`, `use_dpop_nonce`
/// or `invalid_token`, and why; the outer error, that the proof kept could
/// not be logged.
pub(crate) async fn access(
    svc: &Shared,
    method: &Method,
    path: &str,
    headers: &HeaderMap,
    token: &str,
) -> Result<Result<Access, (&'static str, String)>, crate::XrpcError> {
    let mut tx = Tx::new(svc);
    let out = check_access(svc, &mut tx, method, path, headers, token);
    if tx.done().await {
        Ok(out)
    } else {
        crate::internal()
    }
}

fn check_access(
    svc: &Service,
    tx: &mut Tx,
    method: &Method,
    path: &str,
    headers: &HeaderMap,
    token: &str,
) -> Result<Access, (&'static str, String)> {
    let invalid_token = || Err(("invalid_token", "Invalid token".to_string()));
    let proof = dpop::check(svc, headers, method.as_str(), path, Some(token))
        .map_err(|r| (r.error(), r.description().to_string()))?;
    let Some((sid, jti)) = svc.oauth.token_of("access", token) else {
        return invalid_token();
    };
    let Some(proof) = proof else {
        return Err(("invalid_dpop_proof", "DPoP proof required".into()));
    };
    let session = tx.change(|st, now| {
        (
            vec![],
            st.sessions
                .get(&sid)
                .filter(|s| !s.mcp && s.jkt == proof.jkt && s.access == jti && now < s.access_exp)
                .cloned(),
        )
    });
    let Some(s) = session else {
        return invalid_token();
    };
    if svc.account(&s.did).is_none() {
        return invalid_token();
    }
    if !low(svc) {
        let Some(kept) = dpop::keep(svc, &proof, svc.sessions.now()) else {
            return Err((
                "invalid_dpop_proof",
                "DPoP proof jti was used before".into(),
            ));
        };
        tx.spent.push(kept);
    }
    Ok(Access {
        did: s.did,
        scope: s.granted,
    })
}

/// The headers of an answer to an XRPC call with the `DPoP` scheme whose
/// token was looked at: the nonce, the refusal of the token or proof if it
/// was refused (`error` and why), and that a browser's script may read them,
/// after any the answer exposes already (the rate limits').
pub(crate) fn dpop_headers(svc: &Service, r: &mut Response, refused: Option<(&str, &str)>) {
    set(r, "dpop-nonce", &svc.oauth.nonce(svc.sessions.now()));
    let ours = match refused {
        Some((error, why)) => {
            set(r, "www-authenticate", &www_authenticate(error, why));
            "DPoP-Nonce, WWW-Authenticate"
        }
        None => "DPoP-Nonce",
    };
    let expose = match r
        .headers()
        .get("access-control-expose-headers")
        .and_then(|v| v.to_str().ok())
    {
        Some(before) if !before.is_empty() => format!("{before}, {ours}"),
        _ => ours.to_string(),
    };
    set(r, "access-control-expose-headers", &expose);
}