Skip to content

Open source Grok Bot alternative, Bring your own agent and subscription: message Claude Code, Codex, Gemini CLI, Cursor, Copilot and 40+ AI agents as bots on your own computer, from iPhone, Mac, Windows, Linux or terminal. Agent-agnostic and free. Also a Muse and Dots alternative. Built in Rust.

fix(network): keep what other computers send within bounds

leepokai18205f1adad0
diff --git a/docs/features/codync-network.md b/docs/features/codync-network.md
index 0dcebc9f..7c703a8f 100644
--- a/docs/features/codync-network.md
+++ b/docs/features/codync-network.md
@@ -108,8 +108,9 @@ that was off learns of a removal.
removed with `--cascade` removes and promotes no one, whatever time it signs with: a stolen owner can't undo its
replacement with backdated entries.
- **The log stays small.** Every copy keeps only entries that can count: none by a computer the log never let in,
- no admissions, promotions or removals by plain members, each computer's newest location only, and at most 256
- entries per computer. So the whole roster always fits in the one frame (1 MiB) a hello carries it in.
+ no admissions, promotions or removals by plain members, each computer's newest location only (none for a removed
+ one), and at most 256 entries per computer, each within bounds (a name a computer could have, at most 64
+ addresses, 8 KiB in all). So the whole roster always fits in the one frame (1 MiB) a hello carries it in.
## Bots across computers
@@ -141,8 +142,9 @@ that was off learns of a removal.
reaches its request even when the asking bot was renamed or hidden meanwhile. The chain's hop limit counts
across computers (replies carry it back, one more handoff each), and the receiving computer enforces its own budgets:
8 handoffs per chain, a burst of 5 messages per pair of agents then one every 2 minutes, the same words twice in
- 10 minutes refused. A letter that isn't a request (a notice, or a reply nobody waits for after a restart) shows as
- a "Note from …" notice in the bot's chat.
+ 10 minutes refused. A letter's id is at most 64 bytes, its addresses 128, its body 64 KiB; what another computer
+ offers is kept to its first 200 agents, names cut to 80 bytes and descriptions to 1 KiB. A letter that isn't a
+ request (a notice, or a reply nobody waits for after a restart) shows as a "Note from …" notice in the bot's chat.
- Agents on this computer that aren't Codync bots (a Claude Code or Codex session) get `list_bots`, `message_bot`
and `read_replies` from `codync-host mcp network --name "Claude Code"` (stdio MCP, local API `agentCall`, loopback
only): the cloud assistant's tools (`chat/team/assistant.rs`), under the agent's own name ("Message from Claude Code
diff --git a/docs/plans/codync-network-next.md b/docs/plans/codync-network-next.md
index affab673..59e07173 100644
--- a/docs/plans/codync-network-next.md
+++ b/docs/plans/codync-network-next.md
@@ -237,3 +237,22 @@ Today the only self-hosted path is running the whole `cloud/` Worker with one's
it with `CODYNC_CLOUD_URL`. A lighter path, the host serving MCP itself behind the user's own HTTPS, needs its own
OAuth server, because ChatGPT and Claude require OAuth for remote connectors. The user is still deciding whether to
offer this. Until then, document the full-cloud path in `cloud/README.md` if anyone asks.
+
+## 11. Hardening from the 2.29.0 audit
+
+2.29.0 bounds roster entries, letters' ids and addresses, and what another computer offers. Left for later, each
+needing a design decision first:
+
+- A plain (non-cascade) removal of an admin or owner should void what that computer signs afterwards, whatever time
+ it claims: carry the removed signer's counted entries in the Remove, so no trusted clock is needed. Log format
+ change, so before 0.2.0 spreads.
+- Budgets per sending computer as well as per pair of agents (the sending agent's name is the sender's word), and a
+ cap on the pairs the guard remembers.
+- Rules naming a computer by its key, not its name, which can be taken again after a removal.
+- Letters knocked into Claude Code and Codex sessions: the body inside a random boundary, and the daemon offering
+ those sessions only to computers an allow rule names.
+- A reply matched to its waiting request only from the computer the request went to (`chat/team/remote.rs`).
+- An `asked` entry expiring, so meta-less answers stop passing the rules after a while.
+- A smaller first frame for computers that aren't members (only `Join` is theirs to send).
+- Locations accepted only with this computer's own relay URLs; custom connectors https only.
+- The daemon's control socket created inside a private folder; recovery codes read from stdin, not argv.
diff --git a/host/crates/network/src/node/directory.rs b/host/crates/network/src/node/directory.rs
index 071e40f3..7b0e3ec8 100644
--- a/host/crates/network/src/node/directory.rs
+++ b/host/crates/network/src/node/directory.rs
@@ -16,13 +16,39 @@ pub(super) struct Seen {
/// The computer name an address uses for this one before it is in a network.
const LOCAL: &str = "local";
+/// What another computer's offer may hold before the rest is left out: these show in every app
+/// and in agents' prompts.
+const MAX_AGENTS: usize = 200;
+const MAX_AGENT_NAME: usize = 80;
+const MAX_ABOUT: usize = 1024;
+
+/// Another computer's agents within bounds: the first [`MAX_AGENTS`] with an id a letter can
+/// carry, their names and descriptions cut to length.
+fn bounded(agents: Vec<Agent>) -> Vec<Agent> {
+ let cut = |text: &mut String, max: usize| {
+ if text.len() > max {
+ let end = (0..=max).rev().find(|&i| text.is_char_boundary(i)).unwrap_or(0);
+ text.truncate(end);
+ }
+ };
+ agents
+ .into_iter()
+ .filter(|a| !a.id.is_empty() && a.id.len() <= crate::wire::MAX_ID)
+ .take(MAX_AGENTS)
+ .map(|mut a| {
+ cut(&mut a.name, MAX_AGENT_NAME);
+ cut(&mut a.about, MAX_ABOUT);
+ a
+ })
+ .collect()
+}
impl Inner {
/// Notes that `id` answered with `agents`, or (`None`) that it didn't.
pub(super) fn saw(&self, id: EndpointId, agents: Option<Vec<Agent>>) {
let mut seen = locked(&self.seen);
let changed = if let Some(agents) = agents {
- let now = Seen { agents, answered: true };
+ let now = Seen { agents: bounded(agents), answered: true };
seen.insert(id, now.clone()).is_none_or(|before| before != now)
} else {
let heard = seen.entry(id).or_insert(Seen { agents: Vec::new(), answered: false });
@@ -95,3 +121,21 @@ impl Inner {
}
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::wire::AgentKind;
+
+ #[test]
+ fn another_computers_offer_is_cut_to_bounds() {
+ let agent = |id: String, name: String, about: String| Agent { id, name, about, kind: AgentKind::Codync };
+ let mut offer = vec![agent("x".repeat(65), "an id no letter carries".into(), String::new())];
+ offer.extend((0..300).map(|n| agent(format!("bot-{n}"), "é".repeat(100), "a".repeat(5000))));
+ let kept = bounded(offer);
+ assert_eq!(kept.len(), MAX_AGENTS);
+ assert_eq!(kept[0].id, "bot-0");
+ assert!(kept[0].name.len() <= MAX_AGENT_NAME && kept[0].name.chars().all(|c| c == 'é'));
+ assert_eq!(kept[0].about.len(), MAX_ABOUT);
+ }
+}
diff --git a/host/crates/network/src/node/endpoint.rs b/host/crates/network/src/node/endpoint.rs
index 93def8a5..fff4eb4a 100644
--- a/host/crates/network/src/node/endpoint.rs
+++ b/host/crates/network/src/node/endpoint.rs
@@ -24,7 +24,7 @@ impl Inner {
if roster.members().get(&self.me()).is_none_or(|m| m.addr == addr) {
return Ok(false);
}
- roster.sign(self.endpoint.secret_key(), wire::now_ms(), Change::Locate { addr })?;
+ roster.sign(self.endpoint.secret_key(), wire::now_ms(), Change::locate(addr))?;
self.save(roster)?;
Ok(true)
}
diff --git a/host/crates/network/src/node/mod.rs b/host/crates/network/src/node/mod.rs
index 42ebb8cc..0a03bdd1 100644
--- a/host/crates/network/src/node/mod.rs
+++ b/host/crates/network/src/node/mod.rs
@@ -177,7 +177,7 @@ impl Node {
}
// Where this computer is; nothing to add when it knows no address yet.
let addr = self.inner.endpoint.addr();
- let _ = roster.sign(self.inner.endpoint.secret_key(), wire::now_ms(), Change::Locate { addr });
+ let _ = roster.sign(self.inner.endpoint.secret_key(), wire::now_ms(), Change::locate(addr));
// Held across saving and keeping it, so whoever `changes` wakes sees it.
let mut guard = locked(&self.inner.roster);
self.inner.save(&roster)?;
@@ -482,7 +482,7 @@ impl Inner {
fn check_name(name: &str) -> Result<String> {
let name = name.trim();
- if name.is_empty() || name.len() > 40 || name.contains(['/', ' ', '@', '.']) {
+ if name.is_empty() || name.len() > 40 || name.contains(roster::NOT_IN_NAMES) {
bail!("a computer's name is 1–40 characters, without spaces, /, @ or .");
}
Ok(name.into())
diff --git a/host/crates/network/src/roster.rs b/host/crates/network/src/roster.rs
index 2b4fa6f6..0f9d7dc5 100644
--- a/host/crates/network/src/roster.rs
+++ b/host/crates/network/src/roster.rs
@@ -25,6 +25,14 @@ const FILE: &str = "network.json";
/// Entries one computer may have in the log: far more changes than a network of computers makes,
/// and few enough that the log stays well inside a frame.
const MAX_PER_SIGNER: usize = 256;
+/// What one entry may hold, so no member can grow the log past what a hello carries.
+const MAX_ENTRY: usize = 8 * 1024;
+/// The addresses a location keeps: the relay first, then the direct ones.
+const MAX_ADDRS: usize = 64;
+/// A computer's name (`node::check_name`'s 40) with the number `free_name` adds.
+const MAX_NAME: usize = 48;
+/// What a computer's name never holds: they'd break `[email protected]`.
+pub(crate) const NOT_IN_NAMES: [char; 4] = ['/', ' ', '@', '.'];
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
@@ -88,6 +96,13 @@ pub enum Change {
},
}
+impl Change {
+ /// Where `addr` is reachable, cut to the addresses a location may hold.
+ pub fn locate(addr: EndpointAddr) -> Self {
+ Self::Locate { addr: EndpointAddr::from_parts(addr.id, addr.addrs.into_iter().take(MAX_ADDRS)) }
+ }
+}
+
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct Signed {
/// When it was signed (Unix ms), as its signer says.
@@ -141,7 +156,7 @@ impl Roster {
let network = root.public();
let mut roster = Self { network, log: BTreeSet::new(), members: BTreeMap::new(), removed: BTreeSet::new() };
roster.log.insert(Signed::new(&network, &root, at, Change::Owner { id: me.public(), name }));
- roster.log.insert(Signed::new(&network, me, at, Change::Locate { addr }));
+ roster.log.insert(Signed::new(&network, me, at, Change::locate(addr)));
roster.rebuild();
(roster, root)
}
@@ -223,11 +238,13 @@ impl Roster {
}
}
- /// Drops what can't count, so the log stays small enough to send whole: entries by computers
- /// the log never let in, changes to who is in by computers that may not make them, all but each
- /// computer's newest location, and whatever a computer signed past its share. Returns whether
- /// anything went.
+ /// Drops what can't count, so the log stays small enough to send whole: entries out of bounds,
+ /// entries by computers the log never let in, changes to who is in by computers that may not
+ /// make them, all but each computer's newest location (and none of a removed one's), and
+ /// whatever a computer signed past its share. Returns whether anything went.
fn compact(&mut self, known: &Known) -> bool {
+ let before = self.log.len();
+ self.log.retain(bounded);
let newest = newest_locations(&self.log);
let mut share: BTreeMap<EndpointId, usize> = BTreeMap::new();
let kept: BTreeSet<Signed> = self
@@ -237,7 +254,9 @@ impl Roster {
let counts = known.signers.contains(&s.by)
&& match &s.change {
Change::Owner { .. } => s.by == self.network,
- Change::Locate { .. } => newest.get(&s.by).is_some_and(|(n, _)| *n == *s),
+ Change::Locate { .. } => {
+ !self.removed.contains(&s.by) && newest.get(&s.by).is_some_and(|(n, _)| *n == *s)
+ }
_ => known.deciders.contains(&s.by),
};
let n = share.entry(s.by).or_default();
@@ -246,7 +265,7 @@ impl Roster {
})
.cloned()
.collect();
- let changed = kept.len() != self.log.len();
+ let changed = kept.len() != before;
self.log = kept;
changed
}
@@ -401,6 +420,19 @@ struct Known {
deciders: BTreeSet<EndpointId>,
}
+/// Whether an entry is within bounds: a name a computer may have, a location's few addresses, and
+/// a few KiB in all. Anything past them can't count, whoever signed it.
+fn bounded(s: &Signed) -> bool {
+ let fits = match &s.change {
+ Change::Owner { name, .. } | Change::Admit { name, .. } => {
+ !name.is_empty() && name.len() <= MAX_NAME && !name.contains(NOT_IN_NAMES)
+ }
+ Change::Locate { addr } => addr.addrs.len() <= MAX_ADDRS,
+ Change::Promote { .. } | Change::Remove { .. } => true,
+ };
+ fits && serde_json::to_vec(s).is_ok_and(|bytes| bytes.len() <= MAX_ENTRY)
+}
+
/// Where each computer last said it is reachable: the entry and the address. Only that one counts.
fn newest_locations(log: &BTreeSet<Signed>) -> BTreeMap<EndpointId, (&Signed, &EndpointAddr)> {
let mut newest: BTreeMap<EndpointId, (&Signed, &EndpointAddr)> = BTreeMap::new();
diff --git a/host/crates/network/src/roster/tests.rs b/host/crates/network/src/roster/tests.rs
index f964ee7d..abeaec25 100644
--- a/host/crates/network/src/roster/tests.rs
+++ b/host/crates/network/src/roster/tests.rs
@@ -112,6 +112,37 @@ fn a_computer_moves_itself_only() {
assert!(r.sign(&desk, 4, Change::Locate { addr: fake }).is_err());
}
+#[test]
+fn entries_out_of_bounds_dont_count_and_a_removed_computer_has_no_location() {
+ let (desk, laptop, admin) = (key(), key(), key());
+ let (mut r, _) = Roster::create(&desk, "desk".into(), addr(&desk), 1);
+ r.sign(&desk, 2, Change::Admit { id: laptop.public(), name: "laptop".into() }).unwrap();
+ r.sign(&desk, 3, Change::Admit { id: admin.public(), name: "server".into() }).unwrap();
+ r.sign(&desk, 4, Change::Promote { id: admin.public() }).unwrap();
+ let size = serde_json::to_vec(&r).unwrap().len();
+ // Forty thousand addresses would push every hello past its frame; a name no computer may take.
+ let huge = (0..40_000u32).fold(addr(&laptop), |a, n| {
+ let [_, b, c, d] = n.to_be_bytes();
+ a.with_ip_addr(std::net::SocketAddr::from(([10, b, c, d], 1)))
+ });
+ let mut junk = r.clone();
+ junk.log.insert(Signed::new(&r.network, &laptop, 5, Change::Locate { addr: huge.clone() }));
+ let stranger = key();
+ let long = Change::Admit { id: stranger.public(), name: "x".repeat(10_000) };
+ junk.log.insert(Signed::new(&r.network, &admin, 5, long));
+ let dotted = Change::Admit { id: key().public(), name: "a.b".into() };
+ junk.log.insert(Signed::new(&r.network, &admin, 5, dotted));
+ assert!(!r.merge(&junk), "nothing out of bounds counts");
+ assert_eq!(r.members().len(), 3);
+ assert!(serde_json::to_vec(&r).unwrap().len() < size + 1024);
+ // Its own location is cut to what one may hold, and counts.
+ r.sign(&laptop, 6, Change::locate(huge)).unwrap();
+ assert_eq!(r.members()[&laptop.public()].addr.addrs.len(), MAX_ADDRS);
+ // Once laptop is removed, where it was goes too.
+ r.sign(&desk, 7, Change::Remove { id: laptop.public(), cascade: false }).unwrap();
+ assert!(!r.log.iter().any(|s| s.by == laptop.public() && matches!(s.change, Change::Locate { .. })));
+}
+
#[test]
fn a_stolen_member_cannot_grow_the_log() {
let (desk, laptop) = (key(), key());
diff --git a/host/crates/network/src/wire.rs b/host/crates/network/src/wire.rs
index cddcdff0..a177718f 100644
--- a/host/crates/network/src/wire.rs
+++ b/host/crates/network/src/wire.rs
@@ -14,6 +14,10 @@ use std::fmt::Write;
pub const ALPN: &[u8] = b"codync-network/0";
pub const MAX_BODY: usize = 64 * 1024;
const MAX_META: usize = 16 * 1024;
+/// The longest `from`, `to` and `reply_to`: an agent's address name (or `agent-<name>`), a letter id.
+const MAX_ADDRESS: usize = 128;
+/// The longest letter id (`random_hex(12)` makes 24).
+pub(crate) const MAX_ID: usize = 64;
const MAX_FRAME: usize = 1024 * 1024;
const TICKET_PREFIX: &str = "codync-network:";
@@ -193,6 +197,13 @@ pub fn check(envelope: &Envelope) -> Result<()> {
if envelope.meta.as_ref().is_some_and(|m| m.to_string().len() > MAX_META) {
bail!("a message's meta is at most {MAX_META} bytes");
}
+ let addresses = [Some(&envelope.from), Some(&envelope.to), envelope.reply_to.as_ref()];
+ if envelope.id.is_empty()
+ || envelope.id.len() > MAX_ID
+ || addresses.into_iter().flatten().any(|a| a.len() > MAX_ADDRESS)
+ {
+ bail!("a message's id is 1–{MAX_ID} bytes and its addresses at most {MAX_ADDRESS}");
+ }
Ok(())
}
@@ -200,6 +211,28 @@ pub fn check(envelope: &Envelope) -> Result<()> {
mod tests {
use super::*;
+ #[test]
+ fn a_letters_id_and_addresses_have_bounds() {
+ let letter = |id: &str, from: String| Envelope {
+ id: id.into(),
+ from,
+ to: "reviewer".into(),
+ body: "hi".into(),
+ wake: true,
+ reply_to: None,
+ hops: 0,
+ meta: None,
+ sent_at: 0,
+ };
+ assert!(check(&letter(&random_hex(12), "agent-lead".into())).is_ok());
+ assert!(check(&letter(&random_hex(12), "x".repeat(1 << 20))).is_err());
+ assert!(check(&letter(&"a".repeat(100), "lead".into())).is_err());
+ assert!(check(&letter("", "lead".into())).is_err());
+ let mut reply = letter(&random_hex(12), "lead".into());
+ reply.reply_to = Some("r".repeat(MAX_ADDRESS + 1));
+ assert!(check(&reply).is_err());
+ }
+
#[test]
fn tickets_round_trip_and_reject_garbage() {
let addr = EndpointAddr::new(iroh::SecretKey::generate().public());