garage44.eu/jeroen/cartopolis

logclone: git clone https://garage44.eu/jeroen/cartopolis.git

.. /crates/simulator/src/config.rs

raw

use anyhow::Context;
use figment::providers::{Env, Format, Serialized, Toml};
use figment::Figment;
use serde::{Deserialize, Serialize};
use std::path::Path;

/// Server configuration (ADR-014).
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct SimConfig {
    #[serde(default = "default_listen")]
    pub listen: String,
    /// HTTP listener for the browser transport (`/ws`) and the account admin API
    /// (`/api/admin/*`), or `None` for none.
    ///
    /// Off by default, so solo mode and every existing test get exactly the TCP
    /// listener they had. A deployment turns it on; the listener it wants is a
    /// loopback or docker-gateway address, because it speaks plain HTTP and the
    /// TLS in front of it is Caddy's.
    #[serde(default)]
    pub http_listen: Option<String>,
    /// UDP address the call forwarder listens on (`docs/notes/calls.md`), or
    /// `None` for a server without calls. Off by default for the same reason
    /// `http_listen` is: the tests and every embedded `serve` get what they had.
    #[serde(default)]
    pub calls_listen: Option<String>,
    /// `host:port` clients reach the forwarder at, when that is not the listen
    /// address: behind Docker's NAT, or listening on `0.0.0.0`. WebRTC puts it
    /// in the SDP as the one candidate, so it must be an address, not a name.
    #[serde(default)]
    pub calls_public_addr: Option<String>,
    #[serde(default = "default_db")]
    pub database_path: String,
    #[serde(default = "default_tick_hz")]
    pub tick_hz: f32,
    /// Most prims this world may hold at once.
    ///
    /// Was a per-region column (schema V7), on the reasoning that a region is
    /// the unit an operator hands out. A simulator only ever ran one region, so
    /// the ceiling was always the server's — and a budget an operator sets
    /// belongs beside the rest of their decisions rather than in a table nothing
    /// else reads. Deliberately small: a world that has never been configured
    /// should hit its ceiling during testing rather than the first time somebody
    /// scripts a loop in production.
    #[serde(default = "default_max_prims")]
    pub max_prims: u32,
    /// Most *scripted* prims this world may hold at once. Separate from
    /// [`Self::max_prims`] because a script costs a VM and a share of the tick's
    /// fuel bank, where a plain prim costs a row.
    #[serde(default = "default_max_scripts")]
    pub max_scripts: u32,
    /// The compiled script host prim scripts run in (`deploy/build/script-host.sh`,
    /// `docs/notes/javascript-prim-scripts.md`). Unset, it is
    /// `cartopolis-script-host` beside the simulator's own binary, where the
    /// deploy and the server download put it ([`Self::script_host`]).
    #[serde(default)]
    pub script_host: Option<String>,
    /// `tools/script-host` to run from source with [`Self::script_bun`]
    /// instead, for a server run from a checkout. Unset and with no compiled
    /// host beside the binary, it is this checkout's.
    #[serde(default)]
    pub script_host_dir: Option<String>,
    /// The `bun` executable (1.4 or later) for [`Self::script_host_dir`].
    #[serde(default = "default_script_bun")]
    pub script_bun: String,
    /// A tick the script process has not answered by then is a hung script:
    /// the process is killed and the running prim blamed.
    #[serde(default = "default_script_tick_timeout_ms")]
    pub script_tick_timeout_ms: u64,
    /// Resident memory, in MiB, past which the script process is killed.
    #[serde(default = "default_script_memory_limit_mib")]
    pub script_memory_limit_mib: u64,
    /// Placeholders `{z}`, `{x}`, `{y}` for client tile fetch (ADR-004 / ADR-014).
    #[serde(default = "default_osm_tile_url_template")]
    pub osm_tile_url_template: String,
    /// Where clients should reach this server's HTTP surface, told to each one in
    /// the handshake (`ServerHelloAck::api_base_url`).
    ///
    /// Empty is the default and means "say nothing", which leaves the client to
    /// derive it from the address it connected to — right for the common case
    /// where the reverse proxy serves the wire and the API on one hostname. Set
    /// it when they are not the same, which includes every deployment where the
    /// listener below is bound to a private address.
    ///
    /// No trailing slash; the client appends `/api/...`.
    #[serde(default)]
    pub api_base_url: String,
    /// Atlas, when this server's HTTP listener also answers atlas's paths by
    /// passing them on to it (`atlas_proxy`), e.g. `http://127.0.0.1:4749`.
    /// `cartopolis-server` sets it to the atlas it runs; unset, there is no
    /// such route, as on the hosted server where Caddy routes them itself.
    #[serde(default)]
    pub atlas_url: Option<String>,
    /// The municipality's notices (atlas's `/plans/groningen.json`), read
    /// every so often to wake a closed phone for a notice near a place its
    /// account follows (`plans_watch`). Unset, it is `atlas_url`'s when that
    /// is set, and otherwise nothing is read and nobody is woken.
    #[serde(default)]
    pub plans_url: Option<String>,
    /// The web UI's built files, served at the root of the HTTP listener with
    /// its `index.html` for any path it has no file for (`static_files`). Unset
    /// on the hosted server, where Caddy serves them.
    #[serde(default)]
    pub web_root: Option<String>,
    /// Atlas's map-data tree (its `site_dir`), served under `/data/`.
    #[serde(default)]
    pub map_data_dir: Option<String>,
    /// Where this server's geo services are, told to clients at
    /// `GET /api/services` ([`cartopolis_core::services`]). Each defaults to
    /// cartopolis.org's, so a server that sets none sends its players where they
    /// always went. Flat rather than a `[services]` table for the reason
    /// [`Self::mail`] gives: `CARTO_GEOCODER_URL` is what an operator writes.
    #[serde(default = "default_geocoder_url")]
    pub geocoder_url: String,
    #[serde(default = "default_osm_query_url")]
    pub osm_query_url: String,
    #[serde(default = "default_map_data_url")]
    pub map_data_url: String,
    #[serde(default = "default_terrain_url")]
    pub terrain_url: String,
    #[serde(default = "default_height_url")]
    pub height_url: String,
    /// Directory from which *.png texture files are served to clients.
    #[serde(default = "default_texture_dir")]
    pub texture_dir: String,
    /// Directory holding uploaded model assets, one `.glb` per content hash
    /// (`assets`, `library`).
    ///
    /// Beside the database rather than inside it. `world.db` is written on the
    /// tick path, and a few megabytes per row makes every backup, every
    /// migration and every `VACUUM` carry the whole model library; `texture_dir`
    /// already sets the precedent that bulk content is a directory.
    #[serde(default = "default_asset_dir")]
    pub asset_dir: String,
    /// Words masked in chat (`cartopolis_core::moderation`).
    ///
    /// Defaults to the built-in seed list. An operator replaces it wholesale —
    /// there is no "add to the defaults" mode, because the words a community
    /// needs blocked are not a superset of anyone else's and a half-inherited
    /// list is impossible to reason about.
    #[serde(default = "default_moderation_words")]
    pub moderation_words: Vec<String>,
    /// A file of words, one per line, `#` for a comment. Read at startup into
    /// [`SimConfig::moderation_words`], replacing whatever was there.
    ///
    /// A path rather than a long TOML array because this is the one setting an
    /// operator edits under pressure, mid-incident, and a text file is what a
    /// text editor and `>>` are good at.
    #[serde(default)]
    pub moderation_words_file: Option<String>,
    /// Whether strangers may create their own accounts (`POST /api/register`).
    ///
    /// On by default, and only reachable at all when `http_listen` is set — the
    /// listener is the opt-in, and a server that has published an HTTP surface
    /// for the web client has already decided to have players it did not create
    /// by hand. An operator running a private world turns this off and keeps
    /// `--create-admin` plus the admin API.
    #[serde(default = "default_registration_open")]
    pub registration_open: bool,
    /// SMTP relay for the verification mail, e.g.
    /// `smtps://user:pass@smtp.example.com:465`. Unset means the mailer logs each
    /// message instead of sending it (`mail`'s module note) — which is the dev
    /// loop, and is loudly wrong in production.
    #[serde(default)]
    pub smtp_url: Option<String>,
    /// Envelope sender for that mail. Most relays refuse to send as anything but
    /// an address they have been told belongs to you.
    #[serde(default = "default_mail_from")]
    pub mail_from: String,
    /// Display name beside it.
    #[serde(default = "default_mail_from_name")]
    pub mail_from_name: String,
    /// Public origin of the web app, which verification links are built against
    /// — e.g. `https://cartopolis.org`. Never taken from the request's `Host`
    /// header; see [`crate::mail::MailConfig::public_base_url`].
    #[serde(default = "default_public_base_url")]
    pub public_base_url: String,
    /// Whether communities' public posts go out to the fediverse
    /// (`docs/notes/fediverse.md`). On by default, and only in effect when
    /// `public_base_url` is a public `https` origin: a development sim on
    /// `localhost` keeps its posts to itself whatever this says, since nobody
    /// elsewhere could fetch them.
    #[serde(default = "default_fediverse")]
    pub fediverse: bool,
    /// Tests only: federate over plain `http` and with private addresses,
    /// which is how two simulators on one machine reach each other. It turns
    /// off the guard that keeps strangers' URLs off this machine's private
    /// network, so it must never be set in a deployment.
    #[serde(default)]
    pub fediverse_allow_private: bool,
    /// Tests only: where Discord, Reddit and GitHub are, so a stand-in for
    /// them on this machine can answer a sign-in (`signin::providers`). Only
    /// reachable with `fediverse_allow_private`, whose guard it relies on.
    #[serde(default)]
    pub signin_test_base: Option<String>,
    /// Tests only: where another server's HTTP surface is, by its name, for
    /// servers on this machine whose names cannot carry their ports
    /// (`crate::remote`). Only read with `fediverse_allow_private`; everywhere
    /// else a server `x` is at `https://x`.
    #[serde(default)]
    pub peer_test_bases: std::collections::HashMap<String, String>,
    /// Shared block lists of servers nobody here hears from or sends to
    /// (`fediverse::blocklist`), re-read daily: Mastodon's CSV or one server per
    /// line. The operator's own blocks are kept apart and survive every import.
    #[serde(default = "default_fediverse_blocklists")]
    pub fediverse_blocklists: Vec<String>,
    /// The languages content pages are written and served in
    /// (`docs/mockups/cms`), the first the default: each is an address prefix
    /// (`/nl/over`), so a code here is a path the web UI no longer routes.
    #[serde(default = "default_page_languages")]
    pub page_languages: Vec<String>,
    /// Whether an account may claim a building (`buildings`). The name is from
    /// when it was one house per account, kept so a deployment's setting holds.
    #[serde(default = "default_house_claims_open")]
    pub house_claims_open: bool,
    /// The one municipality whose addresses may be claimed.
    ///
    /// Groningen because that is where the world is: the client's 3DBAG cells,
    /// the seeded region and every fixture are there, and an address claimed in
    /// Maastricht would be a row in a table with nothing on the map behind it.
    /// A single name rather than a list, because widening it is a decision about
    /// map coverage and should be made once the coverage exists.
    #[serde(default = "default_claim_municipality")]
    pub claim_municipality: String,
    /// How many buildings one account may own (`buildings`). A fairness
    /// setting, not a security one: it keeps one account from claiming a street.
    #[serde(default = "default_max_buildings_per_account")]
    pub max_buildings_per_account: usize,
    /// Fetch DB-IP's country table monthly for the web visitors' Countries
    /// (`stats::countries`). Off by default, so a test or a dev server never
    /// reaches the network; a table already beside the database is used either
    /// way.
    #[serde(default)]
    pub geoip_download: bool,
    /// Where Caddy streams its APK download lines (`stats::apk`), e.g. the
    /// docker gateway `172.17.0.1:4750`. `None`: APK downloads are not counted.
    #[serde(default)]
    pub apk_log_listen: Option<String>,
    /// How often, in milliseconds, a connection signed in with an access token
    /// checks the token still exists (`net::handle_connection`): revoking one
    /// ends its open connection within this. Tests shorten it.
    #[serde(default = "default_token_check_ms")]
    pub token_check_ms: u64,
}

