slabs-realtime 0.4.0

Low-level pub/sub broadcast hub for SSE and WebSockets
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
//! In-process topic broadcast hub, presence tracking, and `WebSocket` origin validation for Slabs.
//!
//! [`Realtime`] maps string topic names to [`tokio::sync::broadcast`] channels so HTTP handlers
//! and background jobs can push live updates to connected browsers, tracks Phoenix-style in-memory
//! presence via [`Realtime::track_presence`] / [`Realtime::list_presence`], and validates
//! `WebSocket` upgrade origins against Cross-Site WebSocket Hijacking (CSWSH) via
//! [`validate_ws_origin`].
//!
//! # Delivery, memory bounds, and lag semantics
//!
//! - Single-node and in-memory: messages and presence stay inside one server process and are not
//!   persisted or replicated across nodes.
//! - Zero-leak topics: publishing to a topic with zero active subscribers never allocates a topic
//!   entry and returns `0`. When the last subscriber drops, its drop guard removes the topic from
//!   memory.
//! - Bounded resources: at most [`MAX_TOPICS`] (10,000) concurrent topics and at most
//!   [`MAX_MESSAGE_DATA_BYTES`] (64 KiB) per published payload.
//! - Bounded buffer: each topic holds 256 messages per channel. When a slow receiver falls more
//!   than 256 messages behind, `tokio::sync::broadcast` skips the oldest messages and reports lag.
//! - SSE resilience: [`Realtime::sse_stream`] ignores lag errors so slow clients stay connected,
//!   sanitizes event names against CRLF/NUL injection, and sends a `"ping"` keep-alive comment
//!   every 15 seconds. Direct [`Realtime::subscribe`] callers (such as `WebSocket` loops) receive
//!   a [`Subscription`] wrapping [`tokio::sync::broadcast::Receiver`] and must handle
//!   `RecvError::Lagged` explicitly.
//!
//! # Usage
//!
//! ```rust,no_run
//! use serde::Serialize;
//! use serde_json::json;
//! use slabs_realtime::Realtime;
//!
//! #[derive(Serialize)]
//! struct Ping {
//!     room_id: &'static str,
//! }
//!
//! fn push_updates(realtime: &Realtime) {
//!     let _presence = realtime.track_presence("room:lobby", "usr_1", json!({ "name": "Alice" }));
//!     realtime.publish_html("room:lobby", "message", "<p>Hello</p>");
//!     realtime.publish_json("room:lobby", "ping", &Ping { room_id: "lobby" });
//! }
//!
//! fn sse_handler(realtime: &Realtime) -> impl axum::response::IntoResponse {
//!     realtime.sse_stream("room:lobby")
//! }
//! ```

use axum::http::{header, HeaderMap, Uri};
use axum::response::sse::{Event, KeepAlive, Sse};
use futures_util::Stream;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::collections::HashMap;
use std::convert::Infallible;
use std::ops::{Deref, DerefMut};
use std::pin::Pin;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, RwLock};
use std::task::{Context, Poll};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use tokio::sync::broadcast;
use tokio_stream::wrappers::BroadcastStream;

/// Maximum number of concurrent active topics tracked in memory.
pub const MAX_TOPICS: usize = 10_000;

/// Maximum allowed byte length of a single published message payload (64 KiB).
pub const MAX_MESSAGE_DATA_BYTES: usize = 64 * 1024;

/// Recommended maximum `WebSocket` message size in bytes (64 KiB) for `WebSocketUpgrade::max_message_size`.
pub const MAX_WS_MESSAGE_BYTES: usize = 64 * 1024;

/// Recommended maximum `WebSocket` frame size in bytes (16 KiB) for `WebSocketUpgrade::max_frame_size`.
pub const MAX_WS_FRAME_BYTES: usize = 16 * 1024;

type TopicMap = Arc<RwLock<HashMap<String, broadcast::Sender<RealtimeMessage>>>>;
type PresenceMap = Arc<RwLock<HashMap<String, HashMap<u64, PresenceEntry>>>>;

