Skip to main content

manabrew_server/
config.rs

1const DEFAULT_CAPTURE_MAX_GB: u64 = 20;
2/// Fixed rather than ephemeral: a client that learns it from config rather
3/// than from mDNS needs it to survive a restart.
4const DEFAULT_ART_PORT: u16 = 9528;
5
6const BYTES_PER_GB: u64 = 1024 * 1024 * 1024;
7
8pub use crate::protocol::IceServer as TransportIceServer;
9
10/// Reads `MANABREW_ICE_SERVERS`: a url list, or a JSON array of `RTCIceServer`.
11pub fn parse_ice_servers(raw: &str) -> Vec<TransportIceServer> {
12    let raw = raw.trim();
13    if raw.is_empty() {
14        return Vec::new();
15    }
16    if raw.starts_with('[') {
17        return match serde_json::from_str::<Vec<TransportIceServer>>(raw) {
18            Ok(servers) => servers.into_iter().filter(|s| !s.urls.is_empty()).collect(),
19            Err(error) => {
20                tracing::error!(%error, "MANABREW_ICE_SERVERS is not valid JSON; ignoring it");
21                Vec::new()
22            }
23        };
24    }
25    let urls: Vec<String> = raw
26        .split([',', ' ', '\t', '\n'])
27        .map(str::trim)
28        .filter(|url| !url.is_empty())
29        .map(str::to_string)
30        .collect();
31    if urls.is_empty() {
32        Vec::new()
33    } else {
34        vec![TransportIceServer {
35            urls,
36            username: None,
37            credential: None,
38        }]
39    }
40}
41
42pub struct ServerConfig {
43    pub host: String,
44    pub port: u16,
45    pub health_port: u16,
46    pub max_rooms: usize,
47    pub server_key: String,
48    pub official_key: Option<String>,
49    pub events_dir: Option<String>,
50    pub capture_dir: Option<String>,
51    pub capture_max_gb: u64,
52    pub deck_hub_enabled: bool,
53    pub hub_deck_plays_url: Option<String>,
54    pub hub_deck_plays_token: Option<String>,
55    pub hub_jwks_url: Option<String>,
56    /// Opt-in. Off, the relay never sends a roster.
57    pub direct_transport: bool,
58    /// ICE servers handed to the browser plane. See [`parse_ice_servers`].
59    pub ice_servers: Vec<TransportIceServer>,
60    /// Where this relay keeps card art. Set it and the relay serves
61    /// `/scryfall-img/` for everyone on the network, which is the point of
62    /// running one: nobody else has to hold 8GB of images.
63    pub art_dir: Option<String>,
64    pub art_port: u16,
65    /// An absolute url, for a deployment behind a proxy where the port this
66    /// binds is not the one a client reaches. On a LAN nobody sets this: the
67    /// mDNS record already carries the port and the client already knows the
68    /// host it connected to.
69    pub art_base_url: Option<String>,
70    /// Answer mDNS, so four desktops on a network find this box without anyone
71    /// typing its address.
72    pub lan_advertise: bool,
73}
74
75impl ServerConfig {
76    pub fn from_env() -> Self {
77        ServerConfig {
78            host: std::env::var("FORGE_HOST").unwrap_or_else(|_| "0.0.0.0".into()),
79            port: std::env::var("FORGE_PORT")
80                .ok()
81                .and_then(|p| p.parse().ok())
82                .unwrap_or(9443),
83            health_port: std::env::var("FORGE_HEALTH_PORT")
84                .ok()
85                .and_then(|p| p.parse().ok())
86                .unwrap_or(9444),
87            max_rooms: std::env::var("FORGE_MAX_ROOMS")
88                .ok()
89                .and_then(|r| r.parse().ok())
90                .unwrap_or(100),
91            server_key: std::env::var("MANABREW_SERVER_KEY").unwrap_or_else(|_| "forge".into()),
92            official_key: std::env::var("SECRET_MANABREW_KEY")
93                .ok()
94                .filter(|key| !key.is_empty()),
95            events_dir: std::env::var("MANABREW_EVENTS_DIR")
96                .ok()
97                .filter(|dir| !dir.is_empty()),
98            capture_dir: std::env::var("MANABREW_GAME_CAPTURE_DIR")
99                .ok()
100                .filter(|dir| !dir.is_empty()),
101            capture_max_gb: std::env::var("MANABREW_GAME_CAPTURE_MAX_GB")
102                .ok()
103                .and_then(|gb| gb.parse().ok())
104                .unwrap_or(DEFAULT_CAPTURE_MAX_GB),
105            deck_hub_enabled: std::env::var("DECK_HUB").ok().is_some_and(|value| {
106                matches!(
107                    value.to_ascii_lowercase().as_str(),
108                    "1" | "true" | "yes" | "on"
109                )
110            }),
111            hub_deck_plays_url: std::env::var("MANABREW_HUB_DECK_PLAYS_URL")
112                .ok()
113                .filter(|url| !url.is_empty()),
114            hub_deck_plays_token: std::env::var("MANABREW_HUB_DECK_PLAYS_TOKEN")
115                .ok()
116                .filter(|token| !token.is_empty()),
117            hub_jwks_url: std::env::var("MANABREW_HUB_JWKS_URL")
118                .ok()
119                .filter(|url| !url.is_empty()),
120            direct_transport: std::env::var("MANABREW_DIRECT_TRANSPORT")
121                .is_ok_and(|v| v == "1" || v.eq_ignore_ascii_case("true")),
122            ice_servers: std::env::var("MANABREW_ICE_SERVERS")
123                .ok()
124                .map(|raw| parse_ice_servers(&raw))
125                .unwrap_or_default(),
126            art_dir: std::env::var("MANABREW_ART_DIR")
127                .ok()
128                .filter(|dir| !dir.is_empty()),
129            art_port: std::env::var("MANABREW_ART_PORT")
130                .ok()
131                .and_then(|port| port.parse().ok())
132                .unwrap_or(DEFAULT_ART_PORT),
133            art_base_url: std::env::var("MANABREW_ART_BASE_URL")
134                .ok()
135                .filter(|url| !url.is_empty()),
136            lan_advertise: std::env::var("MANABREW_LAN_ADVERTISE")
137                .map(|value| {
138                    matches!(
139                        value.to_ascii_lowercase().as_str(),
140                        "1" | "true" | "yes" | "on"
141                    )
142                })
143                .unwrap_or(false),
144        }
145    }
146
147    pub fn capture_max_bytes(&self) -> u64 {
148        self.capture_max_gb.saturating_mul(BYTES_PER_GB)
149    }
150}
151
152#[cfg(test)]
153mod tests {
154    use super::*;
155
156    #[test]
157    fn a_plain_url_list_becomes_one_server() {
158        let parsed = parse_ice_servers("stun:a.example.org:19302, stun:b.example.org");
159        assert_eq!(parsed.len(), 1);
160        assert_eq!(
161            parsed[0].urls,
162            vec!["stun:a.example.org:19302", "stun:b.example.org"]
163        );
164        assert!(parsed[0].username.is_none());
165    }
166
167    #[test]
168    fn json_carries_turn_credentials() {
169        let parsed = parse_ice_servers(
170            r#"[{"urls":["turn:t.example.org"],"username":"u","credential":"p"}]"#,
171        );
172        assert_eq!(parsed.len(), 1);
173        assert_eq!(parsed[0].username.as_deref(), Some("u"));
174        assert_eq!(parsed[0].credential.as_deref(), Some("p"));
175    }
176
177    #[test]
178    fn anything_unparseable_yields_no_servers_rather_than_a_panic() {
179        assert!(parse_ice_servers("").is_empty());
180        assert!(parse_ice_servers("   ").is_empty());
181        assert!(parse_ice_servers("[not json").is_empty());
182        assert!(parse_ice_servers(r#"[{"username":"u"}]"#).is_empty());
183        assert!(parse_ice_servers(r#"[{"urls":[]}]"#).is_empty());
184    }
185}