fn default_token_check_ms() -> u64 {
    5_000
}

fn default_max_buildings_per_account() -> usize {
    10
}

fn default_house_claims_open() -> bool {
    true
}

fn default_claim_municipality() -> String {
    "Groningen".into()
}

fn default_registration_open() -> bool {
    true
}

fn default_mail_from() -> String {
    crate::mail::MailConfig::default().from
}

fn default_mail_from_name() -> String {
    crate::mail::MailConfig::default().from_name
}

fn default_public_base_url() -> String {
    crate::mail::MailConfig::default().public_base_url
}

fn default_fediverse() -> bool {
    true
}

fn default_fediverse_blocklists() -> Vec<String> {
    vec![crate::fediverse::blocklist::DEFAULT_LIST.to_string()]
}

fn default_page_languages() -> Vec<String> {
    vec!["nl".into(), "en".into()]
}

fn default_listen() -> String {
    "127.0.0.1:4747".into()
}

fn default_db() -> String {
    "data/world.db".into()
}

fn default_tick_hz() -> f32 {
    20.0
}

fn default_max_prims() -> u32 {
    1_000
}

fn default_max_scripts() -> u32 {
    200
}

fn default_script_bun() -> String {
    "bun".into()
}

fn default_script_tick_timeout_ms() -> u64 {
    1000
}

