Skip to main content

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 = 8;
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// 8 — question cards: `Ask::choice` and `ClientMsg::AnswerQuestion` (the `ask_user` tool).
37
38/// Cap: the peer handles [`crate::ClientMsg::Plugin`] / [`crate::ServerMsg::Plugin`].
39pub const CAP_PLUGIN_CHANNEL: &str = "plugin_channel";
40/// Cap: the peer understands [`crate::View`]s on steps (renders known kinds, shows the
41/// fallback of the others). Part of major 13, listed so later view sites can be negotiated
42/// the same way.
43pub const CAP_VIEWS: &str = "views";
44
45/// Cap: the client decodes [`crate::PluginScope::Bundled`]. Clients without it get bundled
46/// plugins as `global` (their origin already says `bundled`).
47pub const CAP_BUNDLED_SCOPE: &str = "bundled_scope";
48
49/// Most caps one side may list.
50pub const MAX_CAPS: usize = 64;
51/// Longest cap.
52pub const MAX_CAP_CHARS: usize = 64;
53
54/// The caps this build's clients announce.
55pub fn client_caps() -> Vec<String> {
56    vec![
57        CAP_VIEWS.to_owned(),
58        CAP_PLUGIN_CHANNEL.to_owned(),
59        crate::sites::CAP_VIEW_SITES.to_owned(),
60        CAP_BUNDLED_SCOPE.to_owned(),
61        crate::web::CAP_WEB_BRIDGE.to_owned(),
62    ]
63}
64
65/// The caps this build's engine announces.
66pub fn engine_caps() -> Vec<String> {
67    vec![
68        CAP_VIEWS.to_owned(),
69        CAP_PLUGIN_CHANNEL.to_owned(),
70        crate::sites::CAP_VIEW_SITES.to_owned(),
71        CAP_BUNDLED_SCOPE.to_owned(),
72        crate::web::CAP_WEB_BRIDGE.to_owned(),
73    ]
74}
75
76/// Both sides list `cap`.
77pub fn shared(ours: &[String], theirs: &[String], cap: &str) -> bool {
78    ours.iter().any(|c| c == cap) && theirs.iter().any(|c| c == cap)
79}
80
81/// A cap is ASCII lowercase letters, digits, `_`, `.`, `-` (e.g. `plugin_channel`,
82/// `view.byob.plugin_card`).
83pub fn cap_ok(cap: &str) -> bool {
84    (1..=MAX_CAP_CHARS).contains(&cap.len()) && cap.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || matches!(b, b'_' | b'.' | b'-'))
85}
86
87/// Check a peer's caps list.
88pub fn check_caps(caps: &[String]) -> Result<(), String> {
89    if caps.len() > MAX_CAPS {
90        return Err(format!("too many caps (at most {MAX_CAPS})"));
91    }
92    match caps.iter().find(|c| !cap_ok(c)) {
93        Some(bad) => Err(format!("bad cap {:?}", bad.chars().take(MAX_CAP_CHARS).collect::<String>())),
94        None => Ok(()),
95    }
96}
97
98/// Largest plugin channel message (its JSON).
99pub const MAX_PLUGIN_MSG_BYTES: usize = 256 * 1024;
100
101/// A plugin channel message ([`crate::ClientMsg::Plugin`] / [`crate::ServerMsg::Plugin`]):
102/// plugin ids are plugin ids (`[a-z0-9-]`), the message any JSON up to
103/// [`MAX_PLUGIN_MSG_BYTES`].
104pub fn check_plugin_msg(plugin: &str, msg: &Value) -> Result<(), String> {
105    if !byob_types::config::plugin_id_ok(plugin) {
106        return Err(format!("{:?} isn't a plugin id", plugin.chars().take(60).collect::<String>()));
107    }
108    let size = serde_json::to_string(msg).map_or(usize::MAX, |s| s.len());
109    if size > MAX_PLUGIN_MSG_BYTES {
110        return Err(format!("plugin message too large ({size} bytes, at most {MAX_PLUGIN_MSG_BYTES})"));
111    }
112    Ok(())
113}
114
115/// The engine's side of the handshake ([`crate::ServerMsg::Welcome`]).
116#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
117pub struct Welcome {
118    pub protocol: u32,
119    #[serde(default)]
120    pub minor: u32,
121    #[serde(default)]
122    pub caps: Vec<String>,
123}
124
125impl Welcome {
126    /// This build's engine.
127    pub fn current() -> Self {
128        Self { protocol: PROTOCOL_MAJOR, minor: PROTOCOL_MINOR, caps: engine_caps() }
129    }
130}
131
132#[cfg(test)]
133mod tests {
134    use super::*;
135
136    #[test]
137    fn caps_are_shared_only_when_both_list_them() {
138        let a = vec!["views".to_owned(), "plugin_channel".to_owned()];
139        let b = vec!["views".to_owned(), "something_new".to_owned()];
140        assert!(shared(&a, &b, CAP_VIEWS));
141        assert!(!shared(&a, &b, CAP_PLUGIN_CHANNEL));
142        assert!(!shared(&a, &b, "something_new"));
143        assert!(check_caps(&a).is_ok() && check_caps(&client_caps()).is_ok() && check_caps(&engine_caps()).is_ok());
144        assert!(check_caps(&["Bad Cap".to_owned()]).is_err());
145        assert!(check_caps(&vec!["x".to_owned(); MAX_CAPS + 1]).is_err());
146        assert!(check_caps(&["x".repeat(MAX_CAP_CHARS + 1)]).is_err());
147    }
148
149    #[test]
150    fn plugin_messages_are_capped() {
151        assert!(check_plugin_msg("sheets", &serde_json::json!({"op": "get"})).is_ok());
152        assert!(check_plugin_msg("../x", &Value::Null).is_err());
153        assert!(check_plugin_msg("sheets", &Value::String("x".repeat(MAX_PLUGIN_MSG_BYTES))).is_err());
154    }
155}