From c39ff556a3cfe8cb6d7d7a7c08a7afc34611319f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=94=D0=BC=D0=B8=D1=82=D1=80=D0=B8=D0=B9?= Date: Wed, 30 Sep 2026 06:59:11 +0500 Subject: [PATCH] Phase 0/1a: architecture audit and coa-core foundation (fsx, registry, manifest, logging, errors) Co-Authored-By: Claude Sonnet 5.5 --- .gitignore | 6 + Cargo.lock | 747 ++++++++++++++++++++++++++++++++ Cargo.toml | 12 + crates/coa-core/Cargo.toml | 20 + crates/coa-core/src/error.rs | 136 ++++++ crates/coa-core/src/fsx.rs | 281 ++++++++++++ crates/coa-core/src/lib.rs | 9 + crates/coa-core/src/logging.rs | 126 ++++++ crates/coa-core/src/manifest.rs | 238 ++++++++++ crates/coa-core/src/registry.rs | 272 ++++++++++++ docs/ARCHITECTURE.md | 430 ++++++++++++++++++ 11 files changed, 2277 insertions(+) create mode 100644 .gitignore create mode 100644 Cargo.lock create mode 100644 Cargo.toml create mode 100644 crates/coa-core/Cargo.toml create mode 100644 crates/coa-core/src/error.rs create mode 100644 crates/coa-core/src/fsx.rs create mode 100644 crates/coa-core/src/lib.rs create mode 100644 crates/coa-core/src/logging.rs create mode 100644 crates/coa-core/src/manifest.rs create mode 100644 crates/coa-core/src/registry.rs create mode 100644 docs/ARCHITECTURE.md diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..42ca83f --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +/target +node_modules +dist +*.log +.env +src-tauri/gen diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..ff00b80 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,747 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "android_system_properties" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" +dependencies = [ + "libc", +] + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "cc" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f360145194ee8e21db5ee7f3fcd4fe52210864c75c985dae33218202c8bbe040" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "chrono" +version = "0.4.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" +dependencies = [ + "iana-time-zone", + "num-traits", + "serde", + "windows-link", +] + +[[package]] +name = "coa-core" +version = "0.1.0" +dependencies = [ + "chrono", + "dunce", + "fs4", + "hex", + "serde", + "serde_json", + "sha2", + "tempfile", + "thiserror", + "tracing", + "tracing-subscriber", + "uuid", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + +[[package]] +name = "dunce" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "find-msvc-tools" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aedcfb3409746eddb02b9e19ebda1c3394f759a152e48ee875a0844d1b955484" + +[[package]] +name = "fs4" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8640e34b88f7652208ce9e88b1a37a2ae95227d84abec377ccd3c5cfeb141ed4" +dependencies = [ + "rustix", + "windows-sys 0.59.0", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-task", + "pin-project-lite", + "slab", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi", +] + +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "iana-time-zone" +version = "0.1.65" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "log", + "wasm-bindgen", + "windows-core", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "js-sys" +version = "0.3.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7883d941dae510fb2d978fc3fe018c71c9e2892fd38854de3e8b92c2e5ad9cc5" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "lazy_static" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" + +[[package]] +name = "libc" +version = "0.2.189" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "log" +version = "0.4.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rustix" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "serde_json" +version = "1.0.151" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "sharded-slab" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" +dependencies = [ + "lazy_static", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8593e8e72159ed2257d083c7a454a85cbf854f37a0966d8d483aff8c8a3ebcee" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom", + "once_cell", + "rustix", + "windows-sys 0.61.2", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "thread_local" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", +] + +[[package]] +name = "tracing-subscriber" +version = "0.3.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319" +dependencies = [ + "sharded-slab", + "thread_local", + "tracing-core", +] + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicode-ident" +version = "1.0.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954" + +[[package]] +name = "uuid" +version = "1.26.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ef6dac1e96601b4fb3acccccff2139741fcb757cb9a36089bf5be91cfb285ce" +dependencies = [ + "getrandom", + "js-sys", + "serde_core", + "wasm-bindgen", +] + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "wasm-bindgen" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9bb54f33acc68fd454578d9820b0bde1a1a3d17aa17bb7b6595806d02886d409" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e29d0c35b16e224a7eeb5cd2d25e3e1968fbd65604117b44d3b789d00ee8535" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f501a8bc3719dba86ef8ae4728879c08001bea749eb1333ac5b91e040e2a6b7" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.6", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23f0c9c52aa7cd7d77769a4cfe2a9adb1b331f489a41d912ce14513d5ab995c6" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "windows-core" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-sys" +version = "0.59.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..d86cc97 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,12 @@ +[workspace] +resolver = "2" +members = ["crates/coa-core"] + +[workspace.package] +version = "0.1.0" +edition = "2021" +license = "GPL-3.0-only" + +[profile.release] +lto = "thin" +codegen-units = 4 diff --git a/crates/coa-core/Cargo.toml b/crates/coa-core/Cargo.toml new file mode 100644 index 0000000..54d3132 --- /dev/null +++ b/crates/coa-core/Cargo.toml @@ -0,0 +1,20 @@ +[package] +name = "coa-core" +version.workspace = true +edition.workspace = true + +[dependencies] +serde = { version = "1", features = ["derive"] } +serde_json = "1" +sha2 = "0.10" +hex = "0.4" +thiserror = "2" +uuid = { version = "1", features = ["v4", "serde"] } +chrono = { version = "0.4", default-features = false, features = ["clock", "serde", "std"] } +dunce = "1" +fs4 = "0.13" +tracing = "0.1" +tracing-subscriber = { version = "0.3", default-features = false, features = ["fmt", "std"] } + +[dev-dependencies] +tempfile = "3" diff --git a/crates/coa-core/src/error.rs b/crates/coa-core/src/error.rs new file mode 100644 index 0000000..b671e20 --- /dev/null +++ b/crates/coa-core/src/error.rs @@ -0,0 +1,136 @@ +use serde::Serialize; + +pub type Result = std::result::Result; + +#[derive(Debug, thiserror::Error)] +pub enum Error { + #[error("io: {0}")] + Io(#[from] std::io::Error), + #[error("json: {0}")] + Json(#[from] serde_json::Error), + #[error("path rejected: {0}")] + PathRejected(String), + #[error("not enough free space: need {needed} bytes, have {available}")] + InsufficientSpace { needed: u64, available: u64 }, + #[error("hash mismatch for {path}: expected {expected}, got {actual}")] + HashMismatch { path: String, expected: String, actual: String }, + #[error("invalid manifest: {0}")] + InvalidManifest(String), + #[error("installation {0} is not registered")] + UnknownInstallation(String), + #[error("{0}")] + Invalid(String), +} + +/// Stable identifiers the UI maps to human messages. Raw exit codes never reach the user. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum ErrorCode { + DatabaseNotRunning, + PortInUse, + ServerFilesIncomplete, + WorldDbIncompatible, + WorldserverAlreadyRunning, + InvalidConfigValue, + DiskFull, + HashMismatch, + PathRejected, + Unknown, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum FixAction { + FixAutomatically, + OpenFolder, + ShowDetails, + ChooseAnotherFolder, + Retry, +} + +#[derive(Debug, Clone, Serialize)] +pub struct Human { + pub code: ErrorCode, + pub title: &'static str, + pub message: &'static str, + pub actions: &'static [FixAction], +} + +impl ErrorCode { + pub fn human(self) -> Human { + use FixAction::*; + let (title, message, actions): (&str, &str, &'static [FixAction]) = match self { + ErrorCode::DatabaseNotRunning => ( + "Database isn't running", + "The server needs its database to start. Start the database first.", + &[FixAutomatically, ShowDetails], + ), + ErrorCode::PortInUse => ( + "Server port is already in use", + "Another program (or another server) is using a port this server needs.", + &[ShowDetails], + ), + ErrorCode::ServerFilesIncomplete => ( + "Server files are incomplete", + "Some server files are missing or damaged.", + &[FixAutomatically, OpenFolder, ShowDetails], + ), + ErrorCode::WorldDbIncompatible => ( + "World database is incompatible with this build", + "A database update is required before this server version can start.", + &[FixAutomatically, ShowDetails], + ), + ErrorCode::WorldserverAlreadyRunning => ( + "Another worldserver process is already running", + "Stop the other server before starting this one.", + &[ShowDetails], + ), + ErrorCode::InvalidConfigValue => ( + "Your server configuration contains an invalid value", + "Fix the highlighted setting and save again.", + &[OpenFolder, ShowDetails], + ), + ErrorCode::DiskFull => ( + "Not enough free disk space", + "Free up some space or choose another drive, then try again.", + &[ChooseAnotherFolder, Retry], + ), + ErrorCode::HashMismatch => ( + "A downloaded file is damaged", + "The file did not match its checksum and was not used.", + &[Retry, ShowDetails], + ), + ErrorCode::PathRejected => ( + "That location is not allowed", + "The requested file location is outside the server folder.", + &[ShowDetails], + ), + ErrorCode::Unknown => ("Something went wrong", "See the technical details.", &[ShowDetails]), + }; + Human { code: self, title, message, actions } + } +} + +impl Error { + pub fn code(&self) -> ErrorCode { + match self { + Error::InsufficientSpace { .. } => ErrorCode::DiskFull, + Error::HashMismatch { .. } => ErrorCode::HashMismatch, + Error::PathRejected(_) => ErrorCode::PathRejected, + _ => ErrorCode::Unknown, + } + } +} + +/// Error shape sent over Tauri IPC: human text plus the technical string (needed for GitHub issues). +#[derive(Debug, Serialize)] +pub struct UiError { + pub human: Human, + pub technical: String, +} + +impl From for UiError { + fn from(e: Error) -> Self { + UiError { human: e.code().human(), technical: e.to_string() } + } +} diff --git a/crates/coa-core/src/fsx.rs b/crates/coa-core/src/fsx.rs new file mode 100644 index 0000000..f45e656 --- /dev/null +++ b/crates/coa-core/src/fsx.rs @@ -0,0 +1,281 @@ +//! The only module allowed to mutate the filesystem. Every function validates its target first. + +use std::fs::{self, File, OpenOptions}; +use std::io::{Read, Write}; +use std::path::{Component, Path, PathBuf}; + +use sha2::{Digest, Sha256}; + +use crate::error::{Error, Result}; + +/// Resolve `.` and `..` lexically without touching the filesystem. +pub fn normalize_lexical(path: &Path) -> PathBuf { + let mut out = PathBuf::new(); + for component in path.components() { + match component { + Component::CurDir => {} + Component::ParentDir => { + if !out.pop() { + out.push(".."); + } + } + other => out.push(other.as_os_str()), + } + } + out +} + +fn key(path: &Path) -> Vec { + path.components() + .map(|c| c.as_os_str().to_string_lossy().to_lowercase()) + .collect() +} + +/// Case-insensitive component-wise prefix test (Windows semantics). +pub fn starts_with_ci(path: &Path, prefix: &Path) -> bool { + let (p, q) = (key(path), key(prefix)); + p.len() >= q.len() && p[..q.len()] == q[..] +} + +/// Canonicalize the deepest existing ancestor, then re-append the not-yet-existing tail. +/// Detects symlink / junction escapes for paths that do not exist yet. +pub fn canonicalize_lenient(path: &Path) -> Result { + let path = normalize_lexical(path); + let mut tail: Vec = Vec::new(); + let mut cursor = path.as_path(); + loop { + match dunce::canonicalize(cursor) { + Ok(mut base) => { + for part in tail.iter().rev() { + base.push(part); + } + return Ok(base); + } + Err(_) => match (cursor.file_name(), cursor.parent()) { + (Some(name), Some(parent)) => { + tail.push(name.to_os_string()); + cursor = parent; + } + _ => return Err(Error::PathRejected(format!("cannot resolve {}", path.display()))), + }, + } + } +} + +/// Validate that `candidate` (absolute, or relative to `root`) resolves inside `root`, +/// following existing symlinks/junctions. Returns the resolved path. +pub fn ensure_within(root: &Path, candidate: &Path) -> Result { + let root = canonicalize_lenient(root)?; + let joined = if candidate.is_absolute() { candidate.to_path_buf() } else { root.join(candidate) }; + let resolved = canonicalize_lenient(&joined)?; + if starts_with_ci(&resolved, &root) { + Ok(resolved) + } else { + Err(Error::PathRejected(format!("{} is outside {}", resolved.display(), root.display()))) + } +} + +/// Join an untrusted relative path (from a manifest / archive) onto `root`. +/// Rejects absolute paths, drive prefixes, `..`, empty components, NTFS streams and reserved device names. +pub fn safe_join(root: &Path, rel: &str) -> Result { + let bad = |why: &str| Error::PathRejected(format!("{rel:?}: {why}")); + if rel.is_empty() { + return Err(bad("empty")); + } + if rel.contains(':') { + return Err(bad("drive or stream marker")); + } + let normalized = rel.replace('\\', "/"); + if normalized.starts_with('/') { + return Err(bad("absolute")); + } + let mut out = root.to_path_buf(); + for part in normalized.split('/') { + match part { + "" | "." => return Err(bad("empty or dot component")), + ".." => return Err(bad("parent traversal")), + p => { + if p.ends_with('.') || p.ends_with(' ') { + return Err(bad("trailing dot or space")); + } + let stem = p.split('.').next().unwrap_or("").to_ascii_uppercase(); + const RESERVED: [&str; 22] = [ + "CON", "PRN", "AUX", "NUL", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", + "COM9", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9", + ]; + if RESERVED.contains(&stem.as_str()) { + return Err(bad("reserved device name")); + } + out.push(p); + } + } + } + Ok(out) +} + +/// Write `bytes` to `path` so readers see either the old or the new content, never a partial file. +pub fn atomic_write(path: &Path, bytes: &[u8]) -> Result<()> { + let parent = path.parent().ok_or_else(|| Error::PathRejected("no parent directory".into()))?; + fs::create_dir_all(parent)?; + let tmp = parent.join(format!( + ".{}.{}.tmp", + path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(), + std::process::id() + )); + let write = || -> std::io::Result<()> { + let mut f = OpenOptions::new().write(true).create_new(true).open(&tmp)?; + f.write_all(bytes)?; + f.sync_all()?; + Ok(()) + }; + if let Err(e) = write() { + let _ = fs::remove_file(&tmp); + return Err(e.into()); + } + if let Err(e) = fs::rename(&tmp, path) { + let _ = fs::remove_file(&tmp); + return Err(e.into()); + } + Ok(()) +} + +pub fn atomic_write_json(path: &Path, value: &T) -> Result<()> { + let mut bytes = serde_json::to_vec_pretty(value)?; + bytes.push(b'\n'); + atomic_write(path, &bytes) +} + +pub fn read_json(path: &Path) -> Result { + let bytes = fs::read(path)?; + let bytes = bytes.strip_prefix(&[0xEF, 0xBB, 0xBF][..]).unwrap_or(&bytes); + Ok(serde_json::from_slice(bytes)?) +} + +pub fn sha256_file(path: &Path) -> Result { + let mut file = File::open(path)?; + let mut hasher = Sha256::new(); + let mut buf = vec![0u8; 1 << 20]; + loop { + let n = file.read(&mut buf)?; + if n == 0 { + break; + } + hasher.update(&buf[..n]); + } + Ok(hex::encode(hasher.finalize())) +} + +pub fn sha256_bytes(bytes: &[u8]) -> String { + hex::encode(Sha256::digest(bytes)) +} + +/// Free bytes on the volume that holds `path` (or its nearest existing ancestor). +pub fn free_space(path: &Path) -> Result { + let mut cursor = Some(path); + while let Some(p) = cursor { + if p.exists() { + return Ok(fs4::available_space(p)?); + } + cursor = p.parent(); + } + Err(Error::PathRejected(format!("no existing ancestor for {}", path.display()))) +} + +/// Fail before writing if the volume cannot hold `needed` bytes plus a safety margin. +pub fn require_space(path: &Path, needed: u64) -> Result<()> { + const MARGIN: u64 = 256 * 1024 * 1024; + let available = free_space(path)?; + if available < needed.saturating_add(MARGIN) { + return Err(Error::InsufficientSpace { needed: needed.saturating_add(MARGIN), available }); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn safe_join_accepts_normal_and_rejects_traversal() { + let root = Path::new("C:/srv"); + assert!(safe_join(root, "Core/worldserver.exe").is_ok()); + assert!(safe_join(root, "Core\\configs\\a.conf").is_ok()); + for bad in ["", "../x", "a/../../x", "/abs", "C:/x", "a/./b", "a//b", "a/CON", "a/nul.txt", "x.exe:zone", "a/b.", "a/b "] { + assert!(safe_join(root, bad).is_err(), "should reject {bad:?}"); + } + } + + #[test] + fn ensure_within_blocks_escape() { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path().join("srv"); + fs::create_dir_all(&root).unwrap(); + assert!(ensure_within(&root, Path::new("Core/new/file.txt")).is_ok()); + assert!(ensure_within(&root, Path::new("../evil")).is_err()); + assert!(ensure_within(&root, &dir.path().join("other")).is_err()); + // case-insensitive root match (Windows) + let upper = PathBuf::from(root.to_string_lossy().to_uppercase()).join("a"); + if cfg!(windows) { + assert!(ensure_within(&root, &upper).is_ok()); + } + } + + #[test] + fn ensure_within_blocks_junction_escape() { + if !cfg!(windows) { + return; + } + let dir = tempfile::tempdir().unwrap(); + let root = dir.path().join("srv"); + let outside = dir.path().join("outside"); + fs::create_dir_all(&root).unwrap(); + fs::create_dir_all(&outside).unwrap(); + let link = root.join("link"); + // A directory junction needs no privileges (unlike symlinks). + let status = std::process::Command::new("cmd") + .args(["/C", "mklink", "/J"]) + .arg(&link) + .arg(&outside) + .output() + .unwrap(); + if !status.status.success() { + return; + } + assert!(ensure_within(&root, &link.join("file.txt")).is_err()); + } + + #[test] + fn atomic_write_replaces_and_leaves_no_temp() { + let dir = tempfile::tempdir().unwrap(); + let p = dir.path().join("a.json"); + atomic_write(&p, b"one").unwrap(); + atomic_write(&p, b"two").unwrap(); + assert_eq!(fs::read(&p).unwrap(), b"two"); + let leftovers: Vec<_> = fs::read_dir(dir.path()).unwrap().collect(); + assert_eq!(leftovers.len(), 1); + } + + #[test] + fn sha256_matches_known_vector() { + assert_eq!(sha256_bytes(b"abc"), "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"); + let dir = tempfile::tempdir().unwrap(); + let p = dir.path().join("f"); + fs::write(&p, b"abc").unwrap(); + assert_eq!(sha256_file(&p).unwrap(), sha256_bytes(b"abc")); + } + + #[test] + fn read_json_tolerates_bom() { + let dir = tempfile::tempdir().unwrap(); + let p = dir.path().join("b.json"); + fs::write(&p, b"\xEF\xBB\xBF{\"a\":1}").unwrap(); + let v: serde_json::Value = read_json(&p).unwrap(); + assert_eq!(v["a"], 1); + } + + #[test] + fn require_space_rejects_absurd_request() { + let dir = tempfile::tempdir().unwrap(); + assert!(matches!(require_space(dir.path(), u64::MAX / 2), Err(Error::InsufficientSpace { .. }))); + } +} diff --git a/crates/coa-core/src/lib.rs b/crates/coa-core/src/lib.rs new file mode 100644 index 0000000..65fd472 --- /dev/null +++ b/crates/coa-core/src/lib.rs @@ -0,0 +1,9 @@ +pub mod error; +pub mod fsx; +pub mod logging; +pub mod manifest; +pub mod registry; + +pub use error::{Error, ErrorCode, Result}; + +pub const MANAGER_VERSION: &str = env!("CARGO_PKG_VERSION"); diff --git a/crates/coa-core/src/logging.rs b/crates/coa-core/src/logging.rs new file mode 100644 index 0000000..1c2c0f2 --- /dev/null +++ b/crates/coa-core/src/logging.rs @@ -0,0 +1,126 @@ +//! Size-bounded rotating log file: `manager.log`, `manager.log.1` .. `manager.log.N`. + +use std::fs::{self, File, OpenOptions}; +use std::io::{self, Write}; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex}; + +pub struct RotatingWriter { + path: PathBuf, + max_bytes: u64, + keep: usize, + file: Option, + written: u64, +} + +impl RotatingWriter { + pub fn open(path: impl Into, max_bytes: u64, keep: usize) -> io::Result { + let path = path.into(); + if let Some(parent) = path.parent() { + fs::create_dir_all(parent)?; + } + let file = OpenOptions::new().create(true).append(true).open(&path)?; + let written = file.metadata()?.len(); + Ok(Self { path, max_bytes, keep, file: Some(file), written }) + } + + fn numbered(&self, n: usize) -> PathBuf { + let mut name = self.path.file_name().unwrap_or_default().to_os_string(); + name.push(format!(".{n}")); + self.path.with_file_name(name) + } + + fn rotate(&mut self) -> io::Result<()> { + self.file = None; + let _ = fs::remove_file(self.numbered(self.keep)); + for n in (1..self.keep).rev() { + let from = self.numbered(n); + if from.exists() { + let _ = fs::rename(&from, self.numbered(n + 1)); + } + } + if self.keep > 0 { + let _ = fs::rename(&self.path, self.numbered(1)); + } else { + let _ = fs::remove_file(&self.path); + } + self.file = Some(OpenOptions::new().create(true).append(true).open(&self.path)?); + self.written = 0; + Ok(()) + } +} + +impl Write for RotatingWriter { + fn write(&mut self, buf: &[u8]) -> io::Result { + if self.written > 0 && self.written + buf.len() as u64 > self.max_bytes { + self.rotate()?; + } + let file = self.file.as_mut().ok_or_else(|| io::Error::other("log closed"))?; + let n = file.write(buf)?; + self.written += n as u64; + Ok(n) + } + + fn flush(&mut self) -> io::Result<()> { + match self.file.as_mut() { + Some(f) => f.flush(), + None => Ok(()), + } + } +} + +#[derive(Clone)] +pub struct SharedWriter(Arc>); + +impl SharedWriter { + pub fn new(w: RotatingWriter) -> Self { + Self(Arc::new(Mutex::new(w))) + } +} + +impl Write for SharedWriter { + fn write(&mut self, buf: &[u8]) -> io::Result { + self.0.lock().map_err(|_| io::Error::other("log poisoned"))?.write(buf) + } + + fn flush(&mut self) -> io::Result<()> { + self.0.lock().map_err(|_| io::Error::other("log poisoned"))?.flush() + } +} + +impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for SharedWriter { + type Writer = SharedWriter; + + fn make_writer(&'a self) -> Self::Writer { + self.clone() + } +} + +/// Install the global tracing subscriber writing to a rotated file (2 MiB x 5). +pub fn init(log_path: &Path) -> io::Result<()> { + let writer = SharedWriter::new(RotatingWriter::open(log_path, 2 * 1024 * 1024, 5)?); + let _ = tracing_subscriber::fmt().with_writer(writer).with_ansi(false).with_max_level(tracing::Level::INFO).try_init(); + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn rotates_and_bounds_total_size() { + let dir = tempfile::tempdir().unwrap(); + let p = dir.path().join("m.log"); + let mut w = RotatingWriter::open(&p, 100, 2).unwrap(); + for _ in 0..50 { + w.write_all(&[b'x'; 30]).unwrap(); + } + w.flush().unwrap(); + let mut names: Vec<_> = + fs::read_dir(dir.path()).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect(); + names.sort(); + assert_eq!(names, ["m.log", "m.log.1", "m.log.2"]); + let total: u64 = fs::read_dir(dir.path()).unwrap().map(|e| e.unwrap().metadata().unwrap().len()).sum(); + assert!(total <= 3 * 100); + } +} diff --git a/crates/coa-core/src/manifest.rs b/crates/coa-core/src/manifest.rs new file mode 100644 index 0000000..8086c4a --- /dev/null +++ b/crates/coa-core/src/manifest.rs @@ -0,0 +1,238 @@ +//! Release manifest (`manifest.json`) shipped with every base/update/bots package. + +use std::collections::HashSet; +use std::path::Path; + +use serde::{Deserialize, Serialize}; + +use crate::error::{Error, Result}; +use crate::fsx; + +pub const SCHEMA: u32 = 1; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum Kind { + Base, + Update, + Bots, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum Owner { + Core, + Bots, + Manager, + User, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum ReplacePolicy { + Replace, + ReplaceIfPristine, + MergeConfig, + CreateIfMissing, + NeverTouch, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct FileEntry { + pub path: String, + pub sha256: String, + pub size: u64, + pub owner: Owner, + pub policy: ReplacePolicy, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct Migration { + pub id: String, + pub db: String, + pub sha256: String, + #[serde(default)] + pub destructive: bool, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct Revision { + pub commit: Option, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct Signature { + pub alg: String, + pub key_id: String, + pub sig: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Manifest { + pub schema: u32, + pub kind: Kind, + pub version: String, + pub core: Revision, + #[serde(default)] + pub bots: Option, + pub built_at: String, + pub min_manager_version: String, + #[serde(default)] + pub files: Vec, + #[serde(default)] + pub migrations: Vec, + #[serde(default)] + pub signature: Option, +} + +fn is_sha256(s: &str) -> bool { + s.len() == 64 && s.bytes().all(|b| b.is_ascii_hexdigit()) +} + +fn is_commit(s: &str) -> bool { + s.len() == 40 && s.bytes().all(|b| b.is_ascii_hexdigit()) +} + +/// Parse "1.2.3" leniently into a comparable tuple. +pub fn parse_version(v: &str) -> Option<(u64, u64, u64)> { + let core = v.trim_start_matches('v').split(['-', '+']).next()?; + let mut it = core.split('.'); + let major = it.next()?.parse().ok()?; + let minor = it.next().unwrap_or("0").parse().ok()?; + let patch = it.next().unwrap_or("0").parse().ok()?; + if it.next().is_some() { + return None; + } + Some((major, minor, patch)) +} + +impl Manifest { + pub fn parse(bytes: &[u8]) -> Result { + let m: Manifest = serde_json::from_slice(bytes).map_err(|e| Error::InvalidManifest(e.to_string()))?; + m.validate()?; + Ok(m) + } + + pub fn validate(&self) -> Result<()> { + let bad = |s: String| Err(Error::InvalidManifest(s)); + if self.schema != SCHEMA { + return bad(format!("unsupported schema {}", self.schema)); + } + if parse_version(&self.version).is_none() { + return bad(format!("bad version {:?}", self.version)); + } + if parse_version(&self.min_manager_version).is_none() { + return bad(format!("bad minManagerVersion {:?}", self.min_manager_version)); + } + for (label, rev) in [("core", Some(&self.core)), ("bots", self.bots.as_ref())] { + if let Some(Revision { commit: Some(c) }) = rev { + if !is_commit(c) { + return bad(format!("{label} commit must be a full 40-hex SHA, got {c:?}")); + } + } + } + let scratch = Path::new("root"); + let mut seen = HashSet::new(); + for f in &self.files { + fsx::safe_join(scratch, &f.path).map_err(|e| Error::InvalidManifest(e.to_string()))?; + if !is_sha256(&f.sha256) { + return bad(format!("{}: bad sha256", f.path)); + } + if !seen.insert(f.path.replace('\\', "/").to_lowercase()) { + return bad(format!("{}: duplicate path", f.path)); + } + } + let mut ids = HashSet::new(); + for m in &self.migrations { + if m.id.is_empty() || !is_sha256(&m.sha256) || !ids.insert((m.db.clone(), m.id.clone())) { + return bad(format!("migration {:?} invalid or duplicated", m.id)); + } + } + Ok(()) + } + + /// True if this Manager build may apply the manifest. + pub fn compatible_with_manager(&self, manager_version: &str) -> bool { + match (parse_version(manager_version), parse_version(&self.min_manager_version)) { + (Some(have), Some(need)) => have >= need, + _ => false, + } + } + + pub fn total_size(&self) -> u64 { + self.files.iter().map(|f| f.size).sum() + } +} + +/// Verify `path` against the entry; never trusts size alone. +pub fn verify_file(path: &Path, entry: &FileEntry) -> Result<()> { + let len = std::fs::metadata(path)?.len(); + if len != entry.size { + return Err(Error::HashMismatch { + path: entry.path.clone(), + expected: format!("{} bytes", entry.size), + actual: format!("{len} bytes"), + }); + } + let actual = fsx::sha256_file(path)?; + if !actual.eq_ignore_ascii_case(&entry.sha256) { + return Err(Error::HashMismatch { path: entry.path.clone(), expected: entry.sha256.clone(), actual }); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn sample(files: &str) -> String { + format!( + r#"{{"schema":1,"kind":"update","version":"0.4.1","core":{{"commit":"{c}"}},"bots":{{"commit":null}}, + "builtAt":"2026-09-30T00:00:00Z","minManagerVersion":"0.1.0","files":[{files}],"migrations":[]}}"#, + c = "a".repeat(40) + ) + } + + fn file(path: &str, sha: &str) -> String { + format!(r#"{{"path":"{path}","sha256":"{sha}","size":3,"owner":"core","policy":"replace"}}"#) + } + + #[test] + fn parses_valid_manifest() { + let m = Manifest::parse(sample(&file("Core/worldserver.exe", &"b".repeat(64))).as_bytes()).unwrap(); + assert_eq!(m.files.len(), 1); + assert!(m.compatible_with_manager("0.1.0")); + assert!(!m.compatible_with_manager("0.0.9")); + } + + #[test] + fn rejects_traversal_bad_hash_duplicates_and_short_commit() { + let ok = "b".repeat(64); + assert!(Manifest::parse(sample(&file("../x", &ok)).as_bytes()).is_err()); + assert!(Manifest::parse(sample(&file("a/b", "zz")).as_bytes()).is_err()); + let dup = format!("{},{}", file("A/b", &ok), file("a/B", &ok)); + assert!(Manifest::parse(sample(&dup).as_bytes()).is_err()); + let s = sample("").replace(&"a".repeat(40), "master"); + assert!(Manifest::parse(s.as_bytes()).is_err()); + } + + #[test] + fn verify_file_detects_corruption() { + let dir = tempfile::tempdir().unwrap(); + let p = dir.path().join("f"); + std::fs::write(&p, b"abc").unwrap(); + let entry = FileEntry { + path: "f".into(), + sha256: fsx::sha256_bytes(b"abc"), + size: 3, + owner: Owner::Core, + policy: ReplacePolicy::Replace, + }; + verify_file(&p, &entry).unwrap(); + std::fs::write(&p, b"abd").unwrap(); + assert!(matches!(verify_file(&p, &entry), Err(Error::HashMismatch { .. }))); + std::fs::write(&p, b"abcd").unwrap(); + assert!(verify_file(&p, &entry).is_err()); + } +} diff --git a/crates/coa-core/src/registry.rs b/crates/coa-core/src/registry.rs new file mode 100644 index 0000000..db9b8eb --- /dev/null +++ b/crates/coa-core/src/registry.rs @@ -0,0 +1,272 @@ +//! Installation registry and per-installation metadata directory (`.manager`). +//! +//! Registering or importing an installation writes only inside the metadata directory and the registry file. +//! The server folder itself is never written to. + +use std::collections::BTreeMap; +use std::fs; +use std::path::{Path, PathBuf}; + +use serde::{Deserialize, Serialize}; + +use crate::error::{Error, Result}; +use crate::fsx; + +pub const META_SCHEMA: u32 = 1; +pub const LAYOUT_REPACK_V1: &str = "repack-v1"; +const META_SUBDIRS: [&str; 6] = ["manifests", "backups", "migrations", "logs", "cache", "staging"]; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum InstallKind { + New, + Imported, +} + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub struct VersionInfo { + pub version: Option, + pub commit: Option, +} + +/// Non-secret database facts only. Credentials never live in install.json. +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub struct DbInfo { + pub port: Option, + pub schemas: Vec, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct InstallMeta { + pub schema: u32, + pub id: String, + pub kind: InstallKind, + pub server_path: String, + pub layout: String, + pub created_at: String, + pub manager_version: String, + #[serde(default)] + pub core: VersionInfo, + #[serde(default)] + pub bots: VersionInfo, + #[serde(default)] + pub database: DbInfo, + #[serde(default)] + pub client_path: Option, + /// Files that existed before the Manager touched the installation (path -> sha256, when known). + #[serde(default)] + pub original_hashes: BTreeMap, + /// Files the Manager itself created or later modified. + #[serde(default)] + pub managed_files: Vec, +} + +impl InstallMeta { + pub fn new(kind: InstallKind, server_path: &Path) -> Self { + Self { + schema: META_SCHEMA, + id: uuid::Uuid::new_v4().to_string(), + kind, + server_path: server_path.to_string_lossy().into_owned(), + layout: LAYOUT_REPACK_V1.into(), + created_at: chrono::Utc::now().to_rfc3339(), + manager_version: crate::MANAGER_VERSION.into(), + core: VersionInfo::default(), + bots: VersionInfo::default(), + database: DbInfo::default(), + client_path: None, + original_hashes: BTreeMap::new(), + managed_files: Vec::new(), + } + } +} + +/// `D:\CoA-Repack` -> `D:\CoA-Repack.manager`. +pub fn metadata_dir_for(server: &Path) -> Result { + let name = server + .file_name() + .ok_or_else(|| Error::Invalid("a drive root cannot be a server folder".into()))? + .to_string_lossy() + .into_owned(); + Ok(server.with_file_name(format!("{name}.manager"))) +} + +pub struct MetaDir { + pub root: PathBuf, +} + +impl MetaDir { + pub fn install_json(&self) -> PathBuf { + self.root.join("install.json") + } + + pub fn log_file(&self) -> PathBuf { + self.root.join("logs").join("manager.log") + } + + /// Create the metadata directory for `server` (which must already exist) and write `install.json`. + pub fn create(server: &Path, meta: &InstallMeta) -> Result { + if !server.is_dir() { + return Err(Error::Invalid(format!("{} is not a folder", server.display()))); + } + let server_abs = fsx::canonicalize_lenient(server)?; + let root = metadata_dir_for(&server_abs)?; + if fsx::starts_with_ci(&root, &server_abs) { + return Err(Error::PathRejected("metadata folder would be inside the server folder".into())); + } + fs::create_dir_all(&root)?; + for sub in META_SUBDIRS { + fs::create_dir_all(root.join(sub))?; + } + let dir = MetaDir { root }; + fsx::atomic_write_json(&dir.install_json(), meta)?; + Ok(dir) + } + + pub fn open(root: &Path) -> Result<(MetaDir, InstallMeta)> { + let meta: InstallMeta = fsx::read_json(&root.join("install.json"))?; + Ok((MetaDir { root: root.to_path_buf() }, meta)) + } +} + +#[derive(Debug, Default, Serialize, Deserialize)] +struct RegistryFile { + installs: BTreeMap, +} + +/// `%LOCALAPPDATA%\CoAServerManager\installs.json`: id -> server path. Removing an entry never touches files. +pub struct Registry { + file: PathBuf, +} + +impl Registry { + pub fn at(file: impl Into) -> Self { + Self { file: file.into() } + } + + fn load(&self) -> Result { + if !self.file.exists() { + return Ok(RegistryFile::default()); + } + fsx::read_json(&self.file) + } + + pub fn list(&self) -> Result> { + Ok(self.load()?.installs.into_iter().map(|(id, p)| (id, PathBuf::from(p))).collect()) + } + + pub fn find_by_path(&self, server: &Path) -> Result> { + let target = fsx::canonicalize_lenient(server)?; + for (id, p) in self.list()? { + if fsx::canonicalize_lenient(&p).map(|c| fsx::starts_with_ci(&c, &target) && fsx::starts_with_ci(&target, &c)).unwrap_or(false) { + return Ok(Some(id)); + } + } + Ok(None) + } + + /// Register an installation. Rejects duplicates and nested/overlapping folders. + pub fn register(&self, id: &str, server: &Path) -> Result<()> { + let target = fsx::canonicalize_lenient(server)?; + let mut file = self.load()?; + for (other_id, other) in &file.installs { + let other = fsx::canonicalize_lenient(Path::new(other)).unwrap_or_else(|_| PathBuf::from(other)); + if other_id == id { + continue; + } + if fsx::starts_with_ci(&target, &other) || fsx::starts_with_ci(&other, &target) { + return Err(Error::Invalid(format!( + "{} overlaps already registered installation {}", + target.display(), + other.display() + ))); + } + } + file.installs.insert(id.to_string(), target.to_string_lossy().into_owned()); + fsx::atomic_write_json(&self.file, &file) + } + + pub fn unregister(&self, id: &str) -> Result<()> { + let mut file = self.load()?; + if file.installs.remove(id).is_none() { + return Err(Error::UnknownInstallation(id.into())); + } + fsx::atomic_write_json(&self.file, &file) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn metadata_dir_is_a_sibling_and_server_folder_is_untouched() { + let dir = tempfile::tempdir().unwrap(); + let server = dir.path().join("CoA-Repack"); + fs::create_dir_all(server.join("Core")).unwrap(); + fs::write(server.join("Core/worldserver.exe"), b"x").unwrap(); + let before = snapshot(&server); + + let meta = InstallMeta::new(InstallKind::Imported, &server); + let md = MetaDir::create(&server, &meta).unwrap(); + assert_eq!(md.root.file_name().unwrap(), "CoA-Repack.manager"); + assert!(md.install_json().exists()); + for sub in META_SUBDIRS { + assert!(md.root.join(sub).is_dir()); + } + assert_eq!(before, snapshot(&server), "import must not modify the server folder"); + + let (_, loaded) = MetaDir::open(&md.root).unwrap(); + assert_eq!(loaded.id, meta.id); + assert_eq!(loaded.kind, InstallKind::Imported); + } + + fn snapshot(root: &Path) -> Vec<(String, u64)> { + let mut out = Vec::new(); + fn walk(dir: &Path, root: &Path, out: &mut Vec<(String, u64)>) { + for e in fs::read_dir(dir).unwrap() { + let e = e.unwrap(); + let md = e.metadata().unwrap(); + let rel = e.path().strip_prefix(root).unwrap().to_string_lossy().into_owned(); + out.push((rel, if md.is_dir() { 0 } else { md.len() })); + if md.is_dir() { + walk(&e.path(), root, out); + } + } + } + walk(root, root, &mut out); + out.sort(); + out + } + + #[test] + fn registry_rejects_duplicates_and_nesting_but_allows_reregister_same_id() { + let dir = tempfile::tempdir().unwrap(); + let reg = Registry::at(dir.path().join("reg/installs.json")); + let a = dir.path().join("a"); + let inner = a.join("inner"); + let b = dir.path().join("b"); + for p in [&a, &inner, &b] { + fs::create_dir_all(p).unwrap(); + } + reg.register("1", &a).unwrap(); + reg.register("1", &a).unwrap(); + assert!(reg.register("2", &a).is_err(), "same folder"); + assert!(reg.register("2", &inner).is_err(), "nested inside existing"); + assert!(reg.register("3", dir.path()).is_err(), "contains existing"); + reg.register("2", &b).unwrap(); + assert_eq!(reg.list().unwrap().len(), 2); + assert_eq!(reg.find_by_path(&a).unwrap().as_deref(), Some("1")); + reg.unregister("1").unwrap(); + assert!(a.exists(), "unregister never deletes files"); + assert!(matches!(reg.unregister("1"), Err(Error::UnknownInstallation(_)))); + } + + #[test] + fn drive_root_and_missing_folder_are_rejected() { + let meta = InstallMeta::new(InstallKind::New, Path::new("C:/nope")); + assert!(MetaDir::create(Path::new("C:/definitely/missing/folder"), &meta).is_err()); + assert!(metadata_dir_for(Path::new("C:/")).is_err()); + } +} diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md new file mode 100644 index 0000000..76bf9ca --- /dev/null +++ b/docs/ARCHITECTURE.md @@ -0,0 +1,430 @@ +# 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\ .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 +``` + +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> (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 + `\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. + +``` +.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\\ 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\.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 `.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": [""|"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\\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, `characters`+`auth` dump (world optional); + write `txn.json {state: Snapshotted}`. +5. **Apply** into `staging\\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** — run pending SQL through the tracked runner (D7); failure ⇒ stop, keep DB backup, offer restore. +7. **Validate** — start server, health check (D3) 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 = binaries + managed config state + module state only. Database restore is a **separate explicit +action** (spec §19–20). + +### 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`. 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`, resetting characters, overwriting DBs, or restoring DB on a binary rollback. 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. Manager only: detect (`Wow.exe`/`Ascension.exe` + `Data\`), read/write +`realmlist.wtf` after backing it up, and copy `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. +*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. + +--------------------------------------------------------------------------------------------------------- + +## 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 `.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 recovery point's binaries/configs/module state; database untouched unless the user +picks "Restore database" separately (shows dump timestamp and warns that progress since then is lost). + +--------------------------------------------------------------------------------------------------------- + +## 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 |