Skip to main content

hyprstream_rpc_std/
moq_frame.rs

1//! Pure framing + reach-config parsing for the browser moq subscriber.
2//!
3//! These are the transport-independent, side-effect-free pieces of the moq
4//! worker (`moq_worker.rs`, wasm-only). They live here — NOT gated on
5//! `target_arch = "wasm32"` — so they can be unit-tested on the host. The wasm
6//! worker re-uses them; the moq subscribe/WebTransport integration itself is
7//! exercised by the downstream browser e2e.
8
9use serde::Deserialize;
10
11// DMA frame envelope: `[2: track_len LE][track][4: payload_len LE][payload]`.
12//
13// A special track name (`__cmd__`) carries JSON control messages main→worker;
14// `__ready__`/`__error__` are status frames worker→main.
15
16/// Encode one DMA frame.
17///
18/// The track-length prefix is a `u16`; a track name longer than `u16::MAX`
19/// would truncate the length header and desync [`decode_frame`] for the rest of
20/// the stream, so we drop the over-long frame (returning an empty `Vec`) rather
21/// than corrupt the channel. Track names are short by construction (moq paths).
22pub fn encode_frame(track: &str, payload: &[u8]) -> Vec<u8> {
23    let t = track.as_bytes();
24    let track_len = match u16::try_from(t.len()) {
25        Ok(len) => len,
26        Err(_) => {
27            #[cfg(target_arch = "wasm32")]
28            web_sys::console::error_1(
29                &format!(
30                    "[moq-worker] track name too long ({} bytes), dropping frame",
31                    t.len()
32                )
33                .into(),
34            );
35            return Vec::new();
36        }
37    };
38    let mut out = Vec::with_capacity(2 + t.len() + 4 + payload.len());
39    out.extend_from_slice(&track_len.to_le_bytes());
40    out.extend_from_slice(t);
41    out.extend_from_slice(&(payload.len() as u32).to_le_bytes());
42    out.extend_from_slice(payload);
43    out
44}
45
46/// Decode one DMA frame. Returns `(track_name, payload)`, or `None` if the
47/// buffer is malformed (too short, length prefix past the end, or a non-UTF-8
48/// track name).
49pub fn decode_frame(buf: &[u8]) -> Option<(&str, &[u8])> {
50    if buf.len() < 6 {
51        return None;
52    }
53    let track_len = u16::from_le_bytes([buf[0], buf[1]]) as usize;
54    if buf.len() < 2 + track_len + 4 {
55        return None;
56    }
57    let track = std::str::from_utf8(&buf[2..2 + track_len]).ok()?;
58    let payload_len = u32::from_le_bytes([
59        buf[2 + track_len],
60        buf[3 + track_len],
61        buf[4 + track_len],
62        buf[5 + track_len],
63    ]) as usize;
64    let start = 2 + track_len + 4;
65    if buf.len() < start + payload_len {
66        return None;
67    }
68    Some((track, &buf[start..start + payload_len]))
69}
70
71/// Network-routable reach the frontend selects (via `selectReach`) and passes to
72/// the worker as JSON. The moq broadcast path (which track to subscribe) is NOT
73/// here — it arrives later in a `subscribe` command, since one worker can serve
74/// several subscriptions on the same endpoint.
75///
76/// Wire shape: `{ "url": "https://<addr>/moq", "certHashes": ["<base64 SHA-256>", …] }`
77/// `certHashes` are acceptable leaf-cert SHA-256 pins for the self-signed mesh
78/// (matching the QUIC reach's `certHashes`); absent/empty ⇒ use the browser's
79/// system roots (a CA-issued cert).
80#[derive(Debug, Clone, Default, PartialEq, Eq)]
81pub struct ReachConfig {
82    pub url: String,
83    pub cert_hashes: Vec<Vec<u8>>,
84}
85
86#[derive(Deserialize)]
87struct ReachJson {
88    #[serde(default)]
89    url: String,
90    #[serde(default, rename = "certHashes")]
91    cert_hashes: Vec<String>,
92}
93
94/// Parse the reach JSON the frontend emits into a [`ReachConfig`], base64-decoding
95/// the cert hashes.
96///
97/// A cert pin is a security control: silently dropping an undecodable entry
98/// and falling back to system roots would connect unpinned without ever
99/// telling the caller. So an individual undecodable entry is an error (not
100/// skipped) whenever the list is non-empty — the only silent case is a
101/// genuinely empty `certHashes` list, which is the documented "use the
102/// browser's system roots" contract.
103pub fn parse_reach(reach_json: &str) -> Result<ReachConfig, String> {
104    let parsed: ReachJson =
105        serde_json::from_str(reach_json).map_err(|e| format!("bad reach_json: {e}"))?;
106    use base64::Engine;
107    let mut cert_hashes = Vec::with_capacity(parsed.cert_hashes.len());
108    for s in &parsed.cert_hashes {
109        let decoded = base64::engine::general_purpose::STANDARD
110            .decode(s)
111            .map_err(|e| format!("certHashes entry {s:?} is not valid base64: {e}"))?;
112        cert_hashes.push(decoded);
113    }
114    Ok(ReachConfig {
115        url: parsed.url,
116        cert_hashes,
117    })
118}
119
120#[cfg(test)]
121mod tests {
122    use super::*;
123    use base64::Engine as _;
124
125    #[test]
126    fn frame_round_trips() {
127        let f = encode_frame("stream", b"hello-tokens");
128        assert_eq!(decode_frame(&f), Some(("stream", &b"hello-tokens"[..])));
129    }
130
131    #[test]
132    fn frame_round_trips_empty_payload_and_track() {
133        let f = encode_frame("", b"");
134        assert_eq!(decode_frame(&f), Some(("", &b""[..])));
135        let f = encode_frame("__cmd__", b"");
136        assert_eq!(decode_frame(&f), Some(("__cmd__", &b""[..])));
137    }
138
139    #[test]
140    fn frame_handles_binary_payload_with_embedded_lengths() {
141        // A payload whose bytes look like length prefixes must not confuse decode.
142        let payload: Vec<u8> = (0u8..=255).cycle().take(1000).collect();
143        let f = encode_frame("local/streams/deadbeef", &payload);
144        let (track, got) = decode_frame(&f).expect("decode");
145        assert_eq!(track, "local/streams/deadbeef");
146        assert_eq!(got, &payload[..]);
147    }
148
149    #[test]
150    fn over_long_track_is_dropped_not_corrupted() {
151        let huge = "x".repeat(u16::MAX as usize + 1);
152        assert!(encode_frame(&huge, b"payload").is_empty());
153    }
154
155    #[test]
156    fn decode_rejects_malformed() {
157        assert_eq!(decode_frame(&[]), None); // empty
158        assert_eq!(decode_frame(&[0, 0, 0, 0, 0]), None); // < 6 bytes
159                                                          // track_len says 10 but buffer is too short:
160        assert_eq!(decode_frame(&[10, 0, b'a', b'b', 0, 0]), None);
161        // Valid header but truncated payload:
162        let mut f = encode_frame("stream", b"hello");
163        f.truncate(f.len() - 2);
164        assert_eq!(decode_frame(&f), None);
165        // Non-UTF-8 track bytes:
166        let bad = [2u8, 0, 0xff, 0xfe, 0, 0, 0, 0];
167        assert_eq!(decode_frame(&bad), None);
168    }
169
170    #[test]
171    fn parse_reach_url_and_cert_hashes() {
172        // base64 of the 32-byte hash [0x01; 32] = "AQEB…"; use a known small value.
173        let b64 = base64::engine::general_purpose::STANDARD.encode([0xabu8; 32]);
174        let json = format!(r#"{{"url":"https://host.tld:4433/moq","certHashes":["{b64}"]}}"#);
175        let r = parse_reach(&json).unwrap();
176        assert_eq!(r.url, "https://host.tld:4433/moq");
177        assert_eq!(r.cert_hashes, vec![vec![0xabu8; 32]]);
178    }
179
180    #[test]
181    fn parse_reach_defaults() {
182        // Missing certHashes ⇒ empty (fall back to system roots) — the only
183        // silent case; a *present but undecodable* entry is fatal (below).
184        let r = parse_reach(r#"{"url":"https://h/moq"}"#).unwrap();
185        assert_eq!(r.url, "https://h/moq");
186        assert!(r.cert_hashes.is_empty());
187        // Missing url ⇒ empty string (caller treats as unusable).
188        let r = parse_reach(r#"{}"#).unwrap();
189        assert!(r.url.is_empty());
190    }
191
192    #[test]
193    fn parse_reach_rejects_invalid_json() {
194        assert!(parse_reach("not json").is_err());
195    }
196
197    #[test]
198    fn parse_reach_rejects_undecodable_cert_hash() {
199        // A non-empty certHashes list with an undecodable entry must fail
200        // closed, not silently drop the pin and fall back to system roots.
201        let r = parse_reach(r#"{"url":"u","certHashes":["!!!not base64!!!"]}"#);
202        assert!(
203            r.is_err(),
204            "undecodable cert pin must be rejected, not skipped"
205        );
206    }
207}