From 4b513012307234e477a77cddaf6bf3316550d626 Mon Sep 17 00:00:00 2001 From: Nightwalker743 Date: Fri, 20 Nov 2026 18:19:46 -0600 Subject: [PATCH] Keep Playerbot Characters settings isolated across realms --- crates/coa-core/src/docker/lifecycle.rs | 11 +++ crates/coa-core/src/modules.rs | 32 ++++++++ crates/coa-core/src/modules/pbc.rs | 95 ++++++++++++++++++++--- crates/coa-core/src/modules/pbc/models.rs | 9 ++- crates/coa-core/src/multiworld.rs | 2 + crates/coa-core/src/update.rs | 2 +- 6 files changed, 137 insertions(+), 14 deletions(-) diff --git a/crates/coa-core/src/docker/lifecycle.rs b/crates/coa-core/src/docker/lifecycle.rs index c84ace0..44a64b4 100644 --- a/crates/coa-core/src/docker/lifecycle.rs +++ b/crates/coa-core/src/docker/lifecycle.rs @@ -665,6 +665,11 @@ fn game_args( a.extend(env("AC_UPDATES_ENABLE_DATABASES", "0")); if kind == GameKind::World { a.extend(["--volume".into(), format!("{}:{DATA}:ro", data.display())]); + let pbc = crate::modules::pbc::ASSET_DIR; + let assets = host.join(pbc); + if assets.is_dir() { + a.extend(["--volume".into(), format!("{}:/srv/{pbc}:ro", assets.display())]); + } let races = host.join("Data/dbc_races"); if races.is_dir() && races != data.join("dbc_races") { a.extend([ @@ -1066,6 +1071,8 @@ mod tests { #[test] fn a_first_start_creates_the_network_the_image_and_the_containers_in_order() { let (_d, root) = server("t1"); + let assets = root.join(crate::modules::pbc::ASSET_DIR); + fs::create_dir_all(&assets).unwrap(); let sim = Sim::new(); let o = start_all(&sim, &root); assert!(o.ok, "{}", o.output); @@ -1091,6 +1098,10 @@ mod tests { ["coa-t1-db", "coa-t1-world", "coa-t1-auth"], "database, then world, then auth" ); + let calls = sim.calls_of("run"); + let mount = format!("{}:/srv/Extras/PlayerbotCharacters:ro", assets.display()); + assert!(calls[1].args.windows(2).any(|w| w == ["--volume", mount.as_str()])); + assert!(!calls[0].args.contains(&mount) && !calls[2].args.contains(&mount)); let exec = sim.calls_of("exec"); assert_eq!( exec.len(), diff --git a/crates/coa-core/src/modules.rs b/crates/coa-core/src/modules.rs index 05d9bc7..92e175a 100644 --- a/crates/coa-core/src/modules.rs +++ b/crates/coa-core/src/modules.rs @@ -514,6 +514,12 @@ fn settings_in(cat: &[Entry], root: &Path, id: &str) -> Result> { }; Ok(effective .entries() + .filter(|(key, _)| { + id != "mod-pbc" + || !["PBC.ApiKey", "PBC.AltModelApiKey"] + .iter() + .any(|secret| key.eq_ignore_ascii_case(secret)) + }) .map(|(k, v)| { let mut val = fields .get(k) @@ -736,6 +742,32 @@ mod tests { assert_eq!(fs::read_to_string(dist).unwrap(), defaults); } + #[test] + fn playerbot_characters_preserves_legacy_connections_without_exposing_keys() { + let temp = tempfile::tempdir().unwrap(); + let root = temp.path(); + fs::create_dir_all(dir(root)).unwrap(); + let name = "playerbots_characters.conf"; + fs::write( + dir(root).join(name), + "[worldserver]\nPBC.Enable = 1\nPBC.BaseUrl = https://example.test/v1\nPBC.Model = legacy\nPBC.ApiKey = fixture-key\nPBC.AltModelApiKey = fixture-alt-key\n", + ).unwrap(); + fs::write( + dir(root).join(format!("{name}.dist")), + "[worldserver]\nPBC.Enable = 0\nPBC.DefaultConnection = \"\"\n", + ).unwrap(); + + crate::config::materialize_module_configs(root).unwrap(); + let config = read(&dir(root).join(name)).unwrap(); + assert_eq!(config.get("PBC.Enable"), Some("1")); + assert_eq!(config.get("PBC.DefaultConnection"), Some("\"\"")); + assert_eq!(config.get("PBC.ApiKey"), Some("fixture-key")); + assert_eq!(config.get("PBC.AltModelApiKey"), Some("fixture-alt-key")); + let visible = serde_json::to_string(&settings(root, "mod-pbc").unwrap()).unwrap(); + assert!(!visible.contains("fixture-key") && !visible.contains("fixture-alt-key")); + assert!(!pbc::load(root).unwrap().active); + } + #[test] fn time_is_time_card_settings_and_backups_match_the_module() { let temp = tempfile::tempdir().unwrap(); diff --git a/crates/coa-core/src/modules/pbc.rs b/crates/coa-core/src/modules/pbc.rs index 342b09b..dc1d744 100644 --- a/crates/coa-core/src/modules/pbc.rs +++ b/crates/coa-core/src/modules/pbc.rs @@ -5,14 +5,15 @@ use std::fs; use std::io::ErrorKind; use std::path::{Path, PathBuf}; +use crate::config::parser::{ConfFile, unquote}; +use crate::realms::{self, Mode}; use crate::{Error, Result, fsx}; pub mod models; const MODULE: &str = "mod-pbc"; const PATH_SETTING: &str = "PBC.DefaultConnection"; -const CONNECTION_FILE: &str = "Extras/PlayerbotCharacters/manager-connection.jsonc"; -const CONNECTION_SETTING: &str = "../Extras/PlayerbotCharacters/manager-connection.jsonc"; +pub(crate) const ASSET_DIR: &str = "Extras/PlayerbotCharacters"; #[derive(Clone, Copy, PartialEq, Eq, Deserialize, Serialize)] #[serde(rename_all = "lowercase")] @@ -58,8 +59,34 @@ pub struct Setup { pub connection: Option, } -fn connection_path(root: &Path) -> Result { - fsx::ensure_within(root, &root.join(CONNECTION_FILE)) +fn managed_connection(root: &Path) -> Result<(PathBuf, String)> { + let file = match realms::state(root)?.active { + Mode::Coa => "manager-connection.jsonc", + Mode::Wildcard => "manager-connection-wildcard.jsonc", + Mode::Reborn => "manager-connection-reborn.jsonc", + }; + let relative = format!("{ASSET_DIR}/{file}"); + let path = fsx::ensure_within(root, &root.join(&relative))?; + Ok((path, format!("../{relative}"))) +} + +/// Secondary worlds use their own Core directory. Point their packaged paths back to the shared assets. +pub(crate) fn rebase_packaged_paths(config: &str, root: &Path) -> Result { + let mut conf = ConfFile::parse_bytes(config.as_bytes())?; + let assets = root.join(ASSET_DIR); + for key in [ + PATH_SETTING, "PBC.UtilityConnection", "PBC.CondensationConnection", + "PBC.RelationshipUpdateConnection", "PBC.PromptsPath", "PBC.CharacterCardsPath", + "PBC.HttpServerFrontendPath", + ] { + let Some(relative) = conf.get(key).map(unquote) + .and_then(|path| path.strip_prefix("../Extras/PlayerbotCharacters/")) + else { continue }; + let Ok(path) = fsx::safe_join(&assets, relative) else { continue }; + let path = path.to_string_lossy().replace('\\', "/"); + conf.set(key, &format!("\"{path}\""), &[]); + } + Ok(conf.to_text()) } fn read_connection(path: &Path) -> Result>> { @@ -92,8 +119,9 @@ fn module_setting(root: &Path) -> Result { } pub fn load(root: &Path) -> Result { - let active = module_setting(root)?.trim_matches('"') == CONNECTION_SETTING; - let connection = read_connection(&connection_path(root)?)? + let (path, setting) = managed_connection(root)?; + let active = unquote(&module_setting(root)?) == setting; + let connection = read_connection(&path)? .as_deref() .map(parse) .transpose()? @@ -138,14 +166,14 @@ fn connection_key( } pub fn save(root: &Path, meta: &Path, update: ConnectionUpdate) -> Result { - let active = module_setting(root)?.trim_matches('"') == CONNECTION_SETTING; + let (path, setting) = managed_connection(root)?; + let active = unquote(&module_setting(root)?) == setting; let url = connection_url(&update.base_url)?; let base_url = url.as_str().trim_end_matches('/'); let model = update.model.trim(); if model.is_empty() || model.chars().any(char::is_control) { return Err(Error::Invalid("Enter a model name on a single line.".into())); } - let path = connection_path(root)?; let previous = read_connection(&path)?; let key = connection_key( update.api_type, base_url, update.api_key.as_deref(), update.remove_key, @@ -160,7 +188,7 @@ pub fn save(root: &Path, meta: &Path, update: ConnectionUpdate) -> Result }; fsx::atomic_write_private(&path, &serde_json::to_vec_pretty(&connection)?)?; if !active { - let changes = BTreeMap::from([(PATH_SETTING.into(), CONNECTION_SETTING.into())]); + let changes = BTreeMap::from([(PATH_SETTING.into(), setting)]); if let Err(error) = super::save_settings(root, meta, MODULE, &changes) { if let Some(bytes) = previous { fsx::atomic_write_private(&path, &bytes)?; @@ -212,4 +240,53 @@ mod tests { assert!(config.contains("PBC.Enable = 0")); assert!(!config.contains("replacement-key")); } + + #[test] + fn secondary_world_uses_the_shared_pbc_assets_and_keeps_custom_paths() { + let temp = tempfile::tempdir().unwrap(); + let config = "[worldserver]\nPBC.DefaultConnection = \"../Extras/PlayerbotCharacters/manager-connection.jsonc\"\nPBC.PromptsPath = \"../Extras/PlayerbotCharacters/prompts\"\nPBC.UtilityConnection = \"custom.jsonc\"\n"; + let result = rebase_packaged_paths(config, temp.path()).unwrap(); + let result = ConfFile::parse_bytes(result.as_bytes()).unwrap(); + let expected = temp.path().join(ASSET_DIR).to_string_lossy().replace('\\', "/"); + assert_eq!(result.get(PATH_SETTING).map(unquote), Some(format!("{expected}/manager-connection.jsonc").as_str())); + assert_eq!(result.get("PBC.PromptsPath").map(unquote), Some(format!("{expected}/prompts").as_str())); + assert_eq!(result.get("PBC.UtilityConnection").map(unquote), Some("custom.jsonc")); + } + + #[test] + fn each_realm_saves_its_own_model_connection() { + let temp = tempfile::tempdir().unwrap(); + let root = temp.path(); + let config = root.join("Core/configs/modules/playerbots_characters.conf"); + let meta = root.join("metadata"); + fsx::atomic_write(&config, b"[worldserver]\nPBC.Enable = 0\nPBC.DefaultConnection = \"\"\n").unwrap(); + let (coa_path, _) = managed_connection(root).unwrap(); + let endpoint = "https://example.test/v1"; + save(root, &meta, update(ApiType::Openai, endpoint, Some("coa-key"))).unwrap(); + let coa_config = fs::read(&config).unwrap(); + let coa_connection = fs::read(&coa_path).unwrap(); + + let state = root.join("Settings/realm-profile.json"); + let mut realm_state = realms::RealmState { + active: Mode::Wildcard, + wildcard_created: true, + ..Default::default() + }; + fsx::atomic_write_json(&state, &realm_state).unwrap(); + let (wildcard_path, _) = managed_connection(root).unwrap(); + assert_ne!(coa_path, wildcard_path); + assert!(load(root).unwrap().connection.is_none()); + let mut wildcard = update(ApiType::Openai, endpoint, None); + wildcard.model = "wildcard-model".into(); + let saved = save(root, &meta, wildcard).unwrap().connection.unwrap(); + assert!(!saved.has_key); + assert_eq!(saved.model, "wildcard-model"); + assert_eq!(fs::read(&coa_path).unwrap(), coa_connection); + + realm_state.active = Mode::Coa; + fsx::atomic_write_json(&state, &realm_state).unwrap(); + fsx::atomic_write(&config, &coa_config).unwrap(); + let restored = load(root).unwrap(); + assert!(restored.active && restored.connection.unwrap().has_key); + } } diff --git a/crates/coa-core/src/modules/pbc/models.rs b/crates/coa-core/src/modules/pbc/models.rs index c49f840..baf9e32 100644 --- a/crates/coa-core/src/modules/pbc/models.rs +++ b/crates/coa-core/src/modules/pbc/models.rs @@ -9,7 +9,7 @@ use std::time::{Duration, Instant}; use crate::{Error, Result}; -use super::{connection_key, connection_path, connection_url, module_setting, parse, read_connection, ApiType}; +use super::{connection_key, connection_url, managed_connection, module_setting, parse, read_connection, ApiType}; const TIMEOUT: Duration = Duration::from_secs(10); const MAX_PAGE_BYTES: u64 = 4 * 1024 * 1024; @@ -80,7 +80,8 @@ fn request_headers(api_type: ApiType, key: &str) -> Result { pub fn list(root: &Path, request: Request) -> Result> { module_setting(root)?; let mut url = connection_url(&request.base_url)?; - let previous = read_connection(&connection_path(root)?)?; + let (path, _) = managed_connection(root)?; + let previous = read_connection(&path)?; let key = connection_key( request.api_type, url.as_str().trim_end_matches('/'), request.api_key.as_deref(), request.remove_key, previous.as_deref().map(parse).transpose()?, @@ -233,7 +234,7 @@ mod tests { api_type: ApiType::Openai, base_url: base.clone(), model: "saved-model".into(), api_key: Some("fixture-secret".into()), remove_key: false, }).unwrap(); - let path = connection_path(root.path()).unwrap(); + let (path, _) = managed_connection(root.path()).unwrap(); let saved = fs::read(&path).unwrap(); let models = list(root.path(), request(ApiType::Openai, &base, None)).unwrap(); @@ -296,7 +297,7 @@ mod tests { api_type: ApiType::Openai, base_url: endpoint.clone(), model: "saved-model".into(), api_key: Some("fixture-secret".into()), remove_key: false, }).unwrap(); - let path = connection_path(root.path()).unwrap(); + let (path, _) = managed_connection(root.path()).unwrap(); let saved = fs::read(&path).unwrap(); let redirect = list(root.path(), request(ApiType::Openai, &endpoint, None)).err().unwrap(); assert!(redirect.to_string().contains("302")); diff --git a/crates/coa-core/src/multiworld.rs b/crates/coa-core/src/multiworld.rs index 7e42d2c..ffa851c 100644 --- a/crates/coa-core/src/multiworld.rs +++ b/crates/coa-core/src/multiworld.rs @@ -376,6 +376,8 @@ fn prepare(main: &Path, tree: Tree) -> Result { conf.set("CoA.AllowRemoteClients", "1", &[]); } conf.to_text() + } else if path == "Core/configs/modules/playerbots_characters.conf" { + crate::modules::pbc::rebase_packaged_paths(&text, main)? } else { text }; diff --git a/crates/coa-core/src/update.rs b/crates/coa-core/src/update.rs index b7464bf..c717274 100644 --- a/crates/coa-core/src/update.rs +++ b/crates/coa-core/src/update.rs @@ -2369,7 +2369,7 @@ mod tests { const CONNECTION: &str = "Extras/PlayerbotCharacters/manager-connection.jsonc"; const CARD: &str = "Extras/PlayerbotCharacters/cards/Companion.card.txt"; const PROMPT: &str = "Extras/PlayerbotCharacters/prompts/enUS/CharacterContext.custom.txt"; - let defaults = b"[worldserver]\nPBC.Enable = 0\nPBC.DefaultConnection = ../Extras/PlayerbotCharacters/my-connection.jsonc\n"; + let defaults = b"[worldserver]\nPBC.Enable = 0\nPBC.DefaultConnection = \"\"\n"; for configured in [false, true] { let w = world(&[(DIST, defaults), ("Extras/PlayerbotCharacters/cards/README.txt", b"Cards")], false); let host_config = b"[worldserver]\nPBC.Enable = 1\nPBC.DefaultConnection = ../Extras/PlayerbotCharacters/manager-connection.jsonc\n";