Skip to main content

tauri_plugin_socketio/
models.rs

1//! What crosses the IPC: connect options, payloads, states, link info and channel messages.
2
3use std::collections::BTreeMap;
4use std::time::{Duration, SystemTime, UNIX_EPOCH};
5
6use serde::{Deserialize, Serialize};
7use serde_json::Value;
8use std::sync::{Arc, Mutex};
9
10use socketio_next::{
11    ClientBuilder, ConnectParams, ConnectionState, LinkInfo, Payload, TransportType,
12};
13
14use crate::error::ErrorPayload;
15
16/// Who may drive a registered client from the webview.
17#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
18#[serde(rename_all = "camelCase")]
19pub enum Access {
20    /// The webview may emit, ack and disconnect (when its capabilities allow those commands).
21    Full,
22    /// The webview may only observe (subscribe, state, link info), whatever its capabilities
23    /// say. For clients that Rust code owns.
24    ReadOnly,
25}
26
27/// `transports` of the JS options.
28#[derive(Debug, Clone, Copy, Default, Deserialize)]
29#[serde(rename_all = "kebab-case")]
30pub(crate) enum Transports {
31    /// Polling, upgraded to websocket when possible (socket.io-client's default).
32    #[default]
33    Any,
34    Polling,
35    Websocket,
36    /// Polling, then the upgrade must succeed.
37    WebsocketUpgrade,
38}
39
40/// The JS `connect` options (socket.io-client names; durations in milliseconds).
41#[derive(Default, Deserialize)]
42#[serde(rename_all = "camelCase", deny_unknown_fields)]
43pub(crate) struct ConnectOptions {
44    pub url: String,
45    pub namespace: Option<String>,
46    pub path: Option<String>,
47    #[serde(default)]
48    pub query: BTreeMap<String, String>,
49    #[serde(default)]
50    pub headers: BTreeMap<String, String>,
51    pub auth: Option<Value>,
52    #[serde(default)]
53    pub transports: Transports,
54    pub timeout: Option<u64>,
55    pub reconnection: Option<bool>,
56    pub reconnection_attempts: Option<u32>,
57    pub reconnection_delay: Option<u64>,
58    pub reconnection_delay_max: Option<u64>,
59    pub randomization_factor: Option<f64>,
60    pub reconnect_on_disconnect: Option<bool>,
61    pub buffer_while_disconnected: Option<bool>,
62    /// PEM certificates to trust instead of the default roots (a private CA).
63    pub ca: Option<String>,
64}
65
66/// Query, header and auth values are secrets as often as not: only their keys are shown.
67impl std::fmt::Debug for ConnectOptions {
68    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
69        f.debug_struct("ConnectOptions")
70            .field("namespace", &self.namespace)
71            .field("path", &self.path)
72            .field("query_keys", &self.query.keys().collect::<Vec<_>>())
73            .field("header_keys", &self.headers.keys().collect::<Vec<_>>())
74            .field("auth", &self.auth.as_ref().map(|_| "***"))
75            .field("transports", &self.transports)
76            .field("ca", &self.ca.is_some())
77            .finish_non_exhaustive()
78    }
79}
80
81/// Serde's message without the values it quotes (a token passed where a number belongs).
82pub(crate) fn invalid(err: &serde_json::Error) -> crate::Error {
83    let text = err.to_string();
84    let mut out = String::with_capacity(text.len());
85    let mut quoted = false;
86    for c in text.chars() {
87        match c {
88            '"' if !quoted => {
89                quoted = true;
90                out.push_str("\"***");
91            }
92            '"' => {
93                quoted = false;
94                out.push('"');
95            }
96            _ if quoted => {}
97            c => out.push(c),
98        }
99    }
100    crate::Error::InvalidOptions(out)
101}
102
103impl ConnectOptions {
104    /// From the webview's JSON; a bad field is [`Error::InvalidOptions`](crate::Error).
105    pub(crate) fn parse(value: Value) -> crate::Result<Self> {
106        let options: Self = serde_json::from_value(value).map_err(|e| invalid(&e))?;
107        check_headers(&options.headers)?;
108        Ok(options)
109    }
110
111    /// The builder, plus the values the webview may change later (`setAuth`, `setHeaders`,
112    /// `setQuery`): they are read again before every connect attempt.
113    pub(crate) fn into_builder(self) -> crate::Result<(ClientBuilder, Arc<Mutex<Dynamic>>)> {
114        let ms = Duration::from_millis;
115        let dynamic = Arc::new(Mutex::new(Dynamic {
116            auth: self.auth,
117            headers: self.headers,
118            query: self.query,
119        }));
120        let mut b = ClientBuilder::new(self.url).transport_type(match self.transports {
121            Transports::Any => TransportType::Any,
122            Transports::Polling => TransportType::Polling,
123            Transports::Websocket => TransportType::Websocket,
124            Transports::WebsocketUpgrade => TransportType::WebsocketUpgrade,
125        });
126        if let Some(v) = self.namespace {
127            b = b.namespace(v);
128        }
129        if let Some(v) = self.path {
130            b = b.path(v);
131        }
132        let (auth, params) = (Arc::clone(&dynamic), Arc::clone(&dynamic));
133        b = b
134            .auth_with(move || {
135                let auth = lock(&auth).auth.clone();
136                async move { auth.unwrap_or_else(|| Value::Object(Default::default())) }
137            })
138            .connect_params_with(move || {
139                let d = lock(&params);
140                let mut p = ConnectParams::new();
141                for (k, v) in &d.query {
142                    p = p.query(k, v);
143                }
144                for (k, v) in &d.headers {
145                    p = p.header(k, v);
146                }
147                async move { p }
148            });
149        if let Some(pem) = self.ca {
150            let tls = socketio_next::TlsConfig::with_root_certificates_pem(pem.as_bytes())
151                .map_err(|e| crate::Error::SocketIo(e.into()))?;
152            #[cfg(any(feature = "rustls", feature = "native-tls"))]
153            {
154                b = b.tls_config(tls);
155            }
156            #[cfg(not(any(feature = "rustls", feature = "native-tls")))]
157            let _ = tls; // unreachable: without TLS the PEM is refused above
158        }
159        if let Some(v) = self.timeout {
160            b = b.timeout(ms(v));
161        }
162        if let Some(v) = self.reconnection {
163            b = b.reconnection(v);
164        }
165        if let Some(v) = self.reconnection_attempts {
166            b = b.reconnection_attempts(v);
167        }
168        if let Some(v) = self.reconnection_delay {
169            b = b.reconnection_delay(ms(v));
170        }
171        if let Some(v) = self.reconnection_delay_max {
172            b = b.reconnection_delay_max(ms(v));
173        }
174        if let Some(v) = self.randomization_factor {
175            b = b.randomization_factor(v);
176        }
177        if let Some(v) = self.reconnect_on_disconnect {
178            b = b.reconnect_on_disconnect(v);
179        }
180        if let Some(v) = self.buffer_while_disconnected {
181            b = b.buffer_while_disconnected(v);
182        }
183        Ok((b, dynamic))
184    }
185}
186
187/// Headers a webview may not set: they belong to the HTTP / websocket machinery or to the
188/// proxy, and cookies come from the jar. Rust's own clients are not limited.
189const FORBIDDEN_HEADERS: &[&str] = &[
190    "host",
191    "connection",
192    "upgrade",
193    "content-length",
194    "transfer-encoding",
195    "cookie",
196];
197
198/// `InvalidOptions` naming the first forbidden header (never its value).
199pub(crate) fn check_headers(headers: &BTreeMap<String, String>) -> crate::Result<()> {
200    for name in headers.keys() {
201        let lower = name.to_ascii_lowercase();
202        if FORBIDDEN_HEADERS.contains(&lower.as_str())
203            || lower.starts_with("sec-websocket-")
204            || lower.starts_with("proxy-")
205        {
206            return Err(crate::Error::InvalidOptions(format!(
207                "the header `{name}` may not be set from the webview"
208            )));
209        }
210    }
211    Ok(())
212}
213
214/// Connect values a webview may replace on a client it connected; used from the next attempt.
215#[derive(Default)]
216pub(crate) struct Dynamic {
217    pub auth: Option<Value>,
218    pub headers: BTreeMap<String, String>,
219    pub query: BTreeMap<String, String>,
220}
221
222pub(crate) fn lock<T>(m: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
223    m.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
224}
225
226/// Event arguments over the IPC: JSON `args`, and the binary attachments that the
227/// `{"_placeholder":true,"num":n}` objects in `args` stand for (socket.io-parser's encoding).
228/// Bytes travel as arrays of numbers; guest-js turns them into `Uint8Array`s and back.
229#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
230pub struct Args {
231    /// The JSON arguments, placeholders included.
232    #[serde(default)]
233    pub args: Vec<Value>,
234    /// The attachments; empty when the arguments have no binary data.
235    #[serde(default, skip_serializing_if = "Vec::is_empty")]
236    pub binary: Vec<Vec<u8>>,
237}
238
239impl From<Payload> for Args {
240    fn from(payload: Payload) -> Self {
241        match payload {
242            Payload::Text(args) => Args {
243                args,
244                binary: Vec::new(),
245            },
246            Payload::Binary(bytes) => Args {
247                args: vec![Payload::placeholder(0)],
248                binary: vec![bytes.to_vec()],
249            },
250            Payload::Mixed { args, attachments } => Args {
251                args,
252                binary: attachments.into_iter().map(|b| b.to_vec()).collect(),
253            },
254            // Payload is non_exhaustive: a future shape is forwarded by its JSON part
255            other => Args {
256                args: other.args().to_vec(),
257                binary: other.binary().iter().map(|b| b.to_vec()).collect(),
258            },
259        }
260    }
261}
262
263impl From<Args> for Payload {
264    /// Without attachments placeholders are plain JSON; with them, the socket.io binary shape.
265    fn from(args: Args) -> Self {
266        if args.binary.is_empty() {
267            Payload::Text(args.args)
268        } else {
269            Payload::Mixed {
270                args: args.args,
271                attachments: args.binary.into_iter().map(Into::into).collect(),
272            }
273        }
274    }
275}
276
277/// [`ConnectionState`] for JS: `{ status, ... }` with socket.io-client's reason strings and
278/// delays in milliseconds.
279#[derive(Debug, Clone, PartialEq, Serialize)]
280#[serde(tag = "status", rename_all = "camelCase")]
281#[non_exhaustive]
282pub enum State {
283    /// A connect attempt runs (`attempt` 0 is the first connect).
284    #[non_exhaustive]
285    Connecting {
286        /// 0, then 1, 2, ... per reconnect attempt.
287        attempt: u32,
288    },
289    /// The namespace is joined.
290    #[non_exhaustive]
291    Connected {
292        /// `socket.id`.
293        sid: String,
294        /// Connection state recovery restored the session.
295        recovered: bool,
296    },
297    /// The connection was lost; a reconnect follows.
298    #[non_exhaustive]
299    Disconnected {
300        /// `"transport close"`, `"ping timeout"`, ...
301        reason: String,
302        /// The error behind it (e.g. `WebsocketClosed` with the close code).
303        #[serde(skip_serializing_if = "Option::is_none")]
304        error: Option<ErrorPayload>,
305    },
306    /// Waiting `delay` ms before reconnect attempt `attempt`.
307    #[non_exhaustive]
308    Reconnecting {
309        /// 1, 2, ...
310        attempt: u32,
311        /// Milliseconds.
312        delay: u64,
313        /// Why the previous attempt failed.
314        #[serde(skip_serializing_if = "Option::is_none")]
315        error: Option<ErrorPayload>,
316    },
317    /// Final.
318    #[non_exhaustive]
319    Closed {
320        /// `"io client disconnect"`, `"connect rejected"`, `"reconnect failed"`, ...
321        reason: String,
322        /// The error behind it.
323        #[serde(skip_serializing_if = "Option::is_none")]
324        error: Option<ErrorPayload>,
325    },
326}
327
328impl From<&ConnectionState> for State {
329    fn from(state: &ConnectionState) -> Self {
330        let err = |e: &Option<socketio_next::Error>| e.as_ref().map(ErrorPayload::from_core);
331        match state {
332            ConnectionState::Connecting { attempt, .. } => State::Connecting { attempt: *attempt },
333            ConnectionState::Connected { sid, recovered, .. } => State::Connected {
334                sid: sid.clone(),
335                recovered: *recovered,
336            },
337            ConnectionState::Disconnected { reason, error, .. } => State::Disconnected {
338                reason: reason.as_str().to_owned(),
339                error: err(error),
340            },
341            ConnectionState::Reconnecting {
342                attempt,
343                delay,
344                error,
345                ..
346            } => State::Reconnecting {
347                attempt: *attempt,
348                delay: millis(*delay),
349                error: err(error),
350            },
351            ConnectionState::Closed { reason, error, .. } => State::Closed {
352                reason: reason.as_str().to_owned(),
353                error: err(error),
354            },
355            // ConnectionState is non_exhaustive; a new state shows as a connect attempt
356            _ => State::Connecting { attempt: 0 },
357        }
358    }
359}
360
361fn millis(d: Duration) -> u64 {
362    u64::try_from(d.as_millis()).unwrap_or(u64::MAX)
363}
364
365/// [`LinkInfo`] for JS: durations in ms, instants as Unix epoch ms.
366#[derive(Debug, Clone, Serialize)]
367#[serde(rename_all = "camelCase")]
368pub struct Link {
369    /// `socket.id` while connected.
370    pub sid: Option<String>,
371    /// The engine.io session id while connected.
372    pub engine_sid: Option<String>,
373    /// `"polling"` or `"websocket"` while connected.
374    pub transport: Option<&'static str>,
375    /// pingInterval (ms) of the last handshake.
376    pub ping_interval: Option<u64>,
377    /// pingTimeout (ms) of the last handshake.
378    pub ping_timeout: Option<u64>,
379    /// maxPayload of the last handshake.
380    pub max_payload: Option<u64>,
381    /// When the current connection was established (epoch ms).
382    pub connected_at: Option<u64>,
383    /// When the last engine.io packet arrived (epoch ms).
384    pub last_packet_at: Option<u64>,
385    /// When the last ping arrived (epoch ms).
386    pub last_ping_at: Option<u64>,
387    /// When the last connect attempt started (epoch ms).
388    pub last_attempt_at: Option<u64>,
389    /// Reconnect attempts since the last connect.
390    pub reconnect_attempts: u32,
391    /// Acks waiting for the server.
392    pub pending_acks: usize,
393    /// Emits queued while disconnected.
394    pub buffered_emits: usize,
395    /// Engine.io message packets sent / received.
396    pub packets_out: u64,
397    /// See `packets_out`.
398    pub packets_in: u64,
399    /// Bytes of those packets sent / received.
400    pub bytes_out: u64,
401    /// See `bytes_out`.
402    pub bytes_in: u64,
403    /// Successful connects of this client (first one and reconnects).
404    pub sessions: u32,
405}
406
407impl From<&LinkInfo> for Link {
408    fn from(l: &LinkInfo) -> Self {
409        let now = tokio::time::Instant::now();
410        let wall = SystemTime::now();
411        let epoch = |i: Option<tokio::time::Instant>| {
412            i.and_then(|i| wall.checked_sub(now.saturating_duration_since(i)))
413                .and_then(|t| t.duration_since(UNIX_EPOCH).ok())
414                .map(millis)
415        };
416        Link {
417            sid: l.sid.clone(),
418            engine_sid: l.engine_sid.clone(),
419            transport: l.transport.map(|t| t.as_str()),
420            ping_interval: l.ping_interval.map(millis),
421            ping_timeout: l.ping_timeout.map(millis),
422            max_payload: l.max_payload,
423            connected_at: epoch(l.connected_at),
424            last_packet_at: epoch(l.last_packet_at),
425            last_ping_at: epoch(l.last_ping_at),
426            last_attempt_at: epoch(l.last_attempt_at),
427            reconnect_attempts: l.reconnect_attempts,
428            pending_acks: l.pending_acks,
429            buffered_emits: l.buffered_emits,
430            packets_out: l.packets_out,
431            packets_in: l.packets_in,
432            bytes_out: l.bytes_out,
433            bytes_in: l.bytes_in,
434            sessions: l.sessions,
435        }
436    }
437}
438
439/// One registered client, as `list()` reports it.
440#[derive(Debug, Clone, Serialize)]
441#[serde(rename_all = "camelCase")]
442pub struct ClientInfo {
443    /// The registry id.
444    pub id: String,
445    /// Who may drive it from the webview.
446    pub access: Access,
447    /// The namespace.
448    pub namespace: String,
449    /// The current state.
450    pub state: State,
451}
452
453/// What `connect` and `subscribe` resolve with in JS.
454#[derive(Debug, Clone, Serialize)]
455#[serde(rename_all = "camelCase")]
456pub(crate) struct Subscribed {
457    pub subscription: u64,
458    /// The snapshot also sent first on the channel.
459    pub state: State,
460}
461
462/// What a subscription's channel carries.
463#[derive(Debug, Clone, Serialize)]
464#[serde(tag = "type", rename_all = "camelCase")]
465#[non_exhaustive]
466pub enum Message {
467    /// A state transition (the first message is the state at subscribe time).
468    #[non_exhaustive]
469    State {
470        /// The new state.
471        state: State,
472        /// The state at subscribe time (the subscription's first state message); state
473        /// messages queued before it are older.
474        #[serde(skip_serializing_if = "std::ops::Not::not")]
475        snapshot: bool,
476    },
477    /// An event from the server.
478    #[non_exhaustive]
479    Event {
480        /// The event name.
481        event: String,
482        /// Its arguments.
483        #[serde(flatten)]
484        args: Args,
485        /// Set when the server wants an ack: answer with the `ack` command.
486        #[serde(rename = "ackId", skip_serializing_if = "Option::is_none")]
487        ack_id: Option<u64>,
488    },
489}
490
491#[cfg(test)]
492mod tests {
493    use super::*;
494    use serde_json::json;
495
496    #[test]
497    fn payload_shapes_round_trip() {
498        let text: Args = Payload::Text(vec![json!(1), json!("a")]).into();
499        assert_eq!(
500            serde_json::to_value(&text).unwrap(),
501            json!({ "args": [1, "a"] })
502        );
503        let bin: Args = Payload::Binary(vec![1u8, 2].into()).into();
504        assert_eq!(
505            serde_json::to_value(&bin).unwrap(),
506            json!({ "args": [{ "_placeholder": true, "num": 0 }], "binary": [[1, 2]] })
507        );
508        let back: Payload = bin.into();
509        assert!(
510            matches!(back, Payload::Mixed { ref attachments, .. } if attachments[0].as_ref() == [1, 2])
511        );
512        let plain: Payload =
513            serde_json::from_value::<Args>(json!({ "args": [{ "_placeholder": true, "num": 0 }] }))
514                .unwrap()
515                .into();
516        assert!(
517            matches!(plain, Payload::Text(_)),
518            "no attachments: placeholders stay JSON"
519        );
520    }
521
522    /// The JS shape of states (the conversion from socketio-next's states is exercised by
523    /// the IPC tests: reasons, delays, errors of real transitions).
524    #[test]
525    fn states_serialize_with_js_reasons() {
526        let s = State::Disconnected {
527            reason: "transport close".into(),
528            error: None,
529        };
530        assert_eq!(
531            serde_json::to_value(s).unwrap(),
532            json!({ "status": "disconnected", "reason": "transport close" })
533        );
534        let s = State::Reconnecting {
535            attempt: 2,
536            delay: 1500,
537            error: Some(ErrorPayload {
538                kind: "NotConnected",
539                message: "x".into(),
540                data: None,
541            }),
542        };
543        let v = serde_json::to_value(s).unwrap();
544        assert_eq!(v["delay"], 1500);
545        assert_eq!(v["error"]["kind"], "NotConnected");
546    }
547
548    #[test]
549    fn event_message_shape() {
550        let m = Message::Event {
551            event: "e".into(),
552            args: Args {
553                args: vec![json!(1)],
554                binary: vec![],
555            },
556            ack_id: Some(7),
557        };
558        assert_eq!(
559            serde_json::to_value(m).unwrap(),
560            json!({ "type": "event", "event": "e", "args": [1], "ackId": 7 })
561        );
562    }
563
564    #[test]
565    fn options_errors_are_typed_and_hide_values() {
566        let err =
567            ConnectOptions::parse(json!({ "url": "http://x", "timeout": "s3cr3t" })).unwrap_err();
568        let crate::Error::InvalidOptions(text) = &err else {
569            panic!("{err:?}")
570        };
571        assert!(!text.contains("s3cr3t") && text.contains("u64"), "{text}");
572        assert!(ConnectOptions::parse(json!({ "url": "http://x", "timeout": 1.5 })).is_err());
573        let opts = ConnectOptions::parse(json!({
574            "url": "http://x?token=q", "auth": { "token": "a" }, "query": { "k": "qv" }, "headers": { "h": "hv" }
575        }))
576        .unwrap();
577        let dbg = format!("{opts:?}");
578        for secret in ["token=q", "\"a\"", "qv", "hv"] {
579            assert!(!dbg.contains(secret), "{dbg}");
580        }
581    }
582
583    #[test]
584    fn webview_headers_are_limited() {
585        for name in [
586            "Host",
587            "cookie",
588            "Sec-WebSocket-Key",
589            "Proxy-Authorization",
590            "Upgrade",
591        ] {
592            let err =
593                ConnectOptions::parse(json!({ "url": "http://x", "headers": { name: "s3cr3t" } }))
594                    .err()
595                    .unwrap_or_else(|| panic!("{name} accepted"));
596            let text = err.to_string();
597            assert!(text.contains(name) && !text.contains("s3cr3t"), "{text}");
598        }
599        assert!(
600            ConnectOptions::parse(
601                json!({ "url": "http://x", "headers": { "authorization": "Bearer x" } })
602            )
603            .is_ok()
604        );
605    }
606
607    #[test]
608    fn options_reject_unknown_fields() {
609        let err = serde_json::from_value::<ConnectOptions>(
610            json!({ "url": "http://x", "reconection": true }),
611        )
612        .unwrap_err();
613        assert!(err.to_string().contains("reconection"));
614        let ok: ConnectOptions =
615            serde_json::from_value(json!({ "url": "http://x", "transports": "websocket-upgrade" }))
616                .unwrap();
617        assert!(matches!(ok.transports, Transports::WebsocketUpgrade));
618    }
619}