diff --git a/src/auth/accounts.rs b/src/auth/accounts.rs index 5429eda..ef5eefe 100644 --- a/src/auth/accounts.rs +++ b/src/auth/accounts.rs @@ -12,6 +12,10 @@ pub struct Account { pub active: bool, #[serde(default, skip_serializing_if = "Option::is_none")] pub refresh_token: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cached_mc_token: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cached_mc_token_expires_at: Option, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] @@ -123,6 +127,8 @@ pub fn create_offline_account(username: &str) -> Account { account_type: AccountType::Offline, active: false, refresh_token: None, + cached_mc_token: None, + cached_mc_token_expires_at: None, } } @@ -185,13 +191,7 @@ mod tests { } fn dummy_account(name: &str) -> Account { - Account { - uuid: offline_uuid(name), - username: name.to_owned(), - account_type: AccountType::Offline, - active: false, - refresh_token: None, - } + create_offline_account(name) } #[test] diff --git a/src/auth/oauth.rs b/src/auth/oauth.rs index 33bc335..ab20073 100644 --- a/src/auth/oauth.rs +++ b/src/auth/oauth.rs @@ -19,6 +19,8 @@ const DEVICE_CODE_URL: &str = "https://login.microsoftonline.com/consumers/oauth const MSA_AUTHORIZE_URL: &str = "https://login.microsoftonline.com/consumers/oauth2/v2.0/authorize"; const MSA_TOKEN_URL: &str = "https://login.microsoftonline.com/consumers/oauth2/v2.0/token"; const MC_PROFILE_URL: &str = "https://api.minecraftservices.com/minecraft/profile"; +const MC_TOKEN_CACHE_TTL_SECS: i64 = 20 * 60 * 60; +const MC_TOKEN_CACHE_REFRESH_MARGIN_SECS: i64 = 5 * 60; #[derive(Debug, Clone, PartialEq)] pub struct DeviceCodeInfo { @@ -131,7 +133,7 @@ async fn exchange_and_build_account( Err(e) => return AuthResult::Error(format!("Profile parse failed: {e}")), }; - // mojang returns uuids without dashes because of course they do + // mojang returns uuids without dashes let uuid = if profile.id.len() == 32 { format!( "{}-{}-{}-{}-{}", @@ -151,15 +153,42 @@ async fn exchange_and_build_account( account_type: AccountType::Microsoft, active: false, refresh_token: ms_refresh_token.map(|s| s.to_owned()), + cached_mc_token: None, + cached_mc_token_expires_at: None, }) } -// returns (mc_access_token, new_refresh_token). for offline accounts it just -// hands back a dummy token since the server doesn't care. -pub async fn refresh_and_get_token(account: &Account) -> Result<(String, Option), String> { +fn valid_cached_mc_token(account: &Account, now: i64) -> Option<&str> { + let (Some(cached), Some(expires_at)) = ( + account.cached_mc_token.as_deref(), + account.cached_mc_token_expires_at, + ) else { + return None; + }; + + if now < expires_at - MC_TOKEN_CACHE_REFRESH_MARGIN_SECS { + Some(cached) + } else { + None + } +} + +// returns (mc_access_token, new_refresh_token, new_mc_token_expires_at). +// cached tokens return no expiry so callers don't rewrite the account store. +pub async fn refresh_and_get_token( + account: &Account, +) -> Result<(String, Option, Option), String> { match account.account_type { - AccountType::Offline => Ok(("0".to_owned(), None)), + AccountType::Offline => Ok(("0".to_owned(), None, None)), AccountType::Microsoft => { + let now = chrono::Utc::now().timestamp(); + if let Some(cached) = valid_cached_mc_token(account, now) { + tracing::info!("Using cached Minecraft token for '{}'", account.username); + return Ok((cached.to_owned(), None, None)); + } + + tracing::info!("Refreshing Minecraft token for '{}'", account.username); + let refresh = account.refresh_token.as_deref().ok_or_else(|| { format!( "No saved credentials for '{}'. Please remove and re-add the account.", @@ -192,7 +221,55 @@ pub async fn refresh_and_get_token(account: &Account) -> Result<(String, Option< .await .map_err(|e| format!("Minecraft auth failed: {e}"))?; - Ok((mc_token.access_token().as_ref().to_owned(), new_refresh)) + // minecraft-msa-auth does not expose this expiry here, so cache + // conservatively and refresh before the token gets close. + let expires_at = chrono::Utc::now().timestamp() + MC_TOKEN_CACHE_TTL_SECS; + + Ok(( + mc_token.access_token().as_ref().to_owned(), + new_refresh, + Some(expires_at), + )) } } } + +#[cfg(test)] +mod tests { + use super::*; + + fn microsoft_account(cached_mc_token_expires_at: Option) -> Account { + Account { + uuid: "00000000-0000-0000-0000-000000000000".to_owned(), + username: "TestPlayer".to_owned(), + account_type: AccountType::Microsoft, + active: true, + refresh_token: Some("refresh".to_owned()), + cached_mc_token: Some("cached".to_owned()), + cached_mc_token_expires_at, + } + } + + #[test] + fn cached_mc_token_is_valid_before_refresh_margin() { + let now = 1_000; + let account = microsoft_account(Some(now + MC_TOKEN_CACHE_REFRESH_MARGIN_SECS + 1)); + + assert_eq!(valid_cached_mc_token(&account, now), Some("cached")); + } + + #[test] + fn cached_mc_token_expires_inside_refresh_margin() { + let now = 1_000; + let account = microsoft_account(Some(now + MC_TOKEN_CACHE_REFRESH_MARGIN_SECS)); + + assert!(valid_cached_mc_token(&account, now).is_none()); + } + + #[test] + fn cached_mc_token_requires_expiry() { + let account = microsoft_account(None); + + assert!(valid_cached_mc_token(&account, 1_000).is_none()); + } +}