Skip to main content

codync_network/
wire.rs

1//! What computers say to each other: one JSON request and one JSON answer per QUIC stream.
2
3use crate::roster::Roster;
4use anyhow::{Context, Result, anyhow, bail};
5use base64::Engine;
6use base64::engine::general_purpose::URL_SAFE_NO_PAD;
7use iroh::endpoint::Connection;
8use iroh::{EndpointAddr, EndpointId};
9use serde::de::DeserializeOwned;
10use serde::{Deserialize, Serialize};
11use serde_json::Value;
12use std::fmt::Write;
13
14pub const ALPN: &[u8] = b"codync-network/0";
15pub const MAX_BODY: usize = 64 * 1024;
16const MAX_META: usize = 16 * 1024;
17/// The longest `from`, `to` and `reply_to` in bytes: an agent's address name (40 characters of
18/// any script, a number, `agent-`), a letter id.
19pub const MAX_ADDRESS: usize = 256;
20/// The longest letter id (`random_hex(12)` makes 24).
21pub(crate) const MAX_ID: usize = 64;
22const MAX_FRAME: usize = 1024 * 1024;
23const TICKET_PREFIX: &str = "codync-network:";
24
25/// An agent a computer offers to the network.
26#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
27pub struct Agent {
28    pub id: String,
29    pub name: String,
30    /// What it is good at, so other agents pick the right one.
31    #[serde(default)]
32    pub about: String,
33    /// What it is, so others can pick one kind. Set from its [`Reach`](crate::Reach) for the
34    /// sessions the network knocks on itself.
35    #[serde(default)]
36    pub kind: AgentKind,
37}
38
39/// What kind of agent is offered: a Codync bot, a Claude Code session, a Codex thread, a person
40/// at a terminal.
41#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
42#[serde(rename_all = "kebab-case")]
43pub enum AgentKind {
44    Codync,
45    ClaudeCode,
46    Codex,
47    Terminal,
48    /// Not said (a computer from before kinds), or one this version doesn't know.
49    #[default]
50    #[serde(other)]
51    Other,
52}
53
54/// A letter on the wire. The sending computer is whoever opened the connection (iroh proves
55/// its key), so it isn't written here.
56#[derive(Clone, Debug, Serialize, Deserialize)]
57#[serde(rename_all = "camelCase")]
58pub struct Envelope {
59    pub id: String,
60    pub from: String,
61    pub to: String,
62    pub body: String,
63    #[serde(default = "yes")]
64    pub wake: bool,
65    #[serde(default)]
66    pub reply_to: Option<String>,
67    #[serde(default)]
68    pub hops: u8,
69    #[serde(default)]
70    pub meta: Option<Value>,
71    pub sent_at: u64,
72}
73
74fn yes() -> bool {
75    true
76}
77
78#[derive(Serialize, Deserialize)]
79#[serde(tag = "type", rename_all = "camelCase")]
80pub enum Request {
81    /// The only request a computer outside the network may make.
82    Join {
83        network: EndpointId,
84        secret: String,
85        name: String,
86    },
87    /// Swap copies of the roster and the agents on offer.
88    Hello {
89        roster: Roster,
90        agents: Vec<Agent>,
91    },
92    Deliver {
93        envelope: Envelope,
94    },
95}
96
97#[derive(Serialize, Deserialize)]
98#[serde(tag = "type", rename_all = "camelCase")]
99pub enum Response {
100    Welcome {
101        roster: Roster,
102    },
103    Hello {
104        roster: Roster,
105        agents: Vec<Agent>,
106    },
107    Stored,
108    Refused {
109        reason: String,
110    },
111    /// Not yet: the receiving computer hasn't offered its agents since it started. The sender
112    /// keeps the letter and tries again (an older sender, which can't read this, does the same).
113    Later {
114        reason: String,
115    },
116}
117
118/// An invite: where to find the inviting computer and the one-time secret it waits for.
119#[derive(Serialize, Deserialize)]
120pub struct Ticket {
121    pub network: EndpointId,
122    pub secret: String,
123    pub addr: EndpointAddr,
124    /// What the inviting computer calls the network, for a computer in several of them.
125    #[serde(default, skip_serializing_if = "Option::is_none")]
126    pub name: Option<String>,
127}
128
129impl Ticket {
130    pub fn encode(&self) -> Result<String> {
131        Ok(format!("{TICKET_PREFIX}{}", URL_SAFE_NO_PAD.encode(serde_json::to_vec(self)?)))
132    }
133
134    pub fn decode(text: &str) -> Result<Self> {
135        let body = text.trim().strip_prefix(TICKET_PREFIX).ok_or_else(|| anyhow!("not a codync-network invite"))?;
136        let bytes = URL_SAFE_NO_PAD.decode(body).context("the invite is cut off or mistyped")?;
137        serde_json::from_slice(&bytes).context("the invite is cut off or mistyped")
138    }
139}
140
141/// What an invite says about its network, before joining it.
142pub struct InviteInfo {
143    /// The network's id (its root key), as [`Node::network_id`](crate::Node::network_id) gives it.
144    pub network: String,
145    /// What the inviting computer calls the network, if it named it.
146    pub name: Option<String>,
147}
148
149pub fn read_invite(invite: &str) -> Result<InviteInfo> {
150    let ticket = Ticket::decode(invite)?;
151    Ok(InviteInfo { network: ticket.network.to_string(), name: ticket.name })
152}
153
154pub async fn call(conn: &Connection, request: &Request) -> Result<Response> {
155    let (mut send, mut recv) = conn.open_bi().await?;
156    send.write_all(&serde_json::to_vec(request)?).await?;
157    send.finish()?;
158    read(&mut recv).await
159}
160
161pub async fn read<T: DeserializeOwned>(recv: &mut iroh::endpoint::RecvStream) -> Result<T> {
162    let bytes = recv.read_to_end(MAX_FRAME).await?;
163    serde_json::from_slice(&bytes).context("unreadable frame")
164}
165
166pub async fn answer(send: &mut iroh::endpoint::SendStream, response: &Response) -> Result<()> {
167    send.write_all(&serde_json::to_vec(response)?).await?;
168    send.finish()?;
169    Ok(())
170}
171
172pub fn random_hex(bytes: usize) -> String {
173    let mut buf = vec![0u8; bytes];
174    getrandom::fill(&mut buf).expect("the OS random source is always there");
175    hex(&buf)
176}
177
178pub fn hex(bytes: &[u8]) -> String {
179    bytes.iter().fold(String::new(), |mut hex, b| {
180        let _ = write!(hex, "{b:02x}");
181        hex
182    })
183}
184
185pub fn unhex(text: &str) -> Option<Vec<u8>> {
186    (0..text.len()).step_by(2).map(|i| text.get(i..i + 2).and_then(|h| u8::from_str_radix(h, 16).ok())).collect()
187}
188
189pub fn now_ms() -> u64 {
190    let since = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or_default();
191    u64::try_from(since.as_millis()).unwrap_or(u64::MAX)
192}
193
194pub fn check(envelope: &Envelope) -> Result<()> {
195    if envelope.body.trim().is_empty() || envelope.body.len() > MAX_BODY {
196        bail!("a message must be nonempty and at most {MAX_BODY} bytes");
197    }
198    if envelope.meta.as_ref().is_some_and(|m| m.to_string().len() > MAX_META) {
199        bail!("a message's meta is at most {MAX_META} bytes");
200    }
201    let addresses = [Some(&envelope.from), Some(&envelope.to), envelope.reply_to.as_ref()];
202    if envelope.id.is_empty()
203        || envelope.id.len() > MAX_ID
204        || addresses.into_iter().flatten().any(|a| a.len() > MAX_ADDRESS)
205    {
206        bail!("a message's id is 1–{MAX_ID} bytes and its addresses at most {MAX_ADDRESS}");
207    }
208    Ok(())
209}
210
211#[cfg(test)]
212mod tests {
213    use super::*;
214
215    #[test]
216    fn a_letters_id_and_addresses_have_bounds() {
217        let letter = |id: &str, from: String| Envelope {
218            id: id.into(),
219            from,
220            to: "reviewer".into(),
221            body: "hi".into(),
222            wake: true,
223            reply_to: None,
224            hops: 0,
225            meta: None,
226            sent_at: 0,
227        };
228        assert!(check(&letter(&random_hex(12), "agent-lead".into())).is_ok());
229        assert!(check(&letter(&random_hex(12), "x".repeat(1 << 20))).is_err());
230        assert!(check(&letter(&random_hex(12), "審".repeat(40))).is_ok(), "any script's address names");
231        assert!(check(&letter(&"a".repeat(100), "lead".into())).is_err());
232        assert!(check(&letter("", "lead".into())).is_err());
233        let mut reply = letter(&random_hex(12), "lead".into());
234        reply.reply_to = Some("r".repeat(MAX_ADDRESS + 1));
235        assert!(check(&reply).is_err());
236    }
237
238    #[test]
239    fn tickets_round_trip_and_reject_garbage() {
240        let addr = EndpointAddr::new(iroh::SecretKey::generate().public());
241        let ticket = Ticket { network: addr.id, secret: random_hex(16), addr: addr.clone(), name: None };
242        let text = ticket.encode().unwrap();
243        let back = Ticket::decode(&format!("  {text}\n")).unwrap();
244        assert_eq!((back.network, back.secret, back.addr), (ticket.network, ticket.secret, addr));
245        assert!(Ticket::decode("hello").is_err());
246        assert!(Ticket::decode(&text[..text.len() - 4]).is_err());
247    }
248}