diff --git a/Cargo.lock b/Cargo.lock index c7f0c2d..0b28e9f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8,6 +8,41 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" +[[package]] +name = "aead" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0" +dependencies = [ + "crypto-common", + "generic-array", +] + +[[package]] +name = "aes" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0" +dependencies = [ + "cfg-if", + "cipher", + "cpufeatures", +] + +[[package]] +name = "aes-gcm" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "831010a0f742e1209b3bcea8fab6a8e149051ba6099432c8cb2cc117dec3ead1" +dependencies = [ + "aead", + "aes", + "cipher", + "ctr", + "ghash", + "subtle", +] + [[package]] name = "aho-corasick" version = "1.1.5" @@ -276,6 +311,15 @@ dependencies = [ "serde_core", ] +[[package]] +name = "blake2" +version = "0.10.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe" +dependencies = [ + "digest", +] + [[package]] name = "block-buffer" version = "0.10.4" @@ -477,6 +521,30 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" +[[package]] +name = "chacha20" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3613f74bd2eac03dad61bd53dbe620703d4371614fe0bc3b9f04dd36fe4e818" +dependencies = [ + "cfg-if", + "cipher", + "cpufeatures", +] + +[[package]] +name = "chacha20poly1305" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10cd79432192d1c0f4e1a0fef9527696cc039165d729fb41b3f4f4f354c2dc35" +dependencies = [ + "aead", + "chacha20", + "cipher", + "poly1305", + "zeroize", +] + [[package]] name = "chrono" version = "0.4.45" @@ -489,6 +557,33 @@ dependencies = [ "windows-link", ] +[[package]] +name = "cipher" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" +dependencies = [ + "crypto-common", + "inout", + "zeroize", +] + +[[package]] +name = "coa-control-proto" +version = "0.1.0" +dependencies = [ + "base64 0.22.1", + "coa-registry-proto", + "ed25519-dalek", + "hex", + "serde", + "serde_json", + "sha2", + "snow", + "thiserror 2.0.21", + "uuid", +] + [[package]] name = "coa-core" version = "0.6.6" @@ -685,6 +780,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" dependencies = [ "generic-array", + "rand_core", "typenum", ] @@ -717,6 +813,15 @@ version = "1.0.13" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "914a755b7c2d4af2bdcff7ce1739e2db9a1b81a9b07123d8015786ae03c0980d" +[[package]] +name = "ctr" +version = "0.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0369ee1ad671834580515889b80f2ea915f23b8be8d0daa4bbaf2ac5c7590835" +dependencies = [ + "cipher", +] + [[package]] name = "curve25519-dalek" version = "4.1.3" @@ -879,6 +984,7 @@ checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ "block-buffer", "crypto-common", + "subtle", ] [[package]] @@ -1489,6 +1595,16 @@ dependencies = [ "r-efi 6.0.0", ] +[[package]] +name = "ghash" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0d8a4362ccb29cb0b265253fb0a2728f592895ee6854fd9bc13f2ffda266ff1" +dependencies = [ + "opaque-debug", + "polyval", +] + [[package]] name = "gio" version = "0.18.4" @@ -2006,6 +2122,15 @@ dependencies = [ "cfb", ] +[[package]] +name = "inout" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01" +dependencies = [ + "generic-array", +] + [[package]] name = "ipnet" version = "2.12.2" @@ -2757,6 +2882,12 @@ version = "1.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" +[[package]] +name = "opaque-debug" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" + [[package]] name = "open" version = "5.4.4" @@ -3040,6 +3171,29 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "poly1305" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8159bd90725d2df49889a078b54f4f79e87f1f8a8444194cdca81d38f5393abf" +dependencies = [ + "cpufeatures", + "opaque-debug", + "universal-hash", +] + +[[package]] +name = "polyval" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d1fe60d06143b2430aa532c94cfe9e29783047f06c0d7fd359a9a51b729fa25" +dependencies = [ + "cfg-if", + "cpufeatures", + "opaque-debug", + "universal-hash", +] + [[package]] name = "portable-atomic" version = "1.15.0" @@ -3898,6 +4052,22 @@ version = "1.16.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f9395f0f0eee849a9b707b2f06bb92a6a422090e2123bb2ef8e87a0e61892a8e" +[[package]] +name = "snow" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "850948bee068e713b8ab860fe1adc4d109676ab4c3b621fd8147f06b261f2f85" +dependencies = [ + "aes-gcm", + "blake2", + "chacha20poly1305", + "curve25519-dalek", + "rand_core", + "rustc_version", + "sha2", + "subtle", +] + [[package]] name = "socket2" version = "0.6.5" @@ -4931,6 +5101,16 @@ version = "1.13.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8" +[[package]] +name = "universal-hash" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea" +dependencies = [ + "crypto-common", + "subtle", +] + [[package]] name = "untrusted" version = "0.9.0" diff --git a/Cargo.toml b/Cargo.toml index 779d9b2..f549981 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,7 +1,7 @@ [workspace] resolver = "2" -members = ["crates/coa-core", "crates/coa-release", "crates/coa-registry-proto", "src-tauri"] -exclude = ["services/coa-registry"] +members = ["crates/coa-core", "crates/coa-release", "crates/coa-registry-proto", "crates/coa-control-proto", "src-tauri"] +exclude = ["services/coa-registry", "services/coa-registry-e2e", "services/coa-coordinator"] [workspace.package] version = "0.6.6" diff --git a/crates/coa-control-proto/Cargo.toml b/crates/coa-control-proto/Cargo.toml new file mode 100644 index 0000000..aa6d87e --- /dev/null +++ b/crates/coa-control-proto/Cargo.toml @@ -0,0 +1,19 @@ +[package] +name = "coa-control-proto" +description = "Player <-> Host control protocol (Phase 12): coordinator framing, the end-to-end Noise channel, identity binding and the application messages. No I/O." +version = "0.1.0" +edition = "2021" +license = "AGPL-3.0-only" +publish = false + +[dependencies] +coa-registry-proto = { path = "../coa-registry-proto" } +serde = { version = "1", features = ["derive"] } +serde_json = "1" +sha2 = "0.10" +hex = "0.4" +base64 = "0.22" +ed25519-dalek = "2" +snow = "0.9" +thiserror = "2" +uuid = { version = "1", features = ["serde", "v4", "v7"] } diff --git a/crates/coa-control-proto/src/app.rs b/crates/coa-control-proto/src/app.rs new file mode 100644 index 0000000..55aeee7 --- /dev/null +++ b/crates/coa-control-proto/src/app.rs @@ -0,0 +1,210 @@ +//! The application messages inside the end-to-end channel. One request, one response, in order. Nothing here is ever visible to the Coordinator. + +use serde::{Deserialize, Serialize}; +use uuid::Uuid; + +use crate::{invalid, ControlError, Result}; + +pub const MAX_REQUEST_BYTES: usize = 4096; +pub const MIN_USERNAME: usize = 3; +pub const MAX_USERNAME: usize = 16; +pub const MIN_PASSWORD: usize = 8; +pub const MAX_PASSWORD: usize = 16; +pub const MAX_CHARACTERS: usize = 200; + +/// A game account name: 3 to 16 ASCII letters, digits or `_`, not beginning or ending with `_`. +pub fn valid_username(s: &str) -> bool { + (MIN_USERNAME..=MAX_USERNAME).contains(&s.len()) && s.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_') && !s.starts_with('_') && !s.ends_with('_') +} + +/// A game account password: 8 to 16 ASCII letters and digits (the game compares passwords case-insensitively, so letters carry no extra strength; digits and length do). +pub fn valid_password(s: &str) -> bool { + (MIN_PASSWORD..=MAX_PASSWORD).contains(&s.len()) && s.bytes().all(|b| b.is_ascii_alphanumeric()) +} + +/// A password for a realm, 16 characters of `A-Z0-9` from the operating system's randomness (about 82 bits), unique per realm. +pub fn generate_password() -> String { + const ALPHABET: &[u8; 36] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; + let mut out = String::with_capacity(16); + while out.len() < 16 { + for b in Uuid::new_v4().as_bytes() { + // rejection sampling: 252 is the largest multiple of 36 below 256, so every symbol is equally likely + if *b < 252 && out.len() < 16 { + out.push(ALPHABET[(*b % 36) as usize] as char); + } + } + } + out +} + +/// The account name wanted, made fit for the game: letters and digits only, upper case, at most 16 characters. +pub fn sanitize_username(wanted: &str) -> String { + let base: String = wanted.chars().filter(char::is_ascii_alphanumeric).collect::().to_ascii_uppercase(); + let base: String = base.chars().take(MAX_USERNAME).collect(); + if base.len() >= MIN_USERNAME { base } else { format!("{base}PLAYER").chars().take(MAX_USERNAME).collect() } +} + +/// The stable alternative of an occupied name: `DMITRY` becomes `DMITRY_7K4M`. The suffix is derived from the player's id, so the same player gets the same alternative. +pub fn alternative_username(base: &str, player: &Uuid, attempt: u32) -> String { + const ALPHABET: &[u8; 32] = b"ABCDEFGHJKLMNPQRSTUVWXYZ23456789"; + let bytes = player.as_bytes(); + let mix = u32::from_be_bytes([bytes[12], bytes[13], bytes[14], bytes[15]]).wrapping_add(attempt.wrapping_mul(0x9E37_79B1)); + let suffix: String = (0..4).map(|i| ALPHABET[((mix >> (i * 5)) & 31) as usize] as char).collect(); + let keep = MAX_USERNAME - 5; + let head: String = base.chars().take(keep).collect(); + format!("{head}_{suffix}") +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(tag = "op", rename_all = "snake_case", deny_unknown_fields)] +pub enum Request { + Hello { protocol: u32, client: String }, + /// Make the player's account on this realm, or reuse it. `password` is the one the player's Manager keeps for this realm; it travels only inside the channel. + Provision { desired: Option, password: String, have_credentials: bool }, + ListCharacters, + Claim { token: u32 }, + ClaimAck { character_id: Uuid }, + /// Link an account the realm already has (one time). + Link { login: String, password: String }, + Route, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum AppError { + UnsupportedVersion, + Invalid, + ProvisioningOff, + NoAccount, + NotAtCharacterSelect, + NotYours, + AlreadyClaimed, + NotEligible, + WrongCredentials, + AccountTaken, + RateLimited, + Unavailable, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct CharacterEntry { + /// Opaque to the player: the Host's handle for this character, valid for this realm. + pub token: u32, + pub name: String, + pub class: u32, + pub race: u32, + pub level: u32, + pub eligible: bool, + pub reasons: Vec, + /// Already portable and claimed by this player. + pub yours: bool, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(tag = "op", rename_all = "snake_case")] +pub enum Response { + Welcome { realm_id: coa_registry_proto::RealmId, automatic: bool, existing_only: bool, route: Option }, + Provisioned { username: String, created: bool, reset: bool }, + Characters { characters: Vec }, + /// The character as the Host exported it: `payload` is the base64 of the encoded portable snapshot, `sha256` its hash. + Claimed { character_id: Uuid, sha256: String, payload: String }, + Linked { username: String }, + Done, + RouteInfo { address: Option }, + Error { code: AppError, message: String }, +} + +pub fn encode_request(r: &Request) -> Vec { + serde_json::to_vec(r).expect("a request serialises") +} + +pub fn decode_request(bytes: &[u8]) -> Result { + if bytes.len() > MAX_REQUEST_BYTES { + return Err(ControlError::Limit("a request is too long".into())); + } + let r: Request = serde_json::from_slice(bytes).map_err(|_| ControlError::Invalid("a request is not valid".into()))?; + match &r { + Request::Provision { desired, password, .. } => { + if !valid_password(password) || desired.as_deref().is_some_and(|d| d.len() > 64 || d.chars().any(char::is_control)) { + return invalid("a provisioning request has an unusable password or name"); + } + } + Request::Link { login, password } => { + if !valid_username(login) || !valid_password_for_link(password) { + return invalid("a link request has an unusable login or password"); + } + } + Request::Hello { client, .. } if client.len() > 64 => return invalid("the client name is too long"), + _ => {} + } + Ok(r) +} + +/// An existing account's password may be anything the game accepts (6 to 16 printable characters without spaces or quotes). +pub fn valid_password_for_link(s: &str) -> bool { + (6..=16).contains(&s.len()) && s.chars().all(|c| c.is_ascii_graphic() && c != '"' && c != '\'' && c != '\\') +} + +pub fn encode_response(r: &Response) -> Vec { + serde_json::to_vec(r).expect("a response serialises") +} + +pub fn decode_response(bytes: &[u8]) -> Result { + serde_json::from_slice(bytes).map_err(|_| ControlError::Invalid("a response is not valid".into())) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn passwords_are_random_unique_and_fit_the_game() { + let a = generate_password(); + let b = generate_password(); + assert_ne!(a, b); + assert!(valid_password(&a) && a.len() == 16 && a.bytes().all(|c| c.is_ascii_uppercase() || c.is_ascii_digit()), "{a}"); + let mut seen = std::collections::HashSet::new(); + for _ in 0..200 { + assert!(seen.insert(generate_password()), "no repeats"); + } + let symbols: std::collections::HashSet = (0..200).flat_map(|_| generate_password().chars().collect::>()).collect(); + assert_eq!(symbols.len(), 36, "every symbol occurs"); + } + + #[test] + fn names_are_made_fit_and_the_alternative_is_stable() { + assert_eq!(sanitize_username("Dmitry"), "DMITRY"); + assert_eq!(sanitize_username("d m-i_t.r y"), "DMITRY"); + assert_eq!(sanitize_username("ab"), "ABPLAYER"); + assert_eq!(sanitize_username("a very long player name indeed"), "AVERYLONGPLAYERN"); + assert_eq!(sanitize_username("