From 60d71bd0174be484af952ebd1c8dc8b535227fcc Mon Sep 17 00:00:00 2001 From: H2Sxxa Date: Sat, 28 Nov 2026 22:24:01 +0800 Subject: [PATCH 1/3] feat(auth)!: add Yggdrasil site metadata store and refactor account providers - Persist normalized Yggdrasil site metadata in accounts/yggdrasil_sites.json with single-flight fetching, TTL refresh, offline fallback, and account-link GC - Integrate SwappableClient into YggdrasilAuthorizer, YggdrasilAccountProvider, MicrosoftAccountProvider, and YggdrasilSiteStore - Separate pure-data Account from TypedAccountProvider and TypedTextureProvider, moving network/texture operations to providers and AccountStore BREAKING CHANGE: Account::credential is now synchronous, network/texture methods moved from Account/SkinStore to TypedAccountProvider/TypedTextureProvider/AccountStore, and AccountRegistry/AccountStore constructors take SwappableClient and provider instances. Closes #302 --- Cargo.lock | 1 + Cargo.toml | 3 +- crates/core/Cargo.toml | 4 +- crates/core/src/auth/accounts/microsoft.rs | 42 +- crates/core/src/auth/accounts/mod.rs | 54 +- crates/core/src/auth/accounts/offline.rs | 13 +- crates/core/src/auth/accounts/yggdrasil.rs | 214 +----- crates/core/src/auth/authorizers/yggdrasil.rs | 52 +- crates/core/src/auth/credential.rs | 4 + crates/core/src/auth/error.rs | 8 + crates/core/src/auth/microsoft_protocol.rs | 44 +- crates/core/src/auth/mod.rs | 1 + crates/core/src/auth/providers/microsoft.rs | 70 ++ crates/core/src/auth/providers/mod.rs | 160 +++++ crates/core/src/auth/providers/offline.rs | 21 + crates/core/src/auth/providers/yggdrasil.rs | 257 +++++++ crates/elemental/Cargo.toml | 1 + crates/elemental/src/lib.rs | 13 +- crates/launcher/Cargo.toml | 1 + crates/launcher/src/account/mod.rs | 6 + crates/launcher/src/account/registry.rs | 109 ++- crates/launcher/src/account/sites.rs | 350 ++++++++++ crates/launcher/src/account/store.rs | 302 +++++++- crates/launcher/src/lib.rs | 6 +- crates/launcher/src/skin.rs | 54 +- crates/launcher/tests/account_store.rs | 5 +- crates/launcher/tests/common/addon.rs | 2 +- crates/launcher/tests/offline_yggdrasil.rs | 11 +- .../launcher/tests/yggdrasil_site_metadata.rs | 646 ++++++++++++++++++ crates/launchpad/src/commands.rs | 2 +- 30 files changed, 1999 insertions(+), 457 deletions(-) create mode 100644 crates/core/src/auth/providers/microsoft.rs create mode 100644 crates/core/src/auth/providers/mod.rs create mode 100644 crates/core/src/auth/providers/offline.rs create mode 100644 crates/core/src/auth/providers/yggdrasil.rs create mode 100644 crates/launcher/src/account/sites.rs create mode 100644 crates/launcher/tests/yggdrasil_site_metadata.rs diff --git a/Cargo.lock b/Cargo.lock index f219af15..7753970e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -700,6 +700,7 @@ dependencies = [ "sha2 0.11.2", "thiserror 2.0.21", "tokio", + "tracing", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 327ccf10..80db5710 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -29,7 +29,7 @@ erased-serde = "0.4.11" futures = "0.3.34" hex = "0.4.3" jiff = { version = "1.0.0", features = ["serde"] } -nidhogg = { version = "0.3.1", default-features = false } +nidhogg = { version = "0.3.2", default-features = false } reqwest = { version = "0.13.1", default-features = false, features = [ "stream", "http2", @@ -53,6 +53,7 @@ tokio = { version = "1.54.1", features = [ "time", ] } toml = "1.0.0" +tracing = "0.1.44" uuid = "1.19.0" # https://github.com/microsoft/edit/blob/main/Cargo.toml diff --git a/crates/core/Cargo.toml b/crates/core/Cargo.toml index f531306c..501ff262 100644 --- a/crates/core/Cargo.toml +++ b/crates/core/Cargo.toml @@ -25,7 +25,7 @@ tls-aws-lc = ["reqwest?/rustls", "nidhogg?/tls-aws-lc"] tls-rustls-no-provider = ["reqwest?/rustls-no-provider", "nidhogg?/tls-rustls-no-provider"] tls-native = ["reqwest?/native-tls", "nidhogg?/tls-native"] tls-native-vendored = ["reqwest?/native-tls-vendored", "nidhogg?/tls-native-vendored"] -yggdrasil-auth = ["dep:nidhogg"] +yggdrasil-auth = ["dep:nidhogg", "http"] offline-server = ["yggdrasil-auth", "nidhogg/server"] [dependencies] @@ -44,7 +44,7 @@ serde = { workspace = true } serde_json = { workspace = true, optional = true } thiserror = { workspace = true } tokio = { workspace = true } -tracing = "0.1.44" +tracing = { workspace = true } uuid = { workspace = true, features = ["serde", "v4", "v5"] } [target.'cfg(windows)'.dependencies] diff --git a/crates/core/src/auth/accounts/microsoft.rs b/crates/core/src/auth/accounts/microsoft.rs index cebec668..10e33b9e 100644 --- a/crates/core/src/auth/accounts/microsoft.rs +++ b/crates/core/src/auth/accounts/microsoft.rs @@ -1,14 +1,8 @@ -use async_trait::async_trait; use serde::{Deserialize, Serialize}; use crate::auth::accounts::{Account, AccountId}; use crate::auth::credential::{Credential, CredentialKind}; -use crate::auth::error::Result; -use crate::auth::microsoft_protocol::{ - ExchangedMinecraftSession, delete_skin, minecraft_profile, profile_textures, - refresh_microsoft_session, select_cape, unix_now, upload_skin, -}; -use crate::auth::texture::{ProfileTextures, SkinModel}; +use crate::auth::microsoft_protocol::{ExchangedMinecraftSession, unix_now}; const REFRESH_SKEW_SECONDS: u64 = 300; @@ -41,7 +35,6 @@ impl MicrosoftAccount { } } -#[async_trait] impl Account for MicrosoftAccount { fn account_id(&self) -> AccountId { self.account_id @@ -59,8 +52,8 @@ impl Account for MicrosoftAccount { unix_now().saturating_add(REFRESH_SKEW_SECONDS) >= self.expires_at } - async fn credential(&self) -> Result { - Ok(Credential { + fn credential(&self) -> Credential { + Credential { username: self.username.clone(), uuid: self.uuid.clone(), access_token: self.access_token.clone(), @@ -69,33 +62,6 @@ impl Account for MicrosoftAccount { client_id: Some(self.client_id.clone()), #[cfg(feature = "yggdrasil-auth")] auth_server: None, - }) - } - - async fn refresh(&self) -> Result> { - let session = - refresh_microsoft_session(&self.client_id, &self.refresh_token, self.xuid.clone()) - .await?; - Ok(Box::new(Self::from_session(&self.client_id, session))) - } - - async fn textures(&self) -> Result { - profile_textures(minecraft_profile(&self.access_token).await?) - } - - async fn upload_skin(&self, image: Vec, model: SkinModel) -> Result<()> { - upload_skin(&self.access_token, image, model).await - } - - async fn delete_skin(&self) -> Result<()> { - delete_skin(&self.access_token).await - } - - async fn delete_cape(&self) -> Result<()> { - select_cape(&self.access_token, None).await - } - - async fn select_cape(&self, cape_id: Option) -> Result<()> { - select_cape(&self.access_token, cape_id).await + } } } diff --git a/crates/core/src/auth/accounts/mod.rs b/crates/core/src/auth/accounts/mod.rs index 1e758fcd..c395d7e8 100644 --- a/crates/core/src/auth/accounts/mod.rs +++ b/crates/core/src/auth/accounts/mod.rs @@ -4,25 +4,18 @@ pub mod offline; #[cfg(feature = "yggdrasil-auth")] pub mod yggdrasil; -use async_trait::async_trait; +use std::any::Any; + use serde::{Deserialize, Serialize}; use uuid::Uuid; -#[cfg(feature = "yggdrasil-auth")] -use crate::auth::accounts::yggdrasil::Meta; use crate::auth::credential::Credential; -use crate::auth::error::Result; -use crate::auth::texture::{ProfileTextures, SkinModel}; - -fn unsupported(operation: &'static str) -> Result { - Err(crate::auth::error::Error::TextureUnsupported { operation }) -} /// Stable identity of a persisted account. /// /// This is independent from the Minecraft profile UUID because Yggdrasil /// profiles from different API roots may share the same profile ID. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] #[serde(transparent)] pub struct AccountId(Uuid); @@ -57,8 +50,7 @@ impl std::fmt::Display for AccountId { } /// Persisted authentication state owned by one [`crate::auth::authorizers::Authorizer`]. -#[async_trait] -pub trait Account: Send + Sync + erased_serde::Serialize { +pub trait Account: Send + Sync + erased_serde::Serialize + Any { fn account_id(&self) -> AccountId; fn authorizer_id(&self) -> &'static str; @@ -69,41 +61,5 @@ pub trait Account: Send + Sync + erased_serde::Serialize { false } - async fn credential(&self) -> Result; - - async fn refresh(&self) -> Result>; - - /// Returns the authentication service metadata when the provider exposes it. - /// - /// `None` means metadata is unavailable for this account type or, for an - /// offline Yggdrasil account, that there is no remote API root. - #[cfg(feature = "yggdrasil-auth")] - async fn metadata(&self) -> Result> { - Ok(None) - } - - async fn textures(&self) -> Result { - unsupported("read textures") - } - - async fn upload_skin(&self, _image: Vec, _model: SkinModel) -> Result<()> { - unsupported("upload skin") - } - - async fn delete_skin(&self) -> Result<()> { - unsupported("delete skin") - } - - async fn upload_cape(&self, _image: Vec) -> Result<()> { - unsupported("upload cape") - } - - async fn delete_cape(&self) -> Result<()> { - unsupported("delete cape") - } - - /// Selects an owned cape, or clears the active cape when `cape_id` is `None`. - async fn select_cape(&self, _cape_id: Option) -> Result<()> { - unsupported("select cape") - } + fn credential(&self) -> Credential; } diff --git a/crates/core/src/auth/accounts/offline.rs b/crates/core/src/auth/accounts/offline.rs index 399e043b..1d6d81ad 100644 --- a/crates/core/src/auth/accounts/offline.rs +++ b/crates/core/src/auth/accounts/offline.rs @@ -1,10 +1,8 @@ -use async_trait::async_trait; use serde::{Deserialize, Serialize}; use uuid::Uuid; use crate::auth::accounts::{Account, AccountId}; use crate::auth::credential::{Credential, CredentialKind}; -use crate::auth::error::Result; pub const OFFLINE_AUTHORIZER_ID: &str = "offline"; @@ -26,7 +24,6 @@ impl OfflineAccount { } } -#[async_trait] impl Account for OfflineAccount { fn account_id(&self) -> AccountId { self.account_id @@ -40,8 +37,8 @@ impl Account for OfflineAccount { &self.username } - async fn credential(&self) -> Result { - Ok(Credential { + fn credential(&self) -> Credential { + Credential { username: self.username.clone(), uuid: self.uuid.clone(), access_token: String::new(), @@ -50,11 +47,7 @@ impl Account for OfflineAccount { client_id: None, #[cfg(feature = "yggdrasil-auth")] auth_server: None, - }) - } - - async fn refresh(&self) -> Result> { - Ok(Box::new(self.clone())) + } } } diff --git a/crates/core/src/auth/accounts/yggdrasil.rs b/crates/core/src/auth/accounts/yggdrasil.rs index 6a44b2a8..ddb36b2a 100644 --- a/crates/core/src/auth/accounts/yggdrasil.rs +++ b/crates/core/src/auth/accounts/yggdrasil.rs @@ -1,25 +1,11 @@ -use async_trait::async_trait; -use nidhogg::{ - client::Nidhogg, - request::{refresh::Refresh, texture::TextureType as NidhoggTextureType}, - types::{ - profile::{Profile, ProfilePropertyError}, - textures::{ModelType, Texture}, - user::User, - }, -}; - -pub use nidhogg::types::meta::Meta; +pub use nidhogg::types::meta::{Links, Meta, ServerMeta}; +use nidhogg::types::{profile::Profile, user::User}; use serde::{Deserialize, Serialize}; use uuid::Uuid; use crate::auth::accounts::offline::offline_uuid; use crate::auth::accounts::{Account, AccountId}; use crate::auth::credential::{Credential, CredentialKind}; -use crate::auth::error::{Error, Result}; -use crate::auth::texture::{ - Cape, ProfileTextures, Skin, SkinModel, TextureType as AccountTextureType, -}; pub const YGGDRASIL_AUTHORIZER_ID: &str = "yggdrasil"; @@ -76,92 +62,6 @@ impl YggdrasilAccount { }, } } - - fn client(&self) -> Result { - let base_url = self - .base_url - .as_deref() - .ok_or(Error::YggdrasilBaseUrlMissing)?; - Nidhogg::new(base_url.trim_end_matches('/')).map_err(|source| Error::Yggdrasil { source }) - } - - async fn upload( - &self, - texture_type: NidhoggTextureType, - image: Vec, - file_name: &str, - model: Option, - ) -> Result<()> { - self.client()? - .upload_texture( - self.selected_profile.id.clone(), - self.access_token.clone(), - texture_type, - image, - file_name.to_owned(), - model, - ) - .await - .map_err(|source| Error::Yggdrasil { source }) - } - - async fn delete(&self, texture_type: NidhoggTextureType) -> Result<()> { - self.client()? - .delete_texture( - self.selected_profile.id.clone(), - self.access_token.clone(), - texture_type, - ) - .await - .map_err(|source| Error::Yggdrasil { source }) - } - - /// Fetches the metadata document exposed by the account's Yggdrasil API. - /// - /// Returns `None` for offline accounts because they have no remote API - /// root. - pub async fn metadata(&self) -> Result> { - if self.base_url.is_none() { - return Ok(None); - } - self.client()? - .metadata() - .await - .map_err(|source| Error::Yggdrasil { source }) - .map(Some) - } - - pub async fn refresh_account(&self) -> Result { - let response = self - .client()? - .refresh(&Refresh::new( - self.access_token.clone(), - Some(self.client_token.clone()), - true, - Some(Profile { - id: self.selected_profile.id.clone(), - name: self.selected_profile.name.clone(), - properties: None, - }), - )) - .await - .map_err(|source| Error::Yggdrasil { source })?; - - Ok(Self { - account_id: self.account_id, - base_url: self.base_url.clone(), - user_id: user_id(response.user.as_ref()).or_else(|| self.user_id.clone()), - preferred_language: preferred_language(response.user.as_ref()) - .or_else(|| self.preferred_language.clone()), - access_token: response.access_token, - client_token: response.client_token, - selected_profile: response - .selected_profile - .as_ref() - .map(YggdrasilProfile::from) - .unwrap_or_else(|| self.selected_profile.clone()), - }) - } } pub(crate) fn user_id(user: Option<&User>) -> Option { @@ -172,7 +72,6 @@ pub(crate) fn preferred_language(user: Option<&User>) -> Option { user.and_then(User::get_preferred_language).cloned() } -#[async_trait] impl Account for YggdrasilAccount { fn account_id(&self) -> AccountId { self.account_id @@ -186,12 +85,12 @@ impl Account for YggdrasilAccount { &self.selected_profile.name } - async fn credential(&self) -> Result { + fn credential(&self) -> Credential { let (kind, auth_server) = match &self.base_url { Some(base_url) => (CredentialKind::Mojang, Some(base_url.clone())), None => (CredentialKind::Legacy, None), }; - Ok(Credential { + Credential { username: self.selected_profile.name.clone(), uuid: self.selected_profile.id.clone(), access_token: self.access_token.clone(), @@ -199,111 +98,6 @@ impl Account for YggdrasilAccount { xuid: None, client_id: None, auth_server, - }) - } - - async fn refresh(&self) -> Result> { - if self.base_url.is_none() { - return Ok(Box::new(self.clone())); } - Ok(Box::new(self.refresh_account().await?)) - } - - async fn metadata(&self) -> Result> { - YggdrasilAccount::metadata(self).await - } - - async fn textures(&self) -> Result { - let profile = self - .client()? - .get_profile(self.selected_profile.id.clone(), false) - .await - .map_err(|source| Error::Yggdrasil { source })?; - profile_textures(&profile) - } - - async fn upload_skin(&self, image: Vec, model: SkinModel) -> Result<()> { - let model = match model { - SkinModel::Classic => None, - SkinModel::Slim => Some(ModelType::SLIM), - }; - self.upload(NidhoggTextureType::SKIN, image, "skin.png", model) - .await - } - - async fn delete_skin(&self) -> Result<()> { - self.delete(NidhoggTextureType::SKIN).await - } - - async fn upload_cape(&self, image: Vec) -> Result<()> { - self.upload(NidhoggTextureType::CAPE, image, "cape.png", None) - .await - } - - async fn delete_cape(&self) -> Result<()> { - self.delete(NidhoggTextureType::CAPE).await - } -} - -fn profile_textures(profile: &Profile) -> Result { - let textures = optional_property(profile.get_textures())?; - let skin = textures - .as_ref() - .and_then(|textures| textures.textures.skin.as_ref()) - .map(skin_from) - .transpose()?; - let capes = textures - .and_then(|textures| textures.textures.cape) - .map(cape_from) - .into_iter() - .collect(); - let uploadable = optional_property(profile.get_uploadable_textures())? - .unwrap_or_default() - .into_iter() - .filter_map(uploadable_texture) - .collect(); - - Ok(ProfileTextures { - skin, - capes, - uploadable, - }) -} - -fn optional_property(result: std::result::Result) -> Result> { - match result { - Ok(value) => Ok(Some(value)), - Err(ProfilePropertyError::NoPropertyFound(_)) => Ok(None), - Err(source) => Err(Error::YggdrasilTexture { source }), - } -} - -fn skin_from(texture: &Texture) -> Result { - let model = match texture.metadata.as_ref().map(|metadata| &metadata.model) { - Some(ModelType::SLIM) => SkinModel::Slim, - Some(ModelType::DEFAULT) | None => SkinModel::Classic, - }; - Ok(Skin { - url: texture.url.clone(), - model, - }) -} - -fn cape_from(texture: Texture) -> Cape { - Cape { - id: None, - alias: None, - url: texture.url, - active: true, - } -} - -fn uploadable_texture(value: String) -> Option { - if value.eq_ignore_ascii_case("skin") { - Some(AccountTextureType::Skin) - } else if value.eq_ignore_ascii_case("cape") { - Some(AccountTextureType::Cape) - } else { - None } } diff --git a/crates/core/src/auth/authorizers/yggdrasil.rs b/crates/core/src/auth/authorizers/yggdrasil.rs index f933addf..ded7285e 100644 --- a/crates/core/src/auth/authorizers/yggdrasil.rs +++ b/crates/core/src/auth/authorizers/yggdrasil.rs @@ -5,6 +5,8 @@ use crate::auth::accounts::yggdrasil::{ }; use crate::auth::authorizers::Authorizer; use crate::auth::error::{Error, Result}; +use crate::auth::providers::yggdrasil::nidhogg_client; +use crate::http::SwappableClient; use nidhogg::{client::Nidhogg, request::authenticate::Authenticate}; pub struct YggdrasilAuthorizer { @@ -12,19 +14,51 @@ pub struct YggdrasilAuthorizer { pub username: String, pub password: String, pub client_token: Option, + http_client: Option, } impl YggdrasilAuthorizer { + pub fn new( + base_url: impl Into, + username: impl Into, + password: impl Into, + ) -> Self { + Self { + base_url: Some(base_url.into()), + username: username.into(), + password: password.into(), + client_token: None, + http_client: None, + } + } + + pub fn offline(username: impl Into) -> Self { + Self { + base_url: None, + username: username.into(), + password: String::new(), + client_token: None, + http_client: None, + } + } + + pub fn with_client_token(mut self, client_token: impl Into) -> Self { + self.client_token = Some(client_token.into()); + self + } + + /// Configures the [`SwappableClient`] used for Yggdrasil authentication requests. + pub fn with_http_client(mut self, http_client: SwappableClient) -> Self { + self.http_client = Some(http_client); + self + } + fn client(&self) -> Result { let base_url = self .base_url .as_deref() .ok_or(Error::YggdrasilBaseUrlMissing)?; - Self::client_for(base_url) - } - - fn client_for(base_url: &str) -> Result { - Nidhogg::new(base_url.trim_end_matches('/')).map_err(|source| Error::Yggdrasil { source }) + nidhogg_client(base_url, self.http_client.as_ref()) } pub async fn authenticate(&self) -> Result { @@ -63,14 +97,6 @@ impl YggdrasilAuthorizer { selected_profile: YggdrasilProfile::from(selected_profile), }) } - - pub async fn refresh_account(account: &YggdrasilAccount) -> Result { - account.refresh_account().await - } - - pub async fn refresh(&self, account: &YggdrasilAccount) -> Result { - Self::refresh_account(account).await - } } fn normalized_base_url(base_url: &str) -> &str { diff --git a/crates/core/src/auth/credential.rs b/crates/core/src/auth/credential.rs index 40f3ae47..60a70a4a 100644 --- a/crates/core/src/auth/credential.rs +++ b/crates/core/src/auth/credential.rs @@ -13,6 +13,10 @@ pub struct Credential { pub xuid: Option, pub client_id: Option, /// Yggdrasil API root for authlib-injector. + /// + /// Kept as an explicit field for now since authlib-injector is the only + /// external auth protocol supported; can be generalized into a typed auth + /// protocol extension if additional external protocols are added later. #[cfg(feature = "yggdrasil-auth")] pub auth_server: Option, } diff --git a/crates/core/src/auth/error.rs b/crates/core/src/auth/error.rs index 2078c2fa..b29e1169 100644 --- a/crates/core/src/auth/error.rs +++ b/crates/core/src/auth/error.rs @@ -108,6 +108,14 @@ pub enum Error { #[error("texture operation '{operation}' is not supported for this account")] TextureUnsupported { operation: &'static str }, + #[error( + "account type does not match provider '{expected_authorizer}' (found '{actual_authorizer}')" + )] + AccountTypeMismatch { + expected_authorizer: &'static str, + actual_authorizer: String, + }, + #[cfg(feature = "microsoft-auth")] #[error("send texture request for '{operation}' failed")] TextureRequest { diff --git a/crates/core/src/auth/microsoft_protocol.rs b/crates/core/src/auth/microsoft_protocol.rs index eb02e69f..c881d13d 100644 --- a/crates/core/src/auth/microsoft_protocol.rs +++ b/crates/core/src/auth/microsoft_protocol.rs @@ -12,7 +12,7 @@ use serde::Deserialize; use crate::auth::error::{Error, Result, XuidDecodeError}; use crate::auth::texture::{Cape, ProfileTextures, Skin, SkinModel, TextureType}; -use crate::http::{HttpClientConfig, HttpClientError}; +use crate::http::{HttpClientError, SwappableClient}; const MSA_TOKEN_URL: &str = "https://login.microsoftonline.com/common/oauth2/v2.0/token"; const MINECRAFT_PROFILE_URL: &str = "https://api.minecraftservices.com/minecraft/profile"; @@ -64,19 +64,6 @@ pub(crate) fn map_http_client_error(error: HttpClientError) -> Error { } } -fn default_api_client() -> Result { - HttpClientConfig::default() - .build() - .map_err(map_http_client_error) -} - -fn default_oauth_client() -> Result { - let reqwest_client = HttpClientConfig::default() - .build_no_redirect() - .map_err(map_http_client_error)?; - Ok(ReqwestClient::from(reqwest_client)) -} - pub(crate) fn token_url() -> Result { TokenUrl::new(MSA_TOKEN_URL.to_owned()).map_err(|source| Error::Endpoint { endpoint: "token", @@ -85,11 +72,12 @@ pub(crate) fn token_url() -> Result { } pub(crate) async fn refresh_microsoft_session( + http_client: &SwappableClient, client_id: &str, existing_refresh_token: &str, existing_xuid: Option, ) -> Result { - let reqwest_client = default_oauth_client()?; + let reqwest_client = ReqwestClient::from(http_client.no_redirect_client()); let client = refresh_client(client_id)?; let token = client .exchange_refresh_token(&RefreshToken::new(existing_refresh_token.to_owned())) @@ -102,7 +90,7 @@ pub(crate) async fn refresh_microsoft_session( .unwrap_or_else(|| existing_refresh_token.to_owned()); exchange_microsoft_token( - default_api_client()?, + http_client.client(), token.access_token().secret(), refresh_token, existing_xuid, @@ -147,8 +135,11 @@ pub(crate) async fn exchange_microsoft_token( }) } -pub(crate) async fn minecraft_profile(access_token: &str) -> Result { - let client = default_api_client()?; +pub(crate) async fn minecraft_profile( + http_client: &SwappableClient, + access_token: &str, +) -> Result { + let client = http_client.client(); minecraft_profile_with_client(&client, access_token).await } @@ -170,6 +161,7 @@ async fn minecraft_profile_with_client( } pub(crate) async fn upload_skin( + http_client: &SwappableClient, access_token: &str, image: Vec, model: SkinModel, @@ -187,7 +179,8 @@ pub(crate) async fn upload_skin( })?; let form = Form::new().text("variant", variant).part("file", file); send_texture_request( - default_api_client()? + http_client + .client() .post(MINECRAFT_SKIN_UPLOAD_URL) .bearer_auth(access_token) .multipart(form), @@ -196,9 +189,10 @@ pub(crate) async fn upload_skin( .await } -pub(crate) async fn delete_skin(access_token: &str) -> Result<()> { +pub(crate) async fn delete_skin(http_client: &SwappableClient, access_token: &str) -> Result<()> { send_texture_request( - default_api_client()? + http_client + .client() .delete(MINECRAFT_ACTIVE_SKIN_URL) .bearer_auth(access_token), "delete skin", @@ -206,8 +200,12 @@ pub(crate) async fn delete_skin(access_token: &str) -> Result<()> { .await } -pub(crate) async fn select_cape(access_token: &str, cape_id: Option) -> Result<()> { - let client = default_api_client()?; +pub(crate) async fn select_cape( + http_client: &SwappableClient, + access_token: &str, + cape_id: Option, +) -> Result<()> { + let client = http_client.client(); let request = match cape_id { Some(cape_id) => client .put(MINECRAFT_ACTIVE_CAPE_URL) diff --git a/crates/core/src/auth/mod.rs b/crates/core/src/auth/mod.rs index ca5127cd..c6cb1471 100644 --- a/crates/core/src/auth/mod.rs +++ b/crates/core/src/auth/mod.rs @@ -4,6 +4,7 @@ pub mod credential; pub mod error; #[cfg(feature = "microsoft-auth")] mod microsoft_protocol; +pub mod providers; pub mod texture; pub use error::{Error, Result}; diff --git a/crates/core/src/auth/providers/microsoft.rs b/crates/core/src/auth/providers/microsoft.rs new file mode 100644 index 00000000..d89e9092 --- /dev/null +++ b/crates/core/src/auth/providers/microsoft.rs @@ -0,0 +1,70 @@ +use async_trait::async_trait; + +use crate::auth::accounts::microsoft::{MICROSOFT_AUTHORIZER_ID, MicrosoftAccount}; +use crate::auth::error::Result; +use crate::auth::microsoft_protocol::{ + delete_skin, minecraft_profile, profile_textures, refresh_microsoft_session, select_cape, + upload_skin, +}; +use crate::auth::providers::{TypedAccountProvider, TypedTextureProvider}; +use crate::auth::texture::{ProfileTextures, SkinModel}; +use crate::http::SwappableClient; + +#[derive(Debug, Clone, Default)] +pub struct MicrosoftAccountProvider { + http_client: SwappableClient, +} + +impl MicrosoftAccountProvider { + pub fn new(http_client: SwappableClient) -> Self { + Self { http_client } + } +} + +#[async_trait] +impl TypedAccountProvider for MicrosoftAccountProvider { + type Account = MicrosoftAccount; + + fn authorizer_id(&self) -> &'static str { + MICROSOFT_AUTHORIZER_ID + } + + async fn refresh(&self, account: &Self::Account) -> Result { + let session = refresh_microsoft_session( + &self.http_client, + &account.client_id, + &account.refresh_token, + account.xuid.clone(), + ) + .await?; + Ok(MicrosoftAccount::from_session(&account.client_id, session)) + } +} + +#[async_trait] +impl TypedTextureProvider for MicrosoftAccountProvider { + async fn textures(&self, account: &Self::Account) -> Result { + profile_textures(minecraft_profile(&self.http_client, &account.access_token).await?) + } + + async fn upload_skin( + &self, + account: &Self::Account, + image: Vec, + model: SkinModel, + ) -> Result<()> { + upload_skin(&self.http_client, &account.access_token, image, model).await + } + + async fn delete_skin(&self, account: &Self::Account) -> Result<()> { + delete_skin(&self.http_client, &account.access_token).await + } + + async fn delete_cape(&self, account: &Self::Account) -> Result<()> { + select_cape(&self.http_client, &account.access_token, None).await + } + + async fn select_cape(&self, account: &Self::Account, cape_id: Option) -> Result<()> { + select_cape(&self.http_client, &account.access_token, cape_id).await + } +} diff --git a/crates/core/src/auth/providers/mod.rs b/crates/core/src/auth/providers/mod.rs new file mode 100644 index 00000000..19a0385f --- /dev/null +++ b/crates/core/src/auth/providers/mod.rs @@ -0,0 +1,160 @@ +#[cfg(feature = "microsoft-auth")] +pub mod microsoft; +pub mod offline; +#[cfg(feature = "yggdrasil-auth")] +pub mod yggdrasil; + +use std::any::Any; + +use async_trait::async_trait; +use serde::de::DeserializeOwned; + +use crate::auth::accounts::Account; +use crate::auth::error::{Error, Result}; +use crate::auth::texture::{ProfileTextures, SkinModel}; + +fn unsupported(operation: &'static str) -> Result { + Err(Error::TextureUnsupported { operation }) +} + +#[async_trait] +pub trait TypedAccountProvider: Send + Sync { + type Account: Account + DeserializeOwned + 'static; + + fn authorizer_id(&self) -> &'static str; + + async fn refresh(&self, account: &Self::Account) -> Result; +} + +#[async_trait] +pub trait TypedTextureProvider: TypedAccountProvider { + async fn textures(&self, account: &Self::Account) -> Result; + + async fn upload_skin( + &self, + _account: &Self::Account, + _image: Vec, + _model: SkinModel, + ) -> Result<()> { + unsupported("upload skin") + } + + async fn delete_skin(&self, _account: &Self::Account) -> Result<()> { + unsupported("delete skin") + } + + async fn upload_cape(&self, _account: &Self::Account, _image: Vec) -> Result<()> { + unsupported("upload cape") + } + + async fn delete_cape(&self, _account: &Self::Account) -> Result<()> { + unsupported("delete cape") + } + + async fn select_cape(&self, _account: &Self::Account, _cape_id: Option) -> Result<()> { + unsupported("select cape") + } +} + +#[async_trait] +pub trait AccountProvider: Send + Sync { + fn authorizer_id(&self) -> &'static str; + + fn decode(&self, data: &str) -> std::result::Result, serde_json::Error>; + + async fn refresh(&self, account: &dyn Account) -> Result>; +} + +#[async_trait] +pub trait TextureProvider: AccountProvider { + async fn textures(&self, account: &dyn Account) -> Result; + + async fn upload_skin( + &self, + account: &dyn Account, + image: Vec, + model: SkinModel, + ) -> Result<()>; + + async fn delete_skin(&self, account: &dyn Account) -> Result<()>; + + async fn upload_cape(&self, account: &dyn Account, image: Vec) -> Result<()>; + + async fn delete_cape(&self, account: &dyn Account) -> Result<()>; + + async fn select_cape(&self, account: &dyn Account, cape_id: Option) -> Result<()>; +} + +fn downcast_account<'a, P>(provider: &P, account: &'a dyn Account) -> Result<&'a P::Account> +where + P: TypedAccountProvider + ?Sized, +{ + (account as &dyn Any) + .downcast_ref::() + .ok_or_else(|| Error::AccountTypeMismatch { + expected_authorizer: provider.authorizer_id(), + actual_authorizer: account.authorizer_id().to_owned(), + }) +} + +#[async_trait] +impl

