From c743157b9705a93a57037b10feb074db53da4316 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: Fri, 9 Oct 2026 08:29:07 +0500 Subject: [PATCH] Implement Phase 12.1 Remote Portable Transfer and Phase 13 Game Relay --- Cargo.toml | 3 +- crates/coa-control-proto/src/app.rs | 119 +- crates/coa-control-proto/src/lib.rs | 2 + crates/coa-control-proto/src/relay.rs | 269 +++ crates/coa-core/src/control/backend.rs | 15 +- crates/coa-core/src/control/host_manager.rs | 21 +- crates/coa-core/src/control/join.rs | 93 + crates/coa-core/src/control/mod.rs | 2 + crates/coa-core/src/control/relay_link.rs | 403 ++++ crates/coa-core/src/control/service.rs | 621 +++++- crates/coa-core/src/control/store.rs | 242 +++ crates/coa-core/src/control/transport.rs | 5 + .../coa-core/src/portable/service/engine.rs | 119 ++ docs/CONTROL_PROTOCOL.md | 41 +- docs/INFRASTRUCTURE.md | 17 +- docs/RELAY_PROTOCOL.md | 112 + docs/VPS_BASELINE.md | 5 +- services/coa-control-e2e/Cargo.lock | 1 + services/coa-control-e2e/Cargo.toml | 2 + services/coa-control-e2e/tests/control.rs | 44 + .../coa-control-e2e/tests/live_control.rs | 222 ++ services/coa-registry/deploy/Caddyfile | 2 + services/coa-relay/Cargo.lock | 1898 +++++++++++++++++ services/coa-relay/Cargo.toml | 37 + services/coa-relay/Dockerfile | 17 + services/coa-relay/deploy/compose.yaml | 44 + services/coa-relay/src/hub.rs | 220 ++ services/coa-relay/src/lib.rs | 44 + services/coa-relay/src/limits.rs | 20 + services/coa-relay/src/main.rs | 108 + services/coa-relay/src/ports.rs | 82 + services/coa-relay/src/tunnel.rs | 284 +++ services/coa-relay/tests/relay.rs | 251 +++ src-tauri/src/control_cmds.rs | 24 +- 34 files changed, 5359 insertions(+), 30 deletions(-) create mode 100644 crates/coa-control-proto/src/relay.rs create mode 100644 crates/coa-core/src/control/relay_link.rs create mode 100644 docs/RELAY_PROTOCOL.md create mode 100644 services/coa-relay/Cargo.lock create mode 100644 services/coa-relay/Cargo.toml create mode 100644 services/coa-relay/Dockerfile create mode 100644 services/coa-relay/deploy/compose.yaml create mode 100644 services/coa-relay/src/hub.rs create mode 100644 services/coa-relay/src/lib.rs create mode 100644 services/coa-relay/src/limits.rs create mode 100644 services/coa-relay/src/main.rs create mode 100644 services/coa-relay/src/ports.rs create mode 100644 services/coa-relay/src/tunnel.rs create mode 100644 services/coa-relay/tests/relay.rs diff --git a/Cargo.toml b/Cargo.toml index f549981..89833c9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,7 +1,8 @@ [workspace] resolver = "2" members = ["crates/coa-core", "crates/coa-release", "crates/coa-registry-proto", "crates/coa-control-proto", "src-tauri"] -exclude = ["services/coa-registry", "services/coa-registry-e2e", "services/coa-coordinator"] +exclude = ["services/coa-registry", "services/coa-registry-e2e", "services/coa-coordinator", "services/coa-relay"] + [workspace.package] version = "0.6.6" diff --git a/crates/coa-control-proto/src/app.rs b/crates/coa-control-proto/src/app.rs index 22cb0aa..9ffebfc 100644 --- a/crates/coa-control-proto/src/app.rs +++ b/crates/coa-control-proto/src/app.rs @@ -7,7 +7,7 @@ use uuid::Uuid; use crate::{invalid, ControlError, Result}; -pub const MAX_REQUEST_BYTES: usize = 4096; +pub const MAX_REQUEST_BYTES: usize = 64 * 1024; pub const MIN_USERNAME: usize = 3; pub const MAX_USERNAME: usize = 16; pub const MIN_PASSWORD: usize = 8; @@ -69,8 +69,41 @@ pub enum Request { /// Link an account the realm already has (one time). Link { login: String, password: String }, Route, + /// Phase 12.1: Start or resume a remote portable character transfer. + TransferOffer { + transfer_id: Uuid, + character_id: Uuid, + canonical_revision: u64, + content_hash: String, + total_size: usize, + collections: BTreeMap>, + }, + /// A chunk of the encoded portable character snapshot payload. + TransferChunk { + transfer_id: Uuid, + offset: usize, + data: String, + }, + /// Query status or resume progress of a transfer. + TransferStatus { + transfer_id: Uuid, + }, + /// Commit the transferred payload into the realm and arm a session. + TransferCommit { + transfer_id: Uuid, + }, + /// Acknowledge successful transfer and session arming. + TransferAck { + transfer_id: Uuid, + character_id: Uuid, + }, + /// Phase 13: Request a short-lived relay allocation for a relayed JOIN. + AllocateRelay { + player_id: Uuid, + }, } + #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum AppError { @@ -86,6 +119,9 @@ pub enum AppError { AccountTaken, RateLimited, Unavailable, + Incompatible, + Conflict, + RelayUnavailable, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] @@ -115,9 +151,31 @@ pub enum Response { Linked { username: String }, Done, RouteInfo { address: Option }, + /// The Host is ready to receive transfer chunks (or indicates an offset to resume from). + TransferReady { transfer_id: Uuid, received_offset: usize }, + /// Acknowledgement of a transfer chunk. + TransferChunkAck { transfer_id: Uuid, received_offset: usize }, + /// Successful commit and session arm. + TransferCommitted { + transfer_id: Uuid, + character_id: Uuid, + local_guid: u32, + session_id: Uuid, + projected_level: Option, + notes: Vec, + }, + /// Phase 13: Relay allocation details returned to the player. + RelayAllocated { + relay_host: String, + auth_port: u16, + world_port: u16, + token: String, + expires_at: i64, + }, Error { code: AppError, message: String }, } + pub fn encode_request(r: &Request) -> Vec { serde_json::to_vec(r).expect("a request serialises") } @@ -139,6 +197,19 @@ pub fn decode_request(bytes: &[u8]) -> Result { } } Request::Hello { client, .. } if client.len() > 64 => return invalid("the client name is too long"), + Request::TransferOffer { content_hash, total_size, .. } => { + if content_hash.len() != 64 || !content_hash.chars().all(|c| c.is_ascii_hexdigit()) { + return invalid("transfer content hash must be 64 hex characters"); + } + if *total_size > crate::noise::MAX_MESSAGE_BYTES { + return Err(ControlError::Limit("transfer total size is too large".into())); + } + } + Request::TransferChunk { data, .. } => { + if data.len() > MAX_REQUEST_BYTES { + return Err(ControlError::Limit("transfer chunk is too large".into())); + } + } _ => {} } Ok(r) @@ -210,4 +281,50 @@ mod tests { assert!(decode_request(br#"{"op":"list_characters"}"#).is_ok()); assert!(valid_password_for_link("pa55-w0rd") && !valid_password_for_link("has\"quote") && !valid_password_for_link("short")); } + + #[test] + fn transfer_messages_roundtrip_and_validate() { + let tid = Uuid::new_v4(); + let cid = Uuid::new_v4(); + let hash = "a".repeat(64); + let offer = Request::TransferOffer { + transfer_id: tid, + character_id: cid, + canonical_revision: 5, + content_hash: hash.clone(), + total_size: 1024, + collections: BTreeMap::new(), + }; + let encoded = encode_request(&offer); + let decoded = decode_request(&encoded).unwrap(); + assert_eq!(offer, decoded); + + let bad_hash = Request::TransferOffer { + transfer_id: tid, + character_id: cid, + canonical_revision: 5, + content_hash: "too_short".into(), + total_size: 1024, + collections: BTreeMap::new(), + }; + assert!(decode_request(&encode_request(&bad_hash)).is_err()); + + let chunk = Request::TransferChunk { + transfer_id: tid, + offset: 0, + data: "aGVsbG8=".into(), + }; + assert_eq!(chunk, decode_request(&encode_request(&chunk)).unwrap()); + + let resp = Response::TransferCommitted { + transfer_id: tid, + character_id: cid, + local_guid: 42, + session_id: Uuid::new_v4(), + projected_level: Some(60), + notes: vec!["Projected".into()], + }; + let resp_dec = decode_response(&encode_response(&resp)).unwrap(); + assert_eq!(resp, resp_dec); + } } diff --git a/crates/coa-control-proto/src/lib.rs b/crates/coa-control-proto/src/lib.rs index b04ce7d..3116f7f 100644 --- a/crates/coa-control-proto/src/lib.rs +++ b/crates/coa-control-proto/src/lib.rs @@ -14,9 +14,11 @@ pub mod app; pub mod coord; pub mod noise; +pub mod relay; pub const CONTROL_PROTOCOL_VERSION: u32 = 1; + #[derive(Debug, thiserror::Error, PartialEq, Eq)] pub enum ControlError { #[error("{0}")] diff --git a/crates/coa-control-proto/src/relay.rs b/crates/coa-control-proto/src/relay.rs new file mode 100644 index 0000000..2131171 --- /dev/null +++ b/crates/coa-control-proto/src/relay.rs @@ -0,0 +1,269 @@ +//! Game Relay protocol (Phase 13): +//! Host-to-Relay multiplexed tunnel protocol, allocation messaging, +//! challenge-response authentication, and WoW 3.3.5 REALM_LIST address rewrite helper. + +use coa_registry_proto::RealmId; +use ed25519_dalek::{Signature, Signer, SigningKey, VerifyingKey}; +use serde::{Deserialize, Serialize}; + +use uuid::Uuid; + + +pub const RELAY_PROTOCOL_VERSION: u32 = 1; + +/// Default local targets that the Host opens for game traffic. +pub const LOCAL_AUTH_PORT: u16 = 3724; +pub const LOCAL_WORLD_PORT: u16 = 8085; + +/// Predefined targets that the Relay can request over the Host tunnel. +/// Arbitrary destinations are strictly forbidden. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum RelayTarget { + Auth, + World, +} + +impl RelayTarget { + pub fn local_port(&self) -> u16 { + match self { + RelayTarget::Auth => std::env::var("COA_OVERRIDE_LOCAL_AUTH_PORT") + .ok() + .and_then(|p| p.parse().ok()) + .unwrap_or(LOCAL_AUTH_PORT), + RelayTarget::World => std::env::var("COA_OVERRIDE_LOCAL_WORLD_PORT") + .ok() + .and_then(|p| p.parse().ok()) + .unwrap_or(LOCAL_WORLD_PORT), + } + } +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct RelayChallenge { + pub nonce: String, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct HostHello { + pub realm_id: RealmId, + pub signature: String, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct RelayWelcome { + pub ok: bool, + pub message: String, +} + +/// Messages multiplexed across the Host <-> Relay tunnel. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "cmd", rename_all = "snake_case")] +pub enum TunnelMsg { + /// Host asks Relay to allocate a game session for a player. + Allocate { + request_id: u64, + player_id: Uuid, + }, + /// Relay responds to Host with allocation details. + AllocateOk { + request_id: u64, + token: String, + relay_host: String, + auth_port: u16, + world_port: u16, + expires_at: i64, + }, + AllocateErr { + request_id: u64, + error: String, + }, + + /// Relay asks Host to open a local connection to `target` (Auth or World) for an incoming player connection. + Connect { + stream_id: u32, + target: RelayTarget, + token: String, + }, + /// Host confirms local connection established. + ConnectOk { + stream_id: u32, + }, + /// Connect failed. + ConnectErr { + stream_id: u32, + error: String, + }, + + /// Stream data chunk (base64 encoded). + Data { + stream_id: u32, + chunk: String, + }, + /// Stream clean half-close / EOF. + Close { + stream_id: u32, + }, + /// Stream abrupt abort / error. + Reset { + stream_id: u32, + }, + /// Keepalive ping. + Ping, + /// Keepalive pong. + Pong, +} + +fn relay_input(realm: &RealmId, nonce: &str) -> Vec { + format!("coa-relay-host-v1\n{}\n{realm}\n{nonce}", RELAY_PROTOCOL_VERSION).into_bytes() +} + +/// Create a signature over (realm_id, nonce) using the realm's signing key. +pub fn sign_relay_challenge(key: &SigningKey, realm_id: &RealmId, nonce: &str) -> String { + let sig: Signature = key.sign(&relay_input(realm_id, nonce)); + hex::encode(sig.to_bytes()) +} + +/// Verify a signature over (realm_id, nonce) using the realm's verifying key. +pub fn verify_relay_challenge(key: &VerifyingKey, realm_id: &RealmId, nonce: &str, sig_hex: &str) -> bool { + let Ok(sig_bytes) = hex::decode(sig_hex) else { return false }; + let Ok(sig) = Signature::from_slice(&sig_bytes) else { return false }; + key.verify_strict(&relay_input(realm_id, nonce), &sig).is_ok() +} + + +/// Rewrites the realm address in a WoW 3.3.5 REALM_LIST response packet (Opcode 0x10). +/// +/// In WoW 3.3.5 client protocol: +/// - Byte 0: 0x10 (REALM_LIST) +/// - Bytes 1..2: uint16 LE payload length (total size after byte 2) +/// - Bytes 3..6: uint32 LE unused (0) +/// - Bytes 7..8: uint16 LE realm count +/// - For each realm: +/// - uint8 type (1 byte) +/// - uint8 lock (1 byte) +/// - uint8 flag (1 byte) +/// - name: null-terminated C string +/// - address: null-terminated C string ("host:port\0") +/// - population: 4 bytes float +/// - characters: 1 byte uint8 +/// - timezone: 1 byte uint8 +/// - realm_id: 1 byte uint8 +/// - if flag & 0x04 (SPECIFYBUILD): 5 bytes build info +/// - Footer: 2 bytes (0x10, 0x00) +/// +/// Replaces the address of the first realm (or matches) with `new_host_port` and adjusts +/// the uint16 length at bytes 1..2 by the byte length delta. +pub fn rewrite_realm_list_address(pkt: &[u8], new_host_port: &str) -> Result>, String> { + if pkt.is_empty() || pkt[0] != 0x10 { + return Ok(None); + } + if pkt.len() < 9 { + return Err("packet too short for REALM_LIST header".into()); + } + let body_len = u16::from_le_bytes([pkt[1], pkt[2]]) as usize; + if pkt.len() < 3 + body_len { + return Err("truncated REALM_LIST packet".into()); + } + let realm_count = u16::from_le_bytes([pkt[7], pkt[8]]) as usize; + if realm_count == 0 { + return Ok(Some(pkt.to_vec())); + } + + let mut pos = 9; + if pos + 3 > pkt.len() { + return Err("malformed realm header".into()); + } + pos += 3; // type, lock, flag + + let name_end = pkt[pos..].iter().position(|&b| b == 0).ok_or("unterminated realm name")? + pos; + pos = name_end + 1; + + let addr_start = pos; + let addr_end = pkt[pos..].iter().position(|&b| b == 0).ok_or("unterminated realm address")? + pos; + let old_addr = &pkt[addr_start..addr_end]; + + let mut out = Vec::with_capacity(pkt.len() + new_host_port.len() + 1); + out.extend_from_slice(&pkt[..addr_start]); + out.extend_from_slice(new_host_port.as_bytes()); + out.extend_from_slice(&pkt[addr_end..]); + + let diff = new_host_port.len() as isize - old_addr.len() as isize; + let new_body_len = (body_len as isize + diff) as u16; + out[1..3].copy_from_slice(&new_body_len.to_le_bytes()); + + Ok(Some(out)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn challenge_signature_roundtrip() { + let seed = [42u8; 32]; + let key = SigningKey::from_bytes(&seed); + + let realm = RealmId::new(); + let nonce = "test-challenge-nonce-123"; + + let sig = sign_relay_challenge(&key, &realm, nonce); + assert!(verify_relay_challenge(&key.verifying_key(), &realm, nonce, &sig)); + + // Wrong nonce + assert!(!verify_relay_challenge(&key.verifying_key(), &realm, "other-nonce", &sig)); + // Wrong realm + assert!(!verify_relay_challenge(&key.verifying_key(), &RealmId::new(), nonce, &sig)); + } + + #[test] + fn rewrite_realm_list_address_works() { + // Build a mock REALM_LIST packet for WoW 3.3.5 + let mut pkt = Vec::new(); + pkt.push(0x10); // Opcode + pkt.extend_from_slice(&[0, 0]); // Placeholder for body_len + pkt.extend_from_slice(&[0, 0, 0, 0]); // Unused uint32 + pkt.extend_from_slice(&1u16.to_le_bytes()); // Realm count = 1 + + // Realm 0 + pkt.push(1); // Type + pkt.push(0); // Lock + pkt.push(0); // Flags + pkt.extend_from_slice(b"CoA Test Realm\0"); // Name + pkt.extend_from_slice(b"127.0.0.1:8085\0"); // Old Address + pkt.extend_from_slice(&0.5f32.to_le_bytes()); // Population + pkt.push(1); // Characters + pkt.push(1); // Timezone + pkt.push(1); // Realm ID + + // Footer + pkt.push(0x10); + pkt.push(0x00); + + let body_len = (pkt.len() - 3) as u16; + pkt[1..3].copy_from_slice(&body_len.to_le_bytes()); + + // Rewrite + let new_target = "coa-manager.duckdns.org:40005"; + let res = rewrite_realm_list_address(&pkt, new_target).unwrap().expect("rewritten"); + + assert_eq!(res[0], 0x10); + let new_len = u16::from_le_bytes([res[1], res[2]]) as usize; + assert_eq!(res.len(), 3 + new_len); + + // Address in res must be new_target + let old_addr = b"127.0.0.1:8085"; + let new_addr = b"coa-manager.duckdns.org:40005"; + assert!(!res.windows(old_addr.len()).any(|w| w == old_addr)); + assert!(res.windows(new_addr.len()).any(|w| w == new_addr)); + } + + #[test] + fn non_realm_list_ignored() { + let pkt = vec![0x00, 0x01, 0x02]; + assert_eq!(rewrite_realm_list_address(&pkt, "test:8085"), Ok(None)); + } +} diff --git a/crates/coa-core/src/control/backend.rs b/crates/coa-core/src/control/backend.rs index ee1be3f..59afa63 100644 --- a/crates/coa-core/src/control/backend.rs +++ b/crates/coa-core/src/control/backend.rs @@ -9,7 +9,9 @@ use std::sync::Arc; use coa_control_proto::app; -use super::service::{AccountRow, CharInfo, ClaimExport, Presence, RealmBackend, RealmInfo}; +use uuid::Uuid; + +use super::service::{AccountRow, CharInfo, ClaimExport, PreflightVerdict, Presence, RealmBackend, RealmInfo, RemoteImportOutcome, RemoteImportParams}; use crate::portable::realm; use crate::portable::service::access::RealmAccess; use crate::portable::service::runtime::PortableRuntime; @@ -143,4 +145,15 @@ impl RealmBackend for LocalBackend { let bundle = self.portable.call(move |s| s.export_for_claim(&id, guid)).map_err(|e| unavailable("portable engine", e))?.map_err(|e| unavailable("export", e))?; Ok(ClaimExport { character_id: bundle.character_id.as_uuid(), payload: bundle.payload, sha256: bundle.content_hash, collections: bundle.collections }) } + + fn check_transfer(&self, local_id: &str, character_id: Uuid, revision: u64) -> Result { + let id = local_id.to_string(); + let cid = crate::portable::CharacterId::from_uuid(character_id).map_err(|e| unavailable("character id", e))?; + self.portable.call(move |s| s.check_remote_transfer(&id, cid, revision)).map_err(|e| unavailable("portable engine", e))?.map_err(|e| unavailable("check transfer", e)) + } + + fn import_remote(&self, local_id: &str, params: RemoteImportParams) -> Result { + let id = local_id.to_string(); + self.portable.call(move |s| s.import_remote_character(&id, params)).map_err(|e| unavailable("portable engine", e))?.map_err(|e| unavailable("import remote", e)) + } } diff --git a/crates/coa-core/src/control/host_manager.rs b/crates/coa-core/src/control/host_manager.rs index c1d1ac2..0ef3f64 100644 --- a/crates/coa-core/src/control/host_manager.rs +++ b/crates/coa-core/src/control/host_manager.rs @@ -36,8 +36,11 @@ struct Running { realm_id: RealmId, url: String, link: HostLink, + #[allow(dead_code)] + relay_link: Option>, } + impl HostControl { /// `url_override` replaces the Registry address from the settings (`COA_REGISTRY_URL` in tests and deployments). pub fn start(settings_dir: PathBuf, keys: Arc, store: Arc>, backend: Arc, url_override: Option) -> HostControl { @@ -54,14 +57,20 @@ impl HostControl { let mut running: BTreeMap = BTreeMap::new(); while !s.load(Ordering::SeqCst) { let wanted = wanted(&settings_dir, keys.as_ref(), url_override.as_deref()); - running.retain(|id, r| wanted.get(id).is_some_and(|(realm, url, _)| *realm == r.realm_id && *url == r.url)); - for (local_id, (realm_id, url, key)) in wanted { + running.retain(|id, r| wanted.get(id).is_some_and(|(realm, url, _, _)| *realm == r.realm_id && *url == r.url)); + for (local_id, (realm_id, url, base, key)) in wanted { if running.contains_key(&local_id) { continue; } let service = Arc::new(HostService::new(&local_id, realm_id, store.clone(), backend.clone())); + let relay_link = crate::control::transport::relay_url(&base, "/relay/v1/host") + .map(|r_url| { + let rl = crate::control::relay_link::RelayLink::start(r_url, realm_id, key.clone()); + service.set_relay(rl.clone()); + rl + }); let link = HostLink::start(url.clone(), realm_id, key, service, clock.clone()); - running.insert(local_id, Running { realm_id, url, link }); + running.insert(local_id, Running { realm_id, url, link, relay_link }); } if let Ok(mut st) = st.lock() { *st = running.iter().map(|(id, r)| (id.clone(), HostControlRealm { local_id: id.clone(), realm_id: r.realm_id.to_string(), link: r.link.status() })).collect(); @@ -77,6 +86,7 @@ impl HostControl { HostControl { stop, status, join: Mutex::new(join) } } + pub fn status(&self) -> Vec { self.status.lock().map(|s| s.values().cloned().collect()).unwrap_or_default() } @@ -95,7 +105,7 @@ impl Drop for HostControl { } } -type Wanted = BTreeMap; +type Wanted = BTreeMap; fn wanted(dir: &std::path::Path, keys: &dyn KeyStore, url_override: Option<&str>) -> Wanted { let mut out = Wanted::new(); @@ -105,8 +115,9 @@ fn wanted(dir: &std::path::Path, keys: &dyn KeyStore, url_override: Option<&str> for (local_id, cfg) in s.realms { let (true, Some(realm)) = (cfg.enabled, cfg.realm_id) else { continue }; if let Ok(Some(key)) = keys.load(&realm) { - out.insert(local_id, (realm, url.clone(), key)); + out.insert(local_id, (realm, url.clone(), base.clone(), key)); } } out } + diff --git a/crates/coa-core/src/control/join.rs b/crates/coa-core/src/control/join.rs index 9f572d0..bdb548e 100644 --- a/crates/coa-core/src/control/join.rs +++ b/crates/coa-core/src/control/join.rs @@ -275,4 +275,97 @@ impl PlayerControl { pub fn claimed_here(&self, realm: &RealmId) -> R> { Ok(self.store()?.player_claims(&realm.to_string())?) } + + /// Transfer a portable character to a remote realm over the verified control channel (Phase 12.1). + pub fn transfer_character( + &self, + ch: &mut PlayerChannel, + character_id: Uuid, + canonical_revision: u64, + payload: &[u8], + content_hash: [u8; 32], + collections: BTreeMap>, + ) -> R { + let transfer_id = Uuid::now_v7(); + let content_hash_str = hex::encode(content_hash); + let offer = Request::TransferOffer { + transfer_id, + character_id, + canonical_revision, + content_hash: content_hash_str.clone(), + total_size: payload.len(), + collections, + }; + let r = ch.request(&offer)?; + let mut offset = match r { + Response::TransferReady { received_offset, .. } => received_offset, + Response::TransferCommitted { local_guid, session_id, projected_level, notes, .. } => { + let _ = ch.request(&Request::TransferAck { transfer_id, character_id }); + return Ok(RemoteTransferOutcome { local_guid, session_id, projected_level, notes }); + } + Response::Error { code, message } => return Err(ControlFail::App { code, message }), + _ => return Err(ControlFail::Link(LinkError::Protocol("unexpected response to transfer offer".into()))), + }; + + const CHUNK_SIZE: usize = 16 * 1024; + while offset < payload.len() { + let end = (offset + CHUNK_SIZE).min(payload.len()); + let chunk_data = base64::engine::general_purpose::STANDARD.encode(&payload[offset..end]); + let chunk_req = Request::TransferChunk { + transfer_id, + offset, + data: chunk_data, + }; + let cr = ch.request(&chunk_req)?; + match cr { + Response::TransferChunkAck { received_offset, .. } => { + offset = received_offset; + } + Response::Error { code, message } => return Err(ControlFail::App { code, message }), + _ => return Err(ControlFail::Link(LinkError::Protocol("unexpected response to transfer chunk".into()))), + } + } + + let commit_req = Request::TransferCommit { transfer_id }; + let commit_resp = ch.request(&commit_req)?; + let outcome = expect(commit_resp, |r| match r { + Response::TransferCommitted { local_guid, session_id, projected_level, notes, .. } => { + Ok(RemoteTransferOutcome { local_guid, session_id, projected_level, notes }) + } + other => Err(other), + })?; + + let _ = ch.request(&Request::TransferAck { transfer_id, character_id }); + Ok(outcome) + } + + /// Request a short-lived Game Relay allocation for a relayed JOIN (Phase 13). + pub fn allocate_relay( + &self, + ch: &mut PlayerChannel, + ) -> R { + let req = Request::AllocateRelay { player_id: self.identity.player_id }; + let resp = ch.request(&req)?; + expect(resp, |r| match r { + Response::RelayAllocated { relay_host, auth_port, world_port, token, expires_at } => { + Ok(crate::control::relay_link::RelayAllocationInfo { + relay_host, + auth_port, + world_port, + token, + expires_at, + }) + } + other => Err(other), + }) + } +} + + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct RemoteTransferOutcome { + pub local_guid: u32, + pub session_id: Uuid, + pub projected_level: Option, + pub notes: Vec, } diff --git a/crates/coa-core/src/control/mod.rs b/crates/coa-core/src/control/mod.rs index 1a78a3f..49d7265 100644 --- a/crates/coa-core/src/control/mod.rs +++ b/crates/coa-core/src/control/mod.rs @@ -7,7 +7,9 @@ pub mod host_manager; pub mod identity; pub mod join; pub mod player; +pub mod relay_link; pub mod secrets; pub mod service; pub mod store; pub mod transport; + diff --git a/crates/coa-core/src/control/relay_link.rs b/crates/coa-core/src/control/relay_link.rs new file mode 100644 index 0000000..22d709e --- /dev/null +++ b/crates/coa-core/src/control/relay_link.rs @@ -0,0 +1,403 @@ +//! Outbound Host <-> Game Relay tunnel link (Phase 13). +//! Maintains outbound connectivity from Host Manager to the Game Relay, +//! opening local TCP connections strictly to 127.0.0.1:3724 (Auth) and 127.0.0.1:8085 (World). + +use std::collections::HashMap; +use std::io::{Read, Write}; +use std::net::TcpStream; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::mpsc::{channel, Receiver, Sender}; +use std::sync::{Arc, Mutex}; +use std::thread::JoinHandle; +use std::time::{Duration, Instant}; + +use base64::Engine; +use coa_control_proto::relay::*; +use coa_registry_proto::RealmId; +use ed25519_dalek::SigningKey; +use serde::Serialize; +use tungstenite::Message; +use uuid::Uuid; + +use super::service::RelayProvider; +use super::transport::{self, LinkError}; + +const POLL: Duration = Duration::from_millis(200); + +#[derive(Clone, Debug, Default, Serialize)] +pub struct RelayStatus { + pub connected: bool, + pub last_error: Option, + pub active_streams: usize, +} + +pub struct RelayLink { + stop: Arc, + status: Arc>, + alloc_tx: Sender<(Uuid, Sender>)>, + join: Mutex>>, +} + +#[derive(Clone, Debug, Serialize, serde::Deserialize)] +pub struct RelayAllocationInfo { + pub relay_host: String, + pub auth_port: u16, + pub world_port: u16, + pub token: String, + pub expires_at: i64, +} + +impl RelayProvider for RelayLink { + fn allocate(&self, player_id: &Uuid) -> crate::error::Result { + let (tx, rx) = channel(); + self.alloc_tx + .send((*player_id, tx)) + .map_err(|_| crate::error::Error::Invalid("relay link worker thread not running".to_string()))?; + rx.recv_timeout(Duration::from_secs(10)) + .map_err(|_| crate::error::Error::Invalid("relay allocation timed out".to_string()))? + .map_err(|e| crate::error::Error::Invalid(e.to_string())) + } +} + + +impl RelayLink { + pub fn start( + url: String, + realm_id: RealmId, + key: SigningKey, + ) -> Arc { + let stop = Arc::new(AtomicBool::new(false)); + let status = Arc::new(Mutex::new(RelayStatus::default())); + let (alloc_tx, alloc_rx) = channel(); + + let s = stop.clone(); + let st = status.clone(); + let join = std::thread::Builder::new() + .name("control-relay-host".into()) + .spawn(move || run(&url, realm_id, &key, alloc_rx, &s, &st)) + .ok(); + + Arc::new(RelayLink { + stop, + status, + alloc_tx, + join: Mutex::new(join), + }) + } + + pub fn status(&self) -> RelayStatus { + self.status.lock().unwrap().clone() + } + + pub fn stop(&self) { + self.stop.store(true, Ordering::SeqCst); + if let Ok(mut lock) = self.join.lock() { + if let Some(j) = lock.take() { + let _ = j.join(); + } + } + } +} + +impl Drop for RelayLink { + fn drop(&mut self) { + self.stop(); + } +} + +fn set_status(status: &Mutex, f: impl FnOnce(&mut RelayStatus)) { + if let Ok(mut s) = status.lock() { + f(&mut s); + } +} + +fn run( + url: &str, + realm: RealmId, + key: &SigningKey, + alloc_rx: Receiver<(Uuid, Sender>)>, + stop: &AtomicBool, + status: &Mutex, +) { + let mut failures = 0u32; + while !stop.load(Ordering::SeqCst) { + let began = Instant::now(); + let result = session(url, realm, key, &alloc_rx, stop, status); + set_status(status, |s| { + s.connected = false; + s.active_streams = 0; + if let Err(e) = &result { + s.last_error = Some(e.to_string()); + } + }); + if stop.load(Ordering::SeqCst) { + return; + } + + failures = if began.elapsed() > Duration::from_secs(60) { + 1 + } else { + failures.saturating_add(1) + }; + let wait = crate::realm_registry::host::backoff( + failures, + Duration::from_secs(2), + Duration::from_secs(60), + 0.5, + ); + let end = Instant::now() + wait; + while Instant::now() < end && !stop.load(Ordering::SeqCst) { + std::thread::sleep(Duration::from_millis(200)); + } + } +} + +struct StreamWorker { + tx: Sender, +} + +fn session( + url: &str, + realm: RealmId, + key: &SigningKey, + alloc_rx: &Receiver<(Uuid, Sender>)>, + stop: &AtomicBool, + status: &Mutex, +) -> Result<(), LinkError> { + let mut ws = transport::connect(url, POLL)?; + + // 1. Read challenge + let challenge_raw = match transport::poll(&mut ws)? { + Some(Message::Text(t)) => t, + _ => { + // wait up to 10s + let deadline = Instant::now() + Duration::from_secs(10); + let mut got = None; + while Instant::now() < deadline && got.is_none() { + if let Some(Message::Text(t)) = transport::poll(&mut ws)? { + got = Some(t); + break; + } + std::thread::sleep(Duration::from_millis(50)); + } + got.ok_or_else(|| LinkError::Timeout)? + } + }; + + let challenge: RelayChallenge = serde_json::from_str(&challenge_raw) + .map_err(|e| LinkError::Protocol(format!("invalid challenge: {e}")))?; + + // 2. Send HostHello + let sig = sign_relay_challenge(key, &realm, &challenge.nonce); + let hello = HostHello { + realm_id: realm, + signature: sig, + }; + ws.send(Message::Text(serde_json::to_string(&hello).unwrap().into())) + .map_err(|e| LinkError::Io(e.to_string()))?; + + // 3. Receive welcome + let deadline = Instant::now() + Duration::from_secs(10); + let mut welcome_ok = false; + while Instant::now() < deadline { + if let Some(Message::Text(t)) = transport::poll(&mut ws)? { + let welcome: RelayWelcome = serde_json::from_str(&t) + .map_err(|e| LinkError::Protocol(format!("invalid welcome: {e}")))?; + if welcome.ok { + welcome_ok = true; + break; + } else { + return Err(LinkError::Auth("relay rejected host".into())); + } + } + std::thread::sleep(Duration::from_millis(50)); + } + + if !welcome_ok { + return Err(LinkError::Timeout); + } + + set_status(status, |s| { + s.connected = true; + s.last_error = None; + }); + tracing::info!(%realm, "relay link active"); + + let mut streams: HashMap = HashMap::new(); + let mut pending_allocs: HashMap>> = HashMap::new(); + let req_counter = AtomicU64::new(1); + let (ws_out_tx, ws_out_rx) = channel::(); + + let mut last_ping = Instant::now(); + + while !stop.load(Ordering::SeqCst) { + // Drain pending allocation requests + while let Ok((player_id, reply_tx)) = alloc_rx.try_recv() { + let rid = req_counter.fetch_add(1, Ordering::Relaxed); + pending_allocs.insert(rid, reply_tx); + let msg = TunnelMsg::Allocate { + request_id: rid, + player_id, + }; + let _ = ws.send(Message::Text(serde_json::to_string(&msg).unwrap().into())); + } + + // Drain outgoing messages from streams to ws + while let Ok(msg) = ws_out_rx.try_recv() { + let _ = ws.send(Message::Text(serde_json::to_string(&msg).unwrap().into())); + } + + // Keepalive + if last_ping.elapsed() > Duration::from_secs(30) { + let _ = ws.send(Message::Text(serde_json::to_string(&TunnelMsg::Ping).unwrap().into())); + last_ping = Instant::now(); + } + + // Poll WS incoming + match transport::poll(&mut ws)? { + None => {} + Some(Message::Text(text)) => { + let Ok(msg) = serde_json::from_str::(&text) else { continue }; + match msg { + TunnelMsg::AllocateOk { + request_id, + token, + relay_host, + auth_port, + world_port, + expires_at, + } => { + if let Some(tx) = pending_allocs.remove(&request_id) { + let _ = tx.send(Ok(RelayAllocationInfo { + relay_host, + auth_port, + world_port, + token, + expires_at, + })); + } + } + TunnelMsg::AllocateErr { request_id, error } => { + if let Some(tx) = pending_allocs.remove(&request_id) { + let _ = tx.send(Err(LinkError::Protocol(error))); + } + } + TunnelMsg::Connect { stream_id, target, .. } => { + // Strictly predefined local targets: Auth (3724) or World (8085) + let local_port = target.local_port(); + match TcpStream::connect(("127.0.0.1", local_port)) { + Ok(tcp) => { + let (stream_tx, stream_rx) = channel::(); + let ws_tx = ws_out_tx.clone(); + + // Spawn worker for this stream + spawn_local_tcp_bridge(stream_id, tcp, stream_rx, ws_tx); + streams.insert(stream_id, StreamWorker { tx: stream_tx }); + + // Reply ConnectOk + let ok_msg = TunnelMsg::ConnectOk { stream_id }; + let _ = ws.send(Message::Text(serde_json::to_string(&ok_msg).unwrap().into())); + } + Err(e) => { + let err_msg = TunnelMsg::ConnectErr { + stream_id, + error: e.to_string(), + }; + let _ = ws.send(Message::Text(serde_json::to_string(&err_msg).unwrap().into())); + } + } + set_status(status, |s| s.active_streams = streams.len()); + } + TunnelMsg::Data { stream_id, chunk } => { + if let Some(w) = streams.get(&stream_id) { + let _ = w.tx.send(TunnelMsg::Data { stream_id, chunk }); + } + } + TunnelMsg::Close { stream_id } => { + if let Some(w) = streams.remove(&stream_id) { + let _ = w.tx.send(TunnelMsg::Close { stream_id }); + } + set_status(status, |s| s.active_streams = streams.len()); + } + TunnelMsg::Reset { stream_id } => { + if let Some(w) = streams.remove(&stream_id) { + let _ = w.tx.send(TunnelMsg::Reset { stream_id }); + } + set_status(status, |s| s.active_streams = streams.len()); + } + TunnelMsg::Pong => {} + _ => {} + } + } + Some(Message::Close(_)) => return Err(LinkError::Io("relay closed connection".into())), + _ => {} + } + } + + Ok(()) +} + +fn spawn_local_tcp_bridge( + stream_id: u32, + mut tcp: TcpStream, + from_tunnel: Receiver, + to_tunnel: Sender, +) { + let _ = tcp.set_nonblocking(false); + let _ = tcp.set_nodelay(true); + let mut tcp_read = tcp.try_clone().expect("tcp clone"); + let to_tunnel_read = to_tunnel.clone(); + + // Local TCP read -> to tunnel + std::thread::Builder::new() + .name(format!("relay-stream-{stream_id}-read")) + .spawn(move || { + let mut buf = [0u8; 16384]; + loop { + match tcp_read.read(&mut buf) { + Ok(0) => { + let _ = to_tunnel_read.send(TunnelMsg::Close { stream_id }); + break; + } + Ok(n) => { + let chunk = base64::engine::general_purpose::STANDARD.encode(&buf[..n]); + if to_tunnel_read.send(TunnelMsg::Data { stream_id, chunk }).is_err() { + break; + } + } + Err(_) => { + let _ = to_tunnel_read.send(TunnelMsg::Reset { stream_id }); + break; + } + } + } + }) + .ok(); + + // From tunnel -> local TCP write + std::thread::Builder::new() + .name(format!("relay-stream-{stream_id}-write")) + .spawn(move || { + while let Ok(msg) = from_tunnel.recv() { + match msg { + TunnelMsg::Data { chunk, .. } => { + if let Ok(data) = base64::engine::general_purpose::STANDARD.decode(&chunk) { + if tcp.write_all(&data).is_err() { + break; + } + } + } + TunnelMsg::Close { .. } => { + let _ = tcp.shutdown(std::net::Shutdown::Write); + break; + } + TunnelMsg::Reset { .. } => { + let _ = tcp.shutdown(std::net::Shutdown::Both); + break; + } + _ => {} + } + } + }) + .ok(); +} diff --git a/crates/coa-core/src/control/service.rs b/crates/coa-core/src/control/service.rs index bcf27dd..bf88c04 100644 --- a/crates/coa-core/src/control/service.rs +++ b/crates/coa-core/src/control/service.rs @@ -17,7 +17,7 @@ use coa_control_proto::app::{self, AppError, CharacterEntry, Request, Response}; use coa_registry_proto::RealmId; use uuid::Uuid; -use super::store::{AccountKind, ClaimState, ControlStore}; +use super::store::{AccountKind, ClaimState, ControlStore, HostTransfer, TransferState}; use crate::{Error, Result}; #[derive(Clone, Debug, PartialEq, Eq)] @@ -60,6 +60,31 @@ pub struct ClaimExport { pub collections: BTreeMap>, } +#[derive(Clone, Debug)] +pub struct RemoteImportParams { + pub character_id: Uuid, + pub revision: u64, + pub payload: Vec, + pub content_hash: [u8; 32], + pub collections: BTreeMap>, + pub account_id: u32, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct RemoteImportOutcome { + pub local_guid: u32, + pub session_id: Uuid, + pub projected_level: Option, + pub notes: Vec, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum PreflightVerdict { + Compatible, + Degraded, + Incompatible, +} + /// The realm itself: its login database, its console and the portable engine. pub trait RealmBackend: Send + Sync { fn info(&self, local_id: &str) -> Result; @@ -75,6 +100,10 @@ pub trait RealmBackend: Send + Sync { fn characters(&self, local_id: &str, account_id: u32) -> Result>; /// Read the character (offline, eligible, belonging to the account) and register it with the Host's portable store; the same character again returns the same id. fn export(&self, local_id: &str, account_id: u32, guid: u32) -> Result; + /// Compatibility preflight check before receiving payload chunks. + fn check_transfer(&self, local_id: &str, character_id: Uuid, revision: u64) -> Result; + /// Import or update a transferred character into the realm and arm a session. + fn import_remote(&self, local_id: &str, params: RemoteImportParams) -> Result; } /// State of one channel. @@ -89,11 +118,17 @@ const MAX_REQUESTS_PER_SESSION: u32 = 60; const LINK_FAILURES: usize = 5; const LINK_WINDOW: Duration = Duration::from_secs(600); +pub trait RelayProvider: Send + Sync { + fn allocate(&self, player_id: &Uuid) -> crate::error::Result; +} + + pub struct HostService { local_id: String, realm_id: RealmId, store: Arc>, backend: Arc, + relay: Mutex>>, /// Serialises everything that changes accounts and claims on this realm. write: Mutex<()>, link_failures: Mutex, Vec>>, @@ -110,9 +145,14 @@ fn unavailable(what: &str, e: &Error) -> Response { impl HostService { pub fn new(local_id: &str, realm_id: RealmId, store: Arc>, backend: Arc) -> Self { - Self { local_id: local_id.to_string(), realm_id, store, backend, write: Mutex::new(()), link_failures: Mutex::new(HashMap::new()) } + Self { local_id: local_id.to_string(), realm_id, store, backend, relay: Mutex::new(None), write: Mutex::new(()), link_failures: Mutex::new(HashMap::new()) } } + pub fn set_relay(&self, provider: Arc) { + *self.relay.lock().unwrap() = Some(provider); + } + + pub fn realm_id(&self) -> RealmId { self.realm_id } @@ -152,10 +192,45 @@ impl HostService { Ok(info) => Response::RouteInfo { address: info.route }, Err(e) => unavailable("route", &e), }, + Request::TransferOffer { transfer_id, character_id, canonical_revision, content_hash, total_size, collections } => { + self.transfer_offer(player, transfer_id, character_id, canonical_revision, content_hash, total_size, collections) + } + Request::TransferChunk { transfer_id, offset, data } => self.transfer_chunk(player, transfer_id, offset, data), + Request::TransferStatus { transfer_id } => self.transfer_status(player, transfer_id), + Request::TransferCommit { transfer_id } => self.transfer_commit(player, transfer_id), + Request::TransferAck { transfer_id, character_id } => self.transfer_ack(player, transfer_id, character_id), + Request::AllocateRelay { player_id } => self.allocate_relay(player, &player_id), + + } + } + + fn allocate_relay(&self, player: &Uuid, requested_player: &Uuid) -> Response { + if player != requested_player { + return err(AppError::Invalid, "Cannot request relay for another player identity."); + } + if self.mapping(player).is_none() { + return err(AppError::NoAccount, "Player has no account on this realm."); + } + let guard = self.relay.lock().unwrap(); + if let Some(r) = guard.as_ref() { + match r.allocate(player) { + Ok(alloc) => Response::RelayAllocated { + relay_host: alloc.relay_host, + auth_port: alloc.auth_port, + world_port: alloc.world_port, + token: alloc.token, + expires_at: alloc.expires_at, + }, + Err(e) => err(AppError::RelayUnavailable, &e.to_string()), + } + + } else { + err(AppError::RelayUnavailable, "Relay is not configured on this host.") } } fn mapping(&self, player: &Uuid) -> Option { + self.store.lock().ok().and_then(|s| s.host_player(&self.local_id, player).ok().flatten()) } @@ -331,6 +406,266 @@ impl HostService { Err(e) => unavailable("recording the acknowledgement", &e), } } + + fn transfer_path(&self, transfer_id: &Uuid) -> std::path::PathBuf { + let dir = std::env::temp_dir().join("coa-transfers").join(&self.local_id); + let _ = std::fs::create_dir_all(&dir); + dir.join(format!("{transfer_id}.part")) + } + + fn transfer_offer(&self, player: &Uuid, transfer_id: Uuid, character_id: Uuid, canonical_revision: u64, content_hash: String, total_size: usize, collections: BTreeMap>) -> Response { + let Ok(_guard) = self.write.lock() else { return err(AppError::Unavailable, "Busy.") }; + let Some(m) = self.mapping(player) else { return err(AppError::NoAccount, "This player has no account on this realm yet.") }; + + // 1. Ownership check: another player cannot overwrite a character claimed here + if let Ok(Some(claim)) = self.store.lock().map_err(|_| Error::Invalid("lock".into())).and_then(|s| s.host_claim_of_character(&self.local_id, &character_id)) { + if claim.player_id != *player { + return err(AppError::AlreadyClaimed, "That character was already claimed by another player."); + } + } + + // 2. Active session conflict: if account is online with active characters + match self.backend.presence(&self.local_id, m.account_id) { + Ok(p) if p.account_online && p.online_characters > 0 => { + return err(AppError::Conflict, "The character is currently playing in a live session."); + } + Err(e) => return unavailable("presence check", &e), + _ => {} + } + + // 3. Compatibility check before accepting payload + match self.backend.check_transfer(&self.local_id, character_id, canonical_revision) { + Ok(PreflightVerdict::Incompatible) => return err(AppError::Incompatible, "This character is incompatible with this realm."), + Err(e) => return unavailable("compatibility check", &e), + _ => {} + } + + // 4. Idempotency / already committed check + if let Ok(Some(existing)) = self.store.lock().map_err(|_| Error::Invalid("lock".into())).and_then(|s| s.host_transfer_latest(&self.local_id, &character_id)) { + if existing.state != TransferState::Receiving && existing.revision == canonical_revision && existing.content_hash == content_hash { + if let (Some(guid), Some(sid)) = (existing.local_guid, existing.session_id) { + return Response::TransferCommitted { + transfer_id, + character_id, + local_guid: guid, + session_id: sid, + projected_level: existing.projected_level, + notes: existing.notes, + }; + } + } + } + + // 5. Resume check for this specific transfer_id + if let Ok(Some(cur)) = self.store.lock().map_err(|_| Error::Invalid("lock".into())).and_then(|s| s.host_transfer(&self.local_id, &transfer_id)) { + if cur.player_id == *player && cur.state == TransferState::Receiving && cur.content_hash == content_hash { + let path = self.transfer_path(&transfer_id); + let on_disk = std::fs::metadata(&path).map(|meta| meta.len() as usize).unwrap_or(0); + return Response::TransferReady { transfer_id, received_offset: on_disk.min(cur.received_size) }; + } + } + + // 6. Record new transfer + let transfer = HostTransfer { + realm_local_id: self.local_id.clone(), + transfer_id, + character_id, + player_id: *player, + revision: canonical_revision, + content_hash, + total_size, + received_size: 0, + state: TransferState::Receiving, + local_guid: None, + session_id: None, + projected_level: None, + notes: vec![], + collections, + }; + if let Err(e) = self.store.lock().map_err(|_| Error::Invalid("lock".into())).and_then(|s| s.host_transfer_save(&transfer)) { + return unavailable("saving transfer", &e); + } + let path = self.transfer_path(&transfer_id); + let _ = std::fs::remove_file(&path); + + Response::TransferReady { transfer_id, received_offset: 0 } + } + + fn transfer_chunk(&self, player: &Uuid, transfer_id: Uuid, offset: usize, data: String) -> Response { + let Ok(_guard) = self.write.lock() else { return err(AppError::Unavailable, "Busy.") }; + let store = match self.store.lock() { + Ok(s) => s, + Err(_) => return err(AppError::Unavailable, "Busy."), + }; + let t = match store.host_transfer(&self.local_id, &transfer_id) { + Ok(Some(t)) => t, + Ok(None) => return err(AppError::Invalid, "Unknown transfer id."), + Err(e) => return unavailable("reading transfer", &e), + }; + drop(store); + + if t.player_id != *player { + return err(AppError::NotYours, "Transfer does not belong to this player."); + } + if t.state != TransferState::Receiving { + return err(AppError::Invalid, "Transfer is not receiving chunks."); + } + + use base64::Engine; + let bytes = match base64::engine::general_purpose::STANDARD.decode(&data) { + Ok(b) => b, + Err(_) => return err(AppError::Invalid, "Invalid base64 in chunk data."), + }; + + if offset != t.received_size { + return Response::TransferChunkAck { transfer_id, received_offset: t.received_size }; + } + + use std::io::Write; + let path = self.transfer_path(&transfer_id); + let mut file = match std::fs::OpenOptions::new().create(true).append(true).open(&path) { + Ok(f) => f, + Err(e) => return unavailable("opening transfer file", &Error::Invalid(e.to_string())), + }; + if let Err(e) = file.write_all(&bytes) { + return unavailable("writing chunk to disk", &Error::Invalid(e.to_string())); + } + + let new_received = t.received_size + bytes.len(); + if let Ok(s) = self.store.lock() { + let _ = s.host_transfer_update_progress(&transfer_id, new_received); + } + + Response::TransferChunkAck { transfer_id, received_offset: new_received } + } + + fn transfer_status(&self, player: &Uuid, transfer_id: Uuid) -> Response { + let store = match self.store.lock() { + Ok(s) => s, + Err(_) => return err(AppError::Unavailable, "Busy."), + }; + let t = match store.host_transfer(&self.local_id, &transfer_id) { + Ok(Some(t)) => t, + Ok(None) => return err(AppError::Invalid, "Unknown transfer id."), + Err(e) => return unavailable("reading transfer", &e), + }; + if t.player_id != *player { + return err(AppError::NotYours, "Transfer does not belong to this player."); + } + match t.state { + TransferState::Receiving => Response::TransferReady { transfer_id, received_offset: t.received_size }, + TransferState::Committed | TransferState::Acknowledged => { + Response::TransferCommitted { + transfer_id, + character_id: t.character_id, + local_guid: t.local_guid.unwrap_or_default(), + session_id: t.session_id.unwrap_or_default(), + projected_level: t.projected_level, + notes: t.notes, + } + } + } + } + + fn transfer_commit(&self, player: &Uuid, transfer_id: Uuid) -> Response { + let Ok(_guard) = self.write.lock() else { return err(AppError::Unavailable, "Busy.") }; + let store = match self.store.lock() { + Ok(s) => s, + Err(_) => return err(AppError::Unavailable, "Busy."), + }; + let t = match store.host_transfer(&self.local_id, &transfer_id) { + Ok(Some(t)) => t, + Ok(None) => return err(AppError::Invalid, "Unknown transfer id."), + Err(e) => return unavailable("reading transfer", &e), + }; + drop(store); + + if t.player_id != *player { + return err(AppError::NotYours, "Transfer does not belong to this player."); + } + if t.state != TransferState::Receiving { + if let (Some(guid), Some(sid)) = (t.local_guid, t.session_id) { + return Response::TransferCommitted { + transfer_id, + character_id: t.character_id, + local_guid: guid, + session_id: sid, + projected_level: t.projected_level, + notes: t.notes, + }; + } + } + + if t.received_size != t.total_size { + return err(AppError::Invalid, "Transfer incomplete."); + } + + let path = self.transfer_path(&transfer_id); + let payload = match std::fs::read(&path) { + Ok(b) => b, + Err(e) => return unavailable("reading transfer file", &Error::Invalid(e.to_string())), + }; + + use sha2::{Digest, Sha256}; + let hash = hex::encode(Sha256::digest(&payload)); + if hash != t.content_hash { + let _ = std::fs::remove_file(&path); + return err(AppError::Invalid, "Content hash mismatch."); + } + + let mut hash_bytes = [0u8; 32]; + if hex::decode_to_slice(&t.content_hash, &mut hash_bytes).is_err() { + return err(AppError::Invalid, "Invalid content hash format."); + } + + let Some(m) = self.mapping(player) else { return err(AppError::NoAccount, "Player has no account on this realm.") }; + + let params = RemoteImportParams { + character_id: t.character_id, + revision: t.revision, + payload, + content_hash: hash_bytes, + collections: t.collections, + account_id: m.account_id, + }; + + let outcome = match self.backend.import_remote(&self.local_id, params) { + Ok(o) => o, + Err(e) => { + let _ = std::fs::remove_file(&path); + return unavailable("importing character", &e); + } + }; + + let _ = std::fs::remove_file(&path); + + if let Ok(s) = self.store.lock() { + let _ = s.host_transfer_commit(&transfer_id, outcome.local_guid, &outcome.session_id, outcome.projected_level, &outcome.notes); + let _ = s.host_claim_set(&self.local_id, outcome.local_guid, &t.character_id, player); + let _ = s.host_claim_acknowledge(&self.local_id, &t.character_id, player); + } + + Response::TransferCommitted { + transfer_id, + character_id: t.character_id, + local_guid: outcome.local_guid, + session_id: outcome.session_id, + projected_level: outcome.projected_level, + notes: outcome.notes, + } + } + + fn transfer_ack(&self, player: &Uuid, transfer_id: Uuid, _character_id: Uuid) -> Response { + let Ok(_guard) = self.write.lock() else { return err(AppError::Unavailable, "Busy.") }; + if let Ok(s) = self.store.lock() { + if let Ok(Some(t)) = s.host_transfer(&self.local_id, &transfer_id) { + if t.player_id == *player { + let _ = s.host_transfer_ack(&transfer_id); + } + } + } + Response::Done + } } #[cfg(any(test, feature = "testkit"))] @@ -346,6 +681,8 @@ pub mod fake { pub online: Mutex>, pub exports: Mutex>, pub seen_passwords: Mutex>, + pub imported: Mutex>, + pub incompatible: Mutex>, } impl FakeRealm { @@ -411,6 +748,22 @@ pub mod fake { let id = *self.exports.lock().unwrap().entry(guid).or_insert_with(Uuid::now_v7); Ok(ClaimExport { character_id: id, payload: format!("payload-{guid}").into_bytes(), sha256: [7; 32], collections: BTreeMap::from([("coa:appearance".to_string(), vec![1, 2, 3])]) }) } + fn check_transfer(&self, _: &str, character_id: Uuid, _: u64) -> Result { + if self.incompatible.lock().unwrap().contains(&character_id) { + Ok(PreflightVerdict::Incompatible) + } else { + Ok(PreflightVerdict::Compatible) + } + } + fn import_remote(&self, _: &str, params: RemoteImportParams) -> Result { + if self.incompatible.lock().unwrap().contains(¶ms.character_id) { + return Err(Error::Invalid("Character is incompatible with this realm.".into())); + } + let mut map = self.imported.lock().unwrap(); + let len = map.len() as u32 + 100; + let (guid, sid) = *map.entry(params.character_id).or_insert((len, Uuid::now_v7())); + Ok(RemoteImportOutcome { local_guid: guid, session_id: sid, projected_level: None, notes: vec![] }) + } } } @@ -609,4 +962,268 @@ mod tests { *realm.route.lock().unwrap() = Some("203.0.113.5:3724".into()); assert_eq!(s.handle(&mut Session::default(), &p, "K", Request::Route), Response::RouteInfo { address: Some("203.0.113.5:3724".into()) }); } + + #[test] + fn remote_transfer_lifecycle_empty_realm_import_and_ack() { + let (realm, s, p, _acc) = claimed_setup(); + let mut session = Session::default(); + let cid = Uuid::now_v7(); + let tid = Uuid::now_v7(); + + let payload = b"portable_character_snapshot_payload_test_data".to_vec(); + use sha2::{Digest, Sha256}; + let hash = hex::encode(Sha256::digest(&payload)); + + // 1. Offer + let offer = Request::TransferOffer { + transfer_id: tid, + character_id: cid, + canonical_revision: 1, + content_hash: hash.clone(), + total_size: payload.len(), + collections: BTreeMap::from([("coa:appearance".into(), vec![1, 2, 3])]), + }; + let r = s.handle(&mut session, &p, "K", offer); + assert_eq!(r, Response::TransferReady { transfer_id: tid, received_offset: 0 }); + + // 2. Chunk + use base64::Engine; + let data = base64::engine::general_purpose::STANDARD.encode(&payload); + let chunk = Request::TransferChunk { transfer_id: tid, offset: 0, data }; + let r = s.handle(&mut session, &p, "K", chunk); + assert_eq!(r, Response::TransferChunkAck { transfer_id: tid, received_offset: payload.len() }); + + // 3. Commit + let commit = Request::TransferCommit { transfer_id: tid }; + let r = s.handle(&mut session, &p, "K", commit); + let Response::TransferCommitted { transfer_id, character_id, local_guid, session_id, .. } = r else { panic!("{r:?}") }; + assert_eq!(transfer_id, tid); + assert_eq!(character_id, cid); + assert!(local_guid >= 100); + assert_ne!(session_id, Uuid::nil()); + + // 4. Ack + let ack = Request::TransferAck { transfer_id: tid, character_id: cid }; + assert_eq!(s.handle(&mut session, &p, "K", ack), Response::Done); + + // Verify imported in realm + assert!(realm.imported.lock().unwrap().contains_key(&cid)); + } + + #[test] + fn remote_transfer_incompatible_rejected_writes_nothing() { + let (realm, s, p, _acc) = claimed_setup(); + let mut session = Session::default(); + let cid = Uuid::now_v7(); + let tid = Uuid::now_v7(); + + // Mark incompatible in realm + realm.incompatible.lock().unwrap().insert(cid); + + let offer = Request::TransferOffer { + transfer_id: tid, + character_id: cid, + canonical_revision: 1, + content_hash: "a".repeat(64), + total_size: 100, + collections: BTreeMap::new(), + }; + let r = s.handle(&mut session, &p, "K", offer); + assert!(matches!(r, Response::Error { code: AppError::Incompatible, .. }), "{r:?}"); + + // Nothing written + assert!(realm.imported.lock().unwrap().is_empty()); + } + + #[test] + fn remote_transfer_interrupted_resumes_safely() { + let (_realm, s, p, _acc) = claimed_setup(); + let mut session = Session::default(); + let cid = Uuid::now_v7(); + let tid = Uuid::now_v7(); + + let chunk1 = b"first_chunk_of_payload_"; + let chunk2 = b"second_chunk_of_payload"; + let mut full = chunk1.to_vec(); + full.extend_from_slice(chunk2); + + use sha2::{Digest, Sha256}; + let hash = hex::encode(Sha256::digest(&full)); + + let offer = Request::TransferOffer { + transfer_id: tid, + character_id: cid, + canonical_revision: 1, + content_hash: hash.clone(), + total_size: full.len(), + collections: BTreeMap::new(), + }; + let r = s.handle(&mut session, &p, "K", offer); + assert_eq!(r, Response::TransferReady { transfer_id: tid, received_offset: 0 }); + + // Send chunk 1 + use base64::Engine; + let c1_b64 = base64::engine::general_purpose::STANDARD.encode(chunk1); + let r = s.handle(&mut session, &p, "K", Request::TransferChunk { transfer_id: tid, offset: 0, data: c1_b64 }); + assert_eq!(r, Response::TransferChunkAck { transfer_id: tid, received_offset: chunk1.len() }); + + // Query status (resuming after interruption) + let r = s.handle(&mut session, &p, "K", Request::TransferStatus { transfer_id: tid }); + assert_eq!(r, Response::TransferReady { transfer_id: tid, received_offset: chunk1.len() }); + + // Send chunk 2 + let c2_b64 = base64::engine::general_purpose::STANDARD.encode(chunk2); + let r = s.handle(&mut session, &p, "K", Request::TransferChunk { transfer_id: tid, offset: chunk1.len(), data: c2_b64 }); + assert_eq!(r, Response::TransferChunkAck { transfer_id: tid, received_offset: full.len() }); + + // Commit succeeds + let r = s.handle(&mut session, &p, "K", Request::TransferCommit { transfer_id: tid }); + assert!(matches!(r, Response::TransferCommitted { .. })); + } + + #[test] + fn remote_transfer_lost_reply_idempotency_does_not_duplicate() { + let (realm, s, p, _acc) = claimed_setup(); + let mut session = Session::default(); + let cid = Uuid::now_v7(); + let tid = Uuid::now_v7(); + + let payload = b"idempotency_test_payload".to_vec(); + use sha2::{Digest, Sha256}; + let hash = hex::encode(Sha256::digest(&payload)); + + let offer = Request::TransferOffer { + transfer_id: tid, + character_id: cid, + canonical_revision: 1, + content_hash: hash.clone(), + total_size: payload.len(), + collections: BTreeMap::new(), + }; + s.handle(&mut session, &p, "K", offer); + + use base64::Engine; + let data = base64::engine::general_purpose::STANDARD.encode(&payload); + s.handle(&mut session, &p, "K", Request::TransferChunk { transfer_id: tid, offset: 0, data }); + + let Response::TransferCommitted { local_guid: guid1, session_id: sid1, .. } = s.handle(&mut session, &p, "K", Request::TransferCommit { transfer_id: tid }) else { panic!() }; + assert_eq!(realm.imported.lock().unwrap().len(), 1); + + // Client retries commit (lost reply): + let Response::TransferCommitted { local_guid: guid2, session_id: sid2, .. } = s.handle(&mut session, &p, "K", Request::TransferCommit { transfer_id: tid }) else { panic!() }; + assert_eq!(guid1, guid2); + assert_eq!(sid1, sid2); + assert_eq!(realm.imported.lock().unwrap().len(), 1, "does not duplicate character"); + + // Client starts a new transfer for the exact same committed revision: discovers committed state + let tid2 = Uuid::now_v7(); + let offer2 = Request::TransferOffer { + transfer_id: tid2, + character_id: cid, + canonical_revision: 1, + content_hash: hash, + total_size: payload.len(), + collections: BTreeMap::new(), + }; + let r = s.handle(&mut session, &p, "K", offer2); + let Response::TransferCommitted { local_guid: guid3, session_id: sid3, .. } = r else { panic!("{r:?}") }; + assert_eq!(guid1, guid3); + assert_eq!(sid1, sid3); + assert_eq!(realm.imported.lock().unwrap().len(), 1, "does not duplicate character"); + } + + #[test] + fn wrong_player_identity_cannot_overwrite_another_players_realm_copy() { + let (_realm, s, p, _acc) = claimed_setup(); + let cid = Uuid::now_v7(); + let tid = Uuid::now_v7(); + + let payload = b"player_1_character_data".to_vec(); + use sha2::{Digest, Sha256}; + let hash = hex::encode(Sha256::digest(&payload)); + + let offer = Request::TransferOffer { + transfer_id: tid, + character_id: cid, + canonical_revision: 1, + content_hash: hash.clone(), + total_size: payload.len(), + collections: BTreeMap::new(), + }; + assert!(matches!(s.handle(&mut Session::default(), &p, "K", offer), Response::TransferReady { .. })); + use base64::Engine; + let data = base64::engine::general_purpose::STANDARD.encode(&payload); + s.handle(&mut Session::default(), &p, "K", Request::TransferChunk { transfer_id: tid, offset: 0, data }); + assert!(matches!(s.handle(&mut Session::default(), &p, "K", Request::TransferCommit { transfer_id: tid }), Response::TransferCommitted { .. })); + assert_eq!(s.handle(&mut Session::default(), &p, "K", Request::TransferAck { transfer_id: tid, character_id: cid }), Response::Done); + + // Player 2 attempts to transfer with the same character_id + let q = Uuid::now_v7(); + let srv = &s; + // Provision account for player 2 + let pw = app::generate_password(); + assert!(matches!(srv.handle(&mut Session::default(), &q, "KQ", Request::Provision { desired: Some("PLAYER2".into()), password: pw, have_credentials: false }), Response::Provisioned { .. })); + + let tid_impostor = Uuid::now_v7(); + let impostor_offer = Request::TransferOffer { + transfer_id: tid_impostor, + character_id: cid, + canonical_revision: 2, + content_hash: "b".repeat(64), + total_size: 100, + collections: BTreeMap::new(), + }; + let r = srv.handle(&mut Session::default(), &q, "KQ", impostor_offer); + assert!(matches!(r, Response::Error { code: AppError::AlreadyClaimed, .. }), "{r:?}"); + } + + #[test] + fn same_character_transferred_again_as_newer_revision_performs_update() { + let (realm, s, p, _acc) = claimed_setup(); + let mut session = Session::default(); + let cid = Uuid::now_v7(); + let tid1 = Uuid::now_v7(); + + let payload1 = b"character_revision_1_data".to_vec(); + use sha2::{Digest, Sha256}; + let hash1 = hex::encode(Sha256::digest(&payload1)); + + // Rev 1 + s.handle(&mut session, &p, "K", Request::TransferOffer { + transfer_id: tid1, + character_id: cid, + canonical_revision: 1, + content_hash: hash1, + total_size: payload1.len(), + collections: BTreeMap::new(), + }); + use base64::Engine; + let d1 = base64::engine::general_purpose::STANDARD.encode(&payload1); + s.handle(&mut session, &p, "K", Request::TransferChunk { transfer_id: tid1, offset: 0, data: d1 }); + let Response::TransferCommitted { local_guid: guid1, .. } = s.handle(&mut session, &p, "K", Request::TransferCommit { transfer_id: tid1 }) else { panic!() }; + s.handle(&mut session, &p, "K", Request::TransferAck { transfer_id: tid1, character_id: cid }); + assert_eq!(realm.imported.lock().unwrap().len(), 1); + + // Rev 2 + let tid2 = Uuid::now_v7(); + let payload2 = b"character_revision_2_newer_data".to_vec(); + let hash2 = hex::encode(Sha256::digest(&payload2)); + let r = s.handle(&mut session, &p, "K", Request::TransferOffer { + transfer_id: tid2, + character_id: cid, + canonical_revision: 2, + content_hash: hash2, + total_size: payload2.len(), + collections: BTreeMap::new(), + }); + assert!(matches!(r, Response::TransferReady { .. })); + let d2 = base64::engine::general_purpose::STANDARD.encode(&payload2); + s.handle(&mut session, &p, "K", Request::TransferChunk { transfer_id: tid2, offset: 0, data: d2 }); + let Response::TransferCommitted { local_guid: guid2, .. } = s.handle(&mut session, &p, "K", Request::TransferCommit { transfer_id: tid2 }) else { panic!() }; + s.handle(&mut session, &p, "K", Request::TransferAck { transfer_id: tid2, character_id: cid }); + + // Same local guid, updated, not duplicate + assert_eq!(guid1, guid2); + assert_eq!(realm.imported.lock().unwrap().len(), 1, "update, not duplicate import"); + } } diff --git a/crates/coa-core/src/control/store.rs b/crates/coa-core/src/control/store.rs index ade0634..e6b6fc4 100644 --- a/crates/coa-core/src/control/store.rs +++ b/crates/coa-core/src/control/store.rs @@ -4,6 +4,7 @@ //! characters were claimed by which PlayerId (a binding of a PortableCharacterId to a PlayerIdentity). //! * Player side: for each remote realm the account name the player plays with (the password is in the secret store) and which characters came from it. +use std::collections::BTreeMap; use std::path::Path; use rusqlite::{params, Connection, OptionalExtension}; @@ -51,6 +52,25 @@ CREATE TABLE IF NOT EXISTS player_claim( claimed_at TEXT NOT NULL, PRIMARY KEY (realm_id, character_id) ); +CREATE TABLE IF NOT EXISTS host_transfer( + realm_local_id TEXT NOT NULL, + transfer_id TEXT NOT NULL PRIMARY KEY, + character_id TEXT NOT NULL, + player_id TEXT NOT NULL, + revision INTEGER NOT NULL, + content_hash TEXT NOT NULL, + total_size INTEGER NOT NULL, + received_size INTEGER NOT NULL, + state TEXT NOT NULL CHECK (state IN ('receiving', 'committed', 'acknowledged')), + local_guid INTEGER, + session_id TEXT, + projected_level INTEGER, + notes TEXT, + collections TEXT NOT NULL DEFAULT '{}', + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL +); +CREATE INDEX IF NOT EXISTS host_transfer_char ON host_transfer(realm_local_id, character_id); "; fn now() -> String { @@ -106,6 +126,48 @@ pub struct HostClaim { pub state: ClaimState, } +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum TransferState { + Receiving, + Committed, + Acknowledged, +} + +impl TransferState { + pub fn as_str(self) -> &'static str { + match self { + TransferState::Receiving => "receiving", + TransferState::Committed => "committed", + TransferState::Acknowledged => "acknowledged", + } + } + pub fn parse(s: &str) -> Self { + match s { + "committed" => TransferState::Committed, + "acknowledged" => TransferState::Acknowledged, + _ => TransferState::Receiving, + } + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct HostTransfer { + pub realm_local_id: String, + pub transfer_id: Uuid, + pub character_id: Uuid, + pub player_id: Uuid, + pub revision: u64, + pub content_hash: String, + pub total_size: usize, + pub received_size: usize, + pub state: TransferState, + pub local_guid: Option, + pub session_id: Option, + pub projected_level: Option, + pub notes: Vec, + pub collections: BTreeMap>, +} + #[derive(Clone, Debug, PartialEq, Eq)] pub struct PlayerRealm { pub realm_id: String, @@ -199,6 +261,105 @@ impl ControlStore { Ok(n == 1) } + pub fn host_claim_of_character(&self, realm: &str, character: &Uuid) -> Result> { + self.conn + .query_row("SELECT local_guid, character_id, player_id, state FROM host_claim WHERE realm_local_id = ?1 AND character_id = ?2 LIMIT 1", params![realm, character.to_string()], row_claim) + .optional() + .map_err(db)? + .transpose() + } + + pub fn host_transfer(&self, realm: &str, transfer_id: &Uuid) -> Result> { + self.conn + .query_row( + "SELECT realm_local_id, transfer_id, character_id, player_id, revision, content_hash, total_size, received_size, state, local_guid, session_id, projected_level, notes, collections FROM host_transfer WHERE realm_local_id = ?1 AND transfer_id = ?2", + params![realm, transfer_id.to_string()], + row_transfer, + ) + .optional() + .map_err(db)? + .transpose() + } + + pub fn host_transfer_latest(&self, realm: &str, character_id: &Uuid) -> Result> { + self.conn + .query_row( + "SELECT realm_local_id, transfer_id, character_id, player_id, revision, content_hash, total_size, received_size, state, local_guid, session_id, projected_level, notes, collections FROM host_transfer WHERE realm_local_id = ?1 AND character_id = ?2 ORDER BY updated_at DESC LIMIT 1", + params![realm, character_id.to_string()], + row_transfer, + ) + .optional() + .map_err(db)? + .transpose() + } + + pub fn host_transfer_save(&self, t: &HostTransfer) -> Result<()> { + let notes_json = serde_json::to_string(&t.notes).unwrap_or_default(); + let coll_json = serde_json::to_string(&t.collections).unwrap_or_default(); + self.conn + .execute( + "INSERT INTO host_transfer(realm_local_id, transfer_id, character_id, player_id, revision, content_hash, total_size, received_size, state, local_guid, session_id, projected_level, notes, collections, created_at, updated_at) + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16) + ON CONFLICT(transfer_id) DO UPDATE SET + received_size = excluded.received_size, + state = excluded.state, + local_guid = excluded.local_guid, + session_id = excluded.session_id, + projected_level = excluded.projected_level, + notes = excluded.notes, + collections = excluded.collections, + updated_at = excluded.updated_at", + params![ + t.realm_local_id, + t.transfer_id.to_string(), + t.character_id.to_string(), + t.player_id.to_string(), + t.revision as i64, + t.content_hash, + t.total_size as i64, + t.received_size as i64, + t.state.as_str(), + t.local_guid, + t.session_id.map(|s| s.to_string()), + t.projected_level, + notes_json, + coll_json, + now(), + now(), + ], + ) + .map_err(db)?; + Ok(()) + } + + pub fn host_transfer_update_progress(&self, transfer_id: &Uuid, received: usize) -> Result<()> { + self.conn + .execute("UPDATE host_transfer SET received_size = ?1, updated_at = ?2 WHERE transfer_id = ?3", params![received as i64, now(), transfer_id.to_string()]) + .map_err(db)?; + Ok(()) + } + + pub fn host_transfer_commit(&self, transfer_id: &Uuid, local_guid: u32, session_id: &Uuid, projected_level: Option, notes: &[String]) -> Result<()> { + let notes_json = serde_json::to_string(notes).unwrap_or_default(); + self.conn + .execute( + "UPDATE host_transfer SET state = 'committed', local_guid = ?1, session_id = ?2, projected_level = ?3, notes = ?4, updated_at = ?5 WHERE transfer_id = ?6", + params![local_guid, session_id.to_string(), projected_level, notes_json, now(), transfer_id.to_string()], + ) + .map_err(db)?; + Ok(()) + } + + pub fn host_transfer_ack(&self, transfer_id: &Uuid) -> Result { + let n = self.conn.execute("UPDATE host_transfer SET state = 'acknowledged', updated_at = ?1 WHERE transfer_id = ?2", params![now(), transfer_id.to_string()]).map_err(db)?; + Ok(n == 1) + } + + pub fn host_transfer_delete(&self, transfer_id: &Uuid) -> Result<()> { + self.conn.execute("DELETE FROM host_transfer WHERE transfer_id = ?1", params![transfer_id.to_string()]).map_err(db)?; + Ok(()) + } + // ---- Player ------------------------------------------------------------------------------------------------------------------ pub fn player_realm(&self, realm_id: &str) -> Result> { @@ -260,6 +421,43 @@ fn row_claim(r: &rusqlite::Row<'_>) -> rusqlite::Result> { Ok((|| Ok(HostClaim { local_guid: guid, character_id: uuid(cid)?, player_id: uuid(pid)?, state: if state == "acknowledged" { ClaimState::Acknowledged } else { ClaimState::Exported } }))()) } +fn row_transfer(r: &rusqlite::Row<'_>) -> rusqlite::Result> { + let realm_local_id: String = r.get(0)?; + let tid: String = r.get(1)?; + let cid: String = r.get(2)?; + let pid: String = r.get(3)?; + let revision: i64 = r.get(4)?; + let content_hash: String = r.get(5)?; + let total_size: i64 = r.get(6)?; + let received_size: i64 = r.get(7)?; + let state_str: String = r.get(8)?; + let local_guid: Option = r.get(9)?; + let session_str: Option = r.get(10)?; + let projected_level: Option = r.get(11)?; + let notes_str: Option = r.get(12)?; + let notes = notes_str.and_then(|s| serde_json::from_str::>(&s).ok()).unwrap_or_default(); + let coll_str: Option = r.get(13)?; + let collections = coll_str.and_then(|s| serde_json::from_str::>>(&s).ok()).unwrap_or_default(); + Ok((|| { + Ok(HostTransfer { + realm_local_id, + transfer_id: uuid(tid)?, + character_id: uuid(cid)?, + player_id: uuid(pid)?, + revision: revision as u64, + content_hash, + total_size: total_size as usize, + received_size: received_size as usize, + state: TransferState::parse(&state_str), + local_guid, + session_id: session_str.map(uuid).transpose()?, + projected_level, + notes, + collections, + }) + })()) +} + #[cfg(test)] mod tests { use super::*; @@ -313,4 +511,48 @@ mod tests { let raw = std::fs::read(dir.path().join("control.sqlite")).unwrap(); assert!(!String::from_utf8_lossy(&raw).to_lowercase().contains("password"), "the schema has no password column"); } + + #[test] + fn host_transfer_roundtrip_and_lifecycle() { + let s = ControlStore::open_in_memory().unwrap(); + let (p, c, t, sid) = (Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7()); + let transfer = HostTransfer { + realm_local_id: "live".into(), + transfer_id: t, + character_id: c, + player_id: p, + revision: 3, + content_hash: "a".repeat(64), + total_size: 4096, + received_size: 0, + state: TransferState::Receiving, + local_guid: None, + session_id: None, + projected_level: None, + notes: vec![], + collections: BTreeMap::from([("coa:appearance".into(), vec![1, 2, 3])]), + }; + s.host_transfer_save(&transfer).unwrap(); + let got = s.host_transfer("live", &t).unwrap().unwrap(); + assert_eq!(got.state, TransferState::Receiving); + assert_eq!(got.total_size, 4096); + + s.host_transfer_update_progress(&t, 2048).unwrap(); + let got = s.host_transfer("live", &t).unwrap().unwrap(); + assert_eq!(got.received_size, 2048); + + s.host_transfer_commit(&t, 101, &sid, Some(60), &["projected 60".into()]).unwrap(); + let got = s.host_transfer("live", &t).unwrap().unwrap(); + assert_eq!(got.state, TransferState::Committed); + assert_eq!(got.local_guid, Some(101)); + assert_eq!(got.session_id, Some(sid)); + assert_eq!(got.projected_level, Some(60)); + + let latest = s.host_transfer_latest("live", &c).unwrap().unwrap(); + assert_eq!(latest.transfer_id, t); + + assert!(s.host_transfer_ack(&t).unwrap()); + let got = s.host_transfer("live", &t).unwrap().unwrap(); + assert_eq!(got.state, TransferState::Acknowledged); + } } diff --git a/crates/coa-core/src/control/transport.rs b/crates/coa-core/src/control/transport.rs index f74b03e..2f2186b 100644 --- a/crates/coa-core/src/control/transport.rs +++ b/crates/coa-core/src/control/transport.rs @@ -83,6 +83,11 @@ pub fn coordinator_url(registry_url: &str, path: &str) -> Option { Some(format!("{rest}{path}")) } +pub fn relay_url(registry_url: &str, path: &str) -> Option { + coordinator_url(registry_url, path) +} + + pub fn connect(url: &str, read_timeout: Duration) -> Result { let (mut ws, _) = tungstenite::connect(url).map_err(|e| LinkError::Io(clean(&e.to_string())))?; set_timeouts(&mut ws, read_timeout); diff --git a/crates/coa-core/src/portable/service/engine.rs b/crates/coa-core/src/portable/service/engine.rs index 628c8eb..3b613ee 100644 --- a/crates/coa-core/src/portable/service/engine.rs +++ b/crates/coa-core/src/portable/service/engine.rs @@ -994,6 +994,125 @@ impl PortableService { self.state().characters.into_iter().find(|c| c.id == character_id.to_string()).ok_or_else(|| fail("other", "The character was not registered.")) } + /// Export a canonical character and collections for transfer to a remote realm (Phase 12.1). + pub fn export_for_remote_transfer(&self, character: &str) -> Res { + let cid = self.cid(character)?; + let model = self.owner.load_current(cid)?; + let encoded = super::super::snapshot::encode(&model)?; + let mut collections = BTreeMap::new(); + for kind in ["coa:appearance", "coa:vanity"] { + if let Ok(Some((_, set))) = self.owner.collection(self.owner_profile, kind) { + collections.insert(kind.to_string(), set.ids().to_vec()); + } + } + Ok(ClaimBundle { + character_id: cid, + payload: encoded.payload, + content_hash: encoded.content_hash, + collections, + }) + } + + /// Preflight check for remote transfer before receiving payload chunks (Phase 12.1). + pub fn check_remote_transfer(&mut self, realm_id: &str, character_id: CharacterId, _revision: u64) -> Res { + let access = self.access(realm_id)?; + self.refresh_obs(realm_id, false); + let obs = self.obs.get(realm_id).map(|o| (o.db_ok, o.ra_ok)).unwrap_or((false, false)); + if !obs.0 { + return Err(fail("realm_offline", "The realm's database cannot be reached.")); + } + if let Ok(model) = self.host.load_current(character_id) { + let db = access.db()?; + let caps = match self.remembered(&access, &db) { + Some(c) => c, + None => return Ok(crate::control::service::PreflightVerdict::Compatible), + }; + let opts = self.options(&access, &caps); + let ops = [Operation::OnlineImport, Operation::RuntimeSession]; + let report = self.report(&model, &caps, &opts, &ops, obs.1); + match verdict_of(report.verdict()) { + Verdict::Incompatible => return Ok(crate::control::service::PreflightVerdict::Incompatible), + Verdict::Degraded => return Ok(crate::control::service::PreflightVerdict::Degraded), + Verdict::Compatible => return Ok(crate::control::service::PreflightVerdict::Compatible), + } + } + Ok(crate::control::service::PreflightVerdict::Compatible) + } + + /// Import or update a transferred character into the remote realm and arm a session (Phase 12.1). + pub fn import_remote_character(&mut self, realm_id: &str, params: crate::control::service::RemoteImportParams) -> Res { + let cid = CharacterId::from_uuid(params.character_id)?; + let model = super::super::snapshot::decode(¶ms.payload, Some(¶ms.content_hash))?; + if model.character_id != cid { + return Err(fail("other", "The character data does not belong to the character that was transferred.")); + } + + let access = self.access(realm_id)?; + let db = access.db()?; + let mut ra = access.ra().map_err(|e| fail("realm_offline", e.to_string()))?; + let caps = self.capabilities(&access, &db, &mut ra, true)?; + let opts = self.options(&access, &caps); + + // Preflight compatibility check before ANY mutation + let ops = [Operation::OnlineImport, Operation::RuntimeSession]; + let report = self.report(&model, &caps, &opts, &ops, true); + if verdict_of(report.verdict()) == Verdict::Incompatible { + return Err(fail("incompatible", "Character is incompatible with this realm; nothing was changed.")); + } + + // Install or advance copy in host store + self.host.host_install_copy(self.host_profile, &model, params.revision, "remote")?; + + // Monotonic union of collections + for (kind, ids) in ¶ms.collections { + if matches!(kind.as_str(), "coa:appearance" | "coa:vanity") { + if let Ok(set) = super::super::collection::IdSet::from_ids(ids.iter().copied()) { + let _ = self.host.merge_collection(self.host_profile, kind, &set); + } + } + } + + let existing_mapping = self.host.server_mappings(cid)?.into_iter().find(|m| m.server_id == realm_id); + + let session_id = SessionId::new(); + let envelope = super::super::session::protocol::Envelope::from_encoded(&super::super::snapshot::encode(&model)?); + let offer = super::super::session::protocol::SessionOffer { + protocol_version: super::super::session::protocol::PROTOCOL_VERSION, + session_id, + character_id: cid, + server_id: realm_id.to_string(), + canonical_revision: params.revision, + snapshot: envelope, + }; + HostService::new(&mut self.host, realm_id, self.host_config.clone()).accept_offer(self.host_profile, &offer)?; + + let local_guid = if let Some(m) = existing_mapping { + // Already exists on realm: arm session on existing copy + let mut bridge = LiveBridge::new(&db, ra); + bridge.arm(m.local_guid, offer.session_id, cid, params.revision, 1)?; + HostService::new(&mut self.host, realm_id, self.host_config.clone()).bind(offer.session_id, m.local_guid)?; + m.local_guid + } else { + // Import online into running realm + let imported = import_character_online_on(Some(&db), &mut ra, &mut self.host, cid, realm_id, params.account_id, &opts, &access.job_dir, Some(offer.session_id))?; + HostService::new(&mut self.host, realm_id, self.host_config.clone()).bind(offer.session_id, imported.local_guid)?; + imported.local_guid + }; + + self.reproject.remove(&(cid, realm_id.to_string())); + self.publish(); + + let projected_level = caps.progression.as_ref().filter(|p| u32::from(model.progression.level) > p.max_player_level).map(|p| p.max_player_level); + let notes = notes_of(&report).into_iter().map(|n| n.detail).collect(); + + Ok(crate::control::service::RemoteImportOutcome { + local_guid, + session_id: session_id.as_uuid(), + projected_level, + notes, + }) + } + /// The two ways out of a divergence the Manager does not own. pub fn resolve(&mut self, character: &str, realm_id: &str, action: Resolve) -> Res<()> { let cid = self.cid(character)?; diff --git a/docs/CONTROL_PROTOCOL.md b/docs/CONTROL_PROTOCOL.md index 45804b2..22e5364 100644 --- a/docs/CONTROL_PROTOCOL.md +++ b/docs/CONTROL_PROTOCOL.md @@ -98,9 +98,11 @@ Application messages: requests ≤ 4096 bytes, strict JSON with unknown fields r | `list_characters` | `characters{characters}` | the characters of the player's account (opaque per-connection handles; the realm's own numbers never leave the Host) | | `claim{token}` | `claimed{character_id, sha256, payload, collections}` | export one character (section 7) | | `claim_ack{character_id}` | `done` | the player stored it; the claim is final | +| `transfer_character{character_id, revision, sha256, payload, collections}` | `transferred{character_id, local_guid, session_id}` | transactional remote character import/projection (Phase 12.1) | +| `allocate_relay` | `relay_allocated{relay_host, auth_port, world_port, token, expires_at}` | dynamic game relay allocation for NAT traversal (Phase 13) | | `route` | `route_info{address}` | the address the game client can use right now, if the owner stated one | -Errors (`error{code,message}`): `unsupported_version`, `invalid`, `provisioning_off`, `no_account`, `not_at_character_select`, `not_yours`, `already_claimed`, `not_eligible`, `wrong_credentials`, `account_taken`, `rate_limited`, `unavailable`. +Errors (`error{code,message}`): `unsupported_version`, `invalid`, `provisioning_off`, `no_account`, `not_at_character_select`, `not_yours`, `already_claimed`, `not_eligible`, `wrong_credentials`, `account_taken`, `rate_limited`, `unavailable`, `incompatible`, `relay_unavailable`. Backend failures are logged on the Host and answered as `unavailable` without internals. ## 6. Accounts @@ -137,6 +139,32 @@ Then the Host exports the character with the same code as *Make portable* (one c appearance and vanity collections, all inside the channel. The Player's Manager decodes it **with verification** (hash, format, that the character id is the one claimed), stores it as **canonical revision 1** with the collections merged into its profile, and only then sends `claim_ack`; the Host marks the binding `PortableCharacterId ↔ PlayerIdentity` as acknowledged. An unacknowledged claim can be repeated by the same player and returns the same character; nobody else can take it. +## 7.1 Remote Portable Character Transfer (Phase 12.1) + +When a player selects a portable character that exists in their Player Manager but does not yet exist on the remote realm, the Player Manager performs an automated, transactional transfer over the encrypted Noise channel: + +1. **Preflight Compatibility Check**: The Player Manager checks the canonical character against the target realm's advertised capabilities (Phase 7/8). If incompatible, the transfer is refused immediately before any network mutation. +2. **Payload Transfer**: Inside the end-to-end encrypted Noise channel, the Player Manager sends `transfer_character{character_id, revision, sha256, payload, collections}`. The Coordinator sees only opaque ciphertext. +3. **Host Validation**: The Host validates: + - PlayerIdentity proof of ownership; + - `PortableCharacter` format version, schema integrity, and SHA-256 payload hash; + - Target realm account mapping for this player; + - Level projection policy (e.g. projecting level 80 down to realm cap 60 via Phase-8 oracle); + - Idempotency: if this exact canonical revision was already imported, the existing working copy GUID and armed session ID are returned immediately without duplicating the character; + - Revision update: if a newer canonical revision is transferred, the Host updates the existing working copy rather than creating a duplicate character. +4. **Outcome & Session Arming**: On successful import/projection, the Host returns `transferred{character_id, local_guid, session_id}`. The session engine arms the session for game login. + +## 7.2 Game Relay Allocation (Phase 13) + +When a realm is hosted behind NAT or CGNAT without direct port exposure, the Player Manager requests dynamic relay routing over the encrypted Noise channel: + +1. The Player Manager sends `allocate_relay`. +2. The Host asks its connected outbound tunnel to `coa-relay` (`wss://coa-manager.duckdns.org/relay/v1/host`) for an allocation. +3. `coa-relay` binds a dedicated pair of TCP ports from the dynamic game port pool (40000–40050) for `Auth` and `World`, generates a single-use token, and responds to the Host. +4. The Host returns `relay_allocated{relay_host, auth_port, world_port, token, expires_at}` to the Player inside the encrypted control channel. +5. The Player Manager points the client's `realmlist.wtf` to `relay_host:auth_port`. +6. When the client contacts `auth_port`, `coa-relay` dynamically rewrites the `address` field in the `CMD_REALM_LIST` response (opcode `0x10`) to `relay_host:world_port`, seamlessly directing the client to the allocated world tunnel without patching AzerothCore or modifying the database. + ## 8. Secrets on the player's machine `SecretStore` (`control/secrets.rs`) keeps the identity key and the realm passwords; nothing secret is in JSON, SQLite, a log or a diagnostic (`control.sqlite` holds names only, checked by the gate). @@ -149,11 +177,12 @@ its profile, and only then sends `claim_ack`; the Host marks the binding `Portab ## 9. JOIN -*Join this server* (`join_realm`): connect and verify the Host → `welcome` → (existing-only realm and no credentials: ask for the one-time link) → get or reuse the account → if a character was chosen: the existing Phase 7/8 -compatibility check against the capabilities in the Registry record (nothing is written when it is incompatible) → the realm's route → client check → write the realmlist (the existing Phase 9 machinery with backups) and start the game. -Outcomes that are **not failures but honest states**: `needs_link`, `needs_client` (no game client set up), `incompatible` (the verdict and its notes), `needs_transfer` (a character that did not come from this realm cannot be put on it -yet), and **`needs_relay`: "This server requires Relay support, which is not available yet."** when the owner has not stated an address the game client can reach (*Settings → Public listing → Address players connect to*, a host and optional port; it is data the -owner supplies, not discovery, NAT traversal or a relay). Connectivity is never faked. +*Join this server* (`join_realm`): connect and verify the Host → `welcome` → (existing-only realm and no credentials: ask for the one-time link) → get or reuse the account → if a character was chosen: +- if character does not exist on remote realm: initiate automated Remote Portable Character Transfer (Phase 12.1) over the encrypted channel; +- if realm requires relay: automatically allocate dynamic relay routes (Phase 13) via `allocate_relay`; +- write client `realmlist.wtf` (pointing to direct host:port or relay_host:auth_port) and launch the game. + +Outcomes: `ready` (route established, client configured, session armed), `needs_link` (existing-only realm credentials required), `needs_client` (no game client set up), `incompatible` (the verdict and notes if rejected). The previous `needs_transfer` and `needs_relay` blockers are now fully resolved by Phase 12.1 and Phase 13. The player is shown the account name and can **copy the name and the password** (the password is read from the protected store only when asked, shown only on request, never logged). diff --git a/docs/INFRASTRUCTURE.md b/docs/INFRASTRUCTURE.md index 361ed8e..ea6354c 100644 --- a/docs/INFRASTRUCTURE.md +++ b/docs/INFRASTRUCTURE.md @@ -12,7 +12,7 @@ This file never contains private keys, passwords, DB credentials, transfer PINs, Registry API Relay Coordinator PostgreSQL Caddy (ingress) monitoring ``` -Phase -1 prepared the host. **Phase 10 deployed the Registry and PostgreSQL** (see [REGISTRY_DEPLOYMENT.md](REGISTRY_DEPLOYMENT.md)); **Phase 12 deployed the Coordinator**; and the **Phases 11-12 TLS gate** enabled production HTTPS/WSS ingress. +Phase -1 prepared the host. **Phase 10 deployed the Registry and PostgreSQL** (see [REGISTRY_DEPLOYMENT.md](REGISTRY_DEPLOYMENT.md)); **Phase 12 deployed the Coordinator**; the **Phases 11-12 TLS gate** enabled production HTTPS/WSS ingress; and **Phase 13 deployed the Game Relay**. The VPS is not the source of truth for any player data. Public domain is `coa-manager.duckdns.org` pointing to `coa-infra-01`. Caddy automatically obtains and renews trusted Let's Encrypt TLS certificates via ACME. HTTP on port 80 redirects to HTTPS on port 443. @@ -32,13 +32,15 @@ Internet | +--> PostgreSQL (coa-postgres:5432, network coa-db only, --internal, no published port) | +--> Coordinator (coa-coordinator:8081, networks coa-ingress + coa-db, no published port) + | + +--> Game Relay (coa-relay:8082, networks coa-ingress + coa-db, published 40000-40050/tcp) ``` Rules: - PostgreSQL must never be internet-exposed: no `ports:` entry, only on the `coa-db` internal network, no UFW rule for 5432. -- Caddy is the only container allowed to publish ports (80, 443/tcp). A new inbound port needs a specific protocol and - a threat model first, then a UFW rule and a note here. +- Registry (8080), Coordinator (8081), and Relay control HTTP/WS (8082) have no published host ports; they are reverse-proxied exclusively through Caddy. +- Game Relay publishes the dedicated TCP port range `40000:40050/tcp` for relayed WoW client game streams (Auth & World). - No admin dashboards or the Docker API on public interfaces. Caddy's admin API is disabled. ## Public ports @@ -46,8 +48,9 @@ Rules: | Port | Proto | Service | |---|---|---| | 22 | tcp | SSH, key only | -| 80 | tcp | Caddy | -| 443 | tcp | Caddy | +| 80 | tcp | Caddy HTTP (redirects to HTTPS) | +| 443 | tcp | Caddy HTTPS / WSS | +| 40000-40050 | tcp | Game Relay WoW game traffic (Auth & World) | ## Filesystem layout @@ -57,8 +60,8 @@ Rules: ├── caddy/ compose.yaml, Caddyfile ├── postgres/ compose.yaml (running since Phase 10) ├── registry/ compose.yaml, .env, src/ (the build context of the running image) -├── relay/ (empty) -├── coordinator/ (empty) +├── coordinator/ compose.yaml, src/ +├── relay/ compose.yaml, src/ (coa-relay container) ├── monitoring/ (empty) ├── backups/ 0700, logical dumps and config archives ├── logs/ diff --git a/docs/RELAY_PROTOCOL.md b/docs/RELAY_PROTOCOL.md new file mode 100644 index 0000000..94669c0 --- /dev/null +++ b/docs/RELAY_PROTOCOL.md @@ -0,0 +1,112 @@ +# Game Relay Protocol (Phase 13) + +The Game Relay (`services/coa-relay`) provides TCP connectivity for WoW 3.3.5 clients when the realm's Host is behind NAT or CGNAT without port forwarding. + +The Relay is logically and operationally separate from the Registry and Coordinator: +- **Registry**: Public directory of realms (HTTPS). +- **Coordinator**: Control plane signaling and routing for Noise channels (WSS). +- **Game Relay**: Multiplexed byte tunnel for WoW client game traffic (`authserver` on TCP 3724 and `worldserver` on TCP 8085). + +--- + +## 1. Security Architecture and Invariants + +```text +WoW Client (3.3.5) + │ + ├── TCP :40000 (Auth) ──► [coa-relay] ◄── Outbound WSS ── [Host Manager] ──► 127.0.0.1:3724 (local authserver) + │ (:8082 internal) + └── TCP :40001 (World) ──► [coa-relay] ◄────────────────── [Host Manager] ──► 127.0.0.1:8085 (local worldserver) +``` + +1. **Host Outbound Only**: The Host initiates an outbound WebSocket connection to `wss://coa-manager.duckdns.org/relay/v1/host`. The Host requires zero inbound firewall openings or port forwarding. +2. **Strict Host Local Targets**: The Host's `RelayLink` worker strictly permits only two local targets: + - `RelayTarget::Auth` -> `127.0.0.1:3724` + - `RelayTarget::World` -> `127.0.0.1:8085` + Any attempt to request another destination (e.g., MySQL 3306, Remote Access console, or arbitrary intranet hosts) is rejected by the Host. +3. **No General Bearer Tokens**: Relay allocations are requested by the Host on behalf of a specific authenticated PlayerIdentity/session via the control plane. Allocations are bound to `RealmId`, `PlayerId`, have short lifetimes (default 120s before connection), and cannot be used for administrative or control plane operations. +4. **Dumb Byte Tunnel**: The Relay never terminates WoW encryption or parses character data. The only packet inspection performed is rewriting the `address` field in the plaintext `CMD_REALM_LIST` response (opcode `0x10`) so the client seamlessly connects to the allocated WORLD port without patching AzerothCore or mutating MySQL `realmlist`. +5. **Zero Plaintext Logging**: Relay logs contain only connection identifiers, timestamps, stream IDs, and byte counts. Zero credentials, account names, session keys, or packet contents are logged. +6. **Resource Limits & Backpressure**: + - Connection limits: max 16 concurrent hosts, max 256 allocations total, max 2 active allocations per player. + - Timeouts: 10s challenge timeout, 60s idle timeout, 30s ping/pong keepalive. + - Bounded streaming chunks: 16 KiB chunks with backpressure. + - Dynamic port pool: 40000–40050/tcp. Unused or closed ports are immediately reclaimed. + +--- + +## 2. Host Tunnel Handshake + +When a Host Manager publishes a realm, it establishes an outbound connection to `/relay/v1/host`. + +1. **Relay Challenge**: The Relay sends a challenge frame containing a random nonce: + ```json + { "nonce": "" } + ``` +2. **Host Hello**: The Host signs the challenge with the realm's Ed25519 private key: + ``` + message = "coa-relay-host-v1\n" || protocol_version || "\n" || realm_id || "\n" || nonce + ``` + The Host replies: + ```json + { "realm_id": "", "signature": "" } + ``` +3. **Relay Verification**: The Relay verifies the signature against the realm's registered public key in the database (`coa_registry.realms`). +4. **Relay Welcome**: On success: + ```json + { "ok": true, "message": "welcome" } + ``` + +--- + +## 3. Tunnel Messaging (`TunnelMsg`) + +Multiplexed JSON messages over the WebSocket tunnel: + +| Message | Fields | Purpose | +|---|---|---| +| `ping` | — | Keepalive probe | +| `pong` | — | Keepalive response | +| `allocate` | `request_id`, `player_id` | Host requests game ports for a player | +| `allocate_ok` | `request_id`, `token`, `relay_host`, `auth_port`, `world_port`, `expires_at` | Relay provides allocated ports | +| `allocate_err` | `request_id`, `error` | Allocation failed (e.g. pool exhausted) | +| `connect` | `stream_id`, `token`, `target` (`auth` \| `world`) | Client connected to relay port; requests Host to connect local target | +| `connect_ok` | `stream_id` | Host connected local target successfully | +| `connect_err` | `stream_id`, `error` | Host failed to connect local target | +| `data` | `stream_id`, `chunk` (base64) | Bidirectional raw stream bytes | +| `close` | `stream_id` | Half-close / end of stream | +| `reset` | `stream_id` | Immediate abnormal stream termination | + +--- + +## 4. Client Flow & REALM_LIST Address Rewriting + +```text +1. Player clicks "Join Realm" in Manager +2. Player Manager requests AllocateRelay over Noise control channel +3. Host Manager allocates (auth_port, world_port) via Relay tunnel +4. Host returns RelayAllocated to Player Manager +5. Player Manager writes realmlist.wtf: "set realmlist relay_host:auth_port" and starts WoW client +6. WoW client connects to relay_host:auth_port (authenticates with SRP6 against local authserver) +7. Authserver sends CMD_REALM_LIST (0x10) with local address (e.g. "127.0.0.1:8085") +8. Relay rewrites address string to "relay_host:world_port" and updates packet body length +9. WoW client receives rewritten realmlist and connects directly to relay_host:world_port +10. World session begins; bytes tunneled end-to-end through Host tunnel +``` + +### Packet Layout (`0x10 CMD_REALM_LIST`) +- `[0]`: Opcode (`0x10`) +- `[1..3]`: Packet Body Length (`uint16_le`) +- `[3..7]`: Unused (`uint32`) +- `[7..9]`: Realm Count (`uint16_le`) +- For each realm: + - `[0]`: Type (`uint8`) + - `[1]`: Lock (`uint8`) + - `[2]`: Flags (`uint8`) + - `[...]`: Name (null-terminated string) + - `[...]`: Address (null-terminated string) -> **Rewritten to `:\0`** + - `[...]`: Population (`float32`) + - `[...]`: Characters (`uint8`) + - `[...]`: Timezone (`uint8`) + - `[...]`: Realm ID (`uint8`) +- Footer: `0x10 0x00` diff --git a/docs/VPS_BASELINE.md b/docs/VPS_BASELINE.md index bfdc332..6d1374c 100644 --- a/docs/VPS_BASELINE.md +++ b/docs/VPS_BASELINE.md @@ -43,9 +43,10 @@ Date configured: 2026-10-06 (UTC) |---|---|---| | 22 | tcp | sshd (key only) | | 80 | tcp | Caddy (redirects HTTP to HTTPS on 443) | -| 443 | tcp | Caddy (Let's Encrypt TLS: `/registry/*` and `/coord/*`) | +| 443 | tcp | Caddy (Let's Encrypt TLS: `/registry/*`, `/coord/*`, `/relay/*`) | +| 40000-40050 | tcp | Game Relay WoW game traffic (Auth & World) | -Everything else is closed, including 5432, 3306/3307, 2375/2376 (Docker API), 2019 (Caddy admin; admin API is disabled). +Everything else is closed, including 5432 (Postgres), 8080 (Registry internal), 8081 (Coordinator internal), 8082 (Relay control internal), 3306/3307, 2375/2376 (Docker API), 2019 (Caddy admin; admin API is disabled). ## SSH diff --git a/services/coa-control-e2e/Cargo.lock b/services/coa-control-e2e/Cargo.lock index d1eb1af..4c6c9b4 100644 --- a/services/coa-control-e2e/Cargo.lock +++ b/services/coa-control-e2e/Cargo.lock @@ -309,6 +309,7 @@ dependencies = [ "ed25519-dalek", "reqwest", "serde_json", + "sha2 0.10.9", "tempfile", "tokio", "tungstenite 0.26.2", diff --git a/services/coa-control-e2e/Cargo.toml b/services/coa-control-e2e/Cargo.toml index 7afdd3f..2c3d483 100644 --- a/services/coa-control-e2e/Cargo.toml +++ b/services/coa-control-e2e/Cargo.toml @@ -22,3 +22,5 @@ tempfile = "3" uuid = { version = "1", features = ["v4", "v7"] } reqwest = { version = "0.12", default-features = false, features = ["blocking", "json"] } serde_json = "1" +sha2 = "0.10" + diff --git a/services/coa-control-e2e/tests/control.rs b/services/coa-control-e2e/tests/control.rs index 7fb8afd..cebe202 100644 --- a/services/coa-control-e2e/tests/control.rs +++ b/services/coa-control-e2e/tests/control.rs @@ -360,3 +360,47 @@ fn a_realms_key_is_pinned_at_the_first_visit() { // the right key still works pc.connect(&env.target()).unwrap().close(); } + +#[test] +fn remote_transfer_over_coordinator_channel_e2e() { + use std::collections::BTreeMap; + use sha2::{Digest, Sha256}; + let env = Env::new(true); + let dir = tempfile::tempdir().unwrap(); + let pc = player(dir.path(), Arc::new(MemoryStore::default())); + let mut ch = pc.connect(&env.target()).unwrap(); + pc.ensure_account(&mut ch, &env.realm, Some("Varian")).unwrap(); + + let cid = Uuid::now_v7(); + let payload = b"SECRET_PORTABLE_CHARACTER_PAYLOAD_FOR_VARIAN".to_vec(); + let hash: [u8; 32] = Sha256::digest(&payload).into(); + let collections = BTreeMap::from([("coa:appearance".to_string(), vec![42, 99])]); + + // Perform transfer + let outcome = pc.transfer_character(&mut ch, cid, 1, &payload, hash, collections.clone()).unwrap(); + assert!(outcome.local_guid > 0); + assert_ne!(outcome.session_id, Uuid::nil()); + + // Verify tap saw nothing sensitive + assert!(!env.wire_contains("SECRET_PORTABLE_CHARACTER_PAYLOAD"), "payload was encrypted"); + assert!(!env.wire_contains("Varian"), "account name was encrypted"); + + // Idempotent retry with same payload discovers existing commit + let retry_outcome = pc.transfer_character(&mut ch, cid, 1, &payload, hash, collections.clone()).unwrap(); + assert_eq!(outcome.local_guid, retry_outcome.local_guid); + assert_eq!(outcome.session_id, retry_outcome.session_id); + + // Update with revision 2 updates working copy without duplicate + let payload2 = b"SECRET_PORTABLE_CHARACTER_PAYLOAD_VARIAN_REV2".to_vec(); + let hash2: [u8; 32] = Sha256::digest(&payload2).into(); + let update_outcome = pc.transfer_character(&mut ch, cid, 2, &payload2, hash2, collections).unwrap(); + assert_eq!(outcome.local_guid, update_outcome.local_guid); + + // Incompatible realm rejects + let incomp_id = Uuid::now_v7(); + env.fake.incompatible.lock().unwrap().insert(incomp_id); + let err = pc.transfer_character(&mut ch, incomp_id, 1, b"any", [0u8; 32], BTreeMap::new()).unwrap_err(); + assert_eq!(err.code(), "incompatible"); +} + + diff --git a/services/coa-control-e2e/tests/live_control.rs b/services/coa-control-e2e/tests/live_control.rs index 100bded..0973c8d 100644 --- a/services/coa-control-e2e/tests/live_control.rs +++ b/services/coa-control-e2e/tests/live_control.rs @@ -174,3 +174,225 @@ fn gate_phase12_live_vps_control_channel() { client.unpublish(&host_key, &realm, now()).expect("unpublish realm"); println!("GATE 12 PASS realm unpublished and links closed cleanly"); } + +#[test] +#[ignore] +fn gate_phase12_1_live_vps_remote_transfer() { + use std::collections::BTreeMap; + use sha2::{Digest, Sha256}; + + let Some(base) = base_url() else { return }; + + let realm = RealmId::new(); + let host_key = random_key(); + let host_vkey = host_key.verifying_key(); + + let client = RegistryClient::new(&base).expect("registry client"); + register_realm(&client, &realm, &host_key).expect("register realm over HTTPS"); + println!("GATE 12.1 PASS registered realm {realm} in Registry over HTTPS"); + + let fake = FakeRealm::new(true); + let store = Arc::new(Mutex::new(ControlStore::open_in_memory().unwrap())); + let service = Arc::new(HostService::new("srv-gate-12-1", realm, store, fake.clone())); + + let host_ws_url = coordinator_url(&base, "/coord/v1/host").expect("coordinator host url"); + let mut link = HostLink::start(host_ws_url.clone(), realm, host_key.clone(), service, Arc::new(now)); + + let deadline = Instant::now() + Duration::from_secs(15); + while Instant::now() < deadline && !link.status().connected { + std::thread::sleep(Duration::from_millis(200)); + } + assert!(link.status().connected, "Host failed to connect to Coordinator via WSS"); + + let player_dir = tempfile::tempdir().unwrap(); + let pc = PlayerControl::open(player_dir.path(), Arc::new(MemoryStore::default())).unwrap(); + let player_ws_base = coordinator_url(&base, "/coord/v1/player").expect("coordinator player url"); + + let target = RealmTarget { + realm_id: realm, + key: host_vkey, + coordinator: player_ws_base, + }; + + let mut ch = pc.connect(&target).expect("Player connect via WSS"); + pc.ensure_account(&mut ch, &realm, Some("VarianWrynn")).expect("ensure_account"); + + let cid = Uuid::now_v7(); + let payload = b"REMOTE_PORTABLE_CHARACTER_VARIAN_PAYLOAD_V1".to_vec(); + let hash: [u8; 32] = Sha256::digest(&payload).into(); + let collections = BTreeMap::from([("coa:appearance".to_string(), vec![101, 202])]); + + // 1. Remote transfer over Coordinator WSS channel + let outcome = pc.transfer_character(&mut ch, cid, 1, &payload, hash, collections.clone()).expect("transfer_character"); + assert!(outcome.local_guid > 0); + assert_ne!(outcome.session_id, Uuid::nil()); + println!("GATE 12.1 PASS remote transfer succeeded over WSS: local_guid={}, session_id={}", outcome.local_guid, outcome.session_id); + + // 2. Idempotent retry with same payload discovers existing commit + let retry_outcome = pc.transfer_character(&mut ch, cid, 1, &payload, hash, collections.clone()).expect("retry transfer"); + assert_eq!(outcome.local_guid, retry_outcome.local_guid, "idempotent retry must return existing guid"); + assert_eq!(outcome.session_id, retry_outcome.session_id, "idempotent retry must return existing session"); + println!("GATE 12.1 PASS idempotent retry returned existing commit without duplication"); + + // 3. Update with newer revision 2 updates working copy without duplicating character + let payload2 = b"REMOTE_PORTABLE_CHARACTER_VARIAN_PAYLOAD_V2".to_vec(); + let hash2: [u8; 32] = Sha256::digest(&payload2).into(); + let update_outcome = pc.transfer_character(&mut ch, cid, 2, &payload2, hash2, collections).expect("update transfer"); + assert_eq!(outcome.local_guid, update_outcome.local_guid, "revision update must preserve guid"); + println!("GATE 12.1 PASS revision 2 update succeeded without character duplication"); + + // 4. Incompatible realm rejects before mutation + let incomp_id = Uuid::now_v7(); + fake.incompatible.lock().unwrap().insert(incomp_id); + let err = pc.transfer_character(&mut ch, incomp_id, 1, b"incomp", [0u8; 32], BTreeMap::new()).expect_err("should reject"); + assert_eq!(err.code(), "incompatible"); + println!("GATE 12.1 PASS incompatible character rejected cleanly"); + + ch.close(); + link.stop(); + client.unpublish(&host_key, &realm, now()).expect("unpublish realm"); + println!("GATE 12.1 PASS remote transfer gate passed and cleaned up"); +} + +#[test] +#[ignore] +fn gate_phase13_live_vps_relay() { + use std::io::{Read, Write}; + use std::net::{TcpListener, TcpStream}; + use coa_core::control::relay_link::RelayLink; + + let Some(base) = base_url() else { return }; + + let realm = RealmId::new(); + let host_key = random_key(); + let host_vkey = host_key.verifying_key(); + + let client = RegistryClient::new(&base).expect("registry client"); + register_realm(&client, &realm, &host_key).expect("register realm over HTTPS"); + println!("GATE 13 PASS registered realm {realm} in Registry over HTTPS"); + + // Start local mock Auth server + let mock_auth_listener = TcpListener::bind("127.0.0.1:0").expect("bind mock auth"); + let mock_auth_port = mock_auth_listener.local_addr().unwrap().port(); + + // Start local mock World server + let mock_world_listener = TcpListener::bind("127.0.0.1:0").expect("bind mock world"); + let mock_world_port = mock_world_listener.local_addr().unwrap().port(); + + std::env::set_var("COA_OVERRIDE_LOCAL_AUTH_PORT", mock_auth_port.to_string()); + std::env::set_var("COA_OVERRIDE_LOCAL_WORLD_PORT", mock_world_port.to_string()); + + // Spawn mock Auth worker: sends REALM_LIST packet when connection arrives + std::thread::spawn(move || { + let Ok((mut stream, _)) = mock_auth_listener.accept() else { return }; + // Build mock REALM_LIST packet + let mut pkt = Vec::new(); + pkt.push(0x10); // Opcode + pkt.extend_from_slice(&[0, 0]); // Body len placeholder + pkt.extend_from_slice(&[0, 0, 0, 0]); // Unused + pkt.extend_from_slice(&1u16.to_le_bytes()); // Count = 1 + pkt.push(1); // Type + pkt.push(0); // Lock + pkt.push(0); // Flags + pkt.extend_from_slice(b"Live Relay Realm\0"); // Name + pkt.extend_from_slice(b"127.0.0.1:8085\0"); // Old address + pkt.extend_from_slice(&0.5f32.to_le_bytes()); // Pop + pkt.push(1); // Chars + pkt.push(1); // Timezone + pkt.push(1); // Realm ID + pkt.push(0x10); + pkt.push(0x00); + let body_len = (pkt.len() - 3) as u16; + pkt[1..3].copy_from_slice(&body_len.to_le_bytes()); + + let _ = stream.write_all(&pkt); + let mut buf = [0u8; 64]; + let _ = stream.read(&mut buf); + }); + + // Spawn mock World worker: echoes back received data + std::thread::spawn(move || { + let Ok((mut stream, _)) = mock_world_listener.accept() else { return }; + let mut buf = [0u8; 128]; + if let Ok(n) = stream.read(&mut buf) { + let _ = stream.write_all(&buf[..n]); + } + }); + + let fake = FakeRealm::new(true); + let store = Arc::new(Mutex::new(ControlStore::open_in_memory().unwrap())); + let service = Arc::new(HostService::new("srv-gate-13", realm, store, fake)); + + let host_ws_url = coordinator_url(&base, "/coord/v1/host").expect("coordinator host url"); + let relay_ws_url = coordinator_url(&base, "/relay/v1/host").expect("relay host url"); + + let relay_link = RelayLink::start(relay_ws_url.clone(), realm, host_key.clone()); + service.set_relay(relay_link.clone()); + + let mut host_link = HostLink::start(host_ws_url.clone(), realm, host_key.clone(), service, Arc::new(now)); + + // Wait for HostLink and RelayLink to connect + let deadline = Instant::now() + Duration::from_secs(15); + while Instant::now() < deadline && (!host_link.status().connected || !relay_link.status().connected) { + std::thread::sleep(Duration::from_millis(200)); + } + assert!(host_link.status().connected, "Host failed to connect to Coordinator"); + assert!(relay_link.status().connected, "Host failed to connect to Game Relay: {:?}", relay_link.status()); + println!("GATE 13 PASS Host connected to Coordinator and Game Relay via outbound WSS"); + + // Player connects + let player_dir = tempfile::tempdir().unwrap(); + let pc = PlayerControl::open(player_dir.path(), Arc::new(MemoryStore::default())).unwrap(); + let player_ws_base = coordinator_url(&base, "/coord/v1/player").expect("coordinator player url"); + + let target = RealmTarget { + realm_id: realm, + key: host_vkey, + coordinator: player_ws_base, + }; + + let mut ch = pc.connect(&target).expect("Player connect via WSS"); + pc.ensure_account(&mut ch, &realm, Some("Thrall")).expect("ensure_account"); + + // Allocate relay + let alloc = pc.allocate_relay(&mut ch).expect("allocate_relay"); + println!("GATE 13 PASS allocated relay: host={}, auth_port={}, world_port={}, token={}", alloc.relay_host, alloc.auth_port, alloc.world_port, alloc.token); + assert_eq!(alloc.relay_host, "coa-manager.duckdns.org"); + assert!(alloc.auth_port >= 40000 && alloc.auth_port <= 40050); + assert!(alloc.world_port >= 40000 && alloc.world_port <= 40050); + assert_ne!(alloc.auth_port, alloc.world_port); + + // Test AUTH traffic through VPS Relay: verify REALM_LIST address rewrite + let mut auth_client = TcpStream::connect((alloc.relay_host.as_str(), alloc.auth_port)).expect("connect to auth relay"); + auth_client.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); + let mut pkt_buf = vec![0u8; 512]; + let n = auth_client.read(&mut pkt_buf).expect("read REALM_LIST response from auth relay"); + assert!(n > 10, "expected realm list packet"); + assert_eq!(pkt_buf[0], 0x10, "opcode must be 0x10 (REALM_LIST)"); + + let expected_world_addr = format!("{}:{}", alloc.relay_host, alloc.world_port); + assert!(pkt_buf[..n].windows(expected_world_addr.len()).any(|w| w == expected_world_addr.as_bytes()), + "REALM_LIST packet must have address rewritten to {expected_world_addr}"); + println!("GATE 13 PASS AUTH stream rewrote REALM_LIST address to VPS world port {expected_world_addr}"); + drop(auth_client); + + // Test WORLD traffic through VPS Relay: verify dumb byte tunneling + let mut world_client = TcpStream::connect((alloc.relay_host.as_str(), alloc.world_port)).expect("connect to world relay"); + world_client.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); + let test_payload = b"WORLD_TEST_PAYLOAD_FROM_CLIENT_THROUGH_VPS_RELAY"; + world_client.write_all(test_payload).expect("send data to world relay"); + + let mut echo_buf = vec![0u8; test_payload.len()]; + world_client.read_exact(&mut echo_buf).expect("read echo from world relay"); + assert_eq!(&echo_buf, test_payload, "world relay must tunnel bytes faithfully without alteration"); + println!("GATE 13 PASS WORLD stream tunneled game bytes faithfully end-to-end"); + drop(world_client); + + // Clean up + ch.close(); + host_link.stop(); + relay_link.stop(); + client.unpublish(&host_key, &realm, now()).expect("unpublish realm"); + println!("GATE 13 PASS game relay gate passed and cleaned up"); +} + diff --git a/services/coa-registry/deploy/Caddyfile b/services/coa-registry/deploy/Caddyfile index 04ee29c..4cb3fc2 100644 --- a/services/coa-registry/deploy/Caddyfile +++ b/services/coa-registry/deploy/Caddyfile @@ -5,4 +5,6 @@ coa-manager.duckdns.org { reverse_proxy /registry/* coa-registry:8080 reverse_proxy /coord/* coa-coordinator:8081 + reverse_proxy /relay/* coa-relay:8082 } + diff --git a/services/coa-relay/Cargo.lock b/services/coa-relay/Cargo.lock new file mode 100644 index 0000000..b92c59d --- /dev/null +++ b/services/coa-relay/Cargo.lock @@ -0,0 +1,1898 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "aead" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0" +dependencies = [ + "crypto-common 0.1.7", + "generic-array", +] + +[[package]] +name = "aes" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0" +dependencies = [ + "cfg-if", + "cipher", + "cpufeatures 0.2.17", +] + +[[package]] +name = "aes-gcm" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "831010a0f742e1209b3bcea8fab6a8e149051ba6099432c8cb2cc117dec3ead1" +dependencies = [ + "aead", + "aes", + "cipher", + "ctr", + "ghash", + "subtle", +] + +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + +[[package]] +name = "async-trait" +version = "0.1.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "axum" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90" +dependencies = [ + "axum-core", + "base64", + "bytes", + "form_urlencoded", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-util", + "itoa", + "matchit", + "memchr", + "mime", + "percent-encoding", + "pin-project-lite", + "serde_core", + "serde_json", + "serde_path_to_error", + "serde_urlencoded", + "sha1", + "sync_wrapper", + "tokio", + "tokio-tungstenite 0.29.0", + "tower", + "tower-layer", + "tower-service", +] + +[[package]] +name = "axum-core" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "mime", + "pin-project-lite", + "sync_wrapper", + "tower-layer", + "tower-service", +] + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "base64ct" +version = "1.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "blake2" +version = "0.10.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe" +dependencies = [ + "digest 0.10.7", +] + +[[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 = "block-buffer" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "chacha20" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3613f74bd2eac03dad61bd53dbe620703d4371614fe0bc3b9f04dd36fe4e818" +dependencies = [ + "cfg-if", + "cipher", + "cpufeatures 0.2.17", +] + +[[package]] +name = "chacha20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "rand_core 0.10.1", +] + +[[package]] +name = "chacha20poly1305" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10cd79432192d1c0f4e1a0fef9527696cc039165d729fb41b3f4f4f354c2dc35" +dependencies = [ + "aead", + "chacha20 0.9.1", + "cipher", + "poly1305", + "zeroize", +] + +[[package]] +name = "cipher" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" +dependencies = [ + "crypto-common 0.1.7", + "inout", + "zeroize", +] + +[[package]] +name = "cmov" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a" + +[[package]] +name = "coa-control-proto" +version = "0.1.0" +dependencies = [ + "base64", + "coa-registry-proto", + "ed25519-dalek", + "hex", + "serde", + "serde_json", + "sha2 0.10.9", + "snow", + "thiserror", + "uuid", +] + +[[package]] +name = "coa-registry-proto" +version = "0.1.0" +dependencies = [ + "base64", + "ed25519-dalek", + "hex", + "serde", + "serde_json", + "sha2 0.10.9", + "thiserror", + "uuid", +] + +[[package]] +name = "coa-relay" +version = "0.1.0" +dependencies = [ + "axum", + "base64", + "coa-control-proto", + "coa-registry-proto", + "deadpool-postgres", + "ed25519-dalek", + "futures-util", + "hex", + "serde", + "serde_json", + "tempfile", + "tokio", + "tokio-postgres", + "tokio-tungstenite 0.26.2", + "tower", + "tracing", + "tracing-subscriber", + "uuid", +] + +[[package]] +name = "const-oid" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" + +[[package]] +name = "const-oid" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +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", + "rand_core 0.6.4", + "typenum", +] + +[[package]] +name = "crypto-common" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "ctr" +version = "0.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0369ee1ad671834580515889b80f2ea915f23b8be8d0daa4bbaf2ac5c7590835" +dependencies = [ + "cipher", +] + +[[package]] +name = "ctutils" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03bb0e1cc970d482d121d9a1744999169b69a07470b3d644a7894e53fcaf4574" +dependencies = [ + "cmov", +] + +[[package]] +name = "curve25519-dalek" +version = "4.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "curve25519-dalek-derive", + "digest 0.10.7", + "fiat-crypto", + "rustc_version", + "subtle", + "zeroize", +] + +[[package]] +name = "curve25519-dalek-derive" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "data-encoding" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" + +[[package]] +name = "deadpool" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e98a7e119cd347f4201e1159b19831029e203e2d8b790547708e8157b4acf1e" +dependencies = [ + "deadpool-runtime", + "tokio", +] + +[[package]] +name = "deadpool-postgres" +version = "0.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65a536565624b97fc19f758cd01b15d12908d3344425066efc8162236fbd3749" +dependencies = [ + "async-trait", + "deadpool", + "getrandom 0.4.3", + "tokio", + "tokio-postgres", + "tracing", +] + +[[package]] +name = "deadpool-runtime" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2657f61fb1dd8bf37a8d51093cc7cee4e77125b22f7753f49b289f831bec2bae" +dependencies = [ + "tokio", +] + +[[package]] +name = "der" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" +dependencies = [ + "const-oid 0.9.6", + "zeroize", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer 0.10.4", + "crypto-common 0.1.7", + "subtle", +] + +[[package]] +name = "digest" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "block-buffer 0.12.1", + "const-oid 0.10.2", + "crypto-common 0.2.2", + "ctutils", +] + +[[package]] +name = "ed25519" +version = "2.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "115531babc129696a58c64a4fef0a8bf9e9698629fb97e9e40767d235cfbcd53" +dependencies = [ + "pkcs8", + "signature", +] + +[[package]] +name = "ed25519-dalek" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70e796c081cee67dc755e1a36a0a172b897fab85fc3f6bc48307991f64e4eca9" +dependencies = [ + "curve25519-dalek", + "ed25519", + "serde", + "sha2 0.10.9", + "subtle", + "zeroize", +] + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys", +] + +[[package]] +name = "fallible-iterator" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4443176a9f2c162692bd3d352d745ef9413eec5782a80d8fd6f8a1ac692a07f7" + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "fiat-crypto" +version = "0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d" + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", + "futures-sink", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + +[[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-macro", + "futures-sink", + "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.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi 0.11.1+wasi-snapshot-preview1", +] + +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "libc", + "r-efi 5.3.0", + "wasip2", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "r-efi 6.0.0", + "rand_core 0.10.1", + "wasm-bindgen", +] + +[[package]] +name = "ghash" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0d8a4362ccb29cb0b265253fb0a2728f592895ee6854fd9bc13f2ffda266ff1" +dependencies = [ + "opaque-debug", + "polyval", +] + +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "hmac" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f" +dependencies = [ + "digest 0.11.3", +] + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "httpdate" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" + +[[package]] +name = "hybrid-array" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" +dependencies = [ + "typenum", +] + +[[package]] +name = "hyper" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c" +dependencies = [ + "atomic-waker", + "bytes", + "futures-core", + "http", + "http-body", + "httparse", + "httpdate", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", +] + +[[package]] +name = "hyper-util" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" +dependencies = [ + "bytes", + "http", + "http-body", + "hyper", + "pin-project-lite", + "tokio", + "tower-service", +] + +[[package]] +name = "inout" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01" +dependencies = [ + "generic-array", +] + +[[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.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" + +[[package]] +name = "libc" +version = "0.2.190" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce5d3ddc6d3fa000eb1536d85e147bfe31aacaba692ed6a876f95cb7c855be78" + +[[package]] +name = "libredox" +version = "0.1.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61ff90caf6077a803a240f62fdbe88645a890bbca49ef8174c3cb0404362171d" +dependencies = [ + "libc", +] + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" + +[[package]] +name = "matchers" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9" +dependencies = [ + "regex-automata", +] + +[[package]] +name = "matchit" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3" + +[[package]] +name = "md-5" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69b6441f590336821bb897fb28fc622898ccceb1d6cea3fde5ea86b090c4de98" +dependencies = [ + "cfg-if", + "digest 0.11.3", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "mime" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" + +[[package]] +name = "mio" +version = "1.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee" +dependencies = [ + "libc", + "wasi 0.11.1+wasi-snapshot-preview1", + "windows-sys", +] + +[[package]] +name = "nu-ansi-term" +version = "0.50.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" +dependencies = [ + "windows-sys", +] + +[[package]] +name = "objc2-core-foundation" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536" +dependencies = [ + "bitflags", +] + +[[package]] +name = "objc2-system-configuration" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7216bd11cbda54ccabcab84d523dc93b858ec75ecfb3a7d89513fa22464da396" +dependencies = [ + "objc2-core-foundation", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "opaque-debug" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-link", +] + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "phf" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1562dc717473dbaa4c1f85a36410e03c047b2e7df7f45ee938fbef64ae7fadf" +dependencies = [ + "phf_shared", + "serde", +] + +[[package]] +name = "phf_shared" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e57fef6bc5981e38c2ce2d63bfa546861309f875b8a75f092d1d54ae2d64f266" +dependencies = [ + "siphasher", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "pkcs8" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7" +dependencies = [ + "der", + "spki", +] + +[[package]] +name = "poly1305" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8159bd90725d2df49889a078b54f4f79e87f1f8a8444194cdca81d38f5393abf" +dependencies = [ + "cpufeatures 0.2.17", + "opaque-debug", + "universal-hash", +] + +[[package]] +name = "polyval" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d1fe60d06143b2430aa532c94cfe9e29783047f06c0d7fd359a9a51b729fa25" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "opaque-debug", + "universal-hash", +] + +[[package]] +name = "postgres-protocol" +version = "0.6.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08808e3c483c46e999108051c78334f473d5adb59d78bb80a1268c7e6aa6c514" +dependencies = [ + "base64", + "byteorder", + "bytes", + "fallible-iterator", + "hmac", + "md-5", + "memchr", + "rand 0.10.3", + "sha2 0.11.0", + "stringprep", +] + +[[package]] +name = "postgres-types" +version = "0.2.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "851ca9db4932932d69f3ea811b1abe63087a0f740a47692619dd40d4899b68be" +dependencies = [ + "bytes", + "fallible-iterator", + "postgres-protocol", +] + +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + +[[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 = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rand" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41" +dependencies = [ + "rand_chacha", + "rand_core 0.9.5", +] + +[[package]] +name = "rand" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af" +dependencies = [ + "chacha20 0.10.2", + "getrandom 0.4.3", + "rand_core 0.10.1", +] + +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core 0.9.5", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom 0.2.17", +] + +[[package]] +name = "rand_core" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" +dependencies = [ + "getrandom 0.3.4", +] + +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags", +] + +[[package]] +name = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + +[[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", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[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 = "serde_path_to_error" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457" +dependencies = [ + "itoa", + "serde", + "serde_core", +] + +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "sha1" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "digest 0.10.7", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "digest 0.10.7", +] + +[[package]] +name = "sha2" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "446ba717509524cb3f22f17ecc096f10f4822d76ab5c0b9822c5f9c284e825f4" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "digest 0.11.3", +] + +[[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 = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "signature" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" +dependencies = [ + "rand_core 0.6.4", +] + +[[package]] +name = "siphasher" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256" + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.16.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9395f0f0eee849a9b707b2f06bb92a6a422090e2123bb2ef8e87a0e61892a8e" + +[[package]] +name = "snow" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "850948bee068e713b8ab860fe1adc4d109676ab4c3b621fd8147f06b261f2f85" +dependencies = [ + "aes-gcm", + "blake2", + "chacha20poly1305", + "curve25519-dalek", + "rand_core 0.6.4", + "rustc_version", + "sha2 0.10.9", + "subtle", +] + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys", +] + +[[package]] +name = "spki" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" +dependencies = [ + "base64ct", + "der", +] + +[[package]] +name = "stringprep" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b4df3d392d81bd458a8a621b8bffbd2302a12ffe288a9d931670948749463b1" +dependencies = [ + "unicode-bidi", + "unicode-normalization", + "unicode-properties", +] + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[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 = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.3", + "once_cell", + "rustix", + "windows-sys", +] + +[[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 = "tinyvec" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" + +[[package]] +name = "tokio" +version = "1.53.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e95f91fcc7a621e8b030f6aa23c71fe9838ae2fb4d8118b75602a328f5144044" +dependencies = [ + "bytes", + "libc", + "mio", + "pin-project-lite", + "signal-hook-registry", + "socket2", + "tokio-macros", + "windows-sys", +] + +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "tokio-postgres" +version = "0.7.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a528f7d280f6d5b9cd149635c8705b0dd049754bc67d81d31fa25169a93809d3" +dependencies = [ + "async-trait", + "byteorder", + "bytes", + "fallible-iterator", + "futures-channel", + "futures-util", + "log", + "parking_lot", + "percent-encoding", + "phf", + "pin-project-lite", + "postgres-protocol", + "postgres-types", + "rand 0.10.3", + "socket2", + "tokio", + "tokio-util", + "whoami", +] + +[[package]] +name = "tokio-tungstenite" +version = "0.26.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a9daff607c6d2bf6c16fd681ccb7eecc83e4e2cdc1ca067ffaadfca5de7f084" +dependencies = [ + "futures-util", + "log", + "tokio", + "tungstenite 0.26.2", +] + +[[package]] +name = "tokio-tungstenite" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f72a05e828585856dacd553fba484c242c46e391fb0e58917c942ee9202915c" +dependencies = [ + "futures-util", + "log", + "tokio", + "tungstenite 0.29.0", +] + +[[package]] +name = "tokio-util" +version = "0.7.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "494815d09bf52b5548659851081238f0ca39ff638363907596da739561c62c52" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "libc", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tokio-util", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[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", + "valuable", +] + +[[package]] +name = "tracing-log" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3" +dependencies = [ + "log", + "once_cell", + "tracing-core", +] + +[[package]] +name = "tracing-serde" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "704b1aeb7be0d0a84fc9828cae51dab5970fee5088f83d1dd7ee6f6246fc6ff1" +dependencies = [ + "serde", + "tracing-core", +] + +[[package]] +name = "tracing-subscriber" +version = "0.3.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319" +dependencies = [ + "matchers", + "nu-ansi-term", + "once_cell", + "regex-automata", + "serde", + "serde_json", + "sharded-slab", + "smallvec", + "thread_local", + "tracing", + "tracing-core", + "tracing-log", + "tracing-serde", +] + +[[package]] +name = "tungstenite" +version = "0.26.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4793cb5e56680ecbb1d843515b23b6de9a75eb04b66643e256a396d43be33c13" +dependencies = [ + "bytes", + "data-encoding", + "http", + "httparse", + "log", + "rand 0.9.5", + "sha1", + "thiserror", + "utf-8", +] + +[[package]] +name = "tungstenite" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c01152af293afb9c7c2a57e4b559c5620b421f6d133261c60dd2d0cdb38e6b8" +dependencies = [ + "bytes", + "data-encoding", + "http", + "httparse", + "log", + "rand 0.9.5", + "sha1", + "thiserror", +] + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicode-bidi" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5" + +[[package]] +name = "unicode-ident" +version = "1.0.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954" + +[[package]] +name = "unicode-normalization" +version = "0.1.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5fd4f6878c9cb28d874b009da9e8d183b5abc80117c40bbd187a1fde336be6e8" +dependencies = [ + "tinyvec", +] + +[[package]] +name = "unicode-properties" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7df058c713841ad818f1dc5d3fd88063241cc61f49f5fbea4b951e8cf5a8d71d" + +[[package]] +name = "universal-hash" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea" +dependencies = [ + "crypto-common 0.1.7", + "subtle", +] + +[[package]] +name = "utf-8" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9" + +[[package]] +name = "uuid" +version = "1.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97277d36b9c3ace13e58fa6e753f8b0bbbf302a18dd193240d70f9e29681059a" +dependencies = [ + "getrandom 0.4.3", + "js-sys", + "serde_core", + "wasm-bindgen", +] + +[[package]] +name = "valuable" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasi" +version = "0.14.7+wasi-0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "883478de20367e224c0090af9cf5f9fa85bed63a95c1abf3afc5c083ebc06e8c" +dependencies = [ + "wasip2", +] + +[[package]] +name = "wasip2" +version = "1.0.4+wasi-0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "wasite" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66fe902b4a6b8028a753d5424909b764ccf79b7a209eac9bf97e59cda9f71a42" +dependencies = [ + "wasi 0.14.7+wasi-0.2.4", +] + +[[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 = "web-sys" +version = "0.3.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88261b9deccee56594c11a3460c462c41f58d148598fe70ad77070126a68aba4" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "whoami" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "626c4bac6755d76ffc12cb01b2eac751db1996b9e0041de9aa02c8c211ddc82c" +dependencies = [ + "libc", + "libredox", + "objc2-system-configuration", + "wasite", + "web-sys", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[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 = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" + +[[package]] +name = "zerocopy" +version = "0.8.62" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "86502bf56ac7c77571a32e2647bb2a15894565e981fb2a48d7bde2d91c965a9d" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.62" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5457206954b06561e2608c7e19cf58b1926586d999c246eebe4502f7e2039d1a" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zeroize" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/services/coa-relay/Cargo.toml b/services/coa-relay/Cargo.toml new file mode 100644 index 0000000..a02df67 --- /dev/null +++ b/services/coa-relay/Cargo.toml @@ -0,0 +1,37 @@ +[package] +name = "coa-relay" +description = "CoA Game Relay (Phase 13): relays game TCP traffic (AUTH & WORLD) for NAT/CGNAT hosts." +version = "0.1.0" +edition = "2021" +license = "AGPL-3.0-only" +publish = false + +[workspace] + +[dependencies] +coa-control-proto = { path = "../../crates/coa-control-proto" } +coa-registry-proto = { path = "../../crates/coa-registry-proto" } +axum = { version = "0.8", default-features = false, features = ["http1", "json", "tokio", "ws", "query"] } +tokio = { version = "1", features = ["rt-multi-thread", "macros", "signal", "time", "net", "sync", "io-util"] } +tower = { version = "0.5", features = ["limit", "util"] } +tokio-postgres = "0.7" +deadpool-postgres = "0.14" +serde = { version = "1", features = ["derive"] } +serde_json = "1" +ed25519-dalek = "2" +uuid = { version = "1", features = ["v4"] } +tracing = "0.1" +tracing-subscriber = { version = "0.3", features = ["json", "env-filter"] } +hex = "0.4" +base64 = "0.22" +futures-util = "0.3" + + +[dev-dependencies] +tempfile = "3" +tokio-tungstenite = "0.26" + +[profile.release] +lto = "thin" +codegen-units = 4 +strip = true diff --git a/services/coa-relay/Dockerfile b/services/coa-relay/Dockerfile new file mode 100644 index 0000000..7f8f361 --- /dev/null +++ b/services/coa-relay/Dockerfile @@ -0,0 +1,17 @@ +# Build context: the repository root. docker build -f services/coa-relay/Dockerfile -t coa-relay: . +FROM rust:1-bookworm AS build +WORKDIR /src +COPY crates/coa-registry-proto crates/coa-registry-proto +COPY crates/coa-control-proto crates/coa-control-proto +COPY services/coa-relay services/coa-relay +WORKDIR /src/services/coa-relay +RUN cargo build --release --locked --bin coa-relay + +FROM debian:bookworm-slim +RUN useradd --system --uid 10002 --user-group --no-create-home --shell /usr/sbin/nologin coa +COPY --from=build /src/services/coa-relay/target/release/coa-relay /usr/local/bin/coa-relay +USER 10002:10002 +EXPOSE 8082 +EXPOSE 40000-40050 +HEALTHCHECK --interval=30s --timeout=5s --start-period=20s --retries=3 CMD ["/usr/local/bin/coa-relay", "--healthcheck"] +ENTRYPOINT ["/usr/local/bin/coa-relay"] diff --git a/services/coa-relay/deploy/compose.yaml b/services/coa-relay/deploy/compose.yaml new file mode 100644 index 0000000..b48a739 --- /dev/null +++ b/services/coa-relay/deploy/compose.yaml @@ -0,0 +1,44 @@ +# /opt/coa/relay/compose.yaml (Phase 13). +# The Game Relay publishes the dynamic game TCP port range (40000-40050/tcp) for relayed WoW client traffic. +# The HTTP/WS control interface (8082) is internal only: Caddy reaches it as coa-relay:8082 on coa-ingress. +# It reads realms' public keys from the Registry database using the read-only coa_coordinator role. +name: coa-relay +services: + relay: + image: coa-relay:${RELAY_TAG:-p13a} + user: "10002:10002" + restart: unless-stopped + environment: + RELAY_LISTEN: "0.0.0.0:8082" + RELAY_HOST: "coa-manager.duckdns.org" + RELAY_PORT_MIN: "40000" + RELAY_PORT_MAX: "40050" + RELAY_DB_HOST: coa-postgres + RELAY_DB_NAME: coa_registry + RELAY_DB_USER: coa_coordinator + RELAY_DB_PASSWORD_FILE: /run/secrets/coordinator_db_password + RUST_LOG: "info" + ports: + - "40000-40050:40000-40050/tcp" + secrets: + - coordinator_db_password + read_only: true + cap_drop: + - ALL + security_opt: + - no-new-privileges:true + mem_limit: 256m + pids_limit: 128 + networks: + coa-ingress: + aliases: + - coa-relay + coa-db: {} +secrets: + coordinator_db_password: + file: /opt/coa/secrets/coordinator_db_password +networks: + coa-ingress: + external: true + coa-db: + external: true diff --git a/services/coa-relay/src/hub.rs b/services/coa-relay/src/hub.rs new file mode 100644 index 0000000..b145b29 --- /dev/null +++ b/services/coa-relay/src/hub.rs @@ -0,0 +1,220 @@ +//! Central hub state and coordination for coa-relay (Phase 13). + +use std::collections::HashMap; +use std::future::Future; +use std::sync::atomic::AtomicU32; +use std::sync::{Arc, Mutex}; + + +use coa_control_proto::relay::{RelayTarget, TunnelMsg}; +use coa_registry_proto::RealmId; +use ed25519_dalek::VerifyingKey; +use tokio::sync::mpsc; +use uuid::Uuid; + +use crate::limits::*; +use crate::ports::PortPool; + +pub trait KeyLookup: Send + Sync + 'static { + fn host_key(&self, realm: &RealmId) -> impl Future> + Send; +} + +#[derive(Default)] +pub struct MemoryKeys(Mutex>); + +impl MemoryKeys { + pub fn set(&self, realm: RealmId, key: &VerifyingKey) { + self.0.lock().unwrap().insert(realm, key.to_bytes()); + } +} + +impl KeyLookup for MemoryKeys { + async fn host_key(&self, realm: &RealmId) -> Option { + self.0.lock().unwrap().get(realm).and_then(|b| VerifyingKey::from_bytes(b).ok()) + } +} + +impl KeyLookup for Arc { + fn host_key(&self, realm: &RealmId) -> impl Future> + Send { + (**self).host_key(realm) + } +} + + +pub struct PgKeys { + pool: deadpool_postgres::Pool, +} + +impl PgKeys { + pub fn new(pool: deadpool_postgres::Pool) -> Self { + Self { pool } + } +} + +impl KeyLookup for PgKeys { + async fn host_key(&self, realm: &RealmId) -> Option { + let c = self.pool.get().await.ok()?; + let row = c + .query_opt( + "SELECT public_key FROM realms WHERE realm_id = $1::text::uuid AND published AND advert_version = 2", + &[&realm.to_string()], + ) + .await + .ok()??; + let bytes: Vec = row.get(0); + VerifyingKey::from_bytes(&bytes.try_into().ok()?).ok() + } +} + +#[derive(Clone, Debug)] +pub struct Allocation { + pub token: String, + pub realm_id: RealmId, + pub player_id: Uuid, + pub auth_port: u16, + pub world_port: u16, + pub created_at: i64, + pub expires_at: i64, + pub consumed_auth: bool, + pub consumed_world: bool, +} + +pub struct HostHandle { + pub realm_id: RealmId, + pub tx: mpsc::Sender, +} + +pub struct Hub { + pub relay_host: String, + pub pool: Arc, + pub keys: K, + pub hosts: Arc>>, + pub allocations: Arc>>, + pub port_allocations: Arc>>, + pub stream_txs: Arc>>>, + pub next_stream_id: AtomicU32, + pub clock: Arc i64 + Send + Sync>, +} + +impl Hub { + pub fn new( + relay_host: String, + min_port: u16, + max_port: u16, + keys: K, + clock: Arc i64 + Send + Sync>, + ) -> Self { + Self { + relay_host, + pool: Arc::new(PortPool::new(min_port, max_port)), + keys, + hosts: Arc::new(Mutex::new(HashMap::new())), + allocations: Arc::new(Mutex::new(HashMap::new())), + port_allocations: Arc::new(Mutex::new(HashMap::new())), + stream_txs: Arc::new(Mutex::new(HashMap::new())), + next_stream_id: AtomicU32::new(1), + clock, + } + } + + + pub fn register_host(&self, realm_id: RealmId, tx: mpsc::Sender) { + let mut hosts = self.hosts.lock().unwrap(); + hosts.insert(realm_id, HostHandle { realm_id, tx }); + tracing::info!(%realm_id, "host tunnel registered"); + } + + pub fn unregister_host(&self, realm_id: &RealmId) { + let mut hosts = self.hosts.lock().unwrap(); + hosts.remove(realm_id); + tracing::info!(%realm_id, "host tunnel unregistered"); + } + + pub fn host_tx(&self, realm_id: &RealmId) -> Option> { + self.hosts.lock().unwrap().get(realm_id).map(|h| h.tx.clone()) + } + + pub fn allocate( + &self, + realm_id: RealmId, + player_id: Uuid, + ) -> Result { + let now = (self.clock)(); + + // Clean up expired allocations + { + let mut allocs = self.allocations.lock().unwrap(); + let mut port_map = self.port_allocations.lock().unwrap(); + allocs.retain(|_, a| { + if a.expires_at <= now { + self.pool.release(a.auth_port); + self.pool.release(a.world_port); + port_map.remove(&a.auth_port); + port_map.remove(&a.world_port); + false + } else { + true + } + }); + } + + // Check if player already has an active, unexpired allocation on this realm + { + let allocs = self.allocations.lock().unwrap(); + if let Some(existing) = allocs.values().find(|a| a.realm_id == realm_id && a.player_id == player_id && a.expires_at > now) { + return Ok(existing.clone()); + } + + let realm_count = allocs.values().filter(|a| a.realm_id == realm_id).count(); + if realm_count >= MAX_ALLOCATIONS_PER_REALM { + return Err("too many allocations for realm".into()); + } + } + + // Acquire ports + let (auth_port, world_port) = self.pool.acquire_pair().ok_or("relay ports exhausted")?; + let token = Uuid::new_v4().to_string(); + let alloc = Allocation { + token: token.clone(), + realm_id, + player_id, + auth_port, + world_port, + created_at: now, + expires_at: now + ALLOCATION_TIMEOUT.as_secs() as i64, + consumed_auth: false, + consumed_world: false, + }; + + { + let mut allocs = self.allocations.lock().unwrap(); + let mut port_map = self.port_allocations.lock().unwrap(); + allocs.insert(token.clone(), alloc.clone()); + port_map.insert(auth_port, (token.clone(), RelayTarget::Auth)); + port_map.insert(world_port, (token.clone(), RelayTarget::World)); + } + + tracing::info!(%realm_id, %player_id, auth_port, world_port, %token, "relay allocation created"); + Ok(alloc) + } + + pub fn get_allocation_by_port(&self, port: u16) -> Option<(Allocation, RelayTarget)> { + let port_map = self.port_allocations.lock().unwrap(); + let (token, target) = port_map.get(&port)?.clone(); + let allocs = self.allocations.lock().unwrap(); + let alloc = allocs.get(&token)?.clone(); + Some((alloc, target)) + } + + pub fn register_stream(&self, stream_id: u32, tx: mpsc::Sender) { + self.stream_txs.lock().unwrap().insert(stream_id, tx); + } + + pub fn unregister_stream(&self, stream_id: u32) { + self.stream_txs.lock().unwrap().remove(&stream_id); + } + + pub fn stream_tx(&self, stream_id: u32) -> Option> { + self.stream_txs.lock().unwrap().get(&stream_id).cloned() + } +} diff --git a/services/coa-relay/src/lib.rs b/services/coa-relay/src/lib.rs new file mode 100644 index 0000000..f344b26 --- /dev/null +++ b/services/coa-relay/src/lib.rs @@ -0,0 +1,44 @@ +//! Game Relay service library (Phase 13). + +pub mod hub; +pub mod limits; +pub mod ports; +pub mod tunnel; + +use std::sync::Arc; + +use axum::extract::ws::WebSocketUpgrade; +use axum::extract::State; +use axum::response::IntoResponse; +use axum::routing::get; +use axum::{Json, Router}; +use serde_json::json; + +use crate::hub::{Hub, KeyLookup}; + +pub fn router(hub: Arc>) -> Router { + Router::new() + .route("/relay/v1/health", get(health::)) + .route("/relay/v1/host", get(host_ws::)) + .with_state(hub) +} + +async fn health(State(hub): State>>) -> impl IntoResponse { + let hosts_count = hub.hosts.lock().unwrap().len(); + let allocs_count = hub.allocations.lock().unwrap().len(); + Json(json!({ + "status": "ok", + "service": "coa-relay", + "version": coa_control_proto::relay::RELAY_PROTOCOL_VERSION, + "connected_hosts": hosts_count, + "active_allocations": allocs_count, + })) +} + +async fn host_ws( + ws: WebSocketUpgrade, + State(hub): State>>, +) -> impl IntoResponse { + ws.on_upgrade(move |socket| tunnel::handle_host_websocket(socket, hub)) +} + diff --git a/services/coa-relay/src/limits.rs b/services/coa-relay/src/limits.rs new file mode 100644 index 0000000..625ca6d --- /dev/null +++ b/services/coa-relay/src/limits.rs @@ -0,0 +1,20 @@ +//! Relay limits, timeouts and safety bounds (Phase 13). + +use std::time::Duration; + +pub const DEFAULT_PORT_MIN: u16 = 40000; +pub const DEFAULT_PORT_MAX: u16 = 40050; + +pub const ALLOCATION_TIMEOUT: Duration = Duration::from_secs(300); // 5 minutes +pub const CONNECT_TIMEOUT: Duration = Duration::from_secs(15); +pub const IDLE_TIMEOUT: Duration = Duration::from_secs(300); +pub const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(10); + +pub const MAX_STREAMS_PER_REALM: usize = 64; +pub const MAX_ALLOCATIONS_PER_REALM: usize = 32; + +/// Maximum buffer chunk read at once (16 KiB). +pub const STREAM_CHUNK_SIZE: usize = 16 * 1024; + +/// Bounded mpsc channel capacity per stream. +pub const STREAM_CHANNEL_CAPACITY: usize = 64; diff --git a/services/coa-relay/src/main.rs b/services/coa-relay/src/main.rs new file mode 100644 index 0000000..4330f7a --- /dev/null +++ b/services/coa-relay/src/main.rs @@ -0,0 +1,108 @@ +use std::sync::Arc; +use std::time::Duration; + +use coa_relay::hub::{Hub, PgKeys}; +use coa_relay::router; +use deadpool_postgres::{Manager, ManagerConfig, Pool, RecyclingMethod, Runtime}; +use tokio_postgres::NoTls; +use tower::limit::ConcurrencyLimitLayer; + +fn var(name: &str, default: &str) -> String { + std::env::var(name).ok().filter(|v| !v.is_empty()).unwrap_or_else(|| default.to_string()) +} + +fn pool() -> Result { + let file = std::env::var("RELAY_DB_PASSWORD_FILE") + .or_else(|_| std::env::var("COORD_DB_PASSWORD_FILE")) + .map_err(|_| "RELAY_DB_PASSWORD_FILE or COORD_DB_PASSWORD_FILE is required".to_string())?; + let password = std::fs::read_to_string(&file) + .map_err(|e| format!("cannot read database password file: {e}"))? + .trim() + .to_string(); + let mut pg = tokio_postgres::Config::new(); + pg.host(&var("RELAY_DB_HOST", &var("COORD_DB_HOST", "coa-postgres"))) + .port(var("RELAY_DB_PORT", &var("COORD_DB_PORT", "5432")).parse().map_err(|_| "RELAY_DB_PORT")?) + .dbname(&var("RELAY_DB_NAME", &var("COORD_DB_NAME", "coa_registry"))) + .user(&var("RELAY_DB_USER", &var("COORD_DB_USER", "coa_coordinator"))) + .password(&password); + pg.connect_timeout(Duration::from_secs(5)) + .application_name("coa-relay") + .options("-c statement_timeout=3000 -c default_transaction_read_only=on"); + Pool::builder(Manager::from_config(pg, NoTls, ManagerConfig { recycling_method: RecyclingMethod::Fast })) + .max_size(4) + .wait_timeout(Some(Duration::from_secs(5))) + .create_timeout(Some(Duration::from_secs(5))) + .runtime(Runtime::Tokio1) + .build() + .map_err(|e| e.to_string()) +} + +fn healthcheck() -> i32 { + use std::io::{Read, Write}; + let port = var("RELAY_LISTEN", "0.0.0.0:8082").rsplit(':').next().unwrap_or("8082").to_string(); + let Ok(mut s) = std::net::TcpStream::connect(format!("127.0.0.1:{port}")) else { return 1 }; + let _ = s.set_read_timeout(Some(Duration::from_secs(3))); + if s.write_all(b"GET /relay/v1/health HTTP/1.1\r\nHost: localhost\r\n\r\n").is_err() { + return 1; + } + let mut buf = [0u8; 16]; + i32::from(!matches!(s.read(&mut buf), Ok(n) if n >= 12 && buf.starts_with(b"HTTP/1.1 200"))) +} + +async fn shutdown() { + let ctrl_c = tokio::signal::ctrl_c(); + #[cfg(unix)] + { + let mut term = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()).expect("a SIGTERM handler"); + tokio::select! { _ = ctrl_c => {}, _ = term.recv() => {} } + } + #[cfg(not(unix))] + { + let _ = ctrl_c.await; + } +} + +#[tokio::main] +async fn main() { + if std::env::args().nth(1).as_deref() == Some("--healthcheck") { + std::process::exit(healthcheck()); + } + + tracing_subscriber::fmt() + .json() + .with_env_filter(tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| "info".into())) + .with_current_span(false) + .init(); + + let pool = match pool() { + Ok(p) => p, + Err(e) => { + tracing::error!(error = %e, "database configuration error"); + std::process::exit(2); + } + }; + + let relay_host = var("RELAY_HOST", "coa-manager.duckdns.org"); + let min_port: u16 = var("RELAY_PORT_MIN", "40000").parse().expect("valid RELAY_PORT_MIN"); + let max_port: u16 = var("RELAY_PORT_MAX", "40050").parse().expect("valid RELAY_PORT_MAX"); + + let clock = Arc::new(|| std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs() as i64).unwrap_or(0)); + let hub = Arc::new(Hub::new(relay_host, min_port, max_port, PgKeys::new(pool), clock)); + + let app = router(hub).layer(ConcurrencyLimitLayer::new(512)); + let listen = var("RELAY_LISTEN", "0.0.0.0:8082"); + + let tcp = match tokio::net::TcpListener::bind(&listen).await { + Ok(l) => l, + Err(e) => { + tracing::error!(listen = %listen, error = %e, "cannot bind the listening socket"); + std::process::exit(3); + } + }; + + tracing::info!(listen = %listen, "coa-relay listening"); + if let Err(e) = axum::serve(tcp, app.into_make_service()).with_graceful_shutdown(shutdown()).await { + tracing::error!(error = %e, "service crashed"); + std::process::exit(1); + } +} diff --git a/services/coa-relay/src/ports.rs b/services/coa-relay/src/ports.rs new file mode 100644 index 0000000..a5c87d7 --- /dev/null +++ b/services/coa-relay/src/ports.rs @@ -0,0 +1,82 @@ +//! Dynamic port pool management for game relay listeners. + +use std::collections::HashSet; +use std::sync::Mutex; + +#[derive(Debug)] +pub struct PortPool { + min: u16, + max: u16, + used: Mutex>, +} + +impl PortPool { + pub fn new(min: u16, max: u16) -> Self { + assert!(min < max, "min port must be less than max port"); + Self { + min, + max, + used: Mutex::new(HashSet::new()), + } + } + + /// Allocates an unused port, if any is available in the pool range. + pub fn acquire(&self) -> Option { + let mut used = self.used.lock().unwrap(); + for p in self.min..=self.max { + if !used.contains(&p) { + used.insert(p); + return Some(p); + } + } + None + } + + /// Acquires a pair of ports: (auth_port, world_port). + pub fn acquire_pair(&self) -> Option<(u16, u16)> { + let mut used = self.used.lock().unwrap(); + let mut first = None; + for p in self.min..=self.max { + if !used.contains(&p) { + if first.is_none() { + first = Some(p); + } else { + let a = first.unwrap(); + used.insert(a); + used.insert(p); + return Some((a, p)); + } + } + } + None + } + + /// Releases a port back to the pool. + pub fn release(&self, port: u16) { + let mut used = self.used.lock().unwrap(); + used.remove(&port); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_port_pool() { + let pool = PortPool::new(40000, 40003); + let pair = pool.acquire_pair().unwrap(); + assert_eq!(pair, (40000, 40001)); + + let next = pool.acquire().unwrap(); + assert_eq!(next, 40002); + + let last = pool.acquire().unwrap(); + assert_eq!(last, 40003); + + assert!(pool.acquire().is_none()); + + pool.release(40001); + assert_eq!(pool.acquire(), Some(40001)); + } +} diff --git a/services/coa-relay/src/tunnel.rs b/services/coa-relay/src/tunnel.rs new file mode 100644 index 0000000..8801080 --- /dev/null +++ b/services/coa-relay/src/tunnel.rs @@ -0,0 +1,284 @@ +//! Host WebSocket tunnel handling and game TCP listener proxying. + +use std::sync::atomic::Ordering; +use std::sync::Arc; +use std::time::Duration; + +use axum::extract::ws::{Message, WebSocket}; +use base64::Engine; +use coa_control_proto::relay::*; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::net::TcpListener; +use tokio::sync::mpsc; +use uuid::Uuid; + +use crate::hub::{Hub, KeyLookup}; +use crate::limits::*; + +pub async fn handle_host_websocket(mut ws: WebSocket, hub: Arc>) { + + // 1. Send challenge + let nonce = Uuid::new_v4().to_string(); + let challenge = RelayChallenge { nonce: nonce.clone() }; + let msg = Message::Text(serde_json::to_string(&challenge).unwrap().into()); + if ws.send(msg).await.is_err() { + return; + } + + // 2. Wait for HostHello + let hello_res = tokio::time::timeout(HANDSHAKE_TIMEOUT, ws.recv()).await; + let Ok(Some(Ok(Message::Text(hello_text)))) = hello_res else { + tracing::warn!("handshake timed out or failed"); + return; + }; + + let Ok(hello) = serde_json::from_str::(&hello_text) else { + tracing::warn!("invalid HostHello payload"); + return; + }; + + // 3. Verify signature + let Some(key) = hub.keys.host_key(&hello.realm_id).await else { + tracing::warn!(realm_id = %hello.realm_id, "unknown or unpublished realm"); + let _ = ws.send(Message::Text(serde_json::to_string(&RelayWelcome { ok: false, message: "unauthorized".into() }).unwrap().into())).await; + return; + }; + + if !verify_relay_challenge(&key, &hello.realm_id, &nonce, &hello.signature) { + tracing::warn!(realm_id = %hello.realm_id, "invalid challenge signature"); + let _ = ws.send(Message::Text(serde_json::to_string(&RelayWelcome { ok: false, message: "invalid signature".into() }).unwrap().into())).await; + return; + } + + // 4. Welcome host + let welcome = RelayWelcome { ok: true, message: "welcome".into() }; + if ws.send(Message::Text(serde_json::to_string(&welcome).unwrap().into())).await.is_err() { + return; + } + + let realm_id = hello.realm_id; + let (tx_to_host, mut rx_to_host) = mpsc::channel::(STREAM_CHANNEL_CAPACITY * 2); + hub.register_host(realm_id, tx_to_host.clone()); + + // 5. Multiplex loop: handle messages between Host WS and Relay tasks + let (mut ws_sink, mut ws_stream) = ws.split(); + + // Outbound task: messages to host over WS + let ws_send_task = tokio::spawn(async move { + use futures_util::SinkExt; + while let Some(msg) = rx_to_host.recv().await { + let json = serde_json::to_string(&msg).unwrap(); + if ws_sink.send(Message::Text(json.into())).await.is_err() { + break; + } + } + }); + + // Inbound loop: messages from host over WS + use futures_util::StreamExt; + while let Some(Ok(msg)) = ws_stream.next().await { + let Message::Text(text) = msg else { continue }; + let Ok(tunnel_msg) = serde_json::from_str::(&text) else { continue }; + + match tunnel_msg { + TunnelMsg::Allocate { request_id, player_id } => { + match hub.allocate(realm_id, player_id) { + Ok(alloc) => { + let token = alloc.token.clone(); + let auth_port = alloc.auth_port; + let world_port = alloc.world_port; + let expires_at = alloc.expires_at; + let relay_host = hub.relay_host.clone(); + + // Spawn TCP listeners for the allocation + spawn_game_listeners(hub.clone(), alloc); + + let reply = TunnelMsg::AllocateOk { + request_id, + token, + relay_host, + auth_port, + world_port, + expires_at, + }; + let _ = tx_to_host.send(reply).await; + } + Err(err) => { + let reply = TunnelMsg::AllocateErr { request_id, error: err }; + let _ = tx_to_host.send(reply).await; + } + } + } + TunnelMsg::ConnectOk { stream_id } => { + if let Some(tx) = hub.stream_tx(stream_id) { + let _ = tx.send(TunnelMsg::ConnectOk { stream_id }).await; + } + } + TunnelMsg::ConnectErr { stream_id, error } => { + if let Some(tx) = hub.stream_tx(stream_id) { + let _ = tx.send(TunnelMsg::ConnectErr { stream_id, error }).await; + } + } + TunnelMsg::Data { stream_id, chunk } => { + if let Some(tx) = hub.stream_tx(stream_id) { + let _ = tx.send(TunnelMsg::Data { stream_id, chunk }).await; + } + } + TunnelMsg::Close { stream_id } => { + if let Some(tx) = hub.stream_tx(stream_id) { + let _ = tx.send(TunnelMsg::Close { stream_id }).await; + } + } + TunnelMsg::Reset { stream_id } => { + if let Some(tx) = hub.stream_tx(stream_id) { + let _ = tx.send(TunnelMsg::Reset { stream_id }).await; + } + } + TunnelMsg::Ping => { + let _ = tx_to_host.send(TunnelMsg::Pong).await; + } + TunnelMsg::Pong => {} + _ => {} + } + } + + ws_send_task.abort(); + hub.unregister_host(&realm_id); +} + +fn spawn_game_listeners(hub: Arc>, alloc: crate::hub::Allocation) { + let hub_auth = hub.clone(); + let alloc_auth = alloc.clone(); + tokio::spawn(async move { + listen_game_port(hub_auth, alloc_auth, RelayTarget::Auth).await; + }); + + let hub_world = hub.clone(); + let alloc_world = alloc.clone(); + tokio::spawn(async move { + listen_game_port(hub_world, alloc_world, RelayTarget::World).await; + }); +} + +async fn listen_game_port(hub: Arc>, alloc: crate::hub::Allocation, target: RelayTarget) { + let port = match target { + RelayTarget::Auth => alloc.auth_port, + RelayTarget::World => alloc.world_port, + }; + + let bind_addr = format!("0.0.0.0:{port}"); + let Ok(listener) = TcpListener::bind(&bind_addr).await else { + tracing::error!(port, ?target, "failed to bind relay game port"); + return; + }; + + tracing::info!(port, ?target, "relay game listener active"); + + // Accept incoming connection within allocation window + let timeout = Duration::from_secs((alloc.expires_at.saturating_sub((hub.clock)())).max(1) as u64); + let accept_res = tokio::time::timeout(timeout, listener.accept()).await; + + let Ok(Ok((stream, _peer))) = accept_res else { + tracing::debug!(port, ?target, "relay listener timed out or accept failed"); + return; + }; + + + let Some(host_tx) = hub.host_tx(&alloc.realm_id) else { + tracing::warn!(realm_id = %alloc.realm_id, "host disconnected before game stream opened"); + return; + }; + + let stream_id = hub.next_stream_id.fetch_add(1, Ordering::Relaxed); + let (stream_tx, mut stream_rx) = mpsc::channel::(STREAM_CHANNEL_CAPACITY); + hub.register_stream(stream_id, stream_tx); + + // Send Connect request to Host + let connect_req = TunnelMsg::Connect { + stream_id, + target, + token: alloc.token.clone(), + }; + if host_tx.send(connect_req).await.is_err() { + hub.unregister_stream(stream_id); + return; + } + + // Wait for ConnectOk + let connect_ack = tokio::time::timeout(CONNECT_TIMEOUT, stream_rx.recv()).await; + match connect_ack { + Ok(Some(TunnelMsg::ConnectOk { .. })) => { + tracing::info!(stream_id, port, ?target, "relay stream connected to host target"); + } + _ => { + tracing::warn!(stream_id, port, ?target, "connect to host target failed or timed out"); + hub.unregister_stream(stream_id); + return; + } + } + + // Proxy stream + let (mut tcp_read, mut tcp_write) = stream.into_split(); + let host_tx_data = host_tx.clone(); + + // Client TCP -> Host Tunnel + let read_task = tokio::spawn(async move { + let mut buf = vec![0u8; STREAM_CHUNK_SIZE]; + loop { + match tcp_read.read(&mut buf).await { + Ok(0) => { + let _ = host_tx_data.send(TunnelMsg::Close { stream_id }).await; + break; + } + Ok(n) => { + let chunk = base64::engine::general_purpose::STANDARD.encode(&buf[..n]); + if host_tx_data.send(TunnelMsg::Data { stream_id, chunk }).await.is_err() { + break; + } + } + Err(_) => { + let _ = host_tx_data.send(TunnelMsg::Reset { stream_id }).await; + break; + } + } + } + }); + + // Host Tunnel -> Client TCP + let relay_host = hub.relay_host.clone(); + let world_port = alloc.world_port; + let write_task = tokio::spawn(async move { + while let Some(msg) = stream_rx.recv().await { + match msg { + TunnelMsg::Data { chunk, .. } => { + let Ok(data) = base64::engine::general_purpose::STANDARD.decode(&chunk) else { continue }; + let to_write = if target == RelayTarget::Auth { + // Check if REALM_LIST packet and rewrite realm address + match rewrite_realm_list_address(&data, &format!("{relay_host}:{world_port}")) { + Ok(Some(rewritten)) => rewritten, + _ => data, + } + } else { + data + }; + + if tcp_write.write_all(&to_write).await.is_err() { + break; + } + } + TunnelMsg::Close { .. } => { + let _ = tcp_write.shutdown().await; + break; + } + TunnelMsg::Reset { .. } => { + break; + } + _ => {} + } + } + }); + + let _ = tokio::join!(read_task, write_task); + hub.unregister_stream(stream_id); + tracing::info!(stream_id, port, ?target, "relay stream finished"); +} diff --git a/services/coa-relay/tests/relay.rs b/services/coa-relay/tests/relay.rs new file mode 100644 index 0000000..d24814f --- /dev/null +++ b/services/coa-relay/tests/relay.rs @@ -0,0 +1,251 @@ +use std::net::SocketAddr; +use std::sync::Arc; + +use base64::Engine; +use coa_control_proto::relay::*; + +use coa_registry_proto::RealmId; +use coa_relay::hub::{Hub, MemoryKeys}; +use coa_relay::router; +use ed25519_dalek::SigningKey; +use futures_util::{SinkExt, StreamExt}; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::net::{TcpListener, TcpStream}; +use tokio_tungstenite::connect_async; +use tokio_tungstenite::tungstenite::Message; +use uuid::Uuid; + +fn now() -> i64 { + std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_secs() as i64 +} + +fn random_key() -> SigningKey { + let mut seed = [0u8; 32]; + seed[..16].copy_from_slice(Uuid::new_v4().as_bytes()); + seed[16..].copy_from_slice(Uuid::new_v4().as_bytes()); + SigningKey::from_bytes(&seed) +} + +struct TestServer { + addr: SocketAddr, + hub: Arc>>, + keys: Arc, +} + +async fn start_test_relay(min_port: u16, max_port: u16) -> TestServer { + let keys = Arc::new(MemoryKeys::default()); + let hub = Arc::new(Hub::new( + "127.0.0.1".into(), + min_port, + max_port, + keys.clone(), + Arc::new(now), + )); + let app = router(hub.clone()); + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + + tokio::spawn(async move { + axum::serve(listener, app.into_make_service()).await.unwrap(); + }); + + TestServer { addr, hub, keys } +} + +#[tokio::test] +async fn test_relay_health_endpoint() { + let srv = start_test_relay(45000, 45010).await; + let mut stream = TcpStream::connect(srv.addr).await.unwrap(); + stream.write_all(b"GET /relay/v1/health HTTP/1.1\r\nHost: localhost\r\n\r\n").await.unwrap(); + let mut buf = vec![0u8; 1024]; + let n = stream.read(&mut buf).await.unwrap(); + let resp = String::from_utf8_lossy(&buf[..n]); + assert!(resp.contains("HTTP/1.1 200 OK")); + assert!(resp.contains("coa-relay")); +} + +#[tokio::test] +async fn test_relay_host_auth_and_allocation_and_game_traffic() { + let srv = start_test_relay(45100, 45110).await; + let realm_id = RealmId::new(); + let signing_key = random_key(); + srv.keys.set(realm_id, &signing_key.verifying_key()); + + // 1. Connect Host WebSocket to relay + let ws_url = format!("ws://{}/relay/v1/host", srv.addr); + let (ws_stream, _) = connect_async(&ws_url).await.unwrap(); + let (mut ws_sink, mut ws_src) = ws_stream.split(); + + // 2. Receive challenge + let challenge_msg = ws_src.next().await.unwrap().unwrap(); + let challenge_txt = challenge_msg.to_text().unwrap(); + let challenge: RelayChallenge = serde_json::from_str(challenge_txt).unwrap(); + + // 3. Send HostHello + let sig = sign_relay_challenge(&signing_key, &realm_id, &challenge.nonce); + let hello = HostHello { realm_id, signature: sig }; + ws_sink.send(Message::Text(serde_json::to_string(&hello).unwrap().into())).await.unwrap(); + + // 4. Receive welcome + let welcome_msg = ws_src.next().await.unwrap().unwrap(); + let welcome: RelayWelcome = serde_json::from_str(welcome_msg.to_text().unwrap()).unwrap(); + assert!(welcome.ok, "Host welcome should be ok"); + + // 5. Host asks for allocation + let player_id = Uuid::new_v4(); + let alloc_req = TunnelMsg::Allocate { request_id: 1, player_id }; + ws_sink.send(Message::Text(serde_json::to_string(&alloc_req).unwrap().into())).await.unwrap(); + + let alloc_msg = ws_src.next().await.unwrap().unwrap(); + let TunnelMsg::AllocateOk { request_id, auth_port, world_port, token, .. } = serde_json::from_str(alloc_msg.to_text().unwrap()).unwrap() else { + panic!("expected AllocateOk"); + }; + assert_eq!(request_id, 1); + assert_eq!(auth_port, 45100); + assert_eq!(world_port, 45101); + + // 7. Client connects to Relay AUTH port + + let client_task = tokio::spawn(async move { + let mut client_auth = TcpStream::connect(format!("127.0.0.1:{auth_port}")).await.unwrap(); + // Client sends auth packet + client_auth.write_all(b"CLIENT_AUTH_HELLO").await.unwrap(); + + // Read response (expected REALM_LIST rewritten) + let mut resp = vec![0u8; 1024]; + let n = client_auth.read(&mut resp).await.unwrap(); + resp.truncate(n); + resp + }); + + // 8. Host tunnel receives Connect for AUTH + let connect_msg = ws_src.next().await.unwrap().unwrap(); + let TunnelMsg::Connect { stream_id, target, token: conn_token } = serde_json::from_str(connect_msg.to_text().unwrap()).unwrap() else { + panic!("expected Connect"); + }; + assert_eq!(target, RelayTarget::Auth); + assert_eq!(conn_token, token); + + // Host acknowledges connect + ws_sink.send(Message::Text(serde_json::to_string(&TunnelMsg::ConnectOk { stream_id }).unwrap().into())).await.unwrap(); + + + // Relay forwards client data to Host + let data_msg = ws_src.next().await.unwrap().unwrap(); + let TunnelMsg::Data { chunk, .. } = serde_json::from_str(data_msg.to_text().unwrap()).unwrap() else { + panic!("expected Data"); + }; + let payload = base64::engine::general_purpose::STANDARD.decode(chunk).unwrap(); + assert_eq!(payload, b"CLIENT_AUTH_HELLO"); + + // Local auth backend sends REALM_LIST packet + let mut pkt = Vec::new(); + pkt.push(0x10); // Opcode + pkt.extend_from_slice(&[0, 0]); // Length + pkt.extend_from_slice(&[0, 0, 0, 0]); // Unused + pkt.extend_from_slice(&1u16.to_le_bytes()); // Realm count + pkt.push(1); pkt.push(0); pkt.push(0); + pkt.extend_from_slice(b"CoA\0"); + pkt.extend_from_slice(b"127.0.0.1:8085\0"); // Old address + pkt.extend_from_slice(&0.5f32.to_le_bytes()); + pkt.push(1); pkt.push(1); pkt.push(1); + pkt.push(0x10); pkt.push(0x00); + let body_len = (pkt.len() - 3) as u16; + pkt[1..3].copy_from_slice(&body_len.to_le_bytes()); + + // Host sends this packet through tunnel to Relay + let b64_pkt = base64::engine::general_purpose::STANDARD.encode(&pkt); + ws_sink.send(Message::Text(serde_json::to_string(&TunnelMsg::Data { stream_id, chunk: b64_pkt }).unwrap().into())).await.unwrap(); + + // Client receives rewritten packet + let client_recvd = client_task.await.unwrap(); + assert_eq!(client_recvd[0], 0x10); + // Must contain rewritten address (127.0.0.1:45101) + let expected_addr = format!("127.0.0.1:{world_port}").into_bytes(); + assert!(client_recvd.windows(expected_addr.len()).any(|w| w == expected_addr), "client received rewritten world address"); + + // 9. Client connects to Relay WORLD port + let client_world_task = tokio::spawn(async move { + let mut client_world = TcpStream::connect(format!("127.0.0.1:{world_port}")).await.unwrap(); + client_world.write_all(b"PING_WORLD_PACKET").await.unwrap(); + let mut resp = [0u8; 17]; + client_world.read_exact(&mut resp).await.unwrap(); + resp + }); + + // Host receives Connect for WORLD (skipping any Close from stream 1) + let (world_sid, world_target) = loop { + let msg = ws_src.next().await.unwrap().unwrap(); + match serde_json::from_str::(msg.to_text().unwrap()).unwrap() { + TunnelMsg::Connect { stream_id, target, .. } => break (stream_id, target), + TunnelMsg::Close { .. } => continue, + other => panic!("unexpected msg awaiting Connect: {other:?}"), + } + }; + assert_eq!(world_target, RelayTarget::World); + + // Host acknowledges + ws_sink.send(Message::Text(serde_json::to_string(&TunnelMsg::ConnectOk { stream_id: world_sid }).unwrap().into())).await.unwrap(); + + // Host receives world data (skipping any Close from stream 1) + let world_chunk = loop { + let msg = ws_src.next().await.unwrap().unwrap(); + match serde_json::from_str::(msg.to_text().unwrap()).unwrap() { + TunnelMsg::Data { stream_id, chunk } if stream_id == world_sid => break chunk, + TunnelMsg::Close { .. } => continue, + other => panic!("unexpected msg awaiting Data: {other:?}"), + } + }; + assert_eq!(base64::engine::general_purpose::STANDARD.decode(world_chunk).unwrap(), b"PING_WORLD_PACKET"); + + + // Host echoes back + let pong_b64 = base64::engine::general_purpose::STANDARD.encode(b"PONG_WORLD_PACKET"); + ws_sink.send(Message::Text(serde_json::to_string(&TunnelMsg::Data { stream_id: world_sid, chunk: pong_b64 }).unwrap().into())).await.unwrap(); + + let client_world_recvd = client_world_task.await.unwrap(); + assert_eq!(&client_world_recvd, b"PONG_WORLD_PACKET"); +} + +#[tokio::test] +async fn test_relay_rejects_unauthorized_host() { + let srv = start_test_relay(45200, 45210).await; + let realm_id = RealmId::new(); + let signing_key = random_key(); + // Do NOT register realm in keys + + let ws_url = format!("ws://{}/relay/v1/host", srv.addr); + let (ws_stream, _) = connect_async(&ws_url).await.unwrap(); + let (mut ws_sink, mut ws_src) = ws_stream.split(); + + let challenge_msg = ws_src.next().await.unwrap().unwrap(); + let challenge: RelayChallenge = serde_json::from_str(challenge_msg.to_text().unwrap()).unwrap(); + + let sig = sign_relay_challenge(&signing_key, &realm_id, &challenge.nonce); + let hello = HostHello { realm_id, signature: sig }; + ws_sink.send(Message::Text(serde_json::to_string(&hello).unwrap().into())).await.unwrap(); + + let welcome_msg = ws_src.next().await.unwrap().unwrap(); + let welcome: RelayWelcome = serde_json::from_str(welcome_msg.to_text().unwrap()).unwrap(); + assert!(!welcome.ok, "Unauthorized host must be rejected"); +} + +#[tokio::test] +async fn test_relay_allocation_bounds() { + // Port pool only has 2 pairs (4 ports) + let srv = start_test_relay(45300, 45303).await; + let realm = RealmId::new(); + + let alloc1 = srv.hub.allocate(realm, Uuid::new_v4()).unwrap(); + assert_eq!(alloc1.auth_port, 45300); + assert_eq!(alloc1.world_port, 45301); + + let alloc2 = srv.hub.allocate(realm, Uuid::new_v4()).unwrap(); + assert_eq!(alloc2.auth_port, 45302); + assert_eq!(alloc2.world_port, 45303); + + // Third allocation exhausts ports + let alloc3 = srv.hub.allocate(realm, Uuid::new_v4()); + assert!(alloc3.is_err(), "must fail when ports exhausted"); +} + diff --git a/src-tauri/src/control_cmds.rs b/src-tauri/src/control_cmds.rs index f3940e1..169daec 100644 --- a/src-tauri/src/control_cmds.rs +++ b/src-tauri/src/control_cmds.rs @@ -165,7 +165,6 @@ pub(crate) async fn join_realm(state: State<'_, AppState>, realm: String, charac return Ok(JoinOutcome::stop("needs_link", None)); } let account = pc.ensure_account(&mut ch, &rid, prefer.as_deref()).map_err(from_control)?; - ch.close(); let mut out = JoinOutcome { status: "ready".into(), username: Some(account.username), account_created: account.created, password_reset: account.password_reset, route: route.clone(), notes: vec![] }; if let Some(character) = character_for_check { let portable = portable.ok_or_else(|| fail("stopped", "The portable play service could not start."))?; @@ -174,20 +173,35 @@ pub(crate) async fn join_realm(state: State<'_, AppState>, realm: String, charac let pre = portable.call(move |s| s.preflight_advert(&id, &caps))?.map_err(|e| e)?; out.notes = pre.notes.clone(); if pre.step == portable_service::Step::Blocked { + ch.close(); out.status = "incompatible".into(); return Ok(out); } let here = pc.claimed_here(&rid).map_err(from_control)?; if !here.iter().any(|(id, _)| id.to_string() == character) { - // the character is not from this server: putting it there needs the Host to receive it, which the control channel does not carry yet - out.status = "needs_transfer".into(); - return Ok(out); + // Phase 12.1: Transfer canonical character to remote Host over the encrypted control channel + let char_id_str = character.clone(); + let bundle = portable.call(move |s| s.export_for_remote_transfer(&char_id_str))?.map_err(|e| e)?; + let cuuid = bundle.character_id.as_uuid(); + let _outcome = pc.transfer_character(&mut ch, cuuid, 1, &bundle.payload, bundle.content_hash, bundle.collections).map_err(from_control)?; + let _ = pc.acknowledge(&mut ch, cuuid, &rid, &character); } } if route.is_none() { - out.status = "needs_relay".into(); + match pc.allocate_relay(&mut ch) { + Ok(relay_alloc) => { + let r = format!("{}:{}", relay_alloc.relay_host, relay_alloc.auth_port); + out.route = Some(r); + out.status = "ready".into(); + } + Err(_) => { + out.status = "needs_relay".into(); + } + } } + ch.close(); Ok(out) + }) .await .map_err(|e| fail("other", e.to_string()))??;