#[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 std::collections::HashSet;
use reqwest::header::{ACCEPT_CHARSET, AUTHORIZATION, HeaderValue};
use reqwest::multipart::{Form, Part};
use serde::Serialize;
use serde::de::DeserializeOwned;
use url::Url;
use self::models::{
AuthenticateRequest, AuthenticateResponse, GameProfile, MetadataDocument, NameUuidEntry,
RefreshRequest, RefreshResponse, ServerMetadata, SignoutRequest, SkinModel, TextureType,
TokenPairRequest,
};
use crate::error::{Error, Result};
use crate::http::{HttpClient, bearer_header};
use crate::profile::JoinServerBody;
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(Clone, Debug)]
pub struct YggdrasilClient {
api_root: String,
http: HttpClient,
}
impl YggdrasilClient {
pub fn new(api_root: impl AsRef<str>) -> Result<Self> {
Self::from_http(HttpClient::new()?, api_root)
}
pub fn from_http(http: HttpClient, api_root: impl AsRef<str>) -> Result<Self> {
let parsed = crate::util::validate_http_url(api_root.as_ref())?;
Ok(Self {
api_root: normalize_url(&parsed),
http,
})
}
pub async fn discover(entry_url: &str) -> Result<Self> {
Self::discover_with_http(HttpClient::new()?, entry_url).await
}
pub async fn discover_with_http(http: HttpClient, 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;
let mut visited = HashSet::new();
for _hop in 0..5 {
visited.insert(normalize_url(¤t));
let response = http
.send_direct_idempotent(current.as_str(), |client, url| client.get(url))
.await?;
let final_url = response.url().clone();
let final_norm = normalize_url(&final_url);
visited.insert(final_norm.clone());
let Some(raw_loc) = response.headers().get(ALI_HEADER) else {
return Ok(Self {
api_root: final_norm,
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);
}
let next_norm = normalize_url(&next);
if next_norm == final_norm {
return Ok(Self {
api_root: next_norm,
http,
});
}
if visited.contains(&next_norm) {
return Err(Error::InvalidAliLocation);
}
current = next;
}
Err(Error::InvalidAliLocation)
}
#[must_use]
pub fn api_root(&self) -> &str {
&self.api_root
}
#[must_use]
pub fn http(&self) -> &HttpClient {
&self.http
}
#[must_use]
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);
self.http
.send_and_map(
&url,
|client, target| {
client
.get(target)
.header(ACCEPT_CHARSET, HeaderValue::from_static("UTF-8"))
},
|resp| async move {
let raw_json = resp.text().await?;
let metadata: ServerMetadata = serde_json::from_str(&raw_json)?;
Ok(MetadataDocument { metadata, raw_json })
},
)
.await
}
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_idempotent(&url, |client, target| client.post(target).json(req))
.await
{
Ok(_) => Ok(true),
Err(Error::ApiStatus(ref err)) if err.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) -> Result<Option<GameProfile>> {
self.profile_inner(uuid, true).await
}
pub async fn signed_profile(&self, uuid: McUuid) -> Result<Option<GameProfile>> {
self.profile_inner(uuid, false).await
}
async fn profile_inner(&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 profiles_by_names(&self, names: &[impl AsRef<str>]) -> Result<Vec<NameUuidEntry>> {
if names.is_empty() || names.len() > 10 {
return Err(Error::InvalidInput(
"profiles_by_names accepts between 1 and 10 usernames".to_string(),
));
}
let name_refs: Vec<&str> = names.iter().map(AsRef::as_ref).collect();
self.post_yggdrasil_inner("/api/profiles/minecraft", &name_refs, true)
.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> {
self.post_yggdrasil_inner(path, body, false).await
}
async fn post_yggdrasil_inner<B: Serialize + ?Sized, T: DeserializeOwned>(
&self,
path: &str,
body: &B,
idempotent: bool,
) -> Result<T> {
let url = self.endpoint(path);
let build = |client: &reqwest::Client, target: &str| {
client
.post(target)
.header(ACCEPT_CHARSET, HeaderValue::from_static("UTF-8"))
.json(body)
};
let resp = if idempotent {
self.http.send_direct_idempotent(&url, build).await
} else {
self.http.send_direct(&url, build).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 auth = bearer_header(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)
.header(AUTHORIZATION, auth)
.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()
));
let auth = bearer_header(self.token)?;
self.client
.http
.send_direct(&url, |client, target| {
client.delete(target).header(AUTHORIZATION, auth.clone())
})
.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 map_yggdrasil_error(err: Error) -> Error {
if let Error::ApiStatus(ref api_err) = err
&& let Ok(parsed) = serde_json::from_str::<YggdrasilErrorBody>(&api_err.body)
{
return Error::yggdrasil(parsed.error, parsed.error_message, parsed.cause);
}
err
}
#[derive(serde::Deserialize)]
#[serde(rename_all = "camelCase")]
struct YggdrasilErrorBody {
error: String,
error_message: String,
#[serde(default)]
cause: Option<String>,
}