fn default_script_memory_limit_mib() -> u64 {
    1024
}

fn default_osm_tile_url_template() -> String {
    cartopolis_core::world::DEFAULT_TILE_URL_TEMPLATE.into()
}

fn default_geocoder_url() -> String {
    cartopolis_core::services::DEFAULT_GEOCODER_URL.into()
}

fn default_osm_query_url() -> String {
    cartopolis_core::services::DEFAULT_OSM_QUERY_URL.into()
}

fn default_map_data_url() -> String {
    cartopolis_core::services::DEFAULT_MAP_DATA_URL.into()
}

fn default_terrain_url() -> String {
    cartopolis_core::services::DEFAULT_TERRAIN_URL.into()
}

fn default_height_url() -> String {
    cartopolis_core::services::DEFAULT_HEIGHT_URL.into()
}

fn default_texture_dir() -> String {
    "data/textures".into()
}

fn default_asset_dir() -> String {
    "data/assets".into()
}

fn default_moderation_words() -> Vec<String> {
    cartopolis_core::moderation::DEFAULT_WORDS
        .iter()
        .map(|s| (*s).to_string())
        .collect()
}

impl Default for SimConfig {
    fn default() -> Self {
        Self {
            listen: default_listen(),
            http_listen: None,
            calls_listen: None,
            calls_public_addr: None,
            database_path: default_db(),
            tick_hz: default_tick_hz(),
            max_prims: default_max_prims(),
            max_scripts: default_max_scripts(),
            script_host: None,
            script_host_dir: None,
            script_bun: default_script_bun(),
            script_tick_timeout_ms: default_script_tick_timeout_ms(),
            script_memory_limit_mib: default_script_memory_limit_mib(),
            osm_tile_url_template: default_osm_tile_url_template(),
            api_base_url: String::new(),
            atlas_url: None,
            plans_url: None,
            web_root: None,
            map_data_dir: None,
            geocoder_url: default_geocoder_url(),
            osm_query_url: default_osm_query_url(),
            map_data_url: default_map_data_url(),
            terrain_url: default_terrain_url(),
            height_url: default_height_url(),
            texture_dir: default_texture_dir(),
            asset_dir: default_asset_dir(),
            moderation_words: default_moderation_words(),
            moderation_words_file: None,
            registration_open: default_registration_open(),
            smtp_url: None,
            mail_from: default_mail_from(),
            mail_from_name: default_mail_from_name(),
            public_base_url: default_public_base_url(),
            fediverse: default_fediverse(),
            fediverse_allow_private: false,
            signin_test_base: None,
            peer_test_bases: std::collections::HashMap::new(),
            fediverse_blocklists: default_fediverse_blocklists(),
            page_languages: default_page_languages(),
            house_claims_open: default_house_claims_open(),
            claim_municipality: default_claim_municipality(),
            max_buildings_per_account: default_max_buildings_per_account(),
            geoip_download: false,
            apk_log_listen: None,
            token_check_ms: default_token_check_ms(),
        }
    }
}

