mcapi 0.2.0

Unified async Rust client for the Minecraft ecosystem (Mojang, Modrinth, CurseForge, Yggdrasil, Blessing Skin, Loaders, Java Runtimes, and SLP)
Documentation
//! Yggdrasil authentication, session, profile, and optional authlib-injector / RSA verification.

#[cfg(feature = "yggdrasil-authlib")]
#[cfg_attr(docsrs, doc(cfg(feature = "yggdrasil-authlib")))]
pub mod authlib_injector;
pub mod models;
#[cfg(feature = "yggdrasil-verify")]
#[cfg_attr(docsrs, doc(cfg(feature = "yggdrasil-verify")))]
pub mod verify;

use reqwest::header::{ACCEPT_CHARSET, HeaderValue};
use reqwest::multipart::{Form, Part};
use serde::Serialize;
use serde::de::DeserializeOwned;
use url::Url;

use self::models::{
    AuthenticateRequest, AuthenticateResponse, GameProfile, MetadataDocument, ProfileLookupEntry,
    RefreshRequest, RefreshResponse, ServerMetadata, SignoutRequest, SkinModel, TextureType,
    TokenPairRequest,
};
use crate::error::{Error, Result};
use crate::http::HttpCore;
use crate::util::define_authed;
use crate::uuid::McUuid;

const ALI_HEADER: &str = "x-authlib-injector-api-location";

#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct HasJoinedQuery<'a> {
    username: &'a str,
    server_id: &'a str,
    ip: Option<&'a str>,
}

#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct JoinServerBody<'a> {
    access_token: &'a str,
    selected_profile: McUuid,
    server_id: &'a str,
}

/// Async client for Yggdrasil authentication, session, and profile endpoints.
#[derive(Clone, Debug)]
pub struct YggdrasilClient {
    api_root: String,
    http: HttpCore,
}

impl YggdrasilClient {
    /// Creates a new [`YggdrasilClient`] pointing at `api_root` with a default [`HttpCore`].
    pub fn new(api_root: impl Into<String>) -> Result<Self> {
        Ok(Self::from_http(HttpCore::new()?, api_root))
    }

    /// Creates a new [`YggdrasilClient`] sharing an existing [`HttpCore`].
    pub fn from_http(http: HttpCore, api_root: impl Into<String>) -> Self {
        Self {
            api_root: normalize_api_root(&api_root.into()),
            http,
        }
    }

    /// Discovers the real Yggdrasil API root using the authlib-injector ALI header
    /// (`X-Authlib-Injector-API-Location`).
    pub async fn discover(entry_url: &str) -> Result<Self> {
        Self::discover_with_http(HttpCore::new()?, entry_url).await
    }

    /// Discovers the real Yggdrasil API root using an existing shared [`HttpCore`].
    pub async fn discover_with_http(http: HttpCore, entry_url: &str) -> Result<Self> {
        let initial = Url::parse(entry_url)?;
        if !matches!(initial.scheme(), "http" | "https") {
            return Err(Error::InvalidAliLocation);
        }

        let mut current = initial;
        for _hop in 0..5 {
            let response = http
                .send_direct(current.as_str(), |client, url| client.get(url))
                .await?;
            let final_url = response.url().clone();

            let Some(raw_loc) = response.headers().get(ALI_HEADER) else {
                return Ok(Self {
                    api_root: normalize_url(&final_url),
                    http,
                });
            };

            let loc = raw_loc
                .to_str()
                .map_err(|_| Error::InvalidAliLocation)?
                .trim();
            if loc.is_empty() {
                return Err(Error::InvalidAliLocation);
            }
            let next = final_url.join(loc).map_err(|_| Error::InvalidAliLocation)?;
            if !matches!(next.scheme(), "http" | "https") {
                return Err(Error::InvalidAliLocation);
            }
            if final_url.scheme() == "https" && next.scheme() == "http" {
                return Err(Error::InvalidAliLocation);
            }

            if normalize_url(&next) == normalize_url(&final_url) {
                return Ok(Self {
                    api_root: normalize_url(&next),
                    http,
                });
            }
            current = next;
        }

        Ok(Self {
            api_root: normalize_url(&current),
            http,
        })
    }

    /// Returns the normalized Yggdrasil API root URL.
    pub fn api_root(&self) -> &str {
        &self.api_root
    }