AccountProvider for P +where + P: TypedAccountProvider, +{ + fn authorizer_id(&self) -> &'static str { + TypedAccountProvider::authorizer_id(self) + } + + fn decode(&self, data: &str) -> std::result::Result, serde_json::Error> { + serde_json::from_str::(data) + .map(|account| Box::new(account) as Box) + } + + async fn refresh(&self, account: &dyn Account) -> Result> { + let typed = downcast_account(self, account)?; + let refreshed = TypedAccountProvider::refresh(self, typed).await?; + Ok(Box::new(refreshed)) + } +} + +#[async_trait] +impl

TextureProvider for P +where + P: TypedTextureProvider, +{ + async fn textures(&self, account: &dyn Account) -> Result { + let typed = downcast_account(self, account)?; + TypedTextureProvider::textures(self, typed).await + } + + async fn upload_skin( + &self, + account: &dyn Account, + image: Vec, + model: SkinModel, + ) -> Result<()> { + let typed = downcast_account(self, account)?; + TypedTextureProvider::upload_skin(self, typed, image, model).await + } + + async fn delete_skin(&self, account: &dyn Account) -> Result<()> { + let typed = downcast_account(self, account)?; + TypedTextureProvider::delete_skin(self, typed).await + } + + async fn upload_cape(&self, account: &dyn Account, image: Vec) -> Result<()> { + let typed = downcast_account(self, account)?; + TypedTextureProvider::upload_cape(self, typed, image).await + } + + async fn delete_cape(&self, account: &dyn Account) -> Result<()> { + let typed = downcast_account(self, account)?; + TypedTextureProvider::delete_cape(self, typed).await + } + + async fn select_cape(&self, account: &dyn Account, cape_id: Option) -> Result<()> { + let typed = downcast_account(self, account)?; + TypedTextureProvider::select_cape(self, typed, cape_id).await + } +} diff --git a/crates/core/src/auth/providers/offline.rs b/crates/core/src/auth/providers/offline.rs new file mode 100644 index 00000000..377ad5bf --- /dev/null +++ b/crates/core/src/auth/providers/offline.rs @@ -0,0 +1,21 @@ +use async_trait::async_trait; + +use crate::auth::accounts::offline::{OFFLINE_AUTHORIZER_ID, OfflineAccount}; +use crate::auth::error::Result; +use crate::auth::providers::TypedAccountProvider; + +#[derive(Debug, Clone, Copy, Default)] +pub struct OfflineAccountProvider; + +#[async_trait] +impl TypedAccountProvider for OfflineAccountProvider { + type Account = OfflineAccount; + + fn authorizer_id(&self) -> &'static str { + OFFLINE_AUTHORIZER_ID + } + + async fn refresh(&self, account: &Self::Account) -> Result { + Ok(account.clone()) + } +} diff --git a/crates/core/src/auth/providers/yggdrasil.rs b/crates/core/src/auth/providers/yggdrasil.rs new file mode 100644 index 00000000..0e8eae78 --- /dev/null +++ b/crates/core/src/auth/providers/yggdrasil.rs @@ -0,0 +1,257 @@ +use async_trait::async_trait; +use nidhogg::{ + client::Nidhogg, + request::{refresh::Refresh, texture::TextureType as NidhoggTextureType}, + types::{ + meta::Meta, + profile::{Profile, ProfilePropertyError}, + textures::{ModelType, Texture}, + }, +}; + +use crate::auth::accounts::yggdrasil::{ + YGGDRASIL_AUTHORIZER_ID, YggdrasilAccount, YggdrasilProfile, preferred_language, user_id, +}; +use crate::auth::error::{Error, Result}; +use crate::auth::providers::{TypedAccountProvider, TypedTextureProvider}; +use crate::auth::texture::{ + Cape, ProfileTextures, Skin, SkinModel, TextureType as AccountTextureType, +}; +use crate::http::SwappableClient; + +#[derive(Debug, Clone, Default)] +pub struct YggdrasilAccountProvider { + http_client: SwappableClient, +} + +impl YggdrasilAccountProvider { + pub fn new(http_client: SwappableClient) -> Self { + Self { http_client } + } + + fn client(&self, account: &YggdrasilAccount) -> Result { + let base_url = account + .base_url + .as_deref() + .ok_or(Error::YggdrasilBaseUrlMissing)?; + nidhogg_client(base_url, Some(&self.http_client)) + } + + async fn upload( + &self, + account: &YggdrasilAccount, + texture_type: NidhoggTextureType, + image: Vec, + file_name: &str, + model: Option, + ) -> Result<()> { + self.client(account)? + .upload_texture( + account.selected_profile.id.clone(), + account.access_token.clone(), + texture_type, + image, + file_name.to_owned(), + model, + ) + .await + .map_err(|source| Error::Yggdrasil { source }) + } + + async fn delete( + &self, + account: &YggdrasilAccount, + texture_type: NidhoggTextureType, + ) -> Result<()> { + self.client(account)? + .delete_texture( + account.selected_profile.id.clone(), + account.access_token.clone(), + texture_type, + ) + .await + .map_err(|source| Error::Yggdrasil { source }) + } + + pub async fn fetch_site_metadata(&self, base_url: &str) -> Result { + fetch_site_metadata_with_client(base_url, &self.http_client).await + } + + /// Fetches the metadata document exposed by the account's Yggdrasil API. + /// + /// Returns `None` for offline accounts because they have no remote API + /// root. + pub async fn metadata(&self, account: &YggdrasilAccount) -> Result> { + let Some(base_url) = account.base_url.as_deref() else { + return Ok(None); + }; + self.fetch_site_metadata(base_url).await.map(Some) + } +} + +#[async_trait] +impl TypedAccountProvider for YggdrasilAccountProvider { + type Account = YggdrasilAccount; + + fn authorizer_id(&self) -> &'static str { + YGGDRASIL_AUTHORIZER_ID + } + + async fn refresh(&self, account: &Self::Account) -> Result { + if account.base_url.is_none() { + return Ok(account.clone()); + } + let response = self + .client(account)? + .refresh(&Refresh::new( + account.access_token.clone(), + Some(account.client_token.clone()), + true, + Some(Profile { + id: account.selected_profile.id.clone(), + name: account.selected_profile.name.clone(), + properties: None, + }), + )) + .await + .map_err(|source| Error::Yggdrasil { source })?; + + Ok(YggdrasilAccount { + account_id: account.account_id, + base_url: account.base_url.clone(), + user_id: user_id(response.user.as_ref()).or_else(|| account.user_id.clone()), + preferred_language: preferred_language(response.user.as_ref()) + .or_else(|| account.preferred_language.clone()), + access_token: response.access_token, + client_token: response.client_token, + selected_profile: response + .selected_profile + .as_ref() + .map(YggdrasilProfile::from) + .unwrap_or_else(|| account.selected_profile.clone()), + }) + } +} + +#[async_trait] +impl TypedTextureProvider for YggdrasilAccountProvider { + async fn textures(&self, account: &Self::Account) -> Result { + let profile = self + .client(account)? + .get_profile(account.selected_profile.id.clone(), false) + .await + .map_err(|source| Error::Yggdrasil { source })?; + profile_textures(&profile) + } + + async fn upload_skin( + &self, + account: &Self::Account, + image: Vec, + model: SkinModel, + ) -> Result<()> { + let model = match model { + SkinModel::Classic => None, + SkinModel::Slim => Some(ModelType::SLIM), + }; + self.upload(account, NidhoggTextureType::SKIN, image, "skin.png", model) + .await + } + + async fn delete_skin(&self, account: &Self::Account) -> Result<()> { + self.delete(account, NidhoggTextureType::SKIN).await + } + + async fn upload_cape(&self, account: &Self::Account, image: Vec) -> Result<()> { + self.upload(account, NidhoggTextureType::CAPE, image, "cape.png", None) + .await + } + + async fn delete_cape(&self, account: &Self::Account) -> Result<()> { + self.delete(account, NidhoggTextureType::CAPE).await + } +} + +pub(crate) fn nidhogg_client( + base_url: &str, + http_client: Option<&SwappableClient>, +) -> Result { + let normalized = base_url.trim().trim_end_matches('/'); + match http_client { + Some(client) => Ok(Nidhogg::with_client(normalized, client.client())), + None => Nidhogg::new(normalized).map_err(|source| Error::Yggdrasil { source }), + } +} + +pub async fn fetch_site_metadata_with_client( + base_url: &str, + http_client: &SwappableClient, +) -> Result { + nidhogg_client(base_url, Some(http_client))? + .metadata() + .await + .map_err(|source| Error::Yggdrasil { source }) +} + +fn profile_textures(profile: &Profile) -> Result { + let textures = optional_property(profile.get_textures())?; + let skin = textures + .as_ref() + .and_then(|textures| textures.textures.skin.as_ref()) + .map(skin_from) + .transpose()?; + let capes = textures + .and_then(|textures| textures.textures.cape) + .map(cape_from) + .into_iter() + .collect(); + let uploadable = optional_property(profile.get_uploadable_textures())? + .unwrap_or_default() + .into_iter() + .filter_map(uploadable_texture) + .collect(); + + Ok(ProfileTextures { + skin, + capes, + uploadable, + }) +} + +fn optional_property(result: std::result::Result) -> Result> { + match result { + Ok(value) => Ok(Some(value)), + Err(ProfilePropertyError::NoPropertyFound(_)) => Ok(None), + Err(source) => Err(Error::YggdrasilTexture { source }), + } +} + +fn skin_from(texture: &Texture) -> Result { + let model = match texture.metadata.as_ref().map(|metadata| &metadata.model) { + Some(ModelType::SLIM) => SkinModel::Slim, + Some(ModelType::DEFAULT) | None => SkinModel::Classic, + }; + Ok(Skin { + url: texture.url.clone(), + model, + }) +} + +fn cape_from(texture: Texture) -> Cape { + Cape { + id: None, + alias: None, + url: texture.url, + active: true, + } +} + +fn uploadable_texture(value: String) -> Option { + if value.eq_ignore_ascii_case("skin") { + Some(AccountTextureType::Skin) + } else if value.eq_ignore_ascii_case("cape") { + Some(AccountTextureType::Cape) + } else { + None + } +} diff --git a/crates/elemental/Cargo.toml b/crates/elemental/Cargo.toml index de969ba6..2d5adad7 100644 --- a/crates/elemental/Cargo.toml +++ b/crates/elemental/Cargo.toml @@ -105,6 +105,7 @@ microsoft-auth = [ ] yggdrasil-auth = [ "core", + "http", "launcher", "elemental-core/yggdrasil-auth", "elemental-launcher/yggdrasil-auth", diff --git a/crates/elemental/src/lib.rs b/crates/elemental/src/lib.rs index 6f0322dc..83fc410f 100644 --- a/crates/elemental/src/lib.rs +++ b/crates/elemental/src/lib.rs @@ -30,6 +30,10 @@ pub mod prelude { offline::{OFFLINE_AUTHORIZER_ID, OfflineAuthorizer}, }, credential::{Credential, CredentialKind}, + providers::{ + AccountProvider, TextureProvider, TypedAccountProvider, TypedTextureProvider, + offline::OfflineAccountProvider, + }, texture::{Cape, ProfileTextures, Skin, SkinModel, TextureType}, }, launcher::command::LaunchCommand, @@ -56,12 +60,14 @@ pub mod prelude { pub use crate::core::auth::{ accounts::microsoft::MicrosoftAccount, authorizers::microsoft::{MICROSOFT_AUTHORIZER_ID, MicrosoftAuthorizer}, + providers::microsoft::MicrosoftAccountProvider, }; #[cfg(feature = "yggdrasil-auth")] pub use crate::core::auth::{ - accounts::yggdrasil::{Meta, YggdrasilAccount, YggdrasilProfile}, + accounts::yggdrasil::{Links, Meta, ServerMeta, YggdrasilAccount, YggdrasilProfile}, authorizers::yggdrasil::{YGGDRASIL_AUTHORIZER_ID, YggdrasilAuthorizer}, + providers::yggdrasil::YggdrasilAccountProvider, }; #[cfg(feature = "driver")] @@ -103,4 +109,9 @@ pub mod prelude { LauncherBuilder, PrepareStage, PreparedInstance, PreparedInstanceInfo, PreparedInstanceMetadata, QuickPlayOptions, RuntimeOptions, }; + #[cfg(all(feature = "launcher", feature = "yggdrasil-auth"))] + pub use crate::launcher::{ + DEFAULT_YGGDRASIL_SITE_METADATA_TTL, YggdrasilSiteId, YggdrasilSiteIndex, + YggdrasilSiteMetadata, + }; } diff --git a/crates/launcher/Cargo.toml b/crates/launcher/Cargo.toml index 5a24a903..78613754 100644 --- a/crates/launcher/Cargo.toml +++ b/crates/launcher/Cargo.toml @@ -77,6 +77,7 @@ serde_json = { workspace = true } sha2 = { workspace = true } thiserror = { workspace = true } tokio = { workspace = true } +tracing = { workspace = true } [dev-dependencies] async-trait = { workspace = true } diff --git a/crates/launcher/src/account/mod.rs b/crates/launcher/src/account/mod.rs index 2357eac4..feb3230a 100644 --- a/crates/launcher/src/account/mod.rs +++ b/crates/launcher/src/account/mod.rs @@ -1,7 +1,13 @@ mod index; mod registry; +#[cfg(feature = "yggdrasil-auth")] +mod sites; mod store; pub use index::{AccountIndex, AccountRef}; pub use registry::AccountRegistry; +#[cfg(feature = "yggdrasil-auth")] +pub use sites::{ + DEFAULT_YGGDRASIL_SITE_METADATA_TTL, YggdrasilSiteId, YggdrasilSiteIndex, YggdrasilSiteMetadata, +}; pub use store::{AccountListing, AccountStore}; diff --git a/crates/launcher/src/account/registry.rs b/crates/launcher/src/account/registry.rs index 218a61e7..98c5806f 100644 --- a/crates/launcher/src/account/registry.rs +++ b/crates/launcher/src/account/registry.rs @@ -1,68 +1,110 @@ -use std::collections::HashMap; +use std::{collections::HashMap, sync::Arc}; #[cfg(feature = "microsoft-auth")] -use elemental_core::auth::{ - accounts::microsoft::MicrosoftAccount, authorizers::microsoft::MICROSOFT_AUTHORIZER_ID, -}; -use elemental_core::auth::{ - accounts::{Account, offline::OfflineAccount}, - authorizers::offline::OFFLINE_AUTHORIZER_ID, -}; -use serde::{Serialize, de::DeserializeOwned}; - +use elemental_core::auth::providers::microsoft::MicrosoftAccountProvider; #[cfg(feature = "yggdrasil-auth")] -use elemental_core::auth::{ - accounts::yggdrasil::YggdrasilAccount, authorizers::yggdrasil::YGGDRASIL_AUTHORIZER_ID, +use elemental_core::auth::providers::yggdrasil::YggdrasilAccountProvider; +use elemental_core::{ + auth::{ + accounts::Account, + providers::{ + AccountProvider, TextureProvider, TypedAccountProvider, TypedTextureProvider, + offline::OfflineAccountProvider, + }, + }, + http::SwappableClient, }; +use serde::Serialize; -pub(super) type AccountDecoder = - fn(&str) -> std::result::Result, serde_json::Error>; +#[derive(Clone)] +struct RegisteredProvider { + account: Arc, + textures: Option>, +} -/// Maps stable authorizer IDs to the account types they persist. +/// Maps stable authorizer IDs to the account providers they own. #[derive(Clone)] pub struct AccountRegistry { - decoders: HashMap<&'static str, AccountDecoder>, + providers: HashMap<&'static str, RegisteredProvider>, } impl AccountRegistry { - pub fn new() -> Self { - let registry = Self::empty().with::(OFFLINE_AUTHORIZER_ID); + pub fn new(http_client: SwappableClient) -> Self { + let registry = Self::empty().with(OfflineAccountProvider); #[cfg(feature = "microsoft-auth")] - let registry = registry.with::(MICROSOFT_AUTHORIZER_ID); + let registry = registry.with_textures(MicrosoftAccountProvider::new(http_client.clone())); #[cfg(feature = "yggdrasil-auth")] - let registry = registry.with::(YGGDRASIL_AUTHORIZER_ID); + let registry = registry.with_textures(YggdrasilAccountProvider::new(http_client)); + #[cfg(not(any(feature = "microsoft-auth", feature = "yggdrasil-auth")))] + let _ = http_client; registry } pub fn empty() -> Self { Self { - decoders: HashMap::new(), + providers: HashMap::new(), } } - pub fn with(mut self, authorizer_id: &'static str) -> Self + pub fn with

(mut self, provider: P) -> Self + where + P: TypedAccountProvider + 'static, + { + self.register(provider); + self + } + + pub fn register

(&mut self, provider: P) + where + P: TypedAccountProvider + 'static, + { + let id = TypedAccountProvider::authorizer_id(&provider); + self.providers.insert( + id, + RegisteredProvider { + account: Arc::new(provider), + textures: None, + }, + ); + } + + pub fn with_textures

(mut self, provider: P) -> Self where - A: Account + DeserializeOwned + 'static, + P: TypedTextureProvider + 'static, { - self.register::(authorizer_id); + self.register_with_textures(provider); self } - pub fn register(&mut self, authorizer_id: &'static str) + pub fn register_with_textures

(&mut self, provider: P) where - A: Account + DeserializeOwned + 'static, + P: TypedTextureProvider + 'static, { - self.decoders.insert(authorizer_id, decode_account::); + let id = TypedAccountProvider::authorizer_id(&provider); + let provider = Arc::new(provider); + self.providers.insert( + id, + RegisteredProvider { + account: Arc::clone(&provider) as Arc, + textures: Some(provider as Arc), + }, + ); } - pub(super) fn decoder(&self, authorizer: &str) -> Option { - self.decoders.get(authorizer).copied() + pub(super) fn provider(&self, authorizer: &str) -> Option<&Arc> { + self.providers.get(authorizer).map(|entry| &entry.account) + } + + pub(super) fn texture_provider(&self, authorizer: &str) -> Option<&Arc> { + self.providers + .get(authorizer) + .and_then(|entry| entry.textures.as_ref()) } } impl Default for AccountRegistry { fn default() -> Self { - Self::new() + Self::new(SwappableClient::default()) } } @@ -82,10 +124,3 @@ pub(super) fn encode_account( ) -> std::result::Result { serde_json::to_string(&SerializableAccount(account)) } - -fn decode_account(data: &str) -> std::result::Result, serde_json::Error> -where - A: Account + DeserializeOwned + 'static, -{ - serde_json::from_str::(data).map(|account| Box::new(account) as Box) -} diff --git a/crates/launcher/src/account/sites.rs b/crates/launcher/src/account/sites.rs new file mode 100644 index 00000000..5fe7bd72 --- /dev/null +++ b/crates/launcher/src/account/sites.rs @@ -0,0 +1,350 @@ +use std::{ + collections::{BTreeMap, HashMap, HashSet}, + sync::Mutex, + time::{Duration, SystemTime, UNIX_EPOCH}, +}; + +use elemental_core::{ + auth::{ + accounts::{AccountId, yggdrasil::Meta}, + providers::yggdrasil::fetch_site_metadata_with_client, + }, + http::SwappableClient, +}; +use elemental_shared::{ + migrator::NoMigrator, + persistor::{JsonFilePersistor, json_persistor}, + scope::Scope, + store::{Store, StoreLoader}, +}; +use serde::{Deserialize, Serialize}; +use tokio::sync::watch; + +use crate::error::Result; + +pub const DEFAULT_YGGDRASIL_SITE_METADATA_TTL: Duration = Duration::from_secs(60 * 60 * 24); + +const YGGDRASIL_SITE_INDEX_VERSION: usize = 1; + +/// Canonical Yggdrasil API root (trimmed whitespace and trailing `/`). +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +#[serde(transparent)] +pub struct YggdrasilSiteId(String); + +impl YggdrasilSiteId { + pub fn new(base_url: &str) -> Option { + let normalized = base_url.trim().trim_end_matches('/'); + (!normalized.is_empty()).then(|| Self(normalized.to_owned())) + } + + pub fn as_str(&self) -> &str { + &self.0 + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct YggdrasilSiteMetadata { + #[serde(flatten)] + pub meta: Meta, + /// Unix timestamp (seconds) when this snapshot was fetched. + pub fetched_at: u64, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct YggdrasilSiteIndex { + #[serde(default)] + pub accounts: BTreeMap, + #[serde(default)] + pub sites: BTreeMap, +} + +type YggdrasilSiteStoreLoader = StoreLoader< + NoMigrator, + Store, + YggdrasilSiteIndex, + JsonFilePersistor>, +>; + +#[derive(Clone)] +enum InFlightOutcome { + Fetched(YggdrasilSiteMetadata), + PersistFailed(YggdrasilSiteMetadata), + RemoteFailed, +} + +type InFlightMap = HashMap>>; + +struct InFlightGuard<'a> { + in_flight: &'a Mutex, + site: Option, +} + +impl<'a> InFlightGuard<'a> { + fn new(in_flight: &'a Mutex, site: YggdrasilSiteId) -> Self { + Self { + in_flight, + site: Some(site), + } + } + + fn remove(&mut self) { + if let Some(site) = self.site.take() + && let Ok(mut map) = self.in_flight.lock() + { + map.remove(&site); + } + } +} + +impl Drop for InFlightGuard<'_> { + fn drop(&mut self) { + self.remove(); + } +} + +pub(super) struct YggdrasilSiteStore { + store: YggdrasilSiteStoreLoader, + in_flight: Mutex, +} + +impl YggdrasilSiteStore { + pub(super) async fn open(scope: Scope) -> Result { + let store = Store::load( + NoMigrator, + json_persistor("accounts/yggdrasil_sites".to_owned(), scope), + YGGDRASIL_SITE_INDEX_VERSION, + ) + .await?; + + Ok(Self { + store, + in_flight: Mutex::new(HashMap::new()), + }) + } + + pub(super) async fn get(&self, site: &YggdrasilSiteId) -> Option { + self.store.get(|index| index.sites.get(site).cloned()).await + } + + pub(super) async fn get_or_fetch( + &self, + site: &YggdrasilSiteId, + ttl: Duration, + http_client: &SwappableClient, + ) -> Result> { + if let Some(cached) = self.get(site).await { + let age = now_unix_secs().saturating_sub(cached.fetched_at); + if age < ttl.as_secs() { + return Ok(Some(cached)); + } + } + self.refresh(site, http_client).await + } + + pub(super) async fn refresh( + &self, + site: &YggdrasilSiteId, + http_client: &SwappableClient, + ) -> Result> { + loop { + let leader = { + let mut map = self + .in_flight + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + if let Some(rx) = map.get(site) { + Err(rx.clone()) + } else { + let (tx, rx) = watch::channel(None); + map.insert(site.clone(), rx); + Ok(tx) + } + }; + + match leader { + Err(mut rx) => { + let outcome = match rx.wait_for(|value| value.is_some()).await { + Ok(guard) => guard.clone(), + Err(_) => continue, + }; + return match outcome { + Some(InFlightOutcome::Fetched(snapshot)) => Ok(Some(snapshot)), + Some(InFlightOutcome::RemoteFailed) => Ok(self.get(site).await), + Some(InFlightOutcome::PersistFailed(snapshot)) => { + self.persist(site, snapshot.clone()).await?; + Ok(Some(snapshot)) + } + None => continue, + }; + } + Ok(tx) => { + let mut guard = InFlightGuard::new(&self.in_flight, site.clone()); + return match fetch_site_metadata_with_client(site.as_str(), http_client).await { + Ok(meta) => { + let snapshot = YggdrasilSiteMetadata { + meta, + fetched_at: now_unix_secs(), + }; + let persist_result = self.persist(site, snapshot.clone()).await; + guard.remove(); + match persist_result { + Ok(()) => { + let _ = + tx.send(Some(InFlightOutcome::Fetched(snapshot.clone()))); + Ok(Some(snapshot)) + } + Err(err) => { + let _ = tx.send(Some(InFlightOutcome::PersistFailed(snapshot))); + Err(err) + } + } + } + Err(error) => { + tracing::warn!( + site = %site.as_str(), + %error, + "failed to fetch Yggdrasil site metadata" + ); + guard.remove(); + let _ = tx.send(Some(InFlightOutcome::RemoteFailed)); + Ok(self.get(site).await) + } + }; + } + } + } + } + + async fn persist(&self, site: &YggdrasilSiteId, snapshot: YggdrasilSiteMetadata) -> Result<()> { + self.store + .set(|index| { + index.sites.insert(site.clone(), snapshot); + }) + .await?; + Ok(()) + } + + pub(super) async fn account_site(&self, account_id: AccountId) -> Option { + self.store + .get(|index| index.accounts.get(&account_id).cloned()) + .await + } + + pub(super) async fn link_account( + &self, + account_id: AccountId, + site: YggdrasilSiteId, + ) -> Result<()> { + let already_linked = self + .store + .get(|index| index.accounts.get(&account_id) == Some(&site)) + .await; + if already_linked { + return Ok(()); + } + self.store + .set(|index| { + index.accounts.insert(account_id, site); + }) + .await?; + Ok(()) + } + + pub(super) async fn unlink_account(&self, account_id: AccountId) -> Result<()> { + let exists = self + .store + .get(|index| index.accounts.contains_key(&account_id)) + .await; + if !exists { + return Ok(()); + } + self.store + .set(|index| { + index.accounts.remove(&account_id); + }) + .await?; + Ok(()) + } + + pub(super) async fn unlinked_accounts( + &self, + yggdrasil_account_ids: &[AccountId], + ) -> Vec { + self.store + .get(|index| { + yggdrasil_account_ids + .iter() + .copied() + .filter(|id| !index.accounts.contains_key(id)) + .collect() + }) + .await + } + + pub(super) async fn prune_unlinked(&self, live_accounts: &HashSet) -> Result<()> { + let needs_prune = self + .store + .get(|index| { + let stale_links = index + .accounts + .keys() + .any(|account_id| !live_accounts.contains(account_id)); + let active_sites: HashSet<&YggdrasilSiteId> = index + .accounts + .iter() + .filter(|(account_id, _)| live_accounts.contains(account_id)) + .map(|(_, site)| site) + .collect(); + let stale_sites = index.sites.keys().any(|site| !active_sites.contains(site)); + stale_links || stale_sites + }) + .await; + if !needs_prune { + return Ok(()); + } + self.store + .set(|index| { + index + .accounts + .retain(|account_id, _| live_accounts.contains(account_id)); + let active_sites: HashSet = + index.accounts.values().cloned().collect(); + index.sites.retain(|site, _| active_sites.contains(site)); + }) + .await?; + Ok(()) + } + + pub(super) async fn remove(&self, site: &YggdrasilSiteId) -> Result<()> { + let exists = self.store.get(|index| index.sites.contains_key(site)).await; + if !exists { + return Ok(()); + } + self.store + .set(|index| { + index.sites.remove(site); + }) + .await?; + Ok(()) + } + + pub(super) async fn clear(&self) -> Result<()> { + let is_empty = self.store.get(|index| index.sites.is_empty()).await; + if is_empty { + return Ok(()); + } + self.store + .set(|index| { + index.sites.clear(); + }) + .await?; + Ok(()) + } +} + +fn now_unix_secs() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_secs() +} diff --git a/crates/launcher/src/account/store.rs b/crates/launcher/src/account/store.rs index d25f5ab2..da55094c 100644 --- a/crates/launcher/src/account/store.rs +++ b/crates/launcher/src/account/store.rs @@ -1,22 +1,42 @@ -use std::{io::ErrorKind, path::PathBuf}; +#[cfg(feature = "yggdrasil-auth")] +use std::{collections::HashSet, time::Duration}; +use std::{io::ErrorKind, path::PathBuf, sync::Arc}; -use elemental_core::auth::{ - accounts::{Account, AccountId}, - authorizers::Authorizer, +#[cfg(feature = "yggdrasil-auth")] +use elemental_core::auth::accounts::yggdrasil::YGGDRASIL_AUTHORIZER_ID; +use elemental_core::{ + auth::{ + Error as AuthError, + accounts::{Account, AccountId}, + authorizers::Authorizer, + providers::{AccountProvider, TextureProvider}, + texture::{ProfileTextures, SkinModel}, + }, + http::SwappableClient, }; use elemental_shared::{ migrator::NoMigrator, persistor::json_persistor, scope::Scope, store::Store, }; +#[cfg(feature = "yggdrasil-auth")] +use super::sites::{ + DEFAULT_YGGDRASIL_SITE_METADATA_TTL, YggdrasilSiteId, YggdrasilSiteMetadata, YggdrasilSiteStore, +}; use super::{ index::{ACCOUNT_INDEX_VERSION, AccountIndex, AccountIndexStore, AccountRef}, - registry::{AccountDecoder, AccountRegistry, encode_account}, + registry::{AccountRegistry, encode_account}, }; use crate::error::{Error, Result}; pub struct AccountStore { scope: Scope, index: AccountIndexStore, + #[cfg(feature = "yggdrasil-auth")] + sites: YggdrasilSiteStore, + #[cfg(feature = "yggdrasil-auth")] + site_metadata_ttl: Duration, + #[cfg(feature = "yggdrasil-auth")] + http_client: SwappableClient, registry: AccountRegistry, } @@ -29,44 +49,83 @@ pub struct AccountListing { impl AccountStore { pub async fn open(scope: Scope) -> Result { - Self::with_registry(scope, AccountRegistry::new()).await + Self::open_with_http_client(scope, SwappableClient::default()).await + } + + pub async fn open_with_http_client(scope: Scope, http_client: SwappableClient) -> Result { + let registry = AccountRegistry::new(http_client.clone()); + Self::with_registry(scope, http_client, registry).await } - pub async fn with_registry(scope: Scope, registry: AccountRegistry) -> Result { + pub async fn with_registry( + scope: Scope, + http_client: SwappableClient, + registry: AccountRegistry, + ) -> Result { let index = Store::load( NoMigrator, json_persistor("accounts/index".to_owned(), scope.clone()), ACCOUNT_INDEX_VERSION, ) .await?; + #[cfg(feature = "yggdrasil-auth")] + let sites = YggdrasilSiteStore::open(scope.clone()).await?; + #[cfg(not(feature = "yggdrasil-auth"))] + let _ = http_client; Ok(Self { scope, index, + #[cfg(feature = "yggdrasil-auth")] + sites, + #[cfg(feature = "yggdrasil-auth")] + site_metadata_ttl: DEFAULT_YGGDRASIL_SITE_METADATA_TTL, + #[cfg(feature = "yggdrasil-auth")] + http_client, registry, }) } + #[cfg(feature = "yggdrasil-auth")] + pub fn with_site_metadata_ttl(mut self, ttl: Duration) -> Self { + self.site_metadata_ttl = ttl; + self + } + pub async fn index(&self) -> AccountIndex { self.index.cloned().await } - fn decoder(&self, reference: &AccountRef) -> Result { + fn provider( + &self, + account_id: AccountId, + authorizer: &str, + ) -> Result<&Arc> { self.registry - .decoder(&reference.authorizer) + .provider(authorizer) .ok_or_else(|| Error::UnknownAuthorizer { - account_id: reference.account_id, - authorizer: reference.authorizer.clone(), + account_id, + authorizer: authorizer.to_owned(), }) } + fn texture_provider( + &self, + account: &dyn Account, + operation: &'static str, + ) -> Result<&Arc> { + self.registry + .texture_provider(account.authorizer_id()) + .ok_or_else(|| Error::Auth(AuthError::TextureUnsupported { operation })) + } + pub async fn save(&self, account: &dyn Account) -> Result<()> { let account_id = account.account_id(); let reference = AccountRef { account_id, authorizer: account.authorizer_id().to_owned(), }; - self.decoder(&reference)?; + self.provider(reference.account_id, &reference.authorizer)?; let data = encode_account(account).map_err(|source| Error::AccountEncode { account_id: reference.account_id, authorizer: reference.authorizer.clone(), @@ -75,6 +134,11 @@ impl AccountStore { let path = self.account_path(&reference).await?; tokio::fs::write(path, data).await?; self.index.set(|index| index.upsert(reference)).await?; + #[cfg(feature = "yggdrasil-auth")] + match account_site(account) { + Some(site) => self.sites.link_account(account_id, site).await?, + None => self.sites.unlink_account(account_id).await?, + } Ok(()) } @@ -88,6 +152,10 @@ impl AccountStore { { let account = authorizer.authorize().await?; self.save(&account).await?; + #[cfg(feature = "yggdrasil-auth")] + if let Some(site) = account_site(&account) { + self.sites.refresh(&site, &self.http_client).await?; + } Ok(account) } @@ -97,11 +165,40 @@ impl AccountStore { tokio::fs::remove_file(path).await?; self.index.set(|index| index.remove(account_id)).await?; + #[cfg(feature = "yggdrasil-auth")] + { + self.sites.unlink_account(account_id).await?; + let (yggdrasil_ids, live_ids) = self + .index + .get(|index| { + let yggdrasil_ids: Vec = index + .accounts + .iter() + .filter(|entry| entry.authorizer == YGGDRASIL_AUTHORIZER_ID) + .map(|entry| entry.account_id) + .collect(); + let live_ids: HashSet = index + .accounts + .iter() + .map(|entry| entry.account_id) + .collect(); + (yggdrasil_ids, live_ids) + }) + .await; + if self + .sites + .unlinked_accounts(&yggdrasil_ids) + .await + .is_empty() + { + self.sites.prune_unlinked(&live_ids).await?; + } + } Ok(()) } pub async fn load(&self, reference: &AccountRef) -> Result> { - let decoder = self.decoder(reference)?; + let provider = self.provider(reference.account_id, &reference.authorizer)?; let path = self.account_path(reference).await?; let data = match tokio::fs::read_to_string(path).await { Ok(data) => data, @@ -112,11 +209,13 @@ impl AccountStore { } Err(source) => return Err(source.into()), }; - let account = decoder(&data).map_err(|source| Error::AccountDecode { - account_id: reference.account_id, - authorizer: reference.authorizer.clone(), - source, - })?; + let account = provider + .decode(&data) + .map_err(|source| Error::AccountDecode { + account_id: reference.account_id, + authorizer: reference.authorizer.clone(), + source, + })?; if account.account_id() != reference.account_id || account.authorizer_id() != reference.authorizer.as_str() @@ -129,6 +228,18 @@ impl AccountStore { }); } + #[cfg(feature = "yggdrasil-auth")] + if reference.authorizer == YGGDRASIL_AUTHORIZER_ID + && self + .sites + .account_site(reference.account_id) + .await + .is_none() + && let Some(site) = account_site(account.as_ref()) + { + self.sites.link_account(reference.account_id, site).await?; + } + Ok(account) } @@ -205,11 +316,155 @@ impl AccountStore { } async fn persist_refresh(&self, account: Box) -> Result> { - let refreshed = account.refresh().await?; + let provider = self.provider(account.account_id(), account.authorizer_id())?; + let refreshed = provider.refresh(account.as_ref()).await?; self.save(refreshed.as_ref()).await?; + #[cfg(feature = "yggdrasil-auth")] + if let Some(site) = account_site(refreshed.as_ref()) { + self.sites.refresh(&site, &self.http_client).await?; + } Ok(refreshed) } + pub async fn supports_textures(&self, account_id: AccountId) -> Result { + let reference = self.reference(account_id).await?; + Ok(self + .registry + .texture_provider(&reference.authorizer) + .is_some()) + } + + pub async fn textures(&self, account_id: AccountId) -> Result { + let account = self.account(account_id).await?; + let provider = self.texture_provider(account.as_ref(), "read textures")?; + Ok(provider.textures(account.as_ref()).await?) + } + + pub async fn upload_skin( + &self, + account_id: AccountId, + image: Vec, + model: SkinModel, + ) -> Result<()> { + let account = self.account(account_id).await?; + let provider = self.texture_provider(account.as_ref(), "upload skin")?; + Ok(provider.upload_skin(account.as_ref(), image, model).await?) + } + + pub async fn delete_skin(&self, account_id: AccountId) -> Result<()> { + let account = self.account(account_id).await?; + let provider = self.texture_provider(account.as_ref(), "delete skin")?; + Ok(provider.delete_skin(account.as_ref()).await?) + } + + pub async fn upload_cape(&self, account_id: AccountId, image: Vec) -> Result<()> { + let account = self.account(account_id).await?; + let provider = self.texture_provider(account.as_ref(), "upload cape")?; + Ok(provider.upload_cape(account.as_ref(), image).await?) + } + + pub async fn delete_cape(&self, account_id: AccountId) -> Result<()> { + let account = self.account(account_id).await?; + let provider = self.texture_provider(account.as_ref(), "delete cape")?; + Ok(provider.delete_cape(account.as_ref()).await?) + } + + pub async fn select_cape(&self, account_id: AccountId, cape_id: Option) -> Result<()> { + let account = self.account(account_id).await?; + let provider = self.texture_provider(account.as_ref(), "select cape")?; + Ok(provider.select_cape(account.as_ref(), cape_id).await?) + } + + #[cfg(feature = "yggdrasil-auth")] + pub async fn site_metadata(&self, site: &YggdrasilSiteId) -> Option { + self.sites.get(site).await + } + + #[cfg(feature = "yggdrasil-auth")] + pub async fn account_site_metadata( + &self, + account_id: AccountId, + ) -> Result> { + let reference = self.reference(account_id).await?; + let site = if let Some(site) = self.sites.account_site(account_id).await { + Some(site) + } else if reference.authorizer == YGGDRASIL_AUTHORIZER_ID { + let account = self.load(&reference).await?; + account_site(account.as_ref()) + } else { + None + }; + let Some(site) = site else { + return Ok(None); + }; + self.sites + .get_or_fetch(&site, self.site_metadata_ttl, &self.http_client) + .await + } + + #[cfg(feature = "yggdrasil-auth")] + pub async fn refresh_site_metadata( + &self, + site: &YggdrasilSiteId, + ) -> Result> { + self.sites.refresh(site, &self.http_client).await + } + + #[cfg(feature = "yggdrasil-auth")] + pub async fn prune_unused_sites(&self) -> Result<()> { + let (yggdrasil_refs, live_ids) = self + .index + .get(|index| { + let yggdrasil_refs: Vec = index + .accounts + .iter() + .filter(|entry| entry.authorizer == YGGDRASIL_AUTHORIZER_ID) + .cloned() + .collect(); + let live_ids: HashSet = index + .accounts + .iter() + .map(|entry| entry.account_id) + .collect(); + (yggdrasil_refs, live_ids) + }) + .await; + + let yggdrasil_ids: Vec = yggdrasil_refs + .iter() + .map(|entry| entry.account_id) + .collect(); + let unlinked: HashSet = self + .sites + .unlinked_accounts(&yggdrasil_ids) + .await + .into_iter() + .collect(); + + for reference in yggdrasil_refs + .into_iter() + .filter(|entry| unlinked.contains(&entry.account_id)) + { + match self.load(&reference).await { + Ok(_) => {} + Err(Error::UnknownAuthorizer { .. }) => return Ok(()), + Err(source) => return Err(source), + } + } + + self.sites.prune_unlinked(&live_ids).await + } + + #[cfg(feature = "yggdrasil-auth")] + pub async fn remove_site_metadata(&self, site: &YggdrasilSiteId) -> Result<()> { + self.sites.remove(site).await + } + + #[cfg(feature = "yggdrasil-auth")] + pub async fn clear_site_metadata(&self) -> Result<()> { + self.sites.clear().await + } + async fn reference(&self, account_id: AccountId) -> Result { self.index .get(|index| { @@ -231,3 +486,12 @@ impl AccountStore { .await?) } } + +#[cfg(feature = "yggdrasil-auth")] +fn account_site(account: &dyn Account) -> Option { + account + .credential() + .auth_server + .as_deref() + .and_then(YggdrasilSiteId::new) +} diff --git a/crates/launcher/src/lib.rs b/crates/launcher/src/lib.rs index 1e02d0e7..e73f3c87 100644 --- a/crates/launcher/src/lib.rs +++ b/crates/launcher/src/lib.rs @@ -18,6 +18,10 @@ mod spec; mod texture; pub use account::{AccountIndex, AccountListing, AccountRef, AccountRegistry, AccountStore}; +#[cfg(feature = "yggdrasil-auth")] +pub use account::{ + DEFAULT_YGGDRASIL_SITE_METADATA_TTL, YggdrasilSiteId, YggdrasilSiteIndex, YggdrasilSiteMetadata, +}; pub use addon::{AddonRegistry, AddonSpec}; pub use builder::LauncherBuilder; pub use cape::{CapeAsset, CapeEntry, CapeId, CapeStore, SelectedCape}; @@ -53,5 +57,5 @@ pub use result::{ InspectReport, Instance, InstanceInspectionFailure, LaunchedInstance, PreparedInstance, PreparedInstanceInfo, PreparedInstanceMetadata, RemoveInstanceOutcome, }; -pub use skin::{AccountSkinExt, LocalSkin, SelectedSkin, SkinAsset, SkinEntry, SkinId, SkinStore}; +pub use skin::{SelectedSkin, SkinAsset, SkinEntry, SkinId, SkinStore}; pub use spec::DriverSpec; diff --git a/crates/launcher/src/skin.rs b/crates/launcher/src/skin.rs index 24569292..c6a2c2fe 100644 --- a/crates/launcher/src/skin.rs +++ b/crates/launcher/src/skin.rs @@ -1,9 +1,6 @@ -use std::{collections::HashSet, future::Future, path::PathBuf}; +use std::{collections::HashSet, path::PathBuf}; -use elemental_core::auth::{ - accounts::{Account, AccountId}, - texture::SkinModel, -}; +use elemental_core::auth::{accounts::AccountId, texture::SkinModel}; use elemental_shared::{ migrator::NoMigrator, persistor::{JsonFilePersistor, json_persistor}, @@ -13,6 +10,7 @@ use elemental_shared::{ use serde::{Deserialize, Serialize}; use crate::{ + account::AccountStore, error::{Error, Result}, texture::{PNG_SIGNATURE, TextureHash, gc_content, is_valid_name, remove_if_present}, }; @@ -109,27 +107,6 @@ pub struct SkinEntry { pub path: PathBuf, } -/// A local skin bound to an account-facing model choice. -pub struct LocalSkin<'a> { - store: &'a SkinStore, - skin_id: SkinId, - model: SkinModel, -} - -pub trait AccountSkinExt { - /// Uploads `skin` to this account and remembers it as the account's selection. - fn skin(&self, skin: LocalSkin<'_>) -> impl Future> + Send; -} - -impl AccountSkinExt for A -where - A: Account + ?Sized, -{ - async fn skin(&self, skin: LocalSkin<'_>) -> Result<()> { - skin.store.upload(self, skin.skin_id, skin.model).await - } -} - /// Stores skin PNG files locally by SHA-256 content hash and tracks /// per-account selections. pub struct SkinStore { @@ -151,15 +128,6 @@ impl SkinStore { Ok(store) } - /// Builds an account-facing skin handle without touching the filesystem. - pub fn skin(&self, skin_id: SkinId, model: SkinModel) -> LocalSkin<'_> { - LocalSkin { - store: self, - skin_id, - model, - } - } - /// Imports PNG bytes into the local library. pub async fn import( &self, @@ -323,13 +291,17 @@ impl SkinStore { Ok((asset, path)) } - async fn upload(&self, account: &A, skin_id: SkinId, model: SkinModel) -> Result<()> - where - A: Account + ?Sized, - { + /// Uploads a locally stored skin to `account_id` and records it as selected. + pub async fn upload( + &self, + accounts: &AccountStore, + account_id: AccountId, + skin_id: SkinId, + model: SkinModel, + ) -> Result<()> { let (_, path) = self.existing(skin_id).await?; let bytes = tokio::fs::read(&path).await?; - account.upload_skin(bytes, model).await?; - self.select(account.account_id(), skin_id, model).await + accounts.upload_skin(account_id, bytes, model).await?; + self.select(account_id, skin_id, model).await } } diff --git a/crates/launcher/tests/account_store.rs b/crates/launcher/tests/account_store.rs index 6b100460..1494585d 100644 --- a/crates/launcher/tests/account_store.rs +++ b/crates/launcher/tests/account_store.rs @@ -21,9 +21,10 @@ async fn account_store_persists_selects_and_removes_offline_account() { .await .unwrap(); let account_id = account.account_id(); - let expected_uuid = account.credential().await.unwrap().uuid; + let expected_uuid = account.credential().uuid; assert_eq!(account.display_name(), "TestPlayer"); + assert!(!store.supports_textures(account_id).await.unwrap()); assert_eq!(store.list().await.unwrap().len(), 1); assert!(store.selected().await.unwrap().is_none()); @@ -34,7 +35,7 @@ async fn account_store_persists_selects_and_removes_offline_account() { assert_eq!(selected.account_id(), account_id); let account = reopened.account(account_id).await.unwrap(); - let credential = account.credential().await.unwrap(); + let credential = account.credential(); assert_eq!(credential.username, "TestPlayer"); assert_eq!(credential.uuid, expected_uuid); assert_eq!(credential.kind, CredentialKind::Legacy); diff --git a/crates/launcher/tests/common/addon.rs b/crates/launcher/tests/common/addon.rs index 85d99bbd..4749dc8b 100644 --- a/crates/launcher/tests/common/addon.rs +++ b/crates/launcher/tests/common/addon.rs @@ -92,7 +92,7 @@ pub fn seed_local_vanilla_instance(root: &Path, name: &str) -> PathBuf { pub async fn test_credential() -> Credential { let account = OfflineAccount::new("Player".to_owned()); - account.credential().await.unwrap() + account.credential() } pub fn build_launcher(root: &Path, java_home: &Path) -> Launcher { diff --git a/crates/launcher/tests/offline_yggdrasil.rs b/crates/launcher/tests/offline_yggdrasil.rs index 6bb56c12..99ca0d19 100644 --- a/crates/launcher/tests/offline_yggdrasil.rs +++ b/crates/launcher/tests/offline_yggdrasil.rs @@ -16,21 +16,16 @@ async fn offline_yggdrasil_account_survives_restart_without_base_url() { let scope = Scope::Directory(root.clone()); let store = AccountStore::open(scope.clone()).await.unwrap(); - let authorizer = YggdrasilAuthorizer { - base_url: None, - username: "TestPlayer".to_owned(), - password: String::new(), - client_token: None, - }; + let authorizer = YggdrasilAuthorizer::offline("TestPlayer"); let account = store.sign_in(&authorizer).await.unwrap(); let account_id = account.account_id(); - let expected_uuid = account.credential().await.unwrap().uuid; + let expected_uuid = account.credential().uuid; assert_eq!(account.authorizer_id(), YGGDRASIL_AUTHORIZER_ID); let reopened = AccountStore::open(scope).await.unwrap(); let account = reopened.account(account_id).await.unwrap(); - let credential = account.credential().await.unwrap(); + let credential = account.credential(); assert_eq!(account.authorizer_id(), YGGDRASIL_AUTHORIZER_ID); assert_eq!(credential.username, "TestPlayer"); diff --git a/crates/launcher/tests/yggdrasil_site_metadata.rs b/crates/launcher/tests/yggdrasil_site_metadata.rs new file mode 100644 index 00000000..6d1f9410 --- /dev/null +++ b/crates/launcher/tests/yggdrasil_site_metadata.rs @@ -0,0 +1,646 @@ +#![cfg(feature = "yggdrasil-auth")] + +use std::{ + sync::{ + Arc, + atomic::{AtomicBool, AtomicUsize, Ordering}, + }, + time::Duration, +}; + +use elemental_core::{ + auth::{ + accounts::Account, + authorizers::{offline::OfflineAuthorizer, yggdrasil::YggdrasilAuthorizer}, + }, + http::{HttpClientConfig, SwappableClient}, +}; +use elemental_launcher::{AccountStore, YggdrasilSiteId}; +use elemental_shared::scope::Scope; +use serde_json::json; +use tokio::{ + io::{AsyncReadExt, AsyncWriteExt}, + net::{TcpListener, TcpStream}, + sync::{Mutex, Notify}, + task::JoinHandle, +}; + +mod common; + +struct MockServerState { + server_name: Mutex, + metadata_hits: AtomicUsize, + fail_metadata: AtomicBool, + hold_metadata: Option>, + entered_metadata: Option>, + requests: Mutex)>>, +} + +struct MockYggdrasilServer { + base_url: String, + state: Arc, + handle: JoinHandle<()>, +} + +impl MockYggdrasilServer { + async fn start(server_name: &str) -> Self { + Self::start_with_hooks(server_name, None, None).await + } + + async fn start_with_hooks( + server_name: &str, + entered_metadata: Option>, + hold_metadata: Option>, + ) -> Self { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let state = Arc::new(MockServerState { + server_name: Mutex::new(server_name.to_owned()), + metadata_hits: AtomicUsize::new(0), + fail_metadata: AtomicBool::new(false), + hold_metadata, + entered_metadata, + requests: Mutex::new(Vec::new()), + }); + let server_state = Arc::clone(&state); + let handle = tokio::spawn(async move { + loop { + let Ok((stream, _)) = listener.accept().await else { + break; + }; + let state = Arc::clone(&server_state); + tokio::spawn(async move { + handle_connection(stream, state).await; + }); + } + }); + Self { + base_url: format!("http://{addr}"), + state, + handle, + } + } + + fn metadata_hits(&self) -> usize { + self.state.metadata_hits.load(Ordering::SeqCst) + } + + fn set_fail_metadata(&self, fail: bool) { + self.state.fail_metadata.store(fail, Ordering::SeqCst); + } + + async fn set_server_name(&self, name: &str) { + *self.state.server_name.lock().await = name.to_owned(); + } + + async fn take_requests(&self) -> Vec<(String, String, Option)> { + std::mem::take(&mut *self.state.requests.lock().await) + } +} + +impl Drop for MockYggdrasilServer { + fn drop(&mut self) { + self.handle.abort(); + } +} + +async fn read_http_request( + stream: &mut TcpStream, +) -> Option<(String, String, Option, Vec)> { + let mut buf = Vec::new(); + let mut tmp = [0u8; 1024]; + let header_end = loop { + let n = stream.read(&mut tmp).await.ok()?; + if n == 0 { + return None; + } + buf.extend_from_slice(&tmp[..n]); + if let Some(pos) = buf.windows(4).position(|w| w == b"\r\n\r\n") { + break pos + 4; + } + }; + + let headers_str = String::from_utf8_lossy(&buf[..header_end]).into_owned(); + let mut lines = headers_str.lines(); + let request_line = lines.next()?; + let mut parts = request_line.split_whitespace(); + let method = parts.next()?.to_owned(); + let path = parts.next()?.to_owned(); + + let mut content_length = 0usize; + let mut user_agent = None; + for line in lines { + if let Some((name, value)) = line.split_once(':') { + if name.eq_ignore_ascii_case("content-length") { + content_length = value.trim().parse::().ok().unwrap_or(0); + } else if name.eq_ignore_ascii_case("user-agent") { + user_agent = Some(value.trim().to_owned()); + } + } + } + + while buf.len() < header_end + content_length { + let n = stream.read(&mut tmp).await.ok()?; + if n == 0 { + break; + } + buf.extend_from_slice(&tmp[..n]); + } + let body = buf[header_end..buf.len().min(header_end + content_length)].to_vec(); + Some((method, path, user_agent, body)) +} + +async fn write_json_response(stream: &mut TcpStream, status: &str, body: &serde_json::Value) { + let payload = serde_json::to_vec(body).unwrap(); + let header = format!( + "HTTP/1.1 {status}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", + payload.len() + ); + let _ = stream.write_all(header.as_bytes()).await; + let _ = stream.write_all(&payload).await; + let _ = stream.flush().await; +} + +async fn handle_connection(mut stream: TcpStream, state: Arc) { + let Some((method, path, user_agent, body)) = read_http_request(&mut stream).await else { + return; + }; + state + .requests + .lock() + .await + .push((method.clone(), path.clone(), user_agent)); + + match (method.as_str(), path.as_str()) { + ("GET", "/") => { + state.metadata_hits.fetch_add(1, Ordering::SeqCst); + if let Some(entered) = &state.entered_metadata { + entered.notify_waiters(); + } + if let Some(hold) = &state.hold_metadata { + hold.notified().await; + } + if state.fail_metadata.load(Ordering::SeqCst) { + write_json_response(&mut stream, "500 Internal Server Error", &json!({})).await; + return; + } + let server_name = state.server_name.lock().await.clone(); + write_json_response( + &mut stream, + "200 OK", + &json!({ + "meta": { + "serverName": server_name, + "implementationName": "mock-yggdrasil", + "implementationVersion": "1.0.0", + "links": { + "homepage": "https://example.com", + "register": "https://example.com/register" + }, + "feature.non_email_login": true + }, + "skinDomains": ["textures.example.com"], + "signaturePublickey": "-----BEGIN PUBLIC KEY-----\nMOCK\n-----END PUBLIC KEY-----" + }), + ) + .await; + } + ("POST", "/authserver/authenticate") => { + let req: serde_json::Value = serde_json::from_slice(&body).unwrap_or_default(); + let username = req["username"].as_str().unwrap_or("Player"); + let profile_id = format!("{username}-uuid"); + write_json_response( + &mut stream, + "200 OK", + &json!({ + "accessToken": format!("access-{username}"), + "clientToken": req["clientToken"].as_str().unwrap_or("client-token"), + "selectedProfile": { + "id": profile_id, + "name": username + } + }), + ) + .await; + } + ("POST", "/authserver/refresh") => { + let req: serde_json::Value = serde_json::from_slice(&body).unwrap_or_default(); + let name = req["selectedProfile"]["name"].as_str().unwrap_or("Player"); + let id = req["selectedProfile"]["id"] + .as_str() + .unwrap_or("player-uuid"); + write_json_response( + &mut stream, + "200 OK", + &json!({ + "accessToken": "refreshed-access", + "clientToken": req["clientToken"].as_str().unwrap_or("client-token"), + "selectedProfile": { + "id": id, + "name": name + } + }), + ) + .await; + } + _ => { + write_json_response(&mut stream, "404 Not Found", &json!({})).await; + } + } +} + +#[tokio::test] +async fn sign_in_persists_shared_site_metadata_and_reads_offline() { + let server = MockYggdrasilServer::start("LittleSkin").await; + let root = common::temp_root("elemental-yggdrasil-site-persist"); + let scope = Scope::Directory(root.clone()); + let store = AccountStore::open(scope.clone()).await.unwrap(); + + let site_id = YggdrasilSiteId::new(&format!(" {}/ ", server.base_url)).unwrap(); + assert_eq!(site_id.as_str(), server.base_url); + + let first = store + .sign_in(&YggdrasilAuthorizer::new( + format!("{}/", server.base_url), + "Alice", + "pw", + )) + .await + .unwrap(); + let second = store + .sign_in(&YggdrasilAuthorizer::new( + server.base_url.clone(), + "Bob", + "pw", + )) + .await + .unwrap(); + + let index = store.index().await; + assert_eq!(index.accounts.len(), 2); + + let sites_file = root + .join(".elemental") + .join("accounts") + .join("yggdrasil_sites.json"); + let raw: serde_json::Value = + serde_json::from_str(&std::fs::read_to_string(&sites_file).unwrap()).unwrap(); + let accounts_obj = raw["value"]["accounts"].as_object().unwrap(); + assert_eq!(accounts_obj.len(), 2); + assert_eq!( + accounts_obj[&first.account_id().to_string()].as_str(), + Some(site_id.as_str()) + ); + assert_eq!( + accounts_obj[&second.account_id().to_string()].as_str(), + Some(site_id.as_str()) + ); + let sites_obj = raw["value"]["sites"].as_object().unwrap(); + assert_eq!(sites_obj.len(), 1); + assert!(sites_obj.contains_key(site_id.as_str())); + + drop(server); + + let reopened = AccountStore::open(scope).await.unwrap(); + let cached = reopened.site_metadata(&site_id).await.unwrap(); + assert_eq!(cached.meta.meta.server_name.as_deref(), Some("LittleSkin")); + assert_eq!( + cached.meta.skin_domains, + vec!["textures.example.com".to_owned()] + ); + + let alice_meta = reopened + .account_site_metadata(first.account_id()) + .await + .unwrap() + .unwrap(); + let bob_meta = reopened + .account_site_metadata(second.account_id()) + .await + .unwrap() + .unwrap(); + assert_eq!(alice_meta, bob_meta); + + common::remove(&root); +} + +#[tokio::test] +async fn concurrent_refresh_site_metadata_deduplicates_http_requests() { + let entered = Arc::new(Notify::new()); + let hold = Arc::new(Notify::new()); + let server = MockYggdrasilServer::start_with_hooks( + "SingleFlight", + Some(entered.clone()), + Some(hold.clone()), + ) + .await; + + let root = common::temp_root("elemental-yggdrasil-single-flight"); + let store = Arc::new( + AccountStore::open(Scope::Directory(root.clone())) + .await + .unwrap(), + ); + let site_id = YggdrasilSiteId::new(&server.base_url).unwrap(); + + let store_a = Arc::clone(&store); + let site_a = site_id.clone(); + let task_a = tokio::spawn(async move { store_a.refresh_site_metadata(&site_a).await }); + + entered.notified().await; + + let store_b = Arc::clone(&store); + let site_b = site_id.clone(); + let task_b = tokio::spawn(async move { store_b.refresh_site_metadata(&site_b).await }); + + tokio::task::yield_now().await; + hold.notify_waiters(); + + let res_a = task_a.await.unwrap().unwrap().unwrap(); + let res_b = task_b.await.unwrap().unwrap().unwrap(); + assert_eq!(res_a.meta.meta.server_name.as_deref(), Some("SingleFlight")); + assert_eq!(res_a, res_b); + assert_eq!(server.metadata_hits(), 1); + + common::remove(&root); +} + +#[tokio::test] +async fn network_failure_preserves_cached_metadata_and_does_not_fail_refresh() { + let server = MockYggdrasilServer::start("CachedServer").await; + let root = common::temp_root("elemental-yggdrasil-fallback"); + let store = AccountStore::open(Scope::Directory(root.clone())) + .await + .unwrap(); + let site_id = YggdrasilSiteId::new(&server.base_url).unwrap(); + + let account = store + .sign_in(&YggdrasilAuthorizer::new( + server.base_url.clone(), + "Alice", + "pw", + )) + .await + .unwrap(); + + server.set_fail_metadata(true); + + let refreshed_meta = store + .refresh_site_metadata(&site_id) + .await + .unwrap() + .unwrap(); + assert_eq!( + refreshed_meta.meta.meta.server_name.as_deref(), + Some("CachedServer") + ); + + store.refresh(account.account_id()).await.unwrap(); + let still_cached = store.site_metadata(&site_id).await.unwrap(); + assert_eq!( + still_cached.meta.meta.server_name.as_deref(), + Some("CachedServer") + ); + + let missing_site = YggdrasilSiteId::new("http://127.0.0.1:9").unwrap(); + assert!( + store + .refresh_site_metadata(&missing_site) + .await + .unwrap() + .is_none() + ); + + common::remove(&root); +} + +#[tokio::test] +async fn account_site_metadata_respects_ttl_and_avoids_unnecessary_fetches() { + let server = MockYggdrasilServer::start("InitialName").await; + let root = common::temp_root("elemental-yggdrasil-ttl"); + let scope = Scope::Directory(root.clone()); + + let store = AccountStore::open(scope.clone()).await.unwrap(); + let account = store + .sign_in(&YggdrasilAuthorizer::new( + server.base_url.clone(), + "Alice", + "pw", + )) + .await + .unwrap(); + assert_eq!(server.metadata_hits(), 1); + + server.set_server_name("UpdatedName").await; + + let cached = store + .account_site_metadata(account.account_id()) + .await + .unwrap() + .unwrap(); + assert_eq!(cached.meta.meta.server_name.as_deref(), Some("InitialName")); + assert_eq!(server.metadata_hits(), 1); + + let zero_ttl_store = AccountStore::open(scope) + .await + .unwrap() + .with_site_metadata_ttl(Duration::ZERO); + let refreshed = zero_ttl_store + .account_site_metadata(account.account_id()) + .await + .unwrap() + .unwrap(); + assert_eq!( + refreshed.meta.meta.server_name.as_deref(), + Some("UpdatedName") + ); + assert_eq!(server.metadata_hits(), 2); + + common::remove(&root); +} + +#[tokio::test] +async fn legacy_account_without_site_in_index_is_backfilled() { + let server = MockYggdrasilServer::start("LegacySite").await; + let root = common::temp_root("elemental-yggdrasil-backfill"); + let scope = Scope::Directory(root.clone()); + + let store = AccountStore::open(scope.clone()).await.unwrap(); + let account = store + .sign_in(&YggdrasilAuthorizer::new( + server.base_url.clone(), + "LegacyUser", + "pw", + )) + .await + .unwrap(); + let site_id = YggdrasilSiteId::new(&server.base_url).unwrap(); + + store.remove_site_metadata(&site_id).await.unwrap(); + assert!(store.site_metadata(&site_id).await.is_none()); + + let sites_path = root + .join(".elemental") + .join("accounts") + .join("yggdrasil_sites.json"); + let mut raw: serde_json::Value = + serde_json::from_str(&std::fs::read_to_string(&sites_path).unwrap()).unwrap(); + raw["value"]["accounts"].as_object_mut().unwrap().clear(); + std::fs::write(&sites_path, serde_json::to_string(&raw).unwrap()).unwrap(); + + let reopened = AccountStore::open(scope).await.unwrap(); + + let meta = reopened + .account_site_metadata(account.account_id()) + .await + .unwrap() + .unwrap(); + assert_eq!(meta.meta.meta.server_name.as_deref(), Some("LegacySite")); + let backfilled: serde_json::Value = + serde_json::from_str(&std::fs::read_to_string(&sites_path).unwrap()).unwrap(); + assert_eq!( + backfilled["value"]["accounts"][&account.account_id().to_string()].as_str(), + Some(site_id.as_str()) + ); + + let offline = reopened + .sign_in(&OfflineAuthorizer { + username: "OfflineUser".to_owned(), + }) + .await + .unwrap(); + assert!( + reopened + .account_site_metadata(offline.account_id()) + .await + .unwrap() + .is_none() + ); + + common::remove(&root); +} + +#[tokio::test] +async fn remove_and_cleanup_methods_prune_unused_sites() { + let server_a = MockYggdrasilServer::start("SiteA").await; + let server_b = MockYggdrasilServer::start("SiteB").await; + let root = common::temp_root("elemental-yggdrasil-gc"); + let scope = Scope::Directory(root.clone()); + let store = AccountStore::open(scope).await.unwrap(); + + let site_a = YggdrasilSiteId::new(&server_a.base_url).unwrap(); + let site_b = YggdrasilSiteId::new(&server_b.base_url).unwrap(); + + let a1 = store + .sign_in(&YggdrasilAuthorizer::new( + server_a.base_url.clone(), + "A1", + "pw", + )) + .await + .unwrap(); + let a2 = store + .sign_in(&YggdrasilAuthorizer::new( + server_a.base_url.clone(), + "A2", + "pw", + )) + .await + .unwrap(); + let _b1 = store + .sign_in(&YggdrasilAuthorizer::new( + server_b.base_url.clone(), + "B1", + "pw", + )) + .await + .unwrap(); + + store.remove(a1.account_id()).await.unwrap(); + assert!(store.site_metadata(&site_a).await.is_some()); + + store.remove(a2.account_id()).await.unwrap(); + assert!(store.site_metadata(&site_a).await.is_none()); + assert!(store.site_metadata(&site_b).await.is_some()); + + let orphan_site = YggdrasilSiteId::new("https://orphan.example.com").unwrap(); + let sites_path = root + .join(".elemental") + .join("accounts") + .join("yggdrasil_sites.json"); + let mut raw: serde_json::Value = + serde_json::from_str(&std::fs::read_to_string(&sites_path).unwrap()).unwrap(); + raw["value"]["sites"][orphan_site.as_str()] = json!({ + "meta": { "serverName": "Orphan" }, + "skinDomains": [], + "signaturePublickey": "", + "fetched_at": 1 + }); + std::fs::write(&sites_path, serde_json::to_string(&raw).unwrap()).unwrap(); + + let reopened = AccountStore::open(Scope::Directory(root.clone())) + .await + .unwrap(); + assert!(reopened.site_metadata(&orphan_site).await.is_some()); + reopened.prune_unused_sites().await.unwrap(); + assert!(reopened.site_metadata(&orphan_site).await.is_none()); + assert!(reopened.site_metadata(&site_b).await.is_some()); + + reopened.clear_site_metadata().await.unwrap(); + assert!(reopened.site_metadata(&site_b).await.is_none()); + + common::remove(&root); +} + +#[tokio::test] +async fn swappable_client_updates_yggdrasil_requests_after_swap() { + let server = MockYggdrasilServer::start("SwappableSite").await; + let root = common::temp_root("elemental-yggdrasil-swappable-client"); + let client = + SwappableClient::new(HttpClientConfig::new().user_agent("elemental-test/v1")).unwrap(); + let store = AccountStore::open_with_http_client(Scope::Directory(root.clone()), client.clone()) + .await + .unwrap(); + let site_id = YggdrasilSiteId::new(&server.base_url).unwrap(); + + let authorizer = YggdrasilAuthorizer::new(server.base_url.clone(), "Alice", "pw") + .with_http_client(client.clone()); + let account = store.sign_in(&authorizer).await.unwrap(); + assert!(store.supports_textures(account.account_id()).await.unwrap()); + store.refresh(account.account_id()).await.unwrap(); + + let v1_requests = server.take_requests().await; + assert_eq!(v1_requests.len(), 4); + assert!( + v1_requests + .iter() + .any(|(m, p, _)| m == "POST" && p == "/authserver/authenticate") + ); + assert!( + v1_requests + .iter() + .any(|(m, p, _)| m == "POST" && p == "/authserver/refresh") + ); + assert!(v1_requests.iter().any(|(m, p, _)| m == "GET" && p == "/")); + assert!( + v1_requests + .iter() + .all(|(_, _, ua)| ua.as_deref() == Some("elemental-test/v1")) + ); + + client + .update(|cfg| cfg.user_agent("elemental-test/v2")) + .unwrap(); + store.refresh_site_metadata(&site_id).await.unwrap(); + store.refresh(account.account_id()).await.unwrap(); + + let v2_requests = server.take_requests().await; + assert_eq!(v2_requests.len(), 3); + assert!( + v2_requests + .iter() + .all(|(_, _, ua)| ua.as_deref() == Some("elemental-test/v2")) + ); + + common::remove(&root); +} diff --git a/crates/launchpad/src/commands.rs b/crates/launchpad/src/commands.rs index d9e5019b..a1542068 100644 --- a/crates/launchpad/src/commands.rs +++ b/crates/launchpad/src/commands.rs @@ -42,7 +42,7 @@ async fn run_launch(config: LaunchpadConfig) -> Result<()> { } .authorize() .await?; - let credential = account.credential().await?; + let credential = account.credential(); let command = launcher .build_launch_command(&prepared, &credential, &config.runtime, &config.options) .await?; From 464f0877dd202067259f5ad2485860032b90704b Mon Sep 17 00:00:00 2001 From: H2Sxxa Date: Sun, 29 Nov 2026 10:12:34 +0800 Subject: [PATCH 2/3] refactor(auth): move ms_proto to proto::ms --- crates/core/src/auth/accounts/microsoft.rs | 2 +- crates/core/src/auth/authorizers/microsoft.rs | 4 +++- crates/core/src/auth/mod.rs | 3 +-- .../src/auth/{microsoft_protocol.rs => protocol/microsoft.rs} | 0 crates/core/src/auth/protocol/mod.rs | 2 ++ crates/core/src/auth/providers/microsoft.rs | 2 +- 6 files changed, 8 insertions(+), 5 deletions(-) rename crates/core/src/auth/{microsoft_protocol.rs => protocol/microsoft.rs} (100%) create mode 100644 crates/core/src/auth/protocol/mod.rs diff --git a/crates/core/src/auth/accounts/microsoft.rs b/crates/core/src/auth/accounts/microsoft.rs index 10e33b9e..f84237cb 100644 --- a/crates/core/src/auth/accounts/microsoft.rs +++ b/crates/core/src/auth/accounts/microsoft.rs @@ -2,7 +2,7 @@ use serde::{Deserialize, Serialize}; use crate::auth::accounts::{Account, AccountId}; use crate::auth::credential::{Credential, CredentialKind}; -use crate::auth::microsoft_protocol::{ExchangedMinecraftSession, unix_now}; +use crate::auth::protocol::microsoft::{ExchangedMinecraftSession, unix_now}; const REFRESH_SKEW_SECONDS: u64 = 300; diff --git a/crates/core/src/auth/authorizers/microsoft.rs b/crates/core/src/auth/authorizers/microsoft.rs index fc5e8710..15162a7a 100644 --- a/crates/core/src/auth/authorizers/microsoft.rs +++ b/crates/core/src/auth/authorizers/microsoft.rs @@ -2,7 +2,9 @@ pub use crate::auth::accounts::microsoft::MICROSOFT_AUTHORIZER_ID; use crate::auth::accounts::microsoft::MicrosoftAccount; use crate::auth::authorizers::Authorizer; use crate::auth::error::{Error, Result}; -use crate::auth::microsoft_protocol::{exchange_microsoft_token, map_http_client_error, token_url}; +use crate::auth::protocol::microsoft::{ + exchange_microsoft_token, map_http_client_error, token_url, +}; use crate::http::SwappableClient; use oauth2::basic::BasicClient; use oauth2::{ diff --git a/crates/core/src/auth/mod.rs b/crates/core/src/auth/mod.rs index c6cb1471..7584de99 100644 --- a/crates/core/src/auth/mod.rs +++ b/crates/core/src/auth/mod.rs @@ -2,8 +2,7 @@ pub mod accounts; pub mod authorizers; pub mod credential; pub mod error; -#[cfg(feature = "microsoft-auth")] -mod microsoft_protocol; +pub mod protocol; pub mod providers; pub mod texture; diff --git a/crates/core/src/auth/microsoft_protocol.rs b/crates/core/src/auth/protocol/microsoft.rs similarity index 100% rename from crates/core/src/auth/microsoft_protocol.rs rename to crates/core/src/auth/protocol/microsoft.rs diff --git a/crates/core/src/auth/protocol/mod.rs b/crates/core/src/auth/protocol/mod.rs new file mode 100644 index 00000000..fa601e79 --- /dev/null +++ b/crates/core/src/auth/protocol/mod.rs @@ -0,0 +1,2 @@ +#[cfg(feature = "microsoft-auth")] +pub mod microsoft; diff --git a/crates/core/src/auth/providers/microsoft.rs b/crates/core/src/auth/providers/microsoft.rs index d89e9092..191c25f6 100644 --- a/crates/core/src/auth/providers/microsoft.rs +++ b/crates/core/src/auth/providers/microsoft.rs @@ -2,7 +2,7 @@ use async_trait::async_trait; use crate::auth::accounts::microsoft::{MICROSOFT_AUTHORIZER_ID, MicrosoftAccount}; use crate::auth::error::Result; -use crate::auth::microsoft_protocol::{ +use crate::auth::protocol::microsoft::{ delete_skin, minecraft_profile, profile_textures, refresh_microsoft_session, select_cape, upload_skin, }; From ec3e1cc842fecc1e432f8d181d05776022ae0b97 Mon Sep 17 00:00:00 2001 From: H2Sxxa Date: Sun, 29 Nov 2026 10:26:48 +0800 Subject: [PATCH 3/3] refactor(auth): canonicalize Yggdrasil site URLs in elemental-core Normalize YggdrasilSiteId to lowercase scheme/host without default ports, query/fragment, or trailing slashes, and share it across YggdrasilAuthorizer, YggdrasilAccountProvider, and YggdrasilSiteStore. --- crates/core/src/auth/authorizers/yggdrasil.rs | 12 ++--- crates/core/src/auth/providers/yggdrasil.rs | 47 ++++++++++++++++++- crates/launcher/src/account/sites.rs | 17 +------ .../launcher/tests/yggdrasil_site_metadata.rs | 43 +++++++++++++++-- 4 files changed, 91 insertions(+), 28 deletions(-) diff --git a/crates/core/src/auth/authorizers/yggdrasil.rs b/crates/core/src/auth/authorizers/yggdrasil.rs index ded7285e..983a4681 100644 --- a/crates/core/src/auth/authorizers/yggdrasil.rs +++ b/crates/core/src/auth/authorizers/yggdrasil.rs @@ -5,7 +5,7 @@ use crate::auth::accounts::yggdrasil::{ }; use crate::auth::authorizers::Authorizer; use crate::auth::error::{Error, Result}; -use crate::auth::providers::yggdrasil::nidhogg_client; +use crate::auth::providers::yggdrasil::{YggdrasilSiteId, nidhogg_client}; use crate::http::SwappableClient; use nidhogg::{client::Nidhogg, request::authenticate::Authenticate}; @@ -65,7 +65,11 @@ impl YggdrasilAuthorizer { let Some(base_url) = self.base_url.as_deref() else { return Ok(YggdrasilAccount::offline(self.username.clone())); }; - let base_url = normalized_base_url(base_url); + let canonical_site = YggdrasilSiteId::new(base_url); + let base_url = canonical_site + .as_ref() + .map(YggdrasilSiteId::as_str) + .unwrap_or_else(|| base_url.trim().trim_end_matches('/')); let response = self .client()? .authenticate(&Authenticate::new( @@ -99,10 +103,6 @@ impl YggdrasilAuthorizer { } } -fn normalized_base_url(base_url: &str) -> &str { - base_url.trim_end_matches('/') -} - fn account_id(base_url: &str, profile_id: &str) -> AccountId { AccountId::derive(YGGDRASIL_AUTHORIZER_ID, &format!("{base_url}:{profile_id}")) } diff --git a/crates/core/src/auth/providers/yggdrasil.rs b/crates/core/src/auth/providers/yggdrasil.rs index 0e8eae78..42374ab7 100644 --- a/crates/core/src/auth/providers/yggdrasil.rs +++ b/crates/core/src/auth/providers/yggdrasil.rs @@ -9,6 +9,9 @@ use nidhogg::{ }, }; +use reqwest::Url; +use serde::{Deserialize, Serialize}; + use crate::auth::accounts::yggdrasil::{ YGGDRASIL_AUTHORIZER_ID, YggdrasilAccount, YggdrasilProfile, preferred_language, user_id, }; @@ -19,6 +22,44 @@ use crate::auth::texture::{ }; use crate::http::SwappableClient; +/// Canonical Yggdrasil API root normalized to lowercase scheme/host, without +/// default ports, query/fragment components, or trailing slashes. +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +#[serde(transparent)] +pub struct YggdrasilSiteId(String); + +impl YggdrasilSiteId { + pub fn new(base_url: &str) -> Option { + let trimmed = base_url.trim(); + if trimmed.is_empty() { + return None; + } + let mut parsed = match Url::parse(trimmed) { + Ok(url) => url, + Err(_) if !trimmed.contains("://") => Url::parse(&format!("https://{trimmed}")).ok()?, + Err(_) => return None, + }; + if !matches!(parsed.scheme(), "http" | "https") + || !parsed.has_host() + || !parsed.username().is_empty() + || parsed.password().is_some() + { + return None; + } + parsed.set_query(None); + parsed.set_fragment(None); + let trimmed_path = parsed.path().trim_end_matches('/').to_owned(); + parsed.set_path(&trimmed_path); + + let normalized = parsed.as_str().trim_end_matches('/'); + (!normalized.is_empty()).then(|| Self(normalized.to_owned())) + } + + pub fn as_str(&self) -> &str { + &self.0 + } +} + #[derive(Debug, Clone, Default)] pub struct YggdrasilAccountProvider { http_client: SwappableClient, @@ -176,7 +217,11 @@ pub(crate) fn nidhogg_client( base_url: &str, http_client: Option<&SwappableClient>, ) -> Result { - let normalized = base_url.trim().trim_end_matches('/'); + let site = YggdrasilSiteId::new(base_url); + let normalized = site + .as_ref() + .map(YggdrasilSiteId::as_str) + .unwrap_or_else(|| base_url.trim().trim_end_matches('/')); match http_client { Some(client) => Ok(Nidhogg::with_client(normalized, client.client())), None => Nidhogg::new(normalized).map_err(|source| Error::Yggdrasil { source }), diff --git a/crates/launcher/src/account/sites.rs b/crates/launcher/src/account/sites.rs index 5fe7bd72..04dfd5c6 100644 --- a/crates/launcher/src/account/sites.rs +++ b/crates/launcher/src/account/sites.rs @@ -4,6 +4,7 @@ use std::{ time::{Duration, SystemTime, UNIX_EPOCH}, }; +pub use elemental_core::auth::providers::yggdrasil::YggdrasilSiteId; use elemental_core::{ auth::{ accounts::{AccountId, yggdrasil::Meta}, @@ -26,22 +27,6 @@ pub const DEFAULT_YGGDRASIL_SITE_METADATA_TTL: Duration = Duration::from_secs(60 const YGGDRASIL_SITE_INDEX_VERSION: usize = 1; -/// Canonical Yggdrasil API root (trimmed whitespace and trailing `/`). -#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] -#[serde(transparent)] -pub struct YggdrasilSiteId(String); - -impl YggdrasilSiteId { - pub fn new(base_url: &str) -> Option { - let normalized = base_url.trim().trim_end_matches('/'); - (!normalized.is_empty()).then(|| Self(normalized.to_owned())) - } - - pub fn as_str(&self) -> &str { - &self.0 - } -} - #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct YggdrasilSiteMetadata { #[serde(flatten)] diff --git a/crates/launcher/tests/yggdrasil_site_metadata.rs b/crates/launcher/tests/yggdrasil_site_metadata.rs index 6d1f9410..00d47001 100644 --- a/crates/launcher/tests/yggdrasil_site_metadata.rs +++ b/crates/launcher/tests/yggdrasil_site_metadata.rs @@ -249,6 +249,37 @@ async fn handle_connection(mut stream: TcpStream, state: Arc) { } } +#[test] +fn yggdrasil_site_id_normalizes_urls() { + assert_eq!( + YggdrasilSiteId::new(" HTTPS://LittleSkin.CN:443/api/yggdrasil///?x=1#frag ") + .unwrap() + .as_str(), + "https://littleskin.cn/api/yggdrasil" + ); + assert_eq!( + YggdrasilSiteId::new("littleskin.cn/api/yggdrasil/") + .unwrap() + .as_str(), + "https://littleskin.cn/api/yggdrasil" + ); + assert_eq!( + YggdrasilSiteId::new("HTTP://127.0.0.1:80/") + .unwrap() + .as_str(), + "http://127.0.0.1" + ); + assert_eq!( + YggdrasilSiteId::new("http://127.0.0.1:8080/") + .unwrap() + .as_str(), + "http://127.0.0.1:8080" + ); + assert!(YggdrasilSiteId::new(" ").is_none()); + assert!(YggdrasilSiteId::new("ftp://example.com").is_none()); + assert!(YggdrasilSiteId::new("mailto:user@example.com").is_none()); +} + #[tokio::test] async fn sign_in_persists_shared_site_metadata_and_reads_offline() { let server = MockYggdrasilServer::start("LittleSkin").await; @@ -267,12 +298,14 @@ async fn sign_in_persists_shared_site_metadata_and_reads_offline() { )) .await .unwrap(); + let noisy_url = server.base_url.replacen("http://", "HTTP://", 1) + "///?ignored=1#frag"; + let first_same_user = store + .sign_in(&YggdrasilAuthorizer::new(noisy_url.clone(), "Alice", "pw")) + .await + .unwrap(); + assert_eq!(first_same_user.account_id(), first.account_id()); let second = store - .sign_in(&YggdrasilAuthorizer::new( - server.base_url.clone(), - "Bob", - "pw", - )) + .sign_in(&YggdrasilAuthorizer::new(noisy_url, "Bob", "pw")) .await .unwrap();