diff --git a/launcher/Cargo.lock b/launcher/Cargo.lock index 8d80f615c..39972745d 100644 --- a/launcher/Cargo.lock +++ b/launcher/Cargo.lock @@ -2570,10 +2570,14 @@ dependencies = [ "clap", "dirs 5.0.1", "flate2", + "futures-lite 2.6.1", + "getrandom 0.3.4", "gpui", "horizon-prepare", "horizon-theme", "image", + "keyring", + "oo7", "pulldown-cmark", "self-replace", "serde", @@ -2992,6 +2996,20 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "keyring" +version = "3.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eebcc3aff044e5944a8fbaf69eb277d11986064cba30c468730e8b9909fb551c" +dependencies = [ + "byteorder", + "log", + "security-framework 2.11.1", + "security-framework 3.7.0", + "windows-sys 0.60.2", + "zeroize", +] + [[package]] name = "khronos-egl" version = "6.0.0" @@ -4645,7 +4663,7 @@ dependencies = [ "openssl-probe", "rustls-pki-types", "schannel", - "security-framework", + "security-framework 3.7.0", ] [[package]] @@ -4810,6 +4828,19 @@ version = "4.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1c107b6f4780854c8b126e228ea8869f4d7b71260f962fefb57b996b8959ba6b" +[[package]] +name = "security-framework" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "897b2245f0b511c87893af39b033e5ca9cce68824c4d7e7630b5a1d339658d02" +dependencies = [ + "bitflags 2.13.2", + "core-foundation 0.9.4", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + [[package]] name = "security-framework" version = "3.7.0" @@ -6665,6 +6696,15 @@ dependencies = [ "windows-targets 0.52.6", ] +[[package]] +name = "windows-sys" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb" +dependencies = [ + "windows-targets 0.53.5", +] + [[package]] name = "windows-sys" version = "0.61.2" diff --git a/launcher/Cargo.toml b/launcher/Cargo.toml index ef74e59a0..1d2e259df 100644 --- a/launcher/Cargo.toml +++ b/launcher/Cargo.toml @@ -22,6 +22,18 @@ image = { version = "0.25", default-features = false, features = ["jpeg"] } clap = { version = "4", features = ["derive"] } horizon-theme = { path = "../crates/horizon-theme" } horizon-prepare = { path = "../crates/horizon-prepare" } +# The session file's random name. +getrandom = "0.3" + +# Microsoft account secrets in the OS keychain: the Secret Service on Linux through oo7 (the same +# build gpui uses), Keychain and Credential Manager through keyring. +[target.'cfg(any(target_os = "linux", target_os = "freebsd"))'.dependencies] +oo7 = { version = "0.5", default-features = false, features = ["async-std", "native_crypto"] } +futures-lite = "2" +[target.'cfg(target_os = "macos")'.dependencies] +keyring = { version = "3", features = ["apple-native"] } +[target.'cfg(target_os = "windows")'.dependencies] +keyring = { version = "3", features = ["windows-native"] } [profile.release] strip = true diff --git a/launcher/src/account.rs b/launcher/src/account.rs new file mode 100644 index 000000000..e64141646 --- /dev/null +++ b/launcher/src/account.rs @@ -0,0 +1,815 @@ +//! Microsoft account sign-in (docs/microsoft-account.md): the OAuth device-code flow, then Xbox +//! Live, XSTS and the Minecraft services, the game ownership check and the profile. Secrets (the +//! Microsoft refresh token, the Minecraft access token) live in the OS keychain; accounts.json +//! keeps only names and UUIDs. The game gets the session in a file it reads once +//! (`--session-file`), never on its command line. Tokens never reach logs, errors or output. +//! +//! The Azure app (client ID) is Horizon's own and is configuration: `HORIZON_MSA_CLIENT_ID` at +//! build time, or at run time to override it. Without one, sign-in says it is not configured. +use serde_json::{json, Value}; +use std::collections::HashMap; +use std::path::{Path, PathBuf}; +use std::sync::{Mutex, OnceLock}; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +/// The keychain service name every secret is stored under. +pub const SERVICE: &str = "dev.playhorizon.launcher"; +const SCOPE: &str = "XboxLive.signin offline_access"; +pub const NOT_CONFIGURED: &str = + "Microsoft sign-in is not configured yet in this build of the launcher (no client ID)."; +const SIGN_IN_AGAIN: &str = "Your Microsoft sign-in expired. Sign in again."; +/// The Minecraft token is renewed when it has less than this left. +const RENEW_BEFORE: u64 = 3600; + +/// The configured Azure app, if any: the run-time variable wins over the build-time one, and an +/// empty value means none. +pub fn client_id() -> Option { + std::env::var("HORIZON_MSA_CLIENT_ID") + .ok() + .or_else(|| option_env!("HORIZON_MSA_CLIENT_ID").map(str::to_owned)) + .map(|id| id.trim().to_owned()) + .filter(|id| !id.is_empty()) +} + +/// Where the requests go: the real services, or a mock in tests. +#[derive(Clone, Debug)] +pub struct Endpoints { + /// The OAuth 2.0 v2 endpoints for personal accounts (`…/devicecode`, `…/token`). + pub microsoft: String, + pub xbox_user: String, + pub xsts: String, + /// api.minecraftservices.com. + pub minecraft: String, +} + +impl Endpoints { + pub fn live() -> Self { + Self { + microsoft: "https://login.microsoftonline.com/consumers/oauth2/v2.0".into(), + xbox_user: "https://user.auth.xboxlive.com/user/authenticate".into(), + xsts: "https://xsts.auth.xboxlive.com/xsts/authorize".into(), + minecraft: "https://api.minecraftservices.com".into(), + } + } +} + +fn agent() -> ureq::Agent { + ureq::AgentBuilder::new() + .timeout(Duration::from_secs(20)) + .user_agent(concat!("horizon-launcher/", env!("CARGO_PKG_VERSION"))) + .build() +} + +/// One request's result: the status and the JSON body (empty when there is none). Transport +/// errors name the service, never the URL's query or the request. +fn send(request: ureq::Request, body: Option, service: &str) -> Result<(u16, Value), String> { + let result = match body { + None => request.call(), + Some(Body::Form(fields)) => request.send_form(&fields), + Some(Body::Json(value)) => request.set("Accept", "application/json").send_json(value), + }; + let response = match result { + Ok(r) => r, + Err(ureq::Error::Status(_, r)) => r, + Err(ureq::Error::Transport(_)) => { + return Err(format!( + "Could not reach {service}. Check your internet connection." + )) + } + }; + let status = response.status(); + let text = response.into_string().unwrap_or_default(); + Ok((status, serde_json::from_str(&text).unwrap_or(Value::Null))) +} + +enum Body<'a> { + Form(Vec<(&'a str, &'a str)>), + Json(Value), +} + +fn str_field(v: &Value, key: &str) -> Option { + v.get(key).and_then(Value::as_str).map(str::to_owned) +} + +fn now() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_or(0, |d| d.as_secs()) +} + +// ----- The device-code flow ---------------------------------------------------------------------- + +/// What the player types at the verification page. +#[derive(Clone)] +pub struct DeviceCode { + pub user_code: String, + pub verification_uri: String, + pub interval: u64, + pub expires_at: u64, + device_code: String, +} + +impl std::fmt::Debug for DeviceCode { + // The device code can be traded for tokens once the player approves: never shown. + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("DeviceCode") + .field("user_code", &self.user_code) + .field("verification_uri", &self.verification_uri) + .finish_non_exhaustive() + } +} + +/// The Microsoft tokens; the access token only lasts for the Xbox step. +pub struct MsTokens { + access: String, + refresh: String, +} + +impl std::fmt::Debug for MsTokens { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("MsTokens()") + } +} + +pub enum Poll { + Pending, + /// The server asked to poll less often: wait 5 s more. + SlowDown, + Done(MsTokens), +} + +pub fn device_code(ep: &Endpoints, client_id: &str) -> Result { + let (status, v) = send( + agent().post(&format!("{}/devicecode", ep.microsoft)), + Some(Body::Form(vec![("client_id", client_id), ("scope", SCOPE)])), + "Microsoft", + )?; + match ( + status, + str_field(&v, "user_code"), + str_field(&v, "device_code"), + ) { + (200, Some(user_code), Some(device_code)) => Ok(DeviceCode { + user_code, + verification_uri: str_field(&v, "verification_uri") + .unwrap_or_else(|| "https://www.microsoft.com/link".into()), + interval: v + .get("interval") + .and_then(Value::as_u64) + .unwrap_or(5) + .max(1), + expires_at: now() + v.get("expires_in").and_then(Value::as_u64).unwrap_or(900), + device_code, + }), + _ => Err(oauth_error(&v)), + } +} + +/// The OAuth error codes as messages for the player. +fn oauth_error(v: &Value) -> String { + match v.get("error").and_then(Value::as_str) { + Some("authorization_declined") => "Sign-in was declined in the browser.".into(), + Some("expired_token") => "The sign-in code expired. Start again.".into(), + Some("bad_verification_code") => "The sign-in code was not recognised. Start again.".into(), + Some("invalid_grant") => SIGN_IN_AGAIN.into(), + Some("invalid_client" | "unauthorized_client") => { + "Microsoft refused this launcher's app registration (client ID).".into() + } + Some(other) => format!("Microsoft sign-in failed ({other})."), + None => "Microsoft sign-in failed.".into(), + } +} + +/// One poll of the token endpoint while the player signs in. +pub fn poll(ep: &Endpoints, client_id: &str, code: &DeviceCode) -> Result { + let (status, v) = send( + agent().post(&format!("{}/token", ep.microsoft)), + Some(Body::Form(vec![ + ("grant_type", "urn:ietf:params:oauth:grant-type:device_code"), + ("client_id", client_id), + ("device_code", &code.device_code), + ])), + "Microsoft", + )?; + match v.get("error").and_then(Value::as_str) { + Some("authorization_pending") => return Ok(Poll::Pending), + Some("slow_down") => return Ok(Poll::SlowDown), + _ => {} + } + ms_tokens(status, &v).map(Poll::Done) +} + +fn ms_tokens(status: u16, v: &Value) -> Result { + match ( + status, + str_field(v, "access_token"), + str_field(v, "refresh_token"), + ) { + (200, Some(access), Some(refresh)) => Ok(MsTokens { access, refresh }), + _ => Err(oauth_error(v)), + } +} + +/// Wait for the player to finish in the browser, polling as asked, until the code expires or +/// `cancelled` says stop. +pub fn wait_for_sign_in( + ep: &Endpoints, + client_id: &str, + code: &DeviceCode, + cancelled: &dyn Fn() -> bool, +) -> Result { + let mut interval = code.interval; + loop { + let until = std::time::Instant::now() + Duration::from_secs(interval); + while std::time::Instant::now() < until { + if cancelled() { + return Err("Sign-in cancelled.".into()); + } + std::thread::sleep(Duration::from_millis(100)); + } + if now() > code.expires_at { + return Err("The sign-in code expired. Start again.".into()); + } + match poll(ep, client_id, code)? { + Poll::Pending => {} + Poll::SlowDown => interval += 5, + Poll::Done(tokens) => return Ok(tokens), + } + } +} + +fn refresh_ms(ep: &Endpoints, client_id: &str, refresh: &str) -> Result { + let (status, v) = send( + agent().post(&format!("{}/token", ep.microsoft)), + Some(Body::Form(vec![ + ("grant_type", "refresh_token"), + ("client_id", client_id), + ("refresh_token", refresh), + ("scope", SCOPE), + ])), + "Microsoft", + )?; + ms_tokens(status, &v) +} + +// ----- Xbox Live, XSTS, Minecraft ---------------------------------------------------------------- + +/// The XSTS `XErr` codes, as the official launcher explains them. +fn xsts_error(code: u64) -> String { + match code { + 2148916233 => "This Microsoft account has no Xbox profile yet. Sign in once at xbox.com to create one, then try again.".into(), + 2148916235 => "Xbox Live is not available in your country or region.".into(), + 2148916236 | 2148916237 => "This account needs adult verification on xbox.com before it can play.".into(), + 2148916238 => "This is a child account: an adult has to add it to a Microsoft family first.".into(), + other => format!("Xbox Live refused the sign-in (error {other})."), + } +} + +/// The Minecraft access token from the Microsoft one, through Xbox Live and XSTS. +struct Minecraft { + token: String, + expires_at: u64, + xuid: Option, +} + +fn minecraft_login(ep: &Endpoints, ms_access: &str) -> Result { + let (status, xbl) = send( + agent().post(&ep.xbox_user), + Some(Body::Json(json!({ + "Properties": { + "AuthMethod": "RPS", + "SiteName": "user.auth.xboxlive.com", + "RpsTicket": format!("d={ms_access}"), + }, + "RelyingParty": "http://auth.xboxlive.com", + "TokenType": "JWT", + }))), + "Xbox Live", + )?; + let xbl_token = str_field(&xbl, "Token") + .filter(|_| status == 200) + .ok_or("Xbox Live refused the sign-in.")?; + let (status, xsts) = send( + agent().post(&ep.xsts), + Some(Body::Json(json!({ + "Properties": { "SandboxId": "RETAIL", "UserTokens": [xbl_token] }, + "RelyingParty": "rp://api.minecraftservices.com/", + "TokenType": "JWT", + }))), + "Xbox Live", + )?; + if let Some(code) = xsts.get("XErr").and_then(Value::as_u64) { + return Err(xsts_error(code)); + } + let claims = xsts.pointer("/DisplayClaims/xui/0"); + let (Some(xsts_token), Some(uhs)) = ( + str_field(&xsts, "Token").filter(|_| status == 200), + claims.and_then(|c| str_field(c, "uhs")), + ) else { + return Err("Xbox Live refused the sign-in.".into()); + }; + let xuid = claims.and_then(|c| str_field(c, "xid")); + let (status, mc) = send( + agent().post(&format!("{}/authentication/login_with_xbox", ep.minecraft)), + Some(Body::Json( + json!({ "identityToken": format!("XBL3.0 x={uhs};{xsts_token}") }), + )), + "the Minecraft services", + )?; + match (status, str_field(&mc, "access_token")) { + (200, Some(token)) => Ok(Minecraft { + token, + expires_at: now() + + mc.get("expires_in") + .and_then(Value::as_u64) + .unwrap_or(86400), + xuid, + }), + // New Azure apps are refused until Mojang approves them (Minecraft API access). + (403, _) => Err( + "The Minecraft services refused this launcher: its app is not approved by Mojang yet." + .into(), + ), + (429, _) => Err("Too many sign-ins in a short time. Wait a minute and try again.".into()), + _ => Err("The Minecraft services refused the sign-in.".into()), + } +} + +fn bearer(request: ureq::Request, token: &str) -> ureq::Request { + request.set("Authorization", &format!("Bearer {token}")) +} + +/// Whether the account owns Minecraft: Java Edition (Game Pass included). +fn owns_game(ep: &Endpoints, token: &str) -> Result { + let (status, v) = send( + bearer( + agent().get(&format!("{}/entitlements/mcstore", ep.minecraft)), + token, + ), + None, + "the Minecraft services", + )?; + if status != 200 { + return Err("Could not check which games this account owns.".into()); + } + Ok(v.get("items") + .and_then(Value::as_array) + .is_some_and(|items| { + items.iter().any(|i| { + matches!( + i.get("name").and_then(Value::as_str), + Some("game_minecraft" | "product_minecraft") + ) + }) + })) +} + +/// A Minecraft profile, as the launcher shows and remembers it (no secrets). +#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)] +pub struct Account { + /// The profile UUID without dashes. + pub uuid: String, + pub name: String, + /// The active skin's URL (textures.minecraft.net) and model ("classic" or "slim"). + #[serde(default)] + pub skin: Option<(String, String)>, + #[serde(default)] + pub cape: Option, +} + +fn profile(ep: &Endpoints, token: &str) -> Result { + let (status, v) = send( + bearer( + agent().get(&format!("{}/minecraft/profile", ep.minecraft)), + token, + ), + None, + "the Minecraft services", + )?; + if status == 404 { + return Err("This account has no Minecraft profile yet. Create one at minecraft.net, then sign in again.".into()); + } + let (Some(uuid), Some(name)) = (str_field(&v, "id"), str_field(&v, "name")) else { + return Err("Could not read the Minecraft profile.".into()); + }; + let active = |key: &str| { + v.get(key) + .and_then(Value::as_array) + .and_then(|list| { + list.iter() + .find(|s| s.get("state").and_then(Value::as_str) == Some("ACTIVE")) + }) + .cloned() + }; + Ok(Account { + uuid: uuid.replace('-', "").to_lowercase(), + name, + skin: active("skins").and_then(|s| { + Some(( + str_field(&s, "url")?, + str_field(&s, "variant") + .unwrap_or_else(|| "CLASSIC".into()) + .to_lowercase(), + )) + }), + cape: active("capes").and_then(|c| str_field(&c, "url")), + }) +} + +/// What the keychain keeps for one account. +#[derive(Clone, serde::Serialize, serde::Deserialize)] +pub struct Secrets { + refresh_token: String, + minecraft_token: String, + minecraft_expires_at: u64, + #[serde(default)] + xuid: Option, +} +impl std::fmt::Debug for Secrets { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("Secrets()") + } +} + +/// From Microsoft tokens to a ready account: Xbox, XSTS, Minecraft, ownership, profile. +pub fn finish_sign_in(ep: &Endpoints, ms: MsTokens) -> Result<(Account, Secrets), String> { + let mc = minecraft_login(ep, &ms.access)?; + if !owns_game(ep, &mc.token)? { + return Err("This account doesn't own Minecraft: Java Edition.".into()); + } + let account = profile(ep, &mc.token)?; + Ok(( + account, + Secrets { + refresh_token: ms.refresh, + minecraft_token: mc.token, + minecraft_expires_at: mc.expires_at, + xuid: mc.xuid, + }, + )) +} + +/// A Minecraft token with at least an hour left, renewed through the refresh token if needed. +/// The profile is read again on renewal (the name may have changed). +pub fn fresh( + ep: &Endpoints, + client_id: &str, + account: &Account, + secrets: Secrets, +) -> Result<(Account, Secrets), String> { + if secrets.minecraft_expires_at > now() + RENEW_BEFORE { + return Ok((account.clone(), secrets)); + } + let ms = refresh_ms(ep, client_id, &secrets.refresh_token)?; + let (renewed, secrets) = finish_sign_in(ep, ms)?; + if renewed.uuid != account.uuid { + return Err( + "The Microsoft account now has another Minecraft profile. Sign in again.".into(), + ); + } + Ok((renewed, secrets)) +} + +// ----- The keychain -------------------------------------------------------------------------------- + +/// Where secrets are kept: the OS keychain, or memory in tests and when there is none. +pub trait SecretStore: Send + Sync { + fn get(&self, key: &str) -> Result, String>; + fn set(&self, key: &str, secret: &str) -> Result<(), String>; + fn delete(&self, key: &str) -> Result<(), String>; + /// False for memory: secrets are gone when the launcher closes. + fn persistent(&self) -> bool; +} + +#[derive(Default)] +pub struct MemoryStore(Mutex>); +impl SecretStore for MemoryStore { + fn get(&self, key: &str) -> Result, String> { + Ok(self.0.lock().unwrap().get(key).cloned()) + } + fn set(&self, key: &str, secret: &str) -> Result<(), String> { + self.0.lock().unwrap().insert(key.into(), secret.into()); + Ok(()) + } + fn delete(&self, key: &str) -> Result<(), String> { + self.0.lock().unwrap().remove(key); + Ok(()) + } + fn persistent(&self) -> bool { + false + } +} + +/// The Secret Service (GNOME Keyring, KWallet) through oo7, as gpui itself uses it. +#[cfg(any(target_os = "linux", target_os = "freebsd"))] +pub struct SystemStore; +#[cfg(any(target_os = "linux", target_os = "freebsd"))] +impl SystemStore { + fn keyring() -> Result { + futures_lite::future::block_on(async { + let keyring = oo7::Keyring::new().await.map_err(|e| e.to_string())?; + keyring.unlock().await.map_err(|e| e.to_string())?; + Ok(keyring) + }) + } +} +#[cfg(any(target_os = "linux", target_os = "freebsd"))] +impl SecretStore for SystemStore { + fn get(&self, key: &str) -> Result, String> { + let keyring = Self::keyring()?; + futures_lite::future::block_on(async { + let attributes = vec![("service", SERVICE), ("account", key)]; + let items = keyring + .search_items(&attributes) + .await + .map_err(|e| e.to_string())?; + let Some(item) = items.into_iter().next() else { + return Ok(None); + }; + item.unlock().await.map_err(|e| e.to_string())?; + let secret = item.secret().await.map_err(|e| e.to_string())?; + Ok(String::from_utf8(secret.to_vec()).ok()) + }) + } + fn set(&self, key: &str, secret: &str) -> Result<(), String> { + let keyring = Self::keyring()?; + futures_lite::future::block_on(async { + let attributes = vec![("service", SERVICE), ("account", key)]; + keyring + .create_item( + "Horizon launcher: Minecraft account", + &attributes, + secret.as_bytes(), + true, + ) + .await + .map_err(|e| e.to_string()) + }) + } + fn delete(&self, key: &str) -> Result<(), String> { + let keyring = Self::keyring()?; + futures_lite::future::block_on(async { + let attributes = vec![("service", SERVICE), ("account", key)]; + keyring.delete(&attributes).await.map_err(|e| e.to_string()) + }) + } + fn persistent(&self) -> bool { + true + } +} + +/// Keychain on macOS, Credential Manager on Windows (the keyring crate). +#[cfg(any(target_os = "macos", target_os = "windows"))] +pub struct SystemStore; +#[cfg(any(target_os = "macos", target_os = "windows"))] +impl SecretStore for SystemStore { + fn get(&self, key: &str) -> Result, String> { + match keyring::Entry::new(SERVICE, key).and_then(|e| e.get_password()) { + Ok(secret) => Ok(Some(secret)), + Err(keyring::Error::NoEntry) => Ok(None), + Err(e) => Err(e.to_string()), + } + } + fn set(&self, key: &str, secret: &str) -> Result<(), String> { + keyring::Entry::new(SERVICE, key) + .and_then(|e| e.set_password(secret)) + .map_err(|e| e.to_string()) + } + fn delete(&self, key: &str) -> Result<(), String> { + match keyring::Entry::new(SERVICE, key).and_then(|e| e.delete_credential()) { + Ok(()) | Err(keyring::Error::NoEntry) => Ok(()), + Err(e) => Err(e.to_string()), + } + } + fn persistent(&self) -> bool { + true + } +} + +pub const NO_KEYCHAIN: &str = "No keychain available: you are signed in until the launcher closes, then you will have to sign in again."; + +/// The keychain if it answers, else memory for this run (said once in the UI with NO_KEYCHAIN). +pub fn store() -> &'static dyn SecretStore { + static STORE: OnceLock> = OnceLock::new(); + STORE + .get_or_init(|| { + #[cfg(any( + target_os = "linux", + target_os = "freebsd", + target_os = "macos", + target_os = "windows" + ))] + if std::env::var_os("HORIZON_NO_KEYCHAIN").is_none() && SystemStore.get("probe").is_ok() + { + return Box::new(SystemStore); + } + Box::::default() + }) + .as_ref() +} + +// ----- Accounts ------------------------------------------------------------------------------------ + +/// accounts.json: the signed-in accounts and the one that plays. Never a token. +#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)] +pub struct Accounts { + pub accounts: Vec, + /// The UUID of the account the game starts with; none plays offline. + pub selected: Option, +} + +impl Accounts { + fn path() -> PathBuf { + crate::backend::data_dir().join("accounts.json") + } + pub fn load() -> Self { + std::fs::read_to_string(Self::path()) + .ok() + .and_then(|t| serde_json::from_str(&t).ok()) + .unwrap_or_default() + } + pub fn save(&self) -> Result<(), String> { + let path = Self::path(); + if let Some(dir) = path.parent() { + std::fs::create_dir_all(dir).map_err(|e| e.to_string())?; + } + let text = serde_json::to_string_pretty(self).map_err(|e| e.to_string())?; + std::fs::write(path, text + "\n").map_err(|e| e.to_string()) + } + pub fn selected(&self) -> Option<&Account> { + let uuid = self.selected.as_ref()?; + self.accounts.iter().find(|a| &a.uuid == uuid) + } + /// Find an account by name (any case) or UUID (with or without dashes). + pub fn find(&self, who: &str) -> Option<&Account> { + let undashed = who.replace('-', "").to_lowercase(); + self.accounts + .iter() + .find(|a| a.name.eq_ignore_ascii_case(who) || a.uuid == undashed) + } + /// Keep a new or renewed account, its secrets in the store, and select it. + pub fn add( + &mut self, + store: &dyn SecretStore, + account: Account, + secrets: &Secrets, + ) -> Result<(), String> { + store.set( + &account.uuid, + &serde_json::to_string(secrets).map_err(|e| e.to_string())?, + )?; + self.selected = Some(account.uuid.clone()); + match self.accounts.iter_mut().find(|a| a.uuid == account.uuid) { + Some(a) => *a = account, + None => self.accounts.push(account), + } + Ok(()) + } + /// Sign out: the secrets leave the keychain, the account the list. + pub fn remove(&mut self, store: &dyn SecretStore, uuid: &str) -> Result<(), String> { + store.delete(uuid)?; + self.accounts.retain(|a| a.uuid != uuid); + if self.selected.as_deref() == Some(uuid) { + self.selected = None; + } + Ok(()) + } +} + +/// The selected account with a token good for this game, renewed and saved if needed. +pub fn session_for_launch( + ep: &Endpoints, + store: &dyn SecretStore, + accounts: &mut Accounts, +) -> Result, String> { + let Some(account) = accounts.selected().cloned() else { + return Ok(None); + }; + let secrets: Secrets = store + .get(&account.uuid)? + .and_then(|s| serde_json::from_str(&s).ok()) + .ok_or_else(|| { + format!( + "{} is no longer signed in on this computer. Sign in again.", + account.name + ) + })?; + let client_id = client_id().ok_or(NOT_CONFIGURED)?; + let before = secrets.minecraft_token.clone(); + let (renewed, secrets) = fresh(ep, &client_id, &account, secrets)?; + if renewed != account || secrets.minecraft_token != before { + accounts.add(store, renewed.clone(), &secrets)?; + accounts.save()?; + } + Ok(Some((renewed, secrets))) +} + +/// Write the session for the game, readable by this user only, in a fresh file it deletes +/// when it reads it. +pub fn write_session_file( + dir: &Path, + account: &Account, + secrets: &Secrets, +) -> Result { + std::fs::create_dir_all(dir).map_err(|e| e.to_string())?; + // Leftovers of games that never started (refused by the game after two minutes anyway). + if let Ok(entries) = std::fs::read_dir(dir) { + for e in entries.flatten() { + let old = e + .metadata() + .and_then(|m| m.modified()) + .is_ok_and(|m| m.elapsed().is_ok_and(|age| age > Duration::from_secs(120))); + if old { + let _ = std::fs::remove_file(e.path()); + } + } + } + let mut name = [0u8; 12]; + getrandom::fill(&mut name).map_err(|e| e.to_string())?; + let path = dir.join(format!( + "session-{}.json", + name.iter().map(|b| format!("{b:02x}")).collect::() + )); + let mut options = std::fs::OpenOptions::new(); + options.write(true).create_new(true); + #[cfg(unix)] + std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600); + let mut file = options.open(&path).map_err(|e| e.to_string())?; + let body = json!({ + "name": account.name, + "uuid": account.uuid, + "access_token": secrets.minecraft_token, + "user_type": "msa", + "xuid": secrets.xuid, + }); + std::io::Write::write_all(&mut file, body.to_string().as_bytes()).map_err(|e| e.to_string())?; + Ok(path) +} + +/// Where a background sign-in is (the window and the MCP server show it). +#[derive(Clone, Debug)] +pub enum SignInState { + Starting, + /// Waiting for the player at `verification_uri` with `user_code`. + Code(DeviceCode), + Done(Result), +} + +/// A sign-in on its own thread, from the code to the saved account. +pub struct SignIn { + state: std::sync::Arc>, + cancel: std::sync::Arc, +} + +impl SignIn { + pub fn start() -> Self { + use std::sync::atomic::Ordering; + let state = std::sync::Arc::new(Mutex::new(SignInState::Starting)); + let cancel = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); + let (thread_state, thread_cancel) = (state.clone(), cancel.clone()); + std::thread::spawn(move || { + let set = |s| *thread_state.lock().unwrap() = s; + let result = (|| { + let ep = Endpoints::live(); + let client_id = client_id().ok_or(NOT_CONFIGURED)?; + let code = device_code(&ep, &client_id)?; + set(SignInState::Code(code.clone())); + let ms = wait_for_sign_in(&ep, &client_id, &code, &|| { + thread_cancel.load(Ordering::Relaxed) + })?; + let (account, secrets) = finish_sign_in(&ep, ms)?; + let mut accounts = Accounts::load(); + accounts.add(store(), account.clone(), &secrets)?; + accounts.save()?; + Ok(account) + })(); + set(SignInState::Done(result)); + }); + Self { state, cancel } + } + pub fn state(&self) -> SignInState { + self.state.lock().unwrap().clone() + } + pub fn cancel(&self) { + self.cancel + .store(true, std::sync::atomic::Ordering::Relaxed); + } +} + +/// Give the game the selected account's session, when there is one. +pub fn attach_session( + cmd: &mut std::process::Command, + game_home: &Path, +) -> Result, String> { + let mut accounts = Accounts::load(); + let Some((account, secrets)) = session_for_launch(&Endpoints::live(), store(), &mut accounts)? + else { + return Ok(None); + }; + let file = write_session_file(&game_home.join("sessions"), &account, &secrets)?; + cmd.arg("--session-file").arg(file); + Ok(Some(account)) +} + +#[cfg(test)] +mod tests; diff --git a/launcher/src/account/tests.rs b/launcher/src/account/tests.rs new file mode 100644 index 000000000..925b78195 --- /dev/null +++ b/launcher/src/account/tests.rs @@ -0,0 +1,410 @@ +//! The sign-in chain against a local mock of the Microsoft, Xbox Live and Minecraft endpoints +//! (recorded response shapes, mock tokens only), and the keychain abstraction in memory. +use super::*; +use std::io::{BufRead, BufReader, Read, Write}; +use std::net::TcpListener; +use std::sync::Arc; + +const UUID: &str = "069a79f444e94726a5befca90e38aaf5"; + +/// What the mock answers and what it was asked. +#[derive(Default)] +struct Mock { + /// Polls left before the token endpoint stops saying authorization_pending. + pending: usize, + xerr: Option, + owns_game: bool, + no_profile: bool, + /// Every request: method, path and body. + log: Vec<(String, String, String)>, +} + +fn reply(status: u16, body: Value) -> (u16, String) { + (status, body.to_string()) +} + +fn route(mock: &mut Mock, method: &str, path: &str, auth: &str, body: &str) -> (u16, String) { + let form = |key: &str| { + body.split('&') + .filter_map(|p| p.split_once('=')) + .find(|(k, _)| *k == key) + .map(|(_, v)| v.replace('+', " ").replace("%3A", ":").replace("%20", " ")) + }; + match (method, path) { + ("POST", "/ms/devicecode") => { + assert_eq!(form("client_id").as_deref(), Some("test-client")); + assert_eq!(form("scope").as_deref(), Some(SCOPE)); + reply( + 200, + json!({"user_code": "ABCD-EFGH", "device_code": "dev-1", "verification_uri": "https://www.microsoft.com/link", "expires_in": 900, "interval": 1}), + ) + } + ("POST", "/ms/token") => match form("grant_type").as_deref() { + Some("urn:ietf:params:oauth:grant-type:device_code") if mock.pending > 0 => { + mock.pending -= 1; + reply(400, json!({"error": "authorization_pending"})) + } + Some("urn:ietf:params:oauth:grant-type:device_code") => { + assert_eq!(form("device_code").as_deref(), Some("dev-1")); + reply( + 200, + json!({"access_token": "ms-access-1", "refresh_token": "ms-refresh-1", "expires_in": 3600}), + ) + } + Some("refresh_token") if form("refresh_token").as_deref() == Some("ms-refresh-1") => { + reply( + 200, + json!({"access_token": "ms-access-2", "refresh_token": "ms-refresh-2"}), + ) + } + _ => reply(400, json!({"error": "invalid_grant"})), + }, + ("POST", "/xbl") => { + let v: Value = serde_json::from_str(body).unwrap(); + assert!(v["Properties"]["RpsTicket"] + .as_str() + .unwrap() + .starts_with("d=ms-access-")); + assert_eq!(v["RelyingParty"], "http://auth.xboxlive.com"); + reply( + 200, + json!({"Token": "xbl-token", "DisplayClaims": {"xui": [{"uhs": "uhs-1"}]}}), + ) + } + ("POST", "/xsts") => { + let v: Value = serde_json::from_str(body).unwrap(); + assert_eq!(v["Properties"]["UserTokens"][0], "xbl-token"); + assert_eq!(v["RelyingParty"], "rp://api.minecraftservices.com/"); + match mock.xerr { + Some(code) => reply(401, json!({"Identity": "0", "XErr": code, "Message": ""})), + None => reply( + 200, + json!({"Token": "xsts-token", "DisplayClaims": {"xui": [{"uhs": "uhs-1", "xid": "2535400000000000"}]}}), + ), + } + } + ("POST", "/mc/authentication/login_with_xbox") => { + let v: Value = serde_json::from_str(body).unwrap(); + assert_eq!(v["identityToken"], "XBL3.0 x=uhs-1;xsts-token"); + reply( + 200, + json!({"username": "mock", "access_token": "mc-token", "token_type": "Bearer", "expires_in": 86400}), + ) + } + ("GET", "/mc/entitlements/mcstore") => { + assert_eq!(auth, "Bearer mc-token"); + let items = if mock.owns_game { + json!([{"name": "product_minecraft", "signature": "x"}, {"name": "game_minecraft", "signature": "x"}]) + } else { + json!([]) + }; + reply(200, json!({"items": items, "signature": "x", "keyId": "1"})) + } + ("GET", "/mc/minecraft/profile") if mock.no_profile => reply( + 404, + json!({"path": "/minecraft/profile", "errorType": "NOT_FOUND", "error": "NOT_FOUND"}), + ), + ("GET", "/mc/minecraft/profile") => reply( + 200, + json!({ + "id": UUID, "name": "Notch", + "skins": [{"id": "s1", "state": "ACTIVE", "url": "http://textures.minecraft.net/texture/abc", "variant": "SLIM"}], + "capes": [{"id": "c1", "state": "INACTIVE", "url": "http://textures.minecraft.net/texture/cape1", "alias": "Migrator"}, + {"id": "c2", "state": "ACTIVE", "url": "http://textures.minecraft.net/texture/cape2", "alias": "Vanilla"}], + }), + ), + _ => reply(404, json!({"error": "NotFound"})), + } +} + +/// A one-thread HTTP/1.1 server: one request per connection. +fn serve(mock: Arc>) -> Endpoints { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let base = format!("http://{}", listener.local_addr().unwrap()); + std::thread::spawn(move || { + for stream in listener.incoming() { + let Ok(mut stream) = stream else { continue }; + let mut reader = BufReader::new(stream.try_clone().unwrap()); + let mut line = String::new(); + if reader.read_line(&mut line).is_err() { + continue; + } + let mut parts = line.split_whitespace(); + let (method, path) = ( + parts.next().unwrap_or("").to_owned(), + parts.next().unwrap_or("").to_owned(), + ); + let (mut length, mut auth) = (0, String::new()); + loop { + let mut header = String::new(); + reader.read_line(&mut header).unwrap(); + let header = header.trim_end(); + if header.is_empty() { + break; + } + let (k, v) = header.split_once(':').unwrap(); + match k.to_ascii_lowercase().as_str() { + "content-length" => length = v.trim().parse().unwrap(), + "authorization" => auth = v.trim().to_owned(), + _ => {} + } + } + let mut body = vec![0; length]; + reader.read_exact(&mut body).unwrap(); + let body = String::from_utf8(body).unwrap(); + let (status, text) = { + let mut m = mock.lock().unwrap(); + m.log.push((method.clone(), path.clone(), body.clone())); + route(&mut m, &method, &path, &auth, &body) + }; + let _ = write!( + stream, + "HTTP/1.1 {status} X\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{text}", + text.len() + ); + } + }); + Endpoints { + microsoft: format!("{base}/ms"), + xbox_user: format!("{base}/xbl"), + xsts: format!("{base}/xsts"), + minecraft: format!("{base}/mc"), + } +} + +fn mock(f: impl FnOnce(&mut Mock)) -> (Arc>, Endpoints) { + let mut m = Mock { + owns_game: true, + ..Default::default() + }; + f(&mut m); + let m = Arc::new(Mutex::new(m)); + let ep = serve(m.clone()); + (m, ep) +} + +#[test] +fn the_whole_chain() { + let (m, ep) = mock(|m| m.pending = 2); + let code = device_code(&ep, "test-client").unwrap(); + assert_eq!( + (code.user_code.as_str(), code.verification_uri.as_str()), + ("ABCD-EFGH", "https://www.microsoft.com/link") + ); + let ms = wait_for_sign_in(&ep, "test-client", &code, &|| false).unwrap(); + let (account, secrets) = finish_sign_in(&ep, ms).unwrap(); + assert_eq!( + account, + Account { + uuid: UUID.into(), + name: "Notch".into(), + skin: Some(( + "http://textures.minecraft.net/texture/abc".into(), + "slim".into() + )), + cape: Some("http://textures.minecraft.net/texture/cape2".into()), + } + ); + assert_eq!(secrets.minecraft_token, "mc-token"); + assert_eq!(secrets.xuid.as_deref(), Some("2535400000000000")); + assert!(secrets.minecraft_expires_at > now() + 80000); + // Two pending polls, then the token; then Xbox, XSTS, Minecraft, entitlements, profile. + let paths: Vec = m + .lock() + .unwrap() + .log + .iter() + .map(|(_, p, _)| p.clone()) + .collect(); + assert_eq!( + paths, + [ + "/ms/devicecode", + "/ms/token", + "/ms/token", + "/ms/token", + "/xbl", + "/xsts", + "/mc/authentication/login_with_xbox", + "/mc/entitlements/mcstore", + "/mc/minecraft/profile" + ] + ); + assert!(!format!("{secrets:?}").contains("mc-token")); +} + +#[test] +fn refresh_only_when_the_token_runs_out() { + let (m, ep) = mock(|_| {}); + let account = Account { + uuid: UUID.into(), + name: "Notch".into(), + skin: None, + cape: None, + }; + let good = Secrets { + refresh_token: "ms-refresh-1".into(), + minecraft_token: "old".into(), + minecraft_expires_at: now() + 7200, + xuid: None, + }; + let (_, kept) = fresh(&ep, "test-client", &account, good).unwrap(); + assert_eq!(kept.minecraft_token, "old"); + assert!(m.lock().unwrap().log.is_empty()); + let stale = Secrets { + minecraft_expires_at: now() + 60, + ..kept.clone() + }; + let (renewed_account, renewed) = fresh(&ep, "test-client", &account, stale).unwrap(); + assert_eq!( + ( + renewed.refresh_token.as_str(), + renewed.minecraft_token.as_str() + ), + ("ms-refresh-2", "mc-token") + ); + assert!(renewed_account.skin.is_some()); + let revoked = Secrets { + refresh_token: "revoked".into(), + minecraft_expires_at: 0, + ..kept + }; + assert_eq!( + fresh(&ep, "test-client", &account, revoked).unwrap_err(), + SIGN_IN_AGAIN + ); +} + +#[test] +fn refusals_have_messages() { + let tokens = || MsTokens { + access: "ms-access-1".into(), + refresh: "r".into(), + }; + let (_, ep) = mock(|m| m.xerr = Some(2148916233)); + assert!(finish_sign_in(&ep, tokens()) + .unwrap_err() + .contains("no Xbox profile")); + let (_, ep) = mock(|m| m.xerr = Some(2148916238)); + assert!(finish_sign_in(&ep, tokens()) + .unwrap_err() + .contains("child account")); + let (_, ep) = mock(|m| m.owns_game = false); + assert_eq!( + finish_sign_in(&ep, tokens()).unwrap_err(), + "This account doesn't own Minecraft: Java Edition." + ); + let (_, ep) = mock(|m| m.no_profile = true); + assert!(finish_sign_in(&ep, tokens()) + .unwrap_err() + .contains("no Minecraft profile")); + assert_eq!( + oauth_error(&json!({"error": "authorization_declined"})), + "Sign-in was declined in the browser." + ); + // Nothing listening: a message, not a URL. + let dead = Endpoints { + microsoft: "http://127.0.0.1:9/ms".into(), + ..Endpoints::live() + }; + assert_eq!( + device_code(&dead, "x").unwrap_err(), + "Could not reach Microsoft. Check your internet connection." + ); +} + +#[test] +fn cancelling_stops_the_wait() { + let (_, ep) = mock(|m| m.pending = 100); + let code = device_code(&ep, "test-client").unwrap(); + assert_eq!( + wait_for_sign_in(&ep, "test-client", &code, &|| true).unwrap_err(), + "Sign-in cancelled." + ); +} + +#[test] +fn accounts_keep_secrets_in_the_store_only() { + let store = MemoryStore::default(); + let mut accounts = Accounts::default(); + let account = Account { + uuid: UUID.into(), + name: "Notch".into(), + skin: None, + cape: None, + }; + let secrets = Secrets { + refresh_token: "r".into(), + minecraft_token: "mc-secret".into(), + minecraft_expires_at: 1, + xuid: None, + }; + accounts.add(&store, account.clone(), &secrets).unwrap(); + assert_eq!(accounts.selected(), Some(&account)); + assert_eq!(accounts.find("notch"), Some(&account)); + assert_eq!( + accounts.find("069a79f4-44e9-4726-a5be-fca90e38aaf5"), + Some(&account) + ); + let saved = serde_json::to_string(&accounts).unwrap(); + assert!(!saved.contains("mc-secret") && !saved.contains("\"r\"")); + assert!(store.get(UUID).unwrap().unwrap().contains("mc-secret")); + accounts.remove(&store, UUID).unwrap(); + assert_eq!( + (accounts.selected(), store.get(UUID).unwrap()), + (None, None) + ); + assert!(!store.persistent()); +} + +#[test] +fn session_files_are_private_and_complete() { + let dir = std::env::temp_dir().join(format!("horizon-launcher-session-{}", std::process::id())); + let account = Account { + uuid: UUID.into(), + name: "Notch".into(), + skin: None, + cape: None, + }; + let secrets = Secrets { + refresh_token: "r".into(), + minecraft_token: "mc-token".into(), + minecraft_expires_at: 1, + xuid: Some("25".into()), + }; + let path = write_session_file(&dir, &account, &secrets).unwrap(); + let v: Value = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap(); + assert_eq!( + v, + json!({"name": "Notch", "uuid": UUID, "access_token": "mc-token", "user_type": "msa", "xuid": "25"}) + ); + // The refresh token never leaves the keychain. + assert!(!v.to_string().contains("\"r\"")); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + assert_eq!( + std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, + 0o600 + ); + } + let other = write_session_file(&dir, &account, &secrets).unwrap(); + assert_ne!(path, other); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn client_id_is_configuration() { + // The run-time variable overrides; empty means not configured. + std::env::set_var("HORIZON_MSA_CLIENT_ID", " "); + assert_eq!(client_id(), None); + std::env::set_var( + "HORIZON_MSA_CLIENT_ID", + "00000000-1111-2222-3333-444444444444", + ); + assert_eq!( + client_id().as_deref(), + Some("00000000-1111-2222-3333-444444444444") + ); + std::env::remove_var("HORIZON_MSA_CLIENT_ID"); +} diff --git a/launcher/src/backend.rs b/launcher/src/backend.rs index 354837d2c..152aa3f69 100644 --- a/launcher/src/backend.rs +++ b/launcher/src/backend.rs @@ -996,7 +996,12 @@ fn need_prepared(tag: &str) -> Result<(), String> { /// The client's command, once its resources are prepared. pub fn client(tag: &str) -> Result { need_prepared(tag)?; - Ok(client_command(tag)) + let mut cmd = client_command(tag); + // A sign-in that can't be renewed (no network, expired) still lets the game start, offline. + if let Err(e) = crate::account::attach_session(&mut cmd, &game_home()) { + eprintln!("Playing offline: {e}"); + } + Ok(cmd) } /// The dedicated server's command in `folder`, once prepared and the EULA is agreed to. @@ -1387,6 +1392,11 @@ pub enum Msg { LauncherUpdated(Result<(), String>), /// `reuse_prepared_everywhere` prepared these versions. Reused(Vec<(String, String)>), + /// Whether secrets are kept in the OS keychain (else only until the launcher closes). + Keychain(bool), + /// The selected account's session file for the game about to start (none = offline), or + /// why it could not be renewed. + Session(Result, String>), } /// A running process; its output arrives as `Msg::Line`, its end as `Msg::Exit`. diff --git a/launcher/src/cli.rs b/launcher/src/cli.rs index b624b2259..46827ca85 100644 --- a/launcher/src/cli.rs +++ b/launcher/src/cli.rs @@ -1,6 +1,7 @@ //! `horizon-launcher `: the same steps as the window, from a terminal. Every //! command goes through `backend`; this file only parses arguments and prints. use clap::{Parser, Subcommand}; +use horizon_launcher::account::{self, Accounts}; use horizon_launcher::backend::{self, Release}; use std::io::{IsTerminal, Write}; use std::path::PathBuf; @@ -20,6 +21,23 @@ struct Cli { command: Option, } +#[derive(Subcommand)] +enum AccountCmd { + /// The signed-in accounts and which one plays + List, + /// Sign in with a Microsoft account in your browser (device code) + SignIn, + /// Sign out: the account's tokens leave the keychain + SignOut { + /// Its name or UUID + who: String, + }, + /// Play as this account + Select { who: String }, + /// Play offline, without an account + Offline, +} + #[derive(Subcommand)] enum Cmd { /// List Horizon releases, or the installed versions @@ -61,6 +79,11 @@ enum Cmd { Notes { tag: Option }, /// Show the Discord, sponsor and website links Links, + /// Microsoft accounts: list them (the default), sign in, sign out, or pick the one that plays + Account { + #[command(subcommand)] + action: Option, + }, /// Show or set the game's menu style (classic is vanilla's own screens) MenuStyle { /// Omit to show the current style @@ -254,6 +277,7 @@ fn execute(command: Cmd, as_json: bool) -> Result<(), String> { ); } } + Cmd::Account { action } => account_command(action.unwrap_or(AccountCmd::List), as_json)?, Cmd::Links => { let links = backend::links(); if as_json { @@ -331,3 +355,76 @@ fn update(check: bool, as_json: bool) -> Result<(), String> { } Ok(()) } + +/// `account …`: names and UUIDs only; tokens are never printed. +fn account_command(action: AccountCmd, as_json: bool) -> Result<(), String> { + let mut accounts = Accounts::load(); + let find = |accounts: &Accounts, who: &str| { + accounts + .find(who) + .cloned() + .ok_or_else(|| format!("No signed-in account {who}. See `horizon-launcher account`.")) + }; + match action { + AccountCmd::List => { + if as_json { + json(serde_json::json!({ + "accounts": accounts.accounts.iter().map(|a| serde_json::json!({ + "name": a.name, "uuid": a.uuid, + "selected": accounts.selected.as_ref() == Some(&a.uuid), + })).collect::>(), + "sign_in_configured": account::client_id().is_some(), + })); + } else if accounts.accounts.is_empty() { + println!("No Microsoft account signed in: the game plays offline."); + } else { + for a in &accounts.accounts { + let mark = if accounts.selected.as_ref() == Some(&a.uuid) { + "*" + } else { + " " + }; + println!("{mark} {} {}", a.name, a.uuid); + } + if accounts.selected().is_none() { + println!("Playing offline (`account select NAME` to play as one)."); + } + } + } + AccountCmd::SignIn => { + let client_id = account::client_id().ok_or(account::NOT_CONFIGURED)?; + let ep = account::Endpoints::live(); + let code = account::device_code(&ep, &client_id)?; + eprintln!( + "To sign in, open {} in a browser and enter the code {}", + code.verification_uri, code.user_code + ); + let ms = account::wait_for_sign_in(&ep, &client_id, &code, &|| false)?; + let (signed_in, secrets) = account::finish_sign_in(&ep, ms)?; + accounts.add(account::store(), signed_in.clone(), &secrets)?; + accounts.save()?; + println!("Signed in as {}.", signed_in.name); + if !account::store().persistent() { + eprintln!("{}", account::NO_KEYCHAIN); + } + } + AccountCmd::SignOut { who } => { + let a = find(&accounts, &who)?; + accounts.remove(account::store(), &a.uuid)?; + accounts.save()?; + println!("Signed out {}.", a.name); + } + AccountCmd::Select { who } => { + let a = find(&accounts, &who)?; + accounts.selected = Some(a.uuid); + accounts.save()?; + println!("The game plays as {}.", a.name); + } + AccountCmd::Offline => { + accounts.selected = None; + accounts.save()?; + println!("The game plays offline."); + } + } + Ok(()) +} diff --git a/launcher/src/lib.rs b/launcher/src/lib.rs index 64766a00c..cac481c4a 100644 --- a/launcher/src/lib.rs +++ b/launcher/src/lib.rs @@ -1,2 +1,3 @@ //! The launcher's core, shared by the GUI, the CLI and the MCP server. +pub mod account; pub mod backend; diff --git a/launcher/src/main.rs b/launcher/src/main.rs index be556226f..b3fade865 100644 --- a/launcher/src/main.rs +++ b/launcher/src/main.rs @@ -13,6 +13,7 @@ use gpui::{ RenderImage, ScrollHandle, SharedString, Stateful, Subscription, TitlebarOptions, Window, WindowBounds, WindowOptions, }; +use horizon_launcher::account::{self, Accounts, SignIn, SignInState}; use horizon_launcher::backend::{self, Job, Msg, Release, Running, Settings, Updates}; use std::borrow::Cow; use std::collections::VecDeque; @@ -147,6 +148,13 @@ struct Launcher { client_started: Option, crash: Option, server: Option, + /// Microsoft accounts (accounts.json), the sign-in under way and what it last showed. + accounts: Accounts, + sign_in: Option, + sign_in_state: Option, + keychain: bool, + /// The game is waiting for its session (a token renewal) before it starts. + starting_client: Option, server_log: VecDeque, server_error: Option, input: String, @@ -228,6 +236,11 @@ impl Launcher { client_started: None, crash: None, server: None, + accounts: Accounts::load(), + sign_in: None, + sign_in_state: None, + keychain: true, + starting_client: None, server_log: VecDeque::new(), server_error: None, input: String::new(), @@ -239,6 +252,11 @@ impl Launcher { _appearance: appearance, }; let tx = this.tx.clone(); + let keychain_tx = this.tx.clone(); + // Asking the keychain can block (D-Bus), so not on this thread. + std::thread::spawn(move || { + let _ = keychain_tx.send(Msg::Keychain(account::store().persistent())); + }); std::thread::spawn(move || { let reused = backend::reuse_prepared_everywhere(); if !reused.is_empty() { @@ -331,6 +349,25 @@ impl Launcher { Msg::Links(links) => self.links = links, // The page reads is_prepared when drawn; `changed` redraws it. Msg::Reused(_) => self.installed = backend::installed(), + Msg::Keychain(persistent) => self.keychain = persistent, + Msg::Session(session) => { + if let Some(tag) = self.starting_client.take() { + let mut cmd = backend::client_command(&tag); + match session { + Ok(Some(file)) => { + cmd.arg("--session-file").arg(file); + } + Ok(None) => {} + // Still play, offline, and say why. + Err(e) => self.client_error = Some(format!("Playing offline: {e}")), + } + self.accounts = Accounts::load(); + match backend::spawn(Job::Client, cmd, self.tx.clone()) { + Ok(r) => self.client = Some(r), + Err(e) => self.client_error = Some(e), + } + } + } Msg::Progress(tag, p) => { self.bar = (self.bar.1, p); self.installing = Some((tag, p)); @@ -454,6 +491,17 @@ impl Launcher { } } } + if let Some(sign_in) = &self.sign_in { + let state = sign_in.state(); + let changed_state = format!("{state:?}") != format!("{:?}", self.sign_in_state); + if changed_state { + if let SignInState::Done(Ok(_)) = state { + self.accounts = Accounts::load(); + } + self.sign_in_state = Some(state); + changed = true; + } + } if self.checked.is_some_and(|at| at.elapsed() > CHECK_EVERY) { self.check_updates(); } @@ -545,7 +593,7 @@ impl Launcher { }; match self.mode { Mode::Client => { - if self.client.is_some() { + if self.client.is_some() || self.starting_client.is_some() { return; } self.client_error = None; @@ -554,10 +602,30 @@ impl Launcher { // A little earlier than the spawn: file times can be coarse. self.client_started = Some(std::time::SystemTime::now() - std::time::Duration::from_secs(2)); - match backend::spawn(Job::Client, backend::client_command(&tag), self.tx.clone()) { - Ok(r) => self.client = Some(r), - Err(e) => self.client_error = Some(e), - } + // The session (a network round trip when the token needs renewing) comes first; + // `drain` starts the game when it arrives. + self.starting_client = Some(tag); + let tx = self.tx.clone(); + std::thread::spawn(move || { + let session = (|| { + let mut accounts = Accounts::load(); + let Some((a, secrets)) = account::session_for_launch( + &account::Endpoints::live(), + account::store(), + &mut accounts, + )? + else { + return Ok(None); + }; + account::write_session_file( + &backend::game_home().join("sessions"), + &a, + &secrets, + ) + .map(Some) + })(); + let _ = tx.send(Msg::Session(session)); + }); } Mode::Server => { if let Some(server) = &mut self.server { @@ -1163,7 +1231,7 @@ impl Launcher { let version = backend::game_version(&tag); let hero = self.hero(&tag, &version, prepared, cx); let running = match self.mode { - Mode::Client => self.client.is_some(), + Mode::Client => self.client.is_some() || self.starting_client.is_some(), Mode::Server => self.server.is_some(), }; let play_label = match (self.mode, running) { @@ -1263,6 +1331,27 @@ impl Launcher { )), &t, )); + if self.mode == Mode::Client { + let who = match self.accounts.selected() { + Some(a) => div().child(format!("{} (Microsoft account)", a.name)), + None => div() + .text_color(t.muted) + .child("Offline: online servers need a Microsoft account."), + }; + rows = rows.child(divider(&t)).child(row( + "Playing as", + who, + Some( + button("accounts", "Accounts…", Kind::Ghost, &t).on_click(cx.listener( + |this, _: &ClickEvent, _, cx| { + this.go(Page::Settings); + cx.notify(); + }, + )), + ), + &t, + )); + } if self.mode == Mode::Server { let folder = self .settings @@ -1761,6 +1850,7 @@ impl Launcher { div() .flex() .flex_col() + .child(self.account_rows(cx)) .child(divider(&t)) .child(row("Updates", auto, Some(toggle), &t)) .child(divider(&t)) @@ -1808,6 +1898,167 @@ impl Launcher { .child(agents) } + /// Settings' Microsoft accounts: who is signed in and plays, the sign-in with its code. + fn account_rows(&mut self, cx: &mut Context) -> Div { + let t = self.theme; + let mut rows = div().flex().flex_col(); + let selected = self.accounts.selected.clone(); + for (i, a) in self.accounts.accounts.clone().into_iter().enumerate() { + let plays = selected.as_ref() == Some(&a.uuid); + let value = div() + .flex() + .flex_col() + .gap(px(2.)) + .child(a.name.clone()) + .child( + div() + .text_size(px(theme::SMALL)) + .text_color(t.muted) + .child(if plays { "Plays" } else { "Signed in" }), + ); + let uuid = a.uuid.clone(); + let mut actions = div().flex().gap(px(4.)); + if plays { + actions = actions.child( + button(format!("offline-{i}"), "Play offline", Kind::Ghost, &t).on_click( + cx.listener(|this, _: &ClickEvent, _, cx| { + this.accounts.selected = None; + let _ = this.accounts.save(); + cx.notify(); + }), + ), + ); + } else { + let uuid = uuid.clone(); + actions = actions.child( + button(format!("select-{i}"), "Play as", Kind::Secondary, &t).on_click( + cx.listener(move |this, _: &ClickEvent, _, cx| { + this.accounts.selected = Some(uuid.clone()); + let _ = this.accounts.save(); + cx.notify(); + }), + ), + ); + } + actions = actions.child( + button(format!("sign-out-{i}"), "Sign out", Kind::Ghost, &t).on_click(cx.listener( + move |this, _: &ClickEvent, _, cx| { + let store = account::store(); + if let Err(e) = this.accounts.remove(store, &uuid) { + this.sign_in_state = Some(SignInState::Done(Err(e))); + } + let _ = this.accounts.save(); + cx.notify(); + }, + )), + ); + let label = if i == 0 { "Accounts" } else { "" }; + rows = rows.child(divider(&t)).child(row( + label, + value, + Some(actions.id(SharedString::from(format!("account-{i}")))), + &t, + )); + } + let configured = account::client_id().is_some(); + let busy = matches!( + self.sign_in_state, + Some(SignInState::Starting | SignInState::Code(_)) + ); + let value = match &self.sign_in_state { + _ if !configured => div().text_color(t.muted).child(account::NOT_CONFIGURED), + Some(SignInState::Starting) => div().text_color(t.muted).child("Asking Microsoft…"), + Some(SignInState::Code(code)) => div() + .flex() + .flex_col() + .gap(px(4.)) + .child(format!( + "Open {} in your browser and enter this code:", + code.verification_uri + )) + .child( + div() + .font_family(theme::MONO) + .text_size(px(theme::LARGE)) + .font_weight(FontWeight::MEDIUM) + .child(code.user_code.clone()), + ), + Some(SignInState::Done(Ok(a))) => div().child(format!("Signed in as {}.", a.name)), + Some(SignInState::Done(Err(e))) => div().text_color(t.danger).child(e.clone()), + None if self.accounts.accounts.is_empty() => div().text_color(t.muted).child( + "Sign in to play on online servers with your name and skin. Without an account the game plays offline.", + ), + None => div().text_color(t.muted).child("Add another account."), + }; + let value = if self.keychain || self.accounts.accounts.is_empty() { + value + } else { + div().flex().flex_col().gap(px(4.)).child(value).child( + div() + .text_size(px(theme::SMALL)) + .text_color(t.muted) + .child(account::NO_KEYCHAIN), + ) + }; + let action = if !configured { + None + } else if let Some(SignInState::Code(code)) = &self.sign_in_state { + let (uri, user_code) = (code.verification_uri.clone(), code.user_code.clone()); + Some( + div() + .flex() + .gap(px(4.)) + .child( + button("sign-in-copy", "Copy code", Kind::Secondary, &t).on_click( + move |_, _, cx| { + cx.write_to_clipboard(gpui::ClipboardItem::new_string( + user_code.clone(), + )) + }, + ), + ) + .child( + button("sign-in-open", "Open link", Kind::Secondary, &t) + .on_click(move |_, _, cx| cx.open_url(&uri)), + ) + .child( + button("sign-in-cancel", "Cancel", Kind::Ghost, &t).on_click(cx.listener( + |this, _: &ClickEvent, _, cx| { + if let Some(s) = this.sign_in.take() { + s.cancel(); + } + this.sign_in_state = None; + cx.notify(); + }, + )), + ), + ) + } else if busy { + None + } else { + Some(div().child( + button("sign-in", "Sign in with Microsoft", Kind::Secondary, &t).on_click( + cx.listener(|this, _: &ClickEvent, _, cx| { + this.sign_in = Some(SignIn::start()); + this.sign_in_state = Some(SignInState::Starting); + cx.notify(); + }), + ), + )) + }; + let label = if self.accounts.accounts.is_empty() { + "Account" + } else { + "" + }; + rows.child(divider(&t)).child(row( + label, + value, + action.map(|a| a.id("sign-in-actions")), + &t, + )) + } + fn console(&self, cx: &mut Context) -> Div { let t = self.theme; let running = self.server.is_some(); diff --git a/launcher/src/mcp.rs b/launcher/src/mcp.rs index a8fd6de9a..d842ade2e 100644 --- a/launcher/src/mcp.rs +++ b/launcher/src/mcp.rs @@ -1,6 +1,7 @@ //! `horizon-launcher mcp`: the Model Context Protocol over stdin and stdout (JSON-RPC 2.0, one //! message per line), so AI agents can install, prepare and run Horizon. Every tool goes through //! `backend`. A server started here lives as long as the session. +use horizon_launcher::account::{self, Accounts, SignIn, SignInState}; use horizon_launcher::backend::{self, Job, Logged}; use serde_json::{json, Value}; use std::io::{BufRead, Write}; @@ -12,6 +13,7 @@ const PROTOCOL: &str = "2025-06-18"; struct Session { server: Option, client: Option, + sign_in: Option, } fn tools() -> Value { @@ -42,6 +44,12 @@ fn tools() -> Value { "inputSchema": { "type": "object", "properties": { "style": { "type": "string", "enum": ["horizon", "classic"], "description": "Omit to show the current style." } } } }, { "name": "logs", "description": "Read the game's log: the last lines of logs/latest.log in the game folder, or with crash the newest crash report (what the game wrote when it last crashed). Read-only.", "inputSchema": { "type": "object", "properties": { "lines": { "type": "integer", "minimum": 1, "maximum": 5000, "description": "How many lines of latest.log (default 100)." }, "crash": { "type": "boolean", "description": "Return the newest crash report instead." } } } }, + { "name": "accounts", "description": "The Microsoft accounts signed in to the launcher (names and UUIDs, never tokens), which one the game plays as (none = offline), and how a sign-in started with sign_in is going.", "inputSchema": none }, + { "name": "sign_in", "description": "Start signing in a Microsoft account: returns a link and a code the player enters in their browser. The sign-in finishes in the background; check it with accounts. Only when the player asks to sign in.", "inputSchema": none }, + { "name": "sign_out", "description": "Sign an account out of the launcher (its tokens leave the keychain).", + "inputSchema": { "type": "object", "properties": { "account": { "type": "string", "description": "Its name or UUID." } }, "required": ["account"] } }, + { "name": "select_account", "description": "Choose the account the game plays as, or \"offline\" to play without one.", + "inputSchema": { "type": "object", "properties": { "account": { "type": "string", "description": "A name or UUID, or \"offline\"." } }, "required": ["account"] } }, { "name": "check_updates", "description": "Check GitHub for a Horizon release newer than every installed version, and for a newer launcher.", "inputSchema": none }, ]) } @@ -242,6 +250,70 @@ impl Session { })) .unwrap()) } + "accounts" => { + let accounts = Accounts::load(); + let sign_in = self.sign_in.as_ref().map(|s| match s.state() { + SignInState::Starting => json!({ "state": "starting" }), + SignInState::Code(c) => json!({ "state": "waiting for the player", "link": c.verification_uri, "code": c.user_code }), + SignInState::Done(Ok(a)) => json!({ "state": "signed in", "name": a.name }), + SignInState::Done(Err(e)) => json!({ "state": "failed", "error": e }), + }); + Ok(serde_json::to_string_pretty(&json!({ + "accounts": accounts.accounts.iter().map(|a| json!({ "name": a.name, "uuid": a.uuid })).collect::>(), + "plays_as": accounts.selected().map(|a| a.name.clone()), + "sign_in_configured": account::client_id().is_some(), + "keychain": account::store().persistent(), + "sign_in": sign_in, + })) + .unwrap()) + } + "sign_in" => { + account::client_id().ok_or(account::NOT_CONFIGURED)?; + if let Some(s) = self.sign_in.take() { + s.cancel(); + } + let sign_in = SignIn::start(); + let deadline = std::time::Instant::now() + Duration::from_secs(30); + let state = loop { + match sign_in.state() { + SignInState::Starting if std::time::Instant::now() < deadline => { + std::thread::sleep(Duration::from_millis(100)) + } + state => break state, + } + }; + self.sign_in = Some(sign_in); + match state { + SignInState::Code(c) => Ok(format!( + "Ask the player to open {} and enter the code {}. Then check accounts.", + c.verification_uri, c.user_code + )), + SignInState::Done(Err(e)) => Err(e), + _ => Err("Microsoft did not answer. Try again.".into()), + } + } + "sign_out" | "select_account" => { + let who = arg_str(args, "account").ok_or("account is required")?; + let mut accounts = Accounts::load(); + if name == "select_account" && who.eq_ignore_ascii_case("offline") { + accounts.selected = None; + accounts.save()?; + return Ok("The game plays offline.".into()); + } + let a = accounts + .find(who) + .cloned() + .ok_or_else(|| format!("No signed-in account {who}."))?; + if name == "sign_out" { + accounts.remove(account::store(), &a.uuid)?; + accounts.save()?; + Ok(format!("Signed out {}.", a.name)) + } else { + accounts.selected = Some(a.uuid); + accounts.save()?; + Ok(format!("The game plays as {}.", a.name)) + } + } _ => Err(format!("Unknown tool {name}")), } } @@ -292,6 +364,7 @@ pub fn serve() -> Result<(), String> { let mut session = Session { server: None, client: None, + sign_in: None, }; let stdin = std::io::stdin(); let mut stdout = std::io::stdout();