diff --git a/src/auth/accounts.rs b/src/auth/accounts.rs index ef5eefe..edbf7d8 100644 --- a/src/auth/accounts.rs +++ b/src/auth/accounts.rs @@ -66,6 +66,12 @@ impl AccountStore { self.accounts.iter().find(|a| a.active) } + pub fn has_microsoft_account(&self) -> bool { + self.accounts + .iter() + .any(|account| account.account_type == AccountType::Microsoft) + } + pub fn set_active(&mut self, index: usize) { for (i, acc) in self.accounts.iter_mut().enumerate() { acc.active = i == index; @@ -194,6 +200,18 @@ mod tests { create_offline_account(name) } + fn microsoft_account(name: &str) -> Account { + Account { + uuid: format!("00000000-0000-0000-0000-{:012}", name.len()), + username: name.to_owned(), + account_type: AccountType::Microsoft, + active: false, + refresh_token: Some("refresh".to_owned()), + cached_mc_token: None, + cached_mc_token_expires_at: None, + } + } + #[test] fn store_add_first_becomes_active() { let tmp = tempfile::tempdir().unwrap(); @@ -234,6 +252,17 @@ mod tests { assert!(store.active_account().is_none()); } + #[test] + fn store_has_microsoft_account_when_one_exists() { + let tmp = tempfile::tempdir().unwrap(); + let mut store = make_store(tmp.path()); + store.add(dummy_account("Offline")); + assert!(!store.has_microsoft_account()); + + store.add(microsoft_account("Owner")); + assert!(store.has_microsoft_account()); + } + #[test] fn store_active_account_returns_active() { let tmp = tempfile::tempdir().unwrap(); diff --git a/src/cli/account.rs b/src/cli/account.rs index 105d178..4e61a98 100644 --- a/src/cli/account.rs +++ b/src/cli/account.rs @@ -21,13 +21,13 @@ pub async fn handle_account(matches: &ArgMatches) -> CliResult { // trait indirection so a mock store can be swapped in for tests trait AccountStoreLike { - fn accounts(&self) -> &[Account]; + fn has_microsoft_account(&self) -> bool; fn add_account(&mut self, account: Account); } impl AccountStoreLike for AccountStore { - fn accounts(&self) -> &[Account] { - &self.accounts + fn has_microsoft_account(&self) -> bool { + AccountStore::has_microsoft_account(self) } fn add_account(&mut self, account: Account) { @@ -114,6 +114,12 @@ fn add_offline_account(store: &mut T, username: &str) -> Cl if username.is_empty() { return Err(io::Error::other("offline username cannot be empty").into()); } + if !store.has_microsoft_account() { + return Err(io::Error::other( + "add a Microsoft account that owns Minecraft before adding offline accounts", + ) + .into()); + } store.add_account(crate::auth::create_offline_account(username)); Ok(()) @@ -122,7 +128,7 @@ fn add_offline_account(store: &mut T, username: &str) -> Cl fn delete_account(matches: &ArgMatches) -> CliResult { let username = required_arg(matches, "username")?; let mut store = AccountStore::load(); - let index = find_account_index(store.accounts(), username) + let index = find_account_index(&store.accounts, username) .ok_or_else(|| io::Error::other(format!("account '{}' not found", username)))?; if !matches.get_flag("yes") && !confirm(&format!("Delete '{}'", username))? { @@ -138,7 +144,7 @@ fn delete_account(matches: &ArgMatches) -> CliResult { fn use_account(matches: &ArgMatches) -> CliResult { let username = required_arg(matches, "username")?; let mut store = AccountStore::load(); - let index = find_account_index(store.accounts(), username) + let index = find_account_index(&store.accounts, username) .ok_or_else(|| io::Error::other(format!("account '{}' not found", username)))?; store.set_active(index); println!("Active account set to '{}'.", username); @@ -164,8 +170,10 @@ mod tests { } impl AccountStoreLike for MockStore { - fn accounts(&self) -> &[Account] { - &self.accounts + fn has_microsoft_account(&self) -> bool { + self.accounts + .iter() + .any(|account| account.account_type == AccountType::Microsoft) } fn add_account(&mut self, account: Account) { @@ -173,14 +181,37 @@ mod tests { } } + fn microsoft_account() -> Account { + Account { + uuid: "00000000-0000-0000-0000-000000000001".to_owned(), + username: "Owner".to_owned(), + account_type: AccountType::Microsoft, + active: false, + refresh_token: Some("refresh".to_owned()), + cached_mc_token: None, + cached_mc_token_expires_at: None, + } + } + #[test] - fn creates_offline_account_through_store() { + fn creates_offline_account_after_microsoft_account_exists() { let mut store = MockStore::default(); + store.add_account(microsoft_account()); add_offline_account(&mut store, "Steve").expect("offline account should be added"); - assert_eq!(store.accounts.len(), 1); - assert_eq!(store.accounts[0].username, "Steve"); - assert_eq!(store.accounts[0].account_type, AccountType::Offline); + assert_eq!(store.accounts.len(), 2); + assert_eq!(store.accounts[1].username, "Steve"); + assert_eq!(store.accounts[1].account_type, AccountType::Offline); + } + + #[test] + fn rejects_offline_account_before_microsoft_account_exists() { + let mut store = MockStore::default(); + let err = add_offline_account(&mut store, "Steve") + .expect_err("offline account should require a microsoft account"); + + assert!(err.to_string().contains("Microsoft account")); + assert!(store.accounts.is_empty()); } #[test] diff --git a/src/instance/launch/mod.rs b/src/instance/launch/mod.rs index e3b1dd3..5fa9483 100644 --- a/src/instance/launch/mod.rs +++ b/src/instance/launch/mod.rs @@ -8,6 +8,7 @@ use std::path::{Path, PathBuf}; use thiserror::Error; +use crate::auth::{Account, AccountType}; use crate::instance::models::{InstanceConfig, ModLoader}; #[derive(Debug, Error)] @@ -86,6 +87,10 @@ struct GameAuth { user_type: String, } +fn account_can_launch(has_microsoft_account: bool, account: &Account) -> bool { + account.account_type == AccountType::Microsoft || has_microsoft_account +} + // mojang's library rules are a fun little state machine: each rule can allow // or disallow based on OS. if no rule matches the current OS, the library is // included only if no rule "dominated" (matched at all). yes, it's weird. @@ -272,23 +277,25 @@ pub async fn launch( jvm.extend(config.jvm_args.clone()); // resolve auth credentials, refreshing the microsoft token if needed. - // falls back to a generic offline player if no account is configured. let mut account_store = crate::auth::AccountStore::load(); let (mc_username, mc_uuid, mc_token, mc_user_type) = match account_store .active_account() .cloned() { Some(acc) => { + if !account_can_launch(account_store.has_microsoft_account(), &acc) { + return Err(LaunchError::Auth( + "Offline accounts require a Microsoft account that owns Minecraft".to_owned(), + )); + } let (token, new_refresh, new_expires) = match acc.account_type { - crate::auth::AccountType::Microsoft => { - match crate::auth::refresh_and_get_token(&acc).await { - Ok(triple) => triple, - Err(e) => { - return Err(LaunchError::Auth(format!("Authentication failed: {e}"))); - } + AccountType::Microsoft => match crate::auth::refresh_and_get_token(&acc).await { + Ok(triple) => triple, + Err(e) => { + return Err(LaunchError::Auth(format!("Authentication failed: {e}"))); } - } - crate::auth::AccountType::Offline => ("0".to_string(), None, None), + }, + AccountType::Offline => ("0".to_string(), None, None), }; if let Some(stored) = account_store .accounts @@ -310,8 +317,8 @@ pub async fn launch( } } let user_type = match acc.account_type { - crate::auth::AccountType::Microsoft => "msa", - crate::auth::AccountType::Offline => "legacy", + AccountType::Microsoft => "msa", + AccountType::Offline => "legacy", }; ( acc.username.clone(), @@ -320,12 +327,7 @@ pub async fn launch( user_type.to_string(), ) } - None => ( - "Player".to_string(), - "00000000-0000-0000-0000-000000000000".to_string(), - "0".to_string(), - "legacy".to_string(), - ), + None => return Err(LaunchError::Auth("No account selected".to_owned())), }; let game_args = build_game_args( @@ -475,6 +477,7 @@ pub async fn launch( #[cfg(test)] mod tests { use super::*; + use crate::auth::{Account, AccountType}; use chrono::Utc; fn test_config() -> InstanceConfig { @@ -493,6 +496,18 @@ mod tests { } } + fn test_account(account_type: AccountType) -> Account { + Account { + uuid: "00000000-0000-0000-0000-000000000001".to_owned(), + username: "TestPlayer".to_owned(), + account_type, + active: true, + refresh_token: Some("refresh".to_owned()), + cached_mc_token: None, + cached_mc_token_expires_at: None, + } + } + #[test] fn game_args_include_empty_user_properties() { let args = build_game_args( @@ -522,4 +537,25 @@ mod tests { .any(|pair| pair == ["--tweakClass", "cpw.mods.fml.common.launcher.FMLTweaker"]) ); } + + #[test] + fn offline_account_cannot_launch_without_microsoft_account() { + let offline = test_account(AccountType::Offline); + + assert!(!account_can_launch(false, &offline)); + } + + #[test] + fn offline_account_can_launch_with_microsoft_account() { + let offline = test_account(AccountType::Offline); + + assert!(account_can_launch(true, &offline)); + } + + #[test] + fn microsoft_account_can_launch_without_offline_gate() { + let microsoft = test_account(AccountType::Microsoft); + + assert!(account_can_launch(false, µsoft)); + } } diff --git a/src/tui/widgets/account.rs b/src/tui/widgets/account.rs index 3771bdf..82af198 100644 --- a/src/tui/widgets/account.rs +++ b/src/tui/widgets/account.rs @@ -26,6 +26,7 @@ pub enum AddMode { None, ChooseType, OfflineNameInput(String), + OfflineBlocked, ConfirmDelete(usize), DeviceCodeWaiting { info: DeviceCodeInfo, @@ -98,7 +99,11 @@ pub fn handle_key(key_event: &KeyEvent, state: &mut AccountState) -> bool { true } KeyCode::Char('o') | KeyCode::Char('2') => { - state.add_mode = AddMode::OfflineNameInput(String::new()); + state.add_mode = if state.store.has_microsoft_account() { + AddMode::OfflineNameInput(String::new()) + } else { + AddMode::OfflineBlocked + }; true } KeyCode::Esc => { @@ -111,13 +116,19 @@ pub fn handle_key(key_event: &KeyEvent, state: &mut AccountState) -> bool { KeyCode::Enter => { let trimmed = name.trim().to_string(); if !trimmed.is_empty() { - let account = auth::create_offline_account(&trimmed); - state.store.add(account); - if state.list_state.selected.is_none() && !state.store.accounts.is_empty() { - state.list_state.selected = Some(0); + if state.store.has_microsoft_account() { + let account = auth::create_offline_account(&trimmed); + state.store.add(account); + if state.list_state.selected.is_none() && !state.store.accounts.is_empty() { + state.list_state.selected = Some(0); + } + state.add_mode = AddMode::None; + } else { + state.add_mode = AddMode::OfflineBlocked; } + } else { + state.add_mode = AddMode::None; } - state.add_mode = AddMode::None; true } KeyCode::Char(c) => { @@ -138,6 +149,13 @@ pub fn handle_key(key_event: &KeyEvent, state: &mut AccountState) -> bool { } _ => true, }, + AddMode::OfflineBlocked => match key_event.code { + KeyCode::Enter | KeyCode::Esc => { + state.add_mode = AddMode::None; + true + } + _ => true, + }, AddMode::DeviceCodeWaiting { .. } => match key_event.code { KeyCode::Esc => { state.add_mode = AddMode::None; @@ -257,6 +275,7 @@ pub fn render(frame: &mut Frame, area: Rect, focused: FocusedArea, state: &mut A match &state.add_mode { AddMode::ChooseType => render_choose_popup(frame), AddMode::OfflineNameInput(name) => render_offline_popup(frame, name), + AddMode::OfflineBlocked => render_offline_blocked_popup(frame), AddMode::ConfirmDelete(idx) => render_confirm_delete(frame, state, *idx), AddMode::DeviceCodeWaiting { info, .. } => render_device_code_popup(frame, info), AddMode::None => {} @@ -444,6 +463,36 @@ fn render_offline_popup(frame: &mut Frame, name: &str) { .render(area, frame.buffer_mut()); } +fn render_offline_blocked_popup(frame: &mut Frame) { + use super::popups::{base::PopupFrame, keybind_line}; + let theme = THEME.as_ref(); + let area = popup_area(frame, 58, 5); + + let border_color = theme.text_dim(); + let bg_color = theme.surface(); + let text_color = theme.text(); + + PopupFrame { + title: Line::from(Span::styled( + " Offline Account ", + Style::default() + .fg(border_color) + .add_modifier(Modifier::BOLD), + )) + .centered(), + border_color, + bg: Some(bg_color), + keybinds: Some(keybind_line(&[("Enter", " close")])), + search_line: None, + content: Box::new(move |inner, buf| { + Paragraph::new("Add a Microsoft account that owns Minecraft first.") + .style(Style::default().fg(text_color)) + .render(inner, buf); + }), + } + .render(area, frame.buffer_mut()); +} + fn render_confirm_delete(frame: &mut Frame, state: &AccountState, idx: usize) { use super::popups::{base::PopupFrame, keybind_line}; let theme = THEME.as_ref();