byob_protocol/version.rs
1//! Version negotiation and capabilities.
2//!
3//! A client opens with [`crate::ClientMsg::Hello`] carrying [`PROTOCOL_MAJOR`],
4//! [`PROTOCOL_MINOR`] and its [`client_caps`]; the engine answers with
5//! [`crate::ServerMsg::Welcome`] (its own version and caps) before anything else.
6//!
7//! Compatibility rules:
8//! - **Major** must match. It is bumped only for changes an older peer can't survive
9//! (a renamed or removed field, a changed meaning). A client with another major gets one
10//! error notice and nothing else.
11//! - **Minor** is informational: everything a minor adds is optional on the wire (serde
12//! defaults, skipped when empty) or behind a cap.
13//! - **Caps** are feature strings. A feature that needs both sides to understand it is used
14//! only when both list its cap ([`shared`]). Unknown caps are ignored.
15//! - Enums that grow decode unknown values into a fallback (`#[serde(other)]`), and a
16//! client skips a [`crate::ServerMsg`] it doesn't know ([`crate::ServerMsg::Unknown`]),
17//! so additions don't need a major bump.
18
19use serde::{Deserialize, Serialize};
20use serde_json::Value;
21
22/// Bumped on a change an older peer can't survive (see the module docs).
23pub const PROTOCOL_MAJOR: u32 = 13;
24/// Bumped on additive changes; peers with the same major but another minor still talk.
25pub const PROTOCOL_MINOR: u32 = 7;
26// Minors: 1 — `Artifact::content_type` (open artifact types; `kind` stays for 13.0 clients);
27// 2 — `PluginInfo::backend` (plugin backend processes); 3 — render sites: `PluginInfo::views`,
28// `View::owner`, `OpenView`/`CloseView`/`ViewEvent`, `LiveView` (cap `view_sites`); 4 — bundled
29// plugins: `PluginScope::Bundled` (cap `bundled_scope`), `PluginInfo::{locked, renderers, starters}`;
30// 5 — web surfaces: `WebCall`/`WebReply`/`WebPush`, `ViewDecl::html`, step views `byob.mcp_app`
31// and `byob.web` (cap `web_bridge`).
32// 6 — `Site::Artifact` and `view:<id>` renderers (an artifact's body is a plugin's live view),
33// the `grid` tree node and `Event::grid`.
34// 7 — `PluginInfo::superseded_by` (manifest `provides`: one of two plugins offering the same
35// thing is used) and native plugin backends (no wire change).
36
37/// Cap: the peer handles [`crate::ClientMsg::Plugin`] / [`crate::ServerMsg::Plugin`].
38pub const CAP_PLUGIN_CHANNEL: &str = "plugin_channel";
39/// Cap: the peer understands [`crate::View`]s on steps (renders known kinds, shows the
40/// fallback of the others). Part of major 13, listed so later view sites can be negotiated
41/// the same way.
42pub const CAP_VIEWS: &str = "views";
43
44/// Cap: the client decodes [`crate::PluginScope::Bundled`]. Clients without it get bundled
45/// plugins as `global` (their origin already says `bundled`).
46pub const CAP_BUNDLED_SCOPE: &str = "bundled_scope";
47
48/// Most caps one side may list.
49pub const MAX_CAPS: usize = 64;
50/// Longest cap.
51pub const MAX_CAP_CHARS: usize = 64;
52
53/// The caps this build's clients announce.
54pub fn client_caps() -> Vec<String> {
55 vec![
56 CAP_VIEWS.to_owned(),
57 CAP_PLUGIN_CHANNEL.to_owned(),
58 crate::sites::CAP_VIEW_SITES.to_owned(),
59 CAP_BUNDLED_SCOPE.to_owned(),
60 crate::web::CAP_WEB_BRIDGE.to_owned(),
61 ]
62}
63
64/// The caps this build's engine announces.
65pub fn engine_caps() -> Vec<String> {
66 vec![
67 CAP_VIEWS.to_owned(),
68 CAP_PLUGIN_CHANNEL.to_owned(),
69 crate::sites::CAP_VIEW_SITES.to_owned(),
70 CAP_BUNDLED_SCOPE.to_owned(),
71 crate::web::CAP_WEB_BRIDGE.to_owned(),
72 ]
73}
74
75/// Both sides list `cap`.
76pub fn shared(ours: &[String], theirs: &[String], cap: &str) -> bool {
77 ours.iter().any(|c| c == cap) && theirs.iter().any(|c| c == cap)
78}
79
80/// A cap is ASCII lowercase letters, digits, `_`, `.`, `-` (e.g. `plugin_channel`,
81/// `view.byob.plugin_card`).
82pub fn cap_ok(cap: &str) -> bool {
83 (1..=MAX_CAP_CHARS).contains(&cap.len()) && cap.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || matches!(b, b'_' | b'.' | b'-'))
84}
85
86/// Check a peer's caps list.
87pub fn check_caps(caps: &[String]) -> Result<(), String> {
88 if caps.len() > MAX_CAPS {
89 return Err(format!("too many caps (at most {MAX_CAPS})"));
90 }
91 match caps.iter().find(|c| !cap_ok(c)) {
92 Some(bad) => Err(format!("bad cap {:?}", bad.chars().take(MAX_CAP_CHARS).collect::<String>())),
93 None => Ok(()),
94 }
95}
96
97/// Largest plugin channel message (its JSON).
98pub const MAX_PLUGIN_MSG_BYTES: usize = 256 * 1024;
99
100/// A plugin channel message ([`crate::ClientMsg::Plugin`] / [`crate::ServerMsg::Plugin`]):
101/// plugin ids are plugin ids (`[a-z0-9-]`), the message any JSON up to
102/// [`MAX_PLUGIN_MSG_BYTES`].
103pub fn check_plugin_msg(plugin: &str, msg: &Value) -> Result<(), String> {
104 if !byob_types::config::plugin_id_ok(plugin) {
105 return Err(format!("{:?} isn't a plugin id", plugin.chars().take(60).collect::<String>()));
106 }
107 let size = serde_json::to_string(msg).map_or(usize::MAX, |s| s.len());
108 if size > MAX_PLUGIN_MSG_BYTES {
109 return Err(format!("plugin message too large ({size} bytes, at most {MAX_PLUGIN_MSG_BYTES})"));
110 }
111 Ok(())
112}
113
114/// The engine's side of the handshake ([`crate::ServerMsg::Welcome`]).
115#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
116pub struct Welcome {
117 pub protocol: u32,
118 #[serde(default)]
119 pub minor: u32,
120 #[serde(default)]
121 pub caps: Vec<String>,
122}
123
124impl Welcome {
125 /// This build's engine.
126 pub fn current() -> Self {
127 Self { protocol: PROTOCOL_MAJOR, minor: PROTOCOL_MINOR, caps: engine_caps() }
128 }
129}
130
131#[cfg(test)]
132mod tests {
133 use super::*;
134
135 #[test]
136 fn caps_are_shared_only_when_both_list_them() {
137 let a = vec!["views".to_owned(), "plugin_channel".to_owned()];
138 let b = vec!["views".to_owned(), "something_new".to_owned()];
139 assert!(shared(&a, &b, CAP_VIEWS));
140 assert!(!shared(&a, &b, CAP_PLUGIN_CHANNEL));
141 assert!(!shared(&a, &b, "something_new"));
142 assert!(check_caps(&a).is_ok() && check_caps(&client_caps()).is_ok() && check_caps(&engine_caps()).is_ok());
143 assert!(check_caps(&["Bad Cap".to_owned()]).is_err());
144 assert!(check_caps(&vec!["x".to_owned(); MAX_CAPS + 1]).is_err());
145 assert!(check_caps(&["x".repeat(MAX_CAP_CHARS + 1)]).is_err());
146 }
147
148 #[test]
149 fn plugin_messages_are_capped() {
150 assert!(check_plugin_msg("sheets", &serde_json::json!({"op": "get"})).is_ok());
151 assert!(check_plugin_msg("../x", &Value::Null).is_err());
152 assert!(check_plugin_msg("sheets", &Value::String("x".repeat(MAX_PLUGIN_MSG_BYTES))).is_err());
153 }
154}