/// Message delivered over a realtime topic to SSE and `WebSocket` subscribers.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RealtimeMessage {
    /// Topic channel name the message was published on.
    pub topic: String,
    /// Named event type sent as the SSE `event:` field.
    pub event: String,
    /// Serialized message body (plain text, HTML fragment, or JSON).
    pub data: String,
}

/// Active presence entry tracked on a realtime topic.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PresenceEntry {
    /// Application-defined presence key (for example a user ID or session ID).
    pub key: String,
    /// Arbitrary JSON metadata attached to this presence entry (for example display name or status).
    pub meta: Value,
    /// UTC RFC 3339 timestamp when this presence entry joined.
    pub joined_at: String,
}

/// Drop guard that removes an empty topic channel when the last subscriber disconnects.
#[derive(Debug)]
struct TopicGuard {
    topics: TopicMap,
    topic: String,
    tracked: bool,
}

impl Drop for TopicGuard {
    fn drop(&mut self) {
        if !self.tracked {
            return;
        }
        let mut guard = self
            .topics
            .write()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        if let Some(tx) = guard.get(&self.topic) {
            if tx.receiver_count() == 0 {
                guard.remove(&self.topic);
            }
        }
    }
}

/// Subscribed broadcast receiver that automatically cleans up empty topics when dropped.
#[derive(Debug)]
pub struct Subscription {
    // Field order matters: `rx` drops before `_guard` so `receiver_count()` decrements first.
    rx: broadcast::Receiver<RealtimeMessage>,
    _guard: TopicGuard,
}

impl Subscription {
    /// Receive the next [`RealtimeMessage`] published to the subscribed topic.
    pub async fn recv(&mut self) -> Result<RealtimeMessage, broadcast::error::RecvError> {
        self.rx.recv().await
    }

    /// Attempt to receive a pending [`RealtimeMessage`] without awaiting.
    pub fn try_recv(&mut self) -> Result<RealtimeMessage, broadcast::error::TryRecvError> {
        self.rx.try_recv()
    }
}

impl Deref for Subscription {
    type Target = broadcast::Receiver<RealtimeMessage>;

    fn deref(&self) -> &Self::Target {
        &self.rx
    }
}

impl DerefMut for Subscription {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.rx
    }
}

/// Guard representing an active presence registration on a topic.
///
/// Dropping this guard removes the presence entry and broadcasts an updated `"presence"` JSON
/// event to all subscribers on the topic.
#[derive(Debug)]
pub struct PresenceGuard {
    realtime: Realtime,
    topic: String,
    key: String,
    conn_id: u64,
    tracked: bool,
}

impl Drop for PresenceGuard {
    fn drop(&mut self) {
        if !self.tracked {
            return;
        }
        let remaining = {
            let mut guard = self
                .realtime
                .presence
                .write()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            if let Some(entries) = guard.get_mut(&self.topic) {
                entries.remove(&self.conn_id);
                if entries.is_empty() {
                    guard.remove(&self.topic);
                    Vec::new()
                } else {
                    sorted_presence(entries)
                }
            } else {
                Vec::new()
            }
        };
        self.realtime.publish_json(
            &self.topic,
            "presence",
            &json!({
                "topic": self.topic,
                "action": "leave",
                "key": self.key,
                "entries": remaining,
            }),
        );
    }
}

struct SseTopicStream {
    // Field order matters: `inner` drops its broadcast receiver before `_guard` checks receiver_count.
    inner: BroadcastStream<RealtimeMessage>,
    _guard: TopicGuard,
}

impl Stream for SseTopicStream {
    type Item = Result<Event, Infallible>;

    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        loop {
            match Pin::new(&mut self.inner).poll_next(cx) {
                Poll::Ready(Some(Ok(msg))) => {
                    let event_name = sanitize_event_name(&msg.event);
                    return Poll::Ready(Some(Ok(Event::default()
                        .event(event_name)
                        .data(msg.data))));
                }
                Poll::Ready(Some(Err(_))) => {
                    // Skip lagged broadcast errors so slow SSE clients stay connected.
                }
                Poll::Ready(None) => return Poll::Ready(None),
                Poll::Pending => return Poll::Pending,
            }
        }
    }
}

