Join online-mode servers with the launcher's account

Read the signed-in account from a session file (--session-file, deleted
on read), answer ClientboundHelloPacket like vanilla: shared secret, server
hash, session join through the services discovery document (authlib's
error mapping and messages), RSA-wrapped key packet, AES/CFB8 both ways.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-14 19:39:16 +02:00
parent c8629f3378
commit 89b2ca64a9
8 changed files with 812 additions and 17 deletions
Generated
+382
View File
@@ -174,6 +174,12 @@ version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
[[package]]
name = "base64"
version = "0.22.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
[[package]]
name = "bit-set"
version = "0.10.0"
@@ -693,6 +699,15 @@ version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b"
[[package]]
name = "form_urlencoded"
version = "1.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf"
dependencies = [
"percent-encoding",
]
[[package]]
name = "futures-core"
version = "0.3.34"
@@ -737,6 +752,17 @@ dependencies = [
"windows-link",
]
[[package]]
name = "getrandom"
version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"
dependencies = [
"cfg-if",
"libc",
"wasi",
]
[[package]]
name = "getrandom"
version = "0.3.4"
@@ -894,6 +920,7 @@ dependencies = [
"pollster",
"serde_json",
"symphonia",
"ureq",
"wgpu",
"winit",
]
@@ -920,8 +947,10 @@ name = "horizon-protocol"
version = "0.1.0"
dependencies = [
"flate2",
"getrandom 0.3.4",
"horizon-world",
"serde_json",
"sha1",
]
[[package]]
@@ -964,6 +993,110 @@ dependencies = [
"cc",
]
[[package]]
name = "icu_collections"
version = "2.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fa68d21081c4a05d5a901a1c62add574c77048b6a1c67be3b50ce0b60d4ca513"
dependencies = [
"displaydoc",
"potential_utf",
"utf8_iter",
"yoke",
"zerofrom",
"zerovec",
]
[[package]]
name = "icu_locale_core"
version = "2.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d56e28588da92eee5c3201a6eff33fabdd49b62269c8938d4ff050ce4d900deb"
dependencies = [
"displaydoc",
"litemap",
"tinystr",
"writeable",
"zerovec",
]
[[package]]
name = "icu_normalizer"
version = "2.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "12f9cf5f235641ed274641dd81c3f28d870e276763d0797aeeab72317b1c646f"
dependencies = [
"icu_collections",
"icu_normalizer_data",
"icu_properties",
"icu_provider",
"smallvec",
"zerovec",
]
[[package]]
name = "icu_normalizer_data"
version = "2.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1563da1ed3e0b3bf3d74c9b85917ac9c56464d2f57242270c09c9e752f8021a0"
[[package]]
name = "icu_properties"
version = "2.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7e7ca276ad3145661a65914e6daf131ca5120cd3dcee8f8f3214b8875184a148"
dependencies = [
"displaydoc",
"icu_collections",
"icu_locale_core",
"icu_properties_data",
"icu_provider",
"zerotrie",
"zerovec",
]
[[package]]
name = "icu_properties_data"
version = "2.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e590f038c1464a96894fd6d10127e90a8be4509f56ff7ecef851b15cee0b7caa"
[[package]]
name = "icu_provider"
version = "2.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d27bbb9d3abbefac45d55f647c9de1d44aafcd1186eb91879afef17c396c3e73"
dependencies = [
"displaydoc",
"icu_locale_core",
"writeable",
"yoke",
"zerofrom",
"zerotrie",
"zerovec",
]
[[package]]
name = "idna"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de"
dependencies = [
"idna_adapter",
"smallvec",
"utf8_iter",
]
[[package]]
name = "idna_adapter"
version = "1.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714"
dependencies = [
"icu_normalizer",
"icu_properties",
]
[[package]]
name = "indexmap"
version = "2.14.2"
@@ -1157,6 +1290,12 @@ version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
[[package]]
name = "litemap"
version = "0.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae"
[[package]]
name = "litrs"
version = "1.0.0"
@@ -1880,6 +2019,15 @@ dependencies = [
"portable-atomic",
]
[[package]]
name = "potential_utf"
version = "0.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661"
dependencies = [
"zerovec",
]
[[package]]
name = "presser"
version = "0.3.1"
@@ -2020,6 +2168,20 @@ version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "19b30a45b0cd0bcca8037f3d0dc3421eaf95327a17cad11964fb8179b4fc4832"
[[package]]
name = "ring"
version = "0.17.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7"
dependencies = [
"cc",
"cfg-if",
"getrandom 0.2.17",
"libc",
"untrusted",
"windows-sys 0.52.0",
]
[[package]]
name = "rustc-hash"
version = "1.1.0"
@@ -2061,6 +2223,41 @@ dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "rustls"
version = "0.23.46"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf"
dependencies = [
"log",
"once_cell",
"ring",
"rustls-pki-types",
"rustls-webpki",
"subtle",
"zeroize",
]
[[package]]
name = "rustls-pki-types"
version = "1.15.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96"
dependencies = [
"zeroize",
]
[[package]]
name = "rustls-webpki"
version = "0.103.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2"
dependencies = [
"ring",
"rustls-pki-types",
"untrusted",
]
[[package]]
name = "rustversion"
version = "1.0.23"
@@ -2254,6 +2451,12 @@ dependencies = [
"bitflags 2.13.2",
]
[[package]]
name = "stable_deref_trait"
version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"
[[package]]
name = "static_assertions"
version = "1.1.0"
@@ -2266,6 +2469,12 @@ version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6637bab7722d379c8b41ba849228d680cc12d0a45ba1fa2b48f2a30577a06731"
[[package]]
name = "subtle"
version = "2.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
[[package]]
name = "symphonia"
version = "0.5.5"
@@ -2359,6 +2568,17 @@ dependencies = [
"unicode-ident",
]
[[package]]
name = "synstructure"
version = "0.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.6",
]
[[package]]
name = "thiserror"
version = "1.0.69"
@@ -2424,6 +2644,16 @@ dependencies = [
"strict-num",
]
[[package]]
name = "tinystr"
version = "0.8.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b1e27c91459209c2986af3dcf603a5a74a4368754ce37414f59acc971167f643"
dependencies = [
"displaydoc",
"zerovec",
]
[[package]]
name = "tokio"
version = "1.53.2"
@@ -2520,6 +2750,45 @@ version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254"
[[package]]
name = "untrusted"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"
[[package]]
name = "ureq"
version = "2.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "02d1a66277ed75f640d608235660df48c8e3c19f3b4edb6a263315626cc3c01d"
dependencies = [
"base64",
"log",
"once_cell",
"rustls",
"rustls-pki-types",
"url",
"webpki-roots 0.26.11",
]
[[package]]
name = "url"
version = "2.5.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed"
dependencies = [
"form_urlencoded",
"idna",
"percent-encoding",
"serde",
]
[[package]]
name = "utf8_iter"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"
[[package]]
name = "uuid"
version = "1.28.0"
@@ -2556,6 +2825,12 @@ dependencies = [
"winapi-util",
]
[[package]]
name = "wasi"
version = "0.11.1+wasi-snapshot-preview1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
[[package]]
name = "wasip2"
version = "1.0.4+wasi-0.2.12"
@@ -2750,6 +3025,24 @@ dependencies = [
"wasm-bindgen",
]
[[package]]
name = "webpki-roots"
version = "0.26.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9"
dependencies = [
"webpki-roots 1.0.9",
]
[[package]]
name = "webpki-roots"
version = "1.0.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7dcd9d09a39985f5344844e66b0c530a33843579125f23e21e9f0f220850f22a"
dependencies = [
"rustls-pki-types",
]
[[package]]
name = "wgpu"
version = "30.0.1"
@@ -3289,6 +3582,12 @@ dependencies = [
"wayland-protocols-wlr",
]
[[package]]
name = "writeable"
version = "0.6.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc"
[[package]]
name = "x11-dl"
version = "2.21.0"
@@ -3356,6 +3655,29 @@ version = "0.8.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "550a2b930b62486a393c52d5c3b84bff264b28aa437ed64694d31e93b1757af7"
[[package]]
name = "yoke"
version = "0.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5"
dependencies = [
"stable_deref_trait",
"yoke-derive",
"zerofrom",
]
[[package]]
name = "yoke-derive"
version = "0.8.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.6",
"synstructure",
]
[[package]]
name = "zerocopy"
version = "0.8.60"
@@ -3376,6 +3698,66 @@ dependencies = [
"syn 2.0.119",
]
[[package]]
name = "zerofrom"
version = "0.1.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272"
dependencies = [
"zerofrom-derive",
]
[[package]]
name = "zerofrom-derive"
version = "0.1.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.6",
"synstructure",
]
[[package]]
name = "zeroize"
version = "1.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879"
[[package]]
name = "zerotrie"
version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f"
dependencies = [
"displaydoc",
"yoke",
"zerofrom",
]
[[package]]
name = "zerovec"
version = "0.11.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bb0464e17806c1d976d5cba29399c7f08e516e279e2ba493f63123b5fca67dd8"
dependencies = [
"yoke",
"zerofrom",
"zerovec-derive",
]
[[package]]
name = "zerovec-derive"
version = "0.11.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "34df6fc39dbd26ddc9c10e6a2984476e13acce22e64e4487636ef494369225da"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.6",
]
[[package]]
name = "zip"
version = "2.4.2"
+2
View File
@@ -30,6 +30,8 @@ horizon-theme = { path = "../horizon-theme" }
arboard = { version = "3.6.1", default-features = false, features = ["wayland-data-control"] }
# Controllers (evdev + libudev on Linux, IOKit on macOS, Windows.Gaming.Input).
gilrs = "0.11"
# HTTPS to the Minecraft services (online-mode session join).
ureq = { version = "2", default-features = false, features = ["tls"] }
[features]
# Records the call sites of mob random draws (`mob_ai_probe` traces).
+343
View File
@@ -0,0 +1,343 @@
//! The Microsoft account the launcher signed in, handed over in a session
//! file (docs/microsoft-account.md), and the Minecraft services call
//! online-mode servers need: authlib's MinecraftServicesSessionService.joinServer
//! through the services discovery document. The access token stays in this
//! process's memory: it is never logged, printed or written anywhere.
use std::{
path::Path,
sync::{Arc, Mutex, OnceLock},
time::{Duration, SystemTime},
};
/// MinecraftServicesEnvironment.PROD.
pub const DEFAULT_DISCOVERY: &str = "https://discovery.minecraftservices.com/minecraft/client";
/// A session file older than this is refused: it can't be replayed later.
const MAX_SESSION_FILE_AGE: Duration = Duration::from_secs(120);
/// A signed-in account (vanilla's User with type msa).
pub struct AuthSession {
pub name: String,
pub uuid: u128,
pub xuid: Option<String>,
access_token: String,
}
impl std::fmt::Debug for AuthSession {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("AuthSession")
.field("name", &self.name)
.field("uuid", &horizon_protocol::crypto::uuid_string(self.uuid))
.field("access_token", &"<hidden>")
.finish()
}
}
/// A UUID with or without dashes.
pub fn parse_uuid(text: &str) -> Option<u128> {
let hex: String = text.chars().filter(|c| *c != '-').collect();
(hex.len() == 32)
.then(|| u128::from_str_radix(&hex, 16).ok())
.flatten()
}
impl AuthSession {
/// For tests and harnesses.
pub fn new(name: &str, uuid: u128, access_token: &str) -> Self {
Self {
name: name.to_owned(),
uuid,
xuid: None,
access_token: access_token.to_owned(),
}
}
/// The session file's JSON: {"name", "uuid", "access_token", "user_type": "msa", "xuid"}.
pub fn parse(text: &str) -> Result<Self, String> {
let v: serde_json::Value =
serde_json::from_str(text).map_err(|_| "the session file is not valid JSON")?;
let field = |k: &str| v.get(k).and_then(|s| s.as_str());
let name = field("name").ok_or("the session file has no name")?;
if name.is_empty() || name.chars().count() > 16 {
return Err("the session file's name is not a valid player name".into());
}
let uuid = field("uuid")
.and_then(parse_uuid)
.ok_or("the session file has no valid uuid")?;
let access_token = field("access_token")
.filter(|t| !t.is_empty())
.ok_or("the session file has no access token")?;
if field("user_type").is_some_and(|t| t != "msa") {
return Err("the session file is not a Microsoft account session".into());
}
Ok(Self {
name: name.to_owned(),
uuid,
xuid: field("xuid").map(str::to_owned),
access_token: access_token.to_owned(),
})
}
/// Read the session file the launcher wrote and delete it at once. It
/// must be fresh and, on Unix, readable by its owner only.
pub fn load(path: &Path) -> Result<Self, String> {
let meta = std::fs::metadata(path).map_err(|e| format!("{}: {e}", path.display()))?;
let refuse = |why: &str| {
let _ = std::fs::remove_file(path);
Err(format!("{}: {why}", path.display()))
};
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
if meta.permissions().mode() & 0o077 != 0 {
return refuse("other users can read it");
}
}
let age = meta
.modified()
.ok()
.and_then(|m| SystemTime::now().duration_since(m).ok())
.unwrap_or_default();
if age > MAX_SESSION_FILE_AGE {
return refuse("it is too old (start the game from the launcher)");
}
let text = std::fs::read_to_string(path);
let _ = std::fs::remove_file(path);
Self::parse(&text.map_err(|e| format!("{}: {e}", path.display()))?)
}
}
static CURRENT: OnceLock<Arc<AuthSession>> = OnceLock::new();
/// The account this game was started with (set once at start).
pub fn set_current(session: AuthSession) {
let _ = CURRENT.set(Arc::new(session));
}
pub fn current() -> Option<Arc<AuthSession>> {
CURRENT.get().cloned()
}
/// Why joining a server through the session service failed, like the
/// AuthenticationException subclasses authlib throws.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum JoinError {
/// No answer, or a 5xx (AuthenticationUnavailableException).
Unavailable,
/// 401 or ForbiddenOperationException (InvalidCredentialsException).
InvalidSession,
/// InsufficientPrivilegesException: multiplayer is off for the account.
InsufficientPrivileges,
/// multiplayer.access.banned or FORCED_USERNAME_CHANGE.
Banned,
/// Anything else, with the service's message.
Other(String),
}
impl JoinError {
/// MinecraftClientHttpException.toAuthenticationException.
pub fn from_response(status: u16, body: &str) -> Self {
let v: serde_json::Value = serde_json::from_str(body).unwrap_or_default();
let error = v.get("error").and_then(|e| e.as_str()).unwrap_or("");
match error {
"ForbiddenOperationException" => return Self::InvalidSession,
"multiplayer.access.banned" | "FORCED_USERNAME_CHANGE" => return Self::Banned,
"InsufficientPrivilegesException" => return Self::InsufficientPrivileges,
_ => {}
}
match status {
401 => Self::InvalidSession,
500.. => Self::Unavailable,
_ => Self::Other(
v.get("errorMessage")
.and_then(|m| m.as_str())
.map_or_else(|| format!("Status: {status}"), str::to_owned),
),
}
}
/// ClientHandshakePacketListenerImpl.authenticateServer's message: the
/// key of the reason inside "disconnect.loginFailedInfo", or its text.
pub fn reason(&self) -> Result<&'static str, &str> {
match self {
Self::Unavailable => Ok("disconnect.loginFailedInfo.serversUnavailable"),
Self::InvalidSession => Ok("disconnect.loginFailedInfo.invalidSession"),
Self::InsufficientPrivileges => Ok("disconnect.loginFailedInfo.insufficientPrivileges"),
Self::Banned => Ok("disconnect.loginFailedInfo.userBanned"),
Self::Other(message) => Err(message),
}
}
}
/// The services discovery document URL: `HORIZON_API_DISCOVERY` overrides
/// it like authlib's `-Dminecraft.api.discovery.host`.
pub fn discovery_url() -> String {
std::env::var("HORIZON_API_DISCOVERY")
.ok()
.filter(|u| !u.is_empty())
.unwrap_or_else(|| DEFAULT_DISCOVERY.to_owned())
}
fn agent() -> ureq::Agent {
ureq::AgentBuilder::new()
.timeout(Duration::from_secs(15))
.user_agent(concat!("Horizon/", env!("CARGO_PKG_VERSION")))
.build()
}
/// The discovery document, fetched once per game (a failure is retried next time).
fn discovery() -> Result<Arc<serde_json::Value>, JoinError> {
static CACHE: Mutex<Option<Arc<serde_json::Value>>> = Mutex::new(None);
if let Some(d) = CACHE.lock().unwrap().clone() {
return Ok(d);
}
let doc: serde_json::Value = agent()
.get(&discovery_url())
.call()
.ok()
.and_then(|r| r.into_string().ok())
.and_then(|t| serde_json::from_str(&t).ok())
.ok_or(JoinError::Unavailable)?;
let doc = Arc::new(doc);
*CACHE.lock().unwrap() = Some(doc.clone());
Ok(doc)
}
/// MinecraftServicesDiscoveryService.getUrl(service, endpoint).
pub fn endpoint(doc: &serde_json::Value, service: &str, name: &str) -> Option<String> {
doc.pointer(&format!("/discovery/{service}/endpoints/{name}/uri"))
.and_then(|u| u.as_str())
.map(str::to_owned)
}
/// The JoinMinecraftServerRequest body; `selectedProfile` is the undashed UUID.
pub fn join_request(session: &AuthSession, server_hash: &str) -> String {
serde_json::json!({
"accessToken": session.access_token,
"selectedProfile": format!("{:032x}", session.uuid),
"serverId": server_hash,
})
.to_string()
}
/// MinecraftServicesSessionService.joinServer: tell the session service this
/// account is joining the server whose hash is `server_hash`.
pub fn join_server(session: &AuthSession, server_hash: &str) -> Result<(), JoinError> {
let doc = discovery()?;
let url = endpoint(&doc, "session", "join").ok_or(JoinError::Unavailable)?;
match agent()
.post(&url)
.set("Content-Type", "application/json; charset=utf-8")
.send_string(&join_request(session, server_hash))
{
Ok(_) => Ok(()),
Err(ureq::Error::Status(status, response)) => Err(JoinError::from_response(
status,
&response.into_string().unwrap_or_default(),
)),
Err(ureq::Error::Transport(_)) => Err(JoinError::Unavailable),
}
}
#[cfg(test)]
mod tests {
use super::*;
const UUID: u128 = 0x069a79f444e94726a5befca90e38aaf5;
fn write(dir: &Path, text: &str, mode: u32) -> std::path::PathBuf {
let path = dir.join("session.json");
std::fs::write(&path, text).unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(mode)).unwrap();
}
let _ = mode;
path
}
#[test]
fn session_files_are_read_once_and_must_be_private() {
let dir = std::env::temp_dir().join(format!("horizon-auth-test-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let text = r#"{"name":"Notch","uuid":"069a79f4-44e9-4726-a5be-fca90e38aaf5","access_token":"mock-token","user_type":"msa"}"#;
let path = write(&dir, text, 0o600);
let s = AuthSession::load(&path).unwrap();
assert_eq!((s.name.as_str(), s.uuid), ("Notch", UUID));
assert!(!path.exists(), "deleted after reading");
assert!(!format!("{s:?}").contains("mock-token"));
#[cfg(unix)]
{
let path = write(&dir, text, 0o644);
assert!(
AuthSession::load(&path)
.unwrap_err()
.contains("other users")
);
assert!(!path.exists());
}
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn session_file_fields() {
assert!(
AuthSession::parse(r#"{"name":"Notch","uuid":"069a79f444e94726a5befca90e38aaf5"}"#)
.is_err()
);
assert!(
AuthSession::parse(
r#"{"name":"","uuid":"069a79f444e94726a5befca90e38aaf5","access_token":"t"}"#
)
.is_err()
);
assert!(AuthSession::parse(r#"{"name":"A","uuid":"nope","access_token":"t"}"#).is_err());
assert!(AuthSession::parse(r#"{"name":"A","uuid":"069a79f444e94726a5befca90e38aaf5","access_token":"t","user_type":"legacy"}"#).is_err());
let s = AuthSession::parse(r#"{"name":"A","uuid":"069a79f444e94726a5befca90e38aaf5","access_token":"t","xuid":"25"}"#).unwrap();
assert_eq!(s.xuid.as_deref(), Some("25"));
}
#[test]
fn join_request_like_authlib() {
let s = AuthSession::new("Notch", UUID, "tok");
let v: serde_json::Value = serde_json::from_str(&join_request(&s, "-7c9d")).unwrap();
assert_eq!(
v,
serde_json::json!({"accessToken": "tok", "selectedProfile": "069a79f444e94726a5befca90e38aaf5", "serverId": "-7c9d"})
);
}
#[test]
fn errors_map_like_authlib() {
let e = |status, body| JoinError::from_response(status, body);
assert_eq!(
e(
403,
r#"{"error":"ForbiddenOperationException","errorMessage":"Invalid token"}"#
),
JoinError::InvalidSession
);
assert_eq!(e(401, ""), JoinError::InvalidSession);
assert_eq!(
e(403, r#"{"error":"InsufficientPrivilegesException"}"#),
JoinError::InsufficientPrivileges
);
assert_eq!(
e(403, r#"{"error":"multiplayer.access.banned"}"#),
JoinError::Banned
);
assert_eq!(e(503, "down"), JoinError::Unavailable);
assert_eq!(
e(429, r#"{"errorMessage":"Too many"}"#),
JoinError::Other("Too many".into())
);
assert_eq!(
JoinError::InvalidSession.reason(),
Ok("disconnect.loginFailedInfo.invalidSession")
);
}
#[test]
fn discovery_endpoints() {
let doc = serde_json::json!({"discovery": {"session": {"endpoints": {"join": {"uri": "https://s/join"}}}}});
assert_eq!(
endpoint(&doc, "session", "join").as_deref(),
Some("https://s/join")
);
assert_eq!(endpoint(&doc, "session", "verify"), None);
}
}
+14 -1
View File
@@ -246,12 +246,13 @@ impl Options {
player_name: std::env::var("HORIZON_PLAYER_NAME").unwrap_or_else(|_| "Player".into()),
dedicated: None,
};
let mut session_file = std::env::var("HORIZON_SESSION_FILE").ok();
let mut args = std::env::args().skip(1);
while let Some(arg) = args.next() {
match arg.as_str() {
"--help" | "-h" => {
println!(
"Horizon — Minecraft Java Edition 26.3 in Rust\n\n --resources PATH Prepared resources (horizon-prepare)\n --render-distance N Chunks, 2..64 (default 12)\n --world NAME World folder under saves/ (default \"New World\")\n --seed N World seed for new worlds (default 0)\n --creative Creative mode (default survival)\n --test-terrain Simple test terrain instead of vanilla generation\n --frames N Exit after N frames (testing)\n --smoke-report PATH Write a JSON report on exit\n --control Accept horizon-ctl commands on a local socket\n --control-socket PATH Control socket path (default $XDG_RUNTIME_DIR/horizon-control.sock)\n --server HOST[:PORT] Join a multiplayer server (offline mode) at start\n --name NAME Player name for multiplayer (default Player)\n\nControls: mouse look, WASD move, Space jump, Left Shift sneak, Left Ctrl sprint,\nleft click break, right click place/use, 1-9/scroll hotbar, E inventory,\nQ drop, F3 debug, Esc pause."
"Horizon — Minecraft Java Edition 26.3 in Rust\n\n --resources PATH Prepared resources (horizon-prepare)\n --render-distance N Chunks, 2..64 (default 12)\n --world NAME World folder under saves/ (default \"New World\")\n --seed N World seed for new worlds (default 0)\n --creative Creative mode (default survival)\n --test-terrain Simple test terrain instead of vanilla generation\n --frames N Exit after N frames (testing)\n --smoke-report PATH Write a JSON report on exit\n --control Accept horizon-ctl commands on a local socket\n --control-socket PATH Control socket path (default $XDG_RUNTIME_DIR/horizon-control.sock)\n --server HOST[:PORT] Join a multiplayer server (offline mode) at start\n --name NAME Player name for multiplayer (default Player)\n --session-file PATH Signed-in account from the launcher (read once, then deleted)\n\nControls: mouse look, WASD move, Space jump, Left Shift sneak, Left Ctrl sprint,\nleft click break, right click place/use, 1-9/scroll hotbar, E inventory,\nQ drop, F3 debug, Esc pause."
);
return Ok(None);
}
@@ -295,6 +296,7 @@ impl Options {
"--world" => o.world = Some(value),
"--server" => o.server = Some(value),
"--name" => o.player_name = value,
"--session-file" => session_file = Some(value),
"--control-socket" => o.control = Some(value.into()),
"--time" => o.time = Some(value.parse()?),
"--weather" => o.weather = Some(value),
@@ -314,6 +316,17 @@ impl Options {
}
}
}
// The launcher's account: online-mode servers need it. A bad file
// only leaves the game offline.
if let Some(path) = session_file.filter(|p| !p.is_empty()) {
match horizon_client::auth::AuthSession::load(path.as_ref()) {
Ok(session) => {
o.player_name = session.name.clone();
horizon_client::auth::set_current(session);
}
Err(e) => eprintln!("Horizon: not signed in: {e}"),
}
}
Ok(Some(o))
}
}
@@ -28,7 +28,12 @@ impl Game<'_> {
while Instant::now() < deadline {
self.update_world();
if self.remote.is_none() {
error = Some("disconnected".to_owned());
error = Some(match self.title.as_ref().map(|t| &t.mode) {
Some(horizon_client::title::Mode::Multiplayer(
horizon_client::multiplayer::Screen::Disconnected { reason },
)) => format!("disconnected: {reason}"),
_ => "disconnected".to_owned(),
});
break;
}
if Instant::now() >= next {
+4 -1
View File
@@ -158,7 +158,10 @@ impl Game<'_> {
let lang = Arc::new(horizon_client::net::load_language(&root));
let view = self.settings.render_distance.clamp(2, 32) as i8;
horizon_client::crash::set_detail("Server", address.to_owned());
let session = Session::connect(address, name, view, lang.clone());
// A signed-in account always plays under its own name.
let auth = horizon_client::auth::current();
let name = auth.as_ref().map_or(name, |a| a.name.as_str());
let session = Session::connect(address, name, auth.clone(), view, lang.clone());
let player_type = super::perspective::player_type(&root);
let mut streaming = Streaming::new(
Arc::new(NoTerrain),
+1
View File
@@ -9,6 +9,7 @@ pub mod atlas_sources;
pub mod attack_strength;
pub mod attribute_updates;
pub mod audio;
pub mod auth;
pub mod auto_jump;
pub mod banner;
pub mod biome;
+60 -14
View File
@@ -1,17 +1,20 @@
//! Multiplayer session: a network thread that connects to a server, logs in
//! (offline mode only), runs the configuration phase and then forwards decoded
//! play packets to the game thread. Keep-alives and pings are answered on the
//! network thread like vanilla's connection handlers so a busy frame never
//! times the client out. Online-mode (authenticated) servers are refused:
//! Horizon never handles Microsoft credentials.
//! Multiplayer session: a network thread that connects to a server, logs in,
//! runs the configuration phase and then forwards decoded play packets to the
//! game thread. Keep-alives and pings are answered on the network thread like
//! vanilla's connection handlers so a busy frame never times the client out.
//! Online-mode servers need the Microsoft account the launcher signed in
//! (crate::auth): the login joins the server through the session service and
//! encrypts the connection (ClientHandshakePacketListenerImpl.handleHello).
use crate::auth::AuthSession;
use horizon_protocol::{
PROTOCOL_VERSION,
connection::{ConnReader, ConnWriter, Connection, Counters},
crypto::offline_uuid,
crypto::{generate_secret, offline_uuid, server_hash},
packets::{Empty, configuration as cfg, handshake, login, play},
registry::Dynamic,
rsa::RsaPublicKey,
servers::parse_address,
text::{Language, plain},
text::{Language, plain, translatable},
};
use std::{
sync::{
@@ -51,8 +54,14 @@ pub struct Session {
debug: bool,
}
impl Session {
/// Start connecting in the background.
pub fn connect(address: &str, name: &str, view_distance: i8, lang: Arc<Language>) -> Self {
/// Start connecting in the background, as `auth`'s account when there is one.
pub fn connect(
address: &str,
name: &str,
auth: Option<Arc<AuthSession>>,
view_distance: i8,
lang: Arc<Language>,
) -> Self {
let (send, events) = channel();
let writer = Arc::new(Mutex::new(None));
let counters = Arc::new(Mutex::new(None));
@@ -64,6 +73,7 @@ impl Session {
let reason = match run(
&address_owned,
&name_owned,
auth.as_deref(),
view_distance,
&lang,
&send,
@@ -131,10 +141,19 @@ fn status(send: &Sender<Event>, text: &str) {
let _ = send.send(Event::Status(text.to_owned()));
}
/// Shown when an online-mode server asks a client without an account to authenticate.
pub const NOT_SIGNED_IN: &str = "This server is in online mode. Sign in with your Microsoft account in the Horizon launcher to join it.";
/// A translation, or the key itself (Language.getOrDefault).
fn tr(lang: &Language, key: &str) -> String {
lang.get(key).cloned().unwrap_or_else(|| key.to_owned())
}
/// The whole connection; returns the disconnect reason.
fn run(
address: &str,
name: &str,
auth: Option<&AuthSession>,
view_distance: i8,
lang: &Language,
send: &Sender<Event>,
@@ -158,8 +177,8 @@ fn run(
.encode(),
)
.map_err(e)?;
status(send, "Logging in...");
let uuid = offline_uuid(name);
// Vanilla's login sends the account's profile id, or the offline one.
let uuid = auth.map_or_else(|| offline_uuid(name), |a| a.uuid);
c.send(
&login::Serverbound::Hello(login::ServerHello {
name: name.to_owned(),
@@ -183,8 +202,35 @@ fn run(
.unwrap_or(p.reason_json);
return Err(reason);
}
login::Clientbound::Hello(_) => {
return Err("This server is in online mode. Horizon only joins offline-mode servers (online-mode=false).".into());
login::Clientbound::Hello(hello) => {
status(send, &tr(lang, "connect.authorizing"));
let key = RsaPublicKey::from_der(&hello.public_key)
.map_err(|err| format!("Protocol error: {err}"))?;
let secret = generate_secret().map_err(e)?;
if hello.should_authenticate {
let account = auth.ok_or_else(|| NOT_SIGNED_IN.to_owned())?;
let hash = server_hash(&hello.server_id, &secret, &hello.public_key);
if let Err(err) = crate::auth::join_server(account, &hash) {
let reason = match err.reason() {
Ok(key) => tr(lang, key),
Err(message) => message.to_owned(),
};
return Err(plain(
&translatable("disconnect.loginFailedInfo", &[&reason]),
lang,
));
}
}
status(send, &tr(lang, "connect.encrypting"));
c.send(
&login::Serverbound::Key(login::Key {
key: key.encrypt(&secret).map_err(e)?,
challenge: key.encrypt(&hello.challenge).map_err(e)?,
})
.encode(),
)
.map_err(e)?;
c.enable_encryption(&secret);
}
login::Clientbound::CustomQuery(q) => {
c.send(