impl SimConfig {
    /// The two ceilings `SimWorld` enforces, in the shape it holds them.
    #[must_use]
    /// The script process to run, first match wins: `script_host`;
    /// `script_host_dir` under `script_bun`; `cartopolis-script-host` beside
    /// the running binary (`beside`, `None` when it cannot be told); this
    /// checkout's `tools/script-host`. An installed server finds the third, a
    /// `cargo run` the fourth.
    pub fn script_host(&self, beside: Option<&Path>) -> crate::scripting::BunEngine {
        use crate::scripting::{BunEngine, COMPILED_HOST};
        let engine = if let Some(exe) = &self.script_host {
            BunEngine::compiled(exe.into())
        } else if let Some(dir) = &self.script_host_dir {
            BunEngine::source(self.script_bun.clone().into(), dir.into())
        } else if let Some(exe) = beside
            .map(|dir| dir.join(COMPILED_HOST))
            .filter(|exe| exe.is_file())
        {
            BunEngine::compiled(exe)
        } else {
            BunEngine {
                program: self.script_bun.clone().into(),
                ..BunEngine::development()
            }
        };
        BunEngine {
            tick_timeout: std::time::Duration::from_millis(self.script_tick_timeout_ms),
            memory_limit_bytes: self.script_memory_limit_mib << 20,
            ..engine
        }
    }