/// Clonable, in-memory topic broadcast and presence hub for SSE and `WebSockets`.
///
/// Topics are created lazily on subscribe (capped at [`MAX_TOPICS`]) with a 256-message ring
/// buffer per topic and automatically removed when the last subscriber disconnects.
#[derive(Debug, Clone)]
pub struct Realtime {
    topics: TopicMap,
    presence: PresenceMap,
    next_presence_id: Arc<AtomicU64>,
}

impl Default for Realtime {
    fn default() -> Self {
        Self {
            topics: Arc::new(RwLock::new(HashMap::new())),
            presence: Arc::new(RwLock::new(HashMap::new())),
            next_presence_id: Arc::new(AtomicU64::new(1)),
        }
    }
}

impl Realtime {
    /// Create an empty in-memory broadcast and presence hub.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Return the current number of active topics with at least one subscriber.
    #[must_use]
    pub fn active_topic_count(&self) -> usize {
        self.topics
            .read()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .len()
    }

    fn subscribe_inner(&self, topic: &str) -> (broadcast::Receiver<RealtimeMessage>, TopicGuard) {
        {
            let guard = self
                .topics
                .read()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            if let Some(tx) = guard.get(topic) {
                return (
                    tx.subscribe(),
                    TopicGuard {
                        topics: Arc::clone(&self.topics),
                        topic: topic.to_string(),
                        tracked: true,
                    },
                );
            }
        }

        let mut guard = self
            .topics
            .write()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        if let Some(tx) = guard.get(topic) {
            return (
                tx.subscribe(),
                TopicGuard {
                    topics: Arc::clone(&self.topics),
                    topic: topic.to_string(),
                    tracked: true,
                },
            );
        }

        if guard.len() >= MAX_TOPICS {
            guard.retain(|_, tx| tx.receiver_count() > 0);
        }
        if guard.len() >= MAX_TOPICS {
            let (tx, rx) = broadcast::channel(1);
            drop(tx);
            return (
                rx,
                TopicGuard {
                    topics: Arc::clone(&self.topics),
                    topic: topic.to_string(),
                    tracked: false,
                },
            );
        }

        let (tx, rx) = broadcast::channel(256);
        guard.insert(topic.to_string(), tx);
        (
            rx,
            TopicGuard {
                topics: Arc::clone(&self.topics),
                topic: topic.to_string(),
                tracked: true,
            },
        )
    }

    /// Subscribe to raw broadcast messages on `topic` for custom SSE or `WebSocket` loops.
    ///
    /// Slow receivers that fall more than 256 messages behind receive `RecvError::Lagged`.
    /// Dropping the returned [`Subscription`] removes `topic` when no subscribers remain.
    pub fn subscribe(&self, topic: &str) -> Subscription {
        let (rx, guard) = self.subscribe_inner(topic);
        Subscription { rx, _guard: guard }
    }

    /// Publish a text payload to `topic` under `event` and return the active subscriber count.
    ///
    /// Returns `0` without allocating a topic entry when `topic` has no active subscribers or
    /// when `data` exceeds [`MAX_MESSAGE_DATA_BYTES`] (64 KiB). Strips `\r`, `\n`, and `\0`
    /// from `event` (falling back to `"message"`).
    pub fn publish_text(&self, topic: &str, event: &str, data: impl Into<String>) -> usize {
        let data = data.into();
        if data.len() > MAX_MESSAGE_DATA_BYTES {
            return 0;
        }
        let tx = {
            let guard = self
                .topics
                .read()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            let Some(tx) = guard.get(topic) else {
                return 0;
            };
            tx.clone()
        };
        let msg = RealtimeMessage {
            topic: topic.to_string(),
            event: sanitize_event_name(event),
            data,
        };
        tx.send(msg).unwrap_or(0)
    }

