diff --git a/Cargo.lock b/Cargo.lock index 98982b9..c7f0c2d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -548,6 +548,7 @@ name = "coa-server-manager" version = "0.6.6" dependencies = [ "coa-core", + "coa-registry-proto", "serde", "serde_json", "tauri", diff --git a/crates/coa-core/src/portable/service/engine.rs b/crates/coa-core/src/portable/service/engine.rs index a17a5ca..7837588 100644 --- a/crates/coa-core/src/portable/service/engine.rs +++ b/crates/coa-core/src/portable/service/engine.rs @@ -577,6 +577,21 @@ impl PortableService { merged.expect("an operation") } + /// The same compatibility check for a realm that is only known by what it advertises (a row of the public list): the Phase 7/8 rules evaluated against the + /// advertised capabilities, with nothing written anywhere. What cannot be known from an advertisement (the realm's client tables) is not assumed. + pub fn preflight_advert(&mut self, character: &str, capabilities: &serde_json::Value) -> Res { + let cid = self.cid(character)?; + let caps = RealmCapabilities::from_json(capabilities.to_string().as_bytes()).map_err(|e| fail("realm_unreadable", e.to_string()))?; + let canonical = self.owner.load_current(cid)?; + let opts = ImportOptions { capabilities: Some(Arc::new(caps.clone())), extensions: Some(self.registry.clone()), ..ImportOptions::default() }; + let report = self.report(&canonical, &caps, &opts, &[Operation::OnlineImport, Operation::RuntimeSession], true); + let verdict = verdict_of(report.verdict()); + let notes = notes_of(&report); + let projection = projection_of(&report); + let step = if verdict == Verdict::Incompatible { Step::Blocked } else { Step::Prepare }; + Ok(PreflightView { verdict, step, projection, notes, needs_account: false }) + } + /// What pressing Play would do, found by looking only: nothing is written to a realm or to a store. pub fn preflight(&mut self, character: &str, realm_id: &str) -> Res { let cid = self.cid(character)?; diff --git a/crates/coa-core/src/realm_registry/browse.rs b/crates/coa-core/src/realm_registry/browse.rs new file mode 100644 index 0000000..0791ec7 --- /dev/null +++ b/crates/coa-core/src/realm_registry/browse.rs @@ -0,0 +1,119 @@ +//! The Player Manager's read side of the Registry: the public list and one realm's detail. Plain HTTP GETs with hard limits; nothing is signed and +//! nothing about the player is sent (no identity, no character, no account: the Registry is asked the same question by everybody). + +use std::io::Read; +use std::time::Duration; + +use coa_registry_proto::*; +use serde::de::DeserializeOwned; + +use super::client::ClientError; + +/// The largest answer read (a full page of 100 summaries is well under this). +const MAX_ANSWER_BYTES: u64 = 2 * 1024 * 1024; + +pub struct BrowseClient { + base: String, + http: reqwest::blocking::Client, +} + +impl BrowseClient { + pub fn new(base: &str) -> crate::Result { + let base = super::settings::validate_url(base)?; + let http = reqwest::blocking::Client::builder() + .timeout(Duration::from_secs(15)) + .connect_timeout(Duration::from_secs(5)) + .redirect(reqwest::redirect::Policy::none()) + .user_agent(concat!("coa-manager/", env!("CARGO_PKG_VERSION"))) + .build() + .map_err(|e| crate::Error::Invalid(e.to_string()))?; + Ok(Self { base, http }) + } + + fn get(&self, path_and_query: &str) -> std::result::Result { + let resp = self.http.get(format!("{}{}", self.base, path_and_query)).send().map_err(|e| ClientError::Transient(e.without_url().to_string()))?; + let status = resp.status(); + let mut bytes = Vec::new(); + resp.take(MAX_ANSWER_BYTES).read_to_end(&mut bytes).map_err(|e| ClientError::Transient(e.to_string()))?; + if status.is_success() { + return serde_json::from_slice(&bytes).map_err(|_| ClientError::Protocol("the answer cannot be read".into())); + } + match serde_json::from_slice::(&bytes) { + Ok(e) if status.as_u16() == 429 || status.as_u16() == 503 => Err(ClientError::Transient(format!("{:?}", e.error.code))), + Ok(e) => Err(ClientError::Rejected { code: e.error.code, status: status.as_u16(), message: e.error.message }), + Err(_) if status.is_server_error() || status.as_u16() == 429 => Err(ClientError::Transient(format!("HTTP {status}"))), + Err(_) => Err(ClientError::Protocol(format!("HTTP {status}"))), + } + } + + /// One page of the public list. The query is checked and normalised by the protocol's own parser before it is sent. + pub fn list(&self, query: &ListQuery) -> std::result::Result { + self.get(&format!("{PATH_LIST}?{}", query.canonical())) + } + + pub fn detail(&self, realm: &RealmId) -> std::result::Result { + self.get(&path_detail(realm)) + } +} + +/// What the browser's controls ask for; every field optional, checked by [`ListQuery::parse`]. +#[derive(Debug, Default, Clone, serde::Deserialize)] +pub struct BrowseParams { + pub q: Option, + pub ruleset: Option, + pub cap_min: Option, + pub cap_max: Option, + pub module: Option, + pub players_min: Option, + pub status: Option, + pub sort: Option, + pub order: Option, + pub cursor: Option, + pub limit: Option, +} + +impl BrowseParams { + pub fn to_query(&self) -> crate::Result { + let enc = |s: &str| s.bytes().map(|b| if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.') { (b as char).to_string() } else { format!("%{b:02X}") }).collect::(); + let mut parts = Vec::new(); + let mut text = |name: &str, v: &Option| { + if let Some(v) = v.as_deref().filter(|v| !v.is_empty()) { + parts.push(format!("{name}={}", enc(v))); + } + }; + text("q", &self.q); + text("ruleset", &self.ruleset); + text("module", &self.module); + text("status", &self.status); + text("sort", &self.sort); + text("order", &self.order); + text("cursor", &self.cursor); + let mut num = |name: &str, v: Option| { + if let Some(v) = v { + parts.push(format!("{name}={v}")); + } + }; + num("cap_min", self.cap_min); + num("cap_max", self.cap_max); + num("players_min", self.players_min); + num("limit", self.limit); + ListQuery::parse(Some(&parts.join("&"))).map_err(|e| crate::Error::Invalid(e.to_string())) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn controls_become_a_checked_query() { + let p = BrowseParams { q: Some("Desc ension".into()), ruleset: Some("coa".into()), cap_min: Some(60), module: Some("playerbots".into()), sort: Some("name".into()), ..Default::default() }; + let q = p.to_query().unwrap(); + assert_eq!((q.q.as_deref(), q.cap_min, q.module.as_deref()), (Some("Desc ension"), Some(60), Some("playerbots"))); + assert!(q.canonical().contains("q=Desc%20ension")); + assert!(BrowseParams { ruleset: Some("normal".into()), ..Default::default() }.to_query().is_err()); + assert!(BrowseParams { module: Some("\n[link](javascript:alert(1)) & ${jndi:ldap://x}".into(); + r.listing.modules = vec![ModuleEntry { id: "mystery-mod".into(), version: Some("9.9.9".into()), enabled: true }]; + store.put_for_test(r.clone()); + let resp = reqwest::blocking::get(format!("{}{PATH_LIST}", server.base)).unwrap(); + assert_eq!(resp.headers()["content-type"], "application/json", "never HTML"); + let page: serde_json::Value = resp.json().unwrap(); + assert_eq!(page["realms"][0]["display_name"], "", "stored and returned as the text it is"); + assert!(page["realms"][0]["description"].as_str().unwrap().contains("