    pub fn world_caps(&self) -> crate::state::WorldCaps {
        crate::state::WorldCaps {
            max_prims: self.max_prims,
            max_scripts: self.max_scripts,
        }
    }

    /// `cartopolis.toml` (optional) + env `CARTO_*` (e.g. `CARTO_listen`, `CARTO_database_path`).
    pub fn load() -> anyhow::Result<Self> {
        Self::load_from(Path::new("cartopolis.toml"))
    }

    /// [`Self::load`] from a named file, which may hold other sections too
    /// (`cartopolis-server` keeps `[atlas]` in it): keys this struct does not
    /// have are ignored.
    pub fn load_from(file: &Path) -> anyhow::Result<Self> {
        let mut figment = Figment::new().merge(Serialized::defaults(SimConfig::default()));
        if file.exists() {
            figment = figment.merge(Toml::file(file));
        }
        figment = figment.merge(Env::prefixed("CARTO_"));
        let mut config: Self = figment.extract()?;
        config.load_moderation_words()?;
        Ok(config)
    }

    /// Resolve [`SimConfig::moderation_words_file`] into the in-memory list.
    ///
    /// A missing or unreadable file is an **error**, not a fallback to the seed
    /// list. Silently running with different filtering than the operator
    /// configured is the failure this whole surface exists to avoid, and it would
    /// only be noticed by whoever it failed to protect.
    pub fn load_moderation_words(&mut self) -> anyhow::Result<()> {
        let Some(ref path) = self.moderation_words_file else {
            return Ok(());
        };
        let text = std::fs::read_to_string(path)
            .with_context(|| format!("read moderation_words_file {path}"))?;
        self.moderation_words = text.lines().map(str::to_string).collect();
        Ok(())
    }

    /// The mail settings, gathered into the shape `mail::Mailer` takes.
    ///
    /// Flat on `SimConfig` rather than a `[mail]` table because every one of
    /// these is set from the environment on the deployed sim (`CARTO_SMTP_URL`,
    /// `CARTO_MAIL_FROM`, …), and figment's env provider addresses a nested table
    /// through a separator nobody would guess from reading this file.
    #[must_use]
    pub fn mail(&self) -> crate::mail::MailConfig {
        crate::mail::MailConfig {
            smtp_url: self.smtp_url.clone(),
            from: self.mail_from.clone(),
            from_name: self.mail_from_name.clone(),
            public_base_url: self.public_base_url.clone(),
        }
    }

    /// The geo services, in the shape `GET /api/services` answers.
    #[must_use]
    pub fn services(&self) -> cartopolis_core::services::ServiceDirectory {
        cartopolis_core::services::ServiceDirectory {
            geocoder: self.geocoder_url.clone(),
            osm_query: self.osm_query_url.clone(),
            map_data: self.map_data_url.clone(),
            terrain: self.terrain_url.clone(),
            height: self.height_url.clone(),
        }
    }

