mcapi 0.3.1

Unified async Rust client for the Minecraft ecosystem (Mojang, Modrinth, CurseForge, Yggdrasil, Blessing Skin, Loaders, BMCLAPI, and Java Runtimes)
Documentation
//! Mojang / Microsoft authentication chain, public session/UUID lookups,
//! Minecraft Services profile/skin/cape management, Piston Meta manifests,
//! and Minecraft Launcher Content (news & Java patch notes).
//!
//! Reference specs:
//! - Mojang API: <https://minecraft.wiki/w/Mojang_API>
//! - Microsoft Authentication: <https://minecraft.wiki/w/Microsoft_authentication>

mod auth;
mod content;
/// Data models for Microsoft auth, Mojang public lookups, Minecraft Services, Piston Meta, and Launcher Content.
pub mod models;
mod piston;
mod public;
mod services;

use crate::error::Result;
use crate::http::HttpClient;
use crate::util::{define_authed, trim_trailing_slash};

/// Default Microsoft OAuth2 origin.
pub const DEFAULT_MS_OAUTH_URL: &str = "https://login.microsoftonline.com";
/// Default Xbox Live user authentication origin.
pub const DEFAULT_XBL_AUTH_URL: &str = "https://user.auth.xboxlive.com";
/// Default Xbox Live XSTS authorization origin.
pub const DEFAULT_XSTS_AUTH_URL: &str = "https://xsts.auth.xboxlive.com";
/// Default Mojang session server origin.
pub const DEFAULT_SESSIONSERVER_URL: &str = "https://sessionserver.mojang.com";
/// Default Minecraft Services API origin.
pub const DEFAULT_MINECRAFT_SERVICES_URL: &str = "https://api.minecraftservices.com";
/// Default Mojang Piston Meta origin.
pub const DEFAULT_PISTON_META_URL: &str = "https://piston-meta.mojang.com";
/// Default Minecraft Launcher Content origin.
pub const DEFAULT_LAUNCHER_CONTENT_URL: &str = "https://launchercontent.mojang.com";

/// Known Xbox Live XSTS rejection reason codes (`XErr`).
#[non_exhaustive]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum XstsErrorKind {
    /// `2148916227`: Xbox account is banned.
    AccountBanned,
    /// `2148916233`: Microsoft account does not have an Xbox profile yet.
    NoXboxAccount,
    /// `2148916234`: Xbox Live Terms of Service have not been accepted.
    TermsOfServiceNotAccepted,
    /// `2148916235`: Xbox Live is unavailable in the account's country/region.
    CountryNotSupported,
    /// `2148916236` / `2148916237`: Adult verification required (e.g. South Korea).
    AdultVerificationRequired,
    /// `2148916238`: Child account must be added to a Microsoft Family.
    ChildAccountRequiresFamily,
    /// Any other numeric `XErr` code.
    Unknown(u64),
}

impl XstsErrorKind {
    /// Classifies a raw Xbox `XErr` code.
    #[must_use]
    pub const fn from_xerr(code: u64) -> Self {
        match code {
            2148916227 => XstsErrorKind::AccountBanned,
            2148916233 => XstsErrorKind::NoXboxAccount,
            2148916234 => XstsErrorKind::TermsOfServiceNotAccepted,
            2148916235 => XstsErrorKind::CountryNotSupported,
            2148916236 | 2148916237 => XstsErrorKind::AdultVerificationRequired,
            2148916238 => XstsErrorKind::ChildAccountRequiresFamily,
            other => XstsErrorKind::Unknown(other),
        }
    }
}

/// Detailed XSTS authorization failure returned by Xbox Live.
#[non_exhaustive]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct XstsError {
    /// Raw numeric Xbox `XErr` rejection code.
    pub xerr: u64,
    /// Classified rejection reason derived from `xerr`.
    pub kind: XstsErrorKind,
    /// Human-readable error message from Xbox Live.
    pub message: String,
    /// Optional resolution URL returned by Xbox Live (e.g. account verification or age gate).
    pub redirect: Option<String>,
}

impl XstsError {
    /// Creates a new [`XstsError`] payload from an Xbox Live `XErr` rejection.
    #[must_use]
    pub fn new(
        xerr: u64,
        kind: XstsErrorKind,
        message: impl Into<String>,
        redirect: Option<String>,
    ) -> Self {
        Self {
            xerr,
            kind,
            message: message.into(),
            redirect,
        }
    }
}

/// Async client covering Microsoft-to-Minecraft authentication, Mojang public endpoints,
/// Minecraft Services account/skin/cape management, Piston Meta manifests, and Launcher Content.
#[derive(Clone, Debug)]
pub struct MojangClient {
    pub(crate) http: HttpClient,
    base_url: Option<String>,
}

impl MojangClient {
    /// Creates a new [`MojangClient`] with default [`HttpClient`] settings.
    pub fn new() -> Result<Self> {
        Ok(Self::from_http(HttpClient::new()?))
    }

    /// Creates a new [`MojangClient`] sharing an existing [`HttpClient`].
    #[must_use]
    pub const fn from_http(http: HttpClient) -> Self {
        Self {
            http,
            base_url: None,
        }
    }

    /// Routes all Mojang/Microsoft endpoints to a custom base URL (for mock tests or proxies).
    #[must_use]
    pub fn with_base_url(mut self, base_url: impl Into<String>) -> Self {
        self.base_url = Some(trim_trailing_slash(base_url));
        self
    }

    /// Returns an authenticated view bound to a Minecraft Services Bearer access token.
    #[must_use]
    pub fn authed<'a>(&'a self, mc_access_token: &'a str) -> Authed<'a> {
        Authed::new(self, mc_access_token)
    }

    /// Returns a reference to the underlying shared [`HttpClient`].
    #[must_use]
    pub fn http(&self) -> &HttpClient {
        &self.http
    }

    pub(crate) fn url(&self, official_base: &str, path: &str) -> String {
        let base = self.base_url.as_deref().unwrap_or(official_base);
        format!("{base}{path}")
    }
}

define_authed!(MojangClient);