    /// Returns the underlying shared [`HttpCore`].
    pub fn http(&self) -> &HttpCore {
        &self.http
    }

    /// Returns an authenticated view bound to `access_token`.
    pub fn authed<'a>(&'a self, access_token: &'a str) -> Authed<'a> {
        Authed::new(self, access_token)
    }

    /// Fetches the raw and parsed server metadata document from `GET /`.
    pub async fn metadata_document(&self) -> Result<MetadataDocument> {
        let url = format!("{}/", self.api_root);
        let resp = self
            .http
            .send_with(&url, |client, target| {
                client
                    .get(target)
                    .header(ACCEPT_CHARSET, HeaderValue::from_static("UTF-8"))
            })
            .await?;
        let raw_json = resp.text().await?;
        let metadata: ServerMetadata = serde_json::from_str(&raw_json)?;
        Ok(MetadataDocument { metadata, raw_json })
    }

    /// Fetches parsed server metadata from `GET /`.
    pub async fn metadata(&self) -> Result<ServerMetadata> {
        Ok(self.metadata_document().await?.metadata)
    }

    /// Authenticates an account via `POST /authserver/authenticate`.
    pub async fn authenticate(&self, req: &AuthenticateRequest) -> Result<AuthenticateResponse> {
        self.post_yggdrasil("/authserver/authenticate", req).await
    }

    /// Refreshes an access token via `POST /authserver/refresh`.
    pub async fn refresh(&self, req: &RefreshRequest) -> Result<RefreshResponse> {
        self.post_yggdrasil("/authserver/refresh", req).await
    }

    /// Validates an access token via `POST /authserver/validate`.
    /// Returns `Ok(true)` on `204` and `Ok(false)` on `403`.
    pub async fn validate(&self, req: &TokenPairRequest) -> Result<bool> {
        let url = self.endpoint("/authserver/validate");
        match self
            .http
            .send_direct(&url, |client, target| client.post(target).json(req))
            .await
        {
            Ok(_) => Ok(true),
            Err(Error::ApiStatus { status: 403, .. }) => Ok(false),
            Err(err) => Err(map_yggdrasil_error(err)),
        }
    }

    /// Invalidates an access token via `POST /authserver/invalidate`.
    pub async fn invalidate(&self, req: &TokenPairRequest) -> Result<()> {
        let url = self.endpoint("/authserver/invalidate");
        self.http
            .send_direct(&url, |client, target| client.post(target).json(req))
            .await
            .map_err(map_yggdrasil_error)?;
        Ok(())
    }

    /// Invalidates all access tokens of an account via `POST /authserver/signout`.
    pub async fn signout(&self, req: &SignoutRequest) -> Result<()> {
        let url = self.endpoint("/authserver/signout");
        self.http
            .send_direct(&url, |client, target| client.post(target).json(req))
            .await
            .map_err(map_yggdrasil_error)?;
        Ok(())
    }

    /// Checks whether a player joined a server via `GET /sessionserver/session/minecraft/hasJoined`.
    pub async fn has_joined(
        &self,
        username: &str,
        server_id: &str,
        ip: Option<&str>,
    ) -> Result<Option<GameProfile>> {
        let url = self.endpoint("/sessionserver/session/minecraft/hasJoined");
        let query = HasJoinedQuery {
            username,
            server_id,
            ip,
        };
        self.http
            .send_optional_json(&url, |client, target| client.get(target).query(&query))
            .await
            .map_err(map_yggdrasil_error)
    }

    /// Fetches a player's full profile (with optional signed textures) via
    /// `GET /sessionserver/session/minecraft/profile/{uuid}`.
    pub async fn profile(&self, uuid: McUuid, unsigned: bool) -> Result<Option<GameProfile>> {
        let url = self.endpoint(&format!(
            "/sessionserver/session/minecraft/profile/{}",
            uuid.to_undashed()
        ));
        let query = [("unsigned", if unsigned { "true" } else { "false" })];
        self.http
            .send_optional_json(&url, |client, target| client.get(target).query(&query))
            .await
            .map_err(map_yggdrasil_error)
    }

    /// Looks up UUIDs and canonical names for up to 10 usernames via `POST /api/profiles/minecraft`.
    pub async fn lookup_profiles_by_names(
        &self,
        names: &[&str],
    ) -> Result<Vec<ProfileLookupEntry>> {
        if names.is_empty() || names.len() > 10 {
            return Err(Error::InvalidInput(
                "lookup_profiles_by_names accepts between 1 and 10 usernames".to_string(),
            ));
        }
        self.post_yggdrasil("/api/profiles/minecraft", names).await
    }