    /// This server's name: the host of `public_base_url`, lower-cased, without
    /// scheme or port (`cartopolis.org`; `localhost` for a development sim).
    ///
    /// It is what makes a username a full address (`name@server_name`) and
    /// what every chat created here begins its id with
    /// (`cartopolis_core::address`, protocol 37). Taken from the public URL
    /// because that is the one name of this server the operator already states
    /// for the outside world; it should not change once chats exist, since it
    /// is written into every device's credential.
    #[must_use]
    pub fn server_name(&self) -> String {
        let url = self.public_base_url.trim();
        let rest = url.split_once("://").map_or(url, |(_, r)| r);
        let host = rest.split(['/', '?', '#']).next().unwrap_or_default();
        let host = host.rsplit_once('@').map_or(host, |(_, h)| h);
        // Drops a port. An IPv6 literal is not a name anybody's address should
        // carry, and falls through to `localhost` below.
        let host = host.split(':').next().unwrap_or_default().to_lowercase();
        if cartopolis_core::address::is_server_name(&host) {
            host
        } else {
            "localhost".into()
        }
    }

    /// What to tell a client about where this server's HTTP surface is
    /// (`ServerHelloAck::api_base_url`).
    ///
    /// The configured value wins. When nothing was configured — the default — a
    /// **loopback** HTTP listener is answered with its own address, and anything
    /// else is left to the client to derive from the address it connected to.
    ///
    /// The asymmetry is the whole point. A deployment binds the listener to a
    /// private address behind a reverse proxy (`172.17.0.1:4748` on the hosted
    /// sim), which no client can reach and which the client must therefore *not*
    /// be told; it reaches the wire and the API on one public hostname and
    /// derives that itself. A development sim binds loopback, and there the
    /// client cannot derive anything at all — `model_assets::derive_api_base`
    /// answers `None` for a loopback address, deliberately, because the HTTP port
    /// is a separate `--http-listen` that nothing in the game port implies. So
    /// the documented dev loop (`cargo run -p cartopolis_simulator`, sign in to
    /// `127.0.0.1:4747`) had no model store at all: uploading, the inventory and
    /// the library were all inert, and the panel said "sign in to a server" to
    /// somebody who was signed in.
    #[must_use]
    pub fn resolved_api_base_url(&self) -> String {
        if !self.api_base_url.is_empty() {
            return self.api_base_url.clone();
        }
        match self.http_listen.as_deref() {
            Some(addr) if is_loopback_bind(addr) => format!("http://{addr}"),
            _ => String::new(),
        }
    }

    /// The compiled chat filter. Built per caller — it is a few dozen short
    /// strings, and a connection builds one once.
    #[must_use]
    pub fn moderation_filter(&self) -> cartopolis_core::moderation::Filter {
        cartopolis_core::moderation::Filter::from_words(
            self.moderation_words.iter().map(String::as_str),
        )
    }

    /// CLI flags override file/env (ADR-014).
    pub fn apply_cli(&mut self, cli: &super::cli::SimCli) {
        if let Some(ref v) = cli.listen {
            self.listen.clone_from(v);
        }
        if let Some(ref v) = cli.http_listen {
            self.http_listen = Some(v.clone());
        }
        if let Some(ref v) = cli.calls_listen {
            self.calls_listen = Some(v.clone());
        }
        if let Some(ref v) = cli.calls_public_addr {
            self.calls_public_addr = Some(v.clone());
        }
        if let Some(ref v) = cli.database_path {
            self.database_path.clone_from(v);
        }
        if let Some(v) = cli.tick_hz {
            self.tick_hz = v;
        }
        if let Some(v) = cli.max_prims {
            self.max_prims = v;
        }
        if let Some(v) = cli.max_scripts {
            self.max_scripts = v;
        }
        if let Some(ref v) = cli.osm_tile_url_template {
            self.osm_tile_url_template.clone_from(v);
        }
        if let Some(ref v) = cli.texture_dir {
            self.texture_dir.clone_from(v);
        }
    }
}

/// Whether a `host:port` bind is one only this machine can reach.
///
/// A string test rather than a `SocketAddr` parse plus `is_loopback`, because
/// `localhost:4748` is a perfectly ordinary thing to write in a config file and
/// does not parse as a `SocketAddr` at all.
fn is_loopback_bind(addr: &str) -> bool {
    let host = match addr.rsplit_once(':') {
        Some((h, _)) => h,
        None => addr,
    };
    let host = host.trim().trim_start_matches('[').trim_end_matches(']');
    host == "localhost" || host == "::1" || host.starts_with("127.")
}

