From 58a99f0a6d16774c6a7f09aa42e49853e574b046 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=94=D0=BC=D0=B8=D1=82=D1=80=D0=B8=D0=B9?= Date: Thu, 22 Oct 2026 13:04:57 +0500 Subject: [PATCH 1/6] feat: multi-ruleset realms and strictly isolated portable characters --- crates/coa-control-proto/src/app.rs | 12 ++ .../coa-control-proto/tests/hostile_input.rs | 14 ++ crates/coa-core/examples/portable_smoke.rs | 6 +- crates/coa-core/src/control/backend.rs | 6 + crates/coa-core/src/control/join.rs | 2 + crates/coa-core/src/control/service.rs | 89 ++++++++++++ crates/coa-core/src/portable/error.rs | 5 + .../src/portable/migrations/001_init.sql | 2 +- .../portable/migrations/009_multiruleset.sql | 23 +++ crates/coa-core/src/portable/model.rs | 78 ++++++++++- .../src/portable/realm/collections.rs | 32 +++-- .../src/portable/realm/live_wardrobe.rs | 10 +- crates/coa-core/src/portable/realm/mod.rs | 2 +- crates/coa-core/src/portable/realm/profile.rs | 7 +- crates/coa-core/src/portable/realm/tests.rs | 2 +- .../coa-core/src/portable/service/access.rs | 13 +- .../coa-core/src/portable/service/engine.rs | 48 +++++-- .../src/portable/session/collection_tests.rs | 24 ++-- crates/coa-core/src/portable/session/host.rs | 18 ++- crates/coa-core/src/portable/session/owner.rs | 23 +-- .../src/portable/session/profile_tests.rs | 4 +- .../coa-core/src/portable/session/protocol.rs | 63 +++++++-- crates/coa-core/src/portable/store.rs | 91 ++++++++++-- crates/coa-core/src/portable/store/owner.rs | 26 +++- crates/coa-core/src/portable/store/tests.rs | 29 ++-- crates/coa-core/src/realm_registry/advert.rs | 25 +++- crates/coa-registry-proto/src/browse.rs | 3 +- crates/coa-registry-proto/src/caps.rs | 12 +- docs/MULTIRULESET_PORTABLE_AUDIT.md | 132 ++++++++++++++++++ docs/REBORN_PORTABLE_AUDIT.md | 40 ++++++ .../migrations/0005_reborn_ruleset.sql | 3 + services/coa-registry/src/pg.rs | 3 + src-tauri/src/control_cmds.rs | 1 + src/lib/browse.ts | 2 +- src/screens/BrowsePage.tsx | 10 +- 35 files changed, 736 insertions(+), 124 deletions(-) create mode 100644 crates/coa-core/src/portable/migrations/009_multiruleset.sql create mode 100644 docs/MULTIRULESET_PORTABLE_AUDIT.md create mode 100644 docs/REBORN_PORTABLE_AUDIT.md create mode 100644 services/coa-registry/migrations/0005_reborn_ruleset.sql diff --git a/crates/coa-control-proto/src/app.rs b/crates/coa-control-proto/src/app.rs index cbbc792..f3e0129 100644 --- a/crates/coa-control-proto/src/app.rs +++ b/crates/coa-control-proto/src/app.rs @@ -16,6 +16,10 @@ pub const MIN_PASSWORD: usize = 8; pub const MAX_PASSWORD: usize = 16; pub const MAX_CHARACTERS: usize = 200; +fn default_ruleset() -> String { + "coa".to_string() +} + /// 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()) @@ -103,6 +107,8 @@ pub enum Request { TransferOffer { transfer_id: Uuid, character_id: Uuid, + #[serde(default = "default_ruleset")] + ruleset: String, canonical_revision: u64, content_hash: String, total_size: usize, @@ -273,11 +279,15 @@ pub fn decode_request(bytes: &[u8]) -> Result { return invalid("the client name is too long") } Request::TransferOffer { + ruleset, content_hash, total_size, collections, .. } => { + if !matches!(ruleset.as_str(), "coa" | "wildcard" | "reborn") { + return invalid("transfer ruleset must be coa, wildcard, or reborn"); + } if content_hash.len() != 64 || !content_hash.chars().all(|c| c.is_ascii_hexdigit()) { return invalid("transfer content hash must be 64 hex characters"); } @@ -430,6 +440,7 @@ mod tests { let offer = Request::TransferOffer { transfer_id: tid, character_id: cid, + ruleset: "coa".into(), canonical_revision: 5, content_hash: hash.clone(), total_size: 1024, @@ -442,6 +453,7 @@ mod tests { let bad_hash = Request::TransferOffer { transfer_id: tid, character_id: cid, + ruleset: "coa".into(), canonical_revision: 5, content_hash: "too_short".into(), total_size: 1024, diff --git a/crates/coa-control-proto/tests/hostile_input.rs b/crates/coa-control-proto/tests/hostile_input.rs index 3764c51..f0d285f 100644 --- a/crates/coa-control-proto/tests/hostile_input.rs +++ b/crates/coa-control-proto/tests/hostile_input.rs @@ -90,6 +90,7 @@ fn test_app_request_hostile_limits_and_validation() { let offer = Request::TransferOffer { transfer_id: Uuid::now_v7(), character_id: Uuid::now_v7(), + ruleset: "coa".into(), canonical_revision: 1, content_hash: "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef".into(), total_size: 1024, @@ -105,6 +106,7 @@ fn test_app_request_hostile_limits_and_validation() { let bad_hash_offer = Request::TransferOffer { transfer_id: Uuid::now_v7(), character_id: Uuid::now_v7(), + ruleset: "coa".into(), canonical_revision: 1, content_hash: "not_a_valid_hex_hash".into(), total_size: 1024, @@ -112,6 +114,18 @@ fn test_app_request_hostile_limits_and_validation() { }; assert!(decode_request(&encode_request(&bad_hash_offer)).is_err()); + // 4b. Invalid ruleset rejected + let bad_ruleset_offer = Request::TransferOffer { + transfer_id: Uuid::now_v7(), + character_id: Uuid::now_v7(), + ruleset: "invalid_ruleset".into(), + canonical_revision: 1, + content_hash: "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef".into(), + total_size: 1024, + collections: BTreeMap::new(), + }; + assert!(decode_request(&encode_request(&bad_ruleset_offer)).is_err()); + // 5. TransferChunk offset out of bounds let bad_offset_chunk = Request::TransferChunk { transfer_id: Uuid::now_v7(), diff --git a/crates/coa-core/examples/portable_smoke.rs b/crates/coa-core/examples/portable_smoke.rs index 020f1be..3ecd0ee 100644 --- a/crates/coa-core/examples/portable_smoke.rs +++ b/crates/coa-core/examples/portable_smoke.rs @@ -457,7 +457,7 @@ fn run() -> Result<(), String> { } ("collection-states", [out]) => { let states = OwnerService::new(&mut store) - .collection_states() + .collection_states(coa_core::portable::Ruleset::Coa) .map_err(|e| e.to_string())?; for s in &states { println!( @@ -618,7 +618,7 @@ fn run() -> Result<(), String> { let set = coa_core::portable::collection::IdSet::from_ids(ids).map_err(|e| e.to_string())?; let merge = store - .merge_collection(profile, kind, &set) + .merge_collection(profile, coa_core::portable::Ruleset::Coa, kind, &set) .map_err(|e| e.to_string())?; println!( "{kind}: {} id(s) added{}", @@ -633,7 +633,7 @@ fn run() -> Result<(), String> { let profile = store.default_profile().map_err(|e| e.to_string())?; for kind in coa_core::portable::session::protocol::COLLECTION_KINDS { match store - .collection_info(profile, kind) + .collection_info(profile, coa_core::portable::Ruleset::Coa, kind) .map_err(|e| e.to_string())? { Some(i) => println!( diff --git a/crates/coa-core/src/control/backend.rs b/crates/coa-core/src/control/backend.rs index a92d6b9..951a58c 100644 --- a/crates/coa-core/src/control/backend.rs +++ b/crates/coa-core/src/control/backend.rs @@ -86,9 +86,15 @@ impl LocalBackend { impl RealmBackend for LocalBackend { fn info(&self, local_id: &str) -> Result { let cfg = settings::load(&self.settings_dir)?.realms.remove(local_id); + let ruleset = self + .access(local_id) + .and_then(|a| a.db()) + .and_then(|db| realm::ruleset_of(&db).map_err(|e| Error::Invalid(e.to_string()))) + .unwrap_or(crate::portable::model::Ruleset::Coa); Ok(RealmInfo { automatic: cfg.as_ref().is_none_or(|c| !c.existing_only), route: cfg.and_then(|c| c.route), + ruleset, }) } diff --git a/crates/coa-core/src/control/join.rs b/crates/coa-core/src/control/join.rs index 2fd3ca8..754817e 100644 --- a/crates/coa-core/src/control/join.rs +++ b/crates/coa-core/src/control/join.rs @@ -413,6 +413,7 @@ impl PlayerControl { &self, ch: &mut PlayerChannel, character_id: Uuid, + ruleset: &str, canonical_revision: u64, payload: &[u8], content_hash: [u8; 32], @@ -423,6 +424,7 @@ impl PlayerControl { let offer = Request::TransferOffer { transfer_id, character_id, + ruleset: ruleset.to_string(), canonical_revision, content_hash: content_hash_str.clone(), total_size: payload.len(), diff --git a/crates/coa-core/src/control/service.rs b/crates/coa-core/src/control/service.rs index 18d1863..36f84d4 100644 --- a/crates/coa-core/src/control/service.rs +++ b/crates/coa-core/src/control/service.rs @@ -26,6 +26,7 @@ pub struct RealmInfo { pub automatic: bool, /// An address a player's game client can reach right now, when the owner has stated one. Not a relay and not discovery. pub route: Option, + pub ruleset: crate::portable::model::Ruleset, } #[derive(Clone, Debug, PartialEq, Eq)] @@ -303,6 +304,7 @@ impl HostService { Request::TransferOffer { transfer_id, character_id, + ruleset, canonical_revision, content_hash, total_size, @@ -311,6 +313,7 @@ impl HostService { player, transfer_id, character_id, + ruleset, canonical_revision, content_hash, total_size, @@ -726,6 +729,7 @@ impl HostService { player: &Uuid, transfer_id: Uuid, character_id: Uuid, + ruleset: String, canonical_revision: u64, content_hash: String, total_size: usize, @@ -741,6 +745,30 @@ impl HostService { ); }; + // 0. Strict ruleset isolation: target realm ruleset must match offer ruleset + let info = match self.backend.info(&self.local_id) { + Ok(i) => i, + Err(e) => return unavailable("reading realm info", &e), + }; + let offer_ruleset = match crate::portable::model::Ruleset::parse(&ruleset) { + Ok(r) => r, + Err(_) => return err(AppError::Incompatible, "Invalid ruleset in transfer offer."), + }; + if offer_ruleset != info.ruleset { + return err( + AppError::Incompatible, + "Character ruleset does not match this realm.", + ); + } + for kind in collections.keys() { + if !kind.starts_with(offer_ruleset.as_str()) { + return err( + AppError::Incompatible, + "Collection kind does not belong to this ruleset.", + ); + } + } + // 1. Ownership check: another player cannot overwrite a character claimed here if let Ok(Some(claim)) = self .store @@ -1083,6 +1111,7 @@ impl HostService { #[cfg(any(test, feature = "testkit"))] pub mod fake { use super::*; + use crate::portable::Ruleset; #[derive(Default)] pub struct FakeRealm { @@ -1141,6 +1170,7 @@ pub mod fake { impl RealmBackend for FakeRealm { fn info(&self, _: &str) -> Result { Ok(RealmInfo { + ruleset: Ruleset::Coa, automatic: *self.automatic.lock().unwrap(), route: self.route.lock().unwrap().clone(), }) @@ -1870,6 +1900,7 @@ mod tests { // 1. Offer let offer = Request::TransferOffer { + ruleset: "coa".into(), transfer_id: tid, character_id: cid, canonical_revision: 1, @@ -1943,6 +1974,7 @@ mod tests { realm.incompatible.lock().unwrap().insert(cid); let offer = Request::TransferOffer { + ruleset: "coa".into(), transfer_id: tid, character_id: cid, canonical_revision: 1, @@ -1982,6 +2014,7 @@ mod tests { let hash = hex::encode(Sha256::digest(&full)); let offer = Request::TransferOffer { + ruleset: "coa".into(), transfer_id: tid, character_id: cid, canonical_revision: 1, @@ -2076,6 +2109,7 @@ mod tests { let hash = hex::encode(Sha256::digest(&payload)); let offer = Request::TransferOffer { + ruleset: "coa".into(), transfer_id: tid, character_id: cid, canonical_revision: 1, @@ -2138,6 +2172,7 @@ mod tests { // Client starts a new transfer for the exact same committed revision: discovers committed state let tid2 = Uuid::now_v7(); let offer2 = Request::TransferOffer { + ruleset: "coa".into(), transfer_id: tid2, character_id: cid, canonical_revision: 1, @@ -2174,6 +2209,7 @@ mod tests { let hash = hex::encode(Sha256::digest(&payload)); let offer = Request::TransferOffer { + ruleset: "coa".into(), transfer_id: tid, character_id: cid, canonical_revision: 1, @@ -2240,6 +2276,7 @@ mod tests { let tid_impostor = Uuid::now_v7(); let impostor_offer = Request::TransferOffer { + ruleset: "coa".into(), transfer_id: tid_impostor, character_id: cid, canonical_revision: 2, @@ -2277,6 +2314,7 @@ mod tests { &p, "K", Request::TransferOffer { + ruleset: "coa".into(), transfer_id: tid1, character_id: cid, canonical_revision: 1, @@ -2328,6 +2366,7 @@ mod tests { &p, "K", Request::TransferOffer { + ruleset: "coa".into(), transfer_id: tid2, character_id: cid, canonical_revision: 2, @@ -2377,4 +2416,54 @@ mod tests { "update, not duplicate import" ); } + + #[test] + fn cross_ruleset_transfer_offers_are_rejected_before_mutation() { + let (realm, s, p, _acc) = claimed_setup(); + let mut session = Session::default(); + let cid = Uuid::now_v7(); + let tid = Uuid::now_v7(); + + // 1. Host is CoA, offer is Wildcard -> Rejected + let wc_offer = Request::TransferOffer { + ruleset: "wildcard".into(), + transfer_id: tid, + character_id: cid, + canonical_revision: 1, + content_hash: "a".repeat(64), + total_size: 100, + collections: BTreeMap::new(), + }; + let r = s.handle(&mut session, &p, "K", wc_offer); + assert!(matches!(r, Response::Error { code: AppError::Incompatible, .. })); + + // 2. Host is CoA, offer is Reborn -> Rejected + let rb_offer = Request::TransferOffer { + ruleset: "reborn".into(), + transfer_id: tid, + character_id: cid, + canonical_revision: 1, + content_hash: "a".repeat(64), + total_size: 100, + collections: BTreeMap::new(), + }; + let r = s.handle(&mut session, &p, "K", rb_offer); + assert!(matches!(r, Response::Error { code: AppError::Incompatible, .. })); + + // 3. Collection kinds for another ruleset -> Rejected + let foreign_coll_offer = Request::TransferOffer { + ruleset: "coa".into(), + transfer_id: tid, + character_id: cid, + canonical_revision: 1, + content_hash: "a".repeat(64), + total_size: 100, + collections: BTreeMap::from([("wildcard:appearance".into(), vec![1, 2, 3])]), + }; + let r = s.handle(&mut session, &p, "K", foreign_coll_offer); + assert!(matches!(r, Response::Error { code: AppError::Incompatible, .. })); + + // Ensure 0 DB imports happened + assert!(realm.imported.lock().unwrap().is_empty()); + } } diff --git a/crates/coa-core/src/portable/error.rs b/crates/coa-core/src/portable/error.rs index dc18243..055f58a 100644 --- a/crates/coa-core/src/portable/error.rs +++ b/crates/coa-core/src/portable/error.rs @@ -64,6 +64,11 @@ pub enum PortableError { RealmRead(String), #[error("the realm database is a {found} realm but a {expected} character was requested")] WrongRealm { expected: String, found: String }, + #[error("ruleset mismatch: character has {character:?}, realm expects {realm:?}")] + RulesetMismatch { + character: super::model::Ruleset, + realm: super::model::Ruleset, + }, #[error("character {character} is already on server {server_id}")] AlreadyOnRealm { diff --git a/crates/coa-core/src/portable/migrations/001_init.sql b/crates/coa-core/src/portable/migrations/001_init.sql index fda742a..332e90f 100644 --- a/crates/coa-core/src/portable/migrations/001_init.sql +++ b/crates/coa-core/src/portable/migrations/001_init.sql @@ -9,7 +9,7 @@ CREATE TABLE profile ( CREATE TABLE character ( character_id TEXT PRIMARY KEY, profile_id TEXT NOT NULL REFERENCES profile(profile_id), - ruleset TEXT NOT NULL CHECK (ruleset IN ('coa', 'wildcard')), + ruleset TEXT NOT NULL CHECK (ruleset IN ('coa', 'wildcard', 'reborn')), name TEXT NOT NULL, race TEXT NOT NULL, class TEXT NOT NULL, diff --git a/crates/coa-core/src/portable/migrations/009_multiruleset.sql b/crates/coa-core/src/portable/migrations/009_multiruleset.sql new file mode 100644 index 0000000..5f2681c --- /dev/null +++ b/crates/coa-core/src/portable/migrations/009_multiruleset.sql @@ -0,0 +1,23 @@ +-- Schema 9: Multi-ruleset partitioned collections and reborn ruleset support. +-- 1. Partition collection table by (profile_id, ruleset, kind) +CREATE TABLE collection_new ( + profile_id TEXT NOT NULL REFERENCES profile(profile_id), + ruleset TEXT NOT NULL CHECK (ruleset IN ('coa', 'wildcard', 'reborn')), + kind TEXT NOT NULL, + collection_revision INTEGER NOT NULL CHECK (collection_revision >= 1), + collection_hash BLOB NOT NULL CHECK (length(collection_hash) = 32), + format_version INTEGER NOT NULL, + item_count INTEGER NOT NULL, + updated_at TEXT NOT NULL, + payload BLOB NOT NULL, + PRIMARY KEY (profile_id, ruleset, kind) +) STRICT; + +INSERT INTO collection_new (profile_id, ruleset, kind, collection_revision, collection_hash, format_version, item_count, updated_at, payload) +SELECT profile_id, 'coa', kind, collection_revision, collection_hash, format_version, item_count, updated_at, payload +FROM collection; + +DROP TABLE collection; +ALTER TABLE collection_new RENAME TO collection; + +CREATE INDEX IF NOT EXISTS character_profile_ruleset ON character(profile_id, ruleset); diff --git a/crates/coa-core/src/portable/model.rs b/crates/coa-core/src/portable/model.rs index 3643128..4bbe8ac 100644 --- a/crates/coa-core/src/portable/model.rs +++ b/crates/coa-core/src/portable/model.rs @@ -59,12 +59,13 @@ pub mod limits { use limits::*; -/// A character belongs to exactly one ruleset for its whole life; CoA and Wildcard never mix. +/// A character belongs to exactly one ruleset for its whole life; rulesets never mix. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum Ruleset { Coa, Wildcard, + Reborn, } impl Ruleset { @@ -72,12 +73,47 @@ impl Ruleset { match self { Ruleset::Coa => "coa", Ruleset::Wildcard => "wildcard", + Ruleset::Reborn => "reborn", + } + } + pub fn display_name(self) -> &'static str { + match self { + Ruleset::Coa => "Conquest of Azeroth", + Ruleset::Wildcard => "Wildcard", + Ruleset::Reborn => "Warcraft Reborn", + } + } + pub fn realm_id(self) -> u32 { + match self { + Ruleset::Coa => 1, + Ruleset::Wildcard => 2, + Ruleset::Reborn => 3, + } + } + pub fn schema(self, kind: &str) -> &'static str { + match (self, kind) { + (_, "auth") => "acore_auth", + (Self::Coa, "characters") => "acore_characters", + (Self::Coa, "world") => "acore_world", + (Self::Wildcard, "characters") => "acore_characters_wildcard", + (Self::Wildcard, "world") => "acore_world_wildcard", + (Self::Reborn, "characters") => "acore_characters_reborn", + (Self::Reborn, "world") => "acore_world_reborn", + _ => "acore_characters", + } + } + pub fn collection_namespace(self) -> &'static str { + match self { + Ruleset::Coa => "coa", + Ruleset::Wildcard => "wildcard", + Ruleset::Reborn => "reborn", } } pub fn parse(s: &str) -> Result { match s { "coa" => Ok(Ruleset::Coa), "wildcard" => Ok(Ruleset::Wildcard), + "reborn" => Ok(Ruleset::Reborn), other => Err(PortableError::Invalid(format!("unknown ruleset {other:?}"))), } } @@ -89,6 +125,46 @@ impl std::fmt::Display for Ruleset { } } +impl From for Ruleset { + fn from(m: crate::realms::Mode) -> Self { + match m { + crate::realms::Mode::Coa => Ruleset::Coa, + crate::realms::Mode::Wildcard => Ruleset::Wildcard, + crate::realms::Mode::Reborn => Ruleset::Reborn, + } + } +} + +impl From for crate::realms::Mode { + fn from(r: Ruleset) -> Self { + match r { + Ruleset::Coa => crate::realms::Mode::Coa, + Ruleset::Wildcard => crate::realms::Mode::Wildcard, + Ruleset::Reborn => crate::realms::Mode::Reborn, + } + } +} + +impl From for Ruleset { + fn from(r: coa_registry_proto::caps::Ruleset) -> Self { + match r { + coa_registry_proto::caps::Ruleset::Coa => Ruleset::Coa, + coa_registry_proto::caps::Ruleset::Wildcard => Ruleset::Wildcard, + coa_registry_proto::caps::Ruleset::Reborn => Ruleset::Reborn, + } + } +} + +impl From for coa_registry_proto::caps::Ruleset { + fn from(r: Ruleset) -> Self { + match r { + Ruleset::Coa => coa_registry_proto::caps::Ruleset::Coa, + Ruleset::Wildcard => coa_registry_proto::caps::Ruleset::Wildcard, + Ruleset::Reborn => coa_registry_proto::caps::Ruleset::Reborn, + } + } +} + /// Binary data as base64 text in the serialised form. #[derive(Clone, PartialEq, Eq, Default)] pub struct Bytes(pub Vec); diff --git a/crates/coa-core/src/portable/realm/collections.rs b/crates/coa-core/src/portable/realm/collections.rs index fb7191e..0873a14 100644 --- a/crates/coa-core/src/portable/realm/collections.rs +++ b/crates/coa-core/src/portable/realm/collections.rs @@ -11,7 +11,6 @@ use crate::db::Db; use super::super::collection::IdSet; use super::super::error::{PortableError, Result}; -use super::super::model::Ruleset; use super::knowledge::{is_bank_vanity_item, RealmKnowledge}; use super::plan::FAIL; use super::ruleset_of; @@ -22,8 +21,12 @@ const CHUNK: usize = 2_000; /// `(table, id column, columns written)` of a collection kind. fn layout(kind: &str) -> Result<(&'static str, &'static str, bool)> { match kind { - "coa:appearance" => Ok(("account_appearance_collection", "appearance_id", true)), - "coa:vanity" => Ok(("account_vanity_collection", "item_id", false)), + "coa:appearance" | "wildcard:appearance" | "reborn:appearance" => { + Ok(("account_appearance_collection", "appearance_id", true)) + } + "coa:vanity" | "wildcard:vanity" | "reborn:vanity" => { + Ok(("account_vanity_collection", "item_id", false)) + } other => Err(PortableError::Invalid(format!( "collection kind {other:?} is not carried" ))), @@ -34,11 +37,12 @@ fn realm_error(e: crate::Error) -> PortableError { PortableError::RealmRead(e.to_string()) } -fn coa_only(db: &Db) -> Result<()> { - if ruleset_of(db)? != Ruleset::Coa { - return Err(PortableError::Invalid( - "collections are carried for CoA realms only (Wildcard transfer is disabled)".into(), - )); +fn check_ruleset(db: &Db, kind: &str) -> Result<()> { + let r = ruleset_of(db)?; + if !kind.starts_with(r.as_str()) { + return Err(PortableError::Invalid(format!( + "collection kind {kind:?} does not belong to realm ruleset {r:?}" + ))); } Ok(()) } @@ -62,7 +66,7 @@ pub fn account_of(db: &Db, local_guid: u32) -> Result> { /// Count, maximum, sum and checksum of the account's rows of this kind: one cheap aggregate over the primary key. pub fn fingerprint(db: &Db, account: u32, kind: &str) -> Result { - coa_only(db)?; + check_ruleset(db, kind)?; let (table, column, _) = layout(kind)?; let out = db .query(&format!("SELECT COUNT(*), IFNULL(MAX(`{column}`), 0), IFNULL(SUM(`{column}`), 0), IFNULL(BIT_XOR(CRC32(`{column}`)), 0) FROM acore_characters.`{table}` WHERE `account_id` = {account}")) @@ -82,7 +86,7 @@ pub fn fingerprint(db: &Db, account: u32, kind: &str) -> Result { /// The ids of the account in this realm, without the bank vanity items. pub fn read_set(db: &Db, account: u32, kind: &str) -> Result { - coa_only(db)?; + check_ruleset(db, kind)?; let (table, column, _) = layout(kind)?; let out = db.query(&format!("SELECT `{column}` FROM acore_characters.`{table}` WHERE `account_id` = {account} ORDER BY `{column}`")).map_err(realm_error)?; let mut ids = Vec::new(); @@ -91,7 +95,7 @@ pub fn read_set(db: &Db, account: u32, kind: &str) -> Result { .trim() .parse() .map_err(|_| PortableError::CorruptSnapshot(format!("{line:?} is not an id")))?; - if kind == "coa:vanity" && is_bank_vanity_item(id) { + if (kind == "coa:vanity" || kind == "wildcard:vanity" || kind == "reborn:vanity") && is_bank_vanity_item(id) { continue; } ids.push(id); @@ -117,10 +121,10 @@ pub fn apply_set( canonical: &IdSet, knowledge: &RealmKnowledge, ) -> Result { - coa_only(db)?; + check_ruleset(db, kind)?; let (table, column, has_source) = layout(kind)?; let known = |id: u32| match kind { - "coa:appearance" => knowledge.knows_appearance(id), + "coa:appearance" | "wildcard:appearance" | "reborn:appearance" => knowledge.knows_appearance(id), _ => knowledge.knows_vanity(id) && !is_bank_vanity_item(id), }; let held = read_set(db, account, kind)?; @@ -130,7 +134,7 @@ pub fn apply_set( .ids() .iter() .copied() - .filter(|id| !(kind == "coa:vanity" && is_bank_vanity_item(*id))) + .filter(|id| !((kind == "coa:vanity" || kind == "wildcard:vanity" || kind == "reborn:vanity") && is_bank_vanity_item(*id))) { if !known(id) { applied.unknown += 1; diff --git a/crates/coa-core/src/portable/realm/live_wardrobe.rs b/crates/coa-core/src/portable/realm/live_wardrobe.rs index a3e5694..b61a2e2 100644 --- a/crates/coa-core/src/portable/realm/live_wardrobe.rs +++ b/crates/coa-core/src/portable/realm/live_wardrobe.rs @@ -168,9 +168,9 @@ fn account_collections_are_read_cheaply_unioned_and_written_without_duplicates_o let (mut store, _) = fresh_store(); let profile = store.default_profile().unwrap(); store - .merge_collection(profile, APPEARANCE, &wardrobe) + .merge_collection(profile, Ruleset::Coa, APPEARANCE, &wardrobe) .unwrap(); - store.merge_collection(profile, VANITY, &vanity).unwrap(); + store.merge_collection(profile, Ruleset::Coa, VANITY, &vanity).unwrap(); let fingerprint_a = fingerprint(&r.a, 5001, APPEARANCE).unwrap(); assert_eq!( fingerprint(&r.a, 5001, APPEARANCE).unwrap(), @@ -331,10 +331,10 @@ fn the_result_comes_back_to_realm_a_unchanged_gameplay_and_complete_collections( reconcile_session(&r.b, &mut store, id, B, true, None).unwrap(); for kind in [APPEARANCE, VANITY] { store - .merge_collection(profile, kind, &read_set(&r.b, ACCOUNT, kind).unwrap()) + .merge_collection(profile, Ruleset::Coa, kind, &read_set(&r.b, ACCOUNT, kind).unwrap()) .unwrap(); store - .merge_collection(profile, kind, &read_set(&r.a, 5001, kind).unwrap()) + .merge_collection(profile, Ruleset::Coa, kind, &read_set(&r.a, 5001, kind).unwrap()) .unwrap(); } @@ -343,7 +343,7 @@ fn the_result_comes_back_to_realm_a_unchanged_gameplay_and_complete_collections( let updated = update_realm_character(&r.a, &mut store, id, "realm-a", &options(a_known.clone())).unwrap(); assert!(updated.updated, "{updated:?}"); - let (_, canonical_wardrobe) = store.collection(profile, APPEARANCE).unwrap().unwrap(); + let (_, canonical_wardrobe) = store.collection(profile, Ruleset::Coa, APPEARANCE).unwrap().unwrap(); let applied = apply_set(&r.a, 5001, APPEARANCE, &canonical_wardrobe, &a_known).unwrap(); assert_eq!(applied.inserted, 1, "only 1300 is new to A"); assert_eq!( diff --git a/crates/coa-core/src/portable/realm/mod.rs b/crates/coa-core/src/portable/realm/mod.rs index 888c0fe..dd36239 100644 --- a/crates/coa-core/src/portable/realm/mod.rs +++ b/crates/coa-core/src/portable/realm/mod.rs @@ -55,7 +55,7 @@ pub fn ruleset_of(db: &Db) -> Result { match db.realm() { Mode::Coa => Ok(Ruleset::Coa), Mode::Wildcard => Ok(Ruleset::Wildcard), - Mode::Reborn => Err(PortableError::Invalid("Portable characters are not supported on Warcraft Reborn realms yet.".into())), + Mode::Reborn => Ok(Ruleset::Reborn), } } diff --git a/crates/coa-core/src/portable/realm/profile.rs b/crates/coa-core/src/portable/realm/profile.rs index bad7386..d754e9d 100644 --- a/crates/coa-core/src/portable/realm/profile.rs +++ b/crates/coa-core/src/portable/realm/profile.rs @@ -14,7 +14,7 @@ use super::super::extension::{ }; use super::super::ids::CharacterId; use super::super::model::PortableCharacter; -use super::super::session::protocol::{COLLECTION_KINDS, PROTOCOL_VERSION}; +use super::super::session::protocol::{collection_kinds, PROTOCOL_VERSION}; use super::super::store::Store; use super::import::ImportOptions; use super::script::SchemaProbe; @@ -103,7 +103,10 @@ pub fn assemble( collection_kinds: if probe.has("account_appearance_collection") && probe.has("account_vanity_collection") { - COLLECTION_KINDS.iter().map(|k| k.to_string()).collect() + collection_kinds(ruleset_of(db)?) + .iter() + .map(|k| k.to_string()) + .collect() } else { Default::default() }, diff --git a/crates/coa-core/src/portable/realm/tests.rs b/crates/coa-core/src/portable/realm/tests.rs index 66581a3..7e605f7 100644 --- a/crates/coa-core/src/portable/realm/tests.rs +++ b/crates/coa-core/src/portable/realm/tests.rs @@ -729,7 +729,7 @@ fn the_wildcard_ruleset_uses_its_own_namespace_and_quarantines_wildcard_state() let wc_db = Db::with_tools(std::path::PathBuf::new(), 1, "root", "x", Mode::Wildcard); let coa_db = Db::with_tools(std::path::PathBuf::new(), 1, "root", "x", Mode::Coa); let reborn_db = Db::with_tools(std::path::PathBuf::new(), 1, "root", "x", Mode::Reborn); - assert!(ruleset_of(&reborn_db).is_err()); + assert_eq!(ruleset_of(&reborn_db).unwrap(), Ruleset::Reborn); assert_eq!( (ruleset_of(&wc_db).unwrap(), ruleset_of(&coa_db).unwrap()), (Ruleset::Wildcard, Ruleset::Coa) diff --git a/crates/coa-core/src/portable/service/access.rs b/crates/coa-core/src/portable/service/access.rs index 1971f7a..9c220ac 100644 --- a/crates/coa-core/src/portable/service/access.rs +++ b/crates/coa-core/src/portable/service/access.rs @@ -112,6 +112,7 @@ pub struct RealmAccess { pub job_dir: PathBuf, pub data_dir: PathBuf, pub game_server_users: Vec, + pub mode: Option, source: Source, } @@ -198,6 +199,7 @@ impl RealmAccess { job_dir: PathBuf::from(&d.job_dir), data_dir: PathBuf::from(&d.data_dir), game_server_users: d.game_server_users.clone(), + mode: None, source: Source::Descriptor(Box::new(d)), }) } @@ -219,6 +221,7 @@ impl RealmAccess { job_dir: root.join("Core").join("PortableImport"), data_dir: root.join("Data"), game_server_users: default_game_users(), + mode: None, source: Source::Install { root: root.to_path_buf(), }, @@ -228,13 +231,19 @@ impl RealmAccess { /// The database with full rights (imports and updates of a stopped realm, reading characters). pub fn db(&self) -> Result { match &self.source { - Source::Install { root } => Db::from_repack(root, Account::Admin), + Source::Install { root } => { + let mut d = Db::from_repack(root, Account::Admin)?; + if let Some(m) = self.mode { + d = d.for_realm(m); + } + Ok(d) + } Source::Descriptor(d) => Ok(Db::with_tools( PathBuf::from(&d.mysql_bin), d.db_port, leak(&d.db_user), d.db_password.expose(), - Mode::Coa, + self.mode.unwrap_or(Mode::Coa), )), } } diff --git a/crates/coa-core/src/portable/service/engine.rs b/crates/coa-core/src/portable/service/engine.rs index fd23e80..2d22fc7 100644 --- a/crates/coa-core/src/portable/service/engine.rs +++ b/crates/coa-core/src/portable/service/engine.rs @@ -136,6 +136,7 @@ struct Saved { #[derive(Debug, Clone)] pub struct ClaimBundle { pub character_id: CharacterId, + pub ruleset: super::super::model::Ruleset, pub payload: Vec, pub content_hash: [u8; 32], pub collections: BTreeMap>, @@ -1438,18 +1439,18 @@ impl PortableService { let model = self.host.load_current(character_id)?; let encoded = super::super::snapshot::encode(&model)?; let mut collections = BTreeMap::new(); - if realm::ruleset_of(&db)? == super::super::model::Ruleset::Coa { - if let Some(account) = realm::collections::account_of(&db, local_guid)? { - for kind in ["coa:appearance", "coa:vanity"] { - if let Ok(set) = realm::collections::read_set(&db, account, kind) { - collections.insert(kind.to_string(), set.ids().to_vec()); - } + let realm_ruleset = realm::ruleset_of(&db)?; + if let Some(account) = realm::collections::account_of(&db, local_guid)? { + for kind in super::super::session::protocol::collection_kinds(realm_ruleset) { + if let Ok(set) = realm::collections::read_set(&db, account, kind) { + collections.insert(kind.to_string(), set.ids().to_vec()); } } } self.publish(); Ok(ClaimBundle { character_id, + ruleset: model.ruleset, payload: encoded.payload, content_hash: encoded.content_hash, collections, @@ -1473,17 +1474,17 @@ impl PortableService { "The character data does not belong to the character that was claimed.", )); } + let ruleset = model.ruleset; if self.owner.character(character_id).is_err() { self.owner .create_character_with_id(self.owner_profile, model, realm_id)?; } for (kind, ids) in collections { - if !matches!(kind.as_str(), "coa:appearance" | "coa:vanity") { - continue; + if kind.starts_with(ruleset.as_str()) { + let set = super::super::collection::IdSet::from_ids(ids.iter().copied())?; + self.owner + .merge_collection(self.owner_profile, ruleset, kind, &set)?; } - let set = super::super::collection::IdSet::from_ids(ids.iter().copied())?; - self.owner - .merge_collection(self.owner_profile, kind, &set)?; } self.publish(); self.state() @@ -1499,13 +1500,14 @@ impl PortableService { let model = self.owner.load_current(cid)?; let encoded = super::super::snapshot::encode(&model)?; let mut collections = BTreeMap::new(); - for kind in ["coa:appearance", "coa:vanity"] { - if let Ok(Some((_, set))) = self.owner.collection(self.owner_profile, kind) { + for kind in super::super::session::protocol::collection_kinds(model.ruleset) { + if let Ok(Some((_, set))) = self.owner.collection(self.owner_profile, model.ruleset, kind) { collections.insert(kind.to_string(), set.ids().to_vec()); } } Ok(ClaimBundle { character_id: cid, + ruleset: model.ruleset, payload: encoded.payload, content_hash: encoded.content_hash, collections, @@ -1591,6 +1593,21 @@ impl PortableService { let opts = self.options(&access, &caps); // Preflight compatibility check before ANY mutation + let db_ruleset = super::super::realm::ruleset_of(&db)?; + if model.ruleset != db_ruleset { + return Err(fail( + "incompatible", + "Character ruleset does not match realm database ruleset.", + )); + } + let caps_ruleset: crate::portable::model::Ruleset = caps.content.ruleset.into(); + if model.ruleset != caps_ruleset { + return Err(fail( + "incompatible", + "Character ruleset does not match realm capability ruleset.", + )); + } + let ops = [Operation::OnlineImport, Operation::RuntimeSession]; let report = self.report(&model, &caps, &opts, &ops, true); if verdict_of(report.verdict()) == Verdict::Incompatible { @@ -1606,9 +1623,9 @@ impl PortableService { // Monotonic union of collections for (kind, ids) in ¶ms.collections { - if matches!(kind.as_str(), "coa:appearance" | "coa:vanity") { + if kind.starts_with(model.ruleset.as_str()) { if let Ok(set) = super::super::collection::IdSet::from_ids(ids.iter().copied()) { - let _ = self.host.merge_collection(self.host_profile, kind, &set); + let _ = self.host.merge_collection(self.host_profile, model.ruleset, kind, &set); } } } @@ -1625,6 +1642,7 @@ impl PortableService { ); let offer = super::super::session::protocol::SessionOffer { protocol_version: super::super::session::protocol::PROTOCOL_VERSION, + ruleset: model.ruleset, session_id, character_id: cid, server_id: realm_id.to_string(), diff --git a/crates/coa-core/src/portable/session/collection_tests.rs b/crates/coa-core/src/portable/session/collection_tests.rs index 5710606..99fd30e 100644 --- a/crates/coa-core/src/portable/session/collection_tests.rs +++ b/crates/coa-core/src/portable/session/collection_tests.rs @@ -7,7 +7,7 @@ use super::*; use crate::portable::collection::IdSet; use crate::portable::fixtures::geared_level_eighty; use crate::portable::ids::{CharacterId, SessionId}; -use crate::portable::model::PortableCharacter; +use crate::portable::model::{PortableCharacter, Ruleset}; use crate::portable::realm::knowledge::RealmKnowledge; use crate::portable::store::Store; @@ -328,10 +328,10 @@ fn a_realm_that_lacks_an_unlock_never_removes_it_and_gets_what_it_knows_back() { // the Owner already holds a big wardrobe from other realms let profile = owner.default_profile().unwrap(); owner - .merge_collection(profile, APPEARANCE, &ids(1..=500)) + .merge_collection(profile, Ruleset::Coa, APPEARANCE, &ids(1..=500)) .unwrap(); owner - .merge_collection(profile, VANITY, &ids(1000..=1010)) + .merge_collection(profile, Ruleset::Coa, VANITY, &ids(1000..=1010)) .unwrap(); // this realm knows only part of it and holds only a few realm.knowledge = knows(ids(1..=300), ids(1000..=1005)); @@ -344,7 +344,7 @@ fn a_realm_that_lacks_an_unlock_never_removes_it_and_gets_what_it_knows_back() { // the Owner unioned the realm's ids (700 included: the realm showed it) and kept everything else let appearance_ack = acks.iter().find(|a| a.kind == APPEARANCE).unwrap(); assert_eq!(appearance_ack.outcome, CollectionOutcome::Applied); - let (_, canonical) = o.store().collection(profile, APPEARANCE).unwrap().unwrap(); + let (_, canonical) = o.store().collection(profile, Ruleset::Coa, APPEARANCE).unwrap().unwrap(); assert_eq!(canonical.len(), 501); assert!( canonical.contains(700) && canonical.contains(1) && canonical.contains(500), @@ -371,12 +371,12 @@ fn an_account_with_unlocks_arrives_on_a_second_realm_from_the_owners_state_alone let mut owner = Store::open_in_memory().unwrap(); let profile = owner.default_profile().unwrap(); owner - .merge_collection(profile, APPEARANCE, &ids(1..=40)) + .merge_collection(profile, Ruleset::Coa, APPEARANCE, &ids(1..=40)) .unwrap(); owner - .merge_collection(profile, VANITY, &ids(50..=60)) + .merge_collection(profile, Ruleset::Coa, VANITY, &ids(50..=60)) .unwrap(); - let states = OwnerService::new(&mut owner).collection_states().unwrap(); + let states = OwnerService::new(&mut owner).collection_states(Ruleset::Coa).unwrap(); assert_eq!(states.len(), 2); let mut host = Store::open_in_memory().unwrap(); @@ -416,7 +416,7 @@ fn hostile_or_broken_collection_messages_change_nothing() { let profile = owner.default_profile().unwrap(); let mut o = OwnerService::new(&mut owner); let good = - collection_to_json(&CollectionObserved::new(SERVER, APPEARANCE, &ids(1..=10)).unwrap()) + collection_to_json(&CollectionObserved::new(SERVER, Ruleset::Coa, APPEARANCE, &ids(1..=10)).unwrap()) .unwrap(); assert_eq!( o.handle_collection(&good).unwrap().outcome, @@ -424,7 +424,7 @@ fn hostile_or_broken_collection_messages_change_nothing() { ); let state_of = |o: &OwnerService| { o.store() - .collection_info(profile, APPEARANCE) + .collection_info(profile, Ruleset::Coa, APPEARANCE) .unwrap() .unwrap() }; @@ -555,7 +555,7 @@ fn ten_thousand_and_fifty_thousand_ids_stay_cheap() { assert_eq!(realm.full_reads, reads); let stored = o .store() - .collection_info(profile, APPEARANCE) + .collection_info(profile, Ruleset::Coa, APPEARANCE) .unwrap() .unwrap(); assert_eq!(stored.count, count as usize); @@ -565,7 +565,7 @@ fn ten_thousand_and_fifty_thousand_ids_stay_cheap() { let mut empty_realm = FakeRealm::new(GUID); empty_realm.knowledge = realm.knowledge.clone(); let state = o - .collection_states() + .collection_states(Ruleset::Coa) .unwrap() .into_iter() .find(|s| s.kind == APPEARANCE) @@ -627,7 +627,7 @@ fn a_lost_acknowledgement_resends_the_same_set_and_the_owner_counts_it_once() { .any(|p| p.kind == APPEARANCE)); assert_eq!( o.store() - .collection_info(profile, APPEARANCE) + .collection_info(profile, Ruleset::Coa, APPEARANCE) .unwrap() .unwrap() .revision, diff --git a/crates/coa-core/src/portable/session/host.rs b/crates/coa-core/src/portable/session/host.rs index 672bdaf..fb0a81f 100644 --- a/crates/coa-core/src/portable/session/host.rs +++ b/crates/coa-core/src/portable/session/host.rs @@ -176,6 +176,12 @@ impl<'a> HostService<'a> { found: model.character_id, }); } + if offer.ruleset != model.ruleset { + return Err(PortableError::RulesetMismatch { + character: model.ruleset, + realm: offer.ruleset, + }); + } self.store .host_install_copy(profile, &model, offer.canonical_revision, "owner")?; self.store.host_prepare_session(offer, &model) @@ -606,8 +612,9 @@ impl<'a> HostService<'a> { let Some(account) = bridge.account_of(guid)? else { continue; }; - for kind in COLLECTION_KINDS { - self.observe_collection(bridge, account, kind, now_secs, events)?; + let character = self.store.character(s.character_id)?; + for kind in collection_kinds(character.ruleset) { + self.observe_collection(bridge, account, character.ruleset, kind, now_secs, events)?; } } Ok(()) @@ -619,6 +626,7 @@ impl<'a> HostService<'a> { &mut self, bridge: &mut dyn RealmBridge, account: u32, + ruleset: crate::portable::model::Ruleset, kind: &str, now_secs: u64, events: &mut Vec, @@ -644,7 +652,7 @@ impl<'a> HostService<'a> { )?; return Ok(()); } - let bytes = collection_to_json(&CollectionObserved::new(&self.server_id, kind, &set)?)?; + let bytes = collection_to_json(&CollectionObserved::new(&self.server_id, ruleset, kind, &set)?)?; self.store.host_collection_observe( &self.server_id, account, @@ -674,7 +682,7 @@ impl<'a> HostService<'a> { account: u32, ack: &CollectionAck, ) -> Result> { - if !carried_kind(&ack.kind) { + if !carried_kind_for(&ack.kind, ack.ruleset) { return Err(PortableError::Invalid( "the acknowledgement is for a kind that is not carried".into(), )); @@ -742,7 +750,7 @@ impl<'a> HostService<'a> { account: u32, state: &CollectionState, ) -> Result> { - if !carried_kind(&state.kind) { + if !carried_kind_for(&state.kind, state.ruleset) { return Err(PortableError::Invalid( "the collection kind is not carried".into(), )); diff --git a/crates/coa-core/src/portable/session/owner.rs b/crates/coa-core/src/portable/session/owner.rs index 72629aa..69783d0 100644 --- a/crates/coa-core/src/portable/session/owner.rs +++ b/crates/coa-core/src/portable/session/owner.rs @@ -49,10 +49,12 @@ impl<'a> OwnerService<'a> { pub fn handle_collection(&mut self, bytes: &[u8]) -> Result { let msg: CollectionObserved = collection_from_json(bytes)?; let profile = self.store.default_profile()?; + let ruleset = msg.ruleset; let rejected = |store: &Store, reason: &str| -> Result { - let info = store.collection_info(profile, &msg.kind).ok().flatten(); + let info = store.collection_info(profile, ruleset, &msg.kind).ok().flatten(); Ok(CollectionAck { protocol_version: PROTOCOL_VERSION, + ruleset, kind: msg.kind.clone(), outcome: CollectionOutcome::Rejected(reason.to_string()), collection_revision: info.as_ref().map_or(0, |i| i.revision), @@ -60,17 +62,17 @@ impl<'a> OwnerService<'a> { canonical: None, }) }; - if !carried_kind(&msg.kind) { - return rejected(self.store, "this collection kind is not carried"); + if !carried_kind_for(&msg.kind, ruleset) { + return rejected(self.store, "this collection kind is not carried for this ruleset"); } let observed = match msg.set.open(&msg.kind) { Ok(set) => set, Err(e) => return rejected(self.store, &e.to_string()), }; - let merge = self.store.merge_collection(profile, &msg.kind, &observed)?; + let merge = self.store.merge_collection(profile, ruleset, &msg.kind, &observed)?; let (info, canonical) = self .store - .collection(profile, &msg.kind)? + .collection(profile, ruleset, &msg.kind)? .map(|(i, s)| (Some(i), s)) .unwrap_or((None, IdSet::new())); let canonical_state = match ( @@ -78,12 +80,13 @@ impl<'a> OwnerService<'a> { observed.count_new(&canonical) == 0 && canonical.count_new(&observed) == 0, ) { (Some(info), false) => { - Some(CollectionState::new(&msg.kind, info.revision, &canonical)?) + Some(CollectionState::new(ruleset, &msg.kind, info.revision, &canonical)?) } _ => None, }; Ok(CollectionAck { protocol_version: PROTOCOL_VERSION, + ruleset, kind: msg.kind, outcome: if merge.changed { CollectionOutcome::Applied @@ -97,12 +100,12 @@ impl<'a> OwnerService<'a> { } /// The canonical collections as messages (for a realm that has none of them yet, or a new one). - pub fn collection_states(&mut self) -> Result> { + pub fn collection_states(&mut self, ruleset: crate::portable::model::Ruleset) -> Result> { let profile = self.store.default_profile()?; let mut out = Vec::new(); - for kind in COLLECTION_KINDS { - if let Some((info, set)) = self.store.collection(profile, kind)? { - out.push(CollectionState::new(kind, info.revision, &set)?); + for kind in collection_kinds(ruleset) { + if let Some((info, set)) = self.store.collection(profile, ruleset, kind)? { + out.push(CollectionState::new(ruleset, kind, info.revision, &set)?); } } Ok(out) diff --git a/crates/coa-core/src/portable/session/profile_tests.rs b/crates/coa-core/src/portable/session/profile_tests.rs index b50fd4f..3f8fa48 100644 --- a/crates/coa-core/src/portable/session/profile_tests.rs +++ b/crates/coa-core/src/portable/session/profile_tests.rs @@ -128,7 +128,7 @@ fn a_changed_content_profile_makes_the_realm_report_its_collections_again_and_re } = rig(|_| {}); let profile = owner.default_profile().unwrap(); owner - .merge_collection(profile, APPEARANCE, &ids(1..=500)) + .merge_collection(profile, Ruleset::Coa, APPEARANCE, &ids(1..=500)) .unwrap(); // the realm's client data knows 1..=300 of the canonical 500 realm.knowledge = RealmKnowledge::new(ids(1..=300), IdSet::new()); @@ -186,7 +186,7 @@ fn a_changed_content_profile_makes_the_realm_report_its_collections_again_and_re ); assert_eq!( o.store() - .collection(profile, APPEARANCE) + .collection(profile, Ruleset::Coa, APPEARANCE) .unwrap() .unwrap() .1 diff --git a/crates/coa-core/src/portable/session/protocol.rs b/crates/coa-core/src/portable/session/protocol.rs index d36407c..2453385 100644 --- a/crates/coa-core/src/portable/session/protocol.rs +++ b/crates/coa-core/src/portable/session/protocol.rs @@ -21,6 +21,12 @@ pub const PROTOCOL_VERSION: u32 = 2; pub const MAX_MESSAGE_BYTES: usize = MAX_COMPRESSED_BYTES * 4 / 3 + 64 * 1024; /// The most item/pet ids an acknowledgement lists. pub const MAX_ACK_IDS: usize = 20_000; +/// The largest serialized collection message accepted. +pub const MAX_COLLECTION_MESSAGE_BYTES: usize = 1024 * 1024; + +fn default_session_ruleset() -> super::super::model::Ruleset { + super::super::model::Ruleset::Coa +} /// A sealed snapshot: the hash of the canonical JSON and the compressed bytes. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] @@ -79,6 +85,8 @@ impl Envelope { #[serde(deny_unknown_fields)] pub struct SessionOffer { pub protocol_version: u32, + #[serde(default = "default_session_ruleset")] + pub ruleset: super::super::model::Ruleset, pub session_id: SessionId, pub character_id: CharacterId, pub server_id: String, @@ -123,6 +131,8 @@ impl SessionProgression { #[serde(deny_unknown_fields)] pub struct PortableSessionStarted { pub protocol_version: u32, + #[serde(default = "default_session_ruleset")] + pub ruleset: super::super::model::Ruleset, pub session_id: SessionId, pub character_id: CharacterId, pub server_id: String, @@ -139,6 +149,8 @@ pub struct PortableSessionStarted { #[serde(deny_unknown_fields)] pub struct PortableCheckpoint { pub protocol_version: u32, + #[serde(default = "default_session_ruleset")] + pub ruleset: super::super::model::Ruleset, pub session_id: SessionId, pub character_id: CharacterId, pub server_id: String, @@ -188,6 +200,8 @@ pub struct NextSession { #[serde(deny_unknown_fields)] pub struct OwnerAck { pub protocol_version: u32, + #[serde(default = "default_session_ruleset")] + pub ruleset: super::super::model::Ruleset, pub session_id: SessionId, /// 0 acknowledges `PortableSessionStarted`. pub sequence: u64, @@ -250,16 +264,17 @@ impl PortableSessionStarted { if let Some(p) = &progression { p.validate()?; } - let b0 = Envelope::seal(b0)?; + let sealed_b0 = Envelope::seal(b0)?; Ok(Self { protocol_version: PROTOCOL_VERSION, + ruleset: b0.ruleset, session_id, character_id, server_id: server_id.to_string(), base_canonical_revision, baseline_generation, - content_hash: b0.content_hash.clone(), - b0, + content_hash: sealed_b0.content_hash.clone(), + b0: sealed_b0, progression, }) } @@ -279,6 +294,7 @@ impl PortableCheckpoint { let realm_snapshot = Envelope::seal(b1)?; Ok(Self { protocol_version: PROTOCOL_VERSION, + ruleset: b1.ruleset, session_id, character_id, server_id: server_id.to_string(), @@ -300,15 +316,32 @@ impl PortableCheckpoint { use super::super::collection::{valid_kind, IdSet, MAX_ENCODED_BYTES}; -/// The collection kinds the v1 protocol carries. -pub const COLLECTION_KINDS: [&str; 2] = ["coa:appearance", "coa:vanity"]; -/// A collection message carries at most one encoded set (base64: 4/3) plus a little structure. -pub const MAX_COLLECTION_MESSAGE_BYTES: usize = MAX_ENCODED_BYTES * 4 / 3 + 64 * 1024; +/// The collection kinds the protocol carries. +pub const COLLECTION_KINDS: [&str; 6] = [ + "coa:appearance", + "coa:vanity", + "wildcard:appearance", + "wildcard:vanity", + "reborn:appearance", + "reborn:vanity", +]; + +pub fn collection_kinds(ruleset: super::super::model::Ruleset) -> &'static [&'static str] { + match ruleset { + super::super::model::Ruleset::Coa => &["coa:appearance", "coa:vanity"], + super::super::model::Ruleset::Wildcard => &["wildcard:appearance", "wildcard:vanity"], + super::super::model::Ruleset::Reborn => &["reborn:appearance", "reborn:vanity"], + } +} pub fn carried_kind(kind: &str) -> bool { valid_kind(kind) && COLLECTION_KINDS.contains(&kind) } +pub fn carried_kind_for(kind: &str, ruleset: super::super::model::Ruleset) -> bool { + valid_kind(kind) && collection_kinds(ruleset).contains(&kind) +} + /// A compact id set as it travels: hash of the kind and content, number of ids, base64 of [`IdSet::encode`]. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] @@ -365,6 +398,8 @@ impl CompactSet { #[serde(deny_unknown_fields)] pub struct CollectionObserved { pub protocol_version: u32, + #[serde(default = "default_session_ruleset")] + pub ruleset: super::super::model::Ruleset, pub server_id: String, pub kind: String, pub set: CompactSet, @@ -375,6 +410,8 @@ pub struct CollectionObserved { #[serde(deny_unknown_fields)] pub struct CollectionState { pub protocol_version: u32, + #[serde(default = "default_session_ruleset")] + pub ruleset: super::super::model::Ruleset, pub kind: String, pub collection_revision: u64, pub set: CompactSet, @@ -400,6 +437,8 @@ pub enum CollectionOutcome { #[serde(deny_unknown_fields)] pub struct CollectionAck { pub protocol_version: u32, + #[serde(default = "default_session_ruleset")] + pub ruleset: super::super::model::Ruleset, pub kind: String, pub outcome: CollectionOutcome, pub collection_revision: u64, @@ -440,14 +479,15 @@ pub fn collection_from_json(bytes: &[u8]) -> Result { } impl CollectionObserved { - pub fn new(server_id: &str, kind: &str, set: &IdSet) -> Result { - if !carried_kind(kind) { + pub fn new(server_id: &str, ruleset: super::super::model::Ruleset, kind: &str, set: &IdSet) -> Result { + if !carried_kind_for(kind, ruleset) { return Err(PortableError::Invalid(format!( - "collection kind {kind:?} is not carried" + "collection kind {kind:?} is not carried for {ruleset:?}" ))); } Ok(Self { protocol_version: PROTOCOL_VERSION, + ruleset, server_id: server_id.to_string(), kind: kind.to_string(), set: CompactSet::seal(kind, set)?, @@ -456,9 +496,10 @@ impl CollectionObserved { } impl CollectionState { - pub fn new(kind: &str, revision: u64, set: &IdSet) -> Result { + pub fn new(ruleset: super::super::model::Ruleset, kind: &str, revision: u64, set: &IdSet) -> Result { Ok(Self { protocol_version: PROTOCOL_VERSION, + ruleset, kind: kind.to_string(), collection_revision: revision, set: CompactSet::seal(kind, set)?, diff --git a/crates/coa-core/src/portable/store.rs b/crates/coa-core/src/portable/store.rs index 0309da7..38e160a 100644 --- a/crates/coa-core/src/portable/store.rs +++ b/crates/coa-core/src/portable/store.rs @@ -27,6 +27,7 @@ const MIGRATIONS: &[&str] = &[ include_str!("migrations/006_collections.sql"), include_str!("migrations/007_capabilities.sql"), include_str!("migrations/008_projection.sql"), + include_str!("migrations/009_multiruleset.sql"), ]; pub const DEFAULT_HISTORY_KEEP: u32 = 20; @@ -173,12 +174,12 @@ impl Store { } fn init(conn: Connection) -> Result { - conn.pragma_update(None, "foreign_keys", true)?; conn.busy_timeout(std::time::Duration::from_secs(5))?; let _ = conn.pragma_update(None, "journal_mode", "WAL"); let _ = conn.pragma_update(None, "synchronous", "NORMAL"); let mut store = Store { conn }; store.migrate()?; + store.conn.pragma_update(None, "foreign_keys", true)?; Ok(store) } @@ -328,6 +329,23 @@ impl Store { read_character(&self.conn, id) } + pub fn get_character( + &self, + id: CharacterId, + expected_ruleset: Option, + ) -> Result { + let rec = read_character(&self.conn, id)?; + if let Some(expected) = expected_ruleset { + if rec.ruleset != expected { + return Err(PortableError::RulesetMismatch { + character: rec.ruleset, + realm: expected, + }); + } + } + Ok(rec) + } + pub fn list_characters(&self, profile: ProfileId) -> Result> { let mut stmt = self.conn.prepare( "SELECT character_id FROM character WHERE profile_id = ?1 ORDER BY character_id", @@ -340,6 +358,22 @@ impl Store { .collect() } + pub fn list_characters_by_ruleset( + &self, + profile: ProfileId, + ruleset: Ruleset, + ) -> Result> { + let mut stmt = self.conn.prepare( + "SELECT character_id FROM character WHERE profile_id = ?1 AND ruleset = ?2 ORDER BY character_id", + )?; + let ids: Vec = stmt + .query_map(params![profile.to_string(), ruleset.as_str()], |r| r.get(0))? + .collect::>()?; + ids.iter() + .map(|text| read_character(&self.conn, text.parse()?)) + .collect() + } + /// Every character of every profile (an overview for tools; normally the UI lists one profile). pub fn list_characters_all(&self) -> Result> { let mut stmt = self @@ -663,6 +697,7 @@ impl Store { pub fn merge_collection( &mut self, profile: ProfileId, + ruleset: Ruleset, kind: &str, incoming: &IdSet, ) -> Result { @@ -682,7 +717,7 @@ impl Store { "profile {profile} does not exist" ))); } - let stored = read_collection(&tx, profile, kind)?; + let stored = read_collection(&tx, profile, ruleset, kind)?; let (current_set, revision) = match &stored { Some((info, set)) => (set.clone(), info.revision), None => (IdSet::new(), 0), @@ -701,11 +736,11 @@ impl Store { let payload = merged.encode(); let at = now(); tx.execute( - "INSERT INTO collection(profile_id, kind, collection_revision, collection_hash, format_version, item_count, updated_at, payload) - VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8) - ON CONFLICT(profile_id, kind) DO UPDATE SET collection_revision = excluded.collection_revision, collection_hash = excluded.collection_hash, + "INSERT INTO collection(profile_id, ruleset, kind, collection_revision, collection_hash, format_version, item_count, updated_at, payload) + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9) + ON CONFLICT(profile_id, ruleset, kind) DO UPDATE SET collection_revision = excluded.collection_revision, collection_hash = excluded.collection_hash, format_version = excluded.format_version, item_count = excluded.item_count, updated_at = excluded.updated_at, payload = excluded.payload", - params![profile.to_string(), kind, (revision + 1) as i64, hash.as_slice(), PORTABLE_COLLECTION_FORMAT_VERSION, merged.len() as i64, at, payload], + params![profile.to_string(), ruleset.as_str(), kind, (revision + 1) as i64, hash.as_slice(), PORTABLE_COLLECTION_FORMAT_VERSION, merged.len() as i64, at, payload], )?; tx.commit()?; Ok(CollectionMerge { @@ -725,13 +760,14 @@ impl Store { pub fn collection_info( &self, profile: ProfileId, + ruleset: Ruleset, kind: &str, ) -> Result> { let row = self .conn .query_row( - "SELECT collection_revision, collection_hash, item_count, updated_at FROM collection WHERE profile_id = ?1 AND kind = ?2", - params![profile.to_string(), kind], + "SELECT collection_revision, collection_hash, item_count, updated_at FROM collection WHERE profile_id = ?1 AND ruleset = ?2 AND kind = ?3", + params![profile.to_string(), ruleset.as_str(), kind], |r| Ok((r.get::<_, i64>(0)?, r.get::<_, Vec>(1)?, r.get::<_, i64>(2)?, r.get::<_, String>(3)?)), ) .optional()?; @@ -750,9 +786,41 @@ impl Store { pub fn collection( &self, profile: ProfileId, + ruleset: Ruleset, kind: &str, ) -> Result> { - read_collection(&self.conn, profile, kind) + read_collection(&self.conn, profile, ruleset, kind) + } + + pub fn list_collections( + &self, + profile: ProfileId, + ruleset: Ruleset, + ) -> Result> { + let mut stmt = self.conn.prepare( + "SELECT kind, collection_revision, collection_hash, item_count, updated_at FROM collection WHERE profile_id = ?1 AND ruleset = ?2 ORDER BY kind", + )?; + let rows = stmt.query_map(params![profile.to_string(), ruleset.as_str()], |r| { + Ok(( + r.get::<_, String>(0)?, + r.get::<_, i64>(1)?, + r.get::<_, Vec>(2)?, + r.get::<_, i64>(3)?, + r.get::<_, String>(4)?, + )) + })?; + let mut out = Vec::new(); + for row in rows { + let (kind, revision, hash, count, updated_at) = row?; + out.push(CollectionInfo { + kind, + revision: revision as u64, + hash: hash_from_blob(hash)?, + count: count as usize, + updated_at, + }); + } + Ok(out) } /// Rewrite the current revision exactly as format 1 stored it (the stores of Phases 1-5 hold such snapshots). Tests only. @@ -776,12 +844,13 @@ impl Store { fn read_collection( conn: &Connection, profile: ProfileId, + ruleset: Ruleset, kind: &str, ) -> Result> { let row = conn .query_row( - "SELECT collection_revision, collection_hash, item_count, updated_at, payload FROM collection WHERE profile_id = ?1 AND kind = ?2", - params![profile.to_string(), kind], + "SELECT collection_revision, collection_hash, item_count, updated_at, payload FROM collection WHERE profile_id = ?1 AND ruleset = ?2 AND kind = ?3", + params![profile.to_string(), ruleset.as_str(), kind], |r| Ok((r.get::<_, i64>(0)?, r.get::<_, Vec>(1)?, r.get::<_, i64>(2)?, r.get::<_, String>(3)?, r.get::<_, Vec>(4)?)), ) .optional()?; diff --git a/crates/coa-core/src/portable/store/owner.rs b/crates/coa-core/src/portable/store/owner.rs index 11e4a0e..713eb35 100644 --- a/crates/coa-core/src/portable/store/owner.rs +++ b/crates/coa-core/src/portable/store/owner.rs @@ -104,6 +104,7 @@ fn head_hash(conn: &Connection, id: CharacterId, revision: u64) -> Result<[u8; 3 } fn ack( + ruleset: Ruleset, session: SessionId, sequence: u64, outcome: AckOutcome, @@ -112,6 +113,7 @@ fn ack( ) -> OwnerAck { OwnerAck { protocol_version: PROTOCOL_VERSION, + ruleset, session_id: session, sequence, outcome, @@ -136,9 +138,10 @@ fn owned_ids( (items, pets) } -fn offer_from_row(row: &OwnerRow) -> SessionOffer { +fn offer_from_row(row: &OwnerRow, ruleset: Ruleset) -> SessionOffer { SessionOffer { protocol_version: PROTOCOL_VERSION, + ruleset, session_id: row.session_id, character_id: row.character_id, server_id: row.server_id.clone(), @@ -163,6 +166,7 @@ fn open_offer(tx: &Transaction<'_>, id: CharacterId, server_id: &str) -> Result< )?; Ok(offer_from_row( &read_owner_row(tx, session)?.expect("just inserted"), + record.ruleset, )) } @@ -186,7 +190,7 @@ impl Store { return Err(PortableError::SessionOpen); } if row.c0_revision == record.revision { - return Ok(offer_from_row(&row)); + return Ok(offer_from_row(&row, record.ruleset)); } tx.execute("UPDATE owner_session SET state = 'superseded', updated_at = ?2 WHERE session_id = ?1", params![live, now()])?; } @@ -200,6 +204,7 @@ impl Store { let tx = self.write_tx()?; let Some(row) = read_owner_row(&tx, msg.session_id)? else { return Ok(ack( + msg.ruleset, msg.session_id, 0, AckOutcome::Rejected("unknown session".into()), @@ -207,9 +212,11 @@ impl Store { [0; 32], )); }; + let record = read_character(&tx, row.character_id)?; let current_hash = head_hash(&tx, row.character_id, row.head_revision)?; let reject = |why: &str| { ack( + record.ruleset, msg.session_id, 0, AckOutcome::Rejected(why.into()), @@ -217,6 +224,9 @@ impl Store { current_hash, ) }; + if msg.ruleset != record.ruleset { + return Ok(reject("the message ruleset does not match the character")); + } if msg.character_id != row.character_id || msg.server_id != row.server_id { return Ok(reject("the message does not belong to this session")); } @@ -237,6 +247,7 @@ impl Store { && row.progression == msg.progression { let mut a = ack( + record.ruleset, msg.session_id, 0, AckOutcome::Duplicate, @@ -253,6 +264,7 @@ impl Store { "offered" => {} _ => { return Ok(ack( + record.ruleset, msg.session_id, 0, AckOutcome::StaleSession, @@ -299,6 +311,7 @@ impl Store { )?; tx.commit()?; let mut a = ack( + record.ruleset, msg.session_id, 0, AckOutcome::Applied, @@ -315,6 +328,7 @@ impl Store { let tx = self.write_tx()?; let Some(row) = read_owner_row(&tx, msg.session_id)? else { return Ok(ack( + msg.ruleset, msg.session_id, msg.sequence, AckOutcome::Rejected("unknown session".into()), @@ -325,9 +339,12 @@ impl Store { let record = read_character(&tx, row.character_id)?; let seen_hash = head_hash(&tx, row.character_id, record.revision)?; let outcome = - |o: AckOutcome| ack(msg.session_id, msg.sequence, o, record.revision, seen_hash); + |o: AckOutcome| ack(record.ruleset, msg.session_id, msg.sequence, o, record.revision, seen_hash); let reject = |why: &str| outcome(AckOutcome::Rejected(why.into())); + if msg.ruleset != record.ruleset { + return Ok(reject("the checkpoint ruleset does not match the character")); + } if msg.character_id != row.character_id || msg.server_id != row.server_id { return Ok(reject("the message does not belong to this session")); } @@ -354,6 +371,7 @@ impl Store { } let revision = revision as u64; let mut a = ack( + record.ruleset, msg.session_id, msg.sequence, AckOutcome::Duplicate, @@ -390,6 +408,7 @@ impl Store { tx.execute("UPDATE owner_session SET state = 'superseded', updated_at = ?2 WHERE session_id = ?1", params![msg.session_id.to_string(), now()])?; tx.commit()?; return Ok(ack( + record.ruleset, msg.session_id, msg.sequence, AckOutcome::StaleSession, @@ -457,6 +476,7 @@ impl Store { }; let mut a = ack( + record.ruleset, msg.session_id, msg.sequence, AckOutcome::Applied, diff --git a/crates/coa-core/src/portable/store/tests.rs b/crates/coa-core/src/portable/store/tests.rs index 0170c11..0f6dcb2 100644 --- a/crates/coa-core/src/portable/store/tests.rs +++ b/crates/coa-core/src/portable/store/tests.rs @@ -918,16 +918,17 @@ fn schema_1_item_mappings_survive_the_migration_as_unverified() { fn collection_union_never_removes_and_unchanged_means_no_revision() { let (mut store, profile) = fresh(); let kind = "coa:wardrobe"; - assert!(store.collection(profile, kind).unwrap().is_none()); + let ruleset = Ruleset::Coa; + assert!(store.collection(profile, ruleset, kind).unwrap().is_none()); // nothing stored, nothing incoming: nothing is created let empty = store - .merge_collection(profile, kind, &IdSet::new()) + .merge_collection(profile, ruleset, kind, &IdSet::new()) .unwrap(); assert!(!empty.changed && empty.info.is_none()); let first = store - .merge_collection(profile, kind, &IdSet::from_ids([10, 20, 30]).unwrap()) + .merge_collection(profile, ruleset, kind, &IdSet::from_ids([10, 20, 30]).unwrap()) .unwrap(); assert!(first.changed); assert_eq!(first.added, 3); @@ -936,7 +937,7 @@ fn collection_union_never_removes_and_unchanged_means_no_revision() { // another realm returns a subset: nothing is lost, nothing changes let subset = store - .merge_collection(profile, kind, &IdSet::from_ids([20]).unwrap()) + .merge_collection(profile, ruleset, kind, &IdSet::from_ids([20]).unwrap()) .unwrap(); assert!(!subset.changed); assert_eq!( @@ -945,13 +946,13 @@ fn collection_union_never_removes_and_unchanged_means_no_revision() { "same revision, same hash" ); let same = store - .merge_collection(profile, kind, &IdSet::from_ids([10, 20, 30]).unwrap()) + .merge_collection(profile, ruleset, kind, &IdSet::from_ids([10, 20, 30]).unwrap()) .unwrap(); assert!(!same.changed); // a realm with new unlocks (and without the old ones) only adds let more = store - .merge_collection(profile, kind, &IdSet::from_ids([30, 40, 5]).unwrap()) + .merge_collection(profile, ruleset, kind, &IdSet::from_ids([30, 40, 5]).unwrap()) .unwrap(); assert!(more.changed); assert_eq!(more.added, 2); @@ -959,22 +960,22 @@ fn collection_union_never_removes_and_unchanged_means_no_revision() { assert_eq!((info2.revision, info2.count), (2, 5)); assert_ne!(info2.hash, info1.hash); - let (info, set) = store.collection(profile, kind).unwrap().unwrap(); + let (info, set) = store.collection(profile, ruleset, kind).unwrap().unwrap(); assert_eq!(set.ids(), &[5, 10, 20, 30, 40]); assert_eq!(info, info2); assert_eq!( - store.collection_info(profile, kind).unwrap().unwrap(), + store.collection_info(profile, ruleset, kind).unwrap().unwrap(), info2 ); // kinds are separate collections assert!(store - .collection_info(profile, "coa:vanity") + .collection_info(profile, ruleset, "coa:vanity") .unwrap() .is_none()); assert!( store - .merge_collection(profile, "wardrobe", &IdSet::new()) + .merge_collection(profile, ruleset, "wardrobe", &IdSet::new()) .is_err(), "kinds must be namespaced" ); @@ -990,7 +991,7 @@ fn collections_hold_tens_of_thousands_of_ids_compactly() { ] { let ids: Vec = (0..count).map(|n| n * 7 + (n % 5)).collect(); let set = IdSet::from_ids(ids).unwrap(); - let merge = store.merge_collection(profile, kind, &set).unwrap(); + let merge = store.merge_collection(profile, Ruleset::Coa, kind, &set).unwrap(); assert_eq!(merge.added, count as usize); let stored_bytes: i64 = store .conn @@ -1004,7 +1005,7 @@ fn collections_hold_tens_of_thousands_of_ids_compactly() { stored_bytes < count as i64 * 2 + 16, "{kind}: {count} ids took {stored_bytes} bytes" ); - let (_, back) = store.collection(profile, kind).unwrap().unwrap(); + let (_, back) = store.collection(profile, Ruleset::Coa, kind).unwrap().unwrap(); assert_eq!(back, set); } } @@ -1013,7 +1014,7 @@ fn collections_hold_tens_of_thousands_of_ids_compactly() { fn a_tampered_collection_is_detected() { let (mut store, profile) = fresh(); store - .merge_collection(profile, "coa:vanity", &IdSet::from_ids([1, 2, 3]).unwrap()) + .merge_collection(profile, Ruleset::Coa, "coa:vanity", &IdSet::from_ids([1, 2, 3]).unwrap()) .unwrap(); let forged = IdSet::from_ids([1, 2, 3, 4]).unwrap().encode(); store @@ -1021,7 +1022,7 @@ fn a_tampered_collection_is_detected() { .execute("UPDATE collection SET payload = ?1", [forged]) .unwrap(); assert!(matches!( - store.collection(profile, "coa:vanity"), + store.collection(profile, Ruleset::Coa, "coa:vanity"), Err(PortableError::CorruptSnapshot(_)) )); } diff --git a/crates/coa-core/src/realm_registry/advert.rs b/crates/coa-core/src/realm_registry/advert.rs index 7e1beb3..bbf5f35 100644 --- a/crates/coa-core/src/realm_registry/advert.rs +++ b/crates/coa-core/src/realm_registry/advert.rs @@ -122,22 +122,39 @@ pub fn modules_of(root: &Path) -> Vec { out } -/// The realm a local id names: an installed server (`srv-` or the bare install id) or a prepared descriptor. +/// The realm a local id names: an installed server (`srv-`, `srv-:` or the bare install id) or a prepared descriptor. pub fn find_access( descriptors: &Path, installs: &[(String, PathBuf)], local_id: &str, ) -> Option { + let (base_id, explicit_mode) = if let Some((base, rs)) = local_id.split_once(':') { + let m = match rs { + "coa" => Some(crate::realms::Mode::Coa), + "wildcard" => Some(crate::realms::Mode::Wildcard), + "reborn" => Some(crate::realms::Mode::Reborn), + _ => None, + }; + (base, m) + } else { + (local_id, None) + }; if let Some((id, root)) = installs .iter() - .find(|(id, _)| format!("srv-{id}") == local_id || id == local_id) + .find(|(id, _)| format!("srv-{id}") == base_id || id == base_id) { - return Some(RealmAccess::from_install(id, root)); + let mut access = RealmAccess::from_install(id, root); + if let Some(m) = explicit_mode { + access.id = format!("srv-{id}:{}", m.name()); + access.name = format!("{} — {}", access.name, m.label()); + access.mode = Some(m); + } + return Some(access); } let (found, _) = load_descriptors(descriptors); found .into_iter() - .find(|d| d.id == local_id) + .find(|d| d.id == local_id || d.id == base_id) .and_then(|d| RealmAccess::from_descriptor(d).ok()) } diff --git a/crates/coa-registry-proto/src/browse.rs b/crates/coa-registry-proto/src/browse.rs index 1312ee2..105a1e6 100644 --- a/crates/coa-registry-proto/src/browse.rs +++ b/crates/coa-registry-proto/src/browse.rs @@ -229,7 +229,8 @@ impl ListQuery { q.ruleset = Some(match value.as_str() { "coa" => Ruleset::Coa, "wildcard" => Ruleset::Wildcard, - _ => return invalid("ruleset is coa or wildcard"), + "reborn" => Ruleset::Reborn, + _ => return invalid("ruleset is coa, wildcard or reborn"), }) } "cap_min" => q.cap_min = Some(number("cap_min", &value, 255)?), diff --git a/crates/coa-registry-proto/src/caps.rs b/crates/coa-registry-proto/src/caps.rs index 54cda59..9919e3f 100644 --- a/crates/coa-registry-proto/src/caps.rs +++ b/crates/coa-registry-proto/src/caps.rs @@ -20,11 +20,12 @@ pub const MAX_CATALOG_ENTRIES: usize = 8; const MAX_TOKEN: usize = 64; const MAX_IDENTITY: usize = 128; -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum Ruleset { Coa, Wildcard, + Reborn, } impl Ruleset { @@ -32,6 +33,15 @@ impl Ruleset { match self { Ruleset::Coa => "coa", Ruleset::Wildcard => "wildcard", + Ruleset::Reborn => "reborn", + } + } + + pub fn display_name(self) -> &'static str { + match self { + Ruleset::Coa => "Conquest of Azeroth", + Ruleset::Wildcard => "Wildcard", + Ruleset::Reborn => "Warcraft Reborn", } } } diff --git a/docs/MULTIRULESET_PORTABLE_AUDIT.md b/docs/MULTIRULESET_PORTABLE_AUDIT.md new file mode 100644 index 0000000..5c4567e --- /dev/null +++ b/docs/MULTIRULESET_PORTABLE_AUDIT.md @@ -0,0 +1,132 @@ +# Multi-Ruleset Realms & Portable Characters: Architectural Audit + +This audit evaluates the released **CoA Server Manager v0.7.0/v0.7.1** architecture to support three independent, strictly isolated gameplay rulesets: +1. **Conquest of Azeroth (`coa`)** +2. **Wildcard (`wildcard`)** +3. **Warcraft Reborn (`reborn`)** + +Date: October 2026 +Status: Pre-Implementation Audit Baseline + +--- + +## 1. Executive Summary & Existing Representation + +Current codebase inspection reveals that while `realms::Mode` already defines `Coa`, `Wildcard`, and `Reborn` for local realm profiles and database switching, the **Portable Characters and Public Realm Registry subsystems** were designed almost entirely around `coa`, with experimental/preliminary partial awareness of `wildcard`, and an explicit blocking error for `reborn` (`ruleset_of`: *"Portable characters are not supported on Warcraft Reborn realms yet"*). + +Furthermore, several critical isolation gaps exist across the stack: +- **Registry & Host Identity Conflation:** Local realm publication keys by `srv-` rather than by `(installation_id, ruleset)`. A host running multiple modes (or switching modes) risks mutating or conflating public realm identity. +- **Collection Bucket Shared per Profile:** Canonical collection storage (`collection` table) is keyed by `(profile_id, kind)` with fixed strings like `coa:appearance` and `coa:vanity`. Wildcard and Reborn collections cannot safely share these keys or numeric id sets without risking collision and cross-ruleset leakage. +- **Store Schema Constraints:** SQLite `character` table and PostgreSQL Registry `realm` table enforce `CHECK (ruleset IN ('coa', 'wildcard'))`, which rejects `reborn`. +- **Remote Control & Session Protocols:** `TransferOffer`, `PortableSessionStarted`, `PortableCheckpoint`, and `OwnerAck` messages do not bind `ruleset` in their envelopes, relying solely on character snapshot payload validation or local mapping lookups. +- **Capability Profiles:** `RealmCapabilities` reports and negotiation hardcode expectations around `coa`, blocking other rulesets. + +--- + +## 2. Inventory of Current Subsystem Locations & Representation + +### 2.1 Realm Profiles & Databases (`crates/coa-core/src/realms.rs`, `db.rs`) +| Ruleset / Mode | Realm ID | Character Database | World Database | Auth Database | Configuration Profile | +|---|---|---|---|---|---| +| **CoA** | `1` | `acore_characters` | `acore_world` | `acore_auth` | `Settings/realm-profiles/coa.json` | +| **Wildcard** | `2` | `acore_characters_wildcard` | `acore_world_wildcard` | `acore_auth` | `Settings/realm-profiles/wildcard.json` | +| **Warcraft Reborn** | `3` | `acore_characters_reborn` | `acore_world_reborn` | `acore_auth` | `Settings/realm-profiles/reborn.json` | + +- **Simultaneous Startup Policy:** + - CoA + Wildcard simultaneous is supported via `secondary_world_port` and `secondary_ra_port` (CoA on primary world port 8085, Wildcard on secondary e.g. 8086). + - Warcraft Reborn simultaneous startup is **strictly unsupported** (`s.simultaneous && s.active == Mode::Reborn` returns `Error::Invalid("Simultaneous startup supports CoA and Wildcard only.")`). +- **Worldserver Capability Detection:** + - Executable inspected directly (`Core/worldserver.exe` on Windows repack, `Core/worldserver` on Linux Docker). + - Wildcard detected by byte pattern: `b"Wildcard synergy settings"`. + - Reborn detected by byte pattern: `b"Warcraft Reborn class spells are unavailable"`. + +### 2.2 Ruleset Enumeration & Protocols +- `crates/coa-core/src/realms.rs`: `enum Mode { Coa, Wildcard, Reborn }` +- `crates/coa-core/src/portable/model.rs`: `enum Ruleset { Coa, Wildcard }` *(Lacks `Reborn`)* +- `crates/coa-registry-proto/src/caps.rs`: `enum Ruleset { Coa, Wildcard }` *(Lacks `Reborn`)* +- `services/coa-registry/src/pg.rs`: `ruleset: match ruleset.as_str() { "coa" => Ruleset::Coa, "wildcard" => Ruleset::Wildcard }` *(Lacks `Reborn`)* +- `src/lib/browse.ts`: `export type Ruleset = "coa" | "wildcard";` *(Lacks `reborn`)* + +### 2.3 Public Registry Model & Publication +- `crates/coa-core/src/realm_registry/settings.rs`: `RegistrySettings.realms` is a `BTreeMap`. +- `src/screens/PublishCard.tsx`: Uses `localId = 'srv-' + serverId`. +- **Host vs Published Realm Identity Issue:** + One installation (`InstallMeta.id`) hosting multiple rulesets currently shares `localId = srv-`. If the host switches active realm from CoA to Wildcard, or publishes both under simultaneous mode, `srv-` cannot represent both published realms distinctly. + Each published realm must possess its own distinct local realm identity (`srv--` or `srv-:`), unique `RealmId` (UUIDv7), and independent Ed25519 signing key in `KeyStore`. + +### 2.4 Canonical Portable Storage (`crates/coa-core/src/portable/store.rs`) +- SQLite schema (`%LOCALAPPDATA%\CoAServerManager\portable\portable.db`): + - `character`: `ruleset TEXT NOT NULL CHECK (ruleset IN ('coa', 'wildcard'))` -> Must be updated to allow `'reborn'`. + - `collection`: `PRIMARY KEY (profile_id, kind)` -> Unpartitioned by ruleset! Must become `(profile_id, ruleset, kind)`. + - `character_server_mapping`: `PRIMARY KEY (character_id, server_id), UNIQUE (server_id, local_guid)`. + - `item_mapping`: `PRIMARY KEY (character_id, server_id, portable_item_id)`. + - `pet_mapping`: `PRIMARY KEY (character_id, server_id, portable_pet_id)`. + - `owner_session`: `character_id`, `server_id`, `c0_revision`, `b0_hash`. + - `host_session`: `character_id`, `server_id`, `local_guid`. + +### 2.5 Remote Transfer & Control Protocol (`crates/coa-control-proto/src/app.rs`) +- `Request::TransferOffer`: + `{ transfer_id, character_id, canonical_revision, content_hash, total_size, collections }` + -> **Missing `ruleset`**. An offer must bind `ruleset: Ruleset` so the host can reject before chunk transport or preflight if target realm mismatch occurs. +- `Request::TransferCommit`: + Currently relies on cached transfer metadata. +- `Response::TransferCommitted`: + Returns session parameters. + +### 2.6 Runtime Sessions & Checkpoints (`crates/coa-core/src/portable/session/protocol.rs`) +- `PortableSessionStarted`: `{ protocol_version, session_id, character_id, server_id, base_canonical_revision, baseline_generation, b0, content_hash, progression }` + -> **Missing `ruleset`**. +- `PortableCheckpoint`: `{ protocol_version, session_id, character_id, server_id, base_canonical_revision, sequence, final_checkpoint, realm_snapshot, content_hash, pin }` + -> **Missing `ruleset`**. +- `OwnerAck`: `{ protocol_version, session_id, sequence, outcome, canonical_revision, canonical_hash, owned_items, owned_pets, canonical, next_session, pin }` + -> Must verify ruleset match in owner session state before applying 3-way merge. + +### 2.7 Direct & Relay Routing +- **Direct Ingress Proxy (`crates/coa-core/src/control/direct_ingress.rs`):** + Listens on direct auth and world ports, intercepts `CMD_REALM_LIST` from the Auth server, and rewrites the realm entry address to the public direct world IP and port. When multiple realms are active (simultaneous CoA + Wildcard), each published realm must target its respective local world port (`ports.world` vs `s.secondary_world_port`). +- **Relay Hub & Allocations (`services/coa-relay/`, `crates/coa-core/src/control/relay_link.rs`):** + Relay allocation requests are authenticated by Ed25519 realm key. Allocations bind a short-lived token to an isolated auth/world stream pair. + +--- + +## 3. Strict Isolation Invariants + +The fundamental architectural invariant is: +$$\text{portable\_character.ruleset} == \text{target\_realm.ruleset}$$ + +On mismatch: +1. **Zero DB Mutation:** No rows written to `acore_characters*`, `item_instance`, or modules. +2. **Zero Session Creation:** No `host_session` or `owner_session` record opened or armed. +3. **Zero Mapping Creation:** No entry in `character_server_mapping`, `item_mapping`, or pet mapping. +4. **Zero Collection Merge:** No union into collections of a different ruleset. +5. **Zero Canonical Revision Change:** Canonical revision remains unchanged; reject with explicit mismatch error. +6. **No Implicit Conversion:** Never attempt conversion, level projection across rulesets, or guessing missing rulesets. + +--- + +## 4. Execution Plan & Phasing + +1. **Authoritative RulesetId Abstraction (Section 3):** + - Normalize `RulesetId` / unified enum across `coa-core`, `coa-registry-proto`, `coa-control-proto`, and TypeScript models. + - Values: `coa`, `wildcard`, `reborn`. +2. **Partitioning Collections & Canonical Storage (Sections 8, 11):** + - Add SQLite migration `009_multiruleset_collections.sql` partitioning collections by `(profile_id, ruleset, kind)` and expanding `character` table ruleset constraint to allow `'reborn'`. + - Update `Store` APIs to accept `ruleset: Ruleset` on character operations and collection operations. +3. **Registry & Multi-Realm Publication on One Host (Sections 5, 6, 26):** + - Partition published realm keys: `srv-:`. + - Each published realm receives its own `RealmId`, Ed25519 key, heartbeat, status, and capabilities. + - Registry PostgreSQL migration for `reborn` ruleset check. +4. **Remote Transfer Envelope & Session Binding (Sections 14, 22):** + - Add `ruleset` to `TransferOffer`, `PortableSessionStarted`, `PortableCheckpoint`. + - Enforce 4-way equality: envelope ruleset == payload ruleset == published realm ruleset == host target DB ruleset. +5. **Wildcard Vertical Slice (Section 15):** + - End-to-end testing of Wildcard claiming, transfer, session, checkpoint, and collection partitioning. + - Verify negative cross-ruleset attack scenarios. +6. **Warcraft Reborn Audit & Vertical Slice (Sections 18, 19):** + - Complete `docs/REBORN_PORTABLE_AUDIT.md`. + - Wire Reborn adapter into the unified engine and verify vertical slice. +7. **UI Multi-Ruleset Filtering (Sections 7, 27):** + - Server browser ruleset tabs/filters (`All`, `Conquest of Azeroth`, `Wildcard`, `Warcraft Reborn`). + - Portable character picker filtered by target realm ruleset. +8. **Regression & Cross-Ruleset Attack Test Suite (Section 29):** + - Comprehensive unit and integration attack tests ensuring strict isolation. diff --git a/docs/REBORN_PORTABLE_AUDIT.md b/docs/REBORN_PORTABLE_AUDIT.md new file mode 100644 index 0000000..e170dd6 --- /dev/null +++ b/docs/REBORN_PORTABLE_AUDIT.md @@ -0,0 +1,40 @@ +# Warcraft Reborn Portable Characters Audit + +## 1. Overview & Current State +The master branch codebase already contains foundational support for Warcraft Reborn (`Mode::Reborn`, realm ID `3`, characters DB `acore_characters_reborn`, world DB `acore_world_reborn`, shared auth DB `acore_auth`). +In previous releases (v0.7.0), portable character transfers into Warcraft Reborn were temporarily guarded by: +```rust +// crates/coa-core/src/portable/realm/mod.rs +Mode::Reborn => Err(PortableError::Invalid("Portable characters are not supported on Warcraft Reborn realms yet.".into())), +``` + +## 2. Ruleset Identity & DB Schemas +- **RulesetId / Ruleset**: + - `Ruleset::Reborn` exists in `crates/coa-core/src/portable/model.rs` and `crates/coa-registry-proto/src/caps.rs`. + - Serialized string: `"reborn"`. + - Display name: `"Warcraft Reborn"`. + - Associated Realm ID: `3`. + - Character Database: `acore_characters_reborn`. + - World Database: `acore_world_reborn`. + - Auth Database: `acore_auth` (shared across all modes). +- **Collections**: + - `reborn:appearance` + - `reborn:vanity` + - Partitioned under `(profile_id, 'reborn', kind)` in canonical SQLite store (`portable.db`). + +## 3. Simultaneous Startup & Multiworld Policy +- As verified in `crates/coa-core/src/multiworld.rs` and `crates/coa-core/src/realms.rs`: + - `CoA + Wildcard` simultaneous execution is supported. + - `Reborn` simultaneous execution is explicitly unsupported (`"Simultaneous startup supports CoA and Wildcard only."`). + - This policy is preserved strictly without changes. + +## 4. Enabling Reborn in Portable Architecture +To complete the Reborn vertical slice with full strict isolation: +1. Map `Mode::Reborn => Ok(Ruleset::Reborn)` in `crates/coa-core/src/portable/realm/mod.rs:ruleset_of`. +2. Update tests verifying `ruleset_of(&reborn_db).unwrap() == Ruleset::Reborn`. +3. Verify Reborn claiming, export, import, session runtime, checkpoints, and collection isolation. +4. Verify non-negotiable isolation tests: + - Reborn character -> CoA realm (rejected). + - Reborn character -> Wildcard realm (rejected). + - CoA character -> Reborn realm (rejected). + - Wildcard character -> Reborn realm (rejected). diff --git a/services/coa-registry/migrations/0005_reborn_ruleset.sql b/services/coa-registry/migrations/0005_reborn_ruleset.sql new file mode 100644 index 0000000..2ef6637 --- /dev/null +++ b/services/coa-registry/migrations/0005_reborn_ruleset.sql @@ -0,0 +1,3 @@ +-- Registry schema, migration 5: add 'reborn' to supported rulesets. +ALTER TABLE realms DROP CONSTRAINT IF EXISTS realms_ruleset_check; +ALTER TABLE realms ADD CONSTRAINT realms_ruleset_check CHECK (ruleset IN ('coa', 'wildcard', 'reborn')); diff --git a/services/coa-registry/src/pg.rs b/services/coa-registry/src/pg.rs index e6b6169..67761ba 100644 --- a/services/coa-registry/src/pg.rs +++ b/services/coa-registry/src/pg.rs @@ -14,6 +14,7 @@ const MIGRATIONS: &[(i32, &str, &str)] = &[ (2, "protocol_v2", include_str!("../migrations/0002_protocol_v2.sql")), (3, "browse_indexes", include_str!("../migrations/0003_browse_indexes.sql")), (4, "created_whole_seconds", include_str!("../migrations/0004_created_whole_seconds.sql")), + (5, "reborn_ruleset", include_str!("../migrations/0005_reborn_ruleset.sql")), ]; pub struct PgConfig { @@ -124,6 +125,7 @@ pub(crate) fn to_row(r: &Row) -> StoreResult { ruleset: match ruleset.as_str() { "coa" => Ruleset::Coa, "wildcard" => Ruleset::Wildcard, + "reborn" => Ruleset::Reborn, other => return Err(StoreError::Backend(format!("a stored ruleset is unknown: {other}"))), }, level_cap: level_cap.map(|n| n as u32), @@ -179,6 +181,7 @@ fn summary_from(r: &Row, now: i64, ttl: i64) -> StoreResult { ruleset: match ruleset.as_str() { "coa" => Ruleset::Coa, "wildcard" => Ruleset::Wildcard, + "reborn" => Ruleset::Reborn, other => return Err(StoreError::Backend(format!("a stored ruleset is unknown: {other}"))), }, level_cap: level_cap.map(|n| n as u32), diff --git a/src-tauri/src/control_cmds.rs b/src-tauri/src/control_cmds.rs index 9d73854..274163d 100644 --- a/src-tauri/src/control_cmds.rs +++ b/src-tauri/src/control_cmds.rs @@ -290,6 +290,7 @@ pub(crate) async fn join_realm( .transfer_character( &mut ch, cuuid, + bundle.ruleset.as_str(), 1, &bundle.payload, bundle.content_hash, diff --git a/src/lib/browse.ts b/src/lib/browse.ts index 13cd2b8..b8e1b37 100644 --- a/src/lib/browse.ts +++ b/src/lib/browse.ts @@ -12,7 +12,7 @@ export interface Rates { export interface ModuleEntry { id: string; version: string | null; enabled: boolean } export interface Population { players: number; bots: number; capacity: number | null } export interface AccountProvisioning { automatic: boolean; existing_only: boolean } -export type Ruleset = "coa" | "wildcard"; +export type Ruleset = "coa" | "wildcard" | "reborn"; export interface RealmSummary { realm_id: string; diff --git a/src/screens/BrowsePage.tsx b/src/screens/BrowsePage.tsx index 0688bfa..c08fd32 100644 --- a/src/screens/BrowsePage.tsx +++ b/src/screens/BrowsePage.tsx @@ -50,7 +50,9 @@ function Online({ p }: { p: RealmSummary["population"] }) { } function Mode({ ruleset }: { ruleset: string }) { - return {ruleset === "wildcard" ? "Wildcard" : "CoA"}; + if (ruleset === "wildcard") return Wildcard; + if (ruleset === "reborn") return Warcraft Reborn; + return CoA; } function compactRates(r: RealmSummary["rates"], t: (k: Key, v?: Record) => string): string { @@ -166,7 +168,7 @@ export function BrowsePage() { const { t } = useI18n(); const { status } = useRegistryStatus(5000); const [q, setQ] = useState(""); - const [ruleset, setRuleset] = useState<"" | "coa" | "wildcard">(""); + const [ruleset, setRuleset] = useState<"" | "coa" | "wildcard" | "reborn">(""); const [capMin, setCapMin] = useState(""); const [capMax, setCapMax] = useState(""); const [module, setModule] = useState(""); @@ -247,8 +249,8 @@ export function BrowsePage() {
setQ(e.target.value)} placeholder={t("browse.search")} className="col-span-2 rounded-md border border-line bg-card px-3 py-2 text-sm" /> - setRuleset(e.target.value as "" | "coa" | "wildcard" | "reborn")} className="rounded-md border border-line bg-card px-3 py-2 text-sm"> +
setCapMin(e.target.value.replace(/\D/g, ""))} placeholder={t("browse.capMin")} className="w-full rounded-md border border-line bg-card px-2 py-2" />– setCapMax(e.target.value.replace(/\D/g, ""))} placeholder={t("browse.capMax")} className="w-full rounded-md border border-line bg-card px-2 py-2" />
setCharacter(e.target.value)} className="w-full rounded-md border border-line bg-card px-3 py-2"> - {characters.map((c) => )} - + {matchingCharacters.length === 0 && ( +
+

{t("browse.noCharacter")}

+ {hiddenCount > 0 && ( +

+ {hiddenCount} {hiddenCount === 1 ? "character" : "characters"} from other game modes {hiddenCount === 1 ? "is" : "are"} hidden +

+ )} +
+ )} + {matchingCharacters.length > 0 && <> +
+ + {hiddenCount > 0 && ( +

+ {hiddenCount} {hiddenCount === 1 ? "character" : "characters"} from other game modes {hiddenCount === 1 ? "is" : "are"} hidden +

+ )} +
{preError &&

{preError}

} {pre && chosen &&

{blocked ? t("browse.cannotPlay") : t("browse.canPlay")}

diff --git a/src/screens/PortablePage.tsx b/src/screens/PortablePage.tsx index f7462db..b688013 100644 --- a/src/screens/PortablePage.tsx +++ b/src/screens/PortablePage.tsx @@ -4,6 +4,8 @@ import { AlertTriangle, CheckCircle2, History, Loader2, Plus, ShieldAlert, Sword import { useT, type Key } from "@/i18n"; import { Button } from "@/components/ui/button"; import { Card } from "@/components/ui/card"; +import { RulesetBadge } from "@/components/RulesetBadge"; +import type { Ruleset } from "@/lib/browse"; import { cn } from "@/lib/utils"; import { asPortableError, portable, usePortable, @@ -110,7 +112,10 @@ function PlayDialog({ character, realms, initial, onClose, onChanged }: { charac return
-

{t("portable.play.title", { name: character.name })}

+
+

{t("portable.play.title", { name: character.name })}

+ +
@@ -218,7 +223,10 @@ function HistoryDialog({ character, onClose }: { character: CharacterView; onClo return
-

{t("portable.history.title", { name: character.name })}

+
+

{t("portable.history.title", { name: character.name })}

+ +
{!list && !error && } @@ -240,8 +248,13 @@ export function PortablePage({ onOpenSettings }: { onOpenSettings?: () => void } const [making, setMaking] = useState(false); const [error, setError] = useState(null); const [copied, setCopied] = useState(false); + const [rulesetFilter, setRulesetFilter] = useState<"" | Ruleset>(""); const realms = state?.realms ?? []; const characters = state?.characters ?? []; + const filteredCharacters = useMemo(() => { + if (!rulesetFilter) return characters; + return characters.filter((c) => c.ruleset === rulesetFilter); + }, [characters, rulesetFilter]); const usable = useMemo(() => realms, [realms]); async function addRealm() { @@ -294,14 +307,66 @@ export function PortablePage({ onOpenSettings }: { onOpenSettings?: () => void }
-

{t("portable.characters.title")}

+
+

{t("portable.characters.title")}

+
+ + + + +
+
{characters.length === 0 && {t("portable.characters.none")}} + {characters.length > 0 && filteredCharacters.length === 0 && ( + + No characters match the selected ruleset filter. + + )}
- {characters.map((c) => + {filteredCharacters.map((c) =>
-

{c.name}

+
+

{c.name}

+ +

{c.class_name} · {t("portable.level", { level: c.level })} · {t("portable.revision", { n: c.revision })}

{t("portable.lastSync", { when: when(c.updated_at) })}{c.active_realm ? ` · ${t("portable.activeOn", { realm: c.active_realm })}` : ""}

From a48717340bd99d391ecef195efc5787746ee6a8a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=94=D0=BC=D0=B8=D1=82=D1=80=D0=B8=D0=B9?= Date: Thu, 22 Oct 2026 22:18:28 +0500 Subject: [PATCH 6/6] chore(reborn): MR3.1 semantic audit, i18n localization, and fail-closed cleanup --- crates/coa-core/src/portable/session/host.rs | 18 ++- crates/coa-core/src/portable/session/tests.rs | 14 ++ docs/REBORN_PORTABLE_AUDIT.md | 124 +++++++++++------- docs/WARCRAFT-REBORN.md | 2 +- src/i18n/locales/de.ts | 6 + src/i18n/locales/en.ts | 6 + src/i18n/locales/es.ts | 6 + src/i18n/locales/fr.ts | 6 + src/i18n/locales/ru.ts | 6 + src/i18n/locales/zh.ts | 6 + src/screens/BrowsePage.tsx | 6 +- src/screens/PortablePage.tsx | 4 +- 12 files changed, 140 insertions(+), 64 deletions(-) diff --git a/crates/coa-core/src/portable/session/host.rs b/crates/coa-core/src/portable/session/host.rs index 5030ef8..4bccc22 100644 --- a/crates/coa-core/src/portable/session/host.rs +++ b/crates/coa-core/src/portable/session/host.rs @@ -183,13 +183,17 @@ impl<'a> HostService<'a> { }); } if let Some((_, rs)) = self.server_id.split_once(':') { - if let Ok(host_ruleset) = rs.parse::() { - if offer.ruleset != host_ruleset || model.ruleset != host_ruleset { - return Err(PortableError::RulesetMismatch { - character: model.ruleset, - realm: host_ruleset, - }); - } + let host_ruleset = rs.parse::().map_err(|_| { + PortableError::Invalid(format!( + "malformed or unknown ruleset suffix in server_id: {:?}", + self.server_id + )) + })?; + if offer.ruleset != host_ruleset || model.ruleset != host_ruleset { + return Err(PortableError::RulesetMismatch { + character: model.ruleset, + realm: host_ruleset, + }); } } self.store diff --git a/crates/coa-core/src/portable/session/tests.rs b/crates/coa-core/src/portable/session/tests.rs index 1c414fe..0dd7dc7 100644 --- a/crates/coa-core/src/portable/session/tests.rs +++ b/crates/coa-core/src/portable/session/tests.rs @@ -1561,6 +1561,20 @@ fn reborn_hostile_attacks_are_rejected_with_zero_mutation() { coll_err2.is_err(), "Reborn merging wildcard:vanity must fail" ); + + // 9. HostService with malformed server_id ruleset suffixes fails closed + for bad_server_id in ["srv-1:unknown", "srv-1:garbage", "srv-1:reborn:extra"] { + let mut h_bad = HostService::new(&mut host, bad_server_id, HostConfig::default()); + let mut offer_bad = OwnerService::new(&mut owner) + .offer(id_reb, "srv-1:reborn") + .unwrap(); + offer_bad.server_id = bad_server_id.to_string(); + let res_bad = h_bad.accept_offer(host_profile, &offer_bad); + assert!( + res_bad.is_err(), + "accept_offer on malformed server id {bad_server_id} must fail closed" + ); + } } #[test] diff --git a/docs/REBORN_PORTABLE_AUDIT.md b/docs/REBORN_PORTABLE_AUDIT.md index 68016fb..953082d 100644 --- a/docs/REBORN_PORTABLE_AUDIT.md +++ b/docs/REBORN_PORTABLE_AUDIT.md @@ -1,62 +1,84 @@ -# Warcraft Reborn Portable Characters Audit +# Warcraft Reborn Portable Characters Audit & Semantic State -## 1. Overview & Baseline vs Current Implementation +## 1. Historical Baseline +The released v0.7.0 master branch codebase contained foundational support for local realm execution: +- Mode: `Mode::Reborn` +- Realm ID: `3` +- Databases: characters DB `acore_characters_reborn`, world DB `acore_world_reborn`, shared auth DB `acore_auth` +- Policy: Reborn runs as the active primary realm on the main world port (8085). Simultaneous execution with CoA/Wildcard is strictly unsupported (`"Simultaneous startup supports CoA and Wildcard only."`). -### 1.1 Baseline Discovered Before Implementation -The released v0.7.0 master branch codebase contained foundational support for local realm execution (`Mode::Reborn`, realm ID `3`, characters DB `acore_characters_reborn`, world DB `acore_world_reborn`, shared auth DB `acore_auth`). -Portable character transfers into Warcraft Reborn were temporarily guarded by: +Before the multi-ruleset implementation, portable character transfers into Warcraft Reborn were temporarily blocked by: ```rust // crates/coa-core/src/portable/realm/mod.rs Mode::Reborn => Err(PortableError::Invalid("Portable characters are not supported on Warcraft Reborn realms yet.".into())), ``` -### 1.2 Implemented in 58a99f0+ and MR1.1 -- **RulesetId / Ruleset**: `Ruleset::Reborn` is established across `coa-core`, `coa-registry-proto`, `coa-control-proto`, and TypeScript models (`"reborn"` wire value, display name `"Warcraft Reborn"`). -- **SQLite Portable Storage:** Migration `009_multiruleset.sql` upgrades released databases to permit `reborn` characters in the `character` table CHECK constraint without dropping child records. -- **Collections:** `reborn:appearance` and `reborn:vanity` defined and carried under exact allowlist in `carried_kind_for`. Partitioned under `(profile_id, 'reborn', kind)`. -- **Wire Protocols:** Control protocol v2, Session protocol v3, and Collection protocol v2 bind `ruleset: Ruleset` explicitly in all messages. +## 2. Current MR3 Implementation +In MR1.1, MR2, and MR3, generic multi-ruleset infrastructure was completed and enabled for Reborn: +- **Ruleset Identity**: `Ruleset::Reborn` established across `coa-core`, `coa-registry-proto`, `coa-control-proto`, and frontend TypeScript models (`"reborn"` wire value, display name `"Warcraft Reborn"`). +- **SQLite Storage**: Migration `009_multiruleset.sql` upgrades released databases to permit `reborn` in `character` CHECK constraints without dropping existing character rows or foreign keys. +- **Collections**: `reborn:appearance` and `reborn:vanity` defined and carried under allowlist in `carried_kind_for`. Partitioned under `(profile_id, 'reborn', kind)`. +- **Wire Protocols**: Control Protocol v2, Session Protocol v3, and Collection Protocol v2 bind `ruleset: Ruleset` explicitly in all messages. +- **Fail-Closed Routing & Ingress**: `srv-X:reborn` resolves strictly to the Reborn realm and fails closed if inactive. HostService rejects malformed server-id ruleset suffixes. +- **Automated Verification**: End-to-end claiming, export, snapshot import, runtime session lifecycle, intermediate/final checkpoints, and logout sync pass. +- **Three-Space Isolation**: Torture fixtures prove zero mutation across rulesets: + - Reborn character -> CoA / Wildcard realm (rejected with zero mutation). + - CoA / Wildcard character -> Reborn realm (rejected with zero mutation). + - Reborn collection rejects foreign namespaced entries (`coa:*`, `wildcard:*`). -### 1.3 Implemented in MR3 Vertical Slice -- Concrete support for Warcraft Reborn character import/export, claiming, session lifecycle, checkpoints, and logout sync. -- `ruleset_of(&reborn_db)` returns `Ok(Ruleset::Reborn)`. -- Reborn character class formatting correctly maps vanilla/standard classes (`reborn:class:1..11`) alongside custom classes. -- Direct ingress and routing respect active primary Reborn realm (realm ID 3, `acore_characters_reborn`, `acore_world_reborn`, port 8085) and fail closed when Reborn is inactive. -- Frontend UI displays `RulesetBadge` with human-facing labels ("Warcraft Reborn", "Wildcard", "Conquest of Azeroth"), ruleset filter tabs in Portable Characters screen, and ruleset-filtered Character Picker in the JOIN drawer. -- Three-space isolation fixture and torture tests prove complete mutation isolation: - - Reborn character -> CoA realm (rejected with zero DB mutation). - - Reborn character -> Wildcard realm (rejected with zero DB mutation). - - CoA character -> Reborn realm (rejected with zero DB mutation). - - Wildcard character -> Reborn realm (rejected with zero DB mutation). - - Reborn collections (`reborn:appearance`, `reborn:vanity`) reject foreign namespaced collections. -- Physical external-client smoke is deferred to the combined manual verification gate. +## 3. Actual Reborn Semantic-State Audit -## 2. Ruleset Identity & DB Schemas -- **RulesetId / Ruleset**: - - `Ruleset::Reborn` exists in `crates/coa-core/src/portable/model.rs` and `crates/coa-registry-proto/src/caps.rs`. - - Serialized string: `"reborn"`. - - Display name: `"Warcraft Reborn"`. - - Associated Realm ID: `3`. - - Character Database: `acore_characters_reborn`. - - World Database: `acore_world_reborn`. - - Auth Database: `acore_auth` (shared across all modes). -- **Collections**: - - `reborn:appearance` - - `reborn:vanity` - - Partitioned under `(profile_id, 'reborn', kind)` in canonical SQLite store (`portable.db`). +### 3.1 Gameplay Identity and Class Architecture +Warcraft Reborn in this core is configured via `CoA.ClassModel = "coa wcr"` / `wcr` mode: +- Classes in Warcraft Reborn are standard classic WoW classes (Warrior, Paladin, Hunter, Rogue, Priest, Death Knight, Shaman, Mage, Warlock, Druid; class IDs 1..11) rather than CoA custom classes (Barbarian, Witch Doctor, etc., IDs 12..32). +- Reborn spells, class abilities, talent trees, and creature summons use dedicated spell/creature ID ranges and corrections (e.g. `REBORN_CREATURE_OFFSET = 1100000`, spell twin scripts), which operate on standard AzerothCore character persistence structures. +- Reborn characters use the exact same character persistence schema (`acore_characters_reborn`) as vanilla/CoA character databases, cloned directly via `db.clone_structure("acore_characters", &stage_chars, &cache)` in `crates/coa-core/src/realms.rs`. -## 3. Simultaneous Startup & Multiworld Policy -- As verified in `crates/coa-core/src/multiworld.rs` and `crates/coa-core/src/realms.rs`: - - `CoA + Wildcard` simultaneous execution is supported. - - `Reborn` simultaneous execution is explicitly unsupported (`"Simultaneous startup supports CoA and Wildcard only."`). - - This policy is preserved strictly without changes. +### 3.2 Table & State Classification Matrix -## 4. Enabling Reborn in Portable Architecture -To complete the Reborn vertical slice with full strict isolation: -1. Map `Mode::Reborn => Ok(Ruleset::Reborn)` in `crates/coa-core/src/portable/realm/mod.rs:ruleset_of`. -2. Update tests verifying `ruleset_of(&reborn_db).unwrap() == Ruleset::Reborn`. -3. Verify Reborn claiming, export, import, session runtime, checkpoints, and collection isolation. -4. Verify non-negotiable isolation tests: - - Reborn character -> CoA realm (rejected). - - Reborn character -> Wildcard realm (rejected). - - CoA character -> Reborn realm (rejected). - - Wildcard character -> Reborn realm (rejected). +| Category / State | Database Table(s) | Portable Character Mapping | Classification | +| :--- | :--- | :--- | :--- | +| **Identity (name, race, class, gender)** | `characters` | `PortableCharacter.name`, `.race`, `.class`, `.gender` | **Already covered by generic PortableCharacter** | +| **Progression (level, XP, money)** | `characters` | `Progression.level`, `.xp`, `.money` | **Already covered by generic PortableCharacter** | +| **Inventory & Equipment** | `character_inventory`, `item_instance` | `Item` records, container links, slot indices, item entry | **Already covered by generic PortableCharacter** | +| **Enchants, Gems, Random Properties** | `item_instance` (`enchantments`, `randomPropertyId`, `durability`) | `Item.enchantments`, `random_property_id`, `durability` | **Already covered by generic PortableCharacter** | +| **Bags & Bank** | `character_inventory` (bag slots, bank slots) | `Item` container slots; personal bank slots | **Already covered by generic PortableCharacter** | +| **Spells** | `character_spell` | `PortableCharacter.spells` (array of spell IDs) | **Already covered by generic PortableCharacter** | +| **Talents** | `character_talent` | `PortableCharacter.talents` (spec, talent IDs, ranks) | **Already covered by generic PortableCharacter** | +| **Glyphs** | `character_glyphs` | `PortableCharacter.glyphs` (spec, slot, glyph ID) | **Already covered by generic PortableCharacter** | +| **Action Bars** | `character_action` | `PortableCharacter.actions` (button, action, type) | **Already covered by generic PortableCharacter** | +| **Skills & Weapon proficiencies** | `character_skills` | `PortableCharacter.skills` (skill ID, value, max) | **Already covered by generic PortableCharacter** | +| **Quests (Active & Rewarded)** | `character_queststatus`, `character_queststatus_rewarded` | `Quest` records, objective counters, rewarded list | **Already covered by generic PortableCharacter** | +| **Reputation** | `character_reputation` | `Reputation` records (faction ID, standing, flags) | **Already covered by generic PortableCharacter** | +| **Pets & Pet Spells** | `character_pet`, `pet_spell` | `Pet` records, entry, name, spells | **Already covered by generic PortableCharacter** | +| **Character Settings & Keybindings** | `character_settings`, `character_account_data` | `Setting` records (source, data payload) | **Already covered by generic PortableCharacter** | +| **Vanity / Transmog Collections** | `account_appearance_collection`, `account_vanity_collection` | `reborn:appearance`, `reborn:vanity` collections | **Account-wide Reborn collection** | +| **Active Auras / Buffs** | `character_aura` | Not persisted in portable snapshot | **Realm-local and intentionally not portable** (refreshed on login) | +| **Spell Cooldowns** | `character_spell_cooldown` | Not persisted in portable snapshot | **Realm-local and intentionally not portable** | +| **Daily / Weekly Quest Resets** | `character_queststatus_daily`, `weekly`, `monthly` | Not persisted in portable snapshot | **Realm-local and intentionally not portable** | +| **Instance Bindings** | `character_instance`, `character_homebind` | Not persisted in portable snapshot | **Realm-local and intentionally not portable** | +| **Battleground / Arena Ratings** | `character_arena_stats`, `character_battleground_random` | Not persisted in portable snapshot | **Realm-local and intentionally not portable** | +| **Manastorm / Challenge states** | `ascension_manastorm_*`, `coa_character_challenge` | Classified as `Blocking` if active | **Blocking** (blocks export while active challenge exists) | +| **Custom Reborn Tables** | None exist in database | N/A | **Irrelevant** (no custom tables in `acore_characters_reborn`) | + +### 3.3 Reborn Extension Requirement Decision + +```text +Reborn extension required: NO +``` + +**Rationale:** +1. Warcraft Reborn builds persistent character state entirely within standard AzerothCore character tables (`characters`, `character_spell`, `character_talent`, `character_action`, `character_skills`, `character_inventory`, `item_instance`, `character_reputation`, `character_pet`). +2. There are no separate Reborn-specific character tables in `acore_characters_reborn` (the schema is identical to `acore_characters`). +3. Reborn class abilities, spells, and talent configurations are encoded natively via standard spell IDs and talent IDs supported by `PortableCharacter.spells` and `PortableCharacter.talents`. +4. Character settings (such as build selections or client UI configs) persist through `character_settings`, which is already captured in `PortableCharacter.settings`. +5. Transmog and cosmetic appearance selections are synchronized cleanly via the `reborn:appearance` and `reborn:vanity` account collections. +6. Therefore, adding a custom typed extension is not needed and would introduce redundant schema without semantic benefit. The generic `PortableCharacter` model provides 100% semantic continuity for Reborn character builds. + +## 4. Remaining Manual Verification +- **Combined Physical Real-Client Gate**: + - Live client connection to a running Warcraft Reborn realm. + - Character creation on Reborn, progression, claiming to Manager. + - Transfer/import to a secondary Reborn realm and runtime session verification. + - Verification that CoA and Wildcard realms remain completely isolated. + - Status: **PENDING COMBINED MANUAL GATE**. diff --git a/docs/WARCRAFT-REBORN.md b/docs/WARCRAFT-REBORN.md index fddbd1e..0fbbdf1 100644 --- a/docs/WARCRAFT-REBORN.md +++ b/docs/WARCRAFT-REBORN.md @@ -7,7 +7,7 @@ have its saved realm updated immediately. Accounts are shared with your other local realms. Warcraft Reborn starts with separate characters; switching profiles does not copy existing characters or progress. -Bots are unavailable on Warcraft Reborn. Other optional modules are experimental. Portable character transfers into Warcraft Reborn are not supported. **Portable characters remain experimental.** +Bots are unavailable on Warcraft Reborn. Other optional modules are experimental. Portable Characters support for Warcraft Reborn is implemented experimentally. Automated isolation/import/session tests pass. Physical real-client verification is still pending the combined manual gate. **Portable characters remain experimental.** Backups and updates include every created realm. Check the realm recorded in a recovery point before restoring it. diff --git a/src/i18n/locales/de.ts b/src/i18n/locales/de.ts index 95413e0..d2b72ea 100644 --- a/src/i18n/locales/de.ts +++ b/src/i18n/locales/de.ts @@ -888,6 +888,12 @@ const de: Partial> = { "crash.hideRaw": "Vollständigen Bericht verbergen", "crash.copyReport": "Bericht kopieren", "crash.copied": "Kopiert!", + "portable.filter.none": "Keine Charaktere entsprechen dem ausgewählten Spielmodus.", + "portable.filter.all": "Alle", + "browse.hidden_characters_one": "{n} Charakter aus anderen Spielmodi ist ausgeblendet", + "browse.hidden_characters_few": "{n} Charaktere aus anderen Spielmodi sind ausgeblendet", + "browse.hidden_characters_many": "{n} Charaktere aus anderen Spielmodi sind ausgeblendet", + "browse.hidden_characters_other": "{n} Charaktere aus anderen Spielmodi sind ausgeblendet", }; export default de; diff --git a/src/i18n/locales/en.ts b/src/i18n/locales/en.ts index 1cbbb73..10a28fd 100644 --- a/src/i18n/locales/en.ts +++ b/src/i18n/locales/en.ts @@ -1029,6 +1029,12 @@ const en = { "portable.err.not_prepared": "Only a realm added from a file can be removed here.", "portable.err.launch": "The game could not be started. Check the client in Settings.", "portable.err.other": "Something went wrong. Nothing was lost.", + "portable.filter.none": "No characters match the selected game mode.", + "portable.filter.all": "All", + "browse.hidden_characters_one": "{n} character from other game modes is hidden", + "browse.hidden_characters_few": "{n} characters from other game modes are hidden", + "browse.hidden_characters_many": "{n} characters from other game modes are hidden", + "browse.hidden_characters_other": "{n} characters from other game modes are hidden", "portable.diag.title": "Diagnostics", "portable.diag.text": "A report for a bug report: realms, versions, sessions and recent problems. No passwords and no character data.", "portable.diag.copy": "Copy diagnostics", diff --git a/src/i18n/locales/es.ts b/src/i18n/locales/es.ts index bfcda03..16d31b0 100644 --- a/src/i18n/locales/es.ts +++ b/src/i18n/locales/es.ts @@ -888,6 +888,12 @@ const es: Partial> = { "crash.hideRaw": "Ocultar informe completo", "crash.copyReport": "Copiar informe", "crash.copied": "¡Copiado!", + "portable.filter.none": "Ningún personaje coincide con el modo de juego seleccionado.", + "portable.filter.all": "Todos", + "browse.hidden_characters_one": "{n} personaje de otros modos de juego está oculto", + "browse.hidden_characters_few": "{n} personajes de otros modos de juego están ocultos", + "browse.hidden_characters_many": "{n} personajes de otros modos de juego están ocultos", + "browse.hidden_characters_other": "{n} personajes de otros modos de juego están ocultos", }; export default es; diff --git a/src/i18n/locales/fr.ts b/src/i18n/locales/fr.ts index ce75aaa..06334bb 100644 --- a/src/i18n/locales/fr.ts +++ b/src/i18n/locales/fr.ts @@ -888,6 +888,12 @@ const fr: Partial> = { "crash.hideRaw": "Masquer le rapport complet", "crash.copyReport": "Copier le rapport", "crash.copied": "Copié !", + "portable.filter.none": "Aucun personnage ne correspond au mode de jeu sélectionné.", + "portable.filter.all": "Tous", + "browse.hidden_characters_one": "{n} personnage d'autres modes de jeu est masqué", + "browse.hidden_characters_few": "{n} personnages d'autres modes de jeu sont masqués", + "browse.hidden_characters_many": "{n} personnages d'autres modes de jeu sont masqués", + "browse.hidden_characters_other": "{n} personnages d'autres modes de jeu sont masqués", }; export default fr; diff --git a/src/i18n/locales/ru.ts b/src/i18n/locales/ru.ts index c162632..d92939f 100644 --- a/src/i18n/locales/ru.ts +++ b/src/i18n/locales/ru.ts @@ -1011,6 +1011,12 @@ const ru: Partial> = { "portable.err.not_prepared": "Здесь можно убрать только реалм, добавленный из файла.", "portable.err.launch": "Не удалось запустить игру. Проверьте клиент в настройках.", "portable.err.other": "Что-то пошло не так. Ничего не потеряно.", + "portable.filter.none": "Нет персонажей для выбранного игрового режима.", + "portable.filter.all": "Все", + "browse.hidden_characters_one": "{n} персонаж из других игровых режимов скрыт", + "browse.hidden_characters_few": "{n} персонажа из других игровых режимов скрыто", + "browse.hidden_characters_many": "{n} персонажей из других игровых режимов скрыто", + "browse.hidden_characters_other": "{n} персонажей из других игровых режимов скрыто", "portable.diag.title": "Диагностика", "portable.diag.text": "Отчёт для сообщения об ошибке: реалмы, версии, сессии и недавние проблемы. Без паролей и без данных персонажей.", "portable.diag.copy": "Скопировать диагностику", diff --git a/src/i18n/locales/zh.ts b/src/i18n/locales/zh.ts index dee58b9..93b8710 100644 --- a/src/i18n/locales/zh.ts +++ b/src/i18n/locales/zh.ts @@ -890,6 +890,12 @@ const zh = { "crash.hideRaw": "隐藏完整日志", "crash.copyReport": "复制崩溃报告", "crash.copied": "已复制!", + "portable.filter.none": "没有符合所选游戏模式的角色。", + "portable.filter.all": "全部", + "browse.hidden_characters_one": "已隐藏 {n} 个其他游戏模式的角色", + "browse.hidden_characters_few": "已隐藏 {n} 个其他游戏模式的角色", + "browse.hidden_characters_many": "已隐藏 {n} 个其他游戏模式的角色", + "browse.hidden_characters_other": "已隐藏 {n} 个其他游戏模式的角色", } as const; export default zh; diff --git a/src/screens/BrowsePage.tsx b/src/screens/BrowsePage.tsx index f6961c9..988d612 100644 --- a/src/screens/BrowsePage.tsx +++ b/src/screens/BrowsePage.tsx @@ -68,7 +68,7 @@ function SortHeader({ id, sort, order, onSort, children, className }: { id: Sort } function Drawer({ summary, catalog, onClose }: { summary: RealmSummary; catalog: Catalog; onClose: () => void }) { - const { t, locale } = useI18n(); + const { t, tn, locale } = useI18n(); const { state, refresh: refreshPortable } = usePortable(); const [detail, setDetail] = useState(null); const [error, setError] = useState(null); @@ -159,7 +159,7 @@ function Drawer({ summary, catalog, onClose }: { summary: RealmSummary; catalog:

{t("browse.noCharacter")}

{hiddenCount > 0 && (

- {hiddenCount} {hiddenCount === 1 ? "character" : "characters"} from other game modes {hiddenCount === 1 ? "is" : "are"} hidden + {tn("browse.hidden_characters", hiddenCount)}

)}
@@ -171,7 +171,7 @@ function Drawer({ summary, catalog, onClose }: { summary: RealmSummary; catalog: {hiddenCount > 0 && (

- {hiddenCount} {hiddenCount === 1 ? "character" : "characters"} from other game modes {hiddenCount === 1 ? "is" : "are"} hidden + {tn("browse.hidden_characters", hiddenCount)}

)}
diff --git a/src/screens/PortablePage.tsx b/src/screens/PortablePage.tsx index b688013..fd6f436 100644 --- a/src/screens/PortablePage.tsx +++ b/src/screens/PortablePage.tsx @@ -318,7 +318,7 @@ export function PortablePage({ onOpenSettings }: { onOpenSettings?: () => void } rulesetFilter === "" ? "bg-white/10 text-ink shadow-sm" : "text-muted hover:text-ink" )} > - {t("browse.any")} + {t("portable.filter.all")}