chadtmiller.com/hud
A remote MCP server that shows atproto records as interactive UI inside MCP Apps hosts
place.hud.hudkit 0.5.0 Latest 5 packages
0
0
//! HUD as a confidential atproto OAuth client of each account's server
//! (atproto's OAuth profile, https://atproto.com/specs/oauth). Its
//! `client_id` is its metadata's URL, `<origin>/oauth/client-metadata.json`;
//! it authenticates with `private_key_jwt`, an ES256 assertion signed by its
//! client key, which `/oauth/jwks.json` publishes.
//!
//! An account named on the sign-in page is resolved to its PDS, whose
//! protected resource metadata names its authorization server; that
//! server's metadata must name itself as issuer, and offer PAR, DPoP with
//! ES256 and `private_key_jwt`. The request is pushed (PAR) with PKCE, a
//! `state` and a DPoP proof of a key made for the session, and the person
//! sent to the server's authorization endpoint. Its answer comes back to
//! `/oauth/callback`: the `state` and `iss` checked, the code exchanged, the
//! token answer checked (DPoP-bound; its `sub` the account named) and its
//! `sub` resolved again, fresh, its PDS's authorization server the one that
//! answered. "Create one" pushes its request to the sign-up PDS's
//! authorization server instead (`Config::sign_up_pds`), with
//! `prompt=create` and no login hint: no account is named, so its answer's
//! `sub`, resolved, is the account. Every request to the server carries a
//! DPoP proof, and is sent again once with the server's `DPoP-Nonce` when
//! it asks for one.
//!
//! A call to the PDS as the account carries its access token as `DPoP` and
//! a proof naming it (`ath`). The token is refreshed when it has expired, or
//! when the PDS refuses it as `invalid_token`, one refresh at a time per
//! session; a refresh the server refuses ends the session.
use super::issuer::{Pending, unissued, with_query};
use super::store::{Kind, Session};
use super::{Account, Asker, Auth, Flow, PENDING_LIFE, PENDING_MAX, now};
use crate::Hud;
use crate::net::Fetched;
use crate::tools::Refusal;
use atproto::jose;
use atproto::keys::{Curve, Keypair};
use bytes::Bytes;
use serde_json::{Value, json};
use std::collections::BTreeMap;
use std::time::Duration;
use url::Url;
/// How long a request to an account's server has.
const WAIT: Duration = Duration::from_secs(10);
/// The most of a metadata document or a token answer read.
const META_MAX: usize = 64 * 1024;
/// The most of a PDS's answer read.
const ANSWER_MAX: usize = 5 * 1024 * 1024;
/// How long before it expires an access token is refreshed.
const EARLY: u64 = 30;
/// How long a client assertion is good for.
const ASSERTION_LIFE: u64 = 60;
/// An account's authorization server, as HUD needs it.
#[derive(Clone, Debug, PartialEq)]
pub struct Server {
pub issuer: String,
pub par: String,
pub authorization: String,
pub token: String,
pub revocation: Option<String>,
}
/// Why the sign-in page's form did not go on to the account's server.
#[derive(Debug, PartialEq)]
pub enum SignIn {
/// Its request is gone: expired, or already used.
Expired,
/// The page again, its request as it shows it with the handle as
/// typed, and a line saying why.
Failed(Pending, String),
}
/// Where `/oauth/callback` sends the person on to.
#[derive(Debug, PartialEq)]
pub enum Callback {
/// The MCP client's redirect URI, with HUD's code or an error.
Client(String),
/// The workspace, a web session begun: its cookie, to give the browser.
Web(String),
/// Nowhere: the workspace's sign-in did not finish, and why.
WebRefused(String),
}
/// A token answer, checked.
#[derive(Debug, PartialEq)]
pub(crate) struct Tokens {
pub access: String,
pub refresh: Option<String>,
pub expires_at: u64,
pub scope: String,
pub sub: String,
}
/// Why a refresh did not happen.
enum Unrefreshed {
/// The server refused it: the session is over.
Refused,
/// The server could not be reached, or failed: the session stays.
Unreachable(String),
}
/// A session's state for one call: its token, key, PDS and nonces, and
/// whether it asked for a permission set.
struct Snapshot {
token: String,
key: Keypair,
pds: String,
nonces: BTreeMap<String, String>,
sets: bool,
}
/// What a request pushed asks for.
enum Push<'a> {
/// A sign-in as the account named: its DID, and the login hint.
SignIn { did: String, login: &'a str },
/// A new account (`prompt=create`), at the sign-up PDS.
SignUp,
}
/// A URL's host, as a person reads it.
fn host_of(url: &str) -> String {
Url::parse(url)
.ok()
.and_then(|u| u.host_str().map(str::to_string))
.unwrap_or_else(|| url.to_string())
}
/// A URL's origin.
pub(crate) fn origin_of(url: &str) -> String {
Url::parse(url).map_or_else(|_| url.to_string(), |u| u.origin().ascii_serialization())
}
/// A URL as a DPoP proof's `htu` names it: without its query or fragment.
fn htu(url: &Url) -> String {
format!("{}{}", url.origin().ascii_serialization(), url.path())
}
/// HUD's client assertion for the server `aud` (RFC 7523): signed by its
/// client key, `iss` and `sub` its client ID.
pub(crate) fn client_assertion(auth: &Auth, aud: &str) -> String {
let iat = now();
let client_id = auth.client_id();
jose::sign(
&auth.key,
&json!({ "typ": "JWT", "kid": auth.kid }),
&json!({
"iss": client_id,
"sub": client_id,
"aud": aud,
"jti": jose::random(16),
"iat": iat,
"exp": iat + ASSERTION_LIFE,
}),
)
}
/// A DPoP proof (RFC 9449) of `key` for a request: its method and URL, the
/// server's nonce if it gave one, and `ath`, the access token's hash, at a
/// resource.
pub(crate) fn dpop_proof(
key: &Keypair,
htm: &str,
url: &Url,
nonce: Option<&str>,
ath: Option<&str>,
) -> String {
let mut claims = json!({ "jti": jose::random(16), "htm": htm, "htu": htu(url), "iat": now() });
if let Some(n) = nonce {
claims["nonce"] = n.into();
}
if let Some(a) = ath {
claims["ath"] = a.into();
}
jose::sign(
key,
&json!({ "typ": "dpop+jwt", "jwk": jose::jwk(&key.public()) }),
&claims,
)
}
/// The OAuth error an answer names: its body's `error`, else its
/// `WWW-Authenticate`'s.
fn oauth_error(got: &Fetched) -> Option<String> {
let body: Option<String> = serde_json::from_slice::<Value>(&got.body)
.ok()
.and_then(|v| v.get("error")?.as_str().map(str::to_string));
body.or_else(|| {
let h = got.header("www-authenticate")?;
let (_, rest) = h.split_once("error=\"")?;
Some(rest.split('"').next()?.to_string())
})
}
/// An error name as safe to repeat: letters, digits and `_`, briefly.
fn safe_name(v: &Value) -> Option<&str> {
let e = v.get("error")?.as_str()?;
(!e.is_empty() && e.len() <= 64 && e.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_'))
.then_some(e)
}
/// A token answer, checked: DPoP-bound, its `sub` a DID, its scope with
/// `atproto`.
pub(crate) fn tokens_of(v: &Value) -> Result<Tokens, String> {
let text = |k: &str| v.get(k).and_then(Value::as_str).filter(|s| !s.is_empty());
if !text("token_type").is_some_and(|t| t.eq_ignore_ascii_case("DPoP")) {
return Err("its tokens are not DPoP-bound".into());
}
let access = text("access_token").ok_or("it gave no access token")?;
let sub = text("sub")
.filter(|s| atproto::syntax::is_did(s))
.ok_or("it named no account")?;
let scope = text("scope").unwrap_or_default();
if !scope.split(' ').any(|s| s == "atproto") {
return Err("its scope lacks atproto".into());
}
let refresh = match v.get("refresh_token") {
None | Some(Value::Null) => None,
Some(Value::String(r)) if !r.is_empty() => Some(r.clone()),
Some(_) => return Err("its refresh token is not a string".into()),
};
Ok(Tokens {
access: access.to_string(),
refresh,
expires_at: now() + v.get("expires_in").and_then(Value::as_u64).unwrap_or(3600),
scope: scope.to_string(),
sub: sub.to_string(),
})
}
/// An endpoint an authorization server names: a URL HUD may call.
fn endpoint(meta: &Value, k: &str, allow_private: bool) -> Option<String> {
let u = Url::parse(meta.get(k)?.as_str()?).ok()?;
let plain = u.username().is_empty() && u.password().is_none() && u.fragment().is_none();
(plain && crate::net::check_url(&u, allow_private).is_ok()).then(|| u.to_string())
}
impl Auth {
/// Keep a sign-in in progress, by its `state`.
fn keep_flow(&self, state: String, flow: Flow) -> Result<(), String> {
let mut st = self.lock();
let now = now();
st.flows.retain(|_, f| f.created + PENDING_LIFE > now);
if st.flows.len() >= PENDING_MAX {
return Err("Too many sign-ins are waiting; try again in a few minutes".into());
}
st.flows.insert(state, flow);
Ok(())
}
}
impl Hud {
/// A JSON object at `url`, answered there, not by a redirect.
async fn get_json(&self, url: &str) -> Result<Value, String> {
let url = Url::parse(url).ok().ok_or("not a URL")?;
let got = self.net.fetch_json(&url, WAIT, META_MAX).await?;
if got.redirected || got.status != 200 {
return Err(format!("it answered {}", got.status));
}
match serde_json::from_slice(&got.body) {
Ok(v @ Value::Object(_)) => Ok(v),
_ => Err("it answered something that is not a JSON object".into()),
}
}
/// The authorization server of a PDS: the first its protected resource
/// metadata names, whose own metadata names it as issuer and offers
/// PAR, DPoP with ES256 and `private_key_jwt` with ES256.
pub(crate) async fn authorization_server(&self, pds: &str) -> Result<Server, String> {
let no_oauth = "Your account's server does not offer OAuth sign-in";
let resource = self
.get_json(&format!("{pds}/.well-known/oauth-protected-resource"))
.await
.map_err(|_| no_oauth.to_string())?;
let issuer = resource["authorization_servers"][0]
.as_str()
.ok_or(no_oauth)?;
let issuer_ok = Url::parse(issuer).is_ok_and(|u| {
u.origin().ascii_serialization() == issuer
&& crate::net::check_url(&u, self.net.allow_private()).is_ok()
});
if !issuer_ok {
return Err(
"Your account's server names an authorization server HUD cannot use".into(),
);
}
let meta = self
.get_json(&format!("{issuer}/.well-known/oauth-authorization-server"))
.await
.map_err(|_| "Your account's authorization server could not be read".to_string())?;
if meta["issuer"] != issuer {
return Err("Your account's authorization server names another issuer".into());
}
let has = |k: &str, v: &str| meta[k].as_array().is_some_and(|a| a.iter().any(|x| x == v));
let signing = meta["token_endpoint_auth_signing_alg_values_supported"].is_null()
|| has("token_endpoint_auth_signing_alg_values_supported", "ES256");
if !has("dpop_signing_alg_values_supported", "ES256")
|| !has("token_endpoint_auth_methods_supported", "private_key_jwt")
|| !signing
{
return Err(
"Your account's authorization server does not offer what HUD signs in with (DPoP and private_key_jwt, ES256)"
.into(),
);
}
let allow = self.net.allow_private();
let (Some(par), Some(authorization), Some(token)) = (
endpoint(&meta, "pushed_authorization_request_endpoint", allow),
endpoint(&meta, "authorization_endpoint", allow),
endpoint(&meta, "token_endpoint", allow),
) else {
return Err("Your account's authorization server lacks an endpoint HUD needs".into());
};
Ok(Server {
issuer: issuer.to_string(),
par,
authorization,
token,
revocation: endpoint(&meta, "revocation_endpoint", allow),
})
}
/// POST a form to an authorization server's endpoint, as HUD: its
/// client assertion and a DPoP proof of `key`, sent again once with a
/// new nonce if the server asks for one. Its status and JSON body.
async fn as_post(
&self,
auth: &Auth,
issuer: &str,
endpoint: &str,
key: &Keypair,
nonce: &mut Option<String>,
form: &[(&str, &str)],
) -> Result<(u16, Value), String> {
let url = Url::parse(endpoint).map_err(|_| "not a URL".to_string())?;
let client_id = auth.client_id();
let mut retried = false;
loop {
let body = url::form_urlencoded::Serializer::new(String::new())
.extend_pairs(form)
.append_pair("client_id", &client_id)
.append_pair(
"client_assertion_type",
"urn:ietf:params:oauth:client-assertion-type:jwt-bearer",
)
.append_pair("client_assertion", &client_assertion(auth, issuer))
.finish();
let req = self
.net
.post(&url)?
.header(
reqwest::header::CONTENT_TYPE,
"application/x-www-form-urlencoded",
)
.header(reqwest::header::ACCEPT, "application/json")
.header(
"DPoP",
dpop_proof(key, "POST", &url, nonce.as_deref(), None),
)
.body(body);
let got = self.net.send(req, WAIT, META_MAX).await?;
if got.redirected {
return Err("it answered from elsewhere".into());
}
let fresh = got.header("dpop-nonce").map(str::to_string);
let changed = fresh.is_some() && fresh != *nonce;
if fresh.is_some() {
*nonce = fresh;
}
if !retried && changed && oauth_error(&got).as_deref() == Some("use_dpop_nonce") {
retried = true;
continue;
}
let body = serde_json::from_slice(&got.body).unwrap_or(Value::Null);
return Ok((got.status, body));
}
}
/// The sign-in page's form: the account named, its server found, the
/// request pushed; the URL of the server's authorization page. Else its
/// page again, saying why, while its request still waits.
pub async fn sign_in(&self, request_id: &str, login: &str) -> Result<String, SignIn> {
let Ok(auth) = self.auth() else {
return Err(SignIn::Expired);
};
if auth.pending(request_id).is_none() {
return Err(SignIn::Expired);
}
let why = match self.push(auth, request_id, login).await {
Ok(to) => return Ok(to),
Err(why) => why,
};
let mut page = auth.pending(request_id).ok_or(SignIn::Expired)?;
page.login_hint = Some(login.trim().to_string()).filter(|h| !h.is_empty());
Err(SignIn::Failed(page, why))
}
/// The account named resolved, its server found, the request pushed
/// and taken; the URL of the server's authorization page, else why not.
async fn push(&self, auth: &Auth, request_id: &str, login: &str) -> Result<String, String> {
let login = login.trim().trim_start_matches('@');
let login = if atproto::syntax::is_did(login) {
login.to_string()
} else {
login.to_ascii_lowercase()
};
if login.is_empty() {
return Err("Enter your handle, as alice.bsky.social".into());
}
if !atproto::syntax::is_handle(&login) && !atproto::syntax::is_did(&login) {
return Err(format!("{login} is not a handle or a DID"));
}
let who = self
.resolve_actor(&login)
.await
.map_err(|_| format!("{login} does not resolve to an account"))?;
let server = self.authorization_server(&who.pds).await?;
self.push_to(
auth,
request_id,
server,
Push::SignIn {
did: who.did,
login: &login,
},
)
.await
}
/// "Create one": the request pushed to the authorization server of the
/// sign-up PDS (`Config::sign_up_pds`) with `prompt=create` and no
/// login hint, the account known only once its answer names it; the
/// URL of that server's sign-up page. Else its page again, saying why,
/// while its request still waits.
pub async fn sign_up(&self, request_id: &str) -> Result<String, SignIn> {
let Ok(auth) = self.auth() else {
return Err(SignIn::Expired);
};
if auth.pending(request_id).is_none() {
return Err(SignIn::Expired);
}
let pds = &self.config.sign_up_pds;
let why = match self.authorization_server(pds).await {
Ok(server) => match self.push_to(auth, request_id, server, Push::SignUp).await {
Ok(to) => return Ok(to),
Err(why) => why,
},
Err(why) => {
tracing::warn!(pds, why, "sign-up PDS unusable");
format!(
"Accounts can't be made at {} now; try again later",
host_of(pds)
)
}
};
let page = auth.pending(request_id).ok_or(SignIn::Expired)?;
Err(SignIn::Failed(page, why))
}
/// A sign-in's request pushed (PAR, PKCE, DPoP) to `server`, the
/// request waiting taken and its flow kept: the URL of the server's
/// authorization page, else why not. Asking for the apps' permission
/// sets first (`Auth::include`), and where the server refuses them
/// (`invalid_scope`: one that knows no sets, or cannot resolve them
/// now), for what the views do (`Auth::scope`) instead.
async fn push_to(
&self,
auth: &Auth,
request_id: &str,
server: Server,
how: Push<'_>,
) -> Result<String, String> {
let state = jose::random(16);
let verifier = jose::random(32);
let dpop = Keypair::generate(Curve::P256);
let mut nonce = None;
let challenge = jose::sha256(&verifier);
let redirect_uri = auth.redirect_uri();
let mut form = vec![
("response_type", "code"),
("code_challenge", challenge.as_str()),
("code_challenge_method", "S256"),
("state", state.as_str()),
("redirect_uri", redirect_uri.as_str()),
];
let (named, did) = match &how {
Push::SignIn { did, login } => {
form.push(("login_hint", *login));
("Your account's server".to_string(), Some(did.clone()))
}
Push::SignUp => {
form.push(("prompt", "create"));
(host_of(&self.config.sign_up_pds), None)
}
};
// Owned, as a borrow held across a send makes the future not `Send`.
let asks: Vec<String> = auth.include.iter().chain([&auth.scope]).cloned().collect();
let mut asks = asks.into_iter().peekable();
let (asked, status, body) = loop {
let asked = asks.next().expect("the views' scope is asked last");
let mut form = form.clone();
form.push(("scope", asked.as_str()));
let pushed = self
.as_post(auth, &server.issuer, &server.par, &dpop, &mut nonce, &form)
.await;
let (status, body) =
pushed.map_err(|why| format!("{named} could not be reached: {why}"))?;
if asks.peek().is_some() && safe_name(&body) == Some("invalid_scope") {
let issuer = &server.issuer;
tracing::warn!(issuer, "permission sets refused; asking without");
continue;
}
break (asked, status, body);
};
let request_uri = body["request_uri"]
.as_str()
.filter(|_| (200..300).contains(&status));
let Some(request_uri) = request_uri else {
let error = safe_name(&body);
tracing::warn!(status, error, issuer = server.issuer, "PAR refused");
return Err(match error {
Some(e) => format!("{named} refused the sign-in: {e}"),
None => format!("{named} refused the sign-in ({status})"),
});
};
// Gone meanwhile, it is told as expired, whatever this says.
let asker = auth.take_request(request_id).ok_or(String::new())?;
let to = with_query(
&server.authorization,
&[
("client_id", &auth.client_id()),
("request_uri", request_uri),
],
);
auth.keep_flow(
state,
Flow {
asker,
verifier,
dpop,
server,
did,
nonce,
asked,
created: now(),
},
)?;
Ok(to)
}
/// `GET /oauth/callback`: the account's server's answer. For an MCP
/// client's sign-in, its redirect URI with HUD's code or an error; for
/// the workspace's, a web session's cookie or why there is none; or,
/// where the sign-in it answers is unknown, a line for an error page.
pub async fn callback(&self, query: &[(String, String)]) -> Result<Callback, String> {
let auth = self.auth()?;
let p = super::issuer::params(query)?;
let flow = p
.get("state")
.and_then(|s| auth.lock().flows.remove(s))
.filter(|f| f.created + PENDING_LIFE > now())
.ok_or("This sign-in has expired or was already used; start again from your app")?;
let back = |error: &str, why: &str| match &flow.asker {
Asker::Mcp(request) => Callback::Client(request.back(
&auth.origin,
&[("error", error), ("error_description", why)],
)),
Asker::Web { .. } => Callback::WebRefused(why.to_string()),
};
if let Some(e) = p.get("error") {
let error = match e.as_str() {
"access_denied" | "login_required" | "consent_required" => e.as_str(),
_ => "access_denied",
};
return Ok(back(
error,
"The sign-in at your account's server did not finish",
));
}
if p.get("iss") != Some(&flow.server.issuer) {
return Ok(back(
"access_denied",
"The answer came from another server than the one asked",
));
}
let Some(code) = p.get("code").filter(|c| !c.is_empty()) else {
return Ok(back("server_error", "Your account's server gave no code"));
};
let session = match self.exchange(auth, &flow, code).await {
Ok(s) => s,
Err(why) => {
tracing::warn!(did = flow.did.as_deref(), why, "sign-in refused");
return Ok(back("access_denied", &why));
}
};
let Asker::Mcp(request) = &flow.asker else {
return Ok(Callback::Web(auth.start_web(session)));
};
match auth.give_code(request, session) {
Ok(code) => Ok(Callback::Client(
request.back(&auth.origin, &[("code", &code)]),
)),
Err(why) => Ok(back("temporarily_unavailable", &why)),
}
}
/// Exchange the account's server's code, check its answer, resolve its
/// `sub` again: the session, its MCP tokens not yet given.
async fn exchange(&self, auth: &Auth, flow: &Flow, code: &str) -> Result<Session, String> {
let mut nonce = flow.nonce.clone();
let redirect_uri = auth.redirect_uri();
let (status, body) = self
.as_post(
auth,
&flow.server.issuer,
&flow.server.token,
&flow.dpop,
&mut nonce,
&[
("grant_type", "authorization_code"),
("code", code),
("redirect_uri", &redirect_uri),
("code_verifier", &flow.verifier),
],
)
.await
.map_err(|why| format!("Your account's server could not be reached: {why}"))?;
if status != 200 {
return Err(match safe_name(&body) {
Some(e) => format!("Your account's server refused the code: {e}"),
None => format!("Your account's server refused the code ({status})"),
});
}
let t = tokens_of(&body).map_err(|why| format!("Your account's server's answer: {why}"))?;
if flow.did.as_ref().is_some_and(|did| t.sub != *did) {
return Err("You signed in as another account than the one you named".into());
}
// The account resolved again, fresh (or for the first time, one
// just made): its PDS's authorization server must be the one that
// answered.
self.fresh_did_doc(&t.sub).await?;
let who = self.resolve_actor(&t.sub).await?;
let server = self.authorization_server(&who.pds).await?;
if server.issuer != flow.server.issuer {
return Err("Your account's server is not the one that signed you in".into());
}
let mut nonces = BTreeMap::new();
if let Some(n) = nonce {
nonces.insert(origin_of(&flow.server.token), n);
}
let (client_id, kind) = match &flow.asker {
Asker::Mcp(request) => (request.client_id.clone(), Kind::Mcp),
Asker::Web { .. } => (String::new(), Kind::Web),
};
Ok(Session {
id: jose::random(32),
did: t.sub,
handle: who.handle,
pds: who.pds,
issuer: flow.server.issuer.clone(),
token_endpoint: flow.server.token.clone(),
revocation_endpoint: flow.server.revocation.clone(),
scope: t.scope,
asked: flow.asked.clone(),
access_token: t.access,
refresh_token: t.refresh,
expires_at: t.expires_at,
dpop: flow.dpop.clone(),
nonces,
client_id,
kind,
mcp: unissued(),
created_at: now(),
ended: false,
})
}
/// Refresh a session's atproto tokens, its lock held.
async fn refresh_locked(&self, auth: &Auth, s: &mut Session) -> Result<(), Unrefreshed> {
let Some(refresh) = s.refresh_token.clone() else {
return Err(Unrefreshed::Refused);
};
let origin = origin_of(&s.token_endpoint);
let mut nonce = s.nonces.get(&origin).cloned();
let answered = self
.as_post(
auth,
&s.issuer,
&s.token_endpoint,
&s.dpop,
&mut nonce,
&[("grant_type", "refresh_token"), ("refresh_token", &refresh)],
)
.await;
if let Some(n) = nonce {
s.nonces.insert(origin, n);
}
let (status, body) = answered.map_err(Unrefreshed::Unreachable)?;
if status >= 500 {
return Err(Unrefreshed::Unreachable(format!("it answered {status}")));
}
let t = match tokens_of(&body) {
Ok(t) if status == 200 && t.sub == s.did => t,
_ => {
let error = safe_name(&body);
tracing::info!(did = s.did, status, error, "refresh refused");
return Err(Unrefreshed::Refused);
}
};
s.access_token = t.access;
if t.refresh.is_some() {
s.refresh_token = t.refresh;
}
s.expires_at = t.expires_at;
s.scope = t.scope;
auth.save(s);
Ok(())
}
/// A session's token for a call, refreshed first if it has expired or
/// is `stale`, the one a PDS just refused: one refresh at a time, as the
/// session's lock is held through it.
async fn snapshot(
&self,
auth: &Auth,
account: &Account,
stale: Option<&str>,
) -> Result<Snapshot, Refusal> {
let mut s = account.session.lock().await;
if s.ended {
return Err(Refusal::SignIn);
}
if s.expires_at <= now() + EARLY || stale == Some(s.access_token.as_str()) {
match self.refresh_locked(auth, &mut s).await {
Ok(()) => {}
Err(Unrefreshed::Refused) => {
auth.end_locked(&mut s);
return Err(Refusal::SignIn);
}
Err(Unrefreshed::Unreachable(why)) => {
return Err(Refusal::Error(format!(
"Your account's server could not renew your sign-in: {why}"
)));
}
}
}
Ok(Snapshot {
token: s.access_token.clone(),
key: s.dpop.clone(),
pds: s.pds.clone(),
nonces: s.nonces.clone(),
sets: crate::scope::includes(&s.asked),
})
}
/// Call the XRPC method `nsid` at the account's PDS, as the account:
/// a POST of `input` if given, else a GET, with `atproto-proxy` naming
/// `proxy` if given. Its answer, whatever its status, as `pds_send`'s.
pub(crate) async fn pds_call(
&self,
account: &Account,
nsid: &str,
query: &[(String, String)],
input: Option<&Value>,
proxy: Option<&str>,
) -> Result<Fetched, Refusal> {
let body = input.map(|i| ("application/json", Bytes::from(i.to_string())));
self.pds_send(account, nsid, query, body, proxy, WAIT).await
}
/// `pds_call` of a write as the account, a POST of `input`. Once it
/// has landed, each app whose records it wrote has its server read
/// them back (`Hud::refresh_written`); then, landed or not, the answers
/// kept for the account are forgotten (`Hud::wrote`), so what it reads
/// next shows what it wrote.
pub(crate) async fn pds_write(
&self,
account: &Account,
nsid: &str,
input: &Value,
proxy: Option<&str>,
) -> Result<Fetched, Refusal> {
let got = self.pds_call(account, nsid, &[], Some(input), proxy).await;
if let Ok(done) = &got
&& done.status == 200
{
let written = crate::writes::written_uris(nsid, input, &done.body);
self.refresh_written(account, &written).await;
}
self.wrote(&account.did);
got
}
/// Call the XRPC method `nsid` at the account's PDS, as the account:
/// a POST of `body` (its content type and bytes) if given, else a GET,
/// with `atproto-proxy` naming `proxy` if given, each try within
/// `wait`. Sent again once for a new DPoP nonce, and once with the
/// token refreshed if the PDS refuses it, or refuses a sign-in that
/// asked for a permission set for want of scope: its server resolves
/// the set again as it refreshes, and it may have grown. Its answer,
/// whatever its status.
pub(crate) async fn pds_send(
&self,
account: &Account,
nsid: &str,
query: &[(String, String)],
body: Option<(&str, Bytes)>,
proxy: Option<&str>,
wait: Duration,
) -> Result<Fetched, Refusal> {
let auth = self.auth()?;
let mut snap = self.snapshot(auth, account, None).await?;
let mut url = Url::parse(&format!("{}/xrpc/{nsid}", snap.pds))
.map_err(|_| Refusal::Error(format!("{} is not a usable PDS", snap.pds)))?;
if !query.is_empty() {
url.query_pairs_mut().extend_pairs(query);
}
let origin = url.origin().ascii_serialization();
let host = url.host_str().unwrap_or_default().to_string();
let (mut nonce_retried, mut refreshed) = (false, false);
loop {
let nonce = snap.nonces.get(&origin).cloned();
let method = if body.is_some() { "POST" } else { "GET" };
let proof = dpop_proof(
&snap.key,
method,
&url,
nonce.as_deref(),
Some(&jose::sha256(&snap.token)),
);
let req = match &body {
Some((kind, bytes)) => self
.net
.post(&url)?
.header(reqwest::header::CONTENT_TYPE, *kind)
.body(bytes.clone()),
None => self.net.get(&url)?,
};
let mut req = req
.header(reqwest::header::ACCEPT, "application/json")
.header(
reqwest::header::AUTHORIZATION,
format!("DPoP {}", snap.token),
)
.header("DPoP", proof);
if let Some(p) = proxy {
req = req.header("atproto-proxy", p);
}
let got = self
.net
.send(req, wait, ANSWER_MAX)
.await
.map_err(|why| Refusal::Error(format!("Could not reach {host}: {why}")))?;
let fresh = got.header("dpop-nonce").map(str::to_string);
let changed = fresh.is_some() && fresh != nonce;
if let Some(n) = fresh.filter(|_| changed) {
snap.nonces.insert(origin.clone(), n.clone());
account
.session
.lock()
.await
.nonces
.insert(origin.clone(), n);
}
if got.status == 401 {
match oauth_error(&got).as_deref() {
Some("use_dpop_nonce") if changed && !nonce_retried => {
nonce_retried = true;
continue;
}
Some("invalid_token" | "InvalidToken" | "ExpiredToken") if !refreshed => {
refreshed = true;
let used = snap.token.clone();
snap = self.snapshot(auth, account, Some(&used)).await?;
continue;
}
_ => {}
}
}
let unscoped = got.status == 403
&& crate::pds::error_name(&got.body).as_deref() == Some("ScopeMissingError");
if unscoped && !refreshed && snap.sets {
refreshed = true;
let used = snap.token.clone();
snap = self.snapshot(auth, account, Some(&used)).await?;
continue;
}
return Ok(got);
}
}
/// Revoke a session's atproto refresh token at its server, if that has
/// a revocation endpoint: as well as may be, its failure ignored.
pub(crate) async fn revoke_at_server(&self, auth: &Auth, s: &mut Session) {
let (Some(endpoint), Some(token)) =
(s.revocation_endpoint.clone(), s.refresh_token.clone())
else {
return;
};
let origin = origin_of(&endpoint);
let mut nonce = s.nonces.get(&origin).cloned();
let done = self
.as_post(
auth,
&s.issuer,
&endpoint,
&s.dpop,
&mut nonce,
&[("token", &token), ("token_type_hint", "refresh_token")],
)
.await;
if let Err(why) = done {
let did = &s.did;
tracing::info!(did, why, "revocation at the account's server failed");
}
}
}