#[cfg(test)]
mod tests {
    use super::*;

    /// An installed server runs the compiled host it was shipped with, and a
    /// setting still wins over it; with neither, a checkout runs its source.
    #[test]
    fn the_script_host_beside_the_binary_is_found() {
        let dir = tempfile::TempDir::new().unwrap();
        let config = SimConfig::default();
        let dev = config.script_host(Some(dir.path()));
        assert_eq!(dev.program, std::path::PathBuf::from("bun"));
        assert!(
            dev.host_dir.is_some(),
            "no compiled host: this checkout's source"
        );

        let exe = dir.path().join(crate::scripting::COMPILED_HOST);
        std::fs::write(&exe, "").unwrap();
        let shipped = config.script_host(Some(dir.path()));
        assert_eq!(shipped.program, exe);
        assert_eq!(shipped.host_dir, None);

        let chosen = SimConfig {
            script_host_dir: Some("/srv/script-host".into()),
            script_bun: "/opt/bun".into(),
            script_tick_timeout_ms: 250,
            ..SimConfig::default()
        }
        .script_host(Some(dir.path()));
        assert_eq!(chosen.program, std::path::PathBuf::from("/opt/bun"));
        assert_eq!(chosen.host_dir, Some("/srv/script-host".into()));
        assert_eq!(chosen.tick_timeout.as_millis(), 250);
    }

    /// A development sim binds loopback and is told to say so: the client cannot
    /// work the HTTP port out from the game port, so without this there is no
    /// model store on the documented dev loop.
    #[test]
    fn a_loopback_listener_answers_its_own_address() {
        let config = SimConfig {
            http_listen: Some("127.0.0.1:4748".into()),
            ..SimConfig::default()
        };
        assert_eq!(config.resolved_api_base_url(), "http://127.0.0.1:4748");
    }

    /// The hosted sim binds the docker gateway and sits behind Caddy. That
    /// address is reachable from nothing the client runs on, so the server says
    /// nothing and the client derives the public hostname it connected to.
    #[test]
    fn a_private_listener_says_nothing() {
        let config = SimConfig {
            http_listen: Some("172.17.0.1:4748".into()),
            ..SimConfig::default()
        };
        assert!(config.resolved_api_base_url().is_empty());

        let wildcard = SimConfig {
            http_listen: Some("0.0.0.0:4748".into()),
            ..SimConfig::default()
        };
        assert!(wildcard.resolved_api_base_url().is_empty());
    }

    /// The server's name is the bare host of its public URL, whatever else
    /// the URL carries: it ends up in every device's credential.
    #[test]
    fn the_server_name_is_the_public_host() {
        let named = |url: &str| {
            SimConfig {
                public_base_url: url.into(),
                ..SimConfig::default()
            }
            .server_name()
        };
        assert_eq!(named("https://Cartopolis.org"), "cartopolis.org");
        assert_eq!(named("https://cartopolis.org/admin/"), "cartopolis.org");
        assert_eq!(named("http://localhost:3100"), "localhost");
        assert_eq!(named("not a url"), "localhost");
    }

    /// Configured wins over derived, in both directions — including an operator
    /// who binds loopback and puts a proxy in front of it.
    #[test]
    fn a_configured_base_wins() {
        let config = SimConfig {
            http_listen: Some("127.0.0.1:4748".into()),
            api_base_url: "https://sim.example.org".into(),
            ..SimConfig::default()
        };
        assert_eq!(config.resolved_api_base_url(), "https://sim.example.org");
    }

    /// No listener at all is no API, whatever the address looks like.
    #[test]
    fn no_listener_is_no_api() {
        assert!(SimConfig::default().resolved_api_base_url().is_empty());
    }

    #[test]
    fn loopback_spellings() {
        assert!(is_loopback_bind("127.0.0.1:4748"));
        assert!(is_loopback_bind("localhost:4748"));
        assert!(is_loopback_bind("[::1]:4748"));
        assert!(!is_loopback_bind("172.17.0.1:4748"));
        assert!(!is_loopback_bind("0.0.0.0:4748"));
    }
}