    /// Serialize `payload` as JSON and publish it to `topic` under `event`.
    ///
    /// Falls back to `"{}"` if serialization fails. Returns the active subscriber count.
    pub fn publish_json<T: Serialize>(&self, topic: &str, event: &str, payload: &T) -> usize {
        let data = serde_json::to_string(payload).unwrap_or_else(|_| "{}".into());
        self.publish_text(topic, event, data)
    }

    /// Publish an HTML fragment to `topic` under `event` for HTMX `sse-swap="<event>"` listeners.
    ///
    /// Returns the active subscriber count.
    pub fn publish_html(&self, topic: &str, event: &str, html: impl Into<String>) -> usize {
        self.publish_text(topic, event, html)
    }

    /// Track an active presence entry for `key` on `topic` and broadcast a `"presence"` update.
    ///
    /// Hold the returned [`PresenceGuard`] for the lifetime of the connection (such as an SSE or
    /// `WebSocket` task). Dropping it removes the entry and broadcasts the departure.
    pub fn track_presence(
        &self,
        topic: &str,
        key: impl Into<String>,
        meta: Value,
    ) -> PresenceGuard {
        let key = key.into();
        let conn_id = self.next_presence_id.fetch_add(1, Ordering::Relaxed);
        let entry = PresenceEntry {
            key: key.clone(),
            meta,
            joined_at: utc_now_rfc3339(),
        };

        let (tracked, entries_snapshot) = {
            let mut guard = self
                .presence
                .write()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            if !guard.contains_key(topic) && guard.len() >= MAX_TOPICS {
                guard.retain(|_, m| !m.is_empty());
            }
            if !guard.contains_key(topic) && guard.len() >= MAX_TOPICS {
                (false, Vec::new())
            } else {
                let map = guard.entry(topic.to_string()).or_default();
                map.insert(conn_id, entry);
                (true, sorted_presence(map))
            }
        };

        if tracked {
            self.publish_json(
                topic,
                "presence",
                &json!({
                    "topic": topic,
                    "action": "join",
                    "key": key,
                    "entries": entries_snapshot,
                }),
            );
        }

        PresenceGuard {
            realtime: self.clone(),
            topic: topic.to_string(),
            key,
            conn_id,
            tracked,
        }
    }

    /// List all currently active [`PresenceEntry`] values tracked on `topic`.
    #[must_use]
    pub fn list_presence(&self, topic: &str) -> Vec<PresenceEntry> {
        let guard = self
            .presence
            .read()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        guard.get(topic).map_or_else(Vec::new, sorted_presence)
    }

    /// Build an Axum SSE response subscribed to `topic` with a 15-second `"ping"` keep-alive.
    ///
    /// Lagged broadcast errors are skipped so slow clients remain connected, and the topic is
    /// cleaned up automatically when the SSE stream closes.
    pub fn sse_stream(&self, topic: &str) -> Sse<impl Stream<Item = Result<Event, Infallible>>> {
        let (rx, guard) = self.subscribe_inner(topic);
        let stream = SseTopicStream {
            inner: BroadcastStream::new(rx),
            _guard: guard,
        };
        Sse::new(stream).keep_alive(
            KeepAlive::new()
                .interval(Duration::from_secs(15))
                .text("ping"),
        )
    }
}

