#[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,
}
#[derive(Clone, Debug)]
pub struct YggdrasilClient {
api_root: String,
http: HttpCore,
}
impl YggdrasilClient {
pub fn new(api_root: impl Into<String>) -> Result<Self> {
Ok(Self::from_http(HttpCore::new()?, api_root))
}
pub fn from_http(http: HttpCore, api_root: impl Into<String>) -> Self {
Self {
api_root: normalize_api_root(&api_root.into()),
http,
}
}
pub async fn discover(entry_url: &str) -> Result<Self> {
Self::discover_with_http(HttpCore::new()?, entry_url).await
}
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(¤t),
http,
})
}
pub fn api_root(&self) -> &str {
&self.api_root
}
pub fn http(&self) -> &HttpCore {
&self.http
}
pub fn authed<'a>(&'a self, access_token: &'a str) -> Authed<'a> {
Authed::new(self, access_token)
}
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 })
}
pub async fn metadata(&self) -> Result<ServerMetadata> {
Ok(self.metadata_document().await?.metadata)
}
pub async fn authenticate(&self, req: &AuthenticateRequest) -> Result<AuthenticateResponse> {
self.post_yggdrasil("/authserver/authenticate", req).await
}
pub async fn refresh(&self, req: &RefreshRequest) -> Result<RefreshResponse> {
self.post_yggdrasil("/authserver/refresh", req).await
}
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)),
}
}
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(())
}
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(())
}
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)
}
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)
}
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> {
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(())
}
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(())
}
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>,
}