Skip to main content

huddle_core/network/
server.rs

1//! Client connector to the centralized `huddle-server`.
2//!
3//! huddle's primary transport is libp2p (mDNS on the LAN, gossipsub
4//! across direct/relayed connections). This module adds a *second* path:
5//! a WebSocket to a single canonical server that the operator hosts. The
6//! server is reachable only as a **Tor v3 onion**, so `.onion` URLs are
7//! dialed through Tor's local SOCKS5 proxy; plain `ws://host:port` URLs
8//! (used in tests) are dialed directly.
9//!
10//! The server is a dumb ciphertext mover: we hand it the same opaque
11//! huddle wire bytes we would have published on a gossipsub topic,
12//! tagged with the cleartext `room` id, base64-encoded. It fans them out
13//! to the room's other members and queues them for offline ones. All
14//! encryption/authentication stays in the layers above — this module
15//! never inspects the payload.
16
17use std::sync::Arc;
18
19use base64::engine::general_purpose::STANDARD as B64;
20use base64::Engine;
21use futures::{SinkExt, StreamExt};
22use serde::{Deserialize, Serialize};
23use tokio::sync::mpsc;
24use tokio_tungstenite::tungstenite::Message as WsMessage;
25use tokio_tungstenite::WebSocketStream;
26use tracing::warn;
27
28use crate::error::{HuddleError, Result};
29use crate::identity::{relay_auth_msg, Identity};
30
31/// Messages we send to the server. Mirrors `huddle-server`'s `ClientMsg`.
32#[derive(Debug, Serialize)]
33#[serde(tag = "type", rename_all = "snake_case")]
34enum ClientMsg {
35    /// huddle 1.1.4: `Hello` now authenticates. It carries our Ed25519
36    /// pubkey and a signature over `relay_auth_msg(nonce)` for the nonce the
37    /// server sent in its opening `Challenge`. The relay verifies the
38    /// signature and that the pubkey hashes to `fingerprint` before it lets
39    /// us touch any mailbox.
40    Hello {
41        fingerprint: String,
42        pubkey_b64: String,
43        signature_b64: String,
44        rooms: Vec<String>,
45    },
46    Subscribe { room: String },
47    Unsubscribe { room: String },
48    Publish { room: String, id: String, payload_b64: String },
49    Fetch,
50    Ping,
51}
52
53/// Messages the server sends back. Mirrors `huddle-server`'s `ServerMsg`.
54#[derive(Debug, Deserialize)]
55#[serde(tag = "type", rename_all = "snake_case")]
56enum ServerMsg {
57    /// huddle 1.1.4: the relay opens the connection with a random challenge
58    /// nonce. We sign it and answer with an authenticated `Hello`.
59    Challenge { nonce_b64: String },
60    // The server echoes our fingerprint on `ready`, but we already know
61    // our own identity, so we keep only the tag and let serde ignore the
62    // extra field.
63    Ready,
64    Message { room: String, id: String, payload_b64: String },
65    Sent { id: String, delivered: usize, queued: usize },
66    Pong,
67    Error { message: String },
68}
69
70/// What the connector surfaces to the rest of huddle-core. The caller
71/// drives these into the same path that handles a received gossipsub
72/// message (decode → decrypt → `AppEvent`).
73#[derive(Debug, Clone)]
74pub enum ServerEvent {
75    /// Handshake complete; the mailbox (if any) will follow as `Message`s.
76    Ready,
77    /// Delivery receipt for one of our `publish` calls: how many of the
78    /// room's other members received it live vs. were queued because they
79    /// were offline. Lets the UI mark a message delivered/pending.
80    Sent { id: String, delivered: usize, queued: usize },
81    /// A room message delivered (live or from the offline mailbox).
82    Message { room: String, id: String, payload: Vec<u8> },
83    /// The socket closed; the caller may choose to reconnect.
84    Disconnected,
85}
86
87/// A live connection to the server. Cloneable handle; cloning shares the
88/// same underlying socket.
89#[derive(Clone)]
90pub struct ServerClient {
91    out_tx: mpsc::UnboundedSender<ClientMsg>,
92}
93
94impl ServerClient {
95    /// Open a connection, send the initial `hello`, and return the client
96    /// plus a stream of [`ServerEvent`]s.
97    ///
98    /// - `url`: `ws://<onion>:80/ws` (onion), `wss://relay/ws` (clearnet TLS),
99    ///   or `ws://host:port/ws` (clearnet plain / tests).
100    /// - `dial`: how to physically reach it — one of the transport "doors"
101    ///   (`Socks5` for onion via Tor, `Tls` for `wss://`, `Direct` for `ws://`).
102    /// - `identity`: our identity, used to answer the relay's auth `Challenge`
103    ///   (huddle 1.1.4). The connector signs the challenge nonce and sends the
104    ///   pubkey + signature in `Hello`; the relay rejects us otherwise.
105    pub async fn connect(
106        url: &str,
107        dial: &crate::network::transport::DialMode,
108        identity: Arc<Identity>,
109        rooms: Vec<String>,
110    ) -> Result<(Self, mpsc::UnboundedReceiver<ServerEvent>)> {
111        use crate::network::transport::DialMode;
112        match dial {
113            DialMode::Socks5 { proxy } => {
114                let proxy: std::net::SocketAddr = proxy
115                    .parse()
116                    .map_err(|e| HuddleError::Network(format!("bad socks address: {e}")))?;
117                let target = host_port_from_ws_url(url)?;
118                let stream = tokio_socks::tcp::Socks5Stream::connect(proxy, target.as_str())
119                    .await
120                    .map_err(|e| HuddleError::Network(format!("tor socks connect: {e}")))?;
121                let (ws, _resp) = tokio_tungstenite::client_async(url, stream)
122                    .await
123                    .map_err(|e| HuddleError::Network(format!("ws handshake: {e}")))?;
124                Ok(Self::spawn(ws, identity, rooms))
125            }
126            // Plain `ws://` and `wss://` with the system trust store both go
127            // through `connect_async`, which negotiates TLS from the URL
128            // scheme (tokio-tungstenite's rustls-tls-native-roots feature).
129            DialMode::Direct | DialMode::Tls { pinned_cert_der: None } => {
130                let (ws, _resp) = tokio_tungstenite::connect_async(url)
131                    .await
132                    .map_err(|e| HuddleError::Network(format!("ws connect: {e}")))?;
133                Ok(Self::spawn(ws, identity, rooms))
134            }
135            // Self-signed cert pinning is structured but not wired in this
136            // build — the recommended clearnet-TLS path uses a real cert
137            // (Caddy / Let's Encrypt / Cloudflare), which the arm above
138            // handles. Onion doors remain available for stronger privacy.
139            DialMode::Tls {
140                pinned_cert_der: Some(_),
141            } => Err(HuddleError::Network(
142                "pinned-certificate wss is not supported in this build — use a real cert (Caddy/Let's Encrypt) or an onion door".into(),
143            )),
144            // huddle 1.0: in-process Tor via Arti. Bootstraps (once) an
145            // embedded Tor client and opens the stream to the onion through
146            // it, then speaks WebSocket over that stream — `spawn` is reused.
147            #[cfg(feature = "arti")]
148            DialMode::Arti { bridge } => {
149                let client =
150                    crate::network::transport::arti_client(bridge.as_deref()).await?;
151                let hp = host_port_from_ws_url(url)?;
152                let (host, port_s) = hp.rsplit_once(':').ok_or_else(|| {
153                    HuddleError::Network(format!("bad host:port from {url}"))
154                })?;
155                let port: u16 = port_s
156                    .parse()
157                    .map_err(|_| HuddleError::Network(format!("bad port in {url}")))?;
158                let stream = client
159                    .connect((host, port))
160                    .await
161                    .map_err(|e| HuddleError::Network(format!("arti connect: {e}")))?;
162                let (ws, _resp) = tokio_tungstenite::client_async(url, stream)
163                    .await
164                    .map_err(|e| HuddleError::Network(format!("ws handshake: {e}")))?;
165                Ok(Self::spawn(ws, identity, rooms))
166            }
167        }
168    }
169
170    /// Spawn the read/write pumps for an established socket. Generic over
171    /// the inner stream so the Tor-SOCKS and direct paths (different
172    /// stream types) share one implementation.
173    fn spawn<S>(
174        ws: WebSocketStream<S>,
175        identity: Arc<Identity>,
176        rooms: Vec<String>,
177    ) -> (Self, mpsc::UnboundedReceiver<ServerEvent>)
178    where
179        S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin + Send + 'static,
180    {
181        let (mut sink, mut stream) = ws.split();
182        let (out_tx, mut out_rx) = mpsc::unbounded_channel::<ClientMsg>();
183        let (ev_tx, ev_rx) = mpsc::unbounded_channel::<ServerEvent>();
184
185        // huddle 1.1.4: we do NOT send `Hello` up front anymore. The relay
186        // opens with a `Challenge`; the reader pump (below) signs that nonce
187        // and queues the authenticated `Hello`. Because the relay rejects
188        // anything sent before a valid `Hello`, the writer pump holds back
189        // any other outgoing frame (a publish/subscribe the app issues during
190        // the handshake window) until the `Hello` has actually gone out.
191        tokio::spawn(async move {
192            let mut hello_sent = false;
193            let mut pending: Vec<ClientMsg> = Vec::new();
194            while let Some(msg) = out_rx.recv().await {
195                let is_hello = matches!(msg, ClientMsg::Hello { .. });
196                if !hello_sent && !is_hello {
197                    pending.push(msg);
198                    continue;
199                }
200                let json = match serde_json::to_string(&msg) {
201                    Ok(j) => j,
202                    Err(_) => continue,
203                };
204                if sink.send(WsMessage::Text(json.into())).await.is_err() {
205                    return;
206                }
207                if is_hello {
208                    hello_sent = true;
209                    // Flush anything the app queued while we waited for the
210                    // challenge, preserving its order after the Hello.
211                    for m in pending.drain(..) {
212                        let json = match serde_json::to_string(&m) {
213                            Ok(j) => j,
214                            Err(_) => continue,
215                        };
216                        if sink.send(WsMessage::Text(json.into())).await.is_err() {
217                            return;
218                        }
219                    }
220                }
221            }
222            // When `out_rx` ends (every `ServerClient` handle dropped) close
223            // the socket so the server marks us offline and starts mailboxing.
224            let _ = sink.close().await;
225        });
226
227        // Reader pump: parse server messages into ServerEvents. On the opening
228        // `Challenge`, prove our identity by signing the nonce and sending the
229        // authenticated `Hello` through the writer.
230        // Held only long enough to send the one `Hello` in response to the
231        // challenge, then dropped. Crucially it must NOT outlive that: if the
232        // reader kept a permanent `out_tx` clone, dropping every public
233        // `ServerClient` handle would no longer end the writer's `out_rx`, the
234        // socket would never close, and the server would never mark us offline
235        // (breaking offline mailboxing). `Option::take()` releases it after use.
236        let mut hello_tx = Some(out_tx.clone());
237        tokio::spawn(async move {
238            while let Some(frame) = stream.next().await {
239                let frame = match frame {
240                    Ok(f) => f,
241                    Err(_) => break,
242                };
243                let text = match frame {
244                    WsMessage::Text(t) => t.as_str().to_string(),
245                    WsMessage::Binary(b) => String::from_utf8_lossy(&b).into_owned(),
246                    WsMessage::Close(_) => break,
247                    _ => continue,
248                };
249                match serde_json::from_str::<ServerMsg>(&text) {
250                    Ok(ServerMsg::Challenge { nonce_b64 }) => {
251                        if let Some(tx) = hello_tx.take() {
252                            match B64.decode(nonce_b64.as_bytes()) {
253                                Ok(nonce) => {
254                                    let sig = identity.sign(&relay_auth_msg(&nonce));
255                                    let hello = ClientMsg::Hello {
256                                        fingerprint: identity.fingerprint().to_string(),
257                                        pubkey_b64: B64.encode(identity.public_bytes()),
258                                        signature_b64: B64.encode(sig),
259                                        rooms: rooms.clone(),
260                                    };
261                                    // If the writer is gone the connection is dead anyway.
262                                    let _ = tx.send(hello);
263                                }
264                                Err(e) => {
265                                    warn!(error = %e, "relay sent an undecodable challenge nonce");
266                                    break;
267                                }
268                            }
269                        }
270                        // `tx` dropped here — the reader no longer pins the
271                        // outgoing channel open.
272                    }
273                    Ok(ServerMsg::Ready) => {
274                        let _ = ev_tx.send(ServerEvent::Ready);
275                    }
276                    Ok(ServerMsg::Sent { id, delivered, queued }) => {
277                        let _ = ev_tx.send(ServerEvent::Sent { id, delivered, queued });
278                    }
279                    Ok(ServerMsg::Message { room, id, payload_b64 }) => {
280                        match B64.decode(payload_b64.as_bytes()) {
281                            Ok(payload) => {
282                                let _ = ev_tx.send(ServerEvent::Message { room, id, payload });
283                            }
284                            Err(e) => warn!(error = %e, "server sent undecodable payload"),
285                        }
286                    }
287                    Ok(ServerMsg::Error { message }) => warn!(%message, "huddle-server error"),
288                    Ok(ServerMsg::Pong) => {}
289                    Err(e) => warn!(error = %e, "unparseable server message"),
290                }
291            }
292            let _ = ev_tx.send(ServerEvent::Disconnected);
293        });
294
295        (Self { out_tx }, ev_rx)
296    }
297
298    /// Send a room's opaque wire bytes to the server for fan-out.
299    pub fn publish(&self, room: &str, id: &str, payload: &[u8]) -> Result<()> {
300        self.send(ClientMsg::Publish {
301            room: room.to_string(),
302            id: id.to_string(),
303            payload_b64: B64.encode(payload),
304        })
305    }
306
307    /// Assert membership of a room so the server mailboxes us when offline.
308    pub fn subscribe(&self, room: &str) -> Result<()> {
309        self.send(ClientMsg::Subscribe { room: room.to_string() })
310    }
311
312    pub fn unsubscribe(&self, room: &str) -> Result<()> {
313        self.send(ClientMsg::Unsubscribe { room: room.to_string() })
314    }
315
316    /// Ask the server to re-drain our mailbox.
317    pub fn fetch(&self) -> Result<()> {
318        self.send(ClientMsg::Fetch)
319    }
320
321    pub fn ping(&self) -> Result<()> {
322        self.send(ClientMsg::Ping)
323    }
324
325    fn send(&self, msg: ClientMsg) -> Result<()> {
326        self.out_tx
327            .send(msg)
328            .map_err(|_| HuddleError::Network("server connection closed".to_string()))
329    }
330}
331
332/// Extract `host:port` from a `ws://`/`wss://` URL for the SOCKS target.
333/// Defaults to port 80 for `ws://` (matches the onion's `HiddenServicePort
334/// 80`) and 443 for `wss://` when no explicit port is given.
335fn host_port_from_ws_url(url: &str) -> Result<String> {
336    let (rest, default_port) = if let Some(r) = url.strip_prefix("wss://") {
337        (r, 443)
338    } else if let Some(r) = url.strip_prefix("ws://") {
339        (r, 80)
340    } else {
341        return Err(HuddleError::Network(format!("expected ws:// url, got {url}")));
342    };
343    let authority = rest.split('/').next().unwrap_or(rest);
344    if authority.is_empty() {
345        return Err(HuddleError::Network(format!("no host in url: {url}")));
346    }
347    if authority.contains(':') {
348        Ok(authority.to_string())
349    } else {
350        Ok(format!("{authority}:{default_port}"))
351    }
352}
353
354#[cfg(test)]
355mod tests {
356    use super::host_port_from_ws_url;
357
358    #[test]
359    fn parses_host_port() {
360        assert_eq!(host_port_from_ws_url("ws://abc.onion/ws").unwrap(), "abc.onion:80");
361        assert_eq!(
362            host_port_from_ws_url("ws://127.0.0.1:8787/ws").unwrap(),
363            "127.0.0.1:8787"
364        );
365        assert_eq!(host_port_from_ws_url("wss://h:443").unwrap(), "h:443");
366        // huddle 1.0: bare wss:// defaults to 443, not 80.
367        assert_eq!(host_port_from_ws_url("wss://relay.example/ws").unwrap(), "relay.example:443");
368        assert!(host_port_from_ws_url("http://x").is_err());
369    }
370}