Compare commits

...
Author SHA1 Message Date
Дмитрий a48717340b chore(reborn): MR3.1 semantic audit, i18n localization, and fail-closed cleanup 2026-10-22 22:18:28 +05:00
Дмитрий 351ace1c56 feat(reborn): MR3 Warcraft Reborn portable character vertical slice and ruleset UI 2026-10-22 21:26:39 +05:00
Дмитрий ba143e1ccd fix(control): MR2.1 fail-closed world-port resolution and ruleset invariant verification
- Make world_port resolution fallible (Result<u16>) across LocalBackend, HostService, DirectRouteManager, and RelayLink without default fallbacks to 8085.
- Enforce strict 4-way invariant: local_id ruleset == RealmAccess.mode == Db.realm() == RealmInfo.ruleset. Malformed or unknown suffixes fail closed.
- If Wildcard is selected and world-port resolution fails (or simultaneous mode is disabled), Direct and Relay fail closed with actionable error and zero fallback to CoA.
- Fix documentation drift in docs/WILDCARD.md and docs/MULTIRULESET_PORTABLE_AUDIT.md regarding simultaneous execution, distinct ports, and current vs historical baseline.
2026-10-22 18:10:49 +05:00
Дмитрий 5343020bed feat(portable): MR2 Wildcard portable character vertical slice
- Enforce fail-closed backend resolution in LocalBackend::info (unknown ruleset = error).
- Implement strict three-space isolation (Wildcard != CoA != Reborn) across canonical store, host mappings, and collections.
- Isolate collection namespaces (wildcard:appearance, wildcard:vanity) and reject cross-ruleset collections in claim and import.
- Enforce Control Protocol v2 ruleset verification on TransferOffer, TransferCommit, and Claimed response.
- Route Direct Ingress and Relay Link dynamically according to realm world port (8085 for CoA, 8086 for Wildcard).
- Add runtime session attack rejection test suite (cross-ruleset session offers, checkpoints, owner acks, server IDs).
- Verify end-to-end Wildcard session lifecycle and documentation updates.
2026-10-22 17:24:15 +05:00
Дмитрий 9d135765cd feat(multiruleset): complete MR1.1 foundation correctness gate 2026-10-22 15:34:37 +05:00
Дмитрий 58a99f0a6d feat: multi-ruleset realms and strictly isolated portable characters 2026-10-22 13:04:57 +05:00
Дмитрий d9c10c4564 Merge released v0.7.1 into feat/multiruleset-realms-portable 2026-10-22 12:00:03 +05:00
Corfirean dc05b2cd3c Record reviewed Manager 0.7.1 release notes 2026-10-22 11:00:19 +05:00
Дмитрий 8d2befd7f0 Update Custom Races client package to 1.8.3 for Manager 0.7.1 2026-10-22 10:41:52 +05:00
Дмитрий 8d9dc47fed Merge published documentation and shared changelog updates for 0.7.1 2026-10-22 09:37:33 +05:00
Corfirean 2e3f36d2fd docs: keep public guides and screenshots focused on users (#139) 2026-10-22 08:12:13 +05:00
Corfirean 8f39896f0c Publish released 0.7 player guides and screenshot gallery on master (#138) 2026-10-22 08:04:59 +05:00
github-actions[bot] 103c829539 Update published Manager changelog 2026-10-22 02:53:40 +00:00
Corfirean 20fb2391ed Record every published Manager version in its own changelog (#137) 2026-10-22 07:49:15 +05:00
Corfirean 43de03eada Keep imported upstream notes separate and read historical BOM fragments (#136) 2026-10-22 00:14:25 +05:00
Дмитрий 5796cffb5e Exclude frozen upstream notes and accept historical UTF-8 BOM fragments 2026-10-22 00:11:44 +05:00
Corfirean cda58cdcd1 Fix collecting the next published Manager changelog from its Git tag (#135) 2026-10-22 00:04:32 +05:00
Дмитрий 112cb7e69c Read new Manager release notes from Git without unsupported subprocess arguments 2026-10-22 00:02:16 +05:00
Дмитрий 517e04dace Preserve published assets on manual publishing retries as well 2026-10-21 23:39:02 +05:00
Дмитрий e87cd0bb78 Do not rebuild or republish an existing release when its tag is created 2026-10-21 23:38:15 +05:00
113 changed files with 6286 additions and 1905 deletions

No files matched your search

+1 -1
View File
@@ -6,7 +6,7 @@ on:
pull_request:
paths: [tools/sync_history.py, tools/test_sync_history.py, changelog/history.json, .github/workflows/changelog.yml]
release:
types: [published, released]
types: [published, prereleased, released]
workflow_run:
workflows: [release]
types: [completed]
+27
View File
@@ -16,7 +16,34 @@ permissions:
contents: write
jobs:
release-intent:
runs-on: ubuntu-latest
outputs:
build: ${{ steps.intent.outputs.build }}
steps:
- id: intent
name: Keep already published release assets immutable
env:
GH_TOKEN: ${{ github.token }}
REQUEST_PUBLISH: ${{ inputs.publish_release && 'true' || 'false' }}
run: |
python3 - <<'PY'
import json, os, subprocess
build = True
if os.environ['GITHUB_EVENT_NAME'] == 'push' or os.environ.get('REQUEST_PUBLISH') == 'true':
result = subprocess.run(['gh', 'api', 'repos/' + os.environ['GITHUB_REPOSITORY'] + '/releases/tags/' + os.environ['GITHUB_REF_NAME']], capture_output=True, text=True)
if result.returncode == 0:
build = json.loads(result.stdout)['draft']
if not build:
print('Published release already exists; preserve its assets and prerelease status.')
elif 'HTTP 404' not in result.stderr:
raise RuntimeError('Could not establish whether this release already exists: ' + result.stderr)
with open(os.environ['GITHUB_OUTPUT'], 'a') as output:
output.write('build=' + str(build).lower() + '\n')
PY
installer:
needs: release-intent
if: needs.release-intent.outputs.build == 'true'
runs-on: windows-latest
timeout-minutes: 60
steps:
+4
View File
@@ -31,6 +31,10 @@ Optional: one short paragraph in plain English for the reader (at most 300 chara
## Shared build and release workflow
Every published Manager version, including a clearly marked Pre-release, belongs in this repository's
CHANGELOG.md and changelog/history.json. Its GitHub release notes use the same reviewed record.
Promotion updates that entry without duplicating it; Manager and server histories remain separate.
Before preparing or publishing a Manager/server release, read the maintained
[release runbook](https://github.com/Corfirean/coa-server-build/blob/main/docs/server-release.md)
and [build agent instructions](https://github.com/Corfirean/coa-server-build/blob/main/AGENTS.md).
+34
View File
@@ -4,8 +4,42 @@ Manager releases only. Updating the Manager does not update the server.
[Server changelog](https://github.com/Corfirean/coa-server-build/blob/main/CHANGELOG.md)
Published releases and previews. Pre-release entries do not change the stable update channel.
Dates follow GitHub publication (UTC); legacy records retain their archived dates. Newest releases first.
## 0.7.1 — 2026-10-22
Close the game, then open Modules → Custom Races → Repair Client Patch to update existing patches, or Install Client Patch for a new installation. Updating the Manager does not automatically replace game files or update your server.
**Portable Characters are experimental and may contain bugs.**
- Updated Custom Races client patches to the complete 1.8.3 package.
- Race patch installation now includes the hide-armor and talent-reset addons.
[Release](https://github.com/Corfirean/coa-server-manager/releases/tag/v0.7.1) · [Source changes](https://github.com/Corfirean/coa-server-manager/compare/v0.7.0...v0.7.1)
[Guides and screenshots](https://github.com/Corfirean/coa-server-manager/blob/master/docs/README.md)
## 0.7.0 — 2026-10-21
Portable transfers into Warcraft Reborn are not supported yet.
**Portable Characters are experimental and may contain bugs.**
- Keep portable characters and their saved versions in the Manager, and use them on compatible realms.
- Make an existing character portable from a connected realm.
- Browse public realms and see their connection details.
- Link an existing realm account or create one on hosts that allow it.
- Switch between CoA, Wildcard and Warcraft Reborn realm profiles on supported server builds.
- Adjust creature health for different locations and enemy types in Content Scaling.
- Switch Custom Races patches faster, with visible feedback while changes are applied.
- Handle Windows requests for administrator permission when launching the game.
[Release](https://github.com/Corfirean/coa-server-manager/releases/tag/v0.7.0) · [Source changes](https://github.com/Corfirean/coa-server-manager/compare/v0.6.22...v0.7.0)
[Player guides and screenshots](https://github.com/Corfirean/coa-server-manager/tree/d22ff09ac6fd7628aac14d90ec23f547cd9b4bf1/docs)
## 0.6.22 — 2026-10-19
- Updated Custom Races client patches to 1.8.
Generated
+3 -3
View File
@@ -586,7 +586,7 @@ dependencies = [
[[package]]
name = "coa-core"
version = "0.7.0"
version = "0.7.1"
dependencies = [
"base64 0.22.1",
"chrono",
@@ -634,7 +634,7 @@ dependencies = [
[[package]]
name = "coa-release"
version = "0.7.0"
version = "0.7.1"
dependencies = [
"chrono",
"coa-core",
@@ -643,7 +643,7 @@ dependencies = [
[[package]]
name = "coa-server-manager"
version = "0.7.0"
version = "0.7.1"
dependencies = [
"coa-control-proto",
"coa-core",
+1 -1
View File
@@ -4,7 +4,7 @@ members = ["crates/coa-core", "crates/coa-release", "crates/coa-registry-proto",
exclude = ["services/coa-registry", "services/coa-registry-e2e", "services/coa-coordinator", "services/coa-relay"]
[workspace.package]
version = "0.7.0"
version = "0.7.1"
edition = "2021"
license = "AGPL-3.0-only"
+2 -2
View File
@@ -29,7 +29,7 @@ no console, no config files, no database tools. Tauri 2 + Rust + React.
the change is applied on the next launch through the Manager.
Bots are unavailable on Wildcard and Warcraft Reborn; other optional modules are experimental. Backups and
database updates include every created realm. Simultaneous startup supports CoA + Wildcard only.
See [realm profiles and validation](docs/WILDCARD.md) and [Warcraft Reborn](docs/WARCRAFT-REBORN.md).
See [Wildcard guide](docs/WILDCARD.md) and [Warcraft Reborn](docs/WARCRAFT-REBORN.md).
* **Companions (bots).** Fill the world with level-appropriate bots, see progress, stop spawning, take them offline,
despawn N to relieve the server, and choose how many log in at server start.
* **Realmlist switcher.** Keep named realmlists (for example *Solo* and *PTR*) and switch the game client between them from a
@@ -58,7 +58,7 @@ no console, no config files, no database tools. Tauri 2 + Rust + React.
The full gallery also covers setup, modules, game clients, playing with friends and making an existing character portable.
[Browse the screenshot gallery](docs/SCREENSHOTS.md).
[Browse the screenshot gallery](docs/SCREENSHOTS.md) · [Player and server owner guides](docs/README.md).
## Install
@@ -0,0 +1,7 @@
---
area: manager
type: changed
audience: players
title: Custom Races client patches now use the latest complete package
---
Install or repair Custom Races client patches from the Modules page to get the updated package, including its latest appearance fixes and login screen artwork.
+53 -1
View File
@@ -112,7 +112,15 @@
"Corfirean/coa-server-manager:20261016-preserve-core-migration-history.md",
"Corfirean/coa-server-manager:20261016-shared-auth-migration-history.md",
"Corfirean/coa-server-manager:20261016-update-compatibility-wording.md",
"Corfirean/coa-server-manager:20261018-custom-races-client.md"
"Corfirean/coa-server-manager:20261018-custom-races-client.md",
"Corfirean/coa-server-manager:20261019-portable-stop-diagnostics.md",
"Corfirean/coa-server-manager:20261019-remote-character-class-names.md",
"Corfirean/coa-server-manager:20261020-client-elevation.md",
"Corfirean/coa-server-manager:20261021-custom-races-switching.md",
"Corfirean/coa-server-manager:20261021-portable-experimental.md",
"Corfirean/coa-server-manager:20261021-scaling-health-settings.md",
"Corfirean/coa-server-manager:20261021-warcraft-reborn-realm.md",
"Corfirean/coa-server-manager:20261022-custom-races-client.md"
],
"releases": [
{
@@ -571,6 +579,50 @@
"Existing client files are preserved when installing or removing race patches"
],
"compare": "https://github.com/Corfirean/coa-server-manager/compare/v0.6.21...v0.6.22"
},
{
"tag": "v0.7.0",
"version": "0.7.0",
"date": "2026-10-21",
"url": "https://github.com/Corfirean/coa-server-manager/releases/tag/v0.7.0",
"notes": [
"Keep portable characters and their saved versions in the Manager, and use them on compatible realms",
"Make an existing character portable from a connected realm",
"Browse public realms and see their connection details",
"Link an existing realm account or create one on hosts that allow it",
"Switch between CoA, Wildcard and Warcraft Reborn realm profiles on supported server builds",
"Adjust creature health for different locations and enemy types in Content Scaling",
"Switch Custom Races patches faster, with visible feedback while changes are applied",
"Handle Windows requests for administrator permission when launching the game"
],
"commit": "d22ff09ac6fd7628aac14d90ec23f547cd9b4bf1",
"experimentalFeatures": [
"portable-characters"
],
"compare": "https://github.com/Corfirean/coa-server-manager/compare/v0.6.22...v0.7.0",
"notice": "Portable transfers into Warcraft Reborn are not supported yet.",
"links": [
"[Player guides and screenshots](https://github.com/Corfirean/coa-server-manager/tree/d22ff09ac6fd7628aac14d90ec23f547cd9b4bf1/docs)"
]
},
{
"tag": "v0.7.1",
"version": "0.7.1",
"date": "2026-10-22",
"url": "https://github.com/Corfirean/coa-server-manager/releases/tag/v0.7.1",
"notes": [
"Updated Custom Races client patches to the complete 1.8.3 package",
"Race patch installation now includes the hide-armor and talent-reset addons"
],
"commit": "8d2befd7f08532b2cb9e0bf2f973bb631f3890e5",
"experimentalFeatures": [
"portable-characters"
],
"compare": "https://github.com/Corfirean/coa-server-manager/compare/v0.7.0...v0.7.1",
"notice": "Close the game, then open Modules → Custom Races → Repair Client Patch to update existing patches, or Install Client Patch for a new installation. Updating the Manager does not automatically replace game files or update your server.",
"links": [
"[Guides and screenshots](https://github.com/Corfirean/coa-server-manager/blob/master/docs/README.md)"
]
}
]
}
+24
View File
@@ -103,6 +103,7 @@ pub enum Request {
TransferOffer {
transfer_id: Uuid,
character_id: Uuid,
ruleset: String,
canonical_revision: u64,
content_hash: String,
total_size: usize,
@@ -189,6 +190,7 @@ pub enum Response {
/// appearance and vanity ids the Host holds for the account (kind -> ids).
Claimed {
character_id: Uuid,
ruleset: String,
sha256: String,
payload: String,
collections: BTreeMap<String, Vec<u32>>,
@@ -273,11 +275,15 @@ pub fn decode_request(bytes: &[u8]) -> Result<Request> {
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 +436,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 +449,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,
@@ -466,5 +474,21 @@ mod tests {
};
let resp_dec = decode_response(&encode_response(&resp)).unwrap();
assert_eq!(resp, resp_dec);
// Control protocol v2 requires ruleset in TransferOffer; missing is rejected
let missing_ruleset_json = serde_json::json!({
"op": "transfer_offer",
"transfer_id": tid,
"character_id": cid,
"canonical_revision": 5,
"content_hash": hash,
"total_size": 1024,
"collections": {}
});
let encoded_missing = serde_json::to_vec(&missing_ruleset_json).unwrap();
assert!(
decode_request(&encoded_missing).is_err(),
"missing ruleset in v2 must be rejected"
);
}
}
+1 -1
View File
@@ -16,7 +16,7 @@ pub mod coord;
pub mod noise;
pub mod relay;
pub const CONTROL_PROTOCOL_VERSION: u32 = 1;
pub const CONTROL_PROTOCOL_VERSION: u32 = 2;
#[derive(Debug, thiserror::Error, PartialEq, Eq)]
pub enum ControlError {
@@ -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(),
+120 -53
View File
@@ -1,57 +1,124 @@
//! Read-only audit, or explicit SQL checks on a disposable database fixture.
use coa_core::{db::{Account, Db}, migrations::{self, Store}, manifest::Manifest, realms::Mode};
use coa_core::{
db::{Account, Db},
manifest::Manifest,
migrations::{self, Store},
realms::Mode,
};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let args: Vec<_> = std::env::args().collect();
if args.len() < 3 { return Err("usage: migration_plan <root> <signed-manifest> [--apply|--sql-only <migration-directory>]".into()); }
let root = std::path::Path::new(&args[1]);
let bytes = std::fs::read(&args[2])?;
let signature = std::fs::read_to_string(format!("{}.sig",args[2]))?;
coa_core::signing::verify(&bytes, &signature, coa_core::signing::EMBEDDED_PUBLIC_KEY)?;
let manifest = Manifest::parse(&bytes)?;
for (index,mode) in [Mode::Coa, Mode::Wildcard].into_iter().enumerate() {
let db = Db::from_repack(root, Account::Admin)?.for_realm(mode);
let rows = db.load_readonly()?;
let relevant: Vec<_> = rows.iter().filter(|r| r.id == "rev_20260903_01_live_class_baseline").map(|r| format!("{} {:?} {}",r.db,r.status,r.baseline)).collect();
println!("{} baseline history: {:?}",mode.name(),relevant);
let list: Vec<_> = manifest.migrations.iter().filter(|m|index==0 || m.db!="auth").cloned().collect();
let plan = migrations::status(&db,&list)?;
println!("{} pending: {:?}",mode.name(),plan.iter().filter(|m|m.status!=migrations::Status::Applied).map(|m|(&m.db,&m.id,m.status)).collect::<Vec<_>>());
}
if args.get(3).is_some_and(|s| s == "--apply" || s == "--sql-only") {
assert!(root.file_name().unwrap().to_string_lossy().starts_with("update-database-diagnosis-") && root.join(".coa-update-fixture").is_file(), "Only disposable fixture roots may be changed");
if args[3] == "--sql-only" {
let db = Db::from_repack(root, Account::Admin)?.for_realm(Mode::Coa);
let identity = || -> coa_core::Result<String> {
let mut rows = String::new();
for (schema,table,columns) in [("acore_auth","account","id,HEX(username)"),("acore_characters","characters","guid,account,HEX(name)"),("acore_characters_wildcard","characters","guid,account,HEX(name)")] {
rows.push_str(schema);
rows.push_str(&db.query(&format!("SELECT {columns} FROM {schema}.{table} ORDER BY 1;"))?);
let args: Vec<_> = std::env::args().collect();
if args.len() < 3 {
return Err("usage: migration_plan <root> <signed-manifest> [--apply|--sql-only <migration-directory>]".into());
}
Ok(coa_core::fsx::sha256_bytes(rows.as_bytes()))
};
let before = identity()?;
migrations::verify_files(&manifest.migrations,std::path::Path::new(&args[4]))?;
for (index,mode) in [Mode::Coa,Mode::Wildcard].into_iter().enumerate() {
let realm_db = db.clone().for_realm(mode);
let list: Vec<_> = manifest.migrations.iter().filter(|m|index==0 || m.db!="auth").cloned().collect();
let result = migrations::apply_pending(&realm_db,&list,std::path::Path::new(&args[4]),&||Ok("disposable fixture".into()))?;
println!("{} SQL result: {}",mode.name(),serde_json::to_string(&result)?);
if result.failed.is_some() {return Err("SQL failed; fixture preserved".into());}
}
assert_eq!(before,identity()?,"Account or character identity changed");
println!("Account and character identities preserved: {}",before);
let capture = root.join("captured-schema");
coa_core::schema_check::capture(&db,&capture)?;
println!("Captured schema SHA256: {}",coa_core::fsx::sha256_file(&capture.join(coa_core::schema_check::CONTRACT))?);
return Ok(());
}
if args.len() != 5 { return Err("Migration directory required".into()); }
use coa_core::update::{Env, RepackEnv};
let meta = coa_core::registry::metadata_dir_for(root)?;
let env = RepackEnv { root, meta_dir: &meta };
let result = env.migrate(&manifest, std::path::Path::new(&args[4]));
let _ = coa_core::driver::run(root, coa_core::driver::Verb::StopAll);
println!("Application result: {}",serde_json::to_string(&result?)?);
}
Ok(())
let root = std::path::Path::new(&args[1]);
let bytes = std::fs::read(&args[2])?;
let signature = std::fs::read_to_string(format!("{}.sig", args[2]))?;
coa_core::signing::verify(&bytes, &signature, coa_core::signing::EMBEDDED_PUBLIC_KEY)?;
let manifest = Manifest::parse(&bytes)?;
for (index, mode) in [Mode::Coa, Mode::Wildcard].into_iter().enumerate() {
let db = Db::from_repack(root, Account::Admin)?.for_realm(mode);
let rows = db.load_readonly()?;
let relevant: Vec<_> = rows
.iter()
.filter(|r| r.id == "rev_20260903_01_live_class_baseline")
.map(|r| format!("{} {:?} {}", r.db, r.status, r.baseline))
.collect();
println!("{} baseline history: {:?}", mode.name(), relevant);
let list: Vec<_> = manifest
.migrations
.iter()
.filter(|m| index == 0 || m.db != "auth")
.cloned()
.collect();
let plan = migrations::status(&db, &list)?;
println!(
"{} pending: {:?}",
mode.name(),
plan.iter()
.filter(|m| m.status != migrations::Status::Applied)
.map(|m| (&m.db, &m.id, m.status))
.collect::<Vec<_>>()
);
}
if args
.get(3)
.is_some_and(|s| s == "--apply" || s == "--sql-only")
{
assert!(
root.file_name()
.unwrap()
.to_string_lossy()
.starts_with("update-database-diagnosis-")
&& root.join(".coa-update-fixture").is_file(),
"Only disposable fixture roots may be changed"
);
if args[3] == "--sql-only" {
let db = Db::from_repack(root, Account::Admin)?.for_realm(Mode::Coa);
let identity = || -> coa_core::Result<String> {
let mut rows = String::new();
for (schema, table, columns) in [
("acore_auth", "account", "id,HEX(username)"),
("acore_characters", "characters", "guid,account,HEX(name)"),
(
"acore_characters_wildcard",
"characters",
"guid,account,HEX(name)",
),
] {
rows.push_str(schema);
rows.push_str(&db.query(&format!(
"SELECT {columns} FROM {schema}.{table} ORDER BY 1;"
))?);
}
Ok(coa_core::fsx::sha256_bytes(rows.as_bytes()))
};
let before = identity()?;
migrations::verify_files(&manifest.migrations, std::path::Path::new(&args[4]))?;
for (index, mode) in [Mode::Coa, Mode::Wildcard].into_iter().enumerate() {
let realm_db = db.clone().for_realm(mode);
let list: Vec<_> = manifest
.migrations
.iter()
.filter(|m| index == 0 || m.db != "auth")
.cloned()
.collect();
let result = migrations::apply_pending(
&realm_db,
&list,
std::path::Path::new(&args[4]),
&|| Ok("disposable fixture".into()),
)?;
println!(
"{} SQL result: {}",
mode.name(),
serde_json::to_string(&result)?
);
if result.failed.is_some() {
return Err("SQL failed; fixture preserved".into());
}
}
assert_eq!(before, identity()?, "Account or character identity changed");
println!("Account and character identities preserved: {}", before);
let capture = root.join("captured-schema");
coa_core::schema_check::capture(&db, &capture)?;
println!(
"Captured schema SHA256: {}",
coa_core::fsx::sha256_file(&capture.join(coa_core::schema_check::CONTRACT))?
);
return Ok(());
}
if args.len() != 5 {
return Err("Migration directory required".into());
}
use coa_core::update::{Env, RepackEnv};
let meta = coa_core::registry::metadata_dir_for(root)?;
let env = RepackEnv {
root,
meta_dir: &meta,
};
let result = env.migrate(&manifest, std::path::Path::new(&args[4]));
let _ = coa_core::driver::run(root, coa_core::driver::Verb::StopAll);
println!("Application result: {}", serde_json::to_string(&result?)?);
}
Ok(())
}
+3 -3
View File
@@ -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!(
+60 -26
View File
@@ -1,28 +1,62 @@
//! Exercise the production updater only on a disposable copy of an installed server.
use coa_core::{registry::MetaDir, update::{self, Env, RepackEnv}};
fn main() -> Result<(),Box<dyn std::error::Error>> {
let args:Vec<_>=std::env::args().collect();
if args.len()!=3 && args.len()!=4 {return Err("usage: upgrade_fixture <disposable-root> <signed-package-directory>".into());}
let root=std::path::Path::new(&args[1]);
assert!(root.file_name().unwrap().to_string_lossy().starts_with("coa-schema-fixture-real") && root.join(".coa-update-fixture").is_file(),"Disposable fixture required");
let meta=coa_core::registry::metadata_dir_for(root)?;
let (_,installed)=MetaDir::open(&meta)?;
assert_eq!(coa_core::fsx::canonicalize_lenient(std::path::Path::new(&installed.server_path))?,coa_core::fsx::canonicalize_lenient(root)?,"Fixture metadata must point to the copy");
assert!(installed.client_path.is_none(),"Detach the real client from fixture metadata");
let env=RepackEnv{root,meta_dir:&meta};
if args.get(3).is_some_and(|flag|flag=="--validate-only") {
let result=env.validate();
let _=coa_core::driver::run(root,coa_core::driver::Verb::StopAll);
result?;
println!("Startup and identity validation passed");
return Ok(());
}
let outcome=update::apply(&update::Params{root,meta_dir:&meta,source:coa_core::pkgsource::Source::Dir(args[2].clone().into()),trusted_key:coa_core::signing::EMBEDDED_PUBLIC_KEY,cancel:Default::default(),resolutions:Default::default(),env:&env,fail_after_ops:None},&|phase,percent|println!("{percent}% {phase}"));
let stopped=coa_core::driver::run(root,coa_core::driver::Verb::StopAll);
println!("Shutdown after test: {:?}",stopped.map(|r|r.ok));
let outcome=outcome?;
println!("Final transaction: {:?}",outcome.txn.state);
env.ensure_stopped()?;
assert_eq!(outcome.txn.state,update::State::Committed);
Ok(())
use coa_core::{
registry::MetaDir,
update::{self, Env, RepackEnv},
};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let args: Vec<_> = std::env::args().collect();
if args.len() != 3 && args.len() != 4 {
return Err("usage: upgrade_fixture <disposable-root> <signed-package-directory>".into());
}
let root = std::path::Path::new(&args[1]);
assert!(
root.file_name()
.unwrap()
.to_string_lossy()
.starts_with("coa-schema-fixture-real")
&& root.join(".coa-update-fixture").is_file(),
"Disposable fixture required"
);
let meta = coa_core::registry::metadata_dir_for(root)?;
let (_, installed) = MetaDir::open(&meta)?;
assert_eq!(
coa_core::fsx::canonicalize_lenient(std::path::Path::new(&installed.server_path))?,
coa_core::fsx::canonicalize_lenient(root)?,
"Fixture metadata must point to the copy"
);
assert!(
installed.client_path.is_none(),
"Detach the real client from fixture metadata"
);
let env = RepackEnv {
root,
meta_dir: &meta,
};
if args.get(3).is_some_and(|flag| flag == "--validate-only") {
let result = env.validate();
let _ = coa_core::driver::run(root, coa_core::driver::Verb::StopAll);
result?;
println!("Startup and identity validation passed");
return Ok(());
}
let outcome = update::apply(
&update::Params {
root,
meta_dir: &meta,
source: coa_core::pkgsource::Source::Dir(args[2].clone().into()),
trusted_key: coa_core::signing::EMBEDDED_PUBLIC_KEY,
cancel: Default::default(),
resolutions: Default::default(),
env: &env,
fail_after_ops: None,
},
&|phase, percent| println!("{percent}% {phase}"),
);
let stopped = coa_core::driver::run(root, coa_core::driver::Verb::StopAll);
println!("Shutdown after test: {:?}", stopped.map(|r| r.ok));
let outcome = outcome?;
println!("Final transaction: {:?}", outcome.txn.state);
env.ensure_stopped()?;
assert_eq!(outcome.txn.state, update::State::Committed);
Ok(())
}
+28 -9
View File
@@ -261,7 +261,9 @@ pub fn config_files(root: &Path) -> Vec<String> {
for e in rd.flatten() {
let n = e.file_name().to_string_lossy().to_string();
// database.json holds generated database passwords; it is launcher state, not configuration.
if e.path().is_file() && (n.contains(".template") || n == "repack.json" || n == "docker.json") {
if e.path().is_file()
&& (n.contains(".template") || n == "repack.json" || n == "docker.json")
{
out.push(format!("Settings/{n}"));
}
}
@@ -381,12 +383,19 @@ pub fn create(
let build = || -> Result<Vec<Component>> {
let mut components = Vec::new();
let realm = crate::realms::state(root)?;
let mut databases: Vec<(String, &str)> = wanted_databases(kind).iter()
.map(|name| Ok((name.to_string(), realm.active.schema(name)?))).collect::<Result<_>>()?;
let mut databases: Vec<(String, &str)> = wanted_databases(kind)
.iter()
.map(|name| Ok((name.to_string(), realm.active.schema(name)?)))
.collect::<Result<_>>()?;
if kind != Kind::Config {
for other in realm.modes().into_iter().filter(|m| *m != realm.active) {
databases.push((format!("{}-characters", other.name()), other.schema("characters")?));
if kind == Kind::Full { databases.push((format!("{}-world", other.name()), other.schema("world")?)); }
databases.push((
format!("{}-characters", other.name()),
other.schema("characters")?,
));
if kind == Kind::Full {
databases.push((format!("{}-world", other.name()), other.schema("world")?));
}
}
}
if kind != Kind::Config && with_database(root, |db| db.schema_exists("acore_playerbots"))? {
@@ -427,16 +436,24 @@ pub fn create(
return Err(e);
}
};
let mysql_snapshot = if kind == Kind::Full && matches!(trigger, Trigger::BeforeUpdate | Trigger::BeforeRepair) && cfg!(windows) && !crate::docker::is_docker(root) {
let mysql_snapshot = if kind == Kind::Full
&& matches!(trigger, Trigger::BeforeUpdate | Trigger::BeforeRepair)
&& cfg!(windows)
&& !crate::docker::is_docker(root)
{
progress("Saving a complete stopped MySQL recovery copy");
match crate::mysql_snapshot::capture(root, &partial) {
Ok(snapshot) => Some(snapshot),
Err(error) => {
if let Ok(owned) = fsx::ensure_within(&backups_dir(meta), &partial) { let _ = fs::remove_dir_all(owned); }
if let Ok(owned) = fsx::ensure_within(&backups_dir(meta), &partial) {
let _ = fs::remove_dir_all(owned);
}
return Err(error);
}
}
} else { None };
} else {
None
};
let point = RecoveryPoint {
realm: crate::realms::state(root)?.active,
schema: 1,
@@ -485,7 +502,9 @@ pub fn verify(meta: &Path, id: &str) -> Result<VerifyReport> {
let dir = point_dir(meta, id)?;
let mut problems = Vec::new();
if let Some(snapshot) = &point.mysql_snapshot {
if let Err(error) = crate::mysql_snapshot::verify(&dir, snapshot) { problems.push(error.to_string()); }
if let Err(error) = crate::mysql_snapshot::verify(&dir, snapshot) {
problems.push(error.to_string());
}
}
let mut names = std::collections::BTreeSet::new();
let mut schemas = std::collections::BTreeSet::new();
+48 -16
View File
@@ -1,7 +1,7 @@
//! Signed channel pointers select one immutable package for an entire transaction.
use serde::{Deserialize, Serialize};
use crate::{Error, Result};
use crate::pkgsource::{fetch_small, Source};
use crate::{Error, Result};
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
@@ -21,15 +21,22 @@ pub struct Envelope {
}
pub fn verify(bytes: &[u8], channel: &str, key: &str) -> Result<Pointer> {
let envelope: Envelope = serde_json::from_slice(bytes).map_err(|e| Error::InvalidManifest(e.to_string()))?;
let envelope: Envelope =
serde_json::from_slice(bytes).map_err(|e| Error::InvalidManifest(e.to_string()))?;
crate::signing::verify(envelope.payload.as_bytes(), &envelope.signature, key)?;
let pointer: Pointer = serde_json::from_str(&envelope.payload).map_err(|e| Error::InvalidManifest(e.to_string()))?;
if pointer.schema != 1 || pointer.channel != channel
let pointer: Pointer = serde_json::from_str(&envelope.payload)
.map_err(|e| Error::InvalidManifest(e.to_string()))?;
if pointer.schema != 1
|| pointer.channel != channel
|| pointer.release_tag != format!("server-{}", pointer.version)
|| pointer.version.is_empty()
|| !pointer.version.bytes().all(|b| b.is_ascii_digit() || b == b'.')
|| !pointer
.version
.bytes()
.all(|b| b.is_ascii_digit() || b == b'.')
|| pointer.snapshot.len() != 64
|| !pointer.snapshot.bytes().all(|b| b.is_ascii_hexdigit()) {
|| !pointer.snapshot.bytes().all(|b| b.is_ascii_hexdigit())
{
return Err(Error::InvalidManifest("Invalid channel pointer".into()));
}
Ok(pointer)
@@ -39,21 +46,37 @@ pub fn resolve(channel: &str) -> Result<Source> {
if channel != "stable" && channel != "edge" {
return Err(Error::InvalidManifest("Unknown release channel".into()));
}
let source = Source::Url("https://raw.githubusercontent.com/Corfirean/coa-server-build/channels".into());
let source =
Source::Url("https://raw.githubusercontent.com/Corfirean/coa-server-build/channels".into());
let bytes = fetch_small(&source, &format!("{channel}.json"))?;
let pointer = verify(&bytes, channel, crate::signing::EMBEDDED_PUBLIC_KEY)?;
Ok(Source::Url(format!("https://github.com/Corfirean/coa-server-build/releases/download/{}", pointer.release_tag)))
Ok(Source::Url(format!(
"https://github.com/Corfirean/coa-server-build/releases/download/{}",
pointer.release_tag
)))
}
pub fn sign(pointer: &Pointer, seed: &str) -> Result<Vec<u8>> {
use base64::{engine::general_purpose::STANDARD, Engine};
use ed25519_dalek::{Signer, SigningKey};
let seed: [u8; 32] = STANDARD.decode(seed.trim()).map_err(|_| Error::Invalid("Invalid signing key".into()))?
.try_into().map_err(|_| Error::Invalid("Invalid signing key length".into()))?;
let seed: [u8; 32] = STANDARD
.decode(seed.trim())
.map_err(|_| Error::Invalid("Invalid signing key".into()))?
.try_into()
.map_err(|_| Error::Invalid("Invalid signing key length".into()))?;
let payload = serde_json::to_string(pointer).map_err(|e| Error::Invalid(e.to_string()))?;
let signature = STANDARD.encode(SigningKey::from_bytes(&seed).sign(payload.as_bytes()).to_bytes());
let bytes = serde_json::to_vec(&Envelope { payload, signature }).map_err(|e| Error::Invalid(e.to_string()))?;
verify(&bytes, &pointer.channel, crate::signing::EMBEDDED_PUBLIC_KEY)?;
let signature = STANDARD.encode(
SigningKey::from_bytes(&seed)
.sign(payload.as_bytes())
.to_bytes(),
);
let bytes = serde_json::to_vec(&Envelope { payload, signature })
.map_err(|e| Error::Invalid(e.to_string()))?;
verify(
&bytes,
&pointer.channel,
crate::signing::EMBEDDED_PUBLIC_KEY,
)?;
Ok(bytes)
}
@@ -67,12 +90,21 @@ mod tests {
let sk = SigningKey::from_bytes(&[17; 32]);
let payload = serde_json::to_string(pointer).unwrap();
let signature = STANDARD.encode(sk.sign(payload.as_bytes()).to_bytes());
(serde_json::to_vec(&Envelope { payload, signature }).unwrap(), STANDARD.encode(sk.verifying_key().to_bytes()))
(
serde_json::to_vec(&Envelope { payload, signature }).unwrap(),
STANDARD.encode(sk.verifying_key().to_bytes()),
)
}
#[test]
fn verifies_identity_signature_and_immutable_tag() {
let mut p = Pointer { schema: 1, channel: "stable".into(), version: "0.261010.40".into(), release_tag: "server-0.261010.40".into(), snapshot: "a".repeat(64) };
let mut p = Pointer {
schema: 1,
channel: "stable".into(),
version: "0.261010.40".into(),
release_tag: "server-0.261010.40".into(),
snapshot: "a".repeat(64),
};
let (bytes, key) = signed(&p);
assert_eq!(verify(&bytes, "stable", &key).unwrap().version, p.version);
assert!(verify(&bytes, "edge", &key).is_err());
+61 -14
View File
@@ -417,11 +417,21 @@ pub fn launch(client: &Path) -> Result<u32> {
return crate::wine::launch(client, exe);
}
let executable = client.join(exe);
let spawn = || Command::new(&executable).current_dir(client).spawn().map(|child| child.id());
let spawn = || {
Command::new(&executable)
.current_dir(client)
.spawn()
.map(|child| child.id())
};
#[cfg(windows)]
{ launch_with_elevation_fallback(spawn, || launch_elevated(&executable, client)).map_err(Into::into) }
{
launch_with_elevation_fallback(spawn, || launch_elevated(&executable, client))
.map_err(Into::into)
}
#[cfg(not(windows))]
{ spawn().map_err(Into::into) }
{
spawn().map_err(Into::into)
}
}
/// Start normally first; ask Windows for elevation only when the client requires it (ERROR_ELEVATION_REQUIRED, 740).
@@ -443,9 +453,15 @@ fn launch_elevated(executable: &Path, directory: &Path) -> std::io::Result<u32>
use std::os::windows::ffi::OsStrExt;
use windows_sys::Win32::Foundation::CloseHandle;
use windows_sys::Win32::System::Threading::GetProcessId;
use windows_sys::Win32::UI::Shell::{ShellExecuteExW, SHELLEXECUTEINFOW, SEE_MASK_NOCLOSEPROCESS, SEE_MASK_NOASYNC};
use windows_sys::Win32::UI::Shell::{
ShellExecuteExW, SEE_MASK_NOASYNC, SEE_MASK_NOCLOSEPROCESS, SHELLEXECUTEINFOW,
};
use windows_sys::Win32::UI::WindowsAndMessaging::SW_SHOWNORMAL;
let file: Vec<u16> = executable.as_os_str().encode_wide().chain(Some(0)).collect();
let file: Vec<u16> = executable
.as_os_str()
.encode_wide()
.chain(Some(0))
.collect();
let cwd: Vec<u16> = directory.as_os_str().encode_wide().chain(Some(0)).collect();
let verb: Vec<u16> = "runas".encode_utf16().chain(Some(0)).collect();
let mut info = SHELLEXECUTEINFOW {
@@ -457,12 +473,22 @@ fn launch_elevated(executable: &Path, directory: &Path) -> std::io::Result<u32>
nShow: SW_SHOWNORMAL,
..Default::default()
};
if unsafe { ShellExecuteExW(&mut info) } == 0 { return Err(std::io::Error::last_os_error()); }
if info.hProcess.is_null() { return Err(std::io::Error::other("Windows did not return the game process handle.")); }
if unsafe { ShellExecuteExW(&mut info) } == 0 {
return Err(std::io::Error::last_os_error());
}
if info.hProcess.is_null() {
return Err(std::io::Error::other(
"Windows did not return the game process handle.",
));
}
let pid = unsafe { GetProcessId(info.hProcess) };
let error = std::io::Error::last_os_error();
unsafe { CloseHandle(info.hProcess); }
if pid == 0 { return Err(error); }
unsafe {
CloseHandle(info.hProcess);
}
if pid == 0 {
return Err(error);
}
Ok(pid)
}
@@ -585,11 +611,29 @@ mod tests {
#[cfg(windows)]
#[test]
fn elevation_is_requested_only_when_windows_requires_it() {
assert_eq!(launch_with_elevation_fallback(|| Ok(17), || panic!("unneeded elevation")).unwrap(), 17);
assert_eq!(launch_with_elevation_fallback(|| Err(std::io::Error::from_raw_os_error(740)), || Ok(23)).unwrap(), 23);
let error = launch_with_elevation_fallback(|| Err(std::io::Error::from_raw_os_error(2)), || panic!("wrong error elevated")).unwrap_err();
assert_eq!(
launch_with_elevation_fallback(|| Ok(17), || panic!("unneeded elevation")).unwrap(),
17
);
assert_eq!(
launch_with_elevation_fallback(
|| Err(std::io::Error::from_raw_os_error(740)),
|| Ok(23)
)
.unwrap(),
23
);
let error = launch_with_elevation_fallback(
|| Err(std::io::Error::from_raw_os_error(2)),
|| panic!("wrong error elevated"),
)
.unwrap_err();
assert_eq!(error.raw_os_error(), Some(2));
let cancelled = launch_with_elevation_fallback(|| Err(std::io::Error::from_raw_os_error(740)), || Err(std::io::Error::from_raw_os_error(1223))).unwrap_err();
let cancelled = launch_with_elevation_fallback(
|| Err(std::io::Error::from_raw_os_error(740)),
|| Err(std::io::Error::from_raw_os_error(1223)),
)
.unwrap_err();
assert_eq!(cancelled.raw_os_error(), Some(1223));
}
@@ -620,7 +664,10 @@ mod tests {
assert!(sync_realm(&c, &meta, crate::realms::Mode::Wildcard).unwrap());
assert_eq!(fs::read(c.join("WTF/Config.wtf")).unwrap(), original);
assert!(sync_realm(&c, &meta, crate::realms::Mode::Reborn).unwrap());
assert_eq!(fs::read(c.join("WTF/Config.wtf")).unwrap(), b"SET sound 1\r\nSET realmName \"Warcraft Reborn\"\r\n");
assert_eq!(
fs::read(c.join("WTF/Config.wtf")).unwrap(),
b"SET sound 1\r\nSET realmName \"Warcraft Reborn\"\r\n"
);
}
#[test]
+10 -2
View File
@@ -61,8 +61,16 @@ pub fn lines_from_text(text: &str, filter: Option<&str>, max_lines: usize) -> Ve
let out: Vec<Line> = text
.lines()
.filter(|l| !l.trim().is_empty())
.filter(|l| needle.as_ref().map(|n| l.to_lowercase().contains(n)).unwrap_or(true))
.map(|l| Line { level: classify(l), text: crate::diag::redact(l) })
.filter(|l| {
needle
.as_ref()
.map(|n| l.to_lowercase().contains(n))
.unwrap_or(true)
})
.map(|l| Line {
level: classify(l),
text: crate::diag::redact(l),
})
.collect();
let skip = out.len().saturating_sub(max_lines);
out.into_iter().skip(skip).collect()
+256 -2
View File
@@ -64,8 +64,31 @@ impl LocalBackend {
}
fn access(&self, local_id: &str) -> Result<RealmAccess> {
find_access(&self.descriptors, &(self.installs)(), local_id)
.ok_or_else(|| Error::Invalid("That realm is not known to this Manager.".into()))
let access =
find_access(&self.descriptors, &(self.installs)(), local_id).ok_or_else(|| {
Error::Invalid(format!(
"That realm is not known to this Manager: {local_id}"
))
})?;
if let Some((_base, rs)) = local_id.split_once(':') {
let expected_mode = match rs {
"coa" => crate::realms::Mode::Coa,
"wildcard" => crate::realms::Mode::Wildcard,
"reborn" => crate::realms::Mode::Reborn,
_ => {
return Err(Error::Invalid(format!(
"Malformed or unknown ruleset suffix in local_id: {rs}"
)))
}
};
if access.mode != Some(expected_mode) {
return Err(Error::Invalid(format!(
"Realm access mode {:?} does not match expected ruleset in local_id {local_id}",
access.mode
)));
}
}
Ok(access)
}
fn account(&self, local_id: &str, filter: &str) -> Result<Option<AccountRow>> {
@@ -86,9 +109,39 @@ impl LocalBackend {
impl RealmBackend for LocalBackend {
fn info(&self, local_id: &str) -> Result<RealmInfo> {
let cfg = settings::load(&self.settings_dir)?.realms.remove(local_id);
let access = self.access(local_id)?;
let db = access.db()?;
let ruleset = realm::ruleset_of(&db).map_err(|e| Error::Invalid(e.to_string()))?;
// Explicit local-id -> ruleset invariant:
// local_id ruleset == RealmAccess.mode == Db.realm() == RealmInfo.ruleset
if let Some((_base, rs)) = local_id.split_once(':') {
let expected_ruleset: crate::portable::Ruleset = rs
.parse()
.map_err(|_| Error::Invalid(format!("Unknown ruleset in local_id: {rs}")))?;
if ruleset != expected_ruleset {
return Err(Error::Invalid(format!(
"Ruleset of realm DB ({ruleset:?}) does not match local_id {local_id}"
)));
}
if access.mode.map(|m| m.name()) != Some(expected_ruleset.as_str()) {
return Err(Error::Invalid(format!(
"RealmAccess mode ({:?}) does not match local_id {local_id}",
access.mode
)));
}
if db.realm().name() != expected_ruleset.as_str() {
return Err(Error::Invalid(format!(
"Db realm ({:?}) does not match local_id {local_id}",
db.realm()
)));
}
}
Ok(RealmInfo {
automatic: cfg.as_ref().is_none_or(|c| !c.existing_only),
route: cfg.and_then(|c| c.route),
ruleset,
})
}
@@ -211,6 +264,7 @@ impl RealmBackend for LocalBackend {
.map_err(|e| unavailable("export", e))?;
Ok(ClaimExport {
character_id: bundle.character_id.as_uuid(),
ruleset: bundle.ruleset,
payload: bundle.payload,
sha256: bundle.content_hash,
collections: bundle.collections,
@@ -243,4 +297,204 @@ impl RealmBackend for LocalBackend {
.map_err(|e| unavailable("portable engine", e))?
.map_err(|e| unavailable("import remote", e))
}
fn world_port(&self, local_id: &str) -> Result<u16> {
if let Ok(override_port) = std::env::var("COA_OVERRIDE_LOCAL_WORLD_PORT") {
if let Ok(p) = override_port.parse::<u16>() {
return Ok(p);
}
}
let access = self.access(local_id)?;
let mode = if let Some(m) = access.mode {
m
} else if let Some((_base, _rs)) = local_id.split_once(':') {
return Err(Error::Invalid(format!(
"Unresolved mode for ruleset suffix in {local_id}"
)));
} else {
// Legacy unsuffixed CoA realm ONLY
crate::realms::Mode::Coa
};
if let Some(ref root) = access.root {
crate::realms::world_port_for_mode(root, mode)
} else {
Err(Error::Invalid(format!(
"No server installation root for {local_id} to resolve world port"
)))
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
use tempfile::tempdir;
#[test]
fn unreadable_or_unknown_realm_fails_closed_in_info() {
let dir = tempdir().unwrap();
let settings = dir.path().join("Settings");
fs::create_dir_all(&settings).unwrap();
fs::write(settings.join("registry.json"), "{}").unwrap();
let desc_dir = dir.path().join("descriptors");
fs::create_dir_all(&desc_dir).unwrap();
let portable_dir = dir.path().join("portable");
let rt = PortableRuntime::start(&portable_dir, Box::new(Vec::new), None).unwrap();
let backend = LocalBackend::new(Arc::new(rt), &settings, &desc_dir, Arc::new(Vec::new));
// Unknown realm id must return Err, never Ok(RealmInfo { ruleset: Ruleset::Coa, .. })
assert!(backend.info("srv-unknown").is_err());
assert!(backend.info("srv-unknown:wildcard").is_err());
assert!(backend.info("srv-unknown:reborn").is_err());
}
#[test]
fn world_port_for_mode_distinguishes_simultaneous_realms() {
let dir = tempdir().unwrap();
let root = dir.path().join("srv");
fs::create_dir_all(root.join("Settings")).unwrap();
fs::write(root.join("Settings/repack.json"), r#"{"worldPort": 8085}"#).unwrap();
fs::write(
root.join("Settings/realm-profile.json"),
r#"{"active": "coa", "wildcard_created": true, "simultaneous": true, "secondary_world_port": 8086}"#,
)
.unwrap();
assert_eq!(
crate::realms::world_port_for_mode(&root, crate::realms::Mode::Coa).unwrap(),
8085
);
assert_eq!(
crate::realms::world_port_for_mode(&root, crate::realms::Mode::Wildcard).unwrap(),
8086
);
let desc_dir = dir.path().join("descriptors");
let portable_dir = dir.path().join("portable");
let rt = PortableRuntime::start(&portable_dir, Box::new(Vec::new), None).unwrap();
let root_clone = root.clone();
let backend = LocalBackend::new(
Arc::new(rt),
root.join("Settings"),
&desc_dir,
Arc::new(move || vec![("test1".to_string(), root_clone.clone())]),
);
assert_eq!(backend.world_port("srv-test1:coa").unwrap(), 8085);
assert_eq!(backend.world_port("srv-test1:wildcard").unwrap(), 8086);
// When simultaneous is false and active is CoA:
fs::write(
root.join("Settings/realm-profile.json"),
r#"{"active": "coa", "wildcard_created": true, "simultaneous": false}"#,
)
.unwrap();
// CoA succeeds with 8085
assert_eq!(backend.world_port("srv-test1:coa").unwrap(), 8085);
// Wildcard must FAIL CLOSED, never return 8085
let err_wc_mode =
crate::realms::world_port_for_mode(&root, crate::realms::Mode::Wildcard).unwrap_err();
assert!(
err_wc_mode.to_string().contains("not active"),
"Expected not active error, got: {err_wc_mode}"
);
assert!(backend.world_port("srv-test1:wildcard").is_err());
// Reborn must FAIL CLOSED
let err_reb_mode =
crate::realms::world_port_for_mode(&root, crate::realms::Mode::Reborn).unwrap_err();
assert!(
err_reb_mode.to_string().contains("not active"),
"Expected not active error, got: {err_reb_mode}"
);
assert!(backend.world_port("srv-test1:reborn").is_err());
// When active is Reborn:
fs::write(
root.join("Settings/realm-profile.json"),
r#"{"active": "reborn", "wildcard_created": true, "reborn_created": true, "simultaneous": false}"#,
)
.unwrap();
// Reborn succeeds with primary world port 8085
assert_eq!(backend.world_port("srv-test1:reborn").unwrap(), 8085);
// CoA must FAIL CLOSED when Reborn is active
assert!(backend.world_port("srv-test1:coa").is_err());
// Wildcard must FAIL CLOSED when Reborn is active
assert!(backend.world_port("srv-test1:wildcard").is_err());
// Malformed and unknown suffixes must fail closed
assert!(backend.access("srv-test1:unknown").is_err());
assert!(backend.access("srv-test1:garbage").is_err());
assert!(backend.access("srv-test1:coa:extra").is_err());
assert!(backend.world_port("srv-test1:unknown").is_err());
assert!(backend.world_port("srv-test1:garbage").is_err());
}
#[test]
fn world_port_lookup_failure_causes_direct_and_relay_to_fail_closed() {
let dir = tempdir().unwrap();
let root = dir.path().join("srv");
fs::create_dir_all(root.join("Settings")).unwrap();
fs::write(root.join("Settings/repack.json"), r#"{"worldPort": 8085}"#).unwrap();
// Server only has active CoA, simultaneous is off
fs::write(
root.join("Settings/realm-profile.json"),
r#"{"active": "coa", "wildcard_created": false, "simultaneous": false}"#,
)
.unwrap();
let desc_dir = dir.path().join("descriptors");
let portable_dir = dir.path().join("portable");
let rt = PortableRuntime::start(&portable_dir, Box::new(Vec::new), None).unwrap();
let root_clone = root.clone();
let backend = Arc::new(LocalBackend::new(
Arc::new(rt),
root.join("Settings"),
&desc_dir,
Arc::new(move || vec![("test1".to_string(), root_clone.clone())]),
));
let store = Arc::new(std::sync::Mutex::new(
crate::control::store::ControlStore::open_in_memory().unwrap(),
));
let service = Arc::new(crate::control::service::HostService::new(
"srv-test1:wildcard",
coa_registry_proto::sign::RealmId::new(),
store,
backend,
));
// 1. HostService::local_world_port fails closed
assert!(service.local_world_port().is_err());
// 2. Direct route manager cannot find a direct route because world port resolution failed
let mut direct_mgr =
crate::control::direct_route::DirectRouteManager::start(None, service.clone());
assert!(!direct_mgr.is_direct_ready());
assert!(service.direct_route().is_none());
direct_mgr.shutdown();
// 3. When relay link has no world port resolved, AllocateRelay refuses
let mut session = crate::control::service::Session::default();
let player = uuid::Uuid::now_v7();
let resp = service.handle(
&mut session,
&player,
"KEY",
coa_control_proto::app::Request::AllocateRelay { player_id: player },
);
assert!(matches!(
resp,
coa_control_proto::app::Response::Error {
code: coa_control_proto::app::AppError::NoAccount
| coa_control_proto::app::AppError::RelayUnavailable,
..
}
));
}
}
+171 -47
View File
@@ -33,8 +33,13 @@ impl DirectIngress {
local_auth_port: u16,
local_world_port: u16,
) -> Result<Self> {
let auth_host = if auth_bind_port == 0 {
"127.0.0.1"
} else {
"0.0.0.0"
};
let auth_listener =
TcpListener::bind(format!("0.0.0.0:{auth_bind_port}")).map_err(|e| {
TcpListener::bind(format!("{auth_host}:{auth_bind_port}")).map_err(|e| {
Error::Invalid(format!(
"Cannot bind direct auth listener on port {auth_bind_port}: {e}"
))
@@ -47,8 +52,13 @@ impl DirectIngress {
.map_err(|e| Error::Invalid(e.to_string()))?
.port();
let world_host = if world_bind_port == 0 {
"127.0.0.1"
} else {
"0.0.0.0"
};
let world_listener =
TcpListener::bind(format!("0.0.0.0:{world_bind_port}")).map_err(|e| {
TcpListener::bind(format!("{world_host}:{world_bind_port}")).map_err(|e| {
Error::Invalid(format!(
"Cannot bind direct world listener on port {world_bind_port}: {e}"
))
@@ -114,7 +124,11 @@ impl DirectIngress {
std::thread::Builder::new()
.name("direct-world-worker".into())
.spawn(move || {
let _ = handle_world_client(client_stream, local_world_port);
if let Err(e) =
handle_world_client(client_stream, local_world_port)
{
eprintln!("handle_world_client error: {e}");
}
})
.ok();
}
@@ -174,8 +188,21 @@ fn handle_auth_client(
local_auth_port: u16,
world_target: Arc<std::sync::RwLock<String>>,
) -> Result<()> {
let mut server = TcpStream::connect(format!("127.0.0.1:{local_auth_port}"))
.map_err(|e| Error::Invalid(format!("Cannot connect to local authserver: {e}")))?;
let mut server = None;
for _ in 0..5 {
match TcpStream::connect(format!("127.0.0.1:{local_auth_port}")) {
Ok(s) => {
server = Some(s);
break;
}
Err(_) => std::thread::sleep(Duration::from_millis(20)),
}
}
let mut server = server.ok_or_else(|| {
Error::Invalid(format!(
"Cannot connect to local authserver: {local_auth_port}"
))
})?;
let _ = client.set_read_timeout(Some(Duration::from_millis(500)));
let _ = server.set_read_timeout(Some(Duration::from_millis(500)));
@@ -213,7 +240,7 @@ fn handle_auth_client(
}
done_c.store(true, Ordering::Relaxed);
if let Some(s) = server_shutdown {
let _ = s.shutdown(std::net::Shutdown::Both);
let _ = s.shutdown(std::net::Shutdown::Write);
}
});
@@ -261,8 +288,21 @@ fn handle_auth_client(
}
fn handle_world_client(mut client: TcpStream, local_world_port: u16) -> Result<()> {
let mut server = TcpStream::connect(format!("127.0.0.1:{local_world_port}"))
.map_err(|e| Error::Invalid(format!("Cannot connect to local worldserver: {e}")))?;
let mut server = None;
for _ in 0..5 {
match TcpStream::connect(format!("127.0.0.1:{local_world_port}")) {
Ok(s) => {
server = Some(s);
break;
}
Err(_) => std::thread::sleep(Duration::from_millis(20)),
}
}
let mut server = server.ok_or_else(|| {
Error::Invalid(format!(
"Cannot connect to local worldserver: {local_world_port}"
))
})?;
let _ = client.set_nonblocking(false);
let _ = server.set_nonblocking(false);
@@ -278,11 +318,11 @@ fn handle_world_client(mut client: TcpStream, local_world_port: u16) -> Result<(
let t_c2s = std::thread::spawn(move || {
let _ = std::io::copy(&mut client_read, &mut server_write);
let _ = server_write.shutdown(std::net::Shutdown::Both);
let _ = server_write.shutdown(std::net::Shutdown::Write);
});
let _ = std::io::copy(&mut server, &mut client);
let _ = client.shutdown(std::net::Shutdown::Both);
let _ = client.shutdown(std::net::Shutdown::Write);
let _ = t_c2s.join();
Ok(())
@@ -320,6 +360,7 @@ mod tests {
let n = stream.read(&mut buf).unwrap();
assert_eq!(&buf[..n], b"WORLD_PING");
stream.write_all(b"WORLD_PONG").unwrap();
stream.flush().unwrap();
let _ = stream.shutdown(std::net::Shutdown::Write);
});
@@ -337,25 +378,27 @@ mod tests {
let mut buf = [0u8; 16];
let _ = stream.read(&mut buf).unwrap();
let mut fake_realm_list = vec![
0x10, // Opcode CMD_REALM_LIST
0x00, 0x00, // Size placeholder
0x00, 0x00, 0x00, 0x00, // Unused
0x01, 0x00, // Realm count: 1
0x01, 0x00, 0x00, 0x00, // Icon
0x00, // Lock
0x00, // Flags
];
fake_realm_list.extend_from_slice(b"RealmOne\0");
fake_realm_list.extend_from_slice(b"127.0.0.1:8085\0"); // original target
fake_realm_list.extend_from_slice(&[0x00, 0x00, 0x00, 0x00]); // Population
fake_realm_list.extend_from_slice(&[0x01]); // Num characters
fake_realm_list.extend_from_slice(&[0x01]); // Timezone
fake_realm_list.extend_from_slice(&[0x00]); // Realm ID
fake_realm_list.extend_from_slice(&[0x02, 0x00]); // Footer
let name_bytes = b"RealmOne\0";
let addr_bytes = b"127.0.0.1:8085\0";
let body_len = 4 + 2 + 3 + name_bytes.len() + addr_bytes.len() + 4 + 1 + 1 + 1 + 2;
let body_len = (fake_realm_list.len() - 3) as u16;
fake_realm_list[1..3].copy_from_slice(&body_len.to_le_bytes());
let mut fake_realm_list = Vec::new();
fake_realm_list.push(0x10); // Opcode
fake_realm_list.extend_from_slice(&(body_len as u16).to_le_bytes()); // Length
fake_realm_list.extend_from_slice(&0u32.to_le_bytes()); // Unused
fake_realm_list.extend_from_slice(&1u16.to_le_bytes()); // Realm count = 1
// Realm info:
fake_realm_list.extend_from_slice(&[1, 0, 0]); // type, lock, flag
fake_realm_list.extend_from_slice(name_bytes);
fake_realm_list.extend_from_slice(addr_bytes);
fake_realm_list.extend_from_slice(&[0, 0, 0, 0]); // pop
fake_realm_list.extend_from_slice(&[0]); // chars
fake_realm_list.extend_from_slice(&[1]); // timezone
fake_realm_list.extend_from_slice(&[1]); // realm id
// Footer:
fake_realm_list.extend_from_slice(&[0x10, 0x00]);
stream.write_all(&fake_realm_list).unwrap();
let _ = stream.shutdown(std::net::Shutdown::Write);
@@ -386,7 +429,7 @@ mod tests {
let mock_world_port = mock_world.local_addr().unwrap().port();
// DirectIngress binds to ephemeral ports (0, 0), so actual ingress port != 8085
let ingress = DirectIngress::start(
let mut ingress = DirectIngress::start(
0,
0,
"198.51.100.1".to_string(),
@@ -415,25 +458,27 @@ mod tests {
let mut buf = [0u8; 16];
let _ = stream.read(&mut buf).unwrap();
let mut fake_realm_list = vec![
0x10, // Opcode CMD_REALM_LIST
0x00, 0x00, // Size placeholder
0x00, 0x00, 0x00, 0x00, // Unused
0x01, 0x00, // Realm count: 1
0x01, 0x00, 0x00, 0x00, // Icon
0x00, // Lock
0x00, // Flags
];
fake_realm_list.extend_from_slice(b"RealmOne\0");
fake_realm_list.extend_from_slice(b"127.0.0.1:8085\0");
fake_realm_list.extend_from_slice(&[0x00, 0x00, 0x00, 0x00]);
fake_realm_list.extend_from_slice(&[0x01]);
fake_realm_list.extend_from_slice(&[0x01]);
fake_realm_list.extend_from_slice(&[0x00]);
fake_realm_list.extend_from_slice(&[0x02, 0x00]);
let name_bytes = b"RealmOne\0";
let addr_bytes = b"127.0.0.1:8085\0";
let body_len = 4 + 2 + 3 + name_bytes.len() + addr_bytes.len() + 4 + 1 + 1 + 1 + 2;
let body_len = (fake_realm_list.len() - 3) as u16;
fake_realm_list[1..3].copy_from_slice(&body_len.to_le_bytes());
let mut fake_realm_list = Vec::new();
fake_realm_list.push(0x10); // Opcode
fake_realm_list.extend_from_slice(&(body_len as u16).to_le_bytes()); // Length
fake_realm_list.extend_from_slice(&0u32.to_le_bytes()); // Unused
fake_realm_list.extend_from_slice(&1u16.to_le_bytes()); // Realm count = 1
// Realm info:
fake_realm_list.extend_from_slice(&[1, 0, 0]); // type, lock, flag
fake_realm_list.extend_from_slice(name_bytes);
fake_realm_list.extend_from_slice(addr_bytes);
fake_realm_list.extend_from_slice(&[0, 0, 0, 0]); // pop
fake_realm_list.extend_from_slice(&[0]); // chars
fake_realm_list.extend_from_slice(&[1]); // timezone
fake_realm_list.extend_from_slice(&[1]); // realm id
// Footer:
fake_realm_list.extend_from_slice(&[0x10, 0x00]);
stream.write_all(&fake_realm_list).unwrap();
let _ = stream.shutdown(std::net::Shutdown::Write);
@@ -462,5 +507,84 @@ mod tests {
drop(client_auth);
t_auth.join().unwrap();
ingress.stop();
}
#[test]
fn test_direct_ingress_wildcard_port_rewrites_to_mapped_port_and_never_advertises_coa_8085() {
let ext_wildcard_port = 48086;
let mock_auth = TcpListener::bind("127.0.0.1:0").unwrap();
let mock_auth_port = mock_auth.local_addr().unwrap().port();
let mock_world = TcpListener::bind("127.0.0.1:0").unwrap();
let mock_world_port = mock_world.local_addr().unwrap().port();
// DirectIngress configured for Wildcard (local_world = mock_world_port, ext_world = 48086)
let mut ingress = DirectIngress::start(
0,
0,
"198.51.100.1".to_string(),
ext_wildcard_port,
mock_auth_port,
mock_world_port,
)
.unwrap();
// Verify Auth rewrite rewrites to external port 48086 and never mentions 8085 or 8086
let t_auth = std::thread::spawn(move || {
let (mut stream, _) = mock_auth.accept().unwrap();
let mut buf = [0u8; 16];
let _ = stream.read(&mut buf).unwrap();
let name_bytes = b"Wildcard\0";
let addr_bytes = b"127.0.0.1:8086\0";
let body_len = 4 + 2 + 3 + name_bytes.len() + addr_bytes.len() + 4 + 1 + 1 + 1 + 2;
let mut fake_realm_list = Vec::new();
fake_realm_list.push(0x10); // Opcode
fake_realm_list.extend_from_slice(&(body_len as u16).to_le_bytes()); // Length
fake_realm_list.extend_from_slice(&0u32.to_le_bytes()); // Unused
fake_realm_list.extend_from_slice(&1u16.to_le_bytes()); // Realm count = 1
// Realm info:
fake_realm_list.extend_from_slice(&[1, 0, 0]); // type, lock, flag
fake_realm_list.extend_from_slice(name_bytes);
fake_realm_list.extend_from_slice(addr_bytes);
fake_realm_list.extend_from_slice(&[0, 0, 0, 0]); // pop
fake_realm_list.extend_from_slice(&[0]); // chars
fake_realm_list.extend_from_slice(&[1]); // timezone
fake_realm_list.extend_from_slice(&[1]); // realm id
// Footer:
fake_realm_list.extend_from_slice(&[0x10, 0x00]);
stream.write_all(&fake_realm_list).unwrap();
let _ = stream.shutdown(std::net::Shutdown::Write);
});
let mut client_auth =
TcpStream::connect(format!("127.0.0.1:{}", ingress.auth_port())).unwrap();
client_auth.write_all(b"AUTH_HELLO").unwrap();
let mut auth_buf = [0u8; 512];
let an = client_auth.read(&mut auth_buf).unwrap();
let payload = String::from_utf8_lossy(&auth_buf[..an]);
assert!(
payload.contains("198.51.100.1:48086"),
"Expected rewritten realm list to contain external port 48086, got: {payload}"
);
assert!(
!payload.contains("8085"),
"DirectIngress for Wildcard must never advertise CoA port 8085"
);
assert!(
!payload.contains(":8086"),
"DirectIngress for Wildcard must rewrite internal port 8086 to external 48086"
);
drop(client_auth);
t_auth.join().unwrap();
ingress.stop();
}
}
+18 -3
View File
@@ -304,10 +304,25 @@ fn attempt_route_discovery(
.ok()
.and_then(|p| p.parse().ok())
.unwrap_or(coa_control_proto::relay::LOCAL_AUTH_PORT);
let local_world = std::env::var("COA_OVERRIDE_LOCAL_WORLD_PORT")
let local_world = match std::env::var("COA_OVERRIDE_LOCAL_WORLD_PORT")
.ok()
.and_then(|p| p.parse().ok())
.unwrap_or(coa_control_proto::relay::LOCAL_WORLD_PORT);
{
Some(p) => p,
None => match service.local_world_port() {
Ok(p) => p,
Err(e) => {
set_status(
status,
RouteStatus::RelayOnly {
reason: format!("Cannot resolve local world port: {e}"),
},
);
service.set_direct_route(None);
return;
}
},
};
let desired_auth_port: u16 = std::env::var("COA_DIRECT_AUTH_PORT")
.ok()
@@ -316,7 +331,7 @@ fn attempt_route_discovery(
let desired_world_port: u16 = std::env::var("COA_DIRECT_WORLD_PORT")
.ok()
.and_then(|p| p.parse().ok())
.unwrap_or(8085);
.unwrap_or(local_world);
let ingress = match DirectIngress::start(
desired_auth_port,
+21 -12
View File
@@ -95,18 +95,27 @@ impl HostControl {
store.clone(),
backend.clone(),
));
let relay_link =
crate::control::transport::relay_url(&base, "/relay/v1/host").map(
|r_url| {
let rl = crate::control::relay_link::RelayLink::start(
r_url,
realm_id,
key.clone(),
);
service.set_relay(rl.clone());
rl
},
);
let relay_link = match service.local_world_port() {
Ok(world_port) => {
crate::control::transport::relay_url(&base, "/relay/v1/host").map(
|r_url| {
let rl =
crate::control::relay_link::RelayLink::start_with_ports(
r_url,
realm_id,
key.clone(),
Some(world_port),
);
service.set_relay(rl.clone());
rl
},
)
}
Err(e) => {
eprintln!("Relay link unavailable for {local_id}: cannot resolve world port: {e}");
None
}
};
let direct_route =
Some(crate::control::direct_route::DirectRouteManager::start(
Some(base.clone()),
+7 -2
View File
@@ -115,6 +115,7 @@ pub struct AccountOutcome {
#[derive(Debug, Clone)]
pub struct Claimed {
pub character_id: Uuid,
pub ruleset: String,
pub payload: Vec<u8>,
pub sha256: [u8; 32],
pub collections: BTreeMap<String, Vec<u32>>,
@@ -347,13 +348,14 @@ impl PlayerControl {
pub fn claim(&self, ch: &mut PlayerChannel, token: u32) -> R<Claimed> {
let r = ch.request(&Request::Claim { token })?;
let (character_id, sha256, payload, collections) = expect(r, |r| match r {
let (character_id, ruleset, sha256, payload, collections) = expect(r, |r| match r {
Response::Claimed {
character_id,
ruleset,
sha256,
payload,
collections,
} => Ok((character_id, sha256, payload, collections)),
} => Ok((character_id, ruleset, sha256, payload, collections)),
other => Err(other),
})?;
let payload = base64::engine::general_purpose::STANDARD
@@ -373,6 +375,7 @@ impl PlayerControl {
})?;
Ok(Claimed {
character_id,
ruleset,
payload,
sha256: hash,
collections,
@@ -413,6 +416,7 @@ impl PlayerControl {
&self,
ch: &mut PlayerChannel,
character_id: Uuid,
ruleset: &str,
canonical_revision: u64,
payload: &[u8],
content_hash: [u8; 32],
@@ -423,6 +427,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(),
+28 -4
View File
@@ -71,6 +71,15 @@ impl RelayProvider for RelayLink {
impl RelayLink {
pub fn start(url: String, realm_id: RealmId, key: SigningKey) -> Arc<Self> {
Self::start_with_ports(url, realm_id, key, None)
}
pub fn start_with_ports(
url: String,
realm_id: RealmId,
key: SigningKey,
local_world_port: Option<u16>,
) -> Arc<Self> {
let stop = Arc::new(AtomicBool::new(false));
let status = Arc::new(Mutex::new(RelayStatus::default()));
let (alloc_tx, alloc_rx) = channel();
@@ -79,7 +88,7 @@ impl RelayLink {
let st = status.clone();
let join = std::thread::Builder::new()
.name("control-relay-host".into())
.spawn(move || run(&url, realm_id, &key, alloc_rx, &s, &st))
.spawn(move || run(&url, realm_id, &key, alloc_rx, &s, &st, local_world_port))
.ok();
Arc::new(RelayLink {
@@ -127,11 +136,12 @@ fn run(
)>,
stop: &AtomicBool,
status: &Mutex<RelayStatus>,
local_world_port: Option<u16>,
) {
let mut failures = 0u32;
while !stop.load(Ordering::SeqCst) {
let began = Instant::now();
let result = session(url, realm, key, &alloc_rx, stop, status);
let result = session(url, realm, key, &alloc_rx, stop, status, local_world_port);
set_status(status, |s| {
s.connected = false;
s.active_streams = 0;
@@ -176,6 +186,7 @@ fn session(
)>,
stop: &AtomicBool,
status: &Mutex<RelayStatus>,
local_world_port: Option<u16>,
) -> Result<(), LinkError> {
let mut ws = transport::connect(url, POLL)?;
@@ -305,8 +316,21 @@ fn session(
TunnelMsg::Connect {
stream_id, target, ..
} => {
// Strictly predefined local targets: Auth (3724) or World (8085)
let local_port = target.local_port();
// Strictly predefined local targets: Auth (3724) or World (8085 or bound realm world port)
let local_port = match target {
RelayTarget::Auth => target.local_port(),
RelayTarget::World => match local_world_port {
Some(p) => p,
None => {
eprintln!("RelayLink cannot connect to World: local_world_port was not provided (fail-closed)");
let _ = ws_out_tx.send(TunnelMsg::ConnectErr {
stream_id,
error: "World port unresolved".into(),
});
continue;
}
},
};
match TcpStream::connect(("127.0.0.1", local_port)) {
Ok(tcp) => {
let (stream_tx, stream_rx) = channel::<TunnelMsg>();
+314 -29
View File
@@ -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<String>,
pub ruleset: crate::portable::model::Ruleset,
}
#[derive(Clone, Debug, PartialEq, Eq)]
@@ -55,6 +56,7 @@ pub struct CharInfo {
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ClaimExport {
pub character_id: Uuid,
pub ruleset: crate::portable::Ruleset,
pub payload: Vec<u8>,
pub sha256: [u8; 32],
pub collections: BTreeMap<String, Vec<u32>>,
@@ -118,6 +120,8 @@ pub trait RealmBackend: Send + Sync {
local_id: &str,
params: RemoteImportParams,
) -> Result<RemoteImportOutcome>;
/// Local world port for this realm. Must fail closed if the realm port cannot be resolved.
fn world_port(&self, local_id: &str) -> Result<u16>;
}
/// State of one channel.
@@ -218,6 +222,10 @@ impl HostService {
self.realm_id
}
pub fn local_world_port(&self) -> Result<u16> {
self.backend.world_port(&self.local_id)
}
/// The player's public key is the one recorded for this player id when there is a record; `None` when the player is new here.
pub fn key_matches(&self, player: &Uuid, public_key: &str) -> bool {
match self
@@ -303,6 +311,7 @@ impl HostService {
Request::TransferOffer {
transfer_id,
character_id,
ruleset,
canonical_revision,
content_hash,
total_size,
@@ -311,6 +320,7 @@ impl HostService {
player,
transfer_id,
character_id,
ruleset,
canonical_revision,
content_hash,
total_size,
@@ -691,6 +701,7 @@ impl HostService {
use base64::Engine;
Response::Claimed {
character_id: exported.character_id,
ruleset: exported.ruleset.as_str().to_string(),
sha256: hex::encode(exported.sha256),
payload: base64::engine::general_purpose::STANDARD.encode(&exported.payload),
collections: exported.collections,
@@ -726,6 +737,7 @@ impl HostService {
player: &Uuid,
transfer_id: Uuid,
character_id: Uuid,
ruleset: String,
canonical_revision: u64,
content_hash: String,
total_size: usize,
@@ -741,6 +753,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 !crate::portable::session::protocol::carried_kind_for(kind, offer_ruleset) {
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
@@ -834,6 +870,7 @@ impl HostService {
realm_local_id: self.local_id.clone(),
transfer_id,
character_id,
ruleset: offer_ruleset.as_str().to_string(),
player_id: *player,
revision: canonical_revision,
content_hash,
@@ -1008,18 +1045,55 @@ impl HostService {
Err(e) => return unavailable("reading transfer file", &Error::Invalid(e.to_string())),
};
use sha2::{Digest, Sha256};
let hash = hex::encode(Sha256::digest(&payload));
if hash != t.content_hash {
let _ = std::fs::remove_file(&path);
return err(AppError::Invalid, "Content hash mismatch.");
}
let mut hash_bytes = [0u8; 32];
if hex::decode_to_slice(&t.content_hash, &mut hash_bytes).is_err() {
let _ = std::fs::remove_file(&path);
return err(AppError::Invalid, "Invalid content hash format.");
}
let decoded = match crate::portable::snapshot::decode(&payload, Some(&hash_bytes)) {
Ok(d) => d,
Err(e) => {
let _ = std::fs::remove_file(&path);
return err(AppError::Invalid, &format!("Corrupt snapshot: {e}"));
}
};
let transfer_ruleset: crate::portable::Ruleset = match t.ruleset.parse() {
Ok(r) => r,
Err(_) => {
let _ = std::fs::remove_file(&path);
return err(AppError::Incompatible, "Invalid transfer ruleset.");
}
};
if decoded.character_id.as_uuid() != t.character_id {
let _ = std::fs::remove_file(&path);
return err(
AppError::Invalid,
"Snapshot character id does not match TransferOffer.",
);
}
if decoded.ruleset != transfer_ruleset {
let _ = std::fs::remove_file(&path);
return err(
AppError::Incompatible,
"Snapshot ruleset does not match TransferOffer.",
);
}
let info = match self.backend.info(&self.local_id) {
Ok(i) => i,
Err(e) => {
let _ = std::fs::remove_file(&path);
return unavailable("reading realm info", &e);
}
};
if transfer_ruleset != info.ruleset {
let _ = std::fs::remove_file(&path);
return err(
AppError::Incompatible,
"Transfer ruleset does not match target realm ruleset.",
);
}
let Some(m) = self.mapping(player) else {
return err(AppError::NoAccount, "Player has no account on this realm.");
};
@@ -1083,6 +1157,7 @@ impl HostService {
#[cfg(any(test, feature = "testkit"))]
pub mod fake {
use super::*;
use crate::portable::Ruleset;
#[derive(Default)]
pub struct FakeRealm {
@@ -1095,6 +1170,7 @@ pub mod fake {
pub seen_passwords: Mutex<Vec<String>>,
pub imported: Mutex<HashMap<Uuid, (u32, Uuid)>>,
pub incompatible: Mutex<std::collections::HashSet<Uuid>>,
pub world_port: Mutex<Option<Result<u16>>>,
}
impl FakeRealm {
@@ -1141,6 +1217,7 @@ pub mod fake {
impl RealmBackend for FakeRealm {
fn info(&self, _: &str) -> Result<RealmInfo> {
Ok(RealmInfo {
ruleset: Ruleset::Coa,
automatic: *self.automatic.lock().unwrap(),
route: self.route.lock().unwrap().clone(),
})
@@ -1245,6 +1322,7 @@ pub mod fake {
.or_insert_with(Uuid::now_v7);
Ok(ClaimExport {
character_id: id,
ruleset: crate::portable::Ruleset::Coa,
payload: format!("payload-{guid}").into_bytes(),
sha256: [7; 32],
collections: BTreeMap::from([("coa:appearance".to_string(), vec![1, 2, 3])]),
@@ -1284,6 +1362,16 @@ pub mod fake {
notes: vec![],
})
}
fn world_port(&self, _: &str) -> Result<u16> {
if let Some(res) = self.world_port.lock().unwrap().as_ref() {
match res {
Ok(p) => Ok(*p),
Err(e) => Err(Error::Invalid(e.to_string())),
}
} else {
Ok(8085)
}
}
}
}
@@ -1424,7 +1512,7 @@ mod tests {
&Uuid::now_v7(),
"K",
Request::Hello {
protocol: 1,
protocol: coa_control_proto::CONTROL_PROTOCOL_VERSION,
client: "t".into(),
},
)
@@ -1655,6 +1743,7 @@ mod tests {
);
let Response::Claimed {
character_id,
ruleset,
sha256,
payload,
collections,
@@ -1662,6 +1751,7 @@ mod tests {
else {
panic!()
};
assert_eq!(ruleset, "coa");
assert_eq!(sha256, hex::encode([7u8; 32]));
assert!(!payload.is_empty() && collections["coa:appearance"] == vec![1, 2, 3]);
// asking again returns the same character
@@ -1857,6 +1947,14 @@ mod tests {
);
}
fn test_snapshot(cid: Uuid, ruleset: crate::portable::Ruleset) -> (Vec<u8>, String) {
let mut model = crate::portable::fixtures::geared_level_eighty();
model.character_id = crate::portable::CharacterId::from_uuid(cid).unwrap();
model.ruleset = ruleset;
let encoded = crate::portable::snapshot::encode(&model).unwrap();
(encoded.payload, hex::encode(encoded.content_hash))
}
#[test]
fn remote_transfer_lifecycle_empty_realm_import_and_ack() {
let (realm, s, p, _acc) = claimed_setup();
@@ -1864,12 +1962,11 @@ mod tests {
let cid = Uuid::now_v7();
let tid = Uuid::now_v7();
let payload = b"portable_character_snapshot_payload_test_data".to_vec();
use sha2::{Digest, Sha256};
let hash = hex::encode(Sha256::digest(&payload));
let (payload, hash) = test_snapshot(cid, crate::portable::Ruleset::Coa);
// 1. Offer
let offer = Request::TransferOffer {
ruleset: "coa".into(),
transfer_id: tid,
character_id: cid,
canonical_revision: 1,
@@ -1943,6 +2040,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,
@@ -1973,15 +2071,12 @@ mod tests {
let cid = Uuid::now_v7();
let tid = Uuid::now_v7();
let chunk1 = b"first_chunk_of_payload_";
let chunk2 = b"second_chunk_of_payload";
let mut full = chunk1.to_vec();
full.extend_from_slice(chunk2);
use sha2::{Digest, Sha256};
let hash = hex::encode(Sha256::digest(&full));
let (full, hash) = test_snapshot(cid, crate::portable::Ruleset::Coa);
let mid = full.len() / 2;
let (chunk1, chunk2) = full.split_at(mid);
let offer = Request::TransferOffer {
ruleset: "coa".into(),
transfer_id: tid,
character_id: cid,
canonical_revision: 1,
@@ -2071,11 +2166,10 @@ mod tests {
let cid = Uuid::now_v7();
let tid = Uuid::now_v7();
let payload = b"idempotency_test_payload".to_vec();
use sha2::{Digest, Sha256};
let hash = hex::encode(Sha256::digest(&payload));
let (payload, hash) = test_snapshot(cid, crate::portable::Ruleset::Coa);
let offer = Request::TransferOffer {
ruleset: "coa".into(),
transfer_id: tid,
character_id: cid,
canonical_revision: 1,
@@ -2138,6 +2232,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,
@@ -2169,11 +2264,10 @@ mod tests {
let cid = Uuid::now_v7();
let tid = Uuid::now_v7();
let payload = b"player_1_character_data".to_vec();
use sha2::{Digest, Sha256};
let hash = hex::encode(Sha256::digest(&payload));
let (payload, hash) = test_snapshot(cid, crate::portable::Ruleset::Coa);
let offer = Request::TransferOffer {
ruleset: "coa".into(),
transfer_id: tid,
character_id: cid,
canonical_revision: 1,
@@ -2240,6 +2334,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,
@@ -2267,9 +2362,7 @@ mod tests {
let cid = Uuid::now_v7();
let tid1 = Uuid::now_v7();
let payload1 = b"character_revision_1_data".to_vec();
use sha2::{Digest, Sha256};
let hash1 = hex::encode(Sha256::digest(&payload1));
let (payload1, hash1) = test_snapshot(cid, crate::portable::Ruleset::Coa);
// Rev 1
s.handle(
@@ -2277,6 +2370,7 @@ mod tests {
&p,
"K",
Request::TransferOffer {
ruleset: "coa".into(),
transfer_id: tid1,
character_id: cid,
canonical_revision: 1,
@@ -2321,13 +2415,18 @@ mod tests {
// Rev 2
let tid2 = Uuid::now_v7();
let payload2 = b"character_revision_2_newer_data".to_vec();
let hash2 = hex::encode(Sha256::digest(&payload2));
let mut model2 = crate::portable::fixtures::geared_level_eighty();
model2.character_id = crate::portable::CharacterId::from_uuid(cid).unwrap();
model2.progression.money += 500;
let enc2 = crate::portable::snapshot::encode(&model2).unwrap();
let (payload2, hash2) = (enc2.payload, hex::encode(enc2.content_hash));
let r = s.handle(
&mut session,
&p,
"K",
Request::TransferOffer {
ruleset: "coa".into(),
transfer_id: tid2,
character_id: cid,
canonical_revision: 2,
@@ -2377,4 +2476,190 @@ 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());
}
#[test]
fn tampered_payload_at_commit_aborts_with_zero_mutation() {
let (realm, s, p, _acc) = claimed_setup();
let mut session = Session::default();
let cid = Uuid::now_v7();
let tid = Uuid::now_v7();
// 1. Offer announces CoA
let (payload_coa, hash_coa) = test_snapshot(cid, crate::portable::Ruleset::Coa);
let offer = Request::TransferOffer {
ruleset: "coa".into(),
transfer_id: tid,
character_id: cid,
canonical_revision: 1,
content_hash: hash_coa,
total_size: payload_coa.len(),
collections: BTreeMap::new(),
};
s.handle(&mut session, &p, "K", offer);
// Attacker creates a Wildcard snapshot with the same CID, but uploads it under the CoA offer
let (payload_wc, hash_wc) = test_snapshot(cid, crate::portable::Ruleset::Wildcard);
// Uploading chunks of payload_wc will mismatch the offered hash
use base64::Engine;
let data = base64::engine::general_purpose::STANDARD.encode(&payload_wc);
s.handle(
&mut session,
&p,
"K",
Request::TransferChunk {
transfer_id: tid,
offset: 0,
data,
},
);
let commit = Request::TransferCommit { transfer_id: tid };
let r = s.handle(&mut session, &p, "K", commit);
assert!(matches!(
r,
Response::Error {
code: AppError::Invalid,
..
}
));
assert!(realm.imported.lock().unwrap().is_empty());
// 2. What if attacker offered hash_wc matching payload_wc, but offer.ruleset is "coa"?
let tid2 = Uuid::now_v7();
let offer2 = Request::TransferOffer {
ruleset: "coa".into(),
transfer_id: tid2,
character_id: cid,
canonical_revision: 1,
content_hash: hash_wc,
total_size: payload_wc.len(),
collections: BTreeMap::new(),
};
s.handle(&mut session, &p, "K", offer2);
let data2 = base64::engine::general_purpose::STANDARD.encode(&payload_wc);
s.handle(
&mut session,
&p,
"K",
Request::TransferChunk {
transfer_id: tid2,
offset: 0,
data: data2,
},
);
let commit2 = Request::TransferCommit { transfer_id: tid2 };
let r2 = s.handle(&mut session, &p, "K", commit2);
assert!(matches!(
r2,
Response::Error {
code: AppError::Incompatible,
..
}
));
assert!(realm.imported.lock().unwrap().is_empty());
// 3. What if snapshot contains a different character_id than offer?
let tid3 = Uuid::now_v7();
let other_cid = Uuid::now_v7();
let (payload_other, hash_other) = test_snapshot(other_cid, crate::portable::Ruleset::Coa);
let offer3 = Request::TransferOffer {
ruleset: "coa".into(),
transfer_id: tid3,
character_id: cid, // offered cid
canonical_revision: 1,
content_hash: hash_other,
total_size: payload_other.len(),
collections: BTreeMap::new(),
};
s.handle(&mut session, &p, "K", offer3);
let data3 = base64::engine::general_purpose::STANDARD.encode(&payload_other);
s.handle(
&mut session,
&p,
"K",
Request::TransferChunk {
transfer_id: tid3,
offset: 0,
data: data3,
},
);
let commit3 = Request::TransferCommit { transfer_id: tid3 };
let r3 = s.handle(&mut session, &p, "K", commit3);
assert!(matches!(
r3,
Response::Error {
code: AppError::Invalid,
..
}
));
assert!(realm.imported.lock().unwrap().is_empty());
}
}
+15 -4
View File
@@ -56,6 +56,7 @@ CREATE TABLE IF NOT EXISTS host_transfer(
realm_local_id TEXT NOT NULL,
transfer_id TEXT NOT NULL PRIMARY KEY,
character_id TEXT NOT NULL,
ruleset TEXT NOT NULL DEFAULT 'coa',
player_id TEXT NOT NULL,
revision INTEGER NOT NULL,
content_hash TEXT NOT NULL,
@@ -155,6 +156,7 @@ pub struct HostTransfer {
pub realm_local_id: String,
pub transfer_id: Uuid,
pub character_id: Uuid,
pub ruleset: String,
pub player_id: Uuid,
pub revision: u64,
pub content_hash: String,
@@ -199,6 +201,10 @@ impl ControlStore {
.map_err(db)?;
let _ = conn.pragma_update(None, "journal_mode", "WAL");
conn.execute_batch(SCHEMA).map_err(db)?;
let _ = conn.execute(
"ALTER TABLE host_transfer ADD COLUMN ruleset TEXT NOT NULL DEFAULT 'coa'",
[],
);
Ok(Self { conn })
}
@@ -307,7 +313,7 @@ impl ControlStore {
pub fn host_transfer(&self, realm: &str, transfer_id: &Uuid) -> Result<Option<HostTransfer>> {
self.conn
.query_row(
"SELECT realm_local_id, transfer_id, character_id, player_id, revision, content_hash, total_size, received_size, state, local_guid, session_id, projected_level, notes, collections FROM host_transfer WHERE realm_local_id = ?1 AND transfer_id = ?2",
"SELECT realm_local_id, transfer_id, character_id, player_id, revision, content_hash, total_size, received_size, state, local_guid, session_id, projected_level, notes, collections, ruleset FROM host_transfer WHERE realm_local_id = ?1 AND transfer_id = ?2",
params![realm, transfer_id.to_string()],
row_transfer,
)
@@ -323,7 +329,7 @@ impl ControlStore {
) -> Result<Option<HostTransfer>> {
self.conn
.query_row(
"SELECT realm_local_id, transfer_id, character_id, player_id, revision, content_hash, total_size, received_size, state, local_guid, session_id, projected_level, notes, collections FROM host_transfer WHERE realm_local_id = ?1 AND character_id = ?2 ORDER BY updated_at DESC LIMIT 1",
"SELECT realm_local_id, transfer_id, character_id, player_id, revision, content_hash, total_size, received_size, state, local_guid, session_id, projected_level, notes, collections, ruleset FROM host_transfer WHERE realm_local_id = ?1 AND character_id = ?2 ORDER BY updated_at DESC LIMIT 1",
params![realm, character_id.to_string()],
row_transfer,
)
@@ -337,8 +343,8 @@ impl ControlStore {
let coll_json = serde_json::to_string(&t.collections).unwrap_or_default();
self.conn
.execute(
"INSERT INTO host_transfer(realm_local_id, transfer_id, character_id, player_id, revision, content_hash, total_size, received_size, state, local_guid, session_id, projected_level, notes, collections, created_at, updated_at)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16)
"INSERT INTO host_transfer(realm_local_id, transfer_id, character_id, ruleset, player_id, revision, content_hash, total_size, received_size, state, local_guid, session_id, projected_level, notes, collections, created_at, updated_at)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17)
ON CONFLICT(transfer_id) DO UPDATE SET
received_size = excluded.received_size,
state = excluded.state,
@@ -347,11 +353,13 @@ impl ControlStore {
projected_level = excluded.projected_level,
notes = excluded.notes,
collections = excluded.collections,
ruleset = excluded.ruleset,
updated_at = excluded.updated_at",
params![
t.realm_local_id,
t.transfer_id.to_string(),
t.character_id.to_string(),
t.ruleset,
t.player_id.to_string(),
t.revision as i64,
t.content_hash,
@@ -540,11 +548,13 @@ fn row_transfer(r: &rusqlite::Row<'_>) -> rusqlite::Result<Result<HostTransfer>>
let collections = coll_str
.and_then(|s| serde_json::from_str::<BTreeMap<String, Vec<u32>>>(&s).ok())
.unwrap_or_default();
let ruleset: String = r.get(14).unwrap_or_else(|_| "coa".to_string());
Ok((|| {
Ok(HostTransfer {
realm_local_id,
transfer_id: uuid(tid)?,
character_id: uuid(cid)?,
ruleset,
player_id: uuid(pid)?,
revision: revision as u64,
content_hash,
@@ -677,6 +687,7 @@ mod tests {
realm_local_id: "live".into(),
transfer_id: t,
character_id: c,
ruleset: "coa".into(),
player_id: p,
revision: 3,
content_hash: "a".repeat(64),
+92 -29
View File
@@ -14,25 +14,12 @@ use crate::download::Cancel;
use crate::error::{Error, Result};
use crate::fsx;
pub const CLIENT_VERSION: &str = "1.8";
pub const CLIENT_VERSION: &str = "1.8.3";
pub const MANIFEST_FILENAME: &str = "custom_races_patch_manifest.txt";
pub const ARCHIVES: &[(&str, &str)] = &[
(
"CoA-Custom-1.6-main-20261012-4dd3a4ec.zip",
"https://github.com/ilusixn/azerothcore-wotlk-coa/releases/download/coa-custom-1.6/CoA-Custom-1.6-main-20261012-4dd3a4ec.zip",
),
(
"CoA-Custom-1.6-client-part1.zip",
"https://github.com/ilusixn/azerothcore-wotlk-coa/releases/download/coa-custom-1.6/CoA-Custom-1.6-client-part1.zip",
),
(
"CoA-Custom-1.6-client-part2.zip",
"https://github.com/ilusixn/azerothcore-wotlk-coa/releases/download/coa-custom-1.6/CoA-Custom-1.6-client-part2.zip",
),
(
"CoA-Custom-1.8-Client.zip",
"https://github.com/ilusixn/azerothcore-wotlk-coa/releases/download/coa-custom-1.8/CoA-Custom-1.8-Client.zip",
),
("CoA-Custom-1.8.3-Client-1.zip", "https://github.com/ilusixn/azerothcore-wotlk-coa/releases/download/coa-custom-1.8.3/CoA-Custom-1.8.3-Client-1.zip"),
("CoA-Custom-1.8.3-Client-2.zip", "https://github.com/ilusixn/azerothcore-wotlk-coa/releases/download/coa-custom-1.8.3/CoA-Custom-1.8.3-Client-2.zip"),
("CoA-Custom-1.8.3-Client-3.zip", "https://github.com/ilusixn/azerothcore-wotlk-coa/releases/download/coa-custom-1.8.3/CoA-Custom-1.8.3-Client-3.zip"),
];
pub const RACE_MPQS: &[&str] = &[
@@ -62,11 +49,19 @@ pub const RACE_MPQS: &[&str] = &[
"patch-ZZV.MPQ",
"patch-ZZW.MPQ",
"patch-ZZZ.MPQ",
"patch-ZK.MPQ",
"patch-ZZX.MPQ",
"patch-ZZZC.MPQ",
"patch-ZZZD.MPQ",
];
pub const RACE_ADDONS: &[&str] = &[
"CoAWC2Cursor/CoAWC2Cursor.lua",
"CoAWC2Cursor/CoAWC2Cursor.toc",
"CoAHideArmor/CoAHideArmor.lua",
"CoAHideArmor/CoAHideArmor.toc",
"CoA_TalentReset/CoA_TalentReset.lua",
"CoA_TalentReset/CoA_TalentReset.toc",
];
pub const EXCLUDED_BOT_RACES_RECOMMENDED: &str =
@@ -189,6 +184,8 @@ fn patch_files(client: &Path) -> Result<Vec<PatchFile>> {
include_str!("custom_races_hashes_1_6.json")
} else if manifest.lines().any(|line| line == "# CoA Custom 1.7") {
include_str!("custom_races_hashes_1_7.json")
} else if manifest.lines().any(|line| line == "# CoA Custom 1.8") {
include_str!("custom_races_hashes_1_8.json")
} else {
include_str!("custom_races_hashes.json")
};
@@ -209,10 +206,9 @@ fn patch_files(client: &Path) -> Result<Vec<PatchFile>> {
));
}
Some(name.to_string())
} else if let Some(name) = line.strip_prefix("ADDON:") {
Some(format!("Interface/AddOns/{name}"))
} else {
None
line.strip_prefix("ADDON:")
.map(|name| format!("Interface/AddOns/{name}"))
};
if let Some(path) = path {
fsx::safe_join(client, &path)?;
@@ -608,17 +604,14 @@ pub fn uninstall_client_patches(client: &Path) -> Result<()> {
fn verify_archive(path: &Path, filename: &str) -> Result<()> {
let expected = match filename {
"CoA-Custom-1.6-main-20261012-4dd3a4ec.zip" => {
"dfe802ea70047c129ac2e0aaa557bab3110e3cc6926d36403b8c880a0e310ee4"
"CoA-Custom-1.8.3-Client-1.zip" => {
"a9dd51ed2d90fb048d549602f40f5429d56e2df0df5606a38781b358fa369568"
}
"CoA-Custom-1.6-client-part1.zip" => {
"1dbf1901ad5be61eba66973609df90712ffc78ef9e9b2c8549a5f3e36332bf12"
"CoA-Custom-1.8.3-Client-2.zip" => {
"ab084a55509ccbcc2977a06dd0c01fa879973a1892baaacaeb3ff52f3dfc750e"
}
"CoA-Custom-1.6-client-part2.zip" => {
"689f7f946b4180fe977dabedc7cfe642e3e7f27431600c64c4dd5b7960b1bc66"
}
"CoA-Custom-1.8-Client.zip" => {
"b0ee9275a373e4024dda7744321d02b686fb1c703603ad635b32bfb6ed9b48aa"
"CoA-Custom-1.8.3-Client-3.zip" => {
"270c7b306624bf9e5c3fe577e3bd058601221df223dd9e449ff7c25de70b9461"
}
_ => return Err(Error::Invalid("Unknown custom races archive.".into())),
};
@@ -1042,6 +1035,55 @@ mod tests {
assert_eq!(actual, expected);
}
#[test]
#[ignore = "Requires the downloaded release archives in the normal download cache"]
fn release_archives_install_toggle_and_uninstall_in_a_disposable_client() {
let temp = tempfile::tempdir().unwrap();
let root = temp.path();
fs::create_dir(root.join("Data")).unwrap();
fs::write(root.join("Ascension.exe"), b"original game executable").unwrap();
fs::write(root.join("Data/patch-T.MPQ"), b"original game patch").unwrap();
fs::write(root.join("Data/patch-user.MPQ"), b"unrelated user patch").unwrap();
install_client_patches(root, &Cancel::default(), &|_, _| {}).unwrap();
let status = client_patch_status(root);
assert_eq!(status.version.as_deref(), Some(CLIENT_VERSION));
assert_eq!(status.state, ClientPatchState::Enabled);
assert!(root.join("Data/patch-ZZZD.MPQ").is_file());
assert!(root
.join("Interface/AddOns/CoAHideArmor/CoAHideArmor.lua")
.is_file());
set_client_patch_enabled(root, false).unwrap();
assert_eq!(client_patch_status(root).state, ClientPatchState::Disabled);
assert_eq!(
fs::read(root.join("Ascension.exe")).unwrap(),
b"original game executable"
);
assert_eq!(
fs::read(root.join("Data/patch-T.MPQ")).unwrap(),
b"original game patch"
);
set_client_patch_enabled(root, true).unwrap();
assert_eq!(client_patch_status(root).state, ClientPatchState::Enabled);
uninstall_client_patches(root).unwrap();
assert_eq!(
client_patch_status(root).state,
ClientPatchState::NotInstalled
);
assert_eq!(
fs::read(root.join("Ascension.exe")).unwrap(),
b"original game executable"
);
assert_eq!(
fs::read(root.join("Data/patch-T.MPQ")).unwrap(),
b"original game patch"
);
assert_eq!(
fs::read(root.join("Data/patch-user.MPQ")).unwrap(),
b"unrelated user patch"
);
assert!(!root.join("Data/patch-ZZZD.MPQ").exists());
}
#[test]
fn legacy_installation_uses_its_own_hashes_when_preserving_originals() {
let temp = tempfile::tempdir().unwrap();
@@ -1087,6 +1129,27 @@ mod tests {
assert!(legacy.keys().all(|key| current.contains_key(key)));
}
#[test]
fn previous_appearance_release_keeps_its_hashes_and_requests_an_update() {
let temp = tempfile::tempdir().unwrap();
fs::write(temp.path().join(MANIFEST_FILENAME), "# CoA Custom 1.8\n").unwrap();
let legacy: std::collections::BTreeMap<String, String> =
serde_json::from_str(include_str!("custom_races_hashes_1_8.json")).unwrap();
let current: std::collections::BTreeMap<String, String> =
serde_json::from_str(include_str!("custom_races_hashes.json")).unwrap();
let files = patch_files(temp.path()).unwrap();
assert_eq!(files.len(), legacy.len());
for file in files {
assert_eq!(file.sha256, legacy[&file.path]);
}
assert!(legacy.keys().all(|path| current.contains_key(path)));
assert!(!legacy.contains_key("Data/patch-ZZZD.MPQ"));
assert!(current.contains_key("Data/patch-ZZZD.MPQ"));
let status = client_patch_status(temp.path());
assert_eq!(status.version.as_deref(), Some("1.8"));
assert_eq!(status.state, ClientPatchState::PartiallyInstalled);
}
#[test]
fn previous_racial_release_keeps_its_hashes_and_addon_paths_stay_inside_client() {
let temp = tempfile::tempdir().unwrap();
+10 -2
View File
@@ -16,6 +16,7 @@
"Data/patch-ZHA.MPQ": "0fc6ebeafe1d14192dc64bafc90bde3c49230df1297f98bf65900a3bcf953617",
"Data/patch-ZHM.MPQ": "317d3ae00f0bd674b358af07544976acb7804aa6d8b19d1788ad96030e8c9bf0",
"Data/patch-ZJ.MPQ": "f821e99add86ef68d108c5ec466328c97677d3ed52f7944e200f3fe38c13b4de",
"Data/patch-ZK.MPQ": "444d0ecb72c1e990509d53e3cfa5b7634c816733533e8a97e5d7f5653ee32cce",
"Data/patch-ZM.MPQ": "424ab1978986e854551633983a94bd15beba6328aabea8c02f98eaa32f6f0b61",
"Data/patch-ZVU.MPQ": "c679b85a2e97344395756b54d2cf6abefe4e80e74944cb55b6e573ad17b7d020",
"Data/patch-ZZE.MPQ": "4b1e289e12c82644cb78f50170e6b5fd53918eb2de834f9e0cebddd81873a8bb",
@@ -25,10 +26,13 @@
"Data/patch-ZZU.MPQ": "8ee1839415b56d46c6eff7eb4dfbaf6fbafc4c6b29b39380d69f4d827d02a99e",
"Data/patch-ZZV.MPQ": "8d5e61d37008abf70478e5d5f46ec7afb0490b9a643323bd75a1c70cadd63290",
"Data/patch-ZZW.MPQ": "3689c485f8ee8fccaa6dbae1d073bc9231229f9a040f79a272d80a87486d0c33",
"Data/patch-ZZX.MPQ": "4c12608089cfe356f7c8882d66db90239ed3ec8ddd980d91d7a3a488680f3c88",
"Data/patch-ZZZ.MPQ": "566aaadf501af42e29a828b1bc2edbd36d436288fb309fe423bd74b9619bf593",
"Data/patch-ZZZC.MPQ": "691a53f6325c2615a64ced0802f18bc4d96e99c62aaa606fc930f9406ee74cdf",
"Data/patch-ZZZD.MPQ": "e4ce9d8b363eb609d0d6d92627eb53454fa2e03e4dbc1795b3573a22b7d009c8",
"EsteriaAppearance.bin": "90d9cfaeaf6de10f014f1d1610ea10453ec9b240255759aea99513cac488a3ec",
"EsteriaAppearance.dll": "64564aceac38b26faefbd51dba779fa338ab5e70a2a2509f6c8f3a991ac98518",
"EsteriaAppearanceGeometry.bin": "fdc1cbba90b66c4533a66365d6d555c2d32ab01acb014fff042b4a6a9c6b6ddc",
"EsteriaAppearance.dll": "196a82f24dd287653e2b2fc4d12bfc796f8ee3f6687ca8308905a5ab528a51a9",
"EsteriaAppearanceGeometry.bin": "19de5b4b4f79778ea5316659efc2f66c6edb6b5149c46efa47c46bfa4ec6904c",
"EsteriaAppearanceMaterials.bin": "f72f027f54a55c05aa0f76b457b97b484fe0e1aedc0e068cc0e0ca53e1878cba",
"EsteriaCosmeticWings.bin": "57352c28459d073a29b3014d33b70f3b3756afa37fa9583ef6b30d503422ac3f",
"EsteriaDrakonid.bin": "95440ee9c065ef20bb7fed6158d20623d68745291cedc2726fc746ff54601f95",
@@ -57,8 +61,12 @@
"EsteriaVrykulTextures.bin": "46098750a0e235724c6e9cc8d9d4e26550aa47bef95fd5f0f82efe5e945bf296",
"EsteriaVulpera.bin": "c5434993b9af4a17d881965e4735cd2ac379e39c7142aac9844adff9528562d4",
"EsteriaVulperaTextures.bin": "1ab844e74684aced2b069f1b91cd563aade45e05bd5e23f866a6c0c301cb098e",
"Interface/AddOns/CoAHideArmor/CoAHideArmor.lua": "8c1c7403524fc9bd56c0809b4101b141da700ba163701209bf1420f2ef106aa7",
"Interface/AddOns/CoAHideArmor/CoAHideArmor.toc": "123580d92fd5ceee258e96296f42c359b7e83cdff151af49c50c6c4e2059677c",
"Interface/AddOns/CoAWC2Cursor/CoAWC2Cursor.lua": "1cf9537ff5f10b77250fea4407aea1008da690afe102ed6ed2dac21f79638cfa",
"Interface/AddOns/CoAWC2Cursor/CoAWC2Cursor.toc": "48ce695dce712b3643ebe13a77e318d623c964acc69479b8fc8cc675099801bf",
"Interface/AddOns/CoA_TalentReset/CoA_TalentReset.lua": "827d756d5948ef918fafaf8b869290b3a1faa4e4cc21b19b512a00d4509f3d41",
"Interface/AddOns/CoA_TalentReset/CoA_TalentReset.toc": "16298c04af68e68d6445e7a11f42aee525dd4145f85d2771ff434fb7c6e95a85",
"dinput8.dll": "f8de78606c241fb3911dce22faf68f5b9f9885b142b183c1e2c09ddc8f7e380c",
"wc2_human.cur": "f609736e29596bb386ef1597b157d211e01a86d32c2a929e256c581c37d71791",
"wc2_orc.cur": "baa512c9b9045762ba35b6e0d35b8f79c54b7649f35cc9c0e0cc8c168a1e5a97"
@@ -0,0 +1,65 @@
{
"Ascension.exe": "e2c347019d554a59639e5978fd68e50e906973ab313c6573cc56ca82e8e3c547",
"Data/patch-T.MPQ": "fe597138ab7f56881b5f4f27d6dc9d81bb278b483ca0d91b7207ffd4a5ae7bfd",
"Data/patch-ZE1.MPQ": "69d79dbbea54ec0312c37770debc79c7bc9ce2e21eedef99c03cd8d911955283",
"Data/patch-ZE2.MPQ": "1a41cae77ad730e9cf69e8d63fd12ae3a579418bb550d351fff469573a97ac3c",
"Data/patch-ZE3.MPQ": "b587202c21b6f580682b601b7c2e905fbfa766276e74733db55c1bddbffb7f87",
"Data/patch-ZE5.MPQ": "476b5a1fcf69f64fdb281e3b445362b936d016066ccd12f897acfcf200d6c0cf",
"Data/patch-ZE6.MPQ": "762592c9ed950b4a7b6c7d85d45050b30fa3f35d53e348ee1e1516fdbb7e5484",
"Data/patch-ZE7.MPQ": "de54b0189d242763d2872223419a259b6b8a4b380c24b50a2ef9c6fa44466248",
"Data/patch-ZE8.MPQ": "1bc5691fb84a84f3e7a0a70baaa9192a97b4ec5906ee37c85838ffe08adef934",
"Data/patch-ZE9.MPQ": "d49c94463e9548e76378ce2c0454d8f204f0745c8c0de32b6dce7f0b0fd67c4a",
"Data/patch-ZEA.MPQ": "78fd10ec5262ae2417eba9700d2172553bbc1e5cfb0b597aada8f1753ca46d9d",
"Data/patch-ZES.MPQ": "a2d9348f917f745c7aa25b2eed96efa312f7b2d2f62cb86a4f2eaabc2dfa895f",
"Data/patch-ZG.MPQ": "48979e1fda775f8deb47bffa48e0a468595d4c71286fee518f51dc5801c5ca39",
"Data/patch-ZH.MPQ": "5e1d2fe287053abba703d7af381e10096c6525ba477ffed3971c2fc4f93e919c",
"Data/patch-ZHA.MPQ": "0fc6ebeafe1d14192dc64bafc90bde3c49230df1297f98bf65900a3bcf953617",
"Data/patch-ZHM.MPQ": "317d3ae00f0bd674b358af07544976acb7804aa6d8b19d1788ad96030e8c9bf0",
"Data/patch-ZJ.MPQ": "f821e99add86ef68d108c5ec466328c97677d3ed52f7944e200f3fe38c13b4de",
"Data/patch-ZM.MPQ": "424ab1978986e854551633983a94bd15beba6328aabea8c02f98eaa32f6f0b61",
"Data/patch-ZVU.MPQ": "c679b85a2e97344395756b54d2cf6abefe4e80e74944cb55b6e573ad17b7d020",
"Data/patch-ZZE.MPQ": "4b1e289e12c82644cb78f50170e6b5fd53918eb2de834f9e0cebddd81873a8bb",
"Data/patch-ZZR.MPQ": "5a7575e592dc0c8a6913e0d946bbe06fa0ca2e4d817ef1f8548d3d13142bcbd3",
"Data/patch-ZZS.MPQ": "533fd69d5784d83e872a5a28d27301dc9ab5d0cb925f8b2116926854e4a0a5b8",
"Data/patch-ZZT.MPQ": "aef3bbe4951333d62fb55224484724fbaa9c35773a19944ffb9935e250cfb59c",
"Data/patch-ZZU.MPQ": "8ee1839415b56d46c6eff7eb4dfbaf6fbafc4c6b29b39380d69f4d827d02a99e",
"Data/patch-ZZV.MPQ": "8d5e61d37008abf70478e5d5f46ec7afb0490b9a643323bd75a1c70cadd63290",
"Data/patch-ZZW.MPQ": "3689c485f8ee8fccaa6dbae1d073bc9231229f9a040f79a272d80a87486d0c33",
"Data/patch-ZZZ.MPQ": "566aaadf501af42e29a828b1bc2edbd36d436288fb309fe423bd74b9619bf593",
"EsteriaAppearance.bin": "90d9cfaeaf6de10f014f1d1610ea10453ec9b240255759aea99513cac488a3ec",
"EsteriaAppearance.dll": "64564aceac38b26faefbd51dba779fa338ab5e70a2a2509f6c8f3a991ac98518",
"EsteriaAppearanceGeometry.bin": "fdc1cbba90b66c4533a66365d6d555c2d32ab01acb014fff042b4a6a9c6b6ddc",
"EsteriaAppearanceMaterials.bin": "f72f027f54a55c05aa0f76b457b97b484fe0e1aedc0e068cc0e0ca53e1878cba",
"EsteriaCosmeticWings.bin": "57352c28459d073a29b3014d33b70f3b3756afa37fa9583ef6b30d503422ac3f",
"EsteriaDrakonid.bin": "95440ee9c065ef20bb7fed6158d20623d68745291cedc2726fc746ff54601f95",
"EsteriaDrakonidCoverage.bin": "9cdc227f08329e1245d2b864a996e7a772c96ecdbe5d81925f4d60cdbe4fa11e",
"EsteriaDrakonidTextures.bin": "1ba9133a75dad291d98a068b2dcde01f31a897a1764cd7f3e2c316c288a8f605",
"EsteriaEarthen.bin": "8a0db93ba2d5c756b44ed84f2f7bc7c15eef13be6a7d87baf1383c6c0c624e02",
"EsteriaGnoll.bin": "cfacc8e681bb8e54a4f01ee9c12a91bf0bd23a23527bb548d4dc21ec1b33eea2",
"EsteriaGnollTextures.bin": "1ba9133a75dad291d98a068b2dcde01f31a897a1764cd7f3e2c316c288a8f605",
"EsteriaHaranir.bin": "59f31d00e372fd2646e1cf0d9d3d5d671b31edd60ff7b862f8d1ce7e53ba1f2f",
"EsteriaHaranirTextures.bin": "99948ca570be2d376f0c67e3b8088739b6fa9f9d2c73985e19f68df77689a229",
"EsteriaHighmountain.bin": "e83349252ad2687ac23fcfc5623db7401cf32e5faf47a5a7be20c2f94b014938",
"EsteriaNaga.bin": "e87547cff5d09500c294f8b06935d134cdd0bbb962e294a72de09404505bd8b3",
"EsteriaNagaTextures.bin": "57ec560f99c1d48ac1e8f6a797c156513b99e7d349e3071afe405f812d159ae3",
"EsteriaSaberon.bin": "7735c9325c807c5125760d87f323d6b7d4162fb542c1d8b5f435ea2d6b9a4daa",
"EsteriaSaberonCoverage.bin": "9cdc227f08329e1245d2b864a996e7a772c96ecdbe5d81925f4d60cdbe4fa11e",
"EsteriaSaberonTextures.bin": "1ba9133a75dad291d98a068b2dcde01f31a897a1764cd7f3e2c316c288a8f605",
"EsteriaSethrak.bin": "bd14857a8c11fdf8027128763293701586b2102f9a6539d33a727014789fd606",
"EsteriaSethrakTextures.bin": "d2b2cf58087a391f00198008fe871edd400ddf28d54a3a05674df74c5198528a",
"EsteriaTarasek.bin": "f718444d5ec36f7aff018883486ae1981151fe6e01f5b7781d68d74e9fadfa47",
"EsteriaTarasekTextures.bin": "1ba9133a75dad291d98a068b2dcde01f31a897a1764cd7f3e2c316c288a8f605",
"EsteriaThinHuman.bin": "75794d192ea0c228b3da7bf7d0bdff1119f79d3f9bfef6650cd5e1a2b5d106eb",
"EsteriaThinHumanTextures.bin": "02aeb4c05893d06125b8b58fdb7c2a56fe3d66a7d094706a44b43cb503d1731e",
"EsteriaTuskarr.bin": "ecbe7ef490ba67eca029a57639192db61238522618491549766fe38529914387",
"EsteriaTuskarrTextures.bin": "e2116c2c83adea079126fd5da765d20da24f044d4f161c4124e4368cb3d6bc71",
"EsteriaVrykul.bin": "39e2b7b4c67997dbbd34bae840bd606a59290f7f2fc82565a0ba00090335415c",
"EsteriaVrykulTextures.bin": "46098750a0e235724c6e9cc8d9d4e26550aa47bef95fd5f0f82efe5e945bf296",
"EsteriaVulpera.bin": "c5434993b9af4a17d881965e4735cd2ac379e39c7142aac9844adff9528562d4",
"EsteriaVulperaTextures.bin": "1ab844e74684aced2b069f1b91cd563aade45e05bd5e23f866a6c0c301cb098e",
"Interface/AddOns/CoAWC2Cursor/CoAWC2Cursor.lua": "1cf9537ff5f10b77250fea4407aea1008da690afe102ed6ed2dac21f79638cfa",
"Interface/AddOns/CoAWC2Cursor/CoAWC2Cursor.toc": "48ce695dce712b3643ebe13a77e318d623c964acc69479b8fc8cc675099801bf",
"dinput8.dll": "f8de78606c241fb3911dce22faf68f5b9f9885b142b183c1e2c09ddc8f7e380c",
"wc2_human.cur": "f609736e29596bb386ef1597b157d211e01a86d32c2a929e256c581c37d71791",
"wc2_orc.cur": "baa512c9b9045762ba35b6e0d35b8f79c54b7649f35cc9c0e0cc8c168a1e5a97"
}
+42 -17
View File
@@ -75,11 +75,23 @@ pub const SCHEMAS: [(&str, &str); 3] = [
];
pub fn schema_of(kind: &str) -> Result<&'static str> {
if kind == "playerbots" { return Ok("acore_playerbots"); }
if let Some(kind) = kind.strip_prefix("wildcard-") { return crate::realms::Mode::Wildcard.schema(kind); }
if let Some(kind) = kind.strip_prefix("reborn-") { return crate::realms::Mode::Reborn.schema(kind); }
if let Some(kind) = kind.strip_prefix("coa-") { return crate::realms::Mode::Coa.schema(kind); }
SCHEMAS.iter().find(|(k, _)| *k == kind).map(|(_, s)| *s).ok_or_else(|| Error::Invalid(format!("unknown database {kind}")))
if kind == "playerbots" {
return Ok("acore_playerbots");
}
if let Some(kind) = kind.strip_prefix("wildcard-") {
return crate::realms::Mode::Wildcard.schema(kind);
}
if let Some(kind) = kind.strip_prefix("reborn-") {
return crate::realms::Mode::Reborn.schema(kind);
}
if let Some(kind) = kind.strip_prefix("coa-") {
return crate::realms::Mode::Coa.schema(kind);
}
SCHEMAS
.iter()
.find(|(k, _)| *k == kind)
.map(|(_, s)| *s)
.ok_or_else(|| Error::Invalid(format!("unknown database {kind}")))
}
fn ident_ok(name: &str) -> bool {
@@ -357,9 +369,11 @@ impl Db {
pub fn recovery_objects(&self, schema: &str) -> Result<Vec<serde_json::Value>> {
let schema = self.realm_schema(schema);
if !ident_ok(schema) { return Err(Error::Invalid("bad schema name".into())); }
if !ident_ok(schema) {
return Err(Error::Invalid("bad schema name".into()));
}
let sql = format!("SELECT routine_type,HEX(routine_name) FROM information_schema.routines WHERE routine_schema='{schema}' UNION ALL SELECT 'TRIGGER',HEX(trigger_name) FROM information_schema.triggers WHERE trigger_schema='{schema}' UNION ALL SELECT 'VIEW',HEX(table_name) FROM information_schema.views WHERE table_schema='{schema}' ORDER BY 1,2;");
parse_recovery_objects(&schema, &self.query(&sql)?)
parse_recovery_objects(schema, &self.query(&sql)?)
}
/// Consistent dump of one schema, zstd-compressed to `out`. Returns (compressed bytes, sha256 of the file).
@@ -469,15 +483,23 @@ impl Db {
}
fn parse_recovery_objects(schema: &str, text: &str) -> Result<Vec<serde_json::Value>> {
text.lines().filter(|line| !line.is_empty()).map(|line| {
let (kind, name) = line.split_once('\t').ok_or_else(|| Error::Invalid("unexpected database object reply".into()))?;
if !matches!(kind, "PROCEDURE" | "FUNCTION" | "TRIGGER" | "VIEW") {
return Err(Error::Invalid("unexpected database object type".into()));
}
let name = hex::decode(name).ok().and_then(|bytes| String::from_utf8(bytes).ok())
.filter(|name| !name.is_empty()).ok_or_else(|| Error::Invalid("unexpected database object name".into()))?;
Ok(serde_json::json!({ "database": schema, "kind": kind, "name": name }))
}).collect()
text.lines()
.filter(|line| !line.is_empty())
.map(|line| {
let (kind, name) = line
.split_once('\t')
.ok_or_else(|| Error::Invalid("unexpected database object reply".into()))?;
if !matches!(kind, "PROCEDURE" | "FUNCTION" | "TRIGGER" | "VIEW") {
return Err(Error::Invalid("unexpected database object type".into()));
}
let name = hex::decode(name)
.ok()
.and_then(|bytes| String::from_utf8(bytes).ok())
.filter(|name| !name.is_empty())
.ok_or_else(|| Error::Invalid("unexpected database object name".into()))?;
Ok(serde_json::json!({ "database": schema, "kind": kind, "name": name }))
})
.collect()
}
/// Name of the service account the Manager uses for the server console (RA). Accounts are stored upper-case.
@@ -587,7 +609,10 @@ mod tests {
use crate::realms::Mode;
let sql = "SELECT * FROM `acore_characters`.characters WHERE name='acore_world'; -- acore_world\nSELECT * FROM acore_world.items; SELECT * FROM acore_world_wildcard.items;";
assert_eq!(super::route_sql(sql, Mode::Reborn), "SELECT * FROM `acore_characters_reborn`.characters WHERE name='acore_world'; -- acore_world\nSELECT * FROM acore_world_reborn.items; SELECT * FROM acore_world_wildcard.items;");
assert_eq!(super::schema_of("reborn-characters").unwrap(), "acore_characters_reborn");
assert_eq!(
super::schema_of("reborn-characters").unwrap(),
"acore_characters_reborn"
);
assert_eq!(super::schema_of("reborn-auth").unwrap(), "acore_auth");
}
use super::*;
+6 -1
View File
@@ -1045,7 +1045,12 @@ real error
fn stop_diagnostics_survive_while_portable_pins_remain_hidden() {
let ordinary = "MySQL is still stopping; wait before copying the repack.";
assert_eq!(redact(ordinary), ordinary);
for secret in ["PIN: 123456", "pin=123456", "transfer_pin=123456", "PIN123456"] {
for secret in [
"PIN: 123456",
"pin=123456",
"transfer_pin=123456",
"PIN123456",
] {
let output = redact(&format!("{ordinary}\n{secret}"));
assert!(output.contains(ordinary));
assert!(!output.contains("123456"));
+20 -5
View File
@@ -1249,12 +1249,27 @@ mod tests {
"db;3306;acore;apppw;acore_characters"
);
let wild = database_env(&s, true, crate::realms::Mode::Wildcard);
assert_eq!(get(&wild, "AC_WORLD_DATABASE_INFO").unwrap(), "db;3306;acore;apppw;acore_world_wildcard");
assert_eq!(get(&wild, "AC_CHARACTER_DATABASE_INFO").unwrap(), "db;3306;acore;apppw;acore_characters_wildcard");
assert_eq!(
get(&wild, "AC_WORLD_DATABASE_INFO").unwrap(),
"db;3306;acore;apppw;acore_world_wildcard"
);
assert_eq!(
get(&wild, "AC_CHARACTER_DATABASE_INFO").unwrap(),
"db;3306;acore;apppw;acore_characters_wildcard"
);
let reborn = database_env(&s, true, crate::realms::Mode::Reborn);
assert_eq!(get(&reborn, "AC_WORLD_DATABASE_INFO").unwrap(), "db;3306;acore;apppw;acore_world_reborn");
assert_eq!(get(&reborn, "AC_CHARACTER_DATABASE_INFO").unwrap(), "db;3306;acore;apppw;acore_characters_reborn");
assert_eq!(get(&reborn, "AC_LOGIN_DATABASE_INFO").unwrap(), "db;3306;acore;apppw;acore_auth");
assert_eq!(
get(&reborn, "AC_WORLD_DATABASE_INFO").unwrap(),
"db;3306;acore;apppw;acore_world_reborn"
);
assert_eq!(
get(&reborn, "AC_CHARACTER_DATABASE_INFO").unwrap(),
"db;3306;acore;apppw;acore_characters_reborn"
);
assert_eq!(
get(&reborn, "AC_LOGIN_DATABASE_INFO").unwrap(),
"db;3306;acore;apppw;acore_auth"
);
// Accounts are shared by both realms; the auth server never sees the others.
assert_eq!(
get(&wild, "AC_LOGIN_DATABASE_INFO").unwrap(),
+30 -6
View File
@@ -12,16 +12,28 @@ pub fn database_log(root: &Path, filter: Option<&str>, max_lines: usize) -> Resu
database_log_with(&SystemDocker, root, filter, max_lines)
}
pub fn database_log_with(d: &dyn Docker, root: &Path, filter: Option<&str>, max_lines: usize) -> Result<Vec<Line>> {
pub fn database_log_with(
d: &dyn Docker,
root: &Path,
filter: Option<&str>,
max_lines: usize,
) -> Result<Vec<Line>> {
let name = Config::load(root)?.names().db;
// Ask for more than wanted: the filter may drop most of them.
let tail = (max_lines * 4).clamp(200, 8000).to_string();
let out = d.run(&Call::new(&["logs", "--tail", &tail, &name], Duration::from_secs(20)))?;
let out = d.run(&Call::new(
&["logs", "--tail", &tail, &name],
Duration::from_secs(20),
))?;
if !out.ok() {
return Err(Error::Invalid("This log does not exist yet.".into()));
}
// MySQL writes to the error stream.
Ok(crate::console::lines_from_text(&format!("{}\n{}", out.stderr, out.stdout), filter, max_lines))
Ok(crate::console::lines_from_text(
&format!("{}\n{}", out.stderr, out.stdout),
filter,
max_lines,
))
}
#[cfg(test)]
@@ -58,7 +70,9 @@ mod tests {
assert_eq!(fake.calls.borrow()[0][..2], ["logs", "--tail"]);
assert_eq!(fake.calls.borrow()[0].last().unwrap(), "coa-t1-db");
assert_eq!(lines.len(), 3);
assert!(lines.iter().any(|l| l.text.contains("boom") && l.level == crate::console::Level::Error));
assert!(lines
.iter()
.any(|l| l.text.contains("boom") && l.level == crate::console::Level::Error));
let only = database_log_with(&fake, &root, Some("slow"), 100).unwrap();
assert_eq!(only.len(), 1);
}
@@ -66,7 +80,17 @@ mod tests {
#[test]
fn a_database_that_never_ran_has_no_log_yet() {
let (_d, root) = root();
let fake = Fake { out: Output { code: Some(1), stdout: String::new(), stderr: "Error: No such container: coa-t1-db".into() }, calls: Default::default() };
assert!(database_log_with(&fake, &root, None, 10).unwrap_err().to_string().contains("does not exist yet"));
let fake = Fake {
out: Output {
code: Some(1),
stdout: String::new(),
stderr: "Error: No such container: coa-t1-db".into(),
},
calls: Default::default(),
};
assert!(database_log_with(&fake, &root, None, 10)
.unwrap_err()
.to_string()
.contains("does not exist yet"));
}
}
+72 -14
View File
@@ -18,7 +18,10 @@ use crate::net::Exposure;
use crate::process::{ServiceState, ServiceStatus};
fn is_open(cfg: &Config) -> bool {
cfg.bind_address.parse::<IpAddr>().map(|ip| !ip.is_loopback()).unwrap_or(false)
cfg.bind_address
.parse::<IpAddr>()
.map(|ip| !ip.is_loopback())
.unwrap_or(false)
}
/// Whether the login and world servers are published beyond this computer.
@@ -46,7 +49,11 @@ pub fn set_open(root: &Path, meta: &Path, open: bool) -> Result<bool> {
if let Ok(bytes) = fs::read(&coa_conf) {
let mut conf = ConfFile::parse_bytes(&bytes)?;
if conf.get("CoA.AllowRemoteClients").map(str::trim) != Some("1") {
conf.set("CoA.AllowRemoteClients", "1", &["Set by CoA Server Manager together with the friends mode"]);
conf.set(
"CoA.AllowRemoteClients",
"1",
&["Set by CoA Server Manager together with the friends mode"],
);
originals.push((coa_conf.clone(), bytes));
coa_edit = Some(conf.to_text());
}
@@ -55,7 +62,16 @@ pub fn set_open(root: &Path, meta: &Path, open: bool) -> Result<bool> {
if !changed && coa_edit.is_none() {
return Ok(false);
}
take_snapshot(meta, Scope::Server, if open { "before opening the servers to friends" } else { "before closing the servers to friends" }, &originals)?;
take_snapshot(
meta,
Scope::Server,
if open {
"before opening the servers to friends"
} else {
"before closing the servers to friends"
},
&originals,
)?;
if changed {
fsx::atomic_write_json(&root.join(MARKER), &cfg)?;
}
@@ -73,10 +89,30 @@ pub fn exposure(root: &Path, ports: &Ports) -> Vec<Exposure> {
let observed = crate::process::observe(root, ports);
let up = |s: &ServiceStatus| matches!(s.state, ServiceState::Running | ServiceState::Starting);
vec![
Exposure { port: ports.mysql, what: "database", listening: up(&observed.mysql), reachable_from_network: false },
Exposure { port: ports.ra, what: "server console", listening: up(&observed.world), reachable_from_network: false },
Exposure { port: ports.auth, what: "login server", listening: up(&observed.auth), reachable_from_network: open && up(&observed.auth) },
Exposure { port: ports.world, what: "game world", listening: up(&observed.world), reachable_from_network: open && up(&observed.world) },
Exposure {
port: ports.mysql,
what: "database",
listening: up(&observed.mysql),
reachable_from_network: false,
},
Exposure {
port: ports.ra,
what: "server console",
listening: up(&observed.world),
reachable_from_network: false,
},
Exposure {
port: ports.auth,
what: "login server",
listening: up(&observed.auth),
reachable_from_network: open && up(&observed.auth),
},
Exposure {
port: ports.world,
what: "game world",
listening: up(&observed.world),
reachable_from_network: open && up(&observed.world),
},
]
}
@@ -91,9 +127,15 @@ mod tests {
fs::create_dir_all(root.join("Settings")).unwrap();
fs::create_dir_all(root.join("Core/configs/modules")).unwrap();
fs::create_dir_all(&meta).unwrap();
let extra = bind.map(|b| format!(r#","bindAddress":"{b}""#)).unwrap_or_default();
let extra = bind
.map(|b| format!(r#","bindAddress":"{b}""#))
.unwrap_or_default();
fs::write(root.join(MARKER), format!(r#"{{"project":"t1"{extra}}}"#)).unwrap();
fs::write(root.join("Core/configs/modules/coa.conf"), "CoA.Enable = 1\n").unwrap();
fs::write(
root.join("Core/configs/modules/coa.conf"),
"CoA.Enable = 1\n",
)
.unwrap();
(d, root, meta)
}
@@ -104,8 +146,15 @@ mod tests {
assert!(set_open(&root, &meta, true).unwrap(), "a restart is needed");
assert!(bind_is_open(&root));
assert_eq!(Config::load(&root).unwrap().bind_address, "0.0.0.0");
assert!(fs::read_to_string(root.join("Core/configs/modules/coa.conf")).unwrap().contains("CoA.AllowRemoteClients = 1"));
assert!(!set_open(&root, &meta, true).unwrap(), "nothing left to change");
assert!(
fs::read_to_string(root.join("Core/configs/modules/coa.conf"))
.unwrap()
.contains("CoA.AllowRemoteClients = 1")
);
assert!(
!set_open(&root, &meta, true).unwrap(),
"nothing left to change"
);
assert!(set_open(&root, &meta, false).unwrap());
assert!(!bind_is_open(&root));
assert_eq!(Config::load(&root).unwrap().bind_address, "127.0.0.1");
@@ -114,7 +163,11 @@ mod tests {
#[test]
fn enabling_remote_client_protocol_requires_restart_even_when_ports_are_open() {
let (_d, root, meta) = server(Some("0.0.0.0"));
fs::write(root.join("Core/configs/modules/coa.conf"), "CoA.Enable = 1\nCoA.AllowRemoteClients = 0\n").unwrap();
fs::write(
root.join("Core/configs/modules/coa.conf"),
"CoA.Enable = 1\nCoA.AllowRemoteClients = 0\n",
)
.unwrap();
assert!(set_open(&root, &meta, true).unwrap());
assert_eq!(Config::load(&root).unwrap().bind_address, "0.0.0.0");
assert!(!set_open(&root, &meta, true).unwrap());
@@ -123,7 +176,10 @@ mod tests {
#[test]
fn an_address_chosen_by_hand_is_kept_when_opening_and_other_settings_survive() {
let (_d, root, meta) = server(Some("192.168.1.20"));
assert!(bind_is_open(&root), "any address but the loopback is the network");
assert!(
bind_is_open(&root),
"any address but the loopback is the network"
);
set_open(&root, &meta, true).unwrap();
let cfg = Config::load(&root).unwrap();
assert_eq!(cfg.bind_address, "192.168.1.20");
@@ -142,7 +198,9 @@ mod tests {
let (_d, root, _meta) = server(Some("0.0.0.0"));
let rows = exposure(&root, &Ports::default());
let by = |what: &str| rows.iter().find(|e| e.what == what).unwrap();
assert!(!by("database").reachable_from_network && !by("server console").reachable_from_network);
assert!(
!by("database").reachable_from_network && !by("server console").reachable_from_network
);
// Nothing runs in this test (docker is not asked to start anything), so nothing is reachable yet.
assert!(rows.iter().all(|e| !e.reachable_from_network));
}
+30 -7
View File
@@ -36,7 +36,12 @@ fn key(path: &Path) -> Vec<String> {
return format!("{}:", char::from(drive).to_ascii_lowercase());
}
Prefix::UNC(server, share) | Prefix::VerbatimUNC(server, share) => {
return format!("\\\\{}\\{}", server.to_string_lossy(), share.to_string_lossy()).to_lowercase();
return format!(
"\\\\{}\\{}",
server.to_string_lossy(),
share.to_string_lossy()
)
.to_lowercase();
}
_ => {}
}
@@ -337,12 +342,30 @@ mod tests {
#[cfg(windows)]
#[test]
fn containment_matches_verbatim_drive_and_unc_prefixes() {
assert!(starts_with_ci(Path::new(r"\\?\C:\server\Extras\file.sql"), Path::new(r"C:\server")));
assert!(starts_with_ci(Path::new(r"C:\server\Extras\file.sql"), Path::new(r"\\?\c:\server")));
assert!(starts_with_ci(Path::new(r"\\?\UNC\host\share\server\file.sql"), Path::new(r"\\host\share\server")));
assert!(!starts_with_ci(Path::new(r"\\?\D:\server\file.sql"), Path::new(r"C:\server")));
assert!(!starts_with_ci(Path::new(r"\\?\C:\server-other\file.sql"), Path::new(r"C:\server")));
assert!(!starts_with_ci(Path::new(r"\\?\UNC\host\other\server\file.sql"), Path::new(r"\\host\share\server")));
assert!(starts_with_ci(
Path::new(r"\\?\C:\server\Extras\file.sql"),
Path::new(r"C:\server")
));
assert!(starts_with_ci(
Path::new(r"C:\server\Extras\file.sql"),
Path::new(r"\\?\c:\server")
));
assert!(starts_with_ci(
Path::new(r"\\?\UNC\host\share\server\file.sql"),
Path::new(r"\\host\share\server")
));
assert!(!starts_with_ci(
Path::new(r"\\?\D:\server\file.sql"),
Path::new(r"C:\server")
));
assert!(!starts_with_ci(
Path::new(r"\\?\C:\server-other\file.sql"),
Path::new(r"C:\server")
));
assert!(!starts_with_ci(
Path::new(r"\\?\UNC\host\other\server\file.sql"),
Path::new(r"\\host\share\server")
));
}
#[cfg(windows)]
+82 -25
View File
@@ -165,21 +165,38 @@ impl Manifest {
}
if let Some(c) = &self.compatibility {
if parse_version(&self.min_manager_version).is_none_or(|v| v < (0, 6, 13)) {
return bad("Release compatibility matrices require Manager 0.6.13 or newer".into());
return bad(
"Release compatibility matrices require Manager 0.6.13 or newer".into(),
);
}
if c.schema != 1 || !matches!(c.platform.as_str(), "windows-x86_64" | "linux-x86_64")
|| !is_commit(&c.core_commit) || self.core.commit.as_deref() != Some(&c.core_commit)
|| c.module_commits.is_empty() || c.module_commits.values().any(|sha| !is_commit(sha))
|| self.bots.as_ref().and_then(|r| r.commit.as_ref()).is_some_and(|sha| c.module_commits.get("bots") != Some(sha))
if c.schema != 1
|| !matches!(c.platform.as_str(), "windows-x86_64" | "linux-x86_64")
|| !is_commit(&c.core_commit)
|| self.core.commit.as_deref() != Some(&c.core_commit)
|| c.module_commits.is_empty()
|| c.module_commits.values().any(|sha| !is_commit(sha))
|| self
.bots
.as_ref()
.and_then(|r| r.commit.as_ref())
.is_some_and(|sha| c.module_commits.get("bots") != Some(sha))
|| parse_version(&c.client_patch_version).is_none()
|| c.source_versions.is_empty() || c.source_versions.iter().any(|v| parse_version(v).is_none())
|| c.source_versions.iter().collect::<HashSet<_>>().len() != c.source_versions.len() {
|| c.source_versions.is_empty()
|| c.source_versions.iter().any(|v| parse_version(v).is_none())
|| c.source_versions.iter().collect::<HashSet<_>>().len() != c.source_versions.len()
{
return bad("Invalid release compatibility matrix".into());
}
if !c.source_databases.is_empty() && (c.source_databases.len() != c.source_versions.len()
|| c.source_versions.iter().any(|v| !c.source_databases.contains_key(v))
|| c.source_databases.values().any(|s| !is_sha256(&s.manifest_sha256)
|| s.schema_sha256.as_ref().is_some_and(|sha| !is_sha256(sha)))) {
if !c.source_databases.is_empty()
&& (c.source_databases.len() != c.source_versions.len()
|| c.source_versions
.iter()
.any(|v| !c.source_databases.contains_key(v))
|| c.source_databases.values().any(|s| {
!is_sha256(&s.manifest_sha256)
|| s.schema_sha256.as_ref().is_some_and(|sha| !is_sha256(sha))
}))
{
return bad("Invalid source database compatibility".into());
}
}
@@ -308,9 +325,15 @@ mod tests {
fn compatibility_matrix_binds_core_and_requires_tested_sources() {
let mut m = Manifest::parse(sample("").as_bytes()).unwrap();
m.min_manager_version = "0.6.13".into();
m.compatibility = Some(Compatibility { schema: 1, platform: "windows-x86_64".into(),
core_commit: "a".repeat(40), module_commits: [("squid".into(), "b".repeat(40))].into(),
source_databases: Default::default(), client_patch_version: "1.5.1".into(), source_versions: vec!["0.261010.32".into()] });
m.compatibility = Some(Compatibility {
schema: 1,
platform: "windows-x86_64".into(),
core_commit: "a".repeat(40),
module_commits: [("squid".into(), "b".repeat(40))].into(),
source_databases: Default::default(),
client_patch_version: "1.5.1".into(),
source_versions: vec!["0.261010.32".into()],
});
m.validate().unwrap();
m.compatibility.as_mut().unwrap().core_commit = "c".repeat(40);
assert!(m.validate().is_err());
@@ -323,14 +346,30 @@ mod tests {
fn compatibility_cannot_claim_a_different_packaged_bot_revision() {
let mut m = Manifest::parse(sample("").as_bytes()).unwrap();
m.min_manager_version = "0.6.13".into();
m.bots = Some(Revision { commit: Some("b".repeat(40)) });
m.compatibility = Some(Compatibility { schema: 1, platform: "windows-x86_64".into(),
core_commit: "a".repeat(40), module_commits: [("bots".into(), "c".repeat(40))].into(),
source_databases: Default::default(), client_patch_version: "1.5.1".into(), source_versions: vec!["0.2.0".into()] });
m.bots = Some(Revision {
commit: Some("b".repeat(40)),
});
m.compatibility = Some(Compatibility {
schema: 1,
platform: "windows-x86_64".into(),
core_commit: "a".repeat(40),
module_commits: [("bots".into(), "c".repeat(40))].into(),
source_databases: Default::default(),
client_patch_version: "1.5.1".into(),
source_versions: vec!["0.2.0".into()],
});
assert!(m.validate().is_err());
m.compatibility.as_mut().unwrap().module_commits.insert("bots".into(), "b".repeat(40));
m.compatibility
.as_mut()
.unwrap()
.module_commits
.insert("bots".into(), "b".repeat(40));
m.validate().unwrap();
m.compatibility.as_mut().unwrap().source_versions.push("0.2.0".into());
m.compatibility
.as_mut()
.unwrap()
.source_versions
.push("0.2.0".into());
assert!(m.validate().is_err());
}
@@ -338,12 +377,30 @@ mod tests {
fn source_database_contracts_must_cover_the_exact_upgrade_versions() {
let mut m = Manifest::parse(sample("").as_bytes()).unwrap();
m.min_manager_version = "0.6.13".into();
m.compatibility = Some(Compatibility { schema: 1, platform: "windows-x86_64".into(),
core_commit: "a".repeat(40), module_commits: [("squid".into(), "b".repeat(40))].into(),
client_patch_version: "1.5.1".into(), source_versions: vec!["0.2.0".into()],
source_databases: [("0.2.0".into(), SourceDatabase { manifest_sha256: "a".repeat(64), schema_sha256: None })].into() });
m.compatibility = Some(Compatibility {
schema: 1,
platform: "windows-x86_64".into(),
core_commit: "a".repeat(40),
module_commits: [("squid".into(), "b".repeat(40))].into(),
client_patch_version: "1.5.1".into(),
source_versions: vec!["0.2.0".into()],
source_databases: [(
"0.2.0".into(),
SourceDatabase {
manifest_sha256: "a".repeat(64),
schema_sha256: None,
},
)]
.into(),
});
m.validate().unwrap();
m.compatibility.as_mut().unwrap().source_databases.get_mut("0.2.0").unwrap().schema_sha256 = Some("bad".into());
m.compatibility
.as_mut()
.unwrap()
.source_databases
.get_mut("0.2.0")
.unwrap()
.schema_sha256 = Some("bad".into());
assert!(m.validate().is_err());
let c = m.compatibility.as_mut().unwrap();
c.source_databases.get_mut("0.2.0").unwrap().schema_sha256 = None;
+23 -3
View File
@@ -101,8 +101,19 @@ impl Store for Db {
let connection = self.clone().for_realm(crate::realms::Mode::Coa);
let world = self.realm_schema("acore_world");
let characters = self.realm_schema("acore_characters");
let others: Vec<_> = [crate::realms::Mode::Coa, crate::realms::Mode::Wildcard, crate::realms::Mode::Reborn].into_iter().filter(|m| *m != self.realm()).map(|m| m.schema("world").unwrap()).collect();
let schemas: std::collections::BTreeSet<_> = [world, characters, AUTH_LEDGER_SCHEMA].into_iter().chain(others.iter().copied()).collect();
let others: Vec<_> = [
crate::realms::Mode::Coa,
crate::realms::Mode::Wildcard,
crate::realms::Mode::Reborn,
]
.into_iter()
.filter(|m| *m != self.realm())
.map(|m| m.schema("world").unwrap())
.collect();
let schemas: std::collections::BTreeSet<_> = [world, characters, AUTH_LEDGER_SCHEMA]
.into_iter()
.chain(others.iter().copied())
.collect();
let catalog = connection.query(&format!("SELECT table_schema,table_name FROM information_schema.tables WHERE table_schema IN ('{}') AND table_name IN ('updates','{LEDGER_TABLE}') AND table_type='BASE TABLE';", schemas.into_iter().collect::<Vec<_>>().join("','")))?;
let available: std::collections::BTreeSet<_> = catalog
.lines()
@@ -120,7 +131,16 @@ impl Store for Db {
queries.push(format!("SELECT 'core','{kind}',{},REPEAT('0',64),'applied',1,'' FROM `{schema}`.`updates` WHERE BINARY RIGHT(name,4)='.sql'",text("LEFT(name,CHAR_LENGTH(name)-4)")));
}
}
for (origin, schema, filter) in [("local",world,""), ("shared",AUTH_LEDGER_SCHEMA,"")].into_iter().chain(others.iter().map(|schema| ("other", *schema, " WHERE `db` IN ('auth','coa-auth','wildcard-auth','reborn-auth')"))) {
for (origin, schema, filter) in [("local", world, ""), ("shared", AUTH_LEDGER_SCHEMA, "")]
.into_iter()
.chain(others.iter().map(|schema| {
(
"other",
*schema,
" WHERE `db` IN ('auth','coa-auth','wildcard-auth','reborn-auth')",
)
}))
{
if available.contains(&(schema, LEDGER_TABLE)) {
queries.push(format!("SELECT '{origin}',{},{},{},{},`baseline`,{} FROM `{schema}`.`{LEDGER_TABLE}`{filter}",text("`db`"),text("`id`"),text("`sha256`"),text("`status`"),text("COALESCE(HEX(`error`),'')")));
}
+33 -8
View File
@@ -173,7 +173,9 @@ fn installed_module_commits(root: &Path) -> BTreeMap<String, String> {
fn list_in(cat: &[Entry], root: &Path) -> Vec<ModuleView> {
let installed_commits = installed_module_commits(root);
let wildcard = crate::realms::state(root).map(|s| s.active != crate::realms::Mode::Coa).unwrap_or(true);
let wildcard = crate::realms::state(root)
.map(|s| s.active != crate::realms::Mode::Coa)
.unwrap_or(true);
cat.iter()
.cloned()
.map(|e| {
@@ -532,10 +534,17 @@ fn save_settings_in(
));
}
}
if id == "content-scaling" && key.starts_with("CoAContentScaling.Difficulty.Health.") && key.ends_with("Multiplier") {
let multiplier = value.parse::<f32>().map_err(|_| Error::Invalid("Health multipliers must be a number from 0.1 to 10.".into()))?;
if id == "content-scaling"
&& key.starts_with("CoAContentScaling.Difficulty.Health.")
&& key.ends_with("Multiplier")
{
let multiplier = value.parse::<f32>().map_err(|_| {
Error::Invalid("Health multipliers must be a number from 0.1 to 10.".into())
})?;
if !multiplier.is_finite() || !(0.1..=10.0).contains(&multiplier) {
return Err(Error::Invalid("Health multipliers must be a number from 0.1 to 10.".into()));
return Err(Error::Invalid(
"Health multipliers must be a number from 0.1 to 10.".into(),
));
}
}
if id == "content-scaling" && key == "CoAContentScaling.World.Leech.Percent" {
@@ -1202,17 +1211,33 @@ mod tests {
for key in keys {
let changes = |v: &str| BTreeMap::from([(key.to_string(), v.to_string())]);
for bad in ["NaN", "inf", "0", "0.09", "10.01", "-1", "abc", ""] {
assert!(save_settings_in(&cat, &root, &meta, "content-scaling", &changes(bad)).is_err(), "{key} {bad}");
assert!(
save_settings_in(&cat, &root, &meta, "content-scaling", &changes(bad)).is_err(),
"{key} {bad}"
);
}
for good in ["0.1", "0.4", "1", "2.5", "10"] {
assert_eq!(save_settings_in(&cat, &root, &meta, "content-scaling", &changes(good)).unwrap(), [key]);
assert_eq!(settings_in(&cat, &root, "content-scaling").unwrap().iter().find(|s| s.key == key).unwrap().value, good);
assert_eq!(
save_settings_in(&cat, &root, &meta, "content-scaling", &changes(good))
.unwrap(),
[key]
);
assert_eq!(
settings_in(&cat, &root, "content-scaling")
.unwrap()
.iter()
.find(|s| s.key == key)
.unwrap()
.value,
good
);
}
}
}
#[test]
fn an_older_file_name_is_used_when_the_current_one_is_missing_and_a_part_that_cannot_be_switched_stays_on() {
fn an_older_file_name_is_used_when_the_current_one_is_missing_and_a_part_that_cannot_be_switched_stays_on(
) {
let d = tempfile::tempdir().unwrap();
let (root, meta) = server(d.path());
fs::write(
+11 -2
View File
@@ -62,8 +62,17 @@ pub fn set_enabled(main: &Path, enabled: bool) -> Result<realms::View> {
));
}
if enabled {
if realms::state(main)?.active == Mode::Reborn { return Err(Error::Invalid("Simultaneous startup supports CoA and Wildcard. Select one of these realms first.".into())); }
if !realms::view(main)?.supported { return Err(Error::Invalid("Update the server to a build with Wildcard support first.".into())); }
if realms::state(main)?.active == Mode::Reborn {
return Err(Error::Invalid(
"Simultaneous startup supports CoA and Wildcard. Select one of these realms first."
.into(),
));
}
if !realms::view(main)?.supported {
return Err(Error::Invalid(
"Update the server to a build with Wildcard support first.".into(),
));
}
secondary_launcher(&fs::read_to_string(main.join("Scripts/manage.py"))?)?;
}
let status = process::observe(main, &crate::layout::read_ports(main));
File diff suppressed because it is too large. Load diff
+3 -2
View File
@@ -456,8 +456,9 @@ mod tests {
ruleset: Ruleset::Coa,
character_formats: ContentProfile::manager_formats(),
online_import_job_formats: jobs.to_vec(),
session_protocol: 2,
collection_protocol: 2,
session_protocol: crate::portable::session::protocol::SESSION_PROTOCOL_VERSION,
collection_protocol:
crate::portable::session::protocol::COLLECTION_PROTOCOL_VERSION,
features: features.iter().copied().collect(),
collection_kinds: ["coa:appearance".to_string(), "coa:vanity".to_string()]
.into_iter()
+5
View File
@@ -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 {
@@ -0,0 +1,48 @@
-- 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;
-- 2. Upgrade character table to allow 'reborn' in CHECK (ruleset IN ('coa', 'wildcard', 'reborn'))
-- Foreign keys are off during migration runner, but legacy child tables remain valid because primary keys are untouched.
CREATE TABLE character_new (
character_id TEXT PRIMARY KEY,
profile_id TEXT NOT NULL REFERENCES profile(profile_id),
ruleset TEXT NOT NULL CHECK (ruleset IN ('coa', 'wildcard', 'reborn')),
name TEXT NOT NULL,
race TEXT NOT NULL,
class TEXT NOT NULL,
gender INTEGER NOT NULL,
level INTEGER NOT NULL,
revision INTEGER NOT NULL CHECK (revision >= 1),
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
archived INTEGER NOT NULL DEFAULT 0 CHECK (archived IN (0, 1))
) STRICT;
INSERT INTO character_new (character_id, profile_id, ruleset, name, race, class, gender, level, revision, created_at, updated_at, archived)
SELECT character_id, profile_id, ruleset, name, race, class, gender, level, revision, created_at, updated_at, archived
FROM character;
DROP TABLE character;
ALTER TABLE character_new RENAME TO character;
CREATE INDEX character_profile ON character(profile_id);
CREATE INDEX character_profile_ruleset ON character(profile_id, ruleset);
+2 -2
View File
@@ -23,8 +23,8 @@ pub mod snapshot;
pub mod store;
pub mod versions;
#[cfg(test)]
pub(crate) mod fixtures;
#[cfg(any(test, feature = "testkit"))]
pub mod fixtures;
pub use collection::IdSet;
pub use error::{PortableError, Result};
+96 -1
View File
@@ -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,23 +73,99 @@ 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) -> Result<&'static str> {
let mode: crate::realms::Mode = self.into();
mode.schema(kind)
.map_err(|e| PortableError::Invalid(e.to_string()))
}
pub fn collection_namespace(self) -> &'static str {
match self {
Ruleset::Coa => "coa",
Ruleset::Wildcard => "wildcard",
Ruleset::Reborn => "reborn",
}
}
pub fn parse(s: &str) -> Result<Self> {
match s {
"coa" => Ok(Ruleset::Coa),
"wildcard" => Ok(Ruleset::Wildcard),
"reborn" => Ok(Ruleset::Reborn),
other => Err(PortableError::Invalid(format!("unknown ruleset {other:?}"))),
}
}
}
impl std::str::FromStr for Ruleset {
type Err = PortableError;
fn from_str(s: &str) -> Result<Self> {
Self::parse(s)
}
}
impl std::fmt::Display for Ruleset {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.as_str())
}
}
impl From<crate::realms::Mode> 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<Ruleset> 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<coa_registry_proto::caps::Ruleset> 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<Ruleset> 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<u8>);
@@ -806,3 +883,21 @@ impl PortableCharacter {
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn schema_mapping_never_falls_back_on_unknown_database_kind() {
for ruleset in [Ruleset::Coa, Ruleset::Wildcard, Ruleset::Reborn] {
assert!(ruleset.schema("auth").is_ok());
assert!(ruleset.schema("characters").is_ok());
assert!(ruleset.schema("world").is_ok());
assert!(ruleset.schema("characters_extra").is_err());
assert!(ruleset.schema("unknown").is_err());
assert!(ruleset.schema("").is_err());
assert!(ruleset.schema("acore_characters").is_err());
}
}
}
@@ -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 !crate::portable::session::protocol::carried_kind_for(kind, r) {
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<Option<u32>> {
/// 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<String> {
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<String> {
/// The ids of the account in this realm, without the bank vanity items.
pub fn read_set(db: &Db, account: u32, kind: &str) -> Result<IdSet> {
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,9 @@ pub fn read_set(db: &Db, account: u32, kind: &str) -> Result<IdSet> {
.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,21 +123,21 @@ pub fn apply_set(
canonical: &IdSet,
knowledge: &RealmKnowledge,
) -> Result<Applied> {
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)?;
let mut applied = Applied::default();
let mut wanted = Vec::new();
for id in canonical
.ids()
.iter()
.copied()
.filter(|id| !(kind == "coa:vanity" && is_bank_vanity_item(*id)))
{
for id in canonical.ids().iter().copied().filter(|id| {
!((kind == "coa:vanity" || kind == "wildcard:vanity" || kind == "reborn:vanity")
&& is_bank_vanity_item(*id))
}) {
if !known(id) {
applied.unknown += 1;
} else if held.contains(id) {
@@ -168,9 +168,11 @@ 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, Ruleset::Coa, VANITY, &vanity)
.unwrap();
store.merge_collection(profile, VANITY, &vanity).unwrap();
let fingerprint_a = fingerprint(&r.a, 5001, APPEARANCE).unwrap();
assert_eq!(
fingerprint(&r.a, 5001, APPEARANCE).unwrap(),
@@ -331,10 +333,20 @@ 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 +355,10 @@ 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!(
+1 -1
View File
@@ -55,7 +55,7 @@ pub fn ruleset_of(db: &Db) -> Result<Ruleset> {
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),
}
}
@@ -14,7 +14,9 @@ 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, COLLECTION_PROTOCOL_VERSION, SESSION_PROTOCOL_VERSION,
};
use super::super::store::Store;
use super::import::ImportOptions;
use super::script::SchemaProbe;
@@ -97,13 +99,16 @@ pub fn assemble(
online_import_job_formats: core
.map(|c| c.portable.job_formats.clone())
.unwrap_or_default(),
session_protocol: PROTOCOL_VERSION,
collection_protocol: PROTOCOL_VERSION,
session_protocol: SESSION_PROTOCOL_VERSION,
collection_protocol: COLLECTION_PROTOCOL_VERSION,
features,
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()
},
+1 -1
View File
@@ -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)
+11 -2
View File
@@ -112,6 +112,7 @@ pub struct RealmAccess {
pub job_dir: PathBuf,
pub data_dir: PathBuf,
pub game_server_users: Vec<String>,
pub mode: Option<crate::realms::Mode>,
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<Db> {
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),
)),
}
}
+92 -27
View File
@@ -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<u8>,
pub content_hash: [u8; 32],
pub collections: BTreeMap<String, Vec<u32>>,
@@ -181,6 +182,16 @@ pub fn class_name(class: &str) -> String {
.and_then(|n| n.parse().ok())
.unwrap_or(0);
match id {
1 => "Warrior",
2 => "Paladin",
3 => "Hunter",
4 => "Rogue",
5 => "Priest",
6 => "Death Knight",
7 => "Shaman",
8 => "Mage",
9 => "Warlock",
11 => "Druid",
12 => "Barbarian",
13 => "Witch Doctor",
14 => "Felsworn",
@@ -363,11 +374,26 @@ impl PortableService {
pub fn reload_realms(&mut self) {
let (descriptors, broken) = access::load_descriptors(&self.dir.join("realms"));
self.broken_descriptors = broken;
let mut realms: Vec<RealmAccess> = self
.installs
.iter()
.map(|(id, root)| RealmAccess::from_install(id, root))
.collect();
let mut realms: Vec<RealmAccess> = Vec::new();
for (id, root) in &self.installs {
realms.push(RealmAccess::from_install(id, root));
if let Ok(state) = crate::realms::state(root) {
if state.wildcard_created {
let mut wc = RealmAccess::from_install(id, root);
wc.id = format!("srv-{id}:wildcard");
wc.name = format!("{} — Wildcard", wc.name);
wc.mode = Some(crate::realms::Mode::Wildcard);
realms.push(wc);
}
if state.reborn_created {
let mut rb = RealmAccess::from_install(id, root);
rb.id = format!("srv-{id}:reborn");
rb.name = format!("{} — Warcraft Reborn", rb.name);
rb.mode = Some(crate::realms::Mode::Reborn);
realms.push(rb);
}
}
}
for d in descriptors {
match RealmAccess::from_descriptor(d) {
Ok(a) if !realms.iter().any(|r| r.id == a.id) => realms.push(a),
@@ -414,10 +440,10 @@ impl PortableService {
}
fn access(&self, id: &str) -> Res<RealmAccess> {
self.realms
.iter()
.find(|r| r.id == id)
.cloned()
if let Some(r) = self.realms.iter().find(|r| r.id == id) {
return Ok(r.clone());
}
crate::realm_registry::advert::find_access(&self.dir.join("realms"), &self.installs, id)
.ok_or_else(|| fail("realm_missing", "That realm is not known to this Manager."))
}
@@ -728,6 +754,7 @@ impl PortableService {
characters.push(CharacterView {
id: c.character_id.to_string(),
name: c.name,
ruleset: c.ruleset,
class_name: class_name(&c.class),
race: c.race,
level: c.level,
@@ -1356,6 +1383,7 @@ impl PortableService {
.map_err(|e| fail("realm_offline", e.to_string()))?;
let list =
realm::inspect_characters(&db).map_err(|e| fail("realm_offline", e.to_string()))?;
let realm_ruleset = realm::ruleset_of(&db)?;
let mut out = Vec::new();
for c in list {
if self.host.find_by_local(realm_id, c.local_guid)?.is_some() {
@@ -1364,7 +1392,7 @@ impl PortableService {
out.push(LocalCharacterView {
token: c.local_guid,
name: c.name.clone(),
class_name: class_name(&format!("coa:class:{}", c.class)),
class_name: class_name(&format!("{}:class:{}", realm_ruleset.as_str(), c.class)),
level: c.level,
account: c.username.clone().unwrap_or_default(),
eligible: c.eligible(),
@@ -1438,18 +1466,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 +1501,25 @@ impl PortableService {
"The character data does not belong to the character that was claimed.",
));
}
let ruleset = model.ruleset;
for kind in collections.keys() {
if !super::super::session::protocol::carried_kind_for(kind, ruleset) {
return Err(fail(
"incompatible",
format!("Foreign collection kind {kind:?} in {ruleset} claim"),
));
}
}
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 super::super::session::protocol::carried_kind_for(kind, ruleset) {
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 +1535,17 @@ 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 +1631,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;
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,10 +1661,19 @@ impl PortableService {
// Monotonic union of collections
for (kind, ids) in &params.collections {
if matches!(kind.as_str(), "coa:appearance" | "coa:vanity") {
if let Ok(set) = super::super::collection::IdSet::from_ids(ids.iter().copied()) {
let _ = self.host.merge_collection(self.host_profile, kind, &set);
}
if !super::super::session::protocol::carried_kind_for(kind, model.ruleset) {
return Err(fail(
"incompatible",
format!(
"Foreign collection kind {kind:?} in {} remote transfer",
model.ruleset
),
));
}
if let Ok(set) = super::super::collection::IdSet::from_ids(ids.iter().copied()) {
let _ = self
.host
.merge_collection(self.host_profile, model.ruleset, kind, &set);
}
}
@@ -1625,6 +1689,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(),
@@ -53,6 +53,7 @@ pub struct CopyView {
pub struct CharacterView {
pub id: String,
pub name: String,
pub ruleset: super::super::model::Ruleset,
pub class_name: String,
pub race: String,
pub level: u8,
@@ -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,11 @@ 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 +375,14 @@ 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(Ruleset::Coa)
.unwrap();
let states = OwnerService::new(&mut owner).collection_states().unwrap();
assert_eq!(states.len(), 2);
let mut host = Store::open_in_memory().unwrap();
@@ -415,16 +421,17 @@ fn hostile_or_broken_collection_messages_change_nothing() {
let mut owner = Store::open_in_memory().unwrap();
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())
.unwrap();
let good = collection_to_json(
&CollectionObserved::new(SERVER, Ruleset::Coa, APPEARANCE, &ids(1..=10)).unwrap(),
)
.unwrap();
assert_eq!(
o.handle_collection(&good).unwrap().outcome,
CollectionOutcome::Applied
);
let state_of = |o: &OwnerService| {
o.store()
.collection_info(profile, APPEARANCE)
.collection_info(profile, Ruleset::Coa, APPEARANCE)
.unwrap()
.unwrap()
};
@@ -487,13 +494,39 @@ fn hostile_or_broken_collection_messages_change_nothing() {
// a set that decodes to more ids than the cap allows is refused before it is built
let mut huge = vec![1u8];
huge.extend([0xFF, 0xFF, 0xFF, 0xFF, 0x0F]);
let message = serde_json::json!({"protocol_version": PROTOCOL_VERSION, "server_id": SERVER, "kind": APPEARANCE, "set": {"hash": "00".repeat(32), "count": 1, "ids": base64::Engine::encode(&base64::engine::general_purpose::STANDARD, huge)}});
let message = serde_json::json!({"protocol_version": COLLECTION_PROTOCOL_VERSION, "ruleset": "coa", "server_id": SERVER, "kind": APPEARANCE, "set": {"hash": "00".repeat(32), "count": 1, "ids": base64::Engine::encode(&base64::engine::general_purpose::STANDARD, huge)}});
assert!(matches!(
o.handle_collection(&serde_json::to_vec(&message).unwrap())
.unwrap()
.outcome,
CollectionOutcome::Rejected(_)
));
// attack test: prefix-confusion collection kinds are strictly rejected with zero state change
for evil_kind in [
"coax:appearance",
"coaevil:vanity",
"wildcard2:appearance",
"reborn-extra:vanity",
"coa:",
"unknown",
"coa:appearance:extra",
] {
let mut v: serde_json::Value = serde_json::from_slice(&good).unwrap();
v["kind"] = evil_kind.into();
let ack = o
.handle_collection(&serde_json::to_vec(&v).unwrap())
.unwrap();
assert!(
matches!(ack.outcome, CollectionOutcome::Rejected(_)),
"evil kind {evil_kind} must be rejected"
);
}
assert_eq!(
state_of(&o),
before,
"prefix confusion attacks must mutate nothing"
);
}
#[test]
@@ -555,7 +588,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 +598,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 +660,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,
@@ -738,3 +771,102 @@ fn a_session_that_changes_nothing_on_a_format_1_store_makes_no_new_revision() {
"the same character in a newer format is not a change"
);
}
#[test]
fn wildcard_and_coa_collections_remain_strictly_isolated() {
let mut owner = Store::open_in_memory().unwrap();
let profile = owner.default_profile().unwrap();
let coa_set = IdSet::from_ids([10, 20, 30]).unwrap();
let wc_set = IdSet::from_ids([10, 40, 50]).unwrap();
owner
.merge_collection(profile, Ruleset::Coa, "coa:appearance", &coa_set)
.unwrap();
owner
.merge_collection(profile, Ruleset::Wildcard, "wildcard:appearance", &wc_set)
.unwrap();
// Verify initial namespaces
let (_, s_coa) = owner
.collection(profile, Ruleset::Coa, "coa:appearance")
.unwrap()
.unwrap();
assert_eq!(s_coa.ids(), &[10, 20, 30]);
let (_, s_wc) = owner
.collection(profile, Ruleset::Wildcard, "wildcard:appearance")
.unwrap()
.unwrap();
assert_eq!(s_wc.ids(), &[10, 40, 50]);
let mut o = OwnerService::new(&mut owner);
// 1. Valid Wildcard observation updates Wildcard collection only
let wc_update = IdSet::from_ids([10, 40, 50, 60]).unwrap();
let msg_wc = CollectionObserved {
protocol_version: COLLECTION_PROTOCOL_VERSION,
ruleset: Ruleset::Wildcard,
server_id: "wc-realm".into(),
kind: "wildcard:appearance".into(),
set: CompactSet::seal("wildcard:appearance", &wc_update).unwrap(),
};
let ack = o.handle_collection(&to_json(&msg_wc).unwrap()).unwrap();
assert!(matches!(
ack.outcome,
CollectionOutcome::Applied | CollectionOutcome::Unchanged
));
// CoA remains exactly [10, 20, 30]
let (_, s_coa_after) = o
.store()
.collection(profile, Ruleset::Coa, "coa:appearance")
.unwrap()
.unwrap();
assert_eq!(s_coa_after.ids(), &[10, 20, 30]);
// Wildcard updated to [10, 40, 50, 60]
let (_, s_wc_after) = o
.store()
.collection(profile, Ruleset::Wildcard, "wildcard:appearance")
.unwrap()
.unwrap();
assert_eq!(s_wc_after.ids(), &[10, 40, 50, 60]);
// 2. Cross-ruleset injection attack: Wildcard message carrying coa:appearance is rejected
let rogue_wc = CollectionObserved {
protocol_version: COLLECTION_PROTOCOL_VERSION,
ruleset: Ruleset::Wildcard,
server_id: "wc-realm".into(),
kind: "coa:appearance".into(),
set: CompactSet::seal("coa:appearance", &IdSet::from_ids([999]).unwrap()).unwrap(),
};
let ack_rogue = o.handle_collection(&to_json(&rogue_wc).unwrap()).unwrap();
assert!(matches!(ack_rogue.outcome, CollectionOutcome::Rejected(_)));
// 3. Cross-ruleset injection attack: CoA message carrying wildcard:appearance is rejected
let rogue_coa = CollectionObserved {
protocol_version: COLLECTION_PROTOCOL_VERSION,
ruleset: Ruleset::Coa,
server_id: "coa-realm".into(),
kind: "wildcard:appearance".into(),
set: CompactSet::seal("wildcard:appearance", &IdSet::from_ids([999]).unwrap()).unwrap(),
};
let ack_rogue2 = o.handle_collection(&to_json(&rogue_coa).unwrap()).unwrap();
assert!(matches!(ack_rogue2.outcome, CollectionOutcome::Rejected(_)));
// Verify neither 999 touched CoA or Wildcard
let (_, s_coa_final) = o
.store()
.collection(profile, Ruleset::Coa, "coa:appearance")
.unwrap()
.unwrap();
assert_eq!(s_coa_final.ids(), &[10, 20, 30]);
let (_, s_wc_final) = o
.store()
.collection(profile, Ruleset::Wildcard, "wildcard:appearance")
.unwrap()
.unwrap();
assert_eq!(s_wc_final.ids(), &[10, 40, 50, 60]);
}
+8 -4
View File
@@ -467,16 +467,20 @@ impl RealmBridge for FakeRealm {
impl FakeRealm {
fn rows(&self, kind: &str) -> Result<&IdSet> {
match kind {
"coa:appearance" => Ok(&self.appearance_rows),
"coa:vanity" => Ok(&self.vanity_rows),
"coa:appearance" | "wildcard:appearance" | "reborn:appearance" => {
Ok(&self.appearance_rows)
}
"coa:vanity" | "wildcard:vanity" | "reborn:vanity" => Ok(&self.vanity_rows),
other => Err(PortableError::Invalid(format!("unknown kind {other}"))),
}
}
fn rows_mut(&mut self, kind: &str) -> Result<&mut IdSet> {
match kind {
"coa:appearance" => Ok(&mut self.appearance_rows),
"coa:vanity" => Ok(&mut self.vanity_rows),
"coa:appearance" | "wildcard:appearance" | "reborn:appearance" => {
Ok(&mut self.appearance_rows)
}
"coa:vanity" | "wildcard:vanity" | "reborn:vanity" => Ok(&mut self.vanity_rows),
other => Err(PortableError::Invalid(format!("unknown kind {other}"))),
}
}
+39 -5
View File
@@ -176,6 +176,26 @@ impl<'a> HostService<'a> {
found: model.character_id,
});
}
if offer.ruleset != model.ruleset {
return Err(PortableError::RulesetMismatch {
character: model.ruleset,
realm: offer.ruleset,
});
}
if let Some((_, rs)) = self.server_id.split_once(':') {
let host_ruleset = rs.parse::<crate::portable::Ruleset>().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
.host_install_copy(profile, &model, offer.canonical_revision, "owner")?;
self.store.host_prepare_session(offer, &model)
@@ -606,8 +626,16 @@ 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 +647,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<HostEvent>,
@@ -644,7 +673,12 @@ 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 +708,7 @@ impl<'a> HostService<'a> {
account: u32,
ack: &CollectionAck,
) -> Result<Option<Applied>> {
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 +776,7 @@ impl<'a> HostService<'a> {
account: u32,
state: &CollectionState,
) -> Result<Option<Applied>> {
if !carried_kind(&state.kind) {
if !carried_kind_for(&state.kind, state.ruleset) {
return Err(PortableError::Invalid(
"the collection kind is not carried".into(),
));
+31 -14
View File
@@ -49,10 +49,15 @@ impl<'a> OwnerService<'a> {
pub fn handle_collection(&mut self, bytes: &[u8]) -> Result<CollectionAck> {
let msg: CollectionObserved = collection_from_json(bytes)?;
let profile = self.store.default_profile()?;
let ruleset = msg.ruleset;
let rejected = |store: &Store, reason: &str| -> Result<CollectionAck> {
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,
protocol_version: crate::portable::session::protocol::COLLECTION_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,30 +65,39 @@ 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 (
&info,
observed.count_new(&canonical) == 0 && canonical.count_new(&observed) == 0,
) {
(Some(info), false) => {
Some(CollectionState::new(&msg.kind, info.revision, &canonical)?)
}
(Some(info), false) => Some(CollectionState::new(
ruleset,
&msg.kind,
info.revision,
&canonical,
)?),
_ => None,
};
Ok(CollectionAck {
protocol_version: PROTOCOL_VERSION,
protocol_version: crate::portable::session::protocol::COLLECTION_PROTOCOL_VERSION,
ruleset,
kind: msg.kind,
outcome: if merge.changed {
CollectionOutcome::Applied
@@ -97,12 +111,15 @@ 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<Vec<CollectionState>> {
pub fn collection_states(
&mut self,
ruleset: crate::portable::model::Ruleset,
) -> Result<Vec<CollectionState>> {
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)
@@ -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
@@ -371,9 +371,10 @@ fn a_session_started_without_its_projection_or_with_a_wrong_one_is_not_opened()
);
// an older protocol is not understood at all
let old = String::from_utf8(genuine.clone())
.unwrap()
.replace("\"protocol_version\":2", "\"protocol_version\":1");
let old = String::from_utf8(genuine.clone()).unwrap().replace(
&format!("\"protocol_version\":{PROTOCOL_VERSION}"),
"\"protocol_version\":1",
);
assert!(o.handle_started(old.as_bytes()).is_err());
assert_eq!(
o.handle_started(&genuine).unwrap().outcome,
+185 -19
View File
@@ -13,14 +13,19 @@ use super::super::model::{limits::MAX_COMPRESSED_BYTES, PortableCharacter};
use super::super::projection::{ProgressionPin, ProjectionContext};
use super::super::snapshot;
/// Version 2 (Phase 8): `PortableSessionStarted` carries the progression the session runs under, every `PortableCheckpoint` and `OwnerAck` its pin.
/// A version 1 peer and a version 2 peer read each other's messages as unsupported, and the realm's capability profile (`session_protocol`)
/// says so before any character is armed.
pub const PROTOCOL_VERSION: u32 = 2;
/// Version 3: `SessionOffer`, `PortableSessionStarted`, `PortableCheckpoint`, and `OwnerAck` require explicit `ruleset`.
/// Version 2 (Phase 8): `PortableSessionStarted` carried progression and pins.
pub const SESSION_PROTOCOL_VERSION: u32 = 3;
/// Protocol version for collection synchronization (`CollectionObserved`, `CollectionState`, `CollectionAck`).
pub const COLLECTION_PROTOCOL_VERSION: u32 = 2;
/// Backward-compatibility alias for session protocol version.
pub const PROTOCOL_VERSION: u32 = SESSION_PROTOCOL_VERSION;
/// A message carries at most one compressed snapshot (base64: 4/3) plus a little structure.
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;
/// A sealed snapshot: the hash of the canonical JSON and the compressed bytes.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
@@ -79,6 +84,7 @@ impl Envelope {
#[serde(deny_unknown_fields)]
pub struct SessionOffer {
pub protocol_version: u32,
pub ruleset: super::super::model::Ruleset,
pub session_id: SessionId,
pub character_id: CharacterId,
pub server_id: String,
@@ -123,6 +129,7 @@ impl SessionProgression {
#[serde(deny_unknown_fields)]
pub struct PortableSessionStarted {
pub protocol_version: u32,
pub ruleset: super::super::model::Ruleset,
pub session_id: SessionId,
pub character_id: CharacterId,
pub server_id: String,
@@ -139,6 +146,7 @@ pub struct PortableSessionStarted {
#[serde(deny_unknown_fields)]
pub struct PortableCheckpoint {
pub protocol_version: u32,
pub ruleset: super::super::model::Ruleset,
pub session_id: SessionId,
pub character_id: CharacterId,
pub server_id: String,
@@ -188,6 +196,7 @@ pub struct NextSession {
#[serde(deny_unknown_fields)]
pub struct OwnerAck {
pub protocol_version: u32,
pub ruleset: super::super::model::Ruleset,
pub session_id: SessionId,
/// 0 acknowledges `PortableSessionStarted`.
pub sequence: u64,
@@ -250,16 +259,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 +289,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 +311,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 +393,7 @@ impl CompactSet {
#[serde(deny_unknown_fields)]
pub struct CollectionObserved {
pub protocol_version: u32,
pub ruleset: super::super::model::Ruleset,
pub server_id: String,
pub kind: String,
pub set: CompactSet,
@@ -375,6 +404,7 @@ pub struct CollectionObserved {
#[serde(deny_unknown_fields)]
pub struct CollectionState {
pub protocol_version: u32,
pub ruleset: super::super::model::Ruleset,
pub kind: String,
pub collection_revision: u64,
pub set: CompactSet,
@@ -400,6 +430,7 @@ pub enum CollectionOutcome {
#[serde(deny_unknown_fields)]
pub struct CollectionAck {
pub protocol_version: u32,
pub ruleset: super::super::model::Ruleset,
pub kind: String,
pub outcome: CollectionOutcome,
pub collection_revision: u64,
@@ -430,24 +461,30 @@ pub fn collection_from_json<T: DeserializeOwned>(bytes: &[u8]) -> Result<T> {
.get("protocol_version")
.and_then(|v| v.as_u64())
.ok_or_else(|| PortableError::Invalid("the message has no protocol version".into()))?;
if version != PROTOCOL_VERSION as u64 {
if version != COLLECTION_PROTOCOL_VERSION as u64 {
return Err(PortableError::UnsupportedFormat {
found: version.min(u32::MAX as u64) as u32,
supported: PROTOCOL_VERSION,
supported: COLLECTION_PROTOCOL_VERSION,
});
}
Ok(serde_json::from_value(value)?)
}
impl CollectionObserved {
pub fn new(server_id: &str, kind: &str, set: &IdSet) -> Result<Self> {
if !carried_kind(kind) {
pub fn new(
server_id: &str,
ruleset: super::super::model::Ruleset,
kind: &str,
set: &IdSet,
) -> Result<Self> {
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,
protocol_version: COLLECTION_PROTOCOL_VERSION,
ruleset,
server_id: server_id.to_string(),
kind: kind.to_string(),
set: CompactSet::seal(kind, set)?,
@@ -456,12 +493,141 @@ impl CollectionObserved {
}
impl CollectionState {
pub fn new(kind: &str, revision: u64, set: &IdSet) -> Result<Self> {
pub fn new(
ruleset: super::super::model::Ruleset,
kind: &str,
revision: u64,
set: &IdSet,
) -> Result<Self> {
Ok(Self {
protocol_version: PROTOCOL_VERSION,
protocol_version: COLLECTION_PROTOCOL_VERSION,
ruleset,
kind: kind.to_string(),
collection_revision: revision,
set: CompactSet::seal(kind, set)?,
})
}
}
/// Legacy Session Protocol v2 representation (Phase 8), where absence of ruleset is defined to mean CoA.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct LegacyV2SessionOffer {
pub protocol_version: u32,
pub session_id: SessionId,
pub character_id: CharacterId,
pub server_id: String,
pub canonical_revision: u64,
pub snapshot: Envelope,
}
impl LegacyV2SessionOffer {
pub fn into_session_offer(self) -> SessionOffer {
SessionOffer {
protocol_version: SESSION_PROTOCOL_VERSION,
ruleset: super::super::model::Ruleset::Coa,
session_id: self.session_id,
character_id: self.character_id,
server_id: self.server_id,
canonical_revision: self.canonical_revision,
snapshot: self.snapshot,
}
}
}
#[cfg(test)]
mod protocol_tests {
use super::*;
use crate::portable::Ruleset;
#[test]
fn session_protocol_v3_requires_ruleset_and_rejects_missing_or_unknown() {
let envelope = Envelope {
content_hash: "00".repeat(32),
payload: "AA==".to_string(),
};
// 1. Valid v3 SessionOffer with explicit ruleset (CoA, Wildcard, Reborn)
for r in [Ruleset::Coa, Ruleset::Wildcard, Ruleset::Reborn] {
let offer = SessionOffer {
protocol_version: SESSION_PROTOCOL_VERSION,
ruleset: r,
session_id: SessionId::new(),
character_id: CharacterId::new(),
server_id: "realm-1".to_string(),
canonical_revision: 1,
snapshot: envelope.clone(),
};
let bytes = to_json(&offer).unwrap();
let parsed: SessionOffer = from_json(&bytes).unwrap();
assert_eq!(parsed.ruleset, r);
}
// 2. Missing ruleset in v3 JSON is rejected (never silently defaults to CoA)
let missing_ruleset_v3 = serde_json::json!({
"protocol_version": SESSION_PROTOCOL_VERSION,
"session_id": SessionId::new().to_string(),
"character_id": CharacterId::new().to_string(),
"server_id": "realm-1",
"canonical_revision": 1,
"snapshot": {
"content_hash": "00".repeat(32),
"payload": "AA=="
}
});
let bytes = serde_json::to_vec(&missing_ruleset_v3).unwrap();
let err: std::result::Result<SessionOffer, _> = from_json(&bytes);
assert!(
err.is_err(),
"missing ruleset must be rejected in protocol v3"
);
// 3. Unknown ruleset in v3 JSON is rejected
let unknown_ruleset_v3 = serde_json::json!({
"protocol_version": SESSION_PROTOCOL_VERSION,
"ruleset": "cyberpunk",
"session_id": SessionId::new().to_string(),
"character_id": CharacterId::new().to_string(),
"server_id": "realm-1",
"canonical_revision": 1,
"snapshot": {
"content_hash": "00".repeat(32),
"payload": "AA=="
}
});
let bytes = serde_json::to_vec(&unknown_ruleset_v3).unwrap();
let err: std::result::Result<SessionOffer, _> = from_json(&bytes);
assert!(err.is_err(), "unknown ruleset must be rejected");
// 4. Old v2 peer message (protocol_version 2) is rejected by current v3 parser
let legacy_v2_json = serde_json::json!({
"protocol_version": 2,
"session_id": SessionId::new().to_string(),
"character_id": CharacterId::new().to_string(),
"server_id": "realm-1",
"canonical_revision": 1,
"snapshot": {
"content_hash": "00".repeat(32),
"payload": "AA=="
}
});
let bytes = serde_json::to_vec(&legacy_v2_json).unwrap();
let err: std::result::Result<SessionOffer, _> = from_json(&bytes);
assert!(
matches!(
err,
Err(PortableError::UnsupportedFormat {
found: 2,
supported: 3
})
),
"v2 peer must be rejected with UnsupportedFormat"
);
// 5. Explicit LegacyV2SessionOffer decode correctly interprets absence of ruleset as CoA
let v2_parsed: LegacyV2SessionOffer = serde_json::from_slice(&bytes).unwrap();
let upgraded = v2_parsed.into_session_offer();
assert_eq!(upgraded.ruleset, Ruleset::Coa);
assert_eq!(upgraded.protocol_version, SESSION_PROTOCOL_VERSION);
}
}
@@ -4,6 +4,7 @@ use super::bridge::*;
use super::fake::*;
use super::protocol::*;
use super::*;
use crate::portable::error::PortableError;
use crate::portable::fixtures::geared_level_eighty;
use crate::portable::ids::{CharacterId, PortableItemId, SessionId};
use crate::portable::model::*;
@@ -1051,3 +1052,611 @@ fn an_autosave_between_checkpoints_is_harmless() {
c0.progression.money + 10
);
}
fn setup_wildcard_in(mut owner: Store, mut host: Store, server_id: &str) -> Setup {
let profile = owner.default_profile().unwrap();
let mut model = geared_level_eighty();
model.ruleset = Ruleset::Wildcard;
model.content_namespace = "wildcard".into();
let id = owner
.create_character(profile, model, "wildcard-origin")
.unwrap();
let c0 = owner.load_current(id).unwrap();
let offer = OwnerService::new(&mut owner).offer(id, server_id).unwrap();
let host_profile = host.default_profile().unwrap();
let mut realm = FakeRealm::new(GUID);
realm.normalize = normalizes;
{
let mut h = HostService::new(&mut host, server_id, HostConfig::default());
h.accept_offer(host_profile, &offer).unwrap();
realm
.import(
&mut host,
id,
server_id,
offer.canonical_revision,
offer.session_id,
)
.unwrap();
HostService::new(&mut host, server_id, HostConfig::default())
.bind(offer.session_id, GUID)
.unwrap();
}
Setup {
owner,
host,
realm,
id,
session: offer.session_id,
c0,
}
}
fn setup_reborn_in(mut owner: Store, mut host: Store, server_id: &str) -> Setup {
let profile = owner.default_profile().unwrap();
let mut model = geared_level_eighty();
model.ruleset = Ruleset::Reborn;
model.content_namespace = "reborn".into();
let id = owner
.create_character(profile, model, "reborn-origin")
.unwrap();
let c0 = owner.load_current(id).unwrap();
let offer = OwnerService::new(&mut owner).offer(id, server_id).unwrap();
let host_profile = host.default_profile().unwrap();
let mut realm = FakeRealm::new(GUID);
realm.normalize = normalizes;
{
let mut h = HostService::new(&mut host, server_id, HostConfig::default());
h.accept_offer(host_profile, &offer).unwrap();
realm
.import(
&mut host,
id,
server_id,
offer.canonical_revision,
offer.session_id,
)
.unwrap();
HostService::new(&mut host, server_id, HostConfig::default())
.bind(offer.session_id, GUID)
.unwrap();
}
Setup {
owner,
host,
realm,
id,
session: offer.session_id,
c0,
}
}
#[test]
fn wildcard_session_offer_carrying_coa_snapshot_is_rejected_with_zero_mutation() {
let mut owner = Store::open_in_memory().unwrap();
let mut host = Store::open_in_memory().unwrap();
let profile = owner.default_profile().unwrap();
let host_profile = host.default_profile().unwrap();
let coa_model = geared_level_eighty();
let id = owner
.create_character(profile, coa_model, "realm-a")
.unwrap();
let mut offer = OwnerService::new(&mut owner)
.offer(id, "srv-1:wildcard")
.unwrap();
// Tamper offer: claim it is Wildcard while snapshot is CoA
offer.ruleset = Ruleset::Wildcard;
let mut h = HostService::new(&mut host, "srv-1:wildcard", HostConfig::default());
let res = h.accept_offer(host_profile, &offer);
assert!(matches!(
res,
Err(PortableError::RulesetMismatch {
character: Ruleset::Coa,
realm: Ruleset::Wildcard
})
));
// Zero mutation on host
assert!(host.character(id).is_err());
assert!(host.host_session(offer.session_id).unwrap().is_none());
}
#[test]
fn wildcard_portable_session_started_marked_coa_is_rejected() {
let Setup {
mut owner,
mut host,
mut realm,
session,
..
} = setup_wildcard_in(
Store::open_in_memory().unwrap(),
Store::open_in_memory().unwrap(),
"srv-1:wildcard",
);
let mut h = HostService::new(&mut host, "srv-1:wildcard", HostConfig::default());
let mut o = OwnerService::new(&mut owner);
realm.login();
h.tick(&mut realm, 0).unwrap();
let outbox = h.outbox().unwrap();
assert_eq!(outbox.len(), 1);
let mut started: PortableSessionStarted = from_json(&outbox[0].bytes).unwrap();
// Tamper: mark as CoA
started.ruleset = Ruleset::Coa;
let tampered_bytes = to_json(&started).unwrap();
let ack = o.handle_started(&tampered_bytes).unwrap();
assert!(matches!(ack.outcome, AckOutcome::Rejected(_)));
// Owner session remains offered, never open
let (state, _, _) = o.session(session).unwrap().unwrap();
assert_eq!(state, "offered");
}
#[test]
fn wildcard_checkpoint_marked_reborn_is_rejected() {
let Setup {
mut owner,
mut host,
mut realm,
id,
..
} = setup_wildcard_in(
Store::open_in_memory().unwrap(),
Store::open_in_memory().unwrap(),
"srv-1:wildcard",
);
let mut h = HostService::new(&mut host, "srv-1:wildcard", HostConfig::default());
let mut o = OwnerService::new(&mut owner);
start(&mut h, &mut o, &mut realm);
realm.play(|m| m.progression.money += 500);
h.tick(&mut realm, 100).unwrap();
h.tick(&mut realm, 101).unwrap();
let outbox = h.outbox().unwrap();
let checkpoint_msg = outbox.iter().find(|m| !m.started).unwrap();
let mut cp: PortableCheckpoint = from_json(&checkpoint_msg.bytes).unwrap();
// Tamper: mark as Reborn
cp.ruleset = Ruleset::Reborn;
let tampered_bytes = to_json(&cp).unwrap();
let initial_rev = o.store().character(id).unwrap().revision;
let initial_snapshot = o.store().load_snapshot(id, initial_rev).unwrap();
let ack = o.handle_checkpoint(&tampered_bytes).unwrap();
assert!(matches!(ack.outcome, AckOutcome::Rejected(_)));
// Zero canonical revision change or mutation
assert_eq!(o.store().character(id).unwrap().revision, initial_rev);
assert_eq!(
o.store().load_snapshot(id, initial_rev).unwrap(),
initial_snapshot
);
}
#[test]
fn wildcard_session_using_coa_server_id_is_rejected() {
let mut owner = Store::open_in_memory().unwrap();
let mut host = Store::open_in_memory().unwrap();
let profile = owner.default_profile().unwrap();
let host_profile = host.default_profile().unwrap();
let mut model = geared_level_eighty();
model.ruleset = Ruleset::Wildcard;
let id = owner
.create_character(profile, model, "wildcard-origin")
.unwrap();
// Offer for srv-1:coa
let offer = OwnerService::new(&mut owner)
.offer(id, "srv-1:coa")
.unwrap();
// Host configured for Wildcard realm
let mut h = HostService::new(&mut host, "srv-1:wildcard", HostConfig::default());
let res = h.accept_offer(host_profile, &offer);
assert!(matches!(res, Err(PortableError::Invalid(_))));
}
#[test]
fn same_character_id_with_foreign_ruleset_is_rejected() {
let mut owner = Store::open_in_memory().unwrap();
let profile = owner.default_profile().unwrap();
let mut model = geared_level_eighty();
model.ruleset = Ruleset::Wildcard;
let id = owner
.create_character(profile, model.clone(), "srv-1:wildcard")
.unwrap();
// Tampered snapshot with same ID but Ruleset::Coa
let mut tampered = model.clone();
tampered.character_id = id;
tampered.ruleset = Ruleset::Coa;
let res = owner.commit_snapshot(id, 1, tampered, "srv-1:wildcard", None);
assert!(matches!(res, Err(PortableError::RulesetChange { .. })));
}
#[test]
fn owner_ack_with_different_ruleset_is_rejected_by_host() {
let Setup {
mut owner,
mut host,
mut realm,
..
} = setup_wildcard_in(
Store::open_in_memory().unwrap(),
Store::open_in_memory().unwrap(),
"srv-1:wildcard",
);
let mut h = HostService::new(&mut host, "srv-1:wildcard", HostConfig::default());
let mut o = OwnerService::new(&mut owner);
realm.login();
h.tick(&mut realm, 0).unwrap();
let outbox = h.outbox().unwrap();
let mut ack = o.handle_started(&outbox[0].bytes).unwrap();
// Tamper ack ruleset to CoA
ack.ruleset = Ruleset::Coa;
let res = h.receive_ack(&mut realm, &ack);
assert!(matches!(
res,
Err(PortableError::RulesetMismatch {
character: Ruleset::Wildcard,
realm: Ruleset::Coa
})
));
}
#[test]
fn final_checkpoint_relabelled_coa_is_rejected() {
let Setup {
mut owner,
mut host,
mut realm,
id,
..
} = setup_wildcard_in(
Store::open_in_memory().unwrap(),
Store::open_in_memory().unwrap(),
"srv-1:wildcard",
);
let mut h = HostService::new(&mut host, "srv-1:wildcard", HostConfig::default());
let mut o = OwnerService::new(&mut owner);
start(&mut h, &mut o, &mut realm);
realm.play(|m| m.progression.money += 1000);
realm.logout();
h.tick(&mut realm, 100).unwrap();
h.tick(&mut realm, 101).unwrap();
let outbox = h.outbox().unwrap();
let final_cp_msg = outbox.iter().find(|m| !m.started).unwrap();
let mut cp: PortableCheckpoint = from_json(&final_cp_msg.bytes).unwrap();
assert!(cp.final_checkpoint);
// Relabel as CoA
cp.ruleset = Ruleset::Coa;
let tampered_bytes = to_json(&cp).unwrap();
let initial_rev = o.store().character(id).unwrap().revision;
let ack = o.handle_checkpoint(&tampered_bytes).unwrap();
assert!(matches!(ack.outcome, AckOutcome::Rejected(_)));
// Revision must not advance and state must not be committed
assert_eq!(o.store().character(id).unwrap().revision, initial_rev);
}
#[test]
fn full_wildcard_session_lifecycle() {
let Setup {
mut owner,
mut host,
mut realm,
id,
session,
c0,
} = setup_wildcard_in(
Store::open_in_memory().unwrap(),
Store::open_in_memory().unwrap(),
"srv-1:wildcard",
);
let mut h = HostService::new(&mut host, "srv-1:wildcard", HostConfig::default());
let mut o = OwnerService::new(&mut owner);
// 1. Start session
start(&mut h, &mut o, &mut realm);
assert_eq!(o.session(session).unwrap().unwrap().0, "open");
// 2. Play on Wildcard realm: earn gold and level up
realm.play(|m| {
m.progression.money += 50_000;
m.progression.xp += 1_000;
});
// 3. Online checkpoint
checkpoint(&mut h, &mut o, &mut realm, 100);
let rev2 = o.store().character(id).unwrap().revision;
assert_eq!(rev2, 2);
let curr2 = o.store().load_current(id).unwrap();
assert_eq!(curr2.ruleset, Ruleset::Wildcard);
assert_eq!(curr2.progression.money, c0.progression.money + 50_000);
// 4. More gameplay then logout
realm.play(|m| {
m.progression.money += 25_000;
});
realm.logout();
h.tick(&mut realm, 200).unwrap();
h.tick(&mut realm, 201).unwrap();
let acks = deliver(&mut h, &mut o, &mut realm);
assert!(acks.iter().any(|a| a.outcome == AckOutcome::Applied));
// 5. Verify final canonical state
let rec = o.store().character(id).unwrap();
assert_eq!(rec.revision, 3);
assert_eq!(rec.ruleset, Ruleset::Wildcard);
let final_model = o.store().load_current(id).unwrap();
assert_eq!(final_model.ruleset, Ruleset::Wildcard);
assert_eq!(final_model.progression.money, c0.progression.money + 75_000);
}
#[test]
fn reborn_hostile_attacks_are_rejected_with_zero_mutation() {
let mut owner = Store::open_in_memory().unwrap();
let mut host = Store::open_in_memory().unwrap();
let profile = owner.default_profile().unwrap();
let host_profile = host.default_profile().unwrap();
let coa_model = geared_level_eighty();
let id_coa = owner
.create_character(profile, coa_model, "realm-coa")
.unwrap();
let mut wc_model = geared_level_eighty();
wc_model.ruleset = Ruleset::Wildcard;
let id_wc = owner
.create_character(profile, wc_model, "realm-wc")
.unwrap();
let mut reb_model = geared_level_eighty();
reb_model.ruleset = Ruleset::Reborn;
let id_reb = owner
.create_character(profile, reb_model, "realm-reb")
.unwrap();
// 1. Reborn offer carrying CoA snapshot
let mut offer_reb_with_coa = OwnerService::new(&mut owner)
.offer(id_coa, "srv-1:reborn")
.unwrap();
offer_reb_with_coa.ruleset = Ruleset::Reborn;
{
let mut h_reborn = HostService::new(&mut host, "srv-1:reborn", HostConfig::default());
let res1 = h_reborn.accept_offer(host_profile, &offer_reb_with_coa);
assert!(matches!(
res1,
Err(PortableError::RulesetMismatch {
character: Ruleset::Coa,
realm: Ruleset::Reborn
})
));
}
assert!(host.character(id_coa).is_err());
// 2. Reborn offer carrying Wildcard snapshot
let mut offer_reb_with_wc = OwnerService::new(&mut owner)
.offer(id_wc, "srv-1:reborn")
.unwrap();
offer_reb_with_wc.ruleset = Ruleset::Reborn;
{
let mut h_reborn = HostService::new(&mut host, "srv-1:reborn", HostConfig::default());
let res2 = h_reborn.accept_offer(host_profile, &offer_reb_with_wc);
assert!(matches!(
res2,
Err(PortableError::RulesetMismatch {
character: Ruleset::Wildcard,
realm: Ruleset::Reborn
})
));
}
assert!(host.character(id_wc).is_err());
// 3. CoA offer -> Reborn realm
let mut offer_coa = OwnerService::new(&mut owner)
.offer(id_coa, "srv-1:reborn")
.unwrap();
offer_coa.ruleset = Ruleset::Coa;
{
let mut h_reborn = HostService::new(&mut host, "srv-1:reborn", HostConfig::default());
let res3 = h_reborn.accept_offer(host_profile, &offer_coa);
assert!(matches!(
res3,
Err(PortableError::RulesetMismatch {
character: Ruleset::Coa,
realm: Ruleset::Reborn
})
));
}
// 4. Wildcard offer -> Reborn realm
let mut offer_wc = OwnerService::new(&mut owner)
.offer(id_wc, "srv-1:reborn")
.unwrap();
offer_wc.ruleset = Ruleset::Wildcard;
{
let mut h_reborn = HostService::new(&mut host, "srv-1:reborn", HostConfig::default());
let res4 = h_reborn.accept_offer(host_profile, &offer_wc);
assert!(matches!(
res4,
Err(PortableError::RulesetMismatch {
character: Ruleset::Wildcard,
realm: Ruleset::Reborn
})
));
}
// 5. Reborn offer -> CoA realm
let mut offer_reb = OwnerService::new(&mut owner)
.offer(id_reb, "srv-1:coa")
.unwrap();
offer_reb.ruleset = Ruleset::Reborn;
{
let mut h_coa = HostService::new(&mut host, "srv-1:coa", HostConfig::default());
let res5 = h_coa.accept_offer(host_profile, &offer_reb);
assert!(matches!(
res5,
Err(PortableError::RulesetMismatch {
character: Ruleset::Reborn,
realm: Ruleset::Coa
})
));
}
// 6. Reborn offer -> Wildcard realm
let mut offer_reb_to_wc = OwnerService::new(&mut owner)
.offer(id_reb, "srv-1:wildcard")
.unwrap();
offer_reb_to_wc.ruleset = Ruleset::Reborn;
{
let mut h_wc = HostService::new(&mut host, "srv-1:wildcard", HostConfig::default());
let res6 = h_wc.accept_offer(host_profile, &offer_reb_to_wc);
assert!(matches!(
res6,
Err(PortableError::RulesetMismatch {
character: Ruleset::Reborn,
realm: Ruleset::Wildcard
})
));
}
// 7. Reborn session using foreign server ID srv-1:coa or srv-1:wildcard
{
let mut h_reborn = HostService::new(&mut host, "srv-1:reborn", HostConfig::default());
let offer_for_coa = OwnerService::new(&mut owner)
.offer(id_reb, "srv-1:coa")
.unwrap();
let res7 = h_reborn.accept_offer(host_profile, &offer_for_coa);
assert!(res7.is_err());
let offer_for_wc = OwnerService::new(&mut owner)
.offer(id_reb, "srv-1:wildcard")
.unwrap();
let res8 = h_reborn.accept_offer(host_profile, &offer_for_wc);
assert!(res8.is_err());
}
// 8. Reborn collection containing foreign collections coa:appearance or wildcard:vanity
let coll_err1 = host.merge_collection(
host_profile,
Ruleset::Reborn,
"coa:appearance",
&crate::portable::IdSet::from_ids([1]).unwrap(),
);
assert!(
coll_err1.is_err(),
"Reborn merging coa:appearance must fail"
);
let coll_err2 = host.merge_collection(
host_profile,
Ruleset::Reborn,
"wildcard:vanity",
&crate::portable::IdSet::from_ids([1]).unwrap(),
);
assert!(
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]
fn full_reborn_session_lifecycle() {
let Setup {
mut owner,
mut host,
mut realm,
id,
session,
c0,
} = setup_reborn_in(
Store::open_in_memory().unwrap(),
Store::open_in_memory().unwrap(),
"srv-1:reborn",
);
let mut h = HostService::new(&mut host, "srv-1:reborn", HostConfig::default());
let mut o = OwnerService::new(&mut owner);
// 1. Start session
start(&mut h, &mut o, &mut realm);
assert_eq!(o.session(session).unwrap().unwrap().0, "open");
// 2. Play on Reborn realm: earn gold and level up
realm.play(|m| {
m.progression.money += 100_000;
m.progression.xp += 5_000;
});
// 3. Online checkpoint
checkpoint(&mut h, &mut o, &mut realm, 100);
let rev2 = o.store().character(id).unwrap().revision;
assert_eq!(rev2, 2);
let curr2 = o.store().load_current(id).unwrap();
assert_eq!(curr2.ruleset, Ruleset::Reborn);
assert_eq!(curr2.progression.money, c0.progression.money + 100_000);
// 4. Test Reborn checkpoint marked CoA / Wildcard rejected by owner
let outbox = h.outbox().unwrap();
if let Some(msg) = outbox.first() {
let mut cp: PortableCheckpoint = from_json(&msg.bytes).unwrap();
cp.ruleset = Ruleset::Coa;
let tampered_bytes = to_json(&cp).unwrap();
let initial_rev = o.store().character(id).unwrap().revision;
let ack = o.handle_checkpoint(&tampered_bytes).unwrap();
assert!(matches!(ack.outcome, AckOutcome::Rejected(_)));
assert_eq!(o.store().character(id).unwrap().revision, initial_rev);
}
// 5. Test OwnerAck marked CoA rejected by Reborn host
if let Some(msg) = outbox.first() {
if let Ok(mut ack) = o.handle_checkpoint(&msg.bytes) {
ack.ruleset = Ruleset::Coa;
let res_ack = h.receive_ack(&mut realm, &ack);
assert!(matches!(
res_ack,
Err(PortableError::RulesetMismatch {
character: Ruleset::Reborn,
realm: Ruleset::Coa
})
));
}
}
// 6. More gameplay then logout
realm.play(|m| {
m.progression.money += 50_000;
});
realm.logout();
h.tick(&mut realm, 200).unwrap();
h.tick(&mut realm, 201).unwrap();
let acks = deliver(&mut h, &mut o, &mut realm);
assert!(acks.iter().any(|a| a.outcome == AckOutcome::Applied));
// 7. Verify final canonical state
let rec = o.store().character(id).unwrap();
assert_eq!(rec.revision, 3);
assert_eq!(rec.ruleset, Ruleset::Reborn);
let final_model = o.store().load_current(id).unwrap();
assert_eq!(final_model.ruleset, Ruleset::Reborn);
assert_eq!(
final_model.progression.money,
c0.progression.money + 150_000
);
}
+89 -11
View File
@@ -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<Store> {
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)
}
@@ -205,11 +206,13 @@ impl Store {
});
}
for next in version..supported {
self.conn.pragma_update(None, "foreign_keys", false)?;
let tx = self.conn.transaction()?;
tx.execute_batch(MIGRATIONS[next as usize])?;
tx.pragma_update(None, "application_id", APPLICATION_ID)?;
tx.pragma_update(None, "user_version", next + 1)?;
tx.commit()?;
self.conn.pragma_update(None, "foreign_keys", true)?;
}
Ok(())
}
@@ -328,6 +331,23 @@ impl Store {
read_character(&self.conn, id)
}
pub fn get_character(
&self,
id: CharacterId,
expected_ruleset: Option<Ruleset>,
) -> Result<CharacterRecord> {
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<Vec<CharacterRecord>> {
let mut stmt = self.conn.prepare(
"SELECT character_id FROM character WHERE profile_id = ?1 ORDER BY character_id",
@@ -340,6 +360,22 @@ impl Store {
.collect()
}
pub fn list_characters_by_ruleset(
&self,
profile: ProfileId,
ruleset: Ruleset,
) -> Result<Vec<CharacterRecord>> {
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<String> = stmt
.query_map(params![profile.to_string(), ruleset.as_str()], |r| r.get(0))?
.collect::<std::result::Result<_, _>>()?;
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<Vec<CharacterRecord>> {
let mut stmt = self
@@ -663,6 +699,7 @@ impl Store {
pub fn merge_collection(
&mut self,
profile: ProfileId,
ruleset: Ruleset,
kind: &str,
incoming: &IdSet,
) -> Result<CollectionMerge> {
@@ -671,6 +708,13 @@ impl Store {
"invalid collection kind {kind:?}"
)));
}
if let Some((ns, _)) = kind.split_once(':') {
if matches!(ns, "coa" | "wildcard" | "reborn") && ns != ruleset.as_str() {
return Err(PortableError::Invalid(format!(
"collection kind namespace {ns:?} does not match ruleset {ruleset:?}"
)));
}
}
let tx = self.write_tx()?;
let profile_exists: bool = tx.query_row(
"SELECT EXISTS(SELECT 1 FROM profile WHERE profile_id = ?1)",
@@ -682,7 +726,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 +745,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 +769,14 @@ impl Store {
pub fn collection_info(
&self,
profile: ProfileId,
ruleset: Ruleset,
kind: &str,
) -> Result<Option<CollectionInfo>> {
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<u8>>(1)?, r.get::<_, i64>(2)?, r.get::<_, String>(3)?)),
)
.optional()?;
@@ -750,9 +795,41 @@ impl Store {
pub fn collection(
&self,
profile: ProfileId,
ruleset: Ruleset,
kind: &str,
) -> Result<Option<(CollectionInfo, IdSet)>> {
read_collection(&self.conn, profile, kind)
read_collection(&self.conn, profile, ruleset, kind)
}
pub fn list_collections(
&self,
profile: ProfileId,
ruleset: Ruleset,
) -> Result<Vec<CollectionInfo>> {
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<u8>>(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 +853,13 @@ impl Store {
fn read_collection(
conn: &Connection,
profile: ProfileId,
ruleset: Ruleset,
kind: &str,
) -> Result<Option<(CollectionInfo, IdSet)>> {
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<u8>>(1)?, r.get::<_, i64>(2)?, r.get::<_, String>(3)?, r.get::<_, Vec<u8>>(4)?)),
)
.optional()?;
@@ -579,6 +579,13 @@ impl Store {
Some(_) => {}
}
let at = now();
let record = read_character(&tx, s.character_id)?;
if ack.ruleset != record.ruleset {
return Err(PortableError::RulesetMismatch {
character: record.ruleset,
realm: ack.ruleset,
});
}
if ack.outcome.accepted() && ack.pin != s.pin {
return Err(PortableError::ProgressionChanged(
"the acknowledgement is under another progression profile than the session".into(),
+34 -4
View File
@@ -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()),
@@ -324,10 +338,23 @@ 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);
let outcome = |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 +381,7 @@ impl Store {
}
let revision = revision as u64;
let mut a = ack(
record.ruleset,
msg.session_id,
msg.sequence,
AckOutcome::Duplicate,
@@ -390,6 +418,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 +486,7 @@ impl Store {
};
let mut a = ack(
record.ruleset,
msg.session_id,
msg.sequence,
AckOutcome::Applied,
+558 -14
View File
@@ -918,16 +918,22 @@ 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 +942,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 +951,23 @@ 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 +975,25 @@ 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 +1009,9 @@ fn collections_hold_tens_of_thousands_of_ids_compactly() {
] {
let ids: Vec<u32> = (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 +1025,10 @@ 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 +1037,12 @@ 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 +1050,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(_))
));
}
@@ -1939,3 +1968,518 @@ fn a_store_that_holds_format_1_snapshots_reads_them_and_compares_them_by_what_th
);
assert_eq!(owner.load_current(id).unwrap(), other);
}
#[test]
fn released_v0_7_x_database_upgrades_transactionally_through_migration_009_and_accepts_reborn() {
let dir = tempfile::tempdir().unwrap();
let file = Store::path_of(dir.path());
let profile = ProfileId::new();
let char_coa = CharacterId::new();
let char_wc = CharacterId::new();
let item_coa = PortableItemId::new();
let now = "2026-10-22T12:00:00Z";
// Build realistic pre-multiruleset v0.7.x database (migrations 0..8)
{
let conn = Connection::open(&file).unwrap();
conn.pragma_update(None, "foreign_keys", true).unwrap();
for m in &MIGRATIONS[..8] {
conn.execute_batch(m).unwrap();
}
conn.pragma_update(None, "application_id", APPLICATION_ID)
.unwrap();
conn.pragma_update(None, "user_version", 8).unwrap();
// 1. Profile
conn.execute(
"INSERT INTO profile (profile_id, created_at, format_version) VALUES (?1, ?2, 1)",
params![profile.to_string(), now],
)
.unwrap();
// 2. Characters (CoA and Wildcard allowed in pre-009 schema)
conn.execute(
"INSERT INTO character (character_id, profile_id, ruleset, name, race, class, gender, level, revision, created_at, updated_at, archived)
VALUES (?1, ?2, 'coa', 'Varian', 'coa:race:1', 'coa:class:1', 0, 80, 1, ?3, ?3, 0)",
params![char_coa.to_string(), profile.to_string(), now],
).unwrap();
conn.execute(
"INSERT INTO character (character_id, profile_id, ruleset, name, race, class, gender, level, revision, created_at, updated_at, archived)
VALUES (?1, ?2, 'wildcard', 'RogueMage', 'coa:race:1', 'coa:class:4', 1, 60, 2, ?3, ?3, 0)",
params![char_wc.to_string(), profile.to_string(), now],
).unwrap();
// Verify pre-009 CHECK constraint rejects 'reborn'
let err = conn.execute(
"INSERT INTO character (character_id, profile_id, ruleset, name, race, class, gender, level, revision, created_at, updated_at, archived)
VALUES (?1, ?2, 'reborn', 'Paladin', 'coa:race:1', 'coa:class:2', 0, 70, 1, ?3, ?3, 0)",
params![CharacterId::new().to_string(), profile.to_string(), now],
);
assert!(err.is_err(), "pre-009 schema must reject reborn");
// 3. Snapshots and revisions
conn.execute(
"INSERT INTO snapshot (character_id, revision, snapshot_format_version, created_at, source_server_id, content_hash, uncompressed_size, payload, note)
VALUES (?1, 1, 2, ?2, 'realm-a', ?3, 4, X'01020304', 'genesis')",
params![char_coa.to_string(), now, [0x42u8; 32]],
).unwrap();
// 4. Mappings and server bindings
conn.execute(
"INSERT INTO character_server_mapping (character_id, server_id, local_guid, last_revision, state, updated_at)
VALUES (?1, 'realm-a', 101, 1, 'active', ?2)",
params![char_coa.to_string(), now],
).unwrap();
conn.execute(
"INSERT INTO item_mapping (character_id, server_id, portable_item_id, local_item_guid, entry, identity, state, created_revision, confirmed_revision, created_at, updated_at)
VALUES (?1, 'realm-a', ?2, 202, 'item_entry', 'ident', 'active', 1, 1, ?3, ?3)",
params![char_coa.to_string(), item_coa.to_string(), now],
).unwrap();
// 5. Baseline session (realm_baseline)
conn.execute(
"INSERT INTO realm_baseline (character_id, server_id, c0_revision, head_revision, state, c0_hash, c0_payload, b0_hash, b0_payload, created_at, updated_at)
VALUES (?1, 'realm-a', 1, 1, 'open', ?2, X'AA', ?2, X'BB', ?3, ?3)",
params![char_coa.to_string(), [0x42u8; 32], now],
).unwrap();
// 6. Pre-009 Collection (single profile_id, kind PK)
conn.execute(
"INSERT INTO collection (profile_id, kind, collection_revision, collection_hash, format_version, item_count, updated_at, payload)
VALUES (?1, 'coa:appearance', 1, ?2, 1, 0, ?3, X'00')",
params![profile.to_string(), [0x42u8; 32], now],
).unwrap();
}
// Upgrade through Store::open_file (applies migration 009)
let store = Store::open_file(&file).unwrap();
assert_eq!(store.schema_version().unwrap(), 9);
// Verify all original rows and fields survived byte-for-byte and constraint-wise
let coa_rec = store.character(char_coa).unwrap();
assert_eq!(coa_rec.ruleset, Ruleset::Coa);
assert_eq!(coa_rec.name, "Varian");
assert_eq!(coa_rec.revision, 1);
assert_eq!(coa_rec.level, 80);
assert_eq!(coa_rec.created_at, now);
let wc_rec = store.character(char_wc).unwrap();
assert_eq!(wc_rec.ruleset, Ruleset::Wildcard);
assert_eq!(wc_rec.name, "RogueMage");
assert_eq!(wc_rec.revision, 2);
// Verify child tables survived without cascading drop
let server_maps = store.server_mappings(char_coa).unwrap();
assert_eq!(server_maps.len(), 1);
assert_eq!(server_maps[0].local_guid, 101);
let item_maps = store.item_mappings(char_coa, "realm-a").unwrap();
assert_eq!(item_maps.len(), 1);
assert_eq!(item_maps[0].portable_item_id, item_coa);
assert_eq!(item_maps[0].local_item_guid, 202);
// Verify collection migrated to composite key (profile_id, ruleset, kind)
let coll_info = store
.collection_info(profile, Ruleset::Coa, "coa:appearance")
.unwrap()
.unwrap();
assert_eq!(coll_info.revision, 1);
// Verify insertion of Reborn character succeeds now on migrated DB
let char_rb = CharacterId::new();
let rb_rec = store.conn.execute(
"INSERT INTO character (character_id, profile_id, ruleset, name, race, class, gender, level, revision, created_at, updated_at, archived)
VALUES (?1, ?2, 'reborn', 'Mograine', 'coa:race:1', 'coa:class:2', 0, 70, 1, ?3, ?3, 0)",
params![char_rb.to_string(), profile.to_string(), now],
);
assert!(
rb_rec.is_ok(),
"migrated database must accept reborn ruleset"
);
let loaded_rb = store.character(char_rb).unwrap();
assert_eq!(loaded_rb.ruleset, Ruleset::Reborn);
assert_eq!(loaded_rb.name, "Mograine");
// Verify invalid ruleset is still rejected by CHECK constraint
let err = store.conn.execute(
"INSERT INTO character (character_id, profile_id, ruleset, name, race, class, gender, level, revision, created_at, updated_at, archived)
VALUES (?1, ?2, 'invalid_ruleset', 'Bad', 'coa:race:1', 'coa:class:1', 0, 1, 1, ?3, ?3, 0)",
params![CharacterId::new().to_string(), profile.to_string(), now],
);
assert!(
err.is_err(),
"migrated database must reject invalid ruleset"
);
}
#[test]
fn mapping_isolation_between_coa_and_wildcard_on_same_installation() {
let mut store = Store::open_in_memory().unwrap();
let profile = store.default_profile().unwrap();
let mut model_coa = fixtures::geared_level_eighty();
model_coa.ruleset = Ruleset::Coa;
let char_coa = store
.create_character(profile, model_coa, "srv-1:coa")
.unwrap();
let mut model_wc = fixtures::geared_level_eighty();
model_wc.ruleset = Ruleset::Wildcard;
let char_wc = store
.create_character(profile, model_wc, "srv-1:wildcard")
.unwrap();
// 1. Both share local_guid = 100 on their respective server_id
store
.bind_server(char_coa, "srv-1:coa", 100, 1, MappingState::Active)
.unwrap();
store
.bind_server(char_wc, "srv-1:wildcard", 100, 1, MappingState::Active)
.unwrap();
// 2. Both share local_item_guid = 500 on their respective server_id
let item_coa = PortableItemId::new();
let item_wc = PortableItemId::new();
store
.reconcile_item_mappings(
char_coa,
"srv-1:coa",
1,
&[obs(item_coa, 500, 10, "entry1")],
)
.unwrap();
store
.reconcile_item_mappings(
char_wc,
"srv-1:wildcard",
1,
&[obs(item_wc, 500, 20, "entry2")],
)
.unwrap();
// Verify lookup isolation
assert_eq!(
store.find_by_local("srv-1:coa", 100).unwrap(),
Some(char_coa)
);
assert_eq!(
store.find_by_local("srv-1:wildcard", 100).unwrap(),
Some(char_wc)
);
let maps_coa = store.item_mappings(char_coa, "srv-1:coa").unwrap();
assert_eq!(maps_coa.len(), 1);
assert_eq!(maps_coa[0].portable_item_id, item_coa);
assert_eq!(maps_coa[0].local_item_guid, 500);
let maps_wc = store.item_mappings(char_wc, "srv-1:wildcard").unwrap();
assert_eq!(maps_wc.len(), 1);
assert_eq!(maps_wc[0].portable_item_id, item_wc);
assert_eq!(maps_wc[0].local_item_guid, 500);
}
#[test]
fn three_space_isolation_fixture_proves_wildcard_activity_leaves_coa_and_reborn_untouched() {
let mut store = Store::open_in_memory().unwrap();
let profile = store.default_profile().unwrap();
// Character A: CoA
let mut model_a = fixtures::geared_level_eighty();
model_a.identity.name = "Hero".into();
model_a.ruleset = Ruleset::Coa;
let char_a = store
.create_character(profile, model_a, "srv-1:coa")
.unwrap();
// Character B: Wildcard
let mut model_b = fixtures::geared_level_eighty();
model_b.identity.name = "Hero".into();
model_b.ruleset = Ruleset::Wildcard;
let char_b = store
.create_character(profile, model_b, "srv-1:wildcard")
.unwrap();
// Character C: Reborn
let mut model_c = fixtures::geared_level_eighty();
model_c.identity.name = "Hero".into();
model_c.ruleset = Ruleset::Reborn;
let char_c = store
.create_character(profile, model_c, "srv-1:reborn")
.unwrap();
// Initial identical mappings (local_guid = 100, item_guid = 200)
store
.bind_server(char_a, "srv-1:coa", 100, 1, MappingState::Active)
.unwrap();
store
.bind_server(char_b, "srv-1:wildcard", 100, 1, MappingState::Active)
.unwrap();
store
.bind_server(char_c, "srv-1:reborn", 100, 1, MappingState::Active)
.unwrap();
let item_a = PortableItemId::new();
let item_b = PortableItemId::new();
let item_c = PortableItemId::new();
store
.reconcile_item_mappings(char_a, "srv-1:coa", 1, &[obs(item_a, 200, 10, "e1")])
.unwrap();
store
.reconcile_item_mappings(char_b, "srv-1:wildcard", 1, &[obs(item_b, 200, 10, "e2")])
.unwrap();
store
.reconcile_item_mappings(char_c, "srv-1:reborn", 1, &[obs(item_c, 200, 10, "e3")])
.unwrap();
// Initial collections
store
.merge_collection(
profile,
Ruleset::Coa,
"coa:appearance",
&IdSet::from_ids([1, 2, 3]).unwrap(),
)
.unwrap();
store
.merge_collection(
profile,
Ruleset::Wildcard,
"wildcard:appearance",
&IdSet::from_ids([1, 2, 4]).unwrap(),
)
.unwrap();
store
.merge_collection(
profile,
Ruleset::Reborn,
"reborn:appearance",
&IdSet::from_ids([1, 2, 5]).unwrap(),
)
.unwrap();
// Record baseline hashes and revisions
let hash_a_before = store.load_snapshot(char_a, 1).unwrap();
let hash_c_before = store.load_snapshot(char_c, 1).unwrap();
// ---- MUTATE WILDCARD B ONLY ----
let mut model_b_mut = store.load_current(char_b).unwrap();
model_b_mut.progression.money += 100_000;
model_b_mut.progression.level = 80;
store
.commit_snapshot(
char_b,
1,
model_b_mut,
"srv-1:wildcard",
Some("wildcard gameplay"),
)
.unwrap();
store
.merge_collection(
profile,
Ruleset::Wildcard,
"wildcard:appearance",
&IdSet::from_ids([1, 2, 4, 999]).unwrap(),
)
.unwrap();
let new_item_b = PortableItemId::new();
store
.reconcile_item_mappings(
char_b,
"srv-1:wildcard",
2,
&[
obs(item_b, 200, 10, "e2"),
obs(new_item_b, 201, 10, "e2_new"),
],
)
.unwrap();
// ---- ASSERT WILDCARD B ADVANCED ----
let rec_b = store.character(char_b).unwrap();
assert_eq!(rec_b.revision, 2);
let (_, coll_b) = store
.collection(profile, Ruleset::Wildcard, "wildcard:appearance")
.unwrap()
.unwrap();
assert_eq!(coll_b.ids(), &[1, 2, 4, 999]);
assert_eq!(
store.item_mappings(char_b, "srv-1:wildcard").unwrap().len(),
2
);
// ---- ASSERT COA A IS 100% UNTOUCHED ----
let rec_a = store.character(char_a).unwrap();
assert_eq!(rec_a.revision, 1);
let hash_a_after = store.load_snapshot(char_a, 1).unwrap();
assert_eq!(hash_a_before, hash_a_after);
let (_, coll_a) = store
.collection(profile, Ruleset::Coa, "coa:appearance")
.unwrap()
.unwrap();
assert_eq!(coll_a.ids(), &[1, 2, 3]);
let items_a = store.item_mappings(char_a, "srv-1:coa").unwrap();
assert_eq!(items_a.len(), 1);
assert_eq!(items_a[0].portable_item_id, item_a);
assert_eq!(items_a[0].local_item_guid, 200);
// ---- ASSERT REBORN C IS 100% UNTOUCHED ----
let rec_c = store.character(char_c).unwrap();
assert_eq!(rec_c.revision, 1);
let hash_c_after = store.load_snapshot(char_c, 1).unwrap();
assert_eq!(hash_c_before, hash_c_after);
let (_, coll_c) = store
.collection(profile, Ruleset::Reborn, "reborn:appearance")
.unwrap()
.unwrap();
assert_eq!(coll_c.ids(), &[1, 2, 5]);
let items_c = store.item_mappings(char_c, "srv-1:reborn").unwrap();
assert_eq!(items_c.len(), 1);
assert_eq!(items_c[0].portable_item_id, item_c);
assert_eq!(items_c[0].local_item_guid, 200);
// ---- MUTATE REBORN C ONLY ----
let mut model_c_mut = store.load_current(char_c).unwrap();
model_c_mut.progression.money += 300_000;
model_c_mut.progression.level = 80;
store
.commit_snapshot(
char_c,
1,
model_c_mut,
"srv-1:reborn",
Some("reborn gameplay progression"),
)
.unwrap();
store
.merge_collection(
profile,
Ruleset::Reborn,
"reborn:appearance",
&IdSet::from_ids([1, 2, 5, 8888]).unwrap(),
)
.unwrap();
let new_item_c = PortableItemId::new();
store
.reconcile_item_mappings(
char_c,
"srv-1:reborn",
2,
&[
obs(item_c, 200, 10, "e3"),
obs(new_item_c, 202, 10, "e3_new"),
],
)
.unwrap();
// ---- ASSERT REBORN C ADVANCED TO REV 2 ----
let rec_c2 = store.character(char_c).unwrap();
assert_eq!(rec_c2.revision, 2);
let (_, coll_c2) = store
.collection(profile, Ruleset::Reborn, "reborn:appearance")
.unwrap()
.unwrap();
assert_eq!(coll_c2.ids(), &[1, 2, 5, 8888]);
assert_eq!(
store.item_mappings(char_c, "srv-1:reborn").unwrap().len(),
2
);
// ---- ASSERT COA A REMAINS 100% UNTOUCHED (STILL REV 1) ----
let rec_a2 = store.character(char_a).unwrap();
assert_eq!(rec_a2.revision, 1);
assert_eq!(store.load_snapshot(char_a, 1).unwrap(), hash_a_before);
let (_, coll_a2) = store
.collection(profile, Ruleset::Coa, "coa:appearance")
.unwrap()
.unwrap();
assert_eq!(coll_a2.ids(), &[1, 2, 3]);
assert_eq!(store.item_mappings(char_a, "srv-1:coa").unwrap().len(), 1);
// ---- ASSERT WILDCARD B REMAINS 100% UNTOUCHED (STILL REV 2) ----
let rec_b2 = store.character(char_b).unwrap();
assert_eq!(rec_b2.revision, 2);
let (_, coll_b2) = store
.collection(profile, Ruleset::Wildcard, "wildcard:appearance")
.unwrap()
.unwrap();
assert_eq!(coll_b2.ids(), &[1, 2, 4, 999]);
assert_eq!(
store.item_mappings(char_b, "srv-1:wildcard").unwrap().len(),
2
);
}
#[test]
fn reborn_store_corruption_fails_closed() {
let mut store = Store::open_in_memory().unwrap();
let profile = store.default_profile().unwrap();
// 1. summary = reborn + snapshot = coa
let mut model_coa = fixtures::geared_level_eighty();
model_coa.ruleset = Ruleset::Coa;
let enc_coa = crate::portable::snapshot::encode(&model_coa).unwrap();
// Insert corrupt summary with reborn ruleset but pointing to coa snapshot
let id_1 = CharacterId::new();
let at = "2026-10-22T12:00:00Z";
store
.conn
.execute(
"INSERT INTO character (character_id, profile_id, ruleset, name, race, class, gender, level, revision, created_at, updated_at, archived)
VALUES (?1, ?2, 'reborn', 'HeroReborn', 'coa:race:1', 'coa:class:1', 0, 80, 1, ?3, ?3, 0)",
rusqlite::params![id_1.to_string(), profile.to_string(), at],
)
.unwrap();
store
.conn
.execute(
"INSERT INTO snapshot (character_id, revision, snapshot_format_version, created_at, source_server_id, content_hash, uncompressed_size, payload, note)
VALUES (?1, 1, 2, ?2, 'srv-1:reborn', ?3, ?4, ?5, 'corrupted snapshot test')",
rusqlite::params![id_1.to_string(), at, enc_coa.content_hash.as_slice(), enc_coa.payload.len() as i64, enc_coa.payload],
)
.unwrap();
// Loading current snapshot must FAIL CLOSED with ruleset mismatch error
let res1 = store.load_current(id_1);
assert!(
res1.is_err(),
"Loading reborn summary with CoA snapshot must fail closed"
);
// 2. summary = reborn + snapshot = wildcard
let mut model_wc = fixtures::geared_level_eighty();
model_wc.ruleset = Ruleset::Wildcard;
let enc_wc = crate::portable::snapshot::encode(&model_wc).unwrap();
let id_2 = CharacterId::new();
store
.conn
.execute(
"INSERT INTO character (character_id, profile_id, ruleset, name, race, class, gender, level, revision, created_at, updated_at, archived)
VALUES (?1, ?2, 'reborn', 'HeroReborn2', 'coa:race:1', 'coa:class:1', 0, 80, 1, ?3, ?3, 0)",
rusqlite::params![id_2.to_string(), profile.to_string(), at],
)
.unwrap();
store
.conn
.execute(
"INSERT INTO snapshot (character_id, revision, snapshot_format_version, created_at, source_server_id, content_hash, uncompressed_size, payload, note)
VALUES (?1, 1, 2, ?2, 'srv-1:reborn', ?3, ?4, ?5, 'corrupted snapshot test 2')",
rusqlite::params![id_2.to_string(), at, enc_wc.content_hash.as_slice(), enc_wc.payload.len() as i64, enc_wc.payload],
)
.unwrap();
let res2 = store.load_current(id_2);
assert!(
res2.is_err(),
"Loading reborn summary with Wildcard snapshot must fail closed"
);
}
+45 -5
View File
@@ -122,23 +122,63 @@ pub fn modules_of(root: &Path) -> Vec<ModuleEntry> {
out
}
/// The realm a local id names: an installed server (`srv-<install id>` or the bare install id) or a prepared descriptor.
/// The realm a local id names: an installed server (`srv-<install id>`, `srv-<install id>:<ruleset>` or the bare install id) or a prepared descriptor.
pub fn find_access(
descriptors: &Path,
installs: &[(String, PathBuf)],
local_id: &str,
) -> Option<RealmAccess> {
let (base_id, explicit_mode) = if let Some((base, rs)) = local_id.split_once(':') {
let m = match rs {
"coa" => crate::realms::Mode::Coa,
"wildcard" => crate::realms::Mode::Wildcard,
"reborn" => crate::realms::Mode::Reborn,
_ => return None,
};
(base, Some(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 {
if let Ok(st) = crate::realms::state(root) {
let supported = match m {
crate::realms::Mode::Coa => {
st.active == crate::realms::Mode::Coa || st.simultaneous
}
crate::realms::Mode::Wildcard => {
st.active == crate::realms::Mode::Wildcard
|| (st.simultaneous && st.wildcard_created)
}
crate::realms::Mode::Reborn => st.active == crate::realms::Mode::Reborn,
};
if !supported {
return None;
}
}
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)
.and_then(|d| RealmAccess::from_descriptor(d).ok())
.find(|d| d.id == local_id || d.id == base_id)
.and_then(|d| {
let mut access = RealmAccess::from_descriptor(d).ok()?;
if let Some(m) = explicit_mode {
access.id = format!("{}:{}", access.id, m.name());
access.name = format!("{} — {}", access.name, m.label());
access.mode = Some(m);
}
Some(access)
})
}
struct Cached {
+295 -58
View File
@@ -23,10 +23,26 @@ pub enum Mode {
impl Mode {
pub fn name(self) -> &'static str {
match self { Self::Coa => "coa", Self::Wildcard => "wildcard", Self::Reborn => "reborn" }
match self {
Self::Coa => "coa",
Self::Wildcard => "wildcard",
Self::Reborn => "reborn",
}
}
pub fn realm_id(self) -> u32 {
match self {
Self::Coa => 1,
Self::Wildcard => 2,
Self::Reborn => 3,
}
}
pub fn label(self) -> &'static str {
match self {
Self::Coa => "Conquest of Azeroth",
Self::Wildcard => "Wildcard",
Self::Reborn => "Warcraft Reborn",
}
}
pub fn realm_id(self) -> u32 { match self { Self::Coa => 1, Self::Wildcard => 2, Self::Reborn => 3 } }
pub fn label(self) -> &'static str { match self { Self::Coa => "Conquest of Azeroth", Self::Wildcard => "Wildcard", Self::Reborn => "Warcraft Reborn" } }
pub fn schema(self, kind: &str) -> Result<&'static str> {
match (self, kind) {
(_, "auth") => Ok("acore_auth"),
@@ -56,10 +72,20 @@ pub struct RealmState {
}
impl RealmState {
pub fn created(&self, mode: Mode) -> bool { match mode { Mode::Coa => true, Mode::Wildcard => self.wildcard_created, Mode::Reborn => self.reborn_created } }
pub fn created(&self, mode: Mode) -> bool {
match mode {
Mode::Coa => true,
Mode::Wildcard => self.wildcard_created,
Mode::Reborn => self.reborn_created,
}
}
pub fn modes(&self) -> Vec<Mode> {
let mut modes = vec![self.active];
modes.extend([Mode::Coa, Mode::Wildcard, Mode::Reborn].into_iter().filter(|m| *m != self.active && self.created(*m)));
modes.extend(
[Mode::Coa, Mode::Wildcard, Mode::Reborn]
.into_iter()
.filter(|m| *m != self.active && self.created(*m)),
);
modes
}
}
@@ -98,9 +124,23 @@ pub fn view(root: &Path) -> Result<View> {
let s = state(root)?;
// Inspect the binary itself; templates or an old log cannot prove installed support.
let binary = fs::read(world_binary(root))?;
let reborn_supported = binary.windows(b"Warcraft Reborn class spells are unavailable".len()).any(|w| w == b"Warcraft Reborn class spells are unavailable");
let supported = binary.windows(b"Wildcard synergy settings".len()).any(|w| w == b"Wildcard synergy settings");
Ok(View { active: s.active, wildcard_created: s.wildcard_created, reborn_created: s.reborn_created, reborn_supported, supported, recovery_pending: root.join(JOURNAL).exists(), simultaneous: s.simultaneous, secondary_world_port: s.secondary_world_port, secondary_running: crate::multiworld::is_running(root) })
let reborn_supported = binary
.windows(b"Warcraft Reborn class spells are unavailable".len())
.any(|w| w == b"Warcraft Reborn class spells are unavailable");
let supported = binary
.windows(b"Wildcard synergy settings".len())
.any(|w| w == b"Wildcard synergy settings");
Ok(View {
active: s.active,
wildcard_created: s.wildcard_created,
reborn_created: s.reborn_created,
reborn_supported,
supported,
recovery_pending: root.join(JOURNAL).exists(),
simultaneous: s.simultaneous,
secondary_world_port: s.secondary_world_port,
secondary_running: crate::multiworld::is_running(root),
})
}
pub fn guard_module(root: &Path, id: &str) -> Result<()> {
@@ -223,24 +263,53 @@ fn wildcard_configs(mut files: Files) -> Result<Files> {
value,
)?;
}
set(&mut files, "Core/configs/modules/playerbots.conf", "AiPlayerbot.Enabled", "0")?;
set(
&mut files,
"Core/configs/modules/playerbots.conf",
"AiPlayerbot.Enabled",
"0",
)?;
Ok(files)
}
fn reborn_configs(mut files: Files) -> Result<Files> {
for (key, value) in [
("CoA.ClassModel", "\"wcr\""), ("CoA.GameModeMask", "0"),
("CoA.MapClass10ToWarrior", "0"), ("CoA.RealmType", "\"live\""),
("CoA.ClassModel", "\"wcr\""),
("CoA.GameModeMask", "0"),
("CoA.MapClass10ToWarrior", "0"),
("CoA.RealmType", "\"live\""),
("CoA.ClientBooleanConfigs", "\"\""),
] { set(&mut files, "Core/configs/modules/coa.conf", key, value)?; }
set(&mut files, "Core/configs/modules/mod-coa-challenges.conf", "CoAChallenges.GameModes.Realm", "\"\"")?;
for path in ["Settings/worldserver.conf.template", "Core/configs/worldserver.conf"] {
if files.contains_key(path) { set(&mut files, path, "RealmID", "3")?; }
] {
set(&mut files, "Core/configs/modules/coa.conf", key, value)?;
}
set(
&mut files,
"Core/configs/modules/mod-coa-challenges.conf",
"CoAChallenges.GameModes.Realm",
"\"\"",
)?;
for path in [
"Settings/worldserver.conf.template",
"Core/configs/worldserver.conf",
] {
if files.contains_key(path) {
set(&mut files, path, "RealmID", "3")?;
}
}
for (key, value) in [("CoaBots.Enable", "0"), ("CoaBots.AutoLoginOnStartup", "0")] {
set(&mut files, "Core/configs/modules/mod_coa_playerbots.conf", key, value)?;
set(
&mut files,
"Core/configs/modules/mod_coa_playerbots.conf",
key,
value,
)?;
}
set(&mut files, "Core/configs/modules/playerbots.conf", "AiPlayerbot.Enabled", "0")?;
set(
&mut files,
"Core/configs/modules/playerbots.conf",
"AiPlayerbot.Enabled",
"0",
)?;
Ok(files)
}
@@ -278,8 +347,15 @@ pub fn recover(root: &Path) -> Result<()> {
fn create_databases(root: &Path, mode: Mode) -> Result<()> {
crate::backup::with_database(root, |_| {
let db = Db::from_repack(root, Account::Admin)?.for_realm(Mode::Coa);
if db.query(&format!("SELECT COUNT(*) FROM acore_auth.realmlist WHERE id={};", mode.realm_id()))? != "0" {
return Err(Error::Invalid(format!("Realm ID {} is already in use. Its settings were left intact.", mode.realm_id())));
if db.query(&format!(
"SELECT COUNT(*) FROM acore_auth.realmlist WHERE id={};",
mode.realm_id()
))? != "0"
{
return Err(Error::Invalid(format!(
"Realm ID {} is already in use. Its settings were left intact.",
mode.realm_id()
)));
}
for kind in ["world", "characters"] {
let source = Mode::Coa.schema(kind)?;
@@ -294,7 +370,10 @@ fn create_databases(root: &Path, mode: Mode) -> Result<()> {
));
}
}
for (kind, tables) in crate::schema_check::WILDCARD_TABLES.iter().filter(|_| mode == Mode::Wildcard) {
for (kind, tables) in crate::schema_check::WILDCARD_TABLES
.iter()
.filter(|_| mode == Mode::Wildcard)
{
let schema = crate::db::schema_of(kind)?;
let present = db.tables(schema)?;
let missing: Vec<_> = tables
@@ -384,21 +463,37 @@ pub fn select(root: &Path, mode: Mode) -> Result<View> {
));
}
if mode == Mode::Reborn && !view(root)?.reborn_supported {
return Err(Error::Invalid("Update the server to a build with Warcraft Reborn support first.".into()));
return Err(Error::Invalid(
"Update the server to a build with Warcraft Reborn support first.".into(),
));
}
if s.simultaneous && mode != s.active {
return Err(Error::Invalid("Disable simultaneous startup before switching realms.".into()));
return Err(Error::Invalid(
"Disable simultaneous startup before switching realms.".into(),
));
}
// Verify launcher support before creating databases or changing the selected realm.
prepare_launcher(root)?;
let before = configs(root)?;
fsx::atomic_write_json(&snapshot(root, s.active), &before)?;
if !s.created(mode) {
let base = if s.active == Mode::Coa { before.clone() } else { fsx::read_json(&snapshot(root, Mode::Coa))? };
let files = match mode { Mode::Wildcard => wildcard_configs(base)?, Mode::Reborn => reborn_configs(base)?, Mode::Coa => unreachable!() };
let base = if s.active == Mode::Coa {
before.clone()
} else {
fsx::read_json(&snapshot(root, Mode::Coa))?
};
let files = match mode {
Mode::Wildcard => wildcard_configs(base)?,
Mode::Reborn => reborn_configs(base)?,
Mode::Coa => unreachable!(),
};
fsx::atomic_write_json(&snapshot(root, mode), &files)?;
create_databases(root, mode)?;
match mode { Mode::Wildcard => s.wildcard_created = true, Mode::Reborn => s.reborn_created = true, Mode::Coa => {} }
match mode {
Mode::Wildcard => s.wildcard_created = true,
Mode::Reborn => s.reborn_created = true,
Mode::Coa => {}
}
fsx::atomic_write_json(&root.join(STATE), &s)?;
}
let target: Files = fsx::read_json(&snapshot(root, mode))?;
@@ -481,9 +576,16 @@ const LAUNCHER_REALM_REPLACEMENTS: &[(&str, &str)] = &[
const LAUNCHER_REALM_INSERT: &str = "# coa-manager-realm-profiles-v1\ndef coa_realm():\n path = ROOT / 'Settings/realm-profile.json'\n return json.loads(path.read_text(encoding='utf-8')).get('active', 'coa') if path.exists() else 'coa'\n\ndef coa_realm_id():\n return 2 if coa_realm() == 'wildcard' else 1\n\ndef coa_realm_name():\n return 'Wildcard' if coa_realm() == 'wildcard' else 'Conquest of Azeroth'\n\n";
fn launcher_insert() -> String {
LAUNCHER_REALM_INSERT.replace("profiles-v1", "profiles-v2")
.replace("return 2 if", "return 3 if coa_realm() == 'reborn' else 2 if")
.replace("return 'Wildcard' if", "return 'Warcraft Reborn' if coa_realm() == 'reborn' else 'Wildcard' if")
LAUNCHER_REALM_INSERT
.replace("profiles-v1", "profiles-v2")
.replace(
"return 2 if",
"return 3 if coa_realm() == 'reborn' else 2 if",
)
.replace(
"return 'Wildcard' if",
"return 'Warcraft Reborn' if coa_realm() == 'reborn' else 'Wildcard' if",
)
}
fn launcher_replacements() -> Vec<(&'static str, String)> {
@@ -493,19 +595,31 @@ fn launcher_replacements() -> Vec<(&'static str, String)> {
}
pub(crate) fn patch_launcher(source: &str) -> Result<String> {
if source.contains("# coa-manager-realm-profiles-v2") { return Ok(source.into()); }
if source.contains("# coa-manager-realm-profiles-v2") {
return Ok(source.into());
}
if source.contains("# coa-manager-realm-profiles-v1") {
let original = unpatch_launcher(source).ok_or_else(|| Error::Invalid("Unrecognised realm launcher patch.".into()))?;
let original = unpatch_launcher(source)
.ok_or_else(|| Error::Invalid("Unrecognised realm launcher patch.".into()))?;
return patch_launcher(&original);
}
let mut out = source.to_string();
for (from, to) in launcher_replacements() {
if !out.contains(from) { return Err(Error::Invalid("This launcher does not support realm profiles. Update the server package first.".into())); }
if !out.contains(from) {
return Err(Error::Invalid(
"This launcher does not support realm profiles. Update the server package first."
.into(),
));
}
out = out.replace(from, &to);
}
// Insert before the entry point so ROOT, json and functions are all defined when called.
let marker = "if __name__ == \"__main__\":";
if !out.contains(marker) { return Err(Error::Invalid("Unrecognised server launcher entry point.".into())); }
if !out.contains(marker) {
return Err(Error::Invalid(
"Unrecognised server launcher entry point.".into(),
));
}
Ok(out.replace(marker, &format!("{}{marker}", launcher_insert())))
}
@@ -514,13 +628,28 @@ pub(crate) fn unpatch_launcher(source: &str) -> Option<String> {
let (insert, replacements) = if source.contains(&launcher_insert()) {
(launcher_insert(), launcher_replacements())
} else if source.contains(LAUNCHER_REALM_INSERT) {
(LAUNCHER_REALM_INSERT.into(), LAUNCHER_REALM_REPLACEMENTS.iter().map(|(a,b)| (*a, b.to_string())).collect())
} else { return None; };
(
LAUNCHER_REALM_INSERT.into(),
LAUNCHER_REALM_REPLACEMENTS
.iter()
.map(|(a, b)| (*a, b.to_string()))
.collect(),
)
} else {
return None;
};
let mut original = source.replacen(&insert, "", 1);
for (from, to) in &replacements { original = original.replace(to, from); }
for (from, to) in &replacements {
original = original.replace(to, from);
}
let mut check = original.clone();
for (from, to) in &replacements { check = check.replace(from, to); }
check = check.replace("if __name__ == \"__main__\":", &format!("{insert}if __name__ == \"__main__\":"));
for (from, to) in &replacements {
check = check.replace(from, to);
}
check = check.replace(
"if __name__ == \"__main__\":",
&format!("{insert}if __name__ == \"__main__\":"),
);
(check == source).then_some(original)
}
@@ -531,18 +660,40 @@ pub fn before_start(root: &Path) -> Result<()> {
return Ok(());
}
prepare_launcher(root)?;
if s.simultaneous && !view(root)?.supported { return Err(Error::Invalid("The installed server build does not support simultaneous Wildcard startup.".into())); }
if s.simultaneous && s.active == Mode::Reborn { return Err(Error::Invalid("Simultaneous startup supports CoA and Wildcard only.".into())); }
if s.simultaneous { fsx::atomic_write_json(&snapshot(root, s.active), &configs(root)?)?; }
if s.active == Mode::Reborn && !view(root)?.reborn_supported { return Err(Error::Invalid("The installed server build does not support Warcraft Reborn.".into())); }
if s.simultaneous && !view(root)?.supported {
return Err(Error::Invalid(
"The installed server build does not support simultaneous Wildcard startup.".into(),
));
}
if s.simultaneous && s.active == Mode::Reborn {
return Err(Error::Invalid(
"Simultaneous startup supports CoA and Wildcard only.".into(),
));
}
if s.simultaneous {
fsx::atomic_write_json(&snapshot(root, s.active), &configs(root)?)?;
}
if s.active == Mode::Reborn && !view(root)?.reborn_supported {
return Err(Error::Invalid(
"The installed server build does not support Warcraft Reborn.".into(),
));
}
if s.active != Mode::Coa {
if s.active == Mode::Wildcard && !view(root)?.supported { return Err(Error::Invalid("The installed server build does not support Wildcard.".into())); }
if s.active == Mode::Wildcard && !view(root)?.supported {
return Err(Error::Invalid(
"The installed server build does not support Wildcard.".into(),
));
}
let path = root.join("Core/configs/modules/mod_coa_playerbots.conf");
let mut conf = ConfFile::parse_bytes(&fs::read(&path)?)?;
conf.set("CoaBots.Enable", "0", &[]);
fsx::atomic_write(&path, conf.to_text().as_bytes())?;
let path = root.join("Core/configs/modules/playerbots.conf");
let bytes = if path.exists() { fs::read(&path)? } else { b"[worldserver]\n".to_vec() };
let bytes = if path.exists() {
fs::read(&path)?
} else {
b"[worldserver]\n".to_vec()
};
let mut conf = ConfFile::parse_bytes(&bytes)?;
conf.set("AiPlayerbot.Enabled", "0", &[]);
fsx::atomic_write(&path, conf.to_text().as_bytes())?;
@@ -552,7 +703,9 @@ pub fn before_start(root: &Path) -> Result<()> {
pub fn setup_realmlist(root: &Path) -> Result<()> {
let s = state(root)?;
if !root.join(STATE).exists() { return Ok(()); }
if !root.join(STATE).exists() {
return Ok(());
}
let db = Db::from_repack(root, Account::Admin)?.for_realm(Mode::Coa);
let port = layout::read_ports(root).world;
for mode in s.modes().into_iter().filter(|m| *m != Mode::Coa) {
@@ -560,8 +713,16 @@ pub fn setup_realmlist(root: &Path) -> Result<()> {
let name = mode.label();
db.query(&format!("INSERT INTO acore_auth.realmlist (id,name,address,localAddress,localSubnetMask,port,icon,flag,timezone,gamebuild) SELECT {id},'{name}',address,localAddress,localSubnetMask,{port},icon,2,timezone,gamebuild FROM acore_auth.realmlist WHERE id=1 ON DUPLICATE KEY UPDATE port={port};"))?;
}
let ids = s.modes().iter().map(|m| m.realm_id().to_string()).collect::<Vec<_>>().join(",");
db.query(&format!("UPDATE acore_auth.realmlist SET flag=2 WHERE id IN ({ids}) AND id<>{};", s.active.realm_id()))?;
let ids = s
.modes()
.iter()
.map(|m| m.realm_id().to_string())
.collect::<Vec<_>>()
.join(",");
db.query(&format!(
"UPDATE acore_auth.realmlist SET flag=2 WHERE id IN ({ids}) AND id<>{};",
s.active.realm_id()
))?;
if s.simultaneous {
let second = s
.secondary_world_port
@@ -576,16 +737,52 @@ pub fn setup_realmlist(root: &Path) -> Result<()> {
Ok(())
}
pub fn world_port_for_mode(root: &Path, mode: Mode) -> Result<u16> {
let ports = crate::layout::read_ports(root);
let s = state(root)?;
if s.simultaneous {
let second = s
.secondary_world_port
.ok_or_else(|| Error::Invalid("Second realm port is missing.".into()))?;
let port = match (s.active, mode) {
(Mode::Coa, Mode::Coa) => ports.world,
(Mode::Coa, Mode::Wildcard) => second,
(Mode::Wildcard, Mode::Wildcard) => ports.world,
(Mode::Wildcard, Mode::Coa) => second,
_ => {
return Err(Error::Invalid(format!(
"Unsupported mode {mode:?} for simultaneous hosting (active: {:?})",
s.active
)))
}
};
Ok(port)
} else if mode == s.active {
Ok(ports.world)
} else {
Err(Error::Invalid(format!(
"Realm mode {mode:?} is not active (active: {:?}) and simultaneous mode is disabled.",
s.active
)))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn legacy_states_and_all_created_realms_are_enumerated_once() {
let legacy: RealmState = serde_json::from_str(r#"{"active":"wildcard","wildcard_created":true}"#).unwrap();
let legacy: RealmState =
serde_json::from_str(r#"{"active":"wildcard","wildcard_created":true}"#).unwrap();
assert!(!legacy.reborn_created);
assert_eq!(legacy.modes(), [Mode::Wildcard, Mode::Coa]);
let all = RealmState { active: Mode::Reborn, wildcard_created: true, reborn_created: true, ..Default::default() };
let all = RealmState {
active: Mode::Reborn,
wildcard_created: true,
reborn_created: true,
..Default::default()
};
assert_eq!(all.modes(), [Mode::Reborn, Mode::Coa, Mode::Wildcard]);
assert_eq!(serde_json::to_string(&Mode::Reborn).unwrap(), "\"reborn\"");
assert_eq!(Mode::Reborn.realm_id(), 3);
@@ -596,19 +793,46 @@ mod tests {
fn reborn_has_its_own_settings_and_restores_the_coa_profile() {
let t = tempfile::tempdir().unwrap();
let mut coa = Files::new();
coa.insert("Core/configs/modules/coa.conf".into(), b"[worldserver]\nCoA.ClassModel = coa\nCoA.GameModeMask = 0\n".to_vec());
coa.insert("Settings/worldserver.conf.template".into(), b"[worldserver]\nRealmID = 1\n".to_vec());
coa.insert("Core/configs/modules/playerbots.conf".into(), b"[worldserver]\nAiPlayerbot.Enabled = 1\n".to_vec());
coa.insert(
"Core/configs/modules/coa.conf".into(),
b"[worldserver]\nCoA.ClassModel = coa\nCoA.GameModeMask = 0\n".to_vec(),
);
coa.insert(
"Settings/worldserver.conf.template".into(),
b"[worldserver]\nRealmID = 1\n".to_vec(),
);
coa.insert(
"Core/configs/modules/playerbots.conf".into(),
b"[worldserver]\nAiPlayerbot.Enabled = 1\n".to_vec(),
);
let reborn = reborn_configs(coa.clone()).unwrap();
let conf = ConfFile::parse_bytes(&reborn["Core/configs/modules/coa.conf"]).unwrap();
assert_eq!(conf.get("CoA.ClassModel"), Some("\"wcr\""));
assert_eq!(conf.get("CoA.GameModeMask"), Some("0"));
assert_eq!(ConfFile::parse_bytes(&reborn["Settings/worldserver.conf.template"]).unwrap().get("RealmID"), Some("3"));
assert_eq!(ConfFile::parse_bytes(&reborn["Core/configs/modules/playerbots.conf"]).unwrap().get("AiPlayerbot.Enabled"), Some("0"));
assert_eq!(
ConfFile::parse_bytes(&reborn["Settings/worldserver.conf.template"])
.unwrap()
.get("RealmID"),
Some("3")
);
assert_eq!(
ConfFile::parse_bytes(&reborn["Core/configs/modules/playerbots.conf"])
.unwrap()
.get("AiPlayerbot.Enabled"),
Some("0")
);
write_configs(t.path(), &reborn).unwrap();
write_configs(t.path(), &coa).unwrap();
assert_eq!(configs(t.path()).unwrap(), coa);
fsx::atomic_write_json(&t.path().join(STATE), &RealmState { active: Mode::Reborn, reborn_created: true, ..Default::default() }).unwrap();
fsx::atomic_write_json(
&t.path().join(STATE),
&RealmState {
active: Mode::Reborn,
reborn_created: true,
..Default::default()
},
)
.unwrap();
assert!(guard_module(t.path(), "companions").is_err());
assert!(guard_module(t.path(), "playerbots").is_err());
assert!(guard_module(t.path(), "content-scaling").is_ok());
@@ -617,9 +841,17 @@ mod tests {
#[test]
fn reborn_support_requires_the_new_code_in_the_installed_binary() {
let t = tempfile::tempdir().unwrap();
fsx::atomic_write(&t.path().join("Core/worldserver.exe"), b"Wildcard synergy settings").unwrap();
fsx::atomic_write(
&t.path().join("Core/worldserver.exe"),
b"Wildcard synergy settings",
)
.unwrap();
assert!(!view(t.path()).unwrap().reborn_supported);
fsx::atomic_write(&t.path().join("Core/worldserver.exe"), b"Warcraft Reborn class spells are unavailable").unwrap();
fsx::atomic_write(
&t.path().join("Core/worldserver.exe"),
b"Warcraft Reborn class spells are unavailable",
)
.unwrap();
let v = view(t.path()).unwrap();
assert!(v.reborn_supported);
assert!(!v.supported);
@@ -629,8 +861,13 @@ mod tests {
fn old_launcher_upgrades_and_both_patch_versions_are_reversible() {
let original = "(\"WorldDatabaseInfo\", \"acore_world\")\n(\"CharacterDatabaseInfo\", \"acore_characters\")\nSET name='AzerothCore',address=\nWHERE id=1;\nmysql(\"UPDATE acore_auth.realmlist SET flag=0\nif __name__ == \"__main__\":\n";
let mut old = original.to_string();
for (from, to) in LAUNCHER_REALM_REPLACEMENTS { old = old.replace(from, to); }
old = old.replace("if __name__ == \"__main__\":", &format!("{LAUNCHER_REALM_INSERT}if __name__ == \"__main__\":"));
for (from, to) in LAUNCHER_REALM_REPLACEMENTS {
old = old.replace(from, to);
}
old = old.replace(
"if __name__ == \"__main__\":",
&format!("{LAUNCHER_REALM_INSERT}if __name__ == \"__main__\":"),
);
assert_eq!(unpatch_launcher(&old).as_deref(), Some(original));
let new = patch_launcher(&old).unwrap();
assert!(new.contains("acore_world_reborn"));
+67 -14
View File
@@ -4,23 +4,57 @@ use std::path::Path;
/// SQUID has its own import ledger, outside the signed package migration ledger.
/// Keep this read-only: a pending base import can contain player data and must not
/// be replayed or cleared merely because the normal schema contract passes.
pub(crate) fn database_problems(root: &Path, mode: crate::realms::Mode, query: &impl Fn(&str) -> crate::Result<String>) -> crate::Result<Vec<crate::schema_check::Problem>> {
pub(crate) fn database_problems(
root: &Path,
mode: crate::realms::Mode,
query: &impl Fn(&str) -> crate::Result<String>,
) -> crate::Result<Vec<crate::schema_check::Problem>> {
let active = root.join("Core/configs/modules/playerbots.conf");
let config = if active.is_file() { active } else { root.join("Core/configs/modules/playerbots.conf.dist") };
let config = if active.is_file() {
active
} else {
root.join("Core/configs/modules/playerbots.conf.dist")
};
let enabled = if config.is_file() {
let conf = crate::config::parser::ConfFile::parse_bytes(&std::fs::read(config)?)?;
!matches!(conf.get("AiPlayerbot.Enabled").unwrap_or("1").trim().trim_matches('"').to_ascii_lowercase().as_str(), "0" | "false" | "no" | "off")
} else { false };
!matches!(
conf.get("AiPlayerbot.Enabled")
.unwrap_or("1")
.trim()
.trim_matches('"')
.to_ascii_lowercase()
.as_str(),
"0" | "false" | "no" | "off"
)
} else {
false
};
let mut problems = Vec::new();
for schema in [mode.schema("characters")?, mode.schema("world")?, "acore_playerbots"] {
let tables: std::collections::BTreeSet<_> = query(&format!("SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA='{schema}';"))?.lines().map(str::to_owned).collect();
for schema in [
mode.schema("characters")?,
mode.schema("world")?,
"acore_playerbots",
] {
let tables: std::collections::BTreeSet<_> = query(&format!(
"SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA='{schema}';"
))?
.lines()
.map(str::to_owned)
.collect();
if tables.contains("coa_squid_pending") {
for pending in query(&format!("SELECT path FROM `{schema}`.coa_squid_pending;"))?.lines().filter(|path| !path.is_empty()) {
for pending in query(&format!("SELECT path FROM `{schema}`.coa_squid_pending;"))?
.lines()
.filter(|path| !path.is_empty())
{
problems.push(crate::schema_check::Problem { database: schema.into(), table: "coa_squid_pending".into(), column: String::new(), detail: format!("SQUID base import was interrupted: {pending}. File repair and package SQL updates cannot complete this import. Restore a verified database backup from before the import; do not delete the pending record or replay base SQL.") });
}
}
if enabled && schema == mode.schema("characters")? {
for table in ["playerbots_names", "playerbots_guild_names", "playerbots_arena_team_names"] {
for table in [
"playerbots_names",
"playerbots_guild_names",
"playerbots_arena_team_names",
] {
if !tables.contains(table) {
problems.push(crate::schema_check::Problem { database: schema.into(), table: table.into(), column: String::new(), detail: "Required SQUID character table is missing. A normal server start provisions it when no interrupted import is present; an interrupted import requires database recovery first.".into() });
}
@@ -237,9 +271,13 @@ mod tests {
for mode in [crate::realms::Mode::Coa, crate::realms::Mode::Wildcard] {
let problems = database_problems(root.path(), mode, &|sql| {
assert!(sql.starts_with("SELECT "));
if sql.contains("information_schema.TABLES") { Ok("coa_squid_pending".into()) }
else { Ok("playerbots/base/ai_playerbot_texts.sql".into()) }
}).unwrap();
if sql.contains("information_schema.TABLES") {
Ok("coa_squid_pending".into())
} else {
Ok("playerbots/base/ai_playerbot_texts.sql".into())
}
})
.unwrap();
assert_eq!(problems.len(), 3);
assert_eq!(problems[0].database, mode.schema("characters").unwrap());
assert!(problems.iter().all(|p| p.detail.contains("interrupted")));
@@ -252,11 +290,26 @@ mod tests {
let config = root.path().join("Core/configs/modules/playerbots.conf");
crate::fsx::atomic_write(&config, b"AiPlayerbot.Enabled = 1\n").unwrap();
let query = |_: &str| Ok(String::new());
assert_eq!(database_problems(root.path(), crate::realms::Mode::Wildcard, &query).unwrap().len(), 3);
assert_eq!(
database_problems(root.path(), crate::realms::Mode::Wildcard, &query)
.unwrap()
.len(),
3
);
crate::fsx::atomic_write(&config, b"AiPlayerbot.Enabled = 0\n").unwrap();
assert!(database_problems(root.path(), crate::realms::Mode::Wildcard, &query).unwrap().is_empty());
assert!(
database_problems(root.path(), crate::realms::Mode::Wildcard, &query)
.unwrap()
.is_empty()
);
crate::fsx::atomic_write(&config, b"AiPlayerbot.Enabled = 1\n").unwrap();
assert!(database_problems(root.path(), crate::realms::Mode::Coa, &|_| Ok("playerbots_names\nplayerbots_guild_names\nplayerbots_arena_team_names".into())).unwrap().is_empty());
assert!(
database_problems(root.path(), crate::realms::Mode::Coa, &|_| Ok(
"playerbots_names\nplayerbots_guild_names\nplayerbots_arena_team_names".into()
))
.unwrap()
.is_empty()
);
}
#[test]
fn a_setting_with_choices_only_accepts_one_of_them() {
+10 -2
View File
@@ -1961,8 +1961,16 @@ fn database_identities(
let mut identities = BTreeMap::new();
for (schema, table, columns) in [
("acore_characters", "characters", "guid,account,HEX(name)"),
("acore_characters_wildcard", "characters", "guid,account,HEX(name)"),
("acore_characters_reborn", "characters", "guid,account,HEX(name)"),
(
"acore_characters_wildcard",
"characters",
"guid,account,HEX(name)",
),
(
"acore_characters_reborn",
"characters",
"guid,account,HEX(name)",
),
("acore_auth", "account", "id,HEX(username)"),
] {
if !db.schema_exists(schema)? || !db.tables(schema)?.iter().any(|name| name == table) {
+141 -59
View File
@@ -1,41 +1,71 @@
use std::{collections::BTreeMap, fs, path::Path};
use serde::{Deserialize, Serialize};
use crate::{config::parser::ConfFile, fsx, Error, Result};
use serde::{Deserialize, Serialize};
use std::{collections::BTreeMap, fs, path::Path};
const FILES: &[&str] = &[
"Settings/repack.json", "Settings/realm-profile.json",
"Settings/worldserver.conf.template", "Settings/authserver.conf.template",
"Core/configs/worldserver.conf", "Core/configs/authserver.conf",
"Settings/realm-profiles/coa.json", "Settings/realm-profiles/wildcard.json",
".realms/secondary/Settings/repack.json", ".realms/secondary/Settings/realm-profile.json",
".realms/secondary/Settings/worldserver.conf.template", ".realms/secondary/Settings/authserver.conf.template",
".realms/secondary/Core/configs/worldserver.conf", ".realms/secondary/Core/configs/authserver.conf",
"Settings/repack.json",
"Settings/realm-profile.json",
"Settings/worldserver.conf.template",
"Settings/authserver.conf.template",
"Core/configs/worldserver.conf",
"Core/configs/authserver.conf",
"Settings/realm-profiles/coa.json",
"Settings/realm-profiles/wildcard.json",
".realms/secondary/Settings/repack.json",
".realms/secondary/Settings/realm-profile.json",
".realms/secondary/Settings/worldserver.conf.template",
".realms/secondary/Settings/authserver.conf.template",
".realms/secondary/Core/configs/worldserver.conf",
".realms/secondary/Core/configs/authserver.conf",
"Settings/realm-profiles/reborn.json",
];
#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct Saved { bytes: Option<Vec<u8>>, sha256: Option<String> }
struct Saved {
bytes: Option<Vec<u8>>,
sha256: Option<String>,
}
pub(crate) fn pending(meta: &Path) -> bool { meta.join("validation-configs.json").exists() }
pub(crate) fn pending(meta: &Path) -> bool {
meta.join("validation-configs.json").exists()
}
pub(crate) fn begin(root: &Path, meta: &Path) -> Result<()> {
if pending(meta) { return Err(Error::Invalid("Interrupted isolated validation must be recovered first.".into())); }
if pending(meta) {
return Err(Error::Invalid(
"Interrupted isolated validation must be recovered first.".into(),
));
}
let mut saved = BTreeMap::new();
for rel in FILES {
let path = fsx::ensure_within(root, &fsx::safe_join(root, rel)?)?;
let bytes = if path.exists() { Some(fs::read(path)?) } else { None };
let bytes = if path.exists() {
Some(fs::read(path)?)
} else {
None
};
let sha256 = bytes.as_ref().map(|b| fsx::sha256_bytes(b));
saved.insert(*rel, Saved { bytes, sha256 });
}
let mut settings: serde_json::Value = fsx::read_json(&root.join("Settings/repack.json"))?;
let mut realm: Option<serde_json::Value> = if root.join("Settings/realm-profile.json").exists() {
let mut realm: Option<serde_json::Value> = if root.join("Settings/realm-profile.json").exists()
{
Some(fsx::read_json(&root.join("Settings/realm-profile.json"))?)
} else { None };
let mut excluded: std::collections::BTreeSet<u64> = ["mysqlPort", "authPort", "worldPort", "raPort"].iter()
.filter_map(|key| settings[*key].as_u64()).collect();
} else {
None
};
let mut excluded: std::collections::BTreeSet<u64> =
["mysqlPort", "authPort", "worldPort", "raPort"]
.iter()
.filter_map(|key| settings[*key].as_u64())
.collect();
if let Some(state) = &realm {
excluded.extend(["secondary_world_port", "secondary_ra_port"].iter().filter_map(|key| state[*key].as_u64()));
excluded.extend(
["secondary_world_port", "secondary_ra_port"]
.iter()
.filter_map(|key| state[*key].as_u64()),
);
}
let mut sockets = Vec::new();
let mut reserve = || -> Result<u16> {
@@ -48,29 +78,84 @@ pub(crate) fn begin(root: &Path, meta: &Path) -> Result<()> {
}
}
};
for key in ["authPort", "worldPort", "raPort"] { settings[key] = reserve()?.into(); }
for key in ["authPort", "worldPort", "raPort"] {
settings[key] = reserve()?.into();
}
if let Some(state) = &mut realm {
for key in ["secondary_world_port", "secondary_ra_port"] {
state[key] = reserve()?.into();
}
}
let mut configs = Vec::new();
for rel in ["Settings/worldserver.conf.template", "Settings/authserver.conf.template", "Core/configs/worldserver.conf", "Core/configs/authserver.conf"] {
for rel in [
"Settings/worldserver.conf.template",
"Settings/authserver.conf.template",
"Core/configs/worldserver.conf",
"Core/configs/authserver.conf",
] {
let path = root.join(rel);
if !path.exists() && rel.ends_with(".template") {
return Err(Error::Invalid(format!("Cannot isolate validation without {rel}.")));
return Err(Error::Invalid(format!(
"Cannot isolate validation without {rel}."
)));
}
if path.exists() {
let mut conf = ConfFile::parse_bytes(&fs::read(&path)?)?;
conf.set("BindIP", "\"127.0.0.1\"", &[]);
if rel.contains("worldserver") { conf.set("Ra.IP", "\"127.0.0.1\"", &[]); }
if rel.contains("worldserver") {
conf.set("Ra.IP", "\"127.0.0.1\"", &[]);
}
configs.push((path, conf.to_text()));
}
}
fsx::atomic_write_json(&meta.join("validation-configs.json"), &saved)?;
fsx::atomic_write_json(&root.join("Settings/repack.json"), &settings)?;
if let Some(state) = realm { fsx::atomic_write_json(&root.join("Settings/realm-profile.json"), &state)?; }
for (path, text) in configs { fsx::atomic_write(&path, text.as_bytes())?; }
if let Some(state) = realm {
fsx::atomic_write_json(&root.join("Settings/realm-profile.json"), &state)?;
}
for (path, text) in configs {
fsx::atomic_write(&path, text.as_bytes())?;
}
Ok(())
}
pub(crate) fn restore(root: &Path, meta: &Path) -> Result<()> {
if !pending(meta) {
return Ok(());
}
let journal = meta.join("validation-configs.json");
let saved: BTreeMap<String, Saved> = fsx::read_json(&journal)?;
// Previous managers could journal only the first two profiles. Recover those
// journals too, while continuing to reject missing or unknown legacy entries.
let legacy = saved.len() == FILES.len() - 1
&& !saved.contains_key("Settings/realm-profiles/reborn.json");
let required = if legacy {
&FILES[..FILES.len() - 1]
} else {
FILES
};
if saved.len() != required.len() || required.iter().any(|rel| !saved.contains_key(*rel)) {
return Err(Error::Invalid(
"Isolated validation configuration journal is incomplete.".into(),
));
}
for (rel, file) in &saved {
fsx::ensure_within(root, &fsx::safe_join(root, rel)?)?;
if file.bytes.as_ref().map(|b| fsx::sha256_bytes(b)) != file.sha256 {
return Err(Error::Invalid(format!(
"Isolated validation recovery copy {rel} is damaged."
)));
}
}
for (rel, file) in saved {
let path = fsx::ensure_within(root, &fsx::safe_join(root, &rel)?)?;
match file.bytes {
Some(bytes) => fsx::atomic_write(&path, &bytes)?,
None if path.exists() => fs::remove_file(path)?,
None => {}
}
}
fs::remove_file(journal)?;
Ok(())
}
@@ -84,10 +169,18 @@ mod tests {
let meta = dir.path().join("metadata");
fs::create_dir_all(root.join("Settings")).unwrap();
fs::create_dir_all(&meta).unwrap();
fsx::atomic_write_json(&root.join(FILES[0]), &serde_json::json!({"mysqlPort":3306,"authPort":3724,"worldPort":8085,"raPort":3443})).unwrap();
fsx::atomic_write_json(
&root.join(FILES[0]),
&serde_json::json!({"mysqlPort":3306,"authPort":3724,"worldPort":8085,"raPort":3443}),
)
.unwrap();
fsx::atomic_write_json(&root.join(FILES[1]), &serde_json::json!({"simultaneous":true,"secondary_world_port":8086,"secondary_ra_port":3444})).unwrap();
for rel in [FILES[2], FILES[3]] {
fsx::atomic_write(&root.join(rel), b"BindIP = \"0.0.0.0\"\r\nRa.IP = \"0.0.0.0\"\r\n").unwrap();
fsx::atomic_write(
&root.join(rel),
b"BindIP = \"0.0.0.0\"\r\nRa.IP = \"0.0.0.0\"\r\n",
)
.unwrap();
}
(dir, root, meta)
}
@@ -95,7 +188,11 @@ mod tests {
#[test]
fn interrupted_validation_restores_original_bytes_and_absent_files() {
let (_dir, root, meta) = fixture();
fsx::atomic_write(&root.join("Settings/realm-profiles/reborn.json"), b"saved reborn profile").unwrap();
fsx::atomic_write(
&root.join("Settings/realm-profiles/reborn.json"),
b"saved reborn profile",
)
.unwrap();
let original: Vec<_> = FILES.iter().map(|p| fs::read(root.join(p)).ok()).collect();
begin(&root, &meta).unwrap();
assert!(crate::update::ensure_recovered(&meta).is_err());
@@ -103,14 +200,28 @@ mod tests {
let settings: serde_json::Value = fsx::read_json(&root.join(FILES[0])).unwrap();
assert_eq!(settings["mysqlPort"], 3306);
let realm: serde_json::Value = fsx::read_json(&root.join(FILES[1])).unwrap();
let ports: std::collections::BTreeSet<_> = [settings["authPort"].as_u64(), settings["worldPort"].as_u64(), settings["raPort"].as_u64(), realm["secondary_world_port"].as_u64(), realm["secondary_ra_port"].as_u64()].into_iter().collect();
let ports: std::collections::BTreeSet<_> = [
settings["authPort"].as_u64(),
settings["worldPort"].as_u64(),
settings["raPort"].as_u64(),
realm["secondary_world_port"].as_u64(),
realm["secondary_ra_port"].as_u64(),
]
.into_iter()
.collect();
assert_eq!(ports.len(), 5);
let config = ConfFile::parse_bytes(&fs::read(root.join(FILES[2])).unwrap()).unwrap();
assert_eq!(config.get("BindIP"), Some("\"127.0.0.1\""));
fsx::atomic_write(&root.join(FILES[4]), b"rendered temporary configuration").unwrap();
fsx::atomic_write(&root.join("Settings/realm-profiles/reborn.json"), b"temporary reborn profile").unwrap();
fsx::atomic_write(
&root.join("Settings/realm-profiles/reborn.json"),
b"temporary reborn profile",
)
.unwrap();
restore(&root, &meta).unwrap();
for (rel, bytes) in FILES.iter().zip(original) { assert_eq!(fs::read(root.join(rel)).ok(), bytes); }
for (rel, bytes) in FILES.iter().zip(original) {
assert_eq!(fs::read(root.join(rel)).ok(), bytes);
}
assert!(!pending(&meta));
restore(&root, &meta).unwrap();
}
@@ -139,32 +250,3 @@ mod tests {
assert_eq!(fs::read(root.join(FILES[0])).unwrap(), before);
}
}
pub(crate) fn restore(root: &Path, meta: &Path) -> Result<()> {
if !pending(meta) { return Ok(()); }
let journal = meta.join("validation-configs.json");
let saved: BTreeMap<String, Saved> = fsx::read_json(&journal)?;
// Previous managers could journal only the first two profiles. Recover those
// journals too, while continuing to reject missing or unknown legacy entries.
let legacy = saved.len() == FILES.len() - 1 && !saved.contains_key("Settings/realm-profiles/reborn.json");
let required = if legacy { &FILES[..FILES.len() - 1] } else { FILES };
if saved.len() != required.len() || required.iter().any(|rel| !saved.contains_key(*rel)) {
return Err(Error::Invalid("Isolated validation configuration journal is incomplete.".into()));
}
for (rel, file) in &saved {
fsx::ensure_within(root, &fsx::safe_join(root, rel)?)?;
if file.bytes.as_ref().map(|b| fsx::sha256_bytes(b)) != file.sha256 {
return Err(Error::Invalid(format!("Isolated validation recovery copy {rel} is damaged.")));
}
}
for (rel, file) in saved {
let path = fsx::ensure_within(root, &fsx::safe_join(root, &rel)?)?;
match file.bytes {
Some(bytes) => fsx::atomic_write(&path, &bytes)?,
None if path.exists() => fs::remove_file(path)?,
None => {},
}
}
fs::remove_file(journal)?;
Ok(())
}
+75 -17
View File
@@ -1,4 +1,9 @@
use crate::{manifest::Manifest, pkgsource::{self, Source}, registry::InstallMeta, update, Result};
use crate::{
manifest::Manifest,
pkgsource::{self, Source},
registry::InstallMeta,
update, Result,
};
#[derive(Debug)]
pub struct Selection {
@@ -8,13 +13,22 @@ pub struct Selection {
}
pub fn select(meta: &InstallMeta, source: Source, key: &str) -> Result<Selection> {
select_with(meta, source, &mut |source| pkgsource::fetch_manifest(source, key))
select_with(meta, source, &mut |source| {
pkgsource::fetch_manifest(source, key)
})
}
fn select_with(meta: &InstallMeta, source: Source, fetch: &mut impl FnMut(&Source) -> Result<(Manifest, Vec<u8>)>) -> Result<Selection> {
fn select_with(
meta: &InstallMeta,
source: Source,
fetch: &mut impl FnMut(&Source) -> Result<(Manifest, Vec<u8>)>,
) -> Result<Selection> {
let (manifest, _) = fetch(&source)?;
update::validate_candidate(meta, &manifest)?;
Ok(Selection { source, latest_version: None })
Ok(Selection {
source,
latest_version: None,
})
}
#[cfg(test)]
@@ -42,23 +56,51 @@ mod tests {
let folder = tempfile::tempdir().unwrap();
let signing = SigningKey::from_bytes(&[37; 32]);
let bytes = serde_json::to_vec(value).unwrap();
fs::write(folder.path().join("manifest.json.sig"), STANDARD.encode(signing.sign(&bytes).to_bytes())).unwrap();
fs::write(folder.path().join("manifest.json"), if tamper { b"tampered".as_slice() } else { &bytes }).unwrap();
fs::write(
folder.path().join("manifest.json.sig"),
STANDARD.encode(signing.sign(&bytes).to_bytes()),
)
.unwrap();
fs::write(
folder.path().join("manifest.json"),
if tamper {
b"tampered".as_slice()
} else {
&bytes
},
)
.unwrap();
(folder, STANDARD.encode(signing.verifying_key().to_bytes()))
}
#[test]
fn every_known_older_version_selects_the_latest_signed_package_once() {
for installed in ["0.2.0", "0.261004.20", "0.261005.0", "0.261007.24", "0.261011.800006", "0.261013.54", "0.261015.58"] {
for installed in [
"0.2.0",
"0.261004.20",
"0.261005.0",
"0.261007.24",
"0.261011.800006",
"0.261013.54",
"0.261015.58",
] {
let (folder, key) = fixture(&package(), false);
for kind in [crate::registry::InstallKind::New, crate::registry::InstallKind::Imported] {
for kind in [
crate::registry::InstallKind::New,
crate::registry::InstallKind::Imported,
] {
let mut installation = meta(installed);
installation.kind = kind;
let mut calls = 0;
let selected = select_with(&installation, Source::Dir(folder.path().into()), &mut |source| {
calls += 1;
pkgsource::fetch_manifest(source, &key)
}).unwrap();
let selected = select_with(
&installation,
Source::Dir(folder.path().into()),
&mut |source| {
calls += 1;
pkgsource::fetch_manifest(source, &key)
},
)
.unwrap();
assert!(matches!(selected.source, Source::Dir(path) if path == folder.path()));
assert!(selected.latest_version.is_none());
assert_eq!(calls, 1, "no intermediate package fetches for {installed}");
@@ -77,17 +119,33 @@ mod tests {
#[test]
fn signed_target_is_required_even_for_unlisted_old_versions() {
let (folder, key) = fixture(&package(), true);
assert!(select(&meta("0.261004.20"), Source::Dir(folder.path().into()), &key).is_err());
assert!(select(
&meta("0.261004.20"),
Source::Dir(folder.path().into()),
&key
)
.is_err());
}
#[test]
fn platform_and_manager_requirements_are_still_enforced() {
for (field, value) in [("minManagerVersion", "99.0.0"), ("platform", "other-platform")] {
for (field, value) in [
("minManagerVersion", "99.0.0"),
("platform", "other-platform"),
] {
let mut target = package();
if field == "platform" { target["compatibility"][field] = value.into(); }
else { target[field] = value.into(); }
if field == "platform" {
target["compatibility"][field] = value.into();
} else {
target[field] = value.into();
}
let (folder, key) = fixture(&target, false);
assert!(select(&meta("0.261004.20"), Source::Dir(folder.path().into()), &key).is_err());
assert!(select(
&meta("0.261004.20"),
Source::Dir(folder.path().into()),
&key
)
.is_err());
}
}
}
+2 -1
View File
@@ -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)?),
+11 -1
View File
@@ -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",
}
}
}
+71 -24
View File
@@ -56,58 +56,104 @@ fn run() -> Result<(), String> {
.unwrap_or(DEFAULT_PART_SIZE);
match cmd.as_str() {
"plan-update" => {
let mut meta = coa_core::registry::InstallMeta::new(coa_core::registry::InstallKind::New, std::path::Path::new("unused"));
let mut meta = coa_core::registry::InstallMeta::new(
coa_core::registry::InstallKind::New,
std::path::Path::new("unused"),
);
meta.core.version = Some(need(&a, "from")?.clone());
let selection = coa_core::update_route::select(&meta, coa_core::pkgsource::Source::Url(need(&a, "source")?.clone()), coa_core::signing::EMBEDDED_PUBLIC_KEY).map_err(e)?;
let (manifest, _) = coa_core::pkgsource::fetch_manifest(&selection.source, coa_core::signing::EMBEDDED_PUBLIC_KEY).map_err(e)?;
println!("{}", serde_json::json!({"from":meta.core.version,"next":manifest.version,"latest":selection.latest_version}));
let selection = coa_core::update_route::select(
&meta,
coa_core::pkgsource::Source::Url(need(&a, "source")?.clone()),
coa_core::signing::EMBEDDED_PUBLIC_KEY,
)
.map_err(e)?;
let (manifest, _) = coa_core::pkgsource::fetch_manifest(
&selection.source,
coa_core::signing::EMBEDDED_PUBLIC_KEY,
)
.map_err(e)?;
println!(
"{}",
serde_json::json!({"from":meta.core.version,"next":manifest.version,"latest":selection.latest_version})
);
}
"verify-install" => {
coa_core::release_schema::verify_install_package(
&PathBuf::from(need(&a, "dir")?), coa_core::signing::EMBEDDED_PUBLIC_KEY,
).map_err(e)?;
&PathBuf::from(need(&a, "dir")?),
coa_core::signing::EMBEDDED_PUBLIC_KEY,
)
.map_err(e)?;
}
"compose-install" => {
coa_core::release_schema::compose_install(
&PathBuf::from(need(&a, "base")?), &PathBuf::from(need(&a, "candidate")?),
&PathBuf::from(need(&a, "fixture")?), coa_core::signing::EMBEDDED_PUBLIC_KEY,
).map_err(e)?;
&PathBuf::from(need(&a, "base")?),
&PathBuf::from(need(&a, "candidate")?),
&PathBuf::from(need(&a, "fixture")?),
coa_core::signing::EMBEDDED_PUBLIC_KEY,
)
.map_err(e)?;
}
"qualify-install" => {
let report = coa_core::release_schema::qualify_install(
&PathBuf::from(need(&a, "package")?), &PathBuf::from(need(&a, "fixture")?),
&PathBuf::from(need(&a, "package")?),
&PathBuf::from(need(&a, "fixture")?),
coa_core::signing::EMBEDDED_PUBLIC_KEY,
).map_err(e)?;
coa_core::fsx::atomic_write_json(&PathBuf::from(need(&a, "report")?), &report).map_err(e)?;
)
.map_err(e)?;
coa_core::fsx::atomic_write_json(&PathBuf::from(need(&a, "report")?), &report)
.map_err(e)?;
}
"qualify-upgrade" => {
let report = coa_core::release_schema::qualify_upgrade(
&PathBuf::from(need(&a, "base")?), &PathBuf::from(need(&a, "source")?),
&PathBuf::from(need(&a, "candidate")?), &PathBuf::from(need(&a, "fixture")?),
&PathBuf::from(need(&a, "base")?),
&PathBuf::from(need(&a, "source")?),
&PathBuf::from(need(&a, "candidate")?),
&PathBuf::from(need(&a, "fixture")?),
coa_core::signing::EMBEDDED_PUBLIC_KEY,
).map_err(e)?;
coa_core::fsx::atomic_write_json(&PathBuf::from(need(&a, "report")?), &report).map_err(e)?;
)
.map_err(e)?;
coa_core::fsx::atomic_write_json(&PathBuf::from(need(&a, "report")?), &report)
.map_err(e)?;
println!("Manager upgrade transaction passed isolated qualification");
}
"qualify-startup" => {
coa_core::release_schema::validate_startup(
&PathBuf::from(need(&a, "fixture")?), &PathBuf::from(need(&a, "tree")?),
&PathBuf::from(need(&a, "base")?), coa_core::signing::EMBEDDED_PUBLIC_KEY,
).map_err(e)?;
&PathBuf::from(need(&a, "fixture")?),
&PathBuf::from(need(&a, "tree")?),
&PathBuf::from(need(&a, "base")?),
coa_core::signing::EMBEDDED_PUBLIC_KEY,
)
.map_err(e)?;
println!("authserver and worldserver passed isolated startup qualification");
}
"verify-channel" => {
let bytes = std::fs::read(need(&a, "file")?).map_err(|x| x.to_string())?;
let pointer = coa_core::channels::verify(&bytes, need(&a, "channel")?, coa_core::signing::EMBEDDED_PUBLIC_KEY).map_err(e)?;
println!("{}", serde_json::to_string(&pointer).map_err(|x| x.to_string())?);
let pointer = coa_core::channels::verify(
&bytes,
need(&a, "channel")?,
coa_core::signing::EMBEDDED_PUBLIC_KEY,
)
.map_err(e)?;
println!(
"{}",
serde_json::to_string(&pointer).map_err(|x| x.to_string())?
);
}
"verify-manifest" => {
let source = coa_core::pkgsource::Source::Dir(PathBuf::from(need(&a, "dir")?));
let (manifest, _) = coa_core::pkgsource::fetch_manifest(&source, coa_core::signing::EMBEDDED_PUBLIC_KEY).map_err(e)?;
let (manifest, _) = coa_core::pkgsource::fetch_manifest(
&source,
coa_core::signing::EMBEDDED_PUBLIC_KEY,
)
.map_err(e)?;
println!("verified signed manifest {}", manifest.version);
}
"verify-upgrade-fixture" => {
coa_core::release_schema::verify_upgrade_fixture(&PathBuf::from(need(&a, "dir")?), coa_core::signing::EMBEDDED_PUBLIC_KEY).map_err(e)?;
coa_core::release_schema::verify_upgrade_fixture(
&PathBuf::from(need(&a, "dir")?),
coa_core::signing::EMBEDDED_PUBLIC_KEY,
)
.map_err(e)?;
println!("verified signed upgrade fixture and every archive file");
}
"extract-schema-base" => {
@@ -252,7 +298,8 @@ fn run() -> Result<(), String> {
}
"sign-channel" => {
let pointer = coa_core::channels::Pointer {
schema: 1, channel: need(&a, "channel")?.clone(),
schema: 1,
channel: need(&a, "channel")?.clone(),
version: need(&a, "version")?.clone(),
release_tag: format!("server-{}", need(&a, "version")?),
snapshot: need(&a, "snapshot")?.clone(),
-667
View File
@@ -1,667 +0,0 @@
# CoA Server Manager — Phase 0 audit & architecture
Status: Phase 0 output. Everything under **Audit findings** was checked against the real repositories and a real
local install (`C:\games\CoA-Repack`); nothing there is invented. Everything under **Decisions** is a proposal
that the phases below implement.
---------------------------------------------------------------------------------------------------------
## 1. Audit findings (facts)
### 1.1 The repack already defines the on-disk layout
`C:\games\CoA-Repack` (RELEASE.json `mainRevision c3beca68`, `sourceRevision b8615469`, 2026-09-11):
```
Core\ authserver.exe worldserver.exe, DLLs, configs\, configs\modules\, Logs\, Crashes\
Data\ maps vmaps mmaps dbc (incl. dbc\Ascension) Cameras 3.8 GB
mysql\ MySQL 8.4.9 (mysqld, mysql, mysqladmin, mysqldump), data\ (3.3 GB), data.7z (141 MB)
Runtime\python\ embedded Python used by Scripts\
Scripts\manage.py the launcher/supervisor (604 lines) + gui_server.py (local web GUI)
Settings\ repack.json (ports, RA creds), database.json (generated DB passwords),
*.conf.template (+ .original)
BugReport\ relay.py, reports\, Logs\
Source\ server-source (2.2 GB) + zip + source-manifest.json
.state\ <name>.json = {pid, exe, created(FILETIME)} for mysql/auth/world/supervisor/relay,
control.lock, configuration.json, debug-logs.json
RELEASE.json {mainRevision, sourceRevision, binaries[{Name,SHA256,Bytes}], account, ...}
MANIFEST.json {fileCount 19382, bytes 3.2 GB, files{path:{bytes,sha256}}} <- per-file hashes
*.bat thin wrappers around Runtime\python\python.exe Scripts\manage.py <verb>
```
Consequences:
* **A per-file hash manifest already exists** (`MANIFEST.json`). It is the baseline for the file-ownership
system on imported repacks: file present in MANIFEST with the same hash → `core/repack, pristine`; present with a
different hash → `modified`; not in MANIFEST → `user`. No need to hash 3 GB to classify.
* **Generated configs are overwritten on every start.** `manage.py prepare()` renders
`Settings\*.template` → `Core\configs\{authserver,worldserver}.conf` and
`modules\mod_ascension_compat.conf` (placeholders `@DATA@ @LOGS@ @LoginDatabaseInfo@ ...`), also writes
`mysql\my.ini`, `mysql\admin-client.ini` (contains the root password) and `modules\coa_bugreport.conf`.
The README says so explicitly. **The templates, not the `.conf` files, are the source of truth** for those three
configs. Other module confs (e.g. `mod_coa_playerbots.conf`) are *not* templated and are edited in place.
* **Process identity is already solved in the repack** the way the spec demands: `{pid, exe, creation FILETIME}`
via `QueryFullProcessImageNameW` + `GetProcessTimes`; listeners via `GetExtendedTcpTable` with owning PID;
a start/stop mutex via `msvcrt.locking` on `.state\control.lock` (1 byte at offset 0 — compatible with
`LockFileEx`); graceful stop = RA `server shutdown 1s 0`, then auth terminate, then `mysqladmin shutdown`.
`stop_all` never hard-kills worldserver. Port offset support exists (`--port-offset`).
* **World is started under a supervisor** (`watch-world`) that also runs the Python bug-report relay; starting
`worldserver.exe` directly skips the relay. The relay ships reports to the maintainers.
* **Ports:** MySQL 3307 (bind 127.0.0.1), auth 3724, world 8085, RA 3443 (RA user/pass in `repack.json`).
* **DB credentials are the *same for every repack download*** (`database.json` is packaged, 48-hex passwords).
Safe only because MySQL is loopback-only. New Manager-created installs must regenerate them.
* **Readiness marker** in `Core\Logs\Server.log`:
`AzerothCore rev. <12-hex> <date> (main branch) (...) (worldserver-daemon) ready...` and
`WORLD: World Initialized In N Minutes M Seconds`. The worldserver banner also **reports its own core commit**
(12 hex) — usable to identify the core version of an imported binary when RELEASE.json is stale.
### 1.2 The reference machine is a real, customised, *running* install
* `Core\worldserver.exe` sha256 `b9aa8f36…` ≠ RELEASE.json (`715bd375…`): the owner's dev build. `Core\`
holds ~60 `worldserver.exe.pre-*` backups and `.pdb`s — **157 GB**. Import must not walk-and-hash everything;
it hashes only what it needs (exes, configs, templates, addon) and enumerates the rest by name/size.
* `mod_coa_playerbots.conf` has 71 `CoaBots.*` keys while the repo's `dist/conf/*.dist` has ~30: real configs
are ahead of the shipped template. The bot schema must therefore tolerate unknown keys (spec §10 already
demands it) and be validated against the *deployed* `.dist`, not only the repo's.
* The worldserver on this machine is **running now (pid 22080)** and the owner runs long bot experiments on it.
**Testing rule: the live install is only ever read.** Start/stop/update tests run on a disposable fixture copy
on different ports (`--port-offset`), never on `C:\games\CoA-Repack`.
* `C:` has 86 GB free (94 % full). Backup/staging code must check free space *before* writing and default
large artefacts (staging, DB dumps) to a user-selectable location.
### 1.3 mod-coa-playerbots is not a plug-in — it is a rebuilt worldserver
`Corfirean/mod-coa-playerbots` (`master`, no GitHub Releases yet) ships `dist\`:
```
bin\worldserver.exe (not in git) Install-CoaBots.ps1/.bat Uninstall-CoaBots.ps1/.bat
conf\mod_coa_playerbots.conf.dist reference\ascensionsidekick-level-builds.json (282 KB)
addon\CoABotUI\{CoABotUI.lua,.toc} sql\2026_09_15_00_ascension_character_selection.sql
release.json {builtForRepack{mainRevision, sourceRevision}, originalWorldserverSha256[], patchedWorldserverSha256[]}
```
* The module is compiled **statically into `worldserver.exe`** (`-DMODULES=static`) *and* needs three small
**core patches** (`docs/core-patches.md`: `LoginQueryHolder` moved to `WorldSession.h`,
`IWorld::AddQueryHolderCallback`, `Group::GetRolls`, plus an Ascension talent accessor). The doc says some of
these were still uncommitted in the core working tree — **must be verified before CI can build bots
from clean commits** (§6 risk R1).
* "Install bots" today = replace `Core\worldserver.exe` (backup → `.orig`), drop `.conf.dist`, create `.conf`
only if absent, copy `Core\reference\ascensionsidekick-level-builds.json`, copy the addon to
`<repack>\Client\Interface\AddOns\CoABotUI` (a `Client\` folder that the repack does not have — the client is
distributed separately), apply `dist\sql\*.sql` to the characters DB with the password read out of
`worldserver.conf` (visible on the command line).
* The installer already does **hash-gated binary replacement** (original ∈ known hashes or patched ∈ known
hashes, else refuse unless `-Force`) and refuses if worldserver is running. The Manager generalises this.
* Bots are real characters on their own accounts (`CoaBotHost*`) in `acore_characters`; no extra database.
Bot creation throttles (`BatchSize 5 / 500 ms`) exist because a 1000-bot synchronous spawn once killed the
server — presets must never lower these. (Confirmed by the owner's own incident notes.)
* The `.conf.dist` is well commented prose — usable as the source for the initial `schemas/bots.json`.
### 1.4 azerothcore-wotlk-coa (core)
* `main`, 1.1 GB, **no releases, no tags, no Windows build workflow**. Only `quality.yml` (ubuntu, source
boundaries) exists. CI for binaries must be written from scratch.
* Build: CMake ≥ out-of-source, `-DSCRIPTS=static -DMODULES=static`, C++20, Boost.PropertyTree (vcpkg
`boost-property-tree`), OpenSSL 3, MySQL client libs. Repo rules (`AGENTS.md`): never edit
`data/sql/base|archive|updates/db_*`; new SQL goes only in `data/sql/updates/pending_db_*/`; **automatic DB
updater is disabled in this project's config** (the bots doc: `AUTOUPDATER: ... disabled`). So schema
migrations are *not* applied by worldserver — the Manager must own a tracked migration runner (spec §18).
* `modules\` contains 24 in-tree modules (mod-ascension, mod-coa-*, …); bots would be the 25th.
Runtime module configs are `Core\configs\modules\*.conf` (+ `.dist`).
* Core HEAD 442cf4c9 (2026-09-30) is ahead of the repack's `mainRevision c3beca68` and the running binary
(`3567e2f8e9d5`): three different revisions are in play on one machine. The compatibility matrix must be
keyed by **exact core commit**, never by "latest".
### 1.5 Toolchain on this machine
Node 26, npm 11, git 2.55, gh (authed as Corfirean), VS 18 Insiders with MSVC 14.51 and WebView2 present.
Rust was **not** installed; `rustup` stable 1.98.1 (msvc) was installed as part of this task. cmake/pnpm absent
(npm is used; CMake is only needed by the *build* repo, on the CI runner).
---------------------------------------------------------------------------------------------------------
## 2. Decisions (architecture)
### D1. One supported layout: the "CoA Repack layout v1"
Both flows converge on the same folder shape:
* **Import** adopts an existing repack-shaped folder (classification: Healthy / Partial / Unknown-custom /
Incompatible, §5).
* **New install** downloads the *base package* (= a repack) and extracts it into staging, verifies, then moves
it into place. Every install is therefore a repack plus Manager metadata.
Result: one code path for process control, config, DB and update. "Unknown custom server" gets the restricted
mode from spec §52 (start/stop via detected exes, backups, console, no update/bots).
A `Layout` trait isolates this (`RepackLayout` now; a hypothetical `NativeLayout` later) so nothing hardcodes
`Core\worldserver.exe`; paths come from `Installation.layout`.
### D2. Manager metadata lives *next to*, not inside, the server folder
`D:\CoA-Repack` ⇒ `D:\CoA-Repack.manager\` (the example in the spec). Rationale: import stays byte-for-byte
read-only on the server folder, folder can be copied/moved without dragging Manager state, backups get a
natural home the user can redirect to another drive.
```
<install>.manager\
install.json identity + detected versions + db info (no secrets) + client path
state.json last known process state, update-transaction status pointer
ownership.sqlite (or ownership.json in v1) path → {owner, hash, version, replacePolicy, origin}
manifests\ copies of every applied release manifest
backups\<id>\ recovery points (each has backup.json + payload)
migrations\ applied-migration ledger (mirrors the DB table, see D7)
staging\ update/install staging (same volume as install → atomic rename)
logs\ manager.log (rotated 5×2 MB) ; cache\
```
A registry at `%LOCALAPPDATA%\CoAServerManager\installs.json` maps `installationId → path`, so a *moved* folder
is re-linkable (the `.manager` folder holds the id; if the path is gone the UI offers "Locate server").
Secrets (DB/RA passwords generated by the Manager) go to **Windows DPAPI-protected** files in the same
`.manager` folder (`secrets.bin`, `CryptProtectData`, user scope). Imported servers keep their own
`Settings\database.json`; the Manager reads it in memory, never displays or logs it.
### D3. Process model (Rust, `process` module)
* `ProcessIdentity {pid, exe_path, creation_time_filetime}` — identical to `.state\*.json`, so records are
interchangeable with the repack's own scripts.
* A process "belongs" to an installation iff `exe_path` is under the installation root (or equals a
configured exe) **and** creation time matches a recorded identity *or* it owns a listening socket on a
configured port. Never by image name alone; never by bare PID.
* Discovery on startup = scan running processes for the installation's exes + `GetExtendedTcpTable` owner PIDs →
rebuild state (works after a Manager crash, PC crash → stale PID dropped because creation-time/exe mismatch).
* Start/stop are serialised with the repack's `.state\control.lock` via `LockFileEx` (same byte), so Manager and
`.bat` files cannot race.
* **Driver strategy.** Phase 2 delegates start/stop to the repack's own `manage.py` through its bundled Python
(`Runtime\python\python.exe -B Scripts\manage.py start-all|stop-all`), because it already handles config
rendering, relay, RA shutdown and readiness, and because behaviour must not regress on a production install.
Observation (identity, ports, health, logs) is native from day one. A native Rust driver for the same
sequence replaces the delegate later, gated behind the same `ServerDriver` trait and validated against the
delegate by the same integration tests. Startup order/health follows spec §7–8.
* States: `Stopped | Starting | Running | Stopping | Crashed | Updating | Unknown`; overall health adds
`Ready | NeedsAttention` using: process alive → port owned by that PID → log `ready...` marker after this
start's timestamp → no `FATAL`/`ERROR` startup lines.
* Forced kill exists only as an explicit, warned last resort after graceful stop times out.
### D4. Config engine (`config` module)
* Line-preserving parser: keeps comments, blank lines, unknown keys, line endings and encoding (UTF-8, LF/CRLF
detected). A `set(key, value)` rewrites only that key's line; missing keys are appended under a
`# Added by CoA Server Manager` comment. Never re-serialises the file.
* Layered targets via the layout: for templated configs the edit is applied to `Settings\<name>.template`
(source of truth) **and** the rendered `.conf` (so the running/next state agrees without a restart of the
renderer); for `mod_coa_playerbots.conf` edit in place.
* Save = validate against schema → write `<file>.tmp` in same dir → re-parse and compare → snapshot previous
into `.manager\backups\config\` → `MoveFileEx(REPLACE_EXISTING)`.
* Merge (`.dist` v1 → v2): add keys present in new `.dist` but missing; never overwrite user values; keys
removed upstream → flagged `deprecated`, kept.
* Schemas: `schemas/bots.json`, `schemas/server.json` (curated whitelist), fields exactly per spec §10
(`key type category title description default min max options advanced restartRequired dangerous`;
`restartRequired ∈ runtime|world|full`). Presets are separate JSON diffs shown as "will change N settings".
### D5. File ownership & manifests
Every release ships `manifest.json`:
```jsonc
{
"schema": 1,
"kind": "base|update|bots",
"version": "0.4.1",
"core": { "commit": "<40 hex>" },
"bots": { "commit": "<40 hex>" | null },
"builtAt": "2026-…Z",
"minManagerVersion": "0.1.0",
"requires": { "core": ["<commit>"|"range"], "dbSchema": ">=N" },
"files": [ { "path":"Core/worldserver.exe", "sha256":"…", "size":123, "owner":"core|bots|manager",
"policy":"replace|replace-if-pristine|merge-config|create-if-missing|never-touch" } ],
"migrations": [ { "id":"2026_09_15_00_…", "db":"characters", "sha256":"…", "destructive":false } ],
"signature": { "alg":"ed25519", "keyId":"…", "sig":"…" } // verified when a public key is embedded (§54)
}
```
`ownership` table per install: `path, owner(core|bots|manager|user), sha256_at_install, installed_version,
policy, origin(imported|installed)`. Update algorithm compares **current hash vs recorded hash vs incoming
hash**: current == recorded → safe to replace; current ≠ recorded → *modified outside Manager* → prompt
(Keep / Replace / Compare / Cancel); path unknown → `user`, never touched. Import seeds the table from
`MANIFEST.json` where present (imports are read-only; hashes computed lazily and only for managed paths).
### D6. Update transaction (Prepare → Verify → Snapshot → Apply → Validate → Commit)
1. **Prepare** — fetch manifest (HTTPS only, signature checked), compatibility matrix check, disk-space check on
staging volume and backup volume.
2. **Download** to `staging\<txid>\dl\` with `.part` files, HTTP Range resume, retry/backoff, cancel, progress.
3. **Verify** — SHA-256 of every artefact; nothing is executed or extracted into the live tree before this.
4. **Snapshot** — server must be stopped (never copy over a running worldserver); create recovery point:
replaced binaries, changed managed configs, module state, full dumps of every managed realm database;
write `txn.json {state: Snapshotted}`.
5. **Apply** into `staging\<txid>\tree\`, resolve ownership conflicts, merge configs, then swap file-by-file with
same-volume atomic renames, journaling each step (`txn.json` lists done/undone operations).
6. **Migrate** — durably mark SQL as running before execution. Failure restores the full database recovery point
before restoring files. Interrupted SQL is never automatically replayed.
7. **Validate** — check database structure, start server, require ten seconds of continuous readiness with timeout.
8. **Commit** — ownership table + `install.json` version bump, mark txn `Committed`, prune staging.
Any crash before Commit leaves `txn.json` in a non-terminal state; on next launch the Manager detects it and
offers *Roll forward* or *Roll back* — the install is "recoverable" by construction.
Rollback restores files, configuration and installation metadata. Once migrations started, it also restores all
databases from the full pre-update recovery point. Failed recovery remains unfinished and blocks startup and another
update. The same journal protects Repair. Old transactions without a full recovery point cannot roll back database
changes automatically. Independent database restore remains available for other recovery points.
### D7. Database strategy (`db` module)
* Driver: talk to the repack's own `mysql.exe` / `mysqldump.exe` / `mysqladmin.exe` (bundled, 8.4.9). Passwords
are passed via a temp `--defaults-extra-file` with restrictive ACL, deleted immediately — never on argv. A
native Rust client (`mysql_async`) is used for health pings and migration ledger reads.
* Ledger: table `acore_world.coa_manager_migrations(id, db, sha256, applied_at, status, error)` (created by the
Manager, in a dedicated table — no core schema is changed) mirrored to `.manager\migrations\`.
Statuses `Applied | Pending | Failed | Running`. Each file runs in a single connection; DDL is not transactional, so
"destructive" migrations (flag in manifest, or heuristic scan for `DROP|TRUNCATE|DELETE|ALTER ... DROP`) force
a fresh DB backup first and require explicit confirmation.
* Backups: `mysqldump --single-transaction --routines --quick` per DB. Quick = characters + auth + configs +
metadata; Full adds world (large); Config-only; DB-only. Compressed with zstd. Restore is always to a
staging schema first (`…_restore`), swapped only after a row-count sanity check, with the current DB dumped
beforehand.
* Never: `DROP DATABASE` or resetting characters. Update recovery restores databases into staging schemas and
keeps the replaced tables in separate schemas. Delete/
reset lives only in **Settings → Advanced → Danger Zone**, deletes tracked files only, and refuses to remove a
directory that still contains untracked files.
* Clean install: extract `mysql\data.7z` (packaged data dir), then **rotate** root/app passwords to fresh random
values (`ALTER USER`), rewrite `Settings\database.json`/templates via the layout renderer, store copies in
DPAPI. `bind-address=127.0.0.1` enforced.
### D8. Bot install/update (needs server-side cooperation — see §4)
Compatibility matrix `compat.json` (published with releases): `[{manager, core, bots, dbSchema}]` keyed by exact
core commit. Bots install = "install the bot-enabled `worldserver.exe` built for **this** core commit" +
conf.dist + talent JSON + SQL migration + (if client attached) addon. Same hash-gated + backup-first rules as
the existing `Install-CoaBots.ps1`, executed through the D6 transaction. Force-install on unknown core =
Advanced override, snapshot first.
### D9. Client integration
The client is a separate object. By default the Manager only detects it (`Wow.exe`/`Ascension.exe` + `Data\`), reads/writes
`realmlist.wtf` after backing it up, and copies `Interface\AddOns\CoABotUI` (backing that one directory up only if
its files differ from the manifest). No touching of `WTF`, `Cache`, other AddOns, or the exe. Downloading or updating
a client is opt-in and described in section 9 (game client download); an existing client is never changed without asking.
*Reference machine note:* `C:\games\Ascension` is a heavily modified Ascension client (custom `d3d9.dll`,
renderer files, many `.bak`s) — client detection must be strictly read-only + additive.
### D10. Network / friends
Detect LAN IP and public IP (HTTPS to a small set of IP-echo endpoints, user-toggle), listening check via
outbound self-test, **CGNAT heuristic** (WAN address of router ∈ 100.64.0.0/10 or private / ≠ public IP),
UPnP/NAT-PMP later. Firewall rules created only through a separate elevated helper (UAC on demand, never whole
app as admin), fixed names `CoA Server Manager - Auth` / `- World`, idempotent (query before add), delete only
own rules. Never exposed: MySQL 3307, RA 3443, Manager control channel (Tauri IPC only, no listener). Private
network = Tailscale detection/guided enable in v1; interface `NetworkProvider` so "CoA Connect" can slot in.
Friend package contains only `realmlist`/instructions/optional addon; secrets structurally excluded (whitelist
copy, not blacklist).
### D11. Stack & code layout
```
coa-server-manager/
docs/ ARCHITECTURE.md, flows, wireframes
schemas/ bots.json, server.json, presets/, manifest.schema.json, compat.schema.json
src-tauri/src/
main.rs, commands/ thin Tauri command layer (validate → call service)
fsx/ path validation, safe join, atomic write/replace, disk space, ownership
layout/ RepackLayout, detection & classification
registry/ installs.json, .manager dir, install.json
process/ identity, listeners, lock, drivers (delegate → native)
health/ probes, log-marker scan, error translation
config/ parser, merge, schema, presets
db/ mysql tool wrapper, ledger, migrations, dump/restore
backup/ recovery points, retention
update/ manifest, download, verify, txn (journal), rollback
client/ detection, realmlist, addon
net/ ips, ports, cgnat, firewall, tailscale
errors/ error catalogue → human message + actions
diag/ diagnostics, export package (redacting)
src/ React + TS + Vite + Tailwind + shadcn/ui (presentation only)
tests/ integration fixtures (fake repack generator), failure-injection harness
coa-server-build/ (separate repo) workflows + packaging + manifest signing
```
All destructive filesystem operations exist only in `fsx`; frontend never has `fs` scope in Tauri capabilities.
Every command that mutates goes through `fsx::Transaction`-style helpers that (a) validate the path is inside a
registered installation *or* the `.manager` dir, (b) refuse symlink/junction escapes, (c) log an audit record.
### D12. Build/release repo (`coa-server-build`)
Windows runner: checkout **exact** core SHA and bots SHA from workflow inputs (refuse branch names), place bots at
`modules/mod-coa-playerbots`, verify core patches are already in the core commit (fail the build if the patch set
is not applied — never apply ad-hoc patches at build time unless they are versioned `.patch` files in the build
repo), vcpkg-cached deps, CMake Release/RelWithDebInfo static, produce **two binaries per core commit**:
`worldserver` (no bots) and `worldserver+bots`, then `authserver`, DLLs, config `.dist`s, talent JSON, addon, SQL
migrations, `RELEASE.json`, `manifest.json` (+SHA256, +ed25519 signature), zstd-compressed update package.
Base package (≈3.2 GB; Data 3.8 GB + mysql data) is split into ≤ 1.9 GB parts (GitHub release asset cap is 2 GiB)
with a parts manifest. Reproducibility: pinned runner image label, recorded compiler/vcpkg versions, source SHAs,
build timestamp written into RELEASE.json.
### D13. Linux: the servers run in Docker (experimental)
Linux has no repack launcher and no Win32 process API, and the host should need nothing but Docker. A server folder
that contains `Settings/docker.json` is a **Docker installation**; every other folder is a repack, handled by the
code above without any change. `driver::run`, `process::observe` and `layout::scan` check for the marker first and
hand over to `coa_core::docker`; nothing else needed to change for start, stop, status and the server list.
* **Containers** (`docker/lifecycle.rs`): `coa-<project>-db` (official `mysql:8.4`, data in a named volume, not
published on the host), `-world` and `-auth` (a small runtime image holding only the shared libraries; the
binaries are mounted from `Core/`, so an update replaces files and never rebuilds an image). The image tag is a
hash of its Dockerfile.
* **Why the `docker` command line and not `docker compose`**: the compose plugin is missing from some distributions'
Docker packages, and the plan is to ask for as little as possible on the host. The command line is wrapped by a
`Docker` trait (`docker/cli.rs`), so the logic is tested with an in-memory fake.
* **Same folder shape as a repack where it matters**: `Core/configs`, `Core/Logs`, `Settings/repack.json`
(ports, RA login), `Settings/database.json` and `Data/`. Configuration editing, log tailing and the RA console
therefore work as they do on Windows. The container runs as the owner of the folder and starts in `Core/`.
* **Settings forced by environment** (the core reads `AC_<KEY>` before the `.conf`): `AC_BIND_IP=0.0.0.0` (the
published address, `bindAddress`, decides who can connect), `AC_DATA_DIR`, `AC_LOGS_DIR`, `AC_RA_ENABLE`,
`AC_RA_IP`, and `AC_UPDATES_ENABLE_DATABASES=0`: the server's own database updater needs a `mysql` client program and
stops the server without one; the Manager applies database updates itself (section 1.4). The remote console is published
on `127.0.0.1` only.
* **Secrets** go to `docker` by environment (`--env NAME` without a value), never on a command line.
* **Order**: database healthy, then world listening, then auth. The auth server exits when no realm is online.
Readiness is a connection that stays open: Docker's proxy accepts connections on a published port before the server
inside listens, so a plain connect proves nothing.
* **Configuration path in the binaries**: Linux builds must use `-DCONF_DIR=configs` (see `coa-server-build`),
otherwise the core looks for module configs in a path baked in at build time.
* **Database access** (`db.rs`): for a Docker installation `Db` runs `mysql`, `mysqldump` and `mysqladmin` inside the
database container with `docker exec -i`, connecting over TCP on the container's loopback exactly as the repack's
commands do on the host (password through `MYSQL_PWD`, never on a command line). Nothing else changes: accounts,
backups, the population query, migrations and the RA service account all go through `Db`, and the host needs no
MySQL client. A repack keeps using its bundled tools.
* **Health of the database container** is a ping over TCP, like every connection the Manager makes. On a new volume the
image first runs a temporary server that answers on its socket but takes no network connection; a socket ping reported
the container healthy about four seconds before TCP worked (measured: 10 s against 14 s).
* **Main configuration files**: a package carries only `worldserver.conf.dist` and `authserver.conf.dist` (the release
tool leaves active files out). On Windows the launcher writes them at each start; on Docker `ensure_main_configs` creates
them from the templates when they are missing, at installation and at every start, and never overwrites one.
* **Installing a new server** (`docker/install.rs`, separate from `install::install_base`, which is not touched). Same
order of events: signed manifest, space and folder checks, verified download, extraction into `<dest>.installing`,
database, then one rename. The package must hold `Core/worldserver`, `Core/authserver`, the `.dist` templates,
`_migrations/` and **`Database/baseline/{auth,characters,world}.sql.zst`**. The baseline is a dump, in the format of the
Manager's backups, of databases in which **every migration of the package is already applied**; the installer imports
it, records those migrations as applied (`baseline = 1`, a few bulk statements) and creates the `acore` account, the
realm port and the console account. It is the same arrangement as a Windows package, which ships its prepared database.
The databases are **not rebuilt from the repository's SQL**: some migrations are guards generated from the maintainers'
live database (`rev_20260903_01_live_class_baseline` refuses to run unless the table holds exactly the rows it expects),
so replaying the SQL files from the base scripts fails, in any order. `coa-release export-baseline --server DIR --out DIR`
produces the dumps from a prepared server (repack or Docker). The game data stays where the person has it
(`dataDir` in `docker.json`, mounted read-only). A failure removes the containers, the volume and the staging folder.
* **Validating a release on Linux** (`docker/fixture.rs`, used by `coa-release extract-schema-base` and `schema-contract` where
there is no Windows database program): the signed base package carries the MySQL data directory of a Windows repack, and a
MySQL 8.4 container opens it as it is (`--lower-case-table-names=1`, the repack's setting). The fixture is a Docker server
folder (`docker.json` with `mysqlData`: the database container uses that directory in place of a volume; an installation
never sets it), plus a `root` account for TCP, which the repack only has for its socket. The release SQL is then applied and the
schema contract captured by the same code as on Windows, and `export-baseline` dumps the result: that is how a Linux build
produces `Database/baseline` without anyone's live database. The migration checksums recorded in the base are those of
files checked out on Windows (CRLF line endings, `core.autocrlf`): the SQL of the core, the modules and SQUID must be
checked out the same way for the checksums to match, or every applied migration looks edited.
* **In the screens** the host is asked once per command (`coa_core::platform::flavor()`: repack on Windows, Docker
elsewhere) and the Docker half lives in `src-tauri/src/docker_install.rs`; the repack arm of each install command is the
code that was there. `install_environment` tells the install screen the kind of server, the suggested folder
(`~/CoaServer`) and why Docker cannot be used, if it cannot. On Docker the screen also asks for the game data folder and
the package, and there is no default package address until a signed Linux package is published. Packages are checked with
the embedded key; only a debug build (`tauri dev`) accepts another one, named in `COA_DEV_TRUSTED_KEY`, to try the
installer on a package signed with a throwaway key.
* **Updates are refused for a Docker server, never half done.** `update::preview`, `apply` and `rollback` refuse it: the
update packages are the repack's (executables, a bundled MySQL, a launcher) and applying one would put Windows files in a
Linux folder. Found by installing a server with the screen: the update check had read the Windows channel and offered one.
* **Realm profiles (CoA / Wildcard) work on a Docker server.** What the repack's patched launcher did at each start is done
by the Docker backend: finish an interrupted switch (`realms::before_start`), name the realms in the realm list, and give
the containers the databases of the selected realm (`acore_world_wildcard` ...). The switch itself (configuration swap,
database copy, journal) is the shared code; `prepare_launcher` has nothing to patch, and Wildcard support is read from
`Core/worldserver` as it is from `Core/worldserver.exe`.
* **The game client starts under Wine on a Linux host** (`wine.rs`; `client::launch` and `client::is_running` hand over):
umu-launcher with a Proton build when `umu-run` is installed (the newest GE-Proton found for Steam, or umu's own choice),
else plain Wine; `WINEPREFIX` defaults to `~/Games/umu/coa-client`; `WINEDLLOVERRIDES=divxtac=d` is always set, because
DivxTac.dll deadlocks the world loading screen under wine-mono. `COA_PROTONPATH`, `COA_WINEPREFIX` or
`client-launch.json` in the Manager's folder (`proton_path`, `prefix`, `runner`) override the detection. Whether the client
runs is read from `/proc` (under Wine the command line holds the Windows form of the path). Output goes to `client.log`.
* **Sharing with friends** (`docker/sharing.rs`): who can reach the game is decided by the address the container ports are
published on, `bindAddress` in `docker.json`; the `BindIP` of the configuration files is forced to `0.0.0.0` inside the
containers and changes nothing. Opening and closing therefore edit `bindAddress` (and set `CoA.AllowRemoteClients`), "servers
open" and the exposure check are computed from it (the database is never published, the console only on `127.0.0.1`), and
there is no firewall row on Linux. Settings the backend fixes (`docker::FORCED_KEYS`) are not offered; a test keeps that list
equal to the variables the containers get. A world that restarts itself (exit code 2) is restarted by Docker once it has come
up. The database console shows `docker logs`, and the file-based screens read Linux locations (the desktop folder from the
user directories file, memory from `/proc/meminfo`, the distribution name for the problem report).
* **Game data folder** (`docker::game_data_dir` / `set_game_data`, Settings card): `dataDir` in `docker.json` can be changed
after the install, only while the world and auth are stopped, and only to a folder that passes the install checks. A world
that stops with "does not hold the CoA client dbc set" is reported as `GameDataMismatch` (wrong data set: the standard one,
not Conquest of Azeroth's) instead of a bare failure.
* **Not done yet**: downloading the game data, updates, port conflict detection, the firewall and exposure checks, the
Wildcard realm profiles, and the client under Wine/Proton.
### D14. Keeping Windows and Linux apart
A fix for one platform must not be able to break the other. The rules:
1. **Platform code lives in its own modules**: `coa_core::docker` for Linux and Docker; the repack code (`driver`, `process`,
`install`, `layout` and the bundled-tool half of `db`) for Windows. A new Linux feature is a new file there, not an edit
of a repack function.
2. **Shared modules hold platform-neutral logic only** (manifest, signing, download, extraction, migrations, backups,
configuration editing, the registry).
3. **The difference enters in as few places as possible**: the early `is_docker` return at the top of `driver::run`,
`process::observe`, `layout::scan` and `Db::from_repack`, and the platform checks of the Tauri layer. Everything past
that point belongs to one platform.
4. **No `cfg` in the middle of a shared algorithm.** Where one is unavoidable (file modes, a path comparison), it is small,
commented, and the other platform's branch is the code that was there before.
5. **Reuse by calling, not by editing**: a Linux feature that needs a helper from a Windows-side file makes it
`pub(crate)` and calls it (visibility only); it does not change what the helper does.
6. **Both platforms are tested on every pull request** (`check.yml`: Windows and Linux). Tests of one platform's behaviour
are marked for that platform, so they cannot fail on the other.
---------------------------------------------------------------------------------------------------------
## 3. Flows
### 3.1 First run
`Welcome → [Install new server] | [I already have a server] | (link) Manage another install`.
New: choose folder (default `C:\Games\CoA Server`; checks: free space ≥ base+backup headroom, folder empty or
absent, not a client folder, not `Documents`/system dirs, not already registered) → single progress screen
(Download → Verify → Extract → Database → Bots(optional) → Start → Health) → "Your server is ready" →
Create account → PLAY. Technical log behind "Show details" only.
### 3.2 Existing-server import (strictly read-only)
select folder → `layout::scan()` (read-only opens, `FILE_SHARE_READ|WRITE` so a live server is unaffected) →
report: core exes + hashes vs RELEASE.json/MANIFEST.json, detected core commit (RELEASE.json → else banner rev in
Server.log → else unknown), configs & modules present, DB running/reachable (ping only), bots detected (conf
present ∧ patched-hash or `CoaBots.*` keys), client detected, classification + "No files will be changed" →
**[Add server]** writes only `<folder>.manager\` and the registry entry. Import never "fixes" anything.
Verification for the fixture test: recursive (path,size,mtime) snapshot of the server folder excluding
files the running server itself changes, diffed before/after.
### 3.3 Update — see D6. Failure matrix (spec §60) is executable via a fault-injection harness: kill at step k,
disk-full at write n, network cut at byte n, migration returns error, new worldserver exits non-zero, port
taken, exe quarantined (file vanishes), folder moved, user-modified managed file, unknown config keys.
### 3.4 Rollback — restore the pre-update databases when migrations started, followed by files and metadata
The UI explains that progress after the recovery point is lost. SQL failures before startup recover automatically;
failed health checks keep the installation blocked until the owner chooses recovery. Every recovery point and staging
schema has a unique identifier, and corrupt update journals fail closed.
---------------------------------------------------------------------------------------------------------
## 4. Required changes in the two source repositories
Prefer server-side cleanliness over Manager hacks. Proposed (each is an issue/PR on the owner's side, none is
made without approval):
| # | Repo | Change | Why |
|---|------|--------|-----|
| S1 | mod-coa-playerbots | Master switch `CoaBots.Enable` (0 = module registered but inert; no login/hooks/commands) | Lets a **single** worldserver ship for everyone. "Disable bots" becomes a config flip with restart, not a binary swap; drops the 2-binary matrix and most of §D8 risk. |
| S2 | mod-coa-playerbots | Commit **all** core patches in the core repo; delete "uncommitted working-tree" state from docs | CI must build from clean SHAs (R1). |
| S3 | mod-coa-playerbots | Real Releases + `dist/release.json` replaced by the shared `manifest.json` schema; `TalentBuildsPath` default = `Core/reference/…`, remove the hard-coded dev path fallback | Manager and installer share one truth; no absolute dev paths. |
| S4 | mod-coa-playerbots | Ship a machine-readable config schema (`conf/…schema.json`) next to `.dist`, or generate it in CI from the `.dist` comments | Avoid schema drift (71 vs 30 keys today). |
| S5 | core | Windows build+release workflow (or the build repo builds it); publish `worldserver --version --json` (core commit, bots commit, DB schema id) | Reliable version detection instead of log scraping. |
| S6 | core | Health endpoint alternative: worldserver already prints `ready...`; add a stable machine line (`COA-READY {...}`) or a tiny loopback status file `Core\Logs\ready.json` | Health without regex on human text. |
| S7 | core/repack | Ship a `manager-hooks.json` in the repack describing service names, ports, exes, config templates, RA settings | Layout detection without hard-coded knowledge; unknown custom builds can opt in. |
| S8 | core | Keep the auto DB updater disabled but expose `--dry-run-updates` listing pending updates | Manager migration UI without re-implementing the updater. |
| S9 | repack | Per-download random DB passwords and `Settings\database.json` generated on first start, not packaged | Security (§1.1). Manager does it itself for new installs meanwhile. |
Everything still works without S1–S9 (Manager has fallbacks), they just remove fragility.
---------------------------------------------------------------------------------------------------------
## 5. Import classification rules
* **Healthy** — `Core\{worldserver,authserver}.exe`, `Core\configs\*.conf`, `Data\dbc`, `mysql\bin\mysqld.exe` +
`mysql\data\acore_{auth,characters,world}`, `Settings\repack.json`, `Scripts\manage.py`, all present.
* **Partial** — a repack skeleton with pieces missing (e.g. no Data\maps, DB dirs absent).
* **Unknown/custom** — has `worldserver.exe` + `authserver.exe` but not the repack scaffolding.
* **Incompatible** — not a 3.3.5 AzerothCore layout / two installations nested / client folder.
The reference install classifies as **Healthy (customised)**: repack shape, binary hash differs from RELEASE.json.
---------------------------------------------------------------------------------------------------------
## 6. Risks & open questions
* **R1 (blocking for Phase 7/6)** — are all core patches committed? Owner action: confirm/commit (S2).
* **R2** — Legal/hosting of the base package: `Data\` (maps/vmaps/mmaps/dbc) derives from the game client;
and Ascension-specific DBC. Where does the owner want to host the 3–4 GB base (GitHub Releases in the build repo,
parts ≤ 1.9 GB; or own storage)? The Manager's downloader is source-agnostic; the choice affects Phase 5–6.
* **R3** — Manager signing key: needs an Ed25519 key pair generated by the owner; public key embedded in the app,
private key in GitHub Actions secrets. Phase 6 can start with unsigned + hash-only and flip the enforcement flag.
* **R4** — Bug-report relay (Python, sends reports to maintainers) is part of the repack's world startup; Manager
keeps it (privacy note surfaced in Settings, user can disable via the existing `coa_bugreport.conf` mechanism
only if the repack supports it — currently it forces `Enable = 1` on every start; not touched by Manager).
* **R5** — Tauri updater needs a hosted, signed `latest.json`; Manager self-update is Phase 10.
* **R6** — Windows long paths / non-ASCII install paths: repack requires a Latin path (uses 8.3 short names);
new-install folder chooser enforces it.
---------------------------------------------------------------------------------------------------------
## 7. Phase plan (each phase ends: compile → tests → run against fixture → verify live install untouched → commit)
| Phase | Deliverable | Done when |
|-------|-------------|-----------|
| 1 | Tauri+Rust+React skeleton, `fsx`, registry, `.manager` layout, logging w/ rotation, manifest structs + JSON schema, error catalogue skeleton | `cargo test` green; app launches; metadata round-trips |
| 2 | Read-only scan/classify/import; process discovery; Start/Stop via delegate driver; health | Import of `C:\games\CoA-Repack` leaves it byte-identical (proved by snapshot diff); Start/Stop verified on **fixture copy, offset ports** |
| 3 | Config parser/merge/atomic save; bots+server schemas; presets; UI | Property tests: unknown keys/comments preserved; round-trip identity |
| 4 | Recovery points, DB dumps, config snapshots, restore-to-staging | Backup→restore fixture test; fails safe when disk full |
| 5 | Clean install from base package; DB bootstrap + password rotation; account creation | Fresh VM/folder install reaches "ready" |
| 6 | Build repo & workflows; signed manifests; update transaction, rollback | Fault-injection suite green (spec §60) |
| 7 | Bots install/update via txn; compat matrix; GUI settings | Install → disable → restore on fixture |
| 8 | Client detection, addon, realmlist, PLAY | Client tree hash unchanged except addon dir + realmlist |
| 9 | Friends: net diagnostics, firewall service, Tailscale | Idempotent rule add/remove test |
| 10 | Error translation, diagnostics, repair, a11y, self-update | Spec §61 checklist |
---------------------------------------------------------------------------------------------------------
## 8. Decisions recorded after owner review (2026-09-30)
* **Core changes go through our own fork.** We are not maintainers of `jealous-sound/azerothcore-wotlk-coa`, so
the bot-enabling core patches (and the S1/S5/S6/S7 style changes) live in a fork owned by the bot/manager
project; the build repo pins exact fork SHAs. Upstream is tracked as a remote and merged periodically; the
compatibility matrix is keyed by fork commit. The fork is created when Phase 6/7 needs it (nothing is pushed
before then). This supersedes S2 (no upstream commits required) and removes risk R1.
* **Base package is compressed and split.** Payloads are zstd/LZMA-compressed and cut into parts below the
2 GiB GitHub asset limit (target 1.9 GB) with a parts list in the manifest; the downloader verifies each part
and the reassembled archive. Actual ratios will be measured in Phase 5 (the packaged database already shrinks
3.3 GB -> 141 MB; `Data\` maps/vmaps/mmaps are expected to compress far less).
* **Manifest signing (R3 resolved).** Ed25519 key generated. Public key: `keys/manifest-signing.pub`, embedded
in the app (`signing::EMBEDDED_PUBLIC_KEY`). Private key: `%USERPROFILE%\.coa-manager\signing\` (outside the
repo, never committed); CI receives it as the `COA_SIGNING_KEY` secret, which the owner must add manually.
Signatures are detached (`manifest.json.sig`, over the exact manifest bytes), so the embedded `signature`
field in the manifest was removed. **Back up the private key** — losing it means shipping a new app to rotate.
### 8.1 Fork created (2026-09-30)
* Fork: `Corfirean/azerothcore-wotlk-coa` (from `jealous-sound/azerothcore-wotlk-coa`). Default branch is `coa-bots`
(a branch named `coa` is impossible: the fork inherits upstream's `coa/...` branches). `main` stays a pure mirror of upstream.
* `coa-bots` = upstream `main` + a small, reviewable patch series (audit of the owner's 38 local commits, 2026-09-30):
1. `Core/Bots` hooks: `LFGMgr::GetProposalIdForPlayer`, `PlayerScript::OnPetitionOffered`, `Guild` friend `BotMgr`.
2. Crash fixes seen under bot load: `CombatManager::PutReference`, `Unit::RemoveFromWorld` dangling delayed-visibility pointer,
`InstanceMap::UnloadAll` teleport race, `IsStatisticAchievement` missing category.
3. `AscensionClassServiceBridge` + `AscensionResourceQuery` (needed by the bot module) and the socketless-bot appearance-sync guard.
4. RA: no throw on abrupt client disconnect (the Manager's RA client does exactly that).
5. CI workflow `coa-bots-build.yml`: builds core + bots module on Windows, runs `worldserver --version`.
* Discovery: the bot chassis (`LoginQueryHolder`, `IWorld::AddQueryHolderCallback`, `Group::GetRolls`) is already in upstream
(`feat(Core): add mod-playerbots hooks and CoA API (#3069)`), so it is not carried; `docs/core-patches.md` in the bots repo is outdated.
* Deliberately NOT carried (owner's other local work, decide separately): CoA mechanic corrections, `AscensionClassTester`
(dev harness; couples core to the bots module), respec `SpecId==0` guard, `cs_daynight`, aura/spell null-guards in
`SpellAuras.h`/`Spell.cpp`, class-contract data, debug `LOG_ERROR` traces in Petition/Query handlers, fleet log appenders in
`worldserver.conf.dist`, `apps/coa-dbc` binaries, `height_query` tool.
* Sync policy: `main` fast-forwards from upstream automatically; `coa-bots` is rebased/merged onto it nightly by a workflow in the
build repository (conflict => issue, no release). Channels: `edge` (every green nightly) and `stable` (promoted by the owner).
---------------------------------------------------------------------------------------------------------
## 9. Backlog (owner requests)
* **Interface languages: English (default), Russian, German, French, Spanish** (requested 2026-09-30).
Plan: i18n layer in the React UI (string catalogue per locale, ICU-style plurals, locale picked from the OS with a
switch in Settings, persisted per user); all user-facing strings currently written in English move into catalogues;
the Rust error catalogue (`error.rs` titles/messages/actions) is keyed by `ErrorCode` and translated on the UI side
(backend keeps stable codes; technical details stay untranslated for bug reports); dates, sizes and numbers use
`Intl`; settings-schema titles/descriptions (`schemas/*.json`) get per-locale overlays (`schemas/i18n/<locale>.json`);
translations are reviewed by native speakers before release, with an English fallback for missing keys and a CI check
that every locale has every key. Do this before the first public release so strings are not retro-fitted.
**Status (2026-09-30, updated):** catalogue + picker + every screen translated (en/ru/de/fr/es drafts); settings-schema titles,
descriptions, categories, presets, options and units are translated through overlays in `src/i18n/schema/`; diagnostics
checks, update steps, companion sizes and friends notes are recognised and translated in the UI. `tools/check-i18n.mjs`
verifies keys, placeholders and overlay coverage. Still English: free-form backend technical messages. Native-speaker
review is still needed (see `docs/TRANSLATIONS.md`).
* **Language choice on the very first screen** (requested 2026-09-30): the welcome screen must offer the language picker
right away (before any other text is read), preselected from the OS language; the choice is persisted and shared with
Settings. **Done 2026-09-30:** shared `LanguagePicker` (top-right of the welcome screen and in Settings).
* **Clean-install gap found by the owner (2026-09-30):** installing from the default URL fails with 404 because the `base`
release does not exist yet (only `edge` is published). The message is now human ("package not available yet"). Also open:
the base package has no `Data\` (maps/dbc/vmaps, ~3.8 GB); the installer needs a "use my existing Data folder / download"
step, and the owner must decide hosting/legal for game data before `base` is published.
* **Modules tab** (requested 2026-09-30): install/manage optional server modules (bots, AH bot, Solocraft, ...).
Design decision: AzerothCore modules are compiled into `worldserver.exe`, so "install" cannot mean "drop files in".
Plan: CI builds one binary containing a curated set of modules, every one disabled by default; the Manager only
enables/disables and configures them (`Core/configs/modules/<name>.conf`, schema-driven settings editor as for bots).
A `modules.json` catalogue travels with update packages (id, title, description, category, source repo + commit,
licence, conf file, enable key, settings schema, needed DB migrations, conflicts, status tested/experimental).
Adding a module = add it to the CI build list + catalogue entry, released as an ordinary update. Only modules tested
against the CoA fork and licence-compatible (AGPL/GPL, because the binary is distributed) are listed. The fork's own
CoA features (dynamic XP, ethereal bazaar, ...) appear in the same tab as "built in" toggles.
* **Known launcher leftovers:** the repack's `Scripts/manage.py` still renders `mod_ascension_compat.conf` at every start;
the core now ignores it ("is no longer read ... move its settings into coa.conf") - harmless warning, clean up together
with a launcher refresh. Migration-runner root cause for the re-created `item_template_ascension_compat` table (a module
script older than the rename is seen as pending) is worked around in `clean-base`, not fixed in the runner.
* **Bug found by the owner on the first clean install (2026-09-30):** login worked at the auth step but the game dropped
the connection. Causes: (1) the package shipped the maintainer's Trace-level logging templates (gigabytes of log per
hour, world thread stalled); (2) no active `coa.conf` (`CoA.Enable = 1`) because packages contain only `*.conf.dist`.
Fixed: `clean-base` restores quiet templates, `assemble-tree` ships `coa.conf.dist`, and the Manager creates missing
module `.conf` files from their `.dist` on install and before each start of a Manager-installed server.
* **Game client download and update through the Manager** (built 2026-10-01, `coa-core::clientdl`). The community PTR launcher
("Conquest of AzerothCore" Electron app) reads its client from
`https://launcher-api.coa-development.org/downloads/client/latest.json` (`{schema, version, publishedAt, files:[{path,size,sha256}]}`;
~200 files, 43 GiB: `Ascension.exe`, DLLs and ~40 big `Data/*.MPQ`) and fetches each file as the content-addressed object
`.../downloads/client/objects/<sha256>`. The Manager uses the same endpoints with its own resumable, hash-verified downloader:
* **State** lives in the client folder (`.coa-manager/client-state.json`: manifest version, per file size/mtime/sha256). A
routine check (every 5 minutes, like the server) is one small manifest request compared with the recorded version; no game file is read.
* **Plan, then apply** (like server updates): files are compared by size and mtime against the state, and hashed only when those
no longer match. Each file is `Missing`, `Changed` (still as the Manager left it) or `Modified` (the player changed it, e.g. a
custom `d3d9.dll` or a patched exe). Modified files are kept on request (and remembered: asked again only when the published file
changes) or replaced after being moved to `.coa-manager/replaced/<time>/`. Objects are staged in `.coa-manager/staging/<sha>` and
moved into place only after the hash matches; state is saved after every file, so cancel, crash or reboot resume where they stopped.
* **Never touched:** `WTF`, `Cache`, `Errors`, `Logs`, `*.log`, `realmlist.wtf`, `Interface/AddOns/CoABotUI` (those have their own paths).
* **UI:** PLAY becomes **UPDATE CLIENT** when a tracked client is outdated (with "Play without updating"); with no client linked it
becomes **Set up game client** (choose an existing folder, or download into `<chosen folder>/CoA Client` with a free-space check).
An existing client that is not tracked can be adopted from Settings > Game client ("Keep this client up to date").
A fresh download gets `realmlist.wtf` for each installed locale (the manifest has none) and, for local hosts, the companion addon.
* **Joining another server:** the welcome screen offers hosting or joining. Joining uses a separate player profile in
the Manager's `remote-client/connection.json`, storing the host address and client folder without a server registry entry,
installation metadata, database or server processes. Only Overview and application Settings appear in the sidebar.
Downloading, adopting and updating clients use the same verified downloader; Play applies the saved realmlist without
forcing a local realm selection. The player can return to hosting without removing their saved connection.
* **Open points:** ask the launcher maintainers before putting heavy load on their API; DBCs live inside the MPQ patch archives
(extracting them would need an MPQ reader), so the server's `Data\dbc` still comes from our `base` package for now.
+5 -4
View File
@@ -6,7 +6,7 @@ type into the game.
Code: `crates/coa-control-proto` (the protocol: pure, no I/O), `services/coa-coordinator` (the Coordinator), `crates/coa-core/src/control` (Host and Player sides),
`src-tauri/src/control_cmds.rs` and `src/screens/JoinPanel.tsx` (the interface). End-to-end tests: `services/coa-control-e2e`. Deployment: [REGISTRY_DEPLOYMENT.md](REGISTRY_DEPLOYMENT.md).
`CONTROL_PROTOCOL_VERSION = 1`; it is independent of the Registry protocol (2) and of the portable formats.
`CONTROL_PROTOCOL_VERSION = 2` (bumped in MR1.1/MR2 to require explicit `ruleset` fields in transfer and claim negotiations); it is independent of the Registry protocol (2) and of the portable formats.
## 1. Shape
@@ -148,8 +148,8 @@ its profile, and only then sends `claim_ack`; the Host marks the binding `Portab
When a player selects a portable character that exists in their Player Manager but does not yet exist on the remote realm, the Player Manager performs an automated, transactional transfer over the encrypted Noise channel:
1. **Preflight Compatibility Check**: The Player Manager checks the canonical character against the target realm's advertised capabilities (Phase 7/8). If incompatible, the transfer is refused immediately before any network mutation.
2. **Transfer Offer (`TransferOffer`)**: Inside the end-to-end encrypted Noise channel, the Player Manager sends `transfer_offer{transfer_id, character_id, canonical_revision, content_hash, total_size, collections}`.
- The Host validates the PlayerIdentity, character ownership, format revision, hash format, size limit (≤ 4 MiB, `MAX_TRANSFER_REQUEST_BYTES`), and collection counts (≤ 100,000 items).
2. **Transfer Offer (`TransferOffer`)**: Inside the end-to-end encrypted Noise channel, the Player Manager sends `transfer_offer{transfer_id, character_id, canonical_revision, content_hash, total_size, collections, ruleset}`.
- The Host validates the PlayerIdentity, character ownership, format revision, hash format, size limit (≤ 4 MiB, `MAX_TRANSFER_REQUEST_BYTES`), collection counts (≤ 100,000 items), and ruleset matching target realm.
- If the exact revision was already committed or an active transfer session exists, the Host responds with `transfer_ready{transfer_id, accepted_offset}`.
3. **Payload Transfer & Chunking (`TransferChunk` / `TransferStatus`)**:
- The Player sends the payload in bounded chunks via `transfer_chunk{transfer_id, offset, data}`.
@@ -157,7 +157,8 @@ When a player selects a portable character that exists in their Player Manager b
- If a connection is interrupted, the Player can query progress via `transfer_status{transfer_id}` and resume from `accepted_offset`.
4. **Validation & Atomic Commit (`TransferCommit`)**:
- Once all chunks arrive, the Player sends `transfer_commit{transfer_id}`.
- The Host verifies the SHA-256 content hash of the assembled payload against the offer.
- The Host verifies the SHA-256 content hash of the canonical JSON against the offer.
- The Host decodes the payload and verifies that `decoded.character_id == transfer.character_id`, `decoded.ruleset == transfer.ruleset`, and `transfer.ruleset == destination_realm.ruleset`.
- The Host runs the level projection engine (e.g. projecting level 80 down to realm cap 60 via Phase-8 oracle).
- The Host imports the character into the realm's characters database, updates/creates the working copy mapping, and arms the session.
- The Host returns `transferred{character_id, local_guid, session_id}`.
-4
View File
@@ -2,8 +2,6 @@
**Portable characters are experimental.** The feature is in active development and may contain bugs.
Draft for owner review — Manager 0.7.0 preview.
## Set up your server
1. Choose **Host a server** on the welcome screen.
@@ -26,5 +24,3 @@ Open **Play with friends**. Use the LAN/private-network instructions for your co
A listing makes your server discoverable; it does not move hosting to the cloud or guarantee that your network can be reached. If joining fails, use the connection checks before changing router settings. Portable characters also require a compatible server build and its required settings.
Use **Backups** before changing server versions or optional modules. To stop accepting visitors, turn off the listing; to stop hosting, stop the server.
Screenshots, exact menu locations and public-service availability will be checked before publication.
+153
View File
@@ -0,0 +1,153 @@
# Multi-Ruleset Realms & Portable Characters: Architectural Audit
This audit evaluates the 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: Updated for MR2 Gate (Wildcard Vertical Slice Completed)
---
## 1. Executive Summary: Baseline vs Implemented vs Planned
### 1.1 Baseline Discovered Before Implementation (v0.7.0 Master)
- `realms::Mode` defined `Coa`, `Wildcard`, and `Reborn` for local realm profiles and database switching (`acore_characters`, `acore_characters_wildcard`, `acore_characters_reborn`).
- 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"*).
- SQLite `character` table had `CHECK (ruleset IN ('coa', 'wildcard'))`, which hard-failed on any `reborn` row.
- SQLite `collection` table was keyed by `(profile_id, kind)` without `ruleset`, causing cross-ruleset collision.
- `Request::TransferOffer`, `PortableSessionStarted`, `PortableCheckpoint`, `OwnerAck`, `CollectionObserved`, `CollectionState`, and `CollectionAck` lacked explicit protocol-level `ruleset` fields or version negotiation.
- Collection validation used unsafe prefix checks (`kind.starts_with(ruleset)`), permitting prefix confusion attacks.
- `Ruleset::schema(kind)` contained a fallback `_ => "acore_characters"`, routing unknown database kinds to CoA.
### 1.2 Implemented in MR1, MR1.1, and MR2
- **Authoritative Ruleset Enum:** `Ruleset` (`Coa`, `Wildcard`, `Reborn`) unified across `coa-core`, `coa-registry-proto`, `coa-control-proto`, and frontend models.
- **Transactional SQLite Migration 009:** Migrates released v0.7.x databases by recreating both `collection` (composite key `profile_id, ruleset, kind`) and `character` (CHECK constraint allowing `'coa', 'wildcard', 'reborn'`) with FK toggles ensuring zero child row loss.
- **Fail-Closed Realm Backend:** Removed unsafe `unwrap_or(Ruleset::Coa)` in `LocalBackend::info()`. Unreadable, unknown, or broken realms fail closed immediately with error rather than falling back to CoA.
- **Control Protocol 2 & Strict Envelopes:**
- `CONTROL_PROTOCOL_VERSION = 2`.
- `Request::TransferOffer` requires explicit `ruleset: String`.
- `Response::Claimed` returns explicit `ruleset: String`.
- Claiming and commit verify that the claimed envelope ruleset matches the decoded payload ruleset and matches target realm ruleset.
- `HostTransfer` stores `ruleset` in SQLite; `transfer_commit` verifies that canonical JSON hash and ruleset match the offer and destination realm before writing to disk.
- **Session Protocol 3 & Ruleset Enforcement:**
- `SESSION_PROTOCOL_VERSION = 3` and `COLLECTION_PROTOCOL_VERSION = 2`.
- `SessionOffer`, `PortableSessionStarted`, `PortableCheckpoint`, and `OwnerAck` require explicit `ruleset`.
- Any mismatch between character ruleset, offer ruleset, session ruleset, or checkpoint ruleset rejects immediately with zero DB mutation and zero canonical revision advance.
- **Wildcard Collections Isolation:**
- `wildcard:appearance` and `wildcard:vanity` isolated from `coa:appearance` and `coa:vanity`.
- Cross-ruleset collection merges strictly rejected by `carried_kind_for(kind, ruleset)`.
- **Database Routing & Three-Space Isolation:**
- Canonical SQL routes through `Db::query()` and `realm_schema` to `acore_characters_wildcard` and `acore_world_wildcard`.
- Multiple characters sharing local GUIDs on distinct server IDs (`srv-1:coa`, `srv-1:wildcard`, `srv-1:reborn`) coexist with zero collision in character mappings and item mappings.
- Mutating Wildcard character state, revisions, or collections leaves CoA and Reborn states 100% byte-for-byte untouched.
- **Direct & Relay Routing for Wildcard:**
- `world_port_for_mode` dynamically determines active world port (8085 for primary CoA, 8086 for secondary Wildcard in simultaneous mode).
- Direct Ingress proxy and Relay link dynamically route to the correct realm world port.
- Direct Ingress Auth rewrite replaces internal realm list address with external mapped Wildcard port (e.g. 48086) and never advertises CoA port 8085.
### 1.3 Still Planned (Subsequent Milestones)
- **MR3 (Warcraft Reborn Vertical Slice):** Unlocking `ruleset_of` for Reborn, import/export adapters, and live verification.
- **MR4 (Multi-Realm Publication UI & Registry):** Simultaneous publication of multiple RealmIds from a single Manager host under distinct identities and keypairs.
---
## 2. Current Implementation Architecture & Historical Baseline Inventory
### 2.1 Current Implementation State (As of MR1, MR1.1, MR2, MR2.1)
- **Authoritative Ruleset Representation:**
- `crates/coa-core/src/portable/model.rs`: `enum Ruleset { Coa, Wildcard, Reborn }` (strict parsing and schema routing without fallbacks).
- `crates/coa-registry-proto/src/caps.rs`: `enum Ruleset { Coa, Wildcard, Reborn }`.
- `services/coa-registry/src/pg.rs`: `ruleset: match ruleset.as_str() { "coa" => Ruleset::Coa, "wildcard" => Ruleset::Wildcard, "reborn" => Ruleset::Reborn, ... }`.
- `src/lib/browse.ts`: `export type Ruleset = "coa" | "wildcard" | "reborn";`.
- `crates/coa-core/src/realms.rs`: `enum Mode { Coa, Wildcard, Reborn }`.
- **Wire Protocols & Ruleset Requirements:**
- **Control Protocol 2:** `CONTROL_PROTOCOL_VERSION = 2`. `Request::TransferOffer` requires explicit, non-default `ruleset: String`. `Response::Claimed` returns explicit `ruleset: String`. `HostTransfer` records ruleset.
- **Session Protocol 3:** `SESSION_PROTOCOL_VERSION = 3`. `SessionOffer`, `PortableSessionStarted`, `PortableCheckpoint`, and `OwnerAck` require explicit, mandatory `ruleset: Ruleset`.
- **Collection Protocol 2:** `COLLECTION_PROTOCOL_VERSION = 2`. `CollectionObserved`, `CollectionState`, and `CollectionAck` require explicit, mandatory `ruleset: Ruleset`.
- **Database Routing & Fail-Closed Invariants:**
- `LocalBackend::info()` and `LocalBackend::access()` strictly enforce:
$$\text{local\_id ruleset} == \text{RealmAccess.mode} == \text{Db.realm()} == \text{RealmInfo.ruleset}$$
Any mismatch or malformed/unknown ruleset suffix returns an immediate error.
- `LocalBackend::world_port()` and `crates/coa-core/src/realms::world_port_for_mode()` return fallible `Result<u16>` without silent fallbacks to 8085. If a realm is not running or not simultaneous, port resolution fails closed and disables Direct and Relay routing for that realm.
- **Canonical Storage (`portable.db`):**
- Transactional SQLite Migration 009 upgraded `character` table constraint to `CHECK (ruleset IN ('coa', 'wildcard', 'reborn'))` while preserving rows byte-for-byte.
- `collection` table is partitioned by `(profile_id, ruleset, kind)`.
- Mappings (`character_server_mapping`, `item_mapping`, `pet_mapping`, sessions) isolate distinct server IDs (`srv-X:coa`, `srv-X:wildcard`, `srv-X:reborn`).
### 2.2 Historical Baseline Inventory (Pre-Implementation State as of v0.7.0 Master)
> [!NOTE]
> The following findings reflect the legacy v0.7.0 baseline discovered before MR1/MR2 implementation and are preserved for historical reference:
- *Historical:* `Ruleset` enum in `model.rs` and `caps.rs` lacked `Reborn`.
- *Historical:* `character` table had `CHECK (ruleset IN ('coa', 'wildcard'))`, causing SQLite constraint failures on Reborn.
- *Historical:* `collection` table was keyed only by `(profile_id, kind)` without `ruleset`.
- *Historical:* `TransferOffer`, `PortableSessionStarted`, `PortableCheckpoint`, and `CollectionState` lacked explicit protocol-level `ruleset` fields.
- *Historical:* `LocalBackend::info()` had an unsafe fallback `ruleset_of(db).unwrap_or(Ruleset::Coa)`.
- *Historical:* `world_port_for_mode()` fell back to `ports.world` (8085) even when Wildcard was inactive.
- *Historical:* `Ruleset::schema(kind)` had `_ => "acore_characters"`.
### 2.3 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.4 Public Registry Model & Multi-Realm Publication
- `crates/coa-core/src/realm_registry/settings.rs`: `RegistrySettings.realms` is a `BTreeMap<String, PublishConfig>`.
- `src/screens/PublishCard.tsx`: Uses `localId = 'srv-' + serverId`.
- **Multi-Realm Publication on One Host:**
Each published realm possesses its own distinct local realm identity (`srv-<id>:<ruleset>`), unique `RealmId` (UUIDv7), and independent Ed25519 signing key in `KeyStore`. Direct Ingress proxy and Relay links dynamically route to the respective realm's active world port.
---
## 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-<serverId>:<ruleset>`.
- 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.
+9 -4
View File
@@ -2,9 +2,16 @@
**Portable characters are experimental.** The feature is in active development and may contain bugs.
Draft for owner review — Manager 0.7.0 preview.
Portable characters let you keep a saved character in the Manager and play it on compatible realms (Conquest of Azeroth and Wildcard).
Portable characters let you keep a saved character in the Manager and play it on compatible CoA realms.
## Multi-Ruleset Isolation Invariant
Portable characters are strictly isolated by gameplay ruleset (`coa`, `wildcard`, `reborn`):
- A character created or claimed on a **Conquest of Azeroth** realm is a CoA character and can only ever be played on CoA realms.
- A character created or claimed on a **Wildcard** realm is a Wildcard character and can only ever be played on Wildcard realms.
- A character created or claimed on a **Warcraft Reborn** realm can only ever be played on Reborn realms.
Cross-ruleset transfers, imports, joins, sessions, and collection merges are impossible: the Manager strictly rejects any mismatched request at every protocol, session, and database boundary with zero mutation to your characters or servers.
## Make your first character portable
@@ -43,5 +50,3 @@ A realm with a lower level cap may play your character at a lower level. Check t
## Saved versions and conflicts
Use **Saved versions** to see when progress was saved. If the Manager reports a conflict, follow its explanation before continuing. Avoid playing two copies at once, and keep normal server backups as well.
Screenshots and exact wording will be reviewed before publication. Cross-server live play has not been re-qualified by this branch sync alone.
+7 -5
View File
@@ -77,7 +77,8 @@ one place, no duplicate ids). Extension payloads must match their recorded hash.
* `rollback_to` creates a **new** revision whose state equals an old one; revision numbers never decrease.
* The newest `history_keep` revisions are kept (default 20, 1..=1000, configurable). The current revision is never
pruned.
* A character's `ruleset` (`coa` | `wildcard`) can never change.
* A character's `ruleset` (`coa` | `wildcard` | `reborn`) can never change.
* The character's `content_namespace` aligns strictly with `ruleset` (`coa`, `wildcard`, or `reborn`).
## Extensions
@@ -87,8 +88,9 @@ that does not support an extension simply does not receive it; the canonical cop
## Collections
Account-wide sets of numeric ids (`coa:wardrobe`, `coa:vanity`, ...), stored per profile and kind:
Account-wide sets of numeric ids (`coa:appearance`, `wildcard:appearance`, `reborn:appearance`, etc.), stored per `(profile_id, ruleset, kind)`:
* partitioned strictly by ruleset: collections of different rulesets never intersect or merge;
* union only: `stored = stored U incoming`; nothing is ever removed because a realm did not return it;
* if the union equals what is stored, **no revision is created** and the hash is unchanged;
* encoding: `[format version][count][first id][gap]...`, unsigned LEB128 varints, strictly ascending ids, 1-2 bytes per
@@ -98,17 +100,17 @@ Account-wide sets of numeric ids (`coa:wardrobe`, `coa:vanity`, ...), stored per
## Store (`%LOCALAPPDATA%\CoAServerManager\portable\portable.db`)
SQLite, WAL, `synchronous=FULL`, `foreign_keys=ON`, `application_id = 0x434F4150`, forward-only migrations tracked in
`PRAGMA user_version` (currently 3). A database from a newer Manager, or a foreign SQLite file, is refused and left untouched.
`PRAGMA user_version` (migration 009 adds multi-ruleset collection partitioning and reborn character support). A database from a newer Manager, or a foreign SQLite file, is refused and left untouched.
| Table | Purpose |
|---|---|
| `profile` | the owner |
| `character` | summary row + canonical revision |
| `character` | summary row + canonical revision (`ruleset IN ('coa', 'wildcard', 'reborn')`) |
| `snapshot` | `(character_id, revision)` -> compressed canonical payload + hash |
| `character_server_mapping` | `(character_id, server_id)` -> local guid; `UNIQUE(server_id, local_guid)` |
| `item_mapping` | one row per mapping with a lifecycle (schema 2, see below) |
| `import_journal` | schema 3: one row per import into a realm (`prepared` / `committed` / `aborted` / `needs_attention`) with the nonce/marker and the plan; see `PORTABLE_IMPORT.md` |
| `collection` | per profile and kind: revision, hash, encoded set |
| `collection` | per profile, ruleset, and kind: revision, hash, encoded set |
| `setting` | `history_keep` |
## Item mapping lifecycle (schema 2)
+11 -9
View File
@@ -1,7 +1,7 @@
# Runtime portable sessions (Phase 5): design and audit
Code: core `src/server/coa/CoAPortableSession*.{h,cpp}` and `CoAPortableImport*.{h,cpp}` (branch `feat/portable-session-bridge` of the
core fork), Manager `crates/coa-core/src/portable/session/`. CoA only; Wildcard portable transfer stays disabled.
core fork), Manager `crates/coa-core/src/portable/session/`. Supports Conquest of Azeroth and Wildcard (MR2) with strict multi-ruleset isolation.
Phase 4 proved the offline model with a real client. Its one fragile rule is that the baseline `B0` must be captured *after*
the realm's own normalisation and *before* the character is played. Phase 5 makes that rule a property of the running
@@ -130,16 +130,18 @@ Messages wait in the outbox until acknowledged; redelivery is harmless (section
## 5. Messages (transport-neutral, versioned, JSON)
`protocol_version = 1`; each message is canonical JSON with unknown fields refused. Snapshots travel in the existing
snapshot envelope (zstd of canonical JSON, SHA-256 of the canonical JSON).
`protocol_version = 3` (Session Protocol Version 3; Collection Protocol Version 2); each message is canonical JSON with unknown fields refused. Snapshots travel in the existing
snapshot envelope (zstd of canonical JSON, SHA-256 of the canonical JSON). Every session message carries an explicit `ruleset` (`coa`, `wildcard`, or `reborn`):
```text
PortableSessionStarted { protocol_version, session_id, character_id, server_id, base_canonical_revision,
baseline_generation, b0: envelope, content_hash }
PortableCheckpoint { protocol_version, session_id, character_id, server_id, base_canonical_revision,
sequence, final_checkpoint, realm_snapshot: envelope, content_hash }
OwnerAck { protocol_version, session_id, sequence, outcome, canonical_revision, canonical_hash,
[final: canonical snapshot envelope] }
SessionOffer { protocol_version, ruleset, session_id, character_id, server_id,
canonical_revision, snapshot: envelope }
PortableSessionStarted { protocol_version, ruleset, session_id, character_id, server_id, base_canonical_revision,
baseline_generation, b0: envelope, content_hash, progression }
PortableCheckpoint { protocol_version, ruleset, session_id, character_id, server_id, base_canonical_revision,
sequence, final_checkpoint, realm_snapshot: envelope, content_hash, pin }
OwnerAck { protocol_version, ruleset, session_id, sequence, outcome, canonical_revision, canonical_hash,
owned_items, owned_pets, [final: canonical snapshot envelope], next_session, pin }
```
`outcome` is `applied`, `duplicate` (same sequence and hash, already applied), `stale_sequence`, `stale_session`
+12
View File
@@ -0,0 +1,12 @@
# Guides and screenshots
- [Screenshot gallery](SCREENSHOTS.md) — explore the interface and its main features.
- [Host your own server](HOST-A-SERVER.md) — install a server, invite friends and publish a realm listing.
- [Portable characters · Experimental](PORTABLE-CHARACTERS.md) — save an existing character and use compatible realms.
- [Wildcard](WILDCARD.md) — switch realm profiles and manage separate characters.
- [Warcraft Reborn](WARCRAFT-REBORN.md) — create and switch to a Warcraft Reborn realm.
- [Updates, backups and repair](REPAIR_AND_REALMS.md) — keep your server updated and recover from problems.
**Portable characters are experimental.** The Manager is in active development and bugs may still occur. Please [report problems](https://github.com/Corfirean/coa-server-manager/issues/new/choose).
[Download the Manager](https://github.com/Corfirean/coa-server-manager/releases/latest) · [Manager changelog](../CHANGELOG.md) · [Server changelog](https://github.com/Corfirean/coa-server-build/blob/main/CHANGELOG.md)
+84
View File
@@ -0,0 +1,84 @@
# Warcraft Reborn Portable Characters Audit & Semantic State
## 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."`).
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())),
```
## 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:*`).
## 3. Actual Reborn Semantic-State Audit
### 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.2 Table & State Classification Matrix
| 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**.
+17 -30
View File
@@ -1,44 +1,31 @@
# Database checks, repair and simultaneous worlds
# Updates, backups and repair
Settings includes **Check files and database**, **Repair**, and **Start CoA and Wildcard together**.
## Update your server
Database checks inspect both realm schemas when Wildcard exists, the migration ledger, character-save columns and CoA starting class data. Results are saved in the installation metadata's `logs/database-checks.json` and included in exported diagnostics. Hash checks skip mutable MySQL data and configuration files.
Select your server in the Manager. When an update is available, choose **UPDATE** and follow the prompts. Keep the Manager open until it finishes: it stops the server, creates a recovery point and checks the updated server.
Repair requires both worlds and auth to be stopped, no unfinished update, and the installed version to match the currently published signed update. The signed base must match the installed base as well. It verifies packages before changing files, creates a full database/config backup, saves every replaced file and a recovery inventory under `<server>.manager/repairs/<backup-id>/`, then restores official files and applies pending migrations to both worlds. Settings and player databases are not replaced. A failure during file replacement restores the original files. Interrupted repair can be retried; its file inventory and backups remain available.
Updates preserve accounts, characters and settings and cover every realm you have created. If an update fails, read the displayed error before trying again; recovery information remains available in the Manager.
Repair reports unresolved schema damage. It does not guess ALTER statements or replay already applied SQL: those cases need a new corrective migration. Applied SQL whose recorded SHA-256 changed is reported and rejected. Manager failure records take precedence over the core's old `updates` entries.
## Keep a backup
## Release schema contracts
Use **Backups** to save characters, accounts and settings before important changes. Full backups also include world data. Check the realm recorded in a recovery point before restoring it, and stop the server before a restore.
`clean-base` clears the character migration ledger after rebuilding the character database and captures `Scripts/database-schema.json`. It contains expected table/column names and column types. Installation and migration validation inspect this contract; older packages receive the narrower character-save checks, clearly labelled in the UI.
Portable character saved versions do not replace server backups. **Portable characters are experimental.**
For each update, capture a fresh contract **from a disposable database already migrated to the exact packaged core**, into the release tree before `pack-update`:
## Check or repair an installation
```powershell
cargo run -p coa-release -- extract-schema-base --package C:\games\signed-base --fixture C:\games\coa-schema-fixture-build
cargo run -p coa-release -- schema-contract --repack C:\games\coa-schema-fixture-build --tree C:\games\release-tree --core C:\games\release-core --bots C:\games\release-bots --repairs C:\games\release-repairs
```
1. Stop the server.
2. Open **Settings** and run **Check files and database**.
3. Review the results. If official server files need restoring, use **Repair** and follow the prompts.
The first command verifies every entry in the signed base archive and extracts only the runtime needed for a disposable database. The second applies the release SQL with temporary ports, checks critical feature tables independently of migration history, and captures the resulting schema. It requires the disposable fixture marker and never starts a world server.
Repair creates a recovery backup and restores official files while preserving settings and player databases. It may require the installed version to match the currently published signed package. Missing player data requires a backup; some database problems require a corrective server update.
Base and update packaging require a complete contract for all three databases. Cumulative updates always carry it, even when unchanged. Signing and verification check the archive contents and contract before publication. Never capture it from a user's server or from an unmigrated previous release database.
If an operation stays blocked or fails again, use **Report a problem** and include diagnostics and the error message. Do not delete database files or recovery records to clear an error.
Corrective SQL under `repairs/{auth,characters,world}` receives new `manager_repair__` migration IDs and runs after historical SQL. Missing Wildcard tables can therefore be restored without replaying historical data deletion. Existing malformed tables still fail schema checks; creating a missing table does not recover its lost rows.
## Run CoA and Wildcard together
## Simultaneous worlds
In **Settings**, enable **Start CoA and Wildcard together**. Both realms share accounts but keep separate characters and world data. Both statuses appear on Overview, and Stop shuts down both.
On Windows the checkbox creates Wildcard when needed and saves distinct secondary world/RA ports. Both worlds start with one shared authserver/MySQL and separate world/character databases. The second world has its own executable copy, config, supervisor, logs and report spool in `.realms/secondary`; Data is read through the primary installation's absolute path. This runtime folder is excluded from packages.
If friends networking was configured before enabling the second realm, run its setup again so both realms are reachable. Disable simultaneous startup before switching to Warcraft Reborn.
The selected realm remains the primary world used by the Manager's console, companions, settings and Play. Selecting another realm still stops/restarts both to preserve that relationship. CoA companion restrictions on Wildcard remain in force. Both world statuses are shown on Overview.
Stop shuts down the secondary supervisor/world before the primary launcher may stop the shared database. Database restores, updates and profile changes reject a running secondary world. Each start refreshes its executable/config copies, so server updates cannot leave an old secondary binary behind. The secondary world inherits the primary network bind setting; its RA console remains on loopback. Enabling friends networking opens/maps both world ports. If networking was enabled before the second realm, enable it again to add the second port's rule/mapping.
## Disposable probes
```powershell
cargo run -p coa-core --example multiworld_e2e -- C:\games\your-fixture
cargo run -p coa-core --example repair_e2e -- C:\games\your-fixture
cargo run -p coa-core --example schema_e2e -- C:\games\your-fixture
```
The first checks both processes, ports, shared services and graceful shutdown. The second uses a test-only signing key, corrupts a fixture file, applies SQL to both worlds, verifies backups and account/character counts, and drops a column only in Wildcard to prove schema checks are isolated. These probes modify the fixture; never use a real server.
[All guides](README.md)
-111
View File
@@ -1,111 +0,0 @@
# Stabilization evidence — 14 October 2026
This batch starts from Manager master b45e250 (published version 0.6.16).
Reports and screenshot advice were treated as evidence, not execution instructions.
## Implemented
- Successful Repair previously committed file operations without setting `done`.
The next journal scan rejected its own completed transaction. A regression failed
on the original code with `Update journal contains inconsistent file operations`.
Repair now verifies target hashes and records completion before committing.
- Legacy completed repair journals are recognized only for the specific repair
shape, matching installation metadata and verified target hashes. Their original
journal is retained before atomically persisting completion. Interrupted,
mismatched, duplicate-path and other invalid journals continue to block actions.
Later legitimate updates do not invalidate the corrected historical record.
- Database Check and the final Repair report now include SQUID pending import
markers in characters, world and shared playerbots databases, plus missing
required character tables when SQUID is enabled. These are read-only checks;
partial imports are never cleared, dropped or automatically replayed.
- Private rehearsal reports file preparation/copy counts and database/startup
stages. Shutdown failure includes the installation path, service states, PID,
ports and redacted launcher output. Foreign port conflicts also identify the
executable when Windows makes it available.
## Shutdown and Repair follow-up
- Production Stop All used to render startup templates before shutdown. Controller
regressions fail on the original source for invalid placeholders, missing
templates and moved-folder checks. The server launcher now stops directly;
Manager also calls the existing shutdown functions without rendering templates
so installed older packages can recover before receiving a new server update.
- Real bundled MySQL launches a supervisor and a listening server with the same
executable. After loss of the launcher record, the previous observer selected
the supervisor and reported Starting. Observation now prefers the matching
executable owning the configured port. Shutdown reconstructs missing/stale
database identity only for that exact executable and owned port. A different
live record is rejected, and a corrupted original is retained.
- Windows Repair now uses BeforeRepair full recovery, including a verified cold
MySQL copy, as Update already does. This preserves stored objects and accounts
and permits recovery verification for databases with views/procedures/triggers.
- Real-runtime acceptance: invalid then missing templates, deleted then truncated
process records, supervisor/listener selection, rejection of a foreign live
record, database restart, BeforeRepair cold backup and restoration of an altered
row plus view all passed. Replaced database files remain available for recovery.
## Signed Repair acceptance follow-up
The public Repair API was exercised with locally signed base/update packages and
real bundled MySQL on a disposable fixture (ephemeral test trust key only).
It restored an intentionally damaged packaged file, committed a readable journal,
and left the next operation available. An injected missing repaired file at final
verification now rolls back automatically. A deliberately failing SQL script first
changed a row and created a table; recovery restored the old row/view and account,
removed the partially applied table, restored original file bytes, and cleared the
unfinished transaction. This full acceptance passed in 142.92 seconds.
Other post-snapshot failures now use the same rollback path. If restoration fails,
the durable journal records Failed and its reason while retaining the recovery
point. Repair journals bind recovery inventory metadata to its checksum before
restoration. Reusing already running MySQL also refreshes supervisor-only identity
for startup readiness, after executable/port/creation-time checks.
These are package/SQL/recovery tests on representative minimal database tables;
they do not claim successful client login, combat or an affected user's installation.
## Overview update failure at 2%
The additional screenshot reports a failed StopAll inside a private rehearsal,
with the launcher's moved-folder/changed-port guard, followed by a disappearing
progress bar on Overview. The shutdown adapter already bypasses startup preparation.
The native recovery test now also supplies a copied configuration signature with
an old installation path, verifies shutdown preserves it, and retains its database
row/view recovery assertions.
Overview previously rendered only its local start/stop failure, ignoring stored
update and recovery-state errors. It now displays those errors with the existing
technical-details and copy controls, even when the update offer and progress bar
are gone. A new update attempt clears an older local action error. Render tests
reproduced the missing alerts before the fix; all 12 frontend tests pass afterward.
## Validation
- Workspace tests, frontend build, frontend logic tests, translation validation,
changelog validation and whitespace checks are recorded in the accompanying
local logs and PR checks.
- Real bundled MySQL regression validates restored rows, users, procedures,
functions, views and triggers, and preservation of custom defaults. It also
confirms SQUID pending imports are reported without modifying their records.
- Published Content Scaling revision e5d8c675 passes the production-budget
regression for 40/100 HP, core multipliers, rank rates, groups and repeated
calculation. This is a code regression, not an in-game Wildcard/PTR comparison.
## Outstanding evidence and release gates
| Report | Current evidence | Next verification |
| --- | --- | --- |
| Manager #98 | Repair journal defect reproduced; report itself has no diagnostic ZIP | Reproduce the complete Custom Races workflow and verify existing affected journal recovery |
| Screenshot: SQUID Start fails but Repair reports zero | Separate SQUID ledger was absent from Repair checks | Retest with a copy of the affected database; recover from a verified pre-import backup |
| Manager #82 / screenshot lock messages | #90 and #91 are already in published 0.6.16; lock regressions pass | Distinguish an active slow check from abandoned maintenance using diagnostics |
| Manager #100 / 54% | Attached archive ends immediately after entering private rehearsal; no failure is captured | Measure the full private-copy run on the affected hardware; new progress identifies its stage |
| Screenshot: stopped-MySQL error | Broken-template shutdown and lost-record/supervisor failures reproduced and fixed on disposable real MySQL | Verify the affected installation has one of these causes; other failures remain diagnostic-specific |
| Manager #25 | Missing defaults have targeted repair; start-data incompatibilities remain separate | Retest imported schema and affected race/class data without suppressing incompatibility checks |
| Manager #54 | Schedule fix is published; Stop now tolerates broken templates and Repair has complete MySQL recovery | Verify the exact unresolved placeholder and original recovery transaction; automatic placeholder guesses are not introduced |
| Scaling screenshot | 2.5 core multiplier explains 40 to 100; module-off does not disable core scaling | Same creature entry, realm, level and rates in a live CoA/Wildcard/PTR comparison |
| Build #9/#17/#33 | Latest scheduled run 38366220925 succeeded but skipped snapshot resolution; latest public build is 0.261013.54 | Qualify a new integrated candidate; old issue state is not current release evidence |
This batch does not publish a Manager installer, promote a server package,
close user reports or claim the complete fresh-install/update/gameplay matrix.
Clean Windows installs now select the full image attached to the same signed stable release used by updates. They never fall back to the legacy base when the current full image is absent. Explicit offline/custom full packages remain supported, while Repair and release upgrade fixtures retain the legacy base source. The release worker composes and validates the complete current database image before publication; users do not run an intermediate base server or an update transaction.
-36
View File
@@ -1,36 +0,0 @@
# Translations
The Manager interface exists in English (source), Russian, German, French and Spanish. Everything except English is a
**draft written by an AI assistant and needs review by a native speaker** before it is treated as final.
## Where the texts are
| What | File | Notes |
|---|---|---|
| Interface texts | `src/i18n/locales/<lang>.ts` | flat `"key": "text"` lists; `en.ts` is the source of truth, other languages fall back to it |
| Setting titles, descriptions, categories, presets, units, option labels | `src/i18n/schema/<lang>.json` | generated once from `schemas/*.json`; edit the JSON directly |
| Backend error messages | keys `err.<code>.title` / `err.<code>.message` in the locale files | codes come from `crates/coa-core/src/error.rs` |
`{name}` placeholders must stay exactly as they are. Plural forms use the suffixes `_one`, `_few`, `_many`, `_other`
(the browser picks the right one for the language).
## Checking your work
```
node tools/check-i18n.mjs # unknown keys, changed placeholders, coverage, schema overlays complete
npx tsc --noEmit # types
npx vite # UI with mock data in a browser; pick the language on the welcome screen
```
## Adding a language
1. Copy `src/i18n/locales/en.ts` to `<lang>.ts` (keep the keys), translate, and register it in `src/i18n/index.tsx`
(`Locale`, `LOCALES`, `DICTS`).
2. Copy `src/i18n/schema/ru.json` to `<lang>.json`, translate the values, and register it in `SCHEMA`.
3. Run the check above.
## Known gaps
* Free-form technical messages produced deep inside the backend (`Error::Invalid("...")`) stay in English; they are
shown as "technical details".
* Texts inside the game itself (client, server data) are not part of the Manager.
-19
View File
@@ -1,19 +0,0 @@
# Update workflow
The Manager selects the latest signed package directly for any known older server version. The source-version list records release qualification; it is not an exclusive allowlist and does not prove that a particular installed database can apply the package. Unknown imported versions, downgrades, incompatible platforms and newer Manager requirements remain blocked.
The updater verifies the signed manifest and archive, checks file changes and database history, stops the server, and saves one complete recovery point. It then replaces files, applies pending SQL once, verifies the target schema and starts the updated server once for validation. Shared authentication migrations run once; both realm histories are checked before changing either. Account and character identities are compared before and after migration and startup.
Account migration history is stored in the shared account database. Read-only checks recognize legacy auth records from both realms. Write operations adopt existing records and preserve already-applied core history; unknown legacy checksums stay unknown. History is read in two batched client calls, with explicit physical schemas and consistent text collations. Use the current Manager for subsequent database operations.
Applied migrations are skipped; changed checksums and interrupted/failed records stop the update. Duplicate SQL identifiers for the same schema are rejected before execution. SQL or startup failure restores files and databases together. If recovery fails, startup remains blocked and the recovery artifacts remain available.
The per-update nested server rehearsal and intermediate-package routing have been removed. Full-copy upgrade/startup testing belongs to release qualification, on independent disposable installations. Cleanup of interrupted rehearsals from older Manager versions remains for compatibility. Signed packages, recovery verification, configuration merge and startup validation stay enabled. No migration guard is bypassed and no unexecuted SQL is marked applied. Retired source archives do not prevent a direct update, but the database history must still be consistent and target checks must pass.
## Verify with an actual installation copy
`cargo run -p coa-core --example upgrade_fixture -- <copy-root> <signed-package-directory>` exercises the production updater, including recovery copies and startup. It refuses mutation unless the directory name starts with `coa-schema-fixture-real` and contains `.coa-update-fixture`. Prepare a disposable copy from a verified recovery point, with separate ports, metadata and no client path. Never point it at a working installation.
`migration_plan <copy-root> <signed-manifest>` reads database history without creating a migration ledger. On a separate marked `update-database-diagnosis-*` copy, `--apply <migration-directory>` exercises the production database phase. `--sql-only <migration-directory>` verifies and applies the signed SQL list for both realms and compares account/character identities. SQL-only success is not full package/startup qualification and does not verify the target schema contract.
Record package signatures, exact source recovery point, actual result, repeat-run behavior and unavailable stages. Do not label a route universally tested based on a version list or SQL-only success.
+5 -21
View File
@@ -5,28 +5,12 @@ installed worldserver must contain Warcraft Reborn support; an old build is
refused before any databases are created. Stop the client before switching to
have its saved realm updated immediately.
The profile uses `CoA.ClassModel = "wcr"`, game-mode mask `0`, live realm type,
and realm ID `3`. Accounts remain in the shared `acore_auth` database. World data
is initially copied from CoA into `acore_world_reborn`; the structure of
`acore_characters` is cloned into `acore_characters_reborn` without copying
players. Existing database names or realm ID 3 block creation.
Accounts are shared with your other local realms. Warcraft Reborn starts with separate characters; switching profiles does not copy existing characters or progress.
Settings are stored in `Settings/realm-profiles/reborn.json`. Creating a profile
from Wildcard uses the saved CoA settings as its base, preventing inheritance of
Wildcard gameplay flags. Both bot systems are disabled and cannot be enabled
through this profile; their class mechanics have not been validated. Other
optional modules are marked 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, updates and database checks include every created realm. Restore keeps
using the realm recorded in the recovery point. The Windows launcher is upgraded
from the Manager's previous two-realm patch and routes Warcraft Reborn to its
own databases. Docker uses the same realm schema mapping.
Backups and updates include every created realm. Check the realm recorded in a recovery point before restoring it.
Simultaneous startup continues to support CoA + Wildcard only. Disable that
option before switching to Warcraft Reborn; it cannot be enabled while Warcraft
Reborn is selected.
Simultaneous startup supports CoA + Wildcard only. Disable **Start CoA and Wildcard together** in Settings before switching to Warcraft Reborn.
Automated checks cover profile configuration and restoration, old state files,
binary support detection, database routing, all-realm enumeration, client realm
selection, and upgrading/reversing the launcher patch. These checks do not
constitute a gameplay validation of Warcraft Reborn or optional modules.
[All guides](README.md)
+20 -21
View File
@@ -4,10 +4,16 @@ Overview offers CoA and Wildcard. The installed worldserver must contain Wildcar
already have its Wildcard migrations. The Manager refuses an unsupported binary, an occupied realm ID 2 or an
existing destination database rather than overwrite them.
The first switch copies the CoA world into `acore_world_wildcard` and creates `acore_characters_wildcard` from
the character schema and neutral server seed tables. Existing characters, card collections and progress are not
copied. Accounts remain in shared `acore_auth`. Realm IDs 1 and 2 share the world port; only the selected world
runs, and the inactive realm is listed offline. A switch while running stops the server gracefully and restarts it.
CoA and Wildcard have separate character and world databases (`acore_characters` / `acore_world` for CoA, and
`acore_characters_wildcard` / `acore_world_wildcard` for Wildcard). Accounts remain in shared `acore_auth`.
When simultaneous realm execution is enabled in configuration (`simultaneous: true`), both CoA and Wildcard
realms can run concurrently:
- Primary and secondary world ports (`ports.world` and `secondary_world_port`, e.g. 8085 and 8086) and RA ports
are distinct.
- Remote routing (both Direct Ingress and Relay links) is strictly bound to the specific ruleset realm selected:
routing to a Wildcard realm targets the Wildcard world port and never advertises or connects to the CoA port.
- When simultaneous execution is disabled, only the currently active realm runs and provides world service.
Configuration profiles are saved under `Settings/realm-profiles`. An interrupted switch can restore its previous
configuration from the journal. CoA companion bots cannot be enabled on Wildcard. Content Scaling and the other
@@ -19,24 +25,17 @@ Recovery points identify their active realm; select that realm before restoring
both realms, with auth applied once. The server updater can replace its launcher: the Manager reapplies the realm
adapter before the next start.
## Portable Characters on Wildcard
As of v0.7.1, Wildcard realms participate in the Portable Characters subsystem with strict multi-ruleset isolation:
- **Canonical Model:** Wildcard portable characters carry `ruleset: "wildcard"` and `content_namespace: "wildcard"`.
- **Claim & Export:** Characters played on a Wildcard realm (`acore_characters_wildcard`) can be claimed and exported into canonical portable snapshots. Wildcard character builds—including spells, talents, skills, action bars, settings, inventory, pets, and currencies—are preserved.
- **Import & Session Runtime:** A Wildcard portable character can be transferred to a remote Wildcard host, imported into its `acore_characters_wildcard` database, armed in a runtime session (Session Protocol 3), and tracked through checkpoints and logout synchronization.
- **Collections:** Wildcard collections (`wildcard:appearance` and `wildcard:vanity`) are partitioned separately from CoA collections. Unlocks on a Wildcard realm union into the profile's Wildcard collections and never touch CoA collections.
- **Fail-Closed Protection:** Any attempt to transfer or import a CoA character into a Wildcard realm, or vice versa, is rejected at the protocol and database boundaries with zero mutation. If world-port resolution fails or a realm mode is inactive, Direct and Relay routing fail closed.
![Wildcard overview](screenshots/wildcard-demo/overview.jpg)
![Module compatibility](screenshots/wildcard-demo/modules.jpg)
## Validation for v0.5.0
- `cargo test --workspace`: 178 core tests passed; command layer and examples compiled.
- `npm run build`, translation key checks and changelog validation passed.
- Native disposable fixture on offset ports: fresh Wildcard creation and startup, CoA startup after switching back,
separate probe values and restored CoA configuration. A second fresh creation verified the arena-season seed fix.
- Full backup verified both worlds, both character databases, shared auth and configurations.
- Native migration probe applied once to each realm and once to auth; repeating it did nothing.
- Restoring Wildcard characters removed a fixture-only change and preserved the CoA probe value.
- Core gameplay wrapper: `VERIFY ALL: PASSED`, gameplay stage only, real clock. First login (7 assertions),
level rolls/reroll (31), skill card rolls (13), stat path (12). The level-roll and skill-card scenarios passed on isolated
reruns after failing in the shared batch; the wrapper records two batch-sensitive cases.
- Browser demo verified active profile, hidden Bots navigation and module compatibility labels. Screenshots show
mock IPC; native checks above exercised the actual backend and server.
The gameplay harness required fixture-only synchronization of already applied migration history by verified SQL
hashes and its normal Windows module config path. Owned server files and databases were not modified.
[All guides](README.md)
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "coa-server-manager",
"version": "0.7.0",
"version": "0.7.1",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "coa-server-manager",
"version": "0.7.0",
"version": "0.7.1",
"dependencies": {
"@tauri-apps/api": "^2.12.0",
"@tauri-apps/plugin-dialog": "^2.8.0",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "coa-server-manager",
"private": true,
"version": "0.7.0",
"version": "0.7.1",
"license": "AGPL-3.0-only",
"type": "module",
"scripts": {
+9 -1
View File
@@ -356,7 +356,7 @@ dependencies = [
[[package]]
name = "coa-core"
version = "0.6.7"
version = "0.7.1"
dependencies = [
"base64 0.22.1",
"chrono",
@@ -364,6 +364,7 @@ dependencies = [
"coa-registry-proto",
"dunce",
"ed25519-dalek",
"flate2",
"fs4",
"hex",
"if-addrs",
@@ -743,6 +744,7 @@ checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb"
dependencies = [
"crc32fast",
"miniz_oxide",
"zlib-rs",
]
[[package]]
@@ -3079,6 +3081,12 @@ dependencies = [
"zopfli",
]
[[package]]
name = "zlib-rs"
version = "0.6.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112"
[[package]]
name = "zmij"
version = "1.0.23"
+37 -20
View File
@@ -364,7 +364,6 @@ fn a_realms_key_is_pinned_at_the_first_visit() {
#[test]
fn remote_transfer_over_coordinator_channel_e2e() {
use std::collections::BTreeMap;
use sha2::{Digest, Sha256};
let env = Env::new(true);
let dir = tempfile::tempdir().unwrap();
let pc = player(dir.path(), Arc::new(MemoryStore::default()));
@@ -372,67 +371,85 @@ fn remote_transfer_over_coordinator_channel_e2e() {
pc.ensure_account(&mut ch, &env.realm, Some("Varian")).unwrap();
let cid = Uuid::now_v7();
let payload = b"SECRET_PORTABLE_CHARACTER_PAYLOAD_FOR_VARIAN".to_vec();
let hash: [u8; 32] = Sha256::digest(&payload).into();
let mut model = coa_core::portable::fixtures::geared_level_eighty();
model.character_id = coa_core::portable::CharacterId::from_uuid(cid).unwrap();
model.ruleset = coa_core::portable::Ruleset::Coa;
let enc = coa_core::portable::snapshot::encode(&model).unwrap();
let payload = enc.payload;
let hash = enc.content_hash;
let collections = BTreeMap::from([("coa:appearance".to_string(), vec![42, 99])]);
// Perform transfer
let outcome = pc.transfer_character(&mut ch, cid, 1, &payload, hash, collections.clone()).unwrap();
let outcome = pc.transfer_character(&mut ch, cid, "coa", 1, &payload, hash, collections.clone()).unwrap();
assert!(outcome.local_guid > 0);
assert_ne!(outcome.session_id, Uuid::nil());
// Verify tap saw nothing sensitive
assert!(!env.wire_contains("SECRET_PORTABLE_CHARACTER_PAYLOAD"), "payload was encrypted");
assert!(!env.wire_contains("Gravewalker"), "character name was encrypted");
assert!(!env.wire_contains("Varian"), "account name was encrypted");
// Idempotent retry with same payload discovers existing commit
let retry_outcome = pc.transfer_character(&mut ch, cid, 1, &payload, hash, collections.clone()).unwrap();
let retry_outcome = pc.transfer_character(&mut ch, cid, "coa", 1, &payload, hash, collections.clone()).unwrap();
assert_eq!(outcome.local_guid, retry_outcome.local_guid);
assert_eq!(outcome.session_id, retry_outcome.session_id);
// Update with revision 2 updates working copy without duplicate
let payload2 = b"SECRET_PORTABLE_CHARACTER_PAYLOAD_VARIAN_REV2".to_vec();
let hash2: [u8; 32] = Sha256::digest(&payload2).into();
let update_outcome = pc.transfer_character(&mut ch, cid, 2, &payload2, hash2, collections).unwrap();
model.progression.money += 1000;
let enc2 = coa_core::portable::snapshot::encode(&model).unwrap();
let payload2 = enc2.payload;
let hash2 = enc2.content_hash;
let update_outcome = pc.transfer_character(&mut ch, cid, "coa", 2, &payload2, hash2, collections).unwrap();
assert_eq!(outcome.local_guid, update_outcome.local_guid);
// Incompatible realm rejects
let incomp_id = Uuid::now_v7();
env.fake.incompatible.lock().unwrap().insert(incomp_id);
let err = pc.transfer_character(&mut ch, incomp_id, 1, b"any", [0u8; 32], BTreeMap::new()).unwrap_err();
let mut incomp_model = coa_core::portable::fixtures::geared_level_eighty();
incomp_model.character_id = coa_core::portable::CharacterId::from_uuid(incomp_id).unwrap();
incomp_model.ruleset = coa_core::portable::Ruleset::Coa;
let incomp_enc = coa_core::portable::snapshot::encode(&incomp_model).unwrap();
let err = pc.transfer_character(&mut ch, incomp_id, "coa", 1, &incomp_enc.payload, incomp_enc.content_hash, BTreeMap::new()).unwrap_err();
assert_eq!(err.code(), "incompatible");
}
#[test]
fn remote_transfer_worst_case_large_payload_near_limit() {
use std::collections::BTreeMap;
use sha2::{Digest, Sha256};
let env = Env::new(true);
let dir = tempfile::tempdir().unwrap();
let pc = player(dir.path(), Arc::new(MemoryStore::default()));
let mut ch = pc.connect(&env.target()).unwrap();
pc.ensure_account(&mut ch, &env.realm, Some("ThrallLarge")).unwrap();
// 1. Build a worst-case payload: 2.5 MiB of character state + 25,000 collection item IDs
let mut large_payload = vec![0x42u8; 2_500_000];
// Fill with pseudo-random printable bytes to prevent trivial compression artifacts
for (i, b) in large_payload.iter_mut().enumerate() {
*b = (32 + (i % 95)) as u8;
let cid = Uuid::now_v7();
let mut model = coa_core::portable::fixtures::geared_level_eighty();
model.character_id = coa_core::portable::CharacterId::from_uuid(cid).unwrap();
model.ruleset = coa_core::portable::Ruleset::Coa;
for ext_idx in 1..=3 {
let mut large_bytes = vec![0u8; 800_000];
for (i, b) in large_bytes.iter_mut().enumerate() {
*b = (32 + ((i + ext_idx) % 95)) as u8;
}
model.extensions.insert(
format!("test:payload{ext_idx}"),
coa_core::portable::model::Extension::new("1.0.0", 1, large_bytes),
);
}
let large_hash: [u8; 32] = Sha256::digest(&large_payload).into();
let enc = coa_core::portable::snapshot::encode(&model).unwrap();
let large_payload = enc.payload;
let large_hash = enc.content_hash;
let mut massive_collections = BTreeMap::new();
let ids: Vec<u32> = (1..=25_000).collect();
massive_collections.insert("coa:appearance".to_string(), ids);
let cid = Uuid::now_v7();
let outcome = pc.transfer_character(&mut ch, cid, 1, &large_payload, large_hash, massive_collections).unwrap();
let outcome = pc.transfer_character(&mut ch, cid, "coa", 1, &large_payload, large_hash, massive_collections).unwrap();
assert!(outcome.local_guid > 0);
assert_ne!(outcome.session_id, Uuid::nil());
// 2. Standard request exceeding 4096 bytes is rejected
let bloated_hello = coa_control_proto::app::Request::Hello {
protocol: 1,
protocol: coa_control_proto::CONTROL_PROTOCOL_VERSION,
client: "A".repeat(5000),
};
let encoded = serde_json::to_vec(&bloated_hello).unwrap();
@@ -223,13 +223,13 @@ fn gate_phase12_1_live_vps_remote_transfer() {
let collections = BTreeMap::from([("coa:appearance".to_string(), vec![101, 202])]);
// 1. Remote transfer over Coordinator WSS channel
let outcome = pc.transfer_character(&mut ch, cid, 1, &payload, hash, collections.clone()).expect("transfer_character");
let outcome = pc.transfer_character(&mut ch, cid, "coa", 1, &payload, hash, collections.clone()).expect("transfer_character");
assert!(outcome.local_guid > 0);
assert_ne!(outcome.session_id, Uuid::nil());
println!("GATE 12.1 PASS remote transfer succeeded over WSS: local_guid={}, session_id={}", outcome.local_guid, outcome.session_id);
// 2. Idempotent retry with same payload discovers existing commit
let retry_outcome = pc.transfer_character(&mut ch, cid, 1, &payload, hash, collections.clone()).expect("retry transfer");
let retry_outcome = pc.transfer_character(&mut ch, cid, "coa", 1, &payload, hash, collections.clone()).expect("retry transfer");
assert_eq!(outcome.local_guid, retry_outcome.local_guid, "idempotent retry must return existing guid");
assert_eq!(outcome.session_id, retry_outcome.session_id, "idempotent retry must return existing session");
println!("GATE 12.1 PASS idempotent retry returned existing commit without duplication");
@@ -237,14 +237,14 @@ fn gate_phase12_1_live_vps_remote_transfer() {
// 3. Update with newer revision 2 updates working copy without duplicating character
let payload2 = b"REMOTE_PORTABLE_CHARACTER_VARIAN_PAYLOAD_V2".to_vec();
let hash2: [u8; 32] = Sha256::digest(&payload2).into();
let update_outcome = pc.transfer_character(&mut ch, cid, 2, &payload2, hash2, collections).expect("update transfer");
let update_outcome = pc.transfer_character(&mut ch, cid, "coa", 2, &payload2, hash2, collections).expect("update transfer");
assert_eq!(outcome.local_guid, update_outcome.local_guid, "revision update must preserve guid");
println!("GATE 12.1 PASS revision 2 update succeeded without character duplication");
// 4. Incompatible realm rejects before mutation
let incomp_id = Uuid::now_v7();
fake.incompatible.lock().unwrap().insert(incomp_id);
let err = pc.transfer_character(&mut ch, incomp_id, 1, b"incomp", [0u8; 32], BTreeMap::new()).expect_err("should reject");
let err = pc.transfer_character(&mut ch, incomp_id, "coa", 1, b"incomp", [0u8; 32], BTreeMap::new()).expect_err("should reject");
assert_eq!(err.code(), "incompatible");
println!("GATE 12.1 PASS incompatible character rejected cleanly");
@@ -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'));
+3
View File
@@ -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<RealmRow> {
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<RealmSummary> {
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),
+35
View File
@@ -285,11 +285,23 @@ pub(crate) async fn join_realm(
let char_id_str = character.clone();
let bundle =
portable.call(move |s| s.export_for_remote_transfer(&char_id_str))??;
if bundle.ruleset.as_str() != detail.ruleset.as_str() {
ch.close();
return Err(fail(
"incompatible",
format!(
"Character ruleset ({}) does not match target realm ruleset ({})",
bundle.ruleset,
detail.ruleset.as_str()
),
));
}
let cuuid = bundle.character_id.as_uuid();
let _outcome = pc_bg
.transfer_character(
&mut ch,
cuuid,
bundle.ruleset.as_str(),
1,
&bundle.payload,
bundle.content_hash,
@@ -518,6 +530,10 @@ pub(crate) async fn join_claim(
.map(|c| c.token)
.unwrap_or(0);
let claimed = pc.claim(&mut ch, token).map_err(from_control)?;
let claimed_ruleset: coa_core::portable::Ruleset = claimed
.ruleset
.parse()
.map_err(|e| fail("incompatible", format!("Invalid ruleset: {e}")))?;
let server_id = format!("rr-{rid}");
let cid = coa_core::portable::ids::CharacterId::from_uuid(claimed.character_id)
.map_err(|e| fail("other", e.to_string()))?;
@@ -526,6 +542,25 @@ pub(crate) async fn join_claim(
claimed.sha256,
claimed.collections.clone(),
);
let decoded = coa_core::portable::snapshot::decode(&payload, Some(&hash))
.map_err(|e| fail("invalid", format!("Corrupt claim snapshot: {e}")))?;
if decoded.ruleset != claimed_ruleset {
return Err(fail(
"incompatible",
format!(
"Claimed ruleset mismatch: envelope={}, snapshot={}",
claimed.ruleset, decoded.ruleset
),
));
}
for kind in claimed.collections.keys() {
if !coa_core::portable::session::protocol::carried_kind_for(kind, claimed_ruleset) {
return Err(fail(
"incompatible",
format!("Foreign collection kind {kind:?} in {claimed_ruleset} claim"),
));
}
}
let view = portable
.call(move |s| s.adopt_claim(&server_id, cid, &payload, &hash, &collections))??;
pc.acknowledge(&mut ch, claimed.character_id, &rid, &view.name)
+1 -1
View File
@@ -1259,7 +1259,7 @@ async fn custom_races_install(
}),
);
})?;
let enabled = ctx.root.as_ref().map_or(true, |root| {
let enabled = ctx.root.as_ref().is_none_or(|root| {
coa_core::modules::list(root)
.iter()
.any(|module| module.id == "custom-races" && module.enabled)
+1 -1
View File
@@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "CoA Server Manager",
"version": "0.7.0",
"version": "0.7.1",
"identifier": "com.coa.servermanager",
"build": {
"beforeDevCommand": "npm run dev",
Loaded 100 of 113 files, more files were not shown because too many files have changed in this diff. Show more