/// Validate `WebSocket` upgrade request headers against Cross-Site WebSocket Hijacking (CSWSH).
///
/// Rejects requests with `Sec-Fetch-Site: cross-site`. Requires a valid `Origin` header whose
/// full origin matches an entry in `allowed_origins` (case-insensitive) or whose authority
/// (`host[:port]`) matches the request `Host` header.
#[must_use]
pub fn validate_ws_origin(headers: &HeaderMap, allowed_origins: &[String]) -> bool {
    if headers
        .get("sec-fetch-site")
        .and_then(|v| v.to_str().ok())
        .is_some_and(|v| v.trim().eq_ignore_ascii_case("cross-site"))
    {
        return false;
    }

    let Some(origin_raw) = headers
        .get(header::ORIGIN)
        .and_then(|v| v.to_str().ok())
        .map(str::trim)
        .filter(|v| !v.is_empty() && !v.eq_ignore_ascii_case("null"))
    else {
        return false;
    };

    let Ok(origin_uri) = origin_raw.parse::<Uri>() else {
        return false;
    };
    let Some(scheme) = origin_uri.scheme_str() else {
        return false;
    };
    if !scheme.eq_ignore_ascii_case("http") && !scheme.eq_ignore_ascii_case("https") {
        return false;
    }
    let Some(authority) = origin_uri.authority() else {
        return false;
    };
    if authority.as_str().contains('@') {
        return false;
    }

    if allowed_origins
        .iter()
        .any(|allowed| allowed.trim().eq_ignore_ascii_case(origin_raw))
    {
        return true;
    }

    let Some(host_raw) = headers
        .get(header::HOST)
        .and_then(|v| v.to_str().ok())
        .map(str::trim)
        .filter(|v| !v.is_empty())
    else {
        return false;
    };

    authorities_match(scheme, authority.as_str(), host_raw)
}

fn authorities_match(scheme: &str, origin_authority: &str, host_header: &str) -> bool {
    if origin_authority.eq_ignore_ascii_case(host_header) {
        return true;
    }
    let default_port = if scheme.eq_ignore_ascii_case("https") {
        ":443"
    } else {
        ":80"
    };
    let norm_origin = origin_authority
        .strip_suffix(default_port)
        .unwrap_or(origin_authority);
    let norm_host = host_header
        .strip_suffix(default_port)
        .unwrap_or(host_header);
    norm_origin.eq_ignore_ascii_case(norm_host)
}

fn sanitize_event_name(event: &str) -> String {
    let clean: String = event
        .chars()
        .filter(|c| !matches!(c, '\r' | '\n' | '\0'))
        .collect();
    if clean.trim().is_empty() {
        "message".to_string()
    } else {
        clean
    }
}

fn sorted_presence(map: &HashMap<u64, PresenceEntry>) -> Vec<PresenceEntry> {
    let mut entries: Vec<PresenceEntry> = map.values().cloned().collect();
    entries.sort_by(|a, b| a.joined_at.cmp(&b.joined_at).then(a.key.cmp(&b.key)));
    entries
}

