From ce1861d88b6cb75f979d1dd6ca240bfca64ce6e9 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 10:58:35 +0500 Subject: [PATCH] Phase 10a: diagnostics, managed-file verification, redacted diagnostic package export Co-Authored-By: Claude Sonnet 5.5 --- README.md | 4 +- crates/coa-core/src/diag.rs | 274 ++++++++++++++++++++++++++++++++ crates/coa-core/src/lib.rs | 1 + src-tauri/src/lib.rs | 40 ++++- src/lib/api.ts | 10 ++ src/screens/DiagnosticsCard.tsx | 93 +++++++++++ src/screens/SettingsHome.tsx | 3 + 7 files changed, 423 insertions(+), 2 deletions(-) create mode 100644 crates/coa-core/src/diag.rs create mode 100644 src/screens/DiagnosticsCard.tsx diff --git a/README.md b/README.md index 9baacf8..2eaaab9 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,9 @@ Design and audit: [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md). | 7 Companions: real population, hardware-aware sizes, RA spawn (install/update of the module rides on the update flow) | done | | 8 Client: read-only detection, backed-up realmlist, isolated addon install, START & PLAY | done | | Backlog: interface languages EN/RU/DE/FR/ES (see docs/ARCHITECTURE.md section 9) | planned | -| 9 Friends, 10 Polish; `coa-server-build` repo (nightly sync, releases) | not started | +| 9 Friends: exposure check, firewall rules, UPnP discovery, LAN/direct/private modes, friend package | done | +| 10 Polish: diagnostics, file verification, redacted diagnostic export | done; self-update installer, accessibility audit, i18n pending | +| `coa-server-build` repo: nightly build, edge/stable releases, fork sync | created; needs the COA_SIGNING_KEY / FORK_PUSH_TOKEN secrets | ## Develop ``` diff --git a/crates/coa-core/src/diag.rs b/crates/coa-core/src/diag.rs new file mode 100644 index 0000000..df60321 --- /dev/null +++ b/crates/coa-core/src/diag.rs @@ -0,0 +1,274 @@ +//! Diagnostics: a fixed list of read-only checks with plain-language results, a verification of the Manager's own files, +//! and a redacted diagnostic package for bug reports. Nothing here changes the server. + +use std::fs; +use std::io::{Read, Seek, SeekFrom, Write}; +use std::path::{Path, PathBuf}; + +use serde::Serialize; + +use crate::config::parser::ConfFile; +use crate::error::{Error, Result}; +use crate::fsx; +use crate::layout::{self, Classification}; +use crate::process::{self, ServiceState}; +use crate::registry::InstallMeta; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "lowercase")] +pub enum Level { + Ok, + Warn, + Fail, +} + +#[derive(Debug, Clone, Serialize)] +pub struct Check { + pub id: &'static str, + pub title: &'static str, + pub level: Level, + pub detail: String, +} + +fn check(id: &'static str, title: &'static str, level: Level, detail: impl Into) -> Check { + Check { id, title, level, detail: detail.into() } +} + +#[derive(Debug, Serialize)] +pub struct Report { + pub checks: Vec, + pub problems: usize, +} + +const MIN_FREE_BYTES: u64 = 5 * 1024 * 1024 * 1024; + +pub fn run(root: &Path, meta: &InstallMeta) -> Report { + let mut c = Vec::new(); + let scan = layout::scan(root); + match &scan { + Ok(r) => { + let (lvl, text) = match r.classification { + Classification::Healthy => (Level::Ok, "All expected server parts were found."), + Classification::Partial => (Level::Warn, "Some server parts are missing."), + Classification::UnknownCustom => (Level::Warn, "This is a custom server build; some features are limited."), + Classification::Incompatible => (Level::Fail, "This folder does not look like a CoA server."), + }; + c.push(check("files", "Server files", lvl, text)); + let missing: Vec<&str> = r.items.iter().filter(|i| i.status == layout::Status::Missing && i.key != "companions" && i.key != "release_info").map(|i| i.label).collect(); + if !missing.is_empty() { + c.push(check("missing_parts", "Missing parts", Level::Warn, missing.join(", "))); + } + } + Err(e) => c.push(check("files", "Server files", Level::Fail, e.to_string())), + } + + let ports = layout::read_ports(root); + let o = process::observe(root, &ports); + for (title, s) in [("Database", &o.mysql), ("Login server", &o.auth), ("World server", &o.world)] { + let (lvl, text) = match (s.state, &s.conflict) { + (ServiceState::Running, _) => (Level::Ok, "Running".to_string()), + (_, Some(conf)) => (Level::Fail, format!("Port {} is used by another program (process {}).", conf.port, conf.pid)), + (ServiceState::Starting, _) => (Level::Warn, "Starting, not answering yet.".to_string()), + _ => (Level::Warn, "Not running.".to_string()), + }; + c.push(check(s.name, title, lvl, text)); + } + + // configuration files must at least be readable text the Manager can edit safely + let mut unreadable = Vec::new(); + for rel in ["Core/configs/worldserver.conf", "Core/configs/authserver.conf", "Settings/worldserver.conf.template", "Settings/authserver.conf.template"] { + let p = root.join(rel); + if p.is_file() && fs::read(&p).map(|b| ConfFile::parse_bytes(&b).is_err()).unwrap_or(true) { + unreadable.push(rel); + } + } + c.push(if unreadable.is_empty() { check("configs", "Configuration", Level::Ok, "Configuration files can be read.") } else { check("configs", "Configuration", Level::Fail, format!("Cannot read: {}", unreadable.join(", "))) }); + for scope in [crate::config::Scope::Server, crate::config::Scope::Bots] { + if let Ok(v) = crate::config::load(root, scope) { + let bad: Vec = v.settings.iter().filter(|s| s.problem.is_some()).map(|s| s.meta.key.clone()).collect(); + if !bad.is_empty() { + c.push(check("config_values", "Setting values", Level::Warn, format!("Unusable values for: {}", bad.join(", ")))); + } + } + } + + match fsx::free_space(root) { + Ok(f) if f >= MIN_FREE_BYTES => c.push(check("disk", "Free disk space", Level::Ok, format!("{} GB free", f >> 30))), + Ok(f) => c.push(check("disk", "Free disk space", Level::Warn, format!("Only {} GB free; backups and updates need room.", f >> 30))), + Err(e) => c.push(check("disk", "Free disk space", Level::Warn, e.to_string())), + } + + let probe = root.join(".coa-write-test"); + let writable = fs::write(&probe, b"x").is_ok(); + let _ = fs::remove_file(&probe); + c.push(if writable { check("permissions", "Permissions", Level::Ok, "The server folder is writable.") } else { check("permissions", "Permissions", Level::Fail, "The Manager cannot write to the server folder (try another location or run once as administrator).") }); + + if let Some(path) = &meta.client_path { + c.push(if crate::client::detect(Path::new(path), None).is_some() { check("client", "Game client", Level::Ok, path.clone()) } else { check("client", "Game client", Level::Warn, "The saved game folder was not found; choose it again in Settings.") }); + } + + let exposed: Vec<&str> = crate::net::exposure(&ports).iter().filter(|e| (e.what == "database" || e.what == "server console") && e.reachable_from_network).map(|e| e.what).collect(); + c.push(if exposed.is_empty() { check("exposure", "Private services", Level::Ok, "Database and server console are not reachable from the network.") } else { check("exposure", "Private services", Level::Fail, format!("Reachable from the network: {}.", exposed.join(", "))) }); + + let problems = c.iter().filter(|x| x.level != Level::Ok).count(); + Report { checks: c, problems } +} + +#[derive(Debug, Serialize)] +pub struct FileProblem { + pub path: String, + pub kind: &'static str, +} + +/// Compare managed files with the hashes the Manager recorded. Read-only; user files are never listed. +pub fn verify_managed(root: &Path, meta: &InstallMeta) -> Vec { + let mut out = Vec::new(); + for (rel, want) in &meta.original_hashes { + let Ok(p) = fsx::safe_join(root, rel) else { continue }; + match fsx::sha256_file(&p) { + Err(_) => out.push(FileProblem { path: rel.clone(), kind: "missing" }), + Ok(h) if !h.eq_ignore_ascii_case(want) => out.push(FileProblem { path: rel.clone(), kind: "changed" }), + Ok(_) => {} + } + } + out +} + +fn tail(path: &Path, max: u64) -> Vec { + let Ok(mut f) = fs::File::open(path) else { return Vec::new() }; + let len = f.metadata().map(|m| m.len()).unwrap_or(0); + let _ = f.seek(SeekFrom::Start(len.saturating_sub(max))); + let mut b = Vec::new(); + let _ = f.take(max).read_to_end(&mut b); + b +} + +/// Remove things that must never leave the machine from log text. +pub fn redact(text: &str) -> String { + let mut out = Vec::new(); + for line in text.lines() { + let l = line.to_lowercase(); + let sensitive = ["password", "passwd", "secret", "token", "apikey", "api_key", "databaseinfo"].iter().any(|k| l.contains(k)); + out.push(if sensitive { "[line removed: may contain a secret]".to_string() } else { line.to_string() }); + } + out.join("\n") +} + +/// Zip with what a maintainer needs to debug a problem, with secrets removed. Returns the number of files inside. +pub fn export_package(root: &Path, meta_dir: &Path, manager_log: &Path, meta: &InstallMeta, report: &Report, out_zip: &Path) -> Result { + let file = fs::File::create(out_zip)?; + let mut zip = zip::ZipWriter::new(file); + let opts = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated); + let mut n = 0; + let mut add = |name: &str, bytes: &[u8]| -> Result<()> { + zip.start_file(name, opts).map_err(|e| Error::Invalid(e.to_string()))?; + zip.write_all(bytes)?; + n += 1; + Ok(()) + }; + let summary = serde_json::json!({ + "manager": crate::MANAGER_VERSION, + "core": meta.core, + "bots": meta.bots, + "kind": meta.kind, + "layout": meta.layout, + "checks": report.checks, + "wow_client_set": meta.client_path.is_some(), + }); + add("summary.json", serde_json::to_string_pretty(&summary)?.as_bytes())?; + for (name, path) in [("manager.log", manager_log.to_path_buf()), ("manager-install.log", meta_dir.join("logs/manager.log")), ("Server.log.tail", root.join("Core/Logs/Server.log")), ("Errors.log.tail", root.join("Core/Logs/Errors.log")), ("Auth.log.tail", root.join("Core/Logs/Auth.log")), ("world-console.log.tail", root.join("Core/Logs/world-console.log")), ("mysql-error.log.tail", root.join("mysql/logs/mysql-error.log"))] { + let bytes = tail(&path, 512 * 1024); + if !bytes.is_empty() { + add(name, redact(&String::from_utf8_lossy(&bytes)).as_bytes())?; + } + } + // Which settings exist, never their values. + if let Ok(b) = fs::read(root.join("Core/configs/worldserver.conf")) { + if let Ok(c) = ConfFile::parse_bytes(&b) { + let keys: Vec<&str> = c.entries().map(|(k, _)| k).collect(); + add("worldserver.conf.keys.txt", keys.join("\n").as_bytes())?; + } + } + if let Ok(b) = fs::read(root.join("RELEASE.json")) { + add("RELEASE.json", redact(&String::from_utf8_lossy(&b)).as_bytes())?; + } + zip.finish().map_err(|e| Error::Invalid(e.to_string()))?; + Ok(n) +} + +pub fn stamp() -> String { + chrono::Local::now().format("%Y%m%d-%H%M%S").to_string() +} + +pub fn desktop_or_temp() -> PathBuf { + let d = std::env::var_os("USERPROFILE").map(PathBuf::from).unwrap_or_else(std::env::temp_dir).join("Desktop"); + if d.is_dir() { d } else { std::env::temp_dir() } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::registry::{InstallKind, InstallMeta}; + + #[test] + fn redaction_removes_lines_that_could_carry_secrets() { + let t = redact("normal line\nLoginDatabaseInfo = \"127.0.0.1;3307;acore;PASS;db\"\nRa.Password=abc\nother"); + assert!(t.contains("normal line") && t.contains("other")); + assert!(!t.contains("PASS") && !t.contains("abc")); + } + + #[test] + fn verify_reports_missing_and_changed_managed_files_only() { + let d = tempfile::tempdir().unwrap(); + fs::write(d.path().join("ok.txt"), "a").unwrap(); + fs::write(d.path().join("changed.txt"), "b").unwrap(); + fs::write(d.path().join("user.txt"), "mine").unwrap(); + let mut meta = InstallMeta::new(InstallKind::New, d.path()); + meta.original_hashes.insert("ok.txt".into(), fsx::sha256_bytes(b"a")); + meta.original_hashes.insert("changed.txt".into(), fsx::sha256_bytes(b"original")); + meta.original_hashes.insert("gone.txt".into(), fsx::sha256_bytes(b"x")); + let mut p: Vec<(String, &str)> = verify_managed(d.path(), &meta).into_iter().map(|f| (f.path, f.kind)).collect(); + p.sort(); + assert_eq!(p, [("changed.txt".to_string(), "changed"), ("gone.txt".to_string(), "missing")]); + } + + #[test] + fn diagnostics_on_a_fake_repack_flag_the_stopped_services_and_pass_the_basics() { + let d = tempfile::tempdir().unwrap(); + let root = d.path().join("srv"); + layout::testkit::fake_repack(&root); + let meta = InstallMeta::new(InstallKind::Imported, &root); + let r = run(&root, &meta); + let get = |id: &str| r.checks.iter().find(|c| c.id == id).unwrap_or_else(|| panic!("{id}")); + assert_eq!(get("files").level, Level::Ok); + assert_eq!(get("permissions").level, Level::Ok); + assert_eq!(get("configs").level, Level::Ok); + assert_ne!(get("world").level, Level::Ok, "a stopped server is reported, not hidden"); + assert!(r.problems >= 3); + } + + #[test] + fn exported_package_holds_no_secrets() { + let d = tempfile::tempdir().unwrap(); + let root = d.path().join("srv"); + layout::testkit::fake_repack(&root); + fs::write(root.join("Core/Logs/Errors.log"), "boom\nDatabase password=hunter2 rejected\n").unwrap(); + fs::write(root.join("Core/configs/worldserver.conf"), "LoginDatabaseInfo = \"127.0.0.1;3307;acore;SECRETPW;auth\"\nRate.XP.Kill = 1\n").unwrap(); + let meta_dir = d.path().join("srv.manager"); + fs::create_dir_all(&meta_dir).unwrap(); + let meta = InstallMeta::new(InstallKind::Imported, &root); + let report = run(&root, &meta); + let zip_path = d.path().join("diag.zip"); + let n = export_package(&root, &meta_dir, &d.path().join("none.log"), &meta, &report, &zip_path).unwrap(); + assert!(n >= 3); + let mut z = zip::ZipArchive::new(fs::File::open(&zip_path).unwrap()).unwrap(); + let mut all = String::new(); + for i in 0..z.len() { + let mut s = String::new(); + let _ = z.by_index(i).unwrap().read_to_string(&mut s); + all.push_str(&s); + } + assert!(all.contains("boom") && all.contains("Rate.XP.Kill"), "keys and ordinary log lines are included"); + assert!(!all.contains("hunter2") && !all.contains("SECRETPW")); + } +} diff --git a/crates/coa-core/src/lib.rs b/crates/coa-core/src/lib.rs index 6f05f4a..eca7f0a 100644 --- a/crates/coa-core/src/lib.rs +++ b/crates/coa-core/src/lib.rs @@ -3,6 +3,7 @@ pub mod cleanbase; pub mod client; pub mod config; pub mod db; +pub mod diag; pub mod download; pub mod driver; pub mod error; diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 543ce61..df620be 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -716,6 +716,41 @@ async fn friends_package(state: State<'_, AppState>, id: String) -> std::result: .await } +#[tauri::command] +async fn run_diagnostics(state: State<'_, AppState>, id: String) -> std::result::Result { + let root = path_of(&state, &id)?; + blocking(move || { + let (_, meta) = install_meta(&root)?; + Ok(coa_core::diag::run(&root, &meta)) + }) + .await +} + +#[tauri::command] +async fn verify_files(state: State<'_, AppState>, id: String) -> std::result::Result, UiError> { + let root = path_of(&state, &id)?; + blocking(move || { + let (_, meta) = install_meta(&root)?; + Ok(coa_core::diag::verify_managed(&root, &meta)) + }) + .await +} + +/// Writes a redacted zip for bug reports to the Desktop and returns its path. +#[tauri::command] +async fn export_diagnostics(state: State<'_, AppState>, id: String) -> std::result::Result { + let root = path_of(&state, &id)?; + blocking(move || { + let (dir, meta) = install_meta(&root)?; + let report = coa_core::diag::run(&root, &meta); + let out = coa_core::diag::desktop_or_temp().join(format!("CoA-Diagnostics-{}.zip", coa_core::diag::stamp())); + coa_core::diag::export_package(&root, &dir, &data_dir().join("logs").join("manager.log"), &meta, &report, &out)?; + Ok(out.to_string_lossy().into_owned()) + }) + .await +} + + pub fn run() { let dir = data_dir(); let _ = coa_core::logging::init(&dir.join("logs").join("manager.log")); @@ -762,7 +797,10 @@ pub fn run() { friends_status, friends_check_internet, friends_enable, - friends_package + friends_package, + run_diagnostics, + verify_files, + export_diagnostics ]) .run(tauri::generate_context!()) .expect("error while running CoA Server Manager"); diff --git a/src/lib/api.ts b/src/lib/api.ts index 256fb17..a46483c 100644 --- a/src/lib/api.ts +++ b/src/lib/api.ts @@ -236,6 +236,13 @@ export interface InternetCheck { router_found: boolean; } +export interface DiagCheck { + id: string; + title: string; + level: "ok" | "warn" | "fail"; + detail: string; +} + export const api = { defaultInstallDir: () => invoke("default_install_dir"), scan: (path: string) => invoke("scan_server", { path }), @@ -277,6 +284,9 @@ export const api = { friendsEnable: (id: string, mode: FriendsMode, host?: string, useUpnp = false) => invoke<{ host: string; restart_required: boolean; note: string | null }>("friends_enable", { id, mode, host: host ?? null, useUpnp }), friendsPackage: (id: string) => invoke("friends_package", { id }), + runDiagnostics: (id: string) => invoke<{ checks: DiagCheck[]; problems: number }>("run_diagnostics", { id }), + verifyFiles: (id: string) => invoke<{ path: string; kind: "missing" | "changed" }[]>("verify_files", { id }), + exportDiagnostics: (id: string) => invoke("export_diagnostics", { id }), previewPreset: (id: string, scope: Scope, preset: string) => invoke("preview_preset", { id, scope, preset }), }; diff --git a/src/screens/DiagnosticsCard.tsx b/src/screens/DiagnosticsCard.tsx new file mode 100644 index 0000000..9c42f4a --- /dev/null +++ b/src/screens/DiagnosticsCard.tsx @@ -0,0 +1,93 @@ +import { useState } from "react"; +import { Check, Loader2, TriangleAlert, X } from "lucide-react"; +import { api, asUiError, type DiagCheck, type UiError } from "@/lib/api"; +import { Button } from "@/components/ui/button"; +import { Card } from "@/components/ui/card"; + +const ICON = { ok: Check, warn: TriangleAlert, fail: X } as const; +const TONE = { ok: "text-ok", warn: "text-warn", fail: "text-bad" } as const; +const WORD = { ok: "OK", warn: "Attention", fail: "Problem" } as const; + +export function DiagnosticsCard({ serverId }: { serverId: string }) { + const [checks, setChecks] = useState(null); + const [files, setFiles] = useState<{ path: string; kind: string }[] | null>(null); + const [busy, setBusy] = useState(null); + const [note, setNote] = useState(null); + const [error, setError] = useState(null); + + async function run(label: string, fn: () => Promise) { + setBusy(label); + setError(null); + setNote(null); + try { + await fn(); + } catch (e) { + setError(asUiError(e)); + } finally { + setBusy(null); + } + } + + const problems = checks?.filter((c) => c.level !== "ok").length ?? 0; + + return ( + +

Diagnostics

+

Looks for common problems. Nothing is changed.

+
+ + + +
+ + {checks && ( +
+

{problems === 0 ? "Everything looks good." : `${problems} thing${problems === 1 ? "" : "s"} to look at`}

+
    + {checks.map((c) => { + const Icon = ICON[c.level]; + return ( +
  • + +
    + {c.title} + — {WORD[c.level]} +

    {c.detail}

    +
    +
  • + ); + })} +
+
+ )} + + {files && ( +
+ {files.length === 0 ? ( +

All program files are intact.

+ ) : ( + <> +

{files.length} program file(s) differ from what was installed. Your own files are never listed here. "Check for updates" restores missing ones.

+
    + {files.map((f) => ( +
  • + {f.path} — {f.kind === "missing" ? "missing" : "changed"} +
  • + ))} +
+ + )} +
+ )} + {note &&

{note}

} + {error &&

{error.human.code === "unknown" ? error.technical : error.human.message}

} +
+ ); +} diff --git a/src/screens/SettingsHome.tsx b/src/screens/SettingsHome.tsx index 49d3f16..9b4558f 100644 --- a/src/screens/SettingsHome.tsx +++ b/src/screens/SettingsHome.tsx @@ -6,6 +6,7 @@ import { api, asUiError, type UiError, type UpdatePreview, type UpdateTxn } from import { Button } from "@/components/ui/button"; import { Card } from "@/components/ui/card"; import { ClientCard } from "@/screens/ClientCard"; +import { DiagnosticsCard } from "@/screens/DiagnosticsCard"; const ACTION_TEXT: Record = { create: "New file", @@ -113,6 +114,8 @@ export function SettingsHome({ serverId }: { serverId: string }) { + +

Server updates

Updates are checked for authenticity, backed up first, and can be undone.