From eebf5621bf5c937e585639a17fb9e900b854b250 Mon Sep 17 00:00:00 2001 From: rdbtCVS <87152661+rdbtCVS@users.noreply.github.com> Date: Wed, 14 Oct 2026 18:54:51 +0100 Subject: [PATCH 01/24] Fix classic menu panorama resource preparation --- crates/horizon-prepare/src/lib.rs | 15 +++- crates/horizon-prepare/src/main.rs | 22 ++++-- crates/horizon-prepare/src/sounds.rs | 109 +++++++++++++++++++++++++-- docs/native-client.md | 7 +- 4 files changed, 137 insertions(+), 16 deletions(-) diff --git a/crates/horizon-prepare/src/lib.rs b/crates/horizon-prepare/src/lib.rs index 246cb4d51..534abfc8a 100644 --- a/crates/horizon-prepare/src/lib.rs +++ b/crates/horizon-prepare/src/lib.rs @@ -17,7 +17,7 @@ pub mod pyjson; mod sounds; mod survival; -pub use sounds::sounds; +pub use sounds::{panorama, sounds}; use pyjson::Value; use sha2::Digest; @@ -452,7 +452,7 @@ pub fn prepare(options: &Options, log: Log) -> Result { origin, log, }; - steps(&run, &lock, &oracle)?; + steps(&run, &lock, &oracle, options.minecraft_dir.as_deref())?; log(&format!( "Prepared Horizon native-client resources: {}", resources.display() @@ -464,7 +464,12 @@ fn arg(path: &Path) -> String { path.display().to_string() } -fn steps(run: &Run, lock: &artifacts::Lock, oracle: &Path) -> Result<(), String> { +fn steps( + run: &Run, + lock: &artifacts::Lock, + oracle: &Path, + minecraft: Option<&Path>, +) -> Result<(), String> { let root = &run.resources; let repo = &run.root; let server_cp = run.server_classpath.as_str(); @@ -678,6 +683,10 @@ fn steps(run: &Run, lock: &artifacts::Lock, oracle: &Path) -> Result<(), String> count += 1; } + // The JAR holds only gray 1x1 panorama placeholders. Import the indexed + // textures afterwards, including on reruns that just extracted the JAR again. + panorama(repo, minecraft, run.log)?; + // One file each, exported again when the exporter or the jar it reads changed. let single = |what: &str, file: &str, diff --git a/crates/horizon-prepare/src/main.rs b/crates/horizon-prepare/src/main.rs index 1ef1387ad..4be86f525 100644 --- a/crates/horizon-prepare/src/main.rs +++ b/crates/horizon-prepare/src/main.rs @@ -10,6 +10,7 @@ horizon-prepare: prepare Horizon's resources from your own Minecraft Java Editio Usage: horizon-prepare [--prepare] [--server-jar PATH] [--minecraft-dir PATH] [--root PATH] horizon-prepare sounds [--minecraft-dir PATH] [--root PATH] + horizon-prepare panorama [--minecraft-dir PATH] [--root PATH] --prepare Import the pinned game files from your own copy first --server-jar PATH The pinned server jar you downloaded yourself @@ -23,6 +24,9 @@ Needs Minecraft played once from the official launcher, and Java (a JDK) of the research-lock.json pins: JAVA_HOME, else javac and java on the PATH. The resources go to /.local/horizon-client/; pass that to horizon-client --resources. +horizon-prepare panorama repairs the classic menu background in existing resources without Java. +Full preparation also imports these textures after extracting the client JAR's placeholders. + horizon-prepare sounds copies the pinned version's sounds (about 380 MB) from the official launcher's asset store into the same folder, checking every file. It is optional: without it the game is silent. Nothing is downloaded; it needs the version played once from the official launcher. @@ -52,7 +56,7 @@ fn main() -> ExitCode { }; let mut root = None; let mut args = std::env::args_os().skip(1).peekable(); - let sounds = args.next_if(|a| a == "sounds").is_some(); + let assets = args.next_if(|a| a == "sounds" || a == "panorama"); while let Some(arg) = args.next() { let text = arg.to_string_lossy().into_owned(); let (flag, inline) = match text.split_once('=') { @@ -71,8 +75,8 @@ fn main() -> ExitCode { } }; let parsed = match flag.as_str() { - "--prepare" | "--server-jar" if sounds => { - Err(format!("{flag} is for preparing, not for sounds")) + "--prepare" | "--server-jar" if assets.is_some() => { + Err(format!("{flag} is for preparing, not for asset copying")) } "--prepare" if inline.is_none() => { options.import = true; @@ -108,10 +112,14 @@ fn main() -> ExitCode { let _ = writeln!(out, "{line}"); let _ = out.flush(); }; - let result = if sounds { - horizon_prepare::sounds(&options.root, options.minecraft_dir.as_deref(), &log) - } else { - horizon_prepare::prepare(&options, &log) + let result = match assets.as_deref().and_then(|a| a.to_str()) { + Some("sounds") => { + horizon_prepare::sounds(&options.root, options.minecraft_dir.as_deref(), &log) + } + Some("panorama") => { + horizon_prepare::panorama(&options.root, options.minecraft_dir.as_deref(), &log) + } + _ => horizon_prepare::prepare(&options, &log), }; match result { Ok(_) => ExitCode::SUCCESS, diff --git a/crates/horizon-prepare/src/sounds.rs b/crates/horizon-prepare/src/sounds.rs index 75ed221a4..e0787656d 100644 --- a/crates/horizon-prepare/src/sounds.rs +++ b/crates/horizon-prepare/src/sounds.rs @@ -1,4 +1,4 @@ -//! The pinned version's sounds (sounds.json and the .ogg files) from the player's own official +//! The pinned version's sounds and title panorama from the player's own official //! launcher install, each object checked against the asset index's SHA-1, copied into //! `.local/horizon-client//assets` where the game reads them (tools/fetch_sounds.py and //! the tools/lab.py functions it called). Nothing is downloaded. @@ -76,6 +76,37 @@ fn is_sound(name: &str) -> bool { /// `.local/horizon-client/`; returns that folder. Files already there with the right /// SHA-1 are kept. pub fn sounds(root: &Path, minecraft: Option<&Path>, log: Log) -> Result { + copy_assets(root, minecraft, log, is_sound, "Sound", &[]) +} + +/// Replaces the client JAR's 1x1 title placeholders with the full panorama from the +/// launcher's asset store. Also usable on already-prepared resources without Java. +pub fn panorama(root: &Path, minecraft: Option<&Path>, log: Log) -> Result { + copy_assets(root, minecraft, log, is_panorama, "Panorama", &PANORAMA) +} + +const PANORAMA: [&str; 7] = [ + "minecraft/textures/gui/title/background/panorama_0.png", + "minecraft/textures/gui/title/background/panorama_1.png", + "minecraft/textures/gui/title/background/panorama_2.png", + "minecraft/textures/gui/title/background/panorama_3.png", + "minecraft/textures/gui/title/background/panorama_4.png", + "minecraft/textures/gui/title/background/panorama_5.png", + "minecraft/textures/gui/title/background/panorama_overlay.png", +]; + +fn is_panorama(name: &str) -> bool { + PANORAMA.contains(&name) +} + +fn copy_assets( + root: &Path, + minecraft: Option<&Path>, + log: Log, + wanted_asset: fn(&str) -> bool, + label: &str, + required: &[&str], +) -> Result { let lock = Lock::read(root)?; let minecraft = artifacts::minecraft_dir(minecraft); let manifest = artifacts::import_manifest(&lock, &minecraft)?; @@ -95,12 +126,17 @@ pub fn sounds(root: &Path, minecraft: Option<&Path>, log: Log) -> Result = Vec::new(); - for (name, info) in objects.iter().filter(|(name, _)| is_sound(name)) { + for (name, info) in objects.iter().filter(|(name, _)| wanted_asset(name)) { match wanted.iter_mut().find(|(n, _)| n == name) { Some(entry) => entry.1 = info, None => wanted.push((name, info)), } } + for name in required { + if !wanted.iter().any(|(n, _)| n == name) { + return Err(format!("{name} is missing from the asset index")); + } + } let mut total: u64 = 0; for (name, info) in &wanted { let hash = info @@ -125,7 +161,7 @@ pub fn sounds(root: &Path, minecraft: Option<&Path>, log: Log) -> Result Fixture { + Self::with_panorama(name, &PANORAMA) + } + + fn with_panorama(name: &str, panorama: &[&'static str]) -> Fixture { let dir = std::env::temp_dir().join(format!( "horizon-prepare-sounds-{name}-{}", std::process::id() @@ -159,12 +199,16 @@ mod tests { let _ = fs::remove_dir_all(&dir); let root = dir.join("horizon"); let minecraft = dir.join("minecraft"); - let objects: Vec<(&'static str, Vec)> = vec![ + let mut objects: Vec<(&'static str, Vec)> = vec![ ("minecraft/sounds.json", b"{\"a\": {}}".to_vec()), ("minecraft/sounds/ambient/cave1.ogg", b"OggS cave".to_vec()), ("minecraft/sounds/dig/stone1.ogg", b"OggS stone".to_vec()), ("minecraft/lang/fr_fr.json", b"{}".to_vec()), ]; + for &name in panorama { + // Distinct object bytes let the test catch swapped faces too. + objects.push((name, name.as_bytes().to_vec())); + } let mut index = String::from("{\"objects\": {"); for (i, (name, data)) in objects.iter().enumerate() { let hash = sha1_hex(data); @@ -243,6 +287,7 @@ mod tests { assert_eq!(&fs::read(target.join("assets").join(name)).unwrap(), data); } assert!(!target.join("assets/minecraft/lang").exists()); + assert!(!target.join("assets/minecraft/textures").exists()); assert_eq!( fs::read(target.join("asset-index.json")).unwrap(), fs::read(f.minecraft.join("assets/indexes/7.json")).unwrap() @@ -267,6 +312,60 @@ mod tests { assert!(f.run().unwrap_err().starts_with("Missing asset object")); } + #[test] + fn panorama_replaces_jar_placeholders_and_repairs_repeated_preparations() { + let f = Fixture::new("panorama"); + let target = f.root.join(".local/horizon-client/9.9"); + for _ in 0..2 { + // Full preparation extracts the JAR before importing the asset store. + for (name, _) in &f.objects[4..] { + let path = target.join("assets").join(name); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, b"1x1 gray placeholder").unwrap(); + } + assert_eq!( + panorama(&f.root, Some(&f.minecraft), &|_| {}).unwrap(), + target + ); + for (name, data) in &f.objects[4..] { + assert_eq!(&fs::read(target.join("assets").join(name)).unwrap(), data); + } + } + assert!(!target.join("assets/minecraft/sounds.json").exists()); + assert!(!target.join("assets/minecraft/lang").exists()); + } + + #[test] + fn panorama_objects_are_verified_before_replacing_placeholders() { + let f = Fixture::new("panorama-corrupt"); + fs::write(f.object(4), b"corrupt panorama").unwrap(); + let path = f + .root + .join(".local/horizon-client/9.9/assets") + .join(f.objects[4].0); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(&path, b"placeholder").unwrap(); + assert!(panorama(&f.root, Some(&f.minecraft), &|_| {}) + .unwrap_err() + .starts_with("Corrupt asset object")); + assert_eq!(fs::read(path).unwrap(), b"placeholder"); + fs::remove_file(f.object(4)).unwrap(); + assert!(panorama(&f.root, Some(&f.minecraft), &|_| {}) + .unwrap_err() + .starts_with("Missing asset object")); + } + + #[test] + fn panorama_requires_every_face_and_the_overlay_in_the_index() { + let f = Fixture::with_panorama("panorama-incomplete", &PANORAMA[..6]); + let error = panorama(&f.root, Some(&f.minecraft), &|_| {}).unwrap_err(); + assert_eq!( + error, + format!("{} is missing from the asset index", PANORAMA[6]) + ); + assert!(!f.root.join(".local/horizon-client/9.9/assets").exists()); + } + #[test] fn the_index_must_be_the_pinned_one() { let f = Fixture::new("index"); diff --git a/docs/native-client.md b/docs/native-client.md index 3081bac7c..f05199ba7 100644 --- a/docs/native-client.md +++ b/docs/native-client.md @@ -23,7 +23,12 @@ verifies it against the pinned checksums, runs vanilla's data generator and smal exporters against those jars, and extracts the jar's assets and data into ignored `.local/horizon-client/26.3/`. Sounds (about 380 MB) are copied from your launcher's asset store by `horizon-prepare sounds`, each file checked against the asset -index's SHA-1. Prepared resources are private; never commit them. +index's SHA-1. Preparation also replaces the JAR's gray 1×1 title panorama placeholders +with the full textures from that asset store. To repair an existing classic menu background +without rerunning the Java exporters, run `horizon-prepare panorama` (or +`cargo run --release -p horizon-prepare -- panorama` in a checkout). Pass +`--minecraft-dir PATH` when using a different Minecraft installation. +Prepared resources are private; never commit them. Preparation is `horizon-prepare` (`crates/horizon-prepare`, Rust): it needs no Python, only the JDK, for the small exporters that call Mojang's own code. Release folders ship it beside From c6634830d319da65d43c92c1861074949a95d793 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 14 Oct 2026 19:19:51 +0200 Subject: [PATCH 02/24] WIP: Microsoft account design note and RSA (not wired yet) Co-Authored-By: Claude Opus 5.5 --- crates/horizon-protocol/src/rsa.rs | 278 +++++++++++++++++++++++++++++ docs/microsoft-account.md | 177 ++++++++++++++++++ 2 files changed, 455 insertions(+) create mode 100644 crates/horizon-protocol/src/rsa.rs create mode 100644 docs/microsoft-account.md diff --git a/crates/horizon-protocol/src/rsa.rs b/crates/horizon-protocol/src/rsa.rs new file mode 100644 index 000000000..fd07db851 --- /dev/null +++ b/crates/horizon-protocol/src/rsa.rs @@ -0,0 +1,278 @@ +//! RSA for the online-mode login: the server's X.509 public key +//! (Crypt.byteToPublicKey) and PKCS#1 v1.5 encryption of the shared secret +//! and challenge (Crypt.encryptUsingKey, Java's "RSA" cipher = +//! RSA/ECB/PKCS1Padding). Modular exponentiation uses Montgomery +//! multiplication on 32-bit limbs; RSA moduli are always odd. +use crate::{Error, Result}; + +/// A non-negative integer, little-endian 32-bit limbs. +#[derive(Clone, Debug, PartialEq, Eq)] +struct Big(Vec); + +impl Big { + fn from_be_bytes(bytes: &[u8], limbs: usize) -> Self { + let mut v = vec![0u32; limbs]; + for (i, b) in bytes.iter().rev().enumerate() { + if *b != 0 { + v[i / 4] |= u32::from(*b) << (8 * (i % 4)); + } + } + Self(v) + } + fn to_be_bytes(&self, len: usize) -> Vec { + let mut out = vec![0u8; len]; + for i in 0..len.min(self.0.len() * 4) { + out[len - 1 - i] = (self.0[i / 4] >> (8 * (i % 4))) as u8; + } + out + } + fn bits(&self) -> usize { + self.0 + .iter() + .rposition(|&l| l != 0) + .map_or(0, |i| i * 32 + 32 - self.0[i].leading_zeros() as usize) + } + fn bit(&self, i: usize) -> bool { + self.0[i / 32] >> (i % 32) & 1 == 1 + } + fn ge(&self, other: &Self) -> bool { + for (a, b) in self.0.iter().rev().zip(other.0.iter().rev()) { + if a != b { + return a > b; + } + } + true + } + fn sub_assign(&mut self, other: &Self) { + let mut borrow = 0i64; + for (a, b) in self.0.iter_mut().zip(&other.0) { + let d = i64::from(*a) - i64::from(*b) - borrow; + borrow = i64::from(d < 0); + *a = d.rem_euclid(1 << 32) as u32; + } + } +} + +/// Montgomery arithmetic modulo an odd `n`. +struct Mont { + n: Big, + /// -n⁻¹ mod 2³². + n0: u32, + /// R² mod n, R = 2^(32·limbs). + r2: Big, +} + +impl Mont { + fn new(n: Big) -> Self { + let k = n.0.len(); + // Newton's iteration for n⁻¹ mod 2³². + let mut inv = 1u32; + for _ in 0..5 { + inv = inv.wrapping_mul(2u32.wrapping_sub(n.0[0].wrapping_mul(inv))); + } + // R² mod n by doubling 1 2·32·k times. + let mut r2 = Big(vec![0; k]); + r2.0[0] = 1; + for _ in 0..64 * k { + let carry = r2.0[k - 1] >> 31; + for i in (1..k).rev() { + r2.0[i] = r2.0[i] << 1 | r2.0[i - 1] >> 31; + } + r2.0[0] <<= 1; + if carry == 1 || r2.ge(&n) { + r2.sub_assign(&n); + } + } + Self { + n0: inv.wrapping_neg(), + n, + r2, + } + } + /// a·b·R⁻¹ mod n (CIOS). + fn mul(&self, a: &Big, b: &Big) -> Big { + let k = self.n.0.len(); + let mut t = vec![0u32; k + 2]; + for i in 0..k { + let mut carry = 0u64; + for j in 0..k { + let s = u64::from(t[j]) + u64::from(a.0[j]) * u64::from(b.0[i]) + carry; + t[j] = s as u32; + carry = s >> 32; + } + let s = u64::from(t[k]) + carry; + t[k] = s as u32; + t[k + 1] = (s >> 32) as u32; + let m = t[0].wrapping_mul(self.n0); + let mut carry = (u64::from(t[0]) + u64::from(m) * u64::from(self.n.0[0])) >> 32; + for j in 1..k { + let s = u64::from(t[j]) + u64::from(m) * u64::from(self.n.0[j]) + carry; + t[j - 1] = s as u32; + carry = s >> 32; + } + let s = u64::from(t[k]) + carry; + t[k - 1] = s as u32; + t[k] = t[k + 1] + (s >> 32) as u32; + } + let overflow = t[k] != 0; + let mut r = Big(t[..k].to_vec()); + if overflow || r.ge(&self.n) { + r.sub_assign(&self.n); + } + r + } + /// base^exp mod n, base < n. + fn pow(&self, base: &Big, exp: &Big) -> Big { + let k = self.n.0.len(); + let mut one = Big(vec![0; k]); + one.0[0] = 1; + let b = self.mul(base, &self.r2); + let mut x = self.mul(&one, &self.r2); + for i in (0..exp.bits()).rev() { + x = self.mul(&x, &x); + if exp.bit(i) { + x = self.mul(&x, &b); + } + } + self.mul(&x, &one) + } +} + +/// A minimal DER reader: (tag, contents) of the element at the front. +fn der(input: &[u8]) -> Result<(u8, &[u8], &[u8])> { + let bad = || Error::new("Malformed public key"); + let (&tag, rest) = input.split_first().ok_or_else(bad)?; + let (&first, mut rest) = rest.split_first().ok_or_else(bad)?; + let len = if first < 0x80 { + usize::from(first) + } else { + let n = usize::from(first & 0x7f); + if n == 0 || n > 4 || rest.len() < n { + return Err(bad()); + } + let len = rest[..n].iter().fold(0usize, |l, b| l << 8 | usize::from(*b)); + rest = &rest[n..]; + len + }; + if rest.len() < len { + return Err(bad()); + } + Ok((tag, &rest[..len], &rest[len..])) +} + +/// The DER of OID 1.2.840.113549.1.1.1 (rsaEncryption). +const RSA_ENCRYPTION: &[u8] = &[0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01]; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct RsaPublicKey { + /// Modulus and exponent, big-endian without leading zeros. + pub modulus: Vec, + pub exponent: Vec, +} + +fn strip(int: &[u8]) -> Vec { + let start = int.iter().position(|&b| b != 0).unwrap_or(int.len()); + int[start..].to_vec() +} + +impl RsaPublicKey { + /// X509EncodedKeySpec: SubjectPublicKeyInfo { AlgorithmIdentifier, BIT STRING RSAPublicKey }. + pub fn from_der(spki: &[u8]) -> Result { + let bad = || Error::new("Malformed public key"); + let (tag, body, _) = der(spki)?; + if tag != 0x30 { + return Err(bad()); + } + let (tag, algorithm, rest) = der(body)?; + let (oid_tag, oid, _) = der(algorithm)?; + if tag != 0x30 || oid_tag != 0x06 || oid != RSA_ENCRYPTION { + return Err(Error::new("Not an RSA public key")); + } + let (tag, bits, _) = der(rest)?; + if tag != 0x03 || bits.first() != Some(&0) { + return Err(bad()); + } + let (tag, key, _) = der(&bits[1..])?; + if tag != 0x30 { + return Err(bad()); + } + let (n_tag, n, rest) = der(key)?; + let (e_tag, e, _) = der(rest)?; + if n_tag != 0x02 || e_tag != 0x02 { + return Err(bad()); + } + let key = Self { + modulus: strip(n), + exponent: strip(e), + }; + if key.modulus.len() < 64 || key.modulus.last().is_none_or(|b| b & 1 == 0) { + return Err(bad()); + } + Ok(key) + } + /// Length of the modulus in bytes (and of every ciphertext). + pub fn size(&self) -> usize { + self.modulus.len() + } + /// The raw RSA operation m^e mod n on a `size()`-byte block. + fn apply(&self, block: &[u8], exponent: &[u8]) -> Vec { + let limbs = self.size().div_ceil(4); + let mont = Mont::new(Big::from_be_bytes(&self.modulus, limbs)); + let m = Big::from_be_bytes(block, limbs); + mont.pow(&m, &Big::from_be_bytes(exponent, limbs.max(exponent.len().div_ceil(4)))) + .to_be_bytes(self.size()) + } + /// RSAES-PKCS1-v1_5 (RFC 8017 7.2.1) with random non-zero padding. + pub fn encrypt(&self, message: &[u8]) -> Result> { + let k = self.size(); + if message.len() + 11 > k { + return Err(Error::new("Message too long for the RSA key")); + } + let mut block = vec![0u8; k]; + block[1] = 2; + let padding = &mut block[2..k - message.len() - 1]; + crate::crypto::random_bytes(padding)?; + for b in padding.iter_mut() { + while *b == 0 { + let mut one = [0u8]; + crate::crypto::random_bytes(&mut one)?; + *b = one[0]; + } + } + block[k - message.len()..].copy_from_slice(message); + Ok(self.apply(&block, &self.exponent)) + } +} + +#[cfg(test)] +pub(crate) mod tests { + use super::*; + + pub fn hex(s: &str) -> Vec { + (0..s.len()) + .step_by(2) + .map(|i| u8::from_str_radix(&s[i..i + 2], 16).unwrap()) + .collect() + } + + /// A 1024-bit test key made with `openssl genrsa 1024`. + pub const TEST_SPKI: &str = "30819f300d06092a864886f70d010101050003818d0030818902818100ab026074f92450a8f726f3895bb11176ca8f065f3100cd4143bac4f7d3674edcff95b41a0525d2365a549c106ec6685881b392177420fd31ff5c144ff11ba24311e751cd2c6b5d1817b6af6686a43c95d61243613005e6945b6093cd95223cec5e8856826da9d2ee1b323362ac1cebeab3659cbc45319a9b540dda816a4798ff0203010001"; + pub const TEST_N: &str = "ab026074f92450a8f726f3895bb11176ca8f065f3100cd4143bac4f7d3674edcff95b41a0525d2365a549c106ec6685881b392177420fd31ff5c144ff11ba24311e751cd2c6b5d1817b6af6686a43c95d61243613005e6945b6093cd95223cec5e8856826da9d2ee1b323362ac1cebeab3659cbc45319a9b540dda816a4798ff"; + pub const TEST_D: &str = "172bcb460e3c0d71d78b3f946d082105a78c99a06c535f7c6860f62f5e45b139e0a7b82f8e630188bbd49b10def1a351dac12a1a6371d4dce16ce893ac67c2247b9ee13e3a840abaf9ea685304558f1a93c4f354193f5713c3e53bd10dd275300db36e764fc081549afbd30cd00c31e6eb726720337a963913d96b50e4d8fd1"; + /// SHA256withRSA signature of "hello" with the test key (openssl pkeyutl), for chat signing. + pub const TEST_SIG_HELLO: &str = "0bc8716622e44f9bf72432045e91bf1b40a96aae3c402fa86262b83758db1c90d2ed16b9fa86f29af175f2e6eedb864bf8da2667a7ada2bf5433fba36c1951af0c356e45bd5f90fb905b9a08f33a0666c4968ccffbf32fda643d736deec66f82c75fe4a8075c7f2b8a6c0ca630e0ffe4805a1f1d672506b82fc188510fb4ef80"; + + #[test] + fn montgomery_matches_small_numbers() { + // 4^13 mod 497 = 445 (the classic example), on one limb. + let mont = Mont::new(Big(vec![497])); + assert_eq!(mont.pow(&Big(vec![4]), &Big(vec![13])), Big(vec![445])); + // Two limbs: (2^40 + 5)^3 mod (2^61 - 1). + let n = (1u128 << 61) - 1; + let m = Mont::new(Big(vec![n as u32, (n >> 32) as u32])); + let b = (1u128 << 40) + 5; + let expected = b * b % n * b % n; + let r = m.pow(&Big(vec![b as u32, (b >> 32) as u32]), &Big(vec![3, 0])); + assert_eq!(u128::from(r.0[0]) | u128::from(r.0[1]) << 32, expected); + } +} diff --git a/docs/microsoft-account.md b/docs/microsoft-account.md new file mode 100644 index 000000000..c992cd25f --- /dev/null +++ b/docs/microsoft-account.md @@ -0,0 +1,177 @@ +# Microsoft account sign-in and online-mode play + +Horizon signs players in with their Microsoft account in the launcher and joins online-mode +(authenticated) servers like vanilla 26.3 does. Offline profiles and offline/LAN play stay exactly as +they are. This note is the design, the status of each part and what Ludovic has to register. + +## What Ludovic registers (needs his accounts) + +Nothing below can be done by an agent: the app registrations belong to Ludovic. Until the client ID +is set, the launcher's sign-in shows "Microsoft sign-in is not configured yet" and everything else +works as before. + +1. **Azure app registration** (https://portal.azure.com → Microsoft Entra ID → App registrations → + New registration): + - Name: `Horizon` (shown to players on the Microsoft consent page). + - Supported account types: **Personal Microsoft accounts only** (Minecraft accounts are + consumer accounts; the launcher uses the `consumers` tenant). + - Redirect URI: none needed for the device-code flow. If the form insists, add a + "Mobile and desktop applications" redirect `https://login.microsoftonline.com/common/oauth2/nativeclient`. + - After creating it: Authentication → Advanced settings → **Allow public client flows: Yes** + (this enables the device-code flow; there is no client secret, Horizon is a public client). + - API permissions: none to add. The launcher requests the scopes `XboxLive.signin offline_access` + at sign-in time; `offline_access` gives the refresh token. + - Copy the **Application (client) ID** (a GUID). +2. **Minecraft API access** (Mojang): new Azure apps are refused by + `api.minecraftservices.com/authentication/login_with_xbox` (HTTP 403, "Invalid app registration") + until Mojang approves them. Apply with the form linked from https://aka.ms/mce-reviewappid + (Minecraft Java "App ID review"), giving the client ID above, the app name, the project URL + (https://github.com/ludovic111/horizon) and a short description ("open-source Minecraft Java + Edition client written in Rust; signs players in to join online-mode servers"). Approval takes + days to weeks; sign-in fails at the Minecraft step with "This app is not approved by Mojang yet" + until then. +3. **Where the ID goes**: + - Release builds: the GitHub repository variable (not a secret: client IDs are public) + `HORIZON_MSA_CLIENT_ID`; the launcher's build reads it with `option_env!` at compile time. + - Any build, at run time: the environment variable `HORIZON_MSA_CLIENT_ID` overrides the built-in + value (empty or unset = not configured). + +Never use another application's client ID (the official launcher's or another launcher's). + +## Flow (launcher) + +All requests use HTTPS and JSON except the two OAuth calls (form-encoded): + +1. **Device code**: `POST https://login.microsoftonline.com/consumers/oauth2/v2.0/devicecode` + (`client_id`, `scope=XboxLive.signin offline_access`). The launcher shows the `user_code` and + `verification_uri` (https://www.microsoft.com/link) with a copy button and opens the browser. +2. **Poll** `POST …/consumers/oauth2/v2.0/token` (`grant_type=urn:ietf:params:oauth:grant-type:device_code`) + every `interval` seconds; `authorization_pending` waits, `slow_down` adds 5 s, `authorization_declined`, + `expired_token` and `bad_verification_code` end the sign-in with a message. Result: the Microsoft + access token and refresh token. +3. **Xbox Live**: `POST https://user.auth.xboxlive.com/user/authenticate` with + `AuthMethod=RPS, SiteName=user.auth.xboxlive.com, RpsTicket=d=`, + `RelyingParty=http://auth.xboxlive.com`. Result: the XBL token and the user hash (`uhs`). +4. **XSTS**: `POST https://xsts.auth.xboxlive.com/xsts/authorize` with the XBL token, + `SandboxId=RETAIL`, `RelyingParty=rp://api.minecraftservices.com/`. The `XErr` codes become + messages: 2148916233 no Xbox profile yet, 2148916235 Xbox Live not available in the country, + 2148916236/2148916237 adult verification (South Korea), 2148916238 child account (needs a family). +5. **Minecraft**: `POST https://api.minecraftservices.com/authentication/login_with_xbox` + (`identityToken = "XBL3.0 x=;"`), the endpoint taken from the services discovery + document (authentication/loginXbox) like authlib does. Result: the Minecraft access token (24 h). +6. **Entitlements**: `GET https://api.minecraftservices.com/entitlements/mcstore`: the account must + own `game_minecraft` or `product_minecraft` (Game Pass included), else "This account doesn't own + Minecraft Java Edition". +7. **Profile**: `GET https://api.minecraftservices.com/minecraft/profile`: UUID, name, skins, capes. + 404 = owns the game but has no profile yet ("Create your Minecraft profile on minecraft.net first"). + +Refresh: the Minecraft token is renewed from the Microsoft refresh token (steps 2-5 with +`grant_type=refresh_token`) when it has less than an hour left, before every launch. A refused +refresh token (`invalid_grant`) asks the player to sign in again. Several accounts can be signed in; +one is selected. "Sign out" deletes the account's secrets from the keychain. + +## Token storage + +- Secrets (the Microsoft refresh token, the Minecraft access token and its expiry) go to the OS + keychain, one item per account: Keychain on macOS, Credential Manager on Windows, the Secret + Service (GNOME Keyring, KWallet) on Linux. Service name `dev.playhorizon.launcher`, account = the + Minecraft UUID. +- `accounts.json` in the launcher's data folder keeps only public data: UUID, name, skin URL, which + account is selected. Never a token. +- No keychain available (a Linux box without a Secret Service, a locked keychain): sign-in still + works for the session but nothing is saved, and the launcher says "No keychain available: you will + have to sign in again next time" (it never falls back to a plain file). +- Tokens never appear in logs, errors, `horizon-launcher` CLI output, MCP results or crash reports. + Requests are logged by endpoint name only. + +## Handing the session to the game + +Vanilla's launcher passes `--accessToken ` on the command line, where every user of the +machine can read it in the process list. Horizon keeps it out of argv: + +- The launcher writes `session-.json` (mode 0600 on Unix, created new, in the game home's + `sessions/` folder) with `{"name", "uuid", "access_token", "user_type": "msa", "xuid"}` and starts + the game with `--session-file PATH`. +- The game reads the file at start and deletes it at once; the token lives only in the game's memory. + A file older than two minutes is refused (and deleted), so a stale file can't be replayed. +- Without a session file the game is offline as today (`--name`, offline UUID). +- `HORIZON_SESSION_FILE` is the same as `--session-file` (development and harnesses). + +## Online-mode login (game) + +Vanilla's `ClientHandshakePacketListenerImpl.handleHello`, `Crypt` and authlib's +`MinecraftServicesSessionService.joinServer`: + +1. `ClientboundHelloPacket` (server id, X.509 RSA public key, challenge, should_authenticate). +2. Generate a random 16-byte AES key (the shared secret). +3. Server hash: SHA-1 over `serverId` (ISO-8859-1), the shared secret, the encoded public key; + `new BigInteger(digest).toString(16)` (signed two's complement hex, e.g. "Notch" → + `4ed1f46bbe04bc756bcb17c0c7ce3e4632f06a48`, "jeb_" → `-7c9d5b0044c130109a5d7b5fb5c317c02b4e28c1`). +4. If `should_authenticate`: `POST` the session service's `join` endpoint + `{"accessToken", "selectedProfile" (undashed UUID), "serverId": hash}`, the URL taken from the + services discovery document (`https://discovery.minecraftservices.com/minecraft/client`, fetched + once per game). Errors map like authlib's `MinecraftClientHttpException`: + `ForbiddenOperationException` or 401 → "Failed to log in: Invalid session (Try restarting your + game and the launcher)", `InsufficientPrivilegesException` → "Multiplayer is disabled…", + `multiplayer.access.banned` / `FORCED_USERNAME_CHANGE` → "You are banned from playing online", + 5xx or no network → "The authentication servers are currently not reachable…". Without a session + the game says "This server is in online mode. Sign in with your Microsoft account in the Horizon + launcher to join it." On a LAN server a failure is only logged (vanilla does the same). +5. Send `ServerboundKeyPacket` (the secret and the challenge, each RSA PKCS#1 v1.5 encrypted with + the server key), then AES/CFB8 (key = IV = the secret) both ways. + +`HORIZON_API_DISCOVERY` overrides the discovery URL, the counterpart of authlib's +`-Dminecraft.api.discovery.host`; it is how the harness points both the vanilla server and Horizon at +a local mock. + +## Skins and capes (part b) + +Profile properties (`textures`, base64 JSON) arrive in `ClientboundPlayerInfoUpdatePacket` for every +player and in the login profile for ourselves. Like authlib's `unpackTextures`, only URLs under the +discovery document's `profiles/getTexture` `validUris` (textures.minecraft.net) are fetched; skins +(classic/slim from the `metadata.model`), capes and elytra textures are downloaded over HTTPS on a +worker thread, cached on disk by texture hash (`assets/skins/xx/hash`, like vanilla's +`SkinManager`), converted from legacy 64×32 the way `SkinTextureDownloader` does and given to the +player renderer. Until a skin arrives the default skin for the UUID shows (as today). + +## Chat signing (part d) + +26.3's dedicated servers default to `enforce-secure-profile=true`. A client without a chat session +can join and play, but every chat message and signed command argument is refused with "Chat +disabled due to missing profile public key. Please try reconnecting." (`SignedMessageChain.Decoder.unsigned`). +To chat on such servers the game will: + +- fetch the profile key pair from the services `player/getCertificates` endpoint (Minecraft token); +- send `ServerboundChatSessionUpdatePacket` (random session UUID, key expiry, public key, Mojang's + key signature) after joining; +- sign each chat message and signable command argument with SHA256withRSA over vanilla's + `SignedMessageBody` layout and keep the last-seen message tracker and acknowledgements. + +Until part d lands, Horizon joins online servers but chat works only where +`enforce-secure-profile=false` (or the server can't validate keys). + +## Harnesses + +`tools/test_online_mode_parity.py` (dev only, needs no account): a local mock of the Minecraft +services (discovery document, `join`, `hasJoined`/`verify`, empty public keys) and a vanilla 26.3 +dedicated server in online mode started with `-Dminecraft.api.discovery.host=`. Horizon's +headless client (`HORIZON_NET_REPORT`) joins with a session file holding a mock token: the server +verifies the join through the mock with the hash it computed itself (so the RSA wrapping, the hash +and AES/CFB8 are all checked against vanilla's code), the player spawns, chats and runs `/list`. +Negative cases: a token the mock rejects (the client must show vanilla's "Invalid session" message) +and a client that skips the join (the server must say "Failed to verify username!"). + +Rust unit tests: server hash vectors (Notch, jeb_, simon), RSA wrapping round trip with a test key, +X.509 key parsing, AES/CFB8 vectors (already in `horizon-protocol`), the session file (permissions, +age, deletion), the error mapping. Launcher: the whole token chain against a local mock of the +Microsoft, Xbox and Minecraft endpoints, and the keychain abstraction with an in-memory backend. + +## PR plan + +- (a) Game: online-mode handshake, encryption, session join, session file, harness. *(this PR)* +- (c) Launcher: device-code sign-in, token chain, keychain, accounts UI, CLI/MCP (`account list`, + `account sign-in`, `account sign-out`, never tokens), session file handoff. +- (b) Game: skins and capes over HTTPS, the real names and skins in game. +- (d) Game: chat signing (profile keys, chat session, signed messages and commands). + +Each part ships on its own: online mode needs a session, which only (c) creates. From c8629f3378fec01fe30c0e32e01e93942f4dcbc5 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 14 Oct 2026 19:35:18 +0200 Subject: [PATCH 03/24] Protocol: RSA public keys and PKCS#1 encryption, server hash, secrets Co-Authored-By: Claude Opus 5.5 --- crates/horizon-protocol/Cargo.toml | 3 ++ crates/horizon-protocol/src/crypto.rs | 74 ++++++++++++++++++++++++++- crates/horizon-protocol/src/lib.rs | 1 + crates/horizon-protocol/src/rsa.rs | 43 ++++++++++++++++ 4 files changed, 119 insertions(+), 2 deletions(-) diff --git a/crates/horizon-protocol/Cargo.toml b/crates/horizon-protocol/Cargo.toml index 04bb00d5b..fad282080 100644 --- a/crates/horizon-protocol/Cargo.toml +++ b/crates/horizon-protocol/Cargo.toml @@ -10,6 +10,9 @@ description = "Horizon's Minecraft Java Edition 26.3 network protocol (version 7 horizon-world = { path = "../horizon-world" } flate2 = { version = "1.1.10", default-features = false, features = ["rust_backend"] } serde_json = "1.0.151" +# The shared secret and RSA padding (OS randomness) and the server hash. +getrandom = "0.3" +sha1 = "0.10" [lints] workspace = true diff --git a/crates/horizon-protocol/src/crypto.rs b/crates/horizon-protocol/src/crypto.rs index c55b003b5..b5b6fa447 100644 --- a/crates/horizon-protocol/src/crypto.rs +++ b/crates/horizon-protocol/src/crypto.rs @@ -1,7 +1,9 @@ //! Connection encryption (Crypt.getCipher: AES/CFB8/NoPadding with the shared //! secret as key and IV) and MD5 name-based UUIDs for offline-mode profiles -//! (UUIDUtil.createOfflinePlayerUUID). Only the AES forward cipher is needed: -//! CFB8 encrypts the shift register in both directions. +//! (UUIDUtil.createOfflinePlayerUUID), the online-mode server hash +//! (Crypt.digestData) and the shared secret. Only the AES forward cipher is +//! needed: CFB8 encrypts the shift register in both directions. +use sha1::{Digest, Sha1}; const SBOX: [u8; 256] = { // Generated from the AES field inverse and affine transform at compile time. @@ -138,6 +140,54 @@ impl Cfb8 { } } +/// Fill `out` with the operating system's cryptographic randomness. +pub fn random_bytes(out: &mut [u8]) -> crate::Result<()> { + getrandom::fill(out).map_err(|e| crate::Error::new(format!("No secure random source: {e}"))) +} + +/// Crypt.generateSecretKey: a random AES-128 key, the connection's shared secret. +pub fn generate_secret() -> crate::Result<[u8; 16]> { + let mut key = [0u8; 16]; + random_bytes(&mut key)?; + Ok(key) +} + +/// `new BigInteger(digest).toString(16)`: the digest read as a signed +/// two's-complement number, in lowercase hex without leading zeros. +pub fn java_hex_digest(digest: &[u8]) -> String { + let negative = digest.first().is_some_and(|b| b & 0x80 != 0); + let mut magnitude = digest.to_vec(); + if negative { + // Two's complement: invert and add one. + let mut carry = true; + for b in magnitude.iter_mut().rev() { + *b = !*b; + if carry { + let (v, c) = b.overflowing_add(1); + *b = v; + carry = c; + } + } + } + let hex: String = magnitude.iter().map(|b| format!("{b:02x}")).collect(); + let hex = hex.trim_start_matches('0'); + let hex = if hex.is_empty() { "0" } else { hex }; + if negative { format!("-{hex}") } else { hex.to_owned() } +} + +/// The server id sent to the session service when joining an online-mode +/// server: SHA-1 over the server id (ISO-8859-1), the shared secret and the +/// server's encoded public key, as a signed hex number. +pub fn server_hash(server_id: &str, secret: &[u8], public_key: &[u8]) -> String { + let mut sha = Sha1::new(); + // ISO-8859-1: characters above U+00FF become '?' like String.getBytes. + let latin1: Vec = server_id.chars().map(|c| u8::try_from(u32::from(c)).unwrap_or(b'?')).collect(); + sha.update(&latin1); + sha.update(secret); + sha.update(public_key); + java_hex_digest(&sha.finalize()) +} + /// MD5 (RFC 1321). pub fn md5(input: &[u8]) -> [u8; 16] { const S: [u32; 64] = [ @@ -256,6 +306,26 @@ mod tests { assert_eq!(data, plain); } + /// The digests of single names published with the protocol docs. + #[test] + fn server_hash_vectors() { + let hash = |name: &str| java_hex_digest(&Sha1::digest(name.as_bytes())); + assert_eq!(hash("Notch"), "4ed1f46bbe04bc756bcb17c0c7ce3e4632f06a48"); + assert_eq!(hash("jeb_"), "-7c9d5b0044c130109a5d7b5fb5c317c02b4e28c1"); + assert_eq!(hash("simon"), "88e16a1019277b15d58faf0541e11910eb756f6"); + // The three inputs are hashed in order: one update equals three. + assert_eq!(server_hash("", b"Not", b"ch"), hash("Notch")); + assert_eq!(java_hex_digest(&[0; 4]), "0"); + assert_eq!(java_hex_digest(&[0xff; 2]), "-1"); + assert_eq!(java_hex_digest(&[0x80, 0]), "-8000"); + } + + #[test] + fn secrets_are_random() { + let (a, b) = (generate_secret().unwrap(), generate_secret().unwrap()); + assert_ne!(a, b); + } + #[test] fn md5_and_offline_uuids() { assert_eq!(md5(b"").to_vec(), hex("d41d8cd98f00b204e9800998ecf8427e")); diff --git a/crates/horizon-protocol/src/lib.rs b/crates/horizon-protocol/src/lib.rs index 1f29637dd..e49031b77 100644 --- a/crates/horizon-protocol/src/lib.rs +++ b/crates/horizon-protocol/src/lib.rs @@ -12,6 +12,7 @@ pub mod ids; pub mod item; pub mod packets; pub mod registry; +pub mod rsa; pub mod servers; pub mod text; diff --git a/crates/horizon-protocol/src/rsa.rs b/crates/horizon-protocol/src/rsa.rs index fd07db851..cbc256c06 100644 --- a/crates/horizon-protocol/src/rsa.rs +++ b/crates/horizon-protocol/src/rsa.rs @@ -249,6 +249,7 @@ pub(crate) mod tests { use super::*; pub fn hex(s: &str) -> Vec { + let s = if s.len() % 2 == 1 { format!("0{s}") } else { s.to_owned() }; (0..s.len()) .step_by(2) .map(|i| u8::from_str_radix(&s[i..i + 2], 16).unwrap()) @@ -275,4 +276,46 @@ pub(crate) mod tests { let r = m.pow(&Big(vec![b as u32, (b >> 32) as u32]), &Big(vec![3, 0])); assert_eq!(u128::from(r.0[0]) | u128::from(r.0[1]) << 32, expected); } + + #[test] + fn parses_x509_public_keys() { + let key = RsaPublicKey::from_der(&hex(TEST_SPKI)).unwrap(); + assert_eq!(key.modulus, hex(TEST_N)); + assert_eq!(key.exponent, vec![1, 0, 1]); + assert_eq!(key.size(), 128); + assert!(RsaPublicKey::from_der(&hex(TEST_SPKI)[..100]).is_err()); + assert!(RsaPublicKey::from_der(b"not a key").is_err()); + } + + /// Encrypted with the public key, decrypted with the private exponent: + /// a PKCS#1 v1.5 type 2 block with non-zero padding around the message. + #[test] + fn pkcs1_round_trip() { + let key = RsaPublicKey::from_der(&hex(TEST_SPKI)).unwrap(); + let secret = [0x5au8; 16]; + let a = key.encrypt(&secret).unwrap(); + let b = key.encrypt(&secret).unwrap(); + assert_eq!(a.len(), 128); + assert_ne!(a, b, "padding is random"); + for c in [a, b] { + let block = key.apply(&c, &hex(TEST_D)); + assert_eq!(&block[..2], &[0, 2]); + let zero = 2 + block[2..].iter().position(|&b| b == 0).unwrap(); + assert_eq!(zero, 128 - 16 - 1); + assert_eq!(&block[zero + 1..], &secret); + } + assert!(key.encrypt(&[0; 118]).is_err()); + } + + /// An OpenSSL signature checked with the public exponent: the block ends + /// with SHA-256("hello"), so the modular arithmetic agrees with OpenSSL's. + #[test] + fn verifies_an_openssl_signature() { + let key = RsaPublicKey::from_der(&hex(TEST_SPKI)).unwrap(); + let block = key.apply(&hex(TEST_SIG_HELLO), &key.exponent); + assert_eq!(&block[..2], &[0, 1]); + assert!(block.ends_with(&hex( + "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824" + ))); + } } From 89b2ca64a9da151ab8876c28d095a5416658f5ed Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 14 Oct 2026 19:39:16 +0200 Subject: [PATCH 04/24] 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 --- Cargo.lock | 382 ++++++++++++++++++ crates/horizon-client/Cargo.toml | 2 + crates/horizon-client/src/auth.rs | 343 ++++++++++++++++ crates/horizon-client/src/game.rs | 15 +- crates/horizon-client/src/game/net_harness.rs | 7 +- crates/horizon-client/src/game/remote.rs | 5 +- crates/horizon-client/src/lib.rs | 1 + crates/horizon-client/src/net.rs | 74 +++- 8 files changed, 812 insertions(+), 17 deletions(-) create mode 100644 crates/horizon-client/src/auth.rs diff --git a/Cargo.lock b/Cargo.lock index 1e3919458..4694fb718 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -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" diff --git a/crates/horizon-client/Cargo.toml b/crates/horizon-client/Cargo.toml index b54424966..42841eecb 100644 --- a/crates/horizon-client/Cargo.toml +++ b/crates/horizon-client/Cargo.toml @@ -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). diff --git a/crates/horizon-client/src/auth.rs b/crates/horizon-client/src/auth.rs new file mode 100644 index 000000000..27339259f --- /dev/null +++ b/crates/horizon-client/src/auth.rs @@ -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, + 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", &"") + .finish() + } +} + +/// A UUID with or without dashes. +pub fn parse_uuid(text: &str) -> Option { + 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 { + 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 { + 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> = 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> { + 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, JoinError> { + static CACHE: Mutex>> = 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 { + 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); + } +} diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index a5cc64b1d..d9fbf97cc 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -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)) } } diff --git a/crates/horizon-client/src/game/net_harness.rs b/crates/horizon-client/src/game/net_harness.rs index d9bb6a74b..681a950b0 100644 --- a/crates/horizon-client/src/game/net_harness.rs +++ b/crates/horizon-client/src/game/net_harness.rs @@ -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 { diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 73edbaca6..ae6b810d4 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -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), diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index eae7dc596..d71d5c19f 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -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; diff --git a/crates/horizon-client/src/net.rs b/crates/horizon-client/src/net.rs index 94bc7c701..2e733c9ba 100644 --- a/crates/horizon-client/src/net.rs +++ b/crates/horizon-client/src/net.rs @@ -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) -> Self { + /// Start connecting in the background, as `auth`'s account when there is one. + pub fn connect( + address: &str, + name: &str, + auth: Option>, + view_distance: i8, + lang: Arc, + ) -> 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, 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, @@ -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( From ac97e9c0b9be8f3368a1a645a15a369d827c5204 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 14 Oct 2026 19:44:50 +0200 Subject: [PATCH 05/24] Harness: online-mode login against vanilla's server and a mock session service Co-Authored-By: Claude Opus 5.5 --- docs/microsoft-account.md | 19 ++- tools/test_online_mode_parity.py | 269 +++++++++++++++++++++++++++++++ 2 files changed, 284 insertions(+), 4 deletions(-) create mode 100644 tools/test_online_mode_parity.py diff --git a/docs/microsoft-account.md b/docs/microsoft-account.md index c992cd25f..41c73c594 100644 --- a/docs/microsoft-account.md +++ b/docs/microsoft-account.md @@ -116,10 +116,18 @@ Vanilla's `ClientHandshakePacketListenerImpl.handleHello`, `Crypt` and authlib's `multiplayer.access.banned` / `FORCED_USERNAME_CHANGE` → "You are banned from playing online", 5xx or no network → "The authentication servers are currently not reachable…". Without a session the game says "This server is in online mode. Sign in with your Microsoft account in the Horizon - launcher to join it." On a LAN server a failure is only logged (vanilla does the same). + launcher to join it." (Vanilla goes on after a failed join on LAN-discovered servers, which then + refuse the player anyway; Horizon stops at once.) 5. Send `ServerboundKeyPacket` (the secret and the challenge, each RSA PKCS#1 v1.5 encrypted with the server key), then AES/CFB8 (key = IV = the secret) both ways. +The connecting screen follows vanilla's states: "Connecting to the server..." until the encryption +request, "Logging in..." while joining the session service, "Encrypting...", then "Joining world...". +Code: `horizon-protocol` (`rsa.rs`, `crypto::server_hash`), `horizon-client` (`auth.rs`, `net.rs`). + +Horizon's own dedicated and LAN servers stay offline-mode (they don't verify players with the +session service); that is separate work. + `HORIZON_API_DISCOVERY` overrides the discovery URL, the counterpart of authlib's `-Dminecraft.api.discovery.host`; it is how the harness points both the vanilla server and Horizon at a local mock. @@ -153,8 +161,10 @@ Until part d lands, Horizon joins online servers but chat works only where ## Harnesses `tools/test_online_mode_parity.py` (dev only, needs no account): a local mock of the Minecraft -services (discovery document, `join`, `hasJoined`/`verify`, empty public keys) and a vanilla 26.3 -dedicated server in online mode started with `-Dminecraft.api.discovery.host=`. Horizon's +services (discovery document, `join`, `hasJoined`/`verify`, no public keys) and a vanilla 26.3 +dedicated server in online mode started with `-Dminecraft.api.discovery.host=` (authlib +10.0.77's only override: it replaces the whole discovery URL; the old `minecraft.api.session.host` +style properties are gone). Horizon's headless client (`HORIZON_NET_REPORT`) joins with a session file holding a mock token: the server verifies the join through the mock with the hash it computed itself (so the RSA wrapping, the hash and AES/CFB8 are all checked against vanilla's code), the player spawns, chats and runs `/list`. @@ -168,7 +178,8 @@ Microsoft, Xbox and Minecraft endpoints, and the keychain abstraction with an in ## PR plan -- (a) Game: online-mode handshake, encryption, session join, session file, harness. *(this PR)* +- (a) Game: online-mode handshake, encryption, session join, session file, harness (15/15 checks + against vanilla 26.3 on macOS). - (c) Launcher: device-code sign-in, token chain, keychain, accounts UI, CLI/MCP (`account list`, `account sign-in`, `account sign-out`, never tokens), session file handoff. - (b) Game: skins and capes over HTTPS, the real names and skins in game. diff --git a/tools/test_online_mode_parity.py b/tools/test_online_mode_parity.py new file mode 100644 index 000000000..45b4b3ac6 --- /dev/null +++ b/tools/test_online_mode_parity.py @@ -0,0 +1,269 @@ +#!/usr/bin/env python3 +"""Horizon's client joins vanilla's online-mode server, with no real account. + +A small mock of the Minecraft services (dev only: the discovery document and +the session service's join and hasJoined endpoints) stands in for Mojang's. +The pinned vanilla 26.3 dedicated server runs in online mode and finds the +mock through authlib's own override, `-Dminecraft.api.discovery.host`; +Horizon's client finds it through `HORIZON_API_DISCOVERY` and signs in with a +session file holding a mock token, as the launcher hands it over. + +The client must answer the server's encryption request: generate the shared +secret, hash the server id with it and the server's public key, join through +the mock, RSA-wrap the secret and the challenge for the server, then encrypt +the connection with AES/CFB8. The server decrypts the secret with its private +key, computes the hash itself and asks the mock whether the player joined +with that hash: so vanilla's own code checks the hash, the RSA wrapping and +the cipher. Then the client plays as in the dedicated-server harness (stands +in the world with its chunks, chats, runs /list, leaves). + +Also checked, with vanilla's messages: +- a token the session service rejects ("Failed to log in: Invalid session"); +- a join the session service forgets (the server: "Failed to verify username!"); +- no account at all (the client refuses before joining). + +Chat is unsigned here: the mock serves no Mojang public keys, so the server +can't validate profile keys and doesn't enforce secure chat. +""" +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +import json +import os +from pathlib import Path +import platform +import shutil +import subprocess +import sys +import threading +import urllib.parse + +try: + from . import lab, oracle_harness as oh, test_rust_parity as base + from .test_dedicated_server_parity import Server, free_port +except ImportError: + import lab + import oracle_harness as oh + import test_rust_parity as base + from test_dedicated_server_parity import Server, free_port + +NAME = 'online-mode-parity' +PLAYER = 'Tester' +PLAYER_UUID = '5f3c1e6a2b9d4c7e8a1f0b2c3d4e5f60' +GOOD, FORGET, BAD = 'mock-token-good', 'mock-token-forget', 'mock-token-rejected' +PROPERTIES = { + 'online-mode': 'true', + 'white-list': 'false', + 'level-seed': '12345', + 'view-distance': '4', + 'simulation-distance': '4', + 'spawn-protection': '0', + 'max-players': '5', + 'pause-when-empty-seconds': '-1', +} + + +def dashed(u): + return f'{u[:8]}-{u[8:12]}-{u[12:16]}-{u[16:20]}-{u[20:]}' + + +class Services: + """The mock session service. Records what was asked, never the tokens.""" + + def __init__(self): + self.joined = {} + self.log = [] + self.lock = threading.Lock() + services = self + + class Handler(BaseHTTPRequestHandler): + def log_message(self, *args): + pass + + def reply(self, status, body=None): + data = b'' if body is None else json.dumps(body).encode() + self.send_response(status) + if body is not None: + self.send_header('Content-Type', 'application/json') + self.send_header('Content-Length', str(len(data))) + self.end_headers() + self.wfile.write(data) + + def do_GET(self): + url = urllib.parse.urlparse(self.path) + query = dict(urllib.parse.parse_qsl(url.query)) + if url.path == '/minecraft/client': + return self.reply(200, services.discovery()) + if url.path == '/session/minecraft/hasJoined': + with services.lock: + ok = services.joined.get(query.get('username')) == query.get('serverId') + services.log.append(('verify', query.get('username'), query.get('serverId'), ok)) + if ok: + return self.reply(200, {'id': PLAYER_UUID, 'name': query['username'], 'properties': []}) + return self.reply(204) + self.reply(404, {'error': 'NotFound', 'path': url.path}) + + def do_POST(self): + body = json.loads(self.rfile.read(int(self.headers.get('Content-Length', 0))) or b'{}') + if self.path != '/session/minecraft/join': + return self.reply(404, {'error': 'NotFound'}) + token, profile, server_id = body.get('accessToken'), body.get('selectedProfile'), body.get('serverId') + accepted = token in (GOOD, FORGET) and profile == PLAYER_UUID + with services.lock: + services.log.append(('join', profile, server_id, accepted)) + if token == GOOD and accepted: + services.joined[PLAYER] = server_id + if not accepted: + return self.reply(403, {'error': 'ForbiddenOperationException', 'errorMessage': 'Invalid token'}) + self.reply(204) + + self.server = ThreadingHTTPServer(('127.0.0.1', 0), Handler) + self.url = f'http://127.0.0.1:{self.server.server_address[1]}' + threading.Thread(target=self.server.serve_forever, daemon=True).start() + + def discovery(self): + def endpoints(**names): + return {'endpoints': {k: {'uri': self.url + v} for k, v in names.items()}} + return {'environment': 'mock', 'product': 'minecraft', 'discovery': { + 'authentication': endpoints(getPublicKeys='/publickeys'), + 'session': endpoints(join='/session/minecraft/join', verify='/session/minecraft/hasJoined', + getProfileById='/session/minecraft/profile/{profileId}'), + 'player': {'endpoints': {}}, + 'profiles': {'endpoints': {'getTexture': {'validUris': [self.url + '/texture/{textureId}']}}}, + 'telemetry': {'endpoints': {}}, + }} + + def take_log(self): + with self.lock: + log, self.log = self.log, [] + return log + + def stop(self): + self.server.shutdown() + + +def session_file(directory, token): + """What the launcher writes: owner-only, read once by the game.""" + path = directory / 'session.json' + path.unlink(missing_ok=True) + fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) + with os.fdopen(fd, 'w') as f: + json.dump({'name': PLAYER, 'uuid': dashed(PLAYER_UUID), 'access_token': token, 'user_type': 'msa'}, f) + return path + + +def run_client(binary, build, port, label, token, discovery): + directory = build / f'client-{label}' + shutil.rmtree(directory, ignore_errors=True) + directory.mkdir() + report = directory / 'report.json' + env = dict(os.environ, HORIZON_NO_AUDIO='1', HORIZON_NET_REPORT=str(report), HORIZON_API_DISCOVERY=discovery) + command = [binary, '--resources', lab.LOCAL / 'horizon-client/26.3', '--render-distance', 2, + '--server', f'127.0.0.1:{port}', '--name', PLAYER] + if token: + command += ['--session-file', session_file(directory, token)] + with (build / f'client-{label}.log').open('w') as log: + subprocess.run([str(c) for c in command], cwd=directory, env=env, stdout=log, stderr=subprocess.STDOUT, + timeout=300, check=True) + got = json.loads(report.read_text()) + got['session file left'] = (directory / 'session.json').exists() + return got + + +def main(): + lock, jars, libraries = base.verify_artifacts() + build = lab.LOCAL / NAME + build.mkdir(parents=True, exist_ok=True) + report = build / 'report.json' + report.unlink(missing_ok=True) + oh.run_logged(['cargo', 'build', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], build, + 'compile-rust') + metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], + cwd=lab.ROOT, text=True)) + binary = Path(metadata['target_directory']) / 'release' / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client') + dependencies = os.pathsep.join(map(str, [jars['server'], *libraries])) + + services = Services() + discovery = services.url + '/minecraft/client' + port = free_port() + directory = build / 'server' + shutil.rmtree(directory, ignore_errors=True) + directory.mkdir() + props = dict(PROPERTIES, **{'server-port': str(port)}) + (directory / 'server.properties').write_text(''.join(f'{k}={v}\n' for k, v in props.items())) + (directory / 'eula.txt').write_text('eula=true\n') + command = ['java', '-Xmx2g', '-Duser.timezone=UTC', f'-Dminecraft.api.discovery.host={discovery}', + '-cp', dependencies, 'net.minecraft.server.Main', 'nogui'] + server = Server(command, directory, 'vanilla-online') + checks = [] + + def check(label, actual, expected): + checks.append(f'{label}: ' + ('ok' if actual == expected else f'expected {expected!r}, got {actual!r}')) + + try: + server.wait_for(r'Done \(', timeout=600) + services.take_log() + + # 1. Signed in: the full encrypted handshake, then play. + got = run_client(binary, build, port, 'signed-in', GOOD, discovery) + server.wait_for(r'Tester left the game', timeout=30) + log = services.take_log() + joins = [e for e in log if e[0] == 'join'] + verifies = [e for e in log if e[0] == 'verify'] + check('signed-in: connected throughout', got['error'], None) + check('signed-in: joined the session service once', [(e[1], e[3]) for e in joins], [(PLAYER_UUID, True)]) + check('signed-in: server verified the same hash', + [(e[1], e[2], e[3]) for e in verifies], [(PLAYER, joins[0][2] if joins else None, True)]) + check('signed-in: own chat shown', any(' hello from the horizon client' in c for c in got['chat']), True) + check('signed-in: /list reply shown', + any('There are 1 of a max of 5 players online: Tester' in c for c in got['chat']), True) + check('signed-in: chunks received', got['chunks'] > 0, True) + check('signed-in: session file deleted', got['session file left'], False) + lines = '\n'.join(server.lines) + check('signed-in: server log', [k for k in [f'UUID of player Tester is {dashed(PLAYER_UUID)}', + 'Tester joined the game', + ' hello from the horizon client', + 'Tester left the game'] if k in lines], [ + f'UUID of player Tester is {dashed(PLAYER_UUID)}', 'Tester joined the game', + ' hello from the horizon client', 'Tester left the game']) + + # 2. A token the session service rejects: vanilla's message, no key sent. + mark = len(server.lines) + got = run_client(binary, build, port, 'rejected', BAD, discovery) + check('rejected token: client message', got['error'], + 'disconnected: Failed to log in: Invalid session (Try restarting your game and the launcher)') + check('rejected token: no verification', [e[0] for e in services.take_log()], ['join']) + + # 3. The session service forgets the join: the server refuses the player. + got = run_client(binary, build, port, 'forgotten', FORGET, discovery) + server.wait_for(r'Failed to verify username', timeout=30) + check('forgotten join: client message', got['error'], 'disconnected: Failed to verify username!') + check('forgotten join: server verified and refused', + [(e[0], e[3]) for e in services.take_log()], [('join', True), ('verify', False)]) + + # 4. No account: refused by the client before anything is sent to the services. + got = run_client(binary, build, port, 'no-account', None, discovery) + check('no account: client message', got['error'] or '', 'disconnected: This server is in online mode. ' + 'Sign in with your Microsoft account in the Horizon launcher to join it.') + check('no account: no service calls', services.take_log(), []) + check('no player joined after the first', 'joined the game' in '\n'.join(server.lines[mark:]), False) + finally: + server.stop() + services.stop() + + for line in checks: + print(line) + failed = [c for c in checks if not c.endswith(': ok')] + if failed: + raise AssertionError(f'{len(failed)} of {len(checks)} checks failed (logs in {build})') + lab.write_json(report, dict( + schema=1, minecraft=lock['minecraft']['version'], platform=platform.platform(), + java=subprocess.check_output(['java', '--version'], text=True).splitlines()[0], checks=len(checks), + scope='Online-mode login against vanilla\'s dedicated server and a mock session service: server hash, ' + 'RSA key packet, AES/CFB8, session join and verify, play; rejected token, forgotten join, no account.')) + print(f'online mode: {len(checks)} checks ok') + + +if __name__ == '__main__': + try: + main() + except AssertionError as error: + sys.exit(f'{NAME}: {error}') From 6957d74742637cbf10e399b64218973b87378f7e Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 14 Oct 2026 19:48:05 +0200 Subject: [PATCH 06/24] docs: Minecraft login endpoint Co-Authored-By: Claude Opus 5.5 --- docs/microsoft-account.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/docs/microsoft-account.md b/docs/microsoft-account.md index 41c73c594..61b402211 100644 --- a/docs/microsoft-account.md +++ b/docs/microsoft-account.md @@ -57,8 +57,7 @@ All requests use HTTPS and JSON except the two OAuth calls (form-encoded): messages: 2148916233 no Xbox profile yet, 2148916235 Xbox Live not available in the country, 2148916236/2148916237 adult verification (South Korea), 2148916238 child account (needs a family). 5. **Minecraft**: `POST https://api.minecraftservices.com/authentication/login_with_xbox` - (`identityToken = "XBL3.0 x=;"`), the endpoint taken from the services discovery - document (authentication/loginXbox) like authlib does. Result: the Minecraft access token (24 h). + (`identityToken = "XBL3.0 x=;"`). Result: the Minecraft access token (24 h). 6. **Entitlements**: `GET https://api.minecraftservices.com/entitlements/mcstore`: the account must own `game_minecraft` or `product_minecraft` (Game Pass included), else "This account doesn't own Minecraft Java Edition". From 0acd686720c6a02c9c916533856357cd0f7c1e1d Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 14 Oct 2026 19:55:56 +0200 Subject: [PATCH 07/24] rustfmt Co-Authored-By: Claude Opus 5.5 --- crates/horizon-protocol/src/crypto.rs | 11 +++++++++-- crates/horizon-protocol/src/rsa.rs | 17 +++++++++++++---- 2 files changed, 22 insertions(+), 6 deletions(-) diff --git a/crates/horizon-protocol/src/crypto.rs b/crates/horizon-protocol/src/crypto.rs index b5b6fa447..bd0244b07 100644 --- a/crates/horizon-protocol/src/crypto.rs +++ b/crates/horizon-protocol/src/crypto.rs @@ -172,7 +172,11 @@ pub fn java_hex_digest(digest: &[u8]) -> String { let hex: String = magnitude.iter().map(|b| format!("{b:02x}")).collect(); let hex = hex.trim_start_matches('0'); let hex = if hex.is_empty() { "0" } else { hex }; - if negative { format!("-{hex}") } else { hex.to_owned() } + if negative { + format!("-{hex}") + } else { + hex.to_owned() + } } /// The server id sent to the session service when joining an online-mode @@ -181,7 +185,10 @@ pub fn java_hex_digest(digest: &[u8]) -> String { pub fn server_hash(server_id: &str, secret: &[u8], public_key: &[u8]) -> String { let mut sha = Sha1::new(); // ISO-8859-1: characters above U+00FF become '?' like String.getBytes. - let latin1: Vec = server_id.chars().map(|c| u8::try_from(u32::from(c)).unwrap_or(b'?')).collect(); + let latin1: Vec = server_id + .chars() + .map(|c| u8::try_from(u32::from(c)).unwrap_or(b'?')) + .collect(); sha.update(&latin1); sha.update(secret); sha.update(public_key); diff --git a/crates/horizon-protocol/src/rsa.rs b/crates/horizon-protocol/src/rsa.rs index cbc256c06..57443e4fd 100644 --- a/crates/horizon-protocol/src/rsa.rs +++ b/crates/horizon-protocol/src/rsa.rs @@ -150,7 +150,9 @@ fn der(input: &[u8]) -> Result<(u8, &[u8], &[u8])> { if n == 0 || n > 4 || rest.len() < n { return Err(bad()); } - let len = rest[..n].iter().fold(0usize, |l, b| l << 8 | usize::from(*b)); + let len = rest[..n] + .iter() + .fold(0usize, |l, b| l << 8 | usize::from(*b)); rest = &rest[n..]; len }; @@ -219,8 +221,11 @@ impl RsaPublicKey { let limbs = self.size().div_ceil(4); let mont = Mont::new(Big::from_be_bytes(&self.modulus, limbs)); let m = Big::from_be_bytes(block, limbs); - mont.pow(&m, &Big::from_be_bytes(exponent, limbs.max(exponent.len().div_ceil(4)))) - .to_be_bytes(self.size()) + mont.pow( + &m, + &Big::from_be_bytes(exponent, limbs.max(exponent.len().div_ceil(4))), + ) + .to_be_bytes(self.size()) } /// RSAES-PKCS1-v1_5 (RFC 8017 7.2.1) with random non-zero padding. pub fn encrypt(&self, message: &[u8]) -> Result> { @@ -249,7 +254,11 @@ pub(crate) mod tests { use super::*; pub fn hex(s: &str) -> Vec { - let s = if s.len() % 2 == 1 { format!("0{s}") } else { s.to_owned() }; + let s = if s.len() % 2 == 1 { + format!("0{s}") + } else { + s.to_owned() + }; (0..s.len()) .step_by(2) .map(|i| u8::from_str_radix(&s[i..i + 2], 16).unwrap()) From f38e8cc393214658641672f62d0a3797fd4008b9 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 14 Oct 2026 19:57:34 +0200 Subject: [PATCH 08/24] Skins over HTTPS: fetch textures with ureq (rustls) Players' skins on online servers come from https://textures.minecraft.net; the old plain-HTTP fetch left everyone with their default skin. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/skins.rs | 96 +++++++++++++++--------------- 1 file changed, 47 insertions(+), 49 deletions(-) diff --git a/crates/horizon-client/src/skins.rs b/crates/horizon-client/src/skins.rs index ef8d575c3..c47c9d47f 100644 --- a/crates/horizon-client/src/skins.rs +++ b/crates/horizon-client/src/skins.rs @@ -246,9 +246,8 @@ pub fn process_legacy_skin(width: u32, height: u32, rgba: &[u8]) -> Option/<2 hex>/`) or over HTTP, keeping each one -/// by kind and hash as vanilla's `TextureCache`s do. Plain HTTP only: an -/// `https` texture that isn't cached fails, and the player keeps their -/// default skin. +/// by kind and hash as vanilla's `TextureCache`s do. A texture that can't +/// be fetched fails, and the player keeps their default skin. pub struct Downloader { root: std::path::PathBuf, states: std::collections::HashMap<(Kind, String), Download>, @@ -318,53 +317,23 @@ impl Downloader { } } -/// A plain HTTP/1.1 GET; the body of a 2xx answer. +/// A GET over HTTP or HTTPS (textures.minecraft.net serves both; vanilla +/// uses https): the body of a 2xx answer, 16 MiB at most, after redirects. fn http_get(url: &str) -> Option> { - use std::io::{Read, Write}; - let rest = url.strip_prefix("http://")?; - let (authority, path) = rest.split_at(rest.find('/').unwrap_or(rest.len())); - let path = if path.is_empty() { "/" } else { path }; - let path = &path[..path.find('#').unwrap_or(path.len())]; - let host = authority.split(':').next()?; - let address = if authority.contains(':') { - authority.to_owned() - } else { - format!("{authority}:80") - }; - let timeout = std::time::Duration::from_secs(15); - let addr = std::net::ToSocketAddrs::to_socket_addrs(&address) - .ok()? - .next()?; - let mut stream = std::net::TcpStream::connect_timeout(&addr, timeout).ok()?; - stream.set_read_timeout(Some(timeout)).ok()?; - write!( - stream, - "GET {path} HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\nUser-Agent: Java\r\n\r\n" - ) - .ok()?; - let mut response = Vec::new(); - stream.take(16 << 20).read_to_end(&mut response).ok()?; - let split = response.windows(4).position(|w| w == b"\r\n\r\n")?; - let head = String::from_utf8_lossy(&response[..split]).to_ascii_lowercase(); - let mut body = response[split + 4..].to_vec(); - let status: u32 = head.split_whitespace().nth(1)?.parse().ok()?; - if status / 100 != 2 { - return None; - } - if head.contains("transfer-encoding: chunked") { - let (mut out, mut at) = (Vec::new(), 0); - loop { - let end = at + body[at..].windows(2).position(|w| w == b"\r\n")?; - let line = String::from_utf8_lossy(&body[at..end]); - let size = usize::from_str_radix(line.split(';').next()?.trim(), 16).ok()?; - if size == 0 { - break; - } - out.extend_from_slice(body.get(end + 2..end + 2 + size)?); - at = end + 4 + size; - } - body = out; - } + use std::io::Read; + let response = ureq::AgentBuilder::new() + .timeout(std::time::Duration::from_secs(15)) + .user_agent("Java") + .build() + .get(url) + .call() + .ok()?; + let mut body = Vec::new(); + response + .into_reader() + .take(16 << 20) + .read_to_end(&mut body) + .ok()?; Some(body) } @@ -424,6 +393,35 @@ pub fn sha1(data: &[u8]) -> [u8; 20] { #[cfg(test)] mod tests { + /// Textures come over plain HTTP too (a local server here; https is the + /// same request through rustls), and only 2xx answers count. + #[test] + fn http_get_reads_2xx_bodies() { + use std::io::{BufRead, BufReader, Write}; + let listener = std::net::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().take(2) { + let mut stream = stream.unwrap(); + let mut line = String::new(); + let mut reader = BufReader::new(stream.try_clone().unwrap()); + reader.read_line(&mut line).unwrap(); + while reader.read_line(&mut String::new()).unwrap() > 2 {} + let reply: &[u8] = if line.contains("/texture/abc") { + b"HTTP/1.1 200 OK\r\nContent-Length: 4\r\nConnection: close\r\n\r\nPNG!" + } else { + b"HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n" + }; + stream.write_all(reply).unwrap(); + } + }); + assert_eq!( + http_get(&format!("{base}/texture/abc")), + Some(b"PNG!".to_vec()) + ); + assert_eq!(http_get(&format!("{base}/texture/missing")), None); + } + use super::*; #[test] From 82bee83dc5176ad01bd941cf8731e345e1ca9adf Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 14 Oct 2026 19:54:48 +0200 Subject: [PATCH 09/24] Launcher: Microsoft account sign-in, keychain and the game's session Device-code OAuth, Xbox Live, XSTS, Minecraft login, ownership and profile; secrets in the OS keychain (oo7 on Linux, keyring on macOS/Windows), accounts.json without tokens; Settings account rows, 'Playing as' on the Play page; CLI 'account' and MCP account tools; the game gets a 0600 session file it deletes. Client ID is configuration (HORIZON_MSA_CLIENT_ID), empty = not configured. Co-Authored-By: Claude Opus 5.5 --- launcher/Cargo.lock | 42 +- launcher/Cargo.toml | 12 + launcher/src/account.rs | 815 ++++++++++++++++++++++++++++++++++ launcher/src/account/tests.rs | 410 +++++++++++++++++ launcher/src/backend.rs | 12 +- launcher/src/cli.rs | 97 ++++ launcher/src/lib.rs | 1 + launcher/src/main.rs | 263 ++++++++++- launcher/src/mcp.rs | 73 +++ 9 files changed, 1717 insertions(+), 8 deletions(-) create mode 100644 launcher/src/account.rs create mode 100644 launcher/src/account/tests.rs 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(); From 324eb2836c588fc40412e463845c92070b5d02de Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 14 Oct 2026 19:58:02 +0200 Subject: [PATCH 10/24] Launcher README: Microsoft accounts Co-Authored-By: Claude Opus 5.5 --- launcher/README.md | 27 ++++++++++++++++++++++++--- 1 file changed, 24 insertions(+), 3 deletions(-) diff --git a/launcher/README.md b/launcher/README.md index f77d345d2..b70b4be82 100644 --- a/launcher/README.md +++ b/launcher/README.md @@ -70,9 +70,14 @@ The same binary is a command-line tool; without a subcommand it opens the window horizon-launcher menu-style [horizon|classic] show or set the game's menu style horizon-launcher update [--check] Horizon and the launcher horizon-launcher logs [--lines N] [--crash] the end of the game's log, or its newest crash report + horizon-launcher account [list] the Microsoft accounts signed in (* = plays) + horizon-launcher account sign-in sign in in your browser with a code + horizon-launcher account sign-out + horizon-launcher account select play as this account + horizon-launcher account offline play without an account `--json` prints JSON where there is something to report (`versions`, `install`, `notes`, -`next`, `links`, `menu-style`, `update --check`, `logs`). Errors go to stderr with exit code 1. `server` runs in the terminal, +`next`, `links`, `menu-style`, `update --check`, `logs`, `account`). Errors go to stderr with exit code 1. `server` runs in the terminal, so lines you type reach its console. `HORIZON_LAUNCHER_HOME` replaces the data folder (for scripts and tests). @@ -84,13 +89,29 @@ scripts and tests). (with the full path to the binary if it is not on your `PATH`). Its tools: `list_versions`, `install_version`, `remove_version`, `prepare_resources`, `launch_client`, `start_server`, -`server_command`, `server_log`, `stop_server`, `patch_notes`, `links`, `menu_style`, `logs` and -`check_updates`. +`server_command`, `server_log`, `stop_server`, `patch_notes`, `links`, `menu_style`, `logs`, +`check_updates`, `accounts`, `sign_in` (returns the link and code for the player; the sign-in +finishes in the background), `sign_out` and `select_account`. A server started through MCP stops (cleanly, with `stop`) when the session ends. Starting one needs `accept_eula`, which an agent should only pass with the player's consent. The window, the command line and the MCP server all call the same core, `src/backend.rs`. +## Microsoft accounts + +Settings → Accounts signs in a Microsoft account to play on online-mode servers under your own +name and skin: the launcher shows a code, you enter it at microsoft.com/link, and the launcher +checks that the account owns Minecraft: Java Edition. The Play page says who plays ("Playing as"); +without an account the game plays offline, as before. Tokens live in the system keychain (Keychain, +Credential Manager, or the Secret Service on Linux), never in a file, a log or the command line; +`accounts.json` in the data folder keeps only names and UUIDs. Without a keychain you stay signed +in until the launcher closes. When the game starts, it gets the session in a private file it +deletes as soon as it has read it. Sign out removes the tokens. + +Sign-in needs Horizon's own Azure app registration: its client ID is built in from +`HORIZON_MSA_CLIENT_ID` (and `HORIZON_MSA_CLIENT_ID` at run time overrides it; empty = not +configured). How it works: [docs/microsoft-account.md](../docs/microsoft-account.md). + ## Logs and crash reports The game writes its log to `logs/latest.log` in the game folder (`HORIZON_HOME`, else From 6bed9b92caac62e29a1e462b9123d6ac321cf024 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 14 Oct 2026 19:58:17 +0200 Subject: [PATCH 11/24] launcher.yml: build in HORIZON_MSA_CLIENT_ID from the repository variable Co-Authored-By: Claude Opus 5.5 --- .github/workflows/launcher.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.github/workflows/launcher.yml b/.github/workflows/launcher.yml index db8c5fac6..50a9ca9ca 100644 --- a/.github/workflows/launcher.yml +++ b/.github/workflows/launcher.yml @@ -33,6 +33,9 @@ jobs: runs-on: ${{ matrix.os }} env: RUSTFLAGS: ${{ matrix.rustflags }} + # Horizon's Azure app for Microsoft sign-in (docs/microsoft-account.md): a repository + # variable, not a secret. Unset, the launcher says sign-in is not configured. + HORIZON_MSA_CLIENT_ID: ${{ vars.HORIZON_MSA_CLIENT_ID }} defaults: run: working-directory: launcher From d4e0dc49177a10d28bbddc4f79720ade32fdfe24 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 14 Oct 2026 20:07:47 +0200 Subject: [PATCH 12/24] Settings subtitle mentions accounts Co-Authored-By: Claude Opus 5.5 --- launcher/src/main.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/launcher/src/main.rs b/launcher/src/main.rs index b3fade865..c81256b18 100644 --- a/launcher/src/main.rs +++ b/launcher/src/main.rs @@ -1843,7 +1843,7 @@ impl Launcher { .gap(px(24.)) .child(page_header( "Settings", - "Updates, menus, and the launcher itself.", + "Accounts, updates, menus, and the launcher itself.", &t, )) .child( From 8987369b07db03fd98e825b40071c3aed663775c Mon Sep 17 00:00:00 2001 From: rdbtCVS <87152661+rdbtCVS@users.noreply.github.com> Date: Wed, 14 Oct 2026 19:09:42 +0100 Subject: [PATCH 13/24] Fix inventory banner face depth ordering --- crates/horizon-client/src/item_render/gui.rs | 138 ++++++++++++++---- .../src/item_render/gui/depth.rs | 119 +++++++++++++++ 2 files changed, 229 insertions(+), 28 deletions(-) create mode 100644 crates/horizon-client/src/item_render/gui/depth.rs diff --git a/crates/horizon-client/src/item_render/gui.rs b/crates/horizon-client/src/item_render/gui.rs index bbdb2cb02..9456b26e4 100644 --- a/crates/horizon-client/src/item_render/gui.rs +++ b/crates/horizon-client/src/item_render/gui.rs @@ -10,6 +10,8 @@ use crate::hud::{HudBatch, Rect}; use glam::{EulerRot, Mat4, Vec2, Vec3}; use std::{collections::HashMap, f32::consts::PI}; +mod depth; + /// `Lighting.DIFFUSE_LIGHT_0` and `DIFFUSE_LIGHT_1`. fn diffuse_lights() -> (Vec3, Vec3) { ( @@ -177,35 +179,19 @@ fn draw_quads( rect: [f32; 4], time: f32, ) { - // Back-face culling: front faces wind counter-clockwise on screen with y up. - let mut visible: Vec<(f32, usize)> = quads - .iter() - .enumerate() - .filter(|(_, q)| { - let p = q.pos.map(|v| Vec2::new(v.x, -v.y)); - let area: f32 = (0..4) - .map(|i| { - let (a, b) = (p[i], p[(i + 1) % 4]); - a.x * b.y - b.x * a.y - }) - .sum(); - area > 0.0 - }) - .map(|(i, q)| (q.pos.iter().map(|v| v.z).sum::() / 4.0, i)) - .collect(); - // Far to near; the depth buffer of the item atlas, approximated per quad. - visible.sort_by(|a, b| a.0.total_cmp(&b.0)); - for (_, i) in visible { - let q = &quads[i]; - let points: [Point; 4] = std::array::from_fn(|k| Point { - p: Vec2::new(q.pos[k].x, q.pos[k].y), - uv: q.uv[k], - }); + for face in depth::sort(quads) { + let q = &quads[face.quad]; + let points: Vec<_> = face + .corners + .iter() + .map(|v| Point { + p: v.pos.truncate(), + uv: v.uv, + }) + .collect(); let color = lit_color(q, lights); - for tri in [ - [points[0], points[1], points[2]], - [points[0], points[2], points[3]], - ] { + for i in 1..points.len().saturating_sub(1) { + let tri = [points[0], points[i], points[i + 1]]; let fan = clip_triangle(tri, rect); if fan.len() < 3 { continue; @@ -275,6 +261,102 @@ pub fn draw_banner_result( mod tests { use super::*; + fn face(y0: f32, y1: f32, z: impl Fn(f32) -> f32, color: u32) -> ItemQuad { + ItemQuad { + pos: [(0.0, y0), (0.0, y1), (8.0, y1), (8.0, y0)].map(|(x, y)| Vec3::new(x, y, z(y))), + uv: [[0.0, 0.0], [0.0, 1.0], [1.0, 1.0], [1.0, 0.0]], + normal: Vec3::Z, + color, + foil: Foil::None, + light_emission: 0, + } + } + + // Sample the emitted triangles in draw order, using opaque test faces. + fn color_at(batch: &HudBatch, p: Vec2) -> Option { + batch.vertices.chunks_exact(3).rev().find_map(|tri| { + let [a, b, c] = std::array::from_fn(|i| Vec2::from(tri[i].pos)); + let area = (b - a).perp_dot(c - a); + if area.abs() < 1e-6 { + return None; + } + let u = (b - p).perp_dot(c - p) / area; + let v = (c - p).perp_dot(a - p) / area; + let w = 1.0 - u - v; + (u >= 0.0 && v >= 0.0 && w >= 0.0).then_some(tri[0].color) + }) + } + + #[test] + fn banner_cloth_occludes_the_support_at_the_top_edge() { + // The cloth is nearer where it overlaps the bar, although its + // average depth is farther away because it slopes along its height. + let bar = face(0.0, 1.0, |_| 0.0, 0xFF80_4000); + let cloth = face(0.0, 8.0, |y| 2.0 - y, 0xFFFF_FFFF); + let mut batch = HudBatch::new([320, 240]); + draw_quads( + &[bar, cloth], + (Vec3::Z, Vec3::Z), + &mut batch, + [0.0, 0.0, 16.0, 16.0], + 0.0, + ); + assert_eq!(color_at(&batch, Vec2::new(4.0, 0.5)), Some(u32::MAX)); + } + + #[test] + fn intersecting_faces_change_draw_order_at_their_intersection() { + let flat = face(0.0, 8.0, |_| 0.0, 0xFFFF_0000); + let tilted = face(0.0, 8.0, |y| y - 4.0, 0xFF00_00FF); + for quads in [[flat, tilted], [tilted, flat]] { + let mut batch = HudBatch::new([320, 240]); + draw_quads( + &quads, + (Vec3::Z, Vec3::Z), + &mut batch, + [0.0, 0.0, 16.0, 16.0], + 0.0, + ); + assert_eq!( + color_at(&batch, Vec2::new(4.0, 2.0)), + Some(lit_color(&flat, (Vec3::Z, Vec3::Z))) + ); + assert_eq!( + color_at(&batch, Vec2::new(4.0, 6.0)), + Some(lit_color(&tilted, (Vec3::Z, Vec3::Z))) + ); + // The cut must interpolate the texture along with the position. + for v in &batch.vertices { + assert!((v.uv[0] - v.pos[0] / 8.0).abs() < 1e-6); + assert!((v.uv[1] - v.pos[1] / 8.0).abs() < 1e-6); + } + } + } + + #[test] + fn coplanar_pattern_layers_keep_submission_order() { + let base = face(0.0, 8.0, |y| 2.0 - y, 0xFFFF_FFFF); + let pattern = ItemQuad { + color: 0xFF00_00FF, + ..base + }; + let quads = [face(0.0, 1.0, |_| 0.0, 0xFF80_4000), base, pattern]; + let mut batch = HudBatch::new([320, 240]); + draw_quads( + &quads, + (Vec3::Z, Vec3::Z), + &mut batch, + [0.0, 0.0, 16.0, 16.0], + 0.0, + ); + for y in [0.5, 6.0] { + assert_eq!( + color_at(&batch, Vec2::new(4.0, y)), + Some(lit_color(&quads[2], (Vec3::Z, Vec3::Z))) + ); + } + } + #[test] fn flat_lights_match_joml() { // new Matrix4f().rotationY(-PI/8).rotateX(3PI/4).transformDirection(L0). diff --git a/crates/horizon-client/src/item_render/gui/depth.rs b/crates/horizon-client/src/item_render/gui/depth.rs new file mode 100644 index 000000000..9fecfdee7 --- /dev/null +++ b/crates/horizon-client/src/item_render/gui/depth.rs @@ -0,0 +1,119 @@ +//! Back-to-front ordering for the orthographic GUI item view (near is +Z). +//! Whole-face average depths fail when a long, tilted face overlaps a short +//! one, such as a banner's cloth and support. Partition faces by their planes +//! instead, splitting intersecting faces with their UVs. Coplanar faces keep +//! submission order so banner/shield pattern layers still paint bottom first. +use super::super::ItemQuad; +use glam::{Vec3, Vec4}; + +#[derive(Clone, Copy)] +pub(super) struct Corner { + pub pos: Vec3, + pub uv: [f32; 2], +} + +pub(super) struct Face { + pub quad: usize, + pub corners: Vec, +} + +const EPSILON: f32 = 1e-4; + +fn split(face: Face, distances: &[f32]) -> (Face, Face) { + let mut back = Vec::new(); + let mut front = Vec::new(); + for i in 0..face.corners.len() { + let a = face.corners[i]; + let b = face.corners[(i + 1) % face.corners.len()]; + let da = distances[i]; + let db = distances[(i + 1) % face.corners.len()]; + if da <= EPSILON { + back.push(a); + } + if da >= -EPSILON { + front.push(a); + } + if (da < -EPSILON && db > EPSILON) || (da > EPSILON && db < -EPSILON) { + let t = da / (da - db); + let corner = Corner { + pos: a.pos.lerp(b.pos, t), + uv: std::array::from_fn(|k| a.uv[k] + (b.uv[k] - a.uv[k]) * t), + }; + back.push(corner); + front.push(corner); + } + } + ( + Face { + quad: face.quad, + corners: back, + }, + Face { + quad: face.quad, + corners: front, + }, + ) +} + +pub(super) fn sort(quads: &[ItemQuad]) -> Vec { + let mut planes = vec![Vec4::ZERO; quads.len()]; + let faces: Vec<_> = quads + .iter() + .enumerate() + .filter_map(|(i, q)| { + let normal = (q.pos[2] - q.pos[0]).cross(q.pos[3] - q.pos[1]); + // Front faces wind counter-clockwise on screen with Y up. + if normal.z >= 0.0 { + return None; + } + let normal = -normal.normalize(); + planes[i] = normal.extend(-normal.dot(q.pos[0])); + Some(Face { + quad: i, + corners: std::array::from_fn::<_, 4, _>(|k| Corner { + pos: q.pos[k], + uv: q.uv[k], + }) + .to_vec(), + }) + }) + .collect(); + let mut out = Vec::new(); + // An explicit stack avoids recursion for models with many parallel faces. + let mut pending = vec![(faces, false)]; + while let Some((faces, emit)) = pending.pop() { + if emit { + out.extend(faces); + continue; + } + let mut faces = faces.into_iter(); + let Some(first) = faces.next() else { continue }; + let plane = planes[first.quad]; + let mut coplanar = vec![first]; + let mut back = Vec::new(); + let mut front = Vec::new(); + for face in faces { + let distances: Vec<_> = face + .corners + .iter() + .map(|c| plane.dot(c.pos.extend(1.0))) + .collect(); + let behind = distances.iter().any(|d| *d < -EPSILON); + let ahead = distances.iter().any(|d| *d > EPSILON); + match (behind, ahead) { + (false, false) => coplanar.push(face), + (true, false) => back.push(face), + (false, true) => front.push(face), + (true, true) => { + let (b, f) = split(face, &distances); + back.push(b); + front.push(f); + } + } + } + pending.push((front, false)); + pending.push((coplanar, true)); + pending.push((back, false)); + } + out +} From aab88753b6825e83d88f12b21895a681b2964e5d Mon Sep 17 00:00:00 2001 From: rdbtCVS <87152661+rdbtCVS@users.noreply.github.com> Date: Wed, 14 Oct 2026 19:15:16 +0100 Subject: [PATCH 14/24] Keep title panorama optional during full resource preparation --- crates/horizon-prepare/src/lib.rs | 3 +- crates/horizon-prepare/src/sounds.rs | 59 ++++++++++++++++++++++++---- docs/native-client.md | 7 ++-- 3 files changed, 58 insertions(+), 11 deletions(-) diff --git a/crates/horizon-prepare/src/lib.rs b/crates/horizon-prepare/src/lib.rs index 534abfc8a..e1c165e8e 100644 --- a/crates/horizon-prepare/src/lib.rs +++ b/crates/horizon-prepare/src/lib.rs @@ -685,7 +685,8 @@ fn steps( // The JAR holds only gray 1x1 panorama placeholders. Import the indexed // textures afterwards, including on reruns that just extracted the JAR again. - panorama(repo, minecraft, run.log)?; + // Cosmetic assets are optional when preparing from already-imported JARs. + sounds::optional_panorama(repo, minecraft, run.log); // One file each, exported again when the exporter or the jar it reads changed. let single = |what: &str, diff --git a/crates/horizon-prepare/src/sounds.rs b/crates/horizon-prepare/src/sounds.rs index e0787656d..b18ed3426 100644 --- a/crates/horizon-prepare/src/sounds.rs +++ b/crates/horizon-prepare/src/sounds.rs @@ -85,6 +85,15 @@ pub fn panorama(root: &Path, minecraft: Option<&Path>, log: Log) -> Result, log: Log) { + if let Err(error) = panorama(root, minecraft, log) { + log(&format!( + "Title panorama not imported: {error}; run horizon-prepare panorama later" + )); + } +} + const PANORAMA: [&str; 7] = [ "minecraft/textures/gui/title/background/panorama_0.png", "minecraft/textures/gui/title/background/panorama_1.png", @@ -138,6 +147,7 @@ fn copy_assets( } } let mut total: u64 = 0; + let mut copies = Vec::with_capacity(wanted.len()); for (name, info) in &wanted { let hash = info .get("hash") @@ -151,15 +161,14 @@ fn copy_assets( let relative = artifacts::safe_relative(name) .ok_or_else(|| format!("Unsafe asset name {name:?} in the asset index"))?; let source = launcher_object(&store, hash)?; - artifacts::import_copy( - &source, - &target.join("assets").join(relative), - hash, - "sha1", - "", - )?; + copies.push((source, target.join("assets").join(relative), hash)); total += size; } + // Check the entire set before replacing any placeholders: a missing late face + // must not leave a mixture of real textures and gray faces in either entry point. + for (source, destination, hash) in copies { + artifacts::import_copy(&source, &destination, hash, "sha1", "")?; + } log(&format!( "{label} assets ready: {} files, {:.1} MB", wanted.len(), @@ -366,6 +375,42 @@ mod tests { assert!(!f.root.join(".local/horizon-client/9.9/assets").exists()); } + #[test] + fn full_preparation_keeps_placeholders_when_panorama_is_unavailable() { + for missing in ["store", "install", "last-object"] { + let f = Fixture::new(&format!("optional-panorama-{missing}")); + // The JARs and manifest were imported earlier; the launcher need not remain. + artifacts::import_manifest(&Lock::read(&f.root).unwrap(), &f.minecraft).unwrap(); + let target = f.root.join(".local/horizon-client/9.9/assets"); + for name in PANORAMA { + let path = target.join(name); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, b"jar placeholder").unwrap(); + } + match missing { + "store" => fs::remove_dir_all(f.minecraft.join("assets")).unwrap(), + "install" => fs::remove_dir_all(&f.minecraft).unwrap(), + _ => fs::remove_file(f.object(f.objects.len() - 1)).unwrap(), + } + // The repair subcommand remains strict, even for a missing final object. + let error = panorama(&f.root, Some(&f.minecraft), &|_| {}).unwrap_err(); + let lines = std::cell::RefCell::new(Vec::new()); + // This is the optional import step used by full preparation after extraction. + optional_panorama(&f.root, Some(&f.minecraft), &|line| { + lines.borrow_mut().push(line.to_string()) + }); + assert_eq!( + *lines.borrow(), + [format!( + "Title panorama not imported: {error}; run horizon-prepare panorama later" + )] + ); + for name in PANORAMA { + assert_eq!(fs::read(target.join(name)).unwrap(), b"jar placeholder"); + } + } + } + #[test] fn the_index_must_be_the_pinned_one() { let f = Fixture::new("index"); diff --git a/docs/native-client.md b/docs/native-client.md index f05199ba7..e51bd8e40 100644 --- a/docs/native-client.md +++ b/docs/native-client.md @@ -23,9 +23,10 @@ verifies it against the pinned checksums, runs vanilla's data generator and smal exporters against those jars, and extracts the jar's assets and data into ignored `.local/horizon-client/26.3/`. Sounds (about 380 MB) are copied from your launcher's asset store by `horizon-prepare sounds`, each file checked against the asset -index's SHA-1. Preparation also replaces the JAR's gray 1×1 title panorama placeholders -with the full textures from that asset store. To repair an existing classic menu background -without rerunning the Java exporters, run `horizon-prepare panorama` (or +index's SHA-1. Preparation also tries to replace the JAR's gray 1×1 title panorama +placeholders with the full textures from that asset store. If the store is missing or +incomplete, preparation logs a warning and keeps the placeholders. To import the panorama +later without rerunning the Java exporters, run `horizon-prepare panorama` (or `cargo run --release -p horizon-prepare -- panorama` in a checkout). Pass `--minecraft-dir PATH` when using a different Minecraft installation. Prepared resources are private; never commit them. From 1596210bba2e71fc117aed34190a2ea0dcca83da Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 14 Oct 2026 19:19:57 +0200 Subject: [PATCH 15/24] Respawn anchors charge, set the respawn point, explode outside the Nether A right click with glowstone on a respawn anchor did nothing and a charged anchor never became the respawn point: the block reported the use and the game dropped it. RespawnAnchorBlock is now played out (game/respawn_anchor.rs): useItemOn charges with glowstone (the block change, block.respawn_anchor.charge, the used item and the charge_respawn_anchor criterion), passing to the off hand's glowstone; useWithoutItem sets the respawn point in the Nether (block.minecraft.set_spawn once, respawn_anchor.set_spawn) and elsewhere explodes: the anchor goes, then a power 5 fiery BLOCK explosion with the bad_respawn_point damage source whose centre resists like water when water would flow into it. Dying with an anchor as the respawn point travels to its dimension and respawns at findStandUpPosition (DismountHelper's safe and unsafe passes, facing the anchor with calculateLookAtYaw), using a charge and playing respawn_anchor.deplete; a missing or empty anchor falls back to the world spawn with block.minecraft.spawn.not_valid. The point is saved in the player's respawn compound with its dimension; a bed or /spawnpoint replaces it. Dying in the Nether without one now respawns in the Overworld. Explosions gained what these need: a damage type, a block resistance override, BaseFireBlock.getState for their fire, the explosion radius in the block loot context (survives_explosion and explosion_decay drawing from the table's random sequence) and TntBlock.wasExploded without a game event. tools/test_use_item_on_parity.py now charges, uses and blows up anchors in both dimensions through vanilla's real ServerExplosion on the stand-in level, and respawns at anchors among blocks through ServerPlayer.findRespawnAndUseSpawnBlock. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game.rs | 81 ++- crates/horizon-client/src/game/commands.rs | 1 + .../src/game/dispense_fixture.rs | 52 +- crates/horizon-client/src/game/end.rs | 6 +- crates/horizon-client/src/game/explosion.rs | 79 ++- .../horizon-client/src/game/respawn_anchor.rs | 542 ++++++++++++++++++ crates/horizon-client/src/game/screens.rs | 10 + crates/horizon-client/src/items.rs | 42 +- crates/horizon-client/src/save.rs | 31 +- .../parity/VanillaBlockUpdateOracle.java | 22 + .../parity/VanillaDispenserOracle.java | 47 +- tools/test_use_item_on_parity.py | 113 +++- 12 files changed, 974 insertions(+), 52 deletions(-) create mode 100644 crates/horizon-client/src/game/respawn_anchor.rs diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index a5cc64b1d..71610bfb7 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -88,6 +88,7 @@ mod recipe_book; mod remote; mod render_control; mod render_tick; +mod respawn_anchor; mod scoreboard; mod screens; mod sculk; @@ -791,6 +792,11 @@ struct Game<'a> { portals: nether_portal::Portals, /// The pending travel goes through an End portal (EndPortalBlock destinations). end_travel: bool, + /// The respawn point when it is not the world spawn or a bed: a respawn + /// anchor (`game/respawn_anchor.rs`). + respawn_config: Option, + /// A respawn travelling to its anchor's dimension and chunks. + respawn_travel: Option, /// The next enter_dimension call comes from an End portal. end_portal_travel: bool, end: end::EndState, @@ -1725,7 +1731,10 @@ impl Game<'_> { food.saturation = (food.saturation + 0.4).min(food.food as f32); } } - PlayerEffect::InteractLoot(_) | PlayerEffect::RespawnAnchor => {} + PlayerEffect::RespawnAnchor => { + self.respawn_anchor_used([pos.x, pos.y, pos.z])? + } + PlayerEffect::InteractLoot(_) => {} }, LevelEvent::PrimeTnt { pos, rot } => self.add_primed_tnt(pos, rot, 80), LevelEvent::BlockEvent { @@ -2119,6 +2128,7 @@ impl Game<'_> { return Ok(()); } let sneaking = self.keys.contains(&KeyCode::ShiftLeft); + let mut anchor_passed = None; // MultiPlayerGameMode.useItemOn: blocks react first unless sneaking with an item. if !(sneaking && self.held().is_some()) && let Some(hit) = self.pick() @@ -2136,6 +2146,15 @@ impl Game<'_> { self.swing_arm(); return Ok(()); } + match self.use_respawn_anchor(hit.pos, held.as_ref())? { + respawn_anchor::AnchorUse::Charged => { + self.swing_arm(); + return Ok(()); + } + // The main hand passes; its item is used, then the off hand's glowstone. + respawn_anchor::AnchorUse::Pass => anchor_passed = Some(hit.pos), + respawn_anchor::AnchorUse::Other => {} + } let face = match hit.face { [0, 1, 0] => Direction::Up, [0, -1, 0] => Direction::Down, @@ -2157,17 +2176,21 @@ impl Game<'_> { }; let at = Vec3::new(hit.point[0], hit.point[1], hit.point[2]); let item = held.as_ref().map(|s| s.item.to_string()); - let result = self.with_level(|b, level, ticks| { - b.use_item_on( - level, - ticks, - BlockPos::new(hit.pos[0], hit.pos[1], hit.pos[2]), - face, - at, - player, - item.as_deref(), - ) - }); + let result = if anchor_passed.is_some() { + horizon_world::level::InteractionResult::Pass + } else { + self.with_level(|b, level, ticks| { + b.use_item_on( + level, + ticks, + BlockPos::new(hit.pos[0], hit.pos[1], hit.pos[2]), + face, + at, + player, + item.as_deref(), + ) + }) + }; self.process_level_events()?; if result.consumes_action() { self.swing_arm(); @@ -2175,6 +2198,12 @@ impl Game<'_> { } } let Some(stack) = self.held().cloned() else { + // Minecraft.startUseItem goes on to the off hand. + if let Some(pos) = anchor_passed + && self.charge_anchor_from_offhand(pos)? + { + return Ok(()); + } self.use_offhand(); return Ok(()); }; @@ -2239,6 +2268,11 @@ impl Game<'_> { return Ok(()); }; if info.block.is_none() { + if let Some(pos) = anchor_passed + && self.charge_anchor_from_offhand(pos)? + { + return Ok(()); + } self.use_offhand(); return Ok(()); } @@ -2585,7 +2619,10 @@ impl Game<'_> { self.streaming.center = (cx, cz); if (-2..=2).all(|dz| (-2..=2).all(|dx| self.streaming.is_lit(cx + dx, cz + dz))) { let (player, target) = self.travelling.take().ok_or("travel")?; - if self.end_travel { + if let Some(config) = self.respawn_travel.take() { + drop(player); + self.place_respawned(config)?; + } else if self.end_travel { self.place_after_end_travel(player, target)?; } else { self.place_after_travel(player, target)?; @@ -5649,6 +5686,17 @@ impl Game<'_> { self.travelling = None; self.player = None; self.spawn = None; + self.respawn_travel = None; + self.respawn_config = + self.level + .respawn_elsewhere + .as_ref() + .map(|(dim, pos, yaw, forced)| respawn_anchor::RespawnConfig { + dim: Dim::from_id(dim), + pos: *pos, + yaw: *yaw, + forced: *forced, + }); self.spawn_search = 0; self.spawn_origin = None; self.spawn_spiral = Default::default(); @@ -7097,6 +7145,8 @@ impl Game<'_> { f64::from(head[1]) + 0.6, f64::from(head[2]) + 0.5, )); + // The bed replaces a respawn anchor. + self.respawn_config = None; self.level.spawn = Some([ f64::from(head[0]), f64::from(head[1]) + 1.0, @@ -7474,6 +7524,9 @@ impl Game<'_> { level.weather = self.world.weather; level.day_time = self.world.day_time; level.spawn = self.spawn.map(|s| [s.x, s.y, s.z]); + level.respawn_elsewhere = self + .respawn_config + .map(|c| (c.dim.id().to_owned(), c.pos, c.yaw, c.forced)); level.rotation = [self.yaw, self.pitch]; level.xp_level = self.experience.level; level.xp_progress = self.experience.progress; @@ -9050,6 +9103,8 @@ pub fn run() -> Result<()> { travelling: None, portals: Default::default(), end_travel: false, + respawn_config: None, + respawn_travel: None, end_portal_travel: false, end: Default::default(), block_ticks: Ticks::new(0), diff --git a/crates/horizon-client/src/game/commands.rs b/crates/horizon-client/src/game/commands.rs index aff5ad2a1..15d43c80b 100644 --- a/crates/horizon-client/src/game/commands.rs +++ b/crates/horizon-client/src/game/commands.rs @@ -2010,6 +2010,7 @@ impl Game<'_> { f64::from(pos[1]), f64::from(pos[2]) + 0.5, )); + self.respawn_config = None; let dim = Text::literal(self.dim.id()); let p = pos.map(|v| Text::literal(v.to_string())); let mut args = vec![ diff --git a/crates/horizon-client/src/game/dispense_fixture.rs b/crates/horizon-client/src/game/dispense_fixture.rs index ab6a79961..6e10b53b1 100644 --- a/crates/horizon-client/src/game/dispense_fixture.rs +++ b/crates/horizon-client/src/game/dispense_fixture.rs @@ -137,6 +137,8 @@ impl Game<'_> { // Hopper cooldowns of an earlier case. self.hoppers.clear(); self.ui.rules = Default::default(); + self.dim = super::Dim::Overworld; + self.respawn_config = None; // The oracle level plays on normal difficulty. self.ui.difficulty = 2; // The oracle level has world seed 0 and fresh random sequences. @@ -162,6 +164,9 @@ impl Game<'_> { } } self.world.game_time = case["time"].as_i64().unwrap_or(0); + if case["dim"].as_str() == Some("nether") { + self.dim = super::Dim::Nether; + } // The oracle level's clock stands at day time 6000. self.world.day_time = 6000; if let Some(rules) = case["rules"].as_object() { @@ -272,6 +277,26 @@ impl Game<'_> { used = self.fixture_use(origin, op)?; } else if let Some(op) = case.get("use_item") { used = self.fixture_use_item(origin, op)?; + } else if let Some(op) = case.get("respawn_at") { + // ServerPlayer.findRespawnAndUseSpawnBlock for a respawn point at the origin. + let config = super::respawn_anchor::RespawnConfig { + dim: self.dim, + pos: [origin.x, origin.y, origin.z], + yaw: 0.0, + forced: op["forced"].as_bool().unwrap_or(false), + }; + let found = + self.find_respawn_and_use(config, op["consume"].as_bool().unwrap_or(true))?; + used.push(match found { + Some((p, yaw)) => format!( + "respawn {} {} {} {}", + num(p.x), + num(p.y), + num(p.z), + yaw.to_bits() as i32 + ), + None => "respawn none".to_owned(), + }); } else if case.get("hopper").is_some() { // HopperBlockEntity.pushItemsTick, once. self.hopper_try_move_items((origin.x, origin.y, origin.z)); @@ -447,14 +472,24 @@ impl Game<'_> { GameMode::Survival }; self.creative = self.mode == GameMode::Creative; + let distance = op["distance"].as_f64().unwrap_or(3.0); let mut player = PlayerMotion::new( self.motion, horizon_core::geometry::Vec3::new( f64::from(pos.x) + 0.5, f64::from(pos.y) + 1.0, - f64::from(pos.z) + 3.5, + f64::from(pos.z) + 0.5 + distance, ), )?; + if let Some(r) = op["respawn"].as_array() { + let p = |i: usize| r.get(i).and_then(Value::as_i64).unwrap_or(0) as i32; + self.respawn_config = Some(super::respawn_anchor::RespawnConfig { + dim: self.dim, + pos: [p(0), p(1), p(2)], + yaw: 0.0, + forced: false, + }); + } player.health.food.food = op["food"].as_i64().unwrap_or(20) as i32; self.player = Some(player); self.yaw = 0.0; @@ -488,7 +523,10 @@ impl Game<'_> { let key = m.component()["translate"] .as_str() .map_or_else(|| m.plain(), str::to_owned); - out.push(format!("msg {key}")); + // The oracle player's advancements are not tracked. + if !key.starts_with("chat.type.advancement") { + out.push(format!("msg {key}")); + } } if let Some(s) = &stack { let used = self.stats.get("used", &s.item) - used_before; @@ -504,6 +542,16 @@ impl Game<'_> { "held {} using {using}", canon_stack(self.inventory[self.selected].as_ref()) )); + out.push(match self.respawn_config { + Some(c) => format!( + "respawn {} {},{},{}", + c.dim.id(), + c.pos[0], + c.pos[1], + c.pos[2] + ), + None => "respawn -".to_owned(), + }); self.player = None; self.using = None; Ok(out) diff --git a/crates/horizon-client/src/game/end.rs b/crates/horizon-client/src/game/end.rs index e6be63093..126bd322b 100644 --- a/crates/horizon-client/src/game/end.rs +++ b/crates/horizon-client/src/game/end.rs @@ -494,14 +494,16 @@ impl Game<'_> { Ok(()) } - /// Dying in the End respawns in the Overworld. + /// Dying away from the Overworld respawns at the world spawn there. pub(super) fn respawn_out_of_end(&mut self) -> Result<()> { - if self.dim != Dim::End || self.player.is_none() { + if self.dim == Dim::Overworld || self.player.is_none() { return Ok(()); } self.end_portal_travel = true; let result = self.enter_dimension(Dim::Overworld); self.end_portal_travel = false; + // The arrival places a fresh player at the spawn. + self.end_travel = true; result } diff --git a/crates/horizon-client/src/game/explosion.rs b/crates/horizon-client/src/game/explosion.rs index 1332ad51d..c03b99609 100644 --- a/crates/horizon-client/src/game/explosion.rs +++ b/crates/horizon-client/src/game/explosion.rs @@ -109,8 +109,14 @@ impl Game<'_> { } hits as f32 / count as f32 } - /// `ServerExplosion.calculateExplodedPositions`. - fn exploded_positions(&mut self, center: [f64; 3], radius: f32) -> Vec<[i32; 3]> { + /// `ServerExplosion.calculateExplodedPositions`; `resists` overrides one + /// block's resistance (`ExplosionDamageCalculator.getBlockExplosionResistance`). + fn exploded_positions( + &mut self, + center: [f64; 3], + radius: f32, + resists: Option<([i32; 3], f32)>, + ) -> Vec<[i32; 3]> { let (min_y, max_y) = self.with_level(|_, level, _| { use horizon_world::level::LevelAccess; (level.min_y(), level.max_y()) @@ -147,8 +153,14 @@ impl Game<'_> { } else { 0.0 }; - if !self.res.facts.is_air(state) || f.fluid != Fluid::None { - power -= (f.explosion_resistance.max(fluid) + 0.3) * 0.3; + match resists { + Some((at, resistance)) if at == pos => { + power -= (resistance + 0.3) * 0.3; + } + _ if !self.res.facts.is_air(state) || f.fluid != Fluid::None => { + power -= (f.explosion_resistance.max(fluid) + 0.3) * 0.3; + } + _ => {} } if power > 0.0 { set.put(Key(pos), ()); @@ -163,8 +175,9 @@ impl Game<'_> { } set.entries().map(|(k, _)| k.0).collect() } - /// `ServerExplosion.hurtEntities` (player, mobs, items, primed TNT). - fn explosion_hurt_entities(&mut self, center: [f64; 3], radius: f32) { + /// `ServerExplosion.hurtEntities` (player, mobs, items, primed TNT); + /// the player takes `damage_type`. + fn explosion_hurt_entities(&mut self, center: [f64; 3], radius: f32, damage_type: &str) { if radius < 1.0e-5 { return; } @@ -223,7 +236,7 @@ impl Game<'_> { let mut hurt = false; let creative = self.creative; if let Some(p) = self.player.as_mut() - && let Some(id) = self.motion.health.damage.id("minecraft:explosion") + && let Some(id) = self.motion.health.damage.id(damage_type) { // Creative players are invulnerable to explosions. if !creative && player_hurtable { @@ -334,6 +347,26 @@ impl Game<'_> { radius: f32, interaction: BlockInteraction, fire: bool, + ) -> Result<()> { + self.server_explode_as( + center, + radius, + interaction, + fire, + "minecraft:explosion", + None, + ) + } + /// `server_explode` with the damage type the player takes and a block + /// whose explosion resistance the damage calculator overrides. + pub(super) fn server_explode_as( + &mut self, + center: [f64; 3], + radius: f32, + interaction: BlockInteraction, + fire: bool, + damage_type: &str, + resists: Option<([i32; 3], f32)>, ) -> Result<()> { if let Some(p) = &self.player { let d = [ @@ -344,11 +377,11 @@ impl Game<'_> { let distance = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt(); self.pad_rumble(horizon_client::gamepad::Rumble::Explosion { distance, radius }); } - let mut targets = self.exploded_positions(center, radius); // Explosion.explode: the blast is heard. let ctx = horizon_client::sculk::Context::default(); self.post_game_event("minecraft:explode", center, ctx); - self.explosion_hurt_entities(center, radius); + let mut targets = self.exploded_positions(center, radius, resists); + self.explosion_hurt_entities(center, radius, damage_type); if interaction != BlockInteraction::Keep { // Util.shuffle(list, level.random) for i in (2..=targets.len()).rev() { @@ -375,8 +408,12 @@ impl Game<'_> { .facts .get(self.world.block(pos[0], pos[1] - 1, pos[2])) .solid_render - && let Some(fire) = self.res.assets.registry.default_state("minecraft:fire") { + // BaseFireBlock.getState: soul fire on its base blocks, + // fire shaped by its neighbours elsewhere. + let at = BlockPos::new(pos[0], pos[1], pos[2]); + let fire = + self.with_level(|b, level, ticks| b.fire_state_for(level, ticks, at)); self.level_set(pos, fire)?; } } @@ -420,32 +457,36 @@ impl Game<'_> { } if !is_tnt { let dynamic = self.pending.dynamic(pos); - let drops = self.res.items.block_drops_full( + // LootContextParams.EXPLOSION_RADIUS under DESTROY_WITH_DECAY: the + // tables' survives_explosion and explosion_decay draw from their + // random sequence. + let decay = (interaction == BlockInteraction::DestroyWithDecay).then_some(radius); + let drops = self.res.items.block_drops_exploded( self.res.assets.registry, state, None, &dynamic, &mut self.world.random, Some((&mut self.rand_sequences, self.level.seed)), + decay, ); for mut stack in drops { if &*stack.item == "minecraft:air" || stack.count == 0 { continue; } self.pending.attach(pos, &mut stack); - // survives_explosion / explosion_decay: 1 / radius per stack. - if interaction == BlockInteraction::DestroyWithDecay - && self.world.random.next_float() > 1.0 / radius - { - continue; - } add_or_append_stack(stacks, stack, pos); } } self.pending.clear(pos); self.level_set(pos, self.world.air)?; - if is_tnt { - self.spawn_primed_tnt(BlockPos::new(pos[0], pos[1], pos[2]), true); + // TntBlock.wasExploded: new PrimedTnt (its push drawn first), then + // getRandomShortFuse(80); no game event. + if is_tnt && self.ui.rules.bool("tnt_explodes") { + let r = &mut self.world.random; + let rot = r.next_double() * f64::from(std::f32::consts::TAU); + let fuse = r.next_int_bound(20).unwrap_or(0) + 10; + self.add_primed_tnt(BlockPos::new(pos[0], pos[1], pos[2]), rot, fuse); } Ok(()) } diff --git a/crates/horizon-client/src/game/respawn_anchor.rs b/crates/horizon-client/src/game/respawn_anchor.rs new file mode 100644 index 000000000..b1b9e18fe --- /dev/null +++ b/crates/horizon-client/src/game/respawn_anchor.rs @@ -0,0 +1,542 @@ +//! `RespawnAnchorBlock` in the game: glowstone charges it (`useItemOn`), a +//! right click on a charged anchor sets the respawn point in the Nether and +//! blows it up anywhere else (`useWithoutItem`), and respawning goes to it +//! (`ServerPlayer.findRespawnAndUseSpawnBlock`, `PlayerList.respawn`), +//! using a charge. +use super::{Dim, Game}; +use horizon_client::{ + Result, + blocks::Fluid, + collisions::{SceneCollisions, no_collision_empty}, + items::ItemStack, + mobs::Who, + motion::PlayerMotion, + text::Text, +}; +use horizon_core::{ + geometry::{Aabb, Axis, Vec3, VoxelShape}, + position::BlockPos, + random::RandomSource, +}; +use horizon_world::{collision_context::CollisionContext, registry::BlockStateId}; + +/// `ServerPlayer.RespawnConfig`: a respawn point other than the world spawn +/// that the game resolves through its block (a respawn anchor). +#[derive(Clone, Copy, Debug, PartialEq)] +pub(super) struct RespawnConfig { + pub dim: Dim, + pub pos: [i32; 3], + pub yaw: f32, + pub forced: bool, +} + +/// `RespawnAnchorBlock.RESPAWN_HORIZONTAL_OFFSETS`, then the same a block +/// below, a block above, and straight above. +const HORIZONTAL: [[i32; 3]; 8] = [ + [0, 0, -1], + [-1, 0, 0], + [0, 0, 1], + [1, 0, 0], + [-1, 0, -1], + [1, 0, -1], + [-1, 0, 1], + [1, 0, 1], +]; +fn respawn_offsets() -> impl Iterator { + HORIZONTAL + .into_iter() + .chain(HORIZONTAL.into_iter().map(|[x, y, z]| [x, y - 1, z])) + .chain(HORIZONTAL.into_iter().map(|[x, y, z]| [x, y + 1, z])) + .chain(std::iter::once([0, 1, 0])) +} + +/// What a right click with an item does to an anchor before `useWithoutItem`. +pub(super) enum AnchorUse { + /// Glowstone charged it. + Charged, + /// `PASS`: the off hand's glowstone charges it instead. + Pass, + /// `TRY_WITH_EMPTY_HAND`, or not an anchor. + Other, +} + +impl Game<'_> { + fn is_anchor(&self, state: BlockStateId) -> bool { + &*self.res.facts.get(state).name == "minecraft:respawn_anchor" + } + fn anchor_charges(&self, state: BlockStateId) -> i32 { + self.res + .assets + .registry + .state(state) + .and_then(|s| s.properties.get("charges")) + .and_then(|c| c.parse().ok()) + .unwrap_or(0) + } + fn anchor_with_charges(&self, state: BlockStateId, charges: i32) -> Option { + let mut s = self.res.assets.registry.state(state)?.clone(); + s.properties.insert("charges".into(), charges.to_string()); + self.res.assets.registry.resolve(&s).ok() + } + /// `RespawnAnchorBlock.canSetSpawn`: the `respawn_anchor_works` attribute + /// (only the Nether's dimension type sets it). + pub(super) fn anchor_works(&self) -> bool { + self.dim == Dim::Nether + } + /// `RespawnAnchorBlock.charge`: one more charge, the block change and the sound. + fn charge_anchor( + &mut self, + pos: [i32; 3], + state: BlockStateId, + who: Option, + ) -> Result<()> { + let Some(next) = self.anchor_with_charges(state, self.anchor_charges(state) + 1) else { + return Ok(()); + }; + self.level_set(pos, next)?; + self.post_block_game_event("minecraft:block_change", pos, who, Some(next)); + let at = [ + f64::from(pos[0]) + 0.5, + f64::from(pos[1]) + 0.5, + f64::from(pos[2]) + 0.5, + ]; + self.audio + .play("minecraft:block.respawn_anchor.charge", Some(at), 1.0, 1.0); + Ok(()) + } + /// `RespawnAnchorBlock.useItemOn` with `held` in the main hand. + pub(super) fn use_respawn_anchor( + &mut self, + pos: [i32; 3], + held: Option<&ItemStack>, + ) -> Result { + let state = self.world.block(pos[0], pos[1], pos[2]); + if !self.is_anchor(state) { + return Ok(AnchorUse::Other); + } + let fuel = |s: Option<&ItemStack>| s.is_some_and(|s| &*s.item == "minecraft:glowstone"); + let chargeable = self.anchor_charges(state) < 4; + if fuel(held) && chargeable { + let used = held.cloned(); + self.charge_anchor(pos, state, Some(Who::Player))?; + // itemStack.consume(1, player); the criterion sees the stack as used. + self.consume_held(); + if let Some(stack) = used { + self.trigger_block("minecraft:item_used_on_block", pos, &stack); + } + return Ok(AnchorUse::Charged); + } + if fuel(self.offhand.as_ref()) && chargeable { + return Ok(AnchorUse::Pass); + } + Ok(AnchorUse::Other) + } + /// The off hand's glowstone on an anchor the main hand passed on. + pub(super) fn charge_anchor_from_offhand(&mut self, pos: [i32; 3]) -> Result { + let state = self.world.block(pos[0], pos[1], pos[2]); + let fuel = self + .offhand + .as_ref() + .is_some_and(|s| &*s.item == "minecraft:glowstone"); + if !self.is_anchor(state) || !fuel || self.anchor_charges(state) >= 4 { + return Ok(false); + } + let used = self.offhand.clone(); + self.charge_anchor(pos, state, Some(Who::Player))?; + if !self.creative + && let Some(s) = self.offhand.as_mut() + { + s.count -= 1; + if s.count == 0 { + self.offhand = None; + } + } + if let Some(stack) = used { + self.trigger_block("minecraft:item_used_on_block", pos, &stack); + } + self.swing_arm(); + Ok(true) + } + /// `RespawnAnchorBlock.useWithoutItem` on a charged anchor: outside the + /// Nether it explodes; inside, it becomes the respawn point. + pub(super) fn respawn_anchor_used(&mut self, pos: [i32; 3]) -> Result<()> { + let state = self.world.block(pos[0], pos[1], pos[2]); + if !self.anchor_works() { + return self.explode_anchor(pos, state); + } + let config = RespawnConfig { + dim: self.dim, + pos, + yaw: 0.0, + forced: false, + }; + // RespawnConfig.isSamePosition: dimension and block. + let same = self + .respawn_config + .is_some_and(|c| c.dim == config.dim && c.pos == config.pos); + if !same { + // setRespawnPosition(config, true): the message, the point; the + // anchor replaces a bed. + self.system_message(Text::translate("block.minecraft.set_spawn", &[])); + self.respawn_config = Some(config); + if let Some([x, y, z]) = self.level.world_spawn { + self.spawn = Some(Vec3::new( + f64::from(x) + 0.5, + f64::from(y), + f64::from(z) + 0.5, + )); + } + let at = [ + f64::from(pos[0]) + 0.5, + f64::from(pos[1]) + 0.5, + f64::from(pos[2]) + 0.5, + ]; + self.audio.play( + "minecraft:block.respawn_anchor.set_spawn", + Some(at), + 1.0, + 1.0, + ); + } + Ok(()) + } + /// `RespawnAnchorBlock.isWaterThatWouldFlow`. + fn water_would_flow(&self, p: [i32; 3]) -> bool { + let f = self.res.facts.get(self.world.block(p[0], p[1], p[2])); + if f.fluid != Fluid::Water { + return false; + } + if f.fluid_level == 8 && !f.fluid_falling { + return true; + } + if f.fluid_level < 2 { + return false; + } + self.res + .facts + .get(self.world.block(p[0], p[1] - 1, p[2])) + .fluid + != Fluid::Water + } + /// `RespawnAnchorBlock.explode`: the anchor goes, then a power 5 fiery + /// explosion (`badRespawnPointExplosion`, `ExplosionInteraction.BLOCK`) + /// whose centre resists like water when water would flow into it. + fn explode_anchor(&mut self, pos: [i32; 3], _state: BlockStateId) -> Result<()> { + self.level_set(pos, self.world.air)?; + let horizontal = [[0, 0, -1], [0, 0, 1], [-1, 0, 0], [1, 0, 0]] + .into_iter() + .any(|d| self.water_would_flow([pos[0] + d[0], pos[1], pos[2] + d[2]])); + let above = self + .res + .facts + .get(self.world.block(pos[0], pos[1] + 1, pos[2])) + .fluid + == Fluid::Water; + let in_water = horizontal || above; + let center = [ + f64::from(pos[0]) + 0.5, + f64::from(pos[1]) + 0.5, + f64::from(pos[2]) + 0.5, + ]; + self.block_explosion(center, in_water.then_some(pos)) + } + /// `Level.explode(null, badRespawnPointExplosion(center), calculator, + /// center, 5, true, ExplosionInteraction.BLOCK)` (beds and anchors): + /// `water_at` is the block that resists like water. + pub(super) fn block_explosion( + &mut self, + center: [f64; 3], + water_at: Option<[i32; 3]>, + ) -> Result<()> { + let interaction = if self.ui.rules.bool("block_explosion_drop_decay") { + super::explosion::BlockInteraction::DestroyWithDecay + } else { + super::explosion::BlockInteraction::Destroy + }; + self.server_explode_as( + center, + 5.0, + interaction, + true, + "minecraft:bad_respawn_point", + water_at.map(|p| (p, 100.0)), + ) + } + + // ---- respawning ------------------------------------------------------- + + /// `DismountHelper.nonClimbableShape`: the collision shape, empty for + /// climbable blocks and open trapdoors. + fn non_climbable_shape(&self, p: [i32; 3]) -> VoxelShape { + let state = self.world.block(p[0], p[1], p[2]); + let name = &self.res.facts.get(state).name; + let open_trapdoor = name.ends_with("_trapdoor") + && self + .res + .assets + .registry + .state(state) + .and_then(|s| s.properties.get("open")) + .is_some_and(|v| v == "true"); + if self.block_in_tag("minecraft:climbable", name) || open_trapdoor { + return VoxelShape::empty(); + } + let binding = self.collision; + let mut scene = SceneCollisions { + world: &self.world, + binding, + subject: None, + }; + binding + .collision_shape_with_context( + &mut scene, + state, + BlockPos::new(p[0], p[1], p[2]), + &CollisionContext::empty(false), + ) + .unwrap_or_else(|_| VoxelShape::empty()) + } + fn block_in_tag(&self, tag: &str, block: &str) -> bool { + self.res + .items + .block_tags + .get(tag) + .is_some_and(|s| s.contains(block)) + } + /// `EntityType.isBlockDangerous` for the player. + fn dangerous_for_player(&self, p: [i32; 3]) -> bool { + let state = self.world.block(p[0], p[1], p[2]); + let name = &*self.res.facts.get(state).name; + let lit_campfire = (name == "minecraft:campfire" || name == "minecraft:soul_campfire") + && self + .res + .assets + .registry + .state(state) + .and_then(|s| s.properties.get("lit")) + .is_some_and(|v| v == "true"); + // NodeEvaluator.isBurningBlock, then the hurting plants and snow. + self.block_in_tag("minecraft:fire", name) + || matches!( + name, + "minecraft:lava" + | "minecraft:magma_block" + | "minecraft:lava_cauldron" + | "minecraft:wither_rose" + | "minecraft:sweet_berry_bush" + | "minecraft:cactus" + | "minecraft:powder_snow" + ) + || lit_campfire + } + /// `DismountHelper.findSafeDismountLocation` for a standing player. + fn safe_dismount_location(&self, p: [i32; 3], check_dangerous: bool) -> Option { + if check_dangerous && self.dangerous_for_player(p) { + return None; + } + let shape = self.non_climbable_shape(p); + let below = self.non_climbable_shape([p[0], p[1] - 1, p[2]]); + let floor = horizon_core::geometry::block_floor_height(&shape, || &below); + // DismountHelper.isBlockFloorValid. + if floor.is_infinite() || floor >= 1.0 { + return None; + } + if check_dangerous && floor <= 0.0 && self.dangerous_for_player([p[0], p[1] - 1, p[2]]) { + return None; + } + let position = Vec3::new( + f64::from(p[0]) + 0.5, + f64::from(p[1]) + floor, + f64::from(p[2]) + 0.5, + ); + // EntityDimensions.makeBoundingBox for 0.6 by 1.8 (the half width is a float). + let half = f64::from(0.6f32 / 2.0); + let bounds = Aabb::new( + Vec3::new(position.x - half, position.y, position.z - half), + Vec3::new( + position.x + half, + position.y + f64::from(1.8f32), + position.z + half, + ), + ); + let mut scene = SceneCollisions { + world: &self.world, + binding: self.collision, + subject: None, + }; + if !no_collision_empty(&mut scene, bounds) { + return None; + } + let name = |q: [i32; 3]| { + self.res + .facts + .get(self.world.block(q[0], q[1], q[2])) + .name + .clone() + }; + if self.block_in_tag("minecraft:invalid_spawn_inside", &name(p)) + || self.block_in_tag( + "minecraft:invalid_spawn_inside", + &name([p[0], p[1] + 1, p[2]]), + ) + { + return None; + } + // WorldBorder.isWithinBounds(box). + let (lo, hi) = (bounds.min(Axis::X), bounds.max(Axis::X) - 1.0e-5); + let (lz, hz) = (bounds.min(Axis::Z), bounds.max(Axis::Z) - 1.0e-5); + (self.border.contains(lo, lz) && self.border.contains(hi, hz)).then_some(position) + } + /// `RespawnAnchorBlock.findStandUpPosition`: a safe spot around the + /// anchor, else any spot. + pub(super) fn anchor_stand_up(&self, pos: [i32; 3]) -> Option { + for check in [true, false] { + for d in respawn_offsets() { + let p = [pos[0] + d[0], pos[1] + d[1], pos[2] + d[2]]; + if let Some(at) = self.safe_dismount_location(p, check) { + return Some(at); + } + } + } + None + } + /// `ServerPlayer.findRespawnAndUseSpawnBlock` for an anchor config in the + /// loaded dimension: the position and yaw, using a charge. + pub(super) fn find_respawn_and_use( + &mut self, + c: RespawnConfig, + consume: bool, + ) -> Result> { + let state = self.world.block(c.pos[0], c.pos[1], c.pos[2]); + if !(self.is_anchor(state) + && (c.forced || self.anchor_charges(state) > 0) + && self.anchor_works()) + { + return Ok(None); + } + let stand = self.anchor_stand_up(c.pos); + if !c.forced + && consume + && stand.is_some() + && let Some(next) = self.anchor_with_charges(state, self.anchor_charges(state) - 1) + { + self.level_set(c.pos, next)?; + } + Ok(stand.map(|p| (p, look_at_yaw(p, c.pos)))) + } + /// The death screen's respawn with an anchor as the respawn point: travel + /// to its dimension and wait for its chunks (`travelling`), then resolve + /// it in [`Game::place_respawned`]. + pub(super) fn begin_anchor_respawn(&mut self) -> Result { + let Some(config) = self.respawn_config else { + return Ok(false); + }; + if self.player.is_none() { + return Ok(false); + } + if self.dim != config.dim { + self.end_portal_travel = false; + self.enter_dimension(config.dim)?; + } else { + let player = self.player.take().ok_or("player")?; + self.travelling = Some((player, Vec3::ZERO)); + } + let target = Vec3::new( + f64::from(config.pos[0]) + 0.5, + f64::from(config.pos[1]), + f64::from(config.pos[2]) + 0.5, + ); + if let Some((_, t)) = self.travelling.as_mut() { + *t = target; + } + self.end_travel = false; + self.respawn_travel = Some(config); + Ok(true) + } + /// `PlayerList.respawn` at an anchor once its dimension is loaded around + /// it: a fresh player at the stand-up position facing the anchor and the + /// deplete sound, or, with no anchor left, the world spawn and + /// `block.minecraft.spawn.not_valid`. + pub(super) fn place_respawned(&mut self, config: RespawnConfig) -> Result<()> { + match self.find_respawn_and_use(config, true)? { + Some((position, yaw)) => { + let mut player = PlayerMotion::new(self.motion, position)?; + player.yaw = yaw; + player.head_yaw = yaw; + self.yaw = yaw; + self.pitch = 0.0; + player.pitch = 0.0; + self.eye = 1.62; + self.previous_eye = 1.62; + self.clock.reset(); + self.previous_position = position; + self.player = Some(player); + self.sway = Default::default(); + self.apply_equipment(); + // ClientboundSoundPacket at the block's corner, seeded from the level random. + let state = self + .world + .block(config.pos[0], config.pos[1], config.pos[2]); + if self.is_anchor(state) { + let _seed = self.world.random.next_long(); + let at = [ + f64::from(config.pos[0]), + f64::from(config.pos[1]), + f64::from(config.pos[2]), + ]; + self.audio + .play("minecraft:block.respawn_anchor.deplete", Some(at), 1.0, 1.0); + } + Ok(()) + } + None => { + // TeleportTransition.missingRespawnBlock: the world spawn, and + // the point is forgotten. + self.respawn_config = None; + self.system_message(Text::translate("block.minecraft.spawn.not_valid", &[])); + let dead = PlayerMotion::new(self.motion, Vec3::ZERO)?; + if self.dim != Dim::Overworld { + // A dead stand-in travels; the arrival makes a fresh player. + let mut dead = dead; + dead.set_health(0.0, false)?; + self.player = Some(dead); + self.end_portal_travel = true; + let result = self.enter_dimension(Dim::Overworld); + self.end_portal_travel = false; + self.end_travel = true; + return result; + } + self.player = None; + self.spawn_player() + } + } + } +} + +/// `RespawnPosAngle.calculateLookAtYaw`: the yaw from the position to the +/// bottom centre of the block. +fn look_at_yaw(position: Vec3, block: [i32; 3]) -> f32 { + let d = Vec3::new( + f64::from(block[0]) + 0.5 - position.x, + f64::from(block[1]) - position.y, + f64::from(block[2]) + 0.5 - position.z, + ) + .normalize(); + // Mth.atan2(z, x) * 180.0F / (float) Math.PI - 90.0: the compiled code + // multiplies by the folded float constant widened to double. + let degrees = horizon_core::geometry::trig::atan2(d.z, d.x) + * f64::from(horizon_core::geometry::trig::RAD_TO_DEG) + - 90.0; + wrap_degrees(degrees) as f32 +} +/// `Mth.wrapDegrees(double)`. +fn wrap_degrees(degrees: f64) -> f64 { + let mut d = degrees % 360.0; + if d >= 180.0 { + d -= 360.0; + } + if d < -180.0 { + d += 360.0; + } + d +} diff --git a/crates/horizon-client/src/game/screens.rs b/crates/horizon-client/src/game/screens.rs index 96a4dc6c4..1de93e862 100644 --- a/crates/horizon-client/src/game/screens.rs +++ b/crates/horizon-client/src/game/screens.rs @@ -261,6 +261,16 @@ impl Game<'_> { self.toggles.respawn(); self.remote_respawn(); } + Some(0) if self.respawn_config.is_some() => { + // LocalPlayer.respawn: KeyMapping.resetToggleKeys. + self.toggles.respawn(); + // PlayerList.respawn at the respawn anchor, once it is loaded. + self.begin_anchor_respawn()?; + self.screen = Screen::Playing; + self.ui.death_text = None; + self.spawn_player()?; + self.capture(true); + } Some(0) => { // LocalPlayer.respawn: KeyMapping.resetToggleKeys. self.toggles.respawn(); diff --git a/crates/horizon-client/src/items.rs b/crates/horizon-client/src/items.rs index 9892243fc..f336d432e 100644 --- a/crates/horizon-client/src/items.rs +++ b/crates/horizon-client/src/items.rs @@ -601,6 +601,7 @@ impl Items { properties: &empty, held: None, killed_by_player: false, + explosion_radius: None, }; ctx.evaluate(table, random) } @@ -662,7 +663,22 @@ impl Items { random: &mut impl RandomSource, sequences: Option<(&mut crate::random_sequences::RandomSequences, i64)>, ) -> Vec { - let drops = self.block_drops_raw(registry, state, held, random, sequences); + self.block_drops_exploded(registry, state, held, dynamic, random, sequences, None) + } + /// `block_drops_full` for a block an explosion destroys: `explosion` + /// is its radius when the explosion decays drops (`DESTROY_WITH_DECAY`). + #[allow(clippy::too_many_arguments)] + pub fn block_drops_exploded( + &self, + registry: &BlockRegistry, + state: BlockStateId, + held: Option<&ItemStack>, + dynamic: &[ItemStack], + random: &mut impl RandomSource, + sequences: Option<(&mut crate::random_sequences::RandomSequences, i64)>, + explosion: Option, + ) -> Vec { + let drops = self.block_drops_raw(registry, state, held, random, sequences, explosion); if !drops.iter().any(|d| d.item.starts_with(DYNAMIC)) { return drops; } @@ -684,6 +700,7 @@ impl Items { held: Option<&ItemStack>, random: &mut impl RandomSource, sequences: Option<(&mut crate::random_sequences::RandomSequences, i64)>, + explosion_radius: Option, ) -> Vec { let Some(block) = registry.state(state) else { return vec![]; @@ -713,6 +730,7 @@ impl Items { properties: &block.properties, held, killed_by_player: false, + explosion_radius, }; return ctx.evaluate(table, random); } @@ -722,6 +740,7 @@ impl Items { properties: &block.properties, held, killed_by_player: false, + explosion_radius, }; ctx.evaluate(table, random) } @@ -744,6 +763,7 @@ impl Items { properties: &empty, held, killed_by_player, + explosion_radius: None, }; ctx.evaluate(table, random) } @@ -775,6 +795,7 @@ impl Items { properties: &block.properties, held: None, killed_by_player: false, + explosion_radius: None, }; match table.get("random_sequence").and_then(Value::as_str) { Some(sequence) => ctx.evaluate(table, sequences.get(sequence, seed)), @@ -799,6 +820,7 @@ impl Items { properties: &empty, held, killed_by_player, + explosion_radius: None, }; ctx.evaluate(table, random) } @@ -820,6 +842,7 @@ impl Items { properties: &empty, held, killed_by_player, + explosion_radius: None, }; ctx.evaluate(table, random) } @@ -859,6 +882,8 @@ struct LootContext<'a> { properties: &'a BTreeMap, held: Option<&'a ItemStack>, killed_by_player: bool, + /// `LootContextParams.EXPLOSION_RADIUS`: an explosion that decays drops. + explosion_radius: Option, } impl LootContext<'_> { /// Level of an enchantment on the tool / killer's weapon. @@ -920,7 +945,10 @@ impl LootContext<'_> { _ => return true, }; match kind { - "minecraft:survives_explosion" => true, + // ExplosionCondition: 1 / radius under a decaying explosion. + "minecraft:survives_explosion" => self + .explosion_radius + .is_none_or(|r| random.next_float() <= 1.0 / r), "minecraft:tool/can_silk_touch" => self.enchantment_level("minecraft:silk_touch") > 0, "minecraft:tool/can_shear" => self.held.is_some_and(|h| &*h.item == "minecraft:shears"), "minecraft:inverted" => !self.condition(&c["term"], random), @@ -1205,6 +1233,15 @@ impl LootContext<'_> { } } } + // ApplyExplosionDecay: each item survives with 1 / radius. + "minecraft:explosion_decay" => { + if let Some(radius) = self.explosion_radius { + let probability = 1.0 / radius; + stack.count = (0..stack.count) + .filter(|_| random.next_float() <= probability) + .count() as u32; + } + } "minecraft:limit_count" => { let limit = &f["limit"]; if let Some(min) = limit["min"].as_i64() { @@ -1238,6 +1275,7 @@ mod tests { properties: props, held, killed_by_player: block.is_empty(), + explosion_radius: None, } } diff --git a/crates/horizon-client/src/save.rs b/crates/horizon-client/src/save.rs index 94b60f3b0..7a90871c2 100644 --- a/crates/horizon-client/src/save.rs +++ b/crates/horizon-client/src/save.rs @@ -1732,6 +1732,9 @@ pub struct Level { pub day_time: i64, /// The player's respawn point (bed, or the world spawn). pub spawn: Option<[f64; 3]>, + /// A respawn point in another dimension than the Overworld (a respawn + /// anchor): dimension, block, yaw and `forced`. + pub respawn_elsewhere: Option<(String, [i32; 3], f32, bool)>, pub position: Option<[f64; 3]>, pub rotation: [f32; 2], pub health: f32, @@ -1924,7 +1927,18 @@ impl Level { && let Some(Tag::IntArray(pos)) = respawn.get("pos") && pos.len() == 3 { - self.spawn = Some([f64::from(pos[0]), f64::from(pos[1]), f64::from(pos[2])]); + let dimension = + text(respawn.get("dimension")).unwrap_or_else(|| "minecraft:overworld".into()); + if dimension == "minecraft:overworld" { + self.spawn = Some([f64::from(pos[0]), f64::from(pos[1]), f64::from(pos[2])]); + } else { + let yaw = match respawn.get("yaw") { + Some(Tag::Float(b)) => f32::from_bits(*b), + _ => 0.0, + }; + let forced = number(respawn.get("forced")).is_some_and(|v| v != 0); + self.respawn_elsewhere = Some((dimension, [pos[0], pos[1], pos[2]], yaw, forced)); + } } let mut inventory = Vec::new(); let mut inventory_components = HashMap::new(); @@ -2116,8 +2130,19 @@ impl Level { if let Some(pos) = self.position { entries.push(("Pos", doubles(&pos))); } - // A respawn point other than the world spawn (a bed). - if let Some(s) = self.spawn { + // A respawn point other than the world spawn: an anchor elsewhere, or a bed. + if let Some((dimension, block, yaw, forced)) = &self.respawn_elsewhere { + let mut respawn = vec![ + ("dimension", string(dimension)), + ("pos", Tag::IntArray(block.to_vec())), + ("yaw", Tag::Float(yaw.to_bits())), + ("pitch", Tag::Float(0f32.to_bits())), + ]; + if *forced { + respawn.push(("forced", Tag::Byte(1))); + } + entries.push(("respawn", Tag::compound(respawn))); + } else if let Some(s) = self.spawn { let block = [ s[0].floor() as i32, s[1].floor() as i32, diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockUpdateOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockUpdateOracle.java index 4093c0538..077a6dbff 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockUpdateOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockUpdateOracle.java @@ -351,6 +351,28 @@ public final class VanillaBlockUpdateOracle { return attributes; } @Override public net.minecraft.world.level.dimension.DimensionType dimensionType() { return type != null ? type : OVERWORLD_TYPE; } + /** + * ServerLevel.explode without the players to send the packet to: the + * ServerExplosion runs, then the explosion sound the client plays at + * the centre is logged. + */ + @Override public void explode(Entity source, net.minecraft.world.damagesource.DamageSource damageSource, + net.minecraft.world.level.ExplosionDamageCalculator calculator, double x, double y, double z, float r, boolean fire, + net.minecraft.world.level.Level.ExplosionInteraction type, net.minecraft.core.particles.ParticleOptions small, + net.minecraft.core.particles.ParticleOptions large, net.minecraft.util.random.WeightedList blockParticles, + net.minecraft.core.Holder sound) { + java.util.function.Function, net.minecraft.world.level.Explosion.BlockInteraction> destroy = + rule -> rules.get(rule) ? net.minecraft.world.level.Explosion.BlockInteraction.DESTROY_WITH_DECAY : net.minecraft.world.level.Explosion.BlockInteraction.DESTROY; + var interaction = switch (type) { + case NONE -> net.minecraft.world.level.Explosion.BlockInteraction.KEEP; + case BLOCK -> destroy.apply(GameRules.BLOCK_EXPLOSION_DROP_DECAY); + case MOB -> rules.get(GameRules.MOB_GRIEFING) ? destroy.apply(GameRules.MOB_EXPLOSION_DROP_DECAY) : net.minecraft.world.level.Explosion.BlockInteraction.KEEP; + case TNT -> destroy.apply(GameRules.TNT_EXPLOSION_DROP_DECAY); + case TRIGGER -> net.minecraft.world.level.Explosion.BlockInteraction.TRIGGER_BLOCK; + }; + new net.minecraft.world.level.ServerExplosion(this, source, damageSource, calculator, new Vec3(x, y, z), r, fire, interaction).explode(); + if (source == null || !source.isSilent()) emit("S " + pos(BlockPos.containing(x, y, z)) + " " + sound.value().location()); + } /** The overworld (fire in an obsidian frame lights a portal here). */ @Override public net.minecraft.resources.ResourceKey dimension() { return dimensionKey != null ? dimensionKey : net.minecraft.world.level.Level.OVERWORLD; } @Override public long getOverworldClockTime() { return DAY.totalTicks(); } diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDispenserOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDispenserOracle.java index abbd13dc4..e1c3ff4e8 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDispenserOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDispenserOracle.java @@ -247,10 +247,18 @@ public final class VanillaDispenserOracle { w.registries = ParityData.access; w.server.loot.delegate = ParityData.loot; VanillaBlockUpdateOracle.set(Level.class, w, "damageSources", new net.minecraft.world.damagesource.DamageSources(ParityData.access)); + if (f.has("dim") && f.get("dim").getAsString().equals("nether")) { + // The Nether's dimension type and attributes (respawn anchors work, beds explode). + if (NETHER == null) NETHER = VanillaBlockUpdateOracle.loadDimensionType(net.minecraft.world.level.dimension.BuiltinDimensionTypes.NETHER); + w.type = NETHER; + w.dimensionKey = Level.NETHER; + w.attributes = net.minecraft.world.attribute.EnvironmentAttributeSystem.builder().addConstantLayer(NETHER.attributes()).build(); + } if (f.has("rules")) { for (var rule : f.getAsJsonObject("rules").entrySet()) { if (rule.getKey().equals("tnt_explodes")) w.rules.set(GameRules.TNT_EXPLODES, rule.getValue().getAsBoolean(), null); if (rule.getKey().equals("spawner_blocks_work")) w.rules.set(GameRules.SPAWNER_BLOCKS_WORK, rule.getValue().getAsBoolean(), null); + if (rule.getKey().equals("block_explosion_drop_decay")) w.rules.set(GameRules.BLOCK_EXPLOSION_DROP_DECAY, rule.getValue().getAsBoolean(), null); } } if (f.has("items")) { @@ -302,6 +310,8 @@ public final class VanillaDispenserOracle { used = use(w, origin, f.getAsJsonObject("use")); } else if (f.has("use_item")) { used = useItem(w, origin, f.getAsJsonObject("use_item")); + } else if (f.has("respawn_at")) { + used = respawnAt(w, origin, f.getAsJsonObject("respawn_at")); } else if (f.has("hopper")) { // HopperBlockEntity.pushItemsTick, once. var hopper = (net.minecraft.world.level.block.entity.HopperBlockEntity) w.getBlockEntity(origin); @@ -379,6 +389,8 @@ public final class VanillaDispenserOracle { result.add("rng " + w.rng.nextLong()); } + static net.minecraft.world.level.dimension.DimensionType NETHER; + /** The player of a "use" case: its main hand, game mode and the statistics it is awarded. */ static final class User extends net.minecraft.server.level.ServerPlayer { VanillaBlockUpdateOracle.World world; @@ -506,8 +518,15 @@ public final class VanillaDispenserOracle { var advancements = (net.minecraft.server.PlayerAdvancements) VanillaBlockUpdateOracle.allocate.invoke(VanillaBlockUpdateOracle.unsafe, net.minecraft.server.PlayerAdvancements.class); VanillaBlockUpdateOracle.set(net.minecraft.server.PlayerAdvancements.class, advancements, "activeTriggers", new HashMap<>()); VanillaBlockUpdateOracle.set(net.minecraft.server.level.ServerPlayer.class, player, "advancements", advancements); - // Standing three blocks south of the clicked block, looking down at it. - var at = net.minecraft.world.phys.Vec3.atBottomCenterOf(pos).add(0, 1, 3); + // Standing three blocks (or `distance`) south of the clicked block, looking down at it. + double distance = use.has("distance") ? use.get("distance").getAsDouble() : 3; + var at = net.minecraft.world.phys.Vec3.atBottomCenterOf(pos).add(0, 1, distance); + if (use.has("respawn")) { + var r = use.getAsJsonArray("respawn"); + BlockPos point = new BlockPos(r.get(0).getAsInt(), r.get(1).getAsInt(), r.get(2).getAsInt()); + player.setRespawnPosition(new net.minecraft.server.level.ServerPlayer.RespawnConfig( + net.minecraft.world.level.storage.LevelData.RespawnData.of(w.dimension(), point, 0.0F, 0.0F), false), false); + } VanillaBlockUpdateOracle.set(Entity.class, player, "position", at); VanillaBlockUpdateOracle.set(Entity.class, player, "blockPosition", BlockPos.containing(at)); VanillaBlockUpdateOracle.set(Entity.class, player, "xRot", 90f); @@ -526,9 +545,33 @@ public final class VanillaDispenserOracle { } List out = new ArrayList<>(player.stats); out.add("held " + ParityData.canon(player.hand) + " using " + (player.using == null ? "-" : player.using)); + var respawn = player.getRespawnConfig(); + out.add("respawn " + (respawn == null ? "-" : respawn.respawnData().dimension().identifier() + " " + VanillaBlockUpdateOracle.pos(respawn.respawnData().pos()))); return out; } + /** + * ServerPlayer.findRespawnAndUseSpawnBlock for a respawn point at `pos` + * (a respawn anchor, in the Nether or not): the position, the yaw that + * looks at the block, and the charge used (a block change). + */ + static List respawnAt(VanillaBlockUpdateOracle.World w, BlockPos pos, JsonObject op) throws Exception { + var config = new net.minecraft.server.level.ServerPlayer.RespawnConfig( + net.minecraft.world.level.storage.LevelData.RespawnData.of(w.dimension(), pos, 0.0F, 0.0F), op.get("forced").getAsBoolean()); + Method find = net.minecraft.server.level.ServerPlayer.class.getDeclaredMethod("findRespawnAndUseSpawnBlock", + ServerLevel.class, net.minecraft.server.level.ServerPlayer.RespawnConfig.class, boolean.class); + find.setAccessible(true); + var found = (Optional) find.invoke(null, w, config, op.get("consume").getAsBoolean()); + if (found.isEmpty()) return List.of("respawn none"); + Object angle = found.get(); + Method position = angle.getClass().getDeclaredMethod("position"); + Method yaw = angle.getClass().getDeclaredMethod("yaw"); + position.setAccessible(true); + yaw.setAccessible(true); + var p = (net.minecraft.world.phys.Vec3) position.invoke(angle); + return List.of("respawn " + num(p.x) + " " + num(p.y) + " " + num(p.z) + " " + Float.floatToRawIntBits((float) yaw.invoke(angle))); + } + /** The level's block entity positions by x, y, z. */ static List sortedEntities(VanillaBlockUpdateOracle.World w) { List out = new ArrayList<>(w.blockEntities == null ? List.of() : w.blockEntities.keySet()); diff --git a/tools/test_use_item_on_parity.py b/tools/test_use_item_on_parity.py index f71bbbe4d..9c860ce64 100644 --- a/tools/test_use_item_on_parity.py +++ b/tools/test_use_item_on_parity.py @@ -1,7 +1,7 @@ #!/usr/bin/env python3 """Compare a player's right click on a block with vanilla's, for items that are both food and blocks (sweet and glow berries, carrots, potatoes), for sweet -berry bushes and for spawn eggs used on a monster spawner. +berry bushes, for spawn eggs used on a monster spawner and for respawn anchors. Every case has a block at the origin, something above it, and a player three blocks south, survival or creative, hungry or full, sneaking or not, who @@ -11,12 +11,18 @@ harness (`VanillaDispenserOracle.useItem`): the block's `useItemOn` and `useWithoutItem` (picking a bush's berries, `SweetBerryBushBlock.useItemOn` passing bone meal on), then `ItemStack.useOn` (`BlockItem.place` with its `mayPlaceOn` rules, `BoneMealItem.useOn`, eating a consumable that could -not be placed, and `SpawnEggItem.useOn` setting a spawner's mob). Horizon runs +not be placed, and `SpawnEggItem.useOn` setting a spawner's mob). Respawn +anchors are charged with glowstone, set the respawn point in the Nether and +explode elsewhere (`RespawnAnchorBlock`, through the stand-in level's real +`ServerExplosion`, with water at the anchor). Respawn cases call +`ServerPlayer.findRespawnAndUseSpawnBlock` on an anchor among blocks +(`RespawnAnchorBlock.findStandUpPosition` through `DismountHelper`): the +position, the yaw that faces the anchor and the charge it uses. Horizon runs `use_item_as_player` on that hit in a headless game -(`HORIZON_DISPENSE_FIXTURE`). Both print block changes, dropped items, -level events, sounds, game events, the used statistic, the held stack, the -item the player started using, spawners' next spawn data, potentials and -delay, system messages and the level random afterwards. +(`HORIZON_DISPENSE_FIXTURE`). Both print block changes, dropped items, level +events, sounds, game events, the used statistic, the held stack, the item the +player started using, spawners' next spawn data, potentials and delay, the +player's respawn point, system messages and the level random afterwards. """ import json import os @@ -37,6 +43,74 @@ ITEMS = ['sweet_berries', 'sweet_berries', 'sweet_berries', 'glow_berries', 'car # What is in the way above the clicked block. ABOVE = ['air'] * 8 + ['short_grass', 'snow', 'stone', 'water', 'dead_bush', 'fern'] EGGS = ['zombie', 'skeleton', 'spider', 'cave_spider', 'pig', 'creeper', 'blaze', 'ghast', 'villager', 'bee', 'cod'] +# What stands around an anchor that explodes. +AROUND = ['stone', 'dirt', 'oak_planks', 'cobblestone', 'glass', 'obsidian', 'netherrack', 'water', 'tnt', 'oak_log', + 'grass_block', 'soul_sand', 'gravel', 'crying_obsidian'] + + +STAND = ['air'] * 6 + ['stone', 'stone', 'oak_slab', 'snow', 'lava', 'magma_block', 'fire', 'cactus', 'water', + 'ladder', 'oak_trapdoor', 'short_grass', 'white_carpet', 'campfire', 'sweet_berry_bush', + 'oak_fence', 'powder_snow', 'farmland', 'soul_sand', 'cobweb', 'end_portal'] + + +def respawn_case(rng, states, case): + """Respawning at an anchor with blocks around it.""" + charges = rng.choice([0, 1, 1, 2, 4]) + cells = [[0, 0, 0, states.get('respawn_anchor', charges=str(charges))]] + for dy in (-2, -1, 0, 1, 2): + for dx in range(-1, 2): + for dz in range(-1, 2): + if (dx, dy, dz) == (0, 0, 0): + continue + if dy == -1 or dy == -2: + name = rng.choice(['stone'] * 6 + STAND) + else: + name = rng.choice(['air'] * 3 + STAND) + if name == 'air': + continue + state = states.any(rng, name) if name in ('oak_trapdoor', 'oak_slab', 'snow', 'campfire', 'water', 'ladder') else states.get(name) + cells.append([dx, dy, dz, state]) + if rng.random() < 0.6: + case['dim'] = 'nether' + case['respawn_at'] = {'forced': rng.random() < 0.2, 'consume': rng.random() < 0.8} + case['cells'] = cells + + +def anchor_case(rng, states, case): + """A respawn anchor clicked in the Nether or the Overworld, with blocks + and water around it.""" + charges = rng.choice([0, 0, 1, 2, 3, 4, 4]) + cells = [[0, 0, 0, states.get('respawn_anchor', charges=str(charges))], + [0, -1, 0, states.get(rng.choice(['netherrack', 'stone', 'soul_sand', 'obsidian', 'soul_soil']))]] + taken = {(0, 0, 0), (0, -1, 0)} + for _ in range(rng.choice([0, 3, 8, 20, 40])): + p = (rng.randrange(-3, 4), rng.randrange(-2, 3), rng.randrange(-3, 4)) + if p in taken: + continue + taken.add(p) + name = rng.choice(AROUND) + state = states.any(rng, 'water') if name == 'water' and rng.random() < 0.5 else states.get(name) + cells.append([*p, state]) + if rng.random() < 0.2: + # Water that would flow into the anchor's place. + d = rng.choice([(1, 0, 0), (-1, 0, 0), (0, 0, 1), (0, 0, -1), (0, 1, 0)]) + cells = [c for c in cells if tuple(c[:3]) != d] + cells.append([*d, states.any(rng, 'water') if rng.random() < 0.4 else states.get('water')]) + nether = rng.random() < 0.5 + if nether: + case['dim'] = 'nether' + item = rng.choice(['glowstone'] * 5 + ['apple', '-', 'stone', 'glowstone_dust']) + count = rng.choice([1, 1, 16, 64]) + use = {'item': '-' if item == '-' else d_plain(item, count), 'creative': rng.random() < 0.2, + 'sneaking': rng.random() < 0.1, 'food': 20, + # Away from the blast: the stand-in player is not an entity of the level. + 'distance': 3 if nether else 12} + if rng.random() < 0.3: + use['respawn'] = rng.choice([[0, 0, 0], [5, 0, 5]]) + if rng.random() < 0.2: + case['rules'] = {'block_explosion_drop_decay': False} + case['use_item'] = use + case['cells'] = cells def cases(facts, count, seed): @@ -46,6 +120,18 @@ def cases(facts, count, seed): case = {**h.environment(rng), 'pos': [0, 0, 0]} case.pop('raining', None) case.pop('thundering', None) + if rng.random() < 0.1: + respawn_case(rng, states, case) + case['items'] = [] + case['mode'] = 'dispense' + yield case + continue + if rng.random() < 0.15: + anchor_case(rng, states, case) + case['items'] = [] + case['mode'] = 'dispense' + yield case + continue cells = [] item = rng.choice(ITEMS) if rng.random() < 0.15: @@ -83,8 +169,14 @@ def cases(facts, count, seed): yield case +def d_plain(item, count): + return d.plain(item, count) + + def kind(case, facts): first = facts.states[case['cells'][0][3]][0].split(':')[1] + if 'respawn_at' in case: + return f'respawn at {first}' item = case['use_item']['item'] item = item.split('"')[1].split(':')[1] if item != '-' else 'empty hand' return f'{item} on {first}' @@ -119,13 +211,15 @@ def main(): rust = h.split_cases((work / 'rust.txt').read_text(), ignore) assert len(native) == len(rust) == len(all_cases), (len(native), len(rust), len(all_cases)) groups, errors = {}, {} - planted = eaten = 0 + planted = eaten = respawned = exploded = 0 for case, a, b in zip(all_cases, native, rust): if a and a[0].startswith('error'): errors.setdefault(a[0], []).append(case) continue planted += any(line.startswith('set 0,1,0') for line in a) eaten += any(line.startswith('held') and not line.endswith('using -') for line in a) + respawned += any(line.startswith('respawn ') and line != 'respawn none' and 'respawn_at' in case for line in a) + exploded += any(line.endswith(' minecraft:explode') for line in a) if not d.same(a, b): groups.setdefault(kind(case, facts), []).append((case, a, b)) for name, entries in sorted(errors.items(), key=lambda e: -len(e[1])): @@ -133,13 +227,14 @@ def main(): for name, entries in sorted(groups.items(), key=lambda e: -len(e[1])): print(f'{name}: {len(entries)} differing') for case, a, b in entries[:args.show]: - print(' case ' + d.describe(case, facts) + ' use=' + json.dumps(case['use_item'])) + print(' case ' + d.describe(case, facts) + ' use=' + json.dumps(case.get('use_item', case.get('respawn_at')))) print(' native ' + ' | '.join(sorted(a))) print(' rust ' + ' | '.join(sorted(b))) total = sum(len(v) for v in groups.values()) skipped = sum(len(v) for v in errors.values()) print(f'{len(all_cases) - total - skipped}/{len(all_cases) - skipped} cases match ({skipped} oracle errors); ' - f'vanilla planted in {planted} and started eating in {eaten}') + f'vanilla planted in {planted}, started eating in {eaten}, exploded {exploded} times and found a respawn ' + f'spot in {respawned}') h.finish(total + skipped) From 190f89b21452143b33b739fe96ad329b391d9235 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 14 Oct 2026 20:17:53 +0200 Subject: [PATCH 16/24] Beds and straw beds blow up when used in the Nether and the End A right click on a bed in the Nether or the End tried to sleep in it (and set the respawn point) as in the Overworld. AbstractBedBlock.useWithoutItem reads the dimension's bed rule, which in the Nether and the End is destroy_on_use: BedBlock.destroyOnUse removes the head, then the foot behind it if it is still the bed, and explodes at the head (power 5, fire, BLOCK interaction, the bad_respawn_point damage source: "Intentional Game Design"); StrawBedBlock.destroyBed plays block.straw_bed.break_leave and removes it. tools/test_use_item_on_parity.py clicks beds and straw beds (head or foot, whole or missing their other half, among blocks) in the Nether and the End, through vanilla's real explosion; the oracle gains the End. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game.rs | 3 ++ .../src/game/dispense_fixture.rs | 6 ++- .../horizon-client/src/game/respawn_anchor.rs | 53 +++++++++++++++++++ .../parity/VanillaDispenserOracle.java | 8 ++- tools/test_use_item_on_parity.py | 47 +++++++++++++++- 5 files changed, 112 insertions(+), 5 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 71610bfb7..890387ac8 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -1711,6 +1711,9 @@ impl Game<'_> { } LevelEvent::Player { pos, effect, .. } => match effect { PlayerEffect::OpenMenu => self.open_menu([pos.x, pos.y, pos.z]), + PlayerEffect::Sleep if self.beds_destroy_on_use() => { + self.destroy_bed_on_use([pos.x, pos.y, pos.z])? + } PlayerEffect::Sleep => self.try_sleep([pos.x, pos.y, pos.z]), PlayerEffect::GiveItem(item) => { if let Some(rest) = self.give(ItemStack { diff --git a/crates/horizon-client/src/game/dispense_fixture.rs b/crates/horizon-client/src/game/dispense_fixture.rs index 6e10b53b1..355a188da 100644 --- a/crates/horizon-client/src/game/dispense_fixture.rs +++ b/crates/horizon-client/src/game/dispense_fixture.rs @@ -164,8 +164,10 @@ impl Game<'_> { } } self.world.game_time = case["time"].as_i64().unwrap_or(0); - if case["dim"].as_str() == Some("nether") { - self.dim = super::Dim::Nether; + match case["dim"].as_str() { + Some("nether") => self.dim = super::Dim::Nether, + Some("end") => self.dim = super::Dim::End, + _ => {} } // The oracle level's clock stands at day time 6000. self.world.day_time = 6000; diff --git a/crates/horizon-client/src/game/respawn_anchor.rs b/crates/horizon-client/src/game/respawn_anchor.rs index b1b9e18fe..f2f21469f 100644 --- a/crates/horizon-client/src/game/respawn_anchor.rs +++ b/crates/horizon-client/src/game/respawn_anchor.rs @@ -240,6 +240,59 @@ impl Game<'_> { ]; self.block_explosion(center, in_water.then_some(pos)) } + /// `BedRule.destroyOnUse` of the dimension's `bed_rule` and + /// `straw_bed_rule`: true in the Nether and the End. + pub(super) fn beds_destroy_on_use(&self) -> bool { + self.dim != Dim::Overworld + } + /// `AbstractBedBlock.useWithoutItem` where the bed rule destroys on use + /// (the bed's head at `head`): `BedBlock.destroyOnUse` removes both + /// halves and explodes; `StrawBedBlock` just falls apart. + pub(super) fn destroy_bed_on_use(&mut self, head: [i32; 3]) -> Result<()> { + let state = self.world.block(head[0], head[1], head[2]); + let name = self.res.facts.get(state).name.clone(); + let center = [ + f64::from(head[0]) + 0.5, + f64::from(head[1]) + 0.5, + f64::from(head[2]) + 0.5, + ]; + if &*name == "minecraft:straw_bed" { + // StrawBedBlock.destroyBed. + self.audio.play( + "minecraft:block.straw_bed.break_leave", + Some(center), + 1.0, + 1.0, + ); + return self.level_set(head, self.world.air); + } + // removeBlock(head), then the foot behind it if it is still this bed. + let facing = self + .res + .assets + .registry + .state(state) + .and_then(|s| s.properties.get("facing").cloned()) + .unwrap_or_default(); + let back = match facing.as_str() { + "north" => [0, 0, 1], + "south" => [0, 0, -1], + "west" => [1, 0, 0], + _ => [-1, 0, 0], + }; + self.level_set(head, self.world.air)?; + let foot = [head[0] + back[0], head[1], head[2] + back[2]]; + if self + .res + .facts + .get(self.world.block(foot[0], foot[1], foot[2])) + .name + == name + { + self.level_set(foot, self.world.air)?; + } + self.block_explosion(center, None) + } /// `Level.explode(null, badRespawnPointExplosion(center), calculator, /// center, 5, true, ExplosionInteraction.BLOCK)` (beds and anchors): /// `water_at` is the block that resists like water. diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDispenserOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDispenserOracle.java index e1c3ff4e8..24cf82ae5 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDispenserOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDispenserOracle.java @@ -253,6 +253,12 @@ public final class VanillaDispenserOracle { w.type = NETHER; w.dimensionKey = Level.NETHER; w.attributes = net.minecraft.world.attribute.EnvironmentAttributeSystem.builder().addConstantLayer(NETHER.attributes()).build(); + } else if (f.has("dim") && f.get("dim").getAsString().equals("end")) { + // The End's (beds explode, anchors do too). + if (END == null) END = VanillaBlockUpdateOracle.loadDimensionType(net.minecraft.world.level.dimension.BuiltinDimensionTypes.END); + w.type = END; + w.dimensionKey = Level.END; + w.attributes = net.minecraft.world.attribute.EnvironmentAttributeSystem.builder().addConstantLayer(END.attributes()).build(); } if (f.has("rules")) { for (var rule : f.getAsJsonObject("rules").entrySet()) { @@ -389,7 +395,7 @@ public final class VanillaDispenserOracle { result.add("rng " + w.rng.nextLong()); } - static net.minecraft.world.level.dimension.DimensionType NETHER; + static net.minecraft.world.level.dimension.DimensionType NETHER, END; /** The player of a "use" case: its main hand, game mode and the statistics it is awarded. */ static final class User extends net.minecraft.server.level.ServerPlayer { diff --git a/tools/test_use_item_on_parity.py b/tools/test_use_item_on_parity.py index 9c860ce64..5b3c40971 100644 --- a/tools/test_use_item_on_parity.py +++ b/tools/test_use_item_on_parity.py @@ -1,7 +1,8 @@ #!/usr/bin/env python3 """Compare a player's right click on a block with vanilla's, for items that are both food and blocks (sweet and glow berries, carrots, potatoes), for sweet -berry bushes, for spawn eggs used on a monster spawner and for respawn anchors. +berry bushes, for spawn eggs used on a monster spawner, for respawn anchors and +for beds in the Nether and the End. Every case has a block at the origin, something above it, and a player three blocks south, survival or creative, hungry or full, sneaking or not, who @@ -17,7 +18,10 @@ explode elsewhere (`RespawnAnchorBlock`, through the stand-in level's real `ServerExplosion`, with water at the anchor). Respawn cases call `ServerPlayer.findRespawnAndUseSpawnBlock` on an anchor among blocks (`RespawnAnchorBlock.findStandUpPosition` through `DismountHelper`): the -position, the yaw that faces the anchor and the charge it uses. Horizon runs +position, the yaw that faces the anchor and the charge it uses. Beds and straw +beds clicked (head or foot, whole or broken) in the Nether and the End blow up +or fall apart (`AbstractBedBlock.useWithoutItem` under the dimension's +`bed_rule`: `BedBlock.destroyOnUse`, `StrawBedBlock.destroyBed`). Horizon runs `use_item_as_player` on that hit in a headless game (`HORIZON_DISPENSE_FIXTURE`). Both print block changes, dropped items, level events, sounds, game events, the used statistic, the held stack, the item the @@ -76,6 +80,39 @@ def respawn_case(rng, states, case): case['cells'] = cells +BED_COLORS = ['red', 'white', 'black', 'cyan', 'lime'] +FACINGS = {'north': (0, -1), 'south': (0, 1), 'west': (-1, 0), 'east': (1, 0)} + + +def bed_case(rng, states, case): + """A bed (or straw bed) clicked in the Nether or the End, among blocks.""" + name = 'straw_bed' if rng.random() < 0.25 else rng.choice(BED_COLORS) + '_bed' + facing = rng.choice(list(FACINGS)) + dx, dz = FACINGS[facing] + # The clicked block is the origin; the other half lies along the facing. + part = rng.choice(['head', 'foot']) + other = (-dx, 0, -dz) if part == 'head' else (dx, 0, dz) + cells = [[0, 0, 0, states.get(name, facing=facing, part=part, occupied='false')], + [0, -1, 0, states.get(rng.choice(['netherrack', 'end_stone', 'obsidian', 'stone']))], + [other[0], -1, other[2], states.get('stone')]] + if rng.random() < 0.9: + cells.append([*other, states.get(name, facing=facing, part='foot' if part == 'head' else 'head', occupied='false')]) + taken = {tuple(c[:3]) for c in cells} + for _ in range(rng.choice([0, 3, 10, 30])): + p = (rng.randrange(-3, 4), rng.randrange(-2, 3), rng.randrange(-3, 4)) + if p in taken: + continue + taken.add(p) + cells.append([*p, states.get(rng.choice(AROUND))]) + case['dim'] = rng.choice(['nether', 'end']) + item = rng.choice(['-', '-', 'apple', 'stone', 'glowstone']) + case['use_item'] = {'item': '-' if item == '-' else d_plain(item, 1), 'creative': rng.random() < 0.2, + 'sneaking': rng.random() < 0.1, 'food': 20, 'distance': 12} + if rng.random() < 0.2: + case['rules'] = {'block_explosion_drop_decay': False} + case['cells'] = cells + + def anchor_case(rng, states, case): """A respawn anchor clicked in the Nether or the Overworld, with blocks and water around it.""" @@ -120,6 +157,12 @@ def cases(facts, count, seed): case = {**h.environment(rng), 'pos': [0, 0, 0]} case.pop('raining', None) case.pop('thundering', None) + if rng.random() < 0.1: + bed_case(rng, states, case) + case['items'] = [] + case['mode'] = 'dispense' + yield case + continue if rng.random() < 0.1: respawn_case(rng, states, case) case['items'] = [] From 72074eb080ac285cb5c665ad966b72d120648042 Mon Sep 17 00:00:00 2001 From: rdbtCVS <87152661+rdbtCVS@users.noreply.github.com> Date: Wed, 14 Oct 2026 19:50:21 +0100 Subject: [PATCH 17/24] Fix LAN host tab list to include connected guests --- crates/horizon-client/src/game/scoreboard.rs | 114 ++++++++++++++++++- 1 file changed, 110 insertions(+), 4 deletions(-) diff --git a/crates/horizon-client/src/game/scoreboard.rs b/crates/horizon-client/src/game/scoreboard.rs index ced283669..e35a9d918 100644 --- a/crates/horizon-client/src/game/scoreboard.rs +++ b/crates/horizon-client/src/game/scoreboard.rs @@ -10,9 +10,11 @@ use horizon_client::{ }, hud::HudBatch, hud_layout, hud_overlays, + lan::guest::Guest, save::{self, uuid_from_text, uuid_text}, scoreboard::{self as sb, Comp, Scoreboard, literal}, scoreboard_cmd::{self, Env, Holder}, + tab_list::TabPlayer, text::Text, }; use horizon_world::nbt::Tag; @@ -581,10 +583,10 @@ impl Game<'_> { impl Game<'_> { /// `Hud.extractTabList`: the player list while the player-list key is - /// held. A single-player world lists only its player, so it shows only - /// with a `list` objective. + /// held. A local world shows it with a joined LAN guest or a `list` + /// objective. pub(super) fn draw_tab_list(&mut self, batch: &mut HudBatch) { - use horizon_client::tab_list::{self, TabInputs, TabPlayer}; + use horizon_client::tab_list::{self, TabInputs}; let chatting = self.remote.is_some() && self.remote_chat_open(); let key = self.screen == super::Screen::Playing && !chatting @@ -600,7 +602,14 @@ impl Game<'_> { let mut me = TabPlayer::new(uuid, PLAYER_NAME); me.game_mode = self.mode_id(); me.skin = "entity/player/wide/steve".into(); - (vec![me], true, Vec::new()) + let guests = self.lan.as_ref().map_or(&[][..], |h| &h.hub.guests); + let players = local_tab_players(me, guests); + let upside_down = players + .iter() + .filter(|p| p.name == "Dinnerbone" || p.name == "Grumm") + .map(|p| p.uuid) + .collect(); + (players, true, upside_down) } }; let board = &self.score.board; @@ -635,6 +644,103 @@ impl Game<'_> { } } +/// The host and guests that have entered the world, rebuilt from live state. +fn local_tab_players(me: TabPlayer, guests: &[Guest]) -> Vec { + let mut players = vec![me]; + players.extend(guests.iter().filter(|g| g.placed).map(|g| { + let mut player = TabPlayer::new(g.uuid, &g.name); + player.game_mode = g.game_mode; + player.latency = g.latency.load(std::sync::atomic::Ordering::Relaxed); + player + })); + players +} + +#[cfg(test)] +mod tab_list_tests { + use super::*; + use horizon_client::{ + lan::{Joined, PlayerSender}, + tab_list, + }; + use horizon_protocol::packets::configuration::ClientInformation; + use std::sync::{ + Arc, + atomic::{AtomicI32, Ordering}, + mpsc, + }; + + fn guest(uuid: u128, name: &str) -> Guest { + let (tx, _rx) = mpsc::channel(); + Guest::new( + Joined { + conn: uuid as u32, + uuid, + name: name.into(), + info: ClientInformation::new(8), + brand: "test".into(), + sender: PlayerSender { + tx, + pending: Arc::default(), + }, + latency: Arc::new(AtomicI32::new(42)), + address: "127.0.0.1:25565".parse().unwrap(), + }, + uuid as i32, + [0.0, 64.0, 0.0], + 8, + ) + } + + #[test] + fn lan_tab_list_tracks_join_and_disconnect() { + let me = TabPlayer::new(1, PLAYER_NAME); + let mut guests = vec![guest(2, "Alex")]; + let players = local_tab_players(me.clone(), &guests); + assert_eq!(players, [me.clone()]); + assert!(!tab_list::visible(true, true, players.len(), false)); + + guests[0].placed = true; + let players = local_tab_players(me.clone(), &guests); + assert_eq!(players.len(), 2); + assert_eq!(players[0], me); + assert_eq!(players[1].uuid, 2); + assert_eq!(players[1].name, "Alex"); + assert!(tab_list::visible(true, true, players.len(), false)); + assert!(!tab_list::visible(false, true, players.len(), false)); + + guests.clear(); + let players = local_tab_players(me, &guests); + assert_eq!(players.len(), 1); + assert!(!tab_list::visible(true, true, players.len(), false)); + assert!(tab_list::visible(true, true, players.len(), true)); + } + + #[test] + fn lan_tab_list_reads_current_guest_state() { + let me = TabPlayer::new(1, PLAYER_NAME); + let mut guests = vec![guest(2, "Alex"), guest(3, "Grumm")]; + for guest in &mut guests { + guest.placed = true; + } + guests[0].game_mode = tab_list::SPECTATOR; + let players = local_tab_players(me.clone(), &guests); + assert_eq!(players.len(), 3); + assert_eq!(players[1].game_mode, tab_list::SPECTATOR); + assert_eq!(players[1].latency, 42); + assert_eq!(players[1].skin, tab_list::default_skin(2)); + assert_eq!(players[2].name, "Grumm"); + + guests[0].game_mode = 1; + guests[0].latency.store(123, Ordering::Relaxed); + guests.remove(1); + let players = local_tab_players(me, &guests); + assert_eq!(players.len(), 2); + assert_eq!(players[1].game_mode, 1); + assert_eq!(players[1].latency, 123); + } +} + /// The commands' view of the game. struct GameEnv<'a, 'b> { g: &'a mut Game<'b>, From 1b1e1291122ee0146c59938901196b93462c75b9 Mon Sep 17 00:00:00 2001 From: rdbtCVS <87152661+rdbtCVS@users.noreply.github.com> Date: Wed, 14 Oct 2026 19:51:23 +0100 Subject: [PATCH 18/24] Fix LAN shutdown when leaving a singleplayer world --- crates/horizon-client/src/game.rs | 2 + tools/test_lan_lifecycle.py | 144 ++++++++++++++++++++++++++++++ 2 files changed, 146 insertions(+) create mode 100644 tools/test_lan_lifecycle.py diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index a5cc64b1d..cfe524711 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -5937,6 +5937,7 @@ impl Game<'_> { if self.remote.is_none() { self.stats.custom("leave_game", 1); } + self.lan_close(false); self.save_game() } fn close_world(&mut self) -> Result<()> { @@ -5950,6 +5951,7 @@ impl Game<'_> { } self.stats.custom("leave_game", 1); self.save_game()?; + self.lan_close(false); horizon_client::crash::clear_detail("World"); self.streaming.paused = true; self.world = World::new(self.res.facts.air, 0); diff --git a/tools/test_lan_lifecycle.py b/tools/test_lan_lifecycle.py new file mode 100644 index 000000000..5344e7564 --- /dev/null +++ b/tools/test_lan_lifecycle.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Check LAN shutdown when leaving a singleplayer world through the pause menu. + +Requires a built horizon-client, prepared resources and a display on Unix: + xvfb-run -a python3 tools/test_lan_lifecycle.py --client target/fast/horizon-client +Worlds and settings are created in a temporary directory. +""" +import argparse +import json +import os +from pathlib import Path +import socket +import subprocess +import tempfile +import time + +ROOT = Path(__file__).resolve().parents[1] +GROUP = '224.0.2.60' +DISCOVERY_PORT = 4445 + + +def command(endpoint, line): + with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as connection: + connection.settimeout(60) + connection.connect(str(endpoint)) + connection.sendall((line + '\n').encode()) + with connection.makefile('r') as reply: + result = json.loads(reply.readline()) + assert 'error' not in result, (line, result) + return result + + +def wait_for(endpoint, line, predicate, timeout=60): + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + try: + result = command(endpoint, line) + except (FileNotFoundError, ConnectionRefusedError): + time.sleep(0.1) + continue + if predicate(result): + return result + time.sleep(0.1) + raise AssertionError(f'timed out waiting for {line}') + + +def announcement(scanner, port, timeout): + deadline = time.monotonic() + timeout + marker = f'[AD]{port}[/AD]'.encode() + while time.monotonic() < deadline: + scanner.settimeout(max(0.001, deadline - time.monotonic())) + try: + message, _ = scanner.recvfrom(4096) + except socket.timeout: + return False + if marker in message: + return True + return False + + +def scenario(endpoint, scanner): + wait_for(endpoint, 'screen', lambda value: value['screen'] == 'title') + command(endpoint, 'open LanLifecycle 0 creative') + wait_for(endpoint, 'status', lambda value: value['player'] is not None + and value['pending_chunks'] == 0) + assert command(endpoint, 'lan status') == {'open': False} + port = 0 + for _ in range(2): + port = command(endpoint, f'lan open {port}')['port'] + with socket.create_connection(('127.0.0.1', port), timeout=2): + pass + assert announcement(scanner, port, 5), 'LAN world was not advertised' + command(endpoint, 'key esc tap') + screen = wait_for(endpoint, 'screen', lambda value: any( + button['label'] == 'Save and Quit to Title' for button in value['buttons'])) + assert screen['screen'] == 'paused', screen + command(endpoint, 'click-button Save and Quit to Title') + wait_for(endpoint, 'screen', lambda value: value['screen'] == 'title') + assert command(endpoint, 'lan status') == {'open': False}, 'LAN stayed open after leaving' + try: + connection = socket.create_connection(('127.0.0.1', port), timeout=2) + except ConnectionRefusedError: + pass + else: + connection.close() + raise AssertionError('LAN still accepts connections after leaving') + # Discard datagrams queued before shutdown, then listen for more than + # two announcement intervals (the pinger sends every 1.5 seconds). + scanner.setblocking(False) + try: + while True: + scanner.recvfrom(4096) + except BlockingIOError: + pass + assert not announcement(scanner, port, 3.5), 'LAN kept advertising after leaving' + command(endpoint, 'open LanLifecycle') + wait_for(endpoint, 'status', lambda value: value['player'] is not None + and value['pending_chunks'] == 0) + assert command(endpoint, 'lan status') == {'open': False}, 'LAN reopened with the world' + command(endpoint, 'lan open 0') + command(endpoint, 'quit') + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--client', type=Path, required=True) + parser.add_argument('--resources', type=Path, default=ROOT / '.local/horizon-client/26.3') + args = parser.parse_args() + client, resources = args.client.resolve(), args.resources.resolve() + with tempfile.TemporaryDirectory(prefix='horizon-lan-') as directory: + work = Path(directory) + endpoint = work / 'control.sock' + with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as scanner: + scanner.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + scanner.bind(('', DISCOVERY_PORT)) + scanner.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, + socket.inet_aton(GROUP) + socket.inet_aton('0.0.0.0')) + with (work / 'client.log').open('w+') as log: + process = subprocess.Popen([ + str(client), '--resources', str(resources), '--render-distance', '2', + '--test-terrain', '--control-socket', str(endpoint), '--timeout-seconds', '180', + ], cwd=work, env=dict(os.environ, HORIZON_HOME=str(work), HORIZON_NO_AUDIO='1', + HORIZON_MENU_STYLE='classic'), + stdout=log, stderr=subprocess.STDOUT) + try: + scenario(endpoint, scanner) + assert process.wait(timeout=20) == 0, 'client exited unsuccessfully' + except Exception: + log.seek(0) + print('\n'.join(log.read().splitlines()[-20:])) + raise + finally: + if process.poll() is None: + process.terminate() + try: + process.wait(timeout=10) + except subprocess.TimeoutExpired: + process.kill() + process.wait(timeout=10) + print('LAN lifecycle passed: leaving stops hosting and discovery; reopening stays private') + + +if __name__ == '__main__': + main() From 0ed50ae6ae9d7c712b3f36f7e8b224682e1a280c Mon Sep 17 00:00:00 2001 From: rdbtCVS <87152661+rdbtCVS@users.noreply.github.com> Date: Wed, 14 Oct 2026 19:53:45 +0100 Subject: [PATCH 19/24] Fix LAN worlds pausing when the host opens menus --- crates/horizon-client/src/game.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index a5cc64b1d..f9de2923c 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -3111,6 +3111,7 @@ impl Game<'_> { /// `Minecraft.pause`: a single-player game with a pausing screen open. fn pauses_game(&self) -> bool { self.remote.is_none() + && self.lan.is_none() && self.title.is_none() && (matches!( self.screen, From 20988e810e4aa17c4fe8f71040b782e3de2d0e3d Mon Sep 17 00:00:00 2001 From: Cosmic <84875247+Online5277@users.noreply.github.com> Date: Wed, 14 Oct 2026 15:14:10 -0400 Subject: [PATCH 20/24] fix(prepare): reuse verified imports from installed versions --- crates/horizon-prepare/src/artifacts.rs | 229 +++++++++++++++++++++++- crates/horizon-prepare/src/lib.rs | 2 +- launcher/README.md | 5 +- launcher/src/backend.rs | 45 ++--- launcher/src/main.rs | 9 +- 5 files changed, 257 insertions(+), 33 deletions(-) diff --git a/crates/horizon-prepare/src/artifacts.rs b/crates/horizon-prepare/src/artifacts.rs index a3e6c2cc0..6f8e45bf8 100644 --- a/crates/horizon-prepare/src/artifacts.rs +++ b/crates/horizon-prepare/src/artifacts.rs @@ -573,6 +573,69 @@ pub struct Artifacts { pub libraries: Vec, } +/// Reuses checked imports from this root or another installed version beside it. +pub fn reuse_imported(root: &Path, log: Log) -> Result { + let root = fs::canonicalize(root).map_err(|e| format!("{}: {e}", root.display()))?; + let lock = Lock::read(&root)?; + let checked = |directory: PathBuf| -> Result, String> { + let candidate = Lock { + json: lock.json.clone(), + version: lock.version.clone(), + java_major: lock.java_major, + directory, + }; + let found = verify(&candidate)?; + let client = client_libraries(&candidate, &found.manifest)?; + let mut files = vec![ + candidate.directory.join("manifest.json"), + candidate.directory.join("jars/client.jar"), + candidate.directory.join("jars/server.jar"), + found.jars["server"].clone(), + ]; + files.extend(found.libraries); + files.extend(client); + Ok(files) + }; + if checked(lock.directory.clone()).is_ok() { + log(&format!("Using imported Minecraft {}", lock.version)); + return Ok(true); + } + let Some(versions) = root.parent() else { + return Ok(false); + }; + let mut siblings: Vec<_> = fs::read_dir(versions) + .map_err(|e| format!("{}: {e}", versions.display()))? + .filter_map(Result::ok) + .map(|entry| entry.path()) + .filter(|path| path != &root && path.is_dir()) + .collect(); + siblings.sort(); + for sibling in siblings { + let source = sibling.join(".local/minecraft").join(&lock.version); + let Ok(files) = checked(source.clone()) else { + continue; + }; + for file in files { + let relative = file.strip_prefix(&source).map_err(|e| e.to_string())?; + import_copy( + &file, + &lock.directory.join(relative), + &digest(&file, "sha256")?, + "sha256", + "", + )?; + } + checked(lock.directory.clone())?; + log(&format!( + "Reused imported Minecraft {} from {}", + lock.version, + sibling.display() + )); + return Ok(true); + } + Ok(false) +} + pub fn verify(lock: &Lock) -> Result { let manifest_path = lock.directory.join("manifest.json"); if !manifest_path.exists() { @@ -597,7 +660,10 @@ pub fn verify(lock: &Lock) -> Result { .and_then(|d| d.get(side)) .and_then(|d| d.get("sha1")) .and_then(Value::as_str); - if !jar.exists() || Some(digest(&jar, "sha1")?.as_str()) != pinned { + if pinned != Some(lock.pin(&format!("{side}_sha1"))?) + || !jar.exists() + || Some(digest(&jar, "sha1")?.as_str()) != pinned + { return Err(format!( "{side} artifact checksum changed; prepare again with --prepare" )); @@ -648,6 +714,167 @@ pub fn client_libraries(lock: &Lock, manifest: &Value) -> Result, S #[cfg(test)] mod tests { use super::*; + use std::io::Write; + + struct Imports { + directory: PathBuf, + source: PathBuf, + target: PathBuf, + } + + impl Imports { + fn new() -> Self { + static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + let n = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let directory = std::env::temp_dir() + .join(format!("horizon-import-reuse-{}-{n}", std::process::id())); + let source = directory.join("old"); + let target = directory.join("new"); + fs::create_dir_all(&target).unwrap(); + let imported = source.join(".local/minecraft/9.9"); + let write = |path: &str, data: &[u8]| { + let path = imported.join(path); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, data).unwrap(); + }; + write("jars/client.jar", b"client"); + write("jars/server-game.jar", b"server game"); + write("libraries/server/server.jar", b"server library"); + write("libraries/client/client.jar", b"client library"); + write("reports/private.txt", b"not an imported artifact"); + let mut bundle = + zip::ZipWriter::new(fs::File::create(imported.join("jars/server.jar")).unwrap()); + let entries = [ + ( + "META-INF/versions.list", + format!("{}\t9.9\tgame.jar\n", crate::sha256_hex(b"server game")), + ), + ( + "META-INF/libraries.list", + format!( + "{}\tserver:library:1\tserver.jar\n", + crate::sha256_hex(b"server library") + ), + ), + ]; + for (name, text) in entries { + bundle + .start_file(name, zip::write::SimpleFileOptions::default()) + .unwrap(); + bundle.write_all(text.as_bytes()).unwrap(); + } + for (name, bytes) in [ + ("META-INF/versions/game.jar", b"server game".as_slice()), + ( + "META-INF/libraries/server.jar", + b"server library".as_slice(), + ), + ] { + bundle + .start_file(name, zip::write::SimpleFileOptions::default()) + .unwrap(); + bundle.write_all(bytes).unwrap(); + } + bundle.finish().unwrap(); + let client_sha1 = digest(&imported.join("jars/client.jar"), "sha1").unwrap(); + let server_sha1 = digest(&imported.join("jars/server.jar"), "sha1").unwrap(); + let library_sha1 = + digest(&imported.join("libraries/client/client.jar"), "sha1").unwrap(); + let manifest = format!( + "{{\"id\":\"9.9\",\"downloads\":{{\"client\":{{\"sha1\":\"{client_sha1}\"}},\"server\":{{\"sha1\":\"{server_sha1}\"}}}},\"libraries\":[{{\"name\":\"client:library:1\",\"downloads\":{{\"artifact\":{{\"path\":\"client.jar\",\"sha1\":\"{library_sha1}\"}}}}}}]}}" + ); + write("manifest.json", manifest.as_bytes()); + let manifest_sha1 = digest(&imported.join("manifest.json"), "sha1").unwrap(); + let lock = format!( + "{{\"minecraft\":{{\"version\":\"9.9\",\"java_major\":25,\"manifest_sha1\":\"{manifest_sha1}\",\"client_sha1\":\"{client_sha1}\",\"server_sha1\":\"{server_sha1}\"}}}}" + ); + fs::write(target.join("research-lock.json"), lock).unwrap(); + Self { + directory, + source, + target, + } + } + + fn imported(&self, root: &Path) -> PathBuf { + root.join(".local/minecraft/9.9") + } + } + + impl Drop for Imports { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.directory); + } + } + + #[test] + fn imported_files_are_reused_without_the_official_install() { + let fixture = Imports::new(); + assert!(reuse_imported(&fixture.target, &|_| {}).unwrap()); + let lock = Lock::read(&fixture.target).unwrap(); + let artifacts = verify(&lock).unwrap(); + assert_eq!( + client_libraries(&lock, &artifacts.manifest).unwrap().len(), + 1 + ); + assert_eq!(artifacts.libraries.len(), 1); + assert!(!lock.directory.join("reports/private.txt").exists()); + // The current root's valid imports suffice even after the older copy is corrupted. + fs::write( + fixture.imported(&fixture.source).join("jars/client.jar"), + b"bad", + ) + .unwrap(); + assert!(reuse_imported(&fixture.target, &|_| {}).unwrap()); + } + + #[test] + fn reuse_rejects_corrupt_imports() { + for file in [ + "manifest.json", + "jars/client.jar", + "jars/server.jar", + "jars/server-game.jar", + "libraries/client/client.jar", + "libraries/server/server.jar", + ] { + let fixture = Imports::new(); + fs::write(fixture.imported(&fixture.source).join(file), b"bad").unwrap(); + assert!(!reuse_imported(&fixture.target, &|_| {}).unwrap(), "{file}"); + assert!(!fixture.imported(&fixture.target).exists()); + } + } + + #[test] + fn reuse_checks_the_target_pins() { + let fixture = Imports::new(); + let mut lock = Lock::read(&fixture.target).unwrap(); + let client = lock.pin("client_sha1").unwrap().to_string(); + let text = fs::read_to_string(fixture.target.join("research-lock.json")).unwrap(); + fs::write( + fixture.target.join("research-lock.json"), + text.replace(&client, "wrong-client-pin"), + ) + .unwrap(); + assert!(!reuse_imported(&fixture.target, &|_| {}).unwrap()); + lock.directory = fixture.imported(&fixture.source); + assert!(verify(&lock).is_ok()); + } + + #[test] + fn reuse_skips_a_bad_sibling_and_repairs_bad_current_imports() { + let fixture = Imports::new(); + let bad = fixture.directory.join("a-bad"); + fs::rename(&fixture.source, &bad).unwrap(); + let valid = Imports::new(); + fs::rename(&valid.source, &fixture.source).unwrap(); + fs::write(fixture.imported(&bad).join("jars/client.jar"), b"bad").unwrap(); + let target = fixture.imported(&fixture.target); + fs::create_dir_all(target.join("jars")).unwrap(); + fs::write(target.join("jars/client.jar"), b"bad").unwrap(); + assert!(reuse_imported(&fixture.target, &|_| {}).unwrap()); + assert_eq!(fs::read(target.join("jars/client.jar")).unwrap(), b"client"); + } #[test] fn natives_follow_the_architecture() { diff --git a/crates/horizon-prepare/src/lib.rs b/crates/horizon-prepare/src/lib.rs index 246cb4d51..24cf44645 100644 --- a/crates/horizon-prepare/src/lib.rs +++ b/crates/horizon-prepare/src/lib.rs @@ -402,7 +402,7 @@ pub fn prepare(options: &Options, log: Log) -> Result { let lock = artifacts::Lock::read(root)?; // Java first: nothing below can finish without it, and the player should hear it at once. let jdk = java::find(lock.java_major)?; - if options.import { + if options.import && !artifacts::reuse_imported(root, log)? { artifacts::import( root, &lock, diff --git a/launcher/README.md b/launcher/README.md index f77d345d2..4eda309d1 100644 --- a/launcher/README.md +++ b/launcher/README.md @@ -21,7 +21,10 @@ The opening, then Play ([clip](docs/opening.webm)): server (`--dedicated --nogui`) in a folder you choose, with a live console. Preparing is horizon-prepare: linked into the launcher, used in-process when a version ships the same preparer sources, else that version's own `horizon-prepare`; versions released before it - still prepare with their Python script and need Python 3.10+. + still prepare with their Python script and need Python 3.10+. Before importing, + preparation reuses checksum-verified game jars and libraries from the current + or another installed Horizon version, so the original Minecraft install is + only required when no valid imported copy exists. - **Patch notes**: each release's notes, newest first, with a link to GitHub Sponsors. Quiet "Join Discord" and "Website" links sit in the sidebar footer. Data lives in the platform's data directory (`~/.local/share/horizon-launcher` on Linux, diff --git a/launcher/src/backend.rs b/launcher/src/backend.rs index 354837d2c..6bac3f6cd 100644 --- a/launcher/src/backend.rs +++ b/launcher/src/backend.rs @@ -591,17 +591,18 @@ fn preparer_binary(dir: &Path) -> Option { /// Java (and Python, for versions before horizon-prepare). pub fn preparer(tag: &str, minecraft: &Path, log: &dyn Fn(String)) -> Result { let version = game_version(tag); + let dir = version_dir(tag); + let reused = horizon_prepare::artifacts::reuse_imported(&dir, &|line| log(line.to_string()))?; let manifest = minecraft .join("versions") .join(&version) .join(format!("{version}.json")); - if !manifest.exists() { + if !reused && !manifest.exists() { return Err(format!( "Minecraft {version} is not in {}. Play {version} once from the official launcher, or choose another folder.", minecraft.display() )); } - let dir = version_dir(tag); let binary = preparer_binary(&dir); let python = if binary.is_some() { // The JDK the version pins, found as horizon-prepare finds it, so a missing one is @@ -625,7 +626,7 @@ pub fn preparer(tag: &str, minecraft: &Path, log: &dyn Fn(String)) -> Result
 Result
 Result<(), String> {
 }
 
 /// The Minecraft folder to prepare from: the one given, the one chosen in the launcher, or the
-/// official launcher's default.
+/// official launcher's default. It may be absent when imported files can be reused.
 pub fn minecraft_dir(requested: Option) -> Result {
-    requested
+    Ok(requested
         .or(Settings::load().minecraft_dir)
         .or_else(default_minecraft_dir)
-        .ok_or_else(|| {
-            "No Minecraft folder found. Pass the official launcher's game folder.".into()
-        })
+        .unwrap_or_else(|| horizon_prepare::artifacts::minecraft_dir(None)))
 }
 
 /// The server folder: the one given, the one chosen in the launcher, or `server/` in the data folder.
diff --git a/launcher/src/main.rs b/launcher/src/main.rs
index be556226f..2a950b1a4 100644
--- a/launcher/src/main.rs
+++ b/launcher/src/main.rs
@@ -501,10 +501,11 @@ impl Launcher {
         let Some(tag) = self.selected().cloned() else {
             return;
         };
-        let Some(minecraft) = self.settings.minecraft_dir.clone() else {
-            self.prepare_error = Some("Choose your Minecraft folder first.".into());
-            return;
-        };
+        let minecraft = self
+            .settings
+            .minecraft_dir
+            .clone()
+            .unwrap_or_else(|| horizon_prepare::artifacts::minecraft_dir(None));
         self.prepare_log.clear();
         self.prepare_error = None;
         self.prepare_log

From 56aae0e9023609cbc1efaa1e59f3e6fd60fe9968 Mon Sep 17 00:00:00 2001
From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com>
Date: Wed, 14 Oct 2026 21:00:13 +0200
Subject: [PATCH 21/24] Maces smash: fall damage bonus, Density, Breach, Wind
 Burst, knockback

A mace hit after falling more than 1.5 blocks is now a smash attack
(MaceItem): the fall-based damage bonus plus Density, mace_smash damage,
the stopped fall with its damage waived, the ground/air smash sounds, the
dust pillars (level event 2013) and the knockback of the creatures around
the target, then the fall reset and landing particles. Breach thins the
target's armor (CombatRules.getDamageAfterAbsorb), Wind Burst bursts at
the player's feet (ExplodeEffect, trigger), and weapons wear by their
weapon component and award the used statistic.

Vanilla details matched on the way: the hurt knockback is 0.4F and reads
the live knockback-resistance attribute, explosion exposure uses the
exact COLLIDER clip, a burst posts the explode game event and ends the
impulse grace unless it is a wind charge's, visible armor stands feel
bursts that affect block-like entities, attack sounds play at the player.

tools/test_mace_parity.py compares the hit with VanillaDispenserOracle's
real MaceItem / hurtServer / post-attack effects: 3000/3000.

Co-Authored-By: Claude Opus 5.5 
---
 crates/horizon-client/src/enchant.rs          |  35 +-
 crates/horizon-client/src/game.rs             |  78 +++--
 .../src/game/commands/world_cmds.rs           |   1 +
 crates/horizon-client/src/game/creatures.rs   |   1 +
 .../src/game/dispense_fixture.rs              | 141 +++++++-
 .../src/game/enchant_effects.rs               |  63 ++++
 crates/horizon-client/src/game/explosion.rs   | 117 +++++--
 crates/horizon-client/src/game/mace.rs        | 330 ++++++++++++++++++
 crates/horizon-client/src/game/sculk.rs       |  13 +
 crates/horizon-client/src/game/wind.rs        |  64 +++-
 crates/horizon-client/src/items.rs            |   7 +
 crates/horizon-client/src/mobs.rs             |  30 +-
 crates/horizon-client/src/mobs/creaking.rs    |   1 +
 crates/horizon-client/src/mobs/guardian.rs    |   5 +-
 crates/horizon-client/src/mobs/sulfur_cube.rs |   1 +
 crates/horizon-client/src/motion.rs           |  20 ++
 .../parity/VanillaBlockUpdateOracle.java      |   2 +
 .../parity/VanillaDispenserOracle.java        | 157 +++++++++
 tools/test_mace_parity.py                     | 204 +++++++++++
 19 files changed, 1174 insertions(+), 96 deletions(-)
 create mode 100644 crates/horizon-client/src/game/mace.rs
 create mode 100644 tools/test_mace_parity.py

diff --git a/crates/horizon-client/src/enchant.rs b/crates/horizon-client/src/enchant.rs
index 6e806712a..c62a67a07 100644
--- a/crates/horizon-client/src/enchant.rs
+++ b/crates/horizon-client/src/enchant.rs
@@ -628,7 +628,8 @@ impl Enchantments {
                 } else {
                     spec
                 };
-                spec.is_null() && entity.is_some() || self.entity_matches(spec, entity)
+                (spec.is_null() && entity.is_some() || self.entity_matches(spec, entity))
+                    && movement_matches(&c["predicate"], role_state(c, ctx))
             }
             "minecraft:random_chance" => {
                 let chance = match &c["chance"] {
@@ -661,6 +662,38 @@ pub struct EffectContext<'a> {
     pub this: Option<&'a str>,
     pub attacker: Option<&'a str>,
     pub direct_attacker: Option<&'a str>,
+    /// The direct attacker's fall distance and whether it flies (elytra or
+    /// abilities), for `movement` and `flags` predicates.
+    pub direct_motion: Option<(f64, bool)>,
+}
+/// The fall distance and flying flag known for an `entity_properties` role.
+fn role_state(c: &Value, ctx: &EffectContext<'_>) -> Option<(f64, bool)> {
+    match c["entity"].as_str().unwrap_or("this") {
+        "direct_attacker" => ctx.direct_motion,
+        _ => None,
+    }
+}
+/// `EntityPredicate`'s `minecraft:movement` fall distance and
+/// `minecraft:flags` is_flying (the parts enchantment requirements use); an
+/// entity whose state is unknown matches neither.
+fn movement_matches(predicate: &Value, state: Option<(f64, bool)>) -> bool {
+    let fall = &predicate["minecraft:movement"]["fall_distance"];
+    let flying = predicate["minecraft:flags"]["is_flying"].as_bool();
+    if fall.is_null() && flying.is_none() {
+        return true;
+    }
+    let Some((distance, is_flying)) = state else {
+        return false;
+    };
+    // MinMaxBounds.Doubles: a number is an exact bound.
+    let bound = |key: &str| {
+        fall.as_f64()
+            .or_else(|| fall.get(key).and_then(Value::as_f64))
+    };
+    // MinMaxBounds.Doubles.matches
+    bound("min").is_none_or(|min| min <= distance)
+        && bound("max").is_none_or(|max| distance <= max)
+        && flying.is_none_or(|f| f == is_flying)
 }
 fn next_int(random: &mut R, bound: i32) -> i32 {
     random.next_int_bound(bound.max(1)).unwrap_or(0)
diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs
index 890387ac8..2ace3cd25 100644
--- a/crates/horizon-client/src/game.rs
+++ b/crates/horizon-client/src/game.rs
@@ -58,6 +58,7 @@ mod level_particles;
 mod lightning;
 mod llamas;
 mod loom;
+mod mace;
 mod machines;
 mod maps;
 mod minecarts;
@@ -1640,6 +1641,11 @@ impl Game<'_> {
                 LevelEvent::LevelEvent { id: 2004, pos, .. } => {
                     self.spawner_burst([pos.x, pos.y, pos.z])
                 }
+                LevelEvent::LevelEvent {
+                    id: 2013,
+                    pos,
+                    data,
+                } => self.smash_dust(pos, data),
                 LevelEvent::LevelEvent {
                     id: id @ 3002..=3005,
                     pos,
@@ -2916,6 +2922,11 @@ impl Game<'_> {
                 MotionEvent::Snowflake { position, velocity } => self.snowflake(position, velocity),
                 MotionEvent::EnterBlock { state } => self.trigger_enter_block(state),
                 MotionEvent::InsidePortal { pos } => self.player_inside_nether_portal(pos),
+                MotionEvent::SmashLanding {
+                    state,
+                    position,
+                    fall_distance,
+                } => self.smash_landing_particles(state, position, fall_distance),
                 _ => {}
             }
         }
@@ -5182,19 +5193,20 @@ impl Game<'_> {
         let delay = 20.0 / speed;
         let scale = ((self.attack_ticks as f32 + 0.5) / delay).clamp(0.0, 1.0);
         let mut amount = damage * (0.2 + scale * scale * 0.8);
+        let target_kind = self.mobs[index].kind.id.clone();
+        let target_kind = format!("minecraft:{}", target_kind.trim_start_matches("minecraft:"));
+        // Item.getAttackDamageBonus (a mace's smash), before the critical hit.
+        amount += self.smash_damage_bonus(&target_kind);
         let player = self.player.as_ref();
+        // Player.canCriticalAttack: falling, off the ground, not sprinting.
         let falling =
-            player.is_some_and(|p| !p.ground.on_ground && p.velocity.y < 0.0 && !p.sprinting);
+            player.is_some_and(|p| !p.ground.on_ground && p.fall_distance > 0.0 && !p.sprinting);
         let crit = scale > 0.9 && falling;
         if crit {
             amount *= 1.5;
         }
         // Enchantment damage (sharpness, smite, bane) scaled by the attack strength.
-        let target_kind = self.mobs[index].kind.id.clone();
-        amount += self.enchant_damage_bonus(&format!(
-            "minecraft:{}",
-            target_kind.trim_start_matches("minecraft:")
-        )) * scale;
+        amount += self.enchant_damage_bonus(&target_kind) * scale;
         self.attack_ticks = 0;
         if let Some(p) = self.player.as_mut()
             && !self.creative
@@ -5206,21 +5218,23 @@ impl Game<'_> {
         self.swing_arm();
         // LivingEntity.setLastHurtMob (tamed wolves join in).
         self.combat.last_hurt_mob = Some((self.mobs[index].id, self.world.game_time));
-        let mob = &mut self.mobs[index];
-        let center = [
-            mob.position.x,
-            mob.position.y + mob.kind.height / 2.0,
-            mob.position.z,
-        ];
-        let dealt = (amount.min(mob.health.max(0.0)) * 10.0).round() as i32;
-        if mob.hurt(amount, from, &mut self.world.random) {
-            self.stats.custom("damage_dealt", dealt);
+        let old_health = self.mobs[index].health;
+        let source = match from {
+            Some(f) => self.attack_source(f),
+            None => horizon_client::mobs::Damage::of(horizon_client::mobs::DamageKind::Generic),
+        };
+        if self.hurt_by_player(index, amount, source) {
+            let mob = &self.mobs[index];
+            // Player.damageStatsAndHearts: the damage the hit actually did.
+            let actual = old_health - mob.health;
             // Player.attack: crit emitter and damage indicator hearts.
             let (feet, width, height) = (
                 [mob.position.x, mob.position.y, mob.position.z],
                 mob.kind.width,
                 mob.kind.height,
             );
+            self.stats
+                .custom("damage_dealt", (actual * 10.0).round() as i32);
             if crit {
                 self.particles.tracking_emitter(
                     horizon_client::particles::ParticleOptions::simple(
@@ -5231,7 +5245,7 @@ impl Game<'_> {
                     height,
                 );
             }
-            if amount > 2.0 {
+            if actual > 2.0 {
                 let indicator = horizon_client::particles::ParticleOptions::simple(
                     horizon_client::particles::ParticleType::DamageIndicator,
                 );
@@ -5240,10 +5254,10 @@ impl Game<'_> {
                     [feet[0], feet[1] + height * 0.5, feet[2]],
                     [0.1, 0.0, 0.1],
                     0.2,
-                    (amount * 0.5) as u32,
+                    (actual * 0.5) as u32,
                 );
             }
-            self.last_hurt_by_player.insert(mob.id);
+            self.last_hurt_by_player.insert(self.mobs[index].id);
             let sound = if crit {
                 "minecraft:entity.player.attack.crit"
             } else if scale > 0.9 {
@@ -5251,33 +5265,21 @@ impl Game<'_> {
             } else {
                 "minecraft:entity.player.attack.weak"
             };
-            self.audio.play(sound, Some(center), 1.0, 1.0);
+            // Player.playServerSideSound: at the player.
+            self.audio.play(sound, from, 1.0, 1.0);
             // The hurt or death sound the mob raised (getHurtSound / getDeathSound,
             // its voice pitch from its own random).
             let queued = std::mem::take(&mut self.mobs[index].outbox);
             for event in queued {
-                if let horizon_client::mobs::MobEvent::Sound(s, _, volume, pitch) = event {
+                if let horizon_client::mobs::MobEvent::Sound(s, at, volume, pitch) = event {
                     self.audio
-                        .play(&format!("minecraft:{s}"), Some(center), volume, pitch);
-                }
-            }
-            self.post_attack(index);
-            if let Some(stack) = self.inventory[self.selected].clone()
-                && let Some(max) = self
-                    .res
-                    .items
-                    .get(&stack.item)
-                    .filter(|i| i.max_damage > 0)
-                    .map(|i| i.max_damage)
-            {
-                let loss = self.durability_loss(&stack, 1);
-                if let Some(stack) = self.inventory[self.selected].as_mut() {
-                    stack.damage += loss;
-                    if stack.damage >= max {
-                        self.inventory[self.selected] = None;
-                    }
+                        .play(&format!("minecraft:{s}"), Some(at), volume, pitch);
                 }
             }
+            self.weapon_hit(index);
+        } else {
+            self.audio
+                .play("minecraft:entity.player.attack.nodamage", from, 1.0, 1.0);
         }
         true
     }
diff --git a/crates/horizon-client/src/game/commands/world_cmds.rs b/crates/horizon-client/src/game/commands/world_cmds.rs
index 43049111a..578153247 100644
--- a/crates/horizon-client/src/game/commands/world_cmds.rs
+++ b/crates/horizon-client/src/game/commands/world_cmds.rs
@@ -89,6 +89,7 @@ impl Game<'_> {
     fn damage_kind(ty: &str) -> DamageKind {
         match ty.trim_start_matches("minecraft:") {
             "player_attack" => DamageKind::PlayerAttack,
+            "mace_smash" => DamageKind::MaceSmash,
             "mob_attack" | "mob_attack_no_aggro" => DamageKind::MobAttack,
             "arrow" => DamageKind::Arrow,
             "thrown" | "trident" | "mob_projectile" => DamageKind::Thrown,
diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs
index ab480f1c0..6a0757252 100644
--- a/crates/horizon-client/src/game/creatures.rs
+++ b/crates/horizon-client/src/game/creatures.rs
@@ -2572,6 +2572,7 @@ fn damage_type(kind: horizon_client::mobs::DamageKind, player: bool) -> &'static
     use horizon_client::mobs::DamageKind as K;
     match kind {
         K::PlayerAttack => "minecraft:player_attack",
+        K::MaceSmash => "minecraft:mace_smash",
         K::MobAttack => "minecraft:mob_attack",
         K::Arrow => "minecraft:arrow",
         K::Thrown => "minecraft:thrown",
diff --git a/crates/horizon-client/src/game/dispense_fixture.rs b/crates/horizon-client/src/game/dispense_fixture.rs
index 355a188da..f8440f06e 100644
--- a/crates/horizon-client/src/game/dispense_fixture.rs
+++ b/crates/horizon-client/src/game/dispense_fixture.rs
@@ -59,8 +59,18 @@ pub(super) fn record_events(events: &[horizon_world::level::LevelEvent]) {
     }
 }
 
+/// Java's `String.format("%.6f")`: the exact value rounded half up (away
+/// from zero) where Rust rounds a tie to even.
 fn num(v: f64) -> String {
-    format!("{v:.6}")
+    let exact = format!("{:.40}", v.abs());
+    let tie = exact
+        .split_once('.')
+        .is_some_and(|(_, f)| f[6..].starts_with('5') && f[7..].bytes().all(|b| b == b'0'));
+    if tie {
+        format!("{:.6}", v + 0.5e-6_f64.copysign(v))
+    } else {
+        format!("{v:.6}")
+    }
 }
 fn floor_pos(p: [f64; 3]) -> String {
     format!(
@@ -299,6 +309,8 @@ impl Game<'_> {
                 ),
                 None => "respawn none".to_owned(),
             });
+        } else if let Some(op) = case.get("attack") {
+            used = self.fixture_attack(op, &targets)?;
         } else if case.get("hopper").is_some() {
             // HopperBlockEntity.pushItemsTick, once.
             self.hopper_try_move_items((origin.x, origin.y, origin.z));
@@ -559,6 +571,119 @@ impl Game<'_> {
         Ok(out)
     }
 
+    /// The player's hit on the first target with the case's item, from the
+    /// attack strength's scaled `base` damage on: the item's damage bonus and
+    /// source, the hurt with the weapon's armor effects, then `weapon_hit`
+    /// (the mace's smash, post-attack enchantments, the wear), as
+    /// `VanillaDispenserOracle.attack` prints them.
+    fn fixture_attack(&mut self, op: &Value, targets: &[Target]) -> Result> {
+        let stack = parse_stack(op["item"].as_str().unwrap_or("-"))?;
+        self.mode = if op["creative"].as_bool().unwrap_or(false) {
+            GameMode::Creative
+        } else {
+            GameMode::Survival
+        };
+        self.creative = self.mode == GameMode::Creative;
+        let v3 = |v: &Value| {
+            horizon_core::geometry::Vec3::new(
+                v[0].as_f64().unwrap_or(0.0),
+                v[1].as_f64().unwrap_or(0.0),
+                v[2].as_f64().unwrap_or(0.0),
+            )
+        };
+        let mut player = PlayerMotion::new(self.motion, v3(&op["player"]))?;
+        player.velocity = v3(&op["motion"]);
+        player.fall_distance = op["fall"].as_f64().unwrap_or(0.0);
+        player.fall_flying = op["fall_flying"].as_bool().unwrap_or(false);
+        player.flying = op["flying"].as_bool().unwrap_or(false);
+        player.may_fly = self.creative;
+        if !op["impact"].is_null() {
+            player.impulse.impact_position = Some(v3(&op["impact"]));
+        }
+        let feet = [player.position.x, player.position.y, player.position.z];
+        self.player = Some(player);
+        self.inventory[self.selected] = stack.clone();
+        let used_before = stack
+            .as_ref()
+            .map_or(0, |s| self.stats.get("used", &s.item));
+        let Some(&Target::Mob(id)) = targets.first() else {
+            return Err("an attack case hits a mob".into());
+        };
+        let index = self
+            .mobs
+            .iter()
+            .position(|m| m.id == id)
+            .ok_or("the target is gone")?;
+        let kind = self.mobs[index].kind.id.clone();
+        let base = op["base"].as_f64().unwrap_or(0.0) as f32;
+        let bonus = self.smash_damage_bonus(&kind);
+        let source = self.attack_source(feet);
+        let hurt = self.hurt_by_player(index, base + bonus, source);
+        // The hurt sound the mob raised, where it stands.
+        for event in std::mem::take(&mut self.mobs[index].outbox) {
+            if let horizon_client::mobs::MobEvent::Sound(s, at, volume, pitch) = event {
+                self.audio
+                    .play(&format!("minecraft:{s}"), Some(at), volume, pitch);
+            }
+        }
+        if hurt {
+            self.weapon_hit(index);
+        }
+        self.process_level_events()?;
+        let mut out = Vec::new();
+        if let Some(s) = &stack {
+            let used = self.stats.get("used", &s.item) - used_before;
+            if used != 0 {
+                out.push(format!("stat {} minecraft:used {used}", s.item));
+            }
+        }
+        let source = match source.kind {
+            horizon_client::mobs::DamageKind::MaceSmash => "minecraft:mace_smash",
+            _ => "minecraft:player_attack",
+        };
+        out.push(format!(
+            "attack bonus={} source={source} hurt={hurt}",
+            num(f64::from(bonus))
+        ));
+        for (i, t) in targets.iter().enumerate() {
+            let (health, v) = match *t {
+                Target::Mob(id) => match self.mobs.iter().find(|m| m.id == id) {
+                    Some(m) => (num(f64::from(m.health)), m.velocity),
+                    None => continue,
+                },
+                Target::Stand(id) => match self.armor_stands.iter().find(|s| s.id == id) {
+                    Some(s) => ("-".to_owned(), s.velocity),
+                    None => continue,
+                },
+            };
+            out.push(format!(
+                "V {i} {health} {} {} {}",
+                num(v.x),
+                num(v.y),
+                num(v.z)
+            ));
+        }
+        if let Some(p) = self.player.take() {
+            let impact = p.impulse.impact_position.map_or("-".to_owned(), |i| {
+                format!("{},{},{}", num(i.x), num(i.y), num(i.z))
+            });
+            out.push(format!(
+                "P {} {} {} fall={} impact={impact} grace={} extra={}",
+                num(p.velocity.x),
+                num(p.velocity.y),
+                num(p.velocity.z),
+                num(p.fall_distance),
+                p.impulse.reset_grace_time,
+                p.spawn_extra_particles_on_fall
+            ));
+        }
+        out.push(format!(
+            "held {}",
+            canon_stack(self.inventory[self.selected].as_ref())
+        ));
+        Ok(out)
+    }
+
     /// A stack in a block entity's slot: a container's, a jukebox's record, a
     /// lectern's book, or the items of a block entity Horizon keeps as saved.
     fn fixture_fill(&mut self, p: (i32, i32, i32), slot: usize, stack: Option) {
@@ -678,8 +803,10 @@ impl Game<'_> {
         self.next_entity += 1;
         let id = self.next_entity;
         if kind == "minecraft:armor_stand" {
-            self.armor_stands
-                .push(horizon_client::entities::ArmorStand::new(id, at, yaw));
+            let mut stand = horizon_client::entities::ArmorStand::new(id, at, yaw);
+            stand.marker = e["marker"].as_bool().unwrap_or(false);
+            stand.on_ground = e["ground"].as_bool().unwrap_or(false);
+            self.armor_stands.push(stand);
             return Ok(Target::Stand(id));
         }
         let t = self
@@ -728,6 +855,14 @@ impl Game<'_> {
         if flag("loot") {
             mob.extra.pick_up_loot = true;
         }
+        mob.on_ground = flag("ground");
+        if let Some(health) = e["health"].as_f64() {
+            mob.attrs.max_health = health as f32;
+            mob.health = health as f32;
+        }
+        if let Some(resistance) = e["knockback_resistance"].as_f64() {
+            mob.attrs.knockback_resistance = resistance;
+        }
         if flag("brown") && s == Species::Mooshroom {
             mob.extra.variant = 1;
         }
diff --git a/crates/horizon-client/src/game/enchant_effects.rs b/crates/horizon-client/src/game/enchant_effects.rs
index 88268379a..5f98fa52a 100644
--- a/crates/horizon-client/src/game/enchant_effects.rs
+++ b/crates/horizon-client/src/game/enchant_effects.rs
@@ -165,6 +165,69 @@ impl Game<'_> {
             self.potions.burning.retain(|(m, _)| *m != id);
             self.potions.burning.push((id, (ignite * 20.0) as i32));
         }
+        self.post_attack_bursts(&held, &kind);
+    }
+    /// `minecraft:post_attack` explode effects on the attacker (wind burst):
+    /// a burst at the player's feet that only knocks back and triggers
+    /// blocks (`ExplodeEffect` with `block_interaction: trigger`).
+    fn post_attack_bursts(&mut self, held: &ItemStack, victim: &str) {
+        let Some(p) = self.player.as_ref() else {
+            return;
+        };
+        // EntityFlagsPredicate.isFlying: gliding or flying.
+        let motion = (p.fall_distance, p.fall_flying || p.flying);
+        let feet = [p.position.x, p.position.y, p.position.z];
+        let ctx = EffectContext {
+            this: Some(victim),
+            attacker: Some("minecraft:player"),
+            direct_attacker: Some("minecraft:player"),
+            is_direct: true,
+            items: Some(&self.res.items),
+            direct_motion: Some(motion),
+            ..Default::default()
+        };
+        let mut bursts = Vec::new();
+        for (id, level) in held.enchantments() {
+            let Some(def) = self.res.stations.enchantments.get(id) else {
+                continue;
+            };
+            for effect in def.effects["minecraft:post_attack"]
+                .as_array()
+                .into_iter()
+                .flatten()
+            {
+                let e = &effect["effect"];
+                if effect["enchanted"] != "attacker"
+                    || effect["affected"] != "attacker"
+                    || e["type"] != "minecraft:explode"
+                    || e["block_interaction"] != "trigger"
+                {
+                    continue;
+                }
+                let ok = effect.get("requirements").is_none_or(|r| {
+                    self.res.stations.enchantments.condition(
+                        r,
+                        *level,
+                        &ctx,
+                        &mut self.world.random,
+                    )
+                });
+                if !ok {
+                    continue;
+                }
+                let radius = horizon_client::enchant::level_value(&e["radius"], *level).max(0.0);
+                // ExplosionDamageCalculator.getKnockbackMultiplier: 1 unless given.
+                let knockback = if e["knockback_multiplier"].is_null() {
+                    1.0
+                } else {
+                    horizon_client::enchant::level_value(&e["knockback_multiplier"], *level)
+                };
+                bursts.push((radius, knockback));
+            }
+        }
+        for (radius, knockback) in bursts {
+            let _ = self.wind_burst(feet, radius, knockback, false, false);
+        }
     }
     /// Burning mobs (fire aspect): one damage every 20 ticks, flame particles.
     pub(super) fn tick_burning(&mut self) {
diff --git a/crates/horizon-client/src/game/explosion.rs b/crates/horizon-client/src/game/explosion.rs
index c03b99609..b871e8df9 100644
--- a/crates/horizon-client/src/game/explosion.rs
+++ b/crates/horizon-client/src/game/explosion.rs
@@ -3,14 +3,64 @@
 //! draws), entity damage with exposure and knockback, block interaction with
 //! merged drops and TNT chain priming, and optional fire.
 use super::Game;
-use horizon_client::{Result, blocks::Fluid, items::ItemStack};
+use horizon_client::{Result, blocks::Fluid, collisions::SceneCollisions, items::ItemStack};
 use horizon_core::{
-    geometry::Vec3,
+    geometry::{Vec3, VoxelShape},
     position::BlockPos,
     random::{LegacyRandom, RandomSource},
 };
-use horizon_world::java_hash_map::{JavaHashMap, JavaKey};
-use std::cmp::Ordering;
+use horizon_world::{
+    collision_context::{CollisionContext, CollisionEntity, CollisionItem},
+    entity_obstruction::EntityIdentity,
+    java_hash_map::{JavaHashMap, JavaKey},
+    registry::BlockStateId,
+    world_ray::{RayBlockMode, RayFluidMode, RayWorld, clip_world},
+};
+use std::{cmp::Ordering, io};
+
+/// `Level.clip` with `ClipContext.Block.COLLIDER`, no fluids and the
+/// collision context of the entity whose exposure is measured.
+struct ColliderRays<'a, 'r> {
+    scene: SceneCollisions<'a, 'r>,
+    context: CollisionContext<'static>,
+}
+impl RayWorld for ColliderRays<'_, '_> {
+    type Error = io::Error;
+    type Block = BlockStateId;
+    type Fluid = ();
+    fn block_state(&mut self, p: BlockPos) -> io::Result {
+        Ok(self.scene.world.block(p.x, p.y, p.z))
+    }
+    fn fluid_state(&mut self, _: BlockPos) -> io::Result<()> {
+        Ok(())
+    }
+    fn block_shape(
+        &mut self,
+        state: BlockStateId,
+        p: BlockPos,
+        _: RayBlockMode,
+    ) -> io::Result {
+        let binding = self.scene.binding;
+        binding
+            .collision_shape_with_context(&mut self.scene, state, p, &self.context)
+            .map_err(|e| io::Error::other(format!("{e:?}")))
+    }
+    fn interaction_shape(&mut self, _: BlockStateId, _: BlockPos) -> io::Result {
+        Ok(VoxelShape::empty())
+    }
+    fn fluid_is_source(&mut self, _: ()) -> io::Result {
+        Ok(false)
+    }
+    fn fluid_is_empty(&mut self, _: ()) -> io::Result {
+        Ok(true)
+    }
+    fn fluid_is_water(&mut self, _: ()) -> io::Result {
+        Ok(false)
+    }
+    fn fluid_shape(&mut self, _: (), _: BlockPos) -> io::Result {
+        Ok(VoxelShape::empty())
+    }
+}
 
 /// `BlockPos` with Java `Vec3i.hashCode` / `compareTo`.
 #[derive(Clone, Copy, PartialEq, Eq)]
@@ -48,35 +98,6 @@ pub(super) fn client_float() -> f32 {
 }
 
 impl Game<'_> {
-    /// `Level.clip(from, to, COLLIDER, NONE)` missing every block, with full
-    /// collision cubes as obstacles.
-    fn clear_line(&self, from: [f64; 3], to: [f64; 3]) -> bool {
-        let d = [to[0] - from[0], to[1] - from[1], to[2] - from[2]];
-        let length = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt();
-        let steps = (length / 0.1).ceil().max(1.0) as i32;
-        let mut last = [i32::MIN; 3];
-        for i in 0..=steps {
-            let t = f64::from(i) / f64::from(steps);
-            let b = [
-                (from[0] + d[0] * t).floor() as i32,
-                (from[1] + d[1] * t).floor() as i32,
-                (from[2] + d[2] * t).floor() as i32,
-            ];
-            if b == last {
-                continue;
-            }
-            last = b;
-            if self
-                .res
-                .facts
-                .get(self.world.block(b[0], b[1], b[2]))
-                .full_collision
-            {
-                return false;
-            }
-        }
-        true
-    }
     /// `ServerExplosion.getSeenPercent` for an entity box.
     pub(super) fn seen_percent(&self, center: [f64; 3], min: [f64; 3], max: [f64; 3]) -> f32 {
         let xs = 1.0 / ((max[0] - min[0]) * 2.0 + 1.0);
@@ -87,6 +108,23 @@ impl Game<'_> {
         if xs < 0.0 || ys < 0.0 || zs < 0.0 {
             return 0.0;
         }
+        // ClipContext(..., entity): the entity standing at the box's bottom.
+        let mut rays = ColliderRays {
+            scene: SceneCollisions {
+                world: &self.world,
+                binding: self.collision,
+                subject: None,
+            },
+            context: CollisionContext::for_entity(
+                CollisionEntity {
+                    identity: EntityIdentity(0),
+                    y: min[1],
+                    descending: false,
+                    main_hand: Some(CollisionItem::EMPTY),
+                },
+                false,
+            ),
+        };
         let (mut hits, mut count) = (0, 0);
         let mut xx = 0.0;
         while xx <= 1.0 {
@@ -97,7 +135,18 @@ impl Game<'_> {
                     let x = min[0] + (max[0] - min[0]) * xx;
                     let y = min[1] + (max[1] - min[1]) * yy;
                     let z = min[2] + (max[2] - min[2]) * zz;
-                    if self.clear_line([x + x_offset, y, z + z_offset], center) {
+                    let from = Vec3::new(x + x_offset, y, z + z_offset);
+                    let to = Vec3::new(center[0], center[1], center[2]);
+                    let missed = clip_world(
+                        &mut rays,
+                        from,
+                        to,
+                        RayBlockMode::Collider,
+                        RayFluidMode::None,
+                        4096,
+                    )
+                    .is_ok_and(|r| r.miss);
+                    if missed {
                         hits += 1;
                     }
                     count += 1;
diff --git a/crates/horizon-client/src/game/mace.rs b/crates/horizon-client/src/game/mace.rs
new file mode 100644
index 000000000..062d04525
--- /dev/null
+++ b/crates/horizon-client/src/game/mace.rs
@@ -0,0 +1,330 @@
+//! Maces (`MaceItem`): a hit after falling more than one and a half blocks is
+//! a smash attack. It adds damage for the height fallen (more with Density),
+//! stops the fall, cancels its damage and knocks the creatures around the
+//! target away. The rest of a weapon hit (`Player.itemAttackInteraction`)
+//! is here too: `hurtEnemy`, the post-attack enchantments and `postHurtEnemy`.
+use super::Game;
+use horizon_client::{
+    enchant::EffectContext,
+    mobs::{Damage, Mob, Species},
+    particles::{ParticleOptions, ParticleType},
+};
+use horizon_core::{geometry::Vec3, position::BlockPos, random::RandomSource};
+use horizon_world::registry::BlockStateId;
+
+/// `MaceItem.SMASH_ATTACK_FALL_THRESHOLD`.
+const FALL_THRESHOLD: f64 = 1.5;
+/// `MaceItem.SMASH_ATTACK_HEAVY_THRESHOLD`.
+const HEAVY_THRESHOLD: f64 = 5.0;
+/// `MaceItem.SMASH_ATTACK_KNOCKBACK_RADIUS`.
+const KNOCKBACK_RADIUS: f64 = 3.5;
+/// `MaceItem.SMASH_ATTACK_KNOCKBACK_POWER`.
+const KNOCKBACK_POWER: f32 = 0.7;
+
+/// `Entity.isAlliedTo` between the player (`player` its UUID) and a mob
+/// without teams: `TamableAnimal.considersEntityAsAlly` (a pet it tamed) and
+/// `Allay.considersEntityAsAlly` (an allay that likes it).
+fn ally_of_player(m: &Mob, player: Option<[i32; 4]>) -> bool {
+    let tamable = matches!(
+        m.species(),
+        Species::Wolf
+            | Species::Cat
+            | Species::Parrot
+            | Species::Nautilus
+            | Species::ZombieNautilus
+    );
+    tamable && m.extra.tame && m.extra.owner.is_some() && m.extra.owner == player
+        || m.species() == Species::Allay && m.extra.tame
+}
+
+impl Game<'_> {
+    fn holds_mace(&self) -> bool {
+        self.inventory[self.selected]
+            .as_ref()
+            .is_some_and(|s| &*s.item == "minecraft:mace")
+    }
+    /// `MaceItem.canSmashAttack` for the player: falling and not gliding.
+    fn can_smash_attack(&self) -> bool {
+        self.player
+            .as_ref()
+            .is_some_and(|p| p.fall_distance > FALL_THRESHOLD && !p.fall_flying)
+    }
+    /// A held mace about to smash (`MaceItem.getItemDamageSource`: the attack
+    /// is `mace_smash` damage).
+    pub(super) fn smash_attack(&self) -> bool {
+        self.holds_mace() && self.can_smash_attack()
+    }
+    /// The damage source of the player's hit from `from` with the held item.
+    pub(super) fn attack_source(&self, from: [f64; 3]) -> Damage {
+        if self.smash_attack() {
+            Damage::mace(from)
+        } else {
+            Damage::player(from)
+        }
+    }
+    /// `MaceItem.getAttackDamageBonus` against `victim`: 4 per block for the
+    /// first three blocks fallen, 2 for the next five, 1 after that, plus
+    /// `smash_damage_per_fallen_block` (Density) for every block.
+    pub(super) fn smash_damage_bonus(&mut self, victim: &str) -> f32 {
+        if !self.smash_attack() {
+            return 0.0;
+        }
+        let fall = self.player.as_ref().map_or(0.0, |p| p.fall_distance);
+        let damage = if fall <= 3.0 {
+            4.0 * fall
+        } else if fall <= 8.0 {
+            12.0 + 2.0 * (fall - 3.0)
+        } else {
+            22.0 + fall - 8.0
+        };
+        let held = self.inventory[self.selected].clone();
+        let ctx = EffectContext {
+            this: Some(victim),
+            attacker: Some("minecraft:player"),
+            direct_attacker: Some("minecraft:player"),
+            is_direct: true,
+            damage_type: Some("minecraft:mace_smash"),
+            items: Some(&self.res.items),
+            ..Default::default()
+        };
+        // EnchantmentHelper.modifyFallBasedDamage(..., 0)
+        let per_block = self.res.stations.enchantments.modify_value(
+            held.as_ref(),
+            "minecraft:smash_damage_per_fallen_block",
+            &ctx,
+            &mut self.world.random,
+            0.0,
+        );
+        (damage + f64::from(per_block) * fall) as f32
+    }
+    /// `LivingEntity.hurtServer` of the mob at `index` by the player's hit:
+    /// the weapon's `armor_effectiveness` enchantments (Breach) thin its armor.
+    pub(super) fn hurt_by_player(&mut self, index: usize, amount: f32, source: Damage) -> bool {
+        let held = self.inventory[self.selected].clone();
+        let kind = self.mobs[index].kind.id.clone();
+        let ctx = EffectContext {
+            this: Some(&kind),
+            attacker: Some("minecraft:player"),
+            direct_attacker: Some("minecraft:player"),
+            is_direct: true,
+            damage_type: Some(match source.kind {
+                horizon_client::mobs::DamageKind::MaceSmash => "minecraft:mace_smash",
+                _ => "minecraft:player_attack",
+            }),
+            items: Some(&self.res.items),
+            ..Default::default()
+        };
+        let enchantments = &self.res.stations.enchantments;
+        let random = &mut self.world.random;
+        // CombatRules.getDamageAfterAbsorb: EnchantmentHelper.modifyArmorEffectiveness.
+        let mut breach = |fraction: f32| {
+            enchantments.modify_value(
+                held.as_ref(),
+                "minecraft:armor_effectiveness",
+                &ctx,
+                random,
+                fraction,
+            )
+        };
+        let old_health = self.mobs[index].health;
+        let hurt = self.mobs[index].damage_with(amount, source, Some(&mut breach));
+        if hurt && self.mobs[index].health != old_health {
+            self.mob_damage_event(self.mobs[index].id);
+        }
+        hurt
+    }
+    /// `Player.itemAttackInteraction` after the player's hit landed on the mob
+    /// at `index`: the item's `hurtEnemy` (the "used" statistic of a weapon),
+    /// the post-attack enchantments, then `postHurtEnemy` with the weapon's
+    /// wear.
+    pub(super) fn weapon_hit(&mut self, index: usize) {
+        let Some(stack) = self.inventory[self.selected].clone() else {
+            return;
+        };
+        let weapon = self
+            .res
+            .items
+            .get(&stack.item)
+            .and_then(|i| i.weapon_damage.map(|d| (d, i.max_damage)));
+        let smash = self.smash_attack();
+        if smash {
+            self.mace_hurt_enemy(index);
+        }
+        if weapon.is_some() {
+            self.stats.add("used", &stack.item, 1);
+        }
+        self.post_attack(index);
+        // MaceItem.postHurtEnemy
+        if smash && let Some(p) = self.player.as_mut() {
+            p.fall_distance = 0.0;
+        }
+        // ItemStack.postHurtEnemy: hurtAndBreak(weapon.itemDamagePerAttack).
+        if let Some((per_attack, max)) = weapon
+            && max > 0
+            && !self.creative
+        {
+            let loss = self.durability_loss(&stack, per_attack);
+            if let Some(held) = self.inventory[self.selected].as_mut() {
+                held.damage += loss;
+                if held.damage >= max {
+                    self.inventory[self.selected] = None;
+                }
+            }
+        }
+    }
+    /// `MaceItem.hurtEnemy` for a smash: the fall stops and its damage is
+    /// waived from where the hit landed, the ground or air smash sounds, and
+    /// the knockback around the target.
+    fn mace_hurt_enemy(&mut self, index: usize) {
+        let target_on_ground = self.mobs[index].on_ground;
+        let Some(p) = self.player.as_mut() else {
+            return;
+        };
+        p.velocity = Vec3::new(p.velocity.x, f64::from(0.01f32), p.velocity.z);
+        // calculateImpactPosition: an earlier impact below the player stays.
+        let impact = match p.impulse.impact_position {
+            Some(at) if at.y <= p.position.y => at,
+            _ => p.position,
+        };
+        p.impulse.set_ignore_fall_damage(true, Some(impact));
+        let fall = p.fall_distance;
+        let feet = [p.position.x, p.position.y, p.position.z];
+        let sound = if target_on_ground {
+            p.spawn_extra_particles_on_fall = true;
+            if fall > HEAVY_THRESHOLD {
+                "minecraft:item.mace.smash_ground_heavy"
+            } else {
+                "minecraft:item.mace.smash_ground"
+            }
+        } else {
+            "minecraft:item.mace.smash_air"
+        };
+        self.audio.play(sound, Some(feet), 1.0, 1.0);
+        self.smash_knockback(index, fall);
+    }
+    /// `MaceItem.knockback`: the dust pillar (level event 2013) under the
+    /// target, then every living entity within 3.5 blocks of it but the
+    /// player and the target pushed away and up, harder after a fall of more
+    /// than five blocks. Spectators, the player's allies (`isAlliedTo`: its
+    /// pets and the allays that like it), marker armor stands and creative
+    /// flyers are spared; the predicate's own tamed-animal test asks whether
+    /// the target owns the animal, which a mob never does.
+    fn smash_knockback(&mut self, index: usize, fall: f64) {
+        let target = &self.mobs[index];
+        let (id, center) = (target.id, target.position);
+        // Entity.getOnPos without a supporting block.
+        let on_pos = [
+            center.x.floor() as i32,
+            (center.y - f64::from(1.0e-5f32)).floor() as i32,
+            center.z.floor() as i32,
+        ];
+        self.level_event_at(2013, on_pos, 750);
+        let heavy = if fall > HEAVY_THRESHOLD { 2.0 } else { 1.0 };
+        // getKnockbackPower and the push of one entity at `at`.
+        let push = |at: Vec3, velocity: &mut Vec3, resistance: f64| {
+            let d = [at.x - center.x, at.y - center.y, at.z - center.z];
+            let distance_sqr = d[0] * d[0] + d[1] * d[1] + d[2] * d[2];
+            if distance_sqr > KNOCKBACK_RADIUS.powi(2) {
+                return;
+            }
+            let length = distance_sqr.sqrt();
+            let power = (KNOCKBACK_RADIUS - length)
+                * f64::from(KNOCKBACK_POWER)
+                * heavy
+                * (1.0 - resistance);
+            if power <= 0.0 {
+                return;
+            }
+            // Vec3.normalize: a vector shorter than 1e-5 has no direction.
+            let (x, z) = if length < f64::from(1.0e-5f32) {
+                (0.0, 0.0)
+            } else {
+                (d[0] / length * power, d[2] / length * power)
+            };
+            *velocity = Vec3::new(
+                velocity.x + x,
+                velocity.y + f64::from(KNOCKBACK_POWER),
+                velocity.z + z,
+            );
+        };
+        let player = self.level.player_uuid.or(Some([0, 0, 0, 1]));
+        for m in self
+            .mobs
+            .iter_mut()
+            .filter(|m| m.id != id && m.alive() && !m.removed && !ally_of_player(m, player))
+        {
+            push(m.position, &mut m.velocity, m.attrs.knockback_resistance);
+        }
+        for s in self.armor_stands.iter_mut().filter(|s| !s.marker) {
+            push(s.position, &mut s.velocity, 0.0);
+        }
+    }
+    /// `ServerPlayer.checkFallDamage` after a smash on a grounded target:
+    /// the landing block's particles, 50 for every block fallen (200 at most).
+    pub(super) fn smash_landing_particles(
+        &mut self,
+        state: BlockStateId,
+        pos: BlockPos,
+        fall_distance: f64,
+    ) {
+        let Some((sprite, tint)) = self.particle_sprite(state) else {
+            return;
+        };
+        let count = (50.0 * fall_distance).clamp(0.0, 200.0) as u32;
+        let spread = f64::from(0.3f32);
+        self.particles.send_particles(
+            &ParticleOptions::block(ParticleType::Block, sprite, tint),
+            [
+                f64::from(pos.x) + 0.5,
+                f64::from(pos.y) + 1.0,
+                f64::from(pos.z) + 0.5,
+            ],
+            [spread; 3],
+            f64::from(0.15f32),
+            count,
+        );
+    }
+    /// Level event 2013 (`ParticleUtils.spawnSmashAttackParticles`): dust
+    /// pillars of the block at `pos`, a cluster over it and a ring 3.5 out.
+    pub(super) fn smash_dust(&mut self, pos: BlockPos, count: i32) {
+        let state = self.world.block(pos.x, pos.y, pos.z);
+        let Some((sprite, tint)) = self.particle_sprite(state) else {
+            return;
+        };
+        let options = ParticleOptions::block(ParticleType::DustPillar, sprite, tint);
+        let center = [
+            f64::from(pos.x) + 0.5,
+            f64::from(pos.y) + 1.0,
+            f64::from(pos.z) + 0.5,
+        ];
+        let near = f64::from(0.2f32);
+        let mut i = 0;
+        while (i as f32) < count as f32 / 3.0 {
+            let r = self.particles.random();
+            let x = center[0] + r.next_gaussian() / 2.0;
+            let z = center[2] + r.next_gaussian() / 2.0;
+            let v = [
+                r.next_gaussian() * near,
+                r.next_gaussian() * near,
+                r.next_gaussian() * near,
+            ];
+            self.particles.add(&options, [x, center[1], z], v);
+            i += 1;
+        }
+        let far = f64::from(0.05f32);
+        let mut i = 0;
+        while (i as f32) < count as f32 / 1.5 {
+            let r = self.particles.random();
+            let angle = f64::from(i);
+            let x = center[0] + KNOCKBACK_RADIUS * angle.cos() + r.next_gaussian() / 2.0;
+            let z = center[2] + KNOCKBACK_RADIUS * angle.sin() + r.next_gaussian() / 2.0;
+            let v = [
+                r.next_gaussian() * far,
+                r.next_gaussian() * far,
+                r.next_gaussian() * far,
+            ];
+            self.particles.add(&options, [x, center[1], z], v);
+            i += 1;
+        }
+    }
+}
diff --git a/crates/horizon-client/src/game/sculk.rs b/crates/horizon-client/src/game/sculk.rs
index c42a3aedf..fb23cc498 100644
--- a/crates/horizon-client/src/game/sculk.rs
+++ b/crates/horizon-client/src/game/sculk.rs
@@ -507,6 +507,19 @@ impl Game<'_> {
         let ctx = self.who_context(who, state);
         self.post_game_event(event, center((pos[0], pos[1], pos[2])), ctx);
     }
+    /// `LivingEntity.actuallyHurt`'s damage vibration, heard as the hit lands;
+    /// the end-of-tick scan then knows this damage.
+    pub(super) fn mob_damage_event(&mut self, id: u32) {
+        if let Some(t) = self
+            .mobs
+            .iter()
+            .find(|m| m.id == id)
+            .and_then(|m| m.last_damage.map(|(_, t)| t))
+        {
+            self.sculk.damaged.insert(id, t);
+        }
+        self.post_entity_event("minecraft:entity_damage", Who::Mob(id));
+    }
     /// A game event of an entity at its position.
     pub(super) fn post_entity_event(&mut self, event: &'static str, who: Who) {
         let at = match who {
diff --git a/crates/horizon-client/src/game/wind.rs b/crates/horizon-client/src/game/wind.rs
index b3cc188d8..3b48e929f 100644
--- a/crates/horizon-client/src/game/wind.rs
+++ b/crates/horizon-client/src/game/wind.rs
@@ -101,13 +101,7 @@ impl Game<'_> {
             ],
             Hit::None => return Ok(()),
         };
-        self.wind_burst(
-            center,
-            radius,
-            knockback,
-            breeze,
-            p.owner == Some(Who::Player),
-        )
+        self.wind_burst(center, radius, knockback, breeze, !breeze)
     }
     /// `AbstractWindCharge.onHitEntity`: one point of damage.
     fn wind_charge_damage(&mut self, p: &Projectile, who: Who) {
@@ -208,7 +202,8 @@ impl Game<'_> {
         center: [f64; 3],
         radius: f32,
         multiplier: f32,
-        player_charge: bool,
+        wind_charge: bool,
+        blocklike: bool,
     ) {
         let diameter = f64::from(radius * 2.0);
         let distance = |p: [f64; 3]| {
@@ -257,11 +252,10 @@ impl Game<'_> {
                         p.velocity.y + dir[1] * power,
                         p.velocity.z + dir[2] * power,
                     );
-                    // ServerPlayer.onExplosionHit: a player's own charge cancels the fall.
-                    if player_charge {
-                        let at = p.position;
-                        p.impulse.set_ignore_fall_damage(true, Some(at));
-                    }
+                    // ServerPlayer.onExplosionHit: a wind charge's burst cancels the
+                    // fall; any other burst ends the grace of the last impulse.
+                    let at = p.position;
+                    p.impulse.set_ignore_fall_damage(wind_charge, Some(at));
                 }
             }
         }
@@ -288,6 +282,39 @@ impl Game<'_> {
             );
         }
         self.mobs = mobs;
+        // ArmorStand.ignoreExplosion: a visible stand feels only a burst that
+        // affects block-like entities (never a wind charge's).
+        if blocklike {
+            let mut stands = std::mem::take(&mut self.armor_stands);
+            for s in stands.iter_mut().filter(|s| !s.invisible) {
+                let feet = [s.position.x, s.position.y, s.position.z];
+                let dist = distance(feet) / diameter;
+                if dist > 1.0 {
+                    continue;
+                }
+                // EntityType.ARMOR_STAND's size, halved when small; a marker has none.
+                let (w, h, eye) = if s.marker {
+                    (0.0, 0.0, 0.0)
+                } else if s.small {
+                    (0.125, f64::from(0.9875f32), f64::from(0.9875f32))
+                } else {
+                    (0.25, f64::from(1.975f32), f64::from(1.7775f32))
+                };
+                let exposure = self.seen_percent(
+                    center,
+                    [feet[0] - w, feet[1], feet[2] - w],
+                    [feet[0] + w, feet[1] + h, feet[2] + w],
+                );
+                let power = (1.0 - dist) * f64::from(exposure) * multiplier;
+                let dir = direction([feet[0], feet[1] + eye, feet[2]]);
+                s.velocity = Vec3::new(
+                    s.velocity.x + dir[0] * power,
+                    s.velocity.y + dir[1] * power,
+                    s.velocity.z + dir[2] * power,
+                );
+            }
+            self.armor_stands = stands;
+        }
         // Arrows and other projectiles (the charges themselves ignore it).
         let push = |position: Vec3, velocity: &mut Vec3, game: &Game<'_>| {
             let feet = [position.x, position.y, position.z];
@@ -331,16 +358,21 @@ impl Game<'_> {
         self.tnts = tnts;
     }
     /// The burst: knockback, the blocks that react, the gust and the sound.
-    fn wind_burst(
+    pub(super) fn wind_burst(
         &mut self,
         center: [f64; 3],
         radius: f32,
         multiplier: f32,
         breeze: bool,
-        player_charge: bool,
+        wind_charge: bool,
     ) -> Result<()> {
+        // ServerExplosion.explode: the blast is heard first.
+        let ctx = horizon_client::sculk::Context::default();
+        self.post_game_event("minecraft:explode", center, ctx);
         let mut targets = self.wind_positions(center, radius);
-        self.wind_knockback(center, radius, multiplier, player_charge);
+        // ServerExplosion.shouldAffectBlocklikeEntities
+        let blocklike = !breeze && !wind_charge && self.ui.rules.bool("mob_griefing");
+        self.wind_knockback(center, radius, multiplier, wind_charge, blocklike);
         // Explosion.canTriggerBlocks: a breeze's charge needs mob griefing.
         if !breeze || self.ui.rules.bool("mob_griefing") {
             // Util.shuffle(list, level.random)
diff --git a/crates/horizon-client/src/items.rs b/crates/horizon-client/src/items.rs
index f336d432e..fc1667298 100644
--- a/crates/horizon-client/src/items.rs
+++ b/crates/horizon-client/src/items.rs
@@ -70,6 +70,8 @@ pub struct ItemInfo {
     pub blocks_attacks: Option,
     /// `weapon.disable_blocking_for_seconds` (axes).
     pub disable_blocking_seconds: f32,
+    /// `weapon.item_damage_per_attack`, when the item is a weapon.
+    pub weapon_damage: Option,
     /// `use_effects.speed_multiplier` (UseEffects.DEFAULT: 0.2).
     pub use_speed: f32,
     /// `glider` (elytra).
@@ -439,6 +441,11 @@ impl Items {
                     disable_blocking_seconds: c["minecraft:weapon"]["disable_blocking_for_seconds"]
                         .as_f64()
                         .unwrap_or(0.0) as f32,
+                    weapon_damage: c["minecraft:weapon"].is_object().then(|| {
+                        c["minecraft:weapon"]["item_damage_per_attack"]
+                            .as_u64()
+                            .unwrap_or(1) as u32
+                    }),
                     equip_asset: c["minecraft:equippable"]["asset_id"]
                         .as_str()
                         .map(str::to_owned),
diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs
index 328265585..e5135fc7c 100644
--- a/crates/horizon-client/src/mobs.rs
+++ b/crates/horizon-client/src/mobs.rs
@@ -492,6 +492,8 @@ pub enum Who {
 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
 pub enum DamageKind {
     PlayerAttack,
+    /// `mace_smash`: a mace hit after a fall (the player attack tags too).
+    MaceSmash,
     MobAttack,
     Arrow,
     Thrown,
@@ -541,6 +543,14 @@ impl Damage {
             from: Some(from),
         }
     }
+    /// `DamageSources.mace`: a player's smash attack.
+    pub fn mace(from: [f64; 3]) -> Self {
+        Self {
+            kind: DamageKind::MaceSmash,
+            attacker: Some(Who::Player),
+            from: Some(from),
+        }
+    }
     pub fn mob(id: u32, from: [f64; 3]) -> Self {
         Self {
             kind: DamageKind::MobAttack,
@@ -1518,6 +1528,16 @@ impl Mob {
         .fold((0.0, 0.0), |(a, t), (x, y)| (a + x, t + y))
     }
     pub fn damage(&mut self, amount: f32, source: Damage) -> bool {
+        self.damage_with(amount, source, None)
+    }
+    /// `damage` by a source with a weapon: `armor_effectiveness` runs the
+    /// weapon's armor-effectiveness enchantments (breach) over the armor fraction.
+    pub fn damage_with(
+        &mut self,
+        amount: f32,
+        source: Damage,
+        armor_effectiveness: Option<&mut dyn FnMut(f32) -> f32>,
+    ) -> bool {
         raider::note_hurt(self);
         if !self.alive() || self.removed || self.invulnerable_flag {
             return false;
@@ -1535,7 +1555,11 @@ impl Mob {
             let armor = self.kind.armor + worn;
             let toughness = 2.0 + (self.kind.armor_toughness + worn_toughness) / 4.0;
             let effective = (armor - amount / toughness).clamp(armor * 0.2, 20.0);
-            amount *= 1.0 - effective / 25.0;
+            let mut fraction = effective / 25.0;
+            if let Some(modify) = armor_effectiveness {
+                fraction = modify(fraction).clamp(0.0, 1.0);
+            }
+            amount *= 1.0 - fraction;
         }
         // CombatRules.getDamageAfterMagicAbsorb: enchantment protection.
         let epf = gear::protection(self, source.kind);
@@ -1570,7 +1594,7 @@ impl Mob {
             let (dx, dz) = source.from.map_or((0.0, 0.0), |f| {
                 (f[0] - self.position.x, f[2] - self.position.z)
             });
-            self.knockback(0.4, dx, dz);
+            self.knockback(f64::from(0.4f32), dx, dz);
         }
         ai::after_hurt(self, &source);
         if self.health <= 0.0 {
@@ -1597,7 +1621,7 @@ impl Mob {
     }
     /// LivingEntity.knockback(power, xd, zd) towards the negative direction.
     pub fn knockback(&mut self, power: f64, mut xd: f64, mut zd: f64) {
-        let power = power * (1.0 - self.kind.knockback_resistance);
+        let power = power * (1.0 - self.attrs.knockback_resistance);
         if power <= 0.0 {
             return;
         }
diff --git a/crates/horizon-client/src/mobs/creaking.rs b/crates/horizon-client/src/mobs/creaking.rs
index 1d8da0ae8..fd6248d2b 100644
--- a/crates/horizon-client/src/mobs/creaking.rs
+++ b/crates/horizon-client/src/mobs/creaking.rs
@@ -117,6 +117,7 @@ pub fn accepts_damage(m: &mut Mob, source: &Damage) -> bool {
     let direct = matches!(
         source.kind,
         DamageKind::PlayerAttack
+            | DamageKind::MaceSmash
             | DamageKind::MobAttack
             | DamageKind::Arrow
             | DamageKind::Thrown
diff --git a/crates/horizon-client/src/mobs/guardian.rs b/crates/horizon-client/src/mobs/guardian.rs
index 5eb72a6e4..d6219794d 100644
--- a/crates/horizon-client/src/mobs/guardian.rs
+++ b/crates/horizon-client/src/mobs/guardian.rs
@@ -291,7 +291,10 @@ pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) {
     if m.hurt_time == 10
         && !moving
         && let Some((d, _)) = m.last_damage
-        && matches!(d.kind, DamageKind::PlayerAttack | DamageKind::MobAttack)
+        && matches!(
+            d.kind,
+            DamageKind::PlayerAttack | DamageKind::MaceSmash | DamageKind::MobAttack
+        )
     {
         let from = [m.position.x, m.position.y, m.position.z];
         match d.attacker {
diff --git a/crates/horizon-client/src/mobs/sulfur_cube.rs b/crates/horizon-client/src/mobs/sulfur_cube.rs
index 57e48d6e2..00b846b86 100644
--- a/crates/horizon-client/src/mobs/sulfur_cube.rs
+++ b/crates/horizon-client/src/mobs/sulfur_cube.rs
@@ -289,6 +289,7 @@ pub fn accepts_damage(m: &mut Mob, source: &Damage, amount: f32) -> bool {
     let immune = matches!(
         source.kind,
         DamageKind::PlayerAttack
+            | DamageKind::MaceSmash
             | DamageKind::MobAttack
             | DamageKind::Arrow
             | DamageKind::Thrown
diff --git a/crates/horizon-client/src/motion.rs b/crates/horizon-client/src/motion.rs
index ee08f43d4..8830fb6f4 100644
--- a/crates/horizon-client/src/motion.rs
+++ b/crates/horizon-client/src/motion.rs
@@ -143,6 +143,13 @@ pub enum MotionEvent {
     InsidePortal {
         pos: BlockPos,
     },
+    /// `ServerPlayer.checkFallDamage` after a mace smash: block particles
+    /// from the landing block, more the further the fall.
+    SmashLanding {
+        state: BlockStateId,
+        position: BlockPos,
+        fall_distance: f64,
+    },
 }
 pub struct PlayerMotion {
     pub position: Vec3,
@@ -200,6 +207,9 @@ pub struct PlayerMotion {
     pub events: Vec,
     pub attributes: LiveAttributes i32>>,
     pub impulse: ImpulseContext,
+    /// `ServerPlayer.spawnExtraParticlesOnFall`: a mace smash on a grounded
+    /// target makes the next landing throw up the block below.
+    pub spawn_extra_particles_on_fall: bool,
     pub health: crate::health::PlayerHealth,
     /// Status effects and armor protection seen by movement and damage.
     pub status: crate::effects::StatusFlags,
@@ -259,6 +269,7 @@ impl PlayerMotion {
             health: crate::health::PlayerHealth::new(&resources.health, &mut attributes)?,
             status: crate::effects::StatusFlags::default(),
             impulse: ImpulseContext::default(),
+            spawn_extra_particles_on_fall: false,
             position,
             velocity: Vec3::ZERO,
             ground: GroundState::default(),
@@ -1385,6 +1396,15 @@ impl EntityMoveWorld for MotionWorld<'_, '_, '_> {
         state: BlockStateId,
         position: BlockPos,
     ) -> Result<()> {
+        if self.player.spawn_extra_particles_on_fall && grounded && self.player.fall_distance > 0.0
+        {
+            self.player.events.push(MotionEvent::SmashLanding {
+                state,
+                position,
+                fall_distance: self.player.fall_distance,
+            });
+            self.player.spawn_extra_particles_on_fall = false;
+        }
         self.player.events.push(MotionEvent::Landing {
             dy,
             grounded,
diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockUpdateOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockUpdateOracle.java
index 077a6dbff..956570d0f 100644
--- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockUpdateOracle.java
+++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockUpdateOracle.java
@@ -281,6 +281,8 @@ public final class VanillaBlockUpdateOracle {
             if (entities != null) entities.add(entity);
             return true;
         }
+        /** No players watch: the hurt animation and its sound are not sent. */
+        @Override public void broadcastDamageEvent(Entity entity, net.minecraft.world.damagesource.DamageSource source) { }
         @Override public void levelEvent(Entity source, int type, BlockPos p, int data) { emit("L " + type + " " + pos(p) + " " + data); }
         @Override public void playSeededSound(Entity except, double x, double y, double z, net.minecraft.core.Holder sound, SoundSource source, float volume, float pitch, long seed) {
             emit("S " + pos(BlockPos.containing(x, y, z)) + " " + sound.value().location());
diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDispenserOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDispenserOracle.java
index 24cf82ae5..4115c9063 100644
--- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDispenserOracle.java
+++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDispenserOracle.java
@@ -218,6 +218,19 @@ public final class VanillaDispenserOracle {
         }
         if (e.has("chest") && ent instanceof net.minecraft.world.entity.animal.equine.AbstractChestedHorse chested) chested.setChest(true);
         if (e.has("loot") && ent instanceof Mob mob) mob.setCanPickUpLoot(true);
+        if (e.has("ground")) ent.setOnGround(true);
+        if (e.has("health") && ent instanceof LivingEntity living) {
+            living.getAttribute(net.minecraft.world.entity.ai.attributes.Attributes.MAX_HEALTH).setBaseValue(e.get("health").getAsDouble());
+            living.setHealth(e.get("health").getAsFloat());
+        }
+        if (e.has("knockback_resistance") && ent instanceof LivingEntity living) {
+            living.getAttribute(net.minecraft.world.entity.ai.attributes.Attributes.KNOCKBACK_RESISTANCE).setBaseValue(e.get("knockback_resistance").getAsDouble());
+        }
+        if (e.has("marker") && ent instanceof net.minecraft.world.entity.decoration.ArmorStand stand) {
+            Method marker = net.minecraft.world.entity.decoration.ArmorStand.class.getDeclaredMethod("setMarker", boolean.class);
+            marker.setAccessible(true);
+            marker.invoke(stand, true);
+        }
         if (e.has("brown") && ent instanceof net.minecraft.world.entity.animal.cow.MushroomCow cow) {
             Method variant = net.minecraft.world.entity.animal.cow.MushroomCow.class.getDeclaredMethod("setVariant", net.minecraft.world.entity.animal.cow.MushroomCow.Variant.class);
             variant.setAccessible(true);
@@ -318,6 +331,8 @@ public final class VanillaDispenserOracle {
             used = useItem(w, origin, f.getAsJsonObject("use_item"));
         } else if (f.has("respawn_at")) {
             used = respawnAt(w, origin, f.getAsJsonObject("respawn_at"));
+        } else if (f.has("attack")) {
+            used = attack(w, f.getAsJsonObject("attack"), targets);
         } else if (f.has("hopper")) {
             // HopperBlockEntity.pushItemsTick, once.
             var hopper = (net.minecraft.world.level.block.entity.HopperBlockEntity) w.getBlockEntity(origin);
@@ -578,6 +593,148 @@ public final class VanillaDispenserOracle {
         return List.of("respawn " + num(p.x) + " " + num(p.y) + " " + num(p.z) + " " + Float.floatToRawIntBits((float) yaw.invoke(angle)));
     }
 
+    /**
+     * The player of an "attack" case: a `ServerPlayer` with a place, a fall
+     * and a velocity, a stand-in connection and abilities.
+     */
+    static final class Attacker extends net.minecraft.server.level.ServerPlayer {
+        VanillaBlockUpdateOracle.World world;
+        boolean creative, fallFlying;
+        ItemStack hand;
+        List stats;
+        Attacker() {
+            super(null, null, null, null);
+        }
+        @Override public ServerLevel level() { return world; }
+        @Override public boolean hasInfiniteMaterials() { return creative; }
+        @Override public boolean isCreative() { return creative; }
+        @Override public boolean isSpectator() { return false; }
+        @Override public boolean isFallFlying() { return fallFlying; }
+        @Override public net.minecraft.world.phys.Vec3 getKnownMovement() { return getDeltaMovement(); }
+        @Override public EntityType getType() { return EntityTypes.PLAYER; }
+        @Override public net.minecraft.core.Holder> typeHolder() { return EntityTypes.PLAYER.builtInRegistryHolder(); }
+        @Override public ItemStack getItemBySlot(EquipmentSlot slot) { return slot == EquipmentSlot.MAINHAND ? hand : ItemStack.EMPTY; }
+        @Override public ItemStack getItemInHand(net.minecraft.world.InteractionHand h) {
+            return h == net.minecraft.world.InteractionHand.MAIN_HAND ? hand : ItemStack.EMPTY;
+        }
+        @Override public void setItemInHand(net.minecraft.world.InteractionHand h, ItemStack stack) {
+            if (h == net.minecraft.world.InteractionHand.MAIN_HAND) hand = stack;
+        }
+        @Override public void awardStat(net.minecraft.stats.Stat stat, int count) {
+            stats.add("stat " + User.key(stat) + " " + BuiltInRegistries.STAT_TYPE.getKey(stat.getType()) + " " + count);
+        }
+    }
+
+    /** The synched data `Entity`'s constructor defines (a player's air supply is 300). */
+    @SuppressWarnings({"unchecked", "rawtypes"})
+    static void defineData(Entity e) throws Exception {
+        var builder = new net.minecraft.network.syncher.SynchedEntityData.Builder(e);
+        Object[][] base = {{"DATA_SHARED_FLAGS_ID", (byte) 0}, {"DATA_AIR_SUPPLY_ID", 300}, {"DATA_CUSTOM_NAME_VISIBLE", false},
+            {"DATA_CUSTOM_NAME", Optional.empty()}, {"DATA_SILENT", false}, {"DATA_NO_GRAVITY", false}, {"DATA_POSE", Pose.STANDING},
+            {"DATA_TICKS_FROZEN", 0}};
+        for (Object[] d : base) {
+            Field f = Entity.class.getDeclaredField((String) d[0]);
+            f.setAccessible(true);
+            builder.define((net.minecraft.network.syncher.EntityDataAccessor) f.get(null), d[1]);
+        }
+        Method define = Entity.class.getDeclaredMethod("defineSynchedData", net.minecraft.network.syncher.SynchedEntityData.Builder.class);
+        define.setAccessible(true);
+        define.invoke(e, builder);
+        VanillaBlockUpdateOracle.set(Entity.class, e, "entityData", builder.build());
+    }
+
+    /** A connection to no client: the motion packets a smash sends go nowhere. */
+    static final class Silent extends net.minecraft.server.network.ServerGamePacketListenerImpl {
+        Silent() { super(null, null, null, null); }
+        @Override public void send(net.minecraft.network.protocol.Packet packet) { }
+    }
+
+    /**
+     * A player hit on the first target with the case's item, as
+     * `Player.attack` and `itemAttackInteraction` run it after the attack
+     * strength scaled the base damage to `base`: the item's damage bonus
+     * (`MaceItem.getAttackDamageBonus`) and damage source, the target's real
+     * `hurtServer` (armor with the weapon's Breach), then `hurtEnemy` (the
+     * mace's smash), the post-attack enchantments (Wind Burst) and
+     * `postHurtEnemy` (the fall reset and the weapon's wear). Every target's
+     * health and velocity, the player's velocity, fall, impulse and the
+     * statistics follow.
+     */
+    static List attack(VanillaBlockUpdateOracle.World w, JsonObject op, List targets) throws Exception {
+        if (VanillaBlockUpdateOracle.Server.players == null) {
+            VanillaBlockUpdateOracle.Server.players = (Ops) VanillaBlockUpdateOracle.allocate.invoke(VanillaBlockUpdateOracle.unsafe, Ops.class);
+        }
+        Attacker player = (Attacker) VanillaBlockUpdateOracle.allocate.invoke(VanillaBlockUpdateOracle.unsafe, Attacker.class);
+        player.world = w;
+        player.creative = op.get("creative").getAsBoolean();
+        player.fallFlying = op.get("fall_flying").getAsBoolean();
+        player.hand = stack(op.get("item").getAsString());
+        player.stats = new ArrayList<>();
+        var abilities = new net.minecraft.world.entity.player.Abilities();
+        abilities.invulnerable = abilities.instabuild = abilities.mayfly = player.creative;
+        abilities.flying = op.get("flying").getAsBoolean();
+        VanillaBlockUpdateOracle.set(net.minecraft.world.entity.player.Player.class, player, "abilities", abilities);
+        var advancements = (net.minecraft.server.PlayerAdvancements) VanillaBlockUpdateOracle.allocate.invoke(VanillaBlockUpdateOracle.unsafe, net.minecraft.server.PlayerAdvancements.class);
+        VanillaBlockUpdateOracle.set(net.minecraft.server.PlayerAdvancements.class, advancements, "activeTriggers", new HashMap<>());
+        VanillaBlockUpdateOracle.set(net.minecraft.server.level.ServerPlayer.class, player, "advancements", advancements);
+        player.connection = (Silent) VanillaBlockUpdateOracle.allocate.invoke(VanillaBlockUpdateOracle.unsafe, Silent.class);
+        defineData(player);
+        player.setId(w.getNextEntityId());
+        VanillaBlockUpdateOracle.set(LivingEntity.class, player, "attributes",
+            new net.minecraft.world.entity.ai.attributes.AttributeMap(net.minecraft.world.entity.player.Player.createAttributes().build()));
+        player.setUUID(new UUID(0L, 1L));
+        VanillaBlockUpdateOracle.set(net.minecraft.world.entity.player.Player.class, player, "gameProfile",
+            new com.mojang.authlib.GameProfile(new UUID(0L, 1L), "Player"));
+        var p = op.getAsJsonArray("player");
+        var at = new net.minecraft.world.phys.Vec3(p.get(0).getAsDouble(), p.get(1).getAsDouble(), p.get(2).getAsDouble());
+        VanillaBlockUpdateOracle.set(Entity.class, player, "position", at);
+        VanillaBlockUpdateOracle.set(Entity.class, player, "blockPosition", BlockPos.containing(at));
+        var standing = EntityTypes.PLAYER.getDimensions();
+        VanillaBlockUpdateOracle.set(Entity.class, player, "dimensions", standing);
+        VanillaBlockUpdateOracle.set(Entity.class, player, "eyeHeight", standing.eyeHeight());
+        player.setBoundingBox(standing.makeBoundingBox(at));
+        var m = op.getAsJsonArray("motion");
+        player.setDeltaMovement(m.get(0).getAsDouble(), m.get(1).getAsDouble(), m.get(2).getAsDouble());
+        player.fallDistance = op.get("fall").getAsDouble();
+        if (op.has("impact")) {
+            var i = op.getAsJsonArray("impact");
+            player.currentImpulseImpactPos = new net.minecraft.world.phys.Vec3(i.get(0).getAsDouble(), i.get(1).getAsDouble(), i.get(2).getAsDouble());
+        }
+        // The player stands in the level, for the bursts that push it.
+        w.entities.add(player);
+        LivingEntity target = (LivingEntity) targets.get(0);
+        ItemStack weapon = player.hand;
+        var source = weapon.getDamageSource(player);
+        float base = op.get("base").getAsFloat();
+        float bonus = weapon.getItem().getAttackDamageBonus(target, base, source);
+        boolean hurt = target.hurtServer(w, source, base + bonus);
+        if (hurt) {
+            boolean weaponHit = weapon.hurtEnemy(target, player);
+            net.minecraft.world.item.enchantment.EnchantmentHelper.doPostAttackEffectsWithItemSource(w, target, source, weapon);
+            if (weaponHit) weapon.postHurtEnemy(target, player);
+        }
+        w.entities.remove(player);
+        List out = new ArrayList<>(player.stats);
+        out.add("attack bonus=" + num(bonus) + " source=" + source.typeHolder().getRegisteredName() + " hurt=" + hurt);
+        for (int i = 0; i < targets.size(); i++) {
+            Entity e = targets.get(i);
+            var v = e.getDeltaMovement();
+            String health = e instanceof LivingEntity living && !(e instanceof net.minecraft.world.entity.decoration.ArmorStand) ? num(living.getHealth()) : "-";
+            out.add("V " + i + " " + health + " " + num(v.x) + " " + num(v.y) + " " + num(v.z));
+        }
+        var v = player.getDeltaMovement();
+        var impact = player.currentImpulseImpactPos;
+        Field grace = LivingEntity.class.getDeclaredField("currentImpulseContextResetGraceTime");
+        grace.setAccessible(true);
+        Field extra = net.minecraft.server.level.ServerPlayer.class.getDeclaredField("spawnExtraParticlesOnFall");
+        extra.setAccessible(true);
+        out.add("P " + num(v.x) + " " + num(v.y) + " " + num(v.z) + " fall=" + num(player.fallDistance)
+            + " impact=" + (impact == null ? "-" : num(impact.x) + "," + num(impact.y) + "," + num(impact.z))
+            + " grace=" + grace.getInt(player) + " extra=" + extra.getBoolean(player));
+        out.add("held " + ParityData.canon(player.hand));
+        return out;
+    }
+
     /** The level's block entity positions by x, y, z. */
     static List sortedEntities(VanillaBlockUpdateOracle.World w) {
         List out = new ArrayList<>(w.blockEntities == null ? List.of() : w.blockEntities.keySet());
diff --git a/tools/test_mace_parity.py b/tools/test_mace_parity.py
new file mode 100644
index 000000000..123f19693
--- /dev/null
+++ b/tools/test_mace_parity.py
@@ -0,0 +1,204 @@
+"""Compare a player's melee hit with a mace (and other weapons) with vanilla's.
+
+Every case has a stone floor, a target mob standing on it or hanging in the
+air (health raised so no hit kills it, sometimes in armor), other mobs and
+armor stands around it, and a player near the target holding a mace with
+Density, Breach, Wind Burst and Unbreaking in any mix, or a sword, an axe, a
+stick or nothing. The player has fallen some distance (sometimes gliding or
+flying), moves, and may still have the impact point of an earlier impulse.
+
+Vanilla runs, over the headless level of the dispenser harness
+(`VanillaDispenserOracle.attack`), the steps of `Player.attack` after the
+attack strength scaled the base damage: `Item.getAttackDamageBonus`
+(`MaceItem`'s smash bonus with Density), the item's damage source
+(`mace_smash` or `player_attack`), the target's real `hurtServer` (armor
+thinned by Breach in `CombatRules.getDamageAfterAbsorb`), then
+`itemAttackInteraction`: `ItemStack.hurtEnemy` (`MaceItem.hurtEnemy`: the
+stopped fall, the waived fall damage, the smash sounds, the dust-pillar level
+event and the knockback around the target), the post-attack enchantments
+(Wind Burst's `ExplodeEffect` on the player) and `postHurtEnemy` (the fall
+reset and the weapon's wear with Unbreaking). Horizon runs the same steps
+through the helpers `Game::attack` uses (`smash_damage_bonus`,
+`hurt_by_player`, `weapon_hit`) in a headless game
+(`HORIZON_DISPENSE_FIXTURE`). Both print every target's health and
+velocity, the player's velocity, fall distance, impulse impact and grace
+time and its landing-particle flag, sounds, level and game events, the used
+statistic, the held stack and the level random afterwards.
+"""
+import json
+import math
+import os
+import random
+try:
+    from . import block_update_harness as h, lab, test_dispenser_parity as d, test_rust_parity as base
+except ImportError:
+    import block_update_harness as h
+    import lab
+    import test_dispenser_parity as d
+    import test_rust_parity as base
+
+TARGETS = ['pig', 'cow', 'sheep', 'zombie', 'husk', 'skeleton', 'zombie', 'pig']
+AROUND = ['pig', 'cow', 'zombie', 'sheep', 'armor_stand']
+ARMOR = ['iron', 'diamond', 'golden', 'chainmail', 'leather']
+FALLS = [0.0, 0.5, 1.0, 1.5, 1.5000001, 2.0, 2.75, 3.0, 3.25, 5.0, 5.0001, 6.5, 8.0, 8.5, 12.0, 25.3, 60.0]
+
+
+def stack(item, enchantments=None, damage=0):
+    components = []
+    if enchantments:
+        levels = ','.join(f'"minecraft:{e}":{lvl}' for e, lvl in enchantments.items())
+        components.append('"minecraft:enchantments":{%s}' % levels)
+    if damage:
+        components.append(f'"minecraft:damage":{damage}')
+    extra = ',components:{%s}' % ','.join(components) if components else ''
+    return '{id:"minecraft:%s",count:1%s}' % (item, extra)
+
+
+def weapon(rng):
+    roll = rng.random()
+    if roll < 0.75:
+        enchantments = {}
+        for name, top in [('density', 5), ('breach', 4), ('wind_burst', 3), ('unbreaking', 3)]:
+            if rng.random() < 0.35:
+                enchantments[name] = rng.randint(1, top)
+        return stack('mace', enchantments, rng.choice([0, 0, 0, 7, 300]))
+    if roll < 0.85:
+        return stack(rng.choice(['diamond_sword', 'iron_axe', 'stone_pickaxe']),
+                     {'breach': 2} if rng.random() < 0.2 else None, rng.choice([0, 0, 10]))
+    return rng.choice([stack('stick'), '-'])
+
+
+def cases(facts, count, seed):
+    rng = random.Random(seed)
+    states = d.States(facts)
+    floors = [states.get(b) for b in ['stone', 'grass_block', 'dirt', 'sand', 'oak_planks']]
+    for n in range(count):
+        case = {**h.environment(rng), 'pos': [0, 0, 0]}
+        case.pop('raining', None)
+        case.pop('thundering', None)
+        floor = rng.choice(floors)
+        case['cells'] = [[x, -1, z, floor] for x in range(-6, 7) for z in range(-6, 7)]
+        if rng.random() < 0.2:
+            # A wall the burst and the dust have to get past.
+            wall = states.get(rng.choice(['stone', 'glass', 'oak_planks']))
+            x = rng.choice([-3, -2, 2, 3])
+            case['cells'] += [[x, y, z, wall] for y in range(0, 3) for z in range(-2, 3)]
+        item = weapon(rng)
+        wind = 'wind_burst' in item
+        grounded = rng.random() < 0.75
+        tx, tz = rng.uniform(-0.5, 0.5), rng.uniform(-0.5, 0.5)
+        ty = 0.0 if grounded else rng.choice([0.5, 1.25, 2.0])
+        target = {'type': 'minecraft:' + rng.choice(TARGETS), 'pos': [tx, ty, tz], 'yaw': rng.uniform(-180, 180),
+                  'health': 1000.0}
+        if grounded:
+            target['ground'] = True
+        if target['type'] in ('minecraft:zombie', 'minecraft:husk', 'minecraft:skeleton') and rng.random() < 0.6:
+            material = rng.choice(ARMOR)
+            target['equip'] = {'chest': d.plain(f'{material}_chestplate')}
+            if rng.random() < 0.5:
+                target['equip']['head'] = d.plain(f'{material}_helmet')
+        if rng.random() < 0.15:
+            target['knockback_resistance'] = rng.choice([0.25, 0.5, 1.0])
+        entities = [target]
+        for _ in range(rng.choice([0, 1, 2, 3, 5])):
+            kind = rng.choice(AROUND)
+            near = rng.random() < 0.8
+            spread = 3.2 if near else 5.0
+            e = {'type': 'minecraft:' + kind, 'pos': [tx + rng.uniform(-spread, spread), rng.choice([0.0, 0.0, 0.5, 1.0]),
+                                                      tz + rng.uniform(-spread, spread)], 'yaw': rng.uniform(-180, 180)}
+            if kind == 'armor_stand':
+                # A marker is spared by the smash; Wind Burst's explosion would
+                # need its zero-size box.
+                if not wind and rng.random() < 0.4:
+                    e['marker'] = True
+            else:
+                e['health'] = 1000.0
+                if rng.random() < 0.2:
+                    e['knockback_resistance'] = rng.choice([0.4, 1.0])
+            if e['pos'][1] == 0.0 and rng.random() < 0.8:
+                e['ground'] = True
+            entities.append(e)
+        case['entities'] = entities
+        angle = rng.uniform(0, 6.283)
+        reach = rng.uniform(0.6, 2.8)
+        px, pz = tx + math.cos(angle) * reach, tz + math.sin(angle) * reach
+        py = ty + rng.choice([0.0, 0.3, 1.0, 1.7, 2.5])
+        fall = rng.choice(FALLS) if rng.random() < 0.7 else round(rng.uniform(0, 30), 3)
+        attack = {'item': item, 'creative': rng.random() < 0.15, 'player': [px, py, pz],
+                  'motion': [rng.uniform(-0.3, 0.3), -rng.uniform(0, 2.5), rng.uniform(-0.3, 0.3)],
+                  'fall': fall, 'fall_flying': rng.random() < 0.08, 'flying': rng.random() < 0.04,
+                  'base': round(rng.uniform(1.2, 7.0), 3)}
+        if rng.random() < 0.3:
+            attack['impact'] = [px + rng.uniform(-1, 1), py + rng.choice([-3.0, -0.5, 0.0, 2.0]), pz + rng.uniform(-1, 1)]
+        case['attack'] = attack
+        case['items'] = []
+        case['mode'] = 'dispense'
+        yield case
+
+
+def kind(case):
+    item = case['attack']['item']
+    name = item.split('"')[1].split(':')[1] if item != '-' else 'empty hand'
+    smash = case['attack']['fall'] > 1.5 and not case['attack']['fall_flying']
+    if name == 'mace':
+        name += ' smash' if smash else ' hit'
+        if 'wind_burst' in item:
+            name += ' with wind burst'
+    return name
+
+
+def main():
+    parser = h.argument_parser(__doc__)
+    args = parser.parse_args()
+    if args.count == 40000:
+        args.count = 3000
+    lock, jars, libraries = base.verify_artifacts()
+    facts = h.load_facts()
+    resources = lab.LOCAL / 'horizon-client' / lock['minecraft']['version']
+    work = lab.LOCAL / 'mace-parity'
+    work.mkdir(parents=True, exist_ok=True)
+    all_cases = list(cases(facts, args.count, args.seed))
+    (work / 'cases.jsonl').write_text(''.join(json.dumps(case) + '\n' for case in all_cases))
+    classes = work / 'classes'
+    classes.mkdir(exist_ok=True)
+    dependencies = os.pathsep.join(map(str, [jars['server'], *libraries]))
+    java_root = lab.ROOT / 'mods/horizon/src/test/java'
+    d.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', '-sourcepath', str(java_root), '-nowarn',
+           '-cp', dependencies, '-d', str(classes), str(java_root / 'dev/horizonlab/parity/VanillaDispenserOracle.java')])
+    d.run(['java', '-Xmx3G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaDispenserOracle',
+           str(resources), str(work / 'cases.jsonl'), str(work / 'native.txt')])
+    d.run(['cargo', 'build', '-q', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT,
+          env={**os.environ, 'CARGO_BUILD_JOBS': os.environ.get('CARGO_BUILD_JOBS', '3')})
+    d.run([str(lab.cargo_target() / 'release/horizon-client'), '--resources', str(resources)], cwd=work,
+          env={**os.environ, 'HORIZON_DISPENSE_FIXTURE': f'{work / "cases.jsonl"},{work / "rust.txt"}', 'HORIZON_NO_AUDIO': '1'})
+    ignore = tuple(prefix + ' ' for prefix in args.ignore.split(',') if prefix) + ('D ',)
+    native = h.split_cases((work / 'native.txt').read_text(), ignore)
+    rust = h.split_cases((work / 'rust.txt').read_text(), ignore)
+    assert len(native) == len(rust) == len(all_cases), (len(native), len(rust), len(all_cases))
+    groups, errors = {}, {}
+    smashed = burst = 0
+    for case, a, b in zip(all_cases, native, rust):
+        if a and a[0].startswith('error'):
+            errors.setdefault(a[0], []).append(case)
+            continue
+        smashed += any('source=minecraft:mace_smash hurt=true' in line for line in a)
+        burst += any(line.endswith('minecraft:entity.wind_charge.wind_burst') for line in a)
+        if not d.same(a, b):
+            groups.setdefault(kind(case), []).append((case, a, b))
+    for name, entries in sorted(errors.items(), key=lambda e: -len(e[1])):
+        print(f'oracle error x{len(entries)}: {name}')
+    for name, entries in sorted(groups.items(), key=lambda e: -len(e[1])):
+        print(f'{name}: {len(entries)} differing')
+        for case, a, b in entries[:args.show]:
+            print('  case entities=' + json.dumps(case['entities']) + ' attack=' + json.dumps(case['attack']) + f' seed={case["seed"]}')
+            print('   native ' + ' | '.join(sorted(a)))
+            print('   rust   ' + ' | '.join(sorted(b)))
+    total = sum(len(v) for v in groups.values())
+    skipped = sum(len(v) for v in errors.values())
+    print(f'{len(all_cases) - total - skipped}/{len(all_cases) - skipped} cases match ({skipped} oracle errors); '
+          f'vanilla smashed in {smashed} and burst in {burst}')
+    h.finish(total + skipped)
+
+
+if __name__ == '__main__':
+    main()

From 322a87cf93d5a20de2ee407b8ef4047e5f3970e0 Mon Sep 17 00:00:00 2001
From: rdbtCVS <87152661+rdbtCVS@users.noreply.github.com>
Date: Wed, 14 Oct 2026 20:34:25 +0100
Subject: [PATCH 22/24] Fix Clippy warnings in LAN tab list regression tests

---
 crates/horizon-client/src/game/scoreboard.rs | 170 +++++++++----------
 1 file changed, 85 insertions(+), 85 deletions(-)

diff --git a/crates/horizon-client/src/game/scoreboard.rs b/crates/horizon-client/src/game/scoreboard.rs
index e35a9d918..7bcb6ceed 100644
--- a/crates/horizon-client/src/game/scoreboard.rs
+++ b/crates/horizon-client/src/game/scoreboard.rs
@@ -656,91 +656,6 @@ fn local_tab_players(me: TabPlayer, guests: &[Guest]) -> Vec {
     players
 }
 
-#[cfg(test)]
-mod tab_list_tests {
-    use super::*;
-    use horizon_client::{
-        lan::{Joined, PlayerSender},
-        tab_list,
-    };
-    use horizon_protocol::packets::configuration::ClientInformation;
-    use std::sync::{
-        Arc,
-        atomic::{AtomicI32, Ordering},
-        mpsc,
-    };
-
-    fn guest(uuid: u128, name: &str) -> Guest {
-        let (tx, _rx) = mpsc::channel();
-        Guest::new(
-            Joined {
-                conn: uuid as u32,
-                uuid,
-                name: name.into(),
-                info: ClientInformation::new(8),
-                brand: "test".into(),
-                sender: PlayerSender {
-                    tx,
-                    pending: Arc::default(),
-                },
-                latency: Arc::new(AtomicI32::new(42)),
-                address: "127.0.0.1:25565".parse().unwrap(),
-            },
-            uuid as i32,
-            [0.0, 64.0, 0.0],
-            8,
-        )
-    }
-
-    #[test]
-    fn lan_tab_list_tracks_join_and_disconnect() {
-        let me = TabPlayer::new(1, PLAYER_NAME);
-        let mut guests = vec![guest(2, "Alex")];
-        let players = local_tab_players(me.clone(), &guests);
-        assert_eq!(players, [me.clone()]);
-        assert!(!tab_list::visible(true, true, players.len(), false));
-
-        guests[0].placed = true;
-        let players = local_tab_players(me.clone(), &guests);
-        assert_eq!(players.len(), 2);
-        assert_eq!(players[0], me);
-        assert_eq!(players[1].uuid, 2);
-        assert_eq!(players[1].name, "Alex");
-        assert!(tab_list::visible(true, true, players.len(), false));
-        assert!(!tab_list::visible(false, true, players.len(), false));
-
-        guests.clear();
-        let players = local_tab_players(me, &guests);
-        assert_eq!(players.len(), 1);
-        assert!(!tab_list::visible(true, true, players.len(), false));
-        assert!(tab_list::visible(true, true, players.len(), true));
-    }
-
-    #[test]
-    fn lan_tab_list_reads_current_guest_state() {
-        let me = TabPlayer::new(1, PLAYER_NAME);
-        let mut guests = vec![guest(2, "Alex"), guest(3, "Grumm")];
-        for guest in &mut guests {
-            guest.placed = true;
-        }
-        guests[0].game_mode = tab_list::SPECTATOR;
-        let players = local_tab_players(me.clone(), &guests);
-        assert_eq!(players.len(), 3);
-        assert_eq!(players[1].game_mode, tab_list::SPECTATOR);
-        assert_eq!(players[1].latency, 42);
-        assert_eq!(players[1].skin, tab_list::default_skin(2));
-        assert_eq!(players[2].name, "Grumm");
-
-        guests[0].game_mode = 1;
-        guests[0].latency.store(123, Ordering::Relaxed);
-        guests.remove(1);
-        let players = local_tab_players(me, &guests);
-        assert_eq!(players.len(), 2);
-        assert_eq!(players[1].game_mode, 1);
-        assert_eq!(players[1].latency, 123);
-    }
-}
-
 /// The commands' view of the game.
 struct GameEnv<'a, 'b> {
     g: &'a mut Game<'b>,
@@ -798,3 +713,88 @@ impl Env for GameEnv<'_, '_> {
         self.g.feedback(message);
     }
 }
+
+#[cfg(test)]
+mod tab_list_tests {
+    use super::*;
+    use horizon_client::{
+        lan::{Joined, PlayerSender},
+        tab_list,
+    };
+    use horizon_protocol::packets::configuration::ClientInformation;
+    use std::sync::{
+        Arc,
+        atomic::{AtomicI32, Ordering},
+        mpsc,
+    };
+
+    fn guest(uuid: u128, name: &str) -> Guest {
+        let (tx, _rx) = mpsc::channel();
+        Guest::new(
+            Joined {
+                conn: uuid as u32,
+                uuid,
+                name: name.into(),
+                info: ClientInformation::new(8),
+                brand: "test".into(),
+                sender: PlayerSender {
+                    tx,
+                    pending: Arc::default(),
+                },
+                latency: Arc::new(AtomicI32::new(42)),
+                address: "127.0.0.1:25565".parse().unwrap(),
+            },
+            uuid as i32,
+            [0.0, 64.0, 0.0],
+            8,
+        )
+    }
+
+    #[test]
+    fn lan_tab_list_tracks_join_and_disconnect() {
+        let me = TabPlayer::new(1, PLAYER_NAME);
+        let mut guests = vec![guest(2, "Alex")];
+        let players = local_tab_players(me.clone(), &guests);
+        assert_eq!(players.as_slice(), std::slice::from_ref(&me));
+        assert!(!tab_list::visible(true, true, players.len(), false));
+
+        guests[0].placed = true;
+        let players = local_tab_players(me.clone(), &guests);
+        assert_eq!(players.len(), 2);
+        assert_eq!(players[0], me);
+        assert_eq!(players[1].uuid, 2);
+        assert_eq!(players[1].name, "Alex");
+        assert!(tab_list::visible(true, true, players.len(), false));
+        assert!(!tab_list::visible(false, true, players.len(), false));
+
+        guests.clear();
+        let players = local_tab_players(me, &guests);
+        assert_eq!(players.len(), 1);
+        assert!(!tab_list::visible(true, true, players.len(), false));
+        assert!(tab_list::visible(true, true, players.len(), true));
+    }
+
+    #[test]
+    fn lan_tab_list_reads_current_guest_state() {
+        let me = TabPlayer::new(1, PLAYER_NAME);
+        let mut guests = vec![guest(2, "Alex"), guest(3, "Grumm")];
+        for guest in &mut guests {
+            guest.placed = true;
+        }
+        guests[0].game_mode = tab_list::SPECTATOR;
+        let players = local_tab_players(me.clone(), &guests);
+        assert_eq!(players.len(), 3);
+        assert_eq!(players[1].game_mode, tab_list::SPECTATOR);
+        assert_eq!(players[1].latency, 42);
+        assert_eq!(players[1].skin, tab_list::default_skin(2));
+        assert_eq!(players[2].name, "Grumm");
+
+        guests[0].game_mode = 1;
+        guests[0].latency.store(123, Ordering::Relaxed);
+        guests.remove(1);
+        let players = local_tab_players(me, &guests);
+        assert_eq!(players.len(), 2);
+        assert_eq!(players[1].game_mode, 1);
+        assert_eq!(players[1].latency, 123);
+    }
+}

From 79ab688bda0059173b43b00dffb51d9727be365e Mon Sep 17 00:00:00 2001
From: rdbtCVS <87152661+rdbtCVS@users.noreply.github.com>
Date: Wed, 14 Oct 2026 20:34:26 +0100
Subject: [PATCH 23/24] Fix banner rendering test lint on Rust 1.99

---
 crates/horizon-client/src/item_render/gui.rs | 28 ++++++++++++--------
 1 file changed, 17 insertions(+), 11 deletions(-)

diff --git a/crates/horizon-client/src/item_render/gui.rs b/crates/horizon-client/src/item_render/gui.rs
index 9456b26e4..e3d7cc876 100644
--- a/crates/horizon-client/src/item_render/gui.rs
+++ b/crates/horizon-client/src/item_render/gui.rs
@@ -274,17 +274,23 @@ mod tests {
 
     // Sample the emitted triangles in draw order, using opaque test faces.
     fn color_at(batch: &HudBatch, p: Vec2) -> Option {
-        batch.vertices.chunks_exact(3).rev().find_map(|tri| {
-            let [a, b, c] = std::array::from_fn(|i| Vec2::from(tri[i].pos));
-            let area = (b - a).perp_dot(c - a);
-            if area.abs() < 1e-6 {
-                return None;
-            }
-            let u = (b - p).perp_dot(c - p) / area;
-            let v = (c - p).perp_dot(a - p) / area;
-            let w = 1.0 - u - v;
-            (u >= 0.0 && v >= 0.0 && w >= 0.0).then_some(tri[0].color)
-        })
+        batch
+            .vertices
+            .as_chunks::<3>()
+            .0
+            .iter()
+            .rev()
+            .find_map(|tri| {
+                let [a, b, c] = std::array::from_fn(|i| Vec2::from(tri[i].pos));
+                let area = (b - a).perp_dot(c - a);
+                if area.abs() < 1e-6 {
+                    return None;
+                }
+                let u = (b - p).perp_dot(c - p) / area;
+                let v = (c - p).perp_dot(a - p) / area;
+                let w = 1.0 - u - v;
+                (u >= 0.0 && v >= 0.0 && w >= 0.0).then_some(tri[0].color)
+            })
     }
 
     #[test]

From 8caee518976214dfeb5cdda6495afd84d6dd6367 Mon Sep 17 00:00:00 2001
From: Cosmic <84875247+Online5277@users.noreply.github.com>
Date: Wed, 14 Oct 2026 15:37:32 -0400
Subject: [PATCH 24/24] Regenerate preparation metadata when reusing imports

---
 crates/horizon-prepare/src/artifacts.rs | 152 +++++++++++++++++++++---
 1 file changed, 134 insertions(+), 18 deletions(-)

diff --git a/crates/horizon-prepare/src/artifacts.rs b/crates/horizon-prepare/src/artifacts.rs
index 6f8e45bf8..c9b1947ed 100644
--- a/crates/horizon-prepare/src/artifacts.rs
+++ b/crates/horizon-prepare/src/artifacts.rs
@@ -513,7 +513,27 @@ pub fn import(
             &hint(LAUNCHER_HINT, version),
         )?);
     }
-    for (side, jar) in [("client", &client), ("server", &server)] {
+    write_import_metadata(
+        root,
+        lock,
+        &client,
+        &server,
+        &client_libraries,
+        &server_libraries,
+        log,
+    )
+}
+
+fn write_import_metadata(
+    root: &Path,
+    lock: &Lock,
+    client: &Path,
+    server: &Path,
+    client_libraries: &[PathBuf],
+    server_libraries: &[PathBuf],
+    log: Log,
+) -> Result<(), String> {
+    for (side, jar) in [("client", client), ("server", server)] {
         let data = crate::inventory::inventory(jar)?;
         let count = |key| data.get(key).cloned().unwrap_or(Value::Null);
         write_json(
@@ -538,25 +558,19 @@ pub fn import(
     write_json(
         &lock.directory.join("prepared.json"),
         &Value::Object(vec![
-            ("version".into(), Value::str(id)),
+            ("version".into(), Value::str(&lock.version)),
             (
                 "jars".into(),
                 Value::Object(vec![
-                    (
-                        "client".into(),
-                        Value::Str(relative_display(&client, root)?),
-                    ),
-                    (
-                        "server".into(),
-                        Value::Str(relative_display(&server, root)?),
-                    ),
+                    ("client".into(), Value::Str(relative_display(client, root)?)),
+                    ("server".into(), Value::Str(relative_display(server, root)?)),
                 ]),
             ),
             (
                 "libraries".into(),
                 Value::Object(vec![
-                    ("client".into(), paths(&client_libraries)?),
-                    ("server".into(), paths(&server_libraries)?),
+                    ("client".into(), paths(client_libraries)?),
+                    ("server".into(), paths(server_libraries)?),
                 ]),
             ),
         ]),
@@ -597,12 +611,33 @@ pub fn reuse_imported(root: &Path, log: Log) -> Result {
         Ok(files)
     };
     if checked(lock.directory.clone()).is_ok() {
+        if [
+            "prepared.json",
+            "reports/client-inventory.json",
+            "reports/server-inventory.json",
+        ]
+        .iter()
+        .any(|path| !lock.directory.join(path).is_file())
+        {
+            let found = verify(&lock)?;
+            let client_libraries = client_libraries(&lock, &found.manifest)?;
+            write_import_metadata(
+                &root,
+                &lock,
+                &found.jars["client"],
+                &found.jars["server"],
+                &client_libraries,
+                &found.libraries,
+                log,
+            )?;
+        }
         log(&format!("Using imported Minecraft {}", lock.version));
         return Ok(true);
     }
     let Some(versions) = root.parent() else {
         return Ok(false);
     };
+    // Sibling discovery is intended for the launcher's versions/ folder.
     let mut siblings: Vec<_> = fs::read_dir(versions)
         .map_err(|e| format!("{}: {e}", versions.display()))?
         .filter_map(Result::ok)
@@ -625,7 +660,17 @@ pub fn reuse_imported(root: &Path, log: Log) -> Result {
                 "",
             )?;
         }
-        checked(lock.directory.clone())?;
+        let found = verify(&lock)?;
+        let client_libraries = client_libraries(&lock, &found.manifest)?;
+        write_import_metadata(
+            &root,
+            &lock,
+            &found.jars["client"],
+            &found.jars["server"],
+            &client_libraries,
+            &found.libraries,
+            log,
+        )?;
         log(&format!(
             "Reused imported Minecraft {} from {}",
             lock.version,
@@ -716,6 +761,15 @@ mod tests {
     use super::*;
     use std::io::Write;
 
+    fn jar(marker: &[u8]) -> Vec {
+        let mut archive = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
+        archive
+            .start_file("marker", zip::write::SimpleFileOptions::default())
+            .unwrap();
+        archive.write_all(marker).unwrap();
+        archive.finish().unwrap().into_inner()
+    }
+
     struct Imports {
         directory: PathBuf,
         source: PathBuf,
@@ -737,8 +791,10 @@ mod tests {
                 fs::create_dir_all(path.parent().unwrap()).unwrap();
                 fs::write(path, data).unwrap();
             };
-            write("jars/client.jar", b"client");
-            write("jars/server-game.jar", b"server game");
+            let client = jar(b"client");
+            let game = jar(b"server game");
+            write("jars/client.jar", &client);
+            write("jars/server-game.jar", &game);
             write("libraries/server/server.jar", b"server library");
             write("libraries/client/client.jar", b"client library");
             write("reports/private.txt", b"not an imported artifact");
@@ -747,7 +803,7 @@ mod tests {
             let entries = [
                 (
                     "META-INF/versions.list",
-                    format!("{}\t9.9\tgame.jar\n", crate::sha256_hex(b"server game")),
+                    format!("{}\t9.9\tgame.jar\n", crate::sha256_hex(&game)),
                 ),
                 (
                     "META-INF/libraries.list",
@@ -764,7 +820,7 @@ mod tests {
                 bundle.write_all(text.as_bytes()).unwrap();
             }
             for (name, bytes) in [
-                ("META-INF/versions/game.jar", b"server game".as_slice()),
+                ("META-INF/versions/game.jar", game.as_slice()),
                 (
                     "META-INF/libraries/server.jar",
                     b"server library".as_slice(),
@@ -810,6 +866,11 @@ mod tests {
     #[test]
     fn imported_files_are_reused_without_the_official_install() {
         let fixture = Imports::new();
+        fs::write(
+            fixture.imported(&fixture.source).join("prepared.json"),
+            b"stale source metadata",
+        )
+        .unwrap();
         assert!(reuse_imported(&fixture.target, &|_| {}).unwrap());
         let lock = Lock::read(&fixture.target).unwrap();
         let artifacts = verify(&lock).unwrap();
@@ -818,14 +879,66 @@ mod tests {
             1
         );
         assert_eq!(artifacts.libraries.len(), 1);
+        let prepared = read_json(&lock.directory.join("prepared.json")).unwrap();
+        assert_eq!(prepared.get("version").and_then(Value::as_str), Some("9.9"));
+        for side in ["client", "server"] {
+            assert_eq!(
+                prepared
+                    .get("jars")
+                    .unwrap()
+                    .get(side)
+                    .and_then(Value::as_str),
+                Some(
+                    relative_display(&artifacts.jars[side], &fixture.target)
+                        .unwrap()
+                        .as_str()
+                )
+            );
+            let inventory = read_json(
+                &lock
+                    .directory
+                    .join(format!("reports/{side}-inventory.json")),
+            )
+            .unwrap();
+            assert_eq!(
+                inventory.get("jar_sha256").and_then(Value::as_str),
+                Some(digest(&artifacts.jars[side], "sha256").unwrap().as_str())
+            );
+        }
         assert!(!lock.directory.join("reports/private.txt").exists());
+        for side in ["client", "server"] {
+            let libraries = prepared
+                .get("libraries")
+                .unwrap()
+                .get(side)
+                .unwrap()
+                .as_array()
+                .unwrap();
+            assert_eq!(libraries.len(), 1);
+            assert_eq!(
+                libraries[0].as_str(),
+                Some(
+                    relative_display(
+                        &lock.directory.join(format!("libraries/{side}/{side}.jar")),
+                        &fixture.target
+                    )
+                    .unwrap()
+                    .as_str()
+                )
+            );
+        }
         // The current root's valid imports suffice even after the older copy is corrupted.
         fs::write(
             fixture.imported(&fixture.source).join("jars/client.jar"),
             b"bad",
         )
         .unwrap();
+        // Repair metadata omitted by earlier reuse implementations, without a sibling.
+        fs::remove_file(lock.directory.join("prepared.json")).unwrap();
+        fs::remove_file(lock.directory.join("reports/client-inventory.json")).unwrap();
         assert!(reuse_imported(&fixture.target, &|_| {}).unwrap());
+        assert!(read_json(&lock.directory.join("prepared.json")).is_ok());
+        assert!(read_json(&lock.directory.join("reports/client-inventory.json")).is_ok());
     }
 
     #[test]
@@ -873,7 +986,10 @@ mod tests {
         fs::create_dir_all(target.join("jars")).unwrap();
         fs::write(target.join("jars/client.jar"), b"bad").unwrap();
         assert!(reuse_imported(&fixture.target, &|_| {}).unwrap());
-        assert_eq!(fs::read(target.join("jars/client.jar")).unwrap(), b"client");
+        assert_eq!(
+            fs::read(target.join("jars/client.jar")).unwrap(),
+            fs::read(fixture.imported(&fixture.source).join("jars/client.jar")).unwrap()
+        );
     }
 
     #[test]