    fn endpoint(&self, path: &str) -> String {
        format!("{}{}", self.api_root, path)
    }

    async fn post_yggdrasil<B: Serialize + ?Sized, T: DeserializeOwned>(
        &self,
        path: &str,
        body: &B,
    ) -> Result<T> {
        let url = self.endpoint(path);
        let resp = self
            .http
            .send_direct(&url, |client, target| {
                client
                    .post(target)
                    .header(ACCEPT_CHARSET, HeaderValue::from_static("UTF-8"))
                    .json(body)
            })
            .await
            .map_err(map_yggdrasil_error)?;
        Ok(resp.json::<T>().await?)
    }
}

define_authed!(YggdrasilClient);

impl<'a> Authed<'a> {
    /// Records a server join on the session server via `POST /sessionserver/session/minecraft/join`.
    pub async fn join_server(&self, selected_profile: McUuid, server_id: &str) -> Result<()> {
        let url = self
            .client
            .endpoint("/sessionserver/session/minecraft/join");
        let payload = JoinServerBody {
            access_token: self.token,
            selected_profile,
            server_id,
        };
        self.client
            .http
            .send_direct(&url, |client, target| client.post(target).json(&payload))
            .await
            .map_err(map_yggdrasil_error)?;
        Ok(())
    }

    /// Uploads a PNG skin or cape texture via `PUT /api/user/profile/{uuid}/{textureType}`.
    pub async fn upload_texture(
        &self,
        profile_uuid: McUuid,
        texture_type: TextureType,
        model: SkinModel,
        png_bytes: Vec<u8>,
    ) -> Result<()> {
        let url = self.client.endpoint(&format!(
            "/api/user/profile/{}/{}",
            profile_uuid.to_undashed(),
            texture_type.as_path_segment()
        ));
        let token = self.token;
        let model_val = model.as_form_value();

        self.client
            .http
            .send_direct_oneshot(&url, move |client, target| {
                let file_part = Part::bytes(png_bytes)
                    .file_name("texture.png")
                    .mime_str("image/png")
                    .expect("static mime type is valid");
                let mut form = Form::new().part("file", file_part);
                if texture_type == TextureType::Skin {
                    form = form.text("model", model_val);
                }
                client.put(target).bearer_auth(token).multipart(form)
            })
            .await
            .map_err(map_yggdrasil_error)?;
        Ok(())
    }

    /// Deletes a skin or cape texture via `DELETE /api/user/profile/{uuid}/{textureType}`.
    pub async fn delete_texture(
        &self,
        profile_uuid: McUuid,
        texture_type: TextureType,
    ) -> Result<()> {
        let url = self.client.endpoint(&format!(
            "/api/user/profile/{}/{}",
            profile_uuid.to_undashed(),
            texture_type.as_path_segment()
        ));
        self.client
            .http
            .send_direct(&url, |client, target| {
                client.delete(target).bearer_auth(self.token)
            })
            .await
            .map_err(map_yggdrasil_error)?;
        Ok(())
    }
}

fn normalize_url(url: &Url) -> String {
    let mut clean = url.clone();
    clean.set_query(None);
    clean.set_fragment(None);
    clean.as_str().trim_end_matches('/').to_string()
}

fn normalize_api_root(raw: &str) -> String {
    if let Ok(url) = Url::parse(raw) {
        normalize_url(&url)
    } else {
        raw.split(['?', '#'])
            .next()
            .unwrap_or(raw)
            .trim_end_matches('/')
            .to_string()
    }
}

fn map_yggdrasil_error(err: Error) -> Error {
    if let Error::ApiStatus { ref body, .. } = err
        && let Ok(parsed) = serde_json::from_str::<YggdrasilErrorBody>(body)
    {
        return Error::Yggdrasil {
            error: parsed.error,
            error_message: parsed.error_message,
            cause: parsed.cause,
        };
    }
    err
}

#[derive(serde::Deserialize)]
#[serde(rename_all = "camelCase")]
struct YggdrasilErrorBody {
    error: String,
    error_message: String,
    #[serde(default)]
    cause: Option<String>,
}