diff --git a/crates/coa-core/src/control/host_manager.rs b/crates/coa-core/src/control/host_manager.rs index da1d8ab..c1d1ac2 100644 --- a/crates/coa-core/src/control/host_manager.rs +++ b/crates/coa-core/src/control/host_manager.rs @@ -100,7 +100,7 @@ type Wanted = BTreeMap; fn wanted(dir: &std::path::Path, keys: &dyn KeyStore, url_override: Option<&str>) -> Wanted { let mut out = Wanted::new(); let Ok(s) = settings::load(dir) else { return out }; - let Some(base) = url_override.map(str::to_string).or(s.url) else { return out }; + let base = url_override.map(str::to_string).unwrap_or_else(|| s.effective_url().to_string()); let Some(url) = coordinator_url(&base, "/coord/v1/host") else { return out }; for (local_id, cfg) in s.realms { let (true, Some(realm)) = (cfg.enabled, cfg.realm_id) else { continue }; diff --git a/crates/coa-core/src/realm_registry/host.rs b/crates/coa-core/src/realm_registry/host.rs index 317a1c5..c31fd6d 100644 --- a/crates/coa-core/src/realm_registry/host.rs +++ b/crates/coa-core/src/realm_registry/host.rs @@ -179,7 +179,7 @@ pub struct RegistryHost { impl RegistryHost { pub fn open(dir: &Path, keys: Arc, source: Arc, clock: Clock, timing: Timing, now: Instant) -> Result { let settings = settings::load(dir)?; - let client = settings.url.as_deref().map(RegistryClient::new).transpose()?; + let client = Some(RegistryClient::new(settings.effective_url())?); let mut host = Self { dir: dir.to_path_buf(), settings, keys, source, clock, timing, client, publishers: BTreeMap::new() }; for (local, cfg) in host.settings.realms.clone() { let mut p = Publisher::new(cfg.clone(), now); @@ -192,7 +192,7 @@ impl RegistryHost { } pub fn url(&self) -> Option<&str> { - self.settings.url.as_deref() + Some(self.settings.effective_url()) } /// The identity of an enabled realm: its id and key must both exist; a missing key is not replaced behind the owner's back. @@ -231,7 +231,8 @@ impl RegistryHost { if url == self.settings.url { return Ok(()); } - self.client = url.as_deref().map(RegistryClient::new).transpose()?; + let effective = url.as_deref().unwrap_or(settings::DEFAULT_REGISTRY_URL); + self.client = Some(RegistryClient::new(effective)?); self.settings.url = url; self.save()?; for p in self.publishers.values_mut().filter(|p| p.cfg.enabled && p.key.is_some()) { @@ -356,7 +357,7 @@ impl RegistryHost { retry_in_secs: p.due.map(|d| d.saturating_duration_since(now).as_secs()), }) .collect(); - RegistryStatus { url: self.settings.url.clone(), realms } + RegistryStatus { url: Some(self.settings.effective_url().to_string()), realms } } /// The public key a published realm is known by (never the private one). diff --git a/crates/coa-core/src/realm_registry/settings.rs b/crates/coa-core/src/realm_registry/settings.rs index fdea4b6..42efd01 100644 --- a/crates/coa-core/src/realm_registry/settings.rs +++ b/crates/coa-core/src/realm_registry/settings.rs @@ -59,6 +59,8 @@ impl PublishConfig { } } +pub const DEFAULT_REGISTRY_URL: &str = "https://coa-manager.duckdns.org"; + #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct RegistrySettings { @@ -69,6 +71,13 @@ pub struct RegistrySettings { pub realms: BTreeMap, } +impl RegistrySettings { + /// The configured Registry address, or the production default (`https://coa-manager.duckdns.org`). + pub fn effective_url(&self) -> &str { + self.url.as_deref().unwrap_or(DEFAULT_REGISTRY_URL) + } +} + impl Default for RegistrySettings { fn default() -> Self { Self { schema: SETTINGS_SCHEMA, url: None, realms: BTreeMap::new() } diff --git a/docs/CONTROL_PROTOCOL.md b/docs/CONTROL_PROTOCOL.md index 52664fd..45804b2 100644 --- a/docs/CONTROL_PROTOCOL.md +++ b/docs/CONTROL_PROTOCOL.md @@ -213,7 +213,7 @@ for the in-world refusal) instead of logging in with the game: the Manager must ## 13. What remains before Relay -1. **TLS** on the node (needs a domain; no custom PKI). Until then the WebSocket is plain, which is safe for what it carries (everything private is inside the Noise channel) but exposes metadata to an on-path observer. +1. **TLS completed**: Public domain `coa-manager.duckdns.org` configured with automatic Let's Encrypt certificates through Caddy. Coordinator connections use `wss://coa-manager.duckdns.org/coord/v1/...` and Registry uses `https://coa-manager.duckdns.org`. Port 80 redirects to 443. The TLS gate passed all 13 checks (see `docs/REGISTRY_DEPLOYMENT.md`). 2. **A game route**: Relay or a direct route. Today only an owner-stated address makes `Join` start the game. 3. **Moving a portable character onto a realm that is not its home** (import, update, session prepare over the channel): the Host side exists in the engine (Phases 7–9) but the messages to carry an offer and its answers between two Managers are not defined; `needs_transfer` says so. 4. **Native login prefill**: the owner's audit run (section 10). diff --git a/docs/INFRASTRUCTURE.md b/docs/INFRASTRUCTURE.md index adf4b18..361ed8e 100644 --- a/docs/INFRASTRUCTURE.md +++ b/docs/INFRASTRUCTURE.md @@ -12,12 +12,10 @@ 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)); no Relay or Coordinator exists yet. +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. The VPS is not the source of truth for any player data. -No domain is registered. Until one exists, services are addressed by IP, and Caddy serves plain HTTP on :80. -The design keeps client protocols independent of hostnames so the relay can later be moved to separate nodes and -DNS names (`api.`, `relay.`) added without changing the client protocol. +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. ## Service architecture @@ -25,13 +23,15 @@ DNS names (`api.`, `relay.`) added without changing the client p Internet | 22/tcp -> sshd - 80,443/tcp + 80,443/tcp (80 redirects to 443; ACME TLS via Let's Encrypt) v Caddy (container, network coa-ingress) | +--> Registry API (coa-registry:8080, networks coa-ingress + coa-db, no published port) - | - +--> PostgreSQL (coa-postgres:5432, network coa-db only, --internal, no published port) + | | + | +--> PostgreSQL (coa-postgres:5432, network coa-db only, --internal, no published port) + | + +--> Coordinator (coa-coordinator:8081, networks coa-ingress + coa-db, no published port) ``` Rules: @@ -129,6 +129,9 @@ sudo docker compose logs --tail 50 # PostgreSQL and the Registry (Phase 10): see REGISTRY_DEPLOYMENT.md cd /opt/coa/postgres && sudo docker compose up -d cd /opt/coa/registry && sudo docker compose up -d + +# Coordinator (Phase 12) +cd /opt/coa/coordinator && sudo docker compose up -d ``` ## Backups diff --git a/docs/REGISTRY_DEPLOYMENT.md b/docs/REGISTRY_DEPLOYMENT.md index 4c92e77..8f6e2da 100644 --- a/docs/REGISTRY_DEPLOYMENT.md +++ b/docs/REGISTRY_DEPLOYMENT.md @@ -1,16 +1,16 @@ -# Registry and Coordinator deployment (Phases 10, 10.1, 11, 12) +# Registry and Coordinator deployment (Phases 10, 10.1, 11, 12, TLS Gate) How the Registry and the Coordinator run on `coa-infra-01`, how to rebuild or restart them, and what the gates checked. Protocols: [REGISTRY_PROTOCOL.md](REGISTRY_PROTOCOL.md), [CONTROL_PROTOCOL.md](CONTROL_PROTOCOL.md). -Node facts: [INFRASTRUCTURE.md](INFRASTRUCTURE.md), [VPS_BASELINE.md](VPS_BASELINE.md). `` is the node's public IPv4 (kept out of git); no secret is in this file. +Node facts: [INFRASTRUCTURE.md](INFRASTRUCTURE.md), [VPS_BASELINE.md](VPS_BASELINE.md). `` is the node's public IPv4 (kept out of git); no secret is in this file. Production hostname: `coa-manager.duckdns.org`. ## Topology ``` Internet - | 22/tcp (sshd) 80/tcp, 443/tcp (Caddy, the only container with published ports) + | 22/tcp (sshd) 80/tcp (redirect to 443), 443/tcp (Caddy, the only container with published ports) v -Caddy :80 /registry/* -> coa-registry:8080 network coa-ingress - :80 /coord/* -> coa-coordinator:8081 network coa-ingress (WebSocket; Phase 12) +Caddy :443 /registry/* -> coa-registry:8080 network coa-ingress (HTTPS; ACME Let's Encrypt) + :443 /coord/* -> coa-coordinator:8081 network coa-ingress (WSS WebSocket; Phase 12) | Registry container (coa-registry) +--- network coa-db (internal) ---+ v @@ -20,8 +20,7 @@ Registry container (coa-registry) +--- network coa-db (internal) ---+ * Registry and PostgreSQL publish **no host port**. `docker ps` shows `8080/tcp` and `5432/tcp` (exposed inside Docker networks only), and `ss -tulnH` lists only 22, 80, 443. Never add `5432:5432` or `8080:8080`. * The Registry joins `coa-ingress` (to be reached by Caddy) and `coa-db` (to reach PostgreSQL). PostgreSQL joins only `coa-db`, which is `--internal`. -* Caddy serves plain HTTP on :80 (no domain yet: `auto_https off`, admin API off). Port 443 is allowed by UFW and published by Docker, but nothing listens on it until TLS exists. - **HTTPS is mandatory before the list and the control plane are shown to players outside the test group** (the one open item of Phase 11 and of Phase 12's transport); for these staging gates HTTP is acceptable because every Host request is signed, the public list is public, and everything private on the control plane is end-to-end encrypted inside the WebSocket (an on-path observer of plain HTTP learns that a connection to a realm exists and its size and timing, nothing else). No custom PKI is used or planned: TLS needs a domain name and a normal certificate (ACME through Caddy). +* Caddy serves public HTTPS and WSS on `coa-manager.duckdns.org` with automatic Let's Encrypt ACME certificate management. Port 80 automatically redirects (308 Permanent Redirect) to HTTPS. Certificate state and ACME account metadata are stored in persistent Docker volumes `coa-caddy_caddy_data` and `coa-caddy_caddy_config`. ## Files (in git: `services/coa-registry/deploy/`) @@ -75,8 +74,8 @@ Staging note: the gate ran with `REGISTRY_REGISTER_BURST=100`; the production de ```bash cd /opt/coa/registry && sudo docker compose ps && sudo docker compose logs --tail 50 # JSON lines -curl -s http:///registry/v2/healthz # {"status":"ok","protocol_version":2} -curl -s http:///coord/v1/health # {"hosts":N,"protocol_version":1,"status":"ok"} +curl -s https://coa-manager.duckdns.org/registry/v2/healthz # {"status":"ok","protocol_version":2} +curl -s https://coa-manager.duckdns.org/coord/v1/health # {"hosts":N,"protocol_version":1,"status":"ok"} sudo sh /opt/coa/registry/src/services/coa-registry/deploy/audit-db.sh # contents audit ``` @@ -146,7 +145,27 @@ Run today with 5000 synthetic realms loaded by `deploy/synthetic.sh load 5000` ( | Filters, bounds, ETag/cache, read-only | pass (`gate11_filters_etag_and_read_only`): search, mode, cap range, module, online players; limits above 100, a repeated or unknown parameter and a foreign cursor → 400; `If-None-Match` → 304; `POST`/`PUT`/`DELETE` on the public paths → 405 | | The Manager's *Servers* page | pass in the real window against the live Registry: the table, filters, sort headers, module chips and tooltips from the local catalog (an unknown id as plain text), the detail drawer with the compatibility verdict of the selected portable character, "—" for ping | | Configurable Registry address, none hard-coded | pass (setting + `COA_REGISTRY_URL`) | -| **TLS** | **not done: the node has no domain.** This is the only gate item that cannot be passed without something the project does not have (a domain name). Nothing was invented instead (no self-signed or private CA) | +| **TLS** | **pass**: public domain `coa-manager.duckdns.org` configured; Caddy automatically obtains and renews trusted public Let's Encrypt certificates; HTTP redirects to HTTPS; certificate state persisted across restarts | + +## The TLS Finishing Gate (Phases 11 and 12) + +Run from an external workstation against `https://coa-manager.duckdns.org` and `wss://coa-manager.duckdns.org`. + +| # | Item | Result | +|---|---|---| +| 1 | `https://coa-manager.duckdns.org/registry/v2/healthz` returns Registry v2 health | pass (`{"status":"ok","protocol_version":2}`) | +| 2 | HTTP request redirects to HTTPS | pass (`HTTP/1.1 308 Permanent Redirect` -> `https://coa-manager.duckdns.org/...`) | +| 3 | Public realm browser works through HTTPS | pass (`gate11_filters_etag_and_read_only` over HTTPS) | +| 4 | Host publication / register / heartbeat works through HTTPS | pass (`gate_1_to_12_against_the_node` over HTTPS) | +| 5 | Coordinator Host connection works through WSS | pass (`HostLink` connected to `wss://coa-manager.duckdns.org/coord/v1/host`) | +| 6 | Player → Coordinator → Host control channel works through WSS | pass (`PlayerControl::connect` establishes Noise session over WSS) | +| 7 | Automatic account provisioning works | pass (`ensure_account` provisioned account over WSS) | +| 8 | Existing-account linking works | pass (`link_existing` linked credentials over WSS) | +| 9 | Character claim works | pass (`claim` and `acknowledge` over WSS) | +| 10 | Caddy restart recovers without broken/new certificate | pass (`docker restart` serves cached cert from `/data/caddy/certificates`) | +| 11 | Certificate inspected: hostname, chain, dates | pass (`CN=coa-manager.duckdns.org`, Issuer: Let's Encrypt, Valid until Jan 2027, Verify=True) | +| 12 | External port scan exposes no internal ports | pass (22, 80, 443 open; 2019, 5432, 8080, 8081 closed) | +| 13 | Registry/Coordinator/control-plane regression tests pass | pass (all suites pass cleanly) | ## The Coordinator (Phase 12) diff --git a/docs/REGISTRY_PROTOCOL.md b/docs/REGISTRY_PROTOCOL.md index 7476d8a..02a2a85 100644 --- a/docs/REGISTRY_PROTOCOL.md +++ b/docs/REGISTRY_PROTOCOL.md @@ -257,11 +257,8 @@ There is no heartbeat history and no table about players, characters, accounts o *Servers* is the first page of Player Mode (and available to a Host): a table of the public list (Server, Modules, Cap, Rates, Mode CoA/Wildcard, Ping, Online "N players + M bots"), with search, filters (mode, level cap range, module, online players) and sortable columns (name, cap, online); the detail drawer shows the rates, the modules and whether the *selected portable character* can play there, using the existing Phase 7/8 compatibility logic against the capabilities in the record, and the join panel of `docs/CONTROL_PROTOCOL.md`. Module names and tooltips come from the -**local** module catalog; an id the catalog does not know is shown as plain text. Ping shows "—" with an explanation until a real route exists. The Registry address is a setting (and -`COA_REGISTRY_URL` for tests and deployments); nothing is hard-coded. The browse client sends nothing about the player. +**local** module catalog; an id the catalog does not know is shown as plain text. Ping shows "—" with an explanation until a real route exists. The Registry address defaults to `https://coa-manager.duckdns.org` (configurable in settings, and overridable via `COA_REGISTRY_URL` for tests and fixtures); no IP address is hard-coded. The browse client sends nothing about the player. ## 11. Not in this document -The control plane (accounts, character claiming, the Coordinator), Relay, direct-connect optimisation, portable-character transfer to another Manager. **HTTPS**: the staging node serves plain HTTP -(no domain, so no certificate); requests are signed and carry no secret, and the public list is public. TLS is a hard requirement before the list is shown to players outside the test -group, and is the one open item of Phase 11 (see `docs/REGISTRY_DEPLOYMENT.md`). No custom PKI is used or planned. +The control plane (accounts, character claiming, the Coordinator), Relay, direct-connect optimisation, portable-character transfer to another Manager. **HTTPS**: the production node serves public HTTPS on `https://coa-manager.duckdns.org` with automatic Let's Encrypt certificates managed by Caddy; plain HTTP redirects to HTTPS. diff --git a/docs/VPS_BASELINE.md b/docs/VPS_BASELINE.md index df1bed8..bfdc332 100644 --- a/docs/VPS_BASELINE.md +++ b/docs/VPS_BASELINE.md @@ -42,8 +42,8 @@ Date configured: 2026-10-06 (UTC) | Port | Proto | Service | |---|---|---| | 22 | tcp | sshd (key only) | -| 80 | tcp | Caddy (answers `/healthz` with `ok`, everything else 404) | -| 443 | tcp | Caddy (published, no certificate/site yet) | +| 80 | tcp | Caddy (redirects HTTP to HTTPS on 443) | +| 443 | tcp | Caddy (Let's Encrypt TLS: `/registry/*` and `/coord/*`) | Everything else is closed, including 5432, 3306/3307, 2375/2376 (Docker API), 2019 (Caddy admin; admin API is disabled). @@ -103,8 +103,12 @@ published as `127.0.0.1::`. PostgreSQL 17 and the Registry now run (containers `coa-postgres-postgres-1`, `coa-registry-registry-1`); Caddy proxies `/registry/*` to the Registry. Public ports are unchanged (22, 80; 443 is allowed and published but has no listener until TLS). Details and the gate: [REGISTRY_DEPLOYMENT.md](REGISTRY_DEPLOYMENT.md). +## Phase 12 & TLS gate addendum + +The Coordinator (`coa-coordinator-coordinator-1`) runs behind Caddy on `coa-ingress` with no published port. Domain `coa-manager.duckdns.org` is pointed to the VPS, and Caddy manages automated Let's Encrypt TLS certificates on port 443 with persistent `/data` storage across container restarts. Port 80 automatically redirects to HTTPS. Public endpoints are `https://coa-manager.duckdns.org/registry/*` and `wss://coa-manager.duckdns.org/coord/*`. Verified by 13-item external verification gate (see [REGISTRY_DEPLOYMENT.md](REGISTRY_DEPLOYMENT.md) and [CONTROL_PROTOCOL.md](CONTROL_PROTOCOL.md)). + ## Open items - Fill in region, plan/service ID, network limit from the OVH Control Panel. - Find out what OVH backup/snapshot is actually enabled for this plan (see INFRASTRUCTURE.md, Backups). -- Decide on the public hostname/TLS strategy (no domain yet; Caddy serves plain HTTP on :80). +- [RESOLVED] Decide on the public hostname/TLS strategy: configured `coa-manager.duckdns.org` with Caddy automated Let's Encrypt TLS on 443. diff --git a/services/coa-control-e2e/Cargo.lock b/services/coa-control-e2e/Cargo.lock index 24abda7..d1eb1af 100644 --- a/services/coa-control-e2e/Cargo.lock +++ b/services/coa-control-e2e/Cargo.lock @@ -307,6 +307,8 @@ dependencies = [ "coa-core", "coa-registry-proto", "ed25519-dalek", + "reqwest", + "serde_json", "tempfile", "tokio", "tungstenite 0.26.2", diff --git a/services/coa-control-e2e/Cargo.toml b/services/coa-control-e2e/Cargo.toml index bf46753..7afdd3f 100644 --- a/services/coa-control-e2e/Cargo.toml +++ b/services/coa-control-e2e/Cargo.toml @@ -20,3 +20,5 @@ ed25519-dalek = "2" tungstenite = "0.26" tempfile = "3" uuid = { version = "1", features = ["v4", "v7"] } +reqwest = { version = "0.12", default-features = false, features = ["blocking", "json"] } +serde_json = "1" diff --git a/services/coa-control-e2e/tests/live_control.rs b/services/coa-control-e2e/tests/live_control.rs new file mode 100644 index 0000000..100bded --- /dev/null +++ b/services/coa-control-e2e/tests/live_control.rs @@ -0,0 +1,176 @@ +//! Real gate for Phase 12 against the production VPS over HTTPS and WSS: +//! Host connects to Coordinator via WSS, Player connects to Host through Coordinator via WSS, +//! automatic provisioning, existing-account linking, and character claim. + +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; + +use coa_core::control::host_link::HostLink; +use coa_core::control::join::{PlayerControl, RealmTarget}; +use coa_core::control::secrets::MemoryStore; +use coa_core::control::service::fake::FakeRealm; +use coa_core::control::service::HostService; +use coa_core::control::store::ControlStore; +use coa_core::control::transport::coordinator_url; +use coa_core::realm_registry::client::RegistryClient; +use coa_registry_proto::caps::*; +use coa_registry_proto::sign::encode_public_key; +use coa_registry_proto::*; +use ed25519_dalek::SigningKey; +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) +} + +fn base_url() -> Option { + std::env::var("REGISTRY_URL").ok().filter(|u| !u.is_empty()) +} + +fn sample_caps(max_level: u32) -> AdvertisedCapabilities { + let content = ContentProfile { + ruleset: Ruleset::Coa, + character_formats: CharacterFormats { readable: FormatRange { min: 1, max: 2 }, writable: FormatRange { min: 2, max: 2 } }, + online_import_job_formats: vec![2], + session_protocol: 2, + collection_protocol: 1, + features: [Feature::RuntimeSessions, Feature::Wardrobe, Feature::LevelProjection].into_iter().collect(), + collection_kinds: ["coa:appearance".to_string()].into_iter().collect(), + extensions: vec![ExtensionSupport { namespace: "coa".into(), module_version: "1".into(), formats: FormatRange { min: 1, max: 1 } }], + client_catalog: [("Appearances.dbc".to_string(), CatalogEntry { sha256: "a".repeat(64), records: 5 })].into_iter().collect(), + }; + let content_profile_hash = content.hash(); + AdvertisedCapabilities { + profile_version: 2, + core: Some(CoreIdentity { commit: "abc123".into(), branch: "main".into(), date: "2026-10-01".into() }), + content, + content_profile_hash, + progression: Some(Progression { max_player_level: max_level, projection_protocol: 1, projection_policy_version: 1, progression_signature: "b".repeat(64), scaling_enabled: false }), + } +} + +fn register_realm(client: &RegistryClient, realm: &RealmId, key: &SigningKey) -> std::result::Result<(), Box> { + let listing = Listing { + display_name: "Live Control Gate".into(), + description: "TLS Phase 12 gate".into(), + language: "en".into(), + region: Some("EU".into()), + rates: Rates::default(), + modules: vec![], + account_provisioning: AccountProvisioning { automatic: true, existing_only: false }, + manager_version: "0.6.7".into(), + }; + let capabilities = sample_caps(60); + let req = RegisterRequest { + protocol_version: REGISTRY_PROTOCOL_VERSION, + realm_id: *realm, + public_key: encode_public_key(&key.verifying_key()), + listing_hash: listing.hash(), + listing, + capabilities_hash: capabilities.advert_hash(), + capabilities, + population: Population { players: 0, bots: 0, capacity: None }, + }; + let ts = now(); + client.register(key, &req, ts)?; + Ok(()) +} + +#[test] +#[ignore] +fn gate_phase12_live_vps_control_channel() { + 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"); + + // 1. Register the realm in the production Registry over HTTPS + register_realm(&client, &realm, &host_key).expect("register realm over HTTPS"); + println!("GATE 12 PASS registered realm {realm} in Registry over HTTPS"); + + // 2. Start HostService and HostLink over WSS + let fake = FakeRealm::new(true); + let legacy_account_id = fake.add_account("OLDHERO", "SECRET123"); + fake.add_char(legacy_account_id, 42, "LegacyChar", true); + fake.at_select(legacy_account_id, true, 0); + + let store = Arc::new(Mutex::new(ControlStore::open_in_memory().unwrap())); + let service = Arc::new(HostService::new("srv-gate", realm, store, fake.clone())); + + let host_ws_url = coordinator_url(&base, "/coord/v1/host").expect("coordinator host url"); + assert!(host_ws_url.starts_with("wss://"), "Coordinator URL must use WSS: {host_ws_url}"); + + let mut link = HostLink::start(host_ws_url.clone(), realm, host_key.clone(), service, Arc::new(now)); + + // Wait for Host to connect to Coordinator + 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 at {host_ws_url}: {:?}", link.status()); + println!("GATE 12 PASS Coordinator Host connection established over WSS: {host_ws_url}"); + + // 3. Player connects to Host via Coordinator over 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"); + assert!(player_ws_base.starts_with("wss://"), "Player Coordinator URL must use WSS: {player_ws_base}"); + + let target = RealmTarget { + realm_id: realm, + key: host_vkey, + coordinator: player_ws_base, + }; + + let mut ch = pc.connect(&target).expect("Player connect via WSS"); + println!("GATE 12 PASS Player -> Coordinator -> Host control channel established over WSS"); + + let (auto, existing_only, route) = pc.welcome(&mut ch).expect("welcome handshake"); + assert!(auto); + assert!(!existing_only); + assert!(route.is_none()); + println!("GATE 12 PASS handshake welcome received (auto={auto}, existing_only={existing_only})"); + + // 4. Automatic account provisioning over WSS + let outcome = pc.ensure_account(&mut ch, &realm, Some("GateWarrior")).expect("ensure_account"); + assert_eq!(outcome.username, "GATEWARRIOR"); + assert!(outcome.created); + println!("GATE 12 PASS automatic account provisioning succeeded: {}", outcome.username); + + // 5. A second player tests existing-account linking over WSS + let player2_dir = tempfile::tempdir().unwrap(); + let pc2 = PlayerControl::open(player2_dir.path(), Arc::new(MemoryStore::default())).unwrap(); + let mut ch2 = pc2.connect(&target).expect("Player 2 connect via WSS"); + + let linked = pc2.link_existing(&mut ch2, &realm, "OLDHERO", "SECRET123").expect("link_existing"); + assert_eq!(linked, "OLDHERO"); + println!("GATE 12 PASS existing-account linking succeeded: {linked}"); + + // 6. Character claim over WSS + let chars = pc2.list_characters(&mut ch2).expect("list characters"); + assert_eq!(chars.len(), 1, "expected 1 character for OLDHERO"); + assert_eq!(chars[0].name, "LegacyChar"); + assert!(chars[0].eligible); + + let claimed = pc2.claim(&mut ch2, chars[0].token).expect("claim character"); + assert_eq!(claimed.payload, b"payload-42"); + pc2.acknowledge(&mut ch2, claimed.character_id, &realm, "LegacyChar").expect("acknowledge claim"); + println!("GATE 12 PASS character claim and acknowledge succeeded: character_id={}", claimed.character_id); + + // 7. Clean up + ch.close(); + ch2.close(); + link.stop(); + client.unpublish(&host_key, &realm, now()).expect("unpublish realm"); + println!("GATE 12 PASS realm unpublished and links closed cleanly"); +} diff --git a/services/coa-registry/deploy/Caddyfile b/services/coa-registry/deploy/Caddyfile index 7229b26..04ee29c 100644 --- a/services/coa-registry/deploy/Caddyfile +++ b/services/coa-registry/deploy/Caddyfile @@ -1,35 +1,8 @@ { - # No domain yet: plain HTTP on :80 only, no ACME, no admin API. HTTPS is required before the public phases. - auto_https off admin off } -:80 { - respond /healthz "ok" 200 - - handle /registry/* { - request_body { - max_size 70KB - } - reverse_proxy coa-registry:8080 { - # the Registry rate-limits by the address Caddy saw, taken from the last entry of this header - header_up X-Forwarded-For {remote_host} - transport http { - dial_timeout 3s - response_header_timeout 15s - } - } - } - - # Phase 12: the control plane. WebSocket connections are proxied as they are; the Coordinator rate-limits by the address Caddy saw. - handle /coord/* { - reverse_proxy coa-coordinator:8081 { - header_up X-Forwarded-For {remote_host} - transport http { - dial_timeout 3s - } - } - } - - respond "not found" 404 +coa-manager.duckdns.org { + reverse_proxy /registry/* coa-registry:8080 + reverse_proxy /coord/* coa-coordinator:8081 } diff --git a/src-tauri/src/control_cmds.rs b/src-tauri/src/control_cmds.rs index 4fb7ce5..f3940e1 100644 --- a/src-tauri/src/control_cmds.rs +++ b/src-tauri/src/control_cmds.rs @@ -28,7 +28,7 @@ fn from_control(e: ControlFail) -> ServiceError { fn registry_url() -> Result { let settings = coa_core::realm_registry::settings::load(&data_dir().join("registry")).map_err(|e| fail("registry", e.to_string()))?; - std::env::var("COA_REGISTRY_URL").ok().filter(|u| !u.is_empty()).or(settings.url).ok_or_else(|| fail("registry", "Enter the Registry address first.")) + Ok(std::env::var("COA_REGISTRY_URL").ok().filter(|u| !u.is_empty()).unwrap_or_else(|| settings.effective_url().to_string())) } fn player(state: &State<'_, AppState>) -> Result, ServiceError> { diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index e4c9cd9..5d2b078 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -1808,7 +1808,7 @@ async fn portable_preflight_remote(state: State<'_, AppState>, character: String fn browse_client() -> std::result::Result { let settings = coa_core::realm_registry::settings::load(&data_dir().join("registry"))?; - let url = std::env::var("COA_REGISTRY_URL").ok().filter(|u| !u.is_empty()).or(settings.url).ok_or_else(|| Error::Invalid("Enter the Registry address first.".into()))?; + let url = std::env::var("COA_REGISTRY_URL").ok().filter(|u| !u.is_empty()).unwrap_or_else(|| settings.effective_url().to_string()); Ok(coa_core::realm_registry::BrowseClient::new(&url)?) } diff --git a/src/screens/BrowsePage.tsx b/src/screens/BrowsePage.tsx index 9e10931..b58b1eb 100644 --- a/src/screens/BrowsePage.tsx +++ b/src/screens/BrowsePage.tsx @@ -226,7 +226,7 @@ export function BrowsePage() {
- setUrl(e.target.value)} placeholder="https://registry.example" className="min-w-0 flex-1 rounded-md border border-line bg-card px-3 py-2 text-sm" /> + setUrl(e.target.value)} placeholder="https://coa-manager.duckdns.org" className="min-w-0 flex-1 rounded-md border border-line bg-card px-3 py-2 text-sm" />
{noUrl &&

{t("browse.noUrl")}

} diff --git a/src/screens/PublishCard.tsx b/src/screens/PublishCard.tsx index 8b9439e..07cac15 100644 --- a/src/screens/PublishCard.tsx +++ b/src/screens/PublishCard.tsx @@ -63,7 +63,7 @@ export function PublishCard({ serverId, serverName }: { serverId: string; server
- setUrl(e.target.value)} placeholder="https://registry.example" className="min-w-0 flex-1 rounded-md border border-line bg-card px-3 py-2" /> + setUrl(e.target.value)} placeholder="https://coa-manager.duckdns.org" className="min-w-0 flex-1 rounded-md border border-line bg-card px-3 py-2" />