feat: require verified account for offline play

This commit is contained in:
objz committed 2026-04-26 20:37:52 +02:00
1 parent de9d11e2f3
commit 33b2d856bc
4 files changed
+179 -34

No files matched your search

+29
View File
@@ -66,6 +66,12 @@ impl AccountStore {
self.accounts.iter().find(|a| a.active) 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) { pub fn set_active(&mut self, index: usize) {
for (i, acc) in self.accounts.iter_mut().enumerate() { for (i, acc) in self.accounts.iter_mut().enumerate() {
acc.active = i == index; acc.active = i == index;
@@ -194,6 +200,18 @@ mod tests {
create_offline_account(name) 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] #[test]
fn store_add_first_becomes_active() { fn store_add_first_becomes_active() {
let tmp = tempfile::tempdir().unwrap(); let tmp = tempfile::tempdir().unwrap();
@@ -234,6 +252,17 @@ mod tests {
assert!(store.active_account().is_none()); 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] #[test]
fn store_active_account_returns_active() { fn store_active_account_returns_active() {
let tmp = tempfile::tempdir().unwrap(); let tmp = tempfile::tempdir().unwrap();
+42 -11
View File
@@ -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 indirection so a mock store can be swapped in for tests
trait AccountStoreLike { trait AccountStoreLike {
fn accounts(&self) -> &[Account]; fn has_microsoft_account(&self) -> bool;
fn add_account(&mut self, account: Account); fn add_account(&mut self, account: Account);
} }
impl AccountStoreLike for AccountStore { impl AccountStoreLike for AccountStore {
fn accounts(&self) -> &[Account] { fn has_microsoft_account(&self) -> bool {
&self.accounts AccountStore::has_microsoft_account(self)
} }
fn add_account(&mut self, account: Account) { fn add_account(&mut self, account: Account) {
@@ -114,6 +114,12 @@ fn add_offline_account<T: AccountStoreLike>(store: &mut T, username: &str) -> Cl
if username.is_empty() { if username.is_empty() {
return Err(io::Error::other("offline username cannot be empty").into()); 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)); store.add_account(crate::auth::create_offline_account(username));
Ok(()) Ok(())
@@ -122,7 +128,7 @@ fn add_offline_account<T: AccountStoreLike>(store: &mut T, username: &str) -> Cl
fn delete_account(matches: &ArgMatches) -> CliResult { fn delete_account(matches: &ArgMatches) -> CliResult {
let username = required_arg(matches, "username")?; let username = required_arg(matches, "username")?;
let mut store = AccountStore::load(); 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)))?; .ok_or_else(|| io::Error::other(format!("account '{}' not found", username)))?;
if !matches.get_flag("yes") && !confirm(&format!("Delete '{}'", 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 { fn use_account(matches: &ArgMatches) -> CliResult {
let username = required_arg(matches, "username")?; let username = required_arg(matches, "username")?;
let mut store = AccountStore::load(); 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)))?; .ok_or_else(|| io::Error::other(format!("account '{}' not found", username)))?;
store.set_active(index); store.set_active(index);
println!("Active account set to '{}'.", username); println!("Active account set to '{}'.", username);
@@ -164,8 +170,10 @@ mod tests {
} }
impl AccountStoreLike for MockStore { impl AccountStoreLike for MockStore {
fn accounts(&self) -> &[Account] { fn has_microsoft_account(&self) -> bool {
&self.accounts self.accounts
.iter()
.any(|account| account.account_type == AccountType::Microsoft)
} }
fn add_account(&mut self, account: Account) { 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] #[test]
fn creates_offline_account_through_store() { fn creates_offline_account_after_microsoft_account_exists() {
let mut store = MockStore::default(); let mut store = MockStore::default();
store.add_account(microsoft_account());
add_offline_account(&mut store, "Steve").expect("offline account should be added"); add_offline_account(&mut store, "Steve").expect("offline account should be added");
assert_eq!(store.accounts.len(), 1); assert_eq!(store.accounts.len(), 2);
assert_eq!(store.accounts[0].username, "Steve"); assert_eq!(store.accounts[1].username, "Steve");
assert_eq!(store.accounts[0].account_type, AccountType::Offline); 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] #[test]
+53 -17
View File
@@ -8,6 +8,7 @@ use std::path::{Path, PathBuf};
use thiserror::Error; use thiserror::Error;
use crate::auth::{Account, AccountType};
use crate::instance::models::{InstanceConfig, ModLoader}; use crate::instance::models::{InstanceConfig, ModLoader};
#[derive(Debug, Error)] #[derive(Debug, Error)]
@@ -86,6 +87,10 @@ struct GameAuth {
user_type: String, 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 // 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 // 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. // 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()); jvm.extend(config.jvm_args.clone());
// resolve auth credentials, refreshing the microsoft token if needed. // 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 mut account_store = crate::auth::AccountStore::load();
let (mc_username, mc_uuid, mc_token, mc_user_type) = match account_store let (mc_username, mc_uuid, mc_token, mc_user_type) = match account_store
.active_account() .active_account()
.cloned() .cloned()
{ {
Some(acc) => { 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 { let (token, new_refresh, new_expires) = match acc.account_type {
crate::auth::AccountType::Microsoft => { AccountType::Microsoft => match crate::auth::refresh_and_get_token(&acc).await {
match crate::auth::refresh_and_get_token(&acc).await { Ok(triple) => triple,
Ok(triple) => triple, Err(e) => {
Err(e) => { return Err(LaunchError::Auth(format!("Authentication failed: {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 if let Some(stored) = account_store
.accounts .accounts
@@ -310,8 +317,8 @@ pub async fn launch(
} }
} }
let user_type = match acc.account_type { let user_type = match acc.account_type {
crate::auth::AccountType::Microsoft => "msa", AccountType::Microsoft => "msa",
crate::auth::AccountType::Offline => "legacy", AccountType::Offline => "legacy",
}; };
( (
acc.username.clone(), acc.username.clone(),
@@ -320,12 +327,7 @@ pub async fn launch(
user_type.to_string(), user_type.to_string(),
) )
} }
None => ( None => return Err(LaunchError::Auth("No account selected".to_owned())),
"Player".to_string(),
"00000000-0000-0000-0000-000000000000".to_string(),
"0".to_string(),
"legacy".to_string(),
),
}; };
let game_args = build_game_args( let game_args = build_game_args(
@@ -475,6 +477,7 @@ pub async fn launch(
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use crate::auth::{Account, AccountType};
use chrono::Utc; use chrono::Utc;
fn test_config() -> InstanceConfig { 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] #[test]
fn game_args_include_empty_user_properties() { fn game_args_include_empty_user_properties() {
let args = build_game_args( let args = build_game_args(
@@ -522,4 +537,25 @@ mod tests {
.any(|pair| pair == ["--tweakClass", "cpw.mods.fml.common.launcher.FMLTweaker"]) .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, &microsoft));
}
} }
+55 -6
View File
@@ -26,6 +26,7 @@ pub enum AddMode {
None, None,
ChooseType, ChooseType,
OfflineNameInput(String), OfflineNameInput(String),
OfflineBlocked,
ConfirmDelete(usize), ConfirmDelete(usize),
DeviceCodeWaiting { DeviceCodeWaiting {
info: DeviceCodeInfo, info: DeviceCodeInfo,
@@ -98,7 +99,11 @@ pub fn handle_key(key_event: &KeyEvent, state: &mut AccountState) -> bool {
true true
} }
KeyCode::Char('o') | KeyCode::Char('2') => { 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 true
} }
KeyCode::Esc => { KeyCode::Esc => {
@@ -111,13 +116,19 @@ pub fn handle_key(key_event: &KeyEvent, state: &mut AccountState) -> bool {
KeyCode::Enter => { KeyCode::Enter => {
let trimmed = name.trim().to_string(); let trimmed = name.trim().to_string();
if !trimmed.is_empty() { if !trimmed.is_empty() {
let account = auth::create_offline_account(&trimmed); if state.store.has_microsoft_account() {
state.store.add(account); let account = auth::create_offline_account(&trimmed);
if state.list_state.selected.is_none() && !state.store.accounts.is_empty() { state.store.add(account);
state.list_state.selected = Some(0); 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 true
} }
KeyCode::Char(c) => { KeyCode::Char(c) => {
@@ -138,6 +149,13 @@ pub fn handle_key(key_event: &KeyEvent, state: &mut AccountState) -> bool {
} }
_ => true, _ => true,
}, },
AddMode::OfflineBlocked => match key_event.code {
KeyCode::Enter | KeyCode::Esc => {
state.add_mode = AddMode::None;
true
}
_ => true,
},
AddMode::DeviceCodeWaiting { .. } => match key_event.code { AddMode::DeviceCodeWaiting { .. } => match key_event.code {
KeyCode::Esc => { KeyCode::Esc => {
state.add_mode = AddMode::None; 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 { match &state.add_mode {
AddMode::ChooseType => render_choose_popup(frame), AddMode::ChooseType => render_choose_popup(frame),
AddMode::OfflineNameInput(name) => render_offline_popup(frame, name), 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::ConfirmDelete(idx) => render_confirm_delete(frame, state, *idx),
AddMode::DeviceCodeWaiting { info, .. } => render_device_code_popup(frame, info), AddMode::DeviceCodeWaiting { info, .. } => render_device_code_popup(frame, info),
AddMode::None => {} AddMode::None => {}
@@ -444,6 +463,36 @@ fn render_offline_popup(frame: &mut Frame, name: &str) {
.render(area, frame.buffer_mut()); .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) { fn render_confirm_delete(frame: &mut Frame, state: &AccountState, idx: usize) {
use super::popups::{base::PopupFrame, keybind_line}; use super::popups::{base::PopupFrame, keybind_line};
let theme = THEME.as_ref(); let theme = THEME.as_ref();