fn utc_now_rfc3339() -> String {
    let dur = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default();
    let secs = dur.as_secs();
    let days = i64::try_from(secs / 86_400).unwrap_or(0);
    let rem = secs % 86_400;
    let hour = rem / 3600;
    let min = (rem % 3600) / 60;
    let sec = rem % 60;

    // Howard Hinnant's civil_from_days algorithm (days since 1970-01-01).
    let z = days + 719_468;
    let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
    let doe = u64::try_from(z - era * 146_097).unwrap_or(0);
    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
    let y = i64::try_from(yoe).unwrap_or(0) + era * 400;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let d = doy - (153 * mp + 2) / 5 + 1;
    let m = if mp < 10 { mp + 3 } else { mp - 9 };
    let y = if m <= 2 { y + 1 } else { y };

    format!("{y:04}-{m:02}-{d:02}T{hour:02}:{min:02}:{sec:02}Z")
}

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

    #[test]
    fn publish_without_subscribers_does_not_leak_topics() {
        let rt = Realtime::new();
        for i in 0..500 {
            let count = rt.publish_text(&format!("ephemeral:{i}"), "ping", "hi");
            assert_eq!(count, 0);
        }
        assert_eq!(rt.active_topic_count(), 0);
    }

    #[tokio::test]
    async fn dropping_last_subscriber_removes_topic() {
        let rt = Realtime::new();
        {
            let mut sub1 = rt.subscribe("room:1");
            let mut sub2 = rt.subscribe("room:1");
            assert_eq!(rt.active_topic_count(), 1);
            assert_eq!(rt.publish_text("room:1", "msg", "hello"), 2);
            assert_eq!(sub1.recv().await.unwrap().data, "hello");
            assert_eq!(sub2.recv().await.unwrap().data, "hello");
            drop(sub1);
            assert_eq!(rt.active_topic_count(), 1);
        }
        assert_eq!(rt.active_topic_count(), 0);
    }

    #[tokio::test]
    async fn sanitizes_event_names_and_enforces_payload_limit() {
        let rt = Realtime::new();
        let mut sub = rt.subscribe("room:sec");

        assert_eq!(
            rt.publish_text("room:sec", "evil\r\ndata: injected\0", "ok"),
            1
        );
        let msg = sub.recv().await.unwrap();
        assert!(!msg.event.contains('\r'));
        assert!(!msg.event.contains('\n'));
        assert!(!msg.event.contains('\0'));

        assert_eq!(rt.publish_text("room:sec", "\r\n\0", "fallback"), 1);
        let msg2 = sub.recv().await.unwrap();
        assert_eq!(msg2.event, "message");

        let oversized = "a".repeat(MAX_MESSAGE_DATA_BYTES + 1);
        assert_eq!(rt.publish_text("room:sec", "big", oversized), 0);
    }

    #[tokio::test]
    async fn presence_tracks_lists_and_broadcasts_on_join_and_drop() {
        let rt = Realtime::new();
        let mut sub = rt.subscribe("room:lobby");

        {
            let _g1 = rt.track_presence("room:lobby", "usr_1", json!({ "name": "Alice" }));
            let join_msg = sub.recv().await.unwrap();
            assert_eq!(join_msg.event, "presence");
            assert!(join_msg.data.contains("\"action\":\"join\""));
            assert!(join_msg.data.contains("usr_1"));

            let list = rt.list_presence("room:lobby");
            assert_eq!(list.len(), 1);
            assert_eq!(list[0].key, "usr_1");
            assert_eq!(list[0].meta, json!({ "name": "Alice" }));
            assert!(list[0].joined_at.ends_with('Z'));
        }

        let leave_msg = sub.recv().await.unwrap();
        assert_eq!(leave_msg.event, "presence");
        assert!(leave_msg.data.contains("\"action\":\"leave\""));
        assert_eq!(rt.list_presence("room:lobby"), Vec::new());
    }

    #[test]
    fn validate_ws_origin_blocks_cswsh_and_allows_same_or_configured_origin() {
        // Same-origin passes
        let mut same = HeaderMap::new();
        same.insert(header::HOST, HeaderValue::from_static("app.example.com"));
        same.insert(
            header::ORIGIN,
            HeaderValue::from_static("https://app.example.com"),
        );
        same.insert("sec-fetch-site", HeaderValue::from_static("same-origin"));
        assert!(validate_ws_origin(&same, &[]));

        // Cross-site Sec-Fetch-Site rejected even if Origin matches Host
        let mut cross_site = same.clone();
        cross_site.insert("sec-fetch-site", HeaderValue::from_static("cross-site"));
        assert!(!validate_ws_origin(&cross_site, &[]));

        // Mismatched Origin rejected unless allowlisted
        let mut evil = HeaderMap::new();
        evil.insert(header::HOST, HeaderValue::from_static("app.example.com"));
        evil.insert(
            header::ORIGIN,
            HeaderValue::from_static("https://evil.test"),
        );
        assert!(!validate_ws_origin(&evil, &[]));
        assert!(validate_ws_origin(
            &evil,
            &["https://evil.test".to_string()]
        ));

        // Missing or null Origin rejected
        let mut missing = HeaderMap::new();
        missing.insert(header::HOST, HeaderValue::from_static("app.example.com"));
        assert!(!validate_ws_origin(&missing, &[]));
        missing.insert(header::ORIGIN, HeaderValue::from_static("null"));
        assert!(!validate_ws_origin(&missing, &[]));
    }
}