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