From f8301d7394e15e0599e6ecb1e5727a47c6d2a414 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: Mon, 5 Oct 2026 16:56:46 +0500 Subject: [PATCH] Read SQUID release settings and protect imported repack binaries --- .../20261005-imported-squid-warning.md | 7 ++ .../20261005-squid-release-metadata.md | 7 ++ changelog.d/20261005-squid-version-reports.md | 7 ++ crates/coa-core/src/diag.rs | 6 +- crates/coa-core/src/layout.rs | 1 + crates/coa-core/src/lib.rs | 2 + crates/coa-core/src/modules.rs | 39 +++++- crates/coa-core/src/package.rs | 18 ++- crates/coa-core/src/squid.rs | 119 ++++++++++++++++++ crates/coa-core/src/update.rs | 24 +++- src/i18n/locales/de.ts | 1 + src/i18n/locales/en.ts | 1 + src/i18n/locales/es.ts | 1 + src/i18n/locales/fr.ts | 1 + src/i18n/locales/ru.ts | 1 + src/i18n/locales/zh.ts | 1 + src/lib/api.ts | 2 + src/lib/moduleSettings.ts | 3 +- src/lib/squidSettings.ts | 8 +- src/screens/ImportServer.tsx | 2 +- src/screens/ModulesPage.tsx | 17 +-- src/screens/SettingsPage.tsx | 7 +- tools/check-module-settings.mjs | 5 + 23 files changed, 257 insertions(+), 23 deletions(-) create mode 100644 changelog.d/20261005-imported-squid-warning.md create mode 100644 changelog.d/20261005-squid-release-metadata.md create mode 100644 changelog.d/20261005-squid-version-reports.md create mode 100644 crates/coa-core/src/squid.rs diff --git a/changelog.d/20261005-imported-squid-warning.md b/changelog.d/20261005-imported-squid-warning.md new file mode 100644 index 0000000..6e7d7b1 --- /dev/null +++ b/changelog.d/20261005-imported-squid-warning.md @@ -0,0 +1,7 @@ +--- +area: manager +type: added +audience: admins +title: Imported SquidBots servers warn before replacing their original binary +--- +Imports explain that the original launcher and updater check the server binary hash. Updating that binary requires an explicit choice to keep or replace it. diff --git a/changelog.d/20261005-squid-release-metadata.md b/changelog.d/20261005-squid-release-metadata.md new file mode 100644 index 0000000..1bcfb69 --- /dev/null +++ b/changelog.d/20261005-squid-release-metadata.md @@ -0,0 +1,7 @@ +--- +area: manager +type: added +audience: admins +title: SquidBots settings follow the options shipped by the module +--- +New options, descriptions, groups and value limits appear automatically from the module settings file. Reset values follow its documented defaults; omitted keys retain their code defaults. diff --git a/changelog.d/20261005-squid-version-reports.md b/changelog.d/20261005-squid-version-reports.md new file mode 100644 index 0000000..0c37f3c --- /dev/null +++ b/changelog.d/20261005-squid-version-reports.md @@ -0,0 +1,7 @@ +--- +area: manager +type: added +audience: admins +title: SquidBots shows its bundled release and includes it in problem reports +--- +The Bots and Modules pages show the shipped release tag and commit when available. Problem reports include the same identifiers to help support diagnose the correct version. diff --git a/crates/coa-core/src/diag.rs b/crates/coa-core/src/diag.rs index 9447d42..431f097 100644 --- a/crates/coa-core/src/diag.rs +++ b/crates/coa-core/src/diag.rs @@ -199,6 +199,7 @@ pub fn export_package(root: &Path, meta_dir: &Path, manager_log: &Path, meta: &I "manager": crate::MANAGER_VERSION, "core": meta.core, "bots": meta.bots, + "squid_bots": crate::squid::release(root), "kind": meta.kind, "layout": meta.layout, "checks": report.checks, @@ -323,6 +324,8 @@ real error let d = tempfile::tempdir().unwrap(); let root = d.path().join("srv"); layout::testkit::fake_repack(&root); + fs::create_dir_all(root.join("Extras/SquidPlayerbots")).unwrap(); + fs::write(root.join("Extras/SquidPlayerbots/release.json"), r#"{"tag":"v1.8","commit":"48c4786a","password":"upstream-secret"}"#).unwrap(); 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"); @@ -340,6 +343,7 @@ real error 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")); + assert!(all.contains("v1.8") && all.contains("48c4786a")); + assert!(!all.contains("hunter2") && !all.contains("SECRETPW") && !all.contains("upstream-secret")); } } diff --git a/crates/coa-core/src/layout.rs b/crates/coa-core/src/layout.rs index 678c6df..f4359d3 100644 --- a/crates/coa-core/src/layout.rs +++ b/crates/coa-core/src/layout.rs @@ -315,6 +315,7 @@ pub fn scan(root: &Path) -> Result { (None, None) }; + if crate::squid::imported_repack(&root) { notes.push("import.squidRepackWarning".into()); } Ok(ScanReport { path: root.to_string_lossy().into_owned(), classification, diff --git a/crates/coa-core/src/lib.rs b/crates/coa-core/src/lib.rs index 7b1cc55..38502dc 100644 --- a/crates/coa-core/src/lib.rs +++ b/crates/coa-core/src/lib.rs @@ -46,3 +46,5 @@ pub mod srp6; pub use error::{Error, ErrorCode, Result}; pub const MANAGER_VERSION: &str = env!("CARGO_PKG_VERSION"); + +pub mod squid; diff --git a/crates/coa-core/src/modules.rs b/crates/coa-core/src/modules.rs index 20585f3..9564696 100644 --- a/crates/coa-core/src/modules.rs +++ b/crates/coa-core/src/modules.rs @@ -87,6 +87,7 @@ fn truthy(v: &str) -> bool { pub struct ModuleView { pub id: String, pub name: String, + pub version: Option, pub description: BTreeMap, pub repo: String, /// The module's configuration is present on this server (otherwise it is not part of this server build). @@ -137,7 +138,11 @@ fn list_in(cat: &[Entry], root: &Path) -> Vec { !e.switchable || read(&conf).or_else(|| read(&dist)).and_then(|c| c.get(&e.enable_key).map(truthy)).unwrap_or(e.default_on) }; let blocked = wildcard && matches!(e.id.as_str(), "companions" | "playerbots"); + let version = if e.id == "playerbots" { crate::squid::release(root).map(|release| { + [release.tag, release.commit.map(|commit| commit.chars().take(8).collect())].into_iter().flatten().collect::>().join(" · ") + }) } else { None }; ModuleView { + version, compatibility: if blocked { "unsupported" } else if wildcard && e.id != "client-compat" { "experimental" } else { "compatible" }.into(), id: e.id, name: e.name, @@ -243,13 +248,14 @@ fn set_enabled_in(cat: &[Entry], root: &Path, meta: &Path, id: &str, on: bool) - Ok(()) } -#[derive(Debug, Serialize, PartialEq, Eq)] +#[derive(Debug, Serialize, PartialEq)] pub struct Setting { pub key: String, pub value: String, pub default: Option, /// The documentation the module ships above the setting. pub doc: String, + pub field: Option, } /// Every active setting of the module with its current value, its documented default and its description. @@ -263,6 +269,7 @@ fn settings_in(cat: &[Entry], root: &Path, id: &str) -> Result> { let conf = dir(root).join(&name); let dist = read(&dir(root).join(format!("{name}.dist"))); let active = read(&conf).or_else(|| dist.clone()).ok_or_else(|| Error::Invalid("This module is not part of this server.".into()))?; + let fields = if id == "playerbots" { crate::squid::fields(root)? } else { Default::default() }; let mut effective = active.clone(); if let Some(defaults) = &dist { for (key, value) in defaults.entries() { @@ -275,8 +282,9 @@ fn settings_in(cat: &[Entry], root: &Path, id: &str) -> Result> { .entries() .map(|(k, v)| Setting { key: k.to_string(), - value: v.to_string(), - default: dist.as_ref().and_then(|d| d.get(k)).map(str::to_string), + value: fields.get(k).and_then(|field| field.default_if_missing.as_ref()).filter(|_| active.get(k).is_none()).and_then(crate::squid::scalar).unwrap_or_else(|| v.to_string()), + default: fields.get(k).and_then(|field| crate::squid::scalar(&field.default)).or_else(|| dist.as_ref().and_then(|d| d.get(k)).map(str::to_string)), + field: fields.get(k).cloned(), doc: dist.as_ref().map(|d| d.doc_for(k)).filter(|d| !d.is_empty()).unwrap_or_else(|| active.doc_for(k)).join(" "), }) .collect()) @@ -293,9 +301,11 @@ fn save_settings_in(cat: &[Entry], root: &Path, meta: &Path, id: &str, changes: let conf = active_file(root, &e)?; let mut file = ConfFile::parse_bytes(&fs::read(&conf)?)?; let dist = read(&dir(root).join(format!("{}.dist", conf_name(root, &e)))); + let fields = if id == "playerbots" { crate::squid::fields(root)? } else { Default::default() }; let mut changed = Vec::new(); for (key, value) in changes { let value = value.trim(); + if let Some(field) = fields.get(key) { crate::squid::validate(field, value)?; } if e.switchable && key == &e.enable_key { return Err(Error::Invalid("Use the module switch to turn this module on or off.".into())); } @@ -374,6 +384,27 @@ mod tests { (root, meta) } + #[test] + fn squid_missing_keys_use_code_defaults_and_saves_enforce_json_ranges() { + let d = tempfile::tempdir().unwrap(); + let root = d.path(); + fs::create_dir_all(dir(root)).unwrap(); + fs::write(dir(root).join("playerbots.conf"), "AiPlayerbot.Enabled = 0\n").unwrap(); + fs::write(dir(root).join("playerbots.conf.dist"), "AiPlayerbot.Enabled = 0\nAiPlayerbot.MinRandomBots = 500\n").unwrap(); + fs::write(dir(root).join("playerbots.conf.settings.json"), r#"{"format":1,"groups":{"population":"Population"},"settings":[{"key":"AiPlayerbot.MinRandomBots","type":"int","group":"population","title":"Minimum bots","description":"Lower bound","default":500,"default_if_missing":50,"min":0,"max":5000}]}"#).unwrap(); + let cat = catalog(); + let options = settings_in(&cat, root, "playerbots").unwrap(); + let option = options.iter().find(|setting| setting.key == "AiPlayerbot.MinRandomBots").unwrap(); + assert_eq!(option.value, "50"); + assert_eq!(option.default.as_deref(), Some("500")); + assert_eq!(option.field.as_ref().unwrap().group_title.as_deref(), Some("Population")); + let before = fs::read(dir(root).join("playerbots.conf")).unwrap(); + assert!(save_settings_in(&cat, root, root, "playerbots", &BTreeMap::from([("AiPlayerbot.MinRandomBots".into(), "5001".into())])).is_err()); + assert_eq!(fs::read(dir(root).join("playerbots.conf")).unwrap(), before); + save_settings_in(&cat, root, root, "playerbots", &BTreeMap::from([("AiPlayerbot.MinRandomBots".into(), "42".into())])).unwrap(); + assert_eq!(settings_in(&cat, root, "playerbots").unwrap().iter().find(|setting| setting.key == "AiPlayerbot.MinRandomBots").unwrap().value, "42"); + } + #[test] fn bot_systems_are_mutually_exclusive_in_both_directions_and_manual_configs() { let d = tempfile::tempdir().unwrap(); @@ -456,7 +487,7 @@ mod tests { let (root, meta) = server(d.path()); let s = settings_in(&test_catalog(), &root, "war-games").unwrap(); assert_eq!(s.len(), 2); - assert_eq!(s[1], Setting { key: "WarGames.ChallengeSeconds".into(), value: "60".into(), default: Some("60".into()), doc: "How long a challenge stays open.".into() }); + assert_eq!(s[1], Setting { key: "WarGames.ChallengeSeconds".into(), value: "60".into(), default: Some("60".into()), doc: "How long a challenge stays open.".into(), field: None }); assert_eq!(s[0].doc, "Turns War Games on. Second line."); let ok = BTreeMap::from([("WarGames.ChallengeSeconds".to_string(), "90".to_string())]); diff --git a/crates/coa-core/src/package.rs b/crates/coa-core/src/package.rs index e03b745..9104045 100644 --- a/crates/coa-core/src/package.rs +++ b/crates/coa-core/src/package.rs @@ -41,7 +41,7 @@ pub fn excluded(rel: &str) -> bool { || l == "mysql/my.ini" || l == "mysql/mysql.pid" || l == "mysql/data.7z" - || l.starts_with("core/configs/") && !l.ends_with(".dist") // generated at first start from Settings templates + || l.starts_with("core/configs/") && !l.ends_with(".dist") && l != "core/configs/modules/playerbots.conf.settings.json" // generated at first start from Settings templates || name.ends_with(".pdb") || name.ends_with(".bak") || name.ends_with(".log") @@ -56,7 +56,7 @@ fn policy_for(rel: &str) -> (Owner, ReplacePolicy) { let l = rel.to_lowercase(); if l.starts_with("_migrations/") { (Owner::Core, ReplacePolicy::NeverTouch) // staged for the migration runner, never copied into the server - } else if l.ends_with(".dist") { + } else if l.ends_with(".dist") || l == "core/configs/modules/playerbots.conf.settings.json" { (Owner::Core, ReplacePolicy::Replace) } else if l.starts_with("mysql/data/") { (Owner::User, ReplacePolicy::NeverTouch) @@ -370,6 +370,20 @@ mod tests { v } + #[test] + fn upstream_settings_metadata_ships_and_updates_but_active_configs_stay_private() { + let d = tempfile::tempdir().unwrap(); + let src = d.path().join("src"); + fs::create_dir_all(src.join("Core/configs/modules")).unwrap(); + fs::write(src.join("Core/configs/modules/playerbots.conf.settings.json"), "{}\n").unwrap(); + fs::write(src.join("Core/configs/modules/playerbots.conf"), "PlayerbotsDatabaseInfo = private\n").unwrap(); + let out = d.path().join("package"); + let manifest = build(&src, &out, &BuildOptions { kind: Kind::Update, version: "1.0.0".into(), core_commit: None, built_at: "test".into(), part_size: 1 << 20, bots_commit: None, migrations: vec![] }, &|_| {}).unwrap(); + assert_eq!(manifest.files.len(), 1); + assert_eq!(manifest.files[0].path, "Core/configs/modules/playerbots.conf.settings.json"); + assert_eq!(manifest.files[0].policy, ReplacePolicy::Replace); + } + fn source() -> (tempfile::TempDir, PathBuf) { let d = tempfile::tempdir().unwrap(); let src = d.path().join("src"); diff --git a/crates/coa-core/src/squid.rs b/crates/coa-core/src/squid.rs new file mode 100644 index 0000000..be27265 --- /dev/null +++ b/crates/coa-core/src/squid.rs @@ -0,0 +1,119 @@ +use std::path::Path; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Serialize, PartialEq, Eq)] +pub struct Release { + pub tag: Option, + pub commit: Option, +} + +pub fn imported_repack(root: &Path) -> bool { + root.join("CoA-Bots/release.json").is_file() +} + +pub fn release(root: &Path) -> Option { + for name in ["Extras/SquidPlayerbots/release.json", "Core/configs/modules/playerbots.conf.settings.json", "CoA-Bots/release.json"] { + let Ok(bytes) = std::fs::read(root.join(name)) else { continue; }; + if bytes.len() > 1024 * 1024 { continue; } + let Ok(json) = serde_json::from_slice::(&bytes) else { continue; }; + let safe = |key: &str| json.get(key).and_then(|value| value.as_str()) + .filter(|value| value.len() <= 80 && value.chars().all(|c| c.is_ascii_alphanumeric() || "._-".contains(c))).map(str::to_owned); + let tag = safe("tag").or_else(|| safe("version")); + let commit = safe("commit").filter(|value| value.len() >= 7 && value.len() <= 40 && value.chars().all(|c| c.is_ascii_hexdigit())); + if tag.is_some() || commit.is_some() { return Some(Release { tag, commit }); } + } + None +} + +#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)] +pub struct Field { + pub key: String, + #[serde(rename = "type")] + pub kind: String, + pub title: String, + pub description: String, + #[serde(default)] + pub group: String, + #[serde(default)] + pub group_title: Option, + pub default: serde_json::Value, + #[serde(default)] + pub default_if_missing: Option, + pub min: Option, + pub max: Option, +} + +#[derive(Deserialize)] +struct Settings { + format: u32, + settings: Vec, + #[serde(default)] + groups: std::collections::BTreeMap, +} + +pub fn fields(root: &Path) -> crate::Result> { + let path = root.join("Core/configs/modules/playerbots.conf.settings.json"); + if !path.is_file() { return Ok(Default::default()); } + let bytes = std::fs::read(path)?; + let invalid = || crate::Error::Invalid("The SquidBots settings JSON is invalid or uses an unsupported format.".into()); + if bytes.len() > 1024 * 1024 { return Err(invalid()); } + let settings: Settings = serde_json::from_slice(&bytes).map_err(|_| invalid())?; + if settings.format != 1 { return Err(invalid()); } + let mut fields = std::collections::BTreeMap::new(); + for mut field in settings.settings { + field.group_title = settings.groups.get(&field.group).cloned(); + if !matches!(field.kind.as_str(), "bool" | "int" | "float" | "string") + || field.key.len() > 200 || field.key.is_empty() + || !field.key.chars().all(|c| c.is_ascii_alphanumeric() || "._".contains(c)) + || field.min.zip(field.max).is_some_and(|(min,max)| min > max) + || scalar(&field.default).is_none() + || field.default_if_missing.as_ref().is_some_and(|value| scalar(value).is_none()) + || fields.contains_key(&field.key) { return Err(invalid()); } + fields.insert(field.key.clone(), field); + } + Ok(fields) +} + +pub fn scalar(value: &serde_json::Value) -> Option { + match value { + serde_json::Value::Bool(value) => Some(if *value { "1" } else { "0" }.into()), + serde_json::Value::String(value) => Some(value.clone()), + serde_json::Value::Number(value) => Some(value.to_string()), + _ => None, + } +} + +pub fn validate(field: &Field, value: &str) -> crate::Result<()> { + let valid = match field.kind.as_str() { + "bool" => matches!(value, "0" | "1"), + "int" | "float" => value.parse::().is_ok_and(|number| number.is_finite() + && (field.kind != "int" || number.fract() == 0.0) + && field.min.is_none_or(|min| number >= min) && field.max.is_none_or(|max| number <= max)), + "string" => true, + _ => false, + }; + if valid { Ok(()) } else { Err(crate::Error::Invalid(format!("{} must match its documented SquidBots type and range.", field.key))) } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn upstream_settings_preserve_types_ranges_and_distinct_defaults() { + let root = tempfile::tempdir().unwrap(); + crate::fsx::atomic_write(&root.path().join("Core/configs/modules/playerbots.conf.settings.json"), br#"{"format":1,"settings":[{"key":"AiPlayerbot.MinRandomBots","type":"int","group":"population","title":"Minimum bots","description":"Lower bound","default":500,"default_if_missing":50,"min":0,"max":5000}]}"#).unwrap(); + let fields = fields(root.path()).unwrap(); + let field = &fields["AiPlayerbot.MinRandomBots"]; + assert_eq!(scalar(&field.default).as_deref(), Some("500")); + assert_eq!(scalar(field.default_if_missing.as_ref().unwrap()).as_deref(), Some("50")); + assert!(validate(field, "5000").is_ok()); + for value in ["5001", "-1", "0.5", "NaN"] { assert!(validate(field, value).is_err()); } + } + #[test] + fn diagnostics_only_expose_release_identifiers() { + let root = tempfile::tempdir().unwrap(); + crate::fsx::atomic_write(&root.path().join("CoA-Bots/release.json"), br#"{"tag":"v1.8","commit":"48c4786a","password":"secret"}"#).unwrap(); + assert!(imported_repack(root.path())); + assert_eq!(release(root.path()).unwrap(), Release { tag: Some("v1.8".into()), commit: Some("48c4786a".into()) }); + } +} diff --git a/crates/coa-core/src/update.rs b/crates/coa-core/src/update.rs index 35412ff..3ef3b09 100644 --- a/crates/coa-core/src/update.rs +++ b/crates/coa-core/src/update.rs @@ -173,7 +173,13 @@ pub fn plan(root: &Path, meta: &InstallMeta, manifest: &Manifest, resolutions: & } (_, Some(c)) if c.eq_ignore_ascii_case(&f.sha256) => (Action::Skip, Some("already up to date".into())), (ReplacePolicy::Replace | ReplacePolicy::ReplaceIfPristine, Some(c)) => { - if recorded.map(|r| r.eq_ignore_ascii_case(c)).unwrap_or(false) { + if f.path == "Core/worldserver.exe" && meta.kind == crate::registry::InstallKind::Imported && crate::squid::imported_repack(root) { + match resolutions.get(&f.path) { + Some(Resolution::Replace) => (Action::Replace, Some("Replacing this binary stops the original SquidBots launcher/updater from accepting its hash.".into())), + Some(Resolution::Keep) => (Action::Skip, Some("kept the original SquidBots binary".into())), + None => (Action::Conflict, Some("This SquidBots repack verifies its worldserver hash. Replacing it stops Start_All_Bots/coa_update from working. Choose explicitly whether to replace this binary.".into())), + } + } else if recorded.map(|r| r.eq_ignore_ascii_case(c)).unwrap_or(false) { (Action::Replace, None) } else if f.policy == ReplacePolicy::ReplaceIfPristine { (Action::Skip, Some("modified outside CoA Server Manager; kept".into())) @@ -865,6 +871,22 @@ mod tests { fs::read(w.root.join(rel)).unwrap() } + #[test] + fn imported_squid_repack_requires_a_decision_even_for_pristine_worldserver() { + let w = world(&[], false); + write(&w.root, "CoA-Bots/release.json", b"{}"); + let (_, mut meta) = MetaDir::open(&w.meta).unwrap(); + meta.kind = InstallKind::Imported; + let manifest: Manifest = serde_json::from_slice(&fs::read(w.pkg.join("manifest.json")).unwrap()).unwrap(); + let action = |resolutions: BTreeMap| { + plan(&w.root, &meta, &manifest, &resolutions, None).unwrap().into_iter().find(|item| item.path == "Core/worldserver.exe").unwrap().action + }; + assert_eq!(action(BTreeMap::new()), Action::Conflict); + assert_eq!(action(BTreeMap::from([("Core/worldserver.exe".into(), Resolution::Keep)])), Action::Skip); + assert_eq!(action(BTreeMap::from([("Core/worldserver.exe".into(), Resolution::Replace)])), Action::Replace); + assert_eq!(read(&w, "Core/worldserver.exe"), b"world-v1"); + } + #[test] fn happy_path_replaces_creates_merges_and_records_ownership() { let w = world(&[], false); diff --git a/src/i18n/locales/de.ts b/src/i18n/locales/de.ts index b9330d3..e825ce1 100644 --- a/src/i18n/locales/de.ts +++ b/src/i18n/locales/de.ts @@ -75,6 +75,7 @@ const de: Partial> = { "btn.restart": "Neustart", "btn.startWithoutUpdate": "Ohne Update starten", "btn.playWithoutUpdate": "Ohne Update spielen", + "import.squidRepackWarning": "Dieses SquidBots-Repack prüft den Worldserver-Hash. Ein Austausch kann Start_All_Bots und coa_update deaktivieren. Updates fragen vorher nach.", "btn.play": "SPIELEN", "btn.startPlay": "STARTEN & SPIELEN", "btn.startingCaps": "STARTET …", diff --git a/src/i18n/locales/en.ts b/src/i18n/locales/en.ts index fe566ef..d63d4b4 100644 --- a/src/i18n/locales/en.ts +++ b/src/i18n/locales/en.ts @@ -106,6 +106,7 @@ const en = { "btn.restart": "Restart", "btn.startWithoutUpdate": "Start without updating", "btn.playWithoutUpdate": "Play without updating", + "import.squidRepackWarning": "This SquidBots repack checks its worldserver hash. Replacing the binary can stop Start_All_Bots and coa_update from working. Updates will ask before replacing it.", "btn.play": "PLAY", "btn.startPlay": "START & PLAY", "btn.startingCaps": "STARTING…", diff --git a/src/i18n/locales/es.ts b/src/i18n/locales/es.ts index a8ee876..c68bcfa 100644 --- a/src/i18n/locales/es.ts +++ b/src/i18n/locales/es.ts @@ -75,6 +75,7 @@ const es: Partial> = { "btn.restart": "Reiniciar", "btn.startWithoutUpdate": "Iniciar sin actualizar", "btn.playWithoutUpdate": "Jugar sin actualizar", + "import.squidRepackWarning": "Este repack SquidBots verifica el hash del servidor. Sustituirlo puede impedir el funcionamiento de Start_All_Bots y coa_update. Se solicitará confirmación.", "btn.play": "JUGAR", "btn.startPlay": "INICIAR Y JUGAR", "btn.startingCaps": "INICIANDO…", diff --git a/src/i18n/locales/fr.ts b/src/i18n/locales/fr.ts index 1b7e1c5..6f0ab00 100644 --- a/src/i18n/locales/fr.ts +++ b/src/i18n/locales/fr.ts @@ -75,6 +75,7 @@ const fr: Partial> = { "btn.restart": "Redémarrer", "btn.startWithoutUpdate": "Démarrer sans mise à jour", "btn.playWithoutUpdate": "Jouer sans mise à jour", + "import.squidRepackWarning": "Ce repack SquidBots vérifie le hash du serveur. Le remplacer peut empêcher Start_All_Bots et coa_update de fonctionner. Une confirmation sera demandée.", "btn.play": "JOUER", "btn.startPlay": "DÉMARRER ET JOUER", "btn.startingCaps": "DÉMARRAGE…", diff --git a/src/i18n/locales/ru.ts b/src/i18n/locales/ru.ts index 5c8b38e..bef5677 100644 --- a/src/i18n/locales/ru.ts +++ b/src/i18n/locales/ru.ts @@ -106,6 +106,7 @@ const ru: Partial> = { "btn.restart": "Перезапустить", "btn.startWithoutUpdate": "Запустить без обновления", "btn.playWithoutUpdate": "Играть без обновления", + "import.squidRepackWarning": "Этот репак SquidBots проверяет хеш worldserver. Замена файла может нарушить работу Start_All_Bots и coa_update. Перед заменой менеджер запросит ваше решение.", "btn.play": "ИГРАТЬ", "btn.startPlay": "ЗАПУСТИТЬ И ИГРАТЬ", "btn.startingCaps": "ЗАПУСК…", diff --git a/src/i18n/locales/zh.ts b/src/i18n/locales/zh.ts index 9f063f8..45c397a 100644 --- a/src/i18n/locales/zh.ts +++ b/src/i18n/locales/zh.ts @@ -87,6 +87,7 @@ const zh = { "btn.restart": "重启", "btn.startWithoutUpdate": "不更新启动服务器", "btn.playWithoutUpdate": "不更新开始游戏", + "import.squidRepackWarning": "此 SquidBots 整合包会检查 worldserver 哈希。替换程序可能导致 Start_All_Bots 和 coa_update 无法运行。更新前会要求您选择。", "btn.play": "开始游戏", "btn.startPlay": "启动并开始游戏", "btn.startingCaps": "正在启动…", diff --git a/src/lib/api.ts b/src/lib/api.ts index afa8b38..554608e 100644 --- a/src/lib/api.ts +++ b/src/lib/api.ts @@ -193,6 +193,7 @@ export interface RealmProfile { export interface ModuleView { id: string; name: string; + version?: string | null; description: Record; repo: string; /** the module is part of this server build (its configuration exists) */ @@ -216,6 +217,7 @@ export interface ModuleSetting { value: string; default: string | null; doc: string; + field?: { key: string; type: string; title: string; description: string; group: string; group_title?: string | null; min?: number | null; max?: number | null } | null; } export interface AllSetting { diff --git a/src/lib/moduleSettings.ts b/src/lib/moduleSettings.ts index c43362e..ca1cca5 100644 --- a/src/lib/moduleSettings.ts +++ b/src/lib/moduleSettings.ts @@ -173,7 +173,8 @@ for (const [category, categoryNames] of Object.entries(auctionCategories)) { { min: 0, max: 1000, advanced: true }, ); } -export function moduleField(key: string, locale: Locale): ModuleField | undefined { +export function moduleField(key: string, locale: Locale, metadata?: ModuleSetting["field"]): ModuleField | undefined { + if (metadata) return { title: metadata.title, description: metadata.description, type: metadata.type, category: metadata.group, advanced: false, min: metadata.min ?? undefined, max: metadata.max ?? undefined }; const field = fields.find(f => f.key === key); if (field) return { ...field, title: text(field.title, locale), description: text(field.description, locale), category: "general", advanced: field.advanced ?? false, step: field.type === "range" ? 0.05 : undefined, options: field.options?.map(o => ({ value: o.value, label: text(o.label, locale) })) }; const existing = [...bots.settings, ...server.settings].find(s => s.key === key); diff --git a/src/lib/squidSettings.ts b/src/lib/squidSettings.ts index b7a2fd7..ebe18d9 100644 --- a/src/lib/squidSettings.ts +++ b/src/lib/squidSettings.ts @@ -24,7 +24,7 @@ function group(key: string, curated: boolean) { /** Use the same settings screen as Companions, backed only by shipped SQUID options. */ export function squidSettingsView(items: ModuleSetting[], locale: Locale): SettingsView { const settings: SettingView[] = items.filter(s => s.key !== "AiPlayerbot.Enabled" && !s.key.startsWith("PlayerbotsDatabase") && !s.key.startsWith("Playerbots.Updates.")).map(s => { - const field = moduleField(s.key, locale); + const field = moduleField(s.key, locale, s.field); const type = field?.type === "bool" || field?.type === "int" || field?.type === "float" || field?.type === "enum" ? field.type : "string"; const decode = (raw: string): JsonValue => { const value = raw.trim().replace(/^"|"$/g, ""); @@ -35,11 +35,13 @@ export function squidSettingsView(items: ModuleSetting[], locale: Locale): Setti const value = decode(s.value), defaultValue = decode(s.default ?? s.value); return { key: s.key, type, title: field?.title ?? s.key, description: field?.description ?? s.doc, - category: group(s.key, !!field), advanced: !field || !!field.advanced, + category: s.field?.group ? "squid." + s.field.group : group(s.key, !!field), advanced: !field || !!field.advanced, min: field?.min, max: field?.max, options: field?.options ?? [], value, default: defaultValue, is_default: value === defaultValue, present: true, problem: null, drift: false, restartRequired: "world", dangerous: false, }; }); - return { scope: "bots", categories: groups.map(g => ({ id: g.id, title: g.titles[languages.indexOf(locale)] })), settings, unknown_keys: 0, drift_keys: [], files: ["Core/configs/modules/playerbots.conf"] }; + const categories = new Map(groups.map(g => [g.id, g.titles[languages.indexOf(locale)]])); + for (const item of items) if (item.field?.group) categories.set("squid." + item.field.group, item.field.group_title ?? categories.get("squid." + item.field.group) ?? item.field.group); + return { scope: "bots", categories: [...categories].map(([id, title]) => ({ id, title })), settings, unknown_keys: 0, drift_keys: [], files: ["Core/configs/modules/playerbots.conf"] }; } diff --git a/src/screens/ImportServer.tsx b/src/screens/ImportServer.tsx index 39524c1..2267fba 100644 --- a/src/screens/ImportServer.tsx +++ b/src/screens/ImportServer.tsx @@ -145,7 +145,7 @@ export function ImportServer(props: { {report.notes.map((n) => (

- {n} + {hasKey(n) ? t(n as Key) : n}

))} diff --git a/src/screens/ModulesPage.tsx b/src/screens/ModulesPage.tsx index c3da379..cce23bc 100644 --- a/src/screens/ModulesPage.tsx +++ b/src/screens/ModulesPage.tsx @@ -133,6 +133,7 @@ export function ModulesPage({ serverId, onChanged }: { serverId: string; onChang

{m.name}

+ {m.version && {m.version}}

{m.description[locale] ?? m.description.en}

@@ -210,7 +211,7 @@ function ModuleSettings({ serverId, module, onSaved }: { serverId: string; modul async function save() { const errors: Record = {}; for (const [key, value] of Object.entries(edits)) { - const field = moduleField(key, locale); + const field = moduleField(key, locale, items?.find(item => item.key === key)?.field); if (field && ["int", "float", "range"].includes(field.type)) { const number = Number(value); const message = !value.trim() || !Number.isFinite(number) ? t("set.enterNumber") @@ -248,13 +249,13 @@ function ModuleSettings({ serverId, module, onSaved }: { serverId: string; modul return next; }); const available = items?.filter(s => s.key !== moduleEnableKey(module.id)) ?? []; - const advancedCount = available.filter(s => !auctionWeightKey(s.key) && (!moduleField(s.key, locale) || moduleField(s.key, locale)?.advanced)).length; + const advancedCount = available.filter(s => !auctionWeightKey(s.key) && (!moduleField(s.key, locale, s.field) || moduleField(s.key, locale, s.field)?.advanced)).length; const visible = available.filter(s => { if (module.id === "ah-bot" && auctionWeightKey(s.key)) return false; - const field = moduleField(s.key, locale); + const field = moduleField(s.key, locale, s.field); if (!advanced && !query.trim() && (!field || field.advanced)) return false; - const title = field ? sx.title({ key: s.key, title: field.title }) : s.key; - const description = field ? sx.description({ key: s.key, description: field.description }) : s.doc; + const title = field ? (s.field ? field.title : sx.title({ key: s.key, title: field.title })) : s.key; + const description = field ? (s.field ? field.description : sx.description({ key: s.key, description: field.description })) : s.doc; return `${title} ${description} ${s.key}`.toLocaleLowerCase(locale).includes(query.trim().toLocaleLowerCase(locale)); }); return ( @@ -278,9 +279,9 @@ function ModuleSettings({ serverId, module, onSaved }: { serverId: string; modul {items && !visible.length && !available.some(s => module.id === "ah-bot" && auctionWeightKey(s.key)) &&

{t(available.length ? "all.none" : "mod.noSettings")}

}
    {visible.map((s) => { - const field = moduleField(s.key, locale); - const title = field ? sx.title({ key: s.key, title: field.title }) : s.key; - const description = field ? sx.description({ key: s.key, description: field.description }) : s.doc; + const field = moduleField(s.key, locale, s.field); + const title = field ? (s.field ? field.title : sx.title({ key: s.key, title: field.title })) : s.key; + const description = field ? (s.field ? field.description : sx.description({ key: s.key, description: field.description })) : s.doc; const value = edits[s.key] ?? s.value; const normalized = canonicalModuleValue(s.key, value); const options = field?.options ?? []; diff --git a/src/screens/SettingsPage.tsx b/src/screens/SettingsPage.tsx index 29bce36..6d03c6e 100644 --- a/src/screens/SettingsPage.tsx +++ b/src/screens/SettingsPage.tsx @@ -178,12 +178,15 @@ export function SettingsPage(props: { serverId: string; scope: Scope; botModule? const [raw, setRaw] = useState(null); const [rawEdits, setRawEdits] = useState>({}); const [onlyChanged, setOnlyChanged] = useState(false); + const [squidVersion, setSquidVersion] = useState(null); const [cols, setCols] = useState([]); const [colEdits, setColEdits] = useState>({}); const load = useCallback(async () => { try { - const v = squid ? squidSettingsView(await api.moduleSettings(serverId, "playerbots"), locale) : await api.settings(serverId, scope); + const data = squid ? await Promise.all([api.moduleSettings(serverId, "playerbots"), api.modulesList(serverId)]) : null; + if (data) setSquidVersion(data[1].find(module => module.id === "playerbots")?.version ?? null); + const v = data ? squidSettingsView(data[0], locale) : await api.settings(serverId, scope); setView(v); setDraft({}); setErrors({}); @@ -363,7 +366,7 @@ export function SettingsPage(props: { serverId: string; scope: Scope; botModule? return (

    {props.title}

    -

    {squid ? "SQUID’s Playerbots" : props.question}

    +

    {squid ? `SQUID’s Playerbots${squidVersion ? " · " + squidVersion : ""}` : props.question}

    {scope === "bots" && !squid && } diff --git a/tools/check-module-settings.mjs b/tools/check-module-settings.mjs index ea6d6d9..2fff933 100644 --- a/tools/check-module-settings.mjs +++ b/tools/check-module-settings.mjs @@ -67,3 +67,8 @@ for (const locale of ["en", "ru", "de", "fr", "es", "zh"]) { if (view.categories.some(c => !c.title)) throw new Error("SQUID categories must be translated"); } console.log("SQUID Bots view: typed values, upstream defaults, categories and hidden managed settings verified"); + +const upstream = squidSettingsView([{ key: "AiPlayerbot.FutureOption", value: "2.5", default: "1", doc: "old description", field: {key:"AiPlayerbot.FutureOption",type:"float",title:"Future option",description:"From the release JSON",group:"new-group",group_title:"New activity",min:0,max:3} }], "ru"); +const future = upstream.settings[0]; +if (future.title !== "Future option" || future.description !== "From the release JSON" || future.type !== "float" || future.min !== 0 || future.max !== 3 || future.advanced || future.category !== "squid.new-group" || upstream.categories.find(c=>c.id===future.category)?.title !== "New activity") throw new Error("New upstream JSON options must appear without handwritten definitions"); +console.log("Upstream metadata: new fields, titles, ranges